{"text":"\/\/\n\/\/ Copyright (C) 2004-2006 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/\n\/\/ Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/\n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ SYSTEM INCLUDES\n#include \n\n\/\/ APPLICATION INCLUDES\n#include \"os\/OsServerTask.h\"\n#include \"os\/OsMsg.h\"\n\n\/\/ EXTERNAL FUNCTIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\nconst int OsServerTask::DEF_MAX_MSGS = OsMsgQ::DEF_MAX_MSGS;\n\n\/\/ STATIC VARIABLE INITIALIZATIONS\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ CREATORS ================================== *\/\n\n\/\/ Constructor\nOsServerTask::OsServerTask(const UtlString& name,\n void* pArg,\n const int maxRequestQMsgs,\n const int priority,\n const int options,\n const int stackSize)\n: OsTask(name, pArg, priority, options, stackSize),\n mIncomingQ(maxRequestQMsgs, OsMsgQ::DEF_MAX_MSG_LEN, OsMsgQ::Q_PRIORITY)\n\n \/\/ other than initialization, no work required\n{\n\/*\n \/\/ Only useful when debugging queue problems -- very small case and doesn't\n \/\/ warrant spam in general case -- my opinion anyways.\n\n if (OsSysLog::willLog(FAC_KERNEL, PRI_INFO))\n {\n\n OsSysLog::add(FAC_KERNEL, PRI_INFO,\n \"OsServerTask::OsServerTask %s queue: %p queue limit: %d\",\n mName.data(), &mIncomingQ, maxRequestQMsgs);\n }\n*\/\n}\n\n\/\/ Destructor\n\/\/ As part of destroying the task, flush all messages from the incoming\n\/\/ OsMsgQ.\nOsServerTask::~OsServerTask()\n{\n waitUntilShutDown(20000); \/\/ upto 20 seconds\n\n mIncomingQ.flush(); \/\/ dispose of any messages in the request queue\n}\n\n\/* ============================ MANIPULATORS ============================== *\/\n\n\/\/ Handle an incoming message.\n\/\/ This is the message handler of last resort. It should only be called when\n\/\/ the handleMessage() method in the derived class returns FALSE (indicating\n\/\/ that the message has not been handled.\nUtlBoolean OsServerTask::handleMessage(OsMsg& rMsg)\n{\n UtlBoolean handled;\n\n handled = FALSE;\n\n switch (rMsg.getMsgType())\n {\n case OsMsg::OS_SHUTDOWN:\n handled = TRUE;\n break;\n default:\n osPrintf(\n \"OsServerTask::handleMessage(): msg type is %d.%d, not OS_SHUTDOWN\\n\",\n rMsg.getMsgType(), rMsg.getMsgSubType());\n \/\/ assert(FALSE);\n break;\n }\n\n return handled;\n}\n\n\/\/ Post a message to this task.\n\/\/ Return the result of the message send operation.\nOsStatus OsServerTask::postMessage(const OsMsg& rMsg, const OsTime& rTimeout,\n UtlBoolean sentFromISR)\n{\n OsStatus res;\n\n if (sentFromISR)\n res = mIncomingQ.sendFromISR(rMsg);\n else\n res = mIncomingQ.send(rMsg, rTimeout);\n return res;\n}\n\n\/\/ Call OsTask::requestShutdown() and then post an OS_SHUTDOWN message\n\/\/ to the incoming message queue to unblock the task.\nvoid OsServerTask::requestShutdown(void)\n{\n OsMsg msg(OsMsg::OS_SHUTDOWN, 0);\n\n OsTask::requestShutdown();\n postMessage(msg);\n}\n\n\/* ============================ ACCESSORS ================================= *\/\n\n\/\/ Get the pointer to the incoming message queue\nOsMsgQ* OsServerTask::getMessageQueue()\n{\n return(&mIncomingQ);\n}\n\n\/* ============================ INQUIRY =================================== *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PROTECTED \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/\/ Waits for a message to arrive on the task's incoming message queue.\nOsStatus OsServerTask::receiveMessage(OsMsg*& rpMsg)\n{\n return mIncomingQ.receive(rpMsg);\n}\n\n\/\/ Waits for a message to arrive on the task's incoming message queue.\nOsStatus OsServerTask::receiveMessage(OsMsg*& rpMsg,\n const OsTime& rTimeout)\n{\n return mIncomingQ.receive(rpMsg, rTimeout);\n}\n\n\/\/ The entry point for the task.\n\/\/ This method executes a message processing loop until either\n\/\/ requestShutdown(), deleteForce(), or the destructor for this object\n\/\/ is called.\nint OsServerTask::run(void* pArg)\n{\n UtlBoolean doShutdown;\n OsMsg* pMsg = NULL;\n OsStatus res;\n\n do\n {\n res = receiveMessage((OsMsg*&) pMsg); \/\/ wait for a message\n assert(res == OS_SUCCESS);\n\n doShutdown = isShuttingDown();\n if (!doShutdown)\n { \/\/ comply with shutdown\n if (!handleMessage(*pMsg)) \/\/ process the message\n OsServerTask::handleMessage(*pMsg);\n }\n\n if (!pMsg->getSentFromISR())\n pMsg->releaseMsg(); \/\/ free the message\n }\n while (!doShutdown);\n\n ackShutdown(); \/\/ acknowledge the task shutdown request\n return 0; \/\/ and then exit\n}\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PRIVATE \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ FUNCTIONS ================================= *\/\nAdd assert to postMessage() call in OsServerTask::requestShutdown().\/\/\n\/\/ Copyright (C) 2004-2006 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/\n\/\/ Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/\n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ SYSTEM INCLUDES\n#include \n\n\/\/ APPLICATION INCLUDES\n#include \"os\/OsServerTask.h\"\n#include \"os\/OsMsg.h\"\n\n\/\/ EXTERNAL FUNCTIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\nconst int OsServerTask::DEF_MAX_MSGS = OsMsgQ::DEF_MAX_MSGS;\n\n\/\/ STATIC VARIABLE INITIALIZATIONS\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ CREATORS ================================== *\/\n\n\/\/ Constructor\nOsServerTask::OsServerTask(const UtlString& name,\n void* pArg,\n const int maxRequestQMsgs,\n const int priority,\n const int options,\n const int stackSize)\n: OsTask(name, pArg, priority, options, stackSize),\n mIncomingQ(maxRequestQMsgs, OsMsgQ::DEF_MAX_MSG_LEN, OsMsgQ::Q_PRIORITY)\n\n \/\/ other than initialization, no work required\n{\n\/*\n \/\/ Only useful when debugging queue problems -- very small case and doesn't\n \/\/ warrant spam in general case -- my opinion anyways.\n\n if (OsSysLog::willLog(FAC_KERNEL, PRI_INFO))\n {\n\n OsSysLog::add(FAC_KERNEL, PRI_INFO,\n \"OsServerTask::OsServerTask %s queue: %p queue limit: %d\",\n mName.data(), &mIncomingQ, maxRequestQMsgs);\n }\n*\/\n}\n\n\/\/ Destructor\n\/\/ As part of destroying the task, flush all messages from the incoming\n\/\/ OsMsgQ.\nOsServerTask::~OsServerTask()\n{\n waitUntilShutDown(20000); \/\/ upto 20 seconds\n\n mIncomingQ.flush(); \/\/ dispose of any messages in the request queue\n}\n\n\/* ============================ MANIPULATORS ============================== *\/\n\n\/\/ Handle an incoming message.\n\/\/ This is the message handler of last resort. It should only be called when\n\/\/ the handleMessage() method in the derived class returns FALSE (indicating\n\/\/ that the message has not been handled.\nUtlBoolean OsServerTask::handleMessage(OsMsg& rMsg)\n{\n UtlBoolean handled;\n\n handled = FALSE;\n\n switch (rMsg.getMsgType())\n {\n case OsMsg::OS_SHUTDOWN:\n handled = TRUE;\n break;\n default:\n osPrintf(\n \"OsServerTask::handleMessage(): msg type is %d.%d, not OS_SHUTDOWN\\n\",\n rMsg.getMsgType(), rMsg.getMsgSubType());\n \/\/ assert(FALSE);\n break;\n }\n\n return handled;\n}\n\n\/\/ Post a message to this task.\n\/\/ Return the result of the message send operation.\nOsStatus OsServerTask::postMessage(const OsMsg& rMsg, const OsTime& rTimeout,\n UtlBoolean sentFromISR)\n{\n OsStatus res;\n\n if (sentFromISR)\n res = mIncomingQ.sendFromISR(rMsg);\n else\n res = mIncomingQ.send(rMsg, rTimeout);\n return res;\n}\n\n\/\/ Call OsTask::requestShutdown() and then post an OS_SHUTDOWN message\n\/\/ to the incoming message queue to unblock the task.\nvoid OsServerTask::requestShutdown(void)\n{\n OsStatus res;\n\n OsMsg msg(OsMsg::OS_SHUTDOWN, 0);\n\n OsTask::requestShutdown();\n res = postMessage(msg);\n assert(res = OS_SUCCESS);\n}\n\n\/* ============================ ACCESSORS ================================= *\/\n\n\/\/ Get the pointer to the incoming message queue\nOsMsgQ* OsServerTask::getMessageQueue()\n{\n return(&mIncomingQ);\n}\n\n\/* ============================ INQUIRY =================================== *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PROTECTED \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/\/ Waits for a message to arrive on the task's incoming message queue.\nOsStatus OsServerTask::receiveMessage(OsMsg*& rpMsg)\n{\n return mIncomingQ.receive(rpMsg);\n}\n\n\/\/ Waits for a message to arrive on the task's incoming message queue.\nOsStatus OsServerTask::receiveMessage(OsMsg*& rpMsg,\n const OsTime& rTimeout)\n{\n return mIncomingQ.receive(rpMsg, rTimeout);\n}\n\n\/\/ The entry point for the task.\n\/\/ This method executes a message processing loop until either\n\/\/ requestShutdown(), deleteForce(), or the destructor for this object\n\/\/ is called.\nint OsServerTask::run(void* pArg)\n{\n UtlBoolean doShutdown;\n OsMsg* pMsg = NULL;\n OsStatus res;\n\n do\n {\n res = receiveMessage((OsMsg*&) pMsg); \/\/ wait for a message\n assert(res == OS_SUCCESS);\n\n doShutdown = isShuttingDown();\n if (!doShutdown)\n { \/\/ comply with shutdown\n if (!handleMessage(*pMsg)) \/\/ process the message\n OsServerTask::handleMessage(*pMsg);\n }\n\n if (!pMsg->getSentFromISR())\n pMsg->releaseMsg(); \/\/ free the message\n }\n while (!doShutdown);\n\n ackShutdown(); \/\/ acknowledge the task shutdown request\n return 0; \/\/ and then exit\n}\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PRIVATE \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ FUNCTIONS ================================= *\/\n<|endoftext|>"} {"text":"\/* Begin CVS Header\n $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/report\/CCopasiObject.cpp,v $\n $Revision: 1.28 $\n $Name: $\n $Author: gasingh $ \n $Date: 2004\/02\/26 00:37:53 $\n End CVS Header *\/\n\n\/**\n * Class CCopasiObject\n *\n * This class is the base class for all global accessible objects in copasi.\n *\n * Copyright Stefan Hoops 2002\n *\/\n\n#include \n\n#include \"copasi.h\"\n#include \"CCopasiObjectName.h\"\n#include \"CCopasiObject.h\"\n#include \"CCopasiContainer.h\"\n\nconst C_FLOAT64 CCopasiObject::DummyValue = 0.0;\n\nCCopasiObject::CCopasiObject():\n mObjectName(),\n mObjectType(),\n mpObjectParent(NULL),\n mObjectFlag(0)\n{}\n\nCCopasiObject::CCopasiObject(const std::string & name,\n const CCopasiContainer * pParent,\n const std::string & type,\n const unsigned C_INT32 & flag):\n mObjectName(name),\n mObjectType(type),\n mpObjectParent(const_cast(pParent)),\n mObjectFlag(flag)\n{\n if (mpObjectParent)\n if (mpObjectParent->isContainer()) mpObjectParent->add(this);\n}\n\nCCopasiObject::CCopasiObject(const CCopasiObject & src,\n const CCopasiContainer * pParent):\n mObjectName(src.mObjectName),\n mObjectType(src.mObjectType),\n mpObjectParent(const_cast(pParent)),\n mObjectFlag(src.mObjectFlag)\n{if (mpObjectParent) mpObjectParent->add(this);}\n\nCCopasiObject::~CCopasiObject()\n{\n if (mpObjectParent)\n mpObjectParent->remove(this);\n}\n\nvoid CCopasiObject::print(std::ostream * ostream) const {(*ostream) << (*this);}\n\nCCopasiObjectName CCopasiObject::getCN() const\n {\n CCopasiObjectName CN;\n\n if (mpObjectParent)\n {\n std::stringstream tmp;\n tmp << mpObjectParent->getCN();\n\n if (mpObjectParent->isNameVector())\n tmp << \"[\" << CCopasiObjectName::escape(mObjectName) << \"]\";\n else if (mpObjectParent->isVector())\n tmp << \"[\" << mpObjectParent->getIndex(this) << \"]\";\n else\n tmp << \",\" << CCopasiObjectName::escape(mObjectType)\n << \"=\" << CCopasiObjectName::escape(mObjectName);\n\n CN = tmp.str();\n }\n else\n {\n CN = CCopasiObjectName::escape(mObjectType)\n + \"=\" + CCopasiObjectName::escape(mObjectName);\n }\n\n return CN;\n }\n\nconst CCopasiObject *\nCCopasiObject::getObject(const CCopasiObjectName & C_UNUSED(cn)) const\n {return NULL;}\n\nconst std::string & CCopasiObject::getName() const {return mObjectName;}\n\nconst std::string\nCCopasiObject::getObjectUniqueNameEx(const bool & isParent) const\n {\n if (isParent && isVector())\n return mpObjectParent->getObjectUniqueNameEx();\n\n if (mpObjectParent && 0 < (mObjectFlag & NonUniqueName))\n return mObjectName + \"{\" + mpObjectParent->getObjectUniqueNameEx() + \"}\";\n\n return mObjectName;\n }\n\nconst std::string CCopasiObject::getObjectUniqueName() const\n{return getObjectUniqueNameEx(false);}\n\nbool CCopasiObject::setObjectName(const std::string & name)\n{\n if (name == mObjectName) return true;\n\n if (mpObjectParent && mpObjectParent->isNameVector())\n {\n CCopasiObjectName NewObject = getObjectType() + \"=\" + name;\n\n if (mpObjectParent->getObject(NewObject))\n return false;\n }\n\n mObjectName = name;\n\n return true;\n}\n\nconst std::string & CCopasiObject::getObjectName() const {return mObjectName;}\n\nconst std::string & CCopasiObject::getObjectType() const {return mObjectType;}\n\nbool CCopasiObject::setObjectParent(const CCopasiContainer * pParent)\n{\n mpObjectParent = const_cast(pParent);\n\n return true;\n}\n\nCCopasiContainer * CCopasiObject::getObjectParent() const {return mpObjectParent;}\n\nCCopasiContainer *\nCCopasiObject::getObjectAncestor(const std::string & type) const\n {\n CCopasiContainer * p = getObjectParent();\n\n while (p)\n {\n if (p->getObjectType() == type) return p;\n p = p->getObjectParent();\n }\n\n return NULL;\n }\n\nunsigned C_INT32\nCCopasiObject::getIndex(const CCopasiObject * C_UNUSED(pObject)) const\n{return C_INVALID_INDEX;}\n\nunsigned C_INT32\nCCopasiObject::getIndex(const std::string & C_UNUSED(name)) const\n {return C_INVALID_INDEX;}\n\nvoid * CCopasiObject::getReference() const\n {return const_cast(this);}\n\nbool CCopasiObject::isContainer() const\n {return (0 < (mObjectFlag & Container));}\n\nbool CCopasiObject::isVector() const\n {return (0 < (mObjectFlag & Vector));}\n\nbool CCopasiObject::isMatrix() const\n {return (0 < (mObjectFlag & Matrix));}\n\nbool CCopasiObject::isNameVector() const\n {return (0 < (mObjectFlag & NameVector));}\n\nbool CCopasiObject::isReference() const\n {return (0 < (mObjectFlag & Reference));}\n\nbool CCopasiObject::isValueBool() const\n {return (0 < (mObjectFlag & ValueBool));}\n\nbool CCopasiObject::isValueInt() const\n {return (0 < (mObjectFlag & ValueInt));}\n\nbool CCopasiObject::isValueDbl() const\n {return (0 < (mObjectFlag & ValueDbl));}\n\nbool CCopasiObject::isStaticString() const\n {return (0 < (mObjectFlag & StaticString));}\n\nstd::ostream &operator<<(std::ostream &os, const CCopasiObject & o)\n{\n os << \"Name: \" << o.getObjectName() << std::endl;\n os << \"Type: \" << o.getObjectType() << std::endl;\n os << \"Container: \" << o.isContainer() << std::endl;\n os << \"Vector: \" << o.isVector() << std::endl;\n os << \"VectorN: \" << o.isNameVector() << std::endl;\n os << \"Matrix: \" << o.isMatrix() << std::endl;\n os << \"Reference: \" << o.isReference() << std::endl;\n os << \"Bool: \" << o.isValueBool() << std::endl;\n os << \"Int: \" << o.isValueInt() << std::endl;\n os << \"Dbl: \" << o.isValueDbl() << std::endl;\n\n return os;\n}\nFixed setObjectName() to update the parent if needed.\/* Begin CVS Header\n $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/report\/CCopasiObject.cpp,v $\n $Revision: 1.29 $\n $Name: $\n $Author: shoops $ \n $Date: 2004\/05\/07 18:34:26 $\n End CVS Header *\/\n\n\/**\n * Class CCopasiObject\n *\n * This class is the base class for all global accessible objects in copasi.\n *\n * Copyright Stefan Hoops 2002\n *\/\n\n#include \n\n#include \"copasi.h\"\n#include \"CCopasiObjectName.h\"\n#include \"CCopasiObject.h\"\n#include \"CCopasiContainer.h\"\n\nconst C_FLOAT64 CCopasiObject::DummyValue = 0.0;\n\nCCopasiObject::CCopasiObject():\n mObjectName(),\n mObjectType(),\n mpObjectParent(NULL),\n mObjectFlag(0)\n{}\n\nCCopasiObject::CCopasiObject(const std::string & name,\n const CCopasiContainer * pParent,\n const std::string & type,\n const unsigned C_INT32 & flag):\n mObjectName(name),\n mObjectType(type),\n mpObjectParent(const_cast(pParent)),\n mObjectFlag(flag)\n{\n if (mpObjectParent)\n if (mpObjectParent->isContainer()) mpObjectParent->add(this);\n}\n\nCCopasiObject::CCopasiObject(const CCopasiObject & src,\n const CCopasiContainer * pParent):\n mObjectName(src.mObjectName),\n mObjectType(src.mObjectType),\n mpObjectParent(const_cast(pParent)),\n mObjectFlag(src.mObjectFlag)\n{if (mpObjectParent) mpObjectParent->add(this);}\n\nCCopasiObject::~CCopasiObject()\n{\n if (mpObjectParent)\n mpObjectParent->remove(this);\n}\n\nvoid CCopasiObject::print(std::ostream * ostream) const {(*ostream) << (*this);}\n\nCCopasiObjectName CCopasiObject::getCN() const\n {\n CCopasiObjectName CN;\n\n if (mpObjectParent)\n {\n std::stringstream tmp;\n tmp << mpObjectParent->getCN();\n\n if (mpObjectParent->isNameVector())\n tmp << \"[\" << CCopasiObjectName::escape(mObjectName) << \"]\";\n else if (mpObjectParent->isVector())\n tmp << \"[\" << mpObjectParent->getIndex(this) << \"]\";\n else\n tmp << \",\" << CCopasiObjectName::escape(mObjectType)\n << \"=\" << CCopasiObjectName::escape(mObjectName);\n\n CN = tmp.str();\n }\n else\n {\n CN = CCopasiObjectName::escape(mObjectType)\n + \"=\" + CCopasiObjectName::escape(mObjectName);\n }\n\n return CN;\n }\n\nconst CCopasiObject *\nCCopasiObject::getObject(const CCopasiObjectName & C_UNUSED(cn)) const\n {return NULL;}\n\nconst std::string & CCopasiObject::getName() const {return mObjectName;}\n\nconst std::string\nCCopasiObject::getObjectUniqueNameEx(const bool & isParent) const\n {\n if (isParent && isVector())\n return mpObjectParent->getObjectUniqueNameEx();\n\n if (mpObjectParent && 0 < (mObjectFlag & NonUniqueName))\n return mObjectName + \"{\" + mpObjectParent->getObjectUniqueNameEx() + \"}\";\n\n return mObjectName;\n }\n\nconst std::string CCopasiObject::getObjectUniqueName() const\n{return getObjectUniqueNameEx(false);}\n\nbool CCopasiObject::setObjectName(const std::string & name)\n{\n if (name == mObjectName) return true;\n\n if (mpObjectParent && mpObjectParent->isNameVector())\n {\n CCopasiObjectName NewObject = getObjectType() + \"=\" + name;\n\n if (mpObjectParent->getObject(NewObject))\n return false;\n }\n\n mObjectName = name;\n\n if (mpObjectParent)\n {\n mpObjectParent->remove(this);\n mpObjectParent->add(this, false);\n }\n\n return true;\n}\n\nconst std::string & CCopasiObject::getObjectName() const {return mObjectName;}\n\nconst std::string & CCopasiObject::getObjectType() const {return mObjectType;}\n\nbool CCopasiObject::setObjectParent(const CCopasiContainer * pParent)\n{\n mpObjectParent = const_cast(pParent);\n\n return true;\n}\n\nCCopasiContainer * CCopasiObject::getObjectParent() const {return mpObjectParent;}\n\nCCopasiContainer *\nCCopasiObject::getObjectAncestor(const std::string & type) const\n {\n CCopasiContainer * p = getObjectParent();\n\n while (p)\n {\n if (p->getObjectType() == type) return p;\n p = p->getObjectParent();\n }\n\n return NULL;\n }\n\nunsigned C_INT32\nCCopasiObject::getIndex(const CCopasiObject * C_UNUSED(pObject)) const\n{return C_INVALID_INDEX;}\n\nunsigned C_INT32\nCCopasiObject::getIndex(const std::string & C_UNUSED(name)) const\n {return C_INVALID_INDEX;}\n\nvoid * CCopasiObject::getReference() const\n {return const_cast(this);}\n\nbool CCopasiObject::isContainer() const\n {return (0 < (mObjectFlag & Container));}\n\nbool CCopasiObject::isVector() const\n {return (0 < (mObjectFlag & Vector));}\n\nbool CCopasiObject::isMatrix() const\n {return (0 < (mObjectFlag & Matrix));}\n\nbool CCopasiObject::isNameVector() const\n {return (0 < (mObjectFlag & NameVector));}\n\nbool CCopasiObject::isReference() const\n {return (0 < (mObjectFlag & Reference));}\n\nbool CCopasiObject::isValueBool() const\n {return (0 < (mObjectFlag & ValueBool));}\n\nbool CCopasiObject::isValueInt() const\n {return (0 < (mObjectFlag & ValueInt));}\n\nbool CCopasiObject::isValueDbl() const\n {return (0 < (mObjectFlag & ValueDbl));}\n\nbool CCopasiObject::isStaticString() const\n {return (0 < (mObjectFlag & StaticString));}\n\nstd::ostream &operator<<(std::ostream &os, const CCopasiObject & o)\n{\n os << \"Name: \" << o.getObjectName() << std::endl;\n os << \"Type: \" << o.getObjectType() << std::endl;\n os << \"Container: \" << o.isContainer() << std::endl;\n os << \"Vector: \" << o.isVector() << std::endl;\n os << \"VectorN: \" << o.isNameVector() << std::endl;\n os << \"Matrix: \" << o.isMatrix() << std::endl;\n os << \"Reference: \" << o.isReference() << std::endl;\n os << \"Bool: \" << o.isValueBool() << std::endl;\n os << \"Int: \" << o.isValueInt() << std::endl;\n os << \"Dbl: \" << o.isValueDbl() << std::endl;\n\n return os;\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n#include \"AliCheb2DStackF.h\"\n#include \"AliCheb2DStackS.h\"\n#include \"AliTPCChebCorr.h\"\n#include \"AliLog.h\"\n#include \n\nClassImp(AliTPCChebCorr)\n\n\nconst float AliTPCChebCorr::fgkAngGap = 5e-4; \/\/ allow some empty ang. space between sectors\nconst float AliTPCChebCorr::fgkY2XHSpan = TMath::Tan(TMath::Pi()\/AliTPCChebCorr::kNSectors - AliTPCChebCorr::fgkAngGap);\n\n\/\/____________________________________________________________________\nAliTPCChebCorr::AliTPCChebCorr()\n : TNamed()\n ,fNStacksSect(0)\n ,fNStacksZSect(0)\n ,fNStacksZ(0)\n ,fNStacks(0)\n ,fZMaxAbs(-1)\n ,fTimeStampStart(0)\n ,fTimeStampEnd(0xffffffff)\n ,fZScaleI(0)\n ,fY2XScaleI(0)\n ,fParams(0)\n{\n\/\/ def. c-tor \n}\n\n\/\/____________________________________________________________________\nAliTPCChebCorr::AliTPCChebCorr(const char* name, const char* title, \n\t\t\t int nps, int nzs, float zmaxAbs)\n : TNamed(name,title)\n ,fNStacksSect(0)\n ,fNStacksZSect(0)\n ,fNStacksZ(0)\n ,fNStacks(0)\n ,fZMaxAbs(-1)\n ,fTimeStampStart(0)\n ,fTimeStampEnd(0xffffffff)\n ,fZScaleI(0)\n ,fY2XScaleI(0)\n ,fParams(0)\n{\n \/\/ c-tor\n SetBinning(nps,nzs,zmaxAbs);\n \/\/\n}\n\n\/\/____________________________________________________________________\nAliTPCChebCorr::~AliTPCChebCorr()\n{\n \/\/ d-tor\n if (fParams) for (int i=fNStacks;i--;) delete fParams[i];\n delete[] fParams;\n}\n\n\/\/____________________________________________________________________\nvoid AliTPCChebCorr::Parameterize(stFun_t fun,int dimOut,const int np[2],const float* prec)\n{\n \/\/ build parameterizations for 2->dimout, on the same grid of np[0]xnp[1] points for\n \/\/ every output dimension, optionally with prec[i] precision for i-th dimension\n \/\/\n if (TestBit(kParamDone)) {\n AliError(\"Parameterization is already done\");\n return;\n }\n \/\/\n if (fZMaxAbs<0) AliFatal(\"First the binning and Z limits should be set\");\n \/\/\n float bmn[2],bmx[2];\n Bool_t useS = GetUseShortPrec(); \/\/ float or short representation for param\n fParams = new AliCheb2DStack*[fNStacks];\n \/\/\n for (int iz=0;izdimout, on the same grid of np[0]xnp[1] points for\n \/\/ every output dimension, optionally with prec[i] precision for i-th dimension\n \/\/\n if (TestBit(kParamDone)) {\n AliError(\"Parameterization is already done\");\n return;\n }\n \/\/\n float bmn[2],bmx[2];\n float y2xMax = TMath::Tan(TMath::Pi()\/kNSectors); \/\/ half-sector span\n \/\/\n fParams = new AliCheb2DStack*[fNStacks];\n Bool_t useS = GetUseShortPrec(); \/\/ float or short representation for param\n \/\/\n for (int iz=0;iz=fNStacksZSect) iz = fNStacksZSect-1;} \/\/ C side\n else {if (iz=fNStacksZ) iz=fNStacksZ-1;\n int is = (y2x+fgkY2XHSpan)*fY2XScaleI;\n if (is<0) is=0; else if (is>=fNStacksSect) is=fNStacksSect-1;\n float tz[2] = {y2x,z}; \/\/ params use row, Y\/X, Z\n GetParam(GetParID(iz,sector,is))->Eval(row,tz,corr);\n \/\/\n}\n\n\/\/____________________________________________________________________\nvoid AliTPCChebCorr::Eval(int sector, int row, float tz[2], float *corr) const\n{\n \/\/ Calculate correction for point with x,y,z sector corrdinates\n \/\/ If sector in 0-71 ROC convention, possible Z-outlying is checked\n int iz = (tz[1]+fZMaxAbs)*fZScaleI, side = sector\/18;\n sector %= 18;\n \/\/ correct for eventual Z calculated in wrong ROC\n if (side) {if (iz>=fNStacksZSect) iz = fNStacksZSect-1;} \/\/ C side\n else {if (iz=fNStacksZ) iz=fNStacksZ-1;\n int is = (tz[0]+fgkY2XHSpan)*fY2XScaleI;\n if (is<0) is=0; else if (is>=fNStacksSect) is=fNStacksSect-1;\n GetParam(GetParID(iz,sector,is))->Eval(row,tz,corr);\n \/\/\n}\n\n\/\/____________________________________________________________________\nvoid AliTPCChebCorr::Print(const Option_t* opt) const\n{\n \/\/ print itself\n printf(\"%s:%s Cheb2D[%c] Param: %d slices in %+.1f<%s<%+.1f %d per sector\\n\",\n\t GetName(),GetTitle(),GetUseFloatPrec()?'F':'S',\n\t fNStacksZ,-fZMaxAbs,GetUseZ2R() ? \"Z\/R\":\"Z\",fZMaxAbs,fNStacksSect);\n printf(\"Time span: %10d:%10d TimeDependent flag: %s\\n\",fTimeStampStart,fTimeStampEnd,\n\t GetTimeDependent() ? \"ON\":\"OFF\");\n TString opts = opt; opts.ToLower();\n if (opts.Contains(\"p\") && TestBit(kParamDone)) {\n for (int iz=0;izPrint(opt);\n\t}\n }\n }\n }\n}\n\n\/\/____________________________________________________________________\nvoid AliTPCChebCorr::SetBinning(int nps,int nzs, float zmxAbs)\n{\n \/\/ set binning, limits\n fNStacksSect = nps;\n fNStacksZSect = nzs;\n fNStacksZ = nzs*2; \/\/ nzs is the number of bins per side!\n fZMaxAbs = zmxAbs;\n fNStacks = fNStacksZ*fNStacksSect*kNSectors;\n \/\/ \n if (zmxAbs<1e-8 || nzs<1 || nps<1) AliFatalF(\"Wrong settings: |Zmax|:%f Nz:%d Nphi:%d\",\n\t\t\t\t\t zmxAbs,nzs,nps);\n fZScaleI = nzs\/zmxAbs;\n fY2XScaleI = nps\/(2*TMath::Tan(TMath::Pi()\/kNSectors));\n \/\/\n}\n\n18 -> kNSectors\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n#include \"AliCheb2DStackF.h\"\n#include \"AliCheb2DStackS.h\"\n#include \"AliTPCChebCorr.h\"\n#include \"AliLog.h\"\n#include \n\nClassImp(AliTPCChebCorr)\n\n\nconst float AliTPCChebCorr::fgkAngGap = 5e-4; \/\/ allow some empty ang. space between sectors\nconst float AliTPCChebCorr::fgkY2XHSpan = TMath::Tan(TMath::Pi()\/AliTPCChebCorr::kNSectors - AliTPCChebCorr::fgkAngGap);\n\n\/\/____________________________________________________________________\nAliTPCChebCorr::AliTPCChebCorr()\n : TNamed()\n ,fNStacksSect(0)\n ,fNStacksZSect(0)\n ,fNStacksZ(0)\n ,fNStacks(0)\n ,fZMaxAbs(-1)\n ,fTimeStampStart(0)\n ,fTimeStampEnd(0xffffffff)\n ,fZScaleI(0)\n ,fY2XScaleI(0)\n ,fParams(0)\n{\n\/\/ def. c-tor \n}\n\n\/\/____________________________________________________________________\nAliTPCChebCorr::AliTPCChebCorr(const char* name, const char* title, \n\t\t\t int nps, int nzs, float zmaxAbs)\n : TNamed(name,title)\n ,fNStacksSect(0)\n ,fNStacksZSect(0)\n ,fNStacksZ(0)\n ,fNStacks(0)\n ,fZMaxAbs(-1)\n ,fTimeStampStart(0)\n ,fTimeStampEnd(0xffffffff)\n ,fZScaleI(0)\n ,fY2XScaleI(0)\n ,fParams(0)\n{\n \/\/ c-tor\n SetBinning(nps,nzs,zmaxAbs);\n \/\/\n}\n\n\/\/____________________________________________________________________\nAliTPCChebCorr::~AliTPCChebCorr()\n{\n \/\/ d-tor\n if (fParams) for (int i=fNStacks;i--;) delete fParams[i];\n delete[] fParams;\n}\n\n\/\/____________________________________________________________________\nvoid AliTPCChebCorr::Parameterize(stFun_t fun,int dimOut,const int np[2],const float* prec)\n{\n \/\/ build parameterizations for 2->dimout, on the same grid of np[0]xnp[1] points for\n \/\/ every output dimension, optionally with prec[i] precision for i-th dimension\n \/\/\n if (TestBit(kParamDone)) {\n AliError(\"Parameterization is already done\");\n return;\n }\n \/\/\n if (fZMaxAbs<0) AliFatal(\"First the binning and Z limits should be set\");\n \/\/\n float bmn[2],bmx[2];\n Bool_t useS = GetUseShortPrec(); \/\/ float or short representation for param\n fParams = new AliCheb2DStack*[fNStacks];\n \/\/\n for (int iz=0;izdimout, on the same grid of np[0]xnp[1] points for\n \/\/ every output dimension, optionally with prec[i] precision for i-th dimension\n \/\/\n if (TestBit(kParamDone)) {\n AliError(\"Parameterization is already done\");\n return;\n }\n \/\/\n float bmn[2],bmx[2];\n float y2xMax = TMath::Tan(TMath::Pi()\/kNSectors); \/\/ half-sector span\n \/\/\n fParams = new AliCheb2DStack*[fNStacks];\n Bool_t useS = GetUseShortPrec(); \/\/ float or short representation for param\n \/\/\n for (int iz=0;iz=fNStacksZSect) iz = fNStacksZSect-1;} \/\/ C side\n else {if (iz=fNStacksZ) iz=fNStacksZ-1;\n int is = (y2x+fgkY2XHSpan)*fY2XScaleI;\n if (is<0) is=0; else if (is>=fNStacksSect) is=fNStacksSect-1;\n float tz[2] = {y2x,z}; \/\/ params use row, Y\/X, Z\n GetParam(GetParID(iz,sector,is))->Eval(row,tz,corr);\n \/\/\n}\n\n\/\/____________________________________________________________________\nvoid AliTPCChebCorr::Eval(int sector, int row, float tz[2], float *corr) const\n{\n \/\/ Calculate correction for point with x,y,z sector corrdinates\n \/\/ If sector in 0-71 ROC convention, possible Z-outlying is checked\n int iz = (tz[1]+fZMaxAbs)*fZScaleI, side = sector\/kNSectors;\n sector %= kNSectors;\n \/\/ correct for eventual Z calculated in wrong ROC\n if (side) {if (iz>=fNStacksZSect) iz = fNStacksZSect-1;} \/\/ C side\n else {if (iz=fNStacksZ) iz=fNStacksZ-1;\n int is = (tz[0]+fgkY2XHSpan)*fY2XScaleI;\n if (is<0) is=0; else if (is>=fNStacksSect) is=fNStacksSect-1;\n GetParam(GetParID(iz,sector,is))->Eval(row,tz,corr);\n \/\/\n}\n\n\/\/____________________________________________________________________\nvoid AliTPCChebCorr::Print(const Option_t* opt) const\n{\n \/\/ print itself\n printf(\"%s:%s Cheb2D[%c] Param: %d slices in %+.1f<%s<%+.1f %d per sector\\n\",\n\t GetName(),GetTitle(),GetUseFloatPrec()?'F':'S',\n\t fNStacksZ,-fZMaxAbs,GetUseZ2R() ? \"Z\/R\":\"Z\",fZMaxAbs,fNStacksSect);\n printf(\"Time span: %10d:%10d TimeDependent flag: %s\\n\",fTimeStampStart,fTimeStampEnd,\n\t GetTimeDependent() ? \"ON\":\"OFF\");\n TString opts = opt; opts.ToLower();\n if (opts.Contains(\"p\") && TestBit(kParamDone)) {\n for (int iz=0;izPrint(opt);\n\t}\n }\n }\n }\n}\n\n\/\/____________________________________________________________________\nvoid AliTPCChebCorr::SetBinning(int nps,int nzs, float zmxAbs)\n{\n \/\/ set binning, limits\n fNStacksSect = nps;\n fNStacksZSect = nzs;\n fNStacksZ = nzs*2; \/\/ nzs is the number of bins per side!\n fZMaxAbs = zmxAbs;\n fNStacks = fNStacksZ*fNStacksSect*kNSectors;\n \/\/ \n if (zmxAbs<1e-8 || nzs<1 || nps<1) AliFatalF(\"Wrong settings: |Zmax|:%f Nz:%d Nphi:%d\",\n\t\t\t\t\t zmxAbs,nzs,nps);\n fZScaleI = nzs\/zmxAbs;\n fY2XScaleI = nps\/(2*TMath::Tan(TMath::Pi()\/kNSectors));\n \/\/\n}\n\n<|endoftext|>"} {"text":"#include \"CHBulk.h\"\n\ntemplate<>\nInputParameters validParams()\n{\n InputParameters params = validParams();\n params.addParam(\"mob_name\",\"M\",\"The mobility used with the kernel\");\n \n return params;\n}\n\nCHBulk::CHBulk(const std::string & name, InputParameters parameters)\n :KernelGrad(name, parameters),\n _mob_name(getParam(\"mob_name\")),\n _M(getMaterialProperty(_mob_name))\n{ \n}\n\nRealGradient\nCHBulk::computeGradDFDCons(PFFunctionType type)\n{\n switch (type)\n {\n case Residual:\n return 3*_u[_qp]*_u[_qp]*_grad_u[_qp] - _grad_u[_qp]; \/\/ return Residual value\n \n case Jacobian: \n return 6*_u[_qp]*_phi[_j][_qp]*_grad_u[_qp] + 3*_u[_qp]*_u[_qp]*_grad_phi[_j][_qp] - _grad_phi[_j][_qp]; \/\/return Jacobian value\n \n }\n \n mooseError(\"Invalid type passed in\");\n}\n\nRealGradient\nCHBulk::precomputeQpResidual()\n{\n return _M[_qp] * computeGradDFDCons(Residual);\n}\n\nRealGradient\nCHBulk::precomputeQpJacobian()\n{\n return _M[_qp] * computeGradDFDCons(Jacobian);\n}\nr2857 dd8cd9ef-2931-0410-98ca-75ad22d19dd1#include \"CHBulk.h\"\n\ntemplate<>\nInputParameters validParams()\n{\n InputParameters params = validParams();\n params.addParam(\"mob_name\",\"M\",\"The mobility used with the kernel\");\n \n return params;\n}\n\nCHBulk::CHBulk(const std::string & name, InputParameters parameters)\n :KernelGrad(name, parameters),\n _mob_name(getParam(\"mob_name\")),\n _M(getMaterialProperty(_mob_name))\n{ \n}\n\nRealGradient\nCHBulk::computeGradDFDCons(PFFunctionType type)\n{\n switch (type)\n {\n case Residual:\n return 3*_u[_qp]*_u[_qp]*_grad_u[_qp] - _grad_u[_qp]; \/\/ return Residual value\n \n case Jacobian: \n return 6*_u[_qp]*_phi[_j][_qp]*_grad_u[_qp] + 3*_u[_qp]*_u[_qp]*_grad_phi[_j][_qp] - _grad_phi[_j][_qp]; \/\/return Jacobian value\n \/\/return 0.0;\n \n }\n \n mooseError(\"Invalid type passed in\");\n}\n\nRealGradient\nCHBulk::precomputeQpResidual()\n{\n return _M[_qp] * computeGradDFDCons(Residual);\n}\n\nRealGradient\nCHBulk::precomputeQpJacobian()\n{\n return _M[_qp] * computeGradDFDCons(Jacobian);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2011, Intel Corporation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without \n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice, \n * this list of conditions and the following disclaimer.\n * - Redistributions in binary form must reproduce the above copyright notice, \n * this list of conditions and the following disclaimer in the documentation \n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE \n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF \n * THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"dpoCKernel.h\"\n\n#include \"dpo_debug.h\"\n#include \"dpoCData.h\"\n#include \"dpoCContext.h\"\n#include \"nsMemory.h\"\n#include \"dpo_security_checks_stub.h\"\n\n#include \"nsIClassInfoImpl.h\"\n\n#ifdef WINDOWS_ROUNDTRIP\n#include \"windows.h\"\n#endif \/* WINDOWS_ROUNDTRIP *\/\n\n\/*\n * Implement ClassInfo support to make this class feel more like a JavaScript class, i.e.,\n * it is autmatically casted to the right interface and all methods are available\n * without using QueryInterface.\n * \n * see https:\/\/developer.mozilla.org\/en\/Using_nsIClassInfo\n *\/\nNS_IMPL_CLASSINFO( dpoCKernel, 0, 0, DPO_KERNEL_CID)\nNS_IMPL_CI_INTERFACE_GETTER2(dpoCKernel, dpoIKernel, nsISecurityCheckedComponent)\n\n\/* \n * Implement the hooks for the cycle collector\n *\/\nNS_IMPL_CYCLE_COLLECTION_CLASS(dpoCKernel)\nNS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(dpoCKernel)\n NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS\n NS_IMPL_CYCLE_COLLECTION_TRAVERSE(parent)\nNS_IMPL_CYCLE_COLLECTION_TRAVERSE_END\n\nNS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(dpoCKernel)\nNS_IMPL_CYCLE_COLLECTION_TRACE_END\n\nNS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(dpoCKernel)\n NS_IMPL_CYCLE_COLLECTION_UNLINK(parent)\nNS_IMPL_CYCLE_COLLECTION_UNLINK_END\n\nNS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(dpoCKernel)\n NS_INTERFACE_MAP_ENTRY(dpoIKernel)\n NS_INTERFACE_MAP_ENTRY(nsISecurityCheckedComponent)\n NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, dpoIKernel)\n NS_IMPL_QUERY_CLASSINFO(dpoCKernel)\nNS_INTERFACE_MAP_END\n\nNS_IMPL_CYCLE_COLLECTING_ADDREF(dpoCKernel)\nNS_IMPL_CYCLE_COLLECTING_RELEASE(dpoCKernel)\n\nDPO_SECURITY_CHECKS_ALL( dpoCKernel)\n\ndpoCKernel::dpoCKernel(dpoIContext *aParent)\n{\n\tDEBUG_LOG_CREATE(\"dpoCKernel\", this);\n\tparent = aParent;\n\tkernel = NULL;\n\tcmdQueue = NULL;\n}\n\ndpoCKernel::~dpoCKernel()\n{\n\tDEBUG_LOG_DESTROY(\"dpoCKernel\", this);\n\tif (kernel != NULL) {\n\t\tclReleaseKernel(kernel);\n\t}\n\tparent = NULL;\n}\n\nnsresult dpoCKernel::InitKernel(cl_command_queue aCmdQueue, cl_kernel aKernel, cl_mem aFailureMem)\n{\n\tcl_int err_code;\n\n\tkernel = aKernel;\n\terr_code = clRetainCommandQueue( aCmdQueue);\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"initCData\", err_code);\n\t\treturn NS_ERROR_NOT_AVAILABLE;\n\t}\n\tcmdQueue = aCmdQueue;\n\n\tfailureMem = aFailureMem;\n\n\terr_code = clSetKernelArg(kernel, 0, sizeof(cl_mem), &failureMem);\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"initCData\", err_code);\n\t\treturn NS_ERROR_NOT_AVAILABLE;\n\t}\n\n\treturn NS_OK;\n}\n\n\/* readonly attribute uint32_t numberOfArgs; *\/\nNS_IMETHODIMP dpoCKernel::GetNumberOfArgs(uint32_t *aNumberOfArgs)\n{\n\tcl_uint result;\n\tcl_int err_code;\n\n\terr_code = clGetKernelInfo(kernel, CL_KERNEL_NUM_ARGS, sizeof(cl_uint), &result, NULL);\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"GetNumberOfArgs\", err_code);\n\t\treturn NS_ERROR_NOT_AVAILABLE;\n\t}\n\n\t\/* skip internal arguments when counting *\/\n\t*aNumberOfArgs = result - DPO_NUMBER_OF_ARTIFICIAL_ARGS;\n\n return NS_OK;\n}\n\n\/* void setArgument (in uint32_t number, in dpoIData argument); *\/\nNS_IMETHODIMP dpoCKernel::SetArgument(uint32_t number, dpoIData *argument)\n{\n\tcl_int err_code;\n\tcl_mem buffer;\n\n\t\/* skip internal arguments *\/\n\tnumber = number + DPO_NUMBER_OF_ARTIFICIAL_ARGS;\n\n\tbuffer = ((dpoCData *) argument)->GetContainedBuffer();\n\tDEBUG_LOG_STATUS(\"SetArgument\", \"buffer is \" << buffer);\n\n\terr_code = clSetKernelArg(kernel, number, sizeof(cl_mem), &buffer);\n\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"SetArgument\", err_code);\n\t\treturn NS_ERROR_INVALID_ARG;\n\t}\n\n return NS_OK;\n}\n\n\/\/ High precision is true when arguments are passed as doubles and false when passed as floats.\n\/* void setScalarArgument (in uint32_t number, in jsval argument); *\/\nNS_IMETHODIMP dpoCKernel::SetScalarArgument(uint32_t number, const jsval & argument, \n\tconst jsval & isInteger, const jsval & highPrecision)\n{\n\tcl_int err_code;\n\tbool isIntegerB;\n\tbool isHighPrecisionB;\n\n\t\/* skip internal arguments *\/\n\tnumber = number + DPO_NUMBER_OF_ARTIFICIAL_ARGS;\n\n\tif (!JSVAL_IS_BOOLEAN(isInteger)) {\n\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"illegal isInteger argument.\");\n\n\t\treturn NS_ERROR_INVALID_ARG;\n\t}\n\tisIntegerB = JSVAL_TO_BOOLEAN(isInteger);\n\t\n\tif (!JSVAL_IS_BOOLEAN(highPrecision)) {\n\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"illegal highPrecision argument.\");\n\n\t\treturn NS_ERROR_INVALID_ARG;\n\t}\n\tisHighPrecisionB = JSVAL_TO_BOOLEAN(highPrecision);\n\n\tif (!JSVAL_IS_NUMBER(argument)) {\n\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"illegal number argument.\");\n\n\t\treturn NS_ERROR_INVALID_ARG;\n\t}\n\n\tif (JSVAL_IS_INT(argument)) {\n\t\tint value = JSVAL_TO_INT(argument);\n\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"(JSVAL_IS_INT(argument)) isIntegerB: \" << isIntegerB << \" isHighPrecisionB \" << isHighPrecisionB);\n\n\t\tif (isIntegerB) {\n\t\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"(JSVAL_IS_INT(argument)) setting integer argument \" << number << \" to integer value \" << value);\n\t\t\tcl_int intVal = (cl_int) value;\n\t\t\terr_code = clSetKernelArg(kernel, number, sizeof(cl_int), &intVal);\n\t\t} else if (isHighPrecisionB) {\n\t\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"setting double argument \" << number << \" to integer value \" << value);\n\t\t\tcl_double doubleVal = (cl_double) value;\n\t\t\terr_code = clSetKernelArg(kernel, number, sizeof(cl_double), &doubleVal);\n\t\t} else {\n\t\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"setting float argument \" << number << \" to integer value \" << value);\n\t\t\tcl_float floatVal = (cl_float) value;\n\t\t\terr_code = clSetKernelArg(kernel, number, sizeof(cl_float), &floatVal);\n\t\t}\n\n\t\tif (err_code != CL_SUCCESS) {\n\t\t\tDEBUG_LOG_ERROR(\"SetScalarArgument\", err_code);\n\t\t\treturn NS_ERROR_NOT_AVAILABLE;\n\t\t}\n\t} else if (JSVAL_IS_DOUBLE(argument)) {\n\t\tdouble value = JSVAL_TO_DOUBLE(argument);\n\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"(JSVAL_IS_DOUBLE(argument)) isIntegerB: \" << isIntegerB << \" isHighPrecisionB \" << isHighPrecisionB);\n\n\t\tif (isIntegerB) {\n\t\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"setting int formal argument \" << number << \" using double value \" << value);\n\t\t\tcl_int intVal = (cl_int) value;\n\t\t\terr_code = clSetKernelArg(kernel, number, sizeof(cl_int), &intVal);\n\t\t} else if (isHighPrecisionB) {\n\t\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"setting double formal argument \" << number << \" using double value \" << value);\n\t\t\tcl_double doubleVal = (cl_double) value;\n\t\t\terr_code = clSetKernelArg(kernel, number, sizeof(cl_double), &doubleVal);\n\t\t} else {\n\t\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"setting float formal argument \" << number << \" using double value \" << value);\n\t\t\tcl_float floatVal = (cl_float) value;\n\t\t\terr_code = clSetKernelArg(kernel, number, sizeof(cl_float), &floatVal);\n\t\t}\n\n\t\tif (err_code != CL_SUCCESS) {\n\t\t\tDEBUG_LOG_ERROR(\"SetScalarArgument\", err_code);\n\t\t\treturn NS_ERROR_NOT_AVAILABLE;\n\t\t}\n\t} else {\n\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"illegal number argument.\");\n\n\t\treturn NS_ERROR_INVALID_ARG;\n\t}\n\n\treturn NS_OK;\n}\n\n\/* uint32_t run (in uint32_t rank, [array, size_is (rank)] in uint32_t shape, [array, size_is (rank), optional] in uint32_t tile); *\/\nNS_IMETHODIMP dpoCKernel::Run(uint32_t rank, uint32_t *shape, uint32_t *tile, uint32_t *_retval)\n{\n\tcl_int err_code;\n\tcl_event runEvent, readEvent, writeEvent;\n\tsize_t *global_work_size;\n\tsize_t *local_work_size;\n\tconst int zero = 0;\n\n\tDEBUG_LOG_STATUS(\"Run\", \"preparing execution of kernel\");\n\n if (sizeof(size_t) == sizeof(uint32_t)) {\n\t\tglobal_work_size = (size_t *) shape;\n\t} else {\n\t\tglobal_work_size = (size_t *) nsMemory::Alloc(rank * sizeof(size_t));\n\t\tif (global_work_size == NULL) {\n\t\t\tDEBUG_LOG_STATUS(\"Run\", \"allocation of global_work_size failed\");\n\t\t\treturn NS_ERROR_OUT_OF_MEMORY;\n\t\t}\n\t\tfor (int cnt = 0; cnt < rank; cnt++) {\n\t\t\tglobal_work_size[cnt] = shape[cnt];\n\t\t}\n\t}\n\n#ifdef USE_LOCAL_WORKSIZE\n\tif (tile == NULL) {\n\t\tlocal_work_size = NULL;\n\t} else {\n\t\tif ((sizeof(size_t) == sizeof(uint32_t))) {\n\t\t\tlocal_work_size = (size_t *) tile;\n\t\t} else {\n\t\t\tlocal_work_size = (size_t *) nsMemory::Alloc(rank * sizeof(size_t));\n\t\t\tif (local_work_size == NULL) {\n\t\t\t\tDEBUG_LOG_STATUS(\"Run\", \"allocation of local_work_size failed\");\n\t\t\t\treturn NS_ERROR_OUT_OF_MEMORY;\n\t\t\t}\n\t\t\tfor (int cnt = 0; cnt < rank; cnt++) {\n\t\t\t\tlocal_work_size[cnt] = (size_t) tile[cnt];\n\t\t\t}\n\t\t}\n\t}\n#else \/* USE_LOCAL_WORKSIZE *\/\n\tlocal_work_size = NULL;\n#endif \/* USE_LOCAL_WORKSIZE *\/\n\n\tDEBUG_LOG_STATUS(\"Run\", \"setting failure code to 0\");\n\n\terr_code = clEnqueueWriteBuffer(cmdQueue, failureMem, CL_FALSE, 0, sizeof(int), &zero, 0, NULL, &writeEvent);\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"Run\", err_code);\n\t\treturn NS_ERROR_ABORT;\n\t}\n\n\tDEBUG_LOG_STATUS(\"Run\", \"enqueing execution of kernel\");\n\n#ifdef WINDOWS_ROUNDTRIP\n\tdpoCContext::RecordBeginOfRoundTrip(parent);\n#endif \/* WINDOWS_ROUNDTRIP *\/\n\n\terr_code = clEnqueueNDRangeKernel(cmdQueue, kernel, rank, NULL, global_work_size, NULL, 1, &writeEvent, &runEvent);\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"Run\", err_code);\n\t\treturn NS_ERROR_ABORT;\n\t}\n\n\tDEBUG_LOG_STATUS(\"Run\", \"reading failure code\");\n\n\terr_code = clEnqueueReadBuffer(cmdQueue, failureMem, CL_FALSE, 0, sizeof(int), _retval, 1, &runEvent, &readEvent);\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"Run\", err_code);\n\t\treturn NS_ERROR_ABORT;\n\t}\n\n\tDEBUG_LOG_STATUS(\"Run\", \"waiting for execution to finish\");\n\t\n\t\/\/ For now we always wait for the run to complete.\n\t\/\/ In the long run, we may want to interleave this with JS execution and only sync on result read.\n\terr_code = clWaitForEvents( 1, &readEvent);\n\t\n\tDEBUG_LOG_STATUS(\"Run\", \"first event fired\");\n\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"Run\", err_code);\n\t\treturn NS_ERROR_ABORT;\n\t}\n#ifdef WINDOWS_ROUNDTRIP\n\tdpoCContext::RecordEndOfRoundTrip(parent);\n#endif \/* WINDOWS_ROUNDTRIP *\/\n\t\n#ifdef CLPROFILE\n#ifdef CLPROFILE_ASYNC\n\terr_code = clSetEventCallback( readEvent, CL_COMPLETE, &dpoCContext::CollectTimings, parent);\n\t\n\tDEBUG_LOG_STATUS(\"Run\", \"second event fired\");\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"Run\", err_code);\n\t\treturn NS_ERROR_ABORT;\n\t}\n#else \/* CLPROFILE_ASYNC *\/\n\tdpoCContext::CollectTimings(readEvent,CL_COMPLETE,parent);\n#endif \/* CLPROFILE_ASYNC *\/\n#endif \/* CLPROFILE *\/\n\t\t\n\tDEBUG_LOG_STATUS(\"Run\", \"execution completed successfully, start cleanup\");\n\t\n\tif (global_work_size != (size_t *) shape) {\n\t\tnsMemory::Free(global_work_size);\n\t}\n#ifdef USE_LOCAL_WORKSIZE\n\tif (local_work_size != (size_t *) tile) {\n\t\tnsMemory::Free(local_work_size);\n\t}\n#endif \/* USE_LOCAL_WORKSIZE *\/\n\t\n\terr_code = clReleaseEvent(readEvent);\n\terr_code = clReleaseEvent(runEvent);\n\terr_code = clReleaseEvent(writeEvent);\n\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"Run\", err_code);\n\t\treturn NS_ERROR_ABORT;\n\t}\n\n\tDEBUG_LOG_STATUS(\"Run\", \"cleanup complete\");\n\n return NS_OK;\n}\nUpdate dpoCKernel.cpp\/*\n * Copyright (c) 2011, Intel Corporation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without \n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice, \n * this list of conditions and the following disclaimer.\n * - Redistributions in binary form must reproduce the above copyright notice, \n * this list of conditions and the following disclaimer in the documentation \n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE \n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF \n * THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"dpoCKernel.h\"\n\n#include \"dpo_debug.h\"\n#include \"dpoCData.h\"\n#include \"dpoCContext.h\"\n#include \"nsMemory.h\"\n#include \"dpo_security_checks_stub.h\"\n\n#include \"nsIClassInfoImpl.h\"\n\n#ifdef WINDOWS_ROUNDTRIP\n#include \"windows.h\"\n#endif \/* WINDOWS_ROUNDTRIP *\/\n\n\/*\n * Implement ClassInfo support to make this class feel more like a JavaScript class, i.e.,\n * it is autmatically casted to the right interface and all methods are available\n * without using QueryInterface.\n * \n * see https:\/\/developer.mozilla.org\/en\/Using_nsIClassInfo\n *\/\nNS_IMPL_CLASSINFO( dpoCKernel, 0, 0, DPO_KERNEL_CID)\nNS_IMPL_CI_INTERFACE_GETTER2(dpoCKernel, dpoIKernel, nsISecurityCheckedComponent)\n\n\/* \n * Implement the hooks for the cycle collector\n *\/\nNS_IMPL_CYCLE_COLLECTION_CLASS(dpoCKernel)\nNS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(dpoCKernel)\n NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS\n NS_IMPL_CYCLE_COLLECTION_TRAVERSE(parent)\nNS_IMPL_CYCLE_COLLECTION_TRAVERSE_END\n\nNS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(dpoCKernel)\nNS_IMPL_CYCLE_COLLECTION_TRACE_END\n\nNS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(dpoCKernel)\n NS_IMPL_CYCLE_COLLECTION_UNLINK(parent)\nNS_IMPL_CYCLE_COLLECTION_UNLINK_END\n\nNS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(dpoCKernel)\n NS_INTERFACE_MAP_ENTRY(dpoIKernel)\n NS_INTERFACE_MAP_ENTRY(nsISecurityCheckedComponent)\n NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, dpoIKernel)\n NS_IMPL_QUERY_CLASSINFO(dpoCKernel)\nNS_INTERFACE_MAP_END\n\nNS_IMPL_CYCLE_COLLECTING_ADDREF(dpoCKernel)\nNS_IMPL_CYCLE_COLLECTING_RELEASE(dpoCKernel)\n\nDPO_SECURITY_CHECKS_ALL( dpoCKernel)\n\ndpoCKernel::dpoCKernel(dpoIContext *aParent)\n{\n\tDEBUG_LOG_CREATE(\"dpoCKernel\", this);\n\tparent = aParent;\n\tkernel = NULL;\n\tcmdQueue = NULL;\n}\n\ndpoCKernel::~dpoCKernel()\n{\n\tDEBUG_LOG_DESTROY(\"dpoCKernel\", this);\n\tif (kernel != NULL) {\n\t\tclReleaseKernel(kernel);\n\t}\n\tparent = NULL;\n}\n\nnsresult dpoCKernel::InitKernel(cl_command_queue aCmdQueue, cl_kernel aKernel, cl_mem aFailureMem)\n{\n\tcl_int err_code;\n\n\tkernel = aKernel;\n\terr_code = clRetainCommandQueue( aCmdQueue);\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"initCData\", err_code);\n\t\treturn NS_ERROR_NOT_AVAILABLE;\n\t}\n\tcmdQueue = aCmdQueue;\n\n\tfailureMem = aFailureMem;\n\n\terr_code = clSetKernelArg(kernel, 0, sizeof(cl_mem), &failureMem);\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"initCData\", err_code);\n\t\treturn NS_ERROR_NOT_AVAILABLE;\n\t}\n\n\treturn NS_OK;\n}\n\n\/* readonly attribute uint32_t numberOfArgs; *\/\nNS_IMETHODIMP dpoCKernel::GetNumberOfArgs(uint32_t *aNumberOfArgs)\n{\n\tcl_uint result;\n\tcl_int err_code;\n\n\terr_code = clGetKernelInfo(kernel, CL_KERNEL_NUM_ARGS, sizeof(cl_uint), &result, NULL);\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"GetNumberOfArgs\", err_code);\n\t\treturn NS_ERROR_NOT_AVAILABLE;\n\t}\n\n\t\/* skip internal arguments when counting *\/\n\t*aNumberOfArgs = result - DPO_NUMBER_OF_ARTIFICIAL_ARGS;\n\n return NS_OK;\n}\n\n\/* void setArgument (in uint32_t number, in dpoIData argument); *\/\nNS_IMETHODIMP dpoCKernel::SetArgument(uint32_t number, dpoIData *argument)\n{\n\tcl_int err_code;\n\tcl_mem buffer;\n\n\t\/* skip internal arguments *\/\n\tnumber = number + DPO_NUMBER_OF_ARTIFICIAL_ARGS;\n\n\tbuffer = ((dpoCData *) argument)->GetContainedBuffer();\n\tDEBUG_LOG_STATUS(\"SetArgument\", \"buffer is \" << buffer);\n\n\terr_code = clSetKernelArg(kernel, number, sizeof(cl_mem), &buffer);\n\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"SetArgument\", err_code);\n\t\treturn NS_ERROR_INVALID_ARG;\n\t}\n\n return NS_OK;\n}\n\n\/\/ High precision is true when arguments are passed as doubles and false when passed as floats.\n\/* void setScalarArgument (in uint32_t number, in jsval argument); *\/\nNS_IMETHODIMP dpoCKernel::SetScalarArgument(uint32_t number, const jsval & argument, \n\tconst jsval & isInteger, const jsval & highPrecision)\n{\n\tcl_int err_code;\n\tbool isIntegerB;\n\tbool isHighPrecisionB;\n\n\t\/* skip internal arguments *\/\n\tnumber = number + DPO_NUMBER_OF_ARTIFICIAL_ARGS;\n\n\tif (!JSVAL_IS_BOOLEAN(isInteger)) {\n\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"illegal isInteger argument.\");\n\n\t\treturn NS_ERROR_INVALID_ARG;\n\t}\n\tisIntegerB = JSVAL_TO_BOOLEAN(isInteger);\n\t\n\tif (!JSVAL_IS_BOOLEAN(highPrecision)) {\n\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"illegal highPrecision argument.\");\n\n\t\treturn NS_ERROR_INVALID_ARG;\n\t}\n\tisHighPrecisionB = JSVAL_TO_BOOLEAN(highPrecision);\n\n\tif (!JSVAL_IS_NUMBER(argument)) {\n\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"illegal number argument.\");\n\n\t\treturn NS_ERROR_INVALID_ARG;\n\t}\n\n\tif (JSVAL_IS_INT(argument)) {\n\t\tint value = JSVAL_TO_INT(argument);\n\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"(JSVAL_IS_INT(argument)) isIntegerB: \" << isIntegerB << \" isHighPrecisionB \" << isHighPrecisionB);\n\n\t\tif (isIntegerB) {\n\t\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"(JSVAL_IS_INT(argument)) setting integer argument \" << number << \" to integer value \" << value);\n\t\t\tcl_int intVal = (cl_int) value;\n\t\t\terr_code = clSetKernelArg(kernel, number, sizeof(cl_int), &intVal);\n\t\t} else if (isHighPrecisionB) {\n\t\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"setting double argument \" << number << \" to integer value \" << value);\n\t\t\tcl_double doubleVal = (cl_double) value;\n\t\t\terr_code = clSetKernelArg(kernel, number, sizeof(cl_double), &doubleVal);\n\t\t} else {\n\t\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"setting float argument \" << number << \" to integer value \" << value);\n\t\t\tcl_float floatVal = (cl_float) value;\n\t\t\terr_code = clSetKernelArg(kernel, number, sizeof(cl_float), &floatVal);\n\t\t}\n\n\t\tif (err_code != CL_SUCCESS) {\n\t\t\tDEBUG_LOG_ERROR(\"SetScalarArgument\", err_code);\n\t\t\treturn NS_ERROR_NOT_AVAILABLE;\n\t\t}\n\t} else if (JSVAL_IS_DOUBLE(argument)) {\n\t\tdouble value = JSVAL_TO_DOUBLE(argument);\n\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"(JSVAL_IS_DOUBLE(argument)) isIntegerB: \" << isIntegerB << \" isHighPrecisionB \" << isHighPrecisionB);\n\n\t\tif (isIntegerB) {\n\t\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"setting int formal argument \" << number << \" using double value \" << value);\n\t\t\tcl_int intVal = (cl_int) value;\n\t\t\terr_code = clSetKernelArg(kernel, number, sizeof(cl_int), &intVal);\n\t\t} else if (isHighPrecisionB) {\n\t\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"setting double formal argument \" << number << \" using double value \" << value);\n\t\t\tcl_double doubleVal = (cl_double) value;\n\t\t\terr_code = clSetKernelArg(kernel, number, sizeof(cl_double), &doubleVal);\n\t\t} else {\n\t\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"setting float formal argument \" << number << \" using double value \" << value);\n\t\t\tcl_float floatVal = (cl_float) value;\n\t\t\terr_code = clSetKernelArg(kernel, number, sizeof(cl_float), &floatVal);\n\t\t}\n\n\t\tif (err_code != CL_SUCCESS) {\n\t\t\tDEBUG_LOG_ERROR(\"SetScalarArgument\", err_code);\n\t\t\treturn NS_ERROR_NOT_AVAILABLE;\n\t\t}\n\t} else {\n\t\tDEBUG_LOG_STATUS(\"SetScalarArgument\", \"illegal number argument.\");\n\n\t\treturn NS_ERROR_INVALID_ARG;\n\t}\n\n\treturn NS_OK;\n}\n\n\/* uint32_t run (in uint32_t rank, [array, size_is (rank)] in uint32_t shape, [array, size_is (rank), optional] in uint32_t tile); *\/\nNS_IMETHODIMP dpoCKernel::Run(uint32_t rank, uint32_t *shape, uint32_t *tile, uint32_t *_retval)\n{\n\tcl_int err_code;\n\tcl_event runEvent, readEvent, writeEvent;\n\tsize_t *global_work_size;\n\tsize_t *local_work_size;\n\tconst int zero = 0;\n\n\tDEBUG_LOG_STATUS(\"Run\", \"preparing execution of kernel\");\n\n if (sizeof(size_t) == sizeof(uint32_t)) {\n\t\tglobal_work_size = (size_t *) shape;\n\t} else {\n\t\tglobal_work_size = (size_t *) nsMemory::Alloc(rank * sizeof(size_t));\n\t\tif (global_work_size == NULL) {\n\t\t\tDEBUG_LOG_STATUS(\"Run\", \"allocation of global_work_size failed\");\n\t\t\treturn NS_ERROR_OUT_OF_MEMORY;\n\t\t}\n\t\tfor (int cnt = 0; cnt < rank; cnt++) {\n\t\t\tglobal_work_size[cnt] = shape[cnt];\n\t\t}\n\t}\n\n#ifdef USE_LOCAL_WORKSIZE\n\tif (tile == NULL) {\n\t\tlocal_work_size = NULL;\n\t} else {\n\t\tif ((sizeof(size_t) == sizeof(uint32_t))) {\n\t\t\tlocal_work_size = (size_t *) tile;\n\t\t} else {\n\t\t\tlocal_work_size = (size_t *) nsMemory::Alloc(rank * sizeof(size_t));\n\t\t\tif (local_work_size == NULL) {\n\t\t\t\tDEBUG_LOG_STATUS(\"Run\", \"allocation of local_work_size failed\");\n\t\t\t\treturn NS_ERROR_OUT_OF_MEMORY;\n\t\t\t}\n\t\t\tfor (int cnt = 0; cnt < rank; cnt++) {\n\t\t\t\tlocal_work_size[cnt] = (size_t) tile[cnt];\n\t\t\t}\n\t\t}\n\t}\n#else \/* USE_LOCAL_WORKSIZE *\/\n\tlocal_work_size = NULL;\n#endif \/* USE_LOCAL_WORKSIZE *\/\n\n\tDEBUG_LOG_STATUS(\"Run\", \"setting failure code to 0\");\n\n\terr_code = clEnqueueWriteBuffer(cmdQueue, failureMem, CL_FALSE, 0, sizeof(int), &zero, 0, NULL, &writeEvent);\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"Run\", err_code);\n\t\treturn NS_ERROR_ABORT;\n\t}\n\n\tDEBUG_LOG_STATUS(\"Run\", \"enqueing execution of kernel\");\n\n#ifdef WINDOWS_ROUNDTRIP\n\tdpoCContext::RecordBeginOfRoundTrip(parent);\n#endif \/* WINDOWS_ROUNDTRIP *\/\n\n\terr_code = clEnqueueNDRangeKernel(cmdQueue, kernel, rank, NULL, global_work_size, NULL, 1, &writeEvent, &runEvent);\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"Run\", err_code);\n\t\treturn NS_ERROR_ABORT;\n\t}\n\n\tDEBUG_LOG_STATUS(\"Run\", \"reading failure code\");\n\n\terr_code = clEnqueueReadBuffer(cmdQueue, failureMem, CL_FALSE, 0, sizeof(int), _retval, 1, &runEvent, &readEvent);\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"Run\", err_code);\n\t\treturn NS_ERROR_ABORT;\n\t}\n\n\tDEBUG_LOG_STATUS(\"Run\", \"waiting for execution to finish\");\n\t\n\t\/\/ For now we always wait for the run to complete.\n\t\/\/ In the long run, we may want to interleave this with JS execution and only sync on result read.\n\terr_code = clWaitForEvents( 1, &readEvent);\n\t\n\tDEBUG_LOG_STATUS(\"Run\", \"first event fired\");\n\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"Run\", err_code);\n\t\treturn NS_ERROR_ABORT;\n\t}\n#ifdef WINDOWS_ROUNDTRIP\n\tdpoCContext::RecordEndOfRoundTrip(parent);\n#endif \/* WINDOWS_ROUNDTRIP *\/\n\t\n#ifdef CLPROFILE\n#ifdef CLPROFILE_ASYNC\n\terr_code = clSetEventCallback( readEvent, CL_COMPLETE, &dpoCContext::CollectTimings, parent);\n\t\n\tDEBUG_LOG_STATUS(\"Run\", \"second event fired\");\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"Run\", err_code);\n\t\treturn NS_ERROR_ABORT;\n\t}\n#else \/* CLPROFILE_ASYNC *\/\n\tdpoCContext::CollectTimings(runEvent,CL_COMPLETE,parent);\n#endif \/* CLPROFILE_ASYNC *\/\n#endif \/* CLPROFILE *\/\n\t\t\n\tDEBUG_LOG_STATUS(\"Run\", \"execution completed successfully, start cleanup\");\n\t\n\tif (global_work_size != (size_t *) shape) {\n\t\tnsMemory::Free(global_work_size);\n\t}\n#ifdef USE_LOCAL_WORKSIZE\n\tif (local_work_size != (size_t *) tile) {\n\t\tnsMemory::Free(local_work_size);\n\t}\n#endif \/* USE_LOCAL_WORKSIZE *\/\n\t\n\terr_code = clReleaseEvent(readEvent);\n\terr_code = clReleaseEvent(runEvent);\n\terr_code = clReleaseEvent(writeEvent);\n\n\tif (err_code != CL_SUCCESS) {\n\t\tDEBUG_LOG_ERROR(\"Run\", err_code);\n\t\treturn NS_ERROR_ABORT;\n\t}\n\n\tDEBUG_LOG_STATUS(\"Run\", \"cleanup complete\");\n\n return NS_OK;\n}\n<|endoftext|>"} {"text":"\/*\n * kPPP: A front end for pppd for the KDE project\n *\n * $Id$\n * \n * Copyright (C) 1997 Bernd Johannes Wuebben \n * wuebben@math.cornell.edu\n *\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this program; if not, write to the Free\n * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\/\n\n\n#include \n#include \n#include \n#include \n\n\n#include \"modem.h\"\n#include \"pppdata.h\"\n#include \"miniterm.h\"\n\n#define T_WIDTH 550\n#define T_HEIGHT 400\n\n#ifdef NO_USLEEP\nextern int usleep( long usec );\n#endif \n\nextern PPPData gpppdata;\n\nMiniTerm::MiniTerm(QWidget *parent=0, const char *name=0)\n : QDialog(parent, name,TRUE, WStyle_Customize|WStyle_NormalBorder)\n{\n\n col = line = col_start = line_start = 0;\n modemfd = -1;\n\n setCaption(i18n(\"Kppp Mini-Terminal\"));\n\n m_file = new QPopupMenu;\n m_file->insertItem( i18n(\"&Quit\"),this, SLOT(cancelbutton()) );\n m_edit = new QPopupMenu;\n m_options = new QPopupMenu;\n m_options->insertItem(i18n(\"&Reset Modem\"),this,SLOT(resetModem()));\n m_help = new QPopupMenu;\n m_help->insertItem( i18n(\"&Help\"),this, SLOT(help()) );\n \n menubar = new KMenuBar( this );\n menubar->insertItem( i18n(\"&File\"), m_file );\n menubar->insertItem( i18n(\"&Modem\"), m_options );\n menubar->insertItem( i18n(\"&Help\"), m_help);\n \n statusbar = new QLabel(this);\n statusbar->setFrameStyle(QFrame::Panel | QFrame::Sunken);\n\n statusbar2 = new QLabel(this);\n statusbar2->setFrameStyle(QFrame::Panel | QFrame::Sunken);\n\n terminal = new MyTerm(this,\"term\");\n connect(terminal,SIGNAL(got_a_line()),this,SLOT(process_line()));\n\n setupToolbar();\n\n statusbar->setGeometry(0, T_HEIGHT - 20, T_WIDTH - 70, 20);\n statusbar2->setGeometry(T_WIDTH - 70, T_HEIGHT - 20, 70, 20);\n\n menubar->setGeometry(0,0,T_WIDTH,30);\n\n terminal->setGeometry(0, menubar->height() + toolbar->height() , \n T_WIDTH, T_HEIGHT - menubar->height() - toolbar->height() - statusbar->height());\n \n readtimer = new QTimer(this);\n connect(readtimer,SIGNAL(timeout()),this,SLOT(readtty()));\n\n inittimer = new QTimer(this);\n connect(inittimer,SIGNAL(timeout()),this,SLOT(init()));\n inittimer->start(500);\n\n} \n\n\nvoid MiniTerm::setupToolbar(){\n\n toolbar = new KToolBar( this );\n\n KIconLoader *loader = kapp->getIconLoader();\n\n QPixmap pixmap;\n\n pixmap = loader->loadIcon(\"exit.xpm\");\n toolbar->insertButton(pixmap, 0,\n\t\t SIGNAL(clicked()), this,\n\t\t SLOT(cancelbutton()), TRUE, i18n(\"Quit MiniTerm\"));\n\n\n pixmap = loader->loadIcon(\"back.xpm\");\n toolbar->insertButton(pixmap, 0,\n\t\t SIGNAL(clicked()), this,\n\t\t SLOT(resetModem()), TRUE, i18n(\"Reset Modem\"));\n\n pixmap = loader->loadIcon(\"help.xpm\");\n toolbar->insertButton(pixmap, 0,\n\t\t SIGNAL(clicked()), this,\n\t\t SLOT(help()), TRUE, i18n(\"Help\"));\n\n toolbar->setBarPos( KToolBar::Top );\n\n}\n\nvoid MiniTerm::process_line(){\n\n QString newline;\n newline = terminal->textLine(line);\n newline = newline.remove(0,col_start);\n newline = newline.stripWhiteSpace();\n writeline(newline.data());\n\n}\n\nvoid MiniTerm::resizeEvent(QResizeEvent*){\n\n menubar->setGeometry(0,0,width(),30);\n\n toolbar->setGeometry(0,menubar->height(),width(),toolbar->height());\n\n terminal->setGeometry(0, menubar->height() + toolbar->height() , \n width(), height() - menubar->height() - toolbar->height() - statusbar->height());\n\n statusbar->setGeometry(0, height() - 20, width() - 70, 20);\n statusbar2->setGeometry(width() - 70, height() - 20, 70, 20);\n\n}\n\nvoid MiniTerm::init() {\n\n inittimer->stop();\n statusbar->setText(i18n(\"Initializing Modem\"));\n kapp->processEvents();\n\n int lock = lockdevice();\n if (lock == 1){\n \n statusbar->setText(i18n(\"Sorry, modem device is locked.\"));\n return;\n }\n if (lock == -1){\n \n statusbar->setText(i18n(\"Sorry, can't create modem lock file.\"));\n return;\n }\n\n if(opentty()){\n\n if(modemfd >= 0) {\n writeline(gpppdata.modemHangupStr());\n usleep(100000); \/\/ wait 0.1 secs\n hangup();\n writeline(gpppdata.modemInitStr());\n usleep(100000);\n }\n\n statusbar->setText(i18n(\"Modem Ready\"));\n terminal->setFocus();\n\n kapp->processEvents();\n kapp->processEvents();\n readtimer->start(1);\n }\n else {\/\/ commmented out since this will now be set by the opentty() better.\n \/\/ statusbar->setText(\"Can't open modem device\");\n unlockdevice();\n }\n} \n\n\n\nvoid MiniTerm::readtty() {\n\n char c;\n\n if(read(modemfd, &c, 1) == 1) {\n c = ((int)c & 0x7F);\n \/\/ printf(\"read:%x %c\\n\",c,c);\n \n \/\/ TODO sort this shit out\n\n if(((int)c != 13)&& ((int)c != 10)&&((int)c != 8))\n terminal->insertChar( c );\n\n if((int)c == 8)\n terminal->backspace();\n if((int)c == 127)\n terminal->backspace();\n\n if((int)c == 10)\n terminal->mynewline();\n\n if((int)c == 13)\n terminal->myreturn();\n }\n \n}\n\n\nvoid MiniTerm::cancelbutton() {\n\n\n readtimer->stop();\n statusbar->setText(i18n(\"Hanging up ...\"));\n kapp->processEvents();\n kapp->flushX();\n\n if(modemfd >= 0) {\n writeline(gpppdata.modemHangupStr());\n usleep(100000); \/\/ 0.1 sec\n hangup();\n }\n\n closetty();\n unlockdevice();\n\n reject();\n}\n\n\n\nvoid MiniTerm::resetModem(){\n \n statusbar->setText(i18n(\"Resetting Modem\"));\n terminal->newLine();\n kapp->processEvents();\n kapp->flushX();\n\n if(modemfd >= 0) {\n writeline(gpppdata.modemHangupStr());\n usleep(100000); \/\/ 0.1 sec\n hangup();\n }\n statusbar->setText(i18n(\"Modem Ready\"));\n}\n\n\nbool MiniTerm::closetty(){\n\n if(modemfd > 0)\n\n \/* discard data not read or transmitted *\/\n tcflush(modemfd, TCIOFLUSH);\n\n if(tcsetattr(modemfd, TCSANOW, &initial_tty) < 0){\n statusbar->setText(i18n(\"Can't restore tty settings: tcsetattr()\\n\"));\n }\n\n ::close(modemfd);\n modemfd = -1;\n return TRUE;\n}\n\n\nbool MiniTerm::opentty() {\n\n memset(&initial_tty,'\\0',sizeof(initial_tty)); \n \n if((modemfd = open(gpppdata.modemDevice(), O_RDWR|O_NDELAY)) < 0){\n\n statusbar->setText(i18n(\"Can't open Modem\"));\n return FALSE;\n }\n \n if(tcgetattr(modemfd, &tty) < 0){\n\n statusbar->setText(i18n(\"tcgetattr() failed\\n\"));\n return FALSE;\n }\n\n initial_tty = tty; \/\/ save a copy\n\n tty.c_cc[VMIN] = 0; \/\/ nonblocking \n tty.c_cc[VTIME] = 0;\n tty.c_oflag = 0;\n tty.c_lflag = 0;\n\n \/\/ clearing CLOCAL as below ensures we observe the modem status lines\n \/\/ tty.c_cflag &= ~(CSIZE | CSTOPB | PARENB | CLOCAL); \n \n \n tty.c_cflag &= ~(CSIZE | CSTOPB | PARENB);\n tty.c_cflag |= CLOCAL ; \/\/ignore modem satus lines\n tty.c_oflag &= ~OPOST; \/\/no outline processing -- transparent output\n \n tty.c_cflag |= CS8 | CREAD; \n tty.c_iflag = IGNBRK | IGNPAR | ISTRIP; \/\/ added ISTRIP\n tty.c_lflag &= ~ICANON; \t\t\t\/\/ non-canonical mode\n tty.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHOKE);\n\n \n if(strcmp(gpppdata.flowcontrol(), \"None\") != 0) {\n if(strcmp(gpppdata.flowcontrol(), \"CRTSCTS\") == 0) {\n tty.c_cflag |= CRTSCTS;\n tty.c_iflag &= ~(IXON | IXOFF);\n }\n else {\n tty.c_cflag &= ~CRTSCTS;\n tty.c_iflag |= IXON | IXOFF;\n tty.c_cc[VSTOP] = 0x13; \/\/ DC3 = XOFF = ^S \n tty.c_cc[VSTART] = 0x11; \/\/ DC1 = XON = ^Q \n }\n }\n else {\n tty.c_cflag &= ~CRTSCTS;\n tty.c_iflag &= ~(IXON | IXOFF);\n }\n\n cfsetospeed(&tty, modemspeed());\n cfsetispeed(&tty, modemspeed());\n\n if(tcsetattr(modemfd, TCSANOW, &tty) < 0){\n\n statusbar->setText(i18n(\"tcsetattr() failed\\n\"));\n return FALSE;\n }\n\n return TRUE;\n}\n\t\t\n\nvoid MiniTerm::hangup() {\n\n struct termios temptty;\n\n if(modemfd >= 0) {\n\n \/\/ Properly bracketed escape code \n tcflush(modemfd,TCOFLUSH);\n \/\/ +3 because quiet time must be greater than guard time.\n usleep((gpppdata.modemEscapeGuardTime()+3)*20000);\n\n write(modemfd, gpppdata.modemEscapeStr(), strlen(gpppdata.modemEscapeStr()) ); \n\n tcflush(modemfd,TCOFLUSH);\n usleep((gpppdata.modemEscapeGuardTime()+3)*20000);\n\n \/\/ Then hangup command\n writeline(gpppdata.modemHangupStr());\n \n usleep(gpppdata.modemInitDelay() * 10000); \/\/ 0.01 - 3.0 sec \n\n tcsendbreak(modemfd, 0);\n\n tcgetattr(modemfd, &temptty);\n cfsetospeed(&temptty, B0);\n cfsetispeed(&temptty, B0);\n tcsetattr(modemfd, TCSAFLUSH, &temptty);\n\n usleep(gpppdata.modemInitDelay() * 10000); \/\/ 0.01 - 3.0 secs \n\n cfsetospeed(&temptty, modemspeed());\n cfsetispeed(&temptty, modemspeed());\n tcsetattr(modemfd, TCSAFLUSH, &temptty);\n \n }\n\n\n}\n\n\nbool MiniTerm::writeChar(char c){\n\n write(modemfd,&c,1);\n return true;\n\n}\n\nbool MiniTerm::writeline(const char *buf) {\n\n\n write(modemfd, buf, strlen(buf));\n\n if(strcmp(gpppdata.enter(), \"CR\/LF\") == 0)\n write(modemfd, \"\\r\\n\", 2);\n \n if(strcmp(gpppdata.enter(), \"LF\") == 0)\n write(modemfd, \"\\n\", 1);\n \n if(strcmp(gpppdata.enter(), \"CR\") == 0)\n write(modemfd, \"\\r\", 1);\n\n return true;\n}\n\n\n\nvoid MiniTerm::closeEvent( QCloseEvent *e ){\n\n e->ignore(); \/\/ don't let the user close the window\n\n}\n\nvoid MiniTerm::help(){\n\n kapp->invokeHTMLHelp(\"kppp\/kppp.html\",\"\");\n\n}\n\n\nMyTerm::MyTerm(QWidget *parent=0 ,const char* name=0)\n : QMultiLineEdit(parent, name)\n{\n p_parent = (MiniTerm*) parent;\n this->setFont(QFont(\"courier\",12,QFont::Normal));\n \n}\n\nvoid MyTerm::keyPressEvent(QKeyEvent *k) {\n\n\n if(k->ascii() == 13){\n myreturn();\n p_parent->writeChar((char) k->ascii());\n return;\n }\n\n\n p_parent->writeChar((char) k->ascii());\n\n}\n\nvoid MyTerm::insertChar(char c) {\n \n QMultiLineEdit::insertChar(c);\n\n}\n\nvoid MyTerm::newLine() {\n \n QMultiLineEdit::newLine();\n\n}\n\nvoid MyTerm::del() {\n \n QMultiLineEdit::del();\n\n}\n\nvoid MyTerm::backspace() {\n \n \/\/ QMultiLineEdit::cursorLeft();\n QMultiLineEdit::backspace();\n\n}\n\nvoid MyTerm::myreturn() {\n \n int column;\n int line;\n\n getCursorPosition(&line,&column);\n for (int i = 0; i < column;i++)\n QMultiLineEdit::cursorLeft();\n\n}\n\nvoid MyTerm::mynewline() {\n \n\n QMultiLineEdit::end(FALSE);\n QMultiLineEdit::newLine();\n\n}\n\n#include \"miniterm.moc\"\nAnd another thing: Assigning defaults in the implementation is frowned on. For instance\/*\n * kPPP: A front end for pppd for the KDE project\n *\n * $Id$\n * \n * Copyright (C) 1997 Bernd Johannes Wuebben \n * wuebben@math.cornell.edu\n *\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this program; if not, write to the Free\n * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\/\n\n\n#include \n#include \n#include \n#include \n\n\n#include \"modem.h\"\n#include \"pppdata.h\"\n#include \"miniterm.h\"\n\n#define T_WIDTH 550\n#define T_HEIGHT 400\n\n#ifdef NO_USLEEP\nextern int usleep( long usec );\n#endif \n\nextern PPPData gpppdata;\n\nMiniTerm::MiniTerm(QWidget *parent, const char *name)\n : QDialog(parent, name,TRUE, WStyle_Customize|WStyle_NormalBorder)\n{\n\n col = line = col_start = line_start = 0;\n modemfd = -1;\n\n setCaption(i18n(\"Kppp Mini-Terminal\"));\n\n m_file = new QPopupMenu;\n m_file->insertItem( i18n(\"&Quit\"),this, SLOT(cancelbutton()) );\n m_edit = new QPopupMenu;\n m_options = new QPopupMenu;\n m_options->insertItem(i18n(\"&Reset Modem\"),this,SLOT(resetModem()));\n m_help = new QPopupMenu;\n m_help->insertItem( i18n(\"&Help\"),this, SLOT(help()) );\n \n menubar = new KMenuBar( this );\n menubar->insertItem( i18n(\"&File\"), m_file );\n menubar->insertItem( i18n(\"&Modem\"), m_options );\n menubar->insertItem( i18n(\"&Help\"), m_help);\n \n statusbar = new QLabel(this);\n statusbar->setFrameStyle(QFrame::Panel | QFrame::Sunken);\n\n statusbar2 = new QLabel(this);\n statusbar2->setFrameStyle(QFrame::Panel | QFrame::Sunken);\n\n terminal = new MyTerm(this,\"term\");\n connect(terminal,SIGNAL(got_a_line()),this,SLOT(process_line()));\n\n setupToolbar();\n\n statusbar->setGeometry(0, T_HEIGHT - 20, T_WIDTH - 70, 20);\n statusbar2->setGeometry(T_WIDTH - 70, T_HEIGHT - 20, 70, 20);\n\n menubar->setGeometry(0,0,T_WIDTH,30);\n\n terminal->setGeometry(0, menubar->height() + toolbar->height() , \n T_WIDTH, T_HEIGHT - menubar->height() - toolbar->height() - statusbar->height());\n \n readtimer = new QTimer(this);\n connect(readtimer,SIGNAL(timeout()),this,SLOT(readtty()));\n\n inittimer = new QTimer(this);\n connect(inittimer,SIGNAL(timeout()),this,SLOT(init()));\n inittimer->start(500);\n\n} \n\n\nvoid MiniTerm::setupToolbar(){\n\n toolbar = new KToolBar( this );\n\n KIconLoader *loader = kapp->getIconLoader();\n\n QPixmap pixmap;\n\n pixmap = loader->loadIcon(\"exit.xpm\");\n toolbar->insertButton(pixmap, 0,\n\t\t SIGNAL(clicked()), this,\n\t\t SLOT(cancelbutton()), TRUE, i18n(\"Quit MiniTerm\"));\n\n\n pixmap = loader->loadIcon(\"back.xpm\");\n toolbar->insertButton(pixmap, 0,\n\t\t SIGNAL(clicked()), this,\n\t\t SLOT(resetModem()), TRUE, i18n(\"Reset Modem\"));\n\n pixmap = loader->loadIcon(\"help.xpm\");\n toolbar->insertButton(pixmap, 0,\n\t\t SIGNAL(clicked()), this,\n\t\t SLOT(help()), TRUE, i18n(\"Help\"));\n\n toolbar->setBarPos( KToolBar::Top );\n\n}\n\nvoid MiniTerm::process_line(){\n\n QString newline;\n newline = terminal->textLine(line);\n newline = newline.remove(0,col_start);\n newline = newline.stripWhiteSpace();\n writeline(newline.data());\n\n}\n\nvoid MiniTerm::resizeEvent(QResizeEvent*){\n\n menubar->setGeometry(0,0,width(),30);\n\n toolbar->setGeometry(0,menubar->height(),width(),toolbar->height());\n\n terminal->setGeometry(0, menubar->height() + toolbar->height() , \n width(), height() - menubar->height() - toolbar->height() - statusbar->height());\n\n statusbar->setGeometry(0, height() - 20, width() - 70, 20);\n statusbar2->setGeometry(width() - 70, height() - 20, 70, 20);\n\n}\n\nvoid MiniTerm::init() {\n\n inittimer->stop();\n statusbar->setText(i18n(\"Initializing Modem\"));\n kapp->processEvents();\n\n int lock = lockdevice();\n if (lock == 1){\n \n statusbar->setText(i18n(\"Sorry, modem device is locked.\"));\n return;\n }\n if (lock == -1){\n \n statusbar->setText(i18n(\"Sorry, can't create modem lock file.\"));\n return;\n }\n\n if(opentty()){\n\n if(modemfd >= 0) {\n writeline(gpppdata.modemHangupStr());\n usleep(100000); \/\/ wait 0.1 secs\n hangup();\n writeline(gpppdata.modemInitStr());\n usleep(100000);\n }\n\n statusbar->setText(i18n(\"Modem Ready\"));\n terminal->setFocus();\n\n kapp->processEvents();\n kapp->processEvents();\n readtimer->start(1);\n }\n else {\/\/ commmented out since this will now be set by the opentty() better.\n \/\/ statusbar->setText(\"Can't open modem device\");\n unlockdevice();\n }\n} \n\n\n\nvoid MiniTerm::readtty() {\n\n char c;\n\n if(read(modemfd, &c, 1) == 1) {\n c = ((int)c & 0x7F);\n \/\/ printf(\"read:%x %c\\n\",c,c);\n \n \/\/ TODO sort this shit out\n\n if(((int)c != 13)&& ((int)c != 10)&&((int)c != 8))\n terminal->insertChar( c );\n\n if((int)c == 8)\n terminal->backspace();\n if((int)c == 127)\n terminal->backspace();\n\n if((int)c == 10)\n terminal->mynewline();\n\n if((int)c == 13)\n terminal->myreturn();\n }\n \n}\n\n\nvoid MiniTerm::cancelbutton() {\n\n\n readtimer->stop();\n statusbar->setText(i18n(\"Hanging up ...\"));\n kapp->processEvents();\n kapp->flushX();\n\n if(modemfd >= 0) {\n writeline(gpppdata.modemHangupStr());\n usleep(100000); \/\/ 0.1 sec\n hangup();\n }\n\n closetty();\n unlockdevice();\n\n reject();\n}\n\n\n\nvoid MiniTerm::resetModem(){\n \n statusbar->setText(i18n(\"Resetting Modem\"));\n terminal->newLine();\n kapp->processEvents();\n kapp->flushX();\n\n if(modemfd >= 0) {\n writeline(gpppdata.modemHangupStr());\n usleep(100000); \/\/ 0.1 sec\n hangup();\n }\n statusbar->setText(i18n(\"Modem Ready\"));\n}\n\n\nbool MiniTerm::closetty(){\n\n if(modemfd > 0)\n\n \/* discard data not read or transmitted *\/\n tcflush(modemfd, TCIOFLUSH);\n\n if(tcsetattr(modemfd, TCSANOW, &initial_tty) < 0){\n statusbar->setText(i18n(\"Can't restore tty settings: tcsetattr()\\n\"));\n }\n\n ::close(modemfd);\n modemfd = -1;\n return TRUE;\n}\n\n\nbool MiniTerm::opentty() {\n\n memset(&initial_tty,'\\0',sizeof(initial_tty)); \n \n if((modemfd = open(gpppdata.modemDevice(), O_RDWR|O_NDELAY)) < 0){\n\n statusbar->setText(i18n(\"Can't open Modem\"));\n return FALSE;\n }\n \n if(tcgetattr(modemfd, &tty) < 0){\n\n statusbar->setText(i18n(\"tcgetattr() failed\\n\"));\n return FALSE;\n }\n\n initial_tty = tty; \/\/ save a copy\n\n tty.c_cc[VMIN] = 0; \/\/ nonblocking \n tty.c_cc[VTIME] = 0;\n tty.c_oflag = 0;\n tty.c_lflag = 0;\n\n \/\/ clearing CLOCAL as below ensures we observe the modem status lines\n \/\/ tty.c_cflag &= ~(CSIZE | CSTOPB | PARENB | CLOCAL); \n \n \n tty.c_cflag &= ~(CSIZE | CSTOPB | PARENB);\n tty.c_cflag |= CLOCAL ; \/\/ignore modem satus lines\n tty.c_oflag &= ~OPOST; \/\/no outline processing -- transparent output\n \n tty.c_cflag |= CS8 | CREAD; \n tty.c_iflag = IGNBRK | IGNPAR | ISTRIP; \/\/ added ISTRIP\n tty.c_lflag &= ~ICANON; \t\t\t\/\/ non-canonical mode\n tty.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHOKE);\n\n \n if(strcmp(gpppdata.flowcontrol(), \"None\") != 0) {\n if(strcmp(gpppdata.flowcontrol(), \"CRTSCTS\") == 0) {\n tty.c_cflag |= CRTSCTS;\n tty.c_iflag &= ~(IXON | IXOFF);\n }\n else {\n tty.c_cflag &= ~CRTSCTS;\n tty.c_iflag |= IXON | IXOFF;\n tty.c_cc[VSTOP] = 0x13; \/\/ DC3 = XOFF = ^S \n tty.c_cc[VSTART] = 0x11; \/\/ DC1 = XON = ^Q \n }\n }\n else {\n tty.c_cflag &= ~CRTSCTS;\n tty.c_iflag &= ~(IXON | IXOFF);\n }\n\n cfsetospeed(&tty, modemspeed());\n cfsetispeed(&tty, modemspeed());\n\n if(tcsetattr(modemfd, TCSANOW, &tty) < 0){\n\n statusbar->setText(i18n(\"tcsetattr() failed\\n\"));\n return FALSE;\n }\n\n return TRUE;\n}\n\t\t\n\nvoid MiniTerm::hangup() {\n\n struct termios temptty;\n\n if(modemfd >= 0) {\n\n \/\/ Properly bracketed escape code \n tcflush(modemfd,TCOFLUSH);\n \/\/ +3 because quiet time must be greater than guard time.\n usleep((gpppdata.modemEscapeGuardTime()+3)*20000);\n\n write(modemfd, gpppdata.modemEscapeStr(), strlen(gpppdata.modemEscapeStr()) ); \n\n tcflush(modemfd,TCOFLUSH);\n usleep((gpppdata.modemEscapeGuardTime()+3)*20000);\n\n \/\/ Then hangup command\n writeline(gpppdata.modemHangupStr());\n \n usleep(gpppdata.modemInitDelay() * 10000); \/\/ 0.01 - 3.0 sec \n\n tcsendbreak(modemfd, 0);\n\n tcgetattr(modemfd, &temptty);\n cfsetospeed(&temptty, B0);\n cfsetispeed(&temptty, B0);\n tcsetattr(modemfd, TCSAFLUSH, &temptty);\n\n usleep(gpppdata.modemInitDelay() * 10000); \/\/ 0.01 - 3.0 secs \n\n cfsetospeed(&temptty, modemspeed());\n cfsetispeed(&temptty, modemspeed());\n tcsetattr(modemfd, TCSAFLUSH, &temptty);\n \n }\n\n\n}\n\n\nbool MiniTerm::writeChar(char c){\n\n write(modemfd,&c,1);\n return true;\n\n}\n\nbool MiniTerm::writeline(const char *buf) {\n\n\n write(modemfd, buf, strlen(buf));\n\n if(strcmp(gpppdata.enter(), \"CR\/LF\") == 0)\n write(modemfd, \"\\r\\n\", 2);\n \n if(strcmp(gpppdata.enter(), \"LF\") == 0)\n write(modemfd, \"\\n\", 1);\n \n if(strcmp(gpppdata.enter(), \"CR\") == 0)\n write(modemfd, \"\\r\", 1);\n\n return true;\n}\n\n\n\nvoid MiniTerm::closeEvent( QCloseEvent *e ){\n\n e->ignore(); \/\/ don't let the user close the window\n\n}\n\nvoid MiniTerm::help(){\n\n kapp->invokeHTMLHelp(\"kppp\/kppp.html\",\"\");\n\n}\n\n\nMyTerm::MyTerm(QWidget *parent, const char* name)\n : QMultiLineEdit(parent, name)\n{\n p_parent = (MiniTerm*)parent;\n this->setFont(QFont(\"courier\",12,QFont::Normal));\n \n}\n\nvoid MyTerm::keyPressEvent(QKeyEvent *k) {\n\n\n if(k->ascii() == 13){\n myreturn();\n p_parent->writeChar((char) k->ascii());\n return;\n }\n\n\n p_parent->writeChar((char) k->ascii());\n\n}\n\nvoid MyTerm::insertChar(char c) {\n \n QMultiLineEdit::insertChar(c);\n\n}\n\nvoid MyTerm::newLine() {\n \n QMultiLineEdit::newLine();\n\n}\n\nvoid MyTerm::del() {\n \n QMultiLineEdit::del();\n\n}\n\nvoid MyTerm::backspace() {\n \n \/\/ QMultiLineEdit::cursorLeft();\n QMultiLineEdit::backspace();\n\n}\n\nvoid MyTerm::myreturn() {\n \n int column;\n int line;\n\n getCursorPosition(&line,&column);\n for (int i = 0; i < column;i++)\n QMultiLineEdit::cursorLeft();\n\n}\n\nvoid MyTerm::mynewline() {\n \n\n QMultiLineEdit::end(FALSE);\n QMultiLineEdit::newLine();\n\n}\n\n#include \"miniterm.moc\"\n<|endoftext|>"} {"text":"#include \"problem_definition.h\"\n\n#include \n#include \n#include \n\n#include \n\ndealii::ParameterHandler bparams::GlobPrm;\n\nnamespace bparams {\nvoid DeclareParameters (dealii::ParameterHandler &local_prm) {\n \/\/ our final strategy is to declare all possible entries\n \/\/ and then ignore some of them suggested by Wolfgang Bangerth\n \/\/ from Colorado State on 05-10-2017\n \/\/ The following are the basic parameters we need to define a problem\n {\n local_prm.declare_entry (\"problem dimension\", \"2\", \n dealii::Patterns::Integer(), \"\");\n local_prm.declare_entry (\"transport model\", \"none\", \n dealii::Patterns::Selection(\"ep|none\"), \n \"valid names such as ep\");\n local_prm.declare_entry (\"ho linear solver name\", \"cg\", \n dealii::Patterns::Selection(\"cg|gmres|bicgstab|direct\"), \n \"solers\");\n local_prm.declare_entry (\"ho preconditioner name\", \"amg\", \n dealii::Patterns::Selection(\"amg|parasails|bjacobi|jacobi|bssor\"), \n \"precond names\");\n local_prm.declare_entry (\"ho ssor factor\", \"1.0\", \n dealii::Patterns::Double (), \n \"damping factor of Block SSOR for HO\");\n local_prm.declare_entry (\"nda linear solver name\", \"none\", \n dealii::Patterns::Selection(\"none|gmres|bicgstab|direct\"), \n \"NDA linear solers\");\n local_prm.declare_entry (\"nda preconditioner name\", \"jacobi\", \n dealii::Patterns::Selection(\"amg|parasails|bjacobi|jacobi|bssor\"), \n \"precond names\");\n local_prm.declare_entry (\"nda ssor factor\", \"1.0\", \n dealii::Patterns::Double (), \n \"damping factor of Block SSOR for NDA\");\n local_prm.declare_entry (\"angular quadrature name\", \"none\", \n dealii::Patterns::Selection (\"lsgc|gl|none\"), \n \"angular quadrature types. only LS-GC for multi-D and GL for 1D implemented for now.\");\n local_prm.declare_entry (\"angular quadrature order\", \"4\", \n dealii::Patterns::Integer (), \n \"Gauss-Chebyshev level-symmetric-like quadrature\");\n local_prm.declare_entry (\"number of groups\", \"1\", \n dealii::Patterns::Integer (), \"Number of groups in MG calculations\");\n local_prm.declare_entry (\"thermal group boundary\", \"0\", \n dealii::Patterns::Integer (), \n \"group number for the first thermal group\");\n local_prm.declare_entry (\"ho spatial discretization\", \"cfem\", \n dealii::Patterns::Selection(\"dfem|cfem\"), \n \"HO equation spatial discretization\");\n local_prm.declare_entry (\"nda spatial discretization\", \"cfem\", \n dealii::Patterns::Selection(\"dfem|cfem|cmfd|rtk\"), \n \"NDA equation spatial discretization\");\n local_prm.declare_entry (\"do eigenvalue calculations\", \"false\", \n dealii::Patterns::Bool(), \n \"Boolean to determine problem type\");\n local_prm.declare_entry (\"do nda\", \"false\", \n dealii::Patterns::Bool(), \n \"Boolean to determine NDA or not\");\n local_prm.declare_entry (\"have reflective BC\", \"false\", \n dealii::Patterns::Bool(), \"\");\n local_prm.declare_entry (\"reflective boundary names\", \"\", \n dealii::Patterns::List (dealii::Patterns::Anything ()), \n \"must be lower cases of xmin,xmax,ymin,ymax,zmin,zmax\");\n local_prm.declare_entry (\"finite element polynomial degree\", \"1\", \n dealii::Patterns::Integer(), \n \"polynomial degree p for finite element\");\n local_prm.declare_entry (\"uniform refinements\", \"0\", \n dealii::Patterns::Integer(), \n \"number of uniform refinements desired\");\n local_prm.declare_entry (\"fuel rod radius\", \"0.5\",\n dealii::Patterns::Double(),\n \"radius of fuel rod\");\n local_prm.declare_entry (\"fuel rod triangulation type\", \"simple\",\n dealii::Patterns::Selection(\"simple|composite\"),\n \"triangulation type of fuel rod\");\n local_prm.declare_entry (\"x, y, z max values of boundary locations\", \"\", \n dealii::Patterns::List (dealii::Patterns::Double ()), \n \"xmax, ymax, zmax of the boundaries, mins are zero\");\n local_prm.declare_entry (\"number of cells for x, y, z directions\", \"\", \n dealii::Patterns::List (dealii::Patterns::Integer ()), \n \"Geometry is hyper rectangle defined by how many cells exist per direction\");\n local_prm.declare_entry (\"number of materials\", \"1\", \n dealii::Patterns::Integer (), \n \"must be a positive integer\");\n local_prm.declare_entry (\"do print angular quadrature info\", \"true\", \n dealii::Patterns::Bool(), \n \"Boolean to determine if printing angular quadrature information\");\n local_prm.declare_entry (\"is mesh generated by deal.II\", \"true\",\n dealii::Patterns::Bool(),\n \"Boolean to determine if generating mesh in dealii or read in mesh\");\n local_prm.declare_entry (\"is mesh pin-resolved\", \"false\", \n dealii::Patterns::Bool(), \n \"Boolean to determine if producing pin-resolved mesh\");\n local_prm.declare_entry (\"output file name base\", \"solu\", \n dealii::Patterns::Anything(), \n \"name base of the output file\");\n local_prm.declare_entry (\"mesh file name\", \"mesh.msh\", \n dealii::Patterns::Anything(), \n \".msh file name for read-in mesh\");\n }\n\n \/\/ Explanation: we brute-forcely declare as many entries as possible without read-in problem-definition\n \/\/ parameters. kNMat and ngrp should both be large enough s.t. when reading starts, the real setting will\n \/\/ have entry-declaration\n local_prm.enter_subsection (\"material ID map\");\n {\n local_prm.declare_entry (\"material id file name\", \"mid.txt\", \n dealii::Patterns::FileName(), \n \"file name for material id map\");\n local_prm.declare_entry (\"fuel pin material id file name\", \"pin_id.txt\",\n dealii::Patterns::FileName(),\n \"file name for pin material id map for pin-resolved calculations\");\n }\n local_prm.leave_subsection ();\n\n local_prm.enter_subsection (\"sigma_t, group=1 to G\");\n {\n for (int m=0; mchange entry names in problem definition#include \"problem_definition.h\"\n\n#include \n#include \n#include \n\n#include \n\ndealii::ParameterHandler bparams::GlobPrm;\n\nnamespace bparams {\nvoid DeclareParameters (dealii::ParameterHandler &local_prm) {\n \/\/ our final strategy is to declare all possible entries\n \/\/ and then ignore some of them suggested by Wolfgang Bangerth\n \/\/ from Colorado State on 05-10-2017\n \/\/ The following are the basic parameters we need to define a problem\n {\n local_prm.declare_entry (\"problem dimension\", \"2\",\n dealii::Patterns::Integer(), \"\");\n local_prm.declare_entry (\"transport model\", \"none\",\n dealii::Patterns::Selection(\"ep|none\"),\n \"valid names such as ep\");\n local_prm.declare_entry (\"ho linear solver name\", \"cg\",\n dealii::Patterns::Selection(\"cg|gmres|bicgstab|direct\"),\n \"solers\");\n local_prm.declare_entry (\"ho preconditioner name\", \"amg\",\n dealii::Patterns::Selection(\"amg|parasails|bjacobi|jacobi|bssor\"),\n \"precond names\");\n local_prm.declare_entry (\"ho ssor factor\", \"1.0\",\n dealii::Patterns::Double (),\n \"damping factor of Block SSOR for HO\");\n local_prm.declare_entry (\"eigen solver name\", \"pi\",\n dealii::Patterns::Selection(\"pi\"), \"\");\n local_prm.declare_entry (\"mg solver name\", \"gs\",\n dealii::Patterns::Selection(\"gs\"), \"\");\n local_prm.declare_entry (\"in group solver name\", \"si\",\n dealii::Patterns::Selection(\"si\"), \"\");\n local_prm.declare_entry (\"nda linear solver name\", \"none\",\n dealii::Patterns::Selection(\"none|gmres|bicgstab|direct\"),\n \"NDA linear solers\");\n local_prm.declare_entry (\"nda preconditioner name\", \"jacobi\",\n dealii::Patterns::Selection(\"amg|parasails|bjacobi|jacobi|bssor\"),\n \"precond names\");\n local_prm.declare_entry (\"nda ssor factor\", \"1.0\",\n dealii::Patterns::Double (),\n \"damping factor of Block SSOR for NDA\");\n local_prm.declare_entry (\"angular quadrature name\", \"none\",\n dealii::Patterns::Selection (\"lsgc|gl|none\"),\n \"angular quadrature types. only LS-GC for multi-D and GL for 1D implemented for now.\");\n local_prm.declare_entry (\"angular quadrature order\", \"4\",\n dealii::Patterns::Integer (),\n \"Gauss-Chebyshev level-symmetric-like quadrature\");\n local_prm.declare_entry (\"number of groups\", \"1\",\n dealii::Patterns::Integer (), \"Number of groups in MG calculations\");\n local_prm.declare_entry (\"thermal group boundary\", \"0\",\n dealii::Patterns::Integer (),\n \"group number for the first thermal group\");\n local_prm.declare_entry (\"ho spatial discretization\", \"cfem\",\n dealii::Patterns::Selection(\"dfem|cfem\"),\n \"HO equation spatial discretization\");\n local_prm.declare_entry (\"nda spatial discretization\", \"cfem\",\n dealii::Patterns::Selection(\"dfem|cfem|cmfd|rtk\"),\n \"NDA equation spatial discretization\");\n local_prm.declare_entry (\"do eigenvalue calculations\", \"false\",\n dealii::Patterns::Bool(),\n \"Boolean to determine problem type\");\n local_prm.declare_entry (\"do nda\", \"false\",\n dealii::Patterns::Bool(),\n \"Boolean to determine NDA or not\");\n local_prm.declare_entry (\"have reflective boundary\", \"false\",\n dealii::Patterns::Bool(), \"\");\n local_prm.declare_entry (\"reflective boundary names\", \"\",\n dealii::Patterns::List (dealii::Patterns::Anything ()),\n \"must be lower cases of xmin,xmax,ymin,ymax,zmin,zmax\");\n local_prm.declare_entry (\"finite element polynomial degree\", \"1\",\n dealii::Patterns::Integer(),\n \"polynomial degree p for finite element\");\n local_prm.declare_entry (\"uniform refinements\", \"0\",\n dealii::Patterns::Integer(),\n \"number of uniform refinements desired\");\n local_prm.declare_entry (\"fuel rod radius\", \"0.5\",\n dealii::Patterns::Double(),\n \"radius of fuel rod\");\n local_prm.declare_entry (\"fuel rod triangulation type\", \"simple\",\n dealii::Patterns::Selection(\"simple|composite\"),\n \"triangulation type of fuel rod\");\n local_prm.declare_entry (\"x, y, z max values of boundary locations\", \"\",\n dealii::Patterns::List (dealii::Patterns::Double ()),\n \"xmax, ymax, zmax of the boundaries, mins are zero\");\n local_prm.declare_entry (\"number of cells for x, y, z directions\", \"\",\n dealii::Patterns::List (dealii::Patterns::Integer ()),\n \"Geometry is hyper rectangle defined by how many cells exist per direction\");\n local_prm.declare_entry (\"number of materials\", \"1\",\n dealii::Patterns::Integer (),\n \"must be a positive integer\");\n local_prm.declare_entry (\"do print angular quadrature info\", \"true\",\n dealii::Patterns::Bool(),\n \"Boolean to determine if printing angular quadrature information\");\n local_prm.declare_entry (\"is mesh generated by deal.II\", \"true\",\n dealii::Patterns::Bool(),\n \"Boolean to determine if generating mesh in dealii or read in mesh\");\n local_prm.declare_entry (\"is mesh pin-resolved\", \"false\",\n dealii::Patterns::Bool(),\n \"Boolean to determine if producing pin-resolved mesh\");\n local_prm.declare_entry (\"output file name base\", \"solu\",\n dealii::Patterns::Anything(),\n \"name base of the output file\");\n local_prm.declare_entry (\"mesh file name\", \"mesh.msh\",\n dealii::Patterns::Anything(),\n \".msh file name for read-in mesh\");\n }\n\n \/\/ Explanation: we brute-forcely declare as many entries as possible without read-in problem-definition\n \/\/ parameters. kNMat and ngrp should both be large enough s.t. when reading starts, the real setting will\n \/\/ have entry-declaration\n local_prm.enter_subsection (\"material ID map\");\n {\n local_prm.declare_entry (\"material id file name\", \"mid.txt\",\n dealii::Patterns::FileName(),\n \"file name for material id map\");\n local_prm.declare_entry (\"fuel pin material id file name\", \"pin_id.txt\",\n dealii::Patterns::FileName(),\n \"file name for pin material id map for pin-resolved calculations\");\n }\n local_prm.leave_subsection ();\n\n local_prm.enter_subsection (\"sigma_t, group=1 to G\");\n {\n for (int m=0; m"} {"text":"#include \n#include \n#include \n#include \"froniussolar_api.h\"\n#include \"fronius_device_info.h\"\n#include \"settings.h\"\n#include \"solar_api_detector.h\"\n#include \"sunspec_detector.h\"\n\nQList SolarApiDetector::mInvalidDevices;\n\nSolarApiDetector::SolarApiDetector(const Settings *settings, QObject *parent):\n\tAbstractDetector(parent),\n\tmSunspecDetector(new SunspecDetector(this)),\n\tmSettings(settings)\n{\n}\n\nDetectorReply *SolarApiDetector::start(const QString &hostName)\n{\n\tReply *reply = new Reply(this);\n\treply->api = new FroniusSolarApi(hostName, mSettings->portNumber(), reply);\n\tmApiToReply[reply->api] = reply;\n\tconnect(reply->api, SIGNAL(converterInfoFound(InverterListData)),\n\t\tthis, SLOT(onConverterInfoFound(InverterListData)));\n\treply->api->getConverterInfoAsync();\n\treturn reply;\n}\n\nvoid SolarApiDetector::onConverterInfoFound(const InverterListData &data)\n{\n\tFroniusSolarApi *api = static_cast(sender());\n\tReply *reply = mApiToReply.value(api);\n\tbool setFinished = true;\n\tfor (QList::const_iterator it = data.inverters.begin();\n\t\t it != data.inverters.end();\n\t\t ++it) {\n\t\t\/\/ Sometimes (during startup?) PV inverters will send 255 as device\n\t\t\/\/ type instead of the real type. We have only seen this in a test\n\t\t\/\/ setup with a Fronius IG Plus 50 V-1.\n\t\tif (it->deviceType == 255) {\n\t\t\tif (!mInvalidDevices.contains(it->uniqueId)) {\n\t\t\t\tmInvalidDevices.append(it->uniqueId);\n\t\t\t\tQLOG_WARN() << \"PV inverter reported type 255. Serial:\" << it->uniqueId;\n\t\t\t}\n\t\t} else {\n\t\t\tReplyToInverter device;\n\t\t\tdevice.reply = reply;\n\t\t\tdevice.inverter = *it;\n\n\t\t\tmSunspecDetector->setUnitId(it->id);\n\t\t\tDetectorReply *dr = mSunspecDetector->start(api->hostName());\n\t\t\tconnect(dr, SIGNAL(deviceFound(DeviceInfo)),\n\t\t\t\t\tthis, SLOT(onSunspecDeviceFound(DeviceInfo)));\n\t\t\tconnect(dr, SIGNAL(finished()), this, SLOT(onSunspecDone()));\n\t\t\tmDetectorReplyToInverter[dr] = device;\n\t\t\tsetFinished = false;\n\t\t}\n\t}\n\tif (setFinished)\n\t\treply->setFinished();\n}\n\nvoid SolarApiDetector::onSunspecDeviceFound(const DeviceInfo &info)\n{\n\tDetectorReply *dr = static_cast(sender());\n\tReplyToInverter &device = mDetectorReplyToInverter[dr];\n\tQ_ASSERT(device.reply != 0);\n\tif (device.reply == 0)\n\t\treturn;\n\tDeviceInfo i2(info);\n\t\/\/ unique ID is used to find inverter settings, and to determine the device instance. In\n\t\/\/ previous versions, the unique ID constructed from data retrieved using the solar API.\n\t\/\/ The sunspec detector uses the serial number of the inverter as unique ID, which is not\n\t\/\/ available in the solar API.\n\ti2.uniqueId = fixUniqueId(device.inverter);\n\n\t\/\/ Fronius inverters have a deviceType that is exposed on solarAPI but not\n\t\/\/ via sunspec. Transplant it here. If this is not a Fronius inverter\n\t\/\/ this value will simply be a zero.\n\ti2.deviceType = device.inverter.deviceType;\n\n\tdevice.deviceFound = true;\n\tdevice.reply->setResult(i2);\n}\n\nvoid SolarApiDetector::onSunspecDone()\n{\n\tDetectorReply *dr = static_cast(sender());\n\tdr->deleteLater();\n\tReplyToInverter device = mDetectorReplyToInverter.take(dr);\n\tQ_ASSERT(device.reply != 0);\n\tif (device.reply == 0)\n\t\treturn;\n\tif (device.deviceFound) {\n\t\tcheckFinished(device.reply);\n\t\treturn;\n\t}\n\t\/\/ Sunspec was not enabled for this inverter, so we fall back to solar api.\n\tDeviceInfo info;\n\tinfo.networkId = device.inverter.id;\n\tinfo.uniqueId = fixUniqueId(device.inverter);\n\tinfo.hostName = device.reply->api->hostName();\n\tinfo.port = device.reply->api->port();\n\tinfo.deviceType = device.inverter.deviceType;\n\tinfo.productId = VE_PROD_ID_PV_INVERTER_FRONIUS;\n\tinfo.maxPower = qQNaN();\n\tconst FroniusDeviceInfo *deviceInfo = FroniusDeviceInfo::find(device.inverter.deviceType);\n\tif (deviceInfo == 0) {\n\t\tQLOG_WARN() << \"Unknown inverter type:\" << device.inverter.deviceType;\n\t\tinfo.productName = \"Unknown PV Inverter\";\n\t\tinfo.phaseCount = 1;\n\t} else {\n\t\tinfo.productName = deviceInfo->name;\n\t\tinfo.phaseCount = deviceInfo->phaseCount;\n\t}\n\tdevice.deviceFound = true;\n\tdevice.reply->setResult(info);\n\tcheckFinished(device.reply);\n}\n\nQString SolarApiDetector::fixUniqueId(const InverterInfo &inverterInfo)\n{\n\tbool isOk = false;\n\tQString result;\n\tforeach (QChar c, inverterInfo.uniqueId) {\n\t\tc = c.toAscii();\n\t\tif (!c.isLetterOrNumber()) {\n\t\t\tc = '_';\n\t\t} else {\n\t\t\tisOk = true;\n\t\t}\n\t\tresult += c;\n\t}\n\tif (!isOk)\n\t\tresult = QString(\"T%1\").arg(inverterInfo.id);\n\treturn QString(\"%1_%2\").arg(inverterInfo.deviceType).arg(result);\n}\n\nvoid SolarApiDetector::checkFinished(Reply *reply)\n{\n\t\/\/ Check if there are any pending replies from the sunspec detector associated `reply`.\n\t\/\/ We need this because a single call to getConverterInfoAsync in the solar API may give us\n\t\/\/ multiple PV inverters. Each PV inverter is tested for ModbusTCP support. Only after the last\n\t\/\/ test has been completed the request, which initiated the call to getConverterInfoAsync can\n\t\/\/ be finished.\n\tforeach (const ReplyToInverter &rti, mDetectorReplyToInverter) {\n\t\tif (rti.reply == reply && !rti.deviceFound)\n\t\t\treturn;\n\t}\n\treply->setFinished();\n}\n\nSolarApiDetector::Reply::Reply(QObject *parent):\n\tDetectorReply(parent),\n\tapi(0)\n{\n}\n\nSolarApiDetector::Reply::~Reply()\n{\n}\nqt5: use QChar.toLatin1 ito toAscii.#include \n#include \n#include \n#include \"froniussolar_api.h\"\n#include \"fronius_device_info.h\"\n#include \"settings.h\"\n#include \"solar_api_detector.h\"\n#include \"sunspec_detector.h\"\n\nQList SolarApiDetector::mInvalidDevices;\n\nSolarApiDetector::SolarApiDetector(const Settings *settings, QObject *parent):\n\tAbstractDetector(parent),\n\tmSunspecDetector(new SunspecDetector(this)),\n\tmSettings(settings)\n{\n}\n\nDetectorReply *SolarApiDetector::start(const QString &hostName)\n{\n\tReply *reply = new Reply(this);\n\treply->api = new FroniusSolarApi(hostName, mSettings->portNumber(), reply);\n\tmApiToReply[reply->api] = reply;\n\tconnect(reply->api, SIGNAL(converterInfoFound(InverterListData)),\n\t\tthis, SLOT(onConverterInfoFound(InverterListData)));\n\treply->api->getConverterInfoAsync();\n\treturn reply;\n}\n\nvoid SolarApiDetector::onConverterInfoFound(const InverterListData &data)\n{\n\tFroniusSolarApi *api = static_cast(sender());\n\tReply *reply = mApiToReply.value(api);\n\tbool setFinished = true;\n\tfor (QList::const_iterator it = data.inverters.begin();\n\t\t it != data.inverters.end();\n\t\t ++it) {\n\t\t\/\/ Sometimes (during startup?) PV inverters will send 255 as device\n\t\t\/\/ type instead of the real type. We have only seen this in a test\n\t\t\/\/ setup with a Fronius IG Plus 50 V-1.\n\t\tif (it->deviceType == 255) {\n\t\t\tif (!mInvalidDevices.contains(it->uniqueId)) {\n\t\t\t\tmInvalidDevices.append(it->uniqueId);\n\t\t\t\tQLOG_WARN() << \"PV inverter reported type 255. Serial:\" << it->uniqueId;\n\t\t\t}\n\t\t} else {\n\t\t\tReplyToInverter device;\n\t\t\tdevice.reply = reply;\n\t\t\tdevice.inverter = *it;\n\n\t\t\tmSunspecDetector->setUnitId(it->id);\n\t\t\tDetectorReply *dr = mSunspecDetector->start(api->hostName());\n\t\t\tconnect(dr, SIGNAL(deviceFound(DeviceInfo)),\n\t\t\t\t\tthis, SLOT(onSunspecDeviceFound(DeviceInfo)));\n\t\t\tconnect(dr, SIGNAL(finished()), this, SLOT(onSunspecDone()));\n\t\t\tmDetectorReplyToInverter[dr] = device;\n\t\t\tsetFinished = false;\n\t\t}\n\t}\n\tif (setFinished)\n\t\treply->setFinished();\n}\n\nvoid SolarApiDetector::onSunspecDeviceFound(const DeviceInfo &info)\n{\n\tDetectorReply *dr = static_cast(sender());\n\tReplyToInverter &device = mDetectorReplyToInverter[dr];\n\tQ_ASSERT(device.reply != 0);\n\tif (device.reply == 0)\n\t\treturn;\n\tDeviceInfo i2(info);\n\t\/\/ unique ID is used to find inverter settings, and to determine the device instance. In\n\t\/\/ previous versions, the unique ID constructed from data retrieved using the solar API.\n\t\/\/ The sunspec detector uses the serial number of the inverter as unique ID, which is not\n\t\/\/ available in the solar API.\n\ti2.uniqueId = fixUniqueId(device.inverter);\n\n\t\/\/ Fronius inverters have a deviceType that is exposed on solarAPI but not\n\t\/\/ via sunspec. Transplant it here. If this is not a Fronius inverter\n\t\/\/ this value will simply be a zero.\n\ti2.deviceType = device.inverter.deviceType;\n\n\tdevice.deviceFound = true;\n\tdevice.reply->setResult(i2);\n}\n\nvoid SolarApiDetector::onSunspecDone()\n{\n\tDetectorReply *dr = static_cast(sender());\n\tdr->deleteLater();\n\tReplyToInverter device = mDetectorReplyToInverter.take(dr);\n\tQ_ASSERT(device.reply != 0);\n\tif (device.reply == 0)\n\t\treturn;\n\tif (device.deviceFound) {\n\t\tcheckFinished(device.reply);\n\t\treturn;\n\t}\n\t\/\/ Sunspec was not enabled for this inverter, so we fall back to solar api.\n\tDeviceInfo info;\n\tinfo.networkId = device.inverter.id;\n\tinfo.uniqueId = fixUniqueId(device.inverter);\n\tinfo.hostName = device.reply->api->hostName();\n\tinfo.port = device.reply->api->port();\n\tinfo.deviceType = device.inverter.deviceType;\n\tinfo.productId = VE_PROD_ID_PV_INVERTER_FRONIUS;\n\tinfo.maxPower = qQNaN();\n\tconst FroniusDeviceInfo *deviceInfo = FroniusDeviceInfo::find(device.inverter.deviceType);\n\tif (deviceInfo == 0) {\n\t\tQLOG_WARN() << \"Unknown inverter type:\" << device.inverter.deviceType;\n\t\tinfo.productName = \"Unknown PV Inverter\";\n\t\tinfo.phaseCount = 1;\n\t} else {\n\t\tinfo.productName = deviceInfo->name;\n\t\tinfo.phaseCount = deviceInfo->phaseCount;\n\t}\n\tdevice.deviceFound = true;\n\tdevice.reply->setResult(info);\n\tcheckFinished(device.reply);\n}\n\nQString SolarApiDetector::fixUniqueId(const InverterInfo &inverterInfo)\n{\n\tbool isOk = false;\n\tQString result;\n\tforeach (QChar c, inverterInfo.uniqueId) {\n\t\tc = c.toLatin1();\n\t\tif (!c.isLetterOrNumber()) {\n\t\t\tc = '_';\n\t\t} else {\n\t\t\tisOk = true;\n\t\t}\n\t\tresult += c;\n\t}\n\tif (!isOk)\n\t\tresult = QString(\"T%1\").arg(inverterInfo.id);\n\treturn QString(\"%1_%2\").arg(inverterInfo.deviceType).arg(result);\n}\n\nvoid SolarApiDetector::checkFinished(Reply *reply)\n{\n\t\/\/ Check if there are any pending replies from the sunspec detector associated `reply`.\n\t\/\/ We need this because a single call to getConverterInfoAsync in the solar API may give us\n\t\/\/ multiple PV inverters. Each PV inverter is tested for ModbusTCP support. Only after the last\n\t\/\/ test has been completed the request, which initiated the call to getConverterInfoAsync can\n\t\/\/ be finished.\n\tforeach (const ReplyToInverter &rti, mDetectorReplyToInverter) {\n\t\tif (rti.reply == reply && !rti.deviceFound)\n\t\t\treturn;\n\t}\n\treply->setFinished();\n}\n\nSolarApiDetector::Reply::Reply(QObject *parent):\n\tDetectorReply(parent),\n\tapi(0)\n{\n}\n\nSolarApiDetector::Reply::~Reply()\n{\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tabsthdl.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2006-10-12 14:51:06 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_xmloff.hxx\"\n\n#ifndef _XMLOFF_PROPERTYHANDLER_TABSTOPTYPES_HXX\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_STYLE_TABSTOP_HPP_\n#include \n#endif\n\nusing namespace ::com::sun::star;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLFontFamilyNamePropHdl\n\/\/\n\nXMLTabStopPropHdl::~XMLTabStopPropHdl()\n{\n \/\/ Nothing to do\n}\n\nbool XMLTabStopPropHdl::equals( const uno::Any& r1, const uno::Any& r2 ) const\n{\n sal_Bool bEqual = sal_False;\n\n uno::Sequence< style::TabStop> aSeq1;\n if( r1 >>= aSeq1 )\n {\n uno::Sequence< style::TabStop> aSeq2;\n if( r2 >>= aSeq2 )\n {\n if( aSeq1.getLength() == aSeq2.getLength() )\n {\n bEqual = sal_True;\n if( aSeq1.getLength() > 0 )\n {\n const style::TabStop* pTabs1 = aSeq1.getConstArray();\n const style::TabStop* pTabs2 = aSeq2.getConstArray();\n\n int i=0;\n\n do\n {\n bEqual = ( pTabs1[i].Position == pTabs2[i].Position &&\n pTabs1[i].Alignment == pTabs2[i].Alignment &&\n pTabs1[i].DecimalChar == pTabs2[i].DecimalChar &&\n pTabs1[i].FillChar == pTabs2[i].FillChar );\n i++;\n\n } while( bEqual && i < aSeq1.getLength() );\n }\n }\n }\n }\n\n return bEqual;\n}\n\nsal_Bool XMLTabStopPropHdl::importXML( const ::rtl::OUString&, ::com::sun::star::uno::Any&, const SvXMLUnitConverter& ) const\n{\n return sal_False;\n}\n\nsal_Bool XMLTabStopPropHdl::exportXML( ::rtl::OUString&, const ::com::sun::star::uno::Any&, const SvXMLUnitConverter& ) const\n{\n return sal_False;\n}\n\nINTEGRATION: CWS changefileheader (1.6.290); FILE MERGED 2008\/04\/01 16:09:58 thb 1.6.290.3: #i85898# Stripping all external header guards 2008\/04\/01 13:05:10 thb 1.6.290.2: #i85898# Stripping all external header guards 2008\/03\/31 16:28:23 rt 1.6.290.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tabsthdl.cxx,v $\n * $Revision: 1.7 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_xmloff.hxx\"\n#include \n#include \n#include \n\nusing namespace ::com::sun::star;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLFontFamilyNamePropHdl\n\/\/\n\nXMLTabStopPropHdl::~XMLTabStopPropHdl()\n{\n \/\/ Nothing to do\n}\n\nbool XMLTabStopPropHdl::equals( const uno::Any& r1, const uno::Any& r2 ) const\n{\n sal_Bool bEqual = sal_False;\n\n uno::Sequence< style::TabStop> aSeq1;\n if( r1 >>= aSeq1 )\n {\n uno::Sequence< style::TabStop> aSeq2;\n if( r2 >>= aSeq2 )\n {\n if( aSeq1.getLength() == aSeq2.getLength() )\n {\n bEqual = sal_True;\n if( aSeq1.getLength() > 0 )\n {\n const style::TabStop* pTabs1 = aSeq1.getConstArray();\n const style::TabStop* pTabs2 = aSeq2.getConstArray();\n\n int i=0;\n\n do\n {\n bEqual = ( pTabs1[i].Position == pTabs2[i].Position &&\n pTabs1[i].Alignment == pTabs2[i].Alignment &&\n pTabs1[i].DecimalChar == pTabs2[i].DecimalChar &&\n pTabs1[i].FillChar == pTabs2[i].FillChar );\n i++;\n\n } while( bEqual && i < aSeq1.getLength() );\n }\n }\n }\n }\n\n return bEqual;\n}\n\nsal_Bool XMLTabStopPropHdl::importXML( const ::rtl::OUString&, ::com::sun::star::uno::Any&, const SvXMLUnitConverter& ) const\n{\n return sal_False;\n}\n\nsal_Bool XMLTabStopPropHdl::exportXML( ::rtl::OUString&, const ::com::sun::star::uno::Any&, const SvXMLUnitConverter& ) const\n{\n return sal_False;\n}\n\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"blackhole\/attribute\/set.hpp\"\n#include \"blackhole\/config.hpp\"\n#include \"blackhole\/detail\/iterator\/join.hpp\"\n#include \"blackhole\/detail\/traits\/tuple.hpp\"\n\nnamespace blackhole {\n\nnamespace attribute {\n\nnamespace set_view {\n\ntemplate\nstruct tuple_extractor_t;\n\n} \/\/ namespace set_view\n\nclass set_view_t {\n template friend struct set_view::tuple_extractor_t;\n\npublic:\n typedef aux::iterator::join_t const_iterator;\n\n struct attached_set_t { set_t v; };\n struct internal_set_t { set_t v; };\n struct external_set_t { set_t v; };\n\nprivate:\n attached_set_t attached; \/\/ Likely empty.\n internal_set_t internal; \/\/ About level + message + pid + tid + timestamp (4-5).\n external_set_t external; \/\/ The most filled (scoped + user attributes)\n\npublic:\n set_view_t() = default;\n set_view_t(set_t attached, set_t external, set_t&& internal);\n\n bool\n empty() const BLACKHOLE_NOEXCEPT {\n return empty();\n }\n\n template\n bool\n empty() const BLACKHOLE_NOEXCEPT;\n\n template\n typename std::enable_if<\n sizeof...(Args) != 0 && sizeof...(Args) <= 3,\n bool\n >::type\n empty() const BLACKHOLE_NOEXCEPT {\n return empty() && empty();\n }\n\n \/\/! Intentionally allow to insert only to external attribute set.\n void insert(pair_t pair);\n\n template\n void insert(InputIterator first, InputIterator last);\n\n const_iterator begin() const BLACKHOLE_NOEXCEPT;\n const_iterator end() const BLACKHOLE_NOEXCEPT;\n\n boost::optional\n find(const std::string& name) const BLACKHOLE_NOEXCEPT;\n\n const attribute_t& at(const std::string& name) const;\n};\n\nnamespace set_view {\n\ntemplate<>\nstruct tuple_extractor_t {\n static\n std::tuple\n extract(const set_view_t& view) {\n return std::make_tuple(view.attached);\n }\n};\n\ntemplate<>\nstruct tuple_extractor_t {\n static\n std::tuple\n extract(const set_view_t& view) {\n return std::make_tuple(view.internal);\n }\n};\n\ntemplate<>\nstruct tuple_extractor_t {\n static\n std::tuple\n extract(const set_view_t& view) {\n return std::make_tuple(view.external);\n }\n};\n\ntemplate\nstruct tuple_extractor_t {\n static\n std::tuple\n extract(const set_view_t& view) {\n return std::tuple_cat(\n tuple_extractor_t::extract(view),\n tuple_extractor_t::extract(view)\n );\n }\n};\n\n} \/\/ namespace set_view\n\ntemplate\nstruct all_empty_t {\n static bool empty(const T& tuple) {\n return std::get(tuple).v.empty() && all_empty_t::empty(tuple);\n }\n};\n\ntemplate\nstruct all_empty_t {\n static bool empty(const T& tuple) {\n return std::get<0>(tuple).v.empty();\n }\n};\n\ntemplate\nstruct tuple_empty {\n static bool empty(const T& tuple) {\n return all_empty_t::value - 1>::empty(tuple);\n }\n};\n\ntemplate\nclass partial_view_t {\npublic:\n typedef std::tuple tuple_type;\n typedef std::integral_constant<\n typename std::tuple_size::value_type,\n std::tuple_size::value\n > tuple_size;\n\n typedef set_view_t::const_iterator const_iterator;\n\nprivate:\n typedef std::array array_type;\n typedef typename make_index_tuple::type index_tuple_type;\n\n const tuple_type tuple;\n\npublic:\n partial_view_t(const set_view_t& view) :\n tuple(set_view::tuple_extractor_t::extract(view))\n {}\n\n bool\n empty() const BLACKHOLE_NOEXCEPT {\n return empty(tuple);\n }\n\n const_iterator\n begin() const BLACKHOLE_NOEXCEPT {\n return const_iterator(to_array(tuple, index_tuple_type()));\n }\n\n const_iterator\n end() const BLACKHOLE_NOEXCEPT {\n return const_iterator(to_array(tuple, index_tuple_type()), aux::iterator::invalidate_tag);\n }\n\nprivate:\n template\n static\n inline\n array_type\n to_array(const tuple_type& tuple, index_tuple) {\n return array_type {{ &std::get(tuple).v... }};\n }\n\n static\n inline\n bool\n empty(const tuple_type& tuple) {\n return tuple_empty::empty(tuple);\n }\n};\n\nBLACKHOLE_API\nset_view_t::set_view_t(set_t attached, set_t external, set_t&& internal) :\n attached({ std::move(attached) }),\n internal({ std::move(internal) }),\n external({ std::move(external) })\n{}\n\ntemplate<>\nBLACKHOLE_API\nbool\nset_view_t::empty() const BLACKHOLE_NOEXCEPT {\n return attached.v.empty();\n}\n\ntemplate<>\nBLACKHOLE_API\nbool\nset_view_t::empty() const BLACKHOLE_NOEXCEPT {\n return internal.v.empty();\n}\n\ntemplate<>\nBLACKHOLE_API\nbool\nset_view_t::empty() const BLACKHOLE_NOEXCEPT {\n return external.v.empty();\n}\n\nBLACKHOLE_API\nvoid\nset_view_t::insert(pair_t pair) {\n external.v.insert(std::move(pair));\n}\n\ntemplate\nBLACKHOLE_API\nvoid\nset_view_t::insert(InputIterator first, InputIterator last) {\n external.v.insert(first, last);\n}\n\nBLACKHOLE_API\nset_view_t::const_iterator\nset_view_t::begin() const BLACKHOLE_NOEXCEPT {\n std::array a{{ &internal.v, &external.v, &attached.v }};\n return const_iterator(a);\n}\n\nBLACKHOLE_API\nset_view_t::const_iterator\nset_view_t::end() const BLACKHOLE_NOEXCEPT {\n std::array a{{ &internal.v, &external.v, &attached.v }};\n return const_iterator(a, aux::iterator::invalidate_tag);\n}\n\nBLACKHOLE_API\nboost::optional\nset_view_t::find(const std::string& name) const BLACKHOLE_NOEXCEPT {\n auto it = internal.v.find(name);\n if (it != internal.v.end()) {\n return it->second;\n }\n\n it = external.v.find(name);\n if (it != external.v.end()) {\n return it->second;\n }\n\n it = attached.v.find(name);\n if (it != attached.v.end()) {\n return it->second;\n }\n\n return boost::optional();\n}\n\nBLACKHOLE_API\nconst attribute_t&\nset_view_t::at(const std::string &name) const {\n auto value = find(name);\n if (!value) {\n throw std::out_of_range(name);\n }\n\n return *value;\n}\n\n} \/\/ namespace attribute\n\n} \/\/ namespace blackhole\n[Code Clean] Simplification for 'empty' method.#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"blackhole\/attribute\/set.hpp\"\n#include \"blackhole\/config.hpp\"\n#include \"blackhole\/detail\/iterator\/join.hpp\"\n#include \"blackhole\/detail\/traits\/tuple.hpp\"\n\nnamespace blackhole {\n\nnamespace attribute {\n\nnamespace set_view {\n\ntemplate\nstruct tuple_extractor_t;\n\n} \/\/ namespace set_view\n\nclass set_view_t {\n template friend struct set_view::tuple_extractor_t;\n\npublic:\n typedef aux::iterator::join_t const_iterator;\n\n struct attached_set_t { set_t v; };\n struct internal_set_t { set_t v; };\n struct external_set_t { set_t v; };\n\nprivate:\n attached_set_t attached; \/\/ Likely empty.\n internal_set_t internal; \/\/ About level + message + pid + tid + timestamp (4-5).\n external_set_t external; \/\/ The most filled (scoped + user attributes)\n\npublic:\n set_view_t() = default;\n set_view_t(set_t attached, set_t external, set_t&& internal);\n\n bool\n empty() const BLACKHOLE_NOEXCEPT {\n return internal.v.empty() && external.v.empty() && attached.v.empty();\n }\n\n \/\/! Intentionally allow to insert only to external attribute set.\n void insert(pair_t pair);\n\n template\n void insert(InputIterator first, InputIterator last);\n\n const_iterator begin() const BLACKHOLE_NOEXCEPT;\n const_iterator end() const BLACKHOLE_NOEXCEPT;\n\n boost::optional\n find(const std::string& name) const BLACKHOLE_NOEXCEPT;\n\n const attribute_t& at(const std::string& name) const;\n};\n\nnamespace set_view {\n\ntemplate<>\nstruct tuple_extractor_t {\n static\n std::tuple\n extract(const set_view_t& view) {\n return std::make_tuple(view.attached);\n }\n};\n\ntemplate<>\nstruct tuple_extractor_t {\n static\n std::tuple\n extract(const set_view_t& view) {\n return std::make_tuple(view.internal);\n }\n};\n\ntemplate<>\nstruct tuple_extractor_t {\n static\n std::tuple\n extract(const set_view_t& view) {\n return std::make_tuple(view.external);\n }\n};\n\ntemplate\nstruct tuple_extractor_t {\n static\n std::tuple\n extract(const set_view_t& view) {\n return std::tuple_cat(\n tuple_extractor_t::extract(view),\n tuple_extractor_t::extract(view)\n );\n }\n};\n\n} \/\/ namespace set_view\n\ntemplate\nstruct all_empty_t {\n static bool empty(const T& tuple) {\n return std::get(tuple).v.empty() && all_empty_t::empty(tuple);\n }\n};\n\ntemplate\nstruct all_empty_t {\n static bool empty(const T& tuple) {\n return std::get<0>(tuple).v.empty();\n }\n};\n\ntemplate\nstruct tuple_empty {\n static bool empty(const T& tuple) {\n return all_empty_t::value - 1>::empty(tuple);\n }\n};\n\ntemplate\nclass partial_view_t {\npublic:\n typedef std::tuple tuple_type;\n typedef std::integral_constant<\n typename std::tuple_size::value_type,\n std::tuple_size::value\n > tuple_size;\n\n typedef set_view_t::const_iterator const_iterator;\n\nprivate:\n typedef std::array array_type;\n typedef typename make_index_tuple::type index_tuple_type;\n\n const tuple_type tuple;\n\npublic:\n partial_view_t(const set_view_t& view) :\n tuple(set_view::tuple_extractor_t::extract(view))\n {}\n\n bool\n empty() const BLACKHOLE_NOEXCEPT {\n return empty(tuple);\n }\n\n const_iterator\n begin() const BLACKHOLE_NOEXCEPT {\n return const_iterator(to_array(tuple, index_tuple_type()));\n }\n\n const_iterator\n end() const BLACKHOLE_NOEXCEPT {\n return const_iterator(to_array(tuple, index_tuple_type()), aux::iterator::invalidate_tag);\n }\n\nprivate:\n template\n static\n inline\n array_type\n to_array(const tuple_type& tuple, index_tuple) {\n return array_type {{ &std::get(tuple).v... }};\n }\n\n static\n inline\n bool\n empty(const tuple_type& tuple) {\n return tuple_empty::empty(tuple);\n }\n};\n\nBLACKHOLE_API\nset_view_t::set_view_t(set_t attached, set_t external, set_t&& internal) :\n attached({ std::move(attached) }),\n internal({ std::move(internal) }),\n external({ std::move(external) })\n{}\n\nBLACKHOLE_API\nvoid\nset_view_t::insert(pair_t pair) {\n external.v.insert(std::move(pair));\n}\n\ntemplate\nBLACKHOLE_API\nvoid\nset_view_t::insert(InputIterator first, InputIterator last) {\n external.v.insert(first, last);\n}\n\nBLACKHOLE_API\nset_view_t::const_iterator\nset_view_t::begin() const BLACKHOLE_NOEXCEPT {\n std::array a{{ &internal.v, &external.v, &attached.v }};\n return const_iterator(a);\n}\n\nBLACKHOLE_API\nset_view_t::const_iterator\nset_view_t::end() const BLACKHOLE_NOEXCEPT {\n std::array a{{ &internal.v, &external.v, &attached.v }};\n return const_iterator(a, aux::iterator::invalidate_tag);\n}\n\nBLACKHOLE_API\nboost::optional\nset_view_t::find(const std::string& name) const BLACKHOLE_NOEXCEPT {\n auto it = internal.v.find(name);\n if (it != internal.v.end()) {\n return it->second;\n }\n\n it = external.v.find(name);\n if (it != external.v.end()) {\n return it->second;\n }\n\n it = attached.v.find(name);\n if (it != attached.v.end()) {\n return it->second;\n }\n\n return boost::optional();\n}\n\nBLACKHOLE_API\nconst attribute_t&\nset_view_t::at(const std::string &name) const {\n auto value = find(name);\n if (!value) {\n throw std::out_of_range(name);\n }\n\n return *value;\n}\n\n} \/\/ namespace attribute\n\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: weighhdl.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 15:45:49 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_xmloff.hxx\"\n\n#ifndef _XMLOFF_PROPERTYHANDLER_FONTWEIGHTTYPES_HXX\n#include \n#endif\n\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include \n#endif\n\n#ifndef _XMLOFF_XMLUCONV_HXX\n#include \n#endif\n\n#ifndef _VCL_VCLENUM_HXX\n#include \n#endif\n\n#ifndef _SOLAR_H\n#include \n#endif\n\n#ifndef _INC_LIMITS\n#include \n#endif\n\n#ifndef _RTL_USTRBUF_HXX_\n#include \n#endif\n\n#ifndef _RTL_USTRING_\n#include \n#endif\n\n#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include \n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star::uno;\nusing namespace ::xmloff::token;\n\nstruct FontWeightMapper\n{\n FontWeight eWeight;\n USHORT nValue;\n};\n\nFontWeightMapper const aFontWeightMap[] =\n{\n { WEIGHT_DONTKNOW, 0 },\n { WEIGHT_THIN, 100 },\n { WEIGHT_ULTRALIGHT, 150 },\n { WEIGHT_LIGHT, 250 },\n { WEIGHT_SEMILIGHT, 350 },\n { WEIGHT_NORMAL, 400 },\n { WEIGHT_MEDIUM, 450 },\n { WEIGHT_SEMIBOLD, 600 },\n { WEIGHT_BOLD, 700 },\n { WEIGHT_ULTRABOLD, 800 },\n { WEIGHT_BLACK, 900 },\n { (FontWeight)USHRT_MAX, 1000 }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLFmtBreakBeforePropHdl\n\/\/\n\nXMLFontWeightPropHdl::~XMLFontWeightPropHdl()\n{\n \/\/ Nothing to do\n}\n\nsal_Bool XMLFontWeightPropHdl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& ) const\n{\n sal_Bool bRet = sal_False;\n sal_uInt16 nWeight = 0;\n\n if( IsXMLToken( rStrImpValue, XML_WEIGHT_NORMAL ) )\n {\n nWeight = 400;\n bRet = sal_True;\n }\n else if( IsXMLToken( rStrImpValue, XML_WEIGHT_BOLD ) )\n {\n nWeight = 700;\n bRet = sal_True;\n }\n else\n {\n sal_Int32 nTemp;\n bRet = SvXMLUnitConverter::convertNumber( nTemp, rStrImpValue, 100, 900 );\n if( bRet )\n nWeight = sal::static_int_cast< sal_uInt16 >(nTemp);\n }\n\n if( bRet )\n {\n bRet = sal_False;\n\n for( int i = 0; aFontWeightMap[i].eWeight != USHRT_MAX; i++ )\n {\n if( (nWeight >= aFontWeightMap[i].nValue) && (nWeight <= aFontWeightMap[i+1].nValue) )\n {\n sal_uInt16 nDiff1 = nWeight - aFontWeightMap[i].nValue;\n sal_uInt16 nDiff2 = aFontWeightMap[i+1].nValue - nWeight;\n\n if( nDiff1 < nDiff2 )\n rValue <<= (float)( VCLUnoHelper::ConvertFontWeight( aFontWeightMap[i].eWeight ) );\n else\n rValue <<= (float)( VCLUnoHelper::ConvertFontWeight( aFontWeightMap[i+1].eWeight ) );\n\n bRet = sal_True;\n break;\n }\n }\n }\n\n return bRet;\n}\n\nsal_Bool XMLFontWeightPropHdl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& ) const\n{\n sal_Bool bRet = sal_False;\n FontWeight eWeight;\n\n float fValue = float();\n if( !( rValue >>= fValue ) )\n {\n sal_Int32 nValue = 0;\n if( rValue >>= nValue )\n {\n fValue = (float)nValue;\n bRet = sal_True;\n }\n }\n else\n bRet = sal_True;\n\n eWeight = VCLUnoHelper::ConvertFontWeight( fValue );\n\n if( bRet )\n {\n sal_uInt16 nWeight = 0;\n\n for( int i = 0; aFontWeightMap[i].eWeight != -1; i++ )\n {\n if( aFontWeightMap[i].eWeight == eWeight )\n {\n nWeight = aFontWeightMap[i].nValue;\n break;\n }\n }\n\n OUStringBuffer aOut;\n\n if( 400 == nWeight )\n aOut.append( GetXMLToken(XML_WEIGHT_NORMAL) );\n else if( 700 == nWeight )\n aOut.append( GetXMLToken(XML_WEIGHT_BOLD) );\n else\n SvXMLUnitConverter::convertNumber( aOut, (sal_Int32)nWeight );\n\n rStrExpValue = aOut.makeStringAndClear();\n }\n\n return bRet;\n}\n\nINTEGRATION: CWS impresstables2 (1.8.46); FILE MERGED 2007\/08\/01 14:35:13 cl 1.8.46.2: RESYNC: (1.8-1.9); FILE MERGED 2007\/07\/27 09:09:54 cl 1.8.46.1: fixed build issues due to pch and namespace ::rtl\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: weighhdl.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2008-03-12 10:54:51 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_xmloff.hxx\"\n\n#ifndef _XMLOFF_PROPERTYHANDLER_FONTWEIGHTTYPES_HXX\n#include \n#endif\n\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include \n#endif\n\n#ifndef _XMLOFF_XMLUCONV_HXX\n#include \n#endif\n\n#ifndef _VCL_VCLENUM_HXX\n#include \n#endif\n\n#ifndef _SOLAR_H\n#include \n#endif\n\n#ifndef _INC_LIMITS\n#include \n#endif\n\n#ifndef _RTL_USTRBUF_HXX_\n#include \n#endif\n\n#ifndef _RTL_USTRING_\n#include \n#endif\n\n#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include \n#endif\n\nusing ::rtl::OUString;\nusing ::rtl::OUStringBuffer;\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::xmloff::token;\n\nstruct FontWeightMapper\n{\n FontWeight eWeight;\n USHORT nValue;\n};\n\nFontWeightMapper const aFontWeightMap[] =\n{\n { WEIGHT_DONTKNOW, 0 },\n { WEIGHT_THIN, 100 },\n { WEIGHT_ULTRALIGHT, 150 },\n { WEIGHT_LIGHT, 250 },\n { WEIGHT_SEMILIGHT, 350 },\n { WEIGHT_NORMAL, 400 },\n { WEIGHT_MEDIUM, 450 },\n { WEIGHT_SEMIBOLD, 600 },\n { WEIGHT_BOLD, 700 },\n { WEIGHT_ULTRABOLD, 800 },\n { WEIGHT_BLACK, 900 },\n { (FontWeight)USHRT_MAX, 1000 }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLFmtBreakBeforePropHdl\n\/\/\n\nXMLFontWeightPropHdl::~XMLFontWeightPropHdl()\n{\n \/\/ Nothing to do\n}\n\nsal_Bool XMLFontWeightPropHdl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& ) const\n{\n sal_Bool bRet = sal_False;\n sal_uInt16 nWeight = 0;\n\n if( IsXMLToken( rStrImpValue, XML_WEIGHT_NORMAL ) )\n {\n nWeight = 400;\n bRet = sal_True;\n }\n else if( IsXMLToken( rStrImpValue, XML_WEIGHT_BOLD ) )\n {\n nWeight = 700;\n bRet = sal_True;\n }\n else\n {\n sal_Int32 nTemp;\n bRet = SvXMLUnitConverter::convertNumber( nTemp, rStrImpValue, 100, 900 );\n if( bRet )\n nWeight = sal::static_int_cast< sal_uInt16 >(nTemp);\n }\n\n if( bRet )\n {\n bRet = sal_False;\n\n for( int i = 0; aFontWeightMap[i].eWeight != USHRT_MAX; i++ )\n {\n if( (nWeight >= aFontWeightMap[i].nValue) && (nWeight <= aFontWeightMap[i+1].nValue) )\n {\n sal_uInt16 nDiff1 = nWeight - aFontWeightMap[i].nValue;\n sal_uInt16 nDiff2 = aFontWeightMap[i+1].nValue - nWeight;\n\n if( nDiff1 < nDiff2 )\n rValue <<= (float)( VCLUnoHelper::ConvertFontWeight( aFontWeightMap[i].eWeight ) );\n else\n rValue <<= (float)( VCLUnoHelper::ConvertFontWeight( aFontWeightMap[i+1].eWeight ) );\n\n bRet = sal_True;\n break;\n }\n }\n }\n\n return bRet;\n}\n\nsal_Bool XMLFontWeightPropHdl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& ) const\n{\n sal_Bool bRet = sal_False;\n FontWeight eWeight;\n\n float fValue = float();\n if( !( rValue >>= fValue ) )\n {\n sal_Int32 nValue = 0;\n if( rValue >>= nValue )\n {\n fValue = (float)nValue;\n bRet = sal_True;\n }\n }\n else\n bRet = sal_True;\n\n eWeight = VCLUnoHelper::ConvertFontWeight( fValue );\n\n if( bRet )\n {\n sal_uInt16 nWeight = 0;\n\n for( int i = 0; aFontWeightMap[i].eWeight != -1; i++ )\n {\n if( aFontWeightMap[i].eWeight == eWeight )\n {\n nWeight = aFontWeightMap[i].nValue;\n break;\n }\n }\n\n OUStringBuffer aOut;\n\n if( 400 == nWeight )\n aOut.append( GetXMLToken(XML_WEIGHT_NORMAL) );\n else if( 700 == nWeight )\n aOut.append( GetXMLToken(XML_WEIGHT_BOLD) );\n else\n SvXMLUnitConverter::convertNumber( aOut, (sal_Int32)nWeight );\n\n rStrExpValue = aOut.makeStringAndClear();\n }\n\n return bRet;\n}\n\n<|endoftext|>"} {"text":"#include \"core\/argparse.h\"\n\n#include \"core\/generator_maze.h\"\n#include \"core\/generator_cell.h\"\n\n#include \"core\/random.h\"\n#include \"core\/imageops.h\"\n\n#include \"core\/debug.h\"\n\n#include \n\n\/\/ later when doing floodfill\n\/\/ #include \"core\/colorbrewer.h\"\n\nvoid maze(int world_width, int world_height, int cell_size, int wall_size, const std::string& output, bool console)\n{\n auto random = Random {};\n auto maze = generator::Maze::FromWidthHeight(world_width, world_height);\n\n auto gen = generator::RecursiveBacktracker{};\n gen.maze = &maze;\n gen.random = &random;\n gen.Setup();\n\n auto drawer = generator::Drawer {};\n drawer.maze = &maze;\n drawer.tracker = &gen;\n drawer.cell_size = cell_size;\n drawer.wall_size = wall_size;\n\n while(gen.HasMoreWork())\n {\n gen.Work();\n }\n\n drawer.Draw();\n\n if(!console)\n {\n debug::MemoryChunkToFile(drawer.image.Write(ImageWriteFormat::PNG), output);\n }\n\n if(console)\n {\n auto table = ImageToStringTable(drawer.image,\n {\n {'#', drawer.wall_color},\n {'\/', drawer.cell_color},\n {' ', drawer.wall_color},\n {' ', drawer.cell_visited_color},\n {'O', drawer.unit_color}\n }\n );\n\n for(int r=0; rcan output to sheet now#include \"core\/argparse.h\"\n\n#include \"core\/generator_maze.h\"\n#include \"core\/generator_cell.h\"\n\n#include \"core\/random.h\"\n#include \"core\/imageops.h\"\n\n#include \"core\/stringutils.h\"\n#include \"core\/debug.h\"\n\n#include \n#include \n#include \n\n\/\/ later when doing floodfill\n\/\/ #include \"core\/colorbrewer.h\"\n\nstruct Output\n{\n explicit Output(const std::string& o)\n : file(o)\n , single(!EndsWith(o, \"\/\"))\n {\n }\n\n std::string NextFile()\n {\n std::ostringstream ss;\n index += 1;\n std::cout << \"Generating \" << index << \"...\\n\";\n ss << file << std::setfill('0') << std::setw(5) << index << \".png\";\n return ss.str();\n }\n\n std::string file;\n bool single;\n int index = 0;\n};\n\nvoid maze(int world_width, int world_height, int cell_size, int wall_size, const std::string& f, bool console)\n{\n auto output = Output{f};\n auto random = Random {};\n auto maze = generator::Maze::FromWidthHeight(world_width, world_height);\n\n auto gen = generator::RecursiveBacktracker{};\n gen.maze = &maze;\n gen.random = &random;\n gen.Setup();\n\n auto drawer = generator::Drawer {};\n drawer.maze = &maze;\n drawer.tracker = &gen;\n drawer.cell_size = cell_size;\n drawer.wall_size = wall_size;\n\n if(!output.single)\n {\n drawer.Draw();\n debug::MemoryChunkToFile(drawer.image.Write(ImageWriteFormat::PNG), output.NextFile());\n }\n\n while(gen.HasMoreWork())\n {\n gen.Work();\n\n if(!output.single)\n {\n drawer.Draw();\n debug::MemoryChunkToFile(drawer.image.Write(ImageWriteFormat::PNG), output.NextFile());\n }\n }\n\n drawer.Draw();\n\n if(!console && output.single)\n {\n debug::MemoryChunkToFile(drawer.image.Write(ImageWriteFormat::PNG), output.file);\n }\n\n if(console)\n {\n auto table = ImageToStringTable(drawer.image,\n {\n {'#', drawer.wall_color},\n {'\/', drawer.cell_color},\n {' ', drawer.wall_color},\n {' ', drawer.cell_visited_color},\n {'O', drawer.unit_color}\n }\n );\n\n for(int r=0; r"} {"text":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Copyright (C) 2015 ScyllaDB\n *\n * Modified by ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#pragma once\n\n#include \n#include \n#include \"enum_set.hh\"\n#include \"service\/pager\/paging_state.hh\"\n#include \"schema.hh\"\n\nnamespace cql3 {\n\nclass metadata {\npublic:\n enum class flag : uint8_t {\n GLOBAL_TABLES_SPEC,\n HAS_MORE_PAGES,\n NO_METADATA\n };\n\n using flag_enum = super_enum;\n\n using flag_enum_set = enum_set;\n\nprivate:\n flag_enum_set _flags;\n\npublic:\n \/\/ Please note that columnCount can actually be smaller than names, even if names is not null. This is\n \/\/ used to include columns in the resultSet that we need to do post-query re-orderings\n \/\/ (SelectStatement.orderResults) but that shouldn't be sent to the user as they haven't been requested\n \/\/ (CASSANDRA-4911). So the serialization code will exclude any columns in name whose index is >= columnCount.\n std::vector<::shared_ptr> names;\n\nprivate:\n const uint32_t _column_count;\n ::shared_ptr _paging_state;\n\npublic:\n metadata(std::vector<::shared_ptr> names_);\n\n metadata(flag_enum_set flags, std::vector<::shared_ptr> names_, uint32_t column_count,\n ::shared_ptr paging_state);\n\n \/\/ The maximum number of values that the ResultSet can hold. This can be bigger than columnCount due to CASSANDRA-4911\n uint32_t value_count();\n\n void add_non_serialized_column(::shared_ptr name);\n\nprivate:\n bool all_in_same_cf() const;\n\npublic:\n void set_has_more_pages(::shared_ptr paging_state);\n\n void set_skip_metadata();\n\n flag_enum_set flags() const;\n\n uint32_t column_count() const;\n\n ::shared_ptr paging_state() const;\n\n const std::vector<::shared_ptr>& get_names() const;\n};\n\ninline ::shared_ptr make_empty_metadata()\n{\n auto result = ::make_shared(std::vector<::shared_ptr>{});\n result->set_skip_metadata();\n return result;\n}\n\nclass prepared_metadata {\npublic:\n enum class flag : uint8_t {\n GLOBAL_TABLES_SPEC,\n };\n\n using flag_enum = super_enum;\n\n using flag_enum_set = enum_set;\nprivate:\n flag_enum_set _flags;\n std::vector<::shared_ptr> _names;\n std::vector _partition_key_bind_indices;\npublic:\n prepared_metadata(const std::vector<::shared_ptr>& names,\n const std::vector& partition_key_bind_indices);\n\n flag_enum_set flags() const;\n const std::vector<::shared_ptr> names() const;\n const std::vector partition_key_bind_indices() const;\n};\n\nclass result_set {\npublic:\n ::shared_ptr _metadata;\n std::deque> _rows;\npublic:\n result_set(std::vector<::shared_ptr> metadata_);\n\n result_set(::shared_ptr metadata);\n\n size_t size() const;\n\n bool empty() const;\n\n void add_row(std::vector row);\n\n void add_column_value(bytes_opt value);\n\n void reverse();\n\n void trim(size_t limit);\n\n template\n void sort(RowComparator&& cmp) {\n std::sort(_rows.begin(), _rows.end(), std::forward(cmp));\n }\n\n metadata& get_metadata();\n\n const metadata& get_metadata() const;\n\n \/\/ Returns a range of rows. A row is a range of bytes_opt.\n const std::deque>& rows() const;\n};\n\n}\ncql3: Specify result set flag ABI explicitly\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Copyright (C) 2015 ScyllaDB\n *\n * Modified by ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#pragma once\n\n#include \n#include \n#include \"enum_set.hh\"\n#include \"service\/pager\/paging_state.hh\"\n#include \"schema.hh\"\n\nnamespace cql3 {\n\nclass metadata {\npublic:\n enum class flag : uint8_t {\n GLOBAL_TABLES_SPEC = 0,\n HAS_MORE_PAGES = 1,\n NO_METADATA = 2,\n };\n\n using flag_enum = super_enum;\n\n using flag_enum_set = enum_set;\n\nprivate:\n flag_enum_set _flags;\n\npublic:\n \/\/ Please note that columnCount can actually be smaller than names, even if names is not null. This is\n \/\/ used to include columns in the resultSet that we need to do post-query re-orderings\n \/\/ (SelectStatement.orderResults) but that shouldn't be sent to the user as they haven't been requested\n \/\/ (CASSANDRA-4911). So the serialization code will exclude any columns in name whose index is >= columnCount.\n std::vector<::shared_ptr> names;\n\nprivate:\n const uint32_t _column_count;\n ::shared_ptr _paging_state;\n\npublic:\n metadata(std::vector<::shared_ptr> names_);\n\n metadata(flag_enum_set flags, std::vector<::shared_ptr> names_, uint32_t column_count,\n ::shared_ptr paging_state);\n\n \/\/ The maximum number of values that the ResultSet can hold. This can be bigger than columnCount due to CASSANDRA-4911\n uint32_t value_count();\n\n void add_non_serialized_column(::shared_ptr name);\n\nprivate:\n bool all_in_same_cf() const;\n\npublic:\n void set_has_more_pages(::shared_ptr paging_state);\n\n void set_skip_metadata();\n\n flag_enum_set flags() const;\n\n uint32_t column_count() const;\n\n ::shared_ptr paging_state() const;\n\n const std::vector<::shared_ptr>& get_names() const;\n};\n\ninline ::shared_ptr make_empty_metadata()\n{\n auto result = ::make_shared(std::vector<::shared_ptr>{});\n result->set_skip_metadata();\n return result;\n}\n\nclass prepared_metadata {\npublic:\n enum class flag : uint8_t {\n GLOBAL_TABLES_SPEC = 0,\n };\n\n using flag_enum = super_enum;\n\n using flag_enum_set = enum_set;\nprivate:\n flag_enum_set _flags;\n std::vector<::shared_ptr> _names;\n std::vector _partition_key_bind_indices;\npublic:\n prepared_metadata(const std::vector<::shared_ptr>& names,\n const std::vector& partition_key_bind_indices);\n\n flag_enum_set flags() const;\n const std::vector<::shared_ptr> names() const;\n const std::vector partition_key_bind_indices() const;\n};\n\nclass result_set {\npublic:\n ::shared_ptr _metadata;\n std::deque> _rows;\npublic:\n result_set(std::vector<::shared_ptr> metadata_);\n\n result_set(::shared_ptr metadata);\n\n size_t size() const;\n\n bool empty() const;\n\n void add_row(std::vector row);\n\n void add_column_value(bytes_opt value);\n\n void reverse();\n\n void trim(size_t limit);\n\n template\n void sort(RowComparator&& cmp) {\n std::sort(_rows.begin(), _rows.end(), std::forward(cmp));\n }\n\n metadata& get_metadata();\n\n const metadata& get_metadata() const;\n\n \/\/ Returns a range of rows. A row is a range of bytes_opt.\n const std::deque>& rows() const;\n};\n\n}\n<|endoftext|>"} {"text":"\/**\n\\file ll_table.hpp\n\\brief Defines class LLTable and its methods.\n\\author Radek Vít\n*\/\n#ifndef CTF_LL_TABLE_H\n#define CTF_LL_TABLE_H\n\n#include \n#include \n\n#include \"translation_grammar.hpp\"\n\nnamespace ctf {\n\/**\n\\brief Class containing rule indices to be used in a LL controlled translation.\n*\/\nclass LLTable {\n public:\n \/**\n \\brief Type of cells.\n *\/\n using cell = size_t;\n \/**\n \\brief Type of rows.\n *\/\n using row = vector;\n\n protected:\n \/**\n \\brief Table storing rule indices. 2D array mapped to 1D array.\n *\/\n row table_;\n \/**\n \\brief Mapping nonterminals to indices to table_.\n *\/\n map nonterminalMap_;\n \/**\n \\brief Mapping terminals to indices to table_ rows.\n *\/\n map terminalMap_;\n \/**\n \\brief Stores invalid rule index.\n *\/\n size_t invalidRuleIndex_;\n \/**\n \\brief Maps 2D indices to 1D indices.\n *\/\n size_t index(size_t y, size_t x) const { return terminalMap_.size() * y + x; }\n\n public:\n \/**\n \\brief Constructs an empty LL table.\n *\/\n LLTable() = default;\n \/**\n \\brief Constructs a LLtable from a translation grammar and a predict set.\n\n \\param[in] tg TranslationGrammar. Terminals and Nonterminals are mapped to\n their respective indices. Rule indices are stored in LLTable.\n \\param[in] predict Predict set for table construction.\n *\/\n LLTable(const TranslationGrammar &tg, const vector> &predict)\n : table_(tg.nonterminals().size() * (tg.terminals().size() + 1),\n tg.rules().size()),\n invalidRuleIndex_(tg.rules().size()) {\n if (predict.size() != tg.rules().size())\n throw std::invalid_argument(\n \"Mismatched predict and TranslationGrammar.rules \"\n \"sizes when constructing LLTable.\");\n\n \/\/ create index maps for terminals and nonterminals\n for (size_t i = 0; i < tg.nonterminals().size(); ++i) {\n nonterminalMap_.insert(std::make_pair(tg.nonterminals()[i], i));\n }\n for (size_t i = 0; i < tg.terminals().size(); ++i) {\n terminalMap_.insert(std::make_pair(tg.terminals()[i], i));\n }\n terminalMap_.insert(std::make_pair(Symbol::eof(), tg.terminals().size()));\n\n \/* fill table *\/\n for (size_t i = 0; i < tg.rules().size(); ++i) {\n auto &terminals = predict[i];\n \/\/ TranslationGrammar requires this to be always found\n size_t ni = nonterminalMap_.at(tg.rules()[i].nonterminal());\n\n for (auto &t : terminals) {\n auto tit = terminalMap_.find(t);\n if (tit == terminalMap_.end())\n throw std::invalid_argument(\n \"Terminal in predict not a terminal in translation grammar when \"\n \"constructing LLTable.\");\n\n size_t ti = tit->second;\n \/\/ a rule is already present\n if (table_[index(ni, ti)] != invalidRuleIndex_) {\n throw std::invalid_argument(\n \"Constructing LLTable from a non-LL TranslationGrammar.\");\n }\n table_[index(ni, terminalMap_.at(t))] = i;\n } \/\/ for all terminals\n } \/\/ for all i\n }\n \/**\n \\brief Returns an index of the rule to be used when t is the current token\n and nt is at the top of input stack.\n\n \\param[in] nt Nonterminal on the top of the stack.\n \\param[in] t Last read terminal.\n\n \\returns Index of the applicable rule or invalid rule index.\n\n If no rule is applicable, returns the index beyond the last rule.\n *\/\n size_t rule_index(const Symbol &nt, const Symbol &t) noexcept {\n \/\/ iterator to nonterminal index\n auto ntit = nonterminalMap_.find(nt);\n \/\/ iterator to terminal index;\n auto tit = terminalMap_.find(t);\n \/\/ either of the arguments not found\n if (ntit == nonterminalMap_.end() || tit == terminalMap_.end())\n return invalidRuleIndex_;\n \/\/ returning from LL table\n return table_[index(ntit->second, tit->second)];\n }\n};\n} \/\/ namespace ctf\n\n#endif\n\/*** End of file ll_table.hpp ***\/modified ll table\/**\n\\file ll_table.hpp\n\\brief Defines class LLTable and its methods.\n\\author Radek Vít\n*\/\n#ifndef CTF_LL_TABLE_H\n#define CTF_LL_TABLE_H\n\n#include \n#include \n#include \n\n#include \"translation_grammar.hpp\"\n\nnamespace ctf {\n\ntemplate \nclass DecisionTable {\n public:\n \/**\n \\brief Type of cells.\n *\/\n using cell = T;\n \/**\n \\brief Type of rows.\n *\/\n using row = vector;\n\n protected:\n \/**\n \\brief Table storing rule indices. 2D array mapped to 1D array.\n *\/\n row table_;\n \/**\n \\brief Mapping nonterminals to table_ indices.\n *\/\n map nonterminalMap_;\n \/**\n \\brief Mapping terminals to table_ row indices.\n *\/\n map terminalMap_;\n \/**\n \\brief Stores invalid value.\n *\/\n cell invalid_;\n \/**\n \\brief Maps 2D indices to 1D indices.\n *\/\n size_t index(size_t y, size_t x) const { return terminalMap_.size() * y + x; }\n\n virtual void initialize_invalid(const TranslationGrammar &) { return; }\n\n virtual void insert_rule(const size_t insertedRule, const size_t i) {\n table_[i] = {insertedRule};\n }\n\n void initialize() {}\n\n void initialize(const TranslationGrammar &tg,\n const vector> &predict) {\n initialize_invalid(tg);\n table_ =\n row(tg.nonterminals().size() * (tg.terminals().size() + 1), invalid_);\n if (predict.size() != tg.rules().size())\n throw std::invalid_argument(\n \"Mismatched predict and TranslationGrammar.rules \"\n \"sizes when constructing a decision table.\");\n\n \/\/ create index maps for terminals and nonterminals\n for (size_t i = 0; i < tg.nonterminals().size(); ++i) {\n nonterminalMap_.insert(std::make_pair(tg.nonterminals()[i], i));\n }\n for (size_t i = 0; i < tg.terminals().size(); ++i) {\n terminalMap_.insert(std::make_pair(tg.terminals()[i], i));\n }\n terminalMap_.insert(std::make_pair(Symbol::eof(), tg.terminals().size()));\n\n \/* fill table *\/\n for (size_t i = 0; i < tg.rules().size(); ++i) {\n auto &terminals = predict[i];\n \/\/ TranslationGrammar requires this to be always found\n size_t ni = nonterminalMap_.at(tg.rules()[i].nonterminal());\n\n for (auto &t : terminals) {\n auto tit = terminalMap_.find(t);\n if (tit == terminalMap_.end())\n throw std::invalid_argument(\n \"Terminal in predict not a terminal in translation grammar when \"\n \"constructing a decision table.\");\n\n size_t ti = tit->second;\n insert_rule(i, index(ni, ti));\n } \/\/ for all terminals\n } \/\/ for all i\n }\n\n public:\n \/**\n \\brief Constructs an empty LL table.\n *\/\n DecisionTable() = default;\n \/**\n \\brief Constructs a decision table from a translation grammar and a predict\n set.\n\n \\param[in] tg TranslationGrammar. Terminals and Nonterminals are mapped to\n their respective indices. Rule indices are stored in the decision table.\n \\param[in] predict Predict set for table construction.\n *\/\n DecisionTable(const TranslationGrammar &tg,\n const vector> &predict) {\n initialize(tg, predict);\n }\n \/**\n \\brief Returns an index of the rule to be used when t is the current token\n and nt is at the top of input stack.\n\n \\param[in] nt Nonterminal on the top of the stack.\n \\param[in] t Last read terminal.\n\n \\returns Index of the applicable rule or invalid rule index.\n\n If no rule is applicable, returns the index beyond the last rule.\n *\/\n size_t rule_index(const Symbol &nt, const Symbol &t) noexcept {\n \/\/ iterator to nonterminal index\n auto ntit = nonterminalMap_.find(nt);\n \/\/ iterator to terminal index;\n auto tit = terminalMap_.find(t);\n \/\/ either of the arguments not found\n if (ntit == nonterminalMap_.end() || tit == terminalMap_.end())\n return invalid_;\n \/\/ returning from LL table\n return table_[index(ntit->second, tit->second)];\n }\n};\n\n\/**\n\\brief Class containing rule indices to be used in a LL controlled translation.\n*\/\nclass LLTable : public DecisionTable {\n void initialize_invalid(const TranslationGrammar &tg) override {\n invalid_ = tg.rules().size();\n }\n\n void insert_rule(const size_t insertedRule, const size_t i) override {\n \/\/ a rule is already present\n if (table_[i] != invalid_) {\n throw std::invalid_argument(\n \"Constructing LLTable from a non-LL TranslationGrammar.\");\n }\n table_[i] = insertedRule;\n }\n\n public:\n LLTable(const TranslationGrammar &tg, const vector> &predict) {\n initialize(tg, predict);\n }\n\n LLTable() { invalid_ = 0; };\n};\n\nclass GeneralLLTable : public DecisionTable> {\n void insert_rule(const size_t insertedRule, const size_t i) override {\n cell inserted{insertedRule};\n cell newTable{};\n std::set_union(table_[i].begin(), table_[i].end(), inserted.begin(),\n inserted.end(), std::back_inserter(newTable));\n std::swap(table_[i], newTable);\n }\n\n void initialize_invalid(const TranslationGrammar &) override {\n invalid_ = {};\n }\n\n public:\n GeneralLLTable(const TranslationGrammar &tg,\n const vector> &predict) {\n initialize(tg, predict);\n }\n\n GeneralLLTable() { initialize(); };\n};\n} \/\/ namespace ctf\n\n#endif\n\/*** End of file ll_table.hpp ***\/<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2016, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * @file\n * This file implements link quality information processing and storage.\n *\/\n\n#include \"link_quality.hpp\"\n\n#include \n\n#include \"common\/code_utils.hpp\"\n#include \"common\/instance.hpp\"\n#include \"common\/locator-getters.hpp\"\n\nnamespace ot {\n\n\/\/ This array gives the decimal point digits representing 0\/8, 1\/8, ..., 7\/8 (does not include the '.').\nstatic const char *const kDigitsString[8] = {\n \/\/ 0\/8, 1\/8, 2\/8, 3\/8, 4\/8, 5\/8, 6\/8, 7\/8\n \"0\", \"125\", \"25\", \"375\", \"5\", \"625\", \"75\", \"875\"};\n\nvoid SuccessRateTracker::AddSample(bool aSuccess, uint16_t aWeight)\n{\n uint32_t oldAverage = mFailureRate;\n uint32_t newValue = (aSuccess) ? 0 : kMaxRateValue;\n uint32_t n = aWeight;\n\n \/\/ `n\/2` is added to the sum to ensure rounding the value to the nearest integer when dividing by `n`\n \/\/ (e.g., 1.2 -> 1, 3.5 -> 4).\n\n mFailureRate = static_cast(((oldAverage * (n - 1)) + newValue + (n \/ 2)) \/ n);\n}\n\nvoid RssAverager::Reset(void)\n{\n mAverage = 0;\n mCount = 0;\n}\n\notError RssAverager::Add(int8_t aRss)\n{\n otError error = OT_ERROR_NONE;\n uint16_t newValue;\n uint16_t oldAverage;\n\n VerifyOrExit(aRss != OT_RADIO_RSSI_INVALID, error = OT_ERROR_INVALID_ARGS);\n\n \/\/ Restrict the RSS value to the closed range [0, -128] so the RSS times precision multiple can fit in 11 bits.\n if (aRss > 0)\n {\n aRss = 0;\n }\n\n \/\/ Multiply the RSS value by a precision multiple (currently -8).\n\n newValue = static_cast(-aRss);\n newValue <<= kPrecisionBitShift;\n\n oldAverage = mAverage;\n\n if (mCount == 0)\n {\n mCount++;\n mAverage = newValue;\n }\n else if (mCount < (1 << kCoeffBitShift) - 1)\n {\n mCount++;\n\n \/\/ Maintain arithmetic mean.\n \/\/ newAverage = newValue * (1\/mCount) + oldAverage * ((mCount -1)\/mCount)\n mAverage = static_cast(((oldAverage * (mCount - 1)) + newValue) \/ mCount);\n }\n else\n {\n \/\/ Maintain exponentially weighted moving average using coefficient of (1\/2^kCoeffBitShift).\n \/\/ newAverage = + newValue * 1\/2^j + oldAverage * (1 - 1\/2^j), for j = kCoeffBitShift.\n\n mAverage = static_cast(((oldAverage << kCoeffBitShift) - oldAverage + newValue) >> kCoeffBitShift);\n }\n\nexit:\n return error;\n}\n\nint8_t RssAverager::GetAverage(void) const\n{\n int8_t average;\n\n VerifyOrExit(mCount != 0, average = OT_RADIO_RSSI_INVALID);\n\n average = -static_cast(mAverage >> kPrecisionBitShift);\n\n \/\/ Check for possible round up (e.g., average of -71.5 --> -72)\n\n if ((mAverage & kPrecisionBitMask) >= (kPrecision >> 1))\n {\n average--;\n }\n\nexit:\n return average;\n}\n\nRssAverager::InfoString RssAverager::ToString(void) const\n{\n InfoString string;\n\n VerifyOrExit(mCount != 0, OT_NOOP);\n IgnoreError(string.Set(\"%d.%s\", -(mAverage >> kPrecisionBitShift), kDigitsString[mAverage & kPrecisionBitMask]));\n\nexit:\n return string;\n}\n\nvoid LinkQualityInfo::Clear(void)\n{\n mRssAverager.Reset();\n SetLinkQuality(0);\n mLastRss = OT_RADIO_RSSI_INVALID;\n\n mFrameErrorRate.Reset();\n mMessageErrorRate.Reset();\n}\n\nvoid LinkQualityInfo::AddRss(int8_t aRss)\n{\n uint8_t oldLinkQuality = kNoLinkQuality;\n\n VerifyOrExit(aRss != OT_RADIO_RSSI_INVALID, OT_NOOP);\n\n mLastRss = aRss;\n\n if (mRssAverager.HasAverage())\n {\n oldLinkQuality = GetLinkQuality();\n }\n\n SuccessOrExit(mRssAverager.Add(aRss));\n\n SetLinkQuality(CalculateLinkQuality(GetLinkMargin(), oldLinkQuality));\n\nexit:\n return;\n}\n\nuint8_t LinkQualityInfo::GetLinkMargin(void) const\n{\n return ConvertRssToLinkMargin(Get().GetNoiseFloor(), GetAverageRss());\n}\n\nLinkQualityInfo::InfoString LinkQualityInfo::ToInfoString(void) const\n{\n return InfoString(\"aveRss:%s, lastRss:%d, linkQuality:%d\", mRssAverager.ToString().AsCString(), GetLastRss(),\n GetLinkQuality());\n}\n\nuint8_t LinkQualityInfo::ConvertRssToLinkMargin(int8_t aNoiseFloor, int8_t aRss)\n{\n int8_t linkMargin = aRss - aNoiseFloor;\n\n if (linkMargin < 0 || aRss == OT_RADIO_RSSI_INVALID)\n {\n linkMargin = 0;\n }\n\n return static_cast(linkMargin);\n}\n\nuint8_t LinkQualityInfo::ConvertLinkMarginToLinkQuality(uint8_t aLinkMargin)\n{\n return CalculateLinkQuality(aLinkMargin, kNoLinkQuality);\n}\n\nuint8_t LinkQualityInfo::ConvertRssToLinkQuality(int8_t aNoiseFloor, int8_t aRss)\n{\n return ConvertLinkMarginToLinkQuality(ConvertRssToLinkMargin(aNoiseFloor, aRss));\n}\n\nint8_t LinkQualityInfo::ConvertLinkQualityToRss(int8_t aNoiseFloor, uint8_t aLinkQuality)\n{\n int8_t linkmargin = 0;\n\n switch (aLinkQuality)\n {\n case 3:\n linkmargin = kLinkQuality3LinkMargin;\n break;\n\n case 2:\n linkmargin = kLinkQuality2LinkMargin;\n break;\n\n case 1:\n linkmargin = kLinkQuality1LinkMargin;\n break;\n\n default:\n linkmargin = kLinkQuality0LinkMargin;\n break;\n }\n\n return linkmargin + aNoiseFloor;\n}\n\nuint8_t LinkQualityInfo::CalculateLinkQuality(uint8_t aLinkMargin, uint8_t aLastLinkQuality)\n{\n uint8_t threshold1, threshold2, threshold3;\n uint8_t linkQuality = 0;\n\n threshold1 = kThreshold1;\n threshold2 = kThreshold2;\n threshold3 = kThreshold3;\n\n \/\/ Apply the hysteresis threshold based on the last link quality value.\n\n switch (aLastLinkQuality)\n {\n case 0:\n threshold1 += kHysteresisThreshold;\n\n \/\/ fall-through\n\n case 1:\n threshold2 += kHysteresisThreshold;\n\n \/\/ fall-through\n\n case 2:\n threshold3 += kHysteresisThreshold;\n\n \/\/ fall-through\n\n default:\n break;\n }\n\n if (aLinkMargin > threshold3)\n {\n linkQuality = 3;\n }\n else if (aLinkMargin > threshold2)\n {\n linkQuality = 2;\n }\n else if (aLinkMargin > threshold1)\n {\n linkQuality = 1;\n }\n\n return linkQuality;\n}\n\n} \/\/ namespace ot\n[link-quality] optimize RSS calculation (#5508)\/*\n * Copyright (c) 2016, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * @file\n * This file implements link quality information processing and storage.\n *\/\n\n#include \"link_quality.hpp\"\n\n#include \n\n#include \"common\/code_utils.hpp\"\n#include \"common\/instance.hpp\"\n#include \"common\/locator-getters.hpp\"\n\nnamespace ot {\n\n\/\/ This array gives the decimal point digits representing 0\/8, 1\/8, ..., 7\/8 (does not include the '.').\nstatic const char *const kDigitsString[8] = {\n \/\/ 0\/8, 1\/8, 2\/8, 3\/8, 4\/8, 5\/8, 6\/8, 7\/8\n \"0\", \"125\", \"25\", \"375\", \"5\", \"625\", \"75\", \"875\"};\n\nvoid SuccessRateTracker::AddSample(bool aSuccess, uint16_t aWeight)\n{\n uint32_t oldAverage = mFailureRate;\n uint32_t newValue = (aSuccess) ? 0 : kMaxRateValue;\n uint32_t n = aWeight;\n\n \/\/ `n\/2` is added to the sum to ensure rounding the value to the nearest integer when dividing by `n`\n \/\/ (e.g., 1.2 -> 1, 3.5 -> 4).\n\n mFailureRate = static_cast(((oldAverage * (n - 1)) + newValue + (n \/ 2)) \/ n);\n}\n\nvoid RssAverager::Reset(void)\n{\n mAverage = 0;\n mCount = 0;\n}\n\notError RssAverager::Add(int8_t aRss)\n{\n otError error = OT_ERROR_NONE;\n uint16_t newValue;\n\n VerifyOrExit(aRss != OT_RADIO_RSSI_INVALID, error = OT_ERROR_INVALID_ARGS);\n\n \/\/ Restrict the RSS value to the closed range [0, -128] so the RSS times precision multiple can fit in 11 bits.\n if (aRss > 0)\n {\n aRss = 0;\n }\n\n \/\/ Multiply the RSS value by a precision multiple (currently -8).\n\n newValue = static_cast(-aRss);\n newValue <<= kPrecisionBitShift;\n\n mCount += (mCount < (1 << kCoeffBitShift));\n \/\/ Maintain arithmetic mean.\n \/\/ newAverage = newValue * (1\/mCount) + oldAverage * ((mCount -1)\/mCount)\n mAverage = static_cast(((mAverage * (mCount - 1)) + newValue) \/ mCount);\n\nexit:\n return error;\n}\n\nint8_t RssAverager::GetAverage(void) const\n{\n int8_t average;\n\n VerifyOrExit(mCount != 0, average = OT_RADIO_RSSI_INVALID);\n\n average = -static_cast(mAverage >> kPrecisionBitShift);\n\n \/\/ Check for possible round up (e.g., average of -71.5 --> -72)\n\n if ((mAverage & kPrecisionBitMask) >= (kPrecision >> 1))\n {\n average--;\n }\n\nexit:\n return average;\n}\n\nRssAverager::InfoString RssAverager::ToString(void) const\n{\n InfoString string;\n\n VerifyOrExit(mCount != 0, OT_NOOP);\n IgnoreError(string.Set(\"%d.%s\", -(mAverage >> kPrecisionBitShift), kDigitsString[mAverage & kPrecisionBitMask]));\n\nexit:\n return string;\n}\n\nvoid LinkQualityInfo::Clear(void)\n{\n mRssAverager.Reset();\n SetLinkQuality(0);\n mLastRss = OT_RADIO_RSSI_INVALID;\n\n mFrameErrorRate.Reset();\n mMessageErrorRate.Reset();\n}\n\nvoid LinkQualityInfo::AddRss(int8_t aRss)\n{\n uint8_t oldLinkQuality = kNoLinkQuality;\n\n VerifyOrExit(aRss != OT_RADIO_RSSI_INVALID, OT_NOOP);\n\n mLastRss = aRss;\n\n if (mRssAverager.HasAverage())\n {\n oldLinkQuality = GetLinkQuality();\n }\n\n SuccessOrExit(mRssAverager.Add(aRss));\n\n SetLinkQuality(CalculateLinkQuality(GetLinkMargin(), oldLinkQuality));\n\nexit:\n return;\n}\n\nuint8_t LinkQualityInfo::GetLinkMargin(void) const\n{\n return ConvertRssToLinkMargin(Get().GetNoiseFloor(), GetAverageRss());\n}\n\nLinkQualityInfo::InfoString LinkQualityInfo::ToInfoString(void) const\n{\n return InfoString(\"aveRss:%s, lastRss:%d, linkQuality:%d\", mRssAverager.ToString().AsCString(), GetLastRss(),\n GetLinkQuality());\n}\n\nuint8_t LinkQualityInfo::ConvertRssToLinkMargin(int8_t aNoiseFloor, int8_t aRss)\n{\n int8_t linkMargin = aRss - aNoiseFloor;\n\n if (linkMargin < 0 || aRss == OT_RADIO_RSSI_INVALID)\n {\n linkMargin = 0;\n }\n\n return static_cast(linkMargin);\n}\n\nuint8_t LinkQualityInfo::ConvertLinkMarginToLinkQuality(uint8_t aLinkMargin)\n{\n return CalculateLinkQuality(aLinkMargin, kNoLinkQuality);\n}\n\nuint8_t LinkQualityInfo::ConvertRssToLinkQuality(int8_t aNoiseFloor, int8_t aRss)\n{\n return ConvertLinkMarginToLinkQuality(ConvertRssToLinkMargin(aNoiseFloor, aRss));\n}\n\nint8_t LinkQualityInfo::ConvertLinkQualityToRss(int8_t aNoiseFloor, uint8_t aLinkQuality)\n{\n int8_t linkmargin = 0;\n\n switch (aLinkQuality)\n {\n case 3:\n linkmargin = kLinkQuality3LinkMargin;\n break;\n\n case 2:\n linkmargin = kLinkQuality2LinkMargin;\n break;\n\n case 1:\n linkmargin = kLinkQuality1LinkMargin;\n break;\n\n default:\n linkmargin = kLinkQuality0LinkMargin;\n break;\n }\n\n return linkmargin + aNoiseFloor;\n}\n\nuint8_t LinkQualityInfo::CalculateLinkQuality(uint8_t aLinkMargin, uint8_t aLastLinkQuality)\n{\n uint8_t threshold1, threshold2, threshold3;\n uint8_t linkQuality = 0;\n\n threshold1 = kThreshold1;\n threshold2 = kThreshold2;\n threshold3 = kThreshold3;\n\n \/\/ Apply the hysteresis threshold based on the last link quality value.\n\n switch (aLastLinkQuality)\n {\n case 0:\n threshold1 += kHysteresisThreshold;\n\n \/\/ fall-through\n\n case 1:\n threshold2 += kHysteresisThreshold;\n\n \/\/ fall-through\n\n case 2:\n threshold3 += kHysteresisThreshold;\n\n \/\/ fall-through\n\n default:\n break;\n }\n\n if (aLinkMargin > threshold3)\n {\n linkQuality = 3;\n }\n else if (aLinkMargin > threshold2)\n {\n linkQuality = 2;\n }\n else if (aLinkMargin > threshold1)\n {\n linkQuality = 1;\n }\n\n return linkQuality;\n}\n\n} \/\/ namespace ot\n<|endoftext|>"} {"text":"\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2003 - 2007 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission \n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU Affero General Public License \n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n#include \"push\/FSocket.h\"\n#include \"base\/SymbianLog.h\"\n#include \"base\/util\/stringUtils.h\"\n#include \"base\/util\/symbianUtils.h\"\n#include \"base\/FConnection.h\"\n#include \"base\/globalsdef.h\"\n\nUSE_NAMESPACE\n\nStringBuffer FSocket::lIP;\n\n\n\nFSocket* FSocket::createSocket(const StringBuffer& peer, int32_t port) \n{\n return FSocket::NewL(peer, port);\n}\n\n\nFSocket* FSocket::NewL(const StringBuffer& peer, int32_t port)\n{\n FSocket* self = FSocket::NewLC(peer, port);\n CleanupStack::Pop( self );\n \n if (self->getLastStatus() != KErrNone) {\n \/\/ Something wrong.\n delete self;\n return NULL;\n }\n return self;\n}\n\nFSocket* FSocket::NewLC(const StringBuffer& peer, int32_t port)\n{\n FSocket* self = new ( ELeave ) FSocket();\n CleanupStack::PushL( self );\n self->ConstructL(peer, port);\n\n return self;\n}\n\n\nvoid FSocket::ConstructL(const StringBuffer& peer, int32_t port) \n{\n \/\/LOG.debug(\"FSocket::ConstructL\");\n \n StringBuffer errorMsg;\n RHostResolver resolver; \n RBuf serverName;\n TNameEntry hostAddress;\n TInetAddr address;\n TInt res = KErrNone;\n\n serverName.Assign(stringBufferToNewBuf(peer));\n \n \/\/\n \/\/ Get the connection manager instance\n \/\/\n FConnection* connection = FConnection::getInstance();\n if (!connection) {\n iStatus = -1;\n errorMsg = \"Error opening connection\";\n goto error;\n }\n \/\/ Session is owned by FConnection!\n RSocketServ* session = connection->getSession();\n\n \/\/\n \/\/ Open the Client Socket tcp\/ip\n \/\/\n#ifdef __WINSCW__\n \/\/ WINSCW: simply open the socket\n res = iSocket.Open(*session, KAfInet, KSockStream, KProtocolInetTcp);\n#else\n \/\/ GCCE: use the existing connection\n \/\/ If first time, connect to gprs\n if (!connection->isConnected()) {\n LOG.debug(\"Starting connection\");\n if (connection->startConnection()) {\n iStatus = -1;\n errorMsg = \"Error starting connection\";\n goto error;\n }\n }\n RConnection* conn = connection->getConnection();\n \n LOG.debug(\"Opening socket and associate with existing connection\");\n res = iSocket.Open(*session, KAfInet, KSockStream, KProtocolInetTcp, *conn);\n \/\/LOG.debug(\"Socket opened (err = %d)\", res);\n#endif\n if (res != KErrNone) {\n iStatus = -1;\n errorMsg.sprintf(\"FSocket : Error opening socket. code %d\", res);\n goto error;\n }\n \n \n \/\/ This works if serverName is the ip address, like \"x.y.z.w\"\n res = address.Input(serverName);\n \n if (res != KErrNone) {\n \/\/\n \/\/ Try to resolve the host address. (On GCCE, use the existing RConnection)\n \/\/\n LOG.debug(\"Resolve IP address...\");\n#ifdef __WINSCW__\n res = resolver.Open(*session, KAfInet, KProtocolInetTcp);\n#else\n res = resolver.Open(*session, KAfInet, KProtocolInetTcp, *conn);\n#endif\n if (res != KErrNone) {\n iStatus = -2;\n errorMsg.sprintf(\"FSocket: Host resolver open failed. code %d\", res);\n goto error;\n }\n \n resolver.GetByName(serverName, hostAddress, iStatus);\n User::WaitForRequest(iStatus);\n resolver.Close();\n if (iStatus != KErrNone) {\n errorMsg.sprintf(\"FSocket: DNS lookup failed. code %d\", iStatus.Int());\n goto error;\n }\n\n \/\/ Set the socket server address\/port\n address = hostAddress().iAddr;\n }\n \n address.SetPort(port);\n \n \n \/\/ --- Connect to host ---\n LOG.debug(\"Socket connect...\");\n iSocket.Connect(address, iStatus);\n User::WaitForRequest(iStatus);\n if (iStatus != KErrNone) {\n errorMsg.sprintf(\"FSocket: Failed to connect to Server. code %d\", iStatus.Int()); \n goto error;\n }\n\n serverName.Close();\n return;\n \nerror:\n LOG.error(errorMsg.c_str());\n serverName.Close();\n return;\n}\n\n\n\nFSocket::FSocket() \n{\n iStatus = KErrNone;\n}\n\nFSocket::~FSocket() \n{\n close();\n}\n\n\n\nint32_t FSocket::writeBuffer(const int8_t* buffer, int32_t len) \n{\n \/\/ This doesn't copy the buffer in memory.\n TPtr8 data((TUint8*)buffer, len);\n data.SetLength(len);\n \n \/\/ Sends data to the remote host.\n iSocket.Write(data, iStatus);\n User::WaitForRequest(iStatus);\n\n if (iStatus == KErrNone) {\n return len;\n }\n else {\n LOG.error(\"FSocket: error writing on socket (status = %d)\", iStatus.Int());\n return -1;\n }\n}\n\n\nint32_t FSocket::readBuffer(int8_t* buffer, int32_t maxLen) \n{\n StringBuffer errorMsg;\n \n RBuf8 data;\n data.CreateL(maxLen);\n \n \/\/ Receives data from a remote host and completes when data is available.\n TSockXfrLength len;\n iSocket.RecvOneOrMore(data, 0, iStatus, len);\n User::WaitForRequest(iStatus);\n \n TInt msgLen = len();\n \n if (iStatus == KErrNone) {\n if (msgLen <= maxLen) {\n \/\/ OK. Copy the message into the preallocated buffer.\n memcpy(buffer, data.Ptr(), msgLen);\n data.Close();\n return msgLen;\n }\n else {\n errorMsg.sprintf(\"FSocket: error reading, message too big (%d > %d) -> rejected.\",\n (int)msgLen, (int)maxLen);\n goto error;\n }\n }\n else if (iStatus == KErrEof) {\n \/\/ Either the remote connection is closed, or the socket has been shutdown.\n errorMsg = \"FSocket: read interrupted (connection closed)\";\n goto error;\n }\n else {\n errorMsg.sprintf(\"FSocket: error reading on socket (status = %d)\", iStatus.Int());\n goto error;\n }\n\nerror:\n LOG.error(errorMsg.c_str());\n buffer = NULL;\n data.Close();\n return -1;\n}\n\n\nvoid FSocket::close() \n{\n \/\/LOG.debug(\"FSocket::close\");\n \n \/\/ TODO: shutdown if I\/O in progress?\n \/\/iSocket.Shutdown(RSocket::EImmediate, iStatus);\n \n iSocket.CancelAll();\n iSocket.Close();\n}\n\n\n\n\nconst StringBuffer& FSocket::address() const {\n return lAddress;\n}\n\nconst StringBuffer& FSocket::peerAddress() const {\n return pAddress;\n}\n\nconst StringBuffer& FSocket::localIP() {\n return lIP;\n}\nFixed distructor: CancelAll() function crashes in case the connection cannot start for network errors\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2003 - 2007 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission \n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU Affero General Public License \n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n#include \"push\/FSocket.h\"\n#include \"base\/SymbianLog.h\"\n#include \"base\/util\/stringUtils.h\"\n#include \"base\/util\/symbianUtils.h\"\n#include \"base\/FConnection.h\"\n#include \"base\/globalsdef.h\"\n\nUSE_NAMESPACE\n\nStringBuffer FSocket::lIP;\n\n\n\nFSocket* FSocket::createSocket(const StringBuffer& peer, int32_t port) \n{\n return FSocket::NewL(peer, port);\n}\n\n\nFSocket* FSocket::NewL(const StringBuffer& peer, int32_t port)\n{\n FSocket* self = FSocket::NewLC(peer, port);\n CleanupStack::Pop( self );\n \n if (self->getLastStatus() != KErrNone) {\n \/\/ Something wrong.\n LOG.debug(\"FSocket::NewL - error in ConstructL (status = %d)\", self->getLastStatus());\n delete self;\n return NULL;\n }\n return self;\n}\n\nFSocket* FSocket::NewLC(const StringBuffer& peer, int32_t port)\n{\n FSocket* self = new ( ELeave ) FSocket();\n CleanupStack::PushL( self );\n self->ConstructL(peer, port);\n\n return self;\n}\n\n\nvoid FSocket::ConstructL(const StringBuffer& peer, int32_t port) \n{\n \/\/LOG.debug(\"FSocket::ConstructL\");\n \n StringBuffer errorMsg;\n RHostResolver resolver; \n RBuf serverName;\n TNameEntry hostAddress;\n TInetAddr address;\n TInt res = KErrNone;\n\n serverName.Assign(stringBufferToNewBuf(peer));\n \n \/\/\n \/\/ Get the connection manager instance\n \/\/\n FConnection* connection = FConnection::getInstance();\n if (!connection) {\n iStatus = -1;\n errorMsg = \"Error opening connection\";\n goto error;\n }\n \/\/ Session is owned by FConnection!\n RSocketServ* session = connection->getSession();\n\n \/\/\n \/\/ Open the Client Socket tcp\/ip\n \/\/\n#ifdef __WINSCW__\n \/\/ WINSCW: simply open the socket\n res = iSocket.Open(*session, KAfInet, KSockStream, KProtocolInetTcp);\n#else\n \/\/ GCCE: use the existing connection\n \/\/ If first time, connect to gprs\n if (!connection->isConnected()) {\n LOG.debug(\"FSocket: not connected, start new connection\");\n if (connection->startConnection()) {\n iStatus = -1;\n errorMsg = \"FSocket: error starting connection\";\n goto error;\n }\n }\n RConnection* conn = connection->getConnection();\n \n LOG.debug(\"Opening socket and associate with existing connection\");\n res = iSocket.Open(*session, KAfInet, KSockStream, KProtocolInetTcp, *conn);\n \/\/LOG.debug(\"Socket opened (err = %d)\", res);\n#endif\n if (res != KErrNone) {\n iStatus = -1;\n errorMsg.sprintf(\"FSocket : Error opening socket. code %d\", res);\n goto error;\n }\n \n \n \/\/ This works if serverName is the ip address, like \"x.y.z.w\"\n res = address.Input(serverName);\n \n if (res != KErrNone) {\n \/\/\n \/\/ Try to resolve the host address. (On GCCE, use the existing RConnection)\n \/\/\n LOG.debug(\"Resolve IP address...\");\n#ifdef __WINSCW__\n res = resolver.Open(*session, KAfInet, KProtocolInetTcp);\n#else\n res = resolver.Open(*session, KAfInet, KProtocolInetTcp, *conn);\n#endif\n if (res != KErrNone) {\n iStatus = -2;\n errorMsg.sprintf(\"FSocket: Host resolver open failed. code %d\", res);\n goto error;\n }\n \n resolver.GetByName(serverName, hostAddress, iStatus);\n User::WaitForRequest(iStatus);\n resolver.Close();\n if (iStatus != KErrNone) {\n errorMsg.sprintf(\"FSocket: DNS lookup failed. code %d\", iStatus.Int());\n goto error;\n }\n\n \/\/ Set the socket server address\/port\n address = hostAddress().iAddr;\n }\n \n address.SetPort(port);\n \n \n \/\/ --- Connect to host ---\n LOG.debug(\"Socket connect...\");\n iSocket.Connect(address, iStatus);\n User::WaitForRequest(iStatus);\n if (iStatus != KErrNone) {\n errorMsg.sprintf(\"FSocket: Failed to connect to Server. code %d\", iStatus.Int()); \n goto error;\n }\n\n serverName.Close();\n return;\n \nerror:\n LOG.error(errorMsg.c_str());\n serverName.Close();\n return;\n}\n\n\n\nFSocket::FSocket() \n{\n iStatus = KErrNone;\n}\n\nFSocket::~FSocket() \n{\n close();\n}\n\n\n\nint32_t FSocket::writeBuffer(const int8_t* buffer, int32_t len) \n{\n \/\/ This doesn't copy the buffer in memory.\n TPtr8 data((TUint8*)buffer, len);\n data.SetLength(len);\n \n \/\/ Sends data to the remote host.\n iSocket.Write(data, iStatus);\n User::WaitForRequest(iStatus);\n\n if (iStatus == KErrNone) {\n return len;\n }\n else {\n LOG.error(\"FSocket: error writing on socket (status = %d)\", iStatus.Int());\n return -1;\n }\n}\n\n\nint32_t FSocket::readBuffer(int8_t* buffer, int32_t maxLen) \n{\n StringBuffer errorMsg;\n \n RBuf8 data;\n data.CreateL(maxLen);\n \n \/\/ Receives data from a remote host and completes when data is available.\n TSockXfrLength len;\n iSocket.RecvOneOrMore(data, 0, iStatus, len);\n User::WaitForRequest(iStatus);\n \n TInt msgLen = len();\n \n if (iStatus == KErrNone) {\n if (msgLen <= maxLen) {\n \/\/ OK. Copy the message into the preallocated buffer.\n memcpy(buffer, data.Ptr(), msgLen);\n data.Close();\n return msgLen;\n }\n else {\n errorMsg.sprintf(\"FSocket: error reading, message too big (%d > %d) -> rejected.\",\n (int)msgLen, (int)maxLen);\n goto error;\n }\n }\n else if (iStatus == KErrEof) {\n \/\/ Either the remote connection is closed, or the socket has been shutdown.\n errorMsg = \"FSocket: read interrupted (connection closed)\";\n goto error;\n }\n else {\n errorMsg.sprintf(\"FSocket: error reading on socket (status = %d)\", iStatus.Int());\n goto error;\n }\n\nerror:\n LOG.error(errorMsg.c_str());\n buffer = NULL;\n data.Close();\n return -1;\n}\n\n\nvoid FSocket::close() \n{\n \/\/LOG.debug(\"FSocket::close\");\n \/\/ TODO: shutdown if I\/O in progress?\n \/\/iSocket.Shutdown(RSocket::EImmediate, iStatus);\n \n \/\/ Seems that this call causes a crash when startConnection failed for network error\n \/\/iSocket.CancelAll();\n\n iSocket.Close();\n}\n\n\n\n\nconst StringBuffer& FSocket::address() const {\n return lAddress;\n}\n\nconst StringBuffer& FSocket::peerAddress() const {\n return pAddress;\n}\n\nconst StringBuffer& FSocket::localIP() {\n return lIP;\n}\n<|endoftext|>"} {"text":"#include \"game\/city\/city.h\"\n#include \"game\/city\/building.h\"\n#include \"game\/city\/organisation.h\"\n#include \"game\/city\/buildingtile.h\"\n#include \"framework\/framework.h\"\n#include \"game\/resources\/gamecore.h\"\n#include \n\nnamespace OpenApoc {\n\nCity::City(Framework &fw, UString mapName)\n\t: TileMap(fw, Vec3{100, 100, 10}), organisations(Organisation::defaultOrganisations)\n{\n\tauto file = fw.data->load_file(\"xcom3\/ufodata\/\" + mapName);\n\tif (!file)\n\t{\n\t\tLogError(\"Failed to open city map \\\"%s\\\"\", mapName.str().c_str());\n\t\treturn;\n\t}\n\n\tthis->buildings = loadBuildingsFromBld(fw, mapName + \".bld\", this->organisations, Building::defaultNames);\n\tthis->cityTiles = CityTile::loadTilesFromFile(fw);\n\n\tfor (int z = 0; z < this->size.z; z++)\n\t{\n\t\tfor (int y = 0; y < this->size.y; y++)\n\t\t{\n\t\t\tfor (int x = 0; x < this->size.x; x++)\n\t\t\t{\n\t\t\t\tuint16_t tileID;\n\t\t\t\tif (!file.readule16(tileID))\n\t\t\t\t{\n\t\t\t\t\tLogError(\"Unexpected EOF reading citymap at %d,%d,%d\",x,y,z);\n\t\t\t\t\ttileID = 0;\n\t\t\t\t}\n\t\t\t\tif (tileID)\n\t\t\t\t{\n\t\t\t\t\tBuilding *bld = nullptr;\n\t\t\t\t\tfor (auto &b : this->buildings)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (b.bounds.within(Vec2{x,y}))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (bld)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tLogError(\"Multiple buildings on tile at %d,%d,%d\", x, y, z);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbld = &b;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (tileID >= this->cityTiles.size())\n\t\t\t\t\t{\n\t\t\t\t\t\tLogError(\"Invalid tile IDX %u at %d,%d,%d\", tileID, x, y, z);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tauto tile = std::make_shared(*this, this->cityTiles[tileID], Vec3{x,y,z}, bld);\n\t\t\t\t\t\tthis->addObject(std::dynamic_pointer_cast(tile));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::default_random_engine generator;\n\tstd::uniform_int_distribution xydistribution(0,99);\n\tstd::uniform_int_distribution zdistribution(8,9);\n\t\/\/Place 1000 random cars\n\tLogInfo(\"Starting placing cars\");\n\tfor (int i = 0; i < 100; i++)\n\t{\n\t\tint x = 0;\n\t\tint y = 0;\n\t\tint z = 0;\n\t\t\n\t\tdo {\n\t\t\tx = xydistribution(generator);\n\t\t\ty = xydistribution(generator);\n\t\t\tz = zdistribution(generator);\n\t\t} while (!this->getTile(x,y,z)->ownedObjects.empty());\n\n\t\tstd::shared_ptr testVehicle(fw.gamecore->vehicleFactory.create(\"POLICE_HOVERCAR\", organisations[0]));\n\t\tthis->vehicles.push_back(testVehicle);\n\n\t\ttestVehicle->launch(*this, Vec3{x,y,z});\n\t}\n\tLogInfo(\"Finished placing cars\");\n}\n\nCity::~City()\n{\n\n}\n\n}; \/\/namespace OpenApoc\nAdd city tiles to collideableObject lists#include \"game\/city\/city.h\"\n#include \"game\/city\/building.h\"\n#include \"game\/city\/organisation.h\"\n#include \"game\/city\/buildingtile.h\"\n#include \"framework\/framework.h\"\n#include \"game\/resources\/gamecore.h\"\n#include \n\nnamespace OpenApoc {\n\nCity::City(Framework &fw, UString mapName)\n\t: TileMap(fw, Vec3{100, 100, 10}), organisations(Organisation::defaultOrganisations)\n{\n\tauto file = fw.data->load_file(\"xcom3\/ufodata\/\" + mapName);\n\tif (!file)\n\t{\n\t\tLogError(\"Failed to open city map \\\"%s\\\"\", mapName.str().c_str());\n\t\treturn;\n\t}\n\n\tthis->buildings = loadBuildingsFromBld(fw, mapName + \".bld\", this->organisations, Building::defaultNames);\n\tthis->cityTiles = CityTile::loadTilesFromFile(fw);\n\n\tfor (int z = 0; z < this->size.z; z++)\n\t{\n\t\tfor (int y = 0; y < this->size.y; y++)\n\t\t{\n\t\t\tfor (int x = 0; x < this->size.x; x++)\n\t\t\t{\n\t\t\t\tuint16_t tileID;\n\t\t\t\tif (!file.readule16(tileID))\n\t\t\t\t{\n\t\t\t\t\tLogError(\"Unexpected EOF reading citymap at %d,%d,%d\",x,y,z);\n\t\t\t\t\ttileID = 0;\n\t\t\t\t}\n\t\t\t\tif (tileID)\n\t\t\t\t{\n\t\t\t\t\tBuilding *bld = nullptr;\n\t\t\t\t\tfor (auto &b : this->buildings)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (b.bounds.within(Vec2{x,y}))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (bld)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tLogError(\"Multiple buildings on tile at %d,%d,%d\", x, y, z);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbld = &b;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (tileID >= this->cityTiles.size())\n\t\t\t\t\t{\n\t\t\t\t\t\tLogError(\"Invalid tile IDX %u at %d,%d,%d\", tileID, x, y, z);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tauto tile = std::make_shared(*this, this->cityTiles[tileID], Vec3{x,y,z}, bld);\n\t\t\t\t\t\tthis->addObject(std::dynamic_pointer_cast(tile));\n\t\t\t\t\t\ttile->setPosition(Vec3{x,y,z});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::default_random_engine generator;\n\tstd::uniform_int_distribution xydistribution(0,99);\n\tstd::uniform_int_distribution zdistribution(8,9);\n\t\/\/Place 1000 random cars\n\tLogInfo(\"Starting placing cars\");\n\tfor (int i = 0; i < 100; i++)\n\t{\n\t\tint x = 0;\n\t\tint y = 0;\n\t\tint z = 0;\n\t\t\n\t\tdo {\n\t\t\tx = xydistribution(generator);\n\t\t\ty = xydistribution(generator);\n\t\t\tz = zdistribution(generator);\n\t\t} while (!this->getTile(x,y,z)->ownedObjects.empty());\n\n\t\tstd::shared_ptr testVehicle(fw.gamecore->vehicleFactory.create(\"POLICE_HOVERCAR\", organisations[0]));\n\t\tthis->vehicles.push_back(testVehicle);\n\n\t\ttestVehicle->launch(*this, Vec3{x,y,z});\n\t}\n\tLogInfo(\"Finished placing cars\");\n}\n\nCity::~City()\n{\n\n}\n\n}; \/\/namespace OpenApoc\n<|endoftext|>"} {"text":"#include \"umundo\/core.h\"\n#include \n\nusing namespace umundo;\n\nbool testRecursiveMutex() {\n\tMutex mutex;\n\tUMUNDO_LOCK(mutex);\n\tif(!mutex.tryLock()) {\n\t\tLOG_ERR(\"tryLock should be possible from within the same thread\");\n\t\tassert(false);\n\t}\n\tUMUNDO_LOCK(mutex);\n\t\/\/ can we unlock it as well?\n\tUMUNDO_UNLOCK(mutex);\n\tUMUNDO_UNLOCK(mutex);\n\treturn true;\n}\n\nstatic Mutex testMutex;\nbool testThreads() {\n\tclass Thread1 : public Thread {\n\t\tvoid run() {\n\t\t\tif(testMutex.tryLock()) {\n\t\t\t\tLOG_ERR(\"tryLock should return false with a mutex locked in another thread\");\n\t\t\t\tassert(false);\n\t\t\t}\n\t\t\tUMUNDO_LOCK(testMutex); \/\/ blocks\n\t\t\tThread::sleepMs(50);\n\t\t\tUMUNDO_UNLOCK(testMutex);\n\t\t\tThread::sleepMs(100);\n\t\t}\n\t};\n\n\t\/**\n\t * tl=tryLock, l=lock, u=unlock b=block, sN=sleep(N)\n\t * thread1: start tl l l s50 u\n\t * main: start l s50 u s20 tl l join\n\t * t-> 0 50 70 100\n\t *\/\n\n\tUMUNDO_LOCK(testMutex);\n\tThread1 thread1;\n\tthread1.start();\n\tThread::sleepMs(50); \/\/ thread1 will trylock and block on lock\n\tUMUNDO_UNLOCK(testMutex); \/\/ unlock\n\tThread::sleepMs(20); \/\/ yield cpu and sleep\n\t\/\/ thread1 sleeps with lock on mutex\n\tif(testMutex.tryLock()) {\n\t\tLOG_ERR(\"tryLock should return false with a mutex locked in another thread\");\n\t\tassert(false);\n\t}\n\tUMUNDO_LOCK(testMutex); \/\/ thread1 will unlock and sleep\n\tthread1.join(); \/\/ join with thread1\n\tif(thread1.isStarted()) {\n\t\tLOG_ERR(\"thread still running after join\");\n\t\tassert(false);\n\t}\n\treturn true;\n}\n\nstatic Monitor testMonitor;\nstatic int passedMonitor = 0;\nbool testMonitors() {\n\tstruct TestThread : public Thread {\n\t\tint _ms;\n\t\tTestThread(int ms) : _ms(ms) {}\n\t\tvoid run() {\n\t\t\ttestMonitor.wait();\n\t\t\tThread::sleepMs(10); \/\/ avoid clash with other threads\n\t\t\tpassedMonitor++;\n\t\t}\n\t};\n\n\tTestThread thread1(0);\n\tTestThread thread2(5);\n\tTestThread thread3(10);\n\n\tfor (int i = 0; i < 10; i++) {\n\t\tpassedMonitor = 0;\n\n\t\t\/\/ all will block on monitor\n\t\tthread1.start();\n\t\tthread2.start();\n\t\tthread3.start();\n\t\tThread::sleepMs(5); \/\/ give threads a chance to run into wait\n\t\tif(passedMonitor != 0) {\n\t\t\tLOG_ERR(\"%d threads already passed the monitor\", passedMonitor);\n\t\t\tassert(false);\n\t\t}\n\t\tUMUNDO_SIGNAL(testMonitor); \/\/ signal a single thread\n\t\tThread::sleepMs(40); \/\/ thread will increase passedMonitor\n\t\tif(passedMonitor != 1) {\n\t\t\tLOG_ERR(\"Expected 1 threads to pass the monitor, but %d did\", passedMonitor);\n\t\t\tassert(false);\n\t\t}\n\t\tUMUNDO_BROADCAST(testMonitor); \/\/ signal all other threads\n\t\tThread::sleepMs(40);\n\n\t\tif (thread1.isStarted() || thread2.isStarted() || thread3.isStarted()) {\n\t\t\tLOG_ERR(\"Threads ran to completion but still insist on being started\");\n\t\t\tassert(false);\n\t\t}\n\t}\n\treturn true;\n}\n\nstatic Monitor testTimedMonitor;\nstatic int passedTimedMonitor = 0;\nbool testTimedMonitors() {\n\tstruct TestThread : public Thread {\n\t\tint _ms;\n\t\tTestThread(int ms) : _ms(ms) {}\n\t\tvoid run() {\n\t\t\ttestTimedMonitor.wait(_ms);\n\t\t\tpassedTimedMonitor++;\n\t\t}\n\t};\n\n\tTestThread thread1(60);\n\tTestThread thread2(0); \/\/ waits forever\n\tTestThread thread3(0); \/\/ waits forever\n\tTestThread thread4(0); \/\/ waits forever\n\tTestThread thread5(0); \/\/ waits forever\n\n\tfor (int i = 0; i < 10; i++) {\n\t\t\/\/ test waiting for a given time\n\t\tpassedTimedMonitor = 0;\n\t\tthread1.start(); \/\/ wait for 15ms at mutex before resuming\n\t\tThread::sleepMs(10);\n\t\tassert(passedTimedMonitor == 0); \/\/ thread1 should not have passed\n\t\tThread::sleepMs(100);\n\t\tassert(passedTimedMonitor == 1); \/\/ thread1 should have passed\n\t\tassert(!thread1.isStarted());\n\n\t\t\/\/ test signalling a set of threads\n\t\tpassedTimedMonitor = 0;\n\t\tthread2.start();\n\t\tthread3.start();\n\t\tthread4.start();\n\t\tthread5.start();\n\t\tThread::sleepMs(20);\n\t\ttestTimedMonitor.signal(2); \/\/ signal 2 threads\n\t\tThread::sleepMs(50);\n\t\tassert(passedTimedMonitor == 2);\n\t\ttestTimedMonitor.signal(1); \/\/ signal another thread\n\t\tThread::sleepMs(50);\n\t\tassert(passedTimedMonitor == 3);\n\t\ttestTimedMonitor.broadcast(); \/\/ signal last thread\n\t\tThread::sleepMs(50);\n\t\tassert(passedTimedMonitor == 4);\n\t\tassert(!thread2.isStarted() && !thread3.isStarted() && !thread4.isStarted() && !thread5.isStarted());\n\n\t\t\/\/ test timed and unlimited waiting\n\t\tpassedTimedMonitor = 0;\n\t\tthread1.start();\n\t\tthread2.start(); \/\/ with another thread\n\t\tthread3.start(); \/\/ with another thread\n\t\tThread::sleepMs(10);\n\t\ttestTimedMonitor.signal(); \/\/ explicit signal\n\t\tThread::sleepMs(30);\n\t\tassert(passedTimedMonitor == 1);\n\t\t\/\/ wo do not know which thread passed\n\t\tassert(!thread1.isStarted() || !thread2.isStarted() || !thread3.isStarted());\n\t\tif (thread1.isStarted()) {\n\t\t\t\/\/ thread1 is still running, just wait\n\t\t\tThread::sleepMs(100);\n\t\t\tassert(passedTimedMonitor == 2);\n\t\t}\n\t\ttestTimedMonitor.broadcast(); \/\/ explicit signal\n\t\tThread::sleepMs(100);\n\t\tassert(passedTimedMonitor == 3);\n\t\tassert(!thread1.isStarted() && !thread2.isStarted() && !thread3.isStarted());\n\n\t\t\/\/ test signalling prior to waiting\n\t\tpassedTimedMonitor = 0;\n\t\ttestTimedMonitor.signal();\n\t\tthread1.start();\n\t\tthread2.start();\n\t\tThread::sleepMs(200);\n\t\tassert(passedTimedMonitor == 1);\n\t\tassert(!thread1.isStarted());\n\t\tassert(thread2.isStarted());\n\t\ttestTimedMonitor.signal();\n\t\tThread::sleepMs(40);\n\t\tassert(passedTimedMonitor == 2);\n\n\t\tassert(!thread1.isStarted());\n\t\tassert(!thread2.isStarted());\n\t\tassert(!thread3.isStarted());\n\n\t}\n\treturn true;\n}\n\nclass FooTracer : public Traceable, public Thread {\n\tvoid run() {\n\t\twhile(isStarted()) {\n\t\t\ttrace(\"This is foo\");\n\t\t\tThread::sleepMs(20);\n\t\t}\n\t}\n\n\tvoid retrace(const std::string& msg, std::map info) {\n\t};\n\n\n};\n\nbool testTracing() {\n\tFooTracer* tr1 = new FooTracer();\n\tFooTracer* tr2 = new FooTracer();\n\tFooTracer* tr3 = new FooTracer();\n\n\ttr1->setTraceFile(\"trace.txt\");\n\ttr2->setTraceFile(\"trace.txt\");\n\ttr3->setTraceFile(\"trace.txt\");\n\n\ttr1->start();\n\ttr2->start();\n\ttr3->start();\n\n\tThread::sleepMs(100);\n\tdelete tr1;\n\tdelete tr2;\n\tdelete tr3;\n\n\tThread::sleepMs(100);\n\n\tFooTracer* tr4 = new FooTracer();\n\ttr4->replay(\"trace.txt\");\n\n\treturn true;\n}\n\nint main(int argc, char** argv) {\n\tif(!testTracing())\n\t\treturn EXIT_FAILURE;\n\tif(!testRecursiveMutex())\n\t\treturn EXIT_FAILURE;\n\tif(!testThreads())\n\t\treturn EXIT_FAILURE;\n\tif(!testMonitors())\n\t\treturn EXIT_FAILURE;\n\tif(!testTimedMonitors())\n\t\treturn EXIT_FAILURE;\n}\nmore timeout issues#include \"umundo\/core.h\"\n#include \n\nusing namespace umundo;\n\nbool testRecursiveMutex() {\n\tMutex mutex;\n\tUMUNDO_LOCK(mutex);\n\tif(!mutex.tryLock()) {\n\t\tLOG_ERR(\"tryLock should be possible from within the same thread\");\n\t\tassert(false);\n\t}\n\tUMUNDO_LOCK(mutex);\n\t\/\/ can we unlock it as well?\n\tUMUNDO_UNLOCK(mutex);\n\tUMUNDO_UNLOCK(mutex);\n\treturn true;\n}\n\nstatic Mutex testMutex;\nbool testThreads() {\n\tclass Thread1 : public Thread {\n\t\tvoid run() {\n\t\t\tif(testMutex.tryLock()) {\n\t\t\t\tLOG_ERR(\"tryLock should return false with a mutex locked in another thread\");\n\t\t\t\tassert(false);\n\t\t\t}\n\t\t\tUMUNDO_LOCK(testMutex); \/\/ blocks\n\t\t\tThread::sleepMs(50);\n\t\t\tUMUNDO_UNLOCK(testMutex);\n\t\t\tThread::sleepMs(100);\n\t\t}\n\t};\n\n\t\/**\n\t * tl=tryLock, l=lock, u=unlock b=block, sN=sleep(N)\n\t * thread1: start tl l l s50 u\n\t * main: start l s50 u s20 tl l join\n\t * t-> 0 50 70 100\n\t *\/\n\n\tUMUNDO_LOCK(testMutex);\n\tThread1 thread1;\n\tthread1.start();\n\tThread::sleepMs(50); \/\/ thread1 will trylock and block on lock\n\tUMUNDO_UNLOCK(testMutex); \/\/ unlock\n\tThread::sleepMs(20); \/\/ yield cpu and sleep\n\t\/\/ thread1 sleeps with lock on mutex\n\tif(testMutex.tryLock()) {\n\t\tLOG_ERR(\"tryLock should return false with a mutex locked in another thread\");\n\t\tassert(false);\n\t}\n\tUMUNDO_LOCK(testMutex); \/\/ thread1 will unlock and sleep\n\tthread1.join(); \/\/ join with thread1\n\tif(thread1.isStarted()) {\n\t\tLOG_ERR(\"thread still running after join\");\n\t\tassert(false);\n\t}\n\treturn true;\n}\n\nstatic Monitor testMonitor;\nstatic int passedMonitor = 0;\nbool testMonitors() {\n\tstruct TestThread : public Thread {\n\t\tint _ms;\n\t\tTestThread(int ms) : _ms(ms) {}\n\t\tvoid run() {\n\t\t\ttestMonitor.wait();\n\t\t\tThread::sleepMs(10); \/\/ avoid clash with other threads\n\t\t\tpassedMonitor++;\n\t\t}\n\t};\n\n\tTestThread thread1(0);\n\tTestThread thread2(5);\n\tTestThread thread3(10);\n\n\tfor (int i = 0; i < 10; i++) {\n\t\tpassedMonitor = 0;\n\n\t\t\/\/ all will block on monitor\n\t\tthread1.start();\n\t\tthread2.start();\n\t\tthread3.start();\n\t\tThread::sleepMs(5); \/\/ give threads a chance to run into wait\n\t\tif(passedMonitor != 0) {\n\t\t\tLOG_ERR(\"%d threads already passed the monitor\", passedMonitor);\n\t\t\tassert(false);\n\t\t}\n\t\tUMUNDO_SIGNAL(testMonitor); \/\/ signal a single thread\n\t\tThread::sleepMs(40); \/\/ thread will increase passedMonitor\n\t\tif(passedMonitor != 1) {\n\t\t\tLOG_ERR(\"Expected 1 threads to pass the monitor, but %d did\", passedMonitor);\n\t\t\tassert(false);\n\t\t}\n\t\tUMUNDO_BROADCAST(testMonitor); \/\/ signal all other threads\n\t\tThread::sleepMs(40);\n\n\t\tif (thread1.isStarted() || thread2.isStarted() || thread3.isStarted()) {\n\t\t\tLOG_ERR(\"Threads ran to completion but still insist on being started\");\n\t\t\tassert(false);\n\t\t}\n\t}\n\treturn true;\n}\n\nstatic Monitor testTimedMonitor;\nstatic int passedTimedMonitor = 0;\nbool testTimedMonitors() {\n\tstruct TestThread : public Thread {\n\t\tint _ms;\n\t\tTestThread(int ms) : _ms(ms) {}\n\t\tvoid run() {\n\t\t\ttestTimedMonitor.wait(_ms);\n\t\t\tpassedTimedMonitor++;\n\t\t}\n\t};\n\n\tTestThread thread1(60);\n\tTestThread thread2(0); \/\/ waits forever\n\tTestThread thread3(0); \/\/ waits forever\n\tTestThread thread4(0); \/\/ waits forever\n\tTestThread thread5(0); \/\/ waits forever\n\n\tfor (int i = 0; i < 10; i++) {\n\t\t\/\/ test waiting for a given time\n\t\tpassedTimedMonitor = 0;\n\t\tthread1.start(); \/\/ wait for 15ms at mutex before resuming\n\t\tThread::sleepMs(10);\n\t\tassert(passedTimedMonitor == 0); \/\/ thread1 should not have passed\n\t\tThread::sleepMs(100);\n\t\tassert(passedTimedMonitor == 1); \/\/ thread1 should have passed\n\t\tassert(!thread1.isStarted());\n\n\t\t\/\/ test signalling a set of threads\n\t\tpassedTimedMonitor = 0;\n\t\tthread2.start();\n\t\tthread3.start();\n\t\tthread4.start();\n\t\tthread5.start();\n\t\tThread::sleepMs(20);\n\t\ttestTimedMonitor.signal(2); \/\/ signal 2 threads\n\t\tThread::sleepMs(50);\n\t\tassert(passedTimedMonitor == 2);\n\t\ttestTimedMonitor.signal(1); \/\/ signal another thread\n\t\tThread::sleepMs(50);\n\t\tassert(passedTimedMonitor == 3);\n\t\ttestTimedMonitor.broadcast(); \/\/ signal last thread\n\t\tThread::sleepMs(50);\n\t\tassert(passedTimedMonitor == 4);\n\t\tassert(!thread2.isStarted() && !thread3.isStarted() && !thread4.isStarted() && !thread5.isStarted());\n\n\t\t\/\/ test timed and unlimited waiting\n\t\tpassedTimedMonitor = 0;\n\t\tthread1.start();\n\t\tthread2.start(); \/\/ with another thread\n\t\tthread3.start(); \/\/ with another thread\n\t\tThread::sleepMs(10);\n\t\ttestTimedMonitor.signal(); \/\/ explicit signal\n\t\tThread::sleepMs(30);\n\t\tassert(passedTimedMonitor == 1);\n\t\t\/\/ wo do not know which thread passed\n\t\tassert(!thread1.isStarted() || !thread2.isStarted() || !thread3.isStarted());\n\t\tif (thread1.isStarted()) {\n\t\t\t\/\/ thread1 is still running, just wait\n\t\t\tThread::sleepMs(100);\n\t\t\tassert(passedTimedMonitor == 2);\n\t\t}\n\t\ttestTimedMonitor.broadcast(); \/\/ explicit signal\n\t\tThread::sleepMs(100);\n\t\tassert(passedTimedMonitor == 3);\n\t\tassert(!thread1.isStarted() && !thread2.isStarted() && !thread3.isStarted());\n\n\t\t\/\/ test signalling prior to waiting\n\t\tpassedTimedMonitor = 0;\n\t\ttestTimedMonitor.signal();\n\t\tthread1.start();\n\t\tthread2.start();\n\t\tThread::sleepMs(400);\n\t\tassert(passedTimedMonitor == 1);\n\t\tassert(!thread1.isStarted());\n\t\tassert(thread2.isStarted());\n\t\ttestTimedMonitor.signal();\n\t\tThread::sleepMs(40);\n\t\tassert(passedTimedMonitor == 2);\n\n\t\tassert(!thread1.isStarted());\n\t\tassert(!thread2.isStarted());\n\t\tassert(!thread3.isStarted());\n\n\t}\n\treturn true;\n}\n\nclass FooTracer : public Traceable, public Thread {\n\tvoid run() {\n\t\twhile(isStarted()) {\n\t\t\ttrace(\"This is foo\");\n\t\t\tThread::sleepMs(20);\n\t\t}\n\t}\n\n\tvoid retrace(const std::string& msg, std::map info) {\n\t};\n\n\n};\n\nbool testTracing() {\n\tFooTracer* tr1 = new FooTracer();\n\tFooTracer* tr2 = new FooTracer();\n\tFooTracer* tr3 = new FooTracer();\n\n\ttr1->setTraceFile(\"trace.txt\");\n\ttr2->setTraceFile(\"trace.txt\");\n\ttr3->setTraceFile(\"trace.txt\");\n\n\ttr1->start();\n\ttr2->start();\n\ttr3->start();\n\n\tThread::sleepMs(100);\n\tdelete tr1;\n\tdelete tr2;\n\tdelete tr3;\n\n\tThread::sleepMs(100);\n\n\tFooTracer* tr4 = new FooTracer();\n\ttr4->replay(\"trace.txt\");\n\n\treturn true;\n}\n\nint main(int argc, char** argv) {\n\tif(!testTracing())\n\t\treturn EXIT_FAILURE;\n\tif(!testRecursiveMutex())\n\t\treturn EXIT_FAILURE;\n\tif(!testThreads())\n\t\treturn EXIT_FAILURE;\n\tif(!testMonitors())\n\t\treturn EXIT_FAILURE;\n\tif(!testTimedMonitors())\n\t\treturn EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the either Technology Preview License Agreement or the\n** Beta Release License Agreement.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qfxpixmap.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nQT_BEGIN_NAMESPACE\nclass QSharedNetworkReply;\ntypedef QHash QFxSharedNetworkReplyHash;\nstatic QFxSharedNetworkReplyHash qfxActiveNetworkReplies;\n\nclass QSharedNetworkReply\n{\npublic:\n QSharedNetworkReply(QNetworkReply *r) : reply(r), refCount(1) {}\n ~QSharedNetworkReply()\n {\n reply->deleteLater();\n }\n QNetworkReply *reply;\n\n int refCount;\n void addRef()\n {\n ++refCount;\n }\n void release()\n {\n Q_ASSERT(refCount > 0);\n --refCount;\n if (refCount == 0) {\n QString key = reply->url().toString();\n qfxActiveNetworkReplies.remove(key);\n delete this;\n }\n }\n};\n\nclass QFxPixmapPrivate\n{\npublic:\n QFxPixmapPrivate() {}\n\n QPixmap pixmap;\n};\n\n\/*!\n \\internal\n \\class QFxPixmap\n \\ingroup group_utility\n \\brief Enacapsultes a pixmap for QFx items.\n\n This class is NOT reentrant.\n The pixmap cache will grow indefinately.\n *\/\nQFxPixmap::QFxPixmap()\n: d(new QFxPixmapPrivate)\n{\n}\n\nQFxPixmap::QFxPixmap(const QUrl &url)\n: d(new QFxPixmapPrivate)\n{\n#ifdef Q_ENABLE_PERFORMANCE_LOG\n QFxPerfTimer perf;\n#endif\n#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML\n if (url.scheme()==QLatin1String(\"file\")) {\n d->pixmap.load(url.toLocalFile());\n } else\n#endif\n {\n QString key = url.toString();\n if (!QPixmapCache::find(key,&d->pixmap)) {\n QFxSharedNetworkReplyHash::Iterator iter = qfxActiveNetworkReplies.find(key);\n if (iter == qfxActiveNetworkReplies.end()) {\n \/\/ API usage error\n qWarning() << \"QFxPixmap: URL not loaded\" << url;\n } else {\n if ((*iter)->reply->error()) {\n qWarning() << \"Network error loading\" << url << (*iter)->reply->errorString();\n } else {\n QImage img;\n if (img.load((*iter)->reply, 0)) {\n d->pixmap = QPixmap::fromImage(img);\n QPixmapCache::insert(key, d->pixmap);\n } else {\n qWarning() << \"Format error loading\" << url;\n }\n }\n (*iter)->release();\n }\n }\n }\n}\n\nQFxPixmap::QFxPixmap(const QFxPixmap &o)\n: d(new QFxPixmapPrivate)\n{\n d->pixmap = o.d->pixmap;\n}\n\nQFxPixmap::~QFxPixmap()\n{\n delete d;\n}\n\nQFxPixmap &QFxPixmap::operator=(const QFxPixmap &o)\n{\n d->pixmap = o.d->pixmap;\n return *this;\n}\n\nbool QFxPixmap::isNull() const\n{\n return d->pixmap.isNull();\n}\n\nint QFxPixmap::width() const\n{\n return d->pixmap.width();\n}\n\nint QFxPixmap::height() const\n{\n return d->pixmap.height();\n}\n\nQFxPixmap::operator const QPixmap &() const\n{\n return d->pixmap;\n}\n\n\/*!\n Starts a network request to load \\a url. When the URL is loaded,\n the given slot is invoked. Note that if the image is already cached,\n the slot may be invoked immediately.\n\n Returns a QNetworkReply if the image is not immediately available, otherwise\n returns 0. The QNetworkReply must not be stored - it may be destroyed at any time.\n*\/\nQNetworkReply *QFxPixmap::get(QmlEngine *engine, const QUrl& url, QObject* obj, const char* slot)\n{\n#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML\n if (url.scheme()==QLatin1String(\"file\")) {\n QObject dummy;\n QObject::connect(&dummy, SIGNAL(destroyed()), obj, slot);\n return 0;\n }\n#endif\n\n QString key = url.toString();\n if (QPixmapCache::find(key,0)) {\n QObject dummy;\n QObject::connect(&dummy, SIGNAL(destroyed()), obj, slot);\n return 0;\n }\n\n QFxSharedNetworkReplyHash::Iterator iter = qfxActiveNetworkReplies.find(key);\n if (iter == qfxActiveNetworkReplies.end()) {\n QNetworkRequest req(url);\n req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);\n QSharedNetworkReply *item = new QSharedNetworkReply(engine->networkAccessManager()->get(req));\n iter = qfxActiveNetworkReplies.insert(key, item);\n } else {\n (*iter)->addRef();\n }\n\n QObject::connect((*iter)->reply, SIGNAL(finished()), obj, slot);\n return (*iter)->reply;\n}\n\n\/*!\n Stops the given slot being invoked if the given url finishes loading.\n May also cancel loading (eg. if no other pending request).\n\n Any connections to the QNetworkReply returned by get() will be\n disconnected.\n*\/\nvoid QFxPixmap::cancelGet(const QUrl& url, QObject* obj)\n{\n QString key = url.toString();\n QFxSharedNetworkReplyHash::Iterator iter = qfxActiveNetworkReplies.find(key);\n if (iter == qfxActiveNetworkReplies.end())\n return;\n QObject::disconnect((*iter)->reply, 0, obj, 0);\n (*iter)->release();\n}\n\nQT_END_NAMESPACE\nAdd some (disabled) test code for limiting image size. QFxImage et al could benefit from a limit feature, especially for remote images.\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the either Technology Preview License Agreement or the\n** Beta Release License Agreement.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qfxpixmap.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nQT_BEGIN_NAMESPACE\nclass QSharedNetworkReply;\ntypedef QHash QFxSharedNetworkReplyHash;\nstatic QFxSharedNetworkReplyHash qfxActiveNetworkReplies;\n\nclass QSharedNetworkReply\n{\npublic:\n QSharedNetworkReply(QNetworkReply *r) : reply(r), refCount(1) {}\n ~QSharedNetworkReply()\n {\n reply->deleteLater();\n }\n QNetworkReply *reply;\n\n int refCount;\n void addRef()\n {\n ++refCount;\n }\n void release()\n {\n Q_ASSERT(refCount > 0);\n --refCount;\n if (refCount == 0) {\n QString key = reply->url().toString();\n qfxActiveNetworkReplies.remove(key);\n delete this;\n }\n }\n};\n\nclass QFxPixmapPrivate\n{\npublic:\n QFxPixmapPrivate() {}\n\n QPixmap pixmap;\n};\n\n\/*!\n \\internal\n \\class QFxPixmap\n \\ingroup group_utility\n \\brief Enacapsultes a pixmap for QFx items.\n\n This class is NOT reentrant.\n The pixmap cache will grow indefinately.\n *\/\nQFxPixmap::QFxPixmap()\n: d(new QFxPixmapPrivate)\n{\n}\n\nQFxPixmap::QFxPixmap(const QUrl &url)\n: d(new QFxPixmapPrivate)\n{\n#ifdef Q_ENABLE_PERFORMANCE_LOG\n QFxPerfTimer perf;\n#endif\n#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML\n if (url.scheme()==QLatin1String(\"file\")) {\n d->pixmap.load(url.toLocalFile());\n } else\n#endif\n {\n QString key = url.toString();\n if (!QPixmapCache::find(key,&d->pixmap)) {\n QFxSharedNetworkReplyHash::Iterator iter = qfxActiveNetworkReplies.find(key);\n if (iter == qfxActiveNetworkReplies.end()) {\n \/\/ API usage error\n qWarning() << \"QFxPixmap: URL not loaded\" << url;\n } else {\n if ((*iter)->reply->error()) {\n qWarning() << \"Network error loading\" << url << (*iter)->reply->errorString();\n } else {\n QImageReader imgio((*iter)->reply);\n\n\/\/#define QT_TEST_SCALED_SIZE\n#ifdef QT_TEST_SCALED_SIZE\n \/*\n Some mechanism is needed for loading images at a limited size, especially\n for remote images. Loading only thumbnails of remote progressive JPEG\n images can be efficient. (Qt jpeg handler does not do so currently)\n *\/\n\n QSize limit(60,60);\n QSize sz = imgio.size();\n if (sz.width() > limit.width() || sz.height() > limit.height()) {\n sz.scale(limit,Qt::KeepAspectRatio);\n imgio.setScaledSize(sz);\n }\n#endif\n\n QImage img;\n if (imgio.read(&img)) {\n#ifdef QT_TEST_SCALED_SIZE\n if (!sz.isValid())\n img = img.scaled(limit,Qt::KeepAspectRatio);\n#endif\n d->pixmap = QPixmap::fromImage(img);\n QPixmapCache::insert(key, d->pixmap);\n } else {\n qWarning() << \"Format error loading\" << url;\n }\n }\n (*iter)->release();\n }\n }\n }\n}\n\nQFxPixmap::QFxPixmap(const QFxPixmap &o)\n: d(new QFxPixmapPrivate)\n{\n d->pixmap = o.d->pixmap;\n}\n\nQFxPixmap::~QFxPixmap()\n{\n delete d;\n}\n\nQFxPixmap &QFxPixmap::operator=(const QFxPixmap &o)\n{\n d->pixmap = o.d->pixmap;\n return *this;\n}\n\nbool QFxPixmap::isNull() const\n{\n return d->pixmap.isNull();\n}\n\nint QFxPixmap::width() const\n{\n return d->pixmap.width();\n}\n\nint QFxPixmap::height() const\n{\n return d->pixmap.height();\n}\n\nQFxPixmap::operator const QPixmap &() const\n{\n return d->pixmap;\n}\n\n\/*!\n Starts a network request to load \\a url. When the URL is loaded,\n the given slot is invoked. Note that if the image is already cached,\n the slot may be invoked immediately.\n\n Returns a QNetworkReply if the image is not immediately available, otherwise\n returns 0. The QNetworkReply must not be stored - it may be destroyed at any time.\n*\/\nQNetworkReply *QFxPixmap::get(QmlEngine *engine, const QUrl& url, QObject* obj, const char* slot)\n{\n#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML\n if (url.scheme()==QLatin1String(\"file\")) {\n QObject dummy;\n QObject::connect(&dummy, SIGNAL(destroyed()), obj, slot);\n return 0;\n }\n#endif\n\n QString key = url.toString();\n if (QPixmapCache::find(key,0)) {\n QObject dummy;\n QObject::connect(&dummy, SIGNAL(destroyed()), obj, slot);\n return 0;\n }\n\n QFxSharedNetworkReplyHash::Iterator iter = qfxActiveNetworkReplies.find(key);\n if (iter == qfxActiveNetworkReplies.end()) {\n QNetworkRequest req(url);\n req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);\n QSharedNetworkReply *item = new QSharedNetworkReply(engine->networkAccessManager()->get(req));\n iter = qfxActiveNetworkReplies.insert(key, item);\n } else {\n (*iter)->addRef();\n }\n\n QObject::connect((*iter)->reply, SIGNAL(finished()), obj, slot);\n return (*iter)->reply;\n}\n\n\/*!\n Stops the given slot being invoked if the given url finishes loading.\n May also cancel loading (eg. if no other pending request).\n\n Any connections to the QNetworkReply returned by get() will be\n disconnected.\n*\/\nvoid QFxPixmap::cancelGet(const QUrl& url, QObject* obj)\n{\n QString key = url.toString();\n QFxSharedNetworkReplyHash::Iterator iter = qfxActiveNetworkReplies.find(key);\n if (iter == qfxActiveNetworkReplies.end())\n return;\n QObject::disconnect((*iter)->reply, 0, obj, 0);\n (*iter)->release();\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"\/\/=============================================================================\n\/\/ ■ VMGS\/Scene\/EditorMainScene.cpp\n\/\/-----------------------------------------------------------------------------\n\/\/ 编辑器场景。\n\/\/=============================================================================\n\n#include \"..\/VMGS.hpp\"\n\n#include \"..\/Control\/GodView.hpp\"\n#include \"..\/Control\/FirstPersonView.hpp\"\n#include \"..\/GameObject\/SkyBox\/SkyBox.hpp\"\n\nnamespace VM76 {\n\n\tGodView* ctl;\n\tFirstPersonView* ctl_fp;\n\tSkyBox* sky;\n\n\tbool fp_control = false;\n\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 场景开始\n\t\/\/-------------------------------------------------------------------------\n\tEditorMainScene::EditorMainScene() {\n\t\tobj = new GObject();\n\n\t\tshader_textured.add_file(GL_VERTEX_SHADER, \"..\/Media\/shaders\/gbuffers_textured.vsh\");\n\t\tshader_textured.add_file(GL_FRAGMENT_SHADER, \"..\/Media\/shaders\/gbuffers_textured.fsh\");\n\t\tshader_textured.link_program();\n\t\tshader_basic.add_file(GL_VERTEX_SHADER, \"..\/Media\/shaders\/gbuffers_basic.vsh\");\n\t\tshader_basic.add_file(GL_FRAGMENT_SHADER, \"..\/Media\/shaders\/gbuffers_basic.fsh\");\n\t\tshader_basic.link_program();\n\t\tgui.add_file(GL_VERTEX_SHADER, \"..\/Media\/shaders\/gui.vsh\");\n\t\tgui.add_file(GL_FRAGMENT_SHADER, \"..\/Media\/shaders\/gui.fsh\");\n\t\tgui.link_program();\n\t\tpost_processing.add_file(GL_VERTEX_SHADER, \"..\/Media\/shaders\/PostProcessing.vsh\");\n\t\tpost_processing.add_file(GL_FRAGMENT_SHADER, \"..\/Media\/shaders\/PostProcessing.fsh\");\n\t\tpost_processing.link_program();\n\n\t\tGLuint* gbuffers_type = new GLuint[3]{GL_RGB8, GL_RGB16F, GL_RGB8};\n\t\tpostBuffer = new RenderBuffer(VMDE->width, VMDE->height, 3, gbuffers_type);\n\n\t\tprojection = glm::perspective(1.3f, aspect_ratio, 0.1f, 1000.0f);\n\t\tview = glm::lookAt(\n\t\t\tglm::vec3(0.0, 2.6, 0.0),\n\t\t\tglm::vec3(0.0, 0.0, 0.0),\n\t\t\tglm::vec3(0.0, 1.0, 0.0)\n\t\t);\n\n\t\t\/\/ Set up hand block indicator's matrix\n\t\tglm::mat4 block_display = glm::translate(\n\t\t\tglm::mat4(1.0),\n\t\t\tglm::vec3(0.02, 0.06, 0.2)\n\t\t);\n\t\tblock_display = glm::scale(block_display, glm::vec3(0.1f));\n\t\tblock_display = glm::rotate(block_display,\n\t\t\tVMath::PIf \/ 4.0f,\n\t\t\tglm::vec3(1.0, 0.0, 0.0)\n\t\t);\n\t\tblock_display = glm::rotate(block_display,\n\t\t\tVMath::PIf \/ 4.0f,\n\t\t\tglm::vec3(0.0, 1.0, 0.0)\n\t\t);\n\n\t\tTiledMap::init_cinstances(clist);\n\t\t\/*for (int i = 0; i < 16; i++) {\n\t\t\tclist[i]->mat[0] = new glm::mat4[1]; clist[i]->mat[0][0] = block_display;\n\t\t\tclist[i]->mat[1] = new glm::mat4[1]; clist[i]->mat[1][0] = block_display;\n\t\t\tclist[i]->mat[2] = new glm::mat4[1]; clist[i]->mat[2][0] = block_display;\n\t\t\tclist[i]->mat[3] = new glm::mat4[1]; clist[i]->mat[3][0] = block_display;\n\t\t\tclist[i]->mat[4] = new glm::mat4[1]; clist[i]->mat[4][0] = block_display;\n\t\t\tclist[i]->mat[5] = new glm::mat4[1]; clist[i]->mat[5][0] = block_display;\n\t\t\tclist[i]->update_instance(1,1,1,1,1,1);\n\t\t}\n\t\tblock_pointer.obj->data.mat_c = 1;*\/\n\n\t\tctl = new GodView();\n\t\tctl_fp = new FirstPersonView();\n\t\tctl->init_control();\n\t\tctl_fp->init_control();\n\t\tctl->cam.wpos = glm::vec3(64.0, 72.0, 64.0);\n\t\tctl_fp->game_player.wpos = glm::vec3(64.0, 72.0, 64.0);\n\n\t\tsky = new SkyBox(\"..\/Media\/skybox.png\");\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 按键回调\n\t\/\/-------------------------------------------------------------------------\n\tbool magnify = false;\n\tbool magnifyPrev = false;\n\n\tvoid EditorMainScene::key_callback(\n\t\tGLFWwindow* window, int key, int scancode, int action, int mods\n\t) {\n\t\t#define PRESS(n) key == n && action == GLFW_PRESS\n\t\tif (PRESS(GLFW_KEY_A)) obj->move(glm::vec3(-1.0, 0.0, 0.0));\n\t\tif (PRESS(GLFW_KEY_D)) obj->move(glm::vec3(1.0, 0.0, 0.0));\n\t\tif (PRESS(GLFW_KEY_W)) obj->move(glm::vec3(0.0, 0.0, -1.0));\n\t\tif (PRESS(GLFW_KEY_S)) obj->move(glm::vec3(0.0, 0.0, 1.0));\n\t\tif (PRESS(GLFW_KEY_UP)) obj->move(glm::vec3(0.0, 1.0, 0.0));\n\t\tif (PRESS(GLFW_KEY_DOWN)) obj->move(glm::vec3(0.0, -1.0, 0.0));\n\n\t\tif (PRESS(GLFW_KEY_F5)) fp_control = !fp_control;\n\n\t\tif (PRESS(GLFW_KEY_0)) hand_id = 0;\n\t\tif (PRESS(GLFW_KEY_0)) hand_id = 0;\n\t\tif (PRESS(GLFW_KEY_1)) hand_id = 1;\n\t\tif (PRESS(GLFW_KEY_2)) hand_id = 2;\n\t\tif (PRESS(GLFW_KEY_3)) hand_id = 3;\n\t\tif (PRESS(GLFW_KEY_4)) hand_id = 4;\n\t\tif (PRESS(GLFW_KEY_5)) hand_id = 5;\n\t\tif (PRESS(GLFW_KEY_6)) hand_id = 6;\n\t\tif (PRESS(GLFW_KEY_7)) hand_id = 7;\n\t\tif (PRESS(GLFW_KEY_8)) hand_id = 8;\n\t\tif (PRESS(GLFW_KEY_9)) hand_id = 9;\n\n\t\tif (PRESS(GLFW_KEY_SPACE)) {\n\t\t\tmap.place_block(obj->pos, hand_id);\n\t\t}\n\n\t\tif (PRESS(GLFW_KEY_O)) {\n\t\t\tmagnify = !magnify;\n\t\t\tif (magnify) projection = glm::perspective(0.3f, aspect_ratio, 0.1f, 1000.0f);\n\t\t\telse projection = glm::perspective(1.3f, aspect_ratio, 0.1f, 1000.0f);\n\t\t}\n\n\t\tstatic Audio::Channel_Vorbis* loop = NULL;\n\t\tstatic Audio::Channel_Triangle* triangle = NULL;\n\t\tstatic Audio::Channel_Sine* sine = NULL;\n\t\tif (PRESS(GLFW_KEY_SEMICOLON)) {\n\t\t\tAudio::play_sound(\"..\/Media\/soft-ping.ogg\", false);\n\t\t}\n\t\tif (PRESS(GLFW_KEY_APOSTROPHE)) {\n\t\t\tif (loop) {\n\t\t\t\tAudio::stop(loop);\n\t\t\t\tloop = NULL;\n\t\t\t} else {\n\t\t\t\tloop = Audio::play_sound(\"..\/Media\/loop-test.ogg\", true, .1f);\n\t\t\t}\n\t\t}\n\t\tif (PRESS(GLFW_KEY_LEFT_BRACKET)) {\n\t\t\tif (triangle) {\n\t\t\t\tAudio::stop(triangle);\n\t\t\t\ttriangle = NULL;\n\t\t\t} else {\n\t\t\t\ttriangle = new Audio::Channel_Triangle(440);\n\t\t\t\tAudio::play_channel(triangle);\n\t\t\t}\n\t\t}\n\t\tif (PRESS(GLFW_KEY_RIGHT_BRACKET)) {\n\t\t\tif (sine) {\n\t\t\t\tAudio::stop(sine);\n\t\t\t\tsine = NULL;\n\t\t\t} else {\n\t\t\t\tsine = new Audio::Channel_Sine(440);\n\t\t\t\tAudio::play_channel(sine);\n\t\t\t}\n\t\t}\n\t\t#undef PRESS\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 刷新\n\t\/\/-------------------------------------------------------------------------\n\tvoid EditorMainScene::update() {\n\t\tif (fp_control)\n\t\t\tctl->update_control();\n\t\telse\n\t\t\tctl_fp->update_control();\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 渲染\n\t\/\/-------------------------------------------------------------------------\n\tvoid EditorMainScene::render() {\n\t\tshader_textured.use();\n\n\t\t\/\/ Setup uniforms\n\t\tshader_textured.set_float(\"brightness\", VMDE->state.brightness);\n\t\tshader_textured.set_texture(\"colortex0\", &tile_texture, 0);\n\n\t\tpostBuffer->bind();\n\t\tRenderBuffer::clearColorDepth(0.5, 0.7, 1.0, 0.0);\n\t\tpostBuffer->set_draw_buffers();\n\n\t\t\/\/ Textured blocks rendering\n\t\tshader_textured.ProjectionView(projection, view);\n\t\tmap.render();\n\n\t\tsky->render();\n\n\t\t\/\/ Setup uniforms\n\t\t\/\/ Non textured rendering\n\t\tshader_basic.use();\n\t\tshader_basic.set_float(\"opaque\", 0.5);\n\t\tshader_textured.ProjectionView(projection, view);\n\t\tblock_pointer.mat[0] = obj->transform();\n\t\tblock_pointer.update_instance(1);\n\t\tblock_pointer.render();\n\n\t\taxe.render();\n\n\n\t\tpostBuffer->unbind();\n\t\tpost_processing.use();\n\t\tpost_processing.set_texture(\"colortex\", postBuffer->texture_buffer[0], 0);\n\t\tpost_processing.set_texture(\"gnormal\", postBuffer->texture_buffer[2], 1);\n\t\tglm::vec3 sunVec = glm::mat3(view) * glm::vec3(cos(VMath::PI * 0.25), sin(VMath::PI * 0.25), sin(VMath::PI * 0.25) * 0.3f);\n\t\tglUniform3f(glGetUniformLocation(post_processing.program, \"sunVec\"), sunVec.x, sunVec.y, sunVec.z);\n\t\tPostProcessingManager::Blit2D();\n\n\t\t\/\/ GUI rendering\n\t\tgui.use();\n\t\tgui.set_texture(\"atlastex\", &tile_texture, 0);\n\t\tgui.ProjectionView(gui_2d_projection, glm::mat4(1.0));\n\t\tVMSC::disable_depth_test();\n\t\t\/\/if (hand_id > 0) clist[hand_id - 1]->render();\n\n\t\tif (SceneManager::render_debug_info) {\n\t\t\tchar info[64];\n\t\t\tsprintf(info, \"Hand ID: %d Pointer ID: %d\",\n\t\t\t\thand_id,\n\t\t\t\tmap.map->tidQuery(obj->pos.x, obj->pos.y, obj->pos.z)\n\t\t\t);\n\t\t\ttrex->instanceRenderText(\n\t\t\t\tinfo, gui_2d_projection,\n\t\t\t\tglm::mat4(1.0),\n\t\t\t\tglm::translate(glm::mat4(1.0), glm::vec3(0.01, 0.88, 0.0)),\n\t\t\t\t0.025, 0.05, TextRenderer::TextDecorationType::OUTLINE\n\t\t\t);\n\t\t\tsprintf(info, \"Pointer pos: (%.0f, %.0f, %.0f)\",\n\t\t\t\tobj->pos.x, obj->pos.y, obj->pos.z\n\t\t\t);\n\t\t\ttrex->instanceRenderText(\n\t\t\t\tinfo, gui_2d_projection,\n\t\t\t\tglm::mat4(1.0),\n\t\t\t\tglm::translate(glm::mat4(1.0), glm::vec3(0.01, 0.82, 0.0)),\n\t\t\t\t0.025, 0.05, TextRenderer::TextDecorationType::OUTLINE\n\t\t\t);\n\t\t}\n\t\tVMSC::enable_depth_test();\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 释放\n\t\/\/-------------------------------------------------------------------------\n\tEditorMainScene::~EditorMainScene() {\n\t\tfor (int i = 0; i < 16; i++) VMDE_Dispose(delete, clist[i]);\n\t\tVMDE_Dispose(delete, trex);\n\t\tVMDE_Dispose(delete, postBuffer);\n\t}\n}\n恢复手渲染\/\/=============================================================================\n\/\/ ■ VMGS\/Scene\/EditorMainScene.cpp\n\/\/-----------------------------------------------------------------------------\n\/\/ 编辑器场景。\n\/\/=============================================================================\n\n#include \"..\/VMGS.hpp\"\n\n#include \"..\/Control\/GodView.hpp\"\n#include \"..\/Control\/FirstPersonView.hpp\"\n#include \"..\/GameObject\/SkyBox\/SkyBox.hpp\"\n\nnamespace VM76 {\n\n\tGodView* ctl;\n\tFirstPersonView* ctl_fp;\n\tSkyBox* sky;\n\n\tbool fp_control = false;\n\t\n\tGDrawable* hand_block;\n\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 场景开始\n\t\/\/-------------------------------------------------------------------------\n\tEditorMainScene::EditorMainScene() {\n\t\tobj = new GObject();\n\t\t\n\t\thand_block = new GDrawable();\n\t\thand_block->data.vertices = new Vertex[4 * 6];\n\t\thand_block->data.indices = new GLuint[6 * 6];\n\n\t\tshader_textured.add_file(GL_VERTEX_SHADER, \"..\/Media\/shaders\/gbuffers_textured.vsh\");\n\t\tshader_textured.add_file(GL_FRAGMENT_SHADER, \"..\/Media\/shaders\/gbuffers_textured.fsh\");\n\t\tshader_textured.link_program();\n\t\tshader_basic.add_file(GL_VERTEX_SHADER, \"..\/Media\/shaders\/gbuffers_basic.vsh\");\n\t\tshader_basic.add_file(GL_FRAGMENT_SHADER, \"..\/Media\/shaders\/gbuffers_basic.fsh\");\n\t\tshader_basic.link_program();\n\t\tgui.add_file(GL_VERTEX_SHADER, \"..\/Media\/shaders\/gui.vsh\");\n\t\tgui.add_file(GL_FRAGMENT_SHADER, \"..\/Media\/shaders\/gui.fsh\");\n\t\tgui.link_program();\n\t\tpost_processing.add_file(GL_VERTEX_SHADER, \"..\/Media\/shaders\/PostProcessing.vsh\");\n\t\tpost_processing.add_file(GL_FRAGMENT_SHADER, \"..\/Media\/shaders\/PostProcessing.fsh\");\n\t\tpost_processing.link_program();\n\n\t\tGLuint* gbuffers_type = new GLuint[3]{GL_RGB8, GL_RGB16F, GL_RGB8};\n\t\tpostBuffer = new RenderBuffer(VMDE->width, VMDE->height, 3, gbuffers_type);\n\n\t\tprojection = glm::perspective(1.3f, aspect_ratio, 0.1f, 1000.0f);\n\t\tview = glm::lookAt(\n\t\t\tglm::vec3(0.0, 2.6, 0.0),\n\t\t\tglm::vec3(0.0, 0.0, 0.0),\n\t\t\tglm::vec3(0.0, 1.0, 0.0)\n\t\t);\n\n\t\t\/\/ Set up hand block indicator's matrix\n\t\tglm::mat4 block_display = glm::translate(\n\t\t\tglm::mat4(1.0),\n\t\t\tglm::vec3(0.02, 0.06, 0.2)\n\t\t);\n\t\tblock_display = glm::scale(block_display, glm::vec3(0.1f));\n\t\tblock_display = glm::rotate(block_display,\n\t\t\tVMath::PIf \/ 4.0f,\n\t\t\tglm::vec3(1.0, 0.0, 0.0)\n\t\t);\n\t\tblock_display = glm::rotate(block_display,\n\t\t\tVMath::PIf \/ 4.0f,\n\t\t\tglm::vec3(0.0, 1.0, 0.0)\n\t\t);\n\n\t\tTiledMap::init_cinstances(clist);\n\t\tint vtx_c = 0, ind_c = 0;\n\t\tfor (int i = 0; i < 6; i++) clist[hand_id - 1]->bake(0,0,0,hand_block->data.vertices,hand_block->data.indices,&vtx_c,&ind_c,i);\n\t\thand_block->data.vtx_c = vtx_c;\n\t\thand_block->data.ind_c = ind_c;\n\t\thand_block->data.mat_c = 1;\n\t\thand_block->data.mat = (GLuint*) &block_display;\n\t\thand_block->fbind();\n\t\tblock_pointer.obj->data.mat_c = 1;\n\n\t\tctl = new GodView();\n\t\tctl_fp = new FirstPersonView();\n\t\tctl->init_control();\n\t\tctl_fp->init_control();\n\t\tctl->cam.wpos = glm::vec3(64.0, 72.0, 64.0);\n\t\tctl_fp->game_player.wpos = glm::vec3(64.0, 72.0, 64.0);\n\n\t\tsky = new SkyBox(\"..\/Media\/skybox.png\");\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 按键回调\n\t\/\/-------------------------------------------------------------------------\n\tbool magnify = false;\n\tbool magnifyPrev = false;\n\n\tvoid EditorMainScene::key_callback(\n\t\tGLFWwindow* window, int key, int scancode, int action, int mods\n\t) {\n\t\t#define PRESS(n) key == n && action == GLFW_PRESS\n\t\tif (PRESS(GLFW_KEY_A)) obj->move(glm::vec3(-1.0, 0.0, 0.0));\n\t\tif (PRESS(GLFW_KEY_D)) obj->move(glm::vec3(1.0, 0.0, 0.0));\n\t\tif (PRESS(GLFW_KEY_W)) obj->move(glm::vec3(0.0, 0.0, -1.0));\n\t\tif (PRESS(GLFW_KEY_S)) obj->move(glm::vec3(0.0, 0.0, 1.0));\n\t\tif (PRESS(GLFW_KEY_UP)) obj->move(glm::vec3(0.0, 1.0, 0.0));\n\t\tif (PRESS(GLFW_KEY_DOWN)) obj->move(glm::vec3(0.0, -1.0, 0.0));\n\n\t\tif (PRESS(GLFW_KEY_F5)) fp_control = !fp_control;\n\n\t\tif (PRESS(GLFW_KEY_0)) hand_id = 0;\n\t\tif (PRESS(GLFW_KEY_1)) hand_id = 1;\n\t\tif (PRESS(GLFW_KEY_2)) hand_id = 2;\n\t\tif (PRESS(GLFW_KEY_3)) hand_id = 3;\n\t\tif (PRESS(GLFW_KEY_4)) hand_id = 4;\n\t\tif (PRESS(GLFW_KEY_5)) hand_id = 5;\n\t\tif (PRESS(GLFW_KEY_6)) hand_id = 6;\n\t\tif (PRESS(GLFW_KEY_7)) hand_id = 7;\n\t\tif (PRESS(GLFW_KEY_8)) hand_id = 8;\n\t\tif (PRESS(GLFW_KEY_9)) hand_id = 9;\n\n\t\tif (hand_id > 0) {\n\t\t\tint vtx_c = 0, ind_c = 0;\n\t\t\tfor (int i = 0; i < 6; i++) clist[hand_id - 1]->bake(0,0,0,hand_block->data.vertices,hand_block->data.indices,&vtx_c,&ind_c,i);\n\t\t\thand_block->update();\n\t\t}\n\n\t\tif (PRESS(GLFW_KEY_SPACE)) {\n\t\t\tmap.place_block(obj->pos, hand_id);\n\t\t}\n\n\t\tif (PRESS(GLFW_KEY_O)) {\n\t\t\tprojection = glm::perspective(0.3f, aspect_ratio, 0.1f, 1000.0f);\n\t\t} else if (key == GLFW_KEY_O && action == GLFW_RELEASE) {\n\t\t\tprojection = glm::perspective(1.3f, aspect_ratio, 0.1f, 1000.0f);\n\t\t}\n\n\t\tstatic Audio::Channel_Vorbis* loop = NULL;\n\t\tstatic Audio::Channel_Triangle* triangle = NULL;\n\t\tstatic Audio::Channel_Sine* sine = NULL;\n\t\tif (PRESS(GLFW_KEY_SEMICOLON)) {\n\t\t\tAudio::play_sound(\"..\/Media\/soft-ping.ogg\", false);\n\t\t}\n\t\tif (PRESS(GLFW_KEY_APOSTROPHE)) {\n\t\t\tif (loop) {\n\t\t\t\tAudio::stop(loop);\n\t\t\t\tloop = NULL;\n\t\t\t} else {\n\t\t\t\tloop = Audio::play_sound(\"..\/Media\/loop-test.ogg\", true, .1f);\n\t\t\t}\n\t\t}\n\t\tif (PRESS(GLFW_KEY_LEFT_BRACKET)) {\n\t\t\tif (triangle) {\n\t\t\t\tAudio::stop(triangle);\n\t\t\t\ttriangle = NULL;\n\t\t\t} else {\n\t\t\t\ttriangle = new Audio::Channel_Triangle(440);\n\t\t\t\tAudio::play_channel(triangle);\n\t\t\t}\n\t\t}\n\t\tif (PRESS(GLFW_KEY_RIGHT_BRACKET)) {\n\t\t\tif (sine) {\n\t\t\t\tAudio::stop(sine);\n\t\t\t\tsine = NULL;\n\t\t\t} else {\n\t\t\t\tsine = new Audio::Channel_Sine(440);\n\t\t\t\tAudio::play_channel(sine);\n\t\t\t}\n\t\t}\n\t\t#undef PRESS\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 刷新\n\t\/\/-------------------------------------------------------------------------\n\tvoid EditorMainScene::update() {\n\t\tif (fp_control)\n\t\t\tctl->update_control();\n\t\telse\n\t\t\tctl_fp->update_control();\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 渲染\n\t\/\/-------------------------------------------------------------------------\n\tvoid EditorMainScene::render() {\n\t\tshader_textured.use();\n\n\t\t\/\/ Setup uniforms\n\t\tshader_textured.set_float(\"brightness\", VMDE->state.brightness);\n\t\tshader_textured.set_texture(\"colortex0\", &tile_texture, 0);\n\n\t\tpostBuffer->bind();\n\t\tRenderBuffer::clearColorDepth(0.5, 0.7, 1.0, 0.0);\n\t\tpostBuffer->set_draw_buffers();\n\n\t\t\/\/ Textured blocks rendering\n\t\tshader_textured.ProjectionView(projection, view);\n\t\tmap.render();\n\n\t\tsky->render();\n\n\t\t\/\/ Setup uniforms\n\t\t\/\/ Non textured rendering\n\t\tshader_basic.use();\n\t\tshader_basic.set_float(\"opaque\", 0.5);\n\t\tshader_textured.ProjectionView(projection, view);\n\t\tblock_pointer.mat[0] = obj->transform();\n\t\tblock_pointer.update_instance(1);\n\t\tblock_pointer.render();\n\n\t\taxe.render();\n\n\n\t\tpostBuffer->unbind();\n\t\tpost_processing.use();\n\t\tpost_processing.set_texture(\"colortex\", postBuffer->texture_buffer[0], 0);\n\t\tpost_processing.set_texture(\"gnormal\", postBuffer->texture_buffer[2], 1);\n\t\tglm::vec3 sunVec = glm::mat3(view) * glm::vec3(cos(VMath::PI * 0.25), sin(VMath::PI * 0.25), sin(VMath::PI * 0.25) * 0.3f);\n\t\tglUniform3f(glGetUniformLocation(post_processing.program, \"sunVec\"), sunVec.x, sunVec.y, sunVec.z);\n\t\tPostProcessingManager::Blit2D();\n\n\t\t\/\/ GUI rendering\n\t\tgui.use();\n\t\tgui.set_texture(\"atlastex\", &tile_texture, 0);\n\t\tgui.ProjectionView(gui_2d_projection, glm::mat4(1.0));\n\t\tVMSC::disable_depth_test();\n\t\tif (hand_id > 0) hand_block->renderOnce();\n\n\t\tif (SceneManager::render_debug_info) {\n\t\t\tchar info[64];\n\t\t\tsprintf(info, \"Hand ID: %d Pointer ID: %d\",\n\t\t\t\thand_id,\n\t\t\t\tmap.map->tidQuery(obj->pos.x, obj->pos.y, obj->pos.z)\n\t\t\t);\n\t\t\ttrex->instanceRenderText(\n\t\t\t\tinfo, gui_2d_projection,\n\t\t\t\tglm::mat4(1.0),\n\t\t\t\tglm::translate(glm::mat4(1.0), glm::vec3(0.01, 0.88, 0.0)),\n\t\t\t\t0.025, 0.05, TextRenderer::TextDecorationType::OUTLINE\n\t\t\t);\n\t\t\tsprintf(info, \"Pointer pos: (%.0f, %.0f, %.0f)\",\n\t\t\t\tobj->pos.x, obj->pos.y, obj->pos.z\n\t\t\t);\n\t\t\ttrex->instanceRenderText(\n\t\t\t\tinfo, gui_2d_projection,\n\t\t\t\tglm::mat4(1.0),\n\t\t\t\tglm::translate(glm::mat4(1.0), glm::vec3(0.01, 0.82, 0.0)),\n\t\t\t\t0.025, 0.05, TextRenderer::TextDecorationType::OUTLINE\n\t\t\t);\n\t\t}\n\t\tVMSC::enable_depth_test();\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 释放\n\t\/\/-------------------------------------------------------------------------\n\tEditorMainScene::~EditorMainScene() {\n\t\tfor (int i = 0; i < 16; i++) VMDE_Dispose(delete, clist[i]);\n\t\tVMDE_Dispose(delete, trex);\n\t\tVMDE_Dispose(delete, postBuffer);\n\t}\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2012-2015 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file i2c.cpp\n *\n * Base class for devices attached via the I2C bus.\n *\n * @todo Bus frequency changes; currently we do nothing with the value\n * that is supplied. Should we just depend on the bus knowing?\n *\/\n\n#include \"i2c.h\"\n#ifdef __PX4_LINUX\n#include \n#include \n#endif\n#include \n#include \n#include \n\n#define PX4_SIMULATE_I2C 1\nstatic int simulate = PX4_SIMULATE_I2C;\n\nnamespace device\n{\n\nI2C::I2C(const char *name,\n\t const char *devname,\n\t int bus,\n\t uint16_t address) :\n\t\/\/ base class\n\tVDev(name, devname),\n\t\/\/ public\n\t\/\/ protected\n\t_retries(0),\n\t\/\/ private\n\t_bus(bus),\n\t_address(address),\n\t_fd(-1)\n{\n\twarnx(\"I2C::I2C name = %s devname = %s\", name, devname);\n\t\/\/ fill in _device_id fields for a I2C device\n\t_device_id.devid_s.bus_type = DeviceBusType_I2C;\n\t_device_id.devid_s.bus = bus;\n\t_device_id.devid_s.address = address;\n\t\/\/ devtype needs to be filled in by the driver\n\t_device_id.devid_s.devtype = 0; \n}\n\nI2C::~I2C()\n{\n\tif (_fd >= 0) {\n\t\t::close(_fd);\n\t\t_fd = -1;\n\t}\n}\n\nint\nI2C::init()\n{\n\tint ret = PX4_OK;\n\n\t\/\/ Assume the driver set the desired bus frequency. There is no standard\n\t\/\/ way to set it from user space.\n\n\t\/\/ do base class init, which will create device node, etc\n\tret = VDev::init();\n\n\tif (ret != PX4_OK) {\n\t\tdebug(\"VDev::init failed\");\n\t\treturn ret;\n\t}\n\n\t_fd = px4_open(get_devname(), PX4_F_RDONLY | PX4_F_WRONLY);\n\tif (_fd < 0) {\n\t\tdebug(\"px4_open failed of device %s\", get_devname());\n\t\treturn PX4_ERROR;\n\t}\n\n\tif (simulate) {\n\t\t_fd = 10000;\n\t}\n\telse {\n\t\t\/\/ Open the actual I2C device and map to the virtual dev name\n\t\t_fd = ::open(get_devname(), O_RDWR);\n\t\tif (_fd < 0) {\n\t\t\twarnx(\"could not open %s\", get_devname());\n\t\t\tpx4_errno = errno;\n\t\t\treturn PX4_ERROR;\n\t\t}\n\t}\n\n\treturn ret;\n}\n\nint\nI2C::transfer(const uint8_t *send, unsigned send_len, uint8_t *recv, unsigned recv_len)\n{\n\tstruct i2c_msg msgv[2];\n\tunsigned msgs;\n\tstruct i2c_rdwr_ioctl_data packets;\n\tint ret;\n\tunsigned retry_count = 0;\n\n\tif (_fd < 0) {\n \t\twarnx(\"I2C device not opened\");\n\t\treturn 1;\n\t}\n\n\tdo {\n\t\t\/\/\tdebug(\"transfer out %p\/%u in %p\/%u\", send, send_len, recv, recv_len);\n\t\tmsgs = 0;\n\n\t\tif (send_len > 0) {\n\t\t\tmsgv[msgs].addr = _address;\n\t\t\tmsgv[msgs].flags = 0;\n\t\t\tmsgv[msgs].buf = const_cast(send);\n\t\t\tmsgv[msgs].len = send_len;\n\t\t\tmsgs++;\n\t\t}\n\n\t\tif (recv_len > 0) {\n\t\t\tmsgv[msgs].addr = _address;\n\t\t\tmsgv[msgs].flags = I2C_M_READ;\n\t\t\tmsgv[msgs].buf = recv;\n\t\t\tmsgv[msgs].len = recv_len;\n\t\t\tmsgs++;\n\t\t}\n\n\t\tif (msgs == 0)\n\t\t\treturn -EINVAL;\n\n\t\tpackets.msgs = msgv;\n\t\tpackets.nmsgs = msgs;\n\n\t\tif (simulate) {\n\t\t\twarnx(\"I2C SIM: transfer_4 on %s\", get_devname());\n\t\t\tret = PX4_OK;\n\t\t}\n\t\telse {\n\t\t\tret = ::ioctl(_fd, I2C_RDWR, (unsigned long)&packets);\n\t\t\tif (ret < 0) {\n\t\t\t\twarnx(\"I2C transfer failed\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\n\t\t\/* success *\/\n\t\tif (ret == PX4_OK)\n\t\t\tbreak;\n\n\t} while (retry_count++ < _retries);\n\n\treturn ret;\n}\n\nint\nI2C::transfer(struct i2c_msg *msgv, unsigned msgs)\n{\n\tstruct i2c_rdwr_ioctl_data packets;\n\tint ret;\n\tunsigned retry_count = 0;\n\n\t\/* force the device address into the message vector *\/\n\tfor (unsigned i = 0; i < msgs; i++)\n\t\tmsgv[i].addr = _address;\n\n\tdo {\n\t\tpackets.msgs = msgv;\n\t\tpackets.nmsgs = msgs;\n\n\t\tif (simulate) {\n\t\t\twarnx(\"I2C SIM: transfer_2 on %s\", get_devname());\n\t\t\tret = PX4_OK;\n\t\t}\n\t\telse {\n\t\t\tret = ::ioctl(_fd, I2C_RDWR, (unsigned long)&packets);\n\t\t}\n\t\tif (ret < 0) {\n \t\twarnx(\"I2C transfer failed\");\n \t\treturn 1;\n \t\t}\n\n\t\t\/* success *\/\n\t\tif (ret == PX4_OK)\n\t\t\tbreak;\n\n\t} while (retry_count++ < _retries);\n\n\treturn ret;\n}\n\nint I2C::ioctl(device::file_t *filp, int cmd, unsigned long arg)\n{\n\t\/\/struct i2c_rdwr_ioctl_data *packets = (i2c_rdwr_ioctl_data *)(void *)arg;\n\n\tswitch (cmd) {\n\tcase I2C_RDWR:\n \twarnx(\"Use I2C::transfer, not ioctl\");\n\t\treturn 0;\n\tdefault:\n\t\t\/* give it to the superclass *\/\n\t\treturn VDev::ioctl(filp, cmd, arg);\n\t}\n}\n\nssize_t\tI2C::read(file_t *filp, char *buffer, size_t buflen)\n{\n\tif (simulate) {\n\t\t\/\/ FIXME no idea what this should be\n\t\twarnx (\"2C SIM I2C::read\");\n\t\treturn 0;\n\t}\n\n\treturn ::read(_fd, buffer, buflen);\n}\n\nssize_t\tI2C::write(file_t *filp, const char *buffer, size_t buflen)\n{\n\tif (simulate) {\n\t\twarnx (\"2C SIM I2C::write\");\n\t\treturn buflen;\n\t}\n\n\treturn ::write(_fd, buffer, buflen);\n}\n\n} \/\/ namespace device\nRemoved annoying \"I2C SIM transfer_4\" message\/****************************************************************************\n *\n * Copyright (c) 2012-2015 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file i2c.cpp\n *\n * Base class for devices attached via the I2C bus.\n *\n * @todo Bus frequency changes; currently we do nothing with the value\n * that is supplied. Should we just depend on the bus knowing?\n *\/\n\n#include \"i2c.h\"\n#ifdef __PX4_LINUX\n#include \n#include \n#endif\n#include \n#include \n#include \n\n#define PX4_SIMULATE_I2C 1\nstatic int simulate = PX4_SIMULATE_I2C;\n\nnamespace device\n{\n\nI2C::I2C(const char *name,\n\t const char *devname,\n\t int bus,\n\t uint16_t address) :\n\t\/\/ base class\n\tVDev(name, devname),\n\t\/\/ public\n\t\/\/ protected\n\t_retries(0),\n\t\/\/ private\n\t_bus(bus),\n\t_address(address),\n\t_fd(-1)\n{\n\twarnx(\"I2C::I2C name = %s devname = %s\", name, devname);\n\t\/\/ fill in _device_id fields for a I2C device\n\t_device_id.devid_s.bus_type = DeviceBusType_I2C;\n\t_device_id.devid_s.bus = bus;\n\t_device_id.devid_s.address = address;\n\t\/\/ devtype needs to be filled in by the driver\n\t_device_id.devid_s.devtype = 0; \n}\n\nI2C::~I2C()\n{\n\tif (_fd >= 0) {\n\t\t::close(_fd);\n\t\t_fd = -1;\n\t}\n}\n\nint\nI2C::init()\n{\n\tint ret = PX4_OK;\n\n\t\/\/ Assume the driver set the desired bus frequency. There is no standard\n\t\/\/ way to set it from user space.\n\n\t\/\/ do base class init, which will create device node, etc\n\tret = VDev::init();\n\n\tif (ret != PX4_OK) {\n\t\tdebug(\"VDev::init failed\");\n\t\treturn ret;\n\t}\n\n\t_fd = px4_open(get_devname(), PX4_F_RDONLY | PX4_F_WRONLY);\n\tif (_fd < 0) {\n\t\tdebug(\"px4_open failed of device %s\", get_devname());\n\t\treturn PX4_ERROR;\n\t}\n\n\tif (simulate) {\n\t\t_fd = 10000;\n\t}\n\telse {\n\t\t\/\/ Open the actual I2C device and map to the virtual dev name\n\t\t_fd = ::open(get_devname(), O_RDWR);\n\t\tif (_fd < 0) {\n\t\t\twarnx(\"could not open %s\", get_devname());\n\t\t\tpx4_errno = errno;\n\t\t\treturn PX4_ERROR;\n\t\t}\n\t}\n\n\treturn ret;\n}\n\nint\nI2C::transfer(const uint8_t *send, unsigned send_len, uint8_t *recv, unsigned recv_len)\n{\n\tstruct i2c_msg msgv[2];\n\tunsigned msgs;\n\tstruct i2c_rdwr_ioctl_data packets;\n\tint ret;\n\tunsigned retry_count = 0;\n\n\tif (_fd < 0) {\n \t\twarnx(\"I2C device not opened\");\n\t\treturn 1;\n\t}\n\n\tdo {\n\t\t\/\/\tdebug(\"transfer out %p\/%u in %p\/%u\", send, send_len, recv, recv_len);\n\t\tmsgs = 0;\n\n\t\tif (send_len > 0) {\n\t\t\tmsgv[msgs].addr = _address;\n\t\t\tmsgv[msgs].flags = 0;\n\t\t\tmsgv[msgs].buf = const_cast(send);\n\t\t\tmsgv[msgs].len = send_len;\n\t\t\tmsgs++;\n\t\t}\n\n\t\tif (recv_len > 0) {\n\t\t\tmsgv[msgs].addr = _address;\n\t\t\tmsgv[msgs].flags = I2C_M_READ;\n\t\t\tmsgv[msgs].buf = recv;\n\t\t\tmsgv[msgs].len = recv_len;\n\t\t\tmsgs++;\n\t\t}\n\n\t\tif (msgs == 0)\n\t\t\treturn -EINVAL;\n\n\t\tpackets.msgs = msgv;\n\t\tpackets.nmsgs = msgs;\n\n\t\tif (simulate) {\n\t\t\t\/\/warnx(\"I2C SIM: transfer_4 on %s\", get_devname());\n\t\t\tret = PX4_OK;\n\t\t}\n\t\telse {\n\t\t\tret = ::ioctl(_fd, I2C_RDWR, (unsigned long)&packets);\n\t\t\tif (ret < 0) {\n\t\t\t\twarnx(\"I2C transfer failed\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\n\t\t\/* success *\/\n\t\tif (ret == PX4_OK)\n\t\t\tbreak;\n\n\t} while (retry_count++ < _retries);\n\n\treturn ret;\n}\n\nint\nI2C::transfer(struct i2c_msg *msgv, unsigned msgs)\n{\n\tstruct i2c_rdwr_ioctl_data packets;\n\tint ret;\n\tunsigned retry_count = 0;\n\n\t\/* force the device address into the message vector *\/\n\tfor (unsigned i = 0; i < msgs; i++)\n\t\tmsgv[i].addr = _address;\n\n\tdo {\n\t\tpackets.msgs = msgv;\n\t\tpackets.nmsgs = msgs;\n\n\t\tif (simulate) {\n\t\t\twarnx(\"I2C SIM: transfer_2 on %s\", get_devname());\n\t\t\tret = PX4_OK;\n\t\t}\n\t\telse {\n\t\t\tret = ::ioctl(_fd, I2C_RDWR, (unsigned long)&packets);\n\t\t}\n\t\tif (ret < 0) {\n \t\twarnx(\"I2C transfer failed\");\n \t\treturn 1;\n \t\t}\n\n\t\t\/* success *\/\n\t\tif (ret == PX4_OK)\n\t\t\tbreak;\n\n\t} while (retry_count++ < _retries);\n\n\treturn ret;\n}\n\nint I2C::ioctl(device::file_t *filp, int cmd, unsigned long arg)\n{\n\t\/\/struct i2c_rdwr_ioctl_data *packets = (i2c_rdwr_ioctl_data *)(void *)arg;\n\n\tswitch (cmd) {\n\tcase I2C_RDWR:\n \twarnx(\"Use I2C::transfer, not ioctl\");\n\t\treturn 0;\n\tdefault:\n\t\t\/* give it to the superclass *\/\n\t\treturn VDev::ioctl(filp, cmd, arg);\n\t}\n}\n\nssize_t\tI2C::read(file_t *filp, char *buffer, size_t buflen)\n{\n\tif (simulate) {\n\t\t\/\/ FIXME no idea what this should be\n\t\twarnx (\"2C SIM I2C::read\");\n\t\treturn 0;\n\t}\n\n\treturn ::read(_fd, buffer, buflen);\n}\n\nssize_t\tI2C::write(file_t *filp, const char *buffer, size_t buflen)\n{\n\tif (simulate) {\n\t\twarnx (\"2C SIM I2C::write\");\n\t\treturn buflen;\n\t}\n\n\treturn ::write(_fd, buffer, buflen);\n}\n\n} \/\/ namespace device\n<|endoftext|>"} {"text":"\/******************************************************************************\n* Copyright (c) 2014, Connor Manning (connor@hobu.co)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include \n#include \"Exchanges.hpp\"\n\nnamespace pdal\n{\nnamespace drivers\n{\nnamespace greyhound\n{\n\nGreyhoundReader::GreyhoundReader(const Options& options)\n : Reader(options)\n , m_uri()\n , m_pipelineId()\n , m_sessionId()\n , m_dims()\n , m_numPoints()\n , m_wsClient()\n{ }\n\nGreyhoundReader::~GreyhoundReader()\n{\n exchanges::Destroy exchange(m_sessionId);\n m_wsClient.exchange(exchange);\n}\n\nOptions GreyhoundReader::getDefaultOptions()\n{\n Options options;\n return options;\n}\n\nstd::vector GreyhoundReader::getDefaultDimensions()\n{\n std::vector output;\n\n \/\/ TODO\n\n return output;\n}\n\nStageSequentialIterator* GreyhoundReader::createSequentialIterator() const\n{\n return new iterators::sequential::Iterator(\n const_cast(m_wsClient), \/\/ TODO\n m_sessionId,\n m_numPoints,\n m_schema.getByteSize());\n}\n\nvoid GreyhoundReader::processOptions(const Options& options)\n{\n m_uri = options.getValueOrThrow(\"uri\");\n m_pipelineId = options.getValueOrThrow(\"pipelineId\");\n\n m_wsClient.initialize(m_uri);\n}\n\nvoid GreyhoundReader::buildSchema(Schema* schema)\n{\n Json::Value jsonResponse;\n Json::Reader jsonReader;\n\n \/\/ Create session.\n {\n exchanges::CreateSession exchange(m_pipelineId);\n m_wsClient.exchange(exchange);\n m_sessionId = exchange.getSession();\n }\n\n \/\/ Get schema\n {\n exchanges::GetSchema exchange(m_sessionId);\n m_wsClient.exchange(exchange);\n m_schema = Schema::from_xml(exchange.schema());\n\n schema = &m_schema;\n }\n}\n\nvoid GreyhoundReader::ready(PointContext ctx)\n{\n Json::Value jsonResponse;\n Json::Reader jsonReader;\n\n \/\/ Get number of points.\n {\n exchanges::GetNumPoints exchange(m_sessionId);\n m_wsClient.exchange(exchange);\n m_numPoints = exchange.count();\n }\n}\n\nnamespace iterators\n{\n\nsequential::Iterator::Iterator(\n WebSocketClient& wsClient,\n std::string sessionId,\n point_count_t numPoints,\n schema::size_type byteSize)\n : m_wsClient(wsClient)\n , m_sessionId(sessionId)\n , m_numPoints(numPoints)\n , m_byteSize(byteSize)\n{ }\n\npoint_count_t sequential::Iterator::readImpl(\n PointBuffer& pointBuffer,\n point_count_t count)\n{\n Json::Value jsonResponse;\n Json::Reader jsonReader;\n\n exchanges::Read exchange(m_sessionId, m_index, count);\n m_wsClient.exchange(exchange);\n std::vector data(exchange.data());\n point_count_t numRead(exchange.numRead());\n\n std::vector& rawBuffer(\n pointBuffer.context().rawPtBuf()->getBuffer());\n\n std::cout << \"PB: \" << pointBuffer.size() << std::endl;\n\n for (std::size_t i(0); i < data.size(); ++i)\n {\n std::memcpy(\n rawBuffer.data() + (m_index * m_byteSize),\n data[i]->data(),\n data[i]->size());\n\n m_index += data[i]->size();\n }\n\n return numRead;\n}\n\nboost::uint64_t sequential::Iterator::skipImpl(\n const boost::uint64_t pointsToSkip)\n{\n const boost::uint64_t skipped(\n std::min(pointsToSkip, m_numPoints - m_index));\n m_index = std::min(m_index + pointsToSkip, m_numPoints);\n return skipped;\n}\n\nbool sequential::Iterator::atEndImpl() const\n{\n return m_index >= m_numPoints;\n}\n\n} \/\/ namespace iterators\n\n} \/\/ namespace greyhound\n} \/\/ namespace drivers\n} \/\/ namespace pdal\n\nSimplify exchange variables in Reader.\/******************************************************************************\n* Copyright (c) 2014, Connor Manning (connor@hobu.co)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include \n#include \"Exchanges.hpp\"\n\nnamespace pdal\n{\nnamespace drivers\n{\nnamespace greyhound\n{\n\nGreyhoundReader::GreyhoundReader(const Options& options)\n : Reader(options)\n , m_uri()\n , m_pipelineId()\n , m_sessionId()\n , m_dims()\n , m_numPoints()\n , m_wsClient()\n{ }\n\nGreyhoundReader::~GreyhoundReader()\n{\n exchanges::Destroy destroyExchange(m_sessionId);\n m_wsClient.exchange(destroyExchange);\n}\n\nOptions GreyhoundReader::getDefaultOptions()\n{\n Options options;\n return options;\n}\n\nstd::vector GreyhoundReader::getDefaultDimensions()\n{\n std::cout << \"DIMS\" << std::endl;\n std::vector output;\n\n return output;\n}\n\nStageSequentialIterator* GreyhoundReader::createSequentialIterator() const\n{\n std::cout << \"CREATING ITERATOR: \" << m_numPoints << std::endl;\n return new iterators::sequential::Iterator(\n const_cast(m_wsClient),\n m_sessionId,\n m_numPoints,\n m_schema.getByteSize());\n}\n\nvoid GreyhoundReader::processOptions(const Options& options)\n{\n m_uri = options.getValueOrThrow(\"uri\");\n m_pipelineId = options.getValueOrThrow(\"pipelineId\");\n\n m_wsClient.initialize(m_uri);\n}\n\nvoid GreyhoundReader::buildSchema(Schema* schema)\n{\n std::cout << \"BUILD SCHEMA\" << std::endl;\n Json::Value jsonResponse;\n Json::Reader jsonReader;\n\n \/\/ Create session.\n exchanges::CreateSession createExchange(m_pipelineId);\n m_wsClient.exchange(createExchange);\n m_sessionId = createExchange.getSession();\n\n \/\/ Get schema\n exchanges::GetSchema schemaExchange(m_sessionId);\n m_wsClient.exchange(schemaExchange);\n m_schema = Schema::from_xml(schemaExchange.schema());\n\n schema::Map dims(m_schema.getDimensions());\n for (auto dim = dims.begin(); dim != dims.end(); ++dim)\n {\n m_dims.push_back(schema->appendDimension(*dim));\n }\n}\n\nvoid GreyhoundReader::ready(PointContext ctx)\n{\n std::cout << \"READY\" << std::endl;\n Json::Value jsonResponse;\n Json::Reader jsonReader;\n\n \/\/ Get number of points.\n exchanges::GetNumPoints numPointsExchange(m_sessionId);\n m_wsClient.exchange(numPointsExchange);\n m_numPoints = numPointsExchange.count();\n}\n\nnamespace iterators\n{\n\nsequential::Iterator::Iterator(\n WebSocketClient& wsClient,\n std::string sessionId,\n point_count_t numPoints,\n schema::size_type byteSize)\n : m_wsClient(wsClient)\n , m_sessionId(sessionId)\n , m_numPoints(numPoints)\n , m_byteSize(byteSize)\n{ }\n\npoint_count_t sequential::Iterator::readImpl(\n PointBuffer& pointBuffer,\n point_count_t count)\n{\n Json::Value jsonResponse;\n Json::Reader jsonReader;\n\n exchanges::Read readExchange(m_sessionId, m_index, count);\n m_wsClient.exchange(readExchange);\n std::vector data(readExchange.data());\n point_count_t numRead(readExchange.numRead());\n\n std::vector& rawBuffer(\n pointBuffer.context().rawPtBuf()->getBuffer());\n\n std::cout << \"PB: \" << pointBuffer.size() << std::endl;\n\n for (std::size_t i(0); i < data.size(); ++i)\n {\n std::memcpy(\n rawBuffer.data() + (m_index * m_byteSize),\n data[i]->data(),\n data[i]->size());\n\n m_index += data[i]->size();\n }\n\n return numRead;\n}\n\nboost::uint64_t sequential::Iterator::skipImpl(\n const boost::uint64_t pointsToSkip)\n{\n const boost::uint64_t skipped(\n std::min(pointsToSkip, m_numPoints - m_index));\n m_index = std::min(m_index + pointsToSkip, m_numPoints);\n return skipped;\n}\n\nbool sequential::Iterator::atEndImpl() const\n{\n return m_index >= m_numPoints;\n}\n\n} \/\/ namespace iterators\n\n} \/\/ namespace greyhound\n} \/\/ namespace drivers\n} \/\/ namespace pdal\n\n<|endoftext|>"} {"text":"\/*****************************************************************************\n Copyright 2004-2008 Steve Ménard\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n\t http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n \n *****************************************************************************\/\n#include \n\nJPStringClass::JPStringClass() : JPClass(JPJni::s_StringClass)\n{\n}\n\nJPStringClass::~JPStringClass()\n{\n}\n\nJPPyObject JPStringClass::convertToPythonObject(jvalue val)\n{\n\tJP_TRACE_IN(\"JPStringType::asHostObject\");\n\n\tif (val.l == NULL)\n\t{\n\t\treturn JPPyObject::getNone();\n\t}\n\n if (JPEnv::getConvertStrings())\n {\n\t\tstring str = JPJni::toStringUTF8((jstring)(val.l));\n\t\treturn JPPyString::fromStringUTF8(str);\n }\n\n\treturn JPPythonEnv::newJavaObject(JPValue(this, val));\n\tJP_TRACE_OUT;\n}\n\nJPMatch::Type JPStringClass::canConvertToJava(PyObject* obj)\n{\n\tJP_TRACE_IN(\"JPStringType::canConvertToJava\");\n\tASSERT_NOT_NULL(obj);\n\n\tif (obj == NULL || JPPyObject::isNone(obj))\n\t{\n\t\treturn JPMatch::_implicit;\n\t}\n\n\tJPValue* value = JPPythonEnv::getJavaValue(obj);\n\tif (value != NULL)\n\t{\n\t\tif (value->getClass() == this)\n\t\t{\n\t\t\treturn JPMatch::_exact;\n\t\t}\n\t\treturn JPMatch::_none;\n\t}\n\n\tif (JPPyString::check(obj))\n\t{\n\t\treturn JPMatch::_exact;\n\t}\n\n\treturn JPMatch::_none;\n\tJP_TRACE_OUT;\n}\n\njvalue JPStringClass::convertToJava(PyObject* obj)\n{\n\tJP_TRACE_IN(\"JPStringType::convertToJava\");\n\tJPJavaFrame frame;\n\tjvalue res;\n\tres.l = NULL;\n\n\tif (JPPyObject::isNone(obj))\n\t{\n\t\treturn res;\n\t}\n\n\t\/\/ java.lang.string is already a global object \n\tJPValue* value = JPPythonEnv::getJavaValue(obj);\n\tif (value != NULL)\n\t{\n\t\tif (value->getClass() == this)\n\t\t{\n\t\t\tres.l = frame.NewLocalRef(value->getJavaObject());\n\t\t\tres.l = frame.keep(res.l);\n\t\t\treturn res;\n\t\t}\n\t\tJP_RAISE_TYPE_ERROR(\"Attempt to convert a non string java object\");\n\t}\n\n\t\/\/ Otherwise convert the string\n\tif (JPPyString::check(obj))\n\t{\n\t\tstring str = JPPyString::asStringUTF8(obj);\n\t\tjstring jstr = JPJni::fromStringUTF8(str);\n\t\tres.l = frame.keep(jstr);\n\t\treturn res;\n\t}\n\tJP_RAISE_TYPE_ERROR(\"Unable to convert to java string\");\n\treturn res;\n\tJP_TRACE_OUT;\n}\n\nJPValue JPStringClass::newInstance(JPPyObjectVector& args)\n{\n\tJP_TRACE_IN(\"JPStringClass::newInstance\");\n\tif (args.size() == 1 && JPPyString::check(args[0]))\n\t{\n\t\t\/\/ JNI has a short cut for constructing java.lang.String\n\t\tJP_TRACE(\"Direct\");\n\t\tstring str = JPPyString::asStringUTF8(args[0]);\n\t\tjvalue res;\n\t\tres.l = JPJni::fromStringUTF8(str);\n\t\treturn JPValue(this, res);\n\t}\n\treturn JPClass::newInstance(args);\n\tJP_TRACE_OUT;\n}\nUnicode\/str polymorphic return\/*****************************************************************************\n Copyright 2004-2008 Steve Ménard\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n\t http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n *****************************************************************************\/\n#include \n\nJPStringClass::JPStringClass() : JPClass(JPJni::s_StringClass)\n{\n}\n\nJPStringClass::~JPStringClass()\n{\n}\n\nJPPyObject JPStringClass::convertToPythonObject(jvalue val)\n{\n\tJP_TRACE_IN(\"JPStringType::asHostObject\");\n\n\tif (val.l == NULL)\n\t{\n\t\treturn JPPyObject::getNone();\n\t}\n\n\tif (JPEnv::getConvertStrings())\n\t{\n\t\tbool unicode = false;\n\t\tstring str = JPJni::toStringUTF8((jstring) (val.l));\n#if PY_MAJOR_VERSION < 3\n\t\tfor (int i = 0; i < str.size(); ++i)\n\t\t{\n\t\t\tif (str[i]&0x80)\n\t\t\t{\n\t\t\t\tunicode = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n#endif\n\t\treturn JPPyString::fromStringUTF8(str, unicode);\n\t}\n\n\treturn JPPythonEnv::newJavaObject(JPValue(this, val));\n\tJP_TRACE_OUT;\n}\n\nJPMatch::Type JPStringClass::canConvertToJava(PyObject* obj)\n{\n\tJP_TRACE_IN(\"JPStringType::canConvertToJava\");\n\tASSERT_NOT_NULL(obj);\n\n\tif (obj == NULL || JPPyObject::isNone(obj))\n\t{\n\t\treturn JPMatch::_implicit;\n\t}\n\n\tJPValue* value = JPPythonEnv::getJavaValue(obj);\n\tif (value != NULL)\n\t{\n\t\tif (value->getClass() == this)\n\t\t{\n\t\t\treturn JPMatch::_exact;\n\t\t}\n\t\treturn JPMatch::_none;\n\t}\n\n\tif (JPPyString::check(obj))\n\t{\n\t\treturn JPMatch::_exact;\n\t}\n\n\treturn JPMatch::_none;\n\tJP_TRACE_OUT;\n}\n\njvalue JPStringClass::convertToJava(PyObject* obj)\n{\n\tJP_TRACE_IN(\"JPStringType::convertToJava\");\n\tJPJavaFrame frame;\n\tjvalue res;\n\tres.l = NULL;\n\n\tif (JPPyObject::isNone(obj))\n\t{\n\t\treturn res;\n\t}\n\n\t\/\/ java.lang.string is already a global object\n\tJPValue* value = JPPythonEnv::getJavaValue(obj);\n\tif (value != NULL)\n\t{\n\t\tif (value->getClass() == this)\n\t\t{\n\t\t\tres.l = frame.NewLocalRef(value->getJavaObject());\n\t\t\tres.l = frame.keep(res.l);\n\t\t\treturn res;\n\t\t}\n\t\tJP_RAISE_TYPE_ERROR(\"Attempt to convert a non string java object\");\n\t}\n\n\t\/\/ Otherwise convert the string\n\tif (JPPyString::check(obj))\n\t{\n\t\tstring str = JPPyString::asStringUTF8(obj);\n\t\tjstring jstr = JPJni::fromStringUTF8(str);\n\t\tres.l = frame.keep(jstr);\n\t\treturn res;\n\t}\n\tJP_RAISE_TYPE_ERROR(\"Unable to convert to java string\");\n\treturn res;\n\tJP_TRACE_OUT;\n}\n\nJPValue JPStringClass::newInstance(JPPyObjectVector& args)\n{\n\tJP_TRACE_IN(\"JPStringClass::newInstance\");\n\tif (args.size() == 1 && JPPyString::check(args[0]))\n\t{\n\t\t\/\/ JNI has a short cut for constructing java.lang.String\n\t\tJP_TRACE(\"Direct\");\n\t\tstring str = JPPyString::asStringUTF8(args[0]);\n\t\tjvalue res;\n\t\tres.l = JPJni::fromStringUTF8(str);\n\t\treturn JPValue(this, res);\n\t}\n\treturn JPClass::newInstance(args);\n\tJP_TRACE_OUT;\n}\n<|endoftext|>"} {"text":"Added low-priority FIXME comment.<|endoftext|>"} {"text":"format: change way how tags are set in pbf<|endoftext|>"} {"text":"\/\/ Copyright (C) 2019 European Spallation Source ERIC\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/\/ \\todo Should not belong to gdgem but to common, reduction?\nnamespace Gem {\n\n\/\/\nvoid HitGenerator::printHits() {\n for (auto & Hit : Hits) {\n fmt::print(\"t {}, p {}, c {}, w {}\\n\", Hit.time, Hit.plane, Hit.coordinate, Hit.weight);\n }\n}\n\n\/\/\nvoid HitGenerator::printEvents() {\n fmt::print(\"t (x, y)\\n\");\n for (auto & Event : Events) {\n fmt::print(\"{} ({}, {})\\n\", Event.TimeNs, Event.XPos, Event.YPos);\n }\n}\n\n\/\/\nstd::vector & HitGenerator::randomEvents(int NumEvents, int MinCoord, int MaxCoord) {\n auto TimeNs = T0;\n std::uniform_int_distribution coords(MinCoord, MaxCoord);\n for (int i = 0; i < NumEvents; i++) {\n auto XPos = coords(RandGen);\n auto YPos = coords(RandGen);\n \/\/fmt::print(\"Event: ({}, {}), t={}\\n\", XPos, YPos, Time);\n Events.push_back({XPos, YPos, TimeNs});\n TimeNs += TGap;\n }\n return Events;\n}\n\n\/\/\nstd::vector & HitGenerator::randomHits(int MaxHits, int Gaps, int DeadTimeNs, bool Shuffle) {\n std::uniform_int_distribution angle(0, 360);\n for (auto & Event : Events) {\n auto Degrees = angle(RandGen);\n \/\/fmt::print(\"({},{}) @ {}\\n\", Event.XPos, Event.YPos, Degrees);\n makeHitsForSinglePlane(0, MaxHits, Event.XPos, Event.YPos, Degrees, Gaps, DeadTimeNs, Shuffle);\n makeHitsForSinglePlane(1, MaxHits, Event.XPos, Event.YPos, Degrees, Gaps, DeadTimeNs, Shuffle);\n advanceTime(TGap);\n }\n return Hits;\n}\n\n\/\/\nstd::vector & HitGenerator::makeHitsForSinglePlane(int Plane, int MaxHits,\n float X0, float Y0, float Angle, int Gaps, int DeadTimeNs, bool Shuffle) {\n int64_t TimeNs = T0;\n int32_t OldTime = TimeNs;\n float TmpCoord{0};\n int Coord{32767}, OldCoord{32767};\n uint16_t ADC{2345};\n std::vector TmpHits;\n\n if ((Plane != PlaneX) and (Plane != PlaneY)) {\n return Hits;\n }\n\n for (int hit = 0; hit < MaxHits; hit++) {\n if (Plane == PlaneX) {\n TmpCoord = X0 + hit * 1.0 * cos(D2R(Angle));\n \/\/fmt::print(\"X0 {}, RO {}, Angle {}, cos(angle) {}, TmpCoord {}\\n\", X0, hit, Angle, cosa, TmpCoord);\n } else {\n TmpCoord = Y0 + hit * 1.0 * sin(D2R(Angle));\n }\n\n Coord = (int)TmpCoord;\n if ((Coord > CoordMax) or (Coord < CoordMin)) {\n continue;\n }\n\n \/\/ Same coordinate - time gap is critical\n if (Coord == OldCoord) {\n \/\/fmt::print(\"Same coordinate, OldTime {}, Time {}\\n\", OldTime, Time);\n if ((OldTime != TimeNs) and (TimeNs - OldTime < DeadTimeNs) ) {\n \/\/ Not the first Hit but within deadtime\n \/\/fmt::print(\" dT {} shorter than deadtime - skipping\\n\", Time - OldTime);\n TimeNs += DeltaT;\n continue;\n }\n }\n\n Hit CurrHit{(uint64_t)TimeNs, (uint16_t)Coord, ADC, (uint8_t)Plane};\n TmpHits.push_back(CurrHit);\n OldTime = TimeNs;\n TimeNs += DeltaT;\n OldCoord = Coord;\n }\n\n \/\/ Handle gaps\n TmpHits = makeGaps(TmpHits, Gaps);\n\n if (Shuffle) {\n std::shuffle(TmpHits.begin(), TmpHits.end(), RandGen);\n }\n\n for (auto &Hit : TmpHits) {\n Hits.push_back(Hit);\n }\n return Hits;\n}\n\n\/\/\nstd::vector & HitGenerator::makeGaps(std::vector & Hits, uint8_t Gaps) {\n if (Gaps == 0) {\n return Hits;\n }\n std::vector GapHits;\n if (Gaps > Hits.size() - 2) {\n \/\/fmt::print(\"Gaps requestes {}, available {}\\n\", Gaps, TmpHits.size() - 2);\n Hits.clear();\n }\n for (unsigned int i = 0; i < Hits.size(); i ++) {\n if ((i == 0) or (i > Gaps)) {\n GapHits.push_back(Hits[i]);\n }\n }\n Hits = GapHits;\n return Hits;\n}\n\n} \/\/ namespace\nMore GCC fixes.\/\/ Copyright (C) 2019 European Spallation Source ERIC\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/\/ \\todo Should not belong to gdgem but to common, reduction?\nnamespace Gem {\n\n\/\/\nvoid HitGenerator::printHits() {\n for (auto & Hit : Hits) {\n fmt::print(\"t {}, p {}, c {}, w {}\\n\", uint64_t(Hit.time), int(Hit.plane), int(Hit.coordinate), int(Hit.weight));\n }\n}\n\n\/\/\nvoid HitGenerator::printEvents() {\n fmt::print(\"t (x, y)\\n\");\n for (auto & Event : Events) {\n fmt::print(\"{} ({}, {})\\n\", Event.TimeNs, Event.XPos, Event.YPos);\n }\n}\n\n\/\/\nstd::vector & HitGenerator::randomEvents(int NumEvents, int MinCoord, int MaxCoord) {\n auto TimeNs = T0;\n std::uniform_int_distribution coords(MinCoord, MaxCoord);\n for (int i = 0; i < NumEvents; i++) {\n auto XPos = coords(RandGen);\n auto YPos = coords(RandGen);\n \/\/fmt::print(\"Event: ({}, {}), t={}\\n\", XPos, YPos, Time);\n Events.push_back({XPos, YPos, TimeNs});\n TimeNs += TGap;\n }\n return Events;\n}\n\n\/\/\nstd::vector & HitGenerator::randomHits(int MaxHits, int Gaps, int DeadTimeNs, bool Shuffle) {\n std::uniform_int_distribution angle(0, 360);\n for (auto & Event : Events) {\n auto Degrees = angle(RandGen);\n \/\/fmt::print(\"({},{}) @ {}\\n\", Event.XPos, Event.YPos, Degrees);\n makeHitsForSinglePlane(0, MaxHits, Event.XPos, Event.YPos, Degrees, Gaps, DeadTimeNs, Shuffle);\n makeHitsForSinglePlane(1, MaxHits, Event.XPos, Event.YPos, Degrees, Gaps, DeadTimeNs, Shuffle);\n advanceTime(TGap);\n }\n return Hits;\n}\n\n\/\/\nstd::vector & HitGenerator::makeHitsForSinglePlane(int Plane, int MaxHits,\n float X0, float Y0, float Angle, int Gaps, int DeadTimeNs, bool Shuffle) {\n int64_t TimeNs = T0;\n int32_t OldTime = TimeNs;\n float TmpCoord{0};\n int Coord{32767}, OldCoord{32767};\n uint16_t ADC{2345};\n std::vector TmpHits;\n\n if ((Plane != PlaneX) and (Plane != PlaneY)) {\n return Hits;\n }\n\n for (int hit = 0; hit < MaxHits; hit++) {\n if (Plane == PlaneX) {\n TmpCoord = X0 + hit * 1.0 * cos(D2R(Angle));\n \/\/fmt::print(\"X0 {}, RO {}, Angle {}, cos(angle) {}, TmpCoord {}\\n\", X0, hit, Angle, cosa, TmpCoord);\n } else {\n TmpCoord = Y0 + hit * 1.0 * sin(D2R(Angle));\n }\n\n Coord = (int)TmpCoord;\n if ((Coord > CoordMax) or (Coord < CoordMin)) {\n continue;\n }\n\n \/\/ Same coordinate - time gap is critical\n if (Coord == OldCoord) {\n \/\/fmt::print(\"Same coordinate, OldTime {}, Time {}\\n\", OldTime, Time);\n if ((OldTime != TimeNs) and (TimeNs - OldTime < DeadTimeNs) ) {\n \/\/ Not the first Hit but within deadtime\n \/\/fmt::print(\" dT {} shorter than deadtime - skipping\\n\", Time - OldTime);\n TimeNs += DeltaT;\n continue;\n }\n }\n\n Hit CurrHit{(uint64_t)TimeNs, (uint16_t)Coord, ADC, (uint8_t)Plane};\n TmpHits.push_back(CurrHit);\n OldTime = TimeNs;\n TimeNs += DeltaT;\n OldCoord = Coord;\n }\n\n \/\/ Handle gaps\n TmpHits = makeGaps(TmpHits, Gaps);\n\n if (Shuffle) {\n std::shuffle(TmpHits.begin(), TmpHits.end(), RandGen);\n }\n\n for (auto &Hit : TmpHits) {\n Hits.push_back(Hit);\n }\n return Hits;\n}\n\n\/\/\nstd::vector & HitGenerator::makeGaps(std::vector & Hits, uint8_t Gaps) {\n if (Gaps == 0) {\n return Hits;\n }\n std::vector GapHits;\n if (Gaps > Hits.size() - 2) {\n \/\/fmt::print(\"Gaps requestes {}, available {}\\n\", Gaps, TmpHits.size() - 2);\n Hits.clear();\n }\n for (unsigned int i = 0; i < Hits.size(); i ++) {\n if ((i == 0) or (i > Gaps)) {\n GapHits.push_back(Hits[i]);\n }\n }\n Hits = GapHits;\n return Hits;\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"removed unnecessary dijkstra.h include<|endoftext|>"} {"text":"#include \"..\/..\/include\/client0\/retrieveFileList.hpp\"\n\nbool retrieveFileList( sf::TcpSocket& server, std::string current_directory ){\n\n\tsf::Packet spacket;\n\t\n\tspacket << current_directory << Ls;\n\tserver.send( spacket );\n\tspacket.clear();\n\n\tsf::Int32 file;\n\tunsigned int filename_length;\n\n\tserver.receive( spacket );\n\tspacket >> file;\n\tspacket.clear();\n\n\tif( static_cast(file) == ServerFailure ){\n\t\tstd::cout << \"ServerFailure\" << std::endl;\n\t\treturn false;\n\t}\n\n\n\tstd::vector directory_array;\n\n\tdo{\n\t\tserver.receive( spacket );\n\t\t\n\t\tdirectory_array.push_back( std::wstring(L\"\") );\n\t\tspacket >> filename_length;\n\n\t\tfor( unsigned int i(0) ; i < filename_length ; ++i ){\n\n\t\t\tspacket >> file;\n\t\t\tdirectory_array.back() += static_cast( file );\n\t\t}\n\t\tspacket.clear();\n\n\t}while( filename_length != 0 );\n\n\tstd::sort( directory_array.begin(), directory_array.end() );\n\tstd::cout << std::endl;\n\n\tsetColors(\"light blue\"); \/\/for folders\n\n\tfor( unsigned int i(3) ; i < directory_array.size() ; ++i )\n\t\tif( directory_array[i][directory_array[i].size()-1] == '\/' )\n\t\t\tstd::wcout << directory_array[i] << std::endl;\n\n\tsetColors(\"light green\"); \/\/for files\n\n\tfor( unsigned int i(3) ; i < directory_array.size() ; ++i )\n\t\tif( directory_array[i][directory_array[i].size()-1] != '\/' )\n\t\t\tstd::wcout << directory_array[i] << std::endl;\n\n\tstd::cout << std::endl;\n\tsetColors(\"reset\");\n\n\treturn true;\n}\nDebugging ls#include \"..\/..\/include\/client0\/retrieveFileList.hpp\"\n\nbool retrieveFileList( sf::TcpSocket& server, std::string current_directory ){\n\n\tsf::Packet spacket;\n\t\n\tspacket << current_directory << Ls;\n\tserver.send( spacket );\n\tspacket.clear();\n\n\tsf::Int32 file;\n\tunsigned int filename_length;\n\n\tserver.receive( spacket );\n\tspacket >> file;\n\tspacket.clear();\n\n\tif( static_cast(file) == ServerFailure ){\n\t\tstd::cout << \"ServerFailure\" << std::endl;\n\t\treturn false;\n\t}\n\n\n\tstd::vector directory_array;\n\n\tdo{\n\t\tserver.receive( spacket );\n\t\t\n\t\tdirectory_array.push_back( std::wstring(L\"\") );\n\t\tspacket >> filename_length;\n\n\t\tfor( unsigned int i(0) ; i < filename_length ; ++i ){\n\n\t\t\tspacket >> file;\n\t\t\tdirectory_array.back() += static_cast( file );\n\t\t}\n\t\tspacket.clear();\n\n\t}while( filename_length != 0 );\n\n\tstd::sort( directory_array.begin(), directory_array.end() );\n\tstd::cout << std::endl;\n\n\tsetColors(\"light blue\"); \/\/for folders\n\n\tfor( unsigned int i(0) ; i < directory_array.size() ; ++i )\n\t\tif( directory_array[i][directory_array[i].size()-1] == '\/' && directory_array[i][0] != '.' )\n\t\t\tstd::wcout << directory_array[i] << std::endl;\n\n\tsetColors(\"light green\"); \/\/for files\n\n\tfor( unsigned int i(0) ; i < directory_array.size() ; ++i )\n\t\tif( directory_array[i][directory_array[i].size()-1] != '\/' )\n\t\t\tstd::wcout << directory_array[i] << std::endl;\n\n\tstd::cout << std::endl;\n\tsetColors(\"reset\");\n\n\treturn true;\n}\n<|endoftext|>"} {"text":"\/**\n * \\file\n * \\remark This file is part of VITA.\n *\n * \\copyright Copyright (C) 2013-2014 EOS di Manlio Morini.\n *\n * \\license\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this file,\n * You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n *\/\n\n#include \n#include \n\n#include \"kernel\/i_mep.h\"\n#include \"kernel\/team.h\"\n\n#if !defined(MASTER_TEST_SET)\n#define BOOST_TEST_MODULE team\n#include \n\nusing namespace boost;\n\n#include \"factory_fixture1.h\"\n#endif\n\nBOOST_FIXTURE_TEST_SUITE(team, F_FACTORY1)\n\nBOOST_AUTO_TEST_CASE(RandomCreation)\n{\n BOOST_TEST_CHECKPOINT(\"Variable length random creation\");\n for (unsigned l(sset.categories() + 2); l < 100; ++l)\n {\n env.code_length = l;\n vita::team t(env, sset);\n \/\/ std::cout << t << std::endl;\n\n BOOST_REQUIRE(t.debug());\n BOOST_REQUIRE_EQUAL(t.age(), 0);\n }\n}\n\nBOOST_AUTO_TEST_CASE(Mutation)\n{\n env.code_length = 100;\n\n vita::team t(env, sset);\n const vita::team orig(t);\n\n BOOST_REQUIRE_GT(t.individuals(), 0);\n\n const unsigned n(4000);\n\n BOOST_TEST_CHECKPOINT(\"Zero probability mutation\");\n env.p_mutation = 0.0;\n for (unsigned i(0); i < n; ++i)\n {\n t.mutation();\n BOOST_REQUIRE_EQUAL(t, orig);\n }\n\/*\n BOOST_TEST_CHECKPOINT(\"50% probability mutation.\");\n env.p_mutation = 0.5;\n\n double diff(0.0), avg_length(0.0);\n\n for (unsigned i(0); i < n; ++i)\n {\n const auto t1{t};\n\n t.mutation();\n diff += t.distance(t1);\n length += t1.eff_size();\n }\n\n const double perc(100.0 * diff \/ length);\n BOOST_CHECK_GT(perc, 47.0);\n BOOST_CHECK_LT(perc, 52.0);*\/\n}\n\nBOOST_AUTO_TEST_CASE(Comparison)\n{\n for (unsigned i(0); i < 2000; ++i)\n {\n vita::team a(env, sset);\n BOOST_REQUIRE_EQUAL(a, a);\n BOOST_REQUIRE_EQUAL(a.distance(a), 0);\n\n vita::team b(a);\n BOOST_REQUIRE_EQUAL(a.signature(), b.signature());\n BOOST_REQUIRE_EQUAL(a, b);\n BOOST_REQUIRE_EQUAL(a.distance(b), 0);\n\n vita::team c(env, sset);\n if (a.signature() != c.signature())\n {\n BOOST_REQUIRE_NE(a, c);\n BOOST_REQUIRE_GT(a.distance(c), 0);\n }\n }\n}\n\nBOOST_AUTO_TEST_CASE(Crossover)\n{\n env.code_length = 100;\n\n vita::team t1(env, sset), t2(env, sset);\n\n const unsigned n(2000);\n double dist(0.0);\n for (unsigned j(0); j < n; ++j)\n {\n const auto tc(t1.crossover(t2));\n BOOST_CHECK(tc.debug(true));\n\n dist += t1.distance(tc);\n }\n\n const double perc(100.0 * dist \/\n (env.code_length * sset.categories() * n *\n t1.individuals()));\n BOOST_CHECK_GT(perc, 45.0);\n BOOST_CHECK_LT(perc, 52.0);\n}\n\nBOOST_AUTO_TEST_CASE(Serialization)\n{\n for (unsigned i(0); i < 2000; ++i)\n {\n std::stringstream ss;\n vita::team t1(env, sset);\n\n for (auto j(vita::random::between(0u, 100u)); j; --j)\n t1.inc_age();\n\n BOOST_REQUIRE(t1.save(ss));\n\n vita::team t2(env, sset);\n BOOST_REQUIRE(t2.load(ss));\n BOOST_REQUIRE(t2.debug());\n\n BOOST_CHECK_EQUAL(t1, t2);\n }\n}\nBOOST_AUTO_TEST_SUITE_END()\n[TST] New test for team's iterators\/**\n * \\file\n * \\remark This file is part of VITA.\n *\n * \\copyright Copyright (C) 2013-2014 EOS di Manlio Morini.\n *\n * \\license\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this file,\n * You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n *\/\n\n#include \n#include \n\n#include \"kernel\/i_mep.h\"\n#include \"kernel\/team.h\"\n\n#if !defined(MASTER_TEST_SET)\n#define BOOST_TEST_MODULE team\n#include \n\nusing namespace boost;\n\n#include \"factory_fixture1.h\"\n#endif\n\nBOOST_FIXTURE_TEST_SUITE(team, F_FACTORY1)\n\nBOOST_AUTO_TEST_CASE(RandomCreation)\n{\n BOOST_TEST_CHECKPOINT(\"Variable length random creation\");\n for (unsigned l(sset.categories() + 2); l < 100; ++l)\n {\n env.code_length = l;\n vita::team t(env, sset);\n \/\/ std::cout << t << std::endl;\n\n BOOST_REQUIRE(t.debug());\n BOOST_REQUIRE_EQUAL(t.age(), 0);\n }\n}\n\nBOOST_AUTO_TEST_CASE(Mutation)\n{\n env.code_length = 100;\n\n vita::team t(env, sset);\n const vita::team orig(t);\n\n BOOST_REQUIRE_GT(t.individuals(), 0);\n\n const unsigned n(4000);\n\n BOOST_TEST_CHECKPOINT(\"Zero probability mutation\");\n env.p_mutation = 0.0;\n for (unsigned i(0); i < n; ++i)\n {\n t.mutation();\n BOOST_REQUIRE_EQUAL(t, orig);\n }\n\/*\n BOOST_TEST_CHECKPOINT(\"50% probability mutation.\");\n env.p_mutation = 0.5;\n\n double diff(0.0), avg_length(0.0);\n\n for (unsigned i(0); i < n; ++i)\n {\n const auto t1{t};\n\n t.mutation();\n diff += t.distance(t1);\n length += t1.eff_size();\n }\n\n const double perc(100.0 * diff \/ length);\n BOOST_CHECK_GT(perc, 47.0);\n BOOST_CHECK_LT(perc, 52.0);*\/\n}\n\nBOOST_AUTO_TEST_CASE(Comparison)\n{\n for (unsigned i(0); i < 2000; ++i)\n {\n vita::team a(env, sset);\n BOOST_REQUIRE_EQUAL(a, a);\n BOOST_REQUIRE_EQUAL(a.distance(a), 0);\n\n vita::team b(a);\n BOOST_REQUIRE_EQUAL(a.signature(), b.signature());\n BOOST_REQUIRE_EQUAL(a, b);\n BOOST_REQUIRE_EQUAL(a.distance(b), 0);\n\n vita::team c(env, sset);\n if (a.signature() != c.signature())\n {\n BOOST_REQUIRE_NE(a, c);\n BOOST_REQUIRE_GT(a.distance(c), 0);\n }\n }\n}\n\nBOOST_AUTO_TEST_CASE(Iterators)\n{\n for (unsigned j(0); j < 1000; ++j)\n {\n vita::team t(env, sset);\n\n unsigned i(0);\n for (const auto &ind : t)\n {\n BOOST_CHECK_EQUAL(ind, t[i]);\n ++i;\n }\n }\n}\n\nBOOST_AUTO_TEST_CASE(Crossover)\n{\n env.code_length = 100;\n\n vita::team t1(env, sset), t2(env, sset);\n\n const unsigned n(2000);\n double dist(0.0);\n for (unsigned j(0); j < n; ++j)\n {\n const auto tc(t1.crossover(t2));\n BOOST_CHECK(tc.debug(true));\n\n dist += t1.distance(tc);\n }\n\n const double perc(100.0 * dist \/\n (env.code_length * sset.categories() * n *\n t1.individuals()));\n BOOST_CHECK_GT(perc, 45.0);\n BOOST_CHECK_LT(perc, 52.0);\n}\n\nBOOST_AUTO_TEST_CASE(Serialization)\n{\n for (unsigned i(0); i < 2000; ++i)\n {\n std::stringstream ss;\n vita::team t1(env, sset);\n\n for (auto j(vita::random::between(0u, 100u)); j; --j)\n t1.inc_age();\n\n BOOST_REQUIRE(t1.save(ss));\n\n vita::team t2(env, sset);\n BOOST_REQUIRE(t2.load(ss));\n BOOST_REQUIRE(t2.debug());\n\n BOOST_CHECK_EQUAL(t1, t2);\n }\n}\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"#include \"application.h\"\n\n\/\/ This #include statement was automatically added by the Spark IDE.\n#include \"flipflop.h\"\n\n\/\/ This #include statement was automatically added by the Spark IDE.\n#include \"hmc5883l.h\"\n\n\/*\n HMC5883l Watermeter Reader\n Author: Keith Baker\n Email: kbaker at alumni dot ithaca dot edu\n \n Very loosely based off of: MAG3110 Breakout Example Code\n by: Aaron Weiss, aaron at sparkfun dot com\n\n Track magnetic impeller of a water meter using a digital compass.\n\n*\/\n\nhmc5883l hmc = hmc5883l();\nflipflop counter = flipflop();\nunsigned long last = millis();\nunsigned long now = millis();\nbyte mps = 0;\nunsigned long last_count = 0;\nfloat avg = 0;\nbool blink = false;\n\n#define LED D7\n\nvoid setup()\n{\n Serial.begin(115200); \/\/ start serial for output\n Serial.println(\"Cloud!\");\n\n \/\/let us know we are connected to cloud so we can re-flash bad code\n pinMode(LED, OUTPUT);\n digitalWrite(LED,HIGH);\n unsigned long time = millis();\n while (millis() < time + 10000 or SPARK_FLASH_UPDATE){\n SPARK_WLAN_Loop();\n }\n digitalWrite(LED,LOW);\n\n Spark.disconnect(); \/\/ We don't need any cloud after we allow re-flash, takes a ton of cycles\n \/\/to late, hold on tight!\n Serial.println(\"Starting...\");\n Wire.begin(true); \/\/ join i2c bus at high speed\n hmc.config(); \/\/ turn the HMC5883l on\n Serial.println(\"Configured\");\n RGB.control(true);\n}\n\nvoid loop()\n{\n now = millis();\n if (hmc.ready(now)){\n digitalWrite(LED,HIGH);\n if (hmc.fastread()){\n Serial.println(\"I2C Read Error\");\n }\n digitalWrite(LED,LOW);\n }\n else if (hmc.available()){\n counter.append(hmc.getz());\n \/\/counter.debug();\n hmc.advance();\n mps ++;\n }\n if (now - last > 1000){\n last = now;\n int delta = counter.count - last_count; \n last_count = counter.count;\n avg = ((avg * 59.0) + delta) \/ 60.0;\n Serial.print(delta);\n Serial.print(\" \"); \n Serial.print(avg); \n Serial.print(\" \");\n Serial.println(mps);\n if (blink){\n blink = false;\n }\n else {\n blink = true;\n }\n RGB.color(delta * 10, (int)(avg * 10.0), (int)blink * 255);\n mps = 0;\n }\n\n}\nslow down i2c, seems more stable#include \"application.h\"\n\n\/\/ This #include statement was automatically added by the Spark IDE.\n#include \"flipflop.h\"\n\n\/\/ This #include statement was automatically added by the Spark IDE.\n#include \"hmc5883l.h\"\n\n\/*\n HMC5883l Watermeter Reader\n Author: Keith Baker\n Email: kbaker at alumni dot ithaca dot edu\n \n Very loosely based off of: MAG3110 Breakout Example Code\n by: Aaron Weiss, aaron at sparkfun dot com\n\n Track magnetic impeller of a water meter using a digital compass.\n\n*\/\n\nhmc5883l hmc = hmc5883l();\nflipflop counter = flipflop();\nunsigned long last = millis();\nunsigned long now = millis();\nbyte mps = 0;\nunsigned long last_count = 0;\nfloat avg = 0;\nbool blink = false;\n\n#define LED D7\n\nvoid setup()\n{\n Serial.begin(115200); \/\/ start serial for output\n Serial.println(\"Cloud!\");\n\n \/\/let us know we are connected to cloud so we can re-flash bad code\n pinMode(LED, OUTPUT);\n digitalWrite(LED,HIGH);\n unsigned long time = millis();\n while (millis() < time + 10000 or SPARK_FLASH_UPDATE){\n SPARK_WLAN_Loop();\n }\n digitalWrite(LED,LOW);\n\n Spark.disconnect(); \/\/ We don't need any cloud after we allow re-flash, takes a ton of cycles\n \/\/to late, hold on tight!\n Serial.println(\"Starting...\");\n Wire.begin(false); \/\/ join i2c bus at high speed\n hmc.config(); \/\/ turn the HMC5883l on\n Serial.println(\"Configured\");\n RGB.control(true);\n}\n\nvoid loop()\n{\n now = millis();\n if (hmc.ready(now)){\n digitalWrite(LED,HIGH);\n if (hmc.fastread()){\n Serial.println(\"I2C Read Error\");\n }\n digitalWrite(LED,LOW);\n }\n else if (hmc.available()){\n counter.append(hmc.getz());\n \/\/counter.debug();\n hmc.advance();\n mps ++;\n }\n if (now - last > 1000){\n last = now;\n int delta = counter.count - last_count; \n last_count = counter.count;\n avg = ((avg * 59.0) + delta) \/ 60.0;\n Serial.print(delta);\n Serial.print(\" \"); \n Serial.print(avg); \n Serial.print(\" \");\n Serial.println(mps);\n if (blink){\n blink = false;\n }\n else {\n blink = true;\n }\n RGB.color(delta * 10, (int)(avg * 10.0), (int)blink * 255);\n mps = 0;\n }\n\n}\n<|endoftext|>"} {"text":"\/\/ ==========================================================================\n\/\/ SeqAn - The Library for Sequence Analysis\n\/\/ ==========================================================================\n\/\/ Copyright (c) 2006-2015, Knut Reinert, FU Berlin\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of Knut Reinert or the FU Berlin nor the names of\n\/\/ its contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\/\/ DAMAGE.\n\/\/\n\/\/ ==========================================================================\n\/\/ Author: Manuel Holtgrewe \n\/\/ ==========================================================================\n\/\/ Tests for the module parallel.\n\/\/ ==========================================================================\n\n#include \/\/ Testing infrastructure.\n#include \/\/ Required to print strings in tests.\n#include \/\/ Header under test.\n\n#if defined(_OPENMP)\n#include \n#endif \/\/ #if defined(_OPENMP)\n\n#include \"test_parallel_atomic_primitives.h\"\n#include \"test_parallel_atomic_misc.h\"\n#include \"test_parallel_splitting.h\"\n#include \"test_parallel_algorithms.h\"\n#include \"test_parallel_queue.h\"\n\nSEQAN_BEGIN_TESTSUITE(test_parallel) {\n#if defined(_OPENMP)\n \/\/ Set number of threads to >=2 so there actually is parallelism.\n if (omp_get_max_threads() < 2)\n omp_set_num_threads(2);\n std::cout << \"PARALLELISM ENABLED (CTEST_FULL_OUTPUT)\" << std::endl;\n#endif \/\/ #if defined(_OPENMP)\n\n \/\/ TODO(holtgrew): Re-enable tests on LLVM when bug 9041 is fixed.\n \/\/ LLVM has problems with atomic operation builtins, re-enable when\n \/\/ this problem is fixed. See http:\/\/llvm.org\/bugs\/show_bug.cgi?id=9041\n \/\/\n \/\/ There is a problem with compare-and-swap on MinGW, too.\n#if !defined(__llvm__) && !defined(PLATFORM_WINDOWS_MINGW)\n \/\/ Tests for atomic primitives.\n SEQAN_CALL_TEST(test_parallel_atomic_inc);\n SEQAN_CALL_TEST(test_parallel_atomic_dec);\n SEQAN_CALL_TEST(test_parallel_atomic_add);\n SEQAN_CALL_TEST(test_parallel_atomic_or);\n SEQAN_CALL_TEST(test_parallel_atomic_xor);\n SEQAN_CALL_TEST(test_parallel_atomic_cas);\n\n \/\/ Tests for misc simpmle atomic operations.\n SEQAN_CALL_TEST(test_parallel_atomic_min);\n SEQAN_CALL_TEST(test_parallel_atomic_max);\n#endif \/\/ #if !defined(__llvm__) && !defined(PLATFORM_WINDOWS_MINGW)\n\n SEQAN_CALL_TEST(test_parallel_splitter_equidistant);\n SEQAN_CALL_TEST(test_parallel_splitting_compute_splitters);\n SEQAN_CALL_TEST(test_parallel_sum);\n SEQAN_CALL_TEST(test_parallel_partial_sum);\n\n \/\/ Tests for parallel queue.\n SEQAN_CALL_TEST(test_parallel_queue_simple);\n SEQAN_CALL_TEST(test_parallel_queue_resize);\n SEQAN_CALL_TEST(test_parallel_queue_non_pod);\n\n#if defined(_OPENMP) || defined(SEQAN_CXX11_STANDARD)\n#ifdef SEQAN_CXX11_STL\n if (std::thread::hardware_concurrency() >= 2u)\n#else\n if (omp_get_max_threads() >= 2)\n#endif\n {\n SEQAN_CALL_TEST(test_parallel_queue_spsc_fixedsize);\n SEQAN_CALL_TEST(test_parallel_queue_spsc_dynamicsize);\n SEQAN_CALL_TEST(test_parallel_queue_spmc_fixedsize);\n SEQAN_CALL_TEST(test_parallel_queue_spmc_dynamicsize);\n SEQAN_CALL_TEST(test_parallel_queue_mpsc_fixedsize);\n SEQAN_CALL_TEST(test_parallel_queue_mpsc_dynamicsize);\n SEQAN_CALL_TEST(test_parallel_queue_mpmc_fixedsize);\n SEQAN_CALL_TEST(test_parallel_queue_mpmc_dynamicsize);\n }\n#endif\n}\nSEQAN_END_TESTSUITE\n[TEST] Parallel: disabled some parallel queue tests\/\/ ==========================================================================\n\/\/ SeqAn - The Library for Sequence Analysis\n\/\/ ==========================================================================\n\/\/ Copyright (c) 2006-2015, Knut Reinert, FU Berlin\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of Knut Reinert or the FU Berlin nor the names of\n\/\/ its contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\/\/ DAMAGE.\n\/\/\n\/\/ ==========================================================================\n\/\/ Author: Manuel Holtgrewe \n\/\/ ==========================================================================\n\/\/ Tests for the module parallel.\n\/\/ ==========================================================================\n\n#include \/\/ Testing infrastructure.\n#include \/\/ Required to print strings in tests.\n#include \/\/ Header under test.\n\n#if defined(_OPENMP)\n#include \n#endif \/\/ #if defined(_OPENMP)\n\n#include \"test_parallel_atomic_primitives.h\"\n#include \"test_parallel_atomic_misc.h\"\n#include \"test_parallel_splitting.h\"\n#include \"test_parallel_algorithms.h\"\n#include \"test_parallel_queue.h\"\n\nSEQAN_BEGIN_TESTSUITE(test_parallel) {\n#if defined(_OPENMP)\n \/\/ Set number of threads to >=2 so there actually is parallelism.\n if (omp_get_max_threads() < 2)\n omp_set_num_threads(2);\n std::cout << \"PARALLELISM ENABLED (CTEST_FULL_OUTPUT)\" << std::endl;\n#endif \/\/ #if defined(_OPENMP)\n\n \/\/ TODO(holtgrew): Re-enable tests on LLVM when bug 9041 is fixed.\n \/\/ LLVM has problems with atomic operation builtins, re-enable when\n \/\/ this problem is fixed. See http:\/\/llvm.org\/bugs\/show_bug.cgi?id=9041\n \/\/\n \/\/ There is a problem with compare-and-swap on MinGW, too.\n#if !defined(__llvm__) && !defined(PLATFORM_WINDOWS_MINGW)\n \/\/ Tests for atomic primitives.\n SEQAN_CALL_TEST(test_parallel_atomic_inc);\n SEQAN_CALL_TEST(test_parallel_atomic_dec);\n SEQAN_CALL_TEST(test_parallel_atomic_add);\n SEQAN_CALL_TEST(test_parallel_atomic_or);\n SEQAN_CALL_TEST(test_parallel_atomic_xor);\n SEQAN_CALL_TEST(test_parallel_atomic_cas);\n\n \/\/ Tests for misc simpmle atomic operations.\n SEQAN_CALL_TEST(test_parallel_atomic_min);\n SEQAN_CALL_TEST(test_parallel_atomic_max);\n#endif \/\/ #if !defined(__llvm__) && !defined(PLATFORM_WINDOWS_MINGW)\n\n SEQAN_CALL_TEST(test_parallel_splitter_equidistant);\n SEQAN_CALL_TEST(test_parallel_splitting_compute_splitters);\n SEQAN_CALL_TEST(test_parallel_sum);\n SEQAN_CALL_TEST(test_parallel_partial_sum);\n\n \/\/ Tests for parallel queue.\n SEQAN_CALL_TEST(test_parallel_queue_simple);\n SEQAN_CALL_TEST(test_parallel_queue_resize);\n SEQAN_CALL_TEST(test_parallel_queue_non_pod);\n\n#if defined(_OPENMP) || defined(SEQAN_CXX11_STANDARD)\n#ifdef SEQAN_CXX11_STL\n if (std::thread::hardware_concurrency() >= 2u)\n#else\n if (omp_get_max_threads() >= 2)\n#endif\n {\n SEQAN_CALL_TEST(test_parallel_queue_spsc_fixedsize);\n SEQAN_CALL_TEST(test_parallel_queue_spsc_dynamicsize);\n SEQAN_CALL_TEST(test_parallel_queue_spmc_fixedsize);\n SEQAN_CALL_TEST(test_parallel_queue_spmc_dynamicsize);\n SEQAN_CALL_TEST(test_parallel_queue_mpsc_fixedsize);\n\/\/ SEQAN_CALL_TEST(test_parallel_queue_mpsc_dynamicsize);\n\/\/ SEQAN_CALL_TEST(test_parallel_queue_mpmc_fixedsize);\n\/\/ SEQAN_CALL_TEST(test_parallel_queue_mpmc_dynamicsize);\n }\n#endif\n}\nSEQAN_END_TESTSUITE\n<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \"prefix_function.hpp\"\n\n\nnamespace gt = testing;\n\n\nnamespace pk\n{\nnamespace testing\n{\n\n\nstruct prefix_function_tester : public gt::Test\n{\n static const int MAX_TEXT_SIZE = 100;\n\n \/\/ tested class:\n prefix_function pf;\n};\n\n\nTEST_F(prefix_function_tester, tests_abcd)\n{\n \/\/ given\n const std::string text = \"abcd\";\n\n \/\/ when\n pf.run(text.c_str(), text.size());\n\n \/\/ then\n const int* prefix_suffix_table = pf.get_prefix_suffix_table();\n\n EXPECT_EQ(0, prefix_suffix_table[0]);\n EXPECT_EQ(0, prefix_suffix_table[1]);\n EXPECT_EQ(0, prefix_suffix_table[2]);\n EXPECT_EQ(0, prefix_suffix_table[3]);\n}\n\n\nTEST_F(prefix_function_tester, tests_aaaa)\n{\n \/\/ given\n const std::string text = \"aaaa\";\n\n \/\/ when\n pf.run(text.c_str(), text.size());\n\n \/\/ then\n const int* prefix_suffix_table = pf.get_prefix_suffix_table();\n\n EXPECT_EQ(0, prefix_suffix_table[0]);\n EXPECT_EQ(1, prefix_suffix_table[1]);\n EXPECT_EQ(2, prefix_suffix_table[2]);\n EXPECT_EQ(3, prefix_suffix_table[3]);\n}\n\n\nTEST_F(prefix_function_tester, tests_abcabcabc)\n{\n \/\/ given\n const std::string text = \"abcabcabc\";\n\n \/\/ when\n pf.run(text.c_str(), text.size());\n\n \/\/ then\n const int* prefix_suffix_table = pf.get_prefix_suffix_table();\n\n EXPECT_EQ(0, prefix_suffix_table[0]);\n EXPECT_EQ(0, prefix_suffix_table[1]);\n EXPECT_EQ(0, prefix_suffix_table[2]);\n EXPECT_EQ(1, prefix_suffix_table[3]);\n EXPECT_EQ(2, prefix_suffix_table[4]);\n EXPECT_EQ(3, prefix_suffix_table[5]);\n EXPECT_EQ(4, prefix_suffix_table[6]);\n EXPECT_EQ(5, prefix_suffix_table[7]);\n EXPECT_EQ(6, prefix_suffix_table[8]);\n}\n\n\nTEST_F(prefix_function_tester, tests_abcdabcaba)\n{\n \/\/ given\n const std::string text = \"abcdabcaba\";\n\n \/\/ when\n pf.run(text.c_str(), text.size());\n\n \/\/ then\n const int* prefix_suffix_table = pf.get_prefix_suffix_table();\n\n EXPECT_EQ(0, prefix_suffix_table[0]);\n EXPECT_EQ(0, prefix_suffix_table[1]);\n EXPECT_EQ(0, prefix_suffix_table[2]);\n EXPECT_EQ(0, prefix_suffix_table[3]);\n EXPECT_EQ(1, prefix_suffix_table[4]);\n EXPECT_EQ(2, prefix_suffix_table[5]);\n EXPECT_EQ(3, prefix_suffix_table[6]);\n EXPECT_EQ(1, prefix_suffix_table[7]);\n EXPECT_EQ(2, prefix_suffix_table[8]);\n EXPECT_EQ(1, prefix_suffix_table[9]);\n}\n\n\n} \/\/ namespace testing\n} \/\/ namespace pk\nAdded test for pattern searching using Knuth's prefix function#include \n\n#include \n\n#include \"prefix_function.hpp\"\n\n\nnamespace gt = testing;\n\n\nnamespace pk\n{\nnamespace testing\n{\n\n\nstruct prefix_function_tester : public gt::Test\n{\n static const int MAX_TEXT_SIZE = 100;\n\n \/\/ tested class:\n prefix_function pf;\n};\n\n\nTEST_F(prefix_function_tester, tests_abcd)\n{\n \/\/ given\n const std::string text = \"abcd\";\n\n \/\/ when\n pf.run(text.c_str(), text.size());\n\n \/\/ then\n const int* prefix_suffix_table = pf.get_prefix_suffix_table();\n\n EXPECT_EQ(0, prefix_suffix_table[0]);\n EXPECT_EQ(0, prefix_suffix_table[1]);\n EXPECT_EQ(0, prefix_suffix_table[2]);\n EXPECT_EQ(0, prefix_suffix_table[3]);\n}\n\n\nTEST_F(prefix_function_tester, tests_aaaa)\n{\n \/\/ given\n const std::string text = \"aaaa\";\n\n \/\/ when\n pf.run(text.c_str(), text.size());\n\n \/\/ then\n const int* prefix_suffix_table = pf.get_prefix_suffix_table();\n\n EXPECT_EQ(0, prefix_suffix_table[0]);\n EXPECT_EQ(1, prefix_suffix_table[1]);\n EXPECT_EQ(2, prefix_suffix_table[2]);\n EXPECT_EQ(3, prefix_suffix_table[3]);\n}\n\n\nTEST_F(prefix_function_tester, tests_abcabcabc)\n{\n \/\/ given\n const std::string text = \"abcabcabc\";\n\n \/\/ when\n pf.run(text.c_str(), text.size());\n\n \/\/ then\n const int* prefix_suffix_table = pf.get_prefix_suffix_table();\n\n EXPECT_EQ(0, prefix_suffix_table[0]);\n EXPECT_EQ(0, prefix_suffix_table[1]);\n EXPECT_EQ(0, prefix_suffix_table[2]);\n EXPECT_EQ(1, prefix_suffix_table[3]);\n EXPECT_EQ(2, prefix_suffix_table[4]);\n EXPECT_EQ(3, prefix_suffix_table[5]);\n EXPECT_EQ(4, prefix_suffix_table[6]);\n EXPECT_EQ(5, prefix_suffix_table[7]);\n EXPECT_EQ(6, prefix_suffix_table[8]);\n}\n\n\nTEST_F(prefix_function_tester, tests_abcdabcaba)\n{\n \/\/ given\n const std::string text = \"abcdabcaba\";\n\n \/\/ when\n pf.run(text.c_str(), text.size());\n\n \/\/ then\n const int* prefix_suffix_table = pf.get_prefix_suffix_table();\n\n EXPECT_EQ(0, prefix_suffix_table[0]);\n EXPECT_EQ(0, prefix_suffix_table[1]);\n EXPECT_EQ(0, prefix_suffix_table[2]);\n EXPECT_EQ(0, prefix_suffix_table[3]);\n EXPECT_EQ(1, prefix_suffix_table[4]);\n EXPECT_EQ(2, prefix_suffix_table[5]);\n EXPECT_EQ(3, prefix_suffix_table[6]);\n EXPECT_EQ(1, prefix_suffix_table[7]);\n EXPECT_EQ(2, prefix_suffix_table[8]);\n EXPECT_EQ(1, prefix_suffix_table[9]);\n}\n\n\nTEST_F(prefix_function_tester, tests_pattern_searching_in_text)\n{\n \/\/ given\n const std::string pattern = \"abca\";\n const std::string text = \"abaabcdabcabdabcabcad\";\n \/\/ pattern ends at: ^ ^ ^\n\n \/\/ when\n std::string s = pattern + \"#\" + text;\n pf.run(s.c_str(), s.size());\n\n \/\/ then\n const int* prefix_suffix_table = pf.get_prefix_suffix_table();\n\n EXPECT_EQ(3, std::count(prefix_suffix_table, prefix_suffix_table + s.size(), pattern.size()));\n\n const int first_occurance = pattern.size() + 1 + 10;\n EXPECT_EQ(pattern.size(), prefix_suffix_table[first_occurance]);\n\n const int second_occurance = pattern.size() + 1 + 16;\n EXPECT_EQ(pattern.size(), prefix_suffix_table[second_occurance]);\n\n const int third_occurance = pattern.size() + 1 + 19;\n EXPECT_EQ(pattern.size(), prefix_suffix_table[third_occurance]);\n}\n\n\n} \/\/ namespace testing\n} \/\/ namespace pk\n<|endoftext|>"} {"text":"\/*\n Copyright 2011 John Selbie\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n\n\n#include \"commonincludes.hpp\"\n#include \"socketaddress.h\"\n#include \"stringhelper.h\"\n\n\nHRESULT ResolveHostName(const char* pszHostName, int family, bool fNumericOnly, CSocketAddress* pAddr)\n{\n\n int ret;\n HRESULT hr = S_OK;\n addrinfo* pResultList = NULL;\n \n addrinfo hints = {};\n \n std::string strHostName(pszHostName);\n StringHelper::Trim(strHostName);\n \n ChkIf(strHostName.length() == 0, E_INVALIDARG);\n ChkIf(pAddr==NULL, E_INVALIDARG);\n \n hints.ai_family = family;\n if (fNumericOnly)\n {\n hints.ai_flags = AI_NUMERICHOST;\n }\n \n \/\/ without a socktype hint, getaddrinfo will return 3x the number of addresses (SOCK_STREAM, SOCK_DGRAM, and SOCK_RAW)\n hints.ai_socktype = SOCK_STREAM;\n\n ret = getaddrinfo(strHostName.c_str(), NULL, &hints, &pResultList);\n \n ChkIf(ret != 0, ERRNO_TO_HRESULT(ret));\n ChkIf(pResultList==NULL, E_FAIL)\n \n \/\/ just pick the first one found\n *pAddr = CSocketAddress(*(pResultList->ai_addr));\n \nCleanup:\n\n if (pResultList != NULL) {\n ::freeaddrinfo(pResultList);\n }\n\n return hr;\n\n}\n\nHRESULT NumericIPToAddress(int family, const char* pszIP, CSocketAddress* pAddr)\n{\n HRESULT hr = S_OK;\n \n ChkIf((family != AF_INET) && (family != AF_INET6), E_INVALIDARG);\n\n if (family == AF_INET)\n {\n sockaddr_in addr4 = {};\n ChkIf(0 == ::inet_pton(family, pszIP, &addr4.sin_addr), E_FAIL);\n addr4.sin_family = family;\n *pAddr = CSocketAddress(addr4);\n }\n else\n {\n sockaddr_in6 addr6 = {};\n ChkIf(0 == ::inet_pton(family, pszIP, &addr6.sin6_addr), E_FAIL);\n addr6.sin6_family = family;\n *pAddr = CSocketAddress(addr6);\n }\n \nCleanup:\n\n return hr;\n \n}\n\n\n\n\nCode style and comment\/*\n Copyright 2011 John Selbie\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n\n\n#include \"commonincludes.hpp\"\n#include \"socketaddress.h\"\n#include \"stringhelper.h\"\n\n\nHRESULT ResolveHostName(const char* pszHostName, int family, bool fNumericOnly, CSocketAddress* pAddr)\n{\n\n int ret;\n HRESULT hr = S_OK;\n addrinfo* pResultList = NULL;\n \n addrinfo hints = {};\n \n std::string strHostName(pszHostName);\n StringHelper::Trim(strHostName);\n \n ChkIf(strHostName.length() == 0, E_INVALIDARG);\n ChkIf(pAddr==NULL, E_INVALIDARG);\n \n hints.ai_family = family;\n if (fNumericOnly)\n {\n hints.ai_flags = AI_NUMERICHOST;\n }\n \n \/\/ without a socktype hint, getaddrinfo will return 3x the number of addresses (SOCK_STREAM, SOCK_DGRAM, and SOCK_RAW)\n hints.ai_socktype = SOCK_STREAM;\n\n ret = getaddrinfo(strHostName.c_str(), NULL, &hints, &pResultList);\n \n ChkIf(ret != 0, ERRNO_TO_HRESULT(ret));\n ChkIf(pResultList==NULL, E_FAIL)\n \n \/\/ just pick the first one found\n *pAddr = CSocketAddress(*(pResultList->ai_addr));\n \nCleanup:\n\n if (pResultList != NULL) \/\/ android will crash if passed NULL\n {\n ::freeaddrinfo(pResultList);\n }\n\n return hr;\n\n}\n\nHRESULT NumericIPToAddress(int family, const char* pszIP, CSocketAddress* pAddr)\n{\n HRESULT hr = S_OK;\n \n ChkIf((family != AF_INET) && (family != AF_INET6), E_INVALIDARG);\n\n if (family == AF_INET)\n {\n sockaddr_in addr4 = {};\n ChkIf(0 == ::inet_pton(family, pszIP, &addr4.sin_addr), E_FAIL);\n addr4.sin_family = family;\n *pAddr = CSocketAddress(addr4);\n }\n else\n {\n sockaddr_in6 addr6 = {};\n ChkIf(0 == ::inet_pton(family, pszIP, &addr6.sin6_addr), E_FAIL);\n addr6.sin6_family = family;\n *pAddr = CSocketAddress(addr6);\n }\n \nCleanup:\n\n return hr;\n \n}\n\n\n\n\n<|endoftext|>"} {"text":"#include \"joedb\/concurrency\/Server.h\"\n#include \"joedb\/concurrency\/network_integers.h\"\n#include \"joedb\/io\/Dump_Writable.h\"\n\n#include \n#include \n#include \n\nnamespace joedb\n{\n std::atomic Server::interrupted(false);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void CDECL Server::signal_handler(int sig)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n interrupted = true;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n Server::Session::Session(Server &server, net::ip::tcp::socket && socket):\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n server(server),\n socket(std::move(socket)),\n state(not_locking)\n {\n std::cerr << \"Created a new session\\n\";\n ++server.session_count;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n Server::Session::~Session()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (state == locking)\n {\n std::cerr << \"Removing lock held by dying session.\\n\";\n server.unlock(*this);\n }\n std::cerr << \"Destroyed Session\\n\";\n --server.session_count;\n server.write_status();\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::write_status()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n std::cerr << joedb::Dump_Writable::get_local_time(std::time(nullptr));\n std::cerr << \"; port = \" << acceptor.local_endpoint().port();\n std::cerr << \"; session_count = \" << session_count << '\\n';\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::lock_dequeue()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (!locked && !lock_queue.empty())\n {\n std::cerr << \"Locking\\n\";\n locked = true;\n std::shared_ptr session = lock_queue.front();\n lock_queue.pop();\n\n if (lock_timeout_seconds > 0)\n {\n lock_timeout_timer.expires_after\n (\n std::chrono::seconds(lock_timeout_seconds)\n );\n\n lock_timeout_timer.async_wait\n (\n std::bind\n (\n &Server::lock_timeout_handler,\n this,\n session,\n std::placeholders::_1\n )\n );\n }\n\n if (session->state == Session::State::waiting_for_lock)\n write_buffer_and_next_command(session, 1);\n else if (session->state == Session::State::waiting_for_lock_pull)\n pull(session);\n\n session->state = Session::State::locking;\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::lock(std::shared_ptr session, Session::State state)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (session->state == Session::State::not_locking)\n {\n session->state = state;\n lock_queue.push(session);\n lock_dequeue();\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::unlock(Session &session)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (session.state == Session::State::locking)\n {\n std::cerr << \"Unlocking\\n\";\n session.state = Session::State::not_locking;\n locked = false;\n lock_timeout_timer.cancel();\n\n lock_dequeue();\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::lock_timeout_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n std::error_code error\n )\n {\n if (!error)\n {\n std::cerr << \"Timeout!\\n\";\n unlock(*session);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::push_transfer_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n size_t offset,\n size_t remaining_size,\n bool conflict,\n std::error_code error,\n size_t bytes_transferred\n )\n {\n if (!error)\n {\n std::cerr << '.';\n\n push_transfer\n (\n session,\n offset + bytes_transferred,\n remaining_size - bytes_transferred,\n conflict\n );\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::push_transfer\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n size_t offset,\n size_t remaining_size,\n bool conflict\n )\n {\n if (remaining_size > 0)\n {\n std::cerr << '.';\n\n net::async_read\n (\n session->socket,\n net::buffer(&push_buffer[offset], remaining_size),\n [this, session, offset, remaining_size, conflict]\n (\n std::error_code error,\n size_t bytes_transferred\n ) mutable\n {\n push_transfer_handler\n (\n session,\n offset,\n remaining_size,\n conflict,\n error,\n bytes_transferred\n );\n }\n );\n }\n else\n {\n if (conflict)\n session->buffer[0] = 'C';\n else\n {\n journal.append_raw_tail(push_buffer.data(), offset);\n session->buffer[0] = 'U';\n }\n\n std::cerr << \" done. Returning '\" << session->buffer[0] << \"'\\n\";\n\n write_buffer_and_next_command(session, 1);\n\n unlock(*session);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::push_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n std::error_code error,\n size_t bytes_transferred\n )\n {\n if (!error)\n {\n const int64_t start = from_network(session->buffer);\n const int64_t size = from_network(session->buffer + 8);\n\n const bool conflict = (size != 0) &&\n (\n start != journal.get_checkpoint_position() ||\n (locked && session->state != Session::State::locking)\n );\n\n if (session->state != Session::State::locking)\n {\n std::cerr << \"Trying to push while not locking.\\n\";\n if (!conflict && !locked)\n {\n std::cerr << \"OK, this session can take the lock.\\n\";\n lock(session, Session::State::locking);\n }\n }\n\n if (session->state == Session::State::locking)\n lock_timeout_timer.cancel();\n\n if (!conflict && size > int64_t(push_buffer.size()))\n push_buffer.resize(size_t(size));\n\n std::cerr << \"Pushing, start = \" << start << \", size = \" << size << ':';\n\n push_transfer\n (\n session,\n 0,\n size_t(size),\n conflict\n );\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::pull_transfer_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n Async_Reader reader,\n std::error_code error,\n size_t bytes_transferred\n )\n {\n if (!error)\n {\n if (reader.get_remaining() > 0)\n {\n std::cerr << '.';\n\n const size_t size = reader.read\n (\n session->buffer,\n Session::buffer_size\n );\n\n net::async_write\n (\n session->socket,\n net::buffer(session->buffer, size_t(size)),\n std::bind\n (\n &Server::pull_transfer_handler,\n this,\n session,\n reader,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n }\n else\n {\n std::cerr << \" OK\\n\";\n read_command(session);\n }\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::pull_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n std::error_code error,\n size_t bytes_transferred\n )\n {\n if (!error)\n {\n const int64_t checkpoint = from_network(session->buffer + 1);\n\n Async_Reader reader = journal.get_tail_reader(checkpoint);\n to_network(reader.get_remaining(), session->buffer + 9);\n\n std::cerr << \"Pulling from checkpoint = \" << checkpoint;\n std::cerr << \", size = \" << reader.get_remaining() << ':';\n\n net::async_write\n (\n session->socket,\n net::buffer(session->buffer, 17),\n std::bind\n (\n &Server::pull_transfer_handler,\n this,\n session,\n reader,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::pull(std::shared_ptr session)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n net::async_read\n (\n session->socket,\n net::buffer(session->buffer + 1, 8),\n std::bind\n (\n &Server::pull_handler,\n this,\n session,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::read_command_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n std::error_code error,\n size_t bytes_transferred\n )\n {\n if (!error)\n {\n std::cerr << \"Received command: \" << session->buffer[0] << '\\n';\n\n switch (session->buffer[0])\n {\n case 'P':\n pull(session);\n break;\n\n case 'L':\n lock(session, Session::State::waiting_for_lock_pull);\n break;\n\n case 'U':\n net::async_read\n (\n session->socket,\n net::buffer(session->buffer, 16),\n std::bind\n (\n &Server::push_handler,\n this,\n session,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n break;\n\n case 'l':\n lock(session, Session::State::waiting_for_lock);\n break;\n\n case 'u':\n if (session->state == Session::State::locking)\n unlock(*session);\n else\n session->buffer[0] = 't';\n write_buffer_and_next_command(session, 1);\n break;\n\n case 'i':\n write_buffer_and_next_command(session, 1);\n write_status();\n break;\n\n case 'Q':\n if (session->state == Session::State::locking)\n unlock(*session);\n break;\n\n default:\n std::cerr << \"Unexpected command\\n\";\n break;\n }\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::read_command(std::shared_ptr session)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n net::async_read\n (\n session->socket,\n net::buffer(session->buffer, 1),\n std::bind\n (\n &Server::read_command_handler,\n this,\n session,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::write_buffer_and_next_command_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n std::error_code error,\n size_t bytes_transferred\n )\n {\n if (!error)\n read_command(session);\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::write_buffer_and_next_command\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n size_t size\n )\n {\n net::async_write\n (\n session->socket,\n net::buffer(session->buffer, size),\n std::bind\n (\n &Server::write_buffer_and_next_command_handler,\n this,\n session,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::handshake_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n std::error_code error,\n size_t bytes_transferred\n )\n {\n if (!error)\n {\n if\n (\n session->buffer[0] == 'j' &&\n session->buffer[1] == 'o' &&\n session->buffer[2] == 'e' &&\n session->buffer[3] == 'd' &&\n session->buffer[4] == 'b'\n )\n {\n const int64_t client_version = from_network(session->buffer + 5);\n\n std::cerr << \"client_version = \" << client_version << '\\n';\n\n if (client_version < 2)\n to_network(0, session->buffer + 5);\n else\n {\n const int64_t server_version = 2;\n to_network(server_version, session->buffer + 5);\n }\n\n write_buffer_and_next_command(session, 13);\n }\n else\n std::cerr << \"Bad handshake\\n\";\n }\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::handle_accept\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::error_code error,\n net::ip::tcp::socket socket\n )\n {\n if (!error)\n {\n std::shared_ptr session(new Session(*this, std::move(socket)));\n\n net::async_read\n (\n session->socket,\n net::buffer(session->buffer, 13),\n std::bind\n (\n &Server::handshake_handler,\n this,\n session,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n\n start_accept();\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::start_accept()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n acceptor.async_accept\n (\n io_context,\n std::bind\n (\n &Server::handle_accept,\n this,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::start_interrupt_timer()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n interrupt_timer.expires_after\n (\n std::chrono::seconds(interrupt_check_seconds)\n );\n\n interrupt_timer.async_wait\n (\n std::bind\n (\n &Server::handle_interrupt_timer,\n this,\n std::placeholders::_1\n )\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::handle_interrupt_timer(std::error_code error)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (!error)\n {\n if (interrupted)\n {\n std::cerr << \"Interruption detected\\n\";\n io_context.stop();\n }\n\n start_interrupt_timer();\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n Server::Server\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n joedb::Writable_Journal &journal,\n net::io_context &io_context,\n uint16_t port,\n uint32_t lock_timeout_seconds\n ):\n journal(journal),\n io_context(io_context),\n acceptor(io_context, net::ip::tcp::endpoint(net::ip::tcp::v4(), port)),\n interrupt_timer(io_context),\n session_count(0),\n lock_timeout_seconds(lock_timeout_seconds),\n lock_timeout_timer(io_context),\n locked(false)\n {\n write_status();\n\n std::signal(SIGINT, signal_handler);\n\n start_interrupt_timer();\n start_accept();\n }\n}\nwrite server status at connection time#include \"joedb\/concurrency\/Server.h\"\n#include \"joedb\/concurrency\/network_integers.h\"\n#include \"joedb\/io\/Dump_Writable.h\"\n\n#include \n#include \n#include \n\nnamespace joedb\n{\n std::atomic Server::interrupted(false);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void CDECL Server::signal_handler(int sig)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n interrupted = true;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n Server::Session::Session(Server &server, net::ip::tcp::socket && socket):\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n server(server),\n socket(std::move(socket)),\n state(not_locking)\n {\n std::cerr << \"Created a new session\\n\";\n ++server.session_count;\n server.write_status();\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n Server::Session::~Session()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (state == locking)\n {\n std::cerr << \"Removing lock held by dying session.\\n\";\n server.unlock(*this);\n }\n std::cerr << \"Destroyed Session\\n\";\n --server.session_count;\n server.write_status();\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::write_status()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n std::cerr << joedb::Dump_Writable::get_local_time(std::time(nullptr));\n std::cerr << \"; port = \" << acceptor.local_endpoint().port();\n std::cerr << \"; session_count = \" << session_count << '\\n';\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::lock_dequeue()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (!locked && !lock_queue.empty())\n {\n std::cerr << \"Locking\\n\";\n locked = true;\n std::shared_ptr session = lock_queue.front();\n lock_queue.pop();\n\n if (lock_timeout_seconds > 0)\n {\n lock_timeout_timer.expires_after\n (\n std::chrono::seconds(lock_timeout_seconds)\n );\n\n lock_timeout_timer.async_wait\n (\n std::bind\n (\n &Server::lock_timeout_handler,\n this,\n session,\n std::placeholders::_1\n )\n );\n }\n\n if (session->state == Session::State::waiting_for_lock)\n write_buffer_and_next_command(session, 1);\n else if (session->state == Session::State::waiting_for_lock_pull)\n pull(session);\n\n session->state = Session::State::locking;\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::lock(std::shared_ptr session, Session::State state)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (session->state == Session::State::not_locking)\n {\n session->state = state;\n lock_queue.push(session);\n lock_dequeue();\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::unlock(Session &session)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (session.state == Session::State::locking)\n {\n std::cerr << \"Unlocking\\n\";\n session.state = Session::State::not_locking;\n locked = false;\n lock_timeout_timer.cancel();\n\n lock_dequeue();\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::lock_timeout_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n std::error_code error\n )\n {\n if (!error)\n {\n std::cerr << \"Timeout!\\n\";\n unlock(*session);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::push_transfer_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n size_t offset,\n size_t remaining_size,\n bool conflict,\n std::error_code error,\n size_t bytes_transferred\n )\n {\n if (!error)\n {\n std::cerr << '.';\n\n push_transfer\n (\n session,\n offset + bytes_transferred,\n remaining_size - bytes_transferred,\n conflict\n );\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::push_transfer\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n size_t offset,\n size_t remaining_size,\n bool conflict\n )\n {\n if (remaining_size > 0)\n {\n std::cerr << '.';\n\n net::async_read\n (\n session->socket,\n net::buffer(&push_buffer[offset], remaining_size),\n [this, session, offset, remaining_size, conflict]\n (\n std::error_code error,\n size_t bytes_transferred\n ) mutable\n {\n push_transfer_handler\n (\n session,\n offset,\n remaining_size,\n conflict,\n error,\n bytes_transferred\n );\n }\n );\n }\n else\n {\n if (conflict)\n session->buffer[0] = 'C';\n else\n {\n journal.append_raw_tail(push_buffer.data(), offset);\n session->buffer[0] = 'U';\n }\n\n std::cerr << \" done. Returning '\" << session->buffer[0] << \"'\\n\";\n\n write_buffer_and_next_command(session, 1);\n\n unlock(*session);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::push_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n std::error_code error,\n size_t bytes_transferred\n )\n {\n if (!error)\n {\n const int64_t start = from_network(session->buffer);\n const int64_t size = from_network(session->buffer + 8);\n\n const bool conflict = (size != 0) &&\n (\n start != journal.get_checkpoint_position() ||\n (locked && session->state != Session::State::locking)\n );\n\n if (session->state != Session::State::locking)\n {\n std::cerr << \"Trying to push while not locking.\\n\";\n if (!conflict && !locked)\n {\n std::cerr << \"OK, this session can take the lock.\\n\";\n lock(session, Session::State::locking);\n }\n }\n\n if (session->state == Session::State::locking)\n lock_timeout_timer.cancel();\n\n if (!conflict && size > int64_t(push_buffer.size()))\n push_buffer.resize(size_t(size));\n\n std::cerr << \"Pushing, start = \" << start << \", size = \" << size << ':';\n\n push_transfer\n (\n session,\n 0,\n size_t(size),\n conflict\n );\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::pull_transfer_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n Async_Reader reader,\n std::error_code error,\n size_t bytes_transferred\n )\n {\n if (!error)\n {\n if (reader.get_remaining() > 0)\n {\n std::cerr << '.';\n\n const size_t size = reader.read\n (\n session->buffer,\n Session::buffer_size\n );\n\n net::async_write\n (\n session->socket,\n net::buffer(session->buffer, size_t(size)),\n std::bind\n (\n &Server::pull_transfer_handler,\n this,\n session,\n reader,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n }\n else\n {\n std::cerr << \" OK\\n\";\n read_command(session);\n }\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::pull_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n std::error_code error,\n size_t bytes_transferred\n )\n {\n if (!error)\n {\n const int64_t checkpoint = from_network(session->buffer + 1);\n\n Async_Reader reader = journal.get_tail_reader(checkpoint);\n to_network(reader.get_remaining(), session->buffer + 9);\n\n std::cerr << \"Pulling from checkpoint = \" << checkpoint;\n std::cerr << \", size = \" << reader.get_remaining() << ':';\n\n net::async_write\n (\n session->socket,\n net::buffer(session->buffer, 17),\n std::bind\n (\n &Server::pull_transfer_handler,\n this,\n session,\n reader,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::pull(std::shared_ptr session)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n net::async_read\n (\n session->socket,\n net::buffer(session->buffer + 1, 8),\n std::bind\n (\n &Server::pull_handler,\n this,\n session,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::read_command_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n std::error_code error,\n size_t bytes_transferred\n )\n {\n if (!error)\n {\n std::cerr << \"Received command: \" << session->buffer[0] << '\\n';\n\n switch (session->buffer[0])\n {\n case 'P':\n pull(session);\n break;\n\n case 'L':\n lock(session, Session::State::waiting_for_lock_pull);\n break;\n\n case 'U':\n net::async_read\n (\n session->socket,\n net::buffer(session->buffer, 16),\n std::bind\n (\n &Server::push_handler,\n this,\n session,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n break;\n\n case 'l':\n lock(session, Session::State::waiting_for_lock);\n break;\n\n case 'u':\n if (session->state == Session::State::locking)\n unlock(*session);\n else\n session->buffer[0] = 't';\n write_buffer_and_next_command(session, 1);\n break;\n\n case 'i':\n write_buffer_and_next_command(session, 1);\n write_status();\n break;\n\n case 'Q':\n if (session->state == Session::State::locking)\n unlock(*session);\n break;\n\n default:\n std::cerr << \"Unexpected command\\n\";\n break;\n }\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::read_command(std::shared_ptr session)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n net::async_read\n (\n session->socket,\n net::buffer(session->buffer, 1),\n std::bind\n (\n &Server::read_command_handler,\n this,\n session,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::write_buffer_and_next_command_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n std::error_code error,\n size_t bytes_transferred\n )\n {\n if (!error)\n read_command(session);\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::write_buffer_and_next_command\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n size_t size\n )\n {\n net::async_write\n (\n session->socket,\n net::buffer(session->buffer, size),\n std::bind\n (\n &Server::write_buffer_and_next_command_handler,\n this,\n session,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::handshake_handler\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::shared_ptr session,\n std::error_code error,\n size_t bytes_transferred\n )\n {\n if (!error)\n {\n if\n (\n session->buffer[0] == 'j' &&\n session->buffer[1] == 'o' &&\n session->buffer[2] == 'e' &&\n session->buffer[3] == 'd' &&\n session->buffer[4] == 'b'\n )\n {\n const int64_t client_version = from_network(session->buffer + 5);\n\n std::cerr << \"client_version = \" << client_version << '\\n';\n\n if (client_version < 2)\n to_network(0, session->buffer + 5);\n else\n {\n const int64_t server_version = 2;\n to_network(server_version, session->buffer + 5);\n }\n\n write_buffer_and_next_command(session, 13);\n }\n else\n std::cerr << \"Bad handshake\\n\";\n }\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::handle_accept\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::error_code error,\n net::ip::tcp::socket socket\n )\n {\n if (!error)\n {\n std::shared_ptr session(new Session(*this, std::move(socket)));\n\n net::async_read\n (\n session->socket,\n net::buffer(session->buffer, 13),\n std::bind\n (\n &Server::handshake_handler,\n this,\n session,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n\n start_accept();\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::start_accept()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n acceptor.async_accept\n (\n io_context,\n std::bind\n (\n &Server::handle_accept,\n this,\n std::placeholders::_1,\n std::placeholders::_2\n )\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::start_interrupt_timer()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n interrupt_timer.expires_after\n (\n std::chrono::seconds(interrupt_check_seconds)\n );\n\n interrupt_timer.async_wait\n (\n std::bind\n (\n &Server::handle_interrupt_timer,\n this,\n std::placeholders::_1\n )\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void Server::handle_interrupt_timer(std::error_code error)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (!error)\n {\n if (interrupted)\n {\n std::cerr << \"Interruption detected\\n\";\n io_context.stop();\n }\n\n start_interrupt_timer();\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n Server::Server\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n joedb::Writable_Journal &journal,\n net::io_context &io_context,\n uint16_t port,\n uint32_t lock_timeout_seconds\n ):\n journal(journal),\n io_context(io_context),\n acceptor(io_context, net::ip::tcp::endpoint(net::ip::tcp::v4(), port)),\n interrupt_timer(io_context),\n session_count(0),\n lock_timeout_seconds(lock_timeout_seconds),\n lock_timeout_timer(io_context),\n locked(false)\n {\n write_status();\n\n std::signal(SIGINT, signal_handler);\n\n start_interrupt_timer();\n start_accept();\n }\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: mutex.hxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 14:29:23 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _OSL_MUTEX_HXX_\n#define _OSL_MUTEX_HXX_\n\n#ifdef __cplusplus\n\n#include \n\n\nnamespace osl\n{\n \/** A mutual exclusion synchronization object\n *\/\n class Mutex {\n\n public:\n \/** Create a thread-local mutex.\n @return 0 if the mutex could not be created, otherwise a handle to the mutex.\n @seealso ::osl_createMutex()\n *\/\n Mutex()\n {\n mutex = osl_createMutex();\n }\n\n \/** Release the OS-structures and free mutex data-structure.\n @seealso ::osl_destroyMutex()\n *\/\n ~Mutex()\n {\n osl_destroyMutex(mutex);\n }\n\n \/** Acquire the mutex, block if already acquired by another thread.\n @return sal_False if system-call fails.\n @seealso ::osl_acquireMutex()\n *\/\n sal_Bool acquire()\n {\n return osl_acquireMutex(mutex);\n }\n\n \/** Try to acquire the mutex without blocking.\n @return sal_False if it could not be acquired.\n @seealso ::osl_tryToAcquireMutex()\n *\/\n sal_Bool tryToAcquire()\n {\n return osl_tryToAcquireMutex(mutex);\n }\n\n \/** Release the mutex.\n @return sal_False if system-call fails.\n @seealso ::osl_releaseMutex()\n *\/\n sal_Bool release()\n {\n return osl_releaseMutex(mutex);\n }\n\n \/** Returns a global static mutex object.\n The global and static mutex object can be used to initialize other\n static objects in a thread safe manner.\n @return the global mutex object\n @seealso ::osl_getGlobalMutex()\n *\/\n static Mutex * getGlobalMutex()\n {\n return (Mutex *)osl_getGlobalMutex();\n }\n\n private:\n oslMutex mutex;\n\n \/** The underlying oslMutex has no reference count.\n\n Since the underlying oslMutex is not a reference counted object, copy\n constructed Mutex may work on an already destructed oslMutex object.\n\n *\/\n Mutex(const Mutex&);\n\n \/** The underlying oslMutex has no reference count.\n\n When destructed, the Mutex object destroys the undelying oslMutex,\n which might cause severe problems in case it's a temporary object.\n\n *\/\n Mutex(oslMutex Mutex);\n\n \/** This assignment operator is private for the same reason as\n the copy constructor.\n *\/\n Mutex& operator= (const Mutex&);\n\n \/** This assignment operator is private for the same reason as\n the constructor taking a oslMutex argument.\n *\/\n Mutex& operator= (oslMutex);\n };\n\n \/** A helper class for mutex objects and interfaces.\n *\/\n template\n class Guard\n {\n private:\n Guard( const Guard& );\n const Guard& operator = ( const Guard& );\n\n protected:\n T * pT;\n public:\n\n \/** Acquires the object specified as parameter.\n *\/\n Guard(T * pT_) : pT(pT_)\n {\n pT->acquire();\n }\n\n \/** Acquires the object specified as parameter.\n *\/\n Guard(T & t) : pT(&t)\n {\n pT->acquire();\n }\n\n \/** Releases the mutex or interface. *\/\n ~Guard()\n {\n pT->release();\n }\n };\n\n \/** A helper class for mutex objects and interfaces.\n *\/\n template\n class ClearableGuard\n {\n private:\n ClearableGuard( const ClearableGuard& );\n const ClearableGuard& operator = ( const ClearableGuard& );\n protected:\n T * pT;\n public:\n\n \/** Acquires the object specified as parameter.\n *\/\n ClearableGuard(T * pT_) : pT(pT_)\n {\n pT->acquire();\n }\n\n \/** Acquires the object specified as parameter.\n *\/\n ClearableGuard(T & t) : pT(&t)\n {\n pT->acquire();\n }\n\n \/** Releases the mutex or interface if not already released by clear().\n *\/\n ~ClearableGuard()\n {\n if (pT)\n pT->release();\n }\n\n \/** Releases the mutex or interface.\n *\/\n void clear()\n {\n if(pT)\n {\n pT->release();\n pT = NULL;\n }\n }\n };\n\n \/** A helper class for mutex objects and interfaces.\n *\/\n template< class T >\n class ResettableGuard : public ClearableGuard< T >\n {\n protected:\n T* pResetT;\n public:\n \/** Acquires the object specified as parameter.\n *\/\n ResettableGuard( T* pT ) :\n ClearableGuard( pT ),\n pResetT( pT )\n {}\n\n \/** Acquires the object specified as parameter.\n *\/\n ResettableGuard( T& rT ) :\n ClearableGuard( rT ),\n pResetT( &rT )\n {}\n\n \/** Re-aquires the mutex or interface.\n *\/\n void reset()\n {\n if( pResetT )\n {\n this->pT = pResetT;\n this->pT->acquire();\n }\n }\n };\n\n typedef Guard MutexGuard;\n typedef ClearableGuard ClearableMutexGuard;\n typedef ResettableGuard< Mutex > ResettableMutexGuard;\n}\n\n#endif \/* __cplusplus *\/\n#endif \/* _OSL_MUTEX_HXX_ *\/\n\nINTEGRATION: CWS warnings01 (1.11.122); FILE MERGED 2005\/11\/07 12:11:25 sb 1.11.122.3: #i53898# Made code warning-free (additional -W switches for GCC). 2005\/09\/23 00:35:06 sb 1.11.122.2: RESYNC: (1.11-1.12); FILE MERGED 2005\/09\/20 12:57:14 sb 1.11.122.1: #i53898# Globally disable problematic warnings.\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: mutex.hxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 04:12:44 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _OSL_MUTEX_HXX_\n#define _OSL_MUTEX_HXX_\n\n#ifdef __cplusplus\n\n#include \n\n\nnamespace osl\n{\n \/** A mutual exclusion synchronization object\n *\/\n class Mutex {\n\n public:\n \/** Create a thread-local mutex.\n @return 0 if the mutex could not be created, otherwise a handle to the mutex.\n @seealso ::osl_createMutex()\n *\/\n Mutex()\n {\n mutex = osl_createMutex();\n }\n\n \/** Release the OS-structures and free mutex data-structure.\n @seealso ::osl_destroyMutex()\n *\/\n ~Mutex()\n {\n osl_destroyMutex(mutex);\n }\n\n \/** Acquire the mutex, block if already acquired by another thread.\n @return sal_False if system-call fails.\n @seealso ::osl_acquireMutex()\n *\/\n sal_Bool acquire()\n {\n return osl_acquireMutex(mutex);\n }\n\n \/** Try to acquire the mutex without blocking.\n @return sal_False if it could not be acquired.\n @seealso ::osl_tryToAcquireMutex()\n *\/\n sal_Bool tryToAcquire()\n {\n return osl_tryToAcquireMutex(mutex);\n }\n\n \/** Release the mutex.\n @return sal_False if system-call fails.\n @seealso ::osl_releaseMutex()\n *\/\n sal_Bool release()\n {\n return osl_releaseMutex(mutex);\n }\n\n \/** Returns a global static mutex object.\n The global and static mutex object can be used to initialize other\n static objects in a thread safe manner.\n @return the global mutex object\n @seealso ::osl_getGlobalMutex()\n *\/\n static Mutex * getGlobalMutex()\n {\n return (Mutex *)osl_getGlobalMutex();\n }\n\n private:\n oslMutex mutex;\n\n \/** The underlying oslMutex has no reference count.\n\n Since the underlying oslMutex is not a reference counted object, copy\n constructed Mutex may work on an already destructed oslMutex object.\n\n *\/\n Mutex(const Mutex&);\n\n \/** The underlying oslMutex has no reference count.\n\n When destructed, the Mutex object destroys the undelying oslMutex,\n which might cause severe problems in case it's a temporary object.\n\n *\/\n Mutex(oslMutex Mutex);\n\n \/** This assignment operator is private for the same reason as\n the copy constructor.\n *\/\n Mutex& operator= (const Mutex&);\n\n \/** This assignment operator is private for the same reason as\n the constructor taking a oslMutex argument.\n *\/\n Mutex& operator= (oslMutex);\n };\n\n \/** A helper class for mutex objects and interfaces.\n *\/\n template\n class Guard\n {\n private:\n Guard( const Guard& );\n const Guard& operator = ( const Guard& );\n\n protected:\n T * pT;\n public:\n\n \/** Acquires the object specified as parameter.\n *\/\n Guard(T * pT_) : pT(pT_)\n {\n pT->acquire();\n }\n\n \/** Acquires the object specified as parameter.\n *\/\n Guard(T & t) : pT(&t)\n {\n pT->acquire();\n }\n\n \/** Releases the mutex or interface. *\/\n ~Guard()\n {\n pT->release();\n }\n };\n\n \/** A helper class for mutex objects and interfaces.\n *\/\n template\n class ClearableGuard\n {\n private:\n ClearableGuard( const ClearableGuard& );\n const ClearableGuard& operator = ( const ClearableGuard& );\n protected:\n T * pT;\n public:\n\n \/** Acquires the object specified as parameter.\n *\/\n ClearableGuard(T * pT_) : pT(pT_)\n {\n pT->acquire();\n }\n\n \/** Acquires the object specified as parameter.\n *\/\n ClearableGuard(T & t) : pT(&t)\n {\n pT->acquire();\n }\n\n \/** Releases the mutex or interface if not already released by clear().\n *\/\n ~ClearableGuard()\n {\n if (pT)\n pT->release();\n }\n\n \/** Releases the mutex or interface.\n *\/\n void clear()\n {\n if(pT)\n {\n pT->release();\n pT = NULL;\n }\n }\n };\n\n \/** A helper class for mutex objects and interfaces.\n *\/\n template< class T >\n class ResettableGuard : public ClearableGuard< T >\n {\n private:\n ResettableGuard(ResettableGuard &); \/\/ not defined\n void operator =(ResettableGuard &); \/\/ not defined\n\n protected:\n T* pResetT;\n public:\n \/** Acquires the object specified as parameter.\n *\/\n ResettableGuard( T* pT_ ) :\n ClearableGuard( pT_ ),\n pResetT( pT_ )\n {}\n\n \/** Acquires the object specified as parameter.\n *\/\n ResettableGuard( T& rT ) :\n ClearableGuard( rT ),\n pResetT( &rT )\n {}\n\n \/** Re-aquires the mutex or interface.\n *\/\n void reset()\n {\n if( pResetT )\n {\n this->pT = pResetT;\n this->pT->acquire();\n }\n }\n };\n\n typedef Guard MutexGuard;\n typedef ClearableGuard ClearableMutexGuard;\n typedef ResettableGuard< Mutex > ResettableMutexGuard;\n}\n\n#endif \/* __cplusplus *\/\n#endif \/* _OSL_MUTEX_HXX_ *\/\n\n<|endoftext|>"} {"text":"#include \r\n\r\n#include \"IDAClientManager.h\"\r\n#include \"SocketOperation.h\"\r\n#include \"DataBaseWriter.h\"\r\n#include \"ProcessUtils.h\"\r\n#include \"LogOperation.h\"\r\n\r\nextern LogOperation Logger;\r\n\r\n#define DATA_BUFSIZE 4096\r\n#define DEFAULT_IDA_PATH TEXT( \"c:\\\\Program Files\\\\IDA\\\\idag.exe\" )\r\n\r\nIDAClientManager::IDAClientManager(): \r\n\tEscapedOutputFilename( NULL ), \r\n\tEscapedLogFilename( NULL ), \r\n\tListeningSocket( INVALID_SOCKET ), \r\n\tTheSource( NULL ), \r\n\tTheTarget( NULL ),\r\n\tIDACommandProcessorThreadId( -1 )\r\n{\r\n\tIDAPath=_strdup( DEFAULT_IDA_PATH );\r\n}\r\n\r\nvoid IDAClientManager::SetDatabase( DBWrapper *OutputDB )\r\n{\r\n\tm_OutputDB=OutputDB;\r\n}\r\n\r\nbool IDAClientManager::StartIDAListener( unsigned short port )\r\n{\t\r\n\tStopIDAListener();\r\n\tListeningPort=port;\r\n\tif( ListeningPort>0 )\r\n\t{\r\n\t\tListeningSocket = CreateListener( NULL, port );\r\n\t\tLogger.Log( 10, \"%s: ListeningSocket=%d\\n\", __FUNCTION__, ListeningSocket );\r\n\t\treturn TRUE;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nbool IDAClientManager::StopIDAListener()\r\n{\r\n\tif( ListeningSocket != INVALID_SOCKET )\r\n\t{\r\n\t\tclosesocket( ListeningSocket );\r\n\t\treturn TRUE;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nIDAClientManager::~IDAClientManager()\r\n{\r\n\tStopIDAListener();\r\n\r\n\tif( IDAPath )\r\n\t\tfree( IDAPath );\r\n\tif( EscapedOutputFilename )\r\n\t\tfree( EscapedOutputFilename );\r\n\tif( EscapedLogFilename )\r\n\t\tfree( EscapedLogFilename );\r\n\r\n\tif( TheSource )\r\n\t\tdelete TheSource;\r\n\r\n\tif( TheTarget )\r\n\t\tdelete TheTarget;\r\n}\r\n\r\nOneIDAClientManager *IDAClientManager::GetOneIDAClientManagerFromFile( char *DataFile )\r\n{\r\n\tOneIDAClientManager *pOneIDAClientManager=new OneIDAClientManager( m_OutputDB );\r\n\tpOneIDAClientManager->Retrieve( DataFile );\r\n\treturn pOneIDAClientManager;\r\n}\r\n\r\nBOOL IDAClientManager::AcceptIDAClient( OneIDAClientManager *pOneIDAClientManager, bool RetrieveData )\r\n{\r\n\tSOCKET ClientSocket=accept( ListeningSocket, NULL, NULL );\r\n\tLogger.Log( 10, \"%s: accepting=%d\\n\", __FUNCTION__, ClientSocket );\r\n\tif( ClientSocket==INVALID_SOCKET )\r\n\t{\r\n\t\tint error=WSAGetLastError();\r\n\t\tLogger.Log( 10, \"Socket error=%d\\n\", error );\r\n\t\treturn FALSE;\r\n\t}else\r\n\t{\r\n\t\tif( RetrieveData )\r\n\t\t{\r\n\t\t\tLogger.Log( 10, \"%s: Calling RetrieveIDARawDataFromSocket\\n\", __FUNCTION__ );\r\n\t\t\tpOneIDAClientManager->RetrieveIDARawDataFromSocket( ClientSocket );\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tLogger.Log( 10, \"%s: SetSocket\\n\", __FUNCTION__ );\r\n\t\t\tpOneIDAClientManager->SetSocket( ClientSocket );\r\n\t\t}\r\n\t\treturn TRUE;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nDWORD IDAClientManager::SetMembers( OneIDAClientManager *OneIDAClientManagerTheSource, OneIDAClientManager *OneIDAClientManagerTheTarget, DiffMachine *pArgDiffMachine )\r\n{\r\n\tTheSource=OneIDAClientManagerTheSource;\r\n\tTheTarget=OneIDAClientManagerTheTarget;\r\n\tpDiffMachine=pArgDiffMachine;\r\n\treturn 1;\r\n}\r\n\r\nDWORD IDAClientManager::IDACommandProcessor()\r\n{\r\n\tSOCKET SocketArray[WSA_MAXIMUM_WAIT_EVENTS];\r\n\tWSAEVENT EventArray[WSA_MAXIMUM_WAIT_EVENTS];\r\n\tWSANETWORKEVENTS NetworkEvents;\r\n\tDWORD EventTotal=0, index;\r\n\r\n\tSocketArray[0]=TheSource->GetSocket();\r\n\tSocketArray[1]=TheTarget->GetSocket();\r\n\tfor( int i=0;i<2;i++ )\r\n\t{\r\n\t\tWSAEVENT NewEvent=WSACreateEvent();\r\n\t\tWSAEventSelect( SocketArray[i], NewEvent, FD_READ|FD_CLOSE );\r\n\t\tEventArray[EventTotal]=NewEvent;\r\n\t\tEventTotal++;\r\n\t}\r\n\twhile( 1 )\r\n\t{\r\n\t\tindex=WSAWaitForMultipleEvents( EventTotal, \r\n\t\t\tEventArray, \r\n\t\t\tFALSE, \r\n\t\t\tWSA_INFINITE, \r\n\t\t\tFALSE );\r\n\r\n\t\tif( index<0 )\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tindex=index-WSA_WAIT_EVENT_0;\r\n\t\t\/\/-------------------------\r\n\t\t\/\/ Iterate through all events and enumerate\r\n\t\t\/\/ if the wait does not fail.\r\n\t\tfor( DWORD i=index; i=4 )\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tDWORD address=*( DWORD * )data;\r\n\t\t\t\t\t\t\t\tLogger.Log( 10, \"%s: Showing address=%x\\n\", __FUNCTION__, address );\r\n\t\t\t\t\t\t\t\t\/\/Get Matching Address\r\n\r\n\t\t\t\t\t\t\t\tDWORD MatchingAddress = 0;\r\n\t\t\t\t\t\t\t\tif( pDiffMachine )\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tMatchingAddress = pDiffMachine->GetMatchAddr( i, address );\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tif( MatchingAddress!=0 )\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\/\/Show using JUMP_TO_ADDR\r\n\t\t\t\t\t\t\t\t\tif( i==0 )\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tTheTarget->ShowAddress( MatchingAddress );\r\n\t\t\t\t\t\t\t\t\t}else\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tTheSource->ShowAddress( MatchingAddress );\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\t\t\t\t\t\t\r\n\t\t\t\t\t}else if( NetworkEvents.lNetworkEvents==FD_CLOSE )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tclosesocket( SocketArray[i] );\r\n\t\t\t\t\t\tWSACloseEvent( EventArray[i] );\r\n\t\t\t\t\t\tmemcpy( SocketArray+i, SocketArray+i+1, EventTotal-i+1 );\r\n\t\t\t\t\t\tmemcpy( EventArray+i, EventArray+i+1, EventTotal-i+1 );\r\n\t\t\t\t\t\tEventTotal--;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn 1;\r\n}\r\n\r\nDWORD WINAPI IDACommandProcessorThread( LPVOID lpParameter )\r\n{\r\n\tIDAClientManager *pIDAClientManager=( IDAClientManager * )lpParameter;\r\n\tpIDAClientManager->IDACommandProcessor();\r\n\treturn 1;\r\n}\r\n\r\nBOOL IDAClientManager::CreateIDACommandProcessorThread()\r\n{\r\n\tif( IDACommandProcessorThreadId > 0 )\r\n\t{\r\n\t\tHANDLE hThread = OpenThread( THREAD_ALL_ACCESS, FALSE, IDACommandProcessorThreadId );\r\n\t\tif( hThread )\r\n\t\t{\r\n\t\t\tCloseHandle( hThread );\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tIDACommandProcessorThreadId = -1;\r\n\t\t}\r\n\t}\r\n\r\n\tif( IDACommandProcessorThreadId == -1 )\r\n\t{\r\n\t\tCreateThread( NULL, 0, IDACommandProcessorThread, ( PVOID )this, 0, &IDACommandProcessorThreadId );\r\n\t\treturn TRUE;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nvoid SendAddMatchAddrTLVData( FunctionMatchInfo &Data, PVOID Context )\r\n{\r\n\tOneIDAClientManager *TheSource=( OneIDAClientManager * )Context;\r\n\tif( TheSource )\r\n\t{\r\n\t\tTheSource->SendTLVData( \r\n\t\t\tADD_MATCH_ADDR, \r\n\t\t\t( PBYTE )&( Data ), \r\n\t\t\tsizeof( Data ) );\r\n\t}\r\n}\r\n\r\nvoid SendUnidentifiedAddrTLVData( DWORD Data, PVOID Context )\r\n{\r\n\tOneIDAClientManager *TheSource=( OneIDAClientManager * )Context;\r\n\tif( TheSource )\r\n\t{\r\n\t\tTheSource->SendTLVData( \r\n\t\t\tADD_UNINDENTIFIED_ADDR, \r\n\t\t\t( PBYTE )&( Data ), \r\n\t\t\tsizeof( Data ) );\r\n\t}\r\n}\r\n\r\nvoid IDAClientManager::ShowResultsOnIDA()\r\n{\r\n\tpDiffMachine->ExecuteOnFunctionMatchInfoList( SendAddMatchAddrTLVData, ( PVOID )TheSource );\r\n\tpDiffMachine->ExecuteOnTheSourceUnidentifedBlockHash( SendUnidentifiedAddrTLVData, ( PVOID )TheSource );\r\n\tpDiffMachine->ExecuteOnTheTargetUnidentifedBlockHash( SendUnidentifiedAddrTLVData, ( PVOID )TheTarget );\r\n#ifdef TODO\r\n\tfor( iter=ReverseFunctionMatchInfoList.begin();iter!=ReverseFunctionMatchInfoList.end();iter++ )\r\n\t{\r\n\t\tTheTarget->SendTLVData( \r\n\t\t\tADD_MATCH_ADDR, \r\n\t\t\t( PBYTE )&( *iter ), \r\n\t\t\tsizeof( *iter ) );\r\n\t}\r\n#endif\r\n\tTheSource->SendTLVData( \r\n\t\tSHOW_DATA, \r\n\t\t( PBYTE )\"test\", \r\n\t\t4 );\r\n\tTheTarget->SendTLVData( \r\n\t\tSHOW_DATA, \r\n\t\t( PBYTE )\"test\", \r\n\t\t4 );\t\r\n}\r\n\r\n#define RUN_DARUNGRIM2_PLUGIN_STR \"static main()\\n\\\r\n{\\n\\\r\n\tWait();\\n\\\r\n\tRunPlugin( \\\"DarunGrim2\\\", 1 );\\n\\\r\n\tSetLogFile( \\\"%s\\\" );\\n\\\r\n\tSaveAnalysisData( \\\"%s\\\", %d, %d );\\n\\\r\n\tExit( 0 );\\n\\\r\n}\"\r\n\r\n#define CONNECT_TO_DARUNGRIM2_STR \"static main()\\n\\\r\n{\\n\\\r\n\tWait();\\n\\\r\n\tRunPlugin( \\\"DarunGrim2\\\", 1 );\\n\\\r\n\tSetLogFile( \\\"%s\\\" );\\n\\\r\n\tConnectToDarunGrim2();\\n\\\r\n\tExit( 0 );\\n\\\r\n}\"\r\n\r\nvoid IDAClientManager::SetIDAPath( const char *ParamIDAPath )\r\n{\r\n\tif( IDAPath )\r\n\t\tfree( IDAPath );\r\n\tIDAPath=_strdup( ParamIDAPath );\r\n}\r\n\r\nvoid IDAClientManager::SetOutputFilename( char *OutputFilename )\r\n{\r\n\t\/\/Create IDC file\r\n\tEscapedOutputFilename=( char * )malloc( strlen( OutputFilename )*2+1 );\r\n\r\n\tif( EscapedOutputFilename )\r\n\t{\r\n\t\tDWORD i=0, j=0;\r\n\t\tfor( ;iUse showing mode by default#include \r\n\r\n#include \"IDAClientManager.h\"\r\n#include \"SocketOperation.h\"\r\n#include \"DataBaseWriter.h\"\r\n#include \"ProcessUtils.h\"\r\n#include \"LogOperation.h\"\r\n\r\nextern LogOperation Logger;\r\n\r\n#define DATA_BUFSIZE 4096\r\n#define DEFAULT_IDA_PATH TEXT( \"c:\\\\Program Files\\\\IDA\\\\idag.exe\" )\r\n\r\nIDAClientManager::IDAClientManager(): \r\n\tEscapedOutputFilename( NULL ), \r\n\tEscapedLogFilename( NULL ), \r\n\tListeningSocket( INVALID_SOCKET ), \r\n\tTheSource( NULL ), \r\n\tTheTarget( NULL ),\r\n\tIDACommandProcessorThreadId( -1 )\r\n{\r\n\tIDAPath=_strdup( DEFAULT_IDA_PATH );\r\n}\r\n\r\nvoid IDAClientManager::SetDatabase( DBWrapper *OutputDB )\r\n{\r\n\tm_OutputDB=OutputDB;\r\n}\r\n\r\nbool IDAClientManager::StartIDAListener( unsigned short port )\r\n{\t\r\n\tStopIDAListener();\r\n\tListeningPort=port;\r\n\tif( ListeningPort>0 )\r\n\t{\r\n\t\tListeningSocket = CreateListener( NULL, port );\r\n\t\tLogger.Log( 10, \"%s: ListeningSocket=%d\\n\", __FUNCTION__, ListeningSocket );\r\n\t\treturn TRUE;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nbool IDAClientManager::StopIDAListener()\r\n{\r\n\tif( ListeningSocket != INVALID_SOCKET )\r\n\t{\r\n\t\tclosesocket( ListeningSocket );\r\n\t\treturn TRUE;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nIDAClientManager::~IDAClientManager()\r\n{\r\n\tStopIDAListener();\r\n\r\n\tif( IDAPath )\r\n\t\tfree( IDAPath );\r\n\tif( EscapedOutputFilename )\r\n\t\tfree( EscapedOutputFilename );\r\n\tif( EscapedLogFilename )\r\n\t\tfree( EscapedLogFilename );\r\n\r\n\tif( TheSource )\r\n\t\tdelete TheSource;\r\n\r\n\tif( TheTarget )\r\n\t\tdelete TheTarget;\r\n}\r\n\r\nOneIDAClientManager *IDAClientManager::GetOneIDAClientManagerFromFile( char *DataFile )\r\n{\r\n\tOneIDAClientManager *pOneIDAClientManager=new OneIDAClientManager( m_OutputDB );\r\n\tpOneIDAClientManager->Retrieve( DataFile );\r\n\treturn pOneIDAClientManager;\r\n}\r\n\r\nBOOL IDAClientManager::AcceptIDAClient( OneIDAClientManager *pOneIDAClientManager, bool RetrieveData )\r\n{\r\n\tSOCKET ClientSocket=accept( ListeningSocket, NULL, NULL );\r\n\tLogger.Log( 10, \"%s: accepting=%d\\n\", __FUNCTION__, ClientSocket );\r\n\tif( ClientSocket==INVALID_SOCKET )\r\n\t{\r\n\t\tint error=WSAGetLastError();\r\n\t\tLogger.Log( 10, \"Socket error=%d\\n\", error );\r\n\t\treturn FALSE;\r\n\t}else\r\n\t{\r\n\t\tif( RetrieveData )\r\n\t\t{\r\n\t\t\tLogger.Log( 10, \"%s: Calling RetrieveIDARawDataFromSocket\\n\", __FUNCTION__ );\r\n\t\t\tpOneIDAClientManager->RetrieveIDARawDataFromSocket( ClientSocket );\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tLogger.Log( 10, \"%s: SetSocket\\n\", __FUNCTION__ );\r\n\t\t\tpOneIDAClientManager->SetSocket( ClientSocket );\r\n\t\t}\r\n\t\treturn TRUE;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nDWORD IDAClientManager::SetMembers( OneIDAClientManager *OneIDAClientManagerTheSource, OneIDAClientManager *OneIDAClientManagerTheTarget, DiffMachine *pArgDiffMachine )\r\n{\r\n\tTheSource=OneIDAClientManagerTheSource;\r\n\tTheTarget=OneIDAClientManagerTheTarget;\r\n\tpDiffMachine=pArgDiffMachine;\r\n\treturn 1;\r\n}\r\n\r\nDWORD IDAClientManager::IDACommandProcessor()\r\n{\r\n\tSOCKET SocketArray[WSA_MAXIMUM_WAIT_EVENTS];\r\n\tWSAEVENT EventArray[WSA_MAXIMUM_WAIT_EVENTS];\r\n\tWSANETWORKEVENTS NetworkEvents;\r\n\tDWORD EventTotal=0, index;\r\n\r\n\tSocketArray[0]=TheSource->GetSocket();\r\n\tSocketArray[1]=TheTarget->GetSocket();\r\n\tfor( int i=0;i<2;i++ )\r\n\t{\r\n\t\tWSAEVENT NewEvent=WSACreateEvent();\r\n\t\tWSAEventSelect( SocketArray[i], NewEvent, FD_READ|FD_CLOSE );\r\n\t\tEventArray[EventTotal]=NewEvent;\r\n\t\tEventTotal++;\r\n\t}\r\n\twhile( 1 )\r\n\t{\r\n\t\tindex=WSAWaitForMultipleEvents( EventTotal, \r\n\t\t\tEventArray, \r\n\t\t\tFALSE, \r\n\t\t\tWSA_INFINITE, \r\n\t\t\tFALSE );\r\n\r\n\t\tif( index<0 )\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tindex=index-WSA_WAIT_EVENT_0;\r\n\t\t\/\/-------------------------\r\n\t\t\/\/ Iterate through all events and enumerate\r\n\t\t\/\/ if the wait does not fail.\r\n\t\tfor( DWORD i=index; i=4 )\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tDWORD address=*( DWORD * )data;\r\n\t\t\t\t\t\t\t\tLogger.Log( 10, \"%s: Showing address=%x\\n\", __FUNCTION__, address );\r\n\t\t\t\t\t\t\t\t\/\/Get Matching Address\r\n\r\n\t\t\t\t\t\t\t\tDWORD MatchingAddress = 0;\r\n\t\t\t\t\t\t\t\tif( pDiffMachine )\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tMatchingAddress = pDiffMachine->GetMatchAddr( i, address );\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tif( MatchingAddress!=0 )\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\/\/Show using JUMP_TO_ADDR\r\n\t\t\t\t\t\t\t\t\tif( i==0 )\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tTheTarget->ShowAddress( MatchingAddress );\r\n\t\t\t\t\t\t\t\t\t}else\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tTheSource->ShowAddress( MatchingAddress );\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\t\t\t\t\t\t\r\n\t\t\t\t\t}else if( NetworkEvents.lNetworkEvents==FD_CLOSE )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tclosesocket( SocketArray[i] );\r\n\t\t\t\t\t\tWSACloseEvent( EventArray[i] );\r\n\t\t\t\t\t\tmemcpy( SocketArray+i, SocketArray+i+1, EventTotal-i+1 );\r\n\t\t\t\t\t\tmemcpy( EventArray+i, EventArray+i+1, EventTotal-i+1 );\r\n\t\t\t\t\t\tEventTotal--;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn 1;\r\n}\r\n\r\nDWORD WINAPI IDACommandProcessorThread( LPVOID lpParameter )\r\n{\r\n\tIDAClientManager *pIDAClientManager=( IDAClientManager * )lpParameter;\r\n\tpIDAClientManager->IDACommandProcessor();\r\n\treturn 1;\r\n}\r\n\r\nBOOL IDAClientManager::CreateIDACommandProcessorThread()\r\n{\r\n\tif( IDACommandProcessorThreadId > 0 )\r\n\t{\r\n\t\tHANDLE hThread = OpenThread( THREAD_ALL_ACCESS, FALSE, IDACommandProcessorThreadId );\r\n\t\tif( hThread )\r\n\t\t{\r\n\t\t\tCloseHandle( hThread );\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tIDACommandProcessorThreadId = -1;\r\n\t\t}\r\n\t}\r\n\r\n\tif( IDACommandProcessorThreadId == -1 )\r\n\t{\r\n\t\tCreateThread( NULL, 0, IDACommandProcessorThread, ( PVOID )this, 0, &IDACommandProcessorThreadId );\r\n\t\treturn TRUE;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nvoid SendAddMatchAddrTLVData( FunctionMatchInfo &Data, PVOID Context )\r\n{\r\n\tOneIDAClientManager *TheSource=( OneIDAClientManager * )Context;\r\n\tif( TheSource )\r\n\t{\r\n\t\tTheSource->SendTLVData( \r\n\t\t\tADD_MATCH_ADDR, \r\n\t\t\t( PBYTE )&( Data ), \r\n\t\t\tsizeof( Data ) );\r\n\t}\r\n}\r\n\r\nvoid SendUnidentifiedAddrTLVData( DWORD Data, PVOID Context )\r\n{\r\n\tOneIDAClientManager *TheSource=( OneIDAClientManager * )Context;\r\n\tif( TheSource )\r\n\t{\r\n\t\tTheSource->SendTLVData( \r\n\t\t\tADD_UNINDENTIFIED_ADDR, \r\n\t\t\t( PBYTE )&( Data ), \r\n\t\t\tsizeof( Data ) );\r\n\t}\r\n}\r\n\r\nvoid IDAClientManager::ShowResultsOnIDA()\r\n{\r\n\tpDiffMachine->ExecuteOnFunctionMatchInfoList( SendAddMatchAddrTLVData, ( PVOID )TheSource );\r\n\tpDiffMachine->ExecuteOnTheSourceUnidentifedBlockHash( SendUnidentifiedAddrTLVData, ( PVOID )TheSource );\r\n\tpDiffMachine->ExecuteOnTheTargetUnidentifedBlockHash( SendUnidentifiedAddrTLVData, ( PVOID )TheTarget );\r\n#ifdef TODO\r\n\tfor( iter=ReverseFunctionMatchInfoList.begin();iter!=ReverseFunctionMatchInfoList.end();iter++ )\r\n\t{\r\n\t\tTheTarget->SendTLVData( \r\n\t\t\tADD_MATCH_ADDR, \r\n\t\t\t( PBYTE )&( *iter ), \r\n\t\t\tsizeof( *iter ) );\r\n\t}\r\n#endif\r\n\tTheSource->SendTLVData( \r\n\t\tSHOW_DATA, \r\n\t\t( PBYTE )\"test\", \r\n\t\t4 );\r\n\tTheTarget->SendTLVData( \r\n\t\tSHOW_DATA, \r\n\t\t( PBYTE )\"test\", \r\n\t\t4 );\t\r\n}\r\n\r\n#define RUN_DARUNGRIM2_PLUGIN_STR \"static main()\\n\\\r\n{\\n\\\r\n\tWait();\\n\\\r\n\tRunPlugin( \\\"DarunGrim2\\\", 1 );\\n\\\r\n\tSetLogFile( \\\"%s\\\" );\\n\\\r\n\tSaveAnalysisData( \\\"%s\\\", %d, %d );\\n\\\r\n\tExit( 0 );\\n\\\r\n}\"\r\n\r\n#define CONNECT_TO_DARUNGRIM2_STR \"static main()\\n\\\r\n{\\n\\\r\n\tWait();\\n\\\r\n\tRunPlugin( \\\"DarunGrim2\\\", 1 );\\n\\\r\n\tSetLogFile( \\\"%s\\\" );\\n\\\r\n\tConnectToDarunGrim2();\\n\\\r\n\tExit( 0 );\\n\\\r\n}\"\r\n\r\nvoid IDAClientManager::SetIDAPath( const char *ParamIDAPath )\r\n{\r\n\tif( IDAPath )\r\n\t\tfree( IDAPath );\r\n\tIDAPath=_strdup( ParamIDAPath );\r\n}\r\n\r\nvoid IDAClientManager::SetOutputFilename( char *OutputFilename )\r\n{\r\n\t\/\/Create IDC file\r\n\tEscapedOutputFilename=( char * )malloc( strlen( OutputFilename )*2+1 );\r\n\r\n\tif( EscapedOutputFilename )\r\n\t{\r\n\t\tDWORD i=0, j=0;\r\n\t\tfor( ;i"} {"text":"#include \"synctool.h\"\r\n#include \r\n#include \r\n#include \r\n\r\nbool isFile(string path)\r\n{\r\n\tstruct stat st;\r\n\treturn (lstat(path.c_str(), &st) != -1) && TYPE(st) == S_IFREG;\r\n}\r\n\r\nbool isDirectory(string path)\r\n{\r\n\tstruct stat st;\r\n\treturn (lstat(path.c_str(), &st) != -1) && TYPE(st) == S_IFDIR;\r\n}\r\n\r\nbool isLink(string path)\r\n{\r\n\tstruct stat st;\r\n\treturn (lstat(path.c_str(), &st) != -1) && TYPE(st) == S_IFLNK;\r\n}\r\n\r\n\/* Write with colorized output *\/\r\nvoid setColor(string color)\r\n{\r\n\tif (gUseColors)\r\n\t\tcout << color;\r\n}\r\n\r\n\/* File operations *\/\r\nvoid removeFile(string file)\r\n{\r\n\tif (!isFile(file))\r\n\t\treturn;\r\n\r\n\tlogMessage(\"RM \" + file, RED);\r\n\tif(remove(file.c_str()) == -1)\r\n\t\tdie(EXIT_FAILURE, \"Error: Could not delete \" + file);\r\n}\r\n\r\nvoid copyFile(string src, string dst)\r\n{\r\n\tif (!filesDiffer(src, dst))\r\n\t\treturn;\r\n\r\n\tif (isFile(dst))\r\n\t\tremoveFile(dst);\r\n\r\n\tlogMessage(\"CP \" + src + \" -> \" + dst, BLUE);\r\n\t\r\n\tifstream fin(src.c_str(), ios::binary);\r\n\tofstream fout(dst.c_str(), ios::binary);\r\n\r\n\tif (!(fin.is_open() && fout.is_open() && (fout << fin.rdbuf())))\r\n\t\tdie(EXIT_FAILURE, \"Error: Could not copy \" + src);\r\n\r\n\tfin.close();\r\n\tfout.close();\r\n\r\n\tstruct stat st;\r\n\r\n\tif (stat(src.c_str(), &st) != -1)\r\n\t{\r\n\t\tstruct utimbuf buf;\r\n\r\n\t\tbuf.actime = st.st_atime;\r\n\t\tbuf.modtime = st.st_mtime;\r\n\r\n\t\tutime(dst.c_str(), &buf);\r\n\r\n\t\t\/* also copy file permissions *\/\r\n\t\tchmod(dst.c_str(), st.st_mode);\r\n\t}\r\n}\r\n\r\nvoid copyLink(string src, string dst)\r\n{\r\n\tint r;\r\n\tchar *target;\r\n\t\r\n\tint size = 1024;\r\n\tstruct stat st;\r\n\r\n\tremoveFile(dst);\r\n\t\r\n\tif ((r = lstat(src.c_str(), &st)) != -1)\r\n\t{\r\n\t\tsize = st.st_size;\r\n\t}\r\n\r\n\ttarget = new char[size];\r\n\r\n\tif (readlink(src.c_str(), target, size) == -1)\r\n\t\tdie(EXIT_FAILURE, \"Error: Could not read link \" + src);\r\n\r\n\tlogMessage(\"LN \" + dst + \" -> \" + target, BLUE);\r\n\r\n\tif (symlink(target, dst.c_str()) == -1)\r\n\t\tdie(EXIT_FAILURE, \"Error: Could not create link \" + dst);\r\n\r\n\tdelete target;\r\n\r\n\tif (r != -1)\r\n\t{\r\n\t\tstruct utimbuf buf;\r\n\r\n\t\tbuf.actime = st.st_atime;\r\n\t\tbuf.modtime = st.st_mtime;\r\n\r\n\t\tutime(dst.c_str(), &buf);\r\n\t}\r\n}\r\n\r\nvoid removeDirectory(string dir)\r\n{\r\n\tif (!isDirectory(dir))\r\n\t\treturn;\r\n\r\n\tDIR *d = opendir(dir.c_str());\r\n\tstruct dirent *ent = NULL;\r\n\r\n\twhile ((ent = readdir(d)))\r\n\t{\r\n\t\tif (string(ent->d_name) == \".\" || string(ent->d_name) == \"..\")\r\n\t\t\tcontinue;\r\n\r\n\t\tstring path = dir + '\/' + ent->d_name;\r\n\r\n\t\tif (isDirectory(path))\r\n\t\t\tremoveDirectory(path);\r\n\t\telse\r\n\t\t\tremoveFile(path);\r\n\t}\r\n\r\n\tclosedir(d);\r\n\r\n\tlogMessage(\"RM \" + dir, RED);\r\n\tif (rmdir(dir.c_str()) == -1)\r\n\t\tdie(EXIT_FAILURE, \"Error: Could not delete \" + dir);\r\n}\r\n\r\nvoid assertCanOpenDirectory(string dir)\r\n{\r\n\tDIR *d = opendir(dir.c_str());\r\n\tif (d == NULL)\r\n\t\tdie(EXIT_FAILURE, \"Error: Cannot access \" + dir);\r\n\r\n\tclosedir(d);\r\n}\r\n\r\nvoid copyAllFiles(string src, string dst)\r\n{\r\n\tDIR *d = opendir(src.c_str());\r\n\tstruct dirent *ent = NULL;\r\n\r\n\twhile ((ent = readdir(d)))\r\n\t{\r\n\t\tif (string(ent->d_name) == \".\" || string(ent->d_name) == \"..\")\r\n\t\t\tcontinue;\r\n\r\n\t\tstring srcPath = src + '\/' + ent->d_name;\r\n\t\tstring dstPath = dst + '\/' + ent->d_name;\r\n\r\n\t\tif (isDirectory(srcPath))\r\n\t\t\tcopyAllFiles(srcPath, dstPath);\r\n\t\telse if (isFile(srcPath))\r\n\t\t\tcopyFile(srcPath, dstPath);\r\n\t\telse if (isLink(srcPath))\r\n\t\t\tcopyLink(srcPath, dstPath);\r\n\t}\r\n\r\n\tclosedir(d);\r\n}\r\n\r\nvoid copyNewAndUpdatedFiles(string src, string dst)\r\n{\r\n\tDIR *d = opendir(src.c_str());\r\n\tstruct dirent *ent = NULL;\r\n\r\n\twhile ((ent = readdir(d)))\r\n\t{\r\n\t\tif (string(ent->d_name) == \".\" || string(ent->d_name) == \"..\")\r\n\t\t\tcontinue;\r\n\r\n\t\tstring srcPath = src + '\/' + ent->d_name;\r\n\t\tstring dstPath = dst + '\/' + ent->d_name;\r\n\r\n\t\tif (isDirectory(srcPath) && !isDirectory(dstPath))\r\n\t\t\tlogMessage(\"Warning: \" + srcPath + \" is a directory, but \" + dstPath + \" is not.\");\r\n\t\telse if (!isDirectory(srcPath) && isDirectory(dstPath))\r\n\t\t\tlogMessage(\"Warning: \" + srcPath + \" is not a directory, but \" + dstPath + \" is.\");\r\n\t\telse if (isDirectory(srcPath))\r\n\t\t\tcopyNewAndUpdatedFiles(srcPath, dstPath);\r\n\t\telse if (isFile(srcPath) && isNewer(srcPath, dstPath))\r\n\t\t\tcopyFile(srcPath, dstPath);\r\n\t\telse if (isLink(srcPath))\r\n\t\t\tcopyLink(srcPath, dstPath);\r\n\t}\r\n\r\n\tclosedir(d);\r\n}\r\n\r\nvoid createDirectoryTree(string src, string dst)\r\n{\r\n\tDIR *d = opendir(src.c_str());\r\n\tstruct dirent *ent = NULL;\r\n\r\n\twhile ((ent = readdir(d)))\r\n\t{\r\n\t\tif (string(ent->d_name) == \".\" || string(ent->d_name) == \"..\")\r\n\t\t\tcontinue;\r\n\r\n\t\tstring srcPath = src + '\/' + ent->d_name;\r\n\t\tstring dstPath = dst + '\/' + ent->d_name;\r\n\r\n\t\tif (isDirectory(srcPath) && !isDirectory(dstPath))\r\n\t\t{\r\n\t\t\tif (isFile(dstPath) || isLink(dstPath))\r\n\t\t\t\tremoveFile(dstPath);\r\n\r\n\t\t\tlogMessage(\"MK \" + dstPath);\r\n\t\t\tif (mkdir(dstPath.c_str(), 0775) == -1)\r\n\t\t\t\tdie(EXIT_FAILURE, \"Could not create \" + dstPath);\r\n\r\n\t\t\tstruct stat st;\r\n\r\n\t\t\tif (stat(srcPath.c_str(), &st) != -1)\r\n\t\t\t{\r\n\t\t\t\tstruct utimbuf buf;\r\n\t\t\t\tbuf.actime = st.st_atime;\r\n\t\t\t\tbuf.modtime = st.st_mtime;\r\n\r\n\t\t\t\tutime(dstPath.c_str(), &buf);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (isDirectory(srcPath) && isDirectory(dstPath))\r\n\t\t\tcreateDirectoryTree(srcPath, dstPath);\r\n\t}\r\n\r\n\tclosedir(d);\r\n}\r\n\r\nvoid removeMissing(string src, string dst)\r\n{\r\n\tDIR *d = opendir(dst.c_str());\r\n\tstruct dirent *ent;\r\n\r\n\twhile ((ent = readdir(d)))\r\n\t{\r\n\t\tif (string(ent->d_name) == \".\" || string(ent->d_name) == \"..\")\r\n\t\t\tcontinue;\r\n\r\n\t\tstring srcPath = src + '\/' + ent->d_name;\r\n\t\tstring dstPath = dst + '\/' + ent->d_name;\r\n\r\n\t\tif (isDirectory(dstPath) && !isDirectory(srcPath))\r\n\t\t\tremoveDirectory(dstPath);\r\n\t\telse if (isFile(dstPath) && !isFile(srcPath))\r\n\t\t\tremoveFile(dstPath);\r\n\t\telse if (isLink(dstPath) && !isLink(srcPath))\r\n\t\t\tremoveFile(dstPath);\r\n\t\telse if (isDirectory(dstPath) && isDirectory(srcPath))\r\n\t\t\tremoveMissing(srcPath, dstPath);\r\n\r\n\t}\r\n\r\n\tclosedir(d);\r\n}\r\nfixed unable to copy errors on empty files#include \"synctool.h\"\r\n#include \r\n#include \r\n#include \r\n\r\nbool isFile(string path)\r\n{\r\n\tstruct stat st;\r\n\treturn (lstat(path.c_str(), &st) != -1) && TYPE(st) == S_IFREG;\r\n}\r\n\r\nbool isDirectory(string path)\r\n{\r\n\tstruct stat st;\r\n\treturn (lstat(path.c_str(), &st) != -1) && TYPE(st) == S_IFDIR;\r\n}\r\n\r\nbool isLink(string path)\r\n{\r\n\tstruct stat st;\r\n\treturn (lstat(path.c_str(), &st) != -1) && TYPE(st) == S_IFLNK;\r\n}\r\n\r\n\/* Write with colorized output *\/\r\nvoid setColor(string color)\r\n{\r\n\tif (gUseColors)\r\n\t\tcout << color;\r\n}\r\n\r\n\/* File operations *\/\r\nvoid removeFile(string file)\r\n{\r\n\tif (!isFile(file))\r\n\t\treturn;\r\n\r\n\tlogMessage(\"RM \" + file, RED);\r\n\tif(remove(file.c_str()) == -1)\r\n\t\tdie(EXIT_FAILURE, \"Error: Could not delete \" + file);\r\n}\r\n\r\nvoid copyFile(string src, string dst)\r\n{\r\n\tif (!filesDiffer(src, dst))\r\n\t\treturn;\r\n\r\n\tif (isFile(dst))\r\n\t\tremoveFile(dst);\r\n\r\n\tlogMessage(\"CP \" + src + \" -> \" + dst, BLUE);\r\n\t\r\n\tifstream fin(src.c_str(), ios::binary);\r\n\tofstream fout(dst.c_str(), ios::binary);\r\n\r\n\tif (!(fin.is_open() && fout.is_open()))\r\n\t\tdie(EXIT_FAILURE, \"Error: Could not copy \" + src);\r\n\r\n\tfout << fin.rdbuf();\r\n\r\n\tfin.close();\r\n\tfout.close();\r\n\r\n\tstruct stat st;\r\n\r\n\tif (stat(src.c_str(), &st) != -1)\r\n\t{\r\n\t\tstruct utimbuf buf;\r\n\r\n\t\tbuf.actime = st.st_atime;\r\n\t\tbuf.modtime = st.st_mtime;\r\n\r\n\t\tutime(dst.c_str(), &buf);\r\n\r\n\t\t\/* also copy file permissions *\/\r\n\t\tchmod(dst.c_str(), st.st_mode);\r\n\t}\r\n}\r\n\r\nvoid copyLink(string src, string dst)\r\n{\r\n\tint r;\r\n\tchar *target;\r\n\t\r\n\tint size = 1024;\r\n\tstruct stat st;\r\n\r\n\tremoveFile(dst);\r\n\t\r\n\tif ((r = lstat(src.c_str(), &st)) != -1)\r\n\t{\r\n\t\tsize = st.st_size;\r\n\t}\r\n\r\n\ttarget = new char[size];\r\n\r\n\tif (readlink(src.c_str(), target, size) == -1)\r\n\t\tdie(EXIT_FAILURE, \"Error: Could not read link \" + src);\r\n\r\n\tlogMessage(\"LN \" + dst + \" -> \" + target, BLUE);\r\n\r\n\tif (symlink(target, dst.c_str()) == -1)\r\n\t\tdie(EXIT_FAILURE, \"Error: Could not create link \" + dst);\r\n\r\n\tdelete target;\r\n\r\n\tif (r != -1)\r\n\t{\r\n\t\tstruct utimbuf buf;\r\n\r\n\t\tbuf.actime = st.st_atime;\r\n\t\tbuf.modtime = st.st_mtime;\r\n\r\n\t\tutime(dst.c_str(), &buf);\r\n\t}\r\n}\r\n\r\nvoid removeDirectory(string dir)\r\n{\r\n\tif (!isDirectory(dir))\r\n\t\treturn;\r\n\r\n\tDIR *d = opendir(dir.c_str());\r\n\tstruct dirent *ent = NULL;\r\n\r\n\twhile ((ent = readdir(d)))\r\n\t{\r\n\t\tif (string(ent->d_name) == \".\" || string(ent->d_name) == \"..\")\r\n\t\t\tcontinue;\r\n\r\n\t\tstring path = dir + '\/' + ent->d_name;\r\n\r\n\t\tif (isDirectory(path))\r\n\t\t\tremoveDirectory(path);\r\n\t\telse\r\n\t\t\tremoveFile(path);\r\n\t}\r\n\r\n\tclosedir(d);\r\n\r\n\tlogMessage(\"RM \" + dir, RED);\r\n\tif (rmdir(dir.c_str()) == -1)\r\n\t\tdie(EXIT_FAILURE, \"Error: Could not delete \" + dir);\r\n}\r\n\r\nvoid assertCanOpenDirectory(string dir)\r\n{\r\n\tDIR *d = opendir(dir.c_str());\r\n\tif (d == NULL)\r\n\t\tdie(EXIT_FAILURE, \"Error: Cannot access \" + dir);\r\n\r\n\tclosedir(d);\r\n}\r\n\r\nvoid copyAllFiles(string src, string dst)\r\n{\r\n\tDIR *d = opendir(src.c_str());\r\n\tstruct dirent *ent = NULL;\r\n\r\n\twhile ((ent = readdir(d)))\r\n\t{\r\n\t\tif (string(ent->d_name) == \".\" || string(ent->d_name) == \"..\")\r\n\t\t\tcontinue;\r\n\r\n\t\tstring srcPath = src + '\/' + ent->d_name;\r\n\t\tstring dstPath = dst + '\/' + ent->d_name;\r\n\r\n\t\tif (isDirectory(srcPath))\r\n\t\t\tcopyAllFiles(srcPath, dstPath);\r\n\t\telse if (isFile(srcPath))\r\n\t\t\tcopyFile(srcPath, dstPath);\r\n\t\telse if (isLink(srcPath))\r\n\t\t\tcopyLink(srcPath, dstPath);\r\n\t}\r\n\r\n\tclosedir(d);\r\n}\r\n\r\nvoid copyNewAndUpdatedFiles(string src, string dst)\r\n{\r\n\tDIR *d = opendir(src.c_str());\r\n\tstruct dirent *ent = NULL;\r\n\r\n\twhile ((ent = readdir(d)))\r\n\t{\r\n\t\tif (string(ent->d_name) == \".\" || string(ent->d_name) == \"..\")\r\n\t\t\tcontinue;\r\n\r\n\t\tstring srcPath = src + '\/' + ent->d_name;\r\n\t\tstring dstPath = dst + '\/' + ent->d_name;\r\n\r\n\t\tif (isDirectory(srcPath) && !isDirectory(dstPath))\r\n\t\t\tlogMessage(\"Warning: \" + srcPath + \" is a directory, but \" + dstPath + \" is not.\");\r\n\t\telse if (!isDirectory(srcPath) && isDirectory(dstPath))\r\n\t\t\tlogMessage(\"Warning: \" + srcPath + \" is not a directory, but \" + dstPath + \" is.\");\r\n\t\telse if (isDirectory(srcPath))\r\n\t\t\tcopyNewAndUpdatedFiles(srcPath, dstPath);\r\n\t\telse if (isFile(srcPath) && isNewer(srcPath, dstPath))\r\n\t\t\tcopyFile(srcPath, dstPath);\r\n\t\telse if (isLink(srcPath))\r\n\t\t\tcopyLink(srcPath, dstPath);\r\n\t}\r\n\r\n\tclosedir(d);\r\n}\r\n\r\nvoid createDirectoryTree(string src, string dst)\r\n{\r\n\tDIR *d = opendir(src.c_str());\r\n\tstruct dirent *ent = NULL;\r\n\r\n\twhile ((ent = readdir(d)))\r\n\t{\r\n\t\tif (string(ent->d_name) == \".\" || string(ent->d_name) == \"..\")\r\n\t\t\tcontinue;\r\n\r\n\t\tstring srcPath = src + '\/' + ent->d_name;\r\n\t\tstring dstPath = dst + '\/' + ent->d_name;\r\n\r\n\t\tif (isDirectory(srcPath) && !isDirectory(dstPath))\r\n\t\t{\r\n\t\t\tif (isFile(dstPath) || isLink(dstPath))\r\n\t\t\t\tremoveFile(dstPath);\r\n\r\n\t\t\tlogMessage(\"MK \" + dstPath);\r\n\t\t\tif (mkdir(dstPath.c_str(), 0775) == -1)\r\n\t\t\t\tdie(EXIT_FAILURE, \"Could not create \" + dstPath);\r\n\r\n\t\t\tstruct stat st;\r\n\r\n\t\t\tif (stat(srcPath.c_str(), &st) != -1)\r\n\t\t\t{\r\n\t\t\t\tstruct utimbuf buf;\r\n\t\t\t\tbuf.actime = st.st_atime;\r\n\t\t\t\tbuf.modtime = st.st_mtime;\r\n\r\n\t\t\t\tutime(dstPath.c_str(), &buf);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (isDirectory(srcPath) && isDirectory(dstPath))\r\n\t\t\tcreateDirectoryTree(srcPath, dstPath);\r\n\t}\r\n\r\n\tclosedir(d);\r\n}\r\n\r\nvoid removeMissing(string src, string dst)\r\n{\r\n\tDIR *d = opendir(dst.c_str());\r\n\tstruct dirent *ent;\r\n\r\n\twhile ((ent = readdir(d)))\r\n\t{\r\n\t\tif (string(ent->d_name) == \".\" || string(ent->d_name) == \"..\")\r\n\t\t\tcontinue;\r\n\r\n\t\tstring srcPath = src + '\/' + ent->d_name;\r\n\t\tstring dstPath = dst + '\/' + ent->d_name;\r\n\r\n\t\tif (isDirectory(dstPath) && !isDirectory(srcPath))\r\n\t\t\tremoveDirectory(dstPath);\r\n\t\telse if (isFile(dstPath) && !isFile(srcPath))\r\n\t\t\tremoveFile(dstPath);\r\n\t\telse if (isLink(dstPath) && !isLink(srcPath))\r\n\t\t\tremoveFile(dstPath);\r\n\t\telse if (isDirectory(dstPath) && isDirectory(srcPath))\r\n\t\t\tremoveMissing(srcPath, dstPath);\r\n\r\n\t}\r\n\r\n\tclosedir(d);\r\n}\r\n<|endoftext|>"} {"text":"\/*\n* Stream Ciphers\n* (C) 2015,2016 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include \n#include \n\n#if defined(BOTAN_HAS_CHACHA)\n #include \n#endif\n\n#if defined(BOTAN_HAS_SALSA20)\n #include \n#endif\n\n#if defined(BOTAN_HAS_SHAKE_CIPHER)\n #include \n#endif\n\n#if defined(BOTAN_HAS_CTR_BE)\n #include \n#endif\n\n#if defined(BOTAN_HAS_OFB)\n #include \n#endif\n\n#if defined(BOTAN_HAS_RC4)\n #include \n#endif\n\n#if defined(BOTAN_HAS_OPENSSL)\n #include \n#endif\n\nnamespace Botan {\n\nstd::unique_ptr StreamCipher::create(const std::string& algo_spec,\n const std::string& provider)\n {\n const SCAN_Name req(algo_spec);\n\n#if defined(BOTAN_HAS_CTR_BE)\n if((req.algo_name() == \"CTR-BE\" || req.algo_name() == \"CTR\") && req.arg_count_between(1,2))\n {\n if(provider.empty() || provider == \"base\")\n {\n auto cipher = BlockCipher::create(req.arg(0));\n if(cipher)\n {\n size_t ctr_size = req.arg_as_integer(1, cipher->block_size());\n return std::unique_ptr(new CTR_BE(cipher.release(), ctr_size));\n }\n }\n }\n#endif\n\n#if defined(BOTAN_HAS_CHACHA)\n if(req.algo_name() == \"ChaCha\")\n {\n if(provider.empty() || provider == \"base\")\n return std::unique_ptr(new ChaCha(req.arg_as_integer(0, 20)));\n }\n#endif\n\n#if defined(BOTAN_HAS_SALSA20)\n if(req.algo_name() == \"Salsa20\")\n {\n if(provider.empty() || provider == \"base\")\n return std::unique_ptr(new Salsa20);\n }\n#endif\n\n#if defined(BOTAN_HAS_SHAKE_CIPHER)\n if(req.algo_name() == \"SHAKE-128\")\n {\n if(provider.empty() || provider == \"base\")\n return std::unique_ptr(new SHAKE_128_Cipher);\n }\n#endif\n\n#if defined(BOTAN_HAS_OFB)\n if(req.algo_name() == \"OFB\" && req.arg_count() == 1)\n {\n if(provider.empty() || provider == \"base\")\n {\n if(auto c = BlockCipher::create(req.arg(0)))\n return std::unique_ptr(new OFB(c.release()));\n }\n }\n#endif\n\n#if defined(BOTAN_HAS_RC4)\n\n if(req.algo_name() == \"RC4\" ||\n req.algo_name() == \"ARC4\" ||\n req.algo_name() == \"MARK-4\")\n {\n const size_t skip = (req.algo_name() == \"MARK-4\") ? 256 : req.arg_as_integer(0, 0);\n\n#if defined(BOTAN_HAS_OPENSSL)\n if(provider.empty() || provider == \"openssl\")\n {\n return std::unique_ptr(make_openssl_rc4(skip));\n }\n#endif\n\n if(provider.empty() || provider == \"base\")\n {\n return std::unique_ptr(new RC4(skip));\n }\n }\n\n#endif\n\n BOTAN_UNUSED(req);\n BOTAN_UNUSED(provider);\n\n return nullptr;\n }\n\n\/\/static\nstd::unique_ptr\nStreamCipher::create_or_throw(const std::string& algo,\n const std::string& provider)\n {\n if(auto sc = StreamCipher::create(algo, provider))\n {\n return sc;\n }\n throw Lookup_Error(\"Stream cipher\", algo, provider);\n }\n\nstd::vector StreamCipher::providers(const std::string& algo_spec)\n {\n return probe_providers_of(algo_spec, {\"base\", \"openssl\"});\n }\n\n}\nAccept ChaCha20 as a name\/*\n* Stream Ciphers\n* (C) 2015,2016 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include \n#include \n\n#if defined(BOTAN_HAS_CHACHA)\n #include \n#endif\n\n#if defined(BOTAN_HAS_SALSA20)\n #include \n#endif\n\n#if defined(BOTAN_HAS_SHAKE_CIPHER)\n #include \n#endif\n\n#if defined(BOTAN_HAS_CTR_BE)\n #include \n#endif\n\n#if defined(BOTAN_HAS_OFB)\n #include \n#endif\n\n#if defined(BOTAN_HAS_RC4)\n #include \n#endif\n\n#if defined(BOTAN_HAS_OPENSSL)\n #include \n#endif\n\nnamespace Botan {\n\nstd::unique_ptr StreamCipher::create(const std::string& algo_spec,\n const std::string& provider)\n {\n const SCAN_Name req(algo_spec);\n\n#if defined(BOTAN_HAS_CTR_BE)\n if((req.algo_name() == \"CTR-BE\" || req.algo_name() == \"CTR\") && req.arg_count_between(1,2))\n {\n if(provider.empty() || provider == \"base\")\n {\n auto cipher = BlockCipher::create(req.arg(0));\n if(cipher)\n {\n size_t ctr_size = req.arg_as_integer(1, cipher->block_size());\n return std::unique_ptr(new CTR_BE(cipher.release(), ctr_size));\n }\n }\n }\n#endif\n\n#if defined(BOTAN_HAS_CHACHA)\n if(req.algo_name() == \"ChaCha\")\n {\n if(provider.empty() || provider == \"base\")\n return std::unique_ptr(new ChaCha(req.arg_as_integer(0, 20)));\n }\n\n if(req.algo_name() == \"ChaCha20\")\n {\n if(provider.empty() || provider == \"base\")\n return std::unique_ptr(new ChaCha(20));\n }\n#endif\n\n#if defined(BOTAN_HAS_SALSA20)\n if(req.algo_name() == \"Salsa20\")\n {\n if(provider.empty() || provider == \"base\")\n return std::unique_ptr(new Salsa20);\n }\n#endif\n\n#if defined(BOTAN_HAS_SHAKE_CIPHER)\n if(req.algo_name() == \"SHAKE-128\")\n {\n if(provider.empty() || provider == \"base\")\n return std::unique_ptr(new SHAKE_128_Cipher);\n }\n#endif\n\n#if defined(BOTAN_HAS_OFB)\n if(req.algo_name() == \"OFB\" && req.arg_count() == 1)\n {\n if(provider.empty() || provider == \"base\")\n {\n if(auto c = BlockCipher::create(req.arg(0)))\n return std::unique_ptr(new OFB(c.release()));\n }\n }\n#endif\n\n#if defined(BOTAN_HAS_RC4)\n\n if(req.algo_name() == \"RC4\" ||\n req.algo_name() == \"ARC4\" ||\n req.algo_name() == \"MARK-4\")\n {\n const size_t skip = (req.algo_name() == \"MARK-4\") ? 256 : req.arg_as_integer(0, 0);\n\n#if defined(BOTAN_HAS_OPENSSL)\n if(provider.empty() || provider == \"openssl\")\n {\n return std::unique_ptr(make_openssl_rc4(skip));\n }\n#endif\n\n if(provider.empty() || provider == \"base\")\n {\n return std::unique_ptr(new RC4(skip));\n }\n }\n\n#endif\n\n BOTAN_UNUSED(req);\n BOTAN_UNUSED(provider);\n\n return nullptr;\n }\n\n\/\/static\nstd::unique_ptr\nStreamCipher::create_or_throw(const std::string& algo,\n const std::string& provider)\n {\n if(auto sc = StreamCipher::create(algo, provider))\n {\n return sc;\n }\n throw Lookup_Error(\"Stream cipher\", algo, provider);\n }\n\nstd::vector StreamCipher::providers(const std::string& algo_spec)\n {\n return probe_providers_of(algo_spec, {\"base\", \"openssl\"});\n }\n\n}\n<|endoftext|>"} {"text":"#include \n\n\tMatrix :: Matrix(){};\n\n\tMatrix :: Matrix(int a, int b)\n\t{\n\t\tcolumns = b;\n\t\tstrings = a;\n\t\tmatrix = new int*[a];\n\n\t\tfor (int i = 0; i < a; i++)\n\t\t{\n\t\t\tmatrix[i] = new int[b]{0};\n\t\t}\n\t};\n\n\tvoid Matrix :: input(string filen)\n\t{\n\t\tifstream file;\n\t\tfile.open(filen);\n\t\t\n\n\t\tmatrix[i] = new *int [strings];\n\t\tfor (int i = 0; i < strings; i++)\n\t\t{\n\t\t\tmatrix[i] = new *int [columns];\n\t\t\tfor (int j = 0; j < columns; j++)\n\t\t\t{\n\t\t\t\tfile >> matrix[i][j];\n\t\t\t}\n\t\t}\n\t\tfile.close();\n\t};\n\n\tvoid Matrix :: set(int x, int y, int z)\n\t{\n\t\tmatrix[x][y] = z;\n\t};\n\n\tint Matrix :: get(int x, int y) const\n\t{\n\t\treturn matrix[x][y];\n\t};\n\n\tMatrix Matrix:: operator+ (Matrix a) const\n\t{\n\t\tMatrix c(strings, columns);\n\n\n\t\tfor (int i = 0; i < strings; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < columns; j++)\n\t\t\t{\n\t\t\t\tc.set(i, j, a.get(i, j) + get(i, j));\n\t\t\t}\n\t\t}\n\t\treturn c;\n\t};\n\n\tMatrix Matrix :: operator* (Matrix a) const\n\t{\n\t\tMatrix c(strings, a.columns);\n\n\t\tfor (int i = 0; i < strings; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < a.columns; j++)\n\t\t\t{\n\t\t\t\tint temp = 0;\n\t\t\t\tfor (int k = 0; k < strings; k++)\n\t\t\t\t{\n\t\t\t\t\ttemp += get(i, k) * a.get(k, j);\n\t\t\t\t}\n\t\t\t\tc.set(i, j, temp);\n\t\t\t}\n\t\t}\n\n\t\treturn c;\n\t};\n\n\tMatrix& Matrix :: operator= (Matrix &other) \n\t{\n\t\tif (this != &other)\n\t\t{\n\t\t\tfor (int i = 0; i < strings; i++)\n\t\t\t{\n\t\t\t\tdelete[] matrix[i];\n\t\t\t}\n\n\t\t\tdelete[] matrix;\n\n\t\t\tcolumns = other.columns;\n\t\t\tstrings = other.strings;\n\n\t\t\tmatrix = new int*[strings];\n\n\t\t\tfor (int i = 0; i < strings; i++)\n\t\t\t{\n\t\t\t\tmatrix[i] = new int[columns]{0};\n\t\t\t}\n\n\t\t\tmatrix = other.matrix;\n\t\t}\n\t\treturn *this;\n\t};\n\n\tbool Matrix :: operator== (Matrix &a) const\n\t{\n\t\tbool k = false;\n\n\t\tfor (int i = 0; i < strings; i++){\n\n\t\t\tfor (int j = 0; j < columns; j++){\n\n\t\t\t\tif (matrix[i][j] == a.matrix[i][j])\n\n\t\t\t\t\tk = true;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn k;\n\t}\n\n\tistream& operator>> (istream& file, const Matrix& result)\n\n\t{\n\n\t\tfor (int i = 0; i < result.strings; i++)\n\n\t\t\tfor (int j = 0; j < result.columns; j++)\n\n\t\t\t\tfile >> result.matrix[i][j];\n\n\t\treturn file;\n\n\t}\n\n\t ostream& operator<< (ostream& os, const Matrix& a)\n\t{\n\t\tfor (int i = 0; i < a.strings; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < a.columns; j++)\n\t\t\t{\n\t\t\t\tos << a.matrix[i][j] << \" \";\n\t\t\t}\n\t\t\tos << endl;\n\t\t}\n\t\tos << endl;\n\t\treturn os;\n\t}\n\n\n\tMatrix :: ~Matrix()\n\t{\n\t\t\/*for (int i = 0; i < strings; i++)\n\t\t{\n\t\t\tdelete[] matrix[i];\n\t\t}\n\n\t\tdelete[] matrix;*\/\n\t};\n\n\n\nUpdate matrix.cpp#include \"matrix.hpp\"\n\nint Matrix::Columns_() const\n{\n\treturn Columns;\n}\n\nint Matrix::Strings_() const\n{\n\treturn Strings;\n}\n\nMatrix::Matrix()\n{\n\tColumns = 0;\n\tStrings = 0;\n\tmatrix = new int*[Strings];\n\tfor (int i = 0; i < Strings; i++)\n\t{\n\t\tmatrix[i] = new int[Columns];\n\t}\n}\n\nMatrix::Matrix(int _Columns, int _Strings)\n{\n\tColumns = _Columns;\n\tStrings = _Strings;\n\tmatrix = new int*[Strings];\n\tfor (int i = 0; i < Strings; ++i)\n\t{\n\t\tmatrix[i] = new int[Columns];\n\t\tfor (int j = 0; j < Columns; ++j)\n\t\t{\n\t\t\tmatrix[i][j] = 0;\n\t\t}\n\t}\n}\n\nMatrix::Matrix(const Matrix& res)\n{\n\tColumns = res.Columns;\n\tStrings = res.Strings;\n\tmatrix = new int*[Strings];\n\t\n\tfor (int i = 0; i < Strings; ++i)\n\t{\n\t\tmatrix[i] = new int[Columns];\n\t\tfor (int j = 0; j < Columns; ++j)\n\t\t{\n\t\t\tmatrix[i][j] = res.matrix[i][j];\n\t\t}\n\t}\n}\n\nMatrix::~Matrix()\n{\n\tfor (int i = 0; i < Strings; ++i)\n\t{\n\t\tdelete[]matrix[i];\n\t}\n\tdelete[]matrix;\n}\n\nistream& operator >> (istream& infile, const Matrix& res) const\n{\n\tfor (int i = 0; i < res.Strings; i++)\n\tfor (int j = 0; j < res.Columns; j++)\n\t\tinfile >> res.matrix[i][j];\n\treturn infile;\n}\n\nvoid Matrix::search(string filen) const\n{\n\tifstream file;\n\tfile.open(filen);\n\tif (!file.is_open())\n\t\tcout << \"Error! Try again!\" << endl;\n\telse\n\t{\n\t\tmatrix = new int*[Strings];\n\t\tfor (int i = 0; i < Strings; i++)\n\t\t{\n\t\t\tmatrix[i] = new int[Columns];\n\t\t\tfor (int j = 0; j < Columns; j++)\n\t\t\t{\n\t\t\t\tfile >> matrix[i][j];\n\t\t\t}\n\t\t}\n\t}\n\tfile.close();\n}\n\nostream& operator << (ostream& outfile, const Matrix& resu)\n{\n\tfor (int i = 0; i < res.Strings; i++)\n\t{\n\t\tfor (int j = 0; j < resu.Columns; j++)\n\t\t{\n\t\t\toutfile << res.matrix[i][j] << \" \";\n\t\t}\n\t}\n\toutfile << endl;\n\treturn outfile;\n}\n\nbool Matrix::operator == (const Matrix& m2) const\n{\n\tbool k = false;\n\tfor (int i = 0; i < Strings; i++)\n\t{\n\t\tfor (int j = 0; j < Columns; j++)\n\t\t{\n\t\t\tif (matrix[i][j] == m2.matrix[i][j])\n\t\t\t\tk = true;\n\t\t}\n\t}\n\treturn k;\n}\n\nMatrix Matrix::operator + (const Matrix& m2) const\n{\n\tif ((Columns != m2.Columns) || (Strings != m2.Strings)) \n\t{\n\t\tcout << \"Error!\";\n\t}\n\telse \n\t{\n\t\tMatrix result(Columns, Strings);\n\t\tfor (int i = 0; i < Strings; ++i)\n\t\t{\n\t\t\tfor (int j = 0; j < Columns; ++j)\n\t\t\t{\n\t\t\t\tresult.matrix[i][j] = matrix[i][j] + m2.matrix[i][j];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n}\n\nMatrix Matrix::operator * (const Matrix& m2) const\n{\n\tif (m2.Strings != Columns)\n\t{\n\t\tcout << \"Error!\";\n\t}\n\telse \n\t{\n\t\tMatrix res(Strings, m2.Columns);\n\t\t\n\t\tfor (int i = 0; i < Strings; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < m2.Columns; j++)\n\t\t\t{\n\t\t\t\tfor (int k = 0; k < Columns; k++)\n\t\t\t\t{\n\t\t\t\t\tres.matrix[i][j] += matrix[i][k] * m2.matrix[k][j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n}\n\nMatrix& Matrix::operator = (const Matrix& res)\n{\n\tif (&result != this)\n\t{\n\t\tfor (int i = 0; i < Strings; i++)\n\t\t{\n\t\t\tdelete[] matrix[i];\n\t\t}\n\t\tdelete[] matrix;\n\t}\n\tStrings = res.Strings;\n\tColumns = res.Columns;\n\t\n\tmatrix = new int*[Strings];\n\t\n\tfor (int i = 0; i < Strings; i++)\n\t{\n\t\tmatrix[i] = new int[Columns];\n\t\tfor (int j = 0; j < Columns; j++)\n\t\t{\n\t\t\tmatrix[i][j] = res.matrix[i][j];\n\t\t}\n\t}\n\treturn *this;\n\n\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/TransformationMatrix.h\"\n\nnamespace IECore {\n\ntemplate class TransformationMatrix;\ntemplate class TransformationMatrix;\n\n} \/\/ namespace IECore\nFixed formatting\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007-2008, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/TransformationMatrix.h\"\n\nnamespace IECore\n{\n\ntemplate class TransformationMatrix;\ntemplate class TransformationMatrix;\n\n} \/\/ namespace IECore\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \"..\/parallel.h\"\n#include \"..\/sequence.h\"\n#include \"..\/task.h\"\n\nclass ParallelSequenceTest : testing::Test\n{\n\n};\n\nTEST(ParallelSequenceTest, Test1)\n{\n\tauto task1 = asyncply::parallel(\n\t\t[&]()\n\t\t{\n\t\t\treturn asyncply::sequence(7.0,\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 3.0;\n\t\t\t\t},\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 4.0;\n\t\t\t\t});\n\t\t},\n\t\t[&]()\n\t\t{\n\t\t\treturn asyncply::sequence(9.0,\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 5.0;\n\t\t\t\t},\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 4.0;\n\t\t\t\t});\n\t\t});\n\tASSERT_EQ(task1->get(), 32.0);\n}\nUpdate test_parallel_sequence.cpp#include \n#include \n#include \n#include \n#include \"..\/parallel.h\"\n#include \"..\/sequence.h\"\n#include \"..\/task.h\"\n\nclass ParallelSequenceTest : testing::Test\n{\n\n};\n\nTEST(ParallelSequenceTest, Test1)\n{\n\tdouble total = asyncply::parallel_sync(\n\t\t[&]()\n\t\t{\n\t\t\treturn asyncply::sequence(7.0,\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 3.0;\n\t\t\t\t},\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 4.0;\n\t\t\t\t});\n\t\t},\n\t\t[&]()\n\t\t{\n\t\t\treturn asyncply::sequence(9.0,\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 5.0;\n\t\t\t\t},\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 4.0;\n\t\t\t\t});\n\t\t});\n\tASSERT_EQ(total, 32.0);\n}\n<|endoftext|>"} {"text":"\/* Sirikata\n * main.cpp\n *\n * Copyright (c) 2009, Ewen Cheslack-Postava\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Sirikata nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \"Forwarder.hpp\"\n\n#include \n\n#include \n#include \n#include \"Server.hpp\"\n\n#include \"Options.hpp\"\n#include \n#include \n#include \n#include \"TCPSpaceNetwork.hpp\"\n#include \"FairServerMessageReceiver.hpp\"\n#include \"FairServerMessageQueue.hpp\"\n#include \n#include \"UniformCoordinateSegmentation.hpp\"\n#include \"CoordinateSegmentationClient.hpp\"\n#include \n#include \n#include \"caches\/CommunicationCache.hpp\"\n#include \"caches\/CacheLRUOriginal.hpp\"\n\n#include \n#include \n#include \n\nnamespace {\nusing namespace Sirikata;\nvoid createServer(Server** server_out, SpaceContext* space_context, Authenticator* auth, Forwarder* forwarder, LocationService* loc_service, CoordinateSegmentation* cseg, Proximity* prox, ObjectSegmentation* oseg, Address4 addr, ObjectHostSessionManager* oh_sess_mgr, ObjectSessionManager* obj_sess_mgr) {\n if (addr == Address4::Null) {\n SILOG(space, fatal, \"The requested server ID isn't in ServerIDMap\");\n space_context->shutdown();\n }\n\n Server* server = new Server(space_context, auth, forwarder, loc_service, cseg, prox, oseg, addr, oh_sess_mgr, obj_sess_mgr);\n prox->initialize(cseg);\n space_context->add(prox);\n space_context->add(server);\n\n *server_out = server;\n}\n}\n\nint main(int argc, char** argv) {\n\n using namespace Sirikata;\n\n DynamicLibrary::Initialize();\n\n InitOptions();\n Trace::Trace::InitOptions();\n SpaceTrace::InitOptions();\n InitSpaceOptions();\n ParseOptions(argc, argv, OPT_CONFIG_FILE);\n\n PluginManager plugins;\n plugins.loadList( GetOptionValue(OPT_PLUGINS) );\n plugins.loadList( GetOptionValue(OPT_SPACE_PLUGINS) );\n\n \/\/ Fill defaults after plugin loading to ensure plugin-added\n \/\/ options get their defaults.\n FillMissingOptionDefaults();\n \/\/ Rerun original parse to make sure any newly added options are\n \/\/ properly parsed.\n ParseOptions(argc, argv, OPT_CONFIG_FILE);\n\n ReportVersion(); \/\/ After options so log goes to the right place\n\n std::string time_server=GetOptionValue(\"time-server\");\n NTPTimeSync sync;\n if (time_server.size() > 0)\n sync.start(time_server);\n\n ServerID server_id = GetOptionValue(\"id\");\n String trace_file = GetPerServerFile(STATS_TRACE_FILE, server_id);\n Sirikata::Trace::Trace* gTrace = new Trace::Trace(trace_file);\n\n \/\/ Compute the starting date\/time\n String start_time_str = GetOptionValue(\"wait-until\");\n Time start_time = start_time_str.empty() ? Timer::now() : Timer::getSpecifiedDate( start_time_str );\n start_time += GetOptionValue(\"wait-additional\");\n\n Duration duration = GetOptionValue(\"duration\");\n\n Network::IOService* ios = Network::IOServiceFactory::makeIOService();\n Network::IOStrand* mainStrand = ios->createStrand();\n\n ODPSST::ConnectionManager* sstConnMgr = new ODPSST::ConnectionManager();\n OHDPSST::ConnectionManager* ohSstConnMgr = new OHDPSST::ConnectionManager();\n\n SpaceContext* space_context = new SpaceContext(\"space\", server_id, sstConnMgr, ohSstConnMgr, ios, mainStrand, start_time, gTrace, duration);\n\n String servermap_type = GetOptionValue(\"servermap\");\n String servermap_options = GetOptionValue(\"servermap-options\");\n ServerIDMap * server_id_map =\n ServerIDMapFactory::getSingleton().getConstructor(servermap_type)(space_context, servermap_options);\n\n space_context->add(space_context);\n\n\n String timeseries_type = GetOptionValue(OPT_TRACE_TIMESERIES);\n String timeseries_options = GetOptionValue(OPT_TRACE_TIMESERIES_OPTIONS);\n Trace::TimeSeries* time_series = Trace::TimeSeriesFactory::getSingleton().getConstructor(timeseries_type)(space_context, timeseries_options);\n\n Sirikata::SpaceNetwork* gNetwork = NULL;\n String network_type = GetOptionValue(NETWORK_TYPE);\n if (network_type == \"tcp\")\n gNetwork = new TCPSpaceNetwork(space_context);\n\n BoundingBox3f region = GetOptionValue(\"region\");\n Vector3ui32 layout = GetOptionValue(\"layout\");\n\n srand( GetOptionValue(\"rand-seed\") );\n\n ObjectHostSessionManager* oh_sess_mgr = new ObjectHostSessionManager(space_context);\n ObjectSessionManager* obj_sess_mgr = new ObjectSessionManager(space_context);\n\n String auth_type = GetOptionValue(SPACE_OPT_AUTH);\n String auth_opts = GetOptionValue(SPACE_OPT_AUTH_OPTIONS);\n Authenticator* auth =\n AuthenticatorFactory::getSingleton().getConstructor(auth_type)(space_context, auth_opts);\n\n gNetwork->setServerIDMap(server_id_map);\n\n\n Forwarder* forwarder = new Forwarder(space_context);\n\n\n String cseg_type = GetOptionValue(CSEG);\n CoordinateSegmentation* cseg = NULL;\n if (cseg_type == \"uniform\")\n cseg = new UniformCoordinateSegmentation(space_context, region, layout);\n else if (cseg_type == \"client\") {\n cseg = new CoordinateSegmentationClient(space_context, region, layout, server_id_map);\n }\n else {\n assert(false);\n exit(-1);\n }\n\n\n String loc_update_type = GetOptionValue(LOC_UPDATE);\n String loc_update_opts = GetOptionValue(LOC_UPDATE_OPTIONS);\n LocationUpdatePolicy* loc_update_policy =\n LocationUpdatePolicyFactory::getSingleton().getConstructor(loc_update_type)(space_context, loc_update_opts);\n\n String loc_service_type = GetOptionValue(LOC);\n String loc_service_opts = GetOptionValue(LOC_OPTIONS);\n LocationService* loc_service =\n LocationServiceFactory::getSingleton().getConstructor(loc_service_type)(space_context, loc_update_policy, loc_service_opts);\n\n ServerMessageQueue* sq = NULL;\n String server_queue_type = GetOptionValue(SERVER_QUEUE);\n if (server_queue_type == \"fair\") {\n sq = new FairServerMessageQueue(\n space_context, gNetwork,\n (ServerMessageQueue::Sender*)forwarder);\n }\n else {\n assert(false);\n exit(-1);\n }\n\n ServerMessageReceiver* server_message_receiver = NULL;\n String server_receiver_type = GetOptionValue(SERVER_RECEIVER);\n if (server_queue_type == \"fair\")\n server_message_receiver =\n new FairServerMessageReceiver(space_context, gNetwork, (ServerMessageReceiver::Listener*)forwarder);\n else {\n assert(false);\n exit(-1);\n }\n\n\n\n LoadMonitor* loadMonitor = new LoadMonitor(space_context, cseg);\n\n\n \/\/ OSeg Cache\n OSegCache* oseg_cache = NULL;\n std::string cacheSelector = GetOptionValue(CACHE_SELECTOR);\n uint32 cacheSize = GetOptionValue(OSEG_CACHE_SIZE);\n if (cacheSelector == CACHE_TYPE_COMMUNICATION) {\n double cacheCommScaling = GetOptionValue(CACHE_COMM_SCALING);\n oseg_cache = new CommunicationCache(space_context, cacheCommScaling, cseg, cacheSize);\n }\n else if (cacheSelector == CACHE_TYPE_ORIGINAL_LRU) {\n uint32 cacheCleanGroupSize = GetOptionValue(OSEG_CACHE_CLEAN_GROUP_SIZE);\n Duration entryLifetime = GetOptionValue(OSEG_CACHE_ENTRY_LIFETIME);\n oseg_cache = new CacheLRUOriginal(space_context, cacheSize, cacheCleanGroupSize, entryLifetime);\n }\n else {\n std::cout<<\"\\n\\nUNKNOWN CACHE TYPE SELECTED. Please re-try.\\n\\n\";\n std::cout.flush();\n assert(false);\n }\n\n \/\/Create OSeg\n std::string oseg_type = GetOptionValue(OSEG);\n std::string oseg_options = GetOptionValue(OSEG_OPTIONS);\n Network::IOStrand* osegStrand = space_context->ioService->createStrand();\n ObjectSegmentation* oseg =\n OSegFactory::getSingleton().getConstructor(oseg_type)(space_context, osegStrand, cseg, oseg_cache, oseg_options);\n \/\/end create oseg\n\n\n \/\/ We have all the info to initialize the forwarder now\n forwarder->initialize(oseg, sq, server_message_receiver, loc_service);\n\n AggregateManager* aggmgr = new AggregateManager(loc_service);\n\n std::string prox_type = GetOptionValue(OPT_PROX);\n std::string prox_options = GetOptionValue(OPT_PROX_OPTIONS);\n Proximity* prox = ProximityFactory::getSingleton().getConstructor(prox_type)(space_context, loc_service, gNetwork, aggmgr, prox_options);\n\n \/\/ We need to do an async lookup, and to finish it the server needs to be\n \/\/ running. But we can't create the server until we have the address from\n \/\/ this lookup. We isolate as little as possible into this callback --\n \/\/ creating the server, finishing prox initialization, and getting them both\n \/\/ registered. We pass storage for the Server to the callback so we can\n \/\/ handle cleaning it up ourselves.\n using std::tr1::placeholders::_1;\n Server* server = NULL;\n server_id_map->lookupExternal(\n space_context->id(),\n space_context->mainStrand->wrap(\n std::tr1::bind( &createServer, &server, space_context, auth, forwarder, loc_service, cseg, prox, oseg, _1, oh_sess_mgr, obj_sess_mgr)\n )\n );\n\n \/\/ If we're one of the initial nodes, we'll have to wait until we hit the start time\n {\n Time now_time = Timer::now();\n if (start_time > now_time) {\n Duration sleep_time = start_time - now_time;\n printf(\"Waiting %f seconds\\n\", sleep_time.toSeconds() ); fflush(stdout);\n#if SIRIKATA_PLATFORM == PLATFORM_WINDOWS\n Sleep( sleep_time.toMilliseconds() );\n#else\n usleep( sleep_time.toMicroseconds() );\n#endif\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/Go go go!! start of simulation\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n space_context->add(auth);\n space_context->add(gNetwork);\n space_context->add(cseg);\n space_context->add(loc_service);\n space_context->add(oseg);\n space_context->add(loadMonitor);\n space_context->add(sstConnMgr);\n space_context->add(ohSstConnMgr);\n\n\n space_context->run(2);\n\n space_context->cleanup();\n\n if (GetOptionValue(PROFILE)) {\n space_context->profiler->report();\n }\n\n gTrace->prepareShutdown();\n prox->shutdown();\n Mesh::FilterFactory::destroy();\n ModelsSystemFactory::destroy();\n LocationServiceFactory::destroy();\n LocationUpdatePolicyFactory::destroy();\n delete server;\n delete sq;\n delete server_message_receiver;\n delete prox;\n delete aggmgr;\n delete server_id_map;\n\n delete loadMonitor;\n\n delete cseg;\n delete oseg;\n delete oseg_cache;\n delete loc_service;\n delete forwarder;\n\n delete obj_sess_mgr;\n delete oh_sess_mgr;\n\n delete gNetwork;\n gNetwork=NULL;\n\n gTrace->shutdown();\n delete gTrace;\n gTrace = NULL;\n\n\n delete space_context;\n space_context = NULL;\n\n delete time_series;\n\n delete mainStrand;\n delete osegStrand;\n\n Network::IOServiceFactory::destroyIOService(ios);\n\n delete sstConnMgr;\n delete ohSstConnMgr;\n\n sync.stop();\n\n plugins.gc();\n\n Sirikata::Logging::finishLog();\n\n return 0;\n}\nChange the way the createServer callback is setup in space's main() because some platforms can't bind enough parameters.\/* Sirikata\n * main.cpp\n *\n * Copyright (c) 2009, Ewen Cheslack-Postava\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Sirikata nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \"Forwarder.hpp\"\n\n#include \n\n#include \n#include \n#include \"Server.hpp\"\n\n#include \"Options.hpp\"\n#include \n#include \n#include \n#include \"TCPSpaceNetwork.hpp\"\n#include \"FairServerMessageReceiver.hpp\"\n#include \"FairServerMessageQueue.hpp\"\n#include \n#include \"UniformCoordinateSegmentation.hpp\"\n#include \"CoordinateSegmentationClient.hpp\"\n#include \n#include \n#include \"caches\/CommunicationCache.hpp\"\n#include \"caches\/CacheLRUOriginal.hpp\"\n\n#include \n#include \n#include \n\nnamespace {\nusing namespace Sirikata;\n\n\/\/ Some platforms can't bind as many variables as we want to use, so we need to\n\/\/ manually package them up.\nstruct ServerData {\n SpaceContext* space_context;\n Authenticator* auth;\n Forwarder* forwarder;\n LocationService* loc_service;\n CoordinateSegmentation* cseg;\n Proximity* prox;\n ObjectSegmentation* oseg;\n ObjectHostSessionManager* oh_sess_mgr;\n ObjectSessionManager* obj_sess_mgr;\n};\nvoid createServer(Server** server_out, ServerData sd, Address4 addr) {\n if (addr == Address4::Null) {\n SILOG(space, fatal, \"The requested server ID isn't in ServerIDMap\");\n sd.space_context->shutdown();\n }\n\n Server* server = new Server(sd.space_context, sd.auth, sd.forwarder, sd.loc_service, sd.cseg, sd.prox, sd.oseg, addr, sd.oh_sess_mgr, sd.obj_sess_mgr);\n sd.prox->initialize(sd.cseg);\n sd.space_context->add(sd.prox);\n sd.space_context->add(server);\n\n *server_out = server;\n}\n}\n\nint main(int argc, char** argv) {\n\n using namespace Sirikata;\n\n DynamicLibrary::Initialize();\n\n InitOptions();\n Trace::Trace::InitOptions();\n SpaceTrace::InitOptions();\n InitSpaceOptions();\n ParseOptions(argc, argv, OPT_CONFIG_FILE);\n\n PluginManager plugins;\n plugins.loadList( GetOptionValue(OPT_PLUGINS) );\n plugins.loadList( GetOptionValue(OPT_SPACE_PLUGINS) );\n\n \/\/ Fill defaults after plugin loading to ensure plugin-added\n \/\/ options get their defaults.\n FillMissingOptionDefaults();\n \/\/ Rerun original parse to make sure any newly added options are\n \/\/ properly parsed.\n ParseOptions(argc, argv, OPT_CONFIG_FILE);\n\n ReportVersion(); \/\/ After options so log goes to the right place\n\n std::string time_server=GetOptionValue(\"time-server\");\n NTPTimeSync sync;\n if (time_server.size() > 0)\n sync.start(time_server);\n\n ServerID server_id = GetOptionValue(\"id\");\n String trace_file = GetPerServerFile(STATS_TRACE_FILE, server_id);\n Sirikata::Trace::Trace* gTrace = new Trace::Trace(trace_file);\n\n \/\/ Compute the starting date\/time\n String start_time_str = GetOptionValue(\"wait-until\");\n Time start_time = start_time_str.empty() ? Timer::now() : Timer::getSpecifiedDate( start_time_str );\n start_time += GetOptionValue(\"wait-additional\");\n\n Duration duration = GetOptionValue(\"duration\");\n\n Network::IOService* ios = Network::IOServiceFactory::makeIOService();\n Network::IOStrand* mainStrand = ios->createStrand();\n\n ODPSST::ConnectionManager* sstConnMgr = new ODPSST::ConnectionManager();\n OHDPSST::ConnectionManager* ohSstConnMgr = new OHDPSST::ConnectionManager();\n\n SpaceContext* space_context = new SpaceContext(\"space\", server_id, sstConnMgr, ohSstConnMgr, ios, mainStrand, start_time, gTrace, duration);\n\n String servermap_type = GetOptionValue(\"servermap\");\n String servermap_options = GetOptionValue(\"servermap-options\");\n ServerIDMap * server_id_map =\n ServerIDMapFactory::getSingleton().getConstructor(servermap_type)(space_context, servermap_options);\n\n space_context->add(space_context);\n\n\n String timeseries_type = GetOptionValue(OPT_TRACE_TIMESERIES);\n String timeseries_options = GetOptionValue(OPT_TRACE_TIMESERIES_OPTIONS);\n Trace::TimeSeries* time_series = Trace::TimeSeriesFactory::getSingleton().getConstructor(timeseries_type)(space_context, timeseries_options);\n\n Sirikata::SpaceNetwork* gNetwork = NULL;\n String network_type = GetOptionValue(NETWORK_TYPE);\n if (network_type == \"tcp\")\n gNetwork = new TCPSpaceNetwork(space_context);\n\n BoundingBox3f region = GetOptionValue(\"region\");\n Vector3ui32 layout = GetOptionValue(\"layout\");\n\n srand( GetOptionValue(\"rand-seed\") );\n\n ObjectHostSessionManager* oh_sess_mgr = new ObjectHostSessionManager(space_context);\n ObjectSessionManager* obj_sess_mgr = new ObjectSessionManager(space_context);\n\n String auth_type = GetOptionValue(SPACE_OPT_AUTH);\n String auth_opts = GetOptionValue(SPACE_OPT_AUTH_OPTIONS);\n Authenticator* auth =\n AuthenticatorFactory::getSingleton().getConstructor(auth_type)(space_context, auth_opts);\n\n gNetwork->setServerIDMap(server_id_map);\n\n\n Forwarder* forwarder = new Forwarder(space_context);\n\n\n String cseg_type = GetOptionValue(CSEG);\n CoordinateSegmentation* cseg = NULL;\n if (cseg_type == \"uniform\")\n cseg = new UniformCoordinateSegmentation(space_context, region, layout);\n else if (cseg_type == \"client\") {\n cseg = new CoordinateSegmentationClient(space_context, region, layout, server_id_map);\n }\n else {\n assert(false);\n exit(-1);\n }\n\n\n String loc_update_type = GetOptionValue(LOC_UPDATE);\n String loc_update_opts = GetOptionValue(LOC_UPDATE_OPTIONS);\n LocationUpdatePolicy* loc_update_policy =\n LocationUpdatePolicyFactory::getSingleton().getConstructor(loc_update_type)(space_context, loc_update_opts);\n\n String loc_service_type = GetOptionValue(LOC);\n String loc_service_opts = GetOptionValue(LOC_OPTIONS);\n LocationService* loc_service =\n LocationServiceFactory::getSingleton().getConstructor(loc_service_type)(space_context, loc_update_policy, loc_service_opts);\n\n ServerMessageQueue* sq = NULL;\n String server_queue_type = GetOptionValue(SERVER_QUEUE);\n if (server_queue_type == \"fair\") {\n sq = new FairServerMessageQueue(\n space_context, gNetwork,\n (ServerMessageQueue::Sender*)forwarder);\n }\n else {\n assert(false);\n exit(-1);\n }\n\n ServerMessageReceiver* server_message_receiver = NULL;\n String server_receiver_type = GetOptionValue(SERVER_RECEIVER);\n if (server_queue_type == \"fair\")\n server_message_receiver =\n new FairServerMessageReceiver(space_context, gNetwork, (ServerMessageReceiver::Listener*)forwarder);\n else {\n assert(false);\n exit(-1);\n }\n\n\n\n LoadMonitor* loadMonitor = new LoadMonitor(space_context, cseg);\n\n\n \/\/ OSeg Cache\n OSegCache* oseg_cache = NULL;\n std::string cacheSelector = GetOptionValue(CACHE_SELECTOR);\n uint32 cacheSize = GetOptionValue(OSEG_CACHE_SIZE);\n if (cacheSelector == CACHE_TYPE_COMMUNICATION) {\n double cacheCommScaling = GetOptionValue(CACHE_COMM_SCALING);\n oseg_cache = new CommunicationCache(space_context, cacheCommScaling, cseg, cacheSize);\n }\n else if (cacheSelector == CACHE_TYPE_ORIGINAL_LRU) {\n uint32 cacheCleanGroupSize = GetOptionValue(OSEG_CACHE_CLEAN_GROUP_SIZE);\n Duration entryLifetime = GetOptionValue(OSEG_CACHE_ENTRY_LIFETIME);\n oseg_cache = new CacheLRUOriginal(space_context, cacheSize, cacheCleanGroupSize, entryLifetime);\n }\n else {\n std::cout<<\"\\n\\nUNKNOWN CACHE TYPE SELECTED. Please re-try.\\n\\n\";\n std::cout.flush();\n assert(false);\n }\n\n \/\/Create OSeg\n std::string oseg_type = GetOptionValue(OSEG);\n std::string oseg_options = GetOptionValue(OSEG_OPTIONS);\n Network::IOStrand* osegStrand = space_context->ioService->createStrand();\n ObjectSegmentation* oseg =\n OSegFactory::getSingleton().getConstructor(oseg_type)(space_context, osegStrand, cseg, oseg_cache, oseg_options);\n \/\/end create oseg\n\n\n \/\/ We have all the info to initialize the forwarder now\n forwarder->initialize(oseg, sq, server_message_receiver, loc_service);\n\n AggregateManager* aggmgr = new AggregateManager(loc_service);\n\n std::string prox_type = GetOptionValue(OPT_PROX);\n std::string prox_options = GetOptionValue(OPT_PROX_OPTIONS);\n Proximity* prox = ProximityFactory::getSingleton().getConstructor(prox_type)(space_context, loc_service, gNetwork, aggmgr, prox_options);\n\n \/\/ We need to do an async lookup, and to finish it the server needs to be\n \/\/ running. But we can't create the server until we have the address from\n \/\/ this lookup. We isolate as little as possible into this callback --\n \/\/ creating the server, finishing prox initialization, and getting them both\n \/\/ registered. We pass storage for the Server to the callback so we can\n \/\/ handle cleaning it up ourselves.\n using std::tr1::placeholders::_1;\n Server* server = NULL;\n ServerData sd;\n sd.space_context = space_context;\n sd.auth = auth;\n sd.forwarder = forwarder;\n sd.loc_service = loc_service;\n sd.cseg = cseg;\n sd.prox = prox;\n sd.oseg = oseg;\n sd.oh_sess_mgr = oh_sess_mgr;\n sd.obj_sess_mgr = obj_sess_mgr;\n server_id_map->lookupExternal(\n space_context->id(),\n space_context->mainStrand->wrap(\n std::tr1::bind( &createServer, &server, sd, _1)\n )\n );\n\n \/\/ If we're one of the initial nodes, we'll have to wait until we hit the start time\n {\n Time now_time = Timer::now();\n if (start_time > now_time) {\n Duration sleep_time = start_time - now_time;\n printf(\"Waiting %f seconds\\n\", sleep_time.toSeconds() ); fflush(stdout);\n#if SIRIKATA_PLATFORM == PLATFORM_WINDOWS\n Sleep( sleep_time.toMilliseconds() );\n#else\n usleep( sleep_time.toMicroseconds() );\n#endif\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/Go go go!! start of simulation\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n space_context->add(auth);\n space_context->add(gNetwork);\n space_context->add(cseg);\n space_context->add(loc_service);\n space_context->add(oseg);\n space_context->add(loadMonitor);\n space_context->add(sstConnMgr);\n space_context->add(ohSstConnMgr);\n\n\n space_context->run(2);\n\n space_context->cleanup();\n\n if (GetOptionValue(PROFILE)) {\n space_context->profiler->report();\n }\n\n gTrace->prepareShutdown();\n prox->shutdown();\n Mesh::FilterFactory::destroy();\n ModelsSystemFactory::destroy();\n LocationServiceFactory::destroy();\n LocationUpdatePolicyFactory::destroy();\n delete server;\n delete sq;\n delete server_message_receiver;\n delete prox;\n delete aggmgr;\n delete server_id_map;\n\n delete loadMonitor;\n\n delete cseg;\n delete oseg;\n delete oseg_cache;\n delete loc_service;\n delete forwarder;\n\n delete obj_sess_mgr;\n delete oh_sess_mgr;\n\n delete gNetwork;\n gNetwork=NULL;\n\n gTrace->shutdown();\n delete gTrace;\n gTrace = NULL;\n\n\n delete space_context;\n space_context = NULL;\n\n delete time_series;\n\n delete mainStrand;\n delete osegStrand;\n\n Network::IOServiceFactory::destroyIOService(ios);\n\n delete sstConnMgr;\n delete ohSstConnMgr;\n\n sync.stop();\n\n plugins.gc();\n\n Sirikata::Logging::finishLog();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n RawSpeed - RAW file decoder.\n\n Copyright (C) 2009-2014 Klaus Post\n Copyright (C) 2014 Pedro Côrte-Real\n Copyright (C) 2017-2018 Roman Lebedev\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"tiff\/CiffIFD.h\"\n#include \"common\/Common.h\" \/\/ for uint32, ushort16, isIn\n#include \"common\/NORangesSet.h\" \/\/ for NORangesSet\n#include \"common\/RawspeedException.h\" \/\/ for RawspeedException\n#include \"io\/ByteStream.h\" \/\/ for ByteStream\n#include \"io\/IOException.h\" \/\/ for IOException\n#include \"parsers\/CiffParserException.h\" \/\/ for ThrowCPE, CiffParserException\n#include \"tiff\/CiffEntry.h\" \/\/ for CiffEntry, CiffDataType::CI...\n#include \/\/ for assert\n#include \/\/ for map, _Rb_tree_iterator\n#include \/\/ for unique_ptr\n#include \/\/ for allocator, operator==, string\n#include \/\/ for pair\n#include \/\/ for vector\n\nusing std::string;\nusing std::vector;\nusing std::unique_ptr;\n\nnamespace rawspeed {\n\nvoid CiffIFD::parseIFDEntry(NORangesSet* valueDatas,\n const ByteStream* valueData,\n ByteStream* dirEntries) {\n assert(valueDatas);\n assert(valueData);\n assert(dirEntries);\n\n unique_ptr t;\n ByteStream dirEntry = dirEntries->getStream(10); \/\/ Entry is 10 bytes.\n\n try {\n t = std::make_unique(valueDatas, valueData, dirEntry);\n } catch (IOException&) {\n \/\/ Ignore unparsable entry\n return;\n }\n\n switch (t->type) {\n case CIFF_SUB1:\n case CIFF_SUB2: {\n \/\/ Ok, have to store it.\n break;\n }\n\n default:\n \/\/ We will never look for this entry. No point in storing it.\n if (!isIn(t->tag, CiffTagsWeCareAbout))\n return;\n }\n\n try {\n switch (t->type) {\n case CIFF_SUB1:\n case CIFF_SUB2: {\n add(std::make_unique(this, t->data));\n break;\n }\n\n default:\n add(move(t));\n }\n } catch (RawspeedException&) {\n \/\/ Unparsable private data are added as entries\n add(move(t));\n }\n}\n\nCiffIFD::CiffIFD(CiffIFD* const parent_) : parent(parent_) {\n recursivelyCheckSubIFDs(1);\n \/\/ If we are good (can add this IFD without violating the limits),\n \/\/ we are still here. However, due to the way we add parsed sub-IFD's (lazy),\n \/\/ we need to count this IFD right *NOW*, not when adding it at the end.\n recursivelyIncrementSubIFDCount();\n}\n\nCiffIFD::CiffIFD(CiffIFD* const parent_, ByteStream directory)\n : CiffIFD(parent_) {\n if (directory.getSize() < 4)\n ThrowCPE(\"CIFF directory is too short.\");\n\n directory.setPosition(directory.getSize() - 4);\n const uint32 valueDataSize = directory.getU32();\n\n \/\/ The Recursion. Directory entries store data here. May contain IFDs.\n directory.setPosition(0);\n const ByteStream valueData(directory.getStream(valueDataSize));\n\n \/\/ count of the Directory entries in this IFD\n const ushort16 entryCount = directory.getU16();\n\n \/\/ each entry is 10 bytes\n ByteStream dirEntries(directory.getStream(entryCount, 10));\n\n \/\/ IFDData might still contain OtherData until the valueDataSize at the end.\n \/\/ But we do not care about that.\n\n \/\/ Each IFD has it's own valueData area.\n \/\/ In that area, no two entries may overlap.\n NORangesSet valueDatas;\n\n for (uint32 i = 0; i < entryCount; i++)\n parseIFDEntry(&valueDatas, &valueData, &dirEntries);\n}\n\nvoid CiffIFD::recursivelyIncrementSubIFDCount() {\n CiffIFD* p = this->parent;\n if (!p)\n return;\n\n p->subIFDCount++;\n\n for (; p != nullptr; p = p->parent)\n p->subIFDCountRecursive++;\n}\n\nvoid CiffIFD::checkSubIFDs(int headroom) const {\n int count = headroom + subIFDCount;\n if (!headroom)\n assert(count <= CiffIFD::Limits::SubIFDCount);\n else if (count > CiffIFD::Limits::SubIFDCount)\n ThrowCPE(\"TIFF IFD has %u SubIFDs\", count);\n\n count = headroom + subIFDCountRecursive;\n if (!headroom)\n assert(count <= CiffIFD::Limits::RecursiveSubIFDCount);\n else if (count > CiffIFD::Limits::RecursiveSubIFDCount)\n ThrowCPE(\"TIFF IFD file has %u SubIFDs (recursively)\", count);\n}\n\nvoid CiffIFD::recursivelyCheckSubIFDs(int headroom) const {\n int depth = 0;\n for (const CiffIFD* p = this; p != nullptr;) {\n if (!headroom)\n assert(depth <= CiffIFD::Limits::Depth);\n else if (depth > CiffIFD::Limits::Depth)\n ThrowCPE(\"CiffIFD cascading overflow, found %u level IFD\", depth);\n\n p->checkSubIFDs(headroom);\n\n \/\/ And step up\n p = p->parent;\n depth++;\n }\n}\n\nvoid CiffIFD::add(std::unique_ptr subIFD) {\n assert(subIFD->parent == this);\n\n \/\/ We are good, and actually can add this sub-IFD, right?\n subIFD->recursivelyCheckSubIFDs(0);\n\n mSubIFD.push_back(move(subIFD));\n}\n\nvoid CiffIFD::add(std::unique_ptr entry) {\n assert(isIn(entry->tag, CiffTagsWeCareAbout));\n mEntry[entry->tag] = move(entry);\n assert(mEntry.size() <= CiffTagsWeCareAbout.size());\n}\n\ntemplate \nstd::vector CiffIFD::getIFDsWithTagIf(CiffTag tag,\n const Lambda& f) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n\n std::vector matchingIFDs;\n\n const auto found = mEntry.find(tag);\n if (found != mEntry.end()) {\n const auto entry = found->second.get();\n if (f(entry))\n matchingIFDs.push_back(this);\n }\n\n for (const auto& i : mSubIFD) {\n const auto t = i->getIFDsWithTagIf(tag, f);\n matchingIFDs.insert(matchingIFDs.end(), t.begin(), t.end());\n }\n\n return matchingIFDs;\n}\n\ntemplate \nconst CiffEntry* CiffIFD::getEntryRecursiveIf(CiffTag tag,\n const Lambda& f) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n\n const auto found = mEntry.find(tag);\n if (found != mEntry.end()) {\n const auto entry = found->second.get();\n if (f(entry))\n return entry;\n }\n\n for (const auto& i : mSubIFD) {\n const CiffEntry* entry = i->getEntryRecursiveIf(tag, f);\n if (entry)\n return entry;\n }\n\n return nullptr;\n}\n\nvector CiffIFD::getIFDsWithTag(CiffTag tag) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n return getIFDsWithTagIf(tag, [](const CiffEntry*) { return true; });\n}\n\nvector CiffIFD::getIFDsWithTagWhere(CiffTag tag,\n uint32 isValue) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n return getIFDsWithTagIf(tag, [&isValue](const CiffEntry* entry) {\n return entry->isInt() && entry->getU32() == isValue;\n });\n}\n\nvector\nCiffIFD::getIFDsWithTagWhere(CiffTag tag, const string& isValue) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n return getIFDsWithTagIf(tag, [&isValue](const CiffEntry* entry) {\n return entry->isString() && isValue == entry->getString();\n });\n}\n\nbool __attribute__((pure)) CiffIFD::hasEntry(CiffTag tag) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n\n return mEntry.count(tag) > 0;\n}\n\nbool __attribute__((pure)) CiffIFD::hasEntryRecursive(CiffTag tag) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n\n if (mEntry.count(tag) > 0)\n return true;\n\n for (const auto& i : mSubIFD) {\n if (i->hasEntryRecursive(tag))\n return true;\n }\n\n return false;\n}\n\nconst CiffEntry* CiffIFD::getEntry(CiffTag tag) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n\n const auto found = mEntry.find(tag);\n if (found != mEntry.end())\n return found->second.get();\n\n ThrowCPE(\"Entry 0x%x not found.\", tag);\n}\n\nconst CiffEntry* CiffIFD::getEntryRecursive(CiffTag tag) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n return getEntryRecursiveIf(tag, [](const CiffEntry*) { return true; });\n}\n\nconst CiffEntry* CiffIFD::getEntryRecursiveWhere(CiffTag tag,\n uint32 isValue) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n return getEntryRecursiveIf(tag, [&isValue](const CiffEntry* entry) {\n return entry->isInt() && entry->getU32() == isValue;\n });\n}\n\nconst CiffEntry* CiffIFD::getEntryRecursiveWhere(CiffTag tag,\n const string& isValue) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n return getEntryRecursiveIf(tag, [&isValue](const CiffEntry* entry) {\n return entry->isString() && isValue == entry->getString();\n });\n}\n\n} \/\/ namespace rawspeed\nCiffIFD::parseIFDEntry(): don't add all entries that failed to parse.\/*\n RawSpeed - RAW file decoder.\n\n Copyright (C) 2009-2014 Klaus Post\n Copyright (C) 2014 Pedro Côrte-Real\n Copyright (C) 2017-2018 Roman Lebedev\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"tiff\/CiffIFD.h\"\n#include \"common\/Common.h\" \/\/ for uint32, ushort16, isIn\n#include \"common\/NORangesSet.h\" \/\/ for NORangesSet\n#include \"common\/RawspeedException.h\" \/\/ for RawspeedException\n#include \"io\/ByteStream.h\" \/\/ for ByteStream\n#include \"io\/IOException.h\" \/\/ for IOException\n#include \"parsers\/CiffParserException.h\" \/\/ for ThrowCPE, CiffParserException\n#include \"tiff\/CiffEntry.h\" \/\/ for CiffEntry, CiffDataType::CI...\n#include \/\/ for assert\n#include \/\/ for map, _Rb_tree_iterator\n#include \/\/ for unique_ptr\n#include \/\/ for allocator, operator==, string\n#include \/\/ for pair\n#include \/\/ for vector\n\nusing std::string;\nusing std::vector;\nusing std::unique_ptr;\n\nnamespace rawspeed {\n\nvoid CiffIFD::parseIFDEntry(NORangesSet* valueDatas,\n const ByteStream* valueData,\n ByteStream* dirEntries) {\n assert(valueDatas);\n assert(valueData);\n assert(dirEntries);\n\n ByteStream dirEntry = dirEntries->getStream(10); \/\/ Entry is 10 bytes.\n\n auto t = std::make_unique(valueDatas, valueData, dirEntry);\n\n switch (t->type) {\n case CIFF_SUB1:\n case CIFF_SUB2: {\n add(std::make_unique(this, t->data));\n break;\n }\n\n default:\n \/\/ Will we ever look for this entry?\n if (!isIn(t->tag, CiffTagsWeCareAbout))\n return;\n add(move(t));\n }\n}\n\nCiffIFD::CiffIFD(CiffIFD* const parent_) : parent(parent_) {\n recursivelyCheckSubIFDs(1);\n \/\/ If we are good (can add this IFD without violating the limits),\n \/\/ we are still here. However, due to the way we add parsed sub-IFD's (lazy),\n \/\/ we need to count this IFD right *NOW*, not when adding it at the end.\n recursivelyIncrementSubIFDCount();\n}\n\nCiffIFD::CiffIFD(CiffIFD* const parent_, ByteStream directory)\n : CiffIFD(parent_) {\n if (directory.getSize() < 4)\n ThrowCPE(\"CIFF directory is too short.\");\n\n directory.setPosition(directory.getSize() - 4);\n const uint32 valueDataSize = directory.getU32();\n\n \/\/ The Recursion. Directory entries store data here. May contain IFDs.\n directory.setPosition(0);\n const ByteStream valueData(directory.getStream(valueDataSize));\n\n \/\/ count of the Directory entries in this IFD\n const ushort16 entryCount = directory.getU16();\n\n \/\/ each entry is 10 bytes\n ByteStream dirEntries(directory.getStream(entryCount, 10));\n\n \/\/ IFDData might still contain OtherData until the valueDataSize at the end.\n \/\/ But we do not care about that.\n\n \/\/ Each IFD has it's own valueData area.\n \/\/ In that area, no two entries may overlap.\n NORangesSet valueDatas;\n\n for (uint32 i = 0; i < entryCount; i++)\n parseIFDEntry(&valueDatas, &valueData, &dirEntries);\n}\n\nvoid CiffIFD::recursivelyIncrementSubIFDCount() {\n CiffIFD* p = this->parent;\n if (!p)\n return;\n\n p->subIFDCount++;\n\n for (; p != nullptr; p = p->parent)\n p->subIFDCountRecursive++;\n}\n\nvoid CiffIFD::checkSubIFDs(int headroom) const {\n int count = headroom + subIFDCount;\n if (!headroom)\n assert(count <= CiffIFD::Limits::SubIFDCount);\n else if (count > CiffIFD::Limits::SubIFDCount)\n ThrowCPE(\"TIFF IFD has %u SubIFDs\", count);\n\n count = headroom + subIFDCountRecursive;\n if (!headroom)\n assert(count <= CiffIFD::Limits::RecursiveSubIFDCount);\n else if (count > CiffIFD::Limits::RecursiveSubIFDCount)\n ThrowCPE(\"TIFF IFD file has %u SubIFDs (recursively)\", count);\n}\n\nvoid CiffIFD::recursivelyCheckSubIFDs(int headroom) const {\n int depth = 0;\n for (const CiffIFD* p = this; p != nullptr;) {\n if (!headroom)\n assert(depth <= CiffIFD::Limits::Depth);\n else if (depth > CiffIFD::Limits::Depth)\n ThrowCPE(\"CiffIFD cascading overflow, found %u level IFD\", depth);\n\n p->checkSubIFDs(headroom);\n\n \/\/ And step up\n p = p->parent;\n depth++;\n }\n}\n\nvoid CiffIFD::add(std::unique_ptr subIFD) {\n assert(subIFD->parent == this);\n\n \/\/ We are good, and actually can add this sub-IFD, right?\n subIFD->recursivelyCheckSubIFDs(0);\n\n mSubIFD.push_back(move(subIFD));\n}\n\nvoid CiffIFD::add(std::unique_ptr entry) {\n assert(isIn(entry->tag, CiffTagsWeCareAbout));\n mEntry[entry->tag] = move(entry);\n assert(mEntry.size() <= CiffTagsWeCareAbout.size());\n}\n\ntemplate \nstd::vector CiffIFD::getIFDsWithTagIf(CiffTag tag,\n const Lambda& f) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n\n std::vector matchingIFDs;\n\n const auto found = mEntry.find(tag);\n if (found != mEntry.end()) {\n const auto entry = found->second.get();\n if (f(entry))\n matchingIFDs.push_back(this);\n }\n\n for (const auto& i : mSubIFD) {\n const auto t = i->getIFDsWithTagIf(tag, f);\n matchingIFDs.insert(matchingIFDs.end(), t.begin(), t.end());\n }\n\n return matchingIFDs;\n}\n\ntemplate \nconst CiffEntry* CiffIFD::getEntryRecursiveIf(CiffTag tag,\n const Lambda& f) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n\n const auto found = mEntry.find(tag);\n if (found != mEntry.end()) {\n const auto entry = found->second.get();\n if (f(entry))\n return entry;\n }\n\n for (const auto& i : mSubIFD) {\n const CiffEntry* entry = i->getEntryRecursiveIf(tag, f);\n if (entry)\n return entry;\n }\n\n return nullptr;\n}\n\nvector CiffIFD::getIFDsWithTag(CiffTag tag) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n return getIFDsWithTagIf(tag, [](const CiffEntry*) { return true; });\n}\n\nvector CiffIFD::getIFDsWithTagWhere(CiffTag tag,\n uint32 isValue) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n return getIFDsWithTagIf(tag, [&isValue](const CiffEntry* entry) {\n return entry->isInt() && entry->getU32() == isValue;\n });\n}\n\nvector\nCiffIFD::getIFDsWithTagWhere(CiffTag tag, const string& isValue) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n return getIFDsWithTagIf(tag, [&isValue](const CiffEntry* entry) {\n return entry->isString() && isValue == entry->getString();\n });\n}\n\nbool __attribute__((pure)) CiffIFD::hasEntry(CiffTag tag) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n\n return mEntry.count(tag) > 0;\n}\n\nbool __attribute__((pure)) CiffIFD::hasEntryRecursive(CiffTag tag) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n\n if (mEntry.count(tag) > 0)\n return true;\n\n for (const auto& i : mSubIFD) {\n if (i->hasEntryRecursive(tag))\n return true;\n }\n\n return false;\n}\n\nconst CiffEntry* CiffIFD::getEntry(CiffTag tag) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n\n const auto found = mEntry.find(tag);\n if (found != mEntry.end())\n return found->second.get();\n\n ThrowCPE(\"Entry 0x%x not found.\", tag);\n}\n\nconst CiffEntry* CiffIFD::getEntryRecursive(CiffTag tag) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n return getEntryRecursiveIf(tag, [](const CiffEntry*) { return true; });\n}\n\nconst CiffEntry* CiffIFD::getEntryRecursiveWhere(CiffTag tag,\n uint32 isValue) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n return getEntryRecursiveIf(tag, [&isValue](const CiffEntry* entry) {\n return entry->isInt() && entry->getU32() == isValue;\n });\n}\n\nconst CiffEntry* CiffIFD::getEntryRecursiveWhere(CiffTag tag,\n const string& isValue) const {\n assert(isIn(tag, CiffTagsWeCareAbout));\n return getEntryRecursiveIf(tag, [&isValue](const CiffEntry* entry) {\n return entry->isString() && isValue == entry->getString();\n });\n}\n\n} \/\/ namespace rawspeed\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkAMRBaseParticlesReader.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n =========================================================================*\/\n#include \"vtkAMRBaseParticlesReader.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkMultiProcessController.h\"\n#include \"vtkMultiBlockDataSet.h\"\n#include \"vtkIndent.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n\n#include \n\nvtkAMRBaseParticlesReader::vtkAMRBaseParticlesReader()\n{\n\n}\n\n\/\/------------------------------------------------------------------------------\nvtkAMRBaseParticlesReader::~vtkAMRBaseParticlesReader()\n{\n\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkAMRBaseParticlesReader::PrintSelf( std::ostream &os, vtkIndent indent )\n{\n this->Superclass::PrintSelf( os, indent );\n}\n\n\/\/------------------------------------------------------------------------------\nint vtkAMRBaseParticlesReader::FillOutputPortInformation(\n int vtkNotUsed(port), vtkInformation *info )\n{\n info->Set( vtkDataObject::DATA_TYPE_NAME(), \"vtkMultiBlockDataSet\" );\n return 1;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkAMRBaseParticlesReader::Initialize( )\n{\n this->SetNumberOfInputPorts( 0 );\n this->Frequency = 1;\n this->FilterLocation = 0;\n this->NumberOfBlocks = 0;\n this->Initialized = false;\n this->Controller = vtkMultiProcessController::GetGlobalController();\n\n for( int i=0; i < 3; ++i )\n {\n this->MinLocation[ i ] = this->MaxLocation[ i ] = 0.0;\n }\n\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkAMRBaseParticlesReader::SetFileName( const char *fileName )\n{\n\n if( this->FileName != NULL )\n {\n\n if( strcmp(this->FileName,fileName) != 0 )\n {\n this->Initialized = false;\n delete [] this->FileName;\n this->FileName = NULL;\n }\n else\n {\n return;\n }\n }\n\n this->FileName = new char[ strlen(fileName)+1 ];\n strcpy(this->FileName,fileName);\n\n this->Modified();\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkAMRBaseParticlesReader::IsParallel()\n{\n if( this->Controller != NULL && this->Controller->GetNumberOfProcesses() > 1 )\n return true;\n return false;\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkAMRBaseParticlesReader::IsBlockMine( const int blkIdx )\n{\n if( !this->IsParallel() )\n return true;\n\n int myRank = this->Controller->GetLocalProcessId();\n if( myRank == this->GetBlockProcessId( blkIdx ) )\n return true;\n return false;\n}\n\n\/\/------------------------------------------------------------------------------\nint vtkAMRBaseParticlesReader::GetBlockProcessId( const int blkIdx )\n{\n if( !this->IsParallel() )\n return 0;\n\n int N = this->Controller->GetNumberOfProcesses();\n return( blkIdx%N );\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkAMRBaseParticlesReader::CheckLocation(\n const double x, const double y, const double z )\n{\n if( !this->FilterLocation )\n return true;\n\n double coords[3];\n coords[0] = x;\n coords[1] = y;\n coords[2] = z;\n\n for( int i=0; i < 3; ++i )\n {\n if( this->MinLocation[i] > coords[i] || coords[i] > this->MaxLocation[i] )\n return false;\n } \/\/ END for all dimensions\n\n return true;\n}\n\n\/\/------------------------------------------------------------------------------\nint vtkAMRBaseParticlesReader::RequestData(\n vtkInformation *vtkNotUsed(request),\n vtkInformationVector **vtkNotUsed(inputVector),\n vtkInformationVector *outputVector )\n{\n \/\/ STEP 0: Get the output object\n vtkInformation *outInf = outputVector->GetInformationObject( 0 );\n vtkMultiBlockDataSet *mbds = vtkMultiBlockDataSet::SafeDownCast(\n outInf->Get( vtkDataObject::DATA_OBJECT() ) );\n assert( \"pre: output multi-block dataset object is NULL\" && (mbds != NULL) );\n\n \/\/ STEP 1: Read Meta-Data\n this->ReadMetaData();\n\n \/\/ STEP 2: Read blocks\n mbds->SetNumberOfBlocks( this->NumberOfBlocks );\n for( unsigned int blkidx=0; blkidx < this->NumberOfBlocks; ++blkidx )\n {\n\n if( this->IsBlockMine( blkidx ) )\n {\n vtkPolyData *particles = this->ReadParticles( blkidx );\n assert( \"particles dataset should not be NULL!\" &&\n (particles != NULL) );\n\n mbds->SetBlock( blkidx, particles );\n particles->Delete();\n }\n else\n {\n mbds->SetBlock( blkidx, NULL );\n }\n\n } \/\/ END for all blocks\n\n \/\/ STEP 3: Synchronize\n if( this->IsParallel( ) )\n this->Controller->Barrier();\n\n return 1;\n}\n\n\nBUGFIX: Intialize FileName to NULL\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkAMRBaseParticlesReader.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n =========================================================================*\/\n#include \"vtkAMRBaseParticlesReader.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkMultiProcessController.h\"\n#include \"vtkMultiBlockDataSet.h\"\n#include \"vtkIndent.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n\n#include \n\nvtkAMRBaseParticlesReader::vtkAMRBaseParticlesReader()\n{\n\n}\n\n\/\/------------------------------------------------------------------------------\nvtkAMRBaseParticlesReader::~vtkAMRBaseParticlesReader()\n{\n\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkAMRBaseParticlesReader::PrintSelf( std::ostream &os, vtkIndent indent )\n{\n this->Superclass::PrintSelf( os, indent );\n}\n\n\/\/------------------------------------------------------------------------------\nint vtkAMRBaseParticlesReader::FillOutputPortInformation(\n int vtkNotUsed(port), vtkInformation *info )\n{\n info->Set( vtkDataObject::DATA_TYPE_NAME(), \"vtkMultiBlockDataSet\" );\n return 1;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkAMRBaseParticlesReader::Initialize( )\n{\n this->SetNumberOfInputPorts( 0 );\n this->Frequency = 1;\n this->FilterLocation = 0;\n this->NumberOfBlocks = 0;\n this->Initialized = false;\n this->FileName = NULL;\n this->Controller = vtkMultiProcessController::GetGlobalController();\n\n for( int i=0; i < 3; ++i )\n {\n this->MinLocation[ i ] = this->MaxLocation[ i ] = 0.0;\n }\n\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkAMRBaseParticlesReader::SetFileName( const char *fileName )\n{\n\n std::cout << \"SetFileName: \" << fileName << std::endl;\n std::cout.flush();\n\n if( this->FileName != NULL )\n {\n\n if( strcmp(this->FileName,fileName) != 0 )\n {\n this->Initialized = false;\n delete [] this->FileName;\n this->FileName = NULL;\n }\n else\n {\n return;\n }\n }\n\n this->FileName = new char[ strlen(fileName)+1 ];\n strcpy(this->FileName,fileName);\n\n std::cout << \"Setting filename done!\\n\";\n std::cout.flush();\n\n this->Modified();\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkAMRBaseParticlesReader::IsParallel()\n{\n if( this->Controller != NULL && this->Controller->GetNumberOfProcesses() > 1 )\n return true;\n return false;\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkAMRBaseParticlesReader::IsBlockMine( const int blkIdx )\n{\n if( !this->IsParallel() )\n return true;\n\n int myRank = this->Controller->GetLocalProcessId();\n if( myRank == this->GetBlockProcessId( blkIdx ) )\n return true;\n return false;\n}\n\n\/\/------------------------------------------------------------------------------\nint vtkAMRBaseParticlesReader::GetBlockProcessId( const int blkIdx )\n{\n if( !this->IsParallel() )\n return 0;\n\n int N = this->Controller->GetNumberOfProcesses();\n return( blkIdx%N );\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkAMRBaseParticlesReader::CheckLocation(\n const double x, const double y, const double z )\n{\n if( !this->FilterLocation )\n return true;\n\n double coords[3];\n coords[0] = x;\n coords[1] = y;\n coords[2] = z;\n\n for( int i=0; i < 3; ++i )\n {\n if( this->MinLocation[i] > coords[i] || coords[i] > this->MaxLocation[i] )\n return false;\n } \/\/ END for all dimensions\n\n return true;\n}\n\n\/\/------------------------------------------------------------------------------\nint vtkAMRBaseParticlesReader::RequestData(\n vtkInformation *vtkNotUsed(request),\n vtkInformationVector **vtkNotUsed(inputVector),\n vtkInformationVector *outputVector )\n{\n \/\/ STEP 0: Get the output object\n vtkInformation *outInf = outputVector->GetInformationObject( 0 );\n vtkMultiBlockDataSet *mbds = vtkMultiBlockDataSet::SafeDownCast(\n outInf->Get( vtkDataObject::DATA_OBJECT() ) );\n assert( \"pre: output multi-block dataset object is NULL\" && (mbds != NULL) );\n\n \/\/ STEP 1: Read Meta-Data\n this->ReadMetaData();\n\n \/\/ STEP 2: Read blocks\n mbds->SetNumberOfBlocks( this->NumberOfBlocks );\n for( unsigned int blkidx=0; blkidx < this->NumberOfBlocks; ++blkidx )\n {\n\n if( this->IsBlockMine( blkidx ) )\n {\n vtkPolyData *particles = this->ReadParticles( blkidx );\n assert( \"particles dataset should not be NULL!\" &&\n (particles != NULL) );\n\n mbds->SetBlock( blkidx, particles );\n particles->Delete();\n }\n else\n {\n mbds->SetBlock( blkidx, NULL );\n }\n\n } \/\/ END for all blocks\n\n \/\/ STEP 3: Synchronize\n if( this->IsParallel( ) )\n this->Controller->Barrier();\n\n return 1;\n}\n\n\n<|endoftext|>"} {"text":"\/**\n * KeybdInput 1.0.4\n *\n * @author Roger Lima (rogerlima@outlook.com)\n * @date 31\/aug\/2014\n * @update 20\/feb\/2016\n * @desc Reads the keyboard input them according to the format specified (only works on Windows)\n * @example\n\tint day, month, year;\n\tKeybdInput< int > userin;\n\n\tuserin.solicit(\n\t\t\"Type a valid date (formatted as dd\/mm\/yyyy): \",\n\t\tstd::regex( \"([0-2]?[0-9]|3[0-1])\/(0?[1-9]|1[012])\/([0-9]{4})\" ),\n\t\t{ &day, &month, &year },\n\t\tfalse,\n\t\tfalse,\n\t\t\"\/\"\n\t);\n\n\twhile ( ( day >= 29 && month == 2 ) && !( ( year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0 )\n\t\t|| day == 31 && ( month == 4 || month == 6 || month == 9 || month == 11 )\n\t)\n\t\tuserin.reset();\n*\/\n\n#pragma once\n#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate< typename T >\nclass KeybdInput {\nprivate:\n\t\/\/ Stores the values to be used in KeybdInput::reset()\n\tbool _instverify, _ispw;\n\tsize_t _inmaxsize;\n\tstd::regex _restriction;\n\tstd::string _rmsg, _sep;\n\tstd::vector< T * > _references = {};\n\n\t\/\/ Stores the user input\n\tstd::string input;\n\n\t\/\/ Receives the current X and Y cursor position from get_cursor_position()\n\tstd::vector< short > cursor_position = { 0, 0 };\n\n\t\/\/ Erase the input of user\n\t\/\/ @param [{size_t=input.size()}] Erase range\n\tvoid erase_input( size_t = 0 );\n\n\t\/\/ Get the console cursor position and pass to the cursor_position\n\tvoid get_cursor_position();\n\n\t\/\/ Set the console cursor position\n\t\/\/ @param {short} X position of cursor\n\t\/\/ @param [{short=cursor_position[ 1 ]}] Y position of cursor\n\tvoid set_cursor_position( short, short = 0 );\n\n\t\/\/ Split a string\n\t\/\/ @param {std::string} Target string\n\t\/\/ @param [{std::string=\"\"}] Separator\n\tstd::vector< std::string > splitstr( std::string str, std::string separator = \"\" );\n\n\t\/\/ Set the reference with input value\n\t\/\/ @param {const std::string&} Input value\n\t\/\/ @param {T*} Target place\n\tvoid set_reference( const std::string&, T * );\n\n\t\/\/ Clear all values of references\n\t\/\/ @param {T*} Target place\n\tvoid clear_references( std::vector< T * > );\npublic:\n\t\/\/ Clipboard (arrow up or down to show the last inputs)\n\tstd::vector< std::string > clipboard;\n\n\t\/\/ Requires the user input again\n\t\/\/ @param [{std::string=_rmsg}] Request message\n\tvoid reset( std::string = \"\" );\n\n\t\/\/ Requires the keyboard input\n\t\/\/ @param {string} Request message\n\t\/\/ @param {regex} The regex\n\t\/\/ @param {vector< T * >} The place(s) where it will be stored the input\n\t\/\/ @param [{bool=false}] Instant verify\n\t\/\/ @param [{bool=false}] Is password\n\t\/\/ @param [{std::string=\" \"}] Separator\n\t\/\/ @param [{size_t=1000}] Input size\n\tvoid solicit( std::string, std::regex, std::vector< T * >, bool = false, bool = false, std::string = \" \", size_t = 1000 );\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::erase_input( size_t erase_range = 0 ) {\n\t\/\/ Default erase range\n\tif ( !erase_range )\n\t\terase_range = input.size();\n\n\tfor ( size_t i = 0; i < erase_range; i++ )\n\t\tstd::cout << \"\\b \\b\";\n\n\tinput = \"\";\n};\n\ntemplate < typename T >\nvoid KeybdInput< T >::set_reference( const std::string& value, T *target ) {\n\tstd::stringstream convert;\n\tconvert << value;\n\tconvert >> *target;\n};\n\nvoid KeybdInput< std::string >::set_reference( const std::string& value, std::string *target ) {\n\t*target = value;\n};\n\ntemplate < typename T >\nvoid KeybdInput< T >::clear_references( std::vector< T * > target ) {\n\tfor ( size_t i = 0; i < _references.size(); *target[ i++ ] = 0 );\n};\n\nvoid KeybdInput< std::string >::clear_references( std::vector< std::string * > target ) {\n\tfor ( size_t i = 0; i < _references.size(); *target[ i++ ] = \"\" );\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::get_cursor_position() {\n\tCONSOLE_SCREEN_BUFFER_INFO screen_buffer_info;\n\tHANDLE hStd = GetStdHandle( STD_OUTPUT_HANDLE );\n\n\tif ( !GetConsoleScreenBufferInfo( hStd, &screen_buffer_info ) )\n\t\tMessageBox( NULL, L\"An error occurred getting the console cursor position.\", L\"KeybdInput ERROR\", NULL );\n\n\tcursor_position[ 0 ] = screen_buffer_info.dwCursorPosition.X;\n\tcursor_position[ 1 ] = screen_buffer_info.dwCursorPosition.Y;\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::set_cursor_position( short x, short y = 0 ) {\n\tif ( !SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), { x, y } ) )\n\t\tMessageBox( NULL, L\"An error occurred setting the console cursor position.\", L\"KeybdInput ERROR\", NULL );\n};\n\ntemplate< typename T >\nstd::vector< std::string > KeybdInput< T >::splitstr( std::string str, std::string separator = \"\" ) {\n\tsize_t index;\n\tstd::vector< std::string > elems;\n\n\twhile ( ( index = str.find( separator ) ) != std::string::npos && str.size() > 1 ) {\n\t\telems.push_back( str.substr( 0, index ? index : 1 ) );\n\t\tstr.erase( 0, index + ( !separator.size() ? 1 : separator.size() ) );\n\t}\n\n\telems.push_back( str );\n\n\treturn elems;\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::reset( std::string msg = \"\" ) {\n\t\/\/ Default request message\n\tif ( msg == \"\" && _rmsg != \"\" )\n\t\tmsg = _rmsg;\n\n\t\/\/ Clear previously set values\n\tclear_references( _references );\n\n\t\/\/ Sets the cursor in the previous line, erase all and requires input again\n\tget_cursor_position();\n\tset_cursor_position( static_cast< short >( msg.size() + input.size() ), cursor_position[ 1 ] - 1 );\n\terase_input( msg.size() + input.size() );\n\tsolicit( msg, std::regex( _restriction ), _references, _instverify, _ispw, _sep, _inmaxsize );\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::solicit( std::string request_msg, std::regex restriction, std::vector< T * > references, bool instant_verify, bool is_password, std::string separator, size_t input_max_size ) {\n\tstatic size_t clipboard_index = 0;\n\tsize_t i, cursor_pos_x,\n\t\tinputLength = 0;\n\tchar key = 0;\n\tbool is_function_key = false,\n\t\tarrow = false,\n\t\twaiting_input = true;\n\tstd::string input_subtr;\n\tstd::vector< std::string > inputParts;\n\n\tif ( references.size() == 0 ) {\n\t\tMessageBox( NULL, L\"\\\"refereces\\\" param need be set with at least one member.\", L\"KeybdInput ERROR\", NULL );\n\t\treturn;\n\t}\n\n\tinput = \"\";\n\tstd::cout << request_msg;\n\n\t\/\/ Retrieves the values to be used in KeybdInput::reset()\n\t_rmsg = request_msg;\n\t_restriction = restriction;\n\t_references = references;\n\t_instverify = instant_verify;\n\t_ispw = is_password;\n\t_sep = separator;\n\t_inmaxsize = input_max_size;\n\n\twhile ( waiting_input ) {\n\t\tkey = _getch();\n\n\t\t\/\/ Arrow keys prefix\n\t\tif ( key == -32 ) {\n\t\t\tarrow = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Prevents function keys\n\t\tif ( key == 0 ) {\n\t\t\tis_function_key = true;\n\t\t\tcontinue;\n\t\t} else if ( is_function_key ) {\n\t\t\tis_function_key = false;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Arrows\n\t\tif ( arrow ) {\n\t\t\tget_cursor_position();\n\n\t\t\t\/\/ LEFT\n\t\t\tif ( key == 75 && static_cast< size_t >( cursor_position[ 0 ] ) > request_msg.size() )\n\t\t\t\tset_cursor_position( cursor_position[ 0 ] - 1 );\n\n\t\t\t\/\/ RIGHT\n\t\t\telse if ( key == 77 && static_cast< size_t >( cursor_position[ 0 ] ) < input.size() + request_msg.size() )\n\t\t\t\tset_cursor_position( cursor_position[ 0 ] + 1 );\n\n\t\t\t\/\/ UP\n\t\t\telse if ( key == 72 && !is_password && clipboard.size() > 0 && clipboard_index > 0 ) {\n\t\t\t\terase_input();\n\t\t\t\tstd::cout << clipboard[ --clipboard_index ];\n\n\t\t\t\tinput = clipboard[ clipboard_index ];\n\t\t\t\tinputLength = clipboard[ clipboard_index ].size();\n\t\t\t}\n\n\t\t\t\/\/ DOWN\n\t\t\telse if ( key == 80 && !is_password && clipboard.size() > 0 && clipboard_index < clipboard.size() - 1 ) {\n\t\t\t\terase_input();\n\t\t\t\tstd::cout << clipboard[ ++clipboard_index ];\n\n\t\t\t\tinput = clipboard[ clipboard_index ];\n\t\t\t\tinputLength = clipboard[ clipboard_index ].size();\n\n\t\t\t\tif ( clipboard_index >= clipboard.size() )\n\t\t\t\t\tclipboard_index = clipboard.size() - 1;\n\t\t\t}\n\n\t\t}\n\n\t\t\/\/ Valid character\n\t\telse if ( key != 8 && key != 13 ) {\n\t\t\t\/\/ Inserts the character in current cursor position\n\t\t\tget_cursor_position();\n\t\t\tinput.insert( cursor_position[ 0 ] - request_msg.size(), std::string( 1, key ) );\n\n\t\t\t\/\/ If the user input satisfy the restrictions, removes the character\n\t\t\tif ( instant_verify && ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) ) {\n\t\t\t\tinput.erase( cursor_position[ 0 ] - request_msg.size(), 1 );\n\t\t\t} else {\n\t\t\t\t\/\/ Appends the character if cursor is at the end, otherwise, interleaves\n\t\t\t\tif ( cursor_position[ 0 ] == ( request_msg.size() + input.size() - 1 ) ) {\n\t\t\t\t\tstd::cout << ( ( is_password ) ? '*' : key );\n\t\t\t\t} else {\n\t\t\t\t\tinput_subtr = input.substr( input.size() - ( ( request_msg.size() + input.size() ) - cursor_position[ 0 ] - 1 ), input.size() );\n\n\t\t\t\t\tstd::cout << ( ( is_password ) ? '*' : key )\n\t\t\t\t\t\t<< ( ( is_password ) ? std::string( input_subtr.size(), '*' ) : input_subtr );\n\t\t\t\t\tset_cursor_position( cursor_position[ 0 ] + 1 );\n\t\t\t\t}\n\n\t\t\t\tinputLength++;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ ENTER\n\t\telse if ( key == 13 && inputLength ) {\n\t\t\t\/\/ If the user input satisfy the restrictions, clear input\n\t\t\tif ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) {\n\t\t\t\terase_input();\n\t\t\t\tinputLength = 0;\n\t\t\t} else {\n\t\t\t\t\/\/ Trim left and right\n\t\t\t\tinput.erase( 0, input.find_first_not_of( ' ' ) );\n\t\t\t\tinput.erase( input.find_last_not_of( ' ' ) + 1 );\n\n\t\t\t\tif ( references.size() == 1 )\n\t\t\t\t\tset_reference( input, references[ 0 ] );\n\t\t\t\telse\n\t\t\t\t\tfor ( i = 0, inputParts = splitstr( input, separator ); i < references.size(); i++ )\n\t\t\t\t\t\tif ( i < inputParts.size() )\n\t\t\t\t\t\t\tset_reference( inputParts[ i ], references[ i ] );\n\n\t\t\t\tstd::cout << std::endl;\n\n\t\t\t\t\/\/ Prevents repetition on clipboard and don't save if it's a password\n\t\t\t\tif ( !is_password && ( clipboard.size() == 0 || input != clipboard[ clipboard.size() - 1 ] ) ) {\n\t\t\t\t\tclipboard.push_back( input );\n\t\t\t\t\tclipboard_index = clipboard.size();\n\t\t\t\t}\n\n\t\t\t\twaiting_input = false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ BACKSPACE\n\t\telse if ( key == 8 && inputLength ) {\n\t\t\tget_cursor_position();\n\t\t\tcursor_pos_x = cursor_position[ 0 ];\n\n\t\t\tif ( cursor_pos_x == ( request_msg.size() + input.size() - 1 ) && inputLength == 1 )\n\t\t\t\tcontinue;\n\n\t\t\tstd::cout << \"\\b \\b\";\n\t\t\tinput.erase( cursor_pos_x - request_msg.size() - 1, 1 );\n\t\t\tinputLength--;\n\n\t\t\t\/\/ If the cursor isn't at the end\n\t\t\tif ( cursor_pos_x <= ( request_msg.size() + input.size() ) ) {\n\t\t\t\t\/\/ Put the cursor at the start and rewrites the input\n\t\t\t\tset_cursor_position( static_cast< short >( request_msg.size() ) );\n\t\t\t\tstd::cout << ( ( is_password ) ? std::string( input.size(), '*' ) : input );\n\n\t\t\t\t\/\/ Put the cursor at the end and erase the last char\n\t\t\t\tset_cursor_position( static_cast< short >( request_msg.size() + input.size() + 1 ) );\n\t\t\t\tstd::cout << \"\\b \\b\";\n\n\t\t\t\t\/\/ Put the cursor at the original position\n\t\t\t\tset_cursor_position( static_cast< short >( cursor_pos_x - 1 ) );\n\t\t\t}\n\t\t}\n\n\t\tarrow = false;\n\t}\n};\nVersion 1.1.0\/**\n * KeybdInput 1.1.0\n *\n * @author Roger Lima (rogerlima@outlook.com)\n * @date 31\/aug\/2014\n * @update 20\/mar\/2016\n * @desc Reads the keyboard input them according to the format specified (only works on Windows)\n * @example\n\tint day, month, year;\n\tKeybdInput< int > userin;\n\n\tuserin.separator = \"\/\";\n\tuserin.solicit(\n\t\t\"Type a valid date (formatted as dd\/mm\/yyyy): \",\n\t\tstd::regex( \"([0-2]?[0-9]|3[0-1])\/(0?[1-9]|1[012])\/([0-9]{4})\" ),\n\t\t{ &day, &month, &year }\n\t);\n\n\twhile ( ( day >= 29 && month == 2 ) && !( ( year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0 )\n\t\t|| day == 31 && ( month == 4 || month == 6 || month == 9 || month == 11 )\n\t)\n\t\tuserin.requires_again();\n*\/\n\n#pragma once\n#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate< typename T >\nclass KeybdInput {\nprivate:\n\t\/\/ Stores the values to be used in KeybdInput::requires_again()\n\tstd::regex restriction_copy;\n\tstd::string request_msg_copy, separator_copy;\n\tstd::vector< T * > references_copy = {};\n\tbool instant_verify_copy, is_password_copy, clear_input_copy;\n\tsize_t input_max_size_copy;\n\n\t\/\/ Retrieves default properties setted in constructor\n\tbool instant_verify_default = false,\n\t\tis_password_default = false,\n\t\tclear_input_default = true;\n\tstd::string separator_default = \" \";\n\tsize_t input_max_size_default = 1000;\n\n\t\/\/ Stores the user input\n\tstd::string input;\n\n\t\/\/ Receives the current X and Y cursor position from get_cursor_position()\n\tstd::vector< short > cursor_position = { 0, 0 };\n\n\t\/\/ Erase the input of user\n\t\/\/ @param [{size_t=input.size()}] Erase range\n\t\/\/ @param [{bool=false}] Force clear input\n\t\/\/ @param [{bool=false}] Is reset\n\tvoid input_back( size_t = NULL, bool = false, bool = false );\n\n\t\/\/ Get the console cursor position and pass to the cursor_position\n\tvoid get_cursor_position();\n\n\t\/\/ Set the console cursor position\n\t\/\/ @param {short} X position of cursor\n\t\/\/ @param [{short=cursor_position[ 1 ]}] Y position of cursor\n\tvoid set_cursor_position( short, short = 0 );\n\n\t\/\/ Split a string\n\t\/\/ @param {std::string} Target string\n\t\/\/ @param [{std::string=\"\"}] Separator\n\tstd::vector< std::string > splitstr( std::string str, std::string separator = \"\" );\n\n\t\/\/ Set the reference with input value\n\t\/\/ @param {const std::string&} Input value\n\t\/\/ @param {T*} Target place\n\tvoid set_reference( const std::string&, T * );\n\n\t\/\/ Clear all values of references\n\t\/\/ @param {T*} Target place\n\tvoid clear_references( std::vector< T * > );\npublic:\n\t\/\/ Properties\n\tbool instant_verify = false,\n\t\tis_password = false,\n\t\tclear_input = true;\n\tstd::string separator = \" \";\n\tsize_t input_max_size = 1000;\n\n\t\/\/ Clipboard (arrow up or down to show the last inputs)\n\tstd::vector< std::string > clipboard;\n\n\t\/\/ Requires the user input again\n\t\/\/ @param [{std::string=request_msg_copy}] Request message\n\tvoid requires_again( std::string = \"\" );\n\n\t\/\/ Requires the keyboard input\n\t\/\/ @param {string} Request message\n\t\/\/ @param {regex} The regex\n\t\/\/ @param {vector< T * >} The place(s) where it will be stored the input\n\t\/\/ @param [{bool=false}] Is reset (for internal use)\n\tvoid solicit( std::string, std::regex, std::vector< T * > );\n\n\t\/\/ Constructor\n\t\/\/ @param [{bool=false}] Instant verify\n\t\/\/ @param [{bool=false}] Is password\n\t\/\/ @param [{bool=true}] Erase the input or repeat in next line if the user input don't match with the restrictons \n\t\/\/ @param [{std::string=\" \"}] Separator\n\t\/\/ @param [{size_t=1000}] Input size\n\tKeybdInput( bool = false, bool = false, bool = true, std::string = \" \", size_t = 1000 );\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::input_back( size_t erase_range, bool force_clear, bool is_reset ) {\n\t\/\/ Default erase range\n\tif ( !erase_range )\n\t\terase_range = input.size();\n\n\tif ( force_clear || clear_input )\n\t\tfor ( size_t i = 0; i < erase_range; i++ )\n\t\t\tstd::cout << \"\\b \\b\";\n\telse if ( !is_reset )\n\t\tstd::cout << std::endl << request_msg_copy;\n\telse\n\t\tstd::cout << std::endl;\n\n\tinput = \"\";\n};\n\ntemplate < typename T >\nvoid KeybdInput< T >::set_reference( const std::string& value, T *target ) {\n\tstd::stringstream convert;\n\tconvert << value;\n\tconvert >> *target;\n};\n\nvoid KeybdInput< std::string >::set_reference( const std::string& value, std::string *target ) {\n\t*target = value;\n};\n\ntemplate < typename T >\nvoid KeybdInput< T >::clear_references( std::vector< T * > target ) {\n\tfor ( size_t i = 0; i < references_copy.size(); *target[ i++ ] = 0 );\n};\n\nvoid KeybdInput< std::string >::clear_references( std::vector< std::string * > target ) {\n\tfor ( size_t i = 0; i < references_copy.size(); *target[ i++ ] = \"\" );\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::get_cursor_position() {\n\tCONSOLE_SCREEN_BUFFER_INFO screen_buffer_info;\n\tHANDLE hStd = GetStdHandle( STD_OUTPUT_HANDLE );\n\n\tif ( !GetConsoleScreenBufferInfo( hStd, &screen_buffer_info ) )\n\t\tMessageBox( NULL, L\"An error occurred getting the console cursor position.\", L\"KeybdInput ERROR\", NULL );\n\n\tcursor_position[ 0 ] = screen_buffer_info.dwCursorPosition.X;\n\tcursor_position[ 1 ] = screen_buffer_info.dwCursorPosition.Y;\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::set_cursor_position( short x, short y = 0 ) {\n\tif ( !SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), { x, y } ) )\n\t\tMessageBox( NULL, L\"An error occurred setting the console cursor position.\", L\"KeybdInput ERROR\", NULL );\n};\n\ntemplate< typename T >\nstd::vector< std::string > KeybdInput< T >::splitstr( std::string str, std::string separator = \"\" ) {\n\tsize_t index;\n\tstd::vector< std::string > elems;\n\n\twhile ( ( index = str.find( separator ) ) != std::string::npos && str.size() > 1 ) {\n\t\telems.push_back( str.substr( 0, index ? index : 1 ) );\n\t\tstr.erase( 0, index + ( !separator.size() ? 1 : separator.size() ) );\n\t}\n\n\telems.push_back( str );\n\n\treturn elems;\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::requires_again( std::string msg = \"\" ) {\n\t\/\/ Default request message\n\tif ( msg == \"\" && request_msg_copy != \"\" )\n\t\tmsg = request_msg_copy;\n\n\t\/\/ Clear previously set values\n\tclear_references( references_copy );\n\n\t\/\/ Sets the options\n\tinstant_verify = instant_verify_copy;\n\tis_password = is_password_copy;\n\tclear_input = clear_input_copy;\n\tseparator = separator_copy;\n\tinput_max_size = input_max_size_copy;\n\n\t\/\/ Sets the cursor in the previous line, clear all (if is set) and requires input again\n\tget_cursor_position();\n\tset_cursor_position( static_cast< short >( msg.size() + input.size() ), cursor_position[ 1 ] - 1 );\n\tinput_back( msg.size() + input.size(), false, true );\n\tsolicit( msg, std::regex( restriction_copy ), references_copy );\n\n\t\/\/ Default values\n\tinstant_verify_copy = instant_verify_default;\n\tis_password_copy = is_password_default;\n\tclear_input_copy = clear_input_default;\n\tseparator_copy = separator_default;\n\tinput_max_size_copy = input_max_size_default;\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::solicit( std::string request_msg, std::regex restriction, std::vector< T * > references ) {\n\tstatic size_t clipboard_index = 0;\n\tsize_t i, cursor_pos_x,\n\t\tinputLength = 0;\n\tchar key = 0;\n\tbool is_function_key = false,\n\t\tarrow = false,\n\t\twaiting_input = true;\n\tstd::string input_subtr;\n\tstd::vector< std::string > inputParts;\n\n\tif ( references.size() == 0 ) {\n\t\tMessageBox( NULL, L\"\\\"refereces\\\" param need be set with at least one member.\", L\"KeybdInput ERROR\", NULL );\n\t\treturn;\n\t}\n\n\tinput = \"\";\n\n\tstd::cout << request_msg;\n\n\t\/\/ Retrieves the values to be used in KeybdInput::requires_again()\n\trequest_msg_copy = request_msg;\n\trestriction_copy = restriction;\n\treferences_copy = references;\n\tinstant_verify_copy = instant_verify;\n\tis_password_copy = is_password;\n\tclear_input_copy = clear_input;\n\tseparator_copy = separator;\n\tinput_max_size_copy = input_max_size;\n\n\twhile ( waiting_input ) {\n\t\tkey = _getch();\n\n\t\t\/\/ Arrow keys prefix\n\t\tif ( key == -32 ) {\n\t\t\tarrow = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Prevents function keys\n\t\tif ( key == 0 ) {\n\t\t\tis_function_key = true;\n\t\t\tcontinue;\n\t\t} else if ( is_function_key ) {\n\t\t\tis_function_key = false;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Arrows\n\t\tif ( arrow ) {\n\t\t\tget_cursor_position();\n\n\t\t\t\/\/ LEFT\n\t\t\tif ( key == 75 && static_cast< size_t >( cursor_position[ 0 ] ) > request_msg.size() )\n\t\t\t\tset_cursor_position( cursor_position[ 0 ] - 1 );\n\n\t\t\t\/\/ RIGHT\n\t\t\telse if ( key == 77 && static_cast< size_t >( cursor_position[ 0 ] ) < input.size() + request_msg.size() )\n\t\t\t\tset_cursor_position( cursor_position[ 0 ] + 1 );\n\n\t\t\t\/\/ UP\n\t\t\telse if ( key == 72 && !is_password && clipboard.size() > 0 && clipboard_index > 0 ) {\n\t\t\t\tinput_back( NULL, true );\n\t\t\t\tstd::cout << clipboard[ --clipboard_index ];\n\n\t\t\t\tinput = clipboard[ clipboard_index ];\n\t\t\t\tinputLength = clipboard[ clipboard_index ].size();\n\t\t\t}\n\n\t\t\t\/\/ DOWN\n\t\t\telse if ( key == 80 && !is_password && clipboard.size() > 0 && clipboard_index < clipboard.size() - 1 ) {\n\t\t\t\tinput_back( NULL, true );\n\t\t\t\tstd::cout << clipboard[ ++clipboard_index ];\n\n\t\t\t\tinput = clipboard[ clipboard_index ];\n\t\t\t\tinputLength = clipboard[ clipboard_index ].size();\n\n\t\t\t\tif ( clipboard_index >= clipboard.size() )\n\t\t\t\t\tclipboard_index = clipboard.size() - 1;\n\t\t\t}\n\n\t\t}\n\n\t\t\/\/ Valid character\n\t\telse if ( key != 8 && key != 13 ) {\n\t\t\t\/\/ Inserts the character in current cursor position\n\t\t\tget_cursor_position();\n\t\t\tinput.insert( cursor_position[ 0 ] - request_msg.size(), std::string( 1, key ) );\n\n\t\t\t\/\/ If the user input satisfy the restrictions, removes the character\n\t\t\tif ( instant_verify && ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) ) {\n\t\t\t\tinput.erase( cursor_position[ 0 ] - request_msg.size(), 1 );\n\t\t\t} else {\n\t\t\t\t\/\/ Appends the character if cursor is at the end, otherwise, interleaves\n\t\t\t\tif ( cursor_position[ 0 ] == ( request_msg.size() + input.size() - 1 ) ) {\n\t\t\t\t\tstd::cout << ( is_password ? '*' : key );\n\t\t\t\t} else {\n\t\t\t\t\tinput_subtr = input.substr( input.size() - ( ( request_msg.size() + input.size() ) - cursor_position[ 0 ] - 1 ), input.size() );\n\n\t\t\t\t\tstd::cout << ( is_password ? '*' : key )\n\t\t\t\t\t\t<< ( is_password ? std::string( input_subtr.size(), '*' ) : input_subtr );\n\t\t\t\t\tset_cursor_position( cursor_position[ 0 ] + 1 );\n\t\t\t\t}\n\n\t\t\t\tinputLength++;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ ENTER\n\t\telse if ( key == 13 && inputLength ) {\n\t\t\t\/\/ Prevents repetition on clipboard and don't save if it's a password\n\t\t\tif ( !is_password && ( clipboard.size() == 0 || input != clipboard[ clipboard.size() - 1 ] ) ) {\n\t\t\t\tclipboard.push_back( input );\n\t\t\t\tclipboard_index = clipboard.size();\n\t\t\t}\n\n\t\t\t\/\/ If the user input satisfy the restrictions, clear input\n\t\t\tif ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) {\n\t\t\t\tinput_back();\n\t\t\t\tinputLength = 0;\n\t\t\t} else {\n\t\t\t\t\/\/ Trim left and right\n\t\t\t\tinput.erase( 0, input.find_first_not_of( ' ' ) );\n\t\t\t\tinput.erase( input.find_last_not_of( ' ' ) + 1 );\n\n\t\t\t\tif ( references.size() == 1 )\n\t\t\t\t\tset_reference( input, references[ 0 ] );\n\t\t\t\telse\n\t\t\t\t\tfor ( i = 0, inputParts = splitstr( input, separator ); i < references.size(); i++ )\n\t\t\t\t\t\tif ( i < inputParts.size() )\n\t\t\t\t\t\t\tset_reference( inputParts[ i ], references[ i ] );\n\n\t\t\t\tstd::cout << std::endl;\n\n\t\t\t\twaiting_input = false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ BACKSPACE\n\t\telse if ( key == 8 && inputLength ) {\n\t\t\tget_cursor_position();\n\t\t\tcursor_pos_x = cursor_position[ 0 ];\n\n\t\t\tif ( cursor_pos_x == ( request_msg.size() + input.size() - 1 ) && inputLength == 1 )\n\t\t\t\tcontinue;\n\n\t\t\tstd::cout << \"\\b \\b\";\n\t\t\tinput.erase( cursor_pos_x - request_msg.size() - 1, 1 );\n\t\t\tinputLength--;\n\n\t\t\t\/\/ If the cursor isn't at the end\n\t\t\tif ( cursor_pos_x <= ( request_msg.size() + input.size() ) ) {\n\t\t\t\t\/\/ Put the cursor at the start and rewrites the input\n\t\t\t\tset_cursor_position( static_cast< short >( request_msg.size() ) );\n\t\t\t\tstd::cout << ( is_password ? std::string( input.size(), '*' ) : input );\n\n\t\t\t\t\/\/ Put the cursor at the end and erase the last char\n\t\t\t\tset_cursor_position( static_cast< short >( request_msg.size() + input.size() + 1 ) );\n\t\t\t\tstd::cout << \"\\b \\b\";\n\n\t\t\t\t\/\/ Put the cursor at the original position\n\t\t\t\tset_cursor_position( static_cast< short >( cursor_pos_x - 1 ) );\n\t\t\t}\n\t\t}\n\n\t\tarrow = false;\n\t}\n\n\t\/\/ Reset to default values\n\tinstant_verify = instant_verify_default;\n\tis_password = is_password_default;\n\tclear_input = clear_input_default;\n\tseparator = separator_default;\n\tinput_max_size = input_max_size_default;\n};\n\ntemplate< typename T >\nKeybdInput< T >::KeybdInput( bool _instant_verify, bool _is_password, bool _clear_input, std::string _separator, size_t _input_max_size ) {\n\tinstant_verify = instant_verify_default = _instant_verify;\n\tis_password = is_password_default = _is_password;\n\tclear_input = clear_input_default = _clear_input;\n\tseparator = separator_default = _separator;\n\tinput_max_size = input_max_size_default = _input_max_size;\n};<|endoftext|>"} {"text":"\/**\n@copyright MIT license; see @ref index or the accompanying LICENSE file.\n*\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace Onsang {\nnamespace UI {\n\nvoid\nCommandStatusLine::set_input_control_impl(\n\tbool const enabled\n) noexcept {\n\tbase::set_input_control_impl(enabled);\n\tif (!has_input_control()) {\n\t\tauto prev_focus = m_prev_focus.lock();\n\t\tget_root()->set_focus(prev_focus);\n\t\tm_prev_focus.reset();\n\t}\n\tm_field.input_control_changed(*this);\n\tqueue_actions(\n\t\tui::UpdateActions::render |\n\t\tui::UpdateActions::flag_noclear\n\t);\n}\n\nvoid\nCommandStatusLine::reflow_impl(\n\tRect const& area,\n\tbool const cache\n) noexcept {\n\tbase::reflow_impl(area, cache);\n\tif (has_input_control()) {\n\t\tm_field.reflow(area);\n\t}\n}\n\nbool\nCommandStatusLine::handle_event_impl(\n\tUI::Event const& event\n) noexcept {\n\tif (event.type != UI::EventType::key_input) {\n\t\treturn false;\n\t}\n\tswitch (event.type) {\n\tcase UI::EventType::key_input:\n\t\tif (!has_input_control()) {\n\t\t\tbreak;\n\t\t}\n\t\tif (event.key_input.code == KeyCode::enter) {\n\t\t\tif (!m_field.m_text_tree.empty()) {\n\t\t\t\t\/\/ TODO\n\t\t\t\t\/\/String const string_value = m_field.m_cursor.get_node().to_string();\n\t\t\t}\n\t\t\tm_field.m_cursor.clear();\n\t\t\tset_input_control(false);\n\t\t\treturn true;\n\t\t} else if (event.key_input.code == KeyCode::esc) {\n\t\t\tm_field.m_cursor.clear();\n\t\t\tset_input_control(false);\n\t\t\treturn true;\n\t\t} else {\n\t\t\tbool view_modified = true;\n\t\t\tswitch (event.key_input.code) {\n\t\t\t\/\/case KeyCode::up : \/* TODO *\/ break;\n\t\t\t\/\/case KeyCode::down : \/* TODO *\/ break;\n\t\t\tcase KeyCode::left : m_field.m_cursor.col_prev(); break;\n\t\t\tcase KeyCode::right: m_field.m_cursor.col_next(); break;\n\t\t\tcase KeyCode::home: m_field.m_cursor.col_extent(txt::Extent::head); break;\n\t\t\tcase KeyCode::end : m_field.m_cursor.col_extent(txt::Extent::tail); break;\n\t\t\tcase KeyCode::del : m_field.m_cursor.erase(); break;\n\t\t\tcase KeyCode::backspace: m_field.m_cursor.erase_before(); break;\n\t\t\tdefault:\n\t\t\t\tif (\n\t\t\t\t\tevent.key_input.cp != codepoint_none &&\n\t\t\t\t\tevent.key_input.cp != '\\t'\n\t\t\t\t) {\n\t\t\t\t\tm_field.m_cursor.insert_step(event.key_input.cp);\n\t\t\t\t} else {\n\t\t\t\t\tview_modified = false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (view_modified) {\n\t\t\t\tm_field.update_view();\n\t\t\t\tqueue_actions(\n\t\t\t\t\tui::UpdateActions::render |\n\t\t\t\t\tui::UpdateActions::flag_noclear\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n\treturn false;\n}\n\nvoid\nCommandStatusLine::render_impl(\n\tUI::Widget::RenderData& rd\n) noexcept {\n\tauto const& frame = get_geometry().get_frame();\n\tif (!has_input_control()) {\n\t\t\/\/ render message & location\n\t\ttty::attr_type const\n\t\t\tprimary_fg = rd.get_attr(ui::property_primary_fg_inactive),\n\t\t\tprimary_bg = rd.get_attr(ui::property_primary_bg_inactive),\n\t\t\tcontent_fg = rd.get_attr(ui::property_content_fg_inactive),\n\t\t\tcontent_bg = rd.get_attr(ui::property_content_bg_inactive)\n\t\t;\n\t\tauto const cell_clear = tty::make_cell(' ', primary_fg, primary_bg);\n\t\trd.terminal.put_line(frame.pos, frame.size.width, Axis::horizontal, cell_clear);\n\t\tgeom_value_type const location_pos = max_ce(\n\t\t\t0, frame.size.width - static_cast(m_location.size())\n\t\t);\n\t\trd.terminal.put_sequence(\n\t\t\tframe.pos.x + location_pos,\n\t\t\tframe.pos.y,\n\t\t\t{m_location},\n\t\t\tframe.size.width - location_pos,\n\t\t\tcontent_fg,\n\t\t\tcontent_bg\n\t\t);\n\t\trd.terminal.put_sequence(\n\t\t\tframe.pos.x,\n\t\t\tframe.pos.y,\n\t\t\t{m_message},\n\t\t\tframe.size.width,\n\t\t\t(m_message_type == MessageType::error)\n\t\t\t? (tty::Color::white | tty::Attr::bold)\n\t\t\t: content_fg,\n\t\t\t(m_message_type == MessageType::error)\n\t\t\t? tty::Color::red\n\t\t\t: content_bg\n\t\t);\n\t} else {\n\t\t\/\/ render field\n\t\trd.update_group(UI::group_field);\n\t\tm_field.render(rd, true);\n\t}\n}\n\nvoid\nCommandStatusLine::set_message(\n\tUI::CommandStatusLine::MessageType type,\n\tString&& text\n) {\n\tm_message_type = type;\n\tm_message = std::move(text);\n\tqueue_actions(\n\t\tui::UpdateActions::render |\n\t\tui::UpdateActions::flag_noclear\n\t);\n}\n\nvoid\nCommandStatusLine::set_location(\n\tString text\n) {\n\tm_location = std::move(text);\n\tqueue_actions(\n\t\tui::UpdateActions::render |\n\t\tui::UpdateActions::flag_noclear\n\t);\n}\n\nvoid\nCommandStatusLine::prompt_command() {\n\tm_field.reflow(get_geometry().get_area());\n\tset_input_control(true);\n\tm_prev_focus = get_root()->get_focus();\n\tget_root()->set_focus(shared_from_this());\n}\n\n} \/\/ namespace UI\n} \/\/ namespace Onsang\nUI\/CommandStatusLine: use BareField::input().\/**\n@copyright MIT license; see @ref index or the accompanying LICENSE file.\n*\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace Onsang {\nnamespace UI {\n\nvoid\nCommandStatusLine::set_input_control_impl(\n\tbool const enabled\n) noexcept {\n\tbase::set_input_control_impl(enabled);\n\tif (!has_input_control()) {\n\t\tauto prev_focus = m_prev_focus.lock();\n\t\tget_root()->set_focus(prev_focus);\n\t\tm_prev_focus.reset();\n\t}\n\tm_field.input_control_changed(*this);\n\tqueue_actions(\n\t\tui::UpdateActions::render |\n\t\tui::UpdateActions::flag_noclear\n\t);\n}\n\nvoid\nCommandStatusLine::reflow_impl(\n\tRect const& area,\n\tbool const cache\n) noexcept {\n\tbase::reflow_impl(area, cache);\n\tif (has_input_control()) {\n\t\tm_field.reflow(area);\n\t}\n}\n\nbool\nCommandStatusLine::handle_event_impl(\n\tUI::Event const& event\n) noexcept {\n\tif (event.type != UI::EventType::key_input) {\n\t\treturn false;\n\t}\n\tswitch (event.type) {\n\tcase UI::EventType::key_input:\n\t\tif (!has_input_control()) {\n\t\t\tbreak;\n\t\t}\n\t\tif (event.key_input.code == KeyCode::enter) {\n\t\t\tif (!m_field.m_text_tree.empty()) {\n\t\t\t\t\/\/ TODO\n\t\t\t\t\/\/String const string_value = m_field.m_cursor.get_node().to_string();\n\t\t\t}\n\t\t\tm_field.m_cursor.clear();\n\t\t\tset_input_control(false);\n\t\t\treturn true;\n\t\t} else if (event.key_input.code == KeyCode::esc) {\n\t\t\tm_field.m_cursor.clear();\n\t\t\tset_input_control(false);\n\t\t\treturn true;\n\t\t} else {\n\t\t\t\/\/ TODO: Command history\n\t\t\tif (m_field.input(event.key_input)) {\n\t\t\t\tqueue_actions(\n\t\t\t\t\tui::UpdateActions::render |\n\t\t\t\t\tui::UpdateActions::flag_noclear\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n\treturn false;\n}\n\nvoid\nCommandStatusLine::render_impl(\n\tUI::Widget::RenderData& rd\n) noexcept {\n\tauto const& frame = get_geometry().get_frame();\n\tif (!has_input_control()) {\n\t\t\/\/ render message & location\n\t\ttty::attr_type const\n\t\t\tprimary_fg = rd.get_attr(ui::property_primary_fg_inactive),\n\t\t\tprimary_bg = rd.get_attr(ui::property_primary_bg_inactive),\n\t\t\tcontent_fg = rd.get_attr(ui::property_content_fg_inactive),\n\t\t\tcontent_bg = rd.get_attr(ui::property_content_bg_inactive)\n\t\t;\n\t\tauto const cell_clear = tty::make_cell(' ', primary_fg, primary_bg);\n\t\trd.terminal.put_line(frame.pos, frame.size.width, Axis::horizontal, cell_clear);\n\t\tgeom_value_type const location_pos = max_ce(\n\t\t\t0, frame.size.width - static_cast(m_location.size())\n\t\t);\n\t\trd.terminal.put_sequence(\n\t\t\tframe.pos.x + location_pos,\n\t\t\tframe.pos.y,\n\t\t\t{m_location},\n\t\t\tframe.size.width - location_pos,\n\t\t\tcontent_fg,\n\t\t\tcontent_bg\n\t\t);\n\t\trd.terminal.put_sequence(\n\t\t\tframe.pos.x,\n\t\t\tframe.pos.y,\n\t\t\t{m_message},\n\t\t\tframe.size.width,\n\t\t\t(m_message_type == MessageType::error)\n\t\t\t? (tty::Color::white | tty::Attr::bold)\n\t\t\t: content_fg,\n\t\t\t(m_message_type == MessageType::error)\n\t\t\t? tty::Color::red\n\t\t\t: content_bg\n\t\t);\n\t} else {\n\t\t\/\/ render field\n\t\trd.update_group(UI::group_field);\n\t\tm_field.render(rd, true);\n\t}\n}\n\nvoid\nCommandStatusLine::set_message(\n\tUI::CommandStatusLine::MessageType type,\n\tString&& text\n) {\n\tm_message_type = type;\n\tm_message = std::move(text);\n\tqueue_actions(\n\t\tui::UpdateActions::render |\n\t\tui::UpdateActions::flag_noclear\n\t);\n}\n\nvoid\nCommandStatusLine::set_location(\n\tString text\n) {\n\tm_location = std::move(text);\n\tqueue_actions(\n\t\tui::UpdateActions::render |\n\t\tui::UpdateActions::flag_noclear\n\t);\n}\n\nvoid\nCommandStatusLine::prompt_command() {\n\tm_field.reflow(get_geometry().get_area());\n\tset_input_control(true);\n\tm_prev_focus = get_root()->get_focus();\n\tget_root()->set_focus(shared_from_this());\n}\n\n} \/\/ namespace UI\n} \/\/ namespace Onsang\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2019 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \n#include \"vm.hh\"\n#include \"compiler.hh\"\n#include \"primitives.hh\"\n\nnamespace wrencc {\n\n#define DEF_PRIMITIVE(fn)\\\nstatic Value _primitive_##fn(VM& vm, Fiber& fiber, Value* args)\n\nDEF_PRIMITIVE(fn_call) {\n vm.call_function(fiber, args[0]->as_function(), 1);\n return nullptr;\n}\n\nDEF_PRIMITIVE(bool_eq) {\n if (!args[1]->is_boolean())\n return BooleanObject::make_boolean(false);\n\n return BooleanObject::make_boolean(\n args[0]->as_boolean() == args[1]->as_boolean());\n}\n\nDEF_PRIMITIVE(bool_ne) {\n if (!args[1]->is_boolean())\n return BooleanObject::make_boolean(true);\n\n return BooleanObject::make_boolean(\n args[0]->as_boolean() != args[1]->as_boolean());\n}\n\nDEF_PRIMITIVE(bool_tostring) {\n if (args[0]->as_boolean()) {\n char* s = new char[5];\n memcpy(s, \"true\", 4);\n s[4] = 0;\n return StringObject::make_string(s);\n }\n else {\n char* s = new char[6];\n memcpy(s, \"false\", 5);\n s[5] = 0;\n return StringObject::make_string(s);\n }\n}\n\nDEF_PRIMITIVE(numeric_abs) {\n double d = args[0]->as_numeric();\n if (d < 0)\n d = -d;\n else if (d == 0)\n d = 0;\n return NumericObject::make_numeric(d);\n}\n\nDEF_PRIMITIVE(numeric_tostring) {\n std::stringstream ss;\n ss << args[0]->as_numeric();\n str_t temp(ss.str());\n\n char* s = new char [temp.size() + 1];\n memcpy(s, temp.data(), temp.size());\n s[temp.size()] = 0;\n\n return StringObject::make_string(s);\n}\n\nDEF_PRIMITIVE(numeric_add) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n\n return NumericObject::make_numeric(\n args[0]->as_numeric() + args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_sub) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n\n return NumericObject::make_numeric(\n args[0]->as_numeric() - args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_mul) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n\n return NumericObject::make_numeric(\n args[0]->as_numeric() * args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_div) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n\n return NumericObject::make_numeric(\n args[0]->as_numeric() \/ args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_gt) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n return BooleanObject::make_boolean(\n args[0]->as_numeric() > args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_ge) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n return BooleanObject::make_boolean(\n args[0]->as_numeric() >= args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_lt) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n return BooleanObject::make_boolean(\n args[0]->as_numeric() < args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_le) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n return BooleanObject::make_boolean(\n args[0]->as_numeric() <= args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_eq) {\n if (!args[1]->is_numeric())\n return BooleanObject::make_boolean(false);\n\n return BooleanObject::make_boolean(\n args[0]->as_numeric() == args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_ne) {\n if (!args[1]->is_numeric())\n return BooleanObject::make_boolean(true);\n\n return BooleanObject::make_boolean(\n args[0]->as_numeric() != args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(string_len) {\n return NumericObject::make_numeric(args[0]->as_string()->size());\n}\n\nDEF_PRIMITIVE(string_contains) {\n StringObject* orig = args[0]->as_string();\n StringObject* subs = args[1]->as_string();\n\n if (orig->size() == 0 && subs->size() == 0)\n return NumericObject::make_numeric(1);\n return NumericObject::make_numeric(strstr(orig->cstr(), subs->cstr()) != 0);\n}\n\nDEF_PRIMITIVE(string_tostring) {\n return args[0];\n}\n\nDEF_PRIMITIVE(string_add) {\n if (!args[1]->is_string())\n return vm.unsupported();\n\n StringObject* lhs = args[0]->as_string();\n StringObject* rhs = args[1]->as_string();\n\n int n = lhs->size() + rhs->size();\n char* s = new char[Xt::as_type(n) + 1];\n memcpy(s, lhs->cstr(), lhs->size());\n memcpy(s + lhs->size(), rhs->cstr(), rhs->size());\n s[n] = 0;\n\n return StringObject::make_string(s);\n}\n\nDEF_PRIMITIVE(string_eq) {\n if (!args[1]->is_string())\n return BooleanObject::make_boolean(false);\n\n auto r = strcmp(args[0]->as_cstring(), args[1]->as_cstring()) == 0;\n return BooleanObject::make_boolean(r);\n}\n\nDEF_PRIMITIVE(string_ne) {\n if (!args[1]->is_string())\n return BooleanObject::make_boolean(true);\n\n auto r = strcmp(args[0]->as_cstring(), args[1]->as_cstring()) != 0;\n return BooleanObject::make_boolean(r);\n}\n\nDEF_PRIMITIVE(fn_eq) {\n if (!args[1]->is_function())\n return BooleanObject::make_boolean(false);\n\n return BooleanObject::make_boolean(args[0] == args[1]);\n}\n\nDEF_PRIMITIVE(fn_ne) {\n if (!args[1]->is_function())\n return BooleanObject::make_boolean(true);\n\n return BooleanObject::make_boolean(args[0] != args[1]);\n}\n\nDEF_PRIMITIVE(io_write) {\n std::cout << args[1] << std::endl;\n return args[1];\n}\n\nstatic constexpr const char* kCoreLib =\n\"class Nil {}\\n\"\n\"class Bool {}\\n\"\n\"class Numeric {}\\n\"\n\"class String {}\\n\"\n\"class Function {}\\n\"\n\"class Class {}\\n\"\n\"class IO {}\\n\"\n\"var io = IO.new\\n\";\n\nvoid load_core(VM& vm) {\n vm.interpret(kCoreLib);\n\n vm.set_bool_cls(vm.get_global(\"Bool\")->as_class());\n vm.set_primitive(vm.bool_cls(), \"toString\", _primitive_bool_tostring);\n vm.set_primitive(vm.bool_cls(), \"== \", _primitive_bool_eq);\n vm.set_primitive(vm.bool_cls(), \"!= \", _primitive_bool_ne);\n\n vm.set_class_cls(vm.get_global(\"Class\")->as_class());\n\n vm.set_fn_cls(vm.get_global(\"Function\")->as_class());\n vm.set_primitive(vm.fn_cls(), \"call\", _primitive_fn_call);\n vm.set_primitive(vm.fn_cls(), \"== \", _primitive_fn_eq);\n vm.set_primitive(vm.fn_cls(), \"!= \", _primitive_fn_ne);\n\n vm.set_nil_cls(vm.get_global(\"Nil\")->as_class());\n\n vm.set_num_cls(vm.get_global(\"Numeric\")->as_class());\n vm.set_primitive(vm.num_cls(), \"abs\", _primitive_numeric_abs);\n vm.set_primitive(vm.num_cls(), \"toString\", _primitive_numeric_tostring);\n vm.set_primitive(vm.num_cls(), \"+ \", _primitive_numeric_add);\n vm.set_primitive(vm.num_cls(), \"- \", _primitive_numeric_sub);\n vm.set_primitive(vm.num_cls(), \"* \", _primitive_numeric_mul);\n vm.set_primitive(vm.num_cls(), \"\/ \", _primitive_numeric_div);\n vm.set_primitive(vm.num_cls(), \"> \", _primitive_numeric_gt);\n vm.set_primitive(vm.num_cls(), \">= \", _primitive_numeric_ge);\n vm.set_primitive(vm.num_cls(), \"< \", _primitive_numeric_lt);\n vm.set_primitive(vm.num_cls(), \"<= \", _primitive_numeric_le);\n vm.set_primitive(vm.num_cls(), \"== \", _primitive_numeric_eq);\n vm.set_primitive(vm.num_cls(), \"!= \", _primitive_numeric_ne);\n\n vm.set_str_cls(vm.get_global(\"String\")->as_class());\n vm.set_primitive(vm.str_cls(), \"len\", _primitive_string_len);\n vm.set_primitive(vm.str_cls(), \"contains \", _primitive_string_contains);\n vm.set_primitive(vm.str_cls(), \"toString\", _primitive_string_tostring);\n vm.set_primitive(vm.str_cls(), \"+ \", _primitive_string_add);\n vm.set_primitive(vm.str_cls(), \"== \", _primitive_string_eq);\n vm.set_primitive(vm.str_cls(), \"!= \", _primitive_string_ne);\n\n ClassObject* io_cls = vm.get_global(\"IO\")->as_class();\n vm.set_primitive(io_cls, \"write \", _primitive_io_write);\n\n ClassObject* unsupported_cls = ClassObject::make_class();\n vm.set_unsupported(InstanceObject::make_instance(unsupported_cls));\n}\n\n}\n:construction: chore(%): add % operators support\/\/ Copyright (c) 2019 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \n#include \n#include \"vm.hh\"\n#include \"compiler.hh\"\n#include \"primitives.hh\"\n\nnamespace wrencc {\n\n#define DEF_PRIMITIVE(fn)\\\nstatic Value _primitive_##fn(VM& vm, Fiber& fiber, Value* args)\n\nDEF_PRIMITIVE(fn_call) {\n vm.call_function(fiber, args[0]->as_function(), 1);\n return nullptr;\n}\n\nDEF_PRIMITIVE(bool_eq) {\n if (!args[1]->is_boolean())\n return BooleanObject::make_boolean(false);\n\n return BooleanObject::make_boolean(\n args[0]->as_boolean() == args[1]->as_boolean());\n}\n\nDEF_PRIMITIVE(bool_ne) {\n if (!args[1]->is_boolean())\n return BooleanObject::make_boolean(true);\n\n return BooleanObject::make_boolean(\n args[0]->as_boolean() != args[1]->as_boolean());\n}\n\nDEF_PRIMITIVE(bool_tostring) {\n if (args[0]->as_boolean()) {\n char* s = new char[5];\n memcpy(s, \"true\", 4);\n s[4] = 0;\n return StringObject::make_string(s);\n }\n else {\n char* s = new char[6];\n memcpy(s, \"false\", 5);\n s[5] = 0;\n return StringObject::make_string(s);\n }\n}\n\nDEF_PRIMITIVE(numeric_abs) {\n double d = args[0]->as_numeric();\n if (d < 0)\n d = -d;\n else if (d == 0)\n d = 0;\n return NumericObject::make_numeric(d);\n}\n\nDEF_PRIMITIVE(numeric_tostring) {\n std::stringstream ss;\n ss << args[0]->as_numeric();\n str_t temp(ss.str());\n\n char* s = new char [temp.size() + 1];\n memcpy(s, temp.data(), temp.size());\n s[temp.size()] = 0;\n\n return StringObject::make_string(s);\n}\n\nDEF_PRIMITIVE(numeric_add) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n\n return NumericObject::make_numeric(\n args[0]->as_numeric() + args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_sub) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n\n return NumericObject::make_numeric(\n args[0]->as_numeric() - args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_mul) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n\n return NumericObject::make_numeric(\n args[0]->as_numeric() * args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_div) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n\n return NumericObject::make_numeric(\n args[0]->as_numeric() \/ args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_mod) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n\n return NumericObject::make_numeric(\n std::fmod(args[0]->as_numeric(), args[1]->as_numeric()));\n}\n\nDEF_PRIMITIVE(numeric_gt) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n return BooleanObject::make_boolean(\n args[0]->as_numeric() > args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_ge) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n return BooleanObject::make_boolean(\n args[0]->as_numeric() >= args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_lt) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n return BooleanObject::make_boolean(\n args[0]->as_numeric() < args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_le) {\n if (!args[1]->is_numeric())\n return vm.unsupported();\n return BooleanObject::make_boolean(\n args[0]->as_numeric() <= args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_eq) {\n if (!args[1]->is_numeric())\n return BooleanObject::make_boolean(false);\n\n return BooleanObject::make_boolean(\n args[0]->as_numeric() == args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(numeric_ne) {\n if (!args[1]->is_numeric())\n return BooleanObject::make_boolean(true);\n\n return BooleanObject::make_boolean(\n args[0]->as_numeric() != args[1]->as_numeric());\n}\n\nDEF_PRIMITIVE(string_len) {\n return NumericObject::make_numeric(args[0]->as_string()->size());\n}\n\nDEF_PRIMITIVE(string_contains) {\n StringObject* orig = args[0]->as_string();\n StringObject* subs = args[1]->as_string();\n\n if (orig->size() == 0 && subs->size() == 0)\n return NumericObject::make_numeric(1);\n return NumericObject::make_numeric(strstr(orig->cstr(), subs->cstr()) != 0);\n}\n\nDEF_PRIMITIVE(string_tostring) {\n return args[0];\n}\n\nDEF_PRIMITIVE(string_add) {\n if (!args[1]->is_string())\n return vm.unsupported();\n\n StringObject* lhs = args[0]->as_string();\n StringObject* rhs = args[1]->as_string();\n\n int n = lhs->size() + rhs->size();\n char* s = new char[Xt::as_type(n) + 1];\n memcpy(s, lhs->cstr(), lhs->size());\n memcpy(s + lhs->size(), rhs->cstr(), rhs->size());\n s[n] = 0;\n\n return StringObject::make_string(s);\n}\n\nDEF_PRIMITIVE(string_eq) {\n if (!args[1]->is_string())\n return BooleanObject::make_boolean(false);\n\n auto r = strcmp(args[0]->as_cstring(), args[1]->as_cstring()) == 0;\n return BooleanObject::make_boolean(r);\n}\n\nDEF_PRIMITIVE(string_ne) {\n if (!args[1]->is_string())\n return BooleanObject::make_boolean(true);\n\n auto r = strcmp(args[0]->as_cstring(), args[1]->as_cstring()) != 0;\n return BooleanObject::make_boolean(r);\n}\n\nDEF_PRIMITIVE(fn_eq) {\n if (!args[1]->is_function())\n return BooleanObject::make_boolean(false);\n\n return BooleanObject::make_boolean(args[0] == args[1]);\n}\n\nDEF_PRIMITIVE(fn_ne) {\n if (!args[1]->is_function())\n return BooleanObject::make_boolean(true);\n\n return BooleanObject::make_boolean(args[0] != args[1]);\n}\n\nDEF_PRIMITIVE(io_write) {\n std::cout << args[1] << std::endl;\n return args[1];\n}\n\nstatic constexpr const char* kCoreLib =\n\"class Nil {}\\n\"\n\"class Bool {}\\n\"\n\"class Numeric {}\\n\"\n\"class String {}\\n\"\n\"class Function {}\\n\"\n\"class Class {}\\n\"\n\"class IO {}\\n\"\n\"var io = IO.new\\n\";\n\nvoid load_core(VM& vm) {\n vm.interpret(kCoreLib);\n\n vm.set_bool_cls(vm.get_global(\"Bool\")->as_class());\n vm.set_primitive(vm.bool_cls(), \"toString\", _primitive_bool_tostring);\n vm.set_primitive(vm.bool_cls(), \"== \", _primitive_bool_eq);\n vm.set_primitive(vm.bool_cls(), \"!= \", _primitive_bool_ne);\n\n vm.set_class_cls(vm.get_global(\"Class\")->as_class());\n\n vm.set_fn_cls(vm.get_global(\"Function\")->as_class());\n vm.set_primitive(vm.fn_cls(), \"call\", _primitive_fn_call);\n vm.set_primitive(vm.fn_cls(), \"== \", _primitive_fn_eq);\n vm.set_primitive(vm.fn_cls(), \"!= \", _primitive_fn_ne);\n\n vm.set_nil_cls(vm.get_global(\"Nil\")->as_class());\n\n vm.set_num_cls(vm.get_global(\"Numeric\")->as_class());\n vm.set_primitive(vm.num_cls(), \"abs\", _primitive_numeric_abs);\n vm.set_primitive(vm.num_cls(), \"toString\", _primitive_numeric_tostring);\n vm.set_primitive(vm.num_cls(), \"+ \", _primitive_numeric_add);\n vm.set_primitive(vm.num_cls(), \"- \", _primitive_numeric_sub);\n vm.set_primitive(vm.num_cls(), \"* \", _primitive_numeric_mul);\n vm.set_primitive(vm.num_cls(), \"\/ \", _primitive_numeric_div);\n vm.set_primitive(vm.num_cls(), \"% \", _primitive_numeric_mod);\n vm.set_primitive(vm.num_cls(), \"> \", _primitive_numeric_gt);\n vm.set_primitive(vm.num_cls(), \">= \", _primitive_numeric_ge);\n vm.set_primitive(vm.num_cls(), \"< \", _primitive_numeric_lt);\n vm.set_primitive(vm.num_cls(), \"<= \", _primitive_numeric_le);\n vm.set_primitive(vm.num_cls(), \"== \", _primitive_numeric_eq);\n vm.set_primitive(vm.num_cls(), \"!= \", _primitive_numeric_ne);\n\n vm.set_str_cls(vm.get_global(\"String\")->as_class());\n vm.set_primitive(vm.str_cls(), \"len\", _primitive_string_len);\n vm.set_primitive(vm.str_cls(), \"contains \", _primitive_string_contains);\n vm.set_primitive(vm.str_cls(), \"toString\", _primitive_string_tostring);\n vm.set_primitive(vm.str_cls(), \"+ \", _primitive_string_add);\n vm.set_primitive(vm.str_cls(), \"== \", _primitive_string_eq);\n vm.set_primitive(vm.str_cls(), \"!= \", _primitive_string_ne);\n\n ClassObject* io_cls = vm.get_global(\"IO\")->as_class();\n vm.set_primitive(io_cls, \"write \", _primitive_io_write);\n\n ClassObject* unsupported_cls = ClassObject::make_class();\n vm.set_unsupported(InstanceObject::make_instance(unsupported_cls));\n}\n\n}\n<|endoftext|>"} {"text":"\/** \\file delete_unused_local_data.cc\n * \\author Oliver Obenland\n *\n * Local data blocks are embedded marc records inside of a record using LOK-Fields.\n * Each local data block belongs to an institution and are marked by the institution's sigil.\n * This tool filters for local data blocks of some institutions of the University of Tübingen\n * and deletes all other local blocks.\n *\/\n\n\/*\n Copyright (C) 2016, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see .\n*\/\n\n#include \n#include \"MarcUtil.h\"\n#include \"RegexMatcher.h\"\n#include \"util.h\"\n#include \"XmlWriter.h\"\n\n\nstatic ssize_t count(0), before_count(0), after_count(0), no_local_data_records_count(0);\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << ::progname << \" marc_input marc_output\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nbool IsUnusedLocalBlock(const MarcUtil::Record * const record, const std::pair &block_start_and_end) {\n static RegexMatcher *matcher(nullptr);\n std::string err_msg;\n if (unlikely(matcher == nullptr)) {\n matcher = RegexMatcher::RegexMatcherFactory(\"^.*aDE-21.*$|^.*aDE-21-24.*$|^.*aDE-21-110.*$\", &err_msg);\n if (matcher == nullptr)\n Error(err_msg);\n }\n\n std::string err_msg;\n std::vector field_indices;\n record->findFieldsInLocalBlock(\"852\", \"??\", block_start_and_end, &field_indices);\n\n const std::vector &fields(record->getFields());\n for (const auto field_index : field_indices) {\n const bool matched = matcher->matched(fields[field_index], &err_msg);\n if (not matched and not err_msg.empty())\n Error(\"Unexpected error while trying to match a field in CompiledPattern::fieldMatched(): \" + err_msg);\n if (matched) {\n return false;\n }\n }\n return true;\n}\n\n\nvoid DeleteLocalBlock(MarcUtil::Record * const record, const std::pair &block_start_and_end) {\n for (size_t field_index(block_start_and_end.second - 1); field_index >= block_start_and_end.first; --field_index)\n record->deleteField(field_index);\n}\n\n\nbool ProcessRecord(MarcUtil::Record * const record) {\n std::vector> local_block_boundaries;\n ssize_t local_data_count = record->findAllLocalDataBlocks(&local_block_boundaries);\n std::reverse(local_block_boundaries.begin(), local_block_boundaries.end());\n\n before_count += local_data_count;\n for (const std::pair &block_start_and_end : local_block_boundaries) {\n if (IsUnusedLocalBlock(record, block_start_and_end)) {\n DeleteLocalBlock(record, block_start_and_end);\n --local_data_count;\n }\n }\n\n after_count += local_data_count;\n return local_data_count != 0;\n}\n\n\nvoid DeleteUnusedLocalData(File * const input, File * const output) {\n XmlWriter xml_writer(output);\n xml_writer.openTag(\"marc:collection\",\n { std::make_pair(\"xmlns:marc\", \"http:\/\/www.loc.gov\/MARC21\/slim\"),\n std::make_pair(\"xmlns:xsi\", \"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"),\n std::make_pair(\"xsi:schemaLocation\", \"http:\/\/www.loc.gov\/standards\/marcxml\/schema\/MARC21slim.xsd\")});\n\n while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(input)) {\n ++count;\n record.setRecordWillBeWrittenAsXml(true);\n ProcessRecord(&record);\n record.write(&xml_writer);\n }\n\n xml_writer.closeTag();\n\n std::cerr << ::progname << \": Deleted \" << (before_count - after_count) << \" of \" << before_count << \" local data blocks.\\n\";\n std::cerr << ::progname << \": Deleted \" << no_local_data_records_count << \" of \" << count << \"records without local data.\\n\";\n}\n\n\nint main(int argc, char **argv) {\n ::progname = argv[0];\n\n if (argc != 3)\n Usage();\n\n const std::string input_filename(argv[1]);\n File input(input_filename, \"r\");\n if (not input)\n Error(\"can't open \\\"\" + input_filename + \"\\\" for reading!\");\n\n const std::string output_filename(argv[2]);\n File output(output_filename, \"w\");\n if (not output)\n Error(\"can't open \\\"\" + output_filename + \"\\\" for writing!\");\n\n try {\n DeleteUnusedLocalData(&input, &output);\n } catch (const std::exception &x) {\n Error(\"caught exception: \" + std::string(x.what()));\n }\n}\nUpdate delete_unused_local_data.cc\/** \\file delete_unused_local_data.cc\n * \\author Oliver Obenland\n *\n * Local data blocks are embedded marc records inside of a record using LOK-Fields.\n * Each local data block belongs to an institution and is marked by the institution's sigil.\n * This tool filters for local data blocks of some institutions of the University of Tübingen\n * and deletes all other local blocks.\n *\/\n\n\/*\n Copyright (C) 2016, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see .\n*\/\n\n#include \n#include \"MarcUtil.h\"\n#include \"RegexMatcher.h\"\n#include \"util.h\"\n#include \"XmlWriter.h\"\n\n\nstatic ssize_t count(0), before_count(0), after_count(0), no_local_data_records_count(0);\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << ::progname << \" marc_input marc_output\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nbool IsUnusedLocalBlock(const MarcUtil::Record * const record, const std::pair &block_start_and_end) {\n static RegexMatcher *matcher(nullptr);\n std::string err_msg;\n if (unlikely(matcher == nullptr)) {\n matcher = RegexMatcher::RegexMatcherFactory(\"^.*aDE-21.*$|^.*aDE-21-24.*$|^.*aDE-21-110.*$\", &err_msg);\n if (matcher == nullptr)\n Error(err_msg);\n }\n\n std::string err_msg;\n std::vector field_indices;\n record->findFieldsInLocalBlock(\"852\", \"??\", block_start_and_end, &field_indices);\n\n const std::vector &fields(record->getFields());\n for (const auto field_index : field_indices) {\n const bool matched = matcher->matched(fields[field_index], &err_msg);\n if (not matched and not err_msg.empty())\n Error(\"Unexpected error while trying to match a field in CompiledPattern::fieldMatched(): \" + err_msg);\n if (matched) {\n return false;\n }\n }\n return true;\n}\n\n\nvoid DeleteLocalBlock(MarcUtil::Record * const record, const std::pair &block_start_and_end) {\n for (size_t field_index(block_start_and_end.second - 1); field_index >= block_start_and_end.first; --field_index)\n record->deleteField(field_index);\n}\n\n\nbool ProcessRecord(MarcUtil::Record * const record) {\n std::vector> local_block_boundaries;\n ssize_t local_data_count = record->findAllLocalDataBlocks(&local_block_boundaries);\n std::reverse(local_block_boundaries.begin(), local_block_boundaries.end());\n\n before_count += local_data_count;\n for (const std::pair &block_start_and_end : local_block_boundaries) {\n if (IsUnusedLocalBlock(record, block_start_and_end)) {\n DeleteLocalBlock(record, block_start_and_end);\n --local_data_count;\n }\n }\n\n after_count += local_data_count;\n return local_data_count != 0;\n}\n\n\nvoid DeleteUnusedLocalData(File * const input, File * const output) {\n XmlWriter xml_writer(output);\n xml_writer.openTag(\"marc:collection\",\n { std::make_pair(\"xmlns:marc\", \"http:\/\/www.loc.gov\/MARC21\/slim\"),\n std::make_pair(\"xmlns:xsi\", \"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"),\n std::make_pair(\"xsi:schemaLocation\", \"http:\/\/www.loc.gov\/standards\/marcxml\/schema\/MARC21slim.xsd\")});\n\n while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(input)) {\n ++count;\n record.setRecordWillBeWrittenAsXml(true);\n ProcessRecord(&record);\n record.write(&xml_writer);\n }\n\n xml_writer.closeTag();\n\n std::cerr << ::progname << \": Deleted \" << (before_count - after_count) << \" of \" << before_count << \" local data blocks.\\n\";\n std::cerr << ::progname << \": Deleted \" << no_local_data_records_count << \" of \" << count << \"records without local data.\\n\";\n}\n\n\nint main(int argc, char **argv) {\n ::progname = argv[0];\n\n if (argc != 3)\n Usage();\n\n const std::string input_filename(argv[1]);\n File input(input_filename, \"r\");\n if (not input)\n Error(\"can't open \\\"\" + input_filename + \"\\\" for reading!\");\n\n const std::string output_filename(argv[2]);\n File output(output_filename, \"w\");\n if (not output)\n Error(\"can't open \\\"\" + output_filename + \"\\\" for writing!\");\n\n try {\n DeleteUnusedLocalData(&input, &output);\n } catch (const std::exception &x) {\n Error(\"caught exception: \" + std::string(x.what()));\n }\n}\n<|endoftext|>"} {"text":"#include \n\n#include \nextern const sqlite3_api_routines *sqlite3_api;\n\n#include \n\n#include \"utils.hpp\"\n#include \"mol_fmcs.hpp\"\n#include \"mol.hpp\"\n\nvoid mol_fmcs_step(sqlite3_context* ctx, int, sqlite3_value** argv)\n{\n int rc = SQLITE_OK;\n \n sqlite3_value *arg = argv[0];\n RDKit::ROMOL_SPTR mol(arg_to_romol(arg, &rc));\n if ( rc != SQLITE_OK ) {\n sqlite3_result_error_code(ctx, rc);\n return;\n }\n\n void **agg = (void **) sqlite3_aggregate_context(ctx, sizeof(void *));\n\n if (agg) {\n if (!*agg) {\n *agg = (void *) new std::vector;\n }\n std::vector *mols = (std::vector *) *agg;\n mols->push_back(mol);\n } \n}\n\nvoid mol_fmcs_final(sqlite3_context * ctx)\n{\n void **agg = (void **) sqlite3_aggregate_context(ctx, 0);\n\n if (agg) {\n if (!*agg) {\n *agg = (void *) new std::vector;\n }\n std::vector *mols = (std::vector *) *agg;\n RDKit::MCSResult results = findMCS(*mols);\n\n sqlite3_result_text(ctx, results.SmartsString.c_str(), -1, SQLITE_TRANSIENT);\n }\n else {\n sqlite3_result_null(ctx);\n }\n}\n\nint chemicalite_init_mol_fmcs(sqlite3 *db)\n{\n (void)db;\n int rc = SQLITE_OK;\n\n rc = sqlite3_create_window_function(\n db,\n \"mol_find_mcs\",\n 1, \/\/ int nArg,\n SQLITE_UTF8, \/\/ int eTextRep,\n 0, \/\/ void *pApp,\n mol_fmcs_step, \/\/ void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n mol_fmcs_final, \/\/ void (*xFinal)(sqlite3_context*),\n 0, \/\/ void (*xValue)(sqlite3_context*),\n 0, \/\/ void (*xInverse)(sqlite3_context*,int,sqlite3_value**),\n 0 \/\/ void(*xDestroy)(void*)\n );\n\n return rc;\n}\nlet mol_find_mcs to return the query molecule instead of a smarts#include \n\n#include \nextern const sqlite3_api_routines *sqlite3_api;\n\n#include \n\n#include \"utils.hpp\"\n#include \"mol_fmcs.hpp\"\n#include \"mol.hpp\"\n\nvoid mol_fmcs_step(sqlite3_context* ctx, int, sqlite3_value** argv)\n{\n int rc = SQLITE_OK;\n \n sqlite3_value *arg = argv[0];\n RDKit::ROMOL_SPTR mol(arg_to_romol(arg, &rc));\n if ( rc != SQLITE_OK ) {\n sqlite3_result_error_code(ctx, rc);\n return;\n }\n\n void **agg = (void **) sqlite3_aggregate_context(ctx, sizeof(void *));\n\n if (agg) {\n if (!*agg) {\n *agg = (void *) new std::vector;\n }\n std::vector *mols = (std::vector *) *agg;\n mols->push_back(mol);\n } \n}\n\nvoid mol_fmcs_final(sqlite3_context * ctx)\n{\n void **agg = (void **) sqlite3_aggregate_context(ctx, 0);\n\n if (agg) {\n if (!*agg) {\n *agg = (void *) new std::vector;\n }\n std::vector *mols = (std::vector *) *agg;\n RDKit::MCSResult results = findMCS(*mols);\n\n#if 0\n sqlite3_result_text(ctx, results.SmartsString.c_str(), -1, SQLITE_TRANSIENT);\n#else\n int rc = SQLITE_OK;\n Blob blob = mol_to_blob(*results.QueryMol, &rc);\n if (rc != SQLITE_OK) {\n sqlite3_result_error_code(ctx, rc);\n }\n else {\n sqlite3_result_blob(ctx, blob.data(), blob.size(), SQLITE_TRANSIENT);\n }\n#endif\n }\n else {\n sqlite3_result_null(ctx);\n }\n}\n\nint chemicalite_init_mol_fmcs(sqlite3 *db)\n{\n (void)db;\n int rc = SQLITE_OK;\n\n rc = sqlite3_create_window_function(\n db,\n \"mol_find_mcs\",\n 1, \/\/ int nArg,\n SQLITE_UTF8, \/\/ int eTextRep,\n 0, \/\/ void *pApp,\n mol_fmcs_step, \/\/ void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n mol_fmcs_final, \/\/ void (*xFinal)(sqlite3_context*),\n 0, \/\/ void (*xValue)(sqlite3_context*),\n 0, \/\/ void (*xInverse)(sqlite3_context*,int,sqlite3_value**),\n 0 \/\/ void(*xDestroy)(void*)\n );\n\n return rc;\n}\n<|endoftext|>"} {"text":"\/*\n * MomentumConn.cpp\n *\n * Created on: Feburary 27, 2014\n * Author: slundquist\n *\/\n\n#include \"MomentumConn.hpp\"\n#include \n\nnamespace PV {\n\nMomentumConn::MomentumConn() { initialize_base(); }\n\nMomentumConn::MomentumConn(const char *name, HyPerCol *hc) : HyPerConn() {\n initialize_base();\n initialize(name, hc);\n}\n\nMomentumConn::~MomentumConn() {\n if (momentumMethod) {\n free(momentumMethod);\n }\n if (prev_dwDataStart) {\n free(prev_dwDataStart[0]);\n free(prev_dwDataStart);\n }\n}\n\nint MomentumConn::initialize_base() {\n prev_dwDataStart = NULL;\n momentumTau = .25;\n momentumMethod = NULL;\n momentumDecay = 0;\n return PV_SUCCESS;\n}\n\nint MomentumConn::allocateDataStructures() {\n int status = HyPerConn::allocateDataStructures();\n if (status == PV_POSTPONE) {\n return status;\n }\n if (!plasticityFlag)\n return status;\n int sx = nfp;\n int sy = sx * nxp;\n int sp = sy * nyp;\n int nPatches = getNumDataPatches();\n\n const int numAxons = numberOfAxonalArborLists();\n\n \/\/ Allocate dw buffer for previous dw\n prev_dwDataStart = (float **)pvCalloc(numAxons, sizeof(float *));\n std::size_t numWeights = (std::size_t)(numAxons * nxp * nyp * nfp) * (std::size_t)nPatches;\n prev_dwDataStart[0] = (float *)pvCalloc(numWeights, sizeof(float));\n for (int arborId = 0; arborId < numAxons; arborId++) {\n prev_dwDataStart[arborId] = (prev_dwDataStart[0] + sp * nPatches * arborId);\n pvAssert(prev_dwDataStart[arborId] != NULL);\n } \/\/ loop over arbors\n\n return PV_SUCCESS;\n}\n\nint MomentumConn::ioParamsFillGroup(enum ParamsIOFlag ioFlag) {\n int status = HyPerConn::ioParamsFillGroup(ioFlag);\n ioParam_momentumMethod(ioFlag);\n ioParam_momentumTau(ioFlag);\n ioParam_momentumDecay(ioFlag);\n ioParam_batchPeriod(ioFlag);\n return status;\n}\n\nvoid MomentumConn::ioParam_momentumTau(enum ParamsIOFlag ioFlag) {\n pvAssert(!parent->parameters()->presentAndNotBeenRead(name, \"plasticityFlag\"));\n if (plasticityFlag) {\n float defaultVal = 0;\n if (strcmp(momentumMethod, \"simple\") == 0) {\n defaultVal = .25;\n }\n else if (strcmp(momentumMethod, \"viscosity\") == 0) {\n defaultVal = 100;\n }\n else if (strcmp(momentumMethod, \"alex\") == 0) {\n defaultVal = .9;\n }\n\n parent->parameters()->ioParamValue(ioFlag, name, \"momentumTau\", &momentumTau, defaultVal);\n }\n}\n\n\/**\n * @brief momentumMethod: The momentum method to use\n * @details Assuming a = dwMax * pre * post\n * simple: deltaW(t) = a + momentumTau * deltaW(t-1)\n * viscosity: deltaW(t) = (deltaW(t-1) * exp(-1\/momentumTau)) + a\n * alex: deltaW(t) = momentumTau * delta(t-1) - momentumDecay * dwMax * w(t) + a\n *\/\nvoid MomentumConn::ioParam_momentumMethod(enum ParamsIOFlag ioFlag) {\n pvAssert(!parent->parameters()->presentAndNotBeenRead(name, \"plasticityFlag\"));\n if (plasticityFlag) {\n parent->parameters()->ioParamStringRequired(ioFlag, name, \"momentumMethod\", &momentumMethod);\n if (strcmp(momentumMethod, \"simple\") != 0 && strcmp(momentumMethod, \"viscosity\") != 0\n && strcmp(momentumMethod, \"alex\")) {\n Fatal() << \"MomentumConn \" << name << \": momentumMethod of \" << momentumMethod\n << \" is not known, options are \\\"simple\\\", \\\"viscosity\\\", and \\\"alex\\\"\\n\";\n }\n }\n}\n\nvoid MomentumConn::ioParam_momentumDecay(enum ParamsIOFlag ioFlag) {\n pvAssert(!parent->parameters()->presentAndNotBeenRead(name, \"plasticityFlag\"));\n if (plasticityFlag) {\n parent->parameters()->ioParamValue(\n ioFlag, name, \"momentumDecay\", &momentumDecay, momentumDecay);\n if (momentumDecay < 0 || momentumDecay > 1) {\n Fatal() << \"MomentumConn \" << name\n << \": momentumDecay must be between 0 and 1 inclusive\\n\";\n }\n }\n}\n\n\/\/ batchPeriod parameter was marked obsolete Jan 17, 2017.\nvoid MomentumConn::ioParam_batchPeriod(enum ParamsIOFlag ioFlag) {\n pvAssert(!parent->parameters()->presentAndNotBeenRead(name, \"plasticityFlag\"));\n if (plasticityFlag and parent->parameters()->present(name, \"batchPeriod\")) {\n int obsoleteBatchPeriod = (int)parent->parameters()->value(name, \"batchPeriod\");\n if (obsoleteBatchPeriod != 1) {\n if (parent->getCommunicator()->globalCommRank() == 0) {\n ErrorLog() << getDescription() << \": MomentumConn parameter batchPeriod is obsolete. \"\n << \"Instead use the HyPerCol nbatch parameter.\\n\";\n }\n MPI_Barrier(parent->getCommunicator()->globalCommunicator());\n exit(EXIT_FAILURE);\n }\n }\n}\n\nint MomentumConn::updateWeights(int arborId) {\n \/\/ Add momentum right before updateWeights\n for (int kArbor = 0; kArbor < this->numberOfAxonalArborLists(); kArbor++) {\n applyMomentum(arborId);\n }\n\n \/\/ Saved to prevweights\n pvAssert(prev_dwDataStart);\n std::memcpy(\n *prev_dwDataStart,\n *get_dwDataStart(),\n sizeof(float) * numberOfAxonalArborLists() * nxp * nyp * nfp * getNumDataPatches());\n\n \/\/ add dw to w\n for (int kArbor = 0; kArbor < this->numberOfAxonalArborLists(); kArbor++) {\n float *w_data_start = get_wDataStart(kArbor);\n for (long int k = 0; k < patchStartIndex(getNumDataPatches()); k++) {\n w_data_start[k] += get_dwDataStart(kArbor)[k];\n }\n }\n return PV_BREAK;\n}\n\nint MomentumConn::applyMomentum(int arbor_ID) {\n int nExt = preSynapticLayer()->getNumExtended();\n const PVLayerLoc *loc = preSynapticLayer()->getLayerLoc();\n int numKernels = getNumDataPatches();\n\n \/\/ Shared weights done in parallel, parallel in numkernels\n if (!strcmp(momentumMethod, \"simple\")) {\n#ifdef PV_USE_OPENMP_THREADS\n#pragma omp parallel for\n#endif\n for (int kernelIdx = 0; kernelIdx < numKernels; kernelIdx++) {\n float *dwdata_start = get_dwDataHead(arbor_ID, kernelIdx);\n float const *prev_dw_start = get_prev_dwDataHead(arbor_ID, kernelIdx);\n float const *wdata_start = get_wDataHead(arbor_ID, kernelIdx);\n for (int k = 0; k < nxp * nyp * nfp; k++) {\n dwdata_start[k] += momentumTau * prev_dw_start[k] - momentumDecay * wdata_start[k];\n }\n }\n }\n else if (!strcmp(momentumMethod, \"viscosity\")) {\n float const tauFactor = exp(-1.0f \/ momentumTau);\n#ifdef PV_USE_OPENMP_THREADS\n#pragma omp parallel for\n#endif\n for (int kernelIdx = 0; kernelIdx < numKernels; kernelIdx++) {\n float *dwdata_start = get_dwDataHead(arbor_ID, kernelIdx);\n float const *prev_dw_start = get_prev_dwDataHead(arbor_ID, kernelIdx);\n float const *wdata_start = get_wDataHead(arbor_ID, kernelIdx);\n for (int k = 0; k < nxp * nyp * nfp; k++) {\n dwdata_start[k] += tauFactor * prev_dw_start[k] - momentumDecay * wdata_start[k];\n }\n }\n }\n else if (!strcmp(momentumMethod, \"alex\")) {\n float const decayFactor = momentumDecay * getDWMax();\n#ifdef PV_USE_OPENMP_THREADS\n#pragma omp parallel for\n#endif\n for (int kernelIdx = 0; kernelIdx < numKernels; kernelIdx++) {\n float *dwdata_start = get_dwDataHead(arbor_ID, kernelIdx);\n float const *prev_dw_start = get_prev_dwDataHead(arbor_ID, kernelIdx);\n float const *wdata_start = get_wDataHead(arbor_ID, kernelIdx);\n for (int k = 0; k < nxp * nyp * nfp; k++) {\n dwdata_start[k] += momentumTau * prev_dw_start[k] - decayFactor * wdata_start[k];\n }\n }\n }\n else {\n pvAssertMessage(0, \"Unrecognized momentumMethod\\n\");\n }\n return PV_SUCCESS;\n}\n\n\/\/ TODO checkpointing not working with batching, must write checkpoint exactly at period\nint MomentumConn::registerData(Checkpointer *checkpointer, std::string const &objName) {\n int status = HyPerConn::registerData(checkpointer, objName);\n if (plasticityFlag) {\n checkpointWeightPvp(checkpointer, \"prev_dW\", prev_dwDataStart);\n }\n}\n\nint MomentumConn::readStateFromCheckpoint(Checkpointer *checkpointer) {\n int status = PV_SUCCESS;\n if (initializeFromCheckpointFlag) {\n status = HyPerConn::readStateFromCheckpoint(checkpointer);\n if (plasticityFlag) {\n checkpointer->readNamedCheckpointEntry(std::string(name), std::string(\"prev_dW\"));\n }\n }\n return status;\n}\n\n} \/\/ end namespace PV\nHotfix: missing return value\/*\n * MomentumConn.cpp\n *\n * Created on: Feburary 27, 2014\n * Author: slundquist\n *\/\n\n#include \"MomentumConn.hpp\"\n#include \n\nnamespace PV {\n\nMomentumConn::MomentumConn() { initialize_base(); }\n\nMomentumConn::MomentumConn(const char *name, HyPerCol *hc) : HyPerConn() {\n initialize_base();\n initialize(name, hc);\n}\n\nMomentumConn::~MomentumConn() {\n if (momentumMethod) {\n free(momentumMethod);\n }\n if (prev_dwDataStart) {\n free(prev_dwDataStart[0]);\n free(prev_dwDataStart);\n }\n}\n\nint MomentumConn::initialize_base() {\n prev_dwDataStart = NULL;\n momentumTau = .25;\n momentumMethod = NULL;\n momentumDecay = 0;\n return PV_SUCCESS;\n}\n\nint MomentumConn::allocateDataStructures() {\n int status = HyPerConn::allocateDataStructures();\n if (status == PV_POSTPONE) {\n return status;\n }\n if (!plasticityFlag)\n return status;\n int sx = nfp;\n int sy = sx * nxp;\n int sp = sy * nyp;\n int nPatches = getNumDataPatches();\n\n const int numAxons = numberOfAxonalArborLists();\n\n \/\/ Allocate dw buffer for previous dw\n prev_dwDataStart = (float **)pvCalloc(numAxons, sizeof(float *));\n std::size_t numWeights = (std::size_t)(numAxons * nxp * nyp * nfp) * (std::size_t)nPatches;\n prev_dwDataStart[0] = (float *)pvCalloc(numWeights, sizeof(float));\n for (int arborId = 0; arborId < numAxons; arborId++) {\n prev_dwDataStart[arborId] = (prev_dwDataStart[0] + sp * nPatches * arborId);\n pvAssert(prev_dwDataStart[arborId] != NULL);\n } \/\/ loop over arbors\n\n return PV_SUCCESS;\n}\n\nint MomentumConn::ioParamsFillGroup(enum ParamsIOFlag ioFlag) {\n int status = HyPerConn::ioParamsFillGroup(ioFlag);\n ioParam_momentumMethod(ioFlag);\n ioParam_momentumTau(ioFlag);\n ioParam_momentumDecay(ioFlag);\n ioParam_batchPeriod(ioFlag);\n return status;\n}\n\nvoid MomentumConn::ioParam_momentumTau(enum ParamsIOFlag ioFlag) {\n pvAssert(!parent->parameters()->presentAndNotBeenRead(name, \"plasticityFlag\"));\n if (plasticityFlag) {\n float defaultVal = 0;\n if (strcmp(momentumMethod, \"simple\") == 0) {\n defaultVal = .25;\n }\n else if (strcmp(momentumMethod, \"viscosity\") == 0) {\n defaultVal = 100;\n }\n else if (strcmp(momentumMethod, \"alex\") == 0) {\n defaultVal = .9;\n }\n\n parent->parameters()->ioParamValue(ioFlag, name, \"momentumTau\", &momentumTau, defaultVal);\n }\n}\n\n\/**\n * @brief momentumMethod: The momentum method to use\n * @details Assuming a = dwMax * pre * post\n * simple: deltaW(t) = a + momentumTau * deltaW(t-1)\n * viscosity: deltaW(t) = (deltaW(t-1) * exp(-1\/momentumTau)) + a\n * alex: deltaW(t) = momentumTau * delta(t-1) - momentumDecay * dwMax * w(t) + a\n *\/\nvoid MomentumConn::ioParam_momentumMethod(enum ParamsIOFlag ioFlag) {\n pvAssert(!parent->parameters()->presentAndNotBeenRead(name, \"plasticityFlag\"));\n if (plasticityFlag) {\n parent->parameters()->ioParamStringRequired(ioFlag, name, \"momentumMethod\", &momentumMethod);\n if (strcmp(momentumMethod, \"simple\") != 0 && strcmp(momentumMethod, \"viscosity\") != 0\n && strcmp(momentumMethod, \"alex\")) {\n Fatal() << \"MomentumConn \" << name << \": momentumMethod of \" << momentumMethod\n << \" is not known, options are \\\"simple\\\", \\\"viscosity\\\", and \\\"alex\\\"\\n\";\n }\n }\n}\n\nvoid MomentumConn::ioParam_momentumDecay(enum ParamsIOFlag ioFlag) {\n pvAssert(!parent->parameters()->presentAndNotBeenRead(name, \"plasticityFlag\"));\n if (plasticityFlag) {\n parent->parameters()->ioParamValue(\n ioFlag, name, \"momentumDecay\", &momentumDecay, momentumDecay);\n if (momentumDecay < 0 || momentumDecay > 1) {\n Fatal() << \"MomentumConn \" << name\n << \": momentumDecay must be between 0 and 1 inclusive\\n\";\n }\n }\n}\n\n\/\/ batchPeriod parameter was marked obsolete Jan 17, 2017.\nvoid MomentumConn::ioParam_batchPeriod(enum ParamsIOFlag ioFlag) {\n pvAssert(!parent->parameters()->presentAndNotBeenRead(name, \"plasticityFlag\"));\n if (plasticityFlag and parent->parameters()->present(name, \"batchPeriod\")) {\n int obsoleteBatchPeriod = (int)parent->parameters()->value(name, \"batchPeriod\");\n if (obsoleteBatchPeriod != 1) {\n if (parent->getCommunicator()->globalCommRank() == 0) {\n ErrorLog() << getDescription() << \": MomentumConn parameter batchPeriod is obsolete. \"\n << \"Instead use the HyPerCol nbatch parameter.\\n\";\n }\n MPI_Barrier(parent->getCommunicator()->globalCommunicator());\n exit(EXIT_FAILURE);\n }\n }\n}\n\nint MomentumConn::updateWeights(int arborId) {\n \/\/ Add momentum right before updateWeights\n for (int kArbor = 0; kArbor < this->numberOfAxonalArborLists(); kArbor++) {\n applyMomentum(arborId);\n }\n\n \/\/ Saved to prevweights\n pvAssert(prev_dwDataStart);\n std::memcpy(\n *prev_dwDataStart,\n *get_dwDataStart(),\n sizeof(float) * numberOfAxonalArborLists() * nxp * nyp * nfp * getNumDataPatches());\n\n \/\/ add dw to w\n for (int kArbor = 0; kArbor < this->numberOfAxonalArborLists(); kArbor++) {\n float *w_data_start = get_wDataStart(kArbor);\n for (long int k = 0; k < patchStartIndex(getNumDataPatches()); k++) {\n w_data_start[k] += get_dwDataStart(kArbor)[k];\n }\n }\n return PV_BREAK;\n}\n\nint MomentumConn::applyMomentum(int arbor_ID) {\n int nExt = preSynapticLayer()->getNumExtended();\n const PVLayerLoc *loc = preSynapticLayer()->getLayerLoc();\n int numKernels = getNumDataPatches();\n\n \/\/ Shared weights done in parallel, parallel in numkernels\n if (!strcmp(momentumMethod, \"simple\")) {\n#ifdef PV_USE_OPENMP_THREADS\n#pragma omp parallel for\n#endif\n for (int kernelIdx = 0; kernelIdx < numKernels; kernelIdx++) {\n float *dwdata_start = get_dwDataHead(arbor_ID, kernelIdx);\n float const *prev_dw_start = get_prev_dwDataHead(arbor_ID, kernelIdx);\n float const *wdata_start = get_wDataHead(arbor_ID, kernelIdx);\n for (int k = 0; k < nxp * nyp * nfp; k++) {\n dwdata_start[k] += momentumTau * prev_dw_start[k] - momentumDecay * wdata_start[k];\n }\n }\n }\n else if (!strcmp(momentumMethod, \"viscosity\")) {\n float const tauFactor = exp(-1.0f \/ momentumTau);\n#ifdef PV_USE_OPENMP_THREADS\n#pragma omp parallel for\n#endif\n for (int kernelIdx = 0; kernelIdx < numKernels; kernelIdx++) {\n float *dwdata_start = get_dwDataHead(arbor_ID, kernelIdx);\n float const *prev_dw_start = get_prev_dwDataHead(arbor_ID, kernelIdx);\n float const *wdata_start = get_wDataHead(arbor_ID, kernelIdx);\n for (int k = 0; k < nxp * nyp * nfp; k++) {\n dwdata_start[k] += tauFactor * prev_dw_start[k] - momentumDecay * wdata_start[k];\n }\n }\n }\n else if (!strcmp(momentumMethod, \"alex\")) {\n float const decayFactor = momentumDecay * getDWMax();\n#ifdef PV_USE_OPENMP_THREADS\n#pragma omp parallel for\n#endif\n for (int kernelIdx = 0; kernelIdx < numKernels; kernelIdx++) {\n float *dwdata_start = get_dwDataHead(arbor_ID, kernelIdx);\n float const *prev_dw_start = get_prev_dwDataHead(arbor_ID, kernelIdx);\n float const *wdata_start = get_wDataHead(arbor_ID, kernelIdx);\n for (int k = 0; k < nxp * nyp * nfp; k++) {\n dwdata_start[k] += momentumTau * prev_dw_start[k] - decayFactor * wdata_start[k];\n }\n }\n }\n else {\n pvAssertMessage(0, \"Unrecognized momentumMethod\\n\");\n }\n return PV_SUCCESS;\n}\n\n\/\/ TODO checkpointing not working with batching, must write checkpoint exactly at period\nint MomentumConn::registerData(Checkpointer *checkpointer, std::string const &objName) {\n int status = HyPerConn::registerData(checkpointer, objName);\n if (plasticityFlag) {\n checkpointWeightPvp(checkpointer, \"prev_dW\", prev_dwDataStart);\n }\n return status;\n}\n\nint MomentumConn::readStateFromCheckpoint(Checkpointer *checkpointer) {\n int status = PV_SUCCESS;\n if (initializeFromCheckpointFlag) {\n status = HyPerConn::readStateFromCheckpoint(checkpointer);\n if (plasticityFlag) {\n checkpointer->readNamedCheckpointEntry(std::string(name), std::string(\"prev_dW\"));\n }\n }\n return status;\n}\n\n} \/\/ end namespace PV\n<|endoftext|>"} {"text":"\/\/\n\/\/ MCIndexSet.cpp\n\/\/ mailcore2\n\/\/\n\/\/ Created by DINH Viêt Hoà on 3\/4\/13.\n\/\/ Copyright (c) 2013 MailCore. All rights reserved.\n\/\/\n\n#include \"MCIndexSet.h\"\n\n#include \"MCString.h\"\n#include \"MCAssert.h\"\n#include \"MCRange.h\"\n#include \"MCLog.h\"\n#include \"MCArray.h\"\n#include \"MCHashMap.h\"\n#include \"MCUtils.h\"\n\nusing namespace mailcore;\n\nvoid IndexSet::init()\n{\n mRanges = NULL;\n mAllocated = 0;\n mCount = 0;\n}\n\nIndexSet::IndexSet()\n{\n init();\n}\n\nIndexSet::IndexSet(IndexSet * o)\n{\n init();\n mRanges = new Range[o->mAllocated];\n for(unsigned int i = 0 ; i < o->mCount ; i ++) {\n mRanges[i] = o->mRanges[i];\n }\n mAllocated = o->mAllocated;\n mCount = o->mCount;\n}\n\nIndexSet::~IndexSet()\n{\n removeAllIndexes();\n}\n\nIndexSet * IndexSet::indexSet()\n{\n IndexSet * result = new IndexSet();\n result->autorelease();\n return result;\n}\n\nIndexSet * IndexSet::indexSetWithRange(Range range)\n{\n IndexSet * result = new IndexSet();\n result->autorelease();\n result->addRange(range);\n return result;\n}\n\nIndexSet * IndexSet::indexSetWithIndex(uint64_t idx)\n{\n IndexSet * result = new IndexSet();\n result->autorelease();\n result->addIndex(idx);\n return result;\n}\n\nunsigned int IndexSet::count()\n{\n unsigned int total = 0;\n for(unsigned int i = 0 ; i < mCount ; i ++) {\n total += mRanges[i].length + 1;\n }\n return total;\n}\n\nint IndexSet::rangeIndexForIndexWithBounds(uint64_t idx, unsigned int left, unsigned int right)\n{\n unsigned int middle = (left + right) \/ 2;\n \n Range middleRange = mRanges[middle];\n \n if (left == right) {\n if ((idx >= RangeLeftBound(middleRange)) && (idx <= RangeRightBound(middleRange))) {\n return left;\n }\n return -1;\n }\n\n if ((idx >= RangeLeftBound(middleRange)) && (idx <= RangeRightBound(middleRange))) {\n return middle;\n }\n if (idx < middleRange.location) {\n return rangeIndexForIndexWithBounds(idx, left, middle);\n }\n else {\n return rangeIndexForIndexWithBounds(idx, middle + 1, right);\n }\n}\n\nint IndexSet::rangeIndexForIndex(uint64_t idx)\n{\n if (mCount == 0)\n return -1;\n \n return rangeIndexForIndexWithBounds(idx, 0, mCount - 1);\n}\n\nint IndexSet::rightRangeIndexForIndexWithBounds(uint64_t idx, unsigned int left, unsigned int right)\n{\n unsigned int middle = (left + right) \/ 2;\n \n Range middleRange = mRanges[middle];\n \n if (left == right) {\n if (idx > middleRange.location + middleRange.length) {\n return left + 1;\n }\n else {\n return left;\n }\n }\n \n if (idx < middleRange.location + middleRange.length) {\n return rightRangeIndexForIndexWithBounds(idx, left, middle);\n }\n else {\n return rightRangeIndexForIndexWithBounds(idx, middle + 1, right);\n }\n}\n\nint IndexSet::rightRangeIndexForIndex(uint64_t idx)\n{\n if (mCount == 0)\n return 0;\n \n return rightRangeIndexForIndexWithBounds(idx, 0, mCount - 1);\n}\n\nint IndexSet::leftRangeIndexForIndexWithBounds(uint64_t idx, unsigned int left, unsigned int right)\n{\n unsigned int middle = (left + right) \/ 2;\n \n Range middleRange = mRanges[middle];\n \n if (left == right) {\n if (idx <= middleRange.location) {\n return left;\n }\n else {\n return left + 1;\n }\n }\n \n if (idx <= middleRange.location) {\n return leftRangeIndexForIndexWithBounds(idx, left, middle);\n }\n else {\n return leftRangeIndexForIndexWithBounds(idx, middle + 1, right);\n }\n}\n\nint IndexSet::leftRangeIndexForIndex(uint64_t idx)\n{\n if (mCount == 0)\n return 0;\n \n return leftRangeIndexForIndexWithBounds(idx, 0, mCount - 1);\n}\n\nvoid IndexSet::addRangeIndex(unsigned int rangeIndex)\n{\n if (mAllocated < mCount + 1) {\n while (mAllocated < mCount + 1) {\n if (mAllocated == 0) {\n mAllocated = 4;\n }\n mAllocated *= 2;\n }\n \n Range * rangesReplacement = new Range[mAllocated];\n for(unsigned int i = 0 ; i < rangeIndex ; i ++) {\n rangesReplacement[i] = mRanges[i];\n }\n for(unsigned int i = rangeIndex ; i < mCount ; i ++) {\n rangesReplacement[i + 1] = mRanges[i];\n }\n mCount ++;\n rangesReplacement[rangeIndex].location = 0;\n rangesReplacement[rangeIndex].length = 0;\n delete [] mRanges;\n mRanges = rangesReplacement;\n }\n else {\n if (mCount > 0) {\n for(int i = mCount - 1 ; i >= (int) rangeIndex ; i --) {\n mRanges[i + 1] = mRanges[i];\n }\n }\n mCount ++;\n mRanges[rangeIndex].location = 0;\n mRanges[rangeIndex].length = 0;\n }\n}\n\nvoid IndexSet::addRange(Range range)\n{\n int rangeIndex = leftRangeIndexForIndex(range.location);\n addRangeIndex(rangeIndex);\n mRanges[rangeIndex] = range;\n \n mergeRanges(rangeIndex);\n if (rangeIndex > 0) {\n tryToMergeAdjacentRanges(rangeIndex - 1);\n }\n if (rangeIndex < mCount - 1) {\n tryToMergeAdjacentRanges(rangeIndex);\n }\n}\n\nvoid IndexSet::tryToMergeAdjacentRanges(unsigned int rangeIndex)\n{\n if (RangeRightBound(mRanges[rangeIndex]) == UINT64_MAX)\n return;\n \n if (RangeRightBound(mRanges[rangeIndex]) + 1 != mRanges[rangeIndex + 1].location) {\n return;\n }\n \n uint64_t right = RangeRightBound(mRanges[rangeIndex + 1]);\n removeRangeIndex(rangeIndex + 1, 1);\n mRanges[rangeIndex].length = right - mRanges[rangeIndex].location;\n}\n\nvoid IndexSet::mergeRanges(unsigned int rangeIndex)\n{\n int right = rangeIndex;\n \n for(int i = rangeIndex ; i < mCount ; i ++) {\n if (RangeHasIntersection(mRanges[rangeIndex], mRanges[i])) {\n right = i;\n }\n else {\n break;\n }\n }\n \n if (right == rangeIndex)\n return;\n \n IndexSet * indexSet = RangeUnion(mRanges[rangeIndex], mRanges[right]);\n MCAssert(indexSet->rangesCount() > 0);\n Range range = indexSet->allRanges()[0];\n removeRangeIndex(rangeIndex + 1, right - rangeIndex);\n mRanges[rangeIndex] = range;\n}\n\nvoid IndexSet::addIndex(uint64_t idx)\n{\n addRange(RangeMake(idx, 0));\n}\n\nvoid IndexSet::removeRangeIndex(unsigned int rangeIndex, unsigned int count)\n{\n for(unsigned int i = rangeIndex + count ; i < mCount ; i ++) {\n mRanges[i - count] = mRanges[i];\n }\n mCount -= count;\n}\n\nvoid IndexSet::removeRange(Range range)\n{\n int left = -1;\n int right = -1;\n int leftRangeIndex = leftRangeIndexForIndex(range.location);\n for(int i = leftRangeIndex ; i < mCount ; i ++) {\n if (RangeHasIntersection(mRanges[i], range)) {\n IndexSet * indexSet = RangeRemoveRange(mRanges[i], range);\n if (indexSet->rangesCount() == 0) {\n if (left == -1) {\n left = i;\n }\n right = i;\n mRanges[i] = RangeEmpty;\n }\n else if (indexSet->rangesCount() == 1) {\n mRanges[i] = indexSet->allRanges()[0];\n }\n else {\n MCAssert(indexSet->rangesCount() == 2);\n addRangeIndex(i);\n mRanges[i] = indexSet->allRanges()[0];\n mRanges[i + 1] = indexSet->allRanges()[1];\n }\n }\n else {\n break;\n }\n }\n \n if (left != -1) {\n removeRangeIndex(left, right - left + 1);\n }\n}\n\nvoid IndexSet::removeIndex(uint64_t idx)\n{\n removeRange(RangeMake(idx, 0));\n}\n\nbool IndexSet::containsIndex(uint64_t idx)\n{\n int rangeIndex = rangeIndexForIndex(idx);\n return rangeIndex != -1;\n}\n\nunsigned int IndexSet::rangesCount()\n{\n return mCount;\n}\n\nRange * IndexSet::allRanges()\n{\n return mRanges;\n}\n\nvoid IndexSet::removeAllIndexes()\n{\n if (mRanges != NULL) {\n delete[] mRanges;\n mRanges = NULL;\n }\n mAllocated = 0;\n mCount = 0;\n}\n\nString * IndexSet::description()\n{\n String * result = String::string();\n for(unsigned int i = 0 ; i < mCount ; i ++) {\n if (i != 0) {\n result->appendUTF8Format(\",\");\n }\n if (mRanges[i].length == 0) {\n result->appendUTF8Format(\"%llu\",\n (unsigned long long) mRanges[i].location);\n }\n else {\n result->appendUTF8Format(\"%llu-%llu\",\n (unsigned long long) mRanges[i].location,\n (unsigned long long) (mRanges[i].location + mRanges[i].length));\n }\n }\n return result;\n}\n\nObject * IndexSet::copy()\n{\n return new IndexSet(this);\n}\n\nvoid IndexSet::intersectsRange(Range range)\n{\n uint64_t right = RangeRightBound(range);\n if (right == UINT64_MAX) {\n removeRange(RangeMake(0, range.location - 1));\n }\n else {\n removeRange(RangeMake(0, range.location - 1));\n removeRange(RangeMake(right, UINT64_MAX));\n }\n}\n\n\nHashMap * IndexSet::serializable()\n{\n HashMap * result = Object::serializable();\n Array * ranges = Array::array();\n for(unsigned int i = 0 ; i < mCount ; i ++) {\n ranges->addObject(RangeToString(mRanges[i]));\n }\n result->setObjectForKey(MCSTR(\"ranges\"), ranges);\n return result;\n}\n\nvoid IndexSet::importSerializable(HashMap * serializable)\n{\n Array * ranges = (Array *) serializable->objectForKey(MCSTR(\"ranges\"));\n for(unsigned int i = 0 ; i < ranges->count() ; i ++) {\n String * rangeStr = (String *) ranges->objectAtIndex(i);\n addRange(RangeFromString(rangeStr));\n }\n}\n\nvoid IndexSet::addIndexSet(IndexSet * indexSet)\n{\n for(unsigned int i = 0 ; i < indexSet->count() ; i ++) {\n addRange(indexSet->allRanges()[i]);\n }\n}\n\nvoid IndexSet::removeIndexSet(IndexSet * indexSet)\n{\n for(unsigned int i = 0 ; i < indexSet->count() ; i ++) {\n removeRange(indexSet->allRanges()[i]);\n }\n}\n\nvoid IndexSet::intersectsIndexSet(IndexSet * indexSet)\n{\n IndexSet * result = new IndexSet();\n for(unsigned int i = 0 ; i < indexSet->count() ; i ++) {\n IndexSet * rangeIntersect = (IndexSet *) copy();\n rangeIntersect->intersectsRange(indexSet->allRanges()[i]);\n result->addIndexSet(rangeIntersect);\n rangeIntersect->release();\n }\n removeAllIndexes();\n addIndexSet(result);\n result->release();\n}\n\nstatic void * createObject()\n{\n return new IndexSet();\n}\n\n__attribute__((constructor))\nstatic void initialize()\n{\n Object::registerObjectConstructor(\"mailcore::IndexSet\", &createObject);\n}\nFixed some IndexSet operations\/\/\n\/\/ MCIndexSet.cpp\n\/\/ mailcore2\n\/\/\n\/\/ Created by DINH Viêt Hoà on 3\/4\/13.\n\/\/ Copyright (c) 2013 MailCore. All rights reserved.\n\/\/\n\n#include \"MCIndexSet.h\"\n\n#include \"MCString.h\"\n#include \"MCAssert.h\"\n#include \"MCRange.h\"\n#include \"MCLog.h\"\n#include \"MCArray.h\"\n#include \"MCHashMap.h\"\n#include \"MCUtils.h\"\n\nusing namespace mailcore;\n\nvoid IndexSet::init()\n{\n mRanges = NULL;\n mAllocated = 0;\n mCount = 0;\n}\n\nIndexSet::IndexSet()\n{\n init();\n}\n\nIndexSet::IndexSet(IndexSet * o)\n{\n init();\n mRanges = new Range[o->mAllocated];\n for(unsigned int i = 0 ; i < o->mCount ; i ++) {\n mRanges[i] = o->mRanges[i];\n }\n mAllocated = o->mAllocated;\n mCount = o->mCount;\n}\n\nIndexSet::~IndexSet()\n{\n removeAllIndexes();\n}\n\nIndexSet * IndexSet::indexSet()\n{\n IndexSet * result = new IndexSet();\n result->autorelease();\n return result;\n}\n\nIndexSet * IndexSet::indexSetWithRange(Range range)\n{\n IndexSet * result = new IndexSet();\n result->autorelease();\n result->addRange(range);\n return result;\n}\n\nIndexSet * IndexSet::indexSetWithIndex(uint64_t idx)\n{\n IndexSet * result = new IndexSet();\n result->autorelease();\n result->addIndex(idx);\n return result;\n}\n\nunsigned int IndexSet::count()\n{\n unsigned int total = 0;\n for(unsigned int i = 0 ; i < mCount ; i ++) {\n total += mRanges[i].length + 1;\n }\n return total;\n}\n\nint IndexSet::rangeIndexForIndexWithBounds(uint64_t idx, unsigned int left, unsigned int right)\n{\n unsigned int middle = (left + right) \/ 2;\n \n Range middleRange = mRanges[middle];\n \n if (left == right) {\n if ((idx >= RangeLeftBound(middleRange)) && (idx <= RangeRightBound(middleRange))) {\n return left;\n }\n return -1;\n }\n\n if ((idx >= RangeLeftBound(middleRange)) && (idx <= RangeRightBound(middleRange))) {\n return middle;\n }\n if (idx < middleRange.location) {\n return rangeIndexForIndexWithBounds(idx, left, middle);\n }\n else {\n return rangeIndexForIndexWithBounds(idx, middle + 1, right);\n }\n}\n\nint IndexSet::rangeIndexForIndex(uint64_t idx)\n{\n if (mCount == 0)\n return -1;\n \n return rangeIndexForIndexWithBounds(idx, 0, mCount - 1);\n}\n\nint IndexSet::rightRangeIndexForIndexWithBounds(uint64_t idx, unsigned int left, unsigned int right)\n{\n unsigned int middle = (left + right) \/ 2;\n \n Range middleRange = mRanges[middle];\n \n if (left == right) {\n if (idx > middleRange.location + middleRange.length) {\n return left + 1;\n }\n else {\n return left;\n }\n }\n \n if (idx < middleRange.location + middleRange.length) {\n return rightRangeIndexForIndexWithBounds(idx, left, middle);\n }\n else {\n return rightRangeIndexForIndexWithBounds(idx, middle + 1, right);\n }\n}\n\nint IndexSet::rightRangeIndexForIndex(uint64_t idx)\n{\n if (mCount == 0)\n return 0;\n \n return rightRangeIndexForIndexWithBounds(idx, 0, mCount - 1);\n}\n\nint IndexSet::leftRangeIndexForIndexWithBounds(uint64_t idx, unsigned int left, unsigned int right)\n{\n unsigned int middle = (left + right) \/ 2;\n \n Range middleRange = mRanges[middle];\n \n if (left == right) {\n if (idx <= middleRange.location) {\n return left;\n }\n else {\n return left + 1;\n }\n }\n \n if (idx <= middleRange.location) {\n return leftRangeIndexForIndexWithBounds(idx, left, middle);\n }\n else {\n return leftRangeIndexForIndexWithBounds(idx, middle + 1, right);\n }\n}\n\nint IndexSet::leftRangeIndexForIndex(uint64_t idx)\n{\n if (mCount == 0)\n return 0;\n \n return leftRangeIndexForIndexWithBounds(idx, 0, mCount - 1);\n}\n\nvoid IndexSet::addRangeIndex(unsigned int rangeIndex)\n{\n if (mAllocated < mCount + 1) {\n while (mAllocated < mCount + 1) {\n if (mAllocated == 0) {\n mAllocated = 4;\n }\n mAllocated *= 2;\n }\n \n Range * rangesReplacement = new Range[mAllocated];\n for(unsigned int i = 0 ; i < rangeIndex ; i ++) {\n rangesReplacement[i] = mRanges[i];\n }\n for(unsigned int i = rangeIndex ; i < mCount ; i ++) {\n rangesReplacement[i + 1] = mRanges[i];\n }\n mCount ++;\n rangesReplacement[rangeIndex].location = 0;\n rangesReplacement[rangeIndex].length = 0;\n delete [] mRanges;\n mRanges = rangesReplacement;\n }\n else {\n if (mCount > 0) {\n for(int i = mCount - 1 ; i >= (int) rangeIndex ; i --) {\n mRanges[i + 1] = mRanges[i];\n }\n }\n mCount ++;\n mRanges[rangeIndex].location = 0;\n mRanges[rangeIndex].length = 0;\n }\n}\n\nvoid IndexSet::addRange(Range range)\n{\n int rangeIndex = leftRangeIndexForIndex(range.location);\n addRangeIndex(rangeIndex);\n mRanges[rangeIndex] = range;\n \n mergeRanges(rangeIndex);\n if (rangeIndex > 0) {\n tryToMergeAdjacentRanges(rangeIndex - 1);\n }\n if (rangeIndex < mCount - 1) {\n tryToMergeAdjacentRanges(rangeIndex);\n }\n}\n\nvoid IndexSet::tryToMergeAdjacentRanges(unsigned int rangeIndex)\n{\n if (RangeRightBound(mRanges[rangeIndex]) == UINT64_MAX)\n return;\n \n if (RangeRightBound(mRanges[rangeIndex]) + 1 != mRanges[rangeIndex + 1].location) {\n return;\n }\n \n uint64_t right = RangeRightBound(mRanges[rangeIndex + 1]);\n removeRangeIndex(rangeIndex + 1, 1);\n mRanges[rangeIndex].length = right - mRanges[rangeIndex].location;\n}\n\nvoid IndexSet::mergeRanges(unsigned int rangeIndex)\n{\n int right = rangeIndex;\n \n for(int i = rangeIndex ; i < mCount ; i ++) {\n if (RangeHasIntersection(mRanges[rangeIndex], mRanges[i])) {\n right = i;\n }\n else {\n break;\n }\n }\n \n if (right == rangeIndex)\n return;\n \n IndexSet * indexSet = RangeUnion(mRanges[rangeIndex], mRanges[right]);\n MCAssert(indexSet->rangesCount() > 0);\n Range range = indexSet->allRanges()[0];\n removeRangeIndex(rangeIndex + 1, right - rangeIndex);\n mRanges[rangeIndex] = range;\n}\n\nvoid IndexSet::addIndex(uint64_t idx)\n{\n addRange(RangeMake(idx, 0));\n}\n\nvoid IndexSet::removeRangeIndex(unsigned int rangeIndex, unsigned int count)\n{\n for(unsigned int i = rangeIndex + count ; i < mCount ; i ++) {\n mRanges[i - count] = mRanges[i];\n }\n mCount -= count;\n}\n\nvoid IndexSet::removeRange(Range range)\n{\n int left = -1;\n int right = -1;\n int leftRangeIndex = leftRangeIndexForIndex(range.location);\n for(int i = leftRangeIndex ; i < mCount ; i ++) {\n if (RangeHasIntersection(mRanges[i], range)) {\n IndexSet * indexSet = RangeRemoveRange(mRanges[i], range);\n if (indexSet->rangesCount() == 0) {\n if (left == -1) {\n left = i;\n }\n right = i;\n mRanges[i] = RangeEmpty;\n }\n else if (indexSet->rangesCount() == 1) {\n mRanges[i] = indexSet->allRanges()[0];\n }\n else {\n MCAssert(indexSet->rangesCount() == 2);\n addRangeIndex(i);\n mRanges[i] = indexSet->allRanges()[0];\n mRanges[i + 1] = indexSet->allRanges()[1];\n }\n }\n else {\n break;\n }\n }\n \n if (left != -1) {\n removeRangeIndex(left, right - left + 1);\n }\n}\n\nvoid IndexSet::removeIndex(uint64_t idx)\n{\n removeRange(RangeMake(idx, 0));\n}\n\nbool IndexSet::containsIndex(uint64_t idx)\n{\n int rangeIndex = rangeIndexForIndex(idx);\n return rangeIndex != -1;\n}\n\nunsigned int IndexSet::rangesCount()\n{\n return mCount;\n}\n\nRange * IndexSet::allRanges()\n{\n return mRanges;\n}\n\nvoid IndexSet::removeAllIndexes()\n{\n if (mRanges != NULL) {\n delete[] mRanges;\n mRanges = NULL;\n }\n mAllocated = 0;\n mCount = 0;\n}\n\nString * IndexSet::description()\n{\n String * result = String::string();\n for(unsigned int i = 0 ; i < mCount ; i ++) {\n if (i != 0) {\n result->appendUTF8Format(\",\");\n }\n if (mRanges[i].length == 0) {\n result->appendUTF8Format(\"%llu\",\n (unsigned long long) mRanges[i].location);\n }\n else {\n result->appendUTF8Format(\"%llu-%llu\",\n (unsigned long long) mRanges[i].location,\n (unsigned long long) (mRanges[i].location + mRanges[i].length));\n }\n }\n return result;\n}\n\nObject * IndexSet::copy()\n{\n return new IndexSet(this);\n}\n\nvoid IndexSet::intersectsRange(Range range)\n{\n uint64_t right = RangeRightBound(range);\n if (right == UINT64_MAX) {\n removeRange(RangeMake(0, range.location - 1));\n }\n else {\n removeRange(RangeMake(0, range.location - 1));\n removeRange(RangeMake(right, UINT64_MAX));\n }\n}\n\n\nHashMap * IndexSet::serializable()\n{\n HashMap * result = Object::serializable();\n Array * ranges = Array::array();\n for(unsigned int i = 0 ; i < mCount ; i ++) {\n ranges->addObject(RangeToString(mRanges[i]));\n }\n result->setObjectForKey(MCSTR(\"ranges\"), ranges);\n return result;\n}\n\nvoid IndexSet::importSerializable(HashMap * serializable)\n{\n Array * ranges = (Array *) serializable->objectForKey(MCSTR(\"ranges\"));\n for(unsigned int i = 0 ; i < ranges->count() ; i ++) {\n String * rangeStr = (String *) ranges->objectAtIndex(i);\n addRange(RangeFromString(rangeStr));\n }\n}\n\nvoid IndexSet::addIndexSet(IndexSet * indexSet)\n{\n for(unsigned int i = 0 ; i < indexSet->rangesCount() ; i ++) {\n addRange(indexSet->allRanges()[i]);\n }\n}\n\nvoid IndexSet::removeIndexSet(IndexSet * indexSet)\n{\n for(unsigned int i = 0 ; i < indexSet->rangesCount() ; i ++) {\n removeRange(indexSet->allRanges()[i]);\n }\n}\n\nvoid IndexSet::intersectsIndexSet(IndexSet * indexSet)\n{\n IndexSet * result = new IndexSet();\n for(unsigned int i = 0 ; i < indexSet->rangesCount() ; i ++) {\n IndexSet * rangeIntersect = (IndexSet *) copy();\n rangeIntersect->intersectsRange(indexSet->allRanges()[i]);\n result->addIndexSet(rangeIntersect);\n rangeIntersect->release();\n }\n removeAllIndexes();\n addIndexSet(result);\n result->release();\n}\n\nstatic void * createObject()\n{\n return new IndexSet();\n}\n\n__attribute__((constructor))\nstatic void initialize()\n{\n Object::registerObjectConstructor(\"mailcore::IndexSet\", &createObject);\n}\n<|endoftext|>"} {"text":"\/**\n * @file\n * @brief Implementation of messenger\n *\n * @copyright MIT License\n *\/\n\n#include \"Messenger.hpp\"\n\n#include \n#include \n#include \n#include \n\n#include \"Message.hpp\"\n#include \"core\/module\/Module.hpp\"\n#include \"core\/utils\/log.h\"\n#include \"core\/utils\/type.h\"\n#include \"delegates.h\"\n\nusing namespace allpix;\n\nMessenger::Messenger() = default;\n#ifdef NDEBUG\nMessenger::~Messenger() = default;\n#else\nMessenger::~Messenger() {\n assert(delegate_to_iterator_.empty());\n}\n#endif\n\n\/\/ Check if the detectors match for the message and the delegate\nstatic bool check_send(BaseMessage* message, BaseDelegate* delegate) {\n if(delegate->getDetector() != nullptr &&\n (message->getDetector() == nullptr || delegate->getDetector()->getName() != message->getDetector()->getName())) {\n return false;\n }\n return true;\n}\n\n\/**\n * Messages should be bound during construction, so this function only gives useful information outside the constructor\n *\/\nbool Messenger::hasReceiver(Module* source, const std::shared_ptr& message) {\n const BaseMessage* inst = message.get();\n std::type_index type_idx = typeid(*inst);\n\n \/\/ Get the name of the output message\n std::string name = source->get_configuration().get(\"output\");\n\n \/\/ Check if a normal specific listener exists\n for(auto& delegate : delegates_[type_idx][name]) {\n if(check_send(message.get(), delegate.get())) {\n return true;\n }\n }\n \/\/ Check if a normal generic listener exists\n for(auto& delegate : delegates_[type_idx][\"*\"]) {\n if(check_send(message.get(), delegate.get())) {\n return true;\n }\n }\n \/\/ Check if a base message specific listener exists\n for(auto& delegate : delegates_[typeid(BaseMessage)][name]) {\n if(check_send(message.get(), delegate.get())) {\n return true;\n }\n }\n \/\/ Check if a base message generic listener exists\n for(auto& delegate : delegates_[typeid(BaseMessage)][\"*\"]) {\n if(check_send(message.get(), delegate.get())) {\n return true;\n }\n }\n\n return false;\n}\n\n\/**\n * Send messages to all specific listeners and also to all generic listeners (listening to all incoming messages)\n *\/\nvoid Messenger::dispatch_message(Module* source, const std::shared_ptr& message, std::string name) {\n \/\/ Get the name of the output message\n if(name == \"-\") {\n name = source->get_configuration().get(\"output\");\n }\n\n bool send = false;\n\n \/\/ Send to specific listeners\n send = dispatch_message(source, message, name, name) || send;\n\n \/\/ Send to generic listeners\n send = dispatch_message(source, message, name, \"*\") || send;\n}\n\n\/**\n * Messages are only dispatched to delegates listening to the exact same type and the exact same name.\n *\/\nbool Messenger::dispatch_message(Module* source,\n const std::shared_ptr& message,\n const std::string& name,\n const std::string& id) {\n bool send = false;\n\n \/\/ Create type identifier from the typeid\n const BaseMessage* inst = message.get();\n std::type_index type_idx = typeid(*inst);\n\n \/\/ Send messages only to their specific listeners\n for(auto& delegate : delegates_[type_idx][id]) {\n if(check_send(message.get(), delegate.get())) {\n LOG(TRACE) << \"Sending message \" << allpix::demangle(type_idx.name()) << \" from \" << source->getUniqueName()\n << \" to \" << delegate->getUniqueName();\n delegate->process(message, name);\n send = true;\n }\n }\n\n \/\/ Dispatch to base message listeners\n assert(typeid(BaseMessage) != typeid(*inst));\n for(auto& delegate : delegates_[typeid(BaseMessage)][id]) {\n if(check_send(message.get(), delegate.get())) {\n LOG(TRACE) << \"Sending message \" << allpix::demangle(type_idx.name()) << \" from \" << source->getUniqueName()\n << \" to generic listener \" << delegate->getUniqueName();\n delegate->process(message, name);\n send = true;\n }\n }\n\n return send;\n}\n\nvoid Messenger::add_delegate(const std::type_info& message_type, Module* module, std::unique_ptr delegate) {\n \/\/ Register generic or specific delegate depending on flag\n std::string message_name;\n if((delegate->getFlags() & MsgFlags::IGNORE_NAME) != MsgFlags::NONE) {\n message_name = \"*\";\n } else {\n message_name = module->get_configuration().get(\"input\");\n }\n\n \/\/ Register delegate internally\n delegates_[std::type_index(message_type)][message_name].push_back(std::move(delegate));\n auto delegate_iter = --delegates_[std::type_index(message_type)][message_name].end();\n delegate_to_iterator_.emplace(delegate_iter->get(),\n std::make_tuple(std::type_index(message_type), message_name, delegate_iter));\n\n \/\/ Add delegate to the module itself\n module->add_delegate(this, delegate_iter->get());\n}\n\n\/**\n * @throws std::out_of_range If a delegate is removed which is never registered\n *\/\nvoid Messenger::remove_delegate(BaseDelegate* delegate) {\n auto iter = delegate_to_iterator_.find(delegate);\n if(iter == delegate_to_iterator_.end()) {\n throw std::out_of_range(\"delegate not found in listeners\");\n }\n delegates_[std::get<0>(iter->second)][std::get<1>(iter->second)].erase(std::get<2>(iter->second));\n delegate_to_iterator_.erase(iter);\n}\nAdd TRACE info about dispatched messages without receiver as it can still be useful\/**\n * @file\n * @brief Implementation of messenger\n *\n * @copyright MIT License\n *\/\n\n#include \"Messenger.hpp\"\n\n#include \n#include \n#include \n#include \n\n#include \"Message.hpp\"\n#include \"core\/module\/Module.hpp\"\n#include \"core\/utils\/log.h\"\n#include \"core\/utils\/type.h\"\n#include \"delegates.h\"\n\nusing namespace allpix;\n\nMessenger::Messenger() = default;\n#ifdef NDEBUG\nMessenger::~Messenger() = default;\n#else\nMessenger::~Messenger() {\n assert(delegate_to_iterator_.empty());\n}\n#endif\n\n\/\/ Check if the detectors match for the message and the delegate\nstatic bool check_send(BaseMessage* message, BaseDelegate* delegate) {\n if(delegate->getDetector() != nullptr &&\n (message->getDetector() == nullptr || delegate->getDetector()->getName() != message->getDetector()->getName())) {\n return false;\n }\n return true;\n}\n\n\/**\n * Messages should be bound during construction, so this function only gives useful information outside the constructor\n *\/\nbool Messenger::hasReceiver(Module* source, const std::shared_ptr& message) {\n const BaseMessage* inst = message.get();\n std::type_index type_idx = typeid(*inst);\n\n \/\/ Get the name of the output message\n std::string name = source->get_configuration().get(\"output\");\n\n \/\/ Check if a normal specific listener exists\n for(auto& delegate : delegates_[type_idx][name]) {\n if(check_send(message.get(), delegate.get())) {\n return true;\n }\n }\n \/\/ Check if a normal generic listener exists\n for(auto& delegate : delegates_[type_idx][\"*\"]) {\n if(check_send(message.get(), delegate.get())) {\n return true;\n }\n }\n \/\/ Check if a base message specific listener exists\n for(auto& delegate : delegates_[typeid(BaseMessage)][name]) {\n if(check_send(message.get(), delegate.get())) {\n return true;\n }\n }\n \/\/ Check if a base message generic listener exists\n for(auto& delegate : delegates_[typeid(BaseMessage)][\"*\"]) {\n if(check_send(message.get(), delegate.get())) {\n return true;\n }\n }\n\n return false;\n}\n\n\/**\n * Send messages to all specific listeners and also to all generic listeners (listening to all incoming messages)\n *\/\nvoid Messenger::dispatch_message(Module* source, const std::shared_ptr& message, std::string name) {\n \/\/ Get the name of the output message\n if(name == \"-\") {\n name = source->get_configuration().get(\"output\");\n }\n\n bool send = false;\n\n \/\/ Send to specific listeners\n send = dispatch_message(source, message, name, name) || send;\n\n \/\/ Send to generic listeners\n send = dispatch_message(source, message, name, \"*\") || send;\n\n \/\/ Display a TRACE log message if the message is send to no receiver\n if(!send) {\n const BaseMessage* inst = message.get();\n LOG(TRACE) << \"Dispatched message \" << allpix::demangle(typeid(*inst).name()) << \" from \" << source->getUniqueName()\n << \" has no receivers!\";\n }\n}\n\n\/**\n * Messages are only dispatched to delegates listening to the exact same type and the exact same name.\n *\/\nbool Messenger::dispatch_message(Module* source,\n const std::shared_ptr& message,\n const std::string& name,\n const std::string& id) {\n bool send = false;\n\n \/\/ Create type identifier from the typeid\n const BaseMessage* inst = message.get();\n std::type_index type_idx = typeid(*inst);\n\n \/\/ Send messages only to their specific listeners\n for(auto& delegate : delegates_[type_idx][id]) {\n if(check_send(message.get(), delegate.get())) {\n LOG(TRACE) << \"Sending message \" << allpix::demangle(type_idx.name()) << \" from \" << source->getUniqueName()\n << \" to \" << delegate->getUniqueName();\n delegate->process(message, name);\n send = true;\n }\n }\n\n \/\/ Dispatch to base message listeners\n assert(typeid(BaseMessage) != typeid(*inst));\n for(auto& delegate : delegates_[typeid(BaseMessage)][id]) {\n if(check_send(message.get(), delegate.get())) {\n LOG(TRACE) << \"Sending message \" << allpix::demangle(type_idx.name()) << \" from \" << source->getUniqueName()\n << \" to generic listener \" << delegate->getUniqueName();\n delegate->process(message, name);\n send = true;\n }\n }\n\n return send;\n}\n\nvoid Messenger::add_delegate(const std::type_info& message_type, Module* module, std::unique_ptr delegate) {\n \/\/ Register generic or specific delegate depending on flag\n std::string message_name;\n if((delegate->getFlags() & MsgFlags::IGNORE_NAME) != MsgFlags::NONE) {\n message_name = \"*\";\n } else {\n message_name = module->get_configuration().get(\"input\");\n }\n\n \/\/ Register delegate internally\n delegates_[std::type_index(message_type)][message_name].push_back(std::move(delegate));\n auto delegate_iter = --delegates_[std::type_index(message_type)][message_name].end();\n delegate_to_iterator_.emplace(delegate_iter->get(),\n std::make_tuple(std::type_index(message_type), message_name, delegate_iter));\n\n \/\/ Add delegate to the module itself\n module->add_delegate(this, delegate_iter->get());\n}\n\n\/**\n * @throws std::out_of_range If a delegate is removed which is never registered\n *\/\nvoid Messenger::remove_delegate(BaseDelegate* delegate) {\n auto iter = delegate_to_iterator_.find(delegate);\n if(iter == delegate_to_iterator_.end()) {\n throw std::out_of_range(\"delegate not found in listeners\");\n }\n delegates_[std::get<0>(iter->second)][std::get<1>(iter->second)].erase(std::get<2>(iter->second));\n delegate_to_iterator_.erase(iter);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/idle_timer.h\"\n\n\/\/ We may not want to port idle_timer to Linux, but we have implemented it\n\/\/ anyway. Define this to 1 to enable the Linux idle timer and then add the\n\/\/ libs that need to be linked (Xss).\n#define ENABLE_XSS_SUPPORT 0\n\n#if defined(OS_MACOSX)\n#include \n#endif\n\n#if defined(OS_LINUX) && ENABLE_XSS_SUPPORT\n\/\/ We may not want to port idle_timer to Linux, but we have implemented it\n\/\/ anyway. Remove the 0 above if we want it.\n#include \n#include \n#include \"base\/lazy_instance.h\"\n#include \"base\/thread_local.h\"\n#endif\n\n#include \"base\/message_loop.h\"\n#include \"base\/time.h\"\n\nnamespace base {\n\n#if defined(OS_WIN)\nbool OSIdleTimeSource(int32 *milliseconds_interval_since_last_event) {\n LASTINPUTINFO lastInputInfo;\n lastInputInfo.cbSize = sizeof(lastInputInfo);\n if (GetLastInputInfo(&lastInputInfo) == 0) {\n return false;\n }\n int32 last_input_time = lastInputInfo.dwTime;\n \n \/\/ Note: On Windows GetLastInputInfo returns a 32bit value which rolls over \n \/\/ ~49days.\n int32 current_time = GetTickCount();\n int32 delta = current_time - last_input_time;\n \/\/ delta will go negative if we've been idle for 2GB of ticks.\n if (delta < 0)\n delta = -delta; \n *milliseconds_interval_since_last_event = delta;\n return true;\n}\n#elif defined(OS_MACOSX)\nbool OSIdleTimeSource(int32 *milliseconds_interval_since_last_event) {\n *milliseconds_interval_since_last_event = \n CGEventSourceSecondsSinceLastEventType(\n kCGEventSourceStateCombinedSessionState, \n kCGAnyInputEventType) * 1000.0;\n return true;\n}\n#elif defined(OS_LINUX) && ENABLE_XSS_SUPPORT\nclass IdleState {\n public:\n IdleState() {\n int event_base, error_base;\n have_idle_info_ = XScreenSaverQueryExtension(GDK_DISPLAY(), &event_base,\n &error_base);\n if (have_idle_info_)\n *idle_info_.Get() = XScreenSaverAllocInfo();\n }\n\n ~IdleState() {\n if (*idle_info_.Get()) {\n XFree(*idle_info_.Get());\n idle_info_.~ThreadLocalPointer();\n }\n }\n\n int32 IdleTime() {\n if (have_idle_info_ && idle_info_.Get()) {\n XScreenSaverQueryInfo(GDK_DISPLAY(), GDK_ROOT_WINDOW(),\n *idle_info_.Get());\n return (*idle_info_.Get())->idle;\n }\n return -1;\n }\n\n private:\n bool have_idle_info_;\n ThreadLocalPointer idle_info_;\n\n DISALLOW_COPY_AND_ASSIGN(IdleState);\n};\n\nbool OSIdleTimeSource(int32* milliseconds_interval_since_last_event) {\n static LazyInstance state_instance(base::LINKER_INITIALIZED);\n IdleState* state = state_instance.Pointer();\n int32 idle_time = state->IdleTime();\n if (0 < idle_time) {\n *milliseconds_interval_since_last_event = idle_time;\n return true;\n }\n return false;\n}\n#endif\n\nIdleTimer::IdleTimer(TimeDelta idle_time, bool repeat)\n : idle_interval_(idle_time),\n repeat_(repeat),\n idle_time_source_(OSIdleTimeSource) {\n DCHECK_EQ(MessageLoop::TYPE_UI, MessageLoop::current()->type()) <<\n \"Requires a thread that processes Windows UI events\";\n}\n\nIdleTimer::~IdleTimer() {\n Stop();\n}\n\nvoid IdleTimer::Start() {\n StartTimer();\n}\n\nvoid IdleTimer::Stop() {\n timer_.Stop();\n}\n\nvoid IdleTimer::Run() {\n \/\/ Verify we can fire the idle timer.\n if (TimeUntilIdle().InMilliseconds() <= 0) {\n OnIdle();\n last_time_fired_ = Time::Now();\n }\n Stop();\n StartTimer(); \/\/ Restart the timer for next run.\n}\n\nvoid IdleTimer::StartTimer() {\n DCHECK(!timer_.IsRunning());\n TimeDelta delay = TimeUntilIdle();\n if (delay.InMilliseconds() < 0)\n delay = TimeDelta();\n timer_.Start(delay, this, &IdleTimer::Run);\n}\n\nTimeDelta IdleTimer::CurrentIdleTime() {\n int32 interval = 0;\n if (idle_time_source_(&interval)) {\n return TimeDelta::FromMilliseconds(interval);\n }\n NOTREACHED();\n return TimeDelta::FromMilliseconds(0);\n}\n\nTimeDelta IdleTimer::TimeUntilIdle() {\n TimeDelta time_since_last_fire = Time::Now() - last_time_fired_;\n TimeDelta current_idle_time = CurrentIdleTime();\n if (current_idle_time > time_since_last_fire) {\n if (repeat_)\n return idle_interval_ - time_since_last_fire;\n return idle_interval_;\n }\n return idle_interval_ - current_idle_time;\n}\n\n} \/\/ namespace base\n\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/idle_timer.h\"\n\n\/\/ We may not want to port idle_timer to Linux, but we have implemented it\n\/\/ anyway. Define this to 1 to enable the Linux idle timer and then add the\n\/\/ libs that need to be linked (Xss).\n#define ENABLE_XSS_SUPPORT 0\n\n#if defined(OS_MACOSX)\n#include \n#endif\n\n#if defined(OS_LINUX) && ENABLE_XSS_SUPPORT\n\/\/ We may not want to port idle_timer to Linux, but we have implemented it\n\/\/ anyway. Remove the 0 above if we want it.\n#include \n#include \n#include \"base\/lazy_instance.h\"\n#include \"base\/thread_local.h\"\n#endif\n\n#include \"base\/message_loop.h\"\n#include \"base\/time.h\"\n\nnamespace base {\n\n#if defined(OS_WIN)\nbool OSIdleTimeSource(int32 *milliseconds_interval_since_last_event) {\n LASTINPUTINFO lastInputInfo;\n lastInputInfo.cbSize = sizeof(lastInputInfo);\n if (GetLastInputInfo(&lastInputInfo) == 0) {\n return false;\n }\n int32 last_input_time = lastInputInfo.dwTime;\n \n \/\/ Note: On Windows GetLastInputInfo returns a 32bit value which rolls over \n \/\/ ~49days.\n int32 current_time = GetTickCount();\n int32 delta = current_time - last_input_time;\n \/\/ delta will go negative if we've been idle for 2GB of ticks.\n if (delta < 0)\n delta = -delta; \n *milliseconds_interval_since_last_event = delta;\n return true;\n}\n#elif defined(OS_MACOSX)\nbool OSIdleTimeSource(int32 *milliseconds_interval_since_last_event) {\n *milliseconds_interval_since_last_event = \n CGEventSourceSecondsSinceLastEventType(\n kCGEventSourceStateCombinedSessionState, \n kCGAnyInputEventType) * 1000.0;\n return true;\n}\n#elif defined(OS_LINUX) && ENABLE_XSS_SUPPORT\nclass IdleState {\n public:\n IdleState() {\n int event_base, error_base;\n have_idle_info_ = XScreenSaverQueryExtension(GDK_DISPLAY(), &event_base,\n &error_base);\n if (have_idle_info_)\n idle_info_.Set(XScreenSaverAllocInfo());\n }\n\n ~IdleState() {\n if (idle_info_.Get()) {\n XFree(idle_info_.Get());\n idle_info_.~ThreadLocalPointer();\n }\n }\n\n int32 IdleTime() {\n if (have_idle_info_ && idle_info_.Get()) {\n XScreenSaverQueryInfo(GDK_DISPLAY(), GDK_ROOT_WINDOW(),\n idle_info_.Get());\n return idle_info_.Get()->idle;\n }\n return -1;\n }\n\n private:\n bool have_idle_info_;\n ThreadLocalPointer idle_info_;\n\n DISALLOW_COPY_AND_ASSIGN(IdleState);\n};\n\nbool OSIdleTimeSource(int32* milliseconds_interval_since_last_event) {\n static LazyInstance state_instance(base::LINKER_INITIALIZED);\n IdleState* state = state_instance.Pointer();\n int32 idle_time = state->IdleTime();\n if (0 < idle_time) {\n *milliseconds_interval_since_last_event = idle_time;\n return true;\n }\n return false;\n}\n#endif\n\nIdleTimer::IdleTimer(TimeDelta idle_time, bool repeat)\n : idle_interval_(idle_time),\n repeat_(repeat),\n idle_time_source_(OSIdleTimeSource) {\n DCHECK_EQ(MessageLoop::TYPE_UI, MessageLoop::current()->type()) <<\n \"Requires a thread that processes Windows UI events\";\n}\n\nIdleTimer::~IdleTimer() {\n Stop();\n}\n\nvoid IdleTimer::Start() {\n StartTimer();\n}\n\nvoid IdleTimer::Stop() {\n timer_.Stop();\n}\n\nvoid IdleTimer::Run() {\n \/\/ Verify we can fire the idle timer.\n if (TimeUntilIdle().InMilliseconds() <= 0) {\n OnIdle();\n last_time_fired_ = Time::Now();\n }\n Stop();\n StartTimer(); \/\/ Restart the timer for next run.\n}\n\nvoid IdleTimer::StartTimer() {\n DCHECK(!timer_.IsRunning());\n TimeDelta delay = TimeUntilIdle();\n if (delay.InMilliseconds() < 0)\n delay = TimeDelta();\n timer_.Start(delay, this, &IdleTimer::Run);\n}\n\nTimeDelta IdleTimer::CurrentIdleTime() {\n int32 interval = 0;\n if (idle_time_source_(&interval)) {\n return TimeDelta::FromMilliseconds(interval);\n }\n NOTREACHED();\n return TimeDelta::FromMilliseconds(0);\n}\n\nTimeDelta IdleTimer::TimeUntilIdle() {\n TimeDelta time_since_last_fire = Time::Now() - last_time_fired_;\n TimeDelta current_idle_time = CurrentIdleTime();\n if (current_idle_time > time_since_last_fire) {\n if (repeat_)\n return idle_interval_ - time_since_last_fire;\n return idle_interval_;\n }\n return idle_interval_ - current_idle_time;\n}\n\n} \/\/ namespace base\n<|endoftext|>"} {"text":"#include \"lcio.h\"\n#include \n\n#include \"IO\/LCReader.h\"\n#include \"IMPL\/LCTOOLS.h\"\n#include \"EVENT\/LCRunHeader.h\" \n\n#include \"EVENT\/SimCalorimeterHit.h\" \n#include \"EVENT\/CalorimeterHit.h\" \n#include \"EVENT\/RawCalorimeterHit.h\" \n\/\/ #include \"EVENT\/SimTrackerHit.h\" \n\n#include \"UTIL\/CellIDDecoder.h\"\n\n#include \n\nusing namespace std ;\nusing namespace lcio ;\n\n\/** dump the given event to screen\n *\/\n\nint main(int argc, char** argv ){\n\n\n char* FILEN ;\n int runNumber=0 ;\n int evtNumber=0 ;\n int nthEvent=1 ;\n\n \/\/ read file name from command line (only argument) \n if( argc < 3 ) {\n\n cout << \" usage: dumpevent filename runNum evtNum \" << endl ;\n cout << \" or: dumpevent filename n \" << endl ;\n cout << \" where the first dumps the event with the specified run and event number\" << endl ;\n cout << \" and the second simply dumps the n-th event in the file\" << endl ;\n\n exit(1) ;\n }\n \n FILEN = argv[1] ;\n\n bool dumpNthEvent( argc == 3 ) ;\n \n\n\n if( dumpNthEvent ) {\n\n nthEvent = atoi( argv[2] ) ;\n\n if( nthEvent < 1 ) {\n\n cout << \" usage: dumpevent filename n - whith n > 0 ! \" << endl ;\n \n exit(1) ;\n }\n\n }else{\n\n runNumber = atoi( argv[2] ) ;\n evtNumber = atoi( argv[3] ) ;\n }\n \n\n \/\/ set the default encoding for cellid's according to the old Mokka convention\n CellIDDecoder::setDefaultEncoding(\"M:3,S-1:3,I:9,J:9,K-1:6\") ;\n CellIDDecoder::setDefaultEncoding(\"M:3,S-1:3,I:9,J:9,K-1:6\") ;\n CellIDDecoder::setDefaultEncoding(\"M:3,S-1:3,I:9,J:9,K-1:6\") ;\n\n LCReader* lcReader ;\n if ( getenv (\"LCIO_DIRECT_ACCESS\") !=0 )\n lcReader = LCFactory::getInstance()->createLCReader(LCReader::directAccess) ;\n else\n lcReader = LCFactory::getInstance()->createLCReader() ;\n \n LCEvent* evt(0) ;\n\n try{\n \n lcReader->open( FILEN ) ;\n \n if( dumpNthEvent ) {\n \n if( nthEvent > 1 )\n\t lcReader->skipNEvents( nthEvent - 1 ) ;\n\n evt = lcReader->readNextEvent() ; \n \n }else{\n \n evt = lcReader->readEvent(runNumber, evtNumber) ; \n }\n \n \n \/\/ } catch( EndOfDataException& e) {\n \/\/ cout << \" couldn't find event \" << evtNumber << \" - run \" << runNumber \n \/\/ \t << \" in file \" << FILEN << endl ; \n \/\/ exit(1) ;\n \n if( !evt ){\n\n if(dumpNthEvent){\n\n\t cout << \" less than \" << nthEvent << \" events in file \" << FILEN << endl ; \n\t \n }else{\n\n\t cout << \" couldn't find event \" << evtNumber << \" - run \" << runNumber \n\t << \" in file \" << FILEN << endl ; \n } \n \n exit(1) ;\n }\n\n LCTOOLS::dumpEventDetailed( evt ) ;\n \n \n lcReader->close() ;\n \n }\n catch( IOException& e) {\n cout << e.what() << endl ;\n exit(1) ;\n }\n\n\/\/ catch( Exception& e) {\n\/\/ cout << e.what() << endl ;\n\/\/ exit(1) ;\n\/\/ }\n return 0 ;\n}\n\nswitch to direct access automatically when evtnum and runnum specified#include \"lcio.h\"\n#include \n\n#include \"IO\/LCReader.h\"\n#include \"IMPL\/LCTOOLS.h\"\n#include \"EVENT\/LCRunHeader.h\" \n\n#include \"EVENT\/SimCalorimeterHit.h\" \n#include \"EVENT\/CalorimeterHit.h\" \n#include \"EVENT\/RawCalorimeterHit.h\" \n\/\/ #include \"EVENT\/SimTrackerHit.h\" \n\n#include \"UTIL\/CellIDDecoder.h\"\n\n#include \n\nusing namespace std ;\nusing namespace lcio ;\n\n\/** dump the given event to screen\n *\/\n\nint main(int argc, char** argv ){\n\n\n char* FILEN ;\n int runNumber=0 ;\n int evtNumber=0 ;\n int nthEvent=1 ;\n\n \/\/ read file name from command line (only argument) \n if( argc < 3 ) {\n\n cout << \" usage: dumpevent filename runNum evtNum \" << endl ;\n cout << \" or: dumpevent filename n \" << endl ;\n cout << \" where the first dumps the event with the specified run and event number\" << endl ;\n cout << \" and the second simply dumps the n-th event in the file\" << endl ;\n\n exit(1) ;\n }\n \n FILEN = argv[1] ;\n\n bool dumpNthEvent( argc == 3 ) ;\n \n\n\n if( dumpNthEvent ) {\n\n nthEvent = atoi( argv[2] ) ;\n\n if( nthEvent < 1 ) {\n\n cout << \" usage: dumpevent filename n - whith n > 0 ! \" << endl ;\n \n exit(1) ;\n }\n\n }else{\n\n runNumber = atoi( argv[2] ) ;\n evtNumber = atoi( argv[3] ) ;\n }\n \n\n \/\/ set the default encoding for cellid's according to the old Mokka convention\n CellIDDecoder::setDefaultEncoding(\"M:3,S-1:3,I:9,J:9,K-1:6\") ;\n CellIDDecoder::setDefaultEncoding(\"M:3,S-1:3,I:9,J:9,K-1:6\") ;\n CellIDDecoder::setDefaultEncoding(\"M:3,S-1:3,I:9,J:9,K-1:6\") ;\n\n LCReader* lcReader ;\n if( dumpNthEvent ) \n lcReader = LCFactory::getInstance()->createLCReader() ;\n else\n lcReader = LCFactory::getInstance()->createLCReader(LCReader::directAccess) ;\n \n LCEvent* evt(0) ;\n\n try{\n \n lcReader->open( FILEN ) ;\n \n if( dumpNthEvent ) {\n \n if( nthEvent > 1 )\n\t lcReader->skipNEvents( nthEvent - 1 ) ;\n\n evt = lcReader->readNextEvent() ; \n \n }else{\n \n evt = lcReader->readEvent(runNumber, evtNumber) ; \n }\n \n \n \/\/ } catch( EndOfDataException& e) {\n \/\/ cout << \" couldn't find event \" << evtNumber << \" - run \" << runNumber \n \/\/ \t << \" in file \" << FILEN << endl ; \n \/\/ exit(1) ;\n \n if( !evt ){\n\n if(dumpNthEvent){\n\n\t cout << \" less than \" << nthEvent << \" events in file \" << FILEN << endl ; \n\t \n }else{\n\n\t cout << \" couldn't find event \" << evtNumber << \" - run \" << runNumber \n\t << \" in file \" << FILEN << endl ; \n } \n \n exit(1) ;\n }\n\n LCTOOLS::dumpEventDetailed( evt ) ;\n \n \n lcReader->close() ;\n \n }\n catch( IOException& e) {\n cout << e.what() << endl ;\n exit(1) ;\n }\n\n\/\/ catch( Exception& e) {\n\/\/ cout << e.what() << endl ;\n\/\/ exit(1) ;\n\/\/ }\n return 0 ;\n}\n\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _SVX_POSTDLG_HXX\n#define _SVX_POSTDLG_HXX\n\n\/\/ include ---------------------------------------------------------------\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ class SvxPostItDialog -------------------------------------------------\n\/*\n {k:\\svx\\prototyp\\dialog\\memo.bmp}\n\n [Description]\n In this dialog a note can be created or edited. If the\n application holds a list of notes, it can be iterated\n over this list with links.\n\n [Items]\n \n \n \n*\/\n\nclass SvxPostItDialog : public SfxModalDialog\n{\npublic:\n SvxPostItDialog( Window* pParent, const SfxItemSet& rCoreSet,\n sal_Bool bPrevNext = sal_False, sal_Bool bRedline = sal_False );\n ~SvxPostItDialog();\n\n static sal_uInt16* GetRanges();\n const SfxItemSet* GetOutputItemSet() const { return pOutSet; }\n\n Link GetPrevHdl() const { return aPrevHdlLink; }\n void SetPrevHdl( const Link& rLink )\n { aPrevHdlLink = rLink; }\n Link GetNextHdl() const { return aNextHdlLink; }\n void SetNextHdl( const Link& rLink )\n { aNextHdlLink = rLink; }\n\n void EnableTravel(sal_Bool bNext, sal_Bool bPrev);\n inline String GetNote() { return aEditED.GetText(); }\n inline void SetNote(const String& rTxt) { aEditED.SetText(rTxt); }\n\n void ShowLastAuthor(const String& rAuthor, const String& rDate);\n inline void DontChangeAuthor() { aAuthorBtn.Enable(sal_False); }\n inline void HideAuthor() { aAuthorBtn.Hide(); }\n inline void SetReadonlyPostIt(sal_Bool bDisable)\n {\n aOKBtn.Enable( !bDisable );\n aEditED.SetReadOnly( bDisable );\n aAuthorBtn.Enable( !bDisable );\n }\n inline sal_Bool IsOkEnabled() const { return aOKBtn.IsEnabled(); }\n\nprivate:\n FixedLine aPostItFL;\n FixedText aLastEditLabelFT;\n FixedInfo aLastEditFT;\n\n FixedText aEditFT;\n MultiLineEdit aEditED;\n\n FixedText aAuthorFT;\n PushButton aAuthorBtn;\n\n OKButton aOKBtn;\n CancelButton aCancelBtn;\n HelpButton aHelpBtn;\n\n ImageButton aPrevBtn;\n ImageButton aNextBtn;\n\n const SfxItemSet& rSet;\n SfxItemSet* pOutSet;\n\n Link aPrevHdlLink;\n Link aNextHdlLink;\n\n#ifdef _SVX_POSTDLG_CXX\n DECL_LINK(Stamp, void *);\n DECL_LINK(OKHdl, void *);\n DECL_LINK(PrevHdl, void *);\n DECL_LINK(NextHdl, void *);\n#endif\n};\n\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nHide aAuthorFT fixed text, too, when the button is hidden\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _SVX_POSTDLG_HXX\n#define _SVX_POSTDLG_HXX\n\n\/\/ include ---------------------------------------------------------------\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ class SvxPostItDialog -------------------------------------------------\n\/*\n {k:\\svx\\prototyp\\dialog\\memo.bmp}\n\n [Description]\n In this dialog a note can be created or edited. If the\n application holds a list of notes, it can be iterated\n over this list with links.\n\n [Items]\n \n \n \n*\/\n\nclass SvxPostItDialog : public SfxModalDialog\n{\npublic:\n SvxPostItDialog( Window* pParent, const SfxItemSet& rCoreSet,\n sal_Bool bPrevNext = sal_False, sal_Bool bRedline = sal_False );\n ~SvxPostItDialog();\n\n static sal_uInt16* GetRanges();\n const SfxItemSet* GetOutputItemSet() const { return pOutSet; }\n\n Link GetPrevHdl() const { return aPrevHdlLink; }\n void SetPrevHdl( const Link& rLink )\n { aPrevHdlLink = rLink; }\n Link GetNextHdl() const { return aNextHdlLink; }\n void SetNextHdl( const Link& rLink )\n { aNextHdlLink = rLink; }\n\n void EnableTravel(sal_Bool bNext, sal_Bool bPrev);\n inline String GetNote() { return aEditED.GetText(); }\n inline void SetNote(const String& rTxt) { aEditED.SetText(rTxt); }\n\n void ShowLastAuthor(const String& rAuthor, const String& rDate);\n inline void DontChangeAuthor() { aAuthorBtn.Enable(sal_False); }\n inline void HideAuthor() { aAuthorFT.Hide(); aAuthorBtn.Hide(); }\n inline void SetReadonlyPostIt(sal_Bool bDisable)\n {\n aOKBtn.Enable( !bDisable );\n aEditED.SetReadOnly( bDisable );\n aAuthorBtn.Enable( !bDisable );\n }\n inline sal_Bool IsOkEnabled() const { return aOKBtn.IsEnabled(); }\n\nprivate:\n FixedLine aPostItFL;\n FixedText aLastEditLabelFT;\n FixedInfo aLastEditFT;\n\n FixedText aEditFT;\n MultiLineEdit aEditED;\n\n FixedText aAuthorFT;\n PushButton aAuthorBtn;\n\n OKButton aOKBtn;\n CancelButton aCancelBtn;\n HelpButton aHelpBtn;\n\n ImageButton aPrevBtn;\n ImageButton aNextBtn;\n\n const SfxItemSet& rSet;\n SfxItemSet* pOutSet;\n\n Link aPrevHdlLink;\n Link aNextHdlLink;\n\n#ifdef _SVX_POSTDLG_CXX\n DECL_LINK(Stamp, void *);\n DECL_LINK(OKHdl, void *);\n DECL_LINK(PrevHdl, void *);\n DECL_LINK(NextHdl, void *);\n#endif\n};\n\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"#include \"..\/..\/..\/Generator\/Generator.h\"\n#include \"..\/..\/..\/Node\/Node.h\"\n#include \"..\/..\/..\/ParseResult\/ParseResult.h\"\n#include \"..\/..\/..\/Element\/Function\/Function.h\"\n#include \"..\/Inst\/Inst.h\"\n#include \"..\/..\/..\/llvm_Function.h\"\n\nnamespace dale\n{\nnamespace Form\n{\nnamespace Proc\n{\nnamespace Setf\n{\nbool parse(Generator *gen,\n Element::Function *fn,\n llvm::BasicBlock *block,\n Node *node,\n bool get_address,\n bool prefixed_with_core,\n ParseResult *pr)\n{\n Context *ctx = gen->ctx;\n\n assert(node->list && \"parseSetf must receive a list!\");\n\n symlist *lst = node->list;\n\n if (!ctx->er->assertArgNums(\"setf\", node, 2, 2)) {\n return false;\n }\n\n \/* Used to use getAddress for the first argument, but now setf\n * always takes a pointer as its first argument, to facilitate\n * overloading etc. *\/\n\n ParseResult pr_variable;\n bool res =\n Form::Proc::Inst::parse(gen, fn, block, (*lst)[1], false, \n false, NULL,\n &pr_variable);\n\n if (!res) {\n return false;\n }\n\n \/* Make sure that the first argument is a pointer. *\/\n\n if (!pr_variable.type->points_to) {\n Error *e = new Error(\n ErrorInst::Generator::IncorrectArgType,\n (*lst)[1],\n \"setf\", \"a pointer\", \"1\", \"a value\"\n );\n ctx->er->addError(e);\n return false;\n }\n\n \/* Can't modify const variables. *\/\n\n if (pr_variable.type->points_to->is_const) {\n Error *e = new Error(\n ErrorInst::Generator::CannotModifyConstVariable,\n node\n );\n ctx->er->addError(e);\n return false;\n }\n\n Node *val_node = (*lst)[2];\n val_node = gen->parseOptionalMacroCall(val_node);\n if (!val_node) {\n return false;\n }\n\n llvm::IRBuilder<> builder(pr_variable.block);\n ParseResult pr_value;\n Element::Variable *var_value = NULL;\n std::vector *lst = val_node->list;\n\n \/* If the value is a variable, or a variable dereference, load the\n * underlying value directly, to shortcut setf-copy for types that\n * define it. *\/\n\n if (val_node->is_token\n && (var_value = ctx->getVariable(\n val_node->token->str_value.c_str()))) {\n pr_value.value = var_value->value;\n pr_value.type = ctx->tr->getPointerType(var_value->type);\n pr_value.do_not_destruct = 1;\n pr_value.block = pr_variable.block;\n } else if (val_node->is_list\n && (lst->size() == 2)\n && (lst->at(0)->is_token)\n && (!lst->at(0)->token->str_value.compare(\"@\"))\n && (lst->at(1)->is_token)\n && (var_value = ctx->getVariable(\n lst->at(1)->token->str_value.c_str()))) {\n pr_value.value = builder.CreateLoad(var_value->value);\n pr_value.type = var_value->type;\n pr_value.do_not_destruct = 1;\n pr_value.block = pr_variable.block;\n } else {\n res =\n Form::Proc::Inst::parse(gen, \n fn, pr_variable.block, val_node, false,\n false,\n pr_variable.type->points_to,\n &pr_value\n );\n\n if (!res) {\n return false;\n }\n }\n\n builder.SetInsertPoint(pr_value.block);\n\n \/* If overridden setf exists, and pr_value is a value of the\n * pointee type of pr_variable, then call overridden setf\n * after allocating memory for pr_value and copying it into\n * place. *\/\n\n if (!prefixed_with_core\n && pr_value.type->isEqualTo(pr_variable.type->points_to)) {\n std::vector types;\n types.push_back(pr_variable.type);\n types.push_back(pr_variable.type);\n Element::Function *over_setf =\n ctx->getFunction(\"setf-assign\", &types, NULL, 0);\n if (!over_setf) {\n goto cont1;\n }\n llvm::Value *new_ptr2 = llvm::cast(\n builder.CreateAlloca(\n ctx->toLLVMType(pr_value.type, \n NULL, false,\n false)\n )\n );\n builder.CreateStore(pr_value.value, new_ptr2);\n std::vector call_args;\n call_args.push_back(pr_variable.value);\n call_args.push_back(new_ptr2);\n llvm::Value *ret =\n builder.CreateCall(over_setf->llvm_function,\n llvm::ArrayRef(call_args));\n\n ParseResult temp;\n pr_variable.block = pr_value.block;\n bool mres = gen->destructIfApplicable(&pr_variable, &builder, &temp);\n if (!mres) {\n return false;\n }\n pr_value.block = temp.block;\n mres = gen->destructIfApplicable(&pr_value, &builder, &temp);\n if (!mres) {\n return false;\n }\n pr->set(temp.block, ctx->tr->type_bool, ret);\n return true;\n }\n\ncont1:\n\n \/* If an appropriate setf definition exists, which matches\n * the arguments exactly, then use it. *\/\n\n if (!prefixed_with_core) {\n std::vector types;\n types.push_back(pr_variable.type);\n types.push_back(pr_value.type);\n Element::Function *over_setf =\n ctx->getFunction(\"setf-assign\", &types, NULL, 0);\n if (!over_setf) {\n goto cont2;\n }\n std::vector call_args;\n call_args.push_back(pr_variable.value);\n call_args.push_back(pr_value.value);\n llvm::Value *ret =\n builder.CreateCall(over_setf->llvm_function,\n llvm::ArrayRef(call_args));\n\n ParseResult temp;\n pr_variable.block = pr_value.block;\n bool mres = gen->destructIfApplicable(&pr_variable, &builder, &temp);\n if (!mres) {\n return false;\n }\n pr_value.block = temp.block;\n mres = gen->destructIfApplicable(&pr_value, &builder, &temp);\n if (!mres) {\n return false;\n }\n\n pr->set(temp.block, ctx->tr->type_bool, ret);\n return true;\n }\n\ncont2:\n\n \/* var_value is only present to support the overridden set\n * operations: if this point is reached, then fall back to the\n * standard form-processing logic. *\/\n\n if (var_value) {\n res =\n Form::Proc::Inst::parse(gen, \n fn, pr_value.block, val_node, false,\n false,\n pr_variable.type->points_to,\n &pr_value\n );\n\n if (!res) {\n return false;\n }\n }\n\n if (pr_value.type->isEqualTo(pr_variable.type->points_to)) {\n builder.CreateStore(pr_value.value, pr_variable.value);\n\n ParseResult temp;\n pr_variable.block = pr_value.block;\n bool mres = gen->destructIfApplicable(&pr_variable, &builder, &temp);\n if (!mres) {\n return false;\n }\n pr_value.block = temp.block;\n mres = gen->destructIfApplicable(&pr_value, &builder, &temp);\n if (!mres) {\n return false;\n }\n\n pr->set(temp.block, ctx->tr->type_bool, \n llvm::ConstantInt::get(\n llvm::IntegerType::get(llvm::getGlobalContext(), 1), 1\n ));\n pr->do_not_copy_with_setf = 1;\n return true;\n }\n\n \/* todo: it would be good to also show the setf-assign\n * candidates here, if applicable. *\/\n ctx->er->assertTypeEquality(\"setf\", (*lst)[2],\n pr_value.type,\n pr_variable.type->points_to,\n false);\n\n return false;\n}\n}\n}\n}\n}\nbad variable name#include \"..\/..\/..\/Generator\/Generator.h\"\n#include \"..\/..\/..\/Node\/Node.h\"\n#include \"..\/..\/..\/ParseResult\/ParseResult.h\"\n#include \"..\/..\/..\/Element\/Function\/Function.h\"\n#include \"..\/Inst\/Inst.h\"\n#include \"..\/..\/..\/llvm_Function.h\"\n\nnamespace dale\n{\nnamespace Form\n{\nnamespace Proc\n{\nnamespace Setf\n{\nbool parse(Generator *gen,\n Element::Function *fn,\n llvm::BasicBlock *block,\n Node *node,\n bool get_address,\n bool prefixed_with_core,\n ParseResult *pr)\n{\n Context *ctx = gen->ctx;\n\n assert(node->list && \"parseSetf must receive a list!\");\n\n symlist *lst = node->list;\n\n if (!ctx->er->assertArgNums(\"setf\", node, 2, 2)) {\n return false;\n }\n\n \/* Used to use getAddress for the first argument, but now setf\n * always takes a pointer as its first argument, to facilitate\n * overloading etc. *\/\n\n ParseResult pr_variable;\n bool res =\n Form::Proc::Inst::parse(gen, fn, block, (*lst)[1], false, \n false, NULL,\n &pr_variable);\n\n if (!res) {\n return false;\n }\n\n \/* Make sure that the first argument is a pointer. *\/\n\n if (!pr_variable.type->points_to) {\n Error *e = new Error(\n ErrorInst::Generator::IncorrectArgType,\n (*lst)[1],\n \"setf\", \"a pointer\", \"1\", \"a value\"\n );\n ctx->er->addError(e);\n return false;\n }\n\n \/* Can't modify const variables. *\/\n\n if (pr_variable.type->points_to->is_const) {\n Error *e = new Error(\n ErrorInst::Generator::CannotModifyConstVariable,\n node\n );\n ctx->er->addError(e);\n return false;\n }\n\n Node *val_node = (*lst)[2];\n val_node = gen->parseOptionalMacroCall(val_node);\n if (!val_node) {\n return false;\n }\n\n llvm::IRBuilder<> builder(pr_variable.block);\n ParseResult pr_value;\n Element::Variable *var_value = NULL;\n symlist *vlst = val_node->list;\n\n \/* If the value is a variable, or a variable dereference, load the\n * underlying value directly, to shortcut setf-copy for types that\n * define it. *\/\n\n if (val_node->is_token\n && (var_value = ctx->getVariable(\n val_node->token->str_value.c_str()))) {\n pr_value.value = var_value->value;\n pr_value.type = ctx->tr->getPointerType(var_value->type);\n pr_value.do_not_destruct = 1;\n pr_value.block = pr_variable.block;\n } else if (val_node->is_list\n && (vlst->size() == 2)\n && (vlst->at(0)->is_token)\n && (!vlst->at(0)->token->str_value.compare(\"@\"))\n && (vlst->at(1)->is_token)\n && (var_value = ctx->getVariable(\n vlst->at(1)->token->str_value.c_str()))) {\n pr_value.value = builder.CreateLoad(var_value->value);\n pr_value.type = var_value->type;\n pr_value.do_not_destruct = 1;\n pr_value.block = pr_variable.block;\n } else {\n res =\n Form::Proc::Inst::parse(gen, \n fn, pr_variable.block, val_node, false,\n false,\n pr_variable.type->points_to,\n &pr_value\n );\n\n if (!res) {\n return false;\n }\n }\n\n builder.SetInsertPoint(pr_value.block);\n\n \/* If overridden setf exists, and pr_value is a value of the\n * pointee type of pr_variable, then call overridden setf\n * after allocating memory for pr_value and copying it into\n * place. *\/\n\n if (!prefixed_with_core\n && pr_value.type->isEqualTo(pr_variable.type->points_to)) {\n std::vector types;\n types.push_back(pr_variable.type);\n types.push_back(pr_variable.type);\n Element::Function *over_setf =\n ctx->getFunction(\"setf-assign\", &types, NULL, 0);\n if (!over_setf) {\n goto cont1;\n }\n llvm::Value *new_ptr2 = llvm::cast(\n builder.CreateAlloca(\n ctx->toLLVMType(pr_value.type, \n NULL, false,\n false)\n )\n );\n builder.CreateStore(pr_value.value, new_ptr2);\n std::vector call_args;\n call_args.push_back(pr_variable.value);\n call_args.push_back(new_ptr2);\n llvm::Value *ret =\n builder.CreateCall(over_setf->llvm_function,\n llvm::ArrayRef(call_args));\n\n ParseResult temp;\n pr_variable.block = pr_value.block;\n bool mres = gen->destructIfApplicable(&pr_variable, &builder, &temp);\n if (!mres) {\n return false;\n }\n pr_value.block = temp.block;\n mres = gen->destructIfApplicable(&pr_value, &builder, &temp);\n if (!mres) {\n return false;\n }\n pr->set(temp.block, ctx->tr->type_bool, ret);\n return true;\n }\n\ncont1:\n\n \/* If an appropriate setf definition exists, which matches\n * the arguments exactly, then use it. *\/\n\n if (!prefixed_with_core) {\n std::vector types;\n types.push_back(pr_variable.type);\n types.push_back(pr_value.type);\n Element::Function *over_setf =\n ctx->getFunction(\"setf-assign\", &types, NULL, 0);\n if (!over_setf) {\n goto cont2;\n }\n std::vector call_args;\n call_args.push_back(pr_variable.value);\n call_args.push_back(pr_value.value);\n llvm::Value *ret =\n builder.CreateCall(over_setf->llvm_function,\n llvm::ArrayRef(call_args));\n\n ParseResult temp;\n pr_variable.block = pr_value.block;\n bool mres = gen->destructIfApplicable(&pr_variable, &builder, &temp);\n if (!mres) {\n return false;\n }\n pr_value.block = temp.block;\n mres = gen->destructIfApplicable(&pr_value, &builder, &temp);\n if (!mres) {\n return false;\n }\n\n pr->set(temp.block, ctx->tr->type_bool, ret);\n return true;\n }\n\ncont2:\n\n \/* var_value is only present to support the overridden set\n * operations: if this point is reached, then fall back to the\n * standard form-processing logic. *\/\n\n if (var_value) {\n res =\n Form::Proc::Inst::parse(gen, \n fn, pr_value.block, val_node, false,\n false,\n pr_variable.type->points_to,\n &pr_value\n );\n\n if (!res) {\n return false;\n }\n }\n\n if (pr_value.type->isEqualTo(pr_variable.type->points_to)) {\n builder.CreateStore(pr_value.value, pr_variable.value);\n\n ParseResult temp;\n pr_variable.block = pr_value.block;\n bool mres = gen->destructIfApplicable(&pr_variable, &builder, &temp);\n if (!mres) {\n return false;\n }\n pr_value.block = temp.block;\n mres = gen->destructIfApplicable(&pr_value, &builder, &temp);\n if (!mres) {\n return false;\n }\n\n pr->set(temp.block, ctx->tr->type_bool, \n llvm::ConstantInt::get(\n llvm::IntegerType::get(llvm::getGlobalContext(), 1), 1\n ));\n pr->do_not_copy_with_setf = 1;\n return true;\n }\n\n \/* todo: it would be good to also show the setf-assign\n * candidates here, if applicable. *\/\n ctx->er->assertTypeEquality(\"setf\", (*lst)[2],\n pr_value.type,\n pr_variable.type->points_to,\n false);\n\n return false;\n}\n}\n}\n}\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \"InstrumentFactories.h\"\n#include \"Stochastic.h\"\n#include \"Ising.h\"\n#include \"Measurement.h\"\n#include \"cli.h\"\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#else\n#define PACKAGE_STRING \"UNKNOWN\"\n#define PACKAGE_VERSION \"UNKNOWN\"\n#endif\n\nnamespace mpi = boost::mpi;\nnamespace opt = boost::program_options;\n\nint main(int argc, char* argv[]) {\n bool verbose = false;\n opt::options_description desc = optionsDescription();\n opt::variables_map vmap;\n opt::store(opt::parse_command_line(argc,argv,desc),vmap);\n opt::notify(vmap);\n \n if (vmap.count(\"help\")) {\n std::cout << desc << \"\\n\";\n return 1;\n }\n \n if(vmap.count(\"distribution\")) {\n isingEnergyDistribution(vmap[\"dimension\"].as(),\n vmap[\"clusters\"].as());\n exit(0);\n }\n \n verbose = vmap.count(\"verbose\");\n \n size_t iterations = vmap[\"iterations\"].as();\n \n ReservoirFactory *rFactory = NULL;\n if ( vmap.count(\"ising\") ) {\n if (!vmap.count(\"dimension\")) {\n std::clog << \"Option --ising requires -d\\n\";\n exit(1);\n }\n \n int dim = vmap[\"dimension\"].as();\n int clst = vmap[\"clusters\"].as();\n rFactory = new IsingReservoir::IsingFactory(dim,clst);\n } else {\n \/\/Assume stochastic\n rFactory = new DefaultArgsReservoirFactory;\n }\n \n SystemFactory *sFactory = new BinomialSystemFactory;\n \n assert(rFactory);\n assert(sFactory);\n \n int dimension = 50;\n const double tau = vmap[\"tau\"].as();\n \n mpi::environment env(argc, argv);\n mpi::communicator world;\n char hostname[256];\n int requester;\n \n if (world.rank()==0) {\n std::string args;\n for (int k=1; k!=argc; ++k) {\n args += argv[k];\n args += \" \";\n }\n printf(\"%s%s\\n\",PACKAGE_STRING,args.c_str());\n std::clog << \"Running v\" << PACKAGE_VERSION << \" on \" << world.size()\n << \" nodes.\" << std::endl;\n std::clog << (double)(dimension*dimension*iterations)\/world.size()\n << \" simulations per node.\" << std::endl;\n printf(\"%s\\n\",outputHeader().c_str());\n }\n \n world.barrier();\n \n gethostname(hostname,255);\n std::clog << \"Hello world from host \"\n << hostname\n << \" (rank \"\n << world.rank()\n << \")\"\n << std::endl;\n \n Experiment::range work;\n Experiment experiment;\n experiment.iterations = iterations;\n experiment.dimension = dimension;\n experiment.sfactory = sFactory;\n experiment.rfactory = rFactory;\n \n for (int k=world.rank(); kFix a race condition with the process checkins at the beginning of the MPI run.#include \n#include \n#include \n#include \n#include \n#include \n#include \"InstrumentFactories.h\"\n#include \"Stochastic.h\"\n#include \"Ising.h\"\n#include \"Measurement.h\"\n#include \"cli.h\"\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#else\n#define PACKAGE_STRING \"UNKNOWN\"\n#define PACKAGE_VERSION \"UNKNOWN\"\n#endif\n\nnamespace mpi = boost::mpi;\nnamespace opt = boost::program_options;\n\nint main(int argc, char* argv[]) {\n bool verbose = false;\n opt::options_description desc = optionsDescription();\n opt::variables_map vmap;\n opt::store(opt::parse_command_line(argc,argv,desc),vmap);\n opt::notify(vmap);\n \n if (vmap.count(\"help\")) {\n std::cout << desc << \"\\n\";\n return 1;\n }\n \n if(vmap.count(\"distribution\")) {\n isingEnergyDistribution(vmap[\"dimension\"].as(),\n vmap[\"clusters\"].as());\n exit(0);\n }\n \n verbose = vmap.count(\"verbose\");\n \n size_t iterations = vmap[\"iterations\"].as();\n \n ReservoirFactory *rFactory = NULL;\n if ( vmap.count(\"ising\") ) {\n if (!vmap.count(\"dimension\")) {\n std::clog << \"Option --ising requires -d\\n\";\n exit(1);\n }\n \n int dim = vmap[\"dimension\"].as();\n int clst = vmap[\"clusters\"].as();\n rFactory = new IsingReservoir::IsingFactory(dim,clst);\n } else {\n \/\/Assume stochastic\n rFactory = new DefaultArgsReservoirFactory;\n }\n \n SystemFactory *sFactory = new BinomialSystemFactory;\n \n assert(rFactory);\n assert(sFactory);\n \n int dimension = 50;\n const double tau = vmap[\"tau\"].as();\n \n mpi::environment env(argc, argv);\n mpi::communicator world;\n char hostname[256];\n int requester;\n \n if (world.rank()==0) {\n std::string args;\n for (int k=1; k!=argc; ++k) {\n args += argv[k];\n args += \" \";\n }\n printf(\"%s%s\\n\",PACKAGE_STRING,args.c_str());\n std::clog << \"Running v\" << PACKAGE_VERSION << \" on \" << world.size()\n << \" nodes.\" << std::endl;\n std::clog << (double)(dimension*dimension*iterations)\/world.size()\n << \" simulations per node.\" << std::endl;\n printf(\"%s\\n\",outputHeader().c_str());\n }\n \n world.barrier();\n \n gethostname(hostname,255);\n fprintf(stderr, \"Hello world from host %s (rank %d)\\n\",hostname,world.rank());\n \n Experiment::range work;\n Experiment experiment;\n experiment.iterations = iterations;\n experiment.dimension = dimension;\n experiment.sfactory = sFactory;\n experiment.rfactory = rFactory;\n \n for (int k=world.rank(); k"} {"text":"#define F_CPU 1000000UL\n\n#include \n#include \"macros.h\"\n#include \"tasks.h\"\n#include \"clock.h\"\n#include \"irqs.h\"\n#include \"adc.h\"\n\n\n\/\/ duration in ms for hBridge output\nconst uint16_t hBridgeOutDuration = 50;\n\n\/\/ wait timeSignalWaitPeriod ms until timeSignal is no longer present\n\/\/ before turning IRQ for timeSignal on again.\nconst uint16_t timeSignalWaitPeriod = 10;\n\n\/\/ when displayed time is not time, we move the minute finger faster\n\/\/ but we will wait this pause (in ms) between every finger movement.\nconst uint16_t pauseBetweenHBridgePulses = 500;\n\n\/\/ 256 * minBatt1Voltage \/ 1.1 (1.1 ref voltage)\nconst uint8_t batt1Min = 186; \/\/ 0.8V\nconst uint8_t batt2Min = 186; \/\/ 0.8V\nconst uint8_t batt3Min = 186; \/\/ 0.8V\n\ntypedef PIN_DIP_3 PauseClockPin;\n\n\/\/ DIP_4 is INT1 irq\ntypedef PIN_DIP_4 CheckBatteryVoltagePin;\n\n\/\/ DIP_5 is INT0 irq\ntypedef PIN_DIP_5 TimeSignalPin;\n\ntypedef PIN_DIP_6 NoonSensorPin;\n\n\ntypedef PIN_DIP_13 HBridge1;\ntypedef PIN_DIP_14 HBridge2;\n\ntypedef PIN_DIP_28 Batt1Pin;\ntypedef PIN_DIP_27 Batt1OutPin;\ntypedef PIN_DIP_26 Batt2Pin;\ntypedef PIN_DIP_25 Batt2OutPin;\ntypedef PIN_DIP_24 Batt3Pin;\ntypedef PIN_DIP_23 Batt3OutPin;\n\nuint16_t time; \/\/ in minutes from 12:00; wraps every 12*60 minutes\n\n\/\/ we allow the displayed time to be pause (for instance during the night,\n\/\/ because the clock is really loud)\nuint16_t displayedTime; \/\/ in minutes from 12:00; wraps every 12*60 minutes\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Task managment \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nenum Task {\n IncMinute = 0,\n CheckBatteries = 0,\n};\n\nuint8_t tasksToRun;\n\n\nvoid startTask(Task task) {\n tasksToRun |= _BV(task);\n}\n\nvoid stopTask(Task task) {\n tasksToRun &= ~(_BV(task));\n}\n\nvoid stopAllTasks() {\n tasksToRun = 0;\n}\n \nuint8_t isAllTasksStopped() {\n return tasksToRun = 0;\n}\n\nuint8_t isTaskStarted(Task task) {\n return tasksToRun & ~(_BV(task));\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ TimerSignal -- INT0 related functionality \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid enableTimerSignalIRQ() {\n EIMSK |= _BV(INT0);\n}\n\nvoid initTimerSignal() {\n \/\/ nothing to do for pin\n \/\/ pins are Hi-Z input by default\n \n \/\/ turn on irq\n enableTimerSignalIRQ();\n sei();\n}\n\n#define NEW_IRQ_TASK IncMinuteIrqTask\nIRQ_TASK(NEW_IRQ_TASK) {\n time++;\n if (time == 12 * 60) time = 0;\n\n startTask(Task::IncMinute);\n \n \/\/ turn off IRQ until signal from real clock is no longer present\n \/\/ otherwise this IRQ will trigger too often.\n EIMSK &= ~(_BV(INT0));\n};\n#include \"internal\/register_irq_task_INT0.h\"\n\nuint8_t timerSignalPresent() {\n return GET_BIT(TimeSignalPin, PIN) == 0;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ CheckBattery -- INT1 related functionality \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid enableCheckBatteryIRQ() {\n EIMSK |= _BV(INT1);\n}\n\nvoid initCheckBatteryPin() {\n \/\/ nothing to do for pin\n \/\/ pins are Hi-Z input by default\n \n \/\/ turn on irq\n enableCheckBatteryIRQ();\n sei();\n}\n\n#define NEW_IRQ_TASK CheckBatteryIrqTask\nIRQ_TASK(NEW_IRQ_TASK) {\n startTask(Task::CheckBatteries);\n \n \/\/ turn off IRQ until button is no longer pressed\n \/\/ otherwise this IRQ will trigger too often.\n EIMSK &= ~(_BV(INT1));\n};\n#include \"internal\/register_irq_task_INT1.h\"\n\nuint8_t checkBatteryPressed() {\n return GET_BIT(CheckBatteryVoltagePin, PIN) == 0;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PauseClock -- related functionality \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid initClockPaused() {\n \/\/ nothing to do\n \/\/ pins are Hi-Z input by default\n}\n\nuint8_t clockPaused() {\n return GET_BIT(PauseClockPin, PIN);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ NoonSensor -- related functionality \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid setNoonSensor(uint8_t v) {\n SET_BIT(NoonSensorPin, PORT, v);\n}\n\nvoid initNoonSensor() {\n SET_BIT(NoonSensorPin, DDR, 1);\n \n \/\/ start with noonSensor \"on\"\n setNoonSensor(1);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nstruct IncMinuteTask {\n static inline uint8_t is_enabled() {\n return isTaskStarted(Task::IncMinute);\n }\n \n template\n static inline T run(const T& clock) {\n \/\/ this task will be called twice for every minute increment.\n \/\/ first to turn the output on and second to turn it off again.\n \n \/\/ we also need to keep track if we have to send a positive or negative\n \/\/ signal.\n \n static uint8_t status = 0;\n \n const uint8_t clockP = clockPaused();\n \n const uint8_t hBridgeStatus = status & 0b11;\n \n if (hBridgeStatus == 0 || hBridgeStatus == 2) {\n if (!clockP) {\n if (hBridgeStatus == 0) SET_BIT(HBridge1, PORT, 1);\n else SET_BIT(HBridge1, PORT, 1);\n\n displayedTime++;\n if (displayedTime == 12 * 60) {\n displayedTime = 0;\n setNoonSensor(1);\n } else setNoonSensor(0);\n \n }\n \n status++;\n \/\/ sleep for hbridgeOutDuration\n return ms_to_units(hBridgeOutDuration);\n }\n \n \/\/ status 1 or 3 → turn HBridge1 \/ HBridge2 off\n if (hBridgeStatus == 1) SET_BIT(HBridge1, PORT, 0);\n else SET_BIT(HBridge2, PORT, 0);\n \n \/\/ we have to make sure the timeSignal is no longer present, before\n \/\/ turning irq for timeSignal on again.\n if (timerSignalPresent()) return ms_to_units(timeSignalWaitPeriod);\n \n \/\/ only then switch to next status:\n status++;\n \n \/\/ mark IncMinuteTask as done:\n \/\/ disable task in tasktracker\n \/\/ remove from taskTracker before enabling IRQ (otherwise we would have a\n \/\/ race condition\n stopTask(Task::IncMinute);\n \n enableTimerSignalIRQ();\n \n if (!clockP && displayedTime != time) {\n \/\/ reenable incMinuteTask, need to correct displayed time\n startTask(Task::IncMinute);\n return ms_to_units(pauseBetweenHBridgePulses);\n }\n \n return 0;\n }\n};\n\n#define NEW_TASK IncMinuteTask\n#include REGISTER_TASK\n\n\nstruct CheckBatteriesTask {\n static inline uint8_t is_enabled() {\n return isTaskStarted(Task::CheckBatteries);\n }\n \n typedef Adc<_adc::Mode::SingleConversion, _adc::Ref::V1_1, Batt1Pin> Adc_Batt1;\n typedef Adc<_adc::Mode::SingleConversion, _adc::Ref::V1_1, Batt2Pin> Adc_Batt2;\n typedef Adc<_adc::Mode::SingleConversion, _adc::Ref::V1_1, Batt3Pin> Adc_Batt3;\n \n template\n static inline T run(const T& clock) {\n Adc_Batt1::init();\n uint8_t batt1 = Adc_Batt1::adc_8bit();\n \/\/ don't need to turn off adc\n \n Adc_Batt2::init();\n uint8_t batt2 = Adc_Batt2::adc_8bit();\n \/\/ don't need to turn off adc\n \n Adc_Batt3::init();\n uint8_t batt3 = Adc_Batt3::adc_8bit();\n Adc_Batt3::turn_off();\n \n SET_BIT(Batt1OutPin, PORT, (batt1 > batt1Min));\n SET_BIT(Batt2OutPin, PORT, (batt2 > batt2Min));\n SET_BIT(Batt3OutPin, PORT, (batt3 > batt3Min));\n \n if (checkBatteryPressed()) return ms_to_units(200);\n \n \/\/ user no longer presses battery check button\n \n \/\/ turn off all outputs:\n SET_BIT(Batt1OutPin, PORT, 0);\n SET_BIT(Batt2OutPin, PORT, 0);\n SET_BIT(Batt3OutPin, PORT, 0);\n \n stopTask(Task::CheckBatteries);\n \n enableCheckBatteryIRQ();\n return 0;\n }\n};\n\n#define NEW_TASK CheckBatteriesTask\n#include REGISTER_TASK\n\n\n__attribute__ ((OS_main)) int main(void) {\n \n set_sleep_mode(SLEEP_MODE_PWR_DOWN);\n \n \/\/ start with all tasks stopped\n stopAllTasks();\n \n displayedTime = 0;\n time = 0;\n \n initNoonSensor();\n initClockPaused();\n initTimerSignal();\n \n for (;;) {\n execTasks();\n \n \/\/ if all tasks are done\n \/\/ power down\n \/\/ go to sleep without race conditions...\n cli();\n if (isAllTasksStopped()) {\n sleep_enable();\n sei();\n sleep_cpu();\n sleep_disable();\n }\n sei();\n }\n return 0;\n}\n\n#define USE_ONLY_DEFINED_IRQS\n#include REGISTER_IRQSfeat\/fix: fix Task enum int value#define F_CPU 1000000UL\n\n#include \n#include \"macros.h\"\n#include \"tasks.h\"\n#include \"clock.h\"\n#include \"irqs.h\"\n#include \"adc.h\"\n\n\n\/\/ duration in ms for hBridge output\nconst uint16_t hBridgeOutDuration = 50;\n\n\/\/ wait timeSignalWaitPeriod ms until timeSignal is no longer present\n\/\/ before turning IRQ for timeSignal on again.\nconst uint16_t timeSignalWaitPeriod = 10;\n\n\/\/ when displayed time is not time, we move the minute finger faster\n\/\/ but we will wait this pause (in ms) between every finger movement.\nconst uint16_t pauseBetweenHBridgePulses = 500;\n\ntemplate \nconstexpr uint8_t voltsToUnits(T volts) {\n return 256 * volts \/ 1.1;\n}\n\n\/\/ 256 * minBatt1Voltage \/ 1.1 (1.1 ref voltage)\nconst uint8_t batt1Min = voltsToUnits(0.8); \/\/ should be 186 units\nconst uint8_t batt2Min = voltsToUnits(0.8); \/\/ should be 186 units\nconst uint8_t batt3Min = voltsToUnits(0.8); \/\/ should be 186 units\n\ntypedef PIN_DIP_3 PauseClockPin;\n\n\/\/ DIP_4 is INT1 irq\ntypedef PIN_DIP_4 CheckBatteryVoltagePin;\n\n\/\/ DIP_5 is INT0 irq\ntypedef PIN_DIP_5 TimeSignalPin;\n\ntypedef PIN_DIP_6 NoonSensorPin;\n\n\ntypedef PIN_DIP_13 HBridge1;\ntypedef PIN_DIP_14 HBridge2;\n\ntypedef PIN_DIP_28 Batt1Pin;\ntypedef PIN_DIP_27 Batt1OutPin;\ntypedef PIN_DIP_26 Batt2Pin;\ntypedef PIN_DIP_25 Batt2OutPin;\ntypedef PIN_DIP_24 Batt3Pin;\ntypedef PIN_DIP_23 Batt3OutPin;\n\nuint16_t time; \/\/ in minutes from 12:00; wraps every 12*60 minutes\n\n\/\/ we allow the displayed time to be pause (for instance during the night,\n\/\/ because the clock is really loud)\nuint16_t displayedTime; \/\/ in minutes from 12:00; wraps every 12*60 minutes\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Task managment \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nenum Task {\n IncMinute = 0,\n CheckBatteries = 1,\n ReenableTimerSignalIrq = 2\n};\n\nuint8_t tasksToRun;\n\n\nvoid startTask(Task task) {\n tasksToRun |= _BV(task);\n}\n\nvoid stopTask(Task task) {\n tasksToRun &= ~(_BV(task));\n}\n\nvoid stopAllTasks() {\n tasksToRun = 0;\n}\n \nuint8_t isAllTasksStopped() {\n return tasksToRun = 0;\n}\n\nuint8_t isTaskStarted(Task task) {\n return tasksToRun & ~(_BV(task));\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ TimerSignal -- INT0 related functionality \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid enableTimerSignalIRQ() {\n EIMSK |= _BV(INT0);\n}\n\nvoid initTimerSignal() {\n \/\/ nothing to do for pin\n \/\/ pins are Hi-Z input by default\n \n \/\/ turn on irq\n enableTimerSignalIRQ();\n sei();\n}\n\n#define NEW_IRQ_TASK IncMinuteIrqTask\nIRQ_TASK(NEW_IRQ_TASK) {\n time++;\n if (time == 12 * 60) time = 0;\n\n startTask(Task::IncMinute);\n startTask(Task::ReenableTimerSignalIrq);\n \n \/\/ turn off IRQ until signal from real clock is no longer present\n \/\/ otherwise this IRQ will trigger too often.\n EIMSK &= ~(_BV(INT0));\n};\n#include \"internal\/register_irq_task_INT0.h\"\n\nuint8_t timerSignalPresent() {\n return GET_BIT(TimeSignalPin, PIN) == 0;\n}\n\n#define NEW_TASK ReenableTimerSignalIrqTask\nstruct NEW_TASK {\n static inline uint8_t is_enabled() {\n return isTaskStarted(Task::ReenableTimerSignalIrq);\n }\n \n template\n static inline T run(const T& clock) {\n if (!timerSignalPresent()) {\n stopTask(Task::ReenableTimerSignalIrq);\n enableTimerSignalIRQ();\n }\n return ms_to_units(5);\n }\n};\n#include REGISTER_TASK\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ CheckBattery -- INT1 related functionality \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid enableCheckBatteryIRQ() {\n EIMSK |= _BV(INT1);\n}\n\nvoid initCheckBatteryPin() {\n \/\/ nothing to do for pin\n \/\/ pins are Hi-Z input by default\n \n \/\/ turn on irq\n enableCheckBatteryIRQ();\n sei();\n}\n\n#define NEW_IRQ_TASK CheckBatteryIrqTask\nIRQ_TASK(NEW_IRQ_TASK) {\n startTask(Task::CheckBatteries);\n \n \/\/ turn off IRQ until button is no longer pressed\n \/\/ otherwise this IRQ will trigger too often.\n EIMSK &= ~(_BV(INT1));\n};\n#include \"internal\/register_irq_task_INT1.h\"\n\nuint8_t checkBatteryPressed() {\n return GET_BIT(CheckBatteryVoltagePin, PIN) == 0;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PauseClock -- related functionality \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid initClockPaused() {\n \/\/ nothing to do\n \/\/ pins are Hi-Z input by default\n}\n\nuint8_t clockPaused() {\n return GET_BIT(PauseClockPin, PIN);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ NoonSensor -- related functionality \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid setNoonSensor(uint8_t v) {\n SET_BIT(NoonSensorPin, PORT, v);\n}\n\nvoid initNoonSensor() {\n SET_BIT(NoonSensorPin, DDR, 1);\n \n \/\/ start with noonSensor \"on\"\n setNoonSensor(1);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#define NEW_TASK IncMinuteTask\nstruct NEW_TASK {\n static inline uint8_t is_enabled() {\n return isTaskStarted(Task::IncMinute);\n }\n \n template\n static inline T run(const T& clock) {\n \/\/ this task will be called twice for every minute increment.\n \/\/ first to turn the output on and second to turn it off again.\n \n \/\/ we also need to keep track if we have to send a positive or negative\n \/\/ signal.\n \n static uint8_t status = 0;\n \n const uint8_t clockP = clockPaused();\n \n const uint8_t hBridgeStatus = status & 0b11;\n \n if (hBridgeStatus == 0 || hBridgeStatus == 2) {\n if (!clockP) {\n if (hBridgeStatus == 0) SET_BIT(HBridge1, PORT, 1);\n else SET_BIT(HBridge1, PORT, 1);\n\n displayedTime++;\n if (displayedTime == 12 * 60) {\n displayedTime = 0;\n setNoonSensor(1);\n } else setNoonSensor(0);\n \n }\n \n status++;\n \/\/ sleep for hbridgeOutDuration\n return ms_to_units(hBridgeOutDuration);\n }\n \n \/\/ status 1 or 3 → turn HBridge1 \/ HBridge2 off\n if (hBridgeStatus == 1) SET_BIT(HBridge1, PORT, 0);\n else SET_BIT(HBridge2, PORT, 0);\n \n \/\/ we have to make sure the timeSignal is no longer present, before\n \/\/ turning irq for timeSignal on again.\n if (timerSignalPresent()) return ms_to_units(timeSignalWaitPeriod);\n \n \/\/ only then switch to next status:\n status++;\n \n \/\/ mark IncMinuteTask as done:\n \/\/ disable task in tasktracker\n stopTask(Task::IncMinute);\n \n if (!clockP && displayedTime != time) {\n \/\/ reenable incMinuteTask, need to correct displayed time\n startTask(Task::IncMinute);\n return ms_to_units(pauseBetweenHBridgePulses);\n }\n \n return 0;\n }\n};\n#include REGISTER_TASK\n\n\n#define NEW_TASK CheckBatteriesTask\nstruct NEW_TASK {\n static inline uint8_t is_enabled() {\n return isTaskStarted(Task::CheckBatteries);\n }\n \n typedef Adc<_adc::Mode::SingleConversion, _adc::Ref::V1_1, Batt1Pin> Adc_Batt1;\n typedef Adc<_adc::Mode::SingleConversion, _adc::Ref::V1_1, Batt2Pin> Adc_Batt2;\n typedef Adc<_adc::Mode::SingleConversion, _adc::Ref::V1_1, Batt3Pin> Adc_Batt3;\n \n template\n static inline T run(const T& clock) {\n Adc_Batt1::init();\n uint8_t batt1 = Adc_Batt1::adc_8bit();\n \/\/ don't need to turn off adc\n \n Adc_Batt2::init();\n uint8_t batt2 = Adc_Batt2::adc_8bit();\n \/\/ don't need to turn off adc\n \n Adc_Batt3::init();\n uint8_t batt3 = Adc_Batt3::adc_8bit();\n Adc_Batt3::turn_off();\n \n SET_BIT(Batt1OutPin, PORT, (batt1 > batt1Min));\n SET_BIT(Batt2OutPin, PORT, (batt2 > batt2Min));\n SET_BIT(Batt3OutPin, PORT, (batt3 > batt3Min));\n \n if (checkBatteryPressed()) return ms_to_units(200);\n \n \/\/ user no longer presses battery check button\n \n \/\/ turn off all outputs:\n SET_BIT(Batt1OutPin, PORT, 0);\n SET_BIT(Batt2OutPin, PORT, 0);\n SET_BIT(Batt3OutPin, PORT, 0);\n \n stopTask(Task::CheckBatteries);\n \n enableCheckBatteryIRQ();\n return 0;\n }\n};\n\n#include REGISTER_TASK\n\n\n\n__attribute__ ((OS_main)) int main(void) {\n \n set_sleep_mode(SLEEP_MODE_PWR_DOWN);\n \n \/\/ start with all tasks stopped\n stopAllTasks();\n \n displayedTime = 0;\n time = 0;\n \n initNoonSensor();\n initClockPaused();\n initTimerSignal();\n \n for (;;) {\n execTasks();\n \n \/\/ if all tasks are done\n \/\/ power down\n \/\/ go to sleep without race conditions...\n cli();\n if (isAllTasksStopped()) {\n sleep_enable();\n sei();\n sleep_cpu();\n sleep_disable();\n }\n sei();\n }\n return 0;\n}\n\n#define USE_ONLY_DEFINED_IRQS\n#include REGISTER_IRQS<|endoftext|>"} {"text":"#ifndef BITSMANIPULATION_HPP_\n#define BITSMANIPULATION_HPP_\n\n#include \n#include \n#include \n\nvoid Representation()\n{\n std::cout << \"Representation of the numbers in binary and hex\" <<\n std::endl;\n\n const long long unsigned int max = std::numeric_limits::max();\n for (long long unsigned int i = 0; i <= max; ++i)\n {\n std::cout << \"Dec: \" << std::dec << std::showbase << i;\n std::cout << \" Bin: 0b\" << std::bitset<8>(i).to_string();\n std::cout << \" Oct: \" << std::oct << std::showbase << i;\n std::cout << \" Hex: \" << std::hex << std::showbase << i << std::endl;\n }\n\n std::cout << std::endl;\n}\n\nvoid OperationAND()\n{\n std::cout << \"Example of AND operation\" << std::endl;\n unsigned char first = 0b00111000;\n unsigned char second = 0b10101010;\n unsigned char result = first & second;\n\n std::cout << \"First value: 0b\" << std::bitset<8>(first).to_string() <<\n std::endl;\n std::cout << \"Second value: 0b\" << std::bitset<8>(second).to_string() <<\n std::endl;\n std::cout << \"Result of AND operation: 0b\" <<\n std::bitset<8>(result).to_string() << std::endl;\n\n first = 0b11111000;\n second = 0b10101011;\n result = first & second;\n\n std::cout << std::endl << \"With other values\" << std::endl;\n std::cout << \"First value: 0b\" << std::bitset<8>(first).to_string() <<\n std::endl;\n std::cout << \"Second value: 0b\" << std::bitset<8>(second).to_string() <<\n std::endl;\n std::cout << \"Result of AND operation: 0b\" <<\n std::bitset<8>(result).to_string() << std::endl;\n\n std::cout << std::endl;\n}\n\n\/\/ TODO: OR operation\n\/\/ TODO: XOR operation\n\/\/ TODO: bit reversing\n\/\/ TODO: bit rotation\n\/\/ TODO: number multiplication to 2\n\/\/ TODO: number division by 2\n\nvoid StartBM()\n{\n Representation();\n OperationAND();\n}\n\n#endif \/* BITSMANIPULATION_HPP_ *\/\nOR operation#ifndef BITSMANIPULATION_HPP_\n#define BITSMANIPULATION_HPP_\n\n#include \n#include \n#include \n\nvoid Representation()\n{\n std::cout << \"Representation of the numbers in binary and hex\" <<\n std::endl;\n\n const long long unsigned int max = std::numeric_limits::max();\n for (long long unsigned int i = 0; i <= max; ++i)\n {\n std::cout << \"Dec: \" << std::dec << std::showbase << i;\n std::cout << \" Bin: 0b\" << std::bitset<8>(i).to_string();\n std::cout << \" Oct: \" << std::oct << std::showbase << i;\n std::cout << \" Hex: \" << std::hex << std::showbase << i << std::endl;\n }\n\n std::cout << std::endl;\n}\n\nvoid OperationAND()\n{\n std::cout << \"Example of AND operation\" << std::endl;\n unsigned char first = 0b00111000;\n unsigned char second = 0b10101010;\n unsigned char result = first & second;\n\n std::cout << \"First value: 0b\" << std::bitset<8>(first).to_string() <<\n std::endl;\n std::cout << \"Second value: 0b\" << std::bitset<8>(second).to_string() <<\n std::endl;\n std::cout << \"Result of AND operation: 0b\" <<\n std::bitset<8>(result).to_string() << std::endl;\n\n first = 0b11111000;\n second = 0b10101011;\n result = first & second;\n\n std::cout << std::endl << \"With other values\" << std::endl;\n std::cout << \"First value: 0b\" << std::bitset<8>(first).to_string() <<\n std::endl;\n std::cout << \"Second value: 0b\" << std::bitset<8>(second).to_string() <<\n std::endl;\n std::cout << \"Result of AND operation: 0b\" <<\n std::bitset<8>(result).to_string() << std::endl;\n\n std::cout << std::endl;\n}\n\nvoid OperationOR()\n{\n std::cout << \"Example of OR operation\" << std::endl;\n unsigned char first = 0b00111000;\n unsigned char second = 0b10101010;\n unsigned char result = first | second;\n\n std::cout << \"First value: 0b\" << std::bitset<8>(first).to_string() <<\n std::endl;\n std::cout << \"Second value: 0b\" << std::bitset<8>(second).to_string() <<\n std::endl;\n std::cout << \"Result of OR operation: 0b\" <<\n std::bitset<8>(result).to_string() << std::endl;\n\n first = 0b11111000;\n second = 0b10101011;\n result = first | second;\n\n std::cout << std::endl << \"With other values\" << std::endl;\n std::cout << \"First value: 0b\" << std::bitset<8>(first).to_string() <<\n std::endl;\n std::cout << \"Second value: 0b\" << std::bitset<8>(second).to_string() <<\n std::endl;\n std::cout << \"Result of OR operation: 0b\" <<\n std::bitset<8>(result).to_string() << std::endl;\n\n std::cout << std::endl;\n}\n\n\/\/ TODO: XOR operation\n\/\/ TODO: bit reversing\n\/\/ TODO: bit rotation\n\/\/ TODO: number multiplication to 2\n\/\/ TODO: number division by 2\n\nvoid StartBM()\n{\n Representation();\n OperationAND();\n OperationOR();\n}\n\n#endif \/* BITSMANIPULATION_HPP_ *\/\n<|endoftext|>"} {"text":"#ifndef BITSMANIPULATION_HPP_\n#define BITSMANIPULATION_HPP_\n\n#include \n#include \n#include \n\nvoid Representation()\n{\n std::cout << \"Representation of the numbers in binary and hex\" <<\n std::endl;\n\n const long long unsigned int max = std::numeric_limits::max();\n for (long long unsigned int i = 0; i <= max; ++i)\n {\n std::cout << \"Dec: \" << std::dec << std::showbase << i;\n std::cout << \" Bin: 0b\" << std::bitset<8>(i).to_string();\n std::cout << \" Oct: \" << std::oct << std::showbase << i;\n std::cout << \" Hex: \" << std::hex << std::showbase << i << std::endl;\n }\n\n std::cout << std::endl;\n}\n\nvoid OperationAND()\n{\n std::cout << \"Example of AND operation\" << std::endl;\n unsigned char first = 0b00111000;\n unsigned char second = 0b10101010;\n\n std::cout << std::bitset<8>(first).to_string() << \" & \" <<\n std::bitset<8>(second).to_string() << \" = \" <<\n std::bitset<8>(first & second).to_string() <<\n std::endl;\n\n first = 0b11111000;\n second = 0b10101011;\n\n std::cout << std::bitset<8>(first).to_string() << \" & \" <<\n std::bitset<8>(second).to_string() << \" = \" <<\n std::bitset<8>(first & second).to_string() <<\n std::endl;\n\n std::cout << std::endl;\n}\n\nvoid OperationOR()\n{\n std::cout << \"Example of OR operation\" << std::endl;\n unsigned char first = 0b00111000;\n unsigned char second = 0b10101010;\n\n std::cout << std::bitset<8>(first).to_string() << \" | \" <<\n std::bitset<8>(second).to_string() << \" = \" <<\n std::bitset<8>(first | second).to_string() <<\n std::endl;\n\n first = 0b11111000;\n second = 0b10101011;\n\n std::cout << std::bitset<8>(first).to_string() << \" | \" <<\n std::bitset<8>(second).to_string() << \" = \" <<\n std::bitset<8>(first | second).to_string() <<\n std::endl;\n\n std::cout << std::endl;\n}\n\nvoid OperationXOR()\n{\n std::cout << \"Example of XOR operation\" << std::endl;\n unsigned char first = 0b00111000;\n unsigned char second = 0b10101010;\n\n std::cout << std::bitset<8>(first).to_string() << \" ^ \" <<\n std::bitset<8>(second).to_string() << \" = \" <<\n std::bitset<8>(first ^ second).to_string() <<\n std::endl;\n\n first = 0b11111000;\n second = 0b10101011;\n\n std::cout << std::bitset<8>(first).to_string() << \" ^ \" <<\n std::bitset<8>(second).to_string() << \" = \" <<\n std::bitset<8>(first ^ second).to_string() <<\n std::endl;\n\n std::cout << \"Byte complementation using XOR operation\" << std::endl;\n first = 0b11111111;\n std::cout << std::bitset<8>(first).to_string() << \" ^ \" <<\n std::bitset<8>(second).to_string() << \" = \" <<\n std::bitset<8>(first ^ second).to_string() <<\n std::endl;\n\n std::cout << std::endl;\n}\n\nvoid Reverse()\n{\n std::cout << \"Byte reverse operation\" << std::endl;\n const unsigned char original = 0b00110010;\n\n unsigned char value = original;\n unsigned char result = 0;\n const int max = std::numeric_limits::digits - 1;\n for (int i = 0; i < max; ++i)\n {\n if (value & 0x01)\n {\n result |= 0x01;\n }\n\n value = static_cast(value >> 1);\n result = static_cast(result << 1);\n }\n\n std::cout << std::bitset<8>(original).to_string() << \" -> \" <<\n std::bitset<8>(result).to_string() << std::endl;\n\n std::cout << std::endl;\n}\n\n\/\/ TODO: bit rotation\n\nvoid MultiplicationBy2()\n{\n std::cout << \"Multiplication by 2\" << std::endl;\n unsigned char value = 0b00111000;\n unsigned char result = static_cast(value << 1);\n\n std::cout << std::bitset<8>(value).to_string() << \" << 1 = \" <<\n std::bitset<8>(result).to_string() << std::endl;\n\n unsigned int valueInt = static_cast(value);\n unsigned int resultInt = static_cast(result);\n std::cout << std::dec << valueInt << \" -> \" << resultInt << std::endl;\n\n std::cout << std::endl;\n}\n\nvoid DivisionBy2()\n{\n std::cout << \"Division by 2\" << std::endl;\n unsigned char value = 0b00111000;\n unsigned char result = static_cast(value >> 1);\n\n std::cout << std::bitset<8>(value).to_string() << \" >> 1 = \" <<\n std::bitset<8>(result).to_string() << std::endl;\n\n unsigned int valueInt = static_cast(value);\n unsigned int resultInt = static_cast(result);\n std::cout << std::dec << valueInt << \" -> \" << resultInt << std::endl;\n\n std::cout << std::endl;\n}\n\nvoid StartBM()\n{\n Representation();\n OperationAND();\n OperationOR();\n OperationXOR();\n Reverse();\n MultiplicationBy2();\n DivisionBy2();\n}\n\n#endif \/* BITSMANIPULATION_HPP_ *\/\nAdd bits rotation#ifndef BITSMANIPULATION_HPP_\n#define BITSMANIPULATION_HPP_\n\n#include \n#include \n#include \n\nvoid Representation()\n{\n std::cout << \"Representation of the numbers in binary and hex\" <<\n std::endl;\n\n const long long unsigned int max = std::numeric_limits::max();\n for (long long unsigned int i = 0; i <= max; ++i)\n {\n std::cout << \"Dec: \" << std::dec << std::showbase << i;\n std::cout << \" Bin: 0b\" << std::bitset<8>(i).to_string();\n std::cout << \" Oct: \" << std::oct << std::showbase << i;\n std::cout << \" Hex: \" << std::hex << std::showbase << i << std::endl;\n }\n\n std::cout << std::endl;\n}\n\nvoid OperationAND()\n{\n std::cout << \"Example of AND operation\" << std::endl;\n unsigned char first = 0b00111000;\n unsigned char second = 0b10101010;\n\n std::cout << std::bitset<8>(first).to_string() << \" & \" <<\n std::bitset<8>(second).to_string() << \" = \" <<\n std::bitset<8>(first & second).to_string() <<\n std::endl;\n\n first = 0b11111000;\n second = 0b10101011;\n\n std::cout << std::bitset<8>(first).to_string() << \" & \" <<\n std::bitset<8>(second).to_string() << \" = \" <<\n std::bitset<8>(first & second).to_string() <<\n std::endl;\n\n std::cout << std::endl;\n}\n\nvoid OperationOR()\n{\n std::cout << \"Example of OR operation\" << std::endl;\n unsigned char first = 0b00111000;\n unsigned char second = 0b10101010;\n\n std::cout << std::bitset<8>(first).to_string() << \" | \" <<\n std::bitset<8>(second).to_string() << \" = \" <<\n std::bitset<8>(first | second).to_string() <<\n std::endl;\n\n first = 0b11111000;\n second = 0b10101011;\n\n std::cout << std::bitset<8>(first).to_string() << \" | \" <<\n std::bitset<8>(second).to_string() << \" = \" <<\n std::bitset<8>(first | second).to_string() <<\n std::endl;\n\n std::cout << std::endl;\n}\n\nvoid OperationXOR()\n{\n std::cout << \"Example of XOR operation\" << std::endl;\n unsigned char first = 0b00111000;\n unsigned char second = 0b10101010;\n\n std::cout << std::bitset<8>(first).to_string() << \" ^ \" <<\n std::bitset<8>(second).to_string() << \" = \" <<\n std::bitset<8>(first ^ second).to_string() <<\n std::endl;\n\n first = 0b11111000;\n second = 0b10101011;\n\n std::cout << std::bitset<8>(first).to_string() << \" ^ \" <<\n std::bitset<8>(second).to_string() << \" = \" <<\n std::bitset<8>(first ^ second).to_string() <<\n std::endl;\n\n std::cout << \"Byte complementation using XOR operation\" << std::endl;\n first = 0b11111111;\n std::cout << std::bitset<8>(first).to_string() << \" ^ \" <<\n std::bitset<8>(second).to_string() << \" = \" <<\n std::bitset<8>(first ^ second).to_string() <<\n std::endl;\n\n std::cout << std::endl;\n}\n\nvoid Reverse()\n{\n std::cout << \"Byte reverse operation\" << std::endl;\n const unsigned char original = 0b00110010;\n\n unsigned char value = original;\n unsigned char result = 0;\n const int max = std::numeric_limits::digits - 1;\n for (int i = 0; i < max; ++i)\n {\n if (value & 0x01)\n {\n result |= 0x01;\n }\n\n value = static_cast(value >> 1);\n result = static_cast(result << 1);\n }\n\n std::cout << std::bitset<8>(original).to_string() << \" -> \" <<\n std::bitset<8>(result).to_string() << std::endl;\n\n std::cout << std::endl;\n}\n\nvoid Rotation()\n{\n std::cout << \"Byte rotation operation\" << std::endl;\n unsigned char original = 0b00110010;\n unsigned char moves = 5;\n int digits = std::numeric_limits::digits;\n unsigned char result = static_cast(\n (original >> moves) | (original << (digits - moves)));\n\n std::cout << std::bitset<8>(original).to_string() << \" -> \" <<\n std::bitset<8>(result).to_string() << std::endl;\n\n std::cout << std::endl;\n}\n\nvoid MultiplicationBy2()\n{\n std::cout << \"Multiplication by 2\" << std::endl;\n unsigned char value = 0b00111000;\n unsigned char result = static_cast(value << 1);\n\n std::cout << std::bitset<8>(value).to_string() << \" << 1 = \" <<\n std::bitset<8>(result).to_string() << std::endl;\n\n unsigned int valueInt = static_cast(value);\n unsigned int resultInt = static_cast(result);\n std::cout << std::dec << valueInt << \" -> \" << resultInt << std::endl;\n\n std::cout << std::endl;\n}\n\nvoid DivisionBy2()\n{\n std::cout << \"Division by 2\" << std::endl;\n unsigned char value = 0b00111000;\n unsigned char result = static_cast(value >> 1);\n\n std::cout << std::bitset<8>(value).to_string() << \" >> 1 = \" <<\n std::bitset<8>(result).to_string() << std::endl;\n\n unsigned int valueInt = static_cast(value);\n unsigned int resultInt = static_cast(result);\n std::cout << std::dec << valueInt << \" -> \" << resultInt << std::endl;\n\n std::cout << std::endl;\n}\n\nvoid StartBM()\n{\n Representation();\n OperationAND();\n OperationOR();\n OperationXOR();\n Reverse();\n Rotation();\n MultiplicationBy2();\n DivisionBy2();\n}\n\n#endif \/* BITSMANIPULATION_HPP_ *\/\n<|endoftext|>"} {"text":"\/*\n* this file is part of the oxygen gtk engine\n* Copyright (c) 2010 Hugo Pereira Da Costa \n* Copyright (c) 2010 Ruslan Kabatsayev \n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2 of the License, or(at your option ) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free\n* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n* MA 02110-1301, USA.\n*\/\n\n#include \"oxygenanimations.h\"\n#include \"..\/oxygengtkutils.h\"\n#include \"..\/oxygenqtsettings.h\"\n#include \"..\/config.h\"\n\n#include \n#include \n\nnamespace Oxygen\n{\n\n \/\/_________________________________________\n Animations::Animations( void ):\n _innerShadowsEnabled( true ),\n _hooksInitialized( false )\n {\n #if OXYGEN_DEBUG\n std::cerr << \"Oxygen::Animations::Animations\" << std::endl;\n #endif\n\n \/\/ create engines\n registerEngine( _backgroundHintEngine = new BackgroundHintEngine( this ) );\n registerEngine( _comboEngine = new ComboEngine( this ) );\n registerEngine( _comboBoxEngine = new ComboBoxEngine( this ) );\n registerEngine( _comboBoxEntryEngine = new ComboBoxEntryEngine( this ) );\n registerEngine( _dialogEngine = new DialogEngine( this ) );\n registerEngine( _flatWidgetEngine = new FlatWidgetEngine( this ) );\n registerEngine( _groupBoxEngine = new GroupBoxEngine( this ) );\n registerEngine( _groupBoxLabelEngine = new GroupBoxLabelEngine( this ) );\n registerEngine( _hoverEngine = new HoverEngine( this ) );\n registerEngine( _mainWindowEngine = new MainWindowEngine( this ) );\n registerEngine( _menuItemEngine = new MenuItemEngine( this ) );\n registerEngine( _panedEngine = new PanedEngine( this ) );\n registerEngine( _scrollBarEngine = new ScrollBarEngine( this ) );\n registerEngine( _scrolledWindowEngine = new ScrolledWindowEngine( this ) );\n registerEngine( _innerShadowEngine = new InnerShadowEngine( this ) );\n registerEngine( _tabWidgetEngine = new TabWidgetEngine( this ) );\n registerEngine( _treeViewEngine = new TreeViewEngine( this ) );\n registerEngine( _widgetSizeEngine = new WidgetSizeEngine( this ) );\n\n \/\/ animations specific engines\n registerEngine( _widgetStateEngine = new WidgetStateEngine( this ) );\n registerEngine( _arrowStateEngine = new ArrowStateEngine( this ) );\n registerEngine( _scrollBarStateEngine = new ScrollBarStateEngine( this ) );\n registerEngine( _tabWidgetStateEngine = new TabWidgetStateEngine( this ) );\n registerEngine( _treeViewStateEngine = new TreeViewStateEngine( this ) );\n registerEngine( _menuBarStateEngine = new MenuBarStateEngine( this ) );\n registerEngine( _menuStateEngine = new MenuStateEngine( this ) );\n registerEngine( _toolBarStateEngine = new ToolBarStateEngine( this ) );\n\n }\n\n \/\/____________________________________________________________________________________________\n Animations::~Animations( void )\n {\n #if OXYGEN_DEBUG\n std::cerr << \"Oxygen::Animations::~Animations\" << std::endl;\n #endif\n\n \/\/ delete all engines\n for( BaseEngine::List::iterator iter = _engines.begin(); iter != _engines.end(); ++iter )\n { delete *iter; }\n\n \/\/ disconnect all signals from map\n for( WidgetMap::iterator iter = _allWidgets.begin(); iter != _allWidgets.end(); iter++ )\n { iter->second.disconnect(); }\n\n \/\/ clear hooks\n _sizeAllocationHook.disconnect();\n _realizationHook.disconnect();\n _innerShadowHook.disconnect();\n\n }\n\n \/\/_________________________________________\n void Animations::initialize( const QtSettings& settings )\n {\n\n const bool animationsEnabled( settings.animationsEnabled() );\n\n \/\/ pass animations configuration to engines\n _widgetStateEngine->setApplicationName( settings.applicationName() );\n _widgetStateEngine->setEnabled( animationsEnabled && settings.genericAnimationsEnabled() );\n _widgetStateEngine->setDuration( settings.genericAnimationsDuration() );\n\n _arrowStateEngine->setApplicationName( settings.applicationName() );\n _arrowStateEngine->setEnabled( animationsEnabled && settings.genericAnimationsEnabled() );\n _arrowStateEngine->setDuration( settings.genericAnimationsDuration() );\n\n _scrollBarStateEngine->setApplicationName( settings.applicationName() );\n _scrollBarStateEngine->setEnabled( animationsEnabled && settings.genericAnimationsEnabled() );\n _scrollBarStateEngine->setDuration( settings.genericAnimationsDuration() );\n\n _tabWidgetStateEngine->setApplicationName( settings.applicationName() );\n _tabWidgetStateEngine->setEnabled( animationsEnabled && settings.genericAnimationsEnabled() );\n _tabWidgetStateEngine->setDuration( settings.genericAnimationsDuration() );\n\n _treeViewStateEngine->setApplicationName( settings.applicationName() );\n _treeViewStateEngine->setEnabled( animationsEnabled && settings.genericAnimationsEnabled() );\n _treeViewStateEngine->setDuration( settings.genericAnimationsDuration() );\n\n _menuBarStateEngine->setApplicationName( settings.applicationName() );\n _menuBarStateEngine->setAnimationsEnabled( animationsEnabled && (settings.menuBarAnimationType() != None) );\n _menuBarStateEngine->setFollowMouse( settings.menuBarAnimationType() == FollowMouse );\n _menuBarStateEngine->setDuration( settings.menuBarAnimationsDuration() );\n _menuBarStateEngine->setFollowMouseAnimationsDuration( settings.menuBarFollowMouseAnimationsDuration() );\n\n _menuStateEngine->setApplicationName( settings.applicationName() );\n _menuStateEngine->setEnabled( animationsEnabled && (settings.menuAnimationType() != None) );\n _menuStateEngine->setFollowMouse( settings.menuAnimationType() == FollowMouse );\n _menuStateEngine->setDuration( settings.menuAnimationsDuration() );\n _menuStateEngine->setFollowMouseAnimationsDuration( settings.menuFollowMouseAnimationsDuration() );\n\n \/\/ for now, only Fade animations mode is supported for toolbar animations\n _toolBarStateEngine->setApplicationName( settings.applicationName() );\n _toolBarStateEngine->setEnabled( animationsEnabled && (settings.toolBarAnimationType() != None) );\n _toolBarStateEngine->setFollowMouse( settings.toolBarAnimationType() == FollowMouse );\n _toolBarStateEngine->setDuration( settings.genericAnimationsDuration() );\n _toolBarStateEngine->setFollowMouseAnimationsDuration( settings.toolBarAnimationsDuration() );\n\n \/\/ background hint engine\n _backgroundHintEngine->setUseBackgroundGradient( settings.useBackgroundGradient() );\n\n }\n\n \/\/____________________________________________________________________________________________\n void Animations::initializeHooks( void )\n {\n if( _hooksInitialized ) return;\n\n \/\/ https:\/\/bugzilla.gnome.org\/show_bug.cgi?id=643416\n #if ENABLE_INNER_SHADOWS_HACK\n if(!getenv(\"OXYGEN_DISABLE_INNER_SHADOWS_HACK\"))\n { _innerShadowHook.connect( \"realize\", (GSignalEmissionHook)innerShadowHook, this ); }\n #endif\n\n _sizeAllocationHook.connect( \"size-allocate\", (GSignalEmissionHook)sizeAllocationHook, this );\n _realizationHook.connect( \"realize\", (GSignalEmissionHook)realizationHook, this );\n\n _hooksInitialized = true;\n }\n\n \/\/____________________________________________________________________________________________\n bool Animations::registerWidget( GtkWidget* widget )\n {\n\n if( _allWidgets.find( widget ) != _allWidgets.end() ) return false;\n\n #if OXYGEN_DEBUG\n std::cerr << \"Oxygen::Animations::registerWidget - \" << widget << \" (\" << (widget ? G_OBJECT_TYPE_NAME( widget ):\"0x0\") << \")\" << std::endl;\n #endif\n\n Signal destroyId;\n destroyId.connect( G_OBJECT( widget ), \"destroy\", G_CALLBACK( destroyNotifyEvent ), this );\n _allWidgets.insert( std::make_pair( widget, destroyId ) );\n return true;\n\n }\n\n \/\/____________________________________________________________________________________________\n void Animations::unregisterWidget( GtkWidget* widget )\n {\n\n #if OXYGEN_DEBUG\n std::cerr << \"Oxygen::Animations::unregisterWidget - \" << widget << \" (\" << G_OBJECT_TYPE_NAME( widget ) << \")\" << std::endl;\n #endif\n\n \/\/ find in map\n WidgetMap::iterator iter( _allWidgets.find( widget ) );\n assert( iter != _allWidgets.end() );\n\n \/\/ disconnect signal\n iter->second.disconnect();\n\n \/\/ erase from map\n _allWidgets.erase( widget );\n\n \/\/ erase from all maps\n for( BaseEngine::List::iterator iter = _engines.begin(); iter != _engines.end(); ++iter )\n { (*iter)->unregisterWidget( widget ); }\n\n }\n\n \/\/____________________________________________________________________________________________\n void Animations::setEnabled( bool value )\n {\n\n for( BaseEngine::List::iterator iter = _engines.begin(); iter != _engines.end(); ++iter )\n { (*iter)->setEnabled( value ); }\n\n }\n\n \/\/____________________________________________________________________________________________\n gboolean Animations::destroyNotifyEvent( GtkWidget* widget, gpointer data )\n {\n static_cast(data)->unregisterWidget( widget );\n return FALSE;\n }\n\n \/\/____________________________________________________________________________________________\n gboolean Animations::sizeAllocationHook( GSignalInvocationHint*, guint, const GValue* params, gpointer data )\n {\n\n \/\/ get widget from params\n GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) );\n\n \/\/ check type\n if( !GTK_IS_WIDGET( widget ) ) return FALSE;\n\n \/\/ cast data\n Animations& animations( *static_cast(data) );\n\n \/\/ groupbox labels\n #if ENABLE_GROUPBOX_HACK\n if( animations.groupBoxLabelEngine().contains( widget ) )\n {\n animations.groupBoxLabelEngine().adjustSize( widget );\n return TRUE;\n }\n #endif\n\n #if ENABLE_COMBOBOX_LIST_RESIZE\n \/\/ comboboxes\n if( !GTK_IS_WINDOW( widget ) ) return TRUE;\n\n GtkWindow* window( GTK_WINDOW( widget ) );\n if( gtk_window_get_type_hint( window ) != GDK_WINDOW_TYPE_HINT_COMBO ) return TRUE;\n\n GtkWidget* combobox = animations.comboBoxEngine().find( widget );\n if( !combobox ) combobox = animations.comboBoxEntryEngine().find( widget );\n if( !combobox ) combobox = animations.comboEngine().find( widget );\n if( !combobox ) return true;\n\n int w, h;\n gtk_window_get_size( window, &w, &h );\n\n gint targetX, dummy, y;\n gtk_window_get_position( window, &dummy, &y );\n gdk_window_get_origin( gtk_widget_get_window( combobox ), &targetX, &dummy );\n\n const GtkAllocation comboAllocation( Gtk::gtk_widget_get_allocation( combobox ) );\n int uglyShadowWidth=!Gtk::gdk_default_screen_is_composited();\n gtk_window_move( window, targetX + comboAllocation.x + 3 - uglyShadowWidth, y );\n\n const GtkAllocation widgetAllocation( Gtk::gtk_widget_get_allocation( widget ) );\n gtk_widget_set_size_request( widget, comboAllocation.width - 6 + 2*uglyShadowWidth, widgetAllocation.height );\n #endif\n\n return TRUE;\n\n }\n\n \/\/____________________________________________________________________________________________\n gboolean Animations::innerShadowHook( GSignalInvocationHint*, guint, const GValue* params, gpointer data )\n {\n\n #if GTK_CHECK_VERSION(2,24,2)\n\n \/\/ get widget from params\n GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) );\n\n \/\/ check type\n if( !GTK_IS_WIDGET( widget ) ) return FALSE;\n\n \/\/ check enabled state\n Animations& animations( *static_cast(data) );\n if( !animations.innerShadowsEnabled() ) return TRUE;\n\n \/\/ blacklist\n if( Gtk::g_object_is_a( G_OBJECT( widget ), \"SwtFixed\" ) ) return TRUE;\n if( Gtk::g_object_is_a( G_OBJECT( widget ), \"GtkPizza\" ) ) return TRUE;\n\n GtkWidget* parent(gtk_widget_get_parent(widget));\n if( !GTK_IS_SCROLLED_WINDOW( parent ) ) return TRUE;\n\n GtkWidget* child(gtk_bin_get_child(GTK_BIN(parent)));\n if(child!=widget) return TRUE;\n\n #if OXYGEN_DEBUG\n std::cerr\n << \"Oxygen::Animations::innerShadowHook -\"\n << \" widget: \" << widget << \" (\" << G_OBJECT_TYPE_NAME(widget) << \")\"\n << \" parent: \" << parent << \" (\" << G_OBJECT_TYPE_NAME(parent) << \")\"\n << \" widget path: \" << Gtk::gtk_widget_path( widget )\n << \" isTreeView: \" << (GTK_IS_TREE_VIEW(widget)?\"true\":\"false\")\n << \" isTextView: \" << (GTK_IS_TEXT_VIEW(widget)?\"true\":\"false\")\n << std::endl;\n #endif\n\n animations.innerShadowEngine().registerWidget( parent );\n animations.innerShadowEngine().registerChild( parent, widget );\n\n #endif \/\/ Gtk version\n return TRUE;\n\n }\n\n \/\/____________________________________________________________________________________________\n gboolean Animations::realizationHook( GSignalInvocationHint*, guint, const GValue* params, gpointer data )\n {\n\n \/\/ get widget from params\n GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) );\n\n \/\/ check type\n if( !GTK_IS_WIDGET( widget ) ) return FALSE;\n\n if( GTK_IS_NOTEBOOK( widget ) )\n { gtk_notebook_set_show_border( GTK_NOTEBOOK(widget), FALSE ); }\n\n #if ENABLE_GROUPBOX_HACK\n if( GTK_IS_LABEL( widget ) && GTK_IS_FRAME( gtk_widget_get_parent( widget ) ) )\n {\n\n GtkFrame *frame( GTK_FRAME( gtk_widget_get_parent( widget ) ) );\n if( widget == gtk_frame_get_label_widget( frame ) && !Gtk::gtk_widget_find_parent( widget, \"GtkPizza\" ) )\n {\n #if OXYGEN_DEBUG\n std::cout\n << \"Oxygen::Animations::realizationHook -\"\n << \" widget: \" << widget << \" (\" << G_OBJECT_TYPE_NAME( widget ) << \")\"\n << \" parent: \" << frame << \" (\" << G_OBJECT_TYPE_NAME( frame ) << \")\"\n << std::endl;\n #endif\n\n \/\/ modify alignment\n gtk_frame_set_label_align( frame, 0.5, 0.0 );\n gtk_frame_set_shadow_type( frame, GTK_SHADOW_OUT );\n\n \/\/ register to engine\n Animations& animations( *static_cast(data) );\n animations.groupBoxLabelEngine().registerWidget( widget );\n animations.groupBoxLabelEngine().adjustSize( widget );\n\n }\n\n }\n #endif\n\n return TRUE;\n\n }\n\n}\nForce shadow on known scrolled windows allready in innerShadowHook CCBUG: 316995\/*\n* this file is part of the oxygen gtk engine\n* Copyright (c) 2010 Hugo Pereira Da Costa \n* Copyright (c) 2010 Ruslan Kabatsayev \n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2 of the License, or(at your option ) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free\n* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n* MA 02110-1301, USA.\n*\/\n\n#include \"oxygenanimations.h\"\n#include \"..\/oxygengtkutils.h\"\n#include \"..\/oxygenqtsettings.h\"\n#include \"..\/config.h\"\n\n#include \n#include \n\nnamespace Oxygen\n{\n\n \/\/_________________________________________\n Animations::Animations( void ):\n _innerShadowsEnabled( true ),\n _hooksInitialized( false )\n {\n #if OXYGEN_DEBUG\n std::cerr << \"Oxygen::Animations::Animations\" << std::endl;\n #endif\n\n \/\/ create engines\n registerEngine( _backgroundHintEngine = new BackgroundHintEngine( this ) );\n registerEngine( _comboEngine = new ComboEngine( this ) );\n registerEngine( _comboBoxEngine = new ComboBoxEngine( this ) );\n registerEngine( _comboBoxEntryEngine = new ComboBoxEntryEngine( this ) );\n registerEngine( _dialogEngine = new DialogEngine( this ) );\n registerEngine( _flatWidgetEngine = new FlatWidgetEngine( this ) );\n registerEngine( _groupBoxEngine = new GroupBoxEngine( this ) );\n registerEngine( _groupBoxLabelEngine = new GroupBoxLabelEngine( this ) );\n registerEngine( _hoverEngine = new HoverEngine( this ) );\n registerEngine( _mainWindowEngine = new MainWindowEngine( this ) );\n registerEngine( _menuItemEngine = new MenuItemEngine( this ) );\n registerEngine( _panedEngine = new PanedEngine( this ) );\n registerEngine( _scrollBarEngine = new ScrollBarEngine( this ) );\n registerEngine( _scrolledWindowEngine = new ScrolledWindowEngine( this ) );\n registerEngine( _innerShadowEngine = new InnerShadowEngine( this ) );\n registerEngine( _tabWidgetEngine = new TabWidgetEngine( this ) );\n registerEngine( _treeViewEngine = new TreeViewEngine( this ) );\n registerEngine( _widgetSizeEngine = new WidgetSizeEngine( this ) );\n\n \/\/ animations specific engines\n registerEngine( _widgetStateEngine = new WidgetStateEngine( this ) );\n registerEngine( _arrowStateEngine = new ArrowStateEngine( this ) );\n registerEngine( _scrollBarStateEngine = new ScrollBarStateEngine( this ) );\n registerEngine( _tabWidgetStateEngine = new TabWidgetStateEngine( this ) );\n registerEngine( _treeViewStateEngine = new TreeViewStateEngine( this ) );\n registerEngine( _menuBarStateEngine = new MenuBarStateEngine( this ) );\n registerEngine( _menuStateEngine = new MenuStateEngine( this ) );\n registerEngine( _toolBarStateEngine = new ToolBarStateEngine( this ) );\n\n }\n\n \/\/____________________________________________________________________________________________\n Animations::~Animations( void )\n {\n #if OXYGEN_DEBUG\n std::cerr << \"Oxygen::Animations::~Animations\" << std::endl;\n #endif\n\n \/\/ delete all engines\n for( BaseEngine::List::iterator iter = _engines.begin(); iter != _engines.end(); ++iter )\n { delete *iter; }\n\n \/\/ disconnect all signals from map\n for( WidgetMap::iterator iter = _allWidgets.begin(); iter != _allWidgets.end(); iter++ )\n { iter->second.disconnect(); }\n\n \/\/ clear hooks\n _sizeAllocationHook.disconnect();\n _realizationHook.disconnect();\n _innerShadowHook.disconnect();\n\n }\n\n \/\/_________________________________________\n void Animations::initialize( const QtSettings& settings )\n {\n\n const bool animationsEnabled( settings.animationsEnabled() );\n\n \/\/ pass animations configuration to engines\n _widgetStateEngine->setApplicationName( settings.applicationName() );\n _widgetStateEngine->setEnabled( animationsEnabled && settings.genericAnimationsEnabled() );\n _widgetStateEngine->setDuration( settings.genericAnimationsDuration() );\n\n _arrowStateEngine->setApplicationName( settings.applicationName() );\n _arrowStateEngine->setEnabled( animationsEnabled && settings.genericAnimationsEnabled() );\n _arrowStateEngine->setDuration( settings.genericAnimationsDuration() );\n\n _scrollBarStateEngine->setApplicationName( settings.applicationName() );\n _scrollBarStateEngine->setEnabled( animationsEnabled && settings.genericAnimationsEnabled() );\n _scrollBarStateEngine->setDuration( settings.genericAnimationsDuration() );\n\n _tabWidgetStateEngine->setApplicationName( settings.applicationName() );\n _tabWidgetStateEngine->setEnabled( animationsEnabled && settings.genericAnimationsEnabled() );\n _tabWidgetStateEngine->setDuration( settings.genericAnimationsDuration() );\n\n _treeViewStateEngine->setApplicationName( settings.applicationName() );\n _treeViewStateEngine->setEnabled( animationsEnabled && settings.genericAnimationsEnabled() );\n _treeViewStateEngine->setDuration( settings.genericAnimationsDuration() );\n\n _menuBarStateEngine->setApplicationName( settings.applicationName() );\n _menuBarStateEngine->setAnimationsEnabled( animationsEnabled && (settings.menuBarAnimationType() != None) );\n _menuBarStateEngine->setFollowMouse( settings.menuBarAnimationType() == FollowMouse );\n _menuBarStateEngine->setDuration( settings.menuBarAnimationsDuration() );\n _menuBarStateEngine->setFollowMouseAnimationsDuration( settings.menuBarFollowMouseAnimationsDuration() );\n\n _menuStateEngine->setApplicationName( settings.applicationName() );\n _menuStateEngine->setEnabled( animationsEnabled && (settings.menuAnimationType() != None) );\n _menuStateEngine->setFollowMouse( settings.menuAnimationType() == FollowMouse );\n _menuStateEngine->setDuration( settings.menuAnimationsDuration() );\n _menuStateEngine->setFollowMouseAnimationsDuration( settings.menuFollowMouseAnimationsDuration() );\n\n \/\/ for now, only Fade animations mode is supported for toolbar animations\n _toolBarStateEngine->setApplicationName( settings.applicationName() );\n _toolBarStateEngine->setEnabled( animationsEnabled && (settings.toolBarAnimationType() != None) );\n _toolBarStateEngine->setFollowMouse( settings.toolBarAnimationType() == FollowMouse );\n _toolBarStateEngine->setDuration( settings.genericAnimationsDuration() );\n _toolBarStateEngine->setFollowMouseAnimationsDuration( settings.toolBarAnimationsDuration() );\n\n \/\/ background hint engine\n _backgroundHintEngine->setUseBackgroundGradient( settings.useBackgroundGradient() );\n\n }\n\n \/\/____________________________________________________________________________________________\n void Animations::initializeHooks( void )\n {\n if( _hooksInitialized ) return;\n\n \/\/ https:\/\/bugzilla.gnome.org\/show_bug.cgi?id=643416\n #if ENABLE_INNER_SHADOWS_HACK\n if(!getenv(\"OXYGEN_DISABLE_INNER_SHADOWS_HACK\"))\n { _innerShadowHook.connect( \"realize\", (GSignalEmissionHook)innerShadowHook, this ); }\n #endif\n\n _sizeAllocationHook.connect( \"size-allocate\", (GSignalEmissionHook)sizeAllocationHook, this );\n _realizationHook.connect( \"realize\", (GSignalEmissionHook)realizationHook, this );\n\n _hooksInitialized = true;\n }\n\n \/\/____________________________________________________________________________________________\n bool Animations::registerWidget( GtkWidget* widget )\n {\n\n if( _allWidgets.find( widget ) != _allWidgets.end() ) return false;\n\n #if OXYGEN_DEBUG\n std::cerr << \"Oxygen::Animations::registerWidget - \" << widget << \" (\" << (widget ? G_OBJECT_TYPE_NAME( widget ):\"0x0\") << \")\" << std::endl;\n #endif\n\n Signal destroyId;\n destroyId.connect( G_OBJECT( widget ), \"destroy\", G_CALLBACK( destroyNotifyEvent ), this );\n _allWidgets.insert( std::make_pair( widget, destroyId ) );\n return true;\n\n }\n\n \/\/____________________________________________________________________________________________\n void Animations::unregisterWidget( GtkWidget* widget )\n {\n\n #if OXYGEN_DEBUG\n std::cerr << \"Oxygen::Animations::unregisterWidget - \" << widget << \" (\" << G_OBJECT_TYPE_NAME( widget ) << \")\" << std::endl;\n #endif\n\n \/\/ find in map\n WidgetMap::iterator iter( _allWidgets.find( widget ) );\n assert( iter != _allWidgets.end() );\n\n \/\/ disconnect signal\n iter->second.disconnect();\n\n \/\/ erase from map\n _allWidgets.erase( widget );\n\n \/\/ erase from all maps\n for( BaseEngine::List::iterator iter = _engines.begin(); iter != _engines.end(); ++iter )\n { (*iter)->unregisterWidget( widget ); }\n\n }\n\n \/\/____________________________________________________________________________________________\n void Animations::setEnabled( bool value )\n {\n\n for( BaseEngine::List::iterator iter = _engines.begin(); iter != _engines.end(); ++iter )\n { (*iter)->setEnabled( value ); }\n\n }\n\n \/\/____________________________________________________________________________________________\n gboolean Animations::destroyNotifyEvent( GtkWidget* widget, gpointer data )\n {\n static_cast(data)->unregisterWidget( widget );\n return FALSE;\n }\n\n \/\/____________________________________________________________________________________________\n gboolean Animations::sizeAllocationHook( GSignalInvocationHint*, guint, const GValue* params, gpointer data )\n {\n\n \/\/ get widget from params\n GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) );\n\n \/\/ check type\n if( !GTK_IS_WIDGET( widget ) ) return FALSE;\n\n \/\/ cast data\n Animations& animations( *static_cast(data) );\n\n \/\/ groupbox labels\n #if ENABLE_GROUPBOX_HACK\n if( animations.groupBoxLabelEngine().contains( widget ) )\n {\n animations.groupBoxLabelEngine().adjustSize( widget );\n return TRUE;\n }\n #endif\n\n #if ENABLE_COMBOBOX_LIST_RESIZE\n \/\/ comboboxes\n if( !GTK_IS_WINDOW( widget ) ) return TRUE;\n\n GtkWindow* window( GTK_WINDOW( widget ) );\n if( gtk_window_get_type_hint( window ) != GDK_WINDOW_TYPE_HINT_COMBO ) return TRUE;\n\n GtkWidget* combobox = animations.comboBoxEngine().find( widget );\n if( !combobox ) combobox = animations.comboBoxEntryEngine().find( widget );\n if( !combobox ) combobox = animations.comboEngine().find( widget );\n if( !combobox ) return true;\n\n int w, h;\n gtk_window_get_size( window, &w, &h );\n\n gint targetX, dummy, y;\n gtk_window_get_position( window, &dummy, &y );\n gdk_window_get_origin( gtk_widget_get_window( combobox ), &targetX, &dummy );\n\n const GtkAllocation comboAllocation( Gtk::gtk_widget_get_allocation( combobox ) );\n int uglyShadowWidth=!Gtk::gdk_default_screen_is_composited();\n gtk_window_move( window, targetX + comboAllocation.x + 3 - uglyShadowWidth, y );\n\n const GtkAllocation widgetAllocation( Gtk::gtk_widget_get_allocation( widget ) );\n gtk_widget_set_size_request( widget, comboAllocation.width - 6 + 2*uglyShadowWidth, widgetAllocation.height );\n #endif\n\n return TRUE;\n\n }\n\n \/\/____________________________________________________________________________________________\n gboolean Animations::innerShadowHook( GSignalInvocationHint*, guint, const GValue* params, gpointer data )\n {\n\n #if GTK_CHECK_VERSION(2,24,2)\n\n \/\/ get widget from params\n GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) );\n\n \/\/ check type\n if( !GTK_IS_WIDGET( widget ) ) return FALSE;\n\n \/\/ check enabled state\n Animations& animations( *static_cast(data) );\n if( !animations.innerShadowsEnabled() ) return TRUE;\n\n \/\/ blacklist\n if( Gtk::g_object_is_a( G_OBJECT( widget ), \"SwtFixed\" ) ) return TRUE;\n if( Gtk::g_object_is_a( G_OBJECT( widget ), \"GtkPizza\" ) ) return TRUE;\n\n GtkWidget* parent(gtk_widget_get_parent(widget));\n if( !GTK_IS_SCROLLED_WINDOW( parent ) ) return TRUE;\n\n GtkWidget* child(gtk_bin_get_child(GTK_BIN(parent)));\n if(child!=widget) return TRUE;\n\n #if OXYGEN_DEBUG\n std::cerr\n << \"Oxygen::Animations::innerShadowHook -\"\n << \" widget: \" << widget << \" (\" << G_OBJECT_TYPE_NAME(widget) << \")\"\n << \" parent: \" << parent << \" (\" << G_OBJECT_TYPE_NAME(parent) << \")\"\n << \" widget path: \" << Gtk::gtk_widget_path( widget )\n << \" isTreeView: \" << (GTK_IS_TREE_VIEW(widget)?\"true\":\"false\")\n << \" isTextView: \" << (GTK_IS_TEXT_VIEW(widget)?\"true\":\"false\")\n << std::endl;\n #endif\n\n \/\/ force shadow type on known windows\n if( Gtk::gtk_scrolled_window_force_sunken( parent ) )\n { gtk_scrolled_window_set_shadow_type( GTK_SCROLLED_WINDOW( parent ), GTK_SHADOW_IN ); }\n\n animations.innerShadowEngine().registerWidget( parent );\n animations.innerShadowEngine().registerChild( parent, widget );\n\n #endif \/\/ Gtk version\n return TRUE;\n\n }\n\n \/\/____________________________________________________________________________________________\n gboolean Animations::realizationHook( GSignalInvocationHint*, guint, const GValue* params, gpointer data )\n {\n\n \/\/ get widget from params\n GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) );\n\n \/\/ check type\n if( !GTK_IS_WIDGET( widget ) ) return FALSE;\n\n if( GTK_IS_NOTEBOOK( widget ) )\n { gtk_notebook_set_show_border( GTK_NOTEBOOK(widget), FALSE ); }\n\n #if ENABLE_GROUPBOX_HACK\n if( GTK_IS_LABEL( widget ) && GTK_IS_FRAME( gtk_widget_get_parent( widget ) ) )\n {\n\n GtkFrame *frame( GTK_FRAME( gtk_widget_get_parent( widget ) ) );\n if( widget == gtk_frame_get_label_widget( frame ) && !Gtk::gtk_widget_find_parent( widget, \"GtkPizza\" ) )\n {\n #if OXYGEN_DEBUG\n std::cout\n << \"Oxygen::Animations::realizationHook -\"\n << \" widget: \" << widget << \" (\" << G_OBJECT_TYPE_NAME( widget ) << \")\"\n << \" parent: \" << frame << \" (\" << G_OBJECT_TYPE_NAME( frame ) << \")\"\n << std::endl;\n #endif\n\n \/\/ modify alignment\n gtk_frame_set_label_align( frame, 0.5, 0.0 );\n gtk_frame_set_shadow_type( frame, GTK_SHADOW_OUT );\n\n \/\/ register to engine\n Animations& animations( *static_cast(data) );\n animations.groupBoxLabelEngine().registerWidget( widget );\n animations.groupBoxLabelEngine().adjustSize( widget );\n\n }\n\n }\n #endif\n\n return TRUE;\n\n }\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"primes.hpp\"\n#include \"snv.hpp\"\n#include \"del.hpp\"\n#include \"read_parsers.hh\"\n\nusing namespace khmer;\nusing namespace read_parsers;\ntypedef Read Sequence;\ntypedef std::chrono::time_point timepoint;\n\ntypedef struct\n{\n uint delsize;\n ulong interval;\n uint ksize;\n ulong limit;\n uint histmax;\n uint numtables;\n double sampling_rate;\n int seed;\n std::string muttype;\n ulong targetsize;\n std::string infile;\n std::string refrfile;\n} ProgramArgs;\n\nvoid print_usage(std::ostream& stream = std::cerr)\n{\n stream << \"Usage: snv-hist [options] seqs.fa [genome.fa]\\n\";\n stream << \" options:\\n\";\n stream << \" -h print this help message and exit\\n\";\n stream << \" -i debug output interval (default: 1000000)\\n\";\n stream << \" -k k-mer length (default: 31)\\n\";\n stream << \" -l limit number of positions to process\\n\";\n stream << \" -m max histogram value (default: 16)\\n\";\n stream << \" -n num tables (default: 4)\\n\";\n stream << \" -r sampling rate (default: 1.0)\\n\";\n stream << \" -s seed for random number generator (default: 42)\\n\";\n stream << \" -t mutation type: snv (default), del\\n\";\n stream << \" -x approx table size (default: 5e8)\\n\";\n stream << \" -z deletion size (default: 5)\\n\";\n}\n\nvoid parse_args(int argc, const char **argv, ProgramArgs *args)\n{\n char c;\n while ((c = getopt (argc, (char *const *)argv, \"d:hi:k:l:m:n:r:s:t:x:z:\")) != -1) {\n if (c == 'd') {\n args->delsize = atoi(optarg);\n }\n else if (c == 'h') {\n print_usage(std::cout);\n exit(0);\n }\n else if (c == 'i') {\n args->interval = atoi(optarg);\n }\n else if (c == 'k') {\n args->ksize = atoi(optarg);\n }\n else if (c == 'l') {\n args->limit = atoi(optarg);\n }\n else if (c == 'm') {\n args->histmax = atoi(optarg);\n }\n else if (c == 'n') {\n args->numtables = atoi(optarg);\n }\n else if (c == 'r') {\n args->sampling_rate = atof(optarg);\n }\n else if (c == 's') {\n args->seed = atoi(optarg);\n }\n else if (c == 't') {\n args->muttype = optarg;\n }\n else if (c == 'x') {\n args->targetsize = atoi(optarg);\n }\n else if (c == 'z') {\n args->delsize = atoi(optarg);\n }\n else {\n std::cerr << \"Unknown option '\" << c << \"'\\n\";\n print_usage();\n exit(1);\n }\n }\n\n args->infile = argv[optind];\n args->refrfile = argv[optind];\n if (argc > optind + 1) {\n args->refrfile = argv[optind + 1];\n }\n}\n\nint main(int argc, const char **argv)\n{\n if (argc == 1) {\n print_usage(std::cout);\n return 0;\n }\n\n ProgramArgs args = {5, 1000000, 31, 0, 16, 4, 1.0, 42, \"snv\", 500000000, \"\", \"\"};\n parse_args(argc, argv, &args);\n\n std::cerr << \"# allocating countgraph\\n\";\n std::vector tablesizes = get_n_primes_near_x(args.targetsize, args.numtables);\n Countgraph countgraph(args.ksize, tablesizes);\n\n std::cerr << \"# consuming reference...\";\n timepoint start = std::chrono::system_clock::now();\n unsigned int seqs_consumed = 0;\n unsigned long long kmers_consumed = 0;\n countgraph.consume_fasta(args.refrfile, seqs_consumed, kmers_consumed);\n timepoint end = std::chrono::system_clock::now();\n std::chrono::duration elapsed = end - start;\n std::cerr << \"consumed \" << seqs_consumed << \" sequence(s) and \"\n << kmers_consumed << \" \" << args.ksize << \"-mers (in \" << elapsed.count() << \" seconds)\\n\";\n\n std::cerr << \"# querying k-mer abundance...\\n\\n\";\n Logger logger(args.interval, std::cerr);\n std::unique_ptr mut = NULL;\n if(args.muttype == \"snv\") {\n mut.reset(new MutatorSNV(args.ksize, logger, args.histmax, args.limit));\n }\n else if(args.muttype == \"del\") {\n mut.reset(new MutatorDel(args.ksize, args.delsize, logger, args.histmax, args.limit));\n }\n else {\n std::cerr << \"Error: unknown mutation type '\" << args.muttype << \"'\\n\";\n exit(1);\n }\n mut->set_sampling_rate(args.sampling_rate, args.seed);\n\n IParser *parser = IParser::get_parser(args.infile);\n Sequence seq;\n while (!parser->is_complete()) {\n try {\n seq = parser->get_next_read();\n } catch (NoMoreReadsAvailable &e) {\n break;\n }\n mut->process(seq.sequence, countgraph);\n }\n std::cout << *mut;\n delete parser;\n\n return 0;\n}\nBringing the C++ code up to date#include \n#include \n#include \n#include \"primes.hpp\"\n#include \"snv.hpp\"\n#include \"del.hpp\"\n#include \"read_parsers.hh\"\n\nusing namespace khmer;\nusing namespace read_parsers;\ntypedef Read Sequence;\ntypedef std::chrono::time_point timepoint;\n\ntypedef struct\n{\n uint delsize;\n ulong interval;\n uint ksize;\n ulong limit;\n uint histmax;\n uint numtables;\n double sampling_rate;\n int seed;\n std::string muttype;\n ulong targetsize;\n std::string infile;\n std::string refrfile;\n} ProgramArgs;\n\nvoid print_usage(std::ostream& stream = std::cerr)\n{\n stream << \"Usage: snv-hist [options] seqs.fa [genome.fa]\\n\";\n stream << \" options:\\n\";\n stream << \" -h print this help message and exit\\n\";\n stream << \" -i debug output interval (default: 1000000)\\n\";\n stream << \" -k k-mer length (default: 31)\\n\";\n stream << \" -l limit number of positions to process\\n\";\n stream << \" -m max histogram value (default: 16)\\n\";\n stream << \" -n num tables (default: 4)\\n\";\n stream << \" -r sampling rate (default: 1.0)\\n\";\n stream << \" -s seed for random number generator (default: 42)\\n\";\n stream << \" -t mutation type: snv (default), del\\n\";\n stream << \" -x approx table size (default: 5e8)\\n\";\n stream << \" -z deletion size (default: 5)\\n\";\n}\n\nvoid parse_args(int argc, const char **argv, ProgramArgs *args)\n{\n char c;\n while ((c = getopt (argc, (char *const *)argv, \"d:hi:k:l:m:n:r:s:t:x:z:\")) != -1) {\n if (c == 'd') {\n args->delsize = atoi(optarg);\n }\n else if (c == 'h') {\n print_usage(std::cout);\n exit(0);\n }\n else if (c == 'i') {\n args->interval = atoi(optarg);\n }\n else if (c == 'k') {\n args->ksize = atoi(optarg);\n }\n else if (c == 'l') {\n args->limit = atoi(optarg);\n }\n else if (c == 'm') {\n args->histmax = atoi(optarg);\n }\n else if (c == 'n') {\n args->numtables = atoi(optarg);\n }\n else if (c == 'r') {\n args->sampling_rate = atof(optarg);\n }\n else if (c == 's') {\n args->seed = atoi(optarg);\n }\n else if (c == 't') {\n args->muttype = optarg;\n }\n else if (c == 'x') {\n args->targetsize = atoi(optarg);\n }\n else if (c == 'z') {\n args->delsize = atoi(optarg);\n }\n else {\n std::cerr << \"Unknown option '\" << c << \"'\\n\";\n print_usage();\n exit(1);\n }\n }\n\n args->infile = argv[optind];\n args->refrfile = argv[optind];\n if (argc > optind + 1) {\n args->refrfile = argv[optind + 1];\n }\n}\n\nint main(int argc, const char **argv)\n{\n if (argc == 1) {\n print_usage(std::cout);\n return 0;\n }\n\n ProgramArgs args = {5, 1000000, 31, 0, 16, 4, 1.0, 42, \"snv\", 500000000, \"\", \"\"};\n parse_args(argc, argv, &args);\n\n std::cerr << \"# allocating countgraph\\n\";\n std::vector tablesizes = get_n_primes_near_x(args.targetsize, args.numtables);\n Countgraph countgraph(args.ksize, tablesizes);\n\n std::cerr << \"# consuming reference...\";\n timepoint start = std::chrono::system_clock::now();\n unsigned int seqs_consumed = 0;\n unsigned long long kmers_consumed = 0;\n countgraph.consume_seqfile(args.refrfile, seqs_consumed, kmers_consumed);\n timepoint end = std::chrono::system_clock::now();\n std::chrono::duration elapsed = end - start;\n std::cerr << \"consumed \" << seqs_consumed << \" sequence(s) and \"\n << kmers_consumed << \" \" << args.ksize << \"-mers (in \" << elapsed.count() << \" seconds)\\n\";\n\n std::cerr << \"# querying k-mer abundance...\\n\\n\";\n Logger logger(args.interval, std::cerr);\n std::unique_ptr mut = NULL;\n if(args.muttype == \"snv\") {\n mut.reset(new MutatorSNV(args.ksize, logger, args.histmax, args.limit));\n }\n else if(args.muttype == \"del\") {\n mut.reset(new MutatorDel(args.ksize, args.delsize, logger, args.histmax, args.limit));\n }\n else {\n std::cerr << \"Error: unknown mutation type '\" << args.muttype << \"'\\n\";\n exit(1);\n }\n mut->set_sampling_rate(args.sampling_rate, args.seed);\n\n FastxParserPtr parser = get_parser(args.infile);\n Sequence seq;\n while (!parser->is_complete()) {\n try {\n seq = parser->get_next_read();\n } catch (NoMoreReadsAvailable &e) {\n break;\n }\n mut->process(seq.sequence, countgraph);\n }\n std::cout << *mut;\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n#include \n#include \n\n#include \"hlinettp.hxx\"\n#include \"hlmarkwn_def.hxx\"\n\nsal_Char const sAnonymous[] = \"anonymous\";\nsal_Char const sHTTPScheme[] = INET_HTTP_SCHEME;\nsal_Char const sFTPScheme[] = INET_FTP_SCHEME;\n\n\/*************************************************************************\n|*\n|* Constructor \/ Destructor\n|*\n|************************************************************************\/\n\nSvxHyperlinkInternetTp::SvxHyperlinkInternetTp ( vcl::Window *pParent,\n IconChoiceDialog* pDlg,\n const SfxItemSet& rItemSet)\n: SvxHyperlinkTabPageBase ( pParent, pDlg, \"HyperlinkInternetPage\", \"cui\/ui\/hyperlinkinternetpage.ui\",\n rItemSet ) ,\n mbMarkWndOpen ( false )\n{\n get(m_pRbtLinktypInternet, \"linktyp_internet\");\n get(m_pRbtLinktypFTP, \"linktyp_ftp\");\n get(m_pCbbTarget, \"target\");\n m_pCbbTarget->SetSmartProtocol(INET_PROT_HTTP);\n get(m_pBtBrowse, \"browse\");\n m_pBtBrowse->SetModeImage(Image(CUI_RES (RID_SVXBMP_BROWSE)));\n get(m_pFtLogin, \"login_label\");\n get(m_pEdLogin, \"login\");\n get(m_pFtPassword, \"password_label\");\n get(m_pEdPassword, \"password\");\n get(m_pCbAnonymous, \"anonymous\");\n\n \/\/ Disable display of bitmap names.\n m_pBtBrowse->EnableTextDisplay (false);\n\n InitStdControls();\n\n m_pCbbTarget->Show();\n m_pCbbTarget->SetHelpId( HID_HYPERDLG_INET_PATH );\n\n SetExchangeSupport ();\n\n\n \/\/ set defaults\n m_pRbtLinktypInternet->Check ();\n m_pBtBrowse->Enable( true );\n\n\n \/\/ set handlers\n Link aLink( LINK ( this, SvxHyperlinkInternetTp, Click_SmartProtocol_Impl ) );\n m_pRbtLinktypInternet->SetClickHdl( aLink );\n m_pRbtLinktypFTP->SetClickHdl ( aLink );\n m_pCbAnonymous->SetClickHdl ( LINK ( this, SvxHyperlinkInternetTp, ClickAnonymousHdl_Impl ) );\n m_pBtBrowse->SetClickHdl ( LINK ( this, SvxHyperlinkInternetTp, ClickBrowseHdl_Impl ) );\n m_pEdLogin->SetModifyHdl ( LINK ( this, SvxHyperlinkInternetTp, ModifiedLoginHdl_Impl ) );\n m_pCbbTarget->SetLoseFocusHdl ( LINK ( this, SvxHyperlinkInternetTp, LostFocusTargetHdl_Impl ) );\n m_pCbbTarget->SetModifyHdl ( LINK ( this, SvxHyperlinkInternetTp, ModifiedTargetHdl_Impl ) );\n maTimer.SetTimeoutHdl ( LINK ( this, SvxHyperlinkInternetTp, TimeoutHdl_Impl ) );\n}\n\nSvxHyperlinkInternetTp::~SvxHyperlinkInternetTp ()\n{\n}\n\n\/*************************************************************************\n|*\n|* Fill the all dialog-controls except controls in groupbox \"more...\"\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkInternetTp::FillDlgFields(const OUString& rStrURL)\n{\n INetURLObject aURL(rStrURL);\n OUString aStrScheme(GetSchemeFromURL(rStrURL));\n\n \/\/ set additional controls for FTP: Username \/ Password\n if (aStrScheme.startsWith(sFTPScheme))\n {\n if ( aURL.GetUser().toAsciiLowerCase().startsWith( sAnonymous ) )\n setAnonymousFTPUser();\n else\n setFTPUser(aURL.GetUser(), aURL.GetPass());\n\n \/\/do not show password and user in url\n if(!aURL.GetUser().isEmpty() || !aURL.GetPass().isEmpty() )\n aURL.SetUserAndPass(aEmptyStr,aEmptyStr);\n }\n\n \/\/ set URL-field\n \/\/ Show the scheme, #72740\n if ( aURL.GetProtocol() != INET_PROT_NOT_VALID )\n m_pCbbTarget->SetText( aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS ) );\n else\n m_pCbbTarget->SetText(rStrURL); \/\/ #77696#\n\n SetScheme(aStrScheme);\n}\n\nvoid SvxHyperlinkInternetTp::setAnonymousFTPUser()\n{\n m_pEdLogin->SetText(OUString(sAnonymous));\n SvAddressParser aAddress( SvtUserOptions().GetEmail() );\n m_pEdPassword->SetText( aAddress.Count() ? aAddress.GetEmailAddress(0) : OUString() );\n\n m_pFtLogin->Disable ();\n m_pFtPassword->Disable ();\n m_pEdLogin->Disable ();\n m_pEdPassword->Disable ();\n m_pCbAnonymous->Check();\n}\n\nvoid SvxHyperlinkInternetTp::setFTPUser(const OUString& rUser, const OUString& rPassword)\n{\n m_pEdLogin->SetText ( rUser );\n m_pEdPassword->SetText ( rPassword );\n\n m_pFtLogin->Enable ();\n m_pFtPassword->Enable ();\n m_pEdLogin->Enable ();\n m_pEdPassword->Enable ();\n m_pCbAnonymous->Check(false);\n}\n\n\/*************************************************************************\n|*\n|* retrieve and prepare data from dialog-fields\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkInternetTp::GetCurentItemData ( OUString& rStrURL, OUString& aStrName,\n OUString& aStrIntName, OUString& aStrFrame,\n SvxLinkInsertMode& eMode )\n{\n rStrURL = CreateAbsoluteURL();\n GetDataFromCommonFields( aStrName, aStrIntName, aStrFrame, eMode );\n}\n\nOUString SvxHyperlinkInternetTp::CreateAbsoluteURL() const\n{\n \/\/ erase leading and trailing whitespaces\n OUString aStrURL( m_pCbbTarget->GetText().trim() );\n\n INetURLObject aURL(aStrURL);\n\n if( aURL.GetProtocol() == INET_PROT_NOT_VALID )\n {\n aURL.SetSmartProtocol( GetSmartProtocolFromButtons() );\n aURL.SetSmartURL(aStrURL);\n }\n\n \/\/ username and password for ftp-url\n if( aURL.GetProtocol() == INET_PROT_FTP && !m_pEdLogin->GetText().isEmpty() )\n aURL.SetUserAndPass ( m_pEdLogin->GetText(), m_pEdPassword->GetText() );\n\n if ( aURL.GetProtocol() != INET_PROT_NOT_VALID )\n return aURL.GetMainURL( INetURLObject::DECODE_WITH_CHARSET );\n else \/\/#105788# always create a URL even if it is not valid\n return aStrURL;\n}\n\n\/*************************************************************************\n|*\n|* static method to create Tabpage\n|*\n|************************************************************************\/\n\nIconChoicePage* SvxHyperlinkInternetTp::Create( vcl::Window* pWindow, IconChoiceDialog* pDlg, const SfxItemSet& rItemSet )\n{\n return( new SvxHyperlinkInternetTp( pWindow, pDlg, rItemSet ) );\n}\n\n\/*************************************************************************\n|*\n|* Set initial focus\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkInternetTp::SetInitFocus()\n{\n m_pCbbTarget->GrabFocus();\n}\n\n\/*************************************************************************\n|*\n|* Contents of editfield \"Target\" modified\n|*\n|************************************************************************\/\n\nIMPL_LINK_NOARG(SvxHyperlinkInternetTp, ModifiedTargetHdl_Impl)\n{\n OUString aScheme = GetSchemeFromURL( m_pCbbTarget->GetText() );\n if( !aScheme.isEmpty() )\n SetScheme( aScheme );\n\n \/\/ start timer\n maTimer.SetTimeout( 2500 );\n maTimer.Start();\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* If target-field was modify, to browse the new doc after timeout\n|*\n|************************************************************************\/\n\nIMPL_LINK_NOARG(SvxHyperlinkInternetTp, TimeoutHdl_Impl)\n{\n RefreshMarkWindow();\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Contents of editfield \"Login\" modified\n|*\n|************************************************************************\/\n\nIMPL_LINK_NOARG(SvxHyperlinkInternetTp, ModifiedLoginHdl_Impl)\n{\n OUString aStrLogin ( m_pEdLogin->GetText() );\n if ( aStrLogin.equalsIgnoreAsciiCase( sAnonymous ) )\n {\n m_pCbAnonymous->Check();\n ClickAnonymousHdl_Impl(NULL);\n }\n\n return( 0L );\n}\n\n\/*************************************************************************\n|************************************************************************\/\n\nvoid SvxHyperlinkInternetTp::SetScheme(const OUString& rScheme)\n{\n \/\/if rScheme is empty or unknown the default beaviour is like it where HTTP\n bool bFTP = rScheme.startsWith(sFTPScheme);\n bool bInternet = !(bFTP);\n\n \/\/update protocol button selection:\n m_pRbtLinktypFTP->Check(bFTP);\n m_pRbtLinktypInternet->Check(bInternet);\n\n \/\/update target:\n RemoveImproperProtocol(rScheme);\n m_pCbbTarget->SetSmartProtocol( GetSmartProtocolFromButtons() );\n\n \/\/show\/hide special fields for FTP:\n m_pFtLogin->Show( bFTP );\n m_pFtPassword->Show( bFTP );\n m_pEdLogin->Show( bFTP );\n m_pEdPassword->Show( bFTP );\n m_pCbAnonymous->Show( bFTP );\n\n \/\/update 'link target in document'-window and opening-button\n if (rScheme.startsWith(sHTTPScheme) || rScheme.isEmpty())\n {\n if ( mbMarkWndOpen )\n ShowMarkWnd ();\n }\n else\n {\n \/\/disable for https and ftp\n if ( mbMarkWndOpen )\n HideMarkWnd ();\n }\n}\n\n\/*************************************************************************\n|*\n|* Remove protocol if it does not fit to the current button selection\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkInternetTp::RemoveImproperProtocol(const OUString& aProperScheme)\n{\n OUString aStrURL ( m_pCbbTarget->GetText() );\n if ( aStrURL != aEmptyStr )\n {\n OUString aStrScheme(GetSchemeFromURL(aStrURL));\n if ( !aStrScheme.isEmpty() && aStrScheme != aProperScheme )\n {\n aStrURL = aStrURL.copy( aStrScheme.getLength() );\n m_pCbbTarget->SetText ( aStrURL );\n }\n }\n}\n\nOUString SvxHyperlinkInternetTp::GetSchemeFromButtons() const\n{\n if( m_pRbtLinktypFTP->IsChecked() )\n return OUString(INET_FTP_SCHEME);\n return OUString(INET_HTTP_SCHEME);\n}\n\nINetProtocol SvxHyperlinkInternetTp::GetSmartProtocolFromButtons() const\n{\n if( m_pRbtLinktypFTP->IsChecked() )\n {\n return INET_PROT_FTP;\n }\n return INET_PROT_HTTP;\n}\n\n\/*************************************************************************\n|*\n|* Click on Radiobutton : Internet or FTP\n|*\n|************************************************************************\/\n\nIMPL_LINK_NOARG(SvxHyperlinkInternetTp, Click_SmartProtocol_Impl)\n{\n OUString aScheme = GetSchemeFromButtons();\n SetScheme(aScheme);\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Click on Checkbox : Anonymous user\n|*\n|************************************************************************\/\n\nIMPL_LINK_NOARG(SvxHyperlinkInternetTp, ClickAnonymousHdl_Impl)\n{\n \/\/ disable login-editfields if checked\n if ( m_pCbAnonymous->IsChecked() )\n {\n if ( m_pEdLogin->GetText().toAsciiLowerCase().startsWith( sAnonymous ) )\n {\n maStrOldUser = aEmptyStr;\n maStrOldPassword = aEmptyStr;\n }\n else\n {\n maStrOldUser = m_pEdLogin->GetText();\n maStrOldPassword = m_pEdPassword->GetText();\n }\n\n setAnonymousFTPUser();\n }\n else\n setFTPUser(maStrOldUser, maStrOldPassword);\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Combobox Target lost the focus\n|*\n|************************************************************************\/\n\nIMPL_LINK_NOARG(SvxHyperlinkInternetTp, LostFocusTargetHdl_Impl)\n{\n RefreshMarkWindow();\n return (0L);\n}\n\n\/*************************************************************************\n|*\n|* Click on imagebutton : Browse\n|*\n|************************************************************************\/\n\nIMPL_LINK_NOARG(SvxHyperlinkInternetTp, ClickBrowseHdl_Impl)\n{\n\n \/\/ Open URL if available\n\n SfxStringItem aName( SID_FILE_NAME, OUString(\"http:\/\/\") );\n SfxStringItem aRefererItem( SID_REFERER, OUString(\"private:user\") );\n SfxBoolItem aNewView( SID_OPEN_NEW_VIEW, true );\n SfxBoolItem aSilent( SID_SILENT, true );\n SfxBoolItem aReadOnly( SID_DOC_READONLY, true );\n\n SfxBoolItem aBrowse( SID_BROWSE, true );\n\n const SfxPoolItem *ppItems[] = { &aName, &aNewView, &aSilent, &aReadOnly, &aRefererItem, &aBrowse, NULL };\n static_cast(mpDialog)->GetBindings()->Execute( SID_OPENDOC, ppItems, 0, SfxCallMode::ASYNCHRON | SfxCallMode::RECORD );\n\n return( 0L );\n}\n\nvoid SvxHyperlinkInternetTp::RefreshMarkWindow()\n{\n if ( m_pRbtLinktypInternet->IsChecked() && IsMarkWndVisible() )\n {\n EnterWait();\n OUString aStrURL( CreateAbsoluteURL() );\n if ( aStrURL != aEmptyStr )\n mpMarkWnd->RefreshTree ( aStrURL );\n else\n mpMarkWnd->SetError( LERR_DOCNOTOPEN );\n LeaveWait();\n }\n\n}\n\n\/*************************************************************************\n|*\n|* Get String from Bookmark-Wnd\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkInternetTp::SetMarkStr ( const OUString& aStrMark )\n{\n OUString aStrURL ( m_pCbbTarget->GetText() );\n\n const sal_Unicode sUHash = '#';\n sal_Int32 nPos = aStrURL.lastIndexOf( sUHash );\n\n if( nPos != -1 )\n aStrURL = aStrURL.copy(0, nPos);\n\n aStrURL += OUStringLiteral1() + aStrMark;\n\n m_pCbbTarget->SetText ( aStrURL );\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nDo not corrupt URIs entered into the Hyperlink dialog\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n#include \n#include \n\n#include \"hlinettp.hxx\"\n#include \"hlmarkwn_def.hxx\"\n\nsal_Char const sAnonymous[] = \"anonymous\";\nsal_Char const sHTTPScheme[] = INET_HTTP_SCHEME;\nsal_Char const sFTPScheme[] = INET_FTP_SCHEME;\n\n\/*************************************************************************\n|*\n|* Constructor \/ Destructor\n|*\n|************************************************************************\/\n\nSvxHyperlinkInternetTp::SvxHyperlinkInternetTp ( vcl::Window *pParent,\n IconChoiceDialog* pDlg,\n const SfxItemSet& rItemSet)\n: SvxHyperlinkTabPageBase ( pParent, pDlg, \"HyperlinkInternetPage\", \"cui\/ui\/hyperlinkinternetpage.ui\",\n rItemSet ) ,\n mbMarkWndOpen ( false )\n{\n get(m_pRbtLinktypInternet, \"linktyp_internet\");\n get(m_pRbtLinktypFTP, \"linktyp_ftp\");\n get(m_pCbbTarget, \"target\");\n m_pCbbTarget->SetSmartProtocol(INET_PROT_HTTP);\n get(m_pBtBrowse, \"browse\");\n m_pBtBrowse->SetModeImage(Image(CUI_RES (RID_SVXBMP_BROWSE)));\n get(m_pFtLogin, \"login_label\");\n get(m_pEdLogin, \"login\");\n get(m_pFtPassword, \"password_label\");\n get(m_pEdPassword, \"password\");\n get(m_pCbAnonymous, \"anonymous\");\n\n \/\/ Disable display of bitmap names.\n m_pBtBrowse->EnableTextDisplay (false);\n\n InitStdControls();\n\n m_pCbbTarget->Show();\n m_pCbbTarget->SetHelpId( HID_HYPERDLG_INET_PATH );\n\n SetExchangeSupport ();\n\n\n \/\/ set defaults\n m_pRbtLinktypInternet->Check ();\n m_pBtBrowse->Enable( true );\n\n\n \/\/ set handlers\n Link aLink( LINK ( this, SvxHyperlinkInternetTp, Click_SmartProtocol_Impl ) );\n m_pRbtLinktypInternet->SetClickHdl( aLink );\n m_pRbtLinktypFTP->SetClickHdl ( aLink );\n m_pCbAnonymous->SetClickHdl ( LINK ( this, SvxHyperlinkInternetTp, ClickAnonymousHdl_Impl ) );\n m_pBtBrowse->SetClickHdl ( LINK ( this, SvxHyperlinkInternetTp, ClickBrowseHdl_Impl ) );\n m_pEdLogin->SetModifyHdl ( LINK ( this, SvxHyperlinkInternetTp, ModifiedLoginHdl_Impl ) );\n m_pCbbTarget->SetLoseFocusHdl ( LINK ( this, SvxHyperlinkInternetTp, LostFocusTargetHdl_Impl ) );\n m_pCbbTarget->SetModifyHdl ( LINK ( this, SvxHyperlinkInternetTp, ModifiedTargetHdl_Impl ) );\n maTimer.SetTimeoutHdl ( LINK ( this, SvxHyperlinkInternetTp, TimeoutHdl_Impl ) );\n}\n\nSvxHyperlinkInternetTp::~SvxHyperlinkInternetTp ()\n{\n}\n\n\/*************************************************************************\n|*\n|* Fill the all dialog-controls except controls in groupbox \"more...\"\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkInternetTp::FillDlgFields(const OUString& rStrURL)\n{\n INetURLObject aURL(rStrURL);\n OUString aStrScheme(GetSchemeFromURL(rStrURL));\n\n \/\/ set additional controls for FTP: Username \/ Password\n if (aStrScheme.startsWith(sFTPScheme))\n {\n if ( aURL.GetUser().toAsciiLowerCase().startsWith( sAnonymous ) )\n setAnonymousFTPUser();\n else\n setFTPUser(aURL.GetUser(), aURL.GetPass());\n\n \/\/do not show password and user in url\n if(!aURL.GetUser().isEmpty() || !aURL.GetPass().isEmpty() )\n aURL.SetUserAndPass(aEmptyStr,aEmptyStr);\n }\n\n \/\/ set URL-field\n \/\/ Show the scheme, #72740\n if ( aURL.GetProtocol() != INET_PROT_NOT_VALID )\n m_pCbbTarget->SetText( aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS ) );\n else\n m_pCbbTarget->SetText(rStrURL); \/\/ #77696#\n\n SetScheme(aStrScheme);\n}\n\nvoid SvxHyperlinkInternetTp::setAnonymousFTPUser()\n{\n m_pEdLogin->SetText(OUString(sAnonymous));\n SvAddressParser aAddress( SvtUserOptions().GetEmail() );\n m_pEdPassword->SetText( aAddress.Count() ? aAddress.GetEmailAddress(0) : OUString() );\n\n m_pFtLogin->Disable ();\n m_pFtPassword->Disable ();\n m_pEdLogin->Disable ();\n m_pEdPassword->Disable ();\n m_pCbAnonymous->Check();\n}\n\nvoid SvxHyperlinkInternetTp::setFTPUser(const OUString& rUser, const OUString& rPassword)\n{\n m_pEdLogin->SetText ( rUser );\n m_pEdPassword->SetText ( rPassword );\n\n m_pFtLogin->Enable ();\n m_pFtPassword->Enable ();\n m_pEdLogin->Enable ();\n m_pEdPassword->Enable ();\n m_pCbAnonymous->Check(false);\n}\n\n\/*************************************************************************\n|*\n|* retrieve and prepare data from dialog-fields\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkInternetTp::GetCurentItemData ( OUString& rStrURL, OUString& aStrName,\n OUString& aStrIntName, OUString& aStrFrame,\n SvxLinkInsertMode& eMode )\n{\n rStrURL = CreateAbsoluteURL();\n GetDataFromCommonFields( aStrName, aStrIntName, aStrFrame, eMode );\n}\n\nOUString SvxHyperlinkInternetTp::CreateAbsoluteURL() const\n{\n \/\/ erase leading and trailing whitespaces\n OUString aStrURL( m_pCbbTarget->GetText().trim() );\n\n INetURLObject aURL(aStrURL);\n\n if( aURL.GetProtocol() == INET_PROT_NOT_VALID )\n {\n aURL.SetSmartProtocol( GetSmartProtocolFromButtons() );\n aURL.SetSmartURL(aStrURL);\n }\n\n \/\/ username and password for ftp-url\n if( aURL.GetProtocol() == INET_PROT_FTP && !m_pEdLogin->GetText().isEmpty() )\n aURL.SetUserAndPass ( m_pEdLogin->GetText(), m_pEdPassword->GetText() );\n\n if ( aURL.GetProtocol() != INET_PROT_NOT_VALID )\n return aURL.GetMainURL( INetURLObject::DECODE_TO_IURI );\n else \/\/#105788# always create a URL even if it is not valid\n return aStrURL;\n}\n\n\/*************************************************************************\n|*\n|* static method to create Tabpage\n|*\n|************************************************************************\/\n\nIconChoicePage* SvxHyperlinkInternetTp::Create( vcl::Window* pWindow, IconChoiceDialog* pDlg, const SfxItemSet& rItemSet )\n{\n return( new SvxHyperlinkInternetTp( pWindow, pDlg, rItemSet ) );\n}\n\n\/*************************************************************************\n|*\n|* Set initial focus\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkInternetTp::SetInitFocus()\n{\n m_pCbbTarget->GrabFocus();\n}\n\n\/*************************************************************************\n|*\n|* Contents of editfield \"Target\" modified\n|*\n|************************************************************************\/\n\nIMPL_LINK_NOARG(SvxHyperlinkInternetTp, ModifiedTargetHdl_Impl)\n{\n OUString aScheme = GetSchemeFromURL( m_pCbbTarget->GetText() );\n if( !aScheme.isEmpty() )\n SetScheme( aScheme );\n\n \/\/ start timer\n maTimer.SetTimeout( 2500 );\n maTimer.Start();\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* If target-field was modify, to browse the new doc after timeout\n|*\n|************************************************************************\/\n\nIMPL_LINK_NOARG(SvxHyperlinkInternetTp, TimeoutHdl_Impl)\n{\n RefreshMarkWindow();\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Contents of editfield \"Login\" modified\n|*\n|************************************************************************\/\n\nIMPL_LINK_NOARG(SvxHyperlinkInternetTp, ModifiedLoginHdl_Impl)\n{\n OUString aStrLogin ( m_pEdLogin->GetText() );\n if ( aStrLogin.equalsIgnoreAsciiCase( sAnonymous ) )\n {\n m_pCbAnonymous->Check();\n ClickAnonymousHdl_Impl(NULL);\n }\n\n return( 0L );\n}\n\n\/*************************************************************************\n|************************************************************************\/\n\nvoid SvxHyperlinkInternetTp::SetScheme(const OUString& rScheme)\n{\n \/\/if rScheme is empty or unknown the default beaviour is like it where HTTP\n bool bFTP = rScheme.startsWith(sFTPScheme);\n bool bInternet = !(bFTP);\n\n \/\/update protocol button selection:\n m_pRbtLinktypFTP->Check(bFTP);\n m_pRbtLinktypInternet->Check(bInternet);\n\n \/\/update target:\n RemoveImproperProtocol(rScheme);\n m_pCbbTarget->SetSmartProtocol( GetSmartProtocolFromButtons() );\n\n \/\/show\/hide special fields for FTP:\n m_pFtLogin->Show( bFTP );\n m_pFtPassword->Show( bFTP );\n m_pEdLogin->Show( bFTP );\n m_pEdPassword->Show( bFTP );\n m_pCbAnonymous->Show( bFTP );\n\n \/\/update 'link target in document'-window and opening-button\n if (rScheme.startsWith(sHTTPScheme) || rScheme.isEmpty())\n {\n if ( mbMarkWndOpen )\n ShowMarkWnd ();\n }\n else\n {\n \/\/disable for https and ftp\n if ( mbMarkWndOpen )\n HideMarkWnd ();\n }\n}\n\n\/*************************************************************************\n|*\n|* Remove protocol if it does not fit to the current button selection\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkInternetTp::RemoveImproperProtocol(const OUString& aProperScheme)\n{\n OUString aStrURL ( m_pCbbTarget->GetText() );\n if ( aStrURL != aEmptyStr )\n {\n OUString aStrScheme(GetSchemeFromURL(aStrURL));\n if ( !aStrScheme.isEmpty() && aStrScheme != aProperScheme )\n {\n aStrURL = aStrURL.copy( aStrScheme.getLength() );\n m_pCbbTarget->SetText ( aStrURL );\n }\n }\n}\n\nOUString SvxHyperlinkInternetTp::GetSchemeFromButtons() const\n{\n if( m_pRbtLinktypFTP->IsChecked() )\n return OUString(INET_FTP_SCHEME);\n return OUString(INET_HTTP_SCHEME);\n}\n\nINetProtocol SvxHyperlinkInternetTp::GetSmartProtocolFromButtons() const\n{\n if( m_pRbtLinktypFTP->IsChecked() )\n {\n return INET_PROT_FTP;\n }\n return INET_PROT_HTTP;\n}\n\n\/*************************************************************************\n|*\n|* Click on Radiobutton : Internet or FTP\n|*\n|************************************************************************\/\n\nIMPL_LINK_NOARG(SvxHyperlinkInternetTp, Click_SmartProtocol_Impl)\n{\n OUString aScheme = GetSchemeFromButtons();\n SetScheme(aScheme);\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Click on Checkbox : Anonymous user\n|*\n|************************************************************************\/\n\nIMPL_LINK_NOARG(SvxHyperlinkInternetTp, ClickAnonymousHdl_Impl)\n{\n \/\/ disable login-editfields if checked\n if ( m_pCbAnonymous->IsChecked() )\n {\n if ( m_pEdLogin->GetText().toAsciiLowerCase().startsWith( sAnonymous ) )\n {\n maStrOldUser = aEmptyStr;\n maStrOldPassword = aEmptyStr;\n }\n else\n {\n maStrOldUser = m_pEdLogin->GetText();\n maStrOldPassword = m_pEdPassword->GetText();\n }\n\n setAnonymousFTPUser();\n }\n else\n setFTPUser(maStrOldUser, maStrOldPassword);\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Combobox Target lost the focus\n|*\n|************************************************************************\/\n\nIMPL_LINK_NOARG(SvxHyperlinkInternetTp, LostFocusTargetHdl_Impl)\n{\n RefreshMarkWindow();\n return (0L);\n}\n\n\/*************************************************************************\n|*\n|* Click on imagebutton : Browse\n|*\n|************************************************************************\/\n\nIMPL_LINK_NOARG(SvxHyperlinkInternetTp, ClickBrowseHdl_Impl)\n{\n\n \/\/ Open URL if available\n\n SfxStringItem aName( SID_FILE_NAME, OUString(\"http:\/\/\") );\n SfxStringItem aRefererItem( SID_REFERER, OUString(\"private:user\") );\n SfxBoolItem aNewView( SID_OPEN_NEW_VIEW, true );\n SfxBoolItem aSilent( SID_SILENT, true );\n SfxBoolItem aReadOnly( SID_DOC_READONLY, true );\n\n SfxBoolItem aBrowse( SID_BROWSE, true );\n\n const SfxPoolItem *ppItems[] = { &aName, &aNewView, &aSilent, &aReadOnly, &aRefererItem, &aBrowse, NULL };\n static_cast(mpDialog)->GetBindings()->Execute( SID_OPENDOC, ppItems, 0, SfxCallMode::ASYNCHRON | SfxCallMode::RECORD );\n\n return( 0L );\n}\n\nvoid SvxHyperlinkInternetTp::RefreshMarkWindow()\n{\n if ( m_pRbtLinktypInternet->IsChecked() && IsMarkWndVisible() )\n {\n EnterWait();\n OUString aStrURL( CreateAbsoluteURL() );\n if ( aStrURL != aEmptyStr )\n mpMarkWnd->RefreshTree ( aStrURL );\n else\n mpMarkWnd->SetError( LERR_DOCNOTOPEN );\n LeaveWait();\n }\n\n}\n\n\/*************************************************************************\n|*\n|* Get String from Bookmark-Wnd\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkInternetTp::SetMarkStr ( const OUString& aStrMark )\n{\n OUString aStrURL ( m_pCbbTarget->GetText() );\n\n const sal_Unicode sUHash = '#';\n sal_Int32 nPos = aStrURL.lastIndexOf( sUHash );\n\n if( nPos != -1 )\n aStrURL = aStrURL.copy(0, nPos);\n\n aStrURL += OUStringLiteral1() + aStrMark;\n\n m_pCbbTarget->SetText ( aStrURL );\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2011, Nathan Rajlich \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include \n#include \n#include \n\nusing namespace v8;\nusing namespace node;\n\nnamespace {\n\n\nHandle node_get_lame_version (const Arguments& args) {\n HandleScope scope;\n return scope.Close(String::New(get_lame_version()));\n}\n\nvoid Initialize(Handle target) {\n HandleScope scope;\n\n NODE_SET_METHOD(target, \"get_lame_version\", node_get_lame_version);\n\n}\n\n} \/\/ anonymous namespace\n\nNODE_MODULE(nodelame, Initialize);\nSome more bindings\/*\n * Copyright (c) 2011, Nathan Rajlich \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include \n#include \n#include \n\nusing namespace v8;\nusing namespace node;\n\nnamespace {\n\n\/* Wrapper ObjectTemplate to hold `lame_t` instances *\/\nPersistent gfpClass;\n\n\n\/* get_lame_version() *\/\nHandle node_get_lame_version (const Arguments& args) {\n HandleScope scope;\n return scope.Close(String::New(get_lame_version()));\n}\n\n\n\/* malloc()'s a `lame_t` struct and returns it to JS land *\/\nHandle node_malloc_gfp (const Arguments& args) {\n HandleScope scope;\n\n lame_global_flags *gfp = lame_init();\n\n Local wrapper = gfpClass->NewInstance();\n wrapper->SetPointerInInternalField(0, gfp);\n\n return scope.Close(wrapper);\n}\n\n\n\/* lame_get_num_channels(gfp) *\/\nHandle node_lame_get_num_channels (const Arguments& args) {\n HandleScope scope;\n \/\/ TODO: Argument validation\n Local wrapper = args[0]->ToObject();\n lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0);\n\n return scope.Close(Integer::New(lame_get_num_channels(gfp)));\n}\n\n\n\/* lame_set_num_channels(gfp) *\/\nHandle node_lame_set_num_channels (const Arguments& args) {\n HandleScope scope;\n \/\/ TODO: Argument validation\n Local wrapper = args[0]->ToObject();\n lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0);\n\n Local val = args[1]->ToNumber();\n return scope.Close(Integer::New(lame_set_num_channels(gfp, val->Int32Value())));\n}\n\n\n\/* lame_init_params(gfp) *\/\nHandle node_lame_init_params (const Arguments& args) {\n HandleScope scope;\n \/\/ TODO: Argument validation\n Local wrapper = args[0]->ToObject();\n lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0);\n\n if (lame_init_params(gfp) == -1) {\n return ThrowException(String::New(\"lame_init_params() failed\"));\n }\n return Undefined();\n}\n\n\n\/* lame_print_config() *\/\nHandle node_lame_print_config (const Arguments& args) {\n HandleScope scope;\n \/\/ TODO: Argument validation\n Local wrapper = args[0]->ToObject();\n lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0);\n\n lame_print_config(gfp);\n return Undefined();\n}\n\n\nvoid Initialize(Handle target) {\n HandleScope scope;\n\n gfpClass = Persistent::New(ObjectTemplate::New());\n gfpClass->SetInternalFieldCount(1);\n\n NODE_SET_METHOD(target, \"get_lame_version\", node_get_lame_version);\n NODE_SET_METHOD(target, \"lame_get_num_channels\", node_lame_get_num_channels);\n NODE_SET_METHOD(target, \"lame_set_num_channels\", node_lame_set_num_channels);\n NODE_SET_METHOD(target, \"lame_init_params\", node_lame_init_params);\n NODE_SET_METHOD(target, \"lame_print_config\", node_lame_print_config);\n NODE_SET_METHOD(target, \"malloc_gfp\", node_malloc_gfp);\n\n}\n\n} \/\/ anonymous namespace\n\nNODE_MODULE(nodelame, Initialize);\n<|endoftext|>"} {"text":"\/* tcpstream.cpp\n Copyright (C) 2003-2005 Tommi Maekitalo\n\nThis file is part of cxxtools.\n\nCxxtools is free software; you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nCxxtools is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Cxxtools; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330,\nBoston, MA 02111-1307 USA\n*\/\n\n#include \"cxxtools\/tcpstream.h\"\n#include \n#include \n#include \n#include \n\n#ifdef DEBUG\n\n#include \"cxxtools\/log.h\"\nlog_define(\"cxxtools.net\");\n\n#else\n\n#define log_warn(expr)\n#define log_debug(expr)\n\n#endif\n\nnamespace cxxtools\n{\n\nnamespace net\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ implementation of Server\n \/\/\n Server::Server()\n : Socket(AF_INET, SOCK_STREAM, 0)\n { }\n\n Server::Server(const std::string& ipaddr, unsigned short int port,\n int backlog) throw (Exception)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n listen(ipaddr, port, backlog);\n }\n\n Server::Server(const char* ipaddr, unsigned short int port,\n int backlog) throw (Exception)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n listen(ipaddr, port, backlog);\n }\n\n void Server::listen(const char* ipaddr, unsigned short int port,\n int backlog) throw (Exception)\n {\n struct hostent* host = ::gethostbyname(ipaddr);\n if (host == 0)\n throw Exception(std::string(\"invalid ipaddress \") + ipaddr);\n\n memset(&servaddr.sockaddr_in, 0, sizeof(servaddr.sockaddr_in));\n\n servaddr.sockaddr_in.sin_family = AF_INET;\n servaddr.sockaddr_in.sin_port = htons(port);\n\n memmove(&(servaddr.sockaddr_in.sin_addr.s_addr), host->h_addr, host->h_length);\n int reuseAddr = 1;\n if (::setsockopt(getFd(), SOL_SOCKET, SO_REUSEADDR,\n &reuseAddr, sizeof(reuseAddr)) < 0)\n throw Exception(\"setsockopt\");\n\n if (::bind(getFd(),\n (struct sockaddr *)&servaddr.sockaddr_in,\n sizeof(servaddr.sockaddr_in)) < 0)\n throw Exception(\"bind\");\n\n if (::listen(getFd(), backlog) < 0)\n throw Exception(\"listen\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ implementation of Stream\n \/\/\n Stream::Stream()\n { }\n\n Stream::Stream(const Server& server)\n {\n accept(server);\n }\n\n Stream::Stream(const std::string& ipaddr, unsigned short int port)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n connect(ipaddr, port);\n }\n\n Stream::Stream(const char* ipaddr, unsigned short int port)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n connect(ipaddr, port);\n }\n\n void Stream::accept(const Server& server)\n {\n close();\n\n socklen_t peeraddr_len;\n peeraddr_len = sizeof(peeraddr);\n setFd(::accept(server.getFd(), &peeraddr.sockaddr, &peeraddr_len));\n if (bad())\n throw Exception(\"accept\");\n\n setTimeout(getTimeout());\n }\n\n void Stream::connect(const char* ipaddr, unsigned short int port)\n {\n if (getFd() < 0)\n create(AF_INET, SOCK_STREAM, 0);\n\n struct hostent* host = ::gethostbyname(ipaddr);\n if (host == 0)\n throw Exception(std::string(\"invalid ipaddress \") + ipaddr);\n\n memset(&peeraddr, 0, sizeof(peeraddr));\n peeraddr.sockaddr_in.sin_family = AF_INET;\n peeraddr.sockaddr_in.sin_port = htons(port);\n\n memmove(&(peeraddr.sockaddr_in.sin_addr.s_addr), host->h_addr, host->h_length);\n\n if (::connect(getFd(), &peeraddr.sockaddr,\n sizeof(peeraddr)) < 0)\n throw Exception(\"connect\");\n\n setTimeout(getTimeout());\n }\n\n Stream::size_type Stream::read(char* buffer, Stream::size_type bufsize) const\n {\n ssize_t n;\n\n if (getTimeout() < 0)\n {\n \/\/ blocking read\n log_debug(\"blocking read\");\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"blocking read ready, return \" << n);\n if (n < 0)\n throw Exception(\"read\");\n }\n else\n {\n \/\/ non-blocking read\n\n \/\/ try reading without timeout\n log_debug(\"non blocking read fd=\" << getFd());\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"non blocking read returns \" << n);\n\n if (n < 0)\n {\n \/\/ no data available\n\n if (errno == EAGAIN)\n {\n if (getTimeout() == 0)\n {\n log_warn(\"timeout\");\n throw Timeout();\n }\n\n doPoll(POLLIN);\n\n log_debug(\"read\");\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"read returns \" << n);\n if (n < 0)\n throw Exception(\"read\");\n }\n else\n {\n throw Exception(\"read\");\n }\n }\n\n }\n\n return n;\n }\n\n Stream::size_type Stream::write(const char* buffer,\n Stream::size_type bufsize) const\n {\n log_debug(\"Stream::write \" << bufsize << \" bytes\");\n\n ssize_t n = 0;\n size_type s = bufsize;\n\n while (true)\n {\n n = ::write(getFd(), buffer, s);\n log_debug(\"::write returns => \" << n);\n\n if (n < 0)\n throw Exception(\"write\");\n\n buffer += n;\n s -= n;\n\n if (s <= 0)\n break;\n\n doPoll(POLLOUT);\n }\n\n return bufsize;\n }\n\n streambuf::streambuf(Stream& stream, unsigned bufsize, int timeout)\n : m_stream(stream),\n m_bufsize(bufsize),\n m_buffer(new char_type[bufsize])\n {\n setTimeout(timeout);\n }\n\n streambuf::int_type streambuf::overflow(streambuf::int_type c)\n {\n if (pptr() != pbase())\n {\n try\n {\n int n = m_stream.write(pbase(), pptr() - pbase());\n if (n <= 0)\n return traits_type::eof();\n }\n catch (const Exception& e)\n {\n log_warn(e.what());\n return traits_type::eof();\n }\n }\n\n setp(m_buffer, m_buffer + m_bufsize);\n if (c != traits_type::eof())\n {\n *pptr() = (char_type)c;\n pbump(1);\n }\n\n return 0;\n }\n\n streambuf::int_type streambuf::underflow()\n {\n try\n {\n Stream::size_type n = m_stream.read(m_buffer, m_bufsize);\n if (n <= 0)\n return traits_type::eof();\n\n setg(m_buffer, m_buffer, m_buffer + n);\n return (int_type)(unsigned char)m_buffer[0];\n }\n catch (const Timeout& e)\n {\n throw;\n }\n catch (const Exception& e)\n {\n log_warn(e.what());\n return traits_type::eof();\n }\n }\n\n int streambuf::sync()\n {\n if (pptr() != pbase())\n {\n try\n {\n int n = m_stream.write(pbase(), pptr() - pbase());\n if (n <= 0)\n return -1;\n else\n setp(m_buffer, m_buffer + m_bufsize);\n }\n catch (const Exception& e)\n {\n log_warn(e.what());\n return -1;\n }\n }\n return 0;\n }\n\n} \/\/ namespace net\n\n} \/\/ namespace cxxtools\nfixed bug when write is unavailable\/* tcpstream.cpp\n Copyright (C) 2003-2005 Tommi Maekitalo\n\nThis file is part of cxxtools.\n\nCxxtools is free software; you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nCxxtools is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Cxxtools; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330,\nBoston, MA 02111-1307 USA\n*\/\n\n#include \"cxxtools\/tcpstream.h\"\n#include \n#include \n#include \n#include \n\n#ifdef DEBUG\n\n#include \"cxxtools\/log.h\"\nlog_define(\"cxxtools.net\");\n\n#else\n\n#define log_warn(expr)\n#define log_debug(expr)\n\n#endif\n\nnamespace cxxtools\n{\n\nnamespace net\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ implementation of Server\n \/\/\n Server::Server()\n : Socket(AF_INET, SOCK_STREAM, 0)\n { }\n\n Server::Server(const std::string& ipaddr, unsigned short int port,\n int backlog) throw (Exception)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n listen(ipaddr, port, backlog);\n }\n\n Server::Server(const char* ipaddr, unsigned short int port,\n int backlog) throw (Exception)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n listen(ipaddr, port, backlog);\n }\n\n void Server::listen(const char* ipaddr, unsigned short int port,\n int backlog) throw (Exception)\n {\n struct hostent* host = ::gethostbyname(ipaddr);\n if (host == 0)\n throw Exception(std::string(\"invalid ipaddress \") + ipaddr);\n\n memset(&servaddr.sockaddr_in, 0, sizeof(servaddr.sockaddr_in));\n\n servaddr.sockaddr_in.sin_family = AF_INET;\n servaddr.sockaddr_in.sin_port = htons(port);\n\n memmove(&(servaddr.sockaddr_in.sin_addr.s_addr), host->h_addr, host->h_length);\n int reuseAddr = 1;\n if (::setsockopt(getFd(), SOL_SOCKET, SO_REUSEADDR,\n &reuseAddr, sizeof(reuseAddr)) < 0)\n throw Exception(\"setsockopt\");\n\n if (::bind(getFd(),\n (struct sockaddr *)&servaddr.sockaddr_in,\n sizeof(servaddr.sockaddr_in)) < 0)\n throw Exception(\"bind\");\n\n if (::listen(getFd(), backlog) < 0)\n throw Exception(\"listen\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ implementation of Stream\n \/\/\n Stream::Stream()\n { }\n\n Stream::Stream(const Server& server)\n {\n accept(server);\n }\n\n Stream::Stream(const std::string& ipaddr, unsigned short int port)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n connect(ipaddr, port);\n }\n\n Stream::Stream(const char* ipaddr, unsigned short int port)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n connect(ipaddr, port);\n }\n\n void Stream::accept(const Server& server)\n {\n close();\n\n socklen_t peeraddr_len;\n peeraddr_len = sizeof(peeraddr);\n setFd(::accept(server.getFd(), &peeraddr.sockaddr, &peeraddr_len));\n if (bad())\n throw Exception(\"accept\");\n\n setTimeout(getTimeout());\n }\n\n void Stream::connect(const char* ipaddr, unsigned short int port)\n {\n if (getFd() < 0)\n create(AF_INET, SOCK_STREAM, 0);\n\n struct hostent* host = ::gethostbyname(ipaddr);\n if (host == 0)\n throw Exception(std::string(\"invalid ipaddress \") + ipaddr);\n\n memset(&peeraddr, 0, sizeof(peeraddr));\n peeraddr.sockaddr_in.sin_family = AF_INET;\n peeraddr.sockaddr_in.sin_port = htons(port);\n\n memmove(&(peeraddr.sockaddr_in.sin_addr.s_addr), host->h_addr, host->h_length);\n\n if (::connect(getFd(), &peeraddr.sockaddr,\n sizeof(peeraddr)) < 0)\n throw Exception(\"connect\");\n\n setTimeout(getTimeout());\n }\n\n Stream::size_type Stream::read(char* buffer, Stream::size_type bufsize) const\n {\n ssize_t n;\n\n if (getTimeout() < 0)\n {\n \/\/ blocking read\n log_debug(\"blocking read\");\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"blocking read ready, return \" << n);\n if (n < 0)\n throw Exception(\"read\");\n }\n else\n {\n \/\/ non-blocking read\n\n \/\/ try reading without timeout\n log_debug(\"non blocking read fd=\" << getFd());\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"non blocking read returns \" << n);\n\n if (n < 0)\n {\n \/\/ no data available\n\n if (errno == EAGAIN)\n {\n if (getTimeout() == 0)\n {\n log_warn(\"timeout\");\n throw Timeout();\n }\n\n doPoll(POLLIN);\n\n log_debug(\"read\");\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"read returns \" << n);\n if (n < 0)\n throw Exception(\"read\");\n }\n else\n {\n throw Exception(\"read\");\n }\n }\n\n }\n\n return n;\n }\n\n Stream::size_type Stream::write(const char* buffer,\n Stream::size_type bufsize) const\n {\n log_debug(\"Stream::write \" << bufsize << \" bytes\");\n\n ssize_t n = 0;\n size_type s = bufsize;\n\n while (true)\n {\n n = ::write(getFd(), buffer, s);\n log_debug(\"::write returns => \" << n);\n\n if (n < 0)\n {\n if (errno == EAGAIN)\n n = 0;\n else\n throw Exception(\"write\");\n }\n\n buffer += n;\n s -= n;\n\n if (s <= 0)\n break;\n\n doPoll(POLLOUT);\n }\n\n return bufsize;\n }\n\n streambuf::streambuf(Stream& stream, unsigned bufsize, int timeout)\n : m_stream(stream),\n m_bufsize(bufsize),\n m_buffer(new char_type[bufsize])\n {\n setTimeout(timeout);\n }\n\n streambuf::int_type streambuf::overflow(streambuf::int_type c)\n {\n if (pptr() != pbase())\n {\n try\n {\n int n = m_stream.write(pbase(), pptr() - pbase());\n if (n <= 0)\n return traits_type::eof();\n }\n catch (const Exception& e)\n {\n log_warn(e.what());\n return traits_type::eof();\n }\n }\n\n setp(m_buffer, m_buffer + m_bufsize);\n if (c != traits_type::eof())\n {\n *pptr() = (char_type)c;\n pbump(1);\n }\n\n return 0;\n }\n\n streambuf::int_type streambuf::underflow()\n {\n try\n {\n Stream::size_type n = m_stream.read(m_buffer, m_bufsize);\n if (n <= 0)\n return traits_type::eof();\n\n setg(m_buffer, m_buffer, m_buffer + n);\n return (int_type)(unsigned char)m_buffer[0];\n }\n catch (const Timeout& e)\n {\n throw;\n }\n catch (const Exception& e)\n {\n log_warn(e.what());\n return traits_type::eof();\n }\n }\n\n int streambuf::sync()\n {\n if (pptr() != pbase())\n {\n try\n {\n int n = m_stream.write(pbase(), pptr() - pbase());\n if (n <= 0)\n return -1;\n else\n setp(m_buffer, m_buffer + m_bufsize);\n }\n catch (const Exception& e)\n {\n log_warn(e.what());\n return -1;\n }\n }\n return 0;\n }\n\n} \/\/ namespace net\n\n} \/\/ namespace cxxtools\n<|endoftext|>"} {"text":"#include \"hphp\/runtime\/base\/base-includes.h\"\n#include \"hphp\/runtime\/ext\/std\/ext_std_errorfunc.h\"\n#include \"hphp\/runtime\/base\/php-globals.h\"\n#include \"hphp\/runtime\/base\/hphp-system.h\"\n#include \"hphp\/runtime\/ext\/ext_hotprofiler.h\"\n#include \"newrelic_transaction.h\"\n#include \"newrelic_collector_client.h\"\n#include \"newrelic_common.h\"\n#include \"newrelic_profiler.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace HPHP {\n\nbool keep_running = true;\n\nclass ScopedGenericSegment : public SweepableResourceData {\npublic:\n DECLARE_RESOURCE_ALLOCATION(ScopedGenericSegment)\n CLASSNAME_IS(\"scoped_generic_segment\")\n\n virtual const String& o_getClassNameHook() const { return classnameof(); }\n\n explicit ScopedGenericSegment(string name) : name(name) {\n segment_id = newrelic_segment_generic_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, name.c_str());\n }\n\n virtual ~ScopedGenericSegment() {\n if (segment_id < 0) return;\n newrelic_segment_end(NEWRELIC_AUTOSCOPE, segment_id);\n }\n\nprivate:\n int64_t segment_id;\n string name;\n};\n\nvoid ScopedGenericSegment::sweep() { }\n\nclass ScopedDatastoreSegment : public SweepableResourceData {\npublic:\n DECLARE_RESOURCE_ALLOCATION(ScopedDatastoreSegment)\n CLASSNAME_IS(\"scoped_database_segment\")\n\n virtual const String& o_getClassNameHook() const { return classnameof(); }\n\n explicit ScopedDatastoreSegment(string table, string operation) : table(table), operation(operation) {\n\/\/ TODO segment_id = newrelic_segment_datastore_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, table.c_str(), operation.c_str());\n }\n\n virtual ~ScopedDatastoreSegment() {\n if (segment_id < 0) return;\n newrelic_segment_end(NEWRELIC_AUTOSCOPE, segment_id);\n }\n\nprivate:\n int64_t segment_id;\n string table;\n string operation;\n};\n\nvoid ScopedDatastoreSegment::sweep() { }\n\n\nclass ScopedExternalSegment : public SweepableResourceData {\npublic:\n DECLARE_RESOURCE_ALLOCATION(ScopedExternalSegment)\n CLASSNAME_IS(\"scoped_external_segment\")\n\n virtual const String& o_getClassNameHook() const { return classnameof(); }\n\n explicit ScopedExternalSegment(string host, string name) : host(host), name(name) {\n segment_id = newrelic_segment_external_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, host.c_str(), name.c_str());\n }\n\n virtual ~ScopedExternalSegment() {\n if (segment_id < 0) return;\n newrelic_segment_end(NEWRELIC_AUTOSCOPE, segment_id);\n }\n\nprivate:\n int64_t segment_id;\n string host;\n string name;\n};\n\nvoid ScopedExternalSegment::sweep() { }\n\n\/\/ Profiler factory- for starting and stopping the profiler\nDECLARE_EXTERN_REQUEST_LOCAL(ProfilerFactory, s_profiler_factory);\n\nstatic int64_t HHVM_FUNCTION(newrelic_start_transaction_intern) {\n int64_t transaction_id = newrelic_transaction_begin();\n return transaction_id;\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_name_transaction_intern, const String & name) {\n return newrelic_transaction_set_name(NEWRELIC_AUTOSCOPE, name.c_str());\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_transaction_set_request_url, const String & request_url) {\n return newrelic_transaction_set_request_url(NEWRELIC_AUTOSCOPE, request_url.c_str());\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_transaction_set_max_trace_segments, int threshold) {\n return newrelic_transaction_set_max_trace_segments(NEWRELIC_AUTOSCOPE, threshold);\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_transaction_set_threshold, int threshold) {\n \/\/deprecated\n return false;\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_end_transaction) {\n return newrelic_transaction_end(NEWRELIC_AUTOSCOPE);\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_segment_generic_begin, const String & name) {\n return newrelic_segment_generic_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, name.c_str());\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_segment_datastore_begin, const String & table, const String & operation, const String & sql, const String & sql_trace_rollup_name, String & sql_obfuscator) {\n\/\/ TODO return newrelic_segment_datastore_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, table.c_str(), operation.c_str(), sql.c_str(), sql_trace_rollup_name.c_str(), sql_obfuscator.c_str());\n return false;\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_segment_external_begin, const String & host, const String & name) {\n return newrelic_segment_external_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, host.c_str(), name.c_str());\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_segment_end, int64_t id) {\n return newrelic_segment_end(NEWRELIC_AUTOSCOPE, id);\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_notice_error_intern, const String & exception_type, const String & error_message, const String & stack_trace, const String & stack_frame_delimiter) {\n return newrelic_transaction_notice_error(NEWRELIC_AUTOSCOPE, exception_type.c_str(), error_message.c_str(), stack_trace.c_str(), stack_frame_delimiter.c_str());\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_add_attribute_intern, const String & name, const String & value) {\n return newrelic_transaction_add_attribute(NEWRELIC_AUTOSCOPE, name.c_str(), value.c_str());\n}\n\nstatic void HHVM_FUNCTION(newrelic_set_external_profiler, int64_t maxdepth ) {\n Profiler *pr = new NewRelicProfiler(maxdepth);\n s_profiler_factory->setExternalProfiler(pr);\n}\n\nstatic Variant HHVM_FUNCTION(newrelic_get_scoped_generic_segment, const String & name) {\n ScopedGenericSegment * segment = nullptr;\n segment = newres(name.c_str());\n return Resource(segment);\n}\n\nstatic Variant HHVM_FUNCTION(newrelic_get_scoped_database_segment, const String & table, const String & operation) {\n ScopedDatastoreSegment * segment = nullptr;\n segment = newres(table.c_str(), operation.c_str());\n return Resource(segment);\n}\n\nstatic Variant HHVM_FUNCTION(newrelic_get_scoped_external_segment, const String & host, const String & name) {\n ScopedExternalSegment * segment = nullptr;\n segment = newres(host.c_str(), name.c_str());\n return Resource(segment);\n}\n\nconst StaticString\n s__NR_ERROR_CALLBACK(\"NewRelicExtensionHelper::errorCallback\"),\n s__NR_EXCEPTION_CALLBACK(\"NewRelicExtensionHelper::exceptionCallback\");\n\nstatic class NewRelicExtension : public Extension {\npublic:\n NewRelicExtension () : Extension(\"newrelic\", NO_EXTENSION_VERSION_YET) {\n config_loaded = false;\n }\n\n virtual void init_newrelic() {\n newrelic_register_message_handler(newrelic_message_handler);\n newrelic_init(license_key.c_str(), app_name.c_str(), app_language.c_str(), app_language_version.c_str());\n }\n\n virtual void moduleLoad(const IniSetting::Map& ini, Hdf config) {\n\n license_key = RuntimeOption::EnvVariables[\"NEWRELIC_LICENSE_KEY\"];\n app_name = RuntimeOption::EnvVariables[\"NEWRELIC_APP_NAME\"];\n app_language = RuntimeOption::EnvVariables[\"NEWRELIC_APP_LANGUAGE\"];\n app_language_version = RuntimeOption::EnvVariables[\"NEWRELIC_APP_LANGUAGE_VERSION\"];\n\n if (app_language.empty()) {\n app_language = \"php-hhvm\";\n }\n\n if (app_language_version.empty()) {\n app_language_version = HPHP::getHphpCompilerVersion();\n }\n\n\n setenv(\"NEWRELIC_LICENSE_KEY\", license_key.c_str(), 1);\n setenv(\"NEWRELIC_APP_NAME\", app_name.c_str(), 1);\n setenv(\"NEWRELIC_APP_LANGUAGE\", app_language.c_str(), 1);\n setenv(\"NEWRELIC_APP_LANGUAGE_VERSION\", app_language_version.c_str(), 1);\n\n if (!license_key.empty() && !app_name.empty() && !app_language.empty() && !app_language_version.empty())\n config_loaded = true;\n\n }\n\n\n void moduleInit () override {\n if (config_loaded) init_newrelic();\n\n HHVM_FE(newrelic_start_transaction_intern);\n HHVM_FE(newrelic_name_transaction_intern);\n HHVM_FE(newrelic_transaction_set_request_url);\n HHVM_FE(newrelic_transaction_set_max_trace_segments);\n HHVM_FE(newrelic_transaction_set_threshold);\n HHVM_FE(newrelic_end_transaction);\n HHVM_FE(newrelic_segment_generic_begin);\n HHVM_FE(newrelic_segment_datastore_begin);\n HHVM_FE(newrelic_segment_external_begin);\n HHVM_FE(newrelic_segment_end);\n HHVM_FE(newrelic_get_scoped_generic_segment);\n HHVM_FE(newrelic_get_scoped_database_segment);\n HHVM_FE(newrelic_get_scoped_external_segment);\n HHVM_FE(newrelic_notice_error_intern);\n HHVM_FE(newrelic_add_attribute_intern);\n HHVM_FE(newrelic_set_external_profiler);\n\n loadSystemlib();\n }\n\n virtual void requestShutdown() {\n\n newrelic_transaction_end(NEWRELIC_AUTOSCOPE);\n }\n\n void requestInit() override {\n auto serverVars = php_global(s__SERVER).toArray();\n\n f_set_error_handler(s__NR_ERROR_CALLBACK);\n f_set_exception_handler(s__NR_EXCEPTION_CALLBACK);\n \/\/TODO: make it possible to disable that via ini\n newrelic_transaction_begin();\n String request_url = php_global(s__SERVER).toArray()[s__REQUEST_URI].toString();\n String request_url = serverVars[s__REQUEST_URI].toString();\n newrelic_transaction_set_request_url(NEWRELIC_AUTOSCOPE, request_url.c_str());\n String script_name = php_global(s__SERVER).toArray()[s__SCRIPT_NAME].toString();\n String script_name = serverVars[s__SCRIPT_NAME].toString();\n newrelic_transaction_set_name(NEWRELIC_AUTOSCOPE, script_name.c_str());\n }\n\nprivate:\n std::string license_key;\n std::string app_name;\n std::string app_language;\n std::string app_language_version;\n int64_t global_transaction_id = 0;\n bool config_loaded;\n\n} s_newrelic_extension;\n\nHHVM_GET_MODULE(newrelic)\n\n} \/\/ namespace HPHP\nremove double code#include \"hphp\/runtime\/base\/base-includes.h\"\n#include \"hphp\/runtime\/ext\/std\/ext_std_errorfunc.h\"\n#include \"hphp\/runtime\/base\/php-globals.h\"\n#include \"hphp\/runtime\/base\/hphp-system.h\"\n#include \"hphp\/runtime\/ext\/ext_hotprofiler.h\"\n#include \"newrelic_transaction.h\"\n#include \"newrelic_collector_client.h\"\n#include \"newrelic_common.h\"\n#include \"newrelic_profiler.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace HPHP {\n\nbool keep_running = true;\n\nclass ScopedGenericSegment : public SweepableResourceData {\npublic:\n DECLARE_RESOURCE_ALLOCATION(ScopedGenericSegment)\n CLASSNAME_IS(\"scoped_generic_segment\")\n\n virtual const String& o_getClassNameHook() const { return classnameof(); }\n\n explicit ScopedGenericSegment(string name) : name(name) {\n segment_id = newrelic_segment_generic_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, name.c_str());\n }\n\n virtual ~ScopedGenericSegment() {\n if (segment_id < 0) return;\n newrelic_segment_end(NEWRELIC_AUTOSCOPE, segment_id);\n }\n\nprivate:\n int64_t segment_id;\n string name;\n};\n\nvoid ScopedGenericSegment::sweep() { }\n\nclass ScopedDatastoreSegment : public SweepableResourceData {\npublic:\n DECLARE_RESOURCE_ALLOCATION(ScopedDatastoreSegment)\n CLASSNAME_IS(\"scoped_database_segment\")\n\n virtual const String& o_getClassNameHook() const { return classnameof(); }\n\n explicit ScopedDatastoreSegment(string table, string operation) : table(table), operation(operation) {\n\/\/ TODO segment_id = newrelic_segment_datastore_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, table.c_str(), operation.c_str());\n }\n\n virtual ~ScopedDatastoreSegment() {\n if (segment_id < 0) return;\n newrelic_segment_end(NEWRELIC_AUTOSCOPE, segment_id);\n }\n\nprivate:\n int64_t segment_id;\n string table;\n string operation;\n};\n\nvoid ScopedDatastoreSegment::sweep() { }\n\n\nclass ScopedExternalSegment : public SweepableResourceData {\npublic:\n DECLARE_RESOURCE_ALLOCATION(ScopedExternalSegment)\n CLASSNAME_IS(\"scoped_external_segment\")\n\n virtual const String& o_getClassNameHook() const { return classnameof(); }\n\n explicit ScopedExternalSegment(string host, string name) : host(host), name(name) {\n segment_id = newrelic_segment_external_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, host.c_str(), name.c_str());\n }\n\n virtual ~ScopedExternalSegment() {\n if (segment_id < 0) return;\n newrelic_segment_end(NEWRELIC_AUTOSCOPE, segment_id);\n }\n\nprivate:\n int64_t segment_id;\n string host;\n string name;\n};\n\nvoid ScopedExternalSegment::sweep() { }\n\n\/\/ Profiler factory- for starting and stopping the profiler\nDECLARE_EXTERN_REQUEST_LOCAL(ProfilerFactory, s_profiler_factory);\n\nstatic int64_t HHVM_FUNCTION(newrelic_start_transaction_intern) {\n int64_t transaction_id = newrelic_transaction_begin();\n return transaction_id;\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_name_transaction_intern, const String & name) {\n return newrelic_transaction_set_name(NEWRELIC_AUTOSCOPE, name.c_str());\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_transaction_set_request_url, const String & request_url) {\n return newrelic_transaction_set_request_url(NEWRELIC_AUTOSCOPE, request_url.c_str());\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_transaction_set_max_trace_segments, int threshold) {\n return newrelic_transaction_set_max_trace_segments(NEWRELIC_AUTOSCOPE, threshold);\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_transaction_set_threshold, int threshold) {\n \/\/deprecated\n return false;\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_end_transaction) {\n return newrelic_transaction_end(NEWRELIC_AUTOSCOPE);\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_segment_generic_begin, const String & name) {\n return newrelic_segment_generic_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, name.c_str());\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_segment_datastore_begin, const String & table, const String & operation, const String & sql, const String & sql_trace_rollup_name, String & sql_obfuscator) {\n\/\/ TODO return newrelic_segment_datastore_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, table.c_str(), operation.c_str(), sql.c_str(), sql_trace_rollup_name.c_str(), sql_obfuscator.c_str());\n return false;\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_segment_external_begin, const String & host, const String & name) {\n return newrelic_segment_external_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, host.c_str(), name.c_str());\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_segment_end, int64_t id) {\n return newrelic_segment_end(NEWRELIC_AUTOSCOPE, id);\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_notice_error_intern, const String & exception_type, const String & error_message, const String & stack_trace, const String & stack_frame_delimiter) {\n return newrelic_transaction_notice_error(NEWRELIC_AUTOSCOPE, exception_type.c_str(), error_message.c_str(), stack_trace.c_str(), stack_frame_delimiter.c_str());\n}\n\nstatic int64_t HHVM_FUNCTION(newrelic_add_attribute_intern, const String & name, const String & value) {\n return newrelic_transaction_add_attribute(NEWRELIC_AUTOSCOPE, name.c_str(), value.c_str());\n}\n\nstatic void HHVM_FUNCTION(newrelic_set_external_profiler, int64_t maxdepth ) {\n Profiler *pr = new NewRelicProfiler(maxdepth);\n s_profiler_factory->setExternalProfiler(pr);\n}\n\nstatic Variant HHVM_FUNCTION(newrelic_get_scoped_generic_segment, const String & name) {\n ScopedGenericSegment * segment = nullptr;\n segment = newres(name.c_str());\n return Resource(segment);\n}\n\nstatic Variant HHVM_FUNCTION(newrelic_get_scoped_database_segment, const String & table, const String & operation) {\n ScopedDatastoreSegment * segment = nullptr;\n segment = newres(table.c_str(), operation.c_str());\n return Resource(segment);\n}\n\nstatic Variant HHVM_FUNCTION(newrelic_get_scoped_external_segment, const String & host, const String & name) {\n ScopedExternalSegment * segment = nullptr;\n segment = newres(host.c_str(), name.c_str());\n return Resource(segment);\n}\n\nconst StaticString\n s__NR_ERROR_CALLBACK(\"NewRelicExtensionHelper::errorCallback\"),\n s__NR_EXCEPTION_CALLBACK(\"NewRelicExtensionHelper::exceptionCallback\");\n\nstatic class NewRelicExtension : public Extension {\npublic:\n NewRelicExtension () : Extension(\"newrelic\", NO_EXTENSION_VERSION_YET) {\n config_loaded = false;\n }\n\n virtual void init_newrelic() {\n newrelic_register_message_handler(newrelic_message_handler);\n newrelic_init(license_key.c_str(), app_name.c_str(), app_language.c_str(), app_language_version.c_str());\n }\n\n virtual void moduleLoad(const IniSetting::Map& ini, Hdf config) {\n\n license_key = RuntimeOption::EnvVariables[\"NEWRELIC_LICENSE_KEY\"];\n app_name = RuntimeOption::EnvVariables[\"NEWRELIC_APP_NAME\"];\n app_language = RuntimeOption::EnvVariables[\"NEWRELIC_APP_LANGUAGE\"];\n app_language_version = RuntimeOption::EnvVariables[\"NEWRELIC_APP_LANGUAGE_VERSION\"];\n\n if (app_language.empty()) {\n app_language = \"php-hhvm\";\n }\n\n if (app_language_version.empty()) {\n app_language_version = HPHP::getHphpCompilerVersion();\n }\n\n\n setenv(\"NEWRELIC_LICENSE_KEY\", license_key.c_str(), 1);\n setenv(\"NEWRELIC_APP_NAME\", app_name.c_str(), 1);\n setenv(\"NEWRELIC_APP_LANGUAGE\", app_language.c_str(), 1);\n setenv(\"NEWRELIC_APP_LANGUAGE_VERSION\", app_language_version.c_str(), 1);\n\n if (!license_key.empty() && !app_name.empty() && !app_language.empty() && !app_language_version.empty())\n config_loaded = true;\n\n }\n\n\n void moduleInit () override {\n if (config_loaded) init_newrelic();\n\n HHVM_FE(newrelic_start_transaction_intern);\n HHVM_FE(newrelic_name_transaction_intern);\n HHVM_FE(newrelic_transaction_set_request_url);\n HHVM_FE(newrelic_transaction_set_max_trace_segments);\n HHVM_FE(newrelic_transaction_set_threshold);\n HHVM_FE(newrelic_end_transaction);\n HHVM_FE(newrelic_segment_generic_begin);\n HHVM_FE(newrelic_segment_datastore_begin);\n HHVM_FE(newrelic_segment_external_begin);\n HHVM_FE(newrelic_segment_end);\n HHVM_FE(newrelic_get_scoped_generic_segment);\n HHVM_FE(newrelic_get_scoped_database_segment);\n HHVM_FE(newrelic_get_scoped_external_segment);\n HHVM_FE(newrelic_notice_error_intern);\n HHVM_FE(newrelic_add_attribute_intern);\n HHVM_FE(newrelic_set_external_profiler);\n\n loadSystemlib();\n }\n\n virtual void requestShutdown() {\n\n newrelic_transaction_end(NEWRELIC_AUTOSCOPE);\n }\n\n void requestInit() override {\n auto serverVars = php_global(s__SERVER).toArray();\n\n f_set_error_handler(s__NR_ERROR_CALLBACK);\n f_set_exception_handler(s__NR_EXCEPTION_CALLBACK);\n \/\/TODO: make it possible to disable that via ini\n newrelic_transaction_begin();\n String request_url = serverVars[s__REQUEST_URI].toString();\n newrelic_transaction_set_request_url(NEWRELIC_AUTOSCOPE, request_url.c_str());\n String script_name = serverVars[s__SCRIPT_NAME].toString();\n newrelic_transaction_set_name(NEWRELIC_AUTOSCOPE, script_name.c_str());\n }\n\nprivate:\n std::string license_key;\n std::string app_name;\n std::string app_language;\n std::string app_language_version;\n int64_t global_transaction_id = 0;\n bool config_loaded;\n\n} s_newrelic_extension;\n\nHHVM_GET_MODULE(newrelic)\n\n} \/\/ namespace HPHP\n<|endoftext|>"} {"text":"\/***************************************************************************\n main.cpp - description\n copyright : (C) 1999 by Christian Thurner\n email : cthurner@freepage.de\n ***************************************************************************\/\n\n\/***************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include \n#include \n#include \n#include \"knode.h\"\n\nvoid convert(const char*);\n\nstatic const KCmdLineOptions options[] =\n{\n\t{ \"convert \", I18N_NOOP(\"convert the database from \"), 0 },\n\t{ \"c\", 0, 0},\n\t{ 0, 0, 0}\n};\n\nint main(int argc, char* argv[])\n{\n\n\tKAboutData aboutData(\"knode\",\n\t\t\t\t\t\t\t\t\t\t\t\tI18N_NOOP(\"KNode\"),\n\t\t\t\t\t\t\t\t\t\t\t\tVERSION,\n\t\t\t\t\t\t\t\t\t\t\t\tI18N_NOOP(\"A newsreader for KDE\"),\n\t\t\t\t\t\t\t\t\t\t\t\tKAboutData::License_GPL,\n \t\t\t\t\t\t\t\t\t\t\"(c) 1999-2000, Christian Thurner\",\n \t\t\t\t\t\t\t\t\t\t0,\n \t\t\t\t\t\t\t\t\t\t\"http:\/\/knode.sourceforge.net\/\",\n \t\t\t\t\t\t\t\t\t\t\"cthurner@freepage.de\");\n \t\t\t\t\t\t\t\t\t\t\n aboutData.addAuthor(\"Christian Thurner\",I18N_NOOP(\"Maintainer\"),\"cthurner@freepage.de\");\n aboutData.addAuthor(\"Christian Gebauer\",0,\"gebauer@bigfoot.com\");\n aboutData.addAuthor(\"Dirk Mueller\",0,\"\");\n\n KCmdLineArgs::init( argc, argv, &aboutData );\n\tKCmdLineArgs::addCmdLineOptions( options );\n\tKCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n\n\tQCString val = args->getOption(\"convert\");\n\tif (val.length()) {\n\t \tcout << I18N_NOOP(\"Converting ...\\n\");\n \tconvert(val);\n\t}\n\t\n\targs->clear();\n\t\n\tKApplication app;\n\tKNodeApp* knode = 0;\n\n\tif (app.isRestored())\n\t\tRESTORE(KNodeApp)\n else {\n\t \tknode = new KNodeApp;\n\t \tQObject::connect(&app, SIGNAL(saveYourself()), knode, SLOT(slotSaveYourself()));\n \tknode->show();\n }\n\n int ret=app.exec();\n\n return ret;\n}\nfixing KAboutData...\/***************************************************************************\n main.cpp - description\n copyright : (C) 1999 by Christian Thurner\n email : cthurner@freepage.de\n ***************************************************************************\/\n\n\/***************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include \n#include \n#include \n#include \"knode.h\"\n\nvoid convert(const char*);\n\nstatic const KCmdLineOptions options[] =\n{\n\t{ \"convert \", I18N_NOOP(\"convert the database from \"), 0 },\n\t{ \"c\", 0, 0},\n\t{ 0, 0, 0}\n};\n\nint main(int argc, char* argv[])\n{\n\n\tKAboutData aboutData(\"knode\",\n\t\t\t\t\t\t\t\t\t\t\t\tI18N_NOOP(\"KNode\"),\n\t\t\t\t\t\t\t\t\t\t\t\t\"0.2\",\n\t\t\t\t\t\t\t\t\t\t\t\tI18N_NOOP(\"A newsreader for KDE\"),\n\t\t\t\t\t\t\t\t\t\t\t\tKAboutData::License_GPL,\n \t\t\t\t\t\t\t\t\t\t\"(c) 1999-2000, Christian Thurner\",\n \t\t\t\t\t\t\t\t\t\t0,\n \t\t\t\t\t\t\t\t\t\t\"http:\/\/knode.sourceforge.net\/\",\n \t\t\t\t\t\t\t\t\t\t\"cthurner@freepage.de\");\n \t\t\t\t\t\t\t\t\t\t\n aboutData.addAuthor(\"Christian Thurner\",I18N_NOOP(\"Maintainer\"),\"cthurner@freepage.de\");\n aboutData.addAuthor(\"Christian Gebauer\",0,\"gebauer@bigfoot.com\");\n aboutData.addAuthor(\"Dirk Mueller\",0,\"mueller@kde.org\");\n\n KCmdLineArgs::init( argc, argv, &aboutData );\n\tKCmdLineArgs::addCmdLineOptions( options );\n\tKCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n\n\tQCString val = args->getOption(\"convert\");\n\tif (val.length()) {\n\t \tcout << I18N_NOOP(\"Converting ...\\n\");\n \tconvert(val);\n\t}\n\t\n\targs->clear();\n\t\n\tKApplication app;\n\tKNodeApp* knode = 0;\n\n\tif (app.isRestored())\n\t\tRESTORE(KNodeApp)\n else {\n\t \tknode = new KNodeApp;\n\t \tQObject::connect(&app, SIGNAL(saveYourself()), knode, SLOT(slotSaveYourself()));\n \tknode->show();\n }\n\n int ret=app.exec();\n\n return ret;\n}\n<|endoftext|>"} {"text":"#ifndef ENUMNYA_HPP\n#define ENUMNYA_HPP\n\n\/*\n\/\/ If you want enum with string conversions:\nenum class MyEnum\n{\n\tOne,\n\tTwo = 20,\n\tThree, \/\/ It's the third\n\tFour = 40, \/\/ It's the fourth\n};\n\n\/\/ Write something like this:\n#define MyEnumDef(K, V) \\\n\tK(One) \\\n\tV(Two, 20) \\\n\tK(Three) \/ * It's the third * \/ \\\n\tV(Four, 40) \/ * It's the fourth * \/\nnya_enum(MyEnum, MyEnumDef)\n\n\n\/\/ enum to string. If wrong, return \"!~MyEnum~\"\n\/\/ ( implemented with usual switch )\nMyEnum e1 = MyEnum::One;\ncout << e1 << endl; \/\/ 0\ncout << e1.c_str() << endl; \/\/ \"One\"\n\n\/\/ string to enum. If wrong, return -1\n\/\/ ( implemented with if-else strcmp )\nMyEnum e2 = \"Two\";\nswitch (e2)\n{\n\tcase MyEnum::One: cout << \"-> 1\\n\"; break;\n\tcase MyEnum::Two: cout << \"-> 2\\n\"; break;\n}\n\nCXX_STANDARD 98\n*\/\n\n#include \n#include \n\n#define NYA_ENUM_K(KEY) KEY,\n#define NYA_ENUM_KV(KEY, VALUE) KEY = VALUE,\n\n#define NYA_ELIF_K(KEY) else if (!strcmp(str, #KEY)) value = KEY;\n#define NYA_ELIF_KV(KEY, VALUE) NYA_ELIF_K(KEY)\n\n#define NYA_ELIFS_K(KEY) else if (str == #KEY) value = KEY;\n#define NYA_ELIFS_KV(KEY, VALUE) NYA_ELIFS_K(KEY)\n\n#define NYA_CASE_K(KEY) case KEY: return #KEY;\n#define NYA_CASE_KV(KEY, VALUE) NYA_CASE_K(KEY)\n\n#define nya_typed_enum(ENUM_NAME, ENUM_DEF, ENUM_TYPE) \\\nstruct ENUM_NAME \\\n{ \\\n enum ENUM_NAME##Enum : ENUM_TYPE \\\n { ENUM_DEF(NYA_ENUM_K, NYA_ENUM_KV) }; \\\n \\\n ENUM_NAME() : value((ENUM_NAME##Enum)-1) {} \\\n ENUM_NAME(ENUM_NAME##Enum en) : value(en) {} \\\n ENUM_NAME(ENUM_TYPE n) : value((ENUM_NAME##Enum)n) {} \\\n \\\n ENUM_NAME(const char* str) \\\n { \\\n if (!*str) value = (ENUM_NAME##Enum)-1; \\\n ENUM_DEF(NYA_ELIF_K, NYA_ELIF_KV) \\\n else value = (ENUM_NAME##Enum)-1; \\\n } \\\n \\\n ENUM_NAME(const std::string& str) \\\n { \\\n if (str.empty()) value = (ENUM_NAME##Enum)-1; \\\n ENUM_DEF(NYA_ELIFS_K, NYA_ELIFS_KV) \\\n else value = (ENUM_NAME##Enum)-1; \\\n } \\\n \\\n const char* c_str() const \\\n { \\\n switch (value) \\\n { \\\n ENUM_DEF(NYA_CASE_K, NYA_CASE_KV) \\\n default: return \"!~\" #ENUM_NAME \"~\"; \\\n } \\\n } \\\n \\\n operator ENUM_NAME##Enum() const { return value; } \\\n \\\nprivate: \\\n ENUM_NAME##Enum value; \\\n};\n\n#define nya_enum(ENUM_NAME, ENUM_DEF) nya_typed_enum(ENUM_NAME, ENUM_DEF, int)\n\n#endif \/\/ENUMNYA_HPP\nenum value_type#ifndef ENUMNYA_HPP\n#define ENUMNYA_HPP\n\n\/*\n\/\/ If you want enum with string conversions:\nenum class MyEnum\n{\n\tOne,\n\tTwo = 20,\n\tThree, \/\/ It's the third\n\tFour = 40, \/\/ It's the fourth\n};\n\n\/\/ Write something like this:\n#define MyEnumDef(K, V) \\\n\tK(One) \\\n\tV(Two, 20) \\\n\tK(Three) \/ * It's the third * \/ \\\n\tV(Four, 40) \/ * It's the fourth * \/\nnya_enum(MyEnum, MyEnumDef)\n\n\n\/\/ enum to string. If wrong, return \"!~MyEnum~\"\n\/\/ ( implemented with usual switch )\nMyEnum e1 = MyEnum::One;\ncout << e1 << endl; \/\/ 0\ncout << e1.c_str() << endl; \/\/ \"One\"\n\n\/\/ string to enum. If wrong, return -1\n\/\/ ( implemented with if-else strcmp )\nMyEnum e2 = \"Two\";\nswitch (e2)\n{\n\tcase MyEnum::One: cout << \"-> 1\\n\"; break;\n\tcase MyEnum::Two: cout << \"-> 2\\n\"; break;\n}\n\nCXX_STANDARD 98\n*\/\n\n#include \n#include \n\n#define NYA_ENUM_K(KEY) KEY,\n#define NYA_ENUM_KV(KEY, VALUE) KEY = VALUE,\n\n#define NYA_ELIF_K(KEY) else if (!strcmp(str, #KEY)) value = KEY;\n#define NYA_ELIF_KV(KEY, VALUE) NYA_ELIF_K(KEY)\n\n#define NYA_ELIFS_K(KEY) else if (str == #KEY) value = KEY;\n#define NYA_ELIFS_KV(KEY, VALUE) NYA_ELIFS_K(KEY)\n\n#define NYA_CASE_K(KEY) case KEY: return #KEY;\n#define NYA_CASE_KV(KEY, VALUE) NYA_CASE_K(KEY)\n\n#define nya_typed_enum(ENUM_NAME, ENUM_DEF, ENUM_TYPE) \\\nstruct ENUM_NAME \\\n{ \\\n typedef ENUM_TYPE value_type; \\\n \\\n enum ENUM_NAME##Enum : ENUM_TYPE \\\n { ENUM_DEF(NYA_ENUM_K, NYA_ENUM_KV) }; \\\n \\\n ENUM_NAME() : value((ENUM_NAME##Enum)-1) {} \\\n ENUM_NAME(ENUM_NAME##Enum en) : value(en) {} \\\n ENUM_NAME(ENUM_TYPE n) : value((ENUM_NAME##Enum)n) {} \\\n \\\n ENUM_NAME(const char* str) \\\n { \\\n if (!*str) value = (ENUM_NAME##Enum)-1; \\\n ENUM_DEF(NYA_ELIF_K, NYA_ELIF_KV) \\\n else value = (ENUM_NAME##Enum)-1; \\\n } \\\n \\\n ENUM_NAME(const std::string& str) \\\n { \\\n if (str.empty()) value = (ENUM_NAME##Enum)-1; \\\n ENUM_DEF(NYA_ELIFS_K, NYA_ELIFS_KV) \\\n else value = (ENUM_NAME##Enum)-1; \\\n } \\\n \\\n const char* c_str() const \\\n { \\\n switch (value) \\\n { \\\n ENUM_DEF(NYA_CASE_K, NYA_CASE_KV) \\\n default: return \"!~\" #ENUM_NAME \"~\"; \\\n } \\\n } \\\n \\\n operator ENUM_NAME##Enum() const { return value; } \\\n \\\nprivate: \\\n ENUM_NAME##Enum value; \\\n};\n\n#define nya_enum(ENUM_NAME, ENUM_DEF) nya_typed_enum(ENUM_NAME, ENUM_DEF, int)\n\n#endif \/\/ENUMNYA_HPP\n<|endoftext|>"} {"text":"#include \"cursor.h\"\n#include \"axlib\/axlib.h\"\n#include \"space.h\"\n\n#define internal static\n#define local_persist static\n\nextern ax_application *FocusedApplication;\n\ninternal CGPoint\nGetCursorPos()\n{\n CGEventRef Event = CGEventCreate(NULL);\n CGPoint Cursor = CGEventGetLocation(Event);\n CFRelease(Event);\n\n return Cursor;\n}\n\ninternal bool\nIsWindowBelowCursor(ax_window *Window)\n{\n CGPoint Cursor = GetCursorPos();\n if(Cursor.x >= Window->Position.x &&\n Cursor.x <= Window->Position.x + Window->Size.width &&\n Cursor.y >= Window->Position.y &&\n Cursor.y <= Window->Position.y + Window->Size.height)\n return true;\n\n return false;\n}\n\nvoid MoveCursorToCenterOfWindow(ax_window *Window)\n{\n CGWarpMouseCursorPosition(CGPointMake(Window->Position.x + Window->Size.width \/ 2,\n Window->Position.y + Window->Size.height \/ 2));\n}\n\nvoid FocusWindowBelowCursor()\n{\n std::vector Windows = AXLibGetAllVisibleWindowsOrdered();\n for(std::size_t Index = 0; Index < Windows.size(); ++Index)\n {\n ax_window *Window = Windows[Index];\n if(IsWindowBelowCursor(Window))\n {\n if(FocusedApplication == Window->Application)\n {\n if(FocusedApplication->Focus != Window)\n AXLibSetFocusedWindow(Window);\n }\n else\n {\n AXLibSetFocusedWindow(Window);\n }\n return;\n }\n }\n}\nallow toggling of mouse-follows-focus#include \"cursor.h\"\n#include \"axlib\/axlib.h\"\n#include \"space.h\"\n\n#define internal static\n#define local_persist static\n\nextern ax_application *FocusedApplication;\nextern kwm_toggles KWMToggles;\n\ninternal CGPoint\nGetCursorPos()\n{\n CGEventRef Event = CGEventCreate(NULL);\n CGPoint Cursor = CGEventGetLocation(Event);\n CFRelease(Event);\n\n return Cursor;\n}\n\ninternal bool\nIsWindowBelowCursor(ax_window *Window)\n{\n CGPoint Cursor = GetCursorPos();\n if(Cursor.x >= Window->Position.x &&\n Cursor.x <= Window->Position.x + Window->Size.width &&\n Cursor.y >= Window->Position.y &&\n Cursor.y <= Window->Position.y + Window->Size.height)\n return true;\n\n return false;\n}\n\nvoid MoveCursorToCenterOfWindow(ax_window *Window)\n{\n if(KWMToggles.UseMouseFollowsFocus)\n {\n CGWarpMouseCursorPosition(CGPointMake(Window->Position.x + Window->Size.width \/ 2,\n Window->Position.y + Window->Size.height \/ 2));\n }\n}\n\nvoid FocusWindowBelowCursor()\n{\n std::vector Windows = AXLibGetAllVisibleWindowsOrdered();\n for(std::size_t Index = 0; Index < Windows.size(); ++Index)\n {\n ax_window *Window = Windows[Index];\n if(IsWindowBelowCursor(Window))\n {\n if(FocusedApplication == Window->Application)\n {\n if(FocusedApplication->Focus != Window)\n AXLibSetFocusedWindow(Window);\n }\n else\n {\n AXLibSetFocusedWindow(Window);\n }\n return;\n }\n }\n}\n<|endoftext|>"} {"text":"#include \"main_window.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"adaptor.h\"\n#include \"node_data.h\"\n\nnamespace {\n\nQAction* makeAction(QString title, std::function fn, QWidget* parent) {\n\tQAction* result = new QAction(title, parent);\n\tnode_editor::qt_bind(result, SIGNAL(triggered(bool)), fn);\n\treturn result;\n}\n\nconst dependency_graph::Metadata& additionNode() {\n\tstatic dependency_graph::Metadata s_meta(\"addition\");\n\n\tif(!s_meta.isValid()) {\n\t\t\/\/ create attributes\n\t\tstatic dependency_graph::InAttr additionInput1, additionInput2;\n\t\tstatic dependency_graph::OutAttr additionOutput;\n\n\t\t\/\/ add attributes to the Metadata instance\n\t\ts_meta.addAttribute(additionInput1, \"input_1\");\n\t\ts_meta.addAttribute(additionInput2, \"input_2\");\n\t\ts_meta.addAttribute(additionOutput, \"output\");\n\n\t\tstd::function additionCompute = [&](dependency_graph::Datablock & data) {\n\t\t\tconst float a = data.get(additionInput1);\n\t\t\tconst float b = data.get(additionInput2);\n\n\t\t\tdata.set(additionOutput, a + b);\n\t\t};\n\t\ts_meta.setCompute(additionCompute);\n\t}\n\n\treturn s_meta;\n}\n\nconst dependency_graph::Metadata& multiplicationNode() {\n\tstatic dependency_graph::Metadata s_meta(\"multiplication\");\n\n\tif(!s_meta.isValid()) {\n\t\tstatic dependency_graph::InAttr multiplicationInput1, multiplicationInput2;\n\t\tstatic dependency_graph::OutAttr multiplicationOutput;\n\t\tstd::function multiplicationCompute = [&](dependency_graph::Datablock & data) {\n\t\t\tconst float a = data.get(multiplicationInput1);\n\t\t\tconst float b = data.get(multiplicationInput2);\n\n\t\t\tdata.set(multiplicationOutput, a * b);\n\t\t};\n\n\t\ts_meta.addAttribute(multiplicationInput1, \"input_1\");\n\t\ts_meta.addAttribute(multiplicationInput2, \"input_2\");\n\t\ts_meta.addAttribute(multiplicationOutput, \"output\");\n\n\t\ts_meta.addInfluence(multiplicationInput1, multiplicationOutput);\n\t\ts_meta.addInfluence(multiplicationInput2, multiplicationOutput);\n\n\t\ts_meta.setCompute(multiplicationCompute);\n\t}\n\n\treturn s_meta;\n}\n\n}\n\nMainWindow::MainWindow() : QMainWindow(), m_nodeCounter(0) {\n\t\/\/ initialise the graph with some nodes (to be removed)\n\t{\n\t\tauto& add = m_graph.nodes().add(additionNode(), \"add1\");\n\t\tadd.setBlindData(NodeData{QPointF(-100, 20)});\n\n\t\tauto& mult = m_graph.nodes().add(multiplicationNode(), \"mult1\");\n\t\tmult.setBlindData(NodeData{QPointF(100, 20)});\n\n\t\tadd.port(2).connect(mult.port(0));\n\t}\n\n\t\/\/ create the main widget, and the main window content\n\tQWidget* main = new QWidget();\n\tsetCentralWidget(main);\n\n\tQHBoxLayout* layout = new QHBoxLayout(main);\n\tlayout->setContentsMargins(0,0,0,0);\n\n\tm_adaptor = new Adaptor(&m_graph);\n\tlayout->addWidget(m_adaptor, 1);\n\n\tm_properties = new Properties();\n\tlayout->addWidget(m_properties);\n\n\t\/\/ connect the selection signal\n\tm_adaptor->scene().setNodeSelectionCallback(\n\t\t[&](std::set, node_editor::GraphScene::NodeRefComparator> selection) {\n\t\t\tm_properties->show(m_adaptor->selectedNodes());\n\t\t}\n\t);\n\n\t\/\/ create the context click menu\n\tm_adaptor->setContextMenuPolicy(Qt::ActionsContextMenu);\n\n\tm_adaptor->addAction(makeAction(\"Add addition node\", [this]() {\n\t\tQPointF pos = m_adaptor->mapToScene(m_adaptor->mapFromGlobal(QCursor::pos()));\n\t\tm_graph.nodes().add(additionNode(), \"add_\" + std::to_string(m_nodeCounter++), NodeData{pos});\n\t}, m_adaptor));\n\n\tm_adaptor->addAction(makeAction(\"Add multiplication node\", [this]() {\n\t\tQPointF pos = m_adaptor->mapToScene(m_adaptor->mapFromGlobal(QCursor::pos()));\n\t\tm_graph.nodes().add(multiplicationNode(), \"mult_\" + std::to_string(m_nodeCounter++), NodeData{pos});\n\t}, m_adaptor));\n\n\tQAction* separator = new QAction(m_adaptor);\n\tseparator->setSeparator(true);\n\tm_adaptor->addAction(separator);\n\n\tQAction* deleteAction = new QAction(\"Delete selected items\", m_adaptor);\n\tdeleteAction->setShortcut(QKeySequence::Delete);\n\tm_adaptor->addAction(deleteAction);\n\tnode_editor::qt_bind(deleteAction, SIGNAL(triggered()), [this]() {\n\t\tm_adaptor->deleteSelected();\n\t});\n}\nFixed influences in ADD node of the possumwood example#include \"main_window.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"adaptor.h\"\n#include \"node_data.h\"\n\nnamespace {\n\nQAction* makeAction(QString title, std::function fn, QWidget* parent) {\n\tQAction* result = new QAction(title, parent);\n\tnode_editor::qt_bind(result, SIGNAL(triggered(bool)), fn);\n\treturn result;\n}\n\nconst dependency_graph::Metadata& additionNode() {\n\tstatic dependency_graph::Metadata s_meta(\"addition\");\n\n\tif(!s_meta.isValid()) {\n\t\t\/\/ create attributes\n\t\tstatic dependency_graph::InAttr additionInput1, additionInput2;\n\t\tstatic dependency_graph::OutAttr additionOutput;\n\n\t\t\/\/ add attributes to the Metadata instance\n\t\ts_meta.addAttribute(additionInput1, \"input_1\");\n\t\ts_meta.addAttribute(additionInput2, \"input_2\");\n\t\ts_meta.addAttribute(additionOutput, \"output\");\n\n\t\ts_meta.addInfluence(additionInput1, additionOutput);\n\t\ts_meta.addInfluence(additionInput2, additionOutput);\n\n\t\tstd::function additionCompute = [&](dependency_graph::Datablock & data) {\n\t\t\tconst float a = data.get(additionInput1);\n\t\t\tconst float b = data.get(additionInput2);\n\n\t\t\tdata.set(additionOutput, a + b);\n\t\t};\n\t\ts_meta.setCompute(additionCompute);\n\t}\n\n\treturn s_meta;\n}\n\nconst dependency_graph::Metadata& multiplicationNode() {\n\tstatic dependency_graph::Metadata s_meta(\"multiplication\");\n\n\tif(!s_meta.isValid()) {\n\t\tstatic dependency_graph::InAttr multiplicationInput1, multiplicationInput2;\n\t\tstatic dependency_graph::OutAttr multiplicationOutput;\n\t\tstd::function multiplicationCompute = [&](dependency_graph::Datablock & data) {\n\t\t\tconst float a = data.get(multiplicationInput1);\n\t\t\tconst float b = data.get(multiplicationInput2);\n\n\t\t\tdata.set(multiplicationOutput, a * b);\n\t\t};\n\n\t\ts_meta.addAttribute(multiplicationInput1, \"input_1\");\n\t\ts_meta.addAttribute(multiplicationInput2, \"input_2\");\n\t\ts_meta.addAttribute(multiplicationOutput, \"output\");\n\n\t\ts_meta.addInfluence(multiplicationInput1, multiplicationOutput);\n\t\ts_meta.addInfluence(multiplicationInput2, multiplicationOutput);\n\n\t\ts_meta.setCompute(multiplicationCompute);\n\t}\n\n\treturn s_meta;\n}\n\n}\n\nMainWindow::MainWindow() : QMainWindow(), m_nodeCounter(0) {\n\t\/\/ initialise the graph with some nodes (to be removed)\n\t{\n\t\tauto& add = m_graph.nodes().add(additionNode(), \"add1\");\n\t\tadd.setBlindData(NodeData{QPointF(-100, 20)});\n\n\t\tauto& mult = m_graph.nodes().add(multiplicationNode(), \"mult1\");\n\t\tmult.setBlindData(NodeData{QPointF(100, 20)});\n\n\t\tadd.port(2).connect(mult.port(0));\n\t}\n\n\t\/\/ create the main widget, and the main window content\n\tQWidget* main = new QWidget();\n\tsetCentralWidget(main);\n\n\tQHBoxLayout* layout = new QHBoxLayout(main);\n\tlayout->setContentsMargins(0,0,0,0);\n\n\tm_adaptor = new Adaptor(&m_graph);\n\tlayout->addWidget(m_adaptor, 1);\n\n\tm_properties = new Properties();\n\tlayout->addWidget(m_properties);\n\n\t\/\/ connect the selection signal\n\tm_adaptor->scene().setNodeSelectionCallback(\n\t\t[&](std::set, node_editor::GraphScene::NodeRefComparator> selection) {\n\t\t\tm_properties->show(m_adaptor->selectedNodes());\n\t\t}\n\t);\n\n\t\/\/ create the context click menu\n\tm_adaptor->setContextMenuPolicy(Qt::ActionsContextMenu);\n\n\tm_adaptor->addAction(makeAction(\"Add addition node\", [this]() {\n\t\tQPointF pos = m_adaptor->mapToScene(m_adaptor->mapFromGlobal(QCursor::pos()));\n\t\tm_graph.nodes().add(additionNode(), \"add_\" + std::to_string(m_nodeCounter++), NodeData{pos});\n\t}, m_adaptor));\n\n\tm_adaptor->addAction(makeAction(\"Add multiplication node\", [this]() {\n\t\tQPointF pos = m_adaptor->mapToScene(m_adaptor->mapFromGlobal(QCursor::pos()));\n\t\tm_graph.nodes().add(multiplicationNode(), \"mult_\" + std::to_string(m_nodeCounter++), NodeData{pos});\n\t}, m_adaptor));\n\n\tQAction* separator = new QAction(m_adaptor);\n\tseparator->setSeparator(true);\n\tm_adaptor->addAction(separator);\n\n\tQAction* deleteAction = new QAction(\"Delete selected items\", m_adaptor);\n\tdeleteAction->setShortcut(QKeySequence::Delete);\n\tm_adaptor->addAction(deleteAction);\n\tnode_editor::qt_bind(deleteAction, SIGNAL(triggered()), [this]() {\n\t\tm_adaptor->deleteSelected();\n\t});\n}\n<|endoftext|>"} {"text":"\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2020 David Shah \n *\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"log.h\"\n#include \"nextpnr.h\"\n\n#include \n\nNEXTPNR_NAMESPACE_BEGIN\n\nstruct TCLEntity\n{\n enum EntityType\n {\n ENTITY_CELL,\n ENTITY_PORT,\n ENTITY_NET,\n } type;\n IdString name;\n\n TCLEntity(EntityType type, IdString name) : type(type), name(name) {}\n\n const std::string &to_string(Context *ctx) { return name.str(ctx); }\n\n CellInfo *get_cell(Context *ctx)\n {\n if (type != ENTITY_CELL)\n return nullptr;\n return ctx->cells.at(name).get();\n }\n\n PortInfo *get_port(Context *ctx)\n {\n if (type != ENTITY_PORT)\n return nullptr;\n return &ctx->ports.at(name);\n }\n\n NetInfo *get_net(Context *ctx)\n {\n if (type != ENTITY_NET)\n return nullptr;\n return ctx->nets.at(name).get();\n }\n};\n\nstruct TCLValue\n{\n TCLValue(const std::string &s) : is_string(true), str(s){};\n TCLValue(const std::vector &l) : is_string(false), list(l){};\n\n bool is_string;\n std::string str; \/\/ simple string value\n std::vector list; \/\/ list of entities\n};\n\nstruct PDCParser\n{\n std::string buf;\n int pos = 0;\n int lineno = 1;\n Context *ctx;\n\n PDCParser(const std::string &buf, Context *ctx) : buf(buf), ctx(ctx){};\n\n inline bool eof() const { return pos == int(buf.size()); }\n\n inline char peek() const { return buf.at(pos); }\n\n inline char get()\n {\n char c = buf.at(pos++);\n if (c == '\\n')\n ++lineno;\n return c;\n }\n\n std::string get(int n)\n {\n std::string s = buf.substr(pos, n);\n pos += n;\n return s;\n }\n\n \/\/ If next char matches c, take it from the stream and return true\n bool check_get(char c)\n {\n if (peek() == c) {\n get();\n return true;\n } else {\n return false;\n }\n }\n\n \/\/ If next char matches any in chars, take it from the stream and return true\n bool check_get_any(const std::string &chrs)\n {\n char c = peek();\n if (chrs.find(c) != std::string::npos) {\n get();\n return true;\n } else {\n return false;\n }\n }\n\n inline void skip_blank(bool nl = false)\n {\n while (!eof() && check_get_any(nl ? \" \\t\\n\\r\" : \" \\t\"))\n ;\n }\n\n \/\/ Return true if end of line (or file)\n inline bool skip_check_eol()\n {\n skip_blank(false);\n if (eof())\n return true;\n char c = peek();\n \/\/ Comments count as end of line\n if (c == '#') {\n get();\n while (!eof() && peek() != '\\n' && peek() != '\\r')\n get();\n return true;\n }\n if (c == ';') {\n \/\/ Forced end of line\n get();\n return true;\n }\n return (c == '\\n' || c == '\\r');\n }\n\n inline std::string get_str()\n {\n std::string s;\n skip_blank(false);\n if (eof())\n return \"\";\n\n bool in_quotes = false, in_braces = false, escaped = false;\n\n char c = get();\n\n if (c == '\"')\n in_quotes = true;\n else if (c == '{')\n in_braces = true;\n else\n s += c;\n\n while (true) {\n char c = peek();\n if (!in_quotes && !in_braces && !escaped && (std::isblank(c) || c == ']')) {\n break;\n }\n get();\n if (escaped) {\n s += c;\n escaped = false;\n } else if ((in_quotes && c == '\"') || (in_braces && c == '}')) {\n break;\n } else if (c == '\\\\') {\n escaped = true;\n } else {\n s += c;\n }\n }\n\n return s;\n }\n\n TCLValue evaluate(const std::vector &arguments)\n {\n NPNR_ASSERT(!arguments.empty());\n auto &arg0 = arguments.at(0);\n NPNR_ASSERT(arg0.is_string);\n const std::string &cmd = arg0.str;\n if (cmd == \"get_ports\")\n return cmd_get_ports(arguments);\n else if (cmd == \"get_cells\")\n return cmd_get_cells(arguments);\n else if (cmd == \"get_nets\")\n return cmd_get_nets(arguments);\n else if (cmd == \"create_clock\")\n return cmd_create_clock(arguments);\n else if (cmd == \"ldc_set_location\")\n return cmd_ldc_set_location(arguments);\n else if (cmd == \"ldc_set_port\")\n return cmd_ldc_set_port(arguments);\n else if (cmd == \"ldc_set_sysconfig\" || cmd == \"get_nets\" || cmd == \"create_clock\") {\n log_warning(\"%s is not yet supported!\\n\", cmd.c_str());\n return TCLValue(\"\");\n } else\n log_error(\"Unsupported PDC command '%s'\\n\", cmd.c_str());\n }\n\n std::vector get_arguments()\n {\n std::vector args;\n while (!skip_check_eol()) {\n if (check_get('[')) {\n \/\/ Start of a sub-expression\n auto result = evaluate(get_arguments());\n NPNR_ASSERT(check_get(']'));\n args.push_back(result);\n } else if (peek() == ']') {\n break;\n } else {\n args.push_back(get_str());\n }\n }\n skip_blank(true);\n return args;\n }\n\n TCLValue cmd_get_nets(const std::vector &arguments)\n {\n std::vector nets;\n for (int i = 1; i < int(arguments.size()); i++) {\n auto &arg = arguments.at(i);\n if (!arg.is_string)\n log_error(\"get_nets expected string arguments (line %d)\\n\", lineno);\n std::string s = arg.str;\n if (s.at(0) == '-')\n log_error(\"unsupported argument '%s' to get_nets (line %d)\\n\", s.c_str(), lineno);\n IdString id = ctx->id(s);\n if (ctx->nets.count(id) || ctx->net_aliases.count(id))\n nets.emplace_back(TCLEntity::ENTITY_NET, ctx->net_aliases.count(id) ? ctx->net_aliases.at(id) : id);\n else\n log_warning(\"get_nets argument '%s' matched no objects.\\n\", s.c_str());\n }\n return nets;\n }\n\n TCLValue cmd_get_ports(const std::vector &arguments)\n {\n std::vector ports;\n for (int i = 1; i < int(arguments.size()); i++) {\n auto &arg = arguments.at(i);\n if (!arg.is_string)\n log_error(\"get_ports expected string arguments (line %d)\\n\", lineno);\n std::string s = arg.str;\n if (s.at(0) == '-')\n log_error(\"unsupported argument '%s' to get_ports (line %d)\\n\", s.c_str(), lineno);\n IdString id = ctx->id(s);\n if (ctx->ports.count(id))\n ports.emplace_back(TCLEntity::ENTITY_PORT, id);\n }\n return ports;\n }\n\n TCLValue cmd_get_cells(const std::vector &arguments)\n {\n std::vector cells;\n for (int i = 1; i < int(arguments.size()); i++) {\n auto &arg = arguments.at(i);\n if (!arg.is_string)\n log_error(\"get_cells expected string arguments (line %d)\\n\", lineno);\n std::string s = arg.str;\n if (s.at(0) == '-')\n log_error(\"unsupported argument '%s' to get_cells (line %d)\\n\", s.c_str(), lineno);\n IdString id = ctx->id(s);\n if (ctx->cells.count(id))\n cells.emplace_back(TCLEntity::ENTITY_CELL, id);\n }\n return cells;\n }\n\n TCLValue cmd_create_clock(const std::vector &arguments)\n {\n float period = 10;\n for (int i = 1; i < int(arguments.size()); i++) {\n auto &arg = arguments.at(i);\n if (arg.is_string) {\n std::string s = arg.str;\n if (s == \"-period\") {\n i++;\n auto &val = arguments.at(i);\n if (!val.is_string)\n log_error(\"expecting string argument to -period (line %d)\\n\", lineno);\n try {\n period = std::stof(val.str);\n } catch (std::exception &e) {\n log_error(\"invalid argument '%s' to -period (line %d)\\n\", val.str.c_str(), lineno);\n }\n } else if (s == \"-name\") {\n i++;\n } else {\n log_error(\"unsupported argument '%s' to create_clock\\n\", s.c_str());\n }\n } else {\n for (const auto &ety : arg.list) {\n NetInfo *net = nullptr;\n if (ety.type == TCLEntity::ENTITY_NET)\n net = ctx->nets.at(ety.name).get();\n else if (ety.type == TCLEntity::ENTITY_PORT)\n net = ctx->ports.at(ety.name).net;\n else\n log_error(\"create_clock applies only to cells or IO ports (line %d)\\n\", lineno);\n ctx->addClock(net->name, 1000.0f \/ period);\n }\n }\n }\n return std::string{};\n }\n\n TCLValue cmd_ldc_set_location(const std::vector &arguments)\n {\n std::string site;\n\n for (int i = 1; i < int(arguments.size()); i++) {\n auto &arg = arguments.at(i);\n if (arg.is_string) {\n std::string s = arg.str;\n if (s == \"-site\") {\n i++;\n auto &val = arguments.at(i);\n if (!val.is_string)\n log_error(\"expecting string argument to -site (line %d)\\n\", lineno);\n site = val.str;\n }\n } else {\n if (site.empty())\n log_error(\"expecting -site before list of objects (line %d)\\n\", lineno);\n for (const auto &ety : arg.list) {\n if (ety.type == TCLEntity::ENTITY_PORT)\n ctx->io_attr[ety.name][id_LOC] = site;\n else if (ety.type == TCLEntity::ENTITY_CELL)\n ctx->cells[ety.name]->attrs[id_LOC] = site;\n else\n log_error(\"ldc_set_location applies only to cells or IO ports (line %d)\\n\", lineno);\n }\n }\n }\n return std::string{};\n }\n\n TCLValue cmd_ldc_set_port(const std::vector &arguments)\n {\n std::unordered_map args;\n for (int i = 1; i < int(arguments.size()); i++) {\n auto &arg = arguments.at(i);\n if (arg.is_string) {\n std::string s = arg.str;\n if (s == \"-iobuf\") {\n i++;\n auto &val = arguments.at(i);\n if (!val.is_string)\n log_error(\"expecting string argument to -iobuf (line %d)\\n\", lineno);\n std::stringstream ss(val.str);\n std::string kv;\n while (ss >> kv) {\n auto eqp = kv.find('=');\n if (eqp == std::string::npos)\n log_error(\"expected key-value pair separated by '=' (line %d)\", lineno);\n std::string k = kv.substr(0, eqp), v = kv.substr(eqp + 1);\n args[ctx->id(k)] = v;\n }\n } else {\n log_error(\"unexpected argument '%s' to ldc_set_port (line %d)\\n\", s.c_str(), lineno);\n }\n } else {\n for (const auto &ety : arg.list) {\n if (ety.type == TCLEntity::ENTITY_PORT)\n for (const auto &kv : args)\n ctx->io_attr[ety.name][kv.first] = kv.second;\n else\n log_error(\"ldc_set_port applies only to IO ports (line %d)\\n\", lineno);\n }\n }\n }\n return std::string{};\n }\n\n void operator()()\n {\n while (!eof()) {\n skip_blank(true);\n auto args = get_arguments();\n if (args.empty())\n continue;\n evaluate(args);\n }\n }\n};\n\nvoid Arch::read_pdc(std::istream &in)\n{\n std::string buf(std::istreambuf_iterator(in), {});\n PDCParser(buf, getCtx())();\n}\n\nNEXTPNR_NAMESPACE_END\nnexus: Add support for get_pins PDC command\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2020 David Shah \n *\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"log.h\"\n#include \"nextpnr.h\"\n\n#include \n\nNEXTPNR_NAMESPACE_BEGIN\n\nstruct TCLEntity\n{\n enum EntityType\n {\n ENTITY_CELL,\n ENTITY_PORT,\n ENTITY_NET,\n ENTITY_PIN,\n } type;\n IdString name;\n IdString pin; \/\/ for cell pins only\n\n TCLEntity(EntityType type, IdString name) : type(type), name(name) {}\n TCLEntity(EntityType type, IdString name, IdString pin) : type(type), name(name), pin(pin) {}\n\n const std::string &to_string(Context *ctx) { return name.str(ctx); }\n\n CellInfo *get_cell(Context *ctx) const\n {\n if (type != ENTITY_CELL)\n return nullptr;\n return ctx->cells.at(name).get();\n }\n\n PortInfo *get_port(Context *ctx) const\n {\n if (type != ENTITY_PORT)\n return nullptr;\n return &ctx->ports.at(name);\n }\n\n NetInfo *get_net(Context *ctx) const\n {\n if (type == ENTITY_PIN) {\n CellInfo *cell = nullptr;\n if (ctx->cells.count(name)) {\n cell = ctx->cells.at(name).get();\n } else {\n const std::string &n = name.str(ctx);\n auto pos = n.rfind('.');\n if (pos == std::string::npos)\n return nullptr;\n \/\/ remove one hierarchy layer due to Radiant weirdness around PLLs etc\n IdString stripped_name = ctx->id(n.substr(0, pos));\n if (!ctx->cells.count(stripped_name))\n return nullptr;\n cell = ctx->cells.at(stripped_name).get();\n }\n if (!cell->ports.count(pin))\n return nullptr;\n return cell->ports.at(pin).net;\n } else if (type == ENTITY_NET) {\n return ctx->nets.at(name).get();\n } else {\n return nullptr;\n }\n }\n};\n\nstruct TCLValue\n{\n TCLValue(const std::string &s) : is_string(true), str(s){};\n TCLValue(const std::vector &l) : is_string(false), list(l){};\n\n bool is_string;\n std::string str; \/\/ simple string value\n std::vector list; \/\/ list of entities\n};\n\nstruct PDCParser\n{\n std::string buf;\n int pos = 0;\n int lineno = 1;\n Context *ctx;\n\n PDCParser(const std::string &buf, Context *ctx) : buf(buf), ctx(ctx){};\n\n inline bool eof() const { return pos == int(buf.size()); }\n\n inline char peek() const { return buf.at(pos); }\n\n inline char get()\n {\n char c = buf.at(pos++);\n if (c == '\\n')\n ++lineno;\n return c;\n }\n\n std::string get(int n)\n {\n std::string s = buf.substr(pos, n);\n pos += n;\n return s;\n }\n\n \/\/ If next char matches c, take it from the stream and return true\n bool check_get(char c)\n {\n if (peek() == c) {\n get();\n return true;\n } else {\n return false;\n }\n }\n\n \/\/ If next char matches any in chars, take it from the stream and return true\n bool check_get_any(const std::string &chrs)\n {\n char c = peek();\n if (chrs.find(c) != std::string::npos) {\n get();\n return true;\n } else {\n return false;\n }\n }\n\n inline void skip_blank(bool nl = false)\n {\n while (!eof() && check_get_any(nl ? \" \\t\\n\\r\" : \" \\t\"))\n ;\n }\n\n \/\/ Return true if end of line (or file)\n inline bool skip_check_eol()\n {\n skip_blank(false);\n if (eof())\n return true;\n char c = peek();\n \/\/ Comments count as end of line\n if (c == '#') {\n get();\n while (!eof() && peek() != '\\n' && peek() != '\\r')\n get();\n return true;\n }\n if (c == ';') {\n \/\/ Forced end of line\n get();\n return true;\n }\n return (c == '\\n' || c == '\\r');\n }\n\n inline std::string get_str()\n {\n std::string s;\n skip_blank(false);\n if (eof())\n return \"\";\n\n bool in_quotes = false, in_braces = false, escaped = false;\n\n char c = get();\n\n if (c == '\"')\n in_quotes = true;\n else if (c == '{')\n in_braces = true;\n else\n s += c;\n\n while (true) {\n char c = peek();\n if (!in_quotes && !in_braces && !escaped && (std::isblank(c) || c == ']')) {\n break;\n }\n get();\n if (escaped) {\n s += c;\n escaped = false;\n } else if ((in_quotes && c == '\"') || (in_braces && c == '}')) {\n break;\n } else if (c == '\\\\') {\n escaped = true;\n } else {\n s += c;\n }\n }\n\n return s;\n }\n\n TCLValue evaluate(const std::vector &arguments)\n {\n NPNR_ASSERT(!arguments.empty());\n auto &arg0 = arguments.at(0);\n NPNR_ASSERT(arg0.is_string);\n const std::string &cmd = arg0.str;\n if (cmd == \"get_ports\")\n return cmd_get_ports(arguments);\n else if (cmd == \"get_cells\")\n return cmd_get_cells(arguments);\n else if (cmd == \"get_nets\")\n return cmd_get_nets(arguments);\n else if (cmd == \"get_pins\")\n return cmd_get_pins(arguments);\n else if (cmd == \"create_clock\")\n return cmd_create_clock(arguments);\n else if (cmd == \"ldc_set_location\")\n return cmd_ldc_set_location(arguments);\n else if (cmd == \"ldc_set_port\")\n return cmd_ldc_set_port(arguments);\n else if (cmd == \"ldc_set_sysconfig\" || cmd == \"get_nets\" || cmd == \"create_clock\") {\n log_warning(\"%s is not yet supported!\\n\", cmd.c_str());\n return TCLValue(\"\");\n } else\n log_error(\"Unsupported PDC command '%s'\\n\", cmd.c_str());\n }\n\n std::vector get_arguments()\n {\n std::vector args;\n while (!skip_check_eol()) {\n if (check_get('[')) {\n \/\/ Start of a sub-expression\n auto result = evaluate(get_arguments());\n NPNR_ASSERT(check_get(']'));\n args.push_back(result);\n } else if (peek() == ']') {\n break;\n } else {\n args.push_back(get_str());\n }\n }\n skip_blank(true);\n return args;\n }\n\n TCLValue cmd_get_nets(const std::vector &arguments)\n {\n std::vector nets;\n for (int i = 1; i < int(arguments.size()); i++) {\n auto &arg = arguments.at(i);\n if (!arg.is_string)\n log_error(\"get_nets expected string arguments (line %d)\\n\", lineno);\n std::string s = arg.str;\n if (s.at(0) == '-')\n log_error(\"unsupported argument '%s' to get_nets (line %d)\\n\", s.c_str(), lineno);\n IdString id = ctx->id(s);\n if (ctx->nets.count(id) || ctx->net_aliases.count(id))\n nets.emplace_back(TCLEntity::ENTITY_NET, ctx->net_aliases.count(id) ? ctx->net_aliases.at(id) : id);\n else\n log_warning(\"get_nets argument '%s' matched no objects.\\n\", s.c_str());\n }\n return nets;\n }\n\n TCLValue cmd_get_ports(const std::vector &arguments)\n {\n std::vector ports;\n for (int i = 1; i < int(arguments.size()); i++) {\n auto &arg = arguments.at(i);\n if (!arg.is_string)\n log_error(\"get_ports expected string arguments (line %d)\\n\", lineno);\n std::string s = arg.str;\n if (s.at(0) == '-')\n log_error(\"unsupported argument '%s' to get_ports (line %d)\\n\", s.c_str(), lineno);\n IdString id = ctx->id(s);\n if (ctx->ports.count(id))\n ports.emplace_back(TCLEntity::ENTITY_PORT, id);\n }\n return ports;\n }\n\n TCLValue cmd_get_cells(const std::vector &arguments)\n {\n std::vector cells;\n for (int i = 1; i < int(arguments.size()); i++) {\n auto &arg = arguments.at(i);\n if (!arg.is_string)\n log_error(\"get_cells expected string arguments (line %d)\\n\", lineno);\n std::string s = arg.str;\n if (s.at(0) == '-')\n log_error(\"unsupported argument '%s' to get_cells (line %d)\\n\", s.c_str(), lineno);\n IdString id = ctx->id(s);\n if (ctx->cells.count(id))\n cells.emplace_back(TCLEntity::ENTITY_CELL, id);\n }\n return cells;\n }\n\n TCLValue cmd_get_pins(const std::vector &arguments)\n {\n std::vector pins;\n for (int i = 1; i < int(arguments.size()); i++) {\n auto &arg = arguments.at(i);\n if (!arg.is_string)\n log_error(\"get_pins expected string arguments (line %d)\\n\", lineno);\n std::string s = arg.str;\n if (s.at(0) == '-')\n log_error(\"unsupported argument '%s' to get_pins (line %d)\\n\", s.c_str(), lineno);\n auto pos = s.rfind('\/');\n if (pos == std::string::npos)\n log_error(\"expected \/ in cell pin name '%s' (line %d)\\n\", s.c_str(), lineno);\n pins.emplace_back(TCLEntity::ENTITY_PIN, ctx->id(s.substr(0, pos)), ctx->id(s.substr(pos + 1)));\n if (pins.back().get_net(ctx) == nullptr) {\n log_warning(\"cell pin '%s' not found\\n\", s.c_str());\n pins.pop_back();\n }\n }\n return pins;\n }\n\n TCLValue cmd_create_clock(const std::vector &arguments)\n {\n float period = 10;\n for (int i = 1; i < int(arguments.size()); i++) {\n auto &arg = arguments.at(i);\n if (arg.is_string) {\n std::string s = arg.str;\n if (s == \"-period\") {\n i++;\n auto &val = arguments.at(i);\n if (!val.is_string)\n log_error(\"expecting string argument to -period (line %d)\\n\", lineno);\n try {\n period = std::stof(val.str);\n } catch (std::exception &e) {\n log_error(\"invalid argument '%s' to -period (line %d)\\n\", val.str.c_str(), lineno);\n }\n } else if (s == \"-name\") {\n i++;\n } else {\n log_error(\"unsupported argument '%s' to create_clock\\n\", s.c_str());\n }\n } else {\n for (const auto &ety : arg.list) {\n NetInfo *net = nullptr;\n if (ety.type == TCLEntity::ENTITY_PIN)\n net = ety.get_net(ctx);\n else if (ety.type == TCLEntity::ENTITY_NET)\n net = ctx->nets.at(ety.name).get();\n else if (ety.type == TCLEntity::ENTITY_PORT)\n net = ctx->ports.at(ety.name).net;\n else\n log_error(\"create_clock applies only to cells, cell pins, or IO ports (line %d)\\n\", lineno);\n ctx->addClock(net->name, 1000.0f \/ period);\n }\n }\n }\n return std::string{};\n }\n\n TCLValue cmd_ldc_set_location(const std::vector &arguments)\n {\n std::string site;\n\n for (int i = 1; i < int(arguments.size()); i++) {\n auto &arg = arguments.at(i);\n if (arg.is_string) {\n std::string s = arg.str;\n if (s == \"-site\") {\n i++;\n auto &val = arguments.at(i);\n if (!val.is_string)\n log_error(\"expecting string argument to -site (line %d)\\n\", lineno);\n site = val.str;\n }\n } else {\n if (site.empty())\n log_error(\"expecting -site before list of objects (line %d)\\n\", lineno);\n for (const auto &ety : arg.list) {\n if (ety.type == TCLEntity::ENTITY_PORT)\n ctx->io_attr[ety.name][id_LOC] = site;\n else if (ety.type == TCLEntity::ENTITY_CELL)\n ctx->cells[ety.name]->attrs[id_LOC] = site;\n else\n log_error(\"ldc_set_location applies only to cells or IO ports (line %d)\\n\", lineno);\n }\n }\n }\n return std::string{};\n }\n\n TCLValue cmd_ldc_set_port(const std::vector &arguments)\n {\n std::unordered_map args;\n for (int i = 1; i < int(arguments.size()); i++) {\n auto &arg = arguments.at(i);\n if (arg.is_string) {\n std::string s = arg.str;\n if (s == \"-iobuf\") {\n i++;\n auto &val = arguments.at(i);\n if (!val.is_string)\n log_error(\"expecting string argument to -iobuf (line %d)\\n\", lineno);\n std::stringstream ss(val.str);\n std::string kv;\n while (ss >> kv) {\n auto eqp = kv.find('=');\n if (eqp == std::string::npos)\n log_error(\"expected key-value pair separated by '=' (line %d)\", lineno);\n std::string k = kv.substr(0, eqp), v = kv.substr(eqp + 1);\n args[ctx->id(k)] = v;\n }\n } else {\n log_error(\"unexpected argument '%s' to ldc_set_port (line %d)\\n\", s.c_str(), lineno);\n }\n } else {\n for (const auto &ety : arg.list) {\n if (ety.type == TCLEntity::ENTITY_PORT)\n for (const auto &kv : args)\n ctx->io_attr[ety.name][kv.first] = kv.second;\n else\n log_error(\"ldc_set_port applies only to IO ports (line %d)\\n\", lineno);\n }\n }\n }\n return std::string{};\n }\n\n void operator()()\n {\n while (!eof()) {\n skip_blank(true);\n auto args = get_arguments();\n if (args.empty())\n continue;\n evaluate(args);\n }\n }\n};\n\nvoid Arch::read_pdc(std::istream &in)\n{\n std::string buf(std::istreambuf_iterator(in), {});\n PDCParser(buf, getCtx())();\n}\n\nNEXTPNR_NAMESPACE_END\n<|endoftext|>"} {"text":"\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield\n *\n * This library is open source and may be redistributed and\/or modified under\n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or\n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRA;NTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * OpenSceneGraph Public License for more details.\n*\/\n#include \n#include \n#include \n#include \n\nusing namespace osg;\n\nView::View():\n Object(true)\n{\n \/\/ OSG_NOTICE<<\"Constructing osg::View\"<setView(this);\n\n double height = osg::DisplaySettings::instance()->getScreenHeight();\n double width = osg::DisplaySettings::instance()->getScreenWidth();\n double distance = osg::DisplaySettings::instance()->getScreenDistance();\n double vfov = osg::RadiansToDegrees(atan2(height\/2.0f,distance)*2.0);\n\n _camera->setProjectionMatrixAsPerspective( vfov, width\/height, 1.0f,10000.0f);\n\n _camera->setClearColor(osg::Vec4f(0.2f, 0.2f, 0.4f, 1.0f));\n\n osg::StateSet* stateset = _camera->getOrCreateStateSet();\n stateset->setGlobalDefaults();\n}\n\nView::View(const osg::View& view, const osg::CopyOp& copyop):\n Object(view,copyop),\n _lightingMode(view._lightingMode),\n _light(view._light),\n _camera(view._camera),\n _slaves(view._slaves)\n{\n}\n\n\nView::~View()\n{\n OSG_INFO<<\"Destructing osg::View\"<setView(0);\n _camera->setCullCallback(0);\n }\n\n \/\/ detach the cameras from this View to prevent dangling pointers\n for(Slaves::iterator itr = _slaves.begin();\n itr != _slaves.end();\n ++itr)\n {\n Slave& cd = *itr;\n cd._camera->setView(0);\n cd._camera->setCullCallback(0);\n }\n\n _camera = 0;\n _slaves.clear();\n _light = 0;\n\n#if 0\n if (osg::Referenced::getDeleteHandler())\n {\n \/\/ osg::Referenced::getDeleteHandler()->setNumFramesToRetainObjects(0);\n osg::Referenced::getDeleteHandler()->flushAll();\n }\n#endif\n\n OSG_INFO<<\"Done destructing osg::View\"<setView(this);\n\n for(unsigned int i=0; i<_slaves.size(); ++i)\n {\n if (_slaves[i]._camera.valid()) _slaves[i]._camera->setView(this);\n }\n\n \/\/ then clear the passing in view.\n rhs._light = 0;\n rhs._camera = 0;\n rhs._slaves.clear();\n}\n\n\nvoid View::setLightingMode(LightingMode lightingMode)\n{\n _lightingMode = lightingMode;\n if (_lightingMode != NO_LIGHT && !_light)\n {\n _light = new osg::Light;\n _light->setThreadSafeRefUnref(true);\n _light->setLightNum(0);\n _light->setAmbient(Vec4(0.00f,0.0f,0.00f,1.0f));\n _light->setDiffuse(Vec4(0.8f,0.8f,0.8f,1.0f));\n _light->setSpecular(Vec4(1.0f,1.0f,1.0f,1.0f));\n }\n}\n\n\nvoid View::setCamera(osg::Camera* camera)\n{\n if (_camera.valid()) _camera->setView(0);\n\n _camera = camera;\n\n if (_camera.valid())\n {\n _camera->setView(this);\n _camera->setRenderer(createRenderer(camera));\n }\n}\n\nvoid View::updateSlaves()\n{\n for(unsigned int i=0; i<_slaves.size(); ++i)\n {\n Slave& slave = _slaves[i];\n slave.updateSlave(*this);\n }\n}\n\nvoid View::Slave::updateSlaveImplementation(View& view)\n{\n if (!view.getCamera()) return;\n\n if (_camera->getReferenceFrame()==osg::Transform::RELATIVE_RF)\n {\n _camera->setProjectionMatrix(view.getCamera()->getProjectionMatrix() * _projectionOffset);\n _camera->setViewMatrix(view.getCamera()->getViewMatrix() * _viewOffset);\n }\n\n _camera->inheritCullSettings(*(view.getCamera()), _camera->getInheritanceMask());\n}\n\nbool View::addSlave(osg::Camera* camera, const osg::Matrix& projectionOffset, const osg::Matrix& viewOffset, bool useMastersSceneData)\n{\n if (!camera) return false;\n\n camera->setView(this);\n\n unsigned int i = _slaves.size();\n\n if (useMastersSceneData)\n {\n camera->removeChildren(0,camera->getNumChildren());\n\n if (_camera.valid())\n {\n for(unsigned int i=0; i<_camera->getNumChildren(); ++i)\n {\n camera->addChild(_camera->getChild(i));\n }\n }\n }\n\n _slaves.push_back(Slave(camera, projectionOffset, viewOffset, useMastersSceneData));\n\n _slaves[i].updateSlave(*this);\n\n camera->setRenderer(createRenderer(camera));\n\n return true;\n}\n\nbool View::removeSlave(unsigned int pos)\n{\n if (pos >= _slaves.size()) return false;\n\n _slaves[pos]._camera->setView(0);\n _slaves[pos]._camera->setCullCallback(0);\n\n _slaves.erase(_slaves.begin()+pos);\n\n return true;\n}\n\n\nView::Slave * View::findSlaveForCamera(osg::Camera* camera)\n{\n unsigned int i = findSlaveIndexForCamera(camera);\n\n if (i >= getNumSlaves()) return (NULL);\n\n return &(_slaves[i]);\n}\n\nunsigned int View::findSlaveIndexForCamera(osg::Camera* camera) const\n{\n if (_camera == camera) return _slaves.size();\n\n for(unsigned int i=0; i<_slaves.size(); ++i)\n {\n if (_slaves[i]._camera == camera) return (i);\n }\n\n return _slaves.size();\n}\n\nFixed shadows warning\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield\n *\n * This library is open source and may be redistributed and\/or modified under\n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or\n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRA;NTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * OpenSceneGraph Public License for more details.\n*\/\n#include \n#include \n#include \n#include \n\nusing namespace osg;\n\nView::View():\n Object(true)\n{\n \/\/ OSG_NOTICE<<\"Constructing osg::View\"<setView(this);\n\n double height = osg::DisplaySettings::instance()->getScreenHeight();\n double width = osg::DisplaySettings::instance()->getScreenWidth();\n double distance = osg::DisplaySettings::instance()->getScreenDistance();\n double vfov = osg::RadiansToDegrees(atan2(height\/2.0f,distance)*2.0);\n\n _camera->setProjectionMatrixAsPerspective( vfov, width\/height, 1.0f,10000.0f);\n\n _camera->setClearColor(osg::Vec4f(0.2f, 0.2f, 0.4f, 1.0f));\n\n osg::StateSet* stateset = _camera->getOrCreateStateSet();\n stateset->setGlobalDefaults();\n}\n\nView::View(const osg::View& view, const osg::CopyOp& copyop):\n Object(view,copyop),\n _lightingMode(view._lightingMode),\n _light(view._light),\n _camera(view._camera),\n _slaves(view._slaves)\n{\n}\n\n\nView::~View()\n{\n OSG_INFO<<\"Destructing osg::View\"<setView(0);\n _camera->setCullCallback(0);\n }\n\n \/\/ detach the cameras from this View to prevent dangling pointers\n for(Slaves::iterator itr = _slaves.begin();\n itr != _slaves.end();\n ++itr)\n {\n Slave& cd = *itr;\n cd._camera->setView(0);\n cd._camera->setCullCallback(0);\n }\n\n _camera = 0;\n _slaves.clear();\n _light = 0;\n\n#if 0\n if (osg::Referenced::getDeleteHandler())\n {\n \/\/ osg::Referenced::getDeleteHandler()->setNumFramesToRetainObjects(0);\n osg::Referenced::getDeleteHandler()->flushAll();\n }\n#endif\n\n OSG_INFO<<\"Done destructing osg::View\"<setView(this);\n\n for(unsigned int i=0; i<_slaves.size(); ++i)\n {\n if (_slaves[i]._camera.valid()) _slaves[i]._camera->setView(this);\n }\n\n \/\/ then clear the passing in view.\n rhs._light = 0;\n rhs._camera = 0;\n rhs._slaves.clear();\n}\n\n\nvoid View::setLightingMode(LightingMode lightingMode)\n{\n _lightingMode = lightingMode;\n if (_lightingMode != NO_LIGHT && !_light)\n {\n _light = new osg::Light;\n _light->setThreadSafeRefUnref(true);\n _light->setLightNum(0);\n _light->setAmbient(Vec4(0.00f,0.0f,0.00f,1.0f));\n _light->setDiffuse(Vec4(0.8f,0.8f,0.8f,1.0f));\n _light->setSpecular(Vec4(1.0f,1.0f,1.0f,1.0f));\n }\n}\n\n\nvoid View::setCamera(osg::Camera* camera)\n{\n if (_camera.valid()) _camera->setView(0);\n\n _camera = camera;\n\n if (_camera.valid())\n {\n _camera->setView(this);\n _camera->setRenderer(createRenderer(camera));\n }\n}\n\nvoid View::updateSlaves()\n{\n for(unsigned int i=0; i<_slaves.size(); ++i)\n {\n Slave& slave = _slaves[i];\n slave.updateSlave(*this);\n }\n}\n\nvoid View::Slave::updateSlaveImplementation(View& view)\n{\n if (!view.getCamera()) return;\n\n if (_camera->getReferenceFrame()==osg::Transform::RELATIVE_RF)\n {\n _camera->setProjectionMatrix(view.getCamera()->getProjectionMatrix() * _projectionOffset);\n _camera->setViewMatrix(view.getCamera()->getViewMatrix() * _viewOffset);\n }\n\n _camera->inheritCullSettings(*(view.getCamera()), _camera->getInheritanceMask());\n}\n\nbool View::addSlave(osg::Camera* camera, const osg::Matrix& projectionOffset, const osg::Matrix& viewOffset, bool useMastersSceneData)\n{\n if (!camera) return false;\n\n camera->setView(this);\n\n\n if (useMastersSceneData)\n {\n camera->removeChildren(0,camera->getNumChildren());\n\n if (_camera.valid())\n {\n for(unsigned int i=0; i<_camera->getNumChildren(); ++i)\n {\n camera->addChild(_camera->getChild(i));\n }\n }\n }\n\n unsigned int i = _slaves.size();\n\n _slaves.push_back(Slave(camera, projectionOffset, viewOffset, useMastersSceneData));\n _slaves[i].updateSlave(*this);\n\n camera->setRenderer(createRenderer(camera));\n\n return true;\n}\n\nbool View::removeSlave(unsigned int pos)\n{\n if (pos >= _slaves.size()) return false;\n\n _slaves[pos]._camera->setView(0);\n _slaves[pos]._camera->setCullCallback(0);\n\n _slaves.erase(_slaves.begin()+pos);\n\n return true;\n}\n\n\nView::Slave * View::findSlaveForCamera(osg::Camera* camera)\n{\n unsigned int i = findSlaveIndexForCamera(camera);\n\n if (i >= getNumSlaves()) return (NULL);\n\n return &(_slaves[i]);\n}\n\nunsigned int View::findSlaveIndexForCamera(osg::Camera* camera) const\n{\n if (_camera == camera) return _slaves.size();\n\n for(unsigned int i=0; i<_slaves.size(); ++i)\n {\n if (_slaves[i]._camera == camera) return (i);\n }\n\n return _slaves.size();\n}\n\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010, Willow Garage, Inc.\n * Copyright (c) 2012-, Open Perception, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n\/**\n\n@b pcd_concatenate_points exemplifies how to concatenate the points of two PointClouds having the same fields.\n\n**\/\n\n#include \n#include \n#include \n#include \n\nEigen::Vector4f translation;\nEigen::Quaternionf orientation;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/** \\brief Parse command line arguments for file names. \n * Returns: a vector with file names indices.\n * \\param argc \n * \\param argv\n * \\param extension\n *\/\nstd::vector\nparseFileExtensionArgument (int argc, char** argv, std::string extension)\n{\n std::vector indices;\n for (int i = 1; i < argc; ++i)\n {\n std::string fname = std::string (argv[i]);\n \n \/\/ Needs to be at least 4: .ext\n if (fname.size () <= 4)\n continue;\n \n \/\/ For being case insensitive\n std::transform (fname.begin (), fname.end (), fname.begin (), tolower);\n std::transform (extension.begin (), extension.end (), extension.begin (), tolower);\n \n \/\/ Check if found\n std::string::size_type it;\n if ((it = fname.find (extension)) != std::string::npos)\n {\n \/\/ Additional check: we want to be able to differentiate between .p and .png\n if ((extension.size () - (fname.size () - it)) == 0)\n indices.push_back (i);\n }\n }\n return (indices);\n}\n\nbool\nloadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)\n{\n using namespace pcl::console;\n TicToc tt;\n print_highlight (\"Loading \"); print_value (\"%s \", filename.c_str ());\n\n tt.tic ();\n if (pcl::io::loadPCDFile (filename, cloud, translation, orientation) < 0)\n return (false);\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", cloud.width * cloud.height); print_info (\" points]\\n\");\n print_info (\"Available dimensions: \"); print_value (\"%s\\n\", pcl::getFieldsList (cloud).c_str ());\n\n return (true);\n}\n\nvoid\nsaveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)\n{\n using namespace pcl::console;\n TicToc tt;\n tt.tic ();\n\n print_highlight (\"Saving \"); print_value (\"%s \", filename.c_str ());\n\n pcl::PCDWriter w;\n w.writeBinaryCompressed (filename, output, translation, orientation);\n \n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", output.width * output.height); print_info (\" points]\\n\");\n}\n\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n if (argc < 2)\n {\n std::cerr << \"Syntax is: \" << argv[0] << \" \" << std::endl;\n std::cerr << \"Result will be saved to output.pcd\" << std::endl;\n return (-1);\n }\n\n std::vector file_indices = parseFileExtensionArgument (argc, argv, \".pcd\");\n\n \/\/pcl::PointCloud cloud_all;\n sensor_msgs::PointCloud2 cloud_all;\n for (size_t i = 0; i < file_indices.size (); ++i)\n {\n \/\/ Load the Point Cloud\n sensor_msgs::PointCloud2 cloud;\n loadCloud (argv[file_indices[i]], cloud);\n \/\/pcl::PointCloud cloud;\n \/\/pcl::io::loadPCDFile (argv[file_indices[i]], cloud);\n \/\/cloud_all += cloud;\n pcl::concatenatePointCloud (cloud_all, cloud, cloud_all);\n }\n\n saveCloud (\"output.pcd\", cloud_all);\n \n return (0);\n}\n\/* ]--- *\/\nadded extra info\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010, Willow Garage, Inc.\n * Copyright (c) 2012-, Open Perception, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n\/**\n\n@b pcd_concatenate_points exemplifies how to concatenate the points of two PointClouds having the same fields.\n\n**\/\n\n#include \n#include \n#include \n#include \n\nEigen::Vector4f translation;\nEigen::Quaternionf orientation;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/** \\brief Parse command line arguments for file names. \n * Returns: a vector with file names indices.\n * \\param argc \n * \\param argv\n * \\param extension\n *\/\nstd::vector\nparseFileExtensionArgument (int argc, char** argv, std::string extension)\n{\n std::vector indices;\n for (int i = 1; i < argc; ++i)\n {\n std::string fname = std::string (argv[i]);\n \n \/\/ Needs to be at least 4: .ext\n if (fname.size () <= 4)\n continue;\n \n \/\/ For being case insensitive\n std::transform (fname.begin (), fname.end (), fname.begin (), tolower);\n std::transform (extension.begin (), extension.end (), extension.begin (), tolower);\n \n \/\/ Check if found\n std::string::size_type it;\n if ((it = fname.find (extension)) != std::string::npos)\n {\n \/\/ Additional check: we want to be able to differentiate between .p and .png\n if ((extension.size () - (fname.size () - it)) == 0)\n indices.push_back (i);\n }\n }\n return (indices);\n}\n\nbool\nloadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)\n{\n using namespace pcl::console;\n TicToc tt;\n print_highlight (\"Loading \"); print_value (\"%s \", filename.c_str ());\n\n tt.tic ();\n if (pcl::io::loadPCDFile (filename, cloud, translation, orientation) < 0)\n return (false);\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", cloud.width * cloud.height); print_info (\" points]\\n\");\n print_info (\"Available dimensions: \"); print_value (\"%s\\n\", pcl::getFieldsList (cloud).c_str ());\n\n return (true);\n}\n\nvoid\nsaveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)\n{\n using namespace pcl::console;\n TicToc tt;\n tt.tic ();\n\n print_highlight (\"Saving \"); print_value (\"%s \", filename.c_str ());\n\n pcl::PCDWriter w;\n w.writeBinary (filename, output, translation, orientation);\n \n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", output.width * output.height); print_info (\" points]\\n\");\n}\n\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n if (argc < 2)\n {\n std::cerr << \"Syntax is: \" << argv[0] << \" \" << std::endl;\n std::cerr << \"Result will be saved to output.pcd\" << std::endl;\n return (-1);\n }\n\n std::vector file_indices = parseFileExtensionArgument (argc, argv, \".pcd\");\n\n \/\/pcl::PointCloud cloud_all;\n sensor_msgs::PointCloud2 cloud_all;\n for (size_t i = 0; i < file_indices.size (); ++i)\n {\n \/\/ Load the Point Cloud\n sensor_msgs::PointCloud2 cloud;\n loadCloud (argv[file_indices[i]], cloud);\n \/\/pcl::PointCloud cloud;\n \/\/pcl::io::loadPCDFile (argv[file_indices[i]], cloud);\n \/\/cloud_all += cloud;\n pcl::concatenatePointCloud (cloud_all, cloud, cloud_all);\n PCL_INFO (\"Total number of points so far: %u. Total data size: %zu bytes.\\n\", cloud_all.width * cloud_all.height, cloud_all.data.size ());\n }\n\n saveCloud (\"output.pcd\", cloud_all);\n \n return (0);\n}\n\/* ]--- *\/\n<|endoftext|>"} {"text":"#include \"ArgHandler.h\"\n\nArgHandler::ArgHandler() {\n\t\/\/ handle defaults in the parse(..) and verify(..) functions\n}\nvoid ArgHandler::parse(int argc, char** argv) {\n\tdesc.add_options()\n \n \/*\n --dsl on\n --dsb on\n --friderived on\n\n --nfeed on\n --avlnflg on\n --baseline on\n *\/\n (\"env\", boost::program_options::value(&env)->default_value(\"on\"),\n \"Turn the environmental module on or off.\"\n )\n (\"bgc\", boost::program_options::value(&bgc)->default_value(\"on\"),\n \"Turn the biogeochemical module on or off.\"\n )\n (\"dvm\", boost::program_options::value(&dvm)->default_value(\"on\"),\n \"Turn the dynamic vegetation module on or off.\"\n )\n (\"calibrationmode\", boost::program_options::value(&calibrationmode)->default_value(\"off\"),\n \"(NOT IMPLEMENTED) whether or not the calibration module is on...? \"\n \"list of strings for modules to calibrate?\"\n )\n (\"loglevel,l\", boost::program_options::value(&loglevel)->default_value(\"trace\"), \n \"the level above which all log messages will be printed. Here are the \"\n \"choices: trace, debug, info, warning, error, fatal.\"\n )\n\t\t(\"mode,m\", boost::program_options::value(&mode)->default_value(\"siterun\"),\"change mode between siterun and regnrun\")\n\t\t(\"control-file,f\", boost::program_options::value(&ctrlfile)->default_value(\"config\/controlfile_site.txt\"), \"choose a control file to use\")\n\t\t(\"cohort-id,c\", boost::program_options::value(&chtid)->default_value(\"1\"), \"choose a specific cohort to run\")\n\t\t(\"space-time-config,s\", boost::program_options::value(), \"choose spatial or temporal running mode\")\n\t\t(\"help,h\", \"produces helps message, then quits\")\n\t\t(\"version,v\", \"(NOT IMPLEMENTED)show the version information\")\n\t\t(\"debug,d\", \"(NOT IMPLEMENTED) enable debug mode\")\n\t;\n\n\tboost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), varmap);\n\tboost::program_options::notify(varmap);\n\n if (varmap.count(\"env\")) {\n env = varmap[\"env\"].as();\n }\n if (varmap.count(\"bgc\")) {\n bgc = varmap[\"bgc\"].as();\n }\n if (varmap.count(\"dvm\")) {\n dvm = varmap[\"dvm\"].as();\n }\n \n\tif (varmap.count(\"cohort-id\")) {\n\t\tchtid = varmap[\"cohort-id\"].as();\n\t}\n\t\n\tif (varmap.count(\"space-time-config\")) {\n\t\tregrunmode = varmap[\"space-time-config\"].as();\n\t}\n\n\tif (varmap.count(\"help\")) {\n\t\thelp = true;\n\t}\n\n\tif (varmap.count(\"version\")) {\n\t\tversion = true;\n\t}\n\n\tif (varmap.count(\"debug\")) {\n\t\tdebug = true;\n\t}\n}\n\nvoid ArgHandler::verify() {\n \/\/ The regional \"run mode\"...loop order??\n std::cout << \"Verification reuimentary - needs more programming help!\\n\";\n if (mode.compare(\"regnrun\") == 0) {\n if ( (regrunmode.compare(\"regner1\") == 0) || \n (regrunmode.compare(\"regner2\") == 0) ) {\n \/\/ pass, all ok\n } else {\n std::cout << \"Invalid option (regrunmode). Quitting.\\n\";\n exit(-1);\n }\n } \n}\n\nstring ArgHandler::getEnv() const {\n return env;\n}\nstring ArgHandler::getBgc() const {\n return bgc;\n}\nstring ArgHandler::getDvm() const {\n return dvm;\n}\nstring ArgHandler::getCalibrationMode(){\n return calibrationmode;\n}\nstring ArgHandler::getLogLevel(){\n\treturn loglevel;\n}\nstring ArgHandler::getMode(){\n\treturn mode;\n}\n\nstring ArgHandler::getCtrlfile(){\n\treturn ctrlfile;\n}\n\nstring ArgHandler::getChtid(){\n\treturn chtid;\n}\n\nstring ArgHandler::getRegrunmode(){\n\treturn regrunmode;\n}\n\nvoid ArgHandler::showHelp(){\n\/**\n * Print out command help\n *\/\n\tstd::cout << desc << std::endl;\n}\ncomment out command line options for module control.#include \"ArgHandler.h\"\n\nArgHandler::ArgHandler() {\n\t\/\/ handle defaults in the parse(..) and verify(..) functions\n}\nvoid ArgHandler::parse(int argc, char** argv) {\n\tdesc.add_options()\n \n \/*\n --env [ on | off ]\n --bgc [ on | off ]\n --dvm [ on | off ]\n --dsl [ on | off ]\n --dsb [ on | off ]\n --friderived [ on | off ]\n *\/\n \/\/ NOT IMPLEMENTED YET - need to sort out some issues\n \/\/ (\"env\", boost::program_options::value(&env)->default_value(\"on\"),\n \/\/ \"Turn the environmental module on or off.\"\n \/\/ )\n \/\/ (\"bgc\", boost::program_options::value(&bgc)->default_value(\"on\"),\n \/\/ \"Turn the biogeochemical module on or off.\"\n \/\/ )\n \/\/ (\"dvm\", boost::program_options::value(&dvm)->default_value(\"on\"),\n \/\/ \"Turn the dynamic vegetation module on or off.\"\n \/\/ )\n \n (\"calibrationmode\", boost::program_options::value(&calibrationmode)->default_value(\"off\"),\n \"(NOT IMPLEMENTED) whether or not the calibration module is on...? \"\n \"list of strings for modules to calibrate?\"\n )\n (\"loglevel,l\", boost::program_options::value(&loglevel)->default_value(\"trace\"), \n \"the level above which all log messages will be printed. Here are the \"\n \"choices: trace, debug, info, warning, error, fatal.\"\n )\n\t\t(\"mode,m\", boost::program_options::value(&mode)->default_value(\"siterun\"),\"change mode between siterun and regnrun\")\n\t\t(\"control-file,f\", boost::program_options::value(&ctrlfile)->default_value(\"config\/controlfile_site.txt\"), \"choose a control file to use\")\n\t\t(\"cohort-id,c\", boost::program_options::value(&chtid)->default_value(\"1\"), \"choose a specific cohort to run\")\n\t\t(\"space-time-config,s\", boost::program_options::value(), \"choose spatial or temporal running mode\")\n\t\t(\"help,h\", \"produces helps message, then quits\")\n\t\t(\"version,v\", \"(NOT IMPLEMENTED)show the version information\")\n\t\t(\"debug,d\", \"(NOT IMPLEMENTED) enable debug mode\")\n\t;\n\n\tboost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), varmap);\n\tboost::program_options::notify(varmap);\n\n if (varmap.count(\"env\")) {\n env = varmap[\"env\"].as();\n }\n if (varmap.count(\"bgc\")) {\n bgc = varmap[\"bgc\"].as();\n }\n if (varmap.count(\"dvm\")) {\n dvm = varmap[\"dvm\"].as();\n }\n \n\tif (varmap.count(\"cohort-id\")) {\n\t\tchtid = varmap[\"cohort-id\"].as();\n\t}\n\t\n\tif (varmap.count(\"space-time-config\")) {\n\t\tregrunmode = varmap[\"space-time-config\"].as();\n\t}\n\n\tif (varmap.count(\"help\")) {\n\t\thelp = true;\n\t}\n\n\tif (varmap.count(\"version\")) {\n\t\tversion = true;\n\t}\n\n\tif (varmap.count(\"debug\")) {\n\t\tdebug = true;\n\t}\n}\n\nvoid ArgHandler::verify() {\n \/\/ The regional \"run mode\"...loop order??\n std::cout << \"Verification reuimentary - needs more programming help!\\n\";\n if (mode.compare(\"regnrun\") == 0) {\n if ( (regrunmode.compare(\"regner1\") == 0) || \n (regrunmode.compare(\"regner2\") == 0) ) {\n \/\/ pass, all ok\n } else {\n std::cout << \"Invalid option (regrunmode). Quitting.\\n\";\n exit(-1);\n }\n } \n}\n\nstring ArgHandler::getEnv() const {\n return env;\n}\nstring ArgHandler::getBgc() const {\n return bgc;\n}\nstring ArgHandler::getDvm() const {\n return dvm;\n}\nstring ArgHandler::getCalibrationMode(){\n return calibrationmode;\n}\nstring ArgHandler::getLogLevel(){\n\treturn loglevel;\n}\nstring ArgHandler::getMode(){\n\treturn mode;\n}\n\nstring ArgHandler::getCtrlfile(){\n\treturn ctrlfile;\n}\n\nstring ArgHandler::getChtid(){\n\treturn chtid;\n}\n\nstring ArgHandler::getRegrunmode(){\n\treturn regrunmode;\n}\n\nvoid ArgHandler::showHelp(){\n\/**\n * Print out command help\n *\/\n\tstd::cout << desc << std::endl;\n}\n<|endoftext|>"} {"text":"\/* \n Authors: Darya Filippova, Geet Duggal, Rob Patro\n dfilippo | geet | robp @cs.cmu.edu\n*\/\n\n#include \n#include \n#include \n#include \n#include \"ArmatusDAG.hpp\"\n\nArmatusDAG::ArmatusDAG(ArmatusParams& p) :\n\tsubProbs(SubProbsVec(p.n)), \n edgeWeights(EdgeWeightsVec(p.n, vector())) {\n\tparams = &p;\n}\n\nvoid ArmatusDAG::build() {\n\t\/\/ Since building the DAG visits everything in the same order as computing\n\t\/\/ a single optimial solution, I've had this function also fill out the\n\t\/\/ necessary information to obtain a backtrace of the opt. sln.\n\tsubProbs[0].topK.push_back({std::numeric_limits::max(), 0, 0.0});\n\t\/\/ What's the right condition here?\n\t\/\/ subProbs[1].topK.push_back({0, 0, std::max(q(0,1), 0.0)});\t\n\t\n for (size_t l : boost::irange(size_t{1}, params->n)) {\n \/\/ was this\n \t \/\/ edgeWeights[l].resize(l-1);\n \/\/ now this\n \t edgeWeights[l].resize(l);\n \t size_t chosenEdge = 0; \n \t double bestScore = 0.0;\n \t for (size_t k : boost::irange(size_t{0}, l)) {\n \t \t\/\/ The last domain is [k,l]\n \t \tdouble edgeWeight = std::max(q(k, l), 0.0);\n edgeWeights[l][k] = edgeWeight;\n double totalScore = edgeWeight;\n bool isDomain = edgeWeight > 0.0;\n bool isPrevDomain = (k == 0) ? true : false;\n if (k > 0) {\n double prevDomainScore = subProbs[k-1].topK[0].score; \n isPrevDomain = prevDomainScore > 0.0;\n \/\/ The score of this solution is the benefit we get from traversing\n \/\/ the edge + the best score available at the child\n totalScore += prevDomainScore;\n }\n if (isDomain or isPrevDomain) {\n if (totalScore > bestScore) {\n bestScore = totalScore;\n chosenEdge = k;\n }\n }\n \t }\n\n \t \/\/ Put our best solution on the stack.\n \t subProbs[l].topK.push_back({chosenEdge, 0, bestScore});\n }\n}\n\n\ndouble ArmatusDAG::s(size_t k, size_t l) {\n\tsize_t d = l-k+1;\n return params->sums(k, l)\/ std::pow(static_cast(d),params->gamma);\n}\n\ndouble ArmatusDAG::q(size_t k, size_t l) {\n\tsize_t d = l-k+1;\n\treturn (s(k, l) - params->mu[d]);\n}\n\n\/**\n* This interface is *wrong* but I wanted to sketch the\n* basic algo.\n**\/\nvoid ArmatusDAG::computeTopK(uint32_t k) {\n\tfor (size_t l : boost::irange(size_t{1}, params->n)) {\n\t\tstd::function BackPointerComparator = [l, this] (const BackPointer& x, const BackPointer& y) -> bool {\n auto scoreX = this->edgeWeights[l][x.edge];\n if (x.edge > 0) { scoreX += this->subProbs[x.edge-1].topK[x.childSolution].score; }\n auto scoreY = this->edgeWeights[l][y.edge];\n if (y.edge > 0) { scoreY += this->subProbs[y.edge-1].topK[y.childSolution].score; }\n\n\t\t\treturn scoreX < scoreY;\n\t\t};\n\n\t\tboost::heap::binomial_heap> pq(BackPointerComparator);\n\t\tfor (size_t j : boost::irange(size_t{0}, l)) { \n if (j > 0) {\n size_t i = j - 1;\n bool isDomain = edgeWeights[l][j] > 0.0; \n bool prevIsDomain = (subProbs[i].topK.size() > 0 and edgeWeights[i].size() > 0) ? edgeWeights[i][subProbs[i].topK[0].edge] > 0 : true;\n if (j == 1) { prevIsDomain = false; }\n \n if (isDomain or prevIsDomain) {\n double score = edgeWeights[l][j] + subProbs[i].topK[0].score;\n pq.push({j, 0, score});\n }\n } else {\n double score = edgeWeights[l][0];\n pq.push({0, 0, score});\n }\n\t\t}\n\n\t\twhile (subProbs[l].topK.size() < k and !pq.empty()) {\n\t\t\tauto bp = pq.top();\n\t\t\tpq.pop();\n size_t j = bp.edge;\n if (j > 0) {\n bool alreadyFound{false};\n if (bp != subProbs[l].topK[0] ) { subProbs[l].topK.push_back(bp); }\n size_t nextSlnIdx = bp.childSolution + 1;\n bool isDomain = edgeWeights[l][j] > 0.0;\n \n size_t i = j - 1;\n \/\/std::cout << bp.edge << \"\\t\" << subProbs.size() << endl;\n if (nextSlnIdx < subProbs[i].topK.size()) {\n bool prevIsDomain = edgeWeights[i][subProbs[i].topK[nextSlnIdx].edge] > 0.0;\n if (isDomain or prevIsDomain ) {\n double score = edgeWeights[l][j] + subProbs[i].topK[nextSlnIdx].score;\n pq.push({j, nextSlnIdx, score});\n }\n }\n } else {\n if (bp != subProbs[l].topK[0] ) { subProbs[l].topK.push_back(bp); }\n }\n\t\t}\n\t}\n\n\t\/\/ size_t sln = 0;\n\t\/\/ while (sln < k and sln < subProbs[params->n-1].topK.size()) {\n\t\/\/ \tstd::cerr << \"solution \" << sln << \" has score \" << subProbs[params->n-1].topK[sln].score << \"\\n\";\n\t\/\/ \t++sln;\n\t\/\/ }\n}\n\n\nWeightedDomainEnsemble ArmatusDAG::extractTopK(uint32_t k) {\n\n const size_t INVALID = std::numeric_limits::max();\n \/\/ We skip 0 since that was already extracted by viterbiPath\n uint32_t currSln{0};\n\n WeightedDomainEnsemble solutions{ DomainEnsemble(k, DomainSet()), Weights(k, 0.0) };\n auto root = params->n-1;\n auto topScore = subProbs[root].topK[0].score;\n auto scores = Weights(k, 0.0);\n\n while (currSln < k and currSln < subProbs[root].topK.size()) {\n auto currentScore = subProbs[root].topK[currSln].score;\n scores[currSln] = currentScore;\n auto& currentDomainSet = solutions.domainSets[currSln];\n solutions.weights[currSln] = currentScore \/ topScore;\n\n \/\/ Which solution to use at the child\n auto bp = currSln;\n int64_t end = params->n-1;\n bool prevWasDomain = true;\n bool done{false};\n Domain prevDomain(root, root);\n\n while (end > 0) { \/\/ and subProbs[end].topK[bp].edge != INVALID) {\n \/\/std::cerr << \"end: \" << end << \"\\n\";\n size_t begin = subProbs[end].topK[bp].edge;\n size_t start = begin;\n\/\/ if (subProbs[begin].topK[subProbs[end].topK[bp].childSolution].edge != INVALID)\n\/\/ start++;\n Domain d(start, end);\n if (d.score(*params) > 0.0){\n currentDomainSet.push_back(d);\n prevWasDomain = true;\n } else {\n \/\/currentDomainSet.push_back(d);\n if (!prevWasDomain) { \n std::cerr << \"WHAT: solution contained two adjacent non-domains; current domain is (\" << start << \", \" << end << \") prev domain was (\" << prevDomain.start << \", \" << prevDomain.end << \")\\n\"; \n }\n prevWasDomain = false;\n }\n prevDomain = d;\n bp = subProbs[end].topK[bp].childSolution;\n end = begin-1;\n }\n\n ++currSln;\n }\n\n \/**\n * consistency check all the extracted domains (for debug purposes only, \n * take this out for release \/ speed).\n *\/\n size_t c = 0;\n double eps = 1e-3;\n for (auto& ds : solutions.domainSets) {\n double score = 0.0;\n for (auto& d : ds) {\n score += d.score(*params);\n }\n if (std::abs(score - scores[c]) > eps) { \n std::cerr << \"For solution [\" << c << \"], the recorded score was \" << scores[c] << \" but extracted domains sum to \" << score << \"\\n\";\n }\n ++c;\n }\n \n return solutions;\n}\n\nvector ArmatusDAG::viterbiPath() {\n\tvector domains;\n const size_t INVALID = std::numeric_limits::max();\n\tsize_t end = params->n-1;\n\t\/\/std::cerr << \"Best score is \" << subProbs[end].topK[0].score << \"\\n\";\n\n\twhile (subProbs[end].topK[0].edge != INVALID) {\n\t\tsize_t begin = subProbs[end].topK[0].edge;\n\t\tdomains.push_back({begin+1, end});\n\t\tend = begin;\n\t}\n\n sort(domains.begin(), domains.end());\n\n\treturn domains;\n}\nIndenting changes\/* \n Authors: Darya Filippova, Geet Duggal, Rob Patro\n dfilippo | geet | robp @cs.cmu.edu\n*\/\n\n#include \n#include \n#include \n#include \n#include \"ArmatusDAG.hpp\"\n\nArmatusDAG::ArmatusDAG(ArmatusParams& p) :\n\tsubProbs(SubProbsVec(p.n)), \n edgeWeights(EdgeWeightsVec(p.n, vector())) {\n\tparams = &p;\n}\n\nvoid ArmatusDAG::build() {\n\t\/\/ Since building the DAG visits everything in the same order as computing\n\t\/\/ a single optimial solution, I've had this function also fill out the\n\t\/\/ necessary information to obtain a backtrace of the opt. sln.\n\tsubProbs[0].topK.push_back({std::numeric_limits::max(), 0, 0.0});\n\t\/\/ What's the right condition here?\n\t\/\/ subProbs[1].topK.push_back({0, 0, std::max(q(0,1), 0.0)});\t\n\t\n for (size_t l : boost::irange(size_t{1}, params->n)) {\n \/\/ was this\n \t \/\/ edgeWeights[l].resize(l-1);\n \/\/ now this\n \t edgeWeights[l].resize(l);\n \t size_t chosenEdge = 0; \n \t double bestScore = 0.0;\n \t for (size_t k : boost::irange(size_t{0}, l)) {\n \t \t\/\/ The last domain is [k,l]\n \t \tdouble edgeWeight = std::max(q(k, l), 0.0);\n edgeWeights[l][k] = edgeWeight;\n double totalScore = edgeWeight;\n bool isDomain = edgeWeight > 0.0;\n bool isPrevDomain = (k == 0) ? true : false;\n if (k > 0) {\n double prevDomainScore = subProbs[k-1].topK[0].score; \n isPrevDomain = prevDomainScore > 0.0;\n \/\/ The score of this solution is the benefit we get from traversing\n \/\/ the edge + the best score available at the child\n totalScore += prevDomainScore;\n }\n if (isDomain or isPrevDomain) {\n if (totalScore > bestScore) {\n bestScore = totalScore;\n chosenEdge = k;\n }\n }\n \t }\n\n \t \/\/ Put our best solution on the stack.\n \t subProbs[l].topK.push_back({chosenEdge, 0, bestScore});\n }\n}\n\n\ndouble ArmatusDAG::s(size_t k, size_t l) {\n\tsize_t d = l-k+1;\n return params->sums(k, l)\/ std::pow(static_cast(d),params->gamma);\n}\n\ndouble ArmatusDAG::q(size_t k, size_t l) {\n\tsize_t d = l-k+1;\n\treturn (s(k, l) - params->mu[d]);\n}\n\n\/**\n* This interface is *wrong* but I wanted to sketch the\n* basic algo.\n**\/\nvoid ArmatusDAG::computeTopK(uint32_t k) {\n for (size_t l : boost::irange(size_t{1}, params->n)) {\n std::function BackPointerComparator = [l, this] (const BackPointer& x, const BackPointer& y) -> bool {\n auto scoreX = this->edgeWeights[l][x.edge];\n if (x.edge > 0) { scoreX += this->subProbs[x.edge-1].topK[x.childSolution].score; }\n auto scoreY = this->edgeWeights[l][y.edge];\n if (y.edge > 0) { scoreY += this->subProbs[y.edge-1].topK[y.childSolution].score; }\n\n return scoreX < scoreY;\n };\n\n boost::heap::binomial_heap> pq(BackPointerComparator);\n for (size_t j : boost::irange(size_t{0}, l)) { \n if (j > 0) {\n size_t i = j - 1;\n bool isDomain = edgeWeights[l][j] > 0.0; \n bool prevIsDomain = (subProbs[i].topK.size() > 0 and edgeWeights[i].size() > 0) ? edgeWeights[i][subProbs[i].topK[0].edge] > 0 : true;\n if (j == 1) { prevIsDomain = false; }\n\n if (isDomain or prevIsDomain) {\n double score = edgeWeights[l][j] + subProbs[i].topK[0].score;\n pq.push({j, 0, score});\n }\n } else {\n double score = edgeWeights[l][0];\n pq.push({0, 0, score});\n }\n }\n\n while (subProbs[l].topK.size() < k and !pq.empty()) {\n auto bp = pq.top();\n pq.pop();\n size_t j = bp.edge;\n if (j > 0) {\n bool alreadyFound{false};\n if (bp != subProbs[l].topK[0] ) { subProbs[l].topK.push_back(bp); }\n size_t nextSlnIdx = bp.childSolution + 1;\n bool isDomain = edgeWeights[l][j] > 0.0;\n\n size_t i = j - 1;\n \/\/std::cout << bp.edge << \"\\t\" << subProbs.size() << endl;\n if (nextSlnIdx < subProbs[i].topK.size()) {\n bool prevIsDomain = edgeWeights[i][subProbs[i].topK[nextSlnIdx].edge] > 0.0;\n if (isDomain or prevIsDomain ) {\n double score = edgeWeights[l][j] + subProbs[i].topK[nextSlnIdx].score;\n pq.push({j, nextSlnIdx, score});\n }\n }\n } else {\n if (bp != subProbs[l].topK[0] ) { subProbs[l].topK.push_back(bp); }\n }\n }\n }\n\n \/\/ size_t sln = 0;\n \/\/ while (sln < k and sln < subProbs[params->n-1].topK.size()) {\n \/\/ \tstd::cerr << \"solution \" << sln << \" has score \" << subProbs[params->n-1].topK[sln].score << \"\\n\";\n \/\/ \t++sln;\n \/\/ }\n}\n\n\nWeightedDomainEnsemble ArmatusDAG::extractTopK(uint32_t k) {\n\n const size_t INVALID = std::numeric_limits::max();\n \/\/ We skip 0 since that was already extracted by viterbiPath\n uint32_t currSln{0};\n\n WeightedDomainEnsemble solutions{ DomainEnsemble(k, DomainSet()), Weights(k, 0.0) };\n auto root = params->n-1;\n auto topScore = subProbs[root].topK[0].score;\n auto scores = Weights(k, 0.0);\n\n while (currSln < k and currSln < subProbs[root].topK.size()) {\n auto currentScore = subProbs[root].topK[currSln].score;\n scores[currSln] = currentScore;\n auto& currentDomainSet = solutions.domainSets[currSln];\n solutions.weights[currSln] = currentScore \/ topScore;\n\n \/\/ Which solution to use at the child\n auto bp = currSln;\n int64_t end = params->n-1;\n bool prevWasDomain = true;\n bool done{false};\n Domain prevDomain(root, root);\n\n while (end > 0) { \/\/ and subProbs[end].topK[bp].edge != INVALID) {\n \/\/std::cerr << \"end: \" << end << \"\\n\";\n size_t begin = subProbs[end].topK[bp].edge;\n size_t start = begin;\n\/\/ if (subProbs[begin].topK[subProbs[end].topK[bp].childSolution].edge != INVALID)\n\/\/ start++;\n Domain d(start, end);\n if (d.score(*params) > 0.0){\n currentDomainSet.push_back(d);\n prevWasDomain = true;\n } else {\n \/\/currentDomainSet.push_back(d);\n if (!prevWasDomain) { \n std::cerr << \"WHAT: solution contained two adjacent non-domains; current domain is (\" << start << \", \" << end << \") prev domain was (\" << prevDomain.start << \", \" << prevDomain.end << \")\\n\"; \n }\n prevWasDomain = false;\n }\n prevDomain = d;\n bp = subProbs[end].topK[bp].childSolution;\n end = begin-1;\n }\n\n ++currSln;\n }\n\n \/**\n * consistency check all the extracted domains (for debug purposes only, \n * take this out for release \/ speed).\n *\/\n size_t c = 0;\n double eps = 1e-3;\n for (auto& ds : solutions.domainSets) {\n double score = 0.0;\n for (auto& d : ds) {\n score += d.score(*params);\n }\n if (std::abs(score - scores[c]) > eps) { \n std::cerr << \"For solution [\" << c << \"], the recorded score was \" << scores[c] << \" but extracted domains sum to \" << score << \"\\n\";\n }\n ++c;\n }\n \n return solutions;\n}\n\nvector ArmatusDAG::viterbiPath() {\n\tvector domains;\n const size_t INVALID = std::numeric_limits::max();\n\tsize_t end = params->n-1;\n\t\/\/std::cerr << \"Best score is \" << subProbs[end].topK[0].score << \"\\n\";\n\n\twhile (subProbs[end].topK[0].edge != INVALID) {\n\t\tsize_t begin = subProbs[end].topK[0].edge;\n\t\tdomains.push_back({begin+1, end});\n\t\tend = begin;\n\t}\n\n sort(domains.begin(), domains.end());\n\n\treturn domains;\n}\n<|endoftext|>"} {"text":"\/\/ Tests to drive abstract sharing analysis\n\n#include \"types.h\"\n#include \"user.h\"\n#include \"mtrace.h\"\n\n#include \n\nint\nmain(int ac, char **av)\n{\n if (ac == 2 && strcmp(av[1], \"on\") == 0)\n mtenable_type(mtrace_record_ascope, \"xv6-asharing\");\n else if (ac == 2 && strcmp(av[1], \"off\") == 0)\n mtdisable(\"xv6-asharing\"); \n else\n die(\"usage: %s on|off\\n\", av[0]);\n}\nbin\/avar.cc: add an \"onkern\" option\/\/ Tests to drive abstract sharing analysis\n\n#include \"types.h\"\n#include \"user.h\"\n#include \"mtrace.h\"\n\n#include \n\nint\nmain(int ac, char **av)\n{\n if (ac == 2 && strcmp(av[1], \"on\") == 0)\n mtenable_type(mtrace_record_ascope, \"xv6-asharing\");\n else if (ac == 2 && strcmp(av[1], \"onkern\") == 0)\n mtenable_type(mtrace_record_kernelscope, \"xv6-asharing\");\n else if (ac == 2 && strcmp(av[1], \"off\") == 0)\n mtdisable(\"xv6-asharing\"); \n else\n die(\"usage: %s on|onkern|off\\n\", av[0]);\n}\n<|endoftext|>"} {"text":"\/\/===- MC-X86Specific.cpp - X86-Specific code for MC ----------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements X86-specific parsing, encoding and decoding stuff for\n\/\/ MC.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AsmParser.h\"\n#include \"llvm\/MC\/MCInst.h\"\nusing namespace llvm;\n\n\/\/\/ X86Operand - Instances of this class represent one X86 machine instruction.\nstruct AsmParser::X86Operand {\n enum {\n Register,\n Immediate,\n Memory\n } Kind;\n \n union {\n struct {\n unsigned RegNo;\n } Reg;\n\n struct {\n MCValue Val;\n } Imm;\n \n struct {\n unsigned SegReg;\n MCValue Disp;\n unsigned BaseReg;\n unsigned IndexReg;\n unsigned Scale;\n } Mem;\n };\n \n unsigned getReg() const {\n assert(Kind == Register && \"Invalid access!\");\n return Reg.RegNo;\n }\n\n static X86Operand CreateReg(unsigned RegNo) {\n X86Operand Res;\n Res.Kind = Register;\n Res.Reg.RegNo = RegNo;\n return Res;\n }\n static X86Operand CreateImm(MCValue Val) {\n X86Operand Res;\n Res.Kind = Immediate;\n Res.Imm.Val = Val;\n return Res;\n }\n static X86Operand CreateMem(unsigned SegReg, MCValue Disp, unsigned BaseReg,\n unsigned IndexReg, unsigned Scale) {\n \/\/ If there is no index register, we should never have a scale, and we\n \/\/ should always have a scale (in {1,2,4,8}) if we do.\n assert(((Scale == 0 && !IndexReg) ||\n (IndexReg && (Scale == 1 || Scale == 2 || \n Scale == 4 || Scale == 8))) &&\n \"Invalid scale!\");\n X86Operand Res;\n Res.Kind = Memory;\n Res.Mem.SegReg = SegReg;\n Res.Mem.Disp = Disp;\n Res.Mem.BaseReg = BaseReg;\n Res.Mem.IndexReg = IndexReg;\n Res.Mem.Scale = Scale;\n return Res;\n }\n};\n\nbool AsmParser::ParseX86Register(X86Operand &Op) {\n assert(Lexer.getKind() == asmtok::Register && \"Invalid token kind!\");\n\n \/\/ FIXME: Decode register number.\n Op = X86Operand::CreateReg(123);\n Lexer.Lex(); \/\/ Eat register token.\n\n return false;\n}\n\nbool AsmParser::ParseX86Operand(X86Operand &Op) {\n switch (Lexer.getKind()) {\n default:\n return ParseX86MemOperand(Op);\n case asmtok::Register:\n \/\/ FIXME: if a segment register, this could either be just the seg reg, or\n \/\/ the start of a memory operand.\n return ParseX86Register(Op);\n case asmtok::Dollar: {\n \/\/ $42 -> immediate.\n Lexer.Lex();\n MCValue Val;\n if (ParseRelocatableExpression(Val))\n return true;\n Op = X86Operand::CreateImm(Val);\n return false;\n }\n case asmtok::Star: {\n Lexer.Lex(); \/\/ Eat the star.\n \n if (Lexer.is(asmtok::Register)) {\n if (ParseX86Register(Op))\n return true;\n } else if (ParseX86MemOperand(Op))\n return true;\n\n \/\/ FIXME: Note the '*' in the operand for use by the matcher.\n return false;\n }\n }\n}\n\n\/\/\/ ParseX86MemOperand: segment: disp(basereg, indexreg, scale)\nbool AsmParser::ParseX86MemOperand(X86Operand &Op) {\n \/\/ FIXME: If SegReg ':' (e.g. %gs:), eat and remember.\n unsigned SegReg = 0;\n \n \/\/ We have to disambiguate a parenthesized expression \"(4+5)\" from the start\n \/\/ of a memory operand with a missing displacement \"(%ebx)\" or \"(,%eax)\". The\n \/\/ only way to do this without lookahead is to eat the ( and see what is after\n \/\/ it.\n MCValue Disp = MCValue::get(0, 0, 0);\n if (Lexer.isNot(asmtok::LParen)) {\n if (ParseRelocatableExpression(Disp)) return true;\n \n \/\/ After parsing the base expression we could either have a parenthesized\n \/\/ memory address or not. If not, return now. If so, eat the (.\n if (Lexer.isNot(asmtok::LParen)) {\n Op = X86Operand::CreateMem(SegReg, Disp, 0, 0, 0);\n return false;\n }\n \n \/\/ Eat the '('.\n Lexer.Lex();\n } else {\n \/\/ Okay, we have a '('. We don't know if this is an expression or not, but\n \/\/ so we have to eat the ( to see beyond it.\n Lexer.Lex(); \/\/ Eat the '('.\n \n if (Lexer.is(asmtok::Register) || Lexer.is(asmtok::Comma)) {\n \/\/ Nothing to do here, fall into the code below with the '(' part of the\n \/\/ memory operand consumed.\n } else {\n \/\/ It must be an parenthesized expression, parse it now.\n if (ParseParenRelocatableExpression(Disp))\n return true;\n \n \/\/ After parsing the base expression we could either have a parenthesized\n \/\/ memory address or not. If not, return now. If so, eat the (.\n if (Lexer.isNot(asmtok::LParen)) {\n Op = X86Operand::CreateMem(SegReg, Disp, 0, 0, 0);\n return false;\n }\n \n \/\/ Eat the '('.\n Lexer.Lex();\n }\n }\n \n \/\/ If we reached here, then we just ate the ( of the memory operand. Process\n \/\/ the rest of the memory operand.\n unsigned BaseReg = 0, IndexReg = 0, Scale = 0;\n \n if (Lexer.is(asmtok::Register)) {\n if (ParseX86Register(Op))\n return true;\n BaseReg = Op.getReg();\n }\n \n if (Lexer.is(asmtok::Comma)) {\n Lexer.Lex(); \/\/ eat the comma.\n \n if (Lexer.is(asmtok::Register)) {\n if (ParseX86Register(Op))\n return true;\n IndexReg = Op.getReg();\n Scale = 1; \/\/ If not specified, the scale defaults to 1.\n }\n \n if (Lexer.is(asmtok::Comma)) {\n Lexer.Lex(); \/\/ Eat the comma.\n\n \/\/ If present, get and validate scale amount.\n if (Lexer.is(asmtok::IntVal)) {\n int64_t ScaleVal = Lexer.getCurIntVal();\n if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8)\n return TokError(\"scale factor in address must be 1, 2, 4 or 8\");\n Lexer.Lex(); \/\/ eat the scale.\n Scale = (unsigned)ScaleVal;\n }\n }\n }\n \n \/\/ Ok, we've eaten the memory operand, verify we have a ')' and eat it too.\n if (Lexer.isNot(asmtok::RParen))\n return TokError(\"unexpected token in memory operand\");\n Lexer.Lex(); \/\/ Eat the ')'.\n \n Op = X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale);\n return false;\n}\n\n\/\/\/ MatchX86Inst - Convert a parsed instruction name and operand list into a\n\/\/\/ concrete instruction.\nstatic bool MatchX86Inst(const char *Name, \n llvm::SmallVector &Operands,\n MCInst &Inst) {\n return false;\n}\n\n\/\/\/ ParseX86InstOperands - Parse the operands of an X86 instruction and return\n\/\/\/ them as the operands of an MCInst.\nbool AsmParser::ParseX86InstOperands(const char *InstName, MCInst &Inst) {\n llvm::SmallVector Operands;\n\n if (Lexer.isNot(asmtok::EndOfStatement)) {\n \/\/ Read the first operand.\n Operands.push_back(X86Operand());\n if (ParseX86Operand(Operands.back()))\n return true;\n \n while (Lexer.is(asmtok::Comma)) {\n Lexer.Lex(); \/\/ Eat the comma.\n \n \/\/ Parse and remember the operand.\n Operands.push_back(X86Operand());\n if (ParseX86Operand(Operands.back()))\n return true;\n }\n }\n\n return MatchX86Inst(InstName, Operands, Inst);\n}\nllvm-mc\/x86: Fix various nit-picky bugs in displacement parsing. - Test case to follow.\/\/===- MC-X86Specific.cpp - X86-Specific code for MC ----------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements X86-specific parsing, encoding and decoding stuff for\n\/\/ MC.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AsmParser.h\"\n#include \"llvm\/MC\/MCInst.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\nusing namespace llvm;\n\n\/\/\/ X86Operand - Instances of this class represent one X86 machine instruction.\nstruct AsmParser::X86Operand {\n enum {\n Register,\n Immediate,\n Memory\n } Kind;\n \n union {\n struct {\n unsigned RegNo;\n } Reg;\n\n struct {\n MCValue Val;\n } Imm;\n \n struct {\n unsigned SegReg;\n MCValue Disp;\n unsigned BaseReg;\n unsigned IndexReg;\n unsigned Scale;\n } Mem;\n };\n \n unsigned getReg() const {\n assert(Kind == Register && \"Invalid access!\");\n return Reg.RegNo;\n }\n\n static X86Operand CreateReg(unsigned RegNo) {\n X86Operand Res;\n Res.Kind = Register;\n Res.Reg.RegNo = RegNo;\n return Res;\n }\n static X86Operand CreateImm(MCValue Val) {\n X86Operand Res;\n Res.Kind = Immediate;\n Res.Imm.Val = Val;\n return Res;\n }\n static X86Operand CreateMem(unsigned SegReg, MCValue Disp, unsigned BaseReg,\n unsigned IndexReg, unsigned Scale) {\n \/\/ If there is no index register, we should never have a scale, and we\n \/\/ should always have a scale (in {1,2,4,8}) if we do.\n assert(((Scale == 0 && !IndexReg) ||\n (IndexReg && (Scale == 1 || Scale == 2 || \n Scale == 4 || Scale == 8))) &&\n \"Invalid scale!\");\n X86Operand Res;\n Res.Kind = Memory;\n Res.Mem.SegReg = SegReg;\n Res.Mem.Disp = Disp;\n Res.Mem.BaseReg = BaseReg;\n Res.Mem.IndexReg = IndexReg;\n Res.Mem.Scale = Scale;\n return Res;\n }\n};\n\nbool AsmParser::ParseX86Register(X86Operand &Op) {\n assert(Lexer.getKind() == asmtok::Register && \"Invalid token kind!\");\n\n \/\/ FIXME: Decode register number.\n Op = X86Operand::CreateReg(123);\n Lexer.Lex(); \/\/ Eat register token.\n\n return false;\n}\n\nbool AsmParser::ParseX86Operand(X86Operand &Op) {\n switch (Lexer.getKind()) {\n default:\n return ParseX86MemOperand(Op);\n case asmtok::Register:\n \/\/ FIXME: if a segment register, this could either be just the seg reg, or\n \/\/ the start of a memory operand.\n return ParseX86Register(Op);\n case asmtok::Dollar: {\n \/\/ $42 -> immediate.\n Lexer.Lex();\n MCValue Val;\n if (ParseRelocatableExpression(Val))\n return true;\n Op = X86Operand::CreateImm(Val);\n return false;\n }\n case asmtok::Star: {\n Lexer.Lex(); \/\/ Eat the star.\n \n if (Lexer.is(asmtok::Register)) {\n if (ParseX86Register(Op))\n return true;\n } else if (ParseX86MemOperand(Op))\n return true;\n\n \/\/ FIXME: Note the '*' in the operand for use by the matcher.\n return false;\n }\n }\n}\n\n\/\/\/ ParseX86MemOperand: segment: disp(basereg, indexreg, scale)\nbool AsmParser::ParseX86MemOperand(X86Operand &Op) {\n \/\/ FIXME: If SegReg ':' (e.g. %gs:), eat and remember.\n unsigned SegReg = 0;\n \n \/\/ We have to disambiguate a parenthesized expression \"(4+5)\" from the start\n \/\/ of a memory operand with a missing displacement \"(%ebx)\" or \"(,%eax)\". The\n \/\/ only way to do this without lookahead is to eat the ( and see what is after\n \/\/ it.\n MCValue Disp = MCValue::get(0, 0, 0);\n if (Lexer.isNot(asmtok::LParen)) {\n if (ParseRelocatableExpression(Disp)) return true;\n \n \/\/ After parsing the base expression we could either have a parenthesized\n \/\/ memory address or not. If not, return now. If so, eat the (.\n if (Lexer.isNot(asmtok::LParen)) {\n Op = X86Operand::CreateMem(SegReg, Disp, 0, 0, 0);\n return false;\n }\n \n \/\/ Eat the '('.\n Lexer.Lex();\n } else {\n \/\/ Okay, we have a '('. We don't know if this is an expression or not, but\n \/\/ so we have to eat the ( to see beyond it.\n Lexer.Lex(); \/\/ Eat the '('.\n \n if (Lexer.is(asmtok::Register) || Lexer.is(asmtok::Comma)) {\n \/\/ Nothing to do here, fall into the code below with the '(' part of the\n \/\/ memory operand consumed.\n } else {\n \/\/ It must be an parenthesized expression, parse it now.\n if (ParseParenRelocatableExpression(Disp))\n return true;\n \n \/\/ After parsing the base expression we could either have a parenthesized\n \/\/ memory address or not. If not, return now. If so, eat the (.\n if (Lexer.isNot(asmtok::LParen)) {\n Op = X86Operand::CreateMem(SegReg, Disp, 0, 0, 0);\n return false;\n }\n \n \/\/ Eat the '('.\n Lexer.Lex();\n }\n }\n \n \/\/ If we reached here, then we just ate the ( of the memory operand. Process\n \/\/ the rest of the memory operand.\n unsigned BaseReg = 0, IndexReg = 0, Scale = 0;\n \n if (Lexer.is(asmtok::Register)) {\n if (ParseX86Register(Op))\n return true;\n BaseReg = Op.getReg();\n }\n \n if (Lexer.is(asmtok::Comma)) {\n Lexer.Lex(); \/\/ Eat the comma.\n\n \/\/ Following the comma we should have either an index register, or a scale\n \/\/ value. We don't support the later form, but we want to parse it\n \/\/ correctly.\n \/\/\n \/\/ Not that even though it would be completely consistent to support syntax\n \/\/ like \"1(%eax,,1)\", the assembler doesn't.\n if (Lexer.is(asmtok::Register)) {\n if (ParseX86Register(Op))\n return true;\n IndexReg = Op.getReg();\n Scale = 1; \/\/ If not specified, the scale defaults to 1.\n \n if (Lexer.isNot(asmtok::RParen)) {\n \/\/ Parse the scale amount:\n \/\/ ::= ',' [scale-expression]\n if (Lexer.isNot(asmtok::Comma))\n return true;\n Lexer.Lex(); \/\/ Eat the comma.\n\n if (Lexer.isNot(asmtok::RParen)) {\n int64_t ScaleVal;\n if (ParseAbsoluteExpression(ScaleVal))\n return true;\n \n \/\/ Validate the scale amount.\n if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8)\n return TokError(\"scale factor in address must be 1, 2, 4 or 8\");\n Scale = (unsigned)ScaleVal;\n }\n }\n } else if (Lexer.isNot(asmtok::RParen)) {\n \/\/ Otherwise we have the unsupported form of a scale amount without an\n \/\/ index.\n SMLoc Loc = Lexer.getLoc();\n\n int64_t Value;\n if (ParseAbsoluteExpression(Value))\n return true;\n \n return Error(Loc, \"cannot have scale factor without index register\");\n }\n }\n \n \/\/ Ok, we've eaten the memory operand, verify we have a ')' and eat it too.\n if (Lexer.isNot(asmtok::RParen))\n return TokError(\"unexpected token in memory operand\");\n Lexer.Lex(); \/\/ Eat the ')'.\n \n Op = X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale);\n return false;\n}\n\n\/\/\/ MatchX86Inst - Convert a parsed instruction name and operand list into a\n\/\/\/ concrete instruction.\nstatic bool MatchX86Inst(const char *Name, \n llvm::SmallVector &Operands,\n MCInst &Inst) {\n return false;\n}\n\n\/\/\/ ParseX86InstOperands - Parse the operands of an X86 instruction and return\n\/\/\/ them as the operands of an MCInst.\nbool AsmParser::ParseX86InstOperands(const char *InstName, MCInst &Inst) {\n llvm::SmallVector Operands;\n\n if (Lexer.isNot(asmtok::EndOfStatement)) {\n \/\/ Read the first operand.\n Operands.push_back(X86Operand());\n if (ParseX86Operand(Operands.back()))\n return true;\n \n while (Lexer.is(asmtok::Comma)) {\n Lexer.Lex(); \/\/ Eat the comma.\n \n \/\/ Parse and remember the operand.\n Operands.push_back(X86Operand());\n if (ParseX86Operand(Operands.back()))\n return true;\n }\n }\n\n return MatchX86Inst(InstName, Operands, Inst);\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \"sass_context_wrapper.h\"\n\nusing namespace v8;\nusing namespace std;\n\n\nvoid WorkOnContext(uv_work_t* req) {\n sass_context_wrapper* ctx_w = static_cast(req->data);\n if (ctx_w->ctx) {\n sass_context* ctx = static_cast(ctx_w->ctx);\n sass_compile(ctx);\n } else if (ctx_w->fctx) {\n sass_file_context* ctx = static_cast(ctx_w->fctx);\n sass_compile_file(ctx);\n }\n}\n\nvoid extractOptions(_NAN_METHOD_ARGS, void* cptr, sass_context_wrapper* ctx_w, bool isFile) {\n char *source;\n char* pathOrData;\n char* imagePath;\n int output_style;\n int source_comments;\n String::AsciiValue astr(args[0]);\n\n String::AsciiValue bstr(args[1]);\n imagePath = new char[strlen(*bstr)+1];\n strcpy(imagePath, *bstr);\n\n if (ctx_w) {\n \/\/ async (callback) style\n Local callback = Local::Cast(args[2]);\n Local errorCallback = Local::Cast(args[3]);\n if (isFile) {\n ctx_w->fctx = (sass_file_context*) cptr;\n } else {\n ctx_w->ctx = (sass_context*) cptr;\n }\n ctx_w->request.data = ctx_w;\n ctx_w->callback = new NanCallback(callback);\n ctx_w->errorCallback = new NanCallback(errorCallback);\n output_style = args[5]->Int32Value();\n source_comments = args[6]->Int32Value();\n String::AsciiValue cstr(args[4]);\n pathOrData = new char[strlen(*cstr)+1];\n strcpy(pathOrData, *cstr);\n } else {\n \/\/ synchronous style\n output_style = args[3]->Int32Value();\n source_comments = args[4]->Int32Value();\n String::AsciiValue cstr(args[2]);\n pathOrData = new char[strlen(*cstr)+1];\n strcpy(pathOrData, *cstr);\n }\n\n if (isFile) {\n sass_file_context *ctx = (sass_file_context*)cptr;\n char *filename = new char[strlen(*astr)+1];\n strcpy(filename, *astr);\n ctx->input_path = filename;\n ctx->options.image_path = imagePath;\n ctx->options.output_style = output_style;\n ctx->options.source_comments = source_comments;\n ctx->options.include_paths = pathOrData;\n if (source_comments == SASS_SOURCE_COMMENTS_MAP) {\n String::AsciiValue dstr(args[7]);\n ctx->source_map_file = new char[strlen(*dstr)+1];\n strcpy(ctx->source_map_file, *dstr);\n }\n } else {\n sass_context *ctx = (sass_context*)cptr;\n source = new char[strlen(*astr)+1];\n strcpy(source, *astr);\n ctx->source_string = source;\n ctx->options.image_path = imagePath;\n ctx->options.output_style = output_style;\n ctx->options.source_comments = source_comments;\n ctx->options.include_paths = pathOrData;\n }\n}\n\nvoid MakeCallback(uv_work_t* req) {\n NanScope();\n TryCatch try_catch;\n sass_context_wrapper* ctx_w = static_cast(req->data);\n Handle val, err;\n const unsigned argc = 2;\n int error_status = ctx_w->ctx ? ctx_w->ctx->error_status : ctx_w->fctx->error_status;\n\n if (error_status == 0) {\n \/\/ if no error, do callback(null, result)\n Handle source_map;\n if (ctx_w->fctx && ctx_w->fctx->options.source_comments == SASS_SOURCE_COMMENTS_MAP) {\n source_map = String::New(ctx_w->fctx->source_map_string);\n } else {\n source_map = Null();\n }\n\n val = ctx_w->ctx ? NanNewLocal(String::New(ctx_w->ctx->output_string)) : NanNewLocal(String::New(ctx_w->fctx->output_string));\n Local argv[argc] = {\n NanNewLocal(val),\n NanNewLocal(source_map),\n };\n ctx_w->callback->Call(argc, argv);\n } else {\n \/\/ if error, do callback(error)\n err = ctx_w->ctx ? NanNewLocal(String::New(ctx_w->ctx->error_message)) : NanNewLocal(String::New(ctx_w->fctx->error_message));\n Local argv[argc] = {\n NanNewLocal(err),\n NanNewLocal(Integer::New(error_status))\n };\n ctx_w->errorCallback->Call(argc, argv);\n }\n if (try_catch.HasCaught()) {\n node::FatalException(try_catch);\n }\n if (ctx_w->ctx) {\n delete ctx_w->ctx->source_string;\n } else {\n delete ctx_w->fctx->input_path;\n }\n sass_free_context_wrapper(ctx_w);\n}\n\nNAN_METHOD(Render) {\n NanScope();\n sass_context* ctx = sass_new_context();\n sass_context_wrapper* ctx_w = sass_new_context_wrapper();\n ctx_w->ctx = ctx;\n extractOptions(args, ctx, ctx_w, false);\n\n int status = uv_queue_work(uv_default_loop(), &ctx_w->request, WorkOnContext, (uv_after_work_cb)MakeCallback);\n assert(status == 0);\n\n NanReturnUndefined();\n}\n\nNAN_METHOD(RenderSync) {\n NanScope();\n sass_context* ctx = sass_new_context();\n extractOptions(args, ctx, NULL, false);\n\n sass_compile(ctx);\n\n delete ctx->source_string;\n ctx->source_string = NULL;\n delete ctx->options.include_paths;\n ctx->options.include_paths = NULL;\n\n if (ctx->error_status == 0) {\n Local output = NanNewLocal(String::New(ctx->output_string));\n sass_free_context(ctx);\n NanReturnValue(output);\n }\n\n Local error = String::New(ctx->error_message);\n\n sass_free_context(ctx);\n NanThrowError(error);\n NanReturnUndefined();\n}\n\nNAN_METHOD(RenderFile) {\n NanScope();\n sass_file_context* fctx = sass_new_file_context();\n sass_context_wrapper* ctx_w = sass_new_context_wrapper();\n ctx_w->fctx = fctx;\n extractOptions(args, fctx, ctx_w, true);\n\n int status = uv_queue_work(uv_default_loop(), &ctx_w->request, WorkOnContext, (uv_after_work_cb)MakeCallback);\n assert(status == 0);\n\n NanReturnUndefined();\n}\n\nNAN_METHOD(RenderFileSync) {\n NanScope();\n sass_file_context* ctx = sass_new_file_context();\n extractOptions(args, ctx, NULL, true);\n\n sass_compile_file(ctx);\n\n delete ctx->input_path;\n ctx->input_path = NULL;\n delete ctx->options.include_paths;\n ctx->options.include_paths = NULL;\n\n if (ctx->error_status == 0) {\n Local output = NanNewLocal(String::New(ctx->output_string));\n sass_free_file_context(ctx);\n\n NanReturnValue(output);\n }\n Local error = String::New(ctx->error_message);\n sass_free_file_context(ctx);\n\n NanThrowError(error);\n NanReturnUndefined();\n}\n\nvoid RegisterModule(v8::Handle target) {\n NODE_SET_METHOD(target, \"render\", Render);\n NODE_SET_METHOD(target, \"renderSync\", RenderSync);\n NODE_SET_METHOD(target, \"renderFile\", RenderFile);\n NODE_SET_METHOD(target, \"renderFileSync\", RenderFileSync);\n}\n\nNODE_MODULE(binding, RegisterModule);\nFixed a strcpy error in binding.cpp#include \n#include \n#include \n#include \n#include \n#include \"sass_context_wrapper.h\"\n\nusing namespace v8;\nusing namespace std;\n\n\nvoid WorkOnContext(uv_work_t* req) {\n sass_context_wrapper* ctx_w = static_cast(req->data);\n if (ctx_w->ctx) {\n sass_context* ctx = static_cast(ctx_w->ctx);\n sass_compile(ctx);\n } else if (ctx_w->fctx) {\n sass_file_context* ctx = static_cast(ctx_w->fctx);\n sass_compile_file(ctx);\n }\n}\n\nvoid extractOptions(_NAN_METHOD_ARGS, void* cptr, sass_context_wrapper* ctx_w, bool isFile) {\n char *source;\n char* pathOrData;\n char* imagePath;\n int output_style;\n int source_comments;\n String::AsciiValue astr(args[0]);\n\n String::AsciiValue bstr(args[1]);\n imagePath = new char[strlen(*bstr)+1];\n strcpy(imagePath, *bstr);\n\n if (ctx_w) {\n \/\/ async (callback) style\n Local callback = Local::Cast(args[2]);\n Local errorCallback = Local::Cast(args[3]);\n if (isFile) {\n ctx_w->fctx = (sass_file_context*) cptr;\n } else {\n ctx_w->ctx = (sass_context*) cptr;\n }\n ctx_w->request.data = ctx_w;\n ctx_w->callback = new NanCallback(callback);\n ctx_w->errorCallback = new NanCallback(errorCallback);\n output_style = args[5]->Int32Value();\n source_comments = args[6]->Int32Value();\n String::AsciiValue cstr(args[4]);\n pathOrData = new char[strlen(*cstr)+1];\n strcpy(pathOrData, *cstr);\n } else {\n \/\/ synchronous style\n output_style = args[3]->Int32Value();\n source_comments = args[4]->Int32Value();\n String::AsciiValue cstr(args[2]);\n pathOrData = new char[strlen(*cstr)+1];\n strcpy(pathOrData, *cstr);\n }\n\n if (isFile) {\n sass_file_context *ctx = (sass_file_context*)cptr;\n char *filename = new char[strlen(*astr)+1];\n strcpy(filename, *astr);\n ctx->input_path = filename;\n ctx->options.image_path = imagePath;\n ctx->options.output_style = output_style;\n ctx->options.source_comments = source_comments;\n ctx->options.include_paths = pathOrData;\n if (source_comments == SASS_SOURCE_COMMENTS_MAP) {\n String::AsciiValue dstr(args[7]);\n ctx->source_map_file = new char[strlen(*dstr)+1];\n ctx->source_map_file = *dstr;\n }\n } else {\n sass_context *ctx = (sass_context*)cptr;\n source = new char[strlen(*astr)+1];\n strcpy(source, *astr);\n ctx->source_string = source;\n ctx->options.image_path = imagePath;\n ctx->options.output_style = output_style;\n ctx->options.source_comments = source_comments;\n ctx->options.include_paths = pathOrData;\n }\n}\n\nvoid MakeCallback(uv_work_t* req) {\n NanScope();\n TryCatch try_catch;\n sass_context_wrapper* ctx_w = static_cast(req->data);\n Handle val, err;\n const unsigned argc = 2;\n int error_status = ctx_w->ctx ? ctx_w->ctx->error_status : ctx_w->fctx->error_status;\n\n if (error_status == 0) {\n \/\/ if no error, do callback(null, result)\n Handle source_map;\n if (ctx_w->fctx && ctx_w->fctx->options.source_comments == SASS_SOURCE_COMMENTS_MAP) {\n source_map = String::New(ctx_w->fctx->source_map_string);\n } else {\n source_map = Null();\n }\n\n val = ctx_w->ctx ? NanNewLocal(String::New(ctx_w->ctx->output_string)) : NanNewLocal(String::New(ctx_w->fctx->output_string));\n Local argv[argc] = {\n NanNewLocal(val),\n NanNewLocal(source_map),\n };\n ctx_w->callback->Call(argc, argv);\n } else {\n \/\/ if error, do callback(error)\n err = ctx_w->ctx ? NanNewLocal(String::New(ctx_w->ctx->error_message)) : NanNewLocal(String::New(ctx_w->fctx->error_message));\n Local argv[argc] = {\n NanNewLocal(err),\n NanNewLocal(Integer::New(error_status))\n };\n ctx_w->errorCallback->Call(argc, argv);\n }\n if (try_catch.HasCaught()) {\n node::FatalException(try_catch);\n }\n if (ctx_w->ctx) {\n delete ctx_w->ctx->source_string;\n } else {\n delete ctx_w->fctx->input_path;\n }\n sass_free_context_wrapper(ctx_w);\n}\n\nNAN_METHOD(Render) {\n NanScope();\n sass_context* ctx = sass_new_context();\n sass_context_wrapper* ctx_w = sass_new_context_wrapper();\n ctx_w->ctx = ctx;\n extractOptions(args, ctx, ctx_w, false);\n\n int status = uv_queue_work(uv_default_loop(), &ctx_w->request, WorkOnContext, (uv_after_work_cb)MakeCallback);\n assert(status == 0);\n\n NanReturnUndefined();\n}\n\nNAN_METHOD(RenderSync) {\n NanScope();\n sass_context* ctx = sass_new_context();\n extractOptions(args, ctx, NULL, false);\n\n sass_compile(ctx);\n\n delete ctx->source_string;\n ctx->source_string = NULL;\n delete ctx->options.include_paths;\n ctx->options.include_paths = NULL;\n\n if (ctx->error_status == 0) {\n Local output = NanNewLocal(String::New(ctx->output_string));\n sass_free_context(ctx);\n NanReturnValue(output);\n }\n\n Local error = String::New(ctx->error_message);\n\n sass_free_context(ctx);\n NanThrowError(error);\n NanReturnUndefined();\n}\n\nNAN_METHOD(RenderFile) {\n NanScope();\n sass_file_context* fctx = sass_new_file_context();\n sass_context_wrapper* ctx_w = sass_new_context_wrapper();\n ctx_w->fctx = fctx;\n extractOptions(args, fctx, ctx_w, true);\n\n int status = uv_queue_work(uv_default_loop(), &ctx_w->request, WorkOnContext, (uv_after_work_cb)MakeCallback);\n assert(status == 0);\n\n NanReturnUndefined();\n}\n\nNAN_METHOD(RenderFileSync) {\n NanScope();\n sass_file_context* ctx = sass_new_file_context();\n extractOptions(args, ctx, NULL, true);\n\n sass_compile_file(ctx);\n\n delete ctx->input_path;\n ctx->input_path = NULL;\n delete ctx->options.include_paths;\n ctx->options.include_paths = NULL;\n\n if (ctx->error_status == 0) {\n Local output = NanNewLocal(String::New(ctx->output_string));\n sass_free_file_context(ctx);\n\n NanReturnValue(output);\n }\n Local error = String::New(ctx->error_message);\n sass_free_file_context(ctx);\n\n NanThrowError(error);\n NanReturnUndefined();\n}\n\nvoid RegisterModule(v8::Handle target) {\n NODE_SET_METHOD(target, \"render\", Render);\n NODE_SET_METHOD(target, \"renderSync\", RenderSync);\n NODE_SET_METHOD(target, \"renderFile\", RenderFile);\n NODE_SET_METHOD(target, \"renderFileSync\", RenderFileSync);\n}\n\nNODE_MODULE(binding, RegisterModule);\n<|endoftext|>"} {"text":"\/\/ Copyright 2018 The NXT Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"backend\/vulkan\/RenderPassVk.h\"\n\n#include \"backend\/vulkan\/FencedDeleter.h\"\n#include \"backend\/vulkan\/TextureVk.h\"\n#include \"backend\/vulkan\/VulkanBackend.h\"\n\nnamespace backend { namespace vulkan {\n\n namespace {\n VkAttachmentLoadOp VulkanAttachmentLoadOp(nxt::LoadOp op) {\n switch (op) {\n case nxt::LoadOp::Load:\n return VK_ATTACHMENT_LOAD_OP_LOAD;\n case nxt::LoadOp::Clear:\n return VK_ATTACHMENT_LOAD_OP_CLEAR;\n default:\n UNREACHABLE();\n }\n }\n } \/\/ anonymous namespace\n\n RenderPass::RenderPass(RenderPassBuilder* builder)\n : RenderPassBase(builder), mDevice(ToBackend(builder->GetDevice())) {\n \/\/ For now we only support single pass render passes.\n ASSERT(GetSubpassCount() == 1);\n ASSERT(GetAttachmentCount() <= kMaxColorAttachments + 1);\n\n const auto& subpass = GetSubpassInfo(0);\n\n \/\/ The Vulkan subpasses want to know the layout of the attachments with VkAttachmentRef.\n \/\/ Precompute them as they must be pointer-chained in VkSubpassDescription\n std::array attachmentRefs;\n attachmentRefs.fill(VkAttachmentReference{VK_ATTACHMENT_UNUSED, VK_IMAGE_LAYOUT_UNDEFINED});\n\n for (uint32_t i : IterateBitSet(subpass.colorAttachmentsSet)) {\n attachmentRefs[i].attachment = subpass.colorAttachments[i];\n attachmentRefs[i].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n }\n if (subpass.depthStencilAttachment) {\n attachmentRefs[kMaxColorAttachments].attachment = subpass.depthStencilAttachment;\n attachmentRefs[kMaxColorAttachments].layout =\n VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;\n }\n\n \/\/ Create the VkSubpassDescription that will be chained in the VkRenderPassCreateInfo\n VkSubpassDescription subpassDesc;\n subpassDesc.flags = 0;\n subpassDesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;\n subpassDesc.inputAttachmentCount = 0;\n subpassDesc.pInputAttachments = nullptr;\n subpassDesc.colorAttachmentCount = kMaxColorAttachments;\n subpassDesc.pColorAttachments = attachmentRefs.data();\n subpassDesc.pResolveAttachments = nullptr;\n subpassDesc.pDepthStencilAttachment = &attachmentRefs[kMaxColorAttachments];\n subpassDesc.preserveAttachmentCount = 0;\n subpassDesc.pPreserveAttachments = nullptr;\n\n \/\/ Create the VkAttachmentDescriptions that will be chained in the VkRenderPassCreateInfo\n std::array attachmentDescs = {};\n for (uint32_t i = 0; i < GetAttachmentCount(); ++i) {\n const auto& attachment = GetAttachmentInfo(i);\n auto& attachmentDesc = attachmentDescs[i];\n\n attachmentDesc.flags = 0;\n attachmentDesc.format = VulkanImageFormat(attachment.format);\n attachmentDesc.samples = VK_SAMPLE_COUNT_1_BIT;\n if (TextureFormatHasDepthOrStencil(attachment.format)) {\n attachmentDesc.loadOp = VulkanAttachmentLoadOp(attachment.depthLoadOp);\n attachmentDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;\n attachmentDesc.stencilLoadOp = VulkanAttachmentLoadOp(attachment.stencilLoadOp);\n attachmentDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;\n\n attachmentDesc.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;\n attachmentDesc.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;\n } else {\n attachmentDesc.loadOp = VulkanAttachmentLoadOp(attachment.colorLoadOp);\n attachmentDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;\n\n attachmentDesc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n attachmentDesc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n }\n }\n\n \/\/ Chain everything in VkRenderPassCreateInfo\n VkRenderPassCreateInfo createInfo;\n createInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;\n createInfo.pNext = nullptr;\n createInfo.flags = 0;\n createInfo.attachmentCount = GetAttachmentCount();\n createInfo.pAttachments = attachmentDescs.data();\n createInfo.subpassCount = 1;\n createInfo.pSubpasses = &subpassDesc;\n createInfo.dependencyCount = 0;\n createInfo.pDependencies = nullptr;\n\n \/\/ Create the render pass from the zillion parameters\n if (mDevice->fn.CreateRenderPass(mDevice->GetVkDevice(), &createInfo, nullptr, &mHandle) !=\n VK_SUCCESS) {\n ASSERT(false);\n }\n }\n\n RenderPass::~RenderPass() {\n if (mHandle != VK_NULL_HANDLE) {\n mDevice->GetFencedDeleter()->DeleteWhenUnused(mHandle);\n mHandle = VK_NULL_HANDLE;\n }\n }\n\n VkRenderPass RenderPass::GetHandle() const {\n return mHandle;\n }\n\n}} \/\/ namespace backend::vulkan\nRenderPassVk: Set the correct number of color attachments\/\/ Copyright 2018 The NXT Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"backend\/vulkan\/RenderPassVk.h\"\n\n#include \"backend\/vulkan\/FencedDeleter.h\"\n#include \"backend\/vulkan\/TextureVk.h\"\n#include \"backend\/vulkan\/VulkanBackend.h\"\n\nnamespace backend { namespace vulkan {\n\n namespace {\n VkAttachmentLoadOp VulkanAttachmentLoadOp(nxt::LoadOp op) {\n switch (op) {\n case nxt::LoadOp::Load:\n return VK_ATTACHMENT_LOAD_OP_LOAD;\n case nxt::LoadOp::Clear:\n return VK_ATTACHMENT_LOAD_OP_CLEAR;\n default:\n UNREACHABLE();\n }\n }\n } \/\/ anonymous namespace\n\n RenderPass::RenderPass(RenderPassBuilder* builder)\n : RenderPassBase(builder), mDevice(ToBackend(builder->GetDevice())) {\n \/\/ For now we only support single pass render passes.\n ASSERT(GetSubpassCount() == 1);\n ASSERT(GetAttachmentCount() <= kMaxColorAttachments + 1);\n\n const auto& subpass = GetSubpassInfo(0);\n\n \/\/ The Vulkan subpasses want to know the layout of the attachments with VkAttachmentRef.\n \/\/ Precompute them as they must be pointer-chained in VkSubpassDescription\n std::array attachmentRefs;\n attachmentRefs.fill(VkAttachmentReference{VK_ATTACHMENT_UNUSED, VK_IMAGE_LAYOUT_UNDEFINED});\n\n for (uint32_t i : IterateBitSet(subpass.colorAttachmentsSet)) {\n attachmentRefs[i].attachment = subpass.colorAttachments[i];\n attachmentRefs[i].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n\n \/\/ TODO(cwallez@chromium.org): need validation rule that attachments are packed\n ASSERT(i == 0 || subpass.colorAttachmentsSet[i - 1]);\n }\n if (subpass.depthStencilAttachment) {\n attachmentRefs[kMaxColorAttachments].attachment = subpass.depthStencilAttachment;\n attachmentRefs[kMaxColorAttachments].layout =\n VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;\n }\n\n \/\/ Create the VkSubpassDescription that will be chained in the VkRenderPassCreateInfo\n VkSubpassDescription subpassDesc;\n subpassDesc.flags = 0;\n subpassDesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;\n subpassDesc.inputAttachmentCount = 0;\n subpassDesc.pInputAttachments = nullptr;\n subpassDesc.colorAttachmentCount =\n static_cast(subpass.colorAttachmentsSet.count());\n subpassDesc.pColorAttachments = attachmentRefs.data();\n subpassDesc.pResolveAttachments = nullptr;\n subpassDesc.pDepthStencilAttachment = &attachmentRefs[kMaxColorAttachments];\n subpassDesc.preserveAttachmentCount = 0;\n subpassDesc.pPreserveAttachments = nullptr;\n\n \/\/ Create the VkAttachmentDescriptions that will be chained in the VkRenderPassCreateInfo\n std::array attachmentDescs = {};\n for (uint32_t i = 0; i < GetAttachmentCount(); ++i) {\n const auto& attachment = GetAttachmentInfo(i);\n auto& attachmentDesc = attachmentDescs[i];\n\n attachmentDesc.flags = 0;\n attachmentDesc.format = VulkanImageFormat(attachment.format);\n attachmentDesc.samples = VK_SAMPLE_COUNT_1_BIT;\n if (TextureFormatHasDepthOrStencil(attachment.format)) {\n attachmentDesc.loadOp = VulkanAttachmentLoadOp(attachment.depthLoadOp);\n attachmentDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;\n attachmentDesc.stencilLoadOp = VulkanAttachmentLoadOp(attachment.stencilLoadOp);\n attachmentDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;\n\n attachmentDesc.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;\n attachmentDesc.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;\n } else {\n attachmentDesc.loadOp = VulkanAttachmentLoadOp(attachment.colorLoadOp);\n attachmentDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;\n\n attachmentDesc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n attachmentDesc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\n }\n }\n\n \/\/ Chain everything in VkRenderPassCreateInfo\n VkRenderPassCreateInfo createInfo;\n createInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;\n createInfo.pNext = nullptr;\n createInfo.flags = 0;\n createInfo.attachmentCount = GetAttachmentCount();\n createInfo.pAttachments = attachmentDescs.data();\n createInfo.subpassCount = 1;\n createInfo.pSubpasses = &subpassDesc;\n createInfo.dependencyCount = 0;\n createInfo.pDependencies = nullptr;\n\n \/\/ Create the render pass from the zillion parameters\n if (mDevice->fn.CreateRenderPass(mDevice->GetVkDevice(), &createInfo, nullptr, &mHandle) !=\n VK_SUCCESS) {\n ASSERT(false);\n }\n }\n\n RenderPass::~RenderPass() {\n if (mHandle != VK_NULL_HANDLE) {\n mDevice->GetFencedDeleter()->DeleteWhenUnused(mHandle);\n mHandle = VK_NULL_HANDLE;\n }\n }\n\n VkRenderPass RenderPass::GetHandle() const {\n return mHandle;\n }\n\n}} \/\/ namespace backend::vulkan\n<|endoftext|>"} {"text":"\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2015 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n#include \"CppExportPlugin.h\"\n#include \"exporter\/CppExporter.h\"\n\n#include \"VisualizationBase\/src\/items\/Item.h\"\n#include \"SelfTest\/src\/TestManager.h\"\n#include \"Core\/src\/Profiler.h\"\n\nnamespace CppExport {\n\nbool CppExportPlugin::initialize(Core::EnvisionManager&)\n{\n\tInteraction::ActionRegistry::instance()->registerInputHandler(\"GenericHandler.TestCppExport\", testExport);\n\n\treturn true;\n}\n\nvoid CppExportPlugin::unload()\n{\n}\n\nvoid CppExportPlugin::selfTest(QString testid)\n{\n\tif (testid.isEmpty()) SelfTest::TestManager::runAllTests().printResultStatistics();\n\telse SelfTest::TestManager::runTest(testid).printResultStatistics();\n}\n\nbool CppExportPlugin::testExport(Visualization::Item *target, QKeySequence, Interaction::ActionRegistry::InputState)\n{\n\tauto n = target;\n\twhile (n && ! n->node()) n = n->parent();\n\n\tif (n)\n\t\tif (n->node())\n\t\t{\n\t\t\tCore::Profiler::start(true, \"Cpp Export\", \"cpp-export.prof\");\n\t\t\tCppExport::CppExporter::exportTree(n->node()->manager(), \"cpp_export\");\n\t\t\tCore::Profiler::stop(\"Cpp Export\");\n\t\t\treturn true;\n\t\t}\n\n\treturn false;\n}\n\n}\nChange the default output directory of cppexport\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2015 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n#include \"CppExportPlugin.h\"\n#include \"exporter\/CppExporter.h\"\n\n#include \"VisualizationBase\/src\/items\/Item.h\"\n#include \"SelfTest\/src\/TestManager.h\"\n#include \"Core\/src\/Profiler.h\"\n\nnamespace CppExport {\n\nbool CppExportPlugin::initialize(Core::EnvisionManager&)\n{\n\tInteraction::ActionRegistry::instance()->registerInputHandler(\"GenericHandler.TestCppExport\", testExport);\n\n\treturn true;\n}\n\nvoid CppExportPlugin::unload()\n{\n}\n\nvoid CppExportPlugin::selfTest(QString testid)\n{\n\tif (testid.isEmpty()) SelfTest::TestManager::runAllTests().printResultStatistics();\n\telse SelfTest::TestManager::runTest(testid).printResultStatistics();\n}\n\nbool CppExportPlugin::testExport(Visualization::Item *target, QKeySequence, Interaction::ActionRegistry::InputState)\n{\n\tauto n = target;\n\twhile (n && ! n->node()) n = n->parent();\n\n\tif (n)\n\t\tif (n->node())\n\t\t{\n\t\t\tCore::Profiler::start(true, \"Cpp Export\", \"cpp-export.prof\");\n\t\t\tCppExport::CppExporter::exportTree(n->node()->manager(), \"exported\");\n\t\t\tCore::Profiler::stop(\"Cpp Export\");\n\t\t\treturn true;\n\t\t}\n\n\treturn false;\n}\n\n}\n<|endoftext|>"} {"text":"#include \n#include \"Atm_command.h\"\n\t\nATM_CLASSNAME & ATM_CLASSNAME::begin( Stream * stream, char buffer[], int size )\n{\n const static state_t state_table[] PROGMEM = {\n \/* ON_ENTER ON_LOOP ON_EXIT EVT_INPUT EVT_OEL ELSE *\/\n \/* IDLE *\/ -1, -1, -1, READCHAR, -1, -1,\n \/* READCHAR *\/ ACT_READCHAR, -1, -1, READCHAR, SEND, -1,\n \/* SEND *\/ ACT_SEND, -1, -1, -1, -1, IDLE,\n };\n table( state_table, ELSE );\n _stream = stream;\n _buffer = buffer;\n _bufsize = size;\n _bufptr = 0;\n _sep = \" \";\n _eol = '\\n';\n _lastch = '\\0'; \n return *this; \n}\n\nATM_CLASSNAME & ATM_CLASSNAME::onCmd( void (*callback)( ATM_CLASSNAME * cmd ) ) \n{\n _callback = callback;\n return *this; \n}\n\nATM_CLASSNAME & ATM_CLASSNAME::separator( const char sep[] ) \n{\n _sep = sep;\n return *this; \n}\n\nchar * ATM_CLASSNAME::arg( int id ) {\n\n int cnt = 0;\n int i;\n if ( id == 0 ) return _buffer;\n for ( i = 0; i < _bufptr; i++ ) {\n if ( _buffer[i] == '\\0' ) {\n if ( ++cnt == id ) {\n i++;\n break;\n }\n }\n }\n return &_buffer[i];\n}\n\nint ATM_CLASSNAME::command( int id, const char * cmdlist ) {\n\n int cnt = 0;\n char * pamem = arg( id );\n char * pa = pamem;\n const char * pc = cmdlist;\n while ( pc[0] != '\\0' ) { \n while ( pc[0] != '\\0' && pc[0] == pa[0] ) {\n pc++;\n pa++;\n }\n if ( pa[0] == '\\0' ) \n return cnt;\n if ( pc[0] == ' ' ) \n cnt++;\n pa = pamem; \n pc++;\n }\n return -1;\n}\n\nint ATM_CLASSNAME::event( int id ) \n{\n switch ( id ) {\n case EVT_INPUT :\n return _stream->available(); \n case EVT_EOL :\n return _buffer[_bufptr-1] == _eol || _bufptr >= _bufsize; \n }\n return 0;\n}\n\nvoid ATM_CLASSNAME::action( int id ) \n{\n switch ( id ) {\n \tcase ACT_READCHAR :\n if ( _stream->available() ) {\n char ch = _stream->read();\n if ( strchr( _sep, ch ) == NULL ) {\n _buffer[_bufptr++] = ch; \n _lastch = ch;\n } else {\n if ( _lastch != '\\0' )\n _buffer[_bufptr++] = '\\0';\n _lastch = '\\0';\n }\n }\n return;\n case ACT_SEND :\n _buffer[--_bufptr] = '\\0';\n (*_callback)( this );\n _lastch = '\\0'; \n _bufptr = 0;\n \t return;\n }\n}\n\r\nFixed typo#include \n#include \"Atm_command.h\"\n\t\nATM_CLASSNAME & ATM_CLASSNAME::begin( Stream * stream, char buffer[], int size )\n{\n const static state_t state_table[] PROGMEM = {\n \/* ON_ENTER ON_LOOP ON_EXIT EVT_INPUT EVT_EOL ELSE *\/\n \/* IDLE *\/ -1, -1, -1, READCHAR, -1, -1,\n \/* READCHAR *\/ ACT_READCHAR, -1, -1, READCHAR, SEND, -1,\n \/* SEND *\/ ACT_SEND, -1, -1, -1, -1, IDLE,\n };\n table( state_table, ELSE );\n _stream = stream;\n _buffer = buffer;\n _bufsize = size;\n _bufptr = 0;\n _sep = \" \";\n _eol = '\\n';\n _lastch = '\\0'; \n return *this; \n}\n\nATM_CLASSNAME & ATM_CLASSNAME::onCmd( void (*callback)( ATM_CLASSNAME * cmd ) ) \n{\n _callback = callback;\n return *this; \n}\n\nATM_CLASSNAME & ATM_CLASSNAME::separator( const char sep[] ) \n{\n _sep = sep;\n return *this; \n}\n\nchar * ATM_CLASSNAME::arg( int id ) {\n\n int cnt = 0;\n int i;\n if ( id == 0 ) return _buffer;\n for ( i = 0; i < _bufptr; i++ ) {\n if ( _buffer[i] == '\\0' ) {\n if ( ++cnt == id ) {\n i++;\n break;\n }\n }\n }\n return &_buffer[i];\n}\n\nint ATM_CLASSNAME::command( int id, const char * cmdlist ) {\n\n int cnt = 0;\n char * pamem = arg( id );\n char * pa = pamem;\n const char * pc = cmdlist;\n while ( pc[0] != '\\0' ) { \n while ( pc[0] != '\\0' && pc[0] == pa[0] ) {\n pc++;\n pa++;\n }\n if ( pa[0] == '\\0' ) \n return cnt;\n if ( pc[0] == ' ' ) \n cnt++;\n pa = pamem; \n pc++;\n }\n return -1;\n}\n\nint ATM_CLASSNAME::event( int id ) \n{\n switch ( id ) {\n case EVT_INPUT :\n return _stream->available(); \n case EVT_EOL :\n return _buffer[_bufptr-1] == _eol || _bufptr >= _bufsize; \n }\n return 0;\n}\n\nvoid ATM_CLASSNAME::action( int id ) \n{\n switch ( id ) {\n \tcase ACT_READCHAR :\n if ( _stream->available() ) {\n char ch = _stream->read();\n if ( strchr( _sep, ch ) == NULL ) {\n _buffer[_bufptr++] = ch; \n _lastch = ch;\n } else {\n if ( _lastch != '\\0' )\n _buffer[_bufptr++] = '\\0';\n _lastch = '\\0';\n }\n }\n return;\n case ACT_SEND :\n _buffer[--_bufptr] = '\\0';\n (*_callback)( this );\n _lastch = '\\0'; \n _bufptr = 0;\n \t return;\n }\n}\n\r\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"blackhole\/detail\/stream\/stream.hpp\"\n#include \"blackhole\/utils\/underlying.hpp\"\n\nnamespace blackhole {\n\nnamespace defaults {\n\nenum class severity {\n debug,\n notice,\n info,\n warning,\n error\n};\n\nvoid\nmap_severity(aux::attachable_ostringstream& stream, const severity& level) {\n static const char* describe[] = {\n \"DEBUG\",\n \"NOTICE\",\n \"INFO\",\n \"WARNING\",\n \"ERROR\"\n };\n\n typedef blackhole::aux::underlying_type::type level_type;\n\n auto value = static_cast(level);\n if(value < static_cast(sizeof(describe) \/ sizeof(describe[0])) && value > 0) {\n stream << describe[value];\n } else {\n stream << value;\n }\n}\n\n} \/\/ namespace defaults\n\n} \/\/ namespace blackhole\n[Bug Fix] Fix linker error.#pragma once\n\n#include \"blackhole\/detail\/stream\/stream.hpp\"\n#include \"blackhole\/utils\/underlying.hpp\"\n\nnamespace blackhole {\n\nnamespace defaults {\n\nenum class severity {\n debug,\n notice,\n info,\n warning,\n error\n};\n\ninline\nvoid\nmap_severity(aux::attachable_ostringstream& stream, const severity& level) {\n static const char* describe[] = {\n \"DEBUG\",\n \"NOTICE\",\n \"INFO\",\n \"WARNING\",\n \"ERROR\"\n };\n\n typedef blackhole::aux::underlying_type::type level_type;\n\n auto value = static_cast(level);\n if(value < static_cast(sizeof(describe) \/ sizeof(describe[0])) && value > 0) {\n stream << describe[value];\n } else {\n stream << value;\n }\n}\n\n} \/\/ namespace defaults\n\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"\/**\n * Copyright (C) 2015 Topology LP\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace bonefish {\n\nwamp_broker::wamp_broker(const std::string& realm)\n : m_realm(realm)\n , m_publication_id_generator()\n , m_subscription_id_generator()\n , m_sessions()\n , m_session_subscriptions()\n , m_topic_subscriptions()\n , m_subscription_topics()\n{\n}\n\nwamp_broker::~wamp_broker()\n{\n}\n\nvoid wamp_broker::attach_session(const std::shared_ptr& session)\n{\n BONEFISH_TRACE(\"attach session: %1%\", *session);\n auto result = m_sessions.insert(\n std::make_pair(session->get_session_id(), std::move(session)));\n if (!result.second) {\n throw std::logic_error(\"broker session already registered\");\n }\n}\n\nvoid wamp_broker::detach_session(const wamp_session_id& session_id)\n{\n auto session_itr = m_sessions.find(session_id);\n if (session_itr == m_sessions.end()) {\n throw std::logic_error(\"broker session does not exist\");\n }\n\n BONEFISH_TRACE(\"detach session: %1%\", session_itr->second.get());\n auto session_subscriptions_itr = m_session_subscriptions.find(session_id);\n if (session_subscriptions_itr != m_session_subscriptions.end()) {\n BONEFISH_TRACE(\"cleaning up session subscriptions\");\n for (const auto& subscription_id : session_subscriptions_itr->second) {\n auto subscription_topics_itr = m_subscription_topics.find(subscription_id);\n if (subscription_topics_itr == m_subscription_topics.end()) {\n BONEFISH_TRACE(\"error: broker subscription topics are out of sync\");\n continue;\n }\n\n std::string topic = subscription_topics_itr->second->get_topic();\n BONEFISH_TRACE(\"cleaning up subscription topic\");\n subscription_topics_itr->second->remove_session(session_itr->second);\n if (subscription_topics_itr->second->get_sessions().size() == 0) {\n m_subscription_topics.erase(subscription_id);\n }\n\n auto topic_subscriptions_itr = m_topic_subscriptions.find(topic);\n if (topic_subscriptions_itr == m_topic_subscriptions.end()) {\n BONEFISH_TRACE(\"error: broker topic subscriptions are out of sync\");\n continue;\n }\n\n BONEFISH_TRACE(\"cleaning up topic subscriptions\");\n topic_subscriptions_itr->second->remove_subscription(subscription_id);\n if (topic_subscriptions_itr->second->get_subscriptions().size() == 0) {\n m_topic_subscriptions.erase(topic);\n }\n }\n\n m_session_subscriptions.erase(session_subscriptions_itr);\n }\n\n m_sessions.erase(session_itr);\n}\n\nvoid wamp_broker::process_publish_message(const wamp_session_id& session_id,\n wamp_publish_message* publish_message)\n{\n auto session_itr = m_sessions.find(session_id);\n if (session_itr == m_sessions.end()) {\n throw std::logic_error(\"broker session does not exist\");\n }\n\n BONEFISH_TRACE(\"%1%, %2%\", *session_itr->second % *publish_message);\n const std::string topic = publish_message->get_topic();\n const wamp_publication_id publication_id = m_publication_id_generator.generate();\n\n \/\/ Since a publish message fans out to potentially numerous event messages\n \/\/ we cannot need to be a bit smarter with how we deal with passing zone\n \/\/ ownership. For all but the last subscription we make a deep copy of the\n \/\/ transient fields for the event messages. When we reach the last subscription\n \/\/ it is then safe to just pass ownership of the zone.\n auto topic_subscriptions_itr = m_topic_subscriptions.find(topic);\n if (topic_subscriptions_itr != m_topic_subscriptions.end()) {\n const auto& subscriptions = topic_subscriptions_itr->second->get_subscriptions();\n std::size_t num_subscriptions = subscriptions.size();\n std::size_t current_subscription = 0;\n\n for (const auto& subscription : subscriptions) {\n const auto& subscription_id = subscription.first;\n const auto& session = subscription.second;\n\n std::unique_ptr event_message;\n if (++current_subscription < num_subscriptions) {\n event_message.reset(new wamp_event_message());\n event_message->set_subscription_id(subscription_id);\n event_message->set_publication_id(publication_id);\n event_message->set_arguments(\n msgpack::object(publish_message->get_arguments(), event_message->get_zone()));\n event_message->set_arguments_kw(\n msgpack::object(publish_message->get_arguments_kw(), event_message->get_zone()));\n } else {\n event_message.reset(new wamp_event_message(publish_message->release_zone()));\n event_message->set_subscription_id(subscription_id);\n event_message->set_publication_id(publication_id);\n event_message->set_arguments(publish_message->get_arguments());\n event_message->set_arguments_kw(publish_message->get_arguments_kw());\n }\n\n BONEFISH_TRACE(\"%1%, %2%\", *session % *event_message);\n session->get_transport()->send_message(std::move(*event_message));\n }\n }\n\n \/\/ TODO: Publish acknowledgements require support for publish options which\n \/\/ we currently do not yet have working.\n \/\/\n \/\/std::unique_ptr published_message(new wamp_published_message);\n \/\/published_message->set_request_id(publish_message->get_request_id());\n \/\/published_message->set_publication_id(publication_id);\n \/\/session_itr->second->get_transport()->send_message(published_message.get());\n}\n\nvoid wamp_broker::process_subscribe_message(const wamp_session_id& session_id,\n wamp_subscribe_message* subscribe_message)\n{\n auto session_itr = m_sessions.find(session_id);\n if (session_itr == m_sessions.end()) {\n throw std::logic_error(\"broker session does not exist\");\n }\n\n BONEFISH_TRACE(\"%1%, %2%\", *session_itr->second % *subscribe_message);\n wamp_subscription_id subscription_id = m_subscription_id_generator.generate();\n auto& session = session_itr->second;\n {\n auto result = m_topic_subscriptions.insert(\n std::make_pair(subscribe_message->get_topic(), nullptr));\n\n if (result.second) {\n result.first->second.reset(new wamp_broker_subscriptions());\n }\n result.first->second->add_subscription(subscription_id, session);\n }\n\n {\n auto result = m_subscription_topics.insert(std::make_pair(subscription_id, nullptr));\n if (result.second) {\n result.first->second.reset(new wamp_broker_topic(subscribe_message->get_topic()));\n result.first->second->add_session(session);\n } else {\n result.first->second->add_session(session);\n }\n }\n\n m_session_subscriptions[session_id].insert(subscription_id);\n\n std::unique_ptr subscribed_message(\n new wamp_subscribed_message(subscribe_message->release_zone()));\n subscribed_message->set_request_id(subscribe_message->get_request_id());\n subscribed_message->set_subscription_id(subscription_id);\n\n BONEFISH_TRACE(\"%1%, %2%\", *session % *subscribed_message);\n session->get_transport()->send_message(std::move(*subscribed_message));\n}\n\nvoid wamp_broker::process_unsubscribe_message(const wamp_session_id& session_id,\n wamp_unsubscribe_message* unsubscribe_message)\n{\n auto session_itr = m_sessions.find(session_id);\n if (session_itr == m_sessions.end()) {\n throw std::logic_error(\"broker session does not exist\");\n }\n\n BONEFISH_TRACE(\"%1%, %2%\", *session_itr->second % *unsubscribe_message);\n auto session_subscriptions_itr = m_session_subscriptions.find(session_id);\n if (session_subscriptions_itr == m_session_subscriptions.end()) {\n send_error(session_itr->second->get_transport(), unsubscribe_message->get_type(),\n unsubscribe_message->get_request_id(), std::string(\"wamp.error.no_subscriptions_for_session\"));\n return;\n }\n\n const wamp_subscription_id& subscription_id = unsubscribe_message->get_subscription_id();\n if (session_subscriptions_itr->second.erase(subscription_id) == 0) {\n send_error(session_itr->second->get_transport(), unsubscribe_message->get_type(),\n unsubscribe_message->get_request_id(), std::string(\"wamp.error.no_such_subscription\"));\n return;\n }\n\n auto subscription_topics_itr = m_subscription_topics.find(subscription_id);\n if (subscription_topics_itr == m_subscription_topics.end()) {\n BONEFISH_TRACE(\"error: broker subscription topics are out of sync\");\n } else {\n std::string topic = subscription_topics_itr->second->get_topic();\n subscription_topics_itr->second->remove_session(session_itr->second);\n if (subscription_topics_itr->second->get_sessions().size() == 0) {\n m_subscription_topics.erase(subscription_id);\n }\n\n auto topic_subscriptions_itr = m_topic_subscriptions.find(topic);\n if (topic_subscriptions_itr == m_topic_subscriptions.end()) {\n BONEFISH_TRACE(\"error: broker topic subscription out of sync\");\n } else {\n topic_subscriptions_itr->second->remove_subscription(subscription_id);\n if (topic_subscriptions_itr->second->get_subscriptions().size() == 0) {\n m_topic_subscriptions.erase(topic);\n }\n }\n }\n\n std::unique_ptr unsubscribed_message(\n new wamp_unsubscribed_message(unsubscribe_message->release_zone()));\n unsubscribed_message->set_request_id(unsubscribe_message->get_request_id());\n\n BONEFISH_TRACE(\"%1%, %2%\", *session_itr->second % *unsubscribed_message);\n session_itr->second->get_transport()->send_message(std::move(*unsubscribed_message));\n}\n\nvoid wamp_broker::send_error(const std::unique_ptr& transport,\n const wamp_message_type request_type, const wamp_request_id& request_id,\n const std::string& error) const\n{\n std::unique_ptr error_message(new wamp_error_message);\n error_message->set_request_type(request_type);\n error_message->set_request_id(request_id);\n error_message->set_error(error);\n\n BONEFISH_TRACE(\"%1%\", *error_message);\n transport->send_message(std::move(*error_message));\n}\n\n} \/\/ namespace bonefish\nFix github issue #43\/**\n * Copyright (C) 2015 Topology LP\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace bonefish {\n\nwamp_broker::wamp_broker(const std::string& realm)\n : m_realm(realm)\n , m_publication_id_generator()\n , m_subscription_id_generator()\n , m_sessions()\n , m_session_subscriptions()\n , m_topic_subscriptions()\n , m_subscription_topics()\n{\n}\n\nwamp_broker::~wamp_broker()\n{\n}\n\nvoid wamp_broker::attach_session(const std::shared_ptr& session)\n{\n BONEFISH_TRACE(\"attach session: %1%\", *session);\n auto result = m_sessions.insert(\n std::make_pair(session->get_session_id(), std::move(session)));\n if (!result.second) {\n throw std::logic_error(\"broker session already registered\");\n }\n}\n\nvoid wamp_broker::detach_session(const wamp_session_id& session_id)\n{\n auto session_itr = m_sessions.find(session_id);\n if (session_itr == m_sessions.end()) {\n throw std::logic_error(\"broker session does not exist\");\n }\n\n BONEFISH_TRACE(\"detach session: %1%\", session_itr->second.get());\n auto session_subscriptions_itr = m_session_subscriptions.find(session_id);\n if (session_subscriptions_itr != m_session_subscriptions.end()) {\n BONEFISH_TRACE(\"cleaning up session subscriptions\");\n for (const auto& subscription_id : session_subscriptions_itr->second) {\n auto subscription_topics_itr = m_subscription_topics.find(subscription_id);\n if (subscription_topics_itr == m_subscription_topics.end()) {\n BONEFISH_TRACE(\"error: broker subscription topics are out of sync\");\n continue;\n }\n\n std::string topic = subscription_topics_itr->second->get_topic();\n BONEFISH_TRACE(\"cleaning up subscription topic\");\n subscription_topics_itr->second->remove_session(session_itr->second);\n if (subscription_topics_itr->second->get_sessions().size() == 0) {\n m_subscription_topics.erase(subscription_id);\n }\n\n auto topic_subscriptions_itr = m_topic_subscriptions.find(topic);\n if (topic_subscriptions_itr == m_topic_subscriptions.end()) {\n BONEFISH_TRACE(\"error: broker topic subscriptions are out of sync\");\n continue;\n }\n\n BONEFISH_TRACE(\"cleaning up topic subscriptions\");\n topic_subscriptions_itr->second->remove_subscription(subscription_id);\n if (topic_subscriptions_itr->second->get_subscriptions().size() == 0) {\n m_topic_subscriptions.erase(topic);\n }\n }\n\n m_session_subscriptions.erase(session_subscriptions_itr);\n }\n\n m_sessions.erase(session_itr);\n}\n\nvoid wamp_broker::process_publish_message(const wamp_session_id& session_id,\n wamp_publish_message* publish_message)\n{\n auto session_itr = m_sessions.find(session_id);\n if (session_itr == m_sessions.end()) {\n throw std::logic_error(\"broker session does not exist\");\n }\n\n BONEFISH_TRACE(\"%1%, %2%\", *session_itr->second % *publish_message);\n const std::string topic = publish_message->get_topic();\n const wamp_publication_id publication_id = m_publication_id_generator.generate();\n\n \/\/ Since a publish message fans out to potentially numerous event messages\n \/\/ we cannot need to be a bit smarter with how we deal with passing zone\n \/\/ ownership. For all but the last subscription we make a deep copy of the\n \/\/ transient fields for the event messages. When we reach the last subscription\n \/\/ it is then safe to just pass ownership of the zone.\n auto topic_subscriptions_itr = m_topic_subscriptions.find(topic);\n if (topic_subscriptions_itr != m_topic_subscriptions.end()) {\n \/\/ Fix github issue #43 = work on a COPY of member subscriptions to avoid iterator \n \/\/ invalidation should session->get_transport()->send_message() failure close & remove the session.\n const auto subscriptions = topic_subscriptions_itr->second->get_subscriptions();\n std::size_t num_subscriptions = subscriptions.size();\n std::size_t current_subscription = 0;\n\n for (const auto& subscription : subscriptions) {\n const auto& subscription_id = subscription.first;\n const auto& session = subscription.second;\n\n std::unique_ptr event_message;\n if (++current_subscription < num_subscriptions) {\n event_message.reset(new wamp_event_message());\n event_message->set_subscription_id(subscription_id);\n event_message->set_publication_id(publication_id);\n event_message->set_arguments(\n msgpack::object(publish_message->get_arguments(), event_message->get_zone()));\n event_message->set_arguments_kw(\n msgpack::object(publish_message->get_arguments_kw(), event_message->get_zone()));\n } else {\n event_message.reset(new wamp_event_message(publish_message->release_zone()));\n event_message->set_subscription_id(subscription_id);\n event_message->set_publication_id(publication_id);\n event_message->set_arguments(publish_message->get_arguments());\n event_message->set_arguments_kw(publish_message->get_arguments_kw());\n }\n\n BONEFISH_TRACE(\"%1%, %2%\", *session % *event_message);\n session->get_transport()->send_message(std::move(*event_message));\n }\n }\n\n \/\/ TODO: Publish acknowledgements require support for publish options which\n \/\/ we currently do not yet have working.\n \/\/\n \/\/std::unique_ptr published_message(new wamp_published_message);\n \/\/published_message->set_request_id(publish_message->get_request_id());\n \/\/published_message->set_publication_id(publication_id);\n \/\/session_itr->second->get_transport()->send_message(published_message.get());\n}\n\nvoid wamp_broker::process_subscribe_message(const wamp_session_id& session_id,\n wamp_subscribe_message* subscribe_message)\n{\n auto session_itr = m_sessions.find(session_id);\n if (session_itr == m_sessions.end()) {\n throw std::logic_error(\"broker session does not exist\");\n }\n\n BONEFISH_TRACE(\"%1%, %2%\", *session_itr->second % *subscribe_message);\n wamp_subscription_id subscription_id = m_subscription_id_generator.generate();\n auto& session = session_itr->second;\n {\n auto result = m_topic_subscriptions.insert(\n std::make_pair(subscribe_message->get_topic(), nullptr));\n\n if (result.second) {\n result.first->second.reset(new wamp_broker_subscriptions());\n }\n result.first->second->add_subscription(subscription_id, session);\n }\n\n {\n auto result = m_subscription_topics.insert(std::make_pair(subscription_id, nullptr));\n if (result.second) {\n result.first->second.reset(new wamp_broker_topic(subscribe_message->get_topic()));\n result.first->second->add_session(session);\n } else {\n result.first->second->add_session(session);\n }\n }\n\n m_session_subscriptions[session_id].insert(subscription_id);\n\n std::unique_ptr subscribed_message(\n new wamp_subscribed_message(subscribe_message->release_zone()));\n subscribed_message->set_request_id(subscribe_message->get_request_id());\n subscribed_message->set_subscription_id(subscription_id);\n\n BONEFISH_TRACE(\"%1%, %2%\", *session % *subscribed_message);\n session->get_transport()->send_message(std::move(*subscribed_message));\n}\n\nvoid wamp_broker::process_unsubscribe_message(const wamp_session_id& session_id,\n wamp_unsubscribe_message* unsubscribe_message)\n{\n auto session_itr = m_sessions.find(session_id);\n if (session_itr == m_sessions.end()) {\n throw std::logic_error(\"broker session does not exist\");\n }\n\n BONEFISH_TRACE(\"%1%, %2%\", *session_itr->second % *unsubscribe_message);\n auto session_subscriptions_itr = m_session_subscriptions.find(session_id);\n if (session_subscriptions_itr == m_session_subscriptions.end()) {\n send_error(session_itr->second->get_transport(), unsubscribe_message->get_type(),\n unsubscribe_message->get_request_id(), std::string(\"wamp.error.no_subscriptions_for_session\"));\n return;\n }\n\n const wamp_subscription_id& subscription_id = unsubscribe_message->get_subscription_id();\n if (session_subscriptions_itr->second.erase(subscription_id) == 0) {\n send_error(session_itr->second->get_transport(), unsubscribe_message->get_type(),\n unsubscribe_message->get_request_id(), std::string(\"wamp.error.no_such_subscription\"));\n return;\n }\n\n auto subscription_topics_itr = m_subscription_topics.find(subscription_id);\n if (subscription_topics_itr == m_subscription_topics.end()) {\n BONEFISH_TRACE(\"error: broker subscription topics are out of sync\");\n } else {\n std::string topic = subscription_topics_itr->second->get_topic();\n subscription_topics_itr->second->remove_session(session_itr->second);\n if (subscription_topics_itr->second->get_sessions().size() == 0) {\n m_subscription_topics.erase(subscription_id);\n }\n\n auto topic_subscriptions_itr = m_topic_subscriptions.find(topic);\n if (topic_subscriptions_itr == m_topic_subscriptions.end()) {\n BONEFISH_TRACE(\"error: broker topic subscription out of sync\");\n } else {\n topic_subscriptions_itr->second->remove_subscription(subscription_id);\n if (topic_subscriptions_itr->second->get_subscriptions().size() == 0) {\n m_topic_subscriptions.erase(topic);\n }\n }\n }\n\n std::unique_ptr unsubscribed_message(\n new wamp_unsubscribed_message(unsubscribe_message->release_zone()));\n unsubscribed_message->set_request_id(unsubscribe_message->get_request_id());\n\n BONEFISH_TRACE(\"%1%, %2%\", *session_itr->second % *unsubscribed_message);\n session_itr->second->get_transport()->send_message(std::move(*unsubscribed_message));\n}\n\nvoid wamp_broker::send_error(const std::unique_ptr& transport,\n const wamp_message_type request_type, const wamp_request_id& request_id,\n const std::string& error) const\n{\n std::unique_ptr error_message(new wamp_error_message);\n error_message->set_request_type(request_type);\n error_message->set_request_id(request_id);\n error_message->set_error(error);\n\n BONEFISH_TRACE(\"%1%\", *error_message);\n transport->send_message(std::move(*error_message));\n}\n\n} \/\/ namespace bonefish\n<|endoftext|>"} {"text":"Add an important reminder to the socket file.<|endoftext|>"} {"text":"\/*\n * DeleteLink.cc\n *\n * Copyright (C) 2015 Linas Vepstas\n *\n * Author: Linas Vepstas January 2009\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the\n * exceptions at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public\n * License along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"DeleteLink.h\"\n\nusing namespace opencog;\n\nvoid DeleteLink::init(void)\n{\n\t\/\/ The handleset must contain a variable in it, somewhere.\n\t\/\/ If it doesn't, then the entire handleset should be deleted\n\t\/\/ (removed from the atomspace). We can't do this at constructor\n\t\/\/ time, because we don't know the atomspace yet. So we hack\n\t\/\/ around this by throwing at constructor time.\n\t\/\/\n\tFreeLink::init();\n\tif (0 == _vars.varseq.size())\n\t\t\/\/ throw DeleteException();\n\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\"Cannot create a fully grounded DeleteLink!\");\n}\n\n#if 0\n\/*****\nWell, we cannot really implement this here; but this is what\nit should actually do. We can't implement it here, because\nfully-grounded DeleteLink's cannot exist.\n****\/\nHandle DeleteLink::execute(AtomSpace * as) const\n{\n\tconst HandleSeq& oset = _outgoing;\n\tfor (const Handle& h : oset)\n\t{\n\t\tType t = h->getType();\n\t\tif (VARIABLE_NODE != t)\n\t\t\tas->removeAtom(h, true);\n\t}\n\treturn Handle::UNDEFINED;\n}\n#endif\n\nDeleteLink::DeleteLink(const HandleSeq& oset,\n TruthValuePtr tv, AttentionValuePtr av)\n\t: FreeLink(DELETE_LINK, oset, tv, av)\n{\n\tinit();\n}\n\nDeleteLink::DeleteLink(Link &l)\n\t: FreeLink(l)\n{\n\t\/\/ Type must be as expected\n\tType tscope = l.getType();\n\tif (not classserver().isA(tscope, DELETE_LINK))\n\t{\n\t\tconst std::string& tname = classserver().getTypeName(tscope);\n\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\"Expecting a DeleteLink, got %s\", tname.c_str());\n\t}\n\n\tinit();\n}\n\n\/* ===================== END OF FILE ===================== *\/\nRemove un-needed includes\/*\n * DeleteLink.cc\n *\n * Copyright (C) 2015 Linas Vepstas\n *\n * Author: Linas Vepstas January 2009\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the\n * exceptions at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public\n * License along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \n#include \n\n#include \"DeleteLink.h\"\n\nusing namespace opencog;\n\nvoid DeleteLink::init(void)\n{\n\t\/\/ The handleset must contain a variable in it, somewhere.\n\t\/\/ If it doesn't, then the entire handleset should be deleted\n\t\/\/ (removed from the atomspace). We can't do this at constructor\n\t\/\/ time, because we don't know the atomspace yet. So we hack\n\t\/\/ around this by throwing at constructor time.\n\t\/\/\n\tFreeLink::init();\n\tif (0 == _vars.varseq.size())\n\t\t\/\/ throw DeleteException();\n\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\"Cannot create a fully grounded DeleteLink!\");\n}\n\n#if 0\n\/*****\nWell, we cannot really implement this here; but this is what\nit should actually do. We can't implement it here, because\nfully-grounded DeleteLink's cannot exist.\n****\/\nHandle DeleteLink::execute(AtomSpace * as) const\n{\n\tconst HandleSeq& oset = _outgoing;\n\tfor (const Handle& h : oset)\n\t{\n\t\tType t = h->getType();\n\t\tif (VARIABLE_NODE != t)\n\t\t\tas->removeAtom(h, true);\n\t}\n\treturn Handle::UNDEFINED;\n}\n#endif\n\nDeleteLink::DeleteLink(const HandleSeq& oset,\n TruthValuePtr tv, AttentionValuePtr av)\n\t: FreeLink(DELETE_LINK, oset, tv, av)\n{\n\tinit();\n}\n\nDeleteLink::DeleteLink(Link &l)\n\t: FreeLink(l)\n{\n\t\/\/ Type must be as expected\n\tType tscope = l.getType();\n\tif (not classserver().isA(tscope, DELETE_LINK))\n\t{\n\t\tconst std::string& tname = classserver().getTypeName(tscope);\n\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\"Expecting a DeleteLink, got %s\", tname.c_str());\n\t}\n\n\tinit();\n}\n\n\/* ===================== END OF FILE ===================== *\/\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \n\n#include \n\n\nClientUnix::ClientUnix(const std::string path)\n{\n\tInit();\n\tm_fd = -1;\n\tm_path = path;\n\tm_connected = false;\n}\n\nClientUnix::~ClientUnix()\n{\n\tDisconnect();\n}\n\nvoid ClientUnix::Connect()\n{\n\tm_quit = false;\n\tThread::Start();\n}\n\nbool ClientUnix::IsConnected()\n{\n\treturn m_connected;\n}\n\nvoid ClientUnix::Disconnect()\n{\n\tm_quit = true;\n\tScopedReadLock rlock(&m_WriterLock);\n\tif (m_fd >= 0)\n\t{\n\t\tif (shutdown(m_fd, SHUT_WR) < 0)\n\t\t\tabort();\t\/\/FIXME: This can be a valid error case\n\t}\n\n\tThread::Stop();\n}\n\nbool ClientUnix::DoSendRequest(Request *request, const struct timespec *Timeout)\n{\n\tstd::string str = \"REQUEST \" + request->Encode() + \"\\n\";\n\treturn SendLine(&str, Timeout);\n}\n\nbool ClientUnix::DoSendCommand(Request *request, const struct timespec *Timeout)\n{\n\tstd::string str = \"COMMAND \" + request->Encode() + \"\\n\";\n\treturn SendLine(&str, Timeout);\n}\n\nbool ClientUnix::SendLine(const std::string *str, const struct timespec *Timeout)\n{\n\tScopedLock lock1(&m_WriterMutex);\n\tif (IsConnected() == false)\n\t\treturn false;\n\n\tScopedReadLock rlock(&m_WriterLock);\n\tprintf(\"Writing(%d): %s\\n\", m_fd, str->c_str());\n\tint err = write(m_fd, str->c_str(), str->size());\n\t\/\/FIXME: Deal with partial write\n\tif (err == (int) str->length())\n\t\treturn true;\n\n\tRaiseOnSendError(errno, Errno::ToStr());\n\treturn false;\n}\n\nvoid ClientUnix::Run()\n{\n\tstruct sockaddr_un addr;\n\tsize_t addr_len = sizeof(addr);\n\n\twhile(m_quit == false)\n\t{\n\t\tReadBuffer Buffer(1024 * 2048);\n\t\tint fd = socket(AF_UNIX, SOCK_STREAM, 0);\n\t\tif (fd < 0)\n\t\t{\n\t\t\tRaiseOnConnectError(errno, Errno::ToStr());\n\t\t\tTime::Sleep(&m_ReConnectTimeout);\n\t\t\tif (close(fd) < 0)\n\t\t\t\tabort();\n\t\t\tcontinue;\n\t\t}\n\n\t\tmemset(&addr, addr_len, 0);\n\n\t\taddr.sun_family = AF_UNIX;\n\t\tsnprintf(addr.sun_path, sizeof(addr.sun_path), \"%s\", m_path.c_str());\n\n\t\tif (connect(fd, (struct sockaddr *) &addr, addr_len) < 0)\n\t\t{\n\t\t\tRaiseOnConnectError(errno, Errno::ToStr());\n\t\t\tif (close(fd) < 0)\n\t\t\t\tabort();\n\t\t\t\n\t\t\tTime::Sleep(&m_ReConnectTimeout);\n\t\t\tcontinue;\n\t\t}\n\n\t\tm_fd = fd;\t\/\/Allow write to access this now that we are connected\n\t\tm_connected = true;\n\t\tRaiseOnConnect();\n\n\t\t\/\/Read Responses \/ Events \/ Etc....\n\t\t\/\/FIXME: Need converted to non-blocking or a dead connection \/ server stops the disconnect from working!\n\t\twhile(m_quit == false && m_fd >= 0)\n\t\t{\n\t\t\tint ret = Buffer.Read(m_fd);\n\t\t\tif (ret <= 0)\n\t\t\t{\n\t\t\t\tm_connected = false;\n\t\t\t\tRaiseOnDisconnect(ret, Errno::ToStr(ret));\n\t\t\t\tScopedWriteLock wlock(&m_WriterLock);\t\/\/We need to protect m_fd from the writer side while we close it\n\t\t\t\tif (close(m_fd) < 0)\n\t\t\t\t\tabort();\n\t\t\t\tm_fd = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/Read Line at a time\n\t\t\tstd::string line;\n\t\t\tbool HasLine = Buffer.GetLine(&line);\n\t\t\twhile(HasLine == true)\n\t\t\t{\n\t\t\t\tRaiseOnData(&line);\n\t\t\t\tHasLine = Buffer.GetLine(&line);\n\t\t\t}\n\t\t}\n\t} \/\/m_quit == false\n}\n\n\nFix Client Refusing the disconnect\n#include \n#include \n#include \n\n#include \n\n\nClientUnix::ClientUnix(const std::string path)\n{\n\tInit();\n\tm_fd = -1;\n\tm_path = path;\n\tm_connected = false;\n}\n\nClientUnix::~ClientUnix()\n{\n\tDisconnect();\n}\n\nvoid ClientUnix::Connect()\n{\n\tm_quit = false;\n\tThread::Start();\n}\n\nbool ClientUnix::IsConnected()\n{\n\treturn m_connected;\n}\n\nvoid ClientUnix::Disconnect()\n{\n\tm_quit = true;\n\tScopedReadLock rlock(&m_WriterLock);\n\tif (m_fd >= 0)\n\t{\n\t\tif (shutdown(m_fd, SHUT_WR) < 0)\n\t\t\tabort();\t\/\/FIXME: This can be a valid error case\n\t}\n\trlock.Unlock();\n\n\tThread::Stop();\n}\n\nbool ClientUnix::DoSendRequest(Request *request, const struct timespec *Timeout)\n{\n\tstd::string str = \"REQUEST \" + request->Encode() + \"\\n\";\n\treturn SendLine(&str, Timeout);\n}\n\nbool ClientUnix::DoSendCommand(Request *request, const struct timespec *Timeout)\n{\n\tstd::string str = \"COMMAND \" + request->Encode() + \"\\n\";\n\treturn SendLine(&str, Timeout);\n}\n\nbool ClientUnix::SendLine(const std::string *str, const struct timespec *Timeout)\n{\n\tScopedLock lock1(&m_WriterMutex);\n\tif (IsConnected() == false)\n\t\treturn false;\n\n\tScopedReadLock rlock(&m_WriterLock);\n\tprintf(\"Writing(%d): %s\\n\", m_fd, str->c_str());\n\tint err = write(m_fd, str->c_str(), str->size());\n\t\/\/FIXME: Deal with partial write\n\tif (err == (int) str->length())\n\t\treturn true;\n\n\tRaiseOnSendError(errno, Errno::ToStr());\n\treturn false;\n}\n\nvoid ClientUnix::Run()\n{\n\tstruct sockaddr_un addr;\n\tsize_t addr_len = sizeof(addr);\n\n\twhile(m_quit == false)\n\t{\n\t\tReadBuffer Buffer(1024 * 2048);\n\t\tint fd = socket(AF_UNIX, SOCK_STREAM, 0);\n\t\tif (fd < 0)\n\t\t{\n\t\t\tRaiseOnConnectError(errno, Errno::ToStr());\n\t\t\tTime::Sleep(&m_ReConnectTimeout);\n\t\t\tif (close(fd) < 0)\n\t\t\t\tabort();\n\t\t\tcontinue;\n\t\t}\n\n\t\tmemset(&addr, addr_len, 0);\n\n\t\taddr.sun_family = AF_UNIX;\n\t\tsnprintf(addr.sun_path, sizeof(addr.sun_path), \"%s\", m_path.c_str());\n\n\t\tif (connect(fd, (struct sockaddr *) &addr, addr_len) < 0)\n\t\t{\n\t\t\tRaiseOnConnectError(errno, Errno::ToStr());\n\t\t\tif (close(fd) < 0)\n\t\t\t\tabort();\n\t\t\t\n\t\t\tTime::Sleep(&m_ReConnectTimeout);\n\t\t\tcontinue;\n\t\t}\n\n\t\tm_fd = fd;\t\/\/Allow write to access this now that we are connected\n\t\tm_connected = true;\n\t\tRaiseOnConnect();\n\n\t\t\/\/Read Responses \/ Events \/ Etc....\n\t\t\/\/FIXME: Need converted to non-blocking or a dead connection \/ server stops the disconnect from working!\n\t\twhile(m_quit == false && m_fd >= 0)\n\t\t{\n\t\t\tint ret = Buffer.Read(m_fd);\n\t\t\tif (ret <= 0)\n\t\t\t{\n\t\t\t\tm_connected = false;\n\t\t\t\tRaiseOnDisconnect(ret, Errno::ToStr(ret));\n\t\t\t\tScopedWriteLock wlock(&m_WriterLock);\t\/\/We need to protect m_fd from the writer side while we close it\n\t\t\t\tif (close(m_fd) < 0)\n\t\t\t\t\tabort();\n\t\t\t\tm_fd = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/Read Line at a time\n\t\t\tstd::string line;\n\t\t\tbool HasLine = Buffer.GetLine(&line);\n\t\t\twhile(HasLine == true)\n\t\t\t{\n\t\t\t\tRaiseOnData(&line);\n\t\t\t\tHasLine = Buffer.GetLine(&line);\n\t\t\t}\n\t\t}\n\t} \/\/m_quit == false\n}\n\n\n<|endoftext|>"} {"text":"#include \"ClueWidget.h\"\n\n#include \"Colors.h\"\n\n#include \n\nnamespace cygnus {\n\nstatic constexpr int kPixelDelta = 5;\n\nClueWidget::ClueWidget(QWidget *parent) : QListWidget(parent) {\n setMinimumWidth(200);\n}\n\nvoid ClueWidget::modifySize(int delta) {\n qDebug() << \"Changing size by\" << delta;\n for (uint32_t i = 0, e = count(); i < e; ++i) {\n QFont font = item(i)->font();\n font.setPointSize(font.pointSize() + delta);\n item(i)->setFont(font);\n }\n qApp->processEvents();\n}\n\nvoid ClueWidget::mousePressEvent(QMouseEvent *event) {\n if (event->button() == Qt::LeftButton) {\n mousePressed_ = true;\n }\n QListWidget::mousePressEvent(event);\n}\n\nvoid ClueWidget::mouseMoveEvent(QMouseEvent *event) {\n if (!mousePressed_) {\n \/\/ Disable click and drag.\n QListWidget::mouseMoveEvent(event);\n }\n}\n\nvoid ClueWidget::mouseReleaseEvent(QMouseEvent *event) {\n if (event->button() == Qt::LeftButton) {\n mousePressed_ = false;\n }\n QListWidget::mouseReleaseEvent(event);\n}\n\nvoid ClueWidget::setPrimary() {\n setStyleSheet(QString(\"QListView::item:selected { background: %1 }\")\n .arg(Colors::colorToString(Colors::PRIMARY_HIGHLIGHT)));\n}\n\nvoid ClueWidget::setSecondary() {\n setStyleSheet(QString(\"QListView::item:selected { background: %1 }\")\n .arg(Colors::colorToString(Colors::SECONDARY_HIGHLIGHT)));\n}\n\n} \/\/ namespace cygnus\nCleanup.#include \"ClueWidget.h\"\n\n#include \"Colors.h\"\n\n#include \n\nnamespace cygnus {\n\nstatic constexpr int kPixelDelta = 5;\n\nClueWidget::ClueWidget(QWidget *parent) : QListWidget(parent) {\n setMinimumWidth(200);\n}\n\nvoid ClueWidget::modifySize(int delta) {\n qDebug() << \"Changing size by\" << delta;\n for (uint32_t i = 0, e = count(); i < e; ++i) {\n QFont font = item(i)->font();\n font.setPointSize(font.pointSize() + delta);\n item(i)->setFont(font);\n }\n}\n\nvoid ClueWidget::mousePressEvent(QMouseEvent *event) {\n if (event->button() == Qt::LeftButton) {\n mousePressed_ = true;\n }\n QListWidget::mousePressEvent(event);\n}\n\nvoid ClueWidget::mouseMoveEvent(QMouseEvent *event) {\n if (!mousePressed_) {\n \/\/ Disable click and drag.\n QListWidget::mouseMoveEvent(event);\n }\n}\n\nvoid ClueWidget::mouseReleaseEvent(QMouseEvent *event) {\n if (event->button() == Qt::LeftButton) {\n mousePressed_ = false;\n }\n QListWidget::mouseReleaseEvent(event);\n}\n\nvoid ClueWidget::setPrimary() {\n setStyleSheet(QString(\"QListView::item:selected { background: %1 }\")\n .arg(Colors::colorToString(Colors::PRIMARY_HIGHLIGHT)));\n}\n\nvoid ClueWidget::setSecondary() {\n setStyleSheet(QString(\"QListView::item:selected { background: %1 }\")\n .arg(Colors::colorToString(Colors::SECONDARY_HIGHLIGHT)));\n}\n\n} \/\/ namespace cygnus\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ @file P2.cpp\n\/\/\/ @brief 2nd partial sieve function.\n\/\/\/ P2(x, y) counts the numbers <= x that have exactly 2 prime\n\/\/\/ factors each exceeding the a-th prime.\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#ifdef _OPENMP\n #include \n#endif\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\nnamespace P2 {\n\n\/\/\/ @return previous_prime or -1 if old <= 2\ninline int64_t get_previous_prime(primesieve::iterator* iter, int64_t old)\n{\n return (old > 2) ? iter->previous_prime() : -1;\n}\n\n\/\/\/ For each prime calculate its first multiple >= low\nvector generate_next_multiples(int64_t low, int64_t size, vector& primes)\n{\n vector next;\n\n next.reserve(size);\n next.push_back(0);\n\n for (int64_t b = 1; b < size; b++)\n {\n int64_t prime = primes[b];\n int64_t next_multiple = ceil_div(low, prime) * prime;\n next_multiple += prime * (~next_multiple & 1);\n next_multiple = max(prime * prime, next_multiple);\n next.push_back(next_multiple);\n }\n\n return next;\n}\n\ntemplate \nT P2_thread(T x,\n int64_t y,\n int64_t segment_size,\n int64_t segments_per_thread,\n int64_t thread_num,\n int64_t low,\n int64_t limit,\n int64_t& pix,\n int64_t& pix_count,\n vector& primes)\n{\n pix = 0;\n pix_count = 0;\n low += thread_num * segments_per_thread * segment_size;\n limit = min(low + segments_per_thread * segment_size, limit);\n int64_t size = pi_bsearch(primes, isqrt(limit)) + 1;\n int64_t start = (int64_t) max((int64_t) (x \/ limit + 1), y);\n int64_t stop = (int64_t) min(x \/ low, isqrt(x));\n T P2_thread = 0;\n\n \/\/ P2_thread = \\sum_{i=pi[start]}^{pi[stop]} pi(x \/ primes[i]) - pi(low - 1)\n \/\/ We use a reverse prime iterator to calculate P2_thread\n primesieve::iterator iter(stop + 1, start);\n int64_t previous_prime = get_previous_prime(&iter, stop + 1);\n int64_t xp = (int64_t) (x \/ previous_prime);\n\n vector next = generate_next_multiples(low, size, primes);\n BitSieve sieve(segment_size);\n\n \/\/ segmented sieve of Eratosthenes\n for (; low < limit; low += segment_size)\n {\n \/\/ current segment = interval [low, high[\n int64_t high = min(low + segment_size, limit);\n int64_t sqrt = isqrt(high - 1);\n int64_t j = 0;\n\n sieve.fill(low, high);\n\n \/\/ cross-off multiples\n for (int64_t i = 2; i < size && primes[i] <= sqrt; i++)\n {\n int64_t k;\n int64_t p2 = primes[i] * 2;\n for (k = next[i]; k < high; k += p2)\n sieve.unset(k - low);\n next[i] = k;\n }\n\n while (previous_prime >= start && xp < high)\n {\n pix += sieve.count(j, xp - low);\n j = xp - low + 1;\n pix_count++;\n P2_thread += pix;\n previous_prime = get_previous_prime(&iter, previous_prime);\n xp = (int64_t) (x \/ previous_prime);\n }\n\n pix += sieve.count(j, (high - 1) - low);\n }\n\n return P2_thread;\n}\n\nvoid balanceLoad(int64_t* segments_per_thread, double seconds1, double time1)\n{\n double time2 = get_wtime();\n double seconds = time2 - seconds1;\n double time = time2 - time1;\n double increase_threshold = in_between(0.3, time \/ 100, 20);\n\n if (seconds < increase_threshold)\n *segments_per_thread += *segments_per_thread * 3;\n else if (*segments_per_thread >= 4)\n *segments_per_thread -= *segments_per_thread \/ 4;\n}\n\n\/\/\/ P2(x, y) counts the numbers <= x that have exactly 2 prime\n\/\/\/ factors each exceeding the a-th prime, a = pi(y).\n\/\/\/ Space complexity: O((x \/ y)^(1\/2)).\n\/\/\/\ntemplate \nT P2(T x, int64_t y, int threads)\n{\n T a = pi_legendre(y, 1);\n T b = pi_legendre((int64_t) isqrt(x), 1);\n\n if (x < 4 || a >= b)\n return 0;\n\n if (print_status())\n {\n cout << endl;\n cout << \"=== P2(x, y) ===\" << endl;\n cout << \"Computation of the 2nd partial sieve function\" << endl;\n }\n\n double time = get_wtime();\n int64_t low = 2;\n int64_t limit = (int64_t)(x \/ max(1, y));\n int64_t segment_size = max(1 << 12, isqrt(limit));\n int64_t segments_per_thread = 1;\n threads = validate_threads(threads, limit);\n\n vector primes = generate_primes(isqrt(limit));\n aligned_vector pix(threads);\n aligned_vector pix_counts(threads);\n\n \/\/ \\sum_{i=a+1}^{b} pi(x \/ primes[i]) - (i - 1)\n \/\/ initialize with \\sum_{i=a+1}^{b} -i + 1\n T sum = (a - 2) * (a + 1) \/ 2 - (b - 2) * (b + 1) \/ 2;\n T pix_total = 0;\n\n while (low < limit)\n {\n int64_t segments = ceil_div(limit - low, segment_size);\n threads = in_between(1, threads, segments);\n segments_per_thread = in_between(1, segments_per_thread, ceil_div(segments, threads));\n double seconds = get_wtime();\n\n #pragma omp parallel for \\\n num_threads(threads) reduction(+: sum)\n for (int i = 0; i < threads; i++)\n sum += P2_thread(x, y, segment_size, segments_per_thread, i,\n low, limit, pix[i], pix_counts[i], primes);\n\n low += segments_per_thread * threads * segment_size;\n balanceLoad(&segments_per_thread, seconds, time);\n\n \/\/ Add missing sum contributions in order\n for (int i = 0; i < threads; i++)\n {\n sum += pix_total * pix_counts[i];\n pix_total += pix[i];\n }\n\n if (print_status())\n cout << \"\\rStatus: \" << get_percent(low, limit) << '%' << flush;\n }\n\n if (print_status())\n print_result(\"P2\", sum, time);\n\n return sum;\n}\n\n} \/\/ namespace P2\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t P2(int64_t x, int64_t y, int threads)\n{\n return P2::P2(x, y, threads);\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t P2(int128_t x, int64_t y, int threads)\n{\n return P2::P2(x, y, threads);\n}\n\n#endif\n\n\/\/\/ P2_lehmer(x, a) counts the numbers <= x that have exactly 2 prime\n\/\/\/ factors each exceeding the a-th prime. This implementation is\n\/\/\/ optimized for small values of a < pi(x^(1\/3)) which requires\n\/\/\/ sieving up to a large limit (x \/ primes[a]). Sieving is done in\n\/\/\/ parallel using primesieve (segmented sieve of Eratosthenes).\n\/\/\/ Space complexity: O(pi(sqrt(x))).\n\/\/\/\nint64_t P2_lehmer(int64_t x, int64_t a, int threads)\n{\n if (print_status())\n {\n cout << endl;\n cout << \"=== P2_lehmer(x, a) ===\" << endl;\n cout << \"Computation of the 2nd partial sieve function\" << endl;\n }\n\n double time = get_wtime();\n vector primes = generate_primes(isqrt(x));\n vector counts(primes.size());\n\n int64_t b = pi_bsearch(primes, isqrt(x));\n int64_t sum = 0;\n int64_t pix = 0;\n\n #pragma omp parallel for schedule(dynamic) \\\n num_threads(validate_threads(threads, b, 1000))\n for (int64_t i = b; i > a; i--)\n {\n int64_t prev = (i == b) ? 0 : x \/ primes[i + 1] + 1;\n int64_t xi = x \/ primes[i];\n counts[i] = primesieve::count_primes(prev, xi);\n }\n\n for (int64_t i = b; i > a; i--)\n {\n pix += counts[i];\n sum += pix - (i - 1);\n }\n\n if (print_status())\n print_result(\"P2\", sum, time);\n\n return sum;\n}\n\n} \/\/ namespace primecount\ntune P2(x, a) load balancer\/\/\/\n\/\/\/ @file P2.cpp\n\/\/\/ @brief 2nd partial sieve function.\n\/\/\/ P2(x, y) counts the numbers <= x that have exactly 2 prime\n\/\/\/ factors each exceeding the a-th prime.\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#ifdef _OPENMP\n #include \n#endif\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\nnamespace P2 {\n\n\/\/\/ @return previous_prime or -1 if old <= 2\ninline int64_t get_previous_prime(primesieve::iterator* iter, int64_t old)\n{\n return (old > 2) ? iter->previous_prime() : -1;\n}\n\n\/\/\/ For each prime calculate its first multiple >= low\nvector generate_next_multiples(int64_t low, int64_t size, vector& primes)\n{\n vector next;\n\n next.reserve(size);\n next.push_back(0);\n\n for (int64_t b = 1; b < size; b++)\n {\n int64_t prime = primes[b];\n int64_t next_multiple = ceil_div(low, prime) * prime;\n next_multiple += prime * (~next_multiple & 1);\n next_multiple = max(prime * prime, next_multiple);\n next.push_back(next_multiple);\n }\n\n return next;\n}\n\ntemplate \nT P2_thread(T x,\n int64_t y,\n int64_t segment_size,\n int64_t segments_per_thread,\n int64_t thread_num,\n int64_t low,\n int64_t limit,\n int64_t& pix,\n int64_t& pix_count,\n vector& primes)\n{\n pix = 0;\n pix_count = 0;\n low += thread_num * segments_per_thread * segment_size;\n limit = min(low + segments_per_thread * segment_size, limit);\n int64_t size = pi_bsearch(primes, isqrt(limit)) + 1;\n int64_t start = (int64_t) max((int64_t) (x \/ limit + 1), y);\n int64_t stop = (int64_t) min(x \/ low, isqrt(x));\n T P2_thread = 0;\n\n \/\/ P2_thread = \\sum_{i=pi[start]}^{pi[stop]} pi(x \/ primes[i]) - pi(low - 1)\n \/\/ We use a reverse prime iterator to calculate P2_thread\n primesieve::iterator iter(stop + 1, start);\n int64_t previous_prime = get_previous_prime(&iter, stop + 1);\n int64_t xp = (int64_t) (x \/ previous_prime);\n\n vector next = generate_next_multiples(low, size, primes);\n BitSieve sieve(segment_size);\n\n \/\/ segmented sieve of Eratosthenes\n for (; low < limit; low += segment_size)\n {\n \/\/ current segment = interval [low, high[\n int64_t high = min(low + segment_size, limit);\n int64_t sqrt = isqrt(high - 1);\n int64_t j = 0;\n\n sieve.fill(low, high);\n\n \/\/ cross-off multiples\n for (int64_t i = 2; i < size && primes[i] <= sqrt; i++)\n {\n int64_t k;\n int64_t p2 = primes[i] * 2;\n for (k = next[i]; k < high; k += p2)\n sieve.unset(k - low);\n next[i] = k;\n }\n\n while (previous_prime >= start && xp < high)\n {\n pix += sieve.count(j, xp - low);\n j = xp - low + 1;\n pix_count++;\n P2_thread += pix;\n previous_prime = get_previous_prime(&iter, previous_prime);\n xp = (int64_t) (x \/ previous_prime);\n }\n\n pix += sieve.count(j, (high - 1) - low);\n }\n\n return P2_thread;\n}\n\nvoid balanceLoad(int64_t* segments_per_thread, double seconds1, double time1)\n{\n double time2 = get_wtime();\n double seconds = time2 - seconds1;\n double time = time2 - time1;\n double increase_threshold = in_between(0.5, time \/ 10, 20);\n\n if (seconds < increase_threshold)\n *segments_per_thread += *segments_per_thread * 3;\n else if (*segments_per_thread >= 4)\n *segments_per_thread -= *segments_per_thread \/ 4;\n}\n\n\/\/\/ P2(x, y) counts the numbers <= x that have exactly 2 prime\n\/\/\/ factors each exceeding the a-th prime, a = pi(y).\n\/\/\/ Space complexity: O((x \/ y)^(1\/2)).\n\/\/\/\ntemplate \nT P2(T x, int64_t y, int threads)\n{\n T a = pi_legendre(y, 1);\n T b = pi_legendre((int64_t) isqrt(x), 1);\n\n if (x < 4 || a >= b)\n return 0;\n\n if (print_status())\n {\n cout << endl;\n cout << \"=== P2(x, y) ===\" << endl;\n cout << \"Computation of the 2nd partial sieve function\" << endl;\n }\n\n double time = get_wtime();\n int64_t low = 2;\n int64_t limit = (int64_t)(x \/ max(1, y));\n int64_t segment_size = max(1 << 12, isqrt(limit));\n int64_t segments_per_thread = 1;\n threads = validate_threads(threads, limit);\n\n vector primes = generate_primes(isqrt(limit));\n aligned_vector pix(threads);\n aligned_vector pix_counts(threads);\n\n \/\/ \\sum_{i=a+1}^{b} pi(x \/ primes[i]) - (i - 1)\n \/\/ initialize with \\sum_{i=a+1}^{b} -i + 1\n T sum = (a - 2) * (a + 1) \/ 2 - (b - 2) * (b + 1) \/ 2;\n T pix_total = 0;\n\n while (low < limit)\n {\n int64_t segments = ceil_div(limit - low, segment_size);\n threads = in_between(1, threads, segments);\n segments_per_thread = in_between(1, segments_per_thread, ceil_div(segments, threads));\n double seconds = get_wtime();\n\n #pragma omp parallel for \\\n num_threads(threads) reduction(+: sum)\n for (int i = 0; i < threads; i++)\n sum += P2_thread(x, y, segment_size, segments_per_thread, i,\n low, limit, pix[i], pix_counts[i], primes);\n\n low += segments_per_thread * threads * segment_size;\n balanceLoad(&segments_per_thread, seconds, time);\n\n \/\/ Add missing sum contributions in order\n for (int i = 0; i < threads; i++)\n {\n sum += pix_total * pix_counts[i];\n pix_total += pix[i];\n }\n\n if (print_status())\n cout << \"\\rStatus: \" << get_percent(low, limit) << '%' << flush;\n }\n\n if (print_status())\n print_result(\"P2\", sum, time);\n\n return sum;\n}\n\n} \/\/ namespace P2\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t P2(int64_t x, int64_t y, int threads)\n{\n return P2::P2(x, y, threads);\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t P2(int128_t x, int64_t y, int threads)\n{\n return P2::P2(x, y, threads);\n}\n\n#endif\n\n\/\/\/ P2_lehmer(x, a) counts the numbers <= x that have exactly 2 prime\n\/\/\/ factors each exceeding the a-th prime. This implementation is\n\/\/\/ optimized for small values of a < pi(x^(1\/3)) which requires\n\/\/\/ sieving up to a large limit (x \/ primes[a]). Sieving is done in\n\/\/\/ parallel using primesieve (segmented sieve of Eratosthenes).\n\/\/\/ Space complexity: O(pi(sqrt(x))).\n\/\/\/\nint64_t P2_lehmer(int64_t x, int64_t a, int threads)\n{\n if (print_status())\n {\n cout << endl;\n cout << \"=== P2_lehmer(x, a) ===\" << endl;\n cout << \"Computation of the 2nd partial sieve function\" << endl;\n }\n\n double time = get_wtime();\n vector primes = generate_primes(isqrt(x));\n vector counts(primes.size());\n\n int64_t b = pi_bsearch(primes, isqrt(x));\n int64_t sum = 0;\n int64_t pix = 0;\n\n #pragma omp parallel for schedule(dynamic) \\\n num_threads(validate_threads(threads, b, 1000))\n for (int64_t i = b; i > a; i--)\n {\n int64_t prev = (i == b) ? 0 : x \/ primes[i + 1] + 1;\n int64_t xi = x \/ primes[i];\n counts[i] = primesieve::count_primes(prev, xi);\n }\n\n for (int64_t i = b; i > a; i--)\n {\n pix += counts[i];\n sum += pix - (i - 1);\n }\n\n if (print_status())\n print_result(\"P2\", sum, time);\n\n return sum;\n}\n\n} \/\/ namespace primecount\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017-2019 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/taocpp\/PEGTL\/\n\n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace TAO_PEGTL_NAMESPACE; \/\/ NOLINT\n\nnamespace example\n{\n \/\/ the grammar\n\n \/\/ clang-format off\n struct integer : plus< digit > {};\n struct variable : identifier {};\n\n struct plus : pad< one< '+' >, space > {};\n struct minus : pad< one< '-' >, space > {};\n struct multiply : pad< one< '*' >, space > {};\n struct divide : pad< one< '\/' >, space > {};\n\n struct open_bracket : seq< one< '(' >, star< space > > {};\n struct close_bracket : seq< star< space >, one< ')' > > {};\n\n struct expression;\n struct bracketed : if_must< open_bracket, expression, close_bracket > {};\n struct value : sor< integer, variable, bracketed >{};\n struct product : list_must< value, sor< multiply, divide > > {};\n struct expression : list_must< product, sor< plus, minus > > {};\n\n struct grammar : seq< expression, eof > {};\n\n \/\/ after a node is stored successfully, you can add an optional transformer like this:\n struct rearrange : std::true_type\n {\n \/\/ recursively rearrange nodes. the basic principle is:\n \/\/\n \/\/ from: PROD\/EXPR\n \/\/ \/ | \\ (LHS... may be one or more children, followed by OP,)\n \/\/ LHS... OP RHS (which is one operator, and RHS, which is a single child)\n \/\/\n \/\/ to: OP\n \/\/ \/ \\ (OP now has two children, the original PROD\/EXPR and RHS)\n \/\/ PROD\/EXPR RHS (Note that PROD\/EXPR has two fewer children now)\n \/\/ |\n \/\/ LHS...\n \/\/\n \/\/ if only one child is left for LHS..., replace the PROD\/EXPR with the child directly.\n \/\/ otherwise, perform the above transformation, then apply it recursively until LHS...\n \/\/ becomes a single child, which then replaces the parent node and the recursion ends.\n template< typename... States >\n static void transform( std::unique_ptr< parse_tree::node >& n, States&&... st )\n {\n if( n->children.size() == 1 ) {\n n = std::move( n->children.back() );\n }\n else {\n n->remove_content();\n auto& c = n->children;\n auto r = std::move( c.back() );\n c.pop_back();\n auto o = std::move( c.back() );\n c.pop_back();\n o->children.emplace_back( std::move( n ) );\n o->children.emplace_back( std::move( r ) );\n n = std::move( o );\n transform( n->children.front(), st... );\n }\n }\n };\n\n \/\/ select which rules in the grammar will produce parse tree nodes:\n\n template< typename Rule >\n using selector = parse_tree::selector<\n Rule,\n parse_tree::apply_store_content::to<\n integer,\n variable >,\n parse_tree::apply_remove_content::to<\n plus,\n minus,\n multiply,\n divide >,\n parse_tree::apply< rearrange >::to<\n product,\n expression > >;\n\n \/\/ debugging\/show result:\n\n void print_node( const parse_tree::node& n, const std::string& s = \"\" )\n {\n \/\/ detect the root node:\n if( n.is_root() ) {\n std::cout << \"ROOT\" << std::endl;\n }\n else {\n if( n.has_content() ) {\n std::cout << s << n.name() << \" \\\"\" << n.string_view() << \"\\\" at \" << n.begin() << \" to \" << n.end() << std::endl;\n }\n else {\n std::cout << s << n.name() << \" at \" << n.begin() << std::endl;\n }\n }\n \/\/ print all child nodes\n if( !n.children.empty() ) {\n const auto s2 = s + \" \";\n for( auto& up : n.children ) {\n print_node( *up, s2 );\n }\n }\n }\n\n} \/\/ namespace example\n\nint main( int argc, char** argv )\n{\n for( int i = 1; i < argc; ++i ) {\n try {\n argv_input in( argv, i );\n if( const auto root = parse_tree::parse< example::grammar, example::selector >( in ) ) {\n example::print_node( *root );\n }\n else {\n std::cout << \"PARSE FAILED\" << std::endl;\n }\n }\n catch( const std::exception& e ) {\n std::cout << \"PARSE FAILED WITH EXCEPTION: \" << e.what() << std::endl;\n }\n }\n return 0;\n}\nAdd missing 'clang-format on'\/\/ Copyright (c) 2017-2019 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/taocpp\/PEGTL\/\n\n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace TAO_PEGTL_NAMESPACE; \/\/ NOLINT\n\nnamespace example\n{\n \/\/ the grammar\n\n \/\/ clang-format off\n struct integer : plus< digit > {};\n struct variable : identifier {};\n\n struct plus : pad< one< '+' >, space > {};\n struct minus : pad< one< '-' >, space > {};\n struct multiply : pad< one< '*' >, space > {};\n struct divide : pad< one< '\/' >, space > {};\n\n struct open_bracket : seq< one< '(' >, star< space > > {};\n struct close_bracket : seq< star< space >, one< ')' > > {};\n\n struct expression;\n struct bracketed : if_must< open_bracket, expression, close_bracket > {};\n struct value : sor< integer, variable, bracketed >{};\n struct product : list_must< value, sor< multiply, divide > > {};\n struct expression : list_must< product, sor< plus, minus > > {};\n\n struct grammar : seq< expression, eof > {};\n \/\/ clang-format on\n\n \/\/ after a node is stored successfully, you can add an optional transformer like this:\n struct rearrange : std::true_type\n {\n \/\/ recursively rearrange nodes. the basic principle is:\n \/\/\n \/\/ from: PROD\/EXPR\n \/\/ \/ | \\ (LHS... may be one or more children, followed by OP,)\n \/\/ LHS... OP RHS (which is one operator, and RHS, which is a single child)\n \/\/\n \/\/ to: OP\n \/\/ \/ \\ (OP now has two children, the original PROD\/EXPR and RHS)\n \/\/ PROD\/EXPR RHS (Note that PROD\/EXPR has two fewer children now)\n \/\/ |\n \/\/ LHS...\n \/\/\n \/\/ if only one child is left for LHS..., replace the PROD\/EXPR with the child directly.\n \/\/ otherwise, perform the above transformation, then apply it recursively until LHS...\n \/\/ becomes a single child, which then replaces the parent node and the recursion ends.\n template< typename... States >\n static void transform( std::unique_ptr< parse_tree::node >& n, States&&... st )\n {\n if( n->children.size() == 1 ) {\n n = std::move( n->children.back() );\n }\n else {\n n->remove_content();\n auto& c = n->children;\n auto r = std::move( c.back() );\n c.pop_back();\n auto o = std::move( c.back() );\n c.pop_back();\n o->children.emplace_back( std::move( n ) );\n o->children.emplace_back( std::move( r ) );\n n = std::move( o );\n transform( n->children.front(), st... );\n }\n }\n };\n\n \/\/ select which rules in the grammar will produce parse tree nodes:\n\n template< typename Rule >\n using selector = parse_tree::selector<\n Rule,\n parse_tree::apply_store_content::to<\n integer,\n variable >,\n parse_tree::apply_remove_content::to<\n plus,\n minus,\n multiply,\n divide >,\n parse_tree::apply< rearrange >::to<\n product,\n expression > >;\n\n \/\/ debugging\/show result:\n\n void print_node( const parse_tree::node& n, const std::string& s = \"\" )\n {\n \/\/ detect the root node:\n if( n.is_root() ) {\n std::cout << \"ROOT\" << std::endl;\n }\n else {\n if( n.has_content() ) {\n std::cout << s << n.name() << \" \\\"\" << n.string_view() << \"\\\" at \" << n.begin() << \" to \" << n.end() << std::endl;\n }\n else {\n std::cout << s << n.name() << \" at \" << n.begin() << std::endl;\n }\n }\n \/\/ print all child nodes\n if( !n.children.empty() ) {\n const auto s2 = s + \" \";\n for( auto& up : n.children ) {\n print_node( *up, s2 );\n }\n }\n }\n\n} \/\/ namespace example\n\nint main( int argc, char** argv )\n{\n for( int i = 1; i < argc; ++i ) {\n try {\n argv_input in( argv, i );\n if( const auto root = parse_tree::parse< example::grammar, example::selector >( in ) ) {\n example::print_node( *root );\n }\n else {\n std::cout << \"PARSE FAILED\" << std::endl;\n }\n }\n catch( const std::exception& e ) {\n std::cout << \"PARSE FAILED WITH EXCEPTION: \" << e.what() << std::endl;\n }\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n This file is part of Akregator.\n\n Copyright (C) 2007 Frank Osterfeld \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n#include \"articlemodel.h\"\n\n#include \"article.h\"\n#include \"articlematcher.h\"\n#include \"akregatorconfig.h\"\n#include \"treenode.h\"\n#include \"feed.h\"\n\n#include \n\n#include \n#include \n\n#include \n#include \n\nusing namespace Akregator;\n\nclass ArticleModel::Private {\nprivate:\n ArticleModel* const q;\npublic:\n Private( TreeNode* node_, ArticleModel* qq );\n Akregator::TreeNode* node;\n QList articles;\n void nodeDestroyed();\n void articlesAdded( TreeNode*, const QList
& );\n void articlesRemoved( TreeNode*, const QList
& );\n void articlesUpdated( TreeNode*, const QList
& );\n\n};\n\nArticleModel::Private::Private( TreeNode* node_, ArticleModel* qq )\n : q( qq ), node( node_ )\n{\n Q_ASSERT( node );\n}\n\nAkregator::ArticleModel::ArticleModel(TreeNode* node, QObject* parent) : QAbstractTableModel( parent ), d( new Private( node, this ) )\n{\n d->articles = node->articles();\n connect( node, SIGNAL(destroyed()), this, SLOT(nodeDestroyed()) );\n connect( node, SIGNAL(signalArticlesAdded(Akregator::TreeNode*, QList)), SLOT( articlesAdded(Akregator::TreeNode*, QList) ) );\n connect( node, SIGNAL(signalArticlesRemoved(Akregator::TreeNode*, QList)), SLOT(articlesRemoved(Akregator::TreeNode*, QList)) );\n connect( node, SIGNAL(signalArticlesUpdated(Akregator::TreeNode*, QList)), SLOT(articlesUpdated(Akregator::TreeNode*, QList)) );\n}\n\nAkregator::ArticleModel::~ArticleModel()\n{\n delete d;\n}\n\nint Akregator::ArticleModel::columnCount( const QModelIndex& parent ) const\n{\n return parent.isValid() ? 0 : ColumnCount;\n}\n\nint Akregator::ArticleModel::rowCount( const QModelIndex& parent ) const\n{\n return parent.isValid() ? 0 : d->articles.count();\n}\n\nQVariant Akregator::ArticleModel::data( const QModelIndex& index, int role ) const\n{\n if ( !index.isValid() || index.row() < 0 || index.row() >= d->articles.count() )\n return QVariant();\n const Akregator::Article article = d->articles[ index.row() ];\n\n if ( article.isNull() )\n return QVariant();\n\n switch ( role )\n {\n case Qt::DisplayRole:\n {\n switch ( index.column() )\n {\n case FeedTitleColumn:\n return article.feed() ? article.feed()->title() : QVariant();\n case DateColumn:\n return article.pubDate();\n case ItemTitleColumn:\n return article.title();\n case AuthorColumn:\n return article.author();\n case DescriptionColumn:\n case ContentColumn:\n return article.description();\n }\n }\n case LinkRole:\n {\n return article.link();\n }\n case ItemIdRole:\n case GuidRole:\n {\n return article.guid();\n }\n case FeedIdRole:\n {\n return article.feed() ? article.feed()->xmlUrl() : QVariant();\n }\n case StatusRole:\n {\n return article.status();\n }\n case IsImportantRole:\n {\n return article.keep();\n }\n }\n\n return QVariant();\n}\n\nvoid Akregator::ArticleModel::Private::nodeDestroyed()\n{\n node = 0;\n articles.clear();\n q->reset();\n}\n\nvoid ArticleModel::Private::articlesAdded( TreeNode* node, const QList
& list )\n{\n const int first = static_cast( articles.count() );\n q->beginInsertRows( QModelIndex(), first, first + list.size() - 1 );\n articles << list; \n q->endInsertRows();\n}\n\nvoid ArticleModel::Private::articlesRemoved( TreeNode* node, const QList
& list )\n{\n \/\/might want to avoid indexOf() in case of performance problems\n Q_FOREACH ( const Article& i, list )\n {\n const int row = articles.indexOf( i ); \n assert( row != -1 );\n q->beginRemoveRows( QModelIndex(), row, row );\n q->endRemoveRows();\n }\n}\n\n\nvoid ArticleModel::Private::articlesUpdated( TreeNode* node, const QList
& list )\n{\n int rmin = articles.count() - 1;\n int rmax = 0;\n\n \/\/might want to avoid indexOf() in case of performance problems\n Q_FOREACH ( const Article& i, list )\n {\n const int row = articles.indexOf( i ); \n assert( row != -1 );\n rmin = std::min( row, rmin );\n rmax = std::max( row, rmax );\n }\n emit q->dataChanged( q->index( rmin, 0 ), q->index( rmax, ColumnCount-1 ) );\n}\n\n\nbool ArticleModel::rowMatches( int row, const boost::shared_ptr& matcher ) const\n{\n assert( matcher );\n if ( row < 0 || row >= d->articles.count() )\n return false;\n return matcher->matches( d->articles[row] );\n}\n\n\n#include \"articlemodel.moc\"\nthe append code only works correctly if list is non-empty\/*\n This file is part of Akregator.\n\n Copyright (C) 2007 Frank Osterfeld \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n#include \"articlemodel.h\"\n\n#include \"article.h\"\n#include \"articlematcher.h\"\n#include \"akregatorconfig.h\"\n#include \"treenode.h\"\n#include \"feed.h\"\n\n#include \n\n#include \n#include \n\n#include \n#include \n\nusing namespace Akregator;\n\nclass ArticleModel::Private {\nprivate:\n ArticleModel* const q;\npublic:\n Private( TreeNode* node_, ArticleModel* qq );\n Akregator::TreeNode* node;\n QList articles;\n void nodeDestroyed();\n void articlesAdded( TreeNode*, const QList
& );\n void articlesRemoved( TreeNode*, const QList
& );\n void articlesUpdated( TreeNode*, const QList
& );\n\n};\n\nArticleModel::Private::Private( TreeNode* node_, ArticleModel* qq )\n : q( qq ), node( node_ )\n{\n Q_ASSERT( node );\n}\n\nAkregator::ArticleModel::ArticleModel(TreeNode* node, QObject* parent) : QAbstractTableModel( parent ), d( new Private( node, this ) )\n{\n d->articles = node->articles();\n connect( node, SIGNAL(destroyed()), this, SLOT(nodeDestroyed()) );\n connect( node, SIGNAL(signalArticlesAdded(Akregator::TreeNode*, QList)), SLOT( articlesAdded(Akregator::TreeNode*, QList) ) );\n connect( node, SIGNAL(signalArticlesRemoved(Akregator::TreeNode*, QList)), SLOT(articlesRemoved(Akregator::TreeNode*, QList)) );\n connect( node, SIGNAL(signalArticlesUpdated(Akregator::TreeNode*, QList)), SLOT(articlesUpdated(Akregator::TreeNode*, QList)) );\n}\n\nAkregator::ArticleModel::~ArticleModel()\n{\n delete d;\n}\n\nint Akregator::ArticleModel::columnCount( const QModelIndex& parent ) const\n{\n return parent.isValid() ? 0 : ColumnCount;\n}\n\nint Akregator::ArticleModel::rowCount( const QModelIndex& parent ) const\n{\n return parent.isValid() ? 0 : d->articles.count();\n}\n\nQVariant Akregator::ArticleModel::data( const QModelIndex& index, int role ) const\n{\n if ( !index.isValid() || index.row() < 0 || index.row() >= d->articles.count() )\n return QVariant();\n const Akregator::Article article = d->articles[ index.row() ];\n\n if ( article.isNull() )\n return QVariant();\n\n switch ( role )\n {\n case Qt::DisplayRole:\n {\n switch ( index.column() )\n {\n case FeedTitleColumn:\n return article.feed() ? article.feed()->title() : QVariant();\n case DateColumn:\n return article.pubDate();\n case ItemTitleColumn:\n return article.title();\n case AuthorColumn:\n return article.author();\n case DescriptionColumn:\n case ContentColumn:\n return article.description();\n }\n }\n case LinkRole:\n {\n return article.link();\n }\n case ItemIdRole:\n case GuidRole:\n {\n return article.guid();\n }\n case FeedIdRole:\n {\n return article.feed() ? article.feed()->xmlUrl() : QVariant();\n }\n case StatusRole:\n {\n return article.status();\n }\n case IsImportantRole:\n {\n return article.keep();\n }\n }\n\n return QVariant();\n}\n\nvoid Akregator::ArticleModel::Private::nodeDestroyed()\n{\n node = 0;\n articles.clear();\n q->reset();\n}\n\nvoid ArticleModel::Private::articlesAdded( TreeNode* node, const QList
& list )\n{\n if ( list.isEmpty() ) \/\/assert?\n return;\n const int first = static_cast( articles.count() );\n q->beginInsertRows( QModelIndex(), first, first + list.size() - 1 );\n articles << list; \n q->endInsertRows();\n}\n\nvoid ArticleModel::Private::articlesRemoved( TreeNode* node, const QList
& list )\n{\n \/\/might want to avoid indexOf() in case of performance problems\n Q_FOREACH ( const Article& i, list )\n {\n const int row = articles.indexOf( i ); \n assert( row != -1 );\n q->beginRemoveRows( QModelIndex(), row, row );\n q->endRemoveRows();\n }\n}\n\n\nvoid ArticleModel::Private::articlesUpdated( TreeNode* node, const QList
& list )\n{\n int rmin = articles.count() - 1;\n int rmax = 0;\n\n \/\/might want to avoid indexOf() in case of performance problems\n Q_FOREACH ( const Article& i, list )\n {\n const int row = articles.indexOf( i ); \n assert( row != -1 );\n rmin = std::min( row, rmin );\n rmax = std::max( row, rmax );\n }\n emit q->dataChanged( q->index( rmin, 0 ), q->index( rmax, ColumnCount-1 ) );\n}\n\n\nbool ArticleModel::rowMatches( int row, const boost::shared_ptr& matcher ) const\n{\n assert( matcher );\n if ( row < 0 || row >= d->articles.count() )\n return false;\n return matcher->matches( d->articles[row] );\n}\n\n\n#include \"articlemodel.moc\"\n<|endoftext|>"} {"text":"\/*\n This file is part of Akregator.\n\n Copyright (C) 2005 Frank Osterfeld \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \n\n#include \n#include \n\n#include \"configdialog.h\"\n\n#include \"akregatorconfig.h\"\n#include \"settings_advanced.h\"\n#include \"settings_appearance.h\"\n#include \"settings_archive.h\"\n#include \"settings_browser.h\"\n#include \"settings_general.h\"\n#include \n#include \n\nnamespace Akregator\n{\n\nConfigDialog::ConfigDialog(QWidget* parent, const char* name, KConfigSkeleton* config, DialogType dialogType, int dialogButtons, ButtonCode defaultButton, bool modal) : KConfigDialog(parent, name, config, dialogType, dialogButtons, defaultButton, modal)\n{\n addPage(new SettingsGeneral(this, \"General\"), i18n(\"General\"), \"package_settings\");\n addPage(new SettingsArchive(this, \"Archive\"), i18n(\"Archive\"), \"package_settings\");\n m_settingsAppearance = new SettingsAppearance(this, \"Appearance\");\n addPage(m_settingsAppearance, i18n(\"Appearance\"), \"fonts\");\n addPage(new SettingsBrowser(this, \"Browser\"), i18n(\"Browser\"), \"package_network\");\n m_settingsAdvanced = new SettingsAdvanced(this, \"Advanced\");\n addPage(m_settingsAdvanced, i18n(\"Advanced\"), \"package_network\");\n m_settingsAdvanced->selectFactory(Settings::archiveBackend());\n m_config = config;\n}\n\nvoid ConfigDialog::updateSettings()\n{\n Settings::setArchiveBackend(m_settingsAdvanced->selectedFactory());\n KConfigDialog::updateSettings();\n}\n \nvoid ConfigDialog::updateWidgets()\n{\n m_settingsAdvanced->selectFactory(Settings::archiveBackend());\n m_settingsAppearance->slider_minimumFontSize->setDisabled(m_config->isImmutable(\"MinimumFontSize\"));\n m_settingsAppearance->slider_mediumFontSize->setDisabled(m_config->isImmutable(\"MediumFontSize\"));\n m_settingsAppearance->lbl_MinimumFontSize->setDisabled(m_config->isImmutable(\"MinimumFontSize\"));\n m_settingsAppearance->lbl_MediumFontSize->setDisabled(m_config->isImmutable(\"MediumFontSize\"));\n KConfigDialog::updateSettings();\n}\n \nConfigDialog::~ConfigDialog() {}\n\n} \/\/ namespace Akregator\n\n#include \"configdialog.moc\"\nfix wrong call. doesn't fix any known bugs, but anyway\/*\n This file is part of Akregator.\n\n Copyright (C) 2005 Frank Osterfeld \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \n\n#include \n#include \n\n#include \"configdialog.h\"\n\n#include \"akregatorconfig.h\"\n#include \"settings_advanced.h\"\n#include \"settings_appearance.h\"\n#include \"settings_archive.h\"\n#include \"settings_browser.h\"\n#include \"settings_general.h\"\n#include \n#include \n\nnamespace Akregator\n{\n\nConfigDialog::ConfigDialog(QWidget* parent, const char* name, KConfigSkeleton* config, DialogType dialogType, int dialogButtons, ButtonCode defaultButton, bool modal) : KConfigDialog(parent, name, config, dialogType, dialogButtons, defaultButton, modal)\n{\n addPage(new SettingsGeneral(this, \"General\"), i18n(\"General\"), \"package_settings\");\n addPage(new SettingsArchive(this, \"Archive\"), i18n(\"Archive\"), \"package_settings\");\n m_settingsAppearance = new SettingsAppearance(this, \"Appearance\");\n addPage(m_settingsAppearance, i18n(\"Appearance\"), \"fonts\");\n addPage(new SettingsBrowser(this, \"Browser\"), i18n(\"Browser\"), \"package_network\");\n m_settingsAdvanced = new SettingsAdvanced(this, \"Advanced\");\n addPage(m_settingsAdvanced, i18n(\"Advanced\"), \"package_network\");\n m_settingsAdvanced->selectFactory(Settings::archiveBackend());\n m_config = config;\n}\n\nvoid ConfigDialog::updateSettings()\n{\n Settings::setArchiveBackend(m_settingsAdvanced->selectedFactory());\n KConfigDialog::updateSettings();\n}\n \nvoid ConfigDialog::updateWidgets()\n{\n m_settingsAdvanced->selectFactory(Settings::archiveBackend());\n m_settingsAppearance->slider_minimumFontSize->setDisabled(m_config->isImmutable(\"MinimumFontSize\"));\n m_settingsAppearance->slider_mediumFontSize->setDisabled(m_config->isImmutable(\"MediumFontSize\"));\n m_settingsAppearance->lbl_MinimumFontSize->setDisabled(m_config->isImmutable(\"MinimumFontSize\"));\n m_settingsAppearance->lbl_MediumFontSize->setDisabled(m_config->isImmutable(\"MediumFontSize\"));\n KConfigDialog::updateWidgets();\n}\n \nConfigDialog::~ConfigDialog() {}\n\n} \/\/ namespace Akregator\n\n#include \"configdialog.moc\"\n<|endoftext|>"} {"text":"\n#ifndef __gl_h_\n#include \n#endif\n\n#include \n#include \n#include \n\n\/\/ Include GLM\n#include \"glm\/glm.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n#include \"glm\/gtc\/matrix_inverse.hpp\"\n#include \"glm\/gtx\/string_cast.hpp\"\n#include \n\n#include \"Camera.h\"\n#include \"GLSpins.h\"\n#include \"ISpinRenderer.h\"\n#include \"ArrowSpinRenderer.h\"\n#include \"SurfaceSpinRenderer.h\"\n#include \"SphereSpinRenderer.h\"\n#include \"BoundingBoxRenderer.h\"\n#include \"CombinedSpinRenderer.h\"\n#include \"CoordinateSystemRenderer.h\"\n#include \"utilities.h\"\n\n#ifndef M_PI\n\t#define M_PI 3.14159265358979323846\n#endif \/\/ !M_PI\n\nGLSpins::GLSpins(std::vector n_cells, bool threeD) {\n if (!gladLoadGL()) {\n std::cerr << \"Failed to initialize glad\" << std::endl;\n }\n \n \/\/ Reset any error potentially caused by glad\n glGetError();\n \n CHECK_GL_ERROR;\n setCameraToDefault();\n\n glClearColor(0.1f, 0.1f, 0.1f, 0.0f);\n glEnable(GL_DEPTH_TEST);\n glDepthFunc(GL_LESS);\n \n Options options;\n options.set(getColormapImplementation(\"hsv\"));\n \n if (threeD)\n {\n \/\/ToDo\n }\n else\n {\n options.set(SurfaceSpinRenderer::generateCartesianSurfaceIndices(n_cells[0], n_cells[1]));\n }\n updateOptions(options);\n \n updateRenderers();\n CHECK_GL_ERROR;\n}\n\nGLSpins::~GLSpins() {\n}\n\nvoid GLSpins::updateSpins(const std::vector& positions, const std::vector& directions) {\n CHECK_GL_ERROR;\n\tfor (auto it : _renderers) {\n auto renderer = it.first;\n renderer->updateSpins(positions, directions);\n }\n CHECK_GL_ERROR;\n}\n\nvoid GLSpins::updateSystemGeometry(glm::vec3 bounds_min, glm::vec3 center, glm::vec3 bounds_max) {\n Options options;\n options.set(bounds_min);\n options.set(bounds_max);\n options.set(center);\n updateOptions(options);\n}\n\nvoid GLSpins::draw() {\n CHECK_GL_ERROR;\n \/\/ Clear the screen and the depth buffer\n auto background_color = _options.get();\n glClearColor(background_color.x, background_color.y, background_color.z, 1.0);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n \n Options options;\n options.set(_camera.cameraPosition());\n options.set(_camera.centerPosition());\n options.set(_camera.upVector());\n auto bounds_min = _options.get();\n auto bounds_max = _options.get();\n auto center = _options.get();\n options.set(center);\n options.set({\n fmax(fabs(bounds_max[0]-center[0]), 1.0),\n fmax(fabs(bounds_max[1]-center[1]), 1.0),\n fmax(fabs(bounds_max[2]-center[2]), 1.0)\n });\n updateOptions(options);\n \n glClear(GL_COLOR_BUFFER_BIT);\n for (auto it : _renderers) {\n auto renderer = it.first;\n auto viewport = it.second;\n glViewport((GLint)(viewport[0] * _width), (GLint)(viewport[1] * _height), (GLsizei)(viewport[2] * _width), (GLsizei)(viewport[3] * _height));\n glClear(GL_DEPTH_BUFFER_BIT);\n renderer->draw(viewport[2]\/viewport[3] * _camera.aspectRatio());\n }\n _fps_counter.tick();\n CHECK_GL_ERROR;\n}\n\nfloat GLSpins::getFramerate() const {\n return _fps_counter.getFramerate();\n}\n\nvoid GLSpins::mouseMove(const glm::vec2& position_before, const glm::vec2& position_after, GLSpins::CameraMovementModes mode) {\n if (position_before == position_after) {\n return;\n }\n auto delta = position_after-position_before;\n auto length = glm::length(delta);\n auto forward = glm::normalize(_camera.centerPosition() - _camera.cameraPosition());\n auto camera_distance = glm::length(_camera.centerPosition() - _camera.cameraPosition());\n auto up = glm::normalize(_camera.upVector());\n auto right = glm::normalize(glm::cross(forward, up));\n up = glm::normalize(glm::cross(right, forward));\n delta = glm::normalize(delta);\n switch (mode) {\n case GLSpins::CameraMovementModes::ROTATE: {\n auto axis = glm::normalize(delta.x * up + delta.y * right);\n float angle = -length * 0.1f \/ 180 * 3.14f;\n auto rotation_matrix = glm::rotate(angle, axis);\n up = glm::mat3(rotation_matrix) * up;\n forward = glm::mat3(rotation_matrix) * forward;\n _camera.lookAt(_camera.centerPosition() - forward * camera_distance,\n _camera.centerPosition(),\n up);\n }\n break;\n case GLSpins::CameraMovementModes::TRANSLATE: {\n float factor = 0.001f * camera_distance * length;\n auto translation = factor * (delta.y * up - delta.x * right);\n _camera.lookAt(_camera.cameraPosition() + translation,\n _camera.centerPosition() + translation,\n up);\n }\n break;\n default:\n break;\n }\n}\n\nvoid GLSpins::mouseScroll(const float& wheel_delta) {\n auto forward = _camera.centerPosition() - _camera.cameraPosition();\n float camera_distance = glm::length(forward);\n float new_camera_distance = (float)(1+0.02*wheel_delta)*camera_distance;\n if (new_camera_distance < 2) {\n new_camera_distance = 2;\n }\n \n auto camera_position = _camera.centerPosition() - new_camera_distance\/camera_distance * forward;\n _camera.lookAt(camera_position,\n _camera.centerPosition(),\n _camera.upVector());\n}\n\nvoid GLSpins::setFramebufferSize(float width, float height) {\n _width = width;\n _height = height;\n _camera.setAspectRatio(width \/ height);\n}\n\nvoid GLSpins::setCameraToDefault() {\n auto center = _options.get();\n _camera.lookAt(glm::vec3(center.x, center.y, center.z+30.0),\n center,\n glm::vec3(0.0f, 1.0f, 0.0f));\n}\n\nvoid GLSpins::setCameraToX() {\n auto center = _options.get();\n float camera_distance = glm::length(_camera.centerPosition() - _camera.cameraPosition());\n _camera.lookAt(glm::vec3(center.x+camera_distance, center.y, center.z),\n center,\n glm::vec3(0.0, 0.0, 1.0));\n}\n\nvoid GLSpins::setCameraToY() {\n auto center = _options.get();\n float camera_distance = glm::length(_camera.centerPosition() - _camera.cameraPosition());\n _camera.lookAt(glm::vec3(center.x, center.y+camera_distance, center.z),\n center,\n glm::vec3(1.0, 0.0, 0.0));\n}\n\nvoid GLSpins::setCameraToZ() {\n auto center = _options.get();\n float camera_distance = glm::length(_camera.centerPosition() - _camera.cameraPosition());\n _camera.lookAt(glm::vec3(center.x, center.y, center.z+camera_distance),\n center,\n glm::vec3(0.0, 1.0, 0.0));\n}\n\nstatic std::array locationToViewport(GLSpins::WidgetLocation location) {\n switch(location) {\n case GLSpins::WidgetLocation::BOTTOM_LEFT:\n return {0.0f, 0.0f, 0.2f, 0.2f};\n case GLSpins::WidgetLocation::BOTTOM_RIGHT:\n return {0.8f, 0.0f, 0.2f, 0.2f};\n case GLSpins::WidgetLocation::TOP_LEFT:\n return {0.0f, 0.8f, 0.2f, 0.2f};\n case GLSpins::WidgetLocation::TOP_RIGHT:\n return {0.8f, 0.8f, 0.2f, 0.2f};\n }\n return {0, 0, 1, 1};\n}\n\nvoid GLSpins::updateRenderers() {\n CHECK_GL_ERROR;\n bool show_bounding_box = options().get();\n bool show_coordinate_system = options().get();\n bool show_miniview = options().get();\n GLSpins::VisualizationMode mode = options().get();\n GLSpins::WidgetLocation coordinate_system_location = options().get();\n GLSpins::WidgetLocation miniview_location = options().get();\n _renderers.clear();\n std::shared_ptr main_renderer;\n switch (mode) {\n case VisualizationMode::ARROWS:\n main_renderer = std::make_shared();\n break;\n case VisualizationMode::SURFACE:\n main_renderer = std::make_shared();\n break;\n case VisualizationMode::SPHERE:\n main_renderer = std::make_shared();\n break;\n }\n if (show_bounding_box && mode != VisualizationMode::SPHERE) {\n std::vector> r = {\n main_renderer,\n std::make_shared()\n };\n main_renderer = std::make_shared(r);\n }\n _renderers.push_back({main_renderer, {0, 0, 1, 1}});\n \n if (show_coordinate_system) {\n std::shared_ptr renderer = std::make_shared();\n _renderers.push_back({renderer, locationToViewport(coordinate_system_location)});\n }\n if (show_miniview) {\n std::shared_ptr renderer;\n if (mode == VisualizationMode::SPHERE) {\n renderer = std::make_shared();\n if (show_bounding_box) {\n std::vector> r = {\n renderer,\n std::make_shared()\n };\n renderer = std::make_shared(r);\n }\n } else {\n renderer = std::make_shared();\n }\n _renderers.push_back({renderer, locationToViewport(miniview_location)});\n }\n\n for (auto it : _renderers) {\n auto renderer = it.first;\n renderer->updateOptions(options());\n }\n CHECK_GL_ERROR;\n}\n\nvoid GLSpins::updateOptions(const Options& options) {\n CHECK_GL_ERROR;\n auto changedOptions = _options.update(options);\n if (changedOptions.size() == 0) {\n return;\n }\n optionsHaveChanged(changedOptions);\n for (auto it : _renderers) {\n auto renderer = it.first;\n renderer->updateOptions(options);\n }\n CHECK_GL_ERROR;\n}\n\nvoid GLSpins::options(const Options& options) {\n _options = options;\n updateOptions(Options());\n}\n\nconst Options& GLSpins::options() const {\n return _options;\n}\n\nvoid GLSpins::optionsHaveChanged(const std::vector& changedOptions) {\n CHECK_GL_ERROR;\n bool renderersChanged = false;\n for (int option_id : changedOptions) {\n switch (option_id) {\n case GLSpins::Option::SHOW_MINIVIEW:\n case GLSpins::Option::SHOW_COORDINATE_SYSTEM:\n case GLSpins::Option::SHOW_BOUNDING_BOX:\n case GLSpins::Option::MINIVIEW_LOCATION:\n case GLSpins::Option::COORDINATE_SYSTEM_LOCATION:\n case GLSpins::Option::VISUALIZATION_MODE:\n renderersChanged = true;\n break;\n }\n }\n if (renderersChanged) {\n updateRenderers();\n }\n CHECK_GL_ERROR;\n}\nModified the camera alignment methods\n#ifndef __gl_h_\n#include \n#endif\n\n#include \n#include \n#include \n\n\/\/ Include GLM\n#include \"glm\/glm.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n#include \"glm\/gtc\/matrix_inverse.hpp\"\n#include \"glm\/gtx\/string_cast.hpp\"\n#include \n\n#include \"Camera.h\"\n#include \"GLSpins.h\"\n#include \"ISpinRenderer.h\"\n#include \"ArrowSpinRenderer.h\"\n#include \"SurfaceSpinRenderer.h\"\n#include \"SphereSpinRenderer.h\"\n#include \"BoundingBoxRenderer.h\"\n#include \"CombinedSpinRenderer.h\"\n#include \"CoordinateSystemRenderer.h\"\n#include \"utilities.h\"\n\n#ifndef M_PI\n\t#define M_PI 3.14159265358979323846\n#endif \/\/ !M_PI\n\nGLSpins::GLSpins(std::vector n_cells, bool threeD) {\n if (!gladLoadGL()) {\n std::cerr << \"Failed to initialize glad\" << std::endl;\n }\n \n \/\/ Reset any error potentially caused by glad\n glGetError();\n \n CHECK_GL_ERROR;\n setCameraToDefault();\n\n glClearColor(0.1f, 0.1f, 0.1f, 0.0f);\n glEnable(GL_DEPTH_TEST);\n glDepthFunc(GL_LESS);\n \n Options options;\n options.set(getColormapImplementation(\"hsv\"));\n \n if (threeD)\n {\n \/\/ToDo\n }\n else\n {\n options.set(SurfaceSpinRenderer::generateCartesianSurfaceIndices(n_cells[0], n_cells[1]));\n }\n updateOptions(options);\n \n updateRenderers();\n CHECK_GL_ERROR;\n}\n\nGLSpins::~GLSpins() {\n}\n\nvoid GLSpins::updateSpins(const std::vector& positions, const std::vector& directions) {\n CHECK_GL_ERROR;\n\tfor (auto it : _renderers) {\n auto renderer = it.first;\n renderer->updateSpins(positions, directions);\n }\n CHECK_GL_ERROR;\n}\n\nvoid GLSpins::updateSystemGeometry(glm::vec3 bounds_min, glm::vec3 center, glm::vec3 bounds_max) {\n Options options;\n options.set(bounds_min);\n options.set(bounds_max);\n options.set(center);\n updateOptions(options);\n}\n\nvoid GLSpins::draw() {\n CHECK_GL_ERROR;\n \/\/ Clear the screen and the depth buffer\n auto background_color = _options.get();\n glClearColor(background_color.x, background_color.y, background_color.z, 1.0);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n \n Options options;\n options.set(_camera.cameraPosition());\n options.set(_camera.centerPosition());\n options.set(_camera.upVector());\n auto bounds_min = _options.get();\n auto bounds_max = _options.get();\n auto center = _options.get();\n options.set(center);\n options.set({\n fmax(fabs(bounds_max[0]-center[0]), 1.0),\n fmax(fabs(bounds_max[1]-center[1]), 1.0),\n fmax(fabs(bounds_max[2]-center[2]), 1.0)\n });\n updateOptions(options);\n \n glClear(GL_COLOR_BUFFER_BIT);\n for (auto it : _renderers) {\n auto renderer = it.first;\n auto viewport = it.second;\n glViewport((GLint)(viewport[0] * _width), (GLint)(viewport[1] * _height), (GLsizei)(viewport[2] * _width), (GLsizei)(viewport[3] * _height));\n glClear(GL_DEPTH_BUFFER_BIT);\n renderer->draw(viewport[2]\/viewport[3] * _camera.aspectRatio());\n }\n _fps_counter.tick();\n CHECK_GL_ERROR;\n}\n\nfloat GLSpins::getFramerate() const {\n return _fps_counter.getFramerate();\n}\n\nvoid GLSpins::mouseMove(const glm::vec2& position_before, const glm::vec2& position_after, GLSpins::CameraMovementModes mode) {\n if (position_before == position_after) {\n return;\n }\n auto delta = position_after-position_before;\n auto length = glm::length(delta);\n auto forward = glm::normalize(_camera.centerPosition() - _camera.cameraPosition());\n auto camera_distance = glm::length(_camera.centerPosition() - _camera.cameraPosition());\n auto up = glm::normalize(_camera.upVector());\n auto right = glm::normalize(glm::cross(forward, up));\n up = glm::normalize(glm::cross(right, forward));\n delta = glm::normalize(delta);\n switch (mode) {\n case GLSpins::CameraMovementModes::ROTATE: {\n auto axis = glm::normalize(delta.x * up + delta.y * right);\n float angle = -length * 0.1f \/ 180 * 3.14f;\n auto rotation_matrix = glm::rotate(angle, axis);\n up = glm::mat3(rotation_matrix) * up;\n forward = glm::mat3(rotation_matrix) * forward;\n _camera.lookAt(_camera.centerPosition() - forward * camera_distance,\n _camera.centerPosition(),\n up);\n }\n break;\n case GLSpins::CameraMovementModes::TRANSLATE: {\n float factor = 0.001f * camera_distance * length;\n auto translation = factor * (delta.y * up - delta.x * right);\n _camera.lookAt(_camera.cameraPosition() + translation,\n _camera.centerPosition() + translation,\n up);\n }\n break;\n default:\n break;\n }\n}\n\nvoid GLSpins::mouseScroll(const float& wheel_delta) {\n auto forward = _camera.centerPosition() - _camera.cameraPosition();\n float camera_distance = glm::length(forward);\n float new_camera_distance = (float)(1+0.02*wheel_delta)*camera_distance;\n if (new_camera_distance < 2) {\n new_camera_distance = 2;\n }\n \n auto camera_position = _camera.centerPosition() - new_camera_distance\/camera_distance * forward;\n _camera.lookAt(camera_position,\n _camera.centerPosition(),\n _camera.upVector());\n}\n\nvoid GLSpins::setFramebufferSize(float width, float height) {\n _width = width;\n _height = height;\n _camera.setAspectRatio(width \/ height);\n}\n\nvoid GLSpins::setCameraToDefault() {\n auto center = _options.get();\n _camera.lookAt(glm::vec3(center.x, center.y, center.z+30.0),\n center,\n glm::vec3(0.0f, 1.0f, 0.0f));\n}\n\nvoid GLSpins::setCameraToX() {\n auto center = _options.get();\n float camera_distance = glm::length(_camera.centerPosition() - _camera.cameraPosition());\n _camera.lookAt(glm::vec3(center.x+camera_distance, center.y, center.z),\n center,\n glm::vec3(0.0, 0.0, 1.0));\n}\n\nvoid GLSpins::setCameraToY() {\n auto center = _options.get();\n float camera_distance = glm::length(_camera.centerPosition() - _camera.cameraPosition());\n _camera.lookAt(glm::vec3(center.x, center.y-camera_distance, center.z),\n center,\n glm::vec3(0.0, 0.0, 1.0));\n}\n\nvoid GLSpins::setCameraToZ() {\n auto center = _options.get();\n float camera_distance = glm::length(_camera.centerPosition() - _camera.cameraPosition());\n _camera.lookAt(glm::vec3(center.x, center.y, center.z+camera_distance),\n center,\n glm::vec3(0.0, 1.0, 0.0));\n}\n\nstatic std::array locationToViewport(GLSpins::WidgetLocation location) {\n switch(location) {\n case GLSpins::WidgetLocation::BOTTOM_LEFT:\n return {0.0f, 0.0f, 0.2f, 0.2f};\n case GLSpins::WidgetLocation::BOTTOM_RIGHT:\n return {0.8f, 0.0f, 0.2f, 0.2f};\n case GLSpins::WidgetLocation::TOP_LEFT:\n return {0.0f, 0.8f, 0.2f, 0.2f};\n case GLSpins::WidgetLocation::TOP_RIGHT:\n return {0.8f, 0.8f, 0.2f, 0.2f};\n }\n return {0, 0, 1, 1};\n}\n\nvoid GLSpins::updateRenderers() {\n CHECK_GL_ERROR;\n bool show_bounding_box = options().get();\n bool show_coordinate_system = options().get();\n bool show_miniview = options().get();\n GLSpins::VisualizationMode mode = options().get();\n GLSpins::WidgetLocation coordinate_system_location = options().get();\n GLSpins::WidgetLocation miniview_location = options().get();\n _renderers.clear();\n std::shared_ptr main_renderer;\n switch (mode) {\n case VisualizationMode::ARROWS:\n main_renderer = std::make_shared();\n break;\n case VisualizationMode::SURFACE:\n main_renderer = std::make_shared();\n break;\n case VisualizationMode::SPHERE:\n main_renderer = std::make_shared();\n break;\n }\n if (show_bounding_box && mode != VisualizationMode::SPHERE) {\n std::vector> r = {\n main_renderer,\n std::make_shared()\n };\n main_renderer = std::make_shared(r);\n }\n _renderers.push_back({main_renderer, {0, 0, 1, 1}});\n \n if (show_coordinate_system) {\n std::shared_ptr renderer = std::make_shared();\n _renderers.push_back({renderer, locationToViewport(coordinate_system_location)});\n }\n if (show_miniview) {\n std::shared_ptr renderer;\n if (mode == VisualizationMode::SPHERE) {\n renderer = std::make_shared();\n if (show_bounding_box) {\n std::vector> r = {\n renderer,\n std::make_shared()\n };\n renderer = std::make_shared(r);\n }\n } else {\n renderer = std::make_shared();\n }\n _renderers.push_back({renderer, locationToViewport(miniview_location)});\n }\n\n for (auto it : _renderers) {\n auto renderer = it.first;\n renderer->updateOptions(options());\n }\n CHECK_GL_ERROR;\n}\n\nvoid GLSpins::updateOptions(const Options& options) {\n CHECK_GL_ERROR;\n auto changedOptions = _options.update(options);\n if (changedOptions.size() == 0) {\n return;\n }\n optionsHaveChanged(changedOptions);\n for (auto it : _renderers) {\n auto renderer = it.first;\n renderer->updateOptions(options);\n }\n CHECK_GL_ERROR;\n}\n\nvoid GLSpins::options(const Options& options) {\n _options = options;\n updateOptions(Options());\n}\n\nconst Options& GLSpins::options() const {\n return _options;\n}\n\nvoid GLSpins::optionsHaveChanged(const std::vector& changedOptions) {\n CHECK_GL_ERROR;\n bool renderersChanged = false;\n for (int option_id : changedOptions) {\n switch (option_id) {\n case GLSpins::Option::SHOW_MINIVIEW:\n case GLSpins::Option::SHOW_COORDINATE_SYSTEM:\n case GLSpins::Option::SHOW_BOUNDING_BOX:\n case GLSpins::Option::MINIVIEW_LOCATION:\n case GLSpins::Option::COORDINATE_SYSTEM_LOCATION:\n case GLSpins::Option::VISUALIZATION_MODE:\n renderersChanged = true;\n break;\n }\n }\n if (renderersChanged) {\n updateRenderers();\n }\n CHECK_GL_ERROR;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \n\n\nnamespace TuneBench {\n\nCorrelatorConf::CorrelatorConf() : isa::OpenCL::KernelConf(), width(1), height(1) {}\n\nstd::string CorrelatorConf::print() const {\n return std::to_string(width) + \" \" + std::to_string(height) + \" \" + isa::OpenCL::KernelConf::print();\n}\n\nstd::string * getCorrelatorOpenCL(const CorrelatorConf & conf, const std::string & dataName, const unsigned int padding, const unsigned int nrChannels, const unsigned int nrStations, const unsigned int nrSamples, const unsigned int nrPolarizations) {\n std::string * code = new std::string();\n\n \/\/ Begin kernel's template\n *code = \"__kernel void correlator(__global const \" + dataName + \"4 * const restrict input, __global \" + dataName + \"8 * const restrict output, __global const unsigned int * const restrict cellMapX, __global const unsigned int * const restrict cellMapY) {\\n\"\n \"const unsigned int cell = (get_group_id(0) * \" + std::to_string(conf.getNrThreadsD0() * conf.getNrItemsD0()) + \") + get_local_id(0);\\n\"\n \"const unsigned int channel = (get_group_id(2) * \" + std::to_string(conf.getNrThreadsD2()) + \") + get_local_id(2);\\n\"\n \"const unsigned int baseStationX = cellMapX[cell];\\n\"\n \"const unsigned int baseStationY = cellMapY[cell];\\n\"\n \"<%DEFINE_STATION%>\"\n \"<%DEFINE_CELL%>\"\n \"\\n\"\n \"\/\/ Compute\\n\"\n \"for ( unsigned int sample = 0; sample < \" + std::to_string(nrSamples) + \"; sample += \" + std::to_string(conf.getNrItemsD1()) + \" ) {\\n\"\n \"<%LOAD_AND_COMPUTE%>\"\n \"}\\n\"\n \"<%STORE%>\"\n \"}\\n\";\n std::string defineStationX_sTemplate = dataName + \"4 sampleStation<%STATION%>XP0 = (\" + dataName + \"4)(0.0);\\n\";\n std::string defineStationY_sTemplate = dataName + \"4 sampleStation<%STATION%>YP1 = (\" + dataName + \"4)(0.0);\\n\";\n std::string defineCell_sTemplate = dataName + \"8 accumulator<%CELL%> = (\" + dataName + \"8)(0.0);\\n\";\n std::string loadX_sTemplate = \"sampleStation<%STATION%>XP0 = input[(channel * \" + std::to_string(nrStations * isa::utils::pad(nrSamples, padding \/ 4)) + \") + ((baseStationX + <%WIDTH%>) * \" + std::to_string(isa::utils::pad(nrSamples, padding \/ 4)) + \") + (sample + <%OFFSETD1%>)];\\n\"\n \"sampleStation<%STATION%>XP1 = input[(channel * \" + std::to_string(nrStations * isa::utils::pad(nrSamples, padding \/ 4)) + \") + ((baseStationX + <%WIDTH%>) * \" + std::to_string(isa::utils::pad(nrSamples, padding \/ 4)) + \") + (sample + <%OFFSETD1%>)];\\n\";\n std::string loadY_sTemplate = \"sampleStation<%STATION%>YP0 = input[(channel * \" + std::to_string(nrStations * isa::utils::pad(nrSamples, padding \/ 4)) + \") + ((baseStationY + <%HEIGHT%>) * \" + std::to_string(isa::utils::pad(nrSamples, padding \/ 4)) + \") + (sample + <%OFFSETD1%>)];\\n\"\n \"sampleStation<%STATION%>YP1 = input[(channel * \" + std::to_string(nrStations * isa::utils::pad(nrSamples, padding \/ 4)) + \") + ((baseStationY + <%HEIGHT%>) * \" + std::to_string(isa::utils::pad(nrSamples, padding \/ 4)) + \") + (sample + <%OFFSETD1%>)];\\n\";\n std::vector< std::string > compute_sTemplate(8);\n compute_sTemplate[0] = \"accumulator<%CELL%>.s0 += (sampleStation<%STATION%>P0.x * sampleStation<%STATION%>P1.x) - (sampleStation<%STATION%>P0.y * (-sampleStation<%STATION%>P1.y));\\n\";\n compute_sTemplate[1] = \"accumulator<%CELL%>.s1 += (sampleStation<%STATION%>P0.x * (-sampleStation<%STATION%>P1.y)) + (sampleStation<%STATION%>P0.y * sampleStation<%STATION%>P1.x);\\n\";\n compute_sTemplate[2] = \"accumulator<%CELL%>.s2 += (sampleStation<%STATION%>P0.x * sampleStation<%STATION%>P1.z) - (sampleStation<%STATION%>P0.y * (-sampleStation<%STATION%>P1.w));\\n\";\n compute_sTemplate[3] = \"accumulator<%CELL%>.s3 += (sampleStation<%STATION%>P0.x * (-sampleStation<%STATION%>P1.w)) + (sampleStation<%STATION%>P0.y * sampleStation<%STATION%>P1.z);\\n\";\n compute_sTemplate[4] = \"accumulator<%CELL%>.s4 += (sampleStation<%STATION%>P0.z * sampleStation<%STATION%>P1.x) - (sampleStation<%STATION%>P0.w * (-sampleStation<%STATION%>P1.y));\\n\";\n compute_sTemplate[5] = \"accumulator<%CELL%>.s5 += (sampleStation<%STATION%>P0.z * (-sampleStation<%STATION%>P1.y)) + (sampleStation<%STATION%>P0.w * sampleStation<%STATION%>P1.x);\\n\";\n compute_sTemplate[6] = \"accumulator<%CELL%>.s6 += (sampleStation<%STATION%>P0.z * sampleStation<%STATION%>P1.z) - (sampleStation<%STATION%>P0.w * (-sampleStation<%STATION%>P1.w));\\n\";\n compute_sTemplate[7] = \"accumulator<%CELL%>.s7 += (sampleStation<%STATION%>P0.z * (-sampleStation<%STATION%>P1.w)) + (sampleStation<%STATION%>P0.w * sampleStation<%STATION%>P1.z);\\n\";\n std::string store_sTemplate = \"output[(((((stationY + <%HEIGHT%>) * (stationY + <%HEIGHT%> + 1)) \/ 2) + stationX + <%WIDTH%>) * \" + std::to_string(nrChannels) + \") + channel] = accumulator<%CELL%>;\\n\";\n \/\/ End kernel's template\n\n std::string * defineStation_s = new std::string();\n std::string * defineCell_s = new std::string();\n std::string * loadCompute_s = new std::string();\n std::string * store_s = new std::string();\n std::string * temp = 0;\n std::string empty_s = \"\";\n\n for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) {\n std::string width_s = std::to_string(width);\n\n temp = isa::utils::replace(&defineStationX_sTemplate, \"<%STATION%>\", width_s);\n defineStation_s->append(*temp);\n delete temp;\n }\n for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) {\n std::string height_s = std::to_string(height);\n\n temp = isa::utils::replace(&defineStationY_sTemplate, \"<%STATION%>\", height_s);\n defineStation_s->append(*temp);\n delete temp;\n }\n for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) {\n for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) {\n std::string cell_s = std::to_string(width) + std::to_string(height);\n std::string width_s = std::to_string(width);\n std::string height_s = std::to_string(height);\n\n temp = isa::utils::replace(&defineCell_sTemplate, \"<%CELL%>\", cell_s);\n defineCell_s->append(*temp);\n delete temp;\n temp = isa::utils::replace(&store_sTemplate, \"<%WIDTH%>\", width_s);\n temp = isa::utils::replace(temp, \"<%HEIGHT%>\", height_s, true);\n store_s->append(*temp);\n delete temp;\n }\n }\n for ( unsigned int sample = 0; sample < conf.getNrItemsD1(); sample++ ) {\n std::string offsetD1_s = std::to_string(sample);\n\n for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) {\n std::string width_s = std::to_string(width);\n\n if ( width == 0 ) {\n temp = isa::utils::replace(&loadX_sTemplate, \"+ <%WIDTH%>\", empty_s);\n } else {\n temp = isa::utils::replace(&loadX_sTemplate, \"<%WIDTH%>\", width_s);\n }\n temp = isa::utils::replace(temp, \"<%STATION%>\", width_s, true);\n loadCompute_s->append(*temp);\n delete temp;\n }\n for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) {\n std::string height_s = std::to_string(height);\n\n if ( height == 0 ) {\n temp = isa::utils::replace(&loadY_sTemplate, \"+ <%WIDTH%>\", empty_s);\n } else {\n temp = isa::utils::replace(&loadY_sTemplate, \"<%WIDTH%>\", height_s);\n }\n temp = isa::utils::replace(temp, \"<%STATION%>\", height_s, true);\n loadCompute_s->append(*temp);\n delete temp;\n }\n loadCompute_s = isa::utils::replace(loadCompute_s, \"<%OFFSETD1%>\", offsetD1_s, true);\n for ( unsigned int computeStatement = 0; computeStatement < 8; computeStatement++ ) {\n for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) {\n for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) {\n std::string cell_s = std::to_string(width) + std::to_string(height);\n\n temp = isa::utils::replace(&compute_sTemplate[computeStatement], \"<%CELL%>\", cell_s);\n loadCompute_s->append(*temp);\n delete temp;\n }\n }\n }\n }\n\n code = isa::utils::replace(code, \"<%DEFINE_STATION%>\", *defineStation_s, true);\n code = isa::utils::replace(code, \"<%DEFINE_CELL%>\", *defineCell_s, true);\n code = isa::utils::replace(code, \"<%LOAD_AND_COMPUTE%>\", *loadCompute_s, true);\n code = isa::utils::replace(code, \"<%STORE%>\", *store_s, true);\n delete defineStation_s;\n delete defineCell_s;\n delete loadCompute_s;\n delete store_s;\n\n return code;\n}\n\nunsigned int generateCellMap(const CorrelatorConf & conf, std::vector< unsigned int > & cellMapX, std::vector< unsigned int > & cellMapY, const unsigned int nrStations) {\n unsigned int nrCells = 0;\n\n cellMapX.clear();\n cellMapY.clear();\n for ( int stationY = nrStations - conf.getCellHeight(); stationY >= 0; stationY -= conf.getCellHeight() ) {\n for ( int stationX = 0; stationX + static_cast< int >(conf.getCellWidth()) - 1 <= stationY; stationX += conf.getCellWidth() ) {\n nrCells++;\n cellMapX.push_back(stationX);\n cellMapY.push_back(stationY);\n }\n }\n\n return nrCells;\n}\n\n}; \/\/ TuneBench\n\nCleaning the store statements.\/\/ Copyright 2016 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \n\n\nnamespace TuneBench {\n\nCorrelatorConf::CorrelatorConf() : isa::OpenCL::KernelConf(), width(1), height(1) {}\n\nstd::string CorrelatorConf::print() const {\n return std::to_string(width) + \" \" + std::to_string(height) + \" \" + isa::OpenCL::KernelConf::print();\n}\n\nstd::string * getCorrelatorOpenCL(const CorrelatorConf & conf, const std::string & dataName, const unsigned int padding, const unsigned int nrChannels, const unsigned int nrStations, const unsigned int nrSamples, const unsigned int nrPolarizations) {\n std::string * code = new std::string();\n\n \/\/ Begin kernel's template\n *code = \"__kernel void correlator(__global const \" + dataName + \"4 * const restrict input, __global \" + dataName + \"8 * const restrict output, __global const unsigned int * const restrict cellMapX, __global const unsigned int * const restrict cellMapY) {\\n\"\n \"const unsigned int cell = (get_group_id(0) * \" + std::to_string(conf.getNrThreadsD0() * conf.getNrItemsD0()) + \") + get_local_id(0);\\n\"\n \"const unsigned int channel = (get_group_id(2) * \" + std::to_string(conf.getNrThreadsD2()) + \") + get_local_id(2);\\n\"\n \"const unsigned int baseStationX = cellMapX[cell];\\n\"\n \"const unsigned int baseStationY = cellMapY[cell];\\n\"\n \"<%DEFINE_STATION%>\"\n \"<%DEFINE_CELL%>\"\n \"\\n\"\n \"\/\/ Compute\\n\"\n \"for ( unsigned int sample = 0; sample < \" + std::to_string(nrSamples) + \"; sample += \" + std::to_string(conf.getNrItemsD1()) + \" ) {\\n\"\n \"<%LOAD_AND_COMPUTE%>\"\n \"}\\n\"\n \"<%STORE%>\"\n \"}\\n\";\n std::string defineStationX_sTemplate = dataName + \"4 sampleStationX<%STATION%>P0 = (\" + dataName + \"4)(0.0);\\n\";\n std::string defineStationY_sTemplate = dataName + \"4 sampleStationY<%STATION%>P1 = (\" + dataName + \"4)(0.0);\\n\";\n std::string defineCell_sTemplate = dataName + \"8 accumulator<%CELL%> = (\" + dataName + \"8)(0.0);\\n\";\n std::string loadX_sTemplate = \"sampleStationX<%STATION%>P0 = input[(channel * \" + std::to_string(nrStations * isa::utils::pad(nrSamples, padding \/ 4)) + \") + ((baseStationX + <%WIDTH%>) * \" + std::to_string(isa::utils::pad(nrSamples, padding \/ 4)) + \") + (sample + <%OFFSETD1%>)];\\n\"\n \"sampleStationX<%STATION%>P1 = input[(channel * \" + std::to_string(nrStations * isa::utils::pad(nrSamples, padding \/ 4)) + \") + ((baseStationX + <%WIDTH%>) * \" + std::to_string(isa::utils::pad(nrSamples, padding \/ 4)) + \") + (sample + <%OFFSETD1%>)];\\n\";\n std::string loadY_sTemplate = \"sampleStationY<%STATION%>P0 = input[(channel * \" + std::to_string(nrStations * isa::utils::pad(nrSamples, padding \/ 4)) + \") + ((baseStationY + <%HEIGHT%>) * \" + std::to_string(isa::utils::pad(nrSamples, padding \/ 4)) + \") + (sample + <%OFFSETD1%>)];\\n\"\n \"sampleStationY<%STATION%>P1 = input[(channel * \" + std::to_string(nrStations * isa::utils::pad(nrSamples, padding \/ 4)) + \") + ((baseStationY + <%HEIGHT%>) * \" + std::to_string(isa::utils::pad(nrSamples, padding \/ 4)) + \") + (sample + <%OFFSETD1%>)];\\n\";\n std::vector< std::string > compute_sTemplate(8);\n compute_sTemplate[0] = \"accumulator<%CELL%>.s0 += (sampleStation<%STATION%>P0.x * sampleStation<%STATION%>P1.x) - (sampleStation<%STATION%>P0.y * (-sampleStation<%STATION%>P1.y));\\n\";\n compute_sTemplate[1] = \"accumulator<%CELL%>.s1 += (sampleStation<%STATION%>P0.x * (-sampleStation<%STATION%>P1.y)) + (sampleStation<%STATION%>P0.y * sampleStation<%STATION%>P1.x);\\n\";\n compute_sTemplate[2] = \"accumulator<%CELL%>.s2 += (sampleStation<%STATION%>P0.x * sampleStation<%STATION%>P1.z) - (sampleStation<%STATION%>P0.y * (-sampleStation<%STATION%>P1.w));\\n\";\n compute_sTemplate[3] = \"accumulator<%CELL%>.s3 += (sampleStation<%STATION%>P0.x * (-sampleStation<%STATION%>P1.w)) + (sampleStation<%STATION%>P0.y * sampleStation<%STATION%>P1.z);\\n\";\n compute_sTemplate[4] = \"accumulator<%CELL%>.s4 += (sampleStation<%STATION%>P0.z * sampleStation<%STATION%>P1.x) - (sampleStation<%STATION%>P0.w * (-sampleStation<%STATION%>P1.y));\\n\";\n compute_sTemplate[5] = \"accumulator<%CELL%>.s5 += (sampleStation<%STATION%>P0.z * (-sampleStation<%STATION%>P1.y)) + (sampleStation<%STATION%>P0.w * sampleStation<%STATION%>P1.x);\\n\";\n compute_sTemplate[6] = \"accumulator<%CELL%>.s6 += (sampleStation<%STATION%>P0.z * sampleStation<%STATION%>P1.z) - (sampleStation<%STATION%>P0.w * (-sampleStation<%STATION%>P1.w));\\n\";\n compute_sTemplate[7] = \"accumulator<%CELL%>.s7 += (sampleStation<%STATION%>P0.z * (-sampleStation<%STATION%>P1.w)) + (sampleStation<%STATION%>P0.w * sampleStation<%STATION%>P1.z);\\n\";\n std::string store_sTemplate = \"output[(((((stationY + <%HEIGHT%>) * (stationY + <%HEIGHT%> + 1)) \/ 2) + stationX + <%WIDTH%>) * \" + std::to_string(nrChannels) + \") + channel] = accumulator<%CELL%>;\\n\";\n \/\/ End kernel's template\n\n std::string * defineStation_s = new std::string();\n std::string * defineCell_s = new std::string();\n std::string * loadCompute_s = new std::string();\n std::string * store_s = new std::string();\n std::string * temp = 0;\n std::string empty_s = \"\";\n\n for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) {\n std::string width_s = std::to_string(width);\n\n temp = isa::utils::replace(&defineStationX_sTemplate, \"<%STATION%>\", width_s);\n defineStation_s->append(*temp);\n delete temp;\n }\n for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) {\n std::string height_s = std::to_string(height);\n\n temp = isa::utils::replace(&defineStationY_sTemplate, \"<%STATION%>\", height_s);\n defineStation_s->append(*temp);\n delete temp;\n }\n for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) {\n for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) {\n std::string cell_s = std::to_string(width) + std::to_string(height);\n std::string width_s = std::to_string(width);\n std::string height_s = std::to_string(height);\n\n temp = isa::utils::replace(&defineCell_sTemplate, \"<%CELL%>\", cell_s);\n defineCell_s->append(*temp);\n delete temp;\n if ( width == 0 ) {\n temp = isa::utils::replace(&store_sTemplate, \" + <%WIDTH%>\", empty_s);\n } else {\n temp = isa::utils::replace(&store_sTemplate, \"<%WIDTH%>\", width_s);\n }\n if ( height == 0 ) {\n temp = isa::utils::replace(temp, \" + <%HEIGHT%>\", empty_s, true);\n } else {\n temp = isa::utils::replace(temp, \"<%HEIGHT%>\", height_s, true);\n }\n temp = isa::utils::replace(temp, \"<%CELL%>\", cell_s, true);\n store_s->append(*temp);\n delete temp;\n }\n }\n for ( unsigned int sample = 0; sample < conf.getNrItemsD1(); sample++ ) {\n std::string offsetD1_s = std::to_string(sample);\n\n for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) {\n std::string width_s = std::to_string(width);\n\n if ( width == 0 ) {\n temp = isa::utils::replace(&loadX_sTemplate, \"+ <%WIDTH%>\", empty_s);\n } else {\n temp = isa::utils::replace(&loadX_sTemplate, \"<%WIDTH%>\", width_s);\n }\n temp = isa::utils::replace(temp, \"<%STATION%>\", width_s, true);\n loadCompute_s->append(*temp);\n delete temp;\n }\n for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) {\n std::string height_s = std::to_string(height);\n\n if ( height == 0 ) {\n temp = isa::utils::replace(&loadY_sTemplate, \"+ <%WIDTH%>\", empty_s);\n } else {\n temp = isa::utils::replace(&loadY_sTemplate, \"<%WIDTH%>\", height_s);\n }\n temp = isa::utils::replace(temp, \"<%STATION%>\", height_s, true);\n loadCompute_s->append(*temp);\n delete temp;\n }\n loadCompute_s = isa::utils::replace(loadCompute_s, \"<%OFFSETD1%>\", offsetD1_s, true);\n for ( unsigned int computeStatement = 0; computeStatement < 8; computeStatement++ ) {\n for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) {\n for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) {\n std::string cell_s = std::to_string(width) + std::to_string(height);\n\n temp = isa::utils::replace(&compute_sTemplate[computeStatement], \"<%CELL%>\", cell_s);\n loadCompute_s->append(*temp);\n delete temp;\n }\n }\n }\n }\n\n code = isa::utils::replace(code, \"<%DEFINE_STATION%>\", *defineStation_s, true);\n code = isa::utils::replace(code, \"<%DEFINE_CELL%>\", *defineCell_s, true);\n code = isa::utils::replace(code, \"<%LOAD_AND_COMPUTE%>\", *loadCompute_s, true);\n code = isa::utils::replace(code, \"<%STORE%>\", *store_s, true);\n delete defineStation_s;\n delete defineCell_s;\n delete loadCompute_s;\n delete store_s;\n\n return code;\n}\n\nunsigned int generateCellMap(const CorrelatorConf & conf, std::vector< unsigned int > & cellMapX, std::vector< unsigned int > & cellMapY, const unsigned int nrStations) {\n unsigned int nrCells = 0;\n\n cellMapX.clear();\n cellMapY.clear();\n for ( int stationY = nrStations - conf.getCellHeight(); stationY >= 0; stationY -= conf.getCellHeight() ) {\n for ( int stationX = 0; stationX + static_cast< int >(conf.getCellWidth()) - 1 <= stationY; stationX += conf.getCellWidth() ) {\n nrCells++;\n cellMapX.push_back(stationX);\n cellMapY.push_back(stationY);\n }\n }\n\n return nrCells;\n}\n\n}; \/\/ TuneBench\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace nix;\nusing namespace nix::base;\n\n\n\/\/-------------------------------------------------------\n\/\/ Implementation of Dimension\n\/\/-------------------------------------------------------\n\nDimension::Dimension()\n : ImplContainer()\n{\n}\n\n\nDimension::Dimension(const shared_ptr &p_impl)\n : ImplContainer(p_impl)\n{\n}\n\n\nDimension::Dimension(shared_ptr &&ptr)\n : ImplContainer(std::move(ptr))\n{\n}\n\n\nDimension::Dimension(const Dimension &other)\n : ImplContainer(other)\n{\n}\n\n\nDimension::Dimension(const SampledDimension &other)\n : ImplContainer(dynamic_pointer_cast(other.impl()))\n{\n}\n\n\nDimension::Dimension(const RangeDimension &other)\n : ImplContainer(dynamic_pointer_cast(other.impl()))\n{\n}\n\n\nDimension::Dimension(const SetDimension &other)\n : ImplContainer(dynamic_pointer_cast(other.impl()))\n{\n}\n\n\nSetDimension Dimension::asSetDimension() const {\n if (dimensionType() != DimensionType::Set) {\n throw IncompatibleDimensions(\"Dimension is not of type Set and thus cannot be cast to this type\", \"asSetDimension\");\n }\n return SetDimension(std::dynamic_pointer_cast(impl()));\n}\n\n\nSampledDimension Dimension::asSampledDimension() const {\n if (dimensionType() != DimensionType::Sample) {\n throw IncompatibleDimensions(\"Dimension is not of type Sample and thus cannot be cast to this type\", \"asSampledDimension\");\n }\n return SampledDimension(std::dynamic_pointer_cast(impl()));\n}\n\n\nRangeDimension Dimension::asRangeDimension() const {\n if (dimensionType() != DimensionType::Range) {\n throw IncompatibleDimensions(\"Dimension is not of type Range and thus cannot be cast to this type\", \"asRangeDimension\");\n }\n return RangeDimension(std::dynamic_pointer_cast(impl()));\n}\n\n\nDimension& Dimension::operator=(const SampledDimension &other) {\n shared_ptr tmp(dynamic_pointer_cast(other.impl()));\n\n if (impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\nDimension& Dimension::operator=(const RangeDimension &other) {\n shared_ptr tmp(dynamic_pointer_cast(other.impl()));\n\n if (impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\nDimension& Dimension::operator=(const SetDimension &other) {\n shared_ptr tmp(dynamic_pointer_cast(other.impl()));\n\n if (impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\/\/-------------------------------------------------------\n\/\/ Implementation of SampledDimension\n\/\/-------------------------------------------------------\n\nSampledDimension::SampledDimension()\n : ImplContainer()\n{\n}\n\n\nSampledDimension::SampledDimension(const std::shared_ptr &p_impl)\n : ImplContainer(p_impl)\n{\n}\n\n\nSampledDimension::SampledDimension(std::shared_ptr &&ptr)\n : ImplContainer(std::move(ptr))\n{\n}\n\n\n\nSampledDimension::SampledDimension(const SampledDimension &other)\n : ImplContainer(other)\n{\n}\n\n\nvoid SampledDimension::unit(const std::string &unit) {\n if (!(util::isSIUnit(unit))) {\n throw InvalidUnit(\"Unit is not a SI unit. Note: so far, only atomic SI units are supported.\",\n \"SampledDimension::unit(const string &unit)\");\n }\n backend()->unit(unit);\n}\n\n\nvoid SampledDimension::samplingInterval(double interval) {\n if (interval <= 0.0) {\n throw std::runtime_error(\"SampledDimenion::samplingInterval: Sampling intervals must be larger than 0.0!\");\n }\n backend()->samplingInterval(interval);\n}\n\n\nsize_t SampledDimension::indexOf(const double position) const {\n int index;\n double offset = backend()->offset() ? *(backend()->offset()) : 0.0;\n double sampling_interval = backend()->samplingInterval();\n index = round(( position - offset) \/ sampling_interval);\n if (index < 0) {\n throw nix::OutOfBounds(\"Position is out of bounds of this dimension!\", 0);\n }\n return static_cast(index);\n}\n\n\ndouble SampledDimension::positionAt(const size_t index) const {\n double offset = backend()->offset() ? *(backend()->offset()) : 0.0;\n double sampling_interval = backend()->samplingInterval();\n return index * sampling_interval + offset;\n}\n\n\nvector SampledDimension::axis(const size_t count, const size_t startIndex) const {\n vector axis(count);\n double offset = backend()->offset() ? *(backend()->offset()) : 0.0;\n double sampling_interval = backend()->samplingInterval();\n for (size_t i = 0; i < axis.size(); ++i) {\n axis[i] = (i + startIndex) * sampling_interval + offset;\n }\n return axis;\n}\n\n\nSampledDimension& SampledDimension::operator=(const SampledDimension &other) {\n shared_ptr tmp(other.impl());\n\n if (impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\nSampledDimension& SampledDimension::operator=(const Dimension &other) {\n shared_ptr tmp(dynamic_pointer_cast(other.impl()));\n\n if (other.dimensionType() == DimensionType::Sample && impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\/\/-------------------------------------------------------\n\/\/ Implementation of SetDimension\n\/\/-------------------------------------------------------\n\n\nSetDimension::SetDimension()\n : ImplContainer()\n{\n}\n\n\nSetDimension::SetDimension(const std::shared_ptr &p_impl)\n : ImplContainer(p_impl)\n{\n}\n\nSetDimension::SetDimension(std::shared_ptr &&ptr)\n : ImplContainer(std::move(ptr))\n{\n}\n\n\nSetDimension::SetDimension(const SetDimension &other)\n : ImplContainer(other)\n{\n}\n\n\nSetDimension& SetDimension::operator=(const SetDimension &other) {\n shared_ptr tmp(other.impl());\n\n if (impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\nSetDimension& SetDimension::operator=(const Dimension &other) {\n shared_ptr tmp(dynamic_pointer_cast(other.impl()));\n\n if (other.dimensionType() == DimensionType::Set && impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\/\/-------------------------------------------------------\n\/\/ Implementation of RangeDimension\n\/\/-------------------------------------------------------\n\n\nRangeDimension::RangeDimension()\n : ImplContainer()\n{\n}\n\n\nRangeDimension::RangeDimension(const std::shared_ptr &p_impl)\n : ImplContainer(p_impl)\n{\n}\n\nRangeDimension::RangeDimension(std::shared_ptr &&ptr)\n : ImplContainer(std::move(ptr))\n{\n}\n\n\nRangeDimension::RangeDimension(const RangeDimension &other)\n : ImplContainer(other)\n{\n}\n\n\nvoid RangeDimension::unit(const std::string &unit) {\n if (!(util::isSIUnit(unit))) {\n throw InvalidUnit(\"Unit is not an atomic SI. Note: So far composite units are not supported\", \"RangeDimension::unit(const string &unit)\");\n }\n backend()->unit(unit);\n}\n\n\nvoid RangeDimension::ticks(const std::vector &ticks) {\n if (!std::is_sorted(ticks.begin(), ticks.end())) {\n std::string caller = \"Range::ticks()\";\n throw UnsortedTicks(caller);\n }\n backend()->ticks(ticks);\n}\n\n\ndouble RangeDimension::tickAt(const size_t index) const {\n vector ticks = this->ticks();\n if (index >= ticks.size()) {\n throw nix::OutOfBounds(\"RangeDimension::tickAt: Given index is out of bounds!\", index);\n }\n return ticks[index];\n}\n\n\nsize_t RangeDimension::indexOf(const double position) const {\n size_t index;\n vector ticks = this->ticks();\n if (position < *ticks.begin()) {\n return 0;\n } else if (position > *prev(ticks.end())) {\n return prev(ticks.end()) - ticks.begin();\n }\n vector::iterator low = std::lower_bound (ticks.begin(), ticks.end(), position);\n if (*low == position) {\n return low - ticks.begin();\n }\n if (low != ticks.begin() && *low != position) {\n double diff_low, diff_before;\n diff_low = fabs(*low - position);\n diff_before = fabs(*(std::prev(low)) - position);\n if (diff_low < diff_before) {\n index = low - ticks.begin();\n } else {\n index = low - ticks.begin() - 1;\n }\n return index;\n } else {\n return low - ticks.begin();\n }\n}\n\n\nvector RangeDimension::axis(const size_t count, const size_t startIndex) const {\n vector ticks = this->ticks();\n if ((startIndex + count) > ticks.size()) {\n throw nix::OutOfBounds(\"RangeDimension::axis: Count is invalid, reaches beyond the ticks stored in this dimension.\");\n } \n vector::const_iterator first = ticks.begin() + startIndex;\n vector axis(first, first + count);\n return axis;\n}\n\n\nRangeDimension& RangeDimension::operator=(const RangeDimension &other) {\n shared_ptr tmp(other.impl());\n\n if (impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\nRangeDimension& RangeDimension::operator=(const Dimension &other) {\n shared_ptr tmp(dynamic_pointer_cast(other.impl()));\n\n if (other.dimensionType() == DimensionType::Range && impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\n\n\nDimensions::indexOf: explicity cast result of round\/\/ Copyright (c) 2013, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace nix;\nusing namespace nix::base;\n\n\n\/\/-------------------------------------------------------\n\/\/ Implementation of Dimension\n\/\/-------------------------------------------------------\n\nDimension::Dimension()\n : ImplContainer()\n{\n}\n\n\nDimension::Dimension(const shared_ptr &p_impl)\n : ImplContainer(p_impl)\n{\n}\n\n\nDimension::Dimension(shared_ptr &&ptr)\n : ImplContainer(std::move(ptr))\n{\n}\n\n\nDimension::Dimension(const Dimension &other)\n : ImplContainer(other)\n{\n}\n\n\nDimension::Dimension(const SampledDimension &other)\n : ImplContainer(dynamic_pointer_cast(other.impl()))\n{\n}\n\n\nDimension::Dimension(const RangeDimension &other)\n : ImplContainer(dynamic_pointer_cast(other.impl()))\n{\n}\n\n\nDimension::Dimension(const SetDimension &other)\n : ImplContainer(dynamic_pointer_cast(other.impl()))\n{\n}\n\n\nSetDimension Dimension::asSetDimension() const {\n if (dimensionType() != DimensionType::Set) {\n throw IncompatibleDimensions(\"Dimension is not of type Set and thus cannot be cast to this type\", \"asSetDimension\");\n }\n return SetDimension(std::dynamic_pointer_cast(impl()));\n}\n\n\nSampledDimension Dimension::asSampledDimension() const {\n if (dimensionType() != DimensionType::Sample) {\n throw IncompatibleDimensions(\"Dimension is not of type Sample and thus cannot be cast to this type\", \"asSampledDimension\");\n }\n return SampledDimension(std::dynamic_pointer_cast(impl()));\n}\n\n\nRangeDimension Dimension::asRangeDimension() const {\n if (dimensionType() != DimensionType::Range) {\n throw IncompatibleDimensions(\"Dimension is not of type Range and thus cannot be cast to this type\", \"asRangeDimension\");\n }\n return RangeDimension(std::dynamic_pointer_cast(impl()));\n}\n\n\nDimension& Dimension::operator=(const SampledDimension &other) {\n shared_ptr tmp(dynamic_pointer_cast(other.impl()));\n\n if (impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\nDimension& Dimension::operator=(const RangeDimension &other) {\n shared_ptr tmp(dynamic_pointer_cast(other.impl()));\n\n if (impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\nDimension& Dimension::operator=(const SetDimension &other) {\n shared_ptr tmp(dynamic_pointer_cast(other.impl()));\n\n if (impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\/\/-------------------------------------------------------\n\/\/ Implementation of SampledDimension\n\/\/-------------------------------------------------------\n\nSampledDimension::SampledDimension()\n : ImplContainer()\n{\n}\n\n\nSampledDimension::SampledDimension(const std::shared_ptr &p_impl)\n : ImplContainer(p_impl)\n{\n}\n\n\nSampledDimension::SampledDimension(std::shared_ptr &&ptr)\n : ImplContainer(std::move(ptr))\n{\n}\n\n\n\nSampledDimension::SampledDimension(const SampledDimension &other)\n : ImplContainer(other)\n{\n}\n\n\nvoid SampledDimension::unit(const std::string &unit) {\n if (!(util::isSIUnit(unit))) {\n throw InvalidUnit(\"Unit is not a SI unit. Note: so far, only atomic SI units are supported.\",\n \"SampledDimension::unit(const string &unit)\");\n }\n backend()->unit(unit);\n}\n\n\nvoid SampledDimension::samplingInterval(double interval) {\n if (interval <= 0.0) {\n throw std::runtime_error(\"SampledDimenion::samplingInterval: Sampling intervals must be larger than 0.0!\");\n }\n backend()->samplingInterval(interval);\n}\n\n\nsize_t SampledDimension::indexOf(const double position) const {\n \/\/FIXME: should we use NDSSize::value_type here instead of ssize_t?\n \/\/FIXME: also, on the smae grounds, should the return not be NDSize::value_type?\n ssize_t index;\n double offset = backend()->offset() ? *(backend()->offset()) : 0.0;\n double sampling_interval = backend()->samplingInterval();\n index = static_cast(round(( position - offset) \/ sampling_interval));\n if (index < 0) {\n throw nix::OutOfBounds(\"Position is out of bounds of this dimension!\", 0);\n }\n return static_cast(index);\n}\n\n\ndouble SampledDimension::positionAt(const size_t index) const {\n double offset = backend()->offset() ? *(backend()->offset()) : 0.0;\n double sampling_interval = backend()->samplingInterval();\n return index * sampling_interval + offset;\n}\n\n\nvector SampledDimension::axis(const size_t count, const size_t startIndex) const {\n vector axis(count);\n double offset = backend()->offset() ? *(backend()->offset()) : 0.0;\n double sampling_interval = backend()->samplingInterval();\n for (size_t i = 0; i < axis.size(); ++i) {\n axis[i] = (i + startIndex) * sampling_interval + offset;\n }\n return axis;\n}\n\n\nSampledDimension& SampledDimension::operator=(const SampledDimension &other) {\n shared_ptr tmp(other.impl());\n\n if (impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\nSampledDimension& SampledDimension::operator=(const Dimension &other) {\n shared_ptr tmp(dynamic_pointer_cast(other.impl()));\n\n if (other.dimensionType() == DimensionType::Sample && impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\/\/-------------------------------------------------------\n\/\/ Implementation of SetDimension\n\/\/-------------------------------------------------------\n\n\nSetDimension::SetDimension()\n : ImplContainer()\n{\n}\n\n\nSetDimension::SetDimension(const std::shared_ptr &p_impl)\n : ImplContainer(p_impl)\n{\n}\n\nSetDimension::SetDimension(std::shared_ptr &&ptr)\n : ImplContainer(std::move(ptr))\n{\n}\n\n\nSetDimension::SetDimension(const SetDimension &other)\n : ImplContainer(other)\n{\n}\n\n\nSetDimension& SetDimension::operator=(const SetDimension &other) {\n shared_ptr tmp(other.impl());\n\n if (impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\nSetDimension& SetDimension::operator=(const Dimension &other) {\n shared_ptr tmp(dynamic_pointer_cast(other.impl()));\n\n if (other.dimensionType() == DimensionType::Set && impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\/\/-------------------------------------------------------\n\/\/ Implementation of RangeDimension\n\/\/-------------------------------------------------------\n\n\nRangeDimension::RangeDimension()\n : ImplContainer()\n{\n}\n\n\nRangeDimension::RangeDimension(const std::shared_ptr &p_impl)\n : ImplContainer(p_impl)\n{\n}\n\nRangeDimension::RangeDimension(std::shared_ptr &&ptr)\n : ImplContainer(std::move(ptr))\n{\n}\n\n\nRangeDimension::RangeDimension(const RangeDimension &other)\n : ImplContainer(other)\n{\n}\n\n\nvoid RangeDimension::unit(const std::string &unit) {\n if (!(util::isSIUnit(unit))) {\n throw InvalidUnit(\"Unit is not an atomic SI. Note: So far composite units are not supported\", \"RangeDimension::unit(const string &unit)\");\n }\n backend()->unit(unit);\n}\n\n\nvoid RangeDimension::ticks(const std::vector &ticks) {\n if (!std::is_sorted(ticks.begin(), ticks.end())) {\n std::string caller = \"Range::ticks()\";\n throw UnsortedTicks(caller);\n }\n backend()->ticks(ticks);\n}\n\n\ndouble RangeDimension::tickAt(const size_t index) const {\n vector ticks = this->ticks();\n if (index >= ticks.size()) {\n throw nix::OutOfBounds(\"RangeDimension::tickAt: Given index is out of bounds!\", index);\n }\n return ticks[index];\n}\n\n\nsize_t RangeDimension::indexOf(const double position) const {\n size_t index;\n vector ticks = this->ticks();\n if (position < *ticks.begin()) {\n return 0;\n } else if (position > *prev(ticks.end())) {\n return prev(ticks.end()) - ticks.begin();\n }\n vector::iterator low = std::lower_bound (ticks.begin(), ticks.end(), position);\n if (*low == position) {\n return low - ticks.begin();\n }\n if (low != ticks.begin() && *low != position) {\n double diff_low, diff_before;\n diff_low = fabs(*low - position);\n diff_before = fabs(*(std::prev(low)) - position);\n if (diff_low < diff_before) {\n index = low - ticks.begin();\n } else {\n index = low - ticks.begin() - 1;\n }\n return index;\n } else {\n return low - ticks.begin();\n }\n}\n\n\nvector RangeDimension::axis(const size_t count, const size_t startIndex) const {\n vector ticks = this->ticks();\n if ((startIndex + count) > ticks.size()) {\n throw nix::OutOfBounds(\"RangeDimension::axis: Count is invalid, reaches beyond the ticks stored in this dimension.\");\n } \n vector::const_iterator first = ticks.begin() + startIndex;\n vector axis(first, first + count);\n return axis;\n}\n\n\nRangeDimension& RangeDimension::operator=(const RangeDimension &other) {\n shared_ptr tmp(other.impl());\n\n if (impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\nRangeDimension& RangeDimension::operator=(const Dimension &other) {\n shared_ptr tmp(dynamic_pointer_cast(other.impl()));\n\n if (other.dimensionType() == DimensionType::Range && impl() != tmp) {\n std::swap(impl(), tmp);\n }\n\n return *this;\n}\n\n\n\n\n<|endoftext|>"} {"text":"coverity#705150 Missing break in switch<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#define WIN32_LEAN_AND_MEAN\n#include \n\n#include \n#include \n#include \n#include \n\n#pragma comment(lib, \"Shlwapi.lib\")\n#pragma comment(lib, \"Ole32.lib\")\n\nconst wchar_t* ProviderGUID = L\"{35788B9B-04AB-4B75-AB3A-1ED403AFC746}\";\n\nusing DllGetClassObjectT = HRESULT(const IID& rclsid, const IID& riid, void** ppv);\n\nBOOL SaveHBITMAPToFile(HBITMAP Bitmap, const char* Filename);\n\nint main(int argc, char** argv)\n{\n\tGUID clsid;\n\tIIDFromString(ProviderGUID, &clsid);\n\n\tHMODULE DLLHandle = LoadLibraryA(\"SaiThumbs.dll\");\n\n\tif( !DLLHandle )\n\t{\n\t\tstd::puts(\"can't open DLL\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tDllGetClassObjectT* DllGetClassObject = reinterpret_cast(GetProcAddress(\n\t\tDLLHandle, \"DllGetClassObject\"));\n\n\tif( DllGetClassObject == nullptr )\n\t{\n\t\tstd::puts(\"Failed: Unable to get DLLGetClassobject address\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tIClassFactory* ClassFactory = nullptr;\n\tHRESULT Result = DllGetClassObject(clsid, IID_IClassFactory, reinterpret_cast(&ClassFactory));\n\tif( Result != S_OK )\n\t{\n\t\tstd::printf(\"Failed: Unable to get IClassFactory: %08x\\n\", Result);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tIInitializeWithFile* InitWithFile;\n\tResult = ClassFactory->CreateInstance(nullptr, IID_IInitializeWithFile, reinterpret_cast(&InitWithFile));\n\tif( Result != S_OK )\n\t{\n\t\tstd::puts(\"Failed: Unable to get IInitializeWithFile\");\n\t\treturn EXIT_FAILURE;\n\t}\n\tClassFactory->Release();\n\n\tIThumbnailProvider* ThumbProvider;\n\tResult = InitWithFile->QueryInterface(IID_IThumbnailProvider, reinterpret_cast(&ThumbProvider));\n\tif( Result != S_OK )\n\t{\n\t\tstd::puts(\"Failed: Unable to get IThumbnailProvider\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tResult = InitWithFile->Initialize(L\".\/test.sai\", 0);\n\tInitWithFile->Release();\n\tif( Result != S_OK )\n\t{\n\t\tstd::puts(\"Failed: Unable to initilize IInitializeWithFile\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tHBITMAP ThumbImage;\n\tWTS_ALPHATYPE ThumbAlphaType;\n\tResult = ThumbProvider->GetThumbnail(256, &ThumbImage, &ThumbAlphaType);\n\tThumbProvider->Release();\n\tif( Result != S_OK )\n\t{\n\t\tstd::puts(\"Failed: GetThumbnail returned failure\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tSaveHBITMAPToFile(\n\t\tThumbImage,\n\t\t\".\/test.bmp\"\n\t);\n\n\treturn EXIT_SUCCESS;\n}\n\nBOOL SaveHBITMAPToFile(HBITMAP Bitmap, const char* Filename)\n{\n\tconst DWORD PaletteSize = 0;\n\tDWORD BmBitsSize = 0, HeaderSize = 0, Written = 0;\n\tBITMAP NewBitmap;\n\tBITMAPFILEHEADER Header;\n\tBITMAPINFOHEADER bi;\n\tHANDLE hOldPal2 = nullptr;\n\tHDC DeviceContext = CreateDC(TEXT(\"DISPLAY\"), nullptr, nullptr, nullptr);\n\tconst int Bits = GetDeviceCaps(DeviceContext, BITSPIXEL) * GetDeviceCaps(DeviceContext, PLANES);\n\tDeleteDC(DeviceContext);\n\tconst WORD BitCount = Bits;\n\tGetObject(Bitmap, sizeof(NewBitmap), reinterpret_cast(&NewBitmap));\n\tbi.biSize = sizeof(BITMAPINFOHEADER);\n\tbi.biWidth = NewBitmap.bmWidth;\n\tbi.biHeight = -NewBitmap.bmHeight;\n\tbi.biPlanes = 1;\n\tbi.biBitCount = BitCount;\n\tbi.biCompression = BI_RGB;\n\tbi.biSizeImage = 0;\n\tbi.biXPelsPerMeter = 0;\n\tbi.biYPelsPerMeter = 0;\n\tbi.biClrImportant = 0;\n\tbi.biClrUsed = 256;\n\tBmBitsSize = ((NewBitmap.bmWidth * BitCount + 31) & ~31) \/ 8\n\t\t* NewBitmap.bmHeight;\n\tconst HANDLE hDib = GlobalAlloc(GHND, BmBitsSize + PaletteSize + sizeof(BITMAPINFOHEADER));\n\tconst LPBITMAPINFOHEADER lpbi = static_cast(GlobalLock(hDib));\n\t*lpbi = bi;\n\n\tconst HANDLE hPal = GetStockObject(DEFAULT_PALETTE);\n\tif( hPal )\n\t{\n\t\tDeviceContext = GetDC(nullptr);\n\t\thOldPal2 = SelectPalette(DeviceContext, static_cast(hPal), FALSE);\n\t\tRealizePalette(DeviceContext);\n\t}\n\n\tGetDIBits(\n\t\tDeviceContext, Bitmap, 0, static_cast(NewBitmap.bmHeight),\n\t\treinterpret_cast(lpbi) + sizeof(BITMAPINFOHEADER)\n\t\t+ PaletteSize, reinterpret_cast(lpbi), DIB_RGB_COLORS);\n\n\tif( hOldPal2 )\n\t{\n\t\tSelectPalette(DeviceContext, static_cast(hOldPal2), TRUE);\n\t\tRealizePalette(DeviceContext);\n\t\tReleaseDC(nullptr, DeviceContext);\n\t}\n\n\tconst HANDLE FileHandle = CreateFileA(\n\t\tFilename, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,\n\t\tFILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);\n\n\tif( FileHandle == INVALID_HANDLE_VALUE )\n\t{\n\t\treturn FALSE;\n\t}\n\n\tHeader.bfType = 0x4D42;\n\tHeaderSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + PaletteSize + BmBitsSize;\n\tHeader.bfSize = HeaderSize;\n\tHeader.bfReserved1 = 0;\n\tHeader.bfReserved2 = 0;\n\tHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) +\n\t\tPaletteSize;\n\n\tWriteFile(FileHandle, reinterpret_cast(&Header), sizeof(BITMAPFILEHEADER), &Written, nullptr);\n\n\tWriteFile(FileHandle, reinterpret_cast(lpbi), HeaderSize, &Written, nullptr);\n\tGlobalUnlock(hDib);\n\tGlobalFree(hDib);\n\tCloseHandle(FileHandle);\n\treturn TRUE;\n}\nAdd unicode arguments#include \n#include \n#include \n\n#define WIN32_LEAN_AND_MEAN\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#pragma comment(lib, \"Shlwapi.lib\")\n#pragma comment(lib, \"Ole32.lib\")\n\nconst wchar_t* ProviderGUID = L\"{35788B9B-04AB-4B75-AB3A-1ED403AFC746}\";\n\nusing DllGetClassObjectT = HRESULT(const IID& rclsid, const IID& riid, void** ppv);\n\nBOOL SaveHBITMAPToFile(HBITMAP Bitmap, const wchar_t* Filename);\n\nint wmain(int argc, wchar_t *argv[], wchar_t *envp[])\n{\n\tif( argc < 3)\n\t{\n\t\tstd::wprintf(\n\t\t\tL\"Usage: %s (Sai File) (output.bmp)\\n\",\n\t\t\targv[0]\n\t\t);\n\t\treturn EXIT_FAILURE;\n\t}\n\tGUID clsid;\n\tIIDFromString(ProviderGUID, &clsid);\n\n\tconst HMODULE DLLHandle = LoadLibraryA(\"SaiThumbs.dll\");\n\n\tif( !DLLHandle )\n\t{\n\t\tstd::puts(\"Failed: Can't open DLL\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tDllGetClassObjectT* DllGetClassObject = reinterpret_cast(GetProcAddress(\n\t\tDLLHandle, \"DllGetClassObject\"));\n\n\tif( DllGetClassObject == nullptr )\n\t{\n\t\tstd::puts(\"Failed: Unable to get DLLGetClassobject address\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tIClassFactory* ClassFactory = nullptr;\n\tHRESULT Result = DllGetClassObject(clsid, IID_IClassFactory, reinterpret_cast(&ClassFactory));\n\tif( Result != S_OK )\n\t{\n\t\tstd::printf(\"Failed: Unable to get IClassFactory: %08x\\n\", Result);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tIInitializeWithFile* InitWithFile;\n\tResult = ClassFactory->CreateInstance(nullptr, IID_IInitializeWithFile, reinterpret_cast(&InitWithFile));\n\tif( Result != S_OK )\n\t{\n\t\tstd::puts(\"Failed: Unable to get IInitializeWithFile\");\n\t\treturn EXIT_FAILURE;\n\t}\n\tClassFactory->Release();\n\n\tIThumbnailProvider* ThumbProvider;\n\tResult = InitWithFile->QueryInterface(IID_IThumbnailProvider, reinterpret_cast(&ThumbProvider));\n\tif( Result != S_OK )\n\t{\n\t\tstd::puts(\"Failed: Unable to get IThumbnailProvider\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tResult = InitWithFile->Initialize(argv[1] , 0);\n\tInitWithFile->Release();\n\tif( Result != S_OK )\n\t{\n\t\tstd::puts(\"Failed: Unable to initilize IInitializeWithFile\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tHBITMAP ThumbImage;\n\tWTS_ALPHATYPE ThumbAlphaType;\n\tResult = ThumbProvider->GetThumbnail(256, &ThumbImage, &ThumbAlphaType);\n\tThumbProvider->Release();\n\tif( Result != S_OK )\n\t{\n\t\tstd::puts(\"Failed: GetThumbnail returned failure\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tSaveHBITMAPToFile(\n\t\tThumbImage,\n\t\targv[2]\n\t);\n\n\treturn EXIT_SUCCESS;\n}\n\nBOOL SaveHBITMAPToFile(HBITMAP Bitmap, const wchar_t* Filename)\n{\n\tconst DWORD PaletteSize = 0;\n\tDWORD BmBitsSize = 0, HeaderSize = 0, Written = 0;\n\tBITMAP NewBitmap;\n\tBITMAPFILEHEADER Header;\n\tBITMAPINFOHEADER bi;\n\tHANDLE hOldPal2 = nullptr;\n\tHDC DeviceContext = CreateDC(TEXT(\"DISPLAY\"), nullptr, nullptr, nullptr);\n\tconst int Bits = GetDeviceCaps(DeviceContext, BITSPIXEL) * GetDeviceCaps(DeviceContext, PLANES);\n\tDeleteDC(DeviceContext);\n\tconst WORD BitCount = Bits;\n\tGetObject(Bitmap, sizeof(NewBitmap), reinterpret_cast(&NewBitmap));\n\tbi.biSize = sizeof(BITMAPINFOHEADER);\n\tbi.biWidth = NewBitmap.bmWidth;\n\tbi.biHeight = -NewBitmap.bmHeight;\n\tbi.biPlanes = 1;\n\tbi.biBitCount = BitCount;\n\tbi.biCompression = BI_RGB;\n\tbi.biSizeImage = 0;\n\tbi.biXPelsPerMeter = 0;\n\tbi.biYPelsPerMeter = 0;\n\tbi.biClrImportant = 0;\n\tbi.biClrUsed = 256;\n\tBmBitsSize = ((NewBitmap.bmWidth * BitCount + 31) & ~31) \/ 8\n\t\t* NewBitmap.bmHeight;\n\tconst HANDLE hDib = GlobalAlloc(GHND, BmBitsSize + PaletteSize + sizeof(BITMAPINFOHEADER));\n\tconst LPBITMAPINFOHEADER lpbi = static_cast(GlobalLock(hDib));\n\t*lpbi = bi;\n\n\tconst HANDLE hPal = GetStockObject(DEFAULT_PALETTE);\n\tif( hPal )\n\t{\n\t\tDeviceContext = GetDC(nullptr);\n\t\thOldPal2 = SelectPalette(DeviceContext, static_cast(hPal), FALSE);\n\t\tRealizePalette(DeviceContext);\n\t}\n\n\tGetDIBits(\n\t\tDeviceContext, Bitmap, 0, static_cast(NewBitmap.bmHeight),\n\t\treinterpret_cast(lpbi) + sizeof(BITMAPINFOHEADER)\n\t\t+ PaletteSize, reinterpret_cast(lpbi), DIB_RGB_COLORS);\n\n\tif( hOldPal2 )\n\t{\n\t\tSelectPalette(DeviceContext, static_cast(hOldPal2), TRUE);\n\t\tRealizePalette(DeviceContext);\n\t\tReleaseDC(nullptr, DeviceContext);\n\t}\n\n\tconst HANDLE FileHandle = CreateFileW(\n\t\tFilename, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,\n\t\tFILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);\n\n\tif( FileHandle == INVALID_HANDLE_VALUE )\n\t{\n\t\treturn FALSE;\n\t}\n\n\tHeader.bfType = 0x4D42;\n\tHeaderSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + PaletteSize + BmBitsSize;\n\tHeader.bfSize = HeaderSize;\n\tHeader.bfReserved1 = 0;\n\tHeader.bfReserved2 = 0;\n\tHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) +\n\t\tPaletteSize;\n\n\tWriteFile(FileHandle, reinterpret_cast(&Header), sizeof(BITMAPFILEHEADER), &Written, nullptr);\n\n\tWriteFile(FileHandle, reinterpret_cast(lpbi), HeaderSize, &Written, nullptr);\n\tGlobalUnlock(hDib);\n\tGlobalFree(hDib);\n\tCloseHandle(FileHandle);\n\treturn TRUE;\n}\n<|endoftext|>"} {"text":"#include \"gamestates\/mainmenustate.hpp\"\n\n#include \n#include \n#include \n\n#include \"config\/settings.hpp\"\n#include \"gui\/texturemanager.hpp\"\n#include \"gui\/ng\/button.hpp\"\n\nnamespace qrw\n{\n\nMainMenuState::MainMenuState(sf::RenderWindow* renderWindow)\n\t: GameState(renderWindow, EGameStateId::EGSID_MAIN_MENU_STATE),\n\t _quitClicked(false),\n\t _mainWindow()\n{\n\t_mainWindow.setSize(sf::Vector2f(145, 240));\n\t_mainWindow.setRelativePosition(sf::Vector2f(15, 15));\n\n\tnamelessgui::Button* button = new namelessgui::Button();\n\n\tbutton->setText(\"Quit\");\n\tbutton->setSize(sf::Vector2f(139, 50));\n\tbutton->signalclicked.connect(std::bind(&MainMenuState::quitClicked, this));\n\tbutton->setParentAnchor({0.5f, 0.0f});\n\tbutton->setAnchor({0.5f, 0.0f});\n\tbutton->setRelativePosition({0.0f, 0.0f});\n\t_mainWindow.addWidget(button);\n\n\t_mainWindow.setVisible(true);\n}\n\nvoid MainMenuState::init(GameState* previousState)\n{\n\tSettings* settings = Settings::getInstance();\n\n\tsf::Uint32 style = sf::Style::Default;\n\n\tif(settings->getFullscreen())\n\t\tstyle = sf::Style::Fullscreen;\n\n\t_renderWindow->create(\n\t\tsf::VideoMode(settings->getResolutionX(), settings->getResolutionY()),\n\t\t\"QRW\",\n\t\tstyle\n\t);\n\n\t\/\/ Set up textures\n\tTextureManager* textureManager = TextureManager::getInstance();\n\n\t\/\/ Set background texture\n\t_background.setSize(sf::Vector2f(settings->getResolutionX(), settings->getResolutionY()));\n\t_background.setTexture(textureManager->getTexture(\"mainmenubackground\"));\n}\n\nEGameStateId MainMenuState::update()\n{\n\tif(_quitClicked)\n\t\treturn EGSID_QUIT;\n\treturn EGSID_NO_CHANGE;\n}\n\nvoid MainMenuState::draw()\n{\n\t_renderWindow->draw(_background);\n\t_mainWindow.render(*_renderWindow, sf::RenderStates::Default);\n}\n\nvoid MainMenuState::handleEvent(sf::Event& event)\n{\n\tif(event.type == sf::Event::Resized)\n\t\t_renderWindow->setView(sf::View(sf::FloatRect(0.0f, 0.0f, event.size.width, event.size.height)));\n\t_mainWindow.handleEvent(event);\n}\n\nvoid MainMenuState::quitClicked()\n{\n\t_quitClicked = true;\n}\n\n} \/\/ namespace qrw\n\nAdded missing buttons to main menu.#include \"gamestates\/mainmenustate.hpp\"\n\n#include \n#include \n#include \n\n#include \"config\/settings.hpp\"\n#include \"gui\/texturemanager.hpp\"\n#include \"gui\/ng\/button.hpp\"\n\nnamespace qrw\n{\n\nMainMenuState::MainMenuState(sf::RenderWindow* renderWindow)\n\t: GameState(renderWindow, EGameStateId::EGSID_MAIN_MENU_STATE),\n\t _quitClicked(false),\n\t _mainWindow()\n{\n\t_mainWindow.setSize(sf::Vector2f(145, 204));\n\t_mainWindow.setRelativePosition(sf::Vector2f(15, 15));\n\n\tnamelessgui::Button* button;\n\tsf::Vector2f buttonSize(139, 50);\n\n\n\tbutton = new namelessgui::Button();\n\tbutton->setText(\"New Match\");\n\tbutton->setSize(buttonSize);\n\tbutton->setParentAnchor({0.5f, 0.01f});\n\tbutton->setAnchor({0.5f, 0.0f});\n\tbutton->setRelativePosition({0.0f, 0.0f});\n\t_mainWindow.addWidget(button);\n\n\tbutton = new namelessgui::Button();\n\tbutton->setText(\"Settings\");\n\tbutton->setSize(buttonSize);\n\tbutton->setParentAnchor({0.5f, 0.01f});\n\tbutton->setAnchor({0.5f, 0.0f});\n\tbutton->setRelativePosition({0.0f, 50.0f});\n\t_mainWindow.addWidget(button);\n\n\tbutton = new namelessgui::Button();\n\tbutton->setText(\"About\");\n\tbutton->setSize(buttonSize);\n\tbutton->setParentAnchor({0.5f, 0.01f});\n\tbutton->setAnchor({0.5f, 0.0f});\n\tbutton->setRelativePosition({0.0f, 100.0f});\n\t_mainWindow.addWidget(button);\n\n\tbutton = new namelessgui::Button();\n\tbutton->setText(\"Quit\");\n\tbutton->setSize(buttonSize);\n\tbutton->signalclicked.connect(std::bind(&MainMenuState::quitClicked, this));\n\tbutton->setParentAnchor({0.5f, 0.01f});\n\tbutton->setAnchor({0.5f, 0.0f});\n\tbutton->setRelativePosition({0.0f, 150.0f});\n\t_mainWindow.addWidget(button);\n\n\t_mainWindow.setVisible(true);\n}\n\nvoid MainMenuState::init(GameState* previousState)\n{\n\tSettings* settings = Settings::getInstance();\n\n\tsf::Uint32 style = sf::Style::Default;\n\n\tif(settings->getFullscreen())\n\t\tstyle = sf::Style::Fullscreen;\n\n\t_renderWindow->create(\n\t\tsf::VideoMode(settings->getResolutionX(), settings->getResolutionY()),\n\t\t\"QRW\",\n\t\tstyle\n\t);\n\n\t\/\/ Set up textures\n\tTextureManager* textureManager = TextureManager::getInstance();\n\n\t\/\/ Set background texture\n\t_background.setSize(sf::Vector2f(settings->getResolutionX(), settings->getResolutionY()));\n\t_background.setTexture(textureManager->getTexture(\"mainmenubackground\"));\n}\n\nEGameStateId MainMenuState::update()\n{\n\tif(_quitClicked)\n\t\treturn EGSID_QUIT;\n\treturn EGSID_NO_CHANGE;\n}\n\nvoid MainMenuState::draw()\n{\n\t_renderWindow->draw(_background);\n\t_mainWindow.render(*_renderWindow, sf::RenderStates::Default);\n}\n\nvoid MainMenuState::handleEvent(sf::Event& event)\n{\n\tif(event.type == sf::Event::Resized)\n\t\t_renderWindow->setView(sf::View(sf::FloatRect(0.0f, 0.0f, event.size.width, event.size.height)));\n\t_mainWindow.handleEvent(event);\n}\n\nvoid MainMenuState::quitClicked()\n{\n\t_quitClicked = true;\n}\n\n} \/\/ namespace qrw\n\n<|endoftext|>"} {"text":"\/*\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file ir_copy_propagation.cpp\n *\n * Moves usage of recently-copied variables to the previous copy of\n * the variable within basic blocks.\n *\n * This should reduce the number of MOV instructions in the generated\n * programs unless copy propagation is also done on the LIR, and may\n * help anyway by triggering other optimizations that live in the HIR.\n *\/\n\n#include \"ir.h\"\n#include \"ir_visitor.h\"\n#include \"ir_basic_block.h\"\n#include \"ir_optimization.h\"\n#include \"glsl_types.h\"\n\nclass acp_entry : public exec_node\n{\npublic:\n acp_entry(ir_variable *lhs, ir_variable *rhs)\n {\n assert(lhs);\n assert(rhs);\n this->lhs = lhs;\n this->rhs = rhs;\n }\n\n ir_variable *lhs;\n ir_variable *rhs;\n};\n\nclass ir_copy_propagation_visitor : public ir_hierarchical_visitor {\npublic:\n ir_copy_propagation_visitor(exec_list *acp)\n {\n progress = false;\n in_lhs = false;\n this->acp = acp;\n }\n\n virtual ir_visitor_status visit(class ir_dereference_variable *);\n virtual ir_visitor_status visit_enter(class ir_loop *);\n virtual ir_visitor_status visit_enter(class ir_function_signature *);\n virtual ir_visitor_status visit_enter(class ir_function *);\n virtual ir_visitor_status visit_enter(class ir_assignment *);\n virtual ir_visitor_status visit_enter(class ir_call *);\n virtual ir_visitor_status visit_enter(class ir_if *);\n\n \/** List of acp_entry *\/\n exec_list *acp;\n bool progress;\n\n \/** Currently in the LHS of an assignment? *\/\n bool in_lhs;\n};\n\n\nir_visitor_status\nir_copy_propagation_visitor::visit_enter(ir_loop *ir)\n{\n (void)ir;\n return visit_continue_with_parent;\n}\n\nir_visitor_status\nir_copy_propagation_visitor::visit_enter(ir_function_signature *ir)\n{\n (void)ir;\n return visit_continue_with_parent;\n}\n\nir_visitor_status\nir_copy_propagation_visitor::visit_enter(ir_assignment *ir)\n{\n (void) ir;\n this->in_lhs = true;\n return visit_continue;\n}\n\nir_visitor_status\nir_copy_propagation_visitor::visit_enter(ir_function *ir)\n{\n (void) ir;\n return visit_continue_with_parent;\n}\n\n\/**\n * Replaces dereferences of ACP RHS variables with ACP LHS variables.\n *\n * This is where the actual copy propagation occurs. Note that the\n * rewriting of ir_dereference means that the ir_dereference instance\n * must not be shared by multiple IR operations!\n *\/\nir_visitor_status\nir_copy_propagation_visitor::visit(ir_dereference_variable *ir)\n{\n \/* Ignores the LHS. Don't want to rewrite the LHS to point at some\n * other storage!\n *\/\n if (this->in_lhs) {\n this->in_lhs = false;\n return visit_continue;\n }\n\n ir_variable *var = ir->variable_referenced();\n\n foreach_iter(exec_list_iterator, iter, *this->acp) {\n acp_entry *entry = (acp_entry *)iter.get();\n\n if (var == entry->lhs) {\n\t ir->var = entry->rhs;\n\t this->progress = true;\n\t break;\n }\n }\n\n return visit_continue;\n}\n\n\nir_visitor_status\nir_copy_propagation_visitor::visit_enter(ir_call *ir)\n{\n (void)ir;\n\n \/* Note, if we were to do copy propagation to parameters of calls, we'd\n * have to be careful about out params.\n *\/\n return visit_continue_with_parent;\n}\n\n\nir_visitor_status\nir_copy_propagation_visitor::visit_enter(ir_if *ir)\n{\n ir->condition->accept(this);\n\n \/* Do not traverse into the body of the if-statement since that is a\n * different basic block.\n *\/\n return visit_continue_with_parent;\n}\n\nstatic bool\npropagate_copies(ir_instruction *ir, exec_list *acp)\n{\n ir_copy_propagation_visitor v(acp);\n\n ir->accept(&v);\n\n return v.progress;\n}\n\nstatic void\nkill_invalidated_copies(ir_assignment *ir, exec_list *acp)\n{\n ir_variable *var = ir->lhs->variable_referenced();\n assert(var != NULL);\n\n foreach_iter(exec_list_iterator, iter, *acp) {\n acp_entry *entry = (acp_entry *)iter.get();\n\n if (entry->lhs == var || entry->rhs == var) {\n\t entry->remove();\n }\n }\n}\n\n\/**\n * Adds an entry to the available copy list if it's a plain assignment\n * of a variable to a variable.\n *\/\nstatic void\nadd_copy(ir_assignment *ir, exec_list *acp)\n{\n void *ctx = talloc_parent(ir);\n acp_entry *entry;\n\n if (ir->condition) {\n ir_constant *condition = ir->condition->as_constant();\n if (!condition || !condition->value.b[0])\n\t return;\n }\n\n ir_variable *lhs_var = ir->lhs->whole_variable_referenced();\n ir_variable *rhs_var = ir->rhs->whole_variable_referenced();\n\n if ((lhs_var != NULL) && (rhs_var != NULL)) {\n entry = new(ctx) acp_entry(lhs_var, rhs_var);\n acp->push_tail(entry);\n }\n}\n\nstatic void\ncopy_propagation_basic_block(ir_instruction *first,\n\t\t\t ir_instruction *last,\n\t\t\t void *data)\n{\n ir_instruction *ir;\n \/* List of avaialble_copy *\/\n exec_list acp;\n bool *out_progress = (bool *)data;\n bool progress = false;\n\n for (ir = first;; ir = (ir_instruction *)ir->next) {\n ir_assignment *ir_assign = ir->as_assignment();\n\n progress = propagate_copies(ir, &acp) || progress;\n\n if (ir_assign) {\n\t kill_invalidated_copies(ir_assign, &acp);\n\n\t add_copy(ir_assign, &acp);\n }\n if (ir == last)\n\t break;\n }\n *out_progress = progress;\n}\n\n\/**\n * Does a copy propagation pass on the code present in the instruction stream.\n *\/\nbool\ndo_copy_propagation(exec_list *instructions)\n{\n bool progress = false;\n\n call_for_basic_blocks(instructions, copy_propagation_basic_block, &progress);\n\n return progress;\n}\nUse a more sensible context in copy propagation.\/*\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file ir_copy_propagation.cpp\n *\n * Moves usage of recently-copied variables to the previous copy of\n * the variable within basic blocks.\n *\n * This should reduce the number of MOV instructions in the generated\n * programs unless copy propagation is also done on the LIR, and may\n * help anyway by triggering other optimizations that live in the HIR.\n *\/\n\n#include \"ir.h\"\n#include \"ir_visitor.h\"\n#include \"ir_basic_block.h\"\n#include \"ir_optimization.h\"\n#include \"glsl_types.h\"\n\nclass acp_entry : public exec_node\n{\npublic:\n acp_entry(ir_variable *lhs, ir_variable *rhs)\n {\n assert(lhs);\n assert(rhs);\n this->lhs = lhs;\n this->rhs = rhs;\n }\n\n ir_variable *lhs;\n ir_variable *rhs;\n};\n\nclass ir_copy_propagation_visitor : public ir_hierarchical_visitor {\npublic:\n ir_copy_propagation_visitor(exec_list *acp)\n {\n progress = false;\n in_lhs = false;\n this->acp = acp;\n }\n\n virtual ir_visitor_status visit(class ir_dereference_variable *);\n virtual ir_visitor_status visit_enter(class ir_loop *);\n virtual ir_visitor_status visit_enter(class ir_function_signature *);\n virtual ir_visitor_status visit_enter(class ir_function *);\n virtual ir_visitor_status visit_enter(class ir_assignment *);\n virtual ir_visitor_status visit_enter(class ir_call *);\n virtual ir_visitor_status visit_enter(class ir_if *);\n\n \/** List of acp_entry *\/\n exec_list *acp;\n bool progress;\n\n \/** Currently in the LHS of an assignment? *\/\n bool in_lhs;\n};\n\n\nir_visitor_status\nir_copy_propagation_visitor::visit_enter(ir_loop *ir)\n{\n (void)ir;\n return visit_continue_with_parent;\n}\n\nir_visitor_status\nir_copy_propagation_visitor::visit_enter(ir_function_signature *ir)\n{\n (void)ir;\n return visit_continue_with_parent;\n}\n\nir_visitor_status\nir_copy_propagation_visitor::visit_enter(ir_assignment *ir)\n{\n (void) ir;\n this->in_lhs = true;\n return visit_continue;\n}\n\nir_visitor_status\nir_copy_propagation_visitor::visit_enter(ir_function *ir)\n{\n (void) ir;\n return visit_continue_with_parent;\n}\n\n\/**\n * Replaces dereferences of ACP RHS variables with ACP LHS variables.\n *\n * This is where the actual copy propagation occurs. Note that the\n * rewriting of ir_dereference means that the ir_dereference instance\n * must not be shared by multiple IR operations!\n *\/\nir_visitor_status\nir_copy_propagation_visitor::visit(ir_dereference_variable *ir)\n{\n \/* Ignores the LHS. Don't want to rewrite the LHS to point at some\n * other storage!\n *\/\n if (this->in_lhs) {\n this->in_lhs = false;\n return visit_continue;\n }\n\n ir_variable *var = ir->variable_referenced();\n\n foreach_iter(exec_list_iterator, iter, *this->acp) {\n acp_entry *entry = (acp_entry *)iter.get();\n\n if (var == entry->lhs) {\n\t ir->var = entry->rhs;\n\t this->progress = true;\n\t break;\n }\n }\n\n return visit_continue;\n}\n\n\nir_visitor_status\nir_copy_propagation_visitor::visit_enter(ir_call *ir)\n{\n (void)ir;\n\n \/* Note, if we were to do copy propagation to parameters of calls, we'd\n * have to be careful about out params.\n *\/\n return visit_continue_with_parent;\n}\n\n\nir_visitor_status\nir_copy_propagation_visitor::visit_enter(ir_if *ir)\n{\n ir->condition->accept(this);\n\n \/* Do not traverse into the body of the if-statement since that is a\n * different basic block.\n *\/\n return visit_continue_with_parent;\n}\n\nstatic bool\npropagate_copies(ir_instruction *ir, exec_list *acp)\n{\n ir_copy_propagation_visitor v(acp);\n\n ir->accept(&v);\n\n return v.progress;\n}\n\nstatic void\nkill_invalidated_copies(ir_assignment *ir, exec_list *acp)\n{\n ir_variable *var = ir->lhs->variable_referenced();\n assert(var != NULL);\n\n foreach_iter(exec_list_iterator, iter, *acp) {\n acp_entry *entry = (acp_entry *)iter.get();\n\n if (entry->lhs == var || entry->rhs == var) {\n\t entry->remove();\n }\n }\n}\n\n\/**\n * Adds an entry to the available copy list if it's a plain assignment\n * of a variable to a variable.\n *\/\nstatic void\nadd_copy(void *ctx, ir_assignment *ir, exec_list *acp)\n{\n acp_entry *entry;\n\n if (ir->condition) {\n ir_constant *condition = ir->condition->as_constant();\n if (!condition || !condition->value.b[0])\n\t return;\n }\n\n ir_variable *lhs_var = ir->lhs->whole_variable_referenced();\n ir_variable *rhs_var = ir->rhs->whole_variable_referenced();\n\n if ((lhs_var != NULL) && (rhs_var != NULL)) {\n entry = new(ctx) acp_entry(lhs_var, rhs_var);\n acp->push_tail(entry);\n }\n}\n\nstatic void\ncopy_propagation_basic_block(ir_instruction *first,\n\t\t\t ir_instruction *last,\n\t\t\t void *data)\n{\n ir_instruction *ir;\n \/* List of avaialble_copy *\/\n exec_list acp;\n bool *out_progress = (bool *)data;\n bool progress = false;\n\n void *ctx = talloc(NULL, void*);\n for (ir = first;; ir = (ir_instruction *)ir->next) {\n ir_assignment *ir_assign = ir->as_assignment();\n\n progress = propagate_copies(ir, &acp) || progress;\n\n if (ir_assign) {\n\t kill_invalidated_copies(ir_assign, &acp);\n\n\t add_copy(ctx, ir_assign, &acp);\n }\n if (ir == last)\n\t break;\n }\n *out_progress = progress;\n talloc_free(ctx);\n}\n\n\/**\n * Does a copy propagation pass on the code present in the instruction stream.\n *\/\nbool\ndo_copy_propagation(exec_list *instructions)\n{\n bool progress = false;\n\n call_for_basic_blocks(instructions, copy_propagation_basic_block, &progress);\n\n return progress;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright © 2011 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file lower_clip_distance.cpp\n *\n * This pass accounts for the difference between the way\n * gl_ClipDistance is declared in standard GLSL (as an array of\n * floats), and the way it is frequently implemented in hardware (as\n * a pair of vec4s, with four clip distances packed into each).\n *\n * The declaration of gl_ClipDistance is replaced with a declaration\n * of gl_ClipDistanceMESA, and any references to gl_ClipDistance are\n * translated to refer to gl_ClipDistanceMESA with the appropriate\n * swizzling of array indices. For instance:\n *\n * gl_ClipDistance[i]\n *\n * is translated into:\n *\n * gl_ClipDistanceMESA[i>>2][i&3]\n *\n * Since some hardware may not internally represent gl_ClipDistance as a pair\n * of vec4's, this lowering pass is optional. To enable it, set the\n * LowerClipDistance flag in gl_shader_compiler_options to true.\n *\/\n\n#include \"glsl_symbol_table.h\"\n#include \"ir_hierarchical_visitor.h\"\n#include \"ir.h\"\n\nclass lower_clip_distance_visitor : public ir_hierarchical_visitor {\npublic:\n lower_clip_distance_visitor()\n : progress(false), old_clip_distance_var(NULL),\n new_clip_distance_var(NULL)\n {\n }\n\n virtual ir_visitor_status visit(ir_variable *);\n void create_indices(ir_rvalue*, ir_rvalue *&, ir_rvalue *&);\n virtual ir_visitor_status visit_leave(ir_dereference_array *);\n virtual ir_visitor_status visit_leave(ir_assignment *);\n void visit_new_assignment(ir_assignment *ir);\n virtual ir_visitor_status visit_leave(ir_call *);\n\n bool progress;\n\n \/**\n * Pointer to the declaration of gl_ClipDistance, if found.\n *\/\n ir_variable *old_clip_distance_var;\n\n \/**\n * Pointer to the newly-created gl_ClipDistanceMESA variable.\n *\/\n ir_variable *new_clip_distance_var;\n};\n\n\n\/**\n * Replace any declaration of gl_ClipDistance as an array of floats with a\n * declaration of gl_ClipDistanceMESA as an array of vec4's.\n *\/\nir_visitor_status\nlower_clip_distance_visitor::visit(ir_variable *ir)\n{\n \/* No point in looking for the declaration of gl_ClipDistance if\n * we've already found it.\n *\/\n if (this->old_clip_distance_var)\n return visit_continue;\n\n if (ir->name && strcmp(ir->name, \"gl_ClipDistance\") == 0) {\n this->progress = true;\n this->old_clip_distance_var = ir;\n assert (ir->type->is_array());\n assert (ir->type->element_type() == glsl_type::float_type);\n unsigned new_size = (ir->type->array_size() + 3) \/ 4;\n\n \/* Clone the old var so that we inherit all of its properties *\/\n this->new_clip_distance_var = ir->clone(ralloc_parent(ir), NULL);\n\n \/* And change the properties that we need to change *\/\n this->new_clip_distance_var->name\n = ralloc_strdup(this->new_clip_distance_var, \"gl_ClipDistanceMESA\");\n this->new_clip_distance_var->type\n = glsl_type::get_array_instance(glsl_type::vec4_type, new_size);\n this->new_clip_distance_var->max_array_access = ir->max_array_access \/ 4;\n\n ir->replace_with(this->new_clip_distance_var);\n }\n return visit_continue;\n}\n\n\n\/**\n * Create the necessary GLSL rvalues to index into gl_ClipDistanceMESA based\n * on the rvalue previously used to index into gl_ClipDistance.\n *\n * \\param array_index Selects one of the vec4's in gl_ClipDistanceMESA\n * \\param swizzle_index Selects a component within the vec4 selected by\n * array_index.\n *\/\nvoid\nlower_clip_distance_visitor::create_indices(ir_rvalue *old_index,\n ir_rvalue *&array_index,\n ir_rvalue *&swizzle_index)\n{\n void *ctx = ralloc_parent(old_index);\n\n \/* Make sure old_index is a signed int so that the bitwise \"shift\" and\n * \"and\" operations below type check properly.\n *\/\n if (old_index->type != glsl_type::int_type) {\n assert (old_index->type == glsl_type::uint_type);\n old_index = new(ctx) ir_expression(ir_unop_u2i, old_index);\n }\n\n ir_constant *old_index_constant = old_index->constant_expression_value();\n if (old_index_constant) {\n \/* gl_ClipDistance is being accessed via a constant index. Don't bother\n * creating expressions to calculate the lowered indices. Just create\n * constants.\n *\/\n int const_val = old_index_constant->get_int_component(0);\n array_index = new(ctx) ir_constant(const_val \/ 4);\n swizzle_index = new(ctx) ir_constant(const_val % 4);\n } else {\n \/* Create a variable to hold the value of old_index (so that we\n * don't compute it twice).\n *\/\n ir_variable *old_index_var = new(ctx) ir_variable(\n glsl_type::int_type, \"clip_distance_index\", ir_var_temporary);\n this->base_ir->insert_before(old_index_var);\n this->base_ir->insert_before(new(ctx) ir_assignment(\n new(ctx) ir_dereference_variable(old_index_var), old_index));\n\n \/* Create the expression clip_distance_index \/ 4. Do this as a bit\n * shift because that's likely to be more efficient.\n *\/\n array_index = new(ctx) ir_expression(\n ir_binop_rshift, new(ctx) ir_dereference_variable(old_index_var),\n new(ctx) ir_constant(2));\n\n \/* Create the expression clip_distance_index % 4. Do this as a bitwise\n * AND because that's likely to be more efficient.\n *\/\n swizzle_index = new(ctx) ir_expression(\n ir_binop_bit_and, new(ctx) ir_dereference_variable(old_index_var),\n new(ctx) ir_constant(3));\n }\n}\n\n\n\/**\n * Replace any expression that indexes into the gl_ClipDistance array with an\n * expression that indexes into one of the vec4's in gl_ClipDistanceMESA and\n * accesses the appropriate component.\n *\/\nir_visitor_status\nlower_clip_distance_visitor::visit_leave(ir_dereference_array *ir)\n{\n \/* If the gl_ClipDistance var hasn't been declared yet, then\n * there's no way this deref can refer to it.\n *\/\n if (!this->old_clip_distance_var)\n return visit_continue;\n\n ir_dereference_variable *old_var_ref = ir->array->as_dereference_variable();\n if (old_var_ref && old_var_ref->var == this->old_clip_distance_var) {\n this->progress = true;\n ir_rvalue *array_index;\n ir_rvalue *swizzle_index;\n this->create_indices(ir->array_index, array_index, swizzle_index);\n void *mem_ctx = ralloc_parent(ir);\n ir->array = new(mem_ctx) ir_dereference_array(\n this->new_clip_distance_var, array_index);\n ir->array_index = swizzle_index;\n }\n\n return visit_continue;\n}\n\n\n\/**\n * Replace any assignment having gl_ClipDistance (undereferenced) as its LHS\n * or RHS with a sequence of assignments, one for each component of the array.\n * Each of these assignments is lowered to refer to gl_ClipDistanceMESA as\n * appropriate.\n *\/\nir_visitor_status\nlower_clip_distance_visitor::visit_leave(ir_assignment *ir)\n{\n ir_dereference_variable *lhs_var = ir->lhs->as_dereference_variable();\n ir_dereference_variable *rhs_var = ir->rhs->as_dereference_variable();\n if ((lhs_var && lhs_var->var == this->old_clip_distance_var)\n || (rhs_var && rhs_var->var == this->old_clip_distance_var)) {\n \/* LHS or RHS of the assignment is the entire gl_ClipDistance array.\n * Since we are reshaping gl_ClipDistance from an array of floats to an\n * array of vec4's, this isn't going to work as a bulk assignment\n * anymore, so unroll it to element-by-element assignments and lower\n * each of them.\n *\n * Note: to unroll into element-by-element assignments, we need to make\n * clones of the LHS and RHS. This is only safe if the LHS and RHS are\n * side-effect free. Fortunately, we know that they are, because the\n * only kind of rvalue that can have side effects is an ir_call, and\n * ir_calls only appear (a) as a statement on their own, or (b) as the\n * RHS of an assignment that stores the result of the call in a\n * temporary variable.\n *\/\n void *ctx = ralloc_parent(ir);\n int array_size = this->old_clip_distance_var->type->array_size();\n for (int i = 0; i < array_size; ++i) {\n ir_dereference_array *new_lhs = new(ctx) ir_dereference_array(\n ir->lhs->clone(ctx, NULL), new(ctx) ir_constant(i));\n new_lhs->accept(this);\n ir_dereference_array *new_rhs = new(ctx) ir_dereference_array(\n ir->rhs->clone(ctx, NULL), new(ctx) ir_constant(i));\n new_rhs->accept(this);\n this->base_ir->insert_before(\n new(ctx) ir_assignment(new_lhs, new_rhs));\n }\n ir->remove();\n }\n\n return visit_continue;\n}\n\n\n\/**\n * Set up base_ir properly and call visit_leave() on a newly created\n * ir_assignment node. This is used in cases where we have to insert an\n * ir_assignment in a place where we know the hierarchical visitor won't see\n * it.\n *\/\nvoid\nlower_clip_distance_visitor::visit_new_assignment(ir_assignment *ir)\n{\n ir_instruction *old_base_ir = this->base_ir;\n this->base_ir = ir;\n ir->accept(this);\n this->base_ir = old_base_ir;\n}\n\n\n\/**\n * If gl_ClipDistance appears as an argument in an ir_call expression, replace\n * it with a temporary variable, and make sure the ir_call is preceded and\/or\n * followed by assignments that copy the contents of the temporary variable to\n * and\/or from gl_ClipDistance. Each of these assignments is then lowered to\n * refer to gl_ClipDistanceMESA.\n *\/\nir_visitor_status\nlower_clip_distance_visitor::visit_leave(ir_call *ir)\n{\n void *ctx = ralloc_parent(ir);\n\n const exec_node *formal_param_node = ir->callee->parameters.head;\n const exec_node *actual_param_node = ir->actual_parameters.head;\n while (!actual_param_node->is_tail_sentinel()) {\n ir_variable *formal_param = (ir_variable *) formal_param_node;\n ir_rvalue *actual_param = (ir_rvalue *) actual_param_node;\n\n \/* Advance formal_param_node and actual_param_node now so that we can\n * safely replace actual_param with another node, if necessary, below.\n *\/\n formal_param_node = formal_param_node->next;\n actual_param_node = actual_param_node->next;\n\n ir_dereference_variable *deref = actual_param->as_dereference_variable();\n if (deref && deref->var == this->old_clip_distance_var) {\n \/* User is trying to pass the whole gl_ClipDistance array to a\n * function call. Since we are reshaping gl_ClipDistance from an\n * array of floats to an array of vec4's, this isn't going to work\n * anymore, so use a temporary array instead.\n *\/\n ir_variable *temp_clip_distance = new(ctx) ir_variable(\n actual_param->type, \"temp_clip_distance\", ir_var_temporary);\n this->base_ir->insert_before(temp_clip_distance);\n actual_param->replace_with(\n new(ctx) ir_dereference_variable(temp_clip_distance));\n if (formal_param->mode == ir_var_function_in\n || formal_param->mode == ir_var_function_inout) {\n \/* Copy from gl_ClipDistance to the temporary before the call.\n * Since we are going to insert this copy before the current\n * instruction, we need to visit it afterwards to make sure it\n * gets lowered.\n *\/\n ir_assignment *new_assignment = new(ctx) ir_assignment(\n new(ctx) ir_dereference_variable(temp_clip_distance),\n new(ctx) ir_dereference_variable(old_clip_distance_var));\n this->base_ir->insert_before(new_assignment);\n this->visit_new_assignment(new_assignment);\n }\n if (formal_param->mode == ir_var_function_out\n || formal_param->mode == ir_var_function_inout) {\n \/* Copy from the temporary to gl_ClipDistance after the call.\n * Since visit_list_elements() has already decided which\n * instruction it's going to visit next, we need to visit\n * afterwards to make sure it gets lowered.\n *\/\n ir_assignment *new_assignment = new(ctx) ir_assignment(\n new(ctx) ir_dereference_variable(old_clip_distance_var),\n new(ctx) ir_dereference_variable(temp_clip_distance));\n this->base_ir->insert_after(new_assignment);\n this->visit_new_assignment(new_assignment);\n }\n }\n }\n\n return visit_continue;\n}\n\n\nbool\nlower_clip_distance(gl_shader *shader)\n{\n lower_clip_distance_visitor v;\n\n visit_list_elements(&v, shader->ir);\n\n if (v.new_clip_distance_var)\n shader->symbols->add_variable(v.new_clip_distance_var);\n\n return v.progress;\n}\nglsl: Convert lower_clip_distance_visitor to be an ir_rvalue_visitor\/*\n * Copyright © 2011 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file lower_clip_distance.cpp\n *\n * This pass accounts for the difference between the way\n * gl_ClipDistance is declared in standard GLSL (as an array of\n * floats), and the way it is frequently implemented in hardware (as\n * a pair of vec4s, with four clip distances packed into each).\n *\n * The declaration of gl_ClipDistance is replaced with a declaration\n * of gl_ClipDistanceMESA, and any references to gl_ClipDistance are\n * translated to refer to gl_ClipDistanceMESA with the appropriate\n * swizzling of array indices. For instance:\n *\n * gl_ClipDistance[i]\n *\n * is translated into:\n *\n * gl_ClipDistanceMESA[i>>2][i&3]\n *\n * Since some hardware may not internally represent gl_ClipDistance as a pair\n * of vec4's, this lowering pass is optional. To enable it, set the\n * LowerClipDistance flag in gl_shader_compiler_options to true.\n *\/\n\n#include \"glsl_symbol_table.h\"\n#include \"ir_rvalue_visitor.h\"\n#include \"ir.h\"\n\nclass lower_clip_distance_visitor : public ir_rvalue_visitor {\npublic:\n lower_clip_distance_visitor()\n : progress(false), old_clip_distance_var(NULL),\n new_clip_distance_var(NULL)\n {\n }\n\n virtual ir_visitor_status visit(ir_variable *);\n void create_indices(ir_rvalue*, ir_rvalue *&, ir_rvalue *&);\n virtual ir_visitor_status visit_leave(ir_assignment *);\n void visit_new_assignment(ir_assignment *ir);\n virtual ir_visitor_status visit_leave(ir_call *);\n\n virtual void handle_rvalue(ir_rvalue **rvalue);\n\n bool progress;\n\n \/**\n * Pointer to the declaration of gl_ClipDistance, if found.\n *\/\n ir_variable *old_clip_distance_var;\n\n \/**\n * Pointer to the newly-created gl_ClipDistanceMESA variable.\n *\/\n ir_variable *new_clip_distance_var;\n};\n\n\n\/**\n * Replace any declaration of gl_ClipDistance as an array of floats with a\n * declaration of gl_ClipDistanceMESA as an array of vec4's.\n *\/\nir_visitor_status\nlower_clip_distance_visitor::visit(ir_variable *ir)\n{\n \/* No point in looking for the declaration of gl_ClipDistance if\n * we've already found it.\n *\/\n if (this->old_clip_distance_var)\n return visit_continue;\n\n if (ir->name && strcmp(ir->name, \"gl_ClipDistance\") == 0) {\n this->progress = true;\n this->old_clip_distance_var = ir;\n assert (ir->type->is_array());\n assert (ir->type->element_type() == glsl_type::float_type);\n unsigned new_size = (ir->type->array_size() + 3) \/ 4;\n\n \/* Clone the old var so that we inherit all of its properties *\/\n this->new_clip_distance_var = ir->clone(ralloc_parent(ir), NULL);\n\n \/* And change the properties that we need to change *\/\n this->new_clip_distance_var->name\n = ralloc_strdup(this->new_clip_distance_var, \"gl_ClipDistanceMESA\");\n this->new_clip_distance_var->type\n = glsl_type::get_array_instance(glsl_type::vec4_type, new_size);\n this->new_clip_distance_var->max_array_access = ir->max_array_access \/ 4;\n\n ir->replace_with(this->new_clip_distance_var);\n }\n return visit_continue;\n}\n\n\n\/**\n * Create the necessary GLSL rvalues to index into gl_ClipDistanceMESA based\n * on the rvalue previously used to index into gl_ClipDistance.\n *\n * \\param array_index Selects one of the vec4's in gl_ClipDistanceMESA\n * \\param swizzle_index Selects a component within the vec4 selected by\n * array_index.\n *\/\nvoid\nlower_clip_distance_visitor::create_indices(ir_rvalue *old_index,\n ir_rvalue *&array_index,\n ir_rvalue *&swizzle_index)\n{\n void *ctx = ralloc_parent(old_index);\n\n \/* Make sure old_index is a signed int so that the bitwise \"shift\" and\n * \"and\" operations below type check properly.\n *\/\n if (old_index->type != glsl_type::int_type) {\n assert (old_index->type == glsl_type::uint_type);\n old_index = new(ctx) ir_expression(ir_unop_u2i, old_index);\n }\n\n ir_constant *old_index_constant = old_index->constant_expression_value();\n if (old_index_constant) {\n \/* gl_ClipDistance is being accessed via a constant index. Don't bother\n * creating expressions to calculate the lowered indices. Just create\n * constants.\n *\/\n int const_val = old_index_constant->get_int_component(0);\n array_index = new(ctx) ir_constant(const_val \/ 4);\n swizzle_index = new(ctx) ir_constant(const_val % 4);\n } else {\n \/* Create a variable to hold the value of old_index (so that we\n * don't compute it twice).\n *\/\n ir_variable *old_index_var = new(ctx) ir_variable(\n glsl_type::int_type, \"clip_distance_index\", ir_var_temporary);\n this->base_ir->insert_before(old_index_var);\n this->base_ir->insert_before(new(ctx) ir_assignment(\n new(ctx) ir_dereference_variable(old_index_var), old_index));\n\n \/* Create the expression clip_distance_index \/ 4. Do this as a bit\n * shift because that's likely to be more efficient.\n *\/\n array_index = new(ctx) ir_expression(\n ir_binop_rshift, new(ctx) ir_dereference_variable(old_index_var),\n new(ctx) ir_constant(2));\n\n \/* Create the expression clip_distance_index % 4. Do this as a bitwise\n * AND because that's likely to be more efficient.\n *\/\n swizzle_index = new(ctx) ir_expression(\n ir_binop_bit_and, new(ctx) ir_dereference_variable(old_index_var),\n new(ctx) ir_constant(3));\n }\n}\n\n\nvoid\nlower_clip_distance_visitor::handle_rvalue(ir_rvalue **rv)\n{\n \/* If the gl_ClipDistance var hasn't been declared yet, then\n * there's no way this deref can refer to it.\n *\/\n if (!this->old_clip_distance_var || *rv == NULL)\n return;\n\n ir_dereference_array *const array_deref = (*rv)->as_dereference_array();\n if (array_deref == NULL)\n return;\n\n \/* Replace any expression that indexes into the gl_ClipDistance array\n * with an expression that indexes into one of the vec4's in\n * gl_ClipDistanceMESA and accesses the appropriate component.\n *\/\n ir_dereference_variable *old_var_ref =\n array_deref->array->as_dereference_variable();\n if (old_var_ref && old_var_ref->var == this->old_clip_distance_var) {\n this->progress = true;\n ir_rvalue *array_index;\n ir_rvalue *swizzle_index;\n this->create_indices(array_deref->array_index, array_index, swizzle_index);\n void *mem_ctx = ralloc_parent(array_deref);\n array_deref->array = new(mem_ctx) ir_dereference_array(\n this->new_clip_distance_var, array_index);\n array_deref->array_index = swizzle_index;\n }\n}\n\n\n\/**\n * Replace any assignment having gl_ClipDistance (undereferenced) as its LHS\n * or RHS with a sequence of assignments, one for each component of the array.\n * Each of these assignments is lowered to refer to gl_ClipDistanceMESA as\n * appropriate.\n *\/\nir_visitor_status\nlower_clip_distance_visitor::visit_leave(ir_assignment *ir)\n{\n ir_dereference_variable *lhs_var = ir->lhs->as_dereference_variable();\n ir_dereference_variable *rhs_var = ir->rhs->as_dereference_variable();\n if ((lhs_var && lhs_var->var == this->old_clip_distance_var)\n || (rhs_var && rhs_var->var == this->old_clip_distance_var)) {\n \/* LHS or RHS of the assignment is the entire gl_ClipDistance array.\n * Since we are reshaping gl_ClipDistance from an array of floats to an\n * array of vec4's, this isn't going to work as a bulk assignment\n * anymore, so unroll it to element-by-element assignments and lower\n * each of them.\n *\n * Note: to unroll into element-by-element assignments, we need to make\n * clones of the LHS and RHS. This is only safe if the LHS and RHS are\n * side-effect free. Fortunately, we know that they are, because the\n * only kind of rvalue that can have side effects is an ir_call, and\n * ir_calls only appear (a) as a statement on their own, or (b) as the\n * RHS of an assignment that stores the result of the call in a\n * temporary variable.\n *\/\n void *ctx = ralloc_parent(ir);\n int array_size = this->old_clip_distance_var->type->array_size();\n for (int i = 0; i < array_size; ++i) {\n ir_dereference_array *new_lhs = new(ctx) ir_dereference_array(\n ir->lhs->clone(ctx, NULL), new(ctx) ir_constant(i));\n this->handle_rvalue((ir_rvalue **) &new_lhs);\n ir_dereference_array *new_rhs = new(ctx) ir_dereference_array(\n ir->rhs->clone(ctx, NULL), new(ctx) ir_constant(i));\n this->handle_rvalue((ir_rvalue **) &new_rhs);\n this->base_ir->insert_before(\n new(ctx) ir_assignment(new_lhs, new_rhs));\n }\n ir->remove();\n\n return visit_continue;\n }\n\n \/* Handle the LHS as if it were an r-value. Normally\n * rvalue_visit(ir_assignment *) only visits the RHS, but we need to lower\n * expressions in the LHS as well.\n *\/\n handle_rvalue((ir_rvalue **)&ir->lhs);\n return rvalue_visit(ir);\n}\n\n\n\/**\n * Set up base_ir properly and call visit_leave() on a newly created\n * ir_assignment node. This is used in cases where we have to insert an\n * ir_assignment in a place where we know the hierarchical visitor won't see\n * it.\n *\/\nvoid\nlower_clip_distance_visitor::visit_new_assignment(ir_assignment *ir)\n{\n ir_instruction *old_base_ir = this->base_ir;\n this->base_ir = ir;\n ir->accept(this);\n this->base_ir = old_base_ir;\n}\n\n\n\/**\n * If gl_ClipDistance appears as an argument in an ir_call expression, replace\n * it with a temporary variable, and make sure the ir_call is preceded and\/or\n * followed by assignments that copy the contents of the temporary variable to\n * and\/or from gl_ClipDistance. Each of these assignments is then lowered to\n * refer to gl_ClipDistanceMESA.\n *\/\nir_visitor_status\nlower_clip_distance_visitor::visit_leave(ir_call *ir)\n{\n void *ctx = ralloc_parent(ir);\n\n const exec_node *formal_param_node = ir->callee->parameters.head;\n const exec_node *actual_param_node = ir->actual_parameters.head;\n while (!actual_param_node->is_tail_sentinel()) {\n ir_variable *formal_param = (ir_variable *) formal_param_node;\n ir_rvalue *actual_param = (ir_rvalue *) actual_param_node;\n\n \/* Advance formal_param_node and actual_param_node now so that we can\n * safely replace actual_param with another node, if necessary, below.\n *\/\n formal_param_node = formal_param_node->next;\n actual_param_node = actual_param_node->next;\n\n ir_dereference_variable *deref = actual_param->as_dereference_variable();\n if (deref && deref->var == this->old_clip_distance_var) {\n \/* User is trying to pass the whole gl_ClipDistance array to a\n * function call. Since we are reshaping gl_ClipDistance from an\n * array of floats to an array of vec4's, this isn't going to work\n * anymore, so use a temporary array instead.\n *\/\n ir_variable *temp_clip_distance = new(ctx) ir_variable(\n actual_param->type, \"temp_clip_distance\", ir_var_temporary);\n this->base_ir->insert_before(temp_clip_distance);\n actual_param->replace_with(\n new(ctx) ir_dereference_variable(temp_clip_distance));\n if (formal_param->mode == ir_var_function_in\n || formal_param->mode == ir_var_function_inout) {\n \/* Copy from gl_ClipDistance to the temporary before the call.\n * Since we are going to insert this copy before the current\n * instruction, we need to visit it afterwards to make sure it\n * gets lowered.\n *\/\n ir_assignment *new_assignment = new(ctx) ir_assignment(\n new(ctx) ir_dereference_variable(temp_clip_distance),\n new(ctx) ir_dereference_variable(old_clip_distance_var));\n this->base_ir->insert_before(new_assignment);\n this->visit_new_assignment(new_assignment);\n }\n if (formal_param->mode == ir_var_function_out\n || formal_param->mode == ir_var_function_inout) {\n \/* Copy from the temporary to gl_ClipDistance after the call.\n * Since visit_list_elements() has already decided which\n * instruction it's going to visit next, we need to visit\n * afterwards to make sure it gets lowered.\n *\/\n ir_assignment *new_assignment = new(ctx) ir_assignment(\n new(ctx) ir_dereference_variable(old_clip_distance_var),\n new(ctx) ir_dereference_variable(temp_clip_distance));\n this->base_ir->insert_after(new_assignment);\n this->visit_new_assignment(new_assignment);\n }\n }\n }\n\n return rvalue_visit(ir);\n}\n\n\nbool\nlower_clip_distance(gl_shader *shader)\n{\n lower_clip_distance_visitor v;\n\n visit_list_elements(&v, shader->ir);\n\n if (v.new_clip_distance_var)\n shader->symbols->add_variable(v.new_clip_distance_var);\n\n return v.progress;\n}\n<|endoftext|>"} {"text":"\/*The MIT License (MIT)\n\nCopyright (c) 2015 Jens Malmborg\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.*\/\n\n#include \n#include \n#include \n#include \"graphics-device.h\"\n#include \"texture-collection.h\"\n#include \"vertex-declaration.h\"\n#include \"window.h\"\n#include \"vertex-data-state.h\"\n\nusing namespace v8;\n\nnamespace {\n\nvoid SetVertexDataState(const FunctionCallbackInfo& args) {\n HandleScope scope(args.GetIsolate());\n ScriptHelper helper(args.GetIsolate());\n auto vertexBuffer = helper.GetObject(args[0]);\n helper.GetObject(args.Holder())->\n SetVertexDataState(vertexBuffer);\n}\n\nvoid SetBlendState(const FunctionCallbackInfo& args) {\n HandleScope scope(args.GetIsolate());\n ScriptHelper helper(args.GetIsolate());\n\n auto state = helper.GetString(args[0]);\n if (state == \"additive\") {\n helper.GetObject(args.Holder())->\n SetBlendState(BlendState::Additive);\n }\n else if (state == \"alphaBlend\") {\n helper.GetObject(args.Holder())->\n SetBlendState(BlendState::AlphaBlend);\n }\n else if (state == \"opaque\") {\n helper.GetObject(args.Holder())->\n SetBlendState(BlendState::Opaque);\n }\n else {\n ScriptEngine::current().ThrowTypeError(\n \"Couln't set blend state to '\" + state + \"'.\");\n }\n}\n\nvoid SetDepthStencilState(const FunctionCallbackInfo& args) {\n HandleScope scope(args.GetIsolate());\n ScriptHelper helper(args.GetIsolate());\n\n auto state = helper.GetString(args[0]);\n if (state == \"default\") {\n helper.GetObject(args.Holder())->\n SetDepthStencilState(DepthStencilState::Default);\n }\n else if (state == \"depthRead\") {\n helper.GetObject(args.Holder())->\n SetDepthStencilState(DepthStencilState::DepthRead);\n }\n else if (state == \"none\") {\n helper.GetObject(args.Holder())->\n SetDepthStencilState(DepthStencilState::None);\n }\n else {\n ScriptEngine::current().ThrowTypeError(\n \"Couln't set depth stencil state to '\" + state + \"'.\");\n }\n}\n\n}\n\nGraphicsDevice::GraphicsDevice(Isolate *isolate, Window *window) :\n ScriptObjectWrap(isolate), textures_(isolate, this), window_(window) {\n textures_.InstallAsObject(\"textures\", this->v8Object());\n SetBlendState(BlendState::Opaque);\n SetDepthStencilState(DepthStencilState::Default);\n}\n\nvoid GraphicsDevice::Clear(float r, float g, float b, float a) {\n glClearColor(r, g, b, a);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);\n}\n\nvoid GraphicsDevice::DrawVertices(PrimitiveType primitiveType,\n int startVertex, int primitiveCount) {\n if (vertexDataState_ == nullptr) {\n throw std::runtime_error(\n \"Vertex data state must be set before drawing vertices.\");\n }\n if (shaderProgram_ == nullptr) {\n throw std::runtime_error(\n \"Shader program must be set before drawing vertices.\");\n }\n switch (primitiveType) {\n case PrimitiveType::TriangleList:\n glDrawArrays(GL_TRIANGLES, startVertex, primitiveCount * 3);\n break;\n case PrimitiveType::PointList:\n glDrawArrays(GL_POINTS, startVertex, primitiveCount);\n break;\n case PrimitiveType::LineList:\n glDrawArrays(GL_LINES, startVertex, primitiveCount * 2);\n break;\n }\n}\n\nvoid GraphicsDevice::DrawElements(PrimitiveType primitiveType,\n int startIndex, int primitiveCount) {\n if (vertexDataState_ == nullptr) {\n throw std::runtime_error(\n \"Vertex data state must be set before drawing elements.\");\n }\n if (shaderProgram_ == nullptr) {\n throw std::runtime_error(\n \"Shader program must be set before drawing elements.\");\n }\n switch (primitiveType) {\n case PrimitiveType::TriangleList:\n glDrawElements(GL_TRIANGLES, primitiveCount * 3, GL_UNSIGNED_INT,\n (void*)(startIndex * sizeof(GLuint)));\n break;\n case PrimitiveType::PointList:\n glDrawElements(GL_TRIANGLES, primitiveCount, GL_UNSIGNED_INT,\n (void*)(startIndex * sizeof(GLuint)));\n break;\n case PrimitiveType::LineList:\n glDrawElements(GL_TRIANGLES, primitiveCount * 2, GL_UNSIGNED_INT,\n (void*)(startIndex * sizeof(GLuint)));\n break;\n }\n}\n\nvoid GraphicsDevice::Present() {\n glfwSwapBuffers(window_->glfwWindow());\n}\n\nvoid GraphicsDevice::SetShaderProgram(ShaderProgram *shaderProgram) {\n if (shaderProgram != nullptr && shaderProgram != shaderProgram_) {\n glUseProgram(shaderProgram->glProgram());\n }\n shaderProgram_ = shaderProgram;\n}\n\nvoid GraphicsDevice::SetSynchronizeWithVerticalRetrace(bool value) {\n glfwSwapInterval(value);\n}\n\nvoid GraphicsDevice::SetTexture(int index, Texture2D* texture) {\n if (textures_[index] == texture) {\n return;\n }\n textures_[index] = texture;\n switch (index) {\n case 0:\n glActiveTexture(GL_TEXTURE0);\n break;\n case 1:\n glActiveTexture(GL_TEXTURE1);\n break;\n case 2:\n glActiveTexture(GL_TEXTURE2);\n break;\n case 3:\n glActiveTexture(GL_TEXTURE3);\n break;\n default:\n throw std::runtime_error(\"Unknown texture unit\");\n }\n if (texture == nullptr) {\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n else {\n glBindTexture(GL_TEXTURE_2D, texture->glTexture());\n }\n}\n\nvoid GraphicsDevice::SetVertexDataState(VertexDataState *vertexDataState) {\n if (vertexDataState == nullptr) {\n glBindVertexArray(0);\n }\n else if (vertexDataState != vertexDataState_) {\n glBindVertexArray(vertexDataState->glVertexArray());\n }\n vertexDataState_ = vertexDataState;\n}\n\nvoid GraphicsDevice::SetBlendState(BlendState state) {\n switch (state) {\n case BlendState::Additive: {\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE);\n break;\n }\n case BlendState::AlphaBlend: {\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n break;\n }\n case BlendState::Opaque: {\n glDisable(GL_BLEND);\n break;\n }\n }\n}\n\nvoid GraphicsDevice::SetDepthStencilState(DepthStencilState state) {\n switch (state) {\n case DepthStencilState::Default: {\n glEnable(GL_DEPTH_TEST);\n glDepthMask(GL_TRUE);\n break;\n }\n case DepthStencilState::DepthRead: {\n glEnable(GL_DEPTH_TEST);\n glDepthMask(GL_FALSE);\n break;\n }\n case DepthStencilState::None: {\n glDisable(GL_DEPTH_TEST);\n glDepthMask(GL_FALSE);\n break;\n }\n }\n}\n\nvoid GraphicsDevice::Initialize() {\n ScriptObjectWrap::Initialize();\n SetFunction(\"clear\", Clear);\n SetFunction(\"drawVertices\", DrawVertices);\n SetFunction(\"drawElements\", DrawElements);\n SetFunction(\"present\", Present);\n SetFunction(\"setShaderProgram\", SetShaderProgram);\n SetFunction(\"setSynchronizeWithVerticalRetrace\",\n SetSynchronizeWithVerticalRetrace);\n SetFunction(\"setVertexDataState\", ::SetVertexDataState);\n SetFunction(\"setBlendState\", ::SetBlendState);\n SetFunction(\"setDepthStencilState\", ::SetDepthStencilState);\n}\n\nvoid GraphicsDevice::Clear(const FunctionCallbackInfo& args) {\n HandleScope scope(args.GetIsolate());\n ScriptObjectHelper options(args.GetIsolate(), args[0]->ToObject());\n\n auto r = options.GetFloat(\"r\");\n auto g = options.GetFloat(\"g\");\n auto b = options.GetFloat(\"b\");\n auto a = options.GetFloat(\"a\");\n\n GetInternalObject(args.Holder())->Clear(r, g, b, a);\n}\n\nvoid GraphicsDevice::DrawVertices(const FunctionCallbackInfo &args) {\n HandleScope scope(args.GetIsolate());\n ScriptObjectHelper options(args.GetIsolate(), args[0]->ToObject());\n\n auto primitiveType = options.GetString(\"primitiveType\");\n auto vertexStart = options.GetInteger(\"vertexStart\");\n auto primitiveCount = options.GetInteger(\"primitiveCount\");\n\n PrimitiveType primitive;\n if (primitiveType == \"triangleList\") {\n primitive = PrimitiveType::TriangleList;\n }\n else if (primitiveType == \"pointList\") {\n primitive = PrimitiveType::PointList;\n }\n else if (primitiveType == \"lineList\") {\n primitive = PrimitiveType::LineList;\n }\n\n auto graphics = GetInternalObject(args.Holder());\n try {\n graphics->DrawVertices(primitive, vertexStart, primitiveCount);\n }\n catch (std::exception& ex) {\n ScriptEngine::current().ThrowTypeError(ex.what());\n }\n}\n\nvoid GraphicsDevice::DrawElements(const FunctionCallbackInfo &args) {\n HandleScope scope(args.GetIsolate());\n ScriptObjectHelper options(args.GetIsolate(), args[0]->ToObject());\n\n auto primitiveType = options.GetString(\"primitiveType\");\n auto indexStart = options.GetInteger(\"indexStart\");\n auto primitiveCount = options.GetInteger(\"primitiveCount\");\n\n PrimitiveType primitive;\n if (primitiveType == \"triangleList\") {\n primitive = PrimitiveType::TriangleList;\n }\n else if (primitiveType == \"pointList\") {\n primitive = PrimitiveType::PointList;\n }\n else if (primitiveType == \"lineList\") {\n primitive = PrimitiveType::LineList;\n }\n\n auto graphics = GetInternalObject(args.Holder());\n try {\n graphics->DrawElements(primitive, indexStart, primitiveCount);\n }\n catch (std::exception& ex) {\n ScriptEngine::current().ThrowTypeError(ex.what());\n }\n}\n\nvoid GraphicsDevice::Present(const FunctionCallbackInfo& args) {\n HandleScope scope(args.GetIsolate());\n GetInternalObject(args.Holder())->Present();\n}\n\nvoid GraphicsDevice::SetShaderProgram(const FunctionCallbackInfo& args) {\n HandleScope scope(args.GetIsolate());\n ScriptHelper helper(args.GetIsolate());\n auto shaderProgram = helper.GetObject(args[0]);\n GetInternalObject(args.Holder())->SetShaderProgram(shaderProgram);\n}\n\nvoid GraphicsDevice::SetSynchronizeWithVerticalRetrace(\n const FunctionCallbackInfo& args) {\n HandleScope scope(args.GetIsolate());\n ScriptHelper helper(args.GetIsolate());\n auto value = helper.GetBoolean(args[0]);\n GetInternalObject(args.Holder())->SetSynchronizeWithVerticalRetrace(value);\n}\nFixed spelling error.\/*The MIT License (MIT)\n\nCopyright (c) 2015 Jens Malmborg\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.*\/\n\n#include \n#include \n#include \n#include \"graphics-device.h\"\n#include \"texture-collection.h\"\n#include \"vertex-declaration.h\"\n#include \"window.h\"\n#include \"vertex-data-state.h\"\n\nusing namespace v8;\n\nnamespace {\n\nvoid SetVertexDataState(const FunctionCallbackInfo& args) {\n HandleScope scope(args.GetIsolate());\n ScriptHelper helper(args.GetIsolate());\n auto vertexBuffer = helper.GetObject(args[0]);\n helper.GetObject(args.Holder())->\n SetVertexDataState(vertexBuffer);\n}\n\nvoid SetBlendState(const FunctionCallbackInfo& args) {\n HandleScope scope(args.GetIsolate());\n ScriptHelper helper(args.GetIsolate());\n\n auto state = helper.GetString(args[0]);\n if (state == \"additive\") {\n helper.GetObject(args.Holder())->\n SetBlendState(BlendState::Additive);\n }\n else if (state == \"alphaBlend\") {\n helper.GetObject(args.Holder())->\n SetBlendState(BlendState::AlphaBlend);\n }\n else if (state == \"opaque\") {\n helper.GetObject(args.Holder())->\n SetBlendState(BlendState::Opaque);\n }\n else {\n ScriptEngine::current().ThrowTypeError(\n \"Couldn't set blend state to '\" + state + \"'.\");\n }\n}\n\nvoid SetDepthStencilState(const FunctionCallbackInfo& args) {\n HandleScope scope(args.GetIsolate());\n ScriptHelper helper(args.GetIsolate());\n\n auto state = helper.GetString(args[0]);\n if (state == \"default\") {\n helper.GetObject(args.Holder())->\n SetDepthStencilState(DepthStencilState::Default);\n }\n else if (state == \"depthRead\") {\n helper.GetObject(args.Holder())->\n SetDepthStencilState(DepthStencilState::DepthRead);\n }\n else if (state == \"none\") {\n helper.GetObject(args.Holder())->\n SetDepthStencilState(DepthStencilState::None);\n }\n else {\n ScriptEngine::current().ThrowTypeError(\n \"Couldn't set depth stencil state to '\" + state + \"'.\");\n }\n}\n\n}\n\nGraphicsDevice::GraphicsDevice(Isolate *isolate, Window *window) :\n ScriptObjectWrap(isolate), textures_(isolate, this), window_(window) {\n textures_.InstallAsObject(\"textures\", this->v8Object());\n SetBlendState(BlendState::Opaque);\n SetDepthStencilState(DepthStencilState::Default);\n}\n\nvoid GraphicsDevice::Clear(float r, float g, float b, float a) {\n glClearColor(r, g, b, a);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);\n}\n\nvoid GraphicsDevice::DrawVertices(PrimitiveType primitiveType,\n int startVertex, int primitiveCount) {\n if (vertexDataState_ == nullptr) {\n throw std::runtime_error(\n \"Vertex data state must be set before drawing vertices.\");\n }\n if (shaderProgram_ == nullptr) {\n throw std::runtime_error(\n \"Shader program must be set before drawing vertices.\");\n }\n switch (primitiveType) {\n case PrimitiveType::TriangleList:\n glDrawArrays(GL_TRIANGLES, startVertex, primitiveCount * 3);\n break;\n case PrimitiveType::PointList:\n glDrawArrays(GL_POINTS, startVertex, primitiveCount);\n break;\n case PrimitiveType::LineList:\n glDrawArrays(GL_LINES, startVertex, primitiveCount * 2);\n break;\n }\n}\n\nvoid GraphicsDevice::DrawElements(PrimitiveType primitiveType,\n int startIndex, int primitiveCount) {\n if (vertexDataState_ == nullptr) {\n throw std::runtime_error(\n \"Vertex data state must be set before drawing elements.\");\n }\n if (shaderProgram_ == nullptr) {\n throw std::runtime_error(\n \"Shader program must be set before drawing elements.\");\n }\n switch (primitiveType) {\n case PrimitiveType::TriangleList:\n glDrawElements(GL_TRIANGLES, primitiveCount * 3, GL_UNSIGNED_INT,\n (void*)(startIndex * sizeof(GLuint)));\n break;\n case PrimitiveType::PointList:\n glDrawElements(GL_TRIANGLES, primitiveCount, GL_UNSIGNED_INT,\n (void*)(startIndex * sizeof(GLuint)));\n break;\n case PrimitiveType::LineList:\n glDrawElements(GL_TRIANGLES, primitiveCount * 2, GL_UNSIGNED_INT,\n (void*)(startIndex * sizeof(GLuint)));\n break;\n }\n}\n\nvoid GraphicsDevice::Present() {\n glfwSwapBuffers(window_->glfwWindow());\n}\n\nvoid GraphicsDevice::SetShaderProgram(ShaderProgram *shaderProgram) {\n if (shaderProgram != nullptr && shaderProgram != shaderProgram_) {\n glUseProgram(shaderProgram->glProgram());\n }\n shaderProgram_ = shaderProgram;\n}\n\nvoid GraphicsDevice::SetSynchronizeWithVerticalRetrace(bool value) {\n glfwSwapInterval(value);\n}\n\nvoid GraphicsDevice::SetTexture(int index, Texture2D* texture) {\n if (textures_[index] == texture) {\n return;\n }\n textures_[index] = texture;\n switch (index) {\n case 0:\n glActiveTexture(GL_TEXTURE0);\n break;\n case 1:\n glActiveTexture(GL_TEXTURE1);\n break;\n case 2:\n glActiveTexture(GL_TEXTURE2);\n break;\n case 3:\n glActiveTexture(GL_TEXTURE3);\n break;\n default:\n throw std::runtime_error(\"Unknown texture unit\");\n }\n if (texture == nullptr) {\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n else {\n glBindTexture(GL_TEXTURE_2D, texture->glTexture());\n }\n}\n\nvoid GraphicsDevice::SetVertexDataState(VertexDataState *vertexDataState) {\n if (vertexDataState == nullptr) {\n glBindVertexArray(0);\n }\n else if (vertexDataState != vertexDataState_) {\n glBindVertexArray(vertexDataState->glVertexArray());\n }\n vertexDataState_ = vertexDataState;\n}\n\nvoid GraphicsDevice::SetBlendState(BlendState state) {\n switch (state) {\n case BlendState::Additive: {\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE);\n break;\n }\n case BlendState::AlphaBlend: {\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n break;\n }\n case BlendState::Opaque: {\n glDisable(GL_BLEND);\n break;\n }\n }\n}\n\nvoid GraphicsDevice::SetDepthStencilState(DepthStencilState state) {\n switch (state) {\n case DepthStencilState::Default: {\n glEnable(GL_DEPTH_TEST);\n glDepthMask(GL_TRUE);\n break;\n }\n case DepthStencilState::DepthRead: {\n glEnable(GL_DEPTH_TEST);\n glDepthMask(GL_FALSE);\n break;\n }\n case DepthStencilState::None: {\n glDisable(GL_DEPTH_TEST);\n glDepthMask(GL_FALSE);\n break;\n }\n }\n}\n\nvoid GraphicsDevice::Initialize() {\n ScriptObjectWrap::Initialize();\n SetFunction(\"clear\", Clear);\n SetFunction(\"drawVertices\", DrawVertices);\n SetFunction(\"drawElements\", DrawElements);\n SetFunction(\"present\", Present);\n SetFunction(\"setShaderProgram\", SetShaderProgram);\n SetFunction(\"setSynchronizeWithVerticalRetrace\",\n SetSynchronizeWithVerticalRetrace);\n SetFunction(\"setVertexDataState\", ::SetVertexDataState);\n SetFunction(\"setBlendState\", ::SetBlendState);\n SetFunction(\"setDepthStencilState\", ::SetDepthStencilState);\n}\n\nvoid GraphicsDevice::Clear(const FunctionCallbackInfo& args) {\n HandleScope scope(args.GetIsolate());\n ScriptObjectHelper options(args.GetIsolate(), args[0]->ToObject());\n\n auto r = options.GetFloat(\"r\");\n auto g = options.GetFloat(\"g\");\n auto b = options.GetFloat(\"b\");\n auto a = options.GetFloat(\"a\");\n\n GetInternalObject(args.Holder())->Clear(r, g, b, a);\n}\n\nvoid GraphicsDevice::DrawVertices(const FunctionCallbackInfo &args) {\n HandleScope scope(args.GetIsolate());\n ScriptObjectHelper options(args.GetIsolate(), args[0]->ToObject());\n\n auto primitiveType = options.GetString(\"primitiveType\");\n auto vertexStart = options.GetInteger(\"vertexStart\");\n auto primitiveCount = options.GetInteger(\"primitiveCount\");\n\n PrimitiveType primitive;\n if (primitiveType == \"triangleList\") {\n primitive = PrimitiveType::TriangleList;\n }\n else if (primitiveType == \"pointList\") {\n primitive = PrimitiveType::PointList;\n }\n else if (primitiveType == \"lineList\") {\n primitive = PrimitiveType::LineList;\n }\n\n auto graphics = GetInternalObject(args.Holder());\n try {\n graphics->DrawVertices(primitive, vertexStart, primitiveCount);\n }\n catch (std::exception& ex) {\n ScriptEngine::current().ThrowTypeError(ex.what());\n }\n}\n\nvoid GraphicsDevice::DrawElements(const FunctionCallbackInfo &args) {\n HandleScope scope(args.GetIsolate());\n ScriptObjectHelper options(args.GetIsolate(), args[0]->ToObject());\n\n auto primitiveType = options.GetString(\"primitiveType\");\n auto indexStart = options.GetInteger(\"indexStart\");\n auto primitiveCount = options.GetInteger(\"primitiveCount\");\n\n PrimitiveType primitive;\n if (primitiveType == \"triangleList\") {\n primitive = PrimitiveType::TriangleList;\n }\n else if (primitiveType == \"pointList\") {\n primitive = PrimitiveType::PointList;\n }\n else if (primitiveType == \"lineList\") {\n primitive = PrimitiveType::LineList;\n }\n\n auto graphics = GetInternalObject(args.Holder());\n try {\n graphics->DrawElements(primitive, indexStart, primitiveCount);\n }\n catch (std::exception& ex) {\n ScriptEngine::current().ThrowTypeError(ex.what());\n }\n}\n\nvoid GraphicsDevice::Present(const FunctionCallbackInfo& args) {\n HandleScope scope(args.GetIsolate());\n GetInternalObject(args.Holder())->Present();\n}\n\nvoid GraphicsDevice::SetShaderProgram(const FunctionCallbackInfo& args) {\n HandleScope scope(args.GetIsolate());\n ScriptHelper helper(args.GetIsolate());\n auto shaderProgram = helper.GetObject(args[0]);\n GetInternalObject(args.Holder())->SetShaderProgram(shaderProgram);\n}\n\nvoid GraphicsDevice::SetSynchronizeWithVerticalRetrace(\n const FunctionCallbackInfo& args) {\n HandleScope scope(args.GetIsolate());\n ScriptHelper helper(args.GetIsolate());\n auto value = helper.GetBoolean(args[0]);\n GetInternalObject(args.Holder())->SetSynchronizeWithVerticalRetrace(value);\n}\n<|endoftext|>"} {"text":"\/\/ MGBench: Multi-GPU Computing Benchmark Suite\n\/\/ Copyright (c) 2016, Tal Ben-Nun\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/ * Neither the names of the copyright holders nor the names of its \n\/\/ contributors may be used to endorse or promote products derived from this\n\/\/ software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include \n#include \n#include \n\n#include \n\nstatic void HandleError(const char *file, int line, cudaError_t err)\n{\n printf(\"ERROR in %s:%d: %s (%d)\\n\", file, line,\n cudaGetErrorString(err), err);\n cudaGetLastError();\n}\n\n\/\/ CUDA assertions\n#define CUDA_CHECK(err) do { cudaError_t errr = (err); if(errr != cudaSuccess) { HandleError(__FILE__, __LINE__, errr); exit(1); } } while(0)\n\n\/\/ Device capability helper macros\n#define CAP(cap) NCAP(cap, cap)\n#define NCAP(cap, name) ((props.cap) ? (#name \" \") : \"\")\n\nint main(int argc, char **argv)\n{\n int ndevs = 0;\n if (cudaGetDeviceCount(&ndevs) != cudaSuccess)\n return 1;\n\n int version = 0;\n CUDA_CHECK(cudaDriverGetVersion(&version));\n std::cout << \"Driver version: \" << (version \/ 1000) << \".\"\n << ((version % 100) \/ 10) << std::endl;\n\n version = 0;\n CUDA_CHECK(cudaRuntimeGetVersion(&version));\n std::cout << \"Runtime version: \" << (version \/ 1000) << \".\"\n << ((version % 100) \/ 10) << std::endl;\n std::cout << std::endl;\n\n \/\/ Print information for each GPU\n for (int i = 0; i < ndevs; ++i)\n {\n CUDA_CHECK(cudaSetDevice(i));\n cudaDeviceProp props;\n CUDA_CHECK(cudaGetDeviceProperties(&props, i));\n\n std::cout << \"GPU \" << (i + 1) << \": \" << props.name << \" (\"\n << props.pciDomainID << \"\/\" << props.pciBusID\n << \"\/\" << props.pciDeviceID << \")\" << std::endl\n\n\n << \"Global memory: \" << (props.totalGlobalMem\/1024.0\/1024.0)\n << \" MB\" << std::endl\n << \"Constant memory: \" << props.totalConstMem\n << \" bytes\" << std::endl\n << \"Shared memory: \" << props.sharedMemPerBlock\n << \" bytes\" << std::endl\n << \"Registers: \" << props.regsPerBlock << std::endl\n << \"Warp size: \" << props.warpSize << std::endl\n << \"Multiprocessors: \" << props.multiProcessorCount\n << std::endl\n << \"Copy engines: \" << props.asyncEngineCount << std::endl\n << \"Clock rate: \" << (props.clockRate \/ 1e6)\n << \" GHz\" << std::endl\n << \"Threads per MP: \" << props.maxThreadsPerMultiProcessor\n << std::endl\n << \"Threads per block: \" << props.maxThreadsPerBlock\n << std::endl\n << \"Max block size: \" << props.maxThreadsDim[0] << \"x\"\n << props.maxThreadsDim[1] << \"x\" << props.maxThreadsDim[2]\n << std::endl\n << \"Max grid size: \" << props.maxGridSize[0] << \"x\"\n << props.maxGridSize[1] << \"x\" << props.maxGridSize[2]\n << std::endl\n << \"Pitch: \" << props.memPitch << \" bytes\" << std::endl;\n\n std::cout << \"Caps: \" << NCAP(ECCEnabled, ecc)\n << NCAP(deviceOverlap, overlap)\n << NCAP(unifiedAddressing, uva)\n << NCAP(kernelExecTimeoutEnabled, timeout)\n << CAP(integrated) << NCAP(canMapHostMemory, hostdma)\n << CAP(surfaceAlignment) << CAP(tccDriver) << std::endl;\n std::cout << std::endl;\n }\n\n std::cout << \"DMA access: \" << std::endl;\n int tmp = 0;\n\n \/\/ Print top row\n printf(\" | \");\n for (int i = 0; i < ndevs; ++i)\n printf(\"%2d \", i + 1);\n printf(\"\\n---+\");\n for (int i = 0; i < ndevs; ++i)\n printf(\"---\");\n printf(\"\\n\");\n \n for (int i = 0; i < ndevs; ++i)\n {\n printf(\"%2d | \", i + 1);\n for (int j = 0; j < ndevs; ++j)\n {\n if (i == j)\n {\n printf(\" x \");\n continue;\n }\n\n cudaDeviceCanAccessPeer(&tmp, i, j);\n printf(\"%2d \", tmp ? 1 : 0);\n }\n printf(\"\\n\");\n }\n \n return 0;\n}\ndevinfo: inspect specific gpu\/\/ MGBench: Multi-GPU Computing Benchmark Suite\n\/\/ Copyright (c) 2016, Tal Ben-Nun\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/ * Neither the names of the copyright holders nor the names of its \n\/\/ contributors may be used to endorse or promote products derived from this\n\/\/ software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include \n#include \n#include \n\n#include \n\nstatic void HandleError(const char *file, int line, cudaError_t err)\n{\n printf(\"ERROR in %s:%d: %s (%d)\\n\", file, line,\n cudaGetErrorString(err), err);\n cudaGetLastError();\n}\n\n\/\/ CUDA assertions\n#define CUDA_CHECK(err) do { cudaError_t errr = (err); if(errr != cudaSuccess) { HandleError(__FILE__, __LINE__, errr); exit(1); } } while(0)\n\n\/\/ Device capability helper macros\n#define CAP(cap) NCAP(cap, cap)\n#define NCAP(cap, name) ((props.cap) ? (#name \" \") : \"\")\n\nint main(int argc, char **argv)\n{\n int ndevs = 0;\n if (cudaGetDeviceCount(&ndevs) != cudaSuccess)\n return 1;\n\n int gpuid = -1;\n if (argc > 1) {\n gpuid = atoi(argv[1]);\n }\n\n int version = 0;\n CUDA_CHECK(cudaDriverGetVersion(&version));\n std::cout << \"Driver version: \" << (version \/ 1000) << \".\"\n << ((version % 100) \/ 10) << std::endl;\n\n version = 0;\n CUDA_CHECK(cudaRuntimeGetVersion(&version));\n std::cout << \"Runtime version: \" << (version \/ 1000) << \".\"\n << ((version % 100) \/ 10) << std::endl;\n std::cout << std::endl;\n\n \/\/ Print information for each GPU\n for (int i = 0; i < ndevs; ++i)\n {\n \/\/ Skip GPUs\n if (gpuid >= 0 && i != gpuid) continue;\n\n CUDA_CHECK(cudaSetDevice(i));\n cudaDeviceProp props;\n CUDA_CHECK(cudaGetDeviceProperties(&props, i));\n\n std::cout << \"GPU \" << (i + 1) << \": \" << props.name << \" (\"\n << props.pciDomainID << \"\/\" << props.pciBusID\n << \"\/\" << props.pciDeviceID << \")\" << std::endl\n\n << \"Compute capability: sm_\" << props.major << props.minor << std::endl\n << \"Global memory: \" << (props.totalGlobalMem\/1024.0\/1024.0)\n << \" MB\" << std::endl\n << \"Constant memory: \" << props.totalConstMem\n << \" bytes\" << std::endl\n << \"Shared memory: \" << props.sharedMemPerBlock\n << \" bytes\" << std::endl\n << \"Registers: \" << props.regsPerBlock << std::endl\n << \"Warp size: \" << props.warpSize << std::endl\n << \"Multiprocessors: \" << props.multiProcessorCount\n << std::endl\n << \"Copy engines: \" << props.asyncEngineCount << std::endl\n << \"Clock rate: \" << (props.clockRate \/ 1e6)\n << \" GHz\" << std::endl\n << \"Threads per MP: \" << props.maxThreadsPerMultiProcessor\n << std::endl\n << \"Threads per block: \" << props.maxThreadsPerBlock\n << std::endl\n << \"Max block size: \" << props.maxThreadsDim[0] << \"x\"\n << props.maxThreadsDim[1] << \"x\" << props.maxThreadsDim[2]\n << std::endl\n << \"Max grid size: \" << props.maxGridSize[0] << \"x\"\n << props.maxGridSize[1] << \"x\" << props.maxGridSize[2]\n << std::endl\n << \"Pitch: \" << props.memPitch << \" bytes\" << std::endl;\n\n std::cout << \"Caps: \" << NCAP(ECCEnabled, ecc)\n << NCAP(deviceOverlap, overlap)\n << NCAP(unifiedAddressing, uva)\n << NCAP(kernelExecTimeoutEnabled, timeout)\n << CAP(integrated) << NCAP(canMapHostMemory, hostdma)\n << CAP(surfaceAlignment) << CAP(tccDriver) << std::endl;\n std::cout << std::endl;\n }\n\n std::cout << \"DMA access: \" << std::endl;\n int tmp = 0;\n\n \/\/ Print top row\n printf(\" | \");\n for (int i = 0; i < ndevs; ++i)\n printf(\"%2d \", i + 1);\n printf(\"\\n---+\");\n for (int i = 0; i < ndevs; ++i)\n printf(\"---\");\n printf(\"\\n\");\n \n for (int i = 0; i < ndevs; ++i)\n {\n printf(\"%2d | \", i + 1);\n for (int j = 0; j < ndevs; ++j)\n {\n if (i == j)\n {\n printf(\" x \");\n continue;\n }\n\n cudaDeviceCanAccessPeer(&tmp, i, j);\n printf(\"%2d \", tmp ? 1 : 0);\n }\n printf(\"\\n\");\n }\n \n return 0;\n}\n<|endoftext|>"} {"text":"#include \"gvki\/Logger.h\"\n#include \"gvki\/PathSeperator.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"string.h\"\n#include \"gvki\/Debug.h\"\n\n#include \n\n#ifndef _WIN32\n\n#include \n#include \n#define MKDIR_FAILS(d) (mkdir(d, 0770) != 0)\n#define DIR_ALREADY_EXISTS (errno == EEXIST)\n\nstatic void checkDirectoryExists(const char* dirName) {\n DIR* dh = opendir(dirName);\n if (dh != NULL)\n {\n closedir(dh);\n return;\n }\n ERROR_MSG(strerror(errno) << \". Directory was :\" << dirName);\n exit(1);\n}\n\n#else\n\n#include \n#include \n#define MKDIR_FAILS(d) (CreateDirectory(ss.str().c_str(), NULL) == 0)\n#define DIR_ALREADY_EXISTS (GetLastError() == ERROR_ALREADY_EXISTS)\n\nstatic void checkDirectoryExists(const char* dirName) {\n DWORD ftyp = GetFileAttributesA(dirName);\n if ((ftyp != INVALID_FILE_ATTRIBUTES) && ftyp & FILE_ATTRIBUTE_DIRECTORY)\n return;\n ERROR_MSG(strerror(errno) << \". Directory was :\" << dirName);\n exit(1);\n}\n\n#endif\n\nusing namespace std;\nusing namespace gvki;\n\n\/\/ Maximum number of files or directories\n\/\/ that can be created\nstatic const int maxFiles = 10000;\n\nLogger& Logger::Singleton()\n{\n static Logger l;\n return l;\n}\n\nLogger::Logger()\n{\n int count = 0;\n bool success= false;\n\n \/\/ FIXME: Reading from the environment probably doesn't belong in here\n \/\/ but it makes implementing the singleton a lot easier\n std::string directoryPrefix;\n\n const char* envTemp = getenv(\"GVKI_ROOT\");\n if (envTemp)\n {\n DEBUG_MSG(\"Using GVKI_ROOT value as destination for directories\");\n\n checkDirectoryExists(envTemp);\n\n directoryPrefix = envTemp;\n\n }\n else\n {\n \/\/ Use the current working directory\n DEBUG_MSG(\"Using current working directory as destination for directories\");\n\n \/\/ FIXME: Hard-coding this size is gross\n #define MAX_DIR_LENGTH 1024\n\n#ifndef _WIN32\n char cwdArray[MAX_DIR_LENGTH];\n char* cwdResult = getcwd(cwdArray, sizeof(cwdArray)\/sizeof(char));\n if (!cwdResult)\n#else\n char cwdResult[MAX_DIR_LENGTH];\n if (GetCurrentDirectory(MAX_DIR_LENGTH, cwdResult) == 0)\n#endif\n {\n ERROR_MSG(strerror(errno) << \". Could not read the current working directory\");\n exit(1);\n }\n else\n directoryPrefix = cwdResult;\n }\n directoryPrefix += PATH_SEP \"gvki\";\n DEBUG_MSG(\"Directory prefix is \\\"\" << directoryPrefix << \"\\\"\");\n\n \/\/ Keep trying a directoryPrefix name with a number as suffix\n \/\/ until we find an available one or we exhaust the maximum\n \/\/ allowed number\n while (count < maxFiles)\n {\n stringstream ss;\n ss << directoryPrefix << \"-\" << count;\n ++count;\n\n \/\/ Make the directoryPrefix\n if (MKDIR_FAILS(ss.str().c_str()))\n {\n if (!DIR_ALREADY_EXISTS)\n {\n ERROR_MSG(strerror(errno) << \". Directory was :\" << directoryPrefix);\n exit(1);\n }\n\n \/\/ It already exists, try again\n continue;\n }\n\n this->directory = ss.str();\n success = true;\n break;\n }\n\n if (!success)\n {\n ERROR_MSG(\"Exhausted available directory names or couldn't create any\");\n exit(1);\n }\n\n DEBUG_MSG(\"Directory used for logging is \\\"\" << this->directory << \"\\\"\");\n\n openLog();\n}\n\n\nvoid Logger::openLog()\n{\n \/\/ FIXME: We should use mkstemp() or something\n std::stringstream ss;\n ss << directory << PATH_SEP << \"log.json\";\n output = new std::ofstream(ss.str().c_str(), std::ofstream::out | std::ofstream::ate);\n\n if (! output->good())\n {\n ERROR_MSG(\"Failed to create file (\" << ss.str() << \") to write log to\");\n exit(1);\n }\n\n \/\/ Start of JSON array\n *output << \"[\" << std::endl;\n}\n\nvoid Logger::closeLog()\n{\n \/\/ End of JSON array\n *output << std::endl << \"]\" << std::endl;\n output->close();\n}\n\nLogger::~Logger()\n{\n closeLog();\n delete output;\n}\n\nvoid Logger::dump(cl_kernel k)\n{\n \/\/ Output JSON format defined by\n \/\/ http:\/\/multicore.doc.ic.ac.uk\/tools\/GPUVerify\/docs\/json_format.html\n KernelInfo& ki = kernels[k];\n\n static bool isFirst = true;\n\n if (!isFirst)\n {\n \/\/ Emit array element seperator\n \/\/ to seperate from previous dump\n *output << \",\" << endl;\n }\n isFirst = false;\n\n *output << \"{\" << endl << \"\\\"language\\\": \\\"OpenCL\\\",\" << endl;\n\n std::string kernelSourceFile = dumpKernelSource(ki);\n\n *output << \"\\\"kernel_file\\\": \\\"\" << kernelSourceFile << \"\\\",\" << endl;\n\n \/\/ FIXME: Teach GPUVerify how to handle non zero global_offset\n \/\/ FIXME: Document this json attribute!\n \/\/ Only emit global_offset if its non zero\n bool hasNonZeroGlobalOffset = false;\n for (int index=0; index < ki.globalWorkOffset.size() ; ++index)\n {\n if (ki.globalWorkOffset[index] != 0)\n hasNonZeroGlobalOffset = true;\n }\n if (hasNonZeroGlobalOffset)\n {\n *output << \"\\\"global_offset\\\": \";\n printJSONArray(ki.globalWorkOffset);\n *output << \",\" << endl;\n }\n\n *output << \"\\\"global_size\\\": \";\n printJSONArray(ki.globalWorkSize);\n *output << \",\" << endl;\n\n *output << \"\\\"local_size\\\": \";\n printJSONArray(ki.localWorkSize);\n *output << \",\" << endl;\n\n assert( (ki.globalWorkOffset.size() == ki.globalWorkSize.size()) &&\n (ki.globalWorkSize.size() == ki.localWorkSize.size()) &&\n \"dimension mismatch\");\n\n *output << \"\\\"entry_point\\\": \\\"\" << ki.entryPointName << \"\\\"\";\n\n \/\/ entry_point might be the last entry is there were no kernel args\n if (ki.arguments.size() == 0)\n *output << endl;\n else\n {\n *output << \",\" << endl << \"\\\"kernel_arguments\\\": [ \" << endl;\n for (int argIndex=0; argIndex < ki.arguments.size() ; ++argIndex)\n {\n printJSONKernelArgumentInfo(ki.arguments[argIndex]);\n if (argIndex != (ki.arguments.size() -1))\n *output << \",\" << endl;\n }\n *output << endl << \"]\" << endl;\n }\n\n\n *output << \"}\";\n}\n\nvoid Logger::printJSONArray(std::vector& array)\n{\n *output << \"[ \";\n for (int index=0; index < array.size(); ++index)\n {\n *output << array[index];\n\n if (index != (array.size() -1))\n *output << \", \";\n }\n *output << \"]\";\n}\n\nvoid Logger::printJSONKernelArgumentInfo(ArgInfo& ai)\n{\n *output << \"{\";\n if (ai.argValue == NULL)\n {\n \/\/ NULL was passed to clSetKernelArg()\n \/\/ That implies its for unallocated memory\n *output << \"\\\"type\\\": \\\"array\\\",\";\n\n \/\/ If the arg is for local memory\n if (ai.argSize != sizeof(cl_mem) && ai.argSize != sizeof(cl_sampler))\n {\n \/\/ We assume this means this arguments is for local memory\n \/\/ where size actually means the sizeof the underlying buffer\n \/\/ rather than the size of the type.\n *output << \"\\\"size\\\" : \" << ai.argSize;\n }\n *output << \"}\";\n return;\n }\n\n \/\/ FIXME:\n \/\/ Eurgh... the spec says\n \/\/ ```\n \/\/ If the argument is a buffer object, the arg_value pointer can be NULL or\n \/\/ point to a NULL value in which case a NULL value will be used as the\n \/\/ value for the argument declared as a pointer to __global or __constant\n \/\/ memory in the kernel. ```\n \/\/\n \/\/ This makes it impossible (seeing as we don't know which address space\n \/\/ the arguments are in) to work out the argument type once derefencing the\n \/\/ pointer and finding it's equal zero because it could be a scalar constant\n \/\/ (of value 0) or it could be an unintialised array!\n\n \/\/ Hack:\n \/\/ It's hard to determine what type the argument is.\n \/\/ We can't dereference the void* to check if\n \/\/ it points to cl_mem we previously stored\n \/\/\n \/\/ In some implementations cl_mem will be a pointer\n \/\/ which poses a risk if a scalar parameter of the same size\n \/\/ as the pointer type.\n if (ai.argSize == sizeof(cl_mem))\n {\n cl_mem mightBecl_mem = *((cl_mem*) ai.argValue);\n\n \/\/ We might be reading invalid data now\n if (buffers.count(mightBecl_mem) == 1)\n {\n \/\/ We're going to assume it's cl_mem that we saw before\n *output << \"\\\"type\\\": \\\"array\\\",\";\n BufferInfo& bi = buffers[mightBecl_mem];\n\n *output << \"\\\"size\\\": \" << bi.size << \"}\";\n return;\n }\n\n }\n\n \/\/ Hack: a similar hack of the image types\n if (ai.argSize == sizeof(cl_mem))\n {\n cl_mem mightBecl_mem = *((cl_mem*) ai.argValue);\n\n \/\/ We might be reading invalid data now\n if (images.count(mightBecl_mem) == 1)\n {\n \/\/ We're going to assume it's cl_mem that we saw before\n *output << \"\\\"type\\\": \\\"image\\\"}\";\n return;\n }\n\n }\n\n \/\/ Hack: a similar hack for the samplers\n if (ai.argSize == sizeof(cl_sampler))\n {\n cl_sampler mightBecl_sampler = *((cl_sampler*) ai.argValue);\n\n \/\/ We might be reading invalid data now\n if (samplers.count(mightBecl_sampler) == 1)\n {\n \/\/ We're going to assume it's cl_mem that we saw before\n *output << \"\\\"type\\\": \\\"sampler\\\"}\";\n return;\n }\n\n }\n\n \/\/ I guess it's scalar???\n *output << \"\\\"type\\\": \\\"scalar\\\",\";\n *output << \" \\\"value\\\": \\\"0x\";\n \/\/ Print the value as hex\n uint8_t* asByte = (uint8_t*) ai.argValue;\n \/\/ We assume the host is little endian so to print the values\n \/\/ we need to go through the array bytes backwards\n for (int byteIndex= ai.argSize -1; byteIndex >=0 ; --byteIndex)\n {\n *output << std::hex << std::setfill('0') << std::setw(2) << ( (unsigned) asByte[byteIndex]);\n }\n *output << \"\\\"\" << std::dec; \/\/std::hex is sticky so switch back to decimal\n\n *output << \"}\";\n return;\n\n}\n\nstatic bool file_exists(std::string& name) {\n\tifstream f(name.c_str());\n\tbool result = f.good();\n\tf.close();\n\treturn result;\n}\n\n\/\/ Define the strict weak ordering over ProgramInfo instances\n\/\/ Is this correct?\nbool ProgramInfoCacheCompare::operator() (const ProgramInfo& lhs, const ProgramInfo& rhs) const\n{\n \/\/ Use the fact that a strict-weak order is already defined over std::vector<>\n return lhs.sources < rhs.sources;\n}\n\nstd::string Logger::dumpKernelSource(KernelInfo& ki)\n{\n ProgramInfo& pi = programs[ki.program];\n\n \/\/ See if we can used a file that we already printed.\n \/\/ This avoid writing duplicate files.\n ProgCacheMapTy::iterator it = WrittenKernelFileCache.find(pi);\n if ( it != WrittenKernelFileCache.end() )\n {\n return it->second;\n }\n\n\n int count = 0;\n bool success = false;\n \/\/ FIXME: I really want a std::unique_ptr\n std::ofstream* kos = 0;\n std::string theKernelPath;\n while (count < maxFiles)\n {\n stringstream ss;\n ss << ki.entryPointName << \".\" << count << \".cl\";\n\n ++count;\n\n std::string withDir = (directory + PATH_SEP) + ss.str();\n if (!file_exists(withDir))\n {\n kos = new std::ofstream(withDir.c_str());\n\n if (!kos->good())\n {\n kos->close();\n delete kos;\n continue;\n }\n\n success = true;\n theKernelPath = ss.str();\n break;\n }\n }\n\n if (!success)\n {\n ERROR_MSG(\"Failed to log kernel output\");\n return std::string(\"FIXME\");\n }\n\n \/\/ Write kernel source\n\n for (vector::const_iterator b = pi.sources.begin(), e = pi.sources.end(); b != e; ++b)\n {\n *kos << *b;\n }\n\n \/\/ Urgh this is bad, need RAII!\n kos->close();\n delete kos;\n\n \/\/ Store in cache\n assert(WrittenKernelFileCache.count(pi) == 0 && \"ProgramInfo already in cache!\");\n WrittenKernelFileCache[pi] = theKernelPath;\n\n return theKernelPath;\n}\nAdded output of memory flags.#include \"gvki\/Logger.h\"\n#include \"gvki\/PathSeperator.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"string.h\"\n#include \"gvki\/Debug.h\"\n\n#include \n\n#ifndef _WIN32\n\n#include \n#include \n#define MKDIR_FAILS(d) (mkdir(d, 0770) != 0)\n#define DIR_ALREADY_EXISTS (errno == EEXIST)\n\nstatic void checkDirectoryExists(const char* dirName) {\n DIR* dh = opendir(dirName);\n if (dh != NULL)\n {\n closedir(dh);\n return;\n }\n ERROR_MSG(strerror(errno) << \". Directory was :\" << dirName);\n exit(1);\n}\n\n#else\n\n#include \n#include \n#define MKDIR_FAILS(d) (CreateDirectory(ss.str().c_str(), NULL) == 0)\n#define DIR_ALREADY_EXISTS (GetLastError() == ERROR_ALREADY_EXISTS)\n\nstatic void checkDirectoryExists(const char* dirName) {\n DWORD ftyp = GetFileAttributesA(dirName);\n if ((ftyp != INVALID_FILE_ATTRIBUTES) && ftyp & FILE_ATTRIBUTE_DIRECTORY)\n return;\n ERROR_MSG(strerror(errno) << \". Directory was :\" << dirName);\n exit(1);\n}\n\n#endif\n\nusing namespace std;\nusing namespace gvki;\n\n\/\/ Maximum number of files or directories\n\/\/ that can be created\nstatic const int maxFiles = 10000;\n\nLogger& Logger::Singleton()\n{\n static Logger l;\n return l;\n}\n\nLogger::Logger()\n{\n int count = 0;\n bool success= false;\n\n \/\/ FIXME: Reading from the environment probably doesn't belong in here\n \/\/ but it makes implementing the singleton a lot easier\n std::string directoryPrefix;\n\n const char* envTemp = getenv(\"GVKI_ROOT\");\n if (envTemp)\n {\n DEBUG_MSG(\"Using GVKI_ROOT value as destination for directories\");\n\n checkDirectoryExists(envTemp);\n\n directoryPrefix = envTemp;\n\n }\n else\n {\n \/\/ Use the current working directory\n DEBUG_MSG(\"Using current working directory as destination for directories\");\n\n \/\/ FIXME: Hard-coding this size is gross\n #define MAX_DIR_LENGTH 1024\n\n#ifndef _WIN32\n char cwdArray[MAX_DIR_LENGTH];\n char* cwdResult = getcwd(cwdArray, sizeof(cwdArray)\/sizeof(char));\n if (!cwdResult)\n#else\n char cwdResult[MAX_DIR_LENGTH];\n if (GetCurrentDirectory(MAX_DIR_LENGTH, cwdResult) == 0)\n#endif\n {\n ERROR_MSG(strerror(errno) << \". Could not read the current working directory\");\n exit(1);\n }\n else\n directoryPrefix = cwdResult;\n }\n directoryPrefix += PATH_SEP \"gvki\";\n DEBUG_MSG(\"Directory prefix is \\\"\" << directoryPrefix << \"\\\"\");\n\n \/\/ Keep trying a directoryPrefix name with a number as suffix\n \/\/ until we find an available one or we exhaust the maximum\n \/\/ allowed number\n while (count < maxFiles)\n {\n stringstream ss;\n ss << directoryPrefix << \"-\" << count;\n ++count;\n\n \/\/ Make the directoryPrefix\n if (MKDIR_FAILS(ss.str().c_str()))\n {\n if (!DIR_ALREADY_EXISTS)\n {\n ERROR_MSG(strerror(errno) << \". Directory was :\" << directoryPrefix);\n exit(1);\n }\n\n \/\/ It already exists, try again\n continue;\n }\n\n this->directory = ss.str();\n success = true;\n break;\n }\n\n if (!success)\n {\n ERROR_MSG(\"Exhausted available directory names or couldn't create any\");\n exit(1);\n }\n\n DEBUG_MSG(\"Directory used for logging is \\\"\" << this->directory << \"\\\"\");\n\n openLog();\n}\n\n\nvoid Logger::openLog()\n{\n \/\/ FIXME: We should use mkstemp() or something\n std::stringstream ss;\n ss << directory << PATH_SEP << \"log.json\";\n output = new std::ofstream(ss.str().c_str(), std::ofstream::out | std::ofstream::ate);\n\n if (! output->good())\n {\n ERROR_MSG(\"Failed to create file (\" << ss.str() << \") to write log to\");\n exit(1);\n }\n\n \/\/ Start of JSON array\n *output << \"[\" << std::endl;\n}\n\nvoid Logger::closeLog()\n{\n \/\/ End of JSON array\n *output << std::endl << \"]\" << std::endl;\n output->close();\n}\n\nLogger::~Logger()\n{\n closeLog();\n delete output;\n}\n\nvoid Logger::dump(cl_kernel k)\n{\n \/\/ Output JSON format defined by\n \/\/ http:\/\/multicore.doc.ic.ac.uk\/tools\/GPUVerify\/docs\/json_format.html\n KernelInfo& ki = kernels[k];\n\n static bool isFirst = true;\n\n if (!isFirst)\n {\n \/\/ Emit array element seperator\n \/\/ to seperate from previous dump\n *output << \",\" << endl;\n }\n isFirst = false;\n\n *output << \"{\" << endl << \"\\\"language\\\": \\\"OpenCL\\\",\" << endl;\n\n std::string kernelSourceFile = dumpKernelSource(ki);\n\n *output << \"\\\"kernel_file\\\": \\\"\" << kernelSourceFile << \"\\\",\" << endl;\n\n \/\/ FIXME: Teach GPUVerify how to handle non zero global_offset\n \/\/ FIXME: Document this json attribute!\n \/\/ Only emit global_offset if its non zero\n bool hasNonZeroGlobalOffset = false;\n for (int index=0; index < ki.globalWorkOffset.size() ; ++index)\n {\n if (ki.globalWorkOffset[index] != 0)\n hasNonZeroGlobalOffset = true;\n }\n if (hasNonZeroGlobalOffset)\n {\n *output << \"\\\"global_offset\\\": \";\n printJSONArray(ki.globalWorkOffset);\n *output << \",\" << endl;\n }\n\n *output << \"\\\"global_size\\\": \";\n printJSONArray(ki.globalWorkSize);\n *output << \",\" << endl;\n\n *output << \"\\\"local_size\\\": \";\n printJSONArray(ki.localWorkSize);\n *output << \",\" << endl;\n\n assert( (ki.globalWorkOffset.size() == ki.globalWorkSize.size()) &&\n (ki.globalWorkSize.size() == ki.localWorkSize.size()) &&\n \"dimension mismatch\");\n\n *output << \"\\\"entry_point\\\": \\\"\" << ki.entryPointName << \"\\\"\";\n\n \/\/ entry_point might be the last entry is there were no kernel args\n if (ki.arguments.size() == 0)\n *output << endl;\n else\n {\n *output << \",\" << endl << \"\\\"kernel_arguments\\\": [ \" << endl;\n for (int argIndex=0; argIndex < ki.arguments.size() ; ++argIndex)\n {\n printJSONKernelArgumentInfo(ki.arguments[argIndex]);\n if (argIndex != (ki.arguments.size() -1))\n *output << \",\" << endl;\n }\n *output << endl << \"]\" << endl;\n }\n\n\n *output << \"}\";\n}\n\nvoid Logger::printJSONArray(std::vector& array)\n{\n *output << \"[ \";\n for (int index=0; index < array.size(); ++index)\n {\n *output << array[index];\n\n if (index != (array.size() -1))\n *output << \", \";\n }\n *output << \"]\";\n}\n\nvoid Logger::printJSONKernelArgumentInfo(ArgInfo& ai)\n{\n *output << \"{\";\n if (ai.argValue == NULL)\n {\n \/\/ NULL was passed to clSetKernelArg()\n \/\/ That implies its for unallocated memory\n *output << \"\\\"type\\\": \\\"array\\\",\";\n\n \/\/ If the arg is for local memory\n if (ai.argSize != sizeof(cl_mem) && ai.argSize != sizeof(cl_sampler))\n {\n \/\/ We assume this means this arguments is for local memory\n \/\/ where size actually means the sizeof the underlying buffer\n \/\/ rather than the size of the type.\n *output << \"\\\"size\\\" : \" << ai.argSize;\n }\n *output << \"}\";\n return;\n }\n\n \/\/ FIXME:\n \/\/ Eurgh... the spec says\n \/\/ ```\n \/\/ If the argument is a buffer object, the arg_value pointer can be NULL or\n \/\/ point to a NULL value in which case a NULL value will be used as the\n \/\/ value for the argument declared as a pointer to __global or __constant\n \/\/ memory in the kernel. ```\n \/\/\n \/\/ This makes it impossible (seeing as we don't know which address space\n \/\/ the arguments are in) to work out the argument type once derefencing the\n \/\/ pointer and finding it's equal zero because it could be a scalar constant\n \/\/ (of value 0) or it could be an unintialised array!\n\n \/\/ Hack:\n \/\/ It's hard to determine what type the argument is.\n \/\/ We can't dereference the void* to check if\n \/\/ it points to cl_mem we previously stored\n \/\/\n \/\/ In some implementations cl_mem will be a pointer\n \/\/ which poses a risk if a scalar parameter of the same size\n \/\/ as the pointer type.\n if (ai.argSize == sizeof(cl_mem))\n {\n cl_mem mightBecl_mem = *((cl_mem*) ai.argValue);\n\n \/\/ We might be reading invalid data now\n if (buffers.count(mightBecl_mem) == 1)\n {\n \/\/ We're going to assume it's cl_mem that we saw before\n *output << \"\\\"type\\\": \\\"array\\\", \";\n BufferInfo& bi = buffers[mightBecl_mem];\n\n *output << \"\\\"size\\\": \" << bi.size << \", \";\n\n *output << \"\\\"flags\\\": \\\"\";\n switch (bi.flags) {\n case CL_MEM_READ_ONLY:\n *output << \"CL_MEM_READ_ONLY\";\n break;\n case CL_MEM_WRITE_ONLY:\n *output << \"CL_MEM_WRITE_ONLY\";\n break;\n case CL_MEM_READ_WRITE:\n *output << \"CL_MEM_READ_WRITE\";\n break;\n default:\n *output << \"UNKNOWN\";\n }\n\n *output << \"\\\"}\";\n\n return;\n }\n\n }\n\n \/\/ Hack: a similar hack of the image types\n if (ai.argSize == sizeof(cl_mem))\n {\n cl_mem mightBecl_mem = *((cl_mem*) ai.argValue);\n\n \/\/ We might be reading invalid data now\n if (images.count(mightBecl_mem) == 1)\n {\n \/\/ We're going to assume it's cl_mem that we saw before\n *output << \"\\\"type\\\": \\\"image\\\"}\";\n return;\n }\n\n }\n\n \/\/ Hack: a similar hack for the samplers\n if (ai.argSize == sizeof(cl_sampler))\n {\n cl_sampler mightBecl_sampler = *((cl_sampler*) ai.argValue);\n\n \/\/ We might be reading invalid data now\n if (samplers.count(mightBecl_sampler) == 1)\n {\n \/\/ We're going to assume it's cl_mem that we saw before\n *output << \"\\\"type\\\": \\\"sampler\\\"}\";\n return;\n }\n\n }\n\n \/\/ I guess it's scalar???\n *output << \"\\\"type\\\": \\\"scalar\\\",\";\n *output << \" \\\"value\\\": \\\"0x\";\n \/\/ Print the value as hex\n uint8_t* asByte = (uint8_t*) ai.argValue;\n \/\/ We assume the host is little endian so to print the values\n \/\/ we need to go through the array bytes backwards\n for (int byteIndex= ai.argSize -1; byteIndex >=0 ; --byteIndex)\n {\n *output << std::hex << std::setfill('0') << std::setw(2) << ( (unsigned) asByte[byteIndex]);\n }\n *output << \"\\\"\" << std::dec; \/\/std::hex is sticky so switch back to decimal\n\n *output << \"}\";\n return;\n\n}\n\nstatic bool file_exists(std::string& name) {\n\tifstream f(name.c_str());\n\tbool result = f.good();\n\tf.close();\n\treturn result;\n}\n\n\/\/ Define the strict weak ordering over ProgramInfo instances\n\/\/ Is this correct?\nbool ProgramInfoCacheCompare::operator() (const ProgramInfo& lhs, const ProgramInfo& rhs) const\n{\n \/\/ Use the fact that a strict-weak order is already defined over std::vector<>\n return lhs.sources < rhs.sources;\n}\n\nstd::string Logger::dumpKernelSource(KernelInfo& ki)\n{\n ProgramInfo& pi = programs[ki.program];\n\n \/\/ See if we can used a file that we already printed.\n \/\/ This avoid writing duplicate files.\n ProgCacheMapTy::iterator it = WrittenKernelFileCache.find(pi);\n if ( it != WrittenKernelFileCache.end() )\n {\n return it->second;\n }\n\n\n int count = 0;\n bool success = false;\n \/\/ FIXME: I really want a std::unique_ptr\n std::ofstream* kos = 0;\n std::string theKernelPath;\n while (count < maxFiles)\n {\n stringstream ss;\n ss << ki.entryPointName << \".\" << count << \".cl\";\n\n ++count;\n\n std::string withDir = (directory + PATH_SEP) + ss.str();\n if (!file_exists(withDir))\n {\n kos = new std::ofstream(withDir.c_str());\n\n if (!kos->good())\n {\n kos->close();\n delete kos;\n continue;\n }\n\n success = true;\n theKernelPath = ss.str();\n break;\n }\n }\n\n if (!success)\n {\n ERROR_MSG(\"Failed to log kernel output\");\n return std::string(\"FIXME\");\n }\n\n \/\/ Write kernel source\n\n for (vector::const_iterator b = pi.sources.begin(), e = pi.sources.end(); b != e; ++b)\n {\n *kos << *b;\n }\n\n \/\/ Urgh this is bad, need RAII!\n kos->close();\n delete kos;\n\n \/\/ Store in cache\n assert(WrittenKernelFileCache.count(pi) == 0 && \"ProgramInfo already in cache!\");\n WrittenKernelFileCache[pi] = theKernelPath;\n\n return theKernelPath;\n}\n<|endoftext|>"} {"text":"\/\/ @(#)root\/gpad:$Id$\n\/\/ Author: Rene Brun 19\/02\/2007\n\n\/*************************************************************************\n * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TView.h\"\n#include \"TROOT.h\"\n#include \"TPluginManager.h\"\n\nClassImp(TView)\n\n\/\/____________________________________________________________________________\nTView::TView(const TView& tv) :\n TObject(tv),\n TAttLine(tv)\n{\n \/\/ Copy constructor.\n}\n\n\/\/____________________________________________________________________________\nTView *TView::CreateView(Int_t system, const Double_t *rmin, const Double_t *rmax) \n{\n \/\/ Create a concrete default 3-d view via the plug-in manager\n \n TView *view = 0;\n TPluginHandler *h;\n if ((h = gROOT->GetPluginManager()->FindHandler(\"TView\"))) {\n if (h->LoadPlugin() == -1)\n return 0;\n view = (TView*)h->ExecPlugin(3,system,rmin,rmax);\n }\n return view;\n}\n- Add header\/\/ @(#)root\/gpad:$Id$\n\/\/ Author: Rene Brun 19\/02\/2007\n\n\/*************************************************************************\n * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TView.h\"\n#include \"TROOT.h\"\n#include \"TPluginManager.h\"\n\nClassImp(TView)\n\n\/\/______________________________________________________________________________\n\/* Begin_Html\nSee TView3D\nEnd_Html *\/\n\n\/\/____________________________________________________________________________\nTView::TView(const TView& tv) :\n TObject(tv),\n TAttLine(tv)\n{\n \/\/ Copy constructor.\n}\n\n\/\/____________________________________________________________________________\nTView *TView::CreateView(Int_t system, const Double_t *rmin, const Double_t *rmax) \n{\n \/\/ Create a concrete default 3-d view via the plug-in manager\n \n TView *view = 0;\n TPluginHandler *h;\n if ((h = gROOT->GetPluginManager()->FindHandler(\"TView\"))) {\n if (h->LoadPlugin() == -1)\n return 0;\n view = (TView*)h->ExecPlugin(3,system,rmin,rmax);\n }\n return view;\n}\n<|endoftext|>"} {"text":"\/\/-----------------------------------------------------------------------\n\/\/ Copyright 2011 Ciaran McHale.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal in the Software without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject to\n\/\/ the following conditions.\n\/\/\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software. \n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n\/\/ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/----------------------------------------------------------------------\n\n#include \"platform.h\"\n#include \n#include \n#include \n#ifdef P_STDIO_HAS_LIMITED_FDS\n#\tifdef WIN32\n\t\t\/\/--------\n\t\t\/\/ Windows does NOT suffer from this problem. However, we can\n\t\t\/\/ pretend it does so we can compile and test both versions of\n\t\t\/\/ the BufferedFileReader class on Windows.\n\t\t\/\/--------\n#\t\tinclude \n#\t\tinclude \n#\telse\n#\t\tinclude \n#\t\tinclude \n#\t\tinclude \n#\tendif\n#endif\n\n\nnamespace CONFIG4CPP_NAMESPACE {\n\nbool\nexecCmd(const char * cmd, StringBuffer & output)\n{\n\tStringBuffer\t\t\tmodifiedCmd;\n\tFILE *\t\t\t\t\tpipe;\n\tint\t\t\t\t\t\tch;\n\tint\t\t\t\t\t\tlen;\n\tint\t\t\t\t\t\tpcloseStatus;\n\n\toutput.empty();\n\n\t\/\/--------\n\t\/\/ Execute the command with its stderr and stdout merged together.\n\t\/\/ TO DO: the \"modifiedCmd\" below works on Linux and in a cmd\n\t\/\/ shell on Windows, but sometimes it does not work in a Cygwin\n\t\/\/ shell.\n\t\/\/--------\n\tmodifiedCmd << cmd << \" 2>&1\";\n\t\/\/modifiedCmd << cmd;\n\tpipe = CONFIG4CPP_POPEN(modifiedCmd.c_str(), \"r\");\n\tif (!pipe) {\n\t\toutput << \"cannot execute '\" << cmd << \"': popen() failed\";\n\t\treturn false;\n\t}\n\n\t\/\/--------\n\t\/\/ Read from the pipe and delete the final '\\n', if any.\n\t\/\/--------\n\twhile ((ch = fgetc(pipe)) != EOF) {\n\t\tif (ch != '\\r') {\n\t\t\toutput.append((char)ch);\n\t\t}\n\t}\n\tlen = output.length();\n\tif (len > 0 && output[len-1] == '\\n') {\n\t\toutput.deleteLastChar();\n\t}\n\n\t\/\/--------\n\t\/\/ We're done. Return success (true) if the exit status of\n\t\/\/ the command was 0.\n\t\/\/--------\n\tpcloseStatus = CONFIG4CPP_PCLOSE(pipe);\n\treturn (pcloseStatus == 0);\n}\n\n\n\n#ifdef WIN32\n\/\/--------\n\/\/ Windows version.\n\/\/--------\n#include \nbool\nisCmdInDir(const char * cmd, const char * dir)\n{\n\tStringBuffer\t\t\tfileName;\n\tstatic const char *\t\textensions[] = { \"\", \".exe\", \".bat\", 0 };\n\tint\t\t\t\t\t\ti;\n\tDWORD\t\t\t\t\tfileAttr;\n\n\tfor (i = 0; extensions[i] != 0; i++) {\n\t\tfileName = \"\";\n\t\tfileName << dir << \"\\\\\" << cmd << extensions[i];\n\t\tfileAttr = GetFileAttributes(fileName.c_str());\n\t\tif (fileAttr != 0xFFFFFFFF) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n#else\n\/\/--------\n\/\/ UNIX version.\n\/\/--------\n#include \n#include \n#include \nbool\nisCmdInDir(const char * cmd, const char * dir)\n{\n\tStringBuffer\t\tfileName;\n\tstruct stat\t\t\tsb;\n\n\tfileName << dir << \"\/\" << cmd;\n\tif (stat(fileName.c_str(), &sb) == 0) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n#endif\n\n\n\n#ifdef P_STDIO_HAS_LIMITED_FDS\n\nBufferedFileReader::BufferedFileReader()\n{\n\tm_fd = -1;\n}\n\nBufferedFileReader::~BufferedFileReader()\n{\n\tif (m_fd != -1) {\n\t\tclose();\n\t}\n}\n\nbool\nBufferedFileReader::open(const char * fileName)\n{\n\tassert(m_fd == -1);\n\tm_fd = ::open(fileName, O_RDONLY);\n\tm_bufIndex = 0;\n\tm_bufLen = 0;\n\treturn (m_fd != -1);\n}\n\nbool\nBufferedFileReader::close()\n{\n\tint\t\t\t\tresult;\n\n\tassert(m_fd != -1);\n\tresult = ::close(m_fd);\n\tif (result != -1) {\n\t\tm_fd = -1;\n\t}\n\treturn (result != -1);\n}\n\nint\nBufferedFileReader::getChar()\n{\n\tint\t\t\t\tsize;\n\tint\t\t\t\tresult;\n\n\tassert(m_fd != -1);\n\tif (m_bufIndex == m_bufLen) {\n\t\tsize = ::read(m_fd, m_buf, BUFFERED_FILE_READER_BUF_SIZE);\n\t\tm_bufIndex = 0;\n\t\tm_bufLen = size;\n\t\tif (size <= 0) {\n\t\t\tm_bufLen = 0;\n\t\t\treturn EOF;\n\t\t}\n\t}\n\tassert(m_bufIndex < m_bufLen);\n\tresult = m_buf[m_bufIndex];\n\tm_bufIndex++;\n\treturn result;\n}\n\n#else\n\nBufferedFileReader::BufferedFileReader()\n{\n\tm_file = 0;\n}\n\nBufferedFileReader::~BufferedFileReader()\n{\n\tif (m_file != 0) {\n\t\tfclose(m_file);\n\t}\n}\n\nbool\nBufferedFileReader::open(const char * fileName)\n{\n\tassert(m_file == 0);\n\tm_file = fopen(fileName, \"r\");\n\treturn (m_file != 0);\n}\n\nbool\nBufferedFileReader::close()\n{\n\tint\t\t\t\tstatus;\n\n\tstatus = fclose(m_file);\n\treturn (status != -1);\n}\n\nint\nBufferedFileReader::getChar()\n{\n\tassert(m_file != 0);\n\treturn fgetc(m_file);\n}\n\n#endif\n} \/\/ namespace CONFIG4CPP_NAMESPACE\nFixes.\/\/-----------------------------------------------------------------------\n\/\/ Copyright 2011 Ciaran McHale.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal in the Software without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject to\n\/\/ the following conditions.\n\/\/\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n\/\/ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/----------------------------------------------------------------------\n\n#include \"platform.h\"\n#include \n#include \n#include \n#ifdef P_STDIO_HAS_LIMITED_FDS\n#\tifdef WIN32\n\t\t\/\/--------\n\t\t\/\/ Windows does NOT suffer from this problem. However, we can\n\t\t\/\/ pretend it does so we can compile and test both versions of\n\t\t\/\/ the BufferedFileReader class on Windows.\n\t\t\/\/--------\n#\t\tinclude \n#\t\tinclude \n#\telse\n#\t\tinclude \n#\t\tinclude \n#\t\tinclude \n#\tendif\n#endif\n\n\nnamespace CONFIG4CPP_NAMESPACE {\n\nbool\nexecCmd(const char * cmd, StringBuffer & output)\n{\n\tStringBuffer\t\t\tmodifiedCmd;\n\tFILE *\t\t\t\t\tpipe;\n\tint\t\t\t\t\t\tch;\n\tint\t\t\t\t\t\tlen;\n\tint\t\t\t\t\t\tpcloseStatus;\n\n\toutput.empty();\n\n\t\/\/--------\n\t\/\/ Execute the command with its stderr and stdout merged together.\n\t\/\/ TO DO: the \"modifiedCmd\" below works on Linux and in a cmd\n\t\/\/ shell on Windows, but sometimes it does not work in a Cygwin\n\t\/\/ shell.\n\t\/\/--------\n\tmodifiedCmd << cmd << \" 2>&1\";\n\t\/\/modifiedCmd << cmd;\n\tpipe = CONFIG4CPP_POPEN(modifiedCmd.c_str(), \"r\");\n\tif (!pipe) {\n\t\toutput << \"cannot execute '\" << cmd << \"': popen() failed\";\n\t\treturn false;\n\t}\n\n\t\/\/--------\n\t\/\/ Read from the pipe and delete the final '\\n', if any.\n\t\/\/--------\n\twhile ((ch = fgetc(pipe)) != EOF) {\n\t\tif (ch != '\\r') {\n\t\t\toutput.append((char)ch);\n\t\t}\n\t}\n\tlen = output.length();\n\tif (len > 0 && output[len-1] == '\\n') {\n\t\toutput.deleteLastChar();\n\t}\n\n\t\/\/--------\n\t\/\/ We're done. Return success (true) if the exit status of\n\t\/\/ the command was 0.\n\t\/\/--------\n\tpcloseStatus = CONFIG4CPP_PCLOSE(pipe);\n\treturn (pcloseStatus == 0);\n}\n\n\n\n#ifdef WIN32\n\/\/--------\n\/\/ Windows version.\n\/\/--------\n#include \nbool\nisCmdInDir(const char * cmd, const char * dir)\n{\n\tStringBuffer\t\t\tfileName;\n\tstatic const char *\t\textensions[] = { \"\", \".exe\", \".bat\", 0 };\n\tint\t\t\t\t\t\ti;\n\tDWORD\t\t\t\t\tfileAttr;\n\n\tfor (i = 0; extensions[i] != 0; i++) {\n\t\tfileName = \"\";\n\t\tfileName << dir << \"\\\\\" << cmd << extensions[i];\n\t\tfileAttr = GetFileAttributes(fileName.c_str());\n\t\tif (fileAttr != 0xFFFFFFFF) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n#else\n\/\/--------\n\/\/ UNIX version.\n\/\/--------\n#include \n#include \n#include \nbool\nisCmdInDir(const char * cmd, const char * dir)\n{\n\tStringBuffer\t\tfileName;\n\tstruct stat\t\t\tsb;\n\n\tfileName << dir << \"\/\" << cmd;\n\tif (stat(fileName.c_str(), &sb) == 0) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n#endif\n\n\n\n#ifdef P_STDIO_HAS_LIMITED_FDS\n\nBufferedFileReader::BufferedFileReader() : m_fd(-1), m_buf(nullptr), m_bufIndex(0), m_bufLen(0)\n{\n}\n\nBufferedFileReader::~BufferedFileReader()\n{\n\tif (m_fd != -1) {\n\t\tclose();\n\t}\n}\n\nbool\nBufferedFileReader::open(const char * fileName)\n{\n\tassert(m_fd == -1);\n\tm_fd = ::open(fileName, O_RDONLY);\n\tm_bufIndex = 0;\n\tm_bufLen = 0;\n\treturn (m_fd != -1);\n}\n\nbool\nBufferedFileReader::close()\n{\n\tint\t\t\t\tresult;\n\n\tassert(m_fd != -1);\n\tresult = ::close(m_fd);\n\tif (result != -1) {\n\t\tm_fd = -1;\n\t}\n\treturn (result != -1);\n}\n\nint\nBufferedFileReader::getChar()\n{\n\tint\t\t\t\tresult;\n\n\tassert(m_fd != -1);\n\tif (m_bufIndex == m_bufLen) {\n\t\tint size = ::read(m_fd, m_buf, BUFFERED_FILE_READER_BUF_SIZE);\n\t\tm_bufIndex = 0;\n\t\tm_bufLen = size;\n\t\tif (size <= 0) {\n\t\t\tm_bufLen = 0;\n\t\t\treturn EOF;\n\t\t}\n\t}\n\tassert(m_bufIndex < m_bufLen);\n\tresult = m_buf[m_bufIndex];\n\tm_bufIndex++;\n\treturn result;\n}\n\n#else\n\nBufferedFileReader::BufferedFileReader()\n{\n\tm_file = 0;\n}\n\nBufferedFileReader::~BufferedFileReader()\n{\n\tif (m_file != 0) {\n\t\tfclose(m_file);\n\t}\n}\n\nbool\nBufferedFileReader::open(const char * fileName)\n{\n\tassert(m_file == 0);\n\tm_file = fopen(fileName, \"r\");\n\treturn (m_file != 0);\n}\n\nbool\nBufferedFileReader::close()\n{\n\tint\t\t\t\tstatus;\n\n\tstatus = fclose(m_file);\n\treturn (status != -1);\n}\n\nint\nBufferedFileReader::getChar()\n{\n\tassert(m_file != 0);\n\treturn fgetc(m_file);\n}\n\n#endif\n} \/\/ namespace CONFIG4CPP_NAMESPACE\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"moveit_recorder\");\n ros::NodeHandle node_handle; \n ros::AsyncSpinner spinner(1);\n spinner.start();\n\n sleep(20); \/\/ to let RVIZ come up\n\n boost::program_options::options_description desc;\n desc.add_options()\n (\"help\", \"Show help message\")\n (\"host\", boost::program_options::value(), \"Host for the MongoDB.\")\n (\"port\", boost::program_options::value(), \"Port for the MongoDB.\");\n\n boost::program_options::variables_map vm;\n boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc);\n boost::program_options::store(po, vm);\n boost::program_options::notify(vm);\n\n if (vm.count(\"help\") || argc == 1) \/\/ show help if no parameters passed\n {\n std::cout << desc << std::endl;\n return 1;\n }\n try\n {\n \/\/connect to the DB\n std::string host = vm.count(\"host\") ? vm[\"host\"].as() : \"\";\n size_t port = vm.count(\"port\") ? vm[\"port\"].as() : 0;\n moveit_warehouse::PlanningSceneStorage pss(host, port);\n\n ROS_INFO(\"Connected to Warehouse DB at host (%s) and port (%d)\", host.c_str(), (int)port);\n\n\n ros::Publisher display_publisher = node_handle.advertise(\"\/move_group\/display_planned_path\", 1, true);\n moveit_msgs::DisplayTrajectory display_trajectory;\n\n \/\/ask the warehouse for the scene\n std::vector ps_names;\n pss.getPlanningSceneNames( ps_names );\n ros::Publisher ps_pub = node_handle.advertise(\"planning_scene\", 1);\n\n std::vector::iterator scene = ps_names.begin();\n for(; scene!=ps_names.end(); ++scene)\n {\n moveit_warehouse::PlanningSceneWithMetadata pswm;\n pss.getPlanningScene(pswm, *scene);\n\n \/\/ visualize the scene\n \/\/ apparently with metadata it extends it\n moveit_msgs::PlanningScene ps_msg = static_cast(*pswm);\n ps_pub.publish(ps_msg);\n\n \/\/get query list\n std::vector pq_names;\n pss.getPlanningQueriesNames( pq_names, *scene);\n\n std::string first_query = pq_names[0];\n\n ROS_INFO(\"%d available queries\", (int)pq_names.size());\n\n \/\/get trajectory list\n std::vector planning_results;\n pss.getPlanningResults(planning_results, *scene, first_query);\n\n ROS_INFO(\"Loaded %d trajectories for query %s\", (int)planning_results.size(), first_query.c_str());\n \n \/\/animate the first trajectory\n moveit_msgs::RobotTrajectory rt_msg = static_cast(*(planning_results[0]));\n\n \/\/get the start point\n moveit_warehouse::MotionPlanRequestWithMetadata planning_query;\n pss.getPlanningQuery(planning_query, *scene, first_query);\n moveit_msgs::MotionPlanRequest mpr = static_cast(*planning_query);\n \n \/\/publish\n display_trajectory.trajectory_start = mpr.start_state;\n display_trajectory.trajectory.push_back(rt_msg);\n display_publisher.publish(display_trajectory);\n sleep(5.0);\n }\n\n \/\/std::vector files = boost::program_options::collect_unrecognized(po.options, boost::program_options::include_positional);\n }\n catch(mongo_ros::DbConnectException &ex)\n {\n ROS_ERROR_STREAM(\"Unable to connect to warehouse. If you just created the database, it could take a while for initial setup. Please try to run the benchmark again.\"\n << std::endl << ex.what());\n }\n\n\n ROS_INFO(\"Successfully performed trajectory playback\");\n ros::shutdown();\n return 0;\n}\nneed to figure out why there are zero trajectories being recalled from the queries ...#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"moveit_recorder\");\n ros::NodeHandle node_handle; \n ros::AsyncSpinner spinner(1);\n spinner.start();\n\n sleep(20); \/\/ to let RVIZ come up\n\n boost::program_options::options_description desc;\n desc.add_options()\n (\"help\", \"Show help message\")\n (\"host\", boost::program_options::value(), \"Host for the MongoDB.\")\n (\"port\", boost::program_options::value(), \"Port for the MongoDB.\");\n\n boost::program_options::variables_map vm;\n boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc);\n boost::program_options::store(po, vm);\n boost::program_options::notify(vm);\n\n if (vm.count(\"help\") || argc == 1) \/\/ show help if no parameters passed\n {\n std::cout << desc << std::endl;\n return 1;\n }\n try\n {\n \/\/connect to the DB\n std::string host = vm.count(\"host\") ? vm[\"host\"].as() : \"\";\n size_t port = vm.count(\"port\") ? vm[\"port\"].as() : 0;\n moveit_warehouse::PlanningSceneStorage pss(host, port);\n\n ROS_INFO(\"Connected to Warehouse DB at host (%s) and port (%d)\", host.c_str(), (int)port);\n\n\n ros::Publisher display_publisher = node_handle.advertise(\"\/move_group\/display_planned_path\", 1, true);\n moveit_msgs::DisplayTrajectory display_trajectory;\n\n \/\/ask the warehouse for the scene\n std::vector ps_names;\n pss.getPlanningSceneNames( ps_names );\n ros::Publisher ps_pub = node_handle.advertise(\"planning_scene\", 1);\n\n std::vector::iterator scene = ps_names.begin();\n for(; scene!=ps_names.end(); ++scene)\n {\n moveit_warehouse::PlanningSceneWithMetadata pswm;\n pss.getPlanningScene(pswm, *scene);\n\n \/\/ visualize the scene\n \/\/ apparently with metadata it extends it\n moveit_msgs::PlanningScene ps_msg = static_cast(*pswm);\n ps_pub.publish(ps_msg);\n\n \/\/get query list\n std::vector pq_names;\n pss.getPlanningQueriesNames( pq_names, *scene);\n\n std::string first_query = pq_names.at(0);\n\n std::cout << pq_names.at(0) << std::endl;\n std::cout << pq_names.at(1) << std::endl;\n std::cout << pq_names.at(2) << std::endl;\n\n\n ROS_INFO(\"%d available queries\", (int)pq_names.size());\n\n \/\/get trajectory list\n std::vector planning_results;\n pss.getPlanningResults(planning_results, *scene, first_query);\n\n ROS_INFO(\"Loaded %d trajectories for query %s\", (int)planning_results.size(), first_query.c_str());\n\n \/\/TODO WHY IS THIS NOT LOADING TRAJECTORIES?\n \n \/\/animate the first trajectory\n moveit_msgs::RobotTrajectory rt_msg = static_cast(*(planning_results[0]));\n\n \/\/get the start point\n moveit_warehouse::MotionPlanRequestWithMetadata planning_query;\n pss.getPlanningQuery(planning_query, *scene, first_query);\n moveit_msgs::MotionPlanRequest mpr = static_cast(*planning_query);\n \n \/\/publish\n display_trajectory.trajectory_start = mpr.start_state;\n display_trajectory.trajectory.push_back(rt_msg);\n display_publisher.publish(display_trajectory);\n sleep(5.0);\n }\n\n \/\/std::vector files = boost::program_options::collect_unrecognized(po.options, boost::program_options::include_positional);\n }\n catch(mongo_ros::DbConnectException &ex)\n {\n ROS_ERROR_STREAM(\"Unable to connect to warehouse. If you just created the database, it could take a while for initial setup. Please try to run the benchmark again.\"\n << std::endl << ex.what());\n }\n\n\n ROS_INFO(\"Successfully performed trajectory playback\");\n ros::shutdown();\n return 0;\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) 2008-2017 the MRtrix3 contributors.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * MRtrix is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty\n * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * For more details, see http:\/\/www.mrtrix.org\/.\n *\/\n\n\n#include \"gui\/mrview\/mode\/lightbox.h\"\n\nnamespace MR\n{\n namespace GUI\n {\n namespace MRView\n {\n namespace Mode\n {\n\n bool LightBox::show_grid_lines(true);\n bool LightBox::show_volumes(false);\n size_t LightBox::n_rows(3);\n size_t LightBox::n_cols(5);\n size_t LightBox::volume_increment(1);\n float LightBox::slice_focus_increment(1.f);\n float LightBox::slice_focus_inc_adjust_rate(0.2f);\n std::string LightBox::prev_image_name;\n ssize_t LightBox::current_slice_index((LightBox::n_rows*LightBox::n_cols) \/ 2);\n\n LightBox::LightBox () :\n layout_is_dirty(true),\n slices_proj_focusdelta(n_rows*n_cols, proj_focusdelta(projection, 0.f))\n {\n Image* img = image();\n\n if(!img || prev_image_name != img->header().name())\n image_changed_event();\n else {\n set_volume_increment(volume_increment);\n set_slice_increment(slice_focus_increment);\n }\n }\n\n\n void LightBox::set_rows(size_t rows)\n {\n n_rows = rows;\n layout_is_dirty = true;\n updateGL();\n }\n\n void LightBox::set_cols(size_t cols)\n {\n n_cols = cols;\n layout_is_dirty = true;\n updateGL();\n }\n\n void LightBox::set_volume_increment(size_t vol_inc)\n {\n volume_increment = vol_inc;\n update_volume_indices();\n updateGL();\n }\n\n void LightBox::set_slice_increment(float inc)\n {\n slice_focus_increment = inc;\n update_slices_focusdelta();\n updateGL();\n }\n\n void LightBox::set_show_grid(bool show_grid)\n {\n show_grid_lines = show_grid;\n updateGL();\n }\n\n void LightBox::set_show_volumes(bool show_vol)\n {\n show_volumes = show_vol;\n if (show_vol) {\n update_volume_indices();\n }\n updateGL();\n }\n\n inline bool LightBox::render_volumes()\n {\n return show_volumes && image () && image()->image.ndim() == 4;\n }\n\n inline void LightBox::update_layout()\n {\n \/\/ Can't use vector resize() because Projection needs to be assignable\n slices_proj_focusdelta = vector(\n n_cols * n_rows,\n proj_focusdelta(projection, 0.f));\n\n update_volume_indices();\n\n ssize_t slice_idx = std::min(current_slice_index, (n_rows * n_cols) - 1);\n\n set_current_slice_index(slice_idx);\n update_slices_focusdelta();\n\n frame_VB.clear();\n frame_VAO.clear();\n }\n\n void LightBox::set_current_slice_index(ssize_t slice_index)\n {\n int prev_index = current_slice_index;\n current_slice_index = slice_index;\n\n if (!render_volumes() && prev_index != (int)current_slice_index) {\n const Projection& slice_proj = slices_proj_focusdelta[current_slice_index].first;\n float focus_delta = slices_proj_focusdelta[current_slice_index].second;\n\n const Eigen::Vector3f slice_focus = move_in_out_displacement(focus_delta, slice_proj);\n set_focus(focus() + slice_focus);\n update_slices_focusdelta();\n } else if (volume_indices[slice_index] == -1)\n current_slice_index = prev_index;\n }\n\n void LightBox::update_slices_focusdelta()\n {\n const int current_slice_index_int = current_slice_index;\n for(int i = 0, N = slices_proj_focusdelta.size(); i < N; ++i) {\n slices_proj_focusdelta[i].second =\n slice_focus_increment * (i - current_slice_index_int);\n }\n }\n\n void LightBox::update_volume_indices()\n {\n bool is_4d = image () && image()->image.ndim() == 4;\n volume_indices.resize (n_rows * n_cols, 0);\n\n if (!is_4d)\n return;\n\n int n_vols = image()->image.size(3);\n int current_vol = image()->image.index(3);\n\n int initial_vol = current_vol + (int)volume_increment *- (int)current_slice_index;\n if (initial_vol < 0)\n current_vol = volume_increment * current_slice_index;\n\n\n for(int i = 0, N = volume_indices.size(); i < N; ++i) {\n int vol_index = current_vol + (int)volume_increment * (i - (int)current_slice_index);\n vol_index = vol_index < 0 || vol_index >= n_vols ? -1 : vol_index;\n volume_indices[i] = vol_index;\n }\n\n for (ssize_t i = current_slice_index; i >= 0; --i) {\n current_slice_index = i;\n if (volume_indices[i] >= 0)\n break;\n }\n }\n\n void LightBox::draw_plane_primitive (int axis, Displayable::Shader& shader_program, Projection& with_projection)\n {\n ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;\n if (visible)\n image()->render3D (shader_program, with_projection, with_projection.depth_of (focus()));\n render_tools (with_projection, false, axis, slice (axis));\n ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;\n }\n\n void LightBox::paint(Projection&)\n {\n ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;\n \/\/ Setup OpenGL environment:\n gl::Disable (gl::BLEND);\n gl::Disable (gl::DEPTH_TEST);\n gl::DepthMask (gl::FALSE_);\n gl::ColorMask (gl::TRUE_, gl::TRUE_, gl::TRUE_, gl::TRUE_);\n\n GLint x = projection.x_position(), y = projection.y_position();\n GLint w = projection.width(), h = projection.height();\n GLfloat dw = w \/ (float)n_cols, dh = h \/ (float)n_rows;\n\n const Eigen::Vector3f orig_focus = window().focus();\n\n if (layout_is_dirty) {\n update_layout();\n layout_is_dirty = false;\n }\n\n bool rend_vols = render_volumes();\n\n ssize_t slice_idx = 0;\n for(size_t row = 0; row < n_rows; ++row) {\n for(size_t col = 0; col < n_cols; ++col, ++slice_idx) {\n Projection& slice_proj = slices_proj_focusdelta[slice_idx].first;\n\n bool render_plane = true;\n\n \/\/ Place the first slice in the top-left corner\n slice_proj.set_viewport(window(), x + dw * col, y + h - (dh * (row+1)), dw, dh);\n\n \/\/ We need to setup the modelview\/proj matrices before we set the new focus\n \/\/ because move_in_out_displacement is reliant on MVP\n setup_projection (plane(), slice_proj);\n\n if (rend_vols) {\n if (volume_indices[slice_idx] != -1)\n image()->image.index(3) = volume_indices[slice_idx];\n else\n render_plane = false;\n }\n\n else {\n float focus_delta = slices_proj_focusdelta[slice_idx].second;\n Eigen::Vector3f slice_focus = move_in_out_displacement(focus_delta, slice_proj);\n set_focus(orig_focus + slice_focus);\n }\n\n if (render_plane)\n draw_plane_primitive(plane(), slice_shader, slice_proj);\n\n if(slice_idx == current_slice_index) {\n \/\/ Drawing plane may alter the depth test state\n \/\/ so need to ensure that crosshairs\/labels will be visible\n gl::Disable (gl::DEPTH_TEST);\n draw_crosshairs(slice_proj);\n draw_orientation_labels(slice_proj);\n }\n }\n }\n\n \/\/ Restore view state\n if(rend_vols && volume_indices[current_slice_index] >= 0)\n image()->image.index(3) = volume_indices[current_slice_index];\n set_focus(orig_focus);\n projection.set_viewport(window(), x, y, w, h);\n\n \/\/ Users may want to screen capture without grid lines\n if(show_grid_lines) {\n gl::Disable(gl::DEPTH_TEST);\n draw_grid();\n }\n ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;\n }\n\n void LightBox::draw_grid()\n {\n ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;\n if(n_cols < 1 && n_rows < 1)\n return;\n\n size_t num_points = ((n_rows - 1) + (n_cols - 1)) * 4;\n\n GL::mat4 MV = GL::identity();\n GL::mat4 P = GL::ortho (0, width(), 0, height(), -1.0, 1.0);\n projection.set (MV, P);\n\n if (!frame_VB || !frame_VAO) {\n frame_VB.gen();\n frame_VAO.gen();\n\n frame_VB.bind (gl::ARRAY_BUFFER);\n frame_VAO.bind();\n\n gl::EnableVertexAttribArray (0);\n gl::VertexAttribPointer (0, 2, gl::FLOAT, gl::FALSE_, 0, (void*)0);\n\n GLfloat data[num_points];\n\n \/\/ Grid line stride\n float x_inc = 2.f \/ n_cols;\n float y_inc = 2.f \/ n_rows;\n\n size_t pt_idx = 0;\n \/\/ Row grid lines\n for(size_t row = 1; row < n_rows; ++row, pt_idx += 4) {\n float y_pos = (y_inc * row) - 1.f;\n data[pt_idx] = -1.f;\n data[pt_idx+1] = y_pos;\n data[pt_idx+2] = 1.f;\n data[pt_idx+3] = y_pos;\n }\n\n \/\/ Column grid lines\n for(size_t col = 1; col < n_cols; ++col, pt_idx += 4) {\n float x_pos = (x_inc * col) - 1.f;\n data[pt_idx] = x_pos;\n data[pt_idx+1] = -1.f;\n data[pt_idx+2] = x_pos;\n data[pt_idx+3] = 1.f;\n }\n\n gl::BufferData (gl::ARRAY_BUFFER, sizeof(data), data, gl::STATIC_DRAW);\n }\n else\n frame_VAO.bind();\n\n if (!frame_program) {\n GL::Shader::Vertex vertex_shader (\n \"layout(location=0) in vec2 pos;\\n\"\n \"void main () {\\n\"\n \" gl_Position = vec4 (pos, 0.0, 1.0);\\n\"\n \"}\\n\");\n GL::Shader::Fragment fragment_shader (\n \"out vec3 color;\\n\"\n \"void main () {\\n\"\n \" color = vec3 (0.1);\\n\"\n \"}\\n\");\n frame_program.attach (vertex_shader);\n frame_program.attach (fragment_shader);\n frame_program.link();\n }\n\n frame_program.start();\n gl::DrawArrays (gl::LINES, 0, num_points \/ 2);\n frame_program.stop();\n ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;\n }\n\n void LightBox::mouse_press_event()\n {\n GLint x = projection.x_position(), y = projection.y_position();\n GLint w = projection.width(), h = projection.height();\n GLint dw = w \/ n_cols, dh = h \/ n_rows;\n\n const auto& mouse_pos = window().mouse_position();\n\n size_t col = (mouse_pos.x() - x) \/ dw;\n size_t row = n_rows - (mouse_pos.y() - y) \/ dh - 1;\n\n if(col < n_cols && row < n_rows) {\n set_current_slice_index(slice_index(row, col));\n }\n }\n\n \/\/ Called when we get a mouse move event\n void LightBox::set_focus_event()\n {\n Base::set_focus_event();\n mouse_press_event();\n }\n\n void LightBox::image_changed_event()\n {\n Base::image_changed_event();\n\n update_volume_indices();\n\n if(image()) {\n const auto& header = image()->header();\n if (prev_image_name.empty()) {\n float slice_inc = std::pow (header.spacing(0)*header.spacing(1)*header.spacing(2), 1.f\/3.f);\n slice_focus_inc_adjust_rate = slice_inc \/ 5.f;\n\n set_slice_increment(slice_inc);\n emit slice_increment_reset();\n }\n\n prev_image_name = image()->header().name();\n }\n else\n prev_image_name.clear();\n }\n\n }\n }\n }\n}\nmrview: lightbox: Correctly update current slice focus\/* Copyright (c) 2008-2017 the MRtrix3 contributors.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * MRtrix is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty\n * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * For more details, see http:\/\/www.mrtrix.org\/.\n *\/\n\n\n#include \"gui\/mrview\/mode\/lightbox.h\"\n\nnamespace MR\n{\n namespace GUI\n {\n namespace MRView\n {\n namespace Mode\n {\n\n bool LightBox::show_grid_lines(true);\n bool LightBox::show_volumes(false);\n size_t LightBox::n_rows(3);\n size_t LightBox::n_cols(5);\n size_t LightBox::volume_increment(1);\n float LightBox::slice_focus_increment(1.f);\n float LightBox::slice_focus_inc_adjust_rate(0.2f);\n std::string LightBox::prev_image_name;\n ssize_t LightBox::current_slice_index((LightBox::n_rows*LightBox::n_cols) \/ 2);\n\n LightBox::LightBox () :\n layout_is_dirty(true),\n slices_proj_focusdelta(n_rows*n_cols, proj_focusdelta(projection, 0.f))\n {\n Image* img = image();\n\n if(!img || prev_image_name != img->header().name())\n image_changed_event();\n else {\n set_volume_increment(volume_increment);\n set_slice_increment(slice_focus_increment);\n }\n }\n\n\n void LightBox::set_rows(size_t rows)\n {\n n_rows = rows;\n layout_is_dirty = true;\n updateGL();\n }\n\n void LightBox::set_cols(size_t cols)\n {\n n_cols = cols;\n layout_is_dirty = true;\n updateGL();\n }\n\n void LightBox::set_volume_increment(size_t vol_inc)\n {\n volume_increment = vol_inc;\n update_volume_indices();\n updateGL();\n }\n\n void LightBox::set_slice_increment(float inc)\n {\n slice_focus_increment = inc;\n update_slices_focusdelta();\n updateGL();\n }\n\n void LightBox::set_show_grid(bool show_grid)\n {\n show_grid_lines = show_grid;\n updateGL();\n }\n\n void LightBox::set_show_volumes(bool show_vol)\n {\n show_volumes = show_vol;\n if (show_vol)\n update_volume_indices();\n else {\n \/\/ Force focus update\n ssize_t prev_index = current_slice_index;\n current_slice_index = -1;\n set_current_slice_index(prev_index);\n }\n updateGL();\n }\n\n inline bool LightBox::render_volumes()\n {\n return show_volumes && image () && image()->image.ndim() == 4;\n }\n\n inline void LightBox::update_layout()\n {\n \/\/ Can't use vector resize() because Projection needs to be assignable\n slices_proj_focusdelta = vector(\n n_cols * n_rows,\n proj_focusdelta(projection, 0.f));\n\n update_volume_indices();\n\n ssize_t slice_idx = std::min(current_slice_index, (n_rows * n_cols) - 1);\n\n set_current_slice_index(slice_idx);\n update_slices_focusdelta();\n\n frame_VB.clear();\n frame_VAO.clear();\n }\n\n void LightBox::set_current_slice_index(ssize_t slice_index)\n {\n int prev_index = current_slice_index;\n current_slice_index = slice_index;\n\n if (!render_volumes() && prev_index != (int)current_slice_index) {\n const Projection& slice_proj = slices_proj_focusdelta[current_slice_index].first;\n float focus_delta = slices_proj_focusdelta[current_slice_index].second;\n\n const Eigen::Vector3f slice_focus = move_in_out_displacement(focus_delta, slice_proj);\n set_focus(focus() + slice_focus);\n update_slices_focusdelta();\n } else if (volume_indices[slice_index] == -1)\n current_slice_index = prev_index;\n }\n\n void LightBox::update_slices_focusdelta()\n {\n const int current_slice_index_int = current_slice_index;\n for(int i = 0, N = slices_proj_focusdelta.size(); i < N; ++i) {\n slices_proj_focusdelta[i].second =\n slice_focus_increment * (i - current_slice_index_int);\n }\n }\n\n void LightBox::update_volume_indices()\n {\n bool is_4d = image () && image()->image.ndim() == 4;\n volume_indices.resize (n_rows * n_cols, 0);\n\n if (!is_4d)\n return;\n\n int n_vols = image()->image.size(3);\n int current_vol = image()->image.index(3);\n\n int initial_vol = current_vol + (int)volume_increment *- (int)current_slice_index;\n if (initial_vol < 0)\n current_vol = volume_increment * current_slice_index;\n\n\n for(int i = 0, N = volume_indices.size(); i < N; ++i) {\n int vol_index = current_vol + (int)volume_increment * (i - (int)current_slice_index);\n vol_index = vol_index < 0 || vol_index >= n_vols ? -1 : vol_index;\n volume_indices[i] = vol_index;\n }\n\n for (ssize_t i = current_slice_index; i >= 0; --i) {\n current_slice_index = i;\n if (volume_indices[i] >= 0)\n break;\n }\n }\n\n void LightBox::draw_plane_primitive (int axis, Displayable::Shader& shader_program, Projection& with_projection)\n {\n ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;\n if (visible)\n image()->render3D (shader_program, with_projection, with_projection.depth_of (focus()));\n render_tools (with_projection, false, axis, slice (axis));\n ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;\n }\n\n void LightBox::paint(Projection&)\n {\n ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;\n \/\/ Setup OpenGL environment:\n gl::Disable (gl::BLEND);\n gl::Disable (gl::DEPTH_TEST);\n gl::DepthMask (gl::FALSE_);\n gl::ColorMask (gl::TRUE_, gl::TRUE_, gl::TRUE_, gl::TRUE_);\n\n GLint x = projection.x_position(), y = projection.y_position();\n GLint w = projection.width(), h = projection.height();\n GLfloat dw = w \/ (float)n_cols, dh = h \/ (float)n_rows;\n\n const Eigen::Vector3f orig_focus = window().focus();\n\n if (layout_is_dirty) {\n update_layout();\n layout_is_dirty = false;\n }\n\n bool rend_vols = render_volumes();\n\n ssize_t slice_idx = 0;\n for(size_t row = 0; row < n_rows; ++row) {\n for(size_t col = 0; col < n_cols; ++col, ++slice_idx) {\n Projection& slice_proj = slices_proj_focusdelta[slice_idx].first;\n\n bool render_plane = true;\n\n \/\/ Place the first slice in the top-left corner\n slice_proj.set_viewport(window(), x + dw * col, y + h - (dh * (row+1)), dw, dh);\n\n \/\/ We need to setup the modelview\/proj matrices before we set the new focus\n \/\/ because move_in_out_displacement is reliant on MVP\n setup_projection (plane(), slice_proj);\n\n if (rend_vols) {\n if (volume_indices[slice_idx] != -1)\n image()->image.index(3) = volume_indices[slice_idx];\n else\n render_plane = false;\n }\n\n else {\n float focus_delta = slices_proj_focusdelta[slice_idx].second;\n Eigen::Vector3f slice_focus = move_in_out_displacement(focus_delta, slice_proj);\n set_focus(orig_focus + slice_focus);\n }\n\n if (render_plane)\n draw_plane_primitive(plane(), slice_shader, slice_proj);\n\n if(slice_idx == current_slice_index) {\n \/\/ Drawing plane may alter the depth test state\n \/\/ so need to ensure that crosshairs\/labels will be visible\n gl::Disable (gl::DEPTH_TEST);\n draw_crosshairs(slice_proj);\n draw_orientation_labels(slice_proj);\n }\n }\n }\n\n \/\/ Restore view state\n if(rend_vols && volume_indices[current_slice_index] >= 0)\n image()->image.index(3) = volume_indices[current_slice_index];\n set_focus(orig_focus);\n projection.set_viewport(window(), x, y, w, h);\n\n \/\/ Users may want to screen capture without grid lines\n if(show_grid_lines) {\n gl::Disable(gl::DEPTH_TEST);\n draw_grid();\n }\n ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;\n }\n\n void LightBox::draw_grid()\n {\n ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;\n if(n_cols < 1 && n_rows < 1)\n return;\n\n size_t num_points = ((n_rows - 1) + (n_cols - 1)) * 4;\n\n GL::mat4 MV = GL::identity();\n GL::mat4 P = GL::ortho (0, width(), 0, height(), -1.0, 1.0);\n projection.set (MV, P);\n\n if (!frame_VB || !frame_VAO) {\n frame_VB.gen();\n frame_VAO.gen();\n\n frame_VB.bind (gl::ARRAY_BUFFER);\n frame_VAO.bind();\n\n gl::EnableVertexAttribArray (0);\n gl::VertexAttribPointer (0, 2, gl::FLOAT, gl::FALSE_, 0, (void*)0);\n\n GLfloat data[num_points];\n\n \/\/ Grid line stride\n float x_inc = 2.f \/ n_cols;\n float y_inc = 2.f \/ n_rows;\n\n size_t pt_idx = 0;\n \/\/ Row grid lines\n for(size_t row = 1; row < n_rows; ++row, pt_idx += 4) {\n float y_pos = (y_inc * row) - 1.f;\n data[pt_idx] = -1.f;\n data[pt_idx+1] = y_pos;\n data[pt_idx+2] = 1.f;\n data[pt_idx+3] = y_pos;\n }\n\n \/\/ Column grid lines\n for(size_t col = 1; col < n_cols; ++col, pt_idx += 4) {\n float x_pos = (x_inc * col) - 1.f;\n data[pt_idx] = x_pos;\n data[pt_idx+1] = -1.f;\n data[pt_idx+2] = x_pos;\n data[pt_idx+3] = 1.f;\n }\n\n gl::BufferData (gl::ARRAY_BUFFER, sizeof(data), data, gl::STATIC_DRAW);\n }\n else\n frame_VAO.bind();\n\n if (!frame_program) {\n GL::Shader::Vertex vertex_shader (\n \"layout(location=0) in vec2 pos;\\n\"\n \"void main () {\\n\"\n \" gl_Position = vec4 (pos, 0.0, 1.0);\\n\"\n \"}\\n\");\n GL::Shader::Fragment fragment_shader (\n \"out vec3 color;\\n\"\n \"void main () {\\n\"\n \" color = vec3 (0.1);\\n\"\n \"}\\n\");\n frame_program.attach (vertex_shader);\n frame_program.attach (fragment_shader);\n frame_program.link();\n }\n\n frame_program.start();\n gl::DrawArrays (gl::LINES, 0, num_points \/ 2);\n frame_program.stop();\n ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;\n }\n\n void LightBox::mouse_press_event()\n {\n GLint x = projection.x_position(), y = projection.y_position();\n GLint w = projection.width(), h = projection.height();\n GLint dw = w \/ n_cols, dh = h \/ n_rows;\n\n const auto& mouse_pos = window().mouse_position();\n\n size_t col = (mouse_pos.x() - x) \/ dw;\n size_t row = n_rows - (mouse_pos.y() - y) \/ dh - 1;\n\n if(col < n_cols && row < n_rows) {\n set_current_slice_index(slice_index(row, col));\n }\n }\n\n \/\/ Called when we get a mouse move event\n void LightBox::set_focus_event()\n {\n Base::set_focus_event();\n mouse_press_event();\n }\n\n void LightBox::image_changed_event()\n {\n Base::image_changed_event();\n\n update_volume_indices();\n\n if(image()) {\n const auto& header = image()->header();\n if (prev_image_name.empty()) {\n float slice_inc = std::pow (header.spacing(0)*header.spacing(1)*header.spacing(2), 1.f\/3.f);\n slice_focus_inc_adjust_rate = slice_inc \/ 5.f;\n\n set_slice_increment(slice_inc);\n emit slice_increment_reset();\n }\n\n prev_image_name = image()->header().name();\n }\n else\n prev_image_name.clear();\n }\n\n }\n }\n }\n}\n<|endoftext|>"} {"text":"#include \"OutputVars.h\"\n#include \"UnitConst.h\" \/\/For unit conversion factors\n#include \"System.h\"\n#include \"MoveSettings.h\"\n#include \"MoleculeLookup.h\"\n\n#if ENSEMBLE == GEMC\n#include \"MoveConst.h\" \/\/For box constants, if we're calculating Hv\n#endif\n\nOutputVars::OutputVars(System & sys, StaticVals const& statV) :\n calc(sys.calcEnergy) { InitRef(sys, statV); }\n\nvoid OutputVars::InitRef(System & sys, StaticVals const& statV)\n{\n T_in_K = statV.forcefield.T_in_K;\n volumeRef = sys.boxDimRef.volume;\n axisRef = &sys.boxDimRef.axis;\n volInvRef = sys.boxDimRef.volInv;\n energyTotRef = & sys.potential.totalEnergy;\n virialTotRef = & sys.potential.totalVirial;\n energyRef = sys.potential.boxEnergy;\n virialRef = sys.potential.boxVirial; \/\/\n kindsRef = statV.mol.kinds;\n molLookupRef = & sys.molLookupRef;\n moveSetRef = & sys.moveSettings;\n movePercRef = statV.movePerc;\n pCalcFreq = statV.simEventFreq.pCalcFreq;\n pressureCalc = statV.simEventFreq.pressureCalc;\n\n virial = new Virial[BOXES_WITH_U_NB];\n}\n\nuint OutputVars::GetTries(uint sub)\n{\n return (sub < mv::SCALEABLE ?\n moveSetRef->tries[sub] + moveSetRef->tempTries[sub] :\n moveSetRef->tries[sub]);\n}\n\nuint OutputVars::GetAccepted(uint sub)\n{\n return (sub < mv::SCALEABLE ?\n moveSetRef->accepted[sub] + moveSetRef->tempAccepted[sub] :\n moveSetRef->accepted[sub]);\n}\n\ndouble OutputVars::GetScale(uint sub)\n{\n return moveSetRef->scale[sub];\n}\n\ndouble OutputVars::GetAcceptPercent(uint sub)\n{\n if(GetTries(sub)==0)\n return 0.0;\n return (double)(GetAccepted(sub))\/(double)(GetTries(sub))*100.0;\n}\n\nvoid OutputVars::Init(pdb_setup::Atoms const& atoms)\n{\n \/\/Init vals.\n numKinds = molLookupRef->GetNumKind();\n resKindNames = atoms.resKindNames;\n\n \/\/Allocate arrays,\n uint kTot = BOX_TOTAL * numKinds;\n numByBox = new uint [BOX_TOTAL];\n numByKindBox = new uint [kTot];\n densityByKindBox = new double [kTot];\n if (numKinds > 1)\n molFractionByKindBox = new double [kTot];\n}\n\nOutputVars::~OutputVars(void)\n{\n if ( numByBox != NULL )\n delete[] numByBox;\n if ( numByKindBox != NULL )\n delete[] numByKindBox;\n if ( numKinds > 1 && molFractionByKindBox != NULL )\n delete[] molFractionByKindBox;\n if ( densityByKindBox != NULL )\n delete[] densityByKindBox;\n}\n\nvoid OutputVars::CalcAndConvert(ulong step)\n{\n double rawPressure[BOXES_WITH_U_NB];\n\n#if ENSEMBLE == GEMC\n \/\/Which box is the liquid in gibbs ensemble\n uint liqBox = mv::BOX0, vapBox = mv::BOX1;\n#endif\n\n molLookupRef->TotalAndDensity(numByBox, numByKindBox, molFractionByKindBox,\n densityByKindBox, volInvRef);\n\n#if ENSEMBLE == GEMC\n \/\/Determine which box is liquid for purposes of heat of vap.\n if (densityByKindBox[numKinds] > densityByKindBox[0])\n {\n vapBox = mv::BOX0;\n liqBox = mv::BOX1;\n }\n#endif\n\n for (uint b = 0; b < BOXES_WITH_U_NB; b++)\n {\n \/\/Account for dimensionality of virial (raw \"virial\" is actually a\n \/\/multiple of the true virial, based on the dimensions stress is exerted\n \/\/in)\n \n if (((step + 1) % pCalcFreq == 0) && pressureCalc)\n {\n virialRef[b] = calc.ForceCalc(b);\n *virialTotRef += virialRef[b];\n \/\/calculate surface tension in mN\/M\n surfaceTens[b] = (virialRef[b].totalTens[2][2] - 0.5 *\n\t\t\t(virialRef[b].totalTens[0][0] +\n\t\t\t virialRef[b].totalTens[1][1]));\n surfaceTens[b] *= unit::K_TO_MN_PER_M \/\n\t(2.0 * axisRef->Get(b).x * axisRef->Get(b).y);\n\n \/\/save the pressure tensor for print\n for (int i = 0; i < 3; i++)\n {\n\t for (int j = 0; j < 3; j++)\n\t {\n\t \/\/convert K to bar\n\t pressureTens[b][i][j] = virialRef[b].totalTens[i][j] *\n\t unit::K_MOLECULE_PER_A3_TO_BAR \/ volumeRef[b];\n\t }\n }\n } \n \n virial[b] = virialRef[b];\n virial[b] \/= unit::DIMENSIONALITY;\n virial[b] \/= volumeRef[b];\n virial[b].Total();\n \n \n rawPressure[b] = 0.0;\n densityTot[b] = 0.0;\n for (uint k = 0; k < numKinds; k++)\n {\n double * density = &densityByKindBox[k+numKinds*b];\n\n \/\/ Instead of converting to mass first\n \/\/ (an alternate route to calculate the ideal gas pressure)\n \/\/ the form of the Boltzmann constant that kcal\/mol\/K is used\n \/\/ such that a single conversion factor can be applied to both\n \/\/ the ideal and virial components of the pressure.\n rawPressure[b] += *density;\n }\n \/\/ Finish ideal component\n rawPressure[b] *= T_in_K;\n \/\/ Add the virial component\n rawPressure[b] += virial[b].total;\n\n \/\/ Convert to desired units\n \/\/ ( starting: K * molecule \/ Angstrom^3 )\n pressure[b] = rawPressure[b];\n pressure[b] *= unit::K_MOLECULE_PER_A3_TO_BAR;\n }\n for (uint b = 0; b < BOX_TOTAL; b++)\n {\n densityTot[b] = 0.0;\n for (uint k = 0; k < numKinds; k++)\n {\n double * density = &densityByKindBox[k+numKinds*b];\n\n \/\/ Convert density to g\/ml (which is equivalent to g\/cm3)\n \/\/ To get kg\/m3, multiply output densities by 1000.\n *density *= unit::MOLECULES_PER_A3_TO_MOL_PER_CM3 *\n kindsRef[k].molMass;\n densityTot[b] += densityByKindBox[k+numKinds*b];\n }\n densityTot[b] *= 1000;\n }\n#if ENSEMBLE == GEMC\n \/\/ delta Hv = (Uv-Ul) + P(Vv-Vl)\n heatOfVap = energyRef[vapBox].total\/numByBox[vapBox] -\n energyRef[liqBox].total\/numByBox[liqBox] +\n rawPressure[vapBox]*(volumeRef[vapBox]\/numByBox[vapBox] -\n volumeRef[liqBox]\/numByBox[liqBox]);\n heatOfVap *= unit::K_TO_KJ_PER_MOL;\n#endif\n\n}\ncalc pressure at step 0#include \"OutputVars.h\"\n#include \"UnitConst.h\" \/\/For unit conversion factors\n#include \"System.h\"\n#include \"MoveSettings.h\"\n#include \"MoleculeLookup.h\"\n\n#if ENSEMBLE == GEMC\n#include \"MoveConst.h\" \/\/For box constants, if we're calculating Hv\n#endif\n\nOutputVars::OutputVars(System & sys, StaticVals const& statV) :\n calc(sys.calcEnergy) { InitRef(sys, statV); }\n\nvoid OutputVars::InitRef(System & sys, StaticVals const& statV)\n{\n T_in_K = statV.forcefield.T_in_K;\n volumeRef = sys.boxDimRef.volume;\n axisRef = &sys.boxDimRef.axis;\n volInvRef = sys.boxDimRef.volInv;\n energyTotRef = & sys.potential.totalEnergy;\n virialTotRef = & sys.potential.totalVirial;\n energyRef = sys.potential.boxEnergy;\n virialRef = sys.potential.boxVirial; \/\/\n kindsRef = statV.mol.kinds;\n molLookupRef = & sys.molLookupRef;\n moveSetRef = & sys.moveSettings;\n movePercRef = statV.movePerc;\n pCalcFreq = statV.simEventFreq.pCalcFreq;\n pressureCalc = statV.simEventFreq.pressureCalc;\n\n virial = new Virial[BOXES_WITH_U_NB];\n}\n\nuint OutputVars::GetTries(uint sub)\n{\n return (sub < mv::SCALEABLE ?\n moveSetRef->tries[sub] + moveSetRef->tempTries[sub] :\n moveSetRef->tries[sub]);\n}\n\nuint OutputVars::GetAccepted(uint sub)\n{\n return (sub < mv::SCALEABLE ?\n moveSetRef->accepted[sub] + moveSetRef->tempAccepted[sub] :\n moveSetRef->accepted[sub]);\n}\n\ndouble OutputVars::GetScale(uint sub)\n{\n return moveSetRef->scale[sub];\n}\n\ndouble OutputVars::GetAcceptPercent(uint sub)\n{\n if(GetTries(sub)==0)\n return 0.0;\n return (double)(GetAccepted(sub))\/(double)(GetTries(sub))*100.0;\n}\n\nvoid OutputVars::Init(pdb_setup::Atoms const& atoms)\n{\n \/\/Init vals.\n numKinds = molLookupRef->GetNumKind();\n resKindNames = atoms.resKindNames;\n\n \/\/Allocate arrays,\n uint kTot = BOX_TOTAL * numKinds;\n numByBox = new uint [BOX_TOTAL];\n numByKindBox = new uint [kTot];\n densityByKindBox = new double [kTot];\n if (numKinds > 1)\n molFractionByKindBox = new double [kTot];\n}\n\nOutputVars::~OutputVars(void)\n{\n if ( numByBox != NULL )\n delete[] numByBox;\n if ( numByKindBox != NULL )\n delete[] numByKindBox;\n if ( numKinds > 1 && molFractionByKindBox != NULL )\n delete[] molFractionByKindBox;\n if ( densityByKindBox != NULL )\n delete[] densityByKindBox;\n}\n\nvoid OutputVars::CalcAndConvert(ulong step)\n{\n double rawPressure[BOXES_WITH_U_NB];\n\n#if ENSEMBLE == GEMC\n \/\/Which box is the liquid in gibbs ensemble\n uint liqBox = mv::BOX0, vapBox = mv::BOX1;\n#endif\n\n molLookupRef->TotalAndDensity(numByBox, numByKindBox, molFractionByKindBox,\n densityByKindBox, volInvRef);\n\n#if ENSEMBLE == GEMC\n \/\/Determine which box is liquid for purposes of heat of vap.\n if (densityByKindBox[numKinds] > densityByKindBox[0])\n {\n vapBox = mv::BOX0;\n liqBox = mv::BOX1;\n }\n#endif\n\n for (uint b = 0; b < BOXES_WITH_U_NB; b++)\n {\n \/\/Account for dimensionality of virial (raw \"virial\" is actually a\n \/\/multiple of the true virial, based on the dimensions stress is exerted\n \/\/in)\n \n if (((step + 1) % pCalcFreq == 0) && pressureCalc)\n {\n virialRef[b] = calc.ForceCalc(b);\n *virialTotRef += virialRef[b];\n } \n\n \/\/calculate surface tension in mN\/M\n surfaceTens[b] = (virialRef[b].totalTens[2][2] - 0.5 *\n\t\t (virialRef[b].totalTens[0][0] +\n\t\t virialRef[b].totalTens[1][1]));\n surfaceTens[b] *= unit::K_TO_MN_PER_M \/\n (2.0 * axisRef->Get(b).x * axisRef->Get(b).y);\n\n \/\/save the pressure tensor for print\n for (int i = 0; i < 3; i++)\n {\n for (int j = 0; j < 3; j++)\n {\n\t \/\/convert K to bar\n\t pressureTens[b][i][j] = virialRef[b].totalTens[i][j] *\n\t unit::K_MOLECULE_PER_A3_TO_BAR \/ volumeRef[b];\n }\n }\n \n virial[b] = virialRef[b];\n virial[b] \/= unit::DIMENSIONALITY;\n virial[b] \/= volumeRef[b];\n virial[b].Total();\n \n \n rawPressure[b] = 0.0;\n densityTot[b] = 0.0;\n for (uint k = 0; k < numKinds; k++)\n {\n double * density = &densityByKindBox[k+numKinds*b];\n\n \/\/ Instead of converting to mass first\n \/\/ (an alternate route to calculate the ideal gas pressure)\n \/\/ the form of the Boltzmann constant that kcal\/mol\/K is used\n \/\/ such that a single conversion factor can be applied to both\n \/\/ the ideal and virial components of the pressure.\n rawPressure[b] += *density;\n }\n \/\/ Finish ideal component\n rawPressure[b] *= T_in_K;\n \/\/ Add the virial component\n rawPressure[b] += virial[b].total;\n\n \/\/ Convert to desired units\n \/\/ ( starting: K * molecule \/ Angstrom^3 )\n pressure[b] = rawPressure[b];\n pressure[b] *= unit::K_MOLECULE_PER_A3_TO_BAR;\n }\n for (uint b = 0; b < BOX_TOTAL; b++)\n {\n densityTot[b] = 0.0;\n for (uint k = 0; k < numKinds; k++)\n {\n double * density = &densityByKindBox[k+numKinds*b];\n\n \/\/ Convert density to g\/ml (which is equivalent to g\/cm3)\n \/\/ To get kg\/m3, multiply output densities by 1000.\n *density *= unit::MOLECULES_PER_A3_TO_MOL_PER_CM3 *\n kindsRef[k].molMass;\n densityTot[b] += densityByKindBox[k+numKinds*b];\n }\n densityTot[b] *= 1000;\n }\n#if ENSEMBLE == GEMC\n \/\/ delta Hv = (Uv-Ul) + P(Vv-Vl)\n heatOfVap = energyRef[vapBox].total\/numByBox[vapBox] -\n energyRef[liqBox].total\/numByBox[liqBox] +\n rawPressure[vapBox]*(volumeRef[vapBox]\/numByBox[vapBox] -\n volumeRef[liqBox]\/numByBox[liqBox]);\n heatOfVap *= unit::K_TO_KJ_PER_MOL;\n#endif\n\n}\n<|endoftext|>"} {"text":"#include \"cmm_socket.private.h\"\n#include \"csocket.h\"\n#include \"debug.h\"\n#include \"timeops.h\"\n#include \"cmm_socket_control.h\"\n#include \n#include \n#include \n#include \n#include \"csocket_sender.h\"\n#include \"csocket_receiver.h\"\n#include \"csocket_mapping.h\"\n#include \nusing std::max;\n\nCSocketPtr\nCSocket::create(boost::weak_ptr sk_,\n struct net_interface local_iface_, \n struct net_interface remote_iface_,\n int accepted_sock)\n{\n CSocketPtr new_csock(new CSocket(sk_, local_iface_, \n remote_iface_, accepted_sock));\n new_csock->self_ptr = new_csock;\n return new_csock;\n}\n\nCSocket::CSocket(boost::weak_ptr sk_,\n struct net_interface local_iface_, \n struct net_interface remote_iface_,\n int accepted_sock)\n : sk(sk_),\n local_iface(local_iface_), remote_iface(remote_iface_),\n stats(local_iface, remote_iface),\n csock_sendr(NULL), csock_recvr(NULL), irob_indexes(local_iface_.labels)\n{\n assert(sk);\n if (accepted_sock == -1) {\n osfd = socket(sk->sock_family, sk->sock_type, sk->sock_protocol);\n if (osfd < 0) {\n \/* out of file descriptors or memory at this point *\/\n throw std::runtime_error(\"Out of FDs or memory!\");\n }\n \n sk->set_all_sockopts(osfd);\n } else {\n osfd = accepted_sock;\n }\n \n int on = 1;\n int rc;\n \/* Make sure that this socket is TCP_NODELAY for good performance *\/\n struct protoent *pe = getprotobyname(\"TCP\");\n if (pe) {\n\trc = setsockopt (osfd, pe->p_proto, TCP_NODELAY, \n\t\t\t (char *) &on, sizeof(on));\n } else {\n\trc = setsockopt (osfd, 6, TCP_NODELAY, \n\t\t\t (char *) &on, sizeof(on));\n }\n if (rc < 0) {\n\tdbgprintf(\"Cannot make socket TCP_NODELAY\");\n }\n}\n\nCSocket::~CSocket()\n{\n dbgprintf(\"CSocket %d is being destroyed\\n\", osfd);\n if (osfd > 0) {\n\t\/* if it's a real open socket *\/\n assert(csock_sendr == NULL && csock_recvr == NULL);\n\tclose(osfd);\n } \n}\n\nint\nCSocket::phys_connect()\n{\n struct sockaddr_in local_addr, remote_addr;\n \n \/\/ XXX-TODO: don't assume it's an inet socket\n\n local_addr.sin_family = AF_INET;\n local_addr.sin_addr = local_iface.ip_addr;\n local_addr.sin_port = 0;\n \n remote_addr.sin_family = AF_INET;\n remote_addr.sin_addr = remote_iface.ip_addr;\n remote_addr.sin_port = sk->remote_listener_port;\n \n int rc = bind(osfd, (struct sockaddr *)&local_addr, \n sizeof(local_addr));\n if (rc < 0) {\n\tperror(\"bind\");\n\tdbgprintf(\"Failed to bind osfd %d to %s:%d\\n\",\n\t\t osfd, inet_ntoa(local_addr.sin_addr), \n\t\t ntohs(local_addr.sin_port));\n\treturn rc;\n }\n dbgprintf(\"Successfully bound osfd %d to %s:%d\\n\",\n\t osfd, inet_ntoa(local_addr.sin_addr), \n\t ntohs(local_addr.sin_port));\n \n rc = connect(osfd, (struct sockaddr *)&remote_addr, \n\t\t sizeof(remote_addr));\n if (rc < 0) {\n\tperror(\"connect\");\n\tdbgprintf(\"Failed to connect osfd %d to %s:%d\\n\",\n\t\t osfd, inet_ntoa(remote_addr.sin_addr), \n\t\t ntohs(remote_addr.sin_port));\n\treturn rc;\n }\n struct CMMSocketControlHdr hdr;\n memset(&hdr, 0, sizeof(hdr));\n hdr.type = htons(CMM_CONTROL_MSG_NEW_INTERFACE);\n hdr.send_labels = 0;\n hdr.op.new_interface.ip_addr = local_iface.ip_addr;\n hdr.op.new_interface.labels = htonl(local_iface.labels);\n hdr.op.new_interface.bandwidth = htonl(local_iface.bandwidth);\n hdr.op.new_interface.RTT = htonl(local_iface.RTT);\n rc = send(osfd, &hdr, sizeof(hdr), 0);\n if (rc != sizeof(hdr)) {\n perror(\"send\");\n dbgprintf(\"Failed to send interface info\\n\");\n return rc;\n }\n\n startup_workers();\n return 0;\n}\n\nvoid\nCSocket::startup_workers()\n{\n if (!csock_sendr && !csock_recvr) {\n\tcsock_sendr = new CSocketSender(CSocketPtr(self_ptr));\n\tcsock_recvr = new CSocketReceiver(CSocketPtr(self_ptr));\n\tint rc = csock_sendr->start();\n if (rc != 0) {\n throw std::runtime_error(\"Failed to create csocket_sender thread!\");\n }\n\trc = csock_recvr->start();\n if (rc != 0) {\n throw std::runtime_error(\"Failed to create csocket_receiver thread!\");\n }\n }\n}\n\n\/* must not be holding sk->scheduling_state_lock. *\/\nbool \nCSocket::matches(u_long send_labels)\n{\n return sk->csock_map->csock_matches(this, send_labels);\n}\n\nu_long\nCSocket::bandwidth()\n{\n u_long bw_est;\n if (stats.get_estimate(NET_STATS_BW_UP, bw_est)) {\n return bw_est;\n } else {\n return iface_bandwidth(local_iface, remote_iface);\n }\n}\n\ndouble CSocket::RTT()\n{\n u_long latency_est;\n if (stats.get_estimate(NET_STATS_LATENCY, latency_est)) {\n return (double)(latency_est * 2);\n } else {\n return iface_RTT(local_iface, remote_iface);\n }\n}\n\nstruct timespec \nCSocket::retransmission_timeout()\n{\n \/\/ have a fairly high floor on this so that we don't\n \/\/ flood the socket with spurious retransmissions\n struct timespec min_rto = {30, 0};\n struct timespec default_rto = {120, 0};\n \n int bufsize = 0;\n socklen_t len = sizeof(bufsize);\n int rc = getsockopt(osfd, SOL_SOCKET, SO_SNDBUF, &bufsize, &len);\n if (rc < 0) {\n\tdbgprintf(\"Failed to get socket send buffer size: %s\\n\", strerror(errno));\n\tdbgprintf(\" returning default RTO\\n\");\n\treturn default_rto;\n }\n\n u_long bw = bandwidth();\n if (bw == 0) {\n\treturn default_rto;\n }\n u_long rto = ((bufsize \/ bandwidth()) + 2 * RTT()) * 2;\n struct timeval tv = convert_to_timeval(rto);\n struct timespec ts_rto = {tv.tv_sec, tv.tv_usec * 1000};\n\n if (ts_rto.tv_sec < min_rto.tv_sec) {\n\treturn min_rto;\n }\n return ts_rto;\n\n \/*\n struct tcp_info info;\n socklen_t len = sizeof(info);\n struct protoent *pe = getprotobyname(\"TCP\");\n int rc = -1;\n if (pe) {\n\trc = getsockopt (osfd, pe->p_proto, TCP_INFO, &info, &len);\n if (rc == 0) {\n long int usecs = info.tcpi_rto;\n ret.tv_sec = usecs \/ 1000000;\n ret.tv_nsec = (usecs - (ret.tv_sec*1000000)) * 1000;\n } else {\n dbgprintf(\"getsockopt failed for TCP_INFO: %s\\n\",\n strerror(errno));\n }\n } else {\n dbgprintf(\"getprotoent failed for TCP: %s\\n\",\n strerror(errno));\n }\n if (rc < 0) {\n\tdbgprintf(\"Cannot read tcpi_rto; making a lazy guess\\n\");\n \/\/TODO: more accurate guess?\n }\n dbgprintf(\"Retransmission timeout for csock %d is %ld.%09ld\\n\",\n osfd, ret.tv_sec, ret.tv_nsec);\n *\/\n}\n\n\n\/\/#define useconds(tv) ((tv).tv_sec*1000000 + (tv).tv_usec)\n\nssize_t\nCSocket::trickle_chunksize()\/*struct timeval time_since_last_fg,\n struct timeval bg_wait_time)*\/\n{\n const long int max_tolerable_fg_delay = 50; \/\/ms\n ssize_t max_chunksize = (bandwidth() * max_tolerable_fg_delay) \/ 1000;\n \/\/ssize_t min_chunksize = 64;\n \/*\n ssize_t chunksize = min_chunksize * (1 << (useconds(time_since_last_fg) \/\n useconds(sk->bg_wait_time())*2));\n if (chunksize < 0) {\n chunksize = max_chunksize;\n }\n *\/\n \/\/ssize_t chunksize = max(chunksize, min_chunksize);\n ssize_t chunksize = max_chunksize;\n return chunksize;\n}\nMinor compile (cast) fix.#include \"cmm_socket.private.h\"\n#include \"csocket.h\"\n#include \"debug.h\"\n#include \"timeops.h\"\n#include \"cmm_socket_control.h\"\n#include \n#include \n#include \n#include \n#include \"csocket_sender.h\"\n#include \"csocket_receiver.h\"\n#include \"csocket_mapping.h\"\n#include \nusing std::max;\n\nCSocketPtr\nCSocket::create(boost::weak_ptr sk_,\n struct net_interface local_iface_, \n struct net_interface remote_iface_,\n int accepted_sock)\n{\n CSocketPtr new_csock(new CSocket(sk_, local_iface_, \n remote_iface_, accepted_sock));\n new_csock->self_ptr = new_csock;\n return new_csock;\n}\n\nCSocket::CSocket(boost::weak_ptr sk_,\n struct net_interface local_iface_, \n struct net_interface remote_iface_,\n int accepted_sock)\n : sk(sk_),\n local_iface(local_iface_), remote_iface(remote_iface_),\n stats(local_iface, remote_iface),\n csock_sendr(NULL), csock_recvr(NULL), irob_indexes(local_iface_.labels)\n{\n assert(sk);\n if (accepted_sock == -1) {\n osfd = socket(sk->sock_family, sk->sock_type, sk->sock_protocol);\n if (osfd < 0) {\n \/* out of file descriptors or memory at this point *\/\n throw std::runtime_error(\"Out of FDs or memory!\");\n }\n \n sk->set_all_sockopts(osfd);\n } else {\n osfd = accepted_sock;\n }\n \n int on = 1;\n int rc;\n \/* Make sure that this socket is TCP_NODELAY for good performance *\/\n struct protoent *pe = getprotobyname(\"TCP\");\n if (pe) {\n\trc = setsockopt (osfd, pe->p_proto, TCP_NODELAY, \n\t\t\t (char *) &on, sizeof(on));\n } else {\n\trc = setsockopt (osfd, 6, TCP_NODELAY, \n\t\t\t (char *) &on, sizeof(on));\n }\n if (rc < 0) {\n\tdbgprintf(\"Cannot make socket TCP_NODELAY\");\n }\n}\n\nCSocket::~CSocket()\n{\n dbgprintf(\"CSocket %d is being destroyed\\n\", osfd);\n if (osfd > 0) {\n\t\/* if it's a real open socket *\/\n assert(csock_sendr == NULL && csock_recvr == NULL);\n\tclose(osfd);\n } \n}\n\nint\nCSocket::phys_connect()\n{\n struct sockaddr_in local_addr, remote_addr;\n \n \/\/ XXX-TODO: don't assume it's an inet socket\n\n local_addr.sin_family = AF_INET;\n local_addr.sin_addr = local_iface.ip_addr;\n local_addr.sin_port = 0;\n \n remote_addr.sin_family = AF_INET;\n remote_addr.sin_addr = remote_iface.ip_addr;\n remote_addr.sin_port = sk->remote_listener_port;\n \n int rc = bind(osfd, (struct sockaddr *)&local_addr, \n sizeof(local_addr));\n if (rc < 0) {\n\tperror(\"bind\");\n\tdbgprintf(\"Failed to bind osfd %d to %s:%d\\n\",\n\t\t osfd, inet_ntoa(local_addr.sin_addr), \n\t\t ntohs(local_addr.sin_port));\n\treturn rc;\n }\n dbgprintf(\"Successfully bound osfd %d to %s:%d\\n\",\n\t osfd, inet_ntoa(local_addr.sin_addr), \n\t ntohs(local_addr.sin_port));\n \n rc = connect(osfd, (struct sockaddr *)&remote_addr, \n\t\t sizeof(remote_addr));\n if (rc < 0) {\n\tperror(\"connect\");\n\tdbgprintf(\"Failed to connect osfd %d to %s:%d\\n\",\n\t\t osfd, inet_ntoa(remote_addr.sin_addr), \n\t\t ntohs(remote_addr.sin_port));\n\treturn rc;\n }\n struct CMMSocketControlHdr hdr;\n memset(&hdr, 0, sizeof(hdr));\n hdr.type = htons(CMM_CONTROL_MSG_NEW_INTERFACE);\n hdr.send_labels = 0;\n hdr.op.new_interface.ip_addr = local_iface.ip_addr;\n hdr.op.new_interface.labels = htonl(local_iface.labels);\n hdr.op.new_interface.bandwidth = htonl(local_iface.bandwidth);\n hdr.op.new_interface.RTT = htonl(local_iface.RTT);\n rc = send(osfd, &hdr, sizeof(hdr), 0);\n if (rc != sizeof(hdr)) {\n perror(\"send\");\n dbgprintf(\"Failed to send interface info\\n\");\n return rc;\n }\n\n startup_workers();\n return 0;\n}\n\nvoid\nCSocket::startup_workers()\n{\n if (!csock_sendr && !csock_recvr) {\n\tcsock_sendr = new CSocketSender(CSocketPtr(self_ptr));\n\tcsock_recvr = new CSocketReceiver(CSocketPtr(self_ptr));\n\tint rc = csock_sendr->start();\n if (rc != 0) {\n throw std::runtime_error(\"Failed to create csocket_sender thread!\");\n }\n\trc = csock_recvr->start();\n if (rc != 0) {\n throw std::runtime_error(\"Failed to create csocket_receiver thread!\");\n }\n }\n}\n\n\/* must not be holding sk->scheduling_state_lock. *\/\nbool \nCSocket::matches(u_long send_labels)\n{\n return sk->csock_map->csock_matches(this, send_labels);\n}\n\nu_long\nCSocket::bandwidth()\n{\n u_long bw_est;\n if (stats.get_estimate(NET_STATS_BW_UP, bw_est)) {\n return bw_est;\n } else {\n return iface_bandwidth(local_iface, remote_iface);\n }\n}\n\ndouble CSocket::RTT()\n{\n u_long latency_est;\n if (stats.get_estimate(NET_STATS_LATENCY, latency_est)) {\n return (double)(latency_est * 2);\n } else {\n return iface_RTT(local_iface, remote_iface);\n }\n}\n\nstruct timespec \nCSocket::retransmission_timeout()\n{\n \/\/ have a fairly high floor on this so that we don't\n \/\/ flood the socket with spurious retransmissions\n struct timespec min_rto = {30, 0};\n struct timespec default_rto = {120, 0};\n \n int bufsize = 0;\n socklen_t len = sizeof(bufsize);\n int rc = getsockopt(osfd, SOL_SOCKET, SO_SNDBUF, &bufsize, &len);\n if (rc < 0) {\n\tdbgprintf(\"Failed to get socket send buffer size: %s\\n\", strerror(errno));\n\tdbgprintf(\" returning default RTO\\n\");\n\treturn default_rto;\n }\n\n u_long bw = bandwidth();\n if (bw == 0) {\n\treturn default_rto;\n }\n u_long rto = ((bufsize \/ bandwidth()) + 2 * (u_long)RTT()) * 2;\n struct timeval tv = convert_to_timeval(rto);\n struct timespec ts_rto = {tv.tv_sec, tv.tv_usec * 1000};\n\n if (ts_rto.tv_sec < min_rto.tv_sec) {\n\treturn min_rto;\n }\n return ts_rto;\n\n \/*\n struct tcp_info info;\n socklen_t len = sizeof(info);\n struct protoent *pe = getprotobyname(\"TCP\");\n int rc = -1;\n if (pe) {\n\trc = getsockopt (osfd, pe->p_proto, TCP_INFO, &info, &len);\n if (rc == 0) {\n long int usecs = info.tcpi_rto;\n ret.tv_sec = usecs \/ 1000000;\n ret.tv_nsec = (usecs - (ret.tv_sec*1000000)) * 1000;\n } else {\n dbgprintf(\"getsockopt failed for TCP_INFO: %s\\n\",\n strerror(errno));\n }\n } else {\n dbgprintf(\"getprotoent failed for TCP: %s\\n\",\n strerror(errno));\n }\n if (rc < 0) {\n\tdbgprintf(\"Cannot read tcpi_rto; making a lazy guess\\n\");\n \/\/TODO: more accurate guess?\n }\n dbgprintf(\"Retransmission timeout for csock %d is %ld.%09ld\\n\",\n osfd, ret.tv_sec, ret.tv_nsec);\n *\/\n}\n\n\n\/\/#define useconds(tv) ((tv).tv_sec*1000000 + (tv).tv_usec)\n\nssize_t\nCSocket::trickle_chunksize()\/*struct timeval time_since_last_fg,\n struct timeval bg_wait_time)*\/\n{\n const long int max_tolerable_fg_delay = 50; \/\/ms\n ssize_t max_chunksize = (bandwidth() * max_tolerable_fg_delay) \/ 1000;\n \/\/ssize_t min_chunksize = 64;\n \/*\n ssize_t chunksize = min_chunksize * (1 << (useconds(time_since_last_fg) \/\n useconds(sk->bg_wait_time())*2));\n if (chunksize < 0) {\n chunksize = max_chunksize;\n }\n *\/\n \/\/ssize_t chunksize = max(chunksize, min_chunksize);\n ssize_t chunksize = max_chunksize;\n return chunksize;\n}\n<|endoftext|>"} {"text":"#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tファイル操作ユーティリティー\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2018 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/sdc_man.hpp\"\n#include \"common\/fixed_stack.hpp\"\n\nnamespace graphics {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief\tファイラー制御型\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tenum class filer_ctrl {\n\t\tOPEN,\t\t\/\/\/< ファイラーを起動\n\t\tUP,\t\t\t\/\/\/< スクロール上\n\t\tDOWN,\t\t\/\/\/< スクロール下\n\t\tBACK,\t\t\/\/\/< ディレクトリーを戻る\n\t\tSELECT,\t\t\/\/\/< 選択\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief\t制御データ構築\n\t\t@param[in]\tpos\t\tファイラー制御型\n\t\t@param[in]\tctrl\t制御データ(参照)\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline void set(filer_ctrl pos, uint32_t& ctrl) noexcept\n\t{\n\t\tctrl |= 1 << static_cast(pos);\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief\tファイラー\n\t\t@param[in]\tSDC\tsdc_man クラス型\n\t\t@param[in]\tRDR\trender クラス型\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tclass filer {\n\n\t\tstatic const int16_t SPC = 2; \/\/\/< 文字間隙間\n\t\tstatic const int16_t FLN = RDR::font_height + SPC; \/\/\/< 行幅\n\t\tstatic const int16_t SCN = (RDR::height - SPC) \/ FLN; \/\/\/< 行数\n\n\t\tstatic const uint32_t PATH_MAX = 128;\t\t\t\t\t\/\/\/< パスの最大文字数\n\n\t\tSDC&\tsdc_;\n\t\tRDR&\trdr_;\n\n\t\tuint32_t\tctrl_;\n\t\tbool\t\topen_;\n\n\t\tstruct rdr_st {\n\t\t\tRDR&\t\trdr_;\n\t\t\tint16_t\t\tvofs_;\n\t\t\tint16_t\t\tvpos_;\n\t\t\tint16_t\t\thmax_;\n\t\t\tint16_t\t\tsel_pos_;\n\t\t\tuint16_t\tnum_;\n\n\t\t\tchar\t\tpath_[PATH_MAX * SCN];\n\n\t\t\trdr_st(RDR& rdr) noexcept : rdr_(rdr), vofs_(0), vpos_(0), hmax_(0), sel_pos_(0),\n\t\t\t\tnum_(0), path_{ 0 }\n\t\t\t{ }\n\t\t};\n\t\trdr_st\trdr_st_;\n\n\t\tstruct pos_t {\n\t\t\tint16_t\t\tvofs_;\n\t\t\tint16_t\t\tsel_pos_;\n\t\t\tpos_t(int16_t vofs = 0, int16_t sel_pos = 0) noexcept :\n\t\t\t\tvofs_(vofs), sel_pos_(sel_pos) { }\n\t\t};\n\t\ttypedef utils::fixed_stack POS_STACK;\n\t\tPOS_STACK\t\tpos_stack_;\n\n\n\t\tstatic uint32_t ctrl_mask_(filer_ctrl ctrl) noexcept\n\t\t{\n\t\t\treturn 1 << static_cast(ctrl);\n\t\t}\n\n\n\t\tstatic void dir_draw_func_(const char* name, const FILINFO* fi, bool dir, void* opt)\n\t\t\tnoexcept\n\t\t{\n\t\t\trdr_st& t = *static_cast(opt);\n\t\t\tif(t.vpos_ >= 0 && t.vpos_ < RDR::height) {\n\t\t\t\tt.rdr_.set_fore_color(RDR::COLOR::White);\n\t\t\t\tt.rdr_.fill(SPC, t.vpos_, RDR::width - SPC * 2, RDR::font_height, 0x0000);\n\t\t\t\tif(dir) t.rdr_.draw_font(SPC, t.vpos_, '\/');\n\t\t\t}\n\t\t\tif(dir) {\n\t\t\t\tt.rdr_.set_fore_color(RDR::COLOR::Blue);\n\t\t\t} else {\n\t\t\t\tt.rdr_.set_fore_color(RDR::COLOR::White);\n\t\t\t}\n\t\t\tauto w = t.rdr_.draw_text(SPC + 8, t.vpos_, name);\n\t\t\tif(t.hmax_ < w) t.hmax_ = w;\n\t\t\tuint32_t n = t.num_ + t.vofs_ \/ FLN;\n\t\t\tif(n < SCN) {\n\t\t\t\tstrncpy(&t.path_[n * PATH_MAX], name, PATH_MAX);\n\t\t\t\tif(dir) {\n\t\t\t\t\tstrncat(&t.path_[n * PATH_MAX], \"\/\", PATH_MAX);\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.vpos_ += FLN;\n\t\t\t++t.num_;\n\t\t}\n\n\n\t\tvoid start_dir_draw_() noexcept\n\t\t{\n\t\t\tuint32_t num = (RDR::height - 2) \/ (RDR::font_height + 2);\n\t\t\trdr_st_.vpos_ = rdr_st_.vofs_ + 2;\n\t\t\trdr_st_.num_ = 0;\n\t\t\tsdc_.start_dir_list(\"\", dir_draw_func_, true, &rdr_st_);\n\t\t}\n\n\n\t\tvoid draw_sel_frame_(int16_t pos, uint16_t c)\n\t\t{\n\t\t\tint16_t h = RDR::font_height + 2;\n\t\t\tint16_t y = pos * h;\n\t\t\trdr_.frame(0, y, rdr_st_.hmax_ + 3, h + 1, c);\n\t\t}\n\n\n\t\tvoid scan_dir_(bool back)\n\t\t{\n\t\t\tif(back) {\n\t\t\t\tif(pos_stack_.empty()) {\n\t\t\t\t\trdr_st_.vofs_ = 0;\n\t\t\t\t\trdr_st_.sel_pos_ = 0;\n\t\t\t\t} else {\n\t\t\t\t\tconst auto& t = pos_stack_.pull();\n\t\t\t\t\trdr_st_.vofs_ = t.vofs_;\n\t\t\t\t\trdr_st_.sel_pos_ = t.sel_pos_;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trdr_st_.vofs_ = 0;\n\t\t\t\trdr_st_.sel_pos_ = 0;\n\t\t\t}\n\t\t\tstart_dir_draw_();\n\t\t}\n\n\tpublic:\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tコンストラクター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tfiler(SDC& sdc, RDR& rdr) noexcept : sdc_(sdc), rdr_(rdr),\n\t\t\tctrl_(0), open_(false),\n\t\t\trdr_st_(rdr_)\n\t\t{ }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tアップデート(毎フレーム呼ぶ)\n\t\t\t@param[in]\tctrl\tファイラー制御\n\t\t\t@return ファイルが選択された場合、ファイルパス\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tconst char* update(uint32_t ctrl) noexcept\n\t\t{\n\t\t\tuint32_t ptrg = ~ctrl_ & ctrl;\n\t\t\tuint32_t ntrg = ctrl_ & ~ctrl;\n\t\t\tctrl_ = ctrl;\n\n\t\t\tif(!sdc_.get_mount()) {\n\t\t\t\topen_ = false;\n\t\t\t\tpos_stack_.clear();\n\t\t\t\trdr_.clear(RDR::COLOR::Black);\n\t\t\t\treturn nullptr;\n\t\t\t}\n\n\t\t\tif(ptrg & ctrl_mask_(filer_ctrl::OPEN)) {\n\t\t\t\topen_ = !open_;\n\t\t\t\tif(open_) {\n\t\t\t\t\tscan_dir_(false);\n\t\t\t\t} else {\n\t\t\t\t\trdr_.clear(RDR::COLOR::Black);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(!open_) return nullptr;\n\n\t\t\t{\n\t\t\t\tuint32_t n;\n\t\t\t\tbool f = sdc_.probe_dir_list(n);\n\t\t\t\tif(f) return nullptr;\n\t\t\t\tif(rdr_st_.num_ < static_cast(n)) return nullptr;\n\t\t\t}\n\n\t\t\t\/\/ 選択フレームの描画\n\t\t\tdraw_sel_frame_(rdr_st_.sel_pos_, 0xffff);\n\t\t\tint16_t pos = rdr_st_.sel_pos_;\n\t\t\tif(ptrg & ctrl_mask_(filer_ctrl::UP)) {\n\t\t\t\tpos--;\n\t\t\t}\n\t\t\tif(ptrg & ctrl_mask_(filer_ctrl::DOWN)) {\n\t\t\t\t++pos;\n\t\t\t}\n\t\t\tint16_t vofs = rdr_st_.vofs_;\n\t\t\tint16_t scn = SCN;\n\t\t\tif(rdr_st_.num_ < scn) scn = rdr_st_.num_; \n\t\t\tif(pos < 0) {\n\t\t\t\tpos = 0;\n\t\t\t\tvofs += FLN;\n\t\t\t} else if(pos >= scn) {\n\t\t\t\tpos = scn - 1;\n\t\t\t\tvofs -= FLN;\n\t\t\t}\n\t\t\tint16_t lim = 0;\n\t\t\tif(rdr_st_.num_ > scn) {\n\t\t\t\tlim = -(rdr_st_.num_ - scn) * FLN;\n\t\t\t}\n\t\t\tif(vofs > 0) {\n\t\t\t\tvofs = 0;\n\t\t\t} else if(vofs < lim) {\n\t\t\t\tvofs = lim;\n\t\t\t}\n\t\t\tif(vofs != rdr_st_.vofs_) {\n\t\t\t\trdr_st_.vofs_ = vofs;\n\t\t\t\tstart_dir_draw_();\n\t\t\t}\n\t\t\t\n\t\t\tif(pos != rdr_st_.sel_pos_) {\n\t\t\t\tdraw_sel_frame_(rdr_st_.sel_pos_, 0x0000);\n\t\t\t\trdr_st_.sel_pos_ = pos;\n\t\t\t}\n\n\t\t\tif(ptrg & ctrl_mask_(filer_ctrl::SELECT)) {\n\t\t\t\tchar* p = &rdr_st_.path_[PATH_MAX * rdr_st_.sel_pos_];\n\t\t\t\tuint32_t l = strlen(p);\n\t\t\t\tif(p[l - 1] == '\/') {\n\t\t\t\t\tpos_stack_.push(pos_t(rdr_st_.vofs_, rdr_st_.sel_pos_));\n\t\t\t\t\tp[l - 1] = 0;\n\t\t\t\t\tsdc_.cd(p);\n\t\t\t\t\trdr_.clear(RDR::COLOR::Black);\n\t\t\t\t\tscan_dir_(false);\n\t\t\t\t} else {\n\t\t\t\t\trdr_.clear(RDR::COLOR::Black);\n\t\t\t\t\topen_ = false;\n\t\t\t\t\treturn static_cast(p);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(ptrg & ctrl_mask_(filer_ctrl::BACK)) {\n\t\t\t\tif(!pos_stack_.empty()) {\n\t\t\t\t\tsdc_.cd(\"..\");\n\t\t\t\t\trdr_.clear(RDR::COLOR::Black);\n\t\t\t\t\tscan_dir_(true);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nullptr;\n\t\t}\n\t};\n}\nupdate: file path length#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tファイル操作ユーティリティー\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2018 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/sdc_man.hpp\"\n#include \"common\/fixed_stack.hpp\"\n\nnamespace graphics {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief\tファイラー制御型\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tenum class filer_ctrl {\n\t\tOPEN,\t\t\/\/\/< ファイラーを起動\n\t\tUP,\t\t\t\/\/\/< スクロール上\n\t\tDOWN,\t\t\/\/\/< スクロール下\n\t\tBACK,\t\t\/\/\/< ディレクトリーを戻る\n\t\tSELECT,\t\t\/\/\/< 選択\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief\t制御データ構築\n\t\t@param[in]\tpos\t\tファイラー制御型\n\t\t@param[in]\tctrl\t制御データ(参照)\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline void set(filer_ctrl pos, uint32_t& ctrl) noexcept\n\t{\n\t\tctrl |= 1 << static_cast(pos);\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief\tファイラー\n\t\t@param[in]\tSDC\tsdc_man クラス型\n\t\t@param[in]\tRDR\trender クラス型\n\t\t@param[in]\tPTM\tパス文字列最大数\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tclass filer {\n\n\t\tstatic const int16_t SPC = 2; \/\/\/< 文字間隙間\n\t\tstatic const int16_t FLN = RDR::font_height + SPC; \/\/\/< 行幅\n\t\tstatic const int16_t SCN = (RDR::height - SPC) \/ FLN; \/\/\/< 行数\n\n\t\tstatic const uint32_t PATH_MAX = PTM;\t\t\t\t\t\/\/\/< パスの最大文字数\n\n\t\tSDC&\tsdc_;\n\t\tRDR&\trdr_;\n\n\t\tuint32_t\tctrl_;\n\t\tbool\t\topen_;\n\n\t\tstruct rdr_st {\n\t\t\tRDR&\t\trdr_;\n\t\t\tint16_t\t\tvofs_;\n\t\t\tint16_t\t\tvpos_;\n\t\t\tint16_t\t\thmax_;\n\t\t\tint16_t\t\tsel_pos_;\n\t\t\tuint16_t\tnum_;\n\n\t\t\tchar\t\tpath_[PATH_MAX * SCN];\n\n\t\t\trdr_st(RDR& rdr) noexcept : rdr_(rdr), vofs_(0), vpos_(0), hmax_(0), sel_pos_(0),\n\t\t\t\tnum_(0), path_{ 0 }\n\t\t\t{ }\n\t\t};\n\t\trdr_st\trdr_st_;\n\n\t\tstruct pos_t {\n\t\t\tint16_t\t\tvofs_;\n\t\t\tint16_t\t\tsel_pos_;\n\t\t\tpos_t(int16_t vofs = 0, int16_t sel_pos = 0) noexcept :\n\t\t\t\tvofs_(vofs), sel_pos_(sel_pos) { }\n\t\t};\n\t\ttypedef utils::fixed_stack POS_STACK;\n\t\tPOS_STACK\t\tpos_stack_;\n\n\n\t\tstatic uint32_t ctrl_mask_(filer_ctrl ctrl) noexcept\n\t\t{\n\t\t\treturn 1 << static_cast(ctrl);\n\t\t}\n\n\n\t\tstatic void dir_draw_func_(const char* name, const FILINFO* fi, bool dir, void* opt)\n\t\t\tnoexcept\n\t\t{\n\t\t\trdr_st& t = *static_cast(opt);\n\t\t\tif(t.vpos_ >= 0 && t.vpos_ < RDR::height) {\n\t\t\t\tt.rdr_.set_fore_color(RDR::COLOR::White);\n\t\t\t\tt.rdr_.fill(SPC, t.vpos_, RDR::width - SPC * 2, RDR::font_height, 0x0000);\n\t\t\t\tif(dir) t.rdr_.draw_font(SPC, t.vpos_, '\/');\n\t\t\t}\n\t\t\tif(dir) {\n\t\t\t\tt.rdr_.set_fore_color(RDR::COLOR::Blue);\n\t\t\t} else {\n\t\t\t\tt.rdr_.set_fore_color(RDR::COLOR::White);\n\t\t\t}\n\t\t\tauto w = t.rdr_.draw_text(SPC + 8, t.vpos_, name);\n\t\t\tif(t.hmax_ < w) t.hmax_ = w;\n\t\t\tuint32_t n = t.num_ + t.vofs_ \/ FLN;\n\t\t\tif(n < SCN) {\n\t\t\t\tstrncpy(&t.path_[n * PATH_MAX], name, PATH_MAX);\n\t\t\t\tif(dir) {\n\t\t\t\t\tstrncat(&t.path_[n * PATH_MAX], \"\/\", PATH_MAX);\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.vpos_ += FLN;\n\t\t\t++t.num_;\n\t\t}\n\n\n\t\tvoid start_dir_draw_() noexcept\n\t\t{\n\t\t\tuint32_t num = (RDR::height - 2) \/ (RDR::font_height + 2);\n\t\t\trdr_st_.vpos_ = rdr_st_.vofs_ + 2;\n\t\t\trdr_st_.num_ = 0;\n\t\t\tsdc_.start_dir_list(\"\", dir_draw_func_, true, &rdr_st_);\n\t\t}\n\n\n\t\tvoid draw_sel_frame_(int16_t pos, uint16_t c)\n\t\t{\n\t\t\tint16_t h = RDR::font_height + 2;\n\t\t\tint16_t y = pos * h;\n\t\t\trdr_.frame(0, y, rdr_st_.hmax_ + 3, h + 1, c);\n\t\t}\n\n\n\t\tvoid scan_dir_(bool back)\n\t\t{\n\t\t\tif(back) {\n\t\t\t\tif(pos_stack_.empty()) {\n\t\t\t\t\trdr_st_.vofs_ = 0;\n\t\t\t\t\trdr_st_.sel_pos_ = 0;\n\t\t\t\t} else {\n\t\t\t\t\tconst auto& t = pos_stack_.pull();\n\t\t\t\t\trdr_st_.vofs_ = t.vofs_;\n\t\t\t\t\trdr_st_.sel_pos_ = t.sel_pos_;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trdr_st_.vofs_ = 0;\n\t\t\t\trdr_st_.sel_pos_ = 0;\n\t\t\t}\n\t\t\tstart_dir_draw_();\n\t\t}\n\n\tpublic:\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tコンストラクター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tfiler(SDC& sdc, RDR& rdr) noexcept : sdc_(sdc), rdr_(rdr),\n\t\t\tctrl_(0), open_(false),\n\t\t\trdr_st_(rdr_)\n\t\t{ }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tアップデート(毎フレーム呼ぶ)\n\t\t\t@param[in]\tctrl\tファイラー制御\n\t\t\t@return ファイルが選択された場合、ファイルパス\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tconst char* update(uint32_t ctrl) noexcept\n\t\t{\n\t\t\tuint32_t ptrg = ~ctrl_ & ctrl;\n\t\t\tuint32_t ntrg = ctrl_ & ~ctrl;\n\t\t\tctrl_ = ctrl;\n\n\t\t\tif(!sdc_.get_mount()) {\n\t\t\t\topen_ = false;\n\t\t\t\tpos_stack_.clear();\n\t\t\t\trdr_.clear(RDR::COLOR::Black);\n\t\t\t\treturn nullptr;\n\t\t\t}\n\n\t\t\tif(ptrg & ctrl_mask_(filer_ctrl::OPEN)) {\n\t\t\t\topen_ = !open_;\n\t\t\t\trdr_.clear(RDR::COLOR::Black);\n\t\t\t\tif(open_) {\n\t\t\t\t\tscan_dir_(false);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(!open_) return nullptr;\n\n\t\t\t{\n\t\t\t\tuint32_t n;\n\t\t\t\tbool f = sdc_.probe_dir_list(n);\n\t\t\t\tif(f) return nullptr;\n\t\t\t\tif(rdr_st_.num_ < static_cast(n)) return nullptr;\n\t\t\t}\n\n\t\t\t\/\/ 選択フレームの描画\n\t\t\tdraw_sel_frame_(rdr_st_.sel_pos_, 0xffff);\n\t\t\tint16_t pos = rdr_st_.sel_pos_;\n\t\t\tif(ptrg & ctrl_mask_(filer_ctrl::UP)) {\n\t\t\t\tpos--;\n\t\t\t}\n\t\t\tif(ptrg & ctrl_mask_(filer_ctrl::DOWN)) {\n\t\t\t\t++pos;\n\t\t\t}\n\t\t\tint16_t vofs = rdr_st_.vofs_;\n\t\t\tint16_t scn = SCN;\n\t\t\tif(rdr_st_.num_ < scn) scn = rdr_st_.num_; \n\t\t\tif(pos < 0) {\n\t\t\t\tpos = 0;\n\t\t\t\tvofs += FLN;\n\t\t\t} else if(pos >= scn) {\n\t\t\t\tpos = scn - 1;\n\t\t\t\tvofs -= FLN;\n\t\t\t}\n\t\t\tint16_t lim = 0;\n\t\t\tif(rdr_st_.num_ > scn) {\n\t\t\t\tlim = -(rdr_st_.num_ - scn) * FLN;\n\t\t\t}\n\t\t\tif(vofs > 0) {\n\t\t\t\tvofs = 0;\n\t\t\t} else if(vofs < lim) {\n\t\t\t\tvofs = lim;\n\t\t\t}\n\t\t\tif(vofs != rdr_st_.vofs_) {\n\t\t\t\trdr_st_.vofs_ = vofs;\n\t\t\t\tstart_dir_draw_();\n\t\t\t}\n\t\t\t\n\t\t\tif(pos != rdr_st_.sel_pos_) {\n\t\t\t\tdraw_sel_frame_(rdr_st_.sel_pos_, 0x0000);\n\t\t\t\trdr_st_.sel_pos_ = pos;\n\t\t\t}\n\n\t\t\tif(ptrg & ctrl_mask_(filer_ctrl::SELECT)) {\n\t\t\t\tchar* p = &rdr_st_.path_[PATH_MAX * rdr_st_.sel_pos_];\n\t\t\t\tuint32_t l = strlen(p);\n\t\t\t\tif(p[l - 1] == '\/') {\n\t\t\t\t\tpos_stack_.push(pos_t(rdr_st_.vofs_, rdr_st_.sel_pos_));\n\t\t\t\t\tp[l - 1] = 0;\n\t\t\t\t\tsdc_.cd(p);\n\t\t\t\t\trdr_.clear(RDR::COLOR::Black);\n\t\t\t\t\tscan_dir_(false);\n\t\t\t\t} else {\n\t\t\t\t\trdr_.clear(RDR::COLOR::Black);\n\t\t\t\t\topen_ = false;\n\t\t\t\t\treturn static_cast(p);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(ptrg & ctrl_mask_(filer_ctrl::BACK)) {\n\t\t\t\tif(!pos_stack_.empty()) {\n\t\t\t\t\tsdc_.cd(\"..\");\n\t\t\t\t\trdr_.clear(RDR::COLOR::Black);\n\t\t\t\t\tscan_dir_(true);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nullptr;\n\t\t}\n\t};\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)\n *\n * Released under the MIT license, see LICENSE.txt\n *\/\n#include \n#include \n#include \"hdf5MetaData.h\"\n#include \"halCommon.h\"\n\nusing namespace hal;\nusing namespace H5;\nusing namespace std;\n\nHDF5MetaData::HDF5MetaData() :\n _parent(NULL)\n{\n}\n\nHDF5MetaData::HDF5MetaData(CommonFG* parent, const string& name)\n{\n open(parent, name);\n}\n\nHDF5MetaData::~HDF5MetaData()\n{\n write();\n}\n\nvoid HDF5MetaData::set(const string& key, const string& value)\n{\n if (has(key) == true)\n {\n _map[key] = value;\n }\n else\n {\n _map.insert(pair(key, value));\n }\n _dirty = true;\n}\n\nconst string& HDF5MetaData::get(const string& key) const\n{\n assert (has(key) == true);\n return _map.find(key)->second;\n}\n\nbool HDF5MetaData::has(const string& key) const\n{\n return _map.find(key) != _map.end();\n}\n\nconst map& HDF5MetaData::getMap() const\n{\n return _map;\n}\n\nstatic void attr_operator(H5Object& loc\/*in*\/,\n const H5std_string attr_name\/*in*\/,\n void *operator_data\/*in,out*\/)\n{\n map* attMap = \n static_cast*>(operator_data);\n StrType vlsType(0, H5T_VARIABLE);\n Attribute attr = loc.openAttribute(attr_name);\n H5std_string strg;\n attr.read(vlsType, strg);\n attMap->insert(pair(attr_name, strg));\n}\n\nvoid HDF5MetaData::open(CommonFG* parent, const string& name)\n{\n assert(parent != NULL);\n _map.clear();\n _parent = parent;\n _name = name;\n _dirty = false;\n\n H5::Exception::dontPrint();\n try\n {\n _group = parent->openGroup(name);\n }\n catch (Exception& e)\n {\n _group = parent->createGroup(name);\n }\n\n if (_group.getNumAttrs() > 0)\n {\n _group.iterateAttrs(attr_operator, NULL, &_map);\n }\n assert(_map.size() == (size_t)_group.getNumAttrs());\n}\n\nvoid HDF5MetaData::write()\n{\n if (!_dirty)\n return;\n\n for (map::iterator i = _map.begin();\n i != _map.end(); \n ++i)\n {\n StrType vlsType(0, H5T_VARIABLE);\n DataSpace attSpace(H5S_SCALAR);\n Attribute attr;\n \/\/ we delve into C api for this test\n if (H5Aexists(_group.getId(), i->first.c_str()) == true)\n {\n _group.removeAttr(_name);\n }\n attr = _group.createAttribute(i->first, vlsType, attSpace);\n attr.write(vlsType, i->second);\n }\n _dirty = false;\n}\nfix metadata rewrite bug\/*\n * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)\n *\n * Released under the MIT license, see LICENSE.txt\n *\/\n#include \n#include \n#include \"hdf5MetaData.h\"\n#include \"halCommon.h\"\n\nusing namespace hal;\nusing namespace H5;\nusing namespace std;\n\nHDF5MetaData::HDF5MetaData() :\n _parent(NULL)\n{\n}\n\nHDF5MetaData::HDF5MetaData(CommonFG* parent, const string& name)\n{\n open(parent, name);\n}\n\nHDF5MetaData::~HDF5MetaData()\n{\n write();\n}\n\nvoid HDF5MetaData::set(const string& key, const string& value)\n{\n if (has(key) == true)\n {\n _map[key] = value;\n }\n else\n {\n _map.insert(pair(key, value));\n }\n _dirty = true;\n}\n\nconst string& HDF5MetaData::get(const string& key) const\n{\n assert (has(key) == true);\n return _map.find(key)->second;\n}\n\nbool HDF5MetaData::has(const string& key) const\n{\n return _map.find(key) != _map.end();\n}\n\nconst map& HDF5MetaData::getMap() const\n{\n return _map;\n}\n\nstatic void attr_operator(H5Object& loc\/*in*\/,\n const H5std_string attr_name\/*in*\/,\n void *operator_data\/*in,out*\/)\n{\n map* attMap = \n static_cast*>(operator_data);\n StrType vlsType(0, H5T_VARIABLE);\n Attribute attr = loc.openAttribute(attr_name);\n H5std_string strg;\n attr.read(vlsType, strg);\n attMap->insert(pair(attr_name, strg));\n}\n\nvoid HDF5MetaData::open(CommonFG* parent, const string& name)\n{\n assert(parent != NULL);\n _map.clear();\n _parent = parent;\n _name = name;\n _dirty = false;\n\n H5::Exception::dontPrint();\n try\n {\n _group = parent->openGroup(name);\n }\n catch (Exception& e)\n {\n _group = parent->createGroup(name);\n }\n\n if (_group.getNumAttrs() > 0)\n {\n _group.iterateAttrs(attr_operator, NULL, &_map);\n }\n assert(_map.size() == (size_t)_group.getNumAttrs());\n}\n\nvoid HDF5MetaData::write()\n{\n if (!_dirty)\n return;\n\n for (map::iterator i = _map.begin();\n i != _map.end(); \n ++i)\n {\n StrType vlsType(0, H5T_VARIABLE);\n DataSpace attSpace(H5S_SCALAR);\n Attribute attr;\n \/\/ we delve into C api for this test\n if (H5Aexists(_group.getId(), i->first.c_str()) == true)\n {\n _group.removeAttr(i->first.c_str());\n }\n attr = _group.createAttribute(i->first, vlsType, attSpace);\n attr.write(vlsType, i->second);\n }\n _dirty = false;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\nint main(int argc, char *argv[]) {\n\tif(argc != 3) {\n\t\tfprintf(stderr, \"Usage: %s host port\\n\", argv[0]);\n\t\treturn 10;\n\t}\n\n\tuint16_t port = strtoul(argv[2], NULL, 10);\n\n\ttry {\n\t\tNetworkConfig *config = new NetworkConfig(\"test\", \"test\", \"n1CKn4M3\", \"us3RN4m3\", \"fuLLn4m3\", \"p4sSW0rd\");\n\t\tif(!config) return 2;\n\n\t\tServerConfig *server = new ServerConfig(argv[1], config, port);\n\t\tif(!server) return 3;\n\t\tconfig->servers.push_back(server);\n\n\t\tNetwork *n = new Network(config);\n\t\tif(!n) return 4;\n\n\t\tn->connectToNetwork(false);\n\t\t\/\/ run until disconnect\n\t\tn->run();\n\n\t\tdelete n;\n\t\tdelete server;\n\t\tdelete config;\n\t} catch(std::runtime_error e) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nAdd missing inclusion#include \n#include \n#include \n#include \n#include \n\nint main(int argc, char *argv[]) {\n\tif(argc != 3) {\n\t\tfprintf(stderr, \"Usage: %s host port\\n\", argv[0]);\n\t\treturn 10;\n\t}\n\n\tuint16_t port = strtoul(argv[2], NULL, 10);\n\n\ttry {\n\t\tNetworkConfig *config = new NetworkConfig(\"test\", \"test\", \"n1CKn4M3\", \"us3RN4m3\", \"fuLLn4m3\", \"p4sSW0rd\");\n\t\tif(!config) return 2;\n\n\t\tServerConfig *server = new ServerConfig(argv[1], config, port);\n\t\tif(!server) return 3;\n\t\tconfig->servers.push_back(server);\n\n\t\tNetwork *n = new Network(config);\n\t\tif(!n) return 4;\n\n\t\tn->connectToNetwork(false);\n\t\t\/\/ run until disconnect\n\t\tn->run();\n\n\t\tdelete n;\n\t\tdelete server;\n\t\tdelete config;\n\t} catch(std::runtime_error e) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n<|endoftext|>"} {"text":"#include \"CoordTransformer.h\"\n#include \"..\/graphics\/Rect.h\"\n#include \"..\/graphics\/Point.h\"\n\n#include \"math.h\"\n\nnamespace avg{\nCoordTransformer::CoordTransformer(IntRect srcRect, double K1, double T, double RescaleFactor)\n :m_K1(K1),\n m_TrapezoidFactor(T),\n m_RescaleFactor(RescaleFactor)\n{\n m_Center = DPoint((srcRect.tl.x+srcRect.br.x-1)\/2., (srcRect.tl.y+srcRect.br.y-1)\/2.);\n \/\/normalize to center-edge distance\n m_Scale = sqrt( pow(m_Center.x - srcRect.Width(),2) + pow(m_Center.y - srcRect.Height(),2) );\n m_TrapezoidScale = srcRect.Height()\/2;\n\n}\n CoordTransformer::~CoordTransformer(){};\n DPoint CoordTransformer::inv_distortion(const DPoint &pt){\n DPoint pt_norm = (pt - m_Center)\/m_Scale;\n double r_d_squared = pt_norm.x*pt_norm.x + pt_norm.y*pt_norm.y;\n double S = (1 - m_K1*r_d_squared)*m_RescaleFactor;\n return (pt_norm*S)*m_Scale + m_Center;\n }\n DPoint CoordTransformer::distortion(const DPoint &pt){\n DPoint pt_norm = (pt - m_Center)\/m_Scale;\n double r_d_squared = pt_norm.x*pt_norm.x + pt_norm.y*pt_norm.y;\n double S = (1 + m_K1*r_d_squared)\/m_RescaleFactor;\n return pt_norm*S*m_Scale + m_Center;\n }\n DPoint CoordTransformer::inv_trapezoid(const DPoint &pt){\n \/\/stretch x coord\n double yn = (pt.y - m_Center.y)\/m_TrapezoidScale;\n return DPoint( \n (pt.x + m_Center.x * yn*m_TrapezoidFactor)\/(1+yn*m_TrapezoidFactor),\n pt.y);\n }\n DPoint CoordTransformer::trapezoid(const DPoint &pt){\n \/\/stretch x coord\n double yn = (pt.y - m_Center.y)\/m_TrapezoidScale;\n return DPoint( \n \/\/m_Center.x + ( pt.x - m_Center.x) * (1 + m_TrapezoidFactor * yn), \n pt.x + yn*m_TrapezoidFactor * (pt.x - m_Center.x),\n pt.y);\n }\n DPoint CoordTransformer::inverse_transform_point(const DPoint &pt){\n return inv_trapezoid(inv_distortion(pt));\n }\n DPoint CoordTransformer::transform_point(const DPoint &pt){\n return distortion(trapezoid(pt));\n }\n double CoordTransformer::getPixelSize(const DPoint &pt){\n \/\/volume dxdy transforms as |D|dx'dy' where |D| is the functional determinant\n \/\/det { { dx'\/dx, dx'\/dy}, {dy'\/dx,dy'\/dy}}\n \/\/|D| = dx'\/dx * dy'\/dy - dx'\/dy * dy'\/dx\n \/\/\n \/\/with x'=x'(x,y) are the new coordinates in terms of the old ones\n \/\/in our case.\n \/\/trapezoid:\n \/\/x' = m0 + (x-m0)*(1+m_TrapezoidFactor*yn)\n \/\/y' = y\n \/\/|D| = (1+m_TrapezoidFactor*yn)|(x,y)\n \/\/\n \/\/distortion:\n \/\/x' = S*(x-x0) + x0\n \/\/y' = S*(y-y0) + y0\n \/\/oBdA x0=y0=0 (volume invariant under translation)\n \/\/S = (1+m_K1*|(x,y)|^2\/m_Scale)\n \/\/dx'\/dx = S+x*dS\/dx\n \/\/dx'\/dy = x*dS\/dy\n \/\/dy'\/dx = y*dS\/dx\n \/\/dy'\/dy = S+y*dS\/dx\n \/\/maxima:\n \/\/S(x,y):= (1+K1 *(x**2+y**2));\n \/\/dS\/dx = 2xK1\n \/\/dS\/dy = 2yK1\n \/\/xd(x,y):=S(x,y)*x;\n \/\/yd(x,y):=S(x,y)*y;\n \/\/\n \/\/diff(xd(x,y),x)*diff(yd(x,y),y)-diff(xd(x,y),y)*diff(yd(x,y),x);\n \/\/|D| = S^2 + 2*x*y*dS\/dx*dS\/dy = S^2 + 16 x^2*y^2 K1^2\n \/\/|D| = (...)|(xt,yt) where xt,yt are the coords after trapezoid trafo \n double yn = (pt.y - m_Center.y)\/m_Scale;\n DPoint pt2 = trapezoid(pt);\n return (1+m_TrapezoidFactor*yn); \/\/ FIXME\n }\n \n}\ninverse transforms finally correct#include \"CoordTransformer.h\"\n#include \"..\/graphics\/Rect.h\"\n#include \"..\/graphics\/Point.h\"\n#include \n#include \"math.h\"\n#define sqrt3 sqrt(3.)\n\nnamespace avg{\nCoordTransformer::CoordTransformer(IntRect srcRect, double K1, double T, double RescaleFactor)\n :m_K1(K1),\n m_TrapezoidFactor(T),\n m_RescaleFactor(RescaleFactor)\n{\n m_Center = DPoint((srcRect.tl.x+srcRect.br.x-1)\/2., (srcRect.tl.y+srcRect.br.y-1)\/2.);\n \/\/normalize to center-edge distance\n m_Scale = sqrt( pow(m_Center.x - srcRect.Width(),2) + pow(m_Center.y - srcRect.Height(),2) );\n m_TrapezoidScale = srcRect.Height()\/2;\n\n}\n CoordTransformer::~CoordTransformer(){};\n DPoint CoordTransformer::inv_distortion(const DPoint &pt){\n if (fabs(m_K1)<1e-10){\n return DPoint(pt);\n }\n DPoint pt_norm = (pt - m_Center)\/m_Scale;\n double r_d = sqrt(pt_norm.x*pt_norm.x + pt_norm.y*pt_norm.y);\n double sub1;\n if (m_K1>0){\n sub1 =pow(sqrt((27*r_d*r_d*m_K1 + 4)\/m_K1)\/(6*sqrt(3)*m_K1) +\n r_d\/(2*m_K1), 1.\/3.); \n }else{\n sub1 =pow(sqrt((27*r_d*r_d*m_K1 - 4)\/m_K1)\/(6*sqrt(3)*m_K1) -\n r_d\/(2*m_K1), 1.\/3.); \n }\n double oldr = (sub1 - 1.\/(3*m_K1*sub1));\n double inv_S = m_RescaleFactor*oldr\/r_d;\n return (pt_norm*inv_S)*m_Scale + m_Center;\n }\n DPoint CoordTransformer::distortion(const DPoint &pt){\n DPoint pt_norm = (pt - m_Center)\/m_Scale;\n double r_d_squared = pt_norm.x*pt_norm.x + pt_norm.y*pt_norm.y;\n double S = (1 + m_K1*r_d_squared)\/m_RescaleFactor;\n return pt_norm*S*m_Scale + m_Center;\n }\n DPoint CoordTransformer::inv_trapezoid(const DPoint &pt){\n \/\/stretch x coord\n double yn = (pt.y - m_Center.y)\/m_TrapezoidScale;\n return DPoint( \n (pt.x + m_Center.x * yn*m_TrapezoidFactor)\/(1+yn*m_TrapezoidFactor),\n pt.y);\n }\n DPoint CoordTransformer::trapezoid(const DPoint &pt){\n \/\/stretch x coord\n double yn = (pt.y - m_Center.y)\/m_TrapezoidScale;\n return DPoint( \n \/\/m_Center.x + ( pt.x - m_Center.x) * (1 + m_TrapezoidFactor * yn), \n pt.x + yn*m_TrapezoidFactor * (pt.x - m_Center.x),\n pt.y);\n }\n DPoint CoordTransformer::inverse_transform_point(const DPoint &pt){\n return inv_trapezoid(inv_distortion(pt));\n }\n DPoint CoordTransformer::transform_point(const DPoint &pt){\n return distortion(trapezoid(pt));\n }\n double CoordTransformer::getPixelSize(const DPoint &pt){\n \/\/volume dxdy transforms as |D|dx'dy' where |D| is the functional determinant\n \/\/det { { dx'\/dx, dx'\/dy}, {dy'\/dx,dy'\/dy}}\n \/\/|D| = dx'\/dx * dy'\/dy - dx'\/dy * dy'\/dx\n \/\/\n \/\/with x'=x'(x,y) are the new coordinates in terms of the old ones\n \/\/in our case.\n \/\/trapezoid:\n \/\/x' = m0 + (x-m0)*(1+m_TrapezoidFactor*yn)\n \/\/y' = y\n \/\/|D| = (1+m_TrapezoidFactor*yn)|(x,y)\n \/\/\n \/\/distortion:\n \/\/x' = S*(x-x0) + x0\n \/\/y' = S*(y-y0) + y0\n \/\/oBdA x0=y0=0 (volume invariant under translation)\n \/\/S = (1+m_K1*|(x,y)|^2\/m_Scale)\n \/\/dx'\/dx = S+x*dS\/dx\n \/\/dx'\/dy = x*dS\/dy\n \/\/dy'\/dx = y*dS\/dx\n \/\/dy'\/dy = S+y*dS\/dx\n \/\/maxima:\n \/\/S(x,y):= (1+K1 *(x**2+y**2));\n \/\/dS\/dx = 2xK1\n \/\/dS\/dy = 2yK1\n \/\/xd(x,y):=S(x,y)*x;\n \/\/yd(x,y):=S(x,y)*y;\n \/\/\n \/\/diff(xd(x,y),x)*diff(yd(x,y),y)-diff(xd(x,y),y)*diff(yd(x,y),x);\n \/\/|D| = S^2 + 2*x*y*dS\/dx*dS\/dy = S^2 + 16 x^2*y^2 K1^2\n \/\/|D| = (...)|(xt,yt) where xt,yt are the coords after trapezoid trafo \n double yn = (pt.y - m_Center.y)\/m_Scale;\n DPoint pt2 = trapezoid(pt);\n return (1+m_TrapezoidFactor*yn); \/\/ FIXME\n }\n \n}\n<|endoftext|>"} {"text":"#include \"line_plot.hpp\"\n#include \"selector.hpp\"\n#include \"..\/app\/data_source.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace datavis {\n\nLinePlot::LinePlot(QObject * parent):\n Plot(parent)\n{}\n\nvoid LinePlot::setDataSource(DataSource * source)\n{\n m_data_source = source;\n\n if (!source || source->data()->size().empty())\n {\n m_dim = -1;\n m_selector_dim = -1;\n m_start = 0;\n m_end = 0;\n }\n else\n {\n auto size = source->data()->size();\n\n if (size.size() > 1)\n {\n m_selector_dim = 0;\n m_dim = 1;\n }\n else\n {\n m_selector_dim = -1;\n m_dim = 0;\n }\n\n m_start = 0;\n m_end = size[m_dim];\n }\n\n findEntireValueRange();\n\n update_selected_region();\n\n emit sourceChanged();\n emit dimensionChanged();\n emit selectorDimChanged();\n emit xRangeChanged();\n emit yRangeChanged();\n emit selectorRangeChanged();\n emit contentChanged();\n}\n\nvoid LinePlot::setSelector(Selector * selector)\n{\n if (m_selector)\n {\n disconnect(m_selector, 0, this, 0);\n }\n\n m_selector = selector;\n\n if (m_selector)\n {\n connect(m_selector, &Selector::valueChanged,\n this, &LinePlot::onSelectorValueChanged);\n }\n\n update_selected_region();\n\n \/\/emit yRangeChanged();\n emit contentChanged();\n}\n\nvoid LinePlot::setDimension(int dim)\n{\n if (!m_data_source)\n return;\n\n auto size = m_data_source->data()->size();\n\n if (dim < 0 || dim >= size.size())\n {\n cerr << \"Invalid dimension: \" << dim << endl;\n return;\n }\n\n if (m_selector_dim == dim)\n m_selector_dim = -1;\n\n m_dim = dim;\n m_start = 0;\n m_end = size[dim];\n\n update_selected_region();\n\n emit dimensionChanged();\n emit selectorDimChanged();\n emit xRangeChanged();\n \/\/emit yRangeChanged();\n emit selectorRangeChanged();\n emit contentChanged();\n}\n\nint LinePlot::selectorDim()\n{\n return m_selector_dim;\n}\n\nvoid LinePlot::setSelectorDim(int new_dim)\n{\n if (!m_data_source)\n {\n cerr << \"No data.\" << endl;\n return;\n }\n\n auto n_data_dim = m_data_source->data()->size().size();\n\n if (new_dim < 0 || new_dim >= n_data_dim)\n {\n cerr << \"Invalid dimension: \" << new_dim << endl;\n return;\n }\n\n if (new_dim == m_dim)\n {\n m_dim = -1;\n }\n\n m_selector_dim = new_dim;\n\n emit dimensionChanged();\n emit selectorDimChanged();\n emit xRangeChanged();\n \/\/emit yRangeChanged();\n emit selectorRangeChanged();\n emit contentChanged();\n}\n\nvoid LinePlot::setRange(int start, int end)\n{\n if (!m_data_source)\n return;\n\n auto size = m_data_source->data()->size();\n\n if (size.empty())\n return;\n\n if (m_dim < 0 || m_dim >= size.size())\n {\n cerr << \"Unexpected: current dimension is invalid.\" << endl;\n return;\n }\n\n if (end < start)\n {\n cerr << \"Warning: negative range.\" << endl;\n return;\n }\n\n if (start < 0 || start + end >= size[m_dim])\n {\n cerr << \"Warning: selected range out of array bounds.\" << endl;\n return;\n }\n\n m_start = start;\n m_end = end;\n\n update_selected_region();\n\n emit xRangeChanged();\n \/\/emit yRangeChanged();\n emit contentChanged();\n}\n\nvoid LinePlot::setColor(const QColor & color)\n{\n m_color = color;\n\n emit colorChanged();\n emit contentChanged();\n}\n\nvoid LinePlot::onSelectorValueChanged()\n{\n update_selected_region();\n\n \/\/emit yRangeChanged();\n emit contentChanged();\n}\n\n\nvoid LinePlot::findEntireValueRange()\n{\n if (!m_data_source)\n m_value_range = Range(0,0);\n\n auto region = get_all(*m_data_source->data());\n\n auto min_it = std::min_element(region.begin(), region.end());\n auto max_it = std::max_element(region.begin(), region.end());\n\n m_value_range.min = min_it.value();\n m_value_range.max = max_it.value();\n}\n\nvoid LinePlot::update_selected_region()\n{\n if (!m_data_source)\n {\n m_data_region = data_region_type();\n return;\n }\n\n auto data_size = m_data_source->data()->size();\n auto n_dim = data_size.size();\n vector offset(n_dim, 0);\n vector size(n_dim, 1);\n\n if (m_selector_dim >= 0 && m_selector)\n {\n assert(m_selector_dim < n_dim);\n int value = m_selector->value();\n \/\/qDebug() << \"Selector value:\" << value;\n \/\/qDebug() << \"Data size: \" << data_size[m_selector_dim];\n if (value >= 0 && value < data_size[m_selector_dim])\n {\n offset[m_selector_dim] = value;\n size[m_selector_dim] = 1;\n }\n else\n {\n m_data_region = data_region_type();\n return;\n }\n }\n\n offset[m_dim] = m_start;\n size[m_dim] = m_end - m_start;\n\n m_data_region = get_region(*m_data_source->data(), offset, size);\n}\n\nPlot::Range LinePlot::xRange()\n{\n if (!m_data_region.is_valid())\n {\n return Range();\n }\n\n return Range { double(m_start), double(m_end) };\n}\n\nPlot::Range LinePlot::yRange()\n{\n return m_value_range;\n#if 0\n if (!m_data_region.is_valid())\n {\n return Range();\n }\n\n auto min_it = std::min_element(m_data_region.begin(), m_data_region.end());\n auto max_it = std::max_element(m_data_region.begin(), m_data_region.end());\n double min_value = min_it.value();\n double max_value = max_it.value();\n\n return Range { min_value, max_value };\n#endif\n}\n\nPlot::Range LinePlot::selectorRange()\n{\n if (!m_data_source)\n return Range();\n\n if (m_selector_dim < 0)\n return Range();\n\n auto data_size = m_data_source->data()->size();\n\n assert(m_selector_dim >= 0 && m_selector_dim < data_size.size());\n\n return Range { double(0), double(data_size[m_selector_dim] - 1) };\n}\n\nvoid LinePlot::plot(QPainter * painter, const QTransform & transform)\n{\n if (!m_data_region.is_valid())\n return;\n\n painter->save();\n\n painter->setPen(m_color);\n painter->setBrush(Qt::NoBrush);\n painter->setRenderHint(QPainter::Antialiasing, true);\n\n QPainterPath path;\n bool first = true;\n for (auto & element : m_data_region)\n {\n int loc = element.location()[m_dim];\n double value = element.value();\n if (first)\n path.moveTo(loc, value);\n else\n path.lineTo(loc, value);\n first = false;\n }\n painter->drawPath(path * transform);\n\n painter->restore();\n}\n\n}\nLine plot: fix selecting dimensions#include \"line_plot.hpp\"\n#include \"selector.hpp\"\n#include \"..\/app\/data_source.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace datavis {\n\nLinePlot::LinePlot(QObject * parent):\n Plot(parent)\n{}\n\nvoid LinePlot::setDataSource(DataSource * source)\n{\n m_data_source = source;\n\n if (!source || source->data()->size().empty())\n {\n m_dim = -1;\n m_selector_dim = -1;\n m_start = 0;\n m_end = 0;\n }\n else\n {\n auto size = source->data()->size();\n\n if (size.size() > 1)\n {\n m_selector_dim = 0;\n m_dim = 1;\n }\n else\n {\n m_selector_dim = -1;\n m_dim = 0;\n }\n\n m_start = 0;\n m_end = size[m_dim];\n }\n\n findEntireValueRange();\n\n update_selected_region();\n\n emit sourceChanged();\n emit dimensionChanged();\n emit selectorDimChanged();\n emit xRangeChanged();\n emit yRangeChanged();\n emit selectorRangeChanged();\n emit contentChanged();\n}\n\nvoid LinePlot::setSelector(Selector * selector)\n{\n if (m_selector)\n {\n disconnect(m_selector, 0, this, 0);\n }\n\n m_selector = selector;\n\n if (m_selector)\n {\n connect(m_selector, &Selector::valueChanged,\n this, &LinePlot::onSelectorValueChanged);\n }\n\n update_selected_region();\n\n \/\/emit yRangeChanged();\n emit contentChanged();\n}\n\nvoid LinePlot::setDimension(int dim)\n{\n if (!m_data_source)\n return;\n\n auto size = m_data_source->data()->size();\n\n if (dim < 0 || dim >= size.size())\n dim = -1;\n\n if (m_selector_dim == dim)\n m_selector_dim = -1;\n\n m_dim = dim;\n\n if (dim >= 0)\n {\n m_start = 0;\n m_end = size[dim];\n }\n else\n {\n m_start = 0;\n m_end = 0;\n }\n\n update_selected_region();\n\n emit dimensionChanged();\n emit selectorDimChanged();\n emit xRangeChanged();\n \/\/emit yRangeChanged();\n emit selectorRangeChanged();\n emit contentChanged();\n}\n\nint LinePlot::selectorDim()\n{\n return m_selector_dim;\n}\n\nvoid LinePlot::setSelectorDim(int new_dim)\n{\n if (!m_data_source)\n {\n cerr << \"No data.\" << endl;\n return;\n }\n\n auto n_data_dim = m_data_source->data()->size().size();\n\n if (new_dim == m_dim)\n {\n m_dim = -1;\n }\n\n if (new_dim < 0 || new_dim >= n_data_dim)\n new_dim = -1;\n\n m_selector_dim = new_dim;\n\n update_selected_region();\n\n emit dimensionChanged();\n emit selectorDimChanged();\n emit xRangeChanged();\n \/\/emit yRangeChanged();\n emit selectorRangeChanged();\n emit contentChanged();\n}\n\nvoid LinePlot::setRange(int start, int end)\n{\n if (!m_data_source)\n return;\n\n auto size = m_data_source->data()->size();\n\n if (size.empty())\n return;\n\n if (m_dim < 0 || m_dim >= size.size())\n {\n cerr << \"Unexpected: current dimension is invalid.\" << endl;\n return;\n }\n\n if (end < start)\n {\n cerr << \"Warning: negative range.\" << endl;\n return;\n }\n\n if (start < 0 || start + end >= size[m_dim])\n {\n cerr << \"Warning: selected range out of array bounds.\" << endl;\n return;\n }\n\n m_start = start;\n m_end = end;\n\n update_selected_region();\n\n emit xRangeChanged();\n \/\/emit yRangeChanged();\n emit contentChanged();\n}\n\nvoid LinePlot::setColor(const QColor & color)\n{\n m_color = color;\n\n emit colorChanged();\n emit contentChanged();\n}\n\nvoid LinePlot::onSelectorValueChanged()\n{\n update_selected_region();\n\n \/\/emit yRangeChanged();\n emit contentChanged();\n}\n\n\nvoid LinePlot::findEntireValueRange()\n{\n if (!m_data_source)\n m_value_range = Range(0,0);\n\n auto region = get_all(*m_data_source->data());\n\n auto min_it = std::min_element(region.begin(), region.end());\n auto max_it = std::max_element(region.begin(), region.end());\n\n m_value_range.min = min_it.value();\n m_value_range.max = max_it.value();\n}\n\nvoid LinePlot::update_selected_region()\n{\n if (!m_data_source)\n {\n m_data_region = data_region_type();\n return;\n }\n\n if (m_dim < 0)\n {\n m_data_region = data_region_type();\n return;\n }\n\n auto data_size = m_data_source->data()->size();\n auto n_dim = data_size.size();\n vector offset(n_dim, 0);\n vector size(n_dim, 1);\n\n if (m_selector_dim >= 0 && m_selector)\n {\n assert(m_selector_dim < n_dim);\n int value = m_selector->value();\n \/\/qDebug() << \"Selector value:\" << value;\n \/\/qDebug() << \"Data size: \" << data_size[m_selector_dim];\n if (value >= 0 && value < data_size[m_selector_dim])\n {\n offset[m_selector_dim] = value;\n size[m_selector_dim] = 1;\n }\n else\n {\n m_data_region = data_region_type();\n return;\n }\n }\n\n offset[m_dim] = m_start;\n size[m_dim] = m_end - m_start;\n\n m_data_region = get_region(*m_data_source->data(), offset, size);\n}\n\nPlot::Range LinePlot::xRange()\n{\n if (!m_data_region.is_valid())\n {\n return Range();\n }\n\n return Range { double(m_start), double(m_end) };\n}\n\nPlot::Range LinePlot::yRange()\n{\n return m_value_range;\n#if 0\n if (!m_data_region.is_valid())\n {\n return Range();\n }\n\n auto min_it = std::min_element(m_data_region.begin(), m_data_region.end());\n auto max_it = std::max_element(m_data_region.begin(), m_data_region.end());\n double min_value = min_it.value();\n double max_value = max_it.value();\n\n return Range { min_value, max_value };\n#endif\n}\n\nPlot::Range LinePlot::selectorRange()\n{\n if (!m_data_source)\n return Range();\n\n if (m_selector_dim < 0)\n return Range();\n\n auto data_size = m_data_source->data()->size();\n\n assert(m_selector_dim >= 0 && m_selector_dim < data_size.size());\n\n return Range { double(0), double(data_size[m_selector_dim] - 1) };\n}\n\nvoid LinePlot::plot(QPainter * painter, const QTransform & transform)\n{\n if (!m_data_region.is_valid())\n return;\n\n painter->save();\n\n painter->setPen(m_color);\n painter->setBrush(Qt::NoBrush);\n painter->setRenderHint(QPainter::Antialiasing, true);\n\n QPainterPath path;\n bool first = true;\n for (auto & element : m_data_region)\n {\n int loc = element.location()[m_dim];\n double value = element.value();\n if (first)\n path.moveTo(loc, value);\n else\n path.lineTo(loc, value);\n first = false;\n }\n painter->drawPath(path * transform);\n\n painter->restore();\n}\n\n}\n<|endoftext|>"} {"text":"\/\/ @(#) $Id$\n\n\/**************************************************************************\n * This file is property of and copyright by the ALICE HLT Project * \n * ALICE Experiment at CERN, All rights reserved. *\n * *\n * Primary Authors: Matthias Richter *\n * for The ALICE HLT Project. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/** @file AliHLTAgentUtil.cxx\n @author Matthias Richter\n @date \n @brief Agent of the libAliHLTUtil library\n*\/\n\n#include \n#include \"AliHLTAgentUtil.h\"\n#include \"AliHLTConfiguration.h\"\n#include \"AliHLTOUTHandlerChain.h\"\n\n\/\/ header files of library components\n#include \"AliHLTDataGenerator.h\"\n#include \"AliHLTRawReaderPublisherComponent.h\"\n#include \"AliHLTLoaderPublisherComponent.h\"\n#include \"AliHLTRootFileStreamerComponent.h\"\n#include \"AliHLTRootFileWriterComponent.h\"\n#include \"AliHLTRootFilePublisherComponent.h\"\n\/\/#include \"AliHLTMCGeneratorComponent.h\"\n#include \"AliHLTESDMCEventPublisherComponent.h\"\n#include \"AliHLTFileWriter.h\"\n#include \"AliHLTFilePublisher.h\"\n#include \"AliHLTBlockFilterComponent.h\"\n#include \"AliHLTEsdCollectorComponent.h\"\n#include \"AliHLTOUTPublisherComponent.h\"\n#include \"AliHLTCompStatCollector.h\"\n\n\/** global instance for agent registration *\/\nAliHLTAgentUtil gAliHLTAgentUtil;\n\n\/** ROOT macro for the implementation of ROOT specific class methods *\/\nClassImp(AliHLTAgentUtil)\n\nAliHLTAgentUtil::AliHLTAgentUtil()\n :\n AliHLTModuleAgent(\"Util\"),\n fCompStatDataHandler(NULL)\n{\n \/\/ see header file for class documentation\n \/\/ or\n \/\/ refer to README to build package\n \/\/ or\n \/\/ visit http:\/\/web.ift.uib.no\/~kjeks\/doc\/alice-hlt\n}\n\nAliHLTAgentUtil::~AliHLTAgentUtil()\n{\n \/\/ see header file for class documentation\n}\n\nint AliHLTAgentUtil::CreateConfigurations(AliHLTConfigurationHandler* handler,\n\t\t\t\t\t AliRawReader* \/*rawReader*\/,\n\t\t\t\t\t AliRunLoader* \/*runloader*\/) const\n{\n \/\/ see header file for class documentation\n if (!handler) return 0;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\n \/\/ a kChain HLTOUT configuration for processing of {'COMPSTAT':'PRIV'} data blocks\n \/\/ produces a TTree object of the component statistics and writes it to disc\n\n \/\/ publisher component\n handler->CreateConfiguration(\"UTIL-hltout-compstat-publisher\", \"AliHLTOUTPublisher\" , NULL, \"\");\n\n \/\/ collector configuration\n handler->CreateConfiguration(\"UTIL-compstat-converter\", \"StatisticsCollector\", \"UTIL-hltout-compstat-publisher\", \"\");\n\n \/\/ writer configuration\n handler->CreateConfiguration(\"UTIL-compstat-writer\", \"ROOTFileWriter\", \"UTIL-compstat-converter\", \"-datafile HLT.statistics.root -concatenate-events -overwrite\");\n\n return 0;\n}\n\nconst char* AliHLTAgentUtil::GetReconstructionChains(AliRawReader* \/*rawReader*\/,\n\t\t\t\t\t\t AliRunLoader* \/*runloader*\/) const\n{\n \/\/ see header file for class documentation\n return NULL;\n}\n\nconst char* AliHLTAgentUtil::GetRequiredComponentLibraries() const\n{\n \/\/ see header file for class documentation\n return NULL;\n}\n\nint AliHLTAgentUtil::RegisterComponents(AliHLTComponentHandler* pHandler) const\n{\n \/\/ see header file for class documentation\n assert(pHandler);\n if (!pHandler) return -EINVAL;\n pHandler->AddComponent(new AliHLTDataGenerator);\n pHandler->AddComponent(new AliHLTRawReaderPublisherComponent);\n pHandler->AddComponent(new AliHLTLoaderPublisherComponent);\n pHandler->AddComponent(new AliHLTRootFileStreamerComponent);\n pHandler->AddComponent(new AliHLTRootFileWriterComponent);\n pHandler->AddComponent(new AliHLTRootFilePublisherComponent);\n \/\/ pHandler->AddComponent(new AliHLTMCGeneratorComponent);\n pHandler->AddComponent(new AliHLTESDMCEventPublisherComponent);\n pHandler->AddComponent(new AliHLTFileWriter);\n pHandler->AddComponent(new AliHLTFilePublisher);\n pHandler->AddComponent(new AliHLTBlockFilterComponent);\n pHandler->AddComponent(new AliHLTEsdCollectorComponent);\n pHandler->AddComponent(new AliHLTOUTPublisherComponent);\n pHandler->AddComponent(new AliHLTCompStatCollector);\n return 0;\n}\n\nint AliHLTAgentUtil::GetHandlerDescription(AliHLTComponentDataType dt,\n\t\t\t\t\t AliHLTUInt32_t \/*spec*\/,\n\t\t\t\t\t AliHLTOUTHandlerDesc& desc) const\n{\n \/\/ see header file for class documentation\n\n \/\/ handler for the component statistics data blocks {'COMPSTAT':'PRIV'}\n if (dt==kAliHLTDataTypeComponentStatistics ||\n dt==kAliHLTDataTypeComponentTable) {\n desc=AliHLTOUTHandlerDesc(kChain, dt, GetModuleId());\n return 1;\n }\n\n return 0;\n}\n\nAliHLTOUTHandler* AliHLTAgentUtil::GetOutputHandler(AliHLTComponentDataType dt,\n\t\t\t\t\t\t AliHLTUInt32_t \/*spec*\/)\n{\n \/\/ see header file for class documentation\n\n \/\/ handler for the component statistics data blocks {'COMPSTAT':'PRIV'}\n if (dt==kAliHLTDataTypeComponentStatistics ||\n dt==kAliHLTDataTypeComponentTable) {\n if (fCompStatDataHandler==NULL)\n fCompStatDataHandler=new AliHLTOUTHandlerChain(\"chains=UTIL-compstat-writer\");\n return fCompStatDataHandler;\n }\n\n return NULL;\n}\n\nint AliHLTAgentUtil::DeleteOutputHandler(AliHLTOUTHandler* pInstance)\n{\n \/\/ see header file for class documentation\n if (pInstance==NULL) return -EINVAL;\n\n if (pInstance==fCompStatDataHandler) {\n delete fCompStatDataHandler;\n fCompStatDataHandler=NULL;\n }\n return 0;\n}\ndisable HLTOUT handler for component statistics due to bug https:\/\/savannah.cern.ch\/bugs\/?51359\/\/ @(#) $Id$\n\n\/**************************************************************************\n * This file is property of and copyright by the ALICE HLT Project * \n * ALICE Experiment at CERN, All rights reserved. *\n * *\n * Primary Authors: Matthias Richter *\n * for The ALICE HLT Project. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/** @file AliHLTAgentUtil.cxx\n @author Matthias Richter\n @date \n @brief Agent of the libAliHLTUtil library\n*\/\n\n#include \n#include \"AliHLTAgentUtil.h\"\n#include \"AliHLTConfiguration.h\"\n#include \"AliHLTOUTHandlerChain.h\"\n\n\/\/ header files of library components\n#include \"AliHLTDataGenerator.h\"\n#include \"AliHLTRawReaderPublisherComponent.h\"\n#include \"AliHLTLoaderPublisherComponent.h\"\n#include \"AliHLTRootFileStreamerComponent.h\"\n#include \"AliHLTRootFileWriterComponent.h\"\n#include \"AliHLTRootFilePublisherComponent.h\"\n\/\/#include \"AliHLTMCGeneratorComponent.h\"\n#include \"AliHLTESDMCEventPublisherComponent.h\"\n#include \"AliHLTFileWriter.h\"\n#include \"AliHLTFilePublisher.h\"\n#include \"AliHLTBlockFilterComponent.h\"\n#include \"AliHLTEsdCollectorComponent.h\"\n#include \"AliHLTOUTPublisherComponent.h\"\n#include \"AliHLTCompStatCollector.h\"\n\n\/** global instance for agent registration *\/\nAliHLTAgentUtil gAliHLTAgentUtil;\n\n\/** ROOT macro for the implementation of ROOT specific class methods *\/\nClassImp(AliHLTAgentUtil)\n\nAliHLTAgentUtil::AliHLTAgentUtil()\n :\n AliHLTModuleAgent(\"Util\"),\n fCompStatDataHandler(NULL)\n{\n \/\/ see header file for class documentation\n \/\/ or\n \/\/ refer to README to build package\n \/\/ or\n \/\/ visit http:\/\/web.ift.uib.no\/~kjeks\/doc\/alice-hlt\n}\n\nAliHLTAgentUtil::~AliHLTAgentUtil()\n{\n \/\/ see header file for class documentation\n}\n\nint AliHLTAgentUtil::CreateConfigurations(AliHLTConfigurationHandler* handler,\n\t\t\t\t\t AliRawReader* \/*rawReader*\/,\n\t\t\t\t\t AliRunLoader* \/*runloader*\/) const\n{\n \/\/ see header file for class documentation\n if (!handler) return 0;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\n \/\/ a kChain HLTOUT configuration for processing of {'COMPSTAT':'PRIV'} data blocks\n \/\/ produces a TTree object of the component statistics and writes it to disc\n\n \/\/ publisher component\n handler->CreateConfiguration(\"UTIL-hltout-compstat-publisher\", \"AliHLTOUTPublisher\" , NULL, \"\");\n\n \/\/ collector configuration\n handler->CreateConfiguration(\"UTIL-compstat-converter\", \"StatisticsCollector\", \"UTIL-hltout-compstat-publisher\", \"\");\n\n \/\/ writer configuration\n handler->CreateConfiguration(\"UTIL-compstat-writer\", \"ROOTFileWriter\", \"UTIL-compstat-converter\", \"-datafile HLT.statistics.root -concatenate-events -overwrite\");\n\n return 0;\n}\n\nconst char* AliHLTAgentUtil::GetReconstructionChains(AliRawReader* \/*rawReader*\/,\n\t\t\t\t\t\t AliRunLoader* \/*runloader*\/) const\n{\n \/\/ see header file for class documentation\n return NULL;\n}\n\nconst char* AliHLTAgentUtil::GetRequiredComponentLibraries() const\n{\n \/\/ see header file for class documentation\n return NULL;\n}\n\nint AliHLTAgentUtil::RegisterComponents(AliHLTComponentHandler* pHandler) const\n{\n \/\/ see header file for class documentation\n assert(pHandler);\n if (!pHandler) return -EINVAL;\n pHandler->AddComponent(new AliHLTDataGenerator);\n pHandler->AddComponent(new AliHLTRawReaderPublisherComponent);\n pHandler->AddComponent(new AliHLTLoaderPublisherComponent);\n pHandler->AddComponent(new AliHLTRootFileStreamerComponent);\n pHandler->AddComponent(new AliHLTRootFileWriterComponent);\n pHandler->AddComponent(new AliHLTRootFilePublisherComponent);\n \/\/ pHandler->AddComponent(new AliHLTMCGeneratorComponent);\n pHandler->AddComponent(new AliHLTESDMCEventPublisherComponent);\n pHandler->AddComponent(new AliHLTFileWriter);\n pHandler->AddComponent(new AliHLTFilePublisher);\n pHandler->AddComponent(new AliHLTBlockFilterComponent);\n pHandler->AddComponent(new AliHLTEsdCollectorComponent);\n pHandler->AddComponent(new AliHLTOUTPublisherComponent);\n pHandler->AddComponent(new AliHLTCompStatCollector);\n return 0;\n}\n\nint AliHLTAgentUtil::GetHandlerDescription(AliHLTComponentDataType dt,\n\t\t\t\t\t AliHLTUInt32_t \/*spec*\/,\n\t\t\t\t\t AliHLTOUTHandlerDesc& desc) const\n{\n \/\/ see header file for class documentation\n return 0;\n\n \/\/ handler for the component statistics data blocks {'COMPSTAT':'PRIV'}\n if (dt==kAliHLTDataTypeComponentStatistics ||\n dt==kAliHLTDataTypeComponentTable) {\n desc=AliHLTOUTHandlerDesc(kChain, dt, GetModuleId());\n return 1;\n }\n\n return 0;\n}\n\nAliHLTOUTHandler* AliHLTAgentUtil::GetOutputHandler(AliHLTComponentDataType dt,\n\t\t\t\t\t\t AliHLTUInt32_t \/*spec*\/)\n{\n \/\/ see header file for class documentation\n return NULL;\n\n \/\/ handler for the component statistics data blocks {'COMPSTAT':'PRIV'}\n if (dt==kAliHLTDataTypeComponentStatistics ||\n dt==kAliHLTDataTypeComponentTable) {\n if (fCompStatDataHandler==NULL)\n fCompStatDataHandler=new AliHLTOUTHandlerChain(\"chains=UTIL-compstat-writer\");\n return fCompStatDataHandler;\n }\n\n return NULL;\n}\n\nint AliHLTAgentUtil::DeleteOutputHandler(AliHLTOUTHandler* pInstance)\n{\n \/\/ see header file for class documentation\n if (pInstance==NULL) return -EINVAL;\n\n if (pInstance==fCompStatDataHandler) {\n delete fCompStatDataHandler;\n fCompStatDataHandler=NULL;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: PackageConstants.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: mtg $ $Date: 2001-07-04 14:56:13 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _PACKAGE_CONSTANTS_HXX_\n#define _PACKAGE_CONSTANTS_HXX_\n\n#ifndef _SAL_TYPES_H_\n#include \n#endif\n\nconst sal_Int32 n_ConstBufferSize = 32768;\nconst sal_Int32 n_ConstNonSpannableBufferSize = 128;\nconst sal_Int32 n_ConstMaxMemoryStreamSize = 20480;\n\n#endif\n#91797# remove unused constant\/*************************************************************************\n *\n * $RCSfile: PackageConstants.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: mtg $ $Date: 2001-09-05 19:31:12 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _PACKAGE_CONSTANTS_HXX_\n#define _PACKAGE_CONSTANTS_HXX_\n\n#ifndef _SAL_TYPES_H_\n#include \n#endif\n\nconst sal_Int32 n_ConstBufferSize = 32768;\nconst sal_Int32 n_ConstMaxMemoryStreamSize = 20480;\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \nusing namespace std;\n\nvoid welcomeBanner();\n\nint main()\n{\n MenuInterface mI;\n mI.banner();\n mI.DisplayMenu();\n\n return 0;\n}\ngit fix#include \n#include \nusing namespace std;\n\nvoid welcomeBanner();\n\nint main()\n{\n MenuInterface mI;\n mI.banner();\n mI.DisplayMenu();\n\n return 0;\n}\n\n\n<|endoftext|>"} {"text":"#pragma once\n\nnamespace principia {\nnamespace base {\n\n#if defined(CDECL)\n# error \"CDECL already defined\"\n#else\n\/\/ Architecture macros from http:\/\/goo.gl\/ZypnO8.\n\/\/ We use cdecl on x86, the calling convention is unambiguous on x86-64.\n# if defined(__i386) || defined(_M_IX86)\n# if defined(_MSC_VER) || defined(__clang__)\n# define CDECL __cdecl\n# elif defined(__GNUC__) || defined(__INTEL_COMPILER)\n# define CDECL __attribute__((cdecl))\n# else\n# error \"Get a real compiler\"\n# endif\n# elif defined(_M_X64) || defined(__x86_64__)\n# define CDECL\n# else\n# error \"Have you tried a Cray-1?\"\n# endif\n#endif\n\n\/\/ DLL-exported functions for interfacing with Platform Invocation Services.\n#if defined(DLLEXPORT)\n# error \"DLLEXPORT already defined\"\n#else\n# if defined(_WIN32) || defined(_WIN64)\n# define DLLEXPORT __declspec(dllexport)\n# else\n# define DLLEXPORT __attribute__((visibility(\"default\")))\n# endif\n#endif\n\n\/\/ A function for use on control paths that don't return a value, typically\n\/\/ because they end with a |LOG(FATAL)|.\n\/\/ MSVC used to require __declspec(noreturn) but doesn't anymore. Odd.\n#ifdef __clang__\n[[noreturn]]\n#endif\ninline void noreturn() { exit(0); }\n\n\/\/ Used to force inlining.\n#ifdef __clang__\n#define FORCE_INLINE [[gnu::always_inline]]\n#elif _MSC_VER\n#define FORCE_INLINE __forceinline\n#endif\n\n} \/\/ namespace base\n} \/\/ namespace principiaAfter egg's review.#pragma once\n\nnamespace principia {\nnamespace base {\n\n#if defined(CDECL)\n# error \"CDECL already defined\"\n#else\n\/\/ Architecture macros from http:\/\/goo.gl\/ZypnO8.\n\/\/ We use cdecl on x86, the calling convention is unambiguous on x86-64.\n# if defined(__i386) || defined(_M_IX86)\n# if defined(_MSC_VER) || defined(__clang__)\n# define CDECL __cdecl\n# elif defined(__GNUC__) || defined(__INTEL_COMPILER)\n# define CDECL __attribute__((cdecl))\n# else\n# error \"Get a real compiler\"\n# endif\n# elif defined(_M_X64) || defined(__x86_64__)\n# define CDECL\n# else\n# error \"Have you tried a Cray-1?\"\n# endif\n#endif\n\n\/\/ DLL-exported functions for interfacing with Platform Invocation Services.\n#if defined(DLLEXPORT)\n# error \"DLLEXPORT already defined\"\n#else\n# if defined(_WIN32) || defined(_WIN64)\n# define DLLEXPORT __declspec(dllexport)\n# else\n# define DLLEXPORT __attribute__((visibility(\"default\")))\n# endif\n#endif\n\n\/\/ A function for use on control paths that don't return a value, typically\n\/\/ because they end with a |LOG(FATAL)|.\n#ifdef __clang__\n[[noreturn]]\n#elif _MSC_VER\n__declspec(noreturn)\n#endif\ninline void noreturn() { exit(0); }\n\n\/\/ Used to force inlining.\n#ifdef __clang__\n#define FORCE_INLINE [[gnu::always_inline]]\n#elif _MSC_VER\n#define FORCE_INLINE __forceinline\n#endif\n\n} \/\/ namespace base\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"#ifndef __Matrix__\n#define __Matrix__\n\n#define GETSIZE(array) (sizeof(array) \/ sizeof(*array))\n\nnamespace base\n{\n namespace matrix\n {\n template < unsigned int Row, unsigned int Col, typename T >\n struct matrix\n {\n public:\n typedef T value_type;\n\n \/\/ since std::vector is absence in avr-gcc, I will use a plain\n \/\/ two-dimensional array to represent a matrix, e.g. mdata[row][col]\n matrix() : mrow(Row), mcol(Col)\n {\n mdata = new value_type*[mrow];\n for(int i = 0; i < mrow; i++)\n {\n mdata[i] = new value_type[mcol];\n }\n }\n\n ~matrix()\n {\n for(int i = 0; i < mrow; i++)\n {\n delete [] mdata[i];\n }\n delete [] mdata;\n }\n\n \/\/ a specific version of traverse. side-effect is everywhere!\n \/\/ traverse :: (a -> b) -> Matrix b\n template< typename UnaryFunction >\n void traverse(UnaryFunction f)\n {\n for(int i = 0; i < mrow; i++)\n {\n for(int j = 0; j < mcol; j++)\n {\n f(mdata[i][j]);\n }\n }\n }\n\n void fillwith(value_type* list)\n {\n auto len = GETSIZE(list);\n \/\/static_assert((mrow * mcol) <= len, \"matrix need more elements\");\n\n unsigned int index = 0;\n traverse([&index, &list](value_type i){ i = list[index++]; });\n }\n\n inline value_type at(unsigned row, unsigned col)\n {\n \/\/static_assert((row <= mrow && col <= mcol), \"out of bound\");\n return mdata[row][col];\n }\n\n private:\n unsigned int mrow;\n unsigned int mcol;\n value_type** mdata;\n };\n\n int main()\n {\n matrix<3,3,float> m;\n float f[9] = {1,2,3,4,5,6,7,8,9};\n m.fillwith(f);\n return 0;\n }\n\n }\n}\n\n#endif\ndaily update#ifndef __Matrix__\n#define __Matrix__\n\n#define GETSIZE(array) (sizeof(array) \/ sizeof(*array))\n\nnamespace base\n{\n namespace matrix\n {\n template < unsigned int Row, unsigned int Col, typename T >\n struct matrix\n {\n public:\n typedef T value_type;\n\n \/\/ since std::vector is absence in avr-gcc, I will use a plain\n \/\/ two-dimensional array to represent a matrix, e.g. mdata[row][col]\n matrix() : mrow(Row), mcol(Col)\n {\n mdata = new value_type*[mrow];\n for(int i = 0; i < mrow; i++)\n {\n mdata[i] = new value_type[mcol];\n }\n }\n\n ~matrix()\n {\n for(int i = 0; i < mrow; i++)\n {\n delete [] mdata[i];\n }\n delete [] mdata;\n }\n\n \/\/ a specific version of traverse. side-effect is everywhere!\n \/\/ traverse :: (a -> b) -> Matrix b\n template< typename UnaryFunction >\n void traverse(UnaryFunction f)\n {\n for(int i = 0; i < mrow; i++)\n {\n for(int j = 0; j < mcol; j++)\n {\n f(mdata[i][j]);\n }\n }\n }\n\n void fillWithList(const value_type* list)\n {\n unsigned index = 0;\n traverse(\n [&](value_type i)\n {\n i = list[index++];\n }\n );\n }\n\n void fillWith(const value_type v)\n {\n traverse(\n [=](value_type i)\n {\n i = v;\n }\n );\n }\n\n template < unsigned row, unsigned col >\n inline value_type at()\n {\n return mdata[row][col];\n }\n\n template < unsigned row, unsigned col >\n inline void set(const value_type v)\n {\n mdata[row][col] = v;\n }\n\n auto operator * (const matrix& m) -> decltype(this)\n {\n for(int i = 0; i < mrow; i++)\n {\n auto reminder = 0;\n for(int j = 0; j < mcol; j++)\n {\n reminder += mdata[i][j] * m.at();\n }\n \/\/ TODO!\n }\n }\n\n private:\n unsigned int mrow;\n unsigned int mcol;\n value_type** mdata;\n };\n }\n}\n\n\/\/ just for test.\nint main()\n{\n using namespace base::matrix;\n matrix<3,3,float> m;\n float f[9] = {1,2,3,4,5,6,7,8,9};\n m.fillWithList(f);\n m.set<2,2>(3);\n int d = m.at<2,3>();\n return 0;\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \"QueryModel.hh\"\n\nQString const QueryModel::MISSING_ATTRIBUTE(\"[missing attribute]\");\n\nQueryModel::HitsCompare::HitsCompare(QueryModel const &parent)\n:\n d_parent(parent)\n{}\n\ninline bool QueryModel::HitsCompare::operator()(int one_idx, int other_idx)\n{\n int oneHits = d_parent.d_results[one_idx].second;\n int twoHits = d_parent.d_results[other_idx].second;\n \n if (oneHits == twoHits)\n return d_parent.d_results[one_idx].first <\n d_parent.d_results[other_idx].first;\n else\n return oneHits > twoHits;\n}\n\nQueryModel::QueryModel(CorpusPtr corpus, QObject *parent)\n:\n QAbstractTableModel(parent),\n d_corpus(corpus),\n d_entryCache(new EntryCache()),\n d_timer(new QTimer)\n{\n connect(this, SIGNAL(queryEntryFound(QString)),\n SLOT(mapperEntryFound(QString)));\n connect(this, SIGNAL(queryFinished(int, int, QString, bool, bool)),\n SLOT(finalizeQuery(int, int, QString, bool, bool)));\n\n \/\/ Timer for progress updates.\n connect(d_timer.data(), SIGNAL(timeout()),\n SLOT(updateProgress()));\n connect(this, SIGNAL(queryStopped(int, int)),\n SLOT(stopProgress()));\n connect(this, SIGNAL(queryFinished(int, int, QString, bool, bool)),\n SLOT(stopProgress()));\n connect(this, SIGNAL(queryFailed(QString)),\n SLOT(stopProgress()));\n}\n\nQueryModel::~QueryModel()\n{\n cancelQuery();\n}\n\nQString QueryModel::asXML() const\n{\n int rows = rowCount(QModelIndex());\n\n \/\/ TODO: Remove selected attribute from the filter...\n\n QStringList outList;\n outList.append(\"\");\n outList.append(\"\");\n outList.append(QString(\"%1<\/corpus>\")\n .arg(QString::fromUtf8(d_corpus->name().c_str())));\n outList.append(QString(\"%1<\/filter>\")\n .arg(d_query));\n outList.append(QString(\"%1<\/attribute>\")\n .arg(d_attribute));\n outList.append(QString(\"%1<\/variants>\")\n .arg(rows));\n outList.append(QString(\"%1<\/hits>\")\n .arg(totalHits()));\n QString date(QDateTime::currentDateTime().toLocalTime().toString());\n outList.append(QString(\"%1<\/date>\")\n .arg(date));\n outList.append(\"<\/statisticsinfo>\");\n\n for (int i = 0; i < rows; ++i) {\n outList.append(\"\");\n outList.append(QString(\"%1<\/value>\")\n .arg(Qt::escape(data(index(i, 0)).toString())));\n outList.append(QString(\"%1<\/frequency>\")\n .arg(data(index(i, 1)).toString()));\n outList.append(QString(\"%1<\/percentage>\")\n .arg(data(index(i, 2)).toDouble() * 100.0, 0, 'f', 1));\n outList.append(\"<\/statistic>\");\n }\n\n outList.append(\"<\/statistics>\");\n\n return outList.join(\"\\n\");\n}\n\nint QueryModel::columnCount(QModelIndex const &index) const\n{\n return 3;\n}\n\nint QueryModel::rowCount(QModelIndex const &index) const\n{\n return d_results.size();\n}\n\nQVariant QueryModel::data(QModelIndex const &index, int role) const\n{\n if (!index.isValid()\n || index.row() >= d_results.size()\n || index.row() < 0\n || index.column() > 2\n || index.column() < 0)\n return QVariant();\n\n switch (role)\n {\n case Qt::UserRole:\n case Qt::DisplayRole:\n switch (index.column())\n {\n case 0:\n \/\/ map positions of the hits index to the positions in d_results\n return d_results[d_hitsIndex[index.row()]].first;\n case 1:\n return d_results[d_hitsIndex[index.row()]].second;\n case 2:\n return static_cast(d_results[d_hitsIndex[index.row()]].second)\n \/ static_cast(d_totalHits);\n default:\n return QVariant();\n }\n\n case Qt::TextAlignmentRole:\n switch (index.column())\n {\n case 1:\n case 2:\n return Qt::AlignRight;\n\n default:\n return Qt::AlignLeft;\n }\n\n default:\n return QVariant();\n }\n}\n\nQString QueryModel::expandQuery(QString const &query,\n QString const &attribute) const\n{\n QString expandedQuery = QString(\"%1\/(@%2\/string(), '%3')[1]\")\n .arg(query)\n .arg(attribute)\n .arg(MISSING_ATTRIBUTE);\n\n \/\/ Not all corpus readers support this styntax.\n if (!validQuery(expandedQuery))\n expandedQuery = QString(\"%1\/@%2\")\n .arg(query)\n .arg(attribute);\n\n return expandedQuery;\n}\n\nvoid QueryModel::updateProgress()\n{\n emit progressChanged(d_entryIterator.progress());\n}\n\nQVariant QueryModel::headerData(int column, Qt::Orientation orientation, int role) const\n{\n if (role != Qt::DisplayRole)\n return QVariant();\n \n if (orientation == Qt::Vertical)\n return QVariant();\n \n switch (column)\n {\n case 0:\n return tr(\"Value\");\n case 1:\n return tr(\"Nodes\");\n case 2:\n return tr(\"Percentage\");\n default:\n return QVariant();\n }\n}\n\nvoid QueryModel::mapperEntryFound(QString entry)\n{\n if (d_cancelled)\n return;\n \n \/\/ find position in d_results using the word index\n int idx = d_valueIndex.value(entry, -1);\n \n if (idx == -1)\n {\n idx = d_results.size();\n d_results.append(QPair(entry, 1));\n d_valueIndex[entry] = idx;\n\n HitsCompare compare(*this);\n \n \/\/ find new position, just above the result with less hits.\n QList::iterator insertPos = qLowerBound(\n d_hitsIndex.begin(), d_hitsIndex.end(), idx, compare);\n \n \/\/ insert at new position\n d_hitsIndex.insert(insertPos, idx);\n \n emit layoutChanged(); \/\/ notify tableview that we have new rows\n }\n else\n {\n HitsCompare compare(*this);\n \n \/\/ Find the current position to remove\n \n \/\/ Binary search: does not work? Why not? :(\n QList::iterator current_pos = qBinaryFind(\n d_hitsIndex.begin(), d_hitsIndex.end(), idx,\n compare);\n \n \/\/ It is already in the words index, it has to be in the hits index as well!\n assert(current_pos != d_hitsIndex.end());\n \n \/\/ remove from current position in the index\n d_hitsIndex.erase(current_pos);\n \n \/\/ Update hits index\n int hits = d_results[idx].second;\n d_results[idx].second = hits + 1;\n \n \/\/ find new position, just above the result with less hits.\n QList::iterator insertPos = qLowerBound(\n d_hitsIndex.begin(), d_hitsIndex.end(), idx, compare);\n \n \/\/ insert at new position\n d_hitsIndex.insert(insertPos, idx);\n }\n \n ++d_totalHits;\n \n emit dataChanged(index(idx, 0), index(idx + 1, 2));\n}\n\nvoid QueryModel::runQuery(QString const &query, QString const &attribute,\n bool yield)\n{\n cancelQuery(); \/\/ just in case\n \n \/\/ clean results cache and notify the table of the loss of rows\n \/\/int size = d_results.size();\n d_results.clear();\n d_hitsIndex.clear();\n emit layoutChanged();\n \n \/\/ clear cache and counter\n d_valueIndex.clear();\n d_totalHits = 0;\n \n d_query = query;\n d_attribute = attribute;\n \n \/\/ Do nothing if we where given a null-pointer\n if (!d_corpus)\n return;\n\n if (!query.isEmpty())\n {\n d_timer->setInterval(100);\n d_timer->setSingleShot(false);\n d_timer->start();\n\n if (yield)\n d_entriesFuture = QtConcurrent::run(this, &QueryModel::getEntriesWithQuery,\n query, attribute, yield);\n else\n d_entriesFuture = QtConcurrent::run(this, &QueryModel::getEntriesWithQuery,\n expandQuery(query, attribute), attribute, yield);\n }\n \/\/ If the query is empty, QueryModel is not supposed to do anything.\n}\n\nbool QueryModel::validQuery(QString const &query) const\n{\n return d_corpus->isValidQuery(alpinocorpus::CorpusReader::XPATH,\n false, query.toUtf8().constData()).isRight();\n}\n\nvoid QueryModel::cancelQuery()\n{\n d_cancelled = true;\n d_entryIterator.interrupt();\n d_entriesFuture.waitForFinished();\n d_timer->stop();\n}\n\nvoid QueryModel::finalizeQuery(int n, int totalEntries, QString query, bool cached, bool yield)\n{\n \/\/ Just to make sure, otherwise data() will go completely crazy\n Q_ASSERT(d_hitsIndex.size() == d_results.size());\n\n layoutChanged(); \/\/ Please, don't do this. Let's copy FilterModel's implementation.\n\n if (!cached)\n {\n d_entryCache->insert(QueryYieldPair(query, yield), new CacheItem(d_totalHits, d_hitsIndex, d_results));\n\n \/\/ this index is no longer needed, as it is only used for constructing d_hitsIndex\n d_valueIndex.clear();\n }\n}\n\n\/\/ run async, because query() starts searching immediately\nvoid QueryModel::getEntriesWithQuery(QString const &query,\n QString const &attribute, bool yield)\n{\n try {\n if (d_entryCache->contains(QueryYieldPair(query, yield)))\n {\n {\n QMutexLocker locker(&d_resultsMutex);\n CacheItem *cachedResult = d_entryCache->object(QueryYieldPair(query, yield));\n d_totalHits = cachedResult->hits;\n d_hitsIndex = cachedResult->index;\n d_results = cachedResult->entries;\n }\n\n emit queryFinished(d_results.size(), d_results.size(), query, true, yield);\n return;\n }\n\n QueryModel::getEntries(\n d_corpus->query(alpinocorpus::CorpusReader::XPATH, query.toUtf8().constData()),\n query.toUtf8().constData(), attribute.toUtf8().constData(), yield);\n } catch (std::exception const &e) {\n qDebug() << \"Error in QueryModel::getEntries: \" << e.what();\n emit queryFailed(e.what());\n }\n}\n\n\/\/ run async\nvoid QueryModel::getEntries(EntryIterator const &i, std::string const &query,\n std::string const &attribute, bool yield)\n{\n if (i.hasProgress())\n emit queryStarted(100);\n else\n emit queryStarted(0);\n \n try {\n d_cancelled = false;\n d_entryIterator = i;\n \n while (!d_cancelled && d_entryIterator.hasNext())\n {\n alpinocorpus::Entry e = d_entryIterator.next(*d_corpus);\n\n if (yield) {\n std::vector sent =\n d_corpus->sentence(e.name, query, attribute);\n\n \/\/ Find all match ids.\n std::set ids;\n foreach (alpinocorpus::LexItem const &lexItem, sent)\n ids.insert(lexItem.matches.begin(), lexItem.matches.end());\n\n foreach (size_t id, ids) {\n std::ostringstream oss;\n bool firstToken = true;\n\n foreach (alpinocorpus::LexItem const &lexItem, sent) {\n if (lexItem.matches.find(id) != lexItem.matches.end()) {\n if (firstToken)\n firstToken = false;\n else\n oss << \" \";\n\n oss << lexItem.word;\n }\n }\n\n std::string result = oss.str();\n emit queryEntryFound(QString::fromUtf8(result.c_str()));\n }\n size_t prevDepth = 0;\n }\n else\n emit queryEntryFound(QString::fromUtf8(e.contents.c_str()));\n }\n \n if (d_cancelled)\n emit queryStopped(d_results.size(), d_results.size());\n else\n emit queryFinished(d_results.size(), d_results.size(), QString::fromUtf8(query.c_str()), false, yield);\n }\n \/\/ Catch d_entryIterator.interrupt()'s shockwaves of terror\n catch (alpinocorpus::IterationInterrupted const &e) {\n emit queryStopped(d_results.size(), d_results.size());\n }\n catch (alpinocorpus::Error const &e) {\n qDebug() << \"Error in QueryModel::getEntries: \" << e.what();\n emit queryFailed(e.what());\n }\n}\n\nvoid QueryModel::stopProgress()\n{\n d_timer->stop();\n}\n\nyield: don't double count multiple occurrences in a tree.#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \"QueryModel.hh\"\n\nQString const QueryModel::MISSING_ATTRIBUTE(\"[missing attribute]\");\n\nQueryModel::HitsCompare::HitsCompare(QueryModel const &parent)\n:\n d_parent(parent)\n{}\n\ninline bool QueryModel::HitsCompare::operator()(int one_idx, int other_idx)\n{\n int oneHits = d_parent.d_results[one_idx].second;\n int twoHits = d_parent.d_results[other_idx].second;\n \n if (oneHits == twoHits)\n return d_parent.d_results[one_idx].first <\n d_parent.d_results[other_idx].first;\n else\n return oneHits > twoHits;\n}\n\nQueryModel::QueryModel(CorpusPtr corpus, QObject *parent)\n:\n QAbstractTableModel(parent),\n d_corpus(corpus),\n d_entryCache(new EntryCache()),\n d_timer(new QTimer)\n{\n connect(this, SIGNAL(queryEntryFound(QString)),\n SLOT(mapperEntryFound(QString)));\n connect(this, SIGNAL(queryFinished(int, int, QString, bool, bool)),\n SLOT(finalizeQuery(int, int, QString, bool, bool)));\n\n \/\/ Timer for progress updates.\n connect(d_timer.data(), SIGNAL(timeout()),\n SLOT(updateProgress()));\n connect(this, SIGNAL(queryStopped(int, int)),\n SLOT(stopProgress()));\n connect(this, SIGNAL(queryFinished(int, int, QString, bool, bool)),\n SLOT(stopProgress()));\n connect(this, SIGNAL(queryFailed(QString)),\n SLOT(stopProgress()));\n}\n\nQueryModel::~QueryModel()\n{\n cancelQuery();\n}\n\nQString QueryModel::asXML() const\n{\n int rows = rowCount(QModelIndex());\n\n \/\/ TODO: Remove selected attribute from the filter...\n\n QStringList outList;\n outList.append(\"\");\n outList.append(\"\");\n outList.append(QString(\"%1<\/corpus>\")\n .arg(QString::fromUtf8(d_corpus->name().c_str())));\n outList.append(QString(\"%1<\/filter>\")\n .arg(d_query));\n outList.append(QString(\"%1<\/attribute>\")\n .arg(d_attribute));\n outList.append(QString(\"%1<\/variants>\")\n .arg(rows));\n outList.append(QString(\"%1<\/hits>\")\n .arg(totalHits()));\n QString date(QDateTime::currentDateTime().toLocalTime().toString());\n outList.append(QString(\"%1<\/date>\")\n .arg(date));\n outList.append(\"<\/statisticsinfo>\");\n\n for (int i = 0; i < rows; ++i) {\n outList.append(\"\");\n outList.append(QString(\"%1<\/value>\")\n .arg(Qt::escape(data(index(i, 0)).toString())));\n outList.append(QString(\"%1<\/frequency>\")\n .arg(data(index(i, 1)).toString()));\n outList.append(QString(\"%1<\/percentage>\")\n .arg(data(index(i, 2)).toDouble() * 100.0, 0, 'f', 1));\n outList.append(\"<\/statistic>\");\n }\n\n outList.append(\"<\/statistics>\");\n\n return outList.join(\"\\n\");\n}\n\nint QueryModel::columnCount(QModelIndex const &index) const\n{\n return 3;\n}\n\nint QueryModel::rowCount(QModelIndex const &index) const\n{\n return d_results.size();\n}\n\nQVariant QueryModel::data(QModelIndex const &index, int role) const\n{\n if (!index.isValid()\n || index.row() >= d_results.size()\n || index.row() < 0\n || index.column() > 2\n || index.column() < 0)\n return QVariant();\n\n switch (role)\n {\n case Qt::UserRole:\n case Qt::DisplayRole:\n switch (index.column())\n {\n case 0:\n \/\/ map positions of the hits index to the positions in d_results\n return d_results[d_hitsIndex[index.row()]].first;\n case 1:\n return d_results[d_hitsIndex[index.row()]].second;\n case 2:\n return static_cast(d_results[d_hitsIndex[index.row()]].second)\n \/ static_cast(d_totalHits);\n default:\n return QVariant();\n }\n\n case Qt::TextAlignmentRole:\n switch (index.column())\n {\n case 1:\n case 2:\n return Qt::AlignRight;\n\n default:\n return Qt::AlignLeft;\n }\n\n default:\n return QVariant();\n }\n}\n\nQString QueryModel::expandQuery(QString const &query,\n QString const &attribute) const\n{\n QString expandedQuery = QString(\"%1\/(@%2\/string(), '%3')[1]\")\n .arg(query)\n .arg(attribute)\n .arg(MISSING_ATTRIBUTE);\n\n \/\/ Not all corpus readers support this styntax.\n if (!validQuery(expandedQuery))\n expandedQuery = QString(\"%1\/@%2\")\n .arg(query)\n .arg(attribute);\n\n return expandedQuery;\n}\n\nvoid QueryModel::updateProgress()\n{\n emit progressChanged(d_entryIterator.progress());\n}\n\nQVariant QueryModel::headerData(int column, Qt::Orientation orientation, int role) const\n{\n if (role != Qt::DisplayRole)\n return QVariant();\n \n if (orientation == Qt::Vertical)\n return QVariant();\n \n switch (column)\n {\n case 0:\n return tr(\"Value\");\n case 1:\n return tr(\"Nodes\");\n case 2:\n return tr(\"Percentage\");\n default:\n return QVariant();\n }\n}\n\nvoid QueryModel::mapperEntryFound(QString entry)\n{\n if (d_cancelled)\n return;\n \n \/\/ find position in d_results using the word index\n int idx = d_valueIndex.value(entry, -1);\n \n if (idx == -1)\n {\n idx = d_results.size();\n d_results.append(QPair(entry, 1));\n d_valueIndex[entry] = idx;\n\n HitsCompare compare(*this);\n \n \/\/ find new position, just above the result with less hits.\n QList::iterator insertPos = qLowerBound(\n d_hitsIndex.begin(), d_hitsIndex.end(), idx, compare);\n \n \/\/ insert at new position\n d_hitsIndex.insert(insertPos, idx);\n \n emit layoutChanged(); \/\/ notify tableview that we have new rows\n }\n else\n {\n HitsCompare compare(*this);\n \n \/\/ Find the current position to remove\n \n \/\/ Binary search: does not work? Why not? :(\n QList::iterator current_pos = qBinaryFind(\n d_hitsIndex.begin(), d_hitsIndex.end(), idx,\n compare);\n \n \/\/ It is already in the words index, it has to be in the hits index as well!\n assert(current_pos != d_hitsIndex.end());\n \n \/\/ remove from current position in the index\n d_hitsIndex.erase(current_pos);\n \n \/\/ Update hits index\n int hits = d_results[idx].second;\n d_results[idx].second = hits + 1;\n \n \/\/ find new position, just above the result with less hits.\n QList::iterator insertPos = qLowerBound(\n d_hitsIndex.begin(), d_hitsIndex.end(), idx, compare);\n \n \/\/ insert at new position\n d_hitsIndex.insert(insertPos, idx);\n }\n \n ++d_totalHits;\n \n emit dataChanged(index(idx, 0), index(idx + 1, 2));\n}\n\nvoid QueryModel::runQuery(QString const &query, QString const &attribute,\n bool yield)\n{\n cancelQuery(); \/\/ just in case\n \n \/\/ clean results cache and notify the table of the loss of rows\n \/\/int size = d_results.size();\n d_results.clear();\n d_hitsIndex.clear();\n emit layoutChanged();\n \n \/\/ clear cache and counter\n d_valueIndex.clear();\n d_totalHits = 0;\n \n d_query = query;\n d_attribute = attribute;\n \n \/\/ Do nothing if we where given a null-pointer\n if (!d_corpus)\n return;\n\n if (!query.isEmpty())\n {\n d_timer->setInterval(100);\n d_timer->setSingleShot(false);\n d_timer->start();\n\n if (yield)\n d_entriesFuture = QtConcurrent::run(this, &QueryModel::getEntriesWithQuery,\n query, attribute, yield);\n else\n d_entriesFuture = QtConcurrent::run(this, &QueryModel::getEntriesWithQuery,\n expandQuery(query, attribute), attribute, yield);\n }\n \/\/ If the query is empty, QueryModel is not supposed to do anything.\n}\n\nbool QueryModel::validQuery(QString const &query) const\n{\n return d_corpus->isValidQuery(alpinocorpus::CorpusReader::XPATH,\n false, query.toUtf8().constData()).isRight();\n}\n\nvoid QueryModel::cancelQuery()\n{\n d_cancelled = true;\n d_entryIterator.interrupt();\n d_entriesFuture.waitForFinished();\n d_timer->stop();\n}\n\nvoid QueryModel::finalizeQuery(int n, int totalEntries, QString query, bool cached, bool yield)\n{\n \/\/ Just to make sure, otherwise data() will go completely crazy\n Q_ASSERT(d_hitsIndex.size() == d_results.size());\n\n layoutChanged(); \/\/ Please, don't do this. Let's copy FilterModel's implementation.\n\n if (!cached)\n {\n d_entryCache->insert(QueryYieldPair(query, yield), new CacheItem(d_totalHits, d_hitsIndex, d_results));\n\n \/\/ this index is no longer needed, as it is only used for constructing d_hitsIndex\n d_valueIndex.clear();\n }\n}\n\n\/\/ run async, because query() starts searching immediately\nvoid QueryModel::getEntriesWithQuery(QString const &query,\n QString const &attribute, bool yield)\n{\n try {\n if (d_entryCache->contains(QueryYieldPair(query, yield)))\n {\n {\n QMutexLocker locker(&d_resultsMutex);\n CacheItem *cachedResult = d_entryCache->object(QueryYieldPair(query, yield));\n d_totalHits = cachedResult->hits;\n d_hitsIndex = cachedResult->index;\n d_results = cachedResult->entries;\n }\n\n emit queryFinished(d_results.size(), d_results.size(), query, true, yield);\n return;\n }\n\n QueryModel::getEntries(\n d_corpus->query(alpinocorpus::CorpusReader::XPATH, query.toUtf8().constData()),\n query.toUtf8().constData(), attribute.toUtf8().constData(), yield);\n } catch (std::exception const &e) {\n qDebug() << \"Error in QueryModel::getEntries: \" << e.what();\n emit queryFailed(e.what());\n }\n}\n\n\/\/ run async\nvoid QueryModel::getEntries(EntryIterator const &i, std::string const &query,\n std::string const &attribute, bool yield)\n{\n if (i.hasProgress())\n emit queryStarted(100);\n else\n emit queryStarted(0);\n \n try {\n d_cancelled = false;\n d_entryIterator = i;\n\n std::set seen;\n \n while (!d_cancelled && d_entryIterator.hasNext())\n {\n alpinocorpus::Entry e = d_entryIterator.next(*d_corpus);\n\n if (yield) {\n \/\/ Check whether we have already processed this tree before.\n if (seen.find(e.name) != seen.end())\n continue;\n seen.insert(e.name);\n\n std::vector sent =\n d_corpus->sentence(e.name, query, attribute);\n\n \/\/ Find all match ids.\n std::set ids;\n foreach (alpinocorpus::LexItem const &lexItem, sent)\n ids.insert(lexItem.matches.begin(), lexItem.matches.end());\n\n foreach (size_t id, ids) {\n std::ostringstream oss;\n bool firstToken = true;\n\n foreach (alpinocorpus::LexItem const &lexItem, sent) {\n if (lexItem.matches.find(id) != lexItem.matches.end()) {\n if (firstToken)\n firstToken = false;\n else\n oss << \" \";\n\n oss << lexItem.word;\n }\n }\n\n std::string result = oss.str();\n emit queryEntryFound(QString::fromUtf8(result.c_str()));\n }\n size_t prevDepth = 0;\n }\n else\n emit queryEntryFound(QString::fromUtf8(e.contents.c_str()));\n }\n \n if (d_cancelled)\n emit queryStopped(d_results.size(), d_results.size());\n else\n emit queryFinished(d_results.size(), d_results.size(), QString::fromUtf8(query.c_str()), false, yield);\n }\n \/\/ Catch d_entryIterator.interrupt()'s shockwaves of terror\n catch (alpinocorpus::IterationInterrupted const &e) {\n emit queryStopped(d_results.size(), d_results.size());\n }\n catch (alpinocorpus::Error const &e) {\n qDebug() << \"Error in QueryModel::getEntries: \" << e.what();\n emit queryFailed(e.what());\n }\n}\n\nvoid QueryModel::stopProgress()\n{\n d_timer->stop();\n}\n\n<|endoftext|>"} {"text":"#include \"helpers.h\"\n\n#include \n\nvoid StartServer(std::string prefix, ::xorg::testing::XServer &server, XOrgConfig &config) {\n std::stringstream conf;\n conf << \"\/tmp\/\" << prefix << \".conf\";\n\n std::stringstream logfile;\n logfile << \"\/tmp\/Xorg-\" << prefix << \".log\";\n\n config.SetPath(conf.str());\n config.WriteConfig();\n server.SetOption(\"-config\", config.GetPath());\n server.SetOption(\"-logfile\", logfile.str());\n server.SetDisplayNumber(133);\n server.Start();\n server.WaitForConnections();\n}\n\nint FindInputDeviceByName(Display *dpy, const std::string &device_name, int *deviceid)\n{\n int ndevices;\n XIDeviceInfo *info;\n\n info = XIQueryDevice(dpy, XIAllDevices, &ndevices);\n\n int found = 0;\n while(ndevices--) {\n if (strcmp(info[ndevices].name, device_name.c_str()) == 0) {\n if (deviceid)\n *deviceid = info[ndevices].deviceid;\n found++;\n }\n }\n\n XIFreeDeviceInfo(info);\n\n return found;\n}\nhelpers: always warn if more than one device with a given name was found#include \"helpers.h\"\n\n#include \n\nvoid StartServer(std::string prefix, ::xorg::testing::XServer &server, XOrgConfig &config) {\n std::stringstream conf;\n conf << \"\/tmp\/\" << prefix << \".conf\";\n\n std::stringstream logfile;\n logfile << \"\/tmp\/Xorg-\" << prefix << \".log\";\n\n config.SetPath(conf.str());\n config.WriteConfig();\n server.SetOption(\"-config\", config.GetPath());\n server.SetOption(\"-logfile\", logfile.str());\n server.SetDisplayNumber(133);\n server.Start();\n server.WaitForConnections();\n}\n\nint FindInputDeviceByName(Display *dpy, const std::string &device_name, int *deviceid)\n{\n int ndevices;\n XIDeviceInfo *info;\n\n info = XIQueryDevice(dpy, XIAllDevices, &ndevices);\n\n int found = 0;\n while(ndevices--) {\n if (strcmp(info[ndevices].name, device_name.c_str()) == 0) {\n if (deviceid)\n *deviceid = info[ndevices].deviceid;\n found++;\n }\n }\n\n if (found > 1) {\n SCOPED_TRACE(\"More than one device named '\" + device_name +\n \"' found.\\nThis may cause some tests to fail.\\n\");\n }\n\n XIFreeDeviceInfo(info);\n\n return found;\n}\n<|endoftext|>"} {"text":"#include \"JPetSigCh.h\"\n#include \n\nClassImp(JPetSigCh);\n\/\/\/ @todo init is not complete\nconst float JPetSigCh::kTimeUnset = std::numeric_limits::infinity();\nvoid JPetSigCh::init()\n{\n SetNameTitle(\"JPetSigCh\", \"Signal Channel Structure\");\n fAmpl = 0;\n fIsSlow = false;\n fIsComplete = false;\n}\n\nJPetSigCh::JPetSigCh(const JPetSigCh& obj)\n{\n init();\n if (this != &obj) {\n fAmpl = obj.fAmpl;\n fIsSlow = obj.fIsSlow;\n fIsComplete = obj.fIsComplete;\n fPM = obj.fPM;\n fTRB = obj.fTRB;\n fScin = obj.fScin;\n fBarrelSlot = obj.fBarrelSlot;\n fChannels = obj.fChannels;\n }\n}\n\nJPetSigCh& JPetSigCh::operator=(JPetSigCh obj)\n{\n my_swap(*this, obj);\n return *this;\n}\n\nJPetSigCh::JPetSigCh(float edge_time, float fall_edge_time)\n{\n init();\n if (fall_edge_time == 0) fIsSlow = true;\n addCh(edge_time, fall_edge_time);\n}\n\nfloat JPetSigCh::getTime(EdgeType type) const {\n assert ((type == kRising) || (type == kFalling));\n if (type == kRising) return fChannels.first;\n if (type == kFalling) { \n if (isSlow()) {\n ERROR(\"This instance of JPetSigCh is of slow type, hence has no falling edge data.\");\n return 0;\n }\n return fChannels.second;\n }\n return 0;\n}\n\ntemplate \nvoid JPetSigCh::set(T** dest, const T& source) throw(std::bad_alloc)\n{\n assert(dest != 0);\n\n if ( &source == 0 && *dest != 0 ) {\n delete *dest;\n *dest = 0;\n return;\n }\n\n if (&source != 0) {\n if (*dest == 0) {\n try {\n *dest = new T;\n } catch (std::bad_alloc& b_a) {\n ERROR(\"Could not allocate memory.\");\n ERROR(b_a.what());\n }\n }\n ** dest = source;\n }\n}\n\nvoid JPetSigCh::addCh(float rise_edge_time, float fall_edge_time)\n{\n fChannels.first = rise_edge_time;\n fChannels.second = fall_edge_time;\n}\n\nRemove todo comment#include \"JPetSigCh.h\"\n#include \n\nClassImp(JPetSigCh);\n\nconst float JPetSigCh::kTimeUnset = std::numeric_limits::infinity();\nvoid JPetSigCh::init()\n{\n SetNameTitle(\"JPetSigCh\", \"Signal Channel Structure\");\n fAmpl = 0;\n fIsSlow = false;\n fIsComplete = false;\n}\n\nJPetSigCh::JPetSigCh(const JPetSigCh& obj)\n{\n init();\n if (this != &obj) {\n fAmpl = obj.fAmpl;\n fIsSlow = obj.fIsSlow;\n fIsComplete = obj.fIsComplete;\n fPM = obj.fPM;\n fTRB = obj.fTRB;\n fScin = obj.fScin;\n fBarrelSlot = obj.fBarrelSlot;\n fChannels = obj.fChannels;\n }\n}\n\nJPetSigCh& JPetSigCh::operator=(JPetSigCh obj)\n{\n my_swap(*this, obj);\n return *this;\n}\n\nJPetSigCh::JPetSigCh(float edge_time, float fall_edge_time)\n{\n init();\n if (fall_edge_time == 0) fIsSlow = true;\n addCh(edge_time, fall_edge_time);\n}\n\nfloat JPetSigCh::getTime(EdgeType type) const {\n assert ((type == kRising) || (type == kFalling));\n if (type == kRising) return fChannels.first;\n if (type == kFalling) { \n if (isSlow()) {\n ERROR(\"This instance of JPetSigCh is of slow type, hence has no falling edge data.\");\n return 0;\n }\n return fChannels.second;\n }\n return 0;\n}\n\ntemplate \nvoid JPetSigCh::set(T** dest, const T& source) throw(std::bad_alloc)\n{\n assert(dest != 0);\n\n if ( &source == 0 && *dest != 0 ) {\n delete *dest;\n *dest = 0;\n return;\n }\n\n if (&source != 0) {\n if (*dest == 0) {\n try {\n *dest = new T;\n } catch (std::bad_alloc& b_a) {\n ERROR(\"Could not allocate memory.\");\n ERROR(b_a.what());\n }\n }\n ** dest = source;\n }\n}\n\nvoid JPetSigCh::addCh(float rise_edge_time, float fall_edge_time)\n{\n fChannels.first = rise_edge_time;\n fChannels.second = fall_edge_time;\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2016 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2016 The Bitcoin Developers\n\/\/ Copyright (c) 2015-2016 Silk Network\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"protocol.h\"\n#include \"util.h\"\n\n#ifndef WIN32\n# include \n#endif\n\nstatic const char* ppszTypeName[] =\n{\n \"ERROR\",\n \"tx\",\n \"block\",\n \"filtered block\",\n \"tx lock request\",\n \"tx lock vote\",\n \"spork\",\n \"sn winner\",\n \"sn scan error\",\n \"sn budget vote\",\n \"sn budget proposal\",\n \"sn budget finalized\",\n \"sn budget finalized vote\",\n \"sn quorum\",\n \"sn announce\",\n \"sn ping\",\n \"sstx\"\n};\n\nCMessageHeader::CMessageHeader()\n{\n memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);\n memset(pchCommand, 0, sizeof(pchCommand));\n pchCommand[1] = 1;\n nMessageSize = -1;\n nChecksum = 0;\n}\n\nCMessageHeader::CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)\n{\n memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);\n memset(pchCommand, 0, sizeof(pchCommand));\n strncpy(pchCommand, pszCommand, COMMAND_SIZE);\n nMessageSize = nMessageSizeIn;\n nChecksum = 0;\n}\n\nstd::string CMessageHeader::GetCommand() const\n{\n return std::string(pchCommand, pchCommand + COMMAND_SIZE);\n}\n\nbool CMessageHeader::IsValid() const\n{\n \/\/ Check start string\n if (memcmp(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0)\n return false;\n\n \/\/ Check the command string for errors\n for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)\n {\n if (*p1 == 0)\n {\n \/\/ Must be all zeros after the first zero\n for (; p1 < pchCommand + COMMAND_SIZE; p1++)\n if (*p1 != 0)\n return false;\n }\n else if (*p1 < ' ' || *p1 > 0x7E)\n return false;\n }\n\n \/\/ Message size\n if (nMessageSize > MAX_SIZE)\n {\n LogPrintf(\"CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\\n\", GetCommand(), nMessageSize);\n return false;\n }\n\n return true;\n}\n\n\n\nCAddress::CAddress() : CService()\n{\n Init();\n}\n\nCAddress::CAddress(CService ipIn, uint64_t nServicesIn) : CService(ipIn)\n{\n Init();\n nServices = nServicesIn;\n}\n\nvoid CAddress::Init()\n{\n nServices = NODE_NETWORK;\n nTime = 100000000;\n nLastTry = 0;\n}\n\nCInv::CInv()\n{\n type = 0;\n hash = 0;\n}\n\nCInv::CInv(int typeIn, const uint256& hashIn)\n{\n type = typeIn;\n hash = hashIn;\n}\n\nCInv::CInv(const std::string& strType, const uint256& hashIn)\n{\n unsigned int i;\n for (i = 1; i < ARRAYLEN(ppszTypeName); i++)\n {\n if (strType == ppszTypeName[i])\n {\n type = i;\n break;\n }\n }\n if (i == ARRAYLEN(ppszTypeName))\n LogPrint(\"net\", \"CInv::CInv(string, uint256) : unknown type '%s'\", strType);\n hash = hashIn;\n}\n\nbool operator<(const CInv& a, const CInv& b)\n{\n return (a.type < b.type || (a.type == b.type && a.hash < b.hash));\n}\n\nbool CInv::IsKnownType() const\n{\n return (type >= 1 && type < (int)ARRAYLEN(ppszTypeName));\n}\n\nconst char* CInv::GetCommand() const\n{\n if (!IsKnownType())\n LogPrint(\"net\", \"CInv::GetCommand() : type=%d unknown type\", type);\n return ppszTypeName[type];\n}\n\nstd::string CInv::ToString() const\n{\n return strprintf(\"%s %s\", GetCommand(), hash.ToString());\n}\n\nvoid CInv::print() const\n{\n LogPrintf(\"CInv(%s)\\n\", ToString());\n}\nUpdate protocol.cpp\/\/ Copyright (c) 2009-2016 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2016 The Bitcoin Developers\n\/\/ Copyright (c) 2015-2016 Silk Network\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"protocol.h\"\n#include \"util.h\"\n\n#ifndef WIN32\n# include \n#endif\n\nstatic const char* ppszTypeName[] =\n{\n \"ERROR\",\n \"tx\",\n \"block\",\n \"filtered block\",\n \"tx lock request\",\n \"tx lock vote\",\n \"spork\",\n \"sn winner\",\n \"sn scan error\",\n \"sn budget vote\",\n \"sn budget proposal\",\n \"sn budget finalized\",\n \"sn budget finalized vote\",\n \"sn quorum\",\n \"sn announce\",\n \"sn ping\",\n \"sstx\"\n};\n\nCMessageHeader::CMessageHeader()\n{\n memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);\n memset(pchCommand, 0, sizeof(pchCommand));\n pchCommand[1] = 1;\n nMessageSize = -1;\n nChecksum = 0;\n}\n\nCMessageHeader::CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)\n{\n memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);\n memset(pchCommand, 0, sizeof(pchCommand));\n strncpy(pchCommand, pszCommand, COMMAND_SIZE);\n nMessageSize = nMessageSizeIn;\n nChecksum = 0;\n}\n\nstd::string CMessageHeader::GetCommand() const\n{\n if (pchCommand[COMMAND_SIZE-1] == 0)\n return std::string(pchCommand, pchCommand + strlen(pchCommand));\n else\n return std::string(pchCommand, pchCommand + COMMAND_SIZE);\n}\n\nbool CMessageHeader::IsValid() const\n{\n \/\/ Check start string\n if (memcmp(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0)\n return false;\n\n \/\/ Check the command string for errors\n for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)\n {\n if (*p1 == 0)\n {\n \/\/ Must be all zeros after the first zero\n for (; p1 < pchCommand + COMMAND_SIZE; p1++)\n if (*p1 != 0)\n return false;\n }\n else if (*p1 < ' ' || *p1 > 0x7E)\n return false;\n }\n\n \/\/ Message size\n if (nMessageSize > MAX_SIZE)\n {\n LogPrintf(\"CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\\n\", GetCommand(), nMessageSize);\n return false;\n }\n\n return true;\n}\n\n\n\nCAddress::CAddress() : CService()\n{\n Init();\n}\n\nCAddress::CAddress(CService ipIn, uint64_t nServicesIn) : CService(ipIn)\n{\n Init();\n nServices = nServicesIn;\n}\n\nvoid CAddress::Init()\n{\n nServices = NODE_NETWORK;\n nTime = 100000000;\n nLastTry = 0;\n}\n\nCInv::CInv()\n{\n type = 0;\n hash = 0;\n}\n\nCInv::CInv(int typeIn, const uint256& hashIn)\n{\n type = typeIn;\n hash = hashIn;\n}\n\nCInv::CInv(const std::string& strType, const uint256& hashIn)\n{\n unsigned int i;\n for (i = 1; i < ARRAYLEN(ppszTypeName); i++)\n {\n if (strType == ppszTypeName[i])\n {\n type = i;\n break;\n }\n }\n if (i == ARRAYLEN(ppszTypeName))\n LogPrint(\"net\", \"CInv::CInv(string, uint256) : unknown type '%s'\", strType);\n hash = hashIn;\n}\n\nbool operator<(const CInv& a, const CInv& b)\n{\n return (a.type < b.type || (a.type == b.type && a.hash < b.hash));\n}\n\nbool CInv::IsKnownType() const\n{\n return (type >= 1 && type < (int)ARRAYLEN(ppszTypeName));\n}\n\nconst char* CInv::GetCommand() const\n{\n if (!IsKnownType())\n LogPrint(\"net\", \"CInv::GetCommand() : type=%d unknown type\", type);\n return ppszTypeName[type];\n}\n\nstd::string CInv::ToString() const\n{\n return strprintf(\"%s %s\", GetCommand(), hash.ToString());\n}\n\nvoid CInv::print() const\n{\n LogPrintf(\"CInv(%s)\\n\", ToString());\n}\n<|endoftext|>"} {"text":"\/**\n * The MIT License (MIT)\n *\n * Copyright © 2017-2018 Ruben Van Boxem\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n **\/\n\n#include \"gui\/events\/xcb.h++\"\n\n#include \"gui\/native_window\/xcb.h++\"\n#include \"gui\/window.h++\"\n\n#include \n\nnamespace\n{\n std::uint8_t mask_send_event_bit(std::uint8_t response_type)\n {\n return response_type & 0b0111'1111;\n }\n}\n\nnamespace skui\n{\n namespace gui\n {\n namespace events\n {\n xcb::xcb(gui::window& window)\n : base{window}\n {\n auto native_xcb_window = dynamic_cast(&window.get_native_window());\n if(!native_xcb_window)\n core::debug_print(\"events::xcb requires a native_window::xcb or native_window::xlib.\\n\");\n\n connection = native_xcb_window->get_connection();\n xcb_window = native_xcb_window->get_window();\n\n \/\/ The magic incantation to receive and be able to check for the \"window was closed\" event\n xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, true, 12, \"WM_PROTOCOLS\");\n core::unique_free_ptr reply(xcb_intern_atom_reply(connection, cookie, nullptr));\n\n xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, false, 16, \"WM_DELETE_WINDOW\");\n wm_delete_window.reset(xcb_intern_atom_reply(connection, cookie2, nullptr));\n\n xcb_change_property(connection,\n XCB_PROP_MODE_REPLACE,\n xcb_window,\n reply->atom, 4, 32, 1, &wm_delete_window->atom);\n \/\/ end magic\n\n xcb_flush(connection);\n }\n\n xcb::~xcb() = default;\n\n void xcb::exec()\n {\n bool running = true;\n\n while(running)\n {\n core::unique_free_ptr event_ptr(xcb_wait_for_event(connection));\n if(!event_ptr)\n {\n core::debug_print(\"Call to xcb_wait_for_event failed. Most likely an I\/O error.\\n\");\n running = false;\n break;\n }\n\n switch(mask_send_event_bit(event_ptr->response_type))\n {\n case XCB_EXPOSE:\n {\n const auto& expose = reinterpret_cast(*event_ptr);\n if(expose.count>0)\n continue;\n\n window.repaint();\n\n break;\n }\n case XCB_UNMAP_NOTIFY:\n {\n \/\/const auto& unmap = reinterpret_cast(*event_ptr);\n break;\n }\n case XCB_BUTTON_PRESS:\n {\n auto button_press = reinterpret_cast(event_ptr.get());\n\n switch (button_press->state)\n {\n case XCB_BUTTON_MASK_1:\n core::debug_print(\"Primary mouse button pressed.\");\n break;\n }\n\n switch (button_press->detail)\n {\n case 4:\n \/\/ Wheel button up\n break;\n case 5:\n \/\/ wheel button down\n break;\n default:\n core::debug_print(\"Button \", button_press->detail, \" pressed in window \", button_press->event, \", at coordinates (\", button_press->event_x, \",\", button_press->event, \").\\n\");\n break;\n }\n break;\n }\n case XCB_BUTTON_RELEASE:\n {\n \/\/auto button_release = reinterpret_cast(event_ptr.get());\n \/\/implementation::print_modifiers(button_release->state);\n break;\n }\n case XCB_MOTION_NOTIFY:\n {\n \/\/auto motion = reinterpret_cast(event_ptr.get());\n break;\n }\n case XCB_ENTER_NOTIFY:\n {\n \/\/auto enter = reinterpret_cast(event_ptr.get());\n break;\n }\n case XCB_LEAVE_NOTIFY:\n {\n \/\/auto leave = reinterpret_cast(event_ptr.get());\n break;\n }\n case XCB_KEY_PRESS:\n {\n \/\/const auto& key_press = reinterpret_cast(*event_ptr);\n \/\/implementation::print_modifiers(key_press->state);\n break;\n }\n case XCB_KEY_RELEASE:\n {\n \/\/const auto& key_release = reinterpret_cast(*event_ptr);\n \/\/implementation::print_modifiers(key_release->state);\n break;\n }\n case XCB_CONFIGURE_NOTIFY:\n {\n \/\/ We send out an event here so when maximizing or minimizing a window, it gets repainted properly\n const auto& configure_notify = *reinterpret_cast(event_ptr.get());\n \/\/ xcb_send_event is hardcoded to read 32 bytes regardless the event type, so give it 32 bytes.\n core::unique_free_ptr event(reinterpret_cast(std::calloc(1, 32)));\n event->response_type = XCB_EXPOSE;\n event->window = xcb_window;\n event->x = static_cast(configure_notify.x);\n event->y = static_cast(configure_notify.y);\n event->width = configure_notify.width;\n event->height = configure_notify.height;\n\n xcb_send_event(connection, false, xcb_window, XCB_EVENT_MASK_EXPOSURE, reinterpret_cast(event.get()));\n xcb_flush(connection);\n\n break;\n }\n case XCB_CLIENT_MESSAGE:\n {\n const auto& client_message = reinterpret_cast(*event_ptr);\n\n if(client_message.data.data32[0] == wm_delete_window->atom)\n {\n core::debug_print(\"WM_DELETE_WINDOW received.\\n\");\n window.close();\n }\n break;\n }\n case XCB_DESTROY_NOTIFY:\n {\n running = false;\n break;\n }\n default:\n core::debug_print(\"Unknown event: \", (int)mask_send_event_bit(event_ptr->response_type), \".\\n\");\n break;\n }\n }\n }\n }\n }\n}\nDon't send an expose event on configure, this triggers too many repaints. Instead, force a repaint on a MapEvent.\/**\n * The MIT License (MIT)\n *\n * Copyright © 2017-2018 Ruben Van Boxem\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n **\/\n\n#include \"gui\/events\/xcb.h++\"\n\n#include \"gui\/native_window\/xcb.h++\"\n#include \"gui\/window.h++\"\n\n#include \n\nnamespace\n{\n std::uint8_t mask_send_event_bit(std::uint8_t response_type)\n {\n return response_type & 0b0111'1111;\n }\n}\n\nnamespace skui\n{\n namespace gui\n {\n namespace events\n {\n xcb::xcb(gui::window& window)\n : base{window}\n {\n auto native_xcb_window = dynamic_cast(&window.get_native_window());\n if(!native_xcb_window)\n core::debug_print(\"events::xcb requires a native_window::xcb or native_window::xlib.\\n\");\n\n connection = native_xcb_window->get_connection();\n xcb_window = native_xcb_window->get_window();\n\n \/\/ The magic incantation to receive and be able to check for the \"window was closed\" event\n xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, true, 12, \"WM_PROTOCOLS\");\n core::unique_free_ptr reply(xcb_intern_atom_reply(connection, cookie, nullptr));\n\n xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, false, 16, \"WM_DELETE_WINDOW\");\n wm_delete_window.reset(xcb_intern_atom_reply(connection, cookie2, nullptr));\n\n xcb_change_property(connection,\n XCB_PROP_MODE_REPLACE,\n xcb_window,\n reply->atom, 4, 32, 1, &wm_delete_window->atom);\n \/\/ end magic\n\n xcb_flush(connection);\n }\n\n xcb::~xcb() = default;\n\n void xcb::exec()\n {\n bool running = true;\n\n while(running)\n {\n core::unique_free_ptr event_ptr(xcb_wait_for_event(connection));\n if(!event_ptr)\n {\n core::debug_print(\"Call to xcb_wait_for_event failed. Most likely an I\/O error.\\n\");\n running = false;\n break;\n }\n\n switch(mask_send_event_bit(event_ptr->response_type))\n {\n case XCB_EXPOSE:\n {\n const auto& expose = reinterpret_cast(*event_ptr);\n if(expose.count>0)\n continue;\n\n window.repaint();\n\n break;\n }\n case XCB_UNMAP_NOTIFY:\n {\n \/\/const auto& unmap = reinterpret_cast(*event_ptr);\n break;\n }\n case XCB_MAP_NOTIFY:\n {\n \/\/const auto& map = reinterpret_cast(*event_ptr);\n window.state = window_state::windowed;\n\n \/\/ Force a repaint on map. This ensures a unminized window is properly displayed.\n window.repaint(true);\n\n break;\n }\n case XCB_BUTTON_PRESS:\n {\n auto button_press = reinterpret_cast(event_ptr.get());\n\n switch (button_press->state)\n {\n case XCB_BUTTON_MASK_1:\n core::debug_print(\"Primary mouse button pressed.\");\n break;\n }\n\n switch (button_press->detail)\n {\n case 4:\n \/\/ Wheel button up\n break;\n case 5:\n \/\/ wheel button down\n break;\n default:\n core::debug_print(\"Button \", button_press->detail, \" pressed in window \", button_press->event, \", at coordinates (\", button_press->event_x, \",\", button_press->event, \").\\n\");\n break;\n }\n break;\n }\n case XCB_BUTTON_RELEASE:\n {\n \/\/auto button_release = reinterpret_cast(event_ptr.get());\n \/\/implementation::print_modifiers(button_release->state);\n break;\n }\n case XCB_MOTION_NOTIFY:\n {\n \/\/auto motion = reinterpret_cast(event_ptr.get());\n break;\n }\n case XCB_ENTER_NOTIFY:\n {\n \/\/auto enter = reinterpret_cast(event_ptr.get());\n break;\n }\n case XCB_LEAVE_NOTIFY:\n {\n \/\/auto leave = reinterpret_cast(event_ptr.get());\n break;\n }\n case XCB_KEY_PRESS:\n {\n \/\/const auto& key_press = reinterpret_cast(*event_ptr);\n \/\/implementation::print_modifiers(key_press->state);\n break;\n }\n case XCB_KEY_RELEASE:\n {\n \/\/const auto& key_release = reinterpret_cast(*event_ptr);\n \/\/implementation::print_modifiers(key_release->state);\n break;\n }\n case XCB_CONFIGURE_NOTIFY:\n {\n \/\/const auto& configure_notify = reinterpret_cast(*event_ptr);\n break;\n }\n case XCB_CLIENT_MESSAGE:\n {\n const auto& client_message = reinterpret_cast(*event_ptr);\n\n if(client_message.data.data32[0] == wm_delete_window->atom)\n {\n core::debug_print(\"WM_DELETE_WINDOW received.\\n\");\n window.close();\n }\n break;\n }\n case XCB_DESTROY_NOTIFY:\n {\n running = false;\n break;\n }\n default:\n core::debug_print(\"Unknown event: \", (int)mask_send_event_bit(event_ptr->response_type), \".\\n\");\n break;\n }\n }\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\n#include \"SerialPort.h\"\n#include \n#include \n\n#include \"Logging.h\"\n#undef LOG_CLASS\n#define LOG_CLASS \"SerialPort\"\n\n\nSerialPort::SerialPort(int portNumber) :\n\tm_iPortNumber(portNumber),\n\tm_hPort(0)\n{\n\t\/\/ build short name from port number\n\tstd::stringstream strPortName;\n\tstrPortName << \"COM\" << m_iPortNumber;\n\tm_strPortName = strPortName.str();\n\n\t\/\/ build filename from port number\n\tstd::stringstream strFileName;\n\tstrFileName << \"\\\\\\\\.\\\\COM\" << m_iPortNumber;\n\tm_strFileName = strFileName.str();\n}\n\n\nbool SerialPort::exists() const\n{\n\t\/\/ source: http:\/\/stackoverflow.com\/questions\/1205383\/listing-serial-com-ports-on-windows\n\n\tstd::wstring strPortNameW(m_strPortName.begin(), m_strPortName.end()); \/\/ convert to wchar\n\tCOMMCONFIG config;\n\tDWORD configSize = sizeof(config);\n\t\/\/ Port exists if configuration can be retrieved (returns true)\n\t\/\/ or the config structure size changes to indicate it was too small.\n\treturn (GetDefaultCommConfigW(strPortNameW.c_str(), &config, &configSize) == TRUE) ||\n\t (configSize != sizeof(config));\n}\n\n\nbool SerialPort::open()\n{\n\tif (!isOpen())\n\t{\n\t\tstd::wstring strFileNameW(m_strFileName.begin(), m_strFileName.end()); \/\/ convert to wchar\n\t\tm_hPort = ::CreateFile(\n\t\t\tstrFileNameW.c_str(),\n\t\t\tGENERIC_READ | GENERIC_WRITE, \/\/ access rights\n\t\t\t0, \/\/ don't share port\n\t\t\t0, \/\/ no security flags necessary\n\t\t\tOPEN_EXISTING, \/\/ must exist to be opened\n\t\t\t0,\t\t\t\t\t \/\/ no overlapped operation\n\t\t\t0 \/\/ no template file for COM ports\n\t\t\t);\n\n\t\tif (m_hPort == INVALID_HANDLE_VALUE)\n\t\t{\n\t\t\thandleError(\"opening serial port\");\n\t\t\tm_hPort = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLOG_INFO(\"Opened serial port \" << m_strPortName);\n\t\t}\n\t}\n\n\treturn isOpen();\n}\n\n\nbool SerialPort::isOpen() const\n{\n\treturn (m_hPort != 0);\n}\n\n\nbool SerialPort::close()\n{\n\tif (isOpen())\n\t{\n\t\tif (::CloseHandle(m_hPort))\n\t\t{\n\t\t\tLOG_INFO(\"Closed serial port \" << m_strPortName);\n\t\t\tm_hPort = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\thandleError(\"closing serial port\");\n\t\t}\n\t}\n\treturn !isOpen();\n}\n\n\nbool SerialPort::setBaudrate(DWORD baudRate)\n{\n\tbool success = false;\n\n\tif (isOpen())\n\t{\n\t\tDCB dcb = { 0 };\n\t\tdcb.DCBlength = sizeof(DCB);\n\n\t\t\/\/ read previous port state\n\t\tif (::GetCommState(m_hPort, &dcb))\n\t\t{\n\t\t\t\/\/ success > fill in new baudrate\n\t\t\tdcb.BaudRate = baudRate;\n\t\t\tdcb.ByteSize = 8;\n\t\t\tdcb.Parity = NOPARITY;\n\t\t\tdcb.StopBits = ONESTOPBIT;\n\t\t}\n\t\telse\n\t\t{\n\t\t\thandleError(\"getting serial port state\");\n\t\t}\n\n\t\t\/\/ set new baudrate\n\t\tif (::SetCommState(m_hPort, &dcb))\n\t\t{\n\t\t\tLOG_INFO(\"Set baudrate of serial port \" << m_strPortName << \" to \" << baudRate);\n\t\t\tsuccess = true;\n\t\t}\n\t\telse \n\t\t{\n\t\t\thandleError(\"setting serial port state\");\n\t\t}\n\t}\n\n\treturn success;\n}\n\n\nDWORD SerialPort::getTimeout() const\n{\n\tDWORD timeout = 0;\n\n\tif (isOpen())\n\t{\n\t\tCOMMTIMEOUTS timeouts = { 0 };\n\n\t\t\/\/ read previous timeouts\n\t\tif (::GetCommTimeouts(m_hPort, &timeouts))\n\t\t{\n\t\t\t\/\/ success > read timeout\n\t\t\ttimeout = timeouts.ReadTotalTimeoutConstant;\n\t\t}\n\t\telse\n\t\t{\n\t\t\thandleError(\"getting serial port timeouts\");\n\t\t}\n\t}\n\n\treturn timeout;\n}\n\n\nbool SerialPort::setTimeout(DWORD timeout)\n{\n\tbool success = false;\n\n\tif (isOpen())\n\t{\n\t\tCOMMTIMEOUTS timeouts = { 0 };\n\n\t\t\/\/ read previous timeouts\n\t\tif (::GetCommTimeouts(m_hPort, &timeouts))\n\t\t{\n\t\t\t\/\/ success > change timeout\n\t\t\ttimeouts.ReadTotalTimeoutConstant = timeout;\n\t\t}\n\t\telse\n\t\t{\n\t\t\thandleError(\"getting serial port timeouts\");\n\t\t}\n\n\t\t\/\/ set new timeout values\n\t\tif (::SetCommTimeouts(m_hPort, &timeouts))\n\t\t{\n\t\t\t\/\/ LOG_INFO(\"Set timeout of serial port \" << m_strPortName << \" to \" << timeout);\n\t\t\tsuccess = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\thandleError(\"setting serial port timeouts\");\n\t\t}\n\t}\n\n\treturn success;\n}\n\n\nDWORD SerialPort::send(const void* pBuffer, DWORD nBytesToSend) const\n{\n\tDWORD nBytesSent= 0;\n\t::WriteFile(m_hPort, pBuffer, nBytesToSend, &nBytesSent, NULL);\n\treturn nBytesSent;\n}\n\n\nDWORD SerialPort::receive(void* pBuffer, DWORD nBytesToReceive) const\n{\n\tDWORD nBytesReceived = 0;\n\t::ReadFile(m_hPort, pBuffer, nBytesToReceive, &nBytesReceived, NULL);\n\treturn nBytesReceived;\n}\n\n\nSerialPort::~SerialPort()\n{\n\tif (isOpen())\n\t{\n\t\tclose();\n\t}\n}\n\n\nvoid SerialPort::handleError(const char* strFunction) const\n{\n\tLPVOID lpMsgBuf;\n\tDWORD error = GetLastError();\n\n\tFormatMessageW(\n\t\tFORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t\tNULL,\n\t\terror,\n\t\tMAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n\t\t(LPTSTR) &lpMsgBuf,\n\t\t0, NULL\n\t);\n\n\tstd::wstring strMsgW((const wchar_t*) lpMsgBuf);\n\tstd::string strMsg(strMsgW.begin(), strMsgW.end());\n\tLOG_ERROR(\"Error while \" << strFunction << \": \" << strMsg);\n\n\tLocalFree(lpMsgBuf);\n}\n\nOnly error messages for serial port\n#include \"SerialPort.h\"\n#include \n#include \n\n#include \"Logging.h\"\n#undef LOG_CLASS\n#define LOG_CLASS \"SerialPort\"\n\n\nSerialPort::SerialPort(int portNumber) :\n\tm_iPortNumber(portNumber),\n\tm_hPort(0)\n{\n\t\/\/ build short name from port number\n\tstd::stringstream strPortName;\n\tstrPortName << \"COM\" << m_iPortNumber;\n\tm_strPortName = strPortName.str();\n\n\t\/\/ build filename from port number\n\tstd::stringstream strFileName;\n\tstrFileName << \"\\\\\\\\.\\\\COM\" << m_iPortNumber;\n\tm_strFileName = strFileName.str();\n}\n\n\nbool SerialPort::exists() const\n{\n\t\/\/ source: http:\/\/stackoverflow.com\/questions\/1205383\/listing-serial-com-ports-on-windows\n\n\tstd::wstring strPortNameW(m_strPortName.begin(), m_strPortName.end()); \/\/ convert to wchar\n\tCOMMCONFIG config;\n\tDWORD configSize = sizeof(config);\n\t\/\/ Port exists if configuration can be retrieved (returns true)\n\t\/\/ or the config structure size changes to indicate it was too small.\n\treturn (GetDefaultCommConfigW(strPortNameW.c_str(), &config, &configSize) == TRUE) ||\n\t (configSize != sizeof(config));\n}\n\n\nbool SerialPort::open()\n{\n\tif (!isOpen())\n\t{\n\t\tstd::wstring strFileNameW(m_strFileName.begin(), m_strFileName.end()); \/\/ convert to wchar\n\t\tm_hPort = ::CreateFile(\n\t\t\tstrFileNameW.c_str(),\n\t\t\tGENERIC_READ | GENERIC_WRITE, \/\/ access rights\n\t\t\t0, \/\/ don't share port\n\t\t\t0, \/\/ no security flags necessary\n\t\t\tOPEN_EXISTING, \/\/ must exist to be opened\n\t\t\t0,\t\t\t\t\t \/\/ no overlapped operation\n\t\t\t0 \/\/ no template file for COM ports\n\t\t\t);\n\n\t\tif (m_hPort == INVALID_HANDLE_VALUE)\n\t\t{\n\t\t\thandleError(\"opening serial port\");\n\t\t\tm_hPort = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ LOG_INFO(\"Opened serial port \" << m_strPortName);\n\t\t}\n\t}\n\n\treturn isOpen();\n}\n\n\nbool SerialPort::isOpen() const\n{\n\treturn (m_hPort != 0);\n}\n\n\nbool SerialPort::close()\n{\n\tif (isOpen())\n\t{\n\t\tif (::CloseHandle(m_hPort))\n\t\t{\n\t\t\t\/\/ LOG_INFO(\"Closed serial port \" << m_strPortName);\n\t\t\tm_hPort = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\thandleError(\"closing serial port\");\n\t\t}\n\t}\n\treturn !isOpen();\n}\n\n\nbool SerialPort::setBaudrate(DWORD baudRate)\n{\n\tbool success = false;\n\n\tif (isOpen())\n\t{\n\t\tDCB dcb = { 0 };\n\t\tdcb.DCBlength = sizeof(DCB);\n\n\t\t\/\/ read previous port state\n\t\tif (::GetCommState(m_hPort, &dcb))\n\t\t{\n\t\t\t\/\/ success > fill in new baudrate\n\t\t\tdcb.BaudRate = baudRate;\n\t\t\tdcb.ByteSize = 8;\n\t\t\tdcb.Parity = NOPARITY;\n\t\t\tdcb.StopBits = ONESTOPBIT;\n\t\t}\n\t\telse\n\t\t{\n\t\t\thandleError(\"getting serial port state\");\n\t\t}\n\n\t\t\/\/ set new baudrate\n\t\tif (::SetCommState(m_hPort, &dcb))\n\t\t{\n\t\t\t\/\/ LOG_INFO(\"Set baudrate of serial port \" << m_strPortName << \" to \" << baudRate);\n\t\t\tsuccess = true;\n\t\t}\n\t\telse \n\t\t{\n\t\t\thandleError(\"setting serial port state\");\n\t\t}\n\t}\n\n\treturn success;\n}\n\n\nDWORD SerialPort::getTimeout() const\n{\n\tDWORD timeout = 0;\n\n\tif (isOpen())\n\t{\n\t\tCOMMTIMEOUTS timeouts = { 0 };\n\n\t\t\/\/ read previous timeouts\n\t\tif (::GetCommTimeouts(m_hPort, &timeouts))\n\t\t{\n\t\t\t\/\/ success > read timeout\n\t\t\ttimeout = timeouts.ReadTotalTimeoutConstant;\n\t\t}\n\t\telse\n\t\t{\n\t\t\thandleError(\"getting serial port timeouts\");\n\t\t}\n\t}\n\n\treturn timeout;\n}\n\n\nbool SerialPort::setTimeout(DWORD timeout)\n{\n\tbool success = false;\n\n\tif (isOpen())\n\t{\n\t\tCOMMTIMEOUTS timeouts = { 0 };\n\n\t\t\/\/ read previous timeouts\n\t\tif (::GetCommTimeouts(m_hPort, &timeouts))\n\t\t{\n\t\t\t\/\/ success > change timeout\n\t\t\ttimeouts.ReadTotalTimeoutConstant = timeout;\n\t\t}\n\t\telse\n\t\t{\n\t\t\thandleError(\"getting serial port timeouts\");\n\t\t}\n\n\t\t\/\/ set new timeout values\n\t\tif (::SetCommTimeouts(m_hPort, &timeouts))\n\t\t{\n\t\t\t\/\/ LOG_INFO(\"Set timeout of serial port \" << m_strPortName << \" to \" << timeout);\n\t\t\tsuccess = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\thandleError(\"setting serial port timeouts\");\n\t\t}\n\t}\n\n\treturn success;\n}\n\n\nDWORD SerialPort::send(const void* pBuffer, DWORD nBytesToSend) const\n{\n\tDWORD nBytesSent= 0;\n\t::WriteFile(m_hPort, pBuffer, nBytesToSend, &nBytesSent, NULL);\n\treturn nBytesSent;\n}\n\n\nDWORD SerialPort::receive(void* pBuffer, DWORD nBytesToReceive) const\n{\n\tDWORD nBytesReceived = 0;\n\t::ReadFile(m_hPort, pBuffer, nBytesToReceive, &nBytesReceived, NULL);\n\treturn nBytesReceived;\n}\n\n\nSerialPort::~SerialPort()\n{\n\tif (isOpen())\n\t{\n\t\tclose();\n\t}\n}\n\n\nvoid SerialPort::handleError(const char* strFunction) const\n{\n\tLPVOID lpMsgBuf;\n\tDWORD error = GetLastError();\n\n\tFormatMessageW(\n\t\tFORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t\tNULL,\n\t\terror,\n\t\tMAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n\t\t(LPTSTR) &lpMsgBuf,\n\t\t0, NULL\n\t);\n\n\tstd::wstring strMsgW((const wchar_t*) lpMsgBuf);\n\tstd::string strMsg(strMsgW.begin(), strMsgW.end());\n\tLOG_ERROR(\"Error while \" << strFunction << \": \" << strMsg);\n\n\tLocalFree(lpMsgBuf);\n}\n\n<|endoftext|>"} {"text":"added handling for ports in mxid<|endoftext|>"} {"text":"#include \"Settings.h\"\n\n#include \n#include \n\n#include \"Error.h\"\n#include \"HotkeyActions.h\"\n#include \"HotkeyInfo.h\"\n#include \"Logger.h\"\n#include \"Monitor.h\"\n#include \"Skin.h\"\n#include \"StringUtils.h\"\n\n#define XML_AUDIODEV \"audioDeviceID\"\n#define XML_HIDE_WHENFULL \"hideFullscreen\"\n#define XML_HIDEANIM \"hideAnimation\"\n#define XML_HIDETIME \"hideDelay\"\n#define XML_HIDESPEED \"hideSpeed\"\n#define XML_LANGUAGE \"language\"\n#define XML_MONITOR \"monitor\"\n#define XML_NOTIFYICON \"notifyIcon\"\n#define XML_ONTOP \"onTop\"\n#define XML_OSD_OFFSET \"osdEdgeOffset\"\n#define XML_OSD_POS \"osdPosition\"\n#define XML_OSD_X \"osdX\"\n#define XML_OSD_Y \"osdY\"\n#define XML_SKIN \"skin\"\n#define XML_SOUNDS \"soundEffects\"\n\nstd::wstring Settings::_appDir(L\"\");\nSettings *Settings::instance;\n\nstd::vector Settings::OSDPosNames = {\n L\"top\",\n L\"left\",\n L\"right\",\n L\"bottom\",\n L\"center\",\n L\"top-left\",\n L\"top-right\",\n L\"bottom-left\",\n L\"bottom-right\",\n L\"custom\"\n};\n\nstd::vector Settings::HideAnimNames = {\n L\"none\",\n L\"fade\"\n};\n\nSettings *Settings::Instance() {\n if (instance == NULL) {\n instance = new Settings();\n }\n return instance;\n}\n\nvoid Settings::Load() {\n _file = AppDir() + L\"\\\\Settings.xml\";\n CLOG(L\"Loading settings: %s\", _file.c_str());\n\n std::string u8FileName = StringUtils::Narrow(_file);\n tinyxml2::XMLError result = _xml.LoadFile(u8FileName.c_str());\n if (result != tinyxml2::XMLError::XML_SUCCESS) {\n throw std::runtime_error(\"Failed to parse XML file\");\n }\n\n _root = _xml.GetDocument()->FirstChildElement(\"settings\");\n if (_root == NULL) {\n throw std::runtime_error(\"Could not find root XML element\");\n }\n\n delete _skin;\n _skin = new Skin(SkinXML());\n}\n\nint Settings::Save() {\n FILE *stream;\n errno_t err = _wfopen_s(&stream, _file.c_str(), L\"w\");\n if (err != 0) {\n CLOG(L\"Could not open settings file for writing!\");\n return 100 + err;\n }\n tinyxml2::XMLError result = _xml.SaveFile(stream);\n fclose(stream);\n return result;\n}\n\nstd::wstring Settings::AppDir() {\n if (_appDir.empty()) {\n wchar_t path[MAX_PATH];\n GetModuleFileName(NULL, path, MAX_PATH);\n PathRemoveFileSpec(path);\n _appDir = std::wstring(path);\n }\n return _appDir;\n}\n\nstd::wstring Settings::SkinDir() {\n return AppDir() + L\"\\\\\" + SKIN_DIR;\n}\n\n\nstd::wstring Settings::SettingsApp() {\n return Settings::AppDir() + L\"\\\\\" + SETTINGS_APP;\n}\n\nstd::wstring Settings::LanguagesDir() {\n return AppDir() + L\"\\\\\" + LANG_DIR;\n}\n\nvoid Settings::LaunchSettingsApp() {\n std::wstring app = SettingsApp();\n\n CLOG(L\"Opening Settings App: %s\", app.c_str());\n int exec = (int) ShellExecute(\n NULL, L\"open\", app.c_str(), NULL, NULL, SW_SHOWNORMAL);\n\n if (exec <= 32) {\n Error::ErrorMessage(GENERR_NOTFOUND, app);\n }\n}\n\nstd::wstring Settings::AudioDeviceID() {\n return GetText(XML_AUDIODEV);\n}\n\nstd::wstring Settings::LanguageName() {\n std::wstring lang = GetText(XML_LANGUAGE);\n\n if (lang == L\"\") {\n return DEFAULT_LANGUAGE;\n } else {\n return lang;\n }\n}\n\nbool Settings::AlwaysOnTop() {\n return GetEnabled(XML_ONTOP);\n}\n\nvoid Settings::AlwaysOnTop(bool enable) {\n SetEnabled(XML_ONTOP, enable);\n}\n\nbool Settings::HideFullscreen() {\n return GetEnabled(XML_HIDE_WHENFULL);\n}\n\nvoid Settings::HideFullscreen(bool enable) {\n SetEnabled(XML_HIDE_WHENFULL, enable);\n}\n\nstd::wstring Settings::Monitor() {\n return GetText(XML_MONITOR);\n}\n\nvoid Settings::Monitor(std::wstring monitorName) {\n SetText(XML_MONITOR, StringUtils::Narrow(monitorName));\n}\n\nint Settings::OSDEdgeOffset() {\n if (HasSetting(XML_OSD_OFFSET)) {\n return GetInt(XML_OSD_OFFSET);\n } else {\n return DEFAULT_OSD_OFFSET;\n }\n}\n\nvoid Settings::OSDEdgeOffset(int offset) {\n SetInt(XML_OSD_OFFSET, offset);\n}\n\nSettings::OSDPos Settings::OSDPosition() {\n std::wstring pos = GetText(XML_OSD_POS);\n std::transform(pos.begin(), pos.end(), pos.begin(), ::tolower);\n\n for (unsigned int i = 0; i < OSDPosNames.size(); ++i) {\n if (pos == OSDPosNames[i]) {\n return (Settings::OSDPos) i;\n }\n }\n\n return DEFAULT_OSD_POS;\n}\n\nvoid Settings::OSDPosition(OSDPos pos) {\n std::wstring posStr = OSDPosNames[(int) pos];\n SetText(XML_OSD_POS, StringUtils::Narrow(posStr));\n}\n\nint Settings::OSDX() {\n return GetInt(XML_OSD_X);\n}\n\nvoid Settings::OSDX(int x) {\n SetInt(XML_OSD_X, x);\n}\n\nint Settings::OSDY() {\n return GetInt(XML_OSD_Y);\n}\n\nvoid Settings::OSDY(int y) {\n SetInt(XML_OSD_Y, y);\n}\n\nSkin *Settings::CurrentSkin() {\n return _skin;\n}\n\nSettings::HideAnim Settings::HideAnimation() {\n std::wstring anim = GetText(XML_HIDEANIM);\n std::transform(anim.begin(), anim.end(), anim.begin(), ::tolower);\n\n for (unsigned int i = 0; i < HideAnimNames.size(); ++i) {\n if (anim == HideAnimNames[i]) {\n return (Settings::HideAnim) i;\n }\n }\n\n return DEFAULT_HIDE_ANIM;\n}\n\nvoid Settings::HideAnimation(Settings::HideAnim anim) {\n std::wstring hideStr = HideAnimNames[(int) anim];\n SetText(XML_HIDEANIM, StringUtils::Narrow(hideStr));\n}\n\nint Settings::HideDelay() {\n return GetInt(XML_HIDETIME);\n}\n\nvoid Settings::HideDelay(int delay) {\n SetInt(XML_HIDETIME, delay);\n}\n\nint Settings::HideSpeed() {\n return GetInt(XML_HIDESPEED);\n}\n\nvoid Settings::HideSpeed(int speed) {\n SetInt(XML_HIDESPEED, speed);\n}\n\nbool Settings::CurrentSkin(std::wstring skinName) {\n std::string name = StringUtils::Narrow(skinName);\n std::wstring xml = SkinXML(skinName);\n if (PathFileExists(xml.c_str()) == FALSE) {\n return false;\n }\n\n SetText(XML_SKIN, name);\n return true;\n}\n\nstd::wstring Settings::SkinName() {\n std::wstring name = GetText(\"skin\");\n\n if (name == L\"\") {\n return DEFAULT_SKIN;\n } else {\n return name;\n }\n}\n\nstd::wstring Settings::SkinXML() {\n return SkinXML(SkinName());\n}\n\nstd::wstring Settings::SkinXML(std::wstring skinName) {\n std::wstring skinXML = Settings::AppDir() + L\"\\\\\" + SKINS_DIR L\"\\\\\"\n + skinName + L\"\\\\\" SKIN_XML;\n return skinXML;\n}\n\nstd::unordered_map Settings::Hotkeys() {\n std::unordered_map keyMappings;\n\n tinyxml2::XMLElement *hotkeys = _root->FirstChildElement(\"hotkeys\");\n if (hotkeys == NULL) {\n return keyMappings;\n }\n\n tinyxml2::XMLElement *hotkey = hotkeys->FirstChildElement(\"hotkey\");\n for (; hotkey != NULL; hotkey = hotkey->NextSiblingElement()) {\n int action = -1;\n hotkey->QueryIntAttribute(\"action\", &action);\n if (action == -1) {\n CLOG(L\"No action provided for hotkey; skipping\");\n continue;\n }\n\n int combination = -1;\n hotkey->QueryIntAttribute(\"combination\", &combination);\n if (combination == -1) {\n CLOG(L\"No key combination provided for hotkey; skipping\");\n continue;\n }\n\n HotkeyInfo hki;\n hki.action = action;\n hki.keyCombination = combination;\n\n \/* Does this hotkey action have any arguments? *\/\n tinyxml2::XMLElement *arg = hotkey->FirstChildElement(\"arg\");\n for (; arg != NULL; arg = arg->NextSiblingElement()) {\n const char *argStr = arg->GetText();\n hki.args.push_back(StringUtils::Widen(argStr));\n }\n \n \/* Whew, we made it! *\/\n CLOG(L\"%s\", hki.ToString().c_str());\n keyMappings[combination] = hki;\n }\n\n return keyMappings;\n}\n\nvoid Settings::Hotkeys(std::vector hotkeys) {\n tinyxml2::XMLElement *hkElem = GetOrCreateElement(\"hotkeys\");\n hkElem->DeleteChildren();\n\n for (HotkeyInfo hotkey : hotkeys) {\n tinyxml2::XMLElement *hk = _xml.NewElement(\"hotkey\");\n\n hk->SetAttribute(\"combination\", hotkey.keyCombination);\n hk->SetAttribute(\"action\", hotkey.action);\n\n if (hotkey.args.size() > 0) {\n for (std::wstring arg : hotkey.args) {\n tinyxml2::XMLElement *argElem = _xml.NewElement(\"arg\");\n argElem->SetText(StringUtils::Narrow(arg).c_str());\n hk->InsertEndChild(argElem);\n }\n }\n\n hkElem->InsertEndChild(hk);\n }\n}\n\nbool Settings::NotifyIconEnabled() {\n return GetEnabled(XML_NOTIFYICON);\n}\n\nvoid Settings::NotifyIconEnabled(bool enable) {\n SetEnabled(XML_NOTIFYICON, enable);\n}\n\nbool Settings::SoundEffectsEnabled() {\n return GetEnabled(XML_SOUNDS);\n}\n\nvoid Settings::SoundEffectsEnabled(bool enable) {\n SetEnabled(XML_SOUNDS, enable);\n}\n\nbool Settings::HasSetting(std::string elementName) {\n tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n return (el != NULL);\n}\n\nbool Settings::GetEnabled(std::string elementName) {\n tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n if (el == NULL) {\n CLOG(L\"Warning: XML element '%s' not found\", elementName.c_str());\n return false;\n } else {\n bool val = false;\n el->QueryBoolText(&val);\n return val;\n }\n}\n\nvoid Settings::SetEnabled(std::string elementName, bool enabled) {\n tinyxml2::XMLElement *el = GetOrCreateElement(elementName);\n el->SetText(enabled ? \"true\" : \"false\");\n}\n\nstd::wstring Settings::GetText(std::string elementName) {\n tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n if (el == NULL) {\n CLOG(L\"Warning: XML element %s not found\",\n StringUtils::Widen(elementName).c_str());\n return L\"\";\n }\n\n const char* str = el->GetText();\n if (str == NULL) {\n return L\"\";\n } else {\n return StringUtils::Widen(str);\n }\n}\n\nvoid Settings::SetText(std::string elementName, std::string text) {\n tinyxml2::XMLElement *el = GetOrCreateElement(elementName);\n el->SetText(text.c_str());\n}\n\nint Settings::GetInt(std::string elementName) {\n tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n if (el == NULL) {\n CLOG(L\"Warning: XML element '%s' not found\", elementName.c_str());\n return 0;\n }\n\n int val = 0;\n el->QueryIntText(&val);\n return val;\n}\n\nvoid Settings::SetInt(std::string elementName, int value) {\n tinyxml2::XMLElement *el = GetOrCreateElement(elementName);\n el->SetText(value);\n}\n\ntinyxml2::XMLElement *Settings::GetOrCreateElement(std::string elementName) {\n tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n if (el == NULL) {\n el = _xml.NewElement(elementName.c_str());\n _root->InsertEndChild(el);\n }\n return el;\n}Initialize path array#include \"Settings.h\"\n\n#include \n#include \n\n#include \"Error.h\"\n#include \"HotkeyActions.h\"\n#include \"HotkeyInfo.h\"\n#include \"Logger.h\"\n#include \"Monitor.h\"\n#include \"Skin.h\"\n#include \"StringUtils.h\"\n\n#define XML_AUDIODEV \"audioDeviceID\"\n#define XML_HIDE_WHENFULL \"hideFullscreen\"\n#define XML_HIDEANIM \"hideAnimation\"\n#define XML_HIDETIME \"hideDelay\"\n#define XML_HIDESPEED \"hideSpeed\"\n#define XML_LANGUAGE \"language\"\n#define XML_MONITOR \"monitor\"\n#define XML_NOTIFYICON \"notifyIcon\"\n#define XML_ONTOP \"onTop\"\n#define XML_OSD_OFFSET \"osdEdgeOffset\"\n#define XML_OSD_POS \"osdPosition\"\n#define XML_OSD_X \"osdX\"\n#define XML_OSD_Y \"osdY\"\n#define XML_SKIN \"skin\"\n#define XML_SOUNDS \"soundEffects\"\n\nstd::wstring Settings::_appDir(L\"\");\nSettings *Settings::instance;\n\nstd::vector Settings::OSDPosNames = {\n L\"top\",\n L\"left\",\n L\"right\",\n L\"bottom\",\n L\"center\",\n L\"top-left\",\n L\"top-right\",\n L\"bottom-left\",\n L\"bottom-right\",\n L\"custom\"\n};\n\nstd::vector Settings::HideAnimNames = {\n L\"none\",\n L\"fade\"\n};\n\nSettings *Settings::Instance() {\n if (instance == NULL) {\n instance = new Settings();\n }\n return instance;\n}\n\nvoid Settings::Load() {\n _file = AppDir() + L\"\\\\Settings.xml\";\n CLOG(L\"Loading settings: %s\", _file.c_str());\n\n std::string u8FileName = StringUtils::Narrow(_file);\n tinyxml2::XMLError result = _xml.LoadFile(u8FileName.c_str());\n if (result != tinyxml2::XMLError::XML_SUCCESS) {\n throw std::runtime_error(\"Failed to parse XML file\");\n }\n\n _root = _xml.GetDocument()->FirstChildElement(\"settings\");\n if (_root == NULL) {\n throw std::runtime_error(\"Could not find root XML element\");\n }\n\n delete _skin;\n _skin = new Skin(SkinXML());\n}\n\nint Settings::Save() {\n FILE *stream;\n errno_t err = _wfopen_s(&stream, _file.c_str(), L\"w\");\n if (err != 0) {\n CLOG(L\"Could not open settings file for writing!\");\n return 100 + err;\n }\n tinyxml2::XMLError result = _xml.SaveFile(stream);\n fclose(stream);\n return result;\n}\n\nstd::wstring Settings::AppDir() {\n if (_appDir.empty()) {\n wchar_t path[MAX_PATH] = { 0 };\n GetModuleFileName(NULL, path, MAX_PATH);\n PathRemoveFileSpec(path);\n _appDir = std::wstring(path);\n }\n return _appDir;\n}\n\nstd::wstring Settings::SkinDir() {\n return AppDir() + L\"\\\\\" + SKIN_DIR;\n}\n\n\nstd::wstring Settings::SettingsApp() {\n return Settings::AppDir() + L\"\\\\\" + SETTINGS_APP;\n}\n\nstd::wstring Settings::LanguagesDir() {\n return AppDir() + L\"\\\\\" + LANG_DIR;\n}\n\nvoid Settings::LaunchSettingsApp() {\n std::wstring app = SettingsApp();\n\n CLOG(L\"Opening Settings App: %s\", app.c_str());\n int exec = (int) ShellExecute(\n NULL, L\"open\", app.c_str(), NULL, NULL, SW_SHOWNORMAL);\n\n if (exec <= 32) {\n Error::ErrorMessage(GENERR_NOTFOUND, app);\n }\n}\n\nstd::wstring Settings::AudioDeviceID() {\n return GetText(XML_AUDIODEV);\n}\n\nstd::wstring Settings::LanguageName() {\n std::wstring lang = GetText(XML_LANGUAGE);\n\n if (lang == L\"\") {\n return DEFAULT_LANGUAGE;\n } else {\n return lang;\n }\n}\n\nbool Settings::AlwaysOnTop() {\n return GetEnabled(XML_ONTOP);\n}\n\nvoid Settings::AlwaysOnTop(bool enable) {\n SetEnabled(XML_ONTOP, enable);\n}\n\nbool Settings::HideFullscreen() {\n return GetEnabled(XML_HIDE_WHENFULL);\n}\n\nvoid Settings::HideFullscreen(bool enable) {\n SetEnabled(XML_HIDE_WHENFULL, enable);\n}\n\nstd::wstring Settings::Monitor() {\n return GetText(XML_MONITOR);\n}\n\nvoid Settings::Monitor(std::wstring monitorName) {\n SetText(XML_MONITOR, StringUtils::Narrow(monitorName));\n}\n\nint Settings::OSDEdgeOffset() {\n if (HasSetting(XML_OSD_OFFSET)) {\n return GetInt(XML_OSD_OFFSET);\n } else {\n return DEFAULT_OSD_OFFSET;\n }\n}\n\nvoid Settings::OSDEdgeOffset(int offset) {\n SetInt(XML_OSD_OFFSET, offset);\n}\n\nSettings::OSDPos Settings::OSDPosition() {\n std::wstring pos = GetText(XML_OSD_POS);\n std::transform(pos.begin(), pos.end(), pos.begin(), ::tolower);\n\n for (unsigned int i = 0; i < OSDPosNames.size(); ++i) {\n if (pos == OSDPosNames[i]) {\n return (Settings::OSDPos) i;\n }\n }\n\n return DEFAULT_OSD_POS;\n}\n\nvoid Settings::OSDPosition(OSDPos pos) {\n std::wstring posStr = OSDPosNames[(int) pos];\n SetText(XML_OSD_POS, StringUtils::Narrow(posStr));\n}\n\nint Settings::OSDX() {\n return GetInt(XML_OSD_X);\n}\n\nvoid Settings::OSDX(int x) {\n SetInt(XML_OSD_X, x);\n}\n\nint Settings::OSDY() {\n return GetInt(XML_OSD_Y);\n}\n\nvoid Settings::OSDY(int y) {\n SetInt(XML_OSD_Y, y);\n}\n\nSkin *Settings::CurrentSkin() {\n return _skin;\n}\n\nSettings::HideAnim Settings::HideAnimation() {\n std::wstring anim = GetText(XML_HIDEANIM);\n std::transform(anim.begin(), anim.end(), anim.begin(), ::tolower);\n\n for (unsigned int i = 0; i < HideAnimNames.size(); ++i) {\n if (anim == HideAnimNames[i]) {\n return (Settings::HideAnim) i;\n }\n }\n\n return DEFAULT_HIDE_ANIM;\n}\n\nvoid Settings::HideAnimation(Settings::HideAnim anim) {\n std::wstring hideStr = HideAnimNames[(int) anim];\n SetText(XML_HIDEANIM, StringUtils::Narrow(hideStr));\n}\n\nint Settings::HideDelay() {\n return GetInt(XML_HIDETIME);\n}\n\nvoid Settings::HideDelay(int delay) {\n SetInt(XML_HIDETIME, delay);\n}\n\nint Settings::HideSpeed() {\n return GetInt(XML_HIDESPEED);\n}\n\nvoid Settings::HideSpeed(int speed) {\n SetInt(XML_HIDESPEED, speed);\n}\n\nbool Settings::CurrentSkin(std::wstring skinName) {\n std::string name = StringUtils::Narrow(skinName);\n std::wstring xml = SkinXML(skinName);\n if (PathFileExists(xml.c_str()) == FALSE) {\n return false;\n }\n\n SetText(XML_SKIN, name);\n return true;\n}\n\nstd::wstring Settings::SkinName() {\n std::wstring name = GetText(\"skin\");\n\n if (name == L\"\") {\n return DEFAULT_SKIN;\n } else {\n return name;\n }\n}\n\nstd::wstring Settings::SkinXML() {\n return SkinXML(SkinName());\n}\n\nstd::wstring Settings::SkinXML(std::wstring skinName) {\n std::wstring skinXML = Settings::AppDir() + L\"\\\\\" + SKINS_DIR L\"\\\\\"\n + skinName + L\"\\\\\" SKIN_XML;\n return skinXML;\n}\n\nstd::unordered_map Settings::Hotkeys() {\n std::unordered_map keyMappings;\n\n tinyxml2::XMLElement *hotkeys = _root->FirstChildElement(\"hotkeys\");\n if (hotkeys == NULL) {\n return keyMappings;\n }\n\n tinyxml2::XMLElement *hotkey = hotkeys->FirstChildElement(\"hotkey\");\n for (; hotkey != NULL; hotkey = hotkey->NextSiblingElement()) {\n int action = -1;\n hotkey->QueryIntAttribute(\"action\", &action);\n if (action == -1) {\n CLOG(L\"No action provided for hotkey; skipping\");\n continue;\n }\n\n int combination = -1;\n hotkey->QueryIntAttribute(\"combination\", &combination);\n if (combination == -1) {\n CLOG(L\"No key combination provided for hotkey; skipping\");\n continue;\n }\n\n HotkeyInfo hki;\n hki.action = action;\n hki.keyCombination = combination;\n\n \/* Does this hotkey action have any arguments? *\/\n tinyxml2::XMLElement *arg = hotkey->FirstChildElement(\"arg\");\n for (; arg != NULL; arg = arg->NextSiblingElement()) {\n const char *argStr = arg->GetText();\n hki.args.push_back(StringUtils::Widen(argStr));\n }\n \n \/* Whew, we made it! *\/\n CLOG(L\"%s\", hki.ToString().c_str());\n keyMappings[combination] = hki;\n }\n\n return keyMappings;\n}\n\nvoid Settings::Hotkeys(std::vector hotkeys) {\n tinyxml2::XMLElement *hkElem = GetOrCreateElement(\"hotkeys\");\n hkElem->DeleteChildren();\n\n for (HotkeyInfo hotkey : hotkeys) {\n tinyxml2::XMLElement *hk = _xml.NewElement(\"hotkey\");\n\n hk->SetAttribute(\"combination\", hotkey.keyCombination);\n hk->SetAttribute(\"action\", hotkey.action);\n\n if (hotkey.args.size() > 0) {\n for (std::wstring arg : hotkey.args) {\n tinyxml2::XMLElement *argElem = _xml.NewElement(\"arg\");\n argElem->SetText(StringUtils::Narrow(arg).c_str());\n hk->InsertEndChild(argElem);\n }\n }\n\n hkElem->InsertEndChild(hk);\n }\n}\n\nbool Settings::NotifyIconEnabled() {\n return GetEnabled(XML_NOTIFYICON);\n}\n\nvoid Settings::NotifyIconEnabled(bool enable) {\n SetEnabled(XML_NOTIFYICON, enable);\n}\n\nbool Settings::SoundEffectsEnabled() {\n return GetEnabled(XML_SOUNDS);\n}\n\nvoid Settings::SoundEffectsEnabled(bool enable) {\n SetEnabled(XML_SOUNDS, enable);\n}\n\nbool Settings::HasSetting(std::string elementName) {\n tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n return (el != NULL);\n}\n\nbool Settings::GetEnabled(std::string elementName) {\n tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n if (el == NULL) {\n CLOG(L\"Warning: XML element '%s' not found\", elementName.c_str());\n return false;\n } else {\n bool val = false;\n el->QueryBoolText(&val);\n return val;\n }\n}\n\nvoid Settings::SetEnabled(std::string elementName, bool enabled) {\n tinyxml2::XMLElement *el = GetOrCreateElement(elementName);\n el->SetText(enabled ? \"true\" : \"false\");\n}\n\nstd::wstring Settings::GetText(std::string elementName) {\n tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n if (el == NULL) {\n CLOG(L\"Warning: XML element %s not found\",\n StringUtils::Widen(elementName).c_str());\n return L\"\";\n }\n\n const char* str = el->GetText();\n if (str == NULL) {\n return L\"\";\n } else {\n return StringUtils::Widen(str);\n }\n}\n\nvoid Settings::SetText(std::string elementName, std::string text) {\n tinyxml2::XMLElement *el = GetOrCreateElement(elementName);\n el->SetText(text.c_str());\n}\n\nint Settings::GetInt(std::string elementName) {\n tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n if (el == NULL) {\n CLOG(L\"Warning: XML element '%s' not found\", elementName.c_str());\n return 0;\n }\n\n int val = 0;\n el->QueryIntText(&val);\n return val;\n}\n\nvoid Settings::SetInt(std::string elementName, int value) {\n tinyxml2::XMLElement *el = GetOrCreateElement(elementName);\n el->SetText(value);\n}\n\ntinyxml2::XMLElement *Settings::GetOrCreateElement(std::string elementName) {\n tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n if (el == NULL) {\n el = _xml.NewElement(elementName.c_str());\n _root->InsertEndChild(el);\n }\n return el;\n}<|endoftext|>"} {"text":"#include \"Agent.h\"\n#include \"Environment.h\"\n#include \"Include.h\"\n\nusing namespace std;\n\nAgent::Agent(Environment* _world){\n\t\n\tsrand( time(NULL) );\n\trunning = false;\n\t\n\tsteps = 0;\n\t\n\tposX = 0;\n\tposY = 0;\n\t\n\tworld = _world;\n\tpositionNode = _world->SetStartNode();\n}\n\nAgent::~Agent(void){\n\n\tdelete positionNode;\n}\n\nint Agent::Run(){\n\n\trunning = true;\n\t\n\t\/\/running until environment is clean\n\twhile (running) {\n\t\tsystem(\"CLS\");\n\t\tworld->draw(posX, posY);\n\t\tVacuum();\n\t\tMove();\n\t\t\n\t\t\/\/will end if taking more than 1k steps.\n\t\tsteps++;\n\t\tif(steps > 1000) {\n\t\t\trunning = false;\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n};\n\nvoid Agent::Vacuum() {\n\n\tif ( positionNode->getValue() == 0 ) {\n\t\t\/\/Sleep(300);\n\t\tcout << \"Node is clean\" << std::endl;\n\t}\n\telse {\n\n\t\t\/\/Sleep(300);\n\t\tstd::cout<< \"I am vacuuming here now, soon clean...\";\n\t\t\/\/Sleep(300);\n\t\tstd::cout<< \" Clean!\"<< std::endl;\n\n\t\tpositionNode->setValue(0);\n\t}\n}\n\nvoid Agent::Move() {\n\n\t\n\tstd::cout<< \"Moving to next - \";\n\n\t\/\/Sleep(1000);\n\n\t\/\/ TODO: Check for wals, dont move towards them!\n\n\tfor(int i = 0; i < 4; i++) {\n\n\n\t}\n\n\n\tbool moveAble = true;\n\tint randomz;\n\twhile( moveAble ) {\n\t\trandomz = rand() % 4;\n\t\tif(randomz == 0) { \/\/ Down\n\t\t\tcout<< \"Down wards\\n\";\n\t\t\tif(world->isMoveAble(posX+1, posY)->getValue() != 2) {\n\t\t\t\tposX += 1;\n\t\t\t\tmoveAble = false;\n\t\t\t} else {\n\t\t\t\t\tcout<< \"Its a wall\\n\";\n\t\t\t\t}\n\t\t} \n\t\telse if(randomz == 1) { \/\/ Right\n\t\t\tcout<< \"Right\\n\";\n\t\t\tif(world->isMoveAble(posX, posY+1)->getValue() != 2) {\n\t\t\t\tposY += 1;\n\t\t\t\tmoveAble = false;\n\t\t\t} else {\n\t\t\t\t\tcout<< \"Its a wall\\n\";\n\t\t\t\t}\n\t\t}\n\t\telse if(randomz == 2) { \/\/ Up\n\t\t\tcout<< \"Up wards\\n\";\n\t\t\tif(world->isMoveAble(posX-1, posY)->getValue() != 2) {\n\t\t\t\tposX -= 1;\n\t\t\t\tmoveAble = false;\n\t\t\t} else {\n\t\t\t\t\tcout<< \"Its a wall\\n\";\n\t\t\t\t}\n\t\t}\n\t\telse if(randomz == 3) { \/\/ Left\n\t\t\tcout<< \"Left\\n\";\n\t\t\tif(world->isMoveAble(posX, posY-1)->getValue() != 2) {\n\t\t\t\tposY -= 1;\n\t\t\t\tmoveAble = false;\n\t\t\t} else {\n\t\t\t\t\tcout<< \"Its a wall\\n\";\n\t\t\t\t}\n\t\t}\n\t}\n\n\tpositionNode = world->isMoveAble(posX, posY);\n\n\tpositionNode->visit();\n\tstd::cout<< \"Moved to x: \"<codetweak#include \"Agent.h\"\n#include \"Environment.h\"\n#include \"Include.h\"\n\nusing namespace std;\n\nAgent::Agent(Environment* _world){\n\t\n\tsrand( time(NULL) );\n\trunning = false;\n\t\n\tsteps = 0;\n\t\n\tposX = 0;\n\tposY = 0;\n\t\n\tworld = _world;\n\tpositionNode = _world->SetStartNode();\n}\n\nAgent::~Agent(void){\n\n\tdelete positionNode;\n}\n\nint Agent::Run(){\n\n\trunning = true;\n\t\n\t\/\/running until environment is clean\n\twhile (running) {\n\t\tsystem(\"CLS\");\n\t\tworld->draw(posX, posY);\n\t\tVacuum();\n\t\tMove();\n\t\t\n\t\t\/\/will end if taking more than 1k steps.\n\t\tsteps++;\n\t\tif(steps > 1000) {\n\t\t\trunning = false;\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n};\n\nvoid Agent::Vacuum() {\n\n\tif ( positionNode->getValue() == 0 ) {\n\t\t\/\/Sleep(300);\n\t\tcout << \"Node is clean\" << std::endl;\n\t}\n\telse {\n\n\t\t\/\/Sleep(300);\n\t\tstd::cout<< \"I am vacuuming here now, soon clean...\";\n\t\t\/\/Sleep(300);\n\t\tstd::cout<< \" Clean!\"<< std::endl;\n\n\t\tpositionNode->setValue(0);\n\t}\n}\n\nvoid Agent::Move() {\n\n\t\n\tstd::cout<< \"Moving to next - \";\n\n\t\/\/Sleep(1000);\n\n\t\/\/ TODO: Check for wals, dont move towards them!\n\n\tfor(int i = 0; i < 4; i++) {\n\n\n\t}\n\n\n\tbool moveAble = true;\n\tint randomz;\n\twhile( moveAble ) {\n\t\trandomz = rand() % 4;\n\t\tif(randomz == 0) { \/\/ Down\n\t\t\tcout<< \"Down wards\\n\";\n\t\t\tif(world->isMoveAble(posX+1, posY)->getValue() != 2) {\n\t\t\t\tposX += 1;\n\t\t\t\tmoveAble = false;\n\t\t\t} else {\n\t\t\t\t\tcout<< \"Its a wall\\n\";\n\t\t\t\t}\n\t\t} \n\t\telse if(randomz == 1) { \/\/ Right\n\t\t\tcout<< \"Right\\n\";\n\t\t\tif(world->isMoveAble(posX, posY+1)->getValue() != 2) {\n\t\t\t\tposY += 1;\n\t\t\t\tmoveAble = false;\n\t\t\t} else {\n\t\t\t\t\tcout<< \"Its a wall\\n\";\n\t\t\t\t}\n\t\t}\n\t\telse if(randomz == 2) { \/\/ Up\n\t\t\tcout<< \"Up wards\\n\";\n\t\t\tif(world->isMoveAble(posX-1, posY)->getValue() != 2) {\n\t\t\t\tposX -= 1;\n\t\t\t\tmoveAble = false;\n\t\t\t} else {\n\t\t\t\t\tcout<< \"Its a wall\\n\";\n\t\t\t\t}\n\t\t}\n\t\telse if(randomz == 3) { \/\/ Left\n\t\t\tcout<< \"Left\\n\";\n\t\t\tif(world->isMoveAble(posX, posY-1)->getValue() != 2) {\n\t\t\t\tposY -= 1;\n\t\t\t\tmoveAble = false;\n\t\t\t} else {\n\t\t\t\t\tcout<< \"Its a wall\\n\";\n\t\t\t\t}\n\t\t}\n\t}\n\n\tpositionNode = world->isMoveAble(posX, posY);\n\n\tpositionNode->visit();\n\tstd::cout<< \"Moved to x: \"<"} {"text":"\/**\n * Based on: https:\/\/github.com\/davetcoleman\/ros_control_boilerplate\n *\/\n\n#include \n#include \n\/\/ #include \n\/\/ #include \n\n#define SYSFS_GPIO_DIR \"\/sys\/class\/gpio\"\n#define SYSFS_PWM_DIR \"\/sys\/devices\/platform\/pwm-ctrl\"\n#define MAX_BUF 256\n\n\/\/ Temp place-holder for some sysfs code.\nint pwm_status(unsigned int pwm, bool enable) {\n int fd;\n char buf[MAX_BUF];\n\n \/\/ First check current value, only update if changed.\n char curr[11];\n int status;\n snprintf(buf, sizeof(buf), SYSFS_PWM_DIR \"\/enable%d\", pwm);\n fd = open(buf, sizeof(buf), O_RDONLY);\n if (fd < 0) {\n perror(\"pwm\/enable\/read\");\n return fd;\n }\n read(fd, curr, sizeof(curr));\n close(fd);\n \n \/\/ \"On\" always ends with \"n\". \n status = (curr[strlen(curr)-2] == 'n');\n\n if (status != enable) {\n ROS_INFO_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"Chan: \" << pwm << \" Enable: \" << enable);\n\n snprintf(buf, sizeof(buf), SYSFS_PWM_DIR \"\/enable%d\", pwm);\n fd = open(buf, O_WRONLY);\n if (fd < 0) {\n perror(\"pwm\/enable\/write\");\n return fd;\n }\n\n if (enable)\n write(fd, \"1\", 2);\n else\n write(fd, \"0\", 2);\n\n close(fd);\n }\n return 0;\n}\n\nint pwm_freq(unsigned int pwm, unsigned int freq) {\n int fd;\n char buf[MAX_BUF];\n\n \/\/ First check current value, only update if changed.\n char curr[11];\n int status;\n snprintf(buf, sizeof(buf), SYSFS_PWM_DIR \"\/freq%d\", pwm);\n fd = open(buf, sizeof(buf), O_RDONLY);\n if (fd < 0) {\n perror(\"pwm\/freq\/read\");\n return fd;\n }\n read(fd, curr, sizeof(curr));\n close(fd);\n\n if (atoi(curr) != freq && freq >= 1) {\n ROS_INFO_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"Chan: \" << pwm << \" Freq: \" << freq);\n\n snprintf(buf, sizeof(buf), SYSFS_PWM_DIR \"\/freq%d\", pwm);\n fd = open(buf, O_WRONLY);\n if (fd < 0) {\n perror(\"pwm\/freq\/write\");\n return fd;\n }\n\n int len = snprintf(buf, sizeof(buf), \"%d\", freq);\n write(fd, buf, len);\n close(fd);\n }\n return 0;\n}\n\nint gpio_set(unsigned int gpio, unsigned int value) {\n int fd;\n char buf[MAX_BUF];\n\n snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR \"\/gpio%d\/value\", gpio);\n fd = open(buf, O_WRONLY);\n if (fd < 0) {\n perror(\"gpio\/set-value\");\n return fd;\n }\n\n if (value)\n write(fd, \"1\", 2);\n else\n write(fd, \"0\", 2);\n\n close(fd);\n return 0;\n}\n\nnamespace kulbu_hardware {\n\nKulbuHardwareInterface::KulbuHardwareInterface(\n ros::NodeHandle& nh,\n int joint_mode)\n : nh_(nh),\n joint_mode_(joint_mode) {\n \/\/ Initialize shared memory and interfaces here\n init(); \/\/ this implementation loads from rosparam\n\n ROS_INFO_NAMED(\"kulbu_hardware_interface\",\n \"Loaded kulbu_hardware_interface.\");\n}\n\nvoid KulbuHardwareInterface::init() {\n ROS_INFO_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"Reading rosparams from namespace: \" << nh_.getNamespace());\n\n nh_.getParam(\"hardware_interface\/steps_per_m\", steps_per_m_);\n if (!steps_per_m_ > 0) {\n ROS_FATAL_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"No step per metre found on parameter server.\"\n << \" Namespace: \" << nh_.getNamespace());\n exit(-1);\n }\n\n \/\/ Get joint names\n nh_.getParam(\"hardware_interface\/joints\", joint_names_);\n if (joint_names_.size() == 0) {\n ROS_FATAL_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"No joints found on parameter server\"\n << \" Namespace: \" << nh_.getNamespace());\n exit(-1);\n }\n num_joints_ = joint_names_.size();\n\n nh_.getParam(\"hardware_interface\/dirs\", pin_dirs_);\n if (pin_dirs_.size() == 0) {\n ROS_FATAL_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"No GPIO direction pins found on parameter server.\"\n << \" Namespace: \" << nh_.getNamespace());\n exit(-1);\n }\n\n nh_.getParam(\"hardware_interface\/steps\", pin_steps_);\n if (pin_steps_.size() == 0) {\n ROS_FATAL_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"No GPIO step pins found on parameter server.\"\n << \" Namespace: \" << nh_.getNamespace());\n exit(-1);\n }\n\n \/\/ Resize vectors\n joint_position_.resize(num_joints_);\n joint_velocity_.resize(num_joints_);\n joint_effort_.resize(num_joints_);\n joint_position_command_.resize(num_joints_);\n joint_velocity_command_.resize(num_joints_);\n joint_effort_command_.resize(num_joints_);\n\n \/\/ Initialise GPIO\n \/\/ wiringPiSetupSys();\n \/\/ FIXME: Ensure duty cycle is correct.\n \/\/ `512 > \/sys\/devices\/platform\/pwm-ctrl\/duty0`\n\n \/\/ Initialize controller\n for (std::size_t i = 0; i < num_joints_; ++i) {\n ROS_DEBUG_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"Loading joint name: \" << joint_names_[i]);\n\n \/\/ Set direction pins to forward by default.\n \/\/ pinMode(pin_dirs_[i], OUTPUT);\n \/\/ digitalWrite(pin_dirs_[i], LOW);\n\n \/\/ Create PWM tone generator for joint\n \/\/ pinMode(pin_steps_[i], SOFT_TONE_OUTPUT);\n \/\/ softToneCreate(pin_steps_[i]);\n\n \/\/ Start with PWM turned off.\n pwm_status(pin_steps_[i], 0);\n \/\/ Start going forward.\n gpio_set(pin_dirs_[i], 0);\n\n \/\/ Create joint state interface\n joint_state_interface_.registerHandle(hardware_interface::JointStateHandle(\n joint_names_[i],\n &joint_position_[i],\n &joint_velocity_[i],\n &joint_effort_[i]));\n\n switch (joint_mode_) {\n case 0:\n \/\/ Create position joint interface\n position_joint_interface_\n .registerHandle(hardware_interface::JointHandle(\n joint_state_interface_.getHandle(\n joint_names_[i]),\n &joint_position_command_[i]));\n break;\n\n case 1:\n \/\/ Create velocity joint interface\n velocity_joint_interface_\n .registerHandle(hardware_interface::JointHandle(\n joint_state_interface_.getHandle(\n joint_names_[i]),\n &joint_velocity_command_[i]));\n break;\n\n case 2:\n \/\/ Create effort joint interface\n effort_joint_interface_\n .registerHandle(hardware_interface::JointHandle(\n joint_state_interface_.getHandle(\n joint_names_[i]),\n &joint_effort_command_[i]));\n break;\n }\n }\n\n registerInterface(&joint_state_interface_); \/\/ From RobotHW base class.\n registerInterface(&position_joint_interface_); \/\/ From RobotHW base class.\n registerInterface(&velocity_joint_interface_); \/\/ From RobotHW base class.\n registerInterface(&effort_joint_interface_); \/\/ From RobotHW base class.\n}\n\nvoid KulbuHardwareInterface::read(ros::Duration elapsed_time) {\n \/\/ Read the joint states from your hardware here\n \/\/ e.g.\n \/\/ for (std::size_t i = 0; i < num_joints_; ++i)\n \/\/ {\n \/\/ joint_position_[i] = robot_api_.getJointPosition(i);\n \/\/ joint_velocity_[i] = robot_api_.getJointVelocity(i);\n \/\/ joint_effort_[i] = robot_api_.getJointEffort(i);\n \/\/ }\n}\n\nvoid KulbuHardwareInterface::write(ros::Duration elapsed_time) {\n int freq = 0;\n int dir = 0;\n\n \/\/ Send commands in different modes\n for (std::size_t i = 0; i < num_joints_; ++i) {\n \/\/ Skip joints with no pins defined\n if (pin_dirs_[i] == -1 || pin_steps_[i] == -1) continue;\n\n switch (joint_mode_) {\n case 1: \/\/ hardware_interface::MODE_VELOCITY:\n \/\/ Calc PWM frequency.\n freq = joint_velocity_command_[i] * steps_per_m_;\n\n \/\/ Reverse flips direction.\n if (freq < 0) {\n freq = abs(freq);\n dir = 1;\n } else {\n dir = 0;\n }\n\n \/\/ Disable PWM when stopped.\n if (freq < 1) {\n freq = 0;\n pwm_status(pin_steps_[i], 0);\n \/\/ FIXME: Only if previously deactivated.\n } else {\n pwm_status(pin_steps_[i], 1);\n }\n\n \/\/ Set direction pin\n \/\/ digitalWrite(pin_dirs_[i], dir);\n gpio_set(pin_dirs_[i], dir);\n\n \/\/ Set PWM frequency\n \/\/ softToneWrite(pin_steps_[i], freq);\n pwm_freq(pin_steps_[i], freq);\n\n ROS_DEBUG_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"\\ni: \" << i <<\n \"\\ncmd: \" << joint_velocity_command_[i] <<\n \"\\ndist: \" << steps_per_m_ <<\n \"\\nfreq: \" << freq <<\n \"\\ndir: \" << dir <<\n \"\\njoint: \" << joint_names_[i] <<\n \"\\ndir: \" << pin_dirs_[i] <<\n \"\\nstep: \" << pin_steps_[i]);\n break;\n\n default:\n ROS_ERROR_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"Joint mode not implemented\");\n break;\n }\n }\n}\n\n\n} \/\/ namespace kulbu_hardware\nCleanup and duty-cycle\/**\n * Based on: https:\/\/github.com\/davetcoleman\/ros_control_boilerplate\n *\/\n\n#include \n#include \n\n#define SYSFS_GPIO_DIR \"\/sys\/class\/gpio\"\n#define SYSFS_PWM_DIR \"\/sys\/devices\/platform\/pwm-ctrl\"\n#define MAX_BUF 256\n\n\/\/ FIXME: Encapsulate this IO code.\nint pwm_enable(unsigned int pwm, bool enable) {\n int fd;\n char buf[MAX_BUF];\n\n \/\/ First check current value, only update if changed.\n char curr[11];\n int status;\n snprintf(buf, sizeof(buf), SYSFS_PWM_DIR \"\/enable%d\", pwm);\n fd = open(buf, sizeof(buf), O_RDONLY);\n if (fd < 0) {\n perror(\"pwm\/enable\/read\");\n return fd;\n }\n read(fd, curr, sizeof(curr));\n close(fd);\n\n \/\/ \"On\" always ends with an \"n\".\n status = (curr[strlen(curr)-2] == 'n');\n\n if (status != enable) {\n ROS_DEBUG_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"Chan: \" << pwm << \" Enable: \" << enable);\n\n snprintf(buf, sizeof(buf), SYSFS_PWM_DIR \"\/enable%d\", pwm);\n fd = open(buf, O_WRONLY);\n if (fd < 0) {\n perror(\"pwm\/enable\/write\");\n return fd;\n }\n\n if (enable)\n write(fd, \"1\", 2);\n else\n write(fd, \"0\", 2);\n\n close(fd);\n }\n return 0;\n}\n\nint pwm_freq(unsigned int pwm, unsigned int freq) {\n int fd;\n char buf[MAX_BUF];\n\n \/\/ First check current value, only update if changed.\n char curr[11];\n int status;\n snprintf(buf, sizeof(buf), SYSFS_PWM_DIR \"\/freq%d\", pwm);\n fd = open(buf, sizeof(buf), O_RDONLY);\n if (fd < 0) {\n perror(\"pwm\/freq\/read\");\n return fd;\n }\n read(fd, curr, sizeof(curr));\n close(fd);\n\n if (atoi(curr) != freq && freq >= 1) {\n ROS_DEBUG_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"Chan: \" << pwm << \" Freq: \" << freq);\n\n snprintf(buf, sizeof(buf), SYSFS_PWM_DIR \"\/freq%d\", pwm);\n fd = open(buf, O_WRONLY);\n if (fd < 0) {\n perror(\"pwm\/freq\/write\");\n return fd;\n }\n\n int len = snprintf(buf, sizeof(buf), \"%d\", freq);\n write(fd, buf, len);\n close(fd);\n }\n return 0;\n}\n\nint pwm_duty(unsigned int pwm, unsigned int duty) {\n int fd;\n char buf[MAX_BUF];\n\n ROS_DEBUG_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"Chan: \" << pwm << \" Duty: \" << duty);\n\n snprintf(buf, sizeof(buf), SYSFS_PWM_DIR \"\/duty%d\", pwm);\n fd = open(buf, O_WRONLY);\n if (fd < 0) {\n perror(\"pwm\/duty\/write\");\n return fd;\n }\n\n int len = snprintf(buf, sizeof(buf), \"%d\", duty);\n write(fd, buf, len);\n close(fd);\n\n return 0;\n}\n\nint gpio_set(unsigned int gpio, unsigned int value) {\n int fd;\n char buf[MAX_BUF];\n\n ROS_DEBUG_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"GPIO: \" << gpio << \" Value: \" << value);\n\n snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR \"\/gpio%d\/value\", gpio);\n fd = open(buf, O_WRONLY);\n if (fd < 0) {\n perror(\"gpio\/set-value\");\n return fd;\n }\n\n if (value)\n write(fd, \"1\", 2);\n else\n write(fd, \"0\", 2);\n\n close(fd);\n return 0;\n}\n\nnamespace kulbu_hardware {\n\nKulbuHardwareInterface::KulbuHardwareInterface(\n ros::NodeHandle& nh,\n int joint_mode)\n : nh_(nh),\n joint_mode_(joint_mode) {\n \/\/ Initialize shared memory and interfaces here\n init(); \/\/ this implementation loads from rosparam\n\n ROS_INFO_NAMED(\"kulbu_hardware_interface\",\n \"Loaded kulbu_hardware_interface.\");\n}\n\nvoid KulbuHardwareInterface::init() {\n ROS_INFO_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"Reading rosparams from namespace: \" << nh_.getNamespace());\n\n nh_.getParam(\"hardware_interface\/steps_per_m\", steps_per_m_);\n if (!steps_per_m_ > 0) {\n ROS_FATAL_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"No step per metre found on parameter server.\"\n << \" Namespace: \" << nh_.getNamespace());\n exit(-1);\n }\n\n \/\/ Get joint names\n nh_.getParam(\"hardware_interface\/joints\", joint_names_);\n if (joint_names_.size() == 0) {\n ROS_FATAL_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"No joints found on parameter server\"\n << \" Namespace: \" << nh_.getNamespace());\n exit(-1);\n }\n num_joints_ = joint_names_.size();\n\n nh_.getParam(\"hardware_interface\/dirs\", pin_dirs_);\n if (pin_dirs_.size() == 0) {\n ROS_FATAL_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"No GPIO direction pins found on parameter server.\"\n << \" Namespace: \" << nh_.getNamespace());\n exit(-1);\n }\n\n nh_.getParam(\"hardware_interface\/steps\", pin_steps_);\n if (pin_steps_.size() == 0) {\n ROS_FATAL_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"No GPIO step pins found on parameter server.\"\n << \" Namespace: \" << nh_.getNamespace());\n exit(-1);\n }\n\n \/\/ Resize vectors\n joint_position_.resize(num_joints_);\n joint_velocity_.resize(num_joints_);\n joint_effort_.resize(num_joints_);\n joint_position_command_.resize(num_joints_);\n joint_velocity_command_.resize(num_joints_);\n joint_effort_command_.resize(num_joints_);\n\n \/\/ Initialize controller\n for (std::size_t i = 0; i < num_joints_; ++i) {\n ROS_DEBUG_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"Loading joint name: \" << joint_names_[i]);\n\n \/\/ Start with PWM turned off and 50\/50 duty cycle.\n pwm_enable(pin_steps_[i], 0);\n pwm_duty(pin_steps_[i], 512);\n\n \/\/ Set direction pins to forward by default.\n gpio_set(pin_dirs_[i], 0);\n\n \/\/ Create joint state interface\n joint_state_interface_.registerHandle(hardware_interface::JointStateHandle(\n joint_names_[i],\n &joint_position_[i],\n &joint_velocity_[i],\n &joint_effort_[i]));\n\n switch (joint_mode_) {\n case 0:\n \/\/ Create position joint interface\n position_joint_interface_\n .registerHandle(hardware_interface::JointHandle(\n joint_state_interface_.getHandle(\n joint_names_[i]),\n &joint_position_command_[i]));\n break;\n\n case 1:\n \/\/ Create velocity joint interface\n velocity_joint_interface_\n .registerHandle(hardware_interface::JointHandle(\n joint_state_interface_.getHandle(\n joint_names_[i]),\n &joint_velocity_command_[i]));\n break;\n\n case 2:\n \/\/ Create effort joint interface\n effort_joint_interface_\n .registerHandle(hardware_interface::JointHandle(\n joint_state_interface_.getHandle(\n joint_names_[i]),\n &joint_effort_command_[i]));\n break;\n }\n }\n\n registerInterface(&joint_state_interface_); \/\/ From RobotHW base class.\n registerInterface(&position_joint_interface_); \/\/ From RobotHW base class.\n registerInterface(&velocity_joint_interface_); \/\/ From RobotHW base class.\n registerInterface(&effort_joint_interface_); \/\/ From RobotHW base class.\n}\n\nvoid KulbuHardwareInterface::read(ros::Duration elapsed_time) {\n \/\/ Read the joint states from your hardware here\n \/\/ e.g.\n \/\/ for (std::size_t i = 0; i < num_joints_; ++i)\n \/\/ {\n \/\/ joint_position_[i] = robot_api_.getJointPosition(i);\n \/\/ joint_velocity_[i] = robot_api_.getJointVelocity(i);\n \/\/ joint_effort_[i] = robot_api_.getJointEffort(i);\n \/\/ }\n}\n\nvoid KulbuHardwareInterface::write(ros::Duration elapsed_time) {\n int freq = 0;\n int dir = 0;\n\n \/\/ Send commands in different modes\n for (std::size_t i = 0; i < num_joints_; ++i) {\n \/\/ Skip joints with no pins defined\n if (pin_dirs_[i] == -1 || pin_steps_[i] == -1) continue;\n\n switch (joint_mode_) {\n case 1: \/\/ hardware_interface::MODE_VELOCITY:\n \/\/ Calc PWM frequency.\n freq = joint_velocity_command_[i] * steps_per_m_;\n\n \/\/ Reverse flips direction.\n if (freq < 0) {\n freq = abs(freq);\n dir = 1;\n } else {\n dir = 0;\n }\n\n \/\/ Disable PWM when stopped.\n if (freq < 1) {\n freq = 0;\n pwm_enable(pin_steps_[i], 0);\n } else {\n pwm_enable(pin_steps_[i], 1);\n }\n\n \/\/ Set direction pin.\n gpio_set(pin_dirs_[i], dir);\n\n \/\/ Set PWM frequency.\n pwm_freq(pin_steps_[i], freq);\n\n ROS_DEBUG_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"\\ni: \" << i <<\n \"\\ncmd: \" << joint_velocity_command_[i] <<\n \"\\ndist: \" << steps_per_m_ <<\n \"\\nfreq: \" << freq <<\n \"\\ndir: \" << dir <<\n \"\\njoint: \" << joint_names_[i] <<\n \"\\ndir: \" << pin_dirs_[i] <<\n \"\\nstep: \" << pin_steps_[i]);\n break;\n\n default:\n ROS_ERROR_STREAM_NAMED(\"kulbu_hardware_interface\",\n \"Joint mode not implemented\");\n break;\n }\n }\n}\n\n\n} \/\/ namespace kulbu_hardware\n<|endoftext|>"} {"text":"\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \n#include \"condor_adtypes.h\"\n\nstruct Lookup {\n\tchar\tstr[20];\n\tAdTypes\t\ttype;\n};\nstatic const Lookup adtypes [] =\n{\n\t{ QUILL_ADTYPE,\t\t\tQUILL_AD, },\n\t{ STARTD_ADTYPE,\t\tSTARTD_AD, },\n\t{ SCHEDD_ADTYPE,\t\tSCHEDD_AD, },\n\t{ MASTER_ADTYPE,\t\tMASTER_AD, },\n\t{ GATEWAY_ADTYPE,\t\tGATEWAY_AD, },\n\t{ CKPT_SRVR_ADTYPE,\t\tCKPT_SRVR_AD, },\n\t{ STARTD_PVT_ADTYPE,\tSTARTD_PVT_AD, },\n\t{ SUBMITTER_ADTYPE,\t\tSUBMITTOR_AD, },\n\t{ COLLECTOR_ADTYPE,\t\tCOLLECTOR_AD, },\n\t{ LICENSE_ADTYPE,\t\tLICENSE_AD, },\n\t{ STORAGE_ADTYPE,\t\tSTORAGE_AD, },\n\t{ ANY_ADTYPE,\t\t\tANY_AD, },\n\t{ BOGUS_ADTYPE,\t\t\tBOGUS_AD, },\n\t{ CLUSTER_ADTYPE,\t\tCLUSTER_AD, },\n\t{ NEGOTIATOR_ADTYPE,\tNEGOTIATOR_AD, },\n\t{ HAD_ADTYPE,\t\t\tHAD_AD, },\n\t{ GENERIC_ADTYPE,\t\tGENERIC_AD, },\n\t{ CREDD_ADTYPE,\t\t\tCREDD_AD, },\n\t{ DATABASE_ADTYPE,\t\tDATABASE_AD, },\n\t{ DBMSD_ADTYPE,\t\t\tDBMSD_AD, },\n\t{ TT_ADTYPE,\t\t\tTT_AD, },\n\t{ GRID_ADTYPE, \t\t\tGRID_AD, },\n\t{ XFER_SERVICE_ADTYPE,\tXFER_SERVICE_AD, },\n\t{ LEASE_MANAGER_ADTYPE,\tLEASE_MANAGER_AD, },\n\t{ \"\",\t\tNO_AD, },\n};\n\nAdTypes\nAdTypeFromString(const char* adtype_string) \n{\n\tconst Lookup\t*v;\n\tfor( v=adtypes; v->type != NO_AD; v++ ) {\n\t\tif( !strcasecmp(v->str, adtype_string) ) {\n\t\t\treturn v->type;\n\t\t}\n\t}\n\treturn NO_AD;\n}\n\nconst char*\nAdTypeToString( AdTypes type )\n{\n\tif( (type >= (AdTypes)0) && (type < NUM_AD_TYPES) ) {\n\t\treturn adtypes[type].str;\n\t} else {\n\t\treturn \"Unknown\";\n\t}\n}\nAdd missing ad types to Adtypes array\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \n#include \"condor_adtypes.h\"\n\nstruct Lookup {\n\tchar\tstr[20];\n\tAdTypes\t\ttype;\n};\nstatic const Lookup adtypes [] =\n{\n\t{ QUILL_ADTYPE,\t\t\tQUILL_AD, },\n\t{ STARTD_ADTYPE,\t\tSTARTD_AD, },\n\t{ SCHEDD_ADTYPE,\t\tSCHEDD_AD, },\n\t{ MASTER_ADTYPE,\t\tMASTER_AD, },\n\t{ GATEWAY_ADTYPE,\t\tGATEWAY_AD, },\n\t{ CKPT_SRVR_ADTYPE,\t\tCKPT_SRVR_AD, },\n\t{ STARTD_PVT_ADTYPE,\tSTARTD_PVT_AD, },\n\t{ SUBMITTER_ADTYPE,\t\tSUBMITTOR_AD, },\n\t{ COLLECTOR_ADTYPE,\t\tCOLLECTOR_AD, },\n\t{ LICENSE_ADTYPE,\t\tLICENSE_AD, },\n\t{ STORAGE_ADTYPE,\t\tSTORAGE_AD, },\n\t{ ANY_ADTYPE,\t\t\tANY_AD, },\n\t{ BOGUS_ADTYPE,\t\t\tBOGUS_AD, },\n\t{ CLUSTER_ADTYPE,\t\tCLUSTER_AD, },\n\t{ NEGOTIATOR_ADTYPE,\tNEGOTIATOR_AD, },\n\t{ HAD_ADTYPE,\t\t\tHAD_AD, },\n\t{ GENERIC_ADTYPE,\t\tGENERIC_AD, },\n\t{ CREDD_ADTYPE,\t\t\tCREDD_AD, },\n\t{ DATABASE_ADTYPE,\t\tDATABASE_AD, },\n\t{ DBMSD_ADTYPE,\t\t\tDBMSD_AD, },\n\t{ TT_ADTYPE,\t\t\tTT_AD, },\n\t{ GRID_ADTYPE, \t\t\tGRID_AD, },\n\t{ XFER_SERVICE_ADTYPE,\tXFER_SERVICE_AD, },\n\t{ LEASE_MANAGER_ADTYPE,\tLEASE_MANAGER_AD, },\n\t{ DEFRAG_ADTYPE,\t\tDEFRAG_AD, },\n\t{ ACCOUNTING_ADTYPE,\tACCOUNTING_AD, },\n\t{ \"\",\t\tNO_AD, },\n};\n\nAdTypes\nAdTypeFromString(const char* adtype_string) \n{\n\tconst Lookup\t*v;\n\tfor( v=adtypes; v->type != NO_AD; v++ ) {\n\t\tif( !strcasecmp(v->str, adtype_string) ) {\n\t\t\treturn v->type;\n\t\t}\n\t}\n\treturn NO_AD;\n}\n\nconst char*\nAdTypeToString( AdTypes type )\n{\n\tif( (type >= (AdTypes)0) && (type < NUM_AD_TYPES) ) {\n\t\treturn adtypes[type].str;\n\t} else {\n\t\treturn \"Unknown\";\n\t}\n}\n<|endoftext|>"} {"text":"#include \"rdsstring.h\"\n\n#include \n\n#include \"data.h\"\n\nnamespace redsea {\n\nnamespace {\n\nstd::string rtrim(std::string s) {\n s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun(std::isspace))).base(), s.end());\n return s;\n}\n\n}\n\nRDSString::RDSString(int len) : chars_(len), is_char_sequential_(len),\n prev_pos_(-1) {\n last_complete_string_ = getString();\n}\n\nvoid RDSString::setAt(int pos, int chr) {\n if (pos < 0 || pos >= (int)chars_.size())\n return;\n\n chars_[pos] = chr;\n\n if (pos != prev_pos_ + 1) {\n for (size_t i=0; i= lengthExpected();\n}\n\nvoid RDSString::clear() {\n for (size_t i=0; ithis is C++17 stuff#include \"rdsstring.h\"\n\n#include \n\n#include \"data.h\"\n\nnamespace redsea {\n\nnamespace {\n\nstd::string rtrim(std::string s) {\n return s;\n}\n\n}\n\nRDSString::RDSString(int len) : chars_(len), is_char_sequential_(len),\n prev_pos_(-1) {\n last_complete_string_ = getString();\n}\n\nvoid RDSString::setAt(int pos, int chr) {\n if (pos < 0 || pos >= (int)chars_.size())\n return;\n\n chars_[pos] = chr;\n\n if (pos != prev_pos_ + 1) {\n for (size_t i=0; i= lengthExpected();\n}\n\nvoid RDSString::clear() {\n for (size_t i=0; i"} {"text":"#include \"src\/rdsstring.h\"\n\n#include \n\n#include \"src\/tables.h\"\n\nnamespace redsea {\n\nnamespace {\n\nstd::string rtrim(std::string s) {\n return s.erase(s.find_last_not_of(' ')+1);\n}\n\n}\n\nLCDchar::LCDchar() : code_(0) {\n}\n\nLCDchar::LCDchar(uint8_t _code) : code_(_code) {\n}\n\nuint8_t LCDchar::getCode() const {\n return code_;\n}\n\nstd::string LCDchar::toString() const {\n return getLCDchar(code_);\n}\n\nRDSString::RDSString(int len) : chars_(len), is_char_sequential_(len),\n prev_pos_(-1), last_complete_string_(getString()) {\n}\n\nvoid RDSString::setAt(int pos, LCDchar chr) {\n if (pos < 0 || pos >= static_cast(chars_.size()))\n return;\n\n chars_.at(pos) = chr;\n\n if (pos != prev_pos_ + 1) {\n for (size_t i=0; i < is_char_sequential_.size(); i++)\n is_char_sequential_[i] = false;\n }\n\n is_char_sequential_.at(pos) = true;\n\n if (isComplete()) {\n last_complete_string_ = getString();\n last_complete_chars_ = getChars();\n }\n\n prev_pos_ = pos;\n}\n\nstd::string RDSString::charAt(int pos) const {\n return (pos < static_cast(last_complete_chars_.size()) ?\n last_complete_chars_[pos].toString() : \" \");\n}\n\nsize_t RDSString::lengthReceived() const {\n size_t result = 0;\n for (size_t i=0; i < is_char_sequential_.size(); i++) {\n if (!is_char_sequential_[i])\n break;\n result = i+1;\n }\n\n return result;\n}\n\nsize_t RDSString::lengthExpected() const {\n size_t result = chars_.size();\n\n for (size_t i=0; i < chars_.size(); i++) {\n if (chars_[i].getCode() == 0x0D) {\n result = i;\n break;\n }\n }\n\n return result;\n}\n\nvoid RDSString::resize(int n) {\n chars_.resize(n, 32);\n}\n\nstd::string RDSString::getString() const {\n std::string result;\n for (LCDchar chr : getChars()) {\n result += chr.toString();\n }\n\n return result;\n}\n\nstd::vector RDSString::getChars() const {\n std::vector result;\n size_t len = lengthExpected();\n for (size_t i=0; i < len; i++) {\n result.push_back(is_char_sequential_[i] ? chars_[i] : 32);\n }\n\n return result;\n}\n\nstd::string RDSString::getTrimmedString() const {\n return rtrim(getString());\n}\n\nstd::string RDSString::getLastCompleteString() const {\n return last_complete_string_;\n}\n\nstd::string RDSString::getLastCompleteString(int start, int len) const {\n std::string result;\n for (int i=start; i < start+len; i++) {\n result += (i < static_cast(last_complete_chars_.size()) ?\n last_complete_chars_[i].toString() : \" \");\n }\n\n return result;\n}\n\nstd::string RDSString::getLastCompleteStringTrimmed() const {\n return rtrim(last_complete_string_);\n}\n\nstd::string RDSString::getLastCompleteStringTrimmed(int start, int len) const {\n return rtrim(getLastCompleteString(start, len));\n}\n\nbool RDSString::hasChars(int start, int len) const {\n return start+len <= static_cast(last_complete_chars_.size());\n}\n\nbool RDSString::isComplete() const {\n return lengthReceived() >= lengthExpected();\n}\n\nvoid RDSString::clear() {\n for (size_t i=0; i < chars_.size(); i++) {\n is_char_sequential_[i] = false;\n }\n last_complete_string_ = getString();\n last_complete_chars_.clear();\n}\n\n} \/\/ namespace redsea\n0x2 to signify ascii value#include \"src\/rdsstring.h\"\n\n#include \n\n#include \"src\/tables.h\"\n\nnamespace redsea {\n\nnamespace {\n\nstd::string rtrim(std::string s) {\n return s.erase(s.find_last_not_of(' ')+1);\n}\n\n}\n\nLCDchar::LCDchar() : code_(0) {\n}\n\nLCDchar::LCDchar(uint8_t _code) : code_(_code) {\n}\n\nuint8_t LCDchar::getCode() const {\n return code_;\n}\n\nstd::string LCDchar::toString() const {\n return getLCDchar(code_);\n}\n\nRDSString::RDSString(int len) : chars_(len), is_char_sequential_(len),\n prev_pos_(-1), last_complete_string_(getString()) {\n}\n\nvoid RDSString::setAt(int pos, LCDchar chr) {\n if (pos < 0 || pos >= static_cast(chars_.size()))\n return;\n\n chars_.at(pos) = chr;\n\n if (pos != prev_pos_ + 1) {\n for (size_t i=0; i < is_char_sequential_.size(); i++)\n is_char_sequential_[i] = false;\n }\n\n is_char_sequential_.at(pos) = true;\n\n if (isComplete()) {\n last_complete_string_ = getString();\n last_complete_chars_ = getChars();\n }\n\n prev_pos_ = pos;\n}\n\nstd::string RDSString::charAt(int pos) const {\n return (pos < static_cast(last_complete_chars_.size()) ?\n last_complete_chars_[pos].toString() : \" \");\n}\n\nsize_t RDSString::lengthReceived() const {\n size_t result = 0;\n for (size_t i=0; i < is_char_sequential_.size(); i++) {\n if (!is_char_sequential_[i])\n break;\n result = i+1;\n }\n\n return result;\n}\n\nsize_t RDSString::lengthExpected() const {\n size_t result = chars_.size();\n\n for (size_t i=0; i < chars_.size(); i++) {\n if (chars_[i].getCode() == 0x0D) {\n result = i;\n break;\n }\n }\n\n return result;\n}\n\nvoid RDSString::resize(int n) {\n chars_.resize(n, 0x20);\n}\n\nstd::string RDSString::getString() const {\n std::string result;\n for (LCDchar chr : getChars()) {\n result += chr.toString();\n }\n\n return result;\n}\n\nstd::vector RDSString::getChars() const {\n std::vector result;\n size_t len = lengthExpected();\n for (size_t i=0; i < len; i++) {\n result.push_back(is_char_sequential_[i] ? chars_[i] : 32);\n }\n\n return result;\n}\n\nstd::string RDSString::getTrimmedString() const {\n return rtrim(getString());\n}\n\nstd::string RDSString::getLastCompleteString() const {\n return last_complete_string_;\n}\n\nstd::string RDSString::getLastCompleteString(int start, int len) const {\n std::string result;\n for (int i=start; i < start+len; i++) {\n result += (i < static_cast(last_complete_chars_.size()) ?\n last_complete_chars_[i].toString() : \" \");\n }\n\n return result;\n}\n\nstd::string RDSString::getLastCompleteStringTrimmed() const {\n return rtrim(last_complete_string_);\n}\n\nstd::string RDSString::getLastCompleteStringTrimmed(int start, int len) const {\n return rtrim(getLastCompleteString(start, len));\n}\n\nbool RDSString::hasChars(int start, int len) const {\n return start+len <= static_cast(last_complete_chars_.size());\n}\n\nbool RDSString::isComplete() const {\n return lengthReceived() >= lengthExpected();\n}\n\nvoid RDSString::clear() {\n for (size_t i=0; i < chars_.size(); i++) {\n is_char_sequential_[i] = false;\n }\n last_complete_string_ = getString();\n last_complete_chars_.clear();\n}\n\n} \/\/ namespace redsea\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#define GEMMI_WRITE_IMPLEMENTATION\n#include \n#undef GEMMI_WRITE_IMPLEMENTATION\n\n#include \"cif.hh\"\n#include \"freesasa.h\"\n\nstruct ModelDiscriminator {\n ModelDiscriminator(const std::string &model_name,\n const int model_col = 11)\n : _model_name(model_name), _model_col(model_col)\n {\n }\n\n bool operator()(const gemmi::cif::Table::Row &site) const\n {\n return _model_name != site[_model_col];\n }\n\nprivate:\n const std::string _model_name;\n int _model_col;\n};\n\nstruct ModelSetDiscriminator {\n ModelSetDiscriminator(const std::set models,\n const int model_col = 11)\n : _models(models), _model_col(model_col)\n {\n }\n\n bool operator()(const gemmi::cif::Table::Row &site) const\n {\n return _models.count(std::stoi(site[_model_col])) == 0;\n }\n\nprivate:\n const std::set _models;\n int _model_col;\n};\n\nstruct ChainDiscriminator {\n ChainDiscriminator(const std::string &model_name, const std::string &chain_name,\n const int model_col = 11, const int chain_col = 1)\n : _model_name(model_name), _chain_name(chain_name),\n _model_col(model_col), _chain_col(chain_col)\n {\n }\n\n bool operator()(const gemmi::cif::Table::Row &site) const\n {\n return _model_name != site[_model_col] || _chain_name != site[_chain_col];\n }\n\nprivate:\n const std::string _model_name, _chain_name;\n int _model_col, _chain_col;\n};\n\nstatic std::unique_ptr>\nget_models(const gemmi::cif::Document &doc)\n{\n auto models = std::make_unique>();\n for (auto block : doc.blocks) {\n for (auto site : block.find(\"_atom_site.\", {\"pdbx_PDB_model_num\"})) {\n models->insert(gemmi::cif::as_int(site[0]));\n }\n }\n return models;\n}\n\nstatic std::unique_ptr>\nget_chains(const gemmi::cif::Document &doc)\n{\n auto chains = std::make_unique>();\n for (auto block : doc.blocks) {\n for (auto site : block.find(\"_atom_site.\", {\"auth_asym_id\"})) {\n chains->insert(site[0]);\n }\n }\n return chains;\n}\n\nstatic std::unique_ptr>\nget_chains(const gemmi::Model &model)\n{\n auto chains = std::make_unique>();\n\n for (auto &chain : model.chains) {\n chains->insert(chain.name);\n }\n\n return chains;\n}\n\nstatic const auto atom_site_columns = std::vector({\n \"group_PDB\",\n \"auth_asym_id\",\n \"auth_seq_id\",\n \"pdbx_PDB_ins_code\",\n \"auth_comp_id\",\n \"auth_atom_id\",\n \"label_alt_id\",\n \"type_symbol\",\n \"Cartn_x\",\n \"Cartn_y\",\n \"Cartn_z\",\n \"pdbx_PDB_model_num\",\n});\n\nstatic freesasa_cif_atom\nfreesasa_atom_from_site(const gemmi::cif::Table::Row &site)\n{\n\n std::unique_ptr auth_atom_id;\n \/\/ remove quotation marks if necessary\n if (site[5][0] == '\"') {\n auth_atom_id = std::make_unique(site[5].substr(1, site[5].size() - 2));\n }\n\n return {\n .group_PDB = site[0].c_str(),\n .auth_asym_id = site[1][0],\n .auth_seq_id = site[2].c_str(),\n .pdbx_PDB_ins_code = site[3].c_str(),\n .auth_comp_id = site[4].c_str(),\n .auth_atom_id = auth_atom_id ? std::move(*auth_atom_id).c_str() : site[5].c_str(),\n .label_alt_id = site[6].c_str(),\n .type_symbol = site[7].c_str(),\n .Cartn_x = atof(site[8].c_str()),\n .Cartn_y = atof(site[9].c_str()),\n .Cartn_z = atof(site[10].c_str())};\n}\n\ntemplate \nstatic freesasa_structure *\nfreesasa_structure_from_pred(const gemmi::cif::Document &doc,\n const T &discriminator,\n const freesasa_classifier *classifier,\n int structure_options)\n{\n freesasa_structure *structure = freesasa_structure_new();\n<<<<<<< HEAD\n std::string auth_atom_id;\n char prevAltId = '.';\n=======\n \/\/ std::string auth_atom_id; \/\/ Should be deleted due to refactoring.\n>>>>>>> 59a514a... Successfully parsing tree structure and input cif file; matching tree atom to cif atom.\n\n for (auto block : doc.blocks) {\n for (auto site : block.find(\"_atom_site.\", atom_site_columns)) {\n if (site[0] != \"ATOM\" && !(structure_options & FREESASA_INCLUDE_HETATM)) {\n continue;\n }\n\n if (discriminator(site)) continue;\n\n freesasa_cif_atom atom = freesasa_atom_from_site(site);\n\n if (!(structure_options & FREESASA_INCLUDE_HYDROGEN) && std::string(atom.type_symbol) == \"H\") {\n continue;\n }\n\n \/\/ Pick the first alternative conformation for an atom\n auto currentAltId = site[6][0];\n if ((currentAltId != '.' && prevAltId == '.') || currentAltId == '.') {\n prevAltId = currentAltId;\n } else if (currentAltId != '.' && currentAltId != prevAltId) {\n continue;\n }\n\n freesasa_structure_add_cif_atom(structure, &atom, classifier, structure_options);\n }\n }\n return structure;\n}\n\nfreesasa_structure *\nfreesasa_structure_from_cif(std::FILE *input,\n const freesasa_classifier *classifier,\n int structure_options)\n{\n const auto doc = gemmi::cif::read_cstream(input, 8192, \"cif-input\");\n const auto models = get_models(doc);\n\n std::unique_ptr discriminator;\n if (structure_options & FREESASA_JOIN_MODELS) {\n discriminator = std::make_unique(std::move(*models));\n } else {\n auto firstModel = models->begin();\n auto singleModel = std::set{*firstModel};\n discriminator = std::make_unique(singleModel);\n }\n return freesasa_structure_from_pred(doc, *discriminator, classifier, structure_options);\n}\n\nfreesasa_structure *\nfreesasa_structure_from_model(const gemmi::cif::Document &doc,\n const std::string &model_name,\n const freesasa_classifier *classifier,\n int structure_options)\n{\n const ModelDiscriminator discriminator(model_name);\n return freesasa_structure_from_pred(doc, discriminator, classifier, structure_options);\n freesasa_structure *structure = freesasa_structure_new();\n}\n\nfreesasa_structure *\nfreesasa_structure_from_chain(const gemmi::cif::Document doc,\n const std::string &model_name,\n const std::string &chain_name,\n const freesasa_classifier *classifier,\n int structure_options)\n{\n const ChainDiscriminator discriminator(model_name, chain_name);\n return freesasa_structure_from_pred(doc, discriminator, classifier, structure_options);\n}\n\nstd::vector\nfreesasa_cif_structure_array(std::FILE *input,\n int *n,\n const freesasa_classifier *classifier,\n int options)\n{\n int n_models = 0, n_chains = 0;\n\n std::vector ss;\n\n const auto doc = gemmi::cif::read_cstream(input, 8192, \"cif-input\");\n\n gemmi::Structure gemmi_struct = gemmi::make_structure_from_block(doc.blocks[0]);\n\n const auto models = gemmi_struct.models;\n\n n_models = models.size();\n\n \/* only keep first model if option not provided *\/\n if (!(options & FREESASA_SEPARATE_MODELS)) n_models = 1;\n\n \/* for each model read chains if requested *\/\n if (options & FREESASA_SEPARATE_CHAINS) {\n for (int i = 0; i < n_models; ++i) {\n auto chain_names = get_chains(models[i]);\n int n_new_chains = chain_names->size();\n n_chains += n_new_chains;\n\n if (n_new_chains == 0) {\n freesasa_warn(\"in %s(): no chains found (in model %s)\", __func__, models[i].name.c_str());\n continue;\n }\n\n ss.reserve(n_new_chains);\n for (auto &chain_name : *chain_names) {\n ss.emplace_back(\n freesasa_structure_from_chain(doc, models[i].name, chain_name, classifier, options));\n freesasa_structure_set_model(ss.back(), i + 1);\n }\n }\n if (n_chains == 0) freesasa_fail(\"In %s(): No chains in any model in protein: %s.\", __func__, gemmi_struct.name.c_str());\n *n = n_chains;\n } else {\n ss.reserve(n_models);\n for (int i = 0; i < n_models; ++i) {\n ss.emplace_back(\n freesasa_structure_from_model(doc, models[i].name, classifier, options));\n freesasa_structure_set_model(ss.back(), i + 1);\n }\n *n = n_models;\n }\n return ss;\n}\n\n\nstruct freesasa_MCRA{\n\n freesasa_MCRA(const int model, const std::string &chain, const std::string &residue, const std::string &res_num, const std::string &atom)\n : _model(model), _chain(chain), _residue(residue), _res_num(res_num), _atom(atom)\n {}\n\n int find_row(gemmi::cif::Table &table, int start_idx=0) const {\n int idx = start_idx, total_rows = table.length();\n\n assert(idx < total_rows);\n\n while (idx < total_rows - 1){\n if ((*this)(table[idx])) {\n return idx;\n }\n ++idx;\n }\n\n std::cout << \"Did not find row for: \" << *this << std::endl;\n std::cout << \"Looping through entire table... \" << std::endl;\n\n idx = 0;\n for (auto site : table) {\n if ((*this)(site)) {\n return idx;\n }\n ++idx;\n }\n std::cout << \"Still couldnt find: \" << *this << std::endl;\n return -1;\n }\n\n friend std::ostream& operator << (std::ostream& os, const freesasa_MCRA& mcra){\n os << \"Atom(\" << mcra._model << \" \" << mcra._chain << \" \" << mcra._residue << \" [\" << mcra._res_num << \"] \" << mcra._atom << \")\";\n return os; \n }\n\nprivate:\n bool operator () (const gemmi::cif::Table::Row &site) const {\n\n \n int model = std::stoul(site[11]);\n const std::string &chain = site[1];\n const std::string &residue = site[4];\n const std::string &res_num = site[2];\n const std::string &atom = site[5][0] != '\"' ? site[5] : site[5].substr(1, site[5].size() - 2);\n\n if (_model == model){\n if (_chain == chain){\n if (_res_num == res_num && _residue == residue){\n if (_atom == atom) {\n \/\/ std::cout << \"Found! \" << *this << std::endl;\n return true;\n } \n } \n } \n }\n return false;\n\n }\n\n const int _model;\n const std::string &_chain, &_residue, &_res_num,&_atom;\n};\n\n\n\nint freesasa_write_cif(std::FILE *output,\n freesasa_node *root,\n int options)\n{\n freesasa_node *result{freesasa_node_children(root)};\n freesasa_node *structure;\n\n assert(output);\n assert(root);\n assert(freesasa_node_type(root) == FREESASA_NODE_ROOT);\n\n std::string inp_file{freesasa_node_name(result)};\n std::string out_file = inp_file.substr(0, inp_file.find_last_of(\".\")) + \".sasa.cif\";\n std::cout << \"Input file: \" << inp_file << std::endl << \"Output File: \" << out_file << std::endl;\n\n const auto doc = gemmi::cif::read_file(inp_file);\n auto block = doc.sole_block();\n auto table = block.find(\"_atom_site.\", atom_site_columns);\n std::cout << \"Number of rows in the table: \" << table.length() << std::endl;\n\n while (result) {\n structure = freesasa_node_children(result);\n std::cout << \"New Result!\" << std::endl;\n while (structure) {\n int rowNum = 0, idx = 0;\n auto model = freesasa_node_structure_model(structure);\n auto chain = freesasa_node_children(structure);\n std::cout << \"New Structure!\" << std::endl;\n while (chain) {\n auto cName = freesasa_node_name(chain);\n auto residue = freesasa_node_children(chain);\n while (residue) {\n auto rName = freesasa_node_name(residue);\n auto rNum = freesasa_node_residue_number(residue);\n auto atom = freesasa_node_children(residue);\n while (atom) {\n auto aName = freesasa_node_name(atom);\n auto area = freesasa_node_area(atom);\n auto radius = freesasa_node_atom_radius(atom);\n\n idx = freesasa_MCRA{model, cName, rName, rNum, aName}.find_row(table, rowNum);\n rowNum = idx != -1 ? idx : rowNum;\n if (idx == -1) exit(1);\n\n atom = freesasa_node_next(atom);\n }\n auto last_res_name = freesasa_node_name(residue);\n auto last_res_number = freesasa_node_residue_number(residue);\n residue = freesasa_node_next(residue);\n }\n auto last_chain = freesasa_node_name(chain);\n chain = freesasa_node_next(chain);\n std::cout << \"Finished chain: \" << cName << std::endl;\n }\n structure = freesasa_node_next(structure);\n }\n result = freesasa_node_next(result);\n }\n return FREESASA_SUCCESS;\n}\nCleaned up code; prepping it for adding the sasa and radius columns to the cif table.#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#define GEMMI_WRITE_IMPLEMENTATION\n#include \n#undef GEMMI_WRITE_IMPLEMENTATION\n\n#include \"cif.hh\"\n#include \"freesasa.h\"\n\nstruct ModelDiscriminator {\n ModelDiscriminator(const std::string &model_name,\n const int model_col = 11)\n : _model_name(model_name), _model_col(model_col)\n {\n }\n\n bool operator()(const gemmi::cif::Table::Row &site) const\n {\n return _model_name != site[_model_col];\n }\n\nprivate:\n const std::string _model_name;\n int _model_col;\n};\n\nstruct ModelSetDiscriminator {\n ModelSetDiscriminator(const std::set models,\n const int model_col = 11)\n : _models(models), _model_col(model_col)\n {\n }\n\n bool operator()(const gemmi::cif::Table::Row &site) const\n {\n return _models.count(std::stoi(site[_model_col])) == 0;\n }\n\nprivate:\n const std::set _models;\n int _model_col;\n};\n\nstruct ChainDiscriminator {\n ChainDiscriminator(const std::string &model_name, const std::string &chain_name,\n const int model_col = 11, const int chain_col = 1)\n : _model_name(model_name), _chain_name(chain_name),\n _model_col(model_col), _chain_col(chain_col)\n {\n }\n\n bool operator()(const gemmi::cif::Table::Row &site) const\n {\n return _model_name != site[_model_col] || _chain_name != site[_chain_col];\n }\n\nprivate:\n const std::string _model_name, _chain_name;\n int _model_col, _chain_col;\n};\n\nstatic std::unique_ptr>\nget_models(const gemmi::cif::Document &doc)\n{\n auto models = std::make_unique>();\n for (auto block : doc.blocks) {\n for (auto site : block.find(\"_atom_site.\", {\"pdbx_PDB_model_num\"})) {\n models->insert(gemmi::cif::as_int(site[0]));\n }\n }\n return models;\n}\n\nstatic std::unique_ptr>\nget_chains(const gemmi::cif::Document &doc)\n{\n auto chains = std::make_unique>();\n for (auto block : doc.blocks) {\n for (auto site : block.find(\"_atom_site.\", {\"auth_asym_id\"})) {\n chains->insert(site[0]);\n }\n }\n return chains;\n}\n\nstatic std::unique_ptr>\nget_chains(const gemmi::Model &model)\n{\n auto chains = std::make_unique>();\n\n for (auto &chain : model.chains) {\n chains->insert(chain.name);\n }\n\n return chains;\n}\n\nstatic const auto atom_site_columns = std::vector({\n \"group_PDB\",\n \"auth_asym_id\",\n \"auth_seq_id\",\n \"pdbx_PDB_ins_code\",\n \"auth_comp_id\",\n \"auth_atom_id\",\n \"label_alt_id\",\n \"type_symbol\",\n \"Cartn_x\",\n \"Cartn_y\",\n \"Cartn_z\",\n \"pdbx_PDB_model_num\",\n});\n\nstatic freesasa_cif_atom\nfreesasa_atom_from_site(const gemmi::cif::Table::Row &site)\n{\n\n std::unique_ptr auth_atom_id;\n \/\/ remove quotation marks if necessary\n if (site[5][0] == '\"') {\n auth_atom_id = std::make_unique(site[5].substr(1, site[5].size() - 2));\n }\n\n return {\n .group_PDB = site[0].c_str(),\n .auth_asym_id = site[1][0],\n .auth_seq_id = site[2].c_str(),\n .pdbx_PDB_ins_code = site[3].c_str(),\n .auth_comp_id = site[4].c_str(),\n .auth_atom_id = auth_atom_id ? std::move(*auth_atom_id).c_str() : site[5].c_str(),\n .label_alt_id = site[6].c_str(),\n .type_symbol = site[7].c_str(),\n .Cartn_x = atof(site[8].c_str()),\n .Cartn_y = atof(site[9].c_str()),\n .Cartn_z = atof(site[10].c_str())};\n}\n\ntemplate \nstatic freesasa_structure *\nfreesasa_structure_from_pred(const gemmi::cif::Document &doc,\n const T &discriminator,\n const freesasa_classifier *classifier,\n int structure_options)\n{\n freesasa_structure *structure = freesasa_structure_new();\n<<<<<<< HEAD\n std::string auth_atom_id;\n char prevAltId = '.';\n=======\n \/\/ std::string auth_atom_id; \/\/ Should be deleted due to refactoring.\n>>>>>>> 59a514a... Successfully parsing tree structure and input cif file; matching tree atom to cif atom.\n\n for (auto block : doc.blocks) {\n for (auto site : block.find(\"_atom_site.\", atom_site_columns)) {\n if (site[0] != \"ATOM\" && !(structure_options & FREESASA_INCLUDE_HETATM)) {\n continue;\n }\n\n if (discriminator(site)) continue;\n\n freesasa_cif_atom atom = freesasa_atom_from_site(site);\n\n if (!(structure_options & FREESASA_INCLUDE_HYDROGEN) && std::string(atom.type_symbol) == \"H\") {\n continue;\n }\n\n \/\/ Pick the first alternative conformation for an atom\n auto currentAltId = site[6][0];\n if ((currentAltId != '.' && prevAltId == '.') || currentAltId == '.') {\n prevAltId = currentAltId;\n } else if (currentAltId != '.' && currentAltId != prevAltId) {\n continue;\n }\n\n freesasa_structure_add_cif_atom(structure, &atom, classifier, structure_options);\n }\n }\n return structure;\n}\n\nfreesasa_structure *\nfreesasa_structure_from_cif(std::FILE *input,\n const freesasa_classifier *classifier,\n int structure_options)\n{\n const auto doc = gemmi::cif::read_cstream(input, 8192, \"cif-input\");\n const auto models = get_models(doc);\n\n std::unique_ptr discriminator;\n if (structure_options & FREESASA_JOIN_MODELS) {\n discriminator = std::make_unique(std::move(*models));\n } else {\n auto firstModel = models->begin();\n auto singleModel = std::set{*firstModel};\n discriminator = std::make_unique(singleModel);\n }\n return freesasa_structure_from_pred(doc, *discriminator, classifier, structure_options);\n}\n\nfreesasa_structure *\nfreesasa_structure_from_model(const gemmi::cif::Document &doc,\n const std::string &model_name,\n const freesasa_classifier *classifier,\n int structure_options)\n{\n const ModelDiscriminator discriminator(model_name);\n return freesasa_structure_from_pred(doc, discriminator, classifier, structure_options);\n freesasa_structure *structure = freesasa_structure_new();\n}\n\nfreesasa_structure *\nfreesasa_structure_from_chain(const gemmi::cif::Document doc,\n const std::string &model_name,\n const std::string &chain_name,\n const freesasa_classifier *classifier,\n int structure_options)\n{\n const ChainDiscriminator discriminator(model_name, chain_name);\n return freesasa_structure_from_pred(doc, discriminator, classifier, structure_options);\n}\n\nstd::vector\nfreesasa_cif_structure_array(std::FILE *input,\n int *n,\n const freesasa_classifier *classifier,\n int options)\n{\n int n_models = 0, n_chains = 0;\n\n std::vector ss;\n\n const auto doc = gemmi::cif::read_cstream(input, 8192, \"cif-input\");\n\n gemmi::Structure gemmi_struct = gemmi::make_structure_from_block(doc.blocks[0]);\n\n const auto models = gemmi_struct.models;\n\n n_models = models.size();\n\n \/* only keep first model if option not provided *\/\n if (!(options & FREESASA_SEPARATE_MODELS)) n_models = 1;\n\n \/* for each model read chains if requested *\/\n if (options & FREESASA_SEPARATE_CHAINS) {\n for (int i = 0; i < n_models; ++i) {\n auto chain_names = get_chains(models[i]);\n int n_new_chains = chain_names->size();\n n_chains += n_new_chains;\n\n if (n_new_chains == 0) {\n freesasa_warn(\"in %s(): no chains found (in model %s)\", __func__, models[i].name.c_str());\n continue;\n }\n\n ss.reserve(n_new_chains);\n for (auto &chain_name : *chain_names) {\n ss.emplace_back(\n freesasa_structure_from_chain(doc, models[i].name, chain_name, classifier, options));\n freesasa_structure_set_model(ss.back(), i + 1);\n }\n }\n if (n_chains == 0) freesasa_fail(\"In %s(): No chains in any model in protein: %s.\", __func__, gemmi_struct.name.c_str());\n *n = n_chains;\n } else {\n ss.reserve(n_models);\n for (int i = 0; i < n_models; ++i) {\n ss.emplace_back(\n freesasa_structure_from_model(doc, models[i].name, classifier, options));\n freesasa_structure_set_model(ss.back(), i + 1);\n }\n *n = n_models;\n }\n return ss;\n}\n\nstruct freesasa_MCRA {\n\n freesasa_MCRA(const int model, const std::string &chain, const std::string &residue, const std::string &res_num, const std::string &atom)\n : _model(model), _chain(chain), _residue(residue), _res_num(res_num), _atom(atom)\n {\n }\n\n int find_row(gemmi::cif::Table &table, int start_idx = 0) const\n {\n int idx = start_idx, total_rows = table.length();\n\n assert(idx < total_rows);\n\n while (idx < total_rows) {\n if ((*this)(table[idx])) {\n return idx;\n }\n ++idx;\n }\n\n std::cout << \"Did not find row for: \" << *this << std::endl;\n std::cout << \"Looping through entire table... \" << std::endl;\n\n idx = 0;\n for (auto site : table) {\n if ((*this)(site)) {\n return idx;\n }\n ++idx;\n }\n std::cout << \"Still couldnt find: \" << *this << std::endl;\n return -1;\n }\n\n friend std::ostream &operator<<(std::ostream &os, const freesasa_MCRA &mcra)\n {\n os << \"Atom(\" << mcra._model << \" \" << mcra._chain << \" \" << mcra._residue << \" [\" << mcra._res_num << \"] \" << mcra._atom << \")\";\n return os;\n }\n\nprivate:\n bool operator()(const gemmi::cif::Table::Row &site) const\n {\n int model = std::stoul(site[11]);\n const std::string &chain = site[1];\n const std::string &residue = site[4];\n const std::string &res_num = site[2];\n const std::string &atom = site[5][0] != '\"' ? site[5] : site[5].substr(1, site[5].size() - 2);\n\n if (_model == model) {\n if (_chain == chain) {\n if (_res_num == res_num && _residue == residue) {\n if (_atom == atom) {\n \/\/ std::cout << \"Found! \" << *this << std::endl;\n return true;\n }\n }\n }\n }\n return false;\n }\n\n const int _model;\n const std::string &_chain, &_residue, &_res_num, &_atom;\n};\n\nint freesasa_write_cif(std::FILE *output,\n freesasa_node *root,\n int options)\n{\n freesasa_node *result{freesasa_node_children(root)};\n freesasa_node *structure;\n\n assert(output);\n assert(root);\n assert(freesasa_node_type(root) == FREESASA_NODE_ROOT);\n\n std::string inp_file{freesasa_node_name(result)};\n std::string out_file = inp_file.substr(0, inp_file.find_last_of(\".\")) + \".sasa.cif\";\n std::cout << \"Input file: \" << inp_file << std::endl\n << \"Output File: \" << out_file << std::endl;\n\n const auto doc = gemmi::cif::read_file(inp_file);\n auto block = doc.sole_block();\n auto table = block.find(\"_atom_site.\", atom_site_columns);\n auto &loop = *table.get_loop();\n std::cout << \"Number of rows x columns in the table: \" << table.length() << \" x \" << loop.tags.size() << std::endl;\n\n \/\/ TODO allocate new vector> with the proper number of columns\n\n std::vector sasa_vals, sasa_radii;\n sasa_vals.reserve(table.length()), sasa_radii.reserve(table.length());\n while (result) {\n structure = freesasa_node_children(result);\n std::cout << \"New Result!\" << std::endl;\n while (structure) {\n int rowNum = 0, idx = 0;\n auto model = freesasa_node_structure_model(structure);\n auto chain = freesasa_node_children(structure);\n std::cout << \"New Structure!\" << std::endl;\n while (chain) {\n auto cName = freesasa_node_name(chain);\n auto residue = freesasa_node_children(chain);\n while (residue) {\n auto rName = freesasa_node_name(residue);\n auto rNum = freesasa_node_residue_number(residue);\n auto atom = freesasa_node_children(residue);\n while (atom) {\n auto aName = freesasa_node_name(atom);\n auto area = freesasa_node_area(atom);\n auto radius = freesasa_node_atom_radius(atom);\n\n idx = freesasa_MCRA{model, cName, rName, rNum, aName}.find_row(table, rowNum);\n if (idx != -1) {\n rowNum = idx;\n sasa_vals[rowNum] = area->total;\n sasa_radii[rowNum] = radius;\n std::cout << \"Atom FREESASA Value and Radius: \" << area->total << \" \" << radius << std::endl;\n } else {\n exit(1);\n }\n atom = freesasa_node_next(atom);\n }\n auto last_res_name = freesasa_node_name(residue);\n auto last_res_number = freesasa_node_residue_number(residue);\n residue = freesasa_node_next(residue);\n }\n auto last_chain = freesasa_node_name(chain);\n chain = freesasa_node_next(chain);\n std::cout << \"Finished chain: \" << cName << std::endl;\n }\n structure = freesasa_node_next(structure);\n }\n result = freesasa_node_next(result);\n }\n std::cout << \"Max freesasa value: \" << sasa_vals[std::distance(sasa_vals.begin(), std::max_element(sasa_vals.begin(), sasa_vals.end()))] << std::endl;\n return FREESASA_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2012 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"config.h\"\n\n#include \"common.h\"\n#include \"couch-kvstore\/couch-fs-stats.h\"\n#include \"histo.h\"\n\nextern \"C\" {\nstatic couch_file_handle cfs_construct(couchstore_error_info_t*, void* cookie);\nstatic couchstore_error_t cfs_open(couchstore_error_info_t*,\n couch_file_handle*, const char*, int);\nstatic void cfs_close(couchstore_error_info_t*, couch_file_handle);\nstatic ssize_t cfs_pread(couchstore_error_info_t*, couch_file_handle,\n void *, size_t, cs_off_t);\nstatic ssize_t cfs_pwrite(couchstore_error_info_t*, couch_file_handle,\n const void *, size_t, cs_off_t);\nstatic cs_off_t cfs_goto_eof(couchstore_error_info_t*, couch_file_handle);\nstatic couchstore_error_t cfs_sync(couchstore_error_info_t*, couch_file_handle);\nstatic couchstore_error_t cfs_advise(couchstore_error_info_t*,\n couch_file_handle,\n cs_off_t, cs_off_t,\n couchstore_file_advice_t);\nstatic void cfs_destroy(couchstore_error_info_t*,couch_file_handle);\n}\n\ncouch_file_ops getCouchstoreStatsOps(CouchstoreStats* stats) {\n couch_file_ops ops = {\n 5,\n cfs_construct,\n cfs_open,\n cfs_close,\n cfs_pread,\n cfs_pwrite,\n cfs_goto_eof,\n cfs_sync,\n cfs_advise,\n cfs_destroy,\n stats\n };\n return ops;\n}\n\nstruct StatFile {\n const couch_file_ops* orig_ops;\n couch_file_handle orig_handle;\n CouchstoreStats* stats;\n cs_off_t last_offs;\n};\n\nextern \"C\" {\n static couch_file_handle cfs_construct(couchstore_error_info_t *errinfo,\n void* cookie) {\n StatFile* sf = new StatFile;\n sf->stats = static_cast(cookie);\n sf->orig_ops = couchstore_get_default_file_ops();\n sf->orig_handle = sf->orig_ops->constructor(errinfo,\n sf->orig_ops->cookie);\n sf->last_offs = 0;\n return reinterpret_cast(sf);\n }\n\n static couchstore_error_t cfs_open(couchstore_error_info_t *errinfo,\n couch_file_handle* h,\n const char* path,\n int flags) {\n StatFile* sf = reinterpret_cast(*h);\n return sf->orig_ops->open(errinfo, &sf->orig_handle, path, flags);\n }\n\n static void cfs_close(couchstore_error_info_t *errinfo,\n couch_file_handle h) {\n StatFile* sf = reinterpret_cast(h);\n sf->orig_ops->close(errinfo, sf->orig_handle);\n }\n\n static ssize_t cfs_pread(couchstore_error_info_t *errinfo,\n couch_file_handle h,\n void* buf,\n size_t sz,\n cs_off_t off) {\n StatFile* sf = reinterpret_cast(h);\n sf->stats->readSizeHisto.add(sz);\n if(sf->last_offs) {\n sf->stats->readSeekHisto.add(abs(off - sf->last_offs));\n }\n sf->last_offs = off;\n BlockTimer bt(&sf->stats->readTimeHisto);\n return sf->orig_ops->pread(errinfo, sf->orig_handle, buf, sz, off);\n }\n\n static ssize_t cfs_pwrite(couchstore_error_info_t *errinfo,\n couch_file_handle h,\n const void* buf,\n size_t sz,\n cs_off_t off) {\n StatFile* sf = reinterpret_cast(h);\n sf->stats->writeSizeHisto.add(sz);\n BlockTimer bt(&sf->stats->writeTimeHisto);\n return sf->orig_ops->pwrite(errinfo, sf->orig_handle, buf, sz, off);\n }\n\n static cs_off_t cfs_goto_eof(couchstore_error_info_t *errinfo,\n couch_file_handle h) {\n StatFile* sf = reinterpret_cast(h);\n return sf->orig_ops->goto_eof(errinfo, sf->orig_handle);\n }\n\n static couchstore_error_t cfs_sync(couchstore_error_info_t *errinfo,\n couch_file_handle h) {\n StatFile* sf = reinterpret_cast(h);\n BlockTimer bt(&sf->stats->syncTimeHisto);\n return sf->orig_ops->sync(errinfo, sf->orig_handle);\n }\n\n static couchstore_error_t cfs_advise(couchstore_error_info_t *errinfo,\n couch_file_handle h,\n cs_off_t offs,\n cs_off_t len,\n couchstore_file_advice_t adv) {\n StatFile* sf = reinterpret_cast(h);\n return sf->orig_ops->advise(errinfo, sf->orig_handle, offs, len, adv);\n }\n\n static void cfs_destroy(couchstore_error_info_t *errinfo,\n couch_file_handle h) {\n StatFile* sf = reinterpret_cast(h);\n sf->orig_ops->destructor(errinfo, sf->orig_handle);\n delete sf;\n }\n\n}\nAddress compiler warning on mac\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2012 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"config.h\"\n\n#include \"common.h\"\n#include \"couch-kvstore\/couch-fs-stats.h\"\n#include \"histo.h\"\n\nextern \"C\" {\nstatic couch_file_handle cfs_construct(couchstore_error_info_t*, void* cookie);\nstatic couchstore_error_t cfs_open(couchstore_error_info_t*,\n couch_file_handle*, const char*, int);\nstatic void cfs_close(couchstore_error_info_t*, couch_file_handle);\nstatic ssize_t cfs_pread(couchstore_error_info_t*, couch_file_handle,\n void *, size_t, cs_off_t);\nstatic ssize_t cfs_pwrite(couchstore_error_info_t*, couch_file_handle,\n const void *, size_t, cs_off_t);\nstatic cs_off_t cfs_goto_eof(couchstore_error_info_t*, couch_file_handle);\nstatic couchstore_error_t cfs_sync(couchstore_error_info_t*, couch_file_handle);\nstatic couchstore_error_t cfs_advise(couchstore_error_info_t*,\n couch_file_handle,\n cs_off_t, cs_off_t,\n couchstore_file_advice_t);\nstatic void cfs_destroy(couchstore_error_info_t*,couch_file_handle);\n}\n\ncouch_file_ops getCouchstoreStatsOps(CouchstoreStats* stats) {\n couch_file_ops ops = {\n 5,\n cfs_construct,\n cfs_open,\n cfs_close,\n cfs_pread,\n cfs_pwrite,\n cfs_goto_eof,\n cfs_sync,\n cfs_advise,\n cfs_destroy,\n stats\n };\n return ops;\n}\n\nstruct StatFile {\n const couch_file_ops* orig_ops;\n couch_file_handle orig_handle;\n CouchstoreStats* stats;\n cs_off_t last_offs;\n};\n\nextern \"C\" {\n static couch_file_handle cfs_construct(couchstore_error_info_t *errinfo,\n void* cookie) {\n StatFile* sf = new StatFile;\n sf->stats = static_cast(cookie);\n sf->orig_ops = couchstore_get_default_file_ops();\n sf->orig_handle = sf->orig_ops->constructor(errinfo,\n sf->orig_ops->cookie);\n sf->last_offs = 0;\n return reinterpret_cast(sf);\n }\n\n static couchstore_error_t cfs_open(couchstore_error_info_t *errinfo,\n couch_file_handle* h,\n const char* path,\n int flags) {\n StatFile* sf = reinterpret_cast(*h);\n return sf->orig_ops->open(errinfo, &sf->orig_handle, path, flags);\n }\n\n static void cfs_close(couchstore_error_info_t *errinfo,\n couch_file_handle h) {\n StatFile* sf = reinterpret_cast(h);\n sf->orig_ops->close(errinfo, sf->orig_handle);\n }\n\n static ssize_t cfs_pread(couchstore_error_info_t *errinfo,\n couch_file_handle h,\n void* buf,\n size_t sz,\n cs_off_t off) {\n StatFile* sf = reinterpret_cast(h);\n sf->stats->readSizeHisto.add(sz);\n if(sf->last_offs) {\n sf->stats->readSeekHisto.add(std::abs(off - sf->last_offs));\n }\n sf->last_offs = off;\n BlockTimer bt(&sf->stats->readTimeHisto);\n return sf->orig_ops->pread(errinfo, sf->orig_handle, buf, sz, off);\n }\n\n static ssize_t cfs_pwrite(couchstore_error_info_t *errinfo,\n couch_file_handle h,\n const void* buf,\n size_t sz,\n cs_off_t off) {\n StatFile* sf = reinterpret_cast(h);\n sf->stats->writeSizeHisto.add(sz);\n BlockTimer bt(&sf->stats->writeTimeHisto);\n return sf->orig_ops->pwrite(errinfo, sf->orig_handle, buf, sz, off);\n }\n\n static cs_off_t cfs_goto_eof(couchstore_error_info_t *errinfo,\n couch_file_handle h) {\n StatFile* sf = reinterpret_cast(h);\n return sf->orig_ops->goto_eof(errinfo, sf->orig_handle);\n }\n\n static couchstore_error_t cfs_sync(couchstore_error_info_t *errinfo,\n couch_file_handle h) {\n StatFile* sf = reinterpret_cast(h);\n BlockTimer bt(&sf->stats->syncTimeHisto);\n return sf->orig_ops->sync(errinfo, sf->orig_handle);\n }\n\n static couchstore_error_t cfs_advise(couchstore_error_info_t *errinfo,\n couch_file_handle h,\n cs_off_t offs,\n cs_off_t len,\n couchstore_file_advice_t adv) {\n StatFile* sf = reinterpret_cast(h);\n return sf->orig_ops->advise(errinfo, sf->orig_handle, offs, len, adv);\n }\n\n static void cfs_destroy(couchstore_error_info_t *errinfo,\n couch_file_handle h) {\n StatFile* sf = reinterpret_cast(h);\n sf->orig_ops->destructor(errinfo, sf->orig_handle);\n delete sf;\n }\n\n}\n<|endoftext|>"} {"text":"\/*\n * PosixCrypto.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n\n\/\/ openssl calls on lion are are all marked as deprecated\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wdeprecated-declarations\"\n#endif\n\nusing namespace rstudio::core;\n\nnamespace rstudio {\nnamespace core {\nnamespace system {\nnamespace crypto {\n\nnamespace {\n\n\/\/ NOTE: we've never see the error codepath in spite of trying to get it to\n\/\/ return an error by tweaking params -- NULL params caused a crash rather\n\/\/ than returning an error). this is presumably because we are calling\n\/\/ such low level functions. we may want to look at the src code to see\n\/\/ if there is a way to test\/engineer an error (or remove the error\n\/\/ checking if there is no way to get one)\n\nError lastCryptoError(const ErrorLocation& location)\n{\n \/\/ get the error code\n unsigned long ec = ::ERR_get_error();\n if (ec == 0)\n {\n LOG_WARNING_MESSAGE(\"lastCrytpoError called with no pending error\");\n return systemError(boost::system::errc::not_supported,\n \"lastCrytpoError called with no pending error\",\n location);\n }\n \n \/\/ get the error message (docs say max len is 120)\n const int ERR_BUFF_SIZE = 250; \n char errorBuffer[ERR_BUFF_SIZE];\n ::ERR_error_string_n(ec, errorBuffer, ERR_BUFF_SIZE);\n \n \/\/ return the error\n return systemError(boost::system::errc::bad_message,\n errorBuffer,\n location);\n} \n \nclass BIOFreeAllScope : boost::noncopyable\n{\npublic:\n BIOFreeAllScope(BIO* pMem)\n : pMem_(pMem)\n {\n }\n \n ~BIOFreeAllScope()\n {\n try\n {\n ::BIO_free_all(pMem_);\n }\n catch(...)\n {\n }\n }\nprivate:\n BIO* pMem_;\n};\n \n} \/\/ anonymous namespace\n \nvoid initialize()\n{\n \/\/ load global error string table\n ::ERR_load_crypto_strings();\n}\n \nError HMAC_SHA2(const std::string& data,\n const std::string& key,\n std::vector* pHMAC)\n{\n \/\/ copy data into vector\n std::vector keyVector;\n std::copy(key.begin(), key.end(), std::back_inserter(keyVector)); \n \n \/\/ call core\n return HMAC_SHA2(data, keyVector, pHMAC);\n}\n \nError HMAC_SHA2(const std::string& data,\n const std::vector& key,\n std::vector* pHMAC)\n{\n \/\/ copy data into data vector\n std::vector dataVector;\n std::copy(data.begin(), data.end(), std::back_inserter(dataVector));\n \n \/\/ perform the hash\n unsigned int md_len = 0;\n pHMAC->resize(EVP_MAX_MD_SIZE);\n unsigned char* pResult = ::HMAC(EVP_sha256(),\n &(key[0]),\n key.size(),\n &(dataVector[0]),\n dataVector.size(),\n &(pHMAC->operator[](0)),\n &md_len);\n if (pResult != NULL)\n {\n pHMAC->resize(md_len);\n return Success();\n }\n else\n {\n return lastCryptoError(ERROR_LOCATION);\n }\n}\n\nError base64Encode(const std::vector& data, \n std::string* pEncoded)\n{\n return base64Encode(&(data[0]), data.size(), pEncoded);\n}\n \nError base64Encode(const unsigned char* pData, \n int len, \n std::string* pEncoded)\n{\n \/\/ allocate BIO\n BIO* pB64 = ::BIO_new(BIO_f_base64());\n if (pB64 == NULL)\n return lastCryptoError(ERROR_LOCATION);\n \n \/\/ no newlines\n BIO_set_flags(pB64, BIO_FLAGS_BASE64_NO_NL);\n \n \/\/ make sure it is freed prior to exit from the function\n BIOFreeAllScope freeB64Scope(pB64);\n \n \/\/ allocate memory stream \n BIO* pMem = ::BIO_new(BIO_s_mem());\n if (pMem == NULL)\n return lastCryptoError(ERROR_LOCATION);\n \n \/\/ tie the stream to the b64 stream\n pB64 = ::BIO_push(pB64, pMem);\n \n \/\/ perform the encoding\n int written = ::BIO_write(pB64, pData, len); \n if (written != len)\n return lastCryptoError(ERROR_LOCATION);\n \n \/\/ flush all writes\n int result = BIO_flush(pB64);\n if (result <= 0)\n return lastCryptoError(ERROR_LOCATION);\n \n \/\/ seek to beginning of memory stream\n result = BIO_seek(pMem, 0);\n if (result == -1)\n return lastCryptoError(ERROR_LOCATION);\n\n \/\/ read the memory stream\n std::vector buffer(len *2); \/\/ plenty more than len * 1.37 + padding\n int bytesRead = ::BIO_read(pMem, &(buffer[0]), buffer.capacity());\n if (bytesRead < 0 && ::ERR_get_error() != 0)\n return lastCryptoError(ERROR_LOCATION);\n\n \/\/ copy to out param\n buffer.resize(bytesRead);\n pEncoded->assign(buffer.begin(), buffer.end());\n\n \/\/ return success\n return Success();\n}\n \n \nError base64Decode(const std::string& data, \n std::vector* pDecoded)\n{\n \/\/ allocate b64 BIO\n BIO* pB64 = ::BIO_new(BIO_f_base64());\n if (pB64 == NULL)\n return lastCryptoError(ERROR_LOCATION);\n \n \/\/ no newlines\n BIO_set_flags(pB64, BIO_FLAGS_BASE64_NO_NL);\n \n \/\/ make sure it is freed prior to exit from the function\n BIOFreeAllScope freeB64Scope(pB64);\n \n \/\/ allocate buffer \n BIO* pMem = BIO_new_mem_buf((void*)data.data(), data.length());\n if (pMem == NULL)\n return lastCryptoError(ERROR_LOCATION);\n \n \/\/ tie the stream to the b64 stream\n pB64 = ::BIO_push(pB64, pMem);\n \n \/\/ reserve adequate memory in the decoded buffer and read into it\n pDecoded->clear();\n pDecoded->resize(data.length());\n int bytesRead = ::BIO_read(pB64, \n &(pDecoded->operator[](0)), \n pDecoded->size());\n if (bytesRead < 0)\n return lastCryptoError(ERROR_LOCATION);\n \n \/\/ resize the out buffer to the number of bytes actually read\n pDecoded->resize(bytesRead);\n \n \/\/ return success\n return Success();\n \n}\n\nnamespace {\nRSA* s_pRSA;\nstd::string s_modulo;\nstd::string s_exponent;\n}\n\ncore::Error rsaInit()\n{\n const int KEY_SIZE = 1024;\n const int ENTROPY_BYTES = 4096;\n\n BIGNUM *bn = BN_new();\n BN_set_word(bn, RSA_F4);\n const BIGNUM *bn_n;\n const BIGNUM *bn_e;\n\n int rnd = ::open(\"\/dev\/urandom\", O_RDONLY);\n if (rnd == -1)\n return systemError(errno, ERROR_LOCATION);\n\n char entropy[ENTROPY_BYTES];\n if (-1 == ::read(rnd, entropy, ENTROPY_BYTES))\n {\n ::close(rnd);\n return systemError(errno, ERROR_LOCATION);\n }\n ::close(rnd);\n\n RAND_seed(entropy, ENTROPY_BYTES);\n\n #if OPENSSL_VERSION_NUMBER < 0x10100000L\n s_pRSA = ::RSA_generate_key(KEY_SIZE, 0x10001, NULL, NULL);\n if (!s_pRSA)\n return lastCryptoError(ERROR_LOCATION);\n\n bn_n = s_pRSA->n;\n bn_e = s_pRSA->e;\n #else\n s_pRSA = RSA_new();\n int rc = ::RSA_generate_key_ex(s_pRSA, KEY_SIZE, bn, NULL);\n if (rc != 1) {\n return lastCryptoError(ERROR_LOCATION);\n RSA_free(s_pRSA);\n }\n BN_clear_free(bn);\n \n RSA_get0_key(s_pRSA, &bn_n, &bn_e, NULL);\n #endif\n\n char* n = BN_bn2hex(bn_n);\n s_modulo = n;\n OPENSSL_free(n);\n char* e = BN_bn2hex(bn_e);\n s_exponent = e;\n OPENSSL_free(e);\n\n return Success();\n}\n\nvoid rsaPublicKey(std::string* pExponent, std::string* pModulo)\n{\n pModulo->assign(s_modulo.begin(), s_modulo.end());\n pExponent->assign(s_exponent.begin(), s_exponent.end());\n}\n\ncore::Error rsaPrivateDecrypt(const std::string& cipherText, std::string* pPlainText)\n{\n std::vector cipherTextBytes;\n Error error = base64Decode(cipherText, &cipherTextBytes);\n if (error)\n return error;\n\n int size = RSA_size(s_pRSA);\n std::vector plainTextBytes(size);\n int bytesRead = RSA_private_decrypt(cipherTextBytes.size(),\n &cipherTextBytes[0],\n &plainTextBytes[0],\n s_pRSA,\n RSA_PKCS1_PADDING);\n if (bytesRead == -1)\n return lastCryptoError(ERROR_LOCATION);\n\n plainTextBytes.resize(bytesRead);\n pPlainText->assign(plainTextBytes.begin(), plainTextBytes.end());\n\n return Success();\n}\n\n \n} \/\/ namespace crypto\n} \/\/ namespace system\n} \/\/ namespace core\n} \/\/ namespace rstudio\n\naddress comments\/*\n * PosixCrypto.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n\n\/\/ openssl calls on lion are are all marked as deprecated\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wdeprecated-declarations\"\n#endif\n\nusing namespace rstudio::core;\n\nnamespace rstudio {\nnamespace core {\nnamespace system {\nnamespace crypto {\n\nnamespace {\n\n\/\/ NOTE: we've never see the error codepath in spite of trying to get it to\n\/\/ return an error by tweaking params -- NULL params caused a crash rather\n\/\/ than returning an error). this is presumably because we are calling\n\/\/ such low level functions. we may want to look at the src code to see\n\/\/ if there is a way to test\/engineer an error (or remove the error\n\/\/ checking if there is no way to get one)\n\nError lastCryptoError(const ErrorLocation& location)\n{\n \/\/ get the error code\n unsigned long ec = ::ERR_get_error();\n if (ec == 0)\n {\n LOG_WARNING_MESSAGE(\"lastCrytpoError called with no pending error\");\n return systemError(boost::system::errc::not_supported,\n \"lastCrytpoError called with no pending error\",\n location);\n }\n \n \/\/ get the error message (docs say max len is 120)\n const int ERR_BUFF_SIZE = 250; \n char errorBuffer[ERR_BUFF_SIZE];\n ::ERR_error_string_n(ec, errorBuffer, ERR_BUFF_SIZE);\n \n \/\/ return the error\n return systemError(boost::system::errc::bad_message,\n errorBuffer,\n location);\n} \n \nclass BIOFreeAllScope : boost::noncopyable\n{\npublic:\n BIOFreeAllScope(BIO* pMem)\n : pMem_(pMem)\n {\n }\n \n ~BIOFreeAllScope()\n {\n try\n {\n ::BIO_free_all(pMem_);\n }\n catch(...)\n {\n }\n }\nprivate:\n BIO* pMem_;\n};\n \n} \/\/ anonymous namespace\n \nvoid initialize()\n{\n \/\/ load global error string table\n ::ERR_load_crypto_strings();\n}\n \nError HMAC_SHA2(const std::string& data,\n const std::string& key,\n std::vector* pHMAC)\n{\n \/\/ copy data into vector\n std::vector keyVector;\n std::copy(key.begin(), key.end(), std::back_inserter(keyVector)); \n \n \/\/ call core\n return HMAC_SHA2(data, keyVector, pHMAC);\n}\n \nError HMAC_SHA2(const std::string& data,\n const std::vector& key,\n std::vector* pHMAC)\n{\n \/\/ copy data into data vector\n std::vector dataVector;\n std::copy(data.begin(), data.end(), std::back_inserter(dataVector));\n \n \/\/ perform the hash\n unsigned int md_len = 0;\n pHMAC->resize(EVP_MAX_MD_SIZE);\n unsigned char* pResult = ::HMAC(EVP_sha256(),\n &(key[0]),\n key.size(),\n &(dataVector[0]),\n dataVector.size(),\n &(pHMAC->operator[](0)),\n &md_len);\n if (pResult != NULL)\n {\n pHMAC->resize(md_len);\n return Success();\n }\n else\n {\n return lastCryptoError(ERROR_LOCATION);\n }\n}\n\nError base64Encode(const std::vector& data, \n std::string* pEncoded)\n{\n return base64Encode(&(data[0]), data.size(), pEncoded);\n}\n \nError base64Encode(const unsigned char* pData, \n int len, \n std::string* pEncoded)\n{\n \/\/ allocate BIO\n BIO* pB64 = ::BIO_new(BIO_f_base64());\n if (pB64 == NULL)\n return lastCryptoError(ERROR_LOCATION);\n \n \/\/ no newlines\n BIO_set_flags(pB64, BIO_FLAGS_BASE64_NO_NL);\n \n \/\/ make sure it is freed prior to exit from the function\n BIOFreeAllScope freeB64Scope(pB64);\n \n \/\/ allocate memory stream \n BIO* pMem = ::BIO_new(BIO_s_mem());\n if (pMem == NULL)\n return lastCryptoError(ERROR_LOCATION);\n \n \/\/ tie the stream to the b64 stream\n pB64 = ::BIO_push(pB64, pMem);\n \n \/\/ perform the encoding\n int written = ::BIO_write(pB64, pData, len); \n if (written != len)\n return lastCryptoError(ERROR_LOCATION);\n \n \/\/ flush all writes\n int result = BIO_flush(pB64);\n if (result <= 0)\n return lastCryptoError(ERROR_LOCATION);\n \n \/\/ seek to beginning of memory stream\n result = BIO_seek(pMem, 0);\n if (result == -1)\n return lastCryptoError(ERROR_LOCATION);\n\n \/\/ read the memory stream\n std::vector buffer(len *2); \/\/ plenty more than len * 1.37 + padding\n int bytesRead = ::BIO_read(pMem, &(buffer[0]), buffer.capacity());\n if (bytesRead < 0 && ::ERR_get_error() != 0)\n return lastCryptoError(ERROR_LOCATION);\n\n \/\/ copy to out param\n buffer.resize(bytesRead);\n pEncoded->assign(buffer.begin(), buffer.end());\n\n \/\/ return success\n return Success();\n}\n \n \nError base64Decode(const std::string& data, \n std::vector* pDecoded)\n{\n \/\/ allocate b64 BIO\n BIO* pB64 = ::BIO_new(BIO_f_base64());\n if (pB64 == NULL)\n return lastCryptoError(ERROR_LOCATION);\n \n \/\/ no newlines\n BIO_set_flags(pB64, BIO_FLAGS_BASE64_NO_NL);\n \n \/\/ make sure it is freed prior to exit from the function\n BIOFreeAllScope freeB64Scope(pB64);\n \n \/\/ allocate buffer \n BIO* pMem = BIO_new_mem_buf((void*)data.data(), data.length());\n if (pMem == NULL)\n return lastCryptoError(ERROR_LOCATION);\n \n \/\/ tie the stream to the b64 stream\n pB64 = ::BIO_push(pB64, pMem);\n \n \/\/ reserve adequate memory in the decoded buffer and read into it\n pDecoded->clear();\n pDecoded->resize(data.length());\n int bytesRead = ::BIO_read(pB64, \n &(pDecoded->operator[](0)), \n pDecoded->size());\n if (bytesRead < 0)\n return lastCryptoError(ERROR_LOCATION);\n \n \/\/ resize the out buffer to the number of bytes actually read\n pDecoded->resize(bytesRead);\n \n \/\/ return success\n return Success();\n \n}\n\nnamespace {\nRSA* s_pRSA;\nstd::string s_modulo;\nstd::string s_exponent;\n}\n\ncore::Error rsaInit()\n{\n const int KEY_SIZE = 1024;\n const int ENTROPY_BYTES = 4096;\n\n BIGNUM *bn = BN_new();\n BN_set_word(bn, RSA_F4);\n const BIGNUM *bn_n;\n const BIGNUM *bn_e;\n\n int rnd = ::open(\"\/dev\/urandom\", O_RDONLY);\n if (rnd == -1)\n return systemError(errno, ERROR_LOCATION);\n\n char entropy[ENTROPY_BYTES];\n if (-1 == ::read(rnd, entropy, ENTROPY_BYTES))\n {\n ::close(rnd);\n return systemError(errno, ERROR_LOCATION);\n }\n ::close(rnd);\n\n RAND_seed(entropy, ENTROPY_BYTES);\n\n #if OPENSSL_VERSION_NUMBER < 0x10100000L\n s_pRSA = ::RSA_generate_key(KEY_SIZE, 0x10001, NULL, NULL);\n if (!s_pRSA)\n return lastCryptoError(ERROR_LOCATION);\n\n bn_n = s_pRSA->n;\n bn_e = s_pRSA->e;\n\n BN_clear_free(bn);\n #else\n s_pRSA = RSA_new();\n int rc = ::RSA_generate_key_ex(s_pRSA, KEY_SIZE, bn, NULL);\n BN_clear_free(bn);\n if (rc != 1) {\n return lastCryptoError(ERROR_LOCATION);\n RSA_free(s_pRSA);\n }\n \n RSA_get0_key(s_pRSA, &bn_n, &bn_e, NULL);\n #endif\n\n char* n = BN_bn2hex(bn_n);\n s_modulo = n;\n OPENSSL_free(n);\n char* e = BN_bn2hex(bn_e);\n s_exponent = e;\n OPENSSL_free(e);\n\n return Success();\n}\n\nvoid rsaPublicKey(std::string* pExponent, std::string* pModulo)\n{\n pModulo->assign(s_modulo.begin(), s_modulo.end());\n pExponent->assign(s_exponent.begin(), s_exponent.end());\n}\n\ncore::Error rsaPrivateDecrypt(const std::string& cipherText, std::string* pPlainText)\n{\n std::vector cipherTextBytes;\n Error error = base64Decode(cipherText, &cipherTextBytes);\n if (error)\n return error;\n\n int size = RSA_size(s_pRSA);\n std::vector plainTextBytes(size);\n int bytesRead = RSA_private_decrypt(cipherTextBytes.size(),\n &cipherTextBytes[0],\n &plainTextBytes[0],\n s_pRSA,\n RSA_PKCS1_PADDING);\n if (bytesRead == -1)\n return lastCryptoError(ERROR_LOCATION);\n\n plainTextBytes.resize(bytesRead);\n pPlainText->assign(plainTextBytes.begin(), plainTextBytes.end());\n\n return Success();\n}\n\n \n} \/\/ namespace crypto\n} \/\/ namespace system\n} \/\/ namespace core\n} \/\/ namespace rstudio\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/*\n * Publisher.cpp\n *\n *\/\n\n#include \"PublisherImpl.h\"\n#include \"..\/participant\/ParticipantImpl.h\"\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n\nusing namespace eprosima::fastrtps;\nusing namespace ::rtps;\n\n\nstatic const char* const CLASS_NAME = \"PublisherImpl\";\n\n::rtps::WriteParams WRITE_PARAM_DEFAULT;\n\nPublisherImpl::PublisherImpl(ParticipantImpl* p,TopicDataType*pdatatype,\n\t\tPublisherAttributes& att,PublisherListener* listen ):\n\t\t\t\t\t\t\t\t\t\tmp_participant(p),\n\t\t\t\t\t\t\t\t\t\tmp_writer(nullptr),\n\t\t\t\t\t\t\t\t\t\tmp_type(pdatatype),\n\t\t\t\t\t\t\t\t\t\tm_att(att),\n#pragma warning (disable : 4355 )\n\t\t\t\t\t\t\t\t\t\tm_history(this, pdatatype->m_typeSize, att.topic.historyQos, att.topic.resourceLimitsQos,att.historyMemoryPolicy),\n\t\t\t\t\t\t\t\t\t\tmp_listener(listen),\n#pragma warning (disable : 4355 )\n\t\t\t\t\t\t\t\t\t\tm_writerListener(this),\n\t\t\t\t\t\t\t\t\t\tmp_userPublisher(nullptr),\n\t\t\t\t\t\t\t\t\t\tmp_rtpsParticipant(nullptr)\n{\n\n}\n\nPublisherImpl::~PublisherImpl()\n{\n\tconst char* const METHOD_NAME = \"~PublisherImpl\";\n\tlogInfo(PUBLISHER,this->getGuid().entityId << \" in topic: \"<m_att.topic.topicName);\n\tRTPSDomain::removeRTPSWriter(mp_writer);\n\tdelete(this->mp_userPublisher);\n}\n\n\n\nbool PublisherImpl::create_new_change(ChangeKind_t changeKind, void* data)\n{\n return create_new_change_with_params(changeKind, data, WRITE_PARAM_DEFAULT);\n}\n\nbool PublisherImpl::create_new_change_with_params(ChangeKind_t changeKind, void* data, WriteParams &wparams)\n{\n\tconst char* const METHOD_NAME = \"create_new_change\";\n\n \/\/\/ Preconditions\n\tif (data == nullptr)\n\t{\n\t\tlogError(PUBLISHER, \"Data pointer not valid\");\n\t\treturn false;\n\t}\n\n\tif(changeKind == NOT_ALIVE_UNREGISTERED || changeKind == NOT_ALIVE_DISPOSED ||\n\t\t\tchangeKind == NOT_ALIVE_DISPOSED_UNREGISTERED)\n\t{\n\t\tif(m_att.topic.topicKind == NO_KEY)\n\t\t{\n\t\t\tlogError(PUBLISHER,\"Topic is NO_KEY, operation not permitted\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tInstanceHandle_t handle;\n\tif(m_att.topic.topicKind == WITH_KEY)\n\t{\n\t\tmp_type->getKey(data,&handle);\n\t}\n\n\tCacheChange_t* ch = mp_writer->new_change(mp_type->getSerializedSizeProvider(data), changeKind,handle);\n\tif(ch != nullptr)\n\t{\n\t\tif(changeKind == ALIVE)\n\t\t{\n\t\t\t\/\/First check that we can actually write to the buffer, then write\n\t\t\t\n\t\t\t\/\/Static mode implies making sure the buffer size is enough for the maximum posible piece of data\n\t\t\tif( (m_att.historyMemoryPolicy == PREALLOCATED_MEMORY_MODE) && ch->serializedPayload.max_size > mp_type->m_typeSize)\n\t\t\t{\n\t\t\t\tlogWarning(RTPS_WRITER,\n\t\t\t\t\t\"Serialized Payload length larger than maximum type size (\" <<\n\t\t\t\t\tch->serializedPayload.length << \"\/\" << mp_type->m_typeSize << \")\");\n\t\t\t\tm_history.release_Cache(ch);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\/\/In the other modes, the cachechange is expected to at least be initialized at this point\n\t\t\tif(ch->serializedPayload.max_size == 0)\n\t\t\t{\n\t\t\t\tlogWarning(RTPS_WRITER,\"Serialized Payload length must be set to >0 \";);\n\t\t\t\tm_history.release_Cache(ch);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\/\/If these two checks are correct, we asume the cachechange is valid and thwn we can write to it.\t\n\t\t\tif(!mp_type->serialize(data,&ch->serializedPayload))\n\t\t\t{\n\t\t\t\tlogWarning(RTPS_WRITER,\"RTPSWriter:Serialization returns false\";);\n\t\t\t\tm_history.release_Cache(ch);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n \/\/ If it is big data, frament it.\n uint32_t high_mark = (mp_participant->getAttributes().rtps.sendSocketBufferSize - RTPSMESSAGE_COMMON_RTPS_PAYLOAD_SIZE) > PAYLOAD_MAX_SIZE ? PAYLOAD_MAX_SIZE : (mp_participant->getAttributes().rtps.sendSocketBufferSize - RTPSMESSAGE_COMMON_RTPS_PAYLOAD_SIZE);\n\n if(ch->serializedPayload.length > high_mark)\n {\n \/\/\/ Fragment the data.\n \/\/ Set the fragment size to the cachechange.\n \/\/ Note: high_mark will always be a value that can be casted to uint16_t)\n ch->setFragmentSize((uint16_t)high_mark);\n }\n\n if(&wparams != &WRITE_PARAM_DEFAULT)\n {\n ch->write_params = wparams;\n }\n\n\t\tif(!this->m_history.add_pub_change(ch, wparams))\n\t\t{\n\t\t\tm_history.release_Cache(ch);\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n\nbool PublisherImpl::removeMinSeqChange()\n{\n\treturn m_history.removeMinChange();\n}\n\nbool PublisherImpl::removeAllChange(size_t* removed)\n{\n\treturn m_history.removeAllChange(removed);\n}\n\nconst GUID_t& PublisherImpl::getGuid()\n{\n\treturn mp_writer->getGuid();\n}\n\/\/\nbool PublisherImpl::updateAttributes(PublisherAttributes& att)\n{\n\tconst char* const METHOD_NAME = \"updateAttributes\";\n\tbool updated = true;\n\tbool missing = false;\n\tif(this->m_att.qos.m_reliability.kind == RELIABLE_RELIABILITY_QOS)\n\t{\n\t\tif(att.unicastLocatorList.size() != this->m_att.unicastLocatorList.size() ||\n\t\t\t\tatt.multicastLocatorList.size() != this->m_att.multicastLocatorList.size())\n\t\t{\n\t\t\tlogWarning(PUBLISHER,\"Locator Lists cannot be changed or updated in this version\");\n\t\t\tupdated &= false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor(LocatorListIterator lit1 = this->m_att.unicastLocatorList.begin();\n\t\t\t\t\tlit1!=this->m_att.unicastLocatorList.end();++lit1)\n\t\t\t{\n\t\t\t\tmissing = true;\n\t\t\t\tfor(LocatorListIterator lit2 = att.unicastLocatorList.begin();\n\t\t\t\t\t\tlit2!= att.unicastLocatorList.end();++lit2)\n\t\t\t\t{\n\t\t\t\t\tif(*lit1 == *lit2)\n\t\t\t\t\t{\n\t\t\t\t\t\tmissing = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(missing)\n\t\t\t\t{\n\t\t\t\t\tlogWarning(PUBLISHER,\"Locator: \"<< *lit1 << \" not present in new list\");\n\t\t\t\t\tlogWarning(PUBLISHER,\"Locator Lists cannot be changed or updated in this version\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(LocatorListIterator lit1 = this->m_att.multicastLocatorList.begin();\n\t\t\t\t\tlit1!=this->m_att.multicastLocatorList.end();++lit1)\n\t\t\t{\n\t\t\t\tmissing = true;\n\t\t\t\tfor(LocatorListIterator lit2 = att.multicastLocatorList.begin();\n\t\t\t\t\t\tlit2!= att.multicastLocatorList.end();++lit2)\n\t\t\t\t{\n\t\t\t\t\tif(*lit1 == *lit2)\n\t\t\t\t\t{\n\t\t\t\t\t\tmissing = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(missing)\n\t\t\t\t{\n\t\t\t\t\tlogWarning(PUBLISHER,\"Locator: \"<< *lit1<< \" not present in new list\");\n\t\t\t\t\tlogWarning(PUBLISHER,\"Locator Lists cannot be changed or updated in this version\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/TOPIC ATTRIBUTES\n\tif(this->m_att.topic != att.topic)\n\t{\n\t\tlogWarning(PUBLISHER,\"Topic Attributes cannot be updated\");\n\t\tupdated &= false;\n\t}\n\t\/\/QOS:\n\t\/\/CHECK IF THE QOS CAN BE SET\n\tif(!this->m_att.qos.canQosBeUpdated(att.qos))\n\t{\n\t\tupdated &=false;\n\t}\n\tif(updated)\n\t{\n\t\tif(this->m_att.qos.m_reliability.kind == RELIABLE_RELIABILITY_QOS)\n\t\t{\n\t\t\t\/\/UPDATE TIMES:\n\t\t\tStatefulWriter* sfw = (StatefulWriter*)mp_writer;\n\t\t\tsfw->updateTimes(att.times);\n\t\t}\n\t\tthis->m_att.qos.setQos(att.qos,false);\n\t\tthis->m_att = att;\n\t\t\/\/Notify the participant that a Writer has changed its QOS\n\t\tmp_rtpsParticipant->updateWriter(this->mp_writer,m_att.qos);\n\t}\n\n\n\treturn updated;\n}\n\nvoid PublisherImpl::PublisherWriterListener::onWriterMatched(RTPSWriter* \/*writer*\/,MatchingInfo& info)\n{\n\tif(mp_publisherImpl->mp_listener!=nullptr)\n\t\tmp_publisherImpl->mp_listener->onPublicationMatched(mp_publisherImpl->mp_userPublisher,info);\n}\n\nbool PublisherImpl::clean_history(unsigned int max)\n{\n if(m_att.topic.historyQos.kind == HistoryQosPolicyKind::KEEP_ALL_HISTORY_QOS)\n return mp_writer->clean_history(max);\n else\n return mp_writer->remove_older_changes(max);\n}\n\nbool PublisherImpl::wait_for_all_acked(const Time_t& max_wait)\n{\n return mp_writer->wait_for_all_acked(max_wait);\n}\n\nRemoving duplicate safechecks on cachechanges (PublisherImpl)\/\/ Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/*\n * Publisher.cpp\n *\n *\/\n\n#include \"PublisherImpl.h\"\n#include \"..\/participant\/ParticipantImpl.h\"\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n\nusing namespace eprosima::fastrtps;\nusing namespace ::rtps;\n\n\nstatic const char* const CLASS_NAME = \"PublisherImpl\";\n\n::rtps::WriteParams WRITE_PARAM_DEFAULT;\n\nPublisherImpl::PublisherImpl(ParticipantImpl* p,TopicDataType*pdatatype,\n\t\tPublisherAttributes& att,PublisherListener* listen ):\n\t\t\t\t\t\t\t\t\t\tmp_participant(p),\n\t\t\t\t\t\t\t\t\t\tmp_writer(nullptr),\n\t\t\t\t\t\t\t\t\t\tmp_type(pdatatype),\n\t\t\t\t\t\t\t\t\t\tm_att(att),\n#pragma warning (disable : 4355 )\n\t\t\t\t\t\t\t\t\t\tm_history(this, pdatatype->m_typeSize, att.topic.historyQos, att.topic.resourceLimitsQos,att.historyMemoryPolicy),\n\t\t\t\t\t\t\t\t\t\tmp_listener(listen),\n#pragma warning (disable : 4355 )\n\t\t\t\t\t\t\t\t\t\tm_writerListener(this),\n\t\t\t\t\t\t\t\t\t\tmp_userPublisher(nullptr),\n\t\t\t\t\t\t\t\t\t\tmp_rtpsParticipant(nullptr)\n{\n\n}\n\nPublisherImpl::~PublisherImpl()\n{\n\tconst char* const METHOD_NAME = \"~PublisherImpl\";\n\tlogInfo(PUBLISHER,this->getGuid().entityId << \" in topic: \"<m_att.topic.topicName);\n\tRTPSDomain::removeRTPSWriter(mp_writer);\n\tdelete(this->mp_userPublisher);\n}\n\n\n\nbool PublisherImpl::create_new_change(ChangeKind_t changeKind, void* data)\n{\n return create_new_change_with_params(changeKind, data, WRITE_PARAM_DEFAULT);\n}\n\nbool PublisherImpl::create_new_change_with_params(ChangeKind_t changeKind, void* data, WriteParams &wparams)\n{\n\tconst char* const METHOD_NAME = \"create_new_change\";\n\n \/\/\/ Preconditions\n\tif (data == nullptr)\n\t{\n\t\tlogError(PUBLISHER, \"Data pointer not valid\");\n\t\treturn false;\n\t}\n\n\tif(changeKind == NOT_ALIVE_UNREGISTERED || changeKind == NOT_ALIVE_DISPOSED ||\n\t\t\tchangeKind == NOT_ALIVE_DISPOSED_UNREGISTERED)\n\t{\n\t\tif(m_att.topic.topicKind == NO_KEY)\n\t\t{\n\t\t\tlogError(PUBLISHER,\"Topic is NO_KEY, operation not permitted\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tInstanceHandle_t handle;\n\tif(m_att.topic.topicKind == WITH_KEY)\n\t{\n\t\tmp_type->getKey(data,&handle);\n\t}\n\n\tCacheChange_t* ch = mp_writer->new_change(mp_type->getSerializedSizeProvider(data), changeKind,handle);\n\tif(ch != nullptr)\n\t{\n\t\tif(changeKind == ALIVE)\n\t\t{\n\t\t\t\/\/If these two checks are correct, we asume the cachechange is valid and thwn we can write to it.\t\n\t\t\tif(!mp_type->serialize(data,&ch->serializedPayload))\n\t\t\t{\n\t\t\t\tlogWarning(RTPS_WRITER,\"RTPSWriter:Serialization returns false\";);\n\t\t\t\tm_history.release_Cache(ch);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n \/\/ If it is big data, frament it.\n uint32_t high_mark = (mp_participant->getAttributes().rtps.sendSocketBufferSize - RTPSMESSAGE_COMMON_RTPS_PAYLOAD_SIZE) > PAYLOAD_MAX_SIZE ? PAYLOAD_MAX_SIZE : (mp_participant->getAttributes().rtps.sendSocketBufferSize - RTPSMESSAGE_COMMON_RTPS_PAYLOAD_SIZE);\n\n if(ch->serializedPayload.length > high_mark)\n {\n \/\/\/ Fragment the data.\n \/\/ Set the fragment size to the cachechange.\n \/\/ Note: high_mark will always be a value that can be casted to uint16_t)\n ch->setFragmentSize((uint16_t)high_mark);\n }\n\n if(&wparams != &WRITE_PARAM_DEFAULT)\n {\n ch->write_params = wparams;\n }\n\n\t\tif(!this->m_history.add_pub_change(ch, wparams))\n\t\t{\n\t\t\tm_history.release_Cache(ch);\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n\nbool PublisherImpl::removeMinSeqChange()\n{\n\treturn m_history.removeMinChange();\n}\n\nbool PublisherImpl::removeAllChange(size_t* removed)\n{\n\treturn m_history.removeAllChange(removed);\n}\n\nconst GUID_t& PublisherImpl::getGuid()\n{\n\treturn mp_writer->getGuid();\n}\n\/\/\nbool PublisherImpl::updateAttributes(PublisherAttributes& att)\n{\n\tconst char* const METHOD_NAME = \"updateAttributes\";\n\tbool updated = true;\n\tbool missing = false;\n\tif(this->m_att.qos.m_reliability.kind == RELIABLE_RELIABILITY_QOS)\n\t{\n\t\tif(att.unicastLocatorList.size() != this->m_att.unicastLocatorList.size() ||\n\t\t\t\tatt.multicastLocatorList.size() != this->m_att.multicastLocatorList.size())\n\t\t{\n\t\t\tlogWarning(PUBLISHER,\"Locator Lists cannot be changed or updated in this version\");\n\t\t\tupdated &= false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor(LocatorListIterator lit1 = this->m_att.unicastLocatorList.begin();\n\t\t\t\t\tlit1!=this->m_att.unicastLocatorList.end();++lit1)\n\t\t\t{\n\t\t\t\tmissing = true;\n\t\t\t\tfor(LocatorListIterator lit2 = att.unicastLocatorList.begin();\n\t\t\t\t\t\tlit2!= att.unicastLocatorList.end();++lit2)\n\t\t\t\t{\n\t\t\t\t\tif(*lit1 == *lit2)\n\t\t\t\t\t{\n\t\t\t\t\t\tmissing = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(missing)\n\t\t\t\t{\n\t\t\t\t\tlogWarning(PUBLISHER,\"Locator: \"<< *lit1 << \" not present in new list\");\n\t\t\t\t\tlogWarning(PUBLISHER,\"Locator Lists cannot be changed or updated in this version\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(LocatorListIterator lit1 = this->m_att.multicastLocatorList.begin();\n\t\t\t\t\tlit1!=this->m_att.multicastLocatorList.end();++lit1)\n\t\t\t{\n\t\t\t\tmissing = true;\n\t\t\t\tfor(LocatorListIterator lit2 = att.multicastLocatorList.begin();\n\t\t\t\t\t\tlit2!= att.multicastLocatorList.end();++lit2)\n\t\t\t\t{\n\t\t\t\t\tif(*lit1 == *lit2)\n\t\t\t\t\t{\n\t\t\t\t\t\tmissing = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(missing)\n\t\t\t\t{\n\t\t\t\t\tlogWarning(PUBLISHER,\"Locator: \"<< *lit1<< \" not present in new list\");\n\t\t\t\t\tlogWarning(PUBLISHER,\"Locator Lists cannot be changed or updated in this version\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/TOPIC ATTRIBUTES\n\tif(this->m_att.topic != att.topic)\n\t{\n\t\tlogWarning(PUBLISHER,\"Topic Attributes cannot be updated\");\n\t\tupdated &= false;\n\t}\n\t\/\/QOS:\n\t\/\/CHECK IF THE QOS CAN BE SET\n\tif(!this->m_att.qos.canQosBeUpdated(att.qos))\n\t{\n\t\tupdated &=false;\n\t}\n\tif(updated)\n\t{\n\t\tif(this->m_att.qos.m_reliability.kind == RELIABLE_RELIABILITY_QOS)\n\t\t{\n\t\t\t\/\/UPDATE TIMES:\n\t\t\tStatefulWriter* sfw = (StatefulWriter*)mp_writer;\n\t\t\tsfw->updateTimes(att.times);\n\t\t}\n\t\tthis->m_att.qos.setQos(att.qos,false);\n\t\tthis->m_att = att;\n\t\t\/\/Notify the participant that a Writer has changed its QOS\n\t\tmp_rtpsParticipant->updateWriter(this->mp_writer,m_att.qos);\n\t}\n\n\n\treturn updated;\n}\n\nvoid PublisherImpl::PublisherWriterListener::onWriterMatched(RTPSWriter* \/*writer*\/,MatchingInfo& info)\n{\n\tif(mp_publisherImpl->mp_listener!=nullptr)\n\t\tmp_publisherImpl->mp_listener->onPublicationMatched(mp_publisherImpl->mp_userPublisher,info);\n}\n\nbool PublisherImpl::clean_history(unsigned int max)\n{\n if(m_att.topic.historyQos.kind == HistoryQosPolicyKind::KEEP_ALL_HISTORY_QOS)\n return mp_writer->clean_history(max);\n else\n return mp_writer->remove_older_changes(max);\n}\n\nbool PublisherImpl::wait_for_all_acked(const Time_t& max_wait)\n{\n return mp_writer->wait_for_all_acked(max_wait);\n}\n\n<|endoftext|>"} {"text":"#include \"debug_log.hpp\"\n#include \"connection_pool.hpp\"\n\n#include \n#include \n#include \n\nnamespace {\nvoid wait_on_signal() {\n boost::asio::io_service signal_io_service;\n boost::asio::io_service::work work{signal_io_service};\n boost::asio::signal_set signals(signal_io_service, SIGINT, SIGTERM);\n signals.async_wait([&](...) { signal_io_service.stop(); });\n signal_io_service.run();\n}\n\ntemplate\ninline const T max(T a, U b) { return a < b ? b : a; }\n} \/\/ namespace\n\nint main(int argc, char *argv[]) {\n using namespace riak;\n using namespace std::chrono;\n namespace po = boost::program_options;\n\n \/\/ Parse arguments\n std::string hostname;\n uint16_t port, num_threads, num_sockets, highwatermark;\n uint32_t nmsgs;\n po::options_description description{\n \"Sends a lot of get_object requests to a Riak node using a connection pool.\"\n };\n description.add_options()\n (\"help,h\", \"prints this help message\")\n (\"hostname,n\",\n po::value(&hostname)->default_value(\"localhost\"),\n \"hostname of Riak node\")\n (\"port,p\",\n po::value(&port)->default_value(10017),\n \"port to connect on Riak node\")\n (\"num-threads,t\",\n po::value(&num_threads)->default_value(2),\n \"number of I\/O threads\")\n (\"num-sockets,s\",\n po::value(&num_sockets)->default_value(256),\n \"number of sockets in pool\")\n (\"highwatermark,k\",\n po::value(&highwatermark)->default_value(1024),\n \"max buffered requests\")\n (\"nmsgs,m\",\n po::value(&nmsgs)->default_value(1000),\n \"number of messages to send to the node\");\n po::variables_map variables;\n try {\n po::store(po::parse_command_line(argc, argv, description), variables);\n po::notify(variables);\n } catch (const std::exception& e) {\n DLOG << e.what();\n return -1;\n }\n if (variables.count(\"help\")) {\n std::cerr << description << std::endl;\n return -1;\n }\n\n \/\/ Simple connection_pool usage:\n \/\/ riak::connection_pool conn(hostname, port, num_threads, num_sockets,\n \/\/ highwatermark);\n \/\/ conn.send(string_message1, deadline_ms, handler);\n \/\/ conn.send(string_message2, deadline_ms, handler);\n \/\/ etc.\n \/\/\n \/\/ What follows is a mess because this is throwaway code.\n\n std::mutex num_sent_mutex;\n uint32_t num_sent = 0;\n auto start_clock = high_resolution_clock::now();\n auto first_response_clock = start_clock;\n\n std::string message{\"\\x09\\x0A\\01\\x62\\x12\\x01\\x6B\", 7};\n DLOG << \"Creating connection pool...\";\n iasdf\n riak::connection_pool conn(hostname, port, num_threads, num_sockets,\n highwatermark);\n\n DLOG << \"Buffering messages...\";\n auto log_every = max(1, nmsgs \/ 20);\n for (int i = 0 ; i < nmsgs ; ++ i) {\n conn.send(\n message, 1000,\n [&](std::string response, std::error_code error) {\n std::lock_guard lock{num_sent_mutex};\n ++num_sent;\n if (num_sent == 1) {\n first_response_clock = high_resolution_clock::now();\n double secs = duration_cast(\n first_response_clock - start_clock).count() \/ 1000.0;\n DLOG << error.message() << \" [first message \" << secs << \" secs].\";\n } else if (num_sent % log_every == 0 || num_sent == nmsgs) {\n if (num_sent <= num_sockets) return;\n auto total = duration_cast(\n high_resolution_clock::now() - first_response_clock);\n auto msgs_per_sec =\n (num_sent - num_sockets) \/ (double(total.count()) \/ 1000.0);\n DLOG << error.message() << \" [sent \" << num_sent << \" at \"\n << msgs_per_sec << \" messages\/sec]\";\n }\n });\n\n if (i % log_every == 0) DLOG << \"Buffered \" << i << \" messages.\";\n }\n DLOG << \"Buffered all the messages. Waiting on signal...\";\n\n wait_on_signal();\n DLOG << \"Signal caught.\";\n\n return 0;\n}\nfixed a stray char sequence#include \"debug_log.hpp\"\n#include \"connection_pool.hpp\"\n\n#include \n#include \n#include \n\nnamespace {\nvoid wait_on_signal() {\n boost::asio::io_service signal_io_service;\n boost::asio::io_service::work work{signal_io_service};\n boost::asio::signal_set signals(signal_io_service, SIGINT, SIGTERM);\n signals.async_wait([&](...) { signal_io_service.stop(); });\n signal_io_service.run();\n}\n\ntemplate\ninline const T max(T a, U b) { return a < b ? b : a; }\n} \/\/ namespace\n\nint main(int argc, char *argv[]) {\n using namespace riak;\n using namespace std::chrono;\n namespace po = boost::program_options;\n\n \/\/ Parse arguments\n std::string hostname;\n uint16_t port, num_threads, num_sockets, highwatermark;\n uint32_t nmsgs;\n po::options_description description{\n \"Sends a lot of get_object requests to a Riak node using a connection pool.\"\n };\n description.add_options()\n (\"help,h\", \"prints this help message\")\n (\"hostname,n\",\n po::value(&hostname)->default_value(\"localhost\"),\n \"hostname of Riak node\")\n (\"port,p\",\n po::value(&port)->default_value(10017),\n \"port to connect on Riak node\")\n (\"num-threads,t\",\n po::value(&num_threads)->default_value(2),\n \"number of I\/O threads\")\n (\"num-sockets,s\",\n po::value(&num_sockets)->default_value(256),\n \"number of sockets in pool\")\n (\"highwatermark,k\",\n po::value(&highwatermark)->default_value(1024),\n \"max buffered requests\")\n (\"nmsgs,m\",\n po::value(&nmsgs)->default_value(1000),\n \"number of messages to send to the node\");\n po::variables_map variables;\n try {\n po::store(po::parse_command_line(argc, argv, description), variables);\n po::notify(variables);\n } catch (const std::exception& e) {\n DLOG << e.what();\n return -1;\n }\n if (variables.count(\"help\")) {\n std::cerr << description << std::endl;\n return -1;\n }\n\n \/\/ Simple connection_pool usage:\n \/\/ riak::connection_pool conn(hostname, port, num_threads, num_sockets,\n \/\/ highwatermark);\n \/\/ conn.send(string_message1, deadline_ms, handler);\n \/\/ conn.send(string_message2, deadline_ms, handler);\n \/\/ etc.\n \/\/\n \/\/ What follows is a mess because this is throwaway code.\n\n std::mutex num_sent_mutex;\n uint32_t num_sent = 0;\n auto start_clock = high_resolution_clock::now();\n auto first_response_clock = start_clock;\n\n std::string message{\"\\x09\\x0A\\01\\x62\\x12\\x01\\x6B\", 7};\n DLOG << \"Creating connection pool...\";\n riak::connection_pool conn(hostname, port, num_threads, num_sockets,\n highwatermark);\n\n DLOG << \"Buffering messages...\";\n auto log_every = max(1, nmsgs \/ 20);\n for (int i = 0 ; i < nmsgs ; ++ i) {\n conn.send(\n message, 1000,\n [&](std::string response, std::error_code error) {\n std::lock_guard lock{num_sent_mutex};\n ++num_sent;\n if (num_sent == 1) {\n first_response_clock = high_resolution_clock::now();\n double secs = duration_cast(\n first_response_clock - start_clock).count() \/ 1000.0;\n DLOG << error.message() << \" [first message \" << secs << \" secs].\";\n } else if (num_sent % log_every == 0 || num_sent == nmsgs) {\n if (num_sent <= num_sockets) return;\n auto total = duration_cast(\n high_resolution_clock::now() - first_response_clock);\n auto msgs_per_sec =\n (num_sent - num_sockets) \/ (double(total.count()) \/ 1000.0);\n DLOG << error.message() << \" [sent \" << num_sent << \" at \"\n << msgs_per_sec << \" messages\/sec]\";\n }\n });\n\n if (i % log_every == 0) DLOG << \"Buffered \" << i << \" messages.\";\n }\n DLOG << \"Buffered all the messages. Waiting on signal...\";\n\n wait_on_signal();\n DLOG << \"Signal caught.\";\n\n return 0;\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"opencv2\/opencv.hpp\"\n\nextern \"C\" {\n#include \"vl\/generic.h\"\n#include \"vl\/slic.h\"\n}\n\n#include \"util.hpp\"\n\nusing namespace cv;\n\ntypedef unsigned int uint;\n\nvoid _getSLICSegments(const Mat& img, std::vector& segmentation)\n{\n\tuint H = img.rows,\n\t W = img.cols,\n\t HW = H * W;\n\n\t\/\/ Convert format from LABLAB to LLAABB (for vlfeat)\n\tauto img_vl = new float[HW * 3];\n\tauto img_ = img.ptr(0);\n\tfor (uint j = 0; j < H; j++) {\n\t\tfor (uint i = 0; i < W; i++) {\n\t\t\timg_vl[j * W + i] = img_[j * W + i][0];\n\t\t\timg_vl[j * W + i + HW] = img_[j * W + i][1];\n\t\t\timg_vl[j * W + i + HW * 2] = img_[j * W + i][2];\n\t\t}\n\t}\n\n\tvl_size regionSize = HW \/ 5e3,\n\t\tminRegionSize = HW \/ 5e4;\n\tprintf(\"\\nSLIC parameters:\\n- regionSize: %llu\\n- minRegionSize: %llu\\n\",\n\t regionSize, minRegionSize);\n\n\tvl_slic_segment(segmentation.data(), img_vl, W, H, img.channels(),\n\t\t\tregionSize, 200, minRegionSize);\n\n\t\/\/ Visualise segmentation\n\tMat mat = img;\n\tint** labels = new int*[H];\n\tfor (uint j = 0; j < H; j++) {\n\t\tlabels[j] = new int[W];\n\t\tfor (uint i = 0; i < W; i++)\n\t\t\tlabels[j][i] = (int) segmentation[j*W + i];\n\t}\n\n\tint label, labelTop, labelBottom, labelLeft, labelRight;\n\tfor (uint j = 1; j < H - 1; j++) {\n\t\tfor (uint i = 1; i < W - 1; i++) {\n\t\t\tlabel = labels[j][i];\n\t\t\tlabelTop = labels[j - 1][i];\n\t\t\tlabelBottom = labels[j + 1][i];\n\t\t\tlabelLeft = labels[j][i - 1];\n\t\t\tlabelRight = labels[j][i + 1];\n\t\t\tif (label != labelTop || label != labelBottom ||\n\t\t\t label != labelLeft || label != labelRight) {\n\t\t\t\tmat.at(j, i)[0] = 0;\n\t\t\t\tmat.at(j, i)[1] = 0;\n\t\t\t\tmat.at(j, i)[2] = 255;\n\t\t\t}\n\t\t}\n\t}\n\tshowImage(\"SLIC\", mat);\n}\n\nfloat _getSLICVariances(Mat& grey, std::vector& segmentation,\n std::vector& vars)\n{\n\tuint n = vars.size(),\n\t HW = grey.cols * grey.rows;\n\n\t\/\/ 1. Aggregate pixels by super pixel\n\tauto spxl_vals = std::vector>(n);\n\tfor (uint i = 0; i < n; i++) {\n\t\tspxl_vals[i] = std::vector(0);\n\t\tspxl_vals[i].reserve(20);\n\t}\n\n\tvl_uint32 spxl_id;\n\tfloat spxl_val;\n\tfor (uint i = 0; i < HW; i++) {\n\t\tspxl_id = segmentation[i];\n\t\tspxl_val = (float) grey.ptr(0)[i];\n\t\tspxl_vals[spxl_id].push_back(spxl_val);\n\t}\n\n\t\/\/ 2. Calculate variance of group of pixels\n\tfor (uint i = 0; i < n; i++)\n\t\tvars[i] = var(spxl_vals[i]);\n\n\t\/\/ 3. Calculate variance threshold (25% with highest variance)\n\tauto vars_sorted = vars;\n\tstd::sort(vars_sorted.begin(), vars_sorted.end());\n\treturn vars_sorted[n - n \/ 4];\n}\n\n\/**\n * Generates a pattern distinctiveness map\n *\n * 1) [Divide image into 9x9 patches]\n * 2) Perform PCA\n * 3) Project each patch into PCA space\n * 4) Take L1-norm and store to map\n *\/\nMat _getPatternDistinct(const Mat& img, std::vector& segmentation,\n std::vector& spxl_vars, float var_thresh)\n{\n\tuint H = img.rows,\n\t W = img.cols,\n\t Y = H - 1, \/\/ Limit of y indexing\n\t X = W - 1,\n\t IH = H - 2, \/\/ Inner width (sans 1-pixel border)\n\t IW = W - 2; \/\/ Inner height\n\n\tconst uchar* row_p = img.ptr(0); \/\/ Pixel values of i-1th row\n\tconst uchar* row = img.ptr(1); \/\/ Pixel values of ith row\n\tconst uchar* row_n; \/\/ Pixel values of i+1th row\n\n\t\/******************************\/\n\t\/* Create list of 9x9 patches *\/\n\t\/******************************\/\n\tauto _patches = std::vector(0);\n\t_patches.reserve(X * Y * 9);\n\n\t\/\/ Patches in superpixels with var above var_thresh\n\tauto _distpatches = std::vector(0);\n\t_distpatches.reserve(X * Y * 9);\n\n\t\/\/ Iterate over all inner pixels (patches) with variance above threshold\n\tuint i = 0, spxl_i;\n\tfor (uint y = 1; y < Y; y++) {\n\t\trow_n = img.ptr(y + 1);\n\t\tfor (uint x = 1; x < X; x++) {\n\t\t\tspxl_i = segmentation[y*X + x];\n\t\t\tif (spxl_vars[spxl_i] > var_thresh) {\n\t\t\t\t_distpatches.push_back(row_p[x - 1]);\n\t\t\t\t_distpatches.push_back(row_p[x] );\n\t\t\t\t_distpatches.push_back(row_p[x + 1]);\n\t\t\t\t_distpatches.push_back(row [x - 1]);\n\t\t\t\t_distpatches.push_back(row [x] );\n\t\t\t\t_distpatches.push_back(row [x + 1]);\n\t\t\t\t_distpatches.push_back(row_n[x - 1]);\n\t\t\t\t_distpatches.push_back(row_n[x] );\n\t\t\t\t_distpatches.push_back(row_n[x + 1]);\n\t\t\t\ti += 9;\n\t\t\t}\n\n\t\t\t_patches.push_back(row_p[x - 1]);\n\t\t\t_patches.push_back(row_p[x] );\n\t\t\t_patches.push_back(row_p[x + 1]);\n\t\t\t_patches.push_back(row [x - 1]);\n\t\t\t_patches.push_back(row [x] );\n\t\t\t_patches.push_back(row [x + 1]);\n\t\t\t_patches.push_back(row_n[x - 1]);\n\t\t\t_patches.push_back(row_n[x] );\n\t\t\t_patches.push_back(row_n[x + 1]);\n\n\t\t}\n\t\trow_p = row;\n\t\trow = row_n;\n\t}\n\t_distpatches.shrink_to_fit();\n\tauto distpatches = Mat(i \/ 9, 9, CV_8U, _distpatches.data());\n\tauto patches = Mat(X*Y, 9, CV_8U, _patches.data());\n\n\t\/*******\/\n\t\/* PCA *\/\n\t\/*******\/\n\tauto pca = PCA(distpatches, Mat(), CV_PCA_DATA_AS_ROW);\n\n\tMat pca_pos = Mat::zeros(IH * IW, 9, CV_32F); \/\/ Coordinates in PCA space\n\tMat pca_norm = Mat::zeros(IH * IW, 1, CV_32F); \/\/ L1 norm of pca_pos\n\n\tpca.project(patches, pca_pos); \t \/\/ Project patches into PCA space\n\treduce(abs(pca_pos), pca_norm, 1, CV_REDUCE_SUM); \/\/ Calc L1 norm\n\n\t\/\/ Pad with 1-pixel thick black border\n\tMat out_inner = Mat(IH, IW, CV_32F, pca_norm.ptr(0), 0);\n\tMat out;\n\tcopyMakeBorder(out_inner, out, 1, 1, 1, 1, BORDER_CONSTANT, 0);\n\n\treturn out;\n}\n\n\/**\n * Generates a colour distinctiveness map\n *\n * 1)\n *\/\nMat _getColourDistinct(const Mat& img, std::vector& segmentation,\n uint spxl_n)\n{\n\t\/\/ 1. Aggregate pixels by super pixel\n\tauto spxl_vals = std::vector>(spxl_n);\n\tfor (uint i = 0; i < spxl_n; i++) {\n\t\tspxl_vals[i] = std::vector(0);\n\t\tspxl_vals[i].reserve(20);\n\t}\n\n\tauto out = Mat(img.size(), CV_32F);\n\treturn out;\n}\n\n\/**\n * Generates a saliency map using a method from Margolin et al. (2013)\n *\n * 1) Acquire pattern distinctiveness map\n * 2) Acquire colour distinctiveness map\n * 3) Calculate pixelwise multiplication of the two maps\n *\/\nconst float maxSize = 1000.f;\n\nMat getSaliency(const Mat& img)\n{\n\tMat img_BGR;\n\n\tuint H = img.rows,\n\t W = img.cols,\n\t HW = H * W;\n\n\tfloat scale = (float) max(H, W) \/ maxSize;\n\tif (scale > 1.f) {\n\t\tresize(img, img_BGR, Size(W \/ scale, H \/ scale));\n\n\t\tW = W \/ scale;\n\t\tH = H \/ scale;\n\t} else {\n\t\timg_BGR = img;\n\t}\n\n\t\/\/ Get grayscale image to work on\n\tauto img_grey = Mat(img_BGR.size(), img_BGR.type());\n\tcvtColor(img_BGR, img_grey, CV_BGR2GRAY);\n\n\tauto img_lab = Mat(img_BGR.size(), img_BGR.type());\n\tcvtColor(img_BGR, img_lab, CV_BGR2Lab);\n\n\t\/\/ Get SLIC superpixels\n\tauto segmentation = std::vector(H*W);\n\t_getSLICSegments(img_lab, segmentation);\n\n\t\/\/ Calculate variance of super pixels\n\tauto spxl_n = std::accumulate(segmentation.begin(),\n\t\tsegmentation.end(), 0, [&](vl_uint32 b, vl_uint32 n) {\n\t\t\treturn n > b ? n : b;\n\t\t}) + 1;\n\tprintf(\"Calculated %d superpixels.\\n\", spxl_n);\n\tauto spxl_vars = std::vector(spxl_n);\n\tauto var_thresh = _getSLICVariances(img_grey, segmentation, spxl_vars);\n\n\t\/\/ Compute distinctiveness maps\n\tMat patternD = _getPatternDistinct(img_grey, segmentation, spxl_vars,\n\t\t\t\t\t var_thresh);\n\tMat colourD = _getColourDistinct(img_lab, segmentation, spxl_n);\n\t\/\/out = patternD.mul(colourD);\n\tMat out = patternD;\n\n\tif (scale > 1.f) {\n\t\tMat out_scaled = Mat();\n\t\tresize(out, out_scaled, img.size());\n\t\tstd::swap(out, out_scaled);\n\t}\n\treturn out;\n}\nChange parameters to speed up getSaliency#pragma once\n\n#include \"opencv2\/opencv.hpp\"\n\nextern \"C\" {\n#include \"vl\/generic.h\"\n#include \"vl\/slic.h\"\n}\n\n#include \"util.hpp\"\n\nusing namespace cv;\n\ntypedef unsigned int uint;\n\nvoid _getSLICSegments(const Mat& img, std::vector& segmentation)\n{\n\tuint H = img.rows,\n\t W = img.cols,\n\t HW = H * W;\n\n\t\/\/ Convert format from LABLAB to LLAABB (for vlfeat)\n\tauto img_vl = new float[HW * 3];\n\tauto img_ = img.ptr(0);\n\tfor (uint j = 0; j < H; j++) {\n\t\tfor (uint i = 0; i < W; i++) {\n\t\t\timg_vl[j * W + i] = img_[j * W + i][0];\n\t\t\timg_vl[j * W + i + HW] = img_[j * W + i][1];\n\t\t\timg_vl[j * W + i + HW * 2] = img_[j * W + i][2];\n\t\t}\n\t}\n\n\tvl_size regionSize = HW \/ 2e3,\n\t\tminRegionSize = HW \/ 5e4;\n\tprintf(\"\\nSLIC parameters:\\n- regionSize: %llu\\n- minRegionSize: %llu\\n\",\n\t regionSize, minRegionSize);\n\n\tvl_slic_segment(segmentation.data(), img_vl, W, H, img.channels(),\n\t\t\tregionSize, 100, minRegionSize);\n\n\t\/\/ Visualise segmentation\n\tMat mat = img;\n\tint** labels = new int*[H];\n\tfor (uint j = 0; j < H; j++) {\n\t\tlabels[j] = new int[W];\n\t\tfor (uint i = 0; i < W; i++)\n\t\t\tlabels[j][i] = (int) segmentation[j*W + i];\n\t}\n\n\tint label, labelTop, labelBottom, labelLeft, labelRight;\n\tfor (uint j = 1; j < H - 1; j++) {\n\t\tfor (uint i = 1; i < W - 1; i++) {\n\t\t\tlabel = labels[j][i];\n\t\t\tlabelTop = labels[j - 1][i];\n\t\t\tlabelBottom = labels[j + 1][i];\n\t\t\tlabelLeft = labels[j][i - 1];\n\t\t\tlabelRight = labels[j][i + 1];\n\t\t\tif (label != labelTop || label != labelBottom ||\n\t\t\t label != labelLeft || label != labelRight) {\n\t\t\t\tmat.at(j, i)[0] = 0;\n\t\t\t\tmat.at(j, i)[1] = 0;\n\t\t\t\tmat.at(j, i)[2] = 255;\n\t\t\t}\n\t\t}\n\t}\n\tshowImage(\"SLIC\", mat);\n}\n\nfloat _getSLICVariances(Mat& grey, std::vector& segmentation,\n std::vector& vars)\n{\n\tuint n = vars.size(),\n\t HW = grey.cols * grey.rows;\n\n\t\/\/ 1. Aggregate pixels by super pixel\n\tauto spxl_vals = std::vector>(n);\n\tfor (uint i = 0; i < n; i++) {\n\t\tspxl_vals[i] = std::vector(0);\n\t\tspxl_vals[i].reserve(20);\n\t}\n\n\tvl_uint32 spxl_id;\n\tfloat spxl_val;\n\tfor (uint i = 0; i < HW; i++) {\n\t\tspxl_id = segmentation[i];\n\t\tspxl_val = (float) grey.ptr(0)[i];\n\t\tspxl_vals[spxl_id].push_back(spxl_val);\n\t}\n\n\t\/\/ 2. Calculate variance of group of pixels\n\tfor (uint i = 0; i < n; i++)\n\t\tvars[i] = var(spxl_vals[i]);\n\n\t\/\/ 3. Calculate variance threshold (25% with highest variance)\n\tauto vars_sorted = vars;\n\tstd::sort(vars_sorted.begin(), vars_sorted.end());\n\treturn vars_sorted[n - n \/ 4];\n}\n\n\/**\n * Generates a pattern distinctiveness map\n *\n * 1) [Divide image into 9x9 patches]\n * 2) Perform PCA\n * 3) Project each patch into PCA space\n * 4) Take L1-norm and store to map\n *\/\nMat _getPatternDistinct(const Mat& img, std::vector& segmentation,\n std::vector& spxl_vars, float var_thresh)\n{\n\tuint H = img.rows,\n\t W = img.cols,\n\t Y = H - 1, \/\/ Limit of y indexing\n\t X = W - 1,\n\t IH = H - 2, \/\/ Inner width (sans 1-pixel border)\n\t IW = W - 2; \/\/ Inner height\n\n\tconst uchar* row_p = img.ptr(0); \/\/ Pixel values of i-1th row\n\tconst uchar* row = img.ptr(1); \/\/ Pixel values of ith row\n\tconst uchar* row_n; \/\/ Pixel values of i+1th row\n\n\t\/******************************\/\n\t\/* Create list of 9x9 patches *\/\n\t\/******************************\/\n\tauto _patches = std::vector(0);\n\t_patches.reserve(X * Y * 9);\n\n\t\/\/ Patches in superpixels with var above var_thresh\n\tauto _distpatches = std::vector(0);\n\t_distpatches.reserve(X * Y * 9);\n\n\t\/\/ Iterate over all inner pixels (patches) with variance above threshold\n\tuint i = 0, spxl_i;\n\tfor (uint y = 1; y < Y; y++) {\n\t\trow_n = img.ptr(y + 1);\n\t\tfor (uint x = 1; x < X; x++) {\n\t\t\tspxl_i = segmentation[y*X + x];\n\t\t\tif (spxl_vars[spxl_i] > var_thresh) {\n\t\t\t\t_distpatches.push_back(row_p[x - 1]);\n\t\t\t\t_distpatches.push_back(row_p[x] );\n\t\t\t\t_distpatches.push_back(row_p[x + 1]);\n\t\t\t\t_distpatches.push_back(row [x - 1]);\n\t\t\t\t_distpatches.push_back(row [x] );\n\t\t\t\t_distpatches.push_back(row [x + 1]);\n\t\t\t\t_distpatches.push_back(row_n[x - 1]);\n\t\t\t\t_distpatches.push_back(row_n[x] );\n\t\t\t\t_distpatches.push_back(row_n[x + 1]);\n\t\t\t\ti += 9;\n\t\t\t}\n\n\t\t\t_patches.push_back(row_p[x - 1]);\n\t\t\t_patches.push_back(row_p[x] );\n\t\t\t_patches.push_back(row_p[x + 1]);\n\t\t\t_patches.push_back(row [x - 1]);\n\t\t\t_patches.push_back(row [x] );\n\t\t\t_patches.push_back(row [x + 1]);\n\t\t\t_patches.push_back(row_n[x - 1]);\n\t\t\t_patches.push_back(row_n[x] );\n\t\t\t_patches.push_back(row_n[x + 1]);\n\n\t\t}\n\t\trow_p = row;\n\t\trow = row_n;\n\t}\n\t_distpatches.shrink_to_fit();\n\tauto distpatches = Mat(i \/ 9, 9, CV_8U, _distpatches.data());\n\tauto patches = Mat(X*Y, 9, CV_8U, _patches.data());\n\n\t\/*******\/\n\t\/* PCA *\/\n\t\/*******\/\n\tauto pca = PCA(distpatches, Mat(), CV_PCA_DATA_AS_ROW);\n\n\tMat pca_pos = Mat::zeros(IH * IW, 9, CV_32F); \/\/ Coordinates in PCA space\n\tMat pca_norm = Mat::zeros(IH * IW, 1, CV_32F); \/\/ L1 norm of pca_pos\n\n\tpca.project(patches, pca_pos); \t \/\/ Project patches into PCA space\n\treduce(abs(pca_pos), pca_norm, 1, CV_REDUCE_SUM); \/\/ Calc L1 norm\n\n\t\/\/ Pad with 1-pixel thick black border\n\tMat out_inner = Mat(IH, IW, CV_32F, pca_norm.ptr(0), 0);\n\tMat out;\n\tcopyMakeBorder(out_inner, out, 1, 1, 1, 1, BORDER_CONSTANT, 0);\n\n\treturn out;\n}\n\n\/**\n * Generates a colour distinctiveness map\n *\n * 1)\n *\/\nMat _getColourDistinct(const Mat& img, std::vector& segmentation,\n uint spxl_n)\n{\n\t\/\/ 1. Aggregate pixels by super pixel\n\tauto spxl_vals = std::vector>(spxl_n);\n\tfor (uint i = 0; i < spxl_n; i++) {\n\t\tspxl_vals[i] = std::vector(0);\n\t\tspxl_vals[i].reserve(20);\n\t}\n\n\tauto out = Mat(img.size(), CV_32F);\n\treturn out;\n}\n\n\/**\n * Generates a saliency map using a method from Margolin et al. (2013)\n *\n * 1) Acquire pattern distinctiveness map\n * 2) Acquire colour distinctiveness map\n * 3) Calculate pixelwise multiplication of the two maps\n *\/\nconst float maxSize = 600.f;\n\nMat getSaliency(const Mat& img)\n{\n\tMat img_BGR;\n\n\tuint H = img.rows,\n\t W = img.cols,\n\t HW = H * W;\n\n\t\/\/ Scale image to have not more than maxSize pixels on its larger\n\t\/\/ dimension\n\tfloat scale = (float) max(H, W) \/ maxSize;\n\tif (scale > 1.f) {\n\t\tresize(img, img_BGR, Size(W \/ scale, H \/ scale));\n\n\t\tW = W \/ scale;\n\t\tH = H \/ scale;\n\t} else {\n\t\timg_BGR = img;\n\t}\n\n\t\/\/ Get grayscale image to work on\n\tauto img_grey = Mat(img_BGR.size(), img_BGR.type());\n\tcvtColor(img_BGR, img_grey, CV_BGR2GRAY);\n\n\tauto img_lab = Mat(img_BGR.size(), img_BGR.type());\n\tcvtColor(img_BGR, img_lab, CV_BGR2Lab);\n\n\t\/\/ Get SLIC superpixels\n\tauto segmentation = std::vector(H*W);\n\t_getSLICSegments(img_lab, segmentation);\n\n\t\/\/ Calculate variance of super pixels\n\tauto spxl_n = std::accumulate(segmentation.begin(),\n\t\tsegmentation.end(), 0, [&](vl_uint32 b, vl_uint32 n) {\n\t\t\treturn n > b ? n : b;\n\t\t}) + 1;\n\tprintf(\"Calculated %d superpixels.\\n\", spxl_n);\n\tauto spxl_vars = std::vector(spxl_n);\n\tauto var_thresh = _getSLICVariances(img_grey, segmentation, spxl_vars);\n\n\t\/\/ Compute distinctiveness maps\n\tMat patternD = _getPatternDistinct(img_grey, segmentation, spxl_vars,\n\t\t\t\t\t var_thresh);\n\tMat colourD = _getColourDistinct(img_lab, segmentation, spxl_n);\n\t\/\/out = patternD.mul(colourD);\n\tMat out = patternD;\n\n\t\/\/ Scale back to original size for further processing\n\tif (scale > 1.f) {\n\t\tMat out_scaled = Mat();\n\t\tresize(out, out_scaled, img.size());\n\t\tstd::swap(out, out_scaled);\n\t}\n\treturn out;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"Timer.h\"\n\n#define USAGE printf(\"Usage: cp src dst [flag]\\n\")\n\nint main(int argc, char** argv) {\n Timer t1;\n Timer t2;\n Timer t3;\n\n int meth = 3;\n\n \/\/ proper # of args\n if (argc < 3 || argc > 4) {\n USAGE;\n exit(1);\n }\n bool test = (argc == 4) ? strcmp(argv[3], \"--test\") == 0 : false;\n for(int i = 3; i < argc; ++i) {\n if (strlen(argv[i]) >= 2 && argv[i][0] == '-') {\n argv[i][2] = 0;\n meth = atoi(argv[i] + 1);\n } else {\n USAGE;\n exit(1);\n }\n }\n\n struct stat a1;\n struct stat a2;\n\n if (stat(argv[1], &a1) == -1) {\n perror(argv[1]);\n exit(1);\n }\n\n if (stat(argv[2], &a2) != -1) {\n USAGE;\n printf(\"Usage: dst cannot exist or be a directory\\n\");\n exit(1);\n }\n\n errno = 0;\n\n if (S_ISDIR(a1.st_mode)) {\n USAGE;\n printf(\"Usage: src cannot be a directory\\n\");\n exit(1);\n }\n\n\n if (test) {\n goto tst;\nret:\n exit(0);\n }\n\n\n \n switch (meth) {\n case 1: \/\/ istream\/ostream\n {\ntst:\n if (test) {\n t1.start();\n }\n std::ifstream fin(argv[1], std::ios::binary);\n if (!fin.good()) {\n printf(\"Error opening %s\\n\", argv[1]);\n exit(1);\n }\n\n std::ofstream fout(argv[2], std::ios::out);\n if (!fout.is_open()) {\n printf(\"Fatal error: can't open %s\\n\", argv[2]);\n exit(1);\n }\n\n char c = fin.get();\n while (fin.good()) {\n fout.put(c);\n c = fin.get();\n }\n }\n\n if (test) {\n double etime;\n printf(\"C++ istream:\\n\");\n t1.elapsedWallclockTime(etime);\n printf(\"Wall clock: %f\\n\", etime);\n t1.elapsedUserTime(etime);\n printf(\"User clock: %f\\n\", etime);\n t1.elapsedSystemTime(etime);\n printf(\"System clock: %f\\n\", etime);\n } else {\n break;\n }\n\n case 2: \/\/ read\/write 1 char at a time\n {\n if (test) {\n t2.start();\n }\n int fd1 = open(argv[1], O_RDONLY);\n if(fd1 == -1) {\n perror(argv[1]);\n exit(1);\n }\n int fd2 = creat(argv[2], a1.st_mode);\n if(fd2 == -1) {\n perror(argv[2]);\n exit(1);\n }\n\n char c;\n int rret = read(fd1, &c, 1);\n\n while (rret) {\n if (write(fd2, &c, rret) == -1) {\n perror(\"write\");\n exit(1);\n }\n rret = read(fd1, &c, 1);\n }\n if (close(fd1) == -1) {\n perror(\"close fd1\");\n exit(1);\n }\n if (close(fd2) == -1) {\n perror(\"close fd2\");\n exit(1);\n }\n }\n\n if (test) {\n double etime;\n printf(\"\\nread\/write 1 char at a time:\\n\");\n t2.elapsedWallclockTime(etime);\n printf(\"Wall clock: %f\\n\", etime);\n t2.elapsedUserTime(etime);\n printf(\"User clock: %f\\n\", etime);\n t2.elapsedSystemTime(etime);\n printf(\"System clock: %f\\n\", etime);\n } else {\n break;\n }\n\n case 3: \/\/ read\/write BUFSIZ at a time\n {\n if (test) {\n t3.start();\n }\n int fd1 = open(argv[1], O_RDONLY);\n if(fd1 == -1) {\n perror(argv[1]);\n exit(1);\n }\n int fd2 = creat(argv[2], a1.st_mode);\n if(fd2 == -1) {\n perror(argv[2]);\n exit(1);\n }\n\n char c[BUFSIZ];\n int rret = read(fd1, &c, BUFSIZ);\n\n while (rret) {\n if (write(fd2, &c, rret) == -1) {\n perror(\"write\");\n exit(1);\n }\n rret = read(fd1, &c, BUFSIZ);\n }\n if (close(fd1) == -1) {\n perror(\"close fd1\");\n exit(1);\n }\n if (close(fd2) == -1) {\n perror(\"close fd2\");\n exit(1);\n }\n }\n if (test) {\n double etime;\n printf(\"\\nread\/write BUFSIZ chars at a time:\\n\");\n t3.elapsedWallclockTime(etime);\n printf(\"Wall clock: %f\\n\", etime);\n t3.elapsedUserTime(etime);\n printf(\"User clock: %f\\n\", etime);\n t3.elapsedSystemTime(etime);\n printf(\"System clock: %f\\n\", etime);\n goto ret;\n } else {\n break;\n }\n\n default:\n printf(\"No.\\n\");\n exit(1);\n }\n\n return 0;\n}\n\nerror checking#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"Timer.h\"\n\n#define USAGE printf(\"Usage: cp src dst [flag]\\n\")\n\nint main(int argc, char** argv) {\n Timer t1;\n Timer t2;\n Timer t3;\n\n int meth = 3;\n\n \/\/ proper # of args\n if (argc < 3 || argc > 4) {\n USAGE;\n exit(1);\n }\n bool test = (argc == 4) ? strcmp(argv[3], \"--test\") == 0 : false;\n for(int i = 3; i < argc; ++i) {\n if (strlen(argv[i]) >= 2 && argv[i][0] == '-') {\n argv[i][2] = 0;\n meth = atoi(argv[i] + 1);\n } else {\n USAGE;\n exit(1);\n }\n }\n\n struct stat a1;\n struct stat a2;\n\n if (stat(argv[1], &a1) == -1) {\n perror(argv[1]);\n exit(1);\n }\n\n if (stat(argv[2], &a2) != -1) {\n USAGE;\n printf(\"Usage: dst cannot exist or be a directory\\n\");\n exit(1);\n }\n\n errno = 0;\n\n if (S_ISDIR(a1.st_mode)) {\n USAGE;\n printf(\"Usage: src cannot be a directory\\n\");\n exit(1);\n }\n\n\n if (test) {\n goto tst;\nret:\n exit(0);\n }\n\n\n \n switch (meth) {\n case 1: \/\/ istream\/ostream\n {\ntst:\n if (test) {\n t1.start();\n }\n std::ifstream fin(argv[1], std::ios::binary);\n if (!fin.good()) {\n printf(\"Error opening %s\\n\", argv[1]);\n exit(1);\n }\n\n std::ofstream fout(argv[2], std::ios::out);\n if (!fout.is_open()) {\n printf(\"Fatal error: can't open %s\\n\", argv[2]);\n exit(1);\n }\n\n char c = fin.get();\n while (fin.good()) {\n fout.put(c);\n c = fin.get();\n }\n }\n\n if (test) {\n double etime;\n printf(\"C++ istream:\\n\");\n t1.elapsedWallclockTime(etime);\n printf(\"Wall clock: %f\\n\", etime);\n t1.elapsedUserTime(etime);\n printf(\"User clock: %f\\n\", etime);\n t1.elapsedSystemTime(etime);\n printf(\"System clock: %f\\n\", etime);\n } else {\n break;\n }\n\n case 2: \/\/ read\/write 1 char at a time\n {\n if (test) {\n t2.start();\n }\n int fd1 = open(argv[1], O_RDONLY);\n if(fd1 == -1) {\n perror(argv[1]);\n exit(1);\n }\n int fd2 = creat(argv[2], a1.st_mode);\n if(fd2 == -1) {\n perror(argv[2]);\n exit(1);\n }\n\n char c;\n int rret = read(fd1, &c, 1);\n\n while (rret) {\n if (write(fd2, &c, rret) == -1) {\n perror(\"write\");\n exit(1);\n }\n rret = read(fd1, &c, 1);\n }\n if (close(fd1) == -1) {\n perror(\"close fd1\");\n exit(1);\n }\n if (close(fd2) == -1) {\n perror(\"close fd2\");\n exit(1);\n }\n }\n\n if (test) {\n double etime;\n printf(\"\\nread\/write 1 char at a time:\\n\");\n t2.elapsedWallclockTime(etime);\n printf(\"Wall clock: %f\\n\", etime);\n t2.elapsedUserTime(etime);\n printf(\"User clock: %f\\n\", etime);\n t2.elapsedSystemTime(etime);\n printf(\"System clock: %f\\n\", etime);\n } else {\n break;\n }\n\n case 3: \/\/ read\/write BUFSIZ at a time\n {\n if (test) {\n t3.start();\n }\n int fd1 = open(argv[1], O_RDONLY);\n if(fd1 == -1) {\n perror(argv[1]);\n exit(1);\n }\n int fd2 = creat(argv[2], a1.st_mode);\n if(fd2 == -1) {\n perror(argv[2]);\n exit(1);\n }\n\n char c[BUFSIZ];\n int rret = read(fd1, &c, BUFSIZ);\n\n while (rret) {\n if (write(fd2, &c, rret) == -1) {\n perror(\"write\");\n exit(1);\n }\n rret = read(fd1, &c, BUFSIZ);\n }\n if (close(fd1) == -1) {\n perror(\"close fd1\");\n exit(1);\n }\n if (close(fd2) == -1) {\n perror(\"close fd2\");\n exit(1);\n }\n }\n if (test) {\n double etime;\n printf(\"\\nread\/write BUFSIZ chars at a time:\\n\");\n t3.elapsedWallclockTime(etime);\n printf(\"Wall clock: %f\\n\", etime);\n t3.elapsedUserTime(etime);\n printf(\"User clock: %f\\n\", etime);\n t3.elapsedSystemTime(etime);\n printf(\"System clock: %f\\n\", etime);\n goto ret;\n } else {\n break;\n }\n\n default:\n printf(\"No.\\n\");\n exit(1);\n }\n\n return 0;\n perror(\"fixed\");\n perror(\"fixed\");\n perror(\"fixed\");\n perror(\"fixed\");\n perror(\"fixed\");\n}\n\n<|endoftext|>"} {"text":"#include \"Diagnostics.h\"\n\n#include \n#include \n#include \/\/ To check if a file exists\n#include \/\/ For creating ROS string messages\n#include \/\/ For time()\n\nusing namespace std;\nusing namespace gazebo;\n\nDiagnostics::Diagnostics(std::string name) {\n\n this->publishedName = name;\n diagLogPublisher = nodeHandle.advertise(\"\/diagsLog\", 1, true);\n diagnosticDataPublisher = nodeHandle.advertise(\"\/\"+publishedName+\"\/diagnostics\", 10);\n fingerAngleSubscribe = nodeHandle.subscribe(publishedName + \"\/fingerAngle\/prev_cmd\", 10, &Diagnostics::fingerTimestampUpdate, this);\n wristAngleSubscribe = nodeHandle.subscribe(publishedName + \"\/fingerAngle\/prev_cmd\", 10, &Diagnostics::wristTimestampUpdate, this);\n imuSubscribe = nodeHandle.subscribe(publishedName + \"\/imu\", 10, &Diagnostics::imuTimestampUpdate, this);\n odometrySubscribe = nodeHandle.subscribe(publishedName + \"\/odom\", 10, &Diagnostics::odometryTimestampUpdate, this);\n sonarLeftSubscribe = nodeHandle.subscribe(publishedName + \"\/sonarLeft\", 10, &Diagnostics::sonarLeftTimestampUpdate, this);\n sonarCenterSubscribe = nodeHandle.subscribe(publishedName + \"\/sonarCenter\", 10, &Diagnostics::sonarCenterTimestampUpdate, this);\n sonarRightSubscribe = nodeHandle.subscribe(publishedName + \"\/sonarRight\", 10, &Diagnostics::sonarRightTimestampUpdate, this);\n\n \/\/ Initialize the variables we use to track the simulation update rate\n prevRealTime = common::Time(0.0);\n prevSimTime = common::Time(0.0);\n simRate = 0.0f;\n\n \/\/ Setup sensor check timers\n sensorCheckTimer = nodeHandle.createTimer(ros::Duration(sensorCheckInterval), &Diagnostics::sensorCheckTimerEventHandler, this);\n \n simCheckTimer = nodeHandle.createTimer(ros::Duration(sensorCheckInterval), &Diagnostics::simCheckTimerEventHandler, this);\n\n if ( checkIfSimulatedRover() ) {\n \/\/ For processing gazebo messages from the world stats topic.\n \/\/ Used to gather information for simulated rovers\n\n \/\/ Create fake argv and argc for the gazebo setup\n char arg0[] = \"diagnostics\";\n char* argv[] = { &arg0[0], NULL };\n int argc = (int)(sizeof(argv) \/ sizeof(argv[0])) - 1;\n gazebo::setupClient(argc, argv);\n\n \/\/ Create Gazebo node and init\n gazebo::transport::NodePtr newNode(new gazebo::transport::Node());\n gazeboNode = newNode;\n gazeboNode->Init();\n string worldStatsTopic = \"\/gazebo\/default\/world_stats\";\n worldStatsSubscriber = gazeboNode->Subscribe(worldStatsTopic, &Diagnostics::simWorldStatsEventHandler, this);\n \n simulated = true;\n publishInfoLogMessage(\"Diagnostic Package Started. Simulated Rover.\");\n } else {\n simulated = false;\n publishInfoLogMessage(\"Diagnostic Package Started. Physical Rover. \");\n \n try { \n string name = wirelessDiags.setInterface();\n publishInfoLogMessage(\"Monitoring wireless interface \" + name);\n } catch( exception &e ) {\n publishErrorLogMessage(\"Error setting interface name for wireless diagnostics: \" + string(e.what()));\n }\n }\n}\n\nvoid Diagnostics::publishDiagnosticData() {\n if (!simulated) {\n WirelessInfo info;\n\n \/\/ Get info about the wireless interface\n \/\/ Catch and display an error if there was an exception\n try {\n info = wirelessDiags.getInfo();\n } catch( exception &e ){\n publishErrorLogMessage(e.what());\n return;\n}\n\n std_msgs::Float32MultiArray rosMsg;\n rosMsg.data.clear();\n rosMsg.data.push_back(info.quality);\n rosMsg.data.push_back(info.bandwidthUsed);\n rosMsg.data.push_back(-1); \/\/ Sim update rate\n diagnosticDataPublisher.publish(rosMsg); \n }\n}\n\nvoid Diagnostics::publishErrorLogMessage(std::string msg) {\n\n std_msgs::String ros_msg;\n ros_msg.data = \"\" + publishedName+\" (\"+getHumanFriendlyTime()+\"): \" + msg + \"<\/font>\";\n diagLogPublisher.publish(ros_msg);\n\n}\n\nvoid Diagnostics::publishWarningLogMessage(std::string msg) {\n std_msgs::String ros_msg;\n ros_msg.data = \"\" + publishedName+\" (\"+getHumanFriendlyTime()+\"): \" + msg + \"<\/font>\";\n diagLogPublisher.publish(ros_msg);\n}\n\nvoid Diagnostics::publishInfoLogMessage(std::string msg) {\n std_msgs::String ros_msg;\n ros_msg.data = \"\" + publishedName + \" (\"+getHumanFriendlyTime()+\"): \" + msg + \"<\/font>\";\n diagLogPublisher.publish(ros_msg);\n}\n\nvoid Diagnostics::fingerTimestampUpdate(const geometry_msgs::QuaternionStamped::ConstPtr& message) {\n\tfingersTimestamp = message->header.stamp;\n}\n\nvoid Diagnostics::wristTimestampUpdate(const geometry_msgs::QuaternionStamped::ConstPtr& message) {\n\twristTimestamp = message->header.stamp;\n}\n\nvoid Diagnostics::imuTimestampUpdate(const sensor_msgs::Imu::ConstPtr& message) {\n\timuTimestamp = message->header.stamp;\n}\n\nvoid Diagnostics::odometryTimestampUpdate(const nav_msgs::Odometry::ConstPtr& message) {\n\todometryTimestamp = message->header.stamp;\n}\n\nvoid Diagnostics::sonarLeftTimestampUpdate(const sensor_msgs::Range::ConstPtr& message) {\n\tsonarLeftTimestamp = message->header.stamp;\n}\n\nvoid Diagnostics::sonarCenterTimestampUpdate(const sensor_msgs::Range::ConstPtr& message) {\n\tsonarCenterTimestamp = message->header.stamp;\n}\n\nvoid Diagnostics::sonarRightTimestampUpdate(const sensor_msgs::Range::ConstPtr& message) {\n\tsonarRightTimestamp = message->header.stamp;\n}\n\n\/\/ Return the current time in this timezone in \"WeekDay Month Day hr:mni:sec year\" format.\n\/\/ We use this instead of asctime or ctime because it is thread safe\nstring Diagnostics::getHumanFriendlyTime() {\n time_t t = std::time(NULL);\n char humanReadableStr[100];\n \n if (strftime(humanReadableStr, sizeof(humanReadableStr), \"%A %c\", localtime(&t)))\n return humanReadableStr;\n else\n return \"\"; \/\/ There was a problem getting the time. Return the empty string.\n \n}\n\n\/\/ sensor check timeout handler. This function is triggered periodically and calls the\n\/\/ sensor check functions.\nvoid Diagnostics::sensorCheckTimerEventHandler(const ros::TimerEvent& event) {\n\n if (!simulated) {\n checkIMU();\n checkGPS();\n checkSonar();\n checkCamera();\n checkGripper();\n checkOdometry();\n \n publishDiagnosticData();\n }\n\n}\n\nvoid Diagnostics::simCheckTimerEventHandler(const ros::TimerEvent& event) {\n \n if (simulated) {\n std_msgs::Float32MultiArray rosMsg;\n rosMsg.data.clear();\n rosMsg.data.push_back(0.0f);\n rosMsg.data.push_back(0.0f);\n rosMsg.data.push_back(checkSimRate());\n diagnosticDataPublisher.publish(rosMsg);\n }\n \n}\n\nfloat Diagnostics::checkSimRate() {\n return simRate;\n}\n\nvoid Diagnostics::checkIMU() {\n \/\/ Example\n \/\/publishWarningLogMessage(\"IMU Warning\");\n\tif (ros::Time::now() - imuTimestamp <= ros::Duration(2.0)) {\n\t\tif (!imuConnected) {\n\t\t\timuConnected = true;\n\t\t\tpublishInfoLogMessage(\"IMU connected\");\n\t\t}\n\t}\n\telse if (imuConnected) {\n\t\timuConnected = false;\n\t\tpublishErrorLogMessage(\"IMU is not connected\");\n\t}\n}\n\nvoid Diagnostics::checkGPS() {\n \/\/ Example\n \/\/publishWarningLogMessage(\"GPS Warning\");\n\n \/\/ Check that a U-Blox device exists in the connected USB devices list\n\n if ( checkGPSExists() ) {\n \/\/ Notify the GUI only if reconnected after being previously disconnected\n if (!GPSConnected) publishInfoLogMessage(\"GPS reconnected\");\n GPSConnected = true;\n } else { \n if (GPSConnected) \/\/ Guard against repeating the error.\n publishErrorLogMessage(\"GPS is not connected\");\n GPSConnected = false;\n }\n}\n\nvoid Diagnostics::checkCamera() {\n \/\/ Example\n \/\/publishWarningLogMessage(\"Camera Warning\");\n\n \/\/ Check that a Logitec c170 device exists in the connected USB devices list\n if ( checkCameraExists() ) {\n \/\/ Notify the GUI only if reconnected after being previously disconnected\n if (!cameraConnected) publishInfoLogMessage(\"Camera reconnected\");\n cameraConnected = true;\n } else {\n publishErrorLogMessage(\"Camera not connected\");\n cameraConnected = false;\n }\n}\n\nvoid Diagnostics::checkSonar() {\n \/\/Example\n \/\/publishErrorLogMessage(\"Sonar Error\");\n\n\tif (ros::Time::now() - sonarLeftTimestamp <= ros::Duration(2.0)) {\n\t\tif (!sonarLeftConnected) {\n\t\t\tsonarLeftConnected = true;\n\t\t\tpublishInfoLogMessage(\"Left ultrasound connected\");\n\t\t}\n\t}\n\telse if (sonarLeftConnected) {\n\t\tsonarLeftConnected = false;\n\t\tpublishErrorLogMessage(\"Left ultrasound is not connected\");\n\t}\n\n\tif (ros::Time::now() - sonarCenterTimestamp <= ros::Duration(2.0)) {\n\t\tif (!sonarCenterConnected) {\n\t\t\tsonarCenterConnected = true;\n\t\t\tpublishInfoLogMessage(\"Center ultrasound connected\");\n\t\t}\n\t}\n\telse if (sonarCenterConnected) {\n\t\tsonarCenterConnected = false;\n\t\tpublishErrorLogMessage(\"Center ultrasound is not connected\");\n\t}\n\n\tif (ros::Time::now() - sonarRightTimestamp <= ros::Duration(2.0)) {\n\t\tif (!sonarRightConnected) {\n\t\t\tsonarRightConnected = true;\n\t\t\tpublishInfoLogMessage(\"Right ultrasound connected\");\n\t\t}\n\t}\n\telse if (sonarRightConnected) {\n\t\tsonarRightConnected = false;\n\t\tpublishErrorLogMessage(\"Right ultrasound is not connected\");\n\t}\n}\n\nvoid Diagnostics::checkGripper() {\n\t\/\/ Example\n\t\/\/publishWarningLogMessage(\"Gripper Warning\");\n\n\tif (ros::Time::now() - fingersTimestamp > ros::Duration(2.0)) {\n\t\tif (!fingersConnected) {\n\t\t\tfingersConnected = true;\n\t\t\tpublishInfoLogMessage(\"Gripper fingers connected\");\n\t\t}\n\t}\n\telse if (fingersConnected) {\n\t\tfingersConnected = false;\n\t\tpublishErrorLogMessage(\"Gripper fingers are not connected\");\n\t}\n\n\tif (ros::Time::now() - wristTimestamp > ros::Duration(2.0)) {\n\t\tif (!wristConnected) {\n\t\t\twristConnected = true;\n\t\t\tpublishInfoLogMessage(\"Gripper wrist connected\");\n\t\t}\n\t}\n\telse if (wristConnected) {\n\t\twristConnected = false;\n\t\tpublishErrorLogMessage(\"Gripper wrist is not connected\");\n\t}\n}\n\nvoid Diagnostics::checkOdometry() {\n\t\/\/ Example\n\t\/\/publishWarningLogMessage(\"Odometry Warning\");\n\n\tif (ros::Time::now() - odometryTimestamp <= ros::Duration(2.0)) {\n\t\tif (!odometryConnected) {\n\t\t\todometryConnected = true;\n\t\t\tpublishInfoLogMessage(\"Encoders connected\");\n\t\t}\n\t}\n\telse if (odometryConnected) {\n\t\todometryConnected = false;\n\t\tpublishErrorLogMessage(\"Encoders are not connected\");\n\t}\n}\n\n\/\/ Check if the U-Blox GPS is connected\n\/\/ ID_VENDOR = 0x1546\n\/\/ ID_PRODUCT = 0x01a6\nbool Diagnostics::checkGPSExists(){\n uint16_t GPSVendorID = 0x1546;\n uint16_t GPSProductID = 0x01a6;\n return checkUSBDeviceExists( GPSVendorID, GPSProductID );\n}\n\n\/\/ Check if the Logitech c170 camera is connected\n\/\/ ID_VENDOR = 0x046d\n\/\/ ID_PRODUCT = 0x082b\nbool Diagnostics::checkCameraExists(){\n uint16_t cameraVendorID = 0x046d;\n uint16_t cameraProductID = 0x082b;\n return checkUSBDeviceExists( cameraVendorID, cameraProductID );\n}\n\n\n\/\/ Search through the connected USB devices for one that matches the\n\/\/ specified vendorID and productID\nbool Diagnostics::checkUSBDeviceExists(uint16_t vendorID, uint16_t productID){\n \n struct usb_bus *bus;\n struct usb_device *dev;\n usb_init();\n usb_find_busses();\n usb_find_devices();\n\n \/\/ Iterate through busses and devices\n for (bus = usb_busses; bus; bus = bus->next)\n for (dev = bus->devices; dev; dev = dev->next)\n if ( dev->descriptor.idVendor == vendorID && dev->descriptor.idProduct == productID )\n return true; \n\n \/\/ GPS not found\n return false;\n}\n\nvoid Diagnostics::simWorldStatsEventHandler(ConstWorldStatisticsPtr &msg) {\n \n const msgs::Time simTimeMsg = msg->sim_time();\n const msgs::Time realTimeMsg = msg->real_time();\n\n common::Time simTime(simTimeMsg.sec(), simTimeMsg.nsec());\n common::Time realTime(realTimeMsg.sec(), realTimeMsg.nsec());\n \n common::Time deltaSimTime = simTime - prevSimTime;\n common::Time deltaRealTime = realTime - prevRealTime;\n\n prevSimTime = simTime;\n prevRealTime = realTime;\n\n simRate = (deltaSimTime.Double())\/(deltaRealTime.Double());\n}\n\n\/\/ Check whether a rover model file exists with the same name as this rover name\n\/\/ if not then we should be a physcial rover. Need a better method.\nbool Diagnostics::checkIfSimulatedRover() {\n struct stat buffer;\n const char *model_path_env = \"GAZEBO_MODEL_PATH\";\n char *model_root = getenv(model_path_env);\n string model_path = string(model_root)+\"\/\"+publishedName+\"\/model.sdf\";\n return (stat(model_path.c_str(), &buffer) == 0); \n}\n \nDiagnostics::~Diagnostics() {\n gazebo::shutdown();\n}\n\nCorrect camera diagnostics function to avoid repeated errors#include \"Diagnostics.h\"\n\n#include \n#include \n#include \/\/ To check if a file exists\n#include \/\/ For creating ROS string messages\n#include \/\/ For time()\n\nusing namespace std;\nusing namespace gazebo;\n\nDiagnostics::Diagnostics(std::string name) {\n\n this->publishedName = name;\n diagLogPublisher = nodeHandle.advertise(\"\/diagsLog\", 1, true);\n diagnosticDataPublisher = nodeHandle.advertise(\"\/\"+publishedName+\"\/diagnostics\", 10);\n fingerAngleSubscribe = nodeHandle.subscribe(publishedName + \"\/fingerAngle\/prev_cmd\", 10, &Diagnostics::fingerTimestampUpdate, this);\n wristAngleSubscribe = nodeHandle.subscribe(publishedName + \"\/fingerAngle\/prev_cmd\", 10, &Diagnostics::wristTimestampUpdate, this);\n imuSubscribe = nodeHandle.subscribe(publishedName + \"\/imu\", 10, &Diagnostics::imuTimestampUpdate, this);\n odometrySubscribe = nodeHandle.subscribe(publishedName + \"\/odom\", 10, &Diagnostics::odometryTimestampUpdate, this);\n sonarLeftSubscribe = nodeHandle.subscribe(publishedName + \"\/sonarLeft\", 10, &Diagnostics::sonarLeftTimestampUpdate, this);\n sonarCenterSubscribe = nodeHandle.subscribe(publishedName + \"\/sonarCenter\", 10, &Diagnostics::sonarCenterTimestampUpdate, this);\n sonarRightSubscribe = nodeHandle.subscribe(publishedName + \"\/sonarRight\", 10, &Diagnostics::sonarRightTimestampUpdate, this);\n\n \/\/ Initialize the variables we use to track the simulation update rate\n prevRealTime = common::Time(0.0);\n prevSimTime = common::Time(0.0);\n simRate = 0.0f;\n\n \/\/ Setup sensor check timers\n sensorCheckTimer = nodeHandle.createTimer(ros::Duration(sensorCheckInterval), &Diagnostics::sensorCheckTimerEventHandler, this);\n \n simCheckTimer = nodeHandle.createTimer(ros::Duration(sensorCheckInterval), &Diagnostics::simCheckTimerEventHandler, this);\n\n if ( checkIfSimulatedRover() ) {\n \/\/ For processing gazebo messages from the world stats topic.\n \/\/ Used to gather information for simulated rovers\n\n \/\/ Create fake argv and argc for the gazebo setup\n char arg0[] = \"diagnostics\";\n char* argv[] = { &arg0[0], NULL };\n int argc = (int)(sizeof(argv) \/ sizeof(argv[0])) - 1;\n gazebo::setupClient(argc, argv);\n\n \/\/ Create Gazebo node and init\n gazebo::transport::NodePtr newNode(new gazebo::transport::Node());\n gazeboNode = newNode;\n gazeboNode->Init();\n string worldStatsTopic = \"\/gazebo\/default\/world_stats\";\n worldStatsSubscriber = gazeboNode->Subscribe(worldStatsTopic, &Diagnostics::simWorldStatsEventHandler, this);\n \n simulated = true;\n publishInfoLogMessage(\"Diagnostic Package Started. Simulated Rover.\");\n } else {\n simulated = false;\n publishInfoLogMessage(\"Diagnostic Package Started. Physical Rover. \");\n \n try { \n string name = wirelessDiags.setInterface();\n publishInfoLogMessage(\"Monitoring wireless interface \" + name);\n } catch( exception &e ) {\n publishErrorLogMessage(\"Error setting interface name for wireless diagnostics: \" + string(e.what()));\n }\n }\n}\n\nvoid Diagnostics::publishDiagnosticData() {\n if (!simulated) {\n WirelessInfo info;\n\n \/\/ Get info about the wireless interface\n \/\/ Catch and display an error if there was an exception\n try {\n info = wirelessDiags.getInfo();\n } catch( exception &e ){\n publishErrorLogMessage(e.what());\n return;\n}\n\n std_msgs::Float32MultiArray rosMsg;\n rosMsg.data.clear();\n rosMsg.data.push_back(info.quality);\n rosMsg.data.push_back(info.bandwidthUsed);\n rosMsg.data.push_back(-1); \/\/ Sim update rate\n diagnosticDataPublisher.publish(rosMsg); \n }\n}\n\nvoid Diagnostics::publishErrorLogMessage(std::string msg) {\n\n std_msgs::String ros_msg;\n ros_msg.data = \"\" + publishedName+\" (\"+getHumanFriendlyTime()+\"): \" + msg + \"<\/font>\";\n diagLogPublisher.publish(ros_msg);\n\n}\n\nvoid Diagnostics::publishWarningLogMessage(std::string msg) {\n std_msgs::String ros_msg;\n ros_msg.data = \"\" + publishedName+\" (\"+getHumanFriendlyTime()+\"): \" + msg + \"<\/font>\";\n diagLogPublisher.publish(ros_msg);\n}\n\nvoid Diagnostics::publishInfoLogMessage(std::string msg) {\n std_msgs::String ros_msg;\n ros_msg.data = \"\" + publishedName + \" (\"+getHumanFriendlyTime()+\"): \" + msg + \"<\/font>\";\n diagLogPublisher.publish(ros_msg);\n}\n\nvoid Diagnostics::fingerTimestampUpdate(const geometry_msgs::QuaternionStamped::ConstPtr& message) {\n\tfingersTimestamp = message->header.stamp;\n}\n\nvoid Diagnostics::wristTimestampUpdate(const geometry_msgs::QuaternionStamped::ConstPtr& message) {\n\twristTimestamp = message->header.stamp;\n}\n\nvoid Diagnostics::imuTimestampUpdate(const sensor_msgs::Imu::ConstPtr& message) {\n\timuTimestamp = message->header.stamp;\n}\n\nvoid Diagnostics::odometryTimestampUpdate(const nav_msgs::Odometry::ConstPtr& message) {\n\todometryTimestamp = message->header.stamp;\n}\n\nvoid Diagnostics::sonarLeftTimestampUpdate(const sensor_msgs::Range::ConstPtr& message) {\n\tsonarLeftTimestamp = message->header.stamp;\n}\n\nvoid Diagnostics::sonarCenterTimestampUpdate(const sensor_msgs::Range::ConstPtr& message) {\n\tsonarCenterTimestamp = message->header.stamp;\n}\n\nvoid Diagnostics::sonarRightTimestampUpdate(const sensor_msgs::Range::ConstPtr& message) {\n\tsonarRightTimestamp = message->header.stamp;\n}\n\n\/\/ Return the current time in this timezone in \"WeekDay Month Day hr:mni:sec year\" format.\n\/\/ We use this instead of asctime or ctime because it is thread safe\nstring Diagnostics::getHumanFriendlyTime() {\n time_t t = std::time(NULL);\n char humanReadableStr[100];\n \n if (strftime(humanReadableStr, sizeof(humanReadableStr), \"%A %c\", localtime(&t)))\n return humanReadableStr;\n else\n return \"\"; \/\/ There was a problem getting the time. Return the empty string.\n \n}\n\n\/\/ sensor check timeout handler. This function is triggered periodically and calls the\n\/\/ sensor check functions.\nvoid Diagnostics::sensorCheckTimerEventHandler(const ros::TimerEvent& event) {\n\n if (!simulated) {\n checkIMU();\n checkGPS();\n checkSonar();\n checkCamera();\n checkGripper();\n checkOdometry();\n \n publishDiagnosticData();\n }\n\n}\n\nvoid Diagnostics::simCheckTimerEventHandler(const ros::TimerEvent& event) {\n \n if (simulated) {\n std_msgs::Float32MultiArray rosMsg;\n rosMsg.data.clear();\n rosMsg.data.push_back(0.0f);\n rosMsg.data.push_back(0.0f);\n rosMsg.data.push_back(checkSimRate());\n diagnosticDataPublisher.publish(rosMsg);\n }\n \n}\n\nfloat Diagnostics::checkSimRate() {\n return simRate;\n}\n\nvoid Diagnostics::checkIMU() {\n \/\/ Example\n \/\/publishWarningLogMessage(\"IMU Warning\");\n\tif (ros::Time::now() - imuTimestamp <= ros::Duration(2.0)) {\n\t\tif (!imuConnected) {\n\t\t\timuConnected = true;\n\t\t\tpublishInfoLogMessage(\"IMU connected\");\n\t\t}\n\t}\n\telse if (imuConnected) {\n\t\timuConnected = false;\n\t\tpublishErrorLogMessage(\"IMU is not connected\");\n\t}\n}\n\nvoid Diagnostics::checkGPS() {\n \/\/ Example\n \/\/publishWarningLogMessage(\"GPS Warning\");\n\n \/\/ Check that a U-Blox device exists in the connected USB devices list\n\n if ( checkGPSExists() ) {\n \/\/ Notify the GUI only if reconnected after being previously disconnected\n if (!GPSConnected) publishInfoLogMessage(\"GPS reconnected\");\n GPSConnected = true;\n } else { \n if (GPSConnected) \/\/ Guard against repeating the error.\n publishErrorLogMessage(\"GPS is not connected\");\n GPSConnected = false;\n }\n}\n\nvoid Diagnostics::checkCamera() {\n \/\/ Example\n \/\/publishWarningLogMessage(\"Camera Warning\");\n\n \/\/ Check that a Logitec c170 device exists in the connected USB devices list\n if ( checkCameraExists() ) {\n \/\/ Notify the GUI only if reconnected after being previously disconnected\n if (!cameraConnected) publishInfoLogMessage(\"Camera reconnected\");\n cameraConnected = true;\n } else {\n if (cameraConnected)\n publishErrorLogMessage(\"Camera not connected\");\n cameraConnected = false;\n }\n}\n\nvoid Diagnostics::checkSonar() {\n \/\/Example\n \/\/publishErrorLogMessage(\"Sonar Error\");\n\n\tif (ros::Time::now() - sonarLeftTimestamp <= ros::Duration(2.0)) {\n\t\tif (!sonarLeftConnected) {\n\t\t\tsonarLeftConnected = true;\n\t\t\tpublishInfoLogMessage(\"Left ultrasound connected\");\n\t\t}\n\t}\n\telse if (sonarLeftConnected) {\n\t\tsonarLeftConnected = false;\n\t\tpublishErrorLogMessage(\"Left ultrasound is not connected\");\n\t}\n\n\tif (ros::Time::now() - sonarCenterTimestamp <= ros::Duration(2.0)) {\n\t\tif (!sonarCenterConnected) {\n\t\t\tsonarCenterConnected = true;\n\t\t\tpublishInfoLogMessage(\"Center ultrasound connected\");\n\t\t}\n\t}\n\telse if (sonarCenterConnected) {\n\t\tsonarCenterConnected = false;\n\t\tpublishErrorLogMessage(\"Center ultrasound is not connected\");\n\t}\n\n\tif (ros::Time::now() - sonarRightTimestamp <= ros::Duration(2.0)) {\n\t\tif (!sonarRightConnected) {\n\t\t\tsonarRightConnected = true;\n\t\t\tpublishInfoLogMessage(\"Right ultrasound connected\");\n\t\t}\n\t}\n\telse if (sonarRightConnected) {\n\t\tsonarRightConnected = false;\n\t\tpublishErrorLogMessage(\"Right ultrasound is not connected\");\n\t}\n}\n\nvoid Diagnostics::checkGripper() {\n\t\/\/ Example\n\t\/\/publishWarningLogMessage(\"Gripper Warning\");\n\n\tif (ros::Time::now() - fingersTimestamp > ros::Duration(2.0)) {\n\t\tif (!fingersConnected) {\n\t\t\tfingersConnected = true;\n\t\t\tpublishInfoLogMessage(\"Gripper fingers connected\");\n\t\t}\n\t}\n\telse if (fingersConnected) {\n\t\tfingersConnected = false;\n\t\tpublishErrorLogMessage(\"Gripper fingers are not connected\");\n\t}\n\n\tif (ros::Time::now() - wristTimestamp > ros::Duration(2.0)) {\n\t\tif (!wristConnected) {\n\t\t\twristConnected = true;\n\t\t\tpublishInfoLogMessage(\"Gripper wrist connected\");\n\t\t}\n\t}\n\telse if (wristConnected) {\n\t\twristConnected = false;\n\t\tpublishErrorLogMessage(\"Gripper wrist is not connected\");\n\t}\n}\n\nvoid Diagnostics::checkOdometry() {\n\t\/\/ Example\n\t\/\/publishWarningLogMessage(\"Odometry Warning\");\n\n\tif (ros::Time::now() - odometryTimestamp <= ros::Duration(2.0)) {\n\t\tif (!odometryConnected) {\n\t\t\todometryConnected = true;\n\t\t\tpublishInfoLogMessage(\"Encoders connected\");\n\t\t}\n\t}\n\telse if (odometryConnected) {\n\t\todometryConnected = false;\n\t\tpublishErrorLogMessage(\"Encoders are not connected\");\n\t}\n}\n\n\/\/ Check if the U-Blox GPS is connected\n\/\/ ID_VENDOR = 0x1546\n\/\/ ID_PRODUCT = 0x01a6\nbool Diagnostics::checkGPSExists(){\n uint16_t GPSVendorID = 0x1546;\n uint16_t GPSProductID = 0x01a6;\n return checkUSBDeviceExists( GPSVendorID, GPSProductID );\n}\n\n\/\/ Check if the Logitech c170 camera is connected\n\/\/ ID_VENDOR = 0x046d\n\/\/ ID_PRODUCT = 0x082b\nbool Diagnostics::checkCameraExists(){\n uint16_t cameraVendorID = 0x046d;\n uint16_t cameraProductID = 0x082b;\n return checkUSBDeviceExists( cameraVendorID, cameraProductID );\n}\n\n\n\/\/ Search through the connected USB devices for one that matches the\n\/\/ specified vendorID and productID\nbool Diagnostics::checkUSBDeviceExists(uint16_t vendorID, uint16_t productID){\n \n struct usb_bus *bus;\n struct usb_device *dev;\n usb_init();\n usb_find_busses();\n usb_find_devices();\n\n \/\/ Iterate through busses and devices\n for (bus = usb_busses; bus; bus = bus->next)\n for (dev = bus->devices; dev; dev = dev->next)\n if ( dev->descriptor.idVendor == vendorID && dev->descriptor.idProduct == productID )\n return true; \n\n \/\/ GPS not found\n return false;\n}\n\nvoid Diagnostics::simWorldStatsEventHandler(ConstWorldStatisticsPtr &msg) {\n \n const msgs::Time simTimeMsg = msg->sim_time();\n const msgs::Time realTimeMsg = msg->real_time();\n\n common::Time simTime(simTimeMsg.sec(), simTimeMsg.nsec());\n common::Time realTime(realTimeMsg.sec(), realTimeMsg.nsec());\n \n common::Time deltaSimTime = simTime - prevSimTime;\n common::Time deltaRealTime = realTime - prevRealTime;\n\n prevSimTime = simTime;\n prevRealTime = realTime;\n\n simRate = (deltaSimTime.Double())\/(deltaRealTime.Double());\n}\n\n\/\/ Check whether a rover model file exists with the same name as this rover name\n\/\/ if not then we should be a physcial rover. Need a better method.\nbool Diagnostics::checkIfSimulatedRover() {\n struct stat buffer;\n const char *model_path_env = \"GAZEBO_MODEL_PATH\";\n char *model_root = getenv(model_path_env);\n string model_path = string(model_root)+\"\/\"+publishedName+\"\/model.sdf\";\n return (stat(model_path.c_str(), &buffer) == 0); \n}\n \nDiagnostics::~Diagnostics() {\n gazebo::shutdown();\n}\n\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN\n *\n * Authors: Hugo Beauzée-Luyssen \n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#if HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"DiscovererWorker.h\"\n\n#include \"logging\/Logger.h\"\n#include \"Folder.h\"\n#include \"Media.h\"\n#include \"MediaLibrary.h\"\n#include \"Device.h\"\n#include \"utils\/Filename.h\"\n#include \"medialibrary\/filesystem\/Errors.h\"\n#include \n\nnamespace medialibrary\n{\n\nDiscovererWorker::DiscovererWorker(MediaLibrary* ml )\n : m_run( false )\n , m_ml( ml )\n{\n}\n\nDiscovererWorker::~DiscovererWorker()\n{\n stop();\n}\n\nvoid DiscovererWorker::addDiscoverer( std::unique_ptr discoverer )\n{\n m_discoverers.push_back( std::move( discoverer ) );\n}\n\nvoid DiscovererWorker::stop()\n{\n bool running = true;\n if ( m_run.compare_exchange_strong( running, false ) )\n {\n {\n std::unique_lock lock( m_mutex );\n while ( m_tasks.empty() == false )\n m_tasks.pop();\n }\n m_cond.notify_all();\n m_thread.join();\n }\n}\n\nbool DiscovererWorker::discover( const std::string& entryPoint )\n{\n if ( entryPoint.length() == 0 )\n return false;\n LOG_INFO( \"Adding \", entryPoint, \" to the folder discovery list\" );\n enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Discover );\n return true;\n}\n\nvoid DiscovererWorker::remove( const std::string& entryPoint )\n{\n enqueue( entryPoint, Task::Type::Remove );\n}\n\nvoid DiscovererWorker::reload()\n{\n enqueue( \"\", Task::Type::Reload );\n}\n\nvoid DiscovererWorker::reload( const std::string& entryPoint )\n{\n enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Reload );\n}\n\nvoid DiscovererWorker::ban( const std::string& entryPoint )\n{\n enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Ban );\n}\n\nvoid DiscovererWorker::unban( const std::string& entryPoint )\n{\n enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Unban );\n}\n\nvoid DiscovererWorker::reloadDevice(int64_t deviceId)\n{\n enqueue( deviceId, Task::Type::ReloadDevice );\n}\n\nvoid DiscovererWorker::enqueue( const std::string& entryPoint, Task::Type type )\n{\n std::unique_lock lock( m_mutex );\n\n LOG_INFO( \"Queuing entrypoint \", entryPoint, \" of type \",\n static_cast::type>( type ) );\n m_tasks.emplace( entryPoint, type );\n notify();\n}\n\nvoid DiscovererWorker::enqueue( int64_t entityId, Task::Type type )\n{\n std::unique_lock lock( m_mutex );\n\n LOG_INFO( \"Queuing entity \", entityId, \" of type \",\n static_cast::type>( type ) );\n m_tasks.emplace( entityId, type );\n notify();\n}\n\nvoid DiscovererWorker::notify()\n{\n if ( m_thread.get_id() == compat::Thread::id{} )\n {\n m_run = true;\n m_thread = compat::Thread( &DiscovererWorker::run, this );\n }\n \/\/ Since we just added an element, let's not check for size == 0 :)\n else if ( m_tasks.size() == 1 )\n m_cond.notify_all();\n}\n\nvoid DiscovererWorker::run() ML_UNHANDLED_EXCEPTION_INIT\n{\n LOG_INFO( \"Entering DiscovererWorker thread\" );\n m_ml->onDiscovererIdleChanged( false );\n while ( m_run == true )\n {\n Task task;\n {\n std::unique_lock lock( m_mutex );\n if ( m_tasks.size() == 0 )\n {\n m_ml->onDiscovererIdleChanged( true );\n m_cond.wait( lock, [this]() { return m_tasks.size() > 0 || m_run == false; } );\n if ( m_run == false )\n break;\n m_ml->onDiscovererIdleChanged( false );\n }\n task = m_tasks.front();\n m_tasks.pop();\n }\n switch ( task.type )\n {\n case Task::Type::Discover:\n runDiscover( task.entryPoint );\n break;\n case Task::Type::Reload:\n runReload( task.entryPoint );\n break;\n case Task::Type::Remove:\n runRemove( task.entryPoint );\n break;\n case Task::Type::Ban:\n runBan( task.entryPoint );\n break;\n case Task::Type::Unban:\n runUnban( task.entryPoint );\n break;\n case Task::Type::ReloadDevice:\n runReloadDevice( task.entityId );\n break;\n default:\n assert(false);\n }\n }\n LOG_INFO( \"Exiting DiscovererWorker thread\" );\n m_ml->onDiscovererIdleChanged( true );\n}\nML_UNHANDLED_EXCEPTION_BODY( \"DiscovererWorker\" )\n\nvoid DiscovererWorker::runReload( const std::string& entryPoint )\n{\n for ( auto& d : m_discoverers )\n {\n try\n {\n if ( entryPoint.empty() == true )\n {\n \/\/ Let the discoverer invoke the callbacks for all its known folders\n d->reload( *this );\n }\n else\n {\n m_ml->getCb()->onReloadStarted( entryPoint );\n LOG_INFO( \"Reloading folder \", entryPoint );\n auto res = d->reload( entryPoint, *this );\n m_ml->getCb()->onReloadCompleted( entryPoint, res );\n }\n }\n catch(std::exception& ex)\n {\n LOG_ERROR( \"Fatal error while reloading: \", ex.what() );\n }\n if ( m_run == false )\n break;\n }\n}\n\nvoid DiscovererWorker::runRemove( const std::string& ep )\n{\n auto entryPoint = utils::file::toFolderPath( ep );\n auto folder = Folder::fromMrl( m_ml, entryPoint );\n if ( folder == nullptr )\n {\n LOG_WARN( \"Can't remove unknown entrypoint: \", entryPoint );\n m_ml->getCb()->onEntryPointRemoved( ep, false );\n return;\n }\n \/\/ The easy case is that this folder was directly discovered. In which case, we just\n \/\/ have to delete it and it won't be discovered again.\n \/\/ If it isn't, we also have to ban it to prevent it from reappearing. The Folder::banFolder\n \/\/ method already handles the prior deletion\n bool res;\n if ( folder->isRootFolder() == false )\n res = Folder::ban( m_ml, entryPoint );\n else\n res = m_ml->deleteFolder( *folder );\n if ( res == false )\n {\n m_ml->getCb()->onEntryPointRemoved( ep, false );\n return;\n }\n m_ml->getCb()->onEntryPointRemoved( ep, true );\n}\n\nvoid DiscovererWorker::runBan( const std::string& entryPoint )\n{\n auto res = Folder::ban( m_ml, entryPoint );\n m_ml->getCb()->onEntryPointBanned( entryPoint, res );\n}\n\nvoid DiscovererWorker::runUnban( const std::string& entryPoint )\n{\n auto folder = Folder::bannedFolder( m_ml, entryPoint );\n if ( folder == nullptr )\n {\n LOG_WARN( \"Can't unban \", entryPoint, \" as it wasn't banned\" );\n m_ml->getCb()->onEntryPointUnbanned( entryPoint, false );\n return;\n }\n auto res = m_ml->deleteFolder( *folder );\n m_ml->getCb()->onEntryPointUnbanned( entryPoint, res );\n\n auto parentPath = utils::file::parentDirectory( entryPoint );\n \/\/ If the parent folder was never added to the media library, the discoverer will reject it.\n \/\/ We could check it from here, but that would mean fetching the folder twice, which would be a waste.\n runReload( parentPath );\n}\n\nvoid DiscovererWorker::runReloadDevice( int64_t deviceId )\n{\n auto device = Device::fetch( m_ml, deviceId );\n if ( device == nullptr )\n {\n LOG_ERROR( \"Can't fetch device \", deviceId, \" to reload it\" );\n return;\n }\n auto entryPoints = Folder::entryPoints( m_ml, false, device->id() );\n if ( entryPoints == nullptr )\n return;\n for ( const auto& ep : entryPoints->all() )\n {\n try\n {\n auto mrl = ep->mrl();\n LOG_INFO( \"Reloading entrypoint on mounted device: \", mrl );\n runReload( mrl );\n }\n catch ( const fs::errors::DeviceRemoved& )\n {\n LOG_INFO( \"Can't reload device \", device->uuid(), \" as it was removed\" );\n }\n }\n}\n\nbool DiscovererWorker::isInterrupted() const\n{\n return m_run.load() == false;\n}\n\nvoid DiscovererWorker::runDiscover( const std::string& entryPoint )\n{\n m_ml->getCb()->onDiscoveryStarted( entryPoint );\n auto discovered = false;\n LOG_INFO( \"Running discover on: \", entryPoint );\n for ( auto& d : m_discoverers )\n {\n \/\/ Assume only one discoverer can handle an entrypoint.\n try\n {\n auto chrono = std::chrono::steady_clock::now();\n if ( d->discover( entryPoint, *this ) == true )\n {\n auto duration = std::chrono::steady_clock::now() - chrono;\n LOG_VERBOSE( \"Discovered \", entryPoint, \" in \",\n std::chrono::duration_cast( duration ).count(), \"µs\" );\n discovered = true;\n break;\n }\n }\n catch(std::exception& ex)\n {\n LOG_ERROR( \"Fatal error while discovering \", entryPoint, \": \", ex.what() );\n }\n\n if ( m_run == false )\n break;\n }\n if ( discovered == false )\n LOG_WARN( \"No IDiscoverer found to discover \", entryPoint );\n m_ml->getCb()->onDiscoveryCompleted( entryPoint, discovered );\n}\n\n}\nDiscovererWorker: Clarify log\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN\n *\n * Authors: Hugo Beauzée-Luyssen \n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#if HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"DiscovererWorker.h\"\n\n#include \"logging\/Logger.h\"\n#include \"Folder.h\"\n#include \"Media.h\"\n#include \"MediaLibrary.h\"\n#include \"Device.h\"\n#include \"utils\/Filename.h\"\n#include \"medialibrary\/filesystem\/Errors.h\"\n#include \n\nnamespace medialibrary\n{\n\nDiscovererWorker::DiscovererWorker(MediaLibrary* ml )\n : m_run( false )\n , m_ml( ml )\n{\n}\n\nDiscovererWorker::~DiscovererWorker()\n{\n stop();\n}\n\nvoid DiscovererWorker::addDiscoverer( std::unique_ptr discoverer )\n{\n m_discoverers.push_back( std::move( discoverer ) );\n}\n\nvoid DiscovererWorker::stop()\n{\n bool running = true;\n if ( m_run.compare_exchange_strong( running, false ) )\n {\n {\n std::unique_lock lock( m_mutex );\n while ( m_tasks.empty() == false )\n m_tasks.pop();\n }\n m_cond.notify_all();\n m_thread.join();\n }\n}\n\nbool DiscovererWorker::discover( const std::string& entryPoint )\n{\n if ( entryPoint.length() == 0 )\n return false;\n LOG_INFO( \"Adding \", entryPoint, \" to the folder discovery list\" );\n enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Discover );\n return true;\n}\n\nvoid DiscovererWorker::remove( const std::string& entryPoint )\n{\n enqueue( entryPoint, Task::Type::Remove );\n}\n\nvoid DiscovererWorker::reload()\n{\n enqueue( \"\", Task::Type::Reload );\n}\n\nvoid DiscovererWorker::reload( const std::string& entryPoint )\n{\n enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Reload );\n}\n\nvoid DiscovererWorker::ban( const std::string& entryPoint )\n{\n enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Ban );\n}\n\nvoid DiscovererWorker::unban( const std::string& entryPoint )\n{\n enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Unban );\n}\n\nvoid DiscovererWorker::reloadDevice(int64_t deviceId)\n{\n enqueue( deviceId, Task::Type::ReloadDevice );\n}\n\nvoid DiscovererWorker::enqueue( const std::string& entryPoint, Task::Type type )\n{\n std::unique_lock lock( m_mutex );\n\n if ( entryPoint.empty() == false )\n {\n LOG_INFO( \"Queuing entrypoint \", entryPoint, \" of type \",\n static_cast::type>( type ) );\n }\n else\n {\n assert( type == Task::Type::Reload );\n LOG_INFO( \"Queuing global reload request\" );\n }\n\n m_tasks.emplace( entryPoint, type );\n notify();\n}\n\nvoid DiscovererWorker::enqueue( int64_t entityId, Task::Type type )\n{\n std::unique_lock lock( m_mutex );\n\n LOG_INFO( \"Queuing entity \", entityId, \" of type \",\n static_cast::type>( type ) );\n m_tasks.emplace( entityId, type );\n notify();\n}\n\nvoid DiscovererWorker::notify()\n{\n if ( m_thread.get_id() == compat::Thread::id{} )\n {\n m_run = true;\n m_thread = compat::Thread( &DiscovererWorker::run, this );\n }\n \/\/ Since we just added an element, let's not check for size == 0 :)\n else if ( m_tasks.size() == 1 )\n m_cond.notify_all();\n}\n\nvoid DiscovererWorker::run() ML_UNHANDLED_EXCEPTION_INIT\n{\n LOG_INFO( \"Entering DiscovererWorker thread\" );\n m_ml->onDiscovererIdleChanged( false );\n while ( m_run == true )\n {\n Task task;\n {\n std::unique_lock lock( m_mutex );\n if ( m_tasks.size() == 0 )\n {\n m_ml->onDiscovererIdleChanged( true );\n m_cond.wait( lock, [this]() { return m_tasks.size() > 0 || m_run == false; } );\n if ( m_run == false )\n break;\n m_ml->onDiscovererIdleChanged( false );\n }\n task = m_tasks.front();\n m_tasks.pop();\n }\n switch ( task.type )\n {\n case Task::Type::Discover:\n runDiscover( task.entryPoint );\n break;\n case Task::Type::Reload:\n runReload( task.entryPoint );\n break;\n case Task::Type::Remove:\n runRemove( task.entryPoint );\n break;\n case Task::Type::Ban:\n runBan( task.entryPoint );\n break;\n case Task::Type::Unban:\n runUnban( task.entryPoint );\n break;\n case Task::Type::ReloadDevice:\n runReloadDevice( task.entityId );\n break;\n default:\n assert(false);\n }\n }\n LOG_INFO( \"Exiting DiscovererWorker thread\" );\n m_ml->onDiscovererIdleChanged( true );\n}\nML_UNHANDLED_EXCEPTION_BODY( \"DiscovererWorker\" )\n\nvoid DiscovererWorker::runReload( const std::string& entryPoint )\n{\n for ( auto& d : m_discoverers )\n {\n try\n {\n if ( entryPoint.empty() == true )\n {\n \/\/ Let the discoverer invoke the callbacks for all its known folders\n d->reload( *this );\n }\n else\n {\n m_ml->getCb()->onReloadStarted( entryPoint );\n LOG_INFO( \"Reloading folder \", entryPoint );\n auto res = d->reload( entryPoint, *this );\n m_ml->getCb()->onReloadCompleted( entryPoint, res );\n }\n }\n catch(std::exception& ex)\n {\n LOG_ERROR( \"Fatal error while reloading: \", ex.what() );\n }\n if ( m_run == false )\n break;\n }\n}\n\nvoid DiscovererWorker::runRemove( const std::string& ep )\n{\n auto entryPoint = utils::file::toFolderPath( ep );\n auto folder = Folder::fromMrl( m_ml, entryPoint );\n if ( folder == nullptr )\n {\n LOG_WARN( \"Can't remove unknown entrypoint: \", entryPoint );\n m_ml->getCb()->onEntryPointRemoved( ep, false );\n return;\n }\n \/\/ The easy case is that this folder was directly discovered. In which case, we just\n \/\/ have to delete it and it won't be discovered again.\n \/\/ If it isn't, we also have to ban it to prevent it from reappearing. The Folder::banFolder\n \/\/ method already handles the prior deletion\n bool res;\n if ( folder->isRootFolder() == false )\n res = Folder::ban( m_ml, entryPoint );\n else\n res = m_ml->deleteFolder( *folder );\n if ( res == false )\n {\n m_ml->getCb()->onEntryPointRemoved( ep, false );\n return;\n }\n m_ml->getCb()->onEntryPointRemoved( ep, true );\n}\n\nvoid DiscovererWorker::runBan( const std::string& entryPoint )\n{\n auto res = Folder::ban( m_ml, entryPoint );\n m_ml->getCb()->onEntryPointBanned( entryPoint, res );\n}\n\nvoid DiscovererWorker::runUnban( const std::string& entryPoint )\n{\n auto folder = Folder::bannedFolder( m_ml, entryPoint );\n if ( folder == nullptr )\n {\n LOG_WARN( \"Can't unban \", entryPoint, \" as it wasn't banned\" );\n m_ml->getCb()->onEntryPointUnbanned( entryPoint, false );\n return;\n }\n auto res = m_ml->deleteFolder( *folder );\n m_ml->getCb()->onEntryPointUnbanned( entryPoint, res );\n\n auto parentPath = utils::file::parentDirectory( entryPoint );\n \/\/ If the parent folder was never added to the media library, the discoverer will reject it.\n \/\/ We could check it from here, but that would mean fetching the folder twice, which would be a waste.\n runReload( parentPath );\n}\n\nvoid DiscovererWorker::runReloadDevice( int64_t deviceId )\n{\n auto device = Device::fetch( m_ml, deviceId );\n if ( device == nullptr )\n {\n LOG_ERROR( \"Can't fetch device \", deviceId, \" to reload it\" );\n return;\n }\n auto entryPoints = Folder::entryPoints( m_ml, false, device->id() );\n if ( entryPoints == nullptr )\n return;\n for ( const auto& ep : entryPoints->all() )\n {\n try\n {\n auto mrl = ep->mrl();\n LOG_INFO( \"Reloading entrypoint on mounted device: \", mrl );\n runReload( mrl );\n }\n catch ( const fs::errors::DeviceRemoved& )\n {\n LOG_INFO( \"Can't reload device \", device->uuid(), \" as it was removed\" );\n }\n }\n}\n\nbool DiscovererWorker::isInterrupted() const\n{\n return m_run.load() == false;\n}\n\nvoid DiscovererWorker::runDiscover( const std::string& entryPoint )\n{\n m_ml->getCb()->onDiscoveryStarted( entryPoint );\n auto discovered = false;\n LOG_INFO( \"Running discover on: \", entryPoint );\n for ( auto& d : m_discoverers )\n {\n \/\/ Assume only one discoverer can handle an entrypoint.\n try\n {\n auto chrono = std::chrono::steady_clock::now();\n if ( d->discover( entryPoint, *this ) == true )\n {\n auto duration = std::chrono::steady_clock::now() - chrono;\n LOG_VERBOSE( \"Discovered \", entryPoint, \" in \",\n std::chrono::duration_cast( duration ).count(), \"µs\" );\n discovered = true;\n break;\n }\n }\n catch(std::exception& ex)\n {\n LOG_ERROR( \"Fatal error while discovering \", entryPoint, \": \", ex.what() );\n }\n\n if ( m_run == false )\n break;\n }\n if ( discovered == false )\n LOG_WARN( \"No IDiscoverer found to discover \", entryPoint );\n m_ml->getCb()->onDiscoveryCompleted( entryPoint, discovered );\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n User Server code for CMPT 276 Group Assignment, Spring 2016.\n\n This server manages a user’s social networking session.\n\n This server supports sign on\/off, add friend, unfriend, update status,\n get user's friend list.\n\n This server handles disallowed method malformed request.\n\n As defined in ServerUrls.h, the URI for this server is\n http:\/\/localhost:34572.\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \"..\/include\/ClientUtils.h\"\n#include \"..\/include\/ServerUrls.h\"\n#include \"..\/include\/ServerUtils.h\"\n#include \"..\/include\/TableCache.h\"\n\n#include \"..\/include\/azure_keys.h\"\n\n\nusing azure::storage::cloud_storage_account;\nusing azure::storage::storage_credentials;\nusing azure::storage::storage_exception;\nusing azure::storage::cloud_table;\nusing azure::storage::cloud_table_client;\nusing azure::storage::edm_type;\nusing azure::storage::entity_property;\nusing azure::storage::table_entity;\nusing azure::storage::table_operation;\nusing azure::storage::table_query;\nusing azure::storage::table_query_iterator;\nusing azure::storage::table_result;\n\nusing pplx::extensibility::critical_section_t;\nusing pplx::extensibility::scoped_critical_section_t;\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::getline;\nusing std::make_pair;\nusing std::pair;\nusing std::string;\nusing std::unordered_map;\nusing std::vector;\nusing std::get;\n\nusing web::http::client::http_client;\nusing web::http::http_headers;\nusing web::http::http_request;\nusing web::http::http_response;\nusing web::http::method;\nusing web::http::methods;\nusing web::http::status_code;\nusing web::http::status_codes;\nusing web::http::uri;\n\nusing web::json::value;\n\nusing web::http::experimental::listener::http_listener;\n\nusing prop_vals_t = vector>;\n\nconst string get_update_data_op {\"GetUpdateData\"};\n\nconst string read_entity_auth_op {\"ReadEntityAuth\"};\nconst string update_entity_auth_op {\"UpdateEntityAuth\"};\n\nconst string auth_table_partition {\"Userid\"};\nconst string data_table {\"DataTable\"};\n\nconst string sign_on {\"SignOn\"}; \/\/POST\nconst string sign_off {\"SignOff\"}; \/\/POST\n\nconst string add_friend {\"AddFriend\"}; \/\/ PUT\nconst string unfriend {\"UnFriend\"}; \/\/PUT\nconst string update_status {\"UpdateStatus\"}; \/\/PUT\n\nconst string get_friend_list {\"ReadFriendList\"}; \/\/GET\n\n\/\/ Cache of active sessions\nstd::unordered_map< string, std::tuple > sessions;\n\n\/*\n Return true if an HTTP request has a JSON body\n\n This routine can be called multiple times on the same message.\n *\/\nbool has_json_body (http_request message) {\n return message.headers()[\"Content-type\"] == \"application\/json\";\n}\n\n\/*\n Given an HTTP message with a JSON body, return the JSON\n body as an unordered map of strings to strings.\n get_json_body and get_json_bourne are valid and identical function calls.\n\n If the message has no JSON body, return an empty map.\n\n THIS ROUTINE CAN ONLY BE CALLED ONCE FOR A GIVEN MESSAGE\n (see http:\/\/microsoft.github.io\/cpprestsdk\/classweb_1_1http_1_1http__request.html#ae6c3d7532fe943de75dcc0445456cbc7\n for source of this limit).\n\n Note that all types of JSON values are returned as strings.\n Use C++ conversion utilities to convert to numbers or dates\n as necessary.\n *\/\nunordered_map get_json_body(http_request message) {\n unordered_map results {};\n const http_headers& headers {message.headers()};\n auto content_type (headers.find(\"Content-Type\"));\n if (content_type == headers.end() ||\n content_type->second != \"application\/json\")\n return results;\n\n value json{};\n message.extract_json(true)\n .then([&json](value v) -> bool\n {\n json = v;\n return true;\n })\n .wait();\n\n if (json.is_object()) {\n for (const auto& v : json.as_object()) {\n if (v.second.is_string()) {\n results[v.first] = v.second.as_string();\n }\n else {\n results[v.first] = v.second.serialize();\n }\n }\n }\n return results;\n}\n\nunordered_map get_json_bourne(http_request message) {\n return get_json_body(message);\n}\n\nvoid handle_post (http_request message){\n string path {uri::decode(message.relative_uri().path())};\n cout << endl << \"**** POST \" << path << endl;\n auto paths = uri::split_path(path);\n\n \/\/ Operation name and user ID\n if(paths.size() < 2) {\n message.reply(status_codes::BadRequest);\n return;\n }\n else if(paths[0] != sign_on && paths[0] != sign_off) {\n message.reply(status_codes::BadRequest);\n }\n\n const string operation = paths[0];\n const string userid = paths[1];\n\n if(operation == sign_on) {\n if(!has_json_body(message)) {\n message.reply(status_codes::BadRequest);\n return;\n }\n\n unordered_map json_body {get_json_bourne(message)};\n if(json_body.size() != 1) {\n message.reply(status_codes::BadRequest);\n return;\n }\n\n unordered_map::const_iterator json_body_password_iterator {json_body.find(\"Password\")};\n \/\/ No 'Password' property\n if(json_body_password_iterator == json_body.end()) {\n message.reply(status_codes::BadRequest);\n return;\n }\n\n vector> json_pw;\n json_pw.push_back(make_pair(\n json_body_password_iterator->first,\n value::string(json_body_password_iterator->second)\n ));\n\n pair result;\n result = do_request(\n methods::GET,\n string(server_urls::auth_server) + \"\/\" +\n get_update_data_op + \"\/\" +\n userid,\n value::object(json_pw)\n );\n if(result.first != status_codes::OK) {\n message.reply(result.first);\n return;\n }\n else if(result.second.size() != 3) {\n message.reply(status_codes::InternalError);\n return;\n }\n\n const string token = get_json_object_prop(\n result.second,\n \"token\"\n );\n const string data_partition = get_json_object_prop(\n result.second,\n \"DataPartition\"\n );\n const string data_row = get_json_object_prop(\n result.second,\n \"DataRow\"\n );\n if(token.empty() ||\n data_partition.empty() ||\n data_row.empty() ) {\n message.reply(status_codes::InternalError);\n return;\n }\n\n std::tuple tuple_insert(\n token,\n data_partition,\n data_row);\n std::pair> pair_insert(\n userid,\n tuple_insert\n );\n sessions.insert(pair_insert);\n\n message.reply(status_codes::OK);\n return;\n }\n\n else if(operation == sign_off) {\n auto session = sessions.find(userid);\n if(session == sessions.end()) {\n message.reply(status_codes::NotFound);\n return;\n }\n\n sessions.erase(session);\n message.reply(status_codes::OK);\n return;\n }\n\n else {\n message.reply(status_codes::InternalError);\n return;\n }\n}\n\nvoid handle_put (http_request message) {\n string path {uri::decode(message.relative_uri().path())};\n cout << endl << \"**** POST \" << path << endl;\n auto paths = uri::split_path(path);\n\n\n\n pair result;\n string user_id {paths[1]};\n string user_token {get<0>(sessions[user_id])};\n string user_partition {get<1>(sessions[user_id])};\n string user_row {get<2>(sessions[user_id])};\n if(true\/*basic criteria*\/){}\n else if (paths[0] == add_friend) {\n \/\/ Get current friends list\n result = do_request(\n methods::GET,\n string(server_urls::basic_server) + \"\/\" +\n read_entity_auth_op + \"\/\" +\n data_table + \"\/\" +\n user_token + \"\/\" +\n user_partition + \"\/\" +\n user_row\n );\n \/\/Check status code\n \/\/Parse JSON body\n unordered_map json_body = unpack_json_object(result.second);\n friends_list_t user_friends = parse_friends_list(json_body[\"Friends\"]);\n \/\/ Add new friend to list\n user_friends.push_back(make_pair(paths[2],paths[3]));\n string user_friends_string = friends_list_to_string(user_friends);\n result.second = build_json_value(\"Friends\", user_friends_string);\n \/\/ Put new friends list\n do_request(\n methods::PUT,\n string(server_urls::basic_server) + \"\/\" +\n update_entity_auth_op + \"\/\" +\n string(paths[2]) + \"\/\" +\n string(paths[3]),\n result.second\n );\n message.reply(status::codes::OK);\n return;\n }\n else if (paths[0] == unfriend) {}\n else if (paths[0] == update_status) {}\n else {\n \/\/ malformed request\n vector vec;\n message.reply(status_codes::BadRequest, value::array(vec));\n return;\n }\n}\n\nvoid handle_get (http_request message) {\n string path {uri::decode(message.relative_uri().path())};\n cout << endl << \"**** POST \" << path << endl;\n auto paths = uri::split_path(path);\n\n if(true\/*basic criteria*\/){}\n else if (paths[0] == get_friend_list) {}\n else {\n \/\/ malformed request\n vector vec;\n message.reply(status_codes::BadRequest, value::array(vec));\n return;\n }\n}\n\n\nint main (int argc, char const * argv[]) {\n cout << \"Opening listener\" << endl;\n http_listener listener {server_urls::user_server};\n listener.support(methods::GET, &handle_get); \/\/ Get user's friend list\n listener.support(methods::POST, &handle_post); \/\/ SignOn, SignOff\n listener.support(methods::PUT, &handle_put); \/\/ Add friend, Unfriend, Update Status\n \/*TO DO: Disallowed method*\/\n listener.open().wait(); \/\/ Wait for listener to complete starting\n\n cout << \"Enter carriage return to stop server.\" << endl;\n string line;\n getline(std::cin, line);\n\n \/\/ Shut it down\n listener.close().wait();\n cout << \"Closed\" << endl;\n}\nupdate documentation of put\/*\n User Server code for CMPT 276 Group Assignment, Spring 2016.\n\n This server manages a user’s social networking session.\n\n This server supports sign on\/off, add friend, unfriend, update status,\n get user's friend list.\n\n This server handles disallowed method malformed request.\n\n As defined in ServerUrls.h, the URI for this server is\n http:\/\/localhost:34572.\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \"..\/include\/ClientUtils.h\"\n#include \"..\/include\/ServerUrls.h\"\n#include \"..\/include\/ServerUtils.h\"\n#include \"..\/include\/TableCache.h\"\n\n#include \"..\/include\/azure_keys.h\"\n\n\nusing azure::storage::cloud_storage_account;\nusing azure::storage::storage_credentials;\nusing azure::storage::storage_exception;\nusing azure::storage::cloud_table;\nusing azure::storage::cloud_table_client;\nusing azure::storage::edm_type;\nusing azure::storage::entity_property;\nusing azure::storage::table_entity;\nusing azure::storage::table_operation;\nusing azure::storage::table_query;\nusing azure::storage::table_query_iterator;\nusing azure::storage::table_result;\n\nusing pplx::extensibility::critical_section_t;\nusing pplx::extensibility::scoped_critical_section_t;\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::getline;\nusing std::make_pair;\nusing std::pair;\nusing std::string;\nusing std::unordered_map;\nusing std::vector;\nusing std::get;\n\nusing web::http::client::http_client;\nusing web::http::http_headers;\nusing web::http::http_request;\nusing web::http::http_response;\nusing web::http::method;\nusing web::http::methods;\nusing web::http::status_code;\nusing web::http::status_codes;\nusing web::http::uri;\n\nusing web::json::value;\n\nusing web::http::experimental::listener::http_listener;\n\nusing prop_vals_t = vector>;\n\nconst string get_update_data_op {\"GetUpdateData\"};\n\nconst string read_entity_auth_op {\"ReadEntityAuth\"};\nconst string update_entity_auth_op {\"UpdateEntityAuth\"};\n\nconst string auth_table_partition {\"Userid\"};\nconst string data_table {\"DataTable\"};\n\nconst string sign_on {\"SignOn\"}; \/\/POST\nconst string sign_off {\"SignOff\"}; \/\/POST\n\nconst string add_friend {\"AddFriend\"}; \/\/ PUT\nconst string unfriend {\"UnFriend\"}; \/\/PUT\nconst string update_status {\"UpdateStatus\"}; \/\/PUT\n\nconst string get_friend_list {\"ReadFriendList\"}; \/\/GET\n\n\/\/ Cache of active sessions\nstd::unordered_map< string, std::tuple > sessions;\n\n\/*\n Return true if an HTTP request has a JSON body\n\n This routine can be called multiple times on the same message.\n *\/\nbool has_json_body (http_request message) {\n return message.headers()[\"Content-type\"] == \"application\/json\";\n}\n\n\/*\n Given an HTTP message with a JSON body, return the JSON\n body as an unordered map of strings to strings.\n get_json_body and get_json_bourne are valid and identical function calls.\n\n If the message has no JSON body, return an empty map.\n\n THIS ROUTINE CAN ONLY BE CALLED ONCE FOR A GIVEN MESSAGE\n (see http:\/\/microsoft.github.io\/cpprestsdk\/classweb_1_1http_1_1http__request.html#ae6c3d7532fe943de75dcc0445456cbc7\n for source of this limit).\n\n Note that all types of JSON values are returned as strings.\n Use C++ conversion utilities to convert to numbers or dates\n as necessary.\n *\/\nunordered_map get_json_body(http_request message) {\n unordered_map results {};\n const http_headers& headers {message.headers()};\n auto content_type (headers.find(\"Content-Type\"));\n if (content_type == headers.end() ||\n content_type->second != \"application\/json\")\n return results;\n\n value json{};\n message.extract_json(true)\n .then([&json](value v) -> bool\n {\n json = v;\n return true;\n })\n .wait();\n\n if (json.is_object()) {\n for (const auto& v : json.as_object()) {\n if (v.second.is_string()) {\n results[v.first] = v.second.as_string();\n }\n else {\n results[v.first] = v.second.serialize();\n }\n }\n }\n return results;\n}\n\nunordered_map get_json_bourne(http_request message) {\n return get_json_body(message);\n}\n\nvoid handle_post (http_request message){\n string path {uri::decode(message.relative_uri().path())};\n cout << endl << \"**** POST \" << path << endl;\n auto paths = uri::split_path(path);\n\n \/\/ Operation name and user ID\n if(paths.size() < 2) {\n message.reply(status_codes::BadRequest);\n return;\n }\n else if(paths[0] != sign_on && paths[0] != sign_off) {\n message.reply(status_codes::BadRequest);\n }\n\n const string operation = paths[0];\n const string userid = paths[1];\n\n if(operation == sign_on) {\n if(!has_json_body(message)) {\n message.reply(status_codes::BadRequest);\n return;\n }\n\n unordered_map json_body {get_json_bourne(message)};\n if(json_body.size() != 1) {\n message.reply(status_codes::BadRequest);\n return;\n }\n\n unordered_map::const_iterator json_body_password_iterator {json_body.find(\"Password\")};\n \/\/ No 'Password' property\n if(json_body_password_iterator == json_body.end()) {\n message.reply(status_codes::BadRequest);\n return;\n }\n\n vector> json_pw;\n json_pw.push_back(make_pair(\n json_body_password_iterator->first,\n value::string(json_body_password_iterator->second)\n ));\n\n pair result;\n result = do_request(\n methods::GET,\n string(server_urls::auth_server) + \"\/\" +\n get_update_data_op + \"\/\" +\n userid,\n value::object(json_pw)\n );\n if(result.first != status_codes::OK) {\n message.reply(result.first);\n return;\n }\n else if(result.second.size() != 3) {\n message.reply(status_codes::InternalError);\n return;\n }\n\n const string token = get_json_object_prop(\n result.second,\n \"token\"\n );\n const string data_partition = get_json_object_prop(\n result.second,\n \"DataPartition\"\n );\n const string data_row = get_json_object_prop(\n result.second,\n \"DataRow\"\n );\n if(token.empty() ||\n data_partition.empty() ||\n data_row.empty() ) {\n message.reply(status_codes::InternalError);\n return;\n }\n\n std::tuple tuple_insert(\n token,\n data_partition,\n data_row);\n std::pair> pair_insert(\n userid,\n tuple_insert\n );\n sessions.insert(pair_insert);\n\n message.reply(status_codes::OK);\n return;\n }\n\n else if(operation == sign_off) {\n auto session = sessions.find(userid);\n if(session == sessions.end()) {\n message.reply(status_codes::NotFound);\n return;\n }\n\n sessions.erase(session);\n message.reply(status_codes::OK);\n return;\n }\n\n else {\n message.reply(status_codes::InternalError);\n return;\n }\n}\n\nvoid handle_put (http_request message) {\n string path {uri::decode(message.relative_uri().path())};\n cout << endl << \"**** POST \" << path << endl;\n auto paths = uri::split_path(path);\n\n\n\n pair result;\n string user_id {paths[1]};\n string user_token {get<0>(sessions[user_id])};\n string user_partition {get<1>(sessions[user_id])};\n string user_row {get<2>(sessions[user_id])};\n if(true\/*basic criteria*\/){}\n else if (paths[0] == add_friend) {\n \/\/ TODO: Check validity of the request\n \/\/ Get current friends list\n result = do_request(\n methods::GET,\n string(server_urls::basic_server) + \"\/\" +\n read_entity_auth_op + \"\/\" +\n data_table + \"\/\" +\n user_token + \"\/\" +\n user_partition + \"\/\" +\n user_row\n );\n \/\/ TODO: Check status code\n \/\/ Parse JSON body\n unordered_map json_body = unpack_json_object(result.second);\n friends_list_t user_friends = parse_friends_list(json_body[\"Friends\"]);\n \/\/ Add new friend to list\n user_friends.push_back(make_pair(paths[2],paths[3]));\n \/\/ Rebuild json body\n string user_friends_string = friends_list_to_string(user_friends);\n result.second = build_json_value(\"Friends\", user_friends_string);\n \/\/ Put new friends list\n do_request(\n methods::PUT,\n string(server_urls::basic_server) + \"\/\" +\n update_entity_auth_op + \"\/\" +\n string(paths[2]) + \"\/\" +\n string(paths[3]),\n result.second\n );\n message.reply(status::codes::OK);\n return;\n }\n else if (paths[0] == unfriend) {}\n else if (paths[0] == update_status) {}\n else {\n \/\/ malformed request\n vector vec;\n message.reply(status_codes::BadRequest, value::array(vec));\n return;\n }\n}\n\nvoid handle_get (http_request message) {\n string path {uri::decode(message.relative_uri().path())};\n cout << endl << \"**** POST \" << path << endl;\n auto paths = uri::split_path(path);\n\n if(true\/*basic criteria*\/){}\n else if (paths[0] == get_friend_list) {}\n else {\n \/\/ malformed request\n vector vec;\n message.reply(status_codes::BadRequest, value::array(vec));\n return;\n }\n}\n\n\nint main (int argc, char const * argv[]) {\n cout << \"Opening listener\" << endl;\n http_listener listener {server_urls::user_server};\n listener.support(methods::GET, &handle_get); \/\/ Get user's friend list\n listener.support(methods::POST, &handle_post); \/\/ SignOn, SignOff\n listener.support(methods::PUT, &handle_put); \/\/ Add friend, Unfriend, Update Status\n \/*TO DO: Disallowed method*\/\n listener.open().wait(); \/\/ Wait for listener to complete starting\n\n cout << \"Enter carriage return to stop server.\" << endl;\n string line;\n getline(std::cin, line);\n\n \/\/ Shut it down\n listener.close().wait();\n cout << \"Closed\" << endl;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017, Baidu.com, Inc. All Rights Reserved\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n#include \"sdk\/bfs_c.h\"\n#include \"sdk\/bfs.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n\nDECLARE_string(flagfile);\nDECLARE_string(nameserver_nodes);\n\nextern \"C\"{\n\nstruct bfs_fs_t {\n baidu::bfs::FS* bfs_fs;\n};\n\nstruct bfs_file_t {\n baidu::bfs::File* bfs_file;\n};\n\nbfs_fs_t* bfs_open_file_system(const char* flag_file) {\n std::string flag = \"--flagfile=\";\n if (flag_file) {\n flag += flag_file;\n } else {\n flag += \".\/bfs.flag\";\n }\n int argc = 1;\n char* file_path = new char[flag.size() + 1];\n strcpy(file_path, flag.c_str());\n char** argv = &file_path;\n ::google::ParseCommandLineFlags(&argc, &argv, false);\n delete[] file_path;\n\n bfs_fs_t* fs = new bfs_fs_t;\n std::string ns_address = FLAGS_nameserver_nodes;\n bool ret = baidu::bfs::FS::OpenFileSystem(ns_address.c_str(),\n &(fs->bfs_fs), baidu::bfs::FSOptions());\n if (!ret) {\n delete fs;\n return NULL;\n }\n return fs;\n}\n\nbfs_file_t* bfs_open_file(const bfs_fs_t* fs, const char* path, int flag) {\n if (flag != O_RDONLY && flag != O_WRONLY) {\n return NULL;\n }\n bfs_file_t* file = new bfs_file_t;\n int32_t ret = 0;\n if (flag == O_RDONLY) {\n ret = fs->bfs_fs->OpenFile(path, flag,\n &(file->bfs_file), baidu::bfs::ReadOptions());\n\n } else {\n ret = fs->bfs_fs->OpenFile(path, flag,\n &(file->bfs_file), baidu::bfs::WriteOptions());\n }\n if (ret != 0) {\n delete file->bfs_file;\n delete file;\n file = NULL;\n }\n return file;\n}\n\nint bfs_close_file(bfs_file_t* file) {\n int32_t ret = file->bfs_file->Close();\n delete file->bfs_file;\n file->bfs_file = NULL;\n delete file;\n return ret;\n}\n\nint bfs_write_file(bfs_file_t* file, const char* buf, int32_t len) {\n return file->bfs_file->Write(buf, len);\n}\n\nint bfs_read_file(bfs_file_t* file, char* buf, int32_t len) {\n return file->bfs_file->Read(buf, len);\n}\n\nint64_t bfs_seek(bfs_file_t* file, int64_t offset, int32_t whence) {\n return file->bfs_file->Seek(offset, whence);\n}\n\nint bfs_create_directory(bfs_fs_t* fs, const char* path) {\n return fs->bfs_fs->CreateDirectory(path);\n}\n\nint bfs_list_directory(bfs_fs_t* fs, const char* path) {\n char file_types[10] ={'-', 'd', 'l'};\n baidu::bfs::BfsFileInfo* files = NULL;\n int num;\n int32_t ret = fs->bfs_fs->ListDirectory(path, &files, &num);\n if (ret != 0) {\n return ret;\n }\n printf(\"Found %d items\\n\", num);\n for (int i = 0; i < num; i++) {\n char statbuf[16] = \"-rwxrwxrwx\";\n int32_t file_type = files[i].mode >> 9;\n int32_t file_perm = files[i].mode & 0777;\n statbuf[0] = file_types[file_type];\n\n for (int j = 1; j < 10; j++) {\n if ((file_perm & (1<<(9-j))) == 0) {\n statbuf[j] = '-';\n }\n }\n char timestr[64];\n struct tm stm;\n time_t ctime = files[i].ctime;\n localtime_r(&ctime, &stm);\n snprintf(timestr, sizeof(timestr), \"%4d-%02d-%02d %2d:%02d\",\n stm.tm_year+1900, stm.tm_mon+1, stm.tm_mday, stm.tm_hour, stm.tm_min);\n std::string prefix = path;\n if (files[i].name[0] == '\\0') {\n int32_t pos = prefix.size() - 1;\n while (pos >= 0 && prefix[pos] == '\/') {\n pos--;\n }\n prefix.resize(pos + 1);\n }\n printf(\"%s %-9s %s %s%s\\n\",\n statbuf, baidu::common::HumanReadableString(files[i].size).c_str(),\n timestr, prefix.c_str(), files[i].name);\n }\n delete[] files;\n return 0;\n}\n\nint bfs_delete_file(bfs_fs_t* fs, const char* path) {\n return fs->bfs_fs->DeleteFile(path);\n}\n\nint bfs_rename(bfs_fs_t* fs, const char* oldpath, const char* newpath) {\n return fs->bfs_fs->Rename(oldpath, newpath);\n}\n\nint bfs_touchz(bfs_fs_t* fs, const char* path) {\n baidu::bfs::File* file;\n int32_t ret = fs->bfs_fs->OpenFile(path, O_WRONLY, 0644,\n &file, baidu::bfs::WriteOptions());\n delete file;\n return ret;\n}\n\nint bfs_symlink(bfs_fs_t* fs, const char* src, const char* dst) {\n return fs->bfs_fs->Symlink(src, dst);\n}\n\nint bfs_cat(bfs_fs_t* fs, const char* path) {\n int64_t bytes = 0;\n baidu::bfs::File* file;\n int32_t ret = fs->bfs_fs->OpenFile(path, O_RDONLY, &file,\n baidu::bfs::ReadOptions());\n if (ret != 0) {\n return ret;\n }\n char buf[10240];\n int32_t len = 0;\n while (1) {\n len = file->Read(buf, sizeof(buf));\n if (len <= 0) {\n break;\n }\n bytes += len;\n write(1, buf, len);\n }\n delete file;\n return len;\n}\n\nint bfs_get(bfs_fs_t* fs, const char* bfs, const char* local) {\n std::string source = bfs;\n std::string target = local;\n std::vector src_elements;\n bool src_isdir = false;\n if (!baidu::common::util::SplitPath(source, &src_elements, &src_isdir)\n || src_isdir || src_elements.empty()) {\n return 1;\n }\n std::string src_file_name = src_elements[src_elements.size() - 1];\n if (target.empty() || target[target.size() - 1] == '\/') {\n target += src_file_name;\n }\n baidu::common::timer::AutoTimer at(0, \"BfsGet\", bfs);\n baidu::bfs::File* file;\n if (fs->bfs_fs->OpenFile(bfs, O_RDONLY, &file,\n baidu::bfs::ReadOptions()) != 0) {\n return 2;\n }\n FILE* fp = fopen(target.c_str(), \"wb\");\n if (fp == NULL) {\n delete file;\n return 3;\n }\n\n char buf[10240];\n int64_t bytes = 0;\n int32_t len = 0;\n while (1) {\n len = file->Read(buf, sizeof(buf));\n if (len <= 0) {\n if (len < 0) {\n fclose(fp);\n return 4;\n }\n break;\n }\n bytes += len;\n fwrite(buf, len, 1, fp);\n }\n printf(\"Read %ld bytes from %s\\n\", bytes, source.c_str());\n delete file;\n fclose(fp);\n return len;\n}\n\nint bfs_put(bfs_fs_t* fs, const char* local, const char* bfs) {\n std::string source = local;\n std::string target = bfs;\n if (source.empty() || source[source.size() - 1] == '\/' || target.empty()) {\n return 1;\n }\n std::string src_file_name;\n size_t pos = source.rfind('\/');\n if (pos == std::string::npos) {\n src_file_name = source;\n } else {\n src_file_name = source.substr(pos+1);\n }\n if (target[target.size() - 1] == '\/') {\n target += src_file_name;\n }\n\n baidu::common::timer::AutoTimer at(0, \"BfsPut\", target.c_str());\n FILE* fp = fopen(local, \"rb\");\n if (fp == NULL) {\n return 2;\n }\n struct stat st;\n if (stat(local, &st)) {\n fclose(fp);\n return 3;\n }\n baidu::bfs::File* file;\n if (fs->bfs_fs->OpenFile(target.c_str(), O_WRONLY | O_TRUNC, st.st_mode,\n &file, baidu::bfs::WriteOptions()) != 0) {\n fclose(fp);\n return 4;\n }\n char buf[10240];\n int64_t len = 0;\n int32_t bytes = 0;\n int ret = 0;\n while ((bytes = fread(buf, 1, sizeof(buf), fp)) > 0) {\n int32_t write_bytes = file->Write(buf, bytes);\n if (write_bytes < bytes) {\n ret = 5;\n break;\n }\n len += bytes;\n }\n fclose(fp);\n if (file->Close() != 0) {\n ret = 6;\n }\n delete file;\n printf(\"Put file to bfs %s %ld bytes\\n\", target.c_str(), len);\n return ret;\n}\n\nint64_t bfs_du_v2(bfs_fs_t* fs, const char* path) {\n int64_t du_size = 0;\n if (fs->bfs_fs->DiskUsage(path, &du_size) != 0) {\n fprintf(stderr, \"Compute Disk Usage fail: %s\\n\", path);\n return -1;\n }\n printf(\"%-9s\\t%s\\n\",\n baidu::common::HumanReadableString(du_size).c_str(), path);\n return du_size;\n}\n\nint bfs_du(bfs_fs_t* fs, const char* path) {\n std::string str_path = path;\n assert(str_path.size() > 0);\n if (str_path[str_path.size() - 1] != '*') {\n if (bfs_du_v2(fs, path) < 0) {\n return -1;\n }\n return 0;\n }\n\n \/\/ Wildcard\n str_path.resize(str_path.size() - 1);\n std::string ppath = str_path.substr(0, str_path.rfind('\/') + 1);\n std::string prefix = str_path.substr(ppath.size());\n int num = 0;\n baidu::bfs::BfsFileInfo* files = NULL;\n int32_t ret = fs->bfs_fs->ListDirectory(ppath.c_str(), &files, &num);\n if (ret != 0) {\n return ret;\n }\n int64_t total_size = 0;\n for (int j = 0; j < num; j++) {\n std::string name(files[j].name);\n if (name.find(prefix) != std::string::npos) {\n int64_t sz = bfs_du_v2(fs, (ppath + name).c_str());\n if (sz > 0) total_size += sz;\n }\n }\n printf(\"%s Total: %s\\n\",\n path, baidu::common::HumanReadableString(total_size).c_str());\n delete[] files;\n return ret;\n}\n\nint bfs_rm_dir(bfs_fs_t* fs, const char* path, bool recursive) {\n return fs->bfs_fs->DeleteDirectory(path, recursive);\n}\n\nint bfs_change_bfs_fslica_num(bfs_fs_t* fs, const char* path,\n const char* bfs_fslica_num) {\n if (!isdigit(*bfs_fslica_num)) {\n return -1;\n }\n return fs->bfs_fs->ChangeReplicaNum(path, strtol(bfs_fslica_num, NULL, 10));\n}\n\nint bfs_chmod(bfs_fs_t* fs, const char* str_mode, const char* path) {\n char* end_pos = NULL;\n int32_t mode = strtol(str_mode, &end_pos, 8);\n if (end_pos != NULL) {\n return -1;\n }\n return fs->bfs_fs->Chmod(mode, path);\n}\n\nint bfs_location(bfs_fs_t* fs, const char* path) {\n std::map > locations;\n int32_t ret = fs->bfs_fs->GetFileLocation(path, &locations);\n if (ret != 0) {\n return ret;\n }\n for (std::map >::iterator it =\n locations.begin(); it != locations.end(); ++it) {\n printf(\"block_id #%ld:\\n\", it->first);\n for (size_t i = 0; i < (it->second).size(); ++i) {\n printf(\"%s\\n\", (it->second)[i].c_str());\n }\n }\n return 0;\n}\n\n}\n\/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: *\/\nfix parse conf bug in bfs_c.cc (#919)\/\/ Copyright (c) 2017, Baidu.com, Inc. All Rights Reserved\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n#include \"sdk\/bfs_c.h\"\n#include \"sdk\/bfs.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n\nDECLARE_string(flagfile);\nDECLARE_string(nameserver_nodes);\n\nextern \"C\"{\n\nstruct bfs_fs_t {\n baidu::bfs::FS* bfs_fs;\n};\n\nstruct bfs_file_t {\n baidu::bfs::File* bfs_file;\n};\n\nbfs_fs_t* bfs_open_file_system(const char* flag_file) {\n if (flag_file) {\n FLAGS_flagfile = flag_file;\n } else {\n FLAGS_flagfile = \".\/bfs.flag\"; \n }\n\n \/\/ This function google::ParseCommandLineFlags(&argc, &argv, false),\n \/\/ parse the config from the argv[1]. And the argv[0] just use to represent \n \/\/ a program name, it's not a config parameter.\n int argc = 1;\n char* name = const_cast(\"bfs_c.cc\");\n char** argv = &name;\n ::google::ParseCommandLineFlags(&argc, &argv, false);\n\n bfs_fs_t* fs = new bfs_fs_t;\n std::string ns_address = FLAGS_nameserver_nodes;\n bool ret = baidu::bfs::FS::OpenFileSystem(ns_address.c_str(),\n &(fs->bfs_fs), baidu::bfs::FSOptions());\n if (!ret) {\n delete fs;\n return NULL;\n }\n return fs;\n}\n\nbfs_file_t* bfs_open_file(const bfs_fs_t* fs, const char* path, int flag) {\n if (flag != O_RDONLY && flag != O_WRONLY) {\n return NULL;\n }\n bfs_file_t* file = new bfs_file_t;\n int32_t ret = 0;\n if (flag == O_RDONLY) {\n ret = fs->bfs_fs->OpenFile(path, flag,\n &(file->bfs_file), baidu::bfs::ReadOptions());\n\n } else {\n ret = fs->bfs_fs->OpenFile(path, flag,\n &(file->bfs_file), baidu::bfs::WriteOptions());\n }\n if (ret != 0) {\n delete file->bfs_file;\n delete file;\n file = NULL;\n }\n return file;\n}\n\nint bfs_close_file(bfs_file_t* file) {\n int32_t ret = file->bfs_file->Close();\n delete file->bfs_file;\n file->bfs_file = NULL;\n delete file;\n return ret;\n}\n\nint bfs_write_file(bfs_file_t* file, const char* buf, int32_t len) {\n return file->bfs_file->Write(buf, len);\n}\n\nint bfs_read_file(bfs_file_t* file, char* buf, int32_t len) {\n return file->bfs_file->Read(buf, len);\n}\n\nint64_t bfs_seek(bfs_file_t* file, int64_t offset, int32_t whence) {\n return file->bfs_file->Seek(offset, whence);\n}\n\nint bfs_create_directory(bfs_fs_t* fs, const char* path) {\n return fs->bfs_fs->CreateDirectory(path);\n}\n\nint bfs_list_directory(bfs_fs_t* fs, const char* path) {\n char file_types[10] ={'-', 'd', 'l'};\n baidu::bfs::BfsFileInfo* files = NULL;\n int num;\n int32_t ret = fs->bfs_fs->ListDirectory(path, &files, &num);\n if (ret != 0) {\n return ret;\n }\n printf(\"Found %d items\\n\", num);\n for (int i = 0; i < num; i++) {\n char statbuf[16] = \"-rwxrwxrwx\";\n int32_t file_type = files[i].mode >> 9;\n int32_t file_perm = files[i].mode & 0777;\n statbuf[0] = file_types[file_type];\n\n for (int j = 1; j < 10; j++) {\n if ((file_perm & (1<<(9-j))) == 0) {\n statbuf[j] = '-';\n }\n }\n char timestr[64];\n struct tm stm;\n time_t ctime = files[i].ctime;\n localtime_r(&ctime, &stm);\n snprintf(timestr, sizeof(timestr), \"%4d-%02d-%02d %2d:%02d\",\n stm.tm_year+1900, stm.tm_mon+1, stm.tm_mday, stm.tm_hour, stm.tm_min);\n std::string prefix = path;\n if (files[i].name[0] == '\\0') {\n int32_t pos = prefix.size() - 1;\n while (pos >= 0 && prefix[pos] == '\/') {\n pos--;\n }\n prefix.resize(pos + 1);\n }\n printf(\"%s %-9s %s %s%s\\n\",\n statbuf, baidu::common::HumanReadableString(files[i].size).c_str(),\n timestr, prefix.c_str(), files[i].name);\n }\n delete[] files;\n return 0;\n}\n\nint bfs_delete_file(bfs_fs_t* fs, const char* path) {\n return fs->bfs_fs->DeleteFile(path);\n}\n\nint bfs_rename(bfs_fs_t* fs, const char* oldpath, const char* newpath) {\n return fs->bfs_fs->Rename(oldpath, newpath);\n}\n\nint bfs_touchz(bfs_fs_t* fs, const char* path) {\n baidu::bfs::File* file;\n int32_t ret = fs->bfs_fs->OpenFile(path, O_WRONLY, 0644,\n &file, baidu::bfs::WriteOptions());\n delete file;\n return ret;\n}\n\nint bfs_symlink(bfs_fs_t* fs, const char* src, const char* dst) {\n return fs->bfs_fs->Symlink(src, dst);\n}\n\nint bfs_cat(bfs_fs_t* fs, const char* path) {\n int64_t bytes = 0;\n baidu::bfs::File* file;\n int32_t ret = fs->bfs_fs->OpenFile(path, O_RDONLY, &file,\n baidu::bfs::ReadOptions());\n if (ret != 0) {\n return ret;\n }\n char buf[10240];\n int32_t len = 0;\n while (1) {\n len = file->Read(buf, sizeof(buf));\n if (len <= 0) {\n break;\n }\n bytes += len;\n write(1, buf, len);\n }\n delete file;\n return len;\n}\n\nint bfs_get(bfs_fs_t* fs, const char* bfs, const char* local) {\n std::string source = bfs;\n std::string target = local;\n std::vector src_elements;\n bool src_isdir = false;\n if (!baidu::common::util::SplitPath(source, &src_elements, &src_isdir)\n || src_isdir || src_elements.empty()) {\n return 1;\n }\n std::string src_file_name = src_elements[src_elements.size() - 1];\n if (target.empty() || target[target.size() - 1] == '\/') {\n target += src_file_name;\n }\n baidu::common::timer::AutoTimer at(0, \"BfsGet\", bfs);\n baidu::bfs::File* file;\n if (fs->bfs_fs->OpenFile(bfs, O_RDONLY, &file,\n baidu::bfs::ReadOptions()) != 0) {\n return 2;\n }\n FILE* fp = fopen(target.c_str(), \"wb\");\n if (fp == NULL) {\n delete file;\n return 3;\n }\n\n char buf[10240];\n int64_t bytes = 0;\n int32_t len = 0;\n while (1) {\n len = file->Read(buf, sizeof(buf));\n if (len <= 0) {\n if (len < 0) {\n fclose(fp);\n return 4;\n }\n break;\n }\n bytes += len;\n fwrite(buf, len, 1, fp);\n }\n printf(\"Read %ld bytes from %s\\n\", bytes, source.c_str());\n delete file;\n fclose(fp);\n return len;\n}\n\nint bfs_put(bfs_fs_t* fs, const char* local, const char* bfs) {\n std::string source = local;\n std::string target = bfs;\n if (source.empty() || source[source.size() - 1] == '\/' || target.empty()) {\n return 1;\n }\n std::string src_file_name;\n size_t pos = source.rfind('\/');\n if (pos == std::string::npos) {\n src_file_name = source;\n } else {\n src_file_name = source.substr(pos+1);\n }\n if (target[target.size() - 1] == '\/') {\n target += src_file_name;\n }\n\n baidu::common::timer::AutoTimer at(0, \"BfsPut\", target.c_str());\n FILE* fp = fopen(local, \"rb\");\n if (fp == NULL) {\n return 2;\n }\n struct stat st;\n if (stat(local, &st)) {\n fclose(fp);\n return 3;\n }\n baidu::bfs::File* file;\n if (fs->bfs_fs->OpenFile(target.c_str(), O_WRONLY | O_TRUNC, st.st_mode,\n &file, baidu::bfs::WriteOptions()) != 0) {\n fclose(fp);\n return 4;\n }\n char buf[10240];\n int64_t len = 0;\n int32_t bytes = 0;\n int ret = 0;\n while ((bytes = fread(buf, 1, sizeof(buf), fp)) > 0) {\n int32_t write_bytes = file->Write(buf, bytes);\n if (write_bytes < bytes) {\n ret = 5;\n break;\n }\n len += bytes;\n }\n fclose(fp);\n if (file->Close() != 0) {\n ret = 6;\n }\n delete file;\n printf(\"Put file to bfs %s %ld bytes\\n\", target.c_str(), len);\n return ret;\n}\n\nint64_t bfs_du_v2(bfs_fs_t* fs, const char* path) {\n int64_t du_size = 0;\n if (fs->bfs_fs->DiskUsage(path, &du_size) != 0) {\n fprintf(stderr, \"Compute Disk Usage fail: %s\\n\", path);\n return -1;\n }\n printf(\"%-9s\\t%s\\n\",\n baidu::common::HumanReadableString(du_size).c_str(), path);\n return du_size;\n}\n\nint bfs_du(bfs_fs_t* fs, const char* path) {\n std::string str_path = path;\n assert(str_path.size() > 0);\n if (str_path[str_path.size() - 1] != '*') {\n if (bfs_du_v2(fs, path) < 0) {\n return -1;\n }\n return 0;\n }\n\n \/\/ Wildcard\n str_path.resize(str_path.size() - 1);\n std::string ppath = str_path.substr(0, str_path.rfind('\/') + 1);\n std::string prefix = str_path.substr(ppath.size());\n int num = 0;\n baidu::bfs::BfsFileInfo* files = NULL;\n int32_t ret = fs->bfs_fs->ListDirectory(ppath.c_str(), &files, &num);\n if (ret != 0) {\n return ret;\n }\n int64_t total_size = 0;\n for (int j = 0; j < num; j++) {\n std::string name(files[j].name);\n if (name.find(prefix) != std::string::npos) {\n int64_t sz = bfs_du_v2(fs, (ppath + name).c_str());\n if (sz > 0) total_size += sz;\n }\n }\n printf(\"%s Total: %s\\n\",\n path, baidu::common::HumanReadableString(total_size).c_str());\n delete[] files;\n return ret;\n}\n\nint bfs_rm_dir(bfs_fs_t* fs, const char* path, bool recursive) {\n return fs->bfs_fs->DeleteDirectory(path, recursive);\n}\n\nint bfs_change_bfs_fslica_num(bfs_fs_t* fs, const char* path,\n const char* bfs_fslica_num) {\n if (!isdigit(*bfs_fslica_num)) {\n return -1;\n }\n return fs->bfs_fs->ChangeReplicaNum(path, strtol(bfs_fslica_num, NULL, 10));\n}\n\nint bfs_chmod(bfs_fs_t* fs, const char* str_mode, const char* path) {\n char* end_pos = NULL;\n int32_t mode = strtol(str_mode, &end_pos, 8);\n if (end_pos != NULL) {\n return -1;\n }\n return fs->bfs_fs->Chmod(mode, path);\n}\n\nint bfs_location(bfs_fs_t* fs, const char* path) {\n std::map > locations;\n int32_t ret = fs->bfs_fs->GetFileLocation(path, &locations);\n if (ret != 0) {\n return ret;\n }\n for (std::map >::iterator it =\n locations.begin(); it != locations.end(); ++it) {\n printf(\"block_id #%ld:\\n\", it->first);\n for (size_t i = 0; i < (it->second).size(); ++i) {\n printf(\"%s\\n\", (it->second)[i].c_str());\n }\n }\n return 0;\n}\n\n}\n\/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: *\/\n<|endoftext|>"} {"text":"\/*\n * Copyright 2017 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkPM4fPriv.h\"\n#include \"SkRasterPipeline.h\"\n#include \"SkReadBuffer.h\"\n#include \"SkString.h\"\n#include \"SkToSRGBColorFilter.h\"\n#include \"SkWriteBuffer.h\"\n\n#if SK_SUPPORT_GPU\n #include \"GrColorSpaceXform.h\"\n#endif\n\nvoid SkToSRGBColorFilter::onAppendStages(SkRasterPipeline* p,\n SkColorSpace* \/*dst color space*\/,\n SkArenaAlloc* alloc,\n bool shaderIsOpaque) const {\n \/\/ Step 1: Linearize by undoing the src transfer function.\n \/\/ Linear and sRGB will return true to isNumericalTransferFn(), so we check them first.\n SkColorSpaceTransferFn srcFn;\n if (fSrcColorSpace->gammaIsLinear()) {\n \/\/ Nothing to do.\n } else if (fSrcColorSpace->gammaCloseToSRGB()) {\n p->append(SkRasterPipeline::from_srgb);\n } else if (fSrcColorSpace->isNumericalTransferFn(&srcFn)) {\n auto copy = alloc->make(srcFn);\n p->append(SkRasterPipeline::parametric, copy);\n } else {\n SkDEBUGFAIL(\"Looks like we got a table transfer function here, quite unexpectedly.\");\n \/\/ TODO: If we really need to handle this, we can, but I don't think Ganesh does.\n }\n\n \/\/ Step 2: Transform to sRGB gamut (without clamping).\n append_gamut_transform(p,\n alloc,\n fSrcColorSpace.get(),\n SkColorSpace::MakeSRGB().get(),\n kPremul_SkAlphaType);\n\n \/\/ Step 3: Back to sRGB encoding.\n p->append(SkRasterPipeline::to_srgb);\n}\n\nsk_sp SkToSRGBColorFilter::Make(sk_sp srcColorSpace) {\n if (!srcColorSpace || srcColorSpace->isSRGB()) {\n return nullptr;\n } else {\n return sk_sp(new SkToSRGBColorFilter(std::move(srcColorSpace)));\n }\n}\n\nSkToSRGBColorFilter::SkToSRGBColorFilter(sk_sp srcColorSpace)\n : fSrcColorSpace(std::move(srcColorSpace)) {\n SkASSERT(fSrcColorSpace);\n}\n\nsk_sp SkToSRGBColorFilter::CreateProc(SkReadBuffer& buffer) {\n auto data = buffer.readByteArrayAsData();\n return data ? Make(SkColorSpace::Deserialize(data->data(), data->size())) : nullptr;\n}\n\nvoid SkToSRGBColorFilter::flatten(SkWriteBuffer& buffer) const {\n buffer.writeDataAsByteArray(fSrcColorSpace->serialize().get());\n}\n\n#if SK_SUPPORT_GPU\nstd::unique_ptr SkToSRGBColorFilter::asFragmentProcessor(\n GrContext*, const GrColorSpaceInfo&) const {\n return GrColorSpaceXformEffect::Make(fSrcColorSpace.get(), SkColorSpace::MakeSRGB().get());\n}\n#endif\nReland \"update SkToSRGBColorFilter color management\"\/*\n * Copyright 2017 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkColorSpaceXformSteps.h\"\n#include \"SkPM4fPriv.h\"\n#include \"SkRasterPipeline.h\"\n#include \"SkReadBuffer.h\"\n#include \"SkString.h\"\n#include \"SkToSRGBColorFilter.h\"\n#include \"SkWriteBuffer.h\"\n\n#if SK_SUPPORT_GPU\n #include \"GrColorSpaceXform.h\"\n#endif\n\nvoid SkToSRGBColorFilter::onAppendStages(SkRasterPipeline* p,\n SkColorSpace* \/*dst color space*\/,\n SkArenaAlloc* alloc,\n bool shaderIsOpaque) const {\n alloc->make(fSrcColorSpace.get(), kPremul_SkAlphaType,\n SkColorSpace::MakeSRGB().get())\n ->apply(p);\n}\n\nsk_sp SkToSRGBColorFilter::Make(sk_sp srcColorSpace) {\n if (!srcColorSpace || srcColorSpace->isSRGB()) {\n return nullptr;\n } else {\n return sk_sp(new SkToSRGBColorFilter(std::move(srcColorSpace)));\n }\n}\n\nSkToSRGBColorFilter::SkToSRGBColorFilter(sk_sp srcColorSpace)\n : fSrcColorSpace(std::move(srcColorSpace)) {\n SkASSERT(fSrcColorSpace);\n}\n\nsk_sp SkToSRGBColorFilter::CreateProc(SkReadBuffer& buffer) {\n auto data = buffer.readByteArrayAsData();\n return data ? Make(SkColorSpace::Deserialize(data->data(), data->size())) : nullptr;\n}\n\nvoid SkToSRGBColorFilter::flatten(SkWriteBuffer& buffer) const {\n buffer.writeDataAsByteArray(fSrcColorSpace->serialize().get());\n}\n\n#if SK_SUPPORT_GPU\nstd::unique_ptr SkToSRGBColorFilter::asFragmentProcessor(\n GrContext*, const GrColorSpaceInfo&) const {\n return GrColorSpaceXformEffect::Make(fSrcColorSpace.get(), SkColorSpace::MakeSRGB().get());\n}\n#endif\n<|endoftext|>"} {"text":"#include \"Engine.h\"\n#include \"Game.h\"\n#include \"ObjectDummy.h\"\n#include \"BodyRigid.h\"\n#include \"BodyDummy.h\"\n#include \"Physics.h\"\n#include \"ShapeCapsule.h\"\n#include \"ActorBase.h\"\n#include \"Visualizer.h\"\n#include \"sys\/SysControl.h\"\n\n\nusing namespace MathLib;\n\n#ifdef MEMORY_INFO\n#define new new(__FILE__, __LINE__) \n#endif \/\/ MEMORY_INFO\n\n\/*\n*\/\n#define ACTOR_BASE_IFPS (1.0f \/ 60.0f)\n#define ACTOR_BASE_CLAMP 89.9f\n#define ACTOR_BASE_COLLISIONS 4\n\n\n\/*\n*\/\nCActorBase::CActorBase()\n{\n\tm_vUp = vec3(0.0f, 0.0f, 1.0f);\t\n\tm_pObject = new CObjectDummy();\n\tm_pDummy = new CBodyDummy();\n\tm_pShape = new CShapeCapsule(1.0f, 1.0f);\n\n\tm_nFlush = 0;\n\tm_vPosition = Vec3_zero;\n\tm_vVelocity = Vec3_zero;\n\tm_fPhiAngle = 0.0f;\t\t\t\/\/倾斜角\t\t二维平面坐标系中,直线向Y周延伸的方向与X轴正向之间的夹角\n\tm_fThetaAngle = 0.0f;\t\t\t\/\/方位角,正北方那条线与当前线条按照顺时针走过的角度\n\n\n\tfor (int i = 0; i < NUM_STATES; i++)\n\t{\n\t\tm_pStates[i] = 0;\n\t\tm_pTimes[i] = 0.0f;\n\t}\n\tm_pDummy->SetEnabled(1);\n\tm_pObject->SetBody(NULL);\n\tm_pObject->SetBody(m_pDummy);\n\tm_pShape->SetBody(NULL);\n\tm_pShape->SetBody(m_pDummy);\n\n\tm_pObject->SetWorldTransform(Get_Body_Transform());\n\tm_pShape->SetRestitution(0.0f);\n\tm_pShape->SetCollisionMask(2);\n\n\n\tSetEnabled(1);\n\tSetViewDirection(vec3(0.0f, 1.0f, 0.0f));\n\tSetCollision(1);\n\tSetCollisionRadius(0.3f);\n\tSetCollisionHeight(1.0f);\n\tSetFriction(2.0f);\n\tSetMinVelocity(2.0f);\n\tSetMaxVelocity(4.0f);\n\tSetAcceleration(8.0f);\n\tSetDamping(8.0f);\n\tSetJumping(1.5f);\n\n\tSetGround(0);\n\tSetCeiling(0);\n}\n\n\nCActorBase::~CActorBase()\n{\n\tm_pDummy->SetObject(NULL);\n\tdelete m_pObject;\n\tdelete m_pDummy;\n}\n\nvoid CActorBase::SetEnabled(int enable)\n{\n\tm_nEnable = enable;\n\tm_pDummy->SetEnabled(m_nEnable);\n}\n\n\nint CActorBase::IsEnabled() const\n{\n\treturn m_nEnable;\n}\nvoid CActorBase::Update(float ifps)\n{\n\tif (!m_nEnable)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ impulse\n\tvec3 impulse = vec3_zero;\n\n\t\/\/ ortho basis\n\tvec3 tangent, binormal;\n\tOrthoBasis(m_vUp, tangent, binormal);\n}Signed-off-by: mrlitong #include \"Engine.h\"\n#include \"Game.h\"\n#include \"ObjectDummy.h\"\n#include \"BodyRigid.h\"\n#include \"BodyDummy.h\"\n#include \"Physics.h\"\n#include \"ShapeCapsule.h\"\n#include \"ActorBase.h\"\n#include \"Visualizer.h\"\n#include \"sys\/SysControl.h\"\n\n\nusing namespace MathLib;\n\n#ifdef MEMORY_INFO\n#define new new(__FILE__, __LINE__) \n#endif \/\/ MEMORY_INFO\n\n\/*\n*\/\n#define ACTOR_BASE_IFPS (1.0f \/ 60.0f)\n#define ACTOR_BASE_CLAMP 89.9f\n#define ACTOR_BASE_COLLISIONS 4\n\n\n\/*\n*\/\nCActorBase::CActorBase()\n{\n\tm_vUp = vec3(0.0f, 0.0f, 1.0f);\t\n\tm_pObject = new CObjectDummy();\n\tm_pDummy = new CBodyDummy();\n\tm_pShape = new CShapeCapsule(1.0f, 1.0f);\n\n\tm_nFlush = 0;\n\tm_vPosition = Vec3_zero;\n\tm_vVelocity = Vec3_zero;\n\tm_fPhiAngle = 0.0f;\t\t\t\/\/倾斜角\t\t二维平面坐标系中,直线向Y周延伸的方向与X轴正向之间的夹角\n\tm_fThetaAngle = 0.0f;\t\t\t\/\/方位角,正北方那条线与当前线条按照顺时针走过的角度\n\n\n\tfor (int i = 0; i < NUM_STATES; i++)\n\t{\n\t\tm_pStates[i] = 0;\n\t\tm_pTimes[i] = 0.0f;\n\t}\n\tm_pDummy->SetEnabled(1);\n\tm_pObject->SetBody(NULL);\n\tm_pObject->SetBody(m_pDummy);\n\tm_pShape->SetBody(NULL);\n\tm_pShape->SetBody(m_pDummy);\n\n\tm_pObject->SetWorldTransform(Get_Body_Transform());\n\tm_pShape->SetRestitution(0.0f);\n\tm_pShape->SetCollisionMask(2);\n\n\n\tSetEnabled(1);\n\tSetViewDirection(vec3(0.0f, 1.0f, 0.0f));\n\tSetCollision(1);\n\tSetCollisionRadius(0.3f);\n\tSetCollisionHeight(1.0f);\n\tSetFriction(2.0f);\n\tSetMinVelocity(2.0f);\n\tSetMaxVelocity(4.0f);\n\tSetAcceleration(8.0f);\n\tSetDamping(8.0f);\n\tSetJumping(1.5f);\n\n\tSetGround(0);\n\tSetCeiling(0);\n}\n\n\nCActorBase::~CActorBase()\n{\n\tm_pDummy->SetObject(NULL);\n\tdelete m_pObject;\n\tdelete m_pDummy;\n}\n\nvoid CActorBase::SetEnabled(int enable)\n{\n\tm_nEnable = enable;\n\tm_pDummy->SetEnabled(m_nEnable);\n}\n\n\nint CActorBase::IsEnabled() const\n{\n\treturn m_nEnable;\n}\nvoid CActorBase::Update(float ifps)\n{\n\tif (!m_nEnable)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ impulse\n\tvec3 impulse = vec3_zero;\n\n\t\/\/ ortho basis\n\tvec3 tangent, binormal;\n\tOrthoBasis(m_vUp, tangent, binormal);\n\n\t\/\/ current basis\n\tvec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;\n\tvec3 y = Normalize(Cross(m_vUp, x));\n\tvec3 z = Normalize(Cross(x, y));\n\n\n\n\n}<|endoftext|>"} {"text":"\/* This file is part of the Vc library. {{{\nCopyright © 2014 Matthias Kretz \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the names of contributing organizations nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n}}}*\/\n\n#include \"unittest.h\"\n#include \n\nusing Vc::simdize;\nusing Vc::float_v;\nusing Vc::int_v;\nusing Vc::int_m;\n\ntemplate \nusing SimdizeAdapter = Vc::SimdizeDetail::Adapter;\n\nTEST(test_simdize)\n{\n using namespace std;\n using namespace Vc;\n using Test0 = simdize;\n using Test1 = simdize>;\n using Test1_0 = typename std::decay(Test1()))>::type;\n using Test1_1 = typename tuple_element<1, typename Test1::base_type>::type;\n using Test2 = simdize>;\n using Test2_0 = typename tuple_element<0, typename Test2::base_type>::type;\n using Test2_1 = typename tuple_element<1, typename Test2::base_type>::type;\n using Test3 = simdize>;\n using Test3_1 = typename tuple_element<1, typename Test3::base_type>::type;\n using Test4 = simdize>;\n using Test4_0 = typename tuple_element<0, typename Test4::base_type>::type;\n using Test4_1 = typename tuple_element<1, typename Test4::base_type>::type;\n using Test4_2 = typename tuple_element<2, typename Test4::base_type>::type;\n COMPARE(Test0::size(), float_v::size());\n COMPARE(Test1_0::size(), float_v::size());\n COMPARE(Test1_1::size(), float_v::size());\n COMPARE(Test1::size(), float_v::size());\n COMPARE(Test2_0::size(), double_v::size());\n COMPARE(Test2_1::size(), double_v::size());\n COMPARE(Test2::size(), double_v::size());\n COMPARE(Test3_1::size(), float_v::size());\n COMPARE(Test3::size(), float_v::size());\n COMPARE(Test4_0::size(), double_v::size());\n COMPARE(Test4_2::size(), double_v::size());\n COMPARE(Test4::size(), double_v::size());\n COMPARE(typeid(Test4_0), typeid(double_v));\n COMPARE(typeid(Test4_1), typeid(std::string));\n COMPARE(typeid(Test4_2), typeid(simdize));\n COMPARE(typeid(simdize>), typeid(tuple));\n COMPARE(typeid(simdize), typeid(float_v));\n COMPARE(typeid(Test1),\n typeid(SimdizeAdapter,\n tuple>,\n float_v::size()>));\n}\n\nTEST(simdize_bools)\n{\n using namespace std;\n using namespace Vc;\n COMPARE(typeid(simdize), typeid(float_m));\n COMPARE(typeid(simdize), typeid(float_m));\n COMPARE(typeid(simdize), typeid(int_m));\n COMPARE(typeid(simdize), typeid(int_m));\n COMPARE(typeid(simdize),\n typeid(simd_mask_array));\n COMPARE(typeid(simdize),\n typeid(simd_mask_array));\n\n COMPARE(typeid(simdize>),\n typeid(SimdizeAdapter, tuple, float_m::size()>));\n COMPARE(typeid(simdize, float_m::size()>),\n typeid(SimdizeAdapter, tuple, float_m::size()>));\n COMPARE(\n typeid(simdize, float_m::size() + 1>),\n typeid(\n SimdizeAdapter, tuple>,\n float_m::size() + 1>));\n\n COMPARE(typeid(simdize>),\n typeid(SimdizeAdapter, tuple, int_v::size()>));\n COMPARE(\n typeid(simdize, 3>),\n typeid(SimdizeAdapter,\n tuple, simd_mask_array>, 3>));\n\n COMPARE(\n typeid(simdize>),\n typeid(SimdizeAdapter,\n tuple, float_m>,\n float_m::size()>));\n COMPARE(typeid(simdize, float_m::size() + 1>),\n typeid(SimdizeAdapter,\n tuple,\n simdarray,\n simd_mask_array>,\n float_m::size() + 1>));\n COMPARE(typeid(simdize, 0, double>),\n typeid(SimdizeAdapter,\n tuple, double_m::size()>));\n\n COMPARE(typeid(simdize, 0, double>),\n typeid(SimdizeAdapter,\n tuple,\n simdize>,\n int_v::size()>));\n}\n\ntemplate struct Foo1 {};\ntemplate struct Foo2 {};\ntemplate struct Foo3 {};\n\nTEST(nontype_template_parameters)\n{\n using namespace std;\n using namespace Vc;\n using std::array;\n\n static_assert(SimdizeDetail::is_class_template>::value, \"\");\n static_assert(SimdizeDetail::is_class_template>::value, \"\");\n static_assert(SimdizeDetail::is_class_template>::value, \"\");\n\n COMPARE(typeid(simdize>),\n typeid(SimdizeAdapter, array, float_v::size()>));\n COMPARE(typeid(simdize>),\n typeid(SimdizeAdapter, array, float_m::size()>));\n COMPARE(\n typeid(simdize>),\n typeid(\n SimdizeAdapter, Foo1, float_v::size()>));\n COMPARE(typeid(simdize>),\n typeid(SimdizeAdapter,\n Foo2, int_v::size()>));\n COMPARE(typeid(simdize>),\n typeid(SimdizeAdapter,\n Foo3, int_v::size()>));\n}\n\nTEST(tuple_interface)\n{\n using V0 = simdize>;\n COMPARE(std::tuple_size::value, 2u);\n COMPARE(typeid(typename std::tuple_element<0, V0>::type), typeid(int_v));\n COMPARE(typeid(typename std::tuple_element<1, V0>::type), typeid(int_m));\n\n V0 v;\n COMPARE(typeid(decltype(std::get<0>(v))), typeid(int_v));\n COMPARE(typeid(decltype(std::get<1>(v))), typeid(int_m));\n std::get<0>(v) = int_v::IndexesFromZero();\n COMPARE(std::get<0>(v), int_v::IndexesFromZero());\n std::get<0>(v) += 1;\n COMPARE(std::get<0>(v), int_v::IndexesFromZero() + 1);\n}\n\nTEST(assign)\n{\n using T = std::tuple;\n using V = simdize;\n V v;\n for (unsigned i = 0; i < v.size(); ++i) {\n assign(v, i, T{1.f * i, i});\n COMPARE(std::get<0>(v)[i], 1.f * i);\n COMPARE(std::get<1>(v)[i], i);\n }\n for (unsigned i = 0; i < v.size(); ++i) {\n COMPARE(std::get<0>(v)[i], 1.f * i);\n COMPARE(std::get<1>(v)[i], i);\n }\n}\n\nTEST(extract)\n{\n using T = std::tuple;\n using V = simdize;\n V v;\n for (unsigned i = 0; i < v.size(); ++i) {\n assign(v, i, T{1.f * i, i});\n COMPARE(std::get<0>(v)[i], 1.f * i);\n COMPARE(std::get<1>(v)[i], i);\n }\n for (unsigned i = 0; i < v.size(); ++i) {\n COMPARE(std::get<0>(v)[i], 1.f * i);\n COMPARE(std::get<1>(v)[i], i);\n }\n for (unsigned i = 0; i < v.size(); ++i) {\n COMPARE(extract(v, i), T(1.f * i, i));\n }\n}\n\nTEST(decorate)\n{\n using T = std::tuple;\n using V = simdize;\n V v;\n auto vv = decorate(v);\n for (unsigned i = 0; i < v.size(); ++i) {\n vv[i] = T{1.f * i, i};\n COMPARE(std::get<0>(v)[i], 1.f * i);\n COMPARE(std::get<1>(v)[i], i);\n }\n for (unsigned i = 0; i < v.size(); ++i) {\n COMPARE(std::get<0>(v)[i], 1.f * i);\n COMPARE(std::get<1>(v)[i], i);\n }\n for (unsigned i = 0; i < v.size(); ++i) {\n T x = vv[i];\n COMPARE(x, T(1.f * i, i));\n }\n const V &v2 = v;\n for (unsigned i = 0; i < v.size(); ++i) {\n T x = decorate(v2)[i];\n COMPARE(x, T(1.f * i, i));\n }\n}\n\nTEST(broadcast)\n{\n {\n using T = std::tuple;\n using V = simdize;\n\n T scalar(2.f, 3);\n V vector(scalar);\n COMPARE(std::get<0>(vector), float_v(2.f));\n COMPARE(std::get<1>(vector), (simdize(3)));\n }\n {\n using T = std::array;\n using V = simdize;\n T scalar{1, 2, 3};\n V vector(scalar);\n COMPARE(vector[0], int_v(1));\n COMPARE(vector[1], int_v(2));\n COMPARE(vector[2], int_v(3));\n }\n}\n\nTEST(list_iterator_vectorization)\n{\n {\n using L = std::list;\n using LIV = simdize;\n L list;\n for (auto i = 1024; i; --i) {\n list.push_back(i);\n }\n LIV b = list.begin();\n LIV e = list.end();\n float_v reference = list.size() - float_v::IndexesFromZero();\n for (; b != e; ++b, reference -= float_v::size()) {\n float_v x = *b;\n COMPARE(x, reference);\n COMPARE(*b, reference);\n *b = x + 1;\n COMPARE(*b, reference + 1);\n }\n reference = list.size() - float_v::IndexesFromZero() + 1;\n for (b = list.begin(); b != e; ++b, reference -= float_v::size()) {\n float_v x = *b;\n COMPARE(x, reference);\n COMPARE(*b, reference);\n }\n }\n {\n using T = std::tuple;\n using V = simdize;\n using L = std::list;\n using LIV = simdize;\n L list;\n for (auto i = 1024; i; --i) {\n list.push_back(T(i, i * 2, i * 3));\n }\n LIV b = list.begin();\n LIV e = list.end();\n auto reference1 = list.size() - float_v::IndexesFromZero();\n auto reference2 = list.size() - simdize::IndexesFromZero();\n for (; b != e; ++b, reference1 -= V::size(), reference2 -= V::size()) {\n V x = *b;\n COMPARE(x, V(reference1, reference2 * 2, reference1 * 3));\n COMPARE(std::get<0>(*b), reference1);\n }\n }\n}\n\n\/\/ vim: foldmethod=marker\nsimdize: fix bool vectorization test\/* This file is part of the Vc library. {{{\nCopyright © 2014 Matthias Kretz \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the names of contributing organizations nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n}}}*\/\n\n#include \"unittest.h\"\n#include \n\nusing Vc::simdize;\nusing Vc::float_v;\nusing Vc::int_v;\nusing Vc::int_m;\n\ntemplate \nusing SimdizeAdapter = Vc::SimdizeDetail::Adapter;\n\nTEST(test_simdize)\n{\n using namespace std;\n using namespace Vc;\n using Test0 = simdize;\n using Test1 = simdize>;\n using Test1_0 = typename std::decay(Test1()))>::type;\n using Test1_1 = typename tuple_element<1, typename Test1::base_type>::type;\n using Test2 = simdize>;\n using Test2_0 = typename tuple_element<0, typename Test2::base_type>::type;\n using Test2_1 = typename tuple_element<1, typename Test2::base_type>::type;\n using Test3 = simdize>;\n using Test3_1 = typename tuple_element<1, typename Test3::base_type>::type;\n using Test4 = simdize>;\n using Test4_0 = typename tuple_element<0, typename Test4::base_type>::type;\n using Test4_1 = typename tuple_element<1, typename Test4::base_type>::type;\n using Test4_2 = typename tuple_element<2, typename Test4::base_type>::type;\n COMPARE(Test0::size(), float_v::size());\n COMPARE(Test1_0::size(), float_v::size());\n COMPARE(Test1_1::size(), float_v::size());\n COMPARE(Test1::size(), float_v::size());\n COMPARE(Test2_0::size(), double_v::size());\n COMPARE(Test2_1::size(), double_v::size());\n COMPARE(Test2::size(), double_v::size());\n COMPARE(Test3_1::size(), float_v::size());\n COMPARE(Test3::size(), float_v::size());\n COMPARE(Test4_0::size(), double_v::size());\n COMPARE(Test4_2::size(), double_v::size());\n COMPARE(Test4::size(), double_v::size());\n COMPARE(typeid(Test4_0), typeid(double_v));\n COMPARE(typeid(Test4_1), typeid(std::string));\n COMPARE(typeid(Test4_2), typeid(simdize));\n COMPARE(typeid(simdize>), typeid(tuple));\n COMPARE(typeid(simdize), typeid(float_v));\n COMPARE(typeid(Test1),\n typeid(SimdizeAdapter,\n tuple>,\n float_v::size()>));\n}\n\nTEST(simdize_bools)\n{\n using namespace std;\n using namespace Vc;\n COMPARE(typeid(simdize), typeid(float_m));\n COMPARE(typeid(simdize), typeid(float_m));\n COMPARE(typeid(simdize), typeid(int_m));\n COMPARE(typeid(simdize), typeid(int_m));\n COMPARE(typeid(simdize),\n typeid(simd_mask_array));\n COMPARE(typeid(simdize),\n typeid(simd_mask_array));\n\n COMPARE(typeid(simdize>),\n typeid(SimdizeAdapter, tuple, float_m::size()>));\n COMPARE(typeid(simdize, float_m::size()>),\n typeid(SimdizeAdapter, tuple, float_m::size()>));\n COMPARE(\n typeid(simdize, float_m::size() + 1>),\n typeid(\n SimdizeAdapter, tuple>,\n float_m::size() + 1>));\n\n COMPARE(typeid(simdize>),\n typeid(SimdizeAdapter, tuple, int_v::size()>));\n COMPARE(\n typeid(simdize, 3>),\n typeid(SimdizeAdapter,\n tuple, simd_mask_array>, 3>));\n\n COMPARE(\n typeid(simdize>),\n typeid(SimdizeAdapter<\n tuple,\n tuple>::type,\n float_m>,\n float_m::size()>));\n COMPARE(typeid(simdize, float_m::size() + 1>),\n typeid(SimdizeAdapter,\n tuple,\n simdarray,\n simd_mask_array>,\n float_m::size() + 1>));\n COMPARE(typeid(simdize, 0, double>),\n typeid(SimdizeAdapter,\n tuple, double_m::size()>));\n\n COMPARE(typeid(simdize, 0, double>),\n typeid(SimdizeAdapter,\n tuple,\n simdize>,\n int_v::size()>));\n}\n\ntemplate struct Foo1 {};\ntemplate struct Foo2 {};\ntemplate struct Foo3 {};\n\nTEST(nontype_template_parameters)\n{\n using namespace std;\n using namespace Vc;\n using std::array;\n\n static_assert(SimdizeDetail::is_class_template>::value, \"\");\n static_assert(SimdizeDetail::is_class_template>::value, \"\");\n static_assert(SimdizeDetail::is_class_template>::value, \"\");\n\n COMPARE(typeid(simdize>),\n typeid(SimdizeAdapter, array, float_v::size()>));\n COMPARE(typeid(simdize>),\n typeid(SimdizeAdapter, array, float_m::size()>));\n COMPARE(\n typeid(simdize>),\n typeid(\n SimdizeAdapter, Foo1, float_v::size()>));\n COMPARE(typeid(simdize>),\n typeid(SimdizeAdapter,\n Foo2, int_v::size()>));\n COMPARE(typeid(simdize>),\n typeid(SimdizeAdapter,\n Foo3, int_v::size()>));\n}\n\nTEST(tuple_interface)\n{\n using V0 = simdize>;\n COMPARE(std::tuple_size::value, 2u);\n COMPARE(typeid(typename std::tuple_element<0, V0>::type), typeid(int_v));\n COMPARE(typeid(typename std::tuple_element<1, V0>::type), typeid(int_m));\n\n V0 v;\n COMPARE(typeid(decltype(std::get<0>(v))), typeid(int_v));\n COMPARE(typeid(decltype(std::get<1>(v))), typeid(int_m));\n std::get<0>(v) = int_v::IndexesFromZero();\n COMPARE(std::get<0>(v), int_v::IndexesFromZero());\n std::get<0>(v) += 1;\n COMPARE(std::get<0>(v), int_v::IndexesFromZero() + 1);\n}\n\nTEST(assign)\n{\n using T = std::tuple;\n using V = simdize;\n V v;\n for (unsigned i = 0; i < v.size(); ++i) {\n assign(v, i, T{1.f * i, i});\n COMPARE(std::get<0>(v)[i], 1.f * i);\n COMPARE(std::get<1>(v)[i], i);\n }\n for (unsigned i = 0; i < v.size(); ++i) {\n COMPARE(std::get<0>(v)[i], 1.f * i);\n COMPARE(std::get<1>(v)[i], i);\n }\n}\n\nTEST(extract)\n{\n using T = std::tuple;\n using V = simdize;\n V v;\n for (unsigned i = 0; i < v.size(); ++i) {\n assign(v, i, T{1.f * i, i});\n COMPARE(std::get<0>(v)[i], 1.f * i);\n COMPARE(std::get<1>(v)[i], i);\n }\n for (unsigned i = 0; i < v.size(); ++i) {\n COMPARE(std::get<0>(v)[i], 1.f * i);\n COMPARE(std::get<1>(v)[i], i);\n }\n for (unsigned i = 0; i < v.size(); ++i) {\n COMPARE(extract(v, i), T(1.f * i, i));\n }\n}\n\nTEST(decorate)\n{\n using T = std::tuple;\n using V = simdize;\n V v;\n auto vv = decorate(v);\n for (unsigned i = 0; i < v.size(); ++i) {\n vv[i] = T{1.f * i, i};\n COMPARE(std::get<0>(v)[i], 1.f * i);\n COMPARE(std::get<1>(v)[i], i);\n }\n for (unsigned i = 0; i < v.size(); ++i) {\n COMPARE(std::get<0>(v)[i], 1.f * i);\n COMPARE(std::get<1>(v)[i], i);\n }\n for (unsigned i = 0; i < v.size(); ++i) {\n T x = vv[i];\n COMPARE(x, T(1.f * i, i));\n }\n const V &v2 = v;\n for (unsigned i = 0; i < v.size(); ++i) {\n T x = decorate(v2)[i];\n COMPARE(x, T(1.f * i, i));\n }\n}\n\nTEST(broadcast)\n{\n {\n using T = std::tuple;\n using V = simdize;\n\n T scalar(2.f, 3);\n V vector(scalar);\n COMPARE(std::get<0>(vector), float_v(2.f));\n COMPARE(std::get<1>(vector), (simdize(3)));\n }\n {\n using T = std::array;\n using V = simdize;\n T scalar{1, 2, 3};\n V vector(scalar);\n COMPARE(vector[0], int_v(1));\n COMPARE(vector[1], int_v(2));\n COMPARE(vector[2], int_v(3));\n }\n}\n\nTEST(list_iterator_vectorization)\n{\n {\n using L = std::list;\n using LIV = simdize;\n L list;\n for (auto i = 1024; i; --i) {\n list.push_back(i);\n }\n LIV b = list.begin();\n LIV e = list.end();\n float_v reference = list.size() - float_v::IndexesFromZero();\n for (; b != e; ++b, reference -= float_v::size()) {\n float_v x = *b;\n COMPARE(x, reference);\n COMPARE(*b, reference);\n *b = x + 1;\n COMPARE(*b, reference + 1);\n }\n reference = list.size() - float_v::IndexesFromZero() + 1;\n for (b = list.begin(); b != e; ++b, reference -= float_v::size()) {\n float_v x = *b;\n COMPARE(x, reference);\n COMPARE(*b, reference);\n }\n }\n {\n using T = std::tuple;\n using V = simdize;\n using L = std::list;\n using LIV = simdize;\n L list;\n for (auto i = 1024; i; --i) {\n list.push_back(T(i, i * 2, i * 3));\n }\n LIV b = list.begin();\n LIV e = list.end();\n auto reference1 = list.size() - float_v::IndexesFromZero();\n auto reference2 = list.size() - simdize::IndexesFromZero();\n for (; b != e; ++b, reference1 -= V::size(), reference2 -= V::size()) {\n V x = *b;\n COMPARE(x, V(reference1, reference2 * 2, reference1 * 3));\n COMPARE(std::get<0>(*b), reference1);\n }\n }\n}\n\n\/\/ vim: foldmethod=marker\n<|endoftext|>"} {"text":"\/*\n * Skaffari - a mail account administration web interface based on Cutelyst\n * Copyright (C) 2017 Matthias Fehring \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"skaffari.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"objects\/domain.h\"\n#include \"objects\/simpleadmin.h\"\n#include \"objects\/simpledomain.h\"\n#include \"objects\/simpleaccount.h\"\n#include \"objects\/adminaccount.h\"\n#include \"objects\/account.h\"\n#include \"objects\/folder.h\"\n#include \"objects\/helpentry.h\"\n\n#include \"utils\/language.h\"\n#include \"utils\/skaffariconfig.h\"\n\n#include \"..\/common\/config.h\"\n#include \"..\/common\/global.h\"\n#include \"root.h\"\n#include \"authstoresql.h\"\n#include \"login.h\"\n#include \"logout.h\"\n#include \"domaineditor.h\"\n#include \"accounteditor.h\"\n#include \"admineditor.h\"\n#include \"myaccount.h\"\n#include \"settingseditor.h\"\n\nQ_LOGGING_CATEGORY(SK_CORE, \"skaffari.core\")\n\nusing namespace Cutelyst;\n\nbool Skaffari::isInitialized = false;\n\nSkaffari::Skaffari(QObject *parent) : Application(parent)\n{\n}\n\nSkaffari::~Skaffari()\n{\n}\n\nbool Skaffari::init()\n{\n QCoreApplication::setApplicationName(QStringLiteral(\"Skaffari\"));\n QCoreApplication::setApplicationVersion(QStringLiteral(SKAFFARI_VERSION));\n\n qRegisterMetaType(\"quota_size_t\");\n qRegisterMetaType(\"dbid_t\");\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType(\"HelpHash\");\n\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n\n const QString tmplName = QStringLiteral(\"default\");\n const QString tmplBasePath = QStringLiteral(SKAFFARI_TMPLDIR) + QLatin1Char('\/') + tmplName;\n\n if (!isInitialized) {\n QVariantMap tmplConfig;\n QFile tmplConfigFile(tmplBasePath + QLatin1String(\"\/config.json\"));\n if (tmplConfigFile.exists()) {\n qCDebug(SK_CORE, \"Found template configuration file.\");\n if (tmplConfigFile.open(QIODevice::ReadOnly|QIODevice::Text)) {\n QJsonParseError jpe;\n QJsonDocument tmplJsonConfig(QJsonDocument::fromJson(tmplConfigFile.readAll(), &jpe));\n if (jpe.error != QJsonParseError::NoError) {\n qCCritical(SK_CORE, \"Failed to parse template configuration file: %s\", qUtf8Printable(jpe.errorString()));\n return false;\n }\n\n tmplConfig = tmplJsonConfig.object().toVariantMap();\n } else {\n qCCritical(SK_CORE, \"Failed to open template configuration file %s.\", qUtf8Printable(tmplConfigFile.fileName()));\n return false;\n }\n }\n\n qCDebug(SK_CORE) << \"Initializing configuration.\";\n SkaffariConfig::load(engine()->config(QStringLiteral(\"Accounts\")),\n engine()->config(QStringLiteral(\"Admins\")),\n engine()->config(QStringLiteral(\"IMAP\")),\n tmplConfig);\n\n if (SkaffariConfig::imapUser().isEmpty()) {\n qCCritical(SK_CORE) << \"No valid IMAP user defined.\";\n return false;\n }\n\n if (SkaffariConfig::imapPassword().isEmpty()) {\n qCCritical(SK_CORE) << \"No valid IMAP password defined.\";\n return false;\n }\n\n \/\/ initialize DB one time to prevent https:\/\/bugreports.qt.io\/browse\/QTBUG-54872\n if (!initDb()) {\n return false;\n }\n\n SkaffariConfig::loadSettingsFromDB();\n\n isInitialized = true;\n }\n\n QString sitePath = tmplBasePath + QLatin1String(\"\/site\");\n\n auto view = new GrantleeView(this);\n view->setTemplateExtension(QStringLiteral(\".html\"));\n view->setWrapper(QStringLiteral(\"wrapper.html\"));\n\tview->setCache(false);\n view->setIncludePaths({sitePath});\n view->engine()->addDefaultLibrary(QStringLiteral(\"grantlee_i18ntags\"));\n view->engine()->addDefaultLibrary(QStringLiteral(\"grantlee_skaffari\"));\n\n \/* Start loading translations *\/\n const QString tmplTransFileName = QLatin1String(\"tmpl_\") + tmplName;\n const QString tmplTransFilePath = tmplBasePath + QLatin1String(\"\/l10n\");\n\n const QStringList supportedLangs = SKAFFARI_SUPPORTED_LANGS;\n for (const QString &lang : supportedLangs) {\n if (Q_LIKELY(lang != QLatin1String(\"en\"))) {\n qCDebug(SK_CORE, \"Loading translations for language %s.\", qUtf8Printable(lang));\n const QLocale locale(lang);\n if (Q_LIKELY(locale.language() != QLocale::C)) {\n auto coreTrans = new QTranslator(this);\n if (Q_LIKELY(coreTrans->load(locale, QStringLiteral(\"skaffari\"), QStringLiteral(\"_\"), QStringLiteral(SKAFFARI_L10NDIR)))) {\n addTranslator(locale, coreTrans);\n } else {\n qCWarning(SK_CORE, \"Failed to load core translation file for language %s from %s.\", qUtf8Printable(locale.bcp47Name()), SKAFFARI_L10NDIR);\n }\n\n auto tmplTrans = new QTranslator(this);\n if (Q_LIKELY(tmplTrans->load(locale, tmplTransFileName, QStringLiteral(\"_\"), tmplTransFilePath))) {\n view->addTranslator(locale, tmplTrans);\n } else {\n qCWarning(SK_CORE, \"Failed to load template translation file for language %s from %s.\", qUtf8Printable(locale.bcp47Name()), qUtf8Printable(tmplTransFilePath));\n }\n } else {\n qCWarning(SK_CORE, \"Invalid language code: %s\", qUtf8Printable(lang));\n }\n }\n }\n \/* End loading translations *\/\n\n\tnew Root(this);\n\tnew Login(this);\n\tnew Logout(this);\n\tnew DomainEditor(this);\n\tnew AccountEditor(this);\n new AdminEditor(this);\n new MyAccount(this);\n new SettingsEditor(this);\n\n auto staticSimple = new StaticSimple(this);\n QString staticPath = tmplBasePath + QLatin1String(\"\/static\");\n staticSimple->setIncludePaths({staticPath});\n\n\tnew Session(this);\n\n new StatusMessage(this);\n\n auto auth = new Authentication(this);\n auto credential = new CredentialPassword(auth);\n credential->setPasswordType(CredentialPassword::Hashed);\n auto store = new AuthStoreSql(this);\n auto realm = new AuthenticationRealm(store, credential, auth);\n store->setParent(realm);\n auth->addRealm(store, credential);\n\n defaultHeaders().setHeader(QStringLiteral(\"X-Frame-Options\"), QStringLiteral(\"DENY\"));\n defaultHeaders().setHeader(QStringLiteral(\"X-Content-Type-Options\"), QStringLiteral(\"nosniff\"));\n defaultHeaders().setHeader(QStringLiteral(\"X-XSS-Protection\"), QStringLiteral(\"1; mode=block\"));\n defaultHeaders().setHeader(QStringLiteral(\"Content-Security-Policy\"), QStringLiteral(\"default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' data:; connect-src 'self';\"));\n defaultHeaders().setHeader(QStringLiteral(\"X-Robots-Tag\"), QStringLiteral(\"none\"));\n\n return true;\n}\n\n\nbool Skaffari::postFork()\n{\n\n initDb();\n\n return true;\n}\n\nbool Skaffari::initDb() const\n{\n const QVariantMap dbconfig = engine()->config(QStringLiteral(\"Database\"));\n const QString dbtype = dbconfig.value(QStringLiteral(\"type\")).toString();\n const QString dbname = dbconfig.value(QStringLiteral(\"name\")).toString();\n const QString dbuser = dbconfig.value(QStringLiteral(\"user\")).toString();\n const QString dbpass = dbconfig.value(QStringLiteral(\"password\")).toString();\n const QString dbhost = dbconfig.value(QStringLiteral(\"host\"), QStringLiteral(\"localhost\")).toString();\n const int dbport = dbconfig.value(QStringLiteral(\"port\"), QStringLiteral(\"3306\")).toInt();\n\n qCDebug(SK_CORE) << \"Establishing database connection\";\n QSqlDatabase db;\n const QString dbConName = Sql::databaseNameThread();\n if (dbtype == QLatin1String(\"QMYSQL\")) {\n if (dbname.isEmpty()) {\n qCCritical(SK_CORE) << \"No database name set!\";\n return false;\n }\n if (dbuser.isEmpty()) {\n qCCritical(SK_CORE) << \"No database user set!\";\n return false;\n }\n if (dbpass.isEmpty()) {\n qCCritical(SK_CORE) << \"No database password set!\";\n return false;\n }\n\n db = QSqlDatabase::addDatabase(dbtype, dbConName);\n if (Q_LIKELY(db.isValid())) {\n db.setDatabaseName(dbname);\n db.setUserName(dbuser);\n db.setPassword(dbpass);\n\n if (dbhost[0] == QLatin1Char('\/')) {\n db.setConnectOptions(QStringLiteral(\"UNIX_SOCKET=%1;MYSQL_OPT_RECONNECT=1;CLIENT_INTERACTIVE=1\").arg(dbhost));\n } else {\n db.setConnectOptions(QStringLiteral(\"MYSQL_OPT_RECONNECT=1;CLIENT_INTERACTIVE=1\"));\n db.setHostName(dbhost);\n db.setPort(dbport);\n }\n } else {\n qCCritical(SK_CORE) << \"Failed to obtain database object.\";\n return false;\n }\n } else {\n qCCritical(SK_CORE) << dbtype << \"is not a supported database type.\";\n return false;\n }\n\n if (Q_UNLIKELY(!db.open())) {\n qCCritical(SK_CORE) << \"Failed to establish database connection:\" << db.lastError().text();\n return false;\n }\n\n return true;\n}\n\n#include \"moc_skaffari.cpp\"\nSkaffari core: use initializer list\/*\n * Skaffari - a mail account administration web interface based on Cutelyst\n * Copyright (C) 2017 Matthias Fehring \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"skaffari.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"objects\/domain.h\"\n#include \"objects\/simpleadmin.h\"\n#include \"objects\/simpledomain.h\"\n#include \"objects\/simpleaccount.h\"\n#include \"objects\/adminaccount.h\"\n#include \"objects\/account.h\"\n#include \"objects\/folder.h\"\n#include \"objects\/helpentry.h\"\n\n#include \"utils\/language.h\"\n#include \"utils\/skaffariconfig.h\"\n\n#include \"..\/common\/config.h\"\n#include \"..\/common\/global.h\"\n#include \"root.h\"\n#include \"authstoresql.h\"\n#include \"login.h\"\n#include \"logout.h\"\n#include \"domaineditor.h\"\n#include \"accounteditor.h\"\n#include \"admineditor.h\"\n#include \"myaccount.h\"\n#include \"settingseditor.h\"\n\nQ_LOGGING_CATEGORY(SK_CORE, \"skaffari.core\")\n\nusing namespace Cutelyst;\n\nbool Skaffari::isInitialized = false;\n\nSkaffari::Skaffari(QObject *parent) : Application(parent)\n{\n}\n\nSkaffari::~Skaffari()\n{\n}\n\nbool Skaffari::init()\n{\n QCoreApplication::setApplicationName(QStringLiteral(\"Skaffari\"));\n QCoreApplication::setApplicationVersion(QStringLiteral(SKAFFARI_VERSION));\n\n qRegisterMetaType(\"quota_size_t\");\n qRegisterMetaType(\"dbid_t\");\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType();\n qRegisterMetaType(\"HelpHash\");\n\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n Grantlee::registerMetaType();\n\n const QString tmplName = QStringLiteral(\"default\");\n const QString tmplBasePath = QStringLiteral(SKAFFARI_TMPLDIR) + QLatin1Char('\/') + tmplName;\n\n if (!isInitialized) {\n QVariantMap tmplConfig;\n QFile tmplConfigFile(tmplBasePath + QLatin1String(\"\/config.json\"));\n if (tmplConfigFile.exists()) {\n qCDebug(SK_CORE, \"Found template configuration file.\");\n if (tmplConfigFile.open(QIODevice::ReadOnly|QIODevice::Text)) {\n QJsonParseError jpe;\n QJsonDocument tmplJsonConfig(QJsonDocument::fromJson(tmplConfigFile.readAll(), &jpe));\n if (jpe.error != QJsonParseError::NoError) {\n qCCritical(SK_CORE, \"Failed to parse template configuration file: %s\", qUtf8Printable(jpe.errorString()));\n return false;\n }\n\n tmplConfig = tmplJsonConfig.object().toVariantMap();\n } else {\n qCCritical(SK_CORE, \"Failed to open template configuration file %s.\", qUtf8Printable(tmplConfigFile.fileName()));\n return false;\n }\n }\n\n qCDebug(SK_CORE) << \"Initializing configuration.\";\n SkaffariConfig::load(engine()->config(QStringLiteral(\"Accounts\")),\n engine()->config(QStringLiteral(\"Admins\")),\n engine()->config(QStringLiteral(\"IMAP\")),\n tmplConfig);\n\n if (SkaffariConfig::imapUser().isEmpty()) {\n qCCritical(SK_CORE) << \"No valid IMAP user defined.\";\n return false;\n }\n\n if (SkaffariConfig::imapPassword().isEmpty()) {\n qCCritical(SK_CORE) << \"No valid IMAP password defined.\";\n return false;\n }\n\n \/\/ initialize DB one time to prevent https:\/\/bugreports.qt.io\/browse\/QTBUG-54872\n if (!initDb()) {\n return false;\n }\n\n SkaffariConfig::loadSettingsFromDB();\n\n isInitialized = true;\n }\n\n QString sitePath = tmplBasePath + QLatin1String(\"\/site\");\n\n auto view = new GrantleeView(this);\n view->setTemplateExtension(QStringLiteral(\".html\"));\n view->setWrapper(QStringLiteral(\"wrapper.html\"));\n\tview->setCache(false);\n view->setIncludePaths({sitePath});\n view->engine()->addDefaultLibrary(QStringLiteral(\"grantlee_i18ntags\"));\n view->engine()->addDefaultLibrary(QStringLiteral(\"grantlee_skaffari\"));\n\n \/* Start loading translations *\/\n const QString tmplTransFileName = QLatin1String(\"tmpl_\") + tmplName;\n const QString tmplTransFilePath = tmplBasePath + QLatin1String(\"\/l10n\");\n\n for (const QString &lang : SKAFFARI_SUPPORTED_LANGS) {\n if (Q_LIKELY(lang != QLatin1String(\"en\"))) {\n qCDebug(SK_CORE, \"Loading translations for language %s.\", qUtf8Printable(lang));\n const QLocale locale(lang);\n if (Q_LIKELY(locale.language() != QLocale::C)) {\n auto coreTrans = new QTranslator(this);\n if (Q_LIKELY(coreTrans->load(locale, QStringLiteral(\"skaffari\"), QStringLiteral(\"_\"), QStringLiteral(SKAFFARI_L10NDIR)))) {\n addTranslator(locale, coreTrans);\n } else {\n qCWarning(SK_CORE, \"Failed to load core translation file for language %s from %s.\", qUtf8Printable(locale.bcp47Name()), SKAFFARI_L10NDIR);\n }\n\n auto tmplTrans = new QTranslator(this);\n if (Q_LIKELY(tmplTrans->load(locale, tmplTransFileName, QStringLiteral(\"_\"), tmplTransFilePath))) {\n view->addTranslator(locale, tmplTrans);\n } else {\n qCWarning(SK_CORE, \"Failed to load template translation file for language %s from %s.\", qUtf8Printable(locale.bcp47Name()), qUtf8Printable(tmplTransFilePath));\n }\n } else {\n qCWarning(SK_CORE, \"Invalid language code: %s\", qUtf8Printable(lang));\n }\n }\n }\n \/* End loading translations *\/\n\n\tnew Root(this);\n\tnew Login(this);\n\tnew Logout(this);\n\tnew DomainEditor(this);\n\tnew AccountEditor(this);\n new AdminEditor(this);\n new MyAccount(this);\n new SettingsEditor(this);\n\n auto staticSimple = new StaticSimple(this);\n QString staticPath = tmplBasePath + QLatin1String(\"\/static\");\n staticSimple->setIncludePaths({staticPath});\n\n\tnew Session(this);\n\n new StatusMessage(this);\n\n auto auth = new Authentication(this);\n auto credential = new CredentialPassword(auth);\n credential->setPasswordType(CredentialPassword::Hashed);\n auto store = new AuthStoreSql(this);\n auto realm = new AuthenticationRealm(store, credential, auth);\n store->setParent(realm);\n auth->addRealm(store, credential);\n\n defaultHeaders().setHeader(QStringLiteral(\"X-Frame-Options\"), QStringLiteral(\"DENY\"));\n defaultHeaders().setHeader(QStringLiteral(\"X-Content-Type-Options\"), QStringLiteral(\"nosniff\"));\n defaultHeaders().setHeader(QStringLiteral(\"X-XSS-Protection\"), QStringLiteral(\"1; mode=block\"));\n defaultHeaders().setHeader(QStringLiteral(\"Content-Security-Policy\"), QStringLiteral(\"default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' data:; connect-src 'self';\"));\n defaultHeaders().setHeader(QStringLiteral(\"X-Robots-Tag\"), QStringLiteral(\"none\"));\n\n return true;\n}\n\n\nbool Skaffari::postFork()\n{\n\n initDb();\n\n return true;\n}\n\nbool Skaffari::initDb() const\n{\n const QVariantMap dbconfig = engine()->config(QStringLiteral(\"Database\"));\n const QString dbtype = dbconfig.value(QStringLiteral(\"type\")).toString();\n const QString dbname = dbconfig.value(QStringLiteral(\"name\")).toString();\n const QString dbuser = dbconfig.value(QStringLiteral(\"user\")).toString();\n const QString dbpass = dbconfig.value(QStringLiteral(\"password\")).toString();\n const QString dbhost = dbconfig.value(QStringLiteral(\"host\"), QStringLiteral(\"localhost\")).toString();\n const int dbport = dbconfig.value(QStringLiteral(\"port\"), QStringLiteral(\"3306\")).toInt();\n\n qCDebug(SK_CORE) << \"Establishing database connection\";\n QSqlDatabase db;\n const QString dbConName = Sql::databaseNameThread();\n if (dbtype == QLatin1String(\"QMYSQL\")) {\n if (dbname.isEmpty()) {\n qCCritical(SK_CORE) << \"No database name set!\";\n return false;\n }\n if (dbuser.isEmpty()) {\n qCCritical(SK_CORE) << \"No database user set!\";\n return false;\n }\n if (dbpass.isEmpty()) {\n qCCritical(SK_CORE) << \"No database password set!\";\n return false;\n }\n\n db = QSqlDatabase::addDatabase(dbtype, dbConName);\n if (Q_LIKELY(db.isValid())) {\n db.setDatabaseName(dbname);\n db.setUserName(dbuser);\n db.setPassword(dbpass);\n\n if (dbhost[0] == QLatin1Char('\/')) {\n db.setConnectOptions(QStringLiteral(\"UNIX_SOCKET=%1;MYSQL_OPT_RECONNECT=1;CLIENT_INTERACTIVE=1\").arg(dbhost));\n } else {\n db.setConnectOptions(QStringLiteral(\"MYSQL_OPT_RECONNECT=1;CLIENT_INTERACTIVE=1\"));\n db.setHostName(dbhost);\n db.setPort(dbport);\n }\n } else {\n qCCritical(SK_CORE) << \"Failed to obtain database object.\";\n return false;\n }\n } else {\n qCCritical(SK_CORE) << dbtype << \"is not a supported database type.\";\n return false;\n }\n\n if (Q_UNLIKELY(!db.open())) {\n qCCritical(SK_CORE) << \"Failed to establish database connection:\" << db.lastError().text();\n return false;\n }\n\n return true;\n}\n\n#include \"moc_skaffari.cpp\"\n<|endoftext|>"} {"text":"\/* Copyright 2013 - 2015 Nikita Batov, Kseniya Gonta and CyberTech Labs Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"analogSensor.h\"\n\n#include \n\n#include \n#include \n\n#include \"i2cCommunicator.h\"\n#include \"configurerHelper.h\"\n\nusing namespace trikControl;\n\nAnalogSensor::AnalogSensor(const QString &port, const trikKernel::Configurer &configurer, I2cCommunicator &communicator)\n\t: mCommunicator(communicator)\n{\n\tmI2cCommandNumber = ConfigurerHelper::configureInt(configurer, mState, port, \"i2cCommandNumber\");\n\tmIRType = configurer.attributeByPort(port, \"type\") == \"sharpGP2\" ? Type::sharpGP2 : Type::analog;\n\t\/\/ We use linear subjection to normalize common analog sensor values:\n\t\/\/ normalizedValue = k * rawValue + b\n\t\/\/ To calculate k and b we need two raw values and two corresponding them normalized values.\n\n\t\/\/ We use hyperbolical subjection to normalize SharpGP2 sensor values:\n\t\/\/ normalizedValue = s \/ (rawValue + l) + n\n\t\/\/ To calculate s, l and n we need sensor readings at three distances.\n\n\tif (mIRType == Type::sharpGP2){\n\t\tCalculateLNS(port, configurer);\t\n\t} else {\n\t\tCalculateKB(port, configurer);\t\n\t}\n\tmState.ready();\n}\n\nAnalogSensor::Status AnalogSensor::status() const\n{\n\treturn DeviceInterface::combine(mCommunicator, mState.status());\n}\n\nint AnalogSensor::read()\n{\n\tauto raw = readRawData();\n\tif (mIRType == Type::sharpGP2){\n\t\treturn mS\/(raw + mL) + mN;\t\n\t}\n\treturn mK * raw + mB;\n}\n\nint AnalogSensor::readRawData()\n{\n\tif (!mState.isReady() || mCommunicator.status() != DeviceInterface::Status::ready) {\n\t\treturn 0;\n\t}\n\n\tQByteArray command(1, '\\0');\n\tcommand[0] = static_cast(mI2cCommandNumber & 0xFF);\n\n\treturn mCommunicator.read(command);\n}\n\nvoid AnalogSensor::CalculateLNS(const QString &port, const trikKernel::Configurer &configurer)\n{\n\tQStringList result;\n\tfor (const QString &str : configurer.attributeByPort(port, \"values\").split(\")\")){\n\t\tresult += str.mid(1).split(\";\");\n\t}\n\tconst int x1 = result[0].toInt();\n\tconst int y1 = result[1].toInt();\n\tconst int x2 = result[2].toInt();\n\tconst int y2 = result[3].toInt();\n\tconst int x3 = result[4].toInt();\n\tconst int y3 = result[5].toInt();\n\n\t\/\/ Counted from equations x1 = mS\/(y1 + mL) + mN, x2 = mS\/(y2 + mL) + mN, x3 = mS\/(y3 + mL) + mN \n\tmL = (-x1 * y1 * y3 - x3 * y2 * y3 + x3 * y1 * y3 + x1 * y1 * y2 + x2 * y2 * y3 - x2 * y1 * y2) \/ \n\t\t\t(x1 * y3 - x2 * y3 + x2 * y1 - x1 * y2 + x3 * y2 - x3 * y1);\n\tmS = (x1 - x2) * (y1 + mL) * (y2 + mL) \/ (y2 - y1);\n\tmN = x1 - mS \/ (y1 + mL);\t\n}\n\nvoid AnalogSensor::CalculateKB(const QString &port, const trikKernel::Configurer &configurer)\n{\n\tconst int rawValue1 = ConfigurerHelper::configureInt(configurer, mState, port, \"rawValue1\");\n\tconst int rawValue2 = ConfigurerHelper::configureInt(configurer, mState, port, \"rawValue2\");\n\tconst int normalizedValue1 = ConfigurerHelper::configureInt(configurer, mState, port, \"normalizedValue1\");\n\tconst int normalizedValue2 = ConfigurerHelper::configureInt(configurer, mState, port, \"normalizedValue2\");\n\tif (rawValue1 == rawValue2) {\n\t\tQLOG_ERROR() << \"Sensor calibration error: rawValue1 = rawValue2!\";\n\t\tmState.fail();\n\t\tmK = 0;\n\t\tmB = 0;\n\t} else {\n\t\tmK = static_cast(normalizedValue2 - normalizedValue1) \/ (rawValue2 - rawValue1);\n\t\tmB = normalizedValue1 - mK * rawValue1;\n\t}\n}\nCorrected the name of sensor type\/* Copyright 2013 - 2015 Nikita Batov, Kseniya Gonta and CyberTech Labs Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"analogSensor.h\"\n\n#include \n\n#include \n#include \n\n#include \"i2cCommunicator.h\"\n#include \"configurerHelper.h\"\n\nusing namespace trikControl;\n\nAnalogSensor::AnalogSensor(const QString &port, const trikKernel::Configurer &configurer, I2cCommunicator &communicator)\n\t: mCommunicator(communicator)\n{\n\tmI2cCommandNumber = ConfigurerHelper::configureInt(configurer, mState, port, \"i2cCommandNumber\");\n\tmIRType = configurer.attributeByPort(port, \"type\") == \"SharpGP2\" ? Type::sharpGP2 : Type::analog;\n\t\/\/ We use linear subjection to normalize common analog sensor values:\n\t\/\/ normalizedValue = k * rawValue + b\n\t\/\/ To calculate k and b we need two raw values and two corresponding them normalized values.\n\n\t\/\/ We use hyperbolical subjection to normalize SharpGP2 sensor values:\n\t\/\/ normalizedValue = s \/ (rawValue + l) + n\n\t\/\/ To calculate s, l and n we need sensor readings at three distances.\n\n\tif (mIRType == Type::sharpGP2){\n\t\tCalculateLNS(port, configurer);\t\n\t} else {\n\t\tCalculateKB(port, configurer);\t\n\t}\n\tmState.ready();\n}\n\nAnalogSensor::Status AnalogSensor::status() const\n{\n\treturn DeviceInterface::combine(mCommunicator, mState.status());\n}\n\nint AnalogSensor::read()\n{\n\tauto raw = readRawData();\n\tif (mIRType == Type::sharpGP2){\n\t\treturn mS\/(raw + mL) + mN;\t\n\t}\n\treturn mK * raw + mB;\n}\n\nint AnalogSensor::readRawData()\n{\n\tif (!mState.isReady() || mCommunicator.status() != DeviceInterface::Status::ready) {\n\t\treturn 0;\n\t}\n\n\tQByteArray command(1, '\\0');\n\tcommand[0] = static_cast(mI2cCommandNumber & 0xFF);\n\n\treturn mCommunicator.read(command);\n}\n\nvoid AnalogSensor::CalculateLNS(const QString &port, const trikKernel::Configurer &configurer)\n{\n\tQStringList result;\n\tfor (const QString &str : configurer.attributeByPort(port, \"values\").split(\")\")){\n\t\tresult += str.mid(1).split(\";\");\n\t}\n\tconst int x1 = result[0].toInt();\n\tconst int y1 = result[1].toInt();\n\tconst int x2 = result[2].toInt();\n\tconst int y2 = result[3].toInt();\n\tconst int x3 = result[4].toInt();\n\tconst int y3 = result[5].toInt();\n\n\t\/\/ Counted from equations x1 = mS\/(y1 + mL) + mN, x2 = mS\/(y2 + mL) + mN, x3 = mS\/(y3 + mL) + mN \n\tmL = (-x1 * y1 * y3 - x3 * y2 * y3 + x3 * y1 * y3 + x1 * y1 * y2 + x2 * y2 * y3 - x2 * y1 * y2) \/ \n\t\t\t(x1 * y3 - x2 * y3 + x2 * y1 - x1 * y2 + x3 * y2 - x3 * y1);\n\tmS = (x1 - x2) * (y1 + mL) * (y2 + mL) \/ (y2 - y1);\n\tmN = x1 - mS \/ (y1 + mL);\t\n}\n\nvoid AnalogSensor::CalculateKB(const QString &port, const trikKernel::Configurer &configurer)\n{\n\tconst int rawValue1 = ConfigurerHelper::configureInt(configurer, mState, port, \"rawValue1\");\n\tconst int rawValue2 = ConfigurerHelper::configureInt(configurer, mState, port, \"rawValue2\");\n\tconst int normalizedValue1 = ConfigurerHelper::configureInt(configurer, mState, port, \"normalizedValue1\");\n\tconst int normalizedValue2 = ConfigurerHelper::configureInt(configurer, mState, port, \"normalizedValue2\");\n\tif (rawValue1 == rawValue2) {\n\t\tQLOG_ERROR() << \"Sensor calibration error: rawValue1 = rawValue2!\";\n\t\tmState.fail();\n\t\tmK = 0;\n\t\tmB = 0;\n\t} else {\n\t\tmK = static_cast(normalizedValue2 - normalizedValue1) \/ (rawValue2 - rawValue1);\n\t\tmB = normalizedValue1 - mK * rawValue1;\n\t}\n}\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ anax\n\/\/\/ An open source C++ entity system.\n\/\/\/\n\/\/\/ Copyright (C) 2013-2014 Miguel Martin (miguel@miguel-martin.com)\n\/\/\/\n\/\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/\/ in the Software without restriction, including without limitation the rights\n\/\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/\/ furnished to do so, subject to the following conditions:\n\/\/\/\n\/\/\/ The above copyright notice and this permission notice shall be included in\n\/\/\/ all copies or substantial portions of the Software.\n\/\/\/\n\/\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/\/ THE SOFTWARE.\n\/\/\/\n\n#include \n\n#include \n\n#include \n\n#include \n\nnamespace anax\n{\n void World::SystemDeleter::operator() (detail::BaseSystem* system) const\n {\n system->m_world = nullptr;\n system->m_entities.clear();\n }\n\n World::World() : \n World(DEFAULT_ENTITY_POOL_SIZE)\n {\n }\n\n World::World(std::size_t entityPoolSize) : \n m_entityIdPool(entityPoolSize),\n m_entityAttributes(entityPoolSize)\n {\n }\n\n void World::removeAllSystems()\n {\n m_systems.clear();\n }\n\n Entity World::createEntity()\n {\n checkForResize(1);\n\n m_entityCache.alive.emplace_back(*this, m_entityIdPool.create());\n return m_entityCache.alive.back();\n }\n\n std::vector World::createEntities(std::size_t amount)\n {\n std::vector temp;\n temp.reserve(amount);\n\n checkForResize(amount);\n\n for(decltype(amount) i = 0; i < amount; ++i)\n {\n Entity e{*this, m_entityIdPool.create()};\n m_entityCache.alive.push_back(e);\n temp.push_back(e);\n }\n\n return temp;\n }\n\n void World::killEntity(Entity& entity)\n {\n \/\/ deactivate the entity\n deactivateEntity(entity);\n\n \/\/ now kill the entity (add it to the killed cache)\n m_entityCache.killed.push_back(entity);\n }\n\n void World::killEntities(std::vector& entities)\n {\n for(auto& i : entities)\n {\n killEntity(i);\n }\n }\n\n void World::activateEntity(Entity& entity)\n {\n ANAX_ASSERT(isValid(entity), \"invalid entity tried to be activated\");\n\n m_entityCache.activated.push_back(entity);\n }\n\n void World::deactivateEntity(Entity& entity)\n {\n ANAX_ASSERT(isValid(entity), \"invalid entity tried to be deactivated\");\n\n m_entityCache.deactivated.push_back(entity);\n }\n\n bool World::isActivated(const Entity& entity) const\n {\n ANAX_ASSERT(isValid(entity), \"invalid entity passed to isActivated\");\n\n return m_entityAttributes.attributes[entity.getId().index].activated;\n }\n\n bool World::isValid(const anax::Entity &entity) const\n {\n return m_entityIdPool.isValid(entity.getId());\n }\n\n void World::refresh()\n {\n \/\/ go through all the activated entities from last call to refresh\n for(auto& entity : m_entityCache.activated)\n {\n auto& attribute = m_entityAttributes.attributes[entity.getId().index]; \n attribute.activated = true;\n\n \/\/ loop through all the systems within the world\n for(auto& i : m_systems)\n {\n auto systemIndex = i.first;\n\n \/\/ if the entity passes the filter the system has and is not already part of the system\n if(i.second->getFilter().doesPassFilter(m_entityAttributes.componentStorage.getComponentTypeList(entity)))\n {\n if(attribute.systems.size() <= systemIndex || !attribute.systems[systemIndex])\n {\n i.second->add(entity); \/\/ add it to the system\n\n detail::EnsureCapacity(attribute.systems, systemIndex); \n attribute.systems[systemIndex] = true;\n }\n }\n \/\/ otherwise if the entity is within the system \n \/\/ and is not relevant to the system anymore...\n \/\/ note: the entity has already failed the filter\n else if(attribute.systems.size() > systemIndex && attribute.systems[systemIndex])\n {\n \/\/ duplicate code (1)\n i.second->remove(entity); \n attribute.systems[systemIndex] = false;\n }\n }\n }\n\n\n \/\/ go through all the deactivated entities from last call to refresh\n for(auto& entity : m_entityCache.deactivated)\n {\n auto& attribute = m_entityAttributes.attributes[entity.getId().index]; \n attribute.activated = false;\n\n \/\/ loop through all the systems within the world\n for(auto& i : m_systems)\n {\n auto systemIndex = i.first;\n if(attribute.systems.size() <= systemIndex) continue;\n\n if(attribute.systems[systemIndex])\n {\n \/\/ duplicate code ...(1)\n i.second->remove(entity); \n attribute.systems[systemIndex] = false;\n }\n }\n }\n\n \/\/ go through all the killed entities from last call to refresh\n for(auto& entity : m_entityCache.killed)\n {\n \/\/ remove the entity from the alive array\n m_entityCache.alive.erase(std::remove(m_entityCache.alive.begin(), m_entityCache.alive.end(), entity), m_entityCache.alive.end()); \n\n \/\/ destroy all the components it has\n m_entityAttributes.componentStorage.removeAllComponents(entity);\n\n \/\/ remove it from the id pool\n m_entityIdPool.remove(entity.getId());\n }\n\n \/\/ clear the temp cache\n m_entityCache.clearTemp();\n }\n\n void World::clear()\n {\n removeAllSystems(); \/\/ remove the systems\n\n \/\/ clear the attributes for all the entities\n m_entityAttributes.clear();\n\n \/\/ clear the entity cache\n m_entityCache.clear();\n\n \/\/ clear the id pool\n m_entityIdPool.clear();\n }\n\n std::size_t World::getEntityCount() const\n {\n return m_entityCache.alive.size();\n }\n\n const World::EntityArray& World::getEntities() const\n {\n return m_entityCache.alive;\n }\n\n void World::checkForResize(std::size_t amountOfEntitiesToBeAllocated)\n {\n auto newSize = getEntityCount() + amountOfEntitiesToBeAllocated;\n if(newSize > m_entityIdPool.getSize())\n {\n resize(newSize);\n }\n }\n\n void World::resize(std::size_t amount)\n {\n m_entityIdPool.resize(amount);\n m_entityAttributes.resize(amount);\n }\n\n void World::addSystem(detail::BaseSystem& system, detail::TypeId systemTypeId)\n {\n ANAX_ASSERT(!system.m_world, \"System is already contained within a World\");\n\n m_systems[systemTypeId].reset(&system);\n\n system.m_world = this;\n system.initialize();\n }\n\n void World::removeSystem(detail::TypeId systemTypeId)\n {\n ANAX_ASSERT(doesSystemExist(systemTypeId), \"System does not exist in world\");\n m_systems.erase(systemTypeId);\n }\n\n bool World::doesSystemExist(detail::TypeId systemTypeId) const\n {\n return m_systems.find(systemTypeId) != m_systems.end();\n }\n\n Entity World::getEntity(std::size_t index)\n {\n return Entity{*this, m_entityIdPool.get(index)};\n }\n}\ninclude algorithm for std::remove\/\/\/\n\/\/\/ anax\n\/\/\/ An open source C++ entity system.\n\/\/\/\n\/\/\/ Copyright (C) 2013-2014 Miguel Martin (miguel@miguel-martin.com)\n\/\/\/\n\/\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/\/ in the Software without restriction, including without limitation the rights\n\/\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/\/ furnished to do so, subject to the following conditions:\n\/\/\/\n\/\/\/ The above copyright notice and this permission notice shall be included in\n\/\/\/ all copies or substantial portions of the Software.\n\/\/\/\n\/\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/\/ THE SOFTWARE.\n\/\/\/\n\n#include \n\n#include \n\n#include \n\n#include \n#include \n\nnamespace anax\n{\n void World::SystemDeleter::operator() (detail::BaseSystem* system) const\n {\n system->m_world = nullptr;\n system->m_entities.clear();\n }\n\n World::World() : \n World(DEFAULT_ENTITY_POOL_SIZE)\n {\n }\n\n World::World(std::size_t entityPoolSize) : \n m_entityIdPool(entityPoolSize),\n m_entityAttributes(entityPoolSize)\n {\n }\n\n void World::removeAllSystems()\n {\n m_systems.clear();\n }\n\n Entity World::createEntity()\n {\n checkForResize(1);\n\n m_entityCache.alive.emplace_back(*this, m_entityIdPool.create());\n return m_entityCache.alive.back();\n }\n\n std::vector World::createEntities(std::size_t amount)\n {\n std::vector temp;\n temp.reserve(amount);\n\n checkForResize(amount);\n\n for(decltype(amount) i = 0; i < amount; ++i)\n {\n Entity e{*this, m_entityIdPool.create()};\n m_entityCache.alive.push_back(e);\n temp.push_back(e);\n }\n\n return temp;\n }\n\n void World::killEntity(Entity& entity)\n {\n \/\/ deactivate the entity\n deactivateEntity(entity);\n\n \/\/ now kill the entity (add it to the killed cache)\n m_entityCache.killed.push_back(entity);\n }\n\n void World::killEntities(std::vector& entities)\n {\n for(auto& i : entities)\n {\n killEntity(i);\n }\n }\n\n void World::activateEntity(Entity& entity)\n {\n ANAX_ASSERT(isValid(entity), \"invalid entity tried to be activated\");\n\n m_entityCache.activated.push_back(entity);\n }\n\n void World::deactivateEntity(Entity& entity)\n {\n ANAX_ASSERT(isValid(entity), \"invalid entity tried to be deactivated\");\n\n m_entityCache.deactivated.push_back(entity);\n }\n\n bool World::isActivated(const Entity& entity) const\n {\n ANAX_ASSERT(isValid(entity), \"invalid entity passed to isActivated\");\n\n return m_entityAttributes.attributes[entity.getId().index].activated;\n }\n\n bool World::isValid(const anax::Entity &entity) const\n {\n return m_entityIdPool.isValid(entity.getId());\n }\n\n void World::refresh()\n {\n \/\/ go through all the activated entities from last call to refresh\n for(auto& entity : m_entityCache.activated)\n {\n auto& attribute = m_entityAttributes.attributes[entity.getId().index]; \n attribute.activated = true;\n\n \/\/ loop through all the systems within the world\n for(auto& i : m_systems)\n {\n auto systemIndex = i.first;\n\n \/\/ if the entity passes the filter the system has and is not already part of the system\n if(i.second->getFilter().doesPassFilter(m_entityAttributes.componentStorage.getComponentTypeList(entity)))\n {\n if(attribute.systems.size() <= systemIndex || !attribute.systems[systemIndex])\n {\n i.second->add(entity); \/\/ add it to the system\n\n detail::EnsureCapacity(attribute.systems, systemIndex); \n attribute.systems[systemIndex] = true;\n }\n }\n \/\/ otherwise if the entity is within the system \n \/\/ and is not relevant to the system anymore...\n \/\/ note: the entity has already failed the filter\n else if(attribute.systems.size() > systemIndex && attribute.systems[systemIndex])\n {\n \/\/ duplicate code (1)\n i.second->remove(entity); \n attribute.systems[systemIndex] = false;\n }\n }\n }\n\n\n \/\/ go through all the deactivated entities from last call to refresh\n for(auto& entity : m_entityCache.deactivated)\n {\n auto& attribute = m_entityAttributes.attributes[entity.getId().index]; \n attribute.activated = false;\n\n \/\/ loop through all the systems within the world\n for(auto& i : m_systems)\n {\n auto systemIndex = i.first;\n if(attribute.systems.size() <= systemIndex) continue;\n\n if(attribute.systems[systemIndex])\n {\n \/\/ duplicate code ...(1)\n i.second->remove(entity); \n attribute.systems[systemIndex] = false;\n }\n }\n }\n\n \/\/ go through all the killed entities from last call to refresh\n for(auto& entity : m_entityCache.killed)\n {\n \/\/ remove the entity from the alive array\n m_entityCache.alive.erase(std::remove(m_entityCache.alive.begin(), m_entityCache.alive.end(), entity), m_entityCache.alive.end()); \n\n \/\/ destroy all the components it has\n m_entityAttributes.componentStorage.removeAllComponents(entity);\n\n \/\/ remove it from the id pool\n m_entityIdPool.remove(entity.getId());\n }\n\n \/\/ clear the temp cache\n m_entityCache.clearTemp();\n }\n\n void World::clear()\n {\n removeAllSystems(); \/\/ remove the systems\n\n \/\/ clear the attributes for all the entities\n m_entityAttributes.clear();\n\n \/\/ clear the entity cache\n m_entityCache.clear();\n\n \/\/ clear the id pool\n m_entityIdPool.clear();\n }\n\n std::size_t World::getEntityCount() const\n {\n return m_entityCache.alive.size();\n }\n\n const World::EntityArray& World::getEntities() const\n {\n return m_entityCache.alive;\n }\n\n void World::checkForResize(std::size_t amountOfEntitiesToBeAllocated)\n {\n auto newSize = getEntityCount() + amountOfEntitiesToBeAllocated;\n if(newSize > m_entityIdPool.getSize())\n {\n resize(newSize);\n }\n }\n\n void World::resize(std::size_t amount)\n {\n m_entityIdPool.resize(amount);\n m_entityAttributes.resize(amount);\n }\n\n void World::addSystem(detail::BaseSystem& system, detail::TypeId systemTypeId)\n {\n ANAX_ASSERT(!system.m_world, \"System is already contained within a World\");\n\n m_systems[systemTypeId].reset(&system);\n\n system.m_world = this;\n system.initialize();\n }\n\n void World::removeSystem(detail::TypeId systemTypeId)\n {\n ANAX_ASSERT(doesSystemExist(systemTypeId), \"System does not exist in world\");\n m_systems.erase(systemTypeId);\n }\n\n bool World::doesSystemExist(detail::TypeId systemTypeId) const\n {\n return m_systems.find(systemTypeId) != m_systems.end();\n }\n\n Entity World::getEntity(std::size_t index)\n {\n return Entity{*this, m_entityIdPool.get(index)};\n }\n}\n<|endoftext|>"} {"text":"#include \"archive.hh\"\n#include \"pool.hh\"\n#include \"remote-store.hh\"\n#include \"serve-protocol.hh\"\n#include \"store-api.hh\"\n#include \"worker-protocol.hh\"\n#include \"ssh.hh\"\n\nnamespace nix {\n\nstatic std::string uriScheme = \"legacy-ssh:\/\/\";\n\nstruct LegacySSHStore : public Store\n{\n struct Connection\n {\n std::unique_ptr sshConn;\n FdSink to;\n FdSource from;\n };\n\n std::string host;\n\n ref> connections;\n\n SSHMaster master;\n\n LegacySSHStore(const string & host, const Params & params)\n : Store(params)\n , host(host)\n , connections(make_ref>(\n std::max(1, std::stoi(get(params, \"max-connections\", \"1\"))),\n [this]() { return openConnection(); },\n [](const ref & r) { return true; }\n ))\n , master(\n host,\n get(params, \"ssh-key\", \"\"),\n \/\/ Use SSH master only if using more than 1 connection.\n connections->capacity() > 1,\n get(params, \"compress\", \"\") == \"true\")\n {\n }\n\n ref openConnection()\n {\n auto conn = make_ref();\n conn->sshConn = master.startCommand(\"nix-store --serve\");\n conn->to = FdSink(conn->sshConn->in.get());\n conn->from = FdSource(conn->sshConn->out.get());\n\n int remoteVersion;\n\n try {\n conn->to << SERVE_MAGIC_1 << SERVE_PROTOCOL_VERSION;\n conn->to.flush();\n\n unsigned int magic = readInt(conn->from);\n if (magic != SERVE_MAGIC_2)\n throw Error(\"protocol mismatch with ‘nix-store --serve’ on ‘%s’\", host);\n remoteVersion = readInt(conn->from);\n if (GET_PROTOCOL_MAJOR(remoteVersion) != 0x200)\n throw Error(\"unsupported ‘nix-store --serve’ protocol version on ‘%s’\", host);\n\n } catch (EndOfFile & e) {\n throw Error(\"cannot connect to ‘%1%’\", host);\n }\n\n return conn;\n };\n\n string getUri() override\n {\n return uriScheme + host;\n }\n\n void queryPathInfoUncached(const Path & path,\n std::function)> success,\n std::function failure) override\n {\n sync2async>(success, failure, [&]() -> std::shared_ptr {\n auto conn(connections->get());\n\n debug(\"querying remote host ‘%s’ for info on ‘%s’\", host, path);\n\n conn->to << cmdQueryPathInfos << PathSet{path};\n conn->to.flush();\n\n auto info = std::make_shared();\n conn->from >> info->path;\n if (info->path.empty()) return nullptr;\n assert(path == info->path);\n\n PathSet references;\n conn->from >> info->deriver;\n info->references = readStorePaths(*this, conn->from);\n readLongLong(conn->from); \/\/ download size\n info->narSize = readLongLong(conn->from);\n\n auto s = readString(conn->from);\n assert(s == \"\");\n\n return info;\n });\n }\n\n void addToStore(const ValidPathInfo & info, const ref & nar,\n bool repair, bool dontCheckSigs,\n std::shared_ptr accessor) override\n {\n debug(\"adding path ‘%s’ to remote host ‘%s’\", info.path, host);\n\n auto conn(connections->get());\n\n conn->to\n << cmdImportPaths\n << 1;\n conn->to(*nar);\n conn->to\n << exportMagic\n << info.path\n << info.references\n << info.deriver\n << 0\n << 0;\n conn->to.flush();\n\n if (readInt(conn->from) != 1)\n throw Error(\"failed to add path ‘%s’ to remote host ‘%s’, info.path, host\");\n\n }\n\n void narFromPath(const Path & path, Sink & sink) override\n {\n auto conn(connections->get());\n\n conn->to << cmdDumpStorePath << path;\n conn->to.flush();\n\n \/* FIXME: inefficient. *\/\n ParseSink parseSink; \/* null sink; just parse the NAR *\/\n TeeSource savedNAR(conn->from);\n parseDump(parseSink, savedNAR);\n sink(*savedNAR.data);\n }\n\n \/* Unsupported methods. *\/\n [[noreturn]] void unsupported()\n {\n throw Error(\"operation not supported on SSH stores\");\n }\n\n PathSet queryAllValidPaths() override { unsupported(); }\n\n void queryReferrers(const Path & path, PathSet & referrers) override\n { unsupported(); }\n\n PathSet queryDerivationOutputs(const Path & path) override\n { unsupported(); }\n\n StringSet queryDerivationOutputNames(const Path & path) override\n { unsupported(); }\n\n Path queryPathFromHashPart(const string & hashPart) override\n { unsupported(); }\n\n Path addToStore(const string & name, const Path & srcPath,\n bool recursive, HashType hashAlgo,\n PathFilter & filter, bool repair) override\n { unsupported(); }\n\n Path addTextToStore(const string & name, const string & s,\n const PathSet & references, bool repair) override\n { unsupported(); }\n\n void buildPaths(const PathSet & paths, BuildMode buildMode) override\n { unsupported(); }\n\n BuildResult buildDerivation(const Path & drvPath, const BasicDerivation & drv,\n BuildMode buildMode) override\n { unsupported(); }\n\n void ensurePath(const Path & path) override\n { unsupported(); }\n\n void addTempRoot(const Path & path) override\n { unsupported(); }\n\n void addIndirectRoot(const Path & path) override\n { unsupported(); }\n\n Roots findRoots() override\n { unsupported(); }\n\n void collectGarbage(const GCOptions & options, GCResults & results) override\n { unsupported(); }\n\n ref getFSAccessor() override\n { unsupported(); }\n\n void addSignatures(const Path & storePath, const StringSet & sigs) override\n { unsupported(); }\n\n bool isTrusted() override\n { return true; }\n\n};\n\nstatic RegisterStoreImplementation regStore([](\n const std::string & uri, const Store::Params & params)\n -> std::shared_ptr\n{\n if (std::string(uri, 0, uriScheme.size()) != uriScheme) return 0;\n return std::make_shared(std::string(uri, uriScheme.size()), params);\n});\n\n}\nFix nix-copy-closure --to#include \"archive.hh\"\n#include \"pool.hh\"\n#include \"remote-store.hh\"\n#include \"serve-protocol.hh\"\n#include \"store-api.hh\"\n#include \"worker-protocol.hh\"\n#include \"ssh.hh\"\n\nnamespace nix {\n\nstatic std::string uriScheme = \"legacy-ssh:\/\/\";\n\nstruct LegacySSHStore : public Store\n{\n struct Connection\n {\n std::unique_ptr sshConn;\n FdSink to;\n FdSource from;\n };\n\n std::string host;\n\n ref> connections;\n\n SSHMaster master;\n\n LegacySSHStore(const string & host, const Params & params)\n : Store(params)\n , host(host)\n , connections(make_ref>(\n std::max(1, std::stoi(get(params, \"max-connections\", \"1\"))),\n [this]() { return openConnection(); },\n [](const ref & r) { return true; }\n ))\n , master(\n host,\n get(params, \"ssh-key\", \"\"),\n \/\/ Use SSH master only if using more than 1 connection.\n connections->capacity() > 1,\n get(params, \"compress\", \"\") == \"true\")\n {\n }\n\n ref openConnection()\n {\n auto conn = make_ref();\n conn->sshConn = master.startCommand(\"nix-store --serve --write\");\n conn->to = FdSink(conn->sshConn->in.get());\n conn->from = FdSource(conn->sshConn->out.get());\n\n int remoteVersion;\n\n try {\n conn->to << SERVE_MAGIC_1 << SERVE_PROTOCOL_VERSION;\n conn->to.flush();\n\n unsigned int magic = readInt(conn->from);\n if (magic != SERVE_MAGIC_2)\n throw Error(\"protocol mismatch with ‘nix-store --serve’ on ‘%s’\", host);\n remoteVersion = readInt(conn->from);\n if (GET_PROTOCOL_MAJOR(remoteVersion) != 0x200)\n throw Error(\"unsupported ‘nix-store --serve’ protocol version on ‘%s’\", host);\n\n } catch (EndOfFile & e) {\n throw Error(\"cannot connect to ‘%1%’\", host);\n }\n\n return conn;\n };\n\n string getUri() override\n {\n return uriScheme + host;\n }\n\n void queryPathInfoUncached(const Path & path,\n std::function)> success,\n std::function failure) override\n {\n sync2async>(success, failure, [&]() -> std::shared_ptr {\n auto conn(connections->get());\n\n debug(\"querying remote host ‘%s’ for info on ‘%s’\", host, path);\n\n conn->to << cmdQueryPathInfos << PathSet{path};\n conn->to.flush();\n\n auto info = std::make_shared();\n conn->from >> info->path;\n if (info->path.empty()) return nullptr;\n assert(path == info->path);\n\n PathSet references;\n conn->from >> info->deriver;\n info->references = readStorePaths(*this, conn->from);\n readLongLong(conn->from); \/\/ download size\n info->narSize = readLongLong(conn->from);\n\n auto s = readString(conn->from);\n assert(s == \"\");\n\n return info;\n });\n }\n\n void addToStore(const ValidPathInfo & info, const ref & nar,\n bool repair, bool dontCheckSigs,\n std::shared_ptr accessor) override\n {\n debug(\"adding path ‘%s’ to remote host ‘%s’\", info.path, host);\n\n auto conn(connections->get());\n\n conn->to\n << cmdImportPaths\n << 1;\n conn->to(*nar);\n conn->to\n << exportMagic\n << info.path\n << info.references\n << info.deriver\n << 0\n << 0;\n conn->to.flush();\n\n if (readInt(conn->from) != 1)\n throw Error(\"failed to add path ‘%s’ to remote host ‘%s’, info.path, host\");\n\n }\n\n void narFromPath(const Path & path, Sink & sink) override\n {\n auto conn(connections->get());\n\n conn->to << cmdDumpStorePath << path;\n conn->to.flush();\n\n \/* FIXME: inefficient. *\/\n ParseSink parseSink; \/* null sink; just parse the NAR *\/\n TeeSource savedNAR(conn->from);\n parseDump(parseSink, savedNAR);\n sink(*savedNAR.data);\n }\n\n \/* Unsupported methods. *\/\n [[noreturn]] void unsupported()\n {\n throw Error(\"operation not supported on SSH stores\");\n }\n\n PathSet queryAllValidPaths() override { unsupported(); }\n\n void queryReferrers(const Path & path, PathSet & referrers) override\n { unsupported(); }\n\n PathSet queryDerivationOutputs(const Path & path) override\n { unsupported(); }\n\n StringSet queryDerivationOutputNames(const Path & path) override\n { unsupported(); }\n\n Path queryPathFromHashPart(const string & hashPart) override\n { unsupported(); }\n\n Path addToStore(const string & name, const Path & srcPath,\n bool recursive, HashType hashAlgo,\n PathFilter & filter, bool repair) override\n { unsupported(); }\n\n Path addTextToStore(const string & name, const string & s,\n const PathSet & references, bool repair) override\n { unsupported(); }\n\n void buildPaths(const PathSet & paths, BuildMode buildMode) override\n { unsupported(); }\n\n BuildResult buildDerivation(const Path & drvPath, const BasicDerivation & drv,\n BuildMode buildMode) override\n { unsupported(); }\n\n void ensurePath(const Path & path) override\n { unsupported(); }\n\n void addTempRoot(const Path & path) override\n { unsupported(); }\n\n void addIndirectRoot(const Path & path) override\n { unsupported(); }\n\n Roots findRoots() override\n { unsupported(); }\n\n void collectGarbage(const GCOptions & options, GCResults & results) override\n { unsupported(); }\n\n ref getFSAccessor() override\n { unsupported(); }\n\n void addSignatures(const Path & storePath, const StringSet & sigs) override\n { unsupported(); }\n\n bool isTrusted() override\n { return true; }\n\n};\n\nstatic RegisterStoreImplementation regStore([](\n const std::string & uri, const Store::Params & params)\n -> std::shared_ptr\n{\n if (std::string(uri, 0, uriScheme.size()) != uriScheme) return 0;\n return std::make_shared(std::string(uri, uriScheme.size()), params);\n});\n\n}\n<|endoftext|>"} {"text":"desktop: avoid loading to-be-recovered documents when recovery is disabled<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013 Spotify AB\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n\/\/ use this file except in compliance with the License. You may obtain a copy of\n\/\/ the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n\/\/ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n\/\/ License for the specific language governing permissions and limitations under\n\/\/ the License.\n\n#include \"annoylib.h\"\n#include \"kissrandom.h\"\n#include \"Python.h\"\n#include \"structmember.h\"\n#include \n#include \n\n\n#if PY_MAJOR_VERSION >= 3\n#define IS_PY3K\n#endif\n\n#ifndef Py_TYPE\n #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)\n#endif\n\n#ifdef IS_PY3K\n #define PyInt_FromLong PyLong_FromLong \n#endif\n\n\ntemplate class AnnoyIndexInterface;\n\n\/\/ annoy python object\ntypedef struct {\n PyObject_HEAD\n int f;\n AnnoyIndexInterface* ptr;\n} py_annoy;\n\n\nstatic PyObject *\npy_an_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {\n py_annoy *self;\n\n self = (py_annoy *)type->tp_alloc(type, 0);\n if (self != NULL) {\n self->f = 0;\n self->ptr = NULL;\n }\n\n return (PyObject *)self;\n}\n\n\nstatic int \npy_an_init(py_annoy *self, PyObject *args, PyObject *kwds) {\n const char *metric;\n\n if (!PyArg_ParseTuple(args, \"is\", &self->f, &metric))\n return -1;\n switch(metric[0]) {\n case 'a':\n self->ptr = new AnnoyIndex(self->f);\n break;\n case 'e':\n self->ptr = new AnnoyIndex(self->f);\n break;\n }\n return 0;\n}\n\n\nstatic void \npy_an_dealloc(py_annoy* self) {\n if (self->ptr) {\n delete self->ptr;\n }\n Py_TYPE(self)->tp_free((PyObject*)self);\n}\n\n\nstatic PyMemberDef py_annoy_members[] = {\n {(char*)\"_f\", T_INT, offsetof(py_annoy, f), 0,\n (char*)\"\"},\n {NULL}\t\/* Sentinel *\/\n};\n\n\nstatic PyObject *\npy_an_load(py_annoy *self, PyObject *args) {\n char* filename;\n bool res = false;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"s\", &filename))\n Py_RETURN_NONE;\n\n res = self->ptr->load(filename);\n\n if (!res) {\n PyErr_SetFromErrno(PyExc_IOError);\n return NULL;\n }\n Py_RETURN_TRUE;\n}\n\n\nstatic PyObject *\npy_an_save(py_annoy *self, PyObject *args) {\n char *filename;\n bool res = false;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"s\", &filename))\n Py_RETURN_NONE;\n\n res = self->ptr->save(filename);\n\n if (!res) {\n PyErr_SetFromErrno(PyExc_IOError);\n return NULL;\n }\n Py_RETURN_TRUE;\n}\n\n\nPyObject*\nget_nns_to_python(const vector& result, const vector& distances, int include_distances) {\n PyObject* l = PyList_New(result.size());\n for (size_t i = 0; i < result.size(); i++)\n PyList_SetItem(l, i, PyInt_FromLong(result[i]));\n if (!include_distances)\n return l;\n\n PyObject* d = PyList_New(distances.size());\n for (size_t i = 0; i < distances.size(); i++)\n PyList_SetItem(d, i, PyFloat_FromDouble(distances[i]));\n\n PyObject* t = PyTuple_New(2);\n PyTuple_SetItem(t, 0, l);\n PyTuple_SetItem(t, 1, d);\n\n return t;\n}\n\n\nstatic PyObject* \npy_an_get_nns_by_item(py_annoy *self, PyObject *args) {\n int32_t item, n, search_k=-1, include_distances=0;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"ii|ii\", &item, &n, &search_k, &include_distances))\n Py_RETURN_NONE;\n\n vector result;\n vector distances;\n self->ptr->get_nns_by_item(item, n, search_k, &result, include_distances ? &distances : NULL);\n\n return get_nns_to_python(result, distances, include_distances);\n}\n\n\nstatic PyObject* \npy_an_get_nns_by_vector(py_annoy *self, PyObject *args) {\n PyObject* v;\n int32_t n, search_k=-1, include_distances=0;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"Oi|ii\", &v, &n, &search_k, &include_distances))\n Py_RETURN_NONE;\n\n vector w(self->f);\n for (int z = 0; z < PyList_Size(v) && z < self->f; z++) {\n PyObject *pf = PyList_GetItem(v,z);\n w[z] = PyFloat_AsDouble(pf);\n }\n\n vector result;\n vector distances;\n self->ptr->get_nns_by_vector(&w[0], n, search_k, &result, include_distances ? &distances : NULL);\n\n return get_nns_to_python(result, distances, include_distances);\n}\n\n\nstatic PyObject* \npy_an_get_item_vector(py_annoy *self, PyObject *args) {\n int32_t item;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"i\", &item))\n Py_RETURN_NONE;\n\n vector v;\n self->ptr->get_item(item, &v);\n PyObject* l = PyList_New(self->f);\n for (int z = 0; z < self->f; z++) {\n PyList_SetItem(l, z, PyFloat_FromDouble(v[z]));\n }\n\n return l;\n}\n\n\nstatic PyObject* \npy_an_add_item(py_annoy *self, PyObject *args) {\n vector w;\n\n PyObject* l;\n int32_t item;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"iO\", &item, &l))\n Py_RETURN_NONE;\n for (int z = 0; z < PyList_Size(l); z++) {\n PyObject *pf = PyList_GetItem(l,z);\n w.push_back(PyFloat_AsDouble(pf));\n }\n self->ptr->add_item(item, &w[0]);\n\n Py_RETURN_NONE;\n}\n\n\nstatic PyObject *\npy_an_build(py_annoy *self, PyObject *args) {\n int q;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"i\", &q))\n Py_RETURN_NONE;\n\n self->ptr->build(q);\n\n Py_RETURN_TRUE;\n}\n\n\nstatic PyObject *\npy_an_unload(py_annoy *self, PyObject *args) {\n if (!self->ptr) \n Py_RETURN_NONE;\n\n self->ptr->unload();\n\n Py_RETURN_TRUE;\n}\n\n\nstatic PyObject *\npy_an_get_distance(py_annoy *self, PyObject *args) {\n int32_t i,j;\n double d=0;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"ii\", &i, &j))\n Py_RETURN_NONE;\n\n d = self->ptr->get_distance(i,j);\n\n return PyFloat_FromDouble(d);\n}\n\n\nstatic PyObject *\npy_an_get_n_items(py_annoy *self, PyObject *args) {\n int32_t n=0;\n bool is_n=false;\n if (!self->ptr) \n Py_RETURN_NONE;\n\n n = self->ptr->get_n_items();\n is_n = true;\n\n if (is_n) return PyInt_FromLong(n);\n Py_RETURN_NONE;\n}\n\n\nstatic PyObject *\npy_an_verbose(py_annoy *self, PyObject *args) {\n int verbose;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"i\", &verbose))\n Py_RETURN_NONE;\n\n self->ptr->verbose((bool)verbose);\n\n Py_RETURN_TRUE;\n}\n\n\nstatic PyMethodDef AnnoyMethods[] = {\n {\"load\",\t(PyCFunction)py_an_load, METH_VARARGS, \"\"},\n {\"save\",\t(PyCFunction)py_an_save, METH_VARARGS, \"\"},\n {\"get_nns_by_item\",(PyCFunction)py_an_get_nns_by_item, METH_VARARGS, \"\"},\n {\"get_nns_by_vector\",(PyCFunction)py_an_get_nns_by_vector, METH_VARARGS, \"\"},\n {\"get_item_vector\",(PyCFunction)py_an_get_item_vector, METH_VARARGS, \"\"},\n {\"add_item\",(PyCFunction)py_an_add_item, METH_VARARGS, \"\"},\n {\"build\",(PyCFunction)py_an_build, METH_VARARGS, \"\"},\n {\"unload\",(PyCFunction)py_an_unload, METH_VARARGS, \"\"},\n {\"get_distance\",(PyCFunction)py_an_get_distance, METH_VARARGS, \"\"},\n {\"get_n_items\",(PyCFunction)py_an_get_n_items, METH_VARARGS, \"\"},\n {\"verbose\",(PyCFunction)py_an_verbose, METH_VARARGS, \"\"},\n {NULL, NULL, 0, NULL}\t\t \/* Sentinel *\/\n};\n\n\nstatic PyTypeObject PyAnnoyType = {\n PyVarObject_HEAD_INIT(NULL, 0)\n \"annoy.Annoy\", \/*tp_name*\/\n sizeof(py_annoy), \/*tp_basicsize*\/\n 0, \/*tp_itemsize*\/\n (destructor)py_an_dealloc, \/*tp_dealloc*\/\n 0, \/*tp_print*\/\n 0, \/*tp_getattr*\/\n 0, \/*tp_setattr*\/\n 0, \/*tp_compare*\/\n 0, \/*tp_repr*\/\n 0, \/*tp_as_number*\/\n 0, \/*tp_as_sequence*\/\n 0, \/*tp_as_mapping*\/\n 0, \/*tp_hash *\/\n 0, \/*tp_call*\/\n 0, \/*tp_str*\/\n 0, \/*tp_getattro*\/\n 0, \/*tp_setattro*\/\n 0, \/*tp_as_buffer*\/\n Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, \/*tp_flags*\/\n \"annoy objects\", \/* tp_doc *\/\n 0, \/* tp_traverse *\/\n 0, \/* tp_clear *\/\n 0, \/* tp_richcompare *\/\n 0, \/* tp_weaklistoffset *\/\n 0, \/* tp_iter *\/\n 0, \/* tp_iternext *\/\n AnnoyMethods, \/* tp_methods *\/\n py_annoy_members, \/* tp_members *\/\n 0, \/* tp_getset *\/\n 0, \/* tp_base *\/\n 0, \/* tp_dict *\/\n 0, \/* tp_descr_get *\/\n 0, \/* tp_descr_set *\/\n 0, \/* tp_dictoffset *\/\n (initproc)py_an_init, \/* tp_init *\/\n 0, \/* tp_alloc *\/\n py_an_new, \/* tp_new *\/\n};\n\nstatic PyMethodDef module_methods[] = {\n {NULL}\t\/* Sentinel *\/\n};\n\n#if PY_MAJOR_VERSION >= 3\n static struct PyModuleDef moduledef = {\n PyModuleDef_HEAD_INIT,\n \"annoylib\", \/* m_name *\/\n \"\", \/* m_doc *\/\n -1, \/* m_size *\/\n module_methods, \/* m_methods *\/\n NULL, \/* m_reload *\/\n NULL, \/* m_traverse *\/\n NULL, \/* m_clear *\/\n NULL, \/* m_free *\/\n };\n#endif\n\nPyObject *create_module(void) {\n PyObject *m;\n\n if (PyType_Ready(&PyAnnoyType) < 0)\n return NULL;\n\n#if PY_MAJOR_VERSION >= 3\n m = PyModule_Create(&moduledef);\n#else\n m = Py_InitModule(\"annoylib\", module_methods);\n#endif\n\n if (m == NULL)\n return NULL;\n\n Py_INCREF(&PyAnnoyType);\n PyModule_AddObject(m, \"Annoy\", (PyObject *)&PyAnnoyType);\n return m;\n}\n\n#if PY_MAJOR_VERSION >= 3\n PyMODINIT_FUNC PyInit_annoylib(void) {\n return create_module(); \/\/ it should return moudule object in py3\n }\n#else\n PyMODINIT_FUNC initannoylib(void) {\n create_module();\n }\n#endif\n\n\n\/\/ vim: tabstop=2 shiftwidth=2\npreallocate vector for add_item\/\/ Copyright (c) 2013 Spotify AB\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n\/\/ use this file except in compliance with the License. You may obtain a copy of\n\/\/ the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n\/\/ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n\/\/ License for the specific language governing permissions and limitations under\n\/\/ the License.\n\n#include \"annoylib.h\"\n#include \"kissrandom.h\"\n#include \"Python.h\"\n#include \"structmember.h\"\n#include \n#include \n\n\n#if PY_MAJOR_VERSION >= 3\n#define IS_PY3K\n#endif\n\n#ifndef Py_TYPE\n #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)\n#endif\n\n#ifdef IS_PY3K\n #define PyInt_FromLong PyLong_FromLong \n#endif\n\n\ntemplate class AnnoyIndexInterface;\n\n\/\/ annoy python object\ntypedef struct {\n PyObject_HEAD\n int f;\n AnnoyIndexInterface* ptr;\n} py_annoy;\n\n\nstatic PyObject *\npy_an_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {\n py_annoy *self;\n\n self = (py_annoy *)type->tp_alloc(type, 0);\n if (self != NULL) {\n self->f = 0;\n self->ptr = NULL;\n }\n\n return (PyObject *)self;\n}\n\n\nstatic int \npy_an_init(py_annoy *self, PyObject *args, PyObject *kwds) {\n const char *metric;\n\n if (!PyArg_ParseTuple(args, \"is\", &self->f, &metric))\n return -1;\n switch(metric[0]) {\n case 'a':\n self->ptr = new AnnoyIndex(self->f);\n break;\n case 'e':\n self->ptr = new AnnoyIndex(self->f);\n break;\n }\n return 0;\n}\n\n\nstatic void \npy_an_dealloc(py_annoy* self) {\n if (self->ptr) {\n delete self->ptr;\n }\n Py_TYPE(self)->tp_free((PyObject*)self);\n}\n\n\nstatic PyMemberDef py_annoy_members[] = {\n {(char*)\"_f\", T_INT, offsetof(py_annoy, f), 0,\n (char*)\"\"},\n {NULL}\t\/* Sentinel *\/\n};\n\n\nstatic PyObject *\npy_an_load(py_annoy *self, PyObject *args) {\n char* filename;\n bool res = false;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"s\", &filename))\n Py_RETURN_NONE;\n\n res = self->ptr->load(filename);\n\n if (!res) {\n PyErr_SetFromErrno(PyExc_IOError);\n return NULL;\n }\n Py_RETURN_TRUE;\n}\n\n\nstatic PyObject *\npy_an_save(py_annoy *self, PyObject *args) {\n char *filename;\n bool res = false;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"s\", &filename))\n Py_RETURN_NONE;\n\n res = self->ptr->save(filename);\n\n if (!res) {\n PyErr_SetFromErrno(PyExc_IOError);\n return NULL;\n }\n Py_RETURN_TRUE;\n}\n\n\nPyObject*\nget_nns_to_python(const vector& result, const vector& distances, int include_distances) {\n PyObject* l = PyList_New(result.size());\n for (size_t i = 0; i < result.size(); i++)\n PyList_SetItem(l, i, PyInt_FromLong(result[i]));\n if (!include_distances)\n return l;\n\n PyObject* d = PyList_New(distances.size());\n for (size_t i = 0; i < distances.size(); i++)\n PyList_SetItem(d, i, PyFloat_FromDouble(distances[i]));\n\n PyObject* t = PyTuple_New(2);\n PyTuple_SetItem(t, 0, l);\n PyTuple_SetItem(t, 1, d);\n\n return t;\n}\n\n\nstatic PyObject* \npy_an_get_nns_by_item(py_annoy *self, PyObject *args) {\n int32_t item, n, search_k=-1, include_distances=0;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"ii|ii\", &item, &n, &search_k, &include_distances))\n Py_RETURN_NONE;\n\n vector result;\n vector distances;\n self->ptr->get_nns_by_item(item, n, search_k, &result, include_distances ? &distances : NULL);\n\n return get_nns_to_python(result, distances, include_distances);\n}\n\n\nstatic PyObject* \npy_an_get_nns_by_vector(py_annoy *self, PyObject *args) {\n PyObject* v;\n int32_t n, search_k=-1, include_distances=0;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"Oi|ii\", &v, &n, &search_k, &include_distances))\n Py_RETURN_NONE;\n\n vector w(self->f);\n for (int z = 0; z < PyList_Size(v) && z < self->f; z++) {\n PyObject *pf = PyList_GetItem(v,z);\n w[z] = PyFloat_AsDouble(pf);\n }\n\n vector result;\n vector distances;\n self->ptr->get_nns_by_vector(&w[0], n, search_k, &result, include_distances ? &distances : NULL);\n\n return get_nns_to_python(result, distances, include_distances);\n}\n\n\nstatic PyObject* \npy_an_get_item_vector(py_annoy *self, PyObject *args) {\n int32_t item;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"i\", &item))\n Py_RETURN_NONE;\n\n vector v;\n self->ptr->get_item(item, &v);\n PyObject* l = PyList_New(self->f);\n for (int z = 0; z < self->f; z++) {\n PyList_SetItem(l, z, PyFloat_FromDouble(v[z]));\n }\n\n return l;\n}\n\n\nstatic PyObject* \npy_an_add_item(py_annoy *self, PyObject *args) {\n PyObject* l;\n int32_t item;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"iO\", &item, &l))\n Py_RETURN_NONE;\n\n vector w(self->f, 0.0);\n for (int z = 0; z < self->f; z++) {\n PyObject *pf = PyList_GetItem(l,z);\n w[z] = PyFloat_AsDouble(pf);\n }\n self->ptr->add_item(item, &w[0]);\n\n Py_RETURN_NONE;\n}\n\n\nstatic PyObject *\npy_an_build(py_annoy *self, PyObject *args) {\n int q;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"i\", &q))\n Py_RETURN_NONE;\n\n self->ptr->build(q);\n\n Py_RETURN_TRUE;\n}\n\n\nstatic PyObject *\npy_an_unload(py_annoy *self, PyObject *args) {\n if (!self->ptr) \n Py_RETURN_NONE;\n\n self->ptr->unload();\n\n Py_RETURN_TRUE;\n}\n\n\nstatic PyObject *\npy_an_get_distance(py_annoy *self, PyObject *args) {\n int32_t i,j;\n double d=0;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"ii\", &i, &j))\n Py_RETURN_NONE;\n\n d = self->ptr->get_distance(i,j);\n\n return PyFloat_FromDouble(d);\n}\n\n\nstatic PyObject *\npy_an_get_n_items(py_annoy *self, PyObject *args) {\n int32_t n=0;\n bool is_n=false;\n if (!self->ptr) \n Py_RETURN_NONE;\n\n n = self->ptr->get_n_items();\n is_n = true;\n\n if (is_n) return PyInt_FromLong(n);\n Py_RETURN_NONE;\n}\n\n\nstatic PyObject *\npy_an_verbose(py_annoy *self, PyObject *args) {\n int verbose;\n if (!self->ptr) \n Py_RETURN_NONE;\n if (!PyArg_ParseTuple(args, \"i\", &verbose))\n Py_RETURN_NONE;\n\n self->ptr->verbose((bool)verbose);\n\n Py_RETURN_TRUE;\n}\n\n\nstatic PyMethodDef AnnoyMethods[] = {\n {\"load\",\t(PyCFunction)py_an_load, METH_VARARGS, \"\"},\n {\"save\",\t(PyCFunction)py_an_save, METH_VARARGS, \"\"},\n {\"get_nns_by_item\",(PyCFunction)py_an_get_nns_by_item, METH_VARARGS, \"\"},\n {\"get_nns_by_vector\",(PyCFunction)py_an_get_nns_by_vector, METH_VARARGS, \"\"},\n {\"get_item_vector\",(PyCFunction)py_an_get_item_vector, METH_VARARGS, \"\"},\n {\"add_item\",(PyCFunction)py_an_add_item, METH_VARARGS, \"\"},\n {\"build\",(PyCFunction)py_an_build, METH_VARARGS, \"\"},\n {\"unload\",(PyCFunction)py_an_unload, METH_VARARGS, \"\"},\n {\"get_distance\",(PyCFunction)py_an_get_distance, METH_VARARGS, \"\"},\n {\"get_n_items\",(PyCFunction)py_an_get_n_items, METH_VARARGS, \"\"},\n {\"verbose\",(PyCFunction)py_an_verbose, METH_VARARGS, \"\"},\n {NULL, NULL, 0, NULL}\t\t \/* Sentinel *\/\n};\n\n\nstatic PyTypeObject PyAnnoyType = {\n PyVarObject_HEAD_INIT(NULL, 0)\n \"annoy.Annoy\", \/*tp_name*\/\n sizeof(py_annoy), \/*tp_basicsize*\/\n 0, \/*tp_itemsize*\/\n (destructor)py_an_dealloc, \/*tp_dealloc*\/\n 0, \/*tp_print*\/\n 0, \/*tp_getattr*\/\n 0, \/*tp_setattr*\/\n 0, \/*tp_compare*\/\n 0, \/*tp_repr*\/\n 0, \/*tp_as_number*\/\n 0, \/*tp_as_sequence*\/\n 0, \/*tp_as_mapping*\/\n 0, \/*tp_hash *\/\n 0, \/*tp_call*\/\n 0, \/*tp_str*\/\n 0, \/*tp_getattro*\/\n 0, \/*tp_setattro*\/\n 0, \/*tp_as_buffer*\/\n Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, \/*tp_flags*\/\n \"annoy objects\", \/* tp_doc *\/\n 0, \/* tp_traverse *\/\n 0, \/* tp_clear *\/\n 0, \/* tp_richcompare *\/\n 0, \/* tp_weaklistoffset *\/\n 0, \/* tp_iter *\/\n 0, \/* tp_iternext *\/\n AnnoyMethods, \/* tp_methods *\/\n py_annoy_members, \/* tp_members *\/\n 0, \/* tp_getset *\/\n 0, \/* tp_base *\/\n 0, \/* tp_dict *\/\n 0, \/* tp_descr_get *\/\n 0, \/* tp_descr_set *\/\n 0, \/* tp_dictoffset *\/\n (initproc)py_an_init, \/* tp_init *\/\n 0, \/* tp_alloc *\/\n py_an_new, \/* tp_new *\/\n};\n\nstatic PyMethodDef module_methods[] = {\n {NULL}\t\/* Sentinel *\/\n};\n\n#if PY_MAJOR_VERSION >= 3\n static struct PyModuleDef moduledef = {\n PyModuleDef_HEAD_INIT,\n \"annoylib\", \/* m_name *\/\n \"\", \/* m_doc *\/\n -1, \/* m_size *\/\n module_methods, \/* m_methods *\/\n NULL, \/* m_reload *\/\n NULL, \/* m_traverse *\/\n NULL, \/* m_clear *\/\n NULL, \/* m_free *\/\n };\n#endif\n\nPyObject *create_module(void) {\n PyObject *m;\n\n if (PyType_Ready(&PyAnnoyType) < 0)\n return NULL;\n\n#if PY_MAJOR_VERSION >= 3\n m = PyModule_Create(&moduledef);\n#else\n m = Py_InitModule(\"annoylib\", module_methods);\n#endif\n\n if (m == NULL)\n return NULL;\n\n Py_INCREF(&PyAnnoyType);\n PyModule_AddObject(m, \"Annoy\", (PyObject *)&PyAnnoyType);\n return m;\n}\n\n#if PY_MAJOR_VERSION >= 3\n PyMODINIT_FUNC PyInit_annoylib(void) {\n return create_module(); \/\/ it should return moudule object in py3\n }\n#else\n PyMODINIT_FUNC initannoylib(void) {\n create_module();\n }\n#endif\n\n\n\/\/ vim: tabstop=2 shiftwidth=2\n<|endoftext|>"} {"text":"#include \"cmdline.h\"\n#include \n#include \n#include \n#include \n#include \"miutils.h\"\n\n\/\/ global object\nExecutableInfo params;\n\nExecutableInfo::ExecutableInfo() \n\t: argCount(0)\n\t, verbose(false) \n\t, miMode(false)\n\t, silent(false)\n\t, stopOnEntry(false)\n{\n\tsetDir(getCurrentDirectory());\n}\n\nvoid ExecutableInfo::clear() {\n\texename.clear();\n\tdir.clear();\n\tfor (int i = 0; i < argCount; i++) {\n\t\targs[i].clear();\n\t}\n\targCount = 0;\n}\n\nExecutableInfo::~ExecutableInfo() {\n\tclear();\n}\n\nbool ExecutableInfo::hasExecutableSpecified() {\n\treturn !exename.empty();\n}\n\nvoid ExecutableInfo::setExecutable(std::wstring exe) {\n\tif (exe.empty()) {\n\t\texename.clear();\n\t\treturn;\n\t}\n\tstd::wstring tmp = unquoteString(exe);\n\texename = relativeToAbsolutePath(tmp);\n}\n\nvoid ExecutableInfo::setDir(std::wstring directory) {\n\tif (directory.empty()) {\n\t\tdir.clear();\n\t\treturn;\n\t}\n\tstd::wstring tmp = unquoteString(directory);\n\tdir = relativeToAbsolutePath(tmp);\n}\n\nvoid ExecutableInfo::addArg(std::wstring param) {\n\tif (argCount >= MAX_PARAM_COUNT) {\n\t\tfprintf(stderr, \"Too many executable file parameters\");\n\t\texit(3);\n\t}\n\targs[argCount++] = param;\n}\n\nvoid ExecutableInfo::dumpParams() {\n\tif (!exename.empty()) {\n\t\twprintf(L\"Executable file: %s\\n\", exename.c_str());\n\t\tif (argCount) {\n\t\t\twprintf(L\"Inferior arguments: \");\n\t\t\tfor (int i = 0; i < argCount; i++) {\n\t\t\t\twprintf(L\"%s \", args[i].c_str());\n\t\t\t}\n\t\t\twprintf(L\"\\n\");\n\t\t}\n\t}\n\tif (!dir.empty())\n\t\twprintf(L\"Directory: %s\\n\", dir.c_str());\n}\n\nenum CmdLineParamType {\n\tNO_PARAMS,\n\tSTRING_PARAM,\n};\n\nstruct CmdLineParamDef;\ntypedef void(*parameterHandler)(CmdLineParamDef * param, const wchar_t * value);\n\nstruct CmdLineParamDef {\n\tconst char * shortName;\n\tconst char * longName;\n\tCmdLineParamType paramType;\n\tconst char * description;\n\tconst char * defValue;\n\tparameterHandler handler;\n\tbool isHelpSection() {\n\t\treturn !shortName && !longName && description;\n\t}\n\tbool isLast() {\n\t\treturn !shortName && !longName && !description;\n\t}\n\n\t\/\/ for normal parameter\n\tCmdLineParamDef(const char * _shortName, const char * _longName, CmdLineParamType _paramType, const char * _description, const char * _defValue, parameterHandler _handler)\n\t\t: shortName(_shortName), longName(_longName), paramType(_paramType), description(_description), defValue(_defValue), handler(_handler) {\n\t}\n\t\/\/ for help section\n\tCmdLineParamDef(const char * _description)\n\t\t: shortName(NULL), longName(NULL), paramType(NO_PARAMS), description(_description), defValue(NULL), handler(NULL) {\n\t}\n\t\/\/ for last item\n\tCmdLineParamDef()\n\t\t: shortName(NULL), longName(NULL), paramType(NO_PARAMS), description(NULL), defValue(NULL), handler(NULL) {\n\t}\n};\n\nvoid dumpParameterHelp();\n\nstatic void showHelp(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tUNREFERENCED_PARAMETER(value);\n\tprintf(\"This is Mago debugger command line interface. Usage:\\n\");\n\tprintf(\" mago-mi [options] [executable-file]\\n\");\n\tprintf(\" mago-mi [options] --args executable-file [inferior-arguments ...]\\n\");\n\tdumpParameterHelp();\n\texit(0);\n}\n\nstatic void showVersion(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tUNREFERENCED_PARAMETER(value);\n\tprintf(\"mago-mi debugger v0.1\\n\");\n\texit(0);\n}\n\nvoid defParamHandler(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tUNREFERENCED_PARAMETER(value);\n\t\/\/ TODO\n}\n\nstatic void handleInterpreter(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tif (wcscmp(value, L\"mi2\")) {\n\t\tfprintf(stderr, \"Only mi2 interpreter is supported\");\n\t\texit(2);\n\t}\n\tparams.miMode = true;\n}\n\nstatic bool argsFound = false;\n\nstatic void handleArgs(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tif (params.hasExecutableSpecified()) {\n\t\tfprintf(stderr, \"Executable file already specified\");\n\t\texit(3);\n\t}\n\tparams.setExecutable(value);\n\targsFound = true;\n}\n\nstatic void handleExec(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tif (params.hasExecutableSpecified()) {\n\t\tfprintf(stderr, \"Executable file already specified\");\n\t\texit(3);\n\t}\n\tparams.setExecutable(std::wstring(value));\n}\n\nstatic void handleDir(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tparams.setDir(value);\n}\n\nstatic void handleVerbose(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tUNREFERENCED_PARAMETER(value);\n\tparams.verbose = true;\n}\n\nstatic void handleSilent(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tUNREFERENCED_PARAMETER(value);\n\tparams.silent = true;\n}\n\nvoid nonParamHandler(const wchar_t * value) {\n\tif (params.exename.empty()) {\n\t\tparams.setExecutable(std::wstring(value));\n\t\treturn;\n\t}\n\tif (!argsFound) {\n\t\tfprintf(stderr, \"Use --args to provide inferior arguments\");\n\t\texit(3);\n\t}\n\tparams.addArg(std::wstring(value));\n}\n\nCmdLineParamDef paramDefs[] = {\n\tCmdLineParamDef(\"Selection of debuggee and its files\"),\n\tCmdLineParamDef(NULL, \"--args\", STRING_PARAM, \"Arguments after executable-file are passed to inferior\", NULL, &handleArgs),\n\tCmdLineParamDef(NULL, \"--exec=EXECFILE\", STRING_PARAM, \"Use EXECFILE as the executable.\", NULL, &handleExec),\n\tCmdLineParamDef(\"Output and user interface control\"),\n\tCmdLineParamDef(NULL, \"--interpreter=mi2\", STRING_PARAM, \"Turn on GDB MI interface mode\", NULL, &handleInterpreter),\n\tCmdLineParamDef(\"Operating modes\"),\n\tCmdLineParamDef(NULL, \"--help\", NO_PARAMS, \"Print this message and then exit\", NULL, &showHelp),\n\tCmdLineParamDef(NULL, \"--version\", NO_PARAMS, \"Print version information and then exit\", NULL, &showVersion),\n\tCmdLineParamDef(\"-v\", NULL, NO_PARAMS, \"Verbose output\", NULL, &handleVerbose),\n\tCmdLineParamDef(NULL, \"--silent\", NO_PARAMS, \"Don't print version info on startup\", NULL, &handleSilent),\n\tCmdLineParamDef(\"Other options\"),\n\tCmdLineParamDef(NULL, \"--cd=DIR\", STRING_PARAM, \"Change current directory to DIR.\", NULL, &handleDir),\n\tCmdLineParamDef()\n};\n\nvoid dumpParameterHelp() {\n\tfor (int i = 0; !paramDefs[i].isLast(); i++) {\n\t\tif (paramDefs[i].isHelpSection()) {\n\t\t\tprintf(\"\\n%s:\\n\\n\", paramDefs[i].description);\n\t\t} else {\n\t\t\tif (paramDefs[i].longName)\n\t\t\t\tprintf(\" %-16s %s\\n\", paramDefs[i].longName, paramDefs[i].description);\n\t\t\tif (paramDefs[i].shortName)\n\t\t\t\tprintf(\" %-16s %s\\n\", paramDefs[i].shortName, paramDefs[i].description);\n\t\t}\n\t}\n}\n\nCmdLineParamDef * findParam(const wchar_t * &name) {\n\tif (name[0] == '-' && name[1] != '-') {\n\t\tfor (int i = 0; !paramDefs[i].isLast(); i++) {\n\t\t\tif (paramDefs[i].isHelpSection())\n\t\t\t\tcontinue;\n\t\t\tif (!paramDefs[i].shortName)\n\t\t\t\tcontinue;\n\t\t\tif (paramDefs[i].shortName[1] == name[1]) {\n\t\t\t\tname += 2;\n\t\t\t\treturn ¶mDefs[i];\n\t\t\t}\n\t\t}\n\t} else if (name[0] == '-' && name[1] == '-') {\n\t\tfor (int i = 0; !paramDefs[i].isLast(); i++) {\n\t\t\tif (paramDefs[i].isHelpSection())\n\t\t\t\tcontinue;\n\t\t\tif (!paramDefs[i].longName)\n\t\t\t\tcontinue;\n\t\t\tint j = 0;\n\t\t\tfor (; name[j] && paramDefs[i].longName[j] && (paramDefs[i].longName[j] != '=') && name[j] == paramDefs[i].longName[j]; j++)\n\t\t\t\t;\n\t\t\tif ((!paramDefs[i].longName[j] || paramDefs[i].longName[j] == '=') && (!name[j] || name[j] == '=')) {\n\t\t\t\tname += j;\n\t\t\t\tif (name[0] == '=')\n\t\t\t\t\tname++;\n\t\t\t\treturn ¶mDefs[i];\n\t\t\t}\n\t\t}\n\t}\n\treturn NULL;\n}\n\nvoid parseCommandLine(int argc, wchar_t *argv[]) {\n\tfor (int i = 1; i < argc; i++) {\n\t\twchar_t * v = argv[i];\n\t\tif (v[0] == '-') {\n\t\t\tconst wchar_t * value = v;\n\t\t\tCmdLineParamDef * param = findParam(value);\n\t\t\tif (!param) {\n\t\t\t\tfwprintf(stderr, L\"Unknown command line parameter %s\", v);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tif (param->paramType != NO_PARAMS) {\n\t\t\t\tif (!value[0]) {\n\t\t\t\t\tif (i == argc - 1) {\n\t\t\t\t\t\tfwprintf(stderr, L\"Value not specified for parameter %s\", v);\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t\tvalue = argv[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (value[0]) {\n\t\t\t\t\tfwprintf(stderr, L\"Value not allowed for parameter %s\", v);\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (param->handler) {\n\t\t\t\tparam->handler(param, value);\n\t\t\t} else {\n\t\t\t\tdefParamHandler(param, value);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tnonParamHandler(v);\n\t\t}\n\t}\n}\ninterpreter options#include \"cmdline.h\"\n#include \n#include \n#include \n#include \n#include \"miutils.h\"\n\n\/\/ global object\nExecutableInfo params;\n\nExecutableInfo::ExecutableInfo() \n\t: argCount(0)\n\t, verbose(false) \n\t, miMode(false)\n\t, silent(false)\n\t, stopOnEntry(false)\n{\n\tsetDir(getCurrentDirectory());\n}\n\nvoid ExecutableInfo::clear() {\n\texename.clear();\n\tdir.clear();\n\tfor (int i = 0; i < argCount; i++) {\n\t\targs[i].clear();\n\t}\n\targCount = 0;\n}\n\nExecutableInfo::~ExecutableInfo() {\n\tclear();\n}\n\nbool ExecutableInfo::hasExecutableSpecified() {\n\treturn !exename.empty();\n}\n\nvoid ExecutableInfo::setExecutable(std::wstring exe) {\n\tif (exe.empty()) {\n\t\texename.clear();\n\t\treturn;\n\t}\n\tstd::wstring tmp = unquoteString(exe);\n\texename = relativeToAbsolutePath(tmp);\n}\n\nvoid ExecutableInfo::setDir(std::wstring directory) {\n\tif (directory.empty()) {\n\t\tdir.clear();\n\t\treturn;\n\t}\n\tstd::wstring tmp = unquoteString(directory);\n\tdir = relativeToAbsolutePath(tmp);\n}\n\nvoid ExecutableInfo::addArg(std::wstring param) {\n\tif (argCount >= MAX_PARAM_COUNT) {\n\t\tfprintf(stderr, \"Too many executable file parameters\");\n\t\texit(3);\n\t}\n\targs[argCount++] = param;\n}\n\nvoid ExecutableInfo::dumpParams() {\n\tif (!exename.empty()) {\n\t\twprintf(L\"Executable file: %s\\n\", exename.c_str());\n\t\tif (argCount) {\n\t\t\twprintf(L\"Inferior arguments: \");\n\t\t\tfor (int i = 0; i < argCount; i++) {\n\t\t\t\twprintf(L\"%s \", args[i].c_str());\n\t\t\t}\n\t\t\twprintf(L\"\\n\");\n\t\t}\n\t}\n\tif (!dir.empty())\n\t\twprintf(L\"Directory: %s\\n\", dir.c_str());\n}\n\nenum CmdLineParamType {\n\tNO_PARAMS,\n\tSTRING_PARAM,\n};\n\nstruct CmdLineParamDef;\ntypedef void(*parameterHandler)(CmdLineParamDef * param, const wchar_t * value);\n\nstruct CmdLineParamDef {\n\tconst char * shortName;\n\tconst char * longName;\n\tCmdLineParamType paramType;\n\tconst char * description;\n\tconst char * defValue;\n\tparameterHandler handler;\n\tbool isHelpSection() {\n\t\treturn !shortName && !longName && description;\n\t}\n\tbool isLast() {\n\t\treturn !shortName && !longName && !description;\n\t}\n\n\t\/\/ for normal parameter\n\tCmdLineParamDef(const char * _shortName, const char * _longName, CmdLineParamType _paramType, const char * _description, const char * _defValue, parameterHandler _handler)\n\t\t: shortName(_shortName), longName(_longName), paramType(_paramType), description(_description), defValue(_defValue), handler(_handler) {\n\t}\n\t\/\/ for help section\n\tCmdLineParamDef(const char * _description)\n\t\t: shortName(NULL), longName(NULL), paramType(NO_PARAMS), description(_description), defValue(NULL), handler(NULL) {\n\t}\n\t\/\/ for last item\n\tCmdLineParamDef()\n\t\t: shortName(NULL), longName(NULL), paramType(NO_PARAMS), description(NULL), defValue(NULL), handler(NULL) {\n\t}\n};\n\nvoid dumpParameterHelp();\n\nstatic void showHelp(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tUNREFERENCED_PARAMETER(value);\n\tprintf(\"This is Mago debugger command line interface. Usage:\\n\");\n\tprintf(\" mago-mi [options] [executable-file]\\n\");\n\tprintf(\" mago-mi [options] --args executable-file [inferior-arguments ...]\\n\");\n\tdumpParameterHelp();\n\texit(0);\n}\n\nstatic void showVersion(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tUNREFERENCED_PARAMETER(value);\n\tprintf(\"mago-mi debugger v0.1\\n\");\n\texit(0);\n}\n\nvoid defParamHandler(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tUNREFERENCED_PARAMETER(value);\n\t\/\/ TODO\n}\n\nstatic void handleInterpreter(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tif (!wcscmp(value, L\"mi2\") || !wcscmp(value, L\"mi\") || !wcscmp(value, L\"mi1\")) {\n\t\tparams.miMode = true;\n\t\treturn;\n\t}\n\tif (!wcscmp(value, L\"console\")) {\n\t\tparams.miMode = false;\n\t\treturn;\n\t}\n\tfprintf(stderr, \"Unknown interpreter is specified\");\n\texit(-3);\n}\n\nstatic bool argsFound = false;\n\nstatic void handleArgs(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tif (params.hasExecutableSpecified()) {\n\t\tfprintf(stderr, \"Executable file already specified\");\n\t\texit(3);\n\t}\n\tparams.setExecutable(value);\n\targsFound = true;\n}\n\nstatic void handleExec(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tif (params.hasExecutableSpecified()) {\n\t\tfprintf(stderr, \"Executable file already specified\");\n\t\texit(3);\n\t}\n\tparams.setExecutable(std::wstring(value));\n}\n\nstatic void handleDir(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tparams.setDir(value);\n}\n\nstatic void handleVerbose(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tUNREFERENCED_PARAMETER(value);\n\tparams.verbose = true;\n}\n\nstatic void handleSilent(CmdLineParamDef * param, const wchar_t * value) {\n\tUNREFERENCED_PARAMETER(param);\n\tUNREFERENCED_PARAMETER(value);\n\tparams.silent = true;\n}\n\nvoid nonParamHandler(const wchar_t * value) {\n\tif (params.exename.empty()) {\n\t\tparams.setExecutable(std::wstring(value));\n\t\treturn;\n\t}\n\tif (!argsFound) {\n\t\tfprintf(stderr, \"Use --args to provide inferior arguments\");\n\t\texit(3);\n\t}\n\tparams.addArg(std::wstring(value));\n}\n\nCmdLineParamDef paramDefs[] = {\n\tCmdLineParamDef(\"Selection of debuggee and its files\"),\n\tCmdLineParamDef(NULL, \"--args\", STRING_PARAM, \"Arguments after executable-file are passed to inferior\", NULL, &handleArgs),\n\tCmdLineParamDef(NULL, \"--exec=EXECFILE\", STRING_PARAM, \"Use EXECFILE as the executable.\", NULL, &handleExec),\n\tCmdLineParamDef(\"Output and user interface control\"),\n\tCmdLineParamDef(NULL, \"--interpreter=mi2\", STRING_PARAM, \"Turn on GDB MI interface mode\", NULL, &handleInterpreter),\n\tCmdLineParamDef(\"Operating modes\"),\n\tCmdLineParamDef(NULL, \"--help\", NO_PARAMS, \"Print this message and then exit\", NULL, &showHelp),\n\tCmdLineParamDef(NULL, \"--version\", NO_PARAMS, \"Print version information and then exit\", NULL, &showVersion),\n\tCmdLineParamDef(\"-v\", NULL, NO_PARAMS, \"Verbose output\", NULL, &handleVerbose),\n\tCmdLineParamDef(NULL, \"--silent\", NO_PARAMS, \"Don't print version info on startup\", NULL, &handleSilent),\n\tCmdLineParamDef(\"Other options\"),\n\tCmdLineParamDef(NULL, \"--cd=DIR\", STRING_PARAM, \"Change current directory to DIR.\", NULL, &handleDir),\n\tCmdLineParamDef()\n};\n\nvoid dumpParameterHelp() {\n\tfor (int i = 0; !paramDefs[i].isLast(); i++) {\n\t\tif (paramDefs[i].isHelpSection()) {\n\t\t\tprintf(\"\\n%s:\\n\\n\", paramDefs[i].description);\n\t\t} else {\n\t\t\tif (paramDefs[i].longName)\n\t\t\t\tprintf(\" %-16s %s\\n\", paramDefs[i].longName, paramDefs[i].description);\n\t\t\tif (paramDefs[i].shortName)\n\t\t\t\tprintf(\" %-16s %s\\n\", paramDefs[i].shortName, paramDefs[i].description);\n\t\t}\n\t}\n}\n\nCmdLineParamDef * findParam(const wchar_t * &name) {\n\tif (name[0] == '-' && name[1] != '-') {\n\t\tfor (int i = 0; !paramDefs[i].isLast(); i++) {\n\t\t\tif (paramDefs[i].isHelpSection())\n\t\t\t\tcontinue;\n\t\t\tif (!paramDefs[i].shortName)\n\t\t\t\tcontinue;\n\t\t\tif (paramDefs[i].shortName[1] == name[1]) {\n\t\t\t\tname += 2;\n\t\t\t\treturn ¶mDefs[i];\n\t\t\t}\n\t\t}\n\t} else if (name[0] == '-' && name[1] == '-') {\n\t\tfor (int i = 0; !paramDefs[i].isLast(); i++) {\n\t\t\tif (paramDefs[i].isHelpSection())\n\t\t\t\tcontinue;\n\t\t\tif (!paramDefs[i].longName)\n\t\t\t\tcontinue;\n\t\t\tint j = 0;\n\t\t\tfor (; name[j] && paramDefs[i].longName[j] && (paramDefs[i].longName[j] != '=') && name[j] == paramDefs[i].longName[j]; j++)\n\t\t\t\t;\n\t\t\tif ((!paramDefs[i].longName[j] || paramDefs[i].longName[j] == '=') && (!name[j] || name[j] == '=')) {\n\t\t\t\tname += j;\n\t\t\t\tif (name[0] == '=')\n\t\t\t\t\tname++;\n\t\t\t\treturn ¶mDefs[i];\n\t\t\t}\n\t\t}\n\t}\n\treturn NULL;\n}\n\nvoid parseCommandLine(int argc, wchar_t *argv[]) {\n\tfor (int i = 1; i < argc; i++) {\n\t\twchar_t * v = argv[i];\n\t\tif (v[0] == '-') {\n\t\t\tconst wchar_t * value = v;\n\t\t\tCmdLineParamDef * param = findParam(value);\n\t\t\tif (!param) {\n\t\t\t\tfwprintf(stderr, L\"Unknown command line parameter %s\", v);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tif (param->paramType != NO_PARAMS) {\n\t\t\t\tif (!value[0]) {\n\t\t\t\t\tif (i == argc - 1) {\n\t\t\t\t\t\tfwprintf(stderr, L\"Value not specified for parameter %s\", v);\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t\tvalue = argv[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (value[0]) {\n\t\t\t\t\tfwprintf(stderr, L\"Value not allowed for parameter %s\", v);\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (param->handler) {\n\t\t\t\tparam->handler(param, value);\n\t\t\t} else {\n\t\t\t\tdefParamHandler(param, value);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tnonParamHandler(v);\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n This file is part of the KOrganizer alarm daemon.\n\n Copyright (c) 2000,2003 Cornelius Schumacher \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n\/\/Added by qt3to4:\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"koeventviewer.h\"\n\n#include \"alarmdialog.h\"\n#include \"alarmdialog.moc\"\n\nAlarmDialog::AlarmDialog( QWidget *parent )\n : KDialog( parent\/*, Qt::WType_TopLevel | Qt::WStyle_Customize | Qt::WStyle_StaysOnTop |\n Qt::WStyle_DialogBorder,*\/ ),\n mSuspendTimer(this)\n{\n QWidget *topBox = new QWidget( this);\n setMainWidget( topBox );\n setCaption( i18n(\"Reminder\") );\n setButtons( Ok | User1 | User2 );\n setDefaultButton( User1 );\n setButtonText( User1, i18n(\"Suspend\") );\n setButtonText( User2, i18n(\"Edit...\") );\n QBoxLayout *topLayout = new QVBoxLayout( topBox );\n topLayout->setSpacing( spacingHint() );\n\n QLabel *label = new QLabel( i18n(\"The following events triggered reminders:\"),\n topBox );\n topLayout->addWidget( label );\n\n mEventViewer = new KOEventViewer( topBox );\n topLayout->addWidget( mEventViewer );\n\n KHBox *suspendBox = new KHBox( topBox );\n suspendBox->setSpacing( spacingHint() );\n topLayout->addWidget( suspendBox );\n\n new QLabel( i18n(\"Suspend duration:\"), suspendBox );\n mSuspendSpin = new QSpinBox( suspendBox );\n mSuspendSpin->setRange( 1, 9999 );\n mSuspendSpin->setValue( 5 ); \/\/ default suspend duration\n\n mSuspendUnit = new KComboBox( suspendBox );\n mSuspendUnit->addItem( i18n(\"minute(s)\") );\n mSuspendUnit->addItem( i18n(\"hour(s)\") );\n mSuspendUnit->addItem( i18n(\"day(s)\") );\n mSuspendUnit->addItem( i18n(\"week(s)\") );\n\n connect( mSuspendSpin, SIGNAL( valueChanged(int) ), this, SLOT( suspendValueChanged() ) );\n connect( mSuspendUnit, SIGNAL( activated(int) ), this, SLOT( suspendUnitChanged() ) );\n connect( mSuspendUnit, SIGNAL( activated(int) ), this, SLOT( suspendUnitChanged() ) );\n\n \/\/ showButton( User2\/*3*\/, false );\n\n setMinimumSize( 300, 200 );\n}\n\nAlarmDialog::~AlarmDialog()\n{\n delete mIncidence;\n}\n\nvoid AlarmDialog::setIncidence( Incidence *incidence )\n{\n mIncidence = incidence->clone();\n mEventViewer->appendIncidence( mIncidence );\n}\n\nvoid AlarmDialog::setRemindAt( QDateTime dt )\n{\n mRemindAt = dt;\n}\n\nvoid AlarmDialog::slotOk()\n{\n accept();\n emit finishedSignal( this );\n}\n\nvoid AlarmDialog::slotUser1()\n{\n if ( !isVisible() )\n return;\n\n int unit=1;\n switch ( mSuspendUnit->currentIndex() ) {\n case 3: \/\/ weeks\n unit *= 7;\n case 2: \/\/ days\n unit *= 24;\n case 1: \/\/ hours\n unit *= 60;\n case 0: \/\/ minutes\n unit *= 60;\n default:\n break;\n }\n\n setTimer( unit * mSuspendSpin->value() );\n accept();\n}\n\nvoid AlarmDialog::setTimer( int seconds )\n{\n connect( &mSuspendTimer, SIGNAL( timeout() ), SLOT( show() ) );\n mSuspendTimer.setSingleShot( true );\n mSuspendTimer.start( 1000 * seconds );\n mRemindAt = QDateTime::currentDateTime();\n mRemindAt = mRemindAt.addSecs( seconds );\n}\n\nvoid AlarmDialog::slotUser2()\n{\n if ( !QDBus::sessionBus().interface()->isServiceRegistered( \"korganizer\" ) ) {\n if ( KToolInvocation::startServiceByDesktopName( \"korganizer\", QString() ) )\n KMessageBox::error( 0, i18n(\"Could not start KOrganizer.\") );\n }\n QDBusInterface korganizer(\"org.kde.korganizer\", \"\/KOrganizer\", \"org.kde.korganizer.KOrganizer\");\n korganizer.call( \"editIncidence\",mIncidence->uid() );\n\n \/\/ get desktop # where korganizer (or kontact) runs\n QString object = QDBus::sessionBus().interface()->isServiceRegistered( \"kontact\" ) ?\n \"kontact-mainwindow_1\" : \"KOrganizer MainWindow\";\n QDBusInterface korganizerObj(\"org.kde.korganizer\", \"\/\"+object);\n QDBusReply reply = korganizerObj.call( \"getWinID\" );\n if ( reply.isValid() ) {\n int window = reply;\n int desktop = KWin::windowInfo( window ).desktop();\n\n if ( KWin::currentDesktop() == desktop ) {\n KWin::iconifyWindow( winId(), false );\n }\n else\n KWin::setCurrentDesktop( desktop );\n\n KWin::activateWindow( KWin::transientFor( window ) );\n }\n}\n\nvoid AlarmDialog::show()\n{\n KDialog::show();\n KWin::setState( winId(), NET::KeepAbove );\n KWin::setOnAllDesktops( winId(), true );\n eventNotification();\n}\n\nvoid AlarmDialog::suspendValueChanged()\n{\n setButtonFocus( User1 );\n}\n\nvoid AlarmDialog::suspendUnitChanged()\n{\n setButtonFocus( User1 );\n setButtonFocus( User2 );\n}\n\nvoid AlarmDialog::eventNotification()\n{\n bool beeped = false;\n Alarm::List alarms = mIncidence->alarms();\n Alarm::List::ConstIterator it;\n for ( it = alarms.begin(); it != alarms.end(); ++it ) {\n Alarm *alarm = *it;\n\/\/ FIXME: Check whether this should be done for all multiple alarms\n if (alarm->type() == Alarm::Procedure) {\n\/\/ FIXME: Add a message box asking whether the procedure should really be executed\n kDebug(5890) << \"Starting program: '\" << alarm->programFile() << \"'\" << endl;\n KProcess proc;\n proc << QFile::encodeName(alarm->programFile());\n proc.start(KProcess::DontCare);\n }\n else if (alarm->type() == Alarm::Audio) {\n beeped = true;\n Phonon::AudioPlayer* player = new Phonon::AudioPlayer( Phonon::NotificationCategory, this );\n player->play( KUrl( QFile::encodeName(alarm->audioFile() ) ) );\n }\n }\n\n if ( !beeped ) {\n KNotification::beep();\n }\n}\n\nvoid AlarmDialog::wakeUp()\n{\n if ( mRemindAt <= QDateTime::currentDateTime() )\n show();\n else\n setTimer( QDateTime::currentDateTime().secsTo( mRemindAt ) );\n}\n\nvoid AlarmDialog::slotSave()\n{\n KConfig *config = KGlobal::config();\n KLockFile::Ptr lock = config->lockFile();\n if ( lock.data()->lock() != KLockFile::LockOK )\n return;\n\n config->setGroup( \"General\" );\n int numReminders = config->readEntry(\"Reminders\", 0);\n config->writeEntry( \"Reminders\", ++numReminders );\n\n config->setGroup( QString(\"Incidence-%1\").arg(numReminders) );\n config->writeEntry( \"UID\", mIncidence->uid() );\n config->writeEntry( \"RemindAt\", mRemindAt );\n config->sync();\n lock.data()->unlock();\n}\n\nminor QString+\"*\" -> QString+'*' change.\/*\n This file is part of the KOrganizer alarm daemon.\n\n Copyright (c) 2000,2003 Cornelius Schumacher \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n\/\/Added by qt3to4:\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"koeventviewer.h\"\n\n#include \"alarmdialog.h\"\n#include \"alarmdialog.moc\"\n\nAlarmDialog::AlarmDialog( QWidget *parent )\n : KDialog( parent\/*, Qt::WType_TopLevel | Qt::WStyle_Customize | Qt::WStyle_StaysOnTop |\n Qt::WStyle_DialogBorder,*\/ ),\n mSuspendTimer(this)\n{\n QWidget *topBox = new QWidget( this);\n setMainWidget( topBox );\n setCaption( i18n(\"Reminder\") );\n setButtons( Ok | User1 | User2 );\n setDefaultButton( User1 );\n setButtonText( User1, i18n(\"Suspend\") );\n setButtonText( User2, i18n(\"Edit...\") );\n QBoxLayout *topLayout = new QVBoxLayout( topBox );\n topLayout->setSpacing( spacingHint() );\n\n QLabel *label = new QLabel( i18n(\"The following events triggered reminders:\"),\n topBox );\n topLayout->addWidget( label );\n\n mEventViewer = new KOEventViewer( topBox );\n topLayout->addWidget( mEventViewer );\n\n KHBox *suspendBox = new KHBox( topBox );\n suspendBox->setSpacing( spacingHint() );\n topLayout->addWidget( suspendBox );\n\n new QLabel( i18n(\"Suspend duration:\"), suspendBox );\n mSuspendSpin = new QSpinBox( suspendBox );\n mSuspendSpin->setRange( 1, 9999 );\n mSuspendSpin->setValue( 5 ); \/\/ default suspend duration\n\n mSuspendUnit = new KComboBox( suspendBox );\n mSuspendUnit->addItem( i18n(\"minute(s)\") );\n mSuspendUnit->addItem( i18n(\"hour(s)\") );\n mSuspendUnit->addItem( i18n(\"day(s)\") );\n mSuspendUnit->addItem( i18n(\"week(s)\") );\n\n connect( mSuspendSpin, SIGNAL( valueChanged(int) ), this, SLOT( suspendValueChanged() ) );\n connect( mSuspendUnit, SIGNAL( activated(int) ), this, SLOT( suspendUnitChanged() ) );\n connect( mSuspendUnit, SIGNAL( activated(int) ), this, SLOT( suspendUnitChanged() ) );\n\n \/\/ showButton( User2\/*3*\/, false );\n\n setMinimumSize( 300, 200 );\n}\n\nAlarmDialog::~AlarmDialog()\n{\n delete mIncidence;\n}\n\nvoid AlarmDialog::setIncidence( Incidence *incidence )\n{\n mIncidence = incidence->clone();\n mEventViewer->appendIncidence( mIncidence );\n}\n\nvoid AlarmDialog::setRemindAt( QDateTime dt )\n{\n mRemindAt = dt;\n}\n\nvoid AlarmDialog::slotOk()\n{\n accept();\n emit finishedSignal( this );\n}\n\nvoid AlarmDialog::slotUser1()\n{\n if ( !isVisible() )\n return;\n\n int unit=1;\n switch ( mSuspendUnit->currentIndex() ) {\n case 3: \/\/ weeks\n unit *= 7;\n case 2: \/\/ days\n unit *= 24;\n case 1: \/\/ hours\n unit *= 60;\n case 0: \/\/ minutes\n unit *= 60;\n default:\n break;\n }\n\n setTimer( unit * mSuspendSpin->value() );\n accept();\n}\n\nvoid AlarmDialog::setTimer( int seconds )\n{\n connect( &mSuspendTimer, SIGNAL( timeout() ), SLOT( show() ) );\n mSuspendTimer.setSingleShot( true );\n mSuspendTimer.start( 1000 * seconds );\n mRemindAt = QDateTime::currentDateTime();\n mRemindAt = mRemindAt.addSecs( seconds );\n}\n\nvoid AlarmDialog::slotUser2()\n{\n if ( !QDBus::sessionBus().interface()->isServiceRegistered( \"korganizer\" ) ) {\n if ( KToolInvocation::startServiceByDesktopName( \"korganizer\", QString() ) )\n KMessageBox::error( 0, i18n(\"Could not start KOrganizer.\") );\n }\n QDBusInterface korganizer(\"org.kde.korganizer\", \"\/KOrganizer\", \"org.kde.korganizer.KOrganizer\");\n korganizer.call( \"editIncidence\",mIncidence->uid() );\n\n \/\/ get desktop # where korganizer (or kontact) runs\n QString object = QDBus::sessionBus().interface()->isServiceRegistered( \"kontact\" ) ?\n \"kontact-mainwindow_1\" : \"KOrganizer MainWindow\";\n QDBusInterface korganizerObj(\"org.kde.korganizer\", '\/'+object);\n QDBusReply reply = korganizerObj.call( \"getWinID\" );\n if ( reply.isValid() ) {\n int window = reply;\n int desktop = KWin::windowInfo( window ).desktop();\n\n if ( KWin::currentDesktop() == desktop ) {\n KWin::iconifyWindow( winId(), false );\n }\n else\n KWin::setCurrentDesktop( desktop );\n\n KWin::activateWindow( KWin::transientFor( window ) );\n }\n}\n\nvoid AlarmDialog::show()\n{\n KDialog::show();\n KWin::setState( winId(), NET::KeepAbove );\n KWin::setOnAllDesktops( winId(), true );\n eventNotification();\n}\n\nvoid AlarmDialog::suspendValueChanged()\n{\n setButtonFocus( User1 );\n}\n\nvoid AlarmDialog::suspendUnitChanged()\n{\n setButtonFocus( User1 );\n setButtonFocus( User2 );\n}\n\nvoid AlarmDialog::eventNotification()\n{\n bool beeped = false;\n Alarm::List alarms = mIncidence->alarms();\n Alarm::List::ConstIterator it;\n for ( it = alarms.begin(); it != alarms.end(); ++it ) {\n Alarm *alarm = *it;\n\/\/ FIXME: Check whether this should be done for all multiple alarms\n if (alarm->type() == Alarm::Procedure) {\n\/\/ FIXME: Add a message box asking whether the procedure should really be executed\n kDebug(5890) << \"Starting program: '\" << alarm->programFile() << \"'\" << endl;\n KProcess proc;\n proc << QFile::encodeName(alarm->programFile());\n proc.start(KProcess::DontCare);\n }\n else if (alarm->type() == Alarm::Audio) {\n beeped = true;\n Phonon::AudioPlayer* player = new Phonon::AudioPlayer( Phonon::NotificationCategory, this );\n player->play( KUrl( QFile::encodeName(alarm->audioFile() ) ) );\n }\n }\n\n if ( !beeped ) {\n KNotification::beep();\n }\n}\n\nvoid AlarmDialog::wakeUp()\n{\n if ( mRemindAt <= QDateTime::currentDateTime() )\n show();\n else\n setTimer( QDateTime::currentDateTime().secsTo( mRemindAt ) );\n}\n\nvoid AlarmDialog::slotSave()\n{\n KConfig *config = KGlobal::config();\n KLockFile::Ptr lock = config->lockFile();\n if ( lock.data()->lock() != KLockFile::LockOK )\n return;\n\n config->setGroup( \"General\" );\n int numReminders = config->readEntry(\"Reminders\", 0);\n config->writeEntry( \"Reminders\", ++numReminders );\n\n config->setGroup( QString(\"Incidence-%1\").arg(numReminders) );\n config->writeEntry( \"UID\", mIncidence->uid() );\n config->writeEntry( \"RemindAt\", mRemindAt );\n config->sync();\n lock.data()->unlock();\n}\n\n<|endoftext|>"} {"text":"#pragma once\n#include \"pch.h\"\n\n\/**\n*sum of squard difference (distance metric)\n*starting from ax,ay in image a and bx,by in image b, with a width and height given\n*indicies out of bounds results in MAX_DOUBLE\n*\/\ndouble ssd(Mat& a, Mat& b, int ax, int ay, int bx, int by, int width, int height){\n\t\/\/check <0 >width >height, els MAX_DOUBLE\n\t\/\/for 0 to height\n\t\t\/\/for 0 to width\n\t\t\t\/\/sum += (a[ay+y][ax+x] - b[by+y][bx+x])^2\n}\n\n\/**\n*result(y,x) is dot product of filter and img centered at y,x\n*\/\nvoid imfilter(Mat& img, Mat& filter, Mat* result){\n\t\/\/TODO:: for each y,x in img, apply dot product of filter and image centered at y,x\n\t\/\/store in result[y][x]\n}\n\n\/**\n*resizes the image to size(img)*ratio, blurs if downsampling\n*result stores new image matrix\n*\/\nvoid imresize(Mat& img, float ratio, Mat* result){\n\n}\n\n\/**\n*singlular vaue decomposition, results are returned in destU, destS, and destV\n*may pass in nil to disregaurd certian results\n*\/\nvoid svd(Mat& a, Mat*destU, Mat*destS, Mat*destV){\n\t\/\/TODO::compute singluar value decomposition of a\n}\n\n\/**\n*uses RANSAC to compute map from a onto b with maximum number of points\n*threadhold is the maximum distance between to valid matches\n*H is the resulting 3x3 projective trasnformation\n*num_matches is the number of points used to compute the homography\n*\/\nvoid findHomographyRANSAC(KeyPoints& a, KeyPoints& b, double threshhold, Mat* H, int* num_matches){\n\n}\n\n\/**\n*helper function for computeHomographyRANSAC\n*computes a homography from a onto b\n*\/\nvoid findHomography(KeyPoints& a, KeyPoints& b, Mat* H){\n\n}\n\n\/**\n*matches the descriptors of a to the descriptors of b\n*returns the indexes of a that match the index of b\n*\/\nvoid match(Descriptors& a, Descriptors& b, vector * indexesA, vector * indexesB){\n\n}\n\n\/**\n*performs harris cornder detections, and returns the key points of the image, and descriptors\n*\/\nvoid harrisCorners(Mat& a, KeyPoints * keyspoints, Descriptors * decriptors){\n\n}\n\n\/**\n*applies H to the plane of a onto the plane of b, returns the new points in result\n*\/\nvoid projectiveTransform(KeyPoints& a, KeyPoints& b, Mat& H, KeyPoints* result){\n\n}removed mat_ops from feature2d.cpp#pragma once\n#include \"pch.h\"\n\n\n\/**\n*uses RANSAC to compute map from a onto b with maximum number of points\n*threadhold is the maximum distance between to valid matches\n*H is the resulting 3x3 projective trasnformation\n*num_matches is the number of points used to compute the homography\n*\/\nvoid findHomographyRANSAC(KeyPoints& a, KeyPoints& b, double threshhold, Mat* H, int* num_matches){\n\n}\n\n\/**\n*helper function for computeHomographyRANSAC\n*computes a homography from a onto b\n*\/\nvoid findHomography(KeyPoints& a, KeyPoints& b, Mat* H){\n\n}\n\n\/**\n*matches the descriptors of a to the descriptors of b\n*returns the indexes of a that match the index of b\n*\/\nvoid match(Descriptors& a, Descriptors& b, vector * indexesA, vector * indexesB){\n\n}\n\n\/**\n*performs harris cornder detections, and returns the key points of the image, and descriptors\n*\/\nvoid harrisCorners(Mat& a, KeyPoints * keyspoints, Descriptors * decriptors){\n\n}\n\n\/**\n*applies H to the plane of a onto the plane of b, returns the new points in result\n*\/\nvoid projectiveTransform(KeyPoints& a, KeyPoints& b, Mat& H, KeyPoints* result){\n\n}<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef GIO_MOUNT_HXX\n#define GIO_MOUNT_HXX\n\n#include \n#include \n\nG_BEGIN_DECLS\n\n#define OOO_TYPE_MOUNT_OPERATION (ooo_mount_operation_get_type ())\n#define OOO_MOUNT_OPERATION(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), OOO_TYPE_MOUNT_OPERATION, OOoMountOperation))\n#define OOO_MOUNT_OPERATION_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), OOO_TYPE_MOUNT_OPERATION, OOoMountOperationClass))\n#define OOO_IS_MOUNT_OPERATION(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), OOO_TYPE_MOUNT_OPERATION))\n#define OOO_IS_MOUNT_OPERATION_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), OOO_TYPE_MOUNT_OPERATION))\n#define OOO_MOUNT_OPERATION_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), OOO_TYPE_MOUNT_OPERATION, OOoMountOperationClass))\n\ntypedef struct OOoMountOperation OOoMountOperation;\ntypedef struct OOoMountOperationClass OOoMountOperationClass;\ntypedef struct OOoMountOperationPrivate OOoMountOperationPrivate;\n\nstruct OOoMountOperation\n{\n GMountOperation parent_instance;\n\n const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment > *pEnv;\n char *m_pPrevUsername;\n char *m_pPrevPassword;\n};\n\nstruct OOoMountOperationClass\n{\n GMountOperationClass parent_class;\n\n \/* Padding for future expansion *\/\n void (*_gtk_reserved1) (void);\n void (*_gtk_reserved2) (void);\n void (*_gtk_reserved3) (void);\n void (*_gtk_reserved4) (void);\n};\n\n\nGType ooo_mount_operation_get_type (void);\nGMountOperation *ooo_mount_operation_new(const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >& rEnv);\n\nG_END_DECLS\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\ndrop typedef, don't need it for C++\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef GIO_MOUNT_HXX\n#define GIO_MOUNT_HXX\n\n#include \n#include \n\nG_BEGIN_DECLS\n\n#define OOO_TYPE_MOUNT_OPERATION (ooo_mount_operation_get_type ())\n#define OOO_MOUNT_OPERATION(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), OOO_TYPE_MOUNT_OPERATION, OOoMountOperation))\n#define OOO_MOUNT_OPERATION_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), OOO_TYPE_MOUNT_OPERATION, OOoMountOperationClass))\n#define OOO_IS_MOUNT_OPERATION(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), OOO_TYPE_MOUNT_OPERATION))\n#define OOO_IS_MOUNT_OPERATION_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), OOO_TYPE_MOUNT_OPERATION))\n#define OOO_MOUNT_OPERATION_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), OOO_TYPE_MOUNT_OPERATION, OOoMountOperationClass))\n\nstruct OOoMountOperation\n{\n GMountOperation parent_instance;\n\n const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment > *pEnv;\n char *m_pPrevUsername;\n char *m_pPrevPassword;\n};\n\nstruct OOoMountOperationClass\n{\n GMountOperationClass parent_class;\n\n \/* Padding for future expansion *\/\n void (*_gtk_reserved1) (void);\n void (*_gtk_reserved2) (void);\n void (*_gtk_reserved3) (void);\n void (*_gtk_reserved4) (void);\n};\n\n\nGType ooo_mount_operation_get_type (void);\nGMountOperation *ooo_mount_operation_new(const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >& rEnv);\n\nG_END_DECLS\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"#include \"BLEUuid.h\"\n\n#include \"BLEDeviceLimits.h\"\n\n#include \"BLEPeripheral.h\"\n\n\/\/#define BLE_PERIPHERAL_DEBUG\n\n#define DEFAULT_DEVICE_NAME \"Arduino\"\n#define DEFAULT_APPEARANCE 0x0000\n\nBLEPeripheral::BLEPeripheral(unsigned char req, unsigned char rdy, unsigned char rst) :\n#ifdef NRF51\n _nRF51822(),\n#else\n _nRF8001(req, rdy, rst),\n#endif\n\n _localName(NULL),\n _manufacturerData(NULL),\n _manufacturerDataLength(0),\n\n _attributes(NULL),\n _numAttributes(0),\n\n _genericAccessService(\"1800\"),\n _deviceNameCharacteristic(\"2a00\", BLERead, 19),\n _appearanceCharacteristic(\"2a01\", BLERead, 2),\n _genericAttributeService(\"1801\"),\n _servicesChangedCharacteristic(\"2a05\", BLEIndicate, 4),\n\n _central(this)\n{\n#ifdef NRF51\n this->_device = &this->_nRF51822;\n#else\n this->_device = &this->_nRF8001;\n#endif\n\n memset(this->_eventHandlers, 0x00, sizeof(this->_eventHandlers));\n\n this->setDeviceName(DEFAULT_DEVICE_NAME);\n this->setAppearance(DEFAULT_APPEARANCE);\n\n this->_device->setEventListener(this);\n}\n\nBLEPeripheral::~BLEPeripheral() {\n if (this->_attributes) {\n free(this->_attributes);\n }\n}\n\nvoid BLEPeripheral::begin() {\n unsigned char advertisementDataType = 0;\n unsigned char scanDataType = 0;\n\n unsigned char advertisementDataLength = 0;\n unsigned char scanDataLength = 0;\n\n unsigned char advertisementData[BLE_ADVERTISEMENT_DATA_MAX_VALUE_LENGTH];\n unsigned char scanData[BLE_SCAN_DATA_MAX_VALUE_LENGTH];\n\n if (this->_advertisedServiceUuid){\n BLEUuid advertisedServiceUuid = BLEUuid(this->_advertisedServiceUuid);\n\n advertisementDataLength = advertisedServiceUuid.length();\n advertisementDataType = (advertisementDataLength > 2) ? 0x06 : 0x02;\n\n memcpy(advertisementData, advertisedServiceUuid.data(), advertisementDataLength);\n } else if (this->_manufacturerData && this->_manufacturerDataLength > 0) {\n advertisementDataLength = this->_manufacturerDataLength;\n\n if (advertisementDataLength > sizeof(advertisementData)) {\n advertisementDataLength = sizeof(advertisementData);\n }\n\n advertisementDataType = 0xff;\n\n memcpy(advertisementData, this->_manufacturerData, advertisementDataLength);\n }\n\n if (this->_localName){\n unsigned char localNameLength = strlen(this->_localName);\n scanDataLength = localNameLength;\n\n if (scanDataLength > sizeof(scanData)) {\n scanDataLength = sizeof(scanData);\n }\n\n scanDataType = (localNameLength > scanDataLength) ? 0x08 : 0x09;\n\n memcpy(scanData, this->_localName, scanDataLength);\n }\n\n for (int i = 0; i < this->_numAttributes; i++) {\n BLEAttribute* attribute = this->_attributes[i];\n if (attribute->type() == BLETypeCharacteristic) {\n BLECharacteristic* characteristic = (BLECharacteristic*)attribute;\n\n characteristic->setValueChangeListener(*this);\n }\n }\n\n this->_device->begin(advertisementDataType, advertisementDataLength, advertisementData, scanDataType, scanDataLength, scanData, this->_attributes, this->_numAttributes);\n this->_device->requestAddress();\n}\n\nvoid BLEPeripheral::poll() {\n this->_device->poll();\n}\n\nvoid BLEPeripheral::setAdvertisedServiceUuid(const char* advertisedServiceUuid) {\n this->_advertisedServiceUuid = advertisedServiceUuid;\n}\n\nvoid BLEPeripheral::setManufacturerData(const unsigned char manufacturerData[], unsigned char manufacturerDataLength) {\n this->_manufacturerData = manufacturerData;\n this->_manufacturerDataLength = manufacturerDataLength;\n}\n\nvoid BLEPeripheral::setLocalName(const char* localName) {\n this->_localName = localName;\n}\n\nvoid BLEPeripheral::setDeviceName(const char* deviceName) {\n this->_deviceNameCharacteristic.setValue(deviceName);\n}\n\nvoid BLEPeripheral::setAppearance(unsigned short appearance) {\n this->_appearanceCharacteristic.setValue((unsigned char *)&appearance, sizeof(appearance));\n}\n\nvoid BLEPeripheral::addAttribute(BLEAttribute& attribute) {\n if (this->_attributes == NULL) {\n this->_attributes = (BLEAttribute**)malloc(BLEAttribute::numAttributes() * sizeof(BLEAttribute*));\n\n this->_attributes[0] = &this->_genericAccessService;\n this->_attributes[1] = &this->_deviceNameCharacteristic;\n this->_attributes[2] = &this->_appearanceCharacteristic;\n\n this->_attributes[3] = &this->_genericAttributeService;\n this->_attributes[4] = &this->_servicesChangedCharacteristic;\n\n this->_numAttributes = 5;\n }\n\n this->_attributes[this->_numAttributes] = &attribute;\n this->_numAttributes++;\n}\n\nvoid BLEPeripheral::disconnect() {\n this->_device->disconnect();\n}\n\nBLECentral BLEPeripheral::central() {\n this->poll();\n\n return this->_central;\n}\n\nbool BLEPeripheral::connected() {\n this->poll();\n\n return this->_central;\n}\n\nvoid BLEPeripheral::setEventHandler(BLEPeripheralEvent event, BLEPeripheralEventHandler eventHandler) {\n if (event < sizeof(this->_eventHandlers)) {\n this->_eventHandlers[event] = eventHandler;\n }\n}\n\nbool BLEPeripheral::characteristicValueChanged(BLECharacteristic& characteristic) {\n this->_device->updateCharacteristicValue(characteristic);\n}\n\nbool BLEPeripheral::canNotifyCharacteristic(BLECharacteristic& characteristic) {\n this->_device->canNotifyCharacteristic(characteristic);\n}\n\nbool BLEPeripheral::canIndicateCharacteristic(BLECharacteristic& characteristic) {\n this->_device->canIndicateCharacteristic(characteristic);\n}\n\nvoid BLEPeripheral::BLEDeviceConnected(BLEDevice& device, const unsigned char* address) {\n this->_central.setAddress(address);\n\n#ifdef BLE_PERIPHERAL_DEBUG\n Serial.print(F(\"Peripheral connected to central: \"));\n Serial.println(this->_central.address());\n#endif\n\n BLEPeripheralEventHandler eventHandler = this->_eventHandlers[BLEConnected];\n if (eventHandler) {\n eventHandler(this->_central);\n }\n}\n\nvoid BLEPeripheral::BLEDeviceDisconnected(BLEDevice& device) {\n#ifdef BLE_PERIPHERAL_DEBUG\n Serial.print(F(\"Peripheral disconnected from central: \"));\n Serial.println(this->_central.address());\n#endif\n\n BLEPeripheralEventHandler eventHandler = this->_eventHandlers[BLEDisconnected];\n if (eventHandler) {\n eventHandler(this->_central);\n }\n\n this->_central.clearAddress();\n}\n\nvoid BLEPeripheral::BLEDeviceCharacteristicValueChanged(BLEDevice& device, BLECharacteristic& characteristic, const unsigned char* value, unsigned char valueLength) {\n characteristic.setValue(this->_central, value, valueLength);\n}\n\nvoid BLEPeripheral::BLEDeviceCharacteristicSubscribedChanged(BLEDevice& device, BLECharacteristic& characteristic, bool subscribed) {\n characteristic.setSubscribed(this->_central, subscribed);\n}\n\nvoid BLEPeripheral::BLEDeviceAddressReceived(BLEDevice& device, const unsigned char* address) {\n#ifdef BLE_PERIPHERAL_DEBUG\n char addressStr[18];\n\n sprintf(addressStr, \"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\",\n address[5],\n address[4],\n address[3],\n address[2],\n address[1],\n address[0]);\n\n Serial.print(F(\"Peripheral address: \"));\n Serial.println(addressStr);\n#endif\n}\n\nvoid BLEPeripheral::BLEDeviceTemperatureReceived(BLEDevice& device, float temperature) {\n}\n\nvoid BLEPeripheral::BLEDeviceBatteryLevelReceived(BLEDevice& device, float batteryLevel) {\n}\n- missing returns#include \"BLEUuid.h\"\n\n#include \"BLEDeviceLimits.h\"\n\n#include \"BLEPeripheral.h\"\n\n\/\/#define BLE_PERIPHERAL_DEBUG\n\n#define DEFAULT_DEVICE_NAME \"Arduino\"\n#define DEFAULT_APPEARANCE 0x0000\n\nBLEPeripheral::BLEPeripheral(unsigned char req, unsigned char rdy, unsigned char rst) :\n#ifdef NRF51\n _nRF51822(),\n#else\n _nRF8001(req, rdy, rst),\n#endif\n\n _localName(NULL),\n _manufacturerData(NULL),\n _manufacturerDataLength(0),\n\n _attributes(NULL),\n _numAttributes(0),\n\n _genericAccessService(\"1800\"),\n _deviceNameCharacteristic(\"2a00\", BLERead, 19),\n _appearanceCharacteristic(\"2a01\", BLERead, 2),\n _genericAttributeService(\"1801\"),\n _servicesChangedCharacteristic(\"2a05\", BLEIndicate, 4),\n\n _central(this)\n{\n#ifdef NRF51\n this->_device = &this->_nRF51822;\n#else\n this->_device = &this->_nRF8001;\n#endif\n\n memset(this->_eventHandlers, 0x00, sizeof(this->_eventHandlers));\n\n this->setDeviceName(DEFAULT_DEVICE_NAME);\n this->setAppearance(DEFAULT_APPEARANCE);\n\n this->_device->setEventListener(this);\n}\n\nBLEPeripheral::~BLEPeripheral() {\n if (this->_attributes) {\n free(this->_attributes);\n }\n}\n\nvoid BLEPeripheral::begin() {\n unsigned char advertisementDataType = 0;\n unsigned char scanDataType = 0;\n\n unsigned char advertisementDataLength = 0;\n unsigned char scanDataLength = 0;\n\n unsigned char advertisementData[BLE_ADVERTISEMENT_DATA_MAX_VALUE_LENGTH];\n unsigned char scanData[BLE_SCAN_DATA_MAX_VALUE_LENGTH];\n\n if (this->_advertisedServiceUuid){\n BLEUuid advertisedServiceUuid = BLEUuid(this->_advertisedServiceUuid);\n\n advertisementDataLength = advertisedServiceUuid.length();\n advertisementDataType = (advertisementDataLength > 2) ? 0x06 : 0x02;\n\n memcpy(advertisementData, advertisedServiceUuid.data(), advertisementDataLength);\n } else if (this->_manufacturerData && this->_manufacturerDataLength > 0) {\n advertisementDataLength = this->_manufacturerDataLength;\n\n if (advertisementDataLength > sizeof(advertisementData)) {\n advertisementDataLength = sizeof(advertisementData);\n }\n\n advertisementDataType = 0xff;\n\n memcpy(advertisementData, this->_manufacturerData, advertisementDataLength);\n }\n\n if (this->_localName){\n unsigned char localNameLength = strlen(this->_localName);\n scanDataLength = localNameLength;\n\n if (scanDataLength > sizeof(scanData)) {\n scanDataLength = sizeof(scanData);\n }\n\n scanDataType = (localNameLength > scanDataLength) ? 0x08 : 0x09;\n\n memcpy(scanData, this->_localName, scanDataLength);\n }\n\n for (int i = 0; i < this->_numAttributes; i++) {\n BLEAttribute* attribute = this->_attributes[i];\n if (attribute->type() == BLETypeCharacteristic) {\n BLECharacteristic* characteristic = (BLECharacteristic*)attribute;\n\n characteristic->setValueChangeListener(*this);\n }\n }\n\n this->_device->begin(advertisementDataType, advertisementDataLength, advertisementData, scanDataType, scanDataLength, scanData, this->_attributes, this->_numAttributes);\n this->_device->requestAddress();\n}\n\nvoid BLEPeripheral::poll() {\n this->_device->poll();\n}\n\nvoid BLEPeripheral::setAdvertisedServiceUuid(const char* advertisedServiceUuid) {\n this->_advertisedServiceUuid = advertisedServiceUuid;\n}\n\nvoid BLEPeripheral::setManufacturerData(const unsigned char manufacturerData[], unsigned char manufacturerDataLength) {\n this->_manufacturerData = manufacturerData;\n this->_manufacturerDataLength = manufacturerDataLength;\n}\n\nvoid BLEPeripheral::setLocalName(const char* localName) {\n this->_localName = localName;\n}\n\nvoid BLEPeripheral::setDeviceName(const char* deviceName) {\n this->_deviceNameCharacteristic.setValue(deviceName);\n}\n\nvoid BLEPeripheral::setAppearance(unsigned short appearance) {\n this->_appearanceCharacteristic.setValue((unsigned char *)&appearance, sizeof(appearance));\n}\n\nvoid BLEPeripheral::addAttribute(BLEAttribute& attribute) {\n if (this->_attributes == NULL) {\n this->_attributes = (BLEAttribute**)malloc(BLEAttribute::numAttributes() * sizeof(BLEAttribute*));\n\n this->_attributes[0] = &this->_genericAccessService;\n this->_attributes[1] = &this->_deviceNameCharacteristic;\n this->_attributes[2] = &this->_appearanceCharacteristic;\n\n this->_attributes[3] = &this->_genericAttributeService;\n this->_attributes[4] = &this->_servicesChangedCharacteristic;\n\n this->_numAttributes = 5;\n }\n\n this->_attributes[this->_numAttributes] = &attribute;\n this->_numAttributes++;\n}\n\nvoid BLEPeripheral::disconnect() {\n this->_device->disconnect();\n}\n\nBLECentral BLEPeripheral::central() {\n this->poll();\n\n return this->_central;\n}\n\nbool BLEPeripheral::connected() {\n this->poll();\n\n return this->_central;\n}\n\nvoid BLEPeripheral::setEventHandler(BLEPeripheralEvent event, BLEPeripheralEventHandler eventHandler) {\n if (event < sizeof(this->_eventHandlers)) {\n this->_eventHandlers[event] = eventHandler;\n }\n}\n\nbool BLEPeripheral::characteristicValueChanged(BLECharacteristic& characteristic) {\n return this->_device->updateCharacteristicValue(characteristic);\n}\n\nbool BLEPeripheral::canNotifyCharacteristic(BLECharacteristic& characteristic) {\n return this->_device->canNotifyCharacteristic(characteristic);\n}\n\nbool BLEPeripheral::canIndicateCharacteristic(BLECharacteristic& characteristic) {\n return this->_device->canIndicateCharacteristic(characteristic);\n}\n\nvoid BLEPeripheral::BLEDeviceConnected(BLEDevice& device, const unsigned char* address) {\n this->_central.setAddress(address);\n\n#ifdef BLE_PERIPHERAL_DEBUG\n Serial.print(F(\"Peripheral connected to central: \"));\n Serial.println(this->_central.address());\n#endif\n\n BLEPeripheralEventHandler eventHandler = this->_eventHandlers[BLEConnected];\n if (eventHandler) {\n eventHandler(this->_central);\n }\n}\n\nvoid BLEPeripheral::BLEDeviceDisconnected(BLEDevice& device) {\n#ifdef BLE_PERIPHERAL_DEBUG\n Serial.print(F(\"Peripheral disconnected from central: \"));\n Serial.println(this->_central.address());\n#endif\n\n BLEPeripheralEventHandler eventHandler = this->_eventHandlers[BLEDisconnected];\n if (eventHandler) {\n eventHandler(this->_central);\n }\n\n this->_central.clearAddress();\n}\n\nvoid BLEPeripheral::BLEDeviceCharacteristicValueChanged(BLEDevice& device, BLECharacteristic& characteristic, const unsigned char* value, unsigned char valueLength) {\n characteristic.setValue(this->_central, value, valueLength);\n}\n\nvoid BLEPeripheral::BLEDeviceCharacteristicSubscribedChanged(BLEDevice& device, BLECharacteristic& characteristic, bool subscribed) {\n characteristic.setSubscribed(this->_central, subscribed);\n}\n\nvoid BLEPeripheral::BLEDeviceAddressReceived(BLEDevice& device, const unsigned char* address) {\n#ifdef BLE_PERIPHERAL_DEBUG\n char addressStr[18];\n\n sprintf(addressStr, \"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\",\n address[5],\n address[4],\n address[3],\n address[2],\n address[1],\n address[0]);\n\n Serial.print(F(\"Peripheral address: \"));\n Serial.println(addressStr);\n#endif\n}\n\nvoid BLEPeripheral::BLEDeviceTemperatureReceived(BLEDevice& device, float temperature) {\n}\n\nvoid BLEPeripheral::BLEDeviceBatteryLevelReceived(BLEDevice& device, float batteryLevel) {\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#ifdef USE_MONT_FP\n#include \n#endif\n#include \n\nnamespace mcl { namespace fp {\n\n#ifdef USE_MONT_FP\nFpGenerator *Op::createFpGenerator()\n{\n\treturn new FpGenerator();\n}\nvoid Op::destroyFpGenerator(FpGenerator *fg)\n{\n\tdelete fg;\n}\n#else\nFpGenerator *Op::createFpGenerator()\n{\n\treturn 0;\n}\nvoid Op::destroyFpGenerator(FpGenerator *)\n{\n}\n#endif\n\ninline const char *verifyStr(bool *isMinus, int *base, const std::string& str)\n{\n\tconst char *p = str.c_str();\n\tif (*p == '-') {\n\t\t*isMinus = true;\n\t\tp++;\n\t} else {\n\t\t*isMinus = false;\n\t}\n\tif (p[0] == '0') {\n\t\tif (p[1] == 'x') {\n\t\t\tif (*base != 0 && *base != 16) {\n\t\t\t\tthrow cybozu::Exception(\"fp:verifyStr:bad base\") << *base << str;\n\t\t\t}\n\t\t\t*base = 16;\n\t\t\tp += 2;\n\t\t} else if (p[1] == 'b') {\n\t\t\tif (*base != 0 && *base != 2) {\n\t\t\t\tthrow cybozu::Exception(\"fp:verifyStr:bad base\") << *base << str;\n\t\t\t}\n\t\t\t*base = 2;\n\t\t\tp += 2;\n\t\t}\n\t}\n\tif (*base == 0) *base = 10;\n\tif (*p == '\\0') throw cybozu::Exception(\"fp:verifyStr:str is empty\");\n\treturn p;\n}\n\nbool strToMpzArray(size_t *pBitSize, Unit *y, size_t maxBitSize, mpz_class& x, const std::string& str, int base)\n{\n\tbool isMinus;\n\tconst char *p = verifyStr(&isMinus, &base, str);\n\tif (!Gmp::setStr(x, p, base)) {\n\t\tthrow cybozu::Exception(\"fp:strToMpzArray:bad format\") << str;\n\t}\n\tconst size_t bitSize = Gmp::getBitSize(x);\n\tif (bitSize > maxBitSize) throw cybozu::Exception(\"fp:strToMpzArray:too large str\") << str << bitSize << maxBitSize;\n\tif (pBitSize) *pBitSize = bitSize;\n\tGmp::getArray(y, (maxBitSize + UnitBitSize - 1) \/ UnitBitSize, x);\n\treturn isMinus;\n}\n\ntemplate\nstruct OpeFunc {\n\tstatic const size_t N = (bitSize + UnitBitSize - 1) \/ UnitBitSize;\n\tstatic inline void set_mpz_t(mpz_t& z, const Unit* p, int n = (int)N)\n\t{\n\t\tz->_mp_alloc = n;\n\t\tz->_mp_size = getNonZeroArraySize(p, n);\n\t\tz->_mp_d = (mp_limb_t*)const_cast(p);\n\t}\n\tstatic inline void set_zero(mpz_t& z, Unit *p, size_t n)\n\t{\n\t\tz->_mp_alloc = (int)n;\n\t\tz->_mp_size = 0;\n\t\tz->_mp_d = (mp_limb_t*)p;\n\t}\n\tstatic inline void clearC(Unit *x)\n\t{\n\t\tclearArray(x, 0, N);\n\t}\n\tstatic inline void copyC(Unit *y, const Unit *x)\n\t{\n\t\tcopyArray(y, x, N);\n\t}\n\tstatic inline void addC(Unit *z, const Unit *x, const Unit *y, const Unit *p)\n\t{\n\t\tUnit ret[N + 2]; \/\/ not N + 1\n\t\tmpz_t mz, mx, my, mp;\n\t\tset_zero(mz, ret, N + 2);\n\t\tset_mpz_t(mx, x);\n\t\tset_mpz_t(my, y);\n\t\tset_mpz_t(mp, p);\n\t\tmpz_add(mz, mx, my);\n\t\tif (mpz_cmp(mz, mp) >= 0) {\n\t\t\tmpz_sub(mz, mz, mp);\n\t\t}\n\t\tGmp::getArray(z, N, mz);\n\t}\n\tstatic inline void subC(Unit *z, const Unit *x, const Unit *y, const Unit *p)\n\t{\n\t\tUnit ret[N + 1];\n\t\tmpz_t mz, mx, my;\n\t\tset_zero(mz, ret, N + 1);\n\t\tset_mpz_t(mx, x);\n\t\tset_mpz_t(my, y);\n\t\tmpz_sub(mz, mx, my);\n\t\tif (mpz_sgn(mz) < 0) {\n\t\t\tmpz_t mp;\n\t\t\tset_mpz_t(mp, p);\n\t\t\tmpz_add(mz, mz, mp);\n\t\t}\n\t\tGmp::getArray(z, N, mz);\n\t}\n\tstatic inline void mulPreC(Unit *z, const Unit *x, const Unit *y)\n\t{\n\t\tmpz_t mx, my, mz;\n\t\tset_zero(mz, z, N * 2);\n\t\tset_mpz_t(mx, x);\n\t\tset_mpz_t(my, y);\n\t\tmpz_mul(mz, mx, my);\n\t\tGmp::getArray(z, N * 2, mz);\n\t}\n\t\/\/ x[N * 2] -> y[N]\n\tstatic inline void modC(Unit *y, const Unit *x, const Unit *p)\n\t{\n\t\tmpz_t mx, my, mp;\n\t\tset_mpz_t(mx, x, N * 2);\n\t\tset_mpz_t(my, y);\n\t\tset_mpz_t(mp, p);\n\t\tmpz_mod(my, mx, mp);\n\t\tclearArray(y, my->_mp_size, N);\n\t}\n\tstatic inline void invOp(Unit *y, const Unit *x, const Op& op)\n\t{\n\t\tmpz_class my;\n\t\tmpz_t mx, mp;\n\t\tset_mpz_t(mx, x);\n\t\tset_mpz_t(mp, op.p);\n\t\tmpz_invert(my.get_mpz_t(), mx, mp);\n\t\tGmp::getArray(y, N, my);\n\t}\n\tstatic inline bool isZeroC(const Unit *x)\n\t{\n\t\treturn isZeroArray(x, N);\n\t}\n\tstatic inline void negC(Unit *y, const Unit *x, const Unit *p)\n\t{\n\t\tif (isZeroC(x)) {\n\t\t\tif (x != y) clearC(y);\n\t\t\treturn;\n\t\t}\n\t\tsubC(y, p, x, p);\n\t}\n};\n\n#ifdef MCL_USE_LLVM\n\t#define SET_OP_LLVM(n) \\\n\t\taddP = mcl_fp_add ## n ##S; \\\n\t\tsubP = mcl_fp_sub ## n ##S; \\\n\t\tmulPreP = mcl_fp_mulPre ## n; \\\n\t\tmont = mcl_fp_mont ## n;\n#else\n\t#define SET_OP_LLVM(n)\n#endif\n\n#define SET_OP(n) \\\n\t\tN = n \/ UnitBitSize; \\\n\t\tisZero = OpeFunc::isZeroC; \\\n\t\tclear = OpeFunc::clearC; \\\n\t\tcopy = OpeFunc::copyC; \\\n\t\tnegP = OpeFunc::negC; \\\n\t\tinvOp = OpeFunc::invOp; \\\n\t\taddP = OpeFunc::addC; \\\n\t\tsubP = OpeFunc::subC; \\\n\t\tmulPreP = OpeFunc::mulPreC; \\\n\t\tmodP = OpeFunc::modC; \\\n\t\tSET_OP_LLVM(n) \n\n#ifdef USE_MONT_FP\ninline void invOpForMont(Unit *y, const Unit *x, const Op& op)\n{\n\tUnit r[maxOpUnitSize];\n\tint k = op.preInv(r, x);\n\t\/*\n\t\txr = 2^k\n\t\tR = 2^(N * 64)\n\t\tget r2^(-k)R^2 = r 2^(N * 64 * 2 - k)\n\t*\/\n\top.mul(y, r, op.invTbl.data() + k * op.N);\n}\n\nstatic void initInvTbl(Op& op)\n{\n\tconst size_t N = op.N;\n\tconst size_t invTblN = N * sizeof(Unit) * 8 * 2;\n\top.invTbl.resize(invTblN * N);\n\tUnit *tbl = op.invTbl.data() + (invTblN - 1) * N;\n\tUnit t[maxOpUnitSize] = {};\n\tt[0] = 2;\n\top.toMont(tbl, t);\n\tfor (size_t i = 0; i < invTblN - 1; i++) {\n\t\top.add(tbl - N, tbl, tbl);\n\t\ttbl -= N;\n\t}\n}\n#endif\n\nstatic void initForMont(Op& op, const Unit *p)\n{\n\tconst size_t N = op.N;\n\tassert(N >= 2);\n\tmpz_class t = 1;\n\tGmp::getArray(op.one, N, t);\n\tt = (t << (N * 64)) % op.mp;\n\tt = (t * t) % op.mp;\n\tGmp::getArray(op.RR, N, t);\n\top.rp = getMontgomeryCoeff(p[0]);\n#ifdef USE_MONT_FP\n\tFpGenerator *fg = op.fg;\n\tif (fg == 0) return;\n\tfg->init(p, (int)N);\n\n\top.neg = Xbyak::CastTo(fg->neg_);\n\top.add = Xbyak::CastTo(fg->add_);\n\top.sub = Xbyak::CastTo(fg->sub_);\n\top.mul = Xbyak::CastTo(fg->mul_);\n\top.preInv = Xbyak::CastTo(op.fg->preInv_);\n\top.invOp = &invOpForMont;\n\n\tinitInvTbl(op);\n#endif\n}\n\nvoid Op::init(const std::string& mstr, int base, size_t maxBitSize, Mode mode)\n{\n\tcybozu::disable_warning_unused_variable(mode);\n\tbool isMinus = fp::strToMpzArray(&bitSize, p, maxBitSize, mp, mstr, base);\n\tif (isMinus) throw cybozu::Exception(\"Op:init:mstr is minus\") << mstr;\n\tif (mp == 0) throw cybozu::Exception(\"Op:init:mstr is zero\") << mstr;\n\n\tconst size_t roundBit = (bitSize + UnitBitSize - 1) & ~(UnitBitSize - 1);\n\tswitch (roundBit) {\n\tcase 32:\n\tcase 64:\n\tcase 96:\n\tcase 128: SET_OP(128); break;\n\tcase 192: SET_OP(192); break;\n\tcase 256: SET_OP(256); break;\n\tcase 320: SET_OP(320); break;\n\tcase 384: SET_OP(384); break;\n\tcase 448: SET_OP(448); break;\n\tcase 512: SET_OP(512); break;\n#if CYBOZU_OS_BIT == 64\n\tcase 576: SET_OP(576); break;\n#else\n\tcase 160: SET_OP(160); break;\n\tcase 224: SET_OP(224); break;\n\tcase 288: SET_OP(288); break;\n\tcase 352: SET_OP(352); break;\n\tcase 416: SET_OP(416); break;\n\tcase 480: SET_OP(480); break;\n\tcase 544: SET_OP(544); break;\n#endif\n\tdefault:\n\t\tthrow cybozu::Exception(\"Op::init:not:support\") << mstr;\n\t}\n#ifdef MCL_USE_LLVM\n\tif (mp == mpz_class(\"0xfffffffffffffffffffffffffffffffeffffffffffffffff\")) {\n\t\tmul = &mcl_fp_mul_NIST_P192; \/\/ slower than MontFp192\n\t}\n#endif\n\tif (useMont) {\n\t\tfp::initForMont(*this, p);\n\t}\n\tsq.set(mp);\n}\n\nvoid arrayToStr(std::string& str, const Unit *x, size_t n, int base, bool withPrefix)\n{\n\tswitch (base) {\n\tcase 10:\n\t\t{\n\t\t\tmpz_class t;\n\t\t\tGmp::setArray(t, x, n);\n\t\t\tGmp::getStr(str, t, 10);\n\t\t}\n\t\treturn;\n\tcase 16:\n\t\tmcl::fp::toStr16(str, x, n, withPrefix);\n\t\treturn;\n\tcase 2:\n\t\tmcl::fp::toStr2(str, x, n, withPrefix);\n\t\treturn;\n\tdefault:\n\t\tthrow cybozu::Exception(\"fp:arrayToStr:bad base\") << base;\n\t}\n}\n\nvoid copyAndMask(Unit *y, const void *x, size_t xByteSize, const Op& op, bool doMask)\n{\n\tconst size_t fpByteSize = sizeof(Unit) * op.N;\n\tif (xByteSize > fpByteSize) {\n\t\tif (!doMask) throw cybozu::Exception(\"fp:copyAndMask:bad size\") << xByteSize << fpByteSize;\n\t\txByteSize = fpByteSize;\n\t}\n\tmemcpy(y, x, xByteSize);\n\tmemset((char *)y + xByteSize, 0, fpByteSize - xByteSize);\n\tif (!doMask) {\n\t\tif (compareArray(y, op.p, op.N) >= 0) throw cybozu::Exception(\"fp:copyAndMask:large x\");\n\t\treturn;\n\t}\n\tmaskArray(y, op.N, op.bitSize - 1);\n\tassert(compareArray(y, op.p, op.N) < 0);\n}\n\n} } \/\/ mcl::fp\n\nadd invMontOp#include \n#include \n#include \n#ifdef USE_MONT_FP\n#include \n#endif\n#include \n\nnamespace mcl { namespace fp {\n\n#ifdef USE_MONT_FP\nFpGenerator *Op::createFpGenerator()\n{\n\treturn new FpGenerator();\n}\nvoid Op::destroyFpGenerator(FpGenerator *fg)\n{\n\tdelete fg;\n}\n#else\nFpGenerator *Op::createFpGenerator()\n{\n\treturn 0;\n}\nvoid Op::destroyFpGenerator(FpGenerator *)\n{\n}\n#endif\n\ninline const char *verifyStr(bool *isMinus, int *base, const std::string& str)\n{\n\tconst char *p = str.c_str();\n\tif (*p == '-') {\n\t\t*isMinus = true;\n\t\tp++;\n\t} else {\n\t\t*isMinus = false;\n\t}\n\tif (p[0] == '0') {\n\t\tif (p[1] == 'x') {\n\t\t\tif (*base != 0 && *base != 16) {\n\t\t\t\tthrow cybozu::Exception(\"fp:verifyStr:bad base\") << *base << str;\n\t\t\t}\n\t\t\t*base = 16;\n\t\t\tp += 2;\n\t\t} else if (p[1] == 'b') {\n\t\t\tif (*base != 0 && *base != 2) {\n\t\t\t\tthrow cybozu::Exception(\"fp:verifyStr:bad base\") << *base << str;\n\t\t\t}\n\t\t\t*base = 2;\n\t\t\tp += 2;\n\t\t}\n\t}\n\tif (*base == 0) *base = 10;\n\tif (*p == '\\0') throw cybozu::Exception(\"fp:verifyStr:str is empty\");\n\treturn p;\n}\n\nbool strToMpzArray(size_t *pBitSize, Unit *y, size_t maxBitSize, mpz_class& x, const std::string& str, int base)\n{\n\tbool isMinus;\n\tconst char *p = verifyStr(&isMinus, &base, str);\n\tif (!Gmp::setStr(x, p, base)) {\n\t\tthrow cybozu::Exception(\"fp:strToMpzArray:bad format\") << str;\n\t}\n\tconst size_t bitSize = Gmp::getBitSize(x);\n\tif (bitSize > maxBitSize) throw cybozu::Exception(\"fp:strToMpzArray:too large str\") << str << bitSize << maxBitSize;\n\tif (pBitSize) *pBitSize = bitSize;\n\tGmp::getArray(y, (maxBitSize + UnitBitSize - 1) \/ UnitBitSize, x);\n\treturn isMinus;\n}\n\ntemplate\nstruct OpeFunc {\n\tstatic const size_t N = (bitSize + UnitBitSize - 1) \/ UnitBitSize;\n\tstatic inline void set_mpz_t(mpz_t& z, const Unit* p, int n = (int)N)\n\t{\n\t\tz->_mp_alloc = n;\n\t\tz->_mp_size = getNonZeroArraySize(p, n);\n\t\tz->_mp_d = (mp_limb_t*)const_cast(p);\n\t}\n\tstatic inline void set_zero(mpz_t& z, Unit *p, size_t n)\n\t{\n\t\tz->_mp_alloc = (int)n;\n\t\tz->_mp_size = 0;\n\t\tz->_mp_d = (mp_limb_t*)p;\n\t}\n\tstatic inline void clearC(Unit *x)\n\t{\n\t\tclearArray(x, 0, N);\n\t}\n\tstatic inline void copyC(Unit *y, const Unit *x)\n\t{\n\t\tcopyArray(y, x, N);\n\t}\n\tstatic inline void addC(Unit *z, const Unit *x, const Unit *y, const Unit *p)\n\t{\n\t\tUnit ret[N + 2]; \/\/ not N + 1\n\t\tmpz_t mz, mx, my, mp;\n\t\tset_zero(mz, ret, N + 2);\n\t\tset_mpz_t(mx, x);\n\t\tset_mpz_t(my, y);\n\t\tset_mpz_t(mp, p);\n\t\tmpz_add(mz, mx, my);\n\t\tif (mpz_cmp(mz, mp) >= 0) {\n\t\t\tmpz_sub(mz, mz, mp);\n\t\t}\n\t\tGmp::getArray(z, N, mz);\n\t}\n\tstatic inline void subC(Unit *z, const Unit *x, const Unit *y, const Unit *p)\n\t{\n\t\tUnit ret[N + 1];\n\t\tmpz_t mz, mx, my;\n\t\tset_zero(mz, ret, N + 1);\n\t\tset_mpz_t(mx, x);\n\t\tset_mpz_t(my, y);\n\t\tmpz_sub(mz, mx, my);\n\t\tif (mpz_sgn(mz) < 0) {\n\t\t\tmpz_t mp;\n\t\t\tset_mpz_t(mp, p);\n\t\t\tmpz_add(mz, mz, mp);\n\t\t}\n\t\tGmp::getArray(z, N, mz);\n\t}\n\tstatic inline void mulPreC(Unit *z, const Unit *x, const Unit *y)\n\t{\n\t\tmpz_t mx, my, mz;\n\t\tset_zero(mz, z, N * 2);\n\t\tset_mpz_t(mx, x);\n\t\tset_mpz_t(my, y);\n\t\tmpz_mul(mz, mx, my);\n\t\tGmp::getArray(z, N * 2, mz);\n\t}\n\t\/\/ x[N * 2] -> y[N]\n\tstatic inline void modC(Unit *y, const Unit *x, const Unit *p)\n\t{\n\t\tmpz_t mx, my, mp;\n\t\tset_mpz_t(mx, x, N * 2);\n\t\tset_mpz_t(my, y);\n\t\tset_mpz_t(mp, p);\n\t\tmpz_mod(my, mx, mp);\n\t\tclearArray(y, my->_mp_size, N);\n\t}\n\tstatic inline void invOp(Unit *y, const Unit *x, const Op& op)\n\t{\n\t\tmpz_class my;\n\t\tmpz_t mx, mp;\n\t\tset_mpz_t(mx, x);\n\t\tset_mpz_t(mp, op.p);\n\t\tmpz_invert(my.get_mpz_t(), mx, mp);\n\t\tGmp::getArray(y, N, my);\n\t}\n\t\/*\n\t\tinv(x\/R) = (1\/x)R -toMont-> 1\/x -toMont-> (1\/x)R^-1\n\t*\/\n\tstatic void invMontOp(Unit *y, const Unit *x, const Op& op)\n\t{\n\t\tinvOp(y, x, op);\n\t\top.toMont(y, y);\n\t\top.toMont(y, y);\n\t}\n\tstatic inline bool isZeroC(const Unit *x)\n\t{\n\t\treturn isZeroArray(x, N);\n\t}\n\tstatic inline void negC(Unit *y, const Unit *x, const Unit *p)\n\t{\n\t\tif (isZeroC(x)) {\n\t\t\tif (x != y) clearC(y);\n\t\t\treturn;\n\t\t}\n\t\tsubC(y, p, x, p);\n\t}\n};\n\n#ifdef MCL_USE_LLVM\n\t#define SET_OP_LLVM(n) \\\n\t\taddP = mcl_fp_add ## n ##S; \\\n\t\tsubP = mcl_fp_sub ## n ##S; \\\n\t\tmulPreP = mcl_fp_mulPre ## n; \\\n\t\tmont = mcl_fp_mont ## n;\n#else\n\t#define SET_OP_LLVM(n)\n#endif\n\n#define SET_OP(n) \\\n\t\tN = n \/ UnitBitSize; \\\n\t\tisZero = OpeFunc::isZeroC; \\\n\t\tclear = OpeFunc::clearC; \\\n\t\tcopy = OpeFunc::copyC; \\\n\t\tnegP = OpeFunc::negC; \\\n\t\tif (useMont) { \\\n\t\t\tinvOp = OpeFunc::invMontOp; \\\n\t\t} else { \\\n\t\t\tinvOp = OpeFunc::invOp; \\\n\t\t} \\\n\t\taddP = OpeFunc::addC; \\\n\t\tsubP = OpeFunc::subC; \\\n\t\tmulPreP = OpeFunc::mulPreC; \\\n\t\tmodP = OpeFunc::modC; \\\n\t\tSET_OP_LLVM(n) \n\n#ifdef USE_MONT_FP\ninline void invOpForMont(Unit *y, const Unit *x, const Op& op)\n{\n\tUnit r[maxOpUnitSize];\n\tint k = op.preInv(r, x);\n\t\/*\n\t\txr = 2^k\n\t\tR = 2^(N * 64)\n\t\tget r2^(-k)R^2 = r 2^(N * 64 * 2 - k)\n\t*\/\n\top.mul(y, r, op.invTbl.data() + k * op.N);\n}\n\nstatic void initInvTbl(Op& op)\n{\n\tconst size_t N = op.N;\n\tconst size_t invTblN = N * sizeof(Unit) * 8 * 2;\n\top.invTbl.resize(invTblN * N);\n\tUnit *tbl = op.invTbl.data() + (invTblN - 1) * N;\n\tUnit t[maxOpUnitSize] = {};\n\tt[0] = 2;\n\top.toMont(tbl, t);\n\tfor (size_t i = 0; i < invTblN - 1; i++) {\n\t\top.add(tbl - N, tbl, tbl);\n\t\ttbl -= N;\n\t}\n}\n#endif\n\nstatic void initForMont(Op& op, const Unit *p)\n{\n\tconst size_t N = op.N;\n\tassert(N >= 2);\n\tmpz_class t = 1;\n\tGmp::getArray(op.one, N, t);\n\tt = (t << (N * 64)) % op.mp;\n\tt = (t * t) % op.mp;\n\tGmp::getArray(op.RR, N, t);\n\top.rp = getMontgomeryCoeff(p[0]);\n#ifdef USE_MONT_FP\n\tFpGenerator *fg = op.fg;\n\tif (fg == 0) return;\n\tfg->init(p, (int)N);\n\n\top.neg = Xbyak::CastTo(fg->neg_);\n\top.add = Xbyak::CastTo(fg->add_);\n\top.sub = Xbyak::CastTo(fg->sub_);\n\top.mul = Xbyak::CastTo(fg->mul_);\n\top.preInv = Xbyak::CastTo(op.fg->preInv_);\n\top.invOp = &invOpForMont;\n\n\tinitInvTbl(op);\n#endif\n}\n\nvoid Op::init(const std::string& mstr, int base, size_t maxBitSize, Mode mode)\n{\n\tcybozu::disable_warning_unused_variable(mode);\n\tbool isMinus = fp::strToMpzArray(&bitSize, p, maxBitSize, mp, mstr, base);\n\tif (isMinus) throw cybozu::Exception(\"Op:init:mstr is minus\") << mstr;\n\tif (mp == 0) throw cybozu::Exception(\"Op:init:mstr is zero\") << mstr;\n\n\tconst size_t roundBit = (bitSize + UnitBitSize - 1) & ~(UnitBitSize - 1);\n\tswitch (roundBit) {\n\tcase 32:\n\tcase 64:\n\tcase 96:\n\tcase 128: SET_OP(128); break;\n\tcase 192: SET_OP(192); break;\n\tcase 256: SET_OP(256); break;\n\tcase 320: SET_OP(320); break;\n\tcase 384: SET_OP(384); break;\n\tcase 448: SET_OP(448); break;\n\tcase 512: SET_OP(512); break;\n#if CYBOZU_OS_BIT == 64\n\tcase 576: SET_OP(576); break;\n#else\n\tcase 160: SET_OP(160); break;\n\tcase 224: SET_OP(224); break;\n\tcase 288: SET_OP(288); break;\n\tcase 352: SET_OP(352); break;\n\tcase 416: SET_OP(416); break;\n\tcase 480: SET_OP(480); break;\n\tcase 544: SET_OP(544); break;\n#endif\n\tdefault:\n\t\tthrow cybozu::Exception(\"Op::init:not:support\") << mstr;\n\t}\n#ifdef MCL_USE_LLVM\n\tif (mp == mpz_class(\"0xfffffffffffffffffffffffffffffffeffffffffffffffff\")) {\n\t\tmul = &mcl_fp_mul_NIST_P192; \/\/ slower than MontFp192\n\t}\n#endif\n\tif (useMont) {\n\t\tfp::initForMont(*this, p);\n\t}\n\tsq.set(mp);\n}\n\nvoid arrayToStr(std::string& str, const Unit *x, size_t n, int base, bool withPrefix)\n{\n\tswitch (base) {\n\tcase 10:\n\t\t{\n\t\t\tmpz_class t;\n\t\t\tGmp::setArray(t, x, n);\n\t\t\tGmp::getStr(str, t, 10);\n\t\t}\n\t\treturn;\n\tcase 16:\n\t\tmcl::fp::toStr16(str, x, n, withPrefix);\n\t\treturn;\n\tcase 2:\n\t\tmcl::fp::toStr2(str, x, n, withPrefix);\n\t\treturn;\n\tdefault:\n\t\tthrow cybozu::Exception(\"fp:arrayToStr:bad base\") << base;\n\t}\n}\n\nvoid copyAndMask(Unit *y, const void *x, size_t xByteSize, const Op& op, bool doMask)\n{\n\tconst size_t fpByteSize = sizeof(Unit) * op.N;\n\tif (xByteSize > fpByteSize) {\n\t\tif (!doMask) throw cybozu::Exception(\"fp:copyAndMask:bad size\") << xByteSize << fpByteSize;\n\t\txByteSize = fpByteSize;\n\t}\n\tmemcpy(y, x, xByteSize);\n\tmemset((char *)y + xByteSize, 0, fpByteSize - xByteSize);\n\tif (!doMask) {\n\t\tif (compareArray(y, op.p, op.N) >= 0) throw cybozu::Exception(\"fp:copyAndMask:large x\");\n\t\treturn;\n\t}\n\tmaskArray(y, op.N, op.bitSize - 1);\n\tassert(compareArray(y, op.p, op.N) < 0);\n}\n\n} } \/\/ mcl::fp\n\n<|endoftext|>"} {"text":"\/\/ibnu.yahya@toroo.org\n#include \"fs.h\"\n#include \n\nfs::fs(QObject *parent) :\n QObject(parent)\n{\n\n}\n\nbool fs::fileRemove(const QString &path){\n QFile file(path);\n return file.remove();\n}\n\nbool fs::fileWrite(const QString &path, const QString &data){\n QFile file(path);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)){\n QTextStream out(&file);\n out << data;\n file.close();\n return true;\n }\n else {\n return false;\n }\n}\n\nQString fs::fileRead(const QString &path){\n \/\/QStringList fields;\n QFile file(path);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)){\n QTextStream out(&file);\n\n \/*while(!out.atEnd()){\n fields.append(out.readLine());\n\n }*\/\n QString data = out.readAll();\n \/*foreach (const QString text, fields){\n qDebug() << text.toUtf8();\n }*\/\n file.close();\n \/\/return fields;\n return data;\n }\n else {\n qDebug()<< \"Err : File not found\";\n return \"\";\n }\n}\n\nQString fs::appPath(){\n return QApplication::applicationDirPath();\n}\n\nQString fs::homePath(){\n QString home = QDir::homePath();\n return home;\n}\n\nbool fs::dir(const QString &opt, const QString &path){\n QDir dir;\n if(opt == \"create\"){\n return dir.mkdir(path);\n }\n else if(opt == \"remove\"){\n return dir.rmdir(path);\n }\n else{\n return false;\n }\n}\n\nbool fs::isExist(const QString &path)\n{\n return QFile::exists(path);\n}\n\nbool fs::isDirectory(const QString &path)\n{\n return QFileInfo(path).isDir();\n}\n\nbool fs::isFile(const QString &path)\n{\n return QFileInfo(path).isFile();\n}\n\nbool fs::isAbsolute(const QString &path)\n{\n return QFileInfo(path).isAbsolute();\n}\n\nbool fs::isExecutable(const QString &path)\n{\n return QFileInfo(path).isExecutable();\n}\n\nbool fs::isSymlink(const QString &path)\n{\n return QFileInfo(path).isSymLink();\n}\n\nbool fs::isReadable(const QString &path)\n{\n return QFileInfo(path).isReadable();\n}\n\nbool fs::isWritable(const QString &path)\n{\n return QFileInfo(path).isWritable();\n}\n\nbool fs::copy(const QString &src, const QString &des){\n if(QFile::exists(des)){\n QFile::remove(des);\n }\n return QFile::copy(src,des);\n}\n\nQString fs::openFileDialog(){\n QFileDialog *fd = new QFileDialog;\n int result = fd->exec();\n if (result)\n {\n QString directory = fd->selectedFiles()[0];\n return directory;\n }\n else {\n return \"\";\n }\n}\n\nQString fs::openDirDialog(){\n QFileDialog *fd = new QFileDialog;\n#ifdef Linux\n QTreeView *tree = fd->findChild ();\n tree->setRootIsDecorated(true);\n tree->setItemsExpandable(true);\n#endif\n fd->setFileMode(QFileDialog::Directory);\n fd->setOption(QFileDialog::ShowDirsOnly);\n fd->setViewMode(QFileDialog::Detail);\n int result = fd->exec();\n QString directory;\n if (result)\n {\n directory = fd->selectedFiles()[0];\n return directory;\n }\n else {\n return \"\";\n }\n}\n\nQString fs::saveFileDialog(){\n QFileDialog *fd = new QFileDialog;\n QString directory = fd->getSaveFileName();\n return directory;\n}\n\nQString fs::saveFileDialog(const QVariant &config){\n QVariantMap conf = json->jsonParser(config).toVariantMap();\n QString title = \"Save File\",\n path = this->homePath(),\n ext = \"\";\n if(conf[\"title\"].toString() != \"\"){\n title = conf[\"title\"].toString();\n }\n\n if(conf[\"path\"].toString() != \"\"){\n path = conf[\"path\"].toString();\n }\n\n if(conf[\"info\"].toString() != \"\"){\n ext = conf[\"info\"].toString();\n }\n\n QFileDialog *fd = new QFileDialog;\n QWidget *widget = new QWidget();\n QString directory = fd->getSaveFileName(widget, title,path,ext);\n return directory;\n}\n\nQStringList fs::list(const QString &path){\n QDirIterator dirIt(path,QDirIterator::Subdirectories);\n QStringList list;\n while (dirIt.hasNext()) {\n dirIt.next();\n list.push_front(dirIt.filePath());\n }\n return list;\n}\n\nQVariant fs::info(const QString &path){\n QVariantMap map;\n QFileInfo info(path);\n QVariant size = info.size();\n QVariant absoluteFilePath = info.absoluteFilePath();\n QVariant baseName = info.baseName();\n QVariant isSymlink = info.isSymLink();\n QVariant isAbsolute = info.isAbsolute();\n QVariant isBundle = info.isBundle();\n QVariant isDir = info.isDir();\n QVariant isExecutable = info.isExecutable();\n QVariant isFile = info.isFile();\n QVariant isHidden = info.isHidden();\n QVariant isReadable = info.isReadable();\n QVariant isRelative = info.isRelative();\n QVariant isRoot = info.isRoot();\n QVariant isWritable = info.isWritable();\n QVariant bundleName = info.bundleName();\n QVariant exists = info.exists();\n QVariant fileName = info.fileName();\n QVariant filePath = info.filePath();\n QVariant group = info.group();\n QVariant lastModified = info.lastModified();\n QVariant lastRead = info.lastRead();\n map.insert(\"size\",size);\n map.insert(\"absoluteFilePath\",absoluteFilePath);\n map.insert(\"baseName\",baseName);\n map.insert(\"isSymlink\",isSymlink);\n map.insert(\"isAbsolute\",isAbsolute);\n map.insert(\"isBundle\",isBundle);\n map.insert(\"isDir\",isDir);\n map.insert(\"isExecutable\",isExecutable);\n map.insert(\"isFile\",isFile);\n map.insert(\"isHidden\",isHidden);\n map.insert(\"isReadable\",isReadable);\n map.insert(\"isRelative\",isRelative);\n map.insert(\"isRoot\",isRoot);\n map.insert(\"isWritable\",isWritable);\n map.insert(\"filePath\",filePath);\n map.insert(\"bundleName\",bundleName);\n map.insert(\"exists\",exists);\n map.insert(\"fileName\",fileName);\n map.insert(\"group\",group);\n map.insert(\"lastModified\",lastModified);\n map.insert(\"lastRead\",lastRead);\n QJsonDocument json_enc = QJsonDocument::fromVariant(map);\n return json_enc.toVariant();\n}\nCHANGE: info object to type #161\/\/ibnu.yahya@toroo.org\n#include \"fs.h\"\n#include \n\nfs::fs(QObject *parent) :\n QObject(parent)\n{\n\n}\n\nbool fs::fileRemove(const QString &path){\n QFile file(path);\n return file.remove();\n}\n\nbool fs::fileWrite(const QString &path, const QString &data){\n QFile file(path);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)){\n QTextStream out(&file);\n out << data;\n file.close();\n return true;\n }\n else {\n return false;\n }\n}\n\nQString fs::fileRead(const QString &path){\n \/\/QStringList fields;\n QFile file(path);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)){\n QTextStream out(&file);\n\n \/*while(!out.atEnd()){\n fields.append(out.readLine());\n\n }*\/\n QString data = out.readAll();\n \/*foreach (const QString text, fields){\n qDebug() << text.toUtf8();\n }*\/\n file.close();\n \/\/return fields;\n return data;\n }\n else {\n qDebug()<< \"Err : File not found\";\n return \"\";\n }\n}\n\nQString fs::appPath(){\n return QApplication::applicationDirPath();\n}\n\nQString fs::homePath(){\n QString home = QDir::homePath();\n return home;\n}\n\nbool fs::dir(const QString &opt, const QString &path){\n QDir dir;\n if(opt == \"create\"){\n return dir.mkdir(path);\n }\n else if(opt == \"remove\"){\n return dir.rmdir(path);\n }\n else{\n return false;\n }\n}\n\nbool fs::isExist(const QString &path)\n{\n return QFile::exists(path);\n}\n\nbool fs::isDirectory(const QString &path)\n{\n return QFileInfo(path).isDir();\n}\n\nbool fs::isFile(const QString &path)\n{\n return QFileInfo(path).isFile();\n}\n\nbool fs::isAbsolute(const QString &path)\n{\n return QFileInfo(path).isAbsolute();\n}\n\nbool fs::isExecutable(const QString &path)\n{\n return QFileInfo(path).isExecutable();\n}\n\nbool fs::isSymlink(const QString &path)\n{\n return QFileInfo(path).isSymLink();\n}\n\nbool fs::isReadable(const QString &path)\n{\n return QFileInfo(path).isReadable();\n}\n\nbool fs::isWritable(const QString &path)\n{\n return QFileInfo(path).isWritable();\n}\n\nbool fs::copy(const QString &src, const QString &des){\n if(QFile::exists(des)){\n QFile::remove(des);\n }\n return QFile::copy(src,des);\n}\n\nQString fs::openFileDialog(){\n QFileDialog *fd = new QFileDialog;\n int result = fd->exec();\n if (result)\n {\n QString directory = fd->selectedFiles()[0];\n return directory;\n }\n else {\n return \"\";\n }\n}\n\nQString fs::openDirDialog(){\n QFileDialog *fd = new QFileDialog;\n#ifdef Linux\n QTreeView *tree = fd->findChild ();\n tree->setRootIsDecorated(true);\n tree->setItemsExpandable(true);\n#endif\n fd->setFileMode(QFileDialog::Directory);\n fd->setOption(QFileDialog::ShowDirsOnly);\n fd->setViewMode(QFileDialog::Detail);\n int result = fd->exec();\n QString directory;\n if (result)\n {\n directory = fd->selectedFiles()[0];\n return directory;\n }\n else {\n return \"\";\n }\n}\n\nQString fs::saveFileDialog(){\n QFileDialog *fd = new QFileDialog;\n QString directory = fd->getSaveFileName();\n return directory;\n}\n\nQString fs::saveFileDialog(const QVariant &config){\n QVariantMap conf = json->jsonParser(config).toVariantMap();\n QString title = \"Save File\",\n path = this->homePath(),\n ext = \"\";\n if(conf[\"title\"].toString() != \"\"){\n title = conf[\"title\"].toString();\n }\n\n if(conf[\"path\"].toString() != \"\"){\n path = conf[\"path\"].toString();\n }\n\n if(conf[\"type\"].toString() != \"\"){\n ext = conf[\"type\"].toString();\n }\n\n QFileDialog *fd = new QFileDialog;\n QWidget *widget = new QWidget();\n QString directory = fd->getSaveFileName(widget, title,path,ext);\n return directory;\n}\n\nQStringList fs::list(const QString &path){\n QDirIterator dirIt(path,QDirIterator::Subdirectories);\n QStringList list;\n while (dirIt.hasNext()) {\n dirIt.next();\n list.push_front(dirIt.filePath());\n }\n return list;\n}\n\nQVariant fs::info(const QString &path){\n QVariantMap map;\n QFileInfo info(path);\n QVariant size = info.size();\n QVariant absoluteFilePath = info.absoluteFilePath();\n QVariant baseName = info.baseName();\n QVariant isSymlink = info.isSymLink();\n QVariant isAbsolute = info.isAbsolute();\n QVariant isBundle = info.isBundle();\n QVariant isDir = info.isDir();\n QVariant isExecutable = info.isExecutable();\n QVariant isFile = info.isFile();\n QVariant isHidden = info.isHidden();\n QVariant isReadable = info.isReadable();\n QVariant isRelative = info.isRelative();\n QVariant isRoot = info.isRoot();\n QVariant isWritable = info.isWritable();\n QVariant bundleName = info.bundleName();\n QVariant exists = info.exists();\n QVariant fileName = info.fileName();\n QVariant filePath = info.filePath();\n QVariant group = info.group();\n QVariant lastModified = info.lastModified();\n QVariant lastRead = info.lastRead();\n map.insert(\"size\",size);\n map.insert(\"absoluteFilePath\",absoluteFilePath);\n map.insert(\"baseName\",baseName);\n map.insert(\"isSymlink\",isSymlink);\n map.insert(\"isAbsolute\",isAbsolute);\n map.insert(\"isBundle\",isBundle);\n map.insert(\"isDir\",isDir);\n map.insert(\"isExecutable\",isExecutable);\n map.insert(\"isFile\",isFile);\n map.insert(\"isHidden\",isHidden);\n map.insert(\"isReadable\",isReadable);\n map.insert(\"isRelative\",isRelative);\n map.insert(\"isRoot\",isRoot);\n map.insert(\"isWritable\",isWritable);\n map.insert(\"filePath\",filePath);\n map.insert(\"bundleName\",bundleName);\n map.insert(\"exists\",exists);\n map.insert(\"fileName\",fileName);\n map.insert(\"group\",group);\n map.insert(\"lastModified\",lastModified);\n map.insert(\"lastRead\",lastRead);\n QJsonDocument json_enc = QJsonDocument::fromVariant(map);\n return json_enc.toVariant();\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2015 Esri\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\nA local copy of the license and additional notices are located with the\nsource distribution at:\nhttp:\/\/github.com\/Esri\/lerc\/\nContributors: Thomas Maurer\n*\/\n\n\/\/\n\/\/ BitMask2.cpp\n\/\/\n\n#include \"BitMask2.h\"\n#include \n#include \n#include \n#include \n\nNAMESPACE_MRF_START\n\n\/\/ -------------------------------------------------------------------------- ;\n\nBitMask2::BitMask2() : m_pBits(NULL), m_nCols(0), m_nRows(0)\n{\n}\n\n\/\/ -------------------------------------------------------------------------- ;\n\nBitMask2::BitMask2(int nCols, int nRows) : m_pBits(NULL)\n{\n SetSize(nCols, nRows);\n}\n\n\/\/ -------------------------------------------------------------------------- ;\n\nBitMask2::BitMask2(const BitMask2& src) : m_pBits(NULL)\n{\n SetSize(src.m_nCols, src.m_nRows);\n if (m_pBits && src.m_pBits)\n memcpy(m_pBits, src.m_pBits, Size());\n}\n\n\/\/ -------------------------------------------------------------------------- ;\n\nBitMask2& BitMask2::operator= (const BitMask2& src)\n{\n if (this == &src) return *this;\n\n SetSize(src.m_nCols, src.m_nRows);\n if (src.m_pBits)\n memcpy(m_pBits, src.m_pBits, Size());\n\n return *this;\n}\n\n\/\/ -------------------------------------------------------------------------- ;\n\nbool BitMask2::SetSize(int nCols, int nRows)\n{\n if (nCols != m_nCols || nRows != m_nRows)\n {\n Clear();\n m_nCols = nCols;\n m_nRows = nRows;\n m_pBits = new Byte[Size()];\n }\n return m_pBits != NULL;\n}\n\n\/\/ -------------------------------------------------------------------------- ;\n\/\/\n\/\/ Count of set bits in a byte, done in 7 32bit instructions\n\/\/ Adds every two bits sideways, makes four copies, masks each of the four results\n\/\/ the last multiplication adds the four results together in the top nibble\n\/\/ This is potentially slower for input data \n\/\/\nstatic inline int csb(unsigned int v) {\n return ((((v - ((v >> 1) & 0x55)) * 0x1010101) & 0x30c00c03) * 0x10040041) >> 0x1c;\n}\n\n\/\/ Number of bits set.\n\/\/ We really only need to know if full, empty or inbetween\nint BitMask2::CountValidBits() const\n{\n assert(Size());\n const Byte* ptr = m_pBits;\n int sum = 0;\n\n \/\/ The first loop is in multiples of four, to let the compiler optimize\n for (int i = 0; i < (Size()\/4) * 4; i++)\n sum += csb(*ptr++);\n \/\/ Second loop for the leftover bytes, up to three\n for (int i = 0; i < Size() % 4; i++)\n sum += csb(*ptr++);\n\n \/\/ Subtract the defined bits potentially contained in the last byte\n \/\/ Number of undefined bytes is (C*R)%8\n \/\/ The undefined bits are at the low bit position, use a mask for them\n sum -= csb((*--ptr) & ((1 << ((m_nCols * m_nRows) % 8)) -1));\n\n return sum;\n}\n\n\/\/ -------------------------------------------------------------------------- ;\n\nvoid BitMask2::Clear()\n{\n delete[] m_pBits;\n m_pBits = NULL;\n m_nCols = 0;\n m_nRows = 0;\n}\n\n\/\/ -------------------------------------------------------------------------- ;\n\nNAMESPACE_MRF_END\nGDAL integration #44\/*\nCopyright 2015 Esri\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\nA local copy of the license and additional notices are located with the\nsource distribution at:\nhttp:\/\/github.com\/Esri\/lerc\/\nContributors: Thomas Maurer\n*\/\n\n\/\/\n\/\/ BitMask2.cpp\n\/\/\n\n#include \"BitMask2.h\"\n#include \n#include \n#include \n#include \n\nNAMESPACE_MRF_START\n\n\/\/ -------------------------------------------------------------------------- ;\n\nBitMask2::BitMask2() : m_pBits(NULL), m_nCols(0), m_nRows(0)\n{\n}\n\n\/\/ -------------------------------------------------------------------------- ;\n\nBitMask2::BitMask2(int nCols, int nRows) : m_pBits(NULL), m_nCols(0), m_nRows(0)\n{\n SetSize(nCols, nRows);\n}\n\n\/\/ -------------------------------------------------------------------------- ;\n\nBitMask2::BitMask2(const BitMask2& src) : m_pBits(NULL), m_nCols(0), m_nRows(0)\n{\n SetSize(src.m_nCols, src.m_nRows);\n if (m_pBits && src.m_pBits)\n memcpy(m_pBits, src.m_pBits, Size());\n}\n\n\/\/ -------------------------------------------------------------------------- ;\n\nBitMask2& BitMask2::operator= (const BitMask2& src)\n{\n if (this == &src) return *this;\n\n SetSize(src.m_nCols, src.m_nRows);\n if (src.m_pBits)\n memcpy(m_pBits, src.m_pBits, Size());\n\n return *this;\n}\n\n\/\/ -------------------------------------------------------------------------- ;\n\nbool BitMask2::SetSize(int nCols, int nRows)\n{\n if (nCols != m_nCols || nRows != m_nRows)\n {\n Clear();\n m_nCols = nCols;\n m_nRows = nRows;\n m_pBits = new Byte[Size()];\n }\n return m_pBits != NULL;\n}\n\n\/\/ -------------------------------------------------------------------------- ;\n\/\/\n\/\/ Count of set bits in a byte, done in 7 32bit instructions\n\/\/ Adds every two bits sideways, makes four copies, masks each of the four results\n\/\/ the last multiplication adds the four results together in the top nibble\n\/\/ This is potentially slower for input data \n\/\/\nstatic inline int csb(unsigned int v) {\n return ((((v - ((v >> 1) & 0x55)) * 0x1010101) & 0x30c00c03) * 0x10040041) >> 0x1c;\n}\n\n\/\/ Number of bits set.\n\/\/ We really only need to know if full, empty or inbetween\nint BitMask2::CountValidBits() const\n{\n assert(Size());\n const Byte* ptr = m_pBits;\n int sum = 0;\n\n \/\/ The first loop is in multiples of four, to let the compiler optimize\n for (int i = 0; i < (Size()\/4) * 4; i++)\n sum += csb(*ptr++);\n \/\/ Second loop for the leftover bytes, up to three\n for (int i = 0; i < Size() % 4; i++)\n sum += csb(*ptr++);\n\n \/\/ Subtract the defined bits potentially contained in the last byte\n \/\/ Number of undefined bytes is (C*R)%8\n \/\/ The undefined bits are at the low bit position, use a mask for them\n sum -= csb((*--ptr) & ((1 << ((m_nCols * m_nRows) % 8)) -1));\n\n return sum;\n}\n\n\/\/ -------------------------------------------------------------------------- ;\n\nvoid BitMask2::Clear()\n{\n delete[] m_pBits;\n m_pBits = NULL;\n m_nCols = 0;\n m_nRows = 0;\n}\n\n\/\/ -------------------------------------------------------------------------- ;\n\nNAMESPACE_MRF_END\n<|endoftext|>"} {"text":"\/\/_________________________________________________________________________\n\/\/ Utility Class for transverse energy studies\n\/\/ Base class for ESD & MC analysis\n\/\/ - cuts for reconstruction and MonteCarlo \n\/\/ implementation file\n\/\/ \n\/\/*-- Authors: Oystein Djuvsland (Bergen), David Silvermyr (ORNL)\n\/\/_________________________________________________________________________\n\n#include \"AliAnalysisEtCuts.h\"\n\n#include \n#include \"TNamed.h\"\n\nusing namespace std;\n\nClassImp(AliAnalysisEtCuts);\n\n\nAliAnalysisEtCuts::AliAnalysisEtCuts() : \n TNamed()\n\t\t\t\t \/\/\n ,fCommonEtaCut(0.5)\n ,fCommonClusterEnergyCut(0.15)\n ,fCommonTrackPtCut(0.0)\n ,fCommonSingleCell(1)\n ,fEmcalTrackDistanceCut(15.0)\n ,fEmcalTrackDxCut(5.0)\n ,fEmcalTrackDzCut(5.0)\n ,fPhosTrackDistanceCut(10.0) \n ,fPhosTrackDxCut(8.0)\n ,fPhosTrackDzCut(3.0)\n ,fPhosTrackRCut(5.0)\n ,fPhosBadDistanceCut(3.0)\n \n ,fGeometryPhosEtaAccCut(0.12)\n ,fGeometryPhosPhiAccMinCut(-100)\/\/260.0)\n ,fGeometryPhosPhiAccMaxCut(-40)\/\/320.0)\n ,fGeometryPhosDetectorRadius(460.0)\n\t\t\t\t \/\/\n ,fGeometryEmcalEtaAccCut(0.6)\n ,fGeometryEmcalPhiAccMinCut(80.0) \/\/ rad 1.4\n ,fGeometryEmcalPhiAccMaxCut(120.0) \/\/ rad 2.1\n\t\t\t\t \/\/,fGeometryEmcalPhiAccMaxCut(180.0) \/\/ rad 3.14\n ,fGeometryEmcalDetectorRadius(440.0)\n\t\t\t\t \/\/\n ,fReconstructedVertexXCut(0.5)\n ,fReconstructedVertexYCut(0.5)\n ,fReconstructedVertexZCut(12.0)\n ,fReconstructedIPxyCut(1.5)\n ,fReconstructedIPzCut(1.5)\n ,fReconstructedNTpcClustersCut(30)\n ,fReconstructedNItsClustersCut(3)\n ,fReconstructedPidCut(0.0)\n\t\t\t\t \/\/\n ,fReconstructedPhosClusterType(-1)\n ,fReconstructedPhosClusterEnergyCut(0.25)\/\/ GeV\n ,fReconstructedPhosSingleCellEnergyCut(0.5)\n ,fReconstructedPhosTrackDistanceTightCut(3.0)\n ,fReconstructedPhosTrackDistanceMediumCut(5.0)\n ,fReconstructedPhosTrackDistanceLooseCut(15.0)\n\t\t\t\t \/\/\n ,fReconstructedEmcalClusterType(1)\n ,fReconstructedEmcalClusterEnergyCut(0.30) \/\/ GeV\n ,fReconstructedEmcalSingleCellEnergyCut(0.5)\n ,fReconstructedEmcalTrackDistanceTightCut(5.0)\n ,fReconstructedEmcalTrackDistanceMediumCut(10.0)\n ,fReconstructedEmcalTrackDistanceLooseCut(15.0)\n \n ,fMonteCarloSingleChargedParticle(3)\n ,fMonteCarloNeutralParticle(0)\n\n ,fHistMakeTree(kFALSE)\n ,fHistMakeTreeDeposit(kFALSE)\n ,fHistNbinsMult(2000)\n ,fHistMinMult(-0.5)\n ,fHistMaxMult(1999.5)\n ,fHistNbinsTotEt(10000)\n ,fHistMinTotEt(0.000)\n ,fHistMaxTotEt(1000)\n ,fHistNbinsParticleEt(5000)\n ,fHistMinParticleEt(0)\n ,fHistMaxParticleEt(500)\n ,fHistNbinsParticlePt(200) \n ,fHistMinParticlePt(0)\n ,fHistMaxParticlePt(20)\n \n ,fPrimaryVertexCutXY(4.0)\n ,fPrimaryVertexCutZ(20.0)\n{ \/\/ ctor\n}\n\nAliAnalysisEtCuts::~AliAnalysisEtCuts()\n{ \/\/ dtor\n}\n\nvoid AliAnalysisEtCuts::SetPbPbDefaults()\n{ \/\/ just increase seom histogram max values for now\n \/\/ enough to multiply conservative p+p defaults by a factor 100?\n fHistMaxMult = 20000;\n fHistMaxTotEt = 10000;\n}\n\n\nslightly reducing PHOS acceptance used\/\/_________________________________________________________________________\n\/\/ Utility Class for transverse energy studies\n\/\/ Base class for ESD & MC analysis\n\/\/ - cuts for reconstruction and MonteCarlo \n\/\/ implementation file\n\/\/ \n\/\/*-- Authors: Oystein Djuvsland (Bergen), David Silvermyr (ORNL)\n\/\/_________________________________________________________________________\n\n#include \"AliAnalysisEtCuts.h\"\n\n#include \n#include \"TNamed.h\"\n\nusing namespace std;\n\nClassImp(AliAnalysisEtCuts);\n\n\nAliAnalysisEtCuts::AliAnalysisEtCuts() : \n TNamed()\n\t\t\t\t \/\/\n ,fCommonEtaCut(0.5)\n ,fCommonClusterEnergyCut(0.15)\n ,fCommonTrackPtCut(0.0)\n ,fCommonSingleCell(1)\n ,fEmcalTrackDistanceCut(15.0)\n ,fEmcalTrackDxCut(5.0)\n ,fEmcalTrackDzCut(5.0)\n ,fPhosTrackDistanceCut(10.0) \n ,fPhosTrackDxCut(8.0)\n ,fPhosTrackDzCut(3.0)\n ,fPhosTrackRCut(5.0)\n ,fPhosBadDistanceCut(3.0)\n \n ,fGeometryPhosEtaAccCut(0.1)\/\/gives wiggle room\n ,fGeometryPhosPhiAccMinCut(-100)\/\/260.0)\n ,fGeometryPhosPhiAccMaxCut(-40)\/\/320.0)\n ,fGeometryPhosDetectorRadius(460.0)\n\t\t\t\t \/\/\n ,fGeometryEmcalEtaAccCut(0.6)\n ,fGeometryEmcalPhiAccMinCut(80.0) \/\/ rad 1.4\n ,fGeometryEmcalPhiAccMaxCut(120.0) \/\/ rad 2.1\n\t\t\t\t \/\/,fGeometryEmcalPhiAccMaxCut(180.0) \/\/ rad 3.14\n ,fGeometryEmcalDetectorRadius(440.0)\n\t\t\t\t \/\/\n ,fReconstructedVertexXCut(0.5)\n ,fReconstructedVertexYCut(0.5)\n ,fReconstructedVertexZCut(12.0)\n ,fReconstructedIPxyCut(1.5)\n ,fReconstructedIPzCut(1.5)\n ,fReconstructedNTpcClustersCut(30)\n ,fReconstructedNItsClustersCut(3)\n ,fReconstructedPidCut(0.0)\n\t\t\t\t \/\/\n ,fReconstructedPhosClusterType(-1)\n ,fReconstructedPhosClusterEnergyCut(0.25)\/\/ GeV\n ,fReconstructedPhosSingleCellEnergyCut(0.5)\n ,fReconstructedPhosTrackDistanceTightCut(3.0)\n ,fReconstructedPhosTrackDistanceMediumCut(5.0)\n ,fReconstructedPhosTrackDistanceLooseCut(15.0)\n\t\t\t\t \/\/\n ,fReconstructedEmcalClusterType(1)\n ,fReconstructedEmcalClusterEnergyCut(0.30) \/\/ GeV\n ,fReconstructedEmcalSingleCellEnergyCut(0.5)\n ,fReconstructedEmcalTrackDistanceTightCut(5.0)\n ,fReconstructedEmcalTrackDistanceMediumCut(10.0)\n ,fReconstructedEmcalTrackDistanceLooseCut(15.0)\n \n ,fMonteCarloSingleChargedParticle(3)\n ,fMonteCarloNeutralParticle(0)\n\n ,fHistMakeTree(kFALSE)\n ,fHistMakeTreeDeposit(kFALSE)\n ,fHistNbinsMult(2000)\n ,fHistMinMult(-0.5)\n ,fHistMaxMult(1999.5)\n ,fHistNbinsTotEt(10000)\n ,fHistMinTotEt(0.000)\n ,fHistMaxTotEt(1000)\n ,fHistNbinsParticleEt(5000)\n ,fHistMinParticleEt(0)\n ,fHistMaxParticleEt(500)\n ,fHistNbinsParticlePt(200) \n ,fHistMinParticlePt(0)\n ,fHistMaxParticlePt(20)\n \n ,fPrimaryVertexCutXY(4.0)\n ,fPrimaryVertexCutZ(20.0)\n{ \/\/ ctor\n}\n\nAliAnalysisEtCuts::~AliAnalysisEtCuts()\n{ \/\/ dtor\n}\n\nvoid AliAnalysisEtCuts::SetPbPbDefaults()\n{ \/\/ just increase seom histogram max values for now\n \/\/ enough to multiply conservative p+p defaults by a factor 100?\n fHistMaxMult = 20000;\n fHistMaxTotEt = 10000;\n}\n\n\n<|endoftext|>"} {"text":"\/\/ Time: O(1), per operation.\n\/\/ Space: O(k), k is the capacity of cache.\n\nclass LFUCache {\npublic:\n LFUCache(int capacity) : capa_(capacity), size_(0) {\n }\n \n int get(int key) {\n if (!key_to_nodeit_.count(key)) {\n return -1;\n }\n \n auto new_node = *key_to_nodeit_[key]; \n auto& freq = std::get(new_node);\n freq_to_nodes_[freq].erase(key_to_nodeit_[key]);\n if (freq_to_nodes_[freq].empty()) {\n freq_to_nodes_.erase(freq);\n if (min_freq_ == freq) {\n ++min_freq_;\n }\n }\n ++freq;\n freq_to_nodes_[freq].emplace_back(new_node);\n key_to_nodeit_[key] = prev(freq_to_nodes_[freq].end());\n\n return std::get(*key_to_nodeit_[key]);\n }\n \n void put(int key, int value) {\n if (capa_ <= 0) {\n return;\n }\n\n if (get(key) != -1) {\n std::get<1>(*key_to_nodeit_[key]) = value;\n return;\n }\n \n if (size_ == capa_) {\n key_to_nodeit_.erase(std::get(freq_to_nodes_[min_freq_].front()));\n freq_to_nodes_[min_freq_].pop_front();\n if (freq_to_nodes_[min_freq_].empty()) {\n freq_to_nodes_.erase(min_freq_);\n }\n --size_;\n }\n \n min_freq_ = 1;\n freq_to_nodes_[min_freq_].emplace_back(make_tuple(key, value, min_freq_));\n key_to_nodeit_[key] = prev(freq_to_nodes_[min_freq_].end());\n ++size_;\n }\n\nprivate:\n enum Data {KEY, VAL, FREQ}; \n int capa_;\n int size_;\n int min_freq_;\n unordered_map>> freq_to_nodes_; \/\/ freq to list of {key, val, freq}\n unordered_map>::iterator> key_to_nodeit_; \/\/ key to list iterator\n};\n\n\/**\n * Your LFUCache object will be instantiated and called as such:\n * LFUCache obj = new LFUCache(capacity);\n * int param_1 = obj.get(key);\n * obj.put(key,value);\n *\/\nUpdate lfu-cache.cpp\/\/ Time: O(1), per operation.\n\/\/ Space: O(k), k is the capacity of cache.\n\nclass LFUCache {\npublic:\n LFUCache(int capacity) : capa_(capacity), size_(0) {\n }\n \n int get(int key) {\n if (!key_to_nodeit_.count(key)) {\n return -1;\n }\n \n auto new_node = *key_to_nodeit_[key]; \n auto& freq = std::get(new_node);\n freq_to_nodes_[freq].erase(key_to_nodeit_[key]);\n if (freq_to_nodes_[freq].empty()) {\n freq_to_nodes_.erase(freq);\n if (min_freq_ == freq) {\n ++min_freq_;\n }\n }\n ++freq;\n freq_to_nodes_[freq].emplace_back(new_node);\n key_to_nodeit_[key] = prev(freq_to_nodes_[freq].end());\n\n return std::get(*key_to_nodeit_[key]);\n }\n \n void put(int key, int value) {\n if (capa_ <= 0) {\n return;\n }\n\n if (get(key) != -1) {\n std::get(*key_to_nodeit_[key]) = value;\n return;\n }\n \n if (size_ == capa_) {\n key_to_nodeit_.erase(std::get(freq_to_nodes_[min_freq_].front()));\n freq_to_nodes_[min_freq_].pop_front();\n if (freq_to_nodes_[min_freq_].empty()) {\n freq_to_nodes_.erase(min_freq_);\n }\n --size_;\n }\n \n min_freq_ = 1;\n freq_to_nodes_[min_freq_].emplace_back(make_tuple(key, value, min_freq_));\n key_to_nodeit_[key] = prev(freq_to_nodes_[min_freq_].end());\n ++size_;\n }\n\nprivate:\n enum Data {KEY, VAL, FREQ}; \n int capa_;\n int size_;\n int min_freq_;\n unordered_map>> freq_to_nodes_; \/\/ freq to list of {key, val, freq}\n unordered_map>::iterator> key_to_nodeit_; \/\/ key to list iterator\n};\n\n\/**\n * Your LFUCache object will be instantiated and called as such:\n * LFUCache obj = new LFUCache(capacity);\n * int param_1 = obj.get(key);\n * obj.put(key,value);\n *\/\n<|endoftext|>"} {"text":"#include \"NNConfig.h\"\r\n#include \"NNApplication.h\"\r\n#include \"NNLabel.h\"\r\n\r\n#include \"UImanager.h\"\r\n\r\n#include \"Maincharacter.h\"\r\n\r\nUImanager* UImanager::m_pInstance = nullptr;\r\n\r\nUImanager* UImanager::GetInstance()\r\n{\r\n\tif ( m_pInstance == nullptr )\r\n\t{\r\n\t\tm_pInstance = new UImanager();\r\n\t}\r\n\r\n\treturn m_pInstance;\r\n}\r\n\r\nvoid UImanager::ReleaseInstance()\r\n{\r\n\tif ( m_pInstance != nullptr )\r\n\t{\r\n\t\tdelete m_pInstance;\r\n\t\tm_pInstance = nullptr;\r\n\t}\r\n}\r\n\r\nUImanager::UImanager(void)\r\n{\r\n\tm_UINum = 0;\t\t\/\/ UI īƮ\r\n\r\n\t\/\/ FPS\r\n\tm_FPSLabel = NNLabel::Create( L\"FPS : \", L\" \", 20.f );\r\n\tm_FPSLabel->SetPosition( 0.f, 0.f );\r\n\tm_UIList[m_UINum++] = m_FPSLabel;\r\n\r\n\t\/\/ cost\r\n\tm_Player1CostLabel = NNLabel::Create( L\"Player1's Cost : \", L\" \", 20.f );\r\n\tm_Player1CostLabel->SetPosition( 0.f, 700.f );\r\n\tm_UIList[m_UINum++] = m_Player1CostLabel;\r\n\t\r\n\tm_Player2CostLabel = NNLabel::Create( L\"Player2's Cost : \", L\" \", 20.f );\r\n\tm_Player2CostLabel->SetPosition( 0.f, 100.f );\r\n\tm_UIList[m_UINum++] = m_Player2CostLabel;\r\n}\r\n\r\n\r\nUImanager::~UImanager(void)\r\n{\r\n\tfor (int i = 0; i < m_UINum; ++i)\r\n\t{\r\n\t\tdelete m_UIList[i];\r\n\t}\r\n}\r\n\r\nvoid UImanager::Update( float dTime, CMaincharacter* Player1, CMaincharacter* Player2 )\r\n{\r\n\t\/\/ FPS\r\n\tswprintf_s( m_FPSBuffer, _countof(m_FPSBuffer), L\"FPS : %0.3f\", NNApplication::GetInstance()->GetFPS() );\r\n\tm_FPSLabel->SetString( m_FPSBuffer );\r\n\r\n\t\/\/ cost\r\n\tswprintf_s( m_Player1CostBuffer, _countof(m_Player1CostBuffer), L\"Player1's Cost : %d\", (int)(Player1->GetCost()) );\r\n\tm_Player1CostLabel->SetString( m_Player1CostBuffer );\r\n\tswprintf_s( m_Player2CostBuffer, _countof(m_Player2CostBuffer), L\"Player2's Cost : %d\", (int)(Player2->GetCost()) );\r\n\tm_Player2CostLabel->SetString( m_Player2CostBuffer );\r\n}\r\n\r\nvoid UImanager::SetAllVisible( bool visible )\r\n{\r\n\tfor (int i = 0; i < m_UINum; ++i)\r\n\t{\r\n\t\tm_UIList[i]->SetVisible( visible );\r\n\t}\r\n}\r\n\r\nvoid UImanager::Render()\r\n{\r\n\tfor (int i = 0; i < m_UINum; ++i)\r\n\t{\r\n\t\tm_UIList[i]->Render();\r\n\t}\r\n}\r\n!! delete -> SafeDelete#include \"NNConfig.h\"\r\n#include \"NNApplication.h\"\r\n#include \"NNLabel.h\"\r\n\r\n#include \"UImanager.h\"\r\n\r\n#include \"Maincharacter.h\"\r\n\r\nUImanager* UImanager::m_pInstance = nullptr;\r\n\r\nUImanager* UImanager::GetInstance()\r\n{\r\n\tif ( m_pInstance == nullptr )\r\n\t{\r\n\t\tm_pInstance = new UImanager();\r\n\t}\r\n\r\n\treturn m_pInstance;\r\n}\r\n\r\nvoid UImanager::ReleaseInstance()\r\n{\r\n\tif ( m_pInstance != nullptr )\r\n\t{\r\n\t\tdelete m_pInstance;\r\n\t\tm_pInstance = nullptr;\r\n\t}\r\n}\r\n\r\nUImanager::UImanager(void)\r\n{\r\n\tm_UINum = 0;\t\t\/\/ UI īƮ\r\n\r\n\t\/\/ FPS\r\n\tm_FPSLabel = NNLabel::Create( L\"FPS : \", L\" \", 20.f );\r\n\tm_FPSLabel->SetPosition( 0.f, 0.f );\r\n\tm_UIList[m_UINum++] = m_FPSLabel;\r\n\r\n\t\/\/ cost\r\n\tm_Player1CostLabel = NNLabel::Create( L\"Player1's Cost : \", L\" \", 20.f );\r\n\tm_Player1CostLabel->SetPosition( 0.f, 700.f );\r\n\tm_UIList[m_UINum++] = m_Player1CostLabel;\r\n\t\r\n\tm_Player2CostLabel = NNLabel::Create( L\"Player2's Cost : \", L\" \", 20.f );\r\n\tm_Player2CostLabel->SetPosition( 0.f, 100.f );\r\n\tm_UIList[m_UINum++] = m_Player2CostLabel;\r\n}\r\n\r\n\r\nUImanager::~UImanager(void)\r\n{\r\n\tfor (int i = 0; i < m_UINum; ++i)\r\n\t{\r\n\t\tSafeDelete(m_UIList[i]);\r\n\t}\r\n}\r\n\r\nvoid UImanager::Update( float dTime, CMaincharacter* Player1, CMaincharacter* Player2 )\r\n{\r\n\t\/\/ FPS\r\n\tswprintf_s( m_FPSBuffer, _countof(m_FPSBuffer), L\"FPS : %0.3f\", NNApplication::GetInstance()->GetFPS() );\r\n\tm_FPSLabel->SetString( m_FPSBuffer );\r\n\r\n\t\/\/ cost\r\n\tswprintf_s( m_Player1CostBuffer, _countof(m_Player1CostBuffer), L\"Player1's Cost : %d\", (int)(Player1->GetCost()) );\r\n\tm_Player1CostLabel->SetString( m_Player1CostBuffer );\r\n\tswprintf_s( m_Player2CostBuffer, _countof(m_Player2CostBuffer), L\"Player2's Cost : %d\", (int)(Player2->GetCost()) );\r\n\tm_Player2CostLabel->SetString( m_Player2CostBuffer );\r\n}\r\n\r\nvoid UImanager::SetAllVisible( bool visible )\r\n{\r\n\tfor (int i = 0; i < m_UINum; ++i)\r\n\t{\r\n\t\tm_UIList[i]->SetVisible( visible );\r\n\t}\r\n}\r\n\r\nvoid UImanager::Render()\r\n{\r\n\tfor (int i = 0; i < m_UINum; ++i)\r\n\t{\r\n\t\tm_UIList[i]->Render();\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"\/* ------------------------------------------------------------------------ *\/\n\/* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\/\n\/* not use this file except in compliance with the License. You may obtain *\/\n\/* a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\/\n\/* See the License for the specific language governing permissions and *\/\n\/* limitations under the License. *\/\n\/* -------------------------------------------------------------------------*\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ This file includes the SQL schema defintion for OpenNebula objects\n\/\/ -----------------------------------------------------------------------------\nnamespace one_db\n{\n \/* ---------------------------------------------------------------------- *\/\n \/* HOST TABLES *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * host_table = \"host_pool\";\n\n const char * host_db_names = \"oid, name, body, state, uid, gid, owner_u, \"\n \"group_u, other_u, cid\";\n\n const char * host_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS host_pool (\"\n \" oid INTEGER PRIMARY KEY, \"\n \" name VARCHAR(128),\"\n \" body MEDIUMTEXT,\"\n \" state INTEGER,\"\n \" uid INTEGER,\"\n \" gid INTEGER,\"\n \" owner_u INTEGER,\"\n \" group_u INTEGER,\"\n \" other_u INTEGER,\"\n \" cid INTEGER)\";\n\n const char * host_monitor_table = \"host_monitoring\";\n\n const char * host_monitor_db_names = \"hid, last_mon_time, body\";\n\n const char * host_monitor_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS host_monitoring (\"\n \" hid INTEGER,\"\n \" last_mon_time INTEGER,\"\n \" body MEDIUMTEXT,\"\n \" PRIMARY KEY(hid, last_mon_time))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* VM TABLES *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * vm_table = \"vm_pool\";\n\n const char * vm_db_names =\n \"oid, name, body, uid, gid, state, lcm_state, \"\n \"owner_u, group_u, other_u, short_body, search_token\";\n\n const char * vm_db_bootstrap = \"CREATE TABLE IF NOT EXISTS \"\n \"vm_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, \"\n \"uid INTEGER, gid INTEGER, state INTEGER, \"\n \"lcm_state INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"short_body MEDIUMTEXT, search_token MEDIUMTEXT\";\n\n const char * vm_monitor_table = \"vm_monitoring\";\n\n const char * vm_monitor_db_names = \"vmid, last_poll, body\";\n\n const char * vm_monitor_db_bootstrap = \"CREATE TABLE IF NOT EXISTS \"\n \"vm_monitoring (vmid INTEGER, last_poll INTEGER, body MEDIUMTEXT, \"\n \"PRIMARY KEY(vmid, last_poll))\";\n\n\n const char * vm_showback_table = \"vm_showback\";\n\n const char * vm_showback_db_names = \"vmid, year, month, body\";\n\n const char * vm_showback_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS vm_showback \"\n \"(vmid INTEGER, year INTEGER, month INTEGER, body MEDIUMTEXT, \"\n \"PRIMARY KEY(vmid, year, month))\";\n\n const char * vm_import_table = \"vm_import\";\n\n const char * vm_import_db_names = \"deploy_id, vmid\";\n\n const char * vm_import_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS vm_import \"\n \"(deploy_id VARCHAR(128), vmid INTEGER, PRIMARY KEY(deploy_id))\";\n\n\n const char * vm_group_table = \"vmgroup_pool\";\n\n const char * vm_group_db_names = \"oid, name, body, uid, gid, owner_u, group_u, \"\n \"other_u\";\n\n const char * vm_group_db_bootstrap = \"CREATE TABLE IF NOT EXISTS vmgroup_pool \"\n \"(oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, \"\n \"uid INTEGER, gid INTEGER, owner_u INTEGER, group_u INTEGER, \"\n \"other_u INTEGER, UNIQUE(name,uid))\";\n\n const char * vm_template_table = \"template_pool\";\n\n const char * vm_template_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * vm_template_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS template_pool (oid INTEGER PRIMARY KEY, \"\n \"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, \"\n \"owner_u INTEGER, group_u INTEGER, other_u INTEGER)\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Cluster tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * cluster_table = \"cluster_pool\";\n\n const char * cluster_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * cluster_db_bootstrap = \"CREATE TABLE IF NOT EXISTS cluster_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name))\";\n\n const char * cluster_datastore_table = \"cluster_datastore_relation\";\n const char * cluster_datastore_db_names = \"cid, oid\";\n const char * cluster_datastore_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS cluster_datastore_relation (\"\n \"cid INTEGER, oid INTEGER, PRIMARY KEY(cid, oid))\";\n\n const char * cluster_network_table = \"cluster_network_relation\";\n const char * cluster_network_db_names = \"cid, oid\";\n const char * cluster_network_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS cluster_network_relation (\"\n \"cid INTEGER, oid INTEGER, PRIMARY KEY(cid, oid))\";\n\n const char * cluster_bitmap_table = \"cluster_vnc_bitmap\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* ACL tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * acl_table = \"acl\";\n\n const char * acl_db_names = \"oid, user, resource, rights, zone\";\n\n const char * acl_db_bootstrap = \"CREATE TABLE IF NOT EXISTS \"\n \"acl (oid INT PRIMARY KEY, user BIGINT, resource BIGINT, \"\n \"rights BIGINT, zone BIGINT, UNIQUE(user, resource, rights, zone))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Datastore tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * ds_table = \"datastore_pool\";\n\n const char * ds_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * ds_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS datastore_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER)\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Document tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * doc_table = \"document_pool\";\n\n const char * doc_db_names =\n \"oid, name, body, type, uid, gid, owner_u, group_u, other_u\";\n\n const char * doc_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS document_pool (oid INTEGER PRIMARY KEY, \"\n \"name VARCHAR(128), body MEDIUMTEXT, type INTEGER, uid INTEGER, gid INTEGER, \"\n \"owner_u INTEGER, group_u INTEGER, other_u INTEGER)\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Group tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * group_table = \"group_pool\";\n\n const char * group_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * group_db_bootstrap = \"CREATE TABLE IF NOT EXISTS group_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* History tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * history_table = \"history\";\n\n const char * history_db_names = \"vid, seq, body, stime, etime\";\n\n const char * history_db_bootstrap = \"CREATE TABLE IF NOT EXISTS \"\n \"history (vid INTEGER, seq INTEGER, body MEDIUMTEXT, \"\n \"stime INTEGER, etime INTEGER,PRIMARY KEY(vid,seq))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Hook tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * hook_table = \"hook_pool\";\n\n const char * hook_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u, type\";\n\n const char * hook_db_bootstrap = \"CREATE TABLE IF NOT EXISTS hook_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER,\"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, type INTEGER)\";\n\n const char * hook_log_table = \"hook_log\";\n\n const char * hook_log_db_names = \"hkid, exeid, timestamp, rc, body\";\n\n const char * hook_log_db_bootstrap = \"CREATE TABLE IF NOT EXISTS hook_log\"\n \" (hkid INTEGER, exeid INTEGER, timestamp INTEGER, rc INTEGER,\"\n \" body MEDIUMTEXT,PRIMARY KEY(hkid, exeid))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Image tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * image_table = \"image_pool\";\n\n const char * image_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * image_db_bootstrap = \"CREATE TABLE IF NOT EXISTS image_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name,uid) )\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Log tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * log_table = \"logdb\";\n\n const char * log_db_names = \"log_index, term, sqlcmd, timestamp, fed_index, applied\";\n\n const char * log_db_bootstrap = \"CREATE TABLE IF NOT EXISTS \"\n \"logdb (log_index BIGINT UNSIGNED PRIMARY KEY, term INTEGER, sqlcmd MEDIUMTEXT, \"\n \"timestamp INTEGER, fed_index BIGINT UNSIGNED, applied BOOLEAN)\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Marketplace tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * mp_table = \"marketplace_pool\";\n\n const char * mp_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * mp_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS marketplace_pool (oid INTEGER PRIMARY KEY, \"\n \"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, \"\n \"owner_u INTEGER, group_u INTEGER, other_u INTEGER)\";\n\n const char * mp_app_table = \"marketplaceapp_pool\";\n\n const char * mp_app_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * mp_app_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS marketplaceapp_pool (oid INTEGER PRIMARY KEY, \"\n \"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, \"\n \"owner_u INTEGER, group_u INTEGER, other_u INTEGER, UNIQUE(name,uid))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Quotas tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * group_quotas_db_table = \"group_quotas\";\n const char * group_quotas_db_names = \"group_oid, body\";\n const char * group_quotas_db_oid_column = \"group_oid\";\n const char * group_quotas_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS group_quotas (\"\n \"group_oid INTEGER PRIMARY KEY, body MEDIUMTEXT)\";\n\n const char * user_quotas_db_table = \"user_quotas\";\n const char * user_quotas_db_names = \"user_oid, body\";\n const char * user_quotas_db_oid_column = \"user_oid\";\n const char * user_quotas_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS user_quotas (\"\n \"user_oid INTEGER PRIMARY KEY, body MEDIUMTEXT)\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Security Group tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * sg_table = \"secgroup_pool\";\n\n const char * sg_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * sg_db_bootstrap = \"CREATE TABLE IF NOT EXISTS secgroup_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name,uid))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* User tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * user_table = \"user_pool\";\n\n const char * user_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * user_db_bootstrap = \"CREATE TABLE IF NOT EXISTS user_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* VDC tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * vdc_table = \"vdc_pool\";\n\n const char * vdc_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * vdc_db_bootstrap = \"CREATE TABLE IF NOT EXISTS vdc_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Virtual Network tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * vn_table = \"network_pool\";\n\n const char * vn_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u, pid\";\n\n const char * vn_db_bootstrap = \"CREATE TABLE IF NOT EXISTS\"\n \" network_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128),\"\n \" body MEDIUMTEXT, uid INTEGER, gid INTEGER,\"\n \" owner_u INTEGER, group_u INTEGER, other_u INTEGER,\"\n \" pid INTEGER, UNIQUE(name,uid))\";\n\n const char * vn_template_table = \"vn_template_pool\";\n\n const char * vn_template_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * vn_template_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS vn_template_pool (oid INTEGER PRIMARY KEY, \"\n \"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, \"\n \"owner_u INTEGER, group_u INTEGER, other_u INTEGER)\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Virtual Router tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * vr_table = \"vrouter_pool\";\n\n const char * vr_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * vr_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS vrouter_pool (oid INTEGER PRIMARY KEY, \"\n \"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, \"\n \"owner_u INTEGER, group_u INTEGER, other_u INTEGER)\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Zone tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * zone_table = \"zone_pool\";\n\n const char * zone_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * zone_db_bootstrap = \"CREATE TABLE IF NOT EXISTS zone_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name))\";\n}\nB #5025: Use user_oid column in acl table (#147)\/* ------------------------------------------------------------------------ *\/\n\/* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\/\n\/* not use this file except in compliance with the License. You may obtain *\/\n\/* a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\/\n\/* See the License for the specific language governing permissions and *\/\n\/* limitations under the License. *\/\n\/* -------------------------------------------------------------------------*\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ This file includes the SQL schema defintion for OpenNebula objects\n\/\/ -----------------------------------------------------------------------------\nnamespace one_db\n{\n \/* ---------------------------------------------------------------------- *\/\n \/* HOST TABLES *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * host_table = \"host_pool\";\n\n const char * host_db_names = \"oid, name, body, state, uid, gid, owner_u, \"\n \"group_u, other_u, cid\";\n\n const char * host_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS host_pool (\"\n \" oid INTEGER PRIMARY KEY, \"\n \" name VARCHAR(128),\"\n \" body MEDIUMTEXT,\"\n \" state INTEGER,\"\n \" uid INTEGER,\"\n \" gid INTEGER,\"\n \" owner_u INTEGER,\"\n \" group_u INTEGER,\"\n \" other_u INTEGER,\"\n \" cid INTEGER)\";\n\n const char * host_monitor_table = \"host_monitoring\";\n\n const char * host_monitor_db_names = \"hid, last_mon_time, body\";\n\n const char * host_monitor_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS host_monitoring (\"\n \" hid INTEGER,\"\n \" last_mon_time INTEGER,\"\n \" body MEDIUMTEXT,\"\n \" PRIMARY KEY(hid, last_mon_time))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* VM TABLES *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * vm_table = \"vm_pool\";\n\n const char * vm_db_names =\n \"oid, name, body, uid, gid, state, lcm_state, \"\n \"owner_u, group_u, other_u, short_body, search_token\";\n\n const char * vm_db_bootstrap = \"CREATE TABLE IF NOT EXISTS \"\n \"vm_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, \"\n \"uid INTEGER, gid INTEGER, state INTEGER, \"\n \"lcm_state INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"short_body MEDIUMTEXT, search_token MEDIUMTEXT\";\n\n const char * vm_monitor_table = \"vm_monitoring\";\n\n const char * vm_monitor_db_names = \"vmid, last_poll, body\";\n\n const char * vm_monitor_db_bootstrap = \"CREATE TABLE IF NOT EXISTS \"\n \"vm_monitoring (vmid INTEGER, last_poll INTEGER, body MEDIUMTEXT, \"\n \"PRIMARY KEY(vmid, last_poll))\";\n\n\n const char * vm_showback_table = \"vm_showback\";\n\n const char * vm_showback_db_names = \"vmid, year, month, body\";\n\n const char * vm_showback_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS vm_showback \"\n \"(vmid INTEGER, year INTEGER, month INTEGER, body MEDIUMTEXT, \"\n \"PRIMARY KEY(vmid, year, month))\";\n\n const char * vm_import_table = \"vm_import\";\n\n const char * vm_import_db_names = \"deploy_id, vmid\";\n\n const char * vm_import_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS vm_import \"\n \"(deploy_id VARCHAR(128), vmid INTEGER, PRIMARY KEY(deploy_id))\";\n\n\n const char * vm_group_table = \"vmgroup_pool\";\n\n const char * vm_group_db_names = \"oid, name, body, uid, gid, owner_u, group_u, \"\n \"other_u\";\n\n const char * vm_group_db_bootstrap = \"CREATE TABLE IF NOT EXISTS vmgroup_pool \"\n \"(oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, \"\n \"uid INTEGER, gid INTEGER, owner_u INTEGER, group_u INTEGER, \"\n \"other_u INTEGER, UNIQUE(name,uid))\";\n\n const char * vm_template_table = \"template_pool\";\n\n const char * vm_template_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * vm_template_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS template_pool (oid INTEGER PRIMARY KEY, \"\n \"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, \"\n \"owner_u INTEGER, group_u INTEGER, other_u INTEGER)\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Cluster tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * cluster_table = \"cluster_pool\";\n\n const char * cluster_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * cluster_db_bootstrap = \"CREATE TABLE IF NOT EXISTS cluster_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name))\";\n\n const char * cluster_datastore_table = \"cluster_datastore_relation\";\n const char * cluster_datastore_db_names = \"cid, oid\";\n const char * cluster_datastore_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS cluster_datastore_relation (\"\n \"cid INTEGER, oid INTEGER, PRIMARY KEY(cid, oid))\";\n\n const char * cluster_network_table = \"cluster_network_relation\";\n const char * cluster_network_db_names = \"cid, oid\";\n const char * cluster_network_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS cluster_network_relation (\"\n \"cid INTEGER, oid INTEGER, PRIMARY KEY(cid, oid))\";\n\n const char * cluster_bitmap_table = \"cluster_vnc_bitmap\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* ACL tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * acl_table = \"acl\";\n\n const char * acl_db_names = \"oid, user_oid, resource, rights, zone\";\n\n const char * acl_db_bootstrap = \"CREATE TABLE IF NOT EXISTS \"\n \"acl (oid INT PRIMARY KEY, user_oid BIGINT, resource BIGINT, \"\n \"rights BIGINT, zone BIGINT, UNIQUE(user_oid, resource, rights, zone))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Datastore tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * ds_table = \"datastore_pool\";\n\n const char * ds_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * ds_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS datastore_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER)\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Document tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * doc_table = \"document_pool\";\n\n const char * doc_db_names =\n \"oid, name, body, type, uid, gid, owner_u, group_u, other_u\";\n\n const char * doc_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS document_pool (oid INTEGER PRIMARY KEY, \"\n \"name VARCHAR(128), body MEDIUMTEXT, type INTEGER, uid INTEGER, gid INTEGER, \"\n \"owner_u INTEGER, group_u INTEGER, other_u INTEGER)\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Group tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * group_table = \"group_pool\";\n\n const char * group_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * group_db_bootstrap = \"CREATE TABLE IF NOT EXISTS group_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* History tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * history_table = \"history\";\n\n const char * history_db_names = \"vid, seq, body, stime, etime\";\n\n const char * history_db_bootstrap = \"CREATE TABLE IF NOT EXISTS \"\n \"history (vid INTEGER, seq INTEGER, body MEDIUMTEXT, \"\n \"stime INTEGER, etime INTEGER,PRIMARY KEY(vid,seq))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Hook tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * hook_table = \"hook_pool\";\n\n const char * hook_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u, type\";\n\n const char * hook_db_bootstrap = \"CREATE TABLE IF NOT EXISTS hook_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER,\"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, type INTEGER)\";\n\n const char * hook_log_table = \"hook_log\";\n\n const char * hook_log_db_names = \"hkid, exeid, timestamp, rc, body\";\n\n const char * hook_log_db_bootstrap = \"CREATE TABLE IF NOT EXISTS hook_log\"\n \" (hkid INTEGER, exeid INTEGER, timestamp INTEGER, rc INTEGER,\"\n \" body MEDIUMTEXT,PRIMARY KEY(hkid, exeid))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Image tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * image_table = \"image_pool\";\n\n const char * image_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * image_db_bootstrap = \"CREATE TABLE IF NOT EXISTS image_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name,uid) )\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Log tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * log_table = \"logdb\";\n\n const char * log_db_names = \"log_index, term, sqlcmd, timestamp, fed_index, applied\";\n\n const char * log_db_bootstrap = \"CREATE TABLE IF NOT EXISTS \"\n \"logdb (log_index BIGINT UNSIGNED PRIMARY KEY, term INTEGER, sqlcmd MEDIUMTEXT, \"\n \"timestamp INTEGER, fed_index BIGINT UNSIGNED, applied BOOLEAN)\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Marketplace tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * mp_table = \"marketplace_pool\";\n\n const char * mp_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * mp_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS marketplace_pool (oid INTEGER PRIMARY KEY, \"\n \"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, \"\n \"owner_u INTEGER, group_u INTEGER, other_u INTEGER)\";\n\n const char * mp_app_table = \"marketplaceapp_pool\";\n\n const char * mp_app_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * mp_app_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS marketplaceapp_pool (oid INTEGER PRIMARY KEY, \"\n \"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, \"\n \"owner_u INTEGER, group_u INTEGER, other_u INTEGER, UNIQUE(name,uid))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Quotas tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * group_quotas_db_table = \"group_quotas\";\n const char * group_quotas_db_names = \"group_oid, body\";\n const char * group_quotas_db_oid_column = \"group_oid\";\n const char * group_quotas_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS group_quotas (\"\n \"group_oid INTEGER PRIMARY KEY, body MEDIUMTEXT)\";\n\n const char * user_quotas_db_table = \"user_quotas\";\n const char * user_quotas_db_names = \"user_oid, body\";\n const char * user_quotas_db_oid_column = \"user_oid\";\n const char * user_quotas_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS user_quotas (\"\n \"user_oid INTEGER PRIMARY KEY, body MEDIUMTEXT)\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Security Group tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * sg_table = \"secgroup_pool\";\n\n const char * sg_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * sg_db_bootstrap = \"CREATE TABLE IF NOT EXISTS secgroup_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name,uid))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* User tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * user_table = \"user_pool\";\n\n const char * user_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * user_db_bootstrap = \"CREATE TABLE IF NOT EXISTS user_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* VDC tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * vdc_table = \"vdc_pool\";\n\n const char * vdc_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * vdc_db_bootstrap = \"CREATE TABLE IF NOT EXISTS vdc_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name))\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Virtual Network tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * vn_table = \"network_pool\";\n\n const char * vn_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u, pid\";\n\n const char * vn_db_bootstrap = \"CREATE TABLE IF NOT EXISTS\"\n \" network_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128),\"\n \" body MEDIUMTEXT, uid INTEGER, gid INTEGER,\"\n \" owner_u INTEGER, group_u INTEGER, other_u INTEGER,\"\n \" pid INTEGER, UNIQUE(name,uid))\";\n\n const char * vn_template_table = \"vn_template_pool\";\n\n const char * vn_template_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * vn_template_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS vn_template_pool (oid INTEGER PRIMARY KEY, \"\n \"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, \"\n \"owner_u INTEGER, group_u INTEGER, other_u INTEGER)\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Virtual Router tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * vr_table = \"vrouter_pool\";\n\n const char * vr_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * vr_db_bootstrap =\n \"CREATE TABLE IF NOT EXISTS vrouter_pool (oid INTEGER PRIMARY KEY, \"\n \"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, \"\n \"owner_u INTEGER, group_u INTEGER, other_u INTEGER)\";\n\n \/* ---------------------------------------------------------------------- *\/\n \/* Zone tables *\/\n \/* ---------------------------------------------------------------------- *\/\n const char * zone_table = \"zone_pool\";\n\n const char * zone_db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\n const char * zone_db_bootstrap = \"CREATE TABLE IF NOT EXISTS zone_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name))\";\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n\n#include \"binary.hxx\"\n#include \"bitnode.hxx\"\n\nnamespace despairagus {\n\tnamespace bitwisetrie {\n\t\tusing std::cout;\n\t\tusing std::ostream;\n\n\t\ttemplate \n\t\tclass bitwisetrie final {\n\t\t\ttemplate\n\t\t\tusing conref = const B &;\n\n\t\t\tusing bitA = std::bitset;\n\t\t\tusing byte = unsigned char;\n\t\t\tusing bit = bool;\n\n\t\t\tconstexpr static const size_t limit{sizeof(A) << 3};\n\n\t\tpublic:\n\t\t\texplicit bitwisetrie(void) = delete;\n\n\t\tprivate:\n\t\t\tbitnode* root;\n\t\t};\n\t}\n}insert functionality#pragma once\n\n#include \n\n#include \"binary.hxx\"\n#include \"bitnode.hxx\"\n\nnamespace despairagus {\n\tnamespace bitwisetrie {\n\t\tusing std::cout;\n\t\tusing std::ostream;\n\n\t\ttemplate \n\t\tclass bitwisetrie final {\n\t\t\ttemplate\n\t\t\tusing conref = const B &;\n\n\t\t\tusing bitA = std::bitset;\n\t\t\tusing byte = unsigned char;\n\t\t\tusing bit = bool;\n\n\t\t\tconstexpr static const size_t limit{sizeof(A) << 3};\n\n\t\t\tstatic inline bitnode* navigate(bitnode* currNode, conref data) {\n\t\t\t\treturn bitwisetrie::navigate(currNode, data, 0);\n\t\t\t}\n\n\t\t\tstatic inline bitnode* navigate(bitnode* currNode, conref data, conref idx) {\n\t\t\t\tbinary bitHolder{data};\n\n\t\t\t\treturn bitwisetrie::navigate(currNode, data, bitHolder, idx);\n\t\t\t}\n\n\t\t\tstatic bitnode* navigate(bitnode* currNode, conref data, conref> bits, conref idx) {\n\t\t\t\tif (idx < limit) {\n\t\t\t\t\tif (bits.getBit(idx)) {\n\t\t\t\t\t\tif (currNode->getOne() == nullptr) {\n\t\t\t\t\t\t\tcurrNode->setOne(new bitnode);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn bitwisetrie::navigate(currNode->getOne(), data, bits, idx + 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (currNode->getZero() == nullptr) {\n\t\t\t\t\t\t\tcurrNode->setZero(new bitnode);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn bitwisetrie::navigate(currNode->getZero(), data, bits, idx + 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn currNode;\n\t\t\t}\n\n\t\tpublic:\n\t\t\texplicit bitwisetrie(void) : root{nullptr} {}\n\n\t\t\tbool insert(conref a) noexcept {\n\t\t\t\tbitnode* leafNode = bitwisetrie::navigate(root, a);\n\n\t\t\t\tif (leafNode->isNotEmpty()) {\n\t\t\t\t\tleafNode->setData(a);\n\t\t\t\t}\n\n\t\t\t\treturn leafNode->isEmpty();\n\t\t\t}\n\n\t\tprivate:\n\t\t\tbitnode* root;\n\t\t};\n\t}\n}<|endoftext|>"} {"text":"#pragma once\n\n#include \n\n#include \"binary.hxx\"\n#include \"bitnode.hxx\"\n\nnamespace despairagus {\n\tnamespace bitwisetrie {\n\t\tusing std::cout;\n\t\tusing std::ostream;\n\n\t\ttemplate \n\t\tclass bitwisetrie final {\n\t\t\ttemplate\n\t\t\tusing conref = const B &;\n\n\t\t\tusing bitA = std::bitset;\n\t\t\tusing byte = unsigned char;\n\t\t\tusing bit = bool;\n\n\t\t\tconstexpr static const size_t limit{sizeof(A) << 3};\n\n\t\t\tstatic inline bitnode* navigate(bitnode* currNode, conref data) {\n\t\t\t\treturn bitwisetrie::navigate(currNode, data, 0);\n\t\t\t}\n\n\t\t\tstatic inline bitnode* navigate(bitnode* currNode, conref data, conref idx) {\n\t\t\t\tbinary bitHolder{data};\n\n\t\t\t\treturn bitwisetrie::navigate(currNode, data, bitHolder, idx);\n\t\t\t}\n\n\t\t\tstatic bitnode* navigate(bitnode* currNode, conref data, conref> bits, conref idx) {\n\t\t\t\tif (idx < limit) {\n\t\t\t\t\tif (bits.getBit(idx)) {\n\t\t\t\t\t\tif (currNode->getOne() == nullptr) {\n\t\t\t\t\t\t\tcurrNode->setOne(new bitnode);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn bitwisetrie::navigate(currNode->getOne(), data, bits, idx + 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (currNode->getZero() == nullptr) {\n\t\t\t\t\t\t\tcurrNode->setZero(new bitnode);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn bitwisetrie::navigate(currNode->getZero(), data, bits, idx + 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn currNode;\n\t\t\t}\n\n\t\tpublic:\n\t\t\texplicit bitwisetrie(void) : root{new bitnode} {}\n\n\t\t\tbool insertOnEmpty(conref a) noexcept {\n\t\t\t\tbitnode* leafNode = bitwisetrie::navigate(root, a);\n\n\t\t\t\tif (leafNode->isEmpty()) {\n\t\t\t\t\tleafNode->setData(a);\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\tprivate:\n\t\t\tbitnode* root;\n\t\t};\n\t}\n}do not pass data since its not needed#pragma once\n\n#include \n\n#include \"binary.hxx\"\n#include \"bitnode.hxx\"\n\nnamespace despairagus {\n\tnamespace bitwisetrie {\n\t\tusing std::cout;\n\t\tusing std::ostream;\n\n\t\ttemplate \n\t\tclass bitwisetrie final {\n\t\t\ttemplate\n\t\t\tusing conref = const B &;\n\n\t\t\tusing bitA = std::bitset;\n\t\t\tusing byte = unsigned char;\n\t\t\tusing bit = bool;\n\n\t\t\tconstexpr static const size_t limit{sizeof(A) << 3};\n\n\t\t\tstatic inline bitnode* navigate(bitnode* currNode, conref data) {\n\t\t\t\treturn bitwisetrie::navigate(currNode, data, 0);\n\t\t\t}\n\n\t\t\tstatic inline bitnode* navigate(bitnode* currNode, conref data, conref idx) {\n\t\t\t\tbinary bitHolder{data};\n\n\t\t\t\treturn bitwisetrie::navigate(currNode, bitHolder, idx);\n\t\t\t}\n\n\t\t\tstatic bitnode* navigate(bitnode* currNode, conref> bits, conref idx) {\n\t\t\t\tif (idx < limit) {\n\t\t\t\t\tif (bits.getBit(idx)) {\n\t\t\t\t\t\tif (currNode->getOne() == nullptr) {\n\t\t\t\t\t\t\tcurrNode->setOne(new bitnode);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn bitwisetrie::navigate(currNode->getOne(), data, bits, idx + 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (currNode->getZero() == nullptr) {\n\t\t\t\t\t\t\tcurrNode->setZero(new bitnode);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn bitwisetrie::navigate(currNode->getZero(), data, bits, idx + 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn currNode;\n\t\t\t}\n\n\t\tpublic:\n\t\t\texplicit bitwisetrie(void) : root{new bitnode} {}\n\n\t\t\tbool insertOnEmpty(conref a) noexcept {\n\t\t\t\tbitnode* leafNode = bitwisetrie::navigate(root, a);\n\n\t\t\t\tif (leafNode->isEmpty()) {\n\t\t\t\t\tleafNode->setData(a);\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\tprivate:\n\t\t\tbitnode* root;\n\t\t};\n\t}\n}<|endoftext|>"} {"text":"#include \"application.h\"\nusing namespace AhoViewer;\n\n#include \"booru\/site.h\"\n#include \"config.h\"\n#include \"imagelist.h\"\n#include \"mainwindow.h\"\n#include \"settings.h\"\n\n#ifdef HAVE_LIBPEAS\n#include \"plugin\/manager.h\"\n#endif \/\/ HAVE_LIBPEAS\n\n#include \n\/\/ This can be removed once it's implemented in C++20\n#include \n#include \n#include \n#include \n\n#ifdef USE_OPENSSL\n#include \n#if (OPENSSL_VERSION_NUMBER < 0x10100000L)\n#include \n#include \n#include \n\nstd::deque locks;\n\nstatic void lock_callback(int mode, int type, const char*, int)\n{\n if ((mode & CRYPTO_LOCK))\n {\n if ((mode & CRYPTO_READ))\n locks[type].lock_shared();\n else\n locks[type].lock();\n }\n else\n {\n if ((mode & CRYPTO_READ))\n locks[type].unlock_shared();\n else\n locks[type].unlock();\n }\n}\n\nstatic unsigned long thread_id()\n{\n return static_cast(pthread_self());\n}\n\nstatic void init_openssl_locks()\n{\n locks.resize(CRYPTO_num_locks());\n CRYPTO_set_id_callback(&thread_id);\n CRYPTO_set_locking_callback(&lock_callback);\n}\n#endif \/\/ OPENSSL_VERSION_NUMBER < 0x10100000L\n#endif \/\/ USE_OPENSSL\n\n#ifdef USE_GNUTLS\n#include \n#if (GCRYPT_VERSION_NUMBER < 0x010600)\nGCRY_THREAD_OPTION_PTHREAD_IMPL;\n\nvoid init_gnutls_locks()\n{\n gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);\n}\n#endif \/\/ GCRYPT_VERSION_NUMBER < 0x010600\n#endif \/\/ USE_GNUTLS\n\n#ifdef HAVE_GSTREAMER\n#include \n#endif \/\/ HAVE_GSTREAMER\n\nApplication::Application()\n : Gtk::Application(\"com.github.ahodesuka.ahoviewer\", Gio::APPLICATION_HANDLES_OPEN)\n#ifdef HAVE_LIBPEAS\n ,\n m_PluginManager\n{\n std::make_unique()\n}\n#endif \/\/ HAVE_LIBPEAS\n{\n \/\/ Disgusting win32 api to start dbus-daemon and make it close when\n \/\/ the ahoviewer process ends\n#ifdef _WIN32\n HANDLE job = CreateJobObject(NULL, NULL);\n JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };\n PROCESS_INFORMATION pi = { 0 };\n STARTUPINFO si = { 0 };\n char cmd[] = \"dbus-daemon.exe --session\";\n\n jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;\n SetInformationJobObject(job, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli));\n si.cb = sizeof(si);\n\n if (CreateProcess(NULL,\n cmd,\n NULL,\n NULL,\n FALSE,\n CREATE_NO_WINDOW | CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB,\n NULL,\n NULL,\n &si,\n &pi))\n {\n AssignProcessToJobObject(job, pi.hProcess);\n ResumeThread(pi.hThread);\n }\n#endif \/\/ _WIN32\n \/\/ The ImageBox needs this, disabling it is silly unless proven otherwise\n Glib::setenv(\"GTK_OVERLAY_SCROLLING\", \"\", true);\n Glib::set_application_name(PACKAGE);\n\n signal_shutdown().connect(sigc::mem_fun(*this, &Application::on_shutdown));\n}\n\nApplication& Application::get_instance()\n{\n static Application app;\n return app;\n}\n\nMainWindow* Application::create_window()\n{\n Glib::RefPtr builder{ Gtk::Builder::create() };\n\n try\n {\n builder->add_from_resource(\"\/ui\/ahoviewer.ui\");\n }\n catch (const Glib::Error& ex)\n {\n std::cerr << \"Gtk::Builder::add_from_resource: \" << ex.what() << std::endl;\n return nullptr;\n }\n\n MainWindow* w{ nullptr };\n builder->get_widget_derived(\"MainWindow\", w);\n\n if (!w)\n throw std::runtime_error(\"Failed to create window\");\n\n auto window{ static_cast(w) };\n add_window(*window);\n\n return w;\n}\n\nint Application::run(int argc, char** argv)\n{\n register_application();\n\n if (!is_remote())\n {\n gtk_init(&argc, &argv);\n#ifdef HAVE_GSTREAMER\n gst_init(&argc, &argv);\n#endif \/\/ HAVE_GSTREAMER\n }\n\n return Gtk::Application::run(argc, argv);\n}\n\nvoid Application::on_activate()\n{\n auto w{ create_window() };\n\n if (get_windows().size() == 1)\n w->restore_last_file();\n\n Gtk::Application::on_activate();\n}\n\n\/\/ Finds the first window with no local image list or creates a\n\/\/ new window and then opens the file\nvoid Application::on_open(const std::vector>& f, const Glib::ustring&)\n{\n auto windows{ get_windows() };\n auto it{ std::find_if(windows.cbegin(), windows.cend(), [](Gtk::Window* w) {\n return static_cast(w)->m_LocalImageList->empty();\n }) };\n\n if (it == windows.cend())\n {\n auto w{ create_window() };\n w->open_file(f.front()->get_path());\n }\n else\n {\n static_cast(*it)->open_file(f.front()->get_path());\n }\n}\n\nvoid Application::on_startup()\n{\n LIBXML_TEST_VERSION\n\n curl_global_init(CURL_GLOBAL_DEFAULT);\n\n curl_version_info_data* ver_info{ curl_version_info(CURLVERSION_NOW) };\n std::string ssl_lib{ ver_info->ssl_version };\n\n#if defined(USE_OPENSSL) && (OPENSSL_VERSION_NUMBER < 0x10100000L)\n if (ssl_lib.find(\"OpenSSL\") != std::string::npos)\n init_openssl_locks();\n#endif \/\/ defined(USE_OPENSSL) && (OPENSSL_VERSION_NUMBER < 0x10100000L)\n\n#if defined(USE_GNUTLS) && GCRYPT_VERSION_NUMBER < 0x010600\n if (ssl_lib.find(\"GnuTLS\") != std::string::npos)\n init_gnutls_locks();\n#endif \/\/ defined(USE_GNUTLS) && GCRYPT_VERSION_NUMBER < 0x010600\n\n Gtk::Main::init_gtkmm_internals();\n\n Gtk::Application::on_startup();\n\n date::set_install(Glib::build_filename(Glib::get_user_cache_dir(), PACKAGE, \"tzdata\"));\n std::thread{ []() {\n try\n {\n date::get_tzdb();\n }\n catch (const std::runtime_error& e)\n {\n std::cerr << \"Failed to fetch IANA timezone database, times will be displayed in UTC\"\n << std::endl;\n }\n } }.detach();\n\n \/\/ Load this after plugins have been loaded so the active plugins can have their keybindings set\n Settings.load_keybindings();\n}\n\nvoid Application::on_window_added(Gtk::Window* w)\n{\n if (get_windows().size() == 0)\n static_cast(w)->m_OriginalWindow = true;\n\n Gtk::Application::on_window_added(w);\n}\n\nvoid Application::on_window_removed(Gtk::Window* w)\n{\n Gtk::Application::on_window_removed(w);\n delete w;\n\n auto windows{ get_windows() };\n\n \/\/ Set a new original window if the previous was closed\n if (windows.size() > 0)\n {\n auto it{ std::find_if(windows.cbegin(), windows.cend(), [](Gtk::Window* mw) {\n return static_cast(mw)->m_OriginalWindow;\n }) };\n\n if (it == windows.cend())\n static_cast(windows.front())->m_OriginalWindow = true;\n }\n}\n\nvoid Application::on_shutdown()\n{\n for (const std::shared_ptr& site : Settings.get_sites())\n site->save_tags();\n}\napplication: Remove CreateProcess call for dbus-daemon#include \"application.h\"\nusing namespace AhoViewer;\n\n#include \"booru\/site.h\"\n#include \"config.h\"\n#include \"imagelist.h\"\n#include \"mainwindow.h\"\n#include \"settings.h\"\n\n#ifdef HAVE_LIBPEAS\n#include \"plugin\/manager.h\"\n#endif \/\/ HAVE_LIBPEAS\n\n#include \n\/\/ This can be removed once it's implemented in C++20\n#include \n#include \n#include \n#include \n\n#ifdef USE_OPENSSL\n#include \n#if (OPENSSL_VERSION_NUMBER < 0x10100000L)\n#include \n#include \n#include \n\nstd::deque locks;\n\nstatic void lock_callback(int mode, int type, const char*, int)\n{\n if ((mode & CRYPTO_LOCK))\n {\n if ((mode & CRYPTO_READ))\n locks[type].lock_shared();\n else\n locks[type].lock();\n }\n else\n {\n if ((mode & CRYPTO_READ))\n locks[type].unlock_shared();\n else\n locks[type].unlock();\n }\n}\n\nstatic unsigned long thread_id()\n{\n return static_cast(pthread_self());\n}\n\nstatic void init_openssl_locks()\n{\n locks.resize(CRYPTO_num_locks());\n CRYPTO_set_id_callback(&thread_id);\n CRYPTO_set_locking_callback(&lock_callback);\n}\n#endif \/\/ OPENSSL_VERSION_NUMBER < 0x10100000L\n#endif \/\/ USE_OPENSSL\n\n#ifdef USE_GNUTLS\n#include \n#if (GCRYPT_VERSION_NUMBER < 0x010600)\nGCRY_THREAD_OPTION_PTHREAD_IMPL;\n\nvoid init_gnutls_locks()\n{\n gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);\n}\n#endif \/\/ GCRYPT_VERSION_NUMBER < 0x010600\n#endif \/\/ USE_GNUTLS\n\n#ifdef HAVE_GSTREAMER\n#include \n#endif \/\/ HAVE_GSTREAMER\n\nApplication::Application()\n : Gtk::Application(\"com.github.ahodesuka.ahoviewer\", Gio::APPLICATION_HANDLES_OPEN)\n#ifdef HAVE_LIBPEAS\n ,\n m_PluginManager\n{\n std::make_unique()\n}\n#endif \/\/ HAVE_LIBPEAS\n{\n \/\/ The ImageBox needs this, disabling it is silly unless proven otherwise\n Glib::setenv(\"GTK_OVERLAY_SCROLLING\", \"\", true);\n Glib::set_application_name(PACKAGE);\n\n signal_shutdown().connect(sigc::mem_fun(*this, &Application::on_shutdown));\n}\n\nApplication& Application::get_instance()\n{\n static Application app;\n return app;\n}\n\nMainWindow* Application::create_window()\n{\n Glib::RefPtr builder{ Gtk::Builder::create() };\n\n try\n {\n builder->add_from_resource(\"\/ui\/ahoviewer.ui\");\n }\n catch (const Glib::Error& ex)\n {\n std::cerr << \"Gtk::Builder::add_from_resource: \" << ex.what() << std::endl;\n return nullptr;\n }\n\n MainWindow* w{ nullptr };\n builder->get_widget_derived(\"MainWindow\", w);\n\n if (!w)\n throw std::runtime_error(\"Failed to create window\");\n\n auto window{ static_cast(w) };\n add_window(*window);\n\n return w;\n}\n\nint Application::run(int argc, char** argv)\n{\n register_application();\n\n if (!is_remote())\n {\n gtk_init(&argc, &argv);\n#ifdef HAVE_GSTREAMER\n gst_init(&argc, &argv);\n#endif \/\/ HAVE_GSTREAMER\n }\n\n return Gtk::Application::run(argc, argv);\n}\n\nvoid Application::on_activate()\n{\n auto w{ create_window() };\n\n if (get_windows().size() == 1)\n w->restore_last_file();\n\n Gtk::Application::on_activate();\n}\n\n\/\/ Finds the first window with no local image list or creates a\n\/\/ new window and then opens the file\nvoid Application::on_open(const std::vector>& f, const Glib::ustring&)\n{\n auto windows{ get_windows() };\n auto it{ std::find_if(windows.cbegin(), windows.cend(), [](Gtk::Window* w) {\n return static_cast(w)->m_LocalImageList->empty();\n }) };\n\n if (it == windows.cend())\n {\n auto w{ create_window() };\n w->open_file(f.front()->get_path());\n }\n else\n {\n static_cast(*it)->open_file(f.front()->get_path());\n }\n}\n\nvoid Application::on_startup()\n{\n LIBXML_TEST_VERSION\n\n curl_global_init(CURL_GLOBAL_DEFAULT);\n\n curl_version_info_data* ver_info{ curl_version_info(CURLVERSION_NOW) };\n std::string ssl_lib{ ver_info->ssl_version };\n\n#if defined(USE_OPENSSL) && (OPENSSL_VERSION_NUMBER < 0x10100000L)\n if (ssl_lib.find(\"OpenSSL\") != std::string::npos)\n init_openssl_locks();\n#endif \/\/ defined(USE_OPENSSL) && (OPENSSL_VERSION_NUMBER < 0x10100000L)\n\n#if defined(USE_GNUTLS) && GCRYPT_VERSION_NUMBER < 0x010600\n if (ssl_lib.find(\"GnuTLS\") != std::string::npos)\n init_gnutls_locks();\n#endif \/\/ defined(USE_GNUTLS) && GCRYPT_VERSION_NUMBER < 0x010600\n\n Gtk::Main::init_gtkmm_internals();\n\n Gtk::Application::on_startup();\n\n date::set_install(Glib::build_filename(Glib::get_user_cache_dir(), PACKAGE, \"tzdata\"));\n std::thread{ []() {\n try\n {\n date::get_tzdb();\n }\n catch (const std::runtime_error& e)\n {\n std::cerr << \"Failed to fetch IANA timezone database, times will be displayed in UTC\"\n << std::endl;\n }\n } }.detach();\n\n \/\/ Load this after plugins have been loaded so the active plugins can have their keybindings set\n Settings.load_keybindings();\n}\n\nvoid Application::on_window_added(Gtk::Window* w)\n{\n if (get_windows().size() == 0)\n static_cast(w)->m_OriginalWindow = true;\n\n Gtk::Application::on_window_added(w);\n}\n\nvoid Application::on_window_removed(Gtk::Window* w)\n{\n Gtk::Application::on_window_removed(w);\n delete w;\n\n auto windows{ get_windows() };\n\n \/\/ Set a new original window if the previous was closed\n if (windows.size() > 0)\n {\n auto it{ std::find_if(windows.cbegin(), windows.cend(), [](Gtk::Window* mw) {\n return static_cast(mw)->m_OriginalWindow;\n }) };\n\n if (it == windows.cend())\n static_cast(windows.front())->m_OriginalWindow = true;\n }\n}\n\nvoid Application::on_shutdown()\n{\n for (const std::shared_ptr& site : Settings.get_sites())\n site->save_tags();\n}\n<|endoftext|>"} {"text":"#include \"hdfscpp.h\"\n\n#include \n\n#include \n\n#include \"filebuf.h\"\n#include \n\n#include \n\/**********************************************************************\/\n\n\/** Reads a int written by java's DataOutput#writeInt\n *\n * FIXME Move to propper namespace\n *\/\ninline int32_t ReadInt(tmacam::filebuf* data) {\n\tassert(sizeof(int32_t) == 4);\n\tconst char* bytes = data->read(sizeof(int32_t));\n\treturn (((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16) |\n\t\t ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff));\n}\n\n \n\/**********************************************************************\/\n\/*\nclass HdfsDumpReader {\nprivate:\n \/\/ No copy, no atribution and no default constructor for this class\n DISALLOW_COPY_AND_ASSIGN(HdfsDumpReader);\n HdfsDumpReader();\n};\n*\/\n\n\/**********************************************************************\/\n\n\nvoid ShowUsage()\n{\n std::cerr << \"Usage: hdfsls \" << std::endl;\n}\n\nint main(int argc, char* argv[])\n{\n using namespace tmacam;\n\n \/\/ Check command line arguments\n if ( argc != 2) {\n std::cerr << \"Wrong number of arguments\" << std::endl;\n ShowUsage();\n exit(EXIT_FAILURE);\n }\n const char* path = argv[1];\n\n \/\/ Connect to HDFS \/ get filesystem handle\n hdfs::FileSystem fs; \n\n \/\/ Path is a file, right?\n if (!fs.Exists(path)) {\n std::cerr << \"Path '\" << path << \"' does not exist.\" << std::endl;\n exit(EXIT_FAILURE);\n }\n hdfs::FileInfoList path_info;\n fs.GetPathInfo(path, &path_info);\n if (path_info->mKind != kObjectKindFile ) {\n std::cerr << \"Path '\" << path << \"' is not a regular file.\"\n << std::endl;\n exit(EXIT_FAILURE);\n }\n\n \/\/\/ BEGIN reader code\n const size_t buff_size = 1<<20; \/\/ 1 MB\n std::vector buff(buff_size);\n\n size_t data_left_len = 0;\n\n hdfs::File file(fs, path, O_RDONLY, buff_size, 0, 0);\n for (size_t bytes_read = 0; bytes_read < path_info->mSize;) {\n tSize read_length = file.Pread(bytes_read, &buff[0], buff_size);\n bytes_read += read_length;\n\n tmacam::filebuf available_data(&buff[0], read_length);\n\n std::cout << \"READ \" << read_length << std::endl;\n\n try {\n while (!available_data.eof()) {\n \/\/ Save current progress\n data_left_len = available_data.len();\n\n int32_t payload_len = ReadInt(&available_data);\n const char* payload_data = available_data.read(payload_len);\n assert(payload_len + 2*sizeof(int32_t) < buff_size);\n int32_t expected_checksum = ReadInt(&available_data);\n\n#ifndef DUMPREADER_FAST_PASS\n \/\/ Calc CRC32\n uLong crc = crc32(0L, (const Bytef*)payload_data, payload_len);\n if (expected_checksum != static_cast(crc)) {\n std::cerr << \"CRC MISSMATCH -- found \" << crc << \n \" expected\" << expected_checksum <<\n std::endl; \n exit(EXIT_FAILURE);\n }\n#endif\n\n \n std::cout << \"P: \" << payload_len << std::endl;\n }\n } catch(std::out_of_range) {\n std::cout << \"ooops \" << std::endl;\n \/\/ not enough data... \n \/\/ rewind reading position\n bytes_read -= data_left_len;\n }\n }\n\n\n \/\/\/ END reader code\n \n\treturn 0;\n}\n\n\/\/ vim: et ai sts=4 ts=4 sw=4\nminor fix#include \"hdfscpp.h\"\n\n#include \n\n#include \n\n#include \"filebuf.h\"\n#include \n\n#include \n\/**********************************************************************\/\n\n\/** Reads a int written by java's DataOutput#writeInt\n *\n * FIXME Move to propper namespace\n *\/\ninline int32_t ReadInt(tmacam::filebuf* data) {\n\tassert(sizeof(int32_t) == 4);\n\tconst char* bytes = data->read(sizeof(int32_t));\n\treturn (((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16) |\n\t\t ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff));\n}\n\n \n\/**********************************************************************\/\n\/*\nclass HdfsDumpReader {\nprivate:\n \/\/ No copy, no atribution and no default constructor for this class\n DISALLOW_COPY_AND_ASSIGN(HdfsDumpReader);\n HdfsDumpReader();\n};\n*\/\n\n\/**********************************************************************\/\n\n\nvoid ShowUsage()\n{\n std::cerr << \"Usage: hdfsls \" << std::endl;\n}\n\nint main(int argc, char* argv[])\n{\n using namespace tmacam;\n\n \/\/ Check command line arguments\n if ( argc != 2) {\n std::cerr << \"Wrong number of arguments\" << std::endl;\n ShowUsage();\n exit(EXIT_FAILURE);\n }\n const char* path = argv[1];\n\n \/\/ Connect to HDFS \/ get filesystem handle\n hdfs::FileSystem fs; \n\n \/\/ Path is a file, right?\n if (!fs.Exists(path)) {\n std::cerr << \"Path '\" << path << \"' does not exist.\" << std::endl;\n exit(EXIT_FAILURE);\n }\n hdfs::FileInfoList path_info;\n fs.GetPathInfo(path, &path_info);\n if (path_info->mKind != kObjectKindFile ) {\n std::cerr << \"Path '\" << path << \"' is not a regular file.\"\n << std::endl;\n exit(EXIT_FAILURE);\n }\n\n \/\/\/ BEGIN reader code\n const size_t buff_size = 1<<20; \/\/ 1 MB\n std::vector buff(buff_size);\n\n size_t data_left_len = 0;\n\n hdfs::File file(fs, path, O_RDONLY, buff_size, 0, 0);\n for (size_t bytes_read = 0; bytes_read < path_info->mSize;) {\n \/* Using Pread() and exceptions for doing this is ugly and lame.\n * We should have used Read() and proper tests but, you know what,\n * this works and is easy to understand -- and this scores +1 in\n * my book.\n *\/\n tSize read_length = file.Pread(bytes_read, &buff[0], buff_size);\n bytes_read += read_length;\n\n tmacam::filebuf available_data(&buff[0], read_length);\n\n std::cout << \"READ \" << read_length << std::endl;\n\n try {\n while (!available_data.eof()) {\n \/\/ Save current progress\n data_left_len = available_data.len();\n \/\/ Read header, payload and CRC. Abort if payload is too big\n int32_t payload_len = ReadInt(&available_data);\n assert(payload_len + 2*sizeof(int32_t) < buff_size);\n const char* payload_data = available_data.read(payload_len);\n int32_t expected_checksum = ReadInt(&available_data);\n#ifndef DUMPREADER_FAST_PASS\n \/\/ Calc CRC32\n uLong crc = crc32(0L, (const Bytef*)payload_data, payload_len);\n if (expected_checksum != static_cast(crc)) {\n std::cerr << \"CRC MISSMATCH -- found \" << crc << \n \" expected\" << expected_checksum <<\n std::endl; \n exit(EXIT_FAILURE);\n }\n#endif\n std::cout << \"P: \" << payload_len << std::endl;\n }\n } catch(std::out_of_range) {\n std::cout << \"ooops \" << std::endl;\n \/\/ not enough data... \n \/\/ rewind reading position\n bytes_read -= data_left_len;\n }\n }\n\n\n \/\/\/ END reader code\n \n\treturn 0;\n}\n\n\/\/ vim: et ai sts=4 ts=4 sw=4\n<|endoftext|>"} {"text":"#include \"3RVX.h\"\n#include \"Controllers\\Volume\\CoreAudio.h\"\n#include \"VolumeOSD.h\"\n#include \n#include \"Logger.h\"\n#include \"Settings.h\"\n#include \n\nint APIENTRY\nwWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,\nLPTSTR lpCmdLine, int nCmdShow) {\n hInst = hInstance;\n\n#ifdef _DEBUG\n Logger::OpenConsole();\n#endif\n\n QCLOG(L\" _____ ______ ____ _______ \");\n QCLOG(L\" |___ \/| _ \\\\ \\\\ \/ \/\\\\ \\\\\/ \/___ \/ \");\n QCLOG(L\" |_ \\\\| |_) \\\\ \\\\ \/ \/ \\\\ \/ |_ \\\\ \");\n QCLOG(L\" ___) | _ < \\\\ V \/ \/ \\\\ ___) |\");\n QCLOG(L\" |____\/|_| \\\\_\\\\ \\\\_\/ \/_\/\\\\_\\\\____\/ \");\n QCLOG(L\"\");\n\n QCLOG(L\"Starting up...\");\n\n mutex = CreateMutex(NULL, FALSE, L\"Local\\\\3RVX\");\n if (GetLastError() == ERROR_ALREADY_EXISTS) {\n if (mutex) {\n ReleaseMutex(mutex);\n }\n\n HWND masterWnd = FindWindow(CLASS_3RVX, CLASS_3RVX);\n CLOG(L\"A previous instance of the program is already running.\\n\"\n L\"Requesting Settings dialog from window: %d\", masterWnd);\n SendMessage(masterWnd, WM_3RVX_CONTROL, MSG_SETTINGS, NULL);\n\n#ifdef _DEBUG\n CLOG(L\"Press [enter] to terminate\");\n std::cin.get();\n#endif\n\n return EXIT_SUCCESS;\n }\n\n using namespace Gdiplus;\n GdiplusStartupInput gdiplusStartupInput;\n GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);\n\n mainWnd = CreateMainWnd(hInstance);\n if (mainWnd == NULL) {\n CLOG(L\"Could not create main window\");\n return EXIT_FAILURE;\n }\n\n HRESULT hr = CoInitializeEx(NULL,\n COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);\n if (hr != S_OK) {\n CLOG(L\"Failed to initialize the COM library.\");\n return EXIT_FAILURE;\n }\n\n \/* Tell the program to initialize *\/\n PostMessage(mainWnd, WM_3RVX_CONTROL, MSG_LOAD, NULL);\n\n \/* Start the event loop *\/\n MSG msg;\n while (GetMessage(&msg, NULL, 0, 0)) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n GdiplusShutdown(gdiplusToken);\n return (int)msg.wParam;\n}\n\nvoid Init() {\n CLOG(L\"Initializing...\");\n\n volCtrl = new CoreAudio(mainWnd);\n volCtrl->Init();\n float currentVolume = volCtrl->Volume();\n\n Settings settings(L\"Settings.xml\");\n\n Skin skin(settings.SkinName());\n\n vOsd = new VolumeOSD(hInst);\n vOsd->LoadSkin(&skin);\n vOsd->MeterLevels(currentVolume);\n\n hotkeys = settings.Hotkeys();\n HotkeyManager *hkm = HotkeyManager::Instance(mainWnd);\n for (auto it = hotkeys.begin(); it != hotkeys.end(); ++it) {\n int combination = it->first;\n hkm->Register(combination);\n }\n\n WTSRegisterSessionNotification(mainWnd, NOTIFY_FOR_THIS_SESSION);\n}\n\nHWND CreateMainWnd(HINSTANCE hInstance) {\n WNDCLASSEX wcex;\n\n wcex.cbSize = sizeof(WNDCLASSEX);\n wcex.style = NULL;\n wcex.lpfnWndProc = WndProc;\n wcex.cbClsExtra = NULL;\n wcex.cbWndExtra = NULL;\n wcex.hInstance = hInstance;\n wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);\n wcex.hCursor = LoadCursor(NULL, IDC_ARROW);\n wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);\n wcex.lpszMenuName = NULL;\n wcex.lpszClassName = CLASS_3RVX;\n wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);\n\n if (!RegisterClassEx(&wcex)) {\n return NULL;\n }\n\n HWND hWnd = CreateWindowEx(\n NULL,\n CLASS_3RVX, CLASS_3RVX,\n NULL, NULL, NULL, \/\/your boat, gently down the stream\n NULL, NULL, HWND_MESSAGE, NULL, hInstance, NULL);\n\n return hWnd;\n}\n\nLRESULT CALLBACK WndProc(\n HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {\n\n switch (message) {\n case MSG_VOLCHNG: {\n float v = volCtrl->Volume();\n QCLOG(L\"Volume level: %.0f\", v * 100.0f);\n vOsd->MeterLevels(v);\n break;\n }\n\n case MSG_DEVCHNG:\n CLOG(L\"Device change detected.\");\n volCtrl->ReattachDefaultDevice();\n break;\n\n case WM_HOTKEY: {\n CLOG(L\"Hotkey: %d\", (int) wParam);\n int action = hotkeys[(int) wParam];\n if (action == 100) {\n float current = volCtrl->Volume();\n volCtrl->Volume(current + .1f);\n }\n break;\n }\n\n case WM_WTSSESSION_CHANGE:\n CLOG(L\"Detected session change\");\n break;\n }\n\n if (message == WM_3RVX_CONTROL) {\n switch (wParam) {\n case MSG_LOAD:\n Init();\n break;\n\n case MSG_SETTINGS:\n CLOG(L\"Launching settings editor\");\n \/* TODO: launch! *\/\n break;\n }\n }\n\n return DefWindowProc(hWnd, message, wParam, lParam);\n}Update for Skin constructor change#include \"3RVX.h\"\n#include \"Controllers\\Volume\\CoreAudio.h\"\n#include \"VolumeOSD.h\"\n#include \n#include \"Logger.h\"\n#include \"Settings.h\"\n#include \n#include \"Skin.h\"\n\nint APIENTRY\nwWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,\nLPTSTR lpCmdLine, int nCmdShow) {\n hInst = hInstance;\n\n#ifdef _DEBUG\n Logger::OpenConsole();\n#endif\n\n QCLOG(L\" _____ ______ ____ _______ \");\n QCLOG(L\" |___ \/| _ \\\\ \\\\ \/ \/\\\\ \\\\\/ \/___ \/ \");\n QCLOG(L\" |_ \\\\| |_) \\\\ \\\\ \/ \/ \\\\ \/ |_ \\\\ \");\n QCLOG(L\" ___) | _ < \\\\ V \/ \/ \\\\ ___) |\");\n QCLOG(L\" |____\/|_| \\\\_\\\\ \\\\_\/ \/_\/\\\\_\\\\____\/ \");\n QCLOG(L\"\");\n\n QCLOG(L\"Starting up...\");\n\n mutex = CreateMutex(NULL, FALSE, L\"Local\\\\3RVX\");\n if (GetLastError() == ERROR_ALREADY_EXISTS) {\n if (mutex) {\n ReleaseMutex(mutex);\n }\n\n HWND masterWnd = FindWindow(CLASS_3RVX, CLASS_3RVX);\n CLOG(L\"A previous instance of the program is already running.\\n\"\n L\"Requesting Settings dialog from window: %d\", masterWnd);\n SendMessage(masterWnd, WM_3RVX_CONTROL, MSG_SETTINGS, NULL);\n\n#ifdef _DEBUG\n CLOG(L\"Press [enter] to terminate\");\n std::cin.get();\n#endif\n\n return EXIT_SUCCESS;\n }\n\n using namespace Gdiplus;\n GdiplusStartupInput gdiplusStartupInput;\n GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);\n\n mainWnd = CreateMainWnd(hInstance);\n if (mainWnd == NULL) {\n CLOG(L\"Could not create main window\");\n return EXIT_FAILURE;\n }\n\n HRESULT hr = CoInitializeEx(NULL,\n COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);\n if (hr != S_OK) {\n CLOG(L\"Failed to initialize the COM library.\");\n return EXIT_FAILURE;\n }\n\n \/* Tell the program to initialize *\/\n PostMessage(mainWnd, WM_3RVX_CONTROL, MSG_LOAD, NULL);\n\n \/* Start the event loop *\/\n MSG msg;\n while (GetMessage(&msg, NULL, 0, 0)) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n GdiplusShutdown(gdiplusToken);\n return (int)msg.wParam;\n}\n\nvoid Init() {\n CLOG(L\"Initializing...\");\n\n volCtrl = new CoreAudio(mainWnd);\n volCtrl->Init();\n float currentVolume = volCtrl->Volume();\n\n Settings settings(L\"Settings.xml\");\n\n std::wstring skinName = settings.SkinName();\n std::wstring skinXML = SKINS_DIR L\"\\\\\" + skinName + L\"\\\\\" SKIN_XML;\n Skin skin(skinXML);\n\n vOsd = new VolumeOSD(hInst);\n vOsd->LoadSkin(&skin);\n vOsd->MeterLevels(currentVolume);\n\n hotkeys = settings.Hotkeys();\n HotkeyManager *hkm = HotkeyManager::Instance(mainWnd);\n for (auto it = hotkeys.begin(); it != hotkeys.end(); ++it) {\n int combination = it->first;\n hkm->Register(combination);\n }\n\n WTSRegisterSessionNotification(mainWnd, NOTIFY_FOR_THIS_SESSION);\n}\n\nHWND CreateMainWnd(HINSTANCE hInstance) {\n WNDCLASSEX wcex;\n\n wcex.cbSize = sizeof(WNDCLASSEX);\n wcex.style = NULL;\n wcex.lpfnWndProc = WndProc;\n wcex.cbClsExtra = NULL;\n wcex.cbWndExtra = NULL;\n wcex.hInstance = hInstance;\n wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);\n wcex.hCursor = LoadCursor(NULL, IDC_ARROW);\n wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);\n wcex.lpszMenuName = NULL;\n wcex.lpszClassName = CLASS_3RVX;\n wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);\n\n if (!RegisterClassEx(&wcex)) {\n return NULL;\n }\n\n HWND hWnd = CreateWindowEx(\n NULL,\n CLASS_3RVX, CLASS_3RVX,\n NULL, NULL, NULL, \/\/your boat, gently down the stream\n NULL, NULL, HWND_MESSAGE, NULL, hInstance, NULL);\n\n return hWnd;\n}\n\nLRESULT CALLBACK WndProc(\n HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {\n\n switch (message) {\n case MSG_VOLCHNG: {\n float v = volCtrl->Volume();\n QCLOG(L\"Volume level: %.0f\", v * 100.0f);\n vOsd->MeterLevels(v);\n break;\n }\n\n case MSG_DEVCHNG:\n CLOG(L\"Device change detected.\");\n volCtrl->ReattachDefaultDevice();\n break;\n\n case WM_HOTKEY: {\n CLOG(L\"Hotkey: %d\", (int) wParam);\n int action = hotkeys[(int) wParam];\n if (action == 100) {\n float current = volCtrl->Volume();\n volCtrl->Volume(current + .1f);\n }\n break;\n }\n\n case WM_WTSSESSION_CHANGE:\n CLOG(L\"Detected session change\");\n break;\n }\n\n if (message == WM_3RVX_CONTROL) {\n switch (wParam) {\n case MSG_LOAD:\n Init();\n break;\n\n case MSG_SETTINGS:\n CLOG(L\"Launching settings editor\");\n \/* TODO: launch! *\/\n break;\n }\n }\n\n return DefWindowProc(hWnd, message, wParam, lParam);\n}<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"testHooks.h\"\n#include \"TestStreams.h\"\n\n#include \"comms\/NMEA.h\"\n\/\/TESTING \"comms\/NMEA.cpp\"\n\/\/TESTING \"math\/GreatCircle.cpp\"\n\/\/TESTING \"math\/Waypoint.cpp\"\n\/\/TESTING \"math\/SpatialMath.cpp\"\n\ntypedef struct GPRMC{\n const char * desc;\n const char * str;\n float time;\n bool active;\n float latitude;\n float longitude;\n float speed;\n float trackAngle;\n long date;\n float magVar;\n} GPRMC;\n\n\/*\nlat\/lon is in degrees+decimal minutes, code spec is decimal degrees\nfunction decimalDegrees(degreeDecimalMinutes)\n minutes = degreeDecimalMinutes % 100.0\n degrees = (degreeDecimalMinutes - minutes) \/ 100.0\n decimalDegrees = degrees + minutes\/60.0\n return decimalDegrees\nend\n\nspeed in GPRMC is in knots, code spec returns mph\nmph(knots) = knots * 1.15077945\n*\/\n\n\/\/examples taken from http:\/\/www.gpsinformation.org\/dale\/nmea.htm\nconst GPRMC goodData[] {\n { \"NE GPRMC\",\n \"$GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A\",\n 123519, true, 48.11729, 11.51666, 25.77746, 84.4, 230394, 3.1\n },\n { \"NW GPRMC\",\n \"$GPRMC,183729,A,3907.356,N,12102.482,W,000.0,360.0,080301,015.5,E*6F\",\n 183729, true, 39.12260, -121.04136, 0.0, 360.0, 80301, 15.5\n },\n { \"Bad Status\",\n \"$GPRMC,152926,V,6027.8259,N,02225.6713,E,10.8,0.0,190803,5.9,E,S*22\",\n 152926, false, 60.46376, 22.42786, 12.428418, 0.0, 190803, 5.9\n },\n { \"Empty Fields\",\n \"$GPRMC,162254.00,A,3723.02837,N,12159.39853,W,0.820,188.36,110706,,,A*74\",\n 162254, true, 37.38380, -121.98998, 0.94364, 188.36, 110706, 0.0\n },\n { \"DecimalTime\",\n \"$GPRMC,230611.016,V,3907.3813,N,12102.4635,W,0.14,136.40,041002,,*04\",\n 230611.016, false, 39.12302, -121.04106, 0.161109, 136.40, 41002, 0.0\n },\n { \"Surrounded GPRMC\",\n \"$GPGSV,3,3,09,24,12,282,00*4D\"\n \"$GPGLL,3553.5295,N,13938.6570,E,002454,A,A*4F\"\n \"$GPBOD,,T,,M,,*47\"\n \"$PGRME,8.6,M,9.6,M,12.9,M*15\"\n \"$PGRMZ,51,f*30\"\n \"$HCHDG,101.1,,,7.1,W*3C\"\n \"$GPRTE,1,1,c,*37\"\n \"$GPRMC,002456,A,3553.5295,N,13938.6570,E,0.0,43.1,180700,7.1,W,A*3D\"\n \"$GPGGA,002454,3553.5295,N,13938.6570,E,1,05,2.2,18.3,M,39.0,M,,*7F\"\n \"$GPGSA,A,3,01,04,07,16,20,,,,,,,,3.6,2.2,2.7*35\"\n \"$GPGSV,3,1,09,01,38,103,37,02,23,215,00,04,38,297,37,05,00,328,00*70\"\n \"$GPGSV,3,2,09,07,77,299,47,11,07,087,00,16,74,041,47,20,38,044,43*73\",\n 2456, true, 35.89215, 139.64428, 0.0, 43.1, 180700,7.1\n },\n};\nconst int numGoodData = sizeof(goodData)\/sizeof(goodData[0]);\n\nconst char * badStrings[] {\n\n};\n\n#define nmeaOfString(s) \\\n StringStream ss(s); \\\n NMEA nmea(ss); \\\n nmea.update(); \\\n ss.reset(\"$\"); \\\n nmea.update();\n \/\/the extra dollar sign is an artifact of the current NMEA implementation\n\nbool parseTime(){\n for(int i=0; iAdd some evil strings to test with#include \n#include \n#include \n#include \n\n#include \"testHooks.h\"\n#include \"TestStreams.h\"\n\n#include \"comms\/NMEA.h\"\n\/\/TESTING \"comms\/NMEA.cpp\"\n\/\/TESTING \"math\/GreatCircle.cpp\"\n\/\/TESTING \"math\/Waypoint.cpp\"\n\/\/TESTING \"math\/SpatialMath.cpp\"\n\ntypedef struct GPRMC{\n const char * desc;\n const char * str;\n float time;\n bool active;\n float latitude;\n float longitude;\n float speed;\n float trackAngle;\n long date;\n float magVar;\n} GPRMC;\n\n\/*\nlat\/lon is in degrees+decimal minutes, code spec is decimal degrees\nfunction decimalDegrees(degreeDecimalMinutes)\n minutes = degreeDecimalMinutes % 100.0\n degrees = (degreeDecimalMinutes - minutes) \/ 100.0\n decimalDegrees = degrees + minutes\/60.0\n return decimalDegrees\nend\n\nspeed in GPRMC is in knots, code spec returns mph\nmph(knots) = knots * 1.15077945\n*\/\n\n\/\/examples taken from http:\/\/www.gpsinformation.org\/dale\/nmea.htm\nconst GPRMC goodData[] {\n { \"NE GPRMC\",\n \"$GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A\",\n 123519, true, 48.11729, 11.51666, 25.77746, 84.4, 230394, 3.1\n },\n { \"NW GPRMC\",\n \"$GPRMC,183729,A,3907.356,N,12102.482,W,000.0,360.0,080301,015.5,E*6F\",\n 183729, true, 39.12260, -121.04136, 0.0, 360.0, 80301, 15.5\n },\n { \"Bad Status\",\n \"$GPRMC,152926,V,6027.8259,N,02225.6713,E,10.8,0.0,190803,5.9,E,S*22\",\n 152926, false, 60.46376, 22.42786, 12.428418, 0.0, 190803, 5.9\n },\n { \"Empty Fields\",\n \"$GPRMC,162254.00,A,3723.02837,N,12159.39853,W,0.820,188.36,110706,,,A*74\",\n 162254, true, 37.38380, -121.98998, 0.94364, 188.36, 110706, 0.0\n },\n { \"DecimalTime\",\n \"$GPRMC,230611.016,V,3907.3813,N,12102.4635,W,0.14,136.40,041002,,*04\",\n 230611.016, false, 39.12302, -121.04106, 0.161109, 136.40, 41002, 0.0\n },\n { \"Surrounded GPRMC\",\n \"$GPGSV,3,3,09,24,12,282,00*4D\"\n \"$GPGLL,3553.5295,N,13938.6570,E,002454,A,A*4F\"\n \"$GPBOD,,T,,M,,*47\"\n \"$PGRME,8.6,M,9.6,M,12.9,M*15\"\n \"$PGRMZ,51,f*30\"\n \"$HCHDG,101.1,,,7.1,W*3C\"\n \"$GPRTE,1,1,c,*37\"\n \"$GPRMC,002456,A,3553.5295,N,13938.6570,E,0.0,43.1,180700,7.1,W,A*3D\"\n \"$GPGGA,002454,3553.5295,N,13938.6570,E,1,05,2.2,18.3,M,39.0,M,,*7F\"\n \"$GPGSA,A,3,01,04,07,16,20,,,,,,,,3.6,2.2,2.7*35\"\n \"$GPGSV,3,1,09,01,38,103,37,02,23,215,00,04,38,297,37,05,00,328,00*70\"\n \"$GPGSV,3,2,09,07,77,299,47,11,07,087,00,16,74,041,47,20,38,044,43*73\",\n 2456, true, 35.89215, 139.64428, 0.0, 43.1, 180700,7.1\n },\n};\nconst int numGoodData = sizeof(goodData)\/sizeof(goodData[0]);\n\nconst char * badStrings[] {\n \"$$$$$$$$$$$\",\n \"$,,,,,,,,,,,,,,,,,,,\",\n \"$GPRMC,,,,,,,,,,,,,,,,,,\",\n \"$GPRMC$\",\n \"$GPRMC,123519,X,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A\",\n \"$GPRMC,X,X,X,X,X,X,X,X,X,X,XXXX\",\n \"$GPRMC,123519549631488436214567\/89321456,A,\",\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\n \"4807.038,N,01131.00000-100.4,E,022.4,084.4,2303946544563217896,003.1,W*6A\",\n};\nconst int numBadStrings = sizeof(badStrings)\/sizeof(badStrings[0]);\n\n#define nmeaOfString(s) \\\n StringStream ss(s); \\\n NMEA nmea(ss); \\\n nmea.update(); \\\n ss.reset(\"$\"); \\\n nmea.update();\n \/\/the extra dollar sign is an artifact of the current NMEA implementation\n\nbool parseTime(){\n for(int i=0; i"} {"text":"\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#pragma once\n\n#include\"ork\/orientation.hpp\"\n#if ORK_USE_GLM\n#include\"glm\/vec3.hpp\"\n#include\"glm\/geometric.hpp\"\n\n\nnamespace ork {\nnamespace GLM {\/\/Kind of deceiving, but whatever\n\n\nstruct dunit3 {\nprivate:\n\tglm::dvec3 _vec;\npublic:\n\tORK_INLINE explicit dunit3(const glm::dvec3&vector) :_vec(glm::normalize(vector)) {}\n\tORK_INLINE dunit3(const double x, const double y, const double z) :_vec(glm::normalize(glm::dvec3(x, y, z))) {}\npublic:\n\tORK_INLINE const glm::dvec3&get()const {\n\t\treturn _vec;\n\t}\n\tORK_INLINE double&operator[](const size_t index) {\n\t\treturn _vec[static_cast(index)];\n\t}\n\tORK_INLINE const double&operator[](const size_t index)const {\n\t\treturn _vec[static_cast(index)];\n\t}\n\tORK_INLINE double x()const { return _vec.x; }\n\tORK_INLINE double y()const { return _vec.y; }\n\tORK_INLINE double z()const { return _vec.z; }\n\tORK_INLINE const double&operator[](const unsigned index) const {\/\/unsigned because glm uses int indices\n\t\treturn _vec[index];\n\t}\n\tORK_INLINE dunit3 operator-()const {\n\t\treturn dunit3(-_vec);\n\t}\n\tORK_INLINE unsigned size()const {\/\/unsigned for consistency with glm\n\t\treturn 3;\n\t}\n\tORK_INLINE unsigned length()const {\/\/For consistency with glm\n\t\treturn 3;\n\t}\n};\n\nORK_INLINE glm::dvec3 operator*(const double lhs, const dunit3&rhs) {\n\treturn lhs*rhs.get();\n}\nORK_ORK_EXT(o_stream&) operator<<(o_stream&stream, const dunit3&vec);\n\n\n\/\/Simply tired of defining these\nORK_EXTERN const dunit3 pos_x;\nORK_EXTERN const dunit3 neg_x;\nORK_EXTERN const dunit3 pos_y;\nORK_EXTERN const dunit3 neg_y;\nORK_EXTERN const dunit3 pos_z;\nORK_EXTERN const dunit3 neg_z;\n\n\n\/\/GLM version of loops, needed because GLM uses length() and unsigned as the type\n#define LOOPVG(SERIES,INDEX)for(unsigned INDEX=0, limit##INDEX=SERIES.length(); INDEX!=limit##INDEX; ++INDEX)\n#define LOOPVIG(SERIES)LOOPVG(SERIES,i)\n#define LOOPVJG(SERIES)LOOPVG(SERIES,j)\n#define LOOPVKG(SERIES)LOOPVG(SERIES,k)\n#define LOOPVLG(SERIES)LOOPVG(SERIES,l)\n\n\n\/*\nThis function basically tests that two floats could have resulted from a single, mathematically equivalent operation\nfloat f1=0.2;\/\/Cannot be exactly represented! (One bit either way)\nfloat f2=0.1;\/\/ditto\nFloat f2+=0.1;\/\/Maybe 2 bits different now(both bits)\nassert(f1==f2);\/\/have fun crashing\nassert(might_be_equal(f1,f2));\/\/We are safe, assuming IEEE 754 (Ok,I am not authoritatively positive)\nThere are false positives with small numbers!\n*\/\nnamespace detail {\n\ntemplate\nORK_INLINE bool equal_simple(const T&lhs, const T&rhs) {\n\tstatic const T abs_eps = eps_factor * std::numeric_limits::epsilon();\/\/We need an absolute epsilon\n\tstatic const T rel_eps = rel_factor * abs_eps;\/\/Factor of 2 to allow for the case of second LSB bump\n\treturn std::abs(lhs - rhs) <= std::max(abs_eps, rel_eps*std::max(lhs, rhs));\n}\n\ntemplate\nORK_INLINE bool equal_vector(const T&lhs, const T&rhs) {\n\tLOOPVIG(lhs) {\n\t\tif(!equal_simple(lhs[i], rhs[i]))return false;\n\t}\n\treturn true;\n}\n\ntemplate\nORK_INLINE bool equal_matrix(const T&lhs, const T&rhs) {\n\tLOOPVIG(lhs) {\n\t\tif(!equal_vector(lhs[i], rhs[i]))return false;\n\t}\n\treturn true;\n}\n\n\ntemplate\nORK_INLINE bool less_simple(const T&lhs, const T&rhs) {\n\treturn lhs < rhs && !equal_simple(lhs, rhs);\n}\n\ntemplate\nORK_INLINE bool greater_simple(const T&lhs, const T&rhs) {\n\treturn lhs > rhs && !equal_simple(lhs, rhs);\n}\n\ntemplate\nORK_INLINE bool less_equal_simple(const T&lhs, const T&rhs) {\n\treturn lhs < rhs || equal_simple(lhs, rhs);\n}\n\ntemplate\nORK_INLINE bool greater_equal_simple(const T&lhs, const T&rhs) {\n\treturn lhs > rhs || equal_simple(lhs, rhs);\n}\n\n\n}\/\/namespace detail\n\n\n\/\/Use matrix as the default because there are more of them\ntemplate\nORK_INLINE bool equal(const T&lhs, const T&rhs) {\n\treturn detail::equal_matrix(lhs, rhs);\n}\n\n\/\/And we have not bothered to add other overloads\ntemplate\nORK_INLINE bool equal(const glm::tvec3&lhs, const glm::tvec3&rhs) {\n\treturn detail::equal_vector>(lhs, rhs);\n}\ntemplate\nORK_INLINE bool equal(const glm::tvec4&lhs, const glm::tvec4&rhs) {\n\treturn detail::equal_vector>(lhs, rhs);\n}\nORK_INLINE bool equal(const GLM::dunit3&lhs, const GLM::dunit3&rhs) {\n\treturn detail::equal_vector(lhs, rhs);\n}\n\n\ntemplate<>\nORK_INLINE bool equal(const float&lhs, const float&rhs) {\n\treturn detail::equal_simple(lhs, rhs);\n}\ntemplate<>\nORK_INLINE bool equal(const double&lhs, const double&rhs) {\n\treturn detail::equal_simple(lhs, rhs);\n}\n\n\ntemplate\nORK_INLINE bool parallel(const V&v1, const V&v2) {\n\tconst double norms = glm::length(v1) * glm::length(v2);\n\tconst double dot = glm::dot(v1, v2);\n\treturn equal(norms, dot);\n}\ntemplate<>\nORK_INLINE bool parallel(const dunit3&v1, const dunit3&v2) {\n\tconst double norms = glm::length(v1.get()) * glm::length(v2.get());\n\tconst double dot = glm::dot(v1.get(), v2.get());\n\treturn equal(norms, dot);\n}\n\n\ntemplate\nORK_INLINE bool antiparallel(const V&v1, const V&v2) {\n\treturn parallel(v1, -v2);\n}\n\n\ntemplate\nORK_INLINE bool axial(const V&v1, const V&v2) {\n\treturn parallel(v1, v2) || parallel(v1, -v2);\n}\n\n\ntemplate\nORK_INLINE bool orthogonal(const V&v1, const V&v2) {\n\tconst double norms = glm::length(v1) * glm::length(v2);\n\tconst double dot = glm::dot(v1, v2);\n\tconst bool test = equal(norms, norms + dot);\n\treturn test;\n}\ntemplate<>\nORK_INLINE bool orthogonal(const dunit3&v1, const dunit3&v2) {\n\treturn orthogonal(v1.get(), v2.get());\n}\n\n\n\/*\nSome vector functions\n*\/\n\n\ntemplate\nORK_INLINE bool less(const V&v1, const V&v2) {\n\tLOOPVIG(v1) {\n\t\tif(equal(v1[i], v2[i]) || v1[i] > v2[i])return false;\n\t}\n\treturn true;\n}\ntemplate<>\nORK_INLINE bool less(const float&lhs, const float&rhs) {\n\treturn detail::less_simple(lhs, rhs);\n}\ntemplate<>\nORK_INLINE bool less(const double&lhs, const double&rhs) {\n\treturn detail::less_simple(lhs, rhs);\n}\n\n\ntemplate\nORK_INLINE bool greater(const V&v1, const V&v2) {\n\tLOOPVIG(v1) {\n\t\tif(equal(v1[i], v2[i]) || v1[i] < v2[i])return false;\n\t}\n\treturn true;\n}\ntemplate<>\nORK_INLINE bool greater(const float&lhs, const float&rhs) {\n\treturn detail::greater_simple(lhs, rhs);\n}\ntemplate<>\nORK_INLINE bool greater(const double&lhs, const double&rhs) {\n\treturn detail::greater_simple(lhs, rhs);\n}\n\n\n\ntemplate\nORK_INLINE bool less_equal(const V&v1, const V&v2) {\n\tLOOPVIG(v1) {\n\t\tif(greater(v1[i], v2[i]))return false;\n\t}\n\treturn true;\n}\ntemplate<>\nORK_INLINE bool less_equal(const float&lhs, const float&rhs) {\n\treturn detail::less_equal_simple(lhs, rhs);\n}\ntemplate<>\nORK_INLINE bool less_equal(const double&lhs, const double&rhs) {\n\treturn detail::less_equal_simple(lhs, rhs);\n}\n\n\ntemplate\nORK_INLINE bool greater_equal(const V&v1, const V&v2) {\n\tLOOPVIG(v1) {\n\t\tif(less(v1[i], v2[i]))return false;\n\t}\n\treturn true;\n}\ntemplate<>\nORK_INLINE bool greater_equal(const float&lhs, const float&rhs) {\n\treturn detail::greater_equal_simple(lhs, rhs);\n}\ntemplate<>\nORK_INLINE bool greater_equal(const double&lhs, const double&rhs) {\n\treturn detail::greater_equal_simple(lhs, rhs);\n}\n\n\n\/\/Rotates a vector about the origin, such that normal would become new_normal if subject to the same rotation\nORK_ORK_EXT(glm::dvec3) rotate(const glm::dvec3&vec, const dunit3&normal, const dunit3&new_normal);\n\n\nORK_ORK_EXT(glm::dvec3) proj_on_plane(const glm::dvec3&vec, const GLM::dunit3&normal);\n\n\n\/*\nOrientation stuff\n*\/\nORK_ORK_EXT(const dunit3&) orientation2direction(orientation axis);\n\n\n}\/\/namespace GLM\n\nORK_ORK_EXT(string) to_string(const glm::dvec3&vec);\n\n}\/\/namespace ork\n\nnamespace glm {\nORK_ORK_EXT(ork::o_stream&) operator<<(ork::o_stream&stream, const glm::dvec2&vec);\nORK_ORK_EXT(ork::o_stream&) operator<<(ork::o_stream&stream, const glm::dvec3&vec);\n}\n\n#endif\/\/ORK_USE_GLMExposed tolerance value to clients\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#pragma once\n\n#include\"ork\/orientation.hpp\"\n#if ORK_USE_GLM\n#include\"glm\/vec3.hpp\"\n#include\"glm\/geometric.hpp\"\n\n\nnamespace ork {\nnamespace GLM {\/\/Kind of deceiving, but whatever\n\n\nstruct dunit3 {\nprivate:\n\tglm::dvec3 _vec;\npublic:\n\tORK_INLINE explicit dunit3(const glm::dvec3&vector) :_vec(glm::normalize(vector)) {}\n\tORK_INLINE dunit3(const double x, const double y, const double z) :_vec(glm::normalize(glm::dvec3(x, y, z))) {}\npublic:\n\tORK_INLINE const glm::dvec3&get()const {\n\t\treturn _vec;\n\t}\n\tORK_INLINE double&operator[](const size_t index) {\n\t\treturn _vec[static_cast(index)];\n\t}\n\tORK_INLINE const double&operator[](const size_t index)const {\n\t\treturn _vec[static_cast(index)];\n\t}\n\tORK_INLINE double x()const { return _vec.x; }\n\tORK_INLINE double y()const { return _vec.y; }\n\tORK_INLINE double z()const { return _vec.z; }\n\tORK_INLINE const double&operator[](const unsigned index) const {\/\/unsigned because glm uses int indices\n\t\treturn _vec[index];\n\t}\n\tORK_INLINE dunit3 operator-()const {\n\t\treturn dunit3(-_vec);\n\t}\n\tORK_INLINE unsigned size()const {\/\/unsigned for consistency with glm\n\t\treturn 3;\n\t}\n\tORK_INLINE unsigned length()const {\/\/For consistency with glm\n\t\treturn 3;\n\t}\n};\n\nORK_INLINE glm::dvec3 operator*(const double lhs, const dunit3&rhs) {\n\treturn lhs*rhs.get();\n}\nORK_ORK_EXT(o_stream&) operator<<(o_stream&stream, const dunit3&vec);\n\n\n\/\/Simply tired of defining these\nORK_EXTERN const dunit3 pos_x;\nORK_EXTERN const dunit3 neg_x;\nORK_EXTERN const dunit3 pos_y;\nORK_EXTERN const dunit3 neg_y;\nORK_EXTERN const dunit3 pos_z;\nORK_EXTERN const dunit3 neg_z;\n\n\n\/\/GLM version of loops, needed because GLM uses length() and unsigned as the type\n#define LOOPVG(SERIES,INDEX)for(unsigned INDEX=0, limit##INDEX=SERIES.length(); INDEX!=limit##INDEX; ++INDEX)\n#define LOOPVIG(SERIES)LOOPVG(SERIES,i)\n#define LOOPVJG(SERIES)LOOPVG(SERIES,j)\n#define LOOPVKG(SERIES)LOOPVG(SERIES,k)\n#define LOOPVLG(SERIES)LOOPVG(SERIES,l)\n\n\n\/*\nThis function basically tests that two floats could have resulted from a single, mathematically equivalent operation\nfloat f1=0.2;\/\/Cannot be exactly represented! (One bit either way)\nfloat f2=0.1;\/\/ditto\nFloat f2+=0.1;\/\/Maybe 2 bits different now(both bits)\nassert(f1==f2);\/\/have fun crashing\nassert(might_be_equal(f1,f2));\/\/We are safe, assuming IEEE 754 (Ok,I am not authoritatively positive)\nThere are false positives with small numbers!\n*\/\ntemplatestruct default_epsilon_factor {\n\tstatic const unsigned value = 16;\/\/This is only verified over time as the minimum upper bound across ACIS and OCC when T is double\n};\ntemplate::value>\nORK_INLINE ORK_CONSTEXPR T tolerance() {\n\treturn eps_factor * std::numeric_limits::epsilon();\n}\n\nnamespace detail {\n\ntemplate::value, unsigned rel_factor = 1>\nORK_INLINE bool equal_simple(const T&lhs, const T&rhs) {\n\tstatic const T abs_eps = tolerance();\/\/We need an absolute epsilon\n\tstatic const T rel_eps = rel_factor * abs_eps;\/\/Factor of 2 to allow for the case of second LSB bump\n\treturn std::abs(lhs - rhs) <= std::max(abs_eps, rel_eps*std::max(lhs, rhs));\n}\n\ntemplate\nORK_INLINE bool equal_vector(const T&lhs, const T&rhs) {\n\tLOOPVIG(lhs) {\n\t\tif(!equal_simple(lhs[i], rhs[i]))return false;\n\t}\n\treturn true;\n}\n\ntemplate\nORK_INLINE bool equal_matrix(const T&lhs, const T&rhs) {\n\tLOOPVIG(lhs) {\n\t\tif(!equal_vector(lhs[i], rhs[i]))return false;\n\t}\n\treturn true;\n}\n\n\ntemplate\nORK_INLINE bool less_simple(const T&lhs, const T&rhs) {\n\treturn lhs < rhs && !equal_simple(lhs, rhs);\n}\n\ntemplate\nORK_INLINE bool greater_simple(const T&lhs, const T&rhs) {\n\treturn lhs > rhs && !equal_simple(lhs, rhs);\n}\n\ntemplate\nORK_INLINE bool less_equal_simple(const T&lhs, const T&rhs) {\n\treturn lhs < rhs || equal_simple(lhs, rhs);\n}\n\ntemplate\nORK_INLINE bool greater_equal_simple(const T&lhs, const T&rhs) {\n\treturn lhs > rhs || equal_simple(lhs, rhs);\n}\n\n\n}\/\/namespace detail\n\n\n\/\/Use matrix as the default because there are more of them\ntemplate\nORK_INLINE bool equal(const T&lhs, const T&rhs) {\n\treturn detail::equal_matrix(lhs, rhs);\n}\n\n\/\/And we have not bothered to add other overloads\ntemplate\nORK_INLINE bool equal(const glm::tvec3&lhs, const glm::tvec3&rhs) {\n\treturn detail::equal_vector>(lhs, rhs);\n}\ntemplate\nORK_INLINE bool equal(const glm::tvec4&lhs, const glm::tvec4&rhs) {\n\treturn detail::equal_vector>(lhs, rhs);\n}\nORK_INLINE bool equal(const GLM::dunit3&lhs, const GLM::dunit3&rhs) {\n\treturn detail::equal_vector(lhs, rhs);\n}\n\n\ntemplate<>\nORK_INLINE bool equal(const float&lhs, const float&rhs) {\n\treturn detail::equal_simple(lhs, rhs);\n}\ntemplate<>\nORK_INLINE bool equal(const double&lhs, const double&rhs) {\n\treturn detail::equal_simple(lhs, rhs);\n}\n\n\ntemplate\nORK_INLINE bool parallel(const V&v1, const V&v2) {\n\tconst double norms = glm::length(v1) * glm::length(v2);\n\tconst double dot = glm::dot(v1, v2);\n\treturn equal(norms, dot);\n}\ntemplate<>\nORK_INLINE bool parallel(const dunit3&v1, const dunit3&v2) {\n\tconst double norms = glm::length(v1.get()) * glm::length(v2.get());\n\tconst double dot = glm::dot(v1.get(), v2.get());\n\treturn equal(norms, dot);\n}\n\n\ntemplate\nORK_INLINE bool antiparallel(const V&v1, const V&v2) {\n\treturn parallel(v1, -v2);\n}\n\n\ntemplate\nORK_INLINE bool axial(const V&v1, const V&v2) {\n\treturn parallel(v1, v2) || parallel(v1, -v2);\n}\n\n\ntemplate\nORK_INLINE bool orthogonal(const V&v1, const V&v2) {\n\tconst double norms = glm::length(v1) * glm::length(v2);\n\tconst double dot = glm::dot(v1, v2);\n\tconst bool test = equal(norms, norms + dot);\n\treturn test;\n}\ntemplate<>\nORK_INLINE bool orthogonal(const dunit3&v1, const dunit3&v2) {\n\treturn orthogonal(v1.get(), v2.get());\n}\n\n\n\/*\nSome vector functions\n*\/\n\n\ntemplate\nORK_INLINE bool less(const V&v1, const V&v2) {\n\tLOOPVIG(v1) {\n\t\tif(equal(v1[i], v2[i]) || v1[i] > v2[i])return false;\n\t}\n\treturn true;\n}\ntemplate<>\nORK_INLINE bool less(const float&lhs, const float&rhs) {\n\treturn detail::less_simple(lhs, rhs);\n}\ntemplate<>\nORK_INLINE bool less(const double&lhs, const double&rhs) {\n\treturn detail::less_simple(lhs, rhs);\n}\n\n\ntemplate\nORK_INLINE bool greater(const V&v1, const V&v2) {\n\tLOOPVIG(v1) {\n\t\tif(equal(v1[i], v2[i]) || v1[i] < v2[i])return false;\n\t}\n\treturn true;\n}\ntemplate<>\nORK_INLINE bool greater(const float&lhs, const float&rhs) {\n\treturn detail::greater_simple(lhs, rhs);\n}\ntemplate<>\nORK_INLINE bool greater(const double&lhs, const double&rhs) {\n\treturn detail::greater_simple(lhs, rhs);\n}\n\n\n\ntemplate\nORK_INLINE bool less_equal(const V&v1, const V&v2) {\n\tLOOPVIG(v1) {\n\t\tif(greater(v1[i], v2[i]))return false;\n\t}\n\treturn true;\n}\ntemplate<>\nORK_INLINE bool less_equal(const float&lhs, const float&rhs) {\n\treturn detail::less_equal_simple(lhs, rhs);\n}\ntemplate<>\nORK_INLINE bool less_equal(const double&lhs, const double&rhs) {\n\treturn detail::less_equal_simple(lhs, rhs);\n}\n\n\ntemplate\nORK_INLINE bool greater_equal(const V&v1, const V&v2) {\n\tLOOPVIG(v1) {\n\t\tif(less(v1[i], v2[i]))return false;\n\t}\n\treturn true;\n}\ntemplate<>\nORK_INLINE bool greater_equal(const float&lhs, const float&rhs) {\n\treturn detail::greater_equal_simple(lhs, rhs);\n}\ntemplate<>\nORK_INLINE bool greater_equal(const double&lhs, const double&rhs) {\n\treturn detail::greater_equal_simple(lhs, rhs);\n}\n\n\n\/\/Rotates a vector about the origin, such that normal would become new_normal if subject to the same rotation\nORK_ORK_EXT(glm::dvec3) rotate(const glm::dvec3&vec, const dunit3&normal, const dunit3&new_normal);\n\n\nORK_ORK_EXT(glm::dvec3) proj_on_plane(const glm::dvec3&vec, const GLM::dunit3&normal);\n\n\n\/*\nOrientation stuff\n*\/\nORK_ORK_EXT(const dunit3&) orientation2direction(orientation axis);\n\n\n}\/\/namespace GLM\n\nORK_ORK_EXT(string) to_string(const glm::dvec3&vec);\n\n}\/\/namespace ork\n\nnamespace glm {\nORK_ORK_EXT(ork::o_stream&) operator<<(ork::o_stream&stream, const glm::dvec2&vec);\nORK_ORK_EXT(ork::o_stream&) operator<<(ork::o_stream&stream, const glm::dvec3&vec);\n}\n\n#endif\/\/ORK_USE_GLM<|endoftext|>"} {"text":"\/\/ Copyright (C) 2017 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Development Kit\"\n\/\/ For conditions of distribution and use, see copyright notice in Prerequisites.hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Ndk\n{\n\tstruct BoxLayout::State\n\t{\n\t\tstd::vector sizeVar;\n\t\tkiwi::Solver solver;\n\t};\n\n\tBoxLayout::BoxLayout(BaseWidget* parent, BoxLayoutOrientation orientation) :\n\tBaseWidget(parent),\n\tm_orientation(orientation),\n\tm_spacing(5.f)\n\t{\n\t\tm_state = std::make_unique();\n\t}\n\n\tBoxLayout::~BoxLayout() = default;\n\n\tvoid BoxLayout::Layout()\n\t{\n\t\tBaseWidget::Layout();\n\n\t\tstd::size_t axis;\n\n\t\tswitch (m_orientation)\n\t\t{\n\t\t\tcase BoxLayoutOrientation_Horizontal:\n\t\t\t\taxis = 0; \/\/< x\n\t\t\t\tbreak;\n\n\t\t\tcase BoxLayoutOrientation_Vertical:\n\t\t\t\taxis = 1; \/\/< y\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tassert(false);\n\t\t\t\tbreak;\n\t\t}\n\n\t\t\/\/TODO: Keep solver state when widgets don't change\n\t\tstd::size_t widgetChildCount = GetWidgetChildCount();\n\t\tif (widgetChildCount == 0)\n\t\t\treturn;\n\n\t\tm_state->solver.reset();\n\n\t\tm_state->sizeVar.clear();\n\t\tm_state->sizeVar.reserve(widgetChildCount);\n\n\t\tkiwi::Expression sizeSum;\n\n\t\tNz::Vector2f layoutSize = GetSize();\n\t\tfloat availableSpace = layoutSize[axis] - m_spacing * (widgetChildCount - 1);\n\t\tfloat perfectSpacePerWidget = availableSpace \/ widgetChildCount;\n\n\t\t\/\/ Handle size\n\t\tForEachWidgetChild([&](BaseWidget* child)\n\t\t{\n\t\t\tif (!child->IsVisible())\n\t\t\t\treturn;\n\n\t\t\tfloat maximumSize = child->GetMaximumSize()[axis];\n\t\t\tfloat minimumSize = child->GetMinimumSize()[axis];\n\n\t\t\tm_state->sizeVar.emplace_back();\n\t\t\tauto& sizeVar = m_state->sizeVar.back();\n\n\t\t\tm_state->solver.addConstraint({ sizeVar >= minimumSize | kiwi::strength::required });\n\n\t\t\tif (maximumSize < std::numeric_limits::infinity())\n\t\t\t\tm_state->solver.addConstraint({ sizeVar <= maximumSize | kiwi::strength::required });\n\n\t\t\tm_state->solver.addConstraint({ sizeVar == perfectSpacePerWidget | kiwi::strength::medium });\n\n\t\t\tsizeSum = sizeSum + sizeVar;\n\t\t});\n\n\t\tkiwi::Variable targetSize(\"LayoutSize\");\n\n\t\tm_state->solver.addConstraint(sizeSum <= targetSize | kiwi::strength::strong);\n\n\t\tm_state->solver.addEditVariable(targetSize, kiwi::strength::strong);\n\t\tm_state->solver.suggestValue(targetSize, availableSpace);\n\n\t\tm_state->solver.updateVariables();\n\n\t\tstd::size_t varIndex = 0;\n\n\t\tfloat remainingSize = availableSpace;\n\n\t\tForEachWidgetChild([&](BaseWidget* child)\n\t\t{\n\t\t\tif (!child->IsVisible())\n\t\t\t\treturn;\n\n\t\t\tNz::Vector2f newSize = layoutSize;\n\t\t\tnewSize[axis] = m_state->sizeVar[varIndex].value();\n\n\t\t\tchild->Resize(newSize);\n\t\t\tremainingSize -= newSize[axis];\n\n\t\t\tvarIndex++;\n\t\t});\n\n\t\tfloat spacing = m_spacing + remainingSize \/ (widgetChildCount - 1);\n\n\t\t\/\/ Handle position\n\t\tfloat cursor = 0.f;\n\t\tbool first = true;\n\t\tForEachWidgetChild([&](BaseWidget* child)\n\t\t{\n\t\t\tif (first)\n\t\t\t\tfirst = false;\n\t\t\telse\n\t\t\t\tcursor += spacing;\n\n\t\t\tNz::Vector2f position = Nz::Vector2f(0.f, 0.f);\n\t\t\tposition[axis] = cursor;\n\n\t\t\tchild->SetPosition(position);\n\n\t\t\tcursor += child->GetSize()[axis];\n\t\t});\n\t}\n}\nSdk\/BoxLayout: Fix widgets not taking up free space\/\/ Copyright (C) 2017 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Development Kit\"\n\/\/ For conditions of distribution and use, see copyright notice in Prerequisites.hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Ndk\n{\n\tstruct BoxLayout::State\n\t{\n\t\tstd::vector sizeVar;\n\t\tkiwi::Solver solver;\n\t};\n\n\tBoxLayout::BoxLayout(BaseWidget* parent, BoxLayoutOrientation orientation) :\n\tBaseWidget(parent),\n\tm_orientation(orientation),\n\tm_spacing(5.f)\n\t{\n\t\tm_state = std::make_unique();\n\t}\n\n\tBoxLayout::~BoxLayout() = default;\n\n\tvoid BoxLayout::Layout()\n\t{\n\t\tBaseWidget::Layout();\n\n\t\tstd::size_t axis;\n\n\t\tswitch (m_orientation)\n\t\t{\n\t\t\tcase BoxLayoutOrientation_Horizontal:\n\t\t\t\taxis = 0; \/\/< x\n\t\t\t\tbreak;\n\n\t\t\tcase BoxLayoutOrientation_Vertical:\n\t\t\t\taxis = 1; \/\/< y\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tassert(false);\n\t\t\t\tbreak;\n\t\t}\n\n\t\t\/\/TODO: Keep solver state when widgets don't change\n\t\tstd::size_t widgetChildCount = GetWidgetChildCount();\n\t\tif (widgetChildCount == 0)\n\t\t\treturn;\n\n\t\tm_state->solver.reset();\n\n\t\tm_state->sizeVar.clear();\n\t\tm_state->sizeVar.reserve(widgetChildCount);\n\n\t\tkiwi::Expression sizeSum;\n\n\t\tNz::Vector2f layoutSize = GetSize();\n\t\tfloat availableSpace = layoutSize[axis] - m_spacing * (widgetChildCount - 1);\n\t\tfloat perfectSpacePerWidget = availableSpace \/ widgetChildCount;\n\n\t\t\/\/ Handle size\n\t\tForEachWidgetChild([&](BaseWidget* child)\n\t\t{\n\t\t\tif (!child->IsVisible())\n\t\t\t\treturn;\n\n\t\t\tfloat maximumSize = child->GetMaximumSize()[axis];\n\t\t\tfloat minimumSize = child->GetMinimumSize()[axis];\n\n\t\t\tm_state->sizeVar.emplace_back();\n\t\t\tauto& sizeVar = m_state->sizeVar.back();\n\n\t\t\tm_state->solver.addConstraint({ sizeVar >= minimumSize | kiwi::strength::required });\n\n\t\t\tif (maximumSize < std::numeric_limits::infinity())\n\t\t\t\tm_state->solver.addConstraint({ sizeVar <= maximumSize | kiwi::strength::required });\n\n\t\t\tm_state->solver.addConstraint({ sizeVar >= perfectSpacePerWidget | kiwi::strength::medium });\n\n\t\t\tsizeSum = sizeSum + sizeVar;\n\t\t});\n\n\t\tkiwi::Variable targetSize(\"LayoutSize\");\n\n\t\tm_state->solver.addConstraint(sizeSum <= targetSize | kiwi::strength::strong);\n\n\t\tm_state->solver.addEditVariable(targetSize, kiwi::strength::strong);\n\t\tm_state->solver.suggestValue(targetSize, availableSpace);\n\n\t\tm_state->solver.updateVariables();\n\n\t\tstd::size_t varIndex = 0;\n\n\t\tfloat remainingSize = availableSpace;\n\n\t\tForEachWidgetChild([&](BaseWidget* child)\n\t\t{\n\t\t\tif (!child->IsVisible())\n\t\t\t\treturn;\n\n\t\t\tNz::Vector2f newSize = layoutSize;\n\t\t\tnewSize[axis] = m_state->sizeVar[varIndex].value();\n\n\t\t\tchild->Resize(newSize);\n\t\t\tremainingSize -= newSize[axis];\n\n\t\t\tvarIndex++;\n\t\t});\n\n\t\tfloat spacing = m_spacing + remainingSize \/ (widgetChildCount - 1);\n\n\t\t\/\/ Handle position\n\t\tfloat cursor = 0.f;\n\t\tbool first = true;\n\t\tForEachWidgetChild([&](BaseWidget* child)\n\t\t{\n\t\t\tif (first)\n\t\t\t\tfirst = false;\n\t\t\telse\n\t\t\t\tcursor += spacing;\n\n\t\t\tNz::Vector2f position = Nz::Vector2f(0.f, 0.f);\n\t\t\tposition[axis] = cursor;\n\n\t\t\tchild->SetPosition(position);\n\n\t\t\tcursor += child->GetSize()[axis];\n\t\t});\n\t}\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n\n This source file is part of the TEM tomography project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n#include \"CentralWidget.h\"\n#include \"ui_CentralWidget.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"ActiveObjects.h\"\n#include \"ComputeHistogram.h\"\n#include \"DataSource.h\"\n#include \"ModuleContour.h\"\n#include \"ModuleManager.h\"\n#include \"Utilities.h\"\n\n#ifdef DAX_DEVICE_ADAPTER\n# include \"dax\/ModuleStreamingContour.h\"\n#endif\n\nnamespace TEM\n{\n\n\/\/-----------------------------------------------------------------------------\n\/\/ This is just here for now - quick and dirty historgram calculations...\nvoid PopulateHistogram(vtkImageData *input, vtkTable *output)\n{\n \/\/ The output table will have the twice the number of columns, they will be\n \/\/ the x and y for input column. This is the bin centers, and the population.\n double minmax[2] = { 0.0, 0.0 };\n const int numberOfBins = 256;\n\n \/\/ The bin values are the centers, extending +\/- half an inc either side\n switch (input->GetScalarType())\n {\n vtkTemplateMacro(\n TEM::GetScalarRange(reinterpret_cast(input->GetPointData()->GetScalars()->GetVoidPointer(0)),\n input->GetPointData()->GetScalars()->GetNumberOfTuples(),\n minmax));\n default:\n break;\n }\n if (minmax[0] == minmax[1])\n {\n minmax[1] = minmax[0] + 1.0;\n }\n\n double inc = (minmax[1] - minmax[0]) \/ numberOfBins;\n double halfInc = inc \/ 2.0;\n vtkSmartPointer extents =\n vtkFloatArray::SafeDownCast(\n output->GetColumnByName(vtkStdString(\"image_extents\").c_str()));\n if (!extents)\n {\n extents = vtkSmartPointer::New();\n extents->SetName(vtkStdString(\"image_extents\").c_str());\n }\n extents->SetNumberOfTuples(numberOfBins);\n double min = minmax[0] + halfInc;\n for (int j = 0; j < numberOfBins; ++j)\n {\n extents->SetValue(j, min + j * inc);\n }\n vtkSmartPointer populations =\n vtkIntArray::SafeDownCast(\n output->GetColumnByName(vtkStdString(\"image_pops\").c_str()));\n if (!populations)\n {\n populations = vtkSmartPointer::New();\n populations->SetName(vtkStdString(\"image_pops\").c_str());\n }\n populations->SetNumberOfTuples(numberOfBins);\n int *pops = static_cast(populations->GetVoidPointer(0));\n for (int k = 0; k < numberOfBins; ++k)\n {\n pops[k] = 0;\n }\n\n switch (input->GetScalarType())\n {\n vtkTemplateMacro(\n TEM::CalculateHistogram(reinterpret_cast(input->GetPointData()->GetScalars()->GetVoidPointer(0)),\n input->GetPointData()->GetScalars()->GetNumberOfTuples(),\n minmax[0], pops, inc, numberOfBins));\n default:\n cout << \"UpdateFromFile: Unknown data type\" << endl;\n }\n\n#ifndef NDEBUG\n vtkIdType total = 0;\n for (int i = 0; i < numberOfBins; ++i)\n total += pops[i];\n assert(total == input->GetPointData()->GetScalars()->GetNumberOfTuples());\n#endif\n\n output->AddColumn(extents.GetPointer());\n output->AddColumn(populations.GetPointer());\n}\n\n\/\/ Quick background thread for the histogram calculation.\nclass HistogramWorker : public QThread\n{\n Q_OBJECT\n\n void run();\n\npublic:\n HistogramWorker(QObject *p = 0) : QThread(p) {}\n\n vtkSmartPointer input;\n vtkSmartPointer output;\n};\n\nvoid HistogramWorker::run()\n{\n if (input && output)\n {\n PopulateHistogram(input.Get(), output.Get());\n }\n}\n\nclass CentralWidget::CWInternals\n{\npublic:\n Ui::CentralWidget Ui;\n};\n\nclass vtkHistogramMarker : public vtkPlot\n{\npublic:\n static vtkHistogramMarker * New();\n double PositionX;\n\n bool Paint(vtkContext2D *painter)\n {\n vtkNew pen;\n pen->SetColor(255, 0, 0, 255);\n pen->SetWidth(2.0);\n painter->ApplyPen(pen.Get());\n painter->DrawLine(PositionX, 0, PositionX, 1e9);\n return true;\n }\n};\nvtkStandardNewMacro(vtkHistogramMarker);\n\nclass vtkChartHistogram : public vtkChartXY\n{\npublic:\n static vtkChartHistogram * New();\n\n bool MouseDoubleClickEvent(const vtkContextMouseEvent &mouse);\n\n vtkNew Transform;\n double PositionX;\n vtkNew Marker;\n};\n\nvtkStandardNewMacro(vtkChartHistogram)\n\nbool vtkChartHistogram::MouseDoubleClickEvent(const vtkContextMouseEvent &m)\n{\n \/\/ Determine the location of the click, and emit something we can listen to!\n vtkPlotBar *histo = 0;\n if (this->GetNumberOfPlots() > 0)\n {\n histo = vtkPlotBar::SafeDownCast(this->GetPlot(0));\n }\n if (!histo)\n {\n return false;\n }\n this->CalculateUnscaledPlotTransform(histo->GetXAxis(), histo->GetYAxis(),\n this->Transform.Get());\n vtkVector2f pos;\n this->Transform->InverseTransformPoints(m.GetScenePos().GetData(), pos.GetData(),\n 1);\n this->PositionX = pos.GetX();\n this->Marker->PositionX = this->PositionX;\n this->Marker->Modified();\n this->Scene->SetDirty(true);\n if (this->GetNumberOfPlots() == 1)\n {\n this->AddPlot(this->Marker.Get());\n }\n this->InvokeEvent(vtkCommand::CursorChangedEvent);\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nCentralWidget::CentralWidget(QWidget* parentObject, Qt::WindowFlags wflags)\n : Superclass(parentObject, wflags),\n Internals(new CentralWidget::CWInternals()),\n Worker(NULL)\n{\n this->Internals->Ui.setupUi(this);\n\n QList sizes;\n sizes << 200 << 200;\n this->Internals->Ui.splitter->setSizes(sizes);\n this->Internals->Ui.splitter->setStretchFactor(0, 0);\n this->Internals->Ui.splitter->setStretchFactor(1, 1);\n\n \/\/ Set up our little chart.\n this->Histogram\n ->SetInteractor(this->Internals->Ui.histogramWidget->GetInteractor());\n this->Internals->Ui.histogramWidget\n ->SetRenderWindow(this->Histogram->GetRenderWindow());\n vtkChartHistogram* chart = this->Chart.Get();\n this->Histogram->GetScene()->AddItem(chart);\n chart->SetBarWidthFraction(1.0);\n chart->SetRenderEmpty(true);\n chart->SetAutoAxes(false);\n chart->GetAxis(vtkAxis::LEFT)->SetTitle(\"\");\n chart->GetAxis(vtkAxis::BOTTOM)->SetTitle(\"\");\n chart->GetAxis(vtkAxis::LEFT)->SetBehavior(vtkAxis::FIXED);\n chart->GetAxis(vtkAxis::LEFT)->SetRange(0.0001, 10);\n chart->GetAxis(vtkAxis::LEFT)->SetMinimumLimit(1);\n chart->GetAxis(vtkAxis::LEFT)->SetLogScale(true);\n\n this->EventLink->Connect(chart, vtkCommand::CursorChangedEvent, this,\n SLOT(histogramClicked(vtkObject*)));\n}\n\n\/\/-----------------------------------------------------------------------------\nCentralWidget::~CentralWidget()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid CentralWidget::setDataSource(DataSource* source)\n{\n if (this->ADataSource)\n {\n this->disconnect(this->ADataSource);\n }\n this->ADataSource = source;\n if (source)\n {\n this->connect(source, SIGNAL(dataChanged()), SLOT(refreshHistogram()));\n }\n\n \/\/ Whenever the data source changes clear the plot, and then populate when\n \/\/ ready (or use the cached histogram values.\n this->Chart->ClearPlots();\n\n if (!source)\n {\n return;\n }\n\n \/\/ Get the actual data source, build a histogram out of it.\n vtkTrivialProducer *t = vtkTrivialProducer::SafeDownCast(\n source->producer()->GetClientSideObject());\n vtkImageData *data = vtkImageData::SafeDownCast(t->GetOutputDataObject(0));\n\n \/\/ Check our cache, and use that if appopriate (or update it).\n if (this->HistogramCache.contains(data))\n {\n vtkTable *cachedTable = this->HistogramCache[data];\n if (cachedTable->GetMTime() > data->GetMTime())\n {\n this->setHistogramTable(cachedTable);\n return;\n }\n else\n {\n \/\/ Should this ever happen? Do we want to support this? -- YES!!!\n \/\/qDebug() << \"Image data changed after histogram calculation.\";\n \/\/return;\n this->HistogramCache.remove(data);\n }\n }\n\n \/\/ Calculate a histogram.\n vtkNew table;\n this->HistogramCache[data] = table.Get();\n\n if (!this->Worker)\n {\n this->Worker = new HistogramWorker(this);\n connect(this->Worker, SIGNAL(finished()), SLOT(histogramReady()));\n }\n else if (this->Worker->isRunning())\n {\n \/\/ FIXME: Queue, abort, something.\n qDebug() << \"Worker already running, skipping this one.\";\n return;\n }\n this->Worker->input = data;\n this->Worker->output = table.Get();\n this->Worker->start();\n}\n\nvoid CentralWidget::refreshHistogram()\n{\n this->setDataSource(this->ADataSource);\n}\n\nvoid CentralWidget::histogramReady()\n{\n if (!this->Worker || !this->Worker->input || !this->Worker->output)\n return;\n\n this->setHistogramTable(this->Worker->output.Get());\n\n this->Worker->input = NULL;\n this->Worker->output = NULL;\n}\n\nvoid CentralWidget::histogramClicked(vtkObject *caller)\n{\n \/\/qDebug() << \"Histogram clicked at\" << this->Chart->PositionX\n \/\/ << \"making this a great spot to ask for an isosurface at value\"\n \/\/ << this->Chart->PositionX;\n Q_ASSERT(this->ADataSource);\n\n vtkSMViewProxy* view = ActiveObjects::instance().activeView();\n if (!view)\n {\n return;\n }\n\n \/\/ Use active ModuleContour is possible. Otherwise, find the first existing\n \/\/ ModuleContour instance or just create a new one, if none exists.\n#ifdef DAX_DEVICE_ADAPTER\n typedef ModuleStreamingContour ModuleContourType;\n#else\n typedef ModuleContour ModuleContourType;\n#endif\n\n ModuleContourType* contour = qobject_cast(\n ActiveObjects::instance().activeModule());\n if (!contour)\n {\n QList contours =\n ModuleManager::instance().findModules(this->ADataSource, view);\n if (contours.size() == 0)\n {\n contour = qobject_cast(ModuleManager::instance().createAndAddModule(\n \"Contour\", this->ADataSource, view));\n }\n else\n {\n contour = contours[0];\n }\n ActiveObjects::instance().setActiveModule(contour);\n }\n Q_ASSERT(contour);\n contour->setIsoValue(this->Chart->PositionX);\n TEM::convert(view)->render();\n}\n\nvoid CentralWidget::setHistogramTable(vtkTable *table)\n{\n this->Chart->ClearPlots();\n vtkPlot *plot = this->Chart->AddPlot(vtkChart::BAR);\n plot->SetInputData(table, \"image_extents\", \"image_pops\");\n plot->SetColor(0, 0, 255, 255);\n plot->GetPen()->SetLineType(vtkPen::NO_PEN);\n vtkDataArray *arr =\n vtkDataArray::SafeDownCast(table->GetColumnByName(\"image_pops\"));\n if (arr)\n {\n double max = log10(arr->GetRange()[1]);\n vtkAxis *axis = this->Chart->GetAxis(vtkAxis::LEFT);\n axis->SetUnscaledMinimum(1.0);\n axis->SetMaximumLimit(max + 2.0);\n axis->SetMaximum(static_cast(max) + 1.0);\n }\n}\n\n} \/\/ end of namespace TEM\n\n#include \"CentralWidget.moc\"\nUse the maximum area to show the bars\/******************************************************************************\n\n This source file is part of the TEM tomography project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n#include \"CentralWidget.h\"\n#include \"ui_CentralWidget.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"ActiveObjects.h\"\n#include \"ComputeHistogram.h\"\n#include \"DataSource.h\"\n#include \"ModuleContour.h\"\n#include \"ModuleManager.h\"\n#include \"Utilities.h\"\n\n#ifdef DAX_DEVICE_ADAPTER\n# include \"dax\/ModuleStreamingContour.h\"\n#endif\n\nnamespace TEM\n{\n\n\/\/-----------------------------------------------------------------------------\n\/\/ This is just here for now - quick and dirty historgram calculations...\nvoid PopulateHistogram(vtkImageData *input, vtkTable *output)\n{\n \/\/ The output table will have the twice the number of columns, they will be\n \/\/ the x and y for input column. This is the bin centers, and the population.\n double minmax[2] = { 0.0, 0.0 };\n const int numberOfBins = 256;\n\n \/\/ The bin values are the centers, extending +\/- half an inc either side\n switch (input->GetScalarType())\n {\n vtkTemplateMacro(\n TEM::GetScalarRange(reinterpret_cast(input->GetPointData()->GetScalars()->GetVoidPointer(0)),\n input->GetPointData()->GetScalars()->GetNumberOfTuples(),\n minmax));\n default:\n break;\n }\n if (minmax[0] == minmax[1])\n {\n minmax[1] = minmax[0] + 1.0;\n }\n\n double inc = (minmax[1] - minmax[0]) \/ numberOfBins;\n double halfInc = inc \/ 2.0;\n vtkSmartPointer extents =\n vtkFloatArray::SafeDownCast(\n output->GetColumnByName(vtkStdString(\"image_extents\").c_str()));\n if (!extents)\n {\n extents = vtkSmartPointer::New();\n extents->SetName(vtkStdString(\"image_extents\").c_str());\n }\n extents->SetNumberOfTuples(numberOfBins);\n double min = minmax[0] + halfInc;\n for (int j = 0; j < numberOfBins; ++j)\n {\n extents->SetValue(j, min + j * inc);\n }\n vtkSmartPointer populations =\n vtkIntArray::SafeDownCast(\n output->GetColumnByName(vtkStdString(\"image_pops\").c_str()));\n if (!populations)\n {\n populations = vtkSmartPointer::New();\n populations->SetName(vtkStdString(\"image_pops\").c_str());\n }\n populations->SetNumberOfTuples(numberOfBins);\n int *pops = static_cast(populations->GetVoidPointer(0));\n for (int k = 0; k < numberOfBins; ++k)\n {\n pops[k] = 0;\n }\n\n switch (input->GetScalarType())\n {\n vtkTemplateMacro(\n TEM::CalculateHistogram(reinterpret_cast(input->GetPointData()->GetScalars()->GetVoidPointer(0)),\n input->GetPointData()->GetScalars()->GetNumberOfTuples(),\n minmax[0], pops, inc, numberOfBins));\n default:\n cout << \"UpdateFromFile: Unknown data type\" << endl;\n }\n\n#ifndef NDEBUG\n vtkIdType total = 0;\n for (int i = 0; i < numberOfBins; ++i)\n total += pops[i];\n assert(total == input->GetPointData()->GetScalars()->GetNumberOfTuples());\n#endif\n\n output->AddColumn(extents.GetPointer());\n output->AddColumn(populations.GetPointer());\n}\n\n\/\/ Quick background thread for the histogram calculation.\nclass HistogramWorker : public QThread\n{\n Q_OBJECT\n\n void run();\n\npublic:\n HistogramWorker(QObject *p = 0) : QThread(p) {}\n\n vtkSmartPointer input;\n vtkSmartPointer output;\n};\n\nvoid HistogramWorker::run()\n{\n if (input && output)\n {\n PopulateHistogram(input.Get(), output.Get());\n }\n}\n\nclass CentralWidget::CWInternals\n{\npublic:\n Ui::CentralWidget Ui;\n};\n\nclass vtkHistogramMarker : public vtkPlot\n{\npublic:\n static vtkHistogramMarker * New();\n double PositionX;\n\n bool Paint(vtkContext2D *painter)\n {\n vtkNew pen;\n pen->SetColor(255, 0, 0, 255);\n pen->SetWidth(2.0);\n painter->ApplyPen(pen.Get());\n painter->DrawLine(PositionX, 0, PositionX, 1e9);\n return true;\n }\n};\nvtkStandardNewMacro(vtkHistogramMarker);\n\nclass vtkChartHistogram : public vtkChartXY\n{\npublic:\n static vtkChartHistogram * New();\n\n bool MouseDoubleClickEvent(const vtkContextMouseEvent &mouse);\n\n vtkNew Transform;\n double PositionX;\n vtkNew Marker;\n};\n\nvtkStandardNewMacro(vtkChartHistogram)\n\nbool vtkChartHistogram::MouseDoubleClickEvent(const vtkContextMouseEvent &m)\n{\n \/\/ Determine the location of the click, and emit something we can listen to!\n vtkPlotBar *histo = 0;\n if (this->GetNumberOfPlots() > 0)\n {\n histo = vtkPlotBar::SafeDownCast(this->GetPlot(0));\n }\n if (!histo)\n {\n return false;\n }\n this->CalculateUnscaledPlotTransform(histo->GetXAxis(), histo->GetYAxis(),\n this->Transform.Get());\n vtkVector2f pos;\n this->Transform->InverseTransformPoints(m.GetScenePos().GetData(), pos.GetData(),\n 1);\n this->PositionX = pos.GetX();\n this->Marker->PositionX = this->PositionX;\n this->Marker->Modified();\n this->Scene->SetDirty(true);\n if (this->GetNumberOfPlots() == 1)\n {\n this->AddPlot(this->Marker.Get());\n }\n this->InvokeEvent(vtkCommand::CursorChangedEvent);\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nCentralWidget::CentralWidget(QWidget* parentObject, Qt::WindowFlags wflags)\n : Superclass(parentObject, wflags),\n Internals(new CentralWidget::CWInternals()),\n Worker(NULL)\n{\n this->Internals->Ui.setupUi(this);\n\n QList sizes;\n sizes << 200 << 200;\n this->Internals->Ui.splitter->setSizes(sizes);\n this->Internals->Ui.splitter->setStretchFactor(0, 0);\n this->Internals->Ui.splitter->setStretchFactor(1, 1);\n\n \/\/ Set up our little chart.\n this->Histogram\n ->SetInteractor(this->Internals->Ui.histogramWidget->GetInteractor());\n this->Internals->Ui.histogramWidget\n ->SetRenderWindow(this->Histogram->GetRenderWindow());\n vtkChartHistogram* chart = this->Chart.Get();\n this->Histogram->GetScene()->AddItem(chart);\n chart->SetBarWidthFraction(1.0);\n chart->SetRenderEmpty(true);\n chart->SetAutoAxes(false);\n chart->GetAxis(vtkAxis::LEFT)->SetTitle(\"\");\n chart->GetAxis(vtkAxis::BOTTOM)->SetTitle(\"\");\n chart->GetAxis(vtkAxis::LEFT)->SetBehavior(vtkAxis::FIXED);\n chart->GetAxis(vtkAxis::LEFT)->SetRange(0.0001, 10);\n chart->GetAxis(vtkAxis::LEFT)->SetMinimumLimit(1);\n chart->GetAxis(vtkAxis::LEFT)->SetLogScale(true);\n\n this->EventLink->Connect(chart, vtkCommand::CursorChangedEvent, this,\n SLOT(histogramClicked(vtkObject*)));\n}\n\n\/\/-----------------------------------------------------------------------------\nCentralWidget::~CentralWidget()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid CentralWidget::setDataSource(DataSource* source)\n{\n if (this->ADataSource)\n {\n this->disconnect(this->ADataSource);\n }\n this->ADataSource = source;\n if (source)\n {\n this->connect(source, SIGNAL(dataChanged()), SLOT(refreshHistogram()));\n }\n\n \/\/ Whenever the data source changes clear the plot, and then populate when\n \/\/ ready (or use the cached histogram values.\n this->Chart->ClearPlots();\n\n if (!source)\n {\n return;\n }\n\n \/\/ Get the actual data source, build a histogram out of it.\n vtkTrivialProducer *t = vtkTrivialProducer::SafeDownCast(\n source->producer()->GetClientSideObject());\n vtkImageData *data = vtkImageData::SafeDownCast(t->GetOutputDataObject(0));\n\n \/\/ Check our cache, and use that if appopriate (or update it).\n if (this->HistogramCache.contains(data))\n {\n vtkTable *cachedTable = this->HistogramCache[data];\n if (cachedTable->GetMTime() > data->GetMTime())\n {\n this->setHistogramTable(cachedTable);\n return;\n }\n else\n {\n \/\/ Should this ever happen? Do we want to support this? -- YES!!!\n \/\/qDebug() << \"Image data changed after histogram calculation.\";\n \/\/return;\n this->HistogramCache.remove(data);\n }\n }\n\n \/\/ Calculate a histogram.\n vtkNew table;\n this->HistogramCache[data] = table.Get();\n\n if (!this->Worker)\n {\n this->Worker = new HistogramWorker(this);\n connect(this->Worker, SIGNAL(finished()), SLOT(histogramReady()));\n }\n else if (this->Worker->isRunning())\n {\n \/\/ FIXME: Queue, abort, something.\n qDebug() << \"Worker already running, skipping this one.\";\n return;\n }\n this->Worker->input = data;\n this->Worker->output = table.Get();\n this->Worker->start();\n}\n\nvoid CentralWidget::refreshHistogram()\n{\n this->setDataSource(this->ADataSource);\n}\n\nvoid CentralWidget::histogramReady()\n{\n if (!this->Worker || !this->Worker->input || !this->Worker->output)\n return;\n\n this->setHistogramTable(this->Worker->output.Get());\n\n this->Worker->input = NULL;\n this->Worker->output = NULL;\n}\n\nvoid CentralWidget::histogramClicked(vtkObject *caller)\n{\n \/\/qDebug() << \"Histogram clicked at\" << this->Chart->PositionX\n \/\/ << \"making this a great spot to ask for an isosurface at value\"\n \/\/ << this->Chart->PositionX;\n Q_ASSERT(this->ADataSource);\n\n vtkSMViewProxy* view = ActiveObjects::instance().activeView();\n if (!view)\n {\n return;\n }\n\n \/\/ Use active ModuleContour is possible. Otherwise, find the first existing\n \/\/ ModuleContour instance or just create a new one, if none exists.\n#ifdef DAX_DEVICE_ADAPTER\n typedef ModuleStreamingContour ModuleContourType;\n#else\n typedef ModuleContour ModuleContourType;\n#endif\n\n ModuleContourType* contour = qobject_cast(\n ActiveObjects::instance().activeModule());\n if (!contour)\n {\n QList contours =\n ModuleManager::instance().findModules(this->ADataSource, view);\n if (contours.size() == 0)\n {\n contour = qobject_cast(ModuleManager::instance().createAndAddModule(\n \"Contour\", this->ADataSource, view));\n }\n else\n {\n contour = contours[0];\n }\n ActiveObjects::instance().setActiveModule(contour);\n }\n Q_ASSERT(contour);\n contour->setIsoValue(this->Chart->PositionX);\n TEM::convert(view)->render();\n}\n\nvoid CentralWidget::setHistogramTable(vtkTable *table)\n{\n this->Chart->ClearPlots();\n vtkPlot *plot = this->Chart->AddPlot(vtkChart::BAR);\n plot->SetInputData(table, \"image_extents\", \"image_pops\");\n plot->SetColor(0, 0, 255, 255);\n plot->GetPen()->SetLineType(vtkPen::NO_PEN);\n vtkDataArray *arr =\n vtkDataArray::SafeDownCast(table->GetColumnByName(\"image_pops\"));\n if (arr)\n {\n double max = log10(arr->GetRange()[1]);\n vtkAxis *axis = this->Chart->GetAxis(vtkAxis::LEFT);\n axis->SetUnscaledMinimum(1.0);\n axis->SetMaximumLimit(max + 2.0);\n axis->SetMaximum(static_cast(max) + 1.0);\n }\n arr = vtkDataArray::SafeDownCast(table->GetColumnByName(\"image_extents\"));\n if (arr && arr->GetNumberOfTuples() > 2)\n {\n double range[2];\n arr->GetRange(range);\n double halfInc = (arr->GetTuple1(1) - arr->GetTuple1(0)) \/ 2.0;\n vtkAxis *axis = this->Chart->GetAxis(vtkAxis::BOTTOM);\n axis->SetBehavior(vtkAxis::FIXED);\n axis->SetRange(range[0] - halfInc , range[1] + halfInc);\n }\n}\n\n} \/\/ end of namespace TEM\n\n#include \"CentralWidget.moc\"\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"include\/swri_console\/bag_reader.h\"\n\n#include \n#include \n\nusing namespace swri_console;\n\nvoid BagReader::readBagFile(const QString& filename)\n{\n rosbag::Bag bag;\n bag.open(filename.toStdString(), rosbag::bagmode::Read);\n\n std::vector topics;\n topics.push_back(std::string(\"\/rosout\"));\n\n rosbag::View view(bag, rosbag::TopicQuery(topics));\n rosbag::View::const_iterator iter;\n\n for(iter = view.begin(); iter != view.end(); iter++)\n {\n rosgraph_msgs::LogConstPtr log = iter->instantiate();\n if (log != NULL ) {\n emit logReceived(log);\n }\n else {\n qWarning(\"Got a message that was not a log message but a: %s\", iter->getDataType().c_str());\n }\n }\n\n emit finishedReading();\n}\n\nvoid BagReader::promptForBagFile()\n{\n QString filename = QFileDialog::getOpenFileName(NULL,\n tr(\"Open Bag File\"),\n QDir::homePath(),\n tr(\"Bag Files (*.bag)\"));\n\n if (filename != NULL)\n {\n readBagFile(filename);\n }\n}\nFixing a cppcheck issue.#include \n#include \n\n#include \"include\/swri_console\/bag_reader.h\"\n\n#include \n#include \n\nusing namespace swri_console;\n\nvoid BagReader::readBagFile(const QString& filename)\n{\n rosbag::Bag bag;\n bag.open(filename.toStdString(), rosbag::bagmode::Read);\n\n std::vector topics;\n topics.push_back(std::string(\"\/rosout\"));\n\n rosbag::View view(bag, rosbag::TopicQuery(topics));\n rosbag::View::const_iterator iter;\n\n for(iter = view.begin(); iter != view.end(); ++iter)\n {\n rosgraph_msgs::LogConstPtr log = iter->instantiate();\n if (log != NULL ) {\n emit logReceived(log);\n }\n else {\n qWarning(\"Got a message that was not a log message but a: %s\", iter->getDataType().c_str());\n }\n }\n\n emit finishedReading();\n}\n\nvoid BagReader::promptForBagFile()\n{\n QString filename = QFileDialog::getOpenFileName(NULL,\n tr(\"Open Bag File\"),\n QDir::homePath(),\n tr(\"Bag Files (*.bag)\"));\n\n if (filename != NULL)\n {\n readBagFile(filename);\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing iter::zip;\n\nint main() {\n \/\/Ryan's test\n {\n std::vector ivec{1, 4, 9, 16, 25, 36};\n std::vector svec{\"hello\", \"good day\", \"goodbye\"};\n\n for (auto e : zip(ivec, svec)) {\n auto &i = std::get<0>(e);\n std::cout << i << std::endl;\n i = 69;\n std::cout << std::get<1>(e) << std::endl;\n }\n\n for (auto e : zip(ivec, svec)) {\n std::cout << std::get<0>(e) << std::endl;\n std::cout << std::get<1>(e) << std::endl;\n }\n\n for (auto e : zip(iter::range(10), iter::range(10, 20))) {\n std::cout << std::get<0>(e) << '\\n';\n std::cout << std::get<1>(e) << '\\n';\n }\n }\n \/\/Aaron's test\n {\n std::array i{{1,2,3,4}};\n std::vector f{1.2,1.4,12.3,4.5,9.9};\n std::vector s{\"i\",\"like\",\"apples\",\"alot\",\"dude\"};\n std::array d{{1.2,1.2,1.2,1.2,1.2}};\n std::cout << std::endl << \"Variadic template zip iterator\" << std::endl;\n for (auto e : iter::zip(i,f,s,d)) {\n std::cout << std::get<0>(e) << \" \" \n << std::get<1>(e) << \" \" \n << std::get<2>(e) << \" \"\n << std::get<3>(e) << std::endl;\n std::get<1>(e)=2.2f; \/\/modify the float array\n }\n std::cout<(e) << \" \" \n << std::get<1>(e) << \" \"\n << std::get<2>(e) << \" \" \n << std::get<3>(e) << std::endl;\n }\n std::cout << std::endl << \"Try some weird range differences\" << std::endl;\n std::vector empty{};\n for (auto e : iter::zip(empty,f,s,d)) {\n std::cout << std::get<0>(e) << \" \" \n << std::get<1>(e) << \" \" \n << std::get<2>(e) << \" \"\n << std::get<3>(e) << std::endl;\n }\n std::cout<(e) << \" \" \n << std::get<1>(e) << \" \" \n << std::get<2>(e) << \" \"\n << std::get<3>(e) << std::endl;\n }\/\/both should print nothing\n std::cout<(e) << \" \" \n << std::get<1>(e) << \" \" \n << std::get<2>(e) << \" \"\n << std::get<3>(e) << std::endl;\n }\n std::cout< constvector{1.1,2.2,3.3,4.4};\n for (auto e : zip(iter::chain(std::vector(5,5),std::array{{1,2}}),\n std::initializer_list{\"asdfas\",\"aaron\",\"ryan\",\"apple\",\"juice\"},\n constvector)) \n { \n\n std::cout << std::get<0>(e) << \" \" \n << std::get<1>(e) << \" \" \n << std::get<2>(e) << std::endl;\n }\n }\n\n\n\n\n return 0;\n}\n\nadds zip test with statically sized array#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing iter::zip;\n\nint main() {\n \/\/Ryan's test\n {\n std::vector ivec{1, 4, 9, 16, 25, 36};\n std::vector svec{\"hello\", \"good day\", \"goodbye\"};\n\n for (auto e : zip(ivec, svec)) {\n auto &i = std::get<0>(e);\n std::cout << i << std::endl;\n i = 69;\n std::cout << std::get<1>(e) << std::endl;\n }\n for (auto e : zip(ivec, svec)) {\n std::cout << std::get<0>(e) << std::endl;\n std::cout << std::get<1>(e) << std::endl;\n }\n\n for (auto e : zip(iter::range(10), iter::range(10, 20))) {\n std::cout << std::get<0>(e) << '\\n';\n std::cout << std::get<1>(e) << '\\n';\n }\n\n int arr[] = {1,2,3,3,4};\n for (auto e : zip(iter::range(10), arr)) {\n std::cout << std::get<0>(e) << '\\n';\n std::cout << std::get<1>(e) << '\\n';\n }\n \n }\n \/\/Aaron's test\n {\n std::array i{{1,2,3,4}};\n std::vector f{1.2,1.4,12.3,4.5,9.9};\n std::vector s{\"i\",\"like\",\"apples\",\"alot\",\"dude\"};\n std::array d{{1.2,1.2,1.2,1.2,1.2}};\n std::cout << std::endl << \"Variadic template zip iterator\" << std::endl;\n for (auto e : iter::zip(i,f,s,d)) {\n std::cout << std::get<0>(e) << \" \" \n << std::get<1>(e) << \" \" \n << std::get<2>(e) << \" \"\n << std::get<3>(e) << std::endl;\n std::get<1>(e)=2.2f; \/\/modify the float array\n }\n std::cout<(e) << \" \" \n << std::get<1>(e) << \" \"\n << std::get<2>(e) << \" \" \n << std::get<3>(e) << std::endl;\n }\n std::cout << std::endl << \"Try some weird range differences\" << std::endl;\n std::vector empty{};\n for (auto e : iter::zip(empty,f,s,d)) {\n std::cout << std::get<0>(e) << \" \" \n << std::get<1>(e) << \" \" \n << std::get<2>(e) << \" \"\n << std::get<3>(e) << std::endl;\n }\n std::cout<(e) << \" \" \n << std::get<1>(e) << \" \" \n << std::get<2>(e) << \" \"\n << std::get<3>(e) << std::endl;\n }\/\/both should print nothing\n std::cout<(e) << \" \" \n << std::get<1>(e) << \" \" \n << std::get<2>(e) << \" \"\n << std::get<3>(e) << std::endl;\n }\n std::cout< constvector{1.1,2.2,3.3,4.4};\n for (auto e : zip(iter::chain(std::vector(5,5),std::array{{1,2}}),\n std::initializer_list{\"asdfas\",\"aaron\",\"ryan\",\"apple\",\"juice\"},\n constvector)) \n { \n\n std::cout << std::get<0>(e) << \" \" \n << std::get<1>(e) << \" \" \n << std::get<2>(e) << std::endl;\n }\n }\n\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/* -------------------------------------------------------------------------- *\/\n\/* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\/\n\/* not use this file except in compliance with the License. You may obtain *\/\n\/* a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\/\n\/* See the License for the specific language governing permissions and *\/\n\/* limitations under the License. *\/\n\/* -------------------------------------------------------------------------- *\/\n\n#include \"MarketPlaceManager.h\"\n#include \"MarketPlacePool.h\"\n#include \"MarketPlaceAppPool.h\"\n#include \"MarketPlaceManagerDriver.h\"\n\n#include \"Nebula.h\"\n\nconst char * MarketPlaceManager::market_driver_name = \"market_exe\";\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nextern \"C\" void * marketplace_action_loop(void *arg)\n{\n MarketPlaceManager * mpm;\n\n if ( arg == 0 )\n {\n return 0;\n }\n\n NebulaLog::log(\"MKP\", Log::INFO, \"Marketplace Manager started.\");\n\n mpm = static_cast(arg);\n\n mpm->am.loop(mpm->timer_period);\n\n NebulaLog::log(\"MKP\", Log::INFO, \"Marketplace Manager stopped.\");\n\n return 0;\n}\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nMarketPlaceManager::MarketPlaceManager(\n time_t _timer_period,\n time_t _monitor_period,\n std::vector& _mads):\n MadManager(_mads),\n timer_period(_timer_period),\n monitor_period(_monitor_period),\n imagem(0)\n{\n Nebula& nd = Nebula::instance();\n\n mppool = nd.get_marketpool();\n apppool = nd.get_apppool();\n dspool = nd.get_dspool();\n ipool = nd.get_ipool();\n\n am.addListener(this);\n};\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint MarketPlaceManager::load_mads(int uid)\n{\n MarketPlaceManagerDriver * marketm_mad;\n\n std::ostringstream oss;\n const VectorAttribute * vattr = 0;\n\n int rc;\n\n NebulaLog::log(\"MKP\", Log::INFO,\"Loading Marketplace Manager driver.\");\n\n if ( mad_conf.size() > 0 )\n {\n vattr = static_cast(mad_conf[0]);\n }\n\n if ( vattr == 0 )\n {\n NebulaLog::log(\"MKP\", Log::INFO,\"Failed to load Marketplace Manager driver.\");\n return -1;\n }\n\n VectorAttribute market_conf(\"MARKET_MAD\", vattr->value());\n\n market_conf.replace(\"NAME\", market_driver_name);\n\n marketm_mad= new MarketPlaceManagerDriver(0, market_conf.value(), false,\n mppool, apppool, this);\n\n rc = add(marketm_mad);\n\n if ( rc == 0 )\n {\n oss.str(\"\");\n oss << \"\\tMarketplace Manager loaded\";\n\n NebulaLog::log(\"MKP\", Log::INFO, oss);\n }\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid MarketPlaceManager::init_managers()\n{\n Nebula& nd = Nebula::instance();\n\n imagem = nd.get_imagem();\n raftm = nd.get_raftm();\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint MarketPlaceManager::start()\n{\n int rc;\n pthread_attr_t pattr;\n\n rc = MadManager::start();\n\n if ( rc != 0 )\n {\n return -1;\n }\n\n NebulaLog::log(\"ImM\",Log::INFO,\"Starting Marketplace Manager...\");\n\n pthread_attr_init (&pattr);\n pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);\n\n rc = pthread_create(&marketm_thread, &pattr, marketplace_action_loop,\n (void *) this);\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nstring * MarketPlaceManager::format_message(\n const string& app_data,\n const string& market_data,\n const string& extra_data)\n{\n ostringstream oss;\n\n oss << \"\"\n << app_data\n << market_data\n << extra_data\n << \"<\/MARKET_DRIVER_ACTION_DATA>\";\n\n return one_util::base64_encode(oss.str());\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid MarketPlaceManager::timer_action(const ActionRequest& ar)\n{\n static int mark = 0;\n static int tics = monitor_period - 5; \/\/first monitor in 5 secs\n\n mark += timer_period;\n tics += timer_period;\n\n if ( mark >= 600 )\n {\n NebulaLog::log(\"MKP\",Log::INFO,\"--Mark--\");\n mark = 0;\n }\n\n if ( tics < monitor_period )\n {\n return;\n }\n\n tics = 0;\n\n if ( !raftm->is_leader() && !raftm->is_solo() )\n {\n return;\n }\n\n int rc;\n\n std::vector markets;\n std::vector::iterator it;\n\n rc = mppool->list(markets);\n\n if ( rc != 0 )\n {\n return;\n }\n\n for(it = markets.begin() ; it != markets.end(); it++)\n {\n monitor_market(*it);\n }\n\n return;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid MarketPlaceManager::monitor_market(int mp_id)\n{\n std::string mp_data;\n std::string mp_name;\n std::string* drv_msg;\n\n std::ostringstream oss;\n\n const MarketPlaceManagerDriver* mpmd = get();\n\n if ( mpmd == 0 )\n {\n oss << \"Error getting MarketPlaceManagerDriver\";\n\n NebulaLog::log(\"MKP\", Log::ERROR, oss);\n return;\n }\n\n MarketPlace * mp = mppool->get(mp_id, true);\n\n if ( mp == 0 )\n {\n return;\n }\n\n mp_name = mp->get_name();\n\n if ( !mp->is_action_supported(MarketPlaceApp::MONITOR) )\n {\n NebulaLog::log(\"MKP\", Log::DEBUG, \"Monitoring disabled for market: \" +\n mp_name);\n\n mp->unlock();\n\n return;\n }\n\n if ( mp->get_zone_id() != Nebula::instance().get_zone_id() )\n {\n mp->unlock();\n return;\n }\n\n mp->to_xml(mp_data);\n\n mp->unlock();\n\n drv_msg = MarketPlaceManager::format_message(\"\", mp_data, \"\");\n\n oss << \"Monitoring marketplace \" << mp_name << \" (\" << mp_id << \")\";\n\n NebulaLog::log(\"MKP\", Log::DEBUG, oss);\n\n mpmd->monitor(mp_id, *drv_msg);\n\n delete drv_msg;\n}\nFix race condition in MarketPlaceManager when drivers load takes too long\/* -------------------------------------------------------------------------- *\/\n\/* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\/\n\/* not use this file except in compliance with the License. You may obtain *\/\n\/* a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\/\n\/* See the License for the specific language governing permissions and *\/\n\/* limitations under the License. *\/\n\/* -------------------------------------------------------------------------- *\/\n\n#include \"MarketPlaceManager.h\"\n#include \"MarketPlacePool.h\"\n#include \"MarketPlaceAppPool.h\"\n#include \"MarketPlaceManagerDriver.h\"\n\n#include \"Nebula.h\"\n\nconst char * MarketPlaceManager::market_driver_name = \"market_exe\";\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nextern \"C\" void * marketplace_action_loop(void *arg)\n{\n MarketPlaceManager * mpm;\n\n if ( arg == 0 )\n {\n return 0;\n }\n\n NebulaLog::log(\"MKP\", Log::INFO, \"Marketplace Manager started.\");\n\n mpm = static_cast(arg);\n\n mpm->am.loop(mpm->timer_period);\n\n NebulaLog::log(\"MKP\", Log::INFO, \"Marketplace Manager stopped.\");\n\n return 0;\n}\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nMarketPlaceManager::MarketPlaceManager(\n time_t _timer_period,\n time_t _monitor_period,\n std::vector& _mads):\n MadManager(_mads),\n timer_period(_timer_period),\n monitor_period(_monitor_period),\n imagem(0),\n raftm(0)\n{\n Nebula& nd = Nebula::instance();\n\n mppool = nd.get_marketpool();\n apppool = nd.get_apppool();\n dspool = nd.get_dspool();\n ipool = nd.get_ipool();\n\n am.addListener(this);\n};\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint MarketPlaceManager::load_mads(int uid)\n{\n MarketPlaceManagerDriver * marketm_mad;\n\n std::ostringstream oss;\n const VectorAttribute * vattr = 0;\n\n int rc;\n\n NebulaLog::log(\"MKP\", Log::INFO,\"Loading Marketplace Manager driver.\");\n\n if ( mad_conf.size() > 0 )\n {\n vattr = static_cast(mad_conf[0]);\n }\n\n if ( vattr == 0 )\n {\n NebulaLog::log(\"MKP\", Log::INFO,\"Failed to load Marketplace Manager driver.\");\n return -1;\n }\n\n VectorAttribute market_conf(\"MARKET_MAD\", vattr->value());\n\n market_conf.replace(\"NAME\", market_driver_name);\n\n marketm_mad= new MarketPlaceManagerDriver(0, market_conf.value(), false,\n mppool, apppool, this);\n\n rc = add(marketm_mad);\n\n if ( rc == 0 )\n {\n oss.str(\"\");\n oss << \"\\tMarketplace Manager loaded\";\n\n NebulaLog::log(\"MKP\", Log::INFO, oss);\n }\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid MarketPlaceManager::init_managers()\n{\n Nebula& nd = Nebula::instance();\n\n imagem = nd.get_imagem();\n raftm = nd.get_raftm();\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint MarketPlaceManager::start()\n{\n int rc;\n pthread_attr_t pattr;\n\n rc = MadManager::start();\n\n if ( rc != 0 )\n {\n return -1;\n }\n\n NebulaLog::log(\"ImM\",Log::INFO,\"Starting Marketplace Manager...\");\n\n pthread_attr_init (&pattr);\n pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);\n\n rc = pthread_create(&marketm_thread, &pattr, marketplace_action_loop,\n (void *) this);\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nstring * MarketPlaceManager::format_message(\n const string& app_data,\n const string& market_data,\n const string& extra_data)\n{\n ostringstream oss;\n\n oss << \"\"\n << app_data\n << market_data\n << extra_data\n << \"<\/MARKET_DRIVER_ACTION_DATA>\";\n\n return one_util::base64_encode(oss.str());\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid MarketPlaceManager::timer_action(const ActionRequest& ar)\n{\n static int mark = 0;\n static int tics = monitor_period - 5; \/\/first monitor in 5 secs\n\n mark += timer_period;\n tics += timer_period;\n\n if ( mark >= 600 )\n {\n NebulaLog::log(\"MKP\",Log::INFO,\"--Mark--\");\n mark = 0;\n }\n\n if ( tics < monitor_period )\n {\n return;\n }\n\n tics = 0;\n\n if (raftm == 0 || (!raftm->is_leader() && !raftm->is_solo()))\n {\n return;\n }\n\n int rc;\n\n std::vector markets;\n std::vector::iterator it;\n\n rc = mppool->list(markets);\n\n if ( rc != 0 )\n {\n return;\n }\n\n for(it = markets.begin() ; it != markets.end(); it++)\n {\n monitor_market(*it);\n }\n\n return;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid MarketPlaceManager::monitor_market(int mp_id)\n{\n std::string mp_data;\n std::string mp_name;\n std::string* drv_msg;\n\n std::ostringstream oss;\n\n const MarketPlaceManagerDriver* mpmd = get();\n\n if ( mpmd == 0 )\n {\n oss << \"Error getting MarketPlaceManagerDriver\";\n\n NebulaLog::log(\"MKP\", Log::ERROR, oss);\n return;\n }\n\n MarketPlace * mp = mppool->get(mp_id, true);\n\n if ( mp == 0 )\n {\n return;\n }\n\n mp_name = mp->get_name();\n\n if ( !mp->is_action_supported(MarketPlaceApp::MONITOR) )\n {\n NebulaLog::log(\"MKP\", Log::DEBUG, \"Monitoring disabled for market: \" +\n mp_name);\n\n mp->unlock();\n\n return;\n }\n\n if ( mp->get_zone_id() != Nebula::instance().get_zone_id() )\n {\n mp->unlock();\n return;\n }\n\n mp->to_xml(mp_data);\n\n mp->unlock();\n\n drv_msg = MarketPlaceManager::format_message(\"\", mp_data, \"\");\n\n oss << \"Monitoring marketplace \" << mp_name << \" (\" << mp_id << \")\";\n\n NebulaLog::log(\"MKP\", Log::DEBUG, oss);\n\n mpmd->monitor(mp_id, *drv_msg);\n\n delete drv_msg;\n}\n<|endoftext|>"} {"text":"\n#include \n#include \"ofxPS3EyeGrabber.h\"\n#include \"beamCamera.h\"\n#include \"settings.h\"\n\n\n\nBeamCamera::BeamCamera(int deviceID, const string name) : cam_name(name)\n{\n grabber.setGrabber(std::make_shared());\n grabber.setDeviceID(deviceID);\n\n grabber.setPixelFormat(OF_PIXELS_RGB);\n grabber.setDesiredFrameRate(FRAMERATE);\n grabber.setup(WIDTH, HEIGHT);\n\n \/\/PS3 Eye specific settings\n grabber.getGrabber()->setAutogain(false);\n grabber.getGrabber()->setAutoWhiteBalance(false);\n\n \/\/allocate our working surfaces\n raw.allocate(WIDTH, HEIGHT);\n grey_bg.allocate(WIDTH, HEIGHT);\n grey_working.allocate(WIDTH, HEIGHT);\n grey_beam_working.allocate(WIDTH, HEIGHT);\n\n threshold = INIT_THRESHOLD;\n learning = NOT_LEARNING;\n\n load_data();\n}\n\nBeamCamera::~BeamCamera()\n{\n \/\/release our surfaces\n raw.clear();\n grey_bg.clear();\n grey_working.clear();\n grey_beam_working.clear();\n\n for(BeamDescriptor* beam : beams)\n {\n if(beam != NULL)\n delete beam;\n }\n}\n\nvoid BeamCamera::load_data()\n{\n ofDirectory dir(cam_name);\n if(!dir.exists())\n {\n dir.create();\n return;\n }\n\n dir.allowExt(IMAGE_FORMAT);\n dir.listDir();\n\n for(ofFile file : dir)\n {\n ofImage img;\n\n if(file.getBaseName() == BACKGROUND_FILE)\n {\n img.load(file);\n grey_bg = img;\n }\n else\n {\n int beam = ofToInt(file.getBaseName());\n\n if(beam < 0)\n continue;\n\n img.load(file);\n \/\/make sure our mask array has a spot for this beam\n if(beam >= (int) beams.size())\n beams.resize(beam + 1, NULL);\n\n beams[beam] = new BeamDescriptor(img);\n }\n }\n}\n\nvoid BeamCamera::update()\n{\n grabber.update();\n\n if(grabber.isFrameNew())\n {\n raw.setFromPixels(grabber.getPixels());\n\n \/\/perform background subtraction\n grey_working = raw;\n cvSub(grey_working.getCvImage(),\n grey_bg.getCvImage(),\n grey_working.getCvImage());\n grey_working.flagImageChanged();\n\n \/\/apply our intensity threshold\n grey_working.threshold(threshold);\n\n if(is_learning() && beams[learning] != NULL)\n {\n beams[learning]->add_to_mask(grey_working);\n }\n }\n}\n\nvoid BeamCamera::draw_raw(int x, int y)\n{\n ofSetHexColor(0xFFFFFF);\n raw.draw(x, y);\n}\n\nvoid BeamCamera::draw_working(int x, int y)\n{\n ofSetHexColor(0xFFFFFF);\n grey_working.draw(x, y);\n}\n\nvoid BeamCamera::draw_masks(int x, int y)\n{\n ofSetHexColor(0xFFFFFF);\n cvZero(grey_beam_working.getCvImage());\n\n for(BeamDescriptor* beam : beams)\n {\n if(beam != NULL)\n {\n cvOr(beam->mask.getCvImage(),\n grey_beam_working.getCvImage(),\n grey_beam_working.getCvImage());\n }\n }\n\n grey_beam_working.flagImageChanged();\n grey_beam_working.draw(x, y);\n\n for(BeamDescriptor* beam : beams)\n {\n if(beam != NULL)\n {\n ofPushStyle();\n beam->blob.draw(x, y);\n ofSetHexColor(0xFF0000);\n ofDrawCircle(beam->top.x, beam->top.y, 3);\n ofSetHexColor(0x0000FF);\n ofDrawCircle(beam->bottom.x, beam->bottom.y, 3);\n ofPopStyle();\n }\n }\n}\n\nint BeamCamera::get_threshold()\n{\n return threshold;\n}\n\nvoid BeamCamera::adjust_threshold(int delta)\n{\n \/\/clamp to [0, 255]\n int new_thresh = threshold + delta;\n if(new_thresh < 0) new_thresh = 0;\n else if(new_thresh > 255) new_thresh = 255;\n threshold = new_thresh;\n}\n\nvoid BeamCamera::learn_background()\n{\n grey_bg = raw;\n\n \/\/save the background to a file\n ofImage background;\n background.setFromPixels(grey_bg.getPixels());\n background.setImageType(OF_IMAGE_GRAYSCALE);\n\n stringstream filename;\n filename << cam_name << \"\/\" << BACKGROUND_FILE << \".\" << IMAGE_FORMAT;\n background.save(filename.str());\n}\n\nbool BeamCamera::is_learning()\n{\n return learning != NOT_LEARNING;\n}\n\nvoid BeamCamera::start_learning_beam(int beam)\n{\n \/\/if we were learning before, stop, before moving on\n if(learning != NOT_LEARNING)\n stop_learning_beam();\n\n ofLog() << cam_name << \" started learning beam \" << beam;\n new_beam(beam);\n learning = beam;\n}\n\nvoid BeamCamera::stop_learning_beam()\n{\n \/\/can't stop a stopped learning\n if(learning == NOT_LEARNING)\n return;\n\n \/\/compute and save the minimum area rect\n BeamDescriptor* beam = beams[learning];\n beam->learn();\n\n \/\/save the mask to a file\n ofImage mask;\n mask.setFromPixels(beam->mask.getPixels());\n mask.setImageType(OF_IMAGE_GRAYSCALE);\n\n stringstream filename;\n filename << cam_name << \"\/\" << learning << \".\" << IMAGE_FORMAT;\n mask.save(filename.str());\n\n ofLog() << cam_name << \" stopped learning beam \" << learning;\n learning = NOT_LEARNING;\n}\n\nvector BeamCamera::hands_for_beam(int beam)\n{\n vector all_hands;\n vector hands_with_velocity;\n\n \/\/return empty array if this camera doesn't handle a beam\n if(!mask_exists(beam))\n return vector();\n\n \/\/apply the mask that corresponds to this beam\n cvAnd(grey_working.getCvImage(),\n beams[beam]->mask.getCvImage(),\n grey_beam_working.getCvImage());\n grey_beam_working.flagImageChanged();\n\n \/\/find our hand blobs\n contourFinder.findContours(grey_beam_working,\n BLOB_AREA_MIN,\n BLOB_AREA_MAX,\n N_BLOBS,\n false); \/\/find holes\n\n \/\/contourFinder.blobs is now populated\n\n for(ofxCvBlob blob : contourFinder.blobs)\n {\n Hand hand = beams[beam]->blob_to_hand(blob);\n\n \/\/figure out where this hand was in the past\n for(Hand& old_hand : beams[beam]->old_hands)\n {\n if(hand.same_hand_as(old_hand))\n {\n hand.compute_velocity(old_hand);\n hands_with_velocity.push_back(hand);\n break;\n }\n }\n\n all_hands.push_back(hand);\n }\n\n beams[beam]->old_hands = all_hands;\n\n return hands_with_velocity;\n}\n\nbool BeamCamera::mask_exists(int beam)\n{\n return (beam < (int)beams.size()) && (beams[beam] != NULL);\n}\n\nbool BeamCamera::handles_beam(int beam)\n{\n return mask_exists(beam) && beams[beam]->found_beam();\n}\n\nvoid BeamCamera::new_beam(int beam)\n{\n \/\/make sure our mask array has a spot for this beam\n if(beam >= (int) beams.size())\n beams.resize(beam + 1, NULL);\n\n if(mask_exists(beam))\n beams[beam]->zero();\n else\n beams[beam] = new BeamDescriptor();\n}\nblur the incoming image, and don't wait for velocities\n#include \n#include \"ofxPS3EyeGrabber.h\"\n#include \"beamCamera.h\"\n#include \"settings.h\"\n\n\n\nBeamCamera::BeamCamera(int deviceID, const string name) : cam_name(name)\n{\n grabber.setGrabber(std::make_shared());\n grabber.setDeviceID(deviceID);\n\n grabber.setPixelFormat(OF_PIXELS_RGB);\n grabber.setDesiredFrameRate(FRAMERATE);\n grabber.setup(WIDTH, HEIGHT);\n\n \/\/PS3 Eye specific settings\n grabber.getGrabber()->setAutogain(false);\n grabber.getGrabber()->setAutoWhiteBalance(false);\n\n \/\/allocate our working surfaces\n raw.allocate(WIDTH, HEIGHT);\n grey_bg.allocate(WIDTH, HEIGHT);\n grey_working.allocate(WIDTH, HEIGHT);\n grey_beam_working.allocate(WIDTH, HEIGHT);\n\n threshold = INIT_THRESHOLD;\n learning = NOT_LEARNING;\n\n load_data();\n}\n\nBeamCamera::~BeamCamera()\n{\n \/\/release our surfaces\n raw.clear();\n grey_bg.clear();\n grey_working.clear();\n grey_beam_working.clear();\n\n for(BeamDescriptor* beam : beams)\n {\n if(beam != NULL)\n delete beam;\n }\n}\n\nvoid BeamCamera::load_data()\n{\n ofDirectory dir(cam_name);\n if(!dir.exists())\n {\n dir.create();\n return;\n }\n\n dir.allowExt(IMAGE_FORMAT);\n dir.listDir();\n\n for(ofFile file : dir)\n {\n ofImage img;\n\n if(file.getBaseName() == BACKGROUND_FILE)\n {\n img.load(file);\n grey_bg = img;\n }\n else\n {\n int beam = ofToInt(file.getBaseName());\n\n if(beam < 0)\n continue;\n\n img.load(file);\n \/\/make sure our mask array has a spot for this beam\n if(beam >= (int) beams.size())\n beams.resize(beam + 1, NULL);\n\n beams[beam] = new BeamDescriptor(img);\n }\n }\n}\n\nvoid BeamCamera::update()\n{\n grabber.update();\n\n if(grabber.isFrameNew())\n {\n raw.setFromPixels(grabber.getPixels());\n\n \/\/perform background subtraction\n grey_working = raw;\n cvSub(grey_working.getCvImage(),\n grey_bg.getCvImage(),\n grey_working.getCvImage());\n grey_working.flagImageChanged();\n grey_working.blur(5);\n \/\/apply our intensity threshold\n grey_working.threshold(threshold);\n grey_working.dilate();\n\n if(is_learning() && beams[learning] != NULL)\n {\n beams[learning]->add_to_mask(grey_working);\n }\n }\n}\n\nvoid BeamCamera::draw_raw(int x, int y)\n{\n ofSetHexColor(0xFFFFFF);\n raw.draw(x, y);\n}\n\nvoid BeamCamera::draw_working(int x, int y)\n{\n ofSetHexColor(0xFFFFFF);\n grey_working.draw(x, y);\n}\n\nvoid BeamCamera::draw_masks(int x, int y)\n{\n ofSetHexColor(0xFFFFFF);\n cvZero(grey_beam_working.getCvImage());\n\n for(BeamDescriptor* beam : beams)\n {\n if(beam != NULL)\n {\n cvOr(beam->mask.getCvImage(),\n grey_beam_working.getCvImage(),\n grey_beam_working.getCvImage());\n }\n }\n\n grey_beam_working.flagImageChanged();\n grey_beam_working.draw(x, y);\n\n for(BeamDescriptor* beam : beams)\n {\n if(beam != NULL)\n {\n ofPushStyle();\n beam->blob.draw(x, y);\n ofSetHexColor(0xFF0000);\n ofDrawCircle(beam->top.x, beam->top.y, 3);\n ofSetHexColor(0x0000FF);\n ofDrawCircle(beam->bottom.x, beam->bottom.y, 3);\n ofPopStyle();\n }\n }\n}\n\nint BeamCamera::get_threshold()\n{\n return threshold;\n}\n\nvoid BeamCamera::adjust_threshold(int delta)\n{\n \/\/clamp to [0, 255]\n int new_thresh = threshold + delta;\n if(new_thresh < 0) new_thresh = 0;\n else if(new_thresh > 255) new_thresh = 255;\n threshold = new_thresh;\n}\n\nvoid BeamCamera::learn_background()\n{\n grey_bg = raw;\n\n \/\/save the background to a file\n ofImage background;\n background.setFromPixels(grey_bg.getPixels());\n background.setImageType(OF_IMAGE_GRAYSCALE);\n\n stringstream filename;\n filename << cam_name << \"\/\" << BACKGROUND_FILE << \".\" << IMAGE_FORMAT;\n background.save(filename.str());\n}\n\nbool BeamCamera::is_learning()\n{\n return learning != NOT_LEARNING;\n}\n\nvoid BeamCamera::start_learning_beam(int beam)\n{\n \/\/if we were learning before, stop, before moving on\n if(learning != NOT_LEARNING)\n stop_learning_beam();\n\n ofLog() << cam_name << \" started learning beam \" << beam;\n new_beam(beam);\n learning = beam;\n}\n\nvoid BeamCamera::stop_learning_beam()\n{\n \/\/can't stop a stopped learning\n if(learning == NOT_LEARNING)\n return;\n\n \/\/compute and save the minimum area rect\n BeamDescriptor* beam = beams[learning];\n beam->learn();\n\n \/\/save the mask to a file\n ofImage mask;\n mask.setFromPixels(beam->mask.getPixels());\n mask.setImageType(OF_IMAGE_GRAYSCALE);\n\n stringstream filename;\n filename << cam_name << \"\/\" << learning << \".\" << IMAGE_FORMAT;\n mask.save(filename.str());\n\n ofLog() << cam_name << \" stopped learning beam \" << learning;\n learning = NOT_LEARNING;\n}\n\nvector BeamCamera::hands_for_beam(int beam)\n{\n vector all_hands;\n vector hands_with_velocity;\n\n \/\/return empty array if this camera doesn't handle a beam\n if(!mask_exists(beam))\n return vector();\n\n \/\/apply the mask that corresponds to this beam\n cvAnd(grey_working.getCvImage(),\n beams[beam]->mask.getCvImage(),\n grey_beam_working.getCvImage());\n grey_beam_working.flagImageChanged();\n\n \/\/find our hand blobs\n contourFinder.findContours(grey_beam_working,\n BLOB_AREA_MIN,\n BLOB_AREA_MAX,\n N_BLOBS,\n false); \/\/find holes\n\n \/\/contourFinder.blobs is now populated\n\n for(ofxCvBlob blob : contourFinder.blobs)\n {\n Hand hand = beams[beam]->blob_to_hand(blob);\n\n \/\/figure out where this hand was in the past\n for(Hand& old_hand : beams[beam]->old_hands)\n {\n if(hand.same_hand_as(old_hand))\n {\n hand.compute_velocity(old_hand);\n hands_with_velocity.push_back(hand);\n break;\n }\n }\n\n all_hands.push_back(hand);\n }\n\n beams[beam]->old_hands = all_hands;\n\n \/\/return hands_with_velocity;\n return all_hands;\n}\n\nbool BeamCamera::mask_exists(int beam)\n{\n return (beam < (int)beams.size()) && (beams[beam] != NULL);\n}\n\nbool BeamCamera::handles_beam(int beam)\n{\n return mask_exists(beam) && beams[beam]->found_beam();\n}\n\nvoid BeamCamera::new_beam(int beam)\n{\n \/\/make sure our mask array has a spot for this beam\n if(beam >= (int) beams.size())\n beams.resize(beam + 1, NULL);\n\n if(mask_exists(beam))\n beams[beam]->zero();\n else\n beams[beam] = new BeamDescriptor();\n}\n<|endoftext|>"} {"text":"\/*--------------------------------------------------------------------------\nCopyright (c) 2014, The Linux Foundation. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of The Linux Foundation nor\n the names of its contributors may be used to endorse or promote\n products derived from this software without specific prior written\n permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\nOR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\nWHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\nOTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n--------------------------------------------------------------------------*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"CompassSensor.h\"\n#include \"sensors.h\"\n\n#define FETCH_FULL_EVENT_BEFORE_RETURN\t1\n#define IGNORE_EVENT_TIME\t\t\t\t10000000\n\n#define EVENT_TYPE_MAG_X\t\tABS_X\n#define EVENT_TYPE_MAG_Y\t\tABS_Y\n#define EVENT_TYPE_MAG_Z\t\tABS_Z\n#define EVENT_TYPE_MAG_STATUS\tABS_MISC\n\n#define EVENT_TYPE_YAW\t\t\tABS_X\n#define EVENT_TYPE_PITCH\t\tABS_Y\n#define EVENT_TYPE_ROLL\t\t\tABS_Z\n\n\/\/ conversion of magnetic data to uT units\n#define CONVERT_MAG\t\t\t\t(1.0f\/16.0f)\n#define CALIBRATE_ERROR_MAGIC\t\t0.000314\n\n\/*****************************************************************************\/\nCompassSensor::CompassSensor(struct SensorContext *context)\n\t: SensorBase(NULL, NULL, context),\n\t mInputReader(4),\n\t mHasPendingEvent(false),\n\t mEnabledTime(0),\n\t res(CONVERT_MAG)\n{\n\tint handle = -1;\n\n\tres = context->sensor->resolution;\n\n\tmemset(mPendingEvent.data, 0, sizeof(mPendingEvent.data));\n\tmPendingEvent.version = sizeof(sensors_event_t);\n\tmPendingEvent.sensor = context->sensor->handle;\n\tmPendingEvent.type = SENSOR_TYPE_MAGNETIC_FIELD;\n\tmPendingEvent.magnetic.status = SENSOR_STATUS_UNRELIABLE;\n\n\tdata_fd = context->data_fd;\n\tstrlcpy(input_sysfs_path, context->enable_path, sizeof(input_sysfs_path));\n\tinput_sysfs_path_len = strlen(input_sysfs_path);\n\n\tenable(0, 1);\n}\n\nCompassSensor::~CompassSensor() {\n\tif (mEnabled) {\n\t\tenable(0, 0);\n\t}\n}\n\nint CompassSensor::enable(int32_t, int en) {\n\tint flags = en ? 1 : 0;\n\tcompass_algo_args arg;\n\targ.common.enable = flags;\n\tchar propBuf[PROPERTY_VALUE_MAX];\n\n\tproperty_get(\"sensors.compass.loopback\", propBuf, \"0\");\n\tif (strcmp(propBuf, \"1\") == 0) {\n\t\tALOGE(\"sensors.compass.loopback is set\");\n\t\tmEnabled = flags;\n\t\tmEnabledTime = 0;\n\t\treturn 0;\n\t}\n\n\tif (flags != mEnabled) {\n\t\tint fd;\n\n\t\tif ((algo != NULL) && (algo->methods->config != NULL)) {\n\t\t\tif (algo->methods->config(CMD_ENABLE, (sensor_algo_args*)&arg)) {\n\t\t\t\tALOGW(\"Calling enable config failed for compass\");\n\t\t\t}\n\t\t}\n\n\t\tstrlcpy(&input_sysfs_path[input_sysfs_path_len],\n\t\t\t\tSYSFS_ENABLE, SYSFS_MAXLEN);\n\t\tfd = open(input_sysfs_path, O_RDWR);\n\t\tif (fd >= 0) {\n\t\t\tchar buf[2];\n\t\t\tint err;\n\t\t\tbuf[1] = 0;\n\t\t\tif (flags) {\n\t\t\t\tbuf[0] = '1';\n\t\t\t\tmEnabledTime = getTimestamp() + IGNORE_EVENT_TIME;\n\t\t\t} else {\n\t\t\t\tbuf[0] = '0';\n\t\t\t}\n\t\t\terr = write(fd, buf, sizeof(buf));\n\t\t\tclose(fd);\n\t\t\tmEnabled = flags;\n\t\t\treturn 0;\n\t\t}\n\t\tALOGE(\"CompassSensor: failed to open %s\", input_sysfs_path);\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\nbool CompassSensor::hasPendingEvents() const {\n\treturn mHasPendingEvent || mHasPendingMetadata;\n}\n\nint CompassSensor::setDelay(int32_t, int64_t delay_ns)\n{\n\tint fd;\n\tint delay_ms = delay_ns \/ 1000000;\n\tcompass_algo_args arg;\n\targ.common.delay_ms = delay_ms;\n\tchar propBuf[PROPERTY_VALUE_MAX];\n\tproperty_get(\"sensors.compass.loopback\", propBuf, \"0\");\n\tif (strcmp(propBuf, \"1\") == 0) {\n\t\tALOGE(\"sensors.compass.loopback is set\");\n\t\treturn 0;\n\t}\n\n\tif ((algo != NULL) && (algo->methods->config != NULL)) {\n\t\tif (algo->methods->config(CMD_DELAY, (sensor_algo_args*)&arg)) {\n\t\t\tALOGW(\"Calling delay config failed for compass\");\n\t\t}\n\t}\n\n\tstrlcpy(&input_sysfs_path[input_sysfs_path_len],\n\t\t\tSYSFS_POLL_DELAY, SYSFS_MAXLEN);\n\tfd = open(input_sysfs_path, O_RDWR);\n\tif (fd >= 0) {\n\t\tchar buf[80];\n\t\tsnprintf(buf, sizeof(buf), \"%d\", delay_ms);\n\t\twrite(fd, buf, strlen(buf)+1);\n\t\tclose(fd);\n\t\treturn 0;\n\t}\n\treturn -1;\n}\n\nint CompassSensor::readEvents(sensors_event_t* data, int count)\n{\n\tif (count < 1)\n\t\treturn -EINVAL;\n\n\tif (mHasPendingEvent) {\n\t\tmHasPendingEvent = false;\n\t\tmPendingEvent.timestamp = getTimestamp();\n\t\t*data = mPendingEvent;\n\t\treturn mEnabled ? 1 : 0;\n\t}\n\n\tif (mHasPendingMetadata) {\n\t\tmHasPendingMetadata--;\n\t\tmeta_data.timestamp = getTimestamp();\n\t\t*data = meta_data;\n\t\treturn mEnabled ? 1 : 0;\n\t}\n\n\tssize_t n = mInputReader.fill(data_fd);\n\tif (n < 0)\n\t\treturn n;\n\n\tint numEventReceived = 0;\n\tinput_event const* event;\n\tsensors_event_t raw, result;\n\n#if FETCH_FULL_EVENT_BEFORE_RETURN\nagain:\n#endif\n\twhile (count && mInputReader.readEvent(&event)) {\n\t\tint type = event->type;\n\t\tif (type == EV_ABS) {\n\t\t\tfloat value = event->value;\n\t\t\tif (event->code == EVENT_TYPE_MAG_X) {\n\t\t\t\tmPendingEvent.magnetic.x = value * res;\n\t\t\t} else if (event->code == EVENT_TYPE_MAG_Y) {\n\t\t\t\tmPendingEvent.magnetic.y = value * res;\n\t\t\t} else if (event->code == EVENT_TYPE_MAG_Z) {\n\t\t\t\tmPendingEvent.magnetic.z = value * res;\n\t\t\t}\n\t\t} else if (type == EV_SYN) {\n\t\t\tswitch (event->code) {\n\t\t\t\tcase SYN_TIME_SEC:\n\t\t\t\t\tmUseAbsTimeStamp = true;\n\t\t\t\t\treport_time = event->value*1000000000LL;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SYN_TIME_NSEC:\n\t\t\t\t\tmUseAbsTimeStamp = true;\n\t\t\t\t\tmPendingEvent.timestamp = report_time+event->value;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SYN_REPORT:\n\t\t\t\t\tif (mUseAbsTimeStamp != true) {\n\t\t\t\t\t\tmPendingEvent.timestamp = timevalToNano(event->time);\n\t\t\t\t\t}\n\t\t\t\t\tif (mEnabled) {\n\t\t\t\t\t\traw = mPendingEvent;\n\n\t\t\t\t\t\tif (algo != NULL) {\n\t\t\t\t\t\t\tif (algo->methods->convert(&raw, &result, NULL)) {\n\t\t\t\t\t\t\t\tALOGE(\"Calibration failed.\");\n\t\t\t\t\t\t\t\tresult.magnetic.x = CALIBRATE_ERROR_MAGIC;\n\t\t\t\t\t\t\t\tresult.magnetic.y = CALIBRATE_ERROR_MAGIC;\n\t\t\t\t\t\t\t\tresult.magnetic.z = CALIBRATE_ERROR_MAGIC;\n\t\t\t\t\t\t\t\tresult.magnetic.status = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tresult = raw;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t*data = result;\n\t\t\t\t\t\tdata->version = sizeof(sensors_event_t);\n\t\t\t\t\t\tdata->sensor = mPendingEvent.sensor;\n\t\t\t\t\t\tdata->type = SENSOR_TYPE_MAGNETIC_FIELD;\n\t\t\t\t\t\tdata->timestamp = mPendingEvent.timestamp;\n\n\t\t\t\t\t\t\/* The raw data is stored inside sensors_event_t.data after\n\t\t\t\t\t\t * sensors_event_t.magnetic. Notice that the raw data is\n\t\t\t\t\t\t * required to composite the virtual sensor uncalibrated\n\t\t\t\t\t\t * magnetic field sensor.\n\t\t\t\t\t\t *\n\t\t\t\t\t\t * data[0~2]: calibrated magnetic field data.\n\t\t\t\t\t\t * data[3]: magnetic field data accuracy.\n\t\t\t\t\t\t * data[4~6]: uncalibrated magnetic field data.\n\t\t\t\t\t\t *\/\n\t\t\t\t\t\tdata->data[4] = mPendingEvent.data[0];\n\t\t\t\t\t\tdata->data[5] = mPendingEvent.data[1];\n\t\t\t\t\t\tdata->data[6] = mPendingEvent.data[2];\n\n\t\t\t\t\t\tdata++;\n\t\t\t\t\t\tnumEventReceived++;\n\t\t\t\t\t\tcount--;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tALOGE(\"CompassSensor: unknown event (type=%d, code=%d)\",\n\t\t\t\t\ttype, event->code);\n\t\t}\n\t\tmInputReader.next();\n\t}\n\n#if FETCH_FULL_EVENT_BEFORE_RETURN\n\t\/* if we didn't read a complete event, see if we can fill and\n\t try again instead of returning with nothing and redoing poll. *\/\n\tif (numEventReceived == 0 && mEnabled == 1) {\n\t\tn = mInputReader.fill(data_fd);\n\t\tif (n)\n\t\t\tgoto again;\n\t}\n#endif\n\n\treturn numEventReceived;\n}\n\ndon't report bogus mag values when uncalibrated\/*--------------------------------------------------------------------------\nCopyright (c) 2014, The Linux Foundation. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of The Linux Foundation nor\n the names of its contributors may be used to endorse or promote\n products derived from this software without specific prior written\n permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\nOR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\nWHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\nOTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n--------------------------------------------------------------------------*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"CompassSensor.h\"\n#include \"sensors.h\"\n\n#define FETCH_FULL_EVENT_BEFORE_RETURN\t1\n#define IGNORE_EVENT_TIME\t\t\t\t10000000\n\n#define EVENT_TYPE_MAG_X\t\tABS_X\n#define EVENT_TYPE_MAG_Y\t\tABS_Y\n#define EVENT_TYPE_MAG_Z\t\tABS_Z\n#define EVENT_TYPE_MAG_STATUS\tABS_MISC\n\n#define EVENT_TYPE_YAW\t\t\tABS_X\n#define EVENT_TYPE_PITCH\t\tABS_Y\n#define EVENT_TYPE_ROLL\t\t\tABS_Z\n\n\/\/ conversion of magnetic data to uT units\n#define CONVERT_MAG\t\t\t\t(1.0f\/16.0f)\n\n\/*****************************************************************************\/\nCompassSensor::CompassSensor(struct SensorContext *context)\n\t: SensorBase(NULL, NULL, context),\n\t mInputReader(4),\n\t mHasPendingEvent(false),\n\t mEnabledTime(0),\n\t res(CONVERT_MAG)\n{\n\tint handle = -1;\n\n\tres = context->sensor->resolution;\n\n\tmemset(mPendingEvent.data, 0, sizeof(mPendingEvent.data));\n\tmPendingEvent.version = sizeof(sensors_event_t);\n\tmPendingEvent.sensor = context->sensor->handle;\n\tmPendingEvent.type = SENSOR_TYPE_MAGNETIC_FIELD;\n\tmPendingEvent.magnetic.status = SENSOR_STATUS_UNRELIABLE;\n\n\tdata_fd = context->data_fd;\n\tstrlcpy(input_sysfs_path, context->enable_path, sizeof(input_sysfs_path));\n\tinput_sysfs_path_len = strlen(input_sysfs_path);\n\n\tenable(0, 1);\n}\n\nCompassSensor::~CompassSensor() {\n\tif (mEnabled) {\n\t\tenable(0, 0);\n\t}\n}\n\nint CompassSensor::enable(int32_t, int en) {\n\tint flags = en ? 1 : 0;\n\tcompass_algo_args arg;\n\targ.common.enable = flags;\n\tchar propBuf[PROPERTY_VALUE_MAX];\n\n\tproperty_get(\"sensors.compass.loopback\", propBuf, \"0\");\n\tif (strcmp(propBuf, \"1\") == 0) {\n\t\tALOGE(\"sensors.compass.loopback is set\");\n\t\tmEnabled = flags;\n\t\tmEnabledTime = 0;\n\t\treturn 0;\n\t}\n\n\tif (flags != mEnabled) {\n\t\tint fd;\n\n\t\tif ((algo != NULL) && (algo->methods->config != NULL)) {\n\t\t\tif (algo->methods->config(CMD_ENABLE, (sensor_algo_args*)&arg)) {\n\t\t\t\tALOGW(\"Calling enable config failed for compass\");\n\t\t\t}\n\t\t}\n\n\t\tstrlcpy(&input_sysfs_path[input_sysfs_path_len],\n\t\t\t\tSYSFS_ENABLE, SYSFS_MAXLEN);\n\t\tfd = open(input_sysfs_path, O_RDWR);\n\t\tif (fd >= 0) {\n\t\t\tchar buf[2];\n\t\t\tint err;\n\t\t\tbuf[1] = 0;\n\t\t\tif (flags) {\n\t\t\t\tbuf[0] = '1';\n\t\t\t\tmEnabledTime = getTimestamp() + IGNORE_EVENT_TIME;\n\t\t\t} else {\n\t\t\t\tbuf[0] = '0';\n\t\t\t}\n\t\t\terr = write(fd, buf, sizeof(buf));\n\t\t\tclose(fd);\n\t\t\tmEnabled = flags;\n\t\t\treturn 0;\n\t\t}\n\t\tALOGE(\"CompassSensor: failed to open %s\", input_sysfs_path);\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\nbool CompassSensor::hasPendingEvents() const {\n\treturn mHasPendingEvent || mHasPendingMetadata;\n}\n\nint CompassSensor::setDelay(int32_t, int64_t delay_ns)\n{\n\tint fd;\n\tint delay_ms = delay_ns \/ 1000000;\n\tcompass_algo_args arg;\n\targ.common.delay_ms = delay_ms;\n\tchar propBuf[PROPERTY_VALUE_MAX];\n\tproperty_get(\"sensors.compass.loopback\", propBuf, \"0\");\n\tif (strcmp(propBuf, \"1\") == 0) {\n\t\tALOGE(\"sensors.compass.loopback is set\");\n\t\treturn 0;\n\t}\n\n\tif ((algo != NULL) && (algo->methods->config != NULL)) {\n\t\tif (algo->methods->config(CMD_DELAY, (sensor_algo_args*)&arg)) {\n\t\t\tALOGW(\"Calling delay config failed for compass\");\n\t\t}\n\t}\n\n\tstrlcpy(&input_sysfs_path[input_sysfs_path_len],\n\t\t\tSYSFS_POLL_DELAY, SYSFS_MAXLEN);\n\tfd = open(input_sysfs_path, O_RDWR);\n\tif (fd >= 0) {\n\t\tchar buf[80];\n\t\tsnprintf(buf, sizeof(buf), \"%d\", delay_ms);\n\t\twrite(fd, buf, strlen(buf)+1);\n\t\tclose(fd);\n\t\treturn 0;\n\t}\n\treturn -1;\n}\n\nint CompassSensor::readEvents(sensors_event_t* data, int count)\n{\n\tif (count < 1)\n\t\treturn -EINVAL;\n\n\tif (mHasPendingEvent) {\n\t\tmHasPendingEvent = false;\n\t\tmPendingEvent.timestamp = getTimestamp();\n\t\t*data = mPendingEvent;\n\t\treturn mEnabled ? 1 : 0;\n\t}\n\n\tif (mHasPendingMetadata) {\n\t\tmHasPendingMetadata--;\n\t\tmeta_data.timestamp = getTimestamp();\n\t\t*data = meta_data;\n\t\treturn mEnabled ? 1 : 0;\n\t}\n\n\tssize_t n = mInputReader.fill(data_fd);\n\tif (n < 0)\n\t\treturn n;\n\n\tint numEventReceived = 0;\n\tinput_event const* event;\n\tsensors_event_t raw, result;\n\n#if FETCH_FULL_EVENT_BEFORE_RETURN\nagain:\n#endif\n\twhile (count && mInputReader.readEvent(&event)) {\n\t\tint type = event->type;\n\t\tif (type == EV_ABS) {\n\t\t\tfloat value = event->value;\n\t\t\tif (event->code == EVENT_TYPE_MAG_X) {\n\t\t\t\tmPendingEvent.magnetic.x = value * res;\n\t\t\t} else if (event->code == EVENT_TYPE_MAG_Y) {\n\t\t\t\tmPendingEvent.magnetic.y = value * res;\n\t\t\t} else if (event->code == EVENT_TYPE_MAG_Z) {\n\t\t\t\tmPendingEvent.magnetic.z = value * res;\n\t\t\t}\n\t\t} else if (type == EV_SYN) {\n\t\t\tswitch (event->code) {\n\t\t\t\tcase SYN_TIME_SEC:\n\t\t\t\t\tmUseAbsTimeStamp = true;\n\t\t\t\t\treport_time = event->value*1000000000LL;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SYN_TIME_NSEC:\n\t\t\t\t\tmUseAbsTimeStamp = true;\n\t\t\t\t\tmPendingEvent.timestamp = report_time+event->value;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SYN_REPORT:\n\t\t\t\t\tif (mUseAbsTimeStamp != true) {\n\t\t\t\t\t\tmPendingEvent.timestamp = timevalToNano(event->time);\n\t\t\t\t\t}\n\t\t\t\t\tif (mEnabled) {\n\t\t\t\t\t\traw = mPendingEvent;\n\n\t\t\t\t\t\tif (algo != NULL) {\n\t\t\t\t\t\t\tif (algo->methods->convert(&raw, &result, NULL)) {\n\t\t\t\t\t\t\t\tALOGW(\"Calibration in progress...\");\n\t\t\t\t\t\t\t\tresult = raw;\n\t\t\t\t\t\t\t\tresult.magnetic.status = SENSOR_STATUS_UNRELIABLE;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tresult = raw;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t*data = result;\n\t\t\t\t\t\tdata->version = sizeof(sensors_event_t);\n\t\t\t\t\t\tdata->sensor = mPendingEvent.sensor;\n\t\t\t\t\t\tdata->type = SENSOR_TYPE_MAGNETIC_FIELD;\n\t\t\t\t\t\tdata->timestamp = mPendingEvent.timestamp;\n\n\t\t\t\t\t\t\/* The raw data is stored inside sensors_event_t.data after\n\t\t\t\t\t\t * sensors_event_t.magnetic. Notice that the raw data is\n\t\t\t\t\t\t * required to composite the virtual sensor uncalibrated\n\t\t\t\t\t\t * magnetic field sensor.\n\t\t\t\t\t\t *\n\t\t\t\t\t\t * data[0~2]: calibrated magnetic field data.\n\t\t\t\t\t\t * data[3]: magnetic field data accuracy.\n\t\t\t\t\t\t * data[4~6]: uncalibrated magnetic field data.\n\t\t\t\t\t\t *\/\n\t\t\t\t\t\tdata->data[4] = mPendingEvent.data[0];\n\t\t\t\t\t\tdata->data[5] = mPendingEvent.data[1];\n\t\t\t\t\t\tdata->data[6] = mPendingEvent.data[2];\n\n\t\t\t\t\t\tdata++;\n\t\t\t\t\t\tnumEventReceived++;\n\t\t\t\t\t\tcount--;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tALOGE(\"CompassSensor: unknown event (type=%d, code=%d)\",\n\t\t\t\t\ttype, event->code);\n\t\t}\n\t\tmInputReader.next();\n\t}\n\n#if FETCH_FULL_EVENT_BEFORE_RETURN\n\t\/* if we didn't read a complete event, see if we can fill and\n\t try again instead of returning with nothing and redoing poll. *\/\n\tif (numEventReceived == 0 && mEnabled == 1) {\n\t\tn = mInputReader.fill(data_fd);\n\t\tif (n)\n\t\t\tgoto again;\n\t}\n#endif\n\n\treturn numEventReceived;\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n\n#include \"base\/trace.hh\"\n#include \"debug\/RubyNetwork.hh\"\n#include \"mem\/protocol\/MachineType.hh\"\n#include \"mem\/ruby\/common\/NetDest.hh\"\n#include \"mem\/ruby\/network\/BasicLink.hh\"\n#include \"mem\/ruby\/network\/Topology.hh\"\n#include \"mem\/ruby\/slicc_interface\/AbstractController.hh\"\n\nusing namespace std;\n\nconst int INFINITE_LATENCY = 10000; \/\/ Yes, this is a big hack\n\n\/\/ Note: In this file, we use the first 2*m_nodes SwitchIDs to\n\/\/ represent the input and output endpoint links. These really are\n\/\/ not 'switches', as they will not have a Switch object allocated for\n\/\/ them. The first m_nodes SwitchIDs are the links into the network,\n\/\/ the second m_nodes set of SwitchIDs represent the the output queues\n\/\/ of the network.\n\n\/\/ Helper functions based on chapter 29 of Cormen et al.\nvoid extend_shortest_path(Matrix& current_dist, Matrix& latencies,\n Matrix& inter_switches);\nMatrix shortest_path(const Matrix& weights, Matrix& latencies,\n Matrix& inter_switches);\nbool link_is_shortest_path_to_node(SwitchID src, SwitchID next,\n SwitchID final, const Matrix& weights, const Matrix& dist);\nNetDest shortest_path_to_node(SwitchID src, SwitchID next,\n const Matrix& weights, const Matrix& dist);\n\nTopology::Topology(uint32_t num_routers, vector ext_links,\n vector int_links)\n : m_number_of_switches(num_routers)\n{\n\n \/\/ initialize component latencies record\n m_component_latencies.resize(0);\n m_component_inter_switches.resize(0);\n\n \/\/ Total nodes\/controllers in network\n \/\/ Must make sure this is called after the State Machine constructors\n m_nodes = MachineType_base_number(MachineType_NUM);\n assert(m_nodes > 1);\n\n if (m_nodes != ext_links.size()) {\n fatal(\"m_nodes (%d) != ext_links vector length (%d)\\n\",\n m_nodes, ext_links.size());\n }\n\n \/\/ analyze both the internal and external links, create data structures\n \/\/ Note that the python created links are bi-directional, but that the\n \/\/ topology and networks utilize uni-directional links. Thus each \n \/\/ BasicLink is converted to two calls to add link, on for each direction\n for (vector::const_iterator i = ext_links.begin();\n i != ext_links.end(); ++i) {\n BasicExtLink *ext_link = (*i);\n AbstractController *abs_cntrl = ext_link->params()->ext_node;\n BasicRouter *router = ext_link->params()->int_node;\n\n \/\/ Store the ExtLink pointers for later\n m_ext_link_vector.push_back(ext_link);\n\n int ext_idx1 = abs_cntrl->params()->cntrl_id;\n int ext_idx2 = ext_idx1 + m_nodes;\n int int_idx = router->params()->router_id + 2*m_nodes;\n\n \/\/ create the internal uni-directional links in both directions\n \/\/ the first direction is marked: In\n addLink(ext_idx1, int_idx, ext_link, LinkDirection_In);\n \/\/ the first direction is marked: Out\n addLink(int_idx, ext_idx2, ext_link, LinkDirection_Out);\n }\n\n for (vector::const_iterator i = int_links.begin();\n i != int_links.end(); ++i) {\n BasicIntLink *int_link = (*i);\n BasicRouter *router_a = int_link->params()->node_a;\n BasicRouter *router_b = int_link->params()->node_b;\n\n \/\/ Store the IntLink pointers for later\n m_int_link_vector.push_back(int_link);\n\n int a = router_a->params()->router_id + 2*m_nodes;\n int b = router_b->params()->router_id + 2*m_nodes;\n\n \/\/ create the internal uni-directional links in both directions\n \/\/ the first direction is marked: In\n addLink(a, b, int_link, LinkDirection_In);\n \/\/ the second direction is marked: Out\n addLink(b, a, int_link, LinkDirection_Out);\n }\n}\n\nvoid\nTopology::createLinks(Network *net)\n{\n \/\/ Find maximum switchID\n SwitchID max_switch_id = 0;\n for (LinkMap::const_iterator i = m_link_map.begin();\n i != m_link_map.end(); ++i) {\n std::pair src_dest = (*i).first;\n max_switch_id = max(max_switch_id, src_dest.first);\n max_switch_id = max(max_switch_id, src_dest.second); \n }\n\n \/\/ Initialize weight, latency, and inter switched vectors\n Matrix topology_weights;\n int num_switches = max_switch_id+1;\n topology_weights.resize(num_switches);\n m_component_latencies.resize(num_switches);\n m_component_inter_switches.resize(num_switches);\n\n for (int i = 0; i < topology_weights.size(); i++) {\n topology_weights[i].resize(num_switches);\n m_component_latencies[i].resize(num_switches);\n m_component_inter_switches[i].resize(num_switches);\n\n for (int j = 0; j < topology_weights[i].size(); j++) {\n topology_weights[i][j] = INFINITE_LATENCY;\n\n \/\/ initialize to invalid values\n m_component_latencies[i][j] = -1;\n\n \/\/ initially assume direct connections \/ no intermediate\n \/\/ switches between components\n m_component_inter_switches[i][j] = 0;\n }\n }\n\n \/\/ Set identity weights to zero\n for (int i = 0; i < topology_weights.size(); i++) {\n topology_weights[i][i] = 0;\n }\n\n \/\/ Fill in the topology weights and bandwidth multipliers\n for (LinkMap::const_iterator i = m_link_map.begin();\n i != m_link_map.end(); ++i) {\n std::pair src_dest = (*i).first;\n BasicLink* link = (*i).second.link;\n int src = src_dest.first;\n int dst = src_dest.second;\n m_component_latencies[src][dst] = link->m_latency;\n topology_weights[src][dst] = link->m_weight;\n }\n \n \/\/ Walk topology and hookup the links\n Matrix dist = shortest_path(topology_weights, m_component_latencies,\n m_component_inter_switches);\n for (int i = 0; i < topology_weights.size(); i++) {\n for (int j = 0; j < topology_weights[i].size(); j++) {\n int weight = topology_weights[i][j];\n if (weight > 0 && weight != INFINITE_LATENCY) {\n NetDest destination_set =\n shortest_path_to_node(i, j, topology_weights, dist);\n makeLink(net, i, j, destination_set);\n }\n }\n }\n}\n\nvoid\nTopology::addLink(SwitchID src, SwitchID dest, BasicLink* link, \n LinkDirection dir)\n{\n assert(src <= m_number_of_switches+m_nodes+m_nodes);\n assert(dest <= m_number_of_switches+m_nodes+m_nodes);\n \n std::pair src_dest_pair;\n LinkEntry link_entry;\n\n src_dest_pair.first = src;\n src_dest_pair.second = dest;\n link_entry.direction = dir;\n link_entry.link = link;\n m_link_map[src_dest_pair] = link_entry;\n}\n\nvoid\nTopology::makeLink(Network *net, SwitchID src, SwitchID dest,\n const NetDest& routing_table_entry)\n{\n \/\/ Make sure we're not trying to connect two end-point nodes\n \/\/ directly together\n assert(src >= 2 * m_nodes || dest >= 2 * m_nodes);\n\n std::pair src_dest;\n LinkEntry link_entry; \n\n if (src < m_nodes) {\n src_dest.first = src;\n src_dest.second = dest;\n link_entry = m_link_map[src_dest];\n net->makeInLink(src, dest - (2 * m_nodes), link_entry.link,\n link_entry.direction, routing_table_entry);\n } else if (dest < 2*m_nodes) {\n assert(dest >= m_nodes);\n NodeID node = dest - m_nodes;\n src_dest.first = src;\n src_dest.second = dest;\n link_entry = m_link_map[src_dest];\n net->makeOutLink(src - (2 * m_nodes), node, link_entry.link,\n link_entry.direction, routing_table_entry);\n } else {\n assert((src >= 2 * m_nodes) && (dest >= 2 * m_nodes));\n src_dest.first = src;\n src_dest.second = dest;\n link_entry = m_link_map[src_dest];\n net->makeInternalLink(src - (2 * m_nodes), dest - (2 * m_nodes),\n link_entry.link, link_entry.direction,\n routing_table_entry);\n }\n}\n\n\/\/ The following all-pairs shortest path algorithm is based on the\n\/\/ discussion from Cormen et al., Chapter 26.1.\nvoid\nextend_shortest_path(Matrix& current_dist, Matrix& latencies,\n Matrix& inter_switches)\n{\n bool change = true;\n int nodes = current_dist.size();\n\n while (change) {\n change = false;\n for (int i = 0; i < nodes; i++) {\n for (int j = 0; j < nodes; j++) {\n int minimum = current_dist[i][j];\n int previous_minimum = minimum;\n int intermediate_switch = -1;\n for (int k = 0; k < nodes; k++) {\n minimum = min(minimum,\n current_dist[i][k] + current_dist[k][j]);\n if (previous_minimum != minimum) {\n intermediate_switch = k;\n inter_switches[i][j] =\n inter_switches[i][k] +\n inter_switches[k][j] + 1;\n }\n previous_minimum = minimum;\n }\n if (current_dist[i][j] != minimum) {\n change = true;\n current_dist[i][j] = minimum;\n assert(intermediate_switch >= 0);\n assert(intermediate_switch < latencies[i].size());\n latencies[i][j] = latencies[i][intermediate_switch] +\n latencies[intermediate_switch][j];\n }\n }\n }\n }\n}\n\nMatrix\nshortest_path(const Matrix& weights, Matrix& latencies, Matrix& inter_switches)\n{\n Matrix dist = weights;\n extend_shortest_path(dist, latencies, inter_switches);\n return dist;\n}\n\nbool\nlink_is_shortest_path_to_node(SwitchID src, SwitchID next, SwitchID final,\n const Matrix& weights, const Matrix& dist)\n{\n return weights[src][next] + dist[next][final] == dist[src][final];\n}\n\nNetDest\nshortest_path_to_node(SwitchID src, SwitchID next, const Matrix& weights,\n const Matrix& dist)\n{\n NetDest result;\n int d = 0;\n int machines;\n int max_machines;\n\n machines = MachineType_NUM;\n max_machines = MachineType_base_number(MachineType_NUM);\n\n for (int m = 0; m < machines; m++) {\n for (int i = 0; i < MachineType_base_count((MachineType)m); i++) {\n \/\/ we use \"d+max_machines\" below since the \"destination\"\n \/\/ switches for the machines are numbered\n \/\/ [MachineType_base_number(MachineType_NUM)...\n \/\/ 2*MachineType_base_number(MachineType_NUM)-1] for the\n \/\/ component network\n if (link_is_shortest_path_to_node(src, next, d + max_machines,\n weights, dist)) {\n MachineID mach = {(MachineType)m, i};\n result.add(mach);\n }\n d++;\n }\n }\n\n DPRINTF(RubyNetwork, \"Returning shortest path\\n\"\n \"(src-(2*max_machines)): %d, (next-(2*max_machines)): %d, \"\n \"src: %d, next: %d, result: %s\\n\",\n (src-(2*max_machines)), (next-(2*max_machines)),\n src, next, result);\n\n return result;\n}\nruby: Fix Topology throttle connections\/*\n * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n\n#include \"base\/trace.hh\"\n#include \"debug\/RubyNetwork.hh\"\n#include \"mem\/protocol\/MachineType.hh\"\n#include \"mem\/ruby\/common\/NetDest.hh\"\n#include \"mem\/ruby\/network\/BasicLink.hh\"\n#include \"mem\/ruby\/network\/Topology.hh\"\n#include \"mem\/ruby\/slicc_interface\/AbstractController.hh\"\n\nusing namespace std;\n\nconst int INFINITE_LATENCY = 10000; \/\/ Yes, this is a big hack\n\n\/\/ Note: In this file, we use the first 2*m_nodes SwitchIDs to\n\/\/ represent the input and output endpoint links. These really are\n\/\/ not 'switches', as they will not have a Switch object allocated for\n\/\/ them. The first m_nodes SwitchIDs are the links into the network,\n\/\/ the second m_nodes set of SwitchIDs represent the the output queues\n\/\/ of the network.\n\n\/\/ Helper functions based on chapter 29 of Cormen et al.\nvoid extend_shortest_path(Matrix& current_dist, Matrix& latencies,\n Matrix& inter_switches);\nMatrix shortest_path(const Matrix& weights, Matrix& latencies,\n Matrix& inter_switches);\nbool link_is_shortest_path_to_node(SwitchID src, SwitchID next,\n SwitchID final, const Matrix& weights, const Matrix& dist);\nNetDest shortest_path_to_node(SwitchID src, SwitchID next,\n const Matrix& weights, const Matrix& dist);\n\nTopology::Topology(uint32_t num_routers, vector ext_links,\n vector int_links)\n : m_number_of_switches(num_routers)\n{\n\n \/\/ initialize component latencies record\n m_component_latencies.resize(0);\n m_component_inter_switches.resize(0);\n\n \/\/ Total nodes\/controllers in network\n \/\/ Must make sure this is called after the State Machine constructors\n m_nodes = MachineType_base_number(MachineType_NUM);\n assert(m_nodes > 1);\n\n if (m_nodes != ext_links.size()) {\n fatal(\"m_nodes (%d) != ext_links vector length (%d)\\n\",\n m_nodes, ext_links.size());\n }\n\n \/\/ analyze both the internal and external links, create data structures\n \/\/ Note that the python created links are bi-directional, but that the\n \/\/ topology and networks utilize uni-directional links. Thus each \n \/\/ BasicLink is converted to two calls to add link, on for each direction\n for (vector::const_iterator i = ext_links.begin();\n i != ext_links.end(); ++i) {\n BasicExtLink *ext_link = (*i);\n AbstractController *abs_cntrl = ext_link->params()->ext_node;\n BasicRouter *router = ext_link->params()->int_node;\n\n \/\/ Store the ExtLink pointers for later\n m_ext_link_vector.push_back(ext_link);\n\n int machine_base_idx = MachineType_base_number(\n string_to_MachineType(abs_cntrl->getName()));\n int ext_idx1 = machine_base_idx + abs_cntrl->getVersion();\n int ext_idx2 = ext_idx1 + m_nodes;\n int int_idx = router->params()->router_id + 2*m_nodes;\n\n \/\/ create the internal uni-directional links in both directions\n \/\/ the first direction is marked: In\n addLink(ext_idx1, int_idx, ext_link, LinkDirection_In);\n \/\/ the first direction is marked: Out\n addLink(int_idx, ext_idx2, ext_link, LinkDirection_Out);\n }\n\n for (vector::const_iterator i = int_links.begin();\n i != int_links.end(); ++i) {\n BasicIntLink *int_link = (*i);\n BasicRouter *router_a = int_link->params()->node_a;\n BasicRouter *router_b = int_link->params()->node_b;\n\n \/\/ Store the IntLink pointers for later\n m_int_link_vector.push_back(int_link);\n\n int a = router_a->params()->router_id + 2*m_nodes;\n int b = router_b->params()->router_id + 2*m_nodes;\n\n \/\/ create the internal uni-directional links in both directions\n \/\/ the first direction is marked: In\n addLink(a, b, int_link, LinkDirection_In);\n \/\/ the second direction is marked: Out\n addLink(b, a, int_link, LinkDirection_Out);\n }\n}\n\nvoid\nTopology::createLinks(Network *net)\n{\n \/\/ Find maximum switchID\n SwitchID max_switch_id = 0;\n for (LinkMap::const_iterator i = m_link_map.begin();\n i != m_link_map.end(); ++i) {\n std::pair src_dest = (*i).first;\n max_switch_id = max(max_switch_id, src_dest.first);\n max_switch_id = max(max_switch_id, src_dest.second); \n }\n\n \/\/ Initialize weight, latency, and inter switched vectors\n Matrix topology_weights;\n int num_switches = max_switch_id+1;\n topology_weights.resize(num_switches);\n m_component_latencies.resize(num_switches);\n m_component_inter_switches.resize(num_switches);\n\n for (int i = 0; i < topology_weights.size(); i++) {\n topology_weights[i].resize(num_switches);\n m_component_latencies[i].resize(num_switches);\n m_component_inter_switches[i].resize(num_switches);\n\n for (int j = 0; j < topology_weights[i].size(); j++) {\n topology_weights[i][j] = INFINITE_LATENCY;\n\n \/\/ initialize to invalid values\n m_component_latencies[i][j] = -1;\n\n \/\/ initially assume direct connections \/ no intermediate\n \/\/ switches between components\n m_component_inter_switches[i][j] = 0;\n }\n }\n\n \/\/ Set identity weights to zero\n for (int i = 0; i < topology_weights.size(); i++) {\n topology_weights[i][i] = 0;\n }\n\n \/\/ Fill in the topology weights and bandwidth multipliers\n for (LinkMap::const_iterator i = m_link_map.begin();\n i != m_link_map.end(); ++i) {\n std::pair src_dest = (*i).first;\n BasicLink* link = (*i).second.link;\n int src = src_dest.first;\n int dst = src_dest.second;\n m_component_latencies[src][dst] = link->m_latency;\n topology_weights[src][dst] = link->m_weight;\n }\n \n \/\/ Walk topology and hookup the links\n Matrix dist = shortest_path(topology_weights, m_component_latencies,\n m_component_inter_switches);\n for (int i = 0; i < topology_weights.size(); i++) {\n for (int j = 0; j < topology_weights[i].size(); j++) {\n int weight = topology_weights[i][j];\n if (weight > 0 && weight != INFINITE_LATENCY) {\n NetDest destination_set =\n shortest_path_to_node(i, j, topology_weights, dist);\n makeLink(net, i, j, destination_set);\n }\n }\n }\n}\n\nvoid\nTopology::addLink(SwitchID src, SwitchID dest, BasicLink* link, \n LinkDirection dir)\n{\n assert(src <= m_number_of_switches+m_nodes+m_nodes);\n assert(dest <= m_number_of_switches+m_nodes+m_nodes);\n \n std::pair src_dest_pair;\n LinkEntry link_entry;\n\n src_dest_pair.first = src;\n src_dest_pair.second = dest;\n link_entry.direction = dir;\n link_entry.link = link;\n m_link_map[src_dest_pair] = link_entry;\n}\n\nvoid\nTopology::makeLink(Network *net, SwitchID src, SwitchID dest,\n const NetDest& routing_table_entry)\n{\n \/\/ Make sure we're not trying to connect two end-point nodes\n \/\/ directly together\n assert(src >= 2 * m_nodes || dest >= 2 * m_nodes);\n\n std::pair src_dest;\n LinkEntry link_entry; \n\n if (src < m_nodes) {\n src_dest.first = src;\n src_dest.second = dest;\n link_entry = m_link_map[src_dest];\n net->makeInLink(src, dest - (2 * m_nodes), link_entry.link,\n link_entry.direction, routing_table_entry);\n } else if (dest < 2*m_nodes) {\n assert(dest >= m_nodes);\n NodeID node = dest - m_nodes;\n src_dest.first = src;\n src_dest.second = dest;\n link_entry = m_link_map[src_dest];\n net->makeOutLink(src - (2 * m_nodes), node, link_entry.link,\n link_entry.direction, routing_table_entry);\n } else {\n assert((src >= 2 * m_nodes) && (dest >= 2 * m_nodes));\n src_dest.first = src;\n src_dest.second = dest;\n link_entry = m_link_map[src_dest];\n net->makeInternalLink(src - (2 * m_nodes), dest - (2 * m_nodes),\n link_entry.link, link_entry.direction,\n routing_table_entry);\n }\n}\n\n\/\/ The following all-pairs shortest path algorithm is based on the\n\/\/ discussion from Cormen et al., Chapter 26.1.\nvoid\nextend_shortest_path(Matrix& current_dist, Matrix& latencies,\n Matrix& inter_switches)\n{\n bool change = true;\n int nodes = current_dist.size();\n\n while (change) {\n change = false;\n for (int i = 0; i < nodes; i++) {\n for (int j = 0; j < nodes; j++) {\n int minimum = current_dist[i][j];\n int previous_minimum = minimum;\n int intermediate_switch = -1;\n for (int k = 0; k < nodes; k++) {\n minimum = min(minimum,\n current_dist[i][k] + current_dist[k][j]);\n if (previous_minimum != minimum) {\n intermediate_switch = k;\n inter_switches[i][j] =\n inter_switches[i][k] +\n inter_switches[k][j] + 1;\n }\n previous_minimum = minimum;\n }\n if (current_dist[i][j] != minimum) {\n change = true;\n current_dist[i][j] = minimum;\n assert(intermediate_switch >= 0);\n assert(intermediate_switch < latencies[i].size());\n latencies[i][j] = latencies[i][intermediate_switch] +\n latencies[intermediate_switch][j];\n }\n }\n }\n }\n}\n\nMatrix\nshortest_path(const Matrix& weights, Matrix& latencies, Matrix& inter_switches)\n{\n Matrix dist = weights;\n extend_shortest_path(dist, latencies, inter_switches);\n return dist;\n}\n\nbool\nlink_is_shortest_path_to_node(SwitchID src, SwitchID next, SwitchID final,\n const Matrix& weights, const Matrix& dist)\n{\n return weights[src][next] + dist[next][final] == dist[src][final];\n}\n\nNetDest\nshortest_path_to_node(SwitchID src, SwitchID next, const Matrix& weights,\n const Matrix& dist)\n{\n NetDest result;\n int d = 0;\n int machines;\n int max_machines;\n\n machines = MachineType_NUM;\n max_machines = MachineType_base_number(MachineType_NUM);\n\n for (int m = 0; m < machines; m++) {\n for (int i = 0; i < MachineType_base_count((MachineType)m); i++) {\n \/\/ we use \"d+max_machines\" below since the \"destination\"\n \/\/ switches for the machines are numbered\n \/\/ [MachineType_base_number(MachineType_NUM)...\n \/\/ 2*MachineType_base_number(MachineType_NUM)-1] for the\n \/\/ component network\n if (link_is_shortest_path_to_node(src, next, d + max_machines,\n weights, dist)) {\n MachineID mach = {(MachineType)m, i};\n result.add(mach);\n }\n d++;\n }\n }\n\n DPRINTF(RubyNetwork, \"Returning shortest path\\n\"\n \"(src-(2*max_machines)): %d, (next-(2*max_machines)): %d, \"\n \"src: %d, next: %d, result: %s\\n\",\n (src-(2*max_machines)), (next-(2*max_machines)),\n src, next, result);\n\n return result;\n}\n<|endoftext|>"} {"text":"#ifndef _SD_ANIMATIONS_HXX_\n#define _SD_ANIMATIONS_HXX_\n\nnamespace sd\n{\n\n\/** stores the link between an after effect node and its master for later insertion\n into the timing hierarchie\n*\/\nstruct AfterEffectNode\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > mxNode;\n ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > mxMaster;\n sal_Int32 mnMasterRel;\n\n AfterEffectNode( const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xMaster, sal_Int32 nMasterRel )\n : mxNode( xNode ), mxMaster( xMaster ), mnMasterRel( nMasterRel ) {}\n};\n\ntypedef std::list< AfterEffectNode > AfterEffectNodeList;\n\n\/** inserts the animation node in the given AfterEffectNode at the correct position\n in the timing hierarchie of its master *\/\nvoid stl_process_after_effect_node_func(AfterEffectNode& rNode);\n\n}; \/\/ namespace sd;\n\n#endif\nINTEGRATION: CWS impress49 (1.2.172); FILE MERGED 2005\/06\/10 15:51:07 cl 1.2.172.1: #i41546# reworked after effects#ifndef _SD_ANIMATIONS_HXX_\n#define _SD_ANIMATIONS_HXX_\n\nnamespace sd\n{\n\n\/** stores the link between an after effect node and its master for later insertion\n into the timing hierarchie\n*\/\nstruct AfterEffectNode\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > mxNode;\n ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > mxMaster;\n bool mbOnNextEffect;\n\n AfterEffectNode( const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xMaster, bool bOnNextEffect )\n : mxNode( xNode ), mxMaster( xMaster ), mbOnNextEffect( bOnNextEffect ) {}\n};\n\ntypedef std::list< AfterEffectNode > AfterEffectNodeList;\n\n\/** inserts the animation node in the given AfterEffectNode at the correct position\n in the timing hierarchie of its master *\/\nvoid stl_process_after_effect_node_func(AfterEffectNode& rNode);\n\n}; \/\/ namespace sd;\n\n#endif\n<|endoftext|>"} {"text":"#ifndef _SDD_HOM_EVALUATION_HH_\n#define _SDD_HOM_EVALUATION_HH_\n\n#include \n#include \n\n#include \"sdd\/hom\/context_fwd.hh\"\n#include \"sdd\/mem\/interrupt.hh\"\n#include \"sdd\/order\/order.hh\"\n\nnamespace sdd { namespace hom {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Evaluate an homomorphism.\ntemplate \nstruct evaluation\n{\n \/\/\/ @brief Used by util::variant.\n using result_type = SDD;\n\n \/\/\/ @brief Terminal |0| case.\n \/\/\/\n \/\/\/ It shall never be called as the |0| case is handled by the evaluation of\n \/\/\/ homomorphism::operator().\n template \n SDD\n operator()( const H&, const zero_terminal&\n , const homomorphism&, const SDD&\n , context&, const order&)\n const noexcept\n {\n assert(false);\n __builtin_unreachable();\n }\n\n \/\/\/ @brief Terminal |1| case.\n template \n SDD\n operator()( const H& h, const one_terminal&\n , const homomorphism&, const SDD& x\n , context& cxt, const order& o)\n const\n {\n return h(cxt, o, x);\n }\n\n \/\/\/ @brief Dispatch evaluation to the concrete homomorphism.\n \/\/\/\n \/\/\/ Implement a part of the automatic saturation: evaluation is propagated on successors\n \/\/\/ whenever possible.\n template \n SDD\n operator()( const H& h, const Node& node\n , const homomorphism& hom, const SDD& x\n , context& cxt, const order& o)\n const\n {\n assert(not o.empty() && \"Empty order.\");\n assert(o.variable() == node.variable() && \"Different variables in order and SDD.\");\n\n if (h.skip(o))\n {\n \/\/ The evaluated homomorphism skips the current level. We can thus forward its application\n \/\/ to the following levels.\n dd::square_union su;\n su.reserve(node.size());\n for (const auto& arc : node)\n {\n try\n {\n SDD new_successor = hom(cxt, o.next(), arc.successor());\n if (not new_successor.empty())\n {\n su.add(new_successor, arc.valuation());\n }\n }\n catch (interrupt>& i)\n {\n su.add(i.result(), arc.valuation());\n i.result() = {node.variable(), su(cxt.sdd_context())};\n throw;\n }\n }\n return {node.variable(), su(cxt.sdd_context())};\n }\n else\n {\n try\n {\n return h(cxt, o, x);\n }\n catch (interrupt>& i)\n {\n throw;\n }\n }\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Default traits for homomorphisms.\ntemplate \nstruct homomorphism_traits\n{\n static constexpr bool should_cache = true;\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief The evaluation of an homomorphism in the cache.\ntemplate \nstruct cached_homomorphism\n{\n \/\/\/ @brief Needed by the cache.\n using result_type = SDD;\n\n \/\/\/ @brief The current order position.\n const order ord;\n\n \/\/\/ @brief The homomorphism to evaluate.\n const homomorphism hom;\n\n \/\/\/ @brief The homomorphism's operand.\n const SDD sdd;\n\n \/\/\/ @brief Constructor.\n cached_homomorphism(const order& o, const homomorphism& h, const SDD& s)\n : ord(o), hom(h), sdd(s)\n {}\n\n \/\/\/ @brief Launch the evaluation.\n \/\/\/\n \/\/\/ Called by the cache.\n SDD\n operator()(context& cxt)\n const\n {\n return binary_visit_self(evaluation(), hom, sdd, cxt, ord);\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @related cached_homomorphism\n\/\/\/ We don't need to compare orders as the SDD operands bring the same information.\ntemplate \ninline\nbool\noperator==(const cached_homomorphism& lhs, const cached_homomorphism& rhs)\nnoexcept\n{\n return lhs.hom == rhs.hom and lhs.sdd == rhs.sdd;\n}\n\n\/\/\/ @internal\n\/\/\/ @related cached_homomorphism\ntemplate \nstd::ostream&\noperator<<(std::ostream& os, const cached_homomorphism& ch)\n{\n return os << ch.hom;\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Used by the cache as a filter to know if an homomorphism should be cached.\ntemplate \nstruct should_cache\n{\n \/\/\/ @brief Needed by mem::variant.\n using result_type = bool;\n\n \/\/\/ @brief Dispatch to each homomorphism's trait.\n template \n constexpr bool\n operator()(const T&)\n const noexcept\n {\n return homomorphism_traits::should_cache;\n }\n\n \/\/\/ @brief Application of should_cache.\n bool\n operator()(const cached_homomorphism& ch)\n const noexcept\n {\n return visit(*this, ch.hom);\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Used by the cache as a filter to know if an homomorphism should be cached.\ntemplate \nstruct one_terminal_evaluation\n{\n \/\/\/ @brief Needed by me::variant.\n using result_type = bool;\n\n \/\/\/ @brief Application of should_cache.\n bool\n operator()(const cached_homomorphism& ch)\n const noexcept\n {\n return ch.sdd != one();\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace sdd::hom\n\nnamespace std {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Hash specialization for sdd::hom::cached_homomorphism\n\/\/\/\n\/\/\/ We don't need to hash order as the SDD operand brings the same information.\ntemplate \nstruct hash>\n{\n std::size_t\n operator()(const sdd::hom::cached_homomorphism& ch)\n const\n {\n std::size_t seed = sdd::util::hash(ch.hom);\n sdd::util::hash_combine(seed, ch.sdd);\n return seed;\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace std\n\n#endif \/\/ _SDD_HOM_EVALUATION_HH_\nRemove useless try\/catch.#ifndef _SDD_HOM_EVALUATION_HH_\n#define _SDD_HOM_EVALUATION_HH_\n\n#include \n#include \n\n#include \"sdd\/hom\/context_fwd.hh\"\n#include \"sdd\/mem\/interrupt.hh\"\n#include \"sdd\/order\/order.hh\"\n\nnamespace sdd { namespace hom {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Evaluate an homomorphism.\ntemplate \nstruct evaluation\n{\n \/\/\/ @brief Used by util::variant.\n using result_type = SDD;\n\n \/\/\/ @brief Terminal |0| case.\n \/\/\/\n \/\/\/ It shall never be called as the |0| case is handled by the evaluation of\n \/\/\/ homomorphism::operator().\n template \n SDD\n operator()( const H&, const zero_terminal&\n , const homomorphism&, const SDD&\n , context&, const order&)\n const noexcept\n {\n assert(false);\n __builtin_unreachable();\n }\n\n \/\/\/ @brief Terminal |1| case.\n template \n SDD\n operator()( const H& h, const one_terminal&\n , const homomorphism&, const SDD& x\n , context& cxt, const order& o)\n const\n {\n return h(cxt, o, x);\n }\n\n \/\/\/ @brief Dispatch evaluation to the concrete homomorphism.\n \/\/\/\n \/\/\/ Implement a part of the automatic saturation: evaluation is propagated on successors\n \/\/\/ whenever possible.\n template \n SDD\n operator()( const H& h, const Node& node\n , const homomorphism& hom, const SDD& x\n , context& cxt, const order& o)\n const\n {\n assert(not o.empty() && \"Empty order.\");\n assert(o.variable() == node.variable() && \"Different variables in order and SDD.\");\n\n if (h.skip(o))\n {\n \/\/ The evaluated homomorphism skips the current level. We can thus forward its application\n \/\/ to the following levels.\n dd::square_union su;\n su.reserve(node.size());\n for (const auto& arc : node)\n {\n try\n {\n SDD new_successor = hom(cxt, o.next(), arc.successor());\n if (not new_successor.empty())\n {\n su.add(new_successor, arc.valuation());\n }\n }\n catch (interrupt>& i)\n {\n su.add(i.result(), arc.valuation());\n i.result() = {node.variable(), su(cxt.sdd_context())};\n throw;\n }\n }\n return {node.variable(), su(cxt.sdd_context())};\n }\n else\n {\n return h(cxt, o, x);\n }\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Default traits for homomorphisms.\ntemplate \nstruct homomorphism_traits\n{\n static constexpr bool should_cache = true;\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief The evaluation of an homomorphism in the cache.\ntemplate \nstruct cached_homomorphism\n{\n \/\/\/ @brief Needed by the cache.\n using result_type = SDD;\n\n \/\/\/ @brief The current order position.\n const order ord;\n\n \/\/\/ @brief The homomorphism to evaluate.\n const homomorphism hom;\n\n \/\/\/ @brief The homomorphism's operand.\n const SDD sdd;\n\n \/\/\/ @brief Constructor.\n cached_homomorphism(const order& o, const homomorphism& h, const SDD& s)\n : ord(o), hom(h), sdd(s)\n {}\n\n \/\/\/ @brief Launch the evaluation.\n \/\/\/\n \/\/\/ Called by the cache.\n SDD\n operator()(context& cxt)\n const\n {\n return binary_visit_self(evaluation(), hom, sdd, cxt, ord);\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @related cached_homomorphism\n\/\/\/ We don't need to compare orders as the SDD operands bring the same information.\ntemplate \ninline\nbool\noperator==(const cached_homomorphism& lhs, const cached_homomorphism& rhs)\nnoexcept\n{\n return lhs.hom == rhs.hom and lhs.sdd == rhs.sdd;\n}\n\n\/\/\/ @internal\n\/\/\/ @related cached_homomorphism\ntemplate \nstd::ostream&\noperator<<(std::ostream& os, const cached_homomorphism& ch)\n{\n return os << ch.hom;\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Used by the cache as a filter to know if an homomorphism should be cached.\ntemplate \nstruct should_cache\n{\n \/\/\/ @brief Needed by mem::variant.\n using result_type = bool;\n\n \/\/\/ @brief Dispatch to each homomorphism's trait.\n template \n constexpr bool\n operator()(const T&)\n const noexcept\n {\n return homomorphism_traits::should_cache;\n }\n\n \/\/\/ @brief Application of should_cache.\n bool\n operator()(const cached_homomorphism& ch)\n const noexcept\n {\n return visit(*this, ch.hom);\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Used by the cache as a filter to know if an homomorphism should be cached.\ntemplate \nstruct one_terminal_evaluation\n{\n \/\/\/ @brief Needed by me::variant.\n using result_type = bool;\n\n \/\/\/ @brief Application of should_cache.\n bool\n operator()(const cached_homomorphism& ch)\n const noexcept\n {\n return ch.sdd != one();\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace sdd::hom\n\nnamespace std {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Hash specialization for sdd::hom::cached_homomorphism\n\/\/\/\n\/\/\/ We don't need to hash order as the SDD operand brings the same information.\ntemplate \nstruct hash>\n{\n std::size_t\n operator()(const sdd::hom::cached_homomorphism& ch)\n const\n {\n std::size_t seed = sdd::util::hash(ch.hom);\n sdd::util::hash_combine(seed, ch.sdd);\n return seed;\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace std\n\n#endif \/\/ _SDD_HOM_EVALUATION_HH_\n<|endoftext|>"} {"text":"#include \n#include \"vector_tile.pb.h\"\n#include \"vector_tile_compression.hpp\"\n\n#include \n#include \n\n#include \n\nint main(int argc, char** argv)\n{\n try\n {\n if (argc < 2)\n {\n std::clog << \"usage: vtile-edit \/path\/to\/tile.vector.mvt [--set-version version]\" << std::endl;\n return -1;\n }\n std::string vtile(argv[1]);\n mapnik::util::file input(vtile);\n if (!input.open())\n {\n std::clog << std::string(\"failed to open \") + vtile << \"\\n\";\n return -1;\n }\n\n unsigned version = 1;\n std::string flag = argv[2];\n if (flag == \"--set-version\")\n {\n version = std::stoi(argv[3]);\n }\n\n std::string message(input.data().get(), input.size());\n\n bool is_zlib = mapnik::vector_tile_impl::is_zlib_compressed(message);\n bool is_gzip = mapnik::vector_tile_impl::is_gzip_compressed(message);\n if (is_zlib || is_gzip)\n {\n if (is_zlib)\n {\n std::cout << \"message: zlib compressed\\n\";\n }\n else if (is_gzip)\n {\n std::cout << \"message: gzip compressed\\n\";\n }\n std::string uncompressed;\n mapnik::vector_tile_impl::zlib_decompress(message,uncompressed);\n message = uncompressed;\n }\n\n vector_tile::Tile tile;\n tile.ParseFromString(message);\n \n for (int j=0;jname() << std::endl;\n std::clog << \"old version: \" << layer->version() << std::endl;\n if (version != layer->version())\n {\n layer->set_version(version);\n }\n std::clog << \"new version: \" << layer->version() << std::endl;\n }\n\n \/\/ Serialize\n std::string output;\n tile.SerializeToString(&output);\n\n \/\/ Recompress\n bool gzip = true;\n if (is_zlib || is_gzip)\n {\n if (is_zlib)\n {\n gzip = false;\n std::cout << \"message: zlib compressing\\n\";\n }\n else if (is_gzip)\n {\n gzip = true;\n std::cout << \"message: gzip compressing\\n\";\n }\n std::string compressed;\n mapnik::vector_tile_impl::zlib_compress(output,compressed,gzip);\n output = compressed;\n }\n\n std::ofstream file(vtile);\n file << output;\n\n std::clog << \"wrote to: \" << vtile << std::endl;\n }\n catch (std::exception const& ex)\n {\n std::clog << \"error: \" << ex.what() << \"\\n\";\n return -1;\n }\n return 0;\n}\nUpdated vtile-edit#include \n#include \"vector_tile.pb.h\"\n#include \"vector_tile_compression.hpp\"\n\n#include \n#include \n\n#include \n\nint main(int argc, char** argv)\n{\n try\n {\n if (argc < 2)\n {\n std::clog << \"usage: vtile-edit \/path\/to\/tile.vector.mvt [--set-version version]\" << std::endl;\n return -1;\n }\n std::string vtile(argv[1]);\n mapnik::util::file input(vtile);\n if (!input.open())\n {\n std::clog << std::string(\"failed to open \") + vtile << \"\\n\";\n return -1;\n }\n\n unsigned version = 0;\n bool clean_empty = false;\n if (argc > 2)\n {\n for (int i = 2; i < argc; i++)\n {\n std::string flag = argv[i];\n if (flag == \"--set-version\")\n {\n version = std::stoi(argv[i + 1]);\n }\n if (flag == \"--clean-empty\")\n {\n clean_empty = true;\n }\n }\n }\n\n std::string message(input.data().get(), input.size());\n\n bool is_zlib = mapnik::vector_tile_impl::is_zlib_compressed(message);\n bool is_gzip = mapnik::vector_tile_impl::is_gzip_compressed(message);\n if (is_zlib || is_gzip)\n {\n if (is_zlib)\n {\n std::cout << \"message: zlib compressed\\n\";\n }\n else if (is_gzip)\n {\n std::cout << \"message: gzip compressed\\n\";\n }\n std::string uncompressed;\n mapnik::vector_tile_impl::zlib_decompress(message,uncompressed);\n message = uncompressed;\n }\n\n vector_tile::Tile tile;\n tile.ParseFromString(message);\n \n for (int j=0;jname() << std::endl;\n if (version != 0)\n {\n std::clog << \"old version: \" << layer->version() << std::endl;\n if (version != layer->version())\n {\n layer->set_version(version);\n }\n std::clog << \"new version: \" << layer->version() << std::endl;\n }\n if (clean_empty)\n {\n std::clog << \"Cleaning empty features\" << std::endl;\n for (int i = 0; i < layer->features_size(); ++i)\n {\n auto feature = layer->mutable_features(i);\n if (feature->geometry_size() == 0 && !feature->has_raster())\n {\n layer->mutable_features()->DeleteSubrange(i,1);\n --i;\n }\n }\n if (layer->features_size() == 0) \n {\n tile.mutable_layers()->DeleteSubrange(j,1);\n --j;\n }\n }\n }\n\n \/\/ Serialize\n std::string output;\n tile.SerializeToString(&output);\n\n \/\/ Recompress\n bool gzip = true;\n if (is_zlib || is_gzip)\n {\n if (is_zlib)\n {\n gzip = false;\n std::cout << \"message: zlib compressing\\n\";\n }\n else if (is_gzip)\n {\n gzip = true;\n std::cout << \"message: gzip compressing\\n\";\n }\n std::string compressed;\n mapnik::vector_tile_impl::zlib_compress(output,compressed,gzip);\n output = compressed;\n }\n\n std::ofstream file(vtile);\n file << output;\n\n std::clog << \"wrote to: \" << vtile << std::endl;\n }\n catch (std::exception const& ex)\n {\n std::clog << \"error: \" << ex.what() << \"\\n\";\n return -1;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\n#include \"Core\/Common.h\"\n#include \n#include \"Assembler.h\"\n#include \"Commands\/CAssemblerLabel.h\"\n#include \"Util\/Util.h\"\n#include \"Core\/FileManager.h\"\n\nFileManager fileManager;\nFileManager* g_fileManager = &fileManager;\n\ntGlobal Global;\nCArchitecture* Arch;\n\nstd::wstring getFolderNameFromPath(const std::wstring& src)\n{\n\tsize_t s = src.rfind('\\\\');\n\tif (s == std::wstring::npos)\n\t{\n\t\ts = src.rfind('\/');\n\t\tif (s == std::wstring::npos)\n\t\t\treturn L\".\";\n\t}\n\n\treturn src.substr(0,s);\n}\n\nstd::wstring getFullPathName(const std::wstring& path)\n{\n\tif (Global.relativeInclude == true)\n\t{\n\t\tif (isAbsolutePath(path))\n\t\t{\n\t\t\treturn path;\n\t\t} else {\n\t\t\tstd::wstring source = Global.FileInfo.FileList[Global.FileInfo.FileNum];\n\t\t\treturn getFolderNameFromPath(source) + L\"\/\" + path;\n\t\t}\n\t} else {\n\t\treturn path;\n\t}\n}\n\nbool checkLabelDefined(const std::wstring& labelName, int section)\n{\n\tLabel* label = Global.symbolTable.getLabel(labelName,Global.FileInfo.FileNum,section);\n\treturn label->isDefined();\n}\n\nbool checkValidLabelName(const std::wstring& labelName)\n{\n\treturn Global.symbolTable.isValidSymbolName(labelName);\n}\n\nbool isPowerOfTwo(u64 n)\n{\n\tif (n == 0) return false;\n\treturn !(n & (n - 1));\n}\nFix getFolderNameFromPath function#include \"stdafx.h\"\n#include \"Core\/Common.h\"\n#include \n#include \"Assembler.h\"\n#include \"Commands\/CAssemblerLabel.h\"\n#include \"Util\/Util.h\"\n#include \"Core\/FileManager.h\"\n\nFileManager fileManager;\nFileManager* g_fileManager = &fileManager;\n\ntGlobal Global;\nCArchitecture* Arch;\n\nstd::wstring getFolderNameFromPath(const std::wstring& src)\n{\n#ifdef _WIN32\n\tsize_t s = src.find_last_of(L\"\\\\\/\");\n#else\n\tsize_t s = src.rfind(L\"\/\");\n#endif\n\tif (s == std::wstring::npos)\n\t{\n\t\treturn L\".\";\n\t}\n\n\treturn src.substr(0,s);\n}\n\nstd::wstring getFullPathName(const std::wstring& path)\n{\n\tif (Global.relativeInclude == true)\n\t{\n\t\tif (isAbsolutePath(path))\n\t\t{\n\t\t\treturn path;\n\t\t} else {\n\t\t\tstd::wstring source = Global.FileInfo.FileList[Global.FileInfo.FileNum];\n\t\t\treturn getFolderNameFromPath(source) + L\"\/\" + path;\n\t\t}\n\t} else {\n\t\treturn path;\n\t}\n}\n\nbool checkLabelDefined(const std::wstring& labelName, int section)\n{\n\tLabel* label = Global.symbolTable.getLabel(labelName,Global.FileInfo.FileNum,section);\n\treturn label->isDefined();\n}\n\nbool checkValidLabelName(const std::wstring& labelName)\n{\n\treturn Global.symbolTable.isValidSymbolName(labelName);\n}\n\nbool isPowerOfTwo(u64 n)\n{\n\tif (n == 0) return false;\n\treturn !(n & (n - 1));\n}\n<|endoftext|>"} {"text":"\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXQt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2010-2011 Razor team\n * Authors:\n * Alexander Sokoloff \n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \"ui_addplugindialog.h\"\n#include \"addplugindialog.h\"\n#include \"plugin.h\"\n#include \"..\/lxqtpanelapplication.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#define SEARCH_ROLE Qt::UserRole\n#define INDEX_ROLE SEARCH_ROLE+1\n\nAddPluginDialog::AddPluginDialog(QWidget *parent):\n QDialog(parent),\n ui(new Ui::AddPluginDialog)\n{\n ui->setupUi(this);\n\n QStringList desktopFilesDirs;\n desktopFilesDirs << QString(getenv(\"LXQT_PANEL_PLUGINS_DIR\")).split(':', QString::SkipEmptyParts);\n desktopFilesDirs << QString(\"%1\/%2\").arg(XdgDirs::dataHome(), \"\/lxqt\/lxqt-panel\");\n desktopFilesDirs << PLUGIN_DESKTOPS_DIR;\n\n mPlugins = LXQt::PluginInfo::search(desktopFilesDirs, QStringLiteral(\"LXQtPanel\/Plugin\"), QStringLiteral(\"*\"));\n std::sort(mPlugins.begin(), mPlugins.end(), [](const LXQt::PluginInfo &p1, const LXQt::PluginInfo &p2) {\n return p1.name() < p2.name() || (p1.name() == p2.name() && p1.comment() < p2.comment());\n });\n\n ui->pluginList->setItemDelegate(new LXQt::HtmlDelegate(QSize(32, 32), ui->pluginList));\n ui->pluginList->setContextMenuPolicy(Qt::CustomContextMenu);\n\n filter();\n\n \/\/ search\n mSearchTimer.setInterval(300);\n mSearchTimer.setSingleShot(true);\n connect(ui->searchEdit, &QLineEdit::textEdited,\n &mSearchTimer, static_cast(&QTimer::start));\n connect(&mSearchTimer, &QTimer::timeout, this, &AddPluginDialog::filter);\n connect(ui->pluginList, &QListWidget::doubleClicked, this, &AddPluginDialog::emitPluginSelected);\n connect(ui->addButton, &QPushButton::clicked, this, &AddPluginDialog::emitPluginSelected);\n\n connect(dynamic_cast(qApp), &LXQtPanelApplication::pluginAdded\n , this, &AddPluginDialog::filter);\n connect(dynamic_cast(qApp), &LXQtPanelApplication::pluginRemoved\n , this, &AddPluginDialog::filter);\n}\n\nAddPluginDialog::~AddPluginDialog()\n{\n delete ui;\n}\n\nvoid AddPluginDialog::filter()\n{\n QListWidget* pluginList = ui->pluginList;\n\n const int curr_item = 0 < pluginList->count() ? pluginList->currentRow() : 0;\n pluginList->clear();\n\n static QIcon fallIco = XdgIcon::fromTheme(\"preferences-plugin\");\n\n int pluginCount = mPlugins.length();\n for (int i = 0; i < pluginCount; ++i)\n {\n const LXQt::PluginInfo &plugin = mPlugins.at(i);\n\n QString s = QStringLiteral(\"%1 %2 %3 %4\").arg(plugin.name(),\n plugin.comment(),\n plugin.value(\"Name\").toString(),\n plugin.value(\"Comment\").toString());\n if (!s.contains(ui->searchEdit->text(), Qt::CaseInsensitive))\n continue;\n\n QListWidgetItem* item = new QListWidgetItem(ui->pluginList);\n \/\/ disable single-instances plugins already in use\n if (dynamic_cast(qApp)->isPluginSingletonAndRunnig(plugin.id()))\n {\n item->setFlags(item->flags() & ~Qt::ItemIsEnabled);\n item->setBackground(palette().brush(QPalette::Disabled, QPalette::Text));\n item->setText(QStringLiteral(\"%1<\/b>
%2
%3<\/small>\")\n .arg(plugin.name(), plugin.comment(), tr(\"(only one instance can run at a time)\")));\n } else\n item->setText(QStringLiteral(\"%1<\/b>
%2\").arg(plugin.name(), plugin.comment()));\n item->setIcon(plugin.icon(fallIco));\n item->setData(INDEX_ROLE, i);\n }\n\n if (pluginCount > 0)\n ui->pluginList->setCurrentRow(curr_item < pluginCount ? curr_item : pluginCount - 1);\n}\n\nvoid AddPluginDialog::emitPluginSelected()\n{\n QListWidget* pluginList = ui->pluginList;\n if (pluginList->currentItem() && pluginList->currentItem()->isSelected())\n {\n LXQt::PluginInfo plugin = mPlugins.at(pluginList->currentItem()->data(INDEX_ROLE).toInt());\n emit pluginSelected(plugin);\n }\n}\n\naddplugindialog: show also the plugin ID (desktop file name)\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXQt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2010-2011 Razor team\n * Authors:\n * Alexander Sokoloff \n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \"ui_addplugindialog.h\"\n#include \"addplugindialog.h\"\n#include \"plugin.h\"\n#include \"..\/lxqtpanelapplication.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#define SEARCH_ROLE Qt::UserRole\n#define INDEX_ROLE SEARCH_ROLE+1\n\nAddPluginDialog::AddPluginDialog(QWidget *parent):\n QDialog(parent),\n ui(new Ui::AddPluginDialog)\n{\n ui->setupUi(this);\n\n QStringList desktopFilesDirs;\n desktopFilesDirs << QString(getenv(\"LXQT_PANEL_PLUGINS_DIR\")).split(':', QString::SkipEmptyParts);\n desktopFilesDirs << QString(\"%1\/%2\").arg(XdgDirs::dataHome(), \"\/lxqt\/lxqt-panel\");\n desktopFilesDirs << PLUGIN_DESKTOPS_DIR;\n\n mPlugins = LXQt::PluginInfo::search(desktopFilesDirs, QStringLiteral(\"LXQtPanel\/Plugin\"), QStringLiteral(\"*\"));\n std::sort(mPlugins.begin(), mPlugins.end(), [](const LXQt::PluginInfo &p1, const LXQt::PluginInfo &p2) {\n return p1.name() < p2.name() || (p1.name() == p2.name() && p1.comment() < p2.comment());\n });\n\n ui->pluginList->setItemDelegate(new LXQt::HtmlDelegate(QSize(32, 32), ui->pluginList));\n ui->pluginList->setContextMenuPolicy(Qt::CustomContextMenu);\n\n filter();\n\n \/\/ search\n mSearchTimer.setInterval(300);\n mSearchTimer.setSingleShot(true);\n connect(ui->searchEdit, &QLineEdit::textEdited,\n &mSearchTimer, static_cast(&QTimer::start));\n connect(&mSearchTimer, &QTimer::timeout, this, &AddPluginDialog::filter);\n connect(ui->pluginList, &QListWidget::doubleClicked, this, &AddPluginDialog::emitPluginSelected);\n connect(ui->addButton, &QPushButton::clicked, this, &AddPluginDialog::emitPluginSelected);\n\n connect(dynamic_cast(qApp), &LXQtPanelApplication::pluginAdded\n , this, &AddPluginDialog::filter);\n connect(dynamic_cast(qApp), &LXQtPanelApplication::pluginRemoved\n , this, &AddPluginDialog::filter);\n}\n\nAddPluginDialog::~AddPluginDialog()\n{\n delete ui;\n}\n\nvoid AddPluginDialog::filter()\n{\n QListWidget* pluginList = ui->pluginList;\n\n const int curr_item = 0 < pluginList->count() ? pluginList->currentRow() : 0;\n pluginList->clear();\n\n static QIcon fallIco = XdgIcon::fromTheme(\"preferences-plugin\");\n\n int pluginCount = mPlugins.length();\n for (int i = 0; i < pluginCount; ++i)\n {\n const LXQt::PluginInfo &plugin = mPlugins.at(i);\n\n QString s = QStringLiteral(\"%1 %2 %3 %4 %5\").arg(plugin.name(),\n plugin.comment(),\n plugin.value(\"Name\").toString(),\n plugin.value(\"Comment\").toString(),\n plugin.id());\n if (!s.contains(ui->searchEdit->text(), Qt::CaseInsensitive))\n continue;\n\n QListWidgetItem* item = new QListWidgetItem(ui->pluginList);\n \/\/ disable single-instances plugins already in use\n if (dynamic_cast(qApp)->isPluginSingletonAndRunnig(plugin.id()))\n {\n item->setFlags(item->flags() & ~Qt::ItemIsEnabled);\n item->setBackground(palette().brush(QPalette::Disabled, QPalette::Text));\n item->setText(QStringLiteral(\"%1<\/b> (%2)
%3
%4<\/small>\")\n .arg(plugin.name(), plugin.id(), plugin.comment(), tr(\"(only one instance can run at a time)\")));\n } else\n item->setText(QStringLiteral(\"%1<\/b> (%2)
%3\").arg(plugin.name(), plugin.id(), plugin.comment()));\n item->setIcon(plugin.icon(fallIco));\n item->setData(INDEX_ROLE, i);\n }\n\n if (pluginCount > 0)\n ui->pluginList->setCurrentRow(curr_item < pluginCount ? curr_item : pluginCount - 1);\n}\n\nvoid AddPluginDialog::emitPluginSelected()\n{\n QListWidget* pluginList = ui->pluginList;\n if (pluginList->currentItem() && pluginList->currentItem()->isSelected())\n {\n LXQt::PluginInfo plugin = mPlugins.at(pluginList->currentItem()->data(INDEX_ROLE).toInt());\n emit pluginSelected(plugin);\n }\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2016, Joseph Mirabel\n\/\/ Authors: Joseph Mirabel (joseph.mirabel@laas.fr)\n\/\/\n\/\/ This file is part of hpp-pinocchio.\n\/\/ hpp-pinocchio is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-pinocchio is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-pinocchio. If not, see .\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\nnamespace hpp {\n namespace pinocchio {\n namespace urdf {\n using se3::FrameIndex;\n\n namespace {\n#ifdef HPP_DEBUG\n const bool verbose = true;\n#else\n const bool verbose = false;\n#endif\n\n JointPtr_t findSpecialJoint (const HumanoidRobotPtr_t& robot, const std::string& linkName)\n {\n return robot->getJointByBodyName (linkName);\n }\n\n void setSpecialJoints (const HumanoidRobotPtr_t& robot, const std::string& prefix) {\n try {\n robot->waist (robot->getJointByName(prefix + \"root_joint\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No waist joint found\");\n }\n try {\n robot->chest (findSpecialJoint (robot, prefix + \"chest\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No chest joint found\");\n }\n try {\n robot->leftWrist (findSpecialJoint (robot, prefix + \"l_wrist\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No left wrist joint found\");\n }\n try {\n robot->rightWrist (findSpecialJoint (robot, prefix + \"r_wrist\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No right wrist joint found\");\n }\n try {\n robot->leftAnkle (findSpecialJoint (robot, prefix + \"l_ankle\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No left ankle joint found\");\n }\n try {\n robot->rightAnkle (findSpecialJoint (robot, prefix + \"r_ankle\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No right ankle joint found\");\n }\n try {\n robot->gazeJoint (findSpecialJoint (robot, prefix + \"gaze\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No gaze joint found\");\n }\n }\n\n void fillGaze (const HumanoidRobotPtr_t robot)\n {\n vector3_t dir, origin;\n \/\/ Gaze direction is defined by the gaze joint local\n \/\/ orientation.\n dir[0] = 1;\n dir[1] = 0;\n dir[2] = 0;\n \/\/ Gaze position should is defined by the gaze joint local\n \/\/ origin.\n origin[0] = 0;\n origin[1] = 0;\n origin[2] = 0;\n robot->gaze (dir, origin);\n }\n\n se3::JointModelVariant buildJoint (const std::string& type)\n {\n if (type == \"freeflyer\") return se3::JointModelFreeFlyer();\n else if (type == \"planar\") return se3::JointModelPlanar();\n else if (type == \"prismatic\") return se3::JointModelPrismatic<0>();\n else throw std::invalid_argument\n (\"Root joint type is currently not available.\");\n }\n\n void setPrefix (const std::string& prefix,\n Model& model, GeomModel& geomModel,\n const JointIndex& idFirstJoint,\n const FrameIndex& idFirstFrame)\n {\n for (JointIndex i = idFirstJoint; i < model.joints.size(); ++i) {\n model.names[i] = prefix + model.names[i];\n }\n for (FrameIndex i = idFirstFrame; i < model.frames.size(); ++i) {\n se3::Frame& f = model.frames[i];\n f.name = prefix + f.name;\n }\n BOOST_FOREACH(se3::GeometryObject& go, geomModel.geometryObjects) {\n go.name = prefix + go.name;\n }\n }\n\n void setRootJointBounds(Model& model,\n const JointIndex& rtIdx,\n const std::string& rootType)\n {\n value_type b = std::numeric_limits::infinity();\n if (rootType == \"freeflyer\") {\n const std::size_t idx = model.joints[rtIdx].idx_q();\n model.upperPositionLimit.segment<3>(idx).setConstant(+b);\n model.lowerPositionLimit.segment<3>(idx).setConstant(-b);\n \/\/ Quaternion bounds\n b = 1.01;\n const size_type quat_idx = idx + 3;\n model.upperPositionLimit.segment<4>(quat_idx).setConstant(+b);\n model.lowerPositionLimit.segment<4>(quat_idx).setConstant(-b);\n } else if (rootType == \"planar\") {\n const std::size_t idx = model.joints[rtIdx].idx_q();\n model.upperPositionLimit.segment<2>(idx).setConstant(+b);\n model.lowerPositionLimit.segment<2>(idx).setConstant(-b);\n \/\/ Unit complex bounds\n b = 1.01;\n const size_type cplx_idx = idx + 2;\n model.upperPositionLimit.segment<2>(cplx_idx).setConstant(+b);\n model.lowerPositionLimit.segment<2>(cplx_idx).setConstant(-b);\n }\n }\n\n std::string makeModelPath (const std::string& package,\n const std::string& type,\n const std::string& modelName,\n const std::string& suffix = \"\")\n {\n std::stringstream ss;\n ss << \"package:\/\/\" << package << \"\/\" << type << \"\/\" << modelName << suffix << \".\" << type;\n return ss.str();\n }\n }\n\n void loadRobotModel (const DevicePtr_t& robot,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& modelName,\n\t\t\t const std::string& urdfSuffix,\n const std::string& srdfSuffix)\n {\n loadModel (robot, 0, \"\", rootJointType,\n makeModelPath(package, \"urdf\", modelName, urdfSuffix),\n makeModelPath(package, \"srdf\", modelName, srdfSuffix));\n }\n\n void loadRobotModel (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n\t\t\t const std::string& prefix,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& modelName,\n\t\t\t const std::string& urdfSuffix,\n const std::string& srdfSuffix)\n {\n loadModel (robot, baseJoint, \n (prefix.empty() ? \"\" : prefix + \"\/\"),\n rootJointType,\n makeModelPath(package, \"urdf\", modelName, urdfSuffix),\n makeModelPath(package, \"srdf\", modelName, srdfSuffix));\n }\n\n void loadHumanoidModel (const HumanoidRobotPtr_t& robot,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& modelName,\n\t\t\t const std::string& urdfSuffix,\n\t\t\t const std::string& srdfSuffix)\n {\n loadRobotModel(robot, rootJointType, package, modelName, urdfSuffix, srdfSuffix);\n\n\t\/\/ Look for special joints and attach them to the model.\n\tsetSpecialJoints (robot, \"\");\n\t\/\/ Fill gaze position and direction.\n\tfillGaze (robot);\n }\n\n void loadHumanoidModel (const HumanoidRobotPtr_t& robot,\n const JointIndex& baseJoint,\n\t\t\t const std::string& prefix,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& modelName,\n\t\t\t const std::string& urdfSuffix,\n\t\t\t const std::string& srdfSuffix)\n {\n loadRobotModel(robot, baseJoint, prefix, rootJointType, package, modelName, urdfSuffix, srdfSuffix);\n\n\t\/\/ Look for special joints and attach them to the model.\n\tsetSpecialJoints (robot, prefix);\n\t\/\/ Fill gaze position and direction.\n\tfillGaze (robot);\n }\n\n void loadUrdfModel (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n const std::string& prefix,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& filename)\n {\n loadModel (robot, baseJoint,\n (prefix.empty() ? \"\" : prefix + \"\/\"),\n rootJointType,\n makeModelPath(package, \"urdf\", filename), \"\");\n }\n\n void loadUrdfModel (const DevicePtr_t& robot,\n\t\t\t const std::string& rootType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& filename)\n {\n loadModel (robot, 0, \"\", rootType,\n makeModelPath(package, \"urdf\", filename), \"\");\n }\n\n template \n void loadModel (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n const std::string& prefix,\n const std::string& rootType,\n const std::string& urdfPath,\n const std::string& srdfPath)\n {\n if (baseJoint != 0)\n throw std::invalid_argument (\"Only appending robots at the world is supported.\");\n std::vector baseDirs = se3::rosPaths();\n\n std::string urdfFileName = se3::retrieveResourcePath(urdfPath, baseDirs);\n if (urdfFileName == \"\") {\n throw std::invalid_argument (std::string (\"Unable to retrieve \") +\n urdfPath);\n }\n Model& model = robot->model();\n const JointIndex idFirstJoint = model.joints.size();\n const FrameIndex idFirstFrame = model.frames.size();\n if (rootType == \"anchor\")\n se3::urdf::buildModel(urdfFileName, model, verbose);\n else\n se3::urdf::buildModel(urdfFileName, buildJoint(rootType), model, verbose);\n robot->createData();\n\n hppDout (notice, \"Finished parsing URDF file.\");\n\n GeomModel geomModel;\n\n se3::urdf::buildGeom(model, urdfFileName, se3::COLLISION, geomModel, baseDirs);\n geomModel.addAllCollisionPairs();\n\n if (LoadSRDF) {\n std::string srdfFileName = se3::retrieveResourcePath(srdfPath, baseDirs);\n if (srdfFileName == \"\") {\n throw std::invalid_argument (std::string (\"Unable to retrieve \") +\n srdfPath);\n }\n se3::srdf::removeCollisionPairsFromSrdf\n (model, geomModel, srdfFileName, verbose);\n }\n\n if (!prefix.empty()) setPrefix(prefix, model, geomModel, idFirstJoint, idFirstFrame);\n\n \/\/ Update root joint bounds\n assert((rootType == \"anchor\")\n || (model.names[idFirstJoint] == prefix + \"root_joint\"));\n setRootJointBounds(model, idFirstJoint, rootType);\n\n se3::appendGeometryModel(robot->geomModel(), geomModel);\n robot->createGeomData();\n\n hppDout (notice, \"Finished parsing SRDF file.\");\n }\n\n template void loadModel (const DevicePtr_t&, const JointIndex&, const std::string&, const std::string&, const std::string&, const std::string&);\n template void loadModel(const DevicePtr_t&, const JointIndex&, const std::string&, const std::string&, const std::string&, const std::string&);\n } \/\/ end of namespace urdf.\n } \/\/ end of namespace pinocchio.\n} \/\/ end of namespace hpp.\nRoot joint type can be prismatic_x or prismatic_y\/\/ Copyright (c) 2016, Joseph Mirabel\n\/\/ Authors: Joseph Mirabel (joseph.mirabel@laas.fr)\n\/\/\n\/\/ This file is part of hpp-pinocchio.\n\/\/ hpp-pinocchio is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-pinocchio is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-pinocchio. If not, see .\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\nnamespace hpp {\n namespace pinocchio {\n namespace urdf {\n using se3::FrameIndex;\n\n namespace {\n#ifdef HPP_DEBUG\n const bool verbose = true;\n#else\n const bool verbose = false;\n#endif\n\n JointPtr_t findSpecialJoint (const HumanoidRobotPtr_t& robot, const std::string& linkName)\n {\n return robot->getJointByBodyName (linkName);\n }\n\n void setSpecialJoints (const HumanoidRobotPtr_t& robot, const std::string& prefix) {\n try {\n robot->waist (robot->getJointByName(prefix + \"root_joint\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No waist joint found\");\n }\n try {\n robot->chest (findSpecialJoint (robot, prefix + \"chest\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No chest joint found\");\n }\n try {\n robot->leftWrist (findSpecialJoint (robot, prefix + \"l_wrist\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No left wrist joint found\");\n }\n try {\n robot->rightWrist (findSpecialJoint (robot, prefix + \"r_wrist\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No right wrist joint found\");\n }\n try {\n robot->leftAnkle (findSpecialJoint (robot, prefix + \"l_ankle\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No left ankle joint found\");\n }\n try {\n robot->rightAnkle (findSpecialJoint (robot, prefix + \"r_ankle\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No right ankle joint found\");\n }\n try {\n robot->gazeJoint (findSpecialJoint (robot, prefix + \"gaze\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No gaze joint found\");\n }\n }\n\n void fillGaze (const HumanoidRobotPtr_t robot)\n {\n vector3_t dir, origin;\n \/\/ Gaze direction is defined by the gaze joint local\n \/\/ orientation.\n dir[0] = 1;\n dir[1] = 0;\n dir[2] = 0;\n \/\/ Gaze position should is defined by the gaze joint local\n \/\/ origin.\n origin[0] = 0;\n origin[1] = 0;\n origin[2] = 0;\n robot->gaze (dir, origin);\n }\n\n se3::JointModelVariant buildJoint (const std::string& type)\n {\n if (type == \"freeflyer\") return se3::JointModelFreeFlyer();\n else if (type == \"planar\") return se3::JointModelPlanar();\n else if (type == \"prismatic_x\") return se3::JointModelPrismatic<0>();\n else if (type == \"prismatic_y\") return se3::JointModelPrismatic<1>();\n else throw std::invalid_argument\n (\"Root joint type is currently not available.\");\n }\n\n void setPrefix (const std::string& prefix,\n Model& model, GeomModel& geomModel,\n const JointIndex& idFirstJoint,\n const FrameIndex& idFirstFrame)\n {\n for (JointIndex i = idFirstJoint; i < model.joints.size(); ++i) {\n model.names[i] = prefix + model.names[i];\n }\n for (FrameIndex i = idFirstFrame; i < model.frames.size(); ++i) {\n se3::Frame& f = model.frames[i];\n f.name = prefix + f.name;\n }\n BOOST_FOREACH(se3::GeometryObject& go, geomModel.geometryObjects) {\n go.name = prefix + go.name;\n }\n }\n\n void setRootJointBounds(Model& model,\n const JointIndex& rtIdx,\n const std::string& rootType)\n {\n value_type b = std::numeric_limits::infinity();\n if (rootType == \"freeflyer\") {\n const std::size_t idx = model.joints[rtIdx].idx_q();\n model.upperPositionLimit.segment<3>(idx).setConstant(+b);\n model.lowerPositionLimit.segment<3>(idx).setConstant(-b);\n \/\/ Quaternion bounds\n b = 1.01;\n const size_type quat_idx = idx + 3;\n model.upperPositionLimit.segment<4>(quat_idx).setConstant(+b);\n model.lowerPositionLimit.segment<4>(quat_idx).setConstant(-b);\n } else if (rootType == \"planar\") {\n const std::size_t idx = model.joints[rtIdx].idx_q();\n model.upperPositionLimit.segment<2>(idx).setConstant(+b);\n model.lowerPositionLimit.segment<2>(idx).setConstant(-b);\n \/\/ Unit complex bounds\n b = 1.01;\n const size_type cplx_idx = idx + 2;\n model.upperPositionLimit.segment<2>(cplx_idx).setConstant(+b);\n model.lowerPositionLimit.segment<2>(cplx_idx).setConstant(-b);\n }\n }\n\n std::string makeModelPath (const std::string& package,\n const std::string& type,\n const std::string& modelName,\n const std::string& suffix = \"\")\n {\n std::stringstream ss;\n ss << \"package:\/\/\" << package << \"\/\" << type << \"\/\" << modelName << suffix << \".\" << type;\n return ss.str();\n }\n }\n\n void loadRobotModel (const DevicePtr_t& robot,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& modelName,\n\t\t\t const std::string& urdfSuffix,\n const std::string& srdfSuffix)\n {\n loadModel (robot, 0, \"\", rootJointType,\n makeModelPath(package, \"urdf\", modelName, urdfSuffix),\n makeModelPath(package, \"srdf\", modelName, srdfSuffix));\n }\n\n void loadRobotModel (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n\t\t\t const std::string& prefix,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& modelName,\n\t\t\t const std::string& urdfSuffix,\n const std::string& srdfSuffix)\n {\n loadModel (robot, baseJoint, \n (prefix.empty() ? \"\" : prefix + \"\/\"),\n rootJointType,\n makeModelPath(package, \"urdf\", modelName, urdfSuffix),\n makeModelPath(package, \"srdf\", modelName, srdfSuffix));\n }\n\n void loadHumanoidModel (const HumanoidRobotPtr_t& robot,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& modelName,\n\t\t\t const std::string& urdfSuffix,\n\t\t\t const std::string& srdfSuffix)\n {\n loadRobotModel(robot, rootJointType, package, modelName, urdfSuffix, srdfSuffix);\n\n\t\/\/ Look for special joints and attach them to the model.\n\tsetSpecialJoints (robot, \"\");\n\t\/\/ Fill gaze position and direction.\n\tfillGaze (robot);\n }\n\n void loadHumanoidModel (const HumanoidRobotPtr_t& robot,\n const JointIndex& baseJoint,\n\t\t\t const std::string& prefix,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& modelName,\n\t\t\t const std::string& urdfSuffix,\n\t\t\t const std::string& srdfSuffix)\n {\n loadRobotModel(robot, baseJoint, prefix, rootJointType, package, modelName, urdfSuffix, srdfSuffix);\n\n\t\/\/ Look for special joints and attach them to the model.\n\tsetSpecialJoints (robot, prefix);\n\t\/\/ Fill gaze position and direction.\n\tfillGaze (robot);\n }\n\n void loadUrdfModel (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n const std::string& prefix,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& filename)\n {\n loadModel (robot, baseJoint,\n (prefix.empty() ? \"\" : prefix + \"\/\"),\n rootJointType,\n makeModelPath(package, \"urdf\", filename), \"\");\n }\n\n void loadUrdfModel (const DevicePtr_t& robot,\n\t\t\t const std::string& rootType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& filename)\n {\n loadModel (robot, 0, \"\", rootType,\n makeModelPath(package, \"urdf\", filename), \"\");\n }\n\n template \n void loadModel (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n const std::string& prefix,\n const std::string& rootType,\n const std::string& urdfPath,\n const std::string& srdfPath)\n {\n if (baseJoint != 0)\n throw std::invalid_argument (\"Only appending robots at the world is supported.\");\n std::vector baseDirs = se3::rosPaths();\n\n std::string urdfFileName = se3::retrieveResourcePath(urdfPath, baseDirs);\n if (urdfFileName == \"\") {\n throw std::invalid_argument (std::string (\"Unable to retrieve \") +\n urdfPath);\n }\n Model& model = robot->model();\n const JointIndex idFirstJoint = model.joints.size();\n const FrameIndex idFirstFrame = model.frames.size();\n if (rootType == \"anchor\")\n se3::urdf::buildModel(urdfFileName, model, verbose);\n else\n se3::urdf::buildModel(urdfFileName, buildJoint(rootType), model, verbose);\n robot->createData();\n\n hppDout (notice, \"Finished parsing URDF file.\");\n\n GeomModel geomModel;\n\n se3::urdf::buildGeom(model, urdfFileName, se3::COLLISION, geomModel, baseDirs);\n geomModel.addAllCollisionPairs();\n\n if (LoadSRDF) {\n std::string srdfFileName = se3::retrieveResourcePath(srdfPath, baseDirs);\n if (srdfFileName == \"\") {\n throw std::invalid_argument (std::string (\"Unable to retrieve \") +\n srdfPath);\n }\n se3::srdf::removeCollisionPairsFromSrdf\n (model, geomModel, srdfFileName, verbose);\n }\n\n if (!prefix.empty()) setPrefix(prefix, model, geomModel, idFirstJoint, idFirstFrame);\n\n \/\/ Update root joint bounds\n assert((rootType == \"anchor\")\n || (model.names[idFirstJoint] == prefix + \"root_joint\"));\n setRootJointBounds(model, idFirstJoint, rootType);\n\n se3::appendGeometryModel(robot->geomModel(), geomModel);\n robot->createGeomData();\n\n hppDout (notice, \"Finished parsing SRDF file.\");\n }\n\n template void loadModel (const DevicePtr_t&, const JointIndex&, const std::string&, const std::string&, const std::string&, const std::string&);\n template void loadModel(const DevicePtr_t&, const JointIndex&, const std::string&, const std::string&, const std::string&, const std::string&);\n } \/\/ end of namespace urdf.\n } \/\/ end of namespace pinocchio.\n} \/\/ end of namespace hpp.\n<|endoftext|>"} {"text":"\/* libwps\n * Copyright (C) 2006 Ariya Hidayat (ariya@kde.org)\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the \n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, \n * Boston, MA 02111-1301 USA\n *\n * For further information visit http:\/\/libwps.sourceforge.net\n *\/\n\n#include \"WPSStreamImplementation.h\"\n#include \"WPSOLEStream.h\"\n#include \"libwps.h\"\n\n#include \n#include \n#include \n\nusing namespace libwps;\n\nclass WPSFileStreamPrivate\n{\npublic:\n\tWPSFileStreamPrivate();\n\t~WPSFileStreamPrivate();\n\tstd::fstream file;\n\tstd::stringstream buffer;\n\tlong streamSize;\n\tuint8_t *buf;\n};\n\nclass WPSMemoryStreamPrivate\n{\npublic:\n\tWPSMemoryStreamPrivate(const std::string str);\n\t~WPSMemoryStreamPrivate();\n\tstd::stringstream buffer;\n\tlong streamSize;\n\tuint8_t *buf;\n};\n\nWPSFileStreamPrivate::WPSFileStreamPrivate() :\n\tfile(),\n\tbuffer(std::ios::binary | std::ios::in | std::ios::out),\n\tstreamSize(0),\n\tbuf(0)\n{\t\n}\n\nWPSFileStreamPrivate::~WPSFileStreamPrivate()\n{\n\tif (buf)\n\t\tdelete [] buf;\n}\n\nWPSMemoryStreamPrivate::WPSMemoryStreamPrivate(const std::string str) :\n\tbuffer(str, std::ios::binary | std::ios::in),\n\tstreamSize(0),\n\tbuf(0)\n{\n}\n\nWPSMemoryStreamPrivate::~WPSMemoryStreamPrivate()\n{\n\tif (buf)\n\t\tdelete [] buf;\n}\n\nWPSFileStream::WPSFileStream(const char* filename)\n{\n\td = new WPSFileStreamPrivate;\n\t\n\td->file.open( filename, std::ios::binary | std::ios::in );\n\td->file.seekg( 0, std::ios::end );\n\td->streamSize = (d->file.good() ? (long)d->file.tellg() : -1L);\n\td->file.seekg( 0, std::ios::beg );\n}\n\nWPSFileStream::~WPSFileStream()\n{\n\tdelete d;\n}\n\nconst uint8_t *WPSFileStream::read(size_t numBytes, size_t &numBytesRead)\n{\n\tnumBytesRead = 0;\n\t\n\tif (numBytes < 0 || atEOS())\n\t{\n\t\treturn 0;\n\t}\n\n\tlong curpos = d->file.tellg();\n\tif ( (curpos + numBytes < curpos) \/*overflow*\/ ||\n\t\t(curpos + numBytes > d->streamSize) ) \/*reading more than available*\/\n\t{\n\t\tnumBytes = d->streamSize - curpos;\n\t}\n\n\tif (d->buf)\n\t\tdelete [] d->buf;\n\td->buf = new uint8_t[numBytes];\n\n\tif(d->file.good())\n\t{\n\t\td->file.read((char *)(d->buf), numBytes); \n\t\tnumBytesRead = (long)d->file.tellg() - curpos;\n\t}\n\t\n\treturn d->buf;\n}\n\nlong WPSFileStream::tell()\n{\n\treturn d->file.good() ? (long)d->file.tellg() : -1L;\n}\n\nint WPSFileStream::seek(long offset, WPX_SEEK_TYPE seekType)\n{\n\tif (seekType == WPX_SEEK_SET)\n\t{\n\t\tif (offset < 0)\n\t\t\toffset = 0;\n\t\tif (offset > d->streamSize)\n\t\t\toffset = d->streamSize;\n\t}\n\n\tif (seekType == WPX_SEEK_CUR)\n\t{\n\t\tif (tell() + offset < 0)\n\t\t\toffset = -tell();\n\t\tif (tell() + offset > d->streamSize)\n\t\t\toffset = d->streamSize - tell();\n\t}\n\n\tif(d->file.good())\n\t{\n\t\td->file.seekg(offset, ((seekType == WPX_SEEK_SET) ? std::ios::beg : std::ios::cur));\n\t\treturn (int) ((long)d->file.tellg() == -1);\n\t}\n\telse\n\t\treturn -1;\n}\n\nbool WPSFileStream::atEOS()\n{\n\treturn (d->file.tellg() >= d->streamSize);\n}\n\nbool WPSFileStream::isOLEStream()\n{\n\tif (d->buffer.str().empty())\n\t\td->buffer << d->file.rdbuf();\n\tStorage tmpStorage( d->buffer );\n\tif (tmpStorage.isOLEStream())\n\t{\n\t\tseek(0, WPX_SEEK_SET);\n\t\treturn true;\n\t}\n\tseek(0, WPX_SEEK_SET);\n\treturn false;\n}\n\nWPXInputStream* WPSFileStream::getDocumentOLEStream(const char * name)\n{\n\tif (d->buffer.str().empty())\n\t\td->buffer << d->file.rdbuf();\n\tStorage *tmpStorage = new Storage( d->buffer );\n\tStream tmpStream( tmpStorage, name );\n\tif (!tmpStorage || (tmpStorage->result() != Storage::Ok) || !tmpStream.size())\n\t{\n\t\tif (tmpStorage)\n\t\t\tdelete tmpStorage;\n\t\treturn (WPSInputStream*)0;\n\t}\n\t\n\tif (d->buf)\n\t\tdelete [] d->buf;\n\td->buf = new uint8_t[tmpStream.size()];\n\tunsigned long tmpLength;\n\ttmpLength = tmpStream.read((unsigned char *)(d->buf), tmpStream.size());\n\n\t\/\/ sanity check\n\tif (tmpLength > tmpStream.size() || tmpLength < tmpStream.size())\n\t\/* something went wrong here and we do not trust the\n\t resulting buffer *\/\n\t{\n\t\tif (tmpStorage)\n\t\t\tdelete tmpStorage;\n\t\treturn (WPSInputStream*)0;\n\t}\n\n\tdelete tmpStorage;\n\treturn new WPSMemoryStream((const char *)(d->buf), tmpLength);\n}\n\nWPXInputStream* WPSFileStream::getDocumentOLEStream()\n{\n\treturn getDocumentOLEStream(\"PerfectOffice_MAIN\");\n}\n\nWPSMemoryStream::WPSMemoryStream(const char *data, const unsigned int dataSize)\n{\n\td = new WPSMemoryStreamPrivate(std::string(data, dataSize));\n\td->buffer.seekg( 0, std::ios::end );\n\td->streamSize = (d->buffer.good() ? (long)d->buffer.tellg() : -1L);\n\td->buffer.seekg( 0, std::ios::beg );\n}\n\nWPSMemoryStream::~WPSMemoryStream()\n{\n\tdelete d;\n}\n\nconst uint8_t *WPSMemoryStream::read(size_t numBytes, size_t &numBytesRead)\n{\n\tnumBytesRead = 0;\n\t\n\tif (numBytes < 0 || atEOS())\n\t{\n\t\treturn 0;\n\t}\n\n\tlong curpos = d->buffer.tellg();\n\tif ( (curpos + numBytes < curpos) \/*overflow*\/ ||\n\t\t(curpos + numBytes > d->streamSize) ) \/*reading more than available*\/\n\t{\n\t\tnumBytes = d->streamSize - curpos;\n\t}\n\n\tif (d->buf)\n\t\tdelete [] d->buf;\n\td->buf = new uint8_t[numBytes];\n\n\tif(d->buffer.good())\n\t{\n\t\td->buffer.read((char *)(d->buf), numBytes); \n\t\tnumBytesRead = (long)d->buffer.tellg() - curpos;\n\t}\n\t\n\treturn d->buf;\n}\n\nlong WPSMemoryStream::tell()\n{\n\treturn d->buffer.good() ? (long)d->buffer.tellg() : -1L;\n}\n\nint WPSMemoryStream::seek(long offset, WPX_SEEK_TYPE seekType)\n{\n\tif (seekType == WPX_SEEK_SET)\n\t{\n\t\tif (offset < 0)\n\t\t\toffset = 0;\n\t\tif (offset > d->streamSize)\n\t\t\toffset = d->streamSize;\n\t}\n\n\tif (seekType == WPX_SEEK_CUR)\n\t{\n\t\tif (tell() + offset < 0)\n\t\t\toffset = -tell();\n\t\tif (tell() + offset > d->streamSize)\n\t\t\toffset = d->streamSize - tell();\n\t}\n\n\tif(d->buffer.good())\n\t{\n\t\td->buffer.seekg(offset, ((seekType == WPX_SEEK_SET) ? std::ios::beg : std::ios::cur));\n\t\treturn (int) ( (long)d->buffer.tellg() == -1);\n\t}\n\telse\n\t\treturn -1;\n}\n\nbool WPSMemoryStream::atEOS()\n{\n\treturn (d->buffer.tellg() >= d->streamSize);\n}\n\nbool WPSMemoryStream::isOLEStream()\n{\n\tStorage tmpStorage( d->buffer );\n\tif (tmpStorage.isOLEStream())\n\t{\n\t\tseek(0, WPX_SEEK_SET);\n\t\treturn true;\n\t}\n\tseek(0, WPX_SEEK_SET);\n\treturn false;\n}\n\nWPXInputStream* WPSMemoryStream::getDocumentOLEStream(const char * name)\n{\n\tStorage *tmpStorage = new Storage( d->buffer );\n\tStream tmpStream( tmpStorage, name );\n\tif (!tmpStorage || (tmpStorage->result() != Storage::Ok) || !tmpStream.size())\n\t{\n\t\tif (tmpStorage)\n\t\t\tdelete tmpStorage;\n\t\treturn (WPSInputStream*)0;\n\t}\n\n\tif (d->buf)\n\t\tdelete [] d->buf;\n\td->buf = new uint8_t[tmpStream.size()];\n\tunsigned long tmpLength;\n\ttmpLength = tmpStream.read((unsigned char *)(d->buf), tmpStream.size());\n\n\t\/\/ sanity check\n\tif (tmpLength > tmpStream.size() || tmpLength < tmpStream.size())\n\t\/* something went wrong here and we do not trust the\n\t resulting buffer *\/\n\t{\n\t\tif (tmpStorage)\n\t\t\tdelete tmpStorage;\n\t\treturn (WPSInputStream*)0;\n\t}\n\n\tdelete tmpStorage;\n\treturn new WPSMemoryStream((const char *)(d->buf), tmpLength);\n}\n\nWPXInputStream* WPSMemoryStream::getDocumentOLEStream()\n{\n\treturn getDocumentOLEStream(\"PerfectOffice_MAIN\");\n}\nputting belts and braces around the stream class (integers, integers, integers)\/* libwps\n * Copyright (C) 2006 Ariya Hidayat (ariya@kde.org)\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the \n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, \n * Boston, MA 02111-1301 USA\n *\n * For further information visit http:\/\/libwps.sourceforge.net\n *\/\n\n#include \"WPSStreamImplementation.h\"\n#include \"WPSOLEStream.h\"\n#include \"libwps.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace libwps;\n\nclass WPSFileStreamPrivate\n{\npublic:\n\tWPSFileStreamPrivate();\n\t~WPSFileStreamPrivate();\n\tstd::fstream file;\n\tstd::stringstream buffer;\n\tunsigned long streamSize;\n\tuint8_t *buf;\n};\n\nclass WPSMemoryStreamPrivate\n{\npublic:\n\tWPSMemoryStreamPrivate(const std::string str);\n\t~WPSMemoryStreamPrivate();\n\tstd::stringstream buffer;\n\tunsigned long streamSize;\n\tuint8_t *buf;\n};\n\nWPSFileStreamPrivate::WPSFileStreamPrivate() :\n\tfile(),\n\tbuffer(std::ios::binary | std::ios::in | std::ios::out),\n\tstreamSize(0),\n\tbuf(0)\n{\t\n}\n\nWPSFileStreamPrivate::~WPSFileStreamPrivate()\n{\n\tif (buf)\n\t\tdelete [] buf;\n}\n\nWPSMemoryStreamPrivate::WPSMemoryStreamPrivate(const std::string str) :\n\tbuffer(str, std::ios::binary | std::ios::in),\n\tstreamSize(0),\n\tbuf(0)\n{\n}\n\nWPSMemoryStreamPrivate::~WPSMemoryStreamPrivate()\n{\n\tif (buf)\n\t\tdelete [] buf;\n}\n\nWPSFileStream::WPSFileStream(const char* filename)\n{\n\td = new WPSFileStreamPrivate;\n\t\n\td->file.open( filename, std::ios::binary | std::ios::in );\n\td->file.seekg( 0, std::ios::end );\n\td->streamSize = (d->file.good() ? (unsigned long)d->file.tellg() : (unsigned long)-1L);\n\tif (d->streamSize == (unsigned long)-1) \/\/ tellg() returned ERROR\n\t\td->streamSize = 0;\n\td->file.seekg( 0, std::ios::beg );\n}\n\nWPSFileStream::~WPSFileStream()\n{\n\tdelete d;\n}\n\nconst uint8_t *WPSFileStream::read(size_t numBytes, size_t &numBytesRead)\n{\n\tnumBytesRead = 0;\n\t\n\tif (numBytes < 0 || atEOS() || numBytes > (std::numeric_limits::max)()\/2)\n\t\treturn 0;\n\n\tunsigned long curpos = d->file.tellg();\n\tif (curpos == (unsigned long)-1) \/\/ tellg() returned ERROR\n\t\treturn 0;\n\n\tif ( (curpos + numBytes < curpos) \/*overflow*\/ ||\n\t\t(curpos + numBytes > d->streamSize) ) \/*reading more than available*\/\n\t{\n\t\tnumBytes = d->streamSize - curpos;\n\t}\n\n\tif (d->buf)\n\t\tdelete [] d->buf;\n\td->buf = new uint8_t[numBytes];\n\n\tif(d->file.good())\n\t{\n\t\td->file.read((char *)(d->buf), numBytes); \n\t\tnumBytesRead = (long)d->file.tellg() - curpos;\n\t}\n\t\n\treturn d->buf;\n}\n\nlong WPSFileStream::tell()\n{\n\treturn d->file.good() ? (long)d->file.tellg() : -1L;\n}\n\nint WPSFileStream::seek(long offset, WPX_SEEK_TYPE seekType)\n{\n\tif (seekType == WPX_SEEK_SET)\n\t{\n\t\tif (offset < 0)\n\t\t\toffset = 0;\n\t\tif (offset > d->streamSize)\n\t\t\toffset = d->streamSize;\n\t}\n\n\tif (seekType == WPX_SEEK_CUR)\n\t{\n\t\tif (tell() + offset < 0)\n\t\t\toffset = -tell();\n\t\tif (tell() + offset > d->streamSize)\n\t\t\toffset = d->streamSize - tell();\n\t}\n\n\tif(d->file.good())\n\t{\n\t\td->file.seekg(offset, ((seekType == WPX_SEEK_SET) ? std::ios::beg : std::ios::cur));\n\t\treturn (int) ((long)d->file.tellg() == -1);\n\t}\n\telse\n\t\treturn -1;\n}\n\nbool WPSFileStream::atEOS()\n{\n\treturn (d->file.tellg() >= d->streamSize);\n}\n\nbool WPSFileStream::isOLEStream()\n{\n\tif (d->buffer.str().empty())\n\t\td->buffer << d->file.rdbuf();\n\tStorage tmpStorage( d->buffer );\n\tif (tmpStorage.isOLEStream())\n\t{\n\t\tseek(0, WPX_SEEK_SET);\n\t\treturn true;\n\t}\n\tseek(0, WPX_SEEK_SET);\n\treturn false;\n}\n\nWPXInputStream* WPSFileStream::getDocumentOLEStream(const char * name)\n{\n\tif (d->buffer.str().empty())\n\t\td->buffer << d->file.rdbuf();\n\tStorage *tmpStorage = new Storage( d->buffer );\n\tStream tmpStream( tmpStorage, name );\n\tif (!tmpStorage || (tmpStorage->result() != Storage::Ok) || !tmpStream.size())\n\t{\n\t\tif (tmpStorage)\n\t\t\tdelete tmpStorage;\n\t\treturn (WPSInputStream*)0;\n\t}\n\t\n\tif (d->buf)\n\t\tdelete [] d->buf;\n\td->buf = new uint8_t[tmpStream.size()];\n\tunsigned long tmpLength;\n\ttmpLength = tmpStream.read((unsigned char *)(d->buf), tmpStream.size());\n\n\t\/\/ sanity check\n\tif (tmpLength > tmpStream.size() || tmpLength < tmpStream.size())\n\t\/* something went wrong here and we do not trust the\n\t resulting buffer *\/\n\t{\n\t\tif (tmpStorage)\n\t\t\tdelete tmpStorage;\n\t\treturn (WPSInputStream*)0;\n\t}\n\n\tdelete tmpStorage;\n\treturn new WPSMemoryStream((const char *)(d->buf), tmpLength);\n}\n\nWPXInputStream* WPSFileStream::getDocumentOLEStream()\n{\n\treturn getDocumentOLEStream(\"PerfectOffice_MAIN\");\n}\n\nWPSMemoryStream::WPSMemoryStream(const char *data, const unsigned int dataSize)\n{\n\td = new WPSMemoryStreamPrivate(std::string(data, dataSize));\n\td->buffer.seekg( 0, std::ios::end );\n\td->streamSize = (d->buffer.good() ? (unsigned long)d->buffer.tellg() : (unsigned long)-1L);\n\tif (d->streamSize == (unsigned long)-1L)\n\t\td->streamSize = 0;\n\td->buffer.seekg( 0, std::ios::beg );\n}\n\nWPSMemoryStream::~WPSMemoryStream()\n{\n\tdelete d;\n}\n\nconst uint8_t *WPSMemoryStream::read(size_t numBytes, size_t &numBytesRead)\n{\n\tnumBytesRead = 0;\n\t\n\tif (numBytes < 0 || atEOS() || numBytes > (std::numeric_limits::max)()\/2)\n\t{\n\t\treturn 0;\n\t}\n\n\tunsigned long curpos = d->buffer.tellg();\n\tif (curpos == (unsigned long)-1) \/\/tellg() returned ERROR\n\t\treturn 0;\n\n\tif ( (curpos + numBytes < curpos) \/*overflow*\/ ||\n\t\t(curpos + numBytes > d->streamSize) ) \/*reading more than available*\/\n\t{\n\t\tnumBytes = d->streamSize - curpos;\n\t}\n\n\tif (d->buf)\n\t\tdelete [] d->buf;\n\td->buf = new uint8_t[numBytes];\n\n\tif(d->buffer.good())\n\t{\n\t\td->buffer.read((char *)(d->buf), numBytes); \n\t\tnumBytesRead = (long)d->buffer.tellg() - curpos;\n\t}\n\t\n\treturn d->buf;\n}\n\nlong WPSMemoryStream::tell()\n{\n\treturn d->buffer.good() ? (long)d->buffer.tellg() : -1L;\n}\n\nint WPSMemoryStream::seek(long offset, WPX_SEEK_TYPE seekType)\n{\n\tif (seekType == WPX_SEEK_SET)\n\t{\n\t\tif (offset < 0)\n\t\t\toffset = 0;\n\t\tif (offset > d->streamSize)\n\t\t\toffset = d->streamSize;\n\t}\n\n\tif (seekType == WPX_SEEK_CUR)\n\t{\n\t\tif (tell() + offset < 0)\n\t\t\toffset = -tell();\n\t\tif (tell() + offset > d->streamSize)\n\t\t\toffset = d->streamSize - tell();\n\t}\n\n\tif(d->buffer.good())\n\t{\n\t\td->buffer.seekg(offset, ((seekType == WPX_SEEK_SET) ? std::ios::beg : std::ios::cur));\n\t\treturn (int) ( (long)d->buffer.tellg() == -1);\n\t}\n\telse\n\t\treturn -1;\n}\n\nbool WPSMemoryStream::atEOS()\n{\n\treturn (d->buffer.tellg() >= d->streamSize);\n}\n\nbool WPSMemoryStream::isOLEStream()\n{\n\tStorage tmpStorage( d->buffer );\n\tif (tmpStorage.isOLEStream())\n\t{\n\t\tseek(0, WPX_SEEK_SET);\n\t\treturn true;\n\t}\n\tseek(0, WPX_SEEK_SET);\n\treturn false;\n}\n\nWPXInputStream* WPSMemoryStream::getDocumentOLEStream(const char * name)\n{\n\tStorage *tmpStorage = new Storage( d->buffer );\n\tStream tmpStream( tmpStorage, name );\n\tif (!tmpStorage || (tmpStorage->result() != Storage::Ok) || !tmpStream.size())\n\t{\n\t\tif (tmpStorage)\n\t\t\tdelete tmpStorage;\n\t\treturn (WPSInputStream*)0;\n\t}\n\n\tif (d->buf)\n\t\tdelete [] d->buf;\n\td->buf = new uint8_t[tmpStream.size()];\n\tunsigned long tmpLength;\n\ttmpLength = tmpStream.read((unsigned char *)(d->buf), tmpStream.size());\n\n\t\/\/ sanity check\n\tif (tmpLength > tmpStream.size() || tmpLength < tmpStream.size())\n\t\/* something went wrong here and we do not trust the\n\t resulting buffer *\/\n\t{\n\t\tif (tmpStorage)\n\t\t\tdelete tmpStorage;\n\t\treturn (WPSInputStream*)0;\n\t}\n\n\tdelete tmpStorage;\n\treturn new WPSMemoryStream((const char *)(d->buf), tmpLength);\n}\n\nWPXInputStream* WPSMemoryStream::getDocumentOLEStream()\n{\n\treturn getDocumentOLEStream(\"PerfectOffice_MAIN\");\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) 2017 Nguyen Viet Giang. All rights reserved. *\/\n#include \"prereq.h\"\n\n#define ADB_API static\n#define WBY_STATIC\nextern \"C\" {\n#include \n}\n\n#include \n#include \n#include \n#include \n\nstatic void wby_init(\n struct wby_server*, const struct wby_config* c, wby_size* needed_memory)\n{\n *needed_memory = 128;\n CHECK_THAT(c->address, Catch::Equals(\"0.0.0.0\"));\n REQUIRE(c->port == 1969);\n}\n\nstatic int wby_start(struct wby_server*, void*)\n{\n \/\/ nop\n return 0;\n}\n\nstatic void wby_stop(struct wby_server*)\n{\n \/\/ nop\n}\n\nstatic void wby_update(struct wby_server*, int)\n{\n \/\/ TODO\n}\n\nstatic int wby_response_begin(\n struct wby_con*, int, int, const struct wby_header*, int)\n{\n \/\/ TODO\n return 0;\n}\n\nstatic void wby_response_end(struct wby_con*)\n{\n \/\/ TODO\n}\n\nstatic int wby_write(struct wby_con*, const void*, wby_size)\n{\n \/\/ TODO\n return 0;\n}\n\nTEST_CASE(\"db\")\n{\n enum { NUM_IDX_BITS = 4 };\n enum { NUM_GEN_BITS = 4 };\n\n aasm_t as;\n aasm_init(&as, &myalloc, NULL);\n REQUIRE(aasm_load(&as, NULL) == AERR_NONE);\n add_module(&as, \"mod_test\");\n aasm_module_push(&as, \"test_f\");\n aasm_emit(&as, ai_lsi(1969));\n aasm_emit(&as, ai_lsi(1970));\n aasm_emit(&as, ai_lsi(1971));\n aasm_emit(&as, ai_lsi(1972));\n aasm_emit(&as, ai_ret());\n aasm_pop(&as);\n aasm_save(&as);\n\n ascheduler_t s;\n\n REQUIRE(AERR_NONE ==\n ascheduler_init(&s, NUM_IDX_BITS, NUM_GEN_BITS, &myalloc, NULL));\n ascheduler_on_panic(&s, &on_panic, NULL);\n\n adb_t db;\n REQUIRE(AERR_NONE ==\n adb_init(&db, &myalloc, NULL, &s, \"0.0.0.0\", 1969, 1));\n\n REQUIRE(AERR_NONE ==\n aloader_add_chunk(&s.loader, as.chunk, as.chunk_size, NULL, NULL));\n REQUIRE(AERR_NONE == aloader_link(&s.loader, TRUE));\n\n aactor_t* a;\n REQUIRE(AERR_NONE == ascheduler_new_actor(&s, CSTACK_SZ, &a));\n any_find(a, \"mod_test\", \"test_f\");\n ascheduler_start(&s, a, 0);\n\n ascheduler_run_once(&s);\n adb_run_once(&db);\n\n adb_cleanup(&db);\n ascheduler_cleanup(&s);\n aasm_cleanup(&as);\n}\nfix wby mock\/* Copyright (c) 2017 Nguyen Viet Giang. All rights reserved. *\/\n#include \"prereq.h\"\n\n#define ADB_API static\n#define WBY_STATIC\nextern \"C\" {\n#include \n}\n\n#include \n#include \n#include \n#include \n\nstatic void wby_init(\n struct wby_server*, const struct wby_config* c, wby_size* needed_memory)\n{\n *needed_memory = 128;\n CHECK_THAT(c->address, Catch::Equals(\"0.0.0.0\"));\n REQUIRE(c->port == 1969);\n}\n\nstatic int wby_start(struct wby_server*, void*)\n{\n \/\/ nop\n return 0;\n}\n\nstatic void wby_stop(struct wby_server*)\n{\n \/\/ nop\n}\n\nstatic void wby_update(struct wby_server*, int)\n{\n \/\/ TODO\n}\n\nstatic int wby_response_begin(\n struct wby_con*, int, int, const struct wby_header*, int)\n{\n \/\/ TODO\n return 0;\n}\n\nstatic void wby_response_end(struct wby_con*)\n{\n \/\/ TODO\n}\n\nstatic int wby_write(struct wby_con*, const void*, wby_size)\n{\n \/\/ TODO\n return 0;\n}\n\nstatic struct wby_con* wby_conn(struct wby_server*, wby_size)\n{\n\t\/\/ TODO\n\treturn NULL;\n}\n\nstatic int wby_frame_begin(struct wby_con*, int)\n{\n\t\/\/ TODO\n\treturn 0;\n}\n\nstatic int wby_frame_end(struct wby_con*)\n{\n\t\/\/ TODO\n\treturn 0;\n}\n\nTEST_CASE(\"db\")\n{\n enum { NUM_IDX_BITS = 4 };\n enum { NUM_GEN_BITS = 4 };\n\n aasm_t as;\n aasm_init(&as, &myalloc, NULL);\n REQUIRE(aasm_load(&as, NULL) == AERR_NONE);\n add_module(&as, \"mod_test\");\n aasm_module_push(&as, \"test_f\");\n aasm_emit(&as, ai_lsi(1969));\n aasm_emit(&as, ai_lsi(1970));\n aasm_emit(&as, ai_lsi(1971));\n aasm_emit(&as, ai_lsi(1972));\n aasm_emit(&as, ai_ret());\n aasm_pop(&as);\n aasm_save(&as);\n\n ascheduler_t s;\n\n REQUIRE(AERR_NONE ==\n ascheduler_init(&s, NUM_IDX_BITS, NUM_GEN_BITS, &myalloc, NULL));\n ascheduler_on_panic(&s, &on_panic, NULL);\n\n adb_t db;\n REQUIRE(AERR_NONE ==\n adb_init(&db, &myalloc, NULL, &s, \"0.0.0.0\", 1969, 1));\n\n REQUIRE(AERR_NONE ==\n aloader_add_chunk(&s.loader, as.chunk, as.chunk_size, NULL, NULL));\n REQUIRE(AERR_NONE == aloader_link(&s.loader, TRUE));\n\n aactor_t* a;\n REQUIRE(AERR_NONE == ascheduler_new_actor(&s, CSTACK_SZ, &a));\n any_find(a, \"mod_test\", \"test_f\");\n ascheduler_start(&s, a, 0);\n\n ascheduler_run_once(&s);\n adb_run_once(&db);\n\n adb_cleanup(&db);\n ascheduler_cleanup(&s);\n aasm_cleanup(&as);\n}\n<|endoftext|>"} {"text":"Clear textures on creation for D3D because it does not<|endoftext|>"} {"text":"#include \"packettrain.h\"\n\n#include \n\nPacketTrain::PacketTrain(QObject *parent)\n: QObject(parent)\n, isInitialized(false)\n, packetCounter(0)\n{\n connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));\n\n timer.setInterval(100);\n}\n\nPacketTrain::~PacketTrain()\n{\n}\n\nbool PacketTrain::initialize(const PeerList &peers, bool master, QUdpSocket *socket)\n{\n if ( isInitialized )\n return false;\n\n if ( peers.isEmpty() ) {\n qDebug() << \"Peer list is empty, can't initialize packettrain test\";\n return false;\n }\n\n this->peers = peers;\n this->master = master;\n this->socket = socket;\n\n return (isInitialized=true);\n}\n\nvoid PacketTrain::uninitialize()\n{\n}\n\nbool PacketTrain::start()\n{\n qDebug() << Q_FUNC_INFO;\n\n \/\/ Master waits for incoming packets\n if ( master ) {\n return true;\n }\n\n \/\/ Clients start sending data now\n timer.start();\n\n return true;\n}\n\nbool PacketTrain::stop()\n{\n qDebug() << Q_FUNC_INFO;\n\n timer.stop();\n return true;\n}\n\nbool PacketTrain::isFinished() const\n{\n if ( master )\n return packetCounter > 100;\n else\n return !timer.isActive();\n}\n\nvoid PacketTrain::processDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port)\n{\n if ( master )\n ++packetCounter;\n\n qDebug() << Q_FUNC_INFO << host.toString() << port;\n}\n\nvoid PacketTrain::timeout()\n{\n if ( packetCounter++ > 100 ) {\n stop();\n return;\n }\n\n foreach(const Peer& peer, peers) {\n QByteArray data;\n data.resize(2500);\n data.fill('X');\n\n socket->writeDatagram(data, peer.host, peer.port);\n }\n}\nAllocate send buffer outside of the loop..#include \"packettrain.h\"\n\n#include \n\nPacketTrain::PacketTrain(QObject *parent)\n: QObject(parent)\n, isInitialized(false)\n, packetCounter(0)\n{\n connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));\n\n timer.setInterval(100);\n}\n\nPacketTrain::~PacketTrain()\n{\n}\n\nbool PacketTrain::initialize(const PeerList &peers, bool master, QUdpSocket *socket)\n{\n if ( isInitialized )\n return false;\n\n if ( peers.isEmpty() ) {\n qDebug() << \"Peer list is empty, can't initialize packettrain test\";\n return false;\n }\n\n this->peers = peers;\n this->master = master;\n this->socket = socket;\n\n return (isInitialized=true);\n}\n\nvoid PacketTrain::uninitialize()\n{\n}\n\nbool PacketTrain::start()\n{\n qDebug() << Q_FUNC_INFO;\n\n \/\/ Master waits for incoming packets\n if ( master ) {\n return true;\n }\n\n \/\/ Clients start sending data now\n timer.start();\n\n return true;\n}\n\nbool PacketTrain::stop()\n{\n qDebug() << Q_FUNC_INFO;\n\n timer.stop();\n return true;\n}\n\nbool PacketTrain::isFinished() const\n{\n if ( master )\n return packetCounter > 100;\n else\n return !timer.isActive();\n}\n\nvoid PacketTrain::processDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port)\n{\n if ( master )\n ++packetCounter;\n\n qDebug() << Q_FUNC_INFO << host.toString() << port;\n}\n\nvoid PacketTrain::timeout()\n{\n if ( packetCounter++ > 100 ) {\n stop();\n return;\n }\n\n QByteArray data;\n data.resize(2500);\n data.fill('X');\n\n foreach(const Peer& peer, peers) {\n socket->writeDatagram(data, peer.host, peer.port);\n }\n}\n<|endoftext|>"} {"text":"#pragma once\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace uvw {\n\n\nnamespace details {\n\n\nstruct IPv4 { };\nstruct IPv6 { };\n\n\ntemplate\nstruct IpTraits;\n\ntemplate<>\nstruct IpTraits {\n using Type = sockaddr_in;\n using AddrFuncType = int(*)(const char *, int, sockaddr_in *);\n using NameFuncType = int(*)(const sockaddr_in *, char *, std::size_t);\n static const AddrFuncType AddrFunc;\n static const NameFuncType NameFunc;\n};\n\ntemplate<>\nstruct IpTraits {\n using Type = sockaddr_in6;\n using AddrFuncType = int(*)(const char *, int, sockaddr_in6 *);\n using NameFuncType = int(*)(const sockaddr_in6 *, char *, std::size_t);\n static const AddrFuncType AddrFunc;\n static const NameFuncType NameFunc;\n};\n\nconst IpTraits::AddrFuncType IpTraits::AddrFunc = uv_ip4_addr;\nconst IpTraits::AddrFuncType IpTraits::AddrFunc = uv_ip6_addr;\nconst IpTraits::NameFuncType IpTraits::NameFunc = uv_ip4_name;\nconst IpTraits::NameFuncType IpTraits::NameFunc = uv_ip6_name;\n\n\n}\n\n\nstruct FileDescriptor {\n using Type = uv_file;\n\n constexpr FileDescriptor(Type desc): fd{desc} { }\n\n constexpr operator Type() const noexcept { return fd; }\n\nprivate:\n const Type fd;\n};\n\n\nstatic constexpr auto STDIN = FileDescriptor{0};\nstatic constexpr auto STDOUT = FileDescriptor{1};\nstatic constexpr auto STDERR = FileDescriptor{2};\n\n\n\/**\n * See Boost\/Mutant idiom:\n * https:\/\/en.wikibooks.org\/wiki\/More_C%2B%2B_Idioms\/Boost_mutant\n *\/\nstruct Addr { std::string ip; unsigned int port; };\nstruct WinSize { int width; int height; };\n\n\nusing TimeSpec = uv_timespec_t;\nusing Stat = uv_stat_t;\n\n\n}\nadded util Flags#pragma once\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace uvw {\n\n\nnamespace details {\n\n\nstruct IPv4 { };\nstruct IPv6 { };\n\n\ntemplate\nstruct IpTraits;\n\ntemplate<>\nstruct IpTraits {\n using Type = sockaddr_in;\n using AddrFuncType = int(*)(const char *, int, sockaddr_in *);\n using NameFuncType = int(*)(const sockaddr_in *, char *, std::size_t);\n static const AddrFuncType AddrFunc;\n static const NameFuncType NameFunc;\n};\n\ntemplate<>\nstruct IpTraits {\n using Type = sockaddr_in6;\n using AddrFuncType = int(*)(const char *, int, sockaddr_in6 *);\n using NameFuncType = int(*)(const sockaddr_in6 *, char *, std::size_t);\n static const AddrFuncType AddrFunc;\n static const NameFuncType NameFunc;\n};\n\nconst IpTraits::AddrFuncType IpTraits::AddrFunc = uv_ip4_addr;\nconst IpTraits::AddrFuncType IpTraits::AddrFunc = uv_ip6_addr;\nconst IpTraits::NameFuncType IpTraits::NameFunc = uv_ip4_name;\nconst IpTraits::NameFuncType IpTraits::NameFunc = uv_ip6_name;\n\n\n}\n\n\ntemplate\nclass Flags final {\n using InnerType = typename std::underlying_type::type;\n\n constexpr InnerType toInnerType(E flag) const noexcept { return static_cast(flag); }\n\npublic:\n using Type = InnerType;\n\n constexpr Flags(E flag) noexcept: flags{toInnerType(flag)} { }\n constexpr Flags(Type f): flags(f) { }\n\n constexpr Flags(const Flags &f) noexcept: flags{f.flags} { }\n constexpr Flags(Flags &&f) noexcept: flags{std::move(f.flags)} { }\n\n ~Flags() noexcept { static_assert(std::is_enum::value, \"!\"); }\n\n constexpr Flags operator|(const Flags& f) const noexcept { return Flags(flags | f.flags); }\n constexpr Flags operator|(E flag) const noexcept { return Flags(flags | toInnerType(flag)); }\n\n constexpr Flags operator&(const Flags& f) const noexcept { return Flags(flags & f.flags); }\n constexpr Flags operator&(E flag) const noexcept { return Flags(flags & toInnerType(flag)); }\n\n constexpr operator bool() const noexcept { return !(flags == InnerType{}); }\n constexpr operator Type() const noexcept { return flags; }\n\nprivate:\n InnerType flags;\n};\n\n\nstruct FileDescriptor {\n using Type = uv_file;\n\n constexpr FileDescriptor(Type desc): fd{desc} { }\n\n constexpr operator Type() const noexcept { return fd; }\n\nprivate:\n const Type fd;\n};\n\n\nstatic constexpr auto STDIN = FileDescriptor{0};\nstatic constexpr auto STDOUT = FileDescriptor{1};\nstatic constexpr auto STDERR = FileDescriptor{2};\n\n\n\/**\n * See Boost\/Mutant idiom:\n * https:\/\/en.wikibooks.org\/wiki\/More_C%2B%2B_Idioms\/Boost_mutant\n *\/\nstruct Addr { std::string ip; unsigned int port; };\nstruct WinSize { int width; int height; };\n\n\nusing TimeSpec = uv_timespec_t;\nusing Stat = uv_stat_t;\n\n\n}\n<|endoftext|>"} {"text":"change<|endoftext|>"} {"text":"\/*************************************************\n* X.509 Certificates Source File *\n* (C) 1999-2006 The Botan Project *\n*************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Botan {\n\n\/*************************************************\n* X509_Certificate Constructor *\n*************************************************\/\nX509_Certificate::X509_Certificate(DataSource& in) :\n X509_Object(in, \"CERTIFICATE\/X509 CERTIFICATE\")\n {\n self_signed = false;\n do_decode();\n }\n\n\/*************************************************\n* X509_Certificate Constructor *\n*************************************************\/\nX509_Certificate::X509_Certificate(const std::string& in) :\n X509_Object(in, \"CERTIFICATE\/X509 CERTIFICATE\")\n {\n self_signed = false;\n do_decode();\n }\n\n\/*************************************************\n* Decode the TBSCertificate data *\n*************************************************\/\nvoid X509_Certificate::force_decode()\n {\n u32bit version;\n BigInt serial_bn;\n AlgorithmIdentifier sig_algo_inner;\n X509_DN dn_issuer, dn_subject;\n X509_Time start, end;\n\n BER_Decoder tbs_cert(tbs_bits);\n\n tbs_cert.decode_optional(version, ASN1_Tag(0),\n ASN1_Tag(CONSTRUCTED | CONTEXT_SPECIFIC))\n .decode(serial_bn)\n .decode(sig_algo_inner)\n .decode(dn_issuer)\n .start_cons(SEQUENCE)\n .decode(start)\n .decode(end)\n .verify_end()\n .end_cons()\n .decode(dn_subject);\n\n if(version > 2)\n throw Decoding_Error(\"Unknown X.509 cert version \" + to_string(version));\n if(sig_algo != sig_algo_inner)\n throw Decoding_Error(\"Algorithm identifier mismatch\");\n\n self_signed = (dn_subject == dn_issuer);\n\n subject.add(dn_subject.contents());\n issuer.add(dn_issuer.contents());\n\n BER_Object public_key = tbs_cert.get_next_object();\n if(public_key.type_tag != SEQUENCE || public_key.class_tag != CONSTRUCTED)\n throw BER_Bad_Tag(\"X509_Certificate: Unexpected tag for public key\",\n public_key.type_tag, public_key.class_tag);\n\n MemoryVector v2_issuer_key_id, v2_subject_key_id;\n\n tbs_cert.decode_optional_string(v2_issuer_key_id, BIT_STRING, 1);\n tbs_cert.decode_optional_string(v2_subject_key_id, BIT_STRING, 2);\n\n BER_Object v3_exts_data = tbs_cert.get_next_object();\n if(v3_exts_data.type_tag == 3 &&\n v3_exts_data.class_tag == ASN1_Tag(CONSTRUCTED | CONTEXT_SPECIFIC))\n {\n Extensions extensions;\n\n BER_Decoder(v3_exts_data.value).decode(extensions).verify_end();\n\n extensions.contents_to(subject, issuer);\n }\n else if(v3_exts_data.type_tag != NO_OBJECT)\n throw BER_Bad_Tag(\"Unknown tag in X.509 cert\",\n v3_exts_data.type_tag, v3_exts_data.class_tag);\n\n if(tbs_cert.more_items())\n throw Decoding_Error(\"TBSCertificate has more items that expected\");\n\n subject.add(\"X509.Certificate.version\", version);\n subject.add(\"X509.Certificate.serial\", BigInt::encode(serial_bn));\n subject.add(\"X509.Certificate.start\", start.readable_string());\n subject.add(\"X509.Certificate.end\", end.readable_string());\n\n issuer.add(\"X509.Certificate.v2.key_id\", v2_issuer_key_id);\n subject.add(\"X509.Certificate.v2.key_id\", v2_subject_key_id);\n\n subject.add(\"X509.Certificate.public_key\",\n PEM_Code::encode(\n ASN1::put_in_sequence(public_key.value),\n \"PUBLIC KEY\"\n )\n );\n\n if(is_CA_cert() &&\n !subject.has_value(\"X509v3.BasicConstraints.path_constraint\"))\n {\n u32bit limit = (x509_version() < 3) ? NO_CERT_PATH_LIMIT : 0;\n subject.add(\"X509v3.BasicConstraints.path_constraint\", limit);\n }\n }\n\n\/*************************************************\n* Return the X.509 version in use *\n*************************************************\/\nu32bit X509_Certificate::x509_version() const\n {\n return (subject.get1_u32bit(\"X509.Certificate.version\") + 1);\n }\n\n\/*************************************************\n* Return the time this cert becomes valid *\n*************************************************\/\nstd::string X509_Certificate::start_time() const\n {\n return subject.get1(\"X509.Certificate.start\");\n }\n\n\/*************************************************\n* Return the time this cert becomes invalid *\n*************************************************\/\nstd::string X509_Certificate::end_time() const\n {\n return subject.get1(\"X509.Certificate.end\");\n }\n\n\/*************************************************\n* Return information about the subject *\n*************************************************\/\nstd::vector\nX509_Certificate::subject_info(const std::string& what) const\n {\n return subject.get(X509_DN::deref_info_field(what));\n }\n\n\/*************************************************\n* Return information about the issuer *\n*************************************************\/\nstd::vector\nX509_Certificate::issuer_info(const std::string& what) const\n {\n return issuer.get(X509_DN::deref_info_field(what));\n }\n\n\/*************************************************\n* Return the public key in this certificate *\n*************************************************\/\nX509_PublicKey* X509_Certificate::subject_public_key() const\n {\n DataSource_Memory source(subject.get1(\"X509.Certificate.public_key\"));\n return X509::load_key(source);\n }\n\n\/*************************************************\n* Check if the certificate is for a CA *\n*************************************************\/\nbool X509_Certificate::is_CA_cert() const\n {\n if(!subject.get1_u32bit(\"X509v3.BasicConstraints.is_ca\"))\n return false;\n if((constraints() & KEY_CERT_SIGN) || (constraints() == NO_CONSTRAINTS))\n return true;\n return false;\n }\n\n\/*************************************************\n* Return the path length constraint *\n*************************************************\/\nu32bit X509_Certificate::path_limit() const\n {\n return subject.get1_u32bit(\"X509v3.BasicConstraints.path_constraint\", 0);\n }\n\n\/*************************************************\n* Return the key usage constraints *\n*************************************************\/\nKey_Constraints X509_Certificate::constraints() const\n {\n return Key_Constraints(subject.get1_u32bit(\"X509v3.KeyUsage\", NO_CONSTRAINTS));\n }\n\n\/*************************************************\n* Return the list of extended key usage OIDs *\n*************************************************\/\nstd::vector X509_Certificate::ex_constraints() const\n {\n return subject.get(\"X509v3.ExtendedKeyUsage\");\n }\n\n\/*************************************************\n* Return the list of certificate policies *\n*************************************************\/\nstd::vector X509_Certificate::policies() const\n {\n return subject.get(\"X509v3.CertificatePolicies\");\n }\n\n\/*************************************************\n* Return the authority key id *\n*************************************************\/\nMemoryVector X509_Certificate::authority_key_id() const\n {\n return issuer.get1_memvec(\"X509v3.AuthorityKeyIdentifier\");\n }\n\n\/*************************************************\n* Return the subject key id *\n*************************************************\/\nMemoryVector X509_Certificate::subject_key_id() const\n {\n return subject.get1_memvec(\"X509v3.SubjectKeyIdentifier\");\n }\n\n\/*************************************************\n* Return the certificate serial number *\n*************************************************\/\nMemoryVector X509_Certificate::serial_number() const\n {\n return subject.get1_memvec(\"X509.Certificate.serial\");\n }\n\n\/*************************************************\n* Return the distinguished name of the issuer *\n*************************************************\/\nX509_DN X509_Certificate::issuer_dn() const\n {\n return create_dn(issuer);\n }\n\n\/*************************************************\n* Return the distinguished name of the subject *\n*************************************************\/\nX509_DN X509_Certificate::subject_dn() const\n {\n return create_dn(subject);\n }\n\n\/*************************************************\n* Compare two certificates for equality *\n*************************************************\/\nbool X509_Certificate::operator==(const X509_Certificate& other) const\n {\n return (sig == other.sig &&\n sig_algo == other.sig_algo &&\n self_signed == other.self_signed &&\n issuer == other.issuer &&\n subject == other.subject);\n }\n\n\/*************************************************\n* X.509 Certificate Comparison *\n*************************************************\/\nbool operator!=(const X509_Certificate& cert1, const X509_Certificate& cert2)\n {\n return !(cert1 == cert2);\n }\n\n\/*************************************************\n* Create and populate a X509_DN *\n*************************************************\/\nX509_DN create_dn(const Data_Store& info)\n {\n class DN_Matcher : public Data_Store::Matcher\n {\n public:\n bool operator()(const std::string& key, const std::string&) const\n {\n if(key.find(\"X520.\") != std::string::npos)\n return true;\n return false;\n }\n };\n\n std::multimap names\n = info.search_with(DN_Matcher());\n\n X509_DN dn;\n\n std::multimap::iterator j;\n for(j = names.begin(); j != names.end(); ++j)\n dn.add_attribute(j->first, j->second);\n\n return dn;\n }\n\n\/*************************************************\n* Create and populate an AlternativeName *\n*************************************************\/\nAlternativeName create_alt_name(const Data_Store& info)\n {\n class AltName_Matcher : public Data_Store::Matcher\n {\n public:\n bool operator()(const std::string& key, const std::string&) const\n {\n if(key == \"RFC882\" || key == \"DNS\" || key == \"URI\")\n return true;\n return false;\n }\n };\n\n std::multimap names\n = info.search_with(AltName_Matcher());\n\n AlternativeName alt_name;\n\n std::multimap::iterator j;\n for(j = names.begin(); j != names.end(); ++j)\n alt_name.add_attribute(j->first, j->second);\n\n return alt_name;\n }\n\n}\nWrap a line at 80 columns\/*************************************************\n* X.509 Certificates Source File *\n* (C) 1999-2006 The Botan Project *\n*************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Botan {\n\n\/*************************************************\n* X509_Certificate Constructor *\n*************************************************\/\nX509_Certificate::X509_Certificate(DataSource& in) :\n X509_Object(in, \"CERTIFICATE\/X509 CERTIFICATE\")\n {\n self_signed = false;\n do_decode();\n }\n\n\/*************************************************\n* X509_Certificate Constructor *\n*************************************************\/\nX509_Certificate::X509_Certificate(const std::string& in) :\n X509_Object(in, \"CERTIFICATE\/X509 CERTIFICATE\")\n {\n self_signed = false;\n do_decode();\n }\n\n\/*************************************************\n* Decode the TBSCertificate data *\n*************************************************\/\nvoid X509_Certificate::force_decode()\n {\n u32bit version;\n BigInt serial_bn;\n AlgorithmIdentifier sig_algo_inner;\n X509_DN dn_issuer, dn_subject;\n X509_Time start, end;\n\n BER_Decoder tbs_cert(tbs_bits);\n\n tbs_cert.decode_optional(version, ASN1_Tag(0),\n ASN1_Tag(CONSTRUCTED | CONTEXT_SPECIFIC))\n .decode(serial_bn)\n .decode(sig_algo_inner)\n .decode(dn_issuer)\n .start_cons(SEQUENCE)\n .decode(start)\n .decode(end)\n .verify_end()\n .end_cons()\n .decode(dn_subject);\n\n if(version > 2)\n throw Decoding_Error(\"Unknown X.509 cert version \" + to_string(version));\n if(sig_algo != sig_algo_inner)\n throw Decoding_Error(\"Algorithm identifier mismatch\");\n\n self_signed = (dn_subject == dn_issuer);\n\n subject.add(dn_subject.contents());\n issuer.add(dn_issuer.contents());\n\n BER_Object public_key = tbs_cert.get_next_object();\n if(public_key.type_tag != SEQUENCE || public_key.class_tag != CONSTRUCTED)\n throw BER_Bad_Tag(\"X509_Certificate: Unexpected tag for public key\",\n public_key.type_tag, public_key.class_tag);\n\n MemoryVector v2_issuer_key_id, v2_subject_key_id;\n\n tbs_cert.decode_optional_string(v2_issuer_key_id, BIT_STRING, 1);\n tbs_cert.decode_optional_string(v2_subject_key_id, BIT_STRING, 2);\n\n BER_Object v3_exts_data = tbs_cert.get_next_object();\n if(v3_exts_data.type_tag == 3 &&\n v3_exts_data.class_tag == ASN1_Tag(CONSTRUCTED | CONTEXT_SPECIFIC))\n {\n Extensions extensions;\n\n BER_Decoder(v3_exts_data.value).decode(extensions).verify_end();\n\n extensions.contents_to(subject, issuer);\n }\n else if(v3_exts_data.type_tag != NO_OBJECT)\n throw BER_Bad_Tag(\"Unknown tag in X.509 cert\",\n v3_exts_data.type_tag, v3_exts_data.class_tag);\n\n if(tbs_cert.more_items())\n throw Decoding_Error(\"TBSCertificate has more items that expected\");\n\n subject.add(\"X509.Certificate.version\", version);\n subject.add(\"X509.Certificate.serial\", BigInt::encode(serial_bn));\n subject.add(\"X509.Certificate.start\", start.readable_string());\n subject.add(\"X509.Certificate.end\", end.readable_string());\n\n issuer.add(\"X509.Certificate.v2.key_id\", v2_issuer_key_id);\n subject.add(\"X509.Certificate.v2.key_id\", v2_subject_key_id);\n\n subject.add(\"X509.Certificate.public_key\",\n PEM_Code::encode(\n ASN1::put_in_sequence(public_key.value),\n \"PUBLIC KEY\"\n )\n );\n\n if(is_CA_cert() &&\n !subject.has_value(\"X509v3.BasicConstraints.path_constraint\"))\n {\n u32bit limit = (x509_version() < 3) ? NO_CERT_PATH_LIMIT : 0;\n subject.add(\"X509v3.BasicConstraints.path_constraint\", limit);\n }\n }\n\n\/*************************************************\n* Return the X.509 version in use *\n*************************************************\/\nu32bit X509_Certificate::x509_version() const\n {\n return (subject.get1_u32bit(\"X509.Certificate.version\") + 1);\n }\n\n\/*************************************************\n* Return the time this cert becomes valid *\n*************************************************\/\nstd::string X509_Certificate::start_time() const\n {\n return subject.get1(\"X509.Certificate.start\");\n }\n\n\/*************************************************\n* Return the time this cert becomes invalid *\n*************************************************\/\nstd::string X509_Certificate::end_time() const\n {\n return subject.get1(\"X509.Certificate.end\");\n }\n\n\/*************************************************\n* Return information about the subject *\n*************************************************\/\nstd::vector\nX509_Certificate::subject_info(const std::string& what) const\n {\n return subject.get(X509_DN::deref_info_field(what));\n }\n\n\/*************************************************\n* Return information about the issuer *\n*************************************************\/\nstd::vector\nX509_Certificate::issuer_info(const std::string& what) const\n {\n return issuer.get(X509_DN::deref_info_field(what));\n }\n\n\/*************************************************\n* Return the public key in this certificate *\n*************************************************\/\nX509_PublicKey* X509_Certificate::subject_public_key() const\n {\n DataSource_Memory source(subject.get1(\"X509.Certificate.public_key\"));\n return X509::load_key(source);\n }\n\n\/*************************************************\n* Check if the certificate is for a CA *\n*************************************************\/\nbool X509_Certificate::is_CA_cert() const\n {\n if(!subject.get1_u32bit(\"X509v3.BasicConstraints.is_ca\"))\n return false;\n if((constraints() & KEY_CERT_SIGN) || (constraints() == NO_CONSTRAINTS))\n return true;\n return false;\n }\n\n\/*************************************************\n* Return the path length constraint *\n*************************************************\/\nu32bit X509_Certificate::path_limit() const\n {\n return subject.get1_u32bit(\"X509v3.BasicConstraints.path_constraint\", 0);\n }\n\n\/*************************************************\n* Return the key usage constraints *\n*************************************************\/\nKey_Constraints X509_Certificate::constraints() const\n {\n return Key_Constraints(subject.get1_u32bit(\"X509v3.KeyUsage\",\n NO_CONSTRAINTS));\n }\n\n\/*************************************************\n* Return the list of extended key usage OIDs *\n*************************************************\/\nstd::vector X509_Certificate::ex_constraints() const\n {\n return subject.get(\"X509v3.ExtendedKeyUsage\");\n }\n\n\/*************************************************\n* Return the list of certificate policies *\n*************************************************\/\nstd::vector X509_Certificate::policies() const\n {\n return subject.get(\"X509v3.CertificatePolicies\");\n }\n\n\/*************************************************\n* Return the authority key id *\n*************************************************\/\nMemoryVector X509_Certificate::authority_key_id() const\n {\n return issuer.get1_memvec(\"X509v3.AuthorityKeyIdentifier\");\n }\n\n\/*************************************************\n* Return the subject key id *\n*************************************************\/\nMemoryVector X509_Certificate::subject_key_id() const\n {\n return subject.get1_memvec(\"X509v3.SubjectKeyIdentifier\");\n }\n\n\/*************************************************\n* Return the certificate serial number *\n*************************************************\/\nMemoryVector X509_Certificate::serial_number() const\n {\n return subject.get1_memvec(\"X509.Certificate.serial\");\n }\n\n\/*************************************************\n* Return the distinguished name of the issuer *\n*************************************************\/\nX509_DN X509_Certificate::issuer_dn() const\n {\n return create_dn(issuer);\n }\n\n\/*************************************************\n* Return the distinguished name of the subject *\n*************************************************\/\nX509_DN X509_Certificate::subject_dn() const\n {\n return create_dn(subject);\n }\n\n\/*************************************************\n* Compare two certificates for equality *\n*************************************************\/\nbool X509_Certificate::operator==(const X509_Certificate& other) const\n {\n return (sig == other.sig &&\n sig_algo == other.sig_algo &&\n self_signed == other.self_signed &&\n issuer == other.issuer &&\n subject == other.subject);\n }\n\n\/*************************************************\n* X.509 Certificate Comparison *\n*************************************************\/\nbool operator!=(const X509_Certificate& cert1, const X509_Certificate& cert2)\n {\n return !(cert1 == cert2);\n }\n\n\/*************************************************\n* Create and populate a X509_DN *\n*************************************************\/\nX509_DN create_dn(const Data_Store& info)\n {\n class DN_Matcher : public Data_Store::Matcher\n {\n public:\n bool operator()(const std::string& key, const std::string&) const\n {\n if(key.find(\"X520.\") != std::string::npos)\n return true;\n return false;\n }\n };\n\n std::multimap names\n = info.search_with(DN_Matcher());\n\n X509_DN dn;\n\n std::multimap::iterator j;\n for(j = names.begin(); j != names.end(); ++j)\n dn.add_attribute(j->first, j->second);\n\n return dn;\n }\n\n\/*************************************************\n* Create and populate an AlternativeName *\n*************************************************\/\nAlternativeName create_alt_name(const Data_Store& info)\n {\n class AltName_Matcher : public Data_Store::Matcher\n {\n public:\n bool operator()(const std::string& key, const std::string&) const\n {\n if(key == \"RFC882\" || key == \"DNS\" || key == \"URI\")\n return true;\n return false;\n }\n };\n\n std::multimap names\n = info.search_with(AltName_Matcher());\n\n AlternativeName alt_name;\n\n std::multimap::iterator j;\n for(j = names.begin(); j != names.end(); ++j)\n alt_name.add_attribute(j->first, j->second);\n\n return alt_name;\n }\n\n}\n<|endoftext|>"} {"text":"\/*************************************************\n* Globally Saved X.509 State Source *\n* (C) 1999-2007 The Botan Project *\n*************************************************\/\n\n#include \n#include \n#include \n\nnamespace Botan {\n\n\/*************************************************\n* Add a new prototype *\n*************************************************\/\nvoid X509_GlobalState::add(Extension_Prototype* proto)\n {\n if(proto)\n prototypes.push_back(proto);\n }\n\n\/*************************************************\n* Get an extension object *\n*************************************************\/\nCertificate_Extension* X509_GlobalState::get_extension(const OID& oid) const\n {\n Certificate_Extension* extension = 0;\n for(u32bit j = 0; j != prototypes.size() && !extension; ++j)\n extension = prototypes[j]->make(oid);\n return extension;\n }\n\n\/*************************************************\n* Set up a new global state for X.509 *\n*************************************************\/\nX509_GlobalState::X509_GlobalState()\n {\n\n#define CREATE_PROTOTYPE(NAME, TYPE) \\\n do { \\\n struct TYPE ## _Prototype : public Extension_Prototype \\\n { \\\n Certificate_Extension* make(const OID& oid) \\\n { \\\n if(OIDS::name_of(oid, NAME)) \\\n return new Cert_Extension::TYPE(); \\\n return 0; \\\n } \\\n }; \\\n \\\n add(new TYPE ## _Prototype); \\\n } while(0);\n\n CREATE_PROTOTYPE(\"X509v3.KeyUsage\", Key_Usage);\n CREATE_PROTOTYPE(\"X509v3.BasicConstraints\", Basic_Constraints);\n CREATE_PROTOTYPE(\"X509v3.SubjectKeyIdentifier\", Subject_Key_ID);\n CREATE_PROTOTYPE(\"X509v3.AuthorityKeyIdentifier\", Authority_Key_ID);\n CREATE_PROTOTYPE(\"X509v3.ExtendedKeyUsage\", Extended_Key_Usage);\n CREATE_PROTOTYPE(\"X509v3.IssuerAlternativeName\", Issuer_Alternative_Name);\n CREATE_PROTOTYPE(\"X509v3.SubjectAlternativeName\", Subject_Alternative_Name);\n CREATE_PROTOTYPE(\"X509v3.CRLNumber\", CRL_Number);\n CREATE_PROTOTYPE(\"X509v3.CertificatePolicies\", Certificate_Policies);\n\n#undef CREATE_PROTOTYPE\n }\n\n\/*************************************************\n* Destroy this global state object *\n*************************************************\/\nX509_GlobalState::~X509_GlobalState()\n {\n for(u32bit j = 0; j != prototypes.size(); ++j)\n delete prototypes[j];\n prototypes.clear();\n }\n\n}\nUse Botan:: prefixes to work around a bug in Visual Studio C++ 2003. Patch from Christophe Meessen on the development list.\/*************************************************\n* Globally Saved X.509 State Source *\n* (C) 1999-2007 The Botan Project *\n*************************************************\/\n\n#include \n#include \n#include \n\nnamespace Botan {\n\n\/*************************************************\n* Add a new prototype *\n*************************************************\/\nvoid X509_GlobalState::add(Extension_Prototype* proto)\n {\n if(proto)\n prototypes.push_back(proto);\n }\n\n\/*************************************************\n* Get an extension object *\n*************************************************\/\nCertificate_Extension* X509_GlobalState::get_extension(const OID& oid) const\n {\n Certificate_Extension* extension = 0;\n for(u32bit j = 0; j != prototypes.size() && !extension; ++j)\n extension = prototypes[j]->make(oid);\n return extension;\n }\n\n\/*************************************************\n* Set up a new global state for X.509 *\n*************************************************\/\nX509_GlobalState::X509_GlobalState()\n {\n\n#define CREATE_PROTOTYPE(NAME, TYPE) \\\n do { \\\n struct TYPE ## _Prototype : public Extension_Prototype \\\n { \\\n Certificate_Extension* make(const OID& oid) \\\n { \\\n if(Botan::OIDS::name_of(oid, NAME)) \\\n return new Botan::Cert_Extension::TYPE(); \\\n return 0; \\\n } \\\n }; \\\n \\\n add(new TYPE ## _Prototype); \\\n } while(0);\n\n CREATE_PROTOTYPE(\"X509v3.KeyUsage\", Key_Usage);\n CREATE_PROTOTYPE(\"X509v3.BasicConstraints\", Basic_Constraints);\n CREATE_PROTOTYPE(\"X509v3.SubjectKeyIdentifier\", Subject_Key_ID);\n CREATE_PROTOTYPE(\"X509v3.AuthorityKeyIdentifier\", Authority_Key_ID);\n CREATE_PROTOTYPE(\"X509v3.ExtendedKeyUsage\", Extended_Key_Usage);\n CREATE_PROTOTYPE(\"X509v3.IssuerAlternativeName\", Issuer_Alternative_Name);\n CREATE_PROTOTYPE(\"X509v3.SubjectAlternativeName\", Subject_Alternative_Name);\n CREATE_PROTOTYPE(\"X509v3.CRLNumber\", CRL_Number);\n CREATE_PROTOTYPE(\"X509v3.CertificatePolicies\", Certificate_Policies);\n\n#undef CREATE_PROTOTYPE\n }\n\n\/*************************************************\n* Destroy this global state object *\n*************************************************\/\nX509_GlobalState::~X509_GlobalState()\n {\n for(u32bit j = 0; j != prototypes.size(); ++j)\n delete prototypes[j];\n prototypes.clear();\n }\n\n}\n<|endoftext|>"} {"text":"#include \n\nCommunication::Communication(ObjectExtractor *p_obj_e, FileAPI *p_api, JacoCustom *p_jaco)\n{\n m_object_ex_ptr = p_obj_e;\n m_api_ptr = p_api;\n m_jaco_ptr = p_jaco;\n m_coordinate_received = false;\n m_grasp_received = false;\n m_train_received = false;\n}\n\n\/\/-----------------------------------------------------------------------------------\/\/\nvoid Communication::callback_android_listener(const std_msgs::String &p_input)\n{\n\n switch(p_input.data[0])\n {\n case('c'):coordinate_processing(p_input);break;\n case('t'):train_processing(p_input);break;\n case('g'):grasp_processing(p_input);break;\n default:break;\n }\n}\n\n\/\/---------------------------------------------------------------------------------\/\/\nvoid Communication::coordinate_processing(std_msgs::String p_coordinate)\n{\n m_coordinate_received = true;\n m_grasp_received = false;\n m_train_received = false;\n\n std::string string_temp = \"\";\n for(int i = 0; i < p_coordinate.data.size(); i ++)\n {\n if(p_coordinate.data.at(i) == '_')\n {\n m_coordinate_user_sended[0] = atof(string_temp.c_str());\n string_temp.clear();\n }\n else\n string_temp += p_coordinate.data.at(i);\n\n }\n m_coordinate_user_sended[1] = atof(string_temp.c_str());\n m_coordinate_user_sended[0] = m_coordinate_user_sended[0]*640;\n m_coordinate_user_sended[1] = m_coordinate_user_sended[1]*480;\n}\n\n\/\/----------------------------------------------------------------------------------------\/\/\nvoid Communication::grasp_processing(std_msgs::String p_grasp)\n{\n m_coordinate_received = false;\n m_grasp_received = false;\n m_train_received = true;\n}\n\n\/\/------------------------------------------------------------------------------------------\/\/\nvoid Communication::train_processing(std_msgs::String p_train)\n{\n m_coordinate_received = false;\n m_grasp_received = false;\n m_train_received = true;\n}\n\n\/\/------------------------------------------------------------------------------------------\/\/\nbool Communication::get_coordinate_received() const\n{\n return m_coordinate_received;\n}\n\n\/\/--------------------------------------------------------------------------------------------\/\/\nbool Communication::get_grasp_received() const\n{\n return m_grasp_received;\n}\n\n\/\/---------------------------------------------------------------------------------------------\/\/\nbool Communication::get_train_received() const\n{\n return m_train_received;\n}\n\n\/\/-----------------------------------------------------------------------------------------------\/\/\nvoid Communication::spin_once()\n{\n if(m_coordinate_received)\n {\n m_position_vector_cvfh = m_object_ex_ptr->coordinate_processing(m_coordinate_user_sended,\n m_api_ptr->getAllHistograme());\n\n m_object_ex_ptr->coordinate_processing(m_coordinate_user_sended,m_api_ptr->getAllHistograme());\n m_object_ex_ptr->spin_once();\n\n \/\/pour retrouver l'object qui est reconnue par le cvfh\n \/\/m_api_ptr->retrieveObjectFromHistogramme(m_position_vector_cvfh);\n }\n else if(m_train_received)\n {\n train();\n }\n else if(m_grasp_received)\n {\n repeat();\n }\n else\n {\n m_object_ex_ptr->spin_once();\n }\n m_coordinate_received = false;\n m_grasp_received = false;\n m_train_received = false;\n}\n\n\/\/-----------------------------------------------------------------------------------------------\/\/\nvoid Communication::train(){\n \/\/\n \/\/Object obj;\n \/\/obj.name = m_api_ptr->findDefaultName();\n pcl::PointCloud::Ptr object_pointcloud = m_object_ex_ptr->getObjectToGrasp();\n pcl::PointCloud::Ptr object_signature = m_object_ex_ptr->m_object_recognition.makeCVFH(object_pointcloud);\n\n \/\/ OBJECT POSE\n \/\/obj.object_pose = ; \/\/ find object pose\n tf::StampedTransform object_tf = m_object_ex_ptr->getCentroidPositionRGBFrame();\n\n \/\/ JACO POSE\n \/\/tf::StampedTransform arm_pose_before_grasp = m_jaco_ptr->getGraspArmPosition();\n \/\/ For testing purposes only, comment the following line and uncomment previous one\n tf::StampedTransform arm_pose_before_grasp = m_jaco_ptr->getArmPositionFromCamera();\n\n \/\/ RELATIVE POSE\n tf::Transform arm_rel_pose;\n tf::Vector3 translation = arm_pose_before_grasp.getOrigin() - object_tf.getOrigin();\n arm_rel_pose = tf::Transform(object_tf.getBasis().transposeTimes(arm_pose_before_grasp.getBasis()), translation);\n\n \/\/ TO VIEW FRAMES\n \/\/static tf::TransformBroadcaster br;\n \/\/br.sendTransform(object_tf);\n \/\/br.sendTransform(tf::StampedTransform(diff,ros::Time::now(),\"detected_object_centroids\",\"jaco_relative_pose\"));\n\n \/\/ PRINT POSE\n \/\/ cout << \"arm pose : [\" << arm_pose_before_grasp.getOrigin().getX() << \", \" <<\n \/\/ arm_pose_before_grasp.getOrigin().getY() << \", \" <<\n \/\/ arm_pose_before_grasp.getOrigin().getZ() << \"]\" << endl;\n\n\n m_api_ptr->save(object_signature,object_pointcloud,arm_rel_pose,object_tf);\n m_relative_pose = arm_rel_pose;\n\n}\n\nvoid Communication::repeat(){\n tf::StampedTransform object_tf = m_object_ex_ptr->getCentroidPositionRGBFrame();\n tf::Vector3 translation2 = object_tf.getOrigin() + m_relative_pose.getOrigin();\n tf::Transform tf_ = tf::Transform(object_tf.getRotation()*m_relative_pose.getRotation(), translation2);\n<<<<<<< HEAD\n=======\n\n m_publish_relative_pose = true;\n boost::thread thread(&Communication::publishRelativePoseTF,this,tf_);\n tf::StampedTransform goal_pose;\n tf::TransformListener listener;\n listener.waitForTransform(\"jaco_api_origin\",\"jaco_tool_relative_pose\",ros::Time(0),ros::Duration(3.0));\n listener.lookupTransform(\"jaco_api_origin\",\"jaco_tool_relative_pose\",ros::Time(0),goal_pose);\n m_publish_relative_pose = false;\n thread.join();\n\n m_jaco_ptr->moveToPoint(goal_pose);\n>>>>>>> f19369e2f55fe711cc39594442a044fe017e9c5b\n\n m_publish_relative_pose = true;\n boost::thread thread(&Communication::publishRelativePoseTF,this,tf_);\n tf::StampedTransform goal_pose;\n tf::TransformListener listener;\n listener.waitForTransform(\"jaco_api_origin\",\"jaco_tool_relative_pose\",ros::Time(0),ros::Duration(3.0));\n listener.lookupTransform(\"jaco_api_origin\",\"jaco_tool_relative_pose\",ros::Time(0),goal_pose);\n m_publish_relative_pose = false;\n thread.join();\n\n<<<<<<< HEAD\n m_jaco_ptr->moveToPoint(goal_pose);\n=======\n}\n>>>>>>> f19369e2f55fe711cc39594442a044fe017e9c5b\n\nvoid Communication::publishRelativePoseTF(tf::Transform relative_pose){\n static tf::TransformBroadcaster br;\n ros::Rate r(10);\n while(m_publish_relative_pose){\n tf::StampedTransform arm_relative = tf::StampedTransform(relative_pose,ros::Time::now(),\"camera_rgb_frame\",\"jaco_tool_relative_pose\");\n br.sendTransform(arm_relative);\n r.sleep();\n }\n\n}\n\nvoid Communication::publishRelativePoseTF(tf::Transform relative_pose){\n static tf::TransformBroadcaster br;\n ros::Rate r(10);\n while(m_publish_relative_pose){\n tf::StampedTransform arm_relative = tf::StampedTransform(relative_pose,ros::Time::now(),\"camera_rgb_frame\",\"jaco_tool_relative_pose\");\n br.sendTransform(arm_relative);\n r.sleep();\n }\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nUpdate communication.cpp#include \n\nCommunication::Communication(ObjectExtractor *p_obj_e, FileAPI *p_api, JacoCustom *p_jaco)\n{\n m_object_ex_ptr = p_obj_e;\n m_api_ptr = p_api;\n m_jaco_ptr = p_jaco;\n m_coordinate_received = false;\n m_grasp_received = false;\n m_train_received = false;\n}\n\n\/\/-----------------------------------------------------------------------------------\/\/\nvoid Communication::callback_android_listener(const std_msgs::String &p_input)\n{\n\n switch(p_input.data[0])\n {\n case('c'):coordinate_processing(p_input);break;\n case('t'):train_processing(p_input);break;\n case('g'):grasp_processing(p_input);break;\n default:break;\n }\n}\n\n\/\/---------------------------------------------------------------------------------\/\/\nvoid Communication::coordinate_processing(std_msgs::String p_coordinate)\n{\n m_coordinate_received = true;\n m_grasp_received = false;\n m_train_received = false;\n\n std::string string_temp = \"\";\n for(int i = 0; i < p_coordinate.data.size(); i ++)\n {\n if(p_coordinate.data.at(i) == '_')\n {\n m_coordinate_user_sended[0] = atof(string_temp.c_str());\n string_temp.clear();\n }\n else\n string_temp += p_coordinate.data.at(i);\n\n }\n m_coordinate_user_sended[1] = atof(string_temp.c_str());\n m_coordinate_user_sended[0] = m_coordinate_user_sended[0]*640;\n m_coordinate_user_sended[1] = m_coordinate_user_sended[1]*480;\n}\n\n\/\/----------------------------------------------------------------------------------------\/\/\nvoid Communication::grasp_processing(std_msgs::String p_grasp)\n{\n m_coordinate_received = false;\n m_grasp_received = false;\n m_train_received = true;\n}\n\n\/\/------------------------------------------------------------------------------------------\/\/\nvoid Communication::train_processing(std_msgs::String p_train)\n{\n m_coordinate_received = false;\n m_grasp_received = false;\n m_train_received = true;\n}\n\n\/\/------------------------------------------------------------------------------------------\/\/\nbool Communication::get_coordinate_received() const\n{\n return m_coordinate_received;\n}\n\n\/\/--------------------------------------------------------------------------------------------\/\/\nbool Communication::get_grasp_received() const\n{\n return m_grasp_received;\n}\n\n\/\/---------------------------------------------------------------------------------------------\/\/\nbool Communication::get_train_received() const\n{\n return m_train_received;\n}\n\n\/\/-----------------------------------------------------------------------------------------------\/\/\nvoid Communication::spin_once()\n{\n if(m_coordinate_received)\n {\n m_position_vector_cvfh = m_object_ex_ptr->coordinate_processing(m_coordinate_user_sended,\n m_api_ptr->getAllHistograme());\n\n m_object_ex_ptr->coordinate_processing(m_coordinate_user_sended,m_api_ptr->getAllHistograme());\n m_object_ex_ptr->spin_once();\n\n \/\/pour retrouver l'object qui est reconnue par le cvfh\n \/\/m_api_ptr->retrieveObjectFromHistogramme(m_position_vector_cvfh);\n }\n else if(m_train_received)\n {\n train();\n }\n else if(m_grasp_received)\n {\n repeat();\n }\n else\n {\n m_object_ex_ptr->spin_once();\n }\n m_coordinate_received = false;\n m_grasp_received = false;\n m_train_received = false;\n}\n\n\/\/-----------------------------------------------------------------------------------------------\/\/\nvoid Communication::train(){\n \/\/\n \/\/Object obj;\n \/\/obj.name = m_api_ptr->findDefaultName();\n pcl::PointCloud::Ptr object_pointcloud = m_object_ex_ptr->getObjectToGrasp();\n pcl::PointCloud::Ptr object_signature = m_object_ex_ptr->m_object_recognition.makeCVFH(object_pointcloud);\n\n \/\/ OBJECT POSE\n \/\/obj.object_pose = ; \/\/ find object pose\n tf::StampedTransform object_tf = m_object_ex_ptr->getCentroidPositionRGBFrame();\n\n \/\/ JACO POSE\n \/\/tf::StampedTransform arm_pose_before_grasp = m_jaco_ptr->getGraspArmPosition();\n \/\/ For testing purposes only, comment the following line and uncomment previous one\n tf::StampedTransform arm_pose_before_grasp = m_jaco_ptr->getArmPositionFromCamera();\n\n \/\/ RELATIVE POSE\n tf::Transform arm_rel_pose;\n tf::Vector3 translation = arm_pose_before_grasp.getOrigin() - object_tf.getOrigin();\n arm_rel_pose = tf::Transform(object_tf.getBasis().transposeTimes(arm_pose_before_grasp.getBasis()), translation);\n\n \/\/ TO VIEW FRAMES\n \/\/static tf::TransformBroadcaster br;\n \/\/br.sendTransform(object_tf);\n \/\/br.sendTransform(tf::StampedTransform(diff,ros::Time::now(),\"detected_object_centroids\",\"jaco_relative_pose\"));\n\n \/\/ PRINT POSE\n \/\/ cout << \"arm pose : [\" << arm_pose_before_grasp.getOrigin().getX() << \", \" <<\n \/\/ arm_pose_before_grasp.getOrigin().getY() << \", \" <<\n \/\/ arm_pose_before_grasp.getOrigin().getZ() << \"]\" << endl;\n\n\n m_api_ptr->save(object_signature,object_pointcloud,arm_rel_pose,object_tf);\n m_relative_pose = arm_rel_pose;\n\n}\n\nvoid Communication::repeat(){\n tf::StampedTransform object_tf = m_object_ex_ptr->getCentroidPositionRGBFrame();\n tf::Vector3 translation2 = object_tf.getOrigin() + m_relative_pose.getOrigin();\n tf::Transform tf_ = tf::Transform(object_tf.getRotation()*m_relative_pose.getRotation(), translation2);\n\n m_publish_relative_pose = true;\n boost::thread thread(&Communication::publishRelativePoseTF,this,tf_);\n tf::StampedTransform goal_pose;\n tf::TransformListener listener;\n listener.waitForTransform(\"jaco_api_origin\",\"jaco_tool_relative_pose\",ros::Time(0),ros::Duration(3.0));\n listener.lookupTransform(\"jaco_api_origin\",\"jaco_tool_relative_pose\",ros::Time(0),goal_pose);\n m_publish_relative_pose = false;\n thread.join();\n\n m_jaco_ptr->moveToPoint(goal_pose);\n\n\n}\n\nvoid Communication::publishRelativePoseTF(tf::Transform relative_pose){\n static tf::TransformBroadcaster br;\n ros::Rate r(10);\n while(m_publish_relative_pose){\n tf::StampedTransform arm_relative = tf::StampedTransform(relative_pose,ros::Time::now(),\"camera_rgb_frame\",\"jaco_tool_relative_pose\");\n br.sendTransform(arm_relative);\n r.sleep();\n }\n\n}\n\nvoid Communication::publishRelativePoseTF(tf::Transform relative_pose){\n static tf::TransformBroadcaster br;\n ros::Rate r(10);\n while(m_publish_relative_pose){\n tf::StampedTransform arm_relative = tf::StampedTransform(relative_pose,ros::Time::now(),\"camera_rgb_frame\",\"jaco_tool_relative_pose\");\n br.sendTransform(arm_relative);\n r.sleep();\n }\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"\/* Copyright (C) 2012-2013 Justin Berger \r\n The full license is available in the LICENSE file at the root of this project and is also available at http:\/\/opensource.org\/licenses\/MIT. *\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\/\/ http:\/\/connect.microsoft.com\/VisualStudio\/feedback\/details\/809540\/c-warnings-in-stl-thread\r\n#pragma warning(disable: 4265)\r\n#include \r\n#pragma warning(default: 4265)\r\n\r\n#ifdef _MSC_VER\r\n#include \r\nstatic std::ostream* defaultStream = &mxcomp::vsdb;\r\n#else \r\nstatic std::ostream* defaultStream = &std::cerr;\r\n#endif\r\n\r\n\r\nnamespace mxcomp {\r\n namespace log {\r\n\r\n\r\n static std::map logStreams;\r\n\tstd::mutex logMutex; \r\n\r\n std::map& logLevels(){\r\n static std::map* logLevels = 0;\r\n\t if (logLevels == 0) { \/\/ Makes logLevels look up cheap when there is an object (no mutex lock)\r\n\t\t std::lock_guard lock(logMutex);\r\n\t\t if (logLevels == 0) { \/\/ If we blocked for another thread, make sure we dont create two logLevels. \r\n\t\t\t logLevels = new std::map();\r\n\t\t }\r\n\t }\r\n return *logLevels;\r\n }\r\n void SetLogStream(std::ostream* stream) {\r\n defaultStream = stream;\r\n }\r\n void SetLogStream(std::ostream& stream) {\r\n defaultStream = &stream;\r\n }\r\n\r\n void SetLogStream(const std::string& category, std::ostream& stream){\r\n logStreams[category] = &stream;\r\n }\r\n\r\n std::ostream& LogStream(const std::string& category){\r\n auto it = logStreams.find(category);\r\n return it == logStreams.end() ? *defaultStream : *(it->second);\r\n }\r\n\r\n void SetLogLevel(const std::string& category, int level){\r\n logLevels()[category] = level;\r\n }\r\n static int getLevel(const std::string& level){\r\n if(level == \"Verbose\") {\r\n\treturn Verbose;\r\n } else if (level == \"Info\") {\r\n\treturn Info;\r\n } else if (level == \"Debug\") {\r\n\treturn Debug;\r\n } else if (level == \"Error\") {\r\n\treturn Error;\r\n }\r\n return INVALID;\r\n }\r\n\r\n void SetLogLevel(const std::string& category, const std::string& level){ \r\n int _level = getLevel(level);\r\n SetLogLevel(category, _level);\r\n LOG(Logging, Verbose) << \"Setting '\" << category << \"' to '\" << level << \"'(\" << _level << \")\" << std::endl;\r\n if(_level == INVALID)\r\n\tLOG(Logging, Error) << \"Invalid logging level('\" << level << \"') set for category '\" << category << \"'. Level set to highest verbosity.\" << std::endl; \r\n }\r\n }\r\n}\r\n\r\n\/\/ We _must_ define this block in this file; as its the only way to insure that it fires off before any of the functions for logging\r\n#ifdef RT_USE_CONFIGURATION\r\n#include \r\nusing namespace rikitiki;\r\nusing namespace rikitiki::log;\r\nusing namespace libconfig; \r\n\r\nstatic bool LoadFromConfig(Configuration& config) {\r\n try {\r\n const Setting& logsettings = config.getRoot()[\"log\"][\"levels\"];\r\n std::string name, value;\r\n for(int i = 0;i < logsettings.getLength();i++){\r\n const Setting& entry = logsettings[i];\r\n bool cFind = entry.lookupValue(\"category\", name);\r\n bool vFind = entry.lookupValue(\"level\", value); \r\n if(cFind && vFind)\r\n\tSetLogLevel(name, value);\r\n }\r\n return true;\r\n } catch(const SettingNotFoundException& nfex){\r\n return false;\r\n }\r\n}\r\n\r\nstatic bool config_loaded = LoadFromConfig(Configuration::Global());\r\n#endif\r\n\r\nfixed non chunking\/* Copyright (C) 2012-2013 Justin Berger \r\n The full license is available in the LICENSE file at the root of this project and is also available at http:\/\/opensource.org\/licenses\/MIT. *\/\r\n\r\n#include \r\n#include \r\n#include \r\n\/\/#include \r\n\r\n\/\/ http:\/\/connect.microsoft.com\/VisualStudio\/feedback\/details\/809540\/c-warnings-in-stl-thread\r\n#pragma warning(disable: 4265)\r\n#include \r\n#pragma warning(default: 4265)\r\n\r\n#ifdef _MSC_VER\r\n#include \r\nstatic std::ostream* defaultStream = &mxcomp::vsdb;\r\n#else \r\nstatic std::ostream* defaultStream = &std::cerr;\r\n#endif\r\n\r\n\r\nnamespace mxcomp {\r\n namespace log {\r\n\r\n\r\n static std::map logStreams;\r\n\tstd::mutex logMutex; \r\n\r\n std::map& logLevels(){\r\n static std::map* logLevels = 0;\r\n\t if (logLevels == 0) { \/\/ Makes logLevels look up cheap when there is an object (no mutex lock)\r\n\t\t std::lock_guard lock(logMutex);\r\n\t\t if (logLevels == 0) { \/\/ If we blocked for another thread, make sure we dont create two logLevels. \r\n\t\t\t logLevels = new std::map();\r\n\t\t }\r\n\t }\r\n return *logLevels;\r\n }\r\n void SetLogStream(std::ostream* stream) {\r\n defaultStream = stream;\r\n }\r\n void SetLogStream(std::ostream& stream) {\r\n defaultStream = &stream;\r\n }\r\n\r\n void SetLogStream(const std::string& category, std::ostream& stream){\r\n logStreams[category] = &stream;\r\n }\r\n\r\n std::ostream& LogStream(const std::string& category){\r\n auto it = logStreams.find(category);\r\n return it == logStreams.end() ? *defaultStream : *(it->second);\r\n }\r\n\r\n void SetLogLevel(const std::string& category, int level){\r\n logLevels()[category] = level;\r\n }\r\n static int getLevel(const std::string& level){\r\n if(level == \"Verbose\") {\r\n\treturn Verbose;\r\n } else if (level == \"Info\") {\r\n\treturn Info;\r\n } else if (level == \"Debug\") {\r\n\treturn Debug;\r\n } else if (level == \"Error\") {\r\n\treturn Error;\r\n }\r\n return INVALID;\r\n }\r\n\r\n void SetLogLevel(const std::string& category, const std::string& level){ \r\n int _level = getLevel(level);\r\n SetLogLevel(category, _level);\r\n LOG(Logging, Verbose) << \"Setting '\" << category << \"' to '\" << level << \"'(\" << _level << \")\" << std::endl;\r\n if(_level == INVALID)\r\n\tLOG(Logging, Error) << \"Invalid logging level('\" << level << \"') set for category '\" << category << \"'. Level set to highest verbosity.\" << std::endl; \r\n }\r\n }\r\n}\r\n\r\n\/\/ We _must_ define this block in this file; as its the only way to insure that it fires off before any of the functions for logging\r\n#ifdef RT_USE_CONFIGURATION\r\n#include \r\nusing namespace rikitiki;\r\nusing namespace rikitiki::log;\r\nusing namespace libconfig; \r\n\r\nstatic bool LoadFromConfig(Configuration& config) {\r\n try {\r\n const Setting& logsettings = config.getRoot()[\"log\"][\"levels\"];\r\n std::string name, value;\r\n for(int i = 0;i < logsettings.getLength();i++){\r\n const Setting& entry = logsettings[i];\r\n bool cFind = entry.lookupValue(\"category\", name);\r\n bool vFind = entry.lookupValue(\"level\", value); \r\n if(cFind && vFind)\r\n\tSetLogLevel(name, value);\r\n }\r\n return true;\r\n } catch(const SettingNotFoundException& nfex){\r\n return false;\r\n }\r\n}\r\n\r\nstatic bool config_loaded = LoadFromConfig(Configuration::Global());\r\n#endif\r\n\r\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"image.h\"\nusing namespace AhoViewer::Booru;\n\n#include \"browser.h\"\n\nImage::Image(const std::string &path, const std::string &url,\n const std::string &thumbPath, const std::string &thumbUrl,\n const std::string &postUrl,\n std::set tags, const Page &page)\n : AhoViewer::Image(path),\n m_Url(url),\n m_ThumbnailUrl(thumbUrl),\n m_PostUrl(postUrl),\n m_Tags(tags),\n m_Page(page),\n m_Curler(m_Url),\n m_ThumbnailCurler(m_ThumbnailUrl),\n m_PixbufError(false)\n{\n m_ThumbnailPath = thumbPath;\n\n if (!m_isWebM)\n m_Curler.signal_write().connect(sigc::mem_fun(*this, &Image::on_write));\n\n if (m_isWebM && !Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))\n m_Loading = true;\n\n m_Curler.set_referer(page.get_site()->get_url());\n m_Curler.signal_progress().connect(sigc::mem_fun(*this, &Image::on_progress));\n m_Curler.signal_finished().connect(sigc::mem_fun(*this, &Image::on_finished));\n}\n\nImage::~Image()\n{\n cancel_download();\n\n if (m_Curler.is_active())\n m_Page.get_image_fetcher().remove_handle(&m_Curler);\n}\n\nstd::string Image::get_filename() const\n{\n return Glib::build_filename(m_Page.get_site()->get_name(), Glib::path_get_basename(m_Path));\n}\n\nconst Glib::RefPtr& Image::get_thumbnail()\n{\n if (!m_ThumbnailPixbuf)\n {\n m_ThumbnailLock.writer_lock();\n if (m_ThumbnailCurler.perform())\n {\n m_ThumbnailCurler.save_file(m_ThumbnailPath);\n\n try\n {\n m_ThumbnailPixbuf = create_pixbuf_at_size(m_ThumbnailPath, 128, 128);\n }\n catch (const Gdk::PixbufError &ex)\n {\n std::cerr << ex.what() << std::endl;\n m_ThumbnailPixbuf = get_missing_pixbuf();\n }\n }\n else\n {\n std::cerr << \"Error while downloading thumbnail \" << m_ThumbnailUrl\n << \" \" << std::endl << \" \" << m_ThumbnailCurler.get_error() << std::endl;\n m_ThumbnailPixbuf = get_missing_pixbuf();\n }\n m_ThumbnailLock.writer_unlock();\n }\n\n return m_ThumbnailPixbuf;\n}\n\nvoid Image::load_pixbuf()\n{\n if (!m_Pixbuf && !m_PixbufError)\n {\n if (Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))\n {\n AhoViewer::Image::load_pixbuf();\n }\n else if (!start_download() && !m_isWebM && m_Loader->get_animation())\n {\n m_Pixbuf = m_Loader->get_animation();\n }\n }\n}\n\nvoid Image::reset_pixbuf()\n{\n if (m_Loading)\n cancel_download();\n\n AhoViewer::Image::reset_pixbuf();\n}\n\nvoid Image::save(const std::string &path)\n{\n if (!Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))\n {\n start_download();\n\n Glib::Threads::Mutex::Lock lock(m_DownloadMutex);\n while (!m_Curler.is_cancelled() && !Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))\n m_DownloadCond.wait(m_DownloadMutex);\n }\n\n if (m_Curler.is_cancelled())\n return;\n\n Glib::RefPtr src = Gio::File::create_for_path(m_Path),\n dst = Gio::File::create_for_path(path);\n src->copy(dst, Gio::FILE_COPY_OVERWRITE);\n}\n\nvoid Image::cancel_download()\n{\n Glib::Threads::Mutex::Lock lock(m_DownloadMutex);\n m_Curler.cancel();\n m_Curler.clear();\n\n if (m_Loader)\n {\n try { m_Loader->close(); }\n catch (...) { }\n m_Loader.reset();\n }\n\n m_DownloadCond.signal();\n}\n\n\/**\n * Returns true if the download was started\n **\/\nbool Image::start_download()\n{\n if (!m_Curler.is_active())\n {\n m_Page.get_image_fetcher().add_handle(&m_Curler);\n m_Loading = true;\n\n if (!m_isWebM)\n {\n m_Loader = Gdk::PixbufLoader::create();\n m_Loader->signal_area_prepared().connect(sigc::mem_fun(*this, &Image::on_area_prepared));\n m_Loader->signal_area_updated().connect(sigc::mem_fun(*this, &Image::on_area_updated));\n }\n\n return true;\n }\n\n return false;\n}\n\nvoid Image::on_write(const unsigned char *d, size_t l)\n{\n try\n {\n Glib::Threads::Mutex::Lock lock(m_DownloadMutex);\n m_Loader->write(d, l);\n }\n catch (const Gdk::PixbufError &ex)\n {\n std::cerr << ex.what() << std::endl;\n cancel_download();\n m_PixbufError = true;\n }\n}\n\nvoid Image::on_progress()\n{\n double c, t;\n m_Curler.get_progress(c, t);\n m_SignalProgress(c, t);\n}\n\nvoid Image::on_finished()\n{\n Glib::Threads::Mutex::Lock lock(m_DownloadMutex);\n\n m_Curler.save_file(m_Path);\n m_Curler.clear();\n\n if (m_Loader)\n {\n m_Loader->close();\n m_Loader.reset();\n }\n\n m_Loading = false;\n\n m_SignalPixbufChanged();\n m_DownloadCond.signal();\n}\n\nvoid Image::on_area_prepared()\n{\n m_ThumbnailLock.reader_lock();\n if (m_ThumbnailPixbuf && m_ThumbnailPixbuf != get_missing_pixbuf())\n {\n Glib::RefPtr pixbuf = m_Loader->get_pixbuf();\n m_ThumbnailPixbuf->composite(pixbuf, 0, 0, pixbuf->get_width(), pixbuf->get_height(), 0, 0,\n static_cast(pixbuf->get_width()) \/ m_ThumbnailPixbuf->get_width(),\n static_cast(pixbuf->get_height()) \/ m_ThumbnailPixbuf->get_height(),\n Gdk::INTERP_BILINEAR, 255);\n }\n m_ThumbnailLock.reader_unlock();\n\n m_Pixbuf = m_Loader->get_animation();\n\n if (!m_Curler.is_cancelled())\n m_SignalPixbufChanged();\n}\n\nvoid Image::on_area_updated(int, int, int, int)\n{\n using namespace std::chrono;\n if (!m_Curler.is_cancelled() && steady_clock::now() >= m_LastDraw + milliseconds(100))\n {\n m_SignalPixbufChanged();\n m_LastDraw = steady_clock::now();\n }\n}\nbooru\/image: Remove curler from the imagefetcher in cancel_download#include \n#include \n\n#include \"image.h\"\nusing namespace AhoViewer::Booru;\n\n#include \"browser.h\"\n\nImage::Image(const std::string &path, const std::string &url,\n const std::string &thumbPath, const std::string &thumbUrl,\n const std::string &postUrl,\n std::set tags, const Page &page)\n : AhoViewer::Image(path),\n m_Url(url),\n m_ThumbnailUrl(thumbUrl),\n m_PostUrl(postUrl),\n m_Tags(tags),\n m_Page(page),\n m_Curler(m_Url),\n m_ThumbnailCurler(m_ThumbnailUrl),\n m_PixbufError(false)\n{\n m_ThumbnailPath = thumbPath;\n\n if (!m_isWebM)\n m_Curler.signal_write().connect(sigc::mem_fun(*this, &Image::on_write));\n\n if (m_isWebM && !Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))\n m_Loading = true;\n\n m_Curler.set_referer(page.get_site()->get_url());\n m_Curler.signal_progress().connect(sigc::mem_fun(*this, &Image::on_progress));\n m_Curler.signal_finished().connect(sigc::mem_fun(*this, &Image::on_finished));\n}\n\nImage::~Image()\n{\n cancel_download();\n}\n\nstd::string Image::get_filename() const\n{\n return Glib::build_filename(m_Page.get_site()->get_name(), Glib::path_get_basename(m_Path));\n}\n\nconst Glib::RefPtr& Image::get_thumbnail()\n{\n if (!m_ThumbnailPixbuf)\n {\n m_ThumbnailLock.writer_lock();\n if (m_ThumbnailCurler.perform())\n {\n m_ThumbnailCurler.save_file(m_ThumbnailPath);\n\n try\n {\n m_ThumbnailPixbuf = create_pixbuf_at_size(m_ThumbnailPath, 128, 128);\n }\n catch (const Gdk::PixbufError &ex)\n {\n std::cerr << ex.what() << std::endl;\n m_ThumbnailPixbuf = get_missing_pixbuf();\n }\n }\n else\n {\n std::cerr << \"Error while downloading thumbnail \" << m_ThumbnailUrl\n << \" \" << std::endl << \" \" << m_ThumbnailCurler.get_error() << std::endl;\n m_ThumbnailPixbuf = get_missing_pixbuf();\n }\n m_ThumbnailLock.writer_unlock();\n }\n\n return m_ThumbnailPixbuf;\n}\n\nvoid Image::load_pixbuf()\n{\n if (!m_Pixbuf && !m_PixbufError)\n {\n if (Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))\n {\n AhoViewer::Image::load_pixbuf();\n }\n else if (!start_download() && !m_isWebM && m_Loader->get_animation())\n {\n m_Pixbuf = m_Loader->get_animation();\n }\n }\n}\n\nvoid Image::reset_pixbuf()\n{\n if (m_Loading)\n cancel_download();\n\n AhoViewer::Image::reset_pixbuf();\n}\n\nvoid Image::save(const std::string &path)\n{\n if (!Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))\n {\n start_download();\n\n Glib::Threads::Mutex::Lock lock(m_DownloadMutex);\n while (!m_Curler.is_cancelled() && !Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))\n m_DownloadCond.wait(m_DownloadMutex);\n }\n\n if (m_Curler.is_cancelled())\n return;\n\n Glib::RefPtr src = Gio::File::create_for_path(m_Path),\n dst = Gio::File::create_for_path(path);\n src->copy(dst, Gio::FILE_COPY_OVERWRITE);\n}\n\nvoid Image::cancel_download()\n{\n Glib::Threads::Mutex::Lock lock(m_DownloadMutex);\n m_Curler.cancel();\n m_Curler.clear();\n\n if (m_Loader)\n {\n try { m_Loader->close(); }\n catch (...) { }\n m_Loader.reset();\n }\n\n m_DownloadCond.signal();\n\n if (m_Curler.is_active())\n m_Page.get_image_fetcher().remove_handle(&m_Curler);\n}\n\n\/**\n * Returns true if the download was started\n **\/\nbool Image::start_download()\n{\n if (!m_Curler.is_active())\n {\n m_Page.get_image_fetcher().add_handle(&m_Curler);\n m_Loading = true;\n\n if (!m_isWebM)\n {\n m_Loader = Gdk::PixbufLoader::create();\n m_Loader->signal_area_prepared().connect(sigc::mem_fun(*this, &Image::on_area_prepared));\n m_Loader->signal_area_updated().connect(sigc::mem_fun(*this, &Image::on_area_updated));\n }\n\n return true;\n }\n\n return false;\n}\n\nvoid Image::on_write(const unsigned char *d, size_t l)\n{\n try\n {\n Glib::Threads::Mutex::Lock lock(m_DownloadMutex);\n m_Loader->write(d, l);\n }\n catch (const Gdk::PixbufError &ex)\n {\n std::cerr << ex.what() << std::endl;\n cancel_download();\n m_PixbufError = true;\n }\n}\n\nvoid Image::on_progress()\n{\n double c, t;\n m_Curler.get_progress(c, t);\n m_SignalProgress(c, t);\n}\n\nvoid Image::on_finished()\n{\n Glib::Threads::Mutex::Lock lock(m_DownloadMutex);\n\n m_Curler.save_file(m_Path);\n m_Curler.clear();\n\n if (m_Loader)\n {\n m_Loader->close();\n m_Loader.reset();\n }\n\n m_Loading = false;\n\n m_SignalPixbufChanged();\n m_DownloadCond.signal();\n}\n\nvoid Image::on_area_prepared()\n{\n m_ThumbnailLock.reader_lock();\n if (m_ThumbnailPixbuf && m_ThumbnailPixbuf != get_missing_pixbuf())\n {\n Glib::RefPtr pixbuf = m_Loader->get_pixbuf();\n m_ThumbnailPixbuf->composite(pixbuf, 0, 0, pixbuf->get_width(), pixbuf->get_height(), 0, 0,\n static_cast(pixbuf->get_width()) \/ m_ThumbnailPixbuf->get_width(),\n static_cast(pixbuf->get_height()) \/ m_ThumbnailPixbuf->get_height(),\n Gdk::INTERP_BILINEAR, 255);\n }\n m_ThumbnailLock.reader_unlock();\n\n m_Pixbuf = m_Loader->get_animation();\n\n if (!m_Curler.is_cancelled())\n m_SignalPixbufChanged();\n}\n\nvoid Image::on_area_updated(int, int, int, int)\n{\n using namespace std::chrono;\n if (!m_Curler.is_cancelled() && steady_clock::now() >= m_LastDraw + milliseconds(100))\n {\n m_SignalPixbufChanged();\n m_LastDraw = steady_clock::now();\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nbool isDirectory(char* directoryName) {\n\t\n\tstruct directoryInCurrent;\n\tint errorCheck;\n\tif (-1 == (errorCheck = stat(directoryName, directoryInCurrent))) {\n\n\t\tperror(\"stat failed\");\n\t\texit(0);\n\t}\n}\n\n\nint main(int argc, char** argv[]) {\n\t\n\tif (argc == 1) {\n\t\t\n\t\tchar const *dirName = \".\";\n\t\tDIR *dirp;\n\t\tif (!(dirp = opendir(dirName))) {\n\t\tcerr << \"Error(\" << errno << \") opening \" << dirName << endl;\n\t\t\treturn errno;\n\t\t}\n\n\t\tdirent *direntp;\n\t\twhile ((direntp = readdir(dirp))) {\n\t\t\tif (direntp->d_name[0] != '.') {\n\t\t\t\t\t\n\t\t\t\t\/\/cout << direntp->d_name << endl; \/\/ use stat here to find attributes of a file\n\t\t\t\tprintf(direntp->d_name, 8);\n\t\t\t\tcout << \" \";\n\t\t\t}\n\t\t}\n\t\tcout << endl;\n\t\tclosedir(dirp);\n\t}\t\n\t\n\telse {\n\t\t\n\t\tvector directories;\n\t\tvector flags;\n\t\tfor (unsigned i = 1; i < argc; ++i) {\n\t\t\t\n\t\t\tif (argv[i][0] == '-') {\n\t\t\t\tflags.push_back(argv[i]);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\t\n\n\n}\n\n\nmade functions to call ls#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nbool isDirectory(char* directoryName) {\n\t\n\tstruct directoryInCurrent;\n\tint errorCheck;\n\tif (-1 == (errorCheck = stat(directoryName, directoryInCurrent))) {\n\n\t\tperror(\"stat failed\");\n\t\treturn false;\n\t}\n\n\tif (directoryInCurrent.st_mode & S_IFDIR) {\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\nbool ls(char* directoryName) {\n\n\t\n\t\tchar const *dirName = \".\";\n\t\tDIR *dirp;\n\t\tif (!(dirp = opendir(dirName))) {\n\t\tcerr << \"Error(\" << errno << \") opening \" << dirName << endl;\n\t\t\treturn errno;\n\t\t}\n\n\t\tdirent *direntp;\n\t\twhile ((direntp = readdir(dirp))) {\n\t\t\tif (direntp->d_name[0] != '.') {\n\t\t\t\t\t\n\t\t\t\t\/\/cout << direntp->d_name << endl; \/\/ use stat here to find attributes of a file\n\t\t\t\tprintf(direntp->d_name, 8);\n\t\t\t\tcout << \" \";\n\t\t\t}\n\t\t}\n\t\tcout << endl;\n\t\tclosedir(dirp);\n}\nbool lsWithFlags(char* directoryName, vector flags) {\n\n\tbool isA = false;\n\tbool isL = false;\n\tbool isR = false;\n\tfor (unsigned i = 0; i < flags.size(); ++i) {\n\t\n\t\tif (flags.at(i) == \"a\") \n\t\t\tisA = true;\n\t\telse if (flags.at(i) == \"l\") \n\t\t\tisL = true;\n\t\telse if (flags.at(i) == \"R\")\n\t\t\tisR = true;\n\n\t}\n\tchar const *dirName = directoryName;\n\tDIR *dirp;\n\tif (!(dirp = opendir(dirName))) {\n\t\tcerr << \"Error(\" << errno << \") opening \" << dirName << endl;\n\t\treturn errno;\n\t}\n\n\tdirent *direntp;\n\twhile ((direntp = readdir(dirp))) {\n\t\tif (direntp->d_name[0] != '.') {\n\t\t\t\t\t\n\t\t\t\/\/cout << direntp->d_name << endl; \/\/ use stat here to find attributes of a file\n\t\t\tprintf(direntp->d_name, 8);\n\t\t\tcout << \" \";\n\t\t}\n\t}\n\tcout << endl;\n\tclosedir(dirp);\n}\n\nint main(int argc, char** argv[]) {\n\t\n\tif (argc == 1) {\n\t\t\n\t\tif (!ls(\".\")) {\n\t\t\texit(1);\n\t\t}\n\t}\t\n\t\n\telse {\n\t\t\n\t\tvector directories;\n\t\tvector flags;\n\t\tfor (unsigned i = 1; i < argc; ++i) {\n\t\t\t\n\t\t\tif (argv[i][0] == '-') {\n\t\t\t\tflags.push_back(argv[i]);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (isDirectory(\t\n\t\t\t}\n\t\t}\n\t}\n\t\n\n\n}\n\n\n<|endoftext|>"} {"text":"#ifndef __INCLUDED_BITFIELD_BITFIELD_HPP__\n#define __INCLUDED_BITFIELD_BITFIELD_HPP__\n\n#include \n#include \n#include \n\nnamespace bitfield {\n template\n class field {\n public:\n static constexpr uint32_t SIZE = Size;\n static constexpr uint32_t OFFSET = Offset;\n static constexpr uint32_t NEXT_OFFSET = SIZE + OFFSET;\n \n static constexpr uint32_t BYTE = bit_type(SIZE).ceil().byte();\n static constexpr uint32_t PADDING = bit_type(NEXT_OFFSET).ceil().diff(NEXT_OFFSET).bit();\n static constexpr uint32_t MASK = bit_type(SIZE).max_value() << PADDING;\n \n template\n using next_field = field;\n using container_type = container::array;\n \n field() = default;\n field(const field & v) { this->set(v.get()); }\n field(uint32_t v) { this->set(v); }\n \n field & operator =(const field & rop) {\n this->set(rop.get());\n return *this;\n }\n \n field & operator =(uint32_t rop) {\n this->set(rop);\n return *this;\n }\n \n operator uint32_t() const {\n return this->get();\n }\n \n \/\/ for Little-Endian\n uint32_t get() const {\n uint32_t value = 0x00;\n uint8_t * addr = bit_type(OFFSET).addr(this);\n uint8_t * value_addr = (uint8_t *)&value;\n \n for (uint32_t i=0; i < BYTE; ++i) {\n value_addr[BYTE-i-1] = addr[i];\n }\n \n value &= MASK;\n value >>= PADDING;\n return value;\n }\n \n \/\/ for Little-Endian\n void set(uint32_t value) {\n static constexpr uint32_t clear_mask = ~MASK;\n \n value <<= PADDING;\n value &= MASK;\n \n uint8_t * addr = bit_type(OFFSET).addr(this);\n uint8_t * value_addr = (uint8_t *)&value;\n uint8_t * clear_mask_addr = (uint8_t *)&clear_mask;\n \n for (uint32_t i=0; i < BYTE; ++i) {\n uint32_t j = BYTE-i-1;\n addr[i] &= clear_mask_addr[j];\n addr[i] |= value_addr[j];\n }\n }\n };\n}\n\n#endif \/\/ __INCLUDED_BITFIELD_BITFIELD_HPP__\nDeleted a copy constructor and copy assignment operator from the field.#ifndef __INCLUDED_BITFIELD_BITFIELD_HPP__\n#define __INCLUDED_BITFIELD_BITFIELD_HPP__\n\n#include \n#include \n#include \n\nnamespace bitfield {\n template\n class field {\n public:\n static constexpr uint32_t SIZE = Size;\n static constexpr uint32_t OFFSET = Offset;\n static constexpr uint32_t NEXT_OFFSET = SIZE + OFFSET;\n \n static constexpr uint32_t BYTE = bit_type(SIZE).ceil().byte();\n static constexpr uint32_t PADDING = bit_type(NEXT_OFFSET).ceil().diff(NEXT_OFFSET).bit();\n static constexpr uint32_t MASK = bit_type(SIZE).max_value() << PADDING;\n \n template\n using next_field = field;\n using container_type = container::array;\n \n field() = default;\n field(const field &) = delete;\n field & operator =(const field &) = delete;\n \n field(uint32_t v) { this->set(v); }\n \n field & operator =(uint32_t rop) {\n this->set(rop);\n return *this;\n }\n \n operator uint32_t() const {\n return this->get();\n }\n \n \/\/ for Little-Endian\n uint32_t get() const {\n uint32_t value = 0x00;\n uint8_t * addr = bit_type(OFFSET).addr(this);\n uint8_t * value_addr = (uint8_t *)&value;\n \n for (uint32_t i=0; i < BYTE; ++i) {\n value_addr[BYTE-i-1] = addr[i];\n }\n \n value &= MASK;\n value >>= PADDING;\n return value;\n }\n \n \/\/ for Little-Endian\n void set(uint32_t value) {\n static constexpr uint32_t clear_mask = ~MASK;\n \n value <<= PADDING;\n value &= MASK;\n \n uint8_t * addr = bit_type(OFFSET).addr(this);\n uint8_t * value_addr = (uint8_t *)&value;\n uint8_t * clear_mask_addr = (uint8_t *)&clear_mask;\n \n for (uint32_t i=0; i < BYTE; ++i) {\n uint32_t j = BYTE-i-1;\n addr[i] &= clear_mask_addr[j];\n addr[i] |= value_addr[j];\n }\n }\n };\n}\n\n#endif \/\/ __INCLUDED_BITFIELD_BITFIELD_HPP__\n<|endoftext|>"} {"text":"small fix<|endoftext|>"} {"text":"Small improvements of the behavior of bodies switched to static<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n * Copyright (c) 2012-, Open Perception, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * person_classifier.cpp\n * Created on: Nov 30, 2012\n * Author: Matteo Munaro\n *\/\n\n#include \n\n\/\/ Compute HOG descriptor:\nvoid hog(double *I, int h, int w, int nCh, int sBin, int oBin, int oGran, double* H);\n\nnamespace pcl\n{\n\tnamespace people\n\t{\n\n\t\tPersonClassifier::PersonClassifier () {}\n\n\t\tPersonClassifier::~PersonClassifier () {}\n\n\t\tvoid\n\t\tPersonClassifier::setSVM (int window_height, int window_width, std::vector SVM_weights, float SVM_offset)\n\t\t{\n\t\t\twindow_height_ = window_height;\n\t\t\twindow_width_ = window_width;\n\t\t\tSVM_weights_ = SVM_weights;\n\t\t\tSVM_offset_ = SVM_offset;\n\t\t}\n\n\t\tvoid\n\t\tPersonClassifier::getSVM (int& window_height, int& window_width, std::vector& SVM_weights, float& SVM_offset)\n\t\t{\n\t\t\twindow_height = window_height_;\n\t\t\twindow_width = window_width_;\n\t\t\tSVM_weights = SVM_weights_;\n\t\t\tSVM_offset = SVM_offset_;\n\t\t}\n\n\t\tvoid\n\t\tPersonClassifier::resize (pcl::PointCloud::Ptr& input_image, pcl::PointCloud::Ptr& output_image,\n\t\t\t\tint width, int height)\n\t\t{\n\t\t\tpcl::RGB new_point;\n\t\t\tnew_point.r = 0;\n\t\t\tnew_point.g = 0;\n\t\t\tnew_point.b = 0;\n\n\t\t\t\/\/ Allocate the vector of points:\n\t\t\toutput_image->points.resize(width*height, new_point);\n\t\t\toutput_image->height = height;\n\t\t\toutput_image->width = width;\n\n\t\t\t\/\/ Compute scale factor:\n\t\t\tfloat scale1 = float(height) \/ float(input_image->height);\n\t\t\tfloat scale2 = float(width) \/ float(input_image->width);\n\n\t\t\tEigen::Matrix3f T_inv;\n\t\t\tT_inv << 1\/scale1, 0, 0,\n\t\t\t\t\t 0, 1\/scale2, 0,\n\t\t\t\t\t 0, 0, 1;\n\n\t\t\tEigen::Vector3f A;\n\t\t\tint c1, c2, f1, f2;\n\t\t\tpcl::RGB g1, g2, g3, g4;\n\t\t\tfloat w1, w2;\n\t\t\tfor (unsigned int i = 0; i < height; i++)\t\t\/\/ for every row\n\t\t\t{\n\t\t\t\tfor (unsigned int j = 0; j < width; j++)\t\/\/ for every column\n\t\t\t\t{\n\t\t\t\t\tA = T_inv * Eigen::Vector3f(i, j, 1);\n\t\t\t\t\tc1 = ceil(A(0));\n\t\t\t\t\tf1 = floor(A(0));\n\t\t\t\t\tc2 = ceil(A(1));\n\t\t\t\t\tf2 = floor(A(1));\n\n\t\t\t\t\tif ((f1 < 0) || (c1 < 0) || (f1 >= input_image->height) || (c1 >= input_image->height) || (f2 < 0) || (c2 < 0) ||\n\t\t\t\t\t\t\t(f2 >= input_image->width) || (c2 >= input_image->width))\n\t\t\t\t\t{\t\/\/ if out of range, continue\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tg1 = (*input_image)(f2, c1);\n\t\t\t\t\tg3 = (*input_image)(f2, f1);\n\t\t\t\t\tg4 = (*input_image)(c2, f1);\n\t\t\t\t\tg2 = (*input_image)(c2, c1);\n\n\t\t\t\t\tw1 = (A(0) - f1);\n\t\t\t\t\tw2 = (A(1) - f2);\n\t\t\t\t\tnew_point.r = int((1 - w1) * ((1 - w2) * g1.r + w2 * g4.r) + w1 * ((1 - w2) * g3.r + w2 * g4.r));\n\t\t\t\t\tnew_point.g = int((1 - w1) * ((1 - w2) * g1.g + w2 * g4.g) + w1 * ((1 - w2) * g3.g + w2 * g4.g));\n\t\t\t\t\tnew_point.b = int((1 - w1) * ((1 - w2) * g1.b + w2 * g4.b) + w1 * ((1 - w2) * g3.b + w2 * g4.b));\n\n\t\t\t\t\t\/\/ Insert the point in the output image:\n\t\t\t\t\t(*output_image)(j,i) = new_point;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid\n\t\tPersonClassifier::copyMakeBorder (pcl::PointCloud::Ptr& input_image, pcl::PointCloud::Ptr& output_image,\n\t\t\t\tint xmin, int ymin, int width, int height)\n\t\t{\n\t\t\tpcl::RGB black_point;\n\t\t\tblack_point.r = 0;\n\t\t\tblack_point.g = 0;\n\t\t\tblack_point.b = 0;\n\t\t\toutput_image->points.resize(height*width, black_point);\n\t\t\toutput_image->width = width;\n\t\t\toutput_image->height = height;\n\n\t\t\tint x_start_in = std::max(0, xmin);\n\t\t\tint x_end_in = std::min(int(input_image->width-1), xmin+width-1);\n\t\t\tint y_start_in = std::max(0, ymin);\n\t\t\tint y_end_in = std::min(int(input_image->height-1), ymin+height-1);\n\n\t\t\tint x_start_out = std::max(0, -xmin);\n\t\t\tint x_end_out = x_start_out + (x_end_in - x_start_in);\n\t\t\tint y_start_out = std::max(0, -ymin);\n\t\t\tint y_end_out = y_start_out + (y_end_in - y_start_in);\n\n\t\t\tfor (unsigned int i = 0; i < (y_end_in - y_start_in + 1); i++)\n\t\t\t{\n\t\t\t\tfor (unsigned int j = 0; j < (x_end_in - x_start_in + 1); j++)\n\t\t\t\t{\n\t\t\t\t\t(*output_image)(x_start_out + j, y_start_out + i) = (*input_image)(x_start_in + j, y_start_in + i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdouble\n\t\tPersonClassifier::evaluate (float height_person, float xc, float yc, pcl::PointCloud::Ptr& image)\n\t\t{\n\t\t\tif (SVM_weights_.size() == 0)\n\t\t\t{\n\t\t\t\tPCL_ERROR (\"[pcl::people::PersonClassifier::evaluate] SVM has not been set!\\n\");\n\t\t\t\treturn (-1000);\n\t\t\t}\n\n\t\t\tint height = floor((height_person * window_height_) \/ (0.75 * window_height_) + 0.5);\t\/\/ floor(i+0.5) = round(i)\n\t\t\tint width = floor((height_person * window_width_) \/ (0.75 * window_height_) + 0.5);\n\t\t\tint xmin = floor(xc - width \/ 2 + 0.5);\n\t\t\tint ymin = floor(yc - height \/ 2 + 0.5);\n\n\t\t\t\/\/ If near the border, fill with black\n\t\t\tpcl::PointCloud::Ptr box(new pcl::PointCloud);\n\t\t\tcopyMakeBorder(image, box, xmin, ymin, width, height);\n\n\t\t\t\/\/ Make the image match the correct size\n\t\t\tpcl::PointCloud::Ptr sample(new pcl::PointCloud);\n\t\t\tresize(box, sample, window_width_, window_height_);\n\n\t\t\t\/\/Convert the image to Matlab format\n\t\t\tdouble* sample_double = new double[sample->width * sample->height * 3];\n\t\t\tint delta = sample->height * sample->width;\n\t\t\tfor(int row = 0; row < sample->height; row++)\n\t\t\t{\n\t\t\t\tfor(int col = 0; col < sample->width; col++)\n\t\t\t\t{\n\t\t\t\t\tsample_double[row + sample->height * col] = (double) ((*sample)(col, row).r); \/\/ptr[col * 3 + 2];\n\t\t\t\t\tsample_double[row + sample->height * col + delta] = (double) ((*sample)(col, row).g); \/\/ptr[col * 3 + 1];\n\t\t\t\t\tsample_double[row + sample->height * col + delta * 2] = (double) ((*sample)(col, row).b); \/\/ptr[col * 3];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdouble *ris = new double[SVM_weights_.size()];\n\n\t\t\t\/\/Calculate HOG descriptor\n\t\t\thog(sample_double, sample->height, sample->width, 3, 8, 9, 10, ris);\n\n\t\t\t\/\/Calculate confidence value by dot product\n\t\t\tdouble confidence = 0.0;\n\t\t\tfor(uint i = 0; i < SVM_weights_.size(); i++)\n\t\t\t{\n\t\t\t\tconfidence += SVM_weights_[i] * ris[i];\n\t\t\t}\n\t\t\t\/\/Confidence correction\n\t\t\tconfidence -= SVM_offset_;\n\n\t\t\tdelete[] ris;\n\t\t\tdelete[] sample_double;\n\n\t\t\treturn confidence;\n\t\t}\n\n\t\tdouble\n\t\tPersonClassifier::evaluate (pcl::PointCloud::Ptr& image, Eigen::Vector3f& bottom, Eigen::Vector3f& top, Eigen::Vector3f& centroid,\n\t\t\t\t\t\t\tEigen::Matrix3f intrinsics_matrix, bool vertical)\n\t\t{\n\t\t\tfloat pixel_height;\n\t\t\tfloat pixel_width;\n\t\t\tif (not vertical)\n\t\t\t{\n\t\t\t\tpixel_height = bottom(1) - top(1);\n\t\t\t\tpixel_width = pixel_height \/ 2.0f;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpixel_width = top(0) - bottom(0);\n\t\t\t\tpixel_height = pixel_width \/ 2.0f;\n\t\t\t}\n\t\t\tfloat pixel_xc = centroid(0);\n\t\t\tfloat pixel_yc = centroid(1);\n\n\t\t\tif (not vertical)\n\t\t\t{\n\t\t\t\treturn (evaluate(pixel_height, pixel_xc, pixel_yc, image));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn (evaluate(pixel_width, pixel_yc, image->height-pixel_xc+1, image));\n\t\t\t}\n\t\t}\n\t} \/* namespace people *\/\n} \/* namespace pcl *\/\nChanged indentation to PCL style for PersonClassifier\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n * Copyright (c) 2012-, Open Perception, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * person_classifier.cpp\n * Created on: Nov 30, 2012\n * Author: Matteo Munaro\n *\/\n\n#include \n\n\/\/ Compute HOG descriptor:\nvoid hog(double *I, int h, int w, int nCh, int sBin, int oBin, int oGran, double* H);\n\nnamespace pcl\n{\n namespace people\n {\n\n PersonClassifier::PersonClassifier () {}\n\n PersonClassifier::~PersonClassifier () {}\n\n void\n PersonClassifier::setSVM (int window_height, int window_width, std::vector SVM_weights, float SVM_offset)\n {\n window_height_ = window_height;\n window_width_ = window_width;\n SVM_weights_ = SVM_weights;\n SVM_offset_ = SVM_offset;\n }\n\n void\n PersonClassifier::getSVM (int& window_height, int& window_width, std::vector& SVM_weights, float& SVM_offset)\n {\n window_height = window_height_;\n window_width = window_width_;\n SVM_weights = SVM_weights_;\n SVM_offset = SVM_offset_;\n }\n\n void\n PersonClassifier::resize (pcl::PointCloud::Ptr& input_image,\n pcl::PointCloud::Ptr& output_image,\n int width,\n int height)\n {\n pcl::RGB new_point;\n new_point.r = 0;\n new_point.g = 0;\n new_point.b = 0;\n\n \/\/ Allocate the vector of points:\n output_image->points.resize(width*height, new_point);\n output_image->height = height;\n output_image->width = width;\n\n \/\/ Compute scale factor:\n float scale1 = float(height) \/ float(input_image->height);\n float scale2 = float(width) \/ float(input_image->width);\n\n Eigen::Matrix3f T_inv;\n T_inv << 1\/scale1, 0, 0,\n 0, 1\/scale2, 0,\n 0, 0, 1;\n\n Eigen::Vector3f A;\n int c1, c2, f1, f2;\n pcl::RGB g1, g2, g3, g4;\n float w1, w2;\n for (unsigned int i = 0; i < height; i++)\t\t\/\/ for every row\n {\n for (unsigned int j = 0; j < width; j++)\t\/\/ for every column\n {\n A = T_inv * Eigen::Vector3f(i, j, 1);\n c1 = ceil(A(0));\n f1 = floor(A(0));\n c2 = ceil(A(1));\n f2 = floor(A(1));\n\n if ( (f1 < 0) ||\n (c1 < 0) ||\n (f1 >= input_image->height) ||\n (c1 >= input_image->height) ||\n (f2 < 0) ||\n (c2 < 0) ||\n (f2 >= input_image->width) ||\n (c2 >= input_image->width))\n { \/\/ if out of range, continue\n continue;\n }\n\n g1 = (*input_image)(f2, c1);\n g3 = (*input_image)(f2, f1);\n g4 = (*input_image)(c2, f1);\n g2 = (*input_image)(c2, c1);\n\n w1 = (A(0) - f1);\n w2 = (A(1) - f2);\n new_point.r = int((1 - w1) * ((1 - w2) * g1.r + w2 * g4.r) + w1 * ((1 - w2) * g3.r + w2 * g4.r));\n new_point.g = int((1 - w1) * ((1 - w2) * g1.g + w2 * g4.g) + w1 * ((1 - w2) * g3.g + w2 * g4.g));\n new_point.b = int((1 - w1) * ((1 - w2) * g1.b + w2 * g4.b) + w1 * ((1 - w2) * g3.b + w2 * g4.b));\n\n \/\/ Insert the point in the output image:\n (*output_image)(j,i) = new_point;\n }\n }\n }\n\n void\n PersonClassifier::copyMakeBorder (pcl::PointCloud::Ptr& input_image,\n pcl::PointCloud::Ptr& output_image,\n int xmin,\n int ymin,\n int width,\n int height)\n {\n pcl::RGB black_point;\n black_point.r = 0;\n black_point.g = 0;\n black_point.b = 0;\n output_image->points.resize(height*width, black_point);\n output_image->width = width;\n output_image->height = height;\n\n int x_start_in = std::max(0, xmin);\n int x_end_in = std::min(int(input_image->width-1), xmin+width-1);\n int y_start_in = std::max(0, ymin);\n int y_end_in = std::min(int(input_image->height-1), ymin+height-1);\n\n int x_start_out = std::max(0, -xmin);\n int x_end_out = x_start_out + (x_end_in - x_start_in);\n int y_start_out = std::max(0, -ymin);\n int y_end_out = y_start_out + (y_end_in - y_start_in);\n\n for (unsigned int i = 0; i < (y_end_in - y_start_in + 1); i++)\n {\n for (unsigned int j = 0; j < (x_end_in - x_start_in + 1); j++)\n {\n (*output_image)(x_start_out + j, y_start_out + i) = (*input_image)(x_start_in + j, y_start_in + i);\n }\n }\n }\n\n double\n PersonClassifier::evaluate (float height_person,\n float xc,\n float yc,\n pcl::PointCloud::Ptr& image)\n {\n if (SVM_weights_.size() == 0)\n {\n PCL_ERROR (\"[pcl::people::PersonClassifier::evaluate] SVM has not been set!\\n\");\n return (-1000);\n }\n\n int height = floor((height_person * window_height_) \/ (0.75 * window_height_) + 0.5);\t\/\/ floor(i+0.5) = round(i)\n int width = floor((height_person * window_width_) \/ (0.75 * window_height_) + 0.5);\n int xmin = floor(xc - width \/ 2 + 0.5);\n int ymin = floor(yc - height \/ 2 + 0.5);\n\n \/\/ If near the border, fill with black\n pcl::PointCloud::Ptr box(new pcl::PointCloud);\n copyMakeBorder(image, box, xmin, ymin, width, height);\n\n \/\/ Make the image match the correct size\n pcl::PointCloud::Ptr sample(new pcl::PointCloud);\n resize(box, sample, window_width_, window_height_);\n\n \/\/Convert the image to Matlab format\n double* sample_double = new double[sample->width * sample->height * 3]; \n int delta = sample->height * sample->width;\n for(int row = 0; row < sample->height; row++)\n {\n for(int col = 0; col < sample->width; col++)\n {\n sample_double[row + sample->height * col] = (double) ((*sample)(col, row).r); \/\/ptr[col * 3 + 2];\n sample_double[row + sample->height * col + delta] = (double) ((*sample)(col, row).g); \/\/ptr[col * 3 + 1];\n sample_double[row + sample->height * col + delta * 2] = (double) ((*sample)(col, row).b); \/\/ptr[col * 3];\n }\n }\n\n double *ris = new double[SVM_weights_.size()];\n\n \/\/Calculate HOG descriptor\n hog(sample_double, sample->height, sample->width, 3, 8, 9, 10, ris);\n\n \/\/Calculate confidence value by dot product\n double confidence = 0.0;\n for(uint i = 0; i < SVM_weights_.size(); i++)\n {\n \tconfidence += SVM_weights_[i] * ris[i];\n }\n \/\/Confidence correction\n confidence -= SVM_offset_;\n\n delete[] ris;\n delete[] sample_double;\n\n return confidence;\n }\n\n double\n PersonClassifier::evaluate (pcl::PointCloud::Ptr& image,\n Eigen::Vector3f& bottom,\n Eigen::Vector3f& top,\n Eigen::Vector3f& centroid,\n Eigen::Matrix3f intrinsics_matrix,\n bool vertical)\n {\n float pixel_height;\n float pixel_width;\n if (not vertical)\n {\n pixel_height = bottom(1) - top(1);\n pixel_width = pixel_height \/ 2.0f;\n }\n else\n {\n pixel_width = top(0) - bottom(0);\n pixel_height = pixel_width \/ 2.0f;\n }\n float pixel_xc = centroid(0);\n float pixel_yc = centroid(1);\n\n if (not vertical)\n {\n return (evaluate(pixel_height, pixel_xc, pixel_yc, image));\n }\n else\n {\n return (evaluate(pixel_width, pixel_yc, image->height-pixel_xc+1, image));\n }\n }\n } \/* namespace people *\/\n} \/* namespace pcl *\/\n<|endoftext|>"} {"text":"Fix for default mapper node count when running with -ll:cpu 0.<|endoftext|>"} {"text":"#include \n\n#include \"photoeffects.hpp\"\n\nusing namespace cv;\n\nTEST(photoeffects, SepiaFakeTest) {\n Mat src(10, 10, CV_8UC1), dst;\n\n EXPECT_EQ(0, sepia(src, dst));\n}\n\nTEST(photoeffects, SepiaFailTest) {\n Mat src(10, 10, CV_8UC3), dst;\n\n EXPECT_EQ(1, sepia(src, dst));\n}\n\n\/*\nTEST(photoeffects, SepiaTest) {\n Mat src(10, 10, CV_8UC1), dst, hsvDst;\n vector channels(3);\n\n EXPECT_EQ(0, sepia(src, dst));\n cvtColor(dst, hsvDst, CV_BGR2HSV);\n split(hsvDst, channels);\n EXPECT_EQ(src.at(0, 0) + 20, channels[2].at(0, 0));\n}\n*\/\nTest was restored, interval [-1,+1] was set for hue, saturation and value.#include \n\n#include \"photoeffects.hpp\"\n\nusing namespace cv;\n\nTEST(photoeffects, SepiaFakeTest) {\n Mat src(10, 10, CV_8UC1), dst;\n\n EXPECT_EQ(0, sepia(src, dst));\n}\n\nTEST(photoeffects, SepiaFailTest) {\n Mat src(10, 10, CV_8UC3), dst;\n\n EXPECT_EQ(1, sepia(src, dst));\n}\n\nTEST(photoeffects, SepiaTest) {\n Mat src(10, 10, CV_8UC1), dst, hsvDst;\n vector channels(3);\n\n EXPECT_EQ(0, sepia(src, dst));\n cvtColor(dst, hsvDst, CV_BGR2HSV);\n split(hsvDst, channels);\n EXPECT_LE(19 - 1, channels[0].at(0, 0)); \/\/ hue = 19\n EXPECT_GE(19 + 1, channels[0].at(0, 0));\n EXPECT_LE(78 - 1, channels[1].at(0, 0)); \/\/ saturation = 78\n EXPECT_GE(78 + 1, channels[1].at(0, 0));\n EXPECT_LE(src.at(0, 0) + 20 - 1, channels[2].at(0, 0));\n EXPECT_GE(src.at(0, 0) + 20 + 1, channels[2].at(0, 0));\n}\n\n<|endoftext|>"} {"text":"\/\/ stdafx.cpp : source file that includes just the standard includes\n\/\/ Base.UnitTest.pch will be the pre-compiled header\n\/\/ stdafx.obj will contain the pre-compiled type information\n\n#include \"stdafx.h\"\n\n\/\/ TODO: reference any additional headers you need in STDAFX.H\n\/\/ and not in this file\nadded doxygen header\/\/\n\/\/ RemotePhotoTool - remote camera control software\n\/\/ Copyright (C) 2008-2013 Michael Fink\n\/\/\n\/\/! \\file Base\\Base.UnitTest\\stdafx.cpp Precompiled header support\n\/\/\n\n\/\/ includes\n#include \"stdafx.h\"\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright (c) 2014 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n\n#include \"icdar\/icdar_reader.hpp\"\n\nconstexpr const std::size_t context = 5;\nconstexpr const std::size_t window = context * 2 + 1;\n\nint main(){\n auto dataset = icdar::read_2013_dataset(\n \"\/home\/wichtounet\/datasets\/icdar_2013_natural\/train\",\n \"\/home\/wichtounet\/datasets\/icdar_2013_natural\/test\", 5, 1);\n\n if(dataset.training_labels.empty() || dataset.training_images.empty()){\n std::cout << \"Problem while reading the dataset\" << std::endl;\n\n return -1;\n }\n\n std::cout << dataset.training_images.size() << \" training images\" << std::endl;\n std::cout << dataset.test_images.size() << \" test images\" << std::endl;\n\n \/\/TODO What about randomization ? \n\n for(auto& image : dataset.training_images){\n std::vector> windows;\n windows.reserve(image.width * image.height);\n\n for(std::size_t i = context; i < image.width - context; ++i){\n for(std::size_t j = context; j < image.height - context; ++j){\n\n windows.emplace_back(window * window);\n\n for(std::size_t a = i - context; a < i - context + window; ++a){\n for(std::size_t b = j - context; b < j - context + window; ++b){\n auto w_i = (a - (i - context));\n auto w_j = (b - (j - context));\n windows.back().at(w_i * window + w_j) = image.pixels.at(a * image.height + b).r;\n }\n }\n }\n }\n\n std::cout << windows.size() << \" windows extracted\" << std::endl;\n }\n\n return 0;\n}\nPrepare CDBN\/\/=======================================================================\n\/\/ Copyright (c) 2014 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n\n#include \"dll\/conv_rbm.hpp\"\n#include \"dll\/conv_dbn.hpp\"\n#include \"dll\/cpp_utils\/algorithm.hpp\"\n\n#include \"icdar\/icdar_reader.hpp\"\n\nconstexpr const std::size_t context = 5;\nconstexpr const std::size_t window = context * 2 + 1;\n\nint main(){\n auto dataset = icdar::read_2013_dataset(\n \"\/home\/wichtounet\/datasets\/icdar_2013_natural\/train\",\n \"\/home\/wichtounet\/datasets\/icdar_2013_natural\/test\", 5, 1);\n\n if(dataset.training_labels.empty() || dataset.training_images.empty()){\n std::cout << \"Problem while reading the dataset\" << std::endl;\n\n return -1;\n }\n\n std::cout << dataset.training_images.size() << \" training images\" << std::endl;\n std::cout << dataset.test_images.size() << \" test images\" << std::endl;\n\n \/\/TODO What about randomization ?\n\n std::vector> windows;\n\n for(auto& image : dataset.training_images){\n windows.reserve(windows.size() + image.width * image.height);\n\n for(std::size_t i = context; i < image.width - context; ++i){\n for(std::size_t j = context; j < image.height - context; ++j){\n\n windows.emplace_back(window * window);\n\n for(std::size_t a = i - context; a < i - context + window; ++a){\n for(std::size_t b = j - context; b < j - context + window; ++b){\n auto w_i = (a - (i - context));\n auto w_j = (b - (j - context));\n windows.back().at(w_i * window + w_j) = image.pixels.at(a * image.height + b).r;\n }\n }\n }\n }\n }\n\n \/\/TODO Normalization\n \/\/TODO Gaussian\n\n std::cout << windows.size() << \" windows extracted\" << std::endl;\n\n typedef dll::conv_dbn_desc<\n dll::dbn_layers<\n dll::conv_rbm_desc, dll::weight_decay, dll::sparsity>::rbm_t\n >>::dbn_t dbn_t;\n\n auto dbn = std::make_unique();\n\n dbn->layer<0>().pbias = 0.05;\n dbn->layer<0>().pbias_lambda = 50;\n\n dbn->pretrain(windows, 50);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n\t[2015\/7\/31] コマンドの実行は仮想関数?関数ポインタ?\n\t\tRelease ビルド 100000000 回の単純呼び出しで、\n\t\t仮想関数 : 450ms\n\t\t関数ポインタ : 400ms\n\t\t微々たる差だが、関数ポインタが少しだけ有利。\n*\/\n#pragma once\n\n#include \"..\/Internal.h\"\n#include \"Device\/GraphicsDriverInterface.h\"\n#include \n#include \"RenderingCommand.h\"\n\nLN_NAMESPACE_BEGIN\nLN_NAMESPACE_GRAPHICS_BEGIN\n\n\n\/\/=============================================================================\n\/\/ RenderingCommand\n\/\/=============================================================================\n\/\/void* RenderingCommand::operator new(size_t size, RenderingCommandList* cmmandList)\n\/\/{\n\/\/\tsize_t dataIdx = cmmandList->Alloc(size, NULL);\n\/\/\tRenderingCommand* cmd = (RenderingCommand*)cmmandList->GetBuffer(dataIdx);\n\/\/\tcmd->m_commandList = cmmandList;\n\/\/\tcmmandList->m_commandList.Add(dataIdx);\n\/\/\treturn cmd;\n\/\/}\n\/\/\n\/\/void RenderingCommand::operator delete(void* ptr, RenderingCommandList* cmmandList)\n\/\/{\n\/\/}\n\n\/\/=============================================================================\n\/\/ RenderingCommandList\n\/\/=============================================================================\n\n#define CREATE_COMMAND(name) \\\n\tsize_t dataIdx = Alloc(sizeof(name##Command), NULL); \\\n\tname##Command* cmd = (name##Command*)&(m_commandDataBuffer.GetData()[dataIdx]); \\\n\tcmd->Type = CommandType_##name; \\\n\tm_commandList.Add(dataIdx);\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nRenderingCommandList::RenderingCommandList()\n\t: m_commandList()\n\t, m_commandDataBuffer()\n\t, m_commandDataBufferUsed(0)\n\t, m_extDataBuffer()\n\t, m_extDataBufferUsed(0)\n\t, m_markGCList()\n\t, m_currentDevice(NULL)\n\t, m_currentRenderer(NULL)\n\t, m_running(false)\n\t, m_idling(true)\n{\n\tm_commandList.Reserve(DataBufferReserve);\t\/\/ 適当に\n\tm_commandDataBuffer.Resize(DataBufferReserve, false);\n\tm_commandDataBufferUsed = 0;\n\tm_extDataBuffer.Resize(DataBufferReserve, false);\n\tm_extDataBufferUsed = 0;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nRenderingCommandList::~RenderingCommandList()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid RenderingCommandList::Execute(Driver::IGraphicsDevice* device\/*Driver::IRenderer* renderer*\/)\n{\n\tLN_RC_TRACE(\"RenderingCommandList::Execute() s %p %d\\n\", this, m_commandList.GetCount());\n\t\/\/ この関数は描画スレッドから呼ばれる\n\n\tm_currentDevice = device;\n\tm_currentRenderer = device->GetRenderer();\n\tLN_FOREACH(size_t dataIdx, m_commandList)\n\t{\n\t\t((RenderingCommand*)GetCommand(dataIdx))->Execute();\n\t}\n\tLN_RC_TRACE(\"RenderingCommandList::Execute() e %p\\n\", this);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid RenderingCommandList::PostExecute()\n{\n\t\/\/LN_RC_TRACE(\"RenderingCommandList::PostExecute() s %p\\n\", this);\n\t\/\/LN_FOREACH(size_t dataIdx, m_commandList)\n\t\/\/{\n\t\/\/\t((RenderingCommand*)GetCommand(dataIdx))->Release(this);\n\t\/\/\t((RenderingCommand*)GetCommand(dataIdx))->~RenderingCommand();\n\t\/\/}\n\t\/\/LN_RC_TRACE(\"RenderingCommandList::PostExecute() e %p\\n\", this);\n\tm_commandList.Clear();\n\tm_commandDataBufferUsed = 0;\n\n\n\tLN_FOREACH(RefObject* obj, m_markGCList)\n\t{\n\t\tobj->Release();\n\t}\n\tm_markGCList.Clear();\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nRenderingCommandList::DataHandle RenderingCommandList::AllocCommand(size_t byteCount, const void* copyData)\n{\n\t\/\/ バッファが足りなければ拡張する\n\tif (m_commandDataBufferUsed + byteCount > m_commandDataBuffer.GetSize()) {\n\t\tsize_t newSize = m_commandDataBuffer.GetSize() + std::max(m_commandDataBuffer.GetSize(), byteCount);\t\/\/ 最低でも byteCount 分を拡張する\n\t\tm_commandDataBuffer.Resize(newSize, false);\n\t}\n\n\tif (copyData != NULL)\n\t{\n\t\tbyte_t* ptr = &(m_commandDataBuffer.GetData()[m_commandDataBufferUsed]);\n\t\tsize_t size = m_commandDataBuffer.GetSize() - m_commandDataBufferUsed;\n\t\tmemcpy_s(ptr, size, copyData, byteCount);\n\t}\n\n\tsize_t dataIdx = m_commandDataBufferUsed;\n\tm_commandDataBufferUsed += byteCount;\n\n\treturn dataIdx;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nRenderingCommandList::DataHandle RenderingCommandList::AllocExtData(size_t byteCount, const void* copyData)\n{\n\t\/\/ バッファが足りなければ拡張する\n\tif (m_extDataBufferUsed + byteCount > m_extDataBuffer.GetSize()) {\n\t\tsize_t newSize = m_extDataBuffer.GetSize() + std::max(m_extDataBuffer.GetSize(), byteCount);\t\/\/ 最低でも byteCount 分を拡張する\n\t\tm_extDataBuffer.Resize(newSize, false);\n\t}\n\n\tif (copyData != NULL)\n\t{\n\t\tbyte_t* ptr = &(m_extDataBuffer.GetData()[m_extDataBufferUsed]);\n\t\tsize_t size = m_extDataBuffer.GetSize() - m_extDataBufferUsed;\n\t\tmemcpy_s(ptr, size, copyData, byteCount);\n\t}\n\n\tsize_t dataIdx = m_extDataBufferUsed;\n\tm_extDataBufferUsed += byteCount;\n\n\treturn dataIdx;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid* RenderingCommandList::GetExtData(DataHandle bufferIndex)\n{\n\treturn &(m_extDataBuffer.GetData()[bufferIndex]);\n}\n\nLN_NAMESPACE_GRAPHICS_END\nLN_NAMESPACE_END\ncomment\/*\n\t[2015\/7\/31] コマンドの実行は仮想関数?関数ポインタ?\n\t\tRelease ビルド 100000000 回の単純呼び出しで、\n\t\t仮想関数 : 450ms\n\t\t関数ポインタ : 400ms\n\t\t微々たる差だが、関数ポインタが少しだけ有利。\n*\/\n#pragma once\n\n#include \"..\/Internal.h\"\n#include \"Device\/GraphicsDriverInterface.h\"\n#include \n#include \"RenderingCommand.h\"\n\nLN_NAMESPACE_BEGIN\nLN_NAMESPACE_GRAPHICS_BEGIN\n\n\n\/\/=============================================================================\n\/\/ RenderingCommand\n\/\/=============================================================================\n\/\/void* RenderingCommand::operator new(size_t size, RenderingCommandList* cmmandList)\n\/\/{\n\/\/\tsize_t dataIdx = cmmandList->Alloc(size, NULL);\n\/\/\tRenderingCommand* cmd = (RenderingCommand*)cmmandList->GetBuffer(dataIdx);\n\/\/\tcmd->m_commandList = cmmandList;\n\/\/\tcmmandList->m_commandList.Add(dataIdx);\n\/\/\treturn cmd;\n\/\/}\n\/\/\n\/\/void RenderingCommand::operator delete(void* ptr, RenderingCommandList* cmmandList)\n\/\/{\n\/\/}\n\n\/\/=============================================================================\n\/\/ RenderingCommandList\n\/\/=============================================================================\n\n#define CREATE_COMMAND(name) \\\n\tsize_t dataIdx = Alloc(sizeof(name##Command), NULL); \\\n\tname##Command* cmd = (name##Command*)&(m_commandDataBuffer.GetData()[dataIdx]); \\\n\tcmd->Type = CommandType_##name; \\\n\tm_commandList.Add(dataIdx);\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nRenderingCommandList::RenderingCommandList()\n\t: m_commandList()\n\t, m_commandDataBuffer()\n\t, m_commandDataBufferUsed(0)\n\t, m_extDataBuffer()\n\t, m_extDataBufferUsed(0)\n\t, m_markGCList()\n\t, m_currentDevice(NULL)\n\t, m_currentRenderer(NULL)\n\t, m_running(false)\n\t, m_idling(true)\n{\n\tm_commandList.Reserve(DataBufferReserve);\t\/\/ 適当に\n\tm_commandDataBuffer.Resize(DataBufferReserve, false);\n\tm_commandDataBufferUsed = 0;\n\tm_extDataBuffer.Resize(DataBufferReserve, false);\n\tm_extDataBufferUsed = 0;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nRenderingCommandList::~RenderingCommandList()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid RenderingCommandList::Execute(Driver::IGraphicsDevice* device\/*Driver::IRenderer* renderer*\/)\n{\n\tLN_RC_TRACE(\"RenderingCommandList::Execute() s %p %d\\n\", this, m_commandList.GetCount());\n\t\/\/ この関数は描画スレッドから呼ばれる\n\n\tm_currentDevice = device;\n\tm_currentRenderer = device->GetRenderer();\n\tLN_FOREACH(size_t dataIdx, m_commandList)\n\t{\n\t\t((RenderingCommand*)GetCommand(dataIdx))->Execute();\n\t}\n\tLN_RC_TRACE(\"RenderingCommandList::Execute() e %p\\n\", this);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid RenderingCommandList::PostExecute()\n{\n\t\/\/LN_RC_TRACE(\"RenderingCommandList::PostExecute() s %p\\n\", this);\n\t\/\/LN_FOREACH(size_t dataIdx, m_commandList)\n\t\/\/{\n\t\/\/\t((RenderingCommand*)GetCommand(dataIdx))->Release(this);\n\t\/\/\t((RenderingCommand*)GetCommand(dataIdx))->~RenderingCommand();\n\t\/\/}\n\t\/\/LN_RC_TRACE(\"RenderingCommandList::PostExecute() e %p\\n\", this);\n\tm_commandList.Clear();\n\tm_commandDataBufferUsed = 0;\n\n\n\tLN_FOREACH(RefObject* obj, m_markGCList)\n\t{\n\t\tobj->Release();\n\t}\n\tm_markGCList.Clear();\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nRenderingCommandList::DataHandle RenderingCommandList::AllocCommand(size_t byteCount, const void* copyData)\n{\n\t\/\/ バッファが足りなければ拡張する\n\tif (m_commandDataBufferUsed + byteCount > m_commandDataBuffer.GetSize()) {\n\t\tsize_t newSize = m_commandDataBuffer.GetSize() + std::max(m_commandDataBuffer.GetSize(), byteCount);\t\/\/ 最低でも byteCount 分を拡張する\n\t\tm_commandDataBuffer.Resize(newSize, false);\n\t}\n\n\tif (copyData != NULL)\n\t{\n\t\tbyte_t* ptr = &(m_commandDataBuffer.GetData()[m_commandDataBufferUsed]);\n\t\tsize_t size = m_commandDataBuffer.GetSize() - m_commandDataBufferUsed;\n\t\tmemcpy_s(ptr, size, copyData, byteCount);\n\t}\n\n\tsize_t dataIdx = m_commandDataBufferUsed;\n\tm_commandDataBufferUsed += byteCount;\n\n\treturn dataIdx;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nRenderingCommandList::DataHandle RenderingCommandList::AllocExtData(size_t byteCount, const void* copyData)\n{\n\t\/\/ TODO: Bug: 確保メモリ量が増え続けている。\n\n\t\/\/ バッファが足りなければ拡張する\n\tif (m_extDataBufferUsed + byteCount > m_extDataBuffer.GetSize()) {\n\t\tsize_t newSize = m_extDataBuffer.GetSize() + std::max(m_extDataBuffer.GetSize(), byteCount);\t\/\/ 最低でも byteCount 分を拡張する\n\t\tm_extDataBuffer.Resize(newSize, false);\n\t}\n\n\tif (copyData != NULL)\n\t{\n\t\tbyte_t* ptr = &(m_extDataBuffer.GetData()[m_extDataBufferUsed]);\n\t\tsize_t size = m_extDataBuffer.GetSize() - m_extDataBufferUsed;\n\t\tmemcpy_s(ptr, size, copyData, byteCount);\n\t}\n\n\tsize_t dataIdx = m_extDataBufferUsed;\n\tm_extDataBufferUsed += byteCount;\n\n\treturn dataIdx;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid* RenderingCommandList::GetExtData(DataHandle bufferIndex)\n{\n\treturn &(m_extDataBuffer.GetData()[bufferIndex]);\n}\n\nLN_NAMESPACE_GRAPHICS_END\nLN_NAMESPACE_END\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace v8;\n\nconst unsigned int QRC_MAX_SIZE[] = { 2938, 2319, 1655, 1268 };\n\nstruct Qrc_Params {\n const char* data;\n QRecLevel ec_level;\n int dot_size;\n int margin;\n int version;\n\n Qrc_Params(std::string p_data, QRecLevel p_ec_level = QR_ECLEVEL_L, int p_dot_size = 3, int p_margin = 4, int p_version = 0) {\n data = new char[p_data.length() + 1];\n strcpy((char*)data, p_data.c_str());\n ec_level = p_ec_level;\n dot_size = p_dot_size;\n margin = p_margin;\n version = p_version;\n }\n\n ~Qrc_Params() {\n delete data;\n }\n};\n\n\nQrc_Params* ValidateArgs(const Arguments& args) {\n struct Qrc_Params* params;\n\n if (args.Length() < 1 || !args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"No source string given\")));\n return NULL;\n }\n std::string data(*v8::String::Utf8Value(args[0]));\n if (data.length() < 1 || data.length() > QRC_MAX_SIZE[0]) {\n ThrowException(Exception::RangeError(String::New(\"Source string length out of range\")));\n return NULL;\n }\n params = new Qrc_Params(data);\n\n if (args.Length() > 1) {\n if (!args[1]->IsObject()) {\n ThrowException(Exception::TypeError(String::New(\"Second argument must be an object\")));\n delete params;\n return NULL;\n }\n Local paramsObj = Local::Cast(args[1]);\n Local paramsEcLevel = paramsObj->Get(String::New(\"ecLevel\"));\n if (!paramsEcLevel->IsUndefined()) {\n if (!paramsEcLevel->IsInt32()) {\n ThrowException(Exception::TypeError(String::New(\"Wrong type for ec level\")));\n delete params;\n return NULL;\n } else if (paramsEcLevel->IntegerValue() < QR_ECLEVEL_L || paramsEcLevel->IntegerValue() > QR_ECLEVEL_H) {\n ThrowException(Exception::RangeError(String::New(\"EC level value out of range\")));\n delete params;\n return NULL;\n } else {\n params->ec_level = (QRecLevel) paramsEcLevel->IntegerValue();\n if (data.length() > QRC_MAX_SIZE[params->ec_level]) {\n ThrowException(Exception::RangeError(String::New(\"Source string length out of range\")));\n delete params;\n return NULL;\n }\n }\n }\n Local paramsDotSize = paramsObj->Get(String::New(\"dotSize\"));\n if (!paramsDotSize->IsUndefined()) {\n if (!paramsDotSize->IsInt32()) {\n ThrowException(Exception::TypeError(String::New(\"Wrong type for dot size\")));\n delete params;\n return NULL;\n } else if (paramsDotSize->IntegerValue() < 1 || paramsDotSize->IntegerValue() > 50) {\n ThrowException(Exception::RangeError(String::New(\"Dot size out of range\")));\n delete params;\n return NULL;\n } else {\n params->dot_size = paramsDotSize->IntegerValue();\n }\n }\n Local paramsMargin = paramsObj->Get(String::New(\"margin\"));\n if (!paramsMargin->IsUndefined()) {\n if (!paramsMargin->IsInt32()) {\n ThrowException(Exception::TypeError(String::New(\"Wrong type for margin\")));\n delete params;\n return NULL;\n } else if (paramsMargin->IntegerValue() < 0 || paramsMargin->IntegerValue() > 10) {\n ThrowException(Exception::RangeError(String::New(\"Margin size out of range\")));\n delete params;\n return NULL;\n } else {\n params->margin = paramsMargin->IntegerValue();\n }\n }\n Local paramsVersion = paramsObj->Get(String::New(\"version\"));\n if (!paramsVersion->IsUndefined()) {\n if (!paramsVersion->IsInt32()) {\n ThrowException(Exception::TypeError(String::New(\"Wrong type for version\")));\n delete params;\n return NULL;\n } else if (paramsVersion->IntegerValue() < 1 || paramsVersion->IntegerValue() > QRSPEC_VERSION_MAX) {\n ThrowException(Exception::RangeError(String::New(\"Version number out of range\")));\n delete params;\n return NULL;\n } else {\n params->version = paramsVersion->IntegerValue();\n }\n }\n }\n\n return params;\n}\n\n\nQRcode* Encode(Qrc_Params* params) {\n QRcode* code;\n code = QRcode_encodeString8bit((const char*)params->data, params->version, params->ec_level);\n return code;\n}\n\n\nHandle EncodeBuf(const Arguments& args) {\n HandleScope scope;\n Local codeObj = Object::New();\n\n Qrc_Params* params = ValidateArgs(args);\n if (!params) {\n return scope.Close(codeObj);\n }\n\n QRcode* code = Encode(params);\n delete params;\n if (code != NULL) {\n Local buffer = node::Buffer::New((const char*)code->data, code->width * code->width);\n codeObj->Set(String::NewSymbol(\"width\"), Integer::New(code->width));\n codeObj->Set(String::NewSymbol(\"version\"), Integer::New(code->version));\n codeObj->Set(String::NewSymbol(\"data\"), buffer->handle_);\n QRcode_free(code);\n }\n return scope.Close(codeObj);\n}\n\n\nHandle EncodePNG(const Arguments& args) {\n HandleScope scope;\n Local obj = Object::New();\n\n Qrc_Params* params = ValidateArgs(args);\n if (!params) {\n return scope.Close(obj);\n }\n\n QRcode* code = Encode(params);\n\n if (code != NULL) {\n char* bp;\n size_t size;\n FILE* stream;\n\n png_structp png_ptr;\n png_infop info_ptr;\n\n stream = open_memstream(&bp, &size);\n if (stream == NULL) {\n delete params;\n return scope.Close(obj);\n }\n\n png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,\n NULL, NULL, NULL);\n if (!png_ptr) {\n delete params;\n return scope.Close(obj);\n }\n\n info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr) {\n png_destroy_write_struct(&png_ptr, (png_infopp)NULL);\n delete params;\n return scope.Close(obj);\n }\n\n if (setjmp(png_jmpbuf(png_ptr))) {\n png_destroy_write_struct(&png_ptr, &info_ptr);\n delete params;\n return scope.Close(obj);\n }\n\n png_init_io(png_ptr, stream);\n\n png_set_IHDR(png_ptr, info_ptr, (code->width + params->margin * 2) * params->dot_size, (code->width + params->margin * 2) * params->dot_size, 1,\n PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,\n PNG_FILTER_TYPE_DEFAULT);\n\n png_set_invert_mono(png_ptr);\n png_write_info(png_ptr, info_ptr);\n\n png_set_packing(png_ptr);\n\n unsigned char* row = new unsigned char[(code->width + params->margin * 2) * params->dot_size];\n\n for (int y = -(params->margin); y < code->width + params->margin; y++) {\n for (int x = -(params->margin * params->dot_size); x < (code->width + params->margin) * params->dot_size; x += params->dot_size) {\n for (int d = 0; d < params->dot_size; d++) {\n if (y < 0 || y > code->width - 1 || x < 0 || x > ((code->width - 1) * params->dot_size)) {\n row[x + params->margin * params->dot_size + d] = 0;\n } else {\n row[x + params->margin * params->dot_size + d] = code->data[y * code->width + x\/params->dot_size] << 7;\n }\n }\n }\n for (int d = 0; d < params->dot_size; d++) {\n png_write_row(png_ptr, row);\n }\n }\n\n png_write_end(png_ptr, info_ptr);\n png_destroy_write_struct(&png_ptr, &info_ptr);\n\n fclose(stream);\n\n delete[] row;\n\n Local buffer = node::Buffer::New(bp, size);\n obj->Set(String::NewSymbol(\"width\"), Integer::New(code->width));\n obj->Set(String::NewSymbol(\"version\"), Integer::New(code->version));\n obj->Set(String::NewSymbol(\"data\"), buffer->handle_);\n QRcode_free(code);\n free(bp);\n }\n delete params;\n return scope.Close(obj);\n}\n\nvoid init(Handle exports) {\n exports->Set(String::NewSymbol(\"encode\"),\n FunctionTemplate::New(EncodeBuf)->GetFunction());\n exports->Set(String::NewSymbol(\"encodePng\"),\n FunctionTemplate::New(EncodePNG)->GetFunction());\n}\n\nNODE_MODULE(qrc, init)\nMake memory buffering portable#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace v8;\n\nconst unsigned int QRC_MAX_SIZE[] = { 2938, 2319, 1655, 1268 };\n\nstruct Qrc_Params {\n const char* data;\n QRecLevel ec_level;\n int dot_size;\n int margin;\n int version;\n\n Qrc_Params(std::string p_data, QRecLevel p_ec_level = QR_ECLEVEL_L, int p_dot_size = 3, int p_margin = 4, int p_version = 0) {\n data = new char[p_data.length() + 1];\n strcpy((char*)data, p_data.c_str());\n ec_level = p_ec_level;\n dot_size = p_dot_size;\n margin = p_margin;\n version = p_version;\n }\n\n ~Qrc_Params() {\n delete data;\n }\n};\n\nstruct Qrc_Png_Buffer {\n char *data;\n size_t size;\n Qrc_Png_Buffer() {\n data = NULL;\n size = 0;\n }\n ~Qrc_Png_Buffer() {\n if (data) {\n free(data);\n }\n }\n};\n\nQrc_Params* ValidateArgs(const Arguments& args) {\n struct Qrc_Params* params;\n\n if (args.Length() < 1 || !args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"No source string given\")));\n return NULL;\n }\n std::string data(*v8::String::Utf8Value(args[0]));\n if (data.length() < 1 || data.length() > QRC_MAX_SIZE[0]) {\n ThrowException(Exception::RangeError(String::New(\"Source string length out of range\")));\n return NULL;\n }\n params = new Qrc_Params(data);\n\n if (args.Length() > 1) {\n if (!args[1]->IsObject()) {\n ThrowException(Exception::TypeError(String::New(\"Second argument must be an object\")));\n delete params;\n return NULL;\n }\n Local paramsObj = Local::Cast(args[1]);\n Local paramsEcLevel = paramsObj->Get(String::New(\"ecLevel\"));\n if (!paramsEcLevel->IsUndefined()) {\n if (!paramsEcLevel->IsInt32()) {\n ThrowException(Exception::TypeError(String::New(\"Wrong type for ec level\")));\n delete params;\n return NULL;\n } else if (paramsEcLevel->IntegerValue() < QR_ECLEVEL_L || paramsEcLevel->IntegerValue() > QR_ECLEVEL_H) {\n ThrowException(Exception::RangeError(String::New(\"EC level value out of range\")));\n delete params;\n return NULL;\n } else {\n params->ec_level = (QRecLevel) paramsEcLevel->IntegerValue();\n if (data.length() > QRC_MAX_SIZE[params->ec_level]) {\n ThrowException(Exception::RangeError(String::New(\"Source string length out of range\")));\n delete params;\n return NULL;\n }\n }\n }\n Local paramsDotSize = paramsObj->Get(String::New(\"dotSize\"));\n if (!paramsDotSize->IsUndefined()) {\n if (!paramsDotSize->IsInt32()) {\n ThrowException(Exception::TypeError(String::New(\"Wrong type for dot size\")));\n delete params;\n return NULL;\n } else if (paramsDotSize->IntegerValue() < 1 || paramsDotSize->IntegerValue() > 50) {\n ThrowException(Exception::RangeError(String::New(\"Dot size out of range\")));\n delete params;\n return NULL;\n } else {\n params->dot_size = paramsDotSize->IntegerValue();\n }\n }\n Local paramsMargin = paramsObj->Get(String::New(\"margin\"));\n if (!paramsMargin->IsUndefined()) {\n if (!paramsMargin->IsInt32()) {\n ThrowException(Exception::TypeError(String::New(\"Wrong type for margin\")));\n delete params;\n return NULL;\n } else if (paramsMargin->IntegerValue() < 0 || paramsMargin->IntegerValue() > 10) {\n ThrowException(Exception::RangeError(String::New(\"Margin size out of range\")));\n delete params;\n return NULL;\n } else {\n params->margin = paramsMargin->IntegerValue();\n }\n }\n Local paramsVersion = paramsObj->Get(String::New(\"version\"));\n if (!paramsVersion->IsUndefined()) {\n if (!paramsVersion->IsInt32()) {\n ThrowException(Exception::TypeError(String::New(\"Wrong type for version\")));\n delete params;\n return NULL;\n } else if (paramsVersion->IntegerValue() < 1 || paramsVersion->IntegerValue() > QRSPEC_VERSION_MAX) {\n ThrowException(Exception::RangeError(String::New(\"Version number out of range\")));\n delete params;\n return NULL;\n } else {\n params->version = paramsVersion->IntegerValue();\n }\n }\n }\n\n return params;\n}\n\n\nQRcode* Encode(Qrc_Params* params) {\n QRcode* code;\n code = QRcode_encodeString8bit((const char*)params->data, params->version, params->ec_level);\n return code;\n}\n\n\nHandle EncodeBuf(const Arguments& args) {\n HandleScope scope;\n Local codeObj = Object::New();\n\n Qrc_Params* params = ValidateArgs(args);\n if (!params) {\n return scope.Close(codeObj);\n }\n\n QRcode* code = Encode(params);\n delete params;\n if (code != NULL) {\n Local buffer = node::Buffer::New((const char*)code->data, code->width * code->width);\n codeObj->Set(String::NewSymbol(\"width\"), Integer::New(code->width));\n codeObj->Set(String::NewSymbol(\"version\"), Integer::New(code->version));\n codeObj->Set(String::NewSymbol(\"data\"), buffer->handle_);\n QRcode_free(code);\n }\n return scope.Close(codeObj);\n}\n\n\nvoid Qrc_png_write_buffer(png_structp png_ptr, png_bytep data, png_size_t length) {\n Qrc_Png_Buffer* b = (Qrc_Png_Buffer *)png_get_io_ptr(png_ptr);\n size_t nsize = b->size + length;\n\n if (b->data) {\n b->data = (char *)realloc(b->data, nsize);\n } else {\n b->data = (char *)malloc(nsize);\n }\n\n if (!b->data) {\n png_error(png_ptr, \"Write Error\");\n }\n\n memcpy(b->data + b->size, data, length);\n b->size += length;\n}\n\n\nHandle EncodePNG(const Arguments& args) {\n HandleScope scope;\n Local obj = Object::New();\n\n Qrc_Params* params = ValidateArgs(args);\n if (!params) {\n return scope.Close(obj);\n }\n\n QRcode* code = Encode(params);\n\n if (code != NULL) {\n Qrc_Png_Buffer* bp = new Qrc_Png_Buffer();\n\n png_structp png_ptr;\n png_infop info_ptr;\n\n png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,\n NULL, NULL, NULL);\n if (!png_ptr) {\n delete params;\n return scope.Close(obj);\n }\n\n info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr) {\n png_destroy_write_struct(&png_ptr, (png_infopp)NULL);\n delete params;\n return scope.Close(obj);\n }\n\n if (setjmp(png_jmpbuf(png_ptr))) {\n png_destroy_write_struct(&png_ptr, &info_ptr);\n delete params;\n return scope.Close(obj);\n }\n\n png_set_write_fn(png_ptr, bp, Qrc_png_write_buffer, NULL);\n\n png_set_IHDR(png_ptr, info_ptr, (code->width + params->margin * 2) * params->dot_size, (code->width + params->margin * 2) * params->dot_size, 1,\n PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,\n PNG_FILTER_TYPE_DEFAULT);\n\n png_set_invert_mono(png_ptr);\n png_write_info(png_ptr, info_ptr);\n\n png_set_packing(png_ptr);\n\n unsigned char* row = new unsigned char[(code->width + params->margin * 2) * params->dot_size];\n\n for (int y = -(params->margin); y < code->width + params->margin; y++) {\n for (int x = -(params->margin * params->dot_size); x < (code->width + params->margin) * params->dot_size; x += params->dot_size) {\n for (int d = 0; d < params->dot_size; d++) {\n if (y < 0 || y > code->width - 1 || x < 0 || x > ((code->width - 1) * params->dot_size)) {\n row[x + params->margin * params->dot_size + d] = 0;\n } else {\n row[x + params->margin * params->dot_size + d] = code->data[y * code->width + x\/params->dot_size] << 7;\n }\n }\n }\n for (int d = 0; d < params->dot_size; d++) {\n png_write_row(png_ptr, row);\n }\n }\n\n png_write_end(png_ptr, info_ptr);\n png_destroy_write_struct(&png_ptr, &info_ptr);\n\n delete[] row;\n\n Local buffer = node::Buffer::New(bp->data, bp->size);\n obj->Set(String::NewSymbol(\"width\"), Integer::New(code->width));\n obj->Set(String::NewSymbol(\"version\"), Integer::New(code->version));\n obj->Set(String::NewSymbol(\"data\"), buffer->handle_);\n QRcode_free(code);\n delete bp;\n }\n delete params;\n return scope.Close(obj);\n}\n\nvoid init(Handle exports) {\n exports->Set(String::NewSymbol(\"encode\"),\n FunctionTemplate::New(EncodeBuf)->GetFunction());\n exports->Set(String::NewSymbol(\"encodePng\"),\n FunctionTemplate::New(EncodePNG)->GetFunction());\n}\n\nNODE_MODULE(qrc, init)\n<|endoftext|>"} {"text":"\/*\n * Copyright 2017 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"ok.h\"\n#include \"SkSurface.h\"\n\nstruct SWDst : Dst {\n SkImageInfo info;\n sk_sp surface;\n\n static std::unique_ptr Create(Options options) {\n SkImageInfo info = SkImageInfo::MakeN32Premul(0,0);\n if (options(\"ct\") == \"565\") { info = info.makeColorType(kRGB_565_SkColorType); }\n if (options(\"ct\") == \"f16\") { info = info.makeColorType(kRGBA_F16_SkColorType); }\n\n SWDst dst;\n dst.info = info;\n return move_unique(dst);\n }\n\n Status draw(Src* src) override {\n auto size = src->size();\n surface = SkSurface::MakeRaster(info.makeWH(size.width(), size.height()));\n return src->draw(surface->getCanvas());\n }\n\n sk_sp image() override {\n return surface->makeImageSnapshot();\n }\n};\nstatic Register sw{\"sw\", \"draw with the software backend\", SWDst::Create};\n\nstatic Register _565{\"565\", \"alias for sw:ct=565\", [](Options options) {\n options[\"ct\"] = \"565\";\n return SWDst::Create(options);\n}};\nok, add sRGB support\/*\n * Copyright 2017 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"ok.h\"\n#include \"SkSurface.h\"\n\nstruct SWDst : Dst {\n SkImageInfo info;\n sk_sp surface;\n\n static std::unique_ptr Create(Options options) {\n SkImageInfo info = SkImageInfo::MakeN32Premul(0,0);\n if (options(\"ct\") == \"565\") { info = info.makeColorType(kRGB_565_SkColorType); }\n if (options(\"ct\") == \"f16\") { info = info.makeColorType(kRGBA_F16_SkColorType); }\n\n if (options(\"cs\") == \"srgb\") {\n auto cs = info.colorType() == kRGBA_F16_SkColorType ? SkColorSpace::MakeSRGBLinear()\n : SkColorSpace::MakeSRGB();\n info = info.makeColorSpace(std::move(cs));\n }\n\n SWDst dst;\n dst.info = info;\n return move_unique(dst);\n }\n\n Status draw(Src* src) override {\n auto size = src->size();\n surface = SkSurface::MakeRaster(info.makeWH(size.width(), size.height()));\n return src->draw(surface->getCanvas());\n }\n\n sk_sp image() override {\n return surface->makeImageSnapshot();\n }\n};\nstatic Register sw{\"sw\", \"draw with the software backend\", SWDst::Create};\n\nstatic Register _565{\"565\", \"alias for sw:ct=565\", [](Options options) {\n options[\"ct\"] = \"565\";\n return SWDst::Create(options);\n}};\n\nstatic Register srgb{\"srgb\", \"alias for sw:cs=srgb\", [](Options options) {\n options[\"cs\"] = \"srgb\";\n return SWDst::Create(options);\n}};\n\nstatic Register f16{\"f16\", \"alias for sw:ct=f16,cs=srgb\", [](Options options) {\n options[\"ct\"] = \"f16\";\n options[\"cs\"] = \"srgb\";\n return SWDst::Create(options);\n}};\n<|endoftext|>"} {"text":"\/*\n * Renderer.cpp\n *\n * Created on: 2012-12-02\n * Author: Nathan\n *\/\n\n#include \n#include \n#include \n#include \n#include \"Renderer.h\"\n#include \"Shaders\/shaders.h\"\n\nShader* shader;\nglm::mat4 projection;\n\nRenderer::Renderer(int width, int height) {\n this->height = height;\n this->width = width;\n std::cout << matrixStack.size() << std::endl;\n matrixStack.push_back(glm::mat4(1.0f));\n std::cout << matrixStack.size() << std::endl;\n loadShader(\"\");\n useShader(0);\n uniforms.projection = setUniform(\"uprojection\");\n uniforms.camera = setUniform(\"ucamera\");\n uniforms.model = setUniform(\"umodel\");\n uniforms.color = setUniform(\"ucolor\");\n\n glm::mat4 projection = setProjection(width, height);\n}\n\nvoid Renderer::loadShader(const std::string &name){\n shader = new Shader(\"res\/shaders\/vert.glsl\", \"res\/shaders\/frag.glsl\", width, height);\n}\n\nglm::vec3 Renderer::unProject(int x, int y, double z){\n glm::ivec4 viewport;\n glGetIntegerv(GL_VIEWPORT, glm::value_ptr(viewport));\n \/*double mv[16], p[16];\n for(int i = 0; i < 16; i++){\n mv[i] = (double)(currentMatrix()).m[i];\n p[i] = (double)projection.m[i];\n }\n double wx = x, wy = y, wz = z;\n double vx = -1, vy = -1, vz = 0-1;\n gluUnProject(wx, wy, wz, mv, p, viewport, &vx, &vy, &vz);\n return glm::vec3(vx, vy, vz); *\/\n return glm::unProject(glm::vec3(x, y, z), currentMatrix(), projection, viewport);\n}\n\nvoid Renderer::setColor(float r, float g, float b, float a){\n glUniform4f(uniforms.color, r, g, b, a);\n}\n\nglm::vec3 Renderer::getCursorPos(int x, int y){\n pushMatrix();\n glm::vec3 p0 = unProject(x, y, 0.0);\n glm::vec3 p1 = unProject(x, y, 1.0);\n float u = -p0.z\/(p1.z - p0.z);\n popMatrix();\n return p0 + (p1 - p0)*u;\n}\n\nvoid Renderer::loadFont(const std::string &name){\n _font.reset(new Font(name));\n}\n\nvoid Renderer::bindTexture(int texture){\n glActiveTexture(GL_TEXTURE0);\n glBindTexture(GL_TEXTURE_2D, texture);\n glUniform1i(uniforms.texture, 0);\n}\n\nGLuint Renderer::makeBuffer(GLenum target, const void *buffer_data, GLsizei buffer_size){\n GLuint vbo;\n glGenBuffers(1, &vbo);\n glBindBuffer(target, vbo);\n glBufferData(target, buffer_size, buffer_data, GL_STATIC_DRAW);\n return vbo;\n}\n\nvoid Renderer::drawVertexArray(const std::vector &vertices){\n GLuint vbo = makeBuffer(GL_ARRAY_BUFFER, &vertices[0], vertices.size());\n glBindBuffer(GL_ARRAY_BUFFER, vbo);\n glEnableVertexAttribArray(0);\n \/*\n glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);\n glDrawArrays(GL_TRIANGLES, 0, vertices.size()\/4);\n glDisableVertexAttribArray(0);\n *\/\n}\n\nvoid Renderer::renderString(glm::vec3 pos, const std::string &text){\n pushMatrix();\n for(unsigned i = 0; i < text.size(); ++i){\n Glyph g = _font->getGlyph(text[i]);\n float x = pos.x + g.left;\n float y = pos.y + g.top;\n float w = g.w;\n float h = g.h;\n glEnable(GL_TEXTURE);\n bindTexture(g.texture);\n glBegin(GL_QUADS);\n glVertex3f(x - w, y - h, 0);\n glVertex3f(x + w, y - h, 0);\n glVertex3f(x - w, y + h, 0);\n glVertex3f(x + w, y + h, 0);\n glEnd();\n \/\/ glBufferData(GL_ARRAY_BUFFER, sizeof (box), box, GL_DYNAMIC_DRAW);\n \/\/ glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);\n\n pos.x += (g.adv);\n }\n popMatrix();\n}\n\n#define NEAR_PLANE 0.0625f\n#define FAR_PLANE 256.0f\n\nglm::mat4 Renderer::setProjection(int width, int height){\n float aspectRatio = static_cast(width) \/ static_cast(height);\n projection = glm::perspective(glm::radians(45.f), aspectRatio, NEAR_PLANE, FAR_PLANE);\n glUniformMatrix4fv(uniforms.projection, 1, GL_FALSE, glm::value_ptr(projection));\n return projection;\n}\n\nvoid Renderer::uploadModelView(){\n glUniformMatrix4fv(uniforms.model, 1, GL_FALSE, glm::value_ptr(currentMatrix()));\n}\n\nvoid Renderer::setCamera(float x, float y, float z){\n camera = glm::translate(glm::mat4(1.f), -glm::vec3(x, y, z));\n glUniformMatrix4fv(uniforms.camera, 1, GL_FALSE, glm::value_ptr(camera));\n}\n\nvoid Renderer::pushMatrix(){\n matrixStack.push_back(matrixStack.back());\n uploadModelView();\n}\n\nvoid Renderer::popMatrix(){\n if(matrixStack.size() > 1) {\n matrixStack.pop_back();\n uploadModelView();\n }\n}\n\nglm::mat4 Renderer::translate(float x, float y, float z){\n glm::mat4 t = glm::translate(glm::mat4(1.f), glm::vec3(x, y, z));\n matrixStack.back() = matrixStack.back() * t;\n uploadModelView();\n return matrixStack.back();\n}\n\nglm::mat4 Renderer::rotate(const glm::vec3 &from, const glm::vec3 &to){\n auto q = glm::quat( from, to );\n auto m = glm::toMat4( q );\n matrixStack.back() = matrixStack.back() * m;\n uploadModelView();\n return matrixStack.back();\n}\n\nglm::mat4 Renderer::rotate(float angle, float x, float y, float z){\n glm::mat4 t = glm::rotate(glm::mat4(1.f), angle, glm::vec3(x, y, z));\n matrixStack.back() = matrixStack.back() * t;\n uploadModelView();\n return matrixStack.back();\n}\n\nglm::mat4 Renderer::scale(float x, float y, float z){\n glm::mat4 t = glm::scale(\n glm::mat4(1.0f),\n glm::vec3(x, y, z));\n matrixStack.back() = matrixStack.back() * t;\n uploadModelView();\n return matrixStack.back();\n}\n\nglm::mat4& Renderer::currentMatrix(){\n return matrixStack.back();\n}\n\nvoid Renderer::loadIdentity(){\n\n}\n\nGLuint Renderer::setUniform(const std::string &name){\n return shader->setUniform(name);\n}\n\nvoid Renderer::useShader(int id){\n shader->enable();\n}\n\nvoid Renderer::disableShader(){\n shader->disable();\n}\n\n\nRenderer::~Renderer() {}\nDelete commented code\/*\n * Renderer.cpp\n *\n * Created on: 2012-12-02\n * Author: Nathan\n *\/\n\n#include \n#include \n#include \n#include \n#include \"Renderer.h\"\n#include \"Shaders\/shaders.h\"\n\nShader* shader;\nglm::mat4 projection;\n\nRenderer::Renderer(int width, int height) {\n this->height = height;\n this->width = width;\n std::cout << matrixStack.size() << std::endl;\n matrixStack.push_back(glm::mat4(1.0f));\n std::cout << matrixStack.size() << std::endl;\n loadShader(\"\");\n useShader(0);\n uniforms.projection = setUniform(\"uprojection\");\n uniforms.camera = setUniform(\"ucamera\");\n uniforms.model = setUniform(\"umodel\");\n uniforms.color = setUniform(\"ucolor\");\n\n glm::mat4 projection = setProjection(width, height);\n}\n\nvoid Renderer::loadShader(const std::string &name){\n shader = new Shader(\"res\/shaders\/vert.glsl\", \"res\/shaders\/frag.glsl\", width, height);\n}\n\nglm::vec3 Renderer::unProject(int x, int y, double z){\n glm::ivec4 viewport;\n glGetIntegerv(GL_VIEWPORT, glm::value_ptr(viewport));\n return glm::unProject(glm::vec3(x, y, z), currentMatrix(), projection, viewport);\n}\n\nvoid Renderer::setColor(float r, float g, float b, float a){\n glUniform4f(uniforms.color, r, g, b, a);\n}\n\nglm::vec3 Renderer::getCursorPos(int x, int y){\n pushMatrix();\n glm::vec3 p0 = unProject(x, y, 0.0);\n glm::vec3 p1 = unProject(x, y, 1.0);\n float u = -p0.z\/(p1.z - p0.z);\n popMatrix();\n return p0 + (p1 - p0)*u;\n}\n\nvoid Renderer::loadFont(const std::string &name){\n _font.reset(new Font(name));\n}\n\nvoid Renderer::bindTexture(int texture){\n glActiveTexture(GL_TEXTURE0);\n glBindTexture(GL_TEXTURE_2D, texture);\n glUniform1i(uniforms.texture, 0);\n}\n\nGLuint Renderer::makeBuffer(GLenum target, const void *buffer_data, GLsizei buffer_size){\n GLuint vbo;\n glGenBuffers(1, &vbo);\n glBindBuffer(target, vbo);\n glBufferData(target, buffer_size, buffer_data, GL_STATIC_DRAW);\n return vbo;\n}\n\nvoid Renderer::drawVertexArray(const std::vector &vertices){\n GLuint vbo = makeBuffer(GL_ARRAY_BUFFER, &vertices[0], vertices.size());\n glBindBuffer(GL_ARRAY_BUFFER, vbo);\n glEnableVertexAttribArray(0);\n \/*\n glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);\n glDrawArrays(GL_TRIANGLES, 0, vertices.size()\/4);\n glDisableVertexAttribArray(0);\n *\/\n}\n\nvoid Renderer::renderString(glm::vec3 pos, const std::string &text){\n pushMatrix();\n for(unsigned i = 0; i < text.size(); ++i){\n Glyph g = _font->getGlyph(text[i]);\n float x = pos.x + g.left;\n float y = pos.y + g.top;\n float w = g.w;\n float h = g.h;\n glEnable(GL_TEXTURE);\n bindTexture(g.texture);\n glBegin(GL_QUADS);\n glVertex3f(x - w, y - h, 0);\n glVertex3f(x + w, y - h, 0);\n glVertex3f(x - w, y + h, 0);\n glVertex3f(x + w, y + h, 0);\n glEnd();\n \/\/ glBufferData(GL_ARRAY_BUFFER, sizeof (box), box, GL_DYNAMIC_DRAW);\n \/\/ glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);\n\n pos.x += (g.adv);\n }\n popMatrix();\n}\n\n#define NEAR_PLANE 0.0625f\n#define FAR_PLANE 256.0f\n\nglm::mat4 Renderer::setProjection(int width, int height){\n float aspectRatio = static_cast(width) \/ static_cast(height);\n projection = glm::perspective(glm::radians(45.f), aspectRatio, NEAR_PLANE, FAR_PLANE);\n glUniformMatrix4fv(uniforms.projection, 1, GL_FALSE, glm::value_ptr(projection));\n return projection;\n}\n\nvoid Renderer::uploadModelView(){\n glUniformMatrix4fv(uniforms.model, 1, GL_FALSE, glm::value_ptr(currentMatrix()));\n}\n\nvoid Renderer::setCamera(float x, float y, float z){\n camera = glm::translate(glm::mat4(1.f), -glm::vec3(x, y, z));\n glUniformMatrix4fv(uniforms.camera, 1, GL_FALSE, glm::value_ptr(camera));\n}\n\nvoid Renderer::pushMatrix(){\n matrixStack.push_back(matrixStack.back());\n uploadModelView();\n}\n\nvoid Renderer::popMatrix(){\n if(matrixStack.size() > 1) {\n matrixStack.pop_back();\n uploadModelView();\n }\n}\n\nglm::mat4 Renderer::translate(float x, float y, float z){\n glm::mat4 t = glm::translate(glm::mat4(1.f), glm::vec3(x, y, z));\n matrixStack.back() = matrixStack.back() * t;\n uploadModelView();\n return matrixStack.back();\n}\n\nglm::mat4 Renderer::rotate(const glm::vec3 &from, const glm::vec3 &to){\n auto q = glm::quat( from, to );\n auto m = glm::toMat4( q );\n matrixStack.back() = matrixStack.back() * m;\n uploadModelView();\n return matrixStack.back();\n}\n\nglm::mat4 Renderer::rotate(float angle, float x, float y, float z){\n glm::mat4 t = glm::rotate(glm::mat4(1.f), angle, glm::vec3(x, y, z));\n matrixStack.back() = matrixStack.back() * t;\n uploadModelView();\n return matrixStack.back();\n}\n\nglm::mat4 Renderer::scale(float x, float y, float z){\n glm::mat4 t = glm::scale(\n glm::mat4(1.0f),\n glm::vec3(x, y, z));\n matrixStack.back() = matrixStack.back() * t;\n uploadModelView();\n return matrixStack.back();\n}\n\nglm::mat4& Renderer::currentMatrix(){\n return matrixStack.back();\n}\n\nvoid Renderer::loadIdentity(){\n\n}\n\nGLuint Renderer::setUniform(const std::string &name){\n return shader->setUniform(name);\n}\n\nvoid Renderer::useShader(int id){\n shader->enable();\n}\n\nvoid Renderer::disableShader(){\n shader->disable();\n}\n\n\nRenderer::~Renderer() {}\n<|endoftext|>"} {"text":"\/\/===--------------------- Unwind_AppleExtras.cpp -------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"config.h\"\n#include \"DwarfParser.hpp\"\n#include \"unwind_ext.h\"\n\n\n\/\/ private keymgr stuff\n#define KEYMGR_GCC3_DW2_OBJ_LIST 302\nextern \"C\" {\n extern void _keymgr_set_and_unlock_processwide_ptr(int key, void *ptr);\n extern void *_keymgr_get_and_lock_processwide_ptr(int key);\n}\n\n\/\/ undocumented libgcc \"struct object\"\nstruct libgcc_object {\n void *start;\n void *unused1;\n void *unused2;\n void *fde;\n unsigned long encoding;\n void *fde_end;\n libgcc_object *next;\n};\n\n\/\/ undocumented libgcc \"struct km_object_info\" referenced by\n\/\/ KEYMGR_GCC3_DW2_OBJ_LIST\nstruct libgcc_object_info {\n libgcc_object *seen_objects;\n libgcc_object *unseen_objects;\n unsigned spare[2];\n};\n\n\n\/\/ static linker symbols to prevent wrong two level namespace for _Unwind symbols\n#if __arm__\n #define NOT_HERE_BEFORE_5_0(sym) \\\n extern const char sym##_tmp30 __asm(\"$ld$hide$os3.0$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp30 = 0; \\\n extern const char sym##_tmp31 __asm(\"$ld$hide$os3.1$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp31 = 0; \\\n extern const char sym##_tmp32 __asm(\"$ld$hide$os3.2$_\" #sym );\\\n __attribute__((visibility(\"default\"))) const char sym##_tmp32 = 0; \\\n extern const char sym##_tmp40 __asm(\"$ld$hide$os4.0$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp40 = 0; \\\n extern const char sym##_tmp41 __asm(\"$ld$hide$os4.1$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp41 = 0; \\\n extern const char sym##_tmp42 __asm(\"$ld$hide$os4.2$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp42 = 0; \\\n extern const char sym##_tmp43 __asm(\"$ld$hide$os4.3$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp43 = 0;\n#elif __arm64__\n #define NOT_HERE_BEFORE_10_6(sym)\n #define NEVER_HERE(sym)\n#else\n #define NOT_HERE_BEFORE_10_6(sym) \\\n extern const char sym##_tmp4 __asm(\"$ld$hide$os10.4$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp4 = 0; \\\n extern const char sym##_tmp5 __asm(\"$ld$hide$os10.5$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp5 = 0;\n #define NEVER_HERE(sym) \\\n extern const char sym##_tmp4 __asm(\"$ld$hide$os10.4$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp4 = 0; \\\n extern const char sym##_tmp5 __asm(\"$ld$hide$os10.5$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp5 = 0; \\\n extern const char sym##_tmp6 __asm(\"$ld$hide$os10.6$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp6 = 0;\n#endif\n\n\n#if _LIBUNWIND_BUILD_ZERO_COST_APIS\n\n\/\/\n\/\/ symbols in libSystem.dylib in 10.6 and later, but are in libgcc_s.dylib in\n\/\/ earlier versions\n\/\/\nNOT_HERE_BEFORE_10_6(_Unwind_DeleteException)\nNOT_HERE_BEFORE_10_6(_Unwind_Find_FDE)\nNOT_HERE_BEFORE_10_6(_Unwind_ForcedUnwind)\nNOT_HERE_BEFORE_10_6(_Unwind_GetGR)\nNOT_HERE_BEFORE_10_6(_Unwind_GetIP)\nNOT_HERE_BEFORE_10_6(_Unwind_GetLanguageSpecificData)\nNOT_HERE_BEFORE_10_6(_Unwind_GetRegionStart)\nNOT_HERE_BEFORE_10_6(_Unwind_RaiseException)\nNOT_HERE_BEFORE_10_6(_Unwind_Resume)\nNOT_HERE_BEFORE_10_6(_Unwind_SetGR)\nNOT_HERE_BEFORE_10_6(_Unwind_SetIP)\nNOT_HERE_BEFORE_10_6(_Unwind_Backtrace)\nNOT_HERE_BEFORE_10_6(_Unwind_FindEnclosingFunction)\nNOT_HERE_BEFORE_10_6(_Unwind_GetCFA)\nNOT_HERE_BEFORE_10_6(_Unwind_GetDataRelBase)\nNOT_HERE_BEFORE_10_6(_Unwind_GetTextRelBase)\nNOT_HERE_BEFORE_10_6(_Unwind_Resume_or_Rethrow)\nNOT_HERE_BEFORE_10_6(_Unwind_GetIPInfo)\nNOT_HERE_BEFORE_10_6(__register_frame)\nNOT_HERE_BEFORE_10_6(__deregister_frame)\n\n\/\/\n\/\/ symbols in libSystem.dylib for compatibility, but we don't want any new code\n\/\/ using them\n\/\/\nNEVER_HERE(__register_frame_info_bases)\nNEVER_HERE(__register_frame_info)\nNEVER_HERE(__register_frame_info_table_bases)\nNEVER_HERE(__register_frame_info_table)\nNEVER_HERE(__register_frame_table)\nNEVER_HERE(__deregister_frame_info)\nNEVER_HERE(__deregister_frame_info_bases)\n\n#endif \/\/ _LIBUNWIND_BUILD_ZERO_COST_APIS\n\n\n\n\n#if _LIBUNWIND_BUILD_SJLJ_APIS\n\/\/\n\/\/ symbols in libSystem.dylib in iOS 5.0 and later, but are in libgcc_s.dylib in\n\/\/ earlier versions\n\/\/\nNOT_HERE_BEFORE_5_0(_Unwind_GetLanguageSpecificData)\nNOT_HERE_BEFORE_5_0(_Unwind_GetRegionStart)\nNOT_HERE_BEFORE_5_0(_Unwind_GetIP)\nNOT_HERE_BEFORE_5_0(_Unwind_SetGR)\nNOT_HERE_BEFORE_5_0(_Unwind_SetIP)\nNOT_HERE_BEFORE_5_0(_Unwind_DeleteException)\nNOT_HERE_BEFORE_5_0(_Unwind_SjLj_Register)\nNOT_HERE_BEFORE_5_0(_Unwind_GetGR)\nNOT_HERE_BEFORE_5_0(_Unwind_GetIPInfo)\nNOT_HERE_BEFORE_5_0(_Unwind_GetCFA)\nNOT_HERE_BEFORE_5_0(_Unwind_SjLj_Resume)\nNOT_HERE_BEFORE_5_0(_Unwind_SjLj_RaiseException)\nNOT_HERE_BEFORE_5_0(_Unwind_SjLj_Resume_or_Rethrow)\nNOT_HERE_BEFORE_5_0(_Unwind_SjLj_Unregister)\n\n#endif \/\/ _LIBUNWIND_BUILD_SJLJ_APIS\n\n\nnamespace libunwind {\n\n_LIBUNWIND_HIDDEN\nbool checkKeyMgrRegisteredFDEs(uintptr_t pc, void *&fde) {\n#if __MAC_OS_X_VERSION_MIN_REQUIRED\n \/\/ lastly check for old style keymgr registration of dynamically generated\n \/\/ FDEs acquire exclusive access to libgcc_object_info\n libgcc_object_info *head = (libgcc_object_info *)\n _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);\n if (head != NULL) {\n \/\/ look at each FDE in keymgr\n for (libgcc_object *ob = head->unseen_objects; ob != NULL; ob = ob->next) {\n CFI_Parser::FDE_Info fdeInfo;\n CFI_Parser::CIE_Info cieInfo;\n const char *msg = CFI_Parser::decodeFDE(\n LocalAddressSpace::sThisAddressSpace,\n (uintptr_t)ob->fde, &fdeInfo, &cieInfo);\n if (msg == NULL) {\n \/\/ Check if this FDE is for a function that includes the pc\n if ((fdeInfo.pcStart <= pc) && (pc < fdeInfo.pcEnd)) {\n fde = (void*)fdeInfo.pcStart;\n _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,\n head);\n return true;\n }\n }\n }\n }\n \/\/ release libgcc_object_info\n _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST, head);\n#else\n (void)pc;\n (void)fde;\n#endif\n return false;\n}\n\n}\n\n\n#if !FOR_DYLD\n\n#include \n\n_LIBUNWIND_HIDDEN\nstruct _Unwind_FunctionContext *__Unwind_SjLj_GetTopOfFunctionStack() {\n return (struct _Unwind_FunctionContext *)\n _pthread_getspecific_direct(__PTK_LIBC_DYLD_Unwind_SjLj_Key);\n}\n\n_LIBUNWIND_HIDDEN\nvoid __Unwind_SjLj_SetTopOfFunctionStack(struct _Unwind_FunctionContext *fc) {\n _pthread_setspecific_direct(__PTK_LIBC_DYLD_Unwind_SjLj_Key, fc);\n}\n#endif\n\n\n\n\nFix conditionals on __Unwind_SjLj_* functions to only build for SJLJ based architectures\/\/===--------------------- Unwind_AppleExtras.cpp -------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"config.h\"\n#include \"DwarfParser.hpp\"\n#include \"unwind_ext.h\"\n\n\n\/\/ private keymgr stuff\n#define KEYMGR_GCC3_DW2_OBJ_LIST 302\nextern \"C\" {\n extern void _keymgr_set_and_unlock_processwide_ptr(int key, void *ptr);\n extern void *_keymgr_get_and_lock_processwide_ptr(int key);\n}\n\n\/\/ undocumented libgcc \"struct object\"\nstruct libgcc_object {\n void *start;\n void *unused1;\n void *unused2;\n void *fde;\n unsigned long encoding;\n void *fde_end;\n libgcc_object *next;\n};\n\n\/\/ undocumented libgcc \"struct km_object_info\" referenced by\n\/\/ KEYMGR_GCC3_DW2_OBJ_LIST\nstruct libgcc_object_info {\n libgcc_object *seen_objects;\n libgcc_object *unseen_objects;\n unsigned spare[2];\n};\n\n\n\/\/ static linker symbols to prevent wrong two level namespace for _Unwind symbols\n#if __arm__\n #define NOT_HERE_BEFORE_5_0(sym) \\\n extern const char sym##_tmp30 __asm(\"$ld$hide$os3.0$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp30 = 0; \\\n extern const char sym##_tmp31 __asm(\"$ld$hide$os3.1$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp31 = 0; \\\n extern const char sym##_tmp32 __asm(\"$ld$hide$os3.2$_\" #sym );\\\n __attribute__((visibility(\"default\"))) const char sym##_tmp32 = 0; \\\n extern const char sym##_tmp40 __asm(\"$ld$hide$os4.0$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp40 = 0; \\\n extern const char sym##_tmp41 __asm(\"$ld$hide$os4.1$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp41 = 0; \\\n extern const char sym##_tmp42 __asm(\"$ld$hide$os4.2$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp42 = 0; \\\n extern const char sym##_tmp43 __asm(\"$ld$hide$os4.3$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp43 = 0;\n#elif __arm64__\n #define NOT_HERE_BEFORE_10_6(sym)\n #define NEVER_HERE(sym)\n#else\n #define NOT_HERE_BEFORE_10_6(sym) \\\n extern const char sym##_tmp4 __asm(\"$ld$hide$os10.4$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp4 = 0; \\\n extern const char sym##_tmp5 __asm(\"$ld$hide$os10.5$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp5 = 0;\n #define NEVER_HERE(sym) \\\n extern const char sym##_tmp4 __asm(\"$ld$hide$os10.4$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp4 = 0; \\\n extern const char sym##_tmp5 __asm(\"$ld$hide$os10.5$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp5 = 0; \\\n extern const char sym##_tmp6 __asm(\"$ld$hide$os10.6$_\" #sym ); \\\n __attribute__((visibility(\"default\"))) const char sym##_tmp6 = 0;\n#endif\n\n\n#if _LIBUNWIND_BUILD_ZERO_COST_APIS\n\n\/\/\n\/\/ symbols in libSystem.dylib in 10.6 and later, but are in libgcc_s.dylib in\n\/\/ earlier versions\n\/\/\nNOT_HERE_BEFORE_10_6(_Unwind_DeleteException)\nNOT_HERE_BEFORE_10_6(_Unwind_Find_FDE)\nNOT_HERE_BEFORE_10_6(_Unwind_ForcedUnwind)\nNOT_HERE_BEFORE_10_6(_Unwind_GetGR)\nNOT_HERE_BEFORE_10_6(_Unwind_GetIP)\nNOT_HERE_BEFORE_10_6(_Unwind_GetLanguageSpecificData)\nNOT_HERE_BEFORE_10_6(_Unwind_GetRegionStart)\nNOT_HERE_BEFORE_10_6(_Unwind_RaiseException)\nNOT_HERE_BEFORE_10_6(_Unwind_Resume)\nNOT_HERE_BEFORE_10_6(_Unwind_SetGR)\nNOT_HERE_BEFORE_10_6(_Unwind_SetIP)\nNOT_HERE_BEFORE_10_6(_Unwind_Backtrace)\nNOT_HERE_BEFORE_10_6(_Unwind_FindEnclosingFunction)\nNOT_HERE_BEFORE_10_6(_Unwind_GetCFA)\nNOT_HERE_BEFORE_10_6(_Unwind_GetDataRelBase)\nNOT_HERE_BEFORE_10_6(_Unwind_GetTextRelBase)\nNOT_HERE_BEFORE_10_6(_Unwind_Resume_or_Rethrow)\nNOT_HERE_BEFORE_10_6(_Unwind_GetIPInfo)\nNOT_HERE_BEFORE_10_6(__register_frame)\nNOT_HERE_BEFORE_10_6(__deregister_frame)\n\n\/\/\n\/\/ symbols in libSystem.dylib for compatibility, but we don't want any new code\n\/\/ using them\n\/\/\nNEVER_HERE(__register_frame_info_bases)\nNEVER_HERE(__register_frame_info)\nNEVER_HERE(__register_frame_info_table_bases)\nNEVER_HERE(__register_frame_info_table)\nNEVER_HERE(__register_frame_table)\nNEVER_HERE(__deregister_frame_info)\nNEVER_HERE(__deregister_frame_info_bases)\n\n#endif \/\/ _LIBUNWIND_BUILD_ZERO_COST_APIS\n\n\n\n\n#if _LIBUNWIND_BUILD_SJLJ_APIS\n\/\/\n\/\/ symbols in libSystem.dylib in iOS 5.0 and later, but are in libgcc_s.dylib in\n\/\/ earlier versions\n\/\/\nNOT_HERE_BEFORE_5_0(_Unwind_GetLanguageSpecificData)\nNOT_HERE_BEFORE_5_0(_Unwind_GetRegionStart)\nNOT_HERE_BEFORE_5_0(_Unwind_GetIP)\nNOT_HERE_BEFORE_5_0(_Unwind_SetGR)\nNOT_HERE_BEFORE_5_0(_Unwind_SetIP)\nNOT_HERE_BEFORE_5_0(_Unwind_DeleteException)\nNOT_HERE_BEFORE_5_0(_Unwind_SjLj_Register)\nNOT_HERE_BEFORE_5_0(_Unwind_GetGR)\nNOT_HERE_BEFORE_5_0(_Unwind_GetIPInfo)\nNOT_HERE_BEFORE_5_0(_Unwind_GetCFA)\nNOT_HERE_BEFORE_5_0(_Unwind_SjLj_Resume)\nNOT_HERE_BEFORE_5_0(_Unwind_SjLj_RaiseException)\nNOT_HERE_BEFORE_5_0(_Unwind_SjLj_Resume_or_Rethrow)\nNOT_HERE_BEFORE_5_0(_Unwind_SjLj_Unregister)\n\n#endif \/\/ _LIBUNWIND_BUILD_SJLJ_APIS\n\n\nnamespace libunwind {\n\n_LIBUNWIND_HIDDEN\nbool checkKeyMgrRegisteredFDEs(uintptr_t pc, void *&fde) {\n#if __MAC_OS_X_VERSION_MIN_REQUIRED\n \/\/ lastly check for old style keymgr registration of dynamically generated\n \/\/ FDEs acquire exclusive access to libgcc_object_info\n libgcc_object_info *head = (libgcc_object_info *)\n _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);\n if (head != NULL) {\n \/\/ look at each FDE in keymgr\n for (libgcc_object *ob = head->unseen_objects; ob != NULL; ob = ob->next) {\n CFI_Parser::FDE_Info fdeInfo;\n CFI_Parser::CIE_Info cieInfo;\n const char *msg = CFI_Parser::decodeFDE(\n LocalAddressSpace::sThisAddressSpace,\n (uintptr_t)ob->fde, &fdeInfo, &cieInfo);\n if (msg == NULL) {\n \/\/ Check if this FDE is for a function that includes the pc\n if ((fdeInfo.pcStart <= pc) && (pc < fdeInfo.pcEnd)) {\n fde = (void*)fdeInfo.pcStart;\n _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,\n head);\n return true;\n }\n }\n }\n }\n \/\/ release libgcc_object_info\n _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST, head);\n#else\n (void)pc;\n (void)fde;\n#endif\n return false;\n}\n\n}\n\n\n#if !FOR_DYLD && _LIBUNWIND_BUILD_SJLJ_APIS\n\n#include \n\n\/\/ Accessors to get get\/set linked list of frames for sjlj based execeptions.\n_LIBUNWIND_HIDDEN\nstruct _Unwind_FunctionContext *__Unwind_SjLj_GetTopOfFunctionStack() {\n return (struct _Unwind_FunctionContext *)\n _pthread_getspecific_direct(__PTK_LIBC_DYLD_Unwind_SjLj_Key);\n}\n\n_LIBUNWIND_HIDDEN\nvoid __Unwind_SjLj_SetTopOfFunctionStack(struct _Unwind_FunctionContext *fc) {\n _pthread_setspecific_direct(__PTK_LIBC_DYLD_Unwind_SjLj_Key, fc);\n}\n#endif\n\n\n\n\n<|endoftext|>"} {"text":"\/\/ Licensed GNU LGPL v2.1 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#include \"bsecxxutils.hh\"\n#include \"bsecxxbase.hh\"\n#include \"bsecategories.hh\"\n#include \nusing namespace std; \/\/ FIXME\n\nnamespace Bse {\n\nstruct TypeRegistry::TypeEntry {\n guint instance_size;\n const gchar *name;\n const gchar *parent;\n const ClassInfo *cinfo;\n GBaseInitFunc binit;\n GClassInitFunc cinit;\n GInstanceInitFunc iinit;\n TypeRegistry::Flags flags;\n TypeRegistry *reg;\n \/*Con*\/ TypeEntry (guint instance_size,\n const gchar *name,\n const gchar *parent,\n const ClassInfo *cinfo,\n GBaseInitFunc binit,\n GClassInitFunc cinit,\n GInstanceInitFunc iinit,\n TypeRegistry::Flags flags)\n : reg (NULL)\n {\n this->instance_size = instance_size;\n this->name = name;\n this->parent = parent;\n this->cinfo = cinfo;\n this->binit = binit;\n this->cinit = cinit;\n this->iinit = iinit;\n this->flags = flags;\n }\n};\n\nstatic list *type_entries = NULL;\n\nTypeRegistry::TypeRegistry (guint instance_size,\n const gchar *name,\n const gchar *parent,\n const ClassInfo *cinfo,\n GBaseInitFunc binit,\n void (*class_init) (CxxBaseClass*),\n GInstanceInitFunc iinit,\n Flags flags)\n : gtype_id (0)\n{\n TypeEntry entry (instance_size, name, parent, cinfo, binit,\n (GClassInitFunc) class_init,\n iinit, flags);\n entry.reg = this;\n\n if (!type_entries)\n type_entries = new list();\n\n list::iterator li;\n for (li = type_entries->begin(); li != type_entries->end(); li++)\n if (strcmp (li->name, parent) == 0)\n break;\n if (li != type_entries->end())\n type_entries->insert (++li, entry);\n else \/\/ parent not found in list\n type_entries->push_front (entry);\n}\n\nvoid\nTypeRegistry::init_types()\n{\n for (list::iterator li = type_entries->begin (); li != type_entries->end (); li++)\n {\n TypeRegistry *self = li->reg;\n GTypeInfo info = { 0, };\n\n info.class_size = BSE_CXX_COMMON_CLASS_SIZE;\n info.base_init = li->binit;\n info.class_init = li->cinit;\n info.instance_size = BSE_CXX_INSTANCE_OFFSET + li->instance_size;\n info.instance_init = li->iinit;\n self->gtype_id = g_type_register_static (g_type_from_name (li->parent),\n li->name, &info, (GTypeFlags) li->flags);\n if (li->cinfo)\n {\n if (li->cinfo->category)\n bse_categories_register (li->cinfo->category, NULL, self->gtype_id, NULL);\n if (li->cinfo->blurb)\n bse_type_add_blurb (self->gtype_id, li->cinfo->blurb, li->cinfo->file, li->cinfo->line);\n }\n }\n delete type_entries;\n type_entries = NULL;\n}\n\nextern \"C\" void\nbse_cxx_init (void) \/\/ prototyped in bseutils.hh\n{\n \/\/ FIXME: delete: init_exception_handler ();\n Bse::TypeRegistry::init_types();\n}\n\n} \/\/ Bse\nBSE: fix bse_cxx_init namespace\/\/ Licensed GNU LGPL v2.1 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#include \"bsecxxutils.hh\"\n#include \"bsecxxbase.hh\"\n#include \"bsecategories.hh\"\n#include \nusing namespace std; \/\/ FIXME\n\nnamespace Bse {\n\nstruct TypeRegistry::TypeEntry {\n guint instance_size;\n const gchar *name;\n const gchar *parent;\n const ClassInfo *cinfo;\n GBaseInitFunc binit;\n GClassInitFunc cinit;\n GInstanceInitFunc iinit;\n TypeRegistry::Flags flags;\n TypeRegistry *reg;\n \/*Con*\/ TypeEntry (guint instance_size,\n const gchar *name,\n const gchar *parent,\n const ClassInfo *cinfo,\n GBaseInitFunc binit,\n GClassInitFunc cinit,\n GInstanceInitFunc iinit,\n TypeRegistry::Flags flags)\n : reg (NULL)\n {\n this->instance_size = instance_size;\n this->name = name;\n this->parent = parent;\n this->cinfo = cinfo;\n this->binit = binit;\n this->cinit = cinit;\n this->iinit = iinit;\n this->flags = flags;\n }\n};\n\nstatic list *type_entries = NULL;\n\nTypeRegistry::TypeRegistry (guint instance_size,\n const gchar *name,\n const gchar *parent,\n const ClassInfo *cinfo,\n GBaseInitFunc binit,\n void (*class_init) (CxxBaseClass*),\n GInstanceInitFunc iinit,\n Flags flags)\n : gtype_id (0)\n{\n TypeEntry entry (instance_size, name, parent, cinfo, binit,\n (GClassInitFunc) class_init,\n iinit, flags);\n entry.reg = this;\n\n if (!type_entries)\n type_entries = new list();\n\n list::iterator li;\n for (li = type_entries->begin(); li != type_entries->end(); li++)\n if (strcmp (li->name, parent) == 0)\n break;\n if (li != type_entries->end())\n type_entries->insert (++li, entry);\n else \/\/ parent not found in list\n type_entries->push_front (entry);\n}\n\nvoid\nTypeRegistry::init_types()\n{\n for (list::iterator li = type_entries->begin (); li != type_entries->end (); li++)\n {\n TypeRegistry *self = li->reg;\n GTypeInfo info = { 0, };\n\n info.class_size = BSE_CXX_COMMON_CLASS_SIZE;\n info.base_init = li->binit;\n info.class_init = li->cinit;\n info.instance_size = BSE_CXX_INSTANCE_OFFSET + li->instance_size;\n info.instance_init = li->iinit;\n self->gtype_id = g_type_register_static (g_type_from_name (li->parent),\n li->name, &info, (GTypeFlags) li->flags);\n if (li->cinfo)\n {\n if (li->cinfo->category)\n bse_categories_register (li->cinfo->category, NULL, self->gtype_id, NULL);\n if (li->cinfo->blurb)\n bse_type_add_blurb (self->gtype_id, li->cinfo->blurb, li->cinfo->file, li->cinfo->line);\n }\n }\n delete type_entries;\n type_entries = NULL;\n}\n\n} \/\/ Bse\n\n\nextern \"C\" void\nbse_cxx_init (void) \/\/ prototyped in bseutils.hh\n{\n \/\/ FIXME: delete: init_exception_handler ();\n Bse::TypeRegistry::init_types();\n}\n<|endoftext|>"} {"text":"\/\/ Licensed GNU LGPL v2.1 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#ifndef __BSE_CXX_UTILS_H__\n#define __BSE_CXX_UTILS_H__\n#include \n#include \n#include \n#include \nnamespace Bse {\n\n\/\/\/ The Procedure namespace contains procedure\/IDL helpers.\nnamespace Procedure {\ntypedef SfiBool Bool;\ntypedef SfiInt Int;\ntypedef SfiNum Num;\ntypedef SfiTime Time;\ntypedef SfiNote Note;\ntypedef SfiReal Real;\ntypedef SfiChoice Choice;\ntypedef std::string String;\ntypedef SfiBBlock BBlock;\ntypedef SfiFBlock FBlock;\ntypedef SfiSeq Seq;\ntypedef SfiRec Rec;\ntypedef SfiProxy Proxy;\n};\n\n\/* --- type alias frequently used standard lib things --- *\/\ntypedef std::string String;\n\n\n\/* --- generally useful templates --- *\/\ntemplate static void\ndelete_this (Data *d)\n{\n delete d;\n}\n\/* check derivation of Derived from Base *\/\ntemplate \/\/ ex: EnforceDerivedFrom assertion;\nstruct EnforceDerivedFrom {\n EnforceDerivedFrom (Derived *derived = 0,\n Base *base = 0)\n {\n base = derived;\n }\n};\n\/* check derivation of Derived* from Base* *\/\ntemplate \/\/ ex: EnforceDerivedFrom assertion;\nstruct EnforceDerivedFrom {\n EnforceDerivedFrom (Derived *derived = 0,\n Base *base = 0)\n {\n base = derived;\n }\n};\n\/* check derivation through EnforceDerivedFrom<>; *\/\ntemplate void\nassert_derived_from (void)\n{\n EnforceDerivedFrom assertion;\n}\n\n\n\/* --- exceptions --- *\/\nstruct Exception : std::exception {\n explicit Exception (const char *_where) : loc (_where) {};\n virtual const char* where() { return loc; }\nprivate:\n const char *loc;\n};\nstruct InvalidArgument2 : Exception {\n const char *item;\n InvalidArgument2 (const char *where, const char *item) : Exception (where), item (item) {};\n const char* what() const throw() { return g_intern_strconcat (\"invalid argument: \", item, NULL); }\n};\n#define InvalidArgument(WHAT) InvalidArgument2 (__func__, #WHAT)\nstruct WrongTypeGValue : Exception {\n WrongTypeGValue (const char *where) : Exception (where) {};\n const char* what() const throw() { return \"GValue contains wrong type for this kind of use\"; }\n};\nstruct DontReach : Exception {\n DontReach (const char *where) : Exception (where) {};\n const char* what() const throw() { return \"Code section should not be reached\"; }\n};\nstruct InvalidConnection : Exception {\n InvalidConnection (const char *where) : Exception (where) {};\n const char* what() const throw() { return \"Function to be connected has invalid signature\"; }\n};\n\n\/* --- records & sequences --- *\/\nclass Record {\n Record& operator= (const Record&);\n explicit Record (const Record&);\npublic:\n explicit Record ();\n virtual SfiRec* to_rec ();\n virtual ~Record ();\n};\n\n\n\/* --- class registration --- *\/\n#define BSE_CXX_TYPE_REGISTER(ObjectType, parent, class_info) \\\n BSE_CXX_TYPE_REGISTER_INITIALIZED (ObjectType, parent, class_info, NULL, TypeRegistry::NONE)\n#define BSE_CXX_TYPE_REGISTER_ABSTRACT(ObjectType, parent, class_info) \\\n BSE_CXX_TYPE_REGISTER_INTERN (ObjectType, parent, class_info, NULL, NULL, TypeRegistry::ABSTRACT)\n\n\/* --- class information --- *\/\nstruct ClassInfo\n{\n const char *category;\n const char *blurb;\n const char *file;\n int line;\n ClassInfo (const char *category,\n const char *blurb,\n const char *file,\n int line)\n {\n this->category = category;\n this->blurb = blurb;\n this->file = file;\n this->line = line;\n }\n};\n\n\n\/* --- type registration internals --- *\/\nstruct CxxBaseClass;\nclass TypeRegistry\n{\n GType gtype_id;\npublic:\n enum Flags {\n NONE = 0,\n ABSTRACT = G_TYPE_FLAG_ABSTRACT\n };\n TypeRegistry (guint instance_size,\n const gchar *name,\n const gchar *parent,\n const ClassInfo *cinfo,\n GBaseInitFunc binit,\n void (*class_init) (CxxBaseClass*),\n GInstanceInitFunc iinit,\n Flags flags);\n const GType\n get_type () const\n {\n return gtype_id;\n }\n static void\n init_types ();\n struct TypeEntry;\n};\n\ntemplate const GType\nbse_type_id_wrapper (const char *type_name)\n{\n static GType type = 0;\n if (!type)\n {\n type = g_type_from_name (type_name);\n RAPICORN_ASSERT (type);\n }\n return type;\n}\n\n#define BSE_CXX_TYPE_GET_REGISTERED(NameSpace, ObjectType) \\\n (::Bse::bse_type_id_wrapper (#NameSpace #ObjectType))\n#define BSE_CXX_TYPE_REGISTER_INITIALIZED(ObjectType, parent, cinfo, binit, flags) \\\n BSE_CXX_TYPE_REGISTER_INTERN (ObjectType, parent, cinfo, binit, \\\n ::Bse::cxx_instance_init_trampoline, flags)\n#define BSE_CXX_TYPE_REGISTER_INTERN(ObjectType, parent, cinfo, binit, iinit, flags) \\\n static Bse::TypeRegistry \\\n ObjectType ## _type_keeper (sizeof (ObjectType), \"Bse\" #ObjectType, parent, \\\n cinfo, binit, \\\n ::Bse::cxx_class_init_trampoline, \\\n iinit, flags);\n#define BSE_CXX_UTILS_ALIGNMENT (2 * sizeof (gsize))\n#define BSE_CXX_UTILS_ALIGN(offset) ((offset + BSE_CXX_UTILS_ALIGNMENT - 1) & -BSE_CXX_UTILS_ALIGNMENT)\n#define BSE_CXX_SIZEOF(Class) BSE_CXX_UTILS_ALIGN (sizeof (Class))\n#define BSE_CXX_COMMON_CLASS_SIZE sizeof (CxxBaseClass)\n\n} \/\/ Bse\n\n#endif \/* __BSE_CXX_UTILS_H__ *\/\nBSE: use noexcept instead of dynamic exception specifications\/\/ Licensed GNU LGPL v2.1 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#ifndef __BSE_CXX_UTILS_H__\n#define __BSE_CXX_UTILS_H__\n#include \n#include \n#include \n#include \nnamespace Bse {\n\n\/\/\/ The Procedure namespace contains procedure\/IDL helpers.\nnamespace Procedure {\ntypedef SfiBool Bool;\ntypedef SfiInt Int;\ntypedef SfiNum Num;\ntypedef SfiTime Time;\ntypedef SfiNote Note;\ntypedef SfiReal Real;\ntypedef SfiChoice Choice;\ntypedef std::string String;\ntypedef SfiBBlock BBlock;\ntypedef SfiFBlock FBlock;\ntypedef SfiSeq Seq;\ntypedef SfiRec Rec;\ntypedef SfiProxy Proxy;\n};\n\n\/* --- type alias frequently used standard lib things --- *\/\ntypedef std::string String;\n\n\n\/* --- generally useful templates --- *\/\ntemplate static void\ndelete_this (Data *d)\n{\n delete d;\n}\n\/* check derivation of Derived from Base *\/\ntemplate \/\/ ex: EnforceDerivedFrom assertion;\nstruct EnforceDerivedFrom {\n EnforceDerivedFrom (Derived *derived = 0,\n Base *base = 0)\n {\n base = derived;\n }\n};\n\/* check derivation of Derived* from Base* *\/\ntemplate \/\/ ex: EnforceDerivedFrom assertion;\nstruct EnforceDerivedFrom {\n EnforceDerivedFrom (Derived *derived = 0,\n Base *base = 0)\n {\n base = derived;\n }\n};\n\/* check derivation through EnforceDerivedFrom<>; *\/\ntemplate void\nassert_derived_from (void)\n{\n EnforceDerivedFrom assertion;\n}\n\n\n\/* --- exceptions --- *\/\nstruct Exception : std::exception {\n explicit Exception (const char *_where) : loc (_where) {};\n virtual const char* where() { return loc; }\nprivate:\n const char *loc;\n};\nstruct InvalidArgument2 : Exception {\n const char *item;\n InvalidArgument2 (const char *where, const char *item) : Exception (where), item (item) {};\n const char* what() const noexcept { return g_intern_strconcat (\"invalid argument: \", item, NULL); }\n};\n#define InvalidArgument(WHAT) InvalidArgument2 (__func__, #WHAT)\nstruct WrongTypeGValue : Exception {\n WrongTypeGValue (const char *where) : Exception (where) {};\n const char* what() const noexcept { return \"GValue contains wrong type for this kind of use\"; }\n};\nstruct DontReach : Exception {\n DontReach (const char *where) : Exception (where) {};\n const char* what() const noexcept { return \"Code section should not be reached\"; }\n};\nstruct InvalidConnection : Exception {\n InvalidConnection (const char *where) : Exception (where) {};\n const char* what() const noexcept { return \"Function to be connected has invalid signature\"; }\n};\n\n\/* --- records & sequences --- *\/\nclass Record {\n Record& operator= (const Record&);\n explicit Record (const Record&);\npublic:\n explicit Record ();\n virtual SfiRec* to_rec ();\n virtual ~Record ();\n};\n\n\n\/* --- class registration --- *\/\n#define BSE_CXX_TYPE_REGISTER(ObjectType, parent, class_info) \\\n BSE_CXX_TYPE_REGISTER_INITIALIZED (ObjectType, parent, class_info, NULL, TypeRegistry::NONE)\n#define BSE_CXX_TYPE_REGISTER_ABSTRACT(ObjectType, parent, class_info) \\\n BSE_CXX_TYPE_REGISTER_INTERN (ObjectType, parent, class_info, NULL, NULL, TypeRegistry::ABSTRACT)\n\n\/* --- class information --- *\/\nstruct ClassInfo\n{\n const char *category;\n const char *blurb;\n const char *file;\n int line;\n ClassInfo (const char *category,\n const char *blurb,\n const char *file,\n int line)\n {\n this->category = category;\n this->blurb = blurb;\n this->file = file;\n this->line = line;\n }\n};\n\n\n\/* --- type registration internals --- *\/\nstruct CxxBaseClass;\nclass TypeRegistry\n{\n GType gtype_id;\npublic:\n enum Flags {\n NONE = 0,\n ABSTRACT = G_TYPE_FLAG_ABSTRACT\n };\n TypeRegistry (guint instance_size,\n const gchar *name,\n const gchar *parent,\n const ClassInfo *cinfo,\n GBaseInitFunc binit,\n void (*class_init) (CxxBaseClass*),\n GInstanceInitFunc iinit,\n Flags flags);\n const GType\n get_type () const\n {\n return gtype_id;\n }\n static void\n init_types ();\n struct TypeEntry;\n};\n\ntemplate const GType\nbse_type_id_wrapper (const char *type_name)\n{\n static GType type = 0;\n if (!type)\n {\n type = g_type_from_name (type_name);\n RAPICORN_ASSERT (type);\n }\n return type;\n}\n\n#define BSE_CXX_TYPE_GET_REGISTERED(NameSpace, ObjectType) \\\n (::Bse::bse_type_id_wrapper (#NameSpace #ObjectType))\n#define BSE_CXX_TYPE_REGISTER_INITIALIZED(ObjectType, parent, cinfo, binit, flags) \\\n BSE_CXX_TYPE_REGISTER_INTERN (ObjectType, parent, cinfo, binit, \\\n ::Bse::cxx_instance_init_trampoline, flags)\n#define BSE_CXX_TYPE_REGISTER_INTERN(ObjectType, parent, cinfo, binit, iinit, flags) \\\n static Bse::TypeRegistry \\\n ObjectType ## _type_keeper (sizeof (ObjectType), \"Bse\" #ObjectType, parent, \\\n cinfo, binit, \\\n ::Bse::cxx_class_init_trampoline, \\\n iinit, flags);\n#define BSE_CXX_UTILS_ALIGNMENT (2 * sizeof (gsize))\n#define BSE_CXX_UTILS_ALIGN(offset) ((offset + BSE_CXX_UTILS_ALIGNMENT - 1) & -BSE_CXX_UTILS_ALIGNMENT)\n#define BSE_CXX_SIZEOF(Class) BSE_CXX_UTILS_ALIGN (sizeof (Class))\n#define BSE_CXX_COMMON_CLASS_SIZE sizeof (CxxBaseClass)\n\n} \/\/ Bse\n\n#endif \/* __BSE_CXX_UTILS_H__ *\/\n<|endoftext|>"} {"text":"#include \n#include \"command.h\"\n#include \"..\/CommandHandler.h\"\n#include \"..\/option.h\"\n#include \"..\/stringparse.h\"\n\n\/* full name of the command *\/\n_CMDNAME(\"delrec\");\n\/* description of the command *\/\n_CMDDESCR(\"delete a recurring message\");\n\/* command usage synopsis *\/\n_CMDUSAGE(\"$delrec ID\");\n\n\/* delrec: delete a recurring message *\/\nstd::string CommandHandler::delrec(char *out, struct command *c)\n{\n\tint opt, all;\n\tsize_t i;\n\tint64_t id;\n\tstatic struct option long_opts[] = {\n\t\t{ \"all\", NO_ARG, 'a' },\n\t\t{ \"help\", NO_ARG, 'h' },\n\t\t{ 0, 0, 0 }\n\t};\n\n\tif (!P_ALMOD(c->privileges)) {\n\t\tPERM_DENIED(out, c->nick, c->argv[0]);\n\t\treturn \"\";\n\t}\n\n\topt_init();\n\tall = 0;\n\twhile ((opt = getopt_long(c->argc, c->argv, \"a\", long_opts)) != EOF) {\n\t\tswitch (opt) {\n\t\tcase 'a':\n\t\t\tall = 1;\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\t_HELPMSG(out, _CMDNAME, _CMDUSAGE, _CMDDESCR);\n\t\t\treturn \"\";\n\t\tcase '?':\n\t\t\t_sprintf(out, MAX_MSG, \"%s\", opterr());\n\t\t\treturn \"\";\n\t\tdefault:\n\t\t\treturn \"\";\n\t\t}\n\t}\n\n\tif (all) {\n\t\tif (optind != c->argc) {\n\t\t\t_USAGEMSG(out, _CMDNAME, _CMDUSAGE);\n\t\t\treturn \"\";\n\t\t}\n\t\tfor (i = 0; i < m_evtp->messages()->size(); ++i)\n\t\t\tm_evtp->delMessage(1);\n\t\t_sprintf(out, MAX_MSG, \"@%s, all recurring message deleted\",\n\t\t\t\tc->nick);\n\t\treturn \"\";\n\t}\n\n\tif ((optind != c->argc - 1)) {\n\t\t_USAGEMSG(out, _CMDNAME, _CMDUSAGE);\n\t\treturn \"\";\n\t}\n\n\tif (!parsenum(c->argv[optind], &id)) {\n\t\t_sprintf(out, MAX_MSG, \"%s: invalid number: %s\",\n\t\t\t\tc->argv[0], c->argv[optind]);\n\t\treturn \"\";\n\t}\n\n\tif (!m_evtp->delMessage(id))\n\t\t_sprintf(out, MAX_MSG, \"%s: invalid ID provided\", c->argv[0]);\n\telse\n\t\t_sprintf(out, MAX_MSG, \"@%s, recurring message %ld deleted.\",\n\t\t\t\tc->nick, id);\n\treturn \"\";\n}\ndelrec all fix#include \n#include \"command.h\"\n#include \"..\/CommandHandler.h\"\n#include \"..\/option.h\"\n#include \"..\/stringparse.h\"\n\n\/* full name of the command *\/\n_CMDNAME(\"delrec\");\n\/* description of the command *\/\n_CMDDESCR(\"delete a recurring message\");\n\/* command usage synopsis *\/\n_CMDUSAGE(\"$delrec ID\");\n\n\/* delrec: delete a recurring message *\/\nstd::string CommandHandler::delrec(char *out, struct command *c)\n{\n\tint opt, all;\n\tsize_t i;\n\tint64_t id;\n\tstatic struct option long_opts[] = {\n\t\t{ \"all\", NO_ARG, 'a' },\n\t\t{ \"help\", NO_ARG, 'h' },\n\t\t{ 0, 0, 0 }\n\t};\n\n\tif (!P_ALMOD(c->privileges)) {\n\t\tPERM_DENIED(out, c->nick, c->argv[0]);\n\t\treturn \"\";\n\t}\n\n\topt_init();\n\tall = 0;\n\twhile ((opt = getopt_long(c->argc, c->argv, \"a\", long_opts)) != EOF) {\n\t\tswitch (opt) {\n\t\tcase 'a':\n\t\t\tall = 1;\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\t_HELPMSG(out, _CMDNAME, _CMDUSAGE, _CMDDESCR);\n\t\t\treturn \"\";\n\t\tcase '?':\n\t\t\t_sprintf(out, MAX_MSG, \"%s\", opterr());\n\t\t\treturn \"\";\n\t\tdefault:\n\t\t\treturn \"\";\n\t\t}\n\t}\n\n\tif (all) {\n\t\tif (optind != c->argc) {\n\t\t\t_USAGEMSG(out, _CMDNAME, _CMDUSAGE);\n\t\t\treturn \"\";\n\t\t}\n\t\twhile (!m_evtp->messages()->empty())\n\t\t\tm_evtp->delMessage(1);\n\t\t_sprintf(out, MAX_MSG, \"@%s, all recurring message deleted\",\n\t\t\t\tc->nick);\n\t\treturn \"\";\n\t}\n\n\tif ((optind != c->argc - 1)) {\n\t\t_USAGEMSG(out, _CMDNAME, _CMDUSAGE);\n\t\treturn \"\";\n\t}\n\n\tif (!parsenum(c->argv[optind], &id)) {\n\t\t_sprintf(out, MAX_MSG, \"%s: invalid number: %s\",\n\t\t\t\tc->argv[0], c->argv[optind]);\n\t\treturn \"\";\n\t}\n\n\tif (!m_evtp->delMessage(id))\n\t\t_sprintf(out, MAX_MSG, \"%s: invalid ID provided\", c->argv[0]);\n\telse\n\t\t_sprintf(out, MAX_MSG, \"@%s, recurring message %ld deleted.\",\n\t\t\t\tc->nick, id);\n\treturn \"\";\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential.\n#include \"stdafx.h\"\n#include \"CoreThread.h\"\n#include \n\ntypedef struct tagTHREADNAME_INFO\n{\n DWORD dwType; \/\/ must be 0x1000\n LPCSTR szName; \/\/ pointer to name (in user addr space)\n DWORD dwThreadID; \/\/ thread ID (-1=caller thread)\n DWORD dwFlags; \/\/ reserved for future use, must be zero\n} THREADNAME_INFO;\n\nvoid SetThreadName(DWORD dwThreadID, LPCSTR szThreadName)\n{\n THREADNAME_INFO info;\n info.dwType = 0x1000;\n info.szName = szThreadName;\n info.dwThreadID = dwThreadID;\n info.dwFlags = 0;\n\n __try\n {\n \/\/ Magic exception which informs the OS of this thread's name\n RaiseException(0x406D1388, 0, sizeof(info)\/sizeof(DWORD), (ULONG_PTR*)&info);\n }\n __except(EXCEPTION_CONTINUE_EXECUTION)\n {\n }\n}\n\nvoid CoreThread::SetCurrentThreadName(void) const {\n#if IS_INTERNAL_BUILD\n ::SetThreadName(\n GetCurrentThreadId(),\n m_name\n );\n#endif\n}\nAdding pack guards to try to get thread naming working in 64-bit\/\/ Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential.\n#include \"stdafx.h\"\n#include \"CoreThread.h\"\n#include \n\n#pragma pack(push, 8)\ntypedef struct tagTHREADNAME_INFO\n{\n DWORD dwType; \/\/ must be 0x1000\n LPCSTR szName; \/\/ pointer to name (in user addr space)\n DWORD dwThreadID; \/\/ thread ID (-1=caller thread)\n DWORD dwFlags; \/\/ reserved for future use, must be zero\n} THREADNAME_INFO;\n#pragma pack(pop)\n\nvoid SetThreadName(DWORD dwThreadID, LPCSTR szThreadName)\n{\n THREADNAME_INFO info;\n info.dwType = 0x1000;\n info.szName = szThreadName;\n info.dwThreadID = dwThreadID;\n info.dwFlags = 0;\n\n __try\n {\n \/\/ Magic exception which informs the OS of this thread's name\n RaiseException(0x406D1388, 0, sizeof(info)\/sizeof(DWORD), (ULONG_PTR*)&info);\n }\n __except(EXCEPTION_CONTINUE_EXECUTION)\n {\n }\n}\n\nvoid CoreThread::SetCurrentThreadName(void) const {\n#if IS_INTERNAL_BUILD\n ::SetThreadName(\n GetCurrentThreadId(),\n m_name\n );\n#endif\n}\n<|endoftext|>"} {"text":"#include \"Daemon.h\"\n\n#ifndef _WIN32\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Config.h\"\n#include \"FS.h\"\n#include \"Log.h\"\n\nvoid handle_signal(int sig)\n{\n\tswitch (sig)\n\t{\n\t\tcase SIGHUP:\n\t\t\tLogPrint(eLogInfo, \"Daemon: Got SIGHUP, reopening log...\");\n\t\t\ti2p::log::Logger().Reopen ();\n\t\tbreak;\n\t\tcase SIGINT:\n\t\t\tDaemon.gracefullShutdownInterval = 10*60; \/\/ 10 minutes\n\t\t\tLogPrint(eLogInfo, \"Graceful shutdown after \", Daemon.gracefullShutdownInterval, \" seconds\");\n\t\tbreak;\t\n\t\tcase SIGABRT:\n\t\tcase SIGTERM:\n\t\t\tDaemon.running = 0; \/\/ Exit loop\n\t\tbreak;\n\t}\n}\n\nnamespace i2p\n{\n\tnamespace util\n\t{\n\t\tbool DaemonLinux::start()\n\t\t{\n\t\t\tif (isDaemon == 1)\n\t\t\t{\n\t\t\t\tpid_t pid;\n\t\t\t\tpid = fork();\n\t\t\t\tif (pid > 0) \/\/ parent\n\t\t\t\t\t::exit (EXIT_SUCCESS);\n\n\t\t\t\tif (pid < 0) \/\/ error\n\t\t\t\t{\n\t\t\t\t\tLogPrint(eLogError, \"Daemon: could not fork: \", strerror(errno));\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\t\/\/ child\n\t\t\t\tumask(S_IWGRP | S_IRWXO); \/\/ 0027\n\t\t\t\tint sid = setsid();\n\t\t\t\tif (sid < 0)\n\t\t\t\t{\n\t\t\t\t\tLogPrint(eLogError, \"Daemon: could not create process group.\");\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tstd::string d = i2p::fs::GetDataDir();\n\t\t\t\tif (chdir(d.c_str()) != 0)\n\t\t\t\t{\n\t\t\t\t\tLogPrint(eLogError, \"Daemon: could not chdir: \", strerror(errno));\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\t\/\/ close stdin\/stdout\/stderr descriptors\n\t\t\t\tfreopen(\"\/dev\/null\", \"r\", stdin);\n\t\t\t\tfreopen(\"\/dev\/null\", \"w\", stdout);\n\t\t\t\tfreopen(\"\/dev\/null\", \"w\", stderr);\n\t\t\t}\n\n\t\t\t\/\/ Pidfile\n\t\t\t\/\/ this code is c-styled and a bit ugly, but we need fd for locking pidfile\n\t\t\tstd::string pidfile; i2p::config::GetOption(\"pidfile\", pidfile);\n\t\t\tif (pidfile == \"\") {\n\t\t\t\tpidfile = i2p::fs::DataDirPath(\"i2pd.pid\");\n\t\t\t}\n\t\t\tif (pidfile != \"\") {\n\t\t\t\tpidFH = open(pidfile.c_str(), O_RDWR | O_CREAT, 0600);\n\t\t\t\tif (pidFH < 0)\n\t\t\t\t{\n\t\t\t\t\tLogPrint(eLogError, \"Daemon: could not create pid file \", pidfile, \": \", strerror(errno));\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (lockf(pidFH, F_TLOCK, 0) != 0)\n\t\t\t\t{\n\t\t\t\t\tLogPrint(eLogError, \"Daemon: could not lock pid file \", pidfile, \": \", strerror(errno));\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tchar pid[10];\n\t\t\t\tsprintf(pid, \"%d\\n\", getpid());\n\t\t\t\tftruncate(pidFH, 0);\n\t\t\t\tif (write(pidFH, pid, strlen(pid)) < 0)\n\t\t\t\t{\n\t\t\t\t\tLogPrint(eLogError, \"Daemon: could not write pidfile: \", strerror(errno));\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tgracefullShutdownInterval = 0; \/\/ not specified\n\n\t\t\t\/\/ Signal handler\n\t\t\tstruct sigaction sa;\n\t\t\tsa.sa_handler = handle_signal;\n\t\t\tsigemptyset(&sa.sa_mask);\n\t\t\tsa.sa_flags = SA_RESTART;\n\t\t\tsigaction(SIGHUP, &sa, 0);\n\t\t\tsigaction(SIGABRT, &sa, 0);\n\t\t\tsigaction(SIGTERM, &sa, 0);\n\t\t\tsigaction(SIGINT, &sa, 0);\n\n\t\t\treturn Daemon_Singleton::start();\n\t\t}\n\n\t\tbool DaemonLinux::stop()\n\t\t{\n\t\t\ti2p::fs::Remove(pidfile);\n\n\t\t\treturn Daemon_Singleton::stop();\t\t\t\n\t\t}\n\n\t\tvoid DaemonLinux::run ()\n\t\t{\n\t\t\twhile (running)\n\t\t\t{\n\t\t\t\tstd::this_thread::sleep_for (std::chrono::seconds(1));\n\t\t\t\tif (gracefullShutdownInterval)\n\t\t\t\t{\n\t\t\t\t\tgracefullShutdownInterval--; \/\/ - 1 second\n\t\t\t\t\tif (gracefullShutdownInterval <= 0) \n\t\t\t\t\t{\t\n\t\t\t\t\t\tLogPrint(eLogInfo, \"Graceful shutdown\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t}\n}\n\n#endif\ngraceful shutdown by SIGINT#include \"Daemon.h\"\n\n#ifndef _WIN32\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Config.h\"\n#include \"FS.h\"\n#include \"Log.h\"\n#include \"RouterContext.h\"\n\nvoid handle_signal(int sig)\n{\n\tswitch (sig)\n\t{\n\t\tcase SIGHUP:\n\t\t\tLogPrint(eLogInfo, \"Daemon: Got SIGHUP, reopening log...\");\n\t\t\ti2p::log::Logger().Reopen ();\n\t\tbreak;\n\t\tcase SIGINT:\n\t\t\ti2p::context.SetAcceptsTunnels (false);\n\t\t\tDaemon.gracefullShutdownInterval = 10*60; \/\/ 10 minutes\n\t\t\tLogPrint(eLogInfo, \"Graceful shutdown after \", Daemon.gracefullShutdownInterval, \" seconds\");\n\t\tbreak;\t\n\t\tcase SIGABRT:\n\t\tcase SIGTERM:\n\t\t\tDaemon.running = 0; \/\/ Exit loop\n\t\tbreak;\n\t}\n}\n\nnamespace i2p\n{\n\tnamespace util\n\t{\n\t\tbool DaemonLinux::start()\n\t\t{\n\t\t\tif (isDaemon == 1)\n\t\t\t{\n\t\t\t\tpid_t pid;\n\t\t\t\tpid = fork();\n\t\t\t\tif (pid > 0) \/\/ parent\n\t\t\t\t\t::exit (EXIT_SUCCESS);\n\n\t\t\t\tif (pid < 0) \/\/ error\n\t\t\t\t{\n\t\t\t\t\tLogPrint(eLogError, \"Daemon: could not fork: \", strerror(errno));\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\t\/\/ child\n\t\t\t\tumask(S_IWGRP | S_IRWXO); \/\/ 0027\n\t\t\t\tint sid = setsid();\n\t\t\t\tif (sid < 0)\n\t\t\t\t{\n\t\t\t\t\tLogPrint(eLogError, \"Daemon: could not create process group.\");\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tstd::string d = i2p::fs::GetDataDir();\n\t\t\t\tif (chdir(d.c_str()) != 0)\n\t\t\t\t{\n\t\t\t\t\tLogPrint(eLogError, \"Daemon: could not chdir: \", strerror(errno));\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\t\/\/ close stdin\/stdout\/stderr descriptors\n\t\t\t\tfreopen(\"\/dev\/null\", \"r\", stdin);\n\t\t\t\tfreopen(\"\/dev\/null\", \"w\", stdout);\n\t\t\t\tfreopen(\"\/dev\/null\", \"w\", stderr);\n\t\t\t}\n\n\t\t\t\/\/ Pidfile\n\t\t\t\/\/ this code is c-styled and a bit ugly, but we need fd for locking pidfile\n\t\t\tstd::string pidfile; i2p::config::GetOption(\"pidfile\", pidfile);\n\t\t\tif (pidfile == \"\") {\n\t\t\t\tpidfile = i2p::fs::DataDirPath(\"i2pd.pid\");\n\t\t\t}\n\t\t\tif (pidfile != \"\") {\n\t\t\t\tpidFH = open(pidfile.c_str(), O_RDWR | O_CREAT, 0600);\n\t\t\t\tif (pidFH < 0)\n\t\t\t\t{\n\t\t\t\t\tLogPrint(eLogError, \"Daemon: could not create pid file \", pidfile, \": \", strerror(errno));\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (lockf(pidFH, F_TLOCK, 0) != 0)\n\t\t\t\t{\n\t\t\t\t\tLogPrint(eLogError, \"Daemon: could not lock pid file \", pidfile, \": \", strerror(errno));\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tchar pid[10];\n\t\t\t\tsprintf(pid, \"%d\\n\", getpid());\n\t\t\t\tftruncate(pidFH, 0);\n\t\t\t\tif (write(pidFH, pid, strlen(pid)) < 0)\n\t\t\t\t{\n\t\t\t\t\tLogPrint(eLogError, \"Daemon: could not write pidfile: \", strerror(errno));\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tgracefullShutdownInterval = 0; \/\/ not specified\n\n\t\t\t\/\/ Signal handler\n\t\t\tstruct sigaction sa;\n\t\t\tsa.sa_handler = handle_signal;\n\t\t\tsigemptyset(&sa.sa_mask);\n\t\t\tsa.sa_flags = SA_RESTART;\n\t\t\tsigaction(SIGHUP, &sa, 0);\n\t\t\tsigaction(SIGABRT, &sa, 0);\n\t\t\tsigaction(SIGTERM, &sa, 0);\n\t\t\tsigaction(SIGINT, &sa, 0);\n\n\t\t\treturn Daemon_Singleton::start();\n\t\t}\n\n\t\tbool DaemonLinux::stop()\n\t\t{\n\t\t\ti2p::fs::Remove(pidfile);\n\n\t\t\treturn Daemon_Singleton::stop();\t\t\t\n\t\t}\n\n\t\tvoid DaemonLinux::run ()\n\t\t{\n\t\t\twhile (running)\n\t\t\t{\n\t\t\t\tstd::this_thread::sleep_for (std::chrono::seconds(1));\n\t\t\t\tif (gracefullShutdownInterval)\n\t\t\t\t{\n\t\t\t\t\tgracefullShutdownInterval--; \/\/ - 1 second\n\t\t\t\t\tif (gracefullShutdownInterval <= 0) \n\t\t\t\t\t{\t\n\t\t\t\t\t\tLogPrint(eLogInfo, \"Graceful shutdown\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t}\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \"Device_HM10.h\"\n\nvoid DeviceHM10::serialPrintf(const char *format, ...) {\n\n va_list args;\n char buffer[100];\n\n va_start (args, format);\n vsnprintf (buffer, sizeof(buffer), format, args);\n buffer[sizeof(buffer) - 1] = '\\0';\n\n serial->print(buffer);\n}\n\n \nvoid DeviceHM10::removeBytes(int bLen) {\n\n buffer->removeBytes(bLen);\n checkConnectionStatus();\n}\n\n\nunsigned char DeviceHM10::getByte(unsigned int pos) {\n\n return buffer->getByte(pos);\n}\n\n\nunsigned char * DeviceHM10::getPayload() {\n\n return buffer->getPayload();\n}\n\n\nvoid DeviceHM10::dump(const char * msg, const unsigned char * payload, size_t len) {\n\n Serial.print(msg);\n \n for (unsigned int i = 0; i < len; i++) {\n char buf[4];\n snprintf(buf, sizeof(buf), \"%.2X\", payload[i]);\n Serial.print(buf);\n }\n\n Serial.println(\"\");\n}\n\n\nbool DeviceHM10::isDeviceConnected() {\n\n return status == STATUS_CONNECTED || status == STATUS_DISCONNECTING;\n}\n\n\nbool DeviceHM10::checkConnectionStatus() {\n \n bool connectionStatus = DeviceHM10::isDeviceConnected();\n \n if (buffer->getLen() < 3) {\n int count = serial->readBytes(buffer->getPayload() + buffer->getLen(), 3);\n buffer->addByteCount(count);\n if (count < 3) {\n return connectionStatus;\n }\n }\n \n unsigned char * payload = buffer->getPayload();\n \/\/ OK+CONNX \/ OK+LOST\n if (payload[0] != 'O' || payload[1] != 'K' || payload[2] != '+') {\n return connectionStatus;\n }\n\n\n if (buffer->getLen() < 7) {\n int need = 8 - buffer->getLen();\n int count = serial->readBytes(buffer->getPayload() + buffer->getLen(), need);\n buffer->addByteCount(count);\n if (buffer->getLen() < 7) {\n return connectionStatus;\n }\n }\n\n if (buffer->getLen() > 7) {\n if ( memcmp(buffer->getPayload(), \"OK+CONNE\", 8) == 0 || \n memcmp(buffer->getPayload(), \"OK+CONNF\", 8) == 0 \n ) {\n \n if (status == STATUS_CONNECTING) {\n status = STATUS_INITIALIZING;\n }\n else {\n status = STATUS_DISCONNECTED;\n }\n buffer->removeBytes(8);\n return connectionStatus;\n }\n\n if (memcmp(buffer->getPayload(), \"OK+CONNA\", 8) == 0) {\n buffer->removeBytes(8);\n return connectionStatus;\n }\n }\n \n if (memcmp(buffer->getPayload(), \"OK+CONN\", 7) == 0) {\n buffer->removeBytes(7);\n newConnection = true;\n status = STATUS_CONNECTED;\n Serial.println(\"device connected\");\n return true;\n }\n\n \/\/ BAD: assuming it is OK+LOST\n return reset(\"device disconnected\");\n}\n\n\nbool DeviceHM10::hasBytes(unsigned int bytes) {\n\n if (buffer->hasBytes(bytes)) {\n return true;\n }\n\n int bAvailable = bytes - buffer->getLen();\n\n \n \/\/ do not loop - try to keep the buffer data queue small\n if (serial->available()) {\n if (bAvailable > buffer->getFreeLen()) {\n bAvailable = buffer->getFreeLen();\n }\n\n int total = serial->readBytes(buffer->getPayload() + buffer->getLen(), bAvailable);\n if (total > 0) {\n buffer->addByteCount(total);\n }\n }\n\n if (!checkConnectionStatus()) {\n return false;\n }\n\n if (buffer->hasBytes(bytes)) {\n return true;\n }\n\n return false;\n}\n\n\nvoid DeviceHM10::write(const unsigned char *payload, int len) {\n\n if (status != STATUS_CONNECTED) {\n return;\n }\n\n serial->write(payload, len);\n}\n\n\nbool DeviceHM10::reset(const char * message) {\n\n Serial.println(message);\n\n if (status == STATUS_DISCONNECTING) {\n status = STATUS_DISCONNECTED;\n }\n else {\n status = STATUS_INITIALIZING;\n }\n \n newConnection = false;\n serial->flush();\n buffer->reset();\n\n \/\/ purge serial buffer\n while (serial->available()) {\n int val = serial->read();\n }\n\n return false;\n}\n\n\nbool DeviceHM10::isNewConnection() {\n \n if (newConnection == true) {\n newConnection = false;\n return true;\n }\n\n return false;\n}\n\n\nbool DeviceHM10::isConnected() {\n\n if (status == STATUS_CONNECTED) {\n return true;\n }\n else if (status == STATUS_DISCONNECTED) {\n return false;\n }\n\n if (status == STATUS_INITIALIZING) {\n if (!sendCommand(\"CON\", mac)) return false;\n status = STATUS_CONNECTING;\n }\n\n if (status == STATUS_DISCONNECTING) {\n \/\/ Empty AT command disconnects the device\n serial->print(\"AT\");\n }\n\n return checkConnectionStatus();\n}\n\n\nbool DeviceHM10::sendCommand(const char *cmd, const char *value) {\n\n char buffer[40];\n char expected[40];\n int count = 0;\n\n while (count < 5) {\n delay(count * 100);\n count++;\n\n \/\/ purge serial buffer\n while (serial->available()) {\n int val = serial->read();\n }\n \n if (cmd == NULL || strlen(cmd) == 0) {\n serialPrintf(\"AT\");\n snprintf(expected, sizeof(expected), \"OK\");\n }\n else {\n serialPrintf(\"AT+%s%s\", cmd, value);\n \n if (value == NULL || strlen(value) == 0) {\n snprintf(expected, sizeof(expected), \"OK+%s\", cmd);\n }\n else if (cmd == \"CON\") {\n return true;\n \/\/snprintf(expected, sizeof(expected), \"OK+CONNA\");\n }\n else {\n snprintf(expected, sizeof(expected), \"OK+Set:%s\", value);\n }\n }\n \n int total = serial->readBytes(buffer, strlen(expected));\n \n if (total >= 0) {\n \/\/ read extra bytes still in buffer\n while (serial->available() && (total < sizeof(buffer))) {\n buffer[total++] = serial->read();\n }\n \n buffer[total] = '\\0';\n }\n \n if (total <= 0) {\n continue;\n }\n \n if (strcmp(buffer, expected) != 0) {\n Serial.print(\"command \");\n Serial.print(cmd);\n Serial.print(\" failed: \");\n Serial.println(buffer);\n Serial.print(\"expected: \");\n Serial.println(expected);\n \n return false;\n }\n \n return true;\n }\n\n Serial.print(\"failed to get answer for command \");\n Serial.println(cmd);\n\n return false;\n}\n\n\nvoid DeviceHM10::connect() {\n\n if (status == STATUS_CONNECTED || status == STATUS_INITIALIZING || status == STATUS_CONNECTING) {\n return;\n }\n \n status = STATUS_INITIALIZING;\n \/\/ TODO: Do discovery\n}\n\n\nvoid DeviceHM10::disconnect() {\n\n if (status == STATUS_DISCONNECTED) {\n return;\n }\n\n status = STATUS_DISCONNECTING;\n}\n\n\nboolean DeviceHM10::initDevice() {\n if (!sendCommand(\"\", \"\")) return false;\n if (!sendCommand(\"RENEW\", \"\")) return false;\n if (!sendCommand(\"IMME\", \"1\")) return false;\n if (!sendCommand(\"MODE\", \"1\")) return false;\n if (!sendCommand(\"COMP\", \"1\")) return false;\n if (!sendCommand(\"NOTI\", \"1\")) return false;\n if (!sendCommand(\"UUID\", \"0x1800\")) return false;\n if (!sendCommand(\"CHAR\", \"0x2A80\")) return false;\n if (!sendCommand(\"ROLE\", \"1\")) return false;\n delay(1000);\n\n return true;\n}\n\n\nvoid DeviceHM10::init() {\n\n#if defined(HAVE_HWSERIAL1)\n serial = &Serial1;\n#else\n \/\/serial = new SoftwareSerial(TX_PIN, RX_PIN);\n serial = new AltSoftSerial(TX_PIN, RX_PIN);\n#endif\n\n serial->begin(9600);\n\n while (!initDevice()) {\n }\n}\n\n\nDeviceHM10::DeviceHM10() {\n\n buffer = new Buffer();\n newConnection = false;\n status = STATUS_DISCONNECTED;\n}\n\n\nDeviceHM10::~DeviceHM10() {\n\n delete(buffer);\n}\n\n\nFix Arduino connect\/disconnect#include \"Device_HM10.h\"\n\nvoid DeviceHM10::serialPrintf(const char *format, ...) {\n\n va_list args;\n char buffer[100];\n\n va_start (args, format);\n vsnprintf (buffer, sizeof(buffer), format, args);\n buffer[sizeof(buffer) - 1] = '\\0';\n\n serial->print(buffer);\n}\n\n \nvoid DeviceHM10::removeBytes(int bLen) {\n\n buffer->removeBytes(bLen);\n checkConnectionStatus();\n}\n\n\nunsigned char DeviceHM10::getByte(unsigned int pos) {\n\n return buffer->getByte(pos);\n}\n\n\nunsigned char * DeviceHM10::getPayload() {\n\n return buffer->getPayload();\n}\n\n\nvoid DeviceHM10::dump(const char * msg, const unsigned char * payload, size_t len) {\n\n Serial.print(msg);\n \n for (unsigned int i = 0; i < len; i++) {\n char buf[4];\n snprintf(buf, sizeof(buf), \"%.2X\", payload[i]);\n Serial.print(buf);\n }\n\n Serial.println(\"\");\n}\n\n\nbool DeviceHM10::isDeviceConnected() {\n\n return status == STATUS_CONNECTED || status == STATUS_DISCONNECTING;\n}\n\n\nbool DeviceHM10::checkConnectionStatus() {\n \n bool connectionStatus = DeviceHM10::isDeviceConnected();\n \n if (buffer->getLen() < 3) {\n int count = serial->readBytes(buffer->getPayload() + buffer->getLen(), 3);\n buffer->addByteCount(count);\n if (count < 3) {\n return connectionStatus;\n }\n }\n \n unsigned char * payload = buffer->getPayload();\n \/\/ OK+CONNX \/ OK+LOST\n if (payload[0] != 'O' || payload[1] != 'K' || payload[2] != '+') {\n return connectionStatus;\n }\n\n\n if (buffer->getLen() < 7) {\n int need = 8 - buffer->getLen();\n int count = serial->readBytes(buffer->getPayload() + buffer->getLen(), need);\n buffer->addByteCount(count);\n if (buffer->getLen() < 7) {\n return connectionStatus;\n }\n }\n\n if (buffer->getLen() > 7) {\n if ( memcmp(buffer->getPayload(), \"OK+CONNE\", 8) == 0 || \n memcmp(buffer->getPayload(), \"OK+CONNF\", 8) == 0 \n ) {\n \n if (status == STATUS_CONNECTING) {\n status = STATUS_INITIALIZING;\n }\n else {\n status = STATUS_DISCONNECTED;\n }\n buffer->removeBytes(8);\n return connectionStatus;\n }\n\n if (memcmp(buffer->getPayload(), \"OK+CONNA\", 8) == 0) {\n buffer->removeBytes(8);\n return connectionStatus;\n }\n }\n \n if (memcmp(buffer->getPayload(), \"OK+CONN\", 7) == 0) {\n buffer->removeBytes(7);\n newConnection = true;\n status = STATUS_CONNECTED;\n Serial.println(\"device connected\");\n return true;\n }\n\n \/\/ BAD: assuming it is OK+LOST\n return reset(\"device disconnected\");\n}\n\n\nbool DeviceHM10::hasBytes(unsigned int bytes) {\n\n if (buffer->hasBytes(bytes)) {\n return true;\n }\n\n int bAvailable = bytes - buffer->getLen();\n\n \n \/\/ do not loop - try to keep the buffer data queue small\n if (serial->available()) {\n if (bAvailable > buffer->getFreeLen()) {\n bAvailable = buffer->getFreeLen();\n }\n\n int total = serial->readBytes(buffer->getPayload() + buffer->getLen(), bAvailable);\n if (total > 0) {\n buffer->addByteCount(total);\n }\n }\n\n if (!checkConnectionStatus()) {\n return false;\n }\n\n if (buffer->hasBytes(bytes)) {\n return true;\n }\n\n return false;\n}\n\n\nvoid DeviceHM10::write(const unsigned char *payload, int len) {\n\n if (status != STATUS_CONNECTED) {\n return;\n }\n\n serial->write(payload, len);\n}\n\n\nbool DeviceHM10::reset(const char * message) {\n\n Serial.println(message);\n\n if (status == STATUS_DISCONNECTING) {\n status = STATUS_DISCONNECTED;\n }\n else {\n status = STATUS_INITIALIZING;\n }\n \n newConnection = false;\n serial->flush();\n buffer->reset();\n\n \/\/ purge serial buffer\n while (serial->available()) {\n int val = serial->read();\n }\n\n return false;\n}\n\n\nbool DeviceHM10::isNewConnection() {\n \n if (newConnection == true) {\n newConnection = false;\n return true;\n }\n\n return false;\n}\n\n\nbool DeviceHM10::isConnected() {\n\n if (status == STATUS_CONNECTED) {\n return true;\n }\n else if (status == STATUS_DISCONNECTED) {\n return false;\n }\n\n if (status == STATUS_INITIALIZING) {\n if (!sendCommand(\"CON\", mac)) return false;\n status = STATUS_CONNECTING;\n }\n\n if (status == STATUS_DISCONNECTING) {\n \/\/ Empty AT command disconnects the device\n serial->print(\"AT\");\n }\n\n return checkConnectionStatus();\n}\n\n\nbool DeviceHM10::sendCommand(const char *cmd, const char *value) {\n\n char buffer[40];\n char expected[40];\n int count = 0;\n\n while (count < 5) {\n delay(count * 100);\n count++;\n\n \/\/ purge serial buffer\n while (serial->available()) {\n int val = serial->read();\n }\n \n if (cmd == NULL || strlen(cmd) == 0) {\n serialPrintf(\"AT\");\n snprintf(expected, sizeof(expected), \"OK\");\n }\n else {\n serialPrintf(\"AT+%s%s\", cmd, value);\n \n if (value == NULL || strlen(value) == 0) {\n snprintf(expected, sizeof(expected), \"OK+%s\", cmd);\n }\n else if (cmd == \"CON\") {\n return true;\n \/\/snprintf(expected, sizeof(expected), \"OK+CONNA\");\n }\n else {\n snprintf(expected, sizeof(expected), \"OK+Set:%s\", value);\n }\n }\n \n int total = serial->readBytes(buffer, strlen(expected));\n \n if (total >= 0) {\n \/\/ read extra bytes still in buffer\n while (serial->available() && (total < sizeof(buffer))) {\n buffer[total++] = serial->read();\n }\n \n buffer[total] = '\\0';\n }\n \n if (total <= 0) {\n continue;\n }\n \n if (strcmp(buffer, expected) != 0) {\n Serial.print(\"command \");\n Serial.print(cmd);\n Serial.print(\" failed: \");\n Serial.println(buffer);\n Serial.print(\"expected: \");\n Serial.println(expected);\n \n return false;\n }\n \n return true;\n }\n\n Serial.print(\"failed to get answer for command \");\n Serial.println(cmd);\n\n return false;\n}\n\n\nvoid DeviceHM10::connect() {\n\n if (status == STATUS_CONNECTED || status == STATUS_INITIALIZING || status == STATUS_CONNECTING) {\n return;\n }\n \n status = STATUS_INITIALIZING;\n \/\/ TODO: Do discovery\n}\n\n\nvoid DeviceHM10::disconnect() {\n\n if (status == STATUS_DISCONNECTED) {\n return;\n }\n\n if (status == STATUS_INITIALIZING) {\n status = STATUS_DISCONNECTED;\n return;\n }\n\n status = STATUS_DISCONNECTING;\n}\n\n\nboolean DeviceHM10::initDevice() {\n if (!sendCommand(\"\", \"\")) return false;\n if (!sendCommand(\"RENEW\", \"\")) return false;\n if (!sendCommand(\"IMME\", \"1\")) return false;\n if (!sendCommand(\"MODE\", \"1\")) return false;\n if (!sendCommand(\"COMP\", \"1\")) return false;\n if (!sendCommand(\"NOTI\", \"1\")) return false;\n if (!sendCommand(\"UUID\", \"0x1800\")) return false;\n if (!sendCommand(\"CHAR\", \"0x2A80\")) return false;\n if (!sendCommand(\"ROLE\", \"1\")) return false;\n delay(1000);\n\n return true;\n}\n\n\nvoid DeviceHM10::init() {\n\n#if defined(HAVE_HWSERIAL1)\n serial = &Serial1;\n#else\n \/\/serial = new SoftwareSerial(TX_PIN, RX_PIN);\n serial = new AltSoftSerial(TX_PIN, RX_PIN);\n#endif\n\n serial->begin(9600);\n\n while (!initDevice()) {\n }\n}\n\n\nDeviceHM10::DeviceHM10() {\n\n buffer = new Buffer();\n newConnection = false;\n status = STATUS_DISCONNECTED;\n}\n\n\nDeviceHM10::~DeviceHM10() {\n\n delete(buffer);\n}\n\n\n<|endoftext|>"} {"text":"#ifdef PKMDS_CMAKE_USED\n\/\/#include \n#include \n#else\n\/\/#include \"..\\\\..\\\\include\\\\pkmds\\\\pkmds_sql.h\"\n#include \"..\\\\..\\\\include\\\\pkmds\\\\pkmds_gba.h\"\n#endif\n\/\/#include \n\/\/#include \nusing namespace std;\nstring outputpath = \"C:\\\\Users\\\\Michael Bond\\\\Downloads\\\\GBA PKM DUMPED\\\\\";\nint main(int argc, char* argv[])\n{\n\tstring savefile;\n\t\/\/savefile = \"C:\\\\Users\\\\Michael Bond\\\\Dropbox\\\\Saves\\\\pokemon_emerald_version - Copy2.sav\";\n\tsavefile = \"C:\\\\Users\\\\Michael Bond\\\\Dropbox\\\\Saves\\\\Pokemon - Fire Red GBA_MODIFIED.sav\";\n\tconst char * pkmfile = \"C:\\\\Users\\\\Michael Bond\\\\Dropbox\\\\Saves\\\\Gengar_heart.3gpkm\";\n\tgbasavefilepacked* savin = new gbasavefilepacked();\n\tgbasavefile* sav = new gbasavefile();\n\tpokemon_gen3* gbapkm = new pokemon_gen3();\n\tpokemon_obj * pkm = new pokemon_obj();\n\tread(savefile.c_str(),savin);\n\tbuildgbasave(savin,sav);\n\topendb(\"C:\\\\Users\\\\Michael Bond\\\\Dropbox\\\\PKMDS Databases\\\\veekun-pokedex.sqlite\");\n\n\t\/\/read(pkmfile,gbapkm);\n\t\/\/dostuff(gbapkm);\n\n\tfor(int box = 0; box < 14; box++)\n\t{\n\t\tfor(int slot = 0; slot < 30; slot++)\n\t\t{\n\t\t\tgbapkm = &(sav->pcstorage.pcstorage[box][slot]);\n\t\t\tdecryptgbapkm(gbapkm);\n\t\t\tshufflegbapkm(gbapkm,true);\n\t\t\tif(gbapkm->data.species != GBASpecies::NOTHING)\n\t\t\t{\n\t\t\t\t\/\/if(gbapkm->data.species == GBASpecies::squirtle)\n\t\t\t\t\/\/{\n\t\t\t\t\/\/uint32 * ribbons = reinterpret_cast(&(gbapkm->data.ribbons));\n\t\t\t\t\/\/if(*ribbons != 0)\n\t\t\t\t\/\/{\n\t\t\t\tif((box == 0) & (slot == 0))\n\t\t\t\t{\n\t\t\t\t\t\/\/dostuff(gbapkm);\n\t\t\t\t\tconvertgen3pkmtogen5(gbapkm,pkm);\n\t\t\t\t}\n\t\t\t\t\/\/}\n\t\t\t\t\/\/}\n\t\t\t}\n\t\t}\n\t}\n\tclosedb();\n\tcout << \"\\nEND\\n\";\n\tstring test;\n\t\/\/cin >> test;\n\treturn 0;\n}\nUpdate gen-3-test.cpp#ifdef PKMDS_CMAKE_USED\n#include \n#else\n\/\/#include \"..\\\\..\\\\include\\\\pkmds\\\\pkmds_sql.h\"\n#include \"..\\\\..\\\\include\\\\pkmds\\\\pkmds_gba.h\"\n#endif\nusing namespace std;\nint main(int argc, char* argv[])\n{\n\tif(argc > 1)\n\t{\n\tstring savefile = argv[1];\n\tgbasavefilepacked* savin = new gbasavefilepacked();\n\tgbasavefile* sav = new gbasavefile();\n\tpokemon_gen3* gbapkm = new pokemon_gen3();\n\tpokemon_obj * pkm = new pokemon_obj();\n\tread(savefile.c_str(),savin);\n\tbuildgbasave(savin,sav);\n\topendb(\"C:\\\\Users\\\\Michael Bond\\\\Dropbox\\\\PKMDS Databases\\\\veekun-pokedex.sqlite\");\n\tfor(int box = 0; box < 14; box++)\n\t{\n\t\tfor(int slot = 0; slot < 30; slot++)\n\t\t{\n\t\t\tgbapkm = &(sav->pcstorage.pcstorage[box][slot]);\n\t\t\tdecryptgbapkm(gbapkm);\n\t\t\tshufflegbapkm(gbapkm,true);\n\t\t\tif(gbapkm->data.species != GBASpecies::NOTHING)\n\t\t\t{\n\t\t\t\tif((box == 0) & (slot == 0))\n\t\t\t\t{\n\t\t\t\t\tconvertgen3pkmtogen5(gbapkm,pkm);\n\t\t\t\t\tcout << lookuppkmname(pkm) << \"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tclosedb();\n\tcout << \"\\nEND\\n\";\n\t}\n\treturn 0;\n}\n<|endoftext|>"} {"text":"document that these are references to mozilla bugs<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: xlfd_smpl.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: kz $ $Date: 2004-05-18 13:49:24 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include \n#include \n#include \n\n#ifndef XLFD_ATTRIBUTE_HXX\n#include \"xlfd_attr.hxx\"\n#endif\n#ifndef XLFD_SIMPLE_HXX\n#include \"xlfd_smpl.hxx\"\n#endif\n\n\/\/ --------------------------------------------------------------------------\n\/\/\n\/\/\n\/\/ broken down structure equivalent to a Xlfd string\n\/\/\n\/\/\n\/\/ --------------------------------------------------------------------------\n\nXlfd::Xlfd()\n{\n}\n\n\/\/ XlfdCompare abi has to be qsort(3) compatible, the sorting result must\n\/\/ guarantee that fonts with SameFontoutline() are successive\n\/\/ XlfdCompare relies on vFrom->mpFactory eq vTo->mpFactory. Since comparing\n\/\/ Xlfd's is done by comparing attributes there is no way around this.\nextern \"C\" int\nXlfdCompare( const void *vFrom, const void *vTo )\n{\n const Xlfd *pFrom = (Xlfd*)vFrom;\n const Xlfd *pTo = (Xlfd*)vTo;\n\n \/\/ Compare outline description\n if ( pFrom->mnFoundry != pTo->mnFoundry )\n return (int)pFrom->mnFoundry - (int)pTo->mnFoundry;\n if ( pFrom->mnFamily != pTo->mnFamily )\n return (int)pFrom->mnFamily - (int)pTo->mnFamily;\n if ( pFrom->mnWeight != pTo->mnWeight )\n return (int)pFrom->mnWeight - (int)pTo->mnWeight;\n if ( pFrom->mnSlant != pTo->mnSlant )\n return (int)pFrom->mnSlant - (int)pTo->mnSlant;\n if ( pFrom->mnSetwidth != pTo->mnSetwidth )\n return (int)pFrom->mnSetwidth - (int)pTo->mnSetwidth;\n\n \/\/ Addstyle name is futile tricky. it may contain encoding information\n \/\/ (like \"ansi_1251\") which Compares equal, or it may contain style\n \/\/ information (like \"serif\") which Compares unequal, anyway if the font\n \/\/ is \"interface user\" or \"interface system\" then compare equal anyway to\n \/\/ build fontsets as large as possible\n if ( pFrom->mnAddstyle == pTo->mnAddstyle )\n return 0;\n\n AttributeProvider *pFactory = pFrom->mpFactory;\n Attribute *pFamily = pFactory->RetrieveFamily( pFrom->mnFamily );\n if ( pFamily->HasFeature(XLFD_FEATURE_APPLICATION_FONT) )\n return 0;\n\n Attribute *pFromAddStyle = pFactory->RetrieveAddstyle( pFrom->mnAddstyle );\n Attribute *pToAddStyle = pFactory->RetrieveAddstyle( pTo->mnAddstyle );\n\n \/\/ if both addstyles denote encodings or if one denotes an\n \/\/ encoding and the other denotes a style which really\n \/\/ duplicates weight and slant information\n\n int nFromCompare = (pFromAddStyle->GetValue() != RTL_TEXTENCODING_DONTKNOW)\n || (pFromAddStyle->HasFeature(XLFD_FEATURE_REDUNDANTSTYLE)) ?\n -1 : pFrom->mnAddstyle;\n int nToCompare = (pToAddStyle->GetValue() != RTL_TEXTENCODING_DONTKNOW)\n || (pToAddStyle->HasFeature(XLFD_FEATURE_REDUNDANTSTYLE)) ?\n -1 : pTo->mnAddstyle;\n\n return nFromCompare - nToCompare;\n}\n\n\/\/ check whether two fonts are identical as appearance is concerned\n\/\/ this does not Compare the actual scaling of two fonts\nBool\nXlfd::SameFontoutline( const Xlfd* pComparedTo ) const\n{\n void* pThis = (void*)this;\n return XlfdCompare( (void*)pThis, (void*)pComparedTo ) == 0 ;\n}\n\nunsigned short\nXlfd::GetEncoding() const\n{\n Attribute *pAddstyle = mpFactory->RetrieveAddstyle( mnAddstyle );\n if ( pAddstyle->GetValue() != RTL_TEXTENCODING_DONTKNOW )\n return pAddstyle->GetValue();\n\n Attribute *pEncoding = mpFactory->RetrieveCharset( mnCharset );\n return pEncoding->GetValue();\n}\n\nXlfdFonttype\nXlfd::Fonttype() const\n{\n if ( (mnAverageWidth == 0) && (mnPixelSize == 0) && (mnPointSize == 0) )\n {\n return (mnResolutionX == 0)\n && (mnResolutionY == 0) ? eTypeScalable : eTypeScalableBitmap;\n }\n\n return eTypeBitmap;\n}\n\nvoid\nAdvance( const char** pFrom, const char** pTo )\n{\n const char *pTmp = *pTo;\n\n for( ; (*pTmp != '\\0') && (*pTmp++ != '-'); )\n {}\n *pFrom = *pTo;\n *pTo = pTmp;\n}\n\nBool\nXlfd::IsConformant (const char* pXlfd) const\n{\n \/\/ X FontNameRegistry prefix \"-\"\n if (*pXlfd++ != '-')\n return False;\n\n \/\/ All Xlfd FontName fields are defined\n int nNumFields = 1;\n while (*pXlfd != '\\0')\n {\n if (*pXlfd++ == '-')\n nNumFields++;\n }\n \/\/ enough entries ?\n if (nNumFields != 14)\n return False;\n \/\/ and the last one is not empty as well ?\n if (*(pXlfd - 1) == '-')\n return False;\n\n return True;\n}\n\n\/\/ this is the real workhorse function. Since this is called for every font\n\/\/ in the fontpath it has to be as fast a possible\nBool\nXlfd::FromString( const char* pXlfdstring, AttributeProvider *pFactory )\n{\n if (!IsConformant(pXlfdstring))\n return False;\n\n const char* pFrom = pXlfdstring + 1;\n const char* pTo = pFrom;\n mpFactory = pFactory;\n\n Advance( &pFrom, &pTo ); \/\/-foundry-*\n mnFoundry = mpFactory->InsertFoundry( pFrom, pTo - pFrom - 1 );\n\n Advance( &pFrom, &pTo ); \/\/ -*-family-*\n mnFamily = mpFactory->InsertFamily( pFrom, pTo - pFrom - 1 );\n\n Advance( &pFrom, &pTo ); \/\/ -*-*-weight-*\n mnWeight = mpFactory->InsertWeight( pFrom, pTo - pFrom - 1 );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-slant-*\n mnSlant = mpFactory->InsertSlant( pFrom, pTo - pFrom - 1 );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-setwidth-*\n mnSetwidth = mpFactory->InsertSetwidth( pFrom, pTo - pFrom - 1 );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-Addstyle-*\n mnAddstyle = mpFactory->InsertAddstyle( pFrom, pTo - pFrom - 1 );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-*-height-*\n mnPixelSize = atoi( pFrom );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-*-*-pt height-*\n mnPointSize = atoi( pFrom );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-*-*-*-x resolution-*\n mnResolutionX = atoi( pFrom );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-*-*-*-*-y resolution-*\n mnResolutionY = atoi( pFrom );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-*-*-*-*-*-spacing-*\n mcSpacing = pFrom == pTo ? '\\0' : *pFrom;\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-*-*-*-*-*-*-average-*\n mnAverageWidth = atoi( pFrom );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-*-*-*-*-*-*-*-registry-encoding\n const char* pTmp = pFrom;\n Advance( &pTmp, &pTo );\n mnCharset = mpFactory->InsertCharset( pFrom, pTo - pFrom );\n\n \/\/ sanity check whether we have really found a valid XLFD, if not\n \/\/ throw away the whole font, since we have no idea what parts of\n \/\/ the XLFD contains the error.\n if ( !(pTo > pFrom) )\n return False;\n\n \/\/ a non-empty family name is essential, since otherwise the font\n \/\/ would match the \"default font\" #52299#\n Attribute* pFamily = mpFactory->RetrieveFamily( mnFamily );\n const char* pFamilyName = pFamily->GetName();\n if ( pFamilyName[0] == '\\0' )\n return False;\n\n \/\/ well done\n return True;\n}\n\n#if OSL_DEBUG_LEVEL > 1\n\/\/ pure debug for now: this is only to inspect\/pretty print a Xlfd struct\nconst char*\nXlfd::ToString( ByteString &rString ) const\n{\n AppendAttribute( mpFactory->RetrieveFoundry(mnFoundry), rString );\n AppendAttribute( mpFactory->RetrieveFamily(mnFamily), rString );\n AppendAttribute( mpFactory->RetrieveWeight(mnWeight), rString );\n AppendAttribute( mpFactory->RetrieveSlant(mnSlant), rString );\n AppendAttribute( mpFactory->RetrieveSetwidth(mnSetwidth), rString );\n AppendAttribute( mpFactory->RetrieveAddstyle(mnAddstyle), rString );\n\n rString.Append(\"-\"); rString.Append( ByteString::CreateFromInt32( mnPixelSize ) );\n rString.Append(\"-\"); rString.Append( ByteString::CreateFromInt32( mnPointSize ) );\n rString.Append(\"-\"); rString.Append( ByteString::CreateFromInt32( mnResolutionX ) );\n rString.Append(\"-\"); rString.Append( ByteString::CreateFromInt32( mnResolutionY ) );\n rString.Append(\"-\"); rString.Append( (char)mcSpacing );\n rString.Append(\"-\"); rString.Append( ByteString::CreateFromInt32( mnAverageWidth ) );\n\n AppendAttribute( mpFactory->RetrieveCharset(mnCharset), rString );\n\n return rString.GetBuffer() ;\n}\n\nvoid\nXlfd::Dump() const\n{\n ByteString aString;\n fprintf(stderr, \"Xlfd: %s\\n\", ToString(aString) );\n}\n#endif\n\nINTEGRATION: CWS ooo19126 (1.7.446); FILE MERGED 2005\/09\/05 14:45:47 rt 1.7.446.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xlfd_smpl.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 13:10:11 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#include \n#include \n#include \n\n#ifndef XLFD_ATTRIBUTE_HXX\n#include \"xlfd_attr.hxx\"\n#endif\n#ifndef XLFD_SIMPLE_HXX\n#include \"xlfd_smpl.hxx\"\n#endif\n\n\/\/ --------------------------------------------------------------------------\n\/\/\n\/\/\n\/\/ broken down structure equivalent to a Xlfd string\n\/\/\n\/\/\n\/\/ --------------------------------------------------------------------------\n\nXlfd::Xlfd()\n{\n}\n\n\/\/ XlfdCompare abi has to be qsort(3) compatible, the sorting result must\n\/\/ guarantee that fonts with SameFontoutline() are successive\n\/\/ XlfdCompare relies on vFrom->mpFactory eq vTo->mpFactory. Since comparing\n\/\/ Xlfd's is done by comparing attributes there is no way around this.\nextern \"C\" int\nXlfdCompare( const void *vFrom, const void *vTo )\n{\n const Xlfd *pFrom = (Xlfd*)vFrom;\n const Xlfd *pTo = (Xlfd*)vTo;\n\n \/\/ Compare outline description\n if ( pFrom->mnFoundry != pTo->mnFoundry )\n return (int)pFrom->mnFoundry - (int)pTo->mnFoundry;\n if ( pFrom->mnFamily != pTo->mnFamily )\n return (int)pFrom->mnFamily - (int)pTo->mnFamily;\n if ( pFrom->mnWeight != pTo->mnWeight )\n return (int)pFrom->mnWeight - (int)pTo->mnWeight;\n if ( pFrom->mnSlant != pTo->mnSlant )\n return (int)pFrom->mnSlant - (int)pTo->mnSlant;\n if ( pFrom->mnSetwidth != pTo->mnSetwidth )\n return (int)pFrom->mnSetwidth - (int)pTo->mnSetwidth;\n\n \/\/ Addstyle name is futile tricky. it may contain encoding information\n \/\/ (like \"ansi_1251\") which Compares equal, or it may contain style\n \/\/ information (like \"serif\") which Compares unequal, anyway if the font\n \/\/ is \"interface user\" or \"interface system\" then compare equal anyway to\n \/\/ build fontsets as large as possible\n if ( pFrom->mnAddstyle == pTo->mnAddstyle )\n return 0;\n\n AttributeProvider *pFactory = pFrom->mpFactory;\n Attribute *pFamily = pFactory->RetrieveFamily( pFrom->mnFamily );\n if ( pFamily->HasFeature(XLFD_FEATURE_APPLICATION_FONT) )\n return 0;\n\n Attribute *pFromAddStyle = pFactory->RetrieveAddstyle( pFrom->mnAddstyle );\n Attribute *pToAddStyle = pFactory->RetrieveAddstyle( pTo->mnAddstyle );\n\n \/\/ if both addstyles denote encodings or if one denotes an\n \/\/ encoding and the other denotes a style which really\n \/\/ duplicates weight and slant information\n\n int nFromCompare = (pFromAddStyle->GetValue() != RTL_TEXTENCODING_DONTKNOW)\n || (pFromAddStyle->HasFeature(XLFD_FEATURE_REDUNDANTSTYLE)) ?\n -1 : pFrom->mnAddstyle;\n int nToCompare = (pToAddStyle->GetValue() != RTL_TEXTENCODING_DONTKNOW)\n || (pToAddStyle->HasFeature(XLFD_FEATURE_REDUNDANTSTYLE)) ?\n -1 : pTo->mnAddstyle;\n\n return nFromCompare - nToCompare;\n}\n\n\/\/ check whether two fonts are identical as appearance is concerned\n\/\/ this does not Compare the actual scaling of two fonts\nBool\nXlfd::SameFontoutline( const Xlfd* pComparedTo ) const\n{\n void* pThis = (void*)this;\n return XlfdCompare( (void*)pThis, (void*)pComparedTo ) == 0 ;\n}\n\nunsigned short\nXlfd::GetEncoding() const\n{\n Attribute *pAddstyle = mpFactory->RetrieveAddstyle( mnAddstyle );\n if ( pAddstyle->GetValue() != RTL_TEXTENCODING_DONTKNOW )\n return pAddstyle->GetValue();\n\n Attribute *pEncoding = mpFactory->RetrieveCharset( mnCharset );\n return pEncoding->GetValue();\n}\n\nXlfdFonttype\nXlfd::Fonttype() const\n{\n if ( (mnAverageWidth == 0) && (mnPixelSize == 0) && (mnPointSize == 0) )\n {\n return (mnResolutionX == 0)\n && (mnResolutionY == 0) ? eTypeScalable : eTypeScalableBitmap;\n }\n\n return eTypeBitmap;\n}\n\nvoid\nAdvance( const char** pFrom, const char** pTo )\n{\n const char *pTmp = *pTo;\n\n for( ; (*pTmp != '\\0') && (*pTmp++ != '-'); )\n {}\n *pFrom = *pTo;\n *pTo = pTmp;\n}\n\nBool\nXlfd::IsConformant (const char* pXlfd) const\n{\n \/\/ X FontNameRegistry prefix \"-\"\n if (*pXlfd++ != '-')\n return False;\n\n \/\/ All Xlfd FontName fields are defined\n int nNumFields = 1;\n while (*pXlfd != '\\0')\n {\n if (*pXlfd++ == '-')\n nNumFields++;\n }\n \/\/ enough entries ?\n if (nNumFields != 14)\n return False;\n \/\/ and the last one is not empty as well ?\n if (*(pXlfd - 1) == '-')\n return False;\n\n return True;\n}\n\n\/\/ this is the real workhorse function. Since this is called for every font\n\/\/ in the fontpath it has to be as fast a possible\nBool\nXlfd::FromString( const char* pXlfdstring, AttributeProvider *pFactory )\n{\n if (!IsConformant(pXlfdstring))\n return False;\n\n const char* pFrom = pXlfdstring + 1;\n const char* pTo = pFrom;\n mpFactory = pFactory;\n\n Advance( &pFrom, &pTo ); \/\/-foundry-*\n mnFoundry = mpFactory->InsertFoundry( pFrom, pTo - pFrom - 1 );\n\n Advance( &pFrom, &pTo ); \/\/ -*-family-*\n mnFamily = mpFactory->InsertFamily( pFrom, pTo - pFrom - 1 );\n\n Advance( &pFrom, &pTo ); \/\/ -*-*-weight-*\n mnWeight = mpFactory->InsertWeight( pFrom, pTo - pFrom - 1 );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-slant-*\n mnSlant = mpFactory->InsertSlant( pFrom, pTo - pFrom - 1 );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-setwidth-*\n mnSetwidth = mpFactory->InsertSetwidth( pFrom, pTo - pFrom - 1 );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-Addstyle-*\n mnAddstyle = mpFactory->InsertAddstyle( pFrom, pTo - pFrom - 1 );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-*-height-*\n mnPixelSize = atoi( pFrom );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-*-*-pt height-*\n mnPointSize = atoi( pFrom );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-*-*-*-x resolution-*\n mnResolutionX = atoi( pFrom );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-*-*-*-*-y resolution-*\n mnResolutionY = atoi( pFrom );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-*-*-*-*-*-spacing-*\n mcSpacing = pFrom == pTo ? '\\0' : *pFrom;\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-*-*-*-*-*-*-average-*\n mnAverageWidth = atoi( pFrom );\n\n Advance( &pFrom, &pTo ); \/\/-*-*-*-*-*-*-*-*-*-*-*-*-registry-encoding\n const char* pTmp = pFrom;\n Advance( &pTmp, &pTo );\n mnCharset = mpFactory->InsertCharset( pFrom, pTo - pFrom );\n\n \/\/ sanity check whether we have really found a valid XLFD, if not\n \/\/ throw away the whole font, since we have no idea what parts of\n \/\/ the XLFD contains the error.\n if ( !(pTo > pFrom) )\n return False;\n\n \/\/ a non-empty family name is essential, since otherwise the font\n \/\/ would match the \"default font\" #52299#\n Attribute* pFamily = mpFactory->RetrieveFamily( mnFamily );\n const char* pFamilyName = pFamily->GetName();\n if ( pFamilyName[0] == '\\0' )\n return False;\n\n \/\/ well done\n return True;\n}\n\n#if OSL_DEBUG_LEVEL > 1\n\/\/ pure debug for now: this is only to inspect\/pretty print a Xlfd struct\nconst char*\nXlfd::ToString( ByteString &rString ) const\n{\n AppendAttribute( mpFactory->RetrieveFoundry(mnFoundry), rString );\n AppendAttribute( mpFactory->RetrieveFamily(mnFamily), rString );\n AppendAttribute( mpFactory->RetrieveWeight(mnWeight), rString );\n AppendAttribute( mpFactory->RetrieveSlant(mnSlant), rString );\n AppendAttribute( mpFactory->RetrieveSetwidth(mnSetwidth), rString );\n AppendAttribute( mpFactory->RetrieveAddstyle(mnAddstyle), rString );\n\n rString.Append(\"-\"); rString.Append( ByteString::CreateFromInt32( mnPixelSize ) );\n rString.Append(\"-\"); rString.Append( ByteString::CreateFromInt32( mnPointSize ) );\n rString.Append(\"-\"); rString.Append( ByteString::CreateFromInt32( mnResolutionX ) );\n rString.Append(\"-\"); rString.Append( ByteString::CreateFromInt32( mnResolutionY ) );\n rString.Append(\"-\"); rString.Append( (char)mcSpacing );\n rString.Append(\"-\"); rString.Append( ByteString::CreateFromInt32( mnAverageWidth ) );\n\n AppendAttribute( mpFactory->RetrieveCharset(mnCharset), rString );\n\n return rString.GetBuffer() ;\n}\n\nvoid\nXlfd::Dump() const\n{\n ByteString aString;\n fprintf(stderr, \"Xlfd: %s\\n\", ToString(aString) );\n}\n#endif\n\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Markus Pfeiffer\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"SimpleModifier.h\"\n\n#include \"Aql\/AqlValue.h\"\n#include \"Aql\/Collection.h\"\n#include \"Aql\/ExecutionEngine.h\"\n#include \"Aql\/ModificationExecutor.h\"\n#include \"Aql\/ModificationExecutorHelpers.h\"\n#include \"Aql\/OutputAqlItemRow.h\"\n#include \"Aql\/SharedQueryState.h\"\n#include \"Basics\/Common.h\"\n#include \"Basics\/StaticStrings.h\"\n#include \"Basics\/StringUtils.h\"\n#include \"Basics\/VelocyPackHelper.h\"\n#include \"Basics\/application-exit.h\"\n#include \"Cluster\/ServerState.h\"\n#include \"VocBase\/LogicalCollection.h\"\n\n#include \n#include \n\nusing namespace arangodb;\nusing namespace arangodb::aql;\nusing namespace arangodb::aql::ModificationExecutorHelpers;\nusing namespace arangodb::basics;\n\ntemplate \nSimpleModifier::OutputIterator::OutputIterator(\n SimpleModifier const& modifier)\n : _modifier(modifier),\n _operationsIterator(modifier._operations.begin()),\n _resultsIterator(modifier.getResultsIterator()) {}\n\ntemplate \ntypename SimpleModifier::OutputIterator&\nSimpleModifier::OutputIterator::next() {\n \/\/ Only move results on if there has been a document\n \/\/ submitted to the transaction\n if (_operationsIterator->first == ModifierOperationType::ReturnIfAvailable) {\n ++_resultsIterator;\n }\n ++_operationsIterator;\n return *this;\n}\n\ntemplate \ntypename SimpleModifier::OutputIterator&\nSimpleModifier::OutputIterator::operator++() {\n return next();\n}\n\ntemplate \nbool SimpleModifier::OutputIterator::operator!=(\n SimpleModifier::OutputIterator const& other) const\n noexcept {\n return _operationsIterator != other._operationsIterator;\n}\n\ntemplate \nModifierOutput SimpleModifier::OutputIterator::operator*() const {\n switch (_operationsIterator->first) {\n case ModifierOperationType::ReturnIfAvailable: {\n \/\/ This means the results slice is relevant\n if (_modifier.resultAvailable()) {\n VPackSlice elm = *_resultsIterator;\n bool error = VelocyPackHelper::getBooleanValue(elm, StaticStrings::Error, false);\n\n if (error) {\n return ModifierOutput{_operationsIterator->second, ModifierOutput::Type::SkipRow};\n } else {\n return ModifierOutput{\n _operationsIterator->second, ModifierOutput::Type::ReturnIfRequired,\n ModificationExecutorHelpers::getDocumentOrNull(elm, StaticStrings::Old),\n ModificationExecutorHelpers::getDocumentOrNull(elm, StaticStrings::New)};\n }\n } else {\n return ModifierOutput{_operationsIterator->second, ModifierOutput::Type::CopyRow};\n }\n case ModifierOperationType::CopyRow:\n return ModifierOutput{_operationsIterator->second, ModifierOutput::Type::CopyRow};\n case ModifierOperationType::SkipRow:\n return ModifierOutput{_operationsIterator->second, ModifierOutput::Type::SkipRow};\n }\n }\n\n \/\/ Shut up compiler\n TRI_ASSERT(false);\n return ModifierOutput{_operationsIterator->second, ModifierOutput::Type::SkipRow};\n}\n\ntemplate \ntypename SimpleModifier::OutputIterator\nSimpleModifier::OutputIterator::begin() const {\n return SimpleModifier::OutputIterator(this->_modifier);\n}\n\ntemplate \ntypename SimpleModifier::OutputIterator\nSimpleModifier::OutputIterator::end() const {\n auto it = SimpleModifier::OutputIterator(this->_modifier);\n it._operationsIterator = _modifier._operations.end();\n\n return it;\n}\n\ntemplate \nvoid SimpleModifier::checkException() const {\n throwOperationResultException(_infos, std::get(_results));\n}\n\ntemplate \nvoid SimpleModifier::resetResult() noexcept {\n std::lock_guard guard(_resultMutex);\n _results = NoResult{};\n}\n\ntemplate \nvoid SimpleModifier::reset() {\n#ifdef ARANGODB_ENABLE_MAINTAINER_MODE\n {\n std::unique_lock guard(_resultMutex, std::try_to_lock);\n TRI_ASSERT(guard.owns_lock());\n TRI_ASSERT(!std::holds_alternative(_results));\n }\n#endif\n _accumulator.reset();\n _operations.clear();\n resetResult();\n}\n\ntemplate \nvoid SimpleModifier::accumulate(InputAqlItemRow& row) {\n auto result = _completion.accumulate(_accumulator, row);\n _operations.push_back({result, row});\n}\n\ntemplate \nExecutionState SimpleModifier::transact(transaction::Methods& trx) {\n std::unique_lock guard(_resultMutex);\n if (std::holds_alternative(_results)) {\n return ExecutionState::WAITING;\n } else if (std::holds_alternative(_results)) {\n return ExecutionState::DONE;\n } else if (auto* ex = std::get_if(&_results); ex != nullptr) {\n std::rethrow_exception(*ex);\n } else {\n TRI_ASSERT(std::holds_alternative(_results));\n }\n\n _results = NoResult{};\n\n auto result = _completion.transact(trx, _accumulator.closeAndGetContents());\n\n if (result.isReady()) {\n _results = std::move(result.get());\n return ExecutionState::DONE;\n } \n\n _results = Waiting{};\n\n TRI_ASSERT(!ServerState::instance()->isSingleServer());\n TRI_ASSERT(_infos.engine() != nullptr);\n TRI_ASSERT(_infos.engine()->sharedState() != nullptr);\n\n \/\/ The guard has to be unlocked before \"thenValue\" is called, otherwise locking\n \/\/ the mutex there will cause a deadlock if the result is already available.\n guard.unlock();\n\n auto self = this->shared_from_this();\n std::move(result).thenFinal([self, sqs = _infos.engine()->sharedState()](futures::Try&& opRes) {\n sqs->executeAndWakeup([&]() noexcept {\n std::unique_lock guard(self->_resultMutex);\n try {\n TRI_ASSERT(std::holds_alternative(self->_results));\n if (std::holds_alternative(self->_results)) {\n \/\/ get() will throw if opRes holds an exception, which is intended.\n self->_results = std::move(opRes.get());\n } else {\n \/\/ This can never happen.\n using namespace std::string_literals;\n auto state =\n std::visit(overload{[&](NoResult) { return \"NoResults\"s; },\n [&](Waiting) { return \"Waiting\"s; },\n [&](OperationResult const&) {\n return \"Result\"s;\n },\n [&](std::exception_ptr const& ep) {\n auto what = std::string{};\n try {\n std::rethrow_exception(ep);\n } catch (std::exception const& ex) {\n what = ex.what();\n } catch (...) {\n \/\/ Exception unknown, give up immediately.\n LOG_TOPIC(\"4646a\", FATAL, Logger::AQL) << \"Caught an exception while handling another one, giving up.\";\n FATAL_ERROR_ABORT();\n }\n return StringUtils::concatT(\"Exception: \", what);\n }},\n self->_results);\n auto message = StringUtils::concatT(\n \"Unexpected state when reporting modification result, expected \"\n \"'Waiting' but got: \",\n state);\n LOG_TOPIC(\"1f48d\", ERR, Logger::AQL) << message;\n if (std::holds_alternative(self->_results)) {\n \/\/ Avoid overwriting an exception with another exception.\n LOG_TOPIC(\"2d310\", FATAL, Logger::AQL)\n << \"Caught an exception while handling another one, giving up.\";\n FATAL_ERROR_ABORT();\n }\n THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL_AQL, std::move(message));\n }\n } catch(...) {\n auto exptr = std::current_exception();\n self->_results = exptr;\n }\n return true;\n });\n });\n\n return ExecutionState::WAITING;\n}\n\ntemplate \nsize_t SimpleModifier::nrOfOperations() const {\n return _operations.size();\n}\n\ntemplate \nsize_t SimpleModifier::nrOfDocuments() const {\n return _accumulator.nrOfDocuments();\n}\n\ntemplate \nsize_t SimpleModifier::nrOfResults() const {\n if (auto* res = std::get_if(&_results);\n res != nullptr && res->hasSlice() && res->slice().isArray()) {\n return res->slice().length();\n } else {\n return 0;\n }\n}\n\ntemplate \nsize_t SimpleModifier::nrOfErrors() const {\n size_t nrOfErrors{0};\n\n for (auto const& pair : std::get(_results).countErrorCodes) {\n nrOfErrors += pair.second;\n }\n return nrOfErrors;\n}\n\ntemplate \nsize_t SimpleModifier::nrOfWritesExecuted() const {\n return nrOfDocuments() - nrOfErrors();\n}\n\ntemplate \nsize_t SimpleModifier::nrOfWritesIgnored() const {\n return nrOfErrors();\n}\n\ntemplate \nModificationExecutorInfos& SimpleModifier::getInfos() const\n noexcept {\n return _infos;\n}\n\ntemplate \nsize_t SimpleModifier::getBatchSize() const noexcept {\n return _batchSize;\n}\n\ntemplate \nbool SimpleModifier::resultAvailable() const {\n return (nrOfDocuments() > 0 && !_infos._options.silent);\n}\n\ntemplate \nVPackArrayIterator SimpleModifier::getResultsIterator() const {\n if (resultAvailable()) {\n auto const& results = std::get(_results);\n TRI_ASSERT(results.hasSlice() && results.slice().isArray());\n return VPackArrayIterator{results.slice()};\n }\n return VPackArrayIterator(VPackArrayIterator::Empty{});\n}\n\ntemplate \nbool SimpleModifier::hasResultOrException() const noexcept {\n return std::visit(overload{\n [](NoResult) { return false; },\n [](Waiting) { return false; },\n [](OperationResult const&) { return true; },\n [](std::exception_ptr const&) { return true; },\n },\n _results);\n}\n\ntemplate \nbool SimpleModifier::hasNeitherResultNorOperationPending() const noexcept {\n return std::visit(overload{\n [](NoResult) { return true; },\n [](Waiting) { return false; },\n [](OperationResult const&) { return false; },\n [](std::exception_ptr const&) { return false; },\n },\n _results);\n}\n\ntemplate class ::arangodb::aql::SimpleModifier;\ntemplate class ::arangodb::aql::SimpleModifier;\ntemplate class ::arangodb::aql::SimpleModifier;\nmake AQL modification operations blocking again (#14795)\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Markus Pfeiffer\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"SimpleModifier.h\"\n\n#include \"Aql\/AqlValue.h\"\n#include \"Aql\/Collection.h\"\n#include \"Aql\/ExecutionEngine.h\"\n#include \"Aql\/ModificationExecutor.h\"\n#include \"Aql\/ModificationExecutorHelpers.h\"\n#include \"Aql\/OutputAqlItemRow.h\"\n#include \"Aql\/SharedQueryState.h\"\n#include \"Basics\/Common.h\"\n#include \"Basics\/StaticStrings.h\"\n#include \"Basics\/StringUtils.h\"\n#include \"Basics\/VelocyPackHelper.h\"\n#include \"Basics\/application-exit.h\"\n#include \"Cluster\/ServerState.h\"\n#include \"VocBase\/LogicalCollection.h\"\n\n#include \n#include \n\nusing namespace arangodb;\nusing namespace arangodb::aql;\nusing namespace arangodb::aql::ModificationExecutorHelpers;\nusing namespace arangodb::basics;\n\ntemplate \nSimpleModifier::OutputIterator::OutputIterator(\n SimpleModifier const& modifier)\n : _modifier(modifier),\n _operationsIterator(modifier._operations.begin()),\n _resultsIterator(modifier.getResultsIterator()) {}\n\ntemplate \ntypename SimpleModifier::OutputIterator&\nSimpleModifier::OutputIterator::next() {\n \/\/ Only move results on if there has been a document\n \/\/ submitted to the transaction\n if (_operationsIterator->first == ModifierOperationType::ReturnIfAvailable) {\n ++_resultsIterator;\n }\n ++_operationsIterator;\n return *this;\n}\n\ntemplate \ntypename SimpleModifier::OutputIterator&\nSimpleModifier::OutputIterator::operator++() {\n return next();\n}\n\ntemplate \nbool SimpleModifier::OutputIterator::operator!=(\n SimpleModifier::OutputIterator const& other) const\n noexcept {\n return _operationsIterator != other._operationsIterator;\n}\n\ntemplate \nModifierOutput SimpleModifier::OutputIterator::operator*() const {\n switch (_operationsIterator->first) {\n case ModifierOperationType::ReturnIfAvailable: {\n \/\/ This means the results slice is relevant\n if (_modifier.resultAvailable()) {\n VPackSlice elm = *_resultsIterator;\n bool error = VelocyPackHelper::getBooleanValue(elm, StaticStrings::Error, false);\n\n if (error) {\n return ModifierOutput{_operationsIterator->second, ModifierOutput::Type::SkipRow};\n } else {\n return ModifierOutput{\n _operationsIterator->second, ModifierOutput::Type::ReturnIfRequired,\n ModificationExecutorHelpers::getDocumentOrNull(elm, StaticStrings::Old),\n ModificationExecutorHelpers::getDocumentOrNull(elm, StaticStrings::New)};\n }\n } else {\n return ModifierOutput{_operationsIterator->second, ModifierOutput::Type::CopyRow};\n }\n case ModifierOperationType::CopyRow:\n return ModifierOutput{_operationsIterator->second, ModifierOutput::Type::CopyRow};\n case ModifierOperationType::SkipRow:\n return ModifierOutput{_operationsIterator->second, ModifierOutput::Type::SkipRow};\n }\n }\n\n \/\/ Shut up compiler\n TRI_ASSERT(false);\n return ModifierOutput{_operationsIterator->second, ModifierOutput::Type::SkipRow};\n}\n\ntemplate \ntypename SimpleModifier::OutputIterator\nSimpleModifier::OutputIterator::begin() const {\n return SimpleModifier::OutputIterator(this->_modifier);\n}\n\ntemplate \ntypename SimpleModifier::OutputIterator\nSimpleModifier::OutputIterator::end() const {\n auto it = SimpleModifier::OutputIterator(this->_modifier);\n it._operationsIterator = _modifier._operations.end();\n\n return it;\n}\n\ntemplate \nvoid SimpleModifier::checkException() const {\n throwOperationResultException(_infos, std::get(_results));\n}\n\ntemplate \nvoid SimpleModifier::resetResult() noexcept {\n std::lock_guard guard(_resultMutex);\n _results = NoResult{};\n}\n\ntemplate \nvoid SimpleModifier::reset() {\n#ifdef ARANGODB_ENABLE_MAINTAINER_MODE\n {\n std::unique_lock guard(_resultMutex, std::try_to_lock);\n TRI_ASSERT(guard.owns_lock());\n TRI_ASSERT(!std::holds_alternative(_results));\n }\n#endif\n _accumulator.reset();\n _operations.clear();\n resetResult();\n}\n\ntemplate \nvoid SimpleModifier::accumulate(InputAqlItemRow& row) {\n auto result = _completion.accumulate(_accumulator, row);\n _operations.push_back({result, row});\n}\n\ntemplate \nExecutionState SimpleModifier::transact(transaction::Methods& trx) {\n std::unique_lock guard(_resultMutex);\n if (std::holds_alternative(_results)) {\n return ExecutionState::WAITING;\n } else if (std::holds_alternative(_results)) {\n return ExecutionState::DONE;\n } else if (auto* ex = std::get_if(&_results); ex != nullptr) {\n std::rethrow_exception(*ex);\n } else {\n TRI_ASSERT(std::holds_alternative(_results));\n }\n\n _results = NoResult{};\n\n auto result = _completion.transact(trx, _accumulator.closeAndGetContents());\n\n \/\/ we are currently waiting here for the `result` future to get\n \/\/ ready before we continue. this makes the AQL modification\n \/\/ operations blocking as in previous versions of ArangoDB.\n \/\/ TODO: fix this and make it truly non-blocking (requires to\n \/\/ fix some lifecycle issues for AQL queries first).\n result.wait();\n\n if (result.isReady()) {\n _results = std::move(result.get());\n return ExecutionState::DONE;\n } \n\n _results = Waiting{};\n\n TRI_ASSERT(!ServerState::instance()->isSingleServer());\n TRI_ASSERT(_infos.engine() != nullptr);\n TRI_ASSERT(_infos.engine()->sharedState() != nullptr);\n\n \/\/ The guard has to be unlocked before \"thenValue\" is called, otherwise locking\n \/\/ the mutex there will cause a deadlock if the result is already available.\n guard.unlock();\n\n auto self = this->shared_from_this();\n std::move(result).thenFinal([self, sqs = _infos.engine()->sharedState()](futures::Try&& opRes) {\n sqs->executeAndWakeup([&]() noexcept {\n std::unique_lock guard(self->_resultMutex);\n try {\n TRI_ASSERT(std::holds_alternative(self->_results));\n if (std::holds_alternative(self->_results)) {\n \/\/ get() will throw if opRes holds an exception, which is intended.\n self->_results = std::move(opRes.get());\n } else {\n \/\/ This can never happen.\n using namespace std::string_literals;\n auto state =\n std::visit(overload{[&](NoResult) { return \"NoResults\"s; },\n [&](Waiting) { return \"Waiting\"s; },\n [&](OperationResult const&) {\n return \"Result\"s;\n },\n [&](std::exception_ptr const& ep) {\n auto what = std::string{};\n try {\n std::rethrow_exception(ep);\n } catch (std::exception const& ex) {\n what = ex.what();\n } catch (...) {\n \/\/ Exception unknown, give up immediately.\n LOG_TOPIC(\"4646a\", FATAL, Logger::AQL) << \"Caught an exception while handling another one, giving up.\";\n FATAL_ERROR_ABORT();\n }\n return StringUtils::concatT(\"Exception: \", what);\n }},\n self->_results);\n auto message = StringUtils::concatT(\n \"Unexpected state when reporting modification result, expected \"\n \"'Waiting' but got: \",\n state);\n LOG_TOPIC(\"1f48d\", ERR, Logger::AQL) << message;\n if (std::holds_alternative(self->_results)) {\n \/\/ Avoid overwriting an exception with another exception.\n LOG_TOPIC(\"2d310\", FATAL, Logger::AQL)\n << \"Caught an exception while handling another one, giving up.\";\n FATAL_ERROR_ABORT();\n }\n THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL_AQL, std::move(message));\n }\n } catch(...) {\n auto exptr = std::current_exception();\n self->_results = exptr;\n }\n return true;\n });\n });\n\n return ExecutionState::WAITING;\n}\n\ntemplate \nsize_t SimpleModifier::nrOfOperations() const {\n return _operations.size();\n}\n\ntemplate \nsize_t SimpleModifier::nrOfDocuments() const {\n return _accumulator.nrOfDocuments();\n}\n\ntemplate \nsize_t SimpleModifier::nrOfResults() const {\n if (auto* res = std::get_if(&_results);\n res != nullptr && res->hasSlice() && res->slice().isArray()) {\n return res->slice().length();\n } else {\n return 0;\n }\n}\n\ntemplate \nsize_t SimpleModifier::nrOfErrors() const {\n size_t nrOfErrors{0};\n\n for (auto const& pair : std::get(_results).countErrorCodes) {\n nrOfErrors += pair.second;\n }\n return nrOfErrors;\n}\n\ntemplate \nsize_t SimpleModifier::nrOfWritesExecuted() const {\n return nrOfDocuments() - nrOfErrors();\n}\n\ntemplate \nsize_t SimpleModifier::nrOfWritesIgnored() const {\n return nrOfErrors();\n}\n\ntemplate \nModificationExecutorInfos& SimpleModifier::getInfos() const\n noexcept {\n return _infos;\n}\n\ntemplate \nsize_t SimpleModifier::getBatchSize() const noexcept {\n return _batchSize;\n}\n\ntemplate \nbool SimpleModifier::resultAvailable() const {\n return (nrOfDocuments() > 0 && !_infos._options.silent);\n}\n\ntemplate \nVPackArrayIterator SimpleModifier::getResultsIterator() const {\n if (resultAvailable()) {\n auto const& results = std::get(_results);\n TRI_ASSERT(results.hasSlice() && results.slice().isArray());\n return VPackArrayIterator{results.slice()};\n }\n return VPackArrayIterator(VPackArrayIterator::Empty{});\n}\n\ntemplate \nbool SimpleModifier::hasResultOrException() const noexcept {\n return std::visit(overload{\n [](NoResult) { return false; },\n [](Waiting) { return false; },\n [](OperationResult const&) { return true; },\n [](std::exception_ptr const&) { return true; },\n },\n _results);\n}\n\ntemplate \nbool SimpleModifier::hasNeitherResultNorOperationPending() const noexcept {\n return std::visit(overload{\n [](NoResult) { return true; },\n [](Waiting) { return false; },\n [](OperationResult const&) { return false; },\n [](std::exception_ptr const&) { return false; },\n },\n _results);\n}\n\ntemplate class ::arangodb::aql::SimpleModifier;\ntemplate class ::arangodb::aql::SimpleModifier;\ntemplate class ::arangodb::aql::SimpleModifier;\n<|endoftext|>"} {"text":"\/\/ @(#)root\/gui:$Name: $:$Id: TRootContextMenu.cxx,v 1.16 2006\/08\/22 18:27:38 rdm Exp $\n\/\/ Author: Fons Rademakers 12\/02\/98\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TRootContextMenu \/\/\n\/\/ \/\/\n\/\/ This class provides an interface to context sensitive popup menus. \/\/\n\/\/ These menus pop up when the user hits the right mouse button, and \/\/\n\/\/ are destroyed when the menu pops downs. \/\/\n\/\/ The picture below shows a canvas with a pop-up menu. \/\/\n\/\/ \/\/\n\/\/Begin_Html End_Html \/\/\n\/\/ \/\/\n\/\/ The picture below shows a canvas with a pop-up menu and a dialog box.\/\/\n\/\/ \/\/\n\/\/Begin_Html End_Html \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TRootContextMenu.h\"\n#include \"TROOT.h\"\n#include \"TGClient.h\"\n#include \"TList.h\"\n#include \"TContextMenu.h\"\n#include \"TMethod.h\"\n#include \"TMethodArg.h\"\n#include \"TClass.h\"\n#include \"TVirtualX.h\"\n#include \"TCanvas.h\"\n#include \"TDataMember.h\"\n#include \"TToggle.h\"\n#include \"TRootDialog.h\"\n#include \"TDataType.h\"\n#include \"TCanvas.h\"\n#include \"TBrowser.h\"\n#include \"TRootCanvas.h\"\n#include \"TRootBrowser.h\"\n#include \"TClassMenuItem.h\"\n#include \"TObjectSpy.h\"\n\nenum EContextMenu {\n kToggleStart = 1000, \/\/ first id of toggle menu items\n kToggleListStart = 2000, \/\/ first id of toggle list menu items\n kUserFunctionStart = 3000 \/\/ first id of user added functions\/methods, etc...\n};\n\n\nClassImp(TRootContextMenu)\n\n\/\/______________________________________________________________________________\nTRootContextMenu::TRootContextMenu(TContextMenu *c, const char *)\n : TGPopupMenu(gClient->GetDefaultRoot()), TContextMenuImp(c)\n{\n \/\/ Create context menu.\n\n fDialog = 0;\n fTrash = new TList;\n\n \/\/ Context menu handles its own messages\n Associate(this);\n}\n\n\/\/______________________________________________________________________________\nTRootContextMenu::~TRootContextMenu()\n{\n \/\/ Delete a context menu.\n\n delete fDialog;\n if (fTrash) fTrash->Delete();\n delete fTrash;\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::DisplayPopup(Int_t x, Int_t y)\n{\n \/\/ Display context popup menu for currently selected object.\n\n if (fClient->IsEditable()) return;\n\n \/\/ delete menu items releated to previous object and reset menu size\n if (fEntryList) fEntryList->Delete();\n if (fTrash) fTrash->Delete();\n fMenuHeight = 6;\n fMenuWidth = 8;\n\n \/\/ delete previous dialog\n if (fDialog) {\n delete fDialog;\n fDialog = 0;\n }\n\n \/\/ add menu items to popup menu\n CreateMenu(fContextMenu->GetSelectedObject());\n\n int xx, yy, topx = 0, topy = 0;\n UInt_t w, h;\n\n if (fContextMenu->GetSelectedCanvas())\n gVirtualX->GetGeometry(fContextMenu->GetSelectedCanvas()->GetCanvasID(),\n topx, topy, w, h);\n\n xx = topx + x + 1;\n yy = topy + y + 1;\n\n PlaceMenu(xx, yy, kFALSE, kTRUE);\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::CreateMenu(TObject *object)\n{\n \/\/ Create the context menu depending on the selected object.\n\n if (fClient->IsEditable()) return;\n\n int entry = 0, toggle = kToggleStart, togglelist = kToggleListStart;\n int userfunction = kUserFunctionStart;\n\n \/\/ Add a title\n AddLabel(fContextMenu->CreatePopupTitle(object));\n AddSeparator();\n\n \/\/ Get list of menu items from the selected object's class\n TList *menuItemList = object->IsA()->GetMenuList();\n\n TClassMenuItem *menuItem;\n TIter nextItem(menuItemList);\n\n while ((menuItem = (TClassMenuItem*) nextItem())) {\n switch (menuItem->GetType()) {\n case TClassMenuItem::kPopupSeparator:\n AddSeparator();\n break;\n case TClassMenuItem::kPopupStandardList:\n {\n \/\/ Standard list of class methods. Rebuild from scratch.\n \/\/ Get linked list of objects menu items (i.e. member functions\n \/\/ with the token *MENU in their comment fields.\n TList *methodList = new TList;\n object->IsA()->GetMenuItems(methodList);\n\n TMethod *method;\n TClass *classPtr = 0;\n TIter next(methodList);\n\n while ((method = (TMethod*) next())) {\n if (classPtr != method->GetClass()) {\n AddSeparator();\n classPtr = method->GetClass();\n }\n\n TDataMember *m;\n EMenuItemKind menuKind = method->IsMenuItem();\n switch (menuKind) {\n case kMenuDialog:\n AddEntry(method->GetName(), entry++, method);\n break;\n case kMenuSubMenu:\n if ((m = method->FindDataMember())) {\n if (m->GetterMethod()) {\n TGPopupMenu *r = new TGPopupMenu(gClient->GetDefaultRoot());\n AddPopup(method->GetName(), r);\n fTrash->Add(r);\n TIter nxt(m->GetOptions());\n TOptionListItem *it;\n while ((it = (TOptionListItem*) nxt())) {\n char *name = it->fOptName;\n Long_t val = it->fValue;\n\n TToggle *t = new TToggle;\n t->SetToggledObject(object, method);\n t->SetOnValue(val);\n fTrash->Add(t);\n\n r->AddSeparator();\n r->AddEntry(name, togglelist++, t);\n if (t->GetState()) r->CheckEntry(togglelist-1);\n\n }\n } else {\n AddEntry(method->GetName(), entry++, method);\n }\n }\n break;\n\n case kMenuToggle:\n {\n TToggle *t = new TToggle;\n t->SetToggledObject(object, method);\n t->SetOnValue(1);\n fTrash->Add(t);\n AddEntry(method->GetName(), toggle++, t);\n if (t->GetState()) CheckEntry(toggle-1);\n }\n break;\n\n default:\n break;\n }\n }\n delete methodList;\n }\n break;\n case TClassMenuItem::kPopupUserFunction:\n {\n if (menuItem->IsToggle()) {\n if (object) {\n TMethod* method =\n object->IsA()->GetMethodWithPrototype(menuItem->GetFunctionName(),menuItem->GetArgs());\n TToggle *t = new TToggle;\n t->SetToggledObject(object, method);\n t->SetOnValue(1);\n fTrash->Add(t);\n\n AddEntry(method->GetName(), toggle++, t);\n if (t->GetState()) CheckEntry(toggle-1);\n } else {\n Warning(\"Dialog\",\"Cannot use toggle for a global function\");\n }\n } else {\n const char* menuItemTitle = menuItem->GetTitle();\n if (strlen(menuItemTitle)==0) menuItemTitle = menuItem->GetFunctionName();\n AddEntry(menuItemTitle,userfunction++,menuItem);\n }\n }\n break;\n default:\n break;\n }\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::Dialog(TObject *object, TMethod *method)\n{\n \/\/ Create dialog object with OK and Cancel buttons. This dialog\n \/\/ prompts for the arguments of \"method\".\n\n Dialog(object,(TFunction*)method);\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::Dialog(TObject *object, TFunction *function)\n{\n \/\/ Create dialog object with OK and Cancel buttons. This dialog\n \/\/ prompts for the arguments of \"function\".\n \/\/ function may be a global function or a method\n\n Int_t selfobjpos;\n\n if (!function) return;\n\n \/\/ Position, if it exists, of the argument that correspond to the object itself\n if (fContextMenu->GetSelectedMenuItem())\n selfobjpos = fContextMenu->GetSelectedMenuItem()->GetSelfObjectPos();\n else selfobjpos = -1;\n\n const TGWindow *w;\n if (fContextMenu->GetSelectedCanvas()) {\n TCanvas *c = (TCanvas *) fContextMenu->GetSelectedCanvas();\n \/\/ Embedded canvas has no canvasimp that is a TGFrame\n if (c->GetCanvasImp()->IsA()->InheritsFrom(TGFrame::Class())) {\n w = fClient->GetWindowById(gVirtualX->GetWindowID(c->GetCanvasID()));\n if (!w) w = (TRootCanvas *) c->GetCanvasImp();\n } else {\n w = gClient->GetDefaultRoot();\n }\n } else if (fContextMenu->GetBrowser()) {\n TBrowser *b = (TBrowser *) fContextMenu->GetBrowser();\n w = (TRootBrowser *) b->GetBrowserImp();\n } else {\n w = gClient->GetDefaultRoot();\n }\n fDialog = new TRootDialog(this, w, fContextMenu->CreateDialogTitle(object, function));\n\n \/\/ iterate through all arguments and create apropriate input-data objects:\n \/\/ inputlines, option menus...\n TMethodArg *argument = 0;\n\n TIter next(function->GetListOfMethodArgs());\n Int_t argpos = 0;\n\n while ((argument = (TMethodArg *) next())) {\n \/\/ Do not input argument for self object\n if (selfobjpos != argpos) {\n Text_t *argname = fContextMenu->CreateArgumentTitle(argument);\n const Text_t *type = argument->GetTypeName();\n TDataType *datatype = gROOT->GetType(type);\n const Text_t *charstar = \"char*\";\n Text_t basictype[32];\n\n if (datatype) {\n strcpy(basictype, datatype->GetTypeName());\n } else {\n TClass *cl = TClass::GetClass(type);\n if (strncmp(type, \"enum\", 4) && (cl && !(cl->Property() & kIsEnum)))\n Warning(\"Dialog\", \"data type is not basic type, assuming (int)\");\n strcpy(basictype, \"int\");\n }\n\n if (strchr(argname, '*')) {\n strcat(basictype, \"*\");\n type = charstar;\n }\n\n TDataMember *m = argument->GetDataMember();\n if (m && m->GetterMethod(object->IsA())) {\n\n \/\/ Get the current value and form it as a text:\n\n Text_t val[256];\n\n if (!strncmp(basictype, \"char*\", 5)) {\n Text_t *tdefval;\n m->GetterMethod()->Execute(object, \"\", &tdefval);\n strncpy(val, tdefval, 255);\n } else if (!strncmp(basictype, \"float\", 5) ||\n !strncmp(basictype, \"double\", 6)) {\n Double_t ddefval;\n m->GetterMethod()->Execute(object, \"\", ddefval);\n sprintf(val, \"%g\", ddefval);\n } else if (!strncmp(basictype, \"char\", 4) ||\n !strncmp(basictype, \"bool\", 4) ||\n !strncmp(basictype, \"int\", 3) ||\n !strncmp(basictype, \"long\", 4) ||\n !strncmp(basictype, \"short\", 5)) {\n Long_t ldefval;\n m->GetterMethod()->Execute(object, \"\", ldefval);\n sprintf(val, \"%li\", ldefval);\n }\n\n \/\/ Find out whether we have options ...\n\n TList *opt;\n if ((opt = m->GetOptions())) {\n Warning(\"Dialog\", \"option menu not yet implemented\", opt);\n#if 0\n TMotifOptionMenu *o= new TMotifOptionMenu(argname);\n TIter nextopt(opt);\n TOptionListItem *it = 0;\n while ((it = (TOptionListItem*) nextopt())) {\n Text_t *name = it->fOptName;\n Text_t *label = it->fOptLabel;\n Long_t value = it->fValue;\n if (value != -9999) {\n Text_t val[256];\n sprintf(val, \"%li\", value);\n o->AddItem(name, val);\n }else\n o->AddItem(name, label);\n }\n o->SetData(val);\n fDialog->Add(o);\n#endif\n } else {\n \/\/ we haven't got options - textfield ...\n fDialog->Add(argname, val, type);\n }\n } else { \/\/ if m not found ...\n\n char val[256] = \"\";\n const char *tval = argument->GetDefault();\n if (tval) strncpy(val, tval, 255);\n fDialog->Add(argname, val, type);\n }\n }\n argpos++;\n }\n\n fDialog->Popup();\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootContextMenu::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)\n{\n \/\/ Handle context menu messages.\n \n TObjectSpy savedPad;\n if (GetContextMenu()->GetSelectedPad()) {\n savedPad.SetObject(gPad);\n gPad = GetContextMenu()->GetSelectedPad();\n }\n\n switch (GET_MSG(msg)) {\n\n case kC_COMMAND:\n\n switch (GET_SUBMSG(msg)) {\n\n case kCM_MENU:\n \n if (parm1 < kToggleStart) {\n TMethod *m = (TMethod *) parm2;\n GetContextMenu()->Action(m);\n } else if (parm1 >= kToggleStart && parm1 < kToggleListStart) {\n TToggle *t = (TToggle *) parm2;\n GetContextMenu()->Action(t);\n } else if (parm1 >= kToggleListStart && parm1GetState() == 0)\n t->SetState(1);\n } else {\n TClassMenuItem *mi = (TClassMenuItem*)parm2;\n GetContextMenu()->Action(mi);\n }\n break;\n\n case kCM_BUTTON:\n if (parm1 == 1) {\n const char *args = fDialog->GetParameters();\n GetContextMenu()->Execute((char *)args);\n delete fDialog;\n fDialog = 0;\n }\n if (parm1 == 2) {\n const char *args = fDialog->GetParameters();\n GetContextMenu()->Execute((char *)args);\n }\n if (parm1 == 3) {\n delete fDialog;\n fDialog = 0;\n }\n break;\n\n default:\n break;\n }\n break;\n\n case kC_TEXTENTRY:\n\n switch (GET_SUBMSG(msg)) {\n\n case kTE_ENTER:\n {\n const char *args = fDialog->GetParameters();\n GetContextMenu()->Execute((char *)args);\n delete fDialog;\n fDialog = 0;\n }\n break;\n\n default:\n break;\n }\n break;\n\n default:\n break;\n }\n\n if (savedPad.GetObject()) gPad = (TVirtualPad*) savedPad.GetObject();\n\n return kTRUE;\n}\nFix in TRootContextMenu::Dialog method: anytime the argument name contained a '*' the argument type was considered as \"char *\" what is not true for cases as \"Double_t *\" etc.\/\/ @(#)root\/gui:$Name: $:$Id: TRootContextMenu.cxx,v 1.17 2007\/01\/30 11:55:33 brun Exp $\n\/\/ Author: Fons Rademakers 12\/02\/98\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TRootContextMenu \/\/\n\/\/ \/\/\n\/\/ This class provides an interface to context sensitive popup menus. \/\/\n\/\/ These menus pop up when the user hits the right mouse button, and \/\/\n\/\/ are destroyed when the menu pops downs. \/\/\n\/\/ The picture below shows a canvas with a pop-up menu. \/\/\n\/\/ \/\/\n\/\/Begin_Html End_Html \/\/\n\/\/ \/\/\n\/\/ The picture below shows a canvas with a pop-up menu and a dialog box.\/\/\n\/\/ \/\/\n\/\/Begin_Html End_Html \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TRootContextMenu.h\"\n#include \"TROOT.h\"\n#include \"TGClient.h\"\n#include \"TList.h\"\n#include \"TContextMenu.h\"\n#include \"TMethod.h\"\n#include \"TMethodArg.h\"\n#include \"TClass.h\"\n#include \"TVirtualX.h\"\n#include \"TCanvas.h\"\n#include \"TDataMember.h\"\n#include \"TToggle.h\"\n#include \"TRootDialog.h\"\n#include \"TDataType.h\"\n#include \"TCanvas.h\"\n#include \"TBrowser.h\"\n#include \"TRootCanvas.h\"\n#include \"TRootBrowser.h\"\n#include \"TClassMenuItem.h\"\n#include \"TObjectSpy.h\"\n\nenum EContextMenu {\n kToggleStart = 1000, \/\/ first id of toggle menu items\n kToggleListStart = 2000, \/\/ first id of toggle list menu items\n kUserFunctionStart = 3000 \/\/ first id of user added functions\/methods, etc...\n};\n\n\nClassImp(TRootContextMenu)\n\n\/\/______________________________________________________________________________\nTRootContextMenu::TRootContextMenu(TContextMenu *c, const char *)\n : TGPopupMenu(gClient->GetDefaultRoot()), TContextMenuImp(c)\n{\n \/\/ Create context menu.\n\n fDialog = 0;\n fTrash = new TList;\n\n \/\/ Context menu handles its own messages\n Associate(this);\n}\n\n\/\/______________________________________________________________________________\nTRootContextMenu::~TRootContextMenu()\n{\n \/\/ Delete a context menu.\n\n delete fDialog;\n if (fTrash) fTrash->Delete();\n delete fTrash;\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::DisplayPopup(Int_t x, Int_t y)\n{\n \/\/ Display context popup menu for currently selected object.\n\n if (fClient->IsEditable()) return;\n\n \/\/ delete menu items releated to previous object and reset menu size\n if (fEntryList) fEntryList->Delete();\n if (fTrash) fTrash->Delete();\n fMenuHeight = 6;\n fMenuWidth = 8;\n\n \/\/ delete previous dialog\n if (fDialog) {\n delete fDialog;\n fDialog = 0;\n }\n\n \/\/ add menu items to popup menu\n CreateMenu(fContextMenu->GetSelectedObject());\n\n int xx, yy, topx = 0, topy = 0;\n UInt_t w, h;\n\n if (fContextMenu->GetSelectedCanvas())\n gVirtualX->GetGeometry(fContextMenu->GetSelectedCanvas()->GetCanvasID(),\n topx, topy, w, h);\n\n xx = topx + x + 1;\n yy = topy + y + 1;\n\n PlaceMenu(xx, yy, kFALSE, kTRUE);\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::CreateMenu(TObject *object)\n{\n \/\/ Create the context menu depending on the selected object.\n\n if (fClient->IsEditable()) return;\n\n int entry = 0, toggle = kToggleStart, togglelist = kToggleListStart;\n int userfunction = kUserFunctionStart;\n\n \/\/ Add a title\n AddLabel(fContextMenu->CreatePopupTitle(object));\n AddSeparator();\n\n \/\/ Get list of menu items from the selected object's class\n TList *menuItemList = object->IsA()->GetMenuList();\n\n TClassMenuItem *menuItem;\n TIter nextItem(menuItemList);\n\n while ((menuItem = (TClassMenuItem*) nextItem())) {\n switch (menuItem->GetType()) {\n case TClassMenuItem::kPopupSeparator:\n AddSeparator();\n break;\n case TClassMenuItem::kPopupStandardList:\n {\n \/\/ Standard list of class methods. Rebuild from scratch.\n \/\/ Get linked list of objects menu items (i.e. member functions\n \/\/ with the token *MENU in their comment fields.\n TList *methodList = new TList;\n object->IsA()->GetMenuItems(methodList);\n\n TMethod *method;\n TClass *classPtr = 0;\n TIter next(methodList);\n\n while ((method = (TMethod*) next())) {\n if (classPtr != method->GetClass()) {\n AddSeparator();\n classPtr = method->GetClass();\n }\n\n TDataMember *m;\n EMenuItemKind menuKind = method->IsMenuItem();\n switch (menuKind) {\n case kMenuDialog:\n AddEntry(method->GetName(), entry++, method);\n break;\n case kMenuSubMenu:\n if ((m = method->FindDataMember())) {\n if (m->GetterMethod()) {\n TGPopupMenu *r = new TGPopupMenu(gClient->GetDefaultRoot());\n AddPopup(method->GetName(), r);\n fTrash->Add(r);\n TIter nxt(m->GetOptions());\n TOptionListItem *it;\n while ((it = (TOptionListItem*) nxt())) {\n char *name = it->fOptName;\n Long_t val = it->fValue;\n\n TToggle *t = new TToggle;\n t->SetToggledObject(object, method);\n t->SetOnValue(val);\n fTrash->Add(t);\n\n r->AddSeparator();\n r->AddEntry(name, togglelist++, t);\n if (t->GetState()) r->CheckEntry(togglelist-1);\n\n }\n } else {\n AddEntry(method->GetName(), entry++, method);\n }\n }\n break;\n\n case kMenuToggle:\n {\n TToggle *t = new TToggle;\n t->SetToggledObject(object, method);\n t->SetOnValue(1);\n fTrash->Add(t);\n AddEntry(method->GetName(), toggle++, t);\n if (t->GetState()) CheckEntry(toggle-1);\n }\n break;\n\n default:\n break;\n }\n }\n delete methodList;\n }\n break;\n case TClassMenuItem::kPopupUserFunction:\n {\n if (menuItem->IsToggle()) {\n if (object) {\n TMethod* method =\n object->IsA()->GetMethodWithPrototype(menuItem->GetFunctionName(),menuItem->GetArgs());\n TToggle *t = new TToggle;\n t->SetToggledObject(object, method);\n t->SetOnValue(1);\n fTrash->Add(t);\n\n AddEntry(method->GetName(), toggle++, t);\n if (t->GetState()) CheckEntry(toggle-1);\n } else {\n Warning(\"Dialog\",\"Cannot use toggle for a global function\");\n }\n } else {\n const char* menuItemTitle = menuItem->GetTitle();\n if (strlen(menuItemTitle)==0) menuItemTitle = menuItem->GetFunctionName();\n AddEntry(menuItemTitle,userfunction++,menuItem);\n }\n }\n break;\n default:\n break;\n }\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::Dialog(TObject *object, TMethod *method)\n{\n \/\/ Create dialog object with OK and Cancel buttons. This dialog\n \/\/ prompts for the arguments of \"method\".\n\n Dialog(object,(TFunction*)method);\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::Dialog(TObject *object, TFunction *function)\n{\n \/\/ Create dialog object with OK and Cancel buttons. This dialog\n \/\/ prompts for the arguments of \"function\".\n \/\/ function may be a global function or a method\n\n Int_t selfobjpos;\n\n if (!function) return;\n\n \/\/ Position, if it exists, of the argument that correspond to the object itself\n if (fContextMenu->GetSelectedMenuItem())\n selfobjpos = fContextMenu->GetSelectedMenuItem()->GetSelfObjectPos();\n else selfobjpos = -1;\n\n const TGWindow *w;\n if (fContextMenu->GetSelectedCanvas()) {\n TCanvas *c = (TCanvas *) fContextMenu->GetSelectedCanvas();\n \/\/ Embedded canvas has no canvasimp that is a TGFrame\n if (c->GetCanvasImp()->IsA()->InheritsFrom(TGFrame::Class())) {\n w = fClient->GetWindowById(gVirtualX->GetWindowID(c->GetCanvasID()));\n if (!w) w = (TRootCanvas *) c->GetCanvasImp();\n } else {\n w = gClient->GetDefaultRoot();\n }\n } else if (fContextMenu->GetBrowser()) {\n TBrowser *b = (TBrowser *) fContextMenu->GetBrowser();\n w = (TRootBrowser *) b->GetBrowserImp();\n } else {\n w = gClient->GetDefaultRoot();\n }\n fDialog = new TRootDialog(this, w, fContextMenu->CreateDialogTitle(object, function));\n\n \/\/ iterate through all arguments and create apropriate input-data objects:\n \/\/ inputlines, option menus...\n TMethodArg *argument = 0;\n\n TIter next(function->GetListOfMethodArgs());\n Int_t argpos = 0;\n\n while ((argument = (TMethodArg *) next())) {\n \/\/ Do not input argument for self object\n if (selfobjpos != argpos) {\n Text_t *argname = fContextMenu->CreateArgumentTitle(argument);\n const Text_t *type = argument->GetTypeName();\n TDataType *datatype = gROOT->GetType(type);\n Text_t basictype[32];\n\n if (datatype) {\n strcpy(basictype, datatype->GetTypeName());\n } else {\n TClass *cl = TClass::GetClass(type);\n if (strncmp(type, \"enum\", 4) && (cl && !(cl->Property() & kIsEnum)))\n Warning(\"Dialog\", \"data type is not basic type, assuming (int)\");\n strcpy(basictype, \"int\");\n }\n\n if (strchr(argname, '*')) {\n strcat(basictype, \"*\");\n }\n\n TDataMember *m = argument->GetDataMember();\n if (m && m->GetterMethod(object->IsA())) {\n\n \/\/ Get the current value and form it as a text:\n\n Text_t val[256];\n\n if (!strncmp(basictype, \"char*\", 5)) {\n Text_t *tdefval;\n m->GetterMethod()->Execute(object, \"\", &tdefval);\n strncpy(val, tdefval, 255);\n } else if (!strncmp(basictype, \"float\", 5) ||\n !strncmp(basictype, \"double\", 6)) {\n Double_t ddefval;\n m->GetterMethod()->Execute(object, \"\", ddefval);\n sprintf(val, \"%g\", ddefval);\n } else if (!strncmp(basictype, \"char\", 4) ||\n !strncmp(basictype, \"bool\", 4) ||\n !strncmp(basictype, \"int\", 3) ||\n !strncmp(basictype, \"long\", 4) ||\n !strncmp(basictype, \"short\", 5)) {\n Long_t ldefval;\n m->GetterMethod()->Execute(object, \"\", ldefval);\n sprintf(val, \"%li\", ldefval);\n }\n\n \/\/ Find out whether we have options ...\n\n TList *opt;\n if ((opt = m->GetOptions())) {\n Warning(\"Dialog\", \"option menu not yet implemented\", opt);\n#if 0\n TMotifOptionMenu *o= new TMotifOptionMenu(argname);\n TIter nextopt(opt);\n TOptionListItem *it = 0;\n while ((it = (TOptionListItem*) nextopt())) {\n Text_t *name = it->fOptName;\n Text_t *label = it->fOptLabel;\n Long_t value = it->fValue;\n if (value != -9999) {\n Text_t val[256];\n sprintf(val, \"%li\", value);\n o->AddItem(name, val);\n }else\n o->AddItem(name, label);\n }\n o->SetData(val);\n fDialog->Add(o);\n#endif\n } else {\n \/\/ we haven't got options - textfield ...\n fDialog->Add(argname, val, type);\n }\n } else { \/\/ if m not found ...\n\n char val[256] = \"\";\n const char *tval = argument->GetDefault();\n if (tval) strncpy(val, tval, 255);\n fDialog->Add(argname, val, type);\n }\n }\n argpos++;\n }\n\n fDialog->Popup();\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootContextMenu::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)\n{\n \/\/ Handle context menu messages.\n \n TObjectSpy savedPad;\n if (GetContextMenu()->GetSelectedPad()) {\n savedPad.SetObject(gPad);\n gPad = GetContextMenu()->GetSelectedPad();\n }\n\n switch (GET_MSG(msg)) {\n\n case kC_COMMAND:\n\n switch (GET_SUBMSG(msg)) {\n\n case kCM_MENU:\n \n if (parm1 < kToggleStart) {\n TMethod *m = (TMethod *) parm2;\n GetContextMenu()->Action(m);\n } else if (parm1 >= kToggleStart && parm1 < kToggleListStart) {\n TToggle *t = (TToggle *) parm2;\n GetContextMenu()->Action(t);\n } else if (parm1 >= kToggleListStart && parm1GetState() == 0)\n t->SetState(1);\n } else {\n TClassMenuItem *mi = (TClassMenuItem*)parm2;\n GetContextMenu()->Action(mi);\n }\n break;\n\n case kCM_BUTTON:\n if (parm1 == 1) {\n const char *args = fDialog->GetParameters();\n GetContextMenu()->Execute((char *)args);\n delete fDialog;\n fDialog = 0;\n }\n if (parm1 == 2) {\n const char *args = fDialog->GetParameters();\n GetContextMenu()->Execute((char *)args);\n }\n if (parm1 == 3) {\n delete fDialog;\n fDialog = 0;\n }\n break;\n\n default:\n break;\n }\n break;\n\n case kC_TEXTENTRY:\n\n switch (GET_SUBMSG(msg)) {\n\n case kTE_ENTER:\n {\n const char *args = fDialog->GetParameters();\n GetContextMenu()->Execute((char *)args);\n delete fDialog;\n fDialog = 0;\n }\n break;\n\n default:\n break;\n }\n break;\n\n default:\n break;\n }\n\n if (savedPad.GetObject()) gPad = (TVirtualPad*) savedPad.GetObject();\n\n return kTRUE;\n}\n<|endoftext|>"} {"text":"#include \"ros\/ros.h\"\n#include \"geometry_msgs\/Pose.h\"\n#include \"geometry_msgs\/Twist.h\"\n#include \"geometry_msgs\/Wrench.h\"\n#include \"uranus_dp\/State.h\"\n#include \n#include \n\nclass Controller\n{\npublic:\n Controller()\n {\n outputPub = n.advertise(\"outputTopic\", 1);\n stateSub = n.subscribe(\"stateTopic\", 1, &Controller::stateCallback, this);\n setpointSub = n.subscribe(\"setpointTopic\", 1, &Controller::setpointCallback, this);\n\n \/\/ Set default frequency\n frequency = 10;\n\n \/\/ Allocate dynamic member variables\n T = Eigen::MatrixXd(4,3);\n tau = Eigen::VectorXd(6);\n\n \/\/ Initialize controller gains\n K_lin_p = Eigen::Matrix3d::Identity();\n K_lin_d = Eigen::Matrix3d::Identity();\n K_ang_p = Eigen::Matrix3d::Identity();\n K_ang_d = Eigen::Matrix3d::Identity();\n }\n\n \/\/ stateCallback updates the private state variables when a new state message arrives.\n void stateCallback(const uranus_dp::State &state_msg)\n {\n \/\/ Copy position values\n p(0) = state_msg.pose.position.x;\n p(1) = state_msg.pose.position.y;\n p(2) = state_msg.pose.position.z;\n\n \/\/ Copy orientation values (quaternion)\n q(0) = state_msg.pose.orientation.x;\n q(1) = state_msg.pose.orientation.y;\n q(2) = state_msg.pose.orientation.z;\n q(3) = state_msg.pose.orientation.w;\n\n \/\/ Copy linear velocity values\n v(0) = state_msg.twist.linear.x;\n v(1) = state_msg.twist.linear.y;\n v(2) = state_msg.twist.linear.z;\n\n \/\/ Copy angular velocity values\n omega(0) = state_msg.twist.angular.x;\n omega(1) = state_msg.twist.angular.y;\n omega(2) = state_msg.twist.angular.z;\n }\n\n \/\/ setpointCallback updates the private setpoint variable when a new setpoint message arrives.\n void setpointCallback(const geometry_msgs::Twist &setpoint_msg)\n {\n \/\/ Copy linear velocity setpoint values\n v_sp(0) = setpoint_msg.linear.x;\n v_sp(1) = setpoint_msg.linear.y;\n v_sp(2) = setpoint_msg.linear.z;\n\n \/\/ Copy angular velocity setpoint values\n omega_sp(0) = setpoint_msg.angular.x;\n omega_sp(1) = setpoint_msg.angular.y;\n omega_sp(2) = setpoint_msg.angular.z;\n }\n\n \/\/ compute contains the control algorithm, and computes the control output based on the\n \/\/ current state and setpoint.\n void compute(void)\n {\n \/\/ Only pose control for now\n\n \/\/ Position and orientation errors\n p_err = p_sp - p;\n q_err = q_sp - q;\n\n \/\/ Control output\n updateTransformationMatrices();\n Eigen::Vector3d tau_lin = K_lin_p * p_err + K_lin_d * v;\n Eigen::Vector3d tau_ang = - K_ang_p * T.transpose() * q_err - K_ang_d * omega;\n tau << tau_lin, tau_ang;\n\n \/\/ Create and send output message\n geometry_msgs::Wrench output;\n output.force.x = tau(0);\n output.force.y = tau(1);\n output.force.z = tau(2);\n output.torque.x = tau(3);\n output.torque.y = tau(4);\n output.torque.z = tau(5);\n outputPub.publish(output);\n }\n\n \/\/ setFrequency tells the controller which frequency in Hz compute() is called with.\n void setFrequency(unsigned int newFrequency)\n {\n frequency = newFrequency;\n }\nprivate:\n ros::NodeHandle n;\n ros::Publisher outputPub;\n ros::Subscriber stateSub;\n ros::Subscriber setpointSub;\n\n \/\/ Controller frequency\n unsigned int frequency;\n\n \/\/ State\n Eigen::Vector3d p; \/\/ Position\n Eigen::Vector4d q; \/\/ Orientation\n Eigen::Vector3d v; \/\/ Linear velocity\n Eigen::Vector3d omega; \/\/ Angular velocity\n\n \/\/ Setpoints\n Eigen::Vector3d p_sp; \/\/ Position\n Eigen::Vector4d q_sp; \/\/ Orientation\n Eigen::Vector3d v_sp; \/\/ Linear velocity\n Eigen::Vector3d omega_sp; \/\/ Angular velocity\n\n \/\/ Errors\n Eigen::Vector3d p_err; \/\/ Position\n Eigen::Vector4d q_err; \/\/ Orientation\n Eigen::Vector3d v_err; \/\/ Linear velocity\n Eigen::Vector3d omega_err; \/\/ Angular velocity\n\n \/\/ Transformation matrices\n Eigen::Matrix3d R;\n Eigen::MatrixXd T;\n\n \/\/ Control output\n Eigen::VectorXd tau;\n\n \/\/ Controller gains\n Eigen::Matrix3d K_lin_d;\n Eigen::Matrix3d K_lin_p;\n Eigen::Matrix3d K_ang_d;\n Eigen::Matrix3d K_ang_p;\n\n void updateTransformationMatrices(void)\n {\n \/\/ Linear velocity transformation matrix\n R(0,0) = 1 - 2*(pow(q(2),2) + pow(q(3),2));\n R(0,1) = 2*(q(1)*q(2) - q(3)*q(0));\n R(0,2) = 2*(q(1)*q(3) - q(2)*q(0));\n \n R(1,0) = 2*(q(1)*q(2) + q(3)*q(0));\n R(1,1) = 1 - 2*(pow(q(1),2) + pow(q(0),2));\n R(1,2) = 2*(q(2)*q(3) + q(1)*q(0));\n \n R(2,0) = 2*(q(1)*q(3) + q(2)*q(0));\n R(2,1) = 2*(q(2)*q(3) + q(1)*q(0));\n R(2,2) = 1 - 2*(pow(q(1),2) + pow(q(2),2));\n\n \/\/ Angular velocity transformation matrix\n T(0,0) = -q(1);\n T(0,1) = -q(2);\n T(0,2) = -q(3);\n\n T(1,0) = q(0);\n T(1,1) = -q(3);\n T(1,2) = q(2);\n\n T(2,0) = q(3);\n T(2,1) = q(3);\n T(2,2) = -q(1);\n\n T(3,0) = -q(2);\n T(3,1) = q(1);\n T(3,2) = q(0);\n\n T *= 0.5;\n }\n}; \/\/ End of class Controller\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"controller\");\n\n Controller controllerObject;\n\n unsigned int frequency = 10; \/\/ Get from parameter server sometime in the future\n controllerObject.setFrequency(frequency);\n\n ros::Rate loop_rate(frequency);\n while (ros::ok())\n {\n ros::spinOnce();\n\n controllerObject.compute();\n\n loop_rate.sleep();\n }\n\n return 0;\n}\nChange controller class and instance name#include \"ros\/ros.h\"\n#include \"geometry_msgs\/Pose.h\"\n#include \"geometry_msgs\/Twist.h\"\n#include \"geometry_msgs\/Wrench.h\"\n#include \"uranus_dp\/State.h\"\n#include \n#include \n\nclass NonlinearQuaternionPidController\n{\npublic:\n NonlinearQuaternionPidController()\n {\n outputPub = n.advertise(\"outputTopic\", 1);\n stateSub = n.subscribe(\"stateTopic\", 1, &NonlinearQuaternionPidController::stateCallback, this);\n setpointSub = n.subscribe(\"setpointTopic\", 1, &NonlinearQuaternionPidController::setpointCallback, this);\n\n \/\/ Set default frequency\n frequency = 10;\n\n \/\/ Allocate dynamic member variables\n T = Eigen::MatrixXd(4,3);\n tau = Eigen::VectorXd(6);\n\n \/\/ Initialize controller gains\n K_lin_p = Eigen::Matrix3d::Identity();\n K_lin_d = Eigen::Matrix3d::Identity();\n K_ang_p = Eigen::Matrix3d::Identity();\n K_ang_d = Eigen::Matrix3d::Identity();\n }\n\n \/\/ stateCallback updates the private state variables when a new state message arrives.\n void stateCallback(const uranus_dp::State &state_msg)\n {\n \/\/ Copy position values\n p(0) = state_msg.pose.position.x;\n p(1) = state_msg.pose.position.y;\n p(2) = state_msg.pose.position.z;\n\n \/\/ Copy orientation values (quaternion)\n q(0) = state_msg.pose.orientation.x;\n q(1) = state_msg.pose.orientation.y;\n q(2) = state_msg.pose.orientation.z;\n q(3) = state_msg.pose.orientation.w;\n\n \/\/ Copy linear velocity values\n v(0) = state_msg.twist.linear.x;\n v(1) = state_msg.twist.linear.y;\n v(2) = state_msg.twist.linear.z;\n\n \/\/ Copy angular velocity values\n omega(0) = state_msg.twist.angular.x;\n omega(1) = state_msg.twist.angular.y;\n omega(2) = state_msg.twist.angular.z;\n }\n\n \/\/ setpointCallback updates the private setpoint variable when a new setpoint message arrives.\n void setpointCallback(const geometry_msgs::Twist &setpoint_msg)\n {\n \/\/ Copy linear velocity setpoint values\n v_sp(0) = setpoint_msg.linear.x;\n v_sp(1) = setpoint_msg.linear.y;\n v_sp(2) = setpoint_msg.linear.z;\n\n \/\/ Copy angular velocity setpoint values\n omega_sp(0) = setpoint_msg.angular.x;\n omega_sp(1) = setpoint_msg.angular.y;\n omega_sp(2) = setpoint_msg.angular.z;\n }\n\n \/\/ compute contains the control algorithm, and computes the control output based on the\n \/\/ current state and setpoint.\n void compute(void)\n {\n \/\/ Only pose control for now\n\n \/\/ Position and orientation errors\n p_err = p_sp - p;\n q_err = q_sp - q;\n\n \/\/ Control output\n updateTransformationMatrices();\n Eigen::Vector3d tau_lin = K_lin_p * p_err + K_lin_d * v;\n Eigen::Vector3d tau_ang = - K_ang_p * T.transpose() * q_err - K_ang_d * omega;\n tau << tau_lin, tau_ang;\n\n \/\/ Create and send output message\n geometry_msgs::Wrench output;\n output.force.x = tau(0);\n output.force.y = tau(1);\n output.force.z = tau(2);\n output.torque.x = tau(3);\n output.torque.y = tau(4);\n output.torque.z = tau(5);\n outputPub.publish(output);\n }\n\n \/\/ setFrequency tells the controller which frequency in Hz compute() is called with.\n void setFrequency(unsigned int newFrequency)\n {\n frequency = newFrequency;\n }\nprivate:\n ros::NodeHandle n;\n ros::Publisher outputPub;\n ros::Subscriber stateSub;\n ros::Subscriber setpointSub;\n\n \/\/ Controller frequency\n unsigned int frequency;\n\n \/\/ State\n Eigen::Vector3d p; \/\/ Position\n Eigen::Vector4d q; \/\/ Orientation\n Eigen::Vector3d v; \/\/ Linear velocity\n Eigen::Vector3d omega; \/\/ Angular velocity\n\n \/\/ Setpoints\n Eigen::Vector3d p_sp; \/\/ Position\n Eigen::Vector4d q_sp; \/\/ Orientation\n Eigen::Vector3d v_sp; \/\/ Linear velocity\n Eigen::Vector3d omega_sp; \/\/ Angular velocity\n\n \/\/ Errors\n Eigen::Vector3d p_err; \/\/ Position\n Eigen::Vector4d q_err; \/\/ Orientation\n Eigen::Vector3d v_err; \/\/ Linear velocity\n Eigen::Vector3d omega_err; \/\/ Angular velocity\n\n \/\/ Transformation matrices\n Eigen::Matrix3d R;\n Eigen::MatrixXd T;\n\n \/\/ Control output\n Eigen::VectorXd tau;\n\n \/\/ Controller gains\n Eigen::Matrix3d K_lin_d;\n Eigen::Matrix3d K_lin_p;\n Eigen::Matrix3d K_ang_d;\n Eigen::Matrix3d K_ang_p;\n\n void updateTransformationMatrices(void)\n {\n \/\/ Linear velocity transformation matrix\n R(0,0) = 1 - 2*(pow(q(2),2) + pow(q(3),2));\n R(0,1) = 2*(q(1)*q(2) - q(3)*q(0));\n R(0,2) = 2*(q(1)*q(3) - q(2)*q(0));\n \n R(1,0) = 2*(q(1)*q(2) + q(3)*q(0));\n R(1,1) = 1 - 2*(pow(q(1),2) + pow(q(0),2));\n R(1,2) = 2*(q(2)*q(3) + q(1)*q(0));\n \n R(2,0) = 2*(q(1)*q(3) + q(2)*q(0));\n R(2,1) = 2*(q(2)*q(3) + q(1)*q(0));\n R(2,2) = 1 - 2*(pow(q(1),2) + pow(q(2),2));\n\n \/\/ Angular velocity transformation matrix\n T(0,0) = -q(1);\n T(0,1) = -q(2);\n T(0,2) = -q(3);\n\n T(1,0) = q(0);\n T(1,1) = -q(3);\n T(1,2) = q(2);\n\n T(2,0) = q(3);\n T(2,1) = q(3);\n T(2,2) = -q(1);\n\n T(3,0) = -q(2);\n T(3,1) = q(1);\n T(3,2) = q(0);\n\n T *= 0.5;\n }\n}; \/\/ End of class NonlinearQuaternionPidController\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"controller\");\n\n NonlinearQuaternionPidController controller;\n\n unsigned int frequency = 10; \/\/ Get from parameter server sometime in the future\n controller.setFrequency(frequency);\n\n ros::Rate loop_rate(frequency);\n while (ros::ok())\n {\n ros::spinOnce();\n\n controller.compute();\n\n loop_rate.sleep();\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2009 Mark D. Hill and David A. Wood\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef __MEM_RUBY_SYSTEM_MEMORYVECTOR_HH__\n#define __MEM_RUBY_SYSTEM_MEMORYVECTOR_HH__\n\n#include \"mem\/ruby\/common\/Address.hh\"\n\nclass DirectoryMemory;\n\n\/**\n * MemoryVector holds memory data (DRAM only)\n *\/\nclass MemoryVector\n{\n public:\n MemoryVector();\n MemoryVector(uint32 size);\n ~MemoryVector();\n friend class DirectoryMemory;\n\n void resize(uint32 size); \/\/ destructive\n\n void write(const Address & paddr, uint8* data, int len);\n uint8* read(const Address & paddr, uint8* data, int len);\n\n private:\n uint8* getBlockPtr(const PhysAddress & addr);\n\n uint32 m_size;\n uint8** m_pages;\n uint32 m_num_pages;\n const uint32 m_page_offset_mask;\n};\n\ninline\nMemoryVector::MemoryVector()\n : m_page_offset_mask(4095)\n{\n m_size = 0;\n m_num_pages = 0;\n m_pages = NULL;\n}\n\ninline\nMemoryVector::MemoryVector(uint32 size)\n : m_page_offset_mask(4095)\n{\n resize(size);\n}\n\ninline\nMemoryVector::~MemoryVector()\n{\n for (int i = 0; i < m_num_pages; i++) {\n if (m_pages[i] != 0) {\n delete [] m_pages[i];\n }\n }\n delete [] m_pages;\n}\n\ninline void\nMemoryVector::resize(uint32 size)\n{\n if (m_pages != NULL){\n for (int i = 0; i < m_num_pages; i++) {\n if (m_pages[i] != 0) {\n delete [] m_pages[i];\n }\n }\n delete [] m_pages;\n }\n m_size = size;\n assert(size%4096 == 0);\n m_num_pages = size >> 12;\n m_pages = new uint8*[m_num_pages];\n memset(m_pages, 0, m_num_pages * sizeof(uint8*));\n}\n\ninline void\nMemoryVector::write(const Address & paddr, uint8* data, int len)\n{\n assert(paddr.getAddress() + len <= m_size);\n uint32 page_num = paddr.getAddress() >> 12;\n if (m_pages[page_num] == 0) {\n bool all_zeros = true;\n for (int i = 0; i < len;i++) {\n if (data[i] != 0) {\n all_zeros = false;\n break;\n }\n }\n if (all_zeros)\n return;\n m_pages[page_num] = new uint8[4096];\n memset(m_pages[page_num], 0, 4096);\n uint32 offset = paddr.getAddress() & m_page_offset_mask;\n memcpy(&m_pages[page_num][offset], data, len);\n } else {\n memcpy(&m_pages[page_num][paddr.getAddress()&m_page_offset_mask],\n data, len);\n }\n}\n\ninline uint8*\nMemoryVector::read(const Address & paddr, uint8* data, int len)\n{\n assert(paddr.getAddress() + len <= m_size);\n uint32 page_num = paddr.getAddress() >> 12;\n if (m_pages[page_num] == 0) {\n memset(data, 0, len);\n } else {\n memcpy(data, &m_pages[page_num][paddr.getAddress()&m_page_offset_mask],\n len);\n }\n return data;\n}\n\ninline uint8*\nMemoryVector::getBlockPtr(const PhysAddress & paddr)\n{\n uint32 page_num = paddr.getAddress() >> 12;\n if (m_pages[page_num] == 0) {\n m_pages[page_num] = new uint8[4096];\n memset(m_pages[page_num], 0, 4096);\n }\n return &m_pages[page_num][paddr.getAddress()&m_page_offset_mask];\n}\n\n#endif \/\/ __MEM_RUBY_SYSTEM_MEMORYVECTOR_HH__\nRuby Memory Vector: Functions for collating and populating pages This patch adds functions to the memory vector class that can be used for collating memory pages to raw trace and for populating pages from a raw trace.\/*\n * Copyright (c) 2009 Mark D. Hill and David A. Wood\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef __MEM_RUBY_SYSTEM_MEMORYVECTOR_HH__\n#define __MEM_RUBY_SYSTEM_MEMORYVECTOR_HH__\n\n#include \"base\/trace.hh\"\n#include \"mem\/ruby\/common\/Address.hh\"\n\nclass DirectoryMemory;\n\n\/**\n * MemoryVector holds memory data (DRAM only)\n *\/\nclass MemoryVector\n{\n public:\n MemoryVector();\n MemoryVector(uint32 size);\n ~MemoryVector();\n friend class DirectoryMemory;\n\n void resize(uint32 size); \/\/ destructive\n\n void write(const Address & paddr, uint8* data, int len);\n uint8* read(const Address & paddr, uint8* data, int len);\n uint32 collatePages(uint8* &raw_data);\n void populatePages(uint8* raw_data);\n\n private:\n uint8* getBlockPtr(const PhysAddress & addr);\n\n uint32 m_size;\n uint8** m_pages;\n uint32 m_num_pages;\n const uint32 m_page_offset_mask;\n static const uint32 PAGE_SIZE = 4096;\n};\n\ninline\nMemoryVector::MemoryVector()\n : m_page_offset_mask(4095)\n{\n m_size = 0;\n m_num_pages = 0;\n m_pages = NULL;\n}\n\ninline\nMemoryVector::MemoryVector(uint32 size)\n : m_page_offset_mask(4095)\n{\n resize(size);\n}\n\ninline\nMemoryVector::~MemoryVector()\n{\n for (int i = 0; i < m_num_pages; i++) {\n if (m_pages[i] != 0) {\n delete [] m_pages[i];\n }\n }\n delete [] m_pages;\n}\n\ninline void\nMemoryVector::resize(uint32 size)\n{\n if (m_pages != NULL){\n for (int i = 0; i < m_num_pages; i++) {\n if (m_pages[i] != 0) {\n delete [] m_pages[i];\n }\n }\n delete [] m_pages;\n }\n m_size = size;\n assert(size%PAGE_SIZE == 0);\n m_num_pages = size >> 12;\n m_pages = new uint8*[m_num_pages];\n memset(m_pages, 0, m_num_pages * sizeof(uint8*));\n}\n\ninline void\nMemoryVector::write(const Address & paddr, uint8* data, int len)\n{\n assert(paddr.getAddress() + len <= m_size);\n uint32 page_num = paddr.getAddress() >> 12;\n if (m_pages[page_num] == 0) {\n bool all_zeros = true;\n for (int i = 0; i < len;i++) {\n if (data[i] != 0) {\n all_zeros = false;\n break;\n }\n }\n if (all_zeros)\n return;\n m_pages[page_num] = new uint8[PAGE_SIZE];\n memset(m_pages[page_num], 0, PAGE_SIZE);\n uint32 offset = paddr.getAddress() & m_page_offset_mask;\n memcpy(&m_pages[page_num][offset], data, len);\n } else {\n memcpy(&m_pages[page_num][paddr.getAddress()&m_page_offset_mask],\n data, len);\n }\n}\n\ninline uint8*\nMemoryVector::read(const Address & paddr, uint8* data, int len)\n{\n assert(paddr.getAddress() + len <= m_size);\n uint32 page_num = paddr.getAddress() >> 12;\n if (m_pages[page_num] == 0) {\n memset(data, 0, len);\n } else {\n memcpy(data, &m_pages[page_num][paddr.getAddress()&m_page_offset_mask],\n len);\n }\n return data;\n}\n\ninline uint8*\nMemoryVector::getBlockPtr(const PhysAddress & paddr)\n{\n uint32 page_num = paddr.getAddress() >> 12;\n if (m_pages[page_num] == 0) {\n m_pages[page_num] = new uint8[PAGE_SIZE];\n memset(m_pages[page_num], 0, PAGE_SIZE);\n }\n return &m_pages[page_num][paddr.getAddress()&m_page_offset_mask];\n}\n\n\/*!\n * Function for collating all the pages of the physical memory together.\n * In case a pointer for a page is NULL, this page needs only a single byte\n * to represent that the pointer is NULL. Otherwise, it needs 1 + PAGE_SIZE\n * bytes. The first represents that the page pointer is not NULL, and rest of\n * the bytes represent the data on the page.\n *\/\n\ninline uint32\nMemoryVector::collatePages(uint8* &raw_data)\n{\n uint32 num_zero_pages = 0;\n uint32 data_size = 0;\n\n for (uint32 i = 0;i < m_num_pages; ++i)\n {\n if (m_pages[i] == 0) num_zero_pages++;\n }\n\n raw_data = new uint8[ sizeof(uint32) \/* number of pages*\/\n + m_num_pages \/* whether the page is all zeros *\/\n + PAGE_SIZE * (m_num_pages - num_zero_pages)];\n\n \/* Write the number of pages to be stored. *\/\n memcpy(raw_data, &m_num_pages, sizeof(uint32));\n data_size = sizeof(uint32);\n\n for (uint32 i = 0;i < m_num_pages; ++i)\n {\n if (m_pages[i] == 0) {\n raw_data[data_size] = 0;\n } else {\n raw_data[data_size] = 1;\n memcpy(raw_data + data_size + 1, m_pages[i], PAGE_SIZE);\n data_size += PAGE_SIZE;\n }\n data_size += 1;\n }\n\n return data_size;\n}\n\n\/*!\n * Function for populating the pages of the memory using the available raw\n * data. Each page has a byte associate with it, which represents whether the\n * page was NULL or not, when all the pages were collated. The function assumes\n * that the number of pages in the memory are same as those that were recorded\n * in the checkpoint.\n *\/\ninline void\nMemoryVector::populatePages(uint8* raw_data)\n{\n uint32 data_size = 0;\n uint32 num_pages = 0;\n\n \/* Read the number of pages that were stored. *\/\n memcpy(&num_pages, raw_data, sizeof(uint32));\n data_size = sizeof(uint32);\n assert(num_pages == m_num_pages);\n\n for (uint32 i = 0;i < m_num_pages; ++i)\n {\n assert(m_pages[i] == 0);\n if (raw_data[data_size] != 0) {\n m_pages[i] = new uint8[PAGE_SIZE];\n memcpy(m_pages[i], raw_data + data_size + 1, PAGE_SIZE);\n data_size += PAGE_SIZE;\n }\n data_size += 1;\n }\n}\n\n#endif \/\/ __MEM_RUBY_SYSTEM_MEMORYVECTOR_HH__\n<|endoftext|>"} {"text":"\/**\n * @author Parikshit Ram (pram@cc.gatech.edu)\n * @file mog_em_main.cpp\n *\n * This program test drives the parametric estimation\n * of a Gaussian Mixture model using maximum likelihood.\n *\n * PARAMETERS TO BE INPUT:\n *\n * --data\n * This is the file that contains the data on which\n * the model is to be fit\n *\n * --mog_em\/K\n * This is the number of gaussians we want to fit\n * on the data, defaults to '1'\n *\n * --output\n * This file will contain the parameters estimated,\n * defaults to 'ouotput.csv'\n *\n *\/\n#include \"mog_em.hpp\"\n\nPROGRAM_INFO(\"Mixture of Gaussians\",\n \"This program takes a parametric estimate of a Gaussian mixture model (GMM)\"\n \" using maximum likelihood.\", \"mog\");\n\nPARAM_STRING_REQ(\"data\", \"A file containing the data on which the model has to \"\n \"be fit.\", \"mog\");\nPARAM_STRING(\"output\", \"The file into which the output is to be written into.\",\n \"mog\", \"output.csv\");\n\nusing namespace mlpack;\nusing namespace mlpack::gmm;\n\nint main(int argc, char* argv[]) {\n CLI::ParseCommandLine(argc, argv);\n\n \/\/\/\/\/\/ READING PARAMETERS AND LOADING DATA \/\/\/\/\/\/\n arma::mat data_points;\n data::Load(CLI::GetParam(\"mog\/data\").c_str(), data_points, true);\n\n \/\/\/\/\/\/ MIXTURE OF GAUSSIANS USING EM \/\/\/\/\/\/\n MoGEM mog;\n\n CLI::GetParam(\"mog\/k\") = 1;\n CLI::GetParam(\"mog\/d\") = data_points.n_rows;\n\n \/\/\/\/\/\/ Timing the initialization of the mixture model \/\/\/\/\/\/\n Timers::StartTimer(\"mog\/model_init\");\n mog.Init(1, data_points.n_rows);\n Timers::StopTimer(\"mog\/model_init\");\n\n \/\/\/\/\/\/ Computing the parameters of the model using the EM algorithm \/\/\/\/\/\/\n std::vector results;\n\n Timers::StartTimer(\"mog\/EM\");\n mog.ExpectationMaximization(data_points);\n Timers::StopTimer(\"mog\/EM\");\n\n mog.Display();\n mog.OutputResults(results);\n\n \/\/\/\/\/\/ OUTPUT RESULTS \/\/\/\/\/\/\n \/\/ We need a better solution for this. So, currently, we do nothing.\n \/\/ XML is probably the right tool for the job.\n}\nFlesh out main executable for GMMs.\/**\n * @author Parikshit Ram (pram@cc.gatech.edu)\n * @file gmm_main.cpp\n *\n * This program trains a mixture of Gaussians on a given data matrix.\n *\/\n#include \"gmm.hpp\"\n\nPROGRAM_INFO(\"GMM\",\n \"This program takes a parametric estimate of a Gaussian mixture model (GMM)\"\n \" using the EM algorithm to find the maximum likelihood estimate.\", \"\");\n\nPARAM_STRING_REQ(\"data\", \"A file containing the data on which the model has to \"\n \"be fit.\", \"gmm\");\nPARAM_INT(\"gaussians\", \"g\", \"\", 1);\n\nusing namespace mlpack;\nusing namespace mlpack::gmm;\n\nint main(int argc, char* argv[]) {\n CLI::ParseCommandLine(argc, argv);\n\n \/\/\/\/\/\/ READING PARAMETERS AND LOADING DATA \/\/\/\/\/\/\n arma::mat data_points;\n data::Load(CLI::GetParam(\"gmm\/data\").c_str(), data_points, true);\n\n \/\/\/\/\/\/ MIXTURE OF GAUSSIANS USING EM \/\/\/\/\/\/\n GMM gmm(CLI::GetParam(\"gaussians\"), data_points.n_rows);\n\n \/\/\/\/\/\/ Computing the parameters of the model using the EM algorithm \/\/\/\/\/\/\n Timers::StartTimer(\"gmm\/em\");\n gmm.ExpectationMaximization(data_points);\n Timers::StopTimer(\"gmm\/em\");\n\n \/\/\/\/\/\/ OUTPUT RESULTS \/\/\/\/\/\/\n \/\/ We need a better solution for this. So, currently, we do nothing.\n \/\/ XML is probably the right tool for the job.\n}\n<|endoftext|>"} {"text":"#include \"EngineCommand.h\"\n\n#include \n#include \n#include \n\n#include \n\n#include \"SubCommand.h\"\n\n#define kLicenseFlag \"-lic\"\n#define kLicenseFlagLong \"-license\"\n#define kHoudiniVersionFlag \"-hv\"\n#define kHoudiniVersionFlagLong \"-houdiniVersion\"\n#define kHoudiniEngineVersionFlag \"-hev\"\n#define kHoudiniEngineVersionFlagLong \"-houdiniEngineVersion\"\n#define kSaveHIPFlag \"-sh\"\n#define kSaveHIPFlagLong \"-saveHIP\"\n\nconst char* EngineCommand::commandName = \"houdiniEngine\";\n\nclass EngineSubCommandLicense : public SubCommand\n{\n public:\n virtual MStatus doIt()\n {\n int license;\n\n HAPI_GetEnvInt(HAPI_ENVINT_LICENSE, &license);\n\n MString version_string;\n switch(license)\n {\n case HAPI_LICENSE_NONE:\n version_string = \"none\";\n break;\n case HAPI_LICENSE_HOUDINI_ENGINE:\n version_string = \"Houdini-Engine\";\n break;\n case HAPI_LICENSE_HOUDINI:\n version_string = \"Houdini-Escape\";\n break;\n case HAPI_LICENSE_HOUDINI_FX:\n version_string = \"Houdini-Master\";\n break;\n case HAPI_LICENSE_HOUDINI_ENGINE_INDIE:\n version_string = \"Houdini-Engine-Indie\";\n break;\n case HAPI_LICENSE_HOUDINI_INDIE:\n version_string = \"Houdini-Indie\";\n break;\n default:\n version_string = \"Unknown\";\n break;\n }\n\n MPxCommand::setResult(version_string);\n\n return MStatus::kSuccess;\n }\n};\n\nclass EngineSubCommandSaveHIPFile : public SubCommand\n{\n public:\n EngineSubCommandSaveHIPFile(const MString &hipFilePath) :\n myHIPFilePath(hipFilePath)\n {\n }\n\n virtual MStatus doIt()\n {\n HAPI_SaveHIPFile(myHIPFilePath.asChar());\n\n return MStatus::kSuccess;\n }\n\n protected:\n MString myHIPFilePath;\n};\n\nclass EngineSubCommandHoudiniVersion : public SubCommand\n{\n public:\n virtual MStatus doIt()\n {\n int major, minor, build;\n\n HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_MAJOR, &major);\n HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_MINOR, &minor);\n HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_BUILD, &build);\n\n MString version_string;\n version_string.format(\n \"^1s.^2s.^3s\",\n MString() + major,\n MString() + minor,\n MString() + build\n );\n\n MPxCommand::setResult(version_string);\n\n return MStatus::kSuccess;\n }\n};\n\nclass EngineSubCommandHoudiniEngineVersion : public SubCommand\n{\n public:\n virtual MStatus doIt()\n {\n int major, minor, api;\n\n HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MAJOR, &major);\n HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MINOR, &minor);\n HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_ENGINE_API, &api);\n\n MString version_string;\n version_string.format(\n \"^1s.^2s (API: ^3s)\",\n MString() + major,\n MString() + minor,\n MString() + api\n );\n\n MPxCommand::setResult(version_string);\n\n return MStatus::kSuccess;\n }\n};\n\nvoid* EngineCommand::creator()\n{\n return new EngineCommand();\n}\n\nMSyntax\nEngineCommand::newSyntax()\n{\n MSyntax syntax;\n\n \/\/ -license returns the Houdini version that's being used.\n CHECK_MSTATUS(syntax.addFlag(kLicenseFlag, kLicenseFlagLong));\n\n \/\/ -houdiniVersion returns the Houdini version that's being used.\n CHECK_MSTATUS(syntax.addFlag(kHoudiniVersionFlag, kHoudiniVersionFlagLong));\n\n \/\/ -houdiniEngineVersion returns the Houdini Engine version that's being\n \/\/ used.\n CHECK_MSTATUS(syntax.addFlag(kHoudiniEngineVersionFlag, kHoudiniEngineVersionFlagLong));\n\n \/\/ -saveHIP saves the contents of the current Houdini scene as a hip file\n \/\/ expected arguments: hip_file_name - the name of the hip file to save\n CHECK_MSTATUS(syntax.addFlag(kSaveHIPFlag, kSaveHIPFlagLong, MSyntax::kString));\n\n return syntax;\n}\n\nEngineCommand::EngineCommand() :\n mySubCommand(NULL)\n{\n}\n\nEngineCommand::~EngineCommand()\n{\n delete mySubCommand;\n}\n\nMStatus\nEngineCommand::parseArgs(const MArgList &args)\n{\n MStatus status;\n MArgDatabase argData(syntax(), args, &status);\n if(!status)\n {\n return status;\n }\n\n if(!(\n argData.isFlagSet(kLicenseFlag)\n ^ argData.isFlagSet(kHoudiniVersionFlag)\n ^ argData.isFlagSet(kHoudiniEngineVersionFlag)\n ^ argData.isFlagSet(kSaveHIPFlag)\n ))\n {\n displayError(\"Exactly one of these flags must be specified:\\n\"\n kSaveHIPFlagLong \"\\n\"\n );\n return MStatus::kInvalidParameter;\n }\n\n if(argData.isFlagSet(kLicenseFlag))\n {\n mySubCommand = new EngineSubCommandLicense();\n }\n\n if(argData.isFlagSet(kHoudiniVersionFlag))\n {\n mySubCommand = new EngineSubCommandHoudiniVersion();\n }\n\n if(argData.isFlagSet(kHoudiniEngineVersionFlag))\n {\n mySubCommand = new EngineSubCommandHoudiniEngineVersion();\n }\n\n if(argData.isFlagSet(kSaveHIPFlag))\n {\n MString hipFilePath;\n {\n status = argData.getFlagArgument(kSaveHIPFlag, 0, hipFilePath);\n if(!status)\n {\n displayError(\"Invalid argument for \\\"\" kSaveHIPFlagLong \"\\\".\");\n return status;\n }\n }\n\n mySubCommand = new EngineSubCommandSaveHIPFile(hipFilePath);\n }\n\n return MStatus::kSuccess;\n}\n\nMStatus EngineCommand::doIt(const MArgList& args)\n{\n MStatus status;\n\n status = parseArgs(args);\n if(!status)\n {\n return status;\n }\n\n return mySubCommand->doIt();\n}\n\nMStatus EngineCommand::redoIt()\n{\n return mySubCommand->redoIt();\n}\n\nMStatus EngineCommand::undoIt()\n{\n return mySubCommand->undoIt();\n}\n\nbool EngineCommand::isUndoable() const\n{\n return mySubCommand->isUndoable();\n}\nAdd flags to houdiniEngine command to output the build versions#include \"EngineCommand.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"SubCommand.h\"\n\n#define kLicenseFlag \"-lic\"\n#define kLicenseFlagLong \"-license\"\n#define kHoudiniVersionFlag \"-hv\"\n#define kHoudiniVersionFlagLong \"-houdiniVersion\"\n#define kHoudiniEngineVersionFlag \"-hev\"\n#define kHoudiniEngineVersionFlagLong \"-houdiniEngineVersion\"\n#define kBuildHoudiniVersionFlag \"-bhv\"\n#define kBuildHoudiniVersionFlagLong \"-buildHoudiniVersion\"\n#define kBuildHoudiniEngineVersionFlag \"-bev\"\n#define kBuildHoudiniEngineVersionFlagLong \"-buildHoudiniEngineVersion\"\n#define kSaveHIPFlag \"-sh\"\n#define kSaveHIPFlagLong \"-saveHIP\"\n\nconst char* EngineCommand::commandName = \"houdiniEngine\";\n\nclass EngineSubCommandLicense : public SubCommand\n{\n public:\n virtual MStatus doIt()\n {\n int license;\n\n HAPI_GetEnvInt(HAPI_ENVINT_LICENSE, &license);\n\n MString version_string;\n switch(license)\n {\n case HAPI_LICENSE_NONE:\n version_string = \"none\";\n break;\n case HAPI_LICENSE_HOUDINI_ENGINE:\n version_string = \"Houdini-Engine\";\n break;\n case HAPI_LICENSE_HOUDINI:\n version_string = \"Houdini-Escape\";\n break;\n case HAPI_LICENSE_HOUDINI_FX:\n version_string = \"Houdini-Master\";\n break;\n case HAPI_LICENSE_HOUDINI_ENGINE_INDIE:\n version_string = \"Houdini-Engine-Indie\";\n break;\n case HAPI_LICENSE_HOUDINI_INDIE:\n version_string = \"Houdini-Indie\";\n break;\n default:\n version_string = \"Unknown\";\n break;\n }\n\n MPxCommand::setResult(version_string);\n\n return MStatus::kSuccess;\n }\n};\n\nclass EngineSubCommandSaveHIPFile : public SubCommand\n{\n public:\n EngineSubCommandSaveHIPFile(const MString &hipFilePath) :\n myHIPFilePath(hipFilePath)\n {\n }\n\n virtual MStatus doIt()\n {\n HAPI_SaveHIPFile(myHIPFilePath.asChar());\n\n return MStatus::kSuccess;\n }\n\n protected:\n MString myHIPFilePath;\n};\n\nclass EngineSubCommandHoudiniVersion : public SubCommand\n{\n public:\n virtual MStatus doIt()\n {\n int major, minor, build;\n\n HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_MAJOR, &major);\n HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_MINOR, &minor);\n HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_BUILD, &build);\n\n MString version_string;\n version_string.format(\n \"^1s.^2s.^3s\",\n MString() + major,\n MString() + minor,\n MString() + build\n );\n\n MPxCommand::setResult(version_string);\n\n return MStatus::kSuccess;\n }\n};\n\nclass EngineSubCommandHoudiniEngineVersion : public SubCommand\n{\n public:\n virtual MStatus doIt()\n {\n int major, minor, api;\n\n HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MAJOR, &major);\n HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MINOR, &minor);\n HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_ENGINE_API, &api);\n\n MString version_string;\n version_string.format(\n \"^1s.^2s (API: ^3s)\",\n MString() + major,\n MString() + minor,\n MString() + api\n );\n\n MPxCommand::setResult(version_string);\n\n return MStatus::kSuccess;\n }\n};\n\nclass EngineSubCommandBuildHoudiniVersion : public SubCommand\n{\n public:\n virtual MStatus doIt()\n {\n int major = HAPI_VERSION_HOUDINI_MAJOR;\n int minor = HAPI_VERSION_HOUDINI_MINOR;\n int build = HAPI_VERSION_HOUDINI_BUILD;\n\n MString version_string;\n version_string.format(\n \"^1s.^2s.^3s\",\n MString() + major,\n MString() + minor,\n MString() + build\n );\n\n MPxCommand::setResult(version_string);\n\n return MStatus::kSuccess;\n }\n};\n\nclass EngineSubCommandBuildHoudiniEngineVersion : public SubCommand\n{\n public:\n virtual MStatus doIt()\n {\n int major = HAPI_VERSION_HOUDINI_ENGINE_MAJOR;\n int minor = HAPI_VERSION_HOUDINI_ENGINE_MINOR;\n int api = HAPI_VERSION_HOUDINI_ENGINE_API;\n\n MString version_string;\n version_string.format(\n \"^1s.^2s (API: ^3s)\",\n MString() + major,\n MString() + minor,\n MString() + api\n );\n\n MPxCommand::setResult(version_string);\n\n return MStatus::kSuccess;\n }\n};\n\nvoid* EngineCommand::creator()\n{\n return new EngineCommand();\n}\n\nMSyntax\nEngineCommand::newSyntax()\n{\n MSyntax syntax;\n\n \/\/ -license returns the Houdini version that's being used.\n CHECK_MSTATUS(syntax.addFlag(kLicenseFlag, kLicenseFlagLong));\n\n \/\/ -houdiniVersion returns the Houdini version that's being used.\n CHECK_MSTATUS(syntax.addFlag(kHoudiniVersionFlag, kHoudiniVersionFlagLong));\n\n \/\/ -houdiniEngineVersion returns the Houdini Engine version that's being\n \/\/ used.\n CHECK_MSTATUS(syntax.addFlag(kHoudiniEngineVersionFlag, kHoudiniEngineVersionFlagLong));\n\n \/\/ -buildHoudiniVersion returns the Houdini version that was built with.\n CHECK_MSTATUS(syntax.addFlag(\n kBuildHoudiniVersionFlag,\n kBuildHoudiniVersionFlagLong\n ));\n\n \/\/ -buildHoudiniEngineVersion returns the Houdini Engine version that was\n \/\/ built with.\n CHECK_MSTATUS(syntax.addFlag(\n kBuildHoudiniEngineVersionFlag,\n kBuildHoudiniEngineVersionFlagLong\n ));\n\n \/\/ -saveHIP saves the contents of the current Houdini scene as a hip file\n \/\/ expected arguments: hip_file_name - the name of the hip file to save\n CHECK_MSTATUS(syntax.addFlag(kSaveHIPFlag, kSaveHIPFlagLong, MSyntax::kString));\n\n return syntax;\n}\n\nEngineCommand::EngineCommand() :\n mySubCommand(NULL)\n{\n}\n\nEngineCommand::~EngineCommand()\n{\n delete mySubCommand;\n}\n\nMStatus\nEngineCommand::parseArgs(const MArgList &args)\n{\n MStatus status;\n MArgDatabase argData(syntax(), args, &status);\n if(!status)\n {\n return status;\n }\n\n if(!(\n argData.isFlagSet(kLicenseFlag)\n ^ argData.isFlagSet(kHoudiniVersionFlag)\n ^ argData.isFlagSet(kHoudiniEngineVersionFlag)\n ^ argData.isFlagSet(kBuildHoudiniVersionFlag)\n ^ argData.isFlagSet(kBuildHoudiniEngineVersionFlag)\n ^ argData.isFlagSet(kSaveHIPFlag)\n ))\n {\n displayError(\"Exactly one of these flags must be specified:\\n\"\n kSaveHIPFlagLong \"\\n\"\n );\n return MStatus::kInvalidParameter;\n }\n\n if(argData.isFlagSet(kLicenseFlag))\n {\n mySubCommand = new EngineSubCommandLicense();\n }\n\n if(argData.isFlagSet(kHoudiniVersionFlag))\n {\n mySubCommand = new EngineSubCommandHoudiniVersion();\n }\n\n if(argData.isFlagSet(kHoudiniEngineVersionFlag))\n {\n mySubCommand = new EngineSubCommandHoudiniEngineVersion();\n }\n\n if(argData.isFlagSet(kBuildHoudiniVersionFlag))\n {\n mySubCommand = new EngineSubCommandBuildHoudiniVersion();\n }\n\n if(argData.isFlagSet(kBuildHoudiniEngineVersionFlag))\n {\n mySubCommand = new EngineSubCommandBuildHoudiniEngineVersion();\n }\n\n if(argData.isFlagSet(kSaveHIPFlag))\n {\n MString hipFilePath;\n {\n status = argData.getFlagArgument(kSaveHIPFlag, 0, hipFilePath);\n if(!status)\n {\n displayError(\"Invalid argument for \\\"\" kSaveHIPFlagLong \"\\\".\");\n return status;\n }\n }\n\n mySubCommand = new EngineSubCommandSaveHIPFile(hipFilePath);\n }\n\n return MStatus::kSuccess;\n}\n\nMStatus EngineCommand::doIt(const MArgList& args)\n{\n MStatus status;\n\n status = parseArgs(args);\n if(!status)\n {\n return status;\n }\n\n return mySubCommand->doIt();\n}\n\nMStatus EngineCommand::redoIt()\n{\n return mySubCommand->redoIt();\n}\n\nMStatus EngineCommand::undoIt()\n{\n return mySubCommand->undoIt();\n}\n\nbool EngineCommand::isUndoable() const\n{\n return mySubCommand->isUndoable();\n}\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ Provide BZFS with a list server connection\n\n\/* class header *\/\n#include \"ListServerConnection.h\"\n\n\/* system implementation headers *\/\n#include \n#include \n#include \n#include \n\n\/* common implementation headers *\/\n#include \"bzfio.h\"\n#include \"version.h\"\n#include \"TextUtils.h\"\n#include \"Protocol.h\"\n#include \"GameKeeper.h\"\n\n\/* local implementation headers *\/\n#include \"CmdLineOptions.h\"\n\n\/\/ FIXME remove externs!\nextern PingPacket getTeamCounts();\nextern uint16_t curMaxPlayers;\nextern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message);\nextern void sendPlayerInfo(void);\nextern void sendIPUpdate(int targetPlayer, int playerIndex);\nextern CmdLineOptions *clOptions;\n\nconst int ListServerLink::NotConnected = -1;\n\nListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)\n{\n \/\/ parse url\n std::string protocol, _hostname, _pathname;\n int _port = 80;\n bool useDefault = false;\n\n \/\/ use default if it can't be parsed\n if (!BzfNetwork::parseURL(listServerURL, protocol, _hostname, _port,\n\t\t\t _pathname))\n useDefault = true;\n\n \/\/ use default if wrong protocol or invalid port\n if ((protocol != \"http\") || (_port < 1) || (_port > 65535))\n useDefault = true;\n\n \/\/ use default if bad address\n Address _address = Address::getHostAddress(_hostname);\n if (_address.isAny())\n useDefault = true;\n\n \/\/ parse default list server URL if we need to; assume default works\n if (useDefault) {\n BzfNetwork::parseURL(DefaultListServerURL, protocol, _hostname, _port,\n\t\t\t _pathname);\n DEBUG1(\"Provided list server URL (%s) is invalid. Using default of %s.\\n\", listServerURL.c_str(), DefaultListServerURL);\n }\n\n \/\/ add to list\n address = _address;\n port = _port;\n pathname = _pathname;\n hostname = _hostname;\n this->linkSocket = NotConnected;\n\n if (clOptions->pingInterface != \"\")\n this->localAddress\t = Address::getHostAddress(clOptions->pingInterface);\n this->publicizeAddress = publicizedAddress;\n this->publicizeDescription = publicizedTitle;\n this->publicizeServer\t = true; \/\/if this c'tor is called, it's safe to publicize\n \n \/\/ schedule initial ADD message\n queueMessage(ListServerLink::ADD);\n}\n\nListServerLink::ListServerLink()\n{\n \/\/ does not create a usable link, so checks should be placed\n \/\/ in all public member functions to ensure that nothing tries\n \/\/ to happen if publicizeServer is false\n this->linkSocket = NotConnected;\n this->publicizeServer = false;\n}\n\nListServerLink::~ListServerLink()\n{\n \/\/ now tell the list server that we're going away. this can\n \/\/ take some time but we don't want to wait too long. we do\n \/\/ our own multiplexing loop and wait for a maximum of 3 seconds\n \/\/ total.\n\n \/\/ if we aren't supposed to be publicizing, skip the whole thing\n \/\/ and don't waste 3 seconds.\n if (!publicizeServer)\n return;\n\n queueMessage(ListServerLink::REMOVE);\n TimeKeeper start = TimeKeeper::getCurrent();\n do {\n \/\/ compute timeout\n float waitTime = float(3.0 - (TimeKeeper::getCurrent() - start));\n if (waitTime <= 0.0f)\n break;\n if (!isConnected()) \/\/queueMessage should have connected us\n break;\n \/\/ check for list server socket connection\n int fdMax = -1;\n fd_set write_set;\n fd_set read_set;\n FD_ZERO(&write_set);\n FD_ZERO(&read_set);\n if (phase == ListServerLink::CONNECTING) {\n FD_SET((unsigned int)linkSocket, &write_set);\n } else {\n FD_SET((unsigned int)linkSocket, &read_set);\n }\n fdMax = linkSocket;\n\n \/\/ wait for socket to connect or timeout\n struct timeval timeout;\n timeout.tv_sec = long(floorf(waitTime));\n timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));\n int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,\n\t\t\t0, &timeout);\n if (nfound == 0)\n \/\/ Time has gone, close and go\n break;\n \/\/ check for connection to list server\n if (FD_ISSET(linkSocket, &write_set))\n sendQueuedMessages();\n else if (FD_ISSET(linkSocket, &read_set))\n read();\n } while (true);\n\n \/\/ stop list server communication\n closeLink();\n}\n\nvoid ListServerLink::closeLink()\n{\n if (isConnected()) {\n close(linkSocket);\n DEBUG4(\"Closing List Server\\n\");\n linkSocket = NotConnected;\n }\n}\n\nvoid ListServerLink::read()\n{\n if (isConnected()) {\n char buf[2048];\n int bytes = recv(linkSocket, buf, sizeof(buf)-1, 0);\n \/\/ TODO don't close unless we've got it all\n closeLink();\n buf[bytes]=0;\n char* base = buf;\n static char *tokGoodIdentifier = \"TOKGOOD: \";\n static char *tokBadIdentifier = \"TOKBAD: \";\n \/\/ walks entire reply including HTTP headers\n while (*base) {\n \/\/ find next newline\n char* scan = base;\n while (*scan && *scan != '\\r' && *scan != '\\n') scan++;\n \/\/ if no newline then no more complete replies\n if (*scan != '\\r' && *scan != '\\n') break;\n while (*scan && (*scan == '\\r' || *scan == '\\n')) *scan++ = '\\0';\n DEBUG4(\"Got line: \\\"%s\\\"\\n\", base);\n \/\/ TODO don't do this if we don't want central logins\n if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) {\n\tchar *callsign, *group;\n\tcallsign = base + strlen(tokGoodIdentifier);\n\tDEBUG3(\"Got: %s\\n\", base);\n\tgroup = callsign;\n\twhile (*group && (*group != ':')) group++;\n\twhile (*group && (*group == ':')) *group++ = 0;\n\tint playerIndex = GameKeeper::Player::getPlayerIDByName(callsign);\n\tif (playerIndex < curMaxPlayers) {\n\t GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex);\n\t if (playerData != NULL) {\n\t \/\/ don't accept the global auth if there's a local account of the same name\n\t \/\/ and the local account is not marked as being the same as the global account\n\t if (!playerData->accessInfo.hasRealPassword()\n\t\t|| playerData->accessInfo.getUserInfo(callsign).hasGroup(\"LOCAL.GLOBAL\")) {\n\t if (!playerData->accessInfo.isRegistered())\n\t\tplayerData->accessInfo.storeInfo(NULL);\n\t playerData->accessInfo.setPermissionRights();\n\t while (*group) {\n\t\tchar *nextgroup = group;\n\t\twhile (*nextgroup && (*nextgroup != ':')) nextgroup++;\n\t\twhile (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0;\n\t\tplayerData->accessInfo.addGroup(group);\n\t\t\/\/DEBUG3(\"Got: [%d] \\\"%s\\\" \\\"%s\\\"\\n\", playerIndex, callsign, group);\n\t\tgroup = nextgroup;\n\t }\n\t\t playerData->authentication.global(true);\n\t sendMessage(ServerPlayer, playerIndex, \"Global login approved!\");\n\t sendIPUpdate(playerIndex, -1);\n\t sendPlayerInfo();\n\t } else {\n\t sendMessage(ServerPlayer, playerIndex, \"Global login rejected. \"\n\t\t\t \"This callsign is registered locally on this server.\");\n\t sendMessage(ServerPlayer, playerIndex, \"If the local account is yours, \"\n\t\t\t \"\/identify, \/deregister and reconnnect, \"\n\t\t\t \"or ask an admin for the LOCAL.GLOBAL group.\");\n\t sendMessage(ServerPlayer, playerIndex, \"If it is not yours, please ask an admin \"\n\t\t\t \"to deregister it so that you may use your global callsign.\");\n\t }\n\t playerData->setNeedThisHostbanChecked(true);\n\t playerData->player.clearToken();\n\t }\n\t}\n } else if (strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier)) == 0) {\n\tchar *callsign;\n\tcallsign = base + strlen(tokBadIdentifier);\n\tint playerIndex = GameKeeper::Player::getPlayerIDByName(callsign);\n\tDEBUG3(\"Got: [%d] %s\\n\", playerIndex, base);\n\tif (playerIndex < curMaxPlayers) {\n\t GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex);\n\t sendMessage(ServerPlayer, playerIndex, \"Global login rejected, bad token.\");\n\t if (playerData != NULL) {\n\t playerData->setNeedThisHostbanChecked(true);\n\t playerData->player.clearToken();\n\t }\n\t}\n }\n\n \/\/ next reply\n base = scan;\n }\n if (nextMessageType != ListServerLink::NONE) {\n \/\/ There was a pending request arrived after we write:\n \/\/ we should redo all the stuff\n openLink();\n }\n }\n}\n\nvoid ListServerLink::openLink()\n{\n \/\/ start opening connection if not already doing so\n if (!isConnected()) {\n linkSocket = socket(AF_INET, SOCK_STREAM, 0);\n DEBUG4(\"Opening List Server\\n\");\n if (!isConnected()) {\n return;\n }\n\n \/\/ set to non-blocking for connect\n if (BzfNetwork::setNonBlocking(linkSocket) < 0) {\n closeLink();\n return;\n }\n\n \/\/ Make our connection come from our serverAddress in case we have\n \/\/ multiple\/masked IPs so the list server can verify us.\n struct sockaddr_in addr;\n memset(&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_addr = localAddress;\n\n \/\/ assign the address to the socket\n if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {\n closeLink();\n return;\n }\n\n \/\/ connect. this should fail with EINPROGRESS but check for\n \/\/ success just in case.\n memset(&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_port = htons(port);\n addr.sin_addr = address;\n if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {\n#if defined(_WIN32)\n#undef EINPROGRESS\n#define EINPROGRESS EWOULDBLOCK\n#endif\n if (getErrno() != EINPROGRESS) {\n\tnerror(\"connecting to list server\");\n\t\/\/ try to lookup dns name again in case it moved\n\tthis->address = Address::getHostAddress(this->hostname);\n\tcloseLink();\n } else {\n\tphase = CONNECTING;\n }\n } else {\n \/\/ shouldn't arrive here. Just in case, clean\n DEBUG3(\"list server connect and close?\\n\");\n closeLink();\n }\n }\n}\n\nvoid ListServerLink::queueMessage(MessageType type)\n{\n \/\/ ignore if the server is not public\n if (!publicizeServer) return;\n\n \/\/ Open network connection only if closed\n if (!isConnected()) openLink();\n\n \/\/ record next message to send.\n nextMessageType = type;\n}\n\nvoid ListServerLink::sendQueuedMessages()\n{\n if (!isConnected())\n return;\n\n if (nextMessageType == ListServerLink::ADD) {\n DEBUG3(\"Queuing ADD message to list server\\n\");\n addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription));\n lastAddTime = TimeKeeper::getCurrent();\n } else if (nextMessageType == ListServerLink::REMOVE) {\n DEBUG3(\"Queuing REMOVE message to list server\\n\");\n removeMe(publicizeAddress);\n }\n}\n\nvoid ListServerLink::addMe(PingPacket pingInfo,\n\t\t\t std::string publicizedAddress,\n\t\t\t std::string publicizedTitle)\n{\n std::string msg;\n\n \/\/ encode ping reply as ascii hex digits plus NULL\n char gameInfo[PingPacketHexPackedSize + 1];\n pingInfo.packHex(gameInfo);\n\n \/\/ TODO we probably should convert to a POST. List server now allows either\n \/\/ send ADD message (must send blank line)\n msg = TextUtils::format(\"GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s\",\n pathname.c_str(), publicizedAddress.c_str(),\n getServerVersion(), gameInfo,\n getAppVersion());\n msg += \"&checktokens=\";\n \/\/ callsign1@ip1=token1%0D%0Acallsign2@ip2=token2%0D%0A\n for (int i = 0; i < curMaxPlayers; i++) {\n GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i);\n if (!playerData)\n continue;\n NetHandler *handler = playerData->netHandler;\n std::string encodedCallsign = TextUtils::url_encode(playerData->player.getCallSign());\n if (strlen(playerData->player.getCallSign()) && strlen(playerData->player.getToken())) {\n msg += encodedCallsign;\n Address addr = handler->getIPAddress();\n if (!addr.isPrivate()) {\n\tmsg += \"@\";\n\tmsg += handler->getTargetIP();\n }\n msg += \"=\";\n msg += playerData->player.getToken();\n msg += \"%0D%0A\";\n }\n }\n \/\/ *groups=GROUP0%0D%0AGROUP1%0D%0A\n msg += \"&groups=\";\n PlayerAccessMap::iterator itr = groupAccess.begin();\n for ( ; itr != groupAccess.end(); itr++) {\n if (itr->first.substr(0, 6) != \"LOCAL.\") {\n msg += itr->first.c_str();\n msg += \"%0D%0A\";\n }\n }\n\n msg += TextUtils::format(\"&title=%s HTTP\/1.1\\r\\n\"\n \"User-Agent: bzfs %s\\r\\n\"\n \"Host: %s\\r\\n\"\n \"Cache-Control: no-cache\\r\\n\"\n \"Connection: close\\r\\n\"\n \"\\r\\n\",\n publicizedTitle.c_str(),\n getAppVersion(),\n hostname.c_str());\n sendLSMessage(msg);\n}\n\nvoid ListServerLink::removeMe(std::string publicizedAddress)\n{\n std::string msg;\n \/\/ send REMOVE (must send blank line)\n msg = TextUtils::format(\"GET %s?action=REMOVE&nameport=%s HTTP\/1.1\\r\\n\"\n \"User-Agent: bzfs %s\\r\\n\"\n \"Host: %s\\r\\n\"\n \"Cache-Control: no-cache\\r\\n\"\n \"Connection: close\\r\\n\"\n \"\\r\\n\",\n pathname.c_str(),\n publicizedAddress.c_str(),\n getAppVersion(),\n hostname.c_str());\n sendLSMessage(msg);\n}\n\nvoid ListServerLink::sendLSMessage(std::string message)\n{\n const int bufsize = 4096;\n char msg[bufsize];\n strncpy(msg, message.c_str(), bufsize);\n msg[bufsize - 1] = 0;\n if (strlen(msg) > 0) {\n DEBUG3(\"%s\\n\", msg);\n if (send(linkSocket, msg, strlen(msg), 0) == -1) {\n perror(\"List server send failed\");\n DEBUG3(\"Unable to send to the list server!\\n\");\n closeLink();\n } else {\n nextMessageType = ListServerLink::NONE;\n phase\t = ListServerLink::WRITTEN;\n }\n } else {\n closeLink();\n }\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\nChange list server request methods from 'GET' to 'POST (libcurl NOT used).\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ Provide BZFS with a list server connection\n\n\/* class header *\/\n#include \"ListServerConnection.h\"\n\n\/* system implementation headers *\/\n#include \n#include \n#include \n#include \n\n\/* common implementation headers *\/\n#include \"bzfio.h\"\n#include \"version.h\"\n#include \"TextUtils.h\"\n#include \"Protocol.h\"\n#include \"GameKeeper.h\"\n\n\/* local implementation headers *\/\n#include \"CmdLineOptions.h\"\n\n\/\/ FIXME remove externs!\nextern PingPacket getTeamCounts();\nextern uint16_t curMaxPlayers;\nextern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message);\nextern void sendPlayerInfo(void);\nextern void sendIPUpdate(int targetPlayer, int playerIndex);\nextern CmdLineOptions *clOptions;\n\nconst int ListServerLink::NotConnected = -1;\n\nListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)\n{\n \/\/ parse url\n std::string protocol, _hostname, _pathname;\n int _port = 80;\n bool useDefault = false;\n\n \/\/ use default if it can't be parsed\n if (!BzfNetwork::parseURL(listServerURL, protocol, _hostname, _port,\n\t\t\t _pathname))\n useDefault = true;\n\n \/\/ use default if wrong protocol or invalid port\n if ((protocol != \"http\") || (_port < 1) || (_port > 65535))\n useDefault = true;\n\n \/\/ use default if bad address\n Address _address = Address::getHostAddress(_hostname);\n if (_address.isAny())\n useDefault = true;\n\n \/\/ parse default list server URL if we need to; assume default works\n if (useDefault) {\n BzfNetwork::parseURL(DefaultListServerURL, protocol, _hostname, _port,\n\t\t\t _pathname);\n DEBUG1(\"Provided list server URL (%s) is invalid. Using default of %s.\\n\", listServerURL.c_str(), DefaultListServerURL);\n }\n\n \/\/ add to list\n address = _address;\n port = _port;\n pathname = _pathname;\n hostname = _hostname;\n this->linkSocket = NotConnected;\n\n if (clOptions->pingInterface != \"\")\n this->localAddress\t = Address::getHostAddress(clOptions->pingInterface);\n this->publicizeAddress = publicizedAddress;\n this->publicizeDescription = publicizedTitle;\n this->publicizeServer\t = true; \/\/if this c'tor is called, it's safe to publicize\n \n \/\/ schedule initial ADD message\n queueMessage(ListServerLink::ADD);\n}\n\nListServerLink::ListServerLink()\n{\n \/\/ does not create a usable link, so checks should be placed\n \/\/ in all public member functions to ensure that nothing tries\n \/\/ to happen if publicizeServer is false\n this->linkSocket = NotConnected;\n this->publicizeServer = false;\n}\n\nListServerLink::~ListServerLink()\n{\n \/\/ now tell the list server that we're going away. this can\n \/\/ take some time but we don't want to wait too long. we do\n \/\/ our own multiplexing loop and wait for a maximum of 3 seconds\n \/\/ total.\n\n \/\/ if we aren't supposed to be publicizing, skip the whole thing\n \/\/ and don't waste 3 seconds.\n if (!publicizeServer)\n return;\n\n queueMessage(ListServerLink::REMOVE);\n TimeKeeper start = TimeKeeper::getCurrent();\n do {\n \/\/ compute timeout\n float waitTime = float(3.0 - (TimeKeeper::getCurrent() - start));\n if (waitTime <= 0.0f)\n break;\n if (!isConnected()) \/\/queueMessage should have connected us\n break;\n \/\/ check for list server socket connection\n int fdMax = -1;\n fd_set write_set;\n fd_set read_set;\n FD_ZERO(&write_set);\n FD_ZERO(&read_set);\n if (phase == ListServerLink::CONNECTING) {\n FD_SET((unsigned int)linkSocket, &write_set);\n } else {\n FD_SET((unsigned int)linkSocket, &read_set);\n }\n fdMax = linkSocket;\n\n \/\/ wait for socket to connect or timeout\n struct timeval timeout;\n timeout.tv_sec = long(floorf(waitTime));\n timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));\n int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,\n\t\t\t0, &timeout);\n if (nfound == 0)\n \/\/ Time has gone, close and go\n break;\n \/\/ check for connection to list server\n if (FD_ISSET(linkSocket, &write_set))\n sendQueuedMessages();\n else if (FD_ISSET(linkSocket, &read_set))\n read();\n } while (true);\n\n \/\/ stop list server communication\n closeLink();\n}\n\nvoid ListServerLink::closeLink()\n{\n if (isConnected()) {\n close(linkSocket);\n DEBUG4(\"Closing List Server\\n\");\n linkSocket = NotConnected;\n }\n}\n\nvoid ListServerLink::read()\n{\n if (isConnected()) {\n char buf[2048];\n int bytes = recv(linkSocket, buf, sizeof(buf)-1, 0);\n \/\/ TODO don't close unless we've got it all\n closeLink();\n buf[bytes]=0;\n char* base = buf;\n static char *tokGoodIdentifier = \"TOKGOOD: \";\n static char *tokBadIdentifier = \"TOKBAD: \";\n \/\/ walks entire reply including HTTP headers\n while (*base) {\n \/\/ find next newline\n char* scan = base;\n while (*scan && *scan != '\\r' && *scan != '\\n') scan++;\n \/\/ if no newline then no more complete replies\n if (*scan != '\\r' && *scan != '\\n') break;\n while (*scan && (*scan == '\\r' || *scan == '\\n')) *scan++ = '\\0';\n DEBUG4(\"Got line: \\\"%s\\\"\\n\", base);\n \/\/ TODO don't do this if we don't want central logins\n if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) {\n\tchar *callsign, *group;\n\tcallsign = base + strlen(tokGoodIdentifier);\n\tDEBUG3(\"Got: %s\\n\", base);\n\tgroup = callsign;\n\twhile (*group && (*group != ':')) group++;\n\twhile (*group && (*group == ':')) *group++ = 0;\n\tint playerIndex = GameKeeper::Player::getPlayerIDByName(callsign);\n\tif (playerIndex < curMaxPlayers) {\n\t GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex);\n\t if (playerData != NULL) {\n\t \/\/ don't accept the global auth if there's a local account of the same name\n\t \/\/ and the local account is not marked as being the same as the global account\n\t if (!playerData->accessInfo.hasRealPassword()\n\t\t|| playerData->accessInfo.getUserInfo(callsign).hasGroup(\"LOCAL.GLOBAL\")) {\n\t if (!playerData->accessInfo.isRegistered())\n\t\tplayerData->accessInfo.storeInfo(NULL);\n\t playerData->accessInfo.setPermissionRights();\n\t while (*group) {\n\t\tchar *nextgroup = group;\n\t\twhile (*nextgroup && (*nextgroup != ':')) nextgroup++;\n\t\twhile (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0;\n\t\tplayerData->accessInfo.addGroup(group);\n\t\t\/\/DEBUG3(\"Got: [%d] \\\"%s\\\" \\\"%s\\\"\\n\", playerIndex, callsign, group);\n\t\tgroup = nextgroup;\n\t }\n\t\t playerData->authentication.global(true);\n\t sendMessage(ServerPlayer, playerIndex, \"Global login approved!\");\n\t sendIPUpdate(playerIndex, -1);\n\t sendPlayerInfo();\n\t } else {\n\t sendMessage(ServerPlayer, playerIndex, \"Global login rejected. \"\n\t\t\t \"This callsign is registered locally on this server.\");\n\t sendMessage(ServerPlayer, playerIndex, \"If the local account is yours, \"\n\t\t\t \"\/identify, \/deregister and reconnnect, \"\n\t\t\t \"or ask an admin for the LOCAL.GLOBAL group.\");\n\t sendMessage(ServerPlayer, playerIndex, \"If it is not yours, please ask an admin \"\n\t\t\t \"to deregister it so that you may use your global callsign.\");\n\t }\n\t playerData->setNeedThisHostbanChecked(true);\n\t playerData->player.clearToken();\n\t }\n\t}\n } else if (strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier)) == 0) {\n\tchar *callsign;\n\tcallsign = base + strlen(tokBadIdentifier);\n\tint playerIndex = GameKeeper::Player::getPlayerIDByName(callsign);\n\tDEBUG3(\"Got: [%d] %s\\n\", playerIndex, base);\n\tif (playerIndex < curMaxPlayers) {\n\t GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex);\n\t sendMessage(ServerPlayer, playerIndex, \"Global login rejected, bad token.\");\n\t if (playerData != NULL) {\n\t playerData->setNeedThisHostbanChecked(true);\n\t playerData->player.clearToken();\n\t }\n\t}\n }\n\n \/\/ next reply\n base = scan;\n }\n if (nextMessageType != ListServerLink::NONE) {\n \/\/ There was a pending request arrived after we write:\n \/\/ we should redo all the stuff\n openLink();\n }\n }\n}\n\nvoid ListServerLink::openLink()\n{\n \/\/ start opening connection if not already doing so\n if (!isConnected()) {\n linkSocket = socket(AF_INET, SOCK_STREAM, 0);\n DEBUG4(\"Opening List Server\\n\");\n if (!isConnected()) {\n return;\n }\n\n \/\/ set to non-blocking for connect\n if (BzfNetwork::setNonBlocking(linkSocket) < 0) {\n closeLink();\n return;\n }\n\n \/\/ Make our connection come from our serverAddress in case we have\n \/\/ multiple\/masked IPs so the list server can verify us.\n struct sockaddr_in addr;\n memset(&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_addr = localAddress;\n\n \/\/ assign the address to the socket\n if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {\n closeLink();\n return;\n }\n\n \/\/ connect. this should fail with EINPROGRESS but check for\n \/\/ success just in case.\n memset(&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_port = htons(port);\n addr.sin_addr = address;\n if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {\n#if defined(_WIN32)\n#undef EINPROGRESS\n#define EINPROGRESS EWOULDBLOCK\n#endif\n if (getErrno() != EINPROGRESS) {\n\tnerror(\"connecting to list server\");\n\t\/\/ try to lookup dns name again in case it moved\n\tthis->address = Address::getHostAddress(this->hostname);\n\tcloseLink();\n } else {\n\tphase = CONNECTING;\n }\n } else {\n \/\/ shouldn't arrive here. Just in case, clean\n DEBUG3(\"list server connect and close?\\n\");\n closeLink();\n }\n }\n}\n\nvoid ListServerLink::queueMessage(MessageType type)\n{\n \/\/ ignore if the server is not public\n if (!publicizeServer) return;\n\n \/\/ Open network connection only if closed\n if (!isConnected()) openLink();\n\n \/\/ record next message to send.\n nextMessageType = type;\n}\n\nvoid ListServerLink::sendQueuedMessages()\n{\n if (!isConnected())\n return;\n\n if (nextMessageType == ListServerLink::ADD) {\n DEBUG3(\"Queuing ADD message to list server\\n\");\n addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription));\n lastAddTime = TimeKeeper::getCurrent();\n } else if (nextMessageType == ListServerLink::REMOVE) {\n DEBUG3(\"Queuing REMOVE message to list server\\n\");\n removeMe(publicizeAddress);\n }\n}\n\nvoid ListServerLink::addMe(PingPacket pingInfo,\n\t\t\t std::string publicizedAddress,\n\t\t\t std::string publicizedTitle)\n{\n std::string msg;\n\n \/\/ encode ping reply as ascii hex digits plus NULL\n char gameInfo[PingPacketHexPackedSize + 1];\n pingInfo.packHex(gameInfo);\n\n \/\/ TODO we probably should convert to a POST. List server now allows either\n \/\/ send ADD message (must send blank line)\n msg = TextUtils::format(\"POST %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s\",\n pathname.c_str(), publicizedAddress.c_str(),\n getServerVersion(), gameInfo,\n getAppVersion());\n msg += \"&checktokens=\";\n \/\/ callsign1@ip1=token1%0D%0Acallsign2@ip2=token2%0D%0A\n for (int i = 0; i < curMaxPlayers; i++) {\n GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i);\n if (!playerData)\n continue;\n NetHandler *handler = playerData->netHandler;\n std::string encodedCallsign = TextUtils::url_encode(playerData->player.getCallSign());\n if (strlen(playerData->player.getCallSign()) && strlen(playerData->player.getToken())) {\n msg += encodedCallsign;\n Address addr = handler->getIPAddress();\n if (!addr.isPrivate()) {\n\tmsg += \"@\";\n\tmsg += handler->getTargetIP();\n }\n msg += \"=\";\n msg += playerData->player.getToken();\n msg += \"%0D%0A\";\n }\n }\n \/\/ *groups=GROUP0%0D%0AGROUP1%0D%0A\n msg += \"&groups=\";\n PlayerAccessMap::iterator itr = groupAccess.begin();\n for ( ; itr != groupAccess.end(); itr++) {\n if (itr->first.substr(0, 6) != \"LOCAL.\") {\n msg += itr->first.c_str();\n msg += \"%0D%0A\";\n }\n }\n\n msg += TextUtils::format(\"&title=%s HTTP\/1.1\\r\\n\"\n \"User-Agent: bzfs %s\\r\\n\"\n \"Host: %s\\r\\n\"\n \"Cache-Control: no-cache\\r\\n\"\n \"Connection: close\\r\\n\"\n \"\\r\\n\",\n publicizedTitle.c_str(),\n getAppVersion(),\n hostname.c_str());\n sendLSMessage(msg);\n}\n\nvoid ListServerLink::removeMe(std::string publicizedAddress)\n{\n std::string msg;\n \/\/ send REMOVE (must send blank line)\n msg = TextUtils::format(\"POST %s?action=REMOVE&nameport=%s HTTP\/1.1\\r\\n\"\n \"User-Agent: bzfs %s\\r\\n\"\n \"Host: %s\\r\\n\"\n \"Cache-Control: no-cache\\r\\n\"\n \"Connection: close\\r\\n\"\n \"\\r\\n\",\n pathname.c_str(),\n publicizedAddress.c_str(),\n getAppVersion(),\n hostname.c_str());\n sendLSMessage(msg);\n}\n\nvoid ListServerLink::sendLSMessage(std::string message)\n{\n const int bufsize = 4096;\n char msg[bufsize];\n strncpy(msg, message.c_str(), bufsize);\n msg[bufsize - 1] = 0;\n if (strlen(msg) > 0) {\n DEBUG3(\"%s\\n\", msg);\n if (send(linkSocket, msg, strlen(msg), 0) == -1) {\n perror(\"List server send failed\");\n DEBUG3(\"Unable to send to the list server!\\n\");\n closeLink();\n } else {\n nextMessageType = ListServerLink::NONE;\n phase\t = ListServerLink::WRITTEN;\n }\n } else {\n closeLink();\n }\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"\/\/ StdLib.cpp\n\/\/ This file is part of the EScript programming language.\n\/\/ See copyright notice in EScript.h\n\/\/ ------------------------------------------------------\n#include \"StdLib.h\"\n\n#include \"..\/EScript\/EScript.h\"\n#include \"..\/EScript\/Parser\/Compiler.h\"\n#include \"..\/EScript\/Parser\/Parser.h\"\n#include \"..\/EScript\/Utils\/IO\/IO.h\"\n#include \"ext\/JSON.h\"\n\n#include \n#include \n#include \n#include \n\n#if defined(_WIN32)\n#include \n#endif\n\nnamespace EScript{\n\nstd::string StdLib::getOS(){\n\t#if defined(_WIN32) || defined(_WIN64)\n\treturn std::string(\"WINDOWS\");\n\t#elif defined(__APPLE__)\n\treturn std::string(\"MAC OS\");\n\t#elif defined(__linux__)\n\treturn std::string(\"LINUX\");\n\t#elif defined(__unix__)\n\treturn std::string(\"UNIX\");\n\t#else\n\treturn std::string(\"UNKNOWN\");\n\t#endif\n}\n\n\/\/! (static)\nvoid StdLib::print_r(Object * o,int maxLevel,int level) {\n\tif (!o) return;\n\tif (level>maxLevel) {\n\t\tstd::cout << \" ... \\n\";\n\t\treturn;\n\t}\n\n\tif (Array * a=dynamic_cast(o)) {\n\t\tstd::cout << \"[\\n\";\n\t\tERef itRef=a->getIterator();\n\t\tint nr=0;\n\t\twhile (!itRef->end()) {\n\t\t\tObjRef valueRef=itRef->value();\n\t\t\tObjRef keyRef=itRef->key();\n\t\t\tif (nr++>0)std::cout << \",\\n\";\n\t\t\tif (!valueRef.isNull()) {\n\t\t\t\tfor (int i=0;inext();\n\t\t}\n\t\tstd::cout << \"\\n\";\n\t\tfor (int i=0;i(o)) {\n\t\tstd::cout << \"{\\n\";\n\t\tERef itRef=m->getIterator();\n\t\tint nr=0;\n\t\twhile (!itRef->end()) {\n\t\t\tObjRef valueRef=itRef->value();\n\t\t\tObjRef keyRef=itRef->key();\n\t\t\tif (nr++>0)\n\t\t\t\tstd::cout << \",\\n\";\n\t\t\tif (!valueRef.isNull()) {\n\t\t\t\tfor (int i=0;inext();\n\t\t}\n\t\tstd::cout << \"\\n\";\n\t\tfor (int i=0;i(o))\n\t\t\tstd::cout << \"\\\"\"<toString()<<\"\\\"\";\n\t\telse std::cout << o->toString();\n\t}\n}\n\n\/*! Tries to locate the given __filename__ with the current searchPath set in the runtime.\n\t@return the path to the file or the original __filename__ if the file could not be found.\t*\/\nstatic std::string findFile(Runtime & runtime, const std::string & filename){\n\tstatic const StringId seachPathsId(\"__searchPaths\");\n\n\tstd::string file(IO::condensePath(filename));\n\tif( IO::getEntryType(file)!=IO::TYPE_FILE ){\n\t\tif(Array * searchPaths = dynamic_cast(runtime.getAttribute(seachPathsId).getValue())){\n\t\t\tfor(ERef itRef=searchPaths->getIterator();!itRef->end();itRef->next()){\n\t\t\t\tObjRef valueRef = itRef->value();\n\t\t\t\tstd::string s(IO::condensePath(valueRef.toString()+'\/'+filename));\n\t\t\t\tif( IO::getEntryType(s)==IO::TYPE_FILE ){\n\t\t\t\t\tfile = s;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn file;\n}\n\n\/\/! (static)\nObjRef StdLib::loadOnce(Runtime & runtime,const std::string & filename){\n\tstatic const StringId mapId(\"__loadOnce_loadedFiles\");\n\n\tstd::string condensedFilename( IO::condensePath(findFile(runtime,filename)) );\n\tMap * m=dynamic_cast(runtime.getAttribute(mapId).getValue());\n\tif(m==NULL){\n\t\tm=Map::create();\n\t\truntime.setAttribute(mapId, Attribute(m));\n\t}\n\tObjRef obj=m->getValue(condensedFilename);\n\tif(obj.toBool()){ \/\/ already loaded?\n\t\treturn NULL;\n\t}\n\tm->setValue(String::create(condensedFilename),Bool::create(true));\n\treturn _loadAndExecute(runtime,condensedFilename);\n}\n\n#if defined(_WIN32)\nstatic LARGE_INTEGER _getPerformanceCounter();\n\n\/\/ execute this as soon as possible (when the global static variables are initialized)\nstatic LARGE_INTEGER _clockStart = _getPerformanceCounter();\n\n\/\/ wrapper for the windows high performance timer.\nLARGE_INTEGER _getPerformanceCounter(){\n\tLARGE_INTEGER c;\n\tQueryPerformanceCounter(&c);\n\treturn c;\n}\n\n#endif\n\n\/\/ -------------------------------------------------------------\n\/\/! init (globals)\nvoid StdLib::init(EScript::Namespace * globals) {\n\n\t\/*!\t[ESF] void addSearchPath(path)\n\t\tAdds a search path which is used for load(...) and loadOnce(...)\t*\/\n\tES_FUNCTION_DECLARE(globals,\"addSearchPath\",1,1,{\n\t\tstatic const StringId seachPathsId(\"__searchPaths\");\n\t\tArray * searchPaths = dynamic_cast(runtime.getAttribute(seachPathsId).getValue());\n\t\tif(searchPaths == NULL){\n\t\t\tsearchPaths = Array::create();\n\t\t\truntime.setAttribute(seachPathsId, Attribute(searchPaths));\n\t\t}\n\t\tsearchPaths->pushBack(String::create(parameter[0].toString()));\n\t\treturn Void::get();\n\t})\n\n\t\/\/! [ESF] void assert( expression[,text])\n\tES_FUNCTION_DECLARE(globals,\"assert\",1,2, {\n\t\tassertParamCount(runtime,parameter.count(),1,2);\n\t\tif(!parameter[0]->toBool()){\n\t\t\truntime.setException(parameter.count()>1?parameter[1]->toString():\"Assert failed.\");\n\t\t}\n\t\treturn NULL;\n\t})\n\n\t\/\/! [ESF] string chr(number)\n\tES_FUNCTION_DECLARE(globals,\"chr\",1,1,{\n\t\tstd::ostringstream s;\n\t\ts<< static_cast(parameter[0]->toInt());\n\t\treturn String::create(s.str());\n\t})\n\n\n\t\/\/ clock\n\t{\n\t#if defined(_WIN32)\n\ttypedef LARGE_INTEGER timer_t;\n\tstatic timer_t frequency;\n\tif(!QueryPerformanceFrequency(&frequency)) {\n\t\tstd::cout <<(\"QueryPerformanceFrequency failed, timer will not work properly!\");\n\t}\n\n\t\/\/! [ESF] number clock()\n\tES_FUNCTION_DECLARE(globals,\"clock\",0,0,{\n\t\tLARGE_INTEGER time = _getPerformanceCounter();\n\t\treturn Number::create( static_cast(time.QuadPart-_clockStart.QuadPart) \/ static_cast(frequency.QuadPart) );\n\t})\n\n\t#else\n\t\/\/! [ESF] number clock()\n\tESF_DECLARE(globals,\"clock\",0,0,Number::create( static_cast(clock())\/CLOCKS_PER_SEC))\n\t#endif\n\t}\n\n\t\/\/!\t[ESF] Object eval(string)\n\tESF_DECLARE(globals,\"eval\",1,1,\n\t\t\t\t_eval(runtime,CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString()))).detachAndDecrease())\n\n\t\/*!\t[ESF] Map getDate([time])\n\t\tlike http:\/\/de3.php.net\/manual\/de\/function.getdate.php\t*\/\n\tES_FUNCTION_DECLARE(globals,\"getDate\",0,1,{\n\t\ttime_t t=(parameter.count()==0)?time(0):static_cast(parameter[0]->toInt());\n\t\ttm *d=localtime (& t );\n\t\tMap * m=Map::create();\n\t\tm->setValue(String::create(\"seconds\"),Number::create(d->tm_sec));\n\t\tm->setValue(String::create(\"minutes\"),Number::create(d->tm_min));\n\t\tm->setValue(String::create(\"hours\"),Number::create(d->tm_hour));\n\t\tm->setValue(String::create(\"mday\"),Number::create(d->tm_mday));\n\t\tm->setValue(String::create(\"mon\"),Number::create(d->tm_mon+1));\n\t\tm->setValue(String::create(\"year\"),Number::create(d->tm_year+1900));\n\t\tm->setValue(String::create(\"wday\"),Number::create(d->tm_wday));\n\t\tm->setValue(String::create(\"yday\"),Number::create(d->tm_yday));\n\t\tm->setValue(String::create(\"isdst\"),Number::create(d->tm_isdst));\n\t\treturn m;\n\t})\n\n\t\/\/! [ESF] string getOS()\n\tESF_DECLARE(globals,\"getOS\",0,0,String::create(StdLib::getOS()))\n\n\t\/\/! [ESF] Runtime getRuntime( )\n\tESF_DECLARE(globals,\"getRuntime\",0,0, &runtime)\n\n\t\/\/!\t[ESF] mixed load(string filename)\n\tESF_DECLARE(globals,\"load\",1,1,_loadAndExecute(runtime,findFile(runtime,parameter[0].toString())).detachAndDecrease())\n\n\t\/\/!\t[ESF] mixed loadOnce(string filename)\n\tESF_DECLARE(globals,\"loadOnce\",1,1,StdLib::loadOnce(runtime,parameter[0].toString()).detachAndDecrease())\n\n\t\/\/! [ESF] void out(...)\n\tES_FUNCTION_DECLARE(globals,\"out\",0,-1, {\n\t\tfor(ParameterValues::const_iterator it=parameter.begin();it!=parameter.end();++it)\n\t\t\tstd::cout << (*it).toString();\n\t\tstd::cout.flush();\n\t\treturn NULL;\n\t})\n\t\n\t\/\/! [ESF] void out(...)\n\tES_FUNCTION_DECLARE(globals,\"outln\",0,-1, {\n\t\tfor(ParameterValues::const_iterator it=parameter.begin();it!=parameter.end();++it)\n\t\t\tstd::cout << (*it).toString();\n\t\tstd::cout << std::endl;\n\t\tstd::cout.flush();\n\t\treturn NULL;\n\t})\n\n\t\/\/!\t[ESF] BlockStatement parse(string) @deprecated\n\tES_FUNCTION_DECLARE(globals,\"parse\",1,1, {\n\t\tERef script;\n\n\t\tCompiler compiler(runtime.getLogger());\n\t\tscript = compiler.compile(CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString())));\n\n\t\treturn script.detachAndDecrease();\n\t})\n\t\/\/! [ESF] obj parseJSON(string)\n\tESF_DECLARE(globals,\"parseJSON\",1,1,JSON::parseJSON(parameter[0].toString()))\n\n\t\/\/! [ESF] void print_r(...)\n\tES_FUNCTION_DECLARE(globals,\"print_r\",0,-1, {\n\t\tstd::cout << \"\\n\";\n\t\tfor(ParameterValues::const_iterator it=parameter.begin();it!=parameter.end();++it) {\n\t\t\tif (!(*it).isNull())\n\t\t\t\tprint_r((*it).get());\n\t\t}\n\t\treturn NULL;\n\t})\n\n\t\/\/!\t[ESF] number system(command)\n\tESF_DECLARE(globals,\"system\",1,1,Number::create(system(parameter[0]->toString().c_str())))\n\n\t\/\/!\t[ESF] Number exec(String path, Array argv)\n\tES_FUNCTION_DECLARE(globals, \"exec\", 2, 2, {\n\t\tArray * array = assertType(runtime, parameter[1]);\n\t\tuint32_t argc = array->size();\n\n\t\tchar ** argv = new char *[argc + 1];\n\t\tfor(uint_fast32_t i = 0; i < argc; ++i) {\n\t\t\t std::string arg = array->get(i)->toString();\n\t\t\t argv[i] = new char[arg.length() + 1];\n\t\t\t std::copy(arg.begin(), arg.end(), argv[i]);\n\t\t\t argv[i][arg.length()] = '\\0';\n\t\t}\n\t\targv[argc] = NULL;\n\n\t\tNumber * result = Number::create(execv(parameter[0]->toString().c_str(), argv));\n\n\t\tfor(uint_fast32_t i = 0; i < argc; ++i) {\n\t\t\tdelete [] argv[i];\n\t\t}\n\t\tdelete [] argv;\n\n\t\treturn result;\n\t})\n\n\t\/\/! [ESF] number time()\n\tESF_DECLARE(globals,\"time\",0,0,Number::create(static_cast(time(NULL))))\n\n\t\/\/! [ESF] string toJSON(obj[,formatted=true])\n\tESF_DECLARE(globals,\"toJSON\",1,2,String::create(JSON::toJSON(parameter[0].get(),parameter[1].toBool(true))))\n\n}\n\n\n}\n...\/\/ StdLib.cpp\n\/\/ This file is part of the EScript programming language.\n\/\/ See copyright notice in EScript.h\n\/\/ ------------------------------------------------------\n#include \"StdLib.h\"\n\n#include \"..\/EScript\/EScript.h\"\n#include \"..\/EScript\/Parser\/Compiler.h\"\n#include \"..\/EScript\/Parser\/Parser.h\"\n#include \"..\/EScript\/Utils\/IO\/IO.h\"\n#include \"ext\/JSON.h\"\n\n#include \n#include \n#include \n#include \n\n#if defined(_WIN32)\n#include \n#endif\n\nnamespace EScript{\n\nstd::string StdLib::getOS(){\n\t#if defined(_WIN32) || defined(_WIN64)\n\treturn std::string(\"WINDOWS\");\n\t#elif defined(__APPLE__)\n\treturn std::string(\"MAC OS\");\n\t#elif defined(__linux__)\n\treturn std::string(\"LINUX\");\n\t#elif defined(__unix__)\n\treturn std::string(\"UNIX\");\n\t#else\n\treturn std::string(\"UNKNOWN\");\n\t#endif\n}\n\n\/\/! (static)\nvoid StdLib::print_r(Object * o,int maxLevel,int level) {\n\tif (!o) return;\n\tif (level>maxLevel) {\n\t\tstd::cout << \" ... \\n\";\n\t\treturn;\n\t}\n\n\tif (Array * a=dynamic_cast(o)) {\n\t\tstd::cout << \"[\\n\";\n\t\tERef itRef=a->getIterator();\n\t\tint nr=0;\n\t\twhile (!itRef->end()) {\n\t\t\tObjRef valueRef=itRef->value();\n\t\t\tObjRef keyRef=itRef->key();\n\t\t\tif (nr++>0)std::cout << \",\\n\";\n\t\t\tif (!valueRef.isNull()) {\n\t\t\t\tfor (int i=0;inext();\n\t\t}\n\t\tstd::cout << \"\\n\";\n\t\tfor (int i=0;i(o)) {\n\t\tstd::cout << \"{\\n\";\n\t\tERef itRef=m->getIterator();\n\t\tint nr=0;\n\t\twhile (!itRef->end()) {\n\t\t\tObjRef valueRef=itRef->value();\n\t\t\tObjRef keyRef=itRef->key();\n\t\t\tif (nr++>0)\n\t\t\t\tstd::cout << \",\\n\";\n\t\t\tif (!valueRef.isNull()) {\n\t\t\t\tfor (int i=0;inext();\n\t\t}\n\t\tstd::cout << \"\\n\";\n\t\tfor (int i=0;i(o))\n\t\t\tstd::cout << \"\\\"\"<toString()<<\"\\\"\";\n\t\telse std::cout << o->toString();\n\t}\n}\n\n\/*! Tries to locate the given __filename__ with the current searchPath set in the runtime.\n\t@return the path to the file or the original __filename__ if the file could not be found.\t*\/\nstatic std::string findFile(Runtime & runtime, const std::string & filename){\n\tstatic const StringId seachPathsId(\"__searchPaths\");\n\n\tstd::string file(IO::condensePath(filename));\n\tif( IO::getEntryType(file)!=IO::TYPE_FILE ){\n\t\tif(Array * searchPaths = dynamic_cast(runtime.getAttribute(seachPathsId).getValue())){\n\t\t\tfor(ERef itRef=searchPaths->getIterator();!itRef->end();itRef->next()){\n\t\t\t\tObjRef valueRef = itRef->value();\n\t\t\t\tstd::string s(IO::condensePath(valueRef.toString()+'\/'+filename));\n\t\t\t\tif( IO::getEntryType(s)==IO::TYPE_FILE ){\n\t\t\t\t\tfile = s;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn file;\n}\n\n\/\/! (static)\nObjRef StdLib::loadOnce(Runtime & runtime,const std::string & filename){\n\tstatic const StringId mapId(\"__loadOnce_loadedFiles\");\n\n\tstd::string condensedFilename( IO::condensePath(findFile(runtime,filename)) );\n\tMap * m=dynamic_cast(runtime.getAttribute(mapId).getValue());\n\tif(m==NULL){\n\t\tm=Map::create();\n\t\truntime.setAttribute(mapId, Attribute(m));\n\t}\n\tObjRef obj=m->getValue(condensedFilename);\n\tif(obj.toBool()){ \/\/ already loaded?\n\t\treturn NULL;\n\t}\n\tm->setValue(String::create(condensedFilename),Bool::create(true));\n\treturn _loadAndExecute(runtime,condensedFilename);\n}\n\n#if defined(_WIN32)\nstatic LARGE_INTEGER _getPerformanceCounter();\n\n\/\/ execute this as soon as possible (when the global static variables are initialized)\nstatic LARGE_INTEGER _clockStart = _getPerformanceCounter();\n\n\/\/ wrapper for the windows high performance timer.\nLARGE_INTEGER _getPerformanceCounter(){\n\tLARGE_INTEGER c;\n\tQueryPerformanceCounter(&c);\n\treturn c;\n}\n\n#endif\n\n\/\/ -------------------------------------------------------------\n\/\/! init (globals)\nvoid StdLib::init(EScript::Namespace * globals) {\n\n\t\/*!\t[ESF] void addSearchPath(path)\n\t\tAdds a search path which is used for load(...) and loadOnce(...)\t*\/\n\tES_FUNCTION_DECLARE(globals,\"addSearchPath\",1,1,{\n\t\tstatic const StringId seachPathsId(\"__searchPaths\");\n\t\tArray * searchPaths = dynamic_cast(runtime.getAttribute(seachPathsId).getValue());\n\t\tif(searchPaths == NULL){\n\t\t\tsearchPaths = Array::create();\n\t\t\truntime.setAttribute(seachPathsId, Attribute(searchPaths));\n\t\t}\n\t\tsearchPaths->pushBack(String::create(parameter[0].toString()));\n\t\treturn Void::get();\n\t})\n\n\t\/\/! [ESF] void assert( expression[,text])\n\tES_FUNCTION_DECLARE(globals,\"assert\",1,2, {\n\t\tassertParamCount(runtime,parameter.count(),1,2);\n\t\tif(!parameter[0]->toBool()){\n\t\t\truntime.setException(parameter.count()>1?parameter[1]->toString():\"Assert failed.\");\n\t\t}\n\t\treturn NULL;\n\t})\n\n\t\/\/! [ESF] string chr(number)\n\tES_FUNCTION_DECLARE(globals,\"chr\",1,1,{\n\t\tstd::ostringstream s;\n\t\ts<< static_cast(parameter[0]->toInt());\n\t\treturn String::create(s.str());\n\t})\n\n\n\t\/\/ clock\n\t{\n\t#if defined(_WIN32)\n\ttypedef LARGE_INTEGER timer_t;\n\tstatic timer_t frequency;\n\tif(!QueryPerformanceFrequency(&frequency)) {\n\t\tstd::cout <<(\"QueryPerformanceFrequency failed, timer will not work properly!\");\n\t}\n\n\t\/\/! [ESF] number clock()\n\tES_FUNCTION_DECLARE(globals,\"clock\",0,0,{\n\t\tLARGE_INTEGER time = _getPerformanceCounter();\n\t\treturn Number::create( static_cast(time.QuadPart-_clockStart.QuadPart) \/ static_cast(frequency.QuadPart) );\n\t})\n\n\t#else\n\t\/\/! [ESF] number clock()\n\tESF_DECLARE(globals,\"clock\",0,0,Number::create( static_cast(clock())\/CLOCKS_PER_SEC))\n\t#endif\n\t}\n\n\t\/\/!\t[ESF] Object eval(string)\n\tESF_DECLARE(globals,\"eval\",1,1,\n\t\t\t\t_eval(runtime,CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString()))).detachAndDecrease())\n\n\t\/*!\t[ESF] Map getDate([time])\n\t\tlike http:\/\/de3.php.net\/manual\/de\/function.getdate.php\t*\/\n\tES_FUNCTION_DECLARE(globals,\"getDate\",0,1,{\n\t\ttime_t t=(parameter.count()==0)?time(0):static_cast(parameter[0]->toInt());\n\t\ttm *d=localtime (& t );\n\t\tMap * m=Map::create();\n\t\tm->setValue(String::create(\"seconds\"),Number::create(d->tm_sec));\n\t\tm->setValue(String::create(\"minutes\"),Number::create(d->tm_min));\n\t\tm->setValue(String::create(\"hours\"),Number::create(d->tm_hour));\n\t\tm->setValue(String::create(\"mday\"),Number::create(d->tm_mday));\n\t\tm->setValue(String::create(\"mon\"),Number::create(d->tm_mon+1));\n\t\tm->setValue(String::create(\"year\"),Number::create(d->tm_year+1900));\n\t\tm->setValue(String::create(\"wday\"),Number::create(d->tm_wday));\n\t\tm->setValue(String::create(\"yday\"),Number::create(d->tm_yday));\n\t\tm->setValue(String::create(\"isdst\"),Number::create(d->tm_isdst));\n\t\treturn m;\n\t})\n\n\t\/\/! [ESF] string getOS()\n\tESF_DECLARE(globals,\"getOS\",0,0,String::create(StdLib::getOS()))\n\n\t\/\/! [ESF] Runtime getRuntime( )\n\tESF_DECLARE(globals,\"getRuntime\",0,0, &runtime)\n\n\t\/\/!\t[ESF] mixed load(string filename)\n\tESF_DECLARE(globals,\"load\",1,1,_loadAndExecute(runtime,findFile(runtime,parameter[0].toString())).detachAndDecrease())\n\n\t\/\/!\t[ESF] mixed loadOnce(string filename)\n\tESF_DECLARE(globals,\"loadOnce\",1,1,StdLib::loadOnce(runtime,parameter[0].toString()).detachAndDecrease())\n\n\t\/\/! [ESF] void out(...)\n\tES_FUNCTION_DECLARE(globals,\"out\",0,-1, {\n\t\tfor(ParameterValues::const_iterator it=parameter.begin();it!=parameter.end();++it)\n\t\t\tstd::cout << (*it).toString();\n\t\tstd::cout.flush();\n\t\treturn NULL;\n\t})\n\t\n\t\/\/! [ESF] void outln(...)\n\tES_FUNCTION_DECLARE(globals,\"outln\",0,-1, {\n\t\tfor(ParameterValues::const_iterator it=parameter.begin();it!=parameter.end();++it)\n\t\t\tstd::cout << (*it).toString();\n\t\tstd::cout << std::endl;\n\t\tstd::cout.flush();\n\t\treturn NULL;\n\t})\n\n\t\/\/!\t[ESF] BlockStatement parse(string) @deprecated\n\tES_FUNCTION_DECLARE(globals,\"parse\",1,1, {\n\t\tERef script;\n\n\t\tCompiler compiler(runtime.getLogger());\n\t\tscript = compiler.compile(CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString())));\n\n\t\treturn script.detachAndDecrease();\n\t})\n\t\/\/! [ESF] obj parseJSON(string)\n\tESF_DECLARE(globals,\"parseJSON\",1,1,JSON::parseJSON(parameter[0].toString()))\n\n\t\/\/! [ESF] void print_r(...)\n\tES_FUNCTION_DECLARE(globals,\"print_r\",0,-1, {\n\t\tstd::cout << \"\\n\";\n\t\tfor(ParameterValues::const_iterator it=parameter.begin();it!=parameter.end();++it) {\n\t\t\tif (!(*it).isNull())\n\t\t\t\tprint_r((*it).get());\n\t\t}\n\t\treturn NULL;\n\t})\n\n\t\/\/!\t[ESF] number system(command)\n\tESF_DECLARE(globals,\"system\",1,1,Number::create(system(parameter[0]->toString().c_str())))\n\n\t\/\/!\t[ESF] Number exec(String path, Array argv)\n\tES_FUNCTION_DECLARE(globals, \"exec\", 2, 2, {\n\t\tArray * array = assertType(runtime, parameter[1]);\n\t\tuint32_t argc = array->size();\n\n\t\tchar ** argv = new char *[argc + 1];\n\t\tfor(uint_fast32_t i = 0; i < argc; ++i) {\n\t\t\t std::string arg = array->get(i)->toString();\n\t\t\t argv[i] = new char[arg.length() + 1];\n\t\t\t std::copy(arg.begin(), arg.end(), argv[i]);\n\t\t\t argv[i][arg.length()] = '\\0';\n\t\t}\n\t\targv[argc] = NULL;\n\n\t\tNumber * result = Number::create(execv(parameter[0]->toString().c_str(), argv));\n\n\t\tfor(uint_fast32_t i = 0; i < argc; ++i) {\n\t\t\tdelete [] argv[i];\n\t\t}\n\t\tdelete [] argv;\n\n\t\treturn result;\n\t})\n\n\t\/\/! [ESF] number time()\n\tESF_DECLARE(globals,\"time\",0,0,Number::create(static_cast(time(NULL))))\n\n\t\/\/! [ESF] string toJSON(obj[,formatted=true])\n\tESF_DECLARE(globals,\"toJSON\",1,2,String::create(JSON::toJSON(parameter[0].get(),parameter[1].toBool(true))))\n\n}\n\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"openeye.h\"\n#include \"oesystem.h\"\n#include \"oechem.h\"\n#include \"oedocking.h\"\n\nusing namespace OESystem;\nusing namespace OEChem;\nusing namespace OEDocking;\nusing namespace std;\n\nint main(int numOfArg, char* argv[])\n{\n\tOEGraphMol receptor;\n\tOEReadReceptorFile(receptor, argv[3]);\n unsigned int dockMethod = atoi(argv[1]);\n\tunsigned int dockResolution = atoi(argv[2]);\n\tOEDock dock(dockMethod, dockResolution);\n\tdock.Initialize(receptor);\n\n\toemolistream imstr;\n\toemolostream omstr;\n\n\timstr.SetFormat(OEFormat::SDF);\n\tomstr.SetFormat(OEFormat::SDF);\n\n\tOEMol mcmol;\n\t\/\/Scoring the molecules in SDF File\n\t while (OEReadMolecule(imstr, mcmol))\n\t {\n\t OEGraphMol dockedMol;\n\t dock.DockMultiConformerMolecule(dockedMol,mcmol);\n\t string sdtag = OEDockMethodGetName(dockMethod);\n\t OESetSDScore(dockedMol, dock, sdtag);\n\t dock.AnnotatePose(dockedMol);\n\t \/\/Writing moles to the SDF File with Scores\n\t OEWriteMolecule(omstr, dockedMol);\n\t }\n return 0;\n}\nUpdate dockingstd.cpp#include \n#include \n\n#include \"openeye.h\"\n#include \"oesystem.h\"\n#include \"oechem.h\"\n#include \"oedocking.h\"\n\nusing namespace OESystem;\nusing namespace OEChem;\nusing namespace OEDocking;\nusing namespace std;\n\nint main(int numOfArg, char* argv[])\n{\n\tOEGraphMol receptor;\n\tOEReadReceptorFile(receptor, argv[3]);\n \tunsigned int dockMethod = atoi(argv[1]);\n\tunsigned int dockResolution = atoi(argv[2]);\n\tOEDock dock(dockMethod, dockResolution);\n\tdock.Initialize(receptor);\n\n\toemolistream imstr;\n\toemolostream omstr;\n\n\timstr.SetFormat(OEFormat::SDF);\n\tomstr.SetFormat(OEFormat::SDF);\n\n\tOEMol mcmol;\n\t\/\/Scoring the molecules in SDF File\n\t while (OEReadMolecule(imstr, mcmol))\n\t {\n\t OEGraphMol dockedMol;\n\t dock.DockMultiConformerMolecule(dockedMol,mcmol);\n\t string sdtag = OEDockMethodGetName(dockMethod);\n\t OESetSDScore(dockedMol, dock, sdtag);\n\t dock.AnnotatePose(dockedMol);\n\t \/\/Writing moles to the SDF File with Scores\n\t OEWriteMolecule(omstr, dockedMol);\n\t }\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"rpc\/rpc_connection_limits.h\"\n\nnamespace smf {\nrpc_connection_limits::rpc_connection_limits(size_t basic_req_size,\n size_t bloat_mult,\n size_t max_mem)\n : basic_request_size(basic_req_size)\n , bloat_factor(bloat_mult)\n , max_memory(max_mem)\n , resources_available(max_mem) {}\n\nsize_t rpc_connection_limits::estimate_request_size(size_t serialized_size) {\n return (basic_request_size + serialized_size) * bloat_factor;\n}\n\nfuture<> rpc_connection_limits::wait_for_resources(size_t memory_consumed) {\n return resources_available.wait(memory_consumed);\n}\nvoid rpc_connection_limits::release_resources(size_t memory_consumed) {\n resources_available.signal(memory_consumed);\n}\n\nrpc_connection_limits::~rpc_connection_limits() {}\n\nstd::ostream &operator<<(std::ostream &o, const rpc_connection_limits &l) {\n o << \"{'basic_request_size':\" << l.basic_request_size\n << \",'bloat_factor': \" << l.bloat_factor << \",'max_mem':\" << l.max_memory\n << \",'resources_available':\" << l.resources_available.current() << \"}\";\n return o;\n}\n} \/\/ smf\nrpc: rpc_connection_limits.cc formatted output#include \"rpc\/rpc_connection_limits.h\"\n\nnamespace smf {\nrpc_connection_limits::rpc_connection_limits(size_t basic_req_size,\n size_t bloat_mult,\n size_t max_mem)\n : basic_request_size(basic_req_size)\n , bloat_factor(bloat_mult)\n , max_memory(max_mem)\n , resources_available(max_mem) {}\n\nsize_t rpc_connection_limits::estimate_request_size(size_t serialized_size) {\n return (basic_request_size + serialized_size) * bloat_factor;\n}\n\nfuture<> rpc_connection_limits::wait_for_resources(size_t memory_consumed) {\n return resources_available.wait(memory_consumed);\n}\nvoid rpc_connection_limits::release_resources(size_t memory_consumed) {\n resources_available.signal(memory_consumed);\n}\n\nrpc_connection_limits::~rpc_connection_limits() {}\n\nstd::ostream &operator<<(std::ostream &o, const rpc_connection_limits &l) {\n o << \"{'basic_req_size':\" << l.basic_request_size\n << \",'bloat_factor': \" << l.bloat_factor << \",'max_mem':\" << l.max_memory\n << \",'res_avail':\" << l.resources_available.current() << \"}\";\n return o;\n}\n} \/\/ smf\n<|endoftext|>"} {"text":"#include \"HalideRuntime.h\"\n#include \"runtime_internal.h\"\n\nextern \"C\" {\n\nWEAK __attribute__((always_inline)) int halide_profiler_set_current_func(halide_profiler_state *state, int tok, int t) {\n \/\/ Do a volatile store to discourage llvm from reordering it.\n volatile int *ptr = &(state->current_func);\n *ptr = tok + t;\n return 0;\n}\n\n}\nFix profiler performance test#include \"HalideRuntime.h\"\n#include \"runtime_internal.h\"\n\nextern \"C\" {\n\nWEAK __attribute__((always_inline)) int halide_profiler_set_current_func(halide_profiler_state *state, int tok, int t) {\n \/\/ Use empty volatile asm blocks to prevent code motion. Otherwise\n \/\/ llvm reorders or elides the stores.\n int *ptr = &(state->current_func);\n asm volatile (\"\":::);\n *ptr = tok + t;\n asm volatile (\"\":::);\n return 0;\n}\n\n}\n<|endoftext|>"} {"text":"#include \"TROOT.h\"\r\n#include \"TSystem.h\"\r\n#include \"TRolke.h\"\r\n#include \"Riostream.h\"\r\n \r\n \r\nvoid Rolke()\r\n{\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ Routine computes the profile likelihood confidence\r\n\/\/ limits for 7 different model assumptions\r\n\/\/ on systematic\/statistical uncertainties\r\n\/\/\r\n\/\/ You must load libPhysics before executing this script.\r\n\/\/\r\n\/\/ Author : Jan Conrad (CERN) \r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ Model 1 assumes:\r\n\/\/\r\n\/\/ Poisson uncertainty in the background estimate\r\n\/\/ Binomial uncertainty in the efficiency estimate\r\n\/\/\r\n\/\/ y = 10 events observed in the background region\r\n\/\/ x = 5 events in the signal region\r\n\/\/ tau = 2.5 ratio between size of signal\/background region\r\n\/\/ m = 100 MC events have been produced (signal)\r\n\/\/ z = 50 MC events have been observed (signal)\r\n\/\/ alpha = 0.9 Confidence Level\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n \/\/gSystem->Load(\"libPhysics\");\r\n Double_t bm = 0.0;\r\n Double_t tau = 2.5;\r\n Int_t mid = 1;\r\n Int_t m = 100;\r\n Int_t z = 50;\r\n Int_t y = 10;\r\n Int_t x = 5;\r\n \/\/ Initialize parameters not used.\r\n Double_t e = 0.0;\r\n Double_t em = 0.0;\r\n Double_t sde=0.0;\r\n Double_t sdb=0.0;\r\n Double_t b = 0.0;\r\n\r\n\r\n TRolke g;\r\n \r\n g.SetCL(0.90);\r\n \r\n Double_t ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\r\n Double_t ll = g.GetLowerLimit();\r\n \r\n cout << \"Assuming Model 1\" << endl; \r\n cout << \"the Profile Likelihood interval is :\" << endl;\r\n cout << \"[\" << ll << \",\" << ul << \"]\" << endl;\r\n\r\n \r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ Model 2 assumes:\r\n\/\/\r\n\/\/ Poisson uncertainty in the background estimate\r\n\/\/ Gaussian uncertainty in the efficiency estimate\r\n\/\/\r\n\/\/ y = 3 events observed in the background region\r\n\/\/ x = 10 events in the signal region\r\n\/\/ tau = 2.5 ratio between size of signal\/background region\r\n\/\/ em = 0.9 measured efficiency\r\n\/\/ sde = 0.05 standard deviation of efficiency\r\n\/\/ alpha =0.95 Confidence L evel\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n\r\n tau = 2.5;\r\n mid = 2;\r\n y = 3;\r\n x = 10;\r\n em=0.9;\r\n sde=0.05;\r\n\r\n g.SetCL(0.95);\r\n\r\n ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\r\n ll = g.GetLowerLimit();\r\n \r\n cout << \"Assuming MODEL 2\" << endl; \r\n cout << \"the Profile Likelihood interval is :\" << endl;\r\n cout << \"[\" << ll << \",\" << ul << \"]\" << endl;\r\n \r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ Model 3 assumes:\r\n\/\/\r\n\/\/ Gaussian uncertainty in the background estimate\r\n\/\/ Gaussian uncertainty in the efficiency estimate\r\n\/\/\r\n\/\/ bm = 5 expected background\r\n\/\/ x = 10 events in the signal region\r\n\/\/ sdb = 0.5 standard deviation in background estimate\r\n\/\/ em = 0.9 measured efficiency\r\n\/\/ sde = 0.05 standard deviation of efficiency\r\n\/\/ alpha =0.99 Confidence Level\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n\r\n\r\n mid = 3;\r\n bm = 5.0;\r\n x = 10;\r\n em = 0.9;\r\n sde=0.05;\r\n sdb=0.5;\r\n\r\n g.SetCL(0.99);\r\n\r\n\r\n ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\r\n ll = g.GetLowerLimit();\r\n \r\ncout << \"Assuming Model 3\" << endl; \r\ncout << \"the Profile Likelihood interval is :\" << endl;\r\ncout << \"[\" << ll << \",\" << ul << \"]\" << endl;\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ Model 4 assumes:\r\n\/\/\r\n\/\/ Poisson uncertainty in the background estimate\r\n\/\/ known efficiency\r\n\/\/\r\n\/\/ y = 7 events observed in the background region\r\n\/\/ x = 1 events in the signal region\r\n\/\/ tau = 5 ratio between size of signal\/background region\r\n\/\/\r\n\/\/ alpha =0.68 Confidence L evel\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n\r\n tau = 5;\r\n mid = 4;\r\n y = 7;\r\n x = 1;\r\n e = 0.25;\r\n\r\n\r\n g.SetCL(0.68);\r\n\r\n ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\r\n ll = g.GetLowerLimit();\r\n \r\n cout << \"Assuming Model 4\" << endl; \r\n cout << \"the Profile Likelihood interval is :\" << endl;\r\n cout << \"[\" << ll << \",\" << ul << \"]\" << endl;\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ Model 5 assumes:\r\n\/\/\r\n\/\/ Gaussian uncertainty in the background estimate\r\n\/\/ Known efficiency\r\n\/\/\r\n\/\/ bm = 0 measured background expectation\r\n\/\/ x = 1 events in the signal region\r\n\/\/ e = 0.65\r\n\/\/ sdb = 1. standard deviation of background estimate\r\n\/\/ alpha =0.799999 Confidence Level\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n\r\n mid = 5;\r\n bm = 0.0;\r\n x = 1;\r\n e = 0.65;\r\n sdb=1.0;\r\n\r\n g.SetCL(0.80);\r\n\r\n ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\r\n ll = g.GetLowerLimit();\r\n \r\n cout << \"Assuming Model 5\" << endl; \r\n cout << \"the Profile Likelihood interval is :\" << endl;\r\n cout << \"[\" << ll << \",\" << ul << \"]\" << endl;\r\n \r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ Model 6 assumes:\r\n\/\/\r\n\/\/ Known background \r\n\/\/ Binomial uncertainty in the efficiency estimate\r\n\/\/\r\n\/\/ b = 10 known background\r\n\/\/ x = 25 events in the signal region\r\n\/\/ z = 500 Number of observed signal MC events\r\n\/\/ m = 750 Number of produced MC signal events\r\n\/\/ alpha =0.9 Confidence L evel\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n y = 1;\r\n mid = 6;\r\n m = 750;\r\n z = 500;\r\n x = 25;\r\n b = 10.0;\r\n\r\n TRolke p; \r\n p.SetCL(0.90);\r\n ul = p.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\r\n Double_t newll = p.GetLowerLimit();\r\n \r\n cout << \"Assuming Model 6\" << endl; \r\n cout << \"the Profile Likelihood interval is :\" << endl;\r\n cout << \"[\" << newll << \",\" << ul << \"]\" << endl;\r\n \r\n\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ Model 7 assumes:\r\n\/\/\r\n\/\/ Known Background\r\n\/\/ Gaussian uncertainty in the efficiency estimate\r\n\/\/\r\n\/\/ x = 15 events in the signal region\r\n\/\/ em = 0.77 measured efficiency\r\n\/\/ sde = 0.15 standard deviation of efficiency estimate\r\n\/\/ b = 10 known background\r\n\/\/ alpha =0.95 Confidence L evel\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n\r\n mid = 7;\r\n x = 15;\r\n em = 0.77;\r\n sde=0.15;\r\n b = 10.0;\r\n\r\n g.SetCL(0.95);\r\n \r\n ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\r\n ll = g.GetLowerLimit();\r\n \r\n cout << \"Assuming Model 7 \" << endl; \r\n cout << \"the Profile Likelihood interval is :\" << endl;\r\n cout << \"[\" << ll << \",\" << ul << \"]\" << endl;\r\n\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ Example of bounded and unbounded likelihood\r\n\/\/\r\n\/\/ Example for Model 1\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n\r\n Double_t bm = 0.0;\r\n Double_t tau = 5;\r\n Int_t mid = 1;\r\n Int_t m = 100;\r\n Int_t z = 90;\r\n Int_t y = 15;\r\n Int_t x = 0;\r\n \/\/ Initialize parameters not used.\r\n Double_t e = 0.0;\r\n Double_t em = 0.0;\r\n Double_t sde=0.0;\r\n Double_t sdb=0.0;\r\n Double_t b = 0.0;\r\n\r\n\r\n TRolke g;\r\n \r\n g.SetCL(0.90);\r\n g.SetSwitch(1); \/\/bounded\r\n \r\n Double_t ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\r\n Double_t ll = g.GetLowerLimit();\r\n\r\n g.SetSwitch(0); \/\/unbounded\r\n\r\n cout << \"Assuming Model 1\" << endl; \r\n cout << \"the BOUNDED Profile Likelihood interval is :\" << endl;\r\n cout << \"[\" << ll << \",\" << ul << \"]\" << endl;\r\n\r\n\r\n ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\r\n ll = g.GetLowerLimit();\r\n\r\n cout << \"Assuming Model 1\" << endl; \r\n cout << \"the UNBOUNDED Profile Likelihood interval is :\" << endl;\r\n cout << \"[\" << ll << \",\" << ul << \"]\" << endl;\r\n\r\n}\r\n\r\nFrom Anna Kreshuk: New version of the tutorial that can also be run with ACLIC#include \"TROOT.h\"\n#include \"TSystem.h\"\n#include \"TRolke.h\"\n#include \"Riostream.h\"\n \n \nvoid Rolke()\n{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Routine computes the profile likelihood confidence\n\/\/ limits for 7 different model assumptions\n\/\/ on systematic\/statistical uncertainties\n\/\/\n\/\/ You must load libPhysics before executing this script.\n\/\/\n\/\/ Author : Jan Conrad (CERN) \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Model 1 assumes:\n\/\/\n\/\/ Poisson uncertainty in the background estimate\n\/\/ Binomial uncertainty in the efficiency estimate\n\/\/\n\/\/ y = 10 events observed in the background region\n\/\/ x = 5 events in the signal region\n\/\/ tau = 2.5 ratio between size of signal\/background region\n\/\/ m = 100 MC events have been produced (signal)\n\/\/ z = 50 MC events have been observed (signal)\n\/\/ alpha = 0.9 Confidence Level\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/gSystem->Load(\"libPhysics\");\n Double_t bm = 0.0;\n Double_t tau = 2.5;\n Int_t mid = 1;\n Int_t m = 100;\n Int_t z = 50;\n Int_t y = 10;\n Int_t x = 5;\n \/\/ Initialize parameters not used.\n Double_t e = 0.0;\n Double_t em = 0.0;\n Double_t sde=0.0;\n Double_t sdb=0.0;\n Double_t b = 0.0;\n\n\n TRolke g;\n \n g.SetCL(0.90);\n \n Double_t ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\n Double_t ll = g.GetLowerLimit();\n \n cout << \"Assuming Model 1\" << endl; \n cout << \"the Profile Likelihood interval is :\" << endl;\n cout << \"[\" << ll << \",\" << ul << \"]\" << endl;\n\n \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Model 2 assumes:\n\/\/\n\/\/ Poisson uncertainty in the background estimate\n\/\/ Gaussian uncertainty in the efficiency estimate\n\/\/\n\/\/ y = 3 events observed in the background region\n\/\/ x = 10 events in the signal region\n\/\/ tau = 2.5 ratio between size of signal\/background region\n\/\/ em = 0.9 measured efficiency\n\/\/ sde = 0.05 standard deviation of efficiency\n\/\/ alpha =0.95 Confidence L evel\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n tau = 2.5;\n mid = 2;\n y = 3;\n x = 10;\n em=0.9;\n sde=0.05;\n\n g.SetCL(0.95);\n\n ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\n ll = g.GetLowerLimit();\n \n cout << \"Assuming MODEL 2\" << endl; \n cout << \"the Profile Likelihood interval is :\" << endl;\n cout << \"[\" << ll << \",\" << ul << \"]\" << endl;\n \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Model 3 assumes:\n\/\/\n\/\/ Gaussian uncertainty in the background estimate\n\/\/ Gaussian uncertainty in the efficiency estimate\n\/\/\n\/\/ bm = 5 expected background\n\/\/ x = 10 events in the signal region\n\/\/ sdb = 0.5 standard deviation in background estimate\n\/\/ em = 0.9 measured efficiency\n\/\/ sde = 0.05 standard deviation of efficiency\n\/\/ alpha =0.99 Confidence Level\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n mid = 3;\n bm = 5.0;\n x = 10;\n em = 0.9;\n sde=0.05;\n sdb=0.5;\n\n g.SetCL(0.99);\n\n\n ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\n ll = g.GetLowerLimit();\n \ncout << \"Assuming Model 3\" << endl; \ncout << \"the Profile Likelihood interval is :\" << endl;\ncout << \"[\" << ll << \",\" << ul << \"]\" << endl;\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Model 4 assumes:\n\/\/\n\/\/ Poisson uncertainty in the background estimate\n\/\/ known efficiency\n\/\/\n\/\/ y = 7 events observed in the background region\n\/\/ x = 1 events in the signal region\n\/\/ tau = 5 ratio between size of signal\/background region\n\/\/\n\/\/ alpha =0.68 Confidence L evel\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n tau = 5;\n mid = 4;\n y = 7;\n x = 1;\n e = 0.25;\n\n\n g.SetCL(0.68);\n\n ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\n ll = g.GetLowerLimit();\n \n cout << \"Assuming Model 4\" << endl; \n cout << \"the Profile Likelihood interval is :\" << endl;\n cout << \"[\" << ll << \",\" << ul << \"]\" << endl;\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Model 5 assumes:\n\/\/\n\/\/ Gaussian uncertainty in the background estimate\n\/\/ Known efficiency\n\/\/\n\/\/ bm = 0 measured background expectation\n\/\/ x = 1 events in the signal region\n\/\/ e = 0.65\n\/\/ sdb = 1. standard deviation of background estimate\n\/\/ alpha =0.799999 Confidence Level\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n mid = 5;\n bm = 0.0;\n x = 1;\n e = 0.65;\n sdb=1.0;\n\n g.SetCL(0.80);\n\n ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\n ll = g.GetLowerLimit();\n \n cout << \"Assuming Model 5\" << endl; \n cout << \"the Profile Likelihood interval is :\" << endl;\n cout << \"[\" << ll << \",\" << ul << \"]\" << endl;\n \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Model 6 assumes:\n\/\/\n\/\/ Known background \n\/\/ Binomial uncertainty in the efficiency estimate\n\/\/\n\/\/ b = 10 known background\n\/\/ x = 25 events in the signal region\n\/\/ z = 500 Number of observed signal MC events\n\/\/ m = 750 Number of produced MC signal events\n\/\/ alpha =0.9 Confidence L evel\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n y = 1;\n mid = 6;\n m = 750;\n z = 500;\n x = 25;\n b = 10.0;\n\n TRolke p; \n p.SetCL(0.90);\n ul = p.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\n Double_t newll = p.GetLowerLimit();\n \n cout << \"Assuming Model 6\" << endl; \n cout << \"the Profile Likelihood interval is :\" << endl;\n cout << \"[\" << newll << \",\" << ul << \"]\" << endl;\n \n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Model 7 assumes:\n\/\/\n\/\/ Known Background\n\/\/ Gaussian uncertainty in the efficiency estimate\n\/\/\n\/\/ x = 15 events in the signal region\n\/\/ em = 0.77 measured efficiency\n\/\/ sde = 0.15 standard deviation of efficiency estimate\n\/\/ b = 10 known background\n\/\/ alpha =0.95 Confidence L evel\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n mid = 7;\n x = 15;\n em = 0.77;\n sde=0.15;\n b = 10.0;\n\n g.SetCL(0.95);\n \n ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\n ll = g.GetLowerLimit();\n \n cout << \"Assuming Model 7 \" << endl; \n cout << \"the Profile Likelihood interval is :\" << endl;\n cout << \"[\" << ll << \",\" << ul << \"]\" << endl;\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Example of bounded and unbounded likelihood\n\/\/\n\/\/ Example for Model 1\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n bm = 0.0;\n tau = 5;\n mid = 1;\n m = 100;\n z = 90;\n y = 15;\n x = 0;\n \/\/ Initialize parameters not used.\n e = 0.0;\n em = 0.0;\n sde=0.0;\n sdb=0.0;\n b = 0.0;\n\n g.SetCL(0.90);\n g.SetSwitch(1); \/\/bounded\n \n ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\n ll = g.GetLowerLimit();\n \n g.SetSwitch(0); \/\/unbounded\n \n cout << \"Assuming Model 1\" << endl; \n cout << \"the BOUNDED Profile Likelihood interval is :\" << endl;\n cout << \"[\" << ll << \",\" << ul << \"]\" << endl;\n\n\n ul = g.CalculateInterval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);\n ll = g.GetLowerLimit();\n \n cout << \"Assuming Model 1\" << endl; \n cout << \"the UNBOUNDED Profile Likelihood interval is :\" << endl;\n cout << \"[\" << ll << \",\" << ul << \"]\" << endl;\n \n}\n\n<|endoftext|>"} {"text":"\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_STUFF_FUNCTIONS_FLATTOP_HH\n#define DUNE_STUFF_FUNCTIONS_FLATTOP_HH\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Dune {\nnamespace Stuff {\nnamespace Functions {\n\n\n\/**\n * Based on: Brenner, S. C. and Davis, C. B. and Sung, L.-y.\n * A partition of unity method for the displacement obstacle problem of clamped Kirchhoff plates\n * http:\/\/dx.doi.org\/10.1016\/j.cam.2013.09.033\n * Subsection 2.1.1\n *\/\ntemplate< class E, class D, int d, class R, int r, int rC = 1 >\nclass FlatTop\n : public LocalizableFunctionInterface< E, D, d, R, r, rC >\n{\n FlatTop() { static_assert(AlwaysFalse< E >::value, \"Not available for these dimensions!\"); }\n};\n\n\ntemplate< class E, class D, int d, class R >\nclass FlatTop< E, D, d, R, 1, 1 >\n : public GlobalFunctionInterface< E, D, d, R, 1, 1 >\n{\n typedef GlobalFunctionInterface< E, D, d, R, 1, 1 > BaseType;\n typedef FlatTop< E, D, d, R, 1, 1 > ThisType;\n\npublic:\n typedef typename BaseType::EntityType EntityType;\n typedef typename BaseType::DomainFieldType DomainFieldType;\n static const unsigned int dimDomain = BaseType::dimDomain;\n typedef typename BaseType::DomainType DomainType;\n typedef typename BaseType::RangeFieldType RangeFieldType;\n static const unsigned int dimRange = BaseType::dimRange;\n typedef typename BaseType::RangeType RangeType;\n\n typedef Common::FieldVector< DomainFieldType, dimDomain > StuffDomainType;\n typedef Common::FieldVector< RangeFieldType, dimRange > StuffRangeType;\n\n static const bool available = true;\n\n static std::string static_id()\n {\n return BaseType::static_id() + \".flattop\";\n }\n\n static Common::Configuration default_config(const std::string sub_name = \"\")\n {\n Common::Configuration config;\n config[\"lower_left\"] = \"[0.0 0.0 0.0]\";\n config[\"upper_right\"] = \"[1.0 1.0 1.0]\";\n config[\"boundary_layer\"] = \"[1e-1 1e-1 1e-1]\";\n config[\"value\"] = \"1.0\";\n config[\"name\"] = static_id();\n if (sub_name.empty())\n return config;\n else {\n Common::Configuration tmp;\n tmp.add(config, sub_name);\n return tmp;\n }\n } \/\/ ... default_config(...)\n\n static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(),\n const std::string sub_name = static_id())\n {\n \/\/ get correct config\n const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;\n const Common::Configuration default_cfg = default_config();\n return Common::make_unique< ThisType >(\n cfg.get(\"lower_left\", default_cfg.get< DomainType >( \"lower_left\")),\n cfg.get(\"upper_right\", default_cfg.get< DomainType >( \"upper_right\")),\n cfg.get(\"boundary_layer\", default_cfg.get< DomainType >( \"boundary_layer\")),\n cfg.get(\"value\", default_cfg.get< RangeType >( \"value\")),\n cfg.get(\"name\", default_cfg.get< std::string >(\"name\")));\n } \/\/ ... create(...)\n\n FlatTop(const StuffDomainType& lower_left,\n const StuffDomainType& upper_right,\n const StuffDomainType& boundary_layer,\n const StuffRangeType& value = default_config().get< StuffRangeType >(\"value\"),\n const std::string name = default_config().get< std::string >(\"name\"))\n : lower_left_(lower_left)\n , upper_right_(upper_right)\n , boundary_layer_(boundary_layer)\n , value_(value)\n , name_(name)\n {\n check_input();\n }\n\n FlatTop(const ThisType& other)\n : lower_left_(other.lower_left_)\n , upper_right_(other.upper_right_)\n , boundary_layer_(other.boundary_layer_)\n , value_(other.value_)\n , name_(other.name_)\n {}\n\n ThisType& operator=(const ThisType& other) = delete;\n\n virtual ~FlatTop() {}\n\n virtual ThisType* copy() const \/*DS_OVERRIDE DS_FINAL*\/\n {\n return new ThisType(*this);\n }\n\n virtual std::string type() const \/*DS_OVERRIDE DS_FINAL*\/\n {\n return BaseType::static_id() + \".flattop\";\n }\n\n virtual std::string name() const \/*DS_OVERRIDE DS_FINAL*\/\n {\n return name_;\n }\n\n virtual size_t order() const\n {\n \/\/ could be 3 but I am to lazy\n return 4;\n } \/\/ ... order(...)\n\n virtual void evaluate(const DomainType& xx, RangeType& ret) const\n {\n ret = value_;\n for (size_t dd = 0; dd < dimDomain; ++dd) {\n const auto& left = lower_left_[dd];\n const auto& right = upper_right_[dd];\n const auto& point = xx[dd];\n const auto& delta = boundary_layer_[dd];\n if (point < left - delta) {\n \/\/ outside\n ret[0] = 0.0;\n break;\n } else if (point < left + delta) {\n \/\/ left boundary layer\n ret[0] *= phi_left((point - (left + delta)) \/ (2.0*delta));\n } else if (point < right - delta) {\n \/\/ inside\n \/\/ do nothing (keep value)\n } else if (point < right + delta) {\n \/\/ right boundary layer\n ret[0] *= phi_right((point - (right - delta)) \/ (2.0*delta));\n } else {\n \/\/ outside\n ret[0] = 0.0;\n break;\n }\n }\n } \/\/ ... evaluate(...)\n\nprivate:\n void check_input() const\n {\n if (!(Common::FloatCmp::gt(upper_right_, lower_left_)))\n DUNE_THROW(Exceptions::wrong_input_given,\n \"upper_right has to be greater than lower_left!\\n\"\n << \"lower_left = [\" << lower_left_ << \"]\\n\"\n << \"upper_right = [\" << upper_right_ << \"]\");\n if (!(Common::FloatCmp::gt(boundary_layer_, StuffDomainType(0))))\n DUNE_THROW(Exceptions::wrong_input_given,\n \"boundary_layer has to be strictly positive!\\n\"\n << \"boundary_layer = [\" << boundary_layer_ << \"]\");\n if (Common::FloatCmp::gt(boundary_layer_*2.0, upper_right_ - lower_left_))\n DUNE_THROW(Exceptions::wrong_input_given,\n \"boundary_layer has to be thin enough!\\n\"\n \"2*boundary_layer = [\" << boundary_layer_*2.0 << \"]\\n\"\n << \"upper_right - lower_left = [\" << upper_right_ - lower_left_ << \"]\");\n } \/\/ .. check_input(...)\n\n RangeFieldType phi_left(const RangeFieldType& point) const\n {\n assert(!(point < -1.0));\n assert(!(point > 0.0));\n return std::pow(1.0 + point, 2)*(1.0 - 2.0*point);\n } \/\/ ... phi_left(...)\n\n RangeFieldType phi_right(const RangeFieldType& point) const\n {\n assert(!(point < 0.0));\n assert(!(point > 1.0));\n return std::pow(1.0 - point, 2)*(1.0 + 2.0*point);\n } \/\/ ... phi_right(...)\n\n const StuffDomainType lower_left_;\n const StuffDomainType upper_right_;\n const StuffDomainType boundary_layer_;\n const StuffRangeType value_;\n const std::string name_;\n}; \/\/ class FlatTop< ..., 1, 1 >\n\n\n} \/\/ namespace Functions\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTIONS_FLATTOP_HH\n[functions.flattop] drop assertions in transition region\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_STUFF_FUNCTIONS_FLATTOP_HH\n#define DUNE_STUFF_FUNCTIONS_FLATTOP_HH\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Dune {\nnamespace Stuff {\nnamespace Functions {\n\n\n\/**\n * Based on: Brenner, S. C. and Davis, C. B. and Sung, L.-y.\n * A partition of unity method for the displacement obstacle problem of clamped Kirchhoff plates\n * http:\/\/dx.doi.org\/10.1016\/j.cam.2013.09.033\n * Subsection 2.1.1\n *\/\ntemplate< class E, class D, int d, class R, int r, int rC = 1 >\nclass FlatTop\n : public LocalizableFunctionInterface< E, D, d, R, r, rC >\n{\n FlatTop() { static_assert(AlwaysFalse< E >::value, \"Not available for these dimensions!\"); }\n};\n\n\ntemplate< class E, class D, int d, class R >\nclass FlatTop< E, D, d, R, 1, 1 >\n : public GlobalFunctionInterface< E, D, d, R, 1, 1 >\n{\n typedef GlobalFunctionInterface< E, D, d, R, 1, 1 > BaseType;\n typedef FlatTop< E, D, d, R, 1, 1 > ThisType;\n\npublic:\n typedef typename BaseType::EntityType EntityType;\n typedef typename BaseType::DomainFieldType DomainFieldType;\n static const unsigned int dimDomain = BaseType::dimDomain;\n typedef typename BaseType::DomainType DomainType;\n typedef typename BaseType::RangeFieldType RangeFieldType;\n static const unsigned int dimRange = BaseType::dimRange;\n typedef typename BaseType::RangeType RangeType;\n\n typedef Common::FieldVector< DomainFieldType, dimDomain > StuffDomainType;\n typedef Common::FieldVector< RangeFieldType, dimRange > StuffRangeType;\n\n static const bool available = true;\n\n static std::string static_id()\n {\n return BaseType::static_id() + \".flattop\";\n }\n\n static Common::Configuration default_config(const std::string sub_name = \"\")\n {\n Common::Configuration config;\n config[\"lower_left\"] = \"[0.0 0.0 0.0]\";\n config[\"upper_right\"] = \"[1.0 1.0 1.0]\";\n config[\"boundary_layer\"] = \"[1e-1 1e-1 1e-1]\";\n config[\"value\"] = \"1.0\";\n config[\"name\"] = static_id();\n if (sub_name.empty())\n return config;\n else {\n Common::Configuration tmp;\n tmp.add(config, sub_name);\n return tmp;\n }\n } \/\/ ... default_config(...)\n\n static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(),\n const std::string sub_name = static_id())\n {\n \/\/ get correct config\n const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;\n const Common::Configuration default_cfg = default_config();\n return Common::make_unique< ThisType >(\n cfg.get(\"lower_left\", default_cfg.get< DomainType >( \"lower_left\")),\n cfg.get(\"upper_right\", default_cfg.get< DomainType >( \"upper_right\")),\n cfg.get(\"boundary_layer\", default_cfg.get< DomainType >( \"boundary_layer\")),\n cfg.get(\"value\", default_cfg.get< RangeType >( \"value\")),\n cfg.get(\"name\", default_cfg.get< std::string >(\"name\")));\n } \/\/ ... create(...)\n\n FlatTop(const StuffDomainType& lower_left,\n const StuffDomainType& upper_right,\n const StuffDomainType& boundary_layer,\n const StuffRangeType& value = default_config().get< StuffRangeType >(\"value\"),\n const std::string name = default_config().get< std::string >(\"name\"))\n : lower_left_(lower_left)\n , upper_right_(upper_right)\n , boundary_layer_(boundary_layer)\n , value_(value)\n , name_(name)\n {\n check_input();\n }\n\n FlatTop(const ThisType& other)\n : lower_left_(other.lower_left_)\n , upper_right_(other.upper_right_)\n , boundary_layer_(other.boundary_layer_)\n , value_(other.value_)\n , name_(other.name_)\n {}\n\n ThisType& operator=(const ThisType& other) = delete;\n\n virtual ~FlatTop() {}\n\n virtual ThisType* copy() const \/*DS_OVERRIDE DS_FINAL*\/\n {\n return new ThisType(*this);\n }\n\n virtual std::string type() const \/*DS_OVERRIDE DS_FINAL*\/\n {\n return BaseType::static_id() + \".flattop\";\n }\n\n virtual std::string name() const \/*DS_OVERRIDE DS_FINAL*\/\n {\n return name_;\n }\n\n virtual size_t order() const\n {\n \/\/ could be 3 but I am to lazy\n return 4;\n } \/\/ ... order(...)\n\n virtual void evaluate(const DomainType& xx, RangeType& ret) const\n {\n ret = value_;\n for (size_t dd = 0; dd < dimDomain; ++dd) {\n const auto& left = lower_left_[dd];\n const auto& right = upper_right_[dd];\n const auto& point = xx[dd];\n const auto& delta = boundary_layer_[dd];\n if (point < left - delta) {\n \/\/ outside\n ret[0] = 0.0;\n break;\n } else if (point < left + delta) {\n \/\/ left boundary layer\n ret[0] *= phi_left((point - (left + delta)) \/ (2.0*delta));\n } else if (point < right - delta) {\n \/\/ inside\n \/\/ do nothing (keep value)\n } else if (point < right + delta) {\n \/\/ right boundary layer\n ret[0] *= phi_right((point - (right - delta)) \/ (2.0*delta));\n } else {\n \/\/ outside\n ret[0] = 0.0;\n break;\n }\n }\n } \/\/ ... evaluate(...)\n\nprivate:\n void check_input() const\n {\n if (!(Common::FloatCmp::gt(upper_right_, lower_left_)))\n DUNE_THROW(Exceptions::wrong_input_given,\n \"upper_right has to be greater than lower_left!\\n\"\n << \"lower_left = [\" << lower_left_ << \"]\\n\"\n << \"upper_right = [\" << upper_right_ << \"]\");\n if (!(Common::FloatCmp::gt(boundary_layer_, StuffDomainType(0))))\n DUNE_THROW(Exceptions::wrong_input_given,\n \"boundary_layer has to be strictly positive!\\n\"\n << \"boundary_layer = [\" << boundary_layer_ << \"]\");\n if (Common::FloatCmp::gt(boundary_layer_*2.0, upper_right_ - lower_left_))\n DUNE_THROW(Exceptions::wrong_input_given,\n \"boundary_layer has to be thin enough!\\n\"\n \"2*boundary_layer = [\" << boundary_layer_*2.0 << \"]\\n\"\n << \"upper_right - lower_left = [\" << upper_right_ - lower_left_ << \"]\");\n } \/\/ .. check_input(...)\n\n RangeFieldType phi_left(const RangeFieldType& point) const\n {\n if (point < -1.0)\n return 0.0;\n else if (point > 0.0)\n return 1.0;\n else\n return std::pow(1.0 + point, 2)*(1.0 - 2.0*point);\n } \/\/ ... phi_left(...)\n\n RangeFieldType phi_right(const RangeFieldType& point) const\n {\n if (point < 0.0)\n return 1.0;\n else if (point > 1.0)\n return 0.0;\n else\n return std::pow(1.0 - point, 2)*(1.0 + 2.0*point);\n } \/\/ ... phi_right(...)\n\n const StuffDomainType lower_left_;\n const StuffDomainType upper_right_;\n const StuffDomainType boundary_layer_;\n const StuffRangeType value_;\n const std::string name_;\n}; \/\/ class FlatTop< ..., 1, 1 >\n\n\n} \/\/ namespace Functions\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTIONS_FLATTOP_HH\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 Project Vogue. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"elang\/compiler\/ast\/namespace.h\"\n\n#include \"base\/logging.h\"\n#include \"elang\/compiler\/ast\/alias.h\"\n#include \"elang\/compiler\/ast\/class.h\"\n#include \"elang\/compiler\/ast\/namespace_body.h\"\n#include \"elang\/compiler\/modifiers_builder.h\"\n#include \"elang\/compiler\/token_type.h\"\n\nnamespace elang {\nnamespace compiler {\nnamespace ast {\n\nnamespace {\nModifiers GetNamespaceModifiers() {\n ModifiersBuilder builder;\n builder.SetPublic();\n return builder.Get();\n}\n} \/\/ namespace\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ MemberContainer\n\/\/\nMemberContainer::MemberContainer(Zone* zone,\n NamespaceBody* namespace_body,\n Modifiers modifiers,\n Token* keyword,\n Token* name)\n : NamespaceMember(namespace_body, modifiers, keyword, name),\n bodies_(zone),\n map_(zone) {\n}\n\nvoid MemberContainer::AcceptForMembers(Visitor* visitor) {\n for (auto const name_member : map_)\n name_member.second->Accept(visitor);\n}\n\nvoid MemberContainer::AddMember(NamespaceMember* member) {\n DCHECK_EQ(this, member->owner());\n DCHECK(!member->is());\n \/\/ We keep first member declaration.\n if (FindMember(member->name()))\n return;\n map_[member->name()->simple_name()] = member;\n}\n\nvoid MemberContainer::AddNamespaceBody(NamespaceBody* namespace_body) {\n bodies_.push_back(namespace_body);\n}\n\nNamespaceMember* MemberContainer::FindMember(AtomicString* name) {\n auto const it = map_.find(name);\n return it == map_.end() ? nullptr : it->second;\n}\n\nNamespaceMember* MemberContainer::FindMember(Token* name) {\n return FindMember(name->simple_name());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Namespace\n\/\/\nNamespace::Namespace(Zone* zone,\n NamespaceBody* namespace_body,\n Token* keyword,\n Token* name)\n : MemberContainer(zone,\n namespace_body,\n GetNamespaceModifiers(),\n keyword,\n name) {\n DCHECK_EQ(keyword, TokenType::Namespace);\n}\n\n} \/\/ namespace ast\n} \/\/ namespace compiler\n} \/\/ namespace elang\nelang\/compiler\/ast: Make |MemberContainer::AcceptForMembers()| to accept for all members including |Alias| and |Import|.\/\/ Copyright 2014 Project Vogue. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"elang\/compiler\/ast\/namespace.h\"\n\n#include \"base\/logging.h\"\n#include \"elang\/compiler\/ast\/alias.h\"\n#include \"elang\/compiler\/ast\/class.h\"\n#include \"elang\/compiler\/ast\/namespace_body.h\"\n#include \"elang\/compiler\/modifiers_builder.h\"\n#include \"elang\/compiler\/token_type.h\"\n\nnamespace elang {\nnamespace compiler {\nnamespace ast {\n\nnamespace {\nModifiers GetNamespaceModifiers() {\n ModifiersBuilder builder;\n builder.SetPublic();\n return builder.Get();\n}\n} \/\/ namespace\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ MemberContainer\n\/\/\nMemberContainer::MemberContainer(Zone* zone,\n NamespaceBody* namespace_body,\n Modifiers modifiers,\n Token* keyword,\n Token* name)\n : NamespaceMember(namespace_body, modifiers, keyword, name),\n bodies_(zone),\n map_(zone) {\n}\n\nvoid MemberContainer::AcceptForMembers(Visitor* visitor) {\n for (auto const body : bodies_) {\n for (auto const member : body->members())\n member->Accept(visitor);\n }\n}\n\nvoid MemberContainer::AddMember(NamespaceMember* member) {\n DCHECK_EQ(this, member->owner());\n DCHECK(!member->is());\n \/\/ We keep first member declaration.\n if (FindMember(member->name()))\n return;\n map_[member->name()->simple_name()] = member;\n}\n\nvoid MemberContainer::AddNamespaceBody(NamespaceBody* namespace_body) {\n bodies_.push_back(namespace_body);\n}\n\nNamespaceMember* MemberContainer::FindMember(AtomicString* name) {\n auto const it = map_.find(name);\n return it == map_.end() ? nullptr : it->second;\n}\n\nNamespaceMember* MemberContainer::FindMember(Token* name) {\n return FindMember(name->simple_name());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Namespace\n\/\/\nNamespace::Namespace(Zone* zone,\n NamespaceBody* namespace_body,\n Token* keyword,\n Token* name)\n : MemberContainer(zone,\n namespace_body,\n GetNamespaceModifiers(),\n keyword,\n name) {\n DCHECK_EQ(keyword, TokenType::Namespace);\n}\n\n} \/\/ namespace ast\n} \/\/ namespace compiler\n} \/\/ namespace elang\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"IMU_Detector.h\"\n#include \"Mahony_Filter.h\"\n#include \"Complementary_Filter.h\"\n\n\nusing namespace flyhero;\n\nQueueHandle_t data_queue;\n\nvoid imu_task(void *args);\nvoid log_task(void *args);\n\n\nextern \"C\" void app_main(void)\n{\n \/\/ Initialize NVS\n esp_err_t nvs_status = nvs_flash_init();\n\n if (nvs_status == ESP_ERR_NVS_NO_FREE_PAGES)\n {\n ESP_ERROR_CHECK(nvs_flash_erase());\n ESP_ERROR_CHECK(nvs_flash_init());\n }\n\n data_queue = xQueueCreate(10, sizeof(IMU::Euler_Angles));\n\n xTaskCreatePinnedToCore(log_task, \"Log task\", 4096, NULL, 2, NULL, 1);\n xTaskCreatePinnedToCore(imu_task, \"IMU task\", 4096, NULL, 2, NULL, 0);\n}\n\nvoid imu_task(void *args)\n{\n IMU& imu = IMU_Detector::Detect_IMU();\n\n imu.Init();\n\n while (!imu.Start())\n {\n std::cout << \"Calibrating...\" << std::endl;\n imu.Calibrate();\n }\n\n \/\/Mahony_Filter mahony(100, 0);\n Complementary_Filter complementary(0.98f);\n\n IMU::Sensor_Data accel, gyro;\n IMU::Euler_Angles euler;\n\n uint8_t i = 0;\n\n while (true)\n {\n if (imu.Data_Ready())\n {\n imu.Read_Data(accel, gyro);\n\n \/\/mahony.Compute(accel, gyro, euler);\n complementary.Compute(accel, gyro, euler);\n\n i++;\n\n if (i % 100 == 0)\n {\n i = 0;\n\n if (xQueueSendToBack(data_queue, &euler, 0) != pdTRUE)\n break;\n }\n }\n }\n}\n\nvoid log_task(void *args)\n{\n IMU::Euler_Angles euler;\n\n while (true)\n {\n if (xQueueReceive(data_queue, &euler, 0) == pdTRUE)\n std::cout << euler.roll << \" \" << euler.pitch << \" \" << euler.yaw << std::endl;\n }\n}(IMU main): print euler data at same frequency for every IMU#include \n#include \n#include \n\n#include \"IMU_Detector.h\"\n#include \"Mahony_Filter.h\"\n#include \"Complementary_Filter.h\"\n\n\nusing namespace flyhero;\n\nQueueHandle_t data_queue;\n\nvoid imu_task(void *args);\nvoid log_task(void *args);\n\n\nextern \"C\" void app_main(void)\n{\n \/\/ Initialize NVS\n esp_err_t nvs_status = nvs_flash_init();\n\n if (nvs_status == ESP_ERR_NVS_NO_FREE_PAGES)\n {\n ESP_ERROR_CHECK(nvs_flash_erase());\n ESP_ERROR_CHECK(nvs_flash_init());\n }\n\n data_queue = xQueueCreate(10, sizeof(IMU::Euler_Angles));\n\n xTaskCreatePinnedToCore(log_task, \"Log task\", 4096, NULL, 2, NULL, 1);\n xTaskCreatePinnedToCore(imu_task, \"IMU task\", 4096, NULL, 2, NULL, 0);\n}\n\nvoid imu_task(void *args)\n{\n IMU& imu = IMU_Detector::Detect_IMU();\n\n imu.Init();\n\n while (!imu.Start())\n {\n std::cout << \"Calibrating...\" << std::endl;\n imu.Calibrate();\n }\n\n \/\/Mahony_Filter mahony(100, 0);\n Complementary_Filter complementary(0.98f);\n\n IMU::Sensor_Data accel, gyro;\n IMU::Euler_Angles euler;\n\n uint8_t i = 0;\n\n while (true)\n {\n if (imu.Data_Ready())\n {\n imu.Read_Data(accel, gyro);\n\n \/\/mahony.Compute(accel, gyro, euler);\n complementary.Compute(accel, gyro, euler);\n\n i++;\n\n if (i == imu.Get_Sample_Rate() \/ 10)\n {\n i = 0;\n\n if (xQueueSendToBack(data_queue, &euler, 0) != pdTRUE)\n break;\n }\n }\n }\n}\n\nvoid log_task(void *args)\n{\n IMU::Euler_Angles euler;\n\n while (true)\n {\n if (xQueueReceive(data_queue, &euler, 0) == pdTRUE)\n std::cout << euler.roll << \" \" << euler.pitch << \" \" << euler.yaw << std::endl;\n }\n}<|endoftext|>"} {"text":"\n\/**\n * This file is part of the boostcache package.\n *\n * (c) Azat Khuzhin \n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n *\/\n\n#include \"avltree.h\"\n\nnamespace Db\n{\n std::hash AvlTree::m_keyHashFunction = std::hash();\n\n AvlTree::AvlTree()\n : Interface()\n , m_deleteDisposer(m_nodes)\n , m_tree(new Tree)\n {\n }\n\n std::string AvlTree::get(const CommandHandler::Arguments &arguments)\n {\n Node findMe(arguments[1]);\n\n \/\/ get shared lock\n boost::shared_lock lock(m_access);\n\n Tree::const_iterator found = m_tree->find(findMe);\n if (found == m_tree->end()) {\n return CommandHandler::REPLY_NIL;\n }\n return CommandHandler::toReplyString(found->get().value);\n }\n\n std::string AvlTree::set(const CommandHandler::Arguments &arguments)\n {\n \/\/ get exclusive lock\n boost::upgrade_lock lock(m_access);\n boost::upgrade_to_unique_lock uniqueLock(lock);\n\n Node findMe(arguments[1]);\n Tree::iterator found = m_tree->find(findMe);\n if (found != m_tree->end()) {\n found->get().value = arguments[2] \/* value *\/;\n return CommandHandler::REPLY_OK;\n }\n\n m_nodes.push_back(Node(Node::Data(arguments[1] \/* key *\/,\n arguments[2] \/* value *\/)));\n m_nodes.back().get().listIterator = --m_nodes.end();\n m_tree->insert_unique(m_nodes.back());\n\n return CommandHandler::REPLY_OK;\n }\n\n std::string AvlTree::del(const CommandHandler::Arguments &arguments)\n {\n \/\/ get exclusive lock\n boost::upgrade_lock lock(m_access);\n boost::upgrade_to_unique_lock uniqueLock(lock);\n\n Node findMe(arguments[1]);\n Tree::const_iterator found = m_tree->find(findMe);\n if (found == m_tree->end()) {\n return CommandHandler::REPLY_FALSE;\n }\n m_tree->erase_and_dispose(found, m_deleteDisposer);\n\n return CommandHandler::REPLY_OK;\n }\n}\n[db] avltree: del(): return REPLY_TRUE instead of REPLY_OK\n\/**\n * This file is part of the boostcache package.\n *\n * (c) Azat Khuzhin \n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n *\/\n\n#include \"avltree.h\"\n\nnamespace Db\n{\n std::hash AvlTree::m_keyHashFunction = std::hash();\n\n AvlTree::AvlTree()\n : Interface()\n , m_deleteDisposer(m_nodes)\n , m_tree(new Tree)\n {\n }\n\n std::string AvlTree::get(const CommandHandler::Arguments &arguments)\n {\n Node findMe(arguments[1]);\n\n \/\/ get shared lock\n boost::shared_lock lock(m_access);\n\n Tree::const_iterator found = m_tree->find(findMe);\n if (found == m_tree->end()) {\n return CommandHandler::REPLY_NIL;\n }\n return CommandHandler::toReplyString(found->get().value);\n }\n\n std::string AvlTree::set(const CommandHandler::Arguments &arguments)\n {\n \/\/ get exclusive lock\n boost::upgrade_lock lock(m_access);\n boost::upgrade_to_unique_lock uniqueLock(lock);\n\n Node findMe(arguments[1]);\n Tree::iterator found = m_tree->find(findMe);\n if (found != m_tree->end()) {\n found->get().value = arguments[2] \/* value *\/;\n return CommandHandler::REPLY_OK;\n }\n\n m_nodes.push_back(Node(Node::Data(arguments[1] \/* key *\/,\n arguments[2] \/* value *\/)));\n m_nodes.back().get().listIterator = --m_nodes.end();\n m_tree->insert_unique(m_nodes.back());\n\n return CommandHandler::REPLY_OK;\n }\n\n std::string AvlTree::del(const CommandHandler::Arguments &arguments)\n {\n \/\/ get exclusive lock\n boost::upgrade_lock lock(m_access);\n boost::upgrade_to_unique_lock uniqueLock(lock);\n\n Node findMe(arguments[1]);\n Tree::const_iterator found = m_tree->find(findMe);\n if (found == m_tree->end()) {\n return CommandHandler::REPLY_FALSE;\n }\n m_tree->erase_and_dispose(found, m_deleteDisposer);\n\n return CommandHandler::REPLY_TRUE;\n }\n}\n<|endoftext|>"} {"text":"\/\/ @(#)root\/hist:$Id$\n\/\/ Author: Rene Brun 14\/07\/2009\n\n\/*************************************************************************\n * Copyright (C) 1995-2009, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TGraphTime.h\"\n#include \"TVirtualPad.h\"\n#include \"TH1.h\"\n#include \"TROOT.h\"\n#include \"TObjArray.h\"\n#include \"TSystem.h\"\n\nClassImp(TGraphTime)\n\n\/\/______________________________________________________________________________\n\/\/\n\/\/ TGraphTime is used to draw a set of objects evolving with nsteps in time between tmin and tmax.\n\/\/ each time step has a new list of objects. This list can be identical to\n\/\/ the list of objects in the previous steps, but with different attributes.\n\/\/ see example of use in $ROOTSYS\/tutorials\/graphs\/gtime.C\n\n\/\/______________________________________________________________________________\nTGraphTime::TGraphTime(): TNamed()\n{\n \/\/ default constructor.\n\n fSleepTime = 0;\n fNsteps = 0;\n fXmin = 0;\n fXmax = 1;\n fYmin = 0;\n fYmax = 1;\n fSteps = 0;\n fFrame = 0;\n}\n\n\n\/\/______________________________________________________________________________\nTGraphTime::TGraphTime(Int_t nsteps, Double_t xmin, Double_t ymin, Double_t xmax, Double_t ymax)\n :TNamed()\n{\n \/\/ Create a TGraphTime with nsteps in range [xmin,xmax][ymin,ymax]\n\n if (nsteps <= 0) {\n Warning(\"TGraphTime\", \"Number of steps %d changed to 100\",nsteps);\n nsteps = 100;\n }\n fSleepTime = 0;\n fNsteps = nsteps;\n fXmin = xmin;\n fXmax = xmax;\n fYmin = ymin;\n fYmax = ymax;\n fSteps = new TObjArray(nsteps+1);\n fFrame = new TH1D(\"frame\",\"\",100,fXmin,fXmax);\n fFrame->SetMinimum(ymin);\n fFrame->SetMaximum(ymax);\n fFrame->SetStats(0);\n}\n\n\n\/\/______________________________________________________________________________\nTGraphTime::~TGraphTime()\n{\n \/\/ GraphTime default destructor.\n \n if (!fSteps) return;\n fSteps->Delete();\n delete fSteps; fSteps=0;\n}\n\n\n\/\/______________________________________________________________________________\nTGraphTime::TGraphTime(const TGraphTime >ime) : TNamed(gtime)\n{\n \/\/ copy constructor.\n\n fSleepTime = gtime.fSleepTime;\n fNsteps = gtime.fNsteps;\n fXmin = gtime.fXmin;\n fXmax = gtime.fXmax;\n fYmin = gtime.fYmin;\n fYmax = gtime.fYmax;\n fSteps = new TObjArray(fNsteps+1);\n fFrame = new TH1D(\"frame\",\"\",100,fXmin,fXmax);\n fFrame->SetMinimum(fYmin);\n fFrame->SetMaximum(fYmax);\n fFrame->SetStats(0);\n}\n\n\/\/______________________________________________________________________________\nInt_t TGraphTime::Add(const TObject *obj, Int_t slot, Option_t *option)\n{\n \/\/ Add one object to a time slot. \n \/\/ TGraphTime becomes the owner of this object.\n \/\/ object will be drawn with option\n \n if (!fSteps) {\n fNsteps = 100;\n fSteps = new TObjArray(fNsteps+1);\n }\n if (slot < 0 || slot >= fNsteps) return -1;\n TList *list = (TList*)fSteps->UncheckedAt(slot);\n if (!list) {\n list = new TList();\n fSteps->AddAt(list,slot);\n }\n list->Add((TObject*)obj, option);\n return slot;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TGraphTime::Draw(Option_t *option)\n{\n \/\/ Draw this TGraphTime.\n \/\/ for each time step the list of objects added to this step are drawn.\n \n if (!gPad) {\n gROOT->MakeDefCanvas();\n gPad->SetFillColor(41);\n gPad->SetFrameFillColor(19);\n gPad->SetGrid();\n }\n if (fFrame) {\n fFrame->SetTitle(GetTitle());\n fFrame->Draw();\n }\n Paint(option);\n\n}\n\n\/\/______________________________________________________________________________\nvoid TGraphTime::Paint(Option_t *option)\n{\n \/\/ Paint all objects added to each time step\n \n TString opt = option;\n opt.ToLower();\n TObject *frame = gPad->GetPrimitive(\"frame\");\n TList *list = 0;\n\n for (Int_t s=0;sUncheckedAt(s);\n if (list) {\n gPad->GetListOfPrimitives()->Remove(frame);\n gPad->GetListOfPrimitives()->Clear();\n if (frame) gPad->GetListOfPrimitives()->Add(frame);\n list->Draw(\"\");\n gPad->Update();\n if (fSleepTime > 0) gSystem->Sleep(fSleepTime);\n }\n }\n}\nUse effectively the objects draw options when specified.\/\/ @(#)root\/hist:$Id$\n\/\/ Author: Rene Brun 14\/07\/2009\n\n\/*************************************************************************\n * Copyright (C) 1995-2009, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TGraphTime.h\"\n#include \"TVirtualPad.h\"\n#include \"TH1.h\"\n#include \"TROOT.h\"\n#include \"TObjArray.h\"\n#include \"TSystem.h\"\n\nClassImp(TGraphTime)\n\n\/\/______________________________________________________________________________\n\/\/\n\/\/ TGraphTime is used to draw a set of objects evolving with nsteps in time between tmin and tmax.\n\/\/ each time step has a new list of objects. This list can be identical to\n\/\/ the list of objects in the previous steps, but with different attributes.\n\/\/ see example of use in $ROOTSYS\/tutorials\/graphs\/gtime.C\n\n\/\/______________________________________________________________________________\nTGraphTime::TGraphTime(): TNamed()\n{\n \/\/ default constructor.\n\n fSleepTime = 0;\n fNsteps = 0;\n fXmin = 0;\n fXmax = 1;\n fYmin = 0;\n fYmax = 1;\n fSteps = 0;\n fFrame = 0;\n}\n\n\n\/\/______________________________________________________________________________\nTGraphTime::TGraphTime(Int_t nsteps, Double_t xmin, Double_t ymin, Double_t xmax, Double_t ymax)\n :TNamed()\n{\n \/\/ Create a TGraphTime with nsteps in range [xmin,xmax][ymin,ymax]\n\n if (nsteps <= 0) {\n Warning(\"TGraphTime\", \"Number of steps %d changed to 100\",nsteps);\n nsteps = 100;\n }\n fSleepTime = 0;\n fNsteps = nsteps;\n fXmin = xmin;\n fXmax = xmax;\n fYmin = ymin;\n fYmax = ymax;\n fSteps = new TObjArray(nsteps+1);\n fFrame = new TH1D(\"frame\",\"\",100,fXmin,fXmax);\n fFrame->SetMinimum(ymin);\n fFrame->SetMaximum(ymax);\n fFrame->SetStats(0);\n}\n\n\n\/\/______________________________________________________________________________\nTGraphTime::~TGraphTime()\n{\n \/\/ GraphTime default destructor.\n \n if (!fSteps) return;\n fSteps->Delete();\n delete fSteps; fSteps=0;\n}\n\n\n\/\/______________________________________________________________________________\nTGraphTime::TGraphTime(const TGraphTime >ime) : TNamed(gtime)\n{\n \/\/ copy constructor.\n\n fSleepTime = gtime.fSleepTime;\n fNsteps = gtime.fNsteps;\n fXmin = gtime.fXmin;\n fXmax = gtime.fXmax;\n fYmin = gtime.fYmin;\n fYmax = gtime.fYmax;\n fSteps = new TObjArray(fNsteps+1);\n fFrame = new TH1D(\"frame\",\"\",100,fXmin,fXmax);\n fFrame->SetMinimum(fYmin);\n fFrame->SetMaximum(fYmax);\n fFrame->SetStats(0);\n}\n\n\/\/______________________________________________________________________________\nInt_t TGraphTime::Add(const TObject *obj, Int_t slot, Option_t *option)\n{\n \/\/ Add one object to a time slot. \n \/\/ TGraphTime becomes the owner of this object.\n \/\/ object will be drawn with option\n \n if (!fSteps) {\n fNsteps = 100;\n fSteps = new TObjArray(fNsteps+1);\n }\n if (slot < 0 || slot >= fNsteps) return -1;\n TList *list = (TList*)fSteps->UncheckedAt(slot);\n if (!list) {\n list = new TList();\n fSteps->AddAt(list,slot);\n }\n list->Add((TObject*)obj, option);\n return slot;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TGraphTime::Draw(Option_t *option)\n{\n \/\/ Draw this TGraphTime.\n \/\/ for each time step the list of objects added to this step are drawn.\n \n if (!gPad) {\n gROOT->MakeDefCanvas();\n gPad->SetFillColor(41);\n gPad->SetFrameFillColor(19);\n gPad->SetGrid();\n }\n if (fFrame) {\n fFrame->SetTitle(GetTitle());\n fFrame->Draw();\n }\n Paint(option);\n\n}\n\n\/\/______________________________________________________________________________\nvoid TGraphTime::Paint(Option_t *option)\n{\n \/\/ Paint all objects added to each time step\n \n TString opt = option;\n opt.ToLower();\n TObject *frame = gPad->GetPrimitive(\"frame\");\n TList *list = 0;\n TObjLink *lnk;\n\n for (Int_t s=0;sUncheckedAt(s);\n if (list) {\n gPad->GetListOfPrimitives()->Remove(frame);\n gPad->GetListOfPrimitives()->Clear();\n if (frame) gPad->GetListOfPrimitives()->Add(frame);\n lnk = list->FirstLink();\n while(lnk) {\n TObject *obj = lnk->GetObject();\n obj->Draw(lnk->GetAddOption());\n lnk = lnk->Next();\n }\n gPad->Update();\n if (fSleepTime > 0) gSystem->Sleep(fSleepTime);\n }\n }\n}\n<|endoftext|>"} {"text":"\/**\n * \\file dcs\/memory.hpp\n *\n * \\brief Smart pointers are objects which store pointers to dynamically\n * allocated (heap) objects.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * \n *\n * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef DCS_SMART_PTR_HPP\n#define DCS_SMART_PTR_HPP\n\n\n#if __cplusplus > 201103L\n\/\/ C++0x has smart-pointers\n# \tinclude \n# \tdefine DCS_MEMORY_NS_ ::std\n#else\n\/\/ Use Boost smart-pointers\n# \tinclude \n# \tif !DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(102300)\n# \t\terror \"Required Boost library version >= 1.23.\"\n# \tendif\n# \tinclude \n# \tinclude \n# \tdefine DCS_MEMORY_NS_ ::boost\n#endif \/\/ __cplusplus\n\n\nnamespace dcs {\n\n\/\/\/ Object ownership shared among multiple pointers (\\sa \\c boost::shared_ptr).\nusing DCS_MEMORY_NS_::shared_ptr;\n\/\/\/ Non-owning observers of an object owned by \\c shared_ptr.\nusing DCS_MEMORY_NS_::weak_ptr;\n\/\/\/\nusing DCS_MEMORY_NS_::static_pointer_cast;\n\/\/\/\nusing DCS_MEMORY_NS_::dynamic_pointer_cast;\n\/\/\/\nusing DCS_MEMORY_NS_::const_pointer_cast;\n\/\/\/\nusing DCS_MEMORY_NS_::get_deleter;\n\/\/\/\nusing DCS_MEMORY_NS_::swap;\n\/\/\/\n\/\/using DCS_MEMORY_NS_::owner_less;\n\/\/\/\nusing DCS_MEMORY_NS_::enable_shared_from_this;\n\/\/\/\nusing DCS_MEMORY_NS_::make_shared;\n\/\/\/\nusing DCS_MEMORY_NS_::allocate_shared;\n\n\/\/\/ Shared ownership of objects with an embedded reference count.\nusing ::boost::intrusive_ptr;\n\/\/\/ Array ownership shared among multiple pointers.\nusing ::boost::shared_array;\n\/\/\/ Simple sole ownership of arrays. Noncopyable.\nusing ::boost::scoped_array;\n\/\/\/ Simple sole ownership of single objects. Noncopyable.\nusing ::boost::scoped_ptr;\n\/\/\/\nusing ::boost::get_pointer;\n\n} \/\/ Namespace dcs\n\n\n#endif \/\/ DCS_SMART_PTR_HPP\n[memory] Added functions for converting an std::shared_ptr to boost::shared_ptr and vice versa\/**\n * \\file dcs\/memory.hpp\n *\n * \\brief Smart pointers are objects which store pointers to dynamically\n * allocated (heap) objects.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * \n *\n * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef DCS_SMART_PTR_HPP\n#define DCS_SMART_PTR_HPP\n\n#include \n\n#ifdef DCS_MACRO_CXX11\n\/\/ C++11 has smart-pointers\n# \tinclude \n# \tdefine DCS_MEMORY_NS_ ::std\n#else\n\/\/ Use Boost smart-pointers\n# \tinclude \n# \tif !DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(102300)\n# \t\terror \"Required Boost library version >= 1.23.\"\n# \tendif\n# \tinclude \n# \tinclude \n# \tdefine DCS_MEMORY_NS_ ::boost\n#endif \/\/ DCS_MACRO_CXX11\n\n\nnamespace dcs {\n\n\/\/\/ Object ownership shared among multiple pointers (\\sa \\c boost::shared_ptr).\nusing DCS_MEMORY_NS_::shared_ptr;\n\/\/\/ Non-owning observers of an object owned by \\c shared_ptr.\nusing DCS_MEMORY_NS_::weak_ptr;\n\/\/\/\nusing DCS_MEMORY_NS_::static_pointer_cast;\n\/\/\/\nusing DCS_MEMORY_NS_::dynamic_pointer_cast;\n\/\/\/\nusing DCS_MEMORY_NS_::const_pointer_cast;\n\/\/\/\nusing DCS_MEMORY_NS_::get_deleter;\n\/\/\/\nusing DCS_MEMORY_NS_::swap;\n\/\/\/\n\/\/using DCS_MEMORY_NS_::owner_less;\n\/\/\/\nusing DCS_MEMORY_NS_::enable_shared_from_this;\n\/\/\/\nusing DCS_MEMORY_NS_::make_shared;\n\/\/\/\nusing DCS_MEMORY_NS_::allocate_shared;\n\n\/\/\/ Shared ownership of objects with an embedded reference count.\nusing ::boost::intrusive_ptr;\n\/\/\/ Array ownership shared among multiple pointers.\nusing ::boost::shared_array;\n\/\/\/ Simple sole ownership of arrays. Noncopyable.\nusing ::boost::scoped_array;\n\/\/\/ Simple sole ownership of single objects. Noncopyable.\nusing ::boost::scoped_ptr;\n\/\/\/\nusing ::boost::get_pointer;\n\n#ifdef DCS_MACRO_CXX11\n\n\/\/ Conversion functions between boost::shared_ptr and std::shared_ptr (and vice versa)\n\ntemplate\nboost::shared_ptr make_shared_ptr(std::shared_ptr& ptr)\n{\n return boost::shared_ptr(ptr.get(), [ptr](T*) mutable {ptr.reset();});\n}\n\ntemplate\nstd::shared_ptr make_shared_ptr(boost::shared_ptr& ptr)\n{\n return std::shared_ptr(ptr.get(), [ptr](T*) mutable {ptr.reset();});\n}\n\n#endif \/\/ DCS_MACRO_CXX11\n\n} \/\/ Namespace dcs\n\n\n#endif \/\/ DCS_SMART_PTR_HPP\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2011\n * Alessio Sclocco \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\n *\/\n\n#define __CL_ENABLE_EXCEPTIONS\n#include \n#include \n#include \n#include \n #include \nusing std::string;\nusing std::ofstream;\nusing std::vector;\n\n#include \n#include \n#include \nusing isa::utils::toStringValue;\nusing isa::Exceptions::OpenCLError;\nusing isa::utils::Timer;\n\n\n#ifndef CL_DATA_HPP\n#define CL_DATA_HPP\n\nnamespace isa {\n\nnamespace OpenCL {\n\ntemplate< typename T > class CLData {\npublic:\n\tCLData(string name, bool deletePolicy = false);\n\t~CLData();\n\t\n\tinline string getName() const;\n\n\t\/\/ Allocation of host data\n\tvoid allocateHostData(vector < T > * data);\n\tvoid allocateHostData(long long unsigned int nrElements);\n\tvoid deleteHostData();\n\t\n\t\/\/ Allocation of device data\n\tvoid allocateDeviceData(cl::Buffer * data, size_t size);\n\tvoid allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError);\n\tvoid allocateDeviceData() throw (OpenCLError);\n\tvoid allocateSharedDeviceData() throw (OpenCLError);\n\tvoid deleteDeviceData();\n\tinline void setDeviceReadOnly();\n\tinline void setDeviceWriteOnly();\n\tinline void setDeviceReadWrite();\n\n\t\/\/ Memory transfers\n\tvoid copyHostToDevice(bool async = false) throw (OpenCLError);\n\tvoid copyDeviceToHost(bool async = false) throw (OpenCLError);\n\tvoid dumpDeviceToDisk() throw (OpenCLError);\n\n\t\/\/ OpenCL\n\tinline void setCLContext(cl::Context * context);\n\tinline void setCLQueue(cl::CommandQueue * queue);\n\t\n\t\/\/ Access host data\n\tinline T * getHostData();\n\tinline T * getHostDataAt(long long unsigned int startingPoint);\n\tinline void * getRawHostData();\n\tinline void * getRawHostDataAt(long long unsigned int startingPoint);\n\tinline size_t getHostDataSize() const;\n\tinline const T operator[](long long unsigned int item) const;\n\tinline const T getHostDataItem(long long unsigned int item) const;\n\n\t\/\/ Modify host data\n\tinline void setHostDataItem(long long unsigned int item, T value);\n\n\t\/\/ Access device data\n\tinline cl::Buffer * getDeviceData();\n\tinline size_t getDeviceDataSize() const;\n\t\n\t\n\t\/\/ Timers\n\tinline Timer & getH2DTimer();\n\tinline Timer & getD2HTimer();\n\nprivate:\n\tcl::Context * clContext;\n\tcl::CommandQueue * clQueue;\n\tTimer timerH2D;\n\tTimer timerD2H;\n\n\tbool deleteHost;\n\tbool deviceReadOnly;\n\tbool deviceWriteOnly;\n\tvector< T > * hostData;\n\tcl::Buffer * deviceData;\n\tsize_t deviceDataSize;\n\n\tstring name;\n};\n\n\n\/\/ Implementations\n\ntemplate< typename T > CLData< T >::CLData(string name, bool deletePolicy) : clContext(0), clQueue(0), timerH2D(Timer(\"H2D\")), timerD2H(Timer(\"D2H\")), deleteHost(deletePolicy), deviceReadOnly(false), deviceWriteOnly(false), hostData(0), deviceData(0), deviceDataSize(0), name(name) {}\n\n\ntemplate< typename T > CLData< T >::~CLData() {\n\tdeleteHostData();\n\tdeleteDeviceData();\n}\n\n\ntemplate< typename T > void CLData< T >::allocateHostData(vector< T > * data) {\n\tdeleteHostData();\n\thostData = data;\n}\n\n\ntemplate< typename T > void CLData< T >::allocateHostData(long long unsigned int nrElements) {\n\tsize_t newSize = nrElements * sizeof(T);\n\n\tdeleteHostData();\n\thostData = new vector< T >(newSize);\n}\n\n\ntemplate< typename T > void CLData< T >::deleteHostData() {\n\tif ( deleteHost != 0 ) {\n\t\tdelete hostData;\n\t}\n}\n\n\ntemplate< typename T > void CLData< T >::allocateDeviceData(cl::Buffer * data, size_t size) {\n\tdeleteDeviceData();\n\n\tdeviceData = data;\n\tdeviceDataSize = size;\n}\n\n\ntemplate< typename T > void CLData< T >::allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError) {\n\tsize_t newSize = nrElements * sizeof(T);\n\n\tif ( newSize != deviceDataSize ) {\n\t\tdeleteDeviceData();\n\n\t\ttry {\n\t\t\tif ( deviceReadOnly ) {\n\t\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, newSize, NULL, NULL);\n\t\t\t} else if ( deviceWriteOnly ) {\n\t\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, newSize, NULL, NULL);\n\t\t\t} else {\n\t\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, newSize, NULL, NULL);\n\t\t\t}\n\t\t} catch ( cl::Error err ) {\n\t\t\tdeviceDataSize = 0;\n\t\t\tthrow OpenCLError(\"Impossible to allocate \" + name + \" device memory: \" + toStringValue< cl_int >(err.err()));\n\t\t}\n\t\tdeviceDataSize = newSize;\n\t}\n}\n\n\ntemplate< typename T > void CLData< T >::allocateDeviceData() throw (OpenCLError) {\n\tdeleteDeviceData();\n\t\n\ttry {\n\t\tif ( deviceReadOnly ) {\n\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, hostDataSize, NULL, NULL);\n\t\t} else if ( deviceWriteOnly ) {\n\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, hostDataSize, NULL, NULL);\n\t\t} else {\n\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, hostDataSize, NULL, NULL);\n\t\t}\n\t} catch ( cl::Error err ) {\n\t\tdeviceDataSize = 0;\n\t\tthrow OpenCLError(\"Impossible to allocate \" + name + \" device memory: \" + toStringValue< cl_int >(err.err()));\n\t}\n\tdeviceDataSize = hostDataSize;\n}\n\n\ntemplate< typename T > void CLData< T >::allocateSharedDeviceData() throw (OpenCLError) {\n\tdeleteDeviceData();\n\t\n\ttry {\n\t\tif ( deviceReadOnly ) {\n\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, hostDataSize, getRawHostData(), NULL);\n\t\t} else if ( deviceWriteOnly ) {\n\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, hostDataSize, getRawHostData(), NULL);\n\t\t} else {\n\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, hostDataSize, getRawHostData(), NULL);\n\t\t}\n\t} catch ( cl::Error err ) {\n\t\tdeviceDataSize = 0;\n\t\tthrow OpenCLError(\"Impossible to allocate \" + name + \" device memory: \" + toStringValue< cl_int >(err.err()));\n\t}\n\tdeviceDataSize = hostDataSize;\n}\n\n\ntemplate< typename T > void CLData< T >::deleteDeviceData() {\n\tif ( deviceDataSize != 0 ) {\n\t\tdelete deviceData;\n\t\tdeviceData = 0;\n\t\tdeviceDataSize = 0;\n\t}\n}\n\n\ntemplate< typename T > inline void CLData< T >::setDeviceReadOnly() {\n\tdeviceReadOnly = true;\n\tdeviceWriteOnly = false;\n}\n\n\ntemplate< typename T > inline void CLData< T >::setDeviceWriteOnly() {\n\tdeviceWriteOnly = true;\n\tdeviceReadOnly = false;\n}\n\n\ntemplate< typename T > inline void CLData< T >::setDeviceReadWrite() {\n\tdeviceWriteOnly = false;\n\tdeviceReadOnly = false;\n}\n\n\ntemplate< typename T > void CLData< T >::copyHostToDevice(bool async) throw (OpenCLError) {\n\tif ( hostDataSize != deviceDataSize ) {\n\t\tthrow OpenCLError(\"Impossible to copy \" + name + \": different memory sizes.\");\n\t}\n\n\tif ( async ) {\n\t\ttry {\n\t\t\tclQueue->enqueueWriteBuffer(*deviceData, CL_FALSE, 0, deviceDataSize, getRawHostData(), NULL, NULL);\n\t\t} catch ( cl::Error err ) {\n\t\t\tthrow OpenCLError(\"Impossible to copy \" + name + \" to device: \" + toStringValue< cl_int >(err.err()));\n\t\t}\n\t}\n\telse {\n\t\tcl::Event clEvent;\n\n\t\ttry {\n\t\t\ttimerH2D.start();\n\t\t\tclQueue->enqueueWriteBuffer(*deviceData, CL_TRUE, 0, deviceDataSize, getRawHostData(), NULL, &clEvent);\n\t\t\tclEvent.wait();\n\t\t\ttimerH2D.stop();\n\t\t} catch ( cl::Error err ) {\n\t\t\ttimerH2D.reset();\n\t\t\tthrow OpenCLError(\"Impossible to copy \" + name + \" to device: \" + toStringValue< cl_int >(err.err()));\n\t\t}\n\t}\n}\n\n\ntemplate< typename T > void CLData< T >::copyDeviceToHost(bool async) throw (OpenCLError) {\n\tif ( hostDataSize != deviceDataSize ) {\n\t\tthrow OpenCLError(\"Impossible to copy \" + name + \": different memory sizes.\");\n\t}\n\n\tif ( async ) {\n\t\ttry {\n\t\t\tclQueue->enqueueReadBuffer(*deviceData, CL_FALSE, 0, hostDataSize, getRawHostData(), NULL, NULL);\n\t\t} catch ( cl::Error err ) {\n\t\t\tthrow OpenCLError(\"Impossible to copy \" + name + \" to host: \" + toStringValue< cl_int >(err.err()));\n\t\t}\n\t}\n\telse {\n\t\tcl::Event clEvent;\n\n\t\ttry {\n\t\t\ttimerD2H.start();\n\t\t\tclQueue->enqueueReadBuffer(*deviceData, CL_TRUE, 0, hostDataSize, getRawHostData(), NULL, &clEvent);\n\t\t\tclEvent.wait();\n\t\t\ttimerD2H.stop();\n\t\t} catch ( cl::Error err ) {\n\t\t\ttimerD2H.reset();\n\t\t\tthrow OpenCLError(\"Impossible to copy \" + name + \" to host: \" + toStringValue< cl_int >(err.err()));\n\t\t}\n\t}\n\n}\n\n\ntemplate< typename T > void CLData< T >::dumpDeviceToDisk() throw (OpenCLError) {\n\tCLData< T > temp = CLData< T >(\"temp\", true);\n\n\ttemp.setCLContext(clContext);\n\ttemp.setCLQueue(clQueue);\n\ttemp.allocateHostData(hostDataSize \/ sizeof(T));\n\ttemp.allocateDeviceData(deviceData, deviceDataSize);\n\ttemp.copyDeviceToHost();\n\n\tofstream oFile((\".\/\" + name + \".bin\").c_str(), ofstream::binary);\n\toFile.write(reinterpret_cast< char * >(temp.getRawHostData()), temp.getHostDataSize());\n\toFile.close();\n}\n\ntemplate< typename T > inline void CLData< T >::setCLContext(cl::Context * context) {\n\tclContext = context;\n}\n\n\t\ntemplate< typename T > inline void CLData< T >::setCLQueue(cl::CommandQueue * queue) {\n\tclQueue = queue;\n}\n\n\ntemplate< typename T > inline T * CLData< T >::getHostData() {\n\treturn hostData->data();\n}\n\n\ntemplate< typename T > inline T * CLData< T >::getHostDataAt(long long unsigned int startingPoint) {\n\treturn hostData->at(startingPoint);\n}\n\n\ntemplate< typename T > inline void * CLData< T >::getRawHostData() {\n\treturn reinterpret_cast< void * >(hostData->data());\n}\n\n\ntemplate< typename T > inline void * CLData< T >::getRawHostDataAt(long long unsigned int startingPoint) {\n\treturn reinterpret_cast< void * >(hostData->data() + startingPoint);\n}\n\n\ntemplate< typename T > inline size_t CLData< T >::getHostDataSize() const {\n\treturn hostData->size();\n}\n\n\ntemplate< typename T > inline const T CLData< T >::operator[](long long unsigned int item) const {\n\treturn hostData->at(item);\n}\n\n\ntemplate< typename T > inline const T CLData< T >::getHostDataItem(long long unsigned int item) const {\n\treturn hostData->at(item);\n}\n\n\ntemplate< typename T > inline cl::Buffer * CLData< T >::getDeviceData() {\n\treturn deviceData;\n}\n\n\ntemplate< typename T > inline size_t CLData< T >::getDeviceDataSize() const {\n\treturn deviceDataSize;\n}\n\n\ntemplate< typename T > inline void CLData< T >::setHostDataItem(long long unsigned int item, T value) {\n\thostData->at(item) = value;\n}\n\n\ntemplate< typename T > inline string CLData< T >::getName() const {\n\treturn name;\n}\n\n\t\ntemplate< typename T > inline Timer & CLData< T >::getH2DTimer() {\n\treturn timerH2D;\n}\n\n\ntemplate< typename T > inline Timer & CLData< T >::getD2HTimer() {\n\treturn timerD2H;\n}\n\n} \/\/ OpenCL\n} \/\/ isa\n\n#endif \/\/ CL_DATA_HPP\nI decided that is better to have a statically allocated std::vector to store the host data instead of a dynamic allocated one.\/*\n * Copyright (C) 2011\n * Alessio Sclocco \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\n *\/\n\n#define __CL_ENABLE_EXCEPTIONS\n#include \n#include \n#include \n#include \n #include \nusing std::string;\nusing std::ofstream;\nusing std::vector;\n\n#include \n#include \n#include \nusing isa::utils::toStringValue;\nusing isa::Exceptions::OpenCLError;\nusing isa::utils::Timer;\n\n\n#ifndef CL_DATA_HPP\n#define CL_DATA_HPP\n\nnamespace isa {\n\nnamespace OpenCL {\n\ntemplate< typename T > class CLData {\npublic:\n\tCLData(string name, bool deletePolicy = false);\n\t~CLData();\n\t\n\tinline string getName() const;\n\n\t\/\/ Allocation of host data\n\tvoid allocateHostData(vector < T > & data);\n\tvoid allocateHostData(long long unsigned int nrElements);\n\tvoid deleteHostData();\n\t\n\t\/\/ Allocation of device data\n\tvoid allocateDeviceData(cl::Buffer * data, size_t size);\n\tvoid allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError);\n\tvoid allocateDeviceData() throw (OpenCLError);\n\tvoid allocateSharedDeviceData() throw (OpenCLError);\n\tvoid deleteDeviceData();\n\tinline void setDeviceReadOnly();\n\tinline void setDeviceWriteOnly();\n\tinline void setDeviceReadWrite();\n\n\t\/\/ Memory transfers\n\tvoid copyHostToDevice(bool async = false) throw (OpenCLError);\n\tvoid copyDeviceToHost(bool async = false) throw (OpenCLError);\n\tvoid dumpDeviceToDisk() throw (OpenCLError);\n\n\t\/\/ OpenCL\n\tinline void setCLContext(cl::Context * context);\n\tinline void setCLQueue(cl::CommandQueue * queue);\n\t\n\t\/\/ Access host data\n\tinline T * getHostData();\n\tinline T * getHostDataAt(long long unsigned int startingPoint);\n\tinline void * getRawHostData();\n\tinline void * getRawHostDataAt(long long unsigned int startingPoint);\n\tinline size_t getHostDataSize() const;\n\tinline const T operator[](long long unsigned int item) const;\n\tinline const T getHostDataItem(long long unsigned int item) const;\n\n\t\/\/ Modify host data\n\tinline void setHostDataItem(long long unsigned int item, T value);\n\n\t\/\/ Access device data\n\tinline cl::Buffer * getDeviceData();\n\tinline size_t getDeviceDataSize() const;\n\t\n\t\n\t\/\/ Timers\n\tinline Timer & getH2DTimer();\n\tinline Timer & getD2HTimer();\n\nprivate:\n\tcl::Context * clContext;\n\tcl::CommandQueue * clQueue;\n\tTimer timerH2D;\n\tTimer timerD2H;\n\n\tbool deleteHost;\n\tbool deviceReadOnly;\n\tbool deviceWriteOnly;\n\tvector< T > hostData;\n\tsize_t hostDataSize;\n\tcl::Buffer * deviceData;\n\tsize_t deviceDataSize;\n\n\tstring name;\n};\n\n\n\/\/ Implementations\n\ntemplate< typename T > CLData< T >::CLData(string name, bool deletePolicy) : clContext(0), clQueue(0), timerH2D(Timer(\"H2D\")), timerD2H(Timer(\"D2H\")), deleteHost(deletePolicy), deviceReadOnly(false), deviceWriteOnly(false), hostData(vector< T >()), hostDataSize(0), deviceData(0), deviceDataSize(0), name(name) {}\n\n\ntemplate< typename T > CLData< T >::~CLData() {\n\tdeleteHostData();\n\tdeleteDeviceData();\n}\n\n\ntemplate< typename T > void CLData< T >::allocateHostData(vector< T > & data) {\n\thostData = data;\n\thostDataSize = hostData.size() * sizeof(T);\n}\n\n\ntemplate< typename T > void CLData< T >::allocateHostData(long long unsigned int nrElements) {\n\thostData = vector< T >(nrElements, 0);\n\thostDataSize = nrElements * sizeof(T);\n}\n\n\ntemplate< typename T > void CLData< T >::deleteHostData() {\n\tif ( deleteHost ) {\n\t\thostData = vector< T >();\n\t}\n}\n\n\ntemplate< typename T > void CLData< T >::allocateDeviceData(cl::Buffer * data, size_t size) {\n\tdeleteDeviceData();\n\n\tdeviceData = data;\n\tdeviceDataSize = size;\n}\n\n\ntemplate< typename T > void CLData< T >::allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError) {\n\tsize_t newSize = nrElements * sizeof(T);\n\n\tif ( newSize != deviceDataSize ) {\n\t\tdeleteDeviceData();\n\n\t\ttry {\n\t\t\tif ( deviceReadOnly ) {\n\t\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, newSize, NULL, NULL);\n\t\t\t} else if ( deviceWriteOnly ) {\n\t\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, newSize, NULL, NULL);\n\t\t\t} else {\n\t\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, newSize, NULL, NULL);\n\t\t\t}\n\t\t} catch ( cl::Error err ) {\n\t\t\tdeviceDataSize = 0;\n\t\t\tthrow OpenCLError(\"Impossible to allocate \" + name + \" device memory: \" + toStringValue< cl_int >(err.err()));\n\t\t}\n\t\tdeviceDataSize = newSize;\n\t}\n}\n\n\ntemplate< typename T > void CLData< T >::allocateDeviceData() throw (OpenCLError) {\n\tdeleteDeviceData();\n\t\n\ttry {\n\t\tif ( deviceReadOnly ) {\n\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, hostDataSize, NULL, NULL);\n\t\t} else if ( deviceWriteOnly ) {\n\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, hostDataSize, NULL, NULL);\n\t\t} else {\n\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, hostDataSize, NULL, NULL);\n\t\t}\n\t} catch ( cl::Error err ) {\n\t\tdeviceDataSize = 0;\n\t\tthrow OpenCLError(\"Impossible to allocate \" + name + \" device memory: \" + toStringValue< cl_int >(err.err()));\n\t}\n\tdeviceDataSize = hostDataSize;\n}\n\n\ntemplate< typename T > void CLData< T >::allocateSharedDeviceData() throw (OpenCLError) {\n\tdeleteDeviceData();\n\t\n\ttry {\n\t\tif ( deviceReadOnly ) {\n\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, hostDataSize, getRawHostData(), NULL);\n\t\t} else if ( deviceWriteOnly ) {\n\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, hostDataSize, getRawHostData(), NULL);\n\t\t} else {\n\t\t\tdeviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, hostDataSize, getRawHostData(), NULL);\n\t\t}\n\t} catch ( cl::Error err ) {\n\t\tdeviceDataSize = 0;\n\t\tthrow OpenCLError(\"Impossible to allocate \" + name + \" device memory: \" + toStringValue< cl_int >(err.err()));\n\t}\n\tdeviceDataSize = hostDataSize;\n}\n\n\ntemplate< typename T > void CLData< T >::deleteDeviceData() {\n\tif ( deviceDataSize != 0 ) {\n\t\tdelete deviceData;\n\t\tdeviceData = 0;\n\t\tdeviceDataSize = 0;\n\t}\n}\n\n\ntemplate< typename T > inline void CLData< T >::setDeviceReadOnly() {\n\tdeviceReadOnly = true;\n\tdeviceWriteOnly = false;\n}\n\n\ntemplate< typename T > inline void CLData< T >::setDeviceWriteOnly() {\n\tdeviceWriteOnly = true;\n\tdeviceReadOnly = false;\n}\n\n\ntemplate< typename T > inline void CLData< T >::setDeviceReadWrite() {\n\tdeviceWriteOnly = false;\n\tdeviceReadOnly = false;\n}\n\n\ntemplate< typename T > void CLData< T >::copyHostToDevice(bool async) throw (OpenCLError) {\n\tif ( hostDataSize != deviceDataSize ) {\n\t\tthrow OpenCLError(\"Impossible to copy \" + name + \": different memory sizes.\");\n\t}\n\n\tif ( async ) {\n\t\ttry {\n\t\t\tclQueue->enqueueWriteBuffer(*deviceData, CL_FALSE, 0, deviceDataSize, getRawHostData(), NULL, NULL);\n\t\t} catch ( cl::Error err ) {\n\t\t\tthrow OpenCLError(\"Impossible to copy \" + name + \" to device: \" + toStringValue< cl_int >(err.err()));\n\t\t}\n\t} else {\n\t\tcl::Event clEvent;\n\n\t\ttry {\n\t\t\ttimerH2D.start();\n\t\t\tclQueue->enqueueWriteBuffer(*deviceData, CL_TRUE, 0, deviceDataSize, getRawHostData(), NULL, &clEvent);\n\t\t\tclEvent.wait();\n\t\t\ttimerH2D.stop();\n\t\t} catch ( cl::Error err ) {\n\t\t\ttimerH2D.reset();\n\t\t\tthrow OpenCLError(\"Impossible to copy \" + name + \" to device: \" + toStringValue< cl_int >(err.err()));\n\t\t}\n\t}\n}\n\n\ntemplate< typename T > void CLData< T >::copyDeviceToHost(bool async) throw (OpenCLError) {\n\tif ( hostDataSize != deviceDataSize ) {\n\t\tthrow OpenCLError(\"Impossible to copy \" + name + \": different memory sizes.\");\n\t}\n\n\tif ( async ) {\n\t\ttry {\n\t\t\tclQueue->enqueueReadBuffer(*deviceData, CL_FALSE, 0, hostDataSize, getRawHostData(), NULL, NULL);\n\t\t} catch ( cl::Error err ) {\n\t\t\tthrow OpenCLError(\"Impossible to copy \" + name + \" to host: \" + toStringValue< cl_int >(err.err()));\n\t\t}\n\t} else {\n\t\tcl::Event clEvent;\n\n\t\ttry {\n\t\t\ttimerD2H.start();\n\t\t\tclQueue->enqueueReadBuffer(*deviceData, CL_TRUE, 0, hostDataSize, getRawHostData(), NULL, &clEvent);\n\t\t\tclEvent.wait();\n\t\t\ttimerD2H.stop();\n\t\t} catch ( cl::Error err ) {\n\t\t\ttimerD2H.reset();\n\t\t\tthrow OpenCLError(\"Impossible to copy \" + name + \" to host: \" + toStringValue< cl_int >(err.err()));\n\t\t}\n\t}\n\n}\n\n\ntemplate< typename T > void CLData< T >::dumpDeviceToDisk() throw (OpenCLError) {\n\tCLData< T > temp = CLData< T >(\"temp\", true);\n\n\ttemp.setCLContext(clContext);\n\ttemp.setCLQueue(clQueue);\n\ttemp.allocateHostData(hostData.size());\n\ttemp.allocateDeviceData(deviceData, deviceDataSize);\n\ttemp.copyDeviceToHost();\n\n\tofstream oFile((\".\/\" + name + \".bin\").c_str(), ofstream::binary);\n\toFile.write(reinterpret_cast< char * >(temp.getRawHostData()), temp.getHostDataSize());\n\toFile.close();\n}\n\n\ntemplate< typename T > inline void CLData< T >::setCLContext(cl::Context * context) {\n\tclContext = context;\n}\n\n\t\ntemplate< typename T > inline void CLData< T >::setCLQueue(cl::CommandQueue * queue) {\n\tclQueue = queue;\n}\n\n\ntemplate< typename T > inline T * CLData< T >::getHostData() {\n\treturn hostData.data();\n}\n\n\ntemplate< typename T > inline T * CLData< T >::getHostDataAt(long long unsigned int startingPoint) {\n\treturn hostData.data() + startingPoint;\n}\n\n\ntemplate< typename T > inline void * CLData< T >::getRawHostData() {\n\treturn reinterpret_cast< void * >(hostData.data());\n}\n\n\ntemplate< typename T > inline void * CLData< T >::getRawHostDataAt(long long unsigned int startingPoint) {\n\treturn reinterpret_cast< void * >(hostData.data() + startingPoint);\n}\n\n\ntemplate< typename T > inline size_t CLData< T >::getHostDataSize() const {\n\treturn hostDataSize;\n}\n\n\ntemplate< typename T > inline const T CLData< T >::operator[](long long unsigned int item) const {\n\treturn hostData[item];\n}\n\n\ntemplate< typename T > inline const T CLData< T >::getHostDataItem(long long unsigned int item) const {\n\treturn hostData[item];\n}\n\n\ntemplate< typename T > inline cl::Buffer * CLData< T >::getDeviceData() {\n\treturn deviceData;\n}\n\n\ntemplate< typename T > inline size_t CLData< T >::getDeviceDataSize() const {\n\treturn deviceDataSize;\n}\n\n\ntemplate< typename T > inline void CLData< T >::setHostDataItem(long long unsigned int item, T value) {\n\thostData[item] = value;\n}\n\n\ntemplate< typename T > inline string CLData< T >::getName() const {\n\treturn name;\n}\n\n\t\ntemplate< typename T > inline Timer & CLData< T >::getH2DTimer() {\n\treturn timerH2D;\n}\n\n\ntemplate< typename T > inline Timer & CLData< T >::getD2HTimer() {\n\treturn timerD2H;\n}\n\n} \/\/ OpenCL\n} \/\/ isa\n\n#endif \/\/ CL_DATA_HPP\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2014, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/escape_string.hpp\" \/\/ for from_hex\n#include \"libtorrent\/alert_types.hpp\"\n#include \"libtorrent\/bencode.hpp\" \/\/ for bencode()\n#include \"libtorrent\/kademlia\/item.hpp\" \/\/ for sign_mutable_item\n#include \"ed25519.h\"\n#include \n\n#include \n\nusing namespace libtorrent;\n\n#ifdef TORRENT_DISABLE_DHT\n\nint main(int argc, char* argv[])\n{\n\tfprintf(stderr, \"not built with DHT support\\n\");\n\treturn 1;\n}\n\n#else\n\nvoid usage()\n{\n\tfprintf(stderr,\n\t\t\"USAGE:\\ndht \\n\\nCOMMANDS:\\n\"\n\t\t\"get - retrieves and prints out the immutable\\n\"\n\t\t\" item stored under hash.\\n\"\n\t\t\"put - puts the specified string as an immutable\\n\"\n\t\t\" item onto the DHT. The resulting target hash\\n\"\n\t\t\"gen-key - generate ed25519 keypair and save it in\\n\"\n\t\t\" the specified file\\n\"\n\t\t\"mput - puts the specified string as a mutable\\n\"\n\t\t\" object under the public key in key-file\\n\"\n\t\t\"mget - get a mutable object under the specified\\n\"\n\t\t\" public key\\n\"\n\t\t);\n\texit(1);\n}\n\nstd::auto_ptr wait_for_alert(session& s, int alert_type)\n{\n\tstd::auto_ptr ret;\n\tbool found = false;\n\twhile (!found)\n\t{\n\t\ts.wait_for_alert(seconds(5));\n\n\t\tstd::deque alerts;\n\t\ts.pop_alerts(&alerts);\n\t\tfor (std::deque::iterator i = alerts.begin()\n\t\t\t, end(alerts.end()); i != end; ++i)\n\t\t{\n\t\t\tif ((*i)->type() != alert_type)\n\t\t\t{\n\t\t\t\tstatic int spinner = 0;\n\t\t\t\tstatic const char anim[] = {'-', '\\\\', '|', '\/'};\n\t\t\t\tprintf(\"\\r%c\", anim[spinner]);\n\t\t\t\tfflush(stdout);\n\t\t\t\tspinner = (spinner + 1) & 3;\n\t\t\t\t\/\/print some alerts?\n\t\t\t\tdelete *i;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tret = std::auto_ptr(*i);\n\t\t\tfound = true;\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\treturn ret;\n}\n\nvoid put_string(entry& e, boost::array& sig, boost::uint64_t& seq\n\t, std::string const& salt, char const* public_key, char const* private_key\n\t, char const* str)\n{\n\tusing libtorrent::dht::sign_mutable_item;\n\n\te = std::string(str);\n\tstd::vector buf;\n\tbencode(std::back_inserter(buf), e);\n\t++seq;\n\tsign_mutable_item(std::pair(&buf[0], buf.size())\n\t\t, std::pair(&salt[0], salt.size())\n\t\t, seq\n\t\t, public_key\n\t\t, private_key\n\t\t, sig.data());\n}\n\nvoid bootstrap(session& s)\n{\n\tprintf(\"bootstrapping\\n\");\n\twait_for_alert(s, dht_bootstrap_alert::alert_type);\n}\n\nint main(int argc, char* argv[])\n{\n\t\/\/ skip pointer to self\n\t++argv;\n\t--argc;\n\n\tif (argc < 1) usage();\n\n\tif (strcmp(argv[0], \"gen-key\") == 0)\n\t{\n\t\t++argv;\n\t\t--argc;\n\t\tif (argc < 1) usage();\n\t\n\t\tunsigned char seed[32];\n\t\ted25519_create_seed(seed);\n\n\t\tFILE* f = fopen(argv[0], \"wb+\");\n\t\tif (f == NULL)\n\t\t{\n\t\t\tfprintf(stderr, \"failed to open file for writing \\\"%s\\\": (%d) %s\\n\"\n\t\t\t\t, argv[0], errno, strerror(errno));\n\t\t\treturn 1;\n\t\t}\n\n\t\tfwrite(seed, 1, 32, f);\n\t\tfclose(f);\n\t\treturn 0;\n\t}\n\n\tsession s;\n\ts.set_alert_mask(0xffffffff);\n\n\ts.add_dht_router(std::pair(\"router.utorrent.com\", 6881));\n\n\tFILE* f = fopen(\".dht\", \"rb\");\n\tif (f != NULL)\n\t{\n\t\tfseek(f, 0, SEEK_END);\n\t\tint size = ftell(f);\n\t\tfseek(f, 0, SEEK_SET);\n\t\tif (size > 0)\n\t\t{\n\t\t\tstd::vector state;\n\t\t\tstate.resize(size);\n\t\t\tfread(&state[0], 1, state.size(), f);\n\n\t\t\tlazy_entry e;\n\t\t\terror_code ec;\n\t\t\tlazy_bdecode(&state[0], &state[0] + state.size(), e, ec);\n\t\t\tif (ec)\n\t\t\t\tfprintf(stderr, \"failed to parse .dht file: (%d) %s\\n\"\n\t\t\t\t\t, ec.value(), ec.message().c_str());\n\t\t\telse\n\t\t\t\ts.load_state(e);\n\t\t}\n\t\tfclose(f);\n\t}\n\n\tif (strcmp(argv[0], \"get\") == 0)\n\t{\n\t\t++argv;\n\t\t--argc;\n\t\n\t\tif (argc < 1) usage();\n\n\t\tif (strlen(argv[0]) != 40)\n\t\t{\n\t\t\tfprintf(stderr, \"the hash is expected to be 40 hex characters\\n\");\n\t\t\tusage();\n\t\t}\n\t\tsha1_hash target;\n\t\tbool ret = from_hex(argv[0], 40, (char*)&target[0]);\n\t\tif (!ret)\n\t\t{\n\t\t\tfprintf(stderr, \"invalid hex encoding of target hash\\n\");\n\t\t\treturn 1;\n\t\t}\n\n\t\tbootstrap(s);\n\t\ts.dht_get_item(target);\n\n\t\tprintf(\"GET %s\\n\", to_hex(target.to_string()).c_str());\n\n\t\tstd::auto_ptr a = wait_for_alert(s, dht_immutable_item_alert::alert_type);\n\n\t\tdht_immutable_item_alert* item = alert_cast(a.get());\n\t\tentry data;\n\t\tif (item)\n\t\t\tdata.swap(item->item);\n\n\t\tprintf(\"%s\", data.to_string().c_str());\n\t}\n\telse if (strcmp(argv[0], \"put\") == 0)\n\t{\n\t\t++argv;\n\t\t--argc;\n\t\tif (argc < 1) usage();\n\n\t\tentry data;\n\t\tdata = std::string(argv[0]);\n\n\t\tbootstrap(s);\n\t\tsha1_hash target = s.dht_put_item(data);\n\t\t\n\t\tprintf(\"PUT %s\\n\", to_hex(target.to_string()).c_str());\n\n\t\twait_for_alert(s, dht_put_alert::alert_type);\n\t}\n\telse if (strcmp(argv[0], \"mput\") == 0)\n\t{\n\t\t++argv;\n\t\t--argc;\n\t\tif (argc < 1) usage();\n\n\t\tFILE* f = fopen(argv[0], \"rb+\");\n\t\tif (f == NULL)\n\t\t{\n\t\t\tfprintf(stderr, \"failed to open file \\\"%s\\\": (%d) %s\\n\"\n\t\t\t\t, argv[0], errno, strerror(errno));\n\t\t\treturn 1;\n\t\t}\n\n\t\tunsigned char seed[32];\n\t\tfread(seed, 1, 32, f);\n\t\tfclose(f);\n\n\t\t++argv;\n\t\t--argc;\n\t\tif (argc < 1) usage();\n\n\t\tboost::array public_key;\n\t\tboost::array private_key;\n\t\ted25519_create_keypair((unsigned char*)public_key.data()\n\t\t\t, (unsigned char*)private_key.data(), seed);\n\t\t\n\t\tbootstrap(s);\n\t\ts.dht_put_item(public_key, boost::bind(&put_string, _1, _2, _3, _4\n\t\t\t, public_key.data(), private_key.data(), argv[0]));\n\n\t\tprintf(\"public key: %s\\n\", to_hex(std::string(public_key.data()\n\t\t\t, public_key.size())).c_str());\n\n\t\twait_for_alert(s, dht_put_alert::alert_type);\n\t}\n\telse if (strcmp(argv[0], \"mget\") == 0)\n\t{\n\t\t++argv;\n\t\t--argc;\n\t\tif (argc < 1) usage();\n\n\t\tint len = strlen(argv[0]);\n\t\tif (len != 64)\n\t\t{\n\t\t\tfprintf(stderr, \"public key is expected to be 64 hex digits\\n\");\n\t\t\treturn 1;\n\t\t}\n\t\tboost::array public_key;\n\t\tbool ret = from_hex(argv[0], len, &public_key[0]);\n\t\tif (!ret)\n\t\t{\n\t\t\tfprintf(stderr, \"invalid hex encoding of public key\\n\");\n\t\t\treturn 1;\n\t\t}\n\n\t\tbootstrap(s);\n\t\ts.dht_get_item(public_key);\n\n\t\tstd::auto_ptr a = wait_for_alert(s, dht_mutable_item_alert::alert_type);\n\n\t\tdht_mutable_item_alert* item = alert_cast(a.get());\n\t\tentry data;\n\t\tif (item)\n\t\t\tdata.swap(item->item);\n\n\t\tprintf(\"%s\", data.to_string().c_str());\n\t}\n\telse\n\t{\n\t\tusage();\n\t}\n\n\tentry e;\n\ts.save_state(e, session::save_dht_state);\n\tstd::vector state;\n\tbencode(std::back_inserter(state), e);\n\tf = fopen(\".dht\", \"wb+\");\n\tif (f == NULL)\n\t{\n\t\tfprintf(stderr, \"failed to open file .dht for writing\");\n\t\treturn 1;\n\t}\n\tfwrite(&state[0], 1, state.size(), f);\n\tfclose(f);\n}\n\n#endif\n\nfix no-deprecated functions build\/*\n\nCopyright (c) 2014, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/escape_string.hpp\" \/\/ for from_hex\n#include \"libtorrent\/alert_types.hpp\"\n#include \"libtorrent\/bencode.hpp\" \/\/ for bencode()\n#include \"libtorrent\/kademlia\/item.hpp\" \/\/ for sign_mutable_item\n#include \"ed25519.h\"\n#include \n\n#include \n\nusing namespace libtorrent;\n\n#ifdef TORRENT_DISABLE_DHT\n\nint main(int argc, char* argv[])\n{\n\tfprintf(stderr, \"not built with DHT support\\n\");\n\treturn 1;\n}\n\n#else\n\nvoid usage()\n{\n\tfprintf(stderr,\n\t\t\"USAGE:\\ndht \\n\\nCOMMANDS:\\n\"\n\t\t\"get - retrieves and prints out the immutable\\n\"\n\t\t\" item stored under hash.\\n\"\n\t\t\"put - puts the specified string as an immutable\\n\"\n\t\t\" item onto the DHT. The resulting target hash\\n\"\n\t\t\"gen-key - generate ed25519 keypair and save it in\\n\"\n\t\t\" the specified file\\n\"\n\t\t\"mput - puts the specified string as a mutable\\n\"\n\t\t\" object under the public key in key-file\\n\"\n\t\t\"mget - get a mutable object under the specified\\n\"\n\t\t\" public key\\n\"\n\t\t);\n\texit(1);\n}\n\nstd::auto_ptr wait_for_alert(session& s, int alert_type)\n{\n\tstd::auto_ptr ret;\n\tbool found = false;\n\twhile (!found)\n\t{\n\t\ts.wait_for_alert(seconds(5));\n\n\t\tstd::deque alerts;\n\t\ts.pop_alerts(&alerts);\n\t\tfor (std::deque::iterator i = alerts.begin()\n\t\t\t, end(alerts.end()); i != end; ++i)\n\t\t{\n\t\t\tif ((*i)->type() != alert_type)\n\t\t\t{\n\t\t\t\tstatic int spinner = 0;\n\t\t\t\tstatic const char anim[] = {'-', '\\\\', '|', '\/'};\n\t\t\t\tprintf(\"\\r%c\", anim[spinner]);\n\t\t\t\tfflush(stdout);\n\t\t\t\tspinner = (spinner + 1) & 3;\n\t\t\t\t\/\/print some alerts?\n\t\t\t\tdelete *i;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tret = std::auto_ptr(*i);\n\t\t\tfound = true;\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\treturn ret;\n}\n\nvoid put_string(entry& e, boost::array& sig, boost::uint64_t& seq\n\t, std::string const& salt, char const* public_key, char const* private_key\n\t, char const* str)\n{\n\tusing libtorrent::dht::sign_mutable_item;\n\n\te = std::string(str);\n\tstd::vector buf;\n\tbencode(std::back_inserter(buf), e);\n\t++seq;\n\tsign_mutable_item(std::pair(&buf[0], buf.size())\n\t\t, std::pair(&salt[0], salt.size())\n\t\t, seq\n\t\t, public_key\n\t\t, private_key\n\t\t, sig.data());\n}\n\nvoid bootstrap(session& s)\n{\n\tprintf(\"bootstrapping\\n\");\n\twait_for_alert(s, dht_bootstrap_alert::alert_type);\n}\n\nint main(int argc, char* argv[])\n{\n\t\/\/ skip pointer to self\n\t++argv;\n\t--argc;\n\n\tif (argc < 1) usage();\n\n\tif (strcmp(argv[0], \"gen-key\") == 0)\n\t{\n\t\t++argv;\n\t\t--argc;\n\t\tif (argc < 1) usage();\n\t\n\t\tunsigned char seed[32];\n\t\ted25519_create_seed(seed);\n\n\t\tFILE* f = fopen(argv[0], \"wb+\");\n\t\tif (f == NULL)\n\t\t{\n\t\t\tfprintf(stderr, \"failed to open file for writing \\\"%s\\\": (%d) %s\\n\"\n\t\t\t\t, argv[0], errno, strerror(errno));\n\t\t\treturn 1;\n\t\t}\n\n\t\tfwrite(seed, 1, 32, f);\n\t\tfclose(f);\n\t\treturn 0;\n\t}\n\n\tsettings_pack sett;\n\tsett.set_int(settings_pack::alert_mask, 0xffffffff);\n\tsession s(sett);\n\n\ts.add_dht_router(std::pair(\"router.utorrent.com\", 6881));\n\n\tFILE* f = fopen(\".dht\", \"rb\");\n\tif (f != NULL)\n\t{\n\t\tfseek(f, 0, SEEK_END);\n\t\tint size = ftell(f);\n\t\tfseek(f, 0, SEEK_SET);\n\t\tif (size > 0)\n\t\t{\n\t\t\tstd::vector state;\n\t\t\tstate.resize(size);\n\t\t\tfread(&state[0], 1, state.size(), f);\n\n\t\t\tlazy_entry e;\n\t\t\terror_code ec;\n\t\t\tlazy_bdecode(&state[0], &state[0] + state.size(), e, ec);\n\t\t\tif (ec)\n\t\t\t\tfprintf(stderr, \"failed to parse .dht file: (%d) %s\\n\"\n\t\t\t\t\t, ec.value(), ec.message().c_str());\n\t\t\telse\n\t\t\t\ts.load_state(e);\n\t\t}\n\t\tfclose(f);\n\t}\n\n\tif (strcmp(argv[0], \"get\") == 0)\n\t{\n\t\t++argv;\n\t\t--argc;\n\t\n\t\tif (argc < 1) usage();\n\n\t\tif (strlen(argv[0]) != 40)\n\t\t{\n\t\t\tfprintf(stderr, \"the hash is expected to be 40 hex characters\\n\");\n\t\t\tusage();\n\t\t}\n\t\tsha1_hash target;\n\t\tbool ret = from_hex(argv[0], 40, (char*)&target[0]);\n\t\tif (!ret)\n\t\t{\n\t\t\tfprintf(stderr, \"invalid hex encoding of target hash\\n\");\n\t\t\treturn 1;\n\t\t}\n\n\t\tbootstrap(s);\n\t\ts.dht_get_item(target);\n\n\t\tprintf(\"GET %s\\n\", to_hex(target.to_string()).c_str());\n\n\t\tstd::auto_ptr a = wait_for_alert(s, dht_immutable_item_alert::alert_type);\n\n\t\tdht_immutable_item_alert* item = alert_cast(a.get());\n\t\tentry data;\n\t\tif (item)\n\t\t\tdata.swap(item->item);\n\n\t\tprintf(\"%s\", data.to_string().c_str());\n\t}\n\telse if (strcmp(argv[0], \"put\") == 0)\n\t{\n\t\t++argv;\n\t\t--argc;\n\t\tif (argc < 1) usage();\n\n\t\tentry data;\n\t\tdata = std::string(argv[0]);\n\n\t\tbootstrap(s);\n\t\tsha1_hash target = s.dht_put_item(data);\n\t\t\n\t\tprintf(\"PUT %s\\n\", to_hex(target.to_string()).c_str());\n\n\t\twait_for_alert(s, dht_put_alert::alert_type);\n\t}\n\telse if (strcmp(argv[0], \"mput\") == 0)\n\t{\n\t\t++argv;\n\t\t--argc;\n\t\tif (argc < 1) usage();\n\n\t\tFILE* f = fopen(argv[0], \"rb+\");\n\t\tif (f == NULL)\n\t\t{\n\t\t\tfprintf(stderr, \"failed to open file \\\"%s\\\": (%d) %s\\n\"\n\t\t\t\t, argv[0], errno, strerror(errno));\n\t\t\treturn 1;\n\t\t}\n\n\t\tunsigned char seed[32];\n\t\tfread(seed, 1, 32, f);\n\t\tfclose(f);\n\n\t\t++argv;\n\t\t--argc;\n\t\tif (argc < 1) usage();\n\n\t\tboost::array public_key;\n\t\tboost::array private_key;\n\t\ted25519_create_keypair((unsigned char*)public_key.data()\n\t\t\t, (unsigned char*)private_key.data(), seed);\n\t\t\n\t\tbootstrap(s);\n\t\ts.dht_put_item(public_key, boost::bind(&put_string, _1, _2, _3, _4\n\t\t\t, public_key.data(), private_key.data(), argv[0]));\n\n\t\tprintf(\"public key: %s\\n\", to_hex(std::string(public_key.data()\n\t\t\t, public_key.size())).c_str());\n\n\t\twait_for_alert(s, dht_put_alert::alert_type);\n\t}\n\telse if (strcmp(argv[0], \"mget\") == 0)\n\t{\n\t\t++argv;\n\t\t--argc;\n\t\tif (argc < 1) usage();\n\n\t\tint len = strlen(argv[0]);\n\t\tif (len != 64)\n\t\t{\n\t\t\tfprintf(stderr, \"public key is expected to be 64 hex digits\\n\");\n\t\t\treturn 1;\n\t\t}\n\t\tboost::array public_key;\n\t\tbool ret = from_hex(argv[0], len, &public_key[0]);\n\t\tif (!ret)\n\t\t{\n\t\t\tfprintf(stderr, \"invalid hex encoding of public key\\n\");\n\t\t\treturn 1;\n\t\t}\n\n\t\tbootstrap(s);\n\t\ts.dht_get_item(public_key);\n\n\t\tstd::auto_ptr a = wait_for_alert(s, dht_mutable_item_alert::alert_type);\n\n\t\tdht_mutable_item_alert* item = alert_cast(a.get());\n\t\tentry data;\n\t\tif (item)\n\t\t\tdata.swap(item->item);\n\n\t\tprintf(\"%s\", data.to_string().c_str());\n\t}\n\telse\n\t{\n\t\tusage();\n\t}\n\n\tentry e;\n\ts.save_state(e, session::save_dht_state);\n\tstd::vector state;\n\tbencode(std::back_inserter(state), e);\n\tf = fopen(\".dht\", \"wb+\");\n\tif (f == NULL)\n\t{\n\t\tfprintf(stderr, \"failed to open file .dht for writing\");\n\t\treturn 1;\n\t}\n\tfwrite(&state[0], 1, state.size(), f);\n\tfclose(f);\n}\n\n#endif\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: xwin.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: kz $ $Date: 2004-02-25 17:10:20 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"xwin.hxx\"\n#ifndef _COM_SUN_STAR_LANG_SYSTEMDEPENDENT_HPP_\n#include \n#endif\n\n\nusing namespace ::com::sun::star;\n\n\nContainerWindowWrapper::ContainerWindowWrapper(HWND aHwnd)\n : m_aHwnd(aHwnd),\n m_pDisposeEventListeners(0)\n{\n}\n\nContainerWindowWrapper::~ContainerWindowWrapper()\n{\n delete m_pDisposeEventListeners;\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::dispose(\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n cppu::OInterfaceContainerHelper *pDisposeEventListeners(0);\n\n {\n osl::MutexGuard aGuard(m_aMutex);\n pDisposeEventListeners = m_pDisposeEventListeners;\n }\n\n if(pDisposeEventListeners) {\n lang::EventObject aEvt;\n aEvt.Source = static_cast< awt::XWindow* >(this);\n\n pDisposeEventListeners->disposeAndClear(aEvt);\n }\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::addEventListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XEventListener >& Listener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n cppu::OInterfaceContainerHelper *pDisposeEventListeners(0);\n {\n osl::MutexGuard aGuard(m_aMutex);\n pDisposeEventListeners = m_pDisposeEventListeners;\n }\n\n if(! pDisposeEventListeners)\n {\n osl::MutexGuard aGuard(m_aMutex);\n pDisposeEventListeners = m_pDisposeEventListeners =\n new cppu::OInterfaceContainerHelper(m_aMutex);\n }\n\n pDisposeEventListeners->addInterface( Listener );\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::removeEventListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XEventListener >& Listener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n cppu::OInterfaceContainerHelper *pDisposeEventListeners(0);\n {\n osl::MutexGuard aGuard(m_aMutex);\n pDisposeEventListeners = m_pDisposeEventListeners;\n }\n if( pDisposeEventListeners )\n pDisposeEventListeners->removeInterface( Listener );\n}\n\n\n\n\/\/ XSystemDependentWindowPeer\n\n::com::sun::star::uno::Any SAL_CALL\nContainerWindowWrapper::getWindowHandle(\n const ::com::sun::star::uno::Sequence< sal_Int8 >& ProcessId,\n sal_Int16 SystemType\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n if(SystemType == lang::SystemDependent::SYSTEM_WIN32 ||\n SystemType == lang::SystemDependent::SYSTEM_WIN16)\n {\n uno::Any aAny;\n sal_Int32 nHwnd = sal_Int32(m_aHwnd);\n aAny <<= nHwnd;\n return aAny;\n }\n else\n return uno::Any();\n}\n\n\n\nvoid SAL_CALL\nContainerWindowWrapper::setPosSize(\n sal_Int32 X,\n sal_Int32 Y,\n sal_Int32 Width,\n sal_Int32 Height,\n sal_Int16 Flags\n)\n throw (\n ::com::sun::star::uno::RuntimeException)\n{\n\n}\n\n::com::sun::star::awt::Rectangle SAL_CALL\nContainerWindowWrapper::getPosSize(\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n return awt::Rectangle();\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::setVisible(\n sal_Bool Visible\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::setEnable(\n sal_Bool Enable\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::setFocus(\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::addWindowListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XWindowListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::removeWindowListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XWindowListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::addFocusListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XFocusListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::removeFocusListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XFocusListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::addKeyListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XKeyListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::removeKeyListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XKeyListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::addMouseListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XMouseListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::removeMouseListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XMouseListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::addMouseMotionListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XMouseMotionListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::removeMouseMotionListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XMouseMotionListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::addPaintListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XPaintListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::removePaintListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XPaintListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\nINTEGRATION: CWS ooo19126 (1.2.32); FILE MERGED 2005\/09\/05 18:46:13 rt 1.2.32.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xwin.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 18:55:02 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"xwin.hxx\"\n#ifndef _COM_SUN_STAR_LANG_SYSTEMDEPENDENT_HPP_\n#include \n#endif\n\n\nusing namespace ::com::sun::star;\n\n\nContainerWindowWrapper::ContainerWindowWrapper(HWND aHwnd)\n : m_aHwnd(aHwnd),\n m_pDisposeEventListeners(0)\n{\n}\n\nContainerWindowWrapper::~ContainerWindowWrapper()\n{\n delete m_pDisposeEventListeners;\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::dispose(\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n cppu::OInterfaceContainerHelper *pDisposeEventListeners(0);\n\n {\n osl::MutexGuard aGuard(m_aMutex);\n pDisposeEventListeners = m_pDisposeEventListeners;\n }\n\n if(pDisposeEventListeners) {\n lang::EventObject aEvt;\n aEvt.Source = static_cast< awt::XWindow* >(this);\n\n pDisposeEventListeners->disposeAndClear(aEvt);\n }\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::addEventListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XEventListener >& Listener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n cppu::OInterfaceContainerHelper *pDisposeEventListeners(0);\n {\n osl::MutexGuard aGuard(m_aMutex);\n pDisposeEventListeners = m_pDisposeEventListeners;\n }\n\n if(! pDisposeEventListeners)\n {\n osl::MutexGuard aGuard(m_aMutex);\n pDisposeEventListeners = m_pDisposeEventListeners =\n new cppu::OInterfaceContainerHelper(m_aMutex);\n }\n\n pDisposeEventListeners->addInterface( Listener );\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::removeEventListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XEventListener >& Listener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n cppu::OInterfaceContainerHelper *pDisposeEventListeners(0);\n {\n osl::MutexGuard aGuard(m_aMutex);\n pDisposeEventListeners = m_pDisposeEventListeners;\n }\n if( pDisposeEventListeners )\n pDisposeEventListeners->removeInterface( Listener );\n}\n\n\n\n\/\/ XSystemDependentWindowPeer\n\n::com::sun::star::uno::Any SAL_CALL\nContainerWindowWrapper::getWindowHandle(\n const ::com::sun::star::uno::Sequence< sal_Int8 >& ProcessId,\n sal_Int16 SystemType\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n if(SystemType == lang::SystemDependent::SYSTEM_WIN32 ||\n SystemType == lang::SystemDependent::SYSTEM_WIN16)\n {\n uno::Any aAny;\n sal_Int32 nHwnd = sal_Int32(m_aHwnd);\n aAny <<= nHwnd;\n return aAny;\n }\n else\n return uno::Any();\n}\n\n\n\nvoid SAL_CALL\nContainerWindowWrapper::setPosSize(\n sal_Int32 X,\n sal_Int32 Y,\n sal_Int32 Width,\n sal_Int32 Height,\n sal_Int16 Flags\n)\n throw (\n ::com::sun::star::uno::RuntimeException)\n{\n\n}\n\n::com::sun::star::awt::Rectangle SAL_CALL\nContainerWindowWrapper::getPosSize(\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n return awt::Rectangle();\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::setVisible(\n sal_Bool Visible\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::setEnable(\n sal_Bool Enable\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::setFocus(\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::addWindowListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XWindowListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::removeWindowListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XWindowListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::addFocusListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XFocusListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::removeFocusListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XFocusListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::addKeyListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XKeyListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::removeKeyListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XKeyListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::addMouseListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XMouseListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::removeMouseListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XMouseListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\n\nvoid SAL_CALL\nContainerWindowWrapper::addMouseMotionListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XMouseMotionListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::removeMouseMotionListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XMouseMotionListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::addPaintListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XPaintListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n\nvoid SAL_CALL\nContainerWindowWrapper::removePaintListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XPaintListener >& xListener\n)\n throw (\n ::com::sun::star::uno::RuntimeException\n )\n{\n\n}\n<|endoftext|>"} {"text":"#include \"LARASURF.H\"\n\n#include \"CAMERA.H\"\n#include \"COLLIDE.H\"\n#include \"CONTROL.H\"\n#include \"DRAW.H\"\n#include \"LARA.H\"\n#include \"LARAFIRE.H\"\n#include \"SPECIFIC.H\"\n#include INPUT_H\n#include \"LARASWIM.H\"\n\n#if PSX_VERSION\n#include \"COLLIDE_S.H\"\n#endif\n\nvoid lara_col_surftread(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DDBC(<), 4E220(<) (F)\n{\n\tif (item->goal_anim_state == STATE_LARA_UNDERWATER_FORWARD)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_UNDERWATER_DIVING;\n\t\titem->anim_number = ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE;\n\t\titem->pos.x_rot = ANGLE(-45);\n\t\titem->frame_number = anims[ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE].frame_base;\n\t\titem->fallspeed = 80;\n\t\tlara.water_status = LW_UNDERWATER;\n\t}\n\tlara.move_angle = item->pos.y_rot;\n\tLaraSurfaceCollision(item, coll);\n}\n\nvoid lara_col_surfright(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DD90(<), 4E1F4(<) (F)\n{\n\tlara.move_angle = item->pos.y_rot + ANGLE(90);\n\tLaraSurfaceCollision(item, coll);\n}\n\nvoid lara_col_surfleft(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DD64(<), 4E1C8(<) (F)\n{\n\tlara.move_angle = item->pos.y_rot - ANGLE(90);\n\tLaraSurfaceCollision(item, coll);\n}\n\nvoid lara_col_surfback(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DD38(<), 4E19C(<) (F)\n{\n\tlara.move_angle = item->pos.y_rot - ANGLE(180);\n\tLaraSurfaceCollision(item, coll);\n}\n\nvoid lara_col_surfswim(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DCE8(<), 4E14C(<) (F)\n{\n\tcoll->bad_neg = -384;\n\tlara.move_angle = item->pos.y_rot;\n\tLaraSurfaceCollision(item, coll);\n\tLaraTestWaterClimbOut(item, coll);\n}\n\nvoid lara_as_surftread(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DBA0, 4E004 (F)\n{\n\titem->fallspeed -= 4;\n\tif (item->fallspeed < 0)\n\t\titem->fallspeed = 0;\n\n\tif (item->hit_points <= 0)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_WATER_DEATH;\n\n\t\treturn;\n\t}\n\t\n\tif (input & IN_LOOK)\n\t{\n\t\tLookUpDown();\n\t\treturn;\n\t}\n\n\tif (input & IN_LEFT)\n\t{\n\t\titem->pos.y_rot -= ANGLE(4);\n\t}\n\telse if (input & IN_RIGHT)\n\t{\n\t\titem->pos.y_rot += ANGLE(4);\n\t}\n\n\tif(input & IN_FORWARD)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_FORWARD;\n\t}\n\telse if(input & IN_BACK)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_BACK;\n\t}\n\n\tif (input & IN_LSTEP)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_LEFT;\n\t}\n\telse if(input & IN_RSTEP)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_RIGHT;\n\t}\n\n\tif (input & IN_JUMP)\n\t{\n\t\tif (++lara.dive_count == 10)\n\t\t\titem->goal_anim_state = STATE_LARA_UNDERWATER_FORWARD;\n\t}\n\telse\n\t{\n\t\tlara.dive_count = 0;\n\t}\n}\n\nvoid lara_as_surfright(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DAF8, 4DF5C (F)\n{\n\tif (item->hit_points <= 0)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_WATER_DEATH;\n\n\t\treturn;\n\t}\n\t\n\tlara.dive_count = 0;\n\n\tif (input & IN_LEFT)\n\t{\n\t\titem->pos.y_rot -= ANGLE(2);\n\t}\n\telse if (input & IN_RIGHT)\n\t{\n\t\titem->pos.y_rot += ANGLE(2);\n\t}\n\n\tif (!(input & IN_RSTEP))\n\t{\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_STOP;\n\t}\n\n\titem->fallspeed += 8;\n\tif (item->fallspeed > 60)\n\t\titem->fallspeed = 60;\n}\n\nvoid lara_as_surfleft(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DA50(<), 4DEB4(<) (F)\n{\n\tif (item->hit_points <= 0)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_WATER_DEATH;\n\n\t\treturn;\n\t}\n\t\n\tlara.dive_count = 0;\n\t\t\n\tif (input & IN_LEFT)\n\t{\n\t\titem->pos.y_rot -= ANGLE(2);\n\t}\n\telse if (input & IN_RIGHT)\n\t{\n\t\titem->pos.y_rot += ANGLE(2);\n\t}\n\n\tif (!(input & IN_LSTEP))\n\t{\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_STOP;\n\t}\n\n\titem->fallspeed += 8;\n\tif (item->fallspeed > 60)\n\t\titem->fallspeed = 60;\n}\n\nvoid lara_as_surfback(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4D9A8(<), 4DE0C(<) (F)\n{\n\tif (item->hit_points <= 0)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_WATER_DEATH;\n\n\t\treturn;\n\t}\n\t\n\tlara.dive_count = 0;\n\n\tif (input & IN_LEFT)\n\t{\n\t\titem->pos.y_rot -= ANGLE(2);\n\t}\n\telse if (input & IN_RIGHT)\n\t{\n\t\titem->pos.y_rot += ANGLE(2);\n\t}\n\n\tif (!(input & IN_BACK))\n\t{\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_STOP;\n\t}\n\n\titem->fallspeed += 8;\n\tif (item->fallspeed > 60)\n\t\titem->fallspeed = 60;\n}\n\nvoid lara_as_surfswim(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4D8E4(<), 4DD48(<) (F)\n{\n\tif (item->hit_points <= 0)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_WATER_DEATH;\n\n\t\treturn;\n\t}\n\t\n\tlara.dive_count = 0;\n\n\tif (input & IN_LEFT)\n\t{\n\t\titem->pos.y_rot -= ANGLE(4);\n\t}\n\telse if (input & IN_RIGHT)\n\t{\n\t\titem->pos.y_rot += ANGLE(4);\n\t}\n\n\tif (!(input & IN_FORWARD))\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_STOP;\n\tif (input & IN_JUMP)\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_STOP;\n\n\titem->fallspeed += 8;\n\tif (item->fallspeed > 60)\n\t\titem->fallspeed = 60;\n}\n\nvoid LaraSurface(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4D684, 4DAE8 (F)\n{\n\tcamera.target_elevation = ANGLE(-22);\n\n\tcoll->bad_pos = -BAD_HEIGHT;\n\tcoll->bad_neg = -128;\n\tcoll->bad_ceiling = 100;\n\n\tcoll->old.x = item->pos.x_pos;\n\tcoll->old.y = item->pos.y_pos;\n\tcoll->old.z = item->pos.z_pos;\n\n\tcoll->slopes_are_walls = 0;\n\tcoll->slopes_are_pits = 0;\n\tcoll->lava_is_pit = 0;\n\n\tcoll->enable_baddie_push = FALSE;\n\tcoll->enable_spaz = FALSE;\n\t\n\tcoll->radius = 100;\n\tcoll->trigger = 0;\n\n\tif (input & IN_LOOK && lara.look)\n\t\tLookLeftRight();\n\telse\n\t\tResetLook();\n\n\tlara.look = TRUE;\n\n\tlara_control_routines[item->current_anim_state](item, coll);\n\n\titem->pos.z_rot = CLAMPADD(item->pos.z_rot, ANGLE(-2), ANGLE(2));\n\n\tif (lara.current_active && lara.water_status != LW_FLYCHEAT)\n\t\tLaraWaterCurrent(coll);\n\n\tAnimateLara(item);\n\n\titem->pos.x_pos += item->fallspeed * SIN(lara.move_angle) >> W2V_SHIFT;\n\titem->pos.z_pos += item->fallspeed * COS(lara.move_angle) >> W2V_SHIFT;\n\n\tLaraBaddieCollision(item, coll);\n\n\tlara_collision_routines[item->current_anim_state](item, coll);\n\n\tUpdateLaraRoom(item, 100);\n\n\tLaraGun();\n\n\tTestTriggers(coll->trigger, 0, 0);\n}\n\nvoid LaraSurfaceCollision(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4D4F0(<), 4D954(<) (F)\n{\n\tcoll->facing = lara.move_angle;\n\tGetCollisionInfo(coll, item->pos.x_pos, item->pos.y_pos + 700, item->pos.z_pos, item->room_number, 800);\n\tShiftItem(item, coll);\n\tif (coll->coll_type & (CT_FRONT | CT_TOP | CT_TOP_FRONT | CT_CLAMP) || \n\t\tcoll->mid_floor < 0 && (coll->mid_type == BIG_SLOPE || coll->mid_type == DIAGONAL))\n\t{\n\t\titem->fallspeed = 0;\n\t\titem->pos.x_pos = coll->old.x;\n\t\titem->pos.y_pos = coll->old.y;\n\t\titem->pos.z_pos = coll->old.z;\n\t}\n\telse if (coll->coll_type == CT_LEFT)\n\t{\n\t\titem->pos.y_rot += ANGLE(5);\n\t}\n\telse if (coll->coll_type == CT_RIGHT)\n\t{\n\t\titem->pos.y_rot -= ANGLE(5);\n\t}\n\tif (GetWaterHeight(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, item->room_number) - item->pos.y_pos > -100)\n\t{\n\t\tLaraTestWaterStepOut(item, coll);\n\t}\n\telse\n\t{\n\t\titem->goal_anim_state = STATE_LARA_UNDERWATER_FORWARD;\n\t\titem->current_anim_state = STATE_LARA_UNDERWATER_DIVING;\n\t\titem->anim_number = ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE;\n\t\titem->pos.x_rot = ANGLE(-90);\n\t\titem->frame_number = anims[ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE].frame_base;\n\t\titem->fallspeed = 80;\n\t\tlara.water_status = LW_UNDERWATER;\n\t}\n}\n\nint LaraTestWaterClimbOut(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4D22C, 4D690\n{\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nint LaraTestWaterStepOut(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4D100, 4D564 (F)\n{\n\tif (coll->coll_type == CT_FRONT || coll->mid_type == BIG_SLOPE || coll->mid_type == DIAGONAL || coll->mid_floor >= 0)\n\t{\n\t\treturn 0;\n\t}\n\n\tif (coll->mid_floor >= -128)\n\t{\n\t\tif (item->goal_anim_state == STATE_LARA_ONWATER_LEFT)\n\t\t{\n\t\t\titem->goal_anim_state = STATE_LARA_WALK_LEFT;\n\t\t}\n\t\telse if (item->goal_anim_state == STATE_LARA_ONWATER_RIGHT)\n\t\t{\n\t\t\titem->goal_anim_state = STATE_LARA_WALK_RIGHT;\n\t\t}\n\t\telse\n\t\t{\n\t\t\titem->anim_number = ANIMATION_LARA_WADE;\n\t\t\titem->frame_number = anims[ANIMATION_LARA_WADE].frame_base;\n\t\t\titem->goal_anim_state = STATE_LARA_WADE_FORWARD;\n\t\t\titem->current_anim_state = STATE_LARA_WADE_FORWARD;\t\n\t\t}\n\t}\n\telse\n\t{\n\t\titem->anim_number = ANIMATION_LARA_ONWATER_TO_WADE_DEEP;\n\t\titem->frame_number = anims[ANIMATION_LARA_ONWATER_TO_WADE_DEEP].frame_base;\n\t\titem->current_anim_state = STATE_LARA_ONWATER_EXIT;\n\t\titem->goal_anim_state = STATE_LARA_STOP;\n\t}\n\n\titem->pos.y_pos += coll->front_floor + 695;\n\n\tUpdateLaraRoom(item, -381);\n\n\titem->pos.z_rot = 0;\n\titem->pos.x_rot = 0;\n\n\titem->gravity_status = TRUE;\n\titem->speed = 0;\n\titem->fallspeed = 0;\n\n\tlara.water_status = LW_WADE;\n\n\treturn 1;\n}\n[Game]: Correct LaraSurface.#include \"LARASURF.H\"\n\n#include \"CAMERA.H\"\n#include \"COLLIDE.H\"\n#include \"CONTROL.H\"\n#include \"DRAW.H\"\n#include \"LARA.H\"\n#include \"LARAFIRE.H\"\n#include \"SPECIFIC.H\"\n#include INPUT_H\n#include \"LARASWIM.H\"\n\n#if PSX_VERSION\n#include \"COLLIDE_S.H\"\n#endif\n\nvoid lara_col_surftread(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DDBC(<), 4E220(<) (F)\n{\n\tif (item->goal_anim_state == STATE_LARA_UNDERWATER_FORWARD)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_UNDERWATER_DIVING;\n\t\titem->anim_number = ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE;\n\t\titem->pos.x_rot = ANGLE(-45);\n\t\titem->frame_number = anims[ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE].frame_base;\n\t\titem->fallspeed = 80;\n\t\tlara.water_status = LW_UNDERWATER;\n\t}\n\tlara.move_angle = item->pos.y_rot;\n\tLaraSurfaceCollision(item, coll);\n}\n\nvoid lara_col_surfright(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DD90(<), 4E1F4(<) (F)\n{\n\tlara.move_angle = item->pos.y_rot + ANGLE(90);\n\tLaraSurfaceCollision(item, coll);\n}\n\nvoid lara_col_surfleft(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DD64(<), 4E1C8(<) (F)\n{\n\tlara.move_angle = item->pos.y_rot - ANGLE(90);\n\tLaraSurfaceCollision(item, coll);\n}\n\nvoid lara_col_surfback(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DD38(<), 4E19C(<) (F)\n{\n\tlara.move_angle = item->pos.y_rot - ANGLE(180);\n\tLaraSurfaceCollision(item, coll);\n}\n\nvoid lara_col_surfswim(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DCE8(<), 4E14C(<) (F)\n{\n\tcoll->bad_neg = -384;\n\tlara.move_angle = item->pos.y_rot;\n\tLaraSurfaceCollision(item, coll);\n\tLaraTestWaterClimbOut(item, coll);\n}\n\nvoid lara_as_surftread(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DBA0, 4E004 (F)\n{\n\titem->fallspeed -= 4;\n\tif (item->fallspeed < 0)\n\t\titem->fallspeed = 0;\n\n\tif (item->hit_points <= 0)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_WATER_DEATH;\n\n\t\treturn;\n\t}\n\t\n\tif (input & IN_LOOK)\n\t{\n\t\tLookUpDown();\n\t\treturn;\n\t}\n\n\tif (input & IN_LEFT)\n\t{\n\t\titem->pos.y_rot -= ANGLE(4);\n\t}\n\telse if (input & IN_RIGHT)\n\t{\n\t\titem->pos.y_rot += ANGLE(4);\n\t}\n\n\tif(input & IN_FORWARD)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_FORWARD;\n\t}\n\telse if(input & IN_BACK)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_BACK;\n\t}\n\n\tif (input & IN_LSTEP)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_LEFT;\n\t}\n\telse if(input & IN_RSTEP)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_RIGHT;\n\t}\n\n\tif (input & IN_JUMP)\n\t{\n\t\tif (++lara.dive_count == 10)\n\t\t\titem->goal_anim_state = STATE_LARA_UNDERWATER_FORWARD;\n\t}\n\telse\n\t{\n\t\tlara.dive_count = 0;\n\t}\n}\n\nvoid lara_as_surfright(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DAF8, 4DF5C (F)\n{\n\tif (item->hit_points <= 0)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_WATER_DEATH;\n\n\t\treturn;\n\t}\n\t\n\tlara.dive_count = 0;\n\n\tif (input & IN_LEFT)\n\t{\n\t\titem->pos.y_rot -= ANGLE(2);\n\t}\n\telse if (input & IN_RIGHT)\n\t{\n\t\titem->pos.y_rot += ANGLE(2);\n\t}\n\n\tif (!(input & IN_RSTEP))\n\t{\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_STOP;\n\t}\n\n\titem->fallspeed += 8;\n\tif (item->fallspeed > 60)\n\t\titem->fallspeed = 60;\n}\n\nvoid lara_as_surfleft(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4DA50(<), 4DEB4(<) (F)\n{\n\tif (item->hit_points <= 0)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_WATER_DEATH;\n\n\t\treturn;\n\t}\n\t\n\tlara.dive_count = 0;\n\t\t\n\tif (input & IN_LEFT)\n\t{\n\t\titem->pos.y_rot -= ANGLE(2);\n\t}\n\telse if (input & IN_RIGHT)\n\t{\n\t\titem->pos.y_rot += ANGLE(2);\n\t}\n\n\tif (!(input & IN_LSTEP))\n\t{\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_STOP;\n\t}\n\n\titem->fallspeed += 8;\n\tif (item->fallspeed > 60)\n\t\titem->fallspeed = 60;\n}\n\nvoid lara_as_surfback(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4D9A8(<), 4DE0C(<) (F)\n{\n\tif (item->hit_points <= 0)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_WATER_DEATH;\n\n\t\treturn;\n\t}\n\t\n\tlara.dive_count = 0;\n\n\tif (input & IN_LEFT)\n\t{\n\t\titem->pos.y_rot -= ANGLE(2);\n\t}\n\telse if (input & IN_RIGHT)\n\t{\n\t\titem->pos.y_rot += ANGLE(2);\n\t}\n\n\tif (!(input & IN_BACK))\n\t{\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_STOP;\n\t}\n\n\titem->fallspeed += 8;\n\tif (item->fallspeed > 60)\n\t\titem->fallspeed = 60;\n}\n\nvoid lara_as_surfswim(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4D8E4(<), 4DD48(<) (F)\n{\n\tif (item->hit_points <= 0)\n\t{\n\t\titem->goal_anim_state = STATE_LARA_WATER_DEATH;\n\n\t\treturn;\n\t}\n\t\n\tlara.dive_count = 0;\n\n\tif (input & IN_LEFT)\n\t{\n\t\titem->pos.y_rot -= ANGLE(4);\n\t}\n\telse if (input & IN_RIGHT)\n\t{\n\t\titem->pos.y_rot += ANGLE(4);\n\t}\n\n\tif (!(input & IN_FORWARD))\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_STOP;\n\tif (input & IN_JUMP)\n\t\titem->goal_anim_state = STATE_LARA_ONWATER_STOP;\n\n\titem->fallspeed += 8;\n\tif (item->fallspeed > 60)\n\t\titem->fallspeed = 60;\n}\n\nvoid LaraSurface(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4D684, 4DAE8 (F)\n{\n\tcamera.target_elevation = ANGLE(-22);\n\n\tcoll->bad_pos = -BAD_HEIGHT;\n\tcoll->bad_neg = -128;\n\tcoll->bad_ceiling = 100;\n\n\tcoll->old.x = item->pos.x_pos;\n\tcoll->old.y = item->pos.y_pos;\n\tcoll->old.z = item->pos.z_pos;\n\n\tcoll->slopes_are_walls = 0;\n\tcoll->slopes_are_pits = 0;\n\tcoll->lava_is_pit = 0;\n\n\tcoll->enable_baddie_push = FALSE;\n\tcoll->enable_spaz = FALSE;\n\t\n\tcoll->radius = 100;\n\tcoll->trigger = 0;\n\n\tif (input & IN_LOOK && lara.look)\n\t\tLookLeftRight();\n\telse\n\t\tResetLook();\n\n\tlara.look = TRUE;\n\n\tlara_control_routines[item->current_anim_state](item, coll);\n\n\titem->pos.z_rot = CLAMPADD(item->pos.z_rot, ANGLE(-2), ANGLE(2));\n\n\tif (lara.current_active && lara.water_status != LW_FLYCHEAT)\n\t\tLaraWaterCurrent(coll);\n\n\tAnimateLara(item);\n\n#if PSX_VERSION\n\titem->pos.x_pos += item->fallspeed * SIN(lara.move_angle) >> 14;\n\titem->pos.z_pos += item->fallspeed * COS(lara.move_angle) >> 14;\n#elif PC_VERSION\n\titem->pos.x_pos += item->fallspeed * SIN(lara.move_angle) >> W2V_SHIFT;\n\titem->pos.z_pos += item->fallspeed * COS(lara.move_angle) >> W2V_SHIFT;\n#endif\n\n\tLaraBaddieCollision(item, coll);\n\n\tlara_collision_routines[item->current_anim_state](item, coll);\n\n\tUpdateLaraRoom(item, 100);\n\n\tLaraGun();\n\n\tTestTriggers(coll->trigger, 0, 0);\n}\n\nvoid LaraSurfaceCollision(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4D4F0(<), 4D954(<) (F)\n{\n\tcoll->facing = lara.move_angle;\n\tGetCollisionInfo(coll, item->pos.x_pos, item->pos.y_pos + 700, item->pos.z_pos, item->room_number, 800);\n\tShiftItem(item, coll);\n\tif (coll->coll_type & (CT_FRONT | CT_TOP | CT_TOP_FRONT | CT_CLAMP) || \n\t\tcoll->mid_floor < 0 && (coll->mid_type == BIG_SLOPE || coll->mid_type == DIAGONAL))\n\t{\n\t\titem->fallspeed = 0;\n\t\titem->pos.x_pos = coll->old.x;\n\t\titem->pos.y_pos = coll->old.y;\n\t\titem->pos.z_pos = coll->old.z;\n\t}\n\telse if (coll->coll_type == CT_LEFT)\n\t{\n\t\titem->pos.y_rot += ANGLE(5);\n\t}\n\telse if (coll->coll_type == CT_RIGHT)\n\t{\n\t\titem->pos.y_rot -= ANGLE(5);\n\t}\n\tif (GetWaterHeight(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, item->room_number) - item->pos.y_pos > -100)\n\t{\n\t\tLaraTestWaterStepOut(item, coll);\n\t}\n\telse\n\t{\n\t\titem->goal_anim_state = STATE_LARA_UNDERWATER_FORWARD;\n\t\titem->current_anim_state = STATE_LARA_UNDERWATER_DIVING;\n\t\titem->anim_number = ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE;\n\t\titem->pos.x_rot = ANGLE(-90);\n\t\titem->frame_number = anims[ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE].frame_base;\n\t\titem->fallspeed = 80;\n\t\tlara.water_status = LW_UNDERWATER;\n\t}\n}\n\nint LaraTestWaterClimbOut(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4D22C, 4D690\n{\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nint LaraTestWaterStepOut(struct ITEM_INFO* item, struct COLL_INFO* coll)\/\/4D100, 4D564 (F)\n{\n\tif (coll->coll_type == CT_FRONT || coll->mid_type == BIG_SLOPE || coll->mid_type == DIAGONAL || coll->mid_floor >= 0)\n\t{\n\t\treturn 0;\n\t}\n\n\tif (coll->mid_floor >= -128)\n\t{\n\t\tif (item->goal_anim_state == STATE_LARA_ONWATER_LEFT)\n\t\t{\n\t\t\titem->goal_anim_state = STATE_LARA_WALK_LEFT;\n\t\t}\n\t\telse if (item->goal_anim_state == STATE_LARA_ONWATER_RIGHT)\n\t\t{\n\t\t\titem->goal_anim_state = STATE_LARA_WALK_RIGHT;\n\t\t}\n\t\telse\n\t\t{\n\t\t\titem->anim_number = ANIMATION_LARA_WADE;\n\t\t\titem->frame_number = anims[ANIMATION_LARA_WADE].frame_base;\n\t\t\titem->goal_anim_state = STATE_LARA_WADE_FORWARD;\n\t\t\titem->current_anim_state = STATE_LARA_WADE_FORWARD;\t\n\t\t}\n\t}\n\telse\n\t{\n\t\titem->anim_number = ANIMATION_LARA_ONWATER_TO_WADE_DEEP;\n\t\titem->frame_number = anims[ANIMATION_LARA_ONWATER_TO_WADE_DEEP].frame_base;\n\t\titem->current_anim_state = STATE_LARA_ONWATER_EXIT;\n\t\titem->goal_anim_state = STATE_LARA_STOP;\n\t}\n\n\titem->pos.y_pos += coll->front_floor + 695;\n\n\tUpdateLaraRoom(item, -381);\n\n\titem->pos.z_rot = 0;\n\titem->pos.x_rot = 0;\n\n\titem->gravity_status = TRUE;\n\titem->speed = 0;\n\titem->fallspeed = 0;\n\n\tlara.water_status = LW_WADE;\n\n\treturn 1;\n}\n<|endoftext|>"} {"text":"#include \"Trie.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Postgres.h\"\n#include \"Utils.h\"\n\nusing namespace std;\nusing namespace btree;\n\n\/\/\n\/\/ Trie::~Trie\n\/\/\nTrie::~Trie() {\n for (btree_map::iterator iter = children.begin(); iter != children.end(); ++iter) {\n delete iter->second;\n }\n}\n\n\/\/\n\/\/ Trie::add\n\/\/\nvoid Trie::add(const edge* elements, const uint8_t& length,\n const Graph* graph) {\n \/\/ Corner cases\n if (length == 0) { return; } \/\/ this case shouldn't actually happen normally...\n \/\/ Register child\n const word w = elements[0].source;\n assert (w > 0);\n const btree_map::iterator childIter = children.find( w );\n Trie* child = NULL;\n if (childIter == children.end()) {\n child = new Trie();\n children[w] = child;\n } else {\n child = childIter->second;\n }\n \/\/ Register skip-gram\n if (length > 1) {\n const word grandChildW = elements[1].source;\n assert (grandChildW > 0);\n skipGrams[grandChildW].push_back(w);\n }\n \/\/ Register information about child\n if (graph == NULL || graph->containsDeletion(elements[0])) {\n child->registerEdge(elements[0]);\n }\n \/\/ Recursive call\n if (length == 1) {\n child->isLeaf = true; \/\/ Mark this as a leaf node\n completions[w] = child; \/\/ register a completion\n } else {\n child->add(&(elements[1]), length - 1, graph);\n }\n}\n\ninline uint8_t min(const uint8_t& a, const uint8_t b) { return a < b ? a : b; }\n\n\/\/\n\/\/ Trie::addCompletion\n\/\/\ninline void Trie::addCompletion(const Trie* child, const word& source,\n edge* insertion, uint32_t& index) const {\n if (index < MAX_COMPLETIONS - 4) {\n \/\/ case: write directly to insertion buffer\n uint8_t numEdges = child->getEdges(&(insertion[index]));\n for (int i = 0; i < numEdges; ++i) { insertion[index + i].source = source; }\n index += numEdges;\n } else {\n \/\/ case: write to temporary buffer and copy over\n edge buffer[4];\n uint8_t bufferedEdges = child->getEdges(buffer);\n uint8_t numEdges = min( MAX_COMPLETIONS - index, bufferedEdges );\n for (int i = 0; i < numEdges; ++i) { buffer[i].source = source; }\n memcpy(&(insertion[index]), buffer, numEdges * sizeof(edge));\n index += numEdges;\n }\n}\n\n\n\/\/\n\/\/ Trie::contains\n\/\/\nconst bool Trie::contains(const tagged_word* query, \n const uint8_t& queryLength,\n const int16_t& mutationIndex,\n edge* insertions) const {\n assert (queryLength > mutationIndex);\n uint32_t mutableIndex = 0;\n bool contains;\n if (mutationIndex == -1) {\n if (queryLength > 0) {\n btree_map>::const_iterator skipGramIter = skipGrams.find( query[0].word );\n if (skipGramIter != skipGrams.end()) {\n \/\/ Case: add anything that leads into the second term\n for (vector::const_iterator iter = skipGramIter->second.begin(); iter != skipGramIter->second.end(); ++iter) {\n btree_map::const_iterator childIter = children.find( *iter );\n if (childIter != children.end()) {\n addCompletion(childIter->second, childIter->first, insertions, mutableIndex);\n }\n if (mutableIndex >= MAX_COMPLETIONS) { break; }\n }\n } else {\n \/\/ Case: we're kind of shit out of luck. We're inserting into the\n \/\/ beginning of the sentence, but with no valid skip-grams.\n \/\/ So, let's just add some starting words and pray.\n for (btree_map::const_iterator childIter = children.begin(); childIter != children.end(); ++childIter) {\n addCompletion(childIter->second, childIter->first, insertions, mutableIndex);\n if (mutableIndex >= MAX_COMPLETIONS) { break; }\n }\n }\n } else {\n \/\/ Case: add any single-term completions\n for (btree_map::const_iterator iter = children.begin(); iter != children.end(); ++iter) {\n if (iter->second->isLeaf) {\n addCompletion(iter->second, iter->first, insertions, mutableIndex);\n if (mutableIndex >= MAX_COMPLETIONS) { break; }\n }\n }\n }\n contains = containsImpl(query, queryLength, -9000, insertions, mutableIndex); \/\/ already added completions\n } else {\n contains = containsImpl(query, queryLength, mutationIndex, insertions, mutableIndex);\n }\n\n \/\/ Return\n if (mutableIndex < MAX_COMPLETIONS) {\n insertions[mutableIndex].source = 0;\n }\n return contains;\n}\n\n\/\/\n\/\/ Trie::containsImpl\n\/\/\nconst bool Trie::containsImpl(const tagged_word* query, \n const uint8_t& queryLength,\n const int16_t& mutationIndex,\n edge* insertions,\n uint32_t& mutableIndex) const {\n assert (queryLength > mutationIndex);\n\n \/\/ -- Part 1: Fill in completions --\n if (mutationIndex == -1) {\n const bool tooManyChildren = (children.size() > MAX_COMPLETIONS);\n if (!tooManyChildren) {\n \/\/ sub-case: add all children\n btree_map::const_iterator iter;\n for (iter = children.begin(); iter != children.end(); ++iter) {\n addCompletion(iter->second, iter->first, insertions, mutableIndex);\n if (mutableIndex >= MAX_COMPLETIONS) { break; }\n }\n } else {\n \/\/ sub-case: too many children; only add completions\n for (btree_map::const_iterator iter = completions.begin(); iter != completions.end(); ++iter) {\n addCompletion(iter->second, iter->first, insertions, mutableIndex);\n if (mutableIndex >= MAX_COMPLETIONS) { break; }\n }\n }\n }\n \n \/\/ -- Part 2: Check containment --\n if (queryLength == 0) {\n \/\/ return whether the fact exists\n return isLeaf;\n } else {\n \/\/ Case: we're in the middle of the query\n btree_map::const_iterator childIter = children.find( query[0].word );\n if (childIter == children.end()) {\n \/\/ Return false\n return false;\n } else {\n \/\/ Check the child\n return childIter->second->containsImpl(&(query[1]), \n queryLength - 1,\n mutationIndex - 1,\n insertions,\n mutableIndex);\n }\n }\n}\n\n\n\/\/\n\/\/ ReadFactTrie\n\/\/\nFactDB* ReadFactTrie(const uint64_t maxFactsToRead, const Graph* graph) {\n Trie* facts = new Trie();\n char query[127];\n\n \/\/ Read valid deletions\n printf(\"Reading registered deletions...\\n\");\n unordered_map> word2senses;\n \/\/ (query)\n snprintf(query, 127, \"SELECT DISTINCT (source) source, source_sense, type FROM %s WHERE source<>0 AND sink=0 ORDER BY type;\", PG_TABLE_EDGE);\n PGIterator wordIter = PGIterator(query);\n uint32_t numValidInsertions = 0;\n while (wordIter.hasNext()) {\n \/\/ Get fact\n PGRow row = wordIter.next();\n \/\/ Create edge\n edge e;\n e.source = atoi(row[0]);\n e.source_sense = atoi(row[1]);\n e.type = atoi(row[2]);\n e.cost = 1.0f;\n \/\/ Register edge\n word2senses[e.source].push_back(e);\n numValidInsertions += 1;\n }\n printf(\" Done. %u words have sense tags\\n\", numValidInsertions);\n\n\n \/\/ Read facts\n printf(\"Reading facts...\\n\");\n \/\/ (query)\n if (maxFactsToRead == std::numeric_limits::max()) {\n snprintf(query, 127,\n \"SELECT gloss, weight FROM %s ORDER BY weight DESC;\",\n PG_TABLE_FACT);\n } else {\n snprintf(query, 127,\n \"SELECT gloss, weight FROM %s ORDER BY weight DESC LIMIT %lu;\",\n PG_TABLE_FACT,\n maxFactsToRead);\n }\n PGIterator iter = PGIterator(query);\n uint64_t i = 0;\n edge buffer[256];\n uint8_t bufferLength;\n while (iter.hasNext()) {\n \/\/ Get fact\n PGRow row = iter.next();\n const char* gloss = row[0];\n uint32_t weight = atoi(row[1]);\n if (weight < MIN_FACT_COUNT) { break; }\n \/\/ Parse fact\n stringstream stream (&gloss[1]);\n bufferLength = 0;\n while( stream.good() ) {\n \/\/ Parse the word\n string substr;\n getline( stream, substr, ',' );\n word w = atoi(substr.c_str());\n \/\/ Register the word\n unordered_map>::iterator iter = word2senses.find( w );\n if (iter == word2senses.end() || iter->second.size() == 0) {\n buffer[bufferLength].source = w;\n buffer[bufferLength].source_sense = 0;\n buffer[bufferLength].type = 0;\n buffer[bufferLength].cost = 1.0f;\n } else {\n buffer[bufferLength] = iter->second[0];\n }\n buffer[bufferLength].sink = 0;\n buffer[bufferLength].sink_sense = 0;\n if (bufferLength >= MAX_FACT_LENGTH) { break; }\n bufferLength += 1;\n }\n \/\/ Add fact\n \/\/ Add 'canonical' version\n facts->add(buffer, bufferLength, graph);\n \/\/ Add word sense variants\n for (uint32_t k = 0; k < bufferLength; ++k) {\n unordered_map>::iterator iter = word2senses.find( buffer[k].source );\n if (iter != word2senses.end() && iter->second.size() > 1) {\n for (uint32_t sense = 1; sense < iter->second.size(); ++sense) {\n buffer[k] = iter->second[sense];\n facts->add(buffer, bufferLength, graph);\n }\n }\n }\n \/\/ Debug\n i += 1;\n if (i % 10000000 == 0) {\n printf(\" loaded %luM facts\\n\", i \/ 1000000);\n }\n }\n\n \/\/ Return\n printf(\" done reading the fact database (%lu facts read)\\n\", i);\n return facts;\n}\nDebug reading the factdb more#include \"Trie.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Postgres.h\"\n#include \"Utils.h\"\n\nusing namespace std;\nusing namespace btree;\n\n\/\/\n\/\/ Trie::~Trie\n\/\/\nTrie::~Trie() {\n for (btree_map::iterator iter = children.begin(); iter != children.end(); ++iter) {\n delete iter->second;\n }\n}\n\n\/\/\n\/\/ Trie::add\n\/\/\nvoid Trie::add(const edge* elements, const uint8_t& length,\n const Graph* graph) {\n \/\/ Corner cases\n if (length == 0) { return; } \/\/ this case shouldn't actually happen normally...\n \/\/ Register child\n const word w = elements[0].source;\n assert (w > 0);\n const btree_map::iterator childIter = children.find( w );\n Trie* child = NULL;\n if (childIter == children.end()) {\n child = new Trie();\n children[w] = child;\n } else {\n child = childIter->second;\n }\n \/\/ Register skip-gram\n if (length > 1) {\n const word grandChildW = elements[1].source;\n assert (grandChildW > 0);\n skipGrams[grandChildW].push_back(w);\n }\n \/\/ Register information about child\n if (graph == NULL || graph->containsDeletion(elements[0])) {\n child->registerEdge(elements[0]);\n }\n \/\/ Recursive call\n if (length == 1) {\n child->isLeaf = true; \/\/ Mark this as a leaf node\n completions[w] = child; \/\/ register a completion\n } else {\n child->add(&(elements[1]), length - 1, graph);\n }\n}\n\ninline uint8_t min(const uint8_t& a, const uint8_t b) { return a < b ? a : b; }\n\n\/\/\n\/\/ Trie::addCompletion\n\/\/\ninline void Trie::addCompletion(const Trie* child, const word& source,\n edge* insertion, uint32_t& index) const {\n if (index < MAX_COMPLETIONS - 4) {\n \/\/ case: write directly to insertion buffer\n uint8_t numEdges = child->getEdges(&(insertion[index]));\n for (int i = 0; i < numEdges; ++i) { insertion[index + i].source = source; }\n index += numEdges;\n } else {\n \/\/ case: write to temporary buffer and copy over\n edge buffer[4];\n uint8_t bufferedEdges = child->getEdges(buffer);\n uint8_t numEdges = min( MAX_COMPLETIONS - index, bufferedEdges );\n for (int i = 0; i < numEdges; ++i) { buffer[i].source = source; }\n memcpy(&(insertion[index]), buffer, numEdges * sizeof(edge));\n index += numEdges;\n }\n}\n\n\n\/\/\n\/\/ Trie::contains\n\/\/\nconst bool Trie::contains(const tagged_word* query, \n const uint8_t& queryLength,\n const int16_t& mutationIndex,\n edge* insertions) const {\n assert (queryLength > mutationIndex);\n uint32_t mutableIndex = 0;\n bool contains;\n if (mutationIndex == -1) {\n if (queryLength > 0) {\n btree_map>::const_iterator skipGramIter = skipGrams.find( query[0].word );\n if (skipGramIter != skipGrams.end()) {\n \/\/ Case: add anything that leads into the second term\n for (vector::const_iterator iter = skipGramIter->second.begin(); iter != skipGramIter->second.end(); ++iter) {\n btree_map::const_iterator childIter = children.find( *iter );\n if (childIter != children.end()) {\n addCompletion(childIter->second, childIter->first, insertions, mutableIndex);\n }\n if (mutableIndex >= MAX_COMPLETIONS) { break; }\n }\n } else {\n \/\/ Case: we're kind of shit out of luck. We're inserting into the\n \/\/ beginning of the sentence, but with no valid skip-grams.\n \/\/ So, let's just add some starting words and pray.\n for (btree_map::const_iterator childIter = children.begin(); childIter != children.end(); ++childIter) {\n addCompletion(childIter->second, childIter->first, insertions, mutableIndex);\n if (mutableIndex >= MAX_COMPLETIONS) { break; }\n }\n }\n } else {\n \/\/ Case: add any single-term completions\n for (btree_map::const_iterator iter = children.begin(); iter != children.end(); ++iter) {\n if (iter->second->isLeaf) {\n addCompletion(iter->second, iter->first, insertions, mutableIndex);\n if (mutableIndex >= MAX_COMPLETIONS) { break; }\n }\n }\n }\n contains = containsImpl(query, queryLength, -9000, insertions, mutableIndex); \/\/ already added completions\n } else {\n contains = containsImpl(query, queryLength, mutationIndex, insertions, mutableIndex);\n }\n\n \/\/ Return\n if (mutableIndex < MAX_COMPLETIONS) {\n insertions[mutableIndex].source = 0;\n }\n return contains;\n}\n\n\/\/\n\/\/ Trie::containsImpl\n\/\/\nconst bool Trie::containsImpl(const tagged_word* query, \n const uint8_t& queryLength,\n const int16_t& mutationIndex,\n edge* insertions,\n uint32_t& mutableIndex) const {\n assert (queryLength > mutationIndex);\n\n \/\/ -- Part 1: Fill in completions --\n if (mutationIndex == -1) {\n const bool tooManyChildren = (children.size() > MAX_COMPLETIONS);\n if (!tooManyChildren) {\n \/\/ sub-case: add all children\n btree_map::const_iterator iter;\n for (iter = children.begin(); iter != children.end(); ++iter) {\n addCompletion(iter->second, iter->first, insertions, mutableIndex);\n if (mutableIndex >= MAX_COMPLETIONS) { break; }\n }\n } else {\n \/\/ sub-case: too many children; only add completions\n for (btree_map::const_iterator iter = completions.begin(); iter != completions.end(); ++iter) {\n addCompletion(iter->second, iter->first, insertions, mutableIndex);\n if (mutableIndex >= MAX_COMPLETIONS) { break; }\n }\n }\n }\n \n \/\/ -- Part 2: Check containment --\n if (queryLength == 0) {\n \/\/ return whether the fact exists\n return isLeaf;\n } else {\n \/\/ Case: we're in the middle of the query\n btree_map::const_iterator childIter = children.find( query[0].word );\n if (childIter == children.end()) {\n \/\/ Return false\n return false;\n } else {\n \/\/ Check the child\n return childIter->second->containsImpl(&(query[1]), \n queryLength - 1,\n mutationIndex - 1,\n insertions,\n mutableIndex);\n }\n }\n}\n\n\n\/\/\n\/\/ ReadFactTrie\n\/\/\nFactDB* ReadFactTrie(const uint64_t maxFactsToRead, const Graph* graph) {\n Trie* facts = new Trie();\n char query[127];\n\n \/\/ Read valid deletions\n printf(\"Reading registered deletions...\\n\");\n unordered_map> word2senses;\n \/\/ (query)\n snprintf(query, 127, \"SELECT DISTINCT (source) source, source_sense, type FROM %s WHERE source<>0 AND sink=0 ORDER BY type;\", PG_TABLE_EDGE);\n PGIterator wordIter = PGIterator(query);\n uint32_t numValidInsertions = 0;\n while (wordIter.hasNext()) {\n \/\/ Get fact\n PGRow row = wordIter.next();\n \/\/ Create edge\n edge e;\n e.source = atoi(row[0]);\n e.source_sense = atoi(row[1]);\n e.type = atoi(row[2]);\n e.cost = 1.0f;\n \/\/ Register edge\n word2senses[e.source].push_back(e);\n numValidInsertions += 1;\n }\n printf(\" Done. %u words have sense tags\\n\", numValidInsertions);\n\n\n \/\/ Read facts\n printf(\"Reading facts...\\n\");\n \/\/ (query)\n if (maxFactsToRead == std::numeric_limits::max()) {\n snprintf(query, 127,\n \"SELECT gloss, weight FROM %s ORDER BY weight DESC;\",\n PG_TABLE_FACT);\n } else {\n snprintf(query, 127,\n \"SELECT gloss, weight FROM %s ORDER BY weight DESC LIMIT %lu;\",\n PG_TABLE_FACT,\n maxFactsToRead);\n }\n PGIterator iter = PGIterator(query);\n uint64_t i = 0;\n edge buffer[256];\n uint8_t bufferLength;\n while (iter.hasNext()) {\n \/\/ Get fact\n PGRow row = iter.next();\n const char* gloss = row[0];\n uint32_t weight = atoi(row[1]);\n if (weight < MIN_FACT_COUNT) { break; }\n \/\/ Parse fact\n stringstream stream (&gloss[1]);\n bufferLength = 0;\n while( stream.good() ) {\n \/\/ Parse the word\n string substr;\n getline( stream, substr, ',' );\n word w = atoi(substr.c_str());\n \/\/ Register the word\n unordered_map>::iterator iter = word2senses.find( w );\n if (iter == word2senses.end() || iter->second.size() == 0) {\n buffer[bufferLength].source = w;\n buffer[bufferLength].source_sense = 0;\n buffer[bufferLength].type = 0;\n buffer[bufferLength].cost = 1.0f;\n } else {\n buffer[bufferLength] = iter->second[0];\n }\n buffer[bufferLength].sink = 0;\n buffer[bufferLength].sink_sense = 0;\n if (bufferLength >= MAX_FACT_LENGTH) { break; }\n bufferLength += 1;\n }\n \/\/ Add fact\n \/\/ Add 'canonical' version\n facts->add(buffer, bufferLength, graph);\n \/\/ Add word sense variants\n for (uint32_t k = 0; k < bufferLength; ++k) {\n unordered_map>::iterator iter = word2senses.find( buffer[k].source );\n if (iter != word2senses.end() && iter->second.size() > 1) {\n for (uint32_t sense = 1; sense < iter->second.size(); ++sense) {\n buffer[k] = iter->second[sense];\n facts->add(buffer, bufferLength, graph);\n }\n }\n }\n \/\/ Debug\n i += 1;\n if (i % 1000 == 0) {\n printf(\" loaded %lu facts\\n\", i);\n }\n }\n\n \/\/ Return\n printf(\" done reading the fact database (%lu facts read)\\n\", i);\n return facts;\n}\n<|endoftext|>"} {"text":"#include \"GameProcess.h\"\n#include \"Object.h\"\n#include \"Engine.h\"\n#include \"World.h\"\n#include \"App.h\"\n#include \"ToolsCamera.h\"\n#include \"ControlsApp.h\"\n#include \"MathLib.h\"\n#include \"Game.h\"\n#include \"Editor.h\"\n#include \"Input.h\"\n#include \"BlueRayUtils.h\"\n\n\nusing namespace MathLib;\n\nCGameProcess::CGameProcess(void)\n{\n\n}\n\nCGameProcess::~CGameProcess(void)\n{\n\n}\nint CGameProcess::Init()\n{\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"char\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"node\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"smesh\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"sanim\");\n\n\tg_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/test\/test.world\");\n\t\/\/g_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/cj\/cj.world\"); \n\tg_Engine.pControls->SetKeyPressFunc(KeyPress);\n\tg_Engine.pControls->SetKeyReleaseFunc(KeyRelease);\n\n\tm_pRole = new CFPSRoleLocal();\n\tm_pRole->Init(10001, \"data\/role\/hero\/FpsRole\/fps.char\");\t\t\/\/ؽɫԴ\n\n\tm_pRole->SetActorPosition(vec3(0, 0, 0));\t\/\/ýɫʼλáŴΪԭ㣬άϵvec3\n\tm_pSkillSystem = new CSkillSystem(this);\n\tm_pCameraBase = new CCameraBase();\n\tm_pCameraBase->SetEnabled(1);\n\tg_pSysControl->SetMouseGrab(1);\n\n\tm_pStarControl = new CStarControl();\n\tm_pRayControl = new CRayControl();\n\n\treturn 1;\n}\n\nint CGameProcess::ShutDown()\t\t\t\/\/رϷ\n{\n\tdelete m_pRole;\n\tdelete m_pSkillSystem;\n\tdelete m_pCameraBase;\n\tdelete m_pStarControl;\n\tdelete m_pRayControl;\n\n\tDelAllListen();\n\treturn 0;\n}\n\nint CGameProcess::Update()\n{\n\tfloat ifps = g_Engine.pGame->GetIFps();\n\n\tif (g_Engine.pInput->IsKeyDown('1'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"attack02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tpAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);\n\t\t\tm_pRole->StopMove();\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('2'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill01\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('3'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCRoleBase* pTarget = NULL;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 15.0f)\n\t\t\t\t{\n\t\t\t\t\tpTarget = m_vAIList[i];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (pTarget)\n\t\t\t{\n\t\t\t\tCVector vTarget;\n\t\t\t\tvTarget.Append(pTarget->GetRoleID());\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t\tm_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('4'))\/\/෢ӵ\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector vTarget;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t{\n\t\t\t\t\tvTarget.Append(m_vAIList[i]->GetRoleID());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!vTarget.Empty())\n\t\t\t{\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('5'))\n\t{\n\n\t}\n}\n\n\n\n\treturn 0;\n}\n\n\nSigned-off-by: mrlitong #include \"GameProcess.h\"\n#include \"Object.h\"\n#include \"Engine.h\"\n#include \"World.h\"\n#include \"App.h\"\n#include \"ToolsCamera.h\"\n#include \"ControlsApp.h\"\n#include \"MathLib.h\"\n#include \"Game.h\"\n#include \"Editor.h\"\n#include \"Input.h\"\n#include \"BlueRayUtils.h\"\n#include \"World.h\"\n\nusing namespace MathLib;\n\nCGameProcess::CGameProcess(void)\n{\n\n}\n\nCGameProcess::~CGameProcess(void)\n{\n\n}\nint CGameProcess::Init()\n{\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"char\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"node\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"smesh\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"sanim\");\n\n\tg_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/test\/test.world\");\n\t\/\/g_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/cj\/cj.world\"); \n\tg_Engine.pControls->SetKeyPressFunc(KeyPress);\n\tg_Engine.pControls->SetKeyReleaseFunc(KeyRelease);\n\n\tm_pRole = new CFPSRoleLocal();\n\tm_pRole->Init(10001, \"data\/role\/hero\/FpsRole\/fps.char\");\t\t\/\/ؽɫԴ\n\n\tm_pRole->SetActorPosition(vec3(0, 0, 0));\t\/\/ýɫʼλáŴΪԭ㣬άϵvec3\n\tm_pSkillSystem = new CSkillSystem(this);\n\tm_pCameraBase = new CCameraBase();\n\tm_pCameraBase->SetEnabled(1);\n\tg_pSysControl->SetMouseGrab(1);\n\n\tm_pStarControl = new CStarControl();\n\tm_pRayControl = new CRayControl();\n\n\treturn 1;\n}\n\nint CGameProcess::ShutDown()\t\t\t\/\/رϷ\n{\n\tdelete m_pRole;\n\tdelete m_pSkillSystem;\n\tdelete m_pCameraBase;\n\tdelete m_pStarControl;\n\tdelete m_pRayControl;\n\n\tDelAllListen();\n\treturn 0;\n}\n\nint CGameProcess::Update()\n{\n\tfloat ifps = g_Engine.pGame->GetIFps();\n\n\tif (g_Engine.pInput->IsKeyDown('1'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"attack02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tpAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);\n\t\t\tm_pRole->StopMove();\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('2'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill01\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('3'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCRoleBase* pTarget = NULL;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 15.0f)\n\t\t\t\t{\n\t\t\t\t\tpTarget = m_vAIList[i];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (pTarget)\n\t\t\t{\n\t\t\t\tCVector vTarget;\n\t\t\t\tvTarget.Append(pTarget->GetRoleID());\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t\tm_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('4'))\/\/෢ӵ\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector vTarget;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t{\n\t\t\t\t\tvTarget.Append(m_vAIList[i]->GetRoleID());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!vTarget.Empty())\n\t\t\t{\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('5'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill03\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t}\n\n\t}\n}\n\n\n\n\treturn 0;\n}\n\n\n<|endoftext|>"} {"text":"#include \"GameProcess.h\"\n#include \"Object.h\"\n#include \"Engine.h\"\n#include \"World.h\"\n#include \"App.h\"\n#include \"ToolsCamera.h\"\n#include \"ControlsApp.h\"\n#include \"MathLib.h\"\n#include \"Game.h\"\n#include \"Editor.h\"\n#include \"Input.h\"\n#include \"BlueRayUtils.h\"\n#include \"World.h\"\n#include \"Action.h\"\n#include \"FPSRoleLocal.h\"\n\nusing namespace MathLib;\n\nCGameProcess::CGameProcess(void)\n{\n\n}\n\nCGameProcess::~CGameProcess(void)\n{\n\n}\nint CGameProcess::Init()\n{\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"char\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"node\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"smesh\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"sanim\");\n\n\tg_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/test\/test.world\");\n\t\/\/g_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/cj\/cj.world\"); \n\tg_Engine.pControls->SetKeyPressFunc(KeyPress);\n\tg_Engine.pControls->SetKeyReleaseFunc(KeyRelease);\n\n\tm_pRole = new CFPSRoleLocal();\n\tm_pRole->Init(10001, \"data\/role\/hero\/FpsRole\/fps.char\");\t\t\/\/ؽɫԴ\n\n\tm_pRole->SetActorPosition(vec3(0, 0, 0));\t\/\/ýɫʼλáŴΪԭ㣬άϵvec3\n\tm_pSkillSystem = new CSkillSystem(this);\n\tm_pCameraBase = new CCameraBase();\n\tm_pCameraBase->SetEnabled(1);\n\tg_pSysControl->SetMouseGrab(1);\n\n\tm_pStarControl = new CStarControl();\n\tm_pRayControl = new CRayControl();\n\n\treturn 1;\n}\n\nint CGameProcess::ShutDown()\t\t\t\/\/رϷ\n{\n\tdelete m_pRole;\n\tdelete m_pSkillSystem;\n\tdelete m_pCameraBase;\n\tdelete m_pStarControl;\n\tdelete m_pRayControl;\n\n\tDelAllListen();\n\treturn 0;\n}\n\nint CGameProcess::Update()\n{\n\tfloat ifps = g_Engine.pGame->GetIFps();\n\n\tif (g_Engine.pInput->IsKeyDown('1'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"attack02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tpAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);\n\t\t\tm_pRole->StopMove();\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('2'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill01\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('3'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCRoleBase* pTarget = NULL;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 15.0f)\n\t\t\t\t{\n\t\t\t\t\tpTarget = m_vAIList[i];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (pTarget)\n\t\t\t{\n\t\t\t\tCVector vTarget;\n\t\t\t\tvTarget.Append(pTarget->GetRoleID());\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t\tm_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('4'))\/\/෢ӵ\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector vTarget;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t{\n\t\t\t\t\tvTarget.Append(m_vAIList[i]->GetRoleID());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!vTarget.Empty())\n\t\t\t{\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('5'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill03\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector vPos;\n\t\t\tpAction->SetupSkillTargetPoint(vPos);\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('6'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill06\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector vPos;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t\tvPos.Append(m_vAIList[i]->GetPosition());\n\n\t\t\t}\n\t\t\tpAction->SetupSkillTargetPoint(vPos);\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('7'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill05\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector vTarget;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t\tvTarget.Append(m_vAIList[i]->GetRoleID());\n\t\t\t}\n\t\t\tif (!vTarget.Empty())\n\t\t\t{\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('8'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill07\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector vPos;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t\tvPos.Append(m_vAIList[i]->GetPosition());\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n\n\nSigned-off-by: mrlitong #include \"GameProcess.h\"\n#include \"Object.h\"\n#include \"Engine.h\"\n#include \"World.h\"\n#include \"App.h\"\n#include \"ToolsCamera.h\"\n#include \"ControlsApp.h\"\n#include \"MathLib.h\"\n#include \"Game.h\"\n#include \"Editor.h\"\n#include \"Input.h\"\n#include \"BlueRayUtils.h\"\n#include \"World.h\"\n#include \"Action.h\"\n#include \"FPSRoleLocal.h\"\n\nusing namespace MathLib;\n\nCGameProcess::CGameProcess(void)\n{\n\n}\n\nCGameProcess::~CGameProcess(void)\n{\n\n}\nint CGameProcess::Init()\n{\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"char\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"node\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"smesh\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"sanim\");\n\n\tg_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/test\/test.world\");\n\t\/\/g_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/cj\/cj.world\"); \n\tg_Engine.pControls->SetKeyPressFunc(KeyPress);\n\tg_Engine.pControls->SetKeyReleaseFunc(KeyRelease);\n\n\tm_pRole = new CFPSRoleLocal();\n\tm_pRole->Init(10001, \"data\/role\/hero\/FpsRole\/fps.char\");\t\t\/\/ؽɫԴ\n\n\tm_pRole->SetActorPosition(vec3(0, 0, 0));\t\/\/ýɫʼλáŴΪԭ㣬άϵvec3\n\tm_pSkillSystem = new CSkillSystem(this);\n\tm_pCameraBase = new CCameraBase();\n\tm_pCameraBase->SetEnabled(1);\n\tg_pSysControl->SetMouseGrab(1);\n\n\tm_pStarControl = new CStarControl();\n\tm_pRayControl = new CRayControl();\n\n\treturn 1;\n}\n\nint CGameProcess::ShutDown()\t\t\t\/\/رϷ\n{\n\tdelete m_pRole;\n\tdelete m_pSkillSystem;\n\tdelete m_pCameraBase;\n\tdelete m_pStarControl;\n\tdelete m_pRayControl;\n\n\tDelAllListen();\n\treturn 0;\n}\n\nint CGameProcess::Update()\n{\n\tfloat ifps = g_Engine.pGame->GetIFps();\n\n\tif (g_Engine.pInput->IsKeyDown('1'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"attack02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tpAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);\n\t\t\tm_pRole->StopMove();\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('2'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill01\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('3'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCRoleBase* pTarget = NULL;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 15.0f)\n\t\t\t\t{\n\t\t\t\t\tpTarget = m_vAIList[i];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (pTarget)\n\t\t\t{\n\t\t\t\tCVector vTarget;\n\t\t\t\tvTarget.Append(pTarget->GetRoleID());\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t\tm_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('4'))\/\/෢ӵ\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector vTarget;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t{\n\t\t\t\t\tvTarget.Append(m_vAIList[i]->GetRoleID());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!vTarget.Empty())\n\t\t\t{\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('5'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill03\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector vPos;\n\t\t\tpAction->SetupSkillTargetPoint(vPos);\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('6'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill06\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector vPos;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t\tvPos.Append(m_vAIList[i]->GetPosition());\n\n\t\t\t}\n\t\t\tpAction->SetupSkillTargetPoint(vPos);\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('7'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill05\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector vTarget;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t\tvTarget.Append(m_vAIList[i]->GetRoleID());\n\t\t\t}\n\t\t\tif (!vTarget.Empty())\n\t\t\t{\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('8'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill07\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector vPos;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t\tvPos.Append(m_vAIList[i]->GetPosition());\n\t\t\t}\n\t\t\tpAction->SetupSkillBulletPosition(vPos);\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('9'))\n\t{\n\n\t}\n\treturn 0;\n}\n\n\n<|endoftext|>"} {"text":"#include \"ReposLog.hpp\"\n\n#include \"LogCache.hpp\"\n#include \"src\/svnqt\/info_entry.hpp\"\n#include \"src\/svnqt\/svnqttypes.hpp\"\n#include \"src\/svnqt\/client.hpp\"\n#include \"src\/svnqt\/context_listener.hpp\"\n#include \"src\/svnqt\/cache\/DatabaseException.hpp\"\n\n#include \n#include \n\n\/*!\n \\fn svn::cache::ReposLog::ReposLog(svn::Client*aClient,const QString&)\n *\/\nsvn::cache::ReposLog::ReposLog(svn::Client*aClient,const QString&aRepository)\n :m_Client(aClient),m_Database(0),m_ReposRoot(aRepository),m_latestHead(svn::Revision::UNDEFINED)\n{\n if (!aRepository.isEmpty()) {\n m_Database = LogCache::self()->reposDb(aRepository);\n }\n}\n\n\n\/*!\n \\fn svn::cache::ReposLog::latestHeadRev()\n *\/\nsvn::Revision svn::cache::ReposLog::latestHeadRev()\n{\n if (!m_Client||m_ReposRoot.isEmpty()) {\n return svn::Revision::UNDEFINED;\n }\n if (!m_Database) {\n m_Database = LogCache::self()->reposDb(m_ReposRoot);\n if (!m_Database) {\n return svn::Revision::UNDEFINED;\n }\n }\n \/\/\/ no catch - exception has go trough...\n svn::InfoEntries e = (m_Client->info(m_ReposRoot,false,svn::Revision::HEAD,svn::Revision::HEAD));;\n if (e.count()<1||e[0].reposRoot().isEmpty()) {\n return svn::Revision::UNDEFINED;\n }\n return e[0].revision();\n}\n\n\n\/*!\n \\fn svn::cache::ReposLog::latestCachedRev()\n *\/\nsvn::Revision svn::cache::ReposLog::latestCachedRev()\n{\n if (m_ReposRoot.isEmpty()) {\n return svn::Revision::UNDEFINED;\n }\n if (!m_Database) {\n m_Database = LogCache::self()->reposDb(m_ReposRoot);\n if (!m_Database) {\n return svn::Revision::UNDEFINED;\n }\n }\n QString q(\"select revision from 'logentries' order by revision DESC limit 1\");\n QSqlQuery _q(QString::null, m_Database);\n if (!_q.exec(q)) {\n qDebug(_q.lastError().text());\n return svn::Revision::UNDEFINED;\n }\n int _r;\n if (_q.isActive() && _q.next()) {\n\n qDebug(\"Sel result: \"+_q.value(0).toString());\n _r = _q.value(0).toInt();\n } else {\n qDebug(_q.lastError().text());\n return svn::Revision::UNDEFINED;\n }\n return _r;\n}\n\nbool svn::cache::ReposLog::checkFill(svn::Revision&start,svn::Revision&end)\n{\n if (!m_Database) {\n m_Database = LogCache::self()->reposDb(m_ReposRoot);\n if (!m_Database) {\n return false;\n }\n }\n ContextP cp = m_Client->getContext();\n long long icount=0;\n\n svn::Revision _latest=latestCachedRev();\n qDebug(\"Latest cached rev: %i\",_latest.revnum());\n\n start=date2numberRev(start);\n end=date2numberRev(end);\n\n \/\/ both should now one of START, HEAD or NUMBER\n if (start==svn::Revision::HEAD || (end==svn::Revision::NUMBER && start==svn::Revision::NUMBER && start.revnum()>end.revnum())) {\n svn::Revision tmp = start;\n start = end;\n end = tmp;\n }\n qDebug(\"End: \"+end.toString());\n svn::Revision _rstart=_latest.revnum()+1;\n svn::Revision _rend = end;\n if (_rend==svn::Revision::UNDEFINED) {\n _rend=svn::Revision::HEAD;\n }\n \/\/ no catch - exception should go outside.\n if (_rstart==0){\n _rstart = 1;\n }\n qDebug(\"Getting log %s -> %s\",_rstart.toString().latin1(),_rend.toString().latin1());\n if (_rend==svn::Revision::HEAD) {\n _rend=latestHeadRev();\n }\n QSqlCursor cur(\"changeditems\",true,m_Database);\n QSqlCursor bcur(\"logentries\",true,m_Database);\n\n if (_rend==svn::Revision::HEAD||_rend.revnum()>_latest.revnum()) {\n LogEntriesMap _internal;\n qDebug(\"Retrieving from network.\");\n if (!m_Client->log(m_ReposRoot,_rstart,_rend,_internal,svn::Revision::UNDEFINED,true,false)) {\n return false;\n }\n LogEntriesMap::ConstIterator it=_internal.begin();\n\n for (;it!=_internal.end();++it) {\n insertLogEntry((*it),bcur,cur);\n if (cp && cp->getListener()) {\n \/\/cp->getListener()->contextProgress(++icount,_internal.size());\n if (cp->getListener()->contextCancel()) {\n throw svn::ClientException(QString(\"Could not retrieve values: User cancel.\"));\n }\n }\n }\n }\n return true;\n}\n\nbool svn::cache::ReposLog::fillCache(const svn::Revision&_end)\n{\n svn::Revision end = _end;\n svn::Revision start = latestCachedRev().revnum()+1;\n return checkFill(start,end);\n}\n\n\/*!\n \\fn svn::cache::ReposLog::simpleLog(const svn::Revision&start,const svn::Revision&end,LogEntriesMap&target)\n *\/\nbool svn::cache::ReposLog::simpleLog(LogEntriesMap&target,const svn::Revision&_start,const svn::Revision&_end)\n{\n if (!m_Client||m_ReposRoot.isEmpty()) {\n return false;\n }\n target.clear();\n ContextP cp = m_Client->getContext();\n\n svn::Revision end = _end;\n svn::Revision start = _start;\n if (!checkFill(start,end)) {\n return false;\n }\n\n QSqlCursor cur(\"changeditems\",true,m_Database);\n QSqlCursor bcur(\"logentries\",true,m_Database);\n\n qDebug(\"End: \"+end.toString());\n if (end==svn::Revision::HEAD) {\n end = latestCachedRev();\n }\n if (start==svn::Revision::HEAD) {\n start=latestCachedRev();\n }\n\n QString lim = QString(\"revision<=%1 and revision>=%2\").arg(end.revnum()).arg(start.revnum());\n qDebug(lim);\n if (!bcur.select(lim)) {\n qDebug(bcur.lastError().text());\n throw svn::ClientException(QString(\"Could not retrieve values: \")+bcur.lastError().text());\n return false;\n }\n while(bcur.next()) {\n Q_LLONG revision= bcur.value(\"revision\").toLongLong();\n lim=QString(\"revision=%1\").arg(revision);\n if (!cur.select(lim)) {\n qDebug(cur.lastError().text());\n throw svn::ClientException(QString(\"Could not retrieve values: \")+cur.lastError().text());\n return false;\n }\n target[revision].revision=revision;\n target[revision].author=bcur.value(\"author\").toString();\n target[revision].date=bcur.value(\"date\").toLongLong();\n target[revision].message=bcur.value(\"message\").toString();\n while(cur.next()) {\n char c = cur.value(\"action\").toInt();\n LogChangePathEntry lcp;\n lcp.action=cur.value(\"action\").toString()[0];\n lcp.copyFromPath=cur.value(\"copyfrom\").toString().latin1();\n lcp.path= cur.value(\"changeditem\").toString();\n lcp.copyFromRevision=cur.value(\"copyfromrev\").toLongLong();\n target[revision].changedPaths.push_back(lcp);\n }\n if (cp && cp->getListener()) {\n \/\/cp->getListener()->contextProgress(++icount,bcur.size());\n if (cp->getListener()->contextCancel()) {\n throw svn::ClientException(QString(\"Could not retrieve values: User cancel.\"));\n }\n }\n }\n return false;\n}\n\n\n\/*!\n \\fn svn::cache::ReposLog::date2numberRev(const svn::Revision&)\n *\/\nsvn::Revision svn::cache::ReposLog::date2numberRev(const svn::Revision&aRev)\n{\n if (aRev!=svn::Revision::DATE) {\n return aRev;\n }\n if (!m_Database) {\n return svn::Revision::UNDEFINED;\n }\n QSqlCursor bcur(\"logentries\",true,m_Database);\n QSqlIndex order = bcur.index(\"revision\");\n order.setDescending(0,true);\n \/\/\/ @todo as I understood - the resulting revision should always the last one BEFORE this date...\n \/\/QString q=QString(\"date>='%1'\").arg(value);\n \/\/qDebug(q);\n bcur.select(order);\n if (bcur.lastError().type()!=QSqlError::None) {\n qDebug(bcur.lastError().text());\n }\n bool must_remote=true;\n if (bcur.next()) {\n if (bcur.value(\"date\").toLongLong()>=aRev.date()) {\n must_remote=false;\n }\n }\n if (must_remote) {\n svn::InfoEntries e = (m_Client->info(m_ReposRoot,false,aRev,aRev));;\n if (e.count()<1||e[0].reposRoot().isEmpty()) {\n return aRev;\n }\n return e[0].revision();\n }\n QString q=QString(\"date<'%1'\").arg(aRev.date());\n bcur.select(q,order);\n qDebug(\"Search for date: \" +q);\n if (bcur.lastError().type()!=QSqlError::None) {\n qDebug(bcur.lastError().text());\n }\n if (bcur.next()) {\n return bcur.value( \"revision\" ).toInt();\n }\n \/\/ not found...\n svn::InfoEntries e = (m_Client->info(m_ReposRoot,false,svn::Revision::HEAD,svn::Revision::HEAD));;\n if (e.count()<1||e[0].reposRoot().isEmpty()) {\n return aRev;\n }\n return e[0].revision();\n}\n\n\n\/*!\n \\fn svn::cache::ReposLog::insertLogEntry(const svn::LogEntry&)\n *\/\nbool svn::cache::ReposLog::insertLogEntry(const svn::LogEntry&aEntry,QSqlCursor&lCur,QSqlCursor&cCur)\n{\n QSqlRecord *buffer;\n m_Database->transaction();\n\n#if QT_VERSION < 0x040000\n Q_LLONG j = aEntry.revision;\n#else\n qlonglong j = aEntry.revision;\n#endif\n buffer=lCur.primeInsert();\n buffer->setValue(\"revision\",j);\n buffer->setValue(\"date\",aEntry.date);\n buffer->setValue(\"author\",aEntry.author);\n buffer->setValue(\"message\",aEntry.message);\n lCur.insert();\n if (lCur.lastError().type()!=QSqlError::None) {\n m_Database->rollback();\n qDebug(QString(\"Could not insert values: \")+lCur.lastError().text());\n }\n svn::LogChangePathEntries::ConstIterator cpit = aEntry.changedPaths.begin();\n for (;cpit!=aEntry.changedPaths.end();++cpit){\n buffer = cCur.primeInsert();\n buffer->setValue(\"revision\",j);\n buffer->setValue(\"changeditem\",(*cpit).path);\n buffer->setValue(\"action\",QString(QChar((*cpit).action)));\n buffer->setValue(\"copyfrom\",(*cpit).copyFromPath);\n buffer->setValue(\"copyfromrev\",Q_LLONG((*cpit).copyFromRevision));\n cCur.insert();\n if (cCur.lastError().type()!=QSqlError::None) {\n m_Database->rollback();\n qDebug(QString(\"Could not insert values: \")+cCur.lastError().text());\n \/\/throw DatabaseException(QString(\"Could not insert values: \")+cCur.lastError().text());\n }\n }\n m_Database->commit();\n return true;\n}\n * catch svn::Exception not svn::ClientException * don't try retrieve logs for cache if last cached revision is same as head revision#include \"ReposLog.hpp\"\n\n#include \"LogCache.hpp\"\n#include \"src\/svnqt\/info_entry.hpp\"\n#include \"src\/svnqt\/svnqttypes.hpp\"\n#include \"src\/svnqt\/client.hpp\"\n#include \"src\/svnqt\/context_listener.hpp\"\n#include \"src\/svnqt\/cache\/DatabaseException.hpp\"\n\n#include \n#include \n\n\/*!\n \\fn svn::cache::ReposLog::ReposLog(svn::Client*aClient,const QString&)\n *\/\nsvn::cache::ReposLog::ReposLog(svn::Client*aClient,const QString&aRepository)\n :m_Client(aClient),m_Database(0),m_ReposRoot(aRepository),m_latestHead(svn::Revision::UNDEFINED)\n{\n if (!aRepository.isEmpty()) {\n m_Database = LogCache::self()->reposDb(aRepository);\n }\n}\n\n\n\/*!\n \\fn svn::cache::ReposLog::latestHeadRev()\n *\/\nsvn::Revision svn::cache::ReposLog::latestHeadRev()\n{\n if (!m_Client||m_ReposRoot.isEmpty()) {\n return svn::Revision::UNDEFINED;\n }\n if (!m_Database) {\n m_Database = LogCache::self()->reposDb(m_ReposRoot);\n if (!m_Database) {\n return svn::Revision::UNDEFINED;\n }\n }\n \/\/\/ no catch - exception has go trough...\n svn::InfoEntries e = (m_Client->info(m_ReposRoot,false,svn::Revision::HEAD,svn::Revision::HEAD));;\n if (e.count()<1||e[0].reposRoot().isEmpty()) {\n return svn::Revision::UNDEFINED;\n }\n return e[0].revision();\n}\n\n\n\/*!\n \\fn svn::cache::ReposLog::latestCachedRev()\n *\/\nsvn::Revision svn::cache::ReposLog::latestCachedRev()\n{\n if (m_ReposRoot.isEmpty()) {\n return svn::Revision::UNDEFINED;\n }\n if (!m_Database) {\n m_Database = LogCache::self()->reposDb(m_ReposRoot);\n if (!m_Database) {\n return svn::Revision::UNDEFINED;\n }\n }\n QString q(\"select revision from 'logentries' order by revision DESC limit 1\");\n QSqlQuery _q(QString::null, m_Database);\n if (!_q.exec(q)) {\n qDebug(_q.lastError().text());\n return svn::Revision::UNDEFINED;\n }\n int _r;\n if (_q.isActive() && _q.next()) {\n\n qDebug(\"Sel result: \"+_q.value(0).toString());\n _r = _q.value(0).toInt();\n } else {\n qDebug(_q.lastError().text());\n return svn::Revision::UNDEFINED;\n }\n return _r;\n}\n\nbool svn::cache::ReposLog::checkFill(svn::Revision&start,svn::Revision&end)\n{\n if (!m_Database) {\n m_Database = LogCache::self()->reposDb(m_ReposRoot);\n if (!m_Database) {\n return false;\n }\n }\n ContextP cp = m_Client->getContext();\n long long icount=0;\n\n svn::Revision _latest=latestCachedRev();\n qDebug(\"Latest cached rev: %i\",_latest.revnum());\n if (_latest.revnum()>=latestHeadRev().revnum()) {\n return true;\n }\n\n start=date2numberRev(start);\n end=date2numberRev(end);\n\n \/\/ both should now one of START, HEAD or NUMBER\n if (start==svn::Revision::HEAD || (end==svn::Revision::NUMBER && start==svn::Revision::NUMBER && start.revnum()>end.revnum())) {\n svn::Revision tmp = start;\n start = end;\n end = tmp;\n }\n qDebug(\"End: \"+end.toString());\n svn::Revision _rstart=_latest.revnum()+1;\n svn::Revision _rend = end;\n if (_rend==svn::Revision::UNDEFINED) {\n _rend=svn::Revision::HEAD;\n }\n \/\/ no catch - exception should go outside.\n if (_rstart==0){\n _rstart = 1;\n }\n qDebug(\"Getting log %s -> %s\",_rstart.toString().latin1(),_rend.toString().latin1());\n if (_rend==svn::Revision::HEAD) {\n _rend=latestHeadRev();\n }\n QSqlCursor cur(\"changeditems\",true,m_Database);\n QSqlCursor bcur(\"logentries\",true,m_Database);\n\n if (_rend==svn::Revision::HEAD||_rend.revnum()>_latest.revnum()) {\n LogEntriesMap _internal;\n qDebug(\"Retrieving from network.\");\n if (!m_Client->log(m_ReposRoot,_rstart,_rend,_internal,svn::Revision::UNDEFINED,true,false)) {\n return false;\n }\n LogEntriesMap::ConstIterator it=_internal.begin();\n\n for (;it!=_internal.end();++it) {\n insertLogEntry((*it),bcur,cur);\n if (cp && cp->getListener()) {\n \/\/cp->getListener()->contextProgress(++icount,_internal.size());\n if (cp->getListener()->contextCancel()) {\n throw DatabaseException(QString(\"Could not retrieve values: User cancel.\"));\n }\n }\n }\n }\n return true;\n}\n\nbool svn::cache::ReposLog::fillCache(const svn::Revision&_end)\n{\n svn::Revision end = _end;\n svn::Revision start = latestCachedRev().revnum()+1;\n return checkFill(start,end);\n}\n\n\/*!\n \\fn svn::cache::ReposLog::simpleLog(const svn::Revision&start,const svn::Revision&end,LogEntriesMap&target)\n *\/\nbool svn::cache::ReposLog::simpleLog(LogEntriesMap&target,const svn::Revision&_start,const svn::Revision&_end)\n{\n if (!m_Client||m_ReposRoot.isEmpty()) {\n return false;\n }\n target.clear();\n ContextP cp = m_Client->getContext();\n\n svn::Revision end = _end;\n svn::Revision start = _start;\n if (!checkFill(start,end)) {\n return false;\n }\n\n QSqlCursor cur(\"changeditems\",true,m_Database);\n QSqlCursor bcur(\"logentries\",true,m_Database);\n\n qDebug(\"End: \"+end.toString());\n if (end==svn::Revision::HEAD) {\n end = latestCachedRev();\n }\n if (start==svn::Revision::HEAD) {\n start=latestCachedRev();\n }\n\n QString lim = QString(\"revision<=%1 and revision>=%2\").arg(end.revnum()).arg(start.revnum());\n qDebug(lim);\n if (!bcur.select(lim)) {\n qDebug(bcur.lastError().text());\n throw svn::ClientException(QString(\"Could not retrieve values: \")+bcur.lastError().text());\n return false;\n }\n while(bcur.next()) {\n Q_LLONG revision= bcur.value(\"revision\").toLongLong();\n lim=QString(\"revision=%1\").arg(revision);\n if (!cur.select(lim)) {\n qDebug(cur.lastError().text());\n throw svn::ClientException(QString(\"Could not retrieve values: \")+cur.lastError().text());\n return false;\n }\n target[revision].revision=revision;\n target[revision].author=bcur.value(\"author\").toString();\n target[revision].date=bcur.value(\"date\").toLongLong();\n target[revision].message=bcur.value(\"message\").toString();\n while(cur.next()) {\n char c = cur.value(\"action\").toInt();\n LogChangePathEntry lcp;\n lcp.action=cur.value(\"action\").toString()[0];\n lcp.copyFromPath=cur.value(\"copyfrom\").toString().latin1();\n lcp.path= cur.value(\"changeditem\").toString();\n lcp.copyFromRevision=cur.value(\"copyfromrev\").toLongLong();\n target[revision].changedPaths.push_back(lcp);\n }\n if (cp && cp->getListener()) {\n \/\/cp->getListener()->contextProgress(++icount,bcur.size());\n if (cp->getListener()->contextCancel()) {\n throw svn::ClientException(QString(\"Could not retrieve values: User cancel.\"));\n }\n }\n }\n return false;\n}\n\n\n\/*!\n \\fn svn::cache::ReposLog::date2numberRev(const svn::Revision&)\n *\/\nsvn::Revision svn::cache::ReposLog::date2numberRev(const svn::Revision&aRev)\n{\n if (aRev!=svn::Revision::DATE) {\n return aRev;\n }\n if (!m_Database) {\n return svn::Revision::UNDEFINED;\n }\n QSqlCursor bcur(\"logentries\",true,m_Database);\n QSqlIndex order = bcur.index(\"revision\");\n order.setDescending(0,true);\n \/\/\/ @todo as I understood - the resulting revision should always the last one BEFORE this date...\n \/\/QString q=QString(\"date>='%1'\").arg(value);\n \/\/qDebug(q);\n bcur.select(order);\n if (bcur.lastError().type()!=QSqlError::None) {\n qDebug(bcur.lastError().text());\n }\n bool must_remote=true;\n if (bcur.next()) {\n if (bcur.value(\"date\").toLongLong()>=aRev.date()) {\n must_remote=false;\n }\n }\n if (must_remote) {\n svn::InfoEntries e = (m_Client->info(m_ReposRoot,false,aRev,aRev));;\n if (e.count()<1||e[0].reposRoot().isEmpty()) {\n return aRev;\n }\n return e[0].revision();\n }\n QString q=QString(\"date<'%1'\").arg(aRev.date());\n bcur.select(q,order);\n qDebug(\"Search for date: \" +q);\n if (bcur.lastError().type()!=QSqlError::None) {\n qDebug(bcur.lastError().text());\n }\n if (bcur.next()) {\n return bcur.value( \"revision\" ).toInt();\n }\n \/\/ not found...\n svn::InfoEntries e = (m_Client->info(m_ReposRoot,false,svn::Revision::HEAD,svn::Revision::HEAD));;\n if (e.count()<1||e[0].reposRoot().isEmpty()) {\n return aRev;\n }\n return e[0].revision();\n}\n\n\n\/*!\n \\fn svn::cache::ReposLog::insertLogEntry(const svn::LogEntry&)\n *\/\nbool svn::cache::ReposLog::insertLogEntry(const svn::LogEntry&aEntry,QSqlCursor&lCur,QSqlCursor&cCur)\n{\n QSqlRecord *buffer;\n m_Database->transaction();\n\n#if QT_VERSION < 0x040000\n Q_LLONG j = aEntry.revision;\n#else\n qlonglong j = aEntry.revision;\n#endif\n buffer=lCur.primeInsert();\n buffer->setValue(\"revision\",j);\n buffer->setValue(\"date\",aEntry.date);\n buffer->setValue(\"author\",aEntry.author);\n buffer->setValue(\"message\",aEntry.message);\n lCur.insert();\n if (lCur.lastError().type()!=QSqlError::None) {\n m_Database->rollback();\n qDebug(QString(\"Could not insert values: \")+lCur.lastError().text());\n }\n svn::LogChangePathEntries::ConstIterator cpit = aEntry.changedPaths.begin();\n for (;cpit!=aEntry.changedPaths.end();++cpit){\n buffer = cCur.primeInsert();\n buffer->setValue(\"revision\",j);\n buffer->setValue(\"changeditem\",(*cpit).path);\n buffer->setValue(\"action\",QString(QChar((*cpit).action)));\n buffer->setValue(\"copyfrom\",(*cpit).copyFromPath);\n buffer->setValue(\"copyfromrev\",Q_LLONG((*cpit).copyFromRevision));\n cCur.insert();\n if (cCur.lastError().type()!=QSqlError::None) {\n m_Database->rollback();\n qDebug(QString(\"Could not insert values: \")+cCur.lastError().text());\n throw DatabaseException(QString(\"Could not insert values: \")+cCur.lastError().text());\n }\n }\n m_Database->commit();\n return true;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nDEFINE_int32(\n c,\n 4,\n \"threshold under which candidates are output. set to -1 to output all.\");\nDEFINE_bool(i, false, \"add inverted tags\");\nDEFINE_int32(m, 0, \"min number of set\/cleared samples each\");\nDEFINE_int32(M, 0, \"min number of set\/cleared samples total\");\nDEFINE_string(o, \"\", \"set output file\");\nDEFINE_string(k, \"\", \"set output mask file\");\n\nusing std::map;\nusing std::string;\nusing std::tuple;\nusing std::vector;\n\nint num_bits = 0, num_tags = 0;\nmap bit_ids, tag_ids;\nvector bit_ids_r, tag_ids_r;\n\n#if 0\nstruct bool_vec\n{\n\tvector data;\n\n\tbool_vec(int n = 0, bool initval = false) : data(n, initval)\n\t{\n\t}\n\n\tvoid set(int n)\n\t{\n\t\tif (int(data.size()) <= n)\n\t\t\tdata.resize(n+1);\n\t\tdata[n] = true;\n\t}\n\n\tbool get(int n)\n\t{\n\t\treturn data.at(n);\n\t}\n\n\tvoid resize(int n)\n\t{\n\t\tdata.resize(n);\n\t}\n\n\tint count()\n\t{\n\t\treturn std::accumulate(data.begin(), data.end(), 0);\n\t}\n\n\tvoid apply_and(const bool_vec &other)\n\t{\n\t\tassert(data.size() == other.data.size());\n\t\tfor (int i = 0; i < int(data.size()); i++)\n\t\t\tdata[i] = data[i] && other.data[i];\n\t}\n\n\tvoid apply_andc(const bool_vec &other)\n\t{\n\t\tassert(data.size() == other.data.size());\n\t\tfor (int i = 0; i < int(data.size()); i++)\n\t\t\tdata[i] = data[i] && !other.data[i];\n\t}\n};\n#else\nstruct bool_vec {\n\tvector data;\n\n\tbool_vec(int n = 0, bool initval = false)\n\t : data((n + 63) \/ 64, initval ? ~uint64_t(0) : uint64_t(0)) {\n\t\tfor (int i = data.size() * 64 - 1; i >= n; i--)\n\t\t\tdata[n \/ 64] &= ~(uint64_t(1) << (n % 64));\n\t}\n\n\tvoid set(int n) {\n\t\tif (int(data.size() * 64) <= n)\n\t\t\tdata.resize((n + 64) \/ 64);\n\t\tdata[n \/ 64] |= uint64_t(1) << (n % 64);\n\t}\n\n\tbool get(int n) { return (data[n \/ 64] >> (n % 64)) & 1; }\n\n\tvoid resize(int n) { data.resize((n + 63) \/ 64); }\n\n\tint count() {\n\t\tint sum = 0;\n\t\tfor (int i = 0; i < 64 * int(data.size()); i++)\n\t\t\tif (get(i))\n\t\t\t\tsum++;\n\t\treturn sum;\n\t}\n\n\tvoid apply_and(const bool_vec& other) {\n\t\tassert(data.size() == other.data.size());\n\t\tfor (int i = 0; i < int(data.size()); i++)\n\t\t\tdata[i] &= other.data[i];\n\t}\n\n\tvoid apply_andc(const bool_vec& other) {\n\t\tassert(data.size() == other.data.size());\n\t\tfor (int i = 0; i < int(data.size()); i++)\n\t\t\tdata[i] &= ~other.data[i];\n\t}\n};\n#endif\n\n\/\/ segname -> bits, tags_on, tags_off\ntypedef tuple segdata_t;\nmap segdata;\n\nmap segnamecnt;\n\nstatic inline bool_vec& segdata_bits(segdata_t& sd) {\n\treturn std::get<0>(sd);\n}\nstatic inline bool_vec& segdata_tags1(segdata_t& sd) {\n\treturn std::get<1>(sd);\n}\nstatic inline bool_vec& segdata_tags0(segdata_t& sd) {\n\treturn std::get<2>(sd);\n}\n\nvoid read_input(std::istream& f, std::string filename) {\n\tstring token;\n\tsegdata_t* segptr = nullptr;\n\n\twhile (f >> token) {\n\t\tif (token == \"seg\") {\n\t\t\tf >> token;\n\t\t\ttoken = filename + \":\" + token;\n\t\t\twhile (segdata.count(token)) {\n\t\t\t\tint idx = 1;\n\t\t\t\tif (segnamecnt.count(token))\n\t\t\t\t\tidx = segnamecnt.at(token);\n\t\t\t\tsegnamecnt[token] = idx + 1;\n\t\t\t\tchar buffer[64];\n\t\t\t\tsnprintf(buffer, 64, \"-%d\", idx);\n\t\t\t\ttoken += buffer;\n\t\t\t}\n\t\t\tsegptr = &segdata[token];\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (token == \"bit\") {\n\t\t\tassert(segptr != nullptr);\n\n\t\t\tf >> token;\n\t\t\tif (bit_ids.count(token) == 0) {\n\t\t\t\tbit_ids[token] = num_bits++;\n\t\t\t\tbit_ids_r.push_back(token);\n\t\t\t}\n\n\t\t\tint bit_idx = bit_ids.at(token);\n\t\t\tauto& bits = segdata_bits(*segptr);\n\n\t\t\tbits.set(bit_idx);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (token == \"tag\") {\n\t\t\tassert(segptr != nullptr);\n\n\t\t\tf >> token;\n\t\t\tif (tag_ids.count(token) == 0) {\n\t\t\t\ttag_ids[token] = num_tags++;\n\t\t\t\ttag_ids_r.push_back(token);\n\t\t\t}\n\n\t\t\tint tag_idx = tag_ids.at(token);\n\n\t\t\tf >> token;\n\t\t\tassert(token == \"0\" || token == \"1\");\n\n\t\t\tauto& tags = token == \"1\" ? segdata_tags1(*segptr)\n\t\t\t : segdata_tags0(*segptr);\n\n\t\t\ttags.set(tag_idx);\n\n\t\t\tif (FLAGS_i) {\n\t\t\t\tauto& inv_tags = token == \"1\"\n\t\t\t\t ? segdata_tags0(*segptr)\n\t\t\t\t : segdata_tags1(*segptr);\n\n\t\t\t\ttoken = tag_ids_r.at(tag_idx) + \"__INV\";\n\n\t\t\t\tif (tag_ids.count(token) == 0) {\n\t\t\t\t\ttag_ids[token] = num_tags++;\n\t\t\t\t\ttag_ids_r.push_back(token);\n\t\t\t\t}\n\n\t\t\t\tint inv_tag_idx = tag_ids.at(token);\n\t\t\t\tinv_tags.set(inv_tag_idx);\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tabort();\n\t}\n\n\t\/\/ printf(\"Number of segments: %d\\n\", int(segdata.size()));\n\t\/\/ printf(\"Number of bits: %d\\n\", num_bits);\n\t\/\/ printf(\"Number of tags: %d\\n\", num_tags);\n\n\tfor (auto& segdat : segdata) {\n\t\tsegdata_bits(segdat.second).resize(num_bits);\n\t\tsegdata_tags1(segdat.second).resize(num_tags);\n\t\tsegdata_tags0(segdat.second).resize(num_tags);\n\t}\n}\n\nint main(int argc, char** argv) {\n\tgflags::SetUsageMessage(\n\t absl::StrCat(\"Usage: \", argv[0], \" [options] file..\"));\n\tgflags::ParseCommandLineFlags(&argc, &argv, true);\n\n\tif (argc > 1) {\n\t\tfor (int optind = 1; optind < argc; optind++) {\n\t\t\tprintf(\"Reading %s.\\n\", argv[optind]);\n\t\t\tstd::ifstream f;\n\t\t\tf.open(argv[optind]);\n\t\t\tassert(!f.fail());\n\t\t\tread_input(f, argv[optind]);\n\t\t}\n\t} else {\n\t\tprintf(\"Reading from stding.\\n\");\n\t\tread_input(std::cin, \"stdin\");\n\t}\n\n\tprintf(\"#of segments: %d\\n\", int(segdata.size()));\n\tprintf(\"#of bits: %d\\n\", num_bits);\n\tprintf(\"#of tags: %d\\n\", num_tags);\n\n\tFILE* f = stdout;\n\n\tif (!FLAGS_o.empty()) {\n\t\tf = fopen(FLAGS_o.c_str(), \"w\");\n\t\tassert(f != nullptr);\n\t}\n\n\tint cnt_const0 = 0;\n\tint cnt_const1 = 0;\n\tint cnt_candidates = 0;\n\tint min_candidates = num_bits;\n\tint max_candidates = 0;\n\tfloat avg_candidates = 0;\n\n\tstd::vector out_lines;\n\n\tfor (int tag_idx = 0; tag_idx < num_tags; tag_idx++) {\n\t\tbool_vec mask(num_bits, true);\n\t\tint count1 = 0, count0 = 0;\n\n\t\tfor (auto& segdat : segdata) {\n\t\t\tauto& sd = segdat.second;\n\t\t\tbool tag1 = segdata_tags1(sd).get(tag_idx);\n\t\t\tbool tag0 = segdata_tags0(sd).get(tag_idx);\n\n\t\t\tassert(!tag1 || !tag0);\n\n\t\t\tif (tag1) {\n\t\t\t\tcount1++;\n\t\t\t\tmask.apply_and(segdata_bits(sd));\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (tag0) {\n\t\t\t\tcount0++;\n\t\t\t\tmask.apply_andc(segdata_bits(sd));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tassert(count1 || count0);\n\n\t\tstd::string out_line = tag_ids_r.at(tag_idx);\n\n\t\tif (count1 < FLAGS_m) {\n\t\t\tchar buffer[64];\n\t\t\tsnprintf(buffer, 64, \" \", count1);\n\t\t\tout_line += buffer;\n\t\t}\n\n\t\tif (count0 < FLAGS_m) {\n\t\t\tchar buffer[64];\n\t\t\tsnprintf(buffer, 64, \" \", count0);\n\t\t\tout_line += buffer;\n\t\t}\n\n\t\tif (count1 + count0 < FLAGS_M) {\n\t\t\tchar buffer[64];\n\t\t\tsnprintf(buffer, 64, \" \", count1, count0);\n\t\t\tout_line += buffer;\n\t\t}\n\n\t\tif (!count1) {\n\t\t\tout_lines.push_back(out_line + \" \");\n\t\t\tcnt_const0 += 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!count0) {\n\t\t\tout_line += \" \";\n\t\t\tcnt_const1 += 1;\n\t\t}\n\n\t\tint num_candidates = mask.count();\n\n\t\tif (count0) {\n\t\t\tmin_candidates =\n\t\t\t std::min(min_candidates, num_candidates);\n\t\t\tmax_candidates =\n\t\t\t std::max(max_candidates, num_candidates);\n\t\t\tavg_candidates += num_candidates;\n\t\t\tcnt_candidates += 1;\n\t\t}\n\n\t\tif (FLAGS_c < 0 ||\n\t\t (0 < num_candidates && num_candidates <= FLAGS_c)) {\n\t\t\tstd::vector out_tags;\n\t\t\tfor (int bit_idx = 0; bit_idx < num_bits; bit_idx++)\n\t\t\t\tif (mask.get(bit_idx))\n\t\t\t\t\tout_tags.push_back(\n\t\t\t\t\t bit_ids_r.at(bit_idx));\n\t\t\tstd::sort(out_tags.begin(), out_tags.end());\n\t\t\tfor (auto& tag : out_tags)\n\t\t\t\tout_line += \" \" + tag;\n\t\t} else {\n\t\t\tchar buffer[64];\n\t\t\tsnprintf(buffer, 64, \" <%d candidates>\",\n\t\t\t num_candidates);\n\t\t\tout_line += buffer;\n\t\t}\n\n\t\tout_lines.push_back(out_line);\n\t}\n\n\tstd::sort(out_lines.begin(), out_lines.end());\n\n\tfor (auto& line : out_lines)\n\t\tfprintf(f, \"%s\\n\", line.c_str());\n\n\tif (cnt_candidates)\n\t\tavg_candidates \/= cnt_candidates;\n\n\tprintf(\"#of const0 tags: %d\\n\", cnt_const0);\n\tprintf(\"#of const1 tags: %d\\n\", cnt_const1);\n\n\tif (cnt_candidates) {\n\t\tprintf(\"min #of candidates: %d\\n\", min_candidates);\n\t\tprintf(\"max #of candidates: %d\\n\", max_candidates);\n\t\tprintf(\"avg #of candidates: %.3f\\n\", avg_candidates);\n\t}\n\n\tif (!FLAGS_k.empty()) {\n\t\tf = fopen(FLAGS_k.c_str(), \"w\");\n\t\tassert(f != nullptr);\n\t\tstd::sort(bit_ids_r.begin(), bit_ids_r.end());\n\t\tfor (auto bit : bit_ids_r)\n\t\t\tfprintf(f, \"bit %s\\n\", bit.c_str());\n\t}\n\n\treturn 0;\n}\nsegmatch: added warning for missing files#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nDEFINE_int32(\n c,\n 4,\n \"threshold under which candidates are output. set to -1 to output all.\");\nDEFINE_bool(i, false, \"add inverted tags\");\nDEFINE_int32(m, 0, \"min number of set\/cleared samples each\");\nDEFINE_int32(M, 0, \"min number of set\/cleared samples total\");\nDEFINE_string(o, \"\", \"set output file\");\nDEFINE_string(k, \"\", \"set output mask file\");\n\nusing std::map;\nusing std::string;\nusing std::tuple;\nusing std::vector;\n\nint num_bits = 0, num_tags = 0;\nmap bit_ids, tag_ids;\nvector bit_ids_r, tag_ids_r;\n\n#if 0\nstruct bool_vec\n{\n\tvector data;\n\n\tbool_vec(int n = 0, bool initval = false) : data(n, initval)\n\t{\n\t}\n\n\tvoid set(int n)\n\t{\n\t\tif (int(data.size()) <= n)\n\t\t\tdata.resize(n+1);\n\t\tdata[n] = true;\n\t}\n\n\tbool get(int n)\n\t{\n\t\treturn data.at(n);\n\t}\n\n\tvoid resize(int n)\n\t{\n\t\tdata.resize(n);\n\t}\n\n\tint count()\n\t{\n\t\treturn std::accumulate(data.begin(), data.end(), 0);\n\t}\n\n\tvoid apply_and(const bool_vec &other)\n\t{\n\t\tassert(data.size() == other.data.size());\n\t\tfor (int i = 0; i < int(data.size()); i++)\n\t\t\tdata[i] = data[i] && other.data[i];\n\t}\n\n\tvoid apply_andc(const bool_vec &other)\n\t{\n\t\tassert(data.size() == other.data.size());\n\t\tfor (int i = 0; i < int(data.size()); i++)\n\t\t\tdata[i] = data[i] && !other.data[i];\n\t}\n};\n#else\nstruct bool_vec {\n\tvector data;\n\n\tbool_vec(int n = 0, bool initval = false)\n\t : data((n + 63) \/ 64, initval ? ~uint64_t(0) : uint64_t(0)) {\n\t\tfor (int i = data.size() * 64 - 1; i >= n; i--)\n\t\t\tdata[n \/ 64] &= ~(uint64_t(1) << (n % 64));\n\t}\n\n\tvoid set(int n) {\n\t\tif (int(data.size() * 64) <= n)\n\t\t\tdata.resize((n + 64) \/ 64);\n\t\tdata[n \/ 64] |= uint64_t(1) << (n % 64);\n\t}\n\n\tbool get(int n) { return (data[n \/ 64] >> (n % 64)) & 1; }\n\n\tvoid resize(int n) { data.resize((n + 63) \/ 64); }\n\n\tint count() {\n\t\tint sum = 0;\n\t\tfor (int i = 0; i < 64 * int(data.size()); i++)\n\t\t\tif (get(i))\n\t\t\t\tsum++;\n\t\treturn sum;\n\t}\n\n\tvoid apply_and(const bool_vec& other) {\n\t\tassert(data.size() == other.data.size());\n\t\tfor (int i = 0; i < int(data.size()); i++)\n\t\t\tdata[i] &= other.data[i];\n\t}\n\n\tvoid apply_andc(const bool_vec& other) {\n\t\tassert(data.size() == other.data.size());\n\t\tfor (int i = 0; i < int(data.size()); i++)\n\t\t\tdata[i] &= ~other.data[i];\n\t}\n};\n#endif\n\n\/\/ segname -> bits, tags_on, tags_off\ntypedef tuple segdata_t;\nmap segdata;\n\nmap segnamecnt;\n\nstatic inline bool_vec& segdata_bits(segdata_t& sd) {\n\treturn std::get<0>(sd);\n}\nstatic inline bool_vec& segdata_tags1(segdata_t& sd) {\n\treturn std::get<1>(sd);\n}\nstatic inline bool_vec& segdata_tags0(segdata_t& sd) {\n\treturn std::get<2>(sd);\n}\n\nvoid read_input(std::istream& f, std::string filename) {\n\tstring token;\n\tsegdata_t* segptr = nullptr;\n\n\twhile (f >> token) {\n\t\tif (token == \"seg\") {\n\t\t\tf >> token;\n\t\t\ttoken = filename + \":\" + token;\n\t\t\twhile (segdata.count(token)) {\n\t\t\t\tint idx = 1;\n\t\t\t\tif (segnamecnt.count(token))\n\t\t\t\t\tidx = segnamecnt.at(token);\n\t\t\t\tsegnamecnt[token] = idx + 1;\n\t\t\t\tchar buffer[64];\n\t\t\t\tsnprintf(buffer, 64, \"-%d\", idx);\n\t\t\t\ttoken += buffer;\n\t\t\t}\n\t\t\tsegptr = &segdata[token];\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (token == \"bit\") {\n\t\t\tassert(segptr != nullptr);\n\n\t\t\tf >> token;\n\t\t\tif (bit_ids.count(token) == 0) {\n\t\t\t\tbit_ids[token] = num_bits++;\n\t\t\t\tbit_ids_r.push_back(token);\n\t\t\t}\n\n\t\t\tint bit_idx = bit_ids.at(token);\n\t\t\tauto& bits = segdata_bits(*segptr);\n\n\t\t\tbits.set(bit_idx);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (token == \"tag\") {\n\t\t\tassert(segptr != nullptr);\n\n\t\t\tf >> token;\n\t\t\tif (tag_ids.count(token) == 0) {\n\t\t\t\ttag_ids[token] = num_tags++;\n\t\t\t\ttag_ids_r.push_back(token);\n\t\t\t}\n\n\t\t\tint tag_idx = tag_ids.at(token);\n\n\t\t\tf >> token;\n\t\t\tassert(token == \"0\" || token == \"1\");\n\n\t\t\tauto& tags = token == \"1\" ? segdata_tags1(*segptr)\n\t\t\t : segdata_tags0(*segptr);\n\n\t\t\ttags.set(tag_idx);\n\n\t\t\tif (FLAGS_i) {\n\t\t\t\tauto& inv_tags = token == \"1\"\n\t\t\t\t ? segdata_tags0(*segptr)\n\t\t\t\t : segdata_tags1(*segptr);\n\n\t\t\t\ttoken = tag_ids_r.at(tag_idx) + \"__INV\";\n\n\t\t\t\tif (tag_ids.count(token) == 0) {\n\t\t\t\t\ttag_ids[token] = num_tags++;\n\t\t\t\t\ttag_ids_r.push_back(token);\n\t\t\t\t}\n\n\t\t\t\tint inv_tag_idx = tag_ids.at(token);\n\t\t\t\tinv_tags.set(inv_tag_idx);\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tabort();\n\t}\n\n\t\/\/ printf(\"Number of segments: %d\\n\", int(segdata.size()));\n\t\/\/ printf(\"Number of bits: %d\\n\", num_bits);\n\t\/\/ printf(\"Number of tags: %d\\n\", num_tags);\n\n\tfor (auto& segdat : segdata) {\n\t\tsegdata_bits(segdat.second).resize(num_bits);\n\t\tsegdata_tags1(segdat.second).resize(num_tags);\n\t\tsegdata_tags0(segdat.second).resize(num_tags);\n\t}\n}\n\nint main(int argc, char** argv) {\n\tgflags::SetUsageMessage(\n\t absl::StrCat(\"Usage: \", argv[0], \" [options] file..\"));\n\tgflags::ParseCommandLineFlags(&argc, &argv, true);\n\n\tif (argc > 1) {\n\t\tfor (int optind = 1; optind < argc; optind++) {\n\t\t\tprintf(\"Reading %s.\\n\", argv[optind]);\n\t\t\tstd::ifstream f;\n\t\t\tf.open(argv[optind]);\n\n\t\t\t\/\/ Check if input file exists.\n\t\t\tif (!f.good()) {\n\t\t\t\tprintf(\"WARNING: Input file does not exist!\\n\");\n\t\t\t}\n\n\t\t\tassert(!f.fail());\n\t\t\tread_input(f, argv[optind]);\n\t\t}\n\t} else {\n\t\tprintf(\"Reading from stding.\\n\");\n\t\tread_input(std::cin, \"stdin\");\n\t}\n\n\tprintf(\"#of segments: %d\\n\", int(segdata.size()));\n\tprintf(\"#of bits: %d\\n\", num_bits);\n\tprintf(\"#of tags: %d\\n\", num_tags);\n\n\tFILE* f = stdout;\n\n\tif (!FLAGS_o.empty()) {\n\t\tf = fopen(FLAGS_o.c_str(), \"w\");\n\t\tassert(f != nullptr);\n\t}\n\n\tint cnt_const0 = 0;\n\tint cnt_const1 = 0;\n\tint cnt_candidates = 0;\n\tint min_candidates = num_bits;\n\tint max_candidates = 0;\n\tfloat avg_candidates = 0;\n\n\tstd::vector out_lines;\n\n\tfor (int tag_idx = 0; tag_idx < num_tags; tag_idx++) {\n\t\tbool_vec mask(num_bits, true);\n\t\tint count1 = 0, count0 = 0;\n\n\t\tfor (auto& segdat : segdata) {\n\t\t\tauto& sd = segdat.second;\n\t\t\tbool tag1 = segdata_tags1(sd).get(tag_idx);\n\t\t\tbool tag0 = segdata_tags0(sd).get(tag_idx);\n\n\t\t\tassert(!tag1 || !tag0);\n\n\t\t\tif (tag1) {\n\t\t\t\tcount1++;\n\t\t\t\tmask.apply_and(segdata_bits(sd));\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (tag0) {\n\t\t\t\tcount0++;\n\t\t\t\tmask.apply_andc(segdata_bits(sd));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tassert(count1 || count0);\n\n\t\tstd::string out_line = tag_ids_r.at(tag_idx);\n\n\t\tif (count1 < FLAGS_m) {\n\t\t\tchar buffer[64];\n\t\t\tsnprintf(buffer, 64, \" \", count1);\n\t\t\tout_line += buffer;\n\t\t}\n\n\t\tif (count0 < FLAGS_m) {\n\t\t\tchar buffer[64];\n\t\t\tsnprintf(buffer, 64, \" \", count0);\n\t\t\tout_line += buffer;\n\t\t}\n\n\t\tif (count1 + count0 < FLAGS_M) {\n\t\t\tchar buffer[64];\n\t\t\tsnprintf(buffer, 64, \" \", count1, count0);\n\t\t\tout_line += buffer;\n\t\t}\n\n\t\tif (!count1) {\n\t\t\tout_lines.push_back(out_line + \" \");\n\t\t\tcnt_const0 += 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!count0) {\n\t\t\tout_line += \" \";\n\t\t\tcnt_const1 += 1;\n\t\t}\n\n\t\tint num_candidates = mask.count();\n\n\t\tif (count0) {\n\t\t\tmin_candidates =\n\t\t\t std::min(min_candidates, num_candidates);\n\t\t\tmax_candidates =\n\t\t\t std::max(max_candidates, num_candidates);\n\t\t\tavg_candidates += num_candidates;\n\t\t\tcnt_candidates += 1;\n\t\t}\n\n\t\tif (FLAGS_c < 0 ||\n\t\t (0 < num_candidates && num_candidates <= FLAGS_c)) {\n\t\t\tstd::vector out_tags;\n\t\t\tfor (int bit_idx = 0; bit_idx < num_bits; bit_idx++)\n\t\t\t\tif (mask.get(bit_idx))\n\t\t\t\t\tout_tags.push_back(\n\t\t\t\t\t bit_ids_r.at(bit_idx));\n\t\t\tstd::sort(out_tags.begin(), out_tags.end());\n\t\t\tfor (auto& tag : out_tags)\n\t\t\t\tout_line += \" \" + tag;\n\t\t} else {\n\t\t\tchar buffer[64];\n\t\t\tsnprintf(buffer, 64, \" <%d candidates>\",\n\t\t\t num_candidates);\n\t\t\tout_line += buffer;\n\t\t}\n\n\t\tout_lines.push_back(out_line);\n\t}\n\n\tstd::sort(out_lines.begin(), out_lines.end());\n\n\tfor (auto& line : out_lines)\n\t\tfprintf(f, \"%s\\n\", line.c_str());\n\n\tif (cnt_candidates)\n\t\tavg_candidates \/= cnt_candidates;\n\n\tprintf(\"#of const0 tags: %d\\n\", cnt_const0);\n\tprintf(\"#of const1 tags: %d\\n\", cnt_const1);\n\n\tif (cnt_candidates) {\n\t\tprintf(\"min #of candidates: %d\\n\", min_candidates);\n\t\tprintf(\"max #of candidates: %d\\n\", max_candidates);\n\t\tprintf(\"avg #of candidates: %.3f\\n\", avg_candidates);\n\t}\n\n\tif (!FLAGS_k.empty()) {\n\t\tf = fopen(FLAGS_k.c_str(), \"w\");\n\t\tassert(f != nullptr);\n\t\tstd::sort(bit_ids_r.begin(), bit_ids_r.end());\n\t\tfor (auto bit : bit_ids_r)\n\t\t\tfprintf(f, \"bit %s\\n\", bit.c_str());\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\\\n * ANALYSIS PERFORMANCE TOOLS *\n * libparaver-api *\n * Paraver Main Computing Library *\n *****************************************************************************\n * ___ This library is free software; you can redistribute it and\/or *\n * \/ __ modify it under the terms of the GNU LGPL as published *\n * \/ \/ _____ by the Free Software Foundation; either version 2.1 *\n * \/ \/ \/ \\ of the License, or (at your option) any later version. *\n * ( ( ( B S C ) *\n * \\ \\ \\_____\/ This library is distributed in hope that it will be *\n * \\ \\__ useful but WITHOUT ANY WARRANTY; without even the *\n * \\___ implied warranty of MERCHANTABILITY or FITNESS FOR A *\n * PARTICULAR PURPOSE. See the GNU LGPL for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with this library; if not, write to the Free Software Foundation, *\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n * The GNU LEsser General Public License is contained in the file COPYING. *\n * --------- *\n * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *\n\\*****************************************************************************\/\n\n\/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\\\n | @file: $HeadURL$\n | @last_commit: $Date$\n | @version: $Revision$\n\\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\/\n\n#include \"semanticderivedfunctions.h\"\n#include \"kwindow.h\"\n\nusing namespace std;\n\nstring DerivedAdd::name = \"add\";\nTSemanticValue DerivedAdd::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] + myInfo->values[ 1 ];\n\n return tmp;\n}\n\n\nstring DerivedProduct::name = \"product\";\nTSemanticValue DerivedProduct::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] * myInfo->values[ 1 ];\n\n return tmp;\n}\n\n\nstring DerivedSubstract::name = \"substract\";\nTSemanticValue DerivedSubstract::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] - myInfo->values[ 1 ];\n\n return tmp;\n}\n\n\nstring DerivedDivide::name = \"divide\";\nTSemanticValue DerivedDivide::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0.0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n if( myInfo->values[ 1 ] == 0 )\n return 0.0;\n\n tmp = myInfo->values[ 0 ] \/ myInfo->values[ 1 ];\n\n return tmp;\n}\n\n\nstring DerivedMaximum::name = \"maximum\";\nTSemanticValue DerivedMaximum::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] > myInfo->values[ 1 ] ?\n myInfo->values[ 0 ] :\n myInfo->values[ 1 ];\n\n return tmp;\n}\n\n\nstring DerivedMinimum::name = \"minimum\";\nTSemanticValue DerivedMinimum::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] < myInfo->values[ 1 ] ?\n myInfo->values[ 0 ] :\n myInfo->values[ 1 ];\n\n return tmp;\n}\n\n\nstring DerivedDifferent::name = \"different\";\nTSemanticValue DerivedDifferent::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] != myInfo->values[ 1 ] ?\n 1 :\n 0;\n\n return tmp;\n}\n\n\nstring ControlDerivedClearBy::name = \"controlled: clear by\";\nTSemanticValue ControlDerivedClearBy::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();\n\n if( myInfo->values[ 1 ] < prevValue[ tmpOrder ] )\n {\n tmp = 0;\n state[ tmpOrder ] = myInfo->values[ 0 ];\n prevValue[ tmpOrder ] = myInfo->values[ 1 ];\n prevResult[ tmpOrder ] = tmp;\n }\n else\n {\n if( state[ tmpOrder ] != myInfo->values[ 0 ] )\n {\n tmp = myInfo->values[ 0 ];\n state[ tmpOrder ] = myInfo->values[ 0 ];\n prevValue[ tmpOrder ] = myInfo->values[ 1 ];\n prevResult[ tmpOrder ] = tmp;\n }\n else\n tmp = prevResult[ tmpOrder ];\n\n prevValue[ tmpOrder ] = myInfo->values[ 1 ];\n }\n\n return tmp;\n}\n\nvoid ControlDerivedClearBy::init( KWindow *whichWindow )\n{\n TObjectOrder size = 0;\n\n prevValue.clear();\n state.clear();\n prevResult.clear();\n\n if( whichWindow->getLevel() >= SYSTEM )\n size = whichWindow->getTrace()->totalCPUs();\n else\n size = whichWindow->getTrace()->totalThreads();\n\n prevValue.reserve( size );\n state.reserve( size );\n prevResult.reserve( size );\n for( TObjectOrder i = 0; i < size; i++ )\n {\n prevValue.push_back( 0 );\n state.push_back( 0 );\n prevResult.push_back( 0 );\n }\n}\n\n\nstring ControlDerivedMaximum::name = \"controlled: maximum\";\nTSemanticValue ControlDerivedMaximum::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] > myInfo->values[ 1 ] ?\n myInfo->values[ 0 ] :\n myInfo->values[ 1 ];\n\n return tmp;\n}\n\n\nstring ControlDerivedAdd::name = \"controlled: add\";\nTSemanticValue ControlDerivedAdd::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] + myInfo->values[ 1 ];\n\n return tmp;\n}\nBUG FIXED: controlled clear by aware of bursts with same value\/*****************************************************************************\\\n * ANALYSIS PERFORMANCE TOOLS *\n * libparaver-api *\n * Paraver Main Computing Library *\n *****************************************************************************\n * ___ This library is free software; you can redistribute it and\/or *\n * \/ __ modify it under the terms of the GNU LGPL as published *\n * \/ \/ _____ by the Free Software Foundation; either version 2.1 *\n * \/ \/ \/ \\ of the License, or (at your option) any later version. *\n * ( ( ( B S C ) *\n * \\ \\ \\_____\/ This library is distributed in hope that it will be *\n * \\ \\__ useful but WITHOUT ANY WARRANTY; without even the *\n * \\___ implied warranty of MERCHANTABILITY or FITNESS FOR A *\n * PARTICULAR PURPOSE. See the GNU LGPL for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with this library; if not, write to the Free Software Foundation, *\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n * The GNU LEsser General Public License is contained in the file COPYING. *\n * --------- *\n * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *\n\\*****************************************************************************\/\n\n\/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\\\n | @file: $HeadURL$\n | @last_commit: $Date$\n | @version: $Revision$\n\\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\/\n\n#include \"semanticderivedfunctions.h\"\n#include \"kwindow.h\"\n\nusing namespace std;\n\nstring DerivedAdd::name = \"add\";\nTSemanticValue DerivedAdd::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] + myInfo->values[ 1 ];\n\n return tmp;\n}\n\n\nstring DerivedProduct::name = \"product\";\nTSemanticValue DerivedProduct::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] * myInfo->values[ 1 ];\n\n return tmp;\n}\n\n\nstring DerivedSubstract::name = \"substract\";\nTSemanticValue DerivedSubstract::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] - myInfo->values[ 1 ];\n\n return tmp;\n}\n\n\nstring DerivedDivide::name = \"divide\";\nTSemanticValue DerivedDivide::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0.0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n if( myInfo->values[ 1 ] == 0 )\n return 0.0;\n\n tmp = myInfo->values[ 0 ] \/ myInfo->values[ 1 ];\n\n return tmp;\n}\n\n\nstring DerivedMaximum::name = \"maximum\";\nTSemanticValue DerivedMaximum::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] > myInfo->values[ 1 ] ?\n myInfo->values[ 0 ] :\n myInfo->values[ 1 ];\n\n return tmp;\n}\n\n\nstring DerivedMinimum::name = \"minimum\";\nTSemanticValue DerivedMinimum::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] < myInfo->values[ 1 ] ?\n myInfo->values[ 0 ] :\n myInfo->values[ 1 ];\n\n return tmp;\n}\n\n\nstring DerivedDifferent::name = \"different\";\nTSemanticValue DerivedDifferent::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] != myInfo->values[ 1 ] ?\n 1 :\n 0;\n\n return tmp;\n}\n\n\nstring ControlDerivedClearBy::name = \"controlled: clear by\";\nTSemanticValue ControlDerivedClearBy::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();\n\n if( myInfo->values[ 1 ] < prevValue[ tmpOrder ] )\n {\n tmp = 0;\n state[ tmpOrder ] = myInfo->values[ 0 ];\n prevValue[ tmpOrder ] = myInfo->values[ 1 ];\n prevResult[ tmpOrder ] = tmp;\n }\n else\n {\n tmp = myInfo->values[ 0 ];\n state[ tmpOrder ] = myInfo->values[ 0 ];\n prevValue[ tmpOrder ] = myInfo->values[ 1 ];\n prevResult[ tmpOrder ] = tmp;\n }\n\n return tmp;\n}\n\nvoid ControlDerivedClearBy::init( KWindow *whichWindow )\n{\n TObjectOrder size = 0;\n\n prevValue.clear();\n state.clear();\n prevResult.clear();\n\n if( whichWindow->getLevel() >= SYSTEM )\n size = whichWindow->getTrace()->totalCPUs();\n else\n size = whichWindow->getTrace()->totalThreads();\n\n prevValue.reserve( size );\n state.reserve( size );\n prevResult.reserve( size );\n for( TObjectOrder i = 0; i < size; i++ )\n {\n prevValue.push_back( 0 );\n state.push_back( 0 );\n prevResult.push_back( 0 );\n }\n}\n\n\nstring ControlDerivedMaximum::name = \"controlled: maximum\";\nTSemanticValue ControlDerivedMaximum::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] > myInfo->values[ 1 ] ?\n myInfo->values[ 0 ] :\n myInfo->values[ 1 ];\n\n return tmp;\n}\n\n\nstring ControlDerivedAdd::name = \"controlled: add\";\nTSemanticValue ControlDerivedAdd::execute( const SemanticInfo *info )\n{\n TSemanticValue tmp = 0;\n const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;\n\n tmp = myInfo->values[ 0 ] + myInfo->values[ 1 ];\n\n return tmp;\n}\n<|endoftext|>"} {"text":"#include \r\n\r\n#include \"Dominio.h\"\r\n#include \"Entidades.h\"\r\n#include \"TestesDominio.h\"\r\n#include \"TestesEntidades.h\"\r\n\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n\r\n cout << \"Testes de Dominios\" << endl;\r\n\r\n TUNome testeNome;\r\n\r\n switch(testeNome.run()){\r\n case TUNome::SUCESSO: cout << \"Nome - SUCESSO\" << endl;\r\n break;\r\n case TUNome::FALHA : cout << \"Nome - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUTelefone testeTelefone;\r\n\r\n switch(testeTelefone.run()){\r\n case TUTelefone::SUCESSO: cout << \"Telefone - SUCESSO\" << endl;\r\n break;\r\n case TUTelefone::FALHA : cout << \"Telefone - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUTitulo testeTitulo;\r\n\r\n switch(testeTitulo.run()){\r\n case TUTitulo::SUCESSO: cout << \"Titulo - SUCESSO\" << endl;\r\n break;\r\n case TUTitulo::FALHA : cout << \"Titulo - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUCodigo testeCodigo;\r\n\r\n switch(testeCodigo.run()){\r\n case TUCodigo::SUCESSO: cout << \"Codigo - SUCESSO\" << endl;\r\n break;\r\n case TUCodigo::FALHA : cout << \"Codigo - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUGeneroLiterario testeGeneroLiterario;\r\n\r\n switch(testeGeneroLiterario.run()){\r\n case TUGeneroLiterario::SUCESSO: cout << \"Genero Literario - SUCESSO\" << endl;\r\n break;\r\n case TUGeneroLiterario::FALHA : cout << \"Genero Literario - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n\r\n TUApelido testeApelido;\r\n\r\n switch(testeApelido.run()){\r\n case TUApelido::SUCESSO: cout << \"Apelido - SUCESSO\" << endl;\r\n break;\r\n case TUApelido::FALHA : cout << \"Apelido - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUSenha testeSenha;\r\n\r\n switch(testeSenha.run()){\r\n case TUSenha::SUCESSO: cout << \"Senha - SUCESSO\" << endl;\r\n break;\r\n case TUSenha::FALHA : cout << \"Senha - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUData testeData;\r\n\r\n switch(testeData.run()){\r\n case TUData::SUCESSO: cout << \"Data - SUCESSO\" << endl;\r\n break;\r\n case TUData::FALHA : cout << \"Data - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUTexto testeTexto;\r\n\r\n switch(testeTexto.run()){\r\n case TUTexto::SUCESSO: cout << \"Texto - SUCESSO\" << endl;\r\n break;\r\n case TUTexto::FALHA : cout << \"Texto - FALHA\" << endl;\r\n break;\r\n }\r\n cout << endl;\r\n cout << \"Testes de Entidades\" << endl;\r\n\r\n\r\n TUUsuario testeUsuario;\r\n\r\n switch(testeUsuario.run()){\r\n case TUUsuario::SUCESSO: cout << \"Usuario - SUCESSO\" << endl;\r\n break;\r\n case TUUsuario::FALHA : cout << \"Usuario - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUResenha testeResenha;\r\n\r\n switch(testeResenha.run()){\r\n case TUResenha::SUCESSO: cout << \"Resenha - SUCESSO\" << endl;\r\n break;\r\n case TUResenha::FALHA : cout << \"Resenha - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TULivro testeLivro;\r\n\r\n switch(testeLivro.run()){\r\n case TULivro::SUCESSO: cout << \"Livro - SUCESSO\" << endl;\r\n break;\r\n case TULivro::FALHA : cout << \"Livro - FALHA\" << endl;\r\n break;\r\n }\r\n return 0;\r\n}\r\nadd author#include \r\n\r\n#include \"Dominio.h\"\r\n#include \"Entidades.h\"\r\n#include \"TestesDominio.h\"\r\n#include \"TestesEntidades.h\"\r\n\r\n\/** @author Acio Fernandes Galiza Magalhes - 15\/0115121\r\n* @author Diego Brian Coelho Leite - 14\/0136371\r\n*\/\r\n\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n\r\n cout << \"Testes de Dominios\" << endl;\r\n\r\n TUNome testeNome;\r\n\r\n switch(testeNome.run()){\r\n case TUNome::SUCESSO: cout << \"Nome - SUCESSO\" << endl;\r\n break;\r\n case TUNome::FALHA : cout << \"Nome - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUTelefone testeTelefone;\r\n\r\n switch(testeTelefone.run()){\r\n case TUTelefone::SUCESSO: cout << \"Telefone - SUCESSO\" << endl;\r\n break;\r\n case TUTelefone::FALHA : cout << \"Telefone - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUTitulo testeTitulo;\r\n\r\n switch(testeTitulo.run()){\r\n case TUTitulo::SUCESSO: cout << \"Titulo - SUCESSO\" << endl;\r\n break;\r\n case TUTitulo::FALHA : cout << \"Titulo - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUCodigo testeCodigo;\r\n\r\n switch(testeCodigo.run()){\r\n case TUCodigo::SUCESSO: cout << \"Codigo - SUCESSO\" << endl;\r\n break;\r\n case TUCodigo::FALHA : cout << \"Codigo - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUGeneroLiterario testeGeneroLiterario;\r\n\r\n switch(testeGeneroLiterario.run()){\r\n case TUGeneroLiterario::SUCESSO: cout << \"Genero Literario - SUCESSO\" << endl;\r\n break;\r\n case TUGeneroLiterario::FALHA : cout << \"Genero Literario - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n\r\n TUApelido testeApelido;\r\n\r\n switch(testeApelido.run()){\r\n case TUApelido::SUCESSO: cout << \"Apelido - SUCESSO\" << endl;\r\n break;\r\n case TUApelido::FALHA : cout << \"Apelido - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUSenha testeSenha;\r\n\r\n switch(testeSenha.run()){\r\n case TUSenha::SUCESSO: cout << \"Senha - SUCESSO\" << endl;\r\n break;\r\n case TUSenha::FALHA : cout << \"Senha - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUData testeData;\r\n\r\n switch(testeData.run()){\r\n case TUData::SUCESSO: cout << \"Data - SUCESSO\" << endl;\r\n break;\r\n case TUData::FALHA : cout << \"Data - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUTexto testeTexto;\r\n\r\n switch(testeTexto.run()){\r\n case TUTexto::SUCESSO: cout << \"Texto - SUCESSO\" << endl;\r\n break;\r\n case TUTexto::FALHA : cout << \"Texto - FALHA\" << endl;\r\n break;\r\n }\r\n cout << endl;\r\n cout << \"Testes de Entidades\" << endl;\r\n\r\n\r\n TUUsuario testeUsuario;\r\n\r\n switch(testeUsuario.run()){\r\n case TUUsuario::SUCESSO: cout << \"Usuario - SUCESSO\" << endl;\r\n break;\r\n case TUUsuario::FALHA : cout << \"Usuario - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TUResenha testeResenha;\r\n\r\n switch(testeResenha.run()){\r\n case TUResenha::SUCESSO: cout << \"Resenha - SUCESSO\" << endl;\r\n break;\r\n case TUResenha::FALHA : cout << \"Resenha - FALHA\" << endl;\r\n break;\r\n }\r\n\r\n TULivro testeLivro;\r\n\r\n switch(testeLivro.run()){\r\n case TULivro::SUCESSO: cout << \"Livro - SUCESSO\" << endl;\r\n break;\r\n case TULivro::FALHA : cout << \"Livro - FALHA\" << endl;\r\n break;\r\n }\r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"#include \n#include \n\n\n#define USER_AGENT \"Mozilla\/5.0 (X11; Linux x86_64) AppleWebKit\/537.36 (KHTML, like Gecko)\" \\\n \"Chrome\/55.0.0.0 Safari\/537.36 Dobostorta\/\" GIT_VERSION\n\n#define CONNECTION_NAME \"dobostorta-downloader.sock\"\n\n\nclass TortaRequestHandler : public QLocalServer {\n Q_OBJECT\n\n\n TortaRequestHandler() {\n listen(CONNECTION_NAME);\n connect(this, &QLocalServer::newConnection, this, &TortaRequestHandler::newConnection);\n }\n\n void newConnection() {\n QLocalSocket *sock = nextPendingConnection();\n connect(sock, &QLocalSocket::disconnected, sock, &QLocalSocket::close);\n\n sock->waitForReadyRead();\n\n QDataStream stream(sock);\n QByteArray data;\n stream >> data;\n emit receivedRequest({data});\n }\n\npublic:\n ~TortaRequestHandler() {\n close();\n }\n\n static TortaRequestHandler *open() {\n auto server = new TortaRequestHandler();\n if (server->isListening())\n return server;\n\n delete server;\n return nullptr;\n }\n\n static bool request(const QUrl &url) {\n QLocalSocket sock;\n sock.connectToServer(CONNECTION_NAME);\n\n if (!sock.isValid()) {\n qCritical() << tr(\"Failed to open socket: \") << sock.errorString();\n return false;\n }\n\n QByteArray block;\n QDataStream stream(&block, QIODevice::WriteOnly);\n stream << url.toEncoded();\n sock.write(block);\n\n sock.waitForBytesWritten();\n\n return true;\n }\n\nsignals:\n void receivedRequest(const QUrl &url);\n};\n\n\nclass TortaDownload : public QWidget {\n Q_OBJECT\n\n\n QNetworkReply * const reply;\n QVBoxLayout layout;\n QProgressBar progress;\n QPushButton actionButton;\n QPushButton clearButton;\n QTimer intervalTimer;\n QElapsedTimer elapsedTimer;\n\n\n void saveTo(const QString &path) {\n QFile file(path);\n if (!file.open(QIODevice::WriteOnly)) {\n QMessageBox message(QMessageBox::Critical,\n reply->url().toString(),\n tr(\"Failed create %1\\n%2\").arg(path, file.errorString()),\n QMessageBox::Retry | QMessageBox::Abort,\n this);\n if (message.exec() == QMessageBox::Retry)\n saveTo(path);\n return;\n }\n\n file.write(reply->readAll());\n file.close();\n }\n\n static QString bytesToKMG(int bytes) {\n static const char* units[] = {\"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", nullptr};\n for (int i=0; units[i+1] != nullptr; i++) {\n if (bytes < qPow(1024, i + 1)) {\n if (qPow(1024, i + 1) \/ 10 < bytes)\n return QString(\"%1%2\")\n .arg(static_cast(bytes) \/ qPow(1024, i + 1), 0, 'f', 1)\n .arg(units[i + 1]);\n else if (bytes < qPow(1024, i + 1) \/ 100)\n return QString(\"%1%2\")\n .arg(static_cast(bytes) \/ qPow(1024, i), 0, 'f', 1)\n .arg(units[i]);\n else\n return QString(\"%1%2\").arg(bytes \/ qPow(1024, i), 0, 'f', 0).arg(units[i]);\n }\n }\n return QString(\"%1PB\").arg(bytes \/ qPow(1024, 5), 0, 'f', 0);\n }\n\n void setProgressBarColor(const QColor &color) {\n QPalette p;\n p.setColor(QPalette::Highlight, color);\n progress.setPalette(p);\n }\n\n void finished(const QString &filePath) {\n if (reply->error() && reply->error() != QNetworkReply::OperationCanceledError) {\n QMessageBox message(QMessageBox::Critical,\n reply->url().toString(),\n tr(\"Failed download\\n%1\").arg(reply->errorString()),\n QMessageBox::Retry | QMessageBox::Abort,\n this);\n if (message.exec() == QMessageBox::Retry)\n emit retry();\n }\n clearButton.show();\n\n intervalTimer.stop();\n if (!reply->error()) {\n saveTo(filePath);\n progress.setFormat(QString(\"done [%1]\").arg(bytesToKMG(progress.maximum())));\n setProgressBarColor(Qt::gray);\n actionButton.setText(\"open\");\n } else {\n progress.setFormat(QString(\"%p% [%1] %2\").arg(bytesToKMG(progress.maximum()))\n .arg(reply->errorString()));\n setProgressBarColor(Qt::darkRed);\n actionButton.setText(\"retry\");\n }\n }\n\npublic:\n TortaDownload(QWidget *parent, QNetworkReply *reply, const QString &filePath)\n : QWidget(parent), reply(reply), layout(this), progress(this),\n actionButton(\"cancel\", this), clearButton(\"clear\", this) {\n setLayout(&layout);\n\n auto horizontal = new QHBoxLayout;\n layout.addLayout(horizontal);\n\n auto left = new QVBoxLayout;\n horizontal->addLayout(left, 1);\n\n QFileInfo info(filePath);\n auto path = new QLabel(info.dir().path() + \"\/\" + info.fileName() + \"<\/b>\", this);\n path->setWordWrap(true);\n left->addWidget(path);\n\n auto url = new QLabel(QString(\"%1<\/a>\").arg(reply->url().toString()), this);\n url->setOpenExternalLinks(true);\n url->setWordWrap(true);\n left->addWidget(url);\n\n horizontal->addWidget(&actionButton);\n horizontal->addWidget(&clearButton);\n clearButton.hide();\n connect(&actionButton, &QPushButton::clicked, [this, reply, filePath]{\n if (reply->isRunning())\n reply->abort();\n\t\t\telse if (reply->error())\n emit retry();\n else\n\t\t\t\tQDesktopServices::openUrl(QUrl(\"file:\/\/\" + filePath));\n });\n connect(&clearButton, &QPushButton::clicked, [this]{ emit clear(); });\n\n progress.setFormat(\"%p% [%vB \/ %mB]\");\n setProgressBarColor(Qt::darkGray);\n layout.addWidget(&progress);\n\n connect(reply, &QNetworkReply::downloadProgress, [this](qint64 received, qint64 total){\n updateProgressFormat();\n\n progress.setRange(0, total);\n progress.setValue(received);\n });\n connect(reply, &QNetworkReply::finished, [this, filePath]{ finished(filePath); });\n intervalTimer.setSingleShot(false);\n connect(&intervalTimer, &QTimer::timeout, this, &TortaDownload::updateProgressFormat);\n intervalTimer.start(1000);\n elapsedTimer.start();\n }\n\nsignals:\n void clear();\n void retry();\n\nprivate slots:\n void updateProgressFormat() {\n const int remain = qMax(\n 0.0f,\n ((progress.maximum() * elapsedTimer.elapsed()) \/ static_cast(progress.value())\n - elapsedTimer.elapsed()) \/ 1000\n );\n\n QString remainStr;\n if (remain < 60)\n remainStr = QString(\"%1 sec\").arg(remain);\n else if (remain < 60 * 60)\n remainStr = QString(\"%1' %2\\\"\").arg(remain\/60).arg(remain % 60, 2, 'd', 0, '0');\n else\n remainStr = QString(\"%1:%2'\").arg(remain\/60\/60).arg(remain\/60 % 60, 2, 'd', 0, '0');\n\n progress.setFormat(\"%p% \" + QString(\"[%1 \/ %2] %3\").arg(bytesToKMG(progress.value()))\n .arg(bytesToKMG(progress.maximum()))\n .arg(remainStr));\n }\n};\n\n\nclass TortaDL : public QScrollArea {\n Q_OBJECT\n\n\n QVBoxLayout layout;\n QNetworkAccessManager manager;\n TortaRequestHandler * const handler;\n\nprotected:\n void closeEvent(QCloseEvent *e) override {\n handler->close();\n QWidget::closeEvent(e);\n }\n \npublic:\n TortaDL(TortaRequestHandler *handler) : handler(handler) {\n setWindowTitle(\"Dobostorta downloader\");\n\n setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n layout.setAlignment(Qt::AlignTop);\n auto listArea = new QWidget(this);\n listArea->setLayout(&layout);\n setWidget(listArea);\n setWidgetResizable(true);\n\n connect(handler, &TortaRequestHandler::receivedRequest,\n [this](const QUrl &url){ startDownload(url); });\n }\n\n void startDownload(const QUrl &url, const QString &fname) {\n QNetworkRequest request(url);\n request.setRawHeader(\"User-Agent\", USER_AGENT);\n\n auto dl = new TortaDownload(widget(), manager.get(request), fname);\n\n layout.addWidget(dl);\n\n connect(dl, &TortaDownload::retry, [this, url, fname]{ startDownload(url, fname); });\n connect(dl, &TortaDownload::clear, [this, dl]{\n layout.removeWidget(dl);\n delete dl;\n });\n }\n\n bool startDownload(const QUrl &url) {\n const QString filter(QMimeDatabase().mimeTypeForFile(url.fileName()).filterString());\n const QString path(QFileDialog::getSaveFileName(\n this,\n tr(\"Save file\"),\n QFileInfo(QFileDialog().directory(), url.fileName()).absoluteFilePath(),\n filter + tr(\";; All files (*)\")\n ));\n if (path != \"\")\n startDownload(url, path);\n return path != \"\";\n }\n};\n\n\nint main(int argc, char **argv) {\n if (argc == 1) {\n qWarning(\"Dobostorta Downloader\\n$ %s URL...\", argv[0]);\n return -1;\n }\n\n QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);\n QApplication app(argc, argv);\n\n auto handler = TortaRequestHandler::open();\n if (handler == nullptr) {\n for (int i=1; iFixed indent#include \n#include \n\n\n#define USER_AGENT \"Mozilla\/5.0 (X11; Linux x86_64) AppleWebKit\/537.36 (KHTML, like Gecko)\" \\\n \"Chrome\/55.0.0.0 Safari\/537.36 Dobostorta\/\" GIT_VERSION\n\n#define CONNECTION_NAME \"dobostorta-downloader.sock\"\n\n\nclass TortaRequestHandler : public QLocalServer {\n Q_OBJECT\n\n\n TortaRequestHandler() {\n listen(CONNECTION_NAME);\n connect(this, &QLocalServer::newConnection, this, &TortaRequestHandler::newConnection);\n }\n\n void newConnection() {\n QLocalSocket *sock = nextPendingConnection();\n connect(sock, &QLocalSocket::disconnected, sock, &QLocalSocket::close);\n\n sock->waitForReadyRead();\n\n QDataStream stream(sock);\n QByteArray data;\n stream >> data;\n emit receivedRequest({data});\n }\n\npublic:\n ~TortaRequestHandler() {\n close();\n }\n\n static TortaRequestHandler *open() {\n auto server = new TortaRequestHandler();\n if (server->isListening())\n return server;\n\n delete server;\n return nullptr;\n }\n\n static bool request(const QUrl &url) {\n QLocalSocket sock;\n sock.connectToServer(CONNECTION_NAME);\n\n if (!sock.isValid()) {\n qCritical() << tr(\"Failed to open socket: \") << sock.errorString();\n return false;\n }\n\n QByteArray block;\n QDataStream stream(&block, QIODevice::WriteOnly);\n stream << url.toEncoded();\n sock.write(block);\n\n sock.waitForBytesWritten();\n\n return true;\n }\n\nsignals:\n void receivedRequest(const QUrl &url);\n};\n\n\nclass TortaDownload : public QWidget {\n Q_OBJECT\n\n\n QNetworkReply * const reply;\n QVBoxLayout layout;\n QProgressBar progress;\n QPushButton actionButton;\n QPushButton clearButton;\n QTimer intervalTimer;\n QElapsedTimer elapsedTimer;\n\n\n void saveTo(const QString &path) {\n QFile file(path);\n if (!file.open(QIODevice::WriteOnly)) {\n QMessageBox message(QMessageBox::Critical,\n reply->url().toString(),\n tr(\"Failed create %1\\n%2\").arg(path, file.errorString()),\n QMessageBox::Retry | QMessageBox::Abort,\n this);\n if (message.exec() == QMessageBox::Retry)\n saveTo(path);\n return;\n }\n\n file.write(reply->readAll());\n file.close();\n }\n\n static QString bytesToKMG(int bytes) {\n static const char* units[] = {\"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", nullptr};\n for (int i=0; units[i+1] != nullptr; i++) {\n if (bytes < qPow(1024, i + 1)) {\n if (qPow(1024, i + 1) \/ 10 < bytes)\n return QString(\"%1%2\")\n .arg(static_cast(bytes) \/ qPow(1024, i + 1), 0, 'f', 1)\n .arg(units[i + 1]);\n else if (bytes < qPow(1024, i + 1) \/ 100)\n return QString(\"%1%2\")\n .arg(static_cast(bytes) \/ qPow(1024, i), 0, 'f', 1)\n .arg(units[i]);\n else\n return QString(\"%1%2\").arg(bytes \/ qPow(1024, i), 0, 'f', 0).arg(units[i]);\n }\n }\n return QString(\"%1PB\").arg(bytes \/ qPow(1024, 5), 0, 'f', 0);\n }\n\n void setProgressBarColor(const QColor &color) {\n QPalette p;\n p.setColor(QPalette::Highlight, color);\n progress.setPalette(p);\n }\n\n void finished(const QString &filePath) {\n if (reply->error() && reply->error() != QNetworkReply::OperationCanceledError) {\n QMessageBox message(QMessageBox::Critical,\n reply->url().toString(),\n tr(\"Failed download\\n%1\").arg(reply->errorString()),\n QMessageBox::Retry | QMessageBox::Abort,\n this);\n if (message.exec() == QMessageBox::Retry)\n emit retry();\n }\n clearButton.show();\n\n intervalTimer.stop();\n if (!reply->error()) {\n saveTo(filePath);\n progress.setFormat(QString(\"done [%1]\").arg(bytesToKMG(progress.maximum())));\n setProgressBarColor(Qt::gray);\n actionButton.setText(\"open\");\n } else {\n progress.setFormat(QString(\"%p% [%1] %2\").arg(bytesToKMG(progress.maximum()))\n .arg(reply->errorString()));\n setProgressBarColor(Qt::darkRed);\n actionButton.setText(\"retry\");\n }\n }\n\npublic:\n TortaDownload(QWidget *parent, QNetworkReply *reply, const QString &filePath)\n : QWidget(parent), reply(reply), layout(this), progress(this),\n actionButton(\"cancel\", this), clearButton(\"clear\", this) {\n setLayout(&layout);\n\n auto horizontal = new QHBoxLayout;\n layout.addLayout(horizontal);\n\n auto left = new QVBoxLayout;\n horizontal->addLayout(left, 1);\n\n QFileInfo info(filePath);\n auto path = new QLabel(info.dir().path() + \"\/\" + info.fileName() + \"<\/b>\", this);\n path->setWordWrap(true);\n left->addWidget(path);\n\n auto url = new QLabel(QString(\"%1<\/a>\").arg(reply->url().toString()), this);\n url->setOpenExternalLinks(true);\n url->setWordWrap(true);\n left->addWidget(url);\n\n horizontal->addWidget(&actionButton);\n horizontal->addWidget(&clearButton);\n clearButton.hide();\n connect(&actionButton, &QPushButton::clicked, [this, reply, filePath]{\n if (reply->isRunning())\n reply->abort();\n else if (reply->error())\n emit retry();\n else\n QDesktopServices::openUrl(QUrl(\"file:\/\/\" + filePath));\n });\n connect(&clearButton, &QPushButton::clicked, [this]{ emit clear(); });\n\n progress.setFormat(\"%p% [%vB \/ %mB]\");\n setProgressBarColor(Qt::darkGray);\n layout.addWidget(&progress);\n\n connect(reply, &QNetworkReply::downloadProgress, [this](qint64 received, qint64 total){\n updateProgressFormat();\n\n progress.setRange(0, total);\n progress.setValue(received);\n });\n connect(reply, &QNetworkReply::finished, [this, filePath]{ finished(filePath); });\n intervalTimer.setSingleShot(false);\n connect(&intervalTimer, &QTimer::timeout, this, &TortaDownload::updateProgressFormat);\n intervalTimer.start(1000);\n elapsedTimer.start();\n }\n\nsignals:\n void clear();\n void retry();\n\nprivate slots:\n void updateProgressFormat() {\n const int remain = qMax(\n 0.0f,\n ((progress.maximum() * elapsedTimer.elapsed()) \/ static_cast(progress.value())\n - elapsedTimer.elapsed()) \/ 1000\n );\n\n QString remainStr;\n if (remain < 60)\n remainStr = QString(\"%1 sec\").arg(remain);\n else if (remain < 60 * 60)\n remainStr = QString(\"%1' %2\\\"\").arg(remain\/60).arg(remain % 60, 2, 'd', 0, '0');\n else\n remainStr = QString(\"%1:%2'\").arg(remain\/60\/60).arg(remain\/60 % 60, 2, 'd', 0, '0');\n\n progress.setFormat(\"%p% \" + QString(\"[%1 \/ %2] %3\").arg(bytesToKMG(progress.value()))\n .arg(bytesToKMG(progress.maximum()))\n .arg(remainStr));\n }\n};\n\n\nclass TortaDL : public QScrollArea {\n Q_OBJECT\n\n\n QVBoxLayout layout;\n QNetworkAccessManager manager;\n TortaRequestHandler * const handler;\n\nprotected:\n void closeEvent(QCloseEvent *e) override {\n handler->close();\n QWidget::closeEvent(e);\n }\n \npublic:\n TortaDL(TortaRequestHandler *handler) : handler(handler) {\n setWindowTitle(\"Dobostorta downloader\");\n\n setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n layout.setAlignment(Qt::AlignTop);\n auto listArea = new QWidget(this);\n listArea->setLayout(&layout);\n setWidget(listArea);\n setWidgetResizable(true);\n\n connect(handler, &TortaRequestHandler::receivedRequest,\n [this](const QUrl &url){ startDownload(url); });\n }\n\n void startDownload(const QUrl &url, const QString &fname) {\n QNetworkRequest request(url);\n request.setRawHeader(\"User-Agent\", USER_AGENT);\n\n auto dl = new TortaDownload(widget(), manager.get(request), fname);\n\n layout.addWidget(dl);\n\n connect(dl, &TortaDownload::retry, [this, url, fname]{ startDownload(url, fname); });\n connect(dl, &TortaDownload::clear, [this, dl]{\n layout.removeWidget(dl);\n delete dl;\n });\n }\n\n bool startDownload(const QUrl &url) {\n const QString filter(QMimeDatabase().mimeTypeForFile(url.fileName()).filterString());\n const QString path(QFileDialog::getSaveFileName(\n this,\n tr(\"Save file\"),\n QFileInfo(QFileDialog().directory(), url.fileName()).absoluteFilePath(),\n filter + tr(\";; All files (*)\")\n ));\n if (path != \"\")\n startDownload(url, path);\n return path != \"\";\n }\n};\n\n\nint main(int argc, char **argv) {\n if (argc == 1) {\n qWarning(\"Dobostorta Downloader\\n$ %s URL...\", argv[0]);\n return -1;\n }\n\n QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);\n QApplication app(argc, argv);\n\n auto handler = TortaRequestHandler::open();\n if (handler == nullptr) {\n for (int i=1; i"} {"text":"\n#include \"cmd.hpp\"\n#include \n#include \n#include \n#include \n#include \n\nCmd::Cmd()\n{}\n\nCmd::Cmd(string input1)\n{\n\tuCmd = input1;\n\t\/\/\tcout << \"uCmd: \" << uCmd << endl;\n}\n\n\n\/\/where the magic happens\n\/\/uses fork and exec to execute commands and returns bool values to indicate a valid\/invalid command\nbool Cmd::execute(vector myArgs)\n{\n\t\/\/cout << (char*)cmd_s.c_str() << endl;\n\tchar* args[512];\n\tunsigned i;\n\tfor ( i = 0; i < myArgs.size(); i++)\n\t{\n\t\targs[i] = (char*)myArgs[i].c_str();\n\t\tcout << \"ARG I = \" << args[i] << endl;\n\t}\n\targs[i] = NULL;\n\n\tpid_t pid;\n\tpid = fork();\n\tint status;\n\n\tif (pid == -1)\n\t{ \n\t\tperror(\"fork\");\n\t\texit(1);\n\t}\n\tif (pid == 0) \/\/ child process\n\t{\n\t\tif (execvp(args[0], args) == -1)\n\t\t{\n\t\t\tperror(\"exec\");\n\t\t\texit(1);\n\n\t\t}\n\t}\n\telse \/\/ parent process\n\t{\n\t\tif (waitpid(pid, &status, 0) == -1)\n\t\t{\n\t\t\tperror(\"wait\");\n\t\t\texit(1);\n\t\t}\n\t\tif (WEXITSTATUS(status) != 0)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n\n}\n\nremoved debugging statement\n#include \"cmd.hpp\"\n#include \n#include \n#include \n#include \n#include \n\nCmd::Cmd()\n{}\n\nCmd::Cmd(string input1)\n{\n\tuCmd = input1;\n\t\/\/\tcout << \"uCmd: \" << uCmd << endl;\n}\n\n\n\/\/where the magic happens\n\/\/uses fork and exec to execute commands and returns bool values to indicate a valid\/invalid command\nbool Cmd::execute(vector myArgs)\n{\n\t\/\/cout << (char*)cmd_s.c_str() << endl;\n\tchar* args[512];\n\tunsigned i;\n\tfor ( i = 0; i < myArgs.size(); i++)\n\t{\n\t\targs[i] = (char*)myArgs[i].c_str();\n\t}\n\targs[i] = NULL;\n\n\tpid_t pid;\n\tpid = fork();\n\tint status;\n\n\tif (pid == -1)\n\t{ \n\t\tperror(\"fork\");\n\t\texit(1);\n\t}\n\tif (pid == 0) \/\/ child process\n\t{\n\t\tif (execvp(args[0], args) == -1)\n\t\t{\n\t\t\tperror(\"exec\");\n\t\t\texit(1);\n\n\t\t}\n\t}\n\telse \/\/ parent process\n\t{\n\t\tif (waitpid(pid, &status, 0) == -1)\n\t\t{\n\t\t\tperror(\"wait\");\n\t\t\texit(1);\n\t\t}\n\t\tif (WEXITSTATUS(status) != 0)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n\n}\n\n<|endoftext|>"} {"text":"\/\/ @(#)root\/tree:$Name$:$Id$\n\/\/ Author: Rene Brun 14\/04\/97\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TCut \/\/\n\/\/ \/\/\n\/\/ A specialized string object used for TTree selections. \/\/\n\/\/ A TCut object has a name and a title. It does not add any data \/\/\n\/\/ members compared to a TNamed. It only add a set of operators to \/\/\n\/\/ facilitate logical string concatenation. For example, assume \/\/\n\/\/ cut1 = \"x<1\" and cut2 = \"y>2\" \/\/\n\/\/ then \/\/\n\/\/ cut1 && cut2 will be the string \"(x<1)&&(y>2)\" \/\/\n\/\/ \/\/\n\/\/ Operators =, +=, +, *, !, &&, || overloaded. \/\/\n\/\/ \/\/\n\/\/ Examples of use: \/\/\n\/\/ Root > TCut c1 = \"x<1\" \/\/\n\/\/ Root > TCut c2 = \"y<0\" \/\/\n\/\/ Root > TCut c3 = c1&&c2 \/\/\n\/\/ Root > ntuple.Draw(\"x\", c1) \/\/\n\/\/ Root > ntuple.Draw(\"x\", c1||\"x>0\") \/\/\n\/\/ Root > ntuple.Draw(\"x\", c1&&c2) \/\/\n\/\/ Root > ntuple.Draw(\"x\", \"(x+y)\"*(c1&&c2)) \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TCut.h\"\n\nClassImp(TCut)\n\n\/\/______________________________________________________________________________\nTCut::TCut() : TNamed()\n{\n\n}\n\n\/\/______________________________________________________________________________\nTCut::TCut(const char *title) : TNamed(\"CUT\",title)\n{\n\n}\n\n\/\/______________________________________________________________________________\nTCut::TCut(const char *name, const char *title) : TNamed(name,title)\n{\n\n}\n\n\/\/______________________________________________________________________________\nTCut::TCut(const TCut &cut) : TNamed(cut)\n{\n \/\/fName = cut.fName;\n \/\/fTitle = cut.fTitle;\n}\n\n\/\/______________________________________________________________________________\nTCut::~TCut()\n{\n\n}\n\n\/\/______________________________________________________________________________\nTCut& TCut::operator=(const char *rhs)\n{\n fTitle = rhs;\n return *this;\n}\n\n\/\/______________________________________________________________________________\nTCut& TCut::operator=(const TCut& rhs)\n{\n if (this != &rhs)\n TNamed::operator=(rhs);\n\n return *this;\n}\n\n\/\/______________________________________________________________________________\nTCut& TCut::operator+=(const char *rhs)\n{\n fTitle = \"(\" + fTitle + \")&&(\" + TString(rhs) + \")\";\n return *this;\n}\n\n\/\/______________________________________________________________________________\nTCut& TCut::operator+=(const TCut& rhs)\n{\n fTitle = \"(\" + fTitle + \")&&(\" + rhs.fTitle + \")\";\n return *this;\n}\n\n\/\/______________________________________________________________________________\nTCut& TCut::operator*=(const char *rhs)\n{\n fTitle = fTitle + \"*(\" + TString(rhs) + \")\";;\n return *this;\n}\n\n\/\/______________________________________________________________________________\nTCut& TCut::operator*=(const TCut& rhs)\n{\n fTitle = fTitle + \"*(\" + rhs.fTitle + \")\";;\n return *this;\n}\n\n\/\/______________________________________________________________________________\nTCut operator+(const TCut& lhs, const char *rhs)\n{\n return TCut(lhs) += rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator+(const char *lhs, const TCut& rhs)\n{\n return TCut(lhs) += rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator+(const TCut& lhs, const TCut& rhs)\n{\n return TCut(lhs) += rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator*(const TCut& lhs, const char *rhs)\n{\n return TCut(lhs) *= rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator*(const char *lhs, const TCut& rhs)\n{\n return TCut(lhs) *= rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator*(const TCut& lhs, const TCut& rhs)\n{\n return TCut(lhs) *= rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator&&(const TCut& lhs, const char *rhs)\n{\n return TCut(lhs) += rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator&&(const char *lhs, const TCut& rhs)\n{\n return TCut(lhs) += rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator&&(const TCut& lhs, const TCut& rhs)\n{\n return TCut(lhs) += rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator||(const TCut& lhs, const char *rhs)\n{\n TString s = \"(\" + lhs.fTitle + \")||(\" + TString(rhs) + \")\";\n return TCut(s.Data());\n}\n\n\/\/______________________________________________________________________________\nTCut operator||(const char *lhs, const TCut& rhs)\n{\n TString s = \"(\" + TString(lhs) + \")||(\" + rhs.fTitle + \")\";\n return TCut(s.Data());\n}\n\n\/\/______________________________________________________________________________\nTCut operator||(const TCut& lhs, const TCut& rhs)\n{\n TString s = \"(\" + lhs.fTitle + \")||(\" + rhs.fTitle + \")\";\n return TCut(s.Data());\n}\n\n\/\/______________________________________________________________________________\nTCut operator!(const TCut &rhs)\n{\n TString s = \"!(\" + rhs.fTitle + \")\";\n return TCut(s.Data());\n}\n\nsurround cut with ( ) with operator*.\/\/ @(#)root\/tree:$Name: $:$Id: TCut.cxx,v 1.1.1.1 2000\/05\/16 17:00:45 rdm Exp $\n\/\/ Author: Rene Brun 14\/04\/97\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TCut \/\/\n\/\/ \/\/\n\/\/ A specialized string object used for TTree selections. \/\/\n\/\/ A TCut object has a name and a title. It does not add any data \/\/\n\/\/ members compared to a TNamed. It only add a set of operators to \/\/\n\/\/ facilitate logical string concatenation. For example, assume \/\/\n\/\/ cut1 = \"x<1\" and cut2 = \"y>2\" \/\/\n\/\/ then \/\/\n\/\/ cut1 && cut2 will be the string \"(x<1)&&(y>2)\" \/\/\n\/\/ \/\/\n\/\/ Operators =, +=, +, *, !, &&, || overloaded. \/\/\n\/\/ \/\/\n\/\/ Examples of use: \/\/\n\/\/ Root > TCut c1 = \"x<1\" \/\/\n\/\/ Root > TCut c2 = \"y<0\" \/\/\n\/\/ Root > TCut c3 = c1&&c2 \/\/\n\/\/ Root > ntuple.Draw(\"x\", c1) \/\/\n\/\/ Root > ntuple.Draw(\"x\", c1||\"x>0\") \/\/\n\/\/ Root > ntuple.Draw(\"x\", c1&&c2) \/\/\n\/\/ Root > ntuple.Draw(\"x\", \"(x+y)\"*(c1&&c2)) \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TCut.h\"\n\nClassImp(TCut)\n\n\/\/______________________________________________________________________________\nTCut::TCut() : TNamed()\n{\n\n}\n\n\/\/______________________________________________________________________________\nTCut::TCut(const char *title) : TNamed(\"CUT\",title)\n{\n\n}\n\n\/\/______________________________________________________________________________\nTCut::TCut(const char *name, const char *title) : TNamed(name,title)\n{\n\n}\n\n\/\/______________________________________________________________________________\nTCut::TCut(const TCut &cut) : TNamed(cut)\n{\n \/\/fName = cut.fName;\n \/\/fTitle = cut.fTitle;\n}\n\n\/\/______________________________________________________________________________\nTCut::~TCut()\n{\n\n}\n\n\/\/______________________________________________________________________________\nTCut& TCut::operator=(const char *rhs)\n{\n fTitle = rhs;\n return *this;\n}\n\n\/\/______________________________________________________________________________\nTCut& TCut::operator=(const TCut& rhs)\n{\n if (this != &rhs)\n TNamed::operator=(rhs);\n\n return *this;\n}\n\n\/\/______________________________________________________________________________\nTCut& TCut::operator+=(const char *rhs)\n{\n fTitle = \"(\" + fTitle + \")&&(\" + TString(rhs) + \")\";\n return *this;\n}\n\n\/\/______________________________________________________________________________\nTCut& TCut::operator+=(const TCut& rhs)\n{\n fTitle = \"(\" + fTitle + \")&&(\" + rhs.fTitle + \")\";\n return *this;\n}\n\n\/\/______________________________________________________________________________\nTCut& TCut::operator*=(const char *rhs)\n{\n fTitle = \"(\" + fTitle + \")*(\" + TString(rhs) + \")\";\n return *this;\n}\n\n\/\/______________________________________________________________________________\nTCut& TCut::operator*=(const TCut& rhs)\n{\n fTitle = \"(\" + fTitle + \")*(\" + rhs.fTitle + \")\";\n return *this;\n}\n\n\/\/______________________________________________________________________________\nTCut operator+(const TCut& lhs, const char *rhs)\n{\n return TCut(lhs) += rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator+(const char *lhs, const TCut& rhs)\n{\n return TCut(lhs) += rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator+(const TCut& lhs, const TCut& rhs)\n{\n return TCut(lhs) += rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator*(const TCut& lhs, const char *rhs)\n{\n return TCut(lhs) *= rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator*(const char *lhs, const TCut& rhs)\n{\n return TCut(lhs) *= rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator*(const TCut& lhs, const TCut& rhs)\n{\n return TCut(lhs) *= rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator&&(const TCut& lhs, const char *rhs)\n{\n return TCut(lhs) += rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator&&(const char *lhs, const TCut& rhs)\n{\n return TCut(lhs) += rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator&&(const TCut& lhs, const TCut& rhs)\n{\n return TCut(lhs) += rhs;\n}\n\n\/\/______________________________________________________________________________\nTCut operator||(const TCut& lhs, const char *rhs)\n{\n TString s = \"(\" + lhs.fTitle + \")||(\" + TString(rhs) + \")\";\n return TCut(s.Data());\n}\n\n\/\/______________________________________________________________________________\nTCut operator||(const char *lhs, const TCut& rhs)\n{\n TString s = \"(\" + TString(lhs) + \")||(\" + rhs.fTitle + \")\";\n return TCut(s.Data());\n}\n\n\/\/______________________________________________________________________________\nTCut operator||(const TCut& lhs, const TCut& rhs)\n{\n TString s = \"(\" + lhs.fTitle + \")||(\" + rhs.fTitle + \")\";\n return TCut(s.Data());\n}\n\n\/\/______________________________________________________________________________\nTCut operator!(const TCut &rhs)\n{\n TString s = \"!(\" + rhs.fTitle + \")\";\n return TCut(s.Data());\n}\n\n<|endoftext|>"} {"text":"\/\/g++ *.cpp -lpthread -lwiringPi -std=c++11\r\n\/\/LATER MET GUI MAKEFILE \r\n\r\n#include \"I22cCom.h\"\r\n\/\/ Sensors -------------------\r\n#include \"Sensor.h\"\r\n#include \"Log.h\"\r\n#include \"Camera.h\"\r\n#include \"Light.h\"\r\n#include \"MotionSensor.h\"\r\n#include \"PressureSensor.h\"\r\n\/\/ GUI ----------\r\n#include \"dialog.h\"\r\n#include \r\n#include \"temperatuur.h\"\r\n\/\/ ----------\r\n\/\/#define I2CLOC \"\/dev\/i2c-1\"\/\/ <-- this is the real I2C device you need with the scale model\r\n#define I2CLOC \"\/dev\/simudrv\"\r\n#define LOG \"Slaaplog.txt\"\r\n\r\n#include \r\n#include \r\n#include \/\/compile with -lwiringPi\r\n\r\nusing namespace std;\r\n\r\nvector motionSensors; \/\/Vector of the sensors\r\nvector lights; \/\/Vector of the lights\r\nvector active;\r\nPressureSensor* pressureSensor;\r\nCamera* cam; \/\/Pointer to the camera\r\nLog* log;\r\n\r\nint pressureValue;\r\nbool asleep = false;\r\nbool day = true;\r\nbool anomaly = false;\r\nint temperature = 20;\r\nlong sleepTimer = 0;\r\n\r\n\r\nvoid checkAnomaly();\r\nvoid updateSensors();\r\nvoid checkCam();\r\nvoid sendAlert();\r\nvoid init();\r\n\r\nint GUImain(int argc, char *argv[]){\r\n\tQApplication a(argc, argv);\r\n\tDialog w;\r\n\tw.show();\r\n\ta.exec();\r\n}\r\n\r\nint main() {\r\n init();\r\n while(1) {\r\n updateSensors();\r\n checkAnomaly();\r\n checkCam();\r\n checkTemperature();\r\n }\r\n}\r\n\r\n\/*Init for the main*\/\r\nvoid init() {\r\n\tstd::thread GUIloop(GUImain);\r\n\tGUIloop.join();\t\r\n\twiringPiSetupGpio();\r\n\tI2CCom i2c(I2CLOC); \/\/the i2c to communicate with sensor\r\n\tLight x(22);\r\n\tMotionSensor s1(0xFC,i2c);\r\n\tMotionSensor s2(0xBC,i2c);\r\n\tMotionSensor s3(0xEC,i2c);\r\n\tPressureSensor s4(0x06, i2c);\r\n\tLog l1(LOG);\r\n\tCamera c1;\r\n\tcam = &c1;\r\n\tlog = &l1;\r\n\tpressureSensor = &s4;\r\n\tmotionSensors.push_back(&s1);\r\n\tmotionSensors.push_back(&s2);\r\n\tmotionSensors.push_back(&s3);\r\n\tlights.push_back(&x);\r\n\r\nactive.resize(motionSensors.size());\r\n}\r\n\/*Updates sensors*\/\r\nvoid updateSensors() {\r\n \/\/update van elke sensor de value en de active\r\n bool alert = true;\r\n for(int i = 0; icheck()) {\r\n \/\/active[i]=1;\r\n alert = false;\r\n\t\tcout <<\"halleyula\" <check()) {\r\n asleep = true;\r\n }\r\n if(alert & !asleep) {\r\n sendAlert();\r\n }\r\n pressureValue = s4->getValue();\r\n}\r\n\r\n\/*Send Alarm*\/\r\nvoid sendAlert(){\r\n cout<<\"Alert\"<setCamera(true);\r\n } else if(anomaly) {\r\n cam->setCamera(true);\r\n } else {\r\n cam->setCamera(false);\r\n }\r\n}\r\n\r\n\/*Checks if there is an anomaly, otherwise checks if Tim's asleep*\/\r\nvoid checkAnomaly(){\r\n if(pressureValue < 20) {\r\n asleep = false;\r\n sleepTimer = 0;\r\n } else if(pressureValue > 20 && pressureValue < 150) {\r\n anomaly = true;\r\n sleepTimer = 0;\r\n } else if(pressureValue > 150 && pressureValue < 200) {\r\n sleepTimer = 0;\r\n \/\/ Changing positions while asleep\r\n \/\/Do nothing, maybe verify if person really is sleeping\r\n } else if(pressureValue > 200 && sleepTimer = 0) {\r\n sleepTimer = time(0) + 900;\r\n } else if(pressureValue >200 && sleepTimer != 0) {\r\n if( time(0) >= sleepTimer) {\r\n asleep = true\r\n }\r\n }\r\n \r\n}\r\n\r\n\/*Checks the set temperature from the gui*\/\r\ncheckTemperature() {\r\n temperature = IngesteldeTemperatuur;\r\n}\r\n\r\nbugfix\/\/g++ *.cpp -lpthread -lwiringPi -std=c++11\r\n\/\/LATER MET GUI MAKEFILE \r\n\r\n#include \"I22cCom.h\"\r\n\/\/ Sensors -------------------\r\n#include \"Sensor.h\"\r\n#include \"Log.h\"\r\n#include \"Camera.h\"\r\n#include \"Light.h\"\r\n#include \"MotionSensor.h\"\r\n#include \"PressureSensor.h\"\r\n\/\/ GUI ----------\r\n#include \"dialog.h\"\r\n#include \r\n#include \"temperatuur.h\"\r\n\/\/ ----------\r\n\/\/#define I2CLOC \"\/dev\/i2c-1\"\/\/ <-- this is the real I2C device you need with the scale model\r\n#define I2CLOC \"\/dev\/simudrv\"\r\n#define LOG \"Slaaplog.txt\"\r\n\r\n#include \r\n#include \r\n#include \/\/compile with -lwiringPi\r\n\r\nusing namespace std;\r\n\r\nvector motionSensors; \/\/Vector of the sensors\r\nvector lights; \/\/Vector of the lights\r\nvector active;\r\nPressureSensor* pressureSensor;\r\nCamera* cam; \/\/Pointer to the camera\r\nLog* log;\r\n\r\nint pressureValue;\r\nbool asleep = false;\r\nbool day = true;\r\nbool anomaly = false;\r\nint temperature = 20;\r\nlong sleepTimer = 0;\r\n\r\n\r\nvoid checkAnomaly();\r\nvoid updateSensors();\r\nvoid checkCam();\r\nvoid sendAlert();\r\nvoid init();\r\n\r\nint GUImain(int argc, char *argv[]){\r\n\tQApplication a(argc, argv);\r\n\tDialog w;\r\n\tw.show();\r\n\ta.exec();\r\n}\r\n\r\nint main() {\r\n init();\r\n while(1) {\r\n updateSensors();\r\n checkAnomaly();\r\n checkCam();\r\n checkTemperature();\r\n }\r\n}\r\n\r\n\/*Init for the main*\/\r\nvoid init() {\r\n\tthread GUIloop(GUImain);\r\n\tGUIloop.join();\t\r\n\twiringPiSetupGpio();\r\n\tI2CCom i2c(I2CLOC); \/\/the i2c to communicate with sensor\r\n\tLight x(22);\r\n\tMotionSensor s1(0xFC,i2c);\r\n\tMotionSensor s2(0xBC,i2c);\r\n\tMotionSensor s3(0xEC,i2c);\r\n\tPressureSensor s4(0x06, i2c);\r\n\tLog l1(LOG);\r\n\tCamera c1;\r\n\tcam = &c1;\r\n\tlog = &l1;\r\n\tpressureSensor = &s4;\r\n\tmotionSensors.push_back(&s1);\r\n\tmotionSensors.push_back(&s2);\r\n\tmotionSensors.push_back(&s3);\r\n\tlights.push_back(&x);\r\n\r\nactive.resize(motionSensors.size());\r\n}\r\n\/*Updates sensors*\/\r\nvoid updateSensors() {\r\n \/\/update van elke sensor de value en de active\r\n bool alert = true;\r\n for(int i = 0; icheck()) {\r\n \/\/active[i]=1;\r\n alert = false;\r\n\t\tcout <<\"halleyula\" <check()) {\r\n asleep = true;\r\n }\r\n if(alert & !asleep) {\r\n sendAlert();\r\n }\r\n pressureValue = s4->getValue();\r\n}\r\n\r\n\/*Send Alarm*\/\r\nvoid sendAlert(){\r\n cout<<\"Alert\"<setCamera(true);\r\n } else if(anomaly) {\r\n cam->setCamera(true);\r\n } else {\r\n cam->setCamera(false);\r\n }\r\n}\r\n\r\n\/*Checks if there is an anomaly, otherwise checks if Tim's asleep*\/\r\nvoid checkAnomaly(){\r\n if(pressureValue < 20) {\r\n asleep = false;\r\n sleepTimer = 0;\r\n } else if(pressureValue > 20 && pressureValue < 150) {\r\n anomaly = true;\r\n sleepTimer = 0;\r\n } else if(pressureValue > 150 && pressureValue < 200) {\r\n sleepTimer = 0;\r\n \/\/ Changing positions while asleep\r\n \/\/Do nothing, maybe verify if person really is sleeping\r\n } else if(pressureValue > 200 && sleepTimer = 0) {\r\n sleepTimer = time(0) + 900;\r\n } else if(pressureValue >200 && sleepTimer != 0) {\r\n if( time(0) >= sleepTimer) {\r\n asleep = true\r\n }\r\n }\r\n \r\n}\r\n\r\n\/*Checks the set temperature from the gui*\/\r\ncheckTemperature() {\r\n temperature = IngesteldeTemperatuur;\r\n}\r\n\r\n<|endoftext|>"} {"text":"\/\/g++ *.cpp -lpthread -lwiringPi -std=c++11\r\n\/\/LATER MET GUI MAKEFILE \r\n\r\n#include \"Sensor.h\"\r\n#include \"I22cCom.h\"\r\n#include \"Log.h\"\r\n#include \"Camera.h\"\r\n#include \"Light.h\"\r\n#include \"MotionSensor.h\"\r\n#include \"PressureSensor.h\"\r\n#define I2CLOC \"\/dev\/i2c-1\"\/\/ <-- this is the real I2C device you need with the scale model\r\n\/\/\/#define I2CLOC \"\/dev\/simudrv\"\r\n#define LOG \"Slaaplog.txt\"\r\n\r\n#include \r\n#include \r\n#include \/\/compile with -lwiringPi\r\n\r\nusing namespace std;\r\n\r\nvector motionSensors; \/\/Vector of the sensors\r\nvector lights; \/\/Vector of the lights\r\nvector active;\r\nPressureSensor* pressureSensor;\r\nCamera* cam; \/\/Pointer to the camera\r\nLog* log;\r\n\r\nint pressureValue;\r\nbool asleep = false;\r\nbool day = true;\r\nbool anomaly = false;\r\nint temperature = 20;\r\n\r\n\r\nvoid checkAnomaly();\r\nvoid updateSensors();\r\nvoid checkCam();\r\nvoid sendAlert();\r\nvoid init();\r\n\r\nint main() {\t\r\n\r\n init();\r\n \r\n while(1) {\r\n updateSensors();\r\n checkAnomaly();\r\n checkCam();\r\n\t}\r\n}\r\n\r\n\/*Init for the main*\/\r\nvoid init() {\r\n wiringPiSetupGpio();\r\n I2CCom i2c(I2CLOC); \/\/the i2c to communicate with sensors\r\n \r\n Light x(22);\r\n MotionSensor s1(0x05,i2c);\r\n PressureSensor s2(0x06, i2c);\r\n Log l1(LOG);\r\n Camera c1;\r\n \r\n cam = &c1;\r\n log = &l1;\r\n pressureSensor = &s2;\r\n motionSensors.push_back(&s1);\r\n lights.push_back(&x);\r\n\r\n active.resize(motionSensors.size());\r\n}\r\n\/*Updates sensors*\/\r\nvoid updateSensors() {\r\n \/\/update van elke sensor de value en de active\r\n bool alert = true;\r\n for(int i = 0; icheck()) {\r\n active[i]=1;\r\n alert = false;\r\n } else {\r\n active[i]=0;\r\n }\r\n }\r\n if(alert & !asleep) {\r\n sendAlert();\r\n }\r\n}\r\n\r\n\/*Send Alarm*\/\r\nvoid sendAlert(){\r\n cout<<\"Alert\"<setCamera(true);\r\n } else if(anomaly) {\r\n cam->setCamera(true);\r\n } else {\r\n cam->setCamera(false);\r\n }\r\n}\r\n\r\nvoid checkAnomaly(){\r\n \r\n \r\n if(pressureValue > 20 && pressureValue < 150) {\r\n anomaly = true;\r\n }\r\n if(pressureValue > 150 && pressureValue < 200) { \/\/ Changing positions while asleep\r\n \/\/Do nothing, maybe verify if person really is sleeping\r\n }\r\n if(pressureValue > 200) {\r\n asleep = true;\r\n }\r\n \r\n}\r\n\r\nMain Update\/\/g++ *.cpp -lpthread -lwiringPi -std=c++11\r\n\/\/LATER MET GUI MAKEFILE \r\n\r\n#include \"Sensor.h\"\r\n#include \"I22cCom.h\"\r\n#include \"Log.h\"\r\n#include \"Camera.h\"\r\n#include \"Light.h\"\r\n#include \"MotionSensor.h\"\r\n#include \"PressureSensor.h\"\r\n\/\/#define I2CLOC \"\/dev\/i2c-1\"\/\/ <-- this is the real I2C device you need with the scale model\r\n#define I2CLOC \"\/dev\/simudrv\"\r\n#define LOG \"Slaaplog.txt\"\r\n\r\n#include \r\n#include \r\n#include \/\/compile with -lwiringPi\r\n\r\nusing namespace std;\r\n\r\nvector motionSensors; \/\/Vector of the sensors\r\nvector lights; \/\/Vector of the lights\r\nvector active;\r\nPressureSensor* pressureSensor;\r\nCamera* cam; \/\/Pointer to the camera\r\nLog* log;\r\n\r\nint pressureValue;\r\nbool asleep = false;\r\nbool day = true;\r\nbool anomaly = false;\r\nint temperature = 20;\r\n\r\n\r\nvoid checkAnomaly();\r\nvoid updateSensors();\r\nvoid checkCam();\r\nvoid sendAlert();\r\nvoid init();\r\n\r\nint main() {\r\n init();\r\n while(1) {\r\n updateSensors();\r\n checkAnomaly();\r\n checkCam();\r\n }\r\n}\r\n\r\n\/*Init for the main*\/\r\nvoid init() {\r\n wiringPiSetupGpio();\r\n I2CCom i2c(I2CLOC); \/\/the i2c to communicate with sensor\r\n Light x(22);\r\n MotionSensor s1(0xFC,i2c);\r\n MotionSensor s2(0xBC,i2c);\r\n MotionSensor s3(0xEC,i2c);\r\n PressureSensor s4(0x06, i2c);\r\n Log l1(LOG);\r\n Camera c1;\r\n cam = &c1;\r\n log = &l1;\r\n pressureSensor = &s4;\r\n motionSensors.push_back(&s1);\r\n motionSensors.push_back(&s2);\r\n motionSensors.push_back(&s3);\r\n lights.push_back(&x);\r\n\r\n active.resize(motionSensors.size());\r\n}\r\n\/*Updates sensors*\/\r\nvoid updateSensors() {\r\n \/\/update van elke sensor de value en de active\r\n bool alert = true;\r\n for(int i = 0; icheck()) {\r\n \/\/active[i]=1;\r\n alert = false;\r\n\t\tcout <<\"halleyula\" <setCamera(true);\r\n } else if(anomaly) {\r\n cam->setCamera(true);\r\n } else {\r\n cam->setCamera(false);\r\n }\r\n}\r\n\r\nvoid checkAnomaly(){\r\n \r\n \r\n if(pressureValue > 20 && pressureValue < 150) {\r\n anomaly = true;\r\n }\r\n if(pressureValue > 150 && pressureValue < 200) { \/\/ Changing positions while asleep\r\n \/\/Do nothing, maybe verify if person really is sleeping\r\n }\r\n if(pressureValue > 200) {\r\n asleep = true;\r\n }\r\n \r\n}\r\n\r\n<|endoftext|>"} {"text":"\/\/g++ *.cpp -lpthread -lwiringPi -std=c++11\r\n\/\/LATER MET GUI MAKEFILE \r\n\r\n#include \"Sensor.h\"\r\n#include \"I22cCom.h\"\r\n#include \"Log.h\"\r\n#include \"Camera.h\"\r\n#include \"Light.h\"\r\n#include \"MotionSensor.h\"\r\n#include \"PressureSensor.h\"\r\n#define I2CLOC \"\/dev\/i2c-1\"\/\/ <-- this is the real I2C device you need with the scale model\r\n\/\/\/#define I2CLOC \"\/dev\/simudrv\"\r\n#define LOG \"Slaaplog.txt\"\r\n\r\n#include \r\n#include \r\n#include \/\/compile with -lwiringPi\r\n\r\nusing namespace std;\r\n\r\nvector motionSensors; \/\/Vector of the sensors\r\nvector lights; \/\/Vector of the lights\r\nvector active;\r\nPressureSensor& pressureSensor;\r\nCamera& cam; \/\/Pointer to the camera\r\nLog& log;\r\n\r\nint pressureValue;\r\nbool sleep = false;\r\nbool day = true;\r\nbool anomaly = false;\r\nint temperature = 20;\r\n\r\n\r\nint sumActive(int active[]) {\r\n\tint sum=0;\r\n\tfor(int i=0;iCheck()) { \/\/ Call their check function\r\n\t\t\t\tactive[i]=1; \/\/ And if the check is positive (returns true). \r\n\t\t\t\t\/\/TODO ENABLE LIGHTS\r\n\t\t\t} else active[i]=0;\r\n\t\tif(sumActive(active)==0) {\r\n sendAlert();\r\n\t\t}\r\n\t\tfor(i=0;iCheck(); \/\/ Check if timer expired yet\r\n *\/\r\n updateSensors();\r\n checkAnomaly();\r\n checkCam();\r\n\t}\r\n}\r\n\r\n\/*Init for the main*\/\r\nvoid init() {\r\n wiringPiSetupGpio();\r\n I2CCom i2c(I2CLOC); \/\/the i2c to communicate with sensors\r\n \r\n Light x(22);\r\n MotionSensor s1(0x05,i2c);\r\n PressureSensor s2(0x06, i2c, log);\r\n Log l1(LOG);\r\n Camera c1();\r\n \r\n cam = &c1\r\n log = &l1;\r\n pressureSensor = &s2;\r\n motionSensors.push_back(&s1);\r\n lights.push_back(&x);\r\n\r\n active.resize(motionSensors.size);\r\n}\r\n\/*Updates sensors*\/\r\nvoid updateSensors() {\r\n \/\/update van elke sensor de value en de active\r\n bool alert = true;\r\n for(int i = 0; icheck()) {\r\n active[i]=1;\r\n alert = false;\r\n } else {\r\n active[i]=0;\r\n }\r\n }\r\n if(alert) {\r\n sendAlert();\r\n }\r\n}\r\n\r\n\/*Send Alarm*\/\r\nvoid sendAlert(){\r\n cout<<\"Alert\"< 20 && pressureValue < 150) {\r\n anomaly = true;\r\n }\r\n if(pressureValue > 150 && pressureValue < 200) { \/\/ Changing positions while asleep\r\n \/\/Do nothing, maybe verify if person really is sleeping\r\n }\r\n if(pressureValue > 200) {\r\n sleep = true;\r\n }\r\n \r\n}\r\n\r\nmain fix\/\/g++ *.cpp -lpthread -lwiringPi -std=c++11\r\n\/\/LATER MET GUI MAKEFILE \r\n\r\n#include \"Sensor.h\"\r\n#include \"I22cCom.h\"\r\n#include \"Log.h\"\r\n#include \"Camera.h\"\r\n#include \"Light.h\"\r\n#include \"MotionSensor.h\"\r\n#include \"PressureSensor.h\"\r\n#define I2CLOC \"\/dev\/i2c-1\"\/\/ <-- this is the real I2C device you need with the scale model\r\n\/\/\/#define I2CLOC \"\/dev\/simudrv\"\r\n#define LOG \"Slaaplog.txt\"\r\n\r\n#include \r\n#include \r\n#include \/\/compile with -lwiringPi\r\n\r\nusing namespace std;\r\n\r\nvector motionSensors; \/\/Vector of the sensors\r\nvector lights; \/\/Vector of the lights\r\nvector active;\r\nPressureSensor& pressureSensor;\r\nCamera& cam; \/\/Pointer to the camera\r\nLog& log;\r\n\r\nint pressureValue;\r\nbool sleep = false;\r\nbool day = true;\r\nbool anomaly = false;\r\nint temperature = 20;\r\n\r\n\r\nint sumActive(int active[]) {\r\n\tint sum=0;\r\n\tfor(int i=0;iCheck()) { \/\/ Call their check function\r\n\t\t\t\tactive[i]=1; \/\/ And if the check is positive (returns true). \r\n\t\t\t\t\/\/TODO ENABLE LIGHTS\r\n\t\t\t} else active[i]=0;\r\n\t\tif(sumActive(active)==0) {\r\n sendAlert();\r\n\t\t}\r\n\t\tfor(i=0;iCheck(); \/\/ Check if timer expired yet\r\n *\/\r\n updateSensors();\r\n checkAnomaly();\r\n checkCam();\r\n\t}\r\n}\r\n\r\n\/*Init for the main*\/\r\nvoid init() {\r\n wiringPiSetupGpio();\r\n I2CCom i2c(I2CLOC); \/\/the i2c to communicate with sensors\r\n \r\n Light x(22);\r\n MotionSensor s1(0x05,i2c);\r\n PressureSensor s2(0x06, i2c, log);\r\n Log l1(LOG);\r\n Camera c1();\r\n \r\n cam = &c1\r\n log = &l1;\r\n pressureSensor = &s2;\r\n motionSensors.push_back(&s1);\r\n lights.push_back(&x);\r\n\r\n active.resize(motionSensors.size);\r\n}\r\n\/*Updates sensors*\/\r\nvoid updateSensors() {\r\n \/\/update van elke sensor de value en de active\r\n bool alert = true;\r\n for(int i = 0; icheck()) {\r\n active[i]=1;\r\n alert = false;\r\n } else {\r\n active[i]=0;\r\n }\r\n }\r\n if(alert && sleep = false) {\r\n sendAlert();\r\n }\r\n}\r\n\r\n\/*Send Alarm*\/\r\nvoid sendAlert(){\r\n cout<<\"Alert\"< 20 && pressureValue < 150) {\r\n anomaly = true;\r\n }\r\n if(pressureValue > 150 && pressureValue < 200) { \/\/ Changing positions while asleep\r\n \/\/Do nothing, maybe verify if person really is sleeping\r\n }\r\n if(pressureValue > 200) {\r\n sleep = true;\r\n }\r\n \r\n}\r\n\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\nusing namespace std;\n#define HASHSIZE 32\n\nint main(int argc, char* argv[])\n{\n string input;\n\n \/\/ a sha1 hash is 20 bytes\n unsigned char hash[HASHSIZE];\n\n for (int i = 0; i < HASHSIZE; i++) {\n hash[i] = 'x';\n }\n\n \/\/cout << \"enter your string: \";\n \/\/getline(cin, input);\n \tinput = \"hello\";\n\n \/\/ compute the sha1 of the input, and store it our hash array\n SHA256((unsigned char*)input.c_str(), input.size(), hash);\n \/\/ the above is the exact same thing as doing:\n \/\/ SHA_CTX ctx;\n \/\/ \n \/\/ SHA1_Init(&ctx);\n \/\/ SHA1_Update(&ctx, input.c_str(), input.size());\n \/\/ SHA1_Final(hash, &ctx);\n\n \/\/ since the hash array just contains a bunch of bytes,\n \/\/ print them as hexadecimal values\n cout << \"the hash was: \";\n for(int i = 0; i < HASHSIZE; ++i) {\n cout << hex << setw(2) << setfill('0') << (int)hash[i];\n }\n cout << endl;\n cout << \"DONE!\" << endl;\n}\n\nstring getPassword(string masterpass, string location) {\n\tstring prehash = masterpass+location;\n\n\t\/\/unsigned char hash[20];\n\treturn prehash;\n}added a method to do fast conversion between byes and a base 64 string#include \n#include \n#include \n#include \n\nusing namespace std;\n#define HASHSIZE 32\n\nstring getCutHex(unsigned char hash[HASHSIZE]) {\n\tunsigned char b64_1 = hash[0] >> 2;\n\tunsigned char b64_2 = ((hash[0]&0x03)<<4) + (hash[1]>>4);\n\tunsigned char b64_3 = ((hash[1]&0x0F)<<2) + (hash[2]>>6);\n\tunsigned char b64_4 = hash[2] & 0x3F;\n\tcout << (int)0x3F << endl;\n\tcout << (int)hash[0] << \":\" << (int)hash[1] << \":\" << (int)hash[2] << endl;\n\tcout << (int)b64_1 << \":\" << (int)b64_2 << \":\" << (int)b64_3 << \":\" << (int)b64_4 << endl;\n\n\treturn \"\";\n}\n\nstring getPassword(string masterpass, string domain) {\n\tstring prehash = masterpass+domain;\n\tunsigned char hash[HASHSIZE];\n\tSHA256((unsigned char*)prehash.c_str(), prehash.size(), hash);\n\n\tgetCutHex(hash);\n\n\t\/\/unsigned char hash[20];\n\treturn prehash;\n}\n\n\n\nint main(int argc, char* argv[]) {\n\tstring input;\n\n\t\/\/ a sha1 hash is 20 bytes\n\n\n\t\/\/ for (int i = 0; i < HASHSIZE; i++) {\n\t\/\/ \thash[i] = 'x';\n\t\/\/ }\n\n\t\/\/cout << \"enter your string: \";\n\t\/\/getline(cin, input);\n\tinput = \"hello\";\n\n\t\/\/ compute the sha1 of the input, and store it our hash array\n\n\t\/\/ the above is the exact same thing as doing:\n\t\/\/ SHA_CTX ctx;\n\t\/\/ \n\t\/\/ SHA1_Init(&ctx);\n\t\/\/ SHA1_Update(&ctx, input.c_str(), input.size());\n\t\/\/ SHA1_Final(hash, &ctx);\n\n\t\/\/ since the hash array just contains a bunch of bytes,\n\t\/\/ print them as hexadecimal values\n\t\/\/ cout << \"the hash was: \";\n\t\/\/ for(int i = 0; i < HASHSIZE; ++i) {\n\t\/\/ \tcout << hex << setw(2) << setfill('0') << (int)hash[i];\n\t\/\/ }\n\t\/\/ cout << endl;\n\n\tgetPassword (\"harvy\",\"dent\");\n\n\tcout << \"DONE!\" << endl;\n}<|endoftext|>"} {"text":"#pragma once\n\/**\n\t@file\n\t@brief definition of Op\n\t@author MITSUNARI Shigeo(@herumi)\n\t@license modified new BSD license\n\thttp:\/\/opensource.org\/licenses\/BSD-3-Clause\n*\/\n#include \n#include \n#include \n\n#if defined(__EMSCRIPTEN__) || defined(__wasm__)\n\t#define MCL_DONT_USE_XBYAK\n\t#define MCL_DONT_USE_OPENSSL\n#endif\n#if !defined(MCL_DONT_USE_XBYAK) && (defined(_WIN64) || defined(__x86_64__)) && (MCL_SIZEOF_UNIT == 8) && !defined(MCL_STATIC_CODE)\n\t#define MCL_USE_XBYAK\n#endif\n#if defined(MCL_USE_XBYAK) || defined(MCL_STATIC_CODE)\n\t#define MCL_X64_ASM\n\t#define MCL_XBYAK_DIRECT_CALL\n#endif\n\n#define MCL_MAX_HASH_BIT_SIZE 512\n\nnamespace mcl {\n\nstatic const int version = 0x163; \/* 0xABC = A.BC *\/\n\n\/*\n\tspecifies available string format mode for X::setIoMode()\n\t\/\/ for Fp, Fp2, Fp6, Fp12\n\tdefault(0) : IoDec\n\tprintable string(zero terminated, variable size)\n\tIoBin(2) | IoDec(10) | IoHex(16) | IoBinPrefix | IoHexPrefix\n\n\tbyte string(not zero terminated, fixed size)\n\tIoArray | IoArrayRaw\n\tIoArray = IoSerialize\n\n\t\/\/ for Ec\n\taffine(0) | IoEcCompY | IoComp\n\tdefault : affine\n\n\taffine and IoEcCompY are available with ioMode for Fp\n\tIoSerialize ignores ioMode for Fp\n\n\tIoAuto\n\t\tdec or hex according to ios_base::fmtflags\n\tIoBin\n\t\tbinary number([01]+)\n\tIoDec\n\t\tdecimal number\n\tIoHex\n\t\thexadecimal number([0-9a-fA-F]+)\n\tIoBinPrefix\n\t\t0b + \n\tIoHexPrefix\n\t\t0x + \n\tIoArray\n\t\tarray of Unit(fixed size = Fp::getByteSize())\n\tIoArrayRaw\n\t\tarray of Unit(fixed size = Fp::getByteSize()) without Montgomery conversion\n\n\t\/\/ for Ec::setIoMode()\n\tIoEcAffine(default)\n\t\"0\" ; infinity\n\t\"1 \" ; affine coordinate\n\n\tIoEcProj\n\t\"4\" ; projective or jacobi coordinate\n\n\tIoEcCompY\n\t\t1-bit y prepresentation of elliptic curve\n\t\t\"2 \" ; compressed for even y\n\t\t\"3 \" ; compressed for odd y\n\n\tIoSerialize\n\t\tif isMSBserialize(): \/\/ p is not full bit\n\t\t\tsize = Fp::getByteSize()\n\t\t\tuse MSB of array of x for 1-bit y for prime p where (p % 8 != 0)\n\t\t\t[0] ; infinity\n\t\t\t ; for even y\n\t\t\t|1 ; for odd y ; |1 means set MSB of x\n\t\telse:\n\t\t\tsize = Fp::getByteSize() + 1\n\t\t\t[0] ; infinity\n\t\t\t2 ; for even y\n\t\t\t3 ; for odd y\n*\/\nenum IoMode {\n\tIoAuto = 0, \/\/ dec or hex according to ios_base::fmtflags\n\tIoBin = 2, \/\/ binary number without prefix\n\tIoDec = 10, \/\/ decimal number without prefix\n\tIoHex = 16, \/\/ hexadecimal number without prefix\n\tIoArray = 32, \/\/ array of Unit(fixed size)\n\tIoArrayRaw = 64, \/\/ raw array of Unit without Montgomery conversion\n\tIoPrefix = 128, \/\/ append '0b'(bin) or '0x'(hex)\n\tIoBinPrefix = IoBin | IoPrefix,\n\tIoHexPrefix = IoHex | IoPrefix,\n\tIoEcAffine = 0, \/\/ affine coordinate\n\tIoEcCompY = 256, \/\/ 1-bit y representation of elliptic curve\n\tIoSerialize = 512, \/\/ use MBS for 1-bit y\n\tIoFixedSizeByteSeq = IoSerialize, \/\/ obsolete\n\tIoEcProj = 1024, \/\/ projective or jacobi coordinate\n\tIoSerializeHexStr = 2048, \/\/ printable hex string\n\tIoEcAffineSerialize = 4096 \/\/ serialize [x:y]\n};\n\nnamespace fp {\n\ninline bool isIoSerializeMode(int ioMode)\n{\n\treturn ioMode & (IoArray | IoArrayRaw | IoSerialize | IoEcAffineSerialize | IoSerializeHexStr);\n}\n\nconst size_t maxMulVecN = 32; \/\/ inner loop of mulVec\n\n#ifndef MCL_MAX_MUL_VEC_NGLV\n\t#define MCL_MAX_MUL_VEC_NGLV 16\n#endif\nconst size_t maxMulVecNGLV = MCL_MAX_MUL_VEC_NGLV; \/\/ inner loop of mulVec with GLV\n\nstruct FpGenerator;\nstruct Op;\n\ntypedef void (*void1u)(Unit*);\ntypedef void (*void2u)(Unit*, const Unit*);\ntypedef void (*void2uI)(Unit*, const Unit*, Unit);\ntypedef void (*void2uIu)(Unit*, const Unit*, Unit, const Unit*);\ntypedef void (*void2uOp)(Unit*, const Unit*, const Op&);\ntypedef void (*void3u)(Unit*, const Unit*, const Unit*);\ntypedef void (*void4u)(Unit*, const Unit*, const Unit*, const Unit*);\ntypedef int (*int2u)(Unit*, const Unit*);\n\ntypedef Unit (*u1uII)(Unit*, Unit, Unit);\ntypedef Unit (*u3u)(Unit*, const Unit*, const Unit*);\n\n\/*\n\tdisable -Wcast-function-type\n\tthe number of arguments of some JIT functions is smaller than that of T\n*\/\ntemplate\nT func_ptr_cast(S func)\n{\n\treturn reinterpret_cast(reinterpret_cast(func));\n}\nstruct Block {\n\tconst Unit *p; \/\/ pointer to original FpT.v_\n\tsize_t n;\n\tUnit v_[maxUnitSize];\n};\n\nenum Mode {\n\tFP_AUTO,\n\tFP_GMP,\n\tFP_GMP_MONT,\n\tFP_LLVM,\n\tFP_LLVM_MONT,\n\tFP_XBYAK\n};\n\nenum PrimeMode {\n\tPM_GENERIC = 0,\n\tPM_NIST_P192,\n\tPM_SECP256K1,\n\tPM_NIST_P521\n};\n\nstruct Op {\n\t\/*\n\t\tdon't change the layout of rp and p\n\t\tasm code assumes &rp + 1 == p\n\t*\/\n\tUnit rp;\n\tUnit p[maxUnitSize];\n\tmpz_class mp;\n\tuint32_t pmod4;\n\tmcl::SquareRoot sq;\n\tmcl::Modp modp;\n\tmcl::SmallModp smallModp;\n\tUnit half[maxUnitSize]; \/\/ (p + 1) \/ 2\n\tUnit oneRep[maxUnitSize]; \/\/ 1(=inv R if Montgomery)\n\t\/*\n\t\tfor Montgomery\n\t\tone = 1\n\t\tR = (1 << (N * sizeof(Unit) * 8)) % p\n\t\tR2 = (R * R) % p\n\t\tR3 = RR^3\n\t*\/\n\tUnit one[maxUnitSize];\n\tUnit R2[maxUnitSize];\n\tUnit R3[maxUnitSize];\n#ifdef MCL_USE_XBYAK\n\tFpGenerator *fg;\n#endif\n#ifdef MCL_X64_ASM\n\tmcl::Array invTbl;\n#endif\n\tvoid3u fp_addA_;\n\tvoid3u fp_subA_;\n\tvoid2u fp_negA_;\n\tvoid3u fp_mulA_;\n\tvoid2u fp_sqrA_;\n\tvoid2u fp_mul2A_;\n\tvoid2u fp_mul9A_;\n\tvoid3u fp2_addA_;\n\tvoid3u fp2_subA_;\n\tvoid2u fp2_negA_;\n\tvoid3u fp2_mulA_;\n\tvoid2u fp2_sqrA_;\n\tvoid2u fp2_mul2A_;\n\tvoid3u fpDbl_addA_;\n\tvoid3u fpDbl_subA_;\n\tvoid2u fpDbl_modA_;\n\tvoid3u fp2Dbl_mulPreA_;\n\tvoid2u fp2Dbl_sqrPreA_;\n\tvoid2u fp2Dbl_mul_xiA_;\n\tsize_t maxN;\n\tsize_t N;\n\tsize_t bitSize;\n\tbool (*fp_isZero)(const Unit*);\n\tvoid1u fp_clear;\n\tvoid2u fp_copy;\n\tvoid2u fp_shr1;\n\tvoid3u fp_neg;\n\tvoid4u fp_add;\n\tvoid4u fp_sub;\n\tvoid4u fp_mul;\n\tvoid3u fp_sqr;\n\tvoid3u fp_mul2;\n\tvoid2uOp fp_invOp;\n\tvoid2uIu fp_mulUnit; \/\/ fpN1_mod + fp_mulUnitPre\n\n\tvoid3u fpDbl_mulPre;\n\tvoid2u fpDbl_sqrPre;\n\tint2u fp_preInv;\n\tvoid2uI fp_mulUnitPre; \/\/ z[N + 1] = x[N] * y\n\tvoid3u fpN1_mod; \/\/ y[N] = x[N + 1] % p[N]\n\n\tvoid4u fpDbl_add;\n\tvoid4u fpDbl_sub;\n\tvoid3u fpDbl_mod;\n\n\tu3u fp_addPre; \/\/ without modulo p\n\tu3u fp_subPre; \/\/ without modulo p\n\tu3u fpDbl_addPre;\n\tu3u fpDbl_subPre;\n\t\/*\n\t\tfor Fp2 = F[u] \/ (u^2 + 1)\n\t\tx = a + bu\n\t*\/\n\tint xi_a; \/\/ xi = xi_a + u\n\tvoid4u fp2_mulNF;\n\tvoid2u fp2_mul_xiA_;\n\tuint32_t (*hash)(void *out, uint32_t maxOutSize, const void *msg, uint32_t msgSize);\n\n\tPrimeMode primeMode;\n\tbool isFullBit; \/\/ true if bitSize % uniSize == 0\n\tbool isMont; \/\/ true if use Montgomery\n\tbool isFastMod; \/\/ true if modulo is fast\n\n\tOp()\n\t{\n\t\tclear();\n\t}\n\t~Op()\n\t{\n#ifdef MCL_USE_XBYAK\n\t\tdestroyFpGenerator(fg);\n#endif\n\t}\n\tvoid clear()\n\t{\n\t\trp = 0;\n\t\tmemset(p, 0, sizeof(p));\n\t\tmp = 0;\n\t\tpmod4 = 0;\n\t\tsq.clear();\n\t\t\/\/ fg is not set\n\t\tmemset(half, 0, sizeof(half));\n\t\tmemset(oneRep, 0, sizeof(oneRep));\n\t\tmemset(one, 0, sizeof(one));\n\t\tmemset(R2, 0, sizeof(R2));\n\t\tmemset(R3, 0, sizeof(R3));\n#ifdef MCL_X64_ASM\n\t\tinvTbl.clear();\n#endif\n\t\tfp_addA_ = 0;\n\t\tfp_subA_ = 0;\n\t\tfp_negA_ = 0;\n\t\tfp_mulA_ = 0;\n\t\tfp_sqrA_ = 0;\n\t\tfp_mul2A_ = 0;\n\t\tfp_mul9A_ = 0;\n\t\tfp2_addA_ = 0;\n\t\tfp2_subA_ = 0;\n\t\tfp2_negA_ = 0;\n\t\tfp2_mulA_ = 0;\n\t\tfp2_sqrA_ = 0;\n\t\tfp2_mul2A_ = 0;\n\t\tfpDbl_addA_ = 0;\n\t\tfpDbl_subA_ = 0;\n\t\tfpDbl_modA_ = 0;\n\t\tfp2Dbl_mulPreA_ = 0;\n\t\tfp2Dbl_sqrPreA_ = 0;\n\t\tfp2Dbl_mul_xiA_ = 0;\n\t\tmaxN = 0;\n\t\tN = 0;\n\t\tbitSize = 0;\n\t\tfp_isZero = 0;\n\t\tfp_clear = 0;\n\t\tfp_copy = 0;\n\t\tfp_shr1 = 0;\n\t\tfp_neg = 0;\n\t\tfp_add = 0;\n\t\tfp_sub = 0;\n\t\tfp_mul = 0;\n\t\tfp_sqr = 0;\n\t\tfp_mul2 = 0;\n\t\tfp_invOp = 0;\n\t\tfp_mulUnit = 0;\n\n\t\tfpDbl_mulPre = 0;\n\t\tfpDbl_sqrPre = 0;\n\t\tfp_preInv = 0;\n\t\tfp_mulUnitPre = 0;\n\t\tfpN1_mod = 0;\n\n\t\tfpDbl_add = 0;\n\t\tfpDbl_sub = 0;\n\t\tfpDbl_mod = 0;\n\n\t\tfp_addPre = 0;\n\t\tfp_subPre = 0;\n\t\tfpDbl_addPre = 0;\n\t\tfpDbl_subPre = 0;\n\n\t\txi_a = 0;\n\t\tfp2_mulNF = 0;\n\t\tfp2_mul_xiA_ = 0;\n\t\thash = 0;\n\n\t\tprimeMode = PM_GENERIC;\n\t\tisFullBit = false;\n\t\tisMont = false;\n\t\tisFastMod = false;\n\t}\n\tvoid fromMont(Unit* y, const Unit *x) const\n\t{\n\t\t\/*\n\t\t\tM(x, y) = xyR^-1\n\t\t\ty = M(x, 1) = xR^-1\n\t\t*\/\n\t\tfp_mul(y, x, one, p);\n\t}\n\tvoid toMont(Unit* y, const Unit *x) const\n\t{\n\t\t\/*\n\t\t\ty = M(x, R2) = xR^2 R^-1 = xR\n\t\t*\/\n\t\tfp_mul(y, x, R2, p);\n\t}\n\tbool init(const mpz_class& p, size_t maxBitSize, int xi_a, Mode mode, size_t mclMaxBitSize = MCL_MAX_BIT_SIZE);\n#ifdef MCL_USE_XBYAK\n\tstatic FpGenerator* createFpGenerator();\n\tstatic void destroyFpGenerator(FpGenerator *fg);\n#endif\nprivate:\n\tOp(const Op&);\n\tvoid operator=(const Op&);\n};\n\ninline const char* getIoSeparator(int ioMode)\n{\n\treturn (ioMode & (IoArray | IoArrayRaw | IoSerialize | IoSerializeHexStr | IoEcAffineSerialize)) ? \"\" : \" \";\n}\n\ninline void dump(const void *buf, size_t n)\n{\n\tconst uint8_t *s = (const uint8_t *)buf;\n\tfor (size_t i = 0; i < n; i++) {\n\t\tprintf(\"%02x \", s[i]);\n\t}\n\tprintf(\"\\n\");\n}\n\n#ifndef CYBOZU_DONT_USE_STRING\nint detectIoMode(int ioMode, const std::ios_base& ios);\n\ninline void dump(const std::string& s)\n{\n\tdump(s.c_str(), s.size());\n}\n#endif\n\n} } \/\/ mcl::fp\nv1.64#pragma once\n\/**\n\t@file\n\t@brief definition of Op\n\t@author MITSUNARI Shigeo(@herumi)\n\t@license modified new BSD license\n\thttp:\/\/opensource.org\/licenses\/BSD-3-Clause\n*\/\n#include \n#include \n#include \n\n#if defined(__EMSCRIPTEN__) || defined(__wasm__)\n\t#define MCL_DONT_USE_XBYAK\n\t#define MCL_DONT_USE_OPENSSL\n#endif\n#if !defined(MCL_DONT_USE_XBYAK) && (defined(_WIN64) || defined(__x86_64__)) && (MCL_SIZEOF_UNIT == 8) && !defined(MCL_STATIC_CODE)\n\t#define MCL_USE_XBYAK\n#endif\n#if defined(MCL_USE_XBYAK) || defined(MCL_STATIC_CODE)\n\t#define MCL_X64_ASM\n\t#define MCL_XBYAK_DIRECT_CALL\n#endif\n\n#define MCL_MAX_HASH_BIT_SIZE 512\n\nnamespace mcl {\n\nstatic const int version = 0x164; \/* 0xABC = A.BC *\/\n\n\/*\n\tspecifies available string format mode for X::setIoMode()\n\t\/\/ for Fp, Fp2, Fp6, Fp12\n\tdefault(0) : IoDec\n\tprintable string(zero terminated, variable size)\n\tIoBin(2) | IoDec(10) | IoHex(16) | IoBinPrefix | IoHexPrefix\n\n\tbyte string(not zero terminated, fixed size)\n\tIoArray | IoArrayRaw\n\tIoArray = IoSerialize\n\n\t\/\/ for Ec\n\taffine(0) | IoEcCompY | IoComp\n\tdefault : affine\n\n\taffine and IoEcCompY are available with ioMode for Fp\n\tIoSerialize ignores ioMode for Fp\n\n\tIoAuto\n\t\tdec or hex according to ios_base::fmtflags\n\tIoBin\n\t\tbinary number([01]+)\n\tIoDec\n\t\tdecimal number\n\tIoHex\n\t\thexadecimal number([0-9a-fA-F]+)\n\tIoBinPrefix\n\t\t0b + \n\tIoHexPrefix\n\t\t0x + \n\tIoArray\n\t\tarray of Unit(fixed size = Fp::getByteSize())\n\tIoArrayRaw\n\t\tarray of Unit(fixed size = Fp::getByteSize()) without Montgomery conversion\n\n\t\/\/ for Ec::setIoMode()\n\tIoEcAffine(default)\n\t\"0\" ; infinity\n\t\"1 \" ; affine coordinate\n\n\tIoEcProj\n\t\"4\" ; projective or jacobi coordinate\n\n\tIoEcCompY\n\t\t1-bit y prepresentation of elliptic curve\n\t\t\"2 \" ; compressed for even y\n\t\t\"3 \" ; compressed for odd y\n\n\tIoSerialize\n\t\tif isMSBserialize(): \/\/ p is not full bit\n\t\t\tsize = Fp::getByteSize()\n\t\t\tuse MSB of array of x for 1-bit y for prime p where (p % 8 != 0)\n\t\t\t[0] ; infinity\n\t\t\t ; for even y\n\t\t\t|1 ; for odd y ; |1 means set MSB of x\n\t\telse:\n\t\t\tsize = Fp::getByteSize() + 1\n\t\t\t[0] ; infinity\n\t\t\t2 ; for even y\n\t\t\t3 ; for odd y\n*\/\nenum IoMode {\n\tIoAuto = 0, \/\/ dec or hex according to ios_base::fmtflags\n\tIoBin = 2, \/\/ binary number without prefix\n\tIoDec = 10, \/\/ decimal number without prefix\n\tIoHex = 16, \/\/ hexadecimal number without prefix\n\tIoArray = 32, \/\/ array of Unit(fixed size)\n\tIoArrayRaw = 64, \/\/ raw array of Unit without Montgomery conversion\n\tIoPrefix = 128, \/\/ append '0b'(bin) or '0x'(hex)\n\tIoBinPrefix = IoBin | IoPrefix,\n\tIoHexPrefix = IoHex | IoPrefix,\n\tIoEcAffine = 0, \/\/ affine coordinate\n\tIoEcCompY = 256, \/\/ 1-bit y representation of elliptic curve\n\tIoSerialize = 512, \/\/ use MBS for 1-bit y\n\tIoFixedSizeByteSeq = IoSerialize, \/\/ obsolete\n\tIoEcProj = 1024, \/\/ projective or jacobi coordinate\n\tIoSerializeHexStr = 2048, \/\/ printable hex string\n\tIoEcAffineSerialize = 4096 \/\/ serialize [x:y]\n};\n\nnamespace fp {\n\ninline bool isIoSerializeMode(int ioMode)\n{\n\treturn ioMode & (IoArray | IoArrayRaw | IoSerialize | IoEcAffineSerialize | IoSerializeHexStr);\n}\n\nconst size_t maxMulVecN = 32; \/\/ inner loop of mulVec\n\n#ifndef MCL_MAX_MUL_VEC_NGLV\n\t#define MCL_MAX_MUL_VEC_NGLV 16\n#endif\nconst size_t maxMulVecNGLV = MCL_MAX_MUL_VEC_NGLV; \/\/ inner loop of mulVec with GLV\n\nstruct FpGenerator;\nstruct Op;\n\ntypedef void (*void1u)(Unit*);\ntypedef void (*void2u)(Unit*, const Unit*);\ntypedef void (*void2uI)(Unit*, const Unit*, Unit);\ntypedef void (*void2uIu)(Unit*, const Unit*, Unit, const Unit*);\ntypedef void (*void2uOp)(Unit*, const Unit*, const Op&);\ntypedef void (*void3u)(Unit*, const Unit*, const Unit*);\ntypedef void (*void4u)(Unit*, const Unit*, const Unit*, const Unit*);\ntypedef int (*int2u)(Unit*, const Unit*);\n\ntypedef Unit (*u1uII)(Unit*, Unit, Unit);\ntypedef Unit (*u3u)(Unit*, const Unit*, const Unit*);\n\n\/*\n\tdisable -Wcast-function-type\n\tthe number of arguments of some JIT functions is smaller than that of T\n*\/\ntemplate\nT func_ptr_cast(S func)\n{\n\treturn reinterpret_cast(reinterpret_cast(func));\n}\nstruct Block {\n\tconst Unit *p; \/\/ pointer to original FpT.v_\n\tsize_t n;\n\tUnit v_[maxUnitSize];\n};\n\nenum Mode {\n\tFP_AUTO,\n\tFP_GMP,\n\tFP_GMP_MONT,\n\tFP_LLVM,\n\tFP_LLVM_MONT,\n\tFP_XBYAK\n};\n\nenum PrimeMode {\n\tPM_GENERIC = 0,\n\tPM_NIST_P192,\n\tPM_SECP256K1,\n\tPM_NIST_P521\n};\n\nstruct Op {\n\t\/*\n\t\tdon't change the layout of rp and p\n\t\tasm code assumes &rp + 1 == p\n\t*\/\n\tUnit rp;\n\tUnit p[maxUnitSize];\n\tmpz_class mp;\n\tuint32_t pmod4;\n\tmcl::SquareRoot sq;\n\tmcl::Modp modp;\n\tmcl::SmallModp smallModp;\n\tUnit half[maxUnitSize]; \/\/ (p + 1) \/ 2\n\tUnit oneRep[maxUnitSize]; \/\/ 1(=inv R if Montgomery)\n\t\/*\n\t\tfor Montgomery\n\t\tone = 1\n\t\tR = (1 << (N * sizeof(Unit) * 8)) % p\n\t\tR2 = (R * R) % p\n\t\tR3 = RR^3\n\t*\/\n\tUnit one[maxUnitSize];\n\tUnit R2[maxUnitSize];\n\tUnit R3[maxUnitSize];\n#ifdef MCL_USE_XBYAK\n\tFpGenerator *fg;\n#endif\n#ifdef MCL_X64_ASM\n\tmcl::Array invTbl;\n#endif\n\tvoid3u fp_addA_;\n\tvoid3u fp_subA_;\n\tvoid2u fp_negA_;\n\tvoid3u fp_mulA_;\n\tvoid2u fp_sqrA_;\n\tvoid2u fp_mul2A_;\n\tvoid2u fp_mul9A_;\n\tvoid3u fp2_addA_;\n\tvoid3u fp2_subA_;\n\tvoid2u fp2_negA_;\n\tvoid3u fp2_mulA_;\n\tvoid2u fp2_sqrA_;\n\tvoid2u fp2_mul2A_;\n\tvoid3u fpDbl_addA_;\n\tvoid3u fpDbl_subA_;\n\tvoid2u fpDbl_modA_;\n\tvoid3u fp2Dbl_mulPreA_;\n\tvoid2u fp2Dbl_sqrPreA_;\n\tvoid2u fp2Dbl_mul_xiA_;\n\tsize_t maxN;\n\tsize_t N;\n\tsize_t bitSize;\n\tbool (*fp_isZero)(const Unit*);\n\tvoid1u fp_clear;\n\tvoid2u fp_copy;\n\tvoid2u fp_shr1;\n\tvoid3u fp_neg;\n\tvoid4u fp_add;\n\tvoid4u fp_sub;\n\tvoid4u fp_mul;\n\tvoid3u fp_sqr;\n\tvoid3u fp_mul2;\n\tvoid2uOp fp_invOp;\n\tvoid2uIu fp_mulUnit; \/\/ fpN1_mod + fp_mulUnitPre\n\n\tvoid3u fpDbl_mulPre;\n\tvoid2u fpDbl_sqrPre;\n\tint2u fp_preInv;\n\tvoid2uI fp_mulUnitPre; \/\/ z[N + 1] = x[N] * y\n\tvoid3u fpN1_mod; \/\/ y[N] = x[N + 1] % p[N]\n\n\tvoid4u fpDbl_add;\n\tvoid4u fpDbl_sub;\n\tvoid3u fpDbl_mod;\n\n\tu3u fp_addPre; \/\/ without modulo p\n\tu3u fp_subPre; \/\/ without modulo p\n\tu3u fpDbl_addPre;\n\tu3u fpDbl_subPre;\n\t\/*\n\t\tfor Fp2 = F[u] \/ (u^2 + 1)\n\t\tx = a + bu\n\t*\/\n\tint xi_a; \/\/ xi = xi_a + u\n\tvoid4u fp2_mulNF;\n\tvoid2u fp2_mul_xiA_;\n\tuint32_t (*hash)(void *out, uint32_t maxOutSize, const void *msg, uint32_t msgSize);\n\n\tPrimeMode primeMode;\n\tbool isFullBit; \/\/ true if bitSize % uniSize == 0\n\tbool isMont; \/\/ true if use Montgomery\n\tbool isFastMod; \/\/ true if modulo is fast\n\n\tOp()\n\t{\n\t\tclear();\n\t}\n\t~Op()\n\t{\n#ifdef MCL_USE_XBYAK\n\t\tdestroyFpGenerator(fg);\n#endif\n\t}\n\tvoid clear()\n\t{\n\t\trp = 0;\n\t\tmemset(p, 0, sizeof(p));\n\t\tmp = 0;\n\t\tpmod4 = 0;\n\t\tsq.clear();\n\t\t\/\/ fg is not set\n\t\tmemset(half, 0, sizeof(half));\n\t\tmemset(oneRep, 0, sizeof(oneRep));\n\t\tmemset(one, 0, sizeof(one));\n\t\tmemset(R2, 0, sizeof(R2));\n\t\tmemset(R3, 0, sizeof(R3));\n#ifdef MCL_X64_ASM\n\t\tinvTbl.clear();\n#endif\n\t\tfp_addA_ = 0;\n\t\tfp_subA_ = 0;\n\t\tfp_negA_ = 0;\n\t\tfp_mulA_ = 0;\n\t\tfp_sqrA_ = 0;\n\t\tfp_mul2A_ = 0;\n\t\tfp_mul9A_ = 0;\n\t\tfp2_addA_ = 0;\n\t\tfp2_subA_ = 0;\n\t\tfp2_negA_ = 0;\n\t\tfp2_mulA_ = 0;\n\t\tfp2_sqrA_ = 0;\n\t\tfp2_mul2A_ = 0;\n\t\tfpDbl_addA_ = 0;\n\t\tfpDbl_subA_ = 0;\n\t\tfpDbl_modA_ = 0;\n\t\tfp2Dbl_mulPreA_ = 0;\n\t\tfp2Dbl_sqrPreA_ = 0;\n\t\tfp2Dbl_mul_xiA_ = 0;\n\t\tmaxN = 0;\n\t\tN = 0;\n\t\tbitSize = 0;\n\t\tfp_isZero = 0;\n\t\tfp_clear = 0;\n\t\tfp_copy = 0;\n\t\tfp_shr1 = 0;\n\t\tfp_neg = 0;\n\t\tfp_add = 0;\n\t\tfp_sub = 0;\n\t\tfp_mul = 0;\n\t\tfp_sqr = 0;\n\t\tfp_mul2 = 0;\n\t\tfp_invOp = 0;\n\t\tfp_mulUnit = 0;\n\n\t\tfpDbl_mulPre = 0;\n\t\tfpDbl_sqrPre = 0;\n\t\tfp_preInv = 0;\n\t\tfp_mulUnitPre = 0;\n\t\tfpN1_mod = 0;\n\n\t\tfpDbl_add = 0;\n\t\tfpDbl_sub = 0;\n\t\tfpDbl_mod = 0;\n\n\t\tfp_addPre = 0;\n\t\tfp_subPre = 0;\n\t\tfpDbl_addPre = 0;\n\t\tfpDbl_subPre = 0;\n\n\t\txi_a = 0;\n\t\tfp2_mulNF = 0;\n\t\tfp2_mul_xiA_ = 0;\n\t\thash = 0;\n\n\t\tprimeMode = PM_GENERIC;\n\t\tisFullBit = false;\n\t\tisMont = false;\n\t\tisFastMod = false;\n\t}\n\tvoid fromMont(Unit* y, const Unit *x) const\n\t{\n\t\t\/*\n\t\t\tM(x, y) = xyR^-1\n\t\t\ty = M(x, 1) = xR^-1\n\t\t*\/\n\t\tfp_mul(y, x, one, p);\n\t}\n\tvoid toMont(Unit* y, const Unit *x) const\n\t{\n\t\t\/*\n\t\t\ty = M(x, R2) = xR^2 R^-1 = xR\n\t\t*\/\n\t\tfp_mul(y, x, R2, p);\n\t}\n\tbool init(const mpz_class& p, size_t maxBitSize, int xi_a, Mode mode, size_t mclMaxBitSize = MCL_MAX_BIT_SIZE);\n#ifdef MCL_USE_XBYAK\n\tstatic FpGenerator* createFpGenerator();\n\tstatic void destroyFpGenerator(FpGenerator *fg);\n#endif\nprivate:\n\tOp(const Op&);\n\tvoid operator=(const Op&);\n};\n\ninline const char* getIoSeparator(int ioMode)\n{\n\treturn (ioMode & (IoArray | IoArrayRaw | IoSerialize | IoSerializeHexStr | IoEcAffineSerialize)) ? \"\" : \" \";\n}\n\ninline void dump(const void *buf, size_t n)\n{\n\tconst uint8_t *s = (const uint8_t *)buf;\n\tfor (size_t i = 0; i < n; i++) {\n\t\tprintf(\"%02x \", s[i]);\n\t}\n\tprintf(\"\\n\");\n}\n\n#ifndef CYBOZU_DONT_USE_STRING\nint detectIoMode(int ioMode, const std::ios_base& ios);\n\ninline void dump(const std::string& s)\n{\n\tdump(s.c_str(), s.size());\n}\n#endif\n\n} } \/\/ mcl::fp\n<|endoftext|>"} {"text":"\/**\n * @file\n *\n * @brief Tests for yanlr plugin\n *\n * @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n *\n *\/\n\n\/\/ -- Imports ------------------------------------------------------------------------------------------------------------------------------\n\n#include \"yanlr.hpp\"\n\n#include \n#include \n\n#include \n#include \n\nusing ckdb::keyNew;\n\nusing CppKeySet = kdb::KeySet;\nusing CppKey = kdb::Key;\n\n\/\/ -- Macros -------------------------------------------------------------------------------------------------------------------------------\n\n#define OPEN_PLUGIN(parentName, filepath) \\\n\tCppKeySet modules{ 0, KS_END }; \\\n\tCppKeySet config{ 0, KS_END }; \\\n\telektraModulesInit (modules.getKeySet (), 0); \\\n\tCppKey parent{ parentName, KEY_VALUE, filepath, KEY_END }; \\\n\tPlugin * plugin = elektraPluginOpen (\"yanlr\", modules.getKeySet (), config.getKeySet (), *parent); \\\n\texit_if_fail (plugin != NULL, \"Could not open yanlr plugin\")\n\n#define CLOSE_PLUGIN() \\\n\telektraPluginClose (plugin, 0); \\\n\telektraModulesClose (modules.getKeySet (), 0); \\\n\tksDel (modules.release ()); \\\n\tconfig.release ()\n\n#define PREFIX \"user\/tests\/yanlr\/\"\n\n\/\/ -- Functions ---------------------------------------------------------------------------------------------------------------------------\n\nvoid test_read (string const & filepath, CppKeySet expected, int const status = ELEKTRA_PLUGIN_STATUS_SUCCESS)\n#ifdef __llvm__\n\t__attribute__ ((annotate (\"oclint:suppress[high ncss method]\"), annotate (\"oclint:suppress[empty if statement]\"),\n\t\t\tannotate (\"oclint:suppress[too few branches in switch statement]\")))\n#endif\n{\n\tOPEN_PLUGIN (PREFIX, srcdir_file (filepath.c_str ()));\n\n\t\/\/ We replace the value of the parent key of expected keyset, if the header file specifies the value @CONFIG_FILEPATH@.\n\t\/\/ We could also do that via CMake, but the current solution should be easier for now.\n\tCppKey root = expected.lookup (PREFIX, KDB_O_POP);\n\tif (root)\n\t{\n\t\tif (root.getString () == \"@CONFIG_FILEPATH@\") root.setString (srcdir_file (filepath.c_str ()));\n\t\texpected.append (root);\n\t}\n\n\tCppKeySet keys;\n\tsucceed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), status, \"Call of `kdbGet` failed\");\n\tcompare_keyset (expected, keys);\n\n\tCLOSE_PLUGIN ();\n}\n\n\/\/ -- Tests --------------------------------------------------------------------------------------------------------------------------------\n\nTEST (yanlr, basics)\n{\n\tOPEN_PLUGIN (\"system\/elektra\/modules\/yanlr\", \"file\/path\");\n\n\tCppKeySet keys;\n\tsucceed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,\n\t\t\t \"Could not retrieve plugin contract\");\n\n\tCLOSE_PLUGIN ();\n}\n\nTEST (yanlr, empty)\n{\n\ttest_read (\"yanlr\/null.yaml\",\n#include \"yanlr\/null.hpp\"\n\t\t , ELEKTRA_PLUGIN_STATUS_NO_UPDATE);\n\ttest_read (\"yanlr\/comment.yaml\",\n#include \"yanlr\/null.hpp\"\n\t\t , ELEKTRA_PLUGIN_STATUS_NO_UPDATE);\n}\n\nTEST (yanlr, scalar)\n{\n\ttest_read (\"yanlr\/plain_scalar-word_chars.yaml\",\n#include \"yanlr\/plain_scalar-word_chars.hpp\"\n\t);\n\ttest_read (\"yanlr\/plain_scalar-word_chars_space.yaml\",\n#include \"yanlr\/plain_scalar-word_chars_space.hpp\"\n\t);\n\ttest_read (\"yanlr\/single_quoted_scalar.yaml\",\n#include \"yanlr\/single_quoted_scalar.hpp\"\n\t);\n\ttest_read (\"yanlr\/double_quoted_scalar.yaml\",\n#include \"yanlr\/double_quoted_scalar.hpp\"\n\t);\n}\n\nTEST (yanlr, list)\n{\n\ttest_read (\"yanlr\/list-plain_scalars.yaml\",\n#include \"yanlr\/list-plain_scalars.hpp\"\n\t);\n\ttest_read (\"yanlr\/list-list_map-mixed_scalars.yaml\",\n#include \"yanlr\/list-list_map-mixed_scalars.hpp\"\n\t);\n}\n\nTEST (yanlr, map)\n{\n\ttest_read (\"yanlr\/map-null.yaml\",\n#include \"yanlr\/map-null.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-plain_scalar.yaml\",\n#include \"yanlr\/map-plain_scalar.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-plain_scalars.yaml\",\n#include \"yanlr\/map-plain_scalars.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-list-plain_scalars.yaml\",\n#include \"yanlr\/map-list-plain_scalars.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-map-plain_scalars.yaml\",\n#include \"yanlr\/map-map-plain_scalars.hpp\"\n\t);\n}\n\n\/\/ -- Main ---------------------------------------------------------------------------------------------------------------------------------\n\nint main (int argc, char * argv[])\n{\n\tinit (argc, argv); \/\/ Required for `srcdir_file` to work properly\n\t::testing::InitGoogleTest (&argc, argv);\n\treturn RUN_ALL_TESTS ();\n}\nYan LR: Simplify unit tests macros\/**\n * @file\n *\n * @brief Tests for yanlr plugin\n *\n * @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n *\n *\/\n\n\/\/ -- Imports ------------------------------------------------------------------------------------------------------------------------------\n\n#include \"yanlr.hpp\"\n\n#include \n#include \n\n#include \n#include \n\nusing ckdb::keyNew;\n\nusing CppKeySet = kdb::KeySet;\nusing CppKey = kdb::Key;\n\n\/\/ -- Macros -------------------------------------------------------------------------------------------------------------------------------\n\n#define OPEN_PLUGIN(parentName, filepath) \\\n\tCppKeySet modules{ 0, KS_END }; \\\n\telektraModulesInit (modules.getKeySet (), 0); \\\n\tCppKeySet config{ 0, KS_END }; \\\n\tCppKey parent{ parentName, KEY_VALUE, filepath, KEY_END }; \\\n\tPlugin * plugin = elektraPluginOpen (\"yanlr\", modules.getKeySet (), config.getKeySet (), *parent);\n\n#define CLOSE_PLUGIN() \\\n\tconfig.release (); \\\n\telektraPluginClose (plugin, 0); \\\n\telektraModulesClose (modules.getKeySet (), 0)\n\n#define PREFIX \"user\/tests\/yanlr\/\"\n\n\/\/ -- Functions ---------------------------------------------------------------------------------------------------------------------------\n\nvoid test_read (string const & filepath, CppKeySet expected, int const status = ELEKTRA_PLUGIN_STATUS_SUCCESS)\n#ifdef __llvm__\n\t__attribute__ ((annotate (\"oclint:suppress[high ncss method]\"), annotate (\"oclint:suppress[empty if statement]\"),\n\t\t\tannotate (\"oclint:suppress[too few branches in switch statement]\")))\n#endif\n{\n\tOPEN_PLUGIN (PREFIX, srcdir_file (filepath.c_str ()));\n\n\t\/\/ We replace the value of the parent key of expected keyset, if the header file specifies the value @CONFIG_FILEPATH@.\n\t\/\/ We could also do that via CMake, but the current solution should be easier for now.\n\tCppKey root = expected.lookup (PREFIX, KDB_O_POP);\n\tif (root)\n\t{\n\t\tif (root.getString () == \"@CONFIG_FILEPATH@\") root.setString (srcdir_file (filepath.c_str ()));\n\t\texpected.append (root);\n\t}\n\n\tCppKeySet keys;\n\tsucceed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), status, \"Call of `kdbGet` failed\");\n\tcompare_keyset (expected, keys);\n\n\tCLOSE_PLUGIN ();\n}\n\n\/\/ -- Tests --------------------------------------------------------------------------------------------------------------------------------\n\nTEST (yanlr, basics)\n{\n\tOPEN_PLUGIN (\"system\/elektra\/modules\/yanlr\", \"file\/path\");\n\n\tCppKeySet keys;\n\tsucceed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,\n\t\t\t \"Could not retrieve plugin contract\");\n\n\tCLOSE_PLUGIN ();\n}\n\nTEST (yanlr, empty)\n{\n\ttest_read (\"yanlr\/null.yaml\",\n#include \"yanlr\/null.hpp\"\n\t\t , ELEKTRA_PLUGIN_STATUS_NO_UPDATE);\n\ttest_read (\"yanlr\/comment.yaml\",\n#include \"yanlr\/null.hpp\"\n\t\t , ELEKTRA_PLUGIN_STATUS_NO_UPDATE);\n}\n\nTEST (yanlr, scalar)\n{\n\ttest_read (\"yanlr\/plain_scalar-word_chars.yaml\",\n#include \"yanlr\/plain_scalar-word_chars.hpp\"\n\t);\n\ttest_read (\"yanlr\/plain_scalar-word_chars_space.yaml\",\n#include \"yanlr\/plain_scalar-word_chars_space.hpp\"\n\t);\n\ttest_read (\"yanlr\/single_quoted_scalar.yaml\",\n#include \"yanlr\/single_quoted_scalar.hpp\"\n\t);\n\ttest_read (\"yanlr\/double_quoted_scalar.yaml\",\n#include \"yanlr\/double_quoted_scalar.hpp\"\n\t);\n}\n\nTEST (yanlr, list)\n{\n\ttest_read (\"yanlr\/list-plain_scalars.yaml\",\n#include \"yanlr\/list-plain_scalars.hpp\"\n\t);\n\ttest_read (\"yanlr\/list-list_map-mixed_scalars.yaml\",\n#include \"yanlr\/list-list_map-mixed_scalars.hpp\"\n\t);\n}\n\nTEST (yanlr, map)\n{\n\ttest_read (\"yanlr\/map-null.yaml\",\n#include \"yanlr\/map-null.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-plain_scalar.yaml\",\n#include \"yanlr\/map-plain_scalar.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-plain_scalars.yaml\",\n#include \"yanlr\/map-plain_scalars.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-list-plain_scalars.yaml\",\n#include \"yanlr\/map-list-plain_scalars.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-map-plain_scalars.yaml\",\n#include \"yanlr\/map-map-plain_scalars.hpp\"\n\t);\n}\n\n\/\/ -- Main ---------------------------------------------------------------------------------------------------------------------------------\n\nint main (int argc, char * argv[])\n{\n\tinit (argc, argv); \/\/ Required for `srcdir_file` to work properly\n\t::testing::InitGoogleTest (&argc, argv);\n\treturn RUN_ALL_TESTS ();\n}\n<|endoftext|>"} {"text":"\/**\n * @file\n *\n * @brief Tests for yanlr plugin\n *\n * @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n *\n *\/\n\n\/\/ -- Imports ------------------------------------------------------------------------------------------------------------------------------\n\n#include \"yanlr.hpp\"\n\n#include \n#include \n\n#include \n#include \n\nusing ckdb::keyNew;\n\nusing CppKeySet = kdb::KeySet;\nusing CppKey = kdb::Key;\n\n\/\/ -- Macros -------------------------------------------------------------------------------------------------------------------------------\n\n#define OPEN_PLUGIN(parentName, filepath) \\\n\tCppKeySet modules{ 0, KS_END }; \\\n\telektraModulesInit (modules.getKeySet (), 0); \\\n\tCppKeySet config{ 0, KS_END }; \\\n\tCppKey parent{ parentName, KEY_VALUE, filepath, KEY_END }; \\\n\tPlugin * plugin = elektraPluginOpen (\"yanlr\", modules.getKeySet (), config.getKeySet (), *parent);\n\n#define CLOSE_PLUGIN() \\\n\tconfig.release (); \\\n\telektraPluginClose (plugin, 0); \\\n\telektraModulesClose (modules.getKeySet (), 0)\n\n#define PREFIX \"user:\/tests\/yanlr\/\"\n\n\/\/ -- Functions ---------------------------------------------------------------------------------------------------------------------------\n\nvoid test_read (string const & filepath, CppKeySet expected)\n#ifdef __llvm__\n\t__attribute__ ((annotate (\"oclint:suppress[high ncss method]\"), annotate (\"oclint:suppress[empty if statement]\"),\n\t\t\tannotate (\"oclint:suppress[too few branches in switch statement]\")))\n#endif\n{\n\tOPEN_PLUGIN (PREFIX, srcdir_file (filepath.c_str ()));\n\n\t\/\/ We replace the value of the parent key of expected keyset, if the header file specifies the value @CONFIG_FILEPATH@.\n\t\/\/ We could also do that via CMake, but the current solution should be easier for now.\n\tCppKey root = expected.lookup (PREFIX, KDB_O_POP);\n\tif (root)\n\t{\n\t\tif (root.getString () == \"@CONFIG_FILEPATH@\") root.setString (srcdir_file (filepath.c_str ()));\n\t\texpected.append (root);\n\t}\n\n\tCppKeySet keys;\n\tsucceed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS, \"Call of `kdbGet` failed\");\n\tcompare_keyset (expected, keys);\n\n\tCLOSE_PLUGIN ();\n}\n\n\/\/ -- Tests --------------------------------------------------------------------------------------------------------------------------------\n\nTEST (yanlr, basics)\n{\n\tOPEN_PLUGIN (\"system:\/elektra\/modules\/yanlr\", \"file\/path\");\n\n\tCppKeySet keys;\n\tsucceed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,\n\t\t\t \"Could not retrieve plugin contract\");\n\n\tCLOSE_PLUGIN ();\n}\n\nTEST (yanlr, empty)\n{\n\ttest_read (\"yanlr\/null.yaml\",\n#include \"yanlr\/null.hpp\"\n\t);\n\ttest_read (\"yanlr\/comment.yaml\",\n#include \"yanlr\/null.hpp\"\n\t);\n}\n\nTEST (yanlr, scalar)\n{\n\ttest_read (\"yanlr\/plain_scalar-word_chars.yaml\",\n#include \"yanlr\/plain_scalar-word_chars.hpp\"\n\t);\n\ttest_read (\"yanlr\/plain_scalar-word_chars_space.yaml\",\n#include \"yanlr\/plain_scalar-word_chars_space.hpp\"\n\t);\n\ttest_read (\"yanlr\/single_quoted_scalar.yaml\",\n#include \"yanlr\/single_quoted_scalar.hpp\"\n\t);\n\ttest_read (\"yanlr\/double_quoted_scalar.yaml\",\n#include \"yanlr\/double_quoted_scalar.hpp\"\n\t);\n}\n\nTEST (yanlr, list)\n{\n\ttest_read (\"yanlr\/list-plain_scalars.yaml\",\n#include \"yanlr\/list-plain_scalars.hpp\"\n\t);\n\ttest_read (\"yanlr\/list-list_map-mixed_scalars.yaml\",\n#include \"yanlr\/list-list_map-mixed_scalars.hpp\"\n\t);\n}\n\nTEST (yanlr, map)\n{\n\ttest_read (\"yanlr\/map-null.yaml\",\n#include \"yanlr\/map-null.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-plain_scalar.yaml\",\n#include \"yanlr\/map-plain_scalar.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-plain_scalars.yaml\",\n#include \"yanlr\/map-plain_scalars.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-list-plain_scalars.yaml\",\n#include \"yanlr\/map-list-plain_scalars.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-map-plain_scalars.yaml\",\n#include \"yanlr\/map-map-plain_scalars.hpp\"\n\t);\n}\n\n\/\/ -- Main ---------------------------------------------------------------------------------------------------------------------------------\n\nint main (int argc, char * argv[])\n{\n\tinit (argc, argv); \/\/ Required for `srcdir_file` to work properly\n\t::testing::InitGoogleTest (&argc, argv);\n\treturn RUN_ALL_TESTS ();\n}\nYan LR: Update suppressions for OCLint 20.11\/**\n * @file\n *\n * @brief Tests for yanlr plugin\n *\n * @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n *\n *\/\n\n\/\/ -- Imports ------------------------------------------------------------------------------------------------------------------------------\n\n#include \"yanlr.hpp\"\n\n#include \n#include \n\n#include \n#include \n\nusing ckdb::keyNew;\n\nusing CppKeySet = kdb::KeySet;\nusing CppKey = kdb::Key;\n\n\/\/ -- Macros -------------------------------------------------------------------------------------------------------------------------------\n\n#define OPEN_PLUGIN(parentName, filepath) \\\n\tCppKeySet modules{ 0, KS_END }; \\\n\telektraModulesInit (modules.getKeySet (), 0); \\\n\tCppKeySet config{ 0, KS_END }; \\\n\tCppKey parent{ parentName, KEY_VALUE, filepath, KEY_END }; \\\n\tPlugin * plugin = elektraPluginOpen (\"yanlr\", modules.getKeySet (), config.getKeySet (), *parent);\n\n#define CLOSE_PLUGIN() \\\n\tconfig.release (); \\\n\telektraPluginClose (plugin, 0); \\\n\telektraModulesClose (modules.getKeySet (), 0)\n\n#define PREFIX \"user:\/tests\/yanlr\/\"\n\n\/\/ -- Functions ---------------------------------------------------------------------------------------------------------------------------\n\nvoid test_read (string const & filepath, CppKeySet expected)\n#ifdef __llvm__\n\t__attribute__ ((annotate (\"oclint:suppress[high ncss method]\"), annotate (\"oclint:suppress[empty if statement]\"),\n\t\t\tannotate (\"oclint:suppress[too few branches in switch statement]\")))\n#endif\n{\n\tOPEN_PLUGIN (PREFIX, srcdir_file (filepath.c_str ()));\n\n\t\/\/ We replace the value of the parent key of expected keyset, if the header file specifies the value @CONFIG_FILEPATH@.\n\t\/\/ We could also do that via CMake, but the current solution should be easier for now.\n\tCppKey root = expected.lookup (PREFIX, KDB_O_POP);\n\tif (root)\n\t{\n\t\tif (root.getString () == \"@CONFIG_FILEPATH@\") root.setString (srcdir_file (filepath.c_str ()));\n\t\texpected.append (root);\n\t}\n\n\tCppKeySet keys;\n\tsucceed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS, \"Call of `kdbGet` failed\");\n\tcompare_keyset (expected, keys);\n\n\tCLOSE_PLUGIN ();\n}\n\n\/\/ -- Tests --------------------------------------------------------------------------------------------------------------------------------\n\nTEST (yanlr, basics) \/\/! OCLint (avoid private static members)\n#ifdef __llvm__\n__attribute__ ((annotate (\"oclint:suppress[empty if statement]\"), annotate (\"oclint:suppress[too few branches in switch statement]\")))\n#endif\n{\n\tOPEN_PLUGIN (\"system:\/elektra\/modules\/yanlr\", \"file\/path\");\n\n\tCppKeySet keys;\n\tsucceed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,\n\t\t\t \"Could not retrieve plugin contract\");\n\n\tCLOSE_PLUGIN ();\n}\n\nTEST (yanlr, empty) \/\/! OCLint (avoid private static members)\n{\n\ttest_read (\"yanlr\/null.yaml\",\n#include \"yanlr\/null.hpp\"\n\t);\n\ttest_read (\"yanlr\/comment.yaml\",\n#include \"yanlr\/null.hpp\"\n\t);\n}\n\nTEST (yanlr, scalar) \/\/! OCLint (avoid private static members)\n{\n\ttest_read (\"yanlr\/plain_scalar-word_chars.yaml\",\n#include \"yanlr\/plain_scalar-word_chars.hpp\"\n\t);\n\ttest_read (\"yanlr\/plain_scalar-word_chars_space.yaml\",\n#include \"yanlr\/plain_scalar-word_chars_space.hpp\"\n\t);\n\ttest_read (\"yanlr\/single_quoted_scalar.yaml\",\n#include \"yanlr\/single_quoted_scalar.hpp\"\n\t);\n\ttest_read (\"yanlr\/double_quoted_scalar.yaml\",\n#include \"yanlr\/double_quoted_scalar.hpp\"\n\t);\n}\n\nTEST (yanlr, list) \/\/! OCLint (avoid private static members)\n{\n\ttest_read (\"yanlr\/list-plain_scalars.yaml\",\n#include \"yanlr\/list-plain_scalars.hpp\"\n\t);\n\ttest_read (\"yanlr\/list-list_map-mixed_scalars.yaml\",\n#include \"yanlr\/list-list_map-mixed_scalars.hpp\"\n\t);\n}\n\nTEST (yanlr, map) \/\/! OCLint (avoid private static members)\n{\n\ttest_read (\"yanlr\/map-null.yaml\",\n#include \"yanlr\/map-null.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-plain_scalar.yaml\",\n#include \"yanlr\/map-plain_scalar.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-plain_scalars.yaml\",\n#include \"yanlr\/map-plain_scalars.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-list-plain_scalars.yaml\",\n#include \"yanlr\/map-list-plain_scalars.hpp\"\n\t);\n\ttest_read (\"yanlr\/map-map-plain_scalars.yaml\",\n#include \"yanlr\/map-map-plain_scalars.hpp\"\n\t);\n}\n\n\/\/ -- Main ---------------------------------------------------------------------------------------------------------------------------------\n\nint main (int argc, char * argv[])\n{\n\tinit (argc, argv); \/\/ Required for `srcdir_file` to work properly\n\t::testing::InitGoogleTest (&argc, argv);\n\treturn RUN_ALL_TESTS ();\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: shape_io.cc 26 2005-03-29 19:18:59Z pavlenko $\n\n#include \"shape_io.hpp\"\n#include \"shape.hpp\"\n#include \n\nusing mapnik::datasource_exception;\nusing mapnik::geometry_type;\n\nconst std::string shape_io::SHP = \".shp\";\nconst std::string shape_io::DBF = \".dbf\";\nconst std::string shape_io::INDEX = \".index\";\n\nshape_io::shape_io(const std::string& shape_name, bool open_index)\n : type_(shape_null),\n shp_(shape_name + SHP),\n dbf_(shape_name + DBF),\n reclength_(0),\n id_(0)\n{\n bool ok = (shp_.is_open() && dbf_.is_open());\n if (!ok)\n { \n throw datasource_exception(\"Shape Plugin: cannot read shape file '\" + shape_name + \"'\");\n }\n if (open_index)\n {\n try \n {\n \n if (!boost::filesystem::exists(shape_name + INDEX))\n {\n throw datasource_exception(\"Shape Plugin: could not open index: '\" + shape_name + INDEX + \"' does not exist\");\n }\n \n index_= boost::shared_ptr(new shape_file(shape_name + INDEX));\n }\n catch (...)\n {\n std::cerr << \"Shape Plugin: warning - could not open index: '\" + shape_name + INDEX + \"'\" << std::endl;\n }\n }\n}\n\nshape_io::~shape_io()\n{\n shp_.close();\n dbf_.close();\n if (index_) (*index_).close();\n}\n\nvoid shape_io::move_to (int pos)\n{\n shp_.seek(pos);\n id_ = shp_.read_xdr_integer();\n reclength_ = shp_.read_xdr_integer();\n type_ = shp_.read_ndr_integer();\n \n if (shp_.is_eof()) {\n id_ = 0;\n reclength_ = 0;\n type_ = shape_null;\n }\n\n if (type_!= shape_null && type_ != shape_point && type_ != shape_pointm && type_ != shape_pointz)\n {\n shp_.read_envelope(cur_extent_);\n }\n}\n\nint shape_io::type() const\n{\n return type_;\n}\n\nconst box2d& shape_io::current_extent() const\n{\n return cur_extent_;\n}\n\nshape_file& shape_io::shp()\n{\n return shp_;\n}\n\nshape_file& shape_io::shx()\n{\n return shx_;\n}\n\n\ndbf_file& shape_io::dbf()\n{\n return dbf_;\n}\n\ngeometry_type * shape_io::read_polyline()\n{ \n shape_file::record_type record(reclength_*2-36);\n shp_.read_record(record);\n int num_parts=record.read_ndr_integer();\n int num_points=record.read_ndr_integer();\n geometry_type * line = new geometry_type(mapnik::LineString);\n line->set_capacity(num_points + num_parts);\n if (num_parts == 1)\n {\n line->set_capacity(num_points + 1);\n record.skip(4);\n double x=record.read_double();\n double y=record.read_double();\n line->move_to(x,y);\n for (int i=1;iline_to(x,y);\n }\n }\n else\n {\n std::vector parts(num_parts);\n for (int i=0;imove_to(x,y);\n \n for (int j=start+1;jline_to(x,y);\n }\n }\n }\n return line;\n}\n\ngeometry_type * shape_io::read_polylinem()\n{ \n shape_file::record_type record(reclength_*2-36);\n shp_.read_record(record);\n int num_parts=record.read_ndr_integer();\n int num_points=record.read_ndr_integer();\n geometry_type * line = new geometry_type(mapnik::LineString);\n line->set_capacity(num_points + num_parts);\n if (num_parts == 1)\n {\n record.skip(4);\n double x=record.read_double();\n double y=record.read_double();\n line->move_to(x,y);\n for (int i=1;iline_to(x,y);\n }\n }\n else\n {\n std::vector parts(num_parts);\n for (int i=0;imove_to(x,y);\n\t \n for (int j=start+1;jline_to(x,y);\n }\n }\n }\n \/\/ m-range\n \/\/double m0=record.read_double();\n \/\/double m1=record.read_double();\n \n \/\/for (int i=0;iset_capacity(num_points + num_parts);\n if (num_parts == 1)\n {\n record.skip(4);\n double x=record.read_double();\n double y=record.read_double();\n line->move_to(x,y);\n for (int i=1;iline_to(x,y);\n }\n }\n else\n {\n std::vector parts(num_parts);\n for (int i=0;imove_to(x,y);\n \n for (int j=start+1;jline_to(x,y);\n }\n }\n }\n \/\/ z-range\n \/\/double z0=record.read_double();\n \/\/double z1=record.read_double();\n \/\/for (int i=0;i parts(num_parts);\n geometry_type * poly = new geometry_type(mapnik::Polygon);\n poly->set_capacity(num_points + num_parts);\n for (int i=0;imove_to(x,y);\n \n for (int j=start+1;jline_to(x,y);\n }\n }\n return poly;\n}\n\ngeometry_type * shape_io::read_polygonm()\n{\n shape_file::record_type record(reclength_*2-36);\n shp_.read_record(record);\n int num_parts=record.read_ndr_integer();\n int num_points=record.read_ndr_integer();\n std::vector parts(num_parts);\n geometry_type * poly = new geometry_type(mapnik::Polygon);\n poly->set_capacity(num_points + num_parts);\n for (int i=0;imove_to(x,y);\n \n for (int j=start+1;jline_to(x,y);\n }\n }\n \/\/ m-range\n \/\/double m0=record.read_double();\n \/\/double m1=record.read_double();\n \n \/\/for (int i=0;i parts(num_parts);\n geometry_type * poly=new geometry_type(mapnik::Polygon);\n poly->set_capacity(num_points + num_parts);\n for (int i=0;imove_to(x,y);\n \n for (int j=start+1;jline_to(x,y);\n }\n }\n \/\/ z-range\n \/\/double z0=record.read_double();\n \/\/double z1=record.read_double();\n \/\/for (int i=0;ionly warn about missing index file in debug mode\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: shape_io.cc 26 2005-03-29 19:18:59Z pavlenko $\n\n#include \"shape_io.hpp\"\n#include \"shape.hpp\"\n#include \n\nusing mapnik::datasource_exception;\nusing mapnik::geometry_type;\n\nconst std::string shape_io::SHP = \".shp\";\nconst std::string shape_io::DBF = \".dbf\";\nconst std::string shape_io::INDEX = \".index\";\n\nshape_io::shape_io(const std::string& shape_name, bool open_index)\n : type_(shape_null),\n shp_(shape_name + SHP),\n dbf_(shape_name + DBF),\n reclength_(0),\n id_(0)\n{\n bool ok = (shp_.is_open() && dbf_.is_open());\n if (!ok)\n { \n throw datasource_exception(\"Shape Plugin: cannot read shape file '\" + shape_name + \"'\");\n }\n if (open_index)\n {\n try \n {\n \n index_= boost::shared_ptr(new shape_file(shape_name + INDEX));\n }\n catch (...)\n {\n#ifdef MAPNIK_DEBUG \n std::clog << \"Shape Plugin: warning - could not open index: '\" + shape_name + INDEX + \"'\" << std::endl;\n#endif\n }\n }\n}\n\nshape_io::~shape_io()\n{\n shp_.close();\n dbf_.close();\n if (index_) (*index_).close();\n}\n\nvoid shape_io::move_to (int pos)\n{\n shp_.seek(pos);\n id_ = shp_.read_xdr_integer();\n reclength_ = shp_.read_xdr_integer();\n type_ = shp_.read_ndr_integer();\n \n if (shp_.is_eof()) {\n id_ = 0;\n reclength_ = 0;\n type_ = shape_null;\n }\n\n if (type_!= shape_null && type_ != shape_point && type_ != shape_pointm && type_ != shape_pointz)\n {\n shp_.read_envelope(cur_extent_);\n }\n}\n\nint shape_io::type() const\n{\n return type_;\n}\n\nconst box2d& shape_io::current_extent() const\n{\n return cur_extent_;\n}\n\nshape_file& shape_io::shp()\n{\n return shp_;\n}\n\nshape_file& shape_io::shx()\n{\n return shx_;\n}\n\n\ndbf_file& shape_io::dbf()\n{\n return dbf_;\n}\n\ngeometry_type * shape_io::read_polyline()\n{ \n shape_file::record_type record(reclength_*2-36);\n shp_.read_record(record);\n int num_parts=record.read_ndr_integer();\n int num_points=record.read_ndr_integer();\n geometry_type * line = new geometry_type(mapnik::LineString);\n line->set_capacity(num_points + num_parts);\n if (num_parts == 1)\n {\n line->set_capacity(num_points + 1);\n record.skip(4);\n double x=record.read_double();\n double y=record.read_double();\n line->move_to(x,y);\n for (int i=1;iline_to(x,y);\n }\n }\n else\n {\n std::vector parts(num_parts);\n for (int i=0;imove_to(x,y);\n \n for (int j=start+1;jline_to(x,y);\n }\n }\n }\n return line;\n}\n\ngeometry_type * shape_io::read_polylinem()\n{ \n shape_file::record_type record(reclength_*2-36);\n shp_.read_record(record);\n int num_parts=record.read_ndr_integer();\n int num_points=record.read_ndr_integer();\n geometry_type * line = new geometry_type(mapnik::LineString);\n line->set_capacity(num_points + num_parts);\n if (num_parts == 1)\n {\n record.skip(4);\n double x=record.read_double();\n double y=record.read_double();\n line->move_to(x,y);\n for (int i=1;iline_to(x,y);\n }\n }\n else\n {\n std::vector parts(num_parts);\n for (int i=0;imove_to(x,y);\n\t \n for (int j=start+1;jline_to(x,y);\n }\n }\n }\n \/\/ m-range\n \/\/double m0=record.read_double();\n \/\/double m1=record.read_double();\n \n \/\/for (int i=0;iset_capacity(num_points + num_parts);\n if (num_parts == 1)\n {\n record.skip(4);\n double x=record.read_double();\n double y=record.read_double();\n line->move_to(x,y);\n for (int i=1;iline_to(x,y);\n }\n }\n else\n {\n std::vector parts(num_parts);\n for (int i=0;imove_to(x,y);\n \n for (int j=start+1;jline_to(x,y);\n }\n }\n }\n \/\/ z-range\n \/\/double z0=record.read_double();\n \/\/double z1=record.read_double();\n \/\/for (int i=0;i parts(num_parts);\n geometry_type * poly = new geometry_type(mapnik::Polygon);\n poly->set_capacity(num_points + num_parts);\n for (int i=0;imove_to(x,y);\n \n for (int j=start+1;jline_to(x,y);\n }\n }\n return poly;\n}\n\ngeometry_type * shape_io::read_polygonm()\n{\n shape_file::record_type record(reclength_*2-36);\n shp_.read_record(record);\n int num_parts=record.read_ndr_integer();\n int num_points=record.read_ndr_integer();\n std::vector parts(num_parts);\n geometry_type * poly = new geometry_type(mapnik::Polygon);\n poly->set_capacity(num_points + num_parts);\n for (int i=0;imove_to(x,y);\n \n for (int j=start+1;jline_to(x,y);\n }\n }\n \/\/ m-range\n \/\/double m0=record.read_double();\n \/\/double m1=record.read_double();\n \n \/\/for (int i=0;i parts(num_parts);\n geometry_type * poly=new geometry_type(mapnik::Polygon);\n poly->set_capacity(num_points + num_parts);\n for (int i=0;imove_to(x,y);\n \n for (int j=start+1;jline_to(x,y);\n }\n }\n \/\/ z-range\n \/\/double z0=record.read_double();\n \/\/double z1=record.read_double();\n \/\/for (int i=0;i"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2015 Mark Charlebois. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file vdev_posix.cpp\n *\n * POSIX-like API for virtual character device\n *\/\n\n#include \n#include \n#include \n#include \"device.h\"\n#include \"vfile.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace device;\n\nextern \"C\" {\n\nstatic void timer_cb(void *data)\n{\n\tsem_t *p_sem = (sem_t *)data;\n\tsem_post(p_sem);\n\tPX4_DEBUG(\"timer_handler: Timer expired\");\n}\n\n#define PX4_MAX_FD 200\nstatic device::file_t *filemap[PX4_MAX_FD] = {};\n\nint px4_errno;\n\ninline bool valid_fd(int fd)\n{\n\treturn (fd < PX4_MAX_FD && fd >= 0 && filemap[fd] != NULL);\n}\n\nint px4_open(const char *path, int flags, ...)\n{\n\tPX4_DEBUG(\"px4_open\");\n\tVDev *dev = VDev::getDev(path);\n\tint ret = 0;\n\tint i;\n\tmode_t mode;\n\n\tif (!dev && (flags & (PX4_F_WRONLY|PX4_F_CREAT)) != 0 &&\n\t\tstrncmp(path, \"\/obj\/\", 5) != 0 &&\n\t\tstrncmp(path, \"\/dev\/\", 5) != 0) \n\t{\n\t\tva_list p;\n\t\tva_start(p, flags);\n \t\tmode = va_arg(p, mode_t);\n\t\tva_end(p);\n\n\t\t\/\/ Create the file\n\t\tPX4_DEBUG(\"Creating virtual file %s\", path);\n\t\tdev = VFile::createFile(path, mode);\n\t}\n\tif (dev) {\n\t\tfor (i=0; iopen(filemap[i]);\n\t\t}\n\t\telse {\n\t\t\tPX4_WARN(\"exceeded maximum number of file descriptors!\");\n\t\t\tret = -ENOENT;\n\t\t}\n\t}\n\telse {\n\t\tret = -EINVAL;\n\t}\n\tif (ret < 0) {\n\t\tpx4_errno = -ret;\n\t\treturn -1;\n\t}\n\tPX4_DEBUG(\"px4_open fd = %d\", filemap[i]->fd);\n\treturn filemap[i]->fd;\n}\n\nint px4_close(int fd)\n{\n\tint ret;\n\tif (valid_fd(fd)) {\n\t\tVDev *dev = (VDev *)(filemap[fd]->vdev);\n\t\tPX4_DEBUG(\"px4_close fd = %d\", fd);\n\t\tret = dev->close(filemap[fd]);\n\t\tfilemap[fd] = NULL;\n\t}\n\telse { \n ret = -EINVAL;\n }\n\tif (ret < 0) {\n\t\tpx4_errno = -ret;\n\t\tret = PX4_ERROR;\n\t}\n\treturn ret;\n}\n\nssize_t px4_read(int fd, void *buffer, size_t buflen)\n{\n\tint ret;\n\tif (valid_fd(fd)) {\n\t\tVDev *dev = (VDev *)(filemap[fd]->vdev);\n\t\tPX4_DEBUG(\"px4_read fd = %d\", fd);\n\t\tret = dev->read(filemap[fd], (char *)buffer, buflen);\n\t}\n\telse { \n ret = -EINVAL;\n }\n\tif (ret < 0) {\n\t\tpx4_errno = -ret;\n\t\tret = PX4_ERROR;\n\t}\n\treturn ret;\n}\n\nssize_t px4_write(int fd, const void *buffer, size_t buflen)\n{\n\tint ret;\n if (valid_fd(fd)) {\n\t\tVDev *dev = (VDev *)(filemap[fd]->vdev);\n\t\tPX4_DEBUG(\"px4_write fd = %d\", fd);\n\t\tret = dev->write(filemap[fd], (const char *)buffer, buflen);\n\t}\n\telse { \n ret = -EINVAL;\n }\n\tif (ret < 0) {\n\t\tpx4_errno = -ret;\n\t\tret = PX4_ERROR;\n\t}\n return ret;\n}\n\nint px4_ioctl(int fd, int cmd, unsigned long arg)\n{\n\tPX4_DEBUG(\"px4_ioctl fd = %d\", fd);\n\tint ret = 0;\n if (valid_fd(fd)) {\n\t\tVDev *dev = (VDev *)(filemap[fd]->vdev);\n\t\tret = dev->ioctl(filemap[fd], cmd, arg);\n\t}\n\telse { \n ret = -EINVAL;\n }\n\tif (ret < 0) {\n\t\tpx4_errno = -ret;\n\t}\n\t\n return ret;\n}\n\nint px4_poll(px4_pollfd_struct_t *fds, nfds_t nfds, int timeout)\n{\n\tsem_t sem;\n\tint count = 0;\n\tint ret;\n\tunsigned int i;\n\n\tPX4_DEBUG(\"Called px4_poll timeout = %d\", timeout);\n\tsem_init(&sem, 0, 0);\n\n\t\/\/ For each fd \n\tfor (i=0; ivdev);;\n\t\t\tPX4_DEBUG(\"px4_poll: VDev->poll(setup) %d\", fds[i].fd);\n\t\t\tret = dev->poll(filemap[fds[i].fd], &fds[i], true);\n\n\t\t\tif (ret < 0)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (ret >= 0)\n\t{\n\t\tif (timeout >= 0)\n\t\t{\n\t\t\t\/\/ Use a work queue task\n\t\t\twork_s _hpwork;\n\n\t\t\thrt_work_queue(&_hpwork, (worker_t)&timer_cb, (void *)&sem, 1000*timeout);\n\t\t\tsem_wait(&sem);\n\n\t\t\t\/\/ Make sure timer thread is killed before sem goes\n\t\t\t\/\/ out of scope\n\t\t\thrt_work_cancel(&_hpwork);\n \t}\n\t\telse\n\t\t{\n\t\t\tsem_wait(&sem);\n\t\t}\n\n\t\t\/\/ For each fd \n\t\tfor (i=0; ivdev);;\n\t\t\t\tPX4_DEBUG(\"px4_poll: VDev->poll(teardown) %d\", fds[i].fd);\n\t\t\t\tret = dev->poll(filemap[fds[i].fd], &fds[i], false);\n\t\n\t\t\t\tif (ret < 0)\n\t\t\t\t\tbreak;\n\n\t\t\t\tif (fds[i].revents)\n\t\t\t\tcount += 1;\n\t\t\t}\n\t\t}\n\t}\n\n\tsem_destroy(&sem);\n\n\treturn count;\n}\n\nint px4_fsync(int fd)\n{\n\treturn 0;\n}\n\nint px4_access(const char *pathname, int mode)\n{\n\tif (mode == F_OK) {\n\t\terrno = EINVAL;\n\t\treturn -1;\n\t}\n\tVDev *dev = VDev::getDev(pathname);\n\treturn (dev != nullptr) ? 0 : -1;\n}\n\nvoid px4_show_devices()\n{\n\tVDev::showDevices();\n}\n\nvoid px4_show_topics()\n{\n\tVDev::showTopics();\n}\n\nvoid px4_show_files()\n{\n\tVDev::showFiles();\n}\n\nconst char * px4_get_device_names(unsigned int *handle)\n{\n\treturn VDev::devList(handle);\n}\n\nconst char * px4_get_topic_names(unsigned int *handle)\n{\n\treturn VDev::topicList(handle);\n}\n\n}\n\nfix logic in posix access function\/****************************************************************************\n *\n * Copyright (c) 2015 Mark Charlebois. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file vdev_posix.cpp\n *\n * POSIX-like API for virtual character device\n *\/\n\n#include \n#include \n#include \n#include \"device.h\"\n#include \"vfile.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace device;\n\nextern \"C\" {\n\nstatic void timer_cb(void *data)\n{\n\tsem_t *p_sem = (sem_t *)data;\n\tsem_post(p_sem);\n\tPX4_DEBUG(\"timer_handler: Timer expired\");\n}\n\n#define PX4_MAX_FD 200\nstatic device::file_t *filemap[PX4_MAX_FD] = {};\n\nint px4_errno;\n\ninline bool valid_fd(int fd)\n{\n\treturn (fd < PX4_MAX_FD && fd >= 0 && filemap[fd] != NULL);\n}\n\nint px4_open(const char *path, int flags, ...)\n{\n\tPX4_DEBUG(\"px4_open\");\n\tVDev *dev = VDev::getDev(path);\n\tint ret = 0;\n\tint i;\n\tmode_t mode;\n\n\tif (!dev && (flags & (PX4_F_WRONLY|PX4_F_CREAT)) != 0 &&\n\t\tstrncmp(path, \"\/obj\/\", 5) != 0 &&\n\t\tstrncmp(path, \"\/dev\/\", 5) != 0) \n\t{\n\t\tva_list p;\n\t\tva_start(p, flags);\n \t\tmode = va_arg(p, mode_t);\n\t\tva_end(p);\n\n\t\t\/\/ Create the file\n\t\tPX4_DEBUG(\"Creating virtual file %s\", path);\n\t\tdev = VFile::createFile(path, mode);\n\t}\n\tif (dev) {\n\t\tfor (i=0; iopen(filemap[i]);\n\t\t}\n\t\telse {\n\t\t\tPX4_WARN(\"exceeded maximum number of file descriptors!\");\n\t\t\tret = -ENOENT;\n\t\t}\n\t}\n\telse {\n\t\tret = -EINVAL;\n\t}\n\tif (ret < 0) {\n\t\tpx4_errno = -ret;\n\t\treturn -1;\n\t}\n\tPX4_DEBUG(\"px4_open fd = %d\", filemap[i]->fd);\n\treturn filemap[i]->fd;\n}\n\nint px4_close(int fd)\n{\n\tint ret;\n\tif (valid_fd(fd)) {\n\t\tVDev *dev = (VDev *)(filemap[fd]->vdev);\n\t\tPX4_DEBUG(\"px4_close fd = %d\", fd);\n\t\tret = dev->close(filemap[fd]);\n\t\tfilemap[fd] = NULL;\n\t}\n\telse { \n ret = -EINVAL;\n }\n\tif (ret < 0) {\n\t\tpx4_errno = -ret;\n\t\tret = PX4_ERROR;\n\t}\n\treturn ret;\n}\n\nssize_t px4_read(int fd, void *buffer, size_t buflen)\n{\n\tint ret;\n\tif (valid_fd(fd)) {\n\t\tVDev *dev = (VDev *)(filemap[fd]->vdev);\n\t\tPX4_DEBUG(\"px4_read fd = %d\", fd);\n\t\tret = dev->read(filemap[fd], (char *)buffer, buflen);\n\t}\n\telse { \n ret = -EINVAL;\n }\n\tif (ret < 0) {\n\t\tpx4_errno = -ret;\n\t\tret = PX4_ERROR;\n\t}\n\treturn ret;\n}\n\nssize_t px4_write(int fd, const void *buffer, size_t buflen)\n{\n\tint ret;\n if (valid_fd(fd)) {\n\t\tVDev *dev = (VDev *)(filemap[fd]->vdev);\n\t\tPX4_DEBUG(\"px4_write fd = %d\", fd);\n\t\tret = dev->write(filemap[fd], (const char *)buffer, buflen);\n\t}\n\telse { \n ret = -EINVAL;\n }\n\tif (ret < 0) {\n\t\tpx4_errno = -ret;\n\t\tret = PX4_ERROR;\n\t}\n return ret;\n}\n\nint px4_ioctl(int fd, int cmd, unsigned long arg)\n{\n\tPX4_DEBUG(\"px4_ioctl fd = %d\", fd);\n\tint ret = 0;\n if (valid_fd(fd)) {\n\t\tVDev *dev = (VDev *)(filemap[fd]->vdev);\n\t\tret = dev->ioctl(filemap[fd], cmd, arg);\n\t}\n\telse { \n ret = -EINVAL;\n }\n\tif (ret < 0) {\n\t\tpx4_errno = -ret;\n\t}\n\t\n return ret;\n}\n\nint px4_poll(px4_pollfd_struct_t *fds, nfds_t nfds, int timeout)\n{\n\tsem_t sem;\n\tint count = 0;\n\tint ret;\n\tunsigned int i;\n\n\tPX4_DEBUG(\"Called px4_poll timeout = %d\", timeout);\n\tsem_init(&sem, 0, 0);\n\n\t\/\/ For each fd \n\tfor (i=0; ivdev);;\n\t\t\tPX4_DEBUG(\"px4_poll: VDev->poll(setup) %d\", fds[i].fd);\n\t\t\tret = dev->poll(filemap[fds[i].fd], &fds[i], true);\n\n\t\t\tif (ret < 0)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (ret >= 0)\n\t{\n\t\tif (timeout >= 0)\n\t\t{\n\t\t\t\/\/ Use a work queue task\n\t\t\twork_s _hpwork;\n\n\t\t\thrt_work_queue(&_hpwork, (worker_t)&timer_cb, (void *)&sem, 1000*timeout);\n\t\t\tsem_wait(&sem);\n\n\t\t\t\/\/ Make sure timer thread is killed before sem goes\n\t\t\t\/\/ out of scope\n\t\t\thrt_work_cancel(&_hpwork);\n \t}\n\t\telse\n\t\t{\n\t\t\tsem_wait(&sem);\n\t\t}\n\n\t\t\/\/ For each fd \n\t\tfor (i=0; ivdev);;\n\t\t\t\tPX4_DEBUG(\"px4_poll: VDev->poll(teardown) %d\", fds[i].fd);\n\t\t\t\tret = dev->poll(filemap[fds[i].fd], &fds[i], false);\n\t\n\t\t\t\tif (ret < 0)\n\t\t\t\t\tbreak;\n\n\t\t\t\tif (fds[i].revents)\n\t\t\t\tcount += 1;\n\t\t\t}\n\t\t}\n\t}\n\n\tsem_destroy(&sem);\n\n\treturn count;\n}\n\nint px4_fsync(int fd)\n{\n\treturn 0;\n}\n\nint px4_access(const char *pathname, int mode)\n{\n\tif (mode != F_OK) {\n\t\terrno = EINVAL;\n\t\treturn -1;\n\t}\n\tVDev *dev = VDev::getDev(pathname);\n\treturn (dev != nullptr) ? 0 : -1;\n}\n\nvoid px4_show_devices()\n{\n\tVDev::showDevices();\n}\n\nvoid px4_show_topics()\n{\n\tVDev::showTopics();\n}\n\nvoid px4_show_files()\n{\n\tVDev::showFiles();\n}\n\nconst char * px4_get_device_names(unsigned int *handle)\n{\n\treturn VDev::devList(handle);\n}\n\nconst char * px4_get_topic_names(unsigned int *handle)\n{\n\treturn VDev::topicList(handle);\n}\n\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"gen-cpp\/DataHub.h\"\n#include \n#include \n#include \n\n\/**\n * Sample DataHub C++ Client\n *\n * @author anantb\n * @author stephentu\n * @date 11\/07\/2013\n *\n *\/\n\nusing namespace std;\nusing namespace boost;\nusing namespace apache::thrift;\nusing namespace apache::thrift::protocol;\nusing namespace apache::thrift::transport;\n\nusing namespace datahub;\n\nint main () {\n try {\n shared_ptr transport(new THttpClient(\"datahub.csail.mit.edu\", 80, \"\/service\"));\n shared_ptr protocol(new TBinaryProtocol(transport));\n DataHubClient client(protocol);\n\n transport->open();\n double version = client.get_version();\n cout << version << endl;\n\n ConnectionParams params = ConnectionParams();\n params.__set_user(\"anantb\");\n params.__set_password(\"anant\");\n\n Connection conn;\n client.open_connection(conn, params);\n\n ResultSet res;\n client.execute_sql(\n res, conn, \"select * from anantb.test.demo\", vector());\n for(\n const auto* tuple_it = res.tuples.begin();\n tuple_it != res.tuples.end();\n ++tuple_it) {\n for(\n const auto* cell_it = (*tuple_it).cells.begin();\n cell_it != (*tuple_it).cells.end(); \n ++cell_it) {\n std::cout << *cell_it << \"\\t\";\n }\n std::cout << std::endl;\n }\n\n transport->close();\n } catch (TException &tx) {\n cout << \"ERROR: \" << tx.what();\n }\n\n return 0;\n}\ncpp sample#include \n#include \n#include \n\n#include \"gen-cpp\/DataHub.h\"\n#include \n#include \n#include \n\n\/**\n * Sample DataHub C++ Client\n *\n * @author anantb\n * @author stephentu\n * @date 11\/07\/2013\n *\n *\/\n\nusing namespace std;\nusing namespace boost;\nusing namespace apache::thrift;\nusing namespace apache::thrift::protocol;\nusing namespace apache::thrift::transport;\n\nusing namespace datahub;\n\nint main () {\n try {\n shared_ptr transport(new THttpClient(\"datahub.csail.mit.edu\", 80, \"\/service\"));\n shared_ptr protocol(new TBinaryProtocol(transport));\n DataHubClient client(protocol);\n\n transport->open();\n double version = client.get_version();\n cout << version << endl;\n\n ConnectionParams params = ConnectionParams();\n params.__set_user(\"anantb\");\n params.__set_password(\"anant\");\n\n Connection conn;\n client.open_connection(conn, params);\n\n ResultSet res;\n client.execute_sql(\n res, conn, \"select * from anantb.test.demo\", vector());\n for(vector::const_iterator tuple_it = res.tuples.begin();\n tuple_it != res.tuples.end();\n ++tuple_it) {\n for(vector::const_iterator cell_it = (*tuple_it).cells.begin();\n cell_it != (*tuple_it).cells.end(); \n ++cell_it) {\n cout << *cell_it << \"\\t\";\n }\n cout << std::endl;\n }\n\n transport->close();\n } catch (TException &tx) {\n cout << \"ERROR: \" << tx.what();\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/* -*- C++ -*- *\/\n\/*************************************************************************\n * Copyright(c) 1995~2005 Masaharu Goto (cint@pcroot.cern.ch)\n *\n * For the licensing terms see the file COPYING\n *\n ************************************************************************\/\n\n#if defined(interp) && defined(makecint)\n#pragma include \"test.dll\"\n#else\n#include \"t980.h\"\n#endif\n#include \n\nint main(int,char**) {\n A b ;\n b = A(\"A part\") + \" of a whole\";\n A a = A(\"A part\") + \" of a whole\";\n printf(\"%s. %s.\\n\",a.val(),b.val());\n\n f(a,\"A part of a whole\");\n f(\"A part of a whole\",a);\n\n if(strcmp(a,\"A part of a whole\")==0) printf(\"true\\n\");\n else printf(\"false\\n\");\n if(strcmp(a,\"a part of a whole\")==0) printf(\"true\\n\");\n else printf(\"false\\n\");\n\n if(strcmp(a.val(),\"A part of a whole\")==0) printf(\"true\\n\");\n else printf(\"false\\n\");\n if(strcmp(a.val(),\"a part of a whole\")==0) printf(\"true\\n\");\n else printf(\"false\\n\");\n return 0;\n}\n\nFix so it compiles with gcc 4.3.1 (missing includes).\/* -*- C++ -*- *\/\n\/*************************************************************************\n * Copyright(c) 1995~2005 Masaharu Goto (cint@pcroot.cern.ch)\n *\n * For the licensing terms see the file COPYING\n *\n ************************************************************************\/\n\n#if defined(interp) && defined(makecint)\n#pragma include \"test.dll\"\n#else\n#include \"t980.h\"\n#endif\n\n#include \n#include \n\nusing namespace std;\n\nint main(int, char**)\n{\n A b;\n b = A(\"A part\") + \" of a whole\";\n A a = A(\"A part\") + \" of a whole\";\n printf(\"%s. %s.\\n\", a.val(), b.val());\n\n f(a, \"A part of a whole\");\n f(\"A part of a whole\", a);\n\n if (!strcmp(a, \"A part of a whole\")) {\n printf(\"true\\n\");\n }\n else {\n printf(\"false\\n\");\n }\n if (!strcmp(a, \"a part of a whole\")) {\n printf(\"true\\n\");\n }\n else {\n printf(\"false\\n\");\n }\n\n if (!strcmp(a.val(), \"A part of a whole\")) {\n printf(\"true\\n\");\n }\n else {\n printf(\"false\\n\");\n }\n if (!strcmp(a.val(), \"a part of a whole\")) {\n printf(\"true\\n\");\n }\n else {\n printf(\"false\\n\");\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \"Call.h\"\n#include \"Argument.h\"\n#include \"compiler.h\"\n#include \"helper.h\"\n#include \n#include \n#include \n\nCall::Call(std::string code){\n\tstd::size_t p = code.find('(');\n\tfunction_ = code.substr(0, p);\n\tcode = code.substr(p + 1, code.length() - p - 2);\n\n\tstd::stringstream currentArgument;\n\tbool isString = false;\n\tbool isChar = false;\n\tbool isEscaped = false;\n\tstd::stack keller;\n\n\tfor (size_t i = 0; i < code.length(); i++) {\n\t\tchar c = code[i];\n\t\tif (!isString && !isChar){\n\t\t\tswitch (c) {\n\t\t\tcase '(':\n\t\t\tcase '{':\n\t\t\t\tkeller.push(c);\n\t\t\t\tcurrentArgument << c;\n\t\t\t\tbreak;\n\t\t\tcase ')':\n\t\t\t\tif (keller.empty() || pop(keller) != '(')\n\t\t\t\t\tthrow;\n\t\t\t\tcurrentArgument << c;\n\t\t\t\tbreak;\n\t\t\tcase '}':\n\t\t\t\tif (keller.empty() || pop(keller) != '{')\n\t\t\t\t\tthrow;\n\t\t\t\tcurrentArgument << c;\n\t\t\t\tbreak;\n\t\t\tcase ';':\n\t\t\t\tif (!keller.empty()) {\n\t\t\t\t\tcurrentArgument << c;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase '\"':\n\t\t\t\tisString = true;\n\t\t\t\tcurrentArgument << c;\n\t\t\t\tbreak;\n\t\t\tcase '\\'':\n\t\t\t\tisChar = true;\n\t\t\t\tcurrentArgument << c;\n\t\t\t\tbreak;\n\t\t\tcase ' ':\n\t\t\t\tbreak;\n\t\t\tcase ',':\n\t\t\t\tif (keller.size() > 0){ \/\/if it isn't a comma that separates parameters of this call\n\t\t\t\t\tcurrentArgument << c;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tcurrentArgument << c;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (!isEscaped){\n\t\t\t\tif (c == '\"') {\n\t\t\t\t\tisString = false;\n\t\t\t\t}\n\t\t\t\telse if (c == '\\'') {\n\t\t\t\t\tisChar = false;\n\t\t\t\t}\n\t\t\t\telse if (c == '\\\\') {\n\t\t\t\t\tisEscaped = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tisEscaped = false;\n\t\t\t}\n\t\t\tcurrentArgument << c;\n\t\t}\n\n\t\tif (keller.empty() && !isString && !isChar && (i == code.length() - 1 || code[i + 1] == ',')) {\n\t\t\targuments_.emplace_back(parseArgument(currentArgument.str()));\n\n\t\t\t\/\/this clears the stringstream\n\t\t\tcurrentArgument.str(std::string());\n\t\t\tcurrentArgument.clear();\n\t\t}\n\t}\n\n\tif (!keller.empty()) {\n\t\tthrow;\n\t}\n}\n\nType Call::getType() const {\n\treturn CALL;\n}\n\nCallSignature Call::signature() const {\n\tstd::vector params;\n\tfor (auto &a : arguments_) {\n\t\tparams.push_back(a->getType());\n\t}\n\tCallSignature r;\n\tr.first = getFunction();\n\tr.second = params;\n\treturn r;\n}\n\nbool Call::matches(CallSignature sig) const {\n\tif (arguments_.size() != sig.second.size() || sig.first != function_) \/\/TODO: Make case-insensitive check here?\n\t\treturn false;\n\t\/\/assert: lengths are now equal\n\tstd::vector::iterator itr = sig.second.begin();\n\tfor (auto& i : arguments_) {\n\t\tif (i->getType() != *itr\n\t\t\t&& !(isEvaluatable(*itr) && isEvaluatable(i->getType()))\n\t\t\t&& !(isCallable(*itr) && isCallable(i->getType()))\n\t\t\t)\n\t\t\treturn false;\n\t\titr++;\n\t}\n\treturn true;\n}\n\nstd::string Call::getFunction() const {\n\treturn function_;\n}\n\nunsigned int Call::evaluate(Compiler& compiler) const {\n unsigned int target = compiler.bf().allocCell();\n\tevaluate(compiler, target);\n\treturn target;\n}\n\nvoid Call::evaluate(Compiler& compiler, unsigned int target) const {\n MfFunction stmt = compiler.getFunction(*this);\n\tif (stmt != nullptr)\n\t\tstmt(compiler, *this, target);\n}\n\nvoid Call::compile(Compiler& cmp) const {\n\tMfProcedure stmt = cmp.getProcedure(*this);\n\tif (stmt != nullptr)\n\t\tstmt(cmp, *this);\n\telse\n\t\tcmp.warning(this, \"Unknown procedure: \" + function_);\n}\nAdded warning for unknown functions.#include \"Call.h\"\n#include \"Argument.h\"\n#include \"compiler.h\"\n#include \"helper.h\"\n#include \n#include \n#include \n\nCall::Call(std::string code){\n\tstd::size_t p = code.find('(');\n\tfunction_ = code.substr(0, p);\n\tcode = code.substr(p + 1, code.length() - p - 2);\n\n\tstd::stringstream currentArgument;\n\tbool isString = false;\n\tbool isChar = false;\n\tbool isEscaped = false;\n\tstd::stack keller;\n\n\tfor (size_t i = 0; i < code.length(); i++) {\n\t\tchar c = code[i];\n\t\tif (!isString && !isChar){\n\t\t\tswitch (c) {\n\t\t\tcase '(':\n\t\t\tcase '{':\n\t\t\t\tkeller.push(c);\n\t\t\t\tcurrentArgument << c;\n\t\t\t\tbreak;\n\t\t\tcase ')':\n\t\t\t\tif (keller.empty() || pop(keller) != '(')\n\t\t\t\t\tthrow;\n\t\t\t\tcurrentArgument << c;\n\t\t\t\tbreak;\n\t\t\tcase '}':\n\t\t\t\tif (keller.empty() || pop(keller) != '{')\n\t\t\t\t\tthrow;\n\t\t\t\tcurrentArgument << c;\n\t\t\t\tbreak;\n\t\t\tcase ';':\n\t\t\t\tif (!keller.empty()) {\n\t\t\t\t\tcurrentArgument << c;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase '\"':\n\t\t\t\tisString = true;\n\t\t\t\tcurrentArgument << c;\n\t\t\t\tbreak;\n\t\t\tcase '\\'':\n\t\t\t\tisChar = true;\n\t\t\t\tcurrentArgument << c;\n\t\t\t\tbreak;\n\t\t\tcase ' ':\n\t\t\t\tbreak;\n\t\t\tcase ',':\n\t\t\t\tif (keller.size() > 0){ \/\/if it isn't a comma that separates parameters of this call\n\t\t\t\t\tcurrentArgument << c;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tcurrentArgument << c;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (!isEscaped){\n\t\t\t\tif (c == '\"') {\n\t\t\t\t\tisString = false;\n\t\t\t\t}\n\t\t\t\telse if (c == '\\'') {\n\t\t\t\t\tisChar = false;\n\t\t\t\t}\n\t\t\t\telse if (c == '\\\\') {\n\t\t\t\t\tisEscaped = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tisEscaped = false;\n\t\t\t}\n\t\t\tcurrentArgument << c;\n\t\t}\n\n\t\tif (keller.empty() && !isString && !isChar && (i == code.length() - 1 || code[i + 1] == ',')) {\n\t\t\targuments_.emplace_back(parseArgument(currentArgument.str()));\n\n\t\t\t\/\/this clears the stringstream\n\t\t\tcurrentArgument.str(std::string());\n\t\t\tcurrentArgument.clear();\n\t\t}\n\t}\n\n\tif (!keller.empty()) {\n\t\tthrow;\n\t}\n}\n\nType Call::getType() const {\n\treturn CALL;\n}\n\nCallSignature Call::signature() const {\n\tstd::vector params;\n\tfor (auto &a : arguments_) {\n\t\tparams.push_back(a->getType());\n\t}\n\tCallSignature r;\n\tr.first = getFunction();\n\tr.second = params;\n\treturn r;\n}\n\nbool Call::matches(CallSignature sig) const {\n\tif (arguments_.size() != sig.second.size() || sig.first != function_) \/\/TODO: Make case-insensitive check here?\n\t\treturn false;\n\t\/\/assert: lengths are now equal\n\tstd::vector::iterator itr = sig.second.begin();\n\tfor (auto& i : arguments_) {\n\t\tif (i->getType() != *itr\n\t\t\t&& !(isEvaluatable(*itr) && isEvaluatable(i->getType()))\n\t\t\t&& !(isCallable(*itr) && isCallable(i->getType()))\n\t\t\t)\n\t\t\treturn false;\n\t\titr++;\n\t}\n\treturn true;\n}\n\nstd::string Call::getFunction() const {\n\treturn function_;\n}\n\nunsigned int Call::evaluate(Compiler& compiler) const {\n unsigned int target = compiler.bf().allocCell();\n\tevaluate(compiler, target);\n\treturn target;\n}\n\nvoid Call::evaluate(Compiler& cmp, unsigned int target) const {\n MfFunction stmt = cmp.getFunction(*this);\n\tif (stmt != nullptr)\n\t\tstmt(cmp, *this, target);\n\telse\n\t\tcmp.warning(this, \"Unknown function: \" + function_);\n}\n\nvoid Call::compile(Compiler& cmp) const {\n\tMfProcedure stmt = cmp.getProcedure(*this);\n\tif (stmt != nullptr)\n\t\tstmt(cmp, *this);\n\telse\n\t\tcmp.warning(this, \"Unknown procedure: \" + function_);\n}\n<|endoftext|>"} {"text":"Fix static initialization ordering bug that caused crashes at startup when compiling on Mac with static linking.<|endoftext|>"} {"text":"\/**************************************************************************\n *\n * Copyright 2012 Jose Fonseca\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n **************************************************************************\/\n\n\n#include \n#include \/\/ for CHAR_MAX\n#include \n\n#include \"pickle.hpp\"\n\n#include \"os_binary.hpp\"\n\n#include \"cli.hpp\"\n#include \"cli_pager.hpp\"\n\n#include \"trace_parser.hpp\"\n#include \"trace_model.hpp\"\n#include \"trace_callset.hpp\"\n\n\nusing namespace trace;\n\n\nclass PickleVisitor : public trace::Visitor\n{\nprotected:\n PickleWriter &writer;\n bool symbolic;\n\npublic:\n PickleVisitor(PickleWriter &_writer, bool _symbolic) :\n writer(_writer),\n symbolic(_symbolic) {\n }\n\n void visit(Null *node) override {\n writer.writeInt(0);\n }\n\n void visit(Bool *node) override {\n writer.writeBool(node->value);\n }\n\n void visit(SInt *node) override {\n writer.writeInt(node->value);\n }\n\n void visit(UInt *node) override {\n writer.writeInt(node->value);\n }\n\n void visit(Float *node) override {\n writer.writeFloat(node->value);\n }\n\n void visit(Double *node) override {\n writer.writeFloat(node->value);\n }\n\n void visit(String *node) override {\n writer.writeString(node->value);\n }\n\n void visit(WString *node) override {\n writer.writeWString(node->value);\n }\n\n void visit(Enum *node) override {\n if (symbolic) {\n const EnumValue *it = node->lookup();\n if (it) {\n writer.writeString(it->name);\n return;\n }\n }\n writer.writeInt(node->value);\n }\n\n void visit(Bitmask *node) override {\n if (symbolic) {\n unsigned long long value = node->value;\n const BitmaskSig *sig = node->sig;\n writer.beginTuple();\n for (const BitmaskFlag *it = sig->flags; it != sig->flags + sig->num_flags; ++it) {\n if ((it->value && (value & it->value) == it->value) ||\n (!it->value && value == 0)) {\n writer.writeString(it->name);\n value &= ~it->value;\n }\n if (value == 0) {\n break;\n }\n }\n if (value) {\n writer.writeInt(value);\n }\n writer.endTuple();\n } else {\n writer.writeInt(node->value);\n }\n }\n\n void visit(Struct *node) override {\n if (true) {\n \/\/ Structures as dictionaries\n writer.beginDict();\n for (unsigned i = 0; i < node->sig->num_members; ++i) {\n writer.beginItem(node->sig->member_names[i]);\n _visit(node->members[i]);\n writer.endItem();\n }\n writer.endDict();\n } else {\n \/\/ Structures as tuples\n unsigned num_members = node->sig->num_members;\n writer.beginTuple(num_members);\n for (unsigned i = 0; i < num_members; ++i) {\n _visit(node->members[i]);\n }\n writer.endTuple(num_members);\n }\n }\n\n void visit(Array *node) override {\n writer.beginList();\n for (auto & value : node->values) {\n _visit(value);\n }\n writer.endList();\n }\n\n void visit(Blob *node) override {\n writer.writeBytes(node->buf, node->size);\n }\n\n void visit(Pointer *node) override {\n writer.writePointer(node->value);\n }\n\n void visit(Repr *r) override {\n if (symbolic) {\n _visit(r->humanValue);\n } else {\n _visit(r->machineValue);\n }\n }\n\n void visit(Call *call) {\n writer.beginTuple();\n\n writer.writeInt(call->no);\n\n writer.writeString(call->name());\n\n writer.beginList();\n for (unsigned i = 0; i < call->args.size(); ++i) {\n writer.beginTuple(2);\n if (i < call->sig->num_args) {\n writer.writeString(call->sig->arg_names[i]);\n } else {\n writer.writeNone();\n }\n if (call->args[i].value) {\n _visit(call->args[i].value);\n } else {\n writer.writeNone();\n }\n writer.endTuple(2);\n }\n writer.endList();\n\n if (call->ret) {\n _visit(call->ret);\n } else {\n writer.writeNone();\n }\n\n writer.writeInt(call->flags);\n\n writer.endTuple();\n }\n};\n\n\nstatic trace::CallSet calls(trace::FREQUENCY_ALL);\n\nstatic const char *synopsis = \"Pickle given trace(s) to standard output.\";\n\nstatic void\nusage(void)\n{\n std::cout\n << \"usage: apitrace pickle [OPTIONS] TRACE_FILE...\\n\"\n << synopsis << \"\\n\"\n \"\\n\"\n \" -h, --help show this help message and exit\\n\"\n \" -s, --symbolic dump symbolic names\\n\"\n \" --calls=CALLSET only dump specified calls\\n\"\n ;\n}\n\nenum {\n\tCALLS_OPT = CHAR_MAX + 1,\n};\n\nconst static char *\nshortOptions = \"hs\";\n\nconst static struct option\nlongOptions[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"symbolic\", no_argument, 0, 's'},\n {\"calls\", required_argument, 0, CALLS_OPT},\n {0, 0, 0, 0}\n};\n\nstatic int\ncommand(int argc, char *argv[])\n{\n bool symbolic = false;\n\n int opt;\n while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {\n switch (opt) {\n case 'h':\n usage();\n return 0;\n case 's':\n symbolic = true;\n break;\n case CALLS_OPT:\n calls.merge(optarg);\n break;\n default:\n std::cerr << \"error: unexpected option `\" << (char)opt << \"`\\n\";\n usage();\n return 1;\n }\n }\n\n os::setBinaryMode(stdout);\n \n std::cout.sync_with_stdio(false);\n\n PickleWriter writer(std::cout);\n PickleVisitor visitor(writer, symbolic);\n\n for (int i = optind; i < argc; ++i) {\n trace::Parser parser;\n\n if (!parser.open(argv[i])) {\n return 1;\n }\n\n trace::Call *call;\n while ((call = parser.parse_call())) {\n if (calls.contains(*call)) {\n writer.begin();\n visitor.visit(call);\n writer.end();\n }\n delete call;\n }\n }\n\n return 0;\n}\n\nconst Command pickle_command = {\n \"pickle\",\n synopsis,\n usage,\n command\n};\ncli: Terminate pickling early when possible.\/**************************************************************************\n *\n * Copyright 2012 Jose Fonseca\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n **************************************************************************\/\n\n\n#include \n#include \/\/ for CHAR_MAX\n#include \n\n#include \"pickle.hpp\"\n\n#include \"os_binary.hpp\"\n\n#include \"cli.hpp\"\n#include \"cli_pager.hpp\"\n\n#include \"trace_parser.hpp\"\n#include \"trace_model.hpp\"\n#include \"trace_callset.hpp\"\n\n\nusing namespace trace;\n\n\nclass PickleVisitor : public trace::Visitor\n{\nprotected:\n PickleWriter &writer;\n bool symbolic;\n\npublic:\n PickleVisitor(PickleWriter &_writer, bool _symbolic) :\n writer(_writer),\n symbolic(_symbolic) {\n }\n\n void visit(Null *node) override {\n writer.writeInt(0);\n }\n\n void visit(Bool *node) override {\n writer.writeBool(node->value);\n }\n\n void visit(SInt *node) override {\n writer.writeInt(node->value);\n }\n\n void visit(UInt *node) override {\n writer.writeInt(node->value);\n }\n\n void visit(Float *node) override {\n writer.writeFloat(node->value);\n }\n\n void visit(Double *node) override {\n writer.writeFloat(node->value);\n }\n\n void visit(String *node) override {\n writer.writeString(node->value);\n }\n\n void visit(WString *node) override {\n writer.writeWString(node->value);\n }\n\n void visit(Enum *node) override {\n if (symbolic) {\n const EnumValue *it = node->lookup();\n if (it) {\n writer.writeString(it->name);\n return;\n }\n }\n writer.writeInt(node->value);\n }\n\n void visit(Bitmask *node) override {\n if (symbolic) {\n unsigned long long value = node->value;\n const BitmaskSig *sig = node->sig;\n writer.beginTuple();\n for (const BitmaskFlag *it = sig->flags; it != sig->flags + sig->num_flags; ++it) {\n if ((it->value && (value & it->value) == it->value) ||\n (!it->value && value == 0)) {\n writer.writeString(it->name);\n value &= ~it->value;\n }\n if (value == 0) {\n break;\n }\n }\n if (value) {\n writer.writeInt(value);\n }\n writer.endTuple();\n } else {\n writer.writeInt(node->value);\n }\n }\n\n void visit(Struct *node) override {\n if (true) {\n \/\/ Structures as dictionaries\n writer.beginDict();\n for (unsigned i = 0; i < node->sig->num_members; ++i) {\n writer.beginItem(node->sig->member_names[i]);\n _visit(node->members[i]);\n writer.endItem();\n }\n writer.endDict();\n } else {\n \/\/ Structures as tuples\n unsigned num_members = node->sig->num_members;\n writer.beginTuple(num_members);\n for (unsigned i = 0; i < num_members; ++i) {\n _visit(node->members[i]);\n }\n writer.endTuple(num_members);\n }\n }\n\n void visit(Array *node) override {\n writer.beginList();\n for (auto & value : node->values) {\n _visit(value);\n }\n writer.endList();\n }\n\n void visit(Blob *node) override {\n writer.writeBytes(node->buf, node->size);\n }\n\n void visit(Pointer *node) override {\n writer.writePointer(node->value);\n }\n\n void visit(Repr *r) override {\n if (symbolic) {\n _visit(r->humanValue);\n } else {\n _visit(r->machineValue);\n }\n }\n\n void visit(Call *call) {\n writer.beginTuple();\n\n writer.writeInt(call->no);\n\n writer.writeString(call->name());\n\n writer.beginList();\n for (unsigned i = 0; i < call->args.size(); ++i) {\n writer.beginTuple(2);\n if (i < call->sig->num_args) {\n writer.writeString(call->sig->arg_names[i]);\n } else {\n writer.writeNone();\n }\n if (call->args[i].value) {\n _visit(call->args[i].value);\n } else {\n writer.writeNone();\n }\n writer.endTuple(2);\n }\n writer.endList();\n\n if (call->ret) {\n _visit(call->ret);\n } else {\n writer.writeNone();\n }\n\n writer.writeInt(call->flags);\n\n writer.endTuple();\n }\n};\n\n\nstatic trace::CallSet calls(trace::FREQUENCY_ALL);\n\nstatic const char *synopsis = \"Pickle given trace(s) to standard output.\";\n\nstatic void\nusage(void)\n{\n std::cout\n << \"usage: apitrace pickle [OPTIONS] TRACE_FILE...\\n\"\n << synopsis << \"\\n\"\n \"\\n\"\n \" -h, --help show this help message and exit\\n\"\n \" -s, --symbolic dump symbolic names\\n\"\n \" --calls=CALLSET only dump specified calls\\n\"\n ;\n}\n\nenum {\n\tCALLS_OPT = CHAR_MAX + 1,\n};\n\nconst static char *\nshortOptions = \"hs\";\n\nconst static struct option\nlongOptions[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"symbolic\", no_argument, 0, 's'},\n {\"calls\", required_argument, 0, CALLS_OPT},\n {0, 0, 0, 0}\n};\n\nstatic int\ncommand(int argc, char *argv[])\n{\n bool symbolic = false;\n\n int opt;\n while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {\n switch (opt) {\n case 'h':\n usage();\n return 0;\n case 's':\n symbolic = true;\n break;\n case CALLS_OPT:\n calls.merge(optarg);\n break;\n default:\n std::cerr << \"error: unexpected option `\" << (char)opt << \"`\\n\";\n usage();\n return 1;\n }\n }\n\n os::setBinaryMode(stdout);\n \n std::cout.sync_with_stdio(false);\n\n PickleWriter writer(std::cout);\n PickleVisitor visitor(writer, symbolic);\n\n for (int i = optind; i < argc; ++i) {\n trace::Parser parser;\n\n if (!parser.open(argv[i])) {\n return 1;\n }\n\n trace::Call *call;\n while ((call = parser.parse_call())) {\n if (call->no > calls.getLast()) {\n delete call;\n break;\n }\n if (calls.contains(*call)) {\n writer.begin();\n visitor.visit(call);\n writer.end();\n }\n delete call;\n }\n }\n\n return 0;\n}\n\nconst Command pickle_command = {\n \"pickle\",\n synopsis,\n usage,\n command\n};\n<|endoftext|>"} {"text":"\n\/\/ QT includes\n#include \n#include \n\n\/\/ getoptPlusPLus includes\n#include \n\n#include \"protoserver\/ProtoConnectionWrapper.h\"\n#include \"X11Wrapper.h\"\n#include \"HyperionConfig.h\"\n#include \"utils\/Profiler.h\"\n\nusing namespace vlofgren;\n\n\/\/ save the image as screenshot\nvoid saveScreenshot(const char * filename, const Image & image)\n{\n\t\/\/ store as PNG\n\tQImage pngImage((const uint8_t *) image.memptr(), image.width(), image.height(), 3*image.width(), QImage::Format_RGB888);\n\tpngImage.save(filename);\n}\n\nint main(int argc, char ** argv)\n{\n\t std::cout\n\t\t<< \"hyperion-x11:\" << std::endl\n\t\t<< \"\\tversion : \" << HYPERION_VERSION_ID << std::endl\n\t\t<< \"\\tbuild time: \" << __DATE__ << \" \" << __TIME__ << std::endl;\n\n\tQCoreApplication app(argc, argv);\n\n\ttry\n\t{\n\t\t\/\/ create the option parser and initialize all parameters\n\t\tOptionsParser optionParser(\"X11 capture application for Hyperion\");\n\t\tParameterSet & parameters = optionParser.getParameters();\n\n\t\tIntParameter & argFps = parameters.add ('f', \"framerate\", \"Capture frame rate [default: 10]\");\n\t\tSwitchParameter<> & argXGetImage = parameters.add> ('x', \"xgetimage\", \"Use XGetImage instead of XRender\");\n\t\tIntParameter & argCropWidth = parameters.add (0x0, \"crop-width\", \"Number of pixels to crop from the left and right sides of the picture before decimation [default: 0]\");\n\t\tIntParameter & argCropHeight = parameters.add (0x0, \"crop-height\", \"Number of pixels to crop from the top and the bottom of the picture before decimation [default: 0]\");\n\t\tIntParameter & argCropLeft = parameters.add (0x0, \"crop-left\", \"Number of pixels to crop from the left of the picture before decimation (overrides --crop-width)\");\n\t\tIntParameter & argCropRight = parameters.add (0x0, \"crop-right\", \"Number of pixels to crop from the right of the picture before decimation (overrides --crop-width)\");\n\t\tIntParameter & argCropTop = parameters.add (0x0, \"crop-top\", \"Number of pixels to crop from the top of the picture before decimation (overrides --crop-height)\");\n\t\tIntParameter & argCropBottom = parameters.add (0x0, \"crop-bottom\", \"Number of pixels to crop from the bottom of the picture before decimation (overrides --crop-height)\");\n\t\tIntParameter & argSizeDecimation = parameters.add ('s', \"size-decimator\", \"Decimation factor for the output size [default=8]\");\n\t\tSwitchParameter<> & argScreenshot = parameters.add> (0x0, \"screenshot\", \"Take a single screenshot, save it to file and quit\");\n\t\tStringParameter & argAddress = parameters.add ('a', \"address\", \"Set the address of the hyperion server [default: 127.0.0.1:19445]\");\n\t\tIntParameter & argPriority = parameters.add ('p', \"priority\", \"Use the provided priority channel (the lower the number, the higher the priority) [default: 800]\");\n\t\tSwitchParameter<> & argSkipReply = parameters.add> (0x0, \"skip-reply\", \"Do not receive and check reply messages from Hyperion\");\n\t\tSwitchParameter<> & argHelp = parameters.add> ('h', \"help\", \"Show this help message and exit\");\n\n\t\t\/\/ set defaults\n\t\targFps.setDefault(10);\n\t\targCropWidth.setDefault(0);\n\t\targCropHeight.setDefault(0);\n\t\targSizeDecimation.setDefault(8);\n\t\targAddress.setDefault(\"127.0.0.1:19445\");\n\t\targPriority.setDefault(800);\n\n\t\t\/\/ parse all options\n\t\toptionParser.parse(argc, const_cast(argv));\n\n\t\t\/\/ check if we need to display the usage. exit if we do.\n\t\tif (argHelp.isSet())\n\t\t{\n\t\t\toptionParser.usage();\n\t\t\treturn 0;\n\t\t}\n\n\t\t\/\/ cropping values if not defined\n\t\tif (!argCropLeft.isSet()) argCropLeft.setDefault(argCropWidth.getValue());\n\t\tif (!argCropRight.isSet()) argCropRight.setDefault(argCropWidth.getValue());\n\t\tif (!argCropTop.isSet())\targCropTop.setDefault(argCropHeight.getValue());\n\t\tif (!argCropBottom.isSet()) argCropBottom.setDefault(argCropHeight.getValue());\n\n\t\t\/\/ Create the X11 grabbing stuff\n\t\tint grabInterval = 1000 \/ argFps.getValue();\n\t\tbool useXGetImage = argXGetImage.isSet();\n\t\tX11Wrapper x11Wrapper(\n\t\t\t\t\tgrabInterval,\n\t\t\t\t\tuseXGetImage,\n\t\t\t\t\targCropLeft.getValue(),\n\t\t\t\t\targCropRight.getValue(),\n\t\t\t\t\targCropTop.getValue(),\n\t\t\t\t\targCropBottom.getValue(),\n\t\t\t\t\targSizeDecimation.getValue(), \/\/ horizontal decimation\n\t\t\t\t\targSizeDecimation.getValue()); \/\/ vertical decimation\n\t\n\tif (!x11Wrapper.displayInit())\n\t return -1;\n\n\t\tif (argScreenshot.isSet())\n\t\t{\n\t\t\t\/\/ Capture a single screenshot and finish\n\t\t\tconst Image & screenshot = x11Wrapper.getScreenshot();\n\t\t\tsaveScreenshot(\"screenshot.png\", screenshot);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Create the Proto-connection with hyperiond\n\t\t\tProtoConnectionWrapper protoWrapper(argAddress.getValue(), argPriority.getValue(), 1000, argSkipReply.isSet());\n\n\t\t\t\/\/ Connect the screen capturing to the proto processing\n\t\t\tQObject::connect(&x11Wrapper, SIGNAL(sig_screenshot(const Image &)), &protoWrapper, SLOT(receiveImage(Image)));\n\t\t\t\n\t\t\t\/\/ Connect the XBMC Video Checker to the proto processing\n\t\t\tQObject::connect(&protoWrapper, SIGNAL(setGrabbingMode(GrabbingMode)), &x11Wrapper, SLOT(setGrabbingMode(GrabbingMode)));\n\t\t\tQObject::connect(&protoWrapper, SIGNAL(setVideoMode(VideoMode)), &x11Wrapper, SLOT(setVideoMode(VideoMode)));\n\n\t\t\t\/\/ Start the capturing\n\t\t\tx11Wrapper.start();\n\n\t\t\t\/\/ Start the application\n\t\t\tapp.exec();\n\t\t}\n\t}\n\tcatch (const std::runtime_error & e)\n\t{\n\t\t\/\/ An error occured. Display error and quit\n\t\tstd::cerr << e.what() << std::endl;\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\nrm profiler at x11\n\/\/ QT includes\n#include \n#include \n\n\/\/ getoptPlusPLus includes\n#include \n\n#include \"protoserver\/ProtoConnectionWrapper.h\"\n#include \"X11Wrapper.h\"\n#include \"HyperionConfig.h\"\n\nusing namespace vlofgren;\n\n\/\/ save the image as screenshot\nvoid saveScreenshot(const char * filename, const Image & image)\n{\n\t\/\/ store as PNG\n\tQImage pngImage((const uint8_t *) image.memptr(), image.width(), image.height(), 3*image.width(), QImage::Format_RGB888);\n\tpngImage.save(filename);\n}\n\nint main(int argc, char ** argv)\n{\n\t std::cout\n\t\t<< \"hyperion-x11:\" << std::endl\n\t\t<< \"\\tversion : \" << HYPERION_VERSION_ID << std::endl\n\t\t<< \"\\tbuild time: \" << __DATE__ << \" \" << __TIME__ << std::endl;\n\n\tQCoreApplication app(argc, argv);\n\n\ttry\n\t{\n\t\t\/\/ create the option parser and initialize all parameters\n\t\tOptionsParser optionParser(\"X11 capture application for Hyperion\");\n\t\tParameterSet & parameters = optionParser.getParameters();\n\n\t\tIntParameter & argFps = parameters.add ('f', \"framerate\", \"Capture frame rate [default: 10]\");\n\t\tSwitchParameter<> & argXGetImage = parameters.add> ('x', \"xgetimage\", \"Use XGetImage instead of XRender\");\n\t\tIntParameter & argCropWidth = parameters.add (0x0, \"crop-width\", \"Number of pixels to crop from the left and right sides of the picture before decimation [default: 0]\");\n\t\tIntParameter & argCropHeight = parameters.add (0x0, \"crop-height\", \"Number of pixels to crop from the top and the bottom of the picture before decimation [default: 0]\");\n\t\tIntParameter & argCropLeft = parameters.add (0x0, \"crop-left\", \"Number of pixels to crop from the left of the picture before decimation (overrides --crop-width)\");\n\t\tIntParameter & argCropRight = parameters.add (0x0, \"crop-right\", \"Number of pixels to crop from the right of the picture before decimation (overrides --crop-width)\");\n\t\tIntParameter & argCropTop = parameters.add (0x0, \"crop-top\", \"Number of pixels to crop from the top of the picture before decimation (overrides --crop-height)\");\n\t\tIntParameter & argCropBottom = parameters.add (0x0, \"crop-bottom\", \"Number of pixels to crop from the bottom of the picture before decimation (overrides --crop-height)\");\n\t\tIntParameter & argSizeDecimation = parameters.add ('s', \"size-decimator\", \"Decimation factor for the output size [default=8]\");\n\t\tSwitchParameter<> & argScreenshot = parameters.add> (0x0, \"screenshot\", \"Take a single screenshot, save it to file and quit\");\n\t\tStringParameter & argAddress = parameters.add ('a', \"address\", \"Set the address of the hyperion server [default: 127.0.0.1:19445]\");\n\t\tIntParameter & argPriority = parameters.add ('p', \"priority\", \"Use the provided priority channel (the lower the number, the higher the priority) [default: 800]\");\n\t\tSwitchParameter<> & argSkipReply = parameters.add> (0x0, \"skip-reply\", \"Do not receive and check reply messages from Hyperion\");\n\t\tSwitchParameter<> & argHelp = parameters.add> ('h', \"help\", \"Show this help message and exit\");\n\n\t\t\/\/ set defaults\n\t\targFps.setDefault(10);\n\t\targCropWidth.setDefault(0);\n\t\targCropHeight.setDefault(0);\n\t\targSizeDecimation.setDefault(8);\n\t\targAddress.setDefault(\"127.0.0.1:19445\");\n\t\targPriority.setDefault(800);\n\n\t\t\/\/ parse all options\n\t\toptionParser.parse(argc, const_cast(argv));\n\n\t\t\/\/ check if we need to display the usage. exit if we do.\n\t\tif (argHelp.isSet())\n\t\t{\n\t\t\toptionParser.usage();\n\t\t\treturn 0;\n\t\t}\n\n\t\t\/\/ cropping values if not defined\n\t\tif (!argCropLeft.isSet()) argCropLeft.setDefault(argCropWidth.getValue());\n\t\tif (!argCropRight.isSet()) argCropRight.setDefault(argCropWidth.getValue());\n\t\tif (!argCropTop.isSet())\targCropTop.setDefault(argCropHeight.getValue());\n\t\tif (!argCropBottom.isSet()) argCropBottom.setDefault(argCropHeight.getValue());\n\n\t\t\/\/ Create the X11 grabbing stuff\n\t\tint grabInterval = 1000 \/ argFps.getValue();\n\t\tbool useXGetImage = argXGetImage.isSet();\n\t\tX11Wrapper x11Wrapper(\n\t\t\t\t\tgrabInterval,\n\t\t\t\t\tuseXGetImage,\n\t\t\t\t\targCropLeft.getValue(),\n\t\t\t\t\targCropRight.getValue(),\n\t\t\t\t\targCropTop.getValue(),\n\t\t\t\t\targCropBottom.getValue(),\n\t\t\t\t\targSizeDecimation.getValue(), \/\/ horizontal decimation\n\t\t\t\t\targSizeDecimation.getValue()); \/\/ vertical decimation\n\t\n\tif (!x11Wrapper.displayInit())\n\t return -1;\n\n\t\tif (argScreenshot.isSet())\n\t\t{\n\t\t\t\/\/ Capture a single screenshot and finish\n\t\t\tconst Image & screenshot = x11Wrapper.getScreenshot();\n\t\t\tsaveScreenshot(\"screenshot.png\", screenshot);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Create the Proto-connection with hyperiond\n\t\t\tProtoConnectionWrapper protoWrapper(argAddress.getValue(), argPriority.getValue(), 1000, argSkipReply.isSet());\n\n\t\t\t\/\/ Connect the screen capturing to the proto processing\n\t\t\tQObject::connect(&x11Wrapper, SIGNAL(sig_screenshot(const Image &)), &protoWrapper, SLOT(receiveImage(Image)));\n\t\t\t\n\t\t\t\/\/ Connect the XBMC Video Checker to the proto processing\n\t\t\tQObject::connect(&protoWrapper, SIGNAL(setGrabbingMode(GrabbingMode)), &x11Wrapper, SLOT(setGrabbingMode(GrabbingMode)));\n\t\t\tQObject::connect(&protoWrapper, SIGNAL(setVideoMode(VideoMode)), &x11Wrapper, SLOT(setVideoMode(VideoMode)));\n\n\t\t\t\/\/ Start the capturing\n\t\t\tx11Wrapper.start();\n\n\t\t\t\/\/ Start the application\n\t\t\tapp.exec();\n\t\t}\n\t}\n\tcatch (const std::runtime_error & e)\n\t{\n\t\t\/\/ An error occured. Display error and quit\n\t\tstd::cerr << e.what() << std::endl;\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Card lookup values\nconst std::string number_lookup[] = { \"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\" };\nconst std::string suit_lookup[] = {\"D\", \"C\", \"H\", \"S\"};\nconst int face_value[] = { 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};\n\n\/\/ Test case constants\nconst int test_case_number[] = {1, 1, 2, 6, 4, 8, 9, 1, 3, 2, 3, 10};\nconst int test_case_suit[] = {0, 2, 1, 0, 1, 0, 2, 1, 0, 3, 2, 0};\nbool test_case = false;\nint test_case_int = 0;\n\nclass Card {\npublic:\n int number;\n int suit;\n\n Card() {\n if (test_case) {\n number = test_case_number[test_case_int];\n suit = test_case_suit[test_case_int];\n test_case_int++;\n }\n else {\n number = (double) rand()\/RAND_MAX*13;\n suit = (double) rand()\/RAND_MAX*4;\n }\n }\n \n Card(int n, int s) {\n number = n;\n suit = s;\n }\n\n std::string getString() {\n std::string s;\n s = number_lookup[number];\n s.append(suit_lookup[suit]);\n return s;\n }\n \n int getValue() {\n return face_value[number];\n }\n};\n\nclass Player {\npublic:\n std::vector hand;\n int hand_count;\n\n Player() {\n hand_count = 0;\n }\n\n int getScore() {\n int score = 0;\n int hasAce = 0;\n for (std::vector::iterator it = hand.begin() ; it != hand.end(); ++it) {\n if (it->number == 0) {\n\thasAce++;\n }\n score += it->getValue();\n }\n\n while (hasAce && score > 21) {\n hasAce--;\n score -= 10;\n }\n return score;\n }\n\n std::string getHand(bool ignoreFirst) {\n std::string s = \"\";\n for (std::vector::iterator it = hand.begin() ; it != hand.end(); ++it) {\n if (!ignoreFirst) {\n\ts.append(it->getString());\n\ts.append(\" \");\n }\n ignoreFirst = false;\n }\n return s;\n }\n\n void drawCard() {\n Card card;\n hand.push_back(card);\n hand_count++;\n }\n\n bool isSplit() {\n std::vector::iterator it = hand.begin();\n int i = it->number;\n it++;\n return (i == it->number);\n }\n};\n\n\nclass Game {\npublic: \n int player_bet;\n int player_cash;\n\n Game() {\n player_cash = 100;\n }\n\n void newGame() {\n Player player, dealer;\n char ch;\n\n player_bet = 0; \/\/ Reset player bet to known value\n\n std::cout << \"Player: $\" << player_cash << \"\\nRound bet: \"; \/\/ Get player bet amount and deduct it\n std::cin >> player_bet;\n\n while (player_cash < player_bet || player_bet == 0) { \/\/ Ensure valid bet amount\n std::cin.clear(); \/\/ Fix looping error with invalid input\n std::cin.ignore(std::numeric_limits::max(), '\\n'); \/\/ Clear read buffer\n std::cout << \"Invalid bet. Round bet: \";\n std::cin >> player_bet;\n }\n\n player_cash -= player_bet;\n\n \/*\n std::cout << \"Test case? (y\/n): \";\n while (true) {\n std::cin >> ch;\n ch = tolower(ch);\n\n if (ch == 'y') {\n\ttest_case = true;\n\tbreak;\n }\n else if (ch == 'n') {\n\tbreak;\n }\n }\n *\/\n\n player.drawCard(); \/\/ Draw cards for player and dealer\n player.drawCard();\n dealer.drawCard();\n dealer.drawCard();\n \n playRound(player, dealer);\n }\n \n void playRound(Player player, Player dealer) {\n char ch;\n \n if (player.getScore() >= 21 || player.hand_count >= 5) { \/\/ End game if player gets 21 or over\n endGame(player, dealer);\n return;\n }\n\n std::cout << \"Dealer : * \" << dealer.getHand(true) << \"\\nPlayer : \" << player.getHand(false) << \"\\nDraw? (y\/n) \";\n\n while (true) {\n std::cin >> ch;\n ch = tolower(ch);\n\n if (ch == 'y') {\n\tplayer.drawCard();\n\tplayRound(player, dealer);\n\tbreak;\n }\n else if (ch == 'n') {\n\tendGame(player, dealer);\n\tbreak;\n }\n }\n }\n\n void endGame(Player player, Player dealer) {\n while (dealer.getScore() < 17 && dealer.hand_count < 5) {\n dealer.drawCard();\n }\n \n std::cout << \"Dealer : \" << dealer.getHand(false) << \"\\nPlayer : \" << player.getHand(false) \/\/ Display hands\n\t << \"\\nDealer: \" << dealer.getScore() << \"\\tPlayer: \" << player.getScore() << \"\\n\"; \/\/ Display points\n \n switch (checkWin(player, dealer)) {\n case 0:\n\tstd::cout << \"Dealer wins!\\n\";\n\tbreak;\n case 1:\n\tstd::cout << \"Tie game!\\n\";\n\tplayer_cash += player_bet;\n\tbreak;\n case 2:\n\tstd::cout << \"Player Wins!\\n\";\n\tif (player.getScore() == 21) {\n\t player_cash += player_bet*2.5;\n\t}\n\telse {\n\t player_cash += player_bet*2;\n\t}\n\tbreak;\n }\n }\n \n int checkWin(Player player, Player dealer) { \/\/ 0 = loss, 1 = tie, 2 = win\n if (player.getScore() > 21) {\n return 0;\n }\n else if (dealer.getScore() > 21) {\n return 2;\n }\n else if (dealer.getScore() == player.getScore()) {\n return 1;\n }\n else if (dealer.getScore() > player.getScore()) {\n return 0;\n }\n else {\n return 2;\n }\n }\n};\n\nint main() {\n Game game;\n char ch;\n\n srand(time(0)); \/\/ initialize random number generator\n\n game.newGame(); \/\/ start new game\n \n while (true) { \/\/ Wait for valid input\n if (game.player_cash <= 0) { \/\/ Make sure the player has cash to continue playing\n std::cout << \"Sorry, You have no more money left.\\n\";\n break;\n }\n std::cout << \"Again? (y\/n): \";\n std::cin >> ch;\n ch = tolower(ch);\n if (ch == 'y') {\n game.newGame(); \/\/ Start new game\n }\n else if (ch == 'n') {\n break; \/\/ Exit loop\n }\n }\n return 0;\n}\nAdded splitting code; need to implement split draw#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Card lookup values\nconst std::string number_lookup[] = { \"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\" };\nconst std::string suit_lookup[] = {\"D\", \"C\", \"H\", \"S\"};\nconst int face_value[] = { 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};\n\n\/\/ Test case constants\nconst int test_case_number[] = {1, 1, 2, 6, 4, 8, 9, 1, 3, 2, 3, 10};\nconst int test_case_suit[] = {0, 2, 1, 0, 1, 0, 2, 1, 0, 3, 2, 0};\nbool test_case = false;\nint test_case_int = 0;\n\nclass Card {\npublic:\n int number;\n int suit;\n\n Card() {\n if (test_case && test_case_int < 12) {\n number = test_case_number[test_case_int];\n suit = test_case_suit[test_case_int];\n test_case_int++;\n }\n else {\n number = (double) rand()\/RAND_MAX*13;\n suit = (double) rand()\/RAND_MAX*4;\n }\n }\n \n Card(int n, int s) {\n number = n;\n suit = s;\n }\n\n std::string getString() {\n std::string s;\n s = number_lookup[number];\n s.append(suit_lookup[suit]);\n return s;\n }\n \n int getValue() {\n return face_value[number];\n }\n};\n\nclass Hand {\npublic:\n std::vector hand;\n int hand_count;\n\n Hand() {\n hand_count = 0;\n }\n\n int getScore() {\n int score = 0;\n int hasAce = 0;\n for (std::vector::iterator it = hand.begin() ; it != hand.end(); ++it) {\n if (it->number == 0) {\n\thasAce++;\n }\n score += it->getValue();\n }\n\n while (hasAce && score > 21) {\n hasAce--;\n score -= 10;\n }\n return score;\n }\n\n std::string getHand(bool ignoreFirst) {\n std::string s = \"\";\n for (std::vector::iterator it = hand.begin() ; it != hand.end(); ++it) {\n if (!ignoreFirst) {\n\ts.append(it->getString());\n\ts.append(\" \");\n }\n ignoreFirst = false;\n }\n return s;\n }\n\n void drawCard() {\n Card card;\n hand.push_back(card);\n hand_count++;\n }\n\n bool isDoubles() {\n if (hand_count > 0) {\n std::vector::iterator it = hand.begin();\n int i = it->number;\n it++;\n return (i == it->number);\n }\n else {\n return false;\n }\n }\n};\n\nclass Player {\npublic:\n Hand hand;\n Hand split;\n Hand split2;\n Hand split3; \n int splitLevel;\n\n Player() {\n splitLevel = 0;\n }\n \n void checkSplit() {\n if (hand.isDoubles() && askSplit()) {\n splitHandler(hand, split);\n splitLevel = 1;\n if (split.isDoubles() && askSplit()) {\n\tsplitHandler(split, split2);\n\tsplitLevel = 2;\n\tif (split2.isDoubles() && askSplit()) {\n\t splitHandler(split2, split3);\n\t splitLevel = 3;\n\t}\n }\n }\n }\n\n bool askSplit() {\n if (splitLevel < 1) {\n std::cout << \"Split? (y\/n): \";\n }\n else {\n std::cout << \"Split again? (y\/n): \";\n }\n\n char ch;\n while (true) { \/\/ Loop input until valid response\n std::cin >> ch;\n ch = tolower(ch);\n if (ch == 'y') {\n\treturn true;\n }\n else if (ch == 'n') {\n\treturn false;\n }\n }\n }\n \n void splitHandler(Hand& h1, Hand& h2) {\n std::vector::iterator it = h1.hand.end();\n it--; \/\/ Get last card\n\n Card card (it->number, it-> suit);\n\n std::cout << card.number << std::endl;\n std::cout << card.suit << std::endl;\n\n h2.hand.push_back(card); \/\/ Push new card to new hand, and delete from old hand\n h1.hand.pop_back();\n\n h1.drawCard(); \/\/ Draw new cards for both split hands\n h2.drawCard();\n }\n \n void printHand() {\n std::cout << \"Player : \" << hand.getHand(false) << \"\\n\";\n if (splitLevel >= 1) {\n std::cout << \"Split : \" << split.getHand(false) << \"\\n\";\n }\n if (splitLevel >= 2) {\n std::cout << \"Split 2 : \" << split2.getHand(false) << \"\\n\";\n }\n if (splitLevel >= 3) {\n std::cout << \"Split 3 : \" << split3.getHand(false) << \"\\n\"; \n } \n }\n};\n\nclass Game {\npublic: \n int player_bet;\n int player_cash;\n\n Game() {\n player_cash = 100;\n }\n\n void newGame() {\n Player player;\n Hand dealer;\n char ch;\n\n player_bet = 0; \/\/ Reset player bet to known value\n\n std::cout << \"Player: $\" << player_cash << \"\\nRound bet: \"; \/\/ Get player bet amount and deduct it\n std::cin >> player_bet;\n\n while (player_cash < player_bet || player_bet == 0) { \/\/ Ensure valid bet amount\n std::cin.clear(); \/\/ Fix looping error with invalid input\n std::cin.ignore(std::numeric_limits::max(), '\\n'); \/\/ Clear read buffer\n std::cout << \"Invalid bet. Round bet: \";\n std::cin >> player_bet;\n }\n\n player_cash -= player_bet;\n\n std::cout << \"Test case? (y\/n): \";\n while (true) {\n std::cin >> ch;\n ch = tolower(ch);\n\n if (ch == 'y') {\n\ttest_case = true;\n\tbreak;\n }\n else if (ch == 'n') {\n\tbreak;\n }\n }\n\n player.hand.drawCard(); \/\/ Draw cards for player and dealer\n player.hand.drawCard();\n dealer.drawCard();\n dealer.drawCard();\n\n player.checkSplit();\n playRound(player, dealer);\n }\n\n void playRound(Player player, Hand dealer) {\n char ch;\n \n if (player.hand.getScore() >= 21 || player.hand.hand_count >= 5) { \/\/ End game if player gets 21 or over\n endGame(player, dealer);\n return;\n }\n\n std::cout << \"Dealer : * \" << dealer.getHand(true) << \"\\n\";\n player.printHand();\n std::cout << \"Draw? (y\/n) \";\n\n while (true) {\n std::cin >> ch;\n ch = tolower(ch);\n\n if (ch == 'y') {\n\tplayer.hand.drawCard();\n\tplayRound(player, dealer);\n\tbreak;\n }\n else if (ch == 'n') {\n\tendGame(player, dealer);\n\tbreak;\n }\n }\n }\n\n void endGame(Player player, Hand dealer) {\n \n while (dealer.getScore() < 17 && dealer.hand_count < 5) {\n dealer.drawCard();\n }\n \n std::cout << \"Dealer : \" << dealer.getHand(false) << \"\\nPlayer : \" << player.hand.getHand(false) \/\/ Display hands\n\t << \"\\nDealer: \" << dealer.getScore() << \"\\tPlayer: \" << player.hand.getScore() << \"\\n\"; \/\/ Display points\n \n switch (checkWin(player.hand, dealer)) {\n case 0:\n\tstd::cout << \"Dealer wins!\\n\";\n\tbreak;\n case 1:\n\tstd::cout << \"Tie game!\\n\";\n\tplayer_cash += player_bet;\n\tbreak;\n case 2:\n\tstd::cout << \"Player Wins!\\n\";\n\tif (player.hand.getScore() == 21) {\n\t player_cash += player_bet*2.5;\n\t}\n\telse {\n\t player_cash += player_bet*2;\n\t}\n\tbreak;\n }\n }\n \n int checkWin(Hand player, Hand dealer) { \/\/ 0 = loss, 1 = tie, 2 = win\n if (player.getScore() > 21) {\n return 0;\n }\n else if (dealer.getScore() > 21) {\n return 2;\n }\n else if (dealer.getScore() == player.getScore()) {\n return 1;\n }\n else if (dealer.getScore() > player.getScore()) {\n return 0;\n }\n else {\n return 2;\n }\n }\n};\n\nint main() {\n Game game;\n char ch;\n\n srand(time(0)); \/\/ initialize random number generator\n\n game.newGame(); \/\/ start new game\n \n while (true) { \/\/ Wait for valid input\n if (game.player_cash <= 0) { \/\/ Make sure the player has cash to continue playing\n std::cout << \"Sorry, You have no more money left.\\n\";\n break;\n }\n std::cout << \"Again? (y\/n): \";\n std::cin >> ch;\n ch = tolower(ch);\n if (ch == 'y') {\n game.newGame(); \/\/ Start new game\n }\n else if (ch == 'n') {\n break; \/\/ Exit loop\n }\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ print.hpp\n\/\/ Created by Daniel Illescas Romero on 09\/09\/2016.\n\n#ifndef print_h\n#define print_h\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/* PRINT functions *\/\n\ntemplate \nvoid print(const Type& value) {\n\tcout << value << endl;\n}\n\ntemplate \nvoid print(const Type& value, const Args& ...args) {\n\tcout << value << ' ';\n\tprint(args...);\n}\n\n\/* TO_STRING functions *\/\n\n\/\/ Stub function (don't use externally) (useful when trying to pass a string to the 'to_string' function, to avoid problems)\nstring to_string(const string& str) {\n\treturn str;\n}\n\n\/\/ Convert char to string\nstring to_string(const char& chr) {\n\treturn string(1,chr);\n}\n\n\/\/ Return a single or double quoted string IF the data is a string or a char\ntemplate \nstring quotedString(const Type& data) {\n\t\n\tif (typeid(data) == typeid(string)) {\n\t\treturn (\"\\\"\" + to_string(data) + \"\\\"\");\n\t}\n\telse if (typeid(data) == typeid(char)) {\n\t\treturn (\"\\'\" + to_string(data) + \"\\'\");\n\t}\n\telse {\n\t\treturn to_string(data);\n\t}\n}\n\n\/\/ Return a string given a container (vector, array, list, initializer_list, deque, set, multiset, unordered_set)\ntemplate \nstring to_string(const Container& cont) {\n\t\n\tstring str;\n\tsize_t position = 0;\n\t\n\tstr += \"[\";\n\t\n\tfor (auto value: cont) {\n\n\t\tstr += quotedString(value);\n\t\t\n\t\tif (position + 1 < cont.size()) {\n\t\t\tstr += \", \";\n\t\t}\n\t\tposition++;\n\t}\n\t\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n\/\/ Return a string given a forward list\ntemplate \nstring to_string(const forward_list& fl) {\n\t\n\tsize_t size = distance(fl.begin(), fl.end());\n\tsize_t position = 0;\n\tstring str;\n\t\n\tstr += \"[\";\n\t\n\tfor (Type value: fl) {\n\t\t\n\t\tstr += quotedString(value);\n\t\t\n\t\tif (position + 1 < size) {\n\t\t\tstr += \", \";\n\t\t}\n\t\tposition++;\n\t}\n\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n\/\/ Return a string given any map type\ntemplate \nstring to_stringMAP(const mapType& map) {\n\tstring str;\n\tsize_t position = 0;\n\t\n\tstr += \"[\";\n\t\n\tfor (auto value: map) {\n\t\t\n\t\tstr += quotedString(value.first) + \": \" + quotedString(value.second);\n\t\t\n\t\tif (position + 1 < map.size()) {\n\t\t\tstr += \", \";\n\t\t}\n\t\t\n\t\tposition++;\n\t}\n\t\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n\/\/ Return a string given a map\ntemplate \nstring to_string(const map& map) {\n\treturn to_stringMAP(map);\n}\n\n\/\/ Return a string given a multimap\ntemplate \nstring to_string(const multimap& map) {\n\treturn to_stringMAP(map);\n}\n\n\/\/ Return a string given an unordered map\ntemplate \nstring to_string(const unordered_map& map) {\n\treturn to_stringMAP(map);\n}\n\n\/\/ Return a string given an unordered multimap\ntemplate \nstring to_string(const unordered_multimap& map) {\n\treturn to_stringMAP(map);\n}\n\n\/\/ Return a string given a classic array and its size\ntemplate \nstring to_string(const Type * array, size_t size) {\n\t\n\tstring str;\n\t\n\tstr += \"[\";\n\t\n\tfor (size_t idx = 0; idx < size; idx++) {\n\t\t\n\t\tstr += quotedString(array[idx]);\n\t\t\n\t\tif (idx + 1 < size) {\n\t\t\tstr += \", \";\n\t\t}\n\t}\n\t\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n\/\/ Return a string given a matrix and its size\ntemplate \nstring to_string(const Type& matrix, size_t rows, size_t cols) {\n\t\n\tstring str;\n\t\n\tstr += \"[\";\n\t\n\tfor (size_t i = 0; i < rows; i++) {\n\t\tstr += \"[\";\n\t\tfor (size_t j = 0; j < cols; j++) {\n\n\t\t\tstr += quotedString(matrix[i][j]);\n\t\t\t\n\t\t\tif (j + 1 < cols) {\n\t\t\t\tstr += \", \";\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (i + 1 < rows) {\n\t\t\tstr += \"], \";\n\t\t}\n\t\telse {\n\t\t\tstr += \"]\";\n\t\t}\n\t\t\n\t}\n\t\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n\/\/ Return a string given a queue (creates a copy of the queue)\ntemplate \nstring to_string(queue queue) {\n\t\n\tstring str;\n\tsize_t originalSize = queue.size();\n\n\tstr += \"[\";\n\n\tfor (size_t idx = 0; idx < originalSize; idx++) {\n\n\t\tstr += quotedString(queue.front());\n\t\tqueue.pop();\n\t\t\n\t\tif (idx + 1 < originalSize) {\n\t\t\tstr += \", \";\n\t\t}\n\t}\n\t\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n\/\/ Return a string given a priority queue (creates a copy of the queue)\ntemplate \nstring to_string(priority_queue pqueue) {\n\t\n\tstring str;\n\tsize_t originalSize = pqueue.size();\n\t\n\tstr += \"[\";\n\t\n\tfor (size_t idx = 0; idx < originalSize; idx++) {\n\t\t\n\t\tstr += quotedString(pqueue.top());\n\t\tpqueue.pop();\n\t\t\n\t\tif (idx + 1 < originalSize) {\n\t\t\tstr += \", \";\n\t\t}\n\t}\n\t\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n\/\/ Return a string given a stack (creates a copy of the stack)\ntemplate \nstring to_string(stack stack) {\n\t\n\tstring str;\n\tsize_t originalSize = stack.size();\n\t\n\tstr += \"[\";\n\t\n\tfor (size_t idx = 0; idx < originalSize; idx++) {\n\t\t\n\t\tstr += quotedString(stack.top());\n\t\tstack.pop();\n\t\t\n\t\tif (idx + 1 < originalSize) {\n\t\t\tstr += \", \";\n\t\t}\n\t}\n\t\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n#endif \/* print_h *\/\nChanged name from print.h -> print.hpp\/\/ print.hpp\n\/\/ Created by Daniel Illescas Romero on 09\/09\/2016.\n\n#ifndef print_hpp\n#define print_hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/* PRINT functions *\/\n\ntemplate \nvoid print(const Type& value) {\n\tcout << value << endl;\n}\n\ntemplate \nvoid print(const Type& value, const Args& ...args) {\n\tcout << value << ' ';\n\tprint(args...);\n}\n\n\/* TO_STRING functions *\/\n\n\/\/ Stub function (don't use externally) (useful when trying to pass a string to the 'to_string' function, to avoid problems)\nstring to_string(const string& str) {\n\treturn str;\n}\n\n\/\/ Convert char to string\nstring to_string(const char& chr) {\n\treturn string(1,chr);\n}\n\n\/\/ Return a single or double quoted string IF the data is a string or a char\ntemplate \nstring quotedString(const Type& data) {\n\t\n\tif (typeid(data) == typeid(string)) {\n\t\treturn (\"\\\"\" + to_string(data) + \"\\\"\");\n\t}\n\telse if (typeid(data) == typeid(char)) {\n\t\treturn (\"\\'\" + to_string(data) + \"\\'\");\n\t}\n\telse {\n\t\treturn to_string(data);\n\t}\n}\n\n\/\/ Return a string given a container (vector, array, list, initializer_list, deque, set, multiset, unordered_set)\ntemplate \nstring to_string(const Container& cont) {\n\t\n\tstring str;\n\tsize_t position = 0;\n\t\n\tstr += \"[\";\n\t\n\tfor (auto value: cont) {\n\n\t\tstr += quotedString(value);\n\t\t\n\t\tif (position + 1 < cont.size()) {\n\t\t\tstr += \", \";\n\t\t}\n\t\tposition++;\n\t}\n\t\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n\/\/ Return a string given a forward list\ntemplate \nstring to_string(const forward_list& fl) {\n\t\n\tsize_t size = distance(fl.begin(), fl.end());\n\tsize_t position = 0;\n\tstring str;\n\t\n\tstr += \"[\";\n\t\n\tfor (Type value: fl) {\n\t\t\n\t\tstr += quotedString(value);\n\t\t\n\t\tif (position + 1 < size) {\n\t\t\tstr += \", \";\n\t\t}\n\t\tposition++;\n\t}\n\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n\/\/ Return a string given any map type\ntemplate \nstring to_stringMAP(const mapType& map) {\n\tstring str;\n\tsize_t position = 0;\n\t\n\tstr += \"[\";\n\t\n\tfor (auto value: map) {\n\t\t\n\t\tstr += quotedString(value.first) + \": \" + quotedString(value.second);\n\t\t\n\t\tif (position + 1 < map.size()) {\n\t\t\tstr += \", \";\n\t\t}\n\t\t\n\t\tposition++;\n\t}\n\t\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n\/\/ Return a string given a map\ntemplate \nstring to_string(const map& map) {\n\treturn to_stringMAP(map);\n}\n\n\/\/ Return a string given a multimap\ntemplate \nstring to_string(const multimap& map) {\n\treturn to_stringMAP(map);\n}\n\n\/\/ Return a string given an unordered map\ntemplate \nstring to_string(const unordered_map& map) {\n\treturn to_stringMAP(map);\n}\n\n\/\/ Return a string given an unordered multimap\ntemplate \nstring to_string(const unordered_multimap& map) {\n\treturn to_stringMAP(map);\n}\n\n\/\/ Return a string given a classic array and its size\ntemplate \nstring to_string(const Type * array, size_t size) {\n\t\n\tstring str;\n\t\n\tstr += \"[\";\n\t\n\tfor (size_t idx = 0; idx < size; idx++) {\n\t\t\n\t\tstr += quotedString(array[idx]);\n\t\t\n\t\tif (idx + 1 < size) {\n\t\t\tstr += \", \";\n\t\t}\n\t}\n\t\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n\/\/ Return a string given a matrix and its size\ntemplate \nstring to_string(const Type& matrix, size_t rows, size_t cols) {\n\t\n\tstring str;\n\t\n\tstr += \"[\";\n\t\n\tfor (size_t i = 0; i < rows; i++) {\n\t\tstr += \"[\";\n\t\tfor (size_t j = 0; j < cols; j++) {\n\n\t\t\tstr += quotedString(matrix[i][j]);\n\t\t\t\n\t\t\tif (j + 1 < cols) {\n\t\t\t\tstr += \", \";\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (i + 1 < rows) {\n\t\t\tstr += \"], \";\n\t\t}\n\t\telse {\n\t\t\tstr += \"]\";\n\t\t}\n\t\t\n\t}\n\t\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n\/\/ Return a string given a queue (creates a copy of the queue)\ntemplate \nstring to_string(queue queue) {\n\t\n\tstring str;\n\tsize_t originalSize = queue.size();\n\n\tstr += \"[\";\n\n\tfor (size_t idx = 0; idx < originalSize; idx++) {\n\n\t\tstr += quotedString(queue.front());\n\t\tqueue.pop();\n\t\t\n\t\tif (idx + 1 < originalSize) {\n\t\t\tstr += \", \";\n\t\t}\n\t}\n\t\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n\/\/ Return a string given a priority queue (creates a copy of the queue)\ntemplate \nstring to_string(priority_queue pqueue) {\n\t\n\tstring str;\n\tsize_t originalSize = pqueue.size();\n\t\n\tstr += \"[\";\n\t\n\tfor (size_t idx = 0; idx < originalSize; idx++) {\n\t\t\n\t\tstr += quotedString(pqueue.top());\n\t\tpqueue.pop();\n\t\t\n\t\tif (idx + 1 < originalSize) {\n\t\t\tstr += \", \";\n\t\t}\n\t}\n\t\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n\/\/ Return a string given a stack (creates a copy of the stack)\ntemplate \nstring to_string(stack stack) {\n\t\n\tstring str;\n\tsize_t originalSize = stack.size();\n\t\n\tstr += \"[\";\n\t\n\tfor (size_t idx = 0; idx < originalSize; idx++) {\n\t\t\n\t\tstr += quotedString(stack.top());\n\t\tstack.pop();\n\t\t\n\t\tif (idx + 1 < originalSize) {\n\t\t\tstr += \", \";\n\t\t}\n\t}\n\t\n\tstr += \"]\";\n\t\n\treturn str;\n}\n\n#endif \/* print_hpp *\/\n<|endoftext|>"} {"text":"#include \"GraphUtil.hpp\"\n#include \"Math.hpp\"\n#include \n\nsf::ConvexShape Line(const sf::Vector2f &Start, const sf::Vector2f &End, float Thickness, const sf::Color &Color, float Outline, const sf::Color &OutlineColor)\n{\n sf::Vector2f Normal(Start.y - End.y, End.x - Start.x);\n float Length = Distance(sf::Vector2f(0.f, 0.f), Normal);\n if (Length != 0.f)\n Normal \/= Length;\n\n Normal *= Thickness \/ 2;\n\n\n sf::ConvexShape Line;\n\n Line.setPointCount(4);\n Line.setPoint(0, Start - Normal);\n Line.setPoint(1, End - Normal);\n Line.setPoint(2, End + Normal);\n Line.setPoint(3, Start + Normal);\n Line.setFillColor(Color);\n Line.setOutlineThickness(Outline);\n Line.setOutlineColor(OutlineColor);\n\n return Line;\n}\n\nsf::CircleShape Circle(const sf::Vector2f &Center, float Radius, const sf::Color &Color, float Outline, const sf::Color &OutlineColor)\n{\n sf::CircleShape Circle;\n Circle.setOrigin(Radius, Radius);\n Circle.setPosition(Center);\n Circle.setRadius(Radius);\n Circle.setFillColor(Color);\n Circle.setOutlineThickness(Outline);\n Circle.setOutlineColor(OutlineColor);\n return Circle;\n}\n\nsf::RectangleShape Rectangle(float Left, float Top, float Width, float Height, const sf::Color &Color, float Outline, const sf::Color &OutlineColor)\n{\n sf::RectangleShape Rectangle;\n Rectangle.setPosition(Left, Top);\n Rectangle.setSize(sf::Vector2f(Width, Height));\n Rectangle.setFillColor(Color);\n Rectangle.setOutlineThickness(Outline);\n Rectangle.setOutlineColor(OutlineColor);\n return Rectangle;\n}\n\nclass BottomLeftCompare\n{\npublic:\n bool operator() (const sf::Vector2f &Lhs, const sf::Vector2f &Rhs) const\n {\n if (Lhs.y == Rhs.y)\n return Lhs.x < Rhs.x;\n else\n return Lhs.y > Rhs.y;\n }\n} BottomLeftComp;\n\nclass AngleCompare\n{\npublic:\n AngleCompare(const sf::Vector2f &NewP) : P(NewP)\n {\n\n }\n\n bool operator() (const sf::Vector2f &Lhs, const sf::Vector2f &Rhs) const\n {\n return (-DotProduct(sf::Vector2f(1.f, 0.f), Lhs - P) \/ Magnitude(Lhs - P)) < (-DotProduct(sf::Vector2f(1.f, 0.f), Rhs - P) \/ Magnitude(Rhs - P));\n }\nprivate:\n sf::Vector2f P;\n};\n\nfloat CCW(const sf::Vector2f &p1, const sf::Vector2f &p2, const sf::Vector2f &p3)\n{\n return CrossProduct(p2 - p1, p3 - p1);\n}\n\nsf::ConvexShape ConvexHull(vector Points)\n{\n iter_swap(Points.begin(), min_element(Points.begin(), Points.end(), BottomLeftComp));\n\n AngleCompare AngleComp(Points.front());\n sort(Points.begin() + 1, Points.end(), AngleComp);\n\n int m = 0;\n for (unsigned int i = 1; i < Points.size(); i++)\n {\n while (CCW(Points[m == 0 ? Points.size() - 1 : m - 1], Points[m], Points[i]) >= 0.f)\n {\n if (m > 0)\n m--;\n else if (i == Points.size() - 1)\n break;\n else\n i++;\n }\n\n m++;\n swap(Points[m], Points[i]);\n }\n\n sf::ConvexShape Shape(m + 1);\n for (unsigned int i = 0; i < Shape.getPointCount(); i++)\n Shape.setPoint(i, Points[i]);\n\n return Shape;\n}\n\nsf::Texture PerlinNoise()\n{\n const int Size2 = 1024;\n const float Persistence = 0.5f;\n\n vector< vector > F(Size2, vector(Size2, 0.f));\n\n for (int i = 2; i <= 7; i++)\n {\n int Freq = pow(2, i);\n float Amplitude = pow(Persistence, 10 - i);\n\n int Size = Size2 \/ Freq;\n vector< vector > G;\n for (int y = 0; y < Size + 1; y++)\n {\n vector Row;\n for (int x = 0; x < Size + 1; x++)\n Row.push_back(PolarToRect(sf::Vector2f(1.f, Random(0.f, 360.f))));\n\n G.push_back(Row);\n }\n\n for (int y = 0; y < Size2; y++)\n {\n for (int x = 0; x < Size2; x++)\n {\n sf::Vector2f p(x, y);\n p *= float(Size) \/ Size2;\n sf::Vector2i p0(p);\n sf::Vector2i p1 = p0 + sf::Vector2i(1, 1);\n\n float s = DotProduct(G[p0.y][p0.x], p - sf::Vector2f(p0));\n float t = DotProduct(G[p0.y][p1.x], p - sf::Vector2f(p1.x, p0.y));\n float u = DotProduct(G[p1.y][p0.x], p - sf::Vector2f(p0.x, p1.y));\n float v = DotProduct(G[p1.y][p1.x], p - sf::Vector2f(p1));\n\n sf::Vector2f S;\n S.x = 3 * pow(p.x - p0.x, 2) - 2 * pow(p.x - p0.x, 3);\n float a = s + S.x * (t - s);\n float b = u + S.x * (v - u);\n S.y = 3 * pow(p.y - p0.y, 2) - 2 * pow(p.y - p0.y, 3);\n float z = a + S.y * (b - a);\n\n F[y][x] += z * Amplitude;\n }\n }\n\n }\n\n float min, max;\n for (int y = 0; y < Size2; y++)\n {\n for (int x = 0; x < Size2; x++)\n {\n if (y == 0 && x == 0)\n min = max = F[y][x];\n else\n {\n if (F[y][x] < min)\n min = F[y][x];\n\n if (F[y][x] > max)\n max = F[y][x];\n }\n }\n }\n\n sf::Image Img;\n Img.create(Size2, Size2, sf::Color::Red);\n for (int y = 0; y < Size2; y++)\n {\n for (int x = 0; x < Size2; x++)\n {\n int val = Map(F[y][x], min, max, 128, 255);\n Img.setPixel(x, y, sf::Color(val, val, val));\n }\n }\n\n sf::Texture Tex;\n Tex.loadFromImage(Img);\n return Tex;\n}\nOptimize Perlin noise generation, make it look a bit nicer#include \"GraphUtil.hpp\"\n#include \"Math.hpp\"\n#include \n\nsf::ConvexShape Line(const sf::Vector2f &Start, const sf::Vector2f &End, float Thickness, const sf::Color &Color, float Outline, const sf::Color &OutlineColor)\n{\n sf::Vector2f Normal(Start.y - End.y, End.x - Start.x);\n float Length = Distance(sf::Vector2f(0.f, 0.f), Normal);\n if (Length != 0.f)\n Normal \/= Length;\n\n Normal *= Thickness \/ 2;\n\n\n sf::ConvexShape Line;\n\n Line.setPointCount(4);\n Line.setPoint(0, Start - Normal);\n Line.setPoint(1, End - Normal);\n Line.setPoint(2, End + Normal);\n Line.setPoint(3, Start + Normal);\n Line.setFillColor(Color);\n Line.setOutlineThickness(Outline);\n Line.setOutlineColor(OutlineColor);\n\n return Line;\n}\n\nsf::CircleShape Circle(const sf::Vector2f &Center, float Radius, const sf::Color &Color, float Outline, const sf::Color &OutlineColor)\n{\n sf::CircleShape Circle;\n Circle.setOrigin(Radius, Radius);\n Circle.setPosition(Center);\n Circle.setRadius(Radius);\n Circle.setFillColor(Color);\n Circle.setOutlineThickness(Outline);\n Circle.setOutlineColor(OutlineColor);\n return Circle;\n}\n\nsf::RectangleShape Rectangle(float Left, float Top, float Width, float Height, const sf::Color &Color, float Outline, const sf::Color &OutlineColor)\n{\n sf::RectangleShape Rectangle;\n Rectangle.setPosition(Left, Top);\n Rectangle.setSize(sf::Vector2f(Width, Height));\n Rectangle.setFillColor(Color);\n Rectangle.setOutlineThickness(Outline);\n Rectangle.setOutlineColor(OutlineColor);\n return Rectangle;\n}\n\nclass BottomLeftCompare\n{\npublic:\n bool operator() (const sf::Vector2f &Lhs, const sf::Vector2f &Rhs) const\n {\n if (Lhs.y == Rhs.y)\n return Lhs.x < Rhs.x;\n else\n return Lhs.y > Rhs.y;\n }\n} BottomLeftComp;\n\nclass AngleCompare\n{\npublic:\n AngleCompare(const sf::Vector2f &NewP) : P(NewP)\n {\n\n }\n\n bool operator() (const sf::Vector2f &Lhs, const sf::Vector2f &Rhs) const\n {\n return (-DotProduct(sf::Vector2f(1.f, 0.f), Lhs - P) \/ Magnitude(Lhs - P)) < (-DotProduct(sf::Vector2f(1.f, 0.f), Rhs - P) \/ Magnitude(Rhs - P));\n }\nprivate:\n sf::Vector2f P;\n};\n\nfloat CCW(const sf::Vector2f &p1, const sf::Vector2f &p2, const sf::Vector2f &p3)\n{\n return CrossProduct(p2 - p1, p3 - p1);\n}\n\nsf::ConvexShape ConvexHull(vector Points)\n{\n iter_swap(Points.begin(), min_element(Points.begin(), Points.end(), BottomLeftComp));\n\n AngleCompare AngleComp(Points.front());\n sort(Points.begin() + 1, Points.end(), AngleComp);\n\n int m = 0;\n for (unsigned int i = 1; i < Points.size(); i++)\n {\n while (CCW(Points[m == 0 ? Points.size() - 1 : m - 1], Points[m], Points[i]) >= 0.f)\n {\n if (m > 0)\n m--;\n else if (i == Points.size() - 1)\n break;\n else\n i++;\n }\n\n m++;\n swap(Points[m], Points[i]);\n }\n\n sf::ConvexShape Shape(m + 1);\n for (unsigned int i = 0; i < Shape.getPointCount(); i++)\n Shape.setPoint(i, Points[i]);\n\n return Shape;\n}\n\nsf::Texture PerlinNoise()\n{\n const int Size2 = 800;\n const float Persistence = 0.5f;\n\n vector< vector > F(Size2, vector(Size2, 0.f));\n\n for (int i = 4; i <= 7; i++)\n {\n int Freq = pow(2, i);\n float Amplitude = pow(Persistence, log(Size2) \/ log(2) - i);\n\n int Size = Size2 \/ Freq;\n vector< vector > G(Size + 1, vector(Size + 1));\n for (int y = 0; y < Size + 1; y++)\n {\n for (int x = 0; x < Size + 1; x++)\n G[y][x] = PolarToRect(sf::Vector2f(1.f, Random(0.f, 360.f)));\n }\n\n for (int y = 0; y < Size2; y++)\n {\n for (int x = 0; x < Size2; x++)\n {\n sf::Vector2f p(x, y);\n p *= float(Size) \/ Size2;\n sf::Vector2i p0(p);\n sf::Vector2i p1 = p0 + sf::Vector2i(1, 1);\n\n sf::Vector2f pp0 = p - sf::Vector2f(p0);\n sf::Vector2f pp1 = p - sf::Vector2f(p1);\n\n float s = DotProduct(G[p0.y][p0.x], pp0);\n float t = DotProduct(G[p0.y][p1.x], sf::Vector2f(pp1.x, pp0.y));\n float u = DotProduct(G[p1.y][p0.x], sf::Vector2f(pp0.x, pp1.y));\n float v = DotProduct(G[p1.y][p1.x], pp1);\n\n sf::Vector2f S;\n S.x = 3 * pow(pp0.x, 2) - 2 * pow(pp0.x, 3);\n float a = s + S.x * (t - s);\n float b = u + S.x * (v - u);\n S.y = 3 * pow(pp0.y, 2) - 2 * pow(pp0.y, 3);\n float z = a + S.y * (b - a);\n\n F[y][x] += z * Amplitude;\n }\n }\n }\n\n float min, max;\n for (int y = 0; y < Size2; y++)\n {\n for (int x = 0; x < Size2; x++)\n {\n if (y == 0 && x == 0)\n min = max = F[y][x];\n else\n {\n if (F[y][x] < min)\n min = F[y][x];\n\n if (F[y][x] > max)\n max = F[y][x];\n }\n }\n }\n\n sf::Image Img;\n Img.create(Size2, Size2, sf::Color::Red);\n for (int y = 0; y < Size2; y++)\n {\n for (int x = 0; x < Size2; x++)\n {\n int val = Map(F[y][x], min, max, 165, 255);\n Img.setPixel(x, y, sf::Color(val, val, val));\n }\n }\n\n sf::Texture Tex;\n Tex.loadFromImage(Img);\n return Tex;\n}\n<|endoftext|>"} {"text":"\nTGeoManager *g=0;\n\nvoid Hgeom(Bool_t isOnlyChambers=kFALSE)\n{\n \n g=new TGeoManager(\"TestHMPID\",\"Private HMPID geometry\");\n Materials(); \n gGeoManager->MakeBox(\"ALIC\",gGeoManager->GetMedium(\"HMPID_CH4\"),3000\/2,3000\/2,3000\/2); \/\/arbitrary values \n gGeoManager->SetTopVolume(gGeoManager->GetVolume(\"ALIC\"));\n \n Hmpid(isOnlyChambers);\n \n gGeoManager->CloseGeometry();\n \n\/\/ gGeoManager->SetVisOption(0); gGeoManager->SetVisLevel(5); \n \n\/\/ gGeoManager->GetMasterVolume()->Draw();\n\/\/ Axis();\n\/\/ gPad->GetView()->SetView(3,94,-70,0);\n new TBrowser;\n}\n\/\/__________________________________________________________________________________________________\nvoid Materials()\n{\n\/\/Media for HMPID\n Double_t a=0,z=0,den=0,radlen=0,intlen=0;\/\/tmp vars for material parameters\n \/\/ A Z rho\n TGeoMaterial *ar,*al,*cu,*w,*ro; TGeoMixture *c6f14,*sio2,*ch4,*csi;\n al =new TGeoMaterial(\"HMPID_Al\" , 26.982 , 13 , 2.700); \n ro =new TGeoMaterial(\"HMPID_Neoc\" , 12.01 , 6 , 0.1 ); \n cu =new TGeoMaterial(\"HMPID_Cu\" , 63.546 , 29 , 8.960); \n w =new TGeoMaterial(\"HMPID_W\" , 183.840 , 74 , 19.300); \n ar =new TGeoMaterial(\"HMPID_Ar\" , 39.948 , 18 , 1.396); \n c6f14=new TGeoMixture (\"HMPID_C6F14\",2,1.68 );c6f14->DefineElement(0, 12.010, 6,6); c6f14->DefineElement(1, 18.998, 9,14);\n sio2 =new TGeoMixture (\"HMPID_SiO2\" ,2,2.20 );sio2 ->DefineElement(0, 28.085,14,1); sio2->DefineElement(1, 15.999, 8, 2);\n ch4 =new TGeoMixture (\"HMPID_CH4\" ,2,0.4224e-3);ch4 ->DefineElement(0, 12.010, 6,1); ch4->DefineElement(1, 1.007, 1, 4); \n csi =new TGeoMixture (\"HMPID_CsI\" ,2,1.8 );csi ->DefineElement(0,132.900,55,1); csi->DefineElement(1,126.900,53, 1);\n \n new TGeoMedium(\"HMPID_Al\" ,1,al);\n new TGeoMedium(\"HMPID_Neoc\" ,2,ro);\n new TGeoMedium(\"HMPID_Cu\" ,3,cu);\n new TGeoMedium(\"HMPID_W\" ,4,w );\n new TGeoMedium(\"HMPID_C6F14\",6,c6f14);\n new TGeoMedium(\"HMPID_SiO2\" ,7,sio2); \n new TGeoMedium(\"HMPID_CH4\" ,8,ch4);\n new TGeoMedium(\"HMPID_CsI\" ,9,csi); \n new TGeoMedium(\"HMPID_Ar\" ,1,ar);\n \n}\/\/Materials()\n\/\/__________________________________________________________________________________________________\nvoid Hmpid(Bool_t isOnlyChambers)\n{\n Double_t cm=1,mm=0.1*cm,um=0.0001*cm;\/\/length units \n TGeoMedium *al =gGeoManager->GetMedium(\"HMPID_Al\"); \n TGeoMedium *ch4 =gGeoManager->GetMedium(\"HMPID_CH4\"); \n TGeoMedium *roha =gGeoManager->GetMedium(\"HMPID_Rohacell\"); \n TGeoMedium *neoc =gGeoManager->GetMedium(\"HMPID_Neoceram\"); \n TGeoMedium *c6f14=gGeoManager->GetMedium(\"HMPID_C6F14\"); \n TGeoMedium *sio2 =gGeoManager->GetMedium(\"HMPID_SiO2\"); \n TGeoMedium *cu =gGeoManager->GetMedium(\"HMPID_Cu\"); \n TGeoMedium *w =gGeoManager->GetMedium(\"HMPID_W\"); \n TGeoMedium *csi =gGeoManager->GetMedium(\"HMPID_CsI\"); \n TGeoMedium *ar =gGeoManager->GetMedium(\"HMPID_Ar\"); \n \n TGeoVolume *hmp=gGeoManager->MakeBox (\"Hmp\",ch4,1681*mm\/2, 1466*mm\/2,(2*80*mm+2*41*mm)\/2);\/\/2033P1 z from p84 TDR \n const Double_t kAngHor=19.5; \/\/ horizontal angle between chambers 19.5 grad\n const Double_t kAngVer=20; \/\/ vertical angle between chambers 20 grad \n const Double_t kAngCom=30; \/\/ common HMPID rotation around z 30 grad \n const Double_t trans[3]={490*cm,0*cm,0*cm}; \/\/center of the chamber is on window- proximity gap surface\n for(Int_t ch=0;ch<=6;ch++){\/\/place 7 chambers\n TGeoHMatrix *mat=new TGeoHMatrix;\n mat->RotateY(90); \/\/rotate around y since initial position is in XY plane -> now in YZ plane\n mat->SetTranslation(trans); \/\/now plane in YZ is shifted along x \n switch(ch){\n case 0: mat->RotateY(kAngHor); mat->RotateZ(-kAngVer); break; \/\/right and down \n case 1: mat->RotateZ(-kAngVer); break; \/\/down \n case 2: mat->RotateY(kAngHor); break; \/\/right \n case 3: break; \/\/no rotation\n case 4: mat->RotateY(-kAngHor); break; \/\/left \n case 5: mat->RotateZ(kAngVer); break; \/\/up\n case 6: mat->RotateY(-kAngHor); mat->RotateZ(kAngVer); break; \/\/left and up \n }\n mat->RotateZ(kAngCom); \/\/apply common rotation in XY plane \n gGeoManager->GetVolume(\"ALIC\")->AddNode(hmp,ch,mat);\n }\n if(isOnlyChambers) return; \/\/do not construct the detailed geometry \n \n TGeoRotation *rot=new TGeoRotation(\"HwireRot\"); rot->RotateY(90); \/\/rotate wires around Y to be along X (initially along Z)\n TGeoVolume *sbo=gGeoManager->MakeBox (\"Hsbo\",ch4 , 1419*mm\/2 , 1378.00*mm\/2 , 50.5*mm\/2);\/\/2072P1\n TGeoVolume *cov=gGeoManager->MakeBox (\"Hcov\",al , 1419*mm\/2 , 1378.00*mm\/2 , 0.5*mm\/2); \n TGeoVolume *hon=gGeoManager->MakeBox (\"Hhon\",roha , 1359*mm\/2 , 1318.00*mm\/2 , 49.5*mm\/2); \n TGeoVolume *rad=gGeoManager->MakeBox (\"Hrad\",c6f14, 1330*mm\/2 , 413.00*mm\/2 , 24.0*mm\/2); \/\/2011P1\n TGeoVolume *neo=gGeoManager->MakeBox (\"Hneo\",neoc , 1330*mm\/2 , 413.00*mm\/2 , 4.0*mm\/2); \n TGeoVolume *win=gGeoManager->MakeBox (\"Hwin\",sio2 , 1330*mm\/2 , 413.00*mm\/2 , 5.0*mm\/2); \n TGeoVolume *si1=gGeoManager->MakeBox (\"Hsi1\",sio2 , 1330*mm\/2 , 5.00*mm\/2 , 15.0*mm\/2); \n TGeoVolume *si2=gGeoManager->MakeBox (\"Hsi2\",neoc , 10*mm\/2 , 403.00*mm\/2 , 15.0*mm\/2); \n TGeoVolume *spa=gGeoManager->MakeTube(\"Hspa\",sio2 , 0*mm , 5.00*mm , 15.0*mm\/2); \n TGeoVolume *fr4=gGeoManager->MakeBox (\"Hfr4\",ch4 , 1407*mm\/2 , 1366.00*mm\/2 , 15.0*mm\/2);\/\/2043P1 \n TGeoVolume *f4a=gGeoManager->MakeBox (\"Hf4a\",al , 1407*mm\/2 , 1366.00*mm\/2 , 10.0*mm\/2); \n TGeoVolume *f4i=gGeoManager->MakeBox (\"Hf4i\",ch4 , 1323*mm\/2 , 1296.00*mm\/2 , 10.0*mm\/2); \n TGeoVolume *col=gGeoManager->MakeTube(\"Hcol\",cu , 0*mm , 100.00*um , 1323.0*mm\/2);\n TGeoVolume *sec=gGeoManager->MakeBox (\"Hsec\",ch4 , 648*mm\/2 , 411.00*mm\/2 , 45.5*mm\/2);\/\/sec=gap+ppf\n TGeoVolume *ppf=gGeoManager->MakeBox (\"Hppf\",al , 648*mm\/2 , 411.00*mm\/2 , 40.0*mm\/2);\/\/2001P2\n TGeoVolume *lar=gGeoManager->MakeBox (\"Hlar\",ar , 181*mm\/2 , 89.25*mm\/2 , 38.3*mm\/2);\/\/2001P2\n TGeoVolume *smo=gGeoManager->MakeBox (\"Hsmo\",ar , 114*mm\/2 , 89.25*mm\/2 , 38.3*mm\/2);\/\/2001P2\n TGeoVolume *gap=gGeoManager->MakeBox (\"Hgap\",ch4 , 640*mm\/2 , 403.20*mm\/2 , 5.5*mm\/2);\/\/gap=pad+ano+cat\n TGeoVolume *cat=gGeoManager->MakeTube(\"Hcat\",cu , 0*mm , 50.00*um , 8.0*mm\/2); \n TGeoVolume *ano=gGeoManager->MakeTube(\"Hano\",w , 0*mm , 20.00*um , 8.0*mm\/2); \n TGeoVolume *pad=gGeoManager->MakeBox (\"Hpad\",csi , 8*mm\/2 , 8.40*mm\/2 , 1.0*mm\/2); \n\/\/\n\/\/ ^ Y z= z=-12mm z=98.25mm ALIC->7xHmp (virtual)-->1xHsbo (virtual) --->2xHcov (real) 2072P1\n\/\/ | ____________________________________ | |-->1xHhon (real) 2072P1\n\/\/ | | ______ ____ ______ | |\n\/\/ | | | | | * | | | |->3xHrad (virtual) --->1xHneo (real) 2011P1\n\/\/ | |50.5mm| |24mm| * |45.5mm| | | |-->1xHwin (real) 2011P1\n\/\/ | | | | | * | | | | |-->2xHsi1 (real) 2011P1\n\/\/ | | | |____| * |______| | | |-->2xHsi2 (real) 2011P1\n\/\/ | | | ____ * ______ | | |->30xHspa (real) 2011P1\n\/\/ | | | | | * | | | |\n\/\/ | | | | | * | | | |->1xHfr4 (vitual) --->1xHf4a (real)---->1xHf4i(virtual) 2043P1 \n\/\/ | | sb | | rad| * | | | | |-->322xHcol (real) 2043P1\n\/\/ | | | |____| * |______| | |\n\/\/ | | | ____ * ______ | |->6xHsec (virtual) --> 1xHppf(real) ---->8xHlar (virtual) 2001P1\n\/\/ | | | | | * | | | |--->8xHsmo (virtual) 2001P1 \n\/\/ | | | | | * | | | | \n\/\/ | | | | | * | | | |-> 1xHgap (virtual) --->48xHrow (virtual) -->80xHcel (virtual) -->4xHcat (real) from p84 TDR \n\/\/ | |______| |____| * |______| | |-->2xHano (real) from p84 TDR \n\/\/ |____________________________________| |-->1xHpad (real) from p84 TDR \n\/\/ --->Z \n hmp->AddNode(sbo ,1,new TGeoTranslation( 0*mm, 0*mm, -73.75*mm)); \/\/p.84 TDR\n sbo->AddNode(hon ,1,new TGeoTranslation( 0*mm,0*mm, 0*mm)); \/\/2072P1\n sbo->AddNode(cov ,1,new TGeoTranslation( 0*mm,0*mm, +25*mm)); \n sbo->AddNode(cov ,2,new TGeoTranslation( 0*mm,0*mm, -25*mm)); \n hmp->AddNode(rad,2,new TGeoTranslation( 0*mm,+434*mm, -12.00*mm)); \n hmp->AddNode(rad,1,new TGeoTranslation( 0*mm, 0*mm, -12.00*mm)); \n hmp->AddNode(rad,0,new TGeoTranslation( 0*mm,-434*mm, -12.00*mm)); \n rad->AddNode(neo,1,new TGeoTranslation( 0*mm, 0*mm, -10.0*mm));\n rad->AddNode(win,1,new TGeoTranslation( 0*mm, 0*mm, 9.5*mm));\n rad->AddNode(si1,1,new TGeoTranslation( 0*mm,-204*mm, -0.5*mm)); rad->AddNode(si1,2,new TGeoTranslation( 0*mm,+204*mm, -0.5*mm));\n rad->AddNode(si2,1,new TGeoTranslation(-660*mm, 0*mm, -0.5*mm)); rad->AddNode(si2,2,new TGeoTranslation(+660*mm, 0*mm, -0.5*mm));\n for(Int_t i=0;i<3;i++) for(Int_t j=0;j<10;j++) rad->AddNode(spa,copy=10*i+j,new TGeoTranslation(-1330*mm\/2+116*mm+j*122*mm,(i-1)*105*mm,-0.5*mm));\n hmp->AddNode(fr4,1,new TGeoTranslation( 0*mm, 0*mm, 9.00*mm)); \/\/p.84 TDR\n for(int i=1;i<=322;i++) fr4->AddNode(col,i,new TGeoCombiTrans( 0*mm, -1296\/2*mm+i*4*mm,-5*mm,rot)); \/\/F4 2043P1\n fr4->AddNode(f4a,1,new TGeoTranslation( 0*mm,0*mm, 2.5*mm)); \n f4a->AddNode(f4i,1,new TGeoTranslation( 0*mm,0*mm, 0*mm));\n hmp->AddNode(sec,4,new TGeoTranslation(-335*mm,+433*mm, 98.25*mm)); hmp->AddNode(sec,5,new TGeoTranslation(+335*mm,+433*mm, 98.25*mm));\n hmp->AddNode(sec,2,new TGeoTranslation(-335*mm, 0*mm, 98.25*mm)); hmp->AddNode(sec,3,new TGeoTranslation(+335*mm, 0*mm, 98.25*mm));\n hmp->AddNode(sec,0,new TGeoTranslation(-335*mm,-433*mm, 98.25*mm)); hmp->AddNode(sec,1,new TGeoTranslation(+335*mm,-433*mm, 98.25*mm));\n sec->AddNode(gap,1,new TGeoTranslation(0,0,-20.00*mm));\n TGeoVolume *row= gap->Divide(\"Hrow\",2,48,0,0);\/\/along Y->48 rows\n TGeoVolume *cel= row->Divide(\"Hcel\",1,80,0,0);\/\/along X->80 cells\n cel->AddNode(cat,1,new TGeoCombiTrans (0, 3.15*mm , -2.70*mm , rot)); \/\/4 cathode wires\n cel->AddNode(ano,1,new TGeoCombiTrans (0, 2.00*mm , -0.29*mm , rot)); \/\/2 anod wires\n cel->AddNode(cat,2,new TGeoCombiTrans (0, 1.05*mm , -2.70*mm , rot)); \n cel->AddNode(cat,3,new TGeoCombiTrans (0, -1.05*mm , -2.70*mm , rot)); \n cel->AddNode(ano,2,new TGeoCombiTrans (0, -2.00*mm , -0.29*mm , rot)); \n cel->AddNode(cat,4,new TGeoCombiTrans (0, -3.15*mm , -2.70*mm , rot)); \n cel->AddNode(pad,1,new TGeoTranslation(0, 0.00*mm , 2.25*mm)); \/\/1 pad \n sec->AddNode(ppf,1,new TGeoTranslation(0,0, 2.75*mm));\n\/\/ ^ Y single cell 5.5mm CH4 = 1*mm CsI + 4.45*mm CsI x cath +0.05*mm safety margin \n\/\/ | ______________________________ \n\/\/ | | | ^ || \n\/\/ | | 1.05mm || \n\/\/ 2.2*mm| xxxxxxxxxxxxxxxxxxxxxxxxxxxx |-- 50um x || cat shift x=0mm , y= 3.15mm , z=-2.70mm \n\/\/ | | || \n\/\/ | | || \n\/\/ __ | .......................... | 2.1mm 20un . || ano shift x=0mm , y= 2.00mm , z=-0.29mm \n\/\/ | | || \n\/\/ | | || \n\/\/ | xxxxxxxxxxxxxxxxxxxxxxxxxxxx |-- x || cat shift x=0mm , y= 1.05mm , z=-2.70mm \n\/\/ | | || \n\/\/ | | 8.4mm || \n\/\/ 4*mm | | 2.1mm || pad shift x=0mm , y= 0.00mm , z=2.25*mm \n\/\/ | | || \n\/\/ | | || \n\/\/ | xxxxxxxxxxxxxxxxxxxxxxxxxxxx |-- x || cat shift x=0mm , y=-1.05mm , z=-2.70mm \n\/\/ | | || \n\/\/ | | || \n\/\/ __ | .......................... | 2.1mm . 2.04mm|| ano shift x=0mm , y=-2.00mm , z=-0.29mm \n\/\/ | | || \n\/\/ | | || \n\/\/ | xxxxxxxxxxxxxxxxxxxxxxxxxxxx |-- x 4.45mm || cat shift x=0mm , y=-3.15mm , z=-2.70mm \n\/\/ 2.2*mm| | || \n\/\/ | | 1.05mm || \n\/\/ |______________________________| v || \n\/\/ < 8 mm > \n\/\/ ----->X ----->Z\n ppf->AddNode(lar,1,new TGeoTranslation(-224.5*mm,-151.875*mm, 0.85*mm));\n ppf->AddNode(lar,2,new TGeoTranslation(-224.5*mm,- 50.625*mm, 0.85*mm));\n ppf->AddNode(lar,3,new TGeoTranslation(-224.5*mm,+ 50.625*mm, 0.85*mm));\n ppf->AddNode(lar,4,new TGeoTranslation(-224.5*mm,+151.875*mm, 0.85*mm));\n ppf->AddNode(lar,5,new TGeoTranslation(+224.5*mm,-151.875*mm, 0.85*mm));\n ppf->AddNode(lar,6,new TGeoTranslation(+224.5*mm,- 50.625*mm, 0.85*mm));\n ppf->AddNode(lar,7,new TGeoTranslation(+224.5*mm,+ 50.625*mm, 0.85*mm));\n ppf->AddNode(lar,8,new TGeoTranslation(+224.5*mm,+151.875*mm, 0.85*mm));\n ppf->AddNode(smo,1,new TGeoTranslation(- 65.0*mm,-151.875*mm, 0.85*mm));\n ppf->AddNode(smo,2,new TGeoTranslation(- 65.0*mm,- 50.625*mm, 0.85*mm));\n ppf->AddNode(smo,3,new TGeoTranslation(- 65.0*mm,+ 50.625*mm, 0.85*mm));\n ppf->AddNode(smo,4,new TGeoTranslation(- 65.0*mm,+151.875*mm, 0.85*mm));\n ppf->AddNode(smo,5,new TGeoTranslation(+ 65.0*mm,-151.875*mm, 0.85*mm));\n ppf->AddNode(smo,6,new TGeoTranslation(+ 65.0*mm,- 50.625*mm, 0.85*mm));\n ppf->AddNode(smo,7,new TGeoTranslation(+ 65.0*mm,+ 50.625*mm, 0.85*mm));\n ppf->AddNode(smo,8,new TGeoTranslation(+ 65.0*mm,+151.875*mm, 0.85*mm)); \n}\/\/Hmpid()\n\/\/++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nvoid Axis()\n{\n\/\/ Draw axises on top of geometry\n Double_t X[6]={0,0,0,300,0,0}; Double_t Y[6]={0,0,0,0,300,0}; Double_t Z[6]={0,0,0,0,0,300};\n TPolyLine3D *pXaxis=new TPolyLine3D(2,X);pXaxis->SetLineColor(kRed); pXaxis->Draw();\n TPolyLine3D *pYaxis=new TPolyLine3D(2,Y);pYaxis->SetLineColor(kGreen); pYaxis->Draw();\n TPolyLine3D *pZaxis=new TPolyLine3D(2,Z);pZaxis->SetLineColor(kBlue); pZaxis->Draw();\n}\n\/\/++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nHgeom is no longer neede as functionality in v2<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"Exceptions.h\"\n#include \"Histogram.h\"\n#include \"BasicStatistics.h\"\n#include \"Helper.h\"\n#include \"Log.h\"\n#include \n#include \n#include \n\nHistogram::Histogram(double min, double max, double bin_size)\n\t: min_(min)\n\t, max_(max)\n\t, bin_size_(bin_size)\n\t, bin_sum_(0)\n{\n\tif (bin_size_<=0)\n\t{\n\t\tTHROW(StatisticsException,\"Cannot initialize histogram with non-positive bin size!\");\n\t}\n\n\tif (min_>=max_)\n\t{\n\t\tTHROW(StatisticsException,\"Cannot initialize histogram with empty range!\");\n\t}\n\n\tbins_.resize(ceil((max_-min_)\/bin_size_));\n}\n\ndouble Histogram::min() const\n{\n\treturn min_;\n}\n\ndouble Histogram::max() const\n{\n\treturn max_;\n}\n\ndouble Histogram::maxValue(bool as_percentage) const\n{\n\tif (bins_.size()==0)\n\t{\n\t\tTHROW(StatisticsException,\"No bins present!\");\n\t}\n\n\tdouble max = *(std::max_element(bins_.begin(), bins_.end()));\n\tif(as_percentage)\n\t{\n\t\treturn 100.0 * max \/ (double)bin_sum_;\n\t}\n\treturn max;\n}\n\ndouble Histogram::minValue(bool as_percentage) const\n{\n\tif (bins_.size()==0)\n\t{\n\t\tTHROW(StatisticsException,\"No bins present!\");\n\t}\n\n\tdouble min = *(std::min_element(bins_.begin(), bins_.end()));\n\tif(as_percentage)\n\t{\n\t\treturn 100.0 * min \/ (double)bin_sum_;\n\t}\n\treturn min;\n}\n\ndouble Histogram::binSize() const\n{\n\treturn bin_size_;\n}\n\nint Histogram::binCount() const\n{\n\treturn bins_.size();\n}\n\nint Histogram::binSum()\n{\n\treturn bin_sum_;\n}\n\ndouble Histogram::binValue(int index, bool as_percentage) const\n{\n\tif (index<0 || index>=(int)bins_.size())\n\t{\n THROW(StatisticsException,\"Index \" + QString::number(index) + \" out of range (0-\" + QString::number(bins_.size()-1) + \")!\");\n\t}\n\n\tdouble value = bins_[index];\n\tif(as_percentage)\n\t{\n\t\treturn 100.0 * value \/ (double)bin_sum_;\n\t}\n\treturn value;\n}\n\ndouble Histogram::startOfBin(int index) const\n{\n\tif (index<0 || index>=(int)bins_.size())\n\t{\n THROW(StatisticsException,\"Index \" + QString::number(index) + \" out of range (0-\" + QString::number(bins_.size()-1) + \")!\");\n\t}\n\n return bin_size_*index + min_;\n}\n\ndouble Histogram::binValue(double val, bool as_percentage) const\n{\n\tdouble value = bins_[binIndex(val)];\n\tif(as_percentage)\n\t{\n\t\treturn 100.0 * value \/ (double)bin_sum_;\n\t}\n\treturn value;\n}\n\nvoid Histogram::inc(double val, bool ignore_bounds_errors)\n{\n\tif (ignore_bounds_errors)\n\t{\n\t\tval = BasicStatistics::bound(val, min_, max_);\n\t}\n\n\tbins_[binIndex(val)]+=1;\n\tbin_sum_ += 1;\n}\n\nvoid Histogram::inc(const QVector& data, bool ignore_bounds_errors)\n{\n\tfor (int i=0; i max_)\n\t{\n\t\tTHROW(StatisticsException, \"Requested position '\" + QString::number(val) + \"' not in range (\" + QString::number(min_) + \"-\" + QString::number(max_) + \")!\");\n\t}\n\n\tint index = floor ( (val-min_) \/ (max_-min_) * bins_.size());\n\tindex = std::max(0, index);\n\tindex = std::min(index, (int)(bins_.size()-1));\n\n\treturn index;\n}\n\n\nvoid Histogram::print(QTextStream& stream, QString indentation, int position_precision, int data_precision, bool ascending) const\n{\n for (int i=0; i Histogram::xCoords()\n{\n\treturn BasicStatistics::range(binCount(), startOfBin(0) + 0.5 * binSize(), binSize());\n}\n\nQVector Histogram::yCoords(bool as_percentage)\n{\n\tif (as_percentage)\n\t{\n\t\tQVector tmp(bins_);\n\t\tfor (int i=0; i x = xCoords();\n\tQVector y = yCoords();\n\tfor (int i=0; iHistogram: updated plotting function.#include \n#include \n#include \n\n#include \"Exceptions.h\"\n#include \"Histogram.h\"\n#include \"BasicStatistics.h\"\n#include \"Helper.h\"\n#include \"Log.h\"\n#include \n#include \n#include \n\nHistogram::Histogram(double min, double max, double bin_size)\n\t: min_(min)\n\t, max_(max)\n\t, bin_size_(bin_size)\n\t, bin_sum_(0)\n{\n\tif (bin_size_<=0)\n\t{\n\t\tTHROW(StatisticsException,\"Cannot initialize histogram with non-positive bin size!\");\n\t}\n\n\tif (min_>=max_)\n\t{\n\t\tTHROW(StatisticsException,\"Cannot initialize histogram with empty range!\");\n\t}\n\n\tbins_.resize(ceil((max_-min_)\/bin_size_));\n}\n\ndouble Histogram::min() const\n{\n\treturn min_;\n}\n\ndouble Histogram::max() const\n{\n\treturn max_;\n}\n\ndouble Histogram::maxValue(bool as_percentage) const\n{\n\tif (bins_.size()==0)\n\t{\n\t\tTHROW(StatisticsException,\"No bins present!\");\n\t}\n\n\tdouble max = *(std::max_element(bins_.begin(), bins_.end()));\n\tif(as_percentage)\n\t{\n\t\treturn 100.0 * max \/ (double)bin_sum_;\n\t}\n\treturn max;\n}\n\ndouble Histogram::minValue(bool as_percentage) const\n{\n\tif (bins_.size()==0)\n\t{\n\t\tTHROW(StatisticsException,\"No bins present!\");\n\t}\n\n\tdouble min = *(std::min_element(bins_.begin(), bins_.end()));\n\tif(as_percentage)\n\t{\n\t\treturn 100.0 * min \/ (double)bin_sum_;\n\t}\n\treturn min;\n}\n\ndouble Histogram::binSize() const\n{\n\treturn bin_size_;\n}\n\nint Histogram::binCount() const\n{\n\treturn bins_.size();\n}\n\nint Histogram::binSum()\n{\n\treturn bin_sum_;\n}\n\ndouble Histogram::binValue(int index, bool as_percentage) const\n{\n\tif (index<0 || index>=(int)bins_.size())\n\t{\n THROW(StatisticsException,\"Index \" + QString::number(index) + \" out of range (0-\" + QString::number(bins_.size()-1) + \")!\");\n\t}\n\n\tdouble value = bins_[index];\n\tif(as_percentage)\n\t{\n\t\treturn 100.0 * value \/ (double)bin_sum_;\n\t}\n\treturn value;\n}\n\ndouble Histogram::startOfBin(int index) const\n{\n\tif (index<0 || index>=(int)bins_.size())\n\t{\n THROW(StatisticsException,\"Index \" + QString::number(index) + \" out of range (0-\" + QString::number(bins_.size()-1) + \")!\");\n\t}\n\n return bin_size_*index + min_;\n}\n\ndouble Histogram::binValue(double val, bool as_percentage) const\n{\n\tdouble value = bins_[binIndex(val)];\n\tif(as_percentage)\n\t{\n\t\treturn 100.0 * value \/ (double)bin_sum_;\n\t}\n\treturn value;\n}\n\nvoid Histogram::inc(double val, bool ignore_bounds_errors)\n{\n\tif (ignore_bounds_errors)\n\t{\n\t\tval = BasicStatistics::bound(val, min_, max_);\n\t}\n\n\tbins_[binIndex(val)]+=1;\n\tbin_sum_ += 1;\n}\n\nvoid Histogram::inc(const QVector& data, bool ignore_bounds_errors)\n{\n\tfor (int i=0; i max_)\n\t{\n\t\tTHROW(StatisticsException, \"Requested position '\" + QString::number(val) + \"' not in range (\" + QString::number(min_) + \"-\" + QString::number(max_) + \")!\");\n\t}\n\n\tint index = floor ( (val-min_) \/ (max_-min_) * bins_.size());\n\tindex = std::max(0, index);\n\tindex = std::min(index, (int)(bins_.size()-1));\n\n\treturn index;\n}\n\n\nvoid Histogram::print(QTextStream& stream, QString indentation, int position_precision, int data_precision, bool ascending) const\n{\n for (int i=0; i Histogram::xCoords()\n{\n\treturn BasicStatistics::range(binCount(), startOfBin(0) + 0.5 * binSize(), binSize());\n}\n\nQVector Histogram::yCoords(bool as_percentage)\n{\n\tif (as_percentage)\n\t{\n\t\tQVector tmp(bins_);\n\t\tfor (int i=0; i x = xCoords();\n\tQVector y = yCoords();\n\tfor (int i=0; i"} {"text":"#include \"MainWindow.h\"\n\n#include \n#include \n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent), stars(0)\n{\n setupUi(this);\n connect(north, &QPushButton::click, this, &MainWindow::doSomething);\n connect(south, &QPushButton::click, this, &MainWindow::doSomething);\n connect(east, &QPushButton::click, this, &MainWindow::doSomething);\n connect(west, &QPushButton::click, this, &MainWindow::doSomething);\n connect(inventory, &QPushButton::click, this, &MainWindow::doInventory);\n description->setHtml(tr(\"

You've been sent on an epic quest (imagine some backstory involving an inn, a suspiciously peppy bard and a threat to middle earth as you know it) to delve deep into the tunnels beneath github, and retrieve the seven<\/s> ten stars!<\/p>

After a long and tedious journey in which we get some character origin stories, you end up in the dungeons.<\/p>\"));\n doPrompt();\n}\n\nvoid MainWindow::changeEvent(QEvent *e)\n{\n QMainWindow::changeEvent(e);\n switch (e->type()) {\n case QEvent::LanguageChange:\n retranslateUi(this);\n break;\n default:\n break;\n }\n}\n\nvoid MainWindow::doSomething()\n{\n\n}\n\nvoid MainWindow::doInventory()\n{\n description->append(tr(\"

You have:
%1 stars
no tea<\/p>\").arg(stars));\n}\n\nvoid MainWindow::prompt()\n{\n description->append(\"

What now?<\/p>\");\n}\nMaze of twisty little commit messages#include \"MainWindow.h\"\n\n#include \n#include \n\n#include \n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent), stars(0)\n{\n setupUi(this);\n connect(north, &QPushButton::click, this, &MainWindow::doSomething);\n connect(south, &QPushButton::click, this, &MainWindow::doSomething);\n connect(east, &QPushButton::click, this, &MainWindow::doSomething);\n connect(west, &QPushButton::click, this, &MainWindow::doSomething);\n connect(inventory, &QPushButton::click, this, &MainWindow::doInventory);\n description->setHtml(tr(\"

You've been sent on an epic quest (imagine\"\n \" some backstory involving an inn, a suspiciously\"\n \" peppy bard and a threat to middle earth as you\"\n \" know it) to delve deep into the tunnels beneath\"\n \" github, and retrieve the seven<\/s> ten stars!<\/p>\"\n \"

After a long and tedious journey in which we get\"\n \" some character origin stories, you end up in the\"\n \" dungeons.<\/p>\"));\n prompt();\n}\n\nvoid MainWindow::changeEvent(QEvent *e)\n{\n QMainWindow::changeEvent(e);\n switch (e->type()) {\n case QEvent::LanguageChange:\n retranslateUi(this);\n break;\n default:\n break;\n }\n}\n\nvoid MainWindow::doSomething()\n{\n int i = random() % 4;\n north->setEnabled(i != 0);\n south->setEnabled(i != 1);\n east->setEnabled(i != 2);\n west->setEnabled(i != 3);\n\n QString twisty;\n switch (i) {\n case 0:\n twisty = tr(\"twisty little maze of passages\");\n break;\n case 1:\n twisty = tr(\"maze of twisty little passages\");\n break;\n case 2:\n twisty = tr(\"little twisty maze of passages\");\n break;\n default:\n twisty = tr(\"twisty maze of little passages\");\n }\n\n if(random() % 3) {\n\n }\n}\n\nvoid MainWindow::doInventory()\n{\n description->append(tr(\"

You have:
%1 stars
no tea<\/p>\").arg(stars));\n}\n\nvoid MainWindow::prompt()\n{\n description->append(\"

What now?<\/p>\");\n}\n<|endoftext|>"} {"text":"#ifndef _SNARKFRONT_SHA_512_224_HPP_\n#define _SNARKFRONT_SHA_512_224_HPP_\n\n#include \n#include \n#include \"Alg.hpp\"\n#include \"Alg_uint.hpp\"\n#include \"AST.hpp\"\n#include \"BitwiseOps.hpp\"\n#include \"Lazy.hpp\"\n#include \"SHA_512.hpp\"\n\nnamespace snarkfront {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SHA-512\/224\n\/\/\n\ntemplate \nclass SHA_512_224 : public SHA_512\n{\npublic:\n typedef T WordType;\n typedef std::array MsgType;\n typedef std::array DigType;\n\n SHA_512_224()\n : m_setDigest(false)\n {}\n\n \/\/ overrides base class SHA-512\n const std::array& digest() {\n if (m_setDigest) {\n for (std::size_t i = 0; i < 3; ++i) {\n \/\/ high 32 bits\n m_Hleft224[2*i] = F::xword(F::SHR(\n this->m_H[i],\n 32));\n\n \/\/ low 32 bits\n m_Hleft224[2*i + 1] = F::xword(F::SHR(\n F::SHL(\n this->m_H[i],\n 32),\n 32));\n }\n\n \/\/ high 32 bits\n m_Hleft224[6] = F::xword(F::SHR(\n this->m_H[3],\n 32));\n\n m_setDigest = false;\n }\n\n return m_Hleft224;\n }\n\n \/\/ overrides base class SHA-512\n virtual void initHashValue() {\n \/\/ set initial hash value (NIST FIPS 180-4 section 5.3.6.1)\n const std::array a {\n 0x8C3D37C819544DA2, 0x73E1996689DCD4D6,\n 0x1DFAB7AE32FF9C82, 0x679DD514582F9FCF,\n\n 0x0F6D2B697BD44DA8, 0x77E36F7304C48942,\n 0x3F9D85A86A1D36C8, 0x1112E6AD91D692A1 };\n\n for (std::size_t i = 0; i < 8; ++i) {\n this->m_H[i] = F::constant(a[i]);\n }\n }\n\n virtual void afterHash() {\n m_setDigest = true;\n }\n\nprivate:\n \/\/ truncated 224-bit message digest\n std::array m_Hleft224;\n\n bool m_setDigest;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ typedefs\n\/\/\n\nnamespace zk {\n template using\n SHA512_224 = SHA_512_224>,\n AST_Var>,\n Lazy>, std::uint64_t>,\n SHA_Functions>,\n AST_Op>,\n BitwiseAST, Alg_uint32>>>;\n} \/\/ namespace zk\n\nnamespace eval {\n typedef SHA_512_224>>\n SHA512_224;\n} \/\/ namespace eval\n\n} \/\/ namespace snarkfront\n\n#endif\n8-bit unsigned int array pre-image#ifndef _SNARKFRONT_SHA_512_224_HPP_\n#define _SNARKFRONT_SHA_512_224_HPP_\n\n#include \n#include \n#include \"Alg.hpp\"\n#include \"Alg_uint.hpp\"\n#include \"AST.hpp\"\n#include \"BitwiseOps.hpp\"\n#include \"Lazy.hpp\"\n#include \"SHA_512.hpp\"\n\nnamespace snarkfront {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SHA-512\/224\n\/\/\n\ntemplate \nclass SHA_512_224 : public SHA_512\n{\npublic:\n typedef T WordType;\n typedef U ByteType;\n\n typedef std::array MsgType;\n typedef std::array DigType;\n typedef std::array PreType;\n\n SHA_512_224()\n : m_setDigest(false)\n {}\n\n \/\/ overrides base class SHA-512\n const std::array& digest() {\n if (m_setDigest) {\n for (std::size_t i = 0; i < 3; ++i) {\n \/\/ high 32 bits\n m_Hleft224[2*i] = F::xword(F::SHR(\n this->m_H[i],\n 32));\n\n \/\/ low 32 bits\n m_Hleft224[2*i + 1] = F::xword(F::SHR(\n F::SHL(\n this->m_H[i],\n 32),\n 32));\n }\n\n \/\/ high 32 bits\n m_Hleft224[6] = F::xword(F::SHR(\n this->m_H[3],\n 32));\n\n m_setDigest = false;\n }\n\n return m_Hleft224;\n }\n\n \/\/ overrides base class SHA-512\n virtual void initHashValue() {\n \/\/ set initial hash value (NIST FIPS 180-4 section 5.3.6.1)\n const std::array a {\n 0x8C3D37C819544DA2, 0x73E1996689DCD4D6,\n 0x1DFAB7AE32FF9C82, 0x679DD514582F9FCF,\n\n 0x0F6D2B697BD44DA8, 0x77E36F7304C48942,\n 0x3F9D85A86A1D36C8, 0x1112E6AD91D692A1 };\n\n for (std::size_t i = 0; i < 8; ++i) {\n this->m_H[i] = F::constant(a[i]);\n }\n }\n\n virtual void afterHash() {\n m_setDigest = true;\n }\n\nprivate:\n \/\/ truncated 224-bit message digest\n std::array m_Hleft224;\n\n bool m_setDigest;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ typedefs\n\/\/\n\nnamespace zk {\n template using\n SHA512_224 = SHA_512_224>,\n AST_Var>,\n Lazy>, std::uint64_t>,\n AST_Var>,\n SHA_Functions>,\n AST_Op>,\n BitwiseAST, Alg_uint32>>>;\n} \/\/ namespace zk\n\nnamespace eval {\n typedef SHA_512_224>>\n SHA512_224;\n} \/\/ namespace eval\n\n} \/\/ namespace snarkfront\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \"Skeletonize.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nutil::ProgramOption optionSkeletonBoundaryWeight(\n\t\tutil::_long_name = \"skeletonBoundaryWeight\",\n\t\tutil::_description_text = \"The weight of the boundary term to find the tube's skeletons.\",\n\t\tutil::_default_value = 1);\n\nutil::ProgramOption optionSkeletonMaxNumSegments(\n\t\tutil::_long_name = \"skeletonMaxNumSegments\",\n\t\tutil::_description_text = \"The maximal number of segments to extract for a skeleton.\",\n\t\tutil::_default_value = 10);\n\nutil::ProgramOption optionSkeletonMinSegmentLength(\n\t\tutil::_long_name = \"skeletonMinSegmentLength\",\n\t\tutil::_description_text = \"The mininal length of a segment (including the boundary penalty) to extract for a skeleton.\",\n\t\tutil::_default_value = 0);\n\nutil::ProgramOption optionSkeletonMinSegmentLengthRatio(\n\t\tutil::_long_name = \"skeletonMinSegmentLengthRatio\",\n\t\tutil::_description_text = \"The mininal length of a segment (including the boundary penalty) as the ratio of the largest segment extracted for a skeleton.\",\n\t\tutil::_default_value = 1);\n\nutil::ProgramOption optionSkeletonSkipExplainedNodes(\n\t\tutil::_long_name = \"skeletonSkipExplainedNodes\",\n\t\tutil::_description_text = \"Don't add segments to nodes that are already explained by the current skeleton. \"\n\t\t \"Nodes are explained, if they fall within a sphere around any current skeleton node. \"\n\t\t \"The size of the sphere is determined by boundary distance * skeletonExplanationWeight.\");\n\nutil::ProgramOption optionSkeletonExplanationWeight(\n\t\tutil::_long_name = \"skeletonExplanationWeight\",\n\t\tutil::_description_text = \"A factor to multiply with the boundary distance to create 'explanation spheres'. \"\n\t\t \"See skeletonSkipExplainedNodes.\",\n\t\tutil::_default_value = 1);\n\nlogger::LogChannel skeletonizelog(\"skeletonizelog\", \"[Skeletonize] \");\n\nSkeletonize::Skeletonize(const GraphVolume& graphVolume) :\n\t_boundaryDistance(\n\t\t\tvigra::Shape3(\n\t\t\t\t\tgraphVolume.getDiscreteBoundingBox().width() + 2,\n\t\t\t\t\tgraphVolume.getDiscreteBoundingBox().height() + 2,\n\t\t\t\t\tgraphVolume.getDiscreteBoundingBox().depth() + 2\n\t\t\t)),\n\t_graphVolume(graphVolume),\n\t_distanceMap(_graphVolume.graph()),\n\t_boundaryWeight(optionSkeletonBoundaryWeight),\n\t_dijkstra(_graphVolume.graph(), _distanceMap),\n\t_nodeLabels(_graphVolume.graph(), Inside),\n\t_minSegmentLength(optionSkeletonMinSegmentLength),\n\t_minSegmentLengthRatio(optionSkeletonMinSegmentLengthRatio),\n\t_skipExplainedNodes(optionSkeletonSkipExplainedNodes),\n\t_explanationWeight(optionSkeletonExplanationWeight) {}\n\nSkeleton\nSkeletonize::getSkeleton() {\n\n\tUTIL_TIME_METHOD;\n\n\tfindBoundaryNodes();\n\n\tinitializeEdgeMap();\n\n\tfindRoot();\n\n\tint maxNumSegments = optionSkeletonMaxNumSegments;\n\tint segmentsFound = 0;\n\twhile (extractLongestSegment() && ++segmentsFound < maxNumSegments) {}\n\n\treturn parseVolumeSkeleton();\n}\n\nvoid\nSkeletonize::findBoundaryNodes() {\n\n\tfor (GraphVolume::NodeIt node(_graphVolume.graph()); node != lemon::INVALID; ++node) {\n\n\t\tint numNeighbors = 0;\n\t\tfor (GraphVolume::IncEdgeIt e(_graphVolume.graph(), node); e != lemon::INVALID; ++e)\n\t\t\tnumNeighbors++;\n\n\t\tif (numNeighbors != GraphVolume::NumNeighbors) {\n\n\t\t\t_boundary.push_back(node);\n\t\t\t_nodeLabels[node] = Boundary;\n\t\t}\n\t}\n}\n\nvoid\nSkeletonize::initializeEdgeMap() {\n\n\t\/\/ the pitch is the number of units per voxel dimension\n\tfloat pitch[3];\n\tpitch[0] = _graphVolume.getResolutionX();\n\tpitch[1] = _graphVolume.getResolutionY();\n\tpitch[2] = _graphVolume.getResolutionZ();\n\n\t_boundaryDistance = 0;\n\tfor (GraphVolume::NodeIt n(_graphVolume.graph()); n != lemon::INVALID; ++n)\n\t\tboundaryDistance(_graphVolume.positions()[n]) = 1.0;\n\n\tif (_graphVolume.getDiscreteBoundingBox().depth() == 1) {\n\n\t\tLOG_DEBUG(skeletonizelog) << \"performing 2D distance transform for boundary penalty\" << std::endl;\n\n\t\t\/\/ perform 2D distance transform if depth is 1\n\t\tvigra::separableMultiDistSquared(\n\t\t\t\t_boundaryDistance.bind<2>(1), \/\/ only on center section (0 and 2 are padded)\n\t\t\t\t_boundaryDistance.bind<2>(1),\n\t\t\t\tfalse, \/* compute distance from object (non-zero) to background (0) *\/\n\t\t\t\tpitch);\n\n\t} else {\n\n\t\tvigra::separableMultiDistSquared(\n\t\t\t\t_boundaryDistance,\n\t\t\t\t_boundaryDistance,\n\t\t\t\tfalse, \/* compute distance from object (non-zero) to background (0) *\/\n\t\t\t\tpitch);\n\t}\n\n\t\/\/ find center point with maximal boundary distance\n\t_maxBoundaryDistance2 = 0;\n\tfor (GraphVolume::NodeIt node(_graphVolume.graph()); node != lemon::INVALID; ++node) {\n\n\t\tconst Position& pos = _graphVolume.positions()[node];\n\t\tif (boundaryDistance(pos) > _maxBoundaryDistance2) {\n\n\t\t\t_center = node;\n\t\t\t_maxBoundaryDistance2 = boundaryDistance(pos);\n\t\t}\n\t}\n\n\t\/\/ create initial edge map from boundary penalty\n\tfor (GraphVolume::EdgeIt e(_graphVolume.graph()); e != lemon::INVALID; ++e)\n\t\t_distanceMap[e] = boundaryPenalty(\n\t\t\t\t0.5*(\n\t\t\t\t\t\tboundaryDistance(_graphVolume.positions()[_graphVolume.graph().u(e)]) +\n\t\t\t\t\t\tboundaryDistance(_graphVolume.positions()[_graphVolume.graph().v(e)])));\n\n\t\/\/ multiply with Euclidean node distances\n\t\/\/\n\t\/\/ The TEASAR paper suggests to add the Euclidean distances. However, for \n\t\/\/ the penalty to be meaningful in anistotropic volumes, it should be \n\t\/\/ multiplied with the Euclidean distance between the nodes (otherwise, it \n\t\/\/ is more expensive to move in the high-resolution dimensions). Therefore, \n\t\/\/ the final value is\n\t\/\/\n\t\/\/ penalty*euclidean + euclidean = euclidean*(penalty + 1)\n\n\tfloat nodeDistances[8];\n\tnodeDistances[0] = 0;\n\tnodeDistances[1] = _graphVolume.getResolutionZ();\n\tnodeDistances[2] = _graphVolume.getResolutionY();\n\tnodeDistances[3] = sqrt(pow(_graphVolume.getResolutionY(), 2) + pow(_graphVolume.getResolutionZ(), 2));\n\tnodeDistances[4] = _graphVolume.getResolutionX();\n\tnodeDistances[5] = sqrt(pow(_graphVolume.getResolutionX(), 2) + pow(_graphVolume.getResolutionZ(), 2));\n\tnodeDistances[6] = sqrt(pow(_graphVolume.getResolutionX(), 2) + pow(_graphVolume.getResolutionY(), 2));\n\tnodeDistances[7] = sqrt(pow(_graphVolume.getResolutionX(), 2) + pow(_graphVolume.getResolutionY(), 2) + pow(_graphVolume.getResolutionZ(), 2));\n\n\tfor (GraphVolume::EdgeIt e(_graphVolume.graph()); e != lemon::INVALID; ++e) {\n\n\t\tPosition u = _graphVolume.positions()[_graphVolume.graph().u(e)];\n\t\tPosition v = _graphVolume.positions()[_graphVolume.graph().v(e)];\n\n\t\tint i = 0;\n\t\tif (u[0] != v[0]) i |= 4;\n\t\tif (u[1] != v[1]) i |= 2;\n\t\tif (u[2] != v[2]) i |= 1;\n\n\t\t_distanceMap[e] = nodeDistances[i]*(_distanceMap[e] + 1);\n\t}\n}\n\nvoid\nSkeletonize::findRoot() {\n\n\t_dijkstra.run(_center);\n\n\t\/\/ find furthest point on boundary\n\t_root = GraphVolume::NodeIt(_graphVolume.graph());\n\tfloat maxValue = -1;\n\tfor (GraphVolume::Node n : _boundary) {\n\t\tif (_dijkstra.distMap()[n] > maxValue) {\n\n\t\t\t_root = n;\n\t\t\tmaxValue = _dijkstra.distMap()[n];\n\t\t}\n\t}\n\n\tif (maxValue == -1)\n\t\tUTIL_THROW_EXCEPTION(\n\t\t\t\tNoNodeFound,\n\t\t\t\t\"could not find a root boundary point\");\n\n\t\/\/ mark root as being part of skeleton\n\t_nodeLabels[_root] = OnSkeleton;\n}\n\nbool\nSkeletonize::extractLongestSegment() {\n\n\t_dijkstra.run(_root);\n\n\t\/\/ find furthest point on boundary\n\tGraphVolume::Node furthest = GraphVolume::NodeIt(_graphVolume.graph());\n\tfloat maxValue = -1;\n\tfor (GraphVolume::Node n : _boundary) {\n\n\t\tif (_skipExplainedNodes && _nodeLabels[n] == Explained)\n\t\t\tcontinue;\n\n\t\tif (_dijkstra.distMap()[n] > maxValue) {\n\n\t\t\tfurthest = n;\n\t\t\tmaxValue = _dijkstra.distMap()[n];\n\t\t}\n\t}\n\n\t\/\/ no more points or length smaller then min segment length\n\tif (maxValue == -1 || maxValue < _minSegmentLength)\n\t\treturn false;\n\n\tLOG_DEBUG(skeletonizelog) << \"extracting segment with length \" << maxValue << std::endl;\n\n\tGraphVolume::Node n = furthest;\n\n\t\/\/ walk backwards to next skeleton point\n\twhile (_nodeLabels[n] != OnSkeleton) {\n\n\t\t_nodeLabels[n] = OnSkeleton;\n\n\t\tif (_skipExplainedNodes)\n\t\t\tdrawExplanationSphere(_graphVolume.positions()[n]);\n\n\t\tGraphVolume::Edge pred = _dijkstra.predMap()[n];\n\t\tGraphVolume::Node u = _graphVolume.graph().u(pred);\n\t\tGraphVolume::Node v = _graphVolume.graph().v(pred);\n\n\t\tn = (u == n ? v : u);\n\n\t\t_distanceMap[pred] = 0.0;\n\t}\n\n\t\/\/ first segment?\n\tif (n == _root) {\n\n\t\tLOG_DEBUG(skeletonizelog) << \"longest segment has length \" << maxValue << std::endl;\n\n\t\t_minSegmentLength = std::max(_minSegmentLength, _minSegmentLengthRatio*maxValue);\n\n\t\tLOG_DEBUG(skeletonizelog) << \"setting min segment length to \" << _minSegmentLength << std::endl;\n\t}\n\n\treturn true;\n}\n\nvoid\nSkeletonize::drawExplanationSphere(const Position& center) {\n\n\tdouble radius2 = boundaryDistance(center)*pow(_explanationWeight, 2);\n\n\tdouble resX2 = pow(_graphVolume.getResolutionX(), 2);\n\tdouble resY2 = pow(_graphVolume.getResolutionY(), 2);\n\tdouble resZ2 = pow(_graphVolume.getResolutionZ(), 2);\n\n\tfor (GraphVolume::Node n : _boundary) {\n\n\t\tconst Position& pos = _graphVolume.positions()[n];\n\t\tdouble distance2 =\n\t\t\t\tresX2*pow(pos[0] - center[0], 2) +\n\t\t\t\tresY2*pow(pos[1] - center[1], 2) +\n\t\t\t\tresZ2*pow(pos[2] - center[2], 2);\n\n\t\tif (distance2 <= radius2)\n\t\t\tif (_nodeLabels[n] != OnSkeleton)\n\t\t\t\t_nodeLabels[n] = Explained;\n\t}\n}\n\ndouble\nSkeletonize::boundaryPenalty(double boundaryDistance) {\n\n\t\/\/ penalty = w*(1.0 - bd\/max_bd)\n\t\/\/\n\t\/\/ w : boundary weight\n\t\/\/ bd : boundary distance\n\t\/\/ max_bd: max boundary distance\n\treturn _boundaryWeight*(1.0 - sqrt(boundaryDistance\/_maxBoundaryDistance2));\n}\n\nSkeleton\nSkeletonize::parseVolumeSkeleton() {\n\n\tSkeleton skeleton;\n\n\tskeleton.setOffset(_graphVolume.getOffset());\n\tskeleton.setResolution(_graphVolume.getResolution());\n\n\ttraverse(_root, skeleton);\n\n\treturn skeleton;\n}\n\nvoid\nSkeletonize::traverse(const GraphVolume::Node& n, Skeleton& skeleton) {\n\n\tPosition pos = _graphVolume.positions()[n];\n\n\t_nodeLabels[n] = Visited;\n\n\tint neighbors = numNeighbors(n);\n\tbool isNode = (neighbors != 2);\n\n\tif (isNode || n == _root)\n\t\tskeleton.openSegment(pos, sqrt(boundaryDistance(pos)));\n\telse\n\t\tskeleton.extendSegment(pos, sqrt(boundaryDistance(pos)));\n\n\tfor (GraphVolume::IncEdgeIt e(_graphVolume.graph(), n); e != lemon::INVALID && neighbors > 0; ++e) {\n\n\t\tif (_distanceMap[e] != 0.0)\n\t\t\tcontinue;\n\n\t\tGraphVolume::Node neighbor = (_graphVolume.graph().u(e) == n ? _graphVolume.graph().v(e) : _graphVolume.graph().u(e));\n\n\t\tneighbors--;\n\n\t\tif (_nodeLabels[neighbor] != Visited)\n\t\t\ttraverse(neighbor, skeleton);\n\t}\n\n\tif (isNode || n == _root)\n\t\tskeleton.closeSegment();\n}\n\nint\nSkeletonize::numNeighbors(const GraphVolume::Node& n) {\n\n\tint num = 0;\n\n\tfor (GraphVolume::IncEdgeIt e(_graphVolume.graph(), n); e != lemon::INVALID; ++e)\n\t\tif (_distanceMap[e] == 0.0)\n\t\t\tnum++;\n\n\treturn num;\n}\n\nRefactor Skeletonize::traverse to avoid deep recursion.#include \n#include \"Skeletonize.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nutil::ProgramOption optionSkeletonBoundaryWeight(\n\t\tutil::_long_name = \"skeletonBoundaryWeight\",\n\t\tutil::_description_text = \"The weight of the boundary term to find the tube's skeletons.\",\n\t\tutil::_default_value = 1);\n\nutil::ProgramOption optionSkeletonMaxNumSegments(\n\t\tutil::_long_name = \"skeletonMaxNumSegments\",\n\t\tutil::_description_text = \"The maximal number of segments to extract for a skeleton.\",\n\t\tutil::_default_value = 10);\n\nutil::ProgramOption optionSkeletonMinSegmentLength(\n\t\tutil::_long_name = \"skeletonMinSegmentLength\",\n\t\tutil::_description_text = \"The mininal length of a segment (including the boundary penalty) to extract for a skeleton.\",\n\t\tutil::_default_value = 0);\n\nutil::ProgramOption optionSkeletonMinSegmentLengthRatio(\n\t\tutil::_long_name = \"skeletonMinSegmentLengthRatio\",\n\t\tutil::_description_text = \"The mininal length of a segment (including the boundary penalty) as the ratio of the largest segment extracted for a skeleton.\",\n\t\tutil::_default_value = 1);\n\nutil::ProgramOption optionSkeletonSkipExplainedNodes(\n\t\tutil::_long_name = \"skeletonSkipExplainedNodes\",\n\t\tutil::_description_text = \"Don't add segments to nodes that are already explained by the current skeleton. \"\n\t\t \"Nodes are explained, if they fall within a sphere around any current skeleton node. \"\n\t\t \"The size of the sphere is determined by boundary distance * skeletonExplanationWeight.\");\n\nutil::ProgramOption optionSkeletonExplanationWeight(\n\t\tutil::_long_name = \"skeletonExplanationWeight\",\n\t\tutil::_description_text = \"A factor to multiply with the boundary distance to create 'explanation spheres'. \"\n\t\t \"See skeletonSkipExplainedNodes.\",\n\t\tutil::_default_value = 1);\n\nlogger::LogChannel skeletonizelog(\"skeletonizelog\", \"[Skeletonize] \");\n\nSkeletonize::Skeletonize(const GraphVolume& graphVolume) :\n\t_boundaryDistance(\n\t\t\tvigra::Shape3(\n\t\t\t\t\tgraphVolume.getDiscreteBoundingBox().width() + 2,\n\t\t\t\t\tgraphVolume.getDiscreteBoundingBox().height() + 2,\n\t\t\t\t\tgraphVolume.getDiscreteBoundingBox().depth() + 2\n\t\t\t)),\n\t_graphVolume(graphVolume),\n\t_distanceMap(_graphVolume.graph()),\n\t_boundaryWeight(optionSkeletonBoundaryWeight),\n\t_dijkstra(_graphVolume.graph(), _distanceMap),\n\t_nodeLabels(_graphVolume.graph(), Inside),\n\t_minSegmentLength(optionSkeletonMinSegmentLength),\n\t_minSegmentLengthRatio(optionSkeletonMinSegmentLengthRatio),\n\t_skipExplainedNodes(optionSkeletonSkipExplainedNodes),\n\t_explanationWeight(optionSkeletonExplanationWeight) {}\n\nSkeleton\nSkeletonize::getSkeleton() {\n\n\tUTIL_TIME_METHOD;\n\n\tfindBoundaryNodes();\n\n\tinitializeEdgeMap();\n\n\tfindRoot();\n\n\tint maxNumSegments = optionSkeletonMaxNumSegments;\n\tint segmentsFound = 0;\n\twhile (extractLongestSegment() && ++segmentsFound < maxNumSegments) {}\n\n\treturn parseVolumeSkeleton();\n}\n\nvoid\nSkeletonize::findBoundaryNodes() {\n\n\tfor (GraphVolume::NodeIt node(_graphVolume.graph()); node != lemon::INVALID; ++node) {\n\n\t\tint numNeighbors = 0;\n\t\tfor (GraphVolume::IncEdgeIt e(_graphVolume.graph(), node); e != lemon::INVALID; ++e)\n\t\t\tnumNeighbors++;\n\n\t\tif (numNeighbors != GraphVolume::NumNeighbors) {\n\n\t\t\t_boundary.push_back(node);\n\t\t\t_nodeLabels[node] = Boundary;\n\t\t}\n\t}\n}\n\nvoid\nSkeletonize::initializeEdgeMap() {\n\n\t\/\/ the pitch is the number of units per voxel dimension\n\tfloat pitch[3];\n\tpitch[0] = _graphVolume.getResolutionX();\n\tpitch[1] = _graphVolume.getResolutionY();\n\tpitch[2] = _graphVolume.getResolutionZ();\n\n\t_boundaryDistance = 0;\n\tfor (GraphVolume::NodeIt n(_graphVolume.graph()); n != lemon::INVALID; ++n)\n\t\tboundaryDistance(_graphVolume.positions()[n]) = 1.0;\n\n\tif (_graphVolume.getDiscreteBoundingBox().depth() == 1) {\n\n\t\tLOG_DEBUG(skeletonizelog) << \"performing 2D distance transform for boundary penalty\" << std::endl;\n\n\t\t\/\/ perform 2D distance transform if depth is 1\n\t\tvigra::separableMultiDistSquared(\n\t\t\t\t_boundaryDistance.bind<2>(1), \/\/ only on center section (0 and 2 are padded)\n\t\t\t\t_boundaryDistance.bind<2>(1),\n\t\t\t\tfalse, \/* compute distance from object (non-zero) to background (0) *\/\n\t\t\t\tpitch);\n\n\t} else {\n\n\t\tvigra::separableMultiDistSquared(\n\t\t\t\t_boundaryDistance,\n\t\t\t\t_boundaryDistance,\n\t\t\t\tfalse, \/* compute distance from object (non-zero) to background (0) *\/\n\t\t\t\tpitch);\n\t}\n\n\t\/\/ find center point with maximal boundary distance\n\t_maxBoundaryDistance2 = 0;\n\tfor (GraphVolume::NodeIt node(_graphVolume.graph()); node != lemon::INVALID; ++node) {\n\n\t\tconst Position& pos = _graphVolume.positions()[node];\n\t\tif (boundaryDistance(pos) > _maxBoundaryDistance2) {\n\n\t\t\t_center = node;\n\t\t\t_maxBoundaryDistance2 = boundaryDistance(pos);\n\t\t}\n\t}\n\n\t\/\/ create initial edge map from boundary penalty\n\tfor (GraphVolume::EdgeIt e(_graphVolume.graph()); e != lemon::INVALID; ++e)\n\t\t_distanceMap[e] = boundaryPenalty(\n\t\t\t\t0.5*(\n\t\t\t\t\t\tboundaryDistance(_graphVolume.positions()[_graphVolume.graph().u(e)]) +\n\t\t\t\t\t\tboundaryDistance(_graphVolume.positions()[_graphVolume.graph().v(e)])));\n\n\t\/\/ multiply with Euclidean node distances\n\t\/\/\n\t\/\/ The TEASAR paper suggests to add the Euclidean distances. However, for \n\t\/\/ the penalty to be meaningful in anistotropic volumes, it should be \n\t\/\/ multiplied with the Euclidean distance between the nodes (otherwise, it \n\t\/\/ is more expensive to move in the high-resolution dimensions). Therefore, \n\t\/\/ the final value is\n\t\/\/\n\t\/\/ penalty*euclidean + euclidean = euclidean*(penalty + 1)\n\n\tfloat nodeDistances[8];\n\tnodeDistances[0] = 0;\n\tnodeDistances[1] = _graphVolume.getResolutionZ();\n\tnodeDistances[2] = _graphVolume.getResolutionY();\n\tnodeDistances[3] = sqrt(pow(_graphVolume.getResolutionY(), 2) + pow(_graphVolume.getResolutionZ(), 2));\n\tnodeDistances[4] = _graphVolume.getResolutionX();\n\tnodeDistances[5] = sqrt(pow(_graphVolume.getResolutionX(), 2) + pow(_graphVolume.getResolutionZ(), 2));\n\tnodeDistances[6] = sqrt(pow(_graphVolume.getResolutionX(), 2) + pow(_graphVolume.getResolutionY(), 2));\n\tnodeDistances[7] = sqrt(pow(_graphVolume.getResolutionX(), 2) + pow(_graphVolume.getResolutionY(), 2) + pow(_graphVolume.getResolutionZ(), 2));\n\n\tfor (GraphVolume::EdgeIt e(_graphVolume.graph()); e != lemon::INVALID; ++e) {\n\n\t\tPosition u = _graphVolume.positions()[_graphVolume.graph().u(e)];\n\t\tPosition v = _graphVolume.positions()[_graphVolume.graph().v(e)];\n\n\t\tint i = 0;\n\t\tif (u[0] != v[0]) i |= 4;\n\t\tif (u[1] != v[1]) i |= 2;\n\t\tif (u[2] != v[2]) i |= 1;\n\n\t\t_distanceMap[e] = nodeDistances[i]*(_distanceMap[e] + 1);\n\t}\n}\n\nvoid\nSkeletonize::findRoot() {\n\n\t_dijkstra.run(_center);\n\n\t\/\/ find furthest point on boundary\n\t_root = GraphVolume::NodeIt(_graphVolume.graph());\n\tfloat maxValue = -1;\n\tfor (GraphVolume::Node n : _boundary) {\n\t\tif (_dijkstra.distMap()[n] > maxValue) {\n\n\t\t\t_root = n;\n\t\t\tmaxValue = _dijkstra.distMap()[n];\n\t\t}\n\t}\n\n\tif (maxValue == -1)\n\t\tUTIL_THROW_EXCEPTION(\n\t\t\t\tNoNodeFound,\n\t\t\t\t\"could not find a root boundary point\");\n\n\t\/\/ mark root as being part of skeleton\n\t_nodeLabels[_root] = OnSkeleton;\n}\n\nbool\nSkeletonize::extractLongestSegment() {\n\n\t_dijkstra.run(_root);\n\n\t\/\/ find furthest point on boundary\n\tGraphVolume::Node furthest = GraphVolume::NodeIt(_graphVolume.graph());\n\tfloat maxValue = -1;\n\tfor (GraphVolume::Node n : _boundary) {\n\n\t\tif (_skipExplainedNodes && _nodeLabels[n] == Explained)\n\t\t\tcontinue;\n\n\t\tif (_dijkstra.distMap()[n] > maxValue) {\n\n\t\t\tfurthest = n;\n\t\t\tmaxValue = _dijkstra.distMap()[n];\n\t\t}\n\t}\n\n\t\/\/ no more points or length smaller then min segment length\n\tif (maxValue == -1 || maxValue < _minSegmentLength)\n\t\treturn false;\n\n\tLOG_DEBUG(skeletonizelog) << \"extracting segment with length \" << maxValue << std::endl;\n\n\tGraphVolume::Node n = furthest;\n\n\t\/\/ walk backwards to next skeleton point\n\twhile (_nodeLabels[n] != OnSkeleton) {\n\n\t\t_nodeLabels[n] = OnSkeleton;\n\n\t\tif (_skipExplainedNodes)\n\t\t\tdrawExplanationSphere(_graphVolume.positions()[n]);\n\n\t\tGraphVolume::Edge pred = _dijkstra.predMap()[n];\n\t\tGraphVolume::Node u = _graphVolume.graph().u(pred);\n\t\tGraphVolume::Node v = _graphVolume.graph().v(pred);\n\n\t\tn = (u == n ? v : u);\n\n\t\t_distanceMap[pred] = 0.0;\n\t}\n\n\t\/\/ first segment?\n\tif (n == _root) {\n\n\t\tLOG_DEBUG(skeletonizelog) << \"longest segment has length \" << maxValue << std::endl;\n\n\t\t_minSegmentLength = std::max(_minSegmentLength, _minSegmentLengthRatio*maxValue);\n\n\t\tLOG_DEBUG(skeletonizelog) << \"setting min segment length to \" << _minSegmentLength << std::endl;\n\t}\n\n\treturn true;\n}\n\nvoid\nSkeletonize::drawExplanationSphere(const Position& center) {\n\n\tdouble radius2 = boundaryDistance(center)*pow(_explanationWeight, 2);\n\n\tdouble resX2 = pow(_graphVolume.getResolutionX(), 2);\n\tdouble resY2 = pow(_graphVolume.getResolutionY(), 2);\n\tdouble resZ2 = pow(_graphVolume.getResolutionZ(), 2);\n\n\tfor (GraphVolume::Node n : _boundary) {\n\n\t\tconst Position& pos = _graphVolume.positions()[n];\n\t\tdouble distance2 =\n\t\t\t\tresX2*pow(pos[0] - center[0], 2) +\n\t\t\t\tresY2*pow(pos[1] - center[1], 2) +\n\t\t\t\tresZ2*pow(pos[2] - center[2], 2);\n\n\t\tif (distance2 <= radius2)\n\t\t\tif (_nodeLabels[n] != OnSkeleton)\n\t\t\t\t_nodeLabels[n] = Explained;\n\t}\n}\n\ndouble\nSkeletonize::boundaryPenalty(double boundaryDistance) {\n\n\t\/\/ penalty = w*(1.0 - bd\/max_bd)\n\t\/\/\n\t\/\/ w : boundary weight\n\t\/\/ bd : boundary distance\n\t\/\/ max_bd: max boundary distance\n\treturn _boundaryWeight*(1.0 - sqrt(boundaryDistance\/_maxBoundaryDistance2));\n}\n\nSkeleton\nSkeletonize::parseVolumeSkeleton() {\n\n\tSkeleton skeleton;\n\n\tskeleton.setOffset(_graphVolume.getOffset());\n\tskeleton.setResolution(_graphVolume.getResolution());\n\n\ttraverse(_root, skeleton);\n\n\treturn skeleton;\n}\n\n\/\/ The old version of this was recursing directly and deeply, leading to stack\n\/\/ overflows in stack restricted environments (e.g. multithreading). The\n\/\/ current version is a fairly direct iteratization of the old, directly\n\/\/ recursive version.\nvoid\nSkeletonize::traverse(const GraphVolume::Node& root, Skeleton& skeleton) {\n\t\/\/ DFS of nodes from root. Data-wise, Nodes are just integer values.\n\tstd::stack traversal;\n\ttraversal.push(root);\n\twhile (!traversal.empty()) {\n\t\tconst GraphVolume::Node n = traversal.top();\n\t\tconst int nNeighbors = numNeighbors(n);\n\n\t\t\/\/ Special nodes that open new segments.\n\t\tconst bool isOpeningNode = n == _root || nNeighbors != 2;\n\n\t\t\/\/ The second time we see a node, we are in back-traversal, popping from\n\t\t\/\/ traversal stack and potentially closing segments.\n\t\tif (_nodeLabels[n] == Visited) {\n\t\t\tif (isOpeningNode) skeleton.closeSegment();\n\t\t\ttraversal.pop();\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Otherwise, we're seeing the node for the first time, so opening \/\n\t\t\/\/ extending segment.\n\t\t_nodeLabels[n] = Visited;\n\t\tconst Position pos = _graphVolume.positions()[n];\n\t\tconst float boundDist = sqrt(boundaryDistance(pos));\n\t\tif (isOpeningNode) {\n\t\t\tskeleton.openSegment(pos, boundDist);\n\t\t} else {\n\t\t\tskeleton.extendSegment(pos, boundDist);\n\t\t}\n\n\t\t\/\/ Iterate through neighbors and put unseen ones onto traversal stack. The\n\t\t\/\/ loop checks against nNeighbors to allow early termination.\n\t\tGraphVolume::IncEdgeIt e(_graphVolume.graph(), n);\n\t\tfor (int i = 0; i < nNeighbors; ++e \/* increment e, not i *\/) {\n\t\t\tassert(e != lemon::INVALID); \/\/ Should never occur.\n\n\t\t\t\/\/ Only increment i if we are using this edge.\n\t\t\tif (_distanceMap[e] != 0.0) continue;\n\t\t\t++i;\n\n\t\t\tconst GraphVolume::Node neighbor = (_graphVolume.graph().u(e) == n ? _graphVolume.graph().v(e) : _graphVolume.graph().u(e));\n\t\t\tif (_nodeLabels[neighbor] != Visited) traversal.push(neighbor);\n\t\t}\n\t}\n}\n\nint\nSkeletonize::numNeighbors(const GraphVolume::Node& n) {\n\n\tint num = 0;\n\n\tfor (GraphVolume::IncEdgeIt e(_graphVolume.graph(), n); e != lemon::INVALID; ++e)\n\t\tif (_distanceMap[e] == 0.0)\n\t\t\tnum++;\n\n\treturn num;\n}\n\n<|endoftext|>"} {"text":"#include \"mmapFile.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef ENABLE_UDC\nextern \"C\" {\n#include \"common.h\"\n#include \"udc.h\"\n}\n#endif\n\n\n\/* constants for header *\/\nstatic const std::string FORMAT_NAME = \"HAL-MMAP\";\nstatic const std::string MMAP_VERSION = \"1.0\";\n\n\n\/* is file a URL that requires UDC? *\/\nstatic bool isUdcUrl(const std::string alignmentPath) {\n return (alignmentPath.find(\"http:\") == 0) or (alignmentPath.find(\"https:\") == 0)\n or (alignmentPath.find(\"ftp:\") == 0);\n}\n\n\/* get the file size from the OS *\/\nstatic size_t getFileStatSize(int fd) {\n struct stat fileStat;\n if (::fstat(fd, &fileStat) < 0) {\n throw hal_errno_exception(\"stat failed\", errno);\n }\n return fileStat.st_size;\n}\n\n\/* constructor, used only by derived classes *\/\nhal::MMapFile::MMapFile(const std::string alignmentPath,\n unsigned mode):\n _alignmentPath(alignmentPath), _mode(halDefaultAccessMode(mode)),\n _basePtr(NULL), _fileSize(0), _mustFetch(false) {\n}\n\n\/* error if file is not open for write accecss *\/\nvoid hal::MMapFile::validateWriteAccess() const {\n if ((_mode & WRITE_ACCESS) == 0) {\n throw hal_exception(_alignmentPath + \" is not open for write access\");\n }\n}\n\n\/* setup pointer to header *\/\nvoid hal::MMapFile::setHeaderPtr() {\n fetchIfNeeded(0, sizeof(mmapHeader));\n _header = static_cast(_basePtr);\n}\n\n\/* validate the file header and save a pointer to it. *\/\nvoid hal::MMapFile::loadHeader(bool markDirty) {\n if (_fileSize < sizeof(mmapHeader)) {\n throw hal_exception(_alignmentPath + \": file size of \" + std::to_string(_fileSize)\n + \" is less that header size of \" + std::to_string(sizeof(mmapHeader)));\n }\n setHeaderPtr();\n\n \/\/ don't print found strings as it might have garbage\n if (::strcmp(_header->format, FORMAT_NAME.c_str()) != 0) {\n throw hal_exception(_alignmentPath + \": invalid file header, expected format name of '\" +\n FORMAT_NAME + \"'\");\n }\n \/\/ FIXME: to need to check version compatibility\n if (::strcmp(_header->mmapVersion, MMAP_VERSION.c_str()) != 0) {\n throw hal_exception(_alignmentPath + \": incompatible mmap format versions: \"\n + \"file version \" + _header->mmapVersion\n + \", mmap API version \" + MMAP_VERSION);\n }\n if ((_header->nextOffset < sizeof(mmapHeader)) or (_header->nextOffset > _fileSize)) {\n throw hal_exception(_alignmentPath + \": header nextOffset field out of bounds, probably file corruption\");\n }\n if ((_header->rootOffset < sizeof(mmapHeader)) or (_header->rootOffset > _fileSize)) {\n throw hal_exception(_alignmentPath + \": header rootOffset field out of bounds, probably file corruption\");\n }\n if (_header->dirty) {\n throw hal_exception(_alignmentPath + \": file is marked as dirty, most likely an inconsistent state.\");\n }\n if (markDirty) {\n _header->dirty = true;\n }\n}\n\n\/* create the header *\/\nvoid hal::MMapFile::createHeader() {\n assert(_mode & WRITE_ACCESS);\n setHeaderPtr();\n assert(FORMAT_NAME.size() < sizeof(_header->format));\n strncpy(_header->format, FORMAT_NAME.c_str(), sizeof(_header->format)-1);\n assert(MMAP_VERSION.size() < sizeof(_header->mmapVersion));\n strncpy(_header->mmapVersion, MMAP_VERSION.c_str(), sizeof(_header->mmapVersion)-1);\n assert(HAL_VERSION.size() < sizeof(_header->halVersion));\n strncpy(_header->halVersion, HAL_VERSION.c_str(), sizeof(_header->halVersion)-1);\n _header->nextOffset = alignRound(sizeof(mmapHeader));\n _header->dirty = true;\n _header->nextOffset = _header->nextOffset;\n}\n\n\/* Grow file to allow for at least the specified amount. This remaps the *\n * file, so the same sufficient virtual space must be available at the address\n * and it is expensive. *\/\nvoid hal::MMapFile::growFile(size_t size) {\n assert(_mode & WRITE_ACCESS);\n growFileImpl(size);\n}\n\n\/* override this for classes that support growing file *\/\nvoid hal::MMapFile::growFileImpl(size_t size) {\n throw hal_exception(\"logic error: growFile() not available for this MMapFile implementation\");\n}\n\nnamespace hal {\n \/* Class that implements local file version of MMapFile *\/\n class MMapFileLocal: public MMapFile {\n public:\n MMapFileLocal(const std::string& alignmentPath,\n unsigned mode,\n size_t initSize,\n size_t growSize);\n virtual void close();\n virtual ~MMapFileLocal();\n\n private:\n int openFile();\n void closeFile();\n void adjustFileSize(size_t size);\n void* mapFile(void *requiredAddr=NULL);\n void unmapFile();\n void openRead();\n void openWrite(size_t initSize);\n void growFileImpl(size_t size);\n\n int _fd; \/\/ open file descriptor\n size_t _growSize; \/\/ amount to grow file by when needed.\n };\n}\n\n\n\/* Constructor. Open or create the specified file. *\/\nhal::MMapFileLocal::MMapFileLocal(const std::string& alignmentPath,\n unsigned mode,\n size_t initSize,\n size_t growSize):\n MMapFile(alignmentPath, mode), _fd(-1), _growSize(growSize) {\n if (_mode & WRITE_ACCESS) {\n openWrite(initSize);\n } else {\n openRead();\n }\n}\n\n\/* close file, marking as clean. Don't *\/\nvoid hal::MMapFileLocal::close() {\n if (_basePtr == NULL) {\n throw hal_exception(_alignmentPath + \": MMapFile::close() called on closed file\");\n }\n if (_mode & WRITE_ACCESS) {\n adjustFileSize(_header->nextOffset);\n _header->dirty = false;\n }\n unmapFile();\n closeFile();\n}\n\n\/* Destructor. write fields to header and close. If write access and close\n * has not been called, file will me left mark dirty *\/\nhal::MMapFileLocal::~MMapFileLocal() {\n unmapFile();\n closeFile();\n}\n\n\/* open the file for the specified mode *\/\nint hal::MMapFileLocal::openFile() {\n assert(_fd < 0);\n unsigned openMode = 0;\n if (_mode & WRITE_ACCESS) {\n openMode = O_RDWR | ((_mode & CREATE_ACCESS) ? (O_CREAT|O_TRUNC) : 0);\n } else {\n openMode = O_RDONLY;\n }\n int fd = ::open(_alignmentPath.c_str(), openMode, 0777);\n if (fd < 0) {\n throw hal_errno_exception(_alignmentPath, \"open failed\", errno);\n }\n return fd;\n}\n\n\/* change size size of the file, possibly deleting data. *\/\nvoid hal::MMapFileLocal::adjustFileSize(size_t size) {\n if (ftruncate(_fd, size) < 0) {\n throw hal_errno_exception(_alignmentPath, \"set size failed\", errno);\n }\n _fileSize = size;\n}\n\n\/* map file into memory *\/\nvoid* hal::MMapFileLocal::mapFile(void *requiredAddr) {\n assert(_basePtr == NULL);\n unsigned prot = PROT_READ | ((_mode & WRITE_ACCESS) ? PROT_WRITE : 0);\n void *ptr = mmap(requiredAddr, _fileSize, prot, MAP_SHARED|MAP_FILE, _fd, 0);\n if (ptr == MAP_FAILED) {\n throw hal_errno_exception(_alignmentPath, \"mmap failed\", errno);\n }\n return ptr;\n}\n\n\/* unmap file, if mapped *\/\nvoid hal::MMapFileLocal::unmapFile() {\n if (_basePtr != NULL) {\n if (::munmap(const_cast(_basePtr), _fileSize) < 0) {\n throw hal_errno_exception(_alignmentPath, \"munmap failed\", errno);\n }\n _basePtr = NULL;\n }\n}\n\n\/* open the file for read access *\/\nvoid hal::MMapFileLocal::openRead() {\n _fd = openFile();\n _fileSize = getFileStatSize(_fd);\n _basePtr = mapFile();\n loadHeader(false);\n}\n\n\/* open the file for write access *\/\nvoid hal::MMapFileLocal::openWrite(size_t initSize) {\n _fd = openFile();\n if (_mode & CREATE_ACCESS) {\n adjustFileSize(0); \/\/ clear out existing data\n }\n if (initSize > _fileSize) {\n adjustFileSize(initSize);\n }\n _basePtr = mapFile();\n if (_mode & CREATE_ACCESS) {\n createHeader();\n } else {\n loadHeader(true);\n }\n}\n\n\/* close the file if open *\/\nvoid hal::MMapFileLocal::closeFile() {\n if (_fd >= 0) {\n if (::close(_fd) < 0) {\n throw hal_errno_exception(_alignmentPath, \"close failed\", errno);\n }\n _fd = -1;\n }\n}\n\n\/* grow file *\/\nvoid hal::MMapFileLocal::growFileImpl(size_t size) {\n assert(_mode & WRITE_ACCESS);\n size_t newSize = _growSize;\n if (newSize < size) {\n newSize += size; \/\/ will leave in extra\n }\n void * requiredAddr = _basePtr;\n unmapFile();\n mapFile(requiredAddr);\n}\n\nnamespace hal {\n \/* Class that implements UDC file version of MMapFile *\/\n class MMapFileUdc: public MMapFile {\n public:\n MMapFileUdc(const std::string& alignmentPath,\n unsigned mode,\n size_t initSize,\n size_t growSize,\n const std::string& udcCacheDir);\n virtual void close();\n virtual ~MMapFileUdc();\n\n protected:\n virtual void fetch(size_t offset,\n size_t accessSize) const;\n\n private:\n struct udcFile *_udcFile;\n };\n}\n\n\n\/* Constructor. Open or create the specified file. *\/\nhal::MMapFileUdc::MMapFileUdc(const std::string& alignmentPath,\n unsigned mode,\n size_t initSize,\n size_t growSize,\n const std::string& udcCacheDir):\n MMapFile(alignmentPath, mode), _udcFile(NULL) {\n if (_mode & WRITE_ACCESS) {\n throw hal_exception(\"write access not supported for UDC:\" + alignmentPath);\n }\n _udcFile = udcFileOpen(const_cast(alignmentPath.c_str()),\n (udcCacheDir.empty()) ? NULL : const_cast(udcCacheDir.c_str()));\n \/\/ get base point and fetch header in one move.\n _basePtr = udcMMapFetch(_udcFile, 0, sizeof(mmapHeader));\n}\n\n\/* close file, marking as clean. Don't *\/\nvoid hal::MMapFileUdc::close() {\n if (_basePtr == NULL) {\n throw hal_exception(_alignmentPath + \": MMapFile::close() called on closed file\");\n }\n udcFileClose(&_udcFile);\n}\n\n\/* Destructor. write fields to header and close. If write access and close\n * has not been called, file will me left mark dirty *\/\nhal::MMapFileUdc::~MMapFileUdc() {\n if (_udcFile != NULL) {\n udcFileClose(&_udcFile);\n }\n}\n\n\/* fetch into UDC cache *\/\nvoid hal::MMapFileUdc::fetch(size_t offset,\n size_t accessSize) const {\n udcMMapFetch(_udcFile, offset, accessSize); \n}\n\n\/** create a MMapFile object, opening a local file *\/\nhal::MMapFile *hal::MMapFile::factory(const std::string& alignmentPath,\n unsigned mode,\n size_t initSize,\n size_t growSize,\n const std::string& udcCacheDir) {\n if (isUdcUrl(alignmentPath)) {\n if (mode & (CREATE_ACCESS | WRITE_ACCESS)) {\n throw hal_exception(\"create or write access not support with URL: \" + alignmentPath);\n }\n#ifdef ENABLE_UDC\n return new MMapFileUdc(alignmentPath, mode, initSize, growSize, udcCacheDir);\n#else\n throw hal_exception(\"URL access requires UDC support to be compiled into HAL library: \" + alignmentPath);\n#endif\n } else {\n return new MMapFileLocal(alignmentPath, mode, initSize, growSize);\n }\n}\n\nFix compilation when ENABLE_UDC is undefined#include \"mmapFile.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef ENABLE_UDC\nextern \"C\" {\n#include \"common.h\"\n#include \"udc.h\"\n}\n#endif\n\n\n\/* constants for header *\/\nstatic const std::string FORMAT_NAME = \"HAL-MMAP\";\nstatic const std::string MMAP_VERSION = \"1.0\";\n\n\n\/* is file a URL that requires UDC? *\/\nstatic bool isUdcUrl(const std::string alignmentPath) {\n return (alignmentPath.find(\"http:\") == 0) or (alignmentPath.find(\"https:\") == 0)\n or (alignmentPath.find(\"ftp:\") == 0);\n}\n\n\/* get the file size from the OS *\/\nstatic size_t getFileStatSize(int fd) {\n struct stat fileStat;\n if (::fstat(fd, &fileStat) < 0) {\n throw hal_errno_exception(\"stat failed\", errno);\n }\n return fileStat.st_size;\n}\n\n\/* constructor, used only by derived classes *\/\nhal::MMapFile::MMapFile(const std::string alignmentPath,\n unsigned mode):\n _alignmentPath(alignmentPath), _mode(halDefaultAccessMode(mode)),\n _basePtr(NULL), _fileSize(0), _mustFetch(false) {\n}\n\n\/* error if file is not open for write accecss *\/\nvoid hal::MMapFile::validateWriteAccess() const {\n if ((_mode & WRITE_ACCESS) == 0) {\n throw hal_exception(_alignmentPath + \" is not open for write access\");\n }\n}\n\n\/* setup pointer to header *\/\nvoid hal::MMapFile::setHeaderPtr() {\n fetchIfNeeded(0, sizeof(mmapHeader));\n _header = static_cast(_basePtr);\n}\n\n\/* validate the file header and save a pointer to it. *\/\nvoid hal::MMapFile::loadHeader(bool markDirty) {\n if (_fileSize < sizeof(mmapHeader)) {\n throw hal_exception(_alignmentPath + \": file size of \" + std::to_string(_fileSize)\n + \" is less that header size of \" + std::to_string(sizeof(mmapHeader)));\n }\n setHeaderPtr();\n\n \/\/ don't print found strings as it might have garbage\n if (::strcmp(_header->format, FORMAT_NAME.c_str()) != 0) {\n throw hal_exception(_alignmentPath + \": invalid file header, expected format name of '\" +\n FORMAT_NAME + \"'\");\n }\n \/\/ FIXME: to need to check version compatibility\n if (::strcmp(_header->mmapVersion, MMAP_VERSION.c_str()) != 0) {\n throw hal_exception(_alignmentPath + \": incompatible mmap format versions: \"\n + \"file version \" + _header->mmapVersion\n + \", mmap API version \" + MMAP_VERSION);\n }\n if ((_header->nextOffset < sizeof(mmapHeader)) or (_header->nextOffset > _fileSize)) {\n throw hal_exception(_alignmentPath + \": header nextOffset field out of bounds, probably file corruption\");\n }\n if ((_header->rootOffset < sizeof(mmapHeader)) or (_header->rootOffset > _fileSize)) {\n throw hal_exception(_alignmentPath + \": header rootOffset field out of bounds, probably file corruption\");\n }\n if (_header->dirty) {\n throw hal_exception(_alignmentPath + \": file is marked as dirty, most likely an inconsistent state.\");\n }\n if (markDirty) {\n _header->dirty = true;\n }\n}\n\n\/* create the header *\/\nvoid hal::MMapFile::createHeader() {\n assert(_mode & WRITE_ACCESS);\n setHeaderPtr();\n assert(FORMAT_NAME.size() < sizeof(_header->format));\n strncpy(_header->format, FORMAT_NAME.c_str(), sizeof(_header->format)-1);\n assert(MMAP_VERSION.size() < sizeof(_header->mmapVersion));\n strncpy(_header->mmapVersion, MMAP_VERSION.c_str(), sizeof(_header->mmapVersion)-1);\n assert(HAL_VERSION.size() < sizeof(_header->halVersion));\n strncpy(_header->halVersion, HAL_VERSION.c_str(), sizeof(_header->halVersion)-1);\n _header->nextOffset = alignRound(sizeof(mmapHeader));\n _header->dirty = true;\n _header->nextOffset = _header->nextOffset;\n}\n\n\/* Grow file to allow for at least the specified amount. This remaps the *\n * file, so the same sufficient virtual space must be available at the address\n * and it is expensive. *\/\nvoid hal::MMapFile::growFile(size_t size) {\n assert(_mode & WRITE_ACCESS);\n growFileImpl(size);\n}\n\n\/* override this for classes that support growing file *\/\nvoid hal::MMapFile::growFileImpl(size_t size) {\n throw hal_exception(\"logic error: growFile() not available for this MMapFile implementation\");\n}\n\nnamespace hal {\n \/* Class that implements local file version of MMapFile *\/\n class MMapFileLocal: public MMapFile {\n public:\n MMapFileLocal(const std::string& alignmentPath,\n unsigned mode,\n size_t initSize,\n size_t growSize);\n virtual void close();\n virtual ~MMapFileLocal();\n\n private:\n int openFile();\n void closeFile();\n void adjustFileSize(size_t size);\n void* mapFile(void *requiredAddr=NULL);\n void unmapFile();\n void openRead();\n void openWrite(size_t initSize);\n void growFileImpl(size_t size);\n\n int _fd; \/\/ open file descriptor\n size_t _growSize; \/\/ amount to grow file by when needed.\n };\n}\n\n\n\/* Constructor. Open or create the specified file. *\/\nhal::MMapFileLocal::MMapFileLocal(const std::string& alignmentPath,\n unsigned mode,\n size_t initSize,\n size_t growSize):\n MMapFile(alignmentPath, mode), _fd(-1), _growSize(growSize) {\n if (_mode & WRITE_ACCESS) {\n openWrite(initSize);\n } else {\n openRead();\n }\n}\n\n\/* close file, marking as clean. Don't *\/\nvoid hal::MMapFileLocal::close() {\n if (_basePtr == NULL) {\n throw hal_exception(_alignmentPath + \": MMapFile::close() called on closed file\");\n }\n if (_mode & WRITE_ACCESS) {\n adjustFileSize(_header->nextOffset);\n _header->dirty = false;\n }\n unmapFile();\n closeFile();\n}\n\n\/* Destructor. write fields to header and close. If write access and close\n * has not been called, file will me left mark dirty *\/\nhal::MMapFileLocal::~MMapFileLocal() {\n unmapFile();\n closeFile();\n}\n\n\/* open the file for the specified mode *\/\nint hal::MMapFileLocal::openFile() {\n assert(_fd < 0);\n unsigned openMode = 0;\n if (_mode & WRITE_ACCESS) {\n openMode = O_RDWR | ((_mode & CREATE_ACCESS) ? (O_CREAT|O_TRUNC) : 0);\n } else {\n openMode = O_RDONLY;\n }\n int fd = ::open(_alignmentPath.c_str(), openMode, 0777);\n if (fd < 0) {\n throw hal_errno_exception(_alignmentPath, \"open failed\", errno);\n }\n return fd;\n}\n\n\/* change size size of the file, possibly deleting data. *\/\nvoid hal::MMapFileLocal::adjustFileSize(size_t size) {\n if (ftruncate(_fd, size) < 0) {\n throw hal_errno_exception(_alignmentPath, \"set size failed\", errno);\n }\n _fileSize = size;\n}\n\n\/* map file into memory *\/\nvoid* hal::MMapFileLocal::mapFile(void *requiredAddr) {\n assert(_basePtr == NULL);\n unsigned prot = PROT_READ | ((_mode & WRITE_ACCESS) ? PROT_WRITE : 0);\n void *ptr = mmap(requiredAddr, _fileSize, prot, MAP_SHARED|MAP_FILE, _fd, 0);\n if (ptr == MAP_FAILED) {\n throw hal_errno_exception(_alignmentPath, \"mmap failed\", errno);\n }\n return ptr;\n}\n\n\/* unmap file, if mapped *\/\nvoid hal::MMapFileLocal::unmapFile() {\n if (_basePtr != NULL) {\n if (::munmap(const_cast(_basePtr), _fileSize) < 0) {\n throw hal_errno_exception(_alignmentPath, \"munmap failed\", errno);\n }\n _basePtr = NULL;\n }\n}\n\n\/* open the file for read access *\/\nvoid hal::MMapFileLocal::openRead() {\n _fd = openFile();\n _fileSize = getFileStatSize(_fd);\n _basePtr = mapFile();\n loadHeader(false);\n}\n\n\/* open the file for write access *\/\nvoid hal::MMapFileLocal::openWrite(size_t initSize) {\n _fd = openFile();\n if (_mode & CREATE_ACCESS) {\n adjustFileSize(0); \/\/ clear out existing data\n }\n if (initSize > _fileSize) {\n adjustFileSize(initSize);\n }\n _basePtr = mapFile();\n if (_mode & CREATE_ACCESS) {\n createHeader();\n } else {\n loadHeader(true);\n }\n}\n\n\/* close the file if open *\/\nvoid hal::MMapFileLocal::closeFile() {\n if (_fd >= 0) {\n if (::close(_fd) < 0) {\n throw hal_errno_exception(_alignmentPath, \"close failed\", errno);\n }\n _fd = -1;\n }\n}\n\n\/* grow file *\/\nvoid hal::MMapFileLocal::growFileImpl(size_t size) {\n assert(_mode & WRITE_ACCESS);\n size_t newSize = _growSize;\n if (newSize < size) {\n newSize += size; \/\/ will leave in extra\n }\n void * requiredAddr = _basePtr;\n unmapFile();\n mapFile(requiredAddr);\n}\n\n#ifdef ENABLE_UDC\nnamespace hal {\n \/* Class that implements UDC file version of MMapFile *\/\n class MMapFileUdc: public MMapFile {\n public:\n MMapFileUdc(const std::string& alignmentPath,\n unsigned mode,\n size_t initSize,\n size_t growSize,\n const std::string& udcCacheDir);\n virtual void close();\n virtual ~MMapFileUdc();\n\n protected:\n virtual void fetch(size_t offset,\n size_t accessSize) const;\n\n private:\n struct udcFile *_udcFile;\n };\n}\n\n\n\/* Constructor. Open or create the specified file. *\/\nhal::MMapFileUdc::MMapFileUdc(const std::string& alignmentPath,\n unsigned mode,\n size_t initSize,\n size_t growSize,\n const std::string& udcCacheDir):\n MMapFile(alignmentPath, mode), _udcFile(NULL) {\n if (_mode & WRITE_ACCESS) {\n throw hal_exception(\"write access not supported for UDC:\" + alignmentPath);\n }\n _udcFile = udcFileOpen(const_cast(alignmentPath.c_str()),\n (udcCacheDir.empty()) ? NULL : const_cast(udcCacheDir.c_str()));\n \/\/ get base point and fetch header in one move.\n _basePtr = udcMMapFetch(_udcFile, 0, sizeof(mmapHeader));\n}\n\n\/* close file, marking as clean. Don't *\/\nvoid hal::MMapFileUdc::close() {\n if (_basePtr == NULL) {\n throw hal_exception(_alignmentPath + \": MMapFile::close() called on closed file\");\n }\n udcFileClose(&_udcFile);\n}\n\n\/* Destructor. write fields to header and close. If write access and close\n * has not been called, file will me left mark dirty *\/\nhal::MMapFileUdc::~MMapFileUdc() {\n if (_udcFile != NULL) {\n udcFileClose(&_udcFile);\n }\n}\n\n\/* fetch into UDC cache *\/\nvoid hal::MMapFileUdc::fetch(size_t offset,\n size_t accessSize) const {\n udcMMapFetch(_udcFile, offset, accessSize); \n}\n\n#endif\n\n\/** create a MMapFile object, opening a local file *\/\nhal::MMapFile *hal::MMapFile::factory(const std::string& alignmentPath,\n unsigned mode,\n size_t initSize,\n size_t growSize,\n const std::string& udcCacheDir) {\n if (isUdcUrl(alignmentPath)) {\n if (mode & (CREATE_ACCESS | WRITE_ACCESS)) {\n throw hal_exception(\"create or write access not support with URL: \" + alignmentPath);\n }\n#ifdef ENABLE_UDC\n return new MMapFileUdc(alignmentPath, mode, initSize, growSize, udcCacheDir);\n#else\n throw hal_exception(\"URL access requires UDC support to be compiled into HAL library: \" + alignmentPath);\n#endif\n } else {\n return new MMapFileLocal(alignmentPath, mode, initSize, growSize);\n }\n}\n\n<|endoftext|>"} {"text":"\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef IP4_PACKET_IP4_HPP\n#define IP4_PACKET_IP4_HPP\n\n#include \"header.hpp\"\n#include \n#include \n#include \n\nnamespace net {\n\n \/** IPv4 packet. *\/\n class PacketIP4 : public Packet {\n public:\n static constexpr int DEFAULT_TTL = 64;\n\n using Span = gsl::span;\n using Cspan = gsl::span;\n\n \/\/\n \/\/ IP header getters\n \/\/\n\n \/** Get IP protocol version field. Must be 4 (RFC 1122) *\/\n uint8_t ip_version() const noexcept\n { return (ip_header().version_ihl >> 4) & 0xf; }\n\n bool is_ipv4() const noexcept\n { return (ip_header().version_ihl & 0xf0) == 0x40; }\n\n \/** Get IP header length field as-is. *\/\n uint8_t ip_ihl() const noexcept\n { return (ip_header().version_ihl & 0xf); }\n\n \/** Get IP header length field in bytes. *\/\n uint8_t ip_header_length() const noexcept\n { return (ip_header().version_ihl & 0xf) * 4; }\n\n \/** Get Differentiated Services Code Point (DSCP)*\/\n DSCP ip_dscp() const noexcept\n { return static_cast(ip_header().ds_ecn >> 2); }\n\n \/** Get Explicit Congestion Notification (ECN) bits *\/\n ECN ip_ecn() const noexcept\n { return ECN(ip_header().ds_ecn & 0x3); }\n\n \/** Get total length header field *\/\n uint16_t ip_total_length() const noexcept\n { return ntohs(ip_header().tot_len); }\n\n \/** Get ID header field *\/\n uint16_t ip_id() const noexcept\n { return ntohs(ip_header().id); }\n\n \/** Get IP header flags *\/\n ip4::Flags ip_flags() const noexcept\n { return static_cast(ntohs(ip_header().frag_off_flags) >> 13); }\n\n \/** Get Fragment offset field *\/\n uint16_t ip_frag_offs() const noexcept\n { return ntohs(ip_header().frag_off_flags) & 0x1fff; }\n\n \/** Get Time-To-Live field *\/\n uint8_t ip_ttl() const noexcept\n { return ip_header().ttl; }\n\n \/** Get protocol field value *\/\n Protocol ip_protocol() const noexcept\n { return static_cast(ip_header().protocol); }\n\n \/** Get the IP header checksum field as-is *\/\n uint16_t ip_checksum() const noexcept\n { return ip_header().check; }\n\n \/** Get source address *\/\n const ip4::Addr& ip_src() const noexcept\n { return ip_header().saddr; }\n\n \/** Get destination address *\/\n const ip4::Addr& ip_dst() const noexcept\n { return ip_header().daddr; }\n\n \/** Get IP data length. *\/\n uint16_t ip_data_length() const noexcept\n {\n \/\/Expects(size() and static_cast(size()) >= sizeof(ip4::Header));\n return size() - ip_header_length();\n }\n\n \/** Adjust packet size to match IP header's tot_len in case of padding *\/\n void adjust_size_from_header() {\n auto ip_len = ip_total_length();\n if (UNLIKELY(size() > ip_len)) {\n set_data_end(ip_len);\n }\n }\n\n \/** Get total data capacity of IP packet in bytes *\/\n uint16_t ip_capacity() const noexcept\n { return capacity() - ip_header_length(); }\n\n \/** Compute IP header checksum on header as-is *\/\n uint16_t compute_ip_checksum() noexcept\n { return net::checksum(&ip_header(), ip_header_length()); };\n\n\n \/\/\n \/\/ IP header setters\n \/\/\n\n \/** Set IP version header field *\/\n void set_ip_version(uint8_t ver) noexcept\n {\n Expects(ver < 0x10);\n ip_header().version_ihl |= ver << 4;\n }\n\n \/** Set IP header length field *\/\n void set_ihl(uint8_t ihl) noexcept\n {\n Expects(ihl < 0x10);\n ip_header().version_ihl |= ihl;\n }\n\n \/** Set IP header lenght field, in bytes *\/\n void set_ip_header_length(uint8_t bytes) noexcept\n { set_ihl(bytes \/ 4); }\n\n \/** Set DSCP header bits *\/\n void set_ip_dscp(DSCP dscp) noexcept\n { ip_header().ds_ecn |= (static_cast(dscp) << 2); }\n\n \/** Set ECN header bits *\/\n void set_ip_ecn(ECN ecn) noexcept\n { ip_header().ds_ecn |= (static_cast(ecn) & 0x3); }\n\n \/** Set total length header field *\/\n void set_ip_total_length(uint16_t len) noexcept\n { ip_header().tot_len = htons(len); }\n\n \/** Set ID header field *\/\n void set_ip_id(uint16_t i) noexcept\n { ip_header().id = htons(i); }\n\n \/** Set flags field *\/\n void set_ip_flags(ip4::Flags f)\n {\n ip_header().frag_off_flags |= static_cast(f) << 13;\n ip_header().frag_off_flags = htons(ip_header().frag_off_flags);\n }\n\n \/** Set fragment offset header field *\/\n void set_ip_frag_offs(uint16_t offs)\n {\n Expects(offs < 0x2000);\n ip_header().frag_off_flags |= htons(offs) >> 3;\n }\n\n \/** Set total length header field *\/\n void set_ip_ttl(uint8_t ttl) noexcept\n { ip_header().ttl = ttl; }\n\n \/**\n * @brief Decrement Time-To-Live by 1 and adjust the checksum.\n *\/\n void decrement_ttl()\n {\n Expects(ip_ttl() != 0);\n ip_header().ttl--;\n \/\/ RFC 1141 p. 1\n uint16_t sum = ntohs(ip_header().check + htons(0x100)); \/\/ increment checksum high byte\n ip_header().check = htons(sum + (sum>>16)); \/\/ add carry\n }\n\n \/** Set protocol header field *\/\n void set_protocol(Protocol p) noexcept\n { ip_header().protocol = static_cast(p); }\n\n \/** Set IP header checksum field directly *\/\n void set_ip_checksum(uint16_t sum) noexcept\n { ip_header().check = sum; }\n\n \/** Calculate and set IP header checksum field *\/\n void set_ip_checksum() noexcept {\n auto& hdr = ip_header();\n hdr.check = 0;\n hdr.check = net::checksum(&hdr, ip_header_length());\n }\n\n \/** Set source address header field *\/\n void set_ip_src(const ip4::Addr& addr) noexcept\n { ip_header().saddr = addr; }\n\n \/** Set destination address header field *\/\n void set_ip_dst(const ip4::Addr& addr) noexcept\n { ip_header().daddr = addr; }\n\n \/**\n * Set size of data contained in IP datagram.\n * @note : does not modify IP header\n **\/\n void set_ip_data_length(uint16_t length) noexcept\n {\n Expects(sizeof(ip4::Header) + length <= (size_t) capacity());\n set_data_end(sizeof(ip4::Header) + length);\n }\n\n \/** Last modifications before transmission *\/\n void make_flight_ready() noexcept {\n assert( ip_header().protocol );\n set_segment_length();\n set_ip_checksum();\n }\n\n void init(Protocol proto = Protocol::HOPOPT) noexcept {\n Expects(size() == 0);\n auto& hdr = ip_header();\n hdr = {};\n hdr.tot_len = 0x1400; \/\/ Big-endian 20\n hdr.ttl = DEFAULT_TTL;\n hdr.protocol = static_cast(proto);\n increment_data_end(sizeof(ip4::Header));\n }\n\n Span ip_data() {\n return {ip_data_ptr(), ip_data_length()};\n }\n\n Cspan ip_data() const {\n return {ip_data_ptr(), ip_data_length()};\n }\n\n bool validate_length() const noexcept {\n return this->size() == ip_header_length() + ip_data_length();\n }\n\n protected:\n\n \/** Get pointer to IP data *\/\n Byte* ip_data_ptr() noexcept __attribute__((assume_aligned(4)))\n {\n return layer_begin() + ip_header_length();\n }\n\n const Byte* ip_data_ptr() const noexcept __attribute__((assume_aligned(4)))\n {\n return layer_begin() + ip_header_length();\n }\n\n private:\n\n \/**\n * Set IP4 header length\n * Inferred from packet size\n *\/\n void set_segment_length() noexcept\n { ip_header().tot_len = htons(size()); }\n\n const ip4::Header& ip_header() const noexcept\n { return *reinterpret_cast(layer_begin()); }\n\n ip4::Header& ip_header() noexcept\n { return *reinterpret_cast(layer_begin()); }\n\n }; \/\/< class PacketIP4\n} \/\/< namespace net\n\n#endif \/\/< IP4_PACKET_IP4_HPP\nip4: Set version and IHL properly in IP4 packet\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef IP4_PACKET_IP4_HPP\n#define IP4_PACKET_IP4_HPP\n\n#include \"header.hpp\"\n#include \n#include \n#include \n\nnamespace net {\n\n \/** IPv4 packet. *\/\n class PacketIP4 : public Packet {\n public:\n static constexpr int DEFAULT_TTL = 64;\n\n using Span = gsl::span;\n using Cspan = gsl::span;\n\n \/\/\n \/\/ IP header getters\n \/\/\n\n \/** Get IP protocol version field. Must be 4 (RFC 1122) *\/\n uint8_t ip_version() const noexcept\n { return (ip_header().version_ihl >> 4) & 0xf; }\n\n bool is_ipv4() const noexcept\n { return (ip_header().version_ihl & 0xf0) == 0x40; }\n\n \/** Get IP header length field as-is. *\/\n uint8_t ip_ihl() const noexcept\n { return (ip_header().version_ihl & 0xf); }\n\n \/** Get IP header length field in bytes. *\/\n uint8_t ip_header_length() const noexcept\n { return (ip_header().version_ihl & 0xf) * 4; }\n\n \/** Get Differentiated Services Code Point (DSCP)*\/\n DSCP ip_dscp() const noexcept\n { return static_cast(ip_header().ds_ecn >> 2); }\n\n \/** Get Explicit Congestion Notification (ECN) bits *\/\n ECN ip_ecn() const noexcept\n { return ECN(ip_header().ds_ecn & 0x3); }\n\n \/** Get total length header field *\/\n uint16_t ip_total_length() const noexcept\n { return ntohs(ip_header().tot_len); }\n\n \/** Get ID header field *\/\n uint16_t ip_id() const noexcept\n { return ntohs(ip_header().id); }\n\n \/** Get IP header flags *\/\n ip4::Flags ip_flags() const noexcept\n { return static_cast(ntohs(ip_header().frag_off_flags) >> 13); }\n\n \/** Get Fragment offset field *\/\n uint16_t ip_frag_offs() const noexcept\n { return ntohs(ip_header().frag_off_flags) & 0x1fff; }\n\n \/** Get Time-To-Live field *\/\n uint8_t ip_ttl() const noexcept\n { return ip_header().ttl; }\n\n \/** Get protocol field value *\/\n Protocol ip_protocol() const noexcept\n { return static_cast(ip_header().protocol); }\n\n \/** Get the IP header checksum field as-is *\/\n uint16_t ip_checksum() const noexcept\n { return ip_header().check; }\n\n \/** Get source address *\/\n const ip4::Addr& ip_src() const noexcept\n { return ip_header().saddr; }\n\n \/** Get destination address *\/\n const ip4::Addr& ip_dst() const noexcept\n { return ip_header().daddr; }\n\n \/** Get IP data length. *\/\n uint16_t ip_data_length() const noexcept\n {\n \/\/Expects(size() and static_cast(size()) >= sizeof(ip4::Header));\n return size() - ip_header_length();\n }\n\n \/** Adjust packet size to match IP header's tot_len in case of padding *\/\n void adjust_size_from_header() {\n auto ip_len = ip_total_length();\n if (UNLIKELY(size() > ip_len)) {\n set_data_end(ip_len);\n }\n }\n\n \/** Get total data capacity of IP packet in bytes *\/\n uint16_t ip_capacity() const noexcept\n { return capacity() - ip_header_length(); }\n\n \/** Compute IP header checksum on header as-is *\/\n uint16_t compute_ip_checksum() noexcept\n { return net::checksum(&ip_header(), ip_header_length()); };\n\n\n \/\/\n \/\/ IP header setters\n \/\/\n\n \/** Set IP version header field *\/\n void set_ip_version(uint8_t ver) noexcept\n {\n Expects(ver < 0x10);\n ip_header().version_ihl &= 0x0F;\n ip_header().version_ihl |= ver << 4;\n }\n\n \/** Set IP header length field *\/\n void set_ihl(uint8_t ihl) noexcept\n {\n Expects(ihl < 0x10);\n ip_header().version_ihl &= 0xF0;\n ip_header().version_ihl |= ihl;\n }\n\n \/** Set IP header lenght field, in bytes *\/\n void set_ip_header_length(uint8_t bytes) noexcept\n { set_ihl(bytes \/ 4); }\n\n \/** Set DSCP header bits *\/\n void set_ip_dscp(DSCP dscp) noexcept\n { ip_header().ds_ecn |= (static_cast(dscp) << 2); }\n\n \/** Set ECN header bits *\/\n void set_ip_ecn(ECN ecn) noexcept\n { ip_header().ds_ecn |= (static_cast(ecn) & 0x3); }\n\n \/** Set total length header field *\/\n void set_ip_total_length(uint16_t len) noexcept\n { ip_header().tot_len = htons(len); }\n\n \/** Set ID header field *\/\n void set_ip_id(uint16_t i) noexcept\n { ip_header().id = htons(i); }\n\n \/** Set flags field *\/\n void set_ip_flags(ip4::Flags f)\n {\n ip_header().frag_off_flags |= static_cast(f) << 13;\n ip_header().frag_off_flags = htons(ip_header().frag_off_flags);\n }\n\n \/** Set fragment offset header field *\/\n void set_ip_frag_offs(uint16_t offs)\n {\n Expects(offs < 0x2000);\n ip_header().frag_off_flags |= htons(offs) >> 3;\n }\n\n \/** Set total length header field *\/\n void set_ip_ttl(uint8_t ttl) noexcept\n { ip_header().ttl = ttl; }\n\n \/**\n * @brief Decrement Time-To-Live by 1 and adjust the checksum.\n *\/\n void decrement_ttl()\n {\n Expects(ip_ttl() != 0);\n ip_header().ttl--;\n \/\/ RFC 1141 p. 1\n uint16_t sum = ntohs(ip_header().check + htons(0x100)); \/\/ increment checksum high byte\n ip_header().check = htons(sum + (sum>>16)); \/\/ add carry\n }\n\n \/** Set protocol header field *\/\n void set_protocol(Protocol p) noexcept\n { ip_header().protocol = static_cast(p); }\n\n \/** Set IP header checksum field directly *\/\n void set_ip_checksum(uint16_t sum) noexcept\n { ip_header().check = sum; }\n\n \/** Calculate and set IP header checksum field *\/\n void set_ip_checksum() noexcept {\n auto& hdr = ip_header();\n hdr.check = 0;\n hdr.check = net::checksum(&hdr, ip_header_length());\n }\n\n \/** Set source address header field *\/\n void set_ip_src(const ip4::Addr& addr) noexcept\n { ip_header().saddr = addr; }\n\n \/** Set destination address header field *\/\n void set_ip_dst(const ip4::Addr& addr) noexcept\n { ip_header().daddr = addr; }\n\n \/**\n * Set size of data contained in IP datagram.\n * @note : does not modify IP header\n **\/\n void set_ip_data_length(uint16_t length) noexcept\n {\n Expects(sizeof(ip4::Header) + length <= (size_t) capacity());\n set_data_end(sizeof(ip4::Header) + length);\n }\n\n \/** Last modifications before transmission *\/\n void make_flight_ready() noexcept {\n assert( ip_header().protocol );\n set_segment_length();\n set_ip_checksum();\n }\n\n void init(Protocol proto = Protocol::HOPOPT) noexcept {\n Expects(size() == 0);\n auto& hdr = ip_header();\n hdr = {};\n hdr.tot_len = 0x1400; \/\/ Big-endian 20\n hdr.ttl = DEFAULT_TTL;\n hdr.protocol = static_cast(proto);\n increment_data_end(sizeof(ip4::Header));\n }\n\n Span ip_data() {\n return {ip_data_ptr(), ip_data_length()};\n }\n\n Cspan ip_data() const {\n return {ip_data_ptr(), ip_data_length()};\n }\n\n bool validate_length() const noexcept {\n return this->size() == ip_header_length() + ip_data_length();\n }\n\n protected:\n\n \/** Get pointer to IP data *\/\n Byte* ip_data_ptr() noexcept __attribute__((assume_aligned(4)))\n {\n return layer_begin() + ip_header_length();\n }\n\n const Byte* ip_data_ptr() const noexcept __attribute__((assume_aligned(4)))\n {\n return layer_begin() + ip_header_length();\n }\n\n private:\n\n \/**\n * Set IP4 header length\n * Inferred from packet size\n *\/\n void set_segment_length() noexcept\n { ip_header().tot_len = htons(size()); }\n\n const ip4::Header& ip_header() const noexcept\n { return *reinterpret_cast(layer_begin()); }\n\n ip4::Header& ip_header() noexcept\n { return *reinterpret_cast(layer_begin()); }\n\n }; \/\/< class PacketIP4\n} \/\/< namespace net\n\n#endif \/\/< IP4_PACKET_IP4_HPP\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cx_dsapi.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 18:56:18 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef ADC_CX_DSAPI_HXX\n#define ADC_CX_DSAPI_HXX\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n#include \n \/\/ COMPONENTS\n#include \n#include \n \/\/ PARAMETERS\n\n\nnamespace csi\n{\nnamespace dsapi\n{\n\nclass Token_Receiver;\nclass Token;\n\nclass Cx_EoHtml;\nclass Cx_EoXmlConst;\nclass Cx_EoXmlLink_BeginTag;\nclass Cx_EoXmlLink_EndTag;\nclass Cx_EoXmlFormat_BeginTag;\nclass Cx_EoXmlFormat_EndTag;\nclass Cx_CheckStar;\n\n\/**\n@descr\n*\/\nclass Context_Docu : public TkpDocuContext,\n private StateMachineContext\n{\n public:\n \/\/ LIFECYCLE\n Context_Docu(\n Token_Receiver & o_rReceiver );\n virtual void SetParentContext(\n TkpContext & io_rParentContext,\n const char * i_sMultiLineEndToken );\n\n ~Context_Docu();\n \/\/ OPERATIONS\n virtual void ReadCharChain(\n CharacterSource & io_rText );\n\n virtual bool PassNewToken();\n virtual void SetMode_IsMultiLine(\n bool i_bTrue );\n\n \/\/ INQUIRY\n virtual TkpContext &\n FollowUpContext();\n private:\n \/\/ SERVICE FUNCTIONS\n virtual void PerformStatusFunction(\n uintt i_nStatusSignal,\n UINT16 i_nTokenId,\n CharacterSource & io_rText );\n\n void SetupStateMachine();\n\n \/\/ DATA\n StateMachin2 aStateMachine;\n Token_Receiver * pReceiver;\n\n \/\/ Contexts\n TkpContext * pParentContext;\n udmstri sMultiLineEndToken;\n\n Dyn pCx_EoHtml;\n Dyn pCx_EoXmlConst;\n Dyn\n pCx_EoXmlLink_BeginTag;\n Dyn\n pCx_EoXmlLink_EndTag;\n Dyn\n pCx_EoXmlFormat_BeginTag;\n Dyn\n pCx_EoXmlFormat_EndTag;\n Dyn pCx_CheckStar;\n\n \/\/ Temporary data, used during ReadCharChain()\n Dyn pNewToken;\n ::TkpContext * pFollowUpContext;\n bool bIsMultiline;\n};\n\n\n} \/\/ namespace dsapi\n} \/\/ namespace csi\n\n\n#endif\n\nINTEGRATION: CWS adc18 (1.2.56); FILE MERGED 2007\/10\/19 10:37:32 np 1.2.56.2: #i81775# 2007\/10\/18 15:23:21 np 1.2.56.1: #i81775#\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cx_dsapi.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2007-11-02 17:12:06 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef ADC_CX_DSAPI_HXX\n#define ADC_CX_DSAPI_HXX\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n#include \n \/\/ COMPONENTS\n#include \n#include \n \/\/ PARAMETERS\n\n\nnamespace csi\n{\nnamespace dsapi\n{\n\nclass Token_Receiver;\nclass Token;\n\nclass Cx_EoHtml;\nclass Cx_EoXmlConst;\nclass Cx_EoXmlLink_BeginTag;\nclass Cx_EoXmlLink_EndTag;\nclass Cx_EoXmlFormat_BeginTag;\nclass Cx_EoXmlFormat_EndTag;\nclass Cx_CheckStar;\n\n\/**\n@descr\n*\/\nclass Context_Docu : public TkpDocuContext,\n private StateMachineContext\n{\n public:\n \/\/ LIFECYCLE\n Context_Docu(\n Token_Receiver & o_rReceiver );\n virtual void SetParentContext(\n TkpContext & io_rParentContext,\n const char * i_sMultiLineEndToken );\n\n ~Context_Docu();\n \/\/ OPERATIONS\n virtual void ReadCharChain(\n CharacterSource & io_rText );\n\n virtual bool PassNewToken();\n virtual void SetMode_IsMultiLine(\n bool i_bTrue );\n\n \/\/ INQUIRY\n virtual TkpContext &\n FollowUpContext();\n private:\n \/\/ SERVICE FUNCTIONS\n virtual void PerformStatusFunction(\n uintt i_nStatusSignal,\n UINT16 i_nTokenId,\n CharacterSource & io_rText );\n\n void SetupStateMachine();\n\n \/\/ DATA\n StateMachin2 aStateMachine;\n Token_Receiver * pReceiver;\n\n \/\/ Contexts\n TkpContext * pParentContext;\n String sMultiLineEndToken;\n\n Dyn pCx_EoHtml;\n Dyn pCx_EoXmlConst;\n Dyn\n pCx_EoXmlLink_BeginTag;\n Dyn\n pCx_EoXmlLink_EndTag;\n Dyn\n pCx_EoXmlFormat_BeginTag;\n Dyn\n pCx_EoXmlFormat_EndTag;\n Dyn pCx_CheckStar;\n\n \/\/ Temporary data, used during ReadCharChain()\n Dyn pNewToken;\n ::TkpContext * pFollowUpContext;\n bool bIsMultiline;\n};\n\n\n} \/\/ namespace dsapi\n} \/\/ namespace csi\n\n\n#endif\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: docu_pe2.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2007-07-31 16:09:44 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef ADC_DSAPI_DOCU_PE2_HXX\n#define ADC_DSAPI_DOCU_PE2_HXX\n\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n#include \n \/\/ COMPONENTS\n \/\/ PARAMETERS\n\nclass ParserInfo;\n\nnamespace ary\n{\nnamespace info\n{\nclass CodeInformation;\nclass DocuToken;\n} \/\/ namespace info\n} \/\/ namespace ary\n\n\n\nnamespace csi\n{\nnamespace dsapi\n{\n\n\nclass Token;\nclass DT_AtTag;\n\nclass SapiDocu_PE : public TokenInterpreter\n{\n public:\n SapiDocu_PE(\n ParserInfo & io_rPositionInfo );\n ~SapiDocu_PE();\n\n void ProcessToken(\n DYN csi::dsapi::Token &\n let_drToken );\n\n virtual void Process_AtTag(\n const Tok_AtTag & i_rToken );\n virtual void Process_HtmlTag(\n const Tok_HtmlTag & i_rToken );\n virtual void Process_XmlConst(\n const Tok_XmlConst &\n i_rToken );\n virtual void Process_XmlLink_BeginTag(\n const Tok_XmlLink_BeginTag &\n i_rToken );\n virtual void Process_XmlLink_EndTag(\n const Tok_XmlLink_EndTag &\n i_rToken );\n virtual void Process_XmlFormat_BeginTag(\n const Tok_XmlFormat_BeginTag &\n i_rToken );\n virtual void Process_XmlFormat_EndTag(\n const Tok_XmlFormat_EndTag &\n i_rToken );\n virtual void Process_Word(\n const Tok_Word & i_rToken );\n virtual void Process_Comma();\n virtual void Process_DocuEnd();\n virtual void Process_EOL();\n\n\n DYN ary::info::CodeInformation *\n ReleaseJustParsedDocu();\n\n bool IsComplete() const;\n\n private:\n enum E_State\n {\n e_none = 0,\n st_short,\n st_description,\n st_attags,\n st_complete\n };\n\n typedef void ( SapiDocu_PE::*F_TokenAdder )( DYN ary::info::DocuToken & let_drNewToken );\n\n void AddDocuToken2Void(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void AddDocuToken2Short(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void AddDocuToken2Description(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void AddDocuToken2Deprecated(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void AddDocuToken2CurAtTag(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void SetCurParameterAtTagName(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void SetCurSeeAlsoAtTagLinkText(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void SetCurSeeAlsoAtTagLinkText_2(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void SetCurSeeAlsoAtTagLinkText_3(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void SetCurSinceAtTagVersion(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void AddDocuToken2SinceAtTag(\n DYN ary::info::DocuToken &\n let_drNewToken );\n\n \/\/ DATA\n Dyn\n pDocu;\n E_State eState;\n ParserInfo * pPositionInfo;\n F_TokenAdder fCurTokenAddFunction;\n\n Dyn pCurAtTag;\n String sCurDimAttribute;\n StreamStr sCurAtSeeType_byXML;\n};\n\n} \/\/ namespace dsapi\n} \/\/ namespace csi\n\n\n\/\/ IMPLEMENTATION\n\n\n#endif\n\nINTEGRATION: CWS adc17 (1.6.2); FILE MERGED 2007\/08\/10 10:37:10 np 1.6.2.1: #i23626 correct spacing in autodoc output#\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: docu_pe2.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2007-09-18 14:26:32 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef ADC_DSAPI_DOCU_PE2_HXX\n#define ADC_DSAPI_DOCU_PE2_HXX\n\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n#include \n \/\/ COMPONENTS\n \/\/ PARAMETERS\n\nclass ParserInfo;\n\nnamespace ary\n{\nnamespace info\n{\nclass CodeInformation;\nclass DocuToken;\n} \/\/ namespace info\n} \/\/ namespace ary\n\n\n\nnamespace csi\n{\nnamespace dsapi\n{\n\n\nclass Token;\nclass DT_AtTag;\n\nclass SapiDocu_PE : public TokenInterpreter\n{\n public:\n SapiDocu_PE(\n ParserInfo & io_rPositionInfo );\n ~SapiDocu_PE();\n\n void ProcessToken(\n DYN csi::dsapi::Token &\n let_drToken );\n\n virtual void Process_AtTag(\n const Tok_AtTag & i_rToken );\n virtual void Process_HtmlTag(\n const Tok_HtmlTag & i_rToken );\n virtual void Process_XmlConst(\n const Tok_XmlConst &\n i_rToken );\n virtual void Process_XmlLink_BeginTag(\n const Tok_XmlLink_BeginTag &\n i_rToken );\n virtual void Process_XmlLink_EndTag(\n const Tok_XmlLink_EndTag &\n i_rToken );\n virtual void Process_XmlFormat_BeginTag(\n const Tok_XmlFormat_BeginTag &\n i_rToken );\n virtual void Process_XmlFormat_EndTag(\n const Tok_XmlFormat_EndTag &\n i_rToken );\n virtual void Process_Word(\n const Tok_Word & i_rToken );\n virtual void Process_Comma();\n virtual void Process_DocuEnd();\n virtual void Process_EOL();\n virtual void Process_White();\n\n\n DYN ary::info::CodeInformation *\n ReleaseJustParsedDocu();\n\n bool IsComplete() const;\n\n private:\n enum E_State\n {\n e_none = 0,\n st_short,\n st_description,\n st_attags,\n st_complete\n };\n\n typedef void ( SapiDocu_PE::*F_TokenAdder )( DYN ary::info::DocuToken & let_drNewToken );\n\n void AddDocuToken2Void(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void AddDocuToken2Short(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void AddDocuToken2Description(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void AddDocuToken2Deprecated(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void AddDocuToken2CurAtTag(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void SetCurParameterAtTagName(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void SetCurSeeAlsoAtTagLinkText(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void SetCurSeeAlsoAtTagLinkText_2(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void SetCurSeeAlsoAtTagLinkText_3(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void SetCurSinceAtTagVersion(\n DYN ary::info::DocuToken &\n let_drNewToken );\n void AddDocuToken2SinceAtTag(\n DYN ary::info::DocuToken &\n let_drNewToken );\n\n \/\/ DATA\n Dyn\n pDocu;\n E_State eState;\n ParserInfo * pPositionInfo;\n F_TokenAdder fCurTokenAddFunction;\n\n Dyn pCurAtTag;\n String sCurDimAttribute;\n StreamStr sCurAtSeeType_byXML;\n};\n\n} \/\/ namespace dsapi\n} \/\/ namespace csi\n\n\n\/\/ IMPLEMENTATION\n\n\n#endif\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/crash_handler_host_linux.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/file_path.h\"\n#include \"base\/format_macros.h\"\n#include \"base\/linux_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/path_service.h\"\n#include \"base\/rand_util.h\"\n#include \"base\/string_util.h\"\n#include \"breakpad\/src\/client\/linux\/handler\/exception_handler.h\"\n#include \"breakpad\/src\/client\/linux\/minidump_writer\/linux_dumper.h\"\n#include \"breakpad\/src\/client\/linux\/minidump_writer\/minidump_writer.h\"\n#include \"chrome\/app\/breakpad_linux.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/env_vars.h\"\n\nusing google_breakpad::ExceptionHandler;\n\n\/\/ Since classes derived from CrashHandlerHostLinux are singletons, it's only\n\/\/ destroyed at the end of the processes lifetime, which is greater in span than\n\/\/ the lifetime of the IO message loop.\nDISABLE_RUNNABLE_METHOD_REFCOUNT(CrashHandlerHostLinux);\n\nCrashHandlerHostLinux::CrashHandlerHostLinux()\n : process_socket_(-1),\n browser_socket_(-1) {\n int fds[2];\n \/\/ We use SOCK_SEQPACKET rather than SOCK_DGRAM to prevent the process from\n \/\/ sending datagrams to other sockets on the system. The sandbox may prevent\n \/\/ the process from calling socket() to create new sockets, but it'll still\n \/\/ inherit some sockets. With PF_UNIX+SOCK_DGRAM, it can call sendmsg to send\n \/\/ a datagram to any (abstract) socket on the same system. With\n \/\/ SOCK_SEQPACKET, this is prevented.\n CHECK_EQ(socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds), 0);\n static const int on = 1;\n\n \/\/ Enable passcred on the server end of the socket\n CHECK_EQ(setsockopt(fds[1], SOL_SOCKET, SO_PASSCRED, &on, sizeof(on)), 0);\n\n process_socket_ = fds[0];\n browser_socket_ = fds[1];\n\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this, &CrashHandlerHostLinux::Init));\n}\n\nCrashHandlerHostLinux::~CrashHandlerHostLinux() {\n HANDLE_EINTR(close(process_socket_));\n HANDLE_EINTR(close(browser_socket_));\n}\n\nvoid CrashHandlerHostLinux::Init() {\n MessageLoopForIO* ml = MessageLoopForIO::current();\n CHECK(ml->WatchFileDescriptor(\n browser_socket_, true \/* persistent *\/,\n MessageLoopForIO::WATCH_READ,\n &file_descriptor_watcher_, this));\n ml->AddDestructionObserver(this);\n}\n\nvoid CrashHandlerHostLinux::OnFileCanWriteWithoutBlocking(int fd) {\n DCHECK(false);\n}\n\nvoid CrashHandlerHostLinux::OnFileCanReadWithoutBlocking(int fd) {\n DCHECK_EQ(fd, browser_socket_);\n\n \/\/ A process has crashed and has signaled us by writing a datagram\n \/\/ to the death signal socket. The datagram contains the crash context needed\n \/\/ for writing the minidump as well as a file descriptor and a credentials\n \/\/ block so that they can't lie about their pid.\n\n \/\/ The length of the control message:\n static const unsigned kControlMsgSize =\n CMSG_SPACE(sizeof(int)) + CMSG_SPACE(sizeof(struct ucred));\n \/\/ The length of the regular payload:\n static const unsigned kCrashContextSize =\n sizeof(ExceptionHandler::CrashContext);\n\n struct msghdr msg = {0};\n struct iovec iov[6];\n char crash_context[kCrashContextSize];\n char guid[kGuidSize + 1];\n char crash_url[kMaxActiveURLSize + 1];\n char distro[kDistroSize + 1];\n char* tid_buf_addr = NULL;\n int tid_fd = -1;\n char control[kControlMsgSize];\n const ssize_t expected_msg_size = sizeof(crash_context) + sizeof(guid) +\n sizeof(crash_url) + sizeof(distro) +\n sizeof(tid_buf_addr) + sizeof(tid_fd);\n\n iov[0].iov_base = crash_context;\n iov[0].iov_len = sizeof(crash_context);\n iov[1].iov_base = guid;\n iov[1].iov_len = sizeof(guid);\n iov[2].iov_base = crash_url;\n iov[2].iov_len = sizeof(crash_url);\n iov[3].iov_base = distro;\n iov[3].iov_len = sizeof(distro);\n iov[4].iov_base = &tid_buf_addr;\n iov[4].iov_len = sizeof(tid_buf_addr);\n iov[5].iov_base = &tid_fd;\n iov[5].iov_len = sizeof(tid_fd);\n msg.msg_iov = iov;\n msg.msg_iovlen = 6;\n msg.msg_control = control;\n msg.msg_controllen = kControlMsgSize;\n\n const ssize_t msg_size = HANDLE_EINTR(recvmsg(browser_socket_, &msg, 0));\n if (msg_size != expected_msg_size) {\n LOG(ERROR) << \"Error reading from death signal socket. Crash dumping\"\n << \" is disabled.\"\n << \" msg_size:\" << msg_size\n << \" errno:\" << errno;\n file_descriptor_watcher_.StopWatchingFileDescriptor();\n return;\n }\n\n if (msg.msg_controllen != kControlMsgSize ||\n msg.msg_flags & ~MSG_TRUNC) {\n LOG(ERROR) << \"Received death signal message with the wrong size;\"\n << \" msg.msg_controllen:\" << msg.msg_controllen\n << \" msg.msg_flags:\" << msg.msg_flags\n << \" kCrashContextSize:\" << kCrashContextSize\n << \" kControlMsgSize:\" << kControlMsgSize;\n return;\n }\n\n \/\/ Walk the control payload an extract the file descriptor and validated pid.\n pid_t crashing_pid = -1;\n int partner_fd = -1;\n int signal_fd = -1;\n for (struct cmsghdr *hdr = CMSG_FIRSTHDR(&msg); hdr;\n hdr = CMSG_NXTHDR(&msg, hdr)) {\n if (hdr->cmsg_level != SOL_SOCKET)\n continue;\n if (hdr->cmsg_type == SCM_RIGHTS) {\n const unsigned len = hdr->cmsg_len -\n (((uint8_t*)CMSG_DATA(hdr)) - (uint8_t*)hdr);\n DCHECK_EQ(len % sizeof(int), 0u);\n const unsigned num_fds = len \/ sizeof(int);\n if (num_fds != 2) {\n \/\/ A nasty process could try and send us too many descriptors and\n \/\/ force a leak.\n LOG(ERROR) << \"Death signal contained wrong number of descriptors;\"\n << \" num_fds:\" << num_fds;\n for (unsigned i = 0; i < num_fds; ++i)\n HANDLE_EINTR(close(reinterpret_cast(CMSG_DATA(hdr))[i]));\n return;\n } else {\n partner_fd = reinterpret_cast(CMSG_DATA(hdr))[0];\n signal_fd = reinterpret_cast(CMSG_DATA(hdr))[1];\n }\n } else if (hdr->cmsg_type == SCM_CREDENTIALS) {\n const struct ucred *cred =\n reinterpret_cast(CMSG_DATA(hdr));\n crashing_pid = cred->pid;\n }\n }\n\n if (crashing_pid == -1 || partner_fd == -1 || signal_fd == -1) {\n LOG(ERROR) << \"Death signal message didn't contain all expected control\"\n << \" messages\";\n if (partner_fd >= 0)\n HANDLE_EINTR(close(partner_fd));\n if (signal_fd >= 0)\n HANDLE_EINTR(close(signal_fd));\n return;\n }\n\n \/\/ Kernel bug workaround (broken in 2.6.30 at least):\n \/\/ The kernel doesn't translate PIDs in SCM_CREDENTIALS across PID\n \/\/ namespaces. Thus |crashing_pid| might be garbage from our point of view.\n \/\/ In the future we can remove this workaround, but we have to wait a couple\n \/\/ of years to be sure that it's worked its way out into the world.\n\n \/\/ The crashing process closes its copy of the signal_fd immediately after\n \/\/ calling sendmsg(). We can thus not reliably look for with with\n \/\/ FindProcessHoldingSocket(). But by necessity, it has to keep the\n \/\/ partner_fd open until the crashdump is complete.\n uint64_t inode_number;\n if (!base::FileDescriptorGetInode(&inode_number, partner_fd)) {\n LOG(WARNING) << \"Failed to get inode number for passed socket\";\n HANDLE_EINTR(close(partner_fd));\n HANDLE_EINTR(close(signal_fd));\n return;\n }\n HANDLE_EINTR(close(partner_fd));\n\n pid_t actual_crashing_pid = -1;\n if (!base::FindProcessHoldingSocket(&actual_crashing_pid, inode_number)) {\n LOG(WARNING) << \"Failed to find process holding other end of crash reply \"\n \"socket\";\n HANDLE_EINTR(close(signal_fd));\n return;\n }\n\n if (actual_crashing_pid != crashing_pid) {\n crashing_pid = actual_crashing_pid;\n\n \/\/ The crashing TID set inside the compromised context via sys_gettid()\n \/\/ in ExceptionHandler::HandleSignal is also wrong and needs to be\n \/\/ translated.\n \/\/\n \/\/ We expect the crashing thread to be in sys_read(), waiting for use to\n \/\/ write to |signal_fd|. Most newer kernels where we have the different pid\n \/\/ namespaces also have \/proc\/[pid]\/syscall, so we can look through\n \/\/ |actual_crashing_pid|'s thread group and find the thread that's in the\n \/\/ read syscall with the right arguments.\n\n std::string expected_syscall_data;\n \/\/ \/proc\/[pid]\/syscall is formatted as follows:\n \/\/ syscall_number arg1 ... arg6 sp pc\n \/\/ but we just check syscall_number through arg3.\n StringAppendF(&expected_syscall_data, \"%d 0x%x %p 0x1 \",\n SYS_read, tid_fd, tid_buf_addr);\n pid_t crashing_tid =\n base::FindThreadIDWithSyscall(crashing_pid, expected_syscall_data);\n if (crashing_tid == -1) {\n \/\/ We didn't find the thread we want. Maybe it didn't reach sys_read()\n \/\/ yet, or the kernel doesn't support \/proc\/[pid]\/syscall or the thread\n \/\/ went away. We'll just take a guess here and assume the crashing\n \/\/ thread is the thread group leader.\n crashing_tid = crashing_pid;\n }\n\n ExceptionHandler::CrashContext* bad_context =\n reinterpret_cast(crash_context);\n bad_context->tid = crashing_tid;\n }\n\n bool upload = true;\n FilePath dumps_path(\"\/tmp\");\n if (getenv(env_vars::kHeadless)) {\n upload = false;\n PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path);\n }\n const uint64 rand = base::RandUint64();\n const std::string minidump_filename =\n StringPrintf(\"%s\/chromium-%s-minidump-%016\" PRIx64 \".dmp\",\n dumps_path.value().c_str(), process_type_.c_str(), rand);\n if (!google_breakpad::WriteMinidump(minidump_filename.c_str(),\n crashing_pid, crash_context,\n kCrashContextSize)) {\n LOG(ERROR) << \"Failed to write crash dump for pid \" << crashing_pid;\n HANDLE_EINTR(close(signal_fd));\n }\n\n \/\/ Send the done signal to the process: it can exit now.\n memset(&msg, 0, sizeof(msg));\n struct iovec done_iov;\n done_iov.iov_base = const_cast(\"\\x42\");\n done_iov.iov_len = 1;\n msg.msg_iov = &done_iov;\n msg.msg_iovlen = 1;\n\n HANDLE_EINTR(sendmsg(signal_fd, &msg, MSG_DONTWAIT | MSG_NOSIGNAL));\n HANDLE_EINTR(close(signal_fd));\n\n \/\/ Sanitize the string data a bit more\n guid[kGuidSize] = crash_url[kMaxActiveURLSize] = distro[kDistroSize] = 0;\n\n BreakpadInfo info;\n info.filename = minidump_filename.c_str();\n info.process_type = process_type_.c_str();\n info.process_type_length = process_type_.length();\n info.crash_url = crash_url;\n info.crash_url_length = strlen(crash_url);\n info.guid = guid;\n info.guid_length = strlen(guid);\n info.distro = distro;\n info.distro_length = strlen(distro);\n info.upload = upload;\n HandleCrashDump(info);\n}\n\nvoid CrashHandlerHostLinux::WillDestroyCurrentMessageLoop() {\n file_descriptor_watcher_.StopWatchingFileDescriptor();\n}\nChange the message size for breakpad notifications. Due to alignment issues, this does not seem to a problem on x86-64, but on x86-32 we would encounter assertion failures.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/crash_handler_host_linux.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/file_path.h\"\n#include \"base\/format_macros.h\"\n#include \"base\/linux_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/path_service.h\"\n#include \"base\/rand_util.h\"\n#include \"base\/string_util.h\"\n#include \"breakpad\/src\/client\/linux\/handler\/exception_handler.h\"\n#include \"breakpad\/src\/client\/linux\/minidump_writer\/linux_dumper.h\"\n#include \"breakpad\/src\/client\/linux\/minidump_writer\/minidump_writer.h\"\n#include \"chrome\/app\/breakpad_linux.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/env_vars.h\"\n\nusing google_breakpad::ExceptionHandler;\n\n\/\/ Since classes derived from CrashHandlerHostLinux are singletons, it's only\n\/\/ destroyed at the end of the processes lifetime, which is greater in span than\n\/\/ the lifetime of the IO message loop.\nDISABLE_RUNNABLE_METHOD_REFCOUNT(CrashHandlerHostLinux);\n\nCrashHandlerHostLinux::CrashHandlerHostLinux()\n : process_socket_(-1),\n browser_socket_(-1) {\n int fds[2];\n \/\/ We use SOCK_SEQPACKET rather than SOCK_DGRAM to prevent the process from\n \/\/ sending datagrams to other sockets on the system. The sandbox may prevent\n \/\/ the process from calling socket() to create new sockets, but it'll still\n \/\/ inherit some sockets. With PF_UNIX+SOCK_DGRAM, it can call sendmsg to send\n \/\/ a datagram to any (abstract) socket on the same system. With\n \/\/ SOCK_SEQPACKET, this is prevented.\n CHECK_EQ(socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds), 0);\n static const int on = 1;\n\n \/\/ Enable passcred on the server end of the socket\n CHECK_EQ(setsockopt(fds[1], SOL_SOCKET, SO_PASSCRED, &on, sizeof(on)), 0);\n\n process_socket_ = fds[0];\n browser_socket_ = fds[1];\n\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this, &CrashHandlerHostLinux::Init));\n}\n\nCrashHandlerHostLinux::~CrashHandlerHostLinux() {\n HANDLE_EINTR(close(process_socket_));\n HANDLE_EINTR(close(browser_socket_));\n}\n\nvoid CrashHandlerHostLinux::Init() {\n MessageLoopForIO* ml = MessageLoopForIO::current();\n CHECK(ml->WatchFileDescriptor(\n browser_socket_, true \/* persistent *\/,\n MessageLoopForIO::WATCH_READ,\n &file_descriptor_watcher_, this));\n ml->AddDestructionObserver(this);\n}\n\nvoid CrashHandlerHostLinux::OnFileCanWriteWithoutBlocking(int fd) {\n DCHECK(false);\n}\n\nvoid CrashHandlerHostLinux::OnFileCanReadWithoutBlocking(int fd) {\n DCHECK_EQ(fd, browser_socket_);\n\n \/\/ A process has crashed and has signaled us by writing a datagram\n \/\/ to the death signal socket. The datagram contains the crash context needed\n \/\/ for writing the minidump as well as a file descriptor and a credentials\n \/\/ block so that they can't lie about their pid.\n\n \/\/ The length of the control message:\n static const unsigned kControlMsgSize =\n CMSG_SPACE(2*sizeof(int)) + CMSG_SPACE(sizeof(struct ucred));\n \/\/ The length of the regular payload:\n static const unsigned kCrashContextSize =\n sizeof(ExceptionHandler::CrashContext);\n\n struct msghdr msg = {0};\n struct iovec iov[6];\n char crash_context[kCrashContextSize];\n char guid[kGuidSize + 1];\n char crash_url[kMaxActiveURLSize + 1];\n char distro[kDistroSize + 1];\n char* tid_buf_addr = NULL;\n int tid_fd = -1;\n char control[kControlMsgSize];\n const ssize_t expected_msg_size = sizeof(crash_context) + sizeof(guid) +\n sizeof(crash_url) + sizeof(distro) +\n sizeof(tid_buf_addr) + sizeof(tid_fd);\n\n iov[0].iov_base = crash_context;\n iov[0].iov_len = sizeof(crash_context);\n iov[1].iov_base = guid;\n iov[1].iov_len = sizeof(guid);\n iov[2].iov_base = crash_url;\n iov[2].iov_len = sizeof(crash_url);\n iov[3].iov_base = distro;\n iov[3].iov_len = sizeof(distro);\n iov[4].iov_base = &tid_buf_addr;\n iov[4].iov_len = sizeof(tid_buf_addr);\n iov[5].iov_base = &tid_fd;\n iov[5].iov_len = sizeof(tid_fd);\n msg.msg_iov = iov;\n msg.msg_iovlen = 6;\n msg.msg_control = control;\n msg.msg_controllen = kControlMsgSize;\n\n const ssize_t msg_size = HANDLE_EINTR(recvmsg(browser_socket_, &msg, 0));\n if (msg_size != expected_msg_size) {\n LOG(ERROR) << \"Error reading from death signal socket. Crash dumping\"\n << \" is disabled.\"\n << \" msg_size:\" << msg_size\n << \" errno:\" << errno;\n file_descriptor_watcher_.StopWatchingFileDescriptor();\n return;\n }\n\n if (msg.msg_controllen != kControlMsgSize ||\n msg.msg_flags & ~MSG_TRUNC) {\n LOG(ERROR) << \"Received death signal message with the wrong size;\"\n << \" msg.msg_controllen:\" << msg.msg_controllen\n << \" msg.msg_flags:\" << msg.msg_flags\n << \" kCrashContextSize:\" << kCrashContextSize\n << \" kControlMsgSize:\" << kControlMsgSize;\n return;\n }\n\n \/\/ Walk the control payload an extract the file descriptor and validated pid.\n pid_t crashing_pid = -1;\n int partner_fd = -1;\n int signal_fd = -1;\n for (struct cmsghdr *hdr = CMSG_FIRSTHDR(&msg); hdr;\n hdr = CMSG_NXTHDR(&msg, hdr)) {\n if (hdr->cmsg_level != SOL_SOCKET)\n continue;\n if (hdr->cmsg_type == SCM_RIGHTS) {\n const unsigned len = hdr->cmsg_len -\n (((uint8_t*)CMSG_DATA(hdr)) - (uint8_t*)hdr);\n DCHECK_EQ(len % sizeof(int), 0u);\n const unsigned num_fds = len \/ sizeof(int);\n if (num_fds != 2) {\n \/\/ A nasty process could try and send us too many descriptors and\n \/\/ force a leak.\n LOG(ERROR) << \"Death signal contained wrong number of descriptors;\"\n << \" num_fds:\" << num_fds;\n for (unsigned i = 0; i < num_fds; ++i)\n HANDLE_EINTR(close(reinterpret_cast(CMSG_DATA(hdr))[i]));\n return;\n } else {\n partner_fd = reinterpret_cast(CMSG_DATA(hdr))[0];\n signal_fd = reinterpret_cast(CMSG_DATA(hdr))[1];\n }\n } else if (hdr->cmsg_type == SCM_CREDENTIALS) {\n const struct ucred *cred =\n reinterpret_cast(CMSG_DATA(hdr));\n crashing_pid = cred->pid;\n }\n }\n\n if (crashing_pid == -1 || partner_fd == -1 || signal_fd == -1) {\n LOG(ERROR) << \"Death signal message didn't contain all expected control\"\n << \" messages\";\n if (partner_fd >= 0)\n HANDLE_EINTR(close(partner_fd));\n if (signal_fd >= 0)\n HANDLE_EINTR(close(signal_fd));\n return;\n }\n\n \/\/ Kernel bug workaround (broken in 2.6.30 at least):\n \/\/ The kernel doesn't translate PIDs in SCM_CREDENTIALS across PID\n \/\/ namespaces. Thus |crashing_pid| might be garbage from our point of view.\n \/\/ In the future we can remove this workaround, but we have to wait a couple\n \/\/ of years to be sure that it's worked its way out into the world.\n\n \/\/ The crashing process closes its copy of the signal_fd immediately after\n \/\/ calling sendmsg(). We can thus not reliably look for with with\n \/\/ FindProcessHoldingSocket(). But by necessity, it has to keep the\n \/\/ partner_fd open until the crashdump is complete.\n uint64_t inode_number;\n if (!base::FileDescriptorGetInode(&inode_number, partner_fd)) {\n LOG(WARNING) << \"Failed to get inode number for passed socket\";\n HANDLE_EINTR(close(partner_fd));\n HANDLE_EINTR(close(signal_fd));\n return;\n }\n HANDLE_EINTR(close(partner_fd));\n\n pid_t actual_crashing_pid = -1;\n if (!base::FindProcessHoldingSocket(&actual_crashing_pid, inode_number)) {\n LOG(WARNING) << \"Failed to find process holding other end of crash reply \"\n \"socket\";\n HANDLE_EINTR(close(signal_fd));\n return;\n }\n\n if (actual_crashing_pid != crashing_pid) {\n crashing_pid = actual_crashing_pid;\n\n \/\/ The crashing TID set inside the compromised context via sys_gettid()\n \/\/ in ExceptionHandler::HandleSignal is also wrong and needs to be\n \/\/ translated.\n \/\/\n \/\/ We expect the crashing thread to be in sys_read(), waiting for use to\n \/\/ write to |signal_fd|. Most newer kernels where we have the different pid\n \/\/ namespaces also have \/proc\/[pid]\/syscall, so we can look through\n \/\/ |actual_crashing_pid|'s thread group and find the thread that's in the\n \/\/ read syscall with the right arguments.\n\n std::string expected_syscall_data;\n \/\/ \/proc\/[pid]\/syscall is formatted as follows:\n \/\/ syscall_number arg1 ... arg6 sp pc\n \/\/ but we just check syscall_number through arg3.\n StringAppendF(&expected_syscall_data, \"%d 0x%x %p 0x1 \",\n SYS_read, tid_fd, tid_buf_addr);\n pid_t crashing_tid =\n base::FindThreadIDWithSyscall(crashing_pid, expected_syscall_data);\n if (crashing_tid == -1) {\n \/\/ We didn't find the thread we want. Maybe it didn't reach sys_read()\n \/\/ yet, or the kernel doesn't support \/proc\/[pid]\/syscall or the thread\n \/\/ went away. We'll just take a guess here and assume the crashing\n \/\/ thread is the thread group leader.\n crashing_tid = crashing_pid;\n }\n\n ExceptionHandler::CrashContext* bad_context =\n reinterpret_cast(crash_context);\n bad_context->tid = crashing_tid;\n }\n\n bool upload = true;\n FilePath dumps_path(\"\/tmp\");\n if (getenv(env_vars::kHeadless)) {\n upload = false;\n PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path);\n }\n const uint64 rand = base::RandUint64();\n const std::string minidump_filename =\n StringPrintf(\"%s\/chromium-%s-minidump-%016\" PRIx64 \".dmp\",\n dumps_path.value().c_str(), process_type_.c_str(), rand);\n if (!google_breakpad::WriteMinidump(minidump_filename.c_str(),\n crashing_pid, crash_context,\n kCrashContextSize)) {\n LOG(ERROR) << \"Failed to write crash dump for pid \" << crashing_pid;\n HANDLE_EINTR(close(signal_fd));\n }\n\n \/\/ Send the done signal to the process: it can exit now.\n memset(&msg, 0, sizeof(msg));\n struct iovec done_iov;\n done_iov.iov_base = const_cast(\"\\x42\");\n done_iov.iov_len = 1;\n msg.msg_iov = &done_iov;\n msg.msg_iovlen = 1;\n\n HANDLE_EINTR(sendmsg(signal_fd, &msg, MSG_DONTWAIT | MSG_NOSIGNAL));\n HANDLE_EINTR(close(signal_fd));\n\n \/\/ Sanitize the string data a bit more\n guid[kGuidSize] = crash_url[kMaxActiveURLSize] = distro[kDistroSize] = 0;\n\n BreakpadInfo info;\n info.filename = minidump_filename.c_str();\n info.process_type = process_type_.c_str();\n info.process_type_length = process_type_.length();\n info.crash_url = crash_url;\n info.crash_url_length = strlen(crash_url);\n info.guid = guid;\n info.guid_length = strlen(guid);\n info.distro = distro;\n info.distro_length = strlen(distro);\n info.upload = upload;\n HandleCrashDump(info);\n}\n\nvoid CrashHandlerHostLinux::WillDestroyCurrentMessageLoop() {\n file_descriptor_watcher_.StopWatchingFileDescriptor();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"app\/l10n_util.h\"\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/debugger\/devtools_client_host.h\"\n#include \"chrome\/browser\/debugger\/devtools_manager.h\"\n#include \"chrome\/browser\/debugger\/devtools_window.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents_view.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"grit\/generated_resources.h\"\n\nDevToolsWindow::DevToolsWindow(Profile* profile)\n : TabStripModelObserver(),\n inspected_tab_closing_(false) {\n static std::wstring g_wp_key = L\"\";\n if (g_wp_key.empty()) {\n \/\/ TODO(pfeldman): Make browser's getter for this key static.\n g_wp_key.append(prefs::kBrowserWindowPlacement);\n g_wp_key.append(L\"_\");\n g_wp_key.append(L\"DevToolsApp\");\n\n PrefService* prefs = g_browser_process->local_state();\n prefs->RegisterDictionaryPref(g_wp_key.c_str());\n\n const DictionaryValue* wp_pref = prefs->GetDictionary(g_wp_key.c_str());\n if (!wp_pref) {\n DictionaryValue* defaults = prefs->GetMutableDictionary(\r\n g_wp_key.c_str());\r\n defaults->SetInteger(L\"left\", 100);\r\n defaults->SetInteger(L\"top\", 100);\r\n defaults->SetInteger(L\"right\", 740);\r\n defaults->SetInteger(L\"bottom\", 740);\r\n defaults->SetBoolean(L\"maximized\", false);\r\n defaults->SetBoolean(L\"always_on_top\", false);\r\n }\n }\n\n browser_.reset(Browser::CreateForApp(L\"DevToolsApp\", profile, false));\n GURL contents(std::string(chrome::kChromeUIDevToolsURL) + \"devtools.html\");\n browser_->AddTabWithURL(contents, GURL(), PageTransition::START_PAGE, true,\n -1, false, NULL);\n tab_contents_ = browser_->GetSelectedTabContents();\n browser_->tabstrip_model()->AddObserver(this);\n}\n\nDevToolsWindow::~DevToolsWindow() {\n}\n\nvoid DevToolsWindow::Show() {\n browser_->window()->Show();\n tab_contents_->view()->SetInitialFocus();\n}\n\nDevToolsWindow* DevToolsWindow::AsDevToolsWindow() {\n return this;\n}\n\nRenderViewHost* DevToolsWindow::GetRenderViewHost() const {\n return tab_contents_->render_view_host();\n}\n\nvoid DevToolsWindow::InspectedTabClosing() {\n inspected_tab_closing_ = true;\n browser_->CloseAllTabs();\n}\n\nvoid DevToolsWindow::SendMessageToClient(const IPC::Message& message) {\n RenderViewHost* target_host = tab_contents_->render_view_host();\n IPC::Message* m = new IPC::Message(message);\n m->set_routing_id(target_host->routing_id());\n target_host->Send(m);\n}\n\nvoid DevToolsWindow::TabClosingAt(TabContents* contents, int index) {\n if (!inspected_tab_closing_ && contents == tab_contents_) {\n \/\/ Notify manager that this DevToolsClientHost no longer exists.\n NotifyCloseListener();\n }\n if (browser_->tabstrip_model()->empty()) {\n \/\/ We are removing the last tab. Delete browser along with the\n \/\/ tabstrip_model and its listeners.\n delete this;\n }\n}\nDevTools: Set Chrome icon to Dev Tools window. BUG=12687\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"app\/l10n_util.h\"\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/debugger\/devtools_client_host.h\"\n#include \"chrome\/browser\/debugger\/devtools_manager.h\"\n#include \"chrome\/browser\/debugger\/devtools_window.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/navigation_controller.h\"\n#include \"chrome\/browser\/tab_contents\/navigation_entry.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents_view.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"grit\/generated_resources.h\"\n\nDevToolsWindow::DevToolsWindow(Profile* profile)\n : TabStripModelObserver(),\n inspected_tab_closing_(false) {\n static std::wstring g_wp_key = L\"\";\n if (g_wp_key.empty()) {\n \/\/ TODO(pfeldman): Make browser's getter for this key static.\n g_wp_key.append(prefs::kBrowserWindowPlacement);\n g_wp_key.append(L\"_\");\n g_wp_key.append(L\"DevToolsApp\");\n\n PrefService* prefs = g_browser_process->local_state();\n prefs->RegisterDictionaryPref(g_wp_key.c_str());\n\n const DictionaryValue* wp_pref = prefs->GetDictionary(g_wp_key.c_str());\n if (!wp_pref) {\n DictionaryValue* defaults = prefs->GetMutableDictionary(\n g_wp_key.c_str());\n defaults->SetInteger(L\"left\", 100);\n defaults->SetInteger(L\"top\", 100);\n defaults->SetInteger(L\"right\", 740);\n defaults->SetInteger(L\"bottom\", 740);\n defaults->SetBoolean(L\"maximized\", false);\n defaults->SetBoolean(L\"always_on_top\", false);\n }\n }\n\n browser_.reset(Browser::CreateForApp(L\"DevToolsApp\", profile, false));\n GURL contents(std::string(chrome::kChromeUIDevToolsURL) + \"devtools.html\");\n browser_->AddTabWithURL(contents, GURL(), PageTransition::START_PAGE, true,\n -1, false, NULL);\n tab_contents_ = browser_->GetSelectedTabContents();\n browser_->tabstrip_model()->AddObserver(this);\n\n \/\/ Wipe out page icon so that the default application icon is used.\n NavigationEntry* entry = tab_contents_->controller().GetActiveEntry();\n entry->favicon().set_bitmap(SkBitmap());\n entry->favicon().set_is_valid(true);\n}\n\nDevToolsWindow::~DevToolsWindow() {\n}\n\nvoid DevToolsWindow::Show() {\n browser_->window()->Show();\n tab_contents_->view()->SetInitialFocus();\n}\n\nDevToolsWindow* DevToolsWindow::AsDevToolsWindow() {\n return this;\n}\n\nRenderViewHost* DevToolsWindow::GetRenderViewHost() const {\n return tab_contents_->render_view_host();\n}\n\nvoid DevToolsWindow::InspectedTabClosing() {\n inspected_tab_closing_ = true;\n browser_->CloseAllTabs();\n}\n\nvoid DevToolsWindow::SendMessageToClient(const IPC::Message& message) {\n RenderViewHost* target_host = tab_contents_->render_view_host();\n IPC::Message* m = new IPC::Message(message);\n m->set_routing_id(target_host->routing_id());\n target_host->Send(m);\n}\n\nvoid DevToolsWindow::TabClosingAt(TabContents* contents, int index) {\n if (!inspected_tab_closing_ && contents == tab_contents_) {\n \/\/ Notify manager that this DevToolsClientHost no longer exists.\n NotifyCloseListener();\n }\n if (browser_->tabstrip_model()->empty()) {\n \/\/ We are removing the last tab. Delete browser along with the\n \/\/ tabstrip_model and its listeners.\n delete this;\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/crx_installer.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"base\/task.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/extensions\/convert_user_script.h\"\n#include \"chrome\/browser\/extensions\/extension_error_reporter.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/shell_integration.h\"\n#include \"chrome\/browser\/web_applications\/web_app.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/extensions\/extension_file_util.h\"\n#include \"chrome\/common\/extensions\/extension_constants.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"grit\/browser_resources.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nnamespace {\n \/\/ Helper function to delete files. This is used to avoid ugly casts which\n \/\/ would be necessary with PostMessage since file_util::Delete is overloaded.\n static void DeleteFileHelper(const FilePath& path, bool recursive) {\n file_util::Delete(path, recursive);\n }\n}\n\nCrxInstaller::CrxInstaller(const FilePath& install_directory,\n ExtensionsService* frontend,\n ExtensionInstallUI* client)\n : install_directory_(install_directory),\n install_source_(Extension::INTERNAL),\n delete_source_(false),\n allow_privilege_increase_(false),\n limit_web_extent_to_download_host_(false),\n create_app_shortcut_(false),\n frontend_(frontend),\n client_(client),\n apps_require_extension_mime_type_(false) {\n extensions_enabled_ = frontend_->extensions_enabled();\n}\n\nCrxInstaller::~CrxInstaller() {\n \/\/ Delete the temp directory and crx file as necessary. Note that the\n \/\/ destructor might be called on any thread, so we post a task to the file\n \/\/ thread to make sure the delete happens there.\n if (!temp_dir_.value().empty()) {\n ChromeThread::PostTask(\n ChromeThread::FILE, FROM_HERE,\n NewRunnableFunction(&DeleteFileHelper, temp_dir_, true));\n }\n\n if (delete_source_) {\n ChromeThread::PostTask(\n ChromeThread::FILE, FROM_HERE,\n NewRunnableFunction(&DeleteFileHelper, source_file_, false));\n }\n\n \/\/ Make sure the UI is deleted on the ui thread.\n ChromeThread::DeleteSoon(ChromeThread::UI, FROM_HERE, client_);\n client_ = NULL;\n}\n\nvoid CrxInstaller::InstallCrx(const FilePath& source_file) {\n source_file_ = source_file;\n\n FilePath user_data_temp_dir;\n CHECK(PathService::Get(chrome::DIR_USER_DATA_TEMP, &user_data_temp_dir));\n\n scoped_refptr unpacker(\n new SandboxedExtensionUnpacker(\n source_file,\n user_data_temp_dir,\n g_browser_process->resource_dispatcher_host(),\n this));\n\n ChromeThread::PostTask(\n ChromeThread::FILE, FROM_HERE,\n NewRunnableMethod(\n unpacker.get(), &SandboxedExtensionUnpacker::Start));\n}\n\nvoid CrxInstaller::InstallUserScript(const FilePath& source_file,\n const GURL& original_url) {\n DCHECK(!original_url.is_empty());\n\n source_file_ = source_file;\n original_url_ = original_url;\n\n ChromeThread::PostTask(\n ChromeThread::FILE, FROM_HERE,\n NewRunnableMethod(this, &CrxInstaller::ConvertUserScriptOnFileThread));\n}\n\nvoid CrxInstaller::ConvertUserScriptOnFileThread() {\n std::string error;\n Extension* extension = ConvertUserScriptToExtension(source_file_,\n original_url_, &error);\n if (!extension) {\n ReportFailureFromFileThread(error);\n return;\n }\n\n OnUnpackSuccess(extension->path(), extension->path(), extension);\n}\n\nvoid CrxInstaller::OnUnpackFailure(const std::string& error_message) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));\n ReportFailureFromFileThread(error_message);\n}\n\nvoid CrxInstaller::OnUnpackSuccess(const FilePath& temp_dir,\n const FilePath& extension_dir,\n Extension* extension) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));\n\n \/\/ Note: We take ownership of |extension| and |temp_dir|.\n extension_.reset(extension);\n temp_dir_ = temp_dir;\n\n \/\/ If the extension was downloaded, apps_require_extension_mime_type_\n \/\/ will be set. In this case, check that if the extension is an app,\n \/\/ it was served with the right mime type. Make an exception for file\n \/\/ URLs, which come from the users computer and have no headers.\n if (extension->is_app() &&\n !original_url_.SchemeIsFile() &&\n apps_require_extension_mime_type_ &&\n original_mime_type_ != Extension::kMimeType) {\n ReportFailureFromFileThread(StringPrintf(\n \"Applications must be served with content type %s.\",\n Extension::kMimeType));\n return;\n }\n\n \/\/ The unpack dir we don't have to delete explicity since it is a child of\n \/\/ the temp dir.\n unpacked_extension_root_ = extension_dir;\n\n \/\/ Only allow extensions with a gallery update url to be installed after\n \/\/ having been directly downloaded from the gallery.\n if (extension->update_url() == GURL(extension_urls::kGalleryUpdateURL) &&\n !ExtensionsService::IsGalleryDownloadURL(original_url_)) {\n ReportFailureFromFileThread(l10n_util::GetStringFUTF8(\n IDS_EXTENSION_DISALLOW_NON_DOWNLOADED_GALLERY_INSTALLS,\n l10n_util::GetStringUTF16(IDS_EXTENSION_WEB_STORE_TITLE)));\n return;\n }\n\n \/\/ Determine whether to allow installation. We always allow themes and\n \/\/ external installs.\n if (!extensions_enabled_ && !extension->is_theme() &&\n !Extension::IsExternalLocation(install_source_)) {\n ReportFailureFromFileThread(\"Extensions are not enabled.\");\n return;\n }\n\n \/\/ Make sure the expected id matches.\n \/\/ TODO(aa): Also support expected version?\n if (!expected_id_.empty() && expected_id_ != extension->id()) {\n ReportFailureFromFileThread(StringPrintf(\n \"ID in new extension manifest (%s) does not match expected id (%s)\",\n extension->id().c_str(),\n expected_id_.c_str()));\n return;\n }\n\n \/\/ Require that apps are served from the domain they claim in their extent,\n \/\/ or some ancestor domain.\n if (extension_->is_app() && limit_web_extent_to_download_host_) {\n URLPattern pattern;\n pattern.set_host(original_url_.host());\n pattern.set_match_subdomains(true);\n\n for (size_t i = 0; i < extension_->web_extent().patterns().size(); ++i) {\n if (!pattern.MatchesHost(extension_->web_extent().patterns()[i].host())) {\n ReportFailureFromFileThread(StringPrintf(\n \"Apps must be served from the host that they affect.\"));\n return;\n }\n }\n }\n\n if (client_ || extension_->GetFullLaunchURL().is_valid()) {\n Extension::DecodeIcon(extension_.get(), Extension::EXTENSION_ICON_LARGE,\n &install_icon_);\n }\n\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this, &CrxInstaller::ConfirmInstall));\n}\n\nvoid CrxInstaller::ConfirmInstall() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n if (frontend_->extension_prefs()->IsExtensionBlacklisted(extension_->id())) {\n LOG(INFO) << \"This extension: \" << extension_->id()\n << \" is blacklisted. Install failed.\";\n ReportFailureFromUIThread(\"This extension is blacklisted.\");\n return;\n }\n\n GURL overlapping_url;\n Extension* overlapping_extension =\n frontend_->GetExtensionByOverlappingWebExtent(extension_->web_extent());\n if (overlapping_extension) {\n ReportFailureFromUIThread(l10n_util::GetStringFUTF8(\n IDS_EXTENSION_OVERLAPPING_WEB_EXTENT,\n UTF8ToUTF16(overlapping_extension->name())));\n return;\n }\n\n current_version_ =\n frontend_->extension_prefs()->GetVersionString(extension_->id());\n\n if (client_) {\n AddRef(); \/\/ Balanced in Proceed() and Abort().\n client_->ConfirmInstall(this, extension_.get());\n } else {\n ChromeThread::PostTask(\n ChromeThread::FILE, FROM_HERE,\n NewRunnableMethod(this, &CrxInstaller::CompleteInstall));\n }\n return;\n}\n\nvoid CrxInstaller::InstallUIProceed(bool create_app_shortcut) {\n if (create_app_shortcut) {\n DCHECK(extension_->GetFullLaunchURL().is_valid());\n create_app_shortcut_ = true;\n }\n\n ChromeThread::PostTask(\n ChromeThread::FILE, FROM_HERE,\n NewRunnableMethod(this, &CrxInstaller::CompleteInstall));\n\n Release(); \/\/ balanced in ConfirmInstall().\n}\n\nvoid CrxInstaller::InstallUIAbort() {\n \/\/ Kill the theme loading bubble.\n NotificationService* service = NotificationService::current();\n service->Notify(NotificationType::NO_THEME_DETECTED,\n Source(this),\n NotificationService::NoDetails());\n Release(); \/\/ balanced in ConfirmInstall().\n\n \/\/ We're done. Since we don't post any more tasks to ourself, our ref count\n \/\/ should go to zero and we die. The destructor will clean up the temp dir.\n}\n\nvoid CrxInstaller::CompleteInstall() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));\n\n if (!current_version_.empty()) {\n scoped_ptr current_version(\n Version::GetVersionFromString(current_version_));\n if (current_version->CompareTo(*(extension_->version())) > 0) {\n ReportFailureFromFileThread(\"Attempted to downgrade extension.\");\n return;\n }\n }\n\n FilePath version_dir = extension_file_util::InstallExtension(\n unpacked_extension_root_,\n extension_->id(),\n extension_->VersionString(),\n install_directory_);\n if (version_dir.empty()) {\n ReportFailureFromFileThread(\n l10n_util::GetStringUTF8(\n IDS_EXTENSION_MOVE_DIRECTORY_TO_PROFILE_FAILED));\n return;\n }\n\n if (create_app_shortcut_) {\n SkBitmap icon = install_icon_.get() ? *install_icon_ :\n *ResourceBundle::GetSharedInstance().GetBitmapNamed(\n IDR_EXTENSION_DEFAULT_ICON);\n\n ShellIntegration::ShortcutInfo shortcut_info;\n shortcut_info.url = extension_->GetFullLaunchURL();\n shortcut_info.extension_id = UTF8ToUTF16(extension_->id());\n shortcut_info.title = UTF8ToUTF16(extension_->name());\n shortcut_info.description = UTF8ToUTF16(extension_->description());\n shortcut_info.favicon = icon;\n shortcut_info.create_on_desktop = true;\n\n \/\/ TODO(aa): Seems nasty to be reusing the old webapps code this way. What\n \/\/ baggage am I inheriting?\n web_app::CreateShortcut(frontend_->profile()->GetPath(), shortcut_info,\n NULL);\n }\n\n \/\/ This is lame, but we must reload the extension because absolute paths\n \/\/ inside the content scripts are established inside InitFromValue() and we\n \/\/ just moved the extension.\n \/\/ TODO(aa): All paths to resources inside extensions should be created\n \/\/ lazily and based on the Extension's root path at that moment.\n std::string error;\n extension_.reset(extension_file_util::LoadExtension(version_dir, true,\n &error));\n DCHECK(error.empty());\n extension_->set_location(install_source_);\n\n ReportSuccessFromFileThread();\n}\n\nvoid CrxInstaller::ReportFailureFromFileThread(const std::string& error) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this, &CrxInstaller::ReportFailureFromUIThread, error));\n}\n\nvoid CrxInstaller::ReportFailureFromUIThread(const std::string& error) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n\n NotificationService* service = NotificationService::current();\n service->Notify(NotificationType::EXTENSION_INSTALL_ERROR,\n Source(this),\n Details(&error));\n\n \/\/ This isn't really necessary, it is only used because unit tests expect to\n \/\/ see errors get reported via this interface.\n \/\/\n \/\/ TODO(aa): Need to go through unit tests and clean them up too, probably get\n \/\/ rid of this line.\n ExtensionErrorReporter::GetInstance()->ReportError(error, false); \/\/ quiet\n\n if (client_)\n client_->OnInstallFailure(error);\n}\n\nvoid CrxInstaller::ReportSuccessFromFileThread() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this, &CrxInstaller::ReportSuccessFromUIThread));\n}\n\nvoid CrxInstaller::ReportSuccessFromUIThread() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n\n \/\/ If there is a client, tell the client about installation.\n if (client_)\n client_->OnInstallSuccess(extension_.get());\n\n \/\/ Tell the frontend about the installation and hand off ownership of\n \/\/ extension_ to it.\n frontend_->OnExtensionInstalled(extension_.release(),\n allow_privilege_increase_);\n\n \/\/ We're done. We don't post any more tasks to ourselves so we are deleted\n \/\/ soon.\n}\nRemove download check for web store apps (temporarily).\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/crx_installer.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"base\/task.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/extensions\/convert_user_script.h\"\n#include \"chrome\/browser\/extensions\/extension_error_reporter.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/shell_integration.h\"\n#include \"chrome\/browser\/web_applications\/web_app.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/extensions\/extension_file_util.h\"\n#include \"chrome\/common\/extensions\/extension_constants.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"grit\/browser_resources.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nnamespace {\n \/\/ Helper function to delete files. This is used to avoid ugly casts which\n \/\/ would be necessary with PostMessage since file_util::Delete is overloaded.\n static void DeleteFileHelper(const FilePath& path, bool recursive) {\n file_util::Delete(path, recursive);\n }\n}\n\nCrxInstaller::CrxInstaller(const FilePath& install_directory,\n ExtensionsService* frontend,\n ExtensionInstallUI* client)\n : install_directory_(install_directory),\n install_source_(Extension::INTERNAL),\n delete_source_(false),\n allow_privilege_increase_(false),\n limit_web_extent_to_download_host_(false),\n create_app_shortcut_(false),\n frontend_(frontend),\n client_(client),\n apps_require_extension_mime_type_(false) {\n extensions_enabled_ = frontend_->extensions_enabled();\n}\n\nCrxInstaller::~CrxInstaller() {\n \/\/ Delete the temp directory and crx file as necessary. Note that the\n \/\/ destructor might be called on any thread, so we post a task to the file\n \/\/ thread to make sure the delete happens there.\n if (!temp_dir_.value().empty()) {\n ChromeThread::PostTask(\n ChromeThread::FILE, FROM_HERE,\n NewRunnableFunction(&DeleteFileHelper, temp_dir_, true));\n }\n\n if (delete_source_) {\n ChromeThread::PostTask(\n ChromeThread::FILE, FROM_HERE,\n NewRunnableFunction(&DeleteFileHelper, source_file_, false));\n }\n\n \/\/ Make sure the UI is deleted on the ui thread.\n ChromeThread::DeleteSoon(ChromeThread::UI, FROM_HERE, client_);\n client_ = NULL;\n}\n\nvoid CrxInstaller::InstallCrx(const FilePath& source_file) {\n source_file_ = source_file;\n\n FilePath user_data_temp_dir;\n CHECK(PathService::Get(chrome::DIR_USER_DATA_TEMP, &user_data_temp_dir));\n\n scoped_refptr unpacker(\n new SandboxedExtensionUnpacker(\n source_file,\n user_data_temp_dir,\n g_browser_process->resource_dispatcher_host(),\n this));\n\n ChromeThread::PostTask(\n ChromeThread::FILE, FROM_HERE,\n NewRunnableMethod(\n unpacker.get(), &SandboxedExtensionUnpacker::Start));\n}\n\nvoid CrxInstaller::InstallUserScript(const FilePath& source_file,\n const GURL& original_url) {\n DCHECK(!original_url.is_empty());\n\n source_file_ = source_file;\n original_url_ = original_url;\n\n ChromeThread::PostTask(\n ChromeThread::FILE, FROM_HERE,\n NewRunnableMethod(this, &CrxInstaller::ConvertUserScriptOnFileThread));\n}\n\nvoid CrxInstaller::ConvertUserScriptOnFileThread() {\n std::string error;\n Extension* extension = ConvertUserScriptToExtension(source_file_,\n original_url_, &error);\n if (!extension) {\n ReportFailureFromFileThread(error);\n return;\n }\n\n OnUnpackSuccess(extension->path(), extension->path(), extension);\n}\n\nvoid CrxInstaller::OnUnpackFailure(const std::string& error_message) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));\n ReportFailureFromFileThread(error_message);\n}\n\nvoid CrxInstaller::OnUnpackSuccess(const FilePath& temp_dir,\n const FilePath& extension_dir,\n Extension* extension) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));\n\n \/\/ Note: We take ownership of |extension| and |temp_dir|.\n extension_.reset(extension);\n temp_dir_ = temp_dir;\n\n \/\/ If the extension was downloaded, apps_require_extension_mime_type_\n \/\/ will be set. In this case, check that if the extension is an app,\n \/\/ it was served with the right mime type. Make an exception for file\n \/\/ URLs, which come from the users computer and have no headers.\n if (extension->is_app() &&\n !original_url_.SchemeIsFile() &&\n apps_require_extension_mime_type_ &&\n original_mime_type_ != Extension::kMimeType) {\n ReportFailureFromFileThread(StringPrintf(\n \"Applications must be served with content type %s.\",\n Extension::kMimeType));\n return;\n }\n\n \/\/ The unpack dir we don't have to delete explicity since it is a child of\n \/\/ the temp dir.\n unpacked_extension_root_ = extension_dir;\n\n \/\/ Determine whether to allow installation. We always allow themes and\n \/\/ external installs.\n if (!extensions_enabled_ && !extension->is_theme() &&\n !Extension::IsExternalLocation(install_source_)) {\n ReportFailureFromFileThread(\"Extensions are not enabled.\");\n return;\n }\n\n \/\/ Make sure the expected id matches.\n \/\/ TODO(aa): Also support expected version?\n if (!expected_id_.empty() && expected_id_ != extension->id()) {\n ReportFailureFromFileThread(StringPrintf(\n \"ID in new extension manifest (%s) does not match expected id (%s)\",\n extension->id().c_str(),\n expected_id_.c_str()));\n return;\n }\n\n \/\/ Require that apps are served from the domain they claim in their extent,\n \/\/ or some ancestor domain.\n if (extension_->is_app() && limit_web_extent_to_download_host_) {\n URLPattern pattern;\n pattern.set_host(original_url_.host());\n pattern.set_match_subdomains(true);\n\n for (size_t i = 0; i < extension_->web_extent().patterns().size(); ++i) {\n if (!pattern.MatchesHost(extension_->web_extent().patterns()[i].host())) {\n ReportFailureFromFileThread(StringPrintf(\n \"Apps must be served from the host that they affect.\"));\n return;\n }\n }\n }\n\n if (client_ || extension_->GetFullLaunchURL().is_valid()) {\n Extension::DecodeIcon(extension_.get(), Extension::EXTENSION_ICON_LARGE,\n &install_icon_);\n }\n\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this, &CrxInstaller::ConfirmInstall));\n}\n\nvoid CrxInstaller::ConfirmInstall() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n if (frontend_->extension_prefs()->IsExtensionBlacklisted(extension_->id())) {\n LOG(INFO) << \"This extension: \" << extension_->id()\n << \" is blacklisted. Install failed.\";\n ReportFailureFromUIThread(\"This extension is blacklisted.\");\n return;\n }\n\n GURL overlapping_url;\n Extension* overlapping_extension =\n frontend_->GetExtensionByOverlappingWebExtent(extension_->web_extent());\n if (overlapping_extension) {\n ReportFailureFromUIThread(l10n_util::GetStringFUTF8(\n IDS_EXTENSION_OVERLAPPING_WEB_EXTENT,\n UTF8ToUTF16(overlapping_extension->name())));\n return;\n }\n\n current_version_ =\n frontend_->extension_prefs()->GetVersionString(extension_->id());\n\n if (client_) {\n AddRef(); \/\/ Balanced in Proceed() and Abort().\n client_->ConfirmInstall(this, extension_.get());\n } else {\n ChromeThread::PostTask(\n ChromeThread::FILE, FROM_HERE,\n NewRunnableMethod(this, &CrxInstaller::CompleteInstall));\n }\n return;\n}\n\nvoid CrxInstaller::InstallUIProceed(bool create_app_shortcut) {\n if (create_app_shortcut) {\n DCHECK(extension_->GetFullLaunchURL().is_valid());\n create_app_shortcut_ = true;\n }\n\n ChromeThread::PostTask(\n ChromeThread::FILE, FROM_HERE,\n NewRunnableMethod(this, &CrxInstaller::CompleteInstall));\n\n Release(); \/\/ balanced in ConfirmInstall().\n}\n\nvoid CrxInstaller::InstallUIAbort() {\n \/\/ Kill the theme loading bubble.\n NotificationService* service = NotificationService::current();\n service->Notify(NotificationType::NO_THEME_DETECTED,\n Source(this),\n NotificationService::NoDetails());\n Release(); \/\/ balanced in ConfirmInstall().\n\n \/\/ We're done. Since we don't post any more tasks to ourself, our ref count\n \/\/ should go to zero and we die. The destructor will clean up the temp dir.\n}\n\nvoid CrxInstaller::CompleteInstall() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));\n\n if (!current_version_.empty()) {\n scoped_ptr current_version(\n Version::GetVersionFromString(current_version_));\n if (current_version->CompareTo(*(extension_->version())) > 0) {\n ReportFailureFromFileThread(\"Attempted to downgrade extension.\");\n return;\n }\n }\n\n FilePath version_dir = extension_file_util::InstallExtension(\n unpacked_extension_root_,\n extension_->id(),\n extension_->VersionString(),\n install_directory_);\n if (version_dir.empty()) {\n ReportFailureFromFileThread(\n l10n_util::GetStringUTF8(\n IDS_EXTENSION_MOVE_DIRECTORY_TO_PROFILE_FAILED));\n return;\n }\n\n if (create_app_shortcut_) {\n SkBitmap icon = install_icon_.get() ? *install_icon_ :\n *ResourceBundle::GetSharedInstance().GetBitmapNamed(\n IDR_EXTENSION_DEFAULT_ICON);\n\n ShellIntegration::ShortcutInfo shortcut_info;\n shortcut_info.url = extension_->GetFullLaunchURL();\n shortcut_info.extension_id = UTF8ToUTF16(extension_->id());\n shortcut_info.title = UTF8ToUTF16(extension_->name());\n shortcut_info.description = UTF8ToUTF16(extension_->description());\n shortcut_info.favicon = icon;\n shortcut_info.create_on_desktop = true;\n\n \/\/ TODO(aa): Seems nasty to be reusing the old webapps code this way. What\n \/\/ baggage am I inheriting?\n web_app::CreateShortcut(frontend_->profile()->GetPath(), shortcut_info,\n NULL);\n }\n\n \/\/ This is lame, but we must reload the extension because absolute paths\n \/\/ inside the content scripts are established inside InitFromValue() and we\n \/\/ just moved the extension.\n \/\/ TODO(aa): All paths to resources inside extensions should be created\n \/\/ lazily and based on the Extension's root path at that moment.\n std::string error;\n extension_.reset(extension_file_util::LoadExtension(version_dir, true,\n &error));\n DCHECK(error.empty());\n extension_->set_location(install_source_);\n\n ReportSuccessFromFileThread();\n}\n\nvoid CrxInstaller::ReportFailureFromFileThread(const std::string& error) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this, &CrxInstaller::ReportFailureFromUIThread, error));\n}\n\nvoid CrxInstaller::ReportFailureFromUIThread(const std::string& error) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n\n NotificationService* service = NotificationService::current();\n service->Notify(NotificationType::EXTENSION_INSTALL_ERROR,\n Source(this),\n Details(&error));\n\n \/\/ This isn't really necessary, it is only used because unit tests expect to\n \/\/ see errors get reported via this interface.\n \/\/\n \/\/ TODO(aa): Need to go through unit tests and clean them up too, probably get\n \/\/ rid of this line.\n ExtensionErrorReporter::GetInstance()->ReportError(error, false); \/\/ quiet\n\n if (client_)\n client_->OnInstallFailure(error);\n}\n\nvoid CrxInstaller::ReportSuccessFromFileThread() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this, &CrxInstaller::ReportSuccessFromUIThread));\n}\n\nvoid CrxInstaller::ReportSuccessFromUIThread() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n\n \/\/ If there is a client, tell the client about installation.\n if (client_)\n client_->OnInstallSuccess(extension_.get());\n\n \/\/ Tell the frontend about the installation and hand off ownership of\n \/\/ extension_ to it.\n frontend_->OnExtensionInstalled(extension_.release(),\n allow_privilege_increase_);\n\n \/\/ We're done. We don't post any more tasks to ourselves so we are deleted\n \/\/ soon.\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/history\/history_database.h\"\n\n#include \n#include \n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/rand_util.h\"\n#include \"base\/string_util.h\"\n#include \"sql\/transaction.h\"\n\n#if defined(OS_MACOSX)\n#include \"base\/mac\/mac_util.h\"\n#endif\n\nnamespace history {\n\nnamespace {\n\n\/\/ Current version number. We write databases at the \"current\" version number,\n\/\/ but any previous version that can read the \"compatible\" one can make do with\n\/\/ or database without *too* many bad effects.\nstatic const int kCurrentVersionNumber = 23;\nstatic const int kCompatibleVersionNumber = 16;\nstatic const char kEarlyExpirationThresholdKey[] = \"early_expiration_threshold\";\n\n\/\/ Key in the meta table used to determine if we need to migrate thumbnails out\n\/\/ of history.\nstatic const char kNeedsThumbnailMigrationKey[] = \"needs_thumbnail_migration\";\n\nvoid ComputeDatabaseMetrics(const FilePath& history_name,\n sql::Connection& db) {\n if (base::RandInt(1, 100) != 50)\n return; \/\/ Only do this computation sometimes since it can be expensive.\n\n int64 file_size = 0;\n if (!file_util::GetFileSize(history_name, &file_size))\n return;\n int file_mb = static_cast(file_size \/ (1024 * 1024));\n UMA_HISTOGRAM_MEMORY_MB(\"History.DatabaseFileMB\", file_mb);\n\n sql::Statement url_count(db.GetUniqueStatement(\"SELECT count(*) FROM urls\"));\n if (!url_count.Step())\n return;\n UMA_HISTOGRAM_COUNTS(\"History.URLTableCount\", url_count.ColumnInt(0));\n\n sql::Statement visit_count(db.GetUniqueStatement(\n \"SELECT count(*) FROM visits\"));\n if (!visit_count.Step())\n return;\n UMA_HISTOGRAM_COUNTS(\"History.VisitTableCount\", visit_count.ColumnInt(0));\n}\n\n} \/\/ namespace\n\nHistoryDatabase::HistoryDatabase()\n : needs_version_17_migration_(false) {\n}\n\nHistoryDatabase::~HistoryDatabase() {\n}\n\nsql::InitStatus HistoryDatabase::Init(const FilePath& history_name,\n sql::ErrorDelegate* error_delegate) {\n db_.set_error_histogram_name(\"Sqlite.History.Error\");\n\n \/\/ Set the exceptional sqlite error handler.\n db_.set_error_delegate(error_delegate);\n\n \/\/ Set the database page size to something a little larger to give us\n \/\/ better performance (we're typically seek rather than bandwidth limited).\n \/\/ This only has an effect before any tables have been created, otherwise\n \/\/ this is a NOP. Must be a power of 2 and a max of 8192.\n db_.set_page_size(4096);\n\n \/\/ Increase the cache size. The page size, plus a little extra, times this\n \/\/ value, tells us how much memory the cache will use maximum.\n \/\/ 6000 * 4MB = 24MB\n \/\/ TODO(brettw) scale this value to the amount of available memory.\n db_.set_cache_size(6000);\n\n \/\/ Note that we don't set exclusive locking here. That's done by\n \/\/ BeginExclusiveMode below which is called later (we have to be in shared\n \/\/ mode to start out for the in-memory backend to read the data).\n\n if (!db_.Open(history_name))\n return sql::INIT_FAILURE;\n\n \/\/ Wrap the rest of init in a tranaction. This will prevent the database from\n \/\/ getting corrupted if we crash in the middle of initialization or migration.\n sql::Transaction committer(&db_);\n if (!committer.Begin())\n return sql::INIT_FAILURE;\n\n#if defined(OS_MACOSX)\n \/\/ Exclude the history file from backups.\n base::mac::SetFileBackupExclusion(history_name);\n#endif\n\n \/\/ Prime the cache.\n db_.Preload();\n\n \/\/ Create the tables and indices.\n \/\/ NOTE: If you add something here, also add it to\n \/\/ RecreateAllButStarAndURLTables.\n if (!meta_table_.Init(&db_, GetCurrentVersion(), kCompatibleVersionNumber))\n return sql::INIT_FAILURE;\n if (!CreateURLTable(false) || !InitVisitTable() ||\n !InitKeywordSearchTermsTable() || !InitDownloadTable() ||\n !InitSegmentTables())\n return sql::INIT_FAILURE;\n CreateMainURLIndex();\n CreateKeywordSearchTermsIndices();\n\n \/\/ Version check.\n sql::InitStatus version_status = EnsureCurrentVersion();\n if (version_status != sql::INIT_OK)\n return version_status;\n\n ComputeDatabaseMetrics(history_name, db_);\n return committer.Commit() ? sql::INIT_OK : sql::INIT_FAILURE;\n}\n\nvoid HistoryDatabase::BeginExclusiveMode() {\n \/\/ We can't use set_exclusive_locking() since that only has an effect before\n \/\/ the DB is opened.\n ignore_result(db_.Execute(\"PRAGMA locking_mode=EXCLUSIVE\"));\n}\n\n\/\/ static\nint HistoryDatabase::GetCurrentVersion() {\n return kCurrentVersionNumber;\n}\n\nvoid HistoryDatabase::BeginTransaction() {\n db_.BeginTransaction();\n}\n\nvoid HistoryDatabase::CommitTransaction() {\n db_.CommitTransaction();\n}\n\nvoid HistoryDatabase::RollbackTransaction() {\n db_.RollbackTransaction();\n}\n\nbool HistoryDatabase::RecreateAllTablesButURL() {\n if (!DropVisitTable())\n return false;\n if (!InitVisitTable())\n return false;\n\n if (!DropKeywordSearchTermsTable())\n return false;\n if (!InitKeywordSearchTermsTable())\n return false;\n\n if (!DropSegmentTables())\n return false;\n if (!InitSegmentTables())\n return false;\n\n \/\/ We also add the supplementary URL indices at this point. This index is\n \/\/ over parts of the URL table that weren't automatically created when the\n \/\/ temporary URL table was\n CreateKeywordSearchTermsIndices();\n return true;\n}\n\nvoid HistoryDatabase::Vacuum() {\n DCHECK_EQ(0, db_.transaction_nesting()) <<\n \"Can not have a transaction when vacuuming.\";\n ignore_result(db_.Execute(\"VACUUM\"));\n}\n\nbool HistoryDatabase::Raze() {\n return db_.Raze();\n}\n\nvoid HistoryDatabase::ThumbnailMigrationDone() {\n meta_table_.SetValue(kNeedsThumbnailMigrationKey, 0);\n}\n\nbool HistoryDatabase::GetNeedsThumbnailMigration() {\n int value = 0;\n return (meta_table_.GetValue(kNeedsThumbnailMigrationKey, &value) &&\n value != 0);\n}\n\nbool HistoryDatabase::SetSegmentID(VisitID visit_id, SegmentID segment_id) {\n sql::Statement s(db_.GetCachedStatement(SQL_FROM_HERE,\n \"UPDATE visits SET segment_id = ? WHERE id = ?\"));\n s.BindInt64(0, segment_id);\n s.BindInt64(1, visit_id);\n DCHECK(db_.GetLastChangeCount() == 1);\n\n return s.Run();\n}\n\nSegmentID HistoryDatabase::GetSegmentID(VisitID visit_id) {\n sql::Statement s(db_.GetCachedStatement(SQL_FROM_HERE,\n \"SELECT segment_id FROM visits WHERE id = ?\"));\n s.BindInt64(0, visit_id);\n\n if (s.Step()) {\n if (s.ColumnType(0) == sql::COLUMN_TYPE_NULL)\n return 0;\n else\n return s.ColumnInt64(0);\n }\n return 0;\n}\n\nbase::Time HistoryDatabase::GetEarlyExpirationThreshold() {\n if (!cached_early_expiration_threshold_.is_null())\n return cached_early_expiration_threshold_;\n\n int64 threshold;\n if (!meta_table_.GetValue(kEarlyExpirationThresholdKey, &threshold)) {\n \/\/ Set to a very early non-zero time, so it's before all history, but not\n \/\/ zero to avoid re-retrieval.\n threshold = 1L;\n }\n\n cached_early_expiration_threshold_ = base::Time::FromInternalValue(threshold);\n return cached_early_expiration_threshold_;\n}\n\nvoid HistoryDatabase::UpdateEarlyExpirationThreshold(base::Time threshold) {\n meta_table_.SetValue(kEarlyExpirationThresholdKey,\n threshold.ToInternalValue());\n cached_early_expiration_threshold_ = threshold;\n}\n\nsql::Connection& HistoryDatabase::GetDB() {\n return db_;\n}\n\nsql::MetaTable& HistoryDatabase::GetMetaTable() {\n return meta_table_;\n}\n\n\/\/ Migration -------------------------------------------------------------------\n\nsql::InitStatus HistoryDatabase::EnsureCurrentVersion() {\n \/\/ We can't read databases newer than we were designed for.\n if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {\n LOG(WARNING) << \"History database is too new.\";\n return sql::INIT_TOO_NEW;\n }\n\n \/\/ NOTICE: If you are changing structures for things shared with the archived\n \/\/ history file like URLs, visits, or downloads, that will need migration as\n \/\/ well. Instead of putting such migration code in this class, it should be\n \/\/ in the corresponding file (url_database.cc, etc.) and called from here and\n \/\/ from the archived_database.cc.\n\n int cur_version = meta_table_.GetVersionNumber();\n\n \/\/ Put migration code here\n\n if (cur_version == 15) {\n if (!db_.Execute(\"DROP TABLE starred\") || !DropStarredIDFromURLs()) {\n LOG(WARNING) << \"Unable to update history database to version 16.\";\n return sql::INIT_FAILURE;\n }\n ++cur_version;\n meta_table_.SetVersionNumber(cur_version);\n meta_table_.SetCompatibleVersionNumber(\n std::min(cur_version, kCompatibleVersionNumber));\n }\n\n if (cur_version == 16) {\n#if !defined(OS_WIN)\n \/\/ In this version we bring the time format on Mac & Linux in sync with the\n \/\/ Windows version so that profiles can be moved between computers.\n MigrateTimeEpoch();\n#endif\n \/\/ On all platforms we bump the version number, so on Windows this\n \/\/ migration is a NOP. We keep the compatible version at 16 since things\n \/\/ will basically still work, just history will be in the future if an\n \/\/ old version reads it.\n ++cur_version;\n meta_table_.SetVersionNumber(cur_version);\n }\n\n if (cur_version == 17) {\n \/\/ Version 17 was for thumbnails to top sites migration. We ended up\n \/\/ disabling it though, so 17->18 does nothing.\n ++cur_version;\n meta_table_.SetVersionNumber(cur_version);\n }\n\n if (cur_version == 18) {\n \/\/ This is the version prior to adding url_source column. We need to\n \/\/ migrate the database.\n cur_version = 19;\n meta_table_.SetVersionNumber(cur_version);\n }\n\n if (cur_version == 19) {\n cur_version++;\n meta_table_.SetVersionNumber(cur_version);\n \/\/ Set a key indicating we need to migrate thumbnails. When successfull the\n \/\/ key is removed (ThumbnailMigrationDone).\n meta_table_.SetValue(kNeedsThumbnailMigrationKey, 1);\n }\n\n if (cur_version == 20) {\n \/\/ This is the version prior to adding the visit_duration field in visits\n \/\/ database. We need to migrate the database.\n if (!MigrateVisitsWithoutDuration()) {\n LOG(WARNING) << \"Unable to update history database to version 21.\";\n return sql::INIT_FAILURE;\n }\n ++cur_version;\n meta_table_.SetVersionNumber(cur_version);\n }\n\n if (cur_version == 21) {\n \/\/ The android_urls table's data schemal was changed in version 21.\n#if defined(OS_ANDROID)\n if (!MigrateToVersion22()) {\n LOG(WARNING) << \"Unable to migrate the android_urls table to version 22\";\n }\n#endif\n ++cur_version;\n meta_table_.SetVersionNumber(cur_version);\n }\n\n if (cur_version == 22) {\n if (!MigrateDownloadsState()) {\n LOG(WARNING) << \"Unable to fix invalid downloads state values\";\n \/\/ Invalid state values may cause crashes.\n return sql::INIT_FAILURE;\n }\n cur_version++;\n meta_table_.SetVersionNumber(cur_version);\n }\n\n \/\/ When the version is too old, we just try to continue anyway, there should\n \/\/ not be a released product that makes a database too old for us to handle.\n LOG_IF(WARNING, cur_version < GetCurrentVersion()) <<\n \"History database version \" << cur_version << \" is too old to handle.\";\n\n return sql::INIT_OK;\n}\n\n#if !defined(OS_WIN)\nvoid HistoryDatabase::MigrateTimeEpoch() {\n \/\/ Update all the times in the URLs and visits table in the main database.\n \/\/ For visits, clear the indexed flag since we'll delete the FTS databases in\n \/\/ the next step.\n ignore_result(db_.Execute(\n \"UPDATE urls \"\n \"SET last_visit_time = last_visit_time + 11644473600000000 \"\n \"WHERE id IN (SELECT id FROM urls WHERE last_visit_time > 0);\"));\n ignore_result(db_.Execute(\n \"UPDATE visits \"\n \"SET visit_time = visit_time + 11644473600000000, is_indexed = 0 \"\n \"WHERE id IN (SELECT id FROM visits WHERE visit_time > 0);\"));\n ignore_result(db_.Execute(\n \"UPDATE segment_usage \"\n \"SET time_slot = time_slot + 11644473600000000 \"\n \"WHERE id IN (SELECT id FROM segment_usage WHERE time_slot > 0);\"));\n\n \/\/ Erase all the full text index files. These will take a while to update and\n \/\/ are less important, so we just blow them away. Same with the archived\n \/\/ database.\n needs_version_17_migration_ = true;\n}\n#endif\n\n} \/\/ namespace history\nAdd history-view-related UMA metrics and histograms for locally managed users.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/history\/history_database.h\"\n\n#include \n#include \n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/rand_util.h\"\n#include \"base\/string_util.h\"\n#include \"base\/time.h\"\n#include \"sql\/transaction.h\"\n\n#if defined(OS_MACOSX)\n#include \"base\/mac\/mac_util.h\"\n#endif\n\nnamespace history {\n\nnamespace {\n\n\/\/ Current version number. We write databases at the \"current\" version number,\n\/\/ but any previous version that can read the \"compatible\" one can make do with\n\/\/ or database without *too* many bad effects.\nstatic const int kCurrentVersionNumber = 23;\nstatic const int kCompatibleVersionNumber = 16;\nstatic const char kEarlyExpirationThresholdKey[] = \"early_expiration_threshold\";\n\n\/\/ Key in the meta table used to determine if we need to migrate thumbnails out\n\/\/ of history.\nstatic const char kNeedsThumbnailMigrationKey[] = \"needs_thumbnail_migration\";\n\nvoid ComputeDatabaseMetrics(const FilePath& history_name,\n sql::Connection& db) {\n if (base::RandInt(1, 100) != 50)\n return; \/\/ Only do this computation sometimes since it can be expensive.\n\n base::TimeTicks start_time = base::TimeTicks::Now();\n int64 file_size = 0;\n if (!file_util::GetFileSize(history_name, &file_size))\n return;\n int file_mb = static_cast(file_size \/ (1024 * 1024));\n UMA_HISTOGRAM_MEMORY_MB(\"History.DatabaseFileMB\", file_mb);\n\n sql::Statement url_count(db.GetUniqueStatement(\"SELECT count(*) FROM urls\"));\n if (!url_count.Step())\n return;\n UMA_HISTOGRAM_COUNTS(\"History.URLTableCount\", url_count.ColumnInt(0));\n\n sql::Statement visit_count(db.GetUniqueStatement(\n \"SELECT count(*) FROM visits\"));\n if (!visit_count.Step())\n return;\n UMA_HISTOGRAM_COUNTS(\"History.VisitTableCount\", visit_count.ColumnInt(0));\n\n base::Time one_week_ago = base::Time::Now() - base::TimeDelta::FromDays(7);\n sql::Statement weekly_visit_sql(db.GetUniqueStatement(\n \"SELECT count(*) FROM visits WHERE visit_time > ?\"));\n weekly_visit_sql.BindInt64(0, one_week_ago.ToInternalValue());\n int weekly_visit_count = weekly_visit_sql.ColumnInt(0);\n UMA_HISTOGRAM_COUNTS(\"History.WeeklyVisitCount\", weekly_visit_count);\n\n base::Time one_month_ago = base::Time::Now() - base::TimeDelta::FromDays(30);\n sql::Statement monthly_visit_sql(db.GetUniqueStatement(\n \"SELECT count(*) FROM visits WHERE visit_time > ? AND visit_time <= ?\"));\n monthly_visit_sql.BindInt64(0, one_month_ago.ToInternalValue());\n monthly_visit_sql.BindInt64(1, one_week_ago.ToInternalValue());\n UMA_HISTOGRAM_COUNTS(\"History.MonthlyVisitCount\",\n monthly_visit_sql.ColumnInt(0) + weekly_visit_count);\n\n UMA_HISTOGRAM_TIMES(\"History.DatabaseBasicMetricsTime\",\n base::TimeTicks::Now() - start_time);\n\n \/\/ Compute the advanced metrics even less often, pending timing data showing\n \/\/ that's not necessary.\n if (base::RandInt(1, 3) == 3) {\n start_time = base::TimeTicks::Now();\n\n \/\/ Collect all URLs visited within the last month.\n sql::Statement url_sql(db.GetUniqueStatement(\n \"SELECT url, last_visit_time FROM urls WHERE last_visit_time > ?\"));\n url_sql.BindInt64(0, one_month_ago.ToInternalValue());\n\n \/\/ Count URLs (which will always be unique) and unique hosts within the last\n \/\/ week and last month.\n int week_url_count = 0;\n int month_url_count = 0;\n std::set week_hosts;\n std::set month_hosts;\n while (url_sql.Step()) {\n GURL url(url_sql.ColumnString(0));\n base::Time visit_time =\n base::Time::FromInternalValue(url_sql.ColumnInt64(1));\n ++month_url_count;\n month_hosts.insert(url.host());\n if (visit_time > one_week_ago) {\n ++week_url_count;\n week_hosts.insert(url.host());\n }\n }\n UMA_HISTOGRAM_COUNTS(\"History.WeeklyURLCount\", week_url_count);\n UMA_HISTOGRAM_COUNTS_10000(\"History.WeeklyHostCount\", week_hosts.size());\n UMA_HISTOGRAM_COUNTS(\"History.MonthlyURLCount\", month_url_count);\n UMA_HISTOGRAM_COUNTS_10000(\"History.MonthlyHostCount\", month_hosts.size());\n UMA_HISTOGRAM_TIMES(\"History.DatabaseAdvancedMetricsTime\",\n base::TimeTicks::Now() - start_time);\n }\n}\n\n} \/\/ namespace\n\nHistoryDatabase::HistoryDatabase()\n : needs_version_17_migration_(false) {\n}\n\nHistoryDatabase::~HistoryDatabase() {\n}\n\nsql::InitStatus HistoryDatabase::Init(const FilePath& history_name,\n sql::ErrorDelegate* error_delegate) {\n db_.set_error_histogram_name(\"Sqlite.History.Error\");\n\n \/\/ Set the exceptional sqlite error handler.\n db_.set_error_delegate(error_delegate);\n\n \/\/ Set the database page size to something a little larger to give us\n \/\/ better performance (we're typically seek rather than bandwidth limited).\n \/\/ This only has an effect before any tables have been created, otherwise\n \/\/ this is a NOP. Must be a power of 2 and a max of 8192.\n db_.set_page_size(4096);\n\n \/\/ Increase the cache size. The page size, plus a little extra, times this\n \/\/ value, tells us how much memory the cache will use maximum.\n \/\/ 6000 * 4MB = 24MB\n \/\/ TODO(brettw) scale this value to the amount of available memory.\n db_.set_cache_size(6000);\n\n \/\/ Note that we don't set exclusive locking here. That's done by\n \/\/ BeginExclusiveMode below which is called later (we have to be in shared\n \/\/ mode to start out for the in-memory backend to read the data).\n\n if (!db_.Open(history_name))\n return sql::INIT_FAILURE;\n\n \/\/ Wrap the rest of init in a tranaction. This will prevent the database from\n \/\/ getting corrupted if we crash in the middle of initialization or migration.\n sql::Transaction committer(&db_);\n if (!committer.Begin())\n return sql::INIT_FAILURE;\n\n#if defined(OS_MACOSX)\n \/\/ Exclude the history file from backups.\n base::mac::SetFileBackupExclusion(history_name);\n#endif\n\n \/\/ Prime the cache.\n db_.Preload();\n\n \/\/ Create the tables and indices.\n \/\/ NOTE: If you add something here, also add it to\n \/\/ RecreateAllButStarAndURLTables.\n if (!meta_table_.Init(&db_, GetCurrentVersion(), kCompatibleVersionNumber))\n return sql::INIT_FAILURE;\n if (!CreateURLTable(false) || !InitVisitTable() ||\n !InitKeywordSearchTermsTable() || !InitDownloadTable() ||\n !InitSegmentTables())\n return sql::INIT_FAILURE;\n CreateMainURLIndex();\n CreateKeywordSearchTermsIndices();\n\n \/\/ Version check.\n sql::InitStatus version_status = EnsureCurrentVersion();\n if (version_status != sql::INIT_OK)\n return version_status;\n\n ComputeDatabaseMetrics(history_name, db_);\n return committer.Commit() ? sql::INIT_OK : sql::INIT_FAILURE;\n}\n\nvoid HistoryDatabase::BeginExclusiveMode() {\n \/\/ We can't use set_exclusive_locking() since that only has an effect before\n \/\/ the DB is opened.\n ignore_result(db_.Execute(\"PRAGMA locking_mode=EXCLUSIVE\"));\n}\n\n\/\/ static\nint HistoryDatabase::GetCurrentVersion() {\n return kCurrentVersionNumber;\n}\n\nvoid HistoryDatabase::BeginTransaction() {\n db_.BeginTransaction();\n}\n\nvoid HistoryDatabase::CommitTransaction() {\n db_.CommitTransaction();\n}\n\nvoid HistoryDatabase::RollbackTransaction() {\n db_.RollbackTransaction();\n}\n\nbool HistoryDatabase::RecreateAllTablesButURL() {\n if (!DropVisitTable())\n return false;\n if (!InitVisitTable())\n return false;\n\n if (!DropKeywordSearchTermsTable())\n return false;\n if (!InitKeywordSearchTermsTable())\n return false;\n\n if (!DropSegmentTables())\n return false;\n if (!InitSegmentTables())\n return false;\n\n \/\/ We also add the supplementary URL indices at this point. This index is\n \/\/ over parts of the URL table that weren't automatically created when the\n \/\/ temporary URL table was\n CreateKeywordSearchTermsIndices();\n return true;\n}\n\nvoid HistoryDatabase::Vacuum() {\n DCHECK_EQ(0, db_.transaction_nesting()) <<\n \"Can not have a transaction when vacuuming.\";\n ignore_result(db_.Execute(\"VACUUM\"));\n}\n\nbool HistoryDatabase::Raze() {\n return db_.Raze();\n}\n\nvoid HistoryDatabase::ThumbnailMigrationDone() {\n meta_table_.SetValue(kNeedsThumbnailMigrationKey, 0);\n}\n\nbool HistoryDatabase::GetNeedsThumbnailMigration() {\n int value = 0;\n return (meta_table_.GetValue(kNeedsThumbnailMigrationKey, &value) &&\n value != 0);\n}\n\nbool HistoryDatabase::SetSegmentID(VisitID visit_id, SegmentID segment_id) {\n sql::Statement s(db_.GetCachedStatement(SQL_FROM_HERE,\n \"UPDATE visits SET segment_id = ? WHERE id = ?\"));\n s.BindInt64(0, segment_id);\n s.BindInt64(1, visit_id);\n DCHECK(db_.GetLastChangeCount() == 1);\n\n return s.Run();\n}\n\nSegmentID HistoryDatabase::GetSegmentID(VisitID visit_id) {\n sql::Statement s(db_.GetCachedStatement(SQL_FROM_HERE,\n \"SELECT segment_id FROM visits WHERE id = ?\"));\n s.BindInt64(0, visit_id);\n\n if (s.Step()) {\n if (s.ColumnType(0) == sql::COLUMN_TYPE_NULL)\n return 0;\n else\n return s.ColumnInt64(0);\n }\n return 0;\n}\n\nbase::Time HistoryDatabase::GetEarlyExpirationThreshold() {\n if (!cached_early_expiration_threshold_.is_null())\n return cached_early_expiration_threshold_;\n\n int64 threshold;\n if (!meta_table_.GetValue(kEarlyExpirationThresholdKey, &threshold)) {\n \/\/ Set to a very early non-zero time, so it's before all history, but not\n \/\/ zero to avoid re-retrieval.\n threshold = 1L;\n }\n\n cached_early_expiration_threshold_ = base::Time::FromInternalValue(threshold);\n return cached_early_expiration_threshold_;\n}\n\nvoid HistoryDatabase::UpdateEarlyExpirationThreshold(base::Time threshold) {\n meta_table_.SetValue(kEarlyExpirationThresholdKey,\n threshold.ToInternalValue());\n cached_early_expiration_threshold_ = threshold;\n}\n\nsql::Connection& HistoryDatabase::GetDB() {\n return db_;\n}\n\nsql::MetaTable& HistoryDatabase::GetMetaTable() {\n return meta_table_;\n}\n\n\/\/ Migration -------------------------------------------------------------------\n\nsql::InitStatus HistoryDatabase::EnsureCurrentVersion() {\n \/\/ We can't read databases newer than we were designed for.\n if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {\n LOG(WARNING) << \"History database is too new.\";\n return sql::INIT_TOO_NEW;\n }\n\n \/\/ NOTICE: If you are changing structures for things shared with the archived\n \/\/ history file like URLs, visits, or downloads, that will need migration as\n \/\/ well. Instead of putting such migration code in this class, it should be\n \/\/ in the corresponding file (url_database.cc, etc.) and called from here and\n \/\/ from the archived_database.cc.\n\n int cur_version = meta_table_.GetVersionNumber();\n\n \/\/ Put migration code here\n\n if (cur_version == 15) {\n if (!db_.Execute(\"DROP TABLE starred\") || !DropStarredIDFromURLs()) {\n LOG(WARNING) << \"Unable to update history database to version 16.\";\n return sql::INIT_FAILURE;\n }\n ++cur_version;\n meta_table_.SetVersionNumber(cur_version);\n meta_table_.SetCompatibleVersionNumber(\n std::min(cur_version, kCompatibleVersionNumber));\n }\n\n if (cur_version == 16) {\n#if !defined(OS_WIN)\n \/\/ In this version we bring the time format on Mac & Linux in sync with the\n \/\/ Windows version so that profiles can be moved between computers.\n MigrateTimeEpoch();\n#endif\n \/\/ On all platforms we bump the version number, so on Windows this\n \/\/ migration is a NOP. We keep the compatible version at 16 since things\n \/\/ will basically still work, just history will be in the future if an\n \/\/ old version reads it.\n ++cur_version;\n meta_table_.SetVersionNumber(cur_version);\n }\n\n if (cur_version == 17) {\n \/\/ Version 17 was for thumbnails to top sites migration. We ended up\n \/\/ disabling it though, so 17->18 does nothing.\n ++cur_version;\n meta_table_.SetVersionNumber(cur_version);\n }\n\n if (cur_version == 18) {\n \/\/ This is the version prior to adding url_source column. We need to\n \/\/ migrate the database.\n cur_version = 19;\n meta_table_.SetVersionNumber(cur_version);\n }\n\n if (cur_version == 19) {\n cur_version++;\n meta_table_.SetVersionNumber(cur_version);\n \/\/ Set a key indicating we need to migrate thumbnails. When successfull the\n \/\/ key is removed (ThumbnailMigrationDone).\n meta_table_.SetValue(kNeedsThumbnailMigrationKey, 1);\n }\n\n if (cur_version == 20) {\n \/\/ This is the version prior to adding the visit_duration field in visits\n \/\/ database. We need to migrate the database.\n if (!MigrateVisitsWithoutDuration()) {\n LOG(WARNING) << \"Unable to update history database to version 21.\";\n return sql::INIT_FAILURE;\n }\n ++cur_version;\n meta_table_.SetVersionNumber(cur_version);\n }\n\n if (cur_version == 21) {\n \/\/ The android_urls table's data schemal was changed in version 21.\n#if defined(OS_ANDROID)\n if (!MigrateToVersion22()) {\n LOG(WARNING) << \"Unable to migrate the android_urls table to version 22\";\n }\n#endif\n ++cur_version;\n meta_table_.SetVersionNumber(cur_version);\n }\n\n if (cur_version == 22) {\n if (!MigrateDownloadsState()) {\n LOG(WARNING) << \"Unable to fix invalid downloads state values\";\n \/\/ Invalid state values may cause crashes.\n return sql::INIT_FAILURE;\n }\n cur_version++;\n meta_table_.SetVersionNumber(cur_version);\n }\n\n \/\/ When the version is too old, we just try to continue anyway, there should\n \/\/ not be a released product that makes a database too old for us to handle.\n LOG_IF(WARNING, cur_version < GetCurrentVersion()) <<\n \"History database version \" << cur_version << \" is too old to handle.\";\n\n return sql::INIT_OK;\n}\n\n#if !defined(OS_WIN)\nvoid HistoryDatabase::MigrateTimeEpoch() {\n \/\/ Update all the times in the URLs and visits table in the main database.\n \/\/ For visits, clear the indexed flag since we'll delete the FTS databases in\n \/\/ the next step.\n ignore_result(db_.Execute(\n \"UPDATE urls \"\n \"SET last_visit_time = last_visit_time + 11644473600000000 \"\n \"WHERE id IN (SELECT id FROM urls WHERE last_visit_time > 0);\"));\n ignore_result(db_.Execute(\n \"UPDATE visits \"\n \"SET visit_time = visit_time + 11644473600000000, is_indexed = 0 \"\n \"WHERE id IN (SELECT id FROM visits WHERE visit_time > 0);\"));\n ignore_result(db_.Execute(\n \"UPDATE segment_usage \"\n \"SET time_slot = time_slot + 11644473600000000 \"\n \"WHERE id IN (SELECT id FROM segment_usage WHERE time_slot > 0);\"));\n\n \/\/ Erase all the full text index files. These will take a while to update and\n \/\/ are less important, so we just blow them away. Same with the archived\n \/\/ database.\n needs_version_17_migration_ = true;\n}\n#endif\n\n} \/\/ namespace history\n<|endoftext|>"} {"text":"\/\/ MenuTheme.hh for FbTk\n\/\/ Copyright (c) 2002-2004 Henrik Kinnunen (fluxgen at fluxbox dot org)\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id$\n\n#ifndef FBTK_MENUTHEME_HH\n#define FBTK_MENUTHEME_HH\n\n#include \"Theme.hh\"\n#include \"Color.hh\"\n#include \"Font.hh\"\n#include \"Texture.hh\"\n#include \"Text.hh\"\n#include \"Subject.hh\"\n#include \"PixmapWithMask.hh\"\n#include \"GContext.hh\"\n\nnamespace FbTk {\n\nclass MenuTheme:public FbTk::Theme {\npublic:\n \/\/!! TODO\n \/\/ this isn't actually used with a theme item\n \/\/ see setMenuMode() for more info\n enum MenuMode {CLICK_OPEN, DELAY_OPEN};\n\n enum BulletType { EMPTY, SQUARE, TRIANGLE, DIAMOND};\n MenuTheme(int screen_num);\n virtual ~MenuTheme();\n\n void reconfigTheme();\n\n bool fallback(ThemeItem_base &item);\n\n \/**\n @name text colors\n *\/\n \/\/\/@{\n inline const FbTk::Color &titleTextColor() const { return *t_text; }\n inline const FbTk::Color &frameTextColor() const { return *f_text; }\n inline const FbTk::Color &highlightTextColor() const { return *h_text; }\n inline const FbTk::Color &disableTextColor() const { return *d_text; }\n \/\/\/@}\n \/**\n @name textures\n *\/\n \/\/\/@{\n inline const FbTk::Texture &titleTexture() const { return *title; }\n inline const FbTk::Texture &frameTexture() const { return *frame; }\n inline const FbTk::Texture &hiliteTexture() const { return *hilite; }\n \/\/\/@}\n\n inline const FbTk::PixmapWithMask &bulletPixmap() const { return *m_bullet_pixmap; }\n inline const FbTk::PixmapWithMask &selectedPixmap() const { return *m_selected_pixmap; }\n inline const FbTk::PixmapWithMask &unselectedPixmap() const { return *m_unselected_pixmap; }\n \/**\n @name fonts\n *\/\n \/\/\/@{\n inline const FbTk::Font &titleFont() const { return *titlefont; }\n inline FbTk::Font &titleFont() { return *titlefont; }\n inline const FbTk::Font &frameFont() const { return *framefont; }\n inline FbTk::Font &frameFont() { return *framefont; }\n \/\/\/@}\n\n inline FbTk::Justify frameFontJustify() const { return *framefont_justify; }\n inline FbTk::Justify titleFontJustify() const { return *titlefont_justify; }\n\t\n \/**\n @name graphic contexts\n *\/\n \/\/\/@{\n inline const GContext &titleTextGC() const { return t_text_gc; }\n inline const GContext &frameTextGC() const { return f_text_gc; }\n inline const GContext &hiliteTextGC() const { return h_text_gc; }\n inline const GContext &disableTextGC() const { return d_text_gc; }\n inline const GContext &hiliteGC() const { return hilite_gc; }\n inline GContext &titleTextGC() { return t_text_gc; }\n inline GContext &frameTextGC() { return f_text_gc; }\n inline GContext &hiliteTextGC() { return h_text_gc; }\n inline GContext &disableTextGC() { return d_text_gc; }\n inline GContext &hiliteGC() { return hilite_gc; }\n \/\/\/@}\n inline BulletType bullet() const { return *m_bullet; }\n inline FbTk::Justify bulletPos() const { return *bullet_pos; }\n\n inline unsigned int titleHeight() const { return m_real_title_height; }\n inline unsigned int itemHeight() const { return m_real_item_height; }\n inline unsigned int borderWidth() const { return *m_border_width; }\n inline unsigned int bevelWidth() const { return *m_bevel_width; }\n\n inline unsigned char alpha() const { return m_alpha; }\n inline void setAlpha(unsigned char alpha) { m_alpha = alpha; }\n \/\/ this isn't actually a theme item\n \/\/ but we'll let it be here for now, until there's a better way to\n \/\/ get resources into menu\n inline void setMenuMode(MenuMode mode) { m_menumode = mode; }\n inline MenuMode menuMode() const { return m_menumode; }\n inline void setDelayOpen(int msec) { m_delayopen = msec; }\n inline void setDelayClose(int msec) { m_delayclose = msec; }\n inline int delayOpen() const { return m_delayopen; }\n inline int delayClose() const { return m_delayclose; }\n \n inline const FbTk::Color &borderColor() const { return *m_border_color; }\n\nprivate:\n FbTk::ThemeItem t_text, f_text, h_text, d_text;\n FbTk::ThemeItem title, frame, hilite;\n FbTk::ThemeItem titlefont, framefont;\n FbTk::ThemeItem framefont_justify, titlefont_justify;\n FbTk::ThemeItem bullet_pos; \n FbTk::ThemeItem m_bullet;\n FbTk::ThemeItem m_title_height, m_item_height;\n FbTk::ThemeItem m_border_width;\n FbTk::ThemeItem m_bevel_width;\n FbTk::ThemeItem m_border_color;\n FbTk::ThemeItem m_bullet_pixmap, m_selected_pixmap, m_unselected_pixmap;\n\n Display *m_display;\n FbTk::GContext t_text_gc, f_text_gc, h_text_gc, d_text_gc, hilite_gc;\n\n unsigned char m_alpha;\n MenuMode m_menumode;\n unsigned int m_delayopen; \/\/\/< in msec\n unsigned int m_delayclose; \/\/\/< in msec\n int m_real_title_height; \/\/\/< the calculated item height (from font and menu.titleHeight)\n int m_real_item_height; \/\/\/< the calculated item height (from font and menu.itemHeight)\n};\n\n} \/\/ end namespace FbTk\n\n#endif \/\/ FBTK_MENUTHEME_HH\nupdated copyright date\/\/ MenuTheme.hh for FbTk\n\/\/ Copyright (c) 2002 - 2005 Henrik Kinnunen (fluxgen at fluxbox dot org)\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id$\n\n#ifndef FBTK_MENUTHEME_HH\n#define FBTK_MENUTHEME_HH\n\n#include \"Theme.hh\"\n#include \"Color.hh\"\n#include \"Font.hh\"\n#include \"Texture.hh\"\n#include \"Text.hh\"\n#include \"Subject.hh\"\n#include \"PixmapWithMask.hh\"\n#include \"GContext.hh\"\n\nnamespace FbTk {\n\nclass MenuTheme:public FbTk::Theme {\npublic:\n \/\/!! TODO\n \/\/ this isn't actually used with a theme item\n \/\/ see setMenuMode() for more info\n enum MenuMode {CLICK_OPEN, DELAY_OPEN};\n\n enum BulletType { EMPTY, SQUARE, TRIANGLE, DIAMOND};\n MenuTheme(int screen_num);\n virtual ~MenuTheme();\n\n void reconfigTheme();\n\n bool fallback(ThemeItem_base &item);\n\n \/**\n @name text colors\n *\/\n \/\/\/@{\n inline const FbTk::Color &titleTextColor() const { return *t_text; }\n inline const FbTk::Color &frameTextColor() const { return *f_text; }\n inline const FbTk::Color &highlightTextColor() const { return *h_text; }\n inline const FbTk::Color &disableTextColor() const { return *d_text; }\n \/\/\/@}\n \/**\n @name textures\n *\/\n \/\/\/@{\n inline const FbTk::Texture &titleTexture() const { return *title; }\n inline const FbTk::Texture &frameTexture() const { return *frame; }\n inline const FbTk::Texture &hiliteTexture() const { return *hilite; }\n \/\/\/@}\n\n inline const FbTk::PixmapWithMask &bulletPixmap() const { return *m_bullet_pixmap; }\n inline const FbTk::PixmapWithMask &selectedPixmap() const { return *m_selected_pixmap; }\n inline const FbTk::PixmapWithMask &unselectedPixmap() const { return *m_unselected_pixmap; }\n \/**\n @name fonts\n *\/\n \/\/\/@{\n inline const FbTk::Font &titleFont() const { return *titlefont; }\n inline FbTk::Font &titleFont() { return *titlefont; }\n inline const FbTk::Font &frameFont() const { return *framefont; }\n inline FbTk::Font &frameFont() { return *framefont; }\n \/\/\/@}\n\n inline FbTk::Justify frameFontJustify() const { return *framefont_justify; }\n inline FbTk::Justify titleFontJustify() const { return *titlefont_justify; }\n\t\n \/**\n @name graphic contexts\n *\/\n \/\/\/@{\n inline const GContext &titleTextGC() const { return t_text_gc; }\n inline const GContext &frameTextGC() const { return f_text_gc; }\n inline const GContext &hiliteTextGC() const { return h_text_gc; }\n inline const GContext &disableTextGC() const { return d_text_gc; }\n inline const GContext &hiliteGC() const { return hilite_gc; }\n inline GContext &titleTextGC() { return t_text_gc; }\n inline GContext &frameTextGC() { return f_text_gc; }\n inline GContext &hiliteTextGC() { return h_text_gc; }\n inline GContext &disableTextGC() { return d_text_gc; }\n inline GContext &hiliteGC() { return hilite_gc; }\n \/\/\/@}\n inline BulletType bullet() const { return *m_bullet; }\n inline FbTk::Justify bulletPos() const { return *bullet_pos; }\n\n inline unsigned int titleHeight() const { return m_real_title_height; }\n inline unsigned int itemHeight() const { return m_real_item_height; }\n inline unsigned int borderWidth() const { return *m_border_width; }\n inline unsigned int bevelWidth() const { return *m_bevel_width; }\n\n inline unsigned char alpha() const { return m_alpha; }\n inline void setAlpha(unsigned char alpha) { m_alpha = alpha; }\n \/\/ this isn't actually a theme item\n \/\/ but we'll let it be here for now, until there's a better way to\n \/\/ get resources into menu\n inline void setMenuMode(MenuMode mode) { m_menumode = mode; }\n inline MenuMode menuMode() const { return m_menumode; }\n inline void setDelayOpen(int msec) { m_delayopen = msec; }\n inline void setDelayClose(int msec) { m_delayclose = msec; }\n inline int delayOpen() const { return m_delayopen; }\n inline int delayClose() const { return m_delayclose; }\n \n inline const FbTk::Color &borderColor() const { return *m_border_color; }\n\nprivate:\n FbTk::ThemeItem t_text, f_text, h_text, d_text;\n FbTk::ThemeItem title, frame, hilite;\n FbTk::ThemeItem titlefont, framefont;\n FbTk::ThemeItem framefont_justify, titlefont_justify;\n FbTk::ThemeItem bullet_pos; \n FbTk::ThemeItem m_bullet;\n FbTk::ThemeItem m_title_height, m_item_height;\n FbTk::ThemeItem m_border_width;\n FbTk::ThemeItem m_bevel_width;\n FbTk::ThemeItem m_border_color;\n FbTk::ThemeItem m_bullet_pixmap, m_selected_pixmap, m_unselected_pixmap;\n\n Display *m_display;\n FbTk::GContext t_text_gc, f_text_gc, h_text_gc, d_text_gc, hilite_gc;\n\n unsigned char m_alpha;\n MenuMode m_menumode;\n unsigned int m_delayopen; \/\/\/< in msec\n unsigned int m_delayclose; \/\/\/< in msec\n int m_real_title_height; \/\/\/< the calculated item height (from font and menu.titleHeight)\n int m_real_item_height; \/\/\/< the calculated item height (from font and menu.itemHeight)\n};\n\n} \/\/ end namespace FbTk\n\n#endif \/\/ FBTK_MENUTHEME_HH\n<|endoftext|>"} {"text":"#include \"TChain.h\"\n#include \"TTree.h\"\n#include \"TH1D.h\"\n#include \"TF1.h\"\n#include \"TCanvas.h\"\n#include \"TObjArray.h\"\n\n#include \"AliAnalysisTask.h\"\n#include \"AliAnalysisManager.h\"\n\n#include \"AliESDEvent.h\"\n#include \"AliESDInputHandler.h\"\n\n#include \"AliT0CalibOffsetChannelsTask.h\"\n\n\/\/#include \"AliCDBMetaData.h\"\n\/\/#include \"AliCDBId.h\"\n\/\/#include \"AliCDBEntry.h\"\n\/\/#include \"AliCDBManager.h\"\n\/\/#include \"AliCDBStorage.h\"\n\n\/\/ Task should calculate channels offset \n\/\/ Authors: Alla \n\nClassImp(AliT0CalibOffsetChannelsTask)\n\/\/________________________________________________________________________\nAliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask() \n : AliAnalysisTaskSE(), fESD(0x0), fTzeroObject(0x0),\n fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),\n fRunNumber(0),fRefPMTA(12), fRefPMTC(0),\n fEvent(0),fStartTime(0), fEndTime(0)\n{\n \/\/ Constructor\n\n for( int ip=0; ip < 24; ip++){\n fTimeDiff[ip] = 0;\n fCFD[ip] = 0;\n fCDBdelays[ip]= 0;\n fCDBcfds[ip]= 0;\n fCFDvsTimestamp[ip] = NULL;\n if (ip<4 ) {\n fCDBT0s[ip]= 0;\n fT0s[ip] =NULL;\n }\n }\n\n \/\/ Define input and output slots here\n \/\/ Input slot #0 works with a TChain\n \/\/ DefineInput(0, TChain::Class());\n \/\/ DefineOutput(1, TObjArray::Class());\n}\n\n\n\/\/________________________________________________________________________\nAliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask(const char *name) \n : AliAnalysisTaskSE(name), fESD(0), fTzeroObject(0),\n fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),\n fRunNumber(0),fRefPMTA(12), fRefPMTC(0), fEvent(0),\n fStartTime(0), fEndTime(0)\n{\n \/\/ Constructor\n \n for( int ip=0; ip < 24; ip++){\n fTimeDiff[ip] = 0;\n fCFD[ip] = 0;\n fCDBdelays[ip]= 0;\n fCDBcfds[ip]= 0;\n fCFDvsTimestamp[ip] = NULL;\n\t\t \n if (ip<4 ) {\n fCDBT0s[ip]= 0;\n fT0s[ip] =NULL;\n }\n }\n \n \/\/ Define input and output slots here\n \/\/ Input slot #0 works with a TChain\n DefineInput(0, TChain::Class());\n DefineOutput(1, TObjArray::Class());\n \/\/ Output slot #0 id reserved by the base class for AOD\n \/\/ Output slot #1 writes into a TH1 container\n}\n\n\/\/________________________________________________________________________\nAliT0CalibOffsetChannelsTask::~AliT0CalibOffsetChannelsTask() \n{\n \/\/ Destructor\n \/\/ printf(\"AliT0CalibOffsetChannels~AliT0CalibOffsetChannels() \");\n delete fTzeroORA;\n delete fTzeroORC;\n delete fResolution;\n delete fTzeroORAplusORC;\n for( Int_t ip=0; ip < 24; ip++){\n delete fTimeDiff[ip];\n delete fCFD[ip];\n delete fCFDvsTimestamp[ip];\n }\n for( Int_t ip=0; ip < 4; ip++) delete fT0s[ip];\n \n delete fTzeroObject;\n}\n\n\/\/________________________________________________________________________\n\/*void AliT0CalibOffsetChannelsTaskX::ConnectInputData(Option_t *) {\n \/\/\n \/\/\n \/\/\n TTree* tree=dynamic_cast(GetInputData(0));\n if (!tree) {\n printf(\"ERROR: Could not read chain from input slot 0\");\n } \n else {\n AliESDInputHandler *esdH = dynamic_cast (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());\n if (!esdH) {\n printf (\"ERROR: Could not get ESDInputHandler\");\n } \n else {\n fESD = esdH->GetEvent();\n printf (\"*** CONNECTED NEW EVENT ****\");\n }\n }\n}\n*\/\n\/\/________________________________________________________________________\nvoid AliT0CalibOffsetChannelsTask::UserCreateOutputObjects()\n{\n \/\/ Create histograms\n Float_t low = fCDBcfds[fRefPMTC] - 400;\n Float_t high = fCDBcfds[fRefPMTA] + 400;\n printf (\" AliT0CalibOffsetChannelsTask %f %f \\n\",low,high);\n \n Float_t timestart = Float_t (fStartTime - 300);\n Float_t timeend = Float_t (fEndTime +300);\n Int_t nTimeBins = (fEndTime - fStartTime+600)\/600;\n for (Int_t i=0; i<24; i++) {\n fTimeDiff[i] = new TH1F (Form(\"CFD1minCFD%d\",i+1),\"fTimeDiff\",150, -300, 300);\n fCFD[i] = new TH1F(Form(\"CFD%d\",i+1),\"CFD\",250,low, high);\/\/6000, 7000);\n \/\/ fCFDvsTimestamp[i] = new TH2F( Form(\"hCFDvsTimestamp%i\", i+1), Form(\"CFD vs timestamp%i\", i+1), nTimeBins, timestart, timeend,250,low, high );\n fCFDvsTimestamp[i] = new TH2F( Form(\"hCFDvsTimestamp%i\", i+1), Form(\"CFD vs timestamp%i\", i+1), nTimeBins,fStartTime - 300, fEndTime +300 ,250,low, high );\n \/\/ fCFDvsTimestamp[i]->SetName(Form(\"hCFDvsTimestamp%i\", i+1));\n \/\/ fCFDvsTimestamp[i]->SetTitle(Form(\"CFD vs timestamp%i\", i+1));\n }\n\n fTzeroORAplusORC = new TH1F(\"fTzeroORAplusORC\",\"ORA+ORC \/2\",200,-4000,4000); \/\/or A plus or C \n fResolution = new TH1F(\"fResolution\",\"fResolution\",200,-2000,2000);\/\/ or A minus or C spectrum\n fTzeroORA = new TH1F(\"fTzeroORA\",\"fTzeroORA\",200,-4000,4000);\/\/ or A spectrum\n fTzeroORC = new TH1F(\"fTzeroORC\",\"fTzeroORC\",200,-4000,4000);\/\/ or C spectrum\n TString histname[4] = {\"hT0AC\",\"hT0A\",\"hT0C\",\"hResolution\"};\n for (int icase=0; icase<4; icase++) \n fT0s[icase] = new TH2F(histname[icase].Data(), histname[icase].Data(), 100, 0, 200, 200, -1000, 1000);\n\n fTzeroObject = new TObjArray(0);\n fTzeroObject->SetOwner(kTRUE);\n \n for (Int_t i=0; i<24; i++)\n fTzeroObject->AddAtAndExpand(fTimeDiff[i],i);\n\n for (Int_t i=0; i<24; i++) \n fTzeroObject->AddAtAndExpand(fCFD[i],i+24); \/\/24 - 48\n\n fTzeroObject->AddAtAndExpand(fTzeroORAplusORC, 48);\n fTzeroObject->AddAtAndExpand(fResolution, 49);\n fTzeroObject->AddAtAndExpand(fTzeroORA, 50);\n fTzeroObject->AddAtAndExpand(fTzeroORC, 51);\n for (int icase=0; icase<4; icase++) \n fTzeroObject->AddAtAndExpand(fT0s[icase], 52+icase);\n for (int icase=0; icase<24; icase++) \n fTzeroObject->AddAtAndExpand(fCFDvsTimestamp[icase], 56+icase);\n\n PostData(1, fTzeroObject);\n fEvent=0;\n \/\/ Called once\n}\n\n\/\/________________________________________________________________________\nvoid AliT0CalibOffsetChannelsTask::UserExec(Option_t *) \n{\n \/\/ Main loop\n \/\/ Called for each event\n\n \/\/ Post output data.\n\n fESD = dynamic_cast(InputEvent());\n if (!fESD) {\n printf(\"ERROR: fESD not available\\n\");\n return;\n }\n UInt_t timestamp=fESD->GetTimeStamp();\n \/* if (fEvent==0 ) \n for (int iii=0; iii<24; iii++)\n fCFDvsTimestamp[iii]->SetBins(121, timestamp-60, timestamp+72000, 250,fCDBcfds[fRefPMTC]-500, fCDBcfds[fRefPMTA] + 500); *\/\n fEvent++;\n \n \n AliESDTZERO* tz= (AliESDTZERO*) fESD->GetESDTZERO();\n Int_t trigT0 = fESD->GetT0Trig();\n Float_t tvdctr = tz->GetTVDC(0);\n Bool_t eq = kTRUE;\n fRunNumber = fESD->GetRunNumber() ;\n if( fRunNumber<165747) eq = kFALSE;\n \n const Double32_t* time = fESD->GetT0time();\n const Double32_t* amp = fESD->GetT0amplitude();\n \n if(tvdctr>-5 && tvdctr<5 && tvdctr!=0) { \/\/event selection\n \/\/ cout<<\" tvdc \"< 0 && amp[i]>0.1 ){\n\tif (eq)\t{\n\t fCFD[i]->Fill( time[i] );\/\/\/\/\/\/!!!!!\n\t fCFDvsTimestamp[i]->Fill(timestamp,time[i]);\n\t if( time[fRefPMTC] > 0 && i<12) {\n\t diff = time[i]-time[fRefPMTC];\n\t fTimeDiff[i]->Fill( diff);\n\t }\n\t if( time[fRefPMTA] >0 && i>11) {\n\t diff = time[i]-time[fRefPMTA] ;\n\t fTimeDiff[i]->Fill( diff);\n\t }\n\t} \/\/eq=1\n\telse {\n\t fCFD[i]->Fill( time[i] + fCDBdelays[i] );\n\t if( time[fRefPMTC] > 0 && i<12) {\n\t diff = time[i]-time[fRefPMTC] + fCDBdelays[i];\n\t fTimeDiff[i]->Fill( diff);\n\t } \/\/C\n\t if( time[fRefPMTA] >0 && i>11) {\n\t diff = time[i]-time[fRefPMTA] + fCDBdelays[i];\n\t fTimeDiff[i]->Fill( diff);\n\t } \/\/A\n\t} \/\/eq=0\n }\n \n }\n const Double32_t* mean = fESD->GetT0TOF();\n Double32_t meanTOF = mean[0] + fCDBT0s[0] ;\n Double32_t orA = mean[1] + fCDBT0s[1] ;\n Double32_t orC = mean[2] + fCDBT0s[2] ;\n Int_t ncont = fESD->GetPrimaryVertexSPD()->GetNContributors();\n \n if(orA<99999) {\n fTzeroORA->Fill(orA);\n if (ncont>0) fT0s[1]->Fill(ncont, orA);\n }\n if(orC<99999) {\n fTzeroORC->Fill(orC);\n if (ncont>0) fT0s[2]->Fill(ncont, orC);\n }\n if(orA<99999 && orC<99999) {\n fResolution->Fill((orA-orC)\/2.);\n fTzeroORAplusORC->Fill(meanTOF); \n if (ncont>0) {\n\tfT0s[0]->Fill(ncont,meanTOF );\n\tfT0s[3]->Fill(ncont,(orA-orC)\/2. );\n }\n }\n } \/\/if TVDC on\n PostData(1, fTzeroObject);\n} \n\/\/________________________________________________________________________\n void AliT0CalibOffsetChannelsTask::Terminate(Option_t *) \n{\n \n \/\/ Called once at the end of the query\n}\n\/* \n@@@@ start 1495913485 end 1495916316\n@@ start 1495913344.000000 end 1495916672.000000 bins 5 \n*\/\nremove amplitude cut when collect calibration data#include \"TChain.h\"\n#include \"TTree.h\"\n#include \"TH1D.h\"\n#include \"TF1.h\"\n#include \"TCanvas.h\"\n#include \"TObjArray.h\"\n\n#include \"AliAnalysisTask.h\"\n#include \"AliAnalysisManager.h\"\n\n#include \"AliESDEvent.h\"\n#include \"AliESDInputHandler.h\"\n\n#include \"AliT0CalibOffsetChannelsTask.h\"\n\n\/\/#include \"AliCDBMetaData.h\"\n\/\/#include \"AliCDBId.h\"\n\/\/#include \"AliCDBEntry.h\"\n\/\/#include \"AliCDBManager.h\"\n\/\/#include \"AliCDBStorage.h\"\n\n\/\/ Task should calculate channels offset \n\/\/ Authors: Alla \n\nClassImp(AliT0CalibOffsetChannelsTask)\n\/\/________________________________________________________________________\nAliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask() \n : AliAnalysisTaskSE(), fESD(0x0), fTzeroObject(0x0),\n fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),\n fRunNumber(0),fRefPMTA(12), fRefPMTC(0),\n fEvent(0),fStartTime(0), fEndTime(0)\n{\n \/\/ Constructor\n\n for( int ip=0; ip < 24; ip++){\n fTimeDiff[ip] = 0;\n fCFD[ip] = 0;\n fCDBdelays[ip]= 0;\n fCDBcfds[ip]= 0;\n fCFDvsTimestamp[ip] = NULL;\n if (ip<4 ) {\n fCDBT0s[ip]= 0;\n fT0s[ip] =NULL;\n }\n }\n\n \/\/ Define input and output slots here\n \/\/ Input slot #0 works with a TChain\n \/\/ DefineInput(0, TChain::Class());\n \/\/ DefineOutput(1, TObjArray::Class());\n}\n\n\n\/\/________________________________________________________________________\nAliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask(const char *name) \n : AliAnalysisTaskSE(name), fESD(0), fTzeroObject(0),\n fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),\n fRunNumber(0),fRefPMTA(12), fRefPMTC(0), fEvent(0),\n fStartTime(0), fEndTime(0)\n{\n \/\/ Constructor\n \n for( int ip=0; ip < 24; ip++){\n fTimeDiff[ip] = 0;\n fCFD[ip] = 0;\n fCDBdelays[ip]= 0;\n fCDBcfds[ip]= 0;\n fCFDvsTimestamp[ip] = NULL;\n\t\t \n if (ip<4 ) {\n fCDBT0s[ip]= 0;\n fT0s[ip] =NULL;\n }\n }\n \n \/\/ Define input and output slots here\n \/\/ Input slot #0 works with a TChain\n DefineInput(0, TChain::Class());\n DefineOutput(1, TObjArray::Class());\n \/\/ Output slot #0 id reserved by the base class for AOD\n \/\/ Output slot #1 writes into a TH1 container\n}\n\n\/\/________________________________________________________________________\nAliT0CalibOffsetChannelsTask::~AliT0CalibOffsetChannelsTask() \n{\n \/\/ Destructor\n \/\/ printf(\"AliT0CalibOffsetChannels~AliT0CalibOffsetChannels() \");\n delete fTzeroORA;\n delete fTzeroORC;\n delete fResolution;\n delete fTzeroORAplusORC;\n for( Int_t ip=0; ip < 24; ip++){\n delete fTimeDiff[ip];\n delete fCFD[ip];\n delete fCFDvsTimestamp[ip];\n }\n for( Int_t ip=0; ip < 4; ip++) delete fT0s[ip];\n \n delete fTzeroObject;\n}\n\n\/\/________________________________________________________________________\n\/*void AliT0CalibOffsetChannelsTaskX::ConnectInputData(Option_t *) {\n \/\/\n \/\/\n \/\/\n TTree* tree=dynamic_cast(GetInputData(0));\n if (!tree) {\n printf(\"ERROR: Could not read chain from input slot 0\");\n } \n else {\n AliESDInputHandler *esdH = dynamic_cast (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());\n if (!esdH) {\n printf (\"ERROR: Could not get ESDInputHandler\");\n } \n else {\n fESD = esdH->GetEvent();\n printf (\"*** CONNECTED NEW EVENT ****\");\n }\n }\n}\n*\/\n\/\/________________________________________________________________________\nvoid AliT0CalibOffsetChannelsTask::UserCreateOutputObjects()\n{\n \/\/ Create histograms\n Float_t low = fCDBcfds[fRefPMTC] - 400;\n Float_t high = fCDBcfds[fRefPMTA] + 400;\n printf (\" AliT0CalibOffsetChannelsTask %f %f \\n\",low,high);\n \n Float_t timestart = Float_t (fStartTime - 300);\n Float_t timeend = Float_t (fEndTime +300);\n Int_t nTimeBins = (fEndTime - fStartTime+600)\/600;\n for (Int_t i=0; i<24; i++) {\n fTimeDiff[i] = new TH1F (Form(\"CFD1minCFD%d\",i+1),\"fTimeDiff\",150, -300, 300);\n fCFD[i] = new TH1F(Form(\"CFD%d\",i+1),\"CFD\",250,low, high);\/\/6000, 7000);\n \/\/ fCFDvsTimestamp[i] = new TH2F( Form(\"hCFDvsTimestamp%i\", i+1), Form(\"CFD vs timestamp%i\", i+1), nTimeBins, timestart, timeend,250,low, high );\n fCFDvsTimestamp[i] = new TH2F( Form(\"hCFDvsTimestamp%i\", i+1), Form(\"CFD vs timestamp%i\", i+1), nTimeBins,fStartTime - 300, fEndTime +300 ,250,low, high );\n \/\/ fCFDvsTimestamp[i]->SetName(Form(\"hCFDvsTimestamp%i\", i+1));\n \/\/ fCFDvsTimestamp[i]->SetTitle(Form(\"CFD vs timestamp%i\", i+1));\n }\n\n fTzeroORAplusORC = new TH1F(\"fTzeroORAplusORC\",\"ORA+ORC \/2\",200,-4000,4000); \/\/or A plus or C \n fResolution = new TH1F(\"fResolution\",\"fResolution\",200,-2000,2000);\/\/ or A minus or C spectrum\n fTzeroORA = new TH1F(\"fTzeroORA\",\"fTzeroORA\",200,-4000,4000);\/\/ or A spectrum\n fTzeroORC = new TH1F(\"fTzeroORC\",\"fTzeroORC\",200,-4000,4000);\/\/ or C spectrum\n TString histname[4] = {\"hT0AC\",\"hT0A\",\"hT0C\",\"hResolution\"};\n for (int icase=0; icase<4; icase++) \n fT0s[icase] = new TH2F(histname[icase].Data(), histname[icase].Data(), 100, 0, 200, 200, -1000, 1000);\n\n fTzeroObject = new TObjArray(0);\n fTzeroObject->SetOwner(kTRUE);\n \n for (Int_t i=0; i<24; i++)\n fTzeroObject->AddAtAndExpand(fTimeDiff[i],i);\n\n for (Int_t i=0; i<24; i++) \n fTzeroObject->AddAtAndExpand(fCFD[i],i+24); \/\/24 - 48\n\n fTzeroObject->AddAtAndExpand(fTzeroORAplusORC, 48);\n fTzeroObject->AddAtAndExpand(fResolution, 49);\n fTzeroObject->AddAtAndExpand(fTzeroORA, 50);\n fTzeroObject->AddAtAndExpand(fTzeroORC, 51);\n for (int icase=0; icase<4; icase++) \n fTzeroObject->AddAtAndExpand(fT0s[icase], 52+icase);\n for (int icase=0; icase<24; icase++) \n fTzeroObject->AddAtAndExpand(fCFDvsTimestamp[icase], 56+icase);\n\n PostData(1, fTzeroObject);\n fEvent=0;\n \/\/ Called once\n}\n\n\/\/________________________________________________________________________\nvoid AliT0CalibOffsetChannelsTask::UserExec(Option_t *) \n{\n \/\/ Main loop\n \/\/ Called for each event\n\n \/\/ Post output data.\n\n fESD = dynamic_cast(InputEvent());\n if (!fESD) {\n printf(\"ERROR: fESD not available\\n\");\n return;\n }\n UInt_t timestamp=fESD->GetTimeStamp();\n \/* if (fEvent==0 ) \n for (int iii=0; iii<24; iii++)\n fCFDvsTimestamp[iii]->SetBins(121, timestamp-60, timestamp+72000, 250,fCDBcfds[fRefPMTC]-500, fCDBcfds[fRefPMTA] + 500); *\/\n fEvent++;\n \n \n AliESDTZERO* tz= (AliESDTZERO*) fESD->GetESDTZERO();\n Int_t trigT0 = fESD->GetT0Trig();\n Float_t tvdctr = tz->GetTVDC(0);\n Bool_t eq = kTRUE;\n fRunNumber = fESD->GetRunNumber() ;\n if( fRunNumber<165747) eq = kFALSE;\n \n const Double32_t* time = fESD->GetT0time();\n const Double32_t* amp = fESD->GetT0amplitude();\n \n if(tvdctr>-5 && tvdctr<5 && tvdctr!=0) { \/\/event selection\n \/\/ cout<<\" tvdc \"< 0 ){\n\tif (eq)\t{\n\t fCFD[i]->Fill( time[i] );\/\/\/\/\/\/!!!!!\n\t fCFDvsTimestamp[i]->Fill(timestamp,time[i]);\n\t if( time[fRefPMTC] > 0 && i<12) {\n\t diff = time[i]-time[fRefPMTC];\n\t fTimeDiff[i]->Fill( diff);\n\t }\n\t if( time[fRefPMTA] >0 && i>11) {\n\t diff = time[i]-time[fRefPMTA] ;\n\t fTimeDiff[i]->Fill( diff);\n\t }\n\t} \/\/eq=1\n\telse {\n\t fCFD[i]->Fill( time[i] + fCDBdelays[i] );\n\t if( time[fRefPMTC] > 0 && i<12) {\n\t diff = time[i]-time[fRefPMTC] + fCDBdelays[i];\n\t fTimeDiff[i]->Fill( diff);\n\t } \/\/C\n\t if( time[fRefPMTA] >0 && i>11) {\n\t diff = time[i]-time[fRefPMTA] + fCDBdelays[i];\n\t fTimeDiff[i]->Fill( diff);\n\t } \/\/A\n\t} \/\/eq=0\n }\n \n }\n const Double32_t* mean = fESD->GetT0TOF();\n Double32_t meanTOF = mean[0] + fCDBT0s[0] ;\n Double32_t orA = mean[1] + fCDBT0s[1] ;\n Double32_t orC = mean[2] + fCDBT0s[2] ;\n Int_t ncont = fESD->GetPrimaryVertexSPD()->GetNContributors();\n \n if(orA<99999) {\n fTzeroORA->Fill(orA);\n if (ncont>0) fT0s[1]->Fill(ncont, orA);\n }\n if(orC<99999) {\n fTzeroORC->Fill(orC);\n if (ncont>0) fT0s[2]->Fill(ncont, orC);\n }\n if(orA<99999 && orC<99999) {\n fResolution->Fill((orA-orC)\/2.);\n fTzeroORAplusORC->Fill(meanTOF); \n if (ncont>0) {\n\tfT0s[0]->Fill(ncont,meanTOF );\n\tfT0s[3]->Fill(ncont,(orA-orC)\/2. );\n }\n }\n } \/\/if TVDC on\n PostData(1, fTzeroObject);\n} \n\/\/________________________________________________________________________\n void AliT0CalibOffsetChannelsTask::Terminate(Option_t *) \n{\n \n \/\/ Called once at the end of the query\n}\n\/* \n@@@@ start 1495913485 end 1495916316\n@@ start 1495913344.000000 end 1495916672.000000 bins 5 \n*\/\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/net\/chrome_cookie_policy.h\"\n\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/cookie_prompt_modal_dialog_delegate.h\"\n#include \"chrome\/browser\/host_content_settings_map.h\"\n#include \"chrome\/browser\/message_box_handler.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/base\/static_cookie_policy.h\"\n\n\/\/ If we queue up more than this number of completions, then switch from ASK to\n\/\/ BLOCK. More than this number of requests at once seems like it could be a\n\/\/ sign of trouble anyways.\nstatic const size_t kMaxCompletionsPerHost = 10000;\n\n\/\/ ----------------------------------------------------------------------------\n\nclass ChromeCookiePolicy::PromptDelegate\n : public CookiePromptModalDialogDelegate {\n public:\n PromptDelegate(ChromeCookiePolicy* cookie_policy, const std::string& host)\n : cookie_policy_(cookie_policy),\n host_(host) {\n }\n\n \/\/ CookiesPromptViewDelegate methods:\n virtual void AllowSiteData(bool remember, bool session_expire);\n virtual void BlockSiteData(bool remember);\n\n private:\n scoped_refptr cookie_policy_;\n std::string host_;\n};\n\nvoid ChromeCookiePolicy::PromptDelegate::AllowSiteData(bool remember,\n bool session_expire) {\n int policy = net::OK;\n if (session_expire)\n policy = net::OK_FOR_SESSION_ONLY;\n cookie_policy_->DidPromptForSetCookie(host_, policy, remember);\n}\n\nvoid ChromeCookiePolicy::PromptDelegate::BlockSiteData(bool remember) {\n cookie_policy_->DidPromptForSetCookie(host_, net::ERR_ACCESS_DENIED,\n remember);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\nChromeCookiePolicy::ChromeCookiePolicy(HostContentSettingsMap* map)\n : host_content_settings_map_(map) {\n}\n\nChromeCookiePolicy::~ChromeCookiePolicy() {\n DCHECK(host_completions_map_.empty());\n}\n\nint ChromeCookiePolicy::CanGetCookies(const GURL& url,\n const GURL& first_party,\n net::CompletionCallback* callback) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n\n if (host_content_settings_map_->BlockThirdPartyCookies()) {\n net::StaticCookiePolicy policy(\n net::StaticCookiePolicy::BLOCK_THIRD_PARTY_COOKIES);\n int rv = policy.CanGetCookies(url, first_party, NULL);\n if (rv != net::OK)\n return rv;\n }\n\n int policy = CheckPolicy(url);\n if (policy != net::ERR_IO_PENDING)\n return policy;\n\n DCHECK(callback);\n\n \/\/ If we are currently prompting the user for a 'set-cookie' matching this\n \/\/ host, then we need to defer reading cookies.\n HostCompletionsMap::iterator it = host_completions_map_.find(url.host());\n if (it == host_completions_map_.end()) {\n policy = net::OK;\n } else if (it->second.size() >= kMaxCompletionsPerHost) {\n LOG(ERROR) << \"Would exceed kMaxCompletionsPerHost\";\n policy = net::ERR_ACCESS_DENIED;\n } else {\n it->second.push_back(Completion::ForGetCookies(callback));\n policy = net::ERR_IO_PENDING;\n }\n return policy;\n}\n\nint ChromeCookiePolicy::CanSetCookie(const GURL& url,\n const GURL& first_party,\n const std::string& cookie_line,\n net::CompletionCallback* callback) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n\n if (host_content_settings_map_->BlockThirdPartyCookies()) {\n net::StaticCookiePolicy policy(\n net::StaticCookiePolicy::BLOCK_THIRD_PARTY_COOKIES);\n int rv = policy.CanSetCookie(url, first_party, cookie_line, NULL);\n if (rv != net::OK)\n return rv;\n }\n\n int policy = CheckPolicy(url);\n if (policy != net::ERR_IO_PENDING)\n return policy;\n\n DCHECK(callback);\n\n \/\/ Else, ask the user...\n\n Completions& completions = host_completions_map_[url.host()];\n\n if (completions.size() >= kMaxCompletionsPerHost) {\n LOG(ERROR) << \"Would exceed kMaxCompletionsPerHost\";\n policy = net::ERR_ACCESS_DENIED;\n } else {\n completions.push_back(Completion::ForSetCookie(callback));\n policy = net::ERR_IO_PENDING;\n }\n\n PromptForSetCookie(url, cookie_line);\n return policy;\n}\n\nint ChromeCookiePolicy::CheckPolicy(const GURL& url) const {\n ContentSetting setting = host_content_settings_map_->GetContentSetting(\n url, CONTENT_SETTINGS_TYPE_COOKIES);\n if (setting == CONTENT_SETTING_BLOCK)\n return net::ERR_ACCESS_DENIED;\n if (setting == CONTENT_SETTING_ALLOW)\n return net::OK;\n return net::ERR_IO_PENDING; \/\/ Need to prompt.\n}\n\nvoid ChromeCookiePolicy::PromptForSetCookie(const GURL& url,\n const std::string& cookie_line) {\n if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this, &ChromeCookiePolicy::PromptForSetCookie, url,\n cookie_line));\n return;\n }\n\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n const std::string& host = url.host();\n\n \/\/ The policy may have changed (due to the \"remember\" option)\n int policy = CheckPolicy(url);\n if (policy != net::ERR_IO_PENDING) {\n DidPromptForSetCookie(host, policy, false);\n return;\n }\n\n \/\/ Show the prompt on top of the current tab.\n Browser* browser = BrowserList::GetLastActive();\n if (!browser || !browser->GetSelectedTabContents()) {\n DidPromptForSetCookie(host, net::ERR_ACCESS_DENIED, false);\n return;\n }\n\n#if defined(OS_WIN)\n RunCookiePrompt(browser->GetSelectedTabContents(), url, cookie_line,\n new PromptDelegate(this, host));\n#else\n \/\/ TODO(darin): Enable prompting for other ports.\n DidPromptForSetCookie(host, net::ERR_ACCESS_DENIED, false);\n#endif\n}\n\nvoid ChromeCookiePolicy::DidPromptForSetCookie(const std::string& host,\n int policy, bool remember) {\n if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) {\n \/\/ Process the remember flag immediately.\n if (remember) {\n ContentSetting content_setting = CONTENT_SETTING_BLOCK;\n if (policy == net::OK || policy == net::OK_FOR_SESSION_ONLY)\n content_setting = CONTENT_SETTING_ALLOW;\n host_content_settings_map_->SetContentSetting(\n host, CONTENT_SETTINGS_TYPE_COOKIES, content_setting);\n }\n\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this, &ChromeCookiePolicy::DidPromptForSetCookie,\n host, policy, remember));\n return;\n }\n\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n\n \/\/ Notify all callbacks, starting with the first until we hit another that\n \/\/ is for a 'set-cookie'.\n HostCompletionsMap::iterator it = host_completions_map_.find(host);\n CHECK(it != host_completions_map_.end());\n\n Completions& completions = it->second;\n CHECK(!completions.empty() && completions[0].is_set_cookie_request());\n\n \/\/ Gather the list of callbacks to notify, and remove them from the\n \/\/ completions list before handing control to the callbacks (in case\n \/\/ they should call back into us to modify host_completions_map_).\n\n std::vector callbacks;\n callbacks.push_back(completions[0].callback());\n size_t i = 1;\n for (; i < completions.size(); ++i) {\n if (completions[i].is_set_cookie_request())\n break;\n callbacks.push_back(completions[i].callback());\n }\n completions.erase(completions.begin(), completions.begin() + i);\n\n if (completions.empty())\n host_completions_map_.erase(it);\n\n for (size_t j = 0; j < callbacks.size(); ++j)\n callbacks[j]->Run(policy);\n}\nThe PromptDelegate needs to delete itself once it gets a reply.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/net\/chrome_cookie_policy.h\"\n\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/cookie_prompt_modal_dialog_delegate.h\"\n#include \"chrome\/browser\/host_content_settings_map.h\"\n#include \"chrome\/browser\/message_box_handler.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/base\/static_cookie_policy.h\"\n\n\/\/ If we queue up more than this number of completions, then switch from ASK to\n\/\/ BLOCK. More than this number of requests at once seems like it could be a\n\/\/ sign of trouble anyways.\nstatic const size_t kMaxCompletionsPerHost = 10000;\n\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ ChromeCookiePolicy cannot just subclass the delegate interface because we\n\/\/ may have several prompts pending.\nclass ChromeCookiePolicy::PromptDelegate\n : public CookiePromptModalDialogDelegate {\n public:\n PromptDelegate(ChromeCookiePolicy* cookie_policy, const std::string& host)\n : cookie_policy_(cookie_policy),\n host_(host) {\n }\n\n \/\/ CookiesPromptViewDelegate methods:\n virtual void AllowSiteData(bool remember, bool session_expire);\n virtual void BlockSiteData(bool remember);\n\n private:\n void NotifyDone(int policy, bool remember);\n\n scoped_refptr cookie_policy_;\n std::string host_;\n};\n\nvoid ChromeCookiePolicy::PromptDelegate::AllowSiteData(bool remember,\n bool session_expire) {\n int policy = net::OK;\n if (session_expire)\n policy = net::OK_FOR_SESSION_ONLY;\n NotifyDone(policy, remember);\n}\n\nvoid ChromeCookiePolicy::PromptDelegate::BlockSiteData(bool remember) {\n NotifyDone(net::ERR_ACCESS_DENIED, remember);\n}\n\nvoid ChromeCookiePolicy::PromptDelegate::NotifyDone(int policy, bool remember) {\n cookie_policy_->DidPromptForSetCookie(host_, policy, remember);\n delete this;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\nChromeCookiePolicy::ChromeCookiePolicy(HostContentSettingsMap* map)\n : host_content_settings_map_(map) {\n}\n\nChromeCookiePolicy::~ChromeCookiePolicy() {\n DCHECK(host_completions_map_.empty());\n}\n\nint ChromeCookiePolicy::CanGetCookies(const GURL& url,\n const GURL& first_party,\n net::CompletionCallback* callback) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n\n if (host_content_settings_map_->BlockThirdPartyCookies()) {\n net::StaticCookiePolicy policy(\n net::StaticCookiePolicy::BLOCK_THIRD_PARTY_COOKIES);\n int rv = policy.CanGetCookies(url, first_party, NULL);\n if (rv != net::OK)\n return rv;\n }\n\n int policy = CheckPolicy(url);\n if (policy != net::ERR_IO_PENDING)\n return policy;\n\n DCHECK(callback);\n\n \/\/ If we are currently prompting the user for a 'set-cookie' matching this\n \/\/ host, then we need to defer reading cookies.\n HostCompletionsMap::iterator it = host_completions_map_.find(url.host());\n if (it == host_completions_map_.end()) {\n policy = net::OK;\n } else if (it->second.size() >= kMaxCompletionsPerHost) {\n LOG(ERROR) << \"Would exceed kMaxCompletionsPerHost\";\n policy = net::ERR_ACCESS_DENIED;\n } else {\n it->second.push_back(Completion::ForGetCookies(callback));\n policy = net::ERR_IO_PENDING;\n }\n return policy;\n}\n\nint ChromeCookiePolicy::CanSetCookie(const GURL& url,\n const GURL& first_party,\n const std::string& cookie_line,\n net::CompletionCallback* callback) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n\n if (host_content_settings_map_->BlockThirdPartyCookies()) {\n net::StaticCookiePolicy policy(\n net::StaticCookiePolicy::BLOCK_THIRD_PARTY_COOKIES);\n int rv = policy.CanSetCookie(url, first_party, cookie_line, NULL);\n if (rv != net::OK)\n return rv;\n }\n\n int policy = CheckPolicy(url);\n if (policy != net::ERR_IO_PENDING)\n return policy;\n\n DCHECK(callback);\n\n \/\/ Else, ask the user...\n\n Completions& completions = host_completions_map_[url.host()];\n\n if (completions.size() >= kMaxCompletionsPerHost) {\n LOG(ERROR) << \"Would exceed kMaxCompletionsPerHost\";\n policy = net::ERR_ACCESS_DENIED;\n } else {\n completions.push_back(Completion::ForSetCookie(callback));\n policy = net::ERR_IO_PENDING;\n }\n\n PromptForSetCookie(url, cookie_line);\n return policy;\n}\n\nint ChromeCookiePolicy::CheckPolicy(const GURL& url) const {\n ContentSetting setting = host_content_settings_map_->GetContentSetting(\n url, CONTENT_SETTINGS_TYPE_COOKIES);\n if (setting == CONTENT_SETTING_BLOCK)\n return net::ERR_ACCESS_DENIED;\n if (setting == CONTENT_SETTING_ALLOW)\n return net::OK;\n return net::ERR_IO_PENDING; \/\/ Need to prompt.\n}\n\nvoid ChromeCookiePolicy::PromptForSetCookie(const GURL& url,\n const std::string& cookie_line) {\n if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this, &ChromeCookiePolicy::PromptForSetCookie, url,\n cookie_line));\n return;\n }\n\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n const std::string& host = url.host();\n\n \/\/ The policy may have changed (due to the \"remember\" option)\n int policy = CheckPolicy(url);\n if (policy != net::ERR_IO_PENDING) {\n DidPromptForSetCookie(host, policy, false);\n return;\n }\n\n \/\/ Show the prompt on top of the current tab.\n Browser* browser = BrowserList::GetLastActive();\n if (!browser || !browser->GetSelectedTabContents()) {\n DidPromptForSetCookie(host, net::ERR_ACCESS_DENIED, false);\n return;\n }\n\n#if defined(OS_WIN)\n RunCookiePrompt(browser->GetSelectedTabContents(), url, cookie_line,\n new PromptDelegate(this, host));\n#else\n \/\/ TODO(darin): Enable prompting for other ports.\n DidPromptForSetCookie(host, net::ERR_ACCESS_DENIED, false);\n#endif\n}\n\nvoid ChromeCookiePolicy::DidPromptForSetCookie(const std::string& host,\n int policy, bool remember) {\n if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) {\n \/\/ Process the remember flag immediately.\n if (remember) {\n ContentSetting content_setting = CONTENT_SETTING_BLOCK;\n if (policy == net::OK || policy == net::OK_FOR_SESSION_ONLY)\n content_setting = CONTENT_SETTING_ALLOW;\n host_content_settings_map_->SetContentSetting(\n host, CONTENT_SETTINGS_TYPE_COOKIES, content_setting);\n }\n\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this, &ChromeCookiePolicy::DidPromptForSetCookie,\n host, policy, remember));\n return;\n }\n\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n\n \/\/ Notify all callbacks, starting with the first until we hit another that\n \/\/ is for a 'set-cookie'.\n HostCompletionsMap::iterator it = host_completions_map_.find(host);\n CHECK(it != host_completions_map_.end());\n\n Completions& completions = it->second;\n CHECK(!completions.empty() && completions[0].is_set_cookie_request());\n\n \/\/ Gather the list of callbacks to notify, and remove them from the\n \/\/ completions list before handing control to the callbacks (in case\n \/\/ they should call back into us to modify host_completions_map_).\n\n std::vector callbacks;\n callbacks.push_back(completions[0].callback());\n size_t i = 1;\n for (; i < completions.size(); ++i) {\n if (completions[i].is_set_cookie_request())\n break;\n callbacks.push_back(completions[i].callback());\n }\n completions.erase(completions.begin(), completions.begin() + i);\n\n if (completions.empty())\n host_completions_map_.erase(it);\n\n for (size_t j = 0; j < callbacks.size(); ++j)\n callbacks[j]->Run(policy);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/render_view_context_menu.h\"\n\n#include \"base\/logging.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/template_url_model.h\"\n#include \"webkit\/glue\/context_node_types.h\"\n\n#include \"generated_resources.h\"\n\nRenderViewContextMenu::RenderViewContextMenu(\n Menu::Delegate* delegate,\n HWND owner,\n ContextNode::Type type,\n const std::wstring& misspelled_word,\n const std::vector& misspelled_word_suggestions,\n Profile* profile)\n : Menu(delegate, Menu::TOPLEFT, owner),\n misspelled_word_(misspelled_word),\n misspelled_word_suggestions_(misspelled_word_suggestions),\n profile_(profile) {\n InitMenu(type);\n}\n\nRenderViewContextMenu::~RenderViewContextMenu() {\n}\n\nvoid RenderViewContextMenu::InitMenu(ContextNode::Type type) {\n switch (type) {\n case ContextNode::PAGE:\n AppendPageItems();\n break;\n case ContextNode::FRAME:\n AppendFrameItems();\n break;\n case ContextNode::LINK:\n AppendLinkItems();\n break;\n case ContextNode::IMAGE:\n AppendImageItems();\n break;\n case ContextNode::IMAGE_LINK:\n AppendLinkItems();\n AppendSeparator();\n AppendImageItems();\n break;\n case ContextNode::SELECTION:\n AppendSelectionItems();\n break;\n case ContextNode::EDITABLE:\n AppendEditableItems();\n break;\n default:\n NOTREACHED() << \"Unknown ContextNode::Type\";\n }\n AppendSeparator();\n AppendDeveloperItems();\n}\n\nvoid RenderViewContextMenu::AppendDeveloperItems() {\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_INSPECTELEMENT);\n}\n\nvoid RenderViewContextMenu::AppendLinkItems() {\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_OPENLINKNEWTAB);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_OPENLINKNEWWINDOW);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_OPENLINKOFFTHERECORD);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_SAVELINKAS);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_COPYLINKLOCATION);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_COPY);\n}\n\nvoid RenderViewContextMenu::AppendImageItems() {\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_SAVEIMAGEAS);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_COPYIMAGELOCATION);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_COPYIMAGE);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_OPENIMAGENEWTAB);\n}\n\nvoid RenderViewContextMenu::AppendPageItems() {\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_BACK);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_FORWARD);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_RELOAD);\n AppendSeparator();\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_SAVEPAGEAS);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_PRINT);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_VIEWPAGESOURCE);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_VIEWPAGEINFO);\n}\n\nvoid RenderViewContextMenu::AppendFrameItems() {\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_BACK);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_FORWARD);\n AppendSeparator();\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_OPENFRAMENEWTAB);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_OPENFRAMENEWWINDOW);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_OPENFRAMEOFFTHERECORD);\n AppendSeparator();\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_SAVEFRAMEAS);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_PRINTFRAME);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_VIEWFRAMESOURCE);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_VIEWFRAMEINFO);\n}\n\nvoid RenderViewContextMenu::AppendSelectionItems() {\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_COPY);\n DCHECK(profile_);\n if (profile_->GetTemplateURLModel()->GetDefaultSearchProvider() != NULL)\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_SEARCHWEBFOR);\n}\n\nvoid RenderViewContextMenu::AppendEditableItems() {\n \/\/ Append Dictionary spell check suggestions.\n for (size_t i = 0; i < misspelled_word_suggestions_.size() &&\n IDC_USESPELLCHECKSUGGESTION_0 + i <= IDC_USESPELLCHECKSUGGESTION_LAST;\n i ++) {\n AppendMenuItemWithLabel(IDC_USESPELLCHECKSUGGESTION_0 + static_cast(i),\n misspelled_word_suggestions_[i]);\n }\n if (misspelled_word_suggestions_.size() > 0)\n AppendSeparator();\n \n \/\/ If word is misspelled, give option for \"Add to dictionary\"\n if (!misspelled_word_.empty()) {\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_ADD_TO_DICTIONARY);\n AppendSeparator();\n }\n\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_UNDO);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_REDO);\n AppendSeparator();\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_CUT);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_COPY);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_PASTE);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_DELETE);\n AppendSeparator();\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_SELECTALL);\n}\n\nDisplay \"No suggestions found\" for misspelled words with no suggestions.\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/render_view_context_menu.h\"\n\n#include \"base\/logging.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/template_url_model.h\"\n#include \"chrome\/common\/l10n_util.h\"\n#include \"webkit\/glue\/context_node_types.h\"\n\n#include \"generated_resources.h\"\n\nRenderViewContextMenu::RenderViewContextMenu(\n Menu::Delegate* delegate,\n HWND owner,\n ContextNode::Type type,\n const std::wstring& misspelled_word,\n const std::vector& misspelled_word_suggestions,\n Profile* profile)\n : Menu(delegate, Menu::TOPLEFT, owner),\n misspelled_word_(misspelled_word),\n misspelled_word_suggestions_(misspelled_word_suggestions),\n profile_(profile) {\n InitMenu(type);\n}\n\nRenderViewContextMenu::~RenderViewContextMenu() {\n}\n\nvoid RenderViewContextMenu::InitMenu(ContextNode::Type type) {\n switch (type) {\n case ContextNode::PAGE:\n AppendPageItems();\n break;\n case ContextNode::FRAME:\n AppendFrameItems();\n break;\n case ContextNode::LINK:\n AppendLinkItems();\n break;\n case ContextNode::IMAGE:\n AppendImageItems();\n break;\n case ContextNode::IMAGE_LINK:\n AppendLinkItems();\n AppendSeparator();\n AppendImageItems();\n break;\n case ContextNode::SELECTION:\n AppendSelectionItems();\n break;\n case ContextNode::EDITABLE:\n AppendEditableItems();\n break;\n default:\n NOTREACHED() << \"Unknown ContextNode::Type\";\n }\n AppendSeparator();\n AppendDeveloperItems();\n}\n\nvoid RenderViewContextMenu::AppendDeveloperItems() {\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_INSPECTELEMENT);\n}\n\nvoid RenderViewContextMenu::AppendLinkItems() {\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_OPENLINKNEWTAB);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_OPENLINKNEWWINDOW);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_OPENLINKOFFTHERECORD);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_SAVELINKAS);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_COPYLINKLOCATION);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_COPY);\n}\n\nvoid RenderViewContextMenu::AppendImageItems() {\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_SAVEIMAGEAS);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_COPYIMAGELOCATION);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_COPYIMAGE);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_OPENIMAGENEWTAB);\n}\n\nvoid RenderViewContextMenu::AppendPageItems() {\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_BACK);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_FORWARD);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_RELOAD);\n AppendSeparator();\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_SAVEPAGEAS);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_PRINT);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_VIEWPAGESOURCE);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_VIEWPAGEINFO);\n}\n\nvoid RenderViewContextMenu::AppendFrameItems() {\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_BACK);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_FORWARD);\n AppendSeparator();\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_OPENFRAMENEWTAB);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_OPENFRAMENEWWINDOW);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_OPENFRAMEOFFTHERECORD);\n AppendSeparator();\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_SAVEFRAMEAS);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_PRINTFRAME);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_VIEWFRAMESOURCE);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_VIEWFRAMEINFO);\n}\n\nvoid RenderViewContextMenu::AppendSelectionItems() {\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_COPY);\n DCHECK(profile_);\n if (profile_->GetTemplateURLModel()->GetDefaultSearchProvider() != NULL)\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_SEARCHWEBFOR);\n}\n\nvoid RenderViewContextMenu::AppendEditableItems() {\n \/\/ Append Dictionary spell check suggestions.\n for (size_t i = 0; i < misspelled_word_suggestions_.size() &&\n IDC_USESPELLCHECKSUGGESTION_0 + i <= IDC_USESPELLCHECKSUGGESTION_LAST;\n i ++) {\n AppendMenuItemWithLabel(IDC_USESPELLCHECKSUGGESTION_0 + static_cast(i),\n misspelled_word_suggestions_[i]);\n }\n if (misspelled_word_suggestions_.size() > 0)\n AppendSeparator();\n \n \/\/ If word is misspelled, give option for \"Add to dictionary\"\n if (!misspelled_word_.empty()) {\n if (misspelled_word_suggestions_.size() == 0) {\n AppendMenuItemWithLabel(0, \n l10n_util::GetString(IDS_CONTENT_CONTEXT_NO_SPELLING_SUGGESTIONS));\n }\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_ADD_TO_DICTIONARY);\n AppendSeparator();\n }\n\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_UNDO);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_REDO);\n AppendSeparator();\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_CUT);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_COPY);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_PASTE);\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_DELETE);\n AppendSeparator();\n AppendDelegateMenuItem(IDS_CONTENT_CONTEXT_SELECTALL);\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/task_manager.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_path.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/crashed_extension_infobar.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/tab_contents\/infobar_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/page_transition_types.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\nconst FilePath::CharType* kTitle1File = FILE_PATH_LITERAL(\"title1.html\");\n\nclass ResourceChangeObserver : public TaskManagerModelObserver {\n public:\n ResourceChangeObserver(const TaskManagerModel* model,\n int target_resource_count)\n : model_(model),\n target_resource_count_(target_resource_count) {\n }\n\n virtual void OnModelChanged() {\n OnResourceChange();\n }\n\n virtual void OnItemsChanged(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsAdded(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsRemoved(int start, int length) {\n OnResourceChange();\n }\n\n private:\n void OnResourceChange() {\n if (model_->ResourceCount() == target_resource_count_)\n MessageLoopForUI::current()->Quit();\n }\n\n const TaskManagerModel* model_;\n const int target_resource_count_;\n};\n\n} \/\/ namespace\n\nclass TaskManagerBrowserTest : public ExtensionBrowserTest {\n public:\n TaskManagerModel* model() const {\n return TaskManager::GetInstance()->model();\n }\n\n void WaitForResourceChange(int target_count) {\n if (model()->ResourceCount() == target_count)\n return;\n ResourceChangeObserver observer(model(), target_count);\n model()->AddObserver(&observer);\n ui_test_utils::RunMessageLoop();\n model()->RemoveObserver(&observer);\n }\n};\n\n\/\/ Regression test for http:\/\/crbug.com\/13361\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) {\n browser()->window()->ShowTaskManager();\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n WaitForResourceChange(3);\n\n \/\/ Close the tab and verify that we notice.\n TabContents* first_tab = browser()->GetTabContentsAt(0);\n ASSERT_TRUE(first_tab);\n browser()->CloseTabContents(first_tab);\n WaitForResourceChange(2);\n}\n\n#if defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/31663\n#define NoticeExtensionChanges DISABLED_NoticeExtensionChanges\n#endif\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeExtensionChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Loading an extension should result in a new resource being\n \/\/ created for it.\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"one_in_shelf\")));\n WaitForResourceChange(3);\n\n \/\/ Make sure we also recognize extensions with just background pages.\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n WaitForResourceChange(4);\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n\n \/\/ Reload the extension using the \"crashed extension\" infobar while the task\n \/\/ manager is still visible. Make sure we don't crash and the extension\n \/\/ gets reloaded and noticed in the task manager.\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_EQ(1, current_tab->infobar_delegate_count());\n InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0);\n CrashedExtensionInfoBarDelegate* crashed_delegate =\n delegate->AsCrashedExtensionInfoBarDelegate();\n ASSERT_TRUE(crashed_delegate);\n crashed_delegate->Accept();\n WaitForResourceChange(3);\n}\n\n\/\/ Regression test for http:\/\/crbug.com\/18693.\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ReloadExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n const Extension* extension = model()->GetResourceExtension(2);\n\n \/\/ Reload the extension a few times and make sure our resource count\n \/\/ doesn't increase.\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, PopulateWebCacheFields) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n WaitForResourceChange(3);\n\n \/\/ Check that we get some value for the cache columns.\n DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n}\nDisable crashy TaskManagerBrowserTest.PopulateWebCacheFields\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/task_manager.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_path.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/crashed_extension_infobar.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/tab_contents\/infobar_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/page_transition_types.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\nconst FilePath::CharType* kTitle1File = FILE_PATH_LITERAL(\"title1.html\");\n\nclass ResourceChangeObserver : public TaskManagerModelObserver {\n public:\n ResourceChangeObserver(const TaskManagerModel* model,\n int target_resource_count)\n : model_(model),\n target_resource_count_(target_resource_count) {\n }\n\n virtual void OnModelChanged() {\n OnResourceChange();\n }\n\n virtual void OnItemsChanged(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsAdded(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsRemoved(int start, int length) {\n OnResourceChange();\n }\n\n private:\n void OnResourceChange() {\n if (model_->ResourceCount() == target_resource_count_)\n MessageLoopForUI::current()->Quit();\n }\n\n const TaskManagerModel* model_;\n const int target_resource_count_;\n};\n\n} \/\/ namespace\n\nclass TaskManagerBrowserTest : public ExtensionBrowserTest {\n public:\n TaskManagerModel* model() const {\n return TaskManager::GetInstance()->model();\n }\n\n void WaitForResourceChange(int target_count) {\n if (model()->ResourceCount() == target_count)\n return;\n ResourceChangeObserver observer(model(), target_count);\n model()->AddObserver(&observer);\n ui_test_utils::RunMessageLoop();\n model()->RemoveObserver(&observer);\n }\n};\n\n\/\/ Regression test for http:\/\/crbug.com\/13361\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) {\n browser()->window()->ShowTaskManager();\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n WaitForResourceChange(3);\n\n \/\/ Close the tab and verify that we notice.\n TabContents* first_tab = browser()->GetTabContentsAt(0);\n ASSERT_TRUE(first_tab);\n browser()->CloseTabContents(first_tab);\n WaitForResourceChange(2);\n}\n\n#if defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/31663\n#define NoticeExtensionChanges DISABLED_NoticeExtensionChanges\n#endif\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeExtensionChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Loading an extension should result in a new resource being\n \/\/ created for it.\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"one_in_shelf\")));\n WaitForResourceChange(3);\n\n \/\/ Make sure we also recognize extensions with just background pages.\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n WaitForResourceChange(4);\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n\n \/\/ Reload the extension using the \"crashed extension\" infobar while the task\n \/\/ manager is still visible. Make sure we don't crash and the extension\n \/\/ gets reloaded and noticed in the task manager.\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_EQ(1, current_tab->infobar_delegate_count());\n InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0);\n CrashedExtensionInfoBarDelegate* crashed_delegate =\n delegate->AsCrashedExtensionInfoBarDelegate();\n ASSERT_TRUE(crashed_delegate);\n crashed_delegate->Accept();\n WaitForResourceChange(3);\n}\n\n\/\/ Regression test for http:\/\/crbug.com\/18693.\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ReloadExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n const Extension* extension = model()->GetResourceExtension(2);\n\n \/\/ Reload the extension a few times and make sure our resource count\n \/\/ doesn't increase.\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n}\n\n\/\/ Crashy, http:\/\/crbug.com\/42301.\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest,\n DISABLED_PopulateWebCacheFields) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n WaitForResourceChange(3);\n\n \/\/ Check that we get some value for the cache columns.\n DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/task_manager.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_path.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/crashed_extension_infobar.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/tab_contents\/infobar_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/page_transition_types.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\nconst FilePath::CharType* kTitle1File = FILE_PATH_LITERAL(\"title1.html\");\n\nclass ResourceChangeObserver : public TaskManagerModelObserver {\n public:\n ResourceChangeObserver(const TaskManagerModel* model,\n int target_resource_count)\n : model_(model),\n target_resource_count_(target_resource_count) {\n }\n\n virtual void OnModelChanged() {\n OnResourceChange();\n }\n\n virtual void OnItemsChanged(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsAdded(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsRemoved(int start, int length) {\n OnResourceChange();\n }\n\n private:\n void OnResourceChange() {\n if (model_->ResourceCount() == target_resource_count_)\n MessageLoopForUI::current()->Quit();\n }\n\n const TaskManagerModel* model_;\n const int target_resource_count_;\n};\n\n} \/\/ namespace\n\nclass TaskManagerBrowserTest : public ExtensionBrowserTest {\n public:\n TaskManagerModel* model() const {\n return TaskManager::GetInstance()->model();\n }\n\n void WaitForResourceChange(int target_count) {\n if (model()->ResourceCount() == target_count)\n return;\n ResourceChangeObserver observer(model(), target_count);\n model()->AddObserver(&observer);\n ui_test_utils::RunMessageLoop();\n model()->RemoveObserver(&observer);\n }\n};\n\n\/\/ Regression test for http:\/\/crbug.com\/13361\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) {\n browser()->window()->ShowTaskManager();\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n WaitForResourceChange(3);\n\n \/\/ Close the tab and verify that we notice.\n TabContents* first_tab = browser()->GetTabContentsAt(0);\n ASSERT_TRUE(first_tab);\n browser()->CloseTabContents(first_tab);\n WaitForResourceChange(2);\n}\n\n#if defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/31663\n#define NoticeExtensionChanges DISABLED_NoticeExtensionChanges\n#endif\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeExtensionChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Loading an extension should result in a new resource being\n \/\/ created for it.\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"one_in_shelf\")));\n WaitForResourceChange(3);\n\n \/\/ Make sure we also recognize extensions with just background pages.\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n WaitForResourceChange(4);\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n\n \/\/ Reload the extension using the \"crashed extension\" infobar while the task\n \/\/ manager is still visible. Make sure we don't crash and the extension\n \/\/ gets reloaded and noticed in the task manager.\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_EQ(1, current_tab->infobar_delegate_count());\n InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0);\n CrashedExtensionInfoBarDelegate* crashed_delegate =\n delegate->AsCrashedExtensionInfoBarDelegate();\n ASSERT_TRUE(crashed_delegate);\n crashed_delegate->Accept();\n WaitForResourceChange(3);\n}\n\n\/\/ Regression test for http:\/\/crbug.com\/18693.\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ReloadExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n const Extension* extension = model()->GetResourceExtension(2);\n\n \/\/ Reload the extension a few times and make sure our resource count\n \/\/ doesn't increase.\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, PopulateWebCacheFields) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n WaitForResourceChange(3);\n\n \/\/ Check that we get some value for the cache columns.\n DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n}\nDisable crashy TaskManagerBrowserTest.PopulateWebCacheFields\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/task_manager.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_path.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/crashed_extension_infobar.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/tab_contents\/infobar_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/page_transition_types.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\nconst FilePath::CharType* kTitle1File = FILE_PATH_LITERAL(\"title1.html\");\n\nclass ResourceChangeObserver : public TaskManagerModelObserver {\n public:\n ResourceChangeObserver(const TaskManagerModel* model,\n int target_resource_count)\n : model_(model),\n target_resource_count_(target_resource_count) {\n }\n\n virtual void OnModelChanged() {\n OnResourceChange();\n }\n\n virtual void OnItemsChanged(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsAdded(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsRemoved(int start, int length) {\n OnResourceChange();\n }\n\n private:\n void OnResourceChange() {\n if (model_->ResourceCount() == target_resource_count_)\n MessageLoopForUI::current()->Quit();\n }\n\n const TaskManagerModel* model_;\n const int target_resource_count_;\n};\n\n} \/\/ namespace\n\nclass TaskManagerBrowserTest : public ExtensionBrowserTest {\n public:\n TaskManagerModel* model() const {\n return TaskManager::GetInstance()->model();\n }\n\n void WaitForResourceChange(int target_count) {\n if (model()->ResourceCount() == target_count)\n return;\n ResourceChangeObserver observer(model(), target_count);\n model()->AddObserver(&observer);\n ui_test_utils::RunMessageLoop();\n model()->RemoveObserver(&observer);\n }\n};\n\n\/\/ Regression test for http:\/\/crbug.com\/13361\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) {\n browser()->window()->ShowTaskManager();\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n WaitForResourceChange(3);\n\n \/\/ Close the tab and verify that we notice.\n TabContents* first_tab = browser()->GetTabContentsAt(0);\n ASSERT_TRUE(first_tab);\n browser()->CloseTabContents(first_tab);\n WaitForResourceChange(2);\n}\n\n#if defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/31663\n#define NoticeExtensionChanges DISABLED_NoticeExtensionChanges\n#endif\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeExtensionChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Loading an extension should result in a new resource being\n \/\/ created for it.\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"one_in_shelf\")));\n WaitForResourceChange(3);\n\n \/\/ Make sure we also recognize extensions with just background pages.\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n WaitForResourceChange(4);\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n\n \/\/ Reload the extension using the \"crashed extension\" infobar while the task\n \/\/ manager is still visible. Make sure we don't crash and the extension\n \/\/ gets reloaded and noticed in the task manager.\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_EQ(1, current_tab->infobar_delegate_count());\n InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0);\n CrashedExtensionInfoBarDelegate* crashed_delegate =\n delegate->AsCrashedExtensionInfoBarDelegate();\n ASSERT_TRUE(crashed_delegate);\n crashed_delegate->Accept();\n WaitForResourceChange(3);\n}\n\n\/\/ Regression test for http:\/\/crbug.com\/18693.\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ReloadExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n const Extension* extension = model()->GetResourceExtension(2);\n\n \/\/ Reload the extension a few times and make sure our resource count\n \/\/ doesn't increase.\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n}\n\n\/\/ Crashy, http:\/\/crbug.com\/42301.\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest,\n DISABLED_PopulateWebCacheFields) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n WaitForResourceChange(3);\n\n \/\/ Check that we get some value for the cache columns.\n DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n}\n<|endoftext|>"} {"text":"#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\n#undef LOGV\r\n#undef LOGE\r\n\r\n\/\/#define LOGV(msg,args...)\r\n#define LOGV(msg,args...) __android_log_print(ANDROID_LOG_ERROR, \"NME::AndroidSound\", msg, ## args)\r\n\r\n#define LOGE(msg,args...) __android_log_print(ANDROID_LOG_ERROR, \"NME::AndroidSound\", msg, ## args)\r\n\r\nextern JNIEnv *gEnv;\r\n\r\nnamespace nme\r\n{\r\n\r\nclass AndroidSoundChannel : public SoundChannel\r\n{\r\npublic:\r\n AndroidSoundChannel(Object *inSound, int inHandle,\r\n\t\t\t\t\t\t\t double startTime, int loops, const SoundTransform &inTransform)\r\n\t{\r\n\t\tmStreamID = -1;\r\n\t\tmSound = inSound;\r\n\t\tinSound->IncRef();\r\n\t\tif (inHandle>=0)\r\n\t\t{\r\n\t\t jclass cls = gEnv->FindClass(\"org\/haxe\/nme\/GameActivity\");\r\n jmethodID mid = gEnv->GetStaticMethodID(cls, \"playSound\", \"(IDDI)I\");\r\n if (mid > 0)\r\n\t\t {\r\n\t\t\t mStreamID = gEnv->CallStaticIntMethod(cls, mid, inHandle, inTransform.volume, inTransform.volume, loops );\r\n\t\t }\r\n\t\t}\r\n }\r\n\r\n ~AndroidSoundChannel()\r\n {\r\n mSound->DecRef();\r\n\t}\r\n\r\n bool isComplete()\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n double getLeft()\r\n\t{\r\n\t\treturn 0.5;\r\n\t}\r\n double getRight()\r\n\t{\r\n\t\treturn 0.5;\r\n\t}\r\n double getPosition()\r\n\t{\r\n\t}\r\n void stop()\r\n\t{\r\n\t}\r\n void setTransform(const SoundTransform &inTransform)\r\n\t{\r\n\t}\r\n\r\n\tObject *mSound;\r\n\tint mStreamID;\r\n};\r\n\r\n\r\n\r\nclass AndroidMusicChannel : public SoundChannel\r\n{\r\npublic:\r\n AndroidMusicChannel(Object *inSound, int inHandle,\r\n\t\t\t\t\t\t\t double startTime, int loops, const SoundTransform &inTransform)\r\n\t{\r\n\t\tmState = 0;\r\n\t\tmSound = inSound;\r\n\t\tinSound->IncRef();\r\n\r\n\t\tif (inHandle>=0)\r\n\t\t{\r\n\t\t jclass cls = gEnv->FindClass(\"org\/haxe\/nme\/GameActivity\");\r\n jmethodID mid = gEnv->GetStaticMethodID(cls, \"playMusic\", \"(IDDI)I\");\r\n if (mid > 0)\r\n\t\t {\r\n\t\t\t mState = gEnv->CallStaticIntMethod(cls, mid, inHandle, inTransform.volume, inTransform.volume, loops );\r\n\t\t }\r\n\t\t}\r\n }\r\n\r\n ~AndroidMusicChannel()\r\n {\r\n mSound->DecRef();\r\n\t}\r\n\r\n bool isComplete()\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n double getLeft()\r\n\t{\r\n\t\treturn 0.5;\r\n\t}\r\n double getRight()\r\n\t{\r\n\t\treturn 0.5;\r\n\t}\r\n double getPosition()\r\n\t{\r\n\t}\r\n void stop()\r\n\t{\r\n\t}\r\n void setTransform(const SoundTransform &inTransform)\r\n\t{\r\n\t}\r\n\r\n\tObject *mSound;\r\n int mState;\r\n};\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass AndroidSound : public Sound\r\n{\r\n enum SoundMode\r\n {\r\n MODE_UNKNOWN,\r\n MODE_SOUND_ID,\r\n MODE_MUSIC_RES_ID,\r\n MODE_MUSIC_NAME,\r\n };\r\n\r\npublic:\r\n\tAndroidSound(const std::string &inSound, bool inForceMusic)\r\n\t{\r\n\t\tIncRef();\r\n\r\n mMode = MODE_UNKNOWN;\r\n\t\tmID = -1;\r\n\t\tjclass cls = gEnv->FindClass(\"org\/haxe\/nme\/GameActivity\");\r\n\t\tjstring str = gEnv->NewStringUTF( inSound.c_str() );\r\n\r\n if (!inForceMusic)\r\n {\r\n jmethodID mid = gEnv->GetStaticMethodID(cls, \"getSoundHandle\", \"(Ljava\/lang\/String;)I\");\r\n if (mid > 0)\r\n\t\t {\r\n\t\t\t mID = gEnv->CallStaticIntMethod(cls, mid, str);\r\n if (mID>=0)\r\n mMode = MODE_SOUND_ID;\r\n\t\t }\r\n }\r\n\r\n if (mID<0)\r\n {\r\n jmethodID gmh = gEnv->GetStaticMethodID(cls, \"getMusicHandle\", \"(Ljava\/lang\/String;)I\");\r\n if (gmh>0)\r\n {\r\n\t\t\t mID = gEnv->CallStaticIntMethod(cls, gmh, str);\r\n if (mID>0)\r\n mMode = MODE_MUSIC_RES_ID;\r\n }\r\n }\r\n\r\n if (mID<0)\r\n {\r\n mMusicName = inSound;\r\n mMode = MODE_MUSIC_NAME;\r\n }\r\n\t}\r\n\r\n int getBytesLoaded() { return 0; }\r\n int getBytesTotal() { return 0; }\r\n bool ok() { return mID >= 0; }\r\n std::string getError() { return ok() ? \"\" : \"Error\"; }\r\n double getLength() { return 0; }\r\n void close() { }\r\n\r\n\r\n SoundChannel *openChannel(double startTime, int loops, const SoundTransform &inTransform)\r\n\t{\r\n if (mMode==MODE_MUSIC_RES_ID)\r\n\t\t return new AndroidMusicChannel(this,mID,startTime,loops,inTransform);\r\n\r\n\r\n\t\treturn new AndroidSoundChannel(this,mID,startTime,loops,inTransform);\r\n\t}\r\n\r\n\tint mID;\r\n std::string mMusicName;\r\n SoundMode mMode;\r\n};\r\n\r\n\r\nSound *Sound::Create(const std::string &inFilename,bool inForceMusic)\r\n{\r\n\treturn new AndroidSound(inFilename,inForceMusic);\r\n}\r\n\r\n\r\n\r\n}\r\nrespect inTransform in android sound constuctors#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\n#undef LOGV\r\n#undef LOGE\r\n\r\n\/\/#define LOGV(msg,args...)\r\n#define LOGV(msg,args...) __android_log_print(ANDROID_LOG_ERROR, \"NME::AndroidSound\", msg, ## args)\r\n\r\n#define LOGE(msg,args...) __android_log_print(ANDROID_LOG_ERROR, \"NME::AndroidSound\", msg, ## args)\r\n\r\nextern JNIEnv *gEnv;\r\n\r\nnamespace nme\r\n{\r\n\r\nclass AndroidSoundChannel : public SoundChannel\r\n{\r\npublic:\r\n AndroidSoundChannel(Object *inSound, int inHandle,\r\n\t\t\t\t\t\t\t double startTime, int loops, const SoundTransform &inTransform)\r\n\t{\r\n\t\tmStreamID = -1;\r\n\t\tmSound = inSound;\r\n\t\tinSound->IncRef();\r\n\t\tif (inHandle>=0)\r\n\t\t{\r\n\t\t jclass cls = gEnv->FindClass(\"org\/haxe\/nme\/GameActivity\");\r\n jmethodID mid = gEnv->GetStaticMethodID(cls, \"playSound\", \"(IDDI)I\");\r\n if (mid > 0)\r\n\t\t {\r\n\t\t\t mStreamID = gEnv->CallStaticIntMethod(cls, mid, inHandle, inTransform.volume*((1-inTransform.pan)\/2), inTransform.volume*((inTransform.pan+1)\/2), loops );\r\n\t\t }\r\n\t\t}\r\n }\r\n\r\n ~AndroidSoundChannel()\r\n {\r\n mSound->DecRef();\r\n\t}\r\n\r\n bool isComplete()\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n double getLeft()\r\n\t{\r\n\t\treturn 0.5;\r\n\t}\r\n double getRight()\r\n\t{\r\n\t\treturn 0.5;\r\n\t}\r\n double getPosition()\r\n\t{\r\n\t}\r\n void stop()\r\n\t{\r\n\t}\r\n void setTransform(const SoundTransform &inTransform)\r\n\t{\r\n\t}\r\n\r\n\tObject *mSound;\r\n\tint mStreamID;\r\n};\r\n\r\n\r\n\r\nclass AndroidMusicChannel : public SoundChannel\r\n{\r\npublic:\r\n AndroidMusicChannel(Object *inSound, int inHandle,\r\n\t\t\t\t\t\t\t double startTime, int loops, const SoundTransform &inTransform)\r\n\t{\r\n\t\tmState = 0;\r\n\t\tmSound = inSound;\r\n\t\tinSound->IncRef();\r\n\r\n\t\tif (inHandle>=0)\r\n\t\t{\r\n\t\t jclass cls = gEnv->FindClass(\"org\/haxe\/nme\/GameActivity\");\r\n jmethodID mid = gEnv->GetStaticMethodID(cls, \"playMusic\", \"(IDDI)I\");\r\n if (mid > 0)\r\n\t\t {\r\n\t\t\t mState = gEnv->CallStaticIntMethod(cls, mid, inHandle, inTransform.volume*((1-inTransform.pan)\/2), inTransform.volume*((inTransform.pan+1)\/2), loops );\r\n\t\t }\r\n\t\t}\r\n }\r\n\r\n ~AndroidMusicChannel()\r\n {\r\n mSound->DecRef();\r\n\t}\r\n\r\n bool isComplete()\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n double getLeft()\r\n\t{\r\n\t\treturn 0.5;\r\n\t}\r\n double getRight()\r\n\t{\r\n\t\treturn 0.5;\r\n\t}\r\n double getPosition()\r\n\t{\r\n\t}\r\n void stop()\r\n\t{\r\n\t}\r\n void setTransform(const SoundTransform &inTransform)\r\n\t{\r\n\t}\r\n\r\n\tObject *mSound;\r\n int mState;\r\n};\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass AndroidSound : public Sound\r\n{\r\n enum SoundMode\r\n {\r\n MODE_UNKNOWN,\r\n MODE_SOUND_ID,\r\n MODE_MUSIC_RES_ID,\r\n MODE_MUSIC_NAME,\r\n };\r\n\r\npublic:\r\n\tAndroidSound(const std::string &inSound, bool inForceMusic)\r\n\t{\r\n\t\tIncRef();\r\n\r\n mMode = MODE_UNKNOWN;\r\n\t\tmID = -1;\r\n\t\tjclass cls = gEnv->FindClass(\"org\/haxe\/nme\/GameActivity\");\r\n\t\tjstring str = gEnv->NewStringUTF( inSound.c_str() );\r\n\r\n if (!inForceMusic)\r\n {\r\n jmethodID mid = gEnv->GetStaticMethodID(cls, \"getSoundHandle\", \"(Ljava\/lang\/String;)I\");\r\n if (mid > 0)\r\n\t\t {\r\n\t\t\t mID = gEnv->CallStaticIntMethod(cls, mid, str);\r\n if (mID>=0)\r\n mMode = MODE_SOUND_ID;\r\n\t\t }\r\n }\r\n\r\n if (mID<0)\r\n {\r\n jmethodID gmh = gEnv->GetStaticMethodID(cls, \"getMusicHandle\", \"(Ljava\/lang\/String;)I\");\r\n if (gmh>0)\r\n {\r\n\t\t\t mID = gEnv->CallStaticIntMethod(cls, gmh, str);\r\n if (mID>0)\r\n mMode = MODE_MUSIC_RES_ID;\r\n }\r\n }\r\n\r\n if (mID<0)\r\n {\r\n mMusicName = inSound;\r\n mMode = MODE_MUSIC_NAME;\r\n }\r\n\t}\r\n\r\n int getBytesLoaded() { return 0; }\r\n int getBytesTotal() { return 0; }\r\n bool ok() { return mID >= 0; }\r\n std::string getError() { return ok() ? \"\" : \"Error\"; }\r\n double getLength() { return 0; }\r\n void close() { }\r\n\r\n\r\n SoundChannel *openChannel(double startTime, int loops, const SoundTransform &inTransform)\r\n\t{\r\n if (mMode==MODE_MUSIC_RES_ID)\r\n\t\t return new AndroidMusicChannel(this,mID,startTime,loops,inTransform);\r\n\r\n\r\n\t\treturn new AndroidSoundChannel(this,mID,startTime,loops,inTransform);\r\n\t}\r\n\r\n\tint mID;\r\n std::string mMusicName;\r\n SoundMode mMode;\r\n};\r\n\r\n\r\nSound *Sound::Create(const std::string &inFilename,bool inForceMusic)\r\n{\r\n\treturn new AndroidSound(inFilename,inForceMusic);\r\n}\r\n\r\n\r\n\r\n}\r\n<|endoftext|>"} {"text":"\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/\/ vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:\n#ident \"$Id$\"\n\/*\nCOPYING CONDITIONS NOTICE:\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of version 2 of the GNU General Public License as\n published by the Free Software Foundation, and provided that the\n following conditions are met:\n\n * Redistributions of source code must retain this COPYING\n CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the\n DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the\n PATENT MARKING NOTICE (below), and the PATENT RIGHTS\n GRANT (below).\n\n * Redistributions in binary form must reproduce this COPYING\n CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the\n DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the\n PATENT MARKING NOTICE (below), and the PATENT RIGHTS\n GRANT (below) in the documentation and\/or other materials\n provided with the distribution.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n\nCOPYRIGHT NOTICE:\n\n TokuDB, Tokutek Fractal Tree Indexing Library.\n Copyright (C) 2007-2013 Tokutek, Inc.\n\nDISCLAIMER:\n\n This program is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n General Public License for more details.\n\nUNIVERSITY PATENT NOTICE:\n\n The technology is licensed by the Massachusetts Institute of\n Technology, Rutgers State University of New Jersey, and the Research\n Foundation of State University of New York at Stony Brook under\n United States of America Serial No. 11\/760379 and to the patents\n and\/or patent applications resulting from it.\n\nPATENT MARKING NOTICE:\n\n This software is covered by US Patent No. 8,185,551.\n\nPATENT RIGHTS GRANT:\n\n \"THIS IMPLEMENTATION\" means the copyrightable works distributed by\n Tokutek as part of the Fractal Tree project.\n\n \"PATENT CLAIMS\" means the claims of patents that are owned or\n licensable by Tokutek, both currently or in the future; and that in\n the absence of this license would be infringed by THIS\n IMPLEMENTATION or by using or running THIS IMPLEMENTATION.\n\n \"PATENT CHALLENGE\" shall mean a challenge to the validity,\n patentability, enforceability and\/or non-infringement of any of the\n PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS.\n\n Tokutek hereby grants to you, for the term and geographical scope of\n the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free,\n irrevocable (except as stated in this section) patent license to\n make, have made, use, offer to sell, sell, import, transfer, and\n otherwise run, modify, and propagate the contents of THIS\n IMPLEMENTATION, where such license applies only to the PATENT\n CLAIMS. This grant does not include claims that would be infringed\n only as a consequence of further modifications of THIS\n IMPLEMENTATION. If you or your agent or licensee institute or order\n or agree to the institution of patent litigation against any entity\n (including a cross-claim or counterclaim in a lawsuit) alleging that\n THIS IMPLEMENTATION constitutes direct or contributory patent\n infringement, or inducement of patent infringement, then any rights\n granted to you under this License shall terminate as of the date\n such litigation is filed. If you or your agent or exclusive\n licensee institute or order or agree to the institution of a PATENT\n CHALLENGE, then Tokutek may terminate any rights granted to you\n under this License.\n*\/\n\n#ident \"Copyright (c) 2007-2013 Tokutek Inc. All rights reserved.\"\n\n#include \n#include \n\n\/\/#include \n#include \n#include \n#include \"toku_crash.h\"\n#include \"toku_atomic.h\"\n\nenum { MAX_GDB_ARGS = 128 };\n\nstatic void\nrun_gdb(pid_t parent_pid, const char *gdb_path) {\n \/\/ 3 bytes per intbyte, null byte\n char pid_buf[sizeof(pid_t) * 3 + 1];\n char exe_buf[sizeof(pid_buf) + sizeof(\"\/proc\/\/exe\")];\n\n \/\/ Get pid and path to executable.\n int n;\n n = snprintf(pid_buf, sizeof(pid_buf), \"%d\", parent_pid);\n paranoid_invariant(n >= 0 && n < (int)sizeof(pid_buf));\n n = snprintf(exe_buf, sizeof(exe_buf), \"\/proc\/%d\/exe\", parent_pid);\n paranoid_invariant(n >= 0 && n < (int)sizeof(exe_buf));\n\n dup2(2, 1); \/\/ redirect output to stderr\n \/\/ Arguments are not dynamic due to possible security holes.\n execlp(gdb_path, gdb_path, \"--batch\", \"-n\",\n \"-ex\", \"thread\",\n \"-ex\", \"bt\",\n \"-ex\", \"bt full\",\n \"-ex\", \"thread apply all bt\",\n \"-ex\", \"thread apply all bt full\",\n exe_buf, pid_buf,\n NULL);\n}\n\nstatic void\nintermediate_process(pid_t parent_pid, const char *gdb_path) {\n \/\/ Disable generating of core dumps\n prctl(PR_SET_DUMPABLE, 0, 0, 0);\n pid_t worker_pid = fork();\n if (worker_pid < 0) {\n perror(\"spawn gdb fork: \");\n goto failure;\n }\n if (worker_pid == 0) {\n \/\/ Child (debugger)\n run_gdb(parent_pid, gdb_path);\n \/\/ Normally run_gdb will not return.\n \/\/ In case it does, kill the process.\n goto failure;\n } else {\n pid_t timeout_pid = fork();\n if (timeout_pid < 0) {\n perror(\"spawn timeout fork: \");\n kill(worker_pid, SIGKILL);\n goto failure;\n }\n\n if (timeout_pid == 0) {\n sleep(5); \/\/ Timeout of 5 seconds\n goto success;\n } else {\n pid_t exited_pid = wait(NULL); \/\/ Wait for first child to exit\n if (exited_pid == worker_pid) {\n \/\/ Kill slower child\n kill(timeout_pid, SIGKILL);\n goto success;\n } else if (exited_pid == timeout_pid) {\n \/\/ Kill slower child\n kill(worker_pid, SIGKILL);\n goto failure; \/\/ Timed out.\n } else {\n perror(\"error while waiting for gdb or timer to end: \");\n \/\/Some failure. Kill everything.\n kill(timeout_pid, SIGKILL);\n kill(worker_pid, SIGKILL);\n goto failure;\n }\n }\n }\nsuccess:\n _exit(EXIT_SUCCESS);\nfailure:\n _exit(EXIT_FAILURE);\n}\n\nstatic void\nspawn_gdb(const char *gdb_path) {\n pid_t parent_pid = getpid();\n \/\/ Give permission for this process and (more importantly) all its children to debug this process.\n prctl(PR_SET_PTRACER, parent_pid, 0, 0, 0);\n fprintf(stderr, \"Attempting to use gdb @[%s] on pid[%d]\\n\", gdb_path, parent_pid);\n fflush(stderr);\n int intermediate_pid = fork();\n if (intermediate_pid < 0) {\n perror(\"spawn_gdb intermediate process fork: \");\n } else if (intermediate_pid == 0) {\n intermediate_process(parent_pid, gdb_path);\n } else {\n waitpid(intermediate_pid, NULL, 0);\n }\n}\n\nvoid\ntoku_try_gdb_stack_trace(const char *gdb_path) {\n char default_gdb_path[] = \"\/usr\/bin\/gdb\";\n static bool started = false;\n if (RUNNING_ON_VALGRIND) {\n fprintf(stderr, \"gdb stack trace skipped due to running under valgrind\\n\");\n fflush(stderr);\n } else if (toku_sync_bool_compare_and_swap(&started, false, true)) {\n spawn_gdb(gdb_path ? gdb_path : default_gdb_path);\n }\n}\n\nRefs Tokutek\/ft-index#28 Fix compile failure on systems that don't support PR_SET_PTRACER\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/\/ vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:\n#ident \"$Id$\"\n\/*\nCOPYING CONDITIONS NOTICE:\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of version 2 of the GNU General Public License as\n published by the Free Software Foundation, and provided that the\n following conditions are met:\n\n * Redistributions of source code must retain this COPYING\n CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the\n DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the\n PATENT MARKING NOTICE (below), and the PATENT RIGHTS\n GRANT (below).\n\n * Redistributions in binary form must reproduce this COPYING\n CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the\n DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the\n PATENT MARKING NOTICE (below), and the PATENT RIGHTS\n GRANT (below) in the documentation and\/or other materials\n provided with the distribution.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n\nCOPYRIGHT NOTICE:\n\n TokuDB, Tokutek Fractal Tree Indexing Library.\n Copyright (C) 2007-2013 Tokutek, Inc.\n\nDISCLAIMER:\n\n This program is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n General Public License for more details.\n\nUNIVERSITY PATENT NOTICE:\n\n The technology is licensed by the Massachusetts Institute of\n Technology, Rutgers State University of New Jersey, and the Research\n Foundation of State University of New York at Stony Brook under\n United States of America Serial No. 11\/760379 and to the patents\n and\/or patent applications resulting from it.\n\nPATENT MARKING NOTICE:\n\n This software is covered by US Patent No. 8,185,551.\n\nPATENT RIGHTS GRANT:\n\n \"THIS IMPLEMENTATION\" means the copyrightable works distributed by\n Tokutek as part of the Fractal Tree project.\n\n \"PATENT CLAIMS\" means the claims of patents that are owned or\n licensable by Tokutek, both currently or in the future; and that in\n the absence of this license would be infringed by THIS\n IMPLEMENTATION or by using or running THIS IMPLEMENTATION.\n\n \"PATENT CHALLENGE\" shall mean a challenge to the validity,\n patentability, enforceability and\/or non-infringement of any of the\n PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS.\n\n Tokutek hereby grants to you, for the term and geographical scope of\n the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free,\n irrevocable (except as stated in this section) patent license to\n make, have made, use, offer to sell, sell, import, transfer, and\n otherwise run, modify, and propagate the contents of THIS\n IMPLEMENTATION, where such license applies only to the PATENT\n CLAIMS. This grant does not include claims that would be infringed\n only as a consequence of further modifications of THIS\n IMPLEMENTATION. If you or your agent or licensee institute or order\n or agree to the institution of patent litigation against any entity\n (including a cross-claim or counterclaim in a lawsuit) alleging that\n THIS IMPLEMENTATION constitutes direct or contributory patent\n infringement, or inducement of patent infringement, then any rights\n granted to you under this License shall terminate as of the date\n such litigation is filed. If you or your agent or exclusive\n licensee institute or order or agree to the institution of a PATENT\n CHALLENGE, then Tokutek may terminate any rights granted to you\n under this License.\n*\/\n\n#ident \"Copyright (c) 2007-2013 Tokutek Inc. All rights reserved.\"\n\n#include \n#include \n\n\/\/#include \n#include \n#include \n#include \"toku_crash.h\"\n#include \"toku_atomic.h\"\n\nenum { MAX_GDB_ARGS = 128 };\n\nstatic void\nrun_gdb(pid_t parent_pid, const char *gdb_path) {\n \/\/ 3 bytes per intbyte, null byte\n char pid_buf[sizeof(pid_t) * 3 + 1];\n char exe_buf[sizeof(pid_buf) + sizeof(\"\/proc\/\/exe\")];\n\n \/\/ Get pid and path to executable.\n int n;\n n = snprintf(pid_buf, sizeof(pid_buf), \"%d\", parent_pid);\n paranoid_invariant(n >= 0 && n < (int)sizeof(pid_buf));\n n = snprintf(exe_buf, sizeof(exe_buf), \"\/proc\/%d\/exe\", parent_pid);\n paranoid_invariant(n >= 0 && n < (int)sizeof(exe_buf));\n\n dup2(2, 1); \/\/ redirect output to stderr\n \/\/ Arguments are not dynamic due to possible security holes.\n execlp(gdb_path, gdb_path, \"--batch\", \"-n\",\n \"-ex\", \"thread\",\n \"-ex\", \"bt\",\n \"-ex\", \"bt full\",\n \"-ex\", \"thread apply all bt\",\n \"-ex\", \"thread apply all bt full\",\n exe_buf, pid_buf,\n NULL);\n}\n\nstatic void\nintermediate_process(pid_t parent_pid, const char *gdb_path) {\n \/\/ Disable generating of core dumps\n prctl(PR_SET_DUMPABLE, 0, 0, 0);\n pid_t worker_pid = fork();\n if (worker_pid < 0) {\n perror(\"spawn gdb fork: \");\n goto failure;\n }\n if (worker_pid == 0) {\n \/\/ Child (debugger)\n run_gdb(parent_pid, gdb_path);\n \/\/ Normally run_gdb will not return.\n \/\/ In case it does, kill the process.\n goto failure;\n } else {\n pid_t timeout_pid = fork();\n if (timeout_pid < 0) {\n perror(\"spawn timeout fork: \");\n kill(worker_pid, SIGKILL);\n goto failure;\n }\n\n if (timeout_pid == 0) {\n sleep(5); \/\/ Timeout of 5 seconds\n goto success;\n } else {\n pid_t exited_pid = wait(NULL); \/\/ Wait for first child to exit\n if (exited_pid == worker_pid) {\n \/\/ Kill slower child\n kill(timeout_pid, SIGKILL);\n goto success;\n } else if (exited_pid == timeout_pid) {\n \/\/ Kill slower child\n kill(worker_pid, SIGKILL);\n goto failure; \/\/ Timed out.\n } else {\n perror(\"error while waiting for gdb or timer to end: \");\n \/\/Some failure. Kill everything.\n kill(timeout_pid, SIGKILL);\n kill(worker_pid, SIGKILL);\n goto failure;\n }\n }\n }\nsuccess:\n _exit(EXIT_SUCCESS);\nfailure:\n _exit(EXIT_FAILURE);\n}\n\nstatic void\nspawn_gdb(const char *gdb_path) {\n pid_t parent_pid = getpid();\n#if defined(PR_SET_PTRACER)\n \/\/ On systems that require permission for the same user to ptrace,\n \/\/ give permission for this process and (more importantly) all its children to debug this process.\n prctl(PR_SET_PTRACER, parent_pid, 0, 0, 0);\n#endif\n fprintf(stderr, \"Attempting to use gdb @[%s] on pid[%d]\\n\", gdb_path, parent_pid);\n fflush(stderr);\n int intermediate_pid = fork();\n if (intermediate_pid < 0) {\n perror(\"spawn_gdb intermediate process fork: \");\n } else if (intermediate_pid == 0) {\n intermediate_process(parent_pid, gdb_path);\n } else {\n waitpid(intermediate_pid, NULL, 0);\n }\n}\n\nvoid\ntoku_try_gdb_stack_trace(const char *gdb_path) {\n char default_gdb_path[] = \"\/usr\/bin\/gdb\";\n static bool started = false;\n if (RUNNING_ON_VALGRIND) {\n fprintf(stderr, \"gdb stack trace skipped due to running under valgrind\\n\");\n fflush(stderr);\n } else if (toku_sync_bool_compare_and_swap(&started, false, true)) {\n spawn_gdb(gdb_path ? gdb_path : default_gdb_path);\n }\n}\n\n<|endoftext|>"} {"text":"#ifdef OS_LINUX\n#define LIBLOADERSRC\n\n#include \"LinuxLibraryLoader.cpp\"\n\n#endif\n \n#ifdef OS_WINDOWS\n#define LIBLOADERSRC\n#include \"WindowsLibraryLoader.cpp\"\n\/\/....\n#endif\n\n#ifndef LIBLOADERSRC\n#error \"no suited library loader found or system not recognized\"\n#endif\n\nfixed osx lib loader#ifdef OS_LINUX\n#define LIBLOADERSRC\n#include \"LinuxLibraryLoader.cpp\"\n#endif\n\n#ifdef OS_MACOSX\n#define LIBLOADERSRC\n#include \"LinuxLibraryLoader.cpp\"\n#endif\n \n#ifdef OS_WINDOWS\n#define LIBLOADERSRC\n#include \"WindowsLibraryLoader.cpp\"\n#endif\n\n#ifndef LIBLOADERSRC\n#error \"no suited library loader found or system not recognized\"\n#endif\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNumericType LaplasOperator( const CMatrix& matrix, const CUniformGrid& grid, size_t x, size_t y )\n{\n\tconst NumericType ldx = ( matrix( x, y ) - matrix( x - 1, y ) ) \/ grid.X.Step( x - 1 );\n\tconst NumericType rdx = ( matrix( x + 1, y ) - matrix( x, y ) ) \/ grid.X.Step( x );\n\tconst NumericType tdy = ( matrix( x, y ) - matrix( x, y - 1 ) ) \/ grid.Y.Step( y - 1 );\n\tconst NumericType bdy = ( matrix( x, y + 1 ) - matrix( x, y ) ) \/ grid.Y.Step( y );\n\tconst NumericType dx = ( ldx - rdx ) \/ grid.X.AverageStep( x );\n\tconst NumericType dy = ( tdy - bdy ) \/ grid.Y.AverageStep( y );\n\treturn ( dx + dy );\n}\n\n\/\/ Вычисление невязки rij во внутренних точках.\nvoid CalcR( const CMatrix&p, const CUniformGrid& grid, CMatrix& r )\n{\n#ifndef DIRCH_NO_OPENMP\n#pragma omp parallel for\n\tfor( long x = 1; x < r.SizeX() - 1; x++ ) {\n#else\n\tfor( size_t x = 1; x < r.SizeX() - 1; x++ ) {\n#endif\n\t\tfor( size_t y = 1; y < r.SizeY() - 1; y++ ) {\n\t\t\tr( x, y ) = LaplasOperator( p, grid, x, y ) - F( grid.X[x], grid.Y[y] );\n\t\t}\n\t}\n}\n\n\/\/ Вычисление значений gij во внутренних точках.\nvoid CalcG( const CMatrix&r, const NumericType alpha, CMatrix& g )\n{\n#ifndef DIRCH_NO_OPENMP\n#pragma omp parallel for\n\tfor( long x = 1; x < g.SizeX() - 1; x++ ) {\n#else\n\tfor( size_t x = 1; x < g.SizeX() - 1; x++ ) {\n#endif\n\t\tfor( size_t y = 1; y < g.SizeY() - 1; y++ ) {\n\t\t\tg( x, y ) = r( x, y ) - alpha * g( x, y );\n\t\t}\n\t}\n}\n\n\n\/\/ Вычисление значений pij во внутренних точках, возвращается максимум норма.\nNumericType CalcP( const CMatrix&g, const NumericType tau, CMatrix& p )\n{\n\tNumericType difference = 0;\n\tfor( size_t x = 1; x < p.SizeX() - 1; x++ ) {\n\t\tfor( size_t y = 1; y < g.SizeY() - 1; y++ ) {\n\t\t\tconst NumericType newValue = p( x, y ) - tau * g( x, y );\n\t\t\tdifference = max( difference, abs( newValue - p( x, y ) ) );\n\t\t\tp( x, y ) = newValue;\n\t\t}\n\t}\n\treturn difference;\n}\n\n\/\/ Вычисление alpha.\nCFraction CalcAlpha( const CMatrix&r, const CMatrix&g, const CUniformGrid& grid )\n{\n\tNumericType numerator = 0;\n\tNumericType denominator = 0;\n#ifndef DIRCH_NO_OPENMP\n#pragma omp parallel for reduction( +:numerator, denominator )\n\tfor( long x = 1; x < r.SizeX() - 1; x++ ) {\n#else\n\tfor( size_t x = 1; x < r.SizeX() - 1; x++ ) {\n#endif\n\t\tfor( size_t y = 1; y < r.SizeY() - 1; y++ ) {\n\t\t\tconst NumericType common = g( x, y ) * grid.X.AverageStep( x ) * grid.Y.AverageStep( y );\n\t\t\tnumerator += LaplasOperator( r, grid, x, y ) * common;\n\t\t\tdenominator += LaplasOperator( g, grid, x, y ) * common;\n\t\t}\n\t}\n\treturn CFraction( numerator, denominator );\n}\n\n\/\/ Вычисление tau.\nCFraction CalcTau( const CMatrix&r, const CMatrix&g, const CUniformGrid& grid )\n{\n\tNumericType numerator = 0;\n\tNumericType denominator = 0;\n#ifndef DIRCH_NO_OPENMP\n#pragma omp parallel for reduction( +:numerator, denominator )\n\tfor( long x = 1; x < r.SizeX() - 1; x++ ) {\n#else\n\tfor( size_t x = 1; x < r.SizeX() - 1; x++ ) {\n#endif\n\t\tfor( size_t y = 1; y < r.SizeY() - 1; y++ ) {\n\t\t\tconst NumericType common = g( x, y ) * grid.X.AverageStep( x ) * grid.Y.AverageStep( y );\n\t\t\tnumerator += r( x, y ) * common;\n\t\t\tdenominator += LaplasOperator( g, grid, x, y ) * common;\n\t\t}\n\t}\n\treturn CFraction( numerator, denominator );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nsmall style changes#include \n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNumericType LaplasOperator( const CMatrix& matrix, const CUniformGrid& grid, size_t x, size_t y )\n{\n\tconst NumericType ldx = ( matrix( x, y ) - matrix( x - 1, y ) ) \/ grid.X.Step( x - 1 );\n\tconst NumericType rdx = ( matrix( x + 1, y ) - matrix( x, y ) ) \/ grid.X.Step( x );\n\tconst NumericType tdy = ( matrix( x, y ) - matrix( x, y - 1 ) ) \/ grid.Y.Step( y - 1 );\n\tconst NumericType bdy = ( matrix( x, y + 1 ) - matrix( x, y ) ) \/ grid.Y.Step( y );\n\tconst NumericType dx = ( ldx - rdx ) \/ grid.X.AverageStep( x );\n\tconst NumericType dy = ( tdy - bdy ) \/ grid.Y.AverageStep( y );\n\treturn ( dx + dy );\n}\n\n\/\/ Вычисление невязки rij во внутренних точках.\nvoid CalcR( const CMatrix& p, const CUniformGrid& grid, CMatrix& r )\n{\n#ifndef DIRCH_NO_OPENMP\n#pragma omp parallel for\n\tfor( long x = 1; x < r.SizeX() - 1; x++ ) {\n#else\n\tfor( size_t x = 1; x < r.SizeX() - 1; x++ ) {\n#endif\n\t\tfor( size_t y = 1; y < r.SizeY() - 1; y++ ) {\n\t\t\tr( x, y ) = LaplasOperator( p, grid, x, y ) - F( grid.X[x], grid.Y[y] );\n\t\t}\n\t}\n}\n\n\/\/ Вычисление значений gij во внутренних точках.\nvoid CalcG( const CMatrix& r, const NumericType alpha, CMatrix& g )\n{\n#ifndef DIRCH_NO_OPENMP\n#pragma omp parallel for\n\tfor( long x = 1; x < g.SizeX() - 1; x++ ) {\n#else\n\tfor( size_t x = 1; x < g.SizeX() - 1; x++ ) {\n#endif\n\t\tfor( size_t y = 1; y < g.SizeY() - 1; y++ ) {\n\t\t\tg( x, y ) = r( x, y ) - alpha * g( x, y );\n\t\t}\n\t}\n}\n\n\/\/ Вычисление значений pij во внутренних точках, возвращается максимум норма.\nNumericType CalcP( const CMatrix& g, const NumericType tau, CMatrix& p )\n{\n\tNumericType difference = 0;\n\tfor( size_t x = 1; x < p.SizeX() - 1; x++ ) {\n\t\tfor( size_t y = 1; y < g.SizeY() - 1; y++ ) {\n\t\t\tconst NumericType newValue = p( x, y ) - tau * g( x, y );\n\t\t\tdifference = max( difference, abs( newValue - p( x, y ) ) );\n\t\t\tp( x, y ) = newValue;\n\t\t}\n\t}\n\treturn difference;\n}\n\n\/\/ Вычисление alpha.\nCFraction CalcAlpha( const CMatrix& r, const CMatrix&g, const CUniformGrid& grid )\n{\n\tNumericType numerator = 0;\n\tNumericType denominator = 0;\n#ifndef DIRCH_NO_OPENMP\n#pragma omp parallel for reduction( +:numerator, denominator )\n\tfor( long x = 1; x < r.SizeX() - 1; x++ ) {\n#else\n\tfor( size_t x = 1; x < r.SizeX() - 1; x++ ) {\n#endif\n\t\tfor( size_t y = 1; y < r.SizeY() - 1; y++ ) {\n\t\t\tconst NumericType common = g( x, y ) * grid.X.AverageStep( x ) * grid.Y.AverageStep( y );\n\t\t\tnumerator += LaplasOperator( r, grid, x, y ) * common;\n\t\t\tdenominator += LaplasOperator( g, grid, x, y ) * common;\n\t\t}\n\t}\n\treturn CFraction( numerator, denominator );\n}\n\n\/\/ Вычисление tau.\nCFraction CalcTau( const CMatrix& r, const CMatrix&g, const CUniformGrid& grid )\n{\n\tNumericType numerator = 0;\n\tNumericType denominator = 0;\n#ifndef DIRCH_NO_OPENMP\n#pragma omp parallel for reduction( +:numerator, denominator )\n\tfor( long x = 1; x < r.SizeX() - 1; x++ ) {\n#else\n\tfor( size_t x = 1; x < r.SizeX() - 1; x++ ) {\n#endif\n\t\tfor( size_t y = 1; y < r.SizeY() - 1; y++ ) {\n\t\t\tconst NumericType common = g( x, y ) * grid.X.AverageStep( x ) * grid.Y.AverageStep( y );\n\t\t\tnumerator += r( x, y ) * common;\n\t\t\tdenominator += LaplasOperator( g, grid, x, y ) * common;\n\t\t}\n\t}\n\treturn CFraction( numerator, denominator );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"#include \"OpenGLTexture.h\"\n\n#include \"TextureRef.h\"\n\n#ifdef WIN32\n#include \n#endif\n\n#define GL_GLEXT_PROTOTYPES\n\n#ifdef __APPLE__\n#include \n#include \n#else\n\/\/ #include \n\/\/ #include \n\/\/ #include \n\n#ifdef _WIN32\n#include \n#endif\n\n#ifdef __WXMAC__\n#include \"OpenGL\/gl.h\"\n#else\n#include \n#endif\n\n#ifdef _WIN32\n#include \"glext.h\"\n#else\n#include \n#endif\n\n#endif\n\n#include \n\nusing namespace std;\nusing namespace canvas;\n\nsize_t OpenGLTexture::total_textures = 0;\nvector OpenGLTexture::freed_textures;\n\nstatic GLenum getOpenGLInternalFormat(InternalFormat internal_format) {\n switch (internal_format) {\n case RG8: return GL_RG8;\n case RGB565: return GL_RGB565;\n case RGBA4: return GL_RGBA4;\n case RGBA8: return GL_RGBA8;\n#ifdef __linux__\n case COMPRESSED_RG: return GL_RG8;\n case COMPRESSED_RGB: return GL_RGB5;\n case COMPRESSED_RGBA: return GL_RGBA8;\n#else\n case COMPRESSED_RG: return GL_COMPRESSED_RG11_EAC;\n case COMPRESSED_RGB: return GL_COMPRESSED_RGB8_ETC2;\n case COMPRESSED_RGBA: return GL_COMPRESSED_RGBA8_ETC2_EAC;\n#endif\n case LUMINANCE_ALPHA: return GL_LUMINANCE_ALPHA;\n }\n return 0;\n}\n\nstatic GLenum getOpenGLFilterType(FilterMode mode) {\n switch (mode) {\n case NEAREST: return GL_NEAREST;\n case LINEAR: return GL_LINEAR;\n case LINEAR_MIPMAP_LINEAR: return GL_LINEAR_MIPMAP_LINEAR;\n }\n return 0;\n}\n\nvoid\nOpenGLTexture::updateData(const void * buffer) {\n updateData(buffer, 0, 0, getActualWidth(), getActualHeight());\n}\n\nvoid\nOpenGLTexture::updateData(const void * buffer, unsigned int x, unsigned int y, unsigned int width, unsigned int height) {\n assert(buffer);\n\n bool initialize = false;\n if (!texture_id) {\n initialize = true;\n glGenTextures(1, &texture_id);\n if (texture_id >= 1) total_textures++; \n }\n assert(texture_id >= 1);\n \n glBindTexture(GL_TEXTURE_2D, texture_id);\n\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n\n bool has_mipmaps = getMinFilter() == LINEAR_MIPMAP_LINEAR;\n if (initialize) {\n \/\/ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, getWidth(), getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); \n glTexStorage2D(GL_TEXTURE_2D, has_mipmaps ? getMipmapLevels() : 1, getOpenGLInternalFormat(getInternalFormat()), getActualWidth(), getActualHeight());\n\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, getOpenGLFilterType(getMinFilter()));\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, getOpenGLFilterType(getMagFilter()));\n }\n\n#ifdef __APPLE__\n glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);\n#else\n glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_BGRA_EXT, GL_UNSIGNED_BYTE, buffer);\n#endif\n if (has_mipmaps) {\n glGenerateMipmap(GL_TEXTURE_2D);\n }\n\n glBindTexture(GL_TEXTURE_2D, 0);\n}\n\nvoid\nOpenGLTexture::releaseTextures() {\n \/\/ cerr << \"DELETING TEXTURES: \" << OpenGLTexture::getFreedTextures().size() << \"\/\" << OpenGLTexture::getNumTextures() << endl;\n \n for (vector::const_iterator it = freed_textures.begin(); it != freed_textures.end(); it++) {\n GLuint texid = *it;\n glDeleteTextures(1, &texid);\n }\n freed_textures.clear();\n}\n\nTextureRef\nOpenGLTexture::createTexture(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, FilterMode min_filter, FilterMode mag_filter, InternalFormat _internal_format, unsigned int mipmap_levels) {\n return TextureRef(_logical_width, _logical_height, _actual_width, _actual_height, new OpenGLTexture(_logical_width, _logical_height, _actual_width, _actual_height, min_filter, mag_filter, _internal_format, mipmap_levels));\n}\nadd conversion for LUMINANCE_ALPHA#include \"OpenGLTexture.h\"\n\n#include \"TextureRef.h\"\n#include \"Image.h\"\n\n#ifdef WIN32\n#include \n#endif\n\n#define GL_GLEXT_PROTOTYPES\n\n#ifdef __APPLE__\n#include \n#include \n#else\n\/\/ #include \n\/\/ #include \n\/\/ #include \n\n#ifdef _WIN32\n#include \n#endif\n\n#ifdef __WXMAC__\n#include \"OpenGL\/gl.h\"\n#else\n#include \n#endif\n\n#ifdef _WIN32\n#include \"glext.h\"\n#else\n#include \n#endif\n\n#endif\n\n#include \n\nusing namespace std;\nusing namespace canvas;\n\nsize_t OpenGLTexture::total_textures = 0;\nvector OpenGLTexture::freed_textures;\n\nstatic GLenum getOpenGLInternalFormat(InternalFormat internal_format) {\n switch (internal_format) {\n case RG8: return GL_RG8;\n case RGB565: return GL_RGB565;\n case RGBA4: return GL_RGBA4;\n case RGBA8: return GL_RGBA8;\n#ifdef __linux__\n case COMPRESSED_RG: return GL_RG8;\n case COMPRESSED_RGB: return GL_RGB5;\n case COMPRESSED_RGBA: return GL_RGBA8;\n#else\n case COMPRESSED_RG: return GL_COMPRESSED_RG11_EAC;\n case COMPRESSED_RGB: return GL_COMPRESSED_RGB8_ETC2;\n case COMPRESSED_RGBA: return GL_COMPRESSED_RGBA8_ETC2_EAC;\n#endif\n case LUMINANCE_ALPHA: return GL_RG8;\n }\n return 0;\n}\n\nstatic GLenum getOpenGLFilterType(FilterMode mode) {\n switch (mode) {\n case NEAREST: return GL_NEAREST;\n case LINEAR: return GL_LINEAR;\n case LINEAR_MIPMAP_LINEAR: return GL_LINEAR_MIPMAP_LINEAR;\n }\n return 0;\n}\n\nvoid\nOpenGLTexture::updateData(const void * buffer) {\n updateData(buffer, 0, 0, getActualWidth(), getActualHeight());\n}\n\nvoid\nOpenGLTexture::updateData(const void * buffer, unsigned int x, unsigned int y, unsigned int width, unsigned int height) {\n assert(buffer);\n\n bool initialize = false;\n if (!texture_id) {\n initialize = true;\n glGenTextures(1, &texture_id);\n if (texture_id >= 1) total_textures++; \n }\n assert(texture_id >= 1);\n \n glBindTexture(GL_TEXTURE_2D, texture_id);\n\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n\n bool has_mipmaps = getMinFilter() == LINEAR_MIPMAP_LINEAR;\n if (initialize) {\n \/\/ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, getWidth(), getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); \n glTexStorage2D(GL_TEXTURE_2D, has_mipmaps ? getMipmapLevels() : 1, getOpenGLInternalFormat(getInternalFormat()), getActualWidth(), getActualHeight());\n\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, getOpenGLFilterType(getMinFilter()));\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, getOpenGLFilterType(getMagFilter()));\n }\n\n if (getInternalFormat() == LUMINANCE_ALPHA) {\n Image tmp_image(width, height, (const unsigned char *)buffer, ImageFormat::RGBA32);\n auto tmp_image2 = tmp_image.changeFormat(ImageFormat::LUMALPHA8);\n glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RG, GL_UNSIGNED_BYTE, tmp_image2->getData());\n } else {\n#ifdef __APPLE__\n glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);\n#else\n glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_BGRA_EXT, GL_UNSIGNED_BYTE, buffer);\n#endif\n }\n if (has_mipmaps) {\n glGenerateMipmap(GL_TEXTURE_2D);\n }\n\n glBindTexture(GL_TEXTURE_2D, 0);\n}\n\nvoid\nOpenGLTexture::releaseTextures() {\n \/\/ cerr << \"DELETING TEXTURES: \" << OpenGLTexture::getFreedTextures().size() << \"\/\" << OpenGLTexture::getNumTextures() << endl;\n \n for (vector::const_iterator it = freed_textures.begin(); it != freed_textures.end(); it++) {\n GLuint texid = *it;\n glDeleteTextures(1, &texid);\n }\n freed_textures.clear();\n}\n\nTextureRef\nOpenGLTexture::createTexture(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, FilterMode min_filter, FilterMode mag_filter, InternalFormat _internal_format, unsigned int mipmap_levels) {\n return TextureRef(_logical_width, _logical_height, _actual_width, _actual_height, new OpenGLTexture(_logical_width, _logical_height, _actual_width, _actual_height, min_filter, mag_filter, _internal_format, mipmap_levels));\n}\n<|endoftext|>"} {"text":"\/** @file edgeelement.cpp\n * \t@brief Класс, представляющий связь на диаграмме\n * *\/\n#include \n#include \n\n#include \"editorviewscene.h\"\n\n#include \"uml_edgeelement.h\"\n#include \"uml_nodeelement.h\"\n\n#include \"realreporoles.h\"\n#include \"realrepoinfo.h\"\n\n#include \n\nusing namespace UML;\n\n#ifndef M_PI\n\/** @brief Константа ПИ *\/\n#define M_PI 3.14159265358979323846264338327950288419717\n\/** @brief Константа 1\/ПИ *\/\n#define M_1_PI 1\/M_PI;\n\/\/ Реквестирую ещё массу бозона Хиггса!\n#endif \/\/M_PI\n\n\/** @brief Индикатор перемещения связи *\/\n\/\/ static bool moving = false;\n\nEdgeElement::EdgeElement()\n: beginning(0), ending(0), src(0), dst(0), portFrom(0), portTo(0), dragState(-1), longPart(0)\n{\n\tsetZValue(100);\n\tsetFlag(ItemIsMovable, true);\n\t\/\/ FIXME: draws strangely...\n\tsetFlag(ItemClipsToShape, false);\n\n\tm_penStyle = Qt::SolidLine;\n\tm_line << QPointF(0,0) << QPointF(200,60);\n\n\tm_endArrowStyle = NO_ARROW;\n}\n\nEdgeElement::~EdgeElement()\n{\n\tif (src)\n\t\tsrc->delEdge(this);\n\tif (dst)\n\t\tdst->delEdge(this);\n}\n\nQRectF EdgeElement::boundingRect() const\n{\n\t\/\/ return m_line.boundingRect().adjusted(-kvadratik,-kvadratik,kvadratik,kvadratik);\n\treturn m_line.boundingRect().adjusted(-20,-20,20,20);\n}\n\nstatic double lineAngle(const QLineF &line)\n{\n\tdouble angle = ::acos(line.dx() \/ line.length());\n\tif (line.dy() >= 0)\n\t\tangle = 2*M_PI - angle;\n\n\treturn angle*180*M_1_PI;\n}\n\nvoid EdgeElement::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*)\n{\n\tpainter->save();\n\tQPen pen = painter->pen();\n\tpen.setColor(m_color);\n\tpen.setStyle(m_penStyle);\n\tpen.setWidth(1);\n\tpainter->setPen(pen);\n\tpainter->drawPolyline(m_line);\n\tpainter->restore();\n\n\tpainter->save();\n\tpainter->translate(m_line[0]);\n\tpainter->drawText(QPointF(10,20), m_fromMult);\n\tpainter->rotate(90-lineAngle(QLineF(m_line[1],m_line[0])));\n\tdrawStartArrow(painter);\n\tpainter->restore();\n\n\tpainter->save();\n\tpainter->translate(m_line[m_line.size()-1]);\n\tpainter->drawText(QPointF(10,20), m_toMult);\n\tpainter->rotate(90-lineAngle(QLineF(m_line[m_line.size()-2],m_line[m_line.size()-1])));\n\tdrawEndArrow(painter);\n\tpainter->restore();\n\n\tif (option->state & QStyle::State_Selected) {\n\t\tpainter->setBrush(Qt::SolidPattern);\n\t\tforeach( QPointF point, m_line)\n\t\t{\n\t\t\tQPen pen;\n\t\t\tQColor color;\n\n\t\t\tcolor.setNamedColor(\"#c3dcc4\");\n\t\t\tpen.setWidth(11);\n\t\t\tpen.setColor(color);\n\t\t\tpainter->setPen(pen);\n\t\t\tpainter->drawPoint(point);\n\n\t\t\tcolor.setNamedColor(\"#465945\");\n\t\t\tpen.setWidth(3);\n\t\t\tpen.setColor(color);\n\t\t\tpainter->setPen(pen);\n\t\t\tpainter->drawPoint(point);\n\t\t}\n\t}\n\n\tif ( ! m_text.isEmpty() ) {\n\t\tpainter->save();\n\t\tQLineF longest(m_line[longPart],m_line[longPart+1]);\n\t\tpainter->translate(m_line[longPart]);\n\t\tpainter->rotate(-lineAngle(longest));\n\n\/\/\t\tpainter->drawText(0,-15,longest.length(),15,\n\/\/\t\t\t\tQt::TextSingleLine | Qt::AlignCenter, m_text);\n\n\t\tQTextDocument d;\n\t\td.setHtml(m_text);\n\t\td.setTextWidth(longest.length());\n\/\/\t\tpainter->drawRect(QRectF(0,0,longest.length(),20));\n\t\td.drawContents(painter);\n\n\t\tpainter->restore();\n\t}\n}\n\nbool canBeConnected( int linkID, int from, int to );\n\/*\nvoid EdgeElement::checkConnection()\n{\n\/\/\tint type = this->type();\n\tint from = -1;\n\tint to = -1;\n\n\tif ( src != 0 )\n\t\tfrom = src->type();\n\n\tif ( dst != 0 )\n\t\tto = dst->type();\n\n\tm_color = Qt::black;\n}\n*\/\nQPainterPath EdgeElement::shape() const\n{\n\tQPainterPath path;\n\tpath.setFillRule(Qt::WindingFill);\n\n\tQPainterPathStroker ps;\n\tps.setWidth(kvadratik);\n\n\tpath.addPolygon(m_line);\n\tpath = ps.createStroke(path);\n\n\tforeach( QPointF point, m_line) {\n\t\tpath.addRect(QRectF(point-QPointF(kvadratik,kvadratik),QSizeF(kvadratik*2,kvadratik*2)));\n\t}\n\n\treturn path;\n}\n\nint EdgeElement::getPoint( const QPointF &location )\n{\n\tfor ( int i = 0 ; i < m_line.size() ; i++ )\n\t\tif ( QRectF(m_line[i]-QPointF(kvadratik,kvadratik),QSizeF(kvadratik*2,kvadratik*2)).contains( location ) )\n\t\t\treturn i;\n\n\treturn -1;\n}\n\nvoid EdgeElement::updateLongestPart()\n{\n\tqreal maxLen = 0.0;\n\tint maxIdx = 0;\n\tfor ( int i = 0; i < m_line.size() - 1 ; i++ ) {\n\t\tqreal newLen = QLineF(m_line[i],m_line[i+1]).length();\n\t\tif ( newLen > maxLen ) {\n\t\t\tmaxLen = newLen;\n\t\t\tmaxIdx = i;\n\t\t}\n\t}\n\tlongPart = maxIdx;\n}\n\nvoid EdgeElement::mousePressEvent ( QGraphicsSceneMouseEvent * event )\n{\n\tdragState = -1;\n\n\tif ( isSelected() )\n\t\tdragState = getPoint( event->pos() );\n\n\tif ( dragState == -1 )\n\t\tElement::mousePressEvent(event);\n}\n\nvoid EdgeElement::connectToPort() {\n\tQAbstractItemModel *im = const_cast(dataIndex.model());\n\n\tsetPos(pos()+m_line[0]);\n\tm_line.translate(-m_line[0]);\n\n\tmoving = true;\n\n\t\/\/ Now we check whether start or end have been connected\n\tNodeElement *new_src = getNodeAt(m_line[0]);\n\tif ( new_src )\n\t\tportFrom = new_src->getPortId( mapToItem(new_src, m_line[0]) );\n\telse\n\t\tportFrom = -1.0;\n\n\tif ( src ) {\n\t\tsrc->delEdge(this);\n\t\tsrc = 0;\n\t}\n\n\tif ( portFrom >= 0.0 ) {\n\t\tsrc = new_src;\n\t\tsrc->addEdge(this);\n\t}\n\n\tif ( src )\n\t\tim->setData(dataIndex, src->uuid(), Unreal::krneRelationship::fromRole);\n\telse\n\t\tim->setData(dataIndex, 0, Unreal::krneRelationship::fromRole);\n\n\tim->setData(dataIndex, portFrom, Unreal::krneRelationship::fromPortRole);\n\n\n\tNodeElement *new_dst = getNodeAt(m_line[m_line.size()-1]);\n\tif ( new_dst )\n\t\tportTo = new_dst->getPortId( mapToItem(new_dst, m_line[m_line.size()-1]) );\n\telse\n\t\tportTo = -1.0;\n\n\tif ( dst ) {\n\t\tdst->delEdge(this);\n\t\tdst = 0;\n\t}\n\n\tif ( portTo >= 0.0 ) {\n\t\tdst = new_dst;\n\t\tdst->addEdge(this);\n\t}\n\n\tif ( dst )\n\t\tim->setData(dataIndex, dst->uuid(), Unreal::krneRelationship::toRole);\n\telse\n\t\tim->setData(dataIndex, 0, Unreal::krneRelationship::toRole);\n\n\tim->setData(dataIndex, portTo, Unreal::krneRelationship::toPortRole);\n\n\tsetFlag(ItemIsMovable, !(dst||src) );\n\n\tim->setData(dataIndex, pos(), Unreal::PositionRole);\n\tim->setData(dataIndex, m_line.toPolygon(), Unreal::ConfigurationRole);\n\n\tmoving = false;\n\n\tadjustLink();\n}\n\nvoid EdgeElement::mouseMoveEvent ( QGraphicsSceneMouseEvent * event )\n{\n\tNodeElement *new_src = getNodeAt(m_line[0]);\n\tNodeElement *new_dst = getNodeAt(m_line[m_line.size()-1]);\n\tif (beginning) {\n\t\tif (beginning!=new_src) {\n\t\t\tbeginning->setPortsVisible(false);\n\t\t}\n\t}\n\tif (ending) {\n\t\tif (ending!=new_dst) {\n\t\t\tending->setPortsVisible(false);\n\t\t}\n\t}\n\tbeginning = new_src;\n\tending = new_dst;\n\tif (beginning) {\n\t\tbeginning->setPortsVisible(true);\n\t}\n\tif (ending) {\n\t\tending->setPortsVisible(true);\n\t}\n\n\tif ( dragState == -1 ) {\n\t\tElement::mouseMoveEvent(event);\n\t} else {\n\t\tprepareGeometryChange();\n\t\tm_line[dragState] = event->pos();\n\t\tupdateLongestPart();\n\t}\n}\n\nvoid EdgeElement::mouseReleaseEvent ( QGraphicsSceneMouseEvent * event )\n{\n\tif ( dragState == -1 )\n\t\tElement::mouseReleaseEvent(event);\n\telse\n\t\tdragState = -1;\n\tconnectToPort();\n\tif (beginning) {\n\t\tbeginning->setPortsVisible(false);\n\t}\n\tif (ending) {\n\t\tending->setPortsVisible(false);\n\t}\n\t\/\/ cleanup after moving\/resizing\n\tbeginning = ending = NULL;\n}\n\nNodeElement *EdgeElement::getNodeAt( const QPointF &position )\n{\n\tforeach( QGraphicsItem *item, scene()->items(mapToScene(position)) ) {\n\t\tNodeElement *e = dynamic_cast(item);\n\t\tif ( e )\n\t\t\treturn e;\n\t}\n\treturn 0;\n}\n\nvoid EdgeElement::contextMenuEvent ( QGraphicsSceneContextMenuEvent * event )\n{\n\tQMenu menu;\n\n\tQAction *addPointAction = menu.addAction(\"Add point\");\n\tQAction *delPointAction = menu.addAction(\"Remove point\");\n\tQAction *squarizeAction = menu.addAction(\"Squarize :)\");\n\n\tif ( QAction *selectedAction = menu.exec(event->screenPos()) ) {\n\t\tif ( selectedAction == delPointAction ) {\n\t\t\tint i = getPoint( event->pos() );\n\t\t\tif ( i != -1 ) {\n\t\t\t\tprepareGeometryChange();\n\t\t\t\tm_line.remove(i);\n\t\t\t\tlongPart = 0;\n\t\t\t\tupdate();\n\t\t\t}\n\t\t} else if ( selectedAction == addPointAction ) {\n\t\t\tfor ( int i = 0; i < m_line.size()-1; i++ ) {\n\t\t\t\tQPainterPath path;\n\t\t\t\tQPainterPathStroker ps;\n\t\t\t\tps.setWidth(kvadratik);\n\n\t\t\t\tpath.moveTo(m_line[i]);\n\t\t\t\tpath.lineTo(m_line[i+1]);\n\t\t\t\tif ( ps.createStroke(path).contains(event->pos()) ) {\n\t\t\t\t\tm_line.insert(i+1,event->pos());\n\t\t\t\t\tupdate();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if ( selectedAction == squarizeAction ) {\n\t\t\tprepareGeometryChange();\n\t\t\tfor ( int i = 0; i < m_line.size()-1; i++ ) {\n\t\t\t\tQLineF line(m_line[i],m_line[i+1]);\n\t\t\t\tif ( qAbs(line.dx()) < qAbs(line.dy()) ) {\n\t\t\t\t\tm_line[i+1].setX(m_line[i].x());\n\t\t\t\t} else {\n\t\t\t\t\tm_line[i+1].setY(m_line[i].y());\n\t\t\t\t}\n\t\t\t}\n\t\t\tadjustLink();\n\t\t\tupdate();\n\t\t}\n\t}\n}\n\nvoid EdgeElement::adjustLink()\n{\n\tprepareGeometryChange();\n\tif ( src )\n\t\tm_line[0] = mapFromItem(src, src->getPortPos(portFrom) );\n\tif ( dst )\n\t\tm_line[m_line.size()-1] = mapFromItem(dst, dst->getPortPos(portTo) );\n\tupdateLongestPart();\n}\n\nvoid EdgeElement::updateData()\n{\n\tif (moving)\n\t\treturn;\n\n\tElement::updateData();\n\n\tRealRepoInfo info;\n\tTypeIdType type = dataIndex.data(Unreal::TypeRole).toString();\n\n\tm_fromMult = dataIndex.data(info.roleByColumnName(type, \"fromMultiplicity\")).toString();\n\tm_toMult = dataIndex.data(info.roleByColumnName(type, \"toMultiplicity\")).toString();\n\n\tsetPos(dataIndex.data(Unreal::PositionRole).toPointF());\n\tQPolygonF newLine = dataIndex.data(Unreal::ConfigurationRole).value();\n\tif (!newLine.isEmpty())\n\t\tm_line = newLine;\n\n\tqDebug() << \"from role: \" << Unreal::krneRelationship::fromRole\n\t\t<< \"to role: \" << Unreal::krneRelationship::toRole;\n\n\tIdType uuidFrom = dataIndex.data(info.roleByColumnName(type, \"from\")).toString();\n\tIdType uuidTo = dataIndex.data(info.roleByColumnName(type, \"to\")).toString();\n\n\tqDebug() << \"from: \" << uuidFrom << \", to: \" << uuidTo;\n\n\tif (src)\n\t\tsrc->delEdge(this);\n\tif (dst)\n\t\tdst->delEdge(this);\n\n\tsrc = dynamic_cast(static_cast(scene())->getElem(uuidFrom));\n\tdst = dynamic_cast(static_cast(scene())->getElem(uuidTo));\n\n\tif (src)\n\t\tsrc->addEdge(this);\n\tif (dst)\n\t\tdst->addEdge(this);\n\n\tsetFlag(ItemIsMovable, !(dst || src));\n\n\tportFrom = dataIndex.data(info.roleByColumnName(type, \"fromPort\")).toDouble();\n\tportTo = dataIndex.data(info.roleByColumnName(type, \"toPort\")).toDouble();\n\n\tadjustLink();\n}\nRequest on Higgs Boson completed.\/** @file edgeelement.cpp\n * \t@brief Класс, представляющий связь на диаграмме\n * *\/\n#include \n#include \n\n#include \"editorviewscene.h\"\n\n#include \"uml_edgeelement.h\"\n#include \"uml_nodeelement.h\"\n\n#include \"realreporoles.h\"\n#include \"realrepoinfo.h\"\n\n#include \n\nusing namespace UML;\n\n#ifndef M_PI\n\/** @brief Константа ПИ *\/\n#define M_PI 3.14159265358979323846264338327950288419717\n\/** @brief Константа 1\/ПИ *\/\n#define M_1_PI 1\/M_PI;\n\/\/ Реквестирую ещё массу бозона Хиггса!\n\/\/ Here you are: The God's particle energy (in GeV)\n#define HIGGS_BOSON_MASS_APPROX 251\n#endif \/\/M_PI\n\n\/** @brief Индикатор перемещения связи *\/\n\/\/ static bool moving = false;\n\nEdgeElement::EdgeElement()\n: beginning(0), ending(0), src(0), dst(0), portFrom(0), portTo(0), dragState(-1), longPart(0)\n{\n\tsetZValue(100);\n\tsetFlag(ItemIsMovable, true);\n\t\/\/ FIXME: draws strangely...\n\tsetFlag(ItemClipsToShape, false);\n\n\tm_penStyle = Qt::SolidLine;\n\tm_line << QPointF(0,0) << QPointF(200,60);\n\n\tm_endArrowStyle = NO_ARROW;\n}\n\nEdgeElement::~EdgeElement()\n{\n\tif (src)\n\t\tsrc->delEdge(this);\n\tif (dst)\n\t\tdst->delEdge(this);\n}\n\nQRectF EdgeElement::boundingRect() const\n{\n\t\/\/ return m_line.boundingRect().adjusted(-kvadratik,-kvadratik,kvadratik,kvadratik);\n\treturn m_line.boundingRect().adjusted(-20,-20,20,20);\n}\n\nstatic double lineAngle(const QLineF &line)\n{\n\tdouble angle = ::acos(line.dx() \/ line.length());\n\tif (line.dy() >= 0)\n\t\tangle = 2*M_PI - angle;\n\n\treturn angle*180*M_1_PI;\n}\n\nvoid EdgeElement::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*)\n{\n\tpainter->save();\n\tQPen pen = painter->pen();\n\tpen.setColor(m_color);\n\tpen.setStyle(m_penStyle);\n\tpen.setWidth(1);\n\tpainter->setPen(pen);\n\tpainter->drawPolyline(m_line);\n\tpainter->restore();\n\n\tpainter->save();\n\tpainter->translate(m_line[0]);\n\tpainter->drawText(QPointF(10,20), m_fromMult);\n\tpainter->rotate(90-lineAngle(QLineF(m_line[1],m_line[0])));\n\tdrawStartArrow(painter);\n\tpainter->restore();\n\n\tpainter->save();\n\tpainter->translate(m_line[m_line.size()-1]);\n\tpainter->drawText(QPointF(10,20), m_toMult);\n\tpainter->rotate(90-lineAngle(QLineF(m_line[m_line.size()-2],m_line[m_line.size()-1])));\n\tdrawEndArrow(painter);\n\tpainter->restore();\n\n\tif (option->state & QStyle::State_Selected) {\n\t\tpainter->setBrush(Qt::SolidPattern);\n\t\tforeach( QPointF point, m_line)\n\t\t{\n\t\t\tQPen pen;\n\t\t\tQColor color;\n\n\t\t\tcolor.setNamedColor(\"#c3dcc4\");\n\t\t\tpen.setWidth(11);\n\t\t\tpen.setColor(color);\n\t\t\tpainter->setPen(pen);\n\t\t\tpainter->drawPoint(point);\n\n\t\t\tcolor.setNamedColor(\"#465945\");\n\t\t\tpen.setWidth(3);\n\t\t\tpen.setColor(color);\n\t\t\tpainter->setPen(pen);\n\t\t\tpainter->drawPoint(point);\n\t\t}\n\t}\n\n\tif ( ! m_text.isEmpty() ) {\n\t\tpainter->save();\n\t\tQLineF longest(m_line[longPart],m_line[longPart+1]);\n\t\tpainter->translate(m_line[longPart]);\n\t\tpainter->rotate(-lineAngle(longest));\n\n\/\/\t\tpainter->drawText(0,-15,longest.length(),15,\n\/\/\t\t\t\tQt::TextSingleLine | Qt::AlignCenter, m_text);\n\n\t\tQTextDocument d;\n\t\td.setHtml(m_text);\n\t\td.setTextWidth(longest.length());\n\/\/\t\tpainter->drawRect(QRectF(0,0,longest.length(),20));\n\t\td.drawContents(painter);\n\n\t\tpainter->restore();\n\t}\n}\n\nbool canBeConnected( int linkID, int from, int to );\n\/*\nvoid EdgeElement::checkConnection()\n{\n\/\/\tint type = this->type();\n\tint from = -1;\n\tint to = -1;\n\n\tif ( src != 0 )\n\t\tfrom = src->type();\n\n\tif ( dst != 0 )\n\t\tto = dst->type();\n\n\tm_color = Qt::black;\n}\n*\/\nQPainterPath EdgeElement::shape() const\n{\n\tQPainterPath path;\n\tpath.setFillRule(Qt::WindingFill);\n\n\tQPainterPathStroker ps;\n\tps.setWidth(kvadratik);\n\n\tpath.addPolygon(m_line);\n\tpath = ps.createStroke(path);\n\n\tforeach( QPointF point, m_line) {\n\t\tpath.addRect(QRectF(point-QPointF(kvadratik,kvadratik),QSizeF(kvadratik*2,kvadratik*2)));\n\t}\n\n\treturn path;\n}\n\nint EdgeElement::getPoint( const QPointF &location )\n{\n\tfor ( int i = 0 ; i < m_line.size() ; i++ )\n\t\tif ( QRectF(m_line[i]-QPointF(kvadratik,kvadratik),QSizeF(kvadratik*2,kvadratik*2)).contains( location ) )\n\t\t\treturn i;\n\n\treturn -1;\n}\n\nvoid EdgeElement::updateLongestPart()\n{\n\tqreal maxLen = 0.0;\n\tint maxIdx = 0;\n\tfor ( int i = 0; i < m_line.size() - 1 ; i++ ) {\n\t\tqreal newLen = QLineF(m_line[i],m_line[i+1]).length();\n\t\tif ( newLen > maxLen ) {\n\t\t\tmaxLen = newLen;\n\t\t\tmaxIdx = i;\n\t\t}\n\t}\n\tlongPart = maxIdx;\n}\n\nvoid EdgeElement::mousePressEvent ( QGraphicsSceneMouseEvent * event )\n{\n\tdragState = -1;\n\n\tif ( isSelected() )\n\t\tdragState = getPoint( event->pos() );\n\n\tif ( dragState == -1 )\n\t\tElement::mousePressEvent(event);\n}\n\nvoid EdgeElement::connectToPort() {\n\tQAbstractItemModel *im = const_cast(dataIndex.model());\n\n\tsetPos(pos()+m_line[0]);\n\tm_line.translate(-m_line[0]);\n\n\tmoving = true;\n\n\t\/\/ Now we check whether start or end have been connected\n\tNodeElement *new_src = getNodeAt(m_line[0]);\n\tif ( new_src )\n\t\tportFrom = new_src->getPortId( mapToItem(new_src, m_line[0]) );\n\telse\n\t\tportFrom = -1.0;\n\n\tif ( src ) {\n\t\tsrc->delEdge(this);\n\t\tsrc = 0;\n\t}\n\n\tif ( portFrom >= 0.0 ) {\n\t\tsrc = new_src;\n\t\tsrc->addEdge(this);\n\t}\n\n\tif ( src )\n\t\tim->setData(dataIndex, src->uuid(), Unreal::krneRelationship::fromRole);\n\telse\n\t\tim->setData(dataIndex, 0, Unreal::krneRelationship::fromRole);\n\n\tim->setData(dataIndex, portFrom, Unreal::krneRelationship::fromPortRole);\n\n\n\tNodeElement *new_dst = getNodeAt(m_line[m_line.size()-1]);\n\tif ( new_dst )\n\t\tportTo = new_dst->getPortId( mapToItem(new_dst, m_line[m_line.size()-1]) );\n\telse\n\t\tportTo = -1.0;\n\n\tif ( dst ) {\n\t\tdst->delEdge(this);\n\t\tdst = 0;\n\t}\n\n\tif ( portTo >= 0.0 ) {\n\t\tdst = new_dst;\n\t\tdst->addEdge(this);\n\t}\n\n\tif ( dst )\n\t\tim->setData(dataIndex, dst->uuid(), Unreal::krneRelationship::toRole);\n\telse\n\t\tim->setData(dataIndex, 0, Unreal::krneRelationship::toRole);\n\n\tim->setData(dataIndex, portTo, Unreal::krneRelationship::toPortRole);\n\n\tsetFlag(ItemIsMovable, !(dst||src) );\n\n\tim->setData(dataIndex, pos(), Unreal::PositionRole);\n\tim->setData(dataIndex, m_line.toPolygon(), Unreal::ConfigurationRole);\n\n\tmoving = false;\n\n\tadjustLink();\n}\n\nvoid EdgeElement::mouseMoveEvent ( QGraphicsSceneMouseEvent * event )\n{\n\tNodeElement *new_src = getNodeAt(m_line[0]);\n\tNodeElement *new_dst = getNodeAt(m_line[m_line.size()-1]);\n\tif (beginning) {\n\t\tif (beginning!=new_src) {\n\t\t\tbeginning->setPortsVisible(false);\n\t\t}\n\t}\n\tif (ending) {\n\t\tif (ending!=new_dst) {\n\t\t\tending->setPortsVisible(false);\n\t\t}\n\t}\n\tbeginning = new_src;\n\tending = new_dst;\n\tif (beginning) {\n\t\tbeginning->setPortsVisible(true);\n\t}\n\tif (ending) {\n\t\tending->setPortsVisible(true);\n\t}\n\n\tif ( dragState == -1 ) {\n\t\tElement::mouseMoveEvent(event);\n\t} else {\n\t\tprepareGeometryChange();\n\t\tm_line[dragState] = event->pos();\n\t\tupdateLongestPart();\n\t}\n}\n\nvoid EdgeElement::mouseReleaseEvent ( QGraphicsSceneMouseEvent * event )\n{\n\tif ( dragState == -1 )\n\t\tElement::mouseReleaseEvent(event);\n\telse\n\t\tdragState = -1;\n\tconnectToPort();\n\tif (beginning) {\n\t\tbeginning->setPortsVisible(false);\n\t}\n\tif (ending) {\n\t\tending->setPortsVisible(false);\n\t}\n\t\/\/ cleanup after moving\/resizing\n\tbeginning = ending = NULL;\n}\n\nNodeElement *EdgeElement::getNodeAt( const QPointF &position )\n{\n\tforeach( QGraphicsItem *item, scene()->items(mapToScene(position)) ) {\n\t\tNodeElement *e = dynamic_cast(item);\n\t\tif ( e )\n\t\t\treturn e;\n\t}\n\treturn 0;\n}\n\nvoid EdgeElement::contextMenuEvent ( QGraphicsSceneContextMenuEvent * event )\n{\n\tQMenu menu;\n\n\tQAction *addPointAction = menu.addAction(\"Add point\");\n\tQAction *delPointAction = menu.addAction(\"Remove point\");\n\tQAction *squarizeAction = menu.addAction(\"Squarize :)\");\n\n\tif ( QAction *selectedAction = menu.exec(event->screenPos()) ) {\n\t\tif ( selectedAction == delPointAction ) {\n\t\t\tint i = getPoint( event->pos() );\n\t\t\tif ( i != -1 ) {\n\t\t\t\tprepareGeometryChange();\n\t\t\t\tm_line.remove(i);\n\t\t\t\tlongPart = 0;\n\t\t\t\tupdate();\n\t\t\t}\n\t\t} else if ( selectedAction == addPointAction ) {\n\t\t\tfor ( int i = 0; i < m_line.size()-1; i++ ) {\n\t\t\t\tQPainterPath path;\n\t\t\t\tQPainterPathStroker ps;\n\t\t\t\tps.setWidth(kvadratik);\n\n\t\t\t\tpath.moveTo(m_line[i]);\n\t\t\t\tpath.lineTo(m_line[i+1]);\n\t\t\t\tif ( ps.createStroke(path).contains(event->pos()) ) {\n\t\t\t\t\tm_line.insert(i+1,event->pos());\n\t\t\t\t\tupdate();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if ( selectedAction == squarizeAction ) {\n\t\t\tprepareGeometryChange();\n\t\t\tfor ( int i = 0; i < m_line.size()-1; i++ ) {\n\t\t\t\tQLineF line(m_line[i],m_line[i+1]);\n\t\t\t\tif ( qAbs(line.dx()) < qAbs(line.dy()) ) {\n\t\t\t\t\tm_line[i+1].setX(m_line[i].x());\n\t\t\t\t} else {\n\t\t\t\t\tm_line[i+1].setY(m_line[i].y());\n\t\t\t\t}\n\t\t\t}\n\t\t\tadjustLink();\n\t\t\tupdate();\n\t\t}\n\t}\n}\n\nvoid EdgeElement::adjustLink()\n{\n\tprepareGeometryChange();\n\tif ( src )\n\t\tm_line[0] = mapFromItem(src, src->getPortPos(portFrom) );\n\tif ( dst )\n\t\tm_line[m_line.size()-1] = mapFromItem(dst, dst->getPortPos(portTo) );\n\tupdateLongestPart();\n}\n\nvoid EdgeElement::updateData()\n{\n\tif (moving)\n\t\treturn;\n\n\tElement::updateData();\n\n\tRealRepoInfo info;\n\tTypeIdType type = dataIndex.data(Unreal::TypeRole).toString();\n\n\tm_fromMult = dataIndex.data(info.roleByColumnName(type, \"fromMultiplicity\")).toString();\n\tm_toMult = dataIndex.data(info.roleByColumnName(type, \"toMultiplicity\")).toString();\n\n\tsetPos(dataIndex.data(Unreal::PositionRole).toPointF());\n\tQPolygonF newLine = dataIndex.data(Unreal::ConfigurationRole).value();\n\tif (!newLine.isEmpty())\n\t\tm_line = newLine;\n\n\tqDebug() << \"from role: \" << Unreal::krneRelationship::fromRole\n\t\t<< \"to role: \" << Unreal::krneRelationship::toRole;\n\n\tIdType uuidFrom = dataIndex.data(info.roleByColumnName(type, \"from\")).toString();\n\tIdType uuidTo = dataIndex.data(info.roleByColumnName(type, \"to\")).toString();\n\n\tqDebug() << \"from: \" << uuidFrom << \", to: \" << uuidTo;\n\n\tif (src)\n\t\tsrc->delEdge(this);\n\tif (dst)\n\t\tdst->delEdge(this);\n\n\tsrc = dynamic_cast(static_cast(scene())->getElem(uuidFrom));\n\tdst = dynamic_cast(static_cast(scene())->getElem(uuidTo));\n\n\tif (src)\n\t\tsrc->addEdge(this);\n\tif (dst)\n\t\tdst->addEdge(this);\n\n\tsetFlag(ItemIsMovable, !(dst || src));\n\n\tportFrom = dataIndex.data(info.roleByColumnName(type, \"fromPort\")).toDouble();\n\tportTo = dataIndex.data(info.roleByColumnName(type, \"toPort\")).toDouble();\n\n\tadjustLink();\n}\n<|endoftext|>"} {"text":"\/*\nResembla: Word-based Japanese similar sentence search library\nhttps:\/\/github.com\/tuem\/resembla\n\nCopyright 2017 Takashi Uemura\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#ifndef RESEMBLA_ELIMINATOR_HPP\n#define RESEMBLA_ELIMINATOR_HPP\n\n#include \n#include \n#include \n\n#include \"string_util.hpp\"\n\nnamespace resembla {\n\ntemplate\nstruct Eliminator\n{\n using size_type = typename string_type::size_type;\n using symbol_type = typename string_type::value_type;\n using distance_type = int;\n\n Eliminator(string_type const& pattern = string_type())\n {\n init(pattern);\n }\n\n void init(string_type const& pattern)\n {\n this->pattern = pattern;\n if(pattern.empty()){\n return;\n }\n\n pattern_length = pattern.size();\n block_size = ((pattern_length - 1) >> bit_offset()) + 1;\n rest_bits = pattern_length - (block_size - 1) * bit_width();\n sink = bitvector_type{1} << (rest_bits - 1);\n\n constructPM();\n zeroes.resize(block_size, 0);\n work.resize(block_size);\n }\n\n void operator()(std::vector& candidates, size_type k)\n {\n using string_distance = std::pair;\n std::vector work(candidates.size());\n size_type p = 0;\n for(const auto& c: candidates){\n work[p].first = c;\n work[p++].second = -distance(c);\n }\n std::nth_element(std::begin(work), std::begin(work) + k, std::end(work),\n [](const string_distance& a, const string_distance& b) -> bool{\n return a.second > b.second;\n });\n#ifdef DEBUG\n std::cerr << \"narrow \" << work.size() << \" strings\" << std::endl;\n for(const auto& i: work){\n std::cerr << cast_string(i.first) << \": \" << i.second << std::endl;\n }\n#endif\n for(size_type i = 0; i < k; ++i){\n candidates[i] = work.at(i).first;\n }\n candidates.erase(std::begin(candidates) + k, std::end(candidates));\n }\n\nprotected:\n string_type pattern;\n size_type pattern_length;\n size_type block_size;\n size_type rest_bits;\n bitvector_type sink;\n\n std::vector> PM_sp;\n std::vector>> PM;\n std::vector zeroes;\n\n struct WorkData\n {\n bitvector_type D0;\n bitvector_type HP;\n bitvector_type HN;\n bitvector_type VP;\n bitvector_type VN;\n\n void reset()\n {\n D0 = HP = HN = VN = 0;\n VP = ~(bitvector_type{0});\n }\n };\n mutable std::vector work;\n\n template static constexpr int bit_width()\n {\n return 8 * sizeof(Integer);\n }\n\n static constexpr int bit_offset(int w)\n {\n return w < 2 ? 0 : (bit_offset(w >> 1) + 1);\n }\n\n template static constexpr int bit_offset()\n {\n return bit_offset(bit_width());\n }\n\n template\n const value_type& find_value(const std::vector>& data,\n const key_type c, const value_type& default_value) const\n {\n if(data.size() < 9){\n for(const auto& p: data){\n if(p.first == c){\n return p.second;\n }\n }\n }\n else{\n size_type l = 0, r = data.size();\n while(l < r){\n auto i = (l + r) \/ 2;\n auto& p = data[i];\n if(p.first < c){\n l = i + 1;\n }\n else if(p.first > c){\n r = i;\n }\n else{\n return p.second;\n }\n }\n }\n return default_value;\n }\n\n void constructPM()\n {\n std::map> PM_work;\n for(size_type i = 0; i < block_size - 1; ++i){\n for(size_type j = 0; j < bit_width(); ++j){\n if(PM_work[pattern[i * bit_width() + j]].empty()){\n PM_work[pattern[i * bit_width() + j]].resize(block_size, 0);\n }\n PM_work[pattern[i * bit_width() + j]][i] |= bitvector_type{1} << j;\n }\n }\n for(size_type i = 0; i < rest_bits; ++i){\n if(PM_work[pattern[(block_size - 1) * bit_width() + i]].empty()){\n PM_work[pattern[(block_size - 1) * bit_width() + i]].resize(block_size, 0);\n }\n PM_work[pattern[(block_size - 1) * bit_width() + i]].back() |= bitvector_type{1} << i;\n }\n\n PM.clear();\n for(const auto& p: PM_work){\n PM.push_back(p);\n }\n }\n\n distance_type distance_sp(string_type const &text) const\n {\n auto& w = work.front();\n w.reset();\n for(size_type i = 0; i < pattern_length; ++i){\n w.VP |= bitvector_type{1} << i;\n }\n\n distance_type D = pattern_length;\n for(auto c: text){\n auto X = find_value(PM, c, zeroes).front() | w.VN;\n\n w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X;\n w.HP = w.VN | ~(w.VP | w.D0);\n w.HN = w.VP & w.D0;\n\n X = (w.HP << 1) | 1;\n w.VP = (w.HN << 1) | ~(X | w.D0);\n w.VN = X & w.D0;\n\n if(w.HP & sink){\n ++D;\n }\n else if(w.HN & sink){\n --D;\n }\n }\n return D;\n }\n\n distance_type distance_lp(string_type const &text) const\n {\n constexpr bitvector_type msb = bitvector_type{1} << (bit_width() - 1);\n for(size_type i = 0; i < block_size; ++i){\n work[i].reset();\n }\n for(size_type i = 0; i < rest_bits; ++i){\n work.back().VP |= bitvector_type{1} << i;\n }\n\n distance_type D = pattern_length;\n for(auto c: text){\n const auto& PMc = find_value(PM, c, zeroes);\n for(size_type r = 0; r < block_size; ++r){\n auto& w = work[r];\n auto X = PMc[r];\n if(r > 0 && (work[r - 1].HN & msb)){\n X |= 1;\n }\n\n w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X | w.VN;\n w.HP = w.VN | ~(w.VP | w.D0);\n w.HN = w.VP & w.D0;\n\n X = w.HP << 1;\n if(r == 0 || work[r - 1].HP & msb){\n X |= 1;\n }\n w.VP = (w.HN << 1) | ~(X | w.D0);\n if(r > 0 && (work[r - 1].HN & msb)){\n w.VP |= 1;\n }\n w.VN = X & w.D0;\n }\n\n if(work.back().HP & sink){\n ++D;\n }\n else if(work.back().HN & sink){\n --D;\n }\n }\n return D;\n }\n\n distance_type distance(string_type const &text) const\n {\n if(text.empty()){\n return pattern_length;\n }\n else if(pattern_length == 0){\n return text.size();\n }\n\n if(block_size == 1){\n return distance_sp(text);\n }\n else{\n return distance_lp(text);\n }\n }\n};\n\n}\n#endif\nreduce copying\/*\nResembla: Word-based Japanese similar sentence search library\nhttps:\/\/github.com\/tuem\/resembla\n\nCopyright 2017 Takashi Uemura\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#ifndef RESEMBLA_ELIMINATOR_HPP\n#define RESEMBLA_ELIMINATOR_HPP\n\n#include \n#include \n#include \n\n#include \"string_util.hpp\"\n\nnamespace resembla {\n\ntemplate\nstruct Eliminator\n{\n using size_type = typename string_type::size_type;\n using symbol_type = typename string_type::value_type;\n using distance_type = int;\n\n Eliminator(string_type const& pattern = string_type())\n {\n init(pattern);\n }\n\n void init(string_type const& pattern)\n {\n this->pattern = pattern;\n if(pattern.empty()){\n return;\n }\n\n pattern_length = pattern.size();\n block_size = ((pattern_length - 1) >> bit_offset()) + 1;\n rest_bits = pattern_length - (block_size - 1) * bit_width();\n sink = bitvector_type{1} << (rest_bits - 1);\n\n constructPM();\n zeroes.resize(block_size, 0);\n work.resize(block_size);\n }\n\n void operator()(std::vector& candidates, size_type k)\n {\n using index_distance = std::pair;\n\n std::vector work(candidates.size());\n for(size_type i = 0; i < work.size(); ++i){\n work[i].first = i;\n work[i].second = -distance(candidates[i]);\n }\n\n \/\/ sort partially to obtain top-k elements\n std::nth_element(std::begin(work), std::begin(work) + k, std::end(work),\n [](const index_distance& a, const index_distance& b) -> bool{\n return a.second > b.second;\n });\n\n \/\/ ensure that work[i].first < work[j].first if i < j < k\n std::partial_sort(std::begin(work), std::begin(work) + k, std::begin(work) + k,\n [](const index_distance& a, const index_distance& b) -> bool{\n return a.first < b.first;\n });\n#ifdef DEBUG\n std::cerr << \"narrow \" << work.size() << \" strings\" << std::endl;\n for(size_type i = 0; i < k; ++i){\n std::cerr << cast_string(candidates[work[i].first]) << \": \" << work[i].second << std::endl;\n }\n#endif\n\n \/\/ sort original list\n for(size_type i = 0; i < k; ++i){\n std::swap(candidates[i], candidates[work[i].first]);\n }\n candidates.erase(std::begin(candidates) + k, std::end(candidates));\n }\n\nprotected:\n string_type pattern;\n size_type pattern_length;\n size_type block_size;\n size_type rest_bits;\n bitvector_type sink;\n\n std::vector> PM_sp;\n std::vector>> PM;\n std::vector zeroes;\n\n struct WorkData\n {\n bitvector_type D0;\n bitvector_type HP;\n bitvector_type HN;\n bitvector_type VP;\n bitvector_type VN;\n\n void reset()\n {\n D0 = HP = HN = VN = 0;\n VP = ~(bitvector_type{0});\n }\n };\n mutable std::vector work;\n\n template static constexpr int bit_width()\n {\n return 8 * sizeof(Integer);\n }\n\n static constexpr int bit_offset(int w)\n {\n return w < 2 ? 0 : (bit_offset(w >> 1) + 1);\n }\n\n template static constexpr int bit_offset()\n {\n return bit_offset(bit_width());\n }\n\n template\n const value_type& find_value(const std::vector>& data,\n const key_type c, const value_type& default_value) const\n {\n if(data.size() < 9){\n for(const auto& p: data){\n if(p.first == c){\n return p.second;\n }\n }\n }\n else{\n size_type l = 0, r = data.size();\n while(l < r){\n auto i = (l + r) \/ 2;\n auto& p = data[i];\n if(p.first < c){\n l = i + 1;\n }\n else if(p.first > c){\n r = i;\n }\n else{\n return p.second;\n }\n }\n }\n return default_value;\n }\n\n void constructPM()\n {\n std::map> PM_work;\n for(size_type i = 0; i < block_size - 1; ++i){\n for(size_type j = 0; j < bit_width(); ++j){\n if(PM_work[pattern[i * bit_width() + j]].empty()){\n PM_work[pattern[i * bit_width() + j]].resize(block_size, 0);\n }\n PM_work[pattern[i * bit_width() + j]][i] |= bitvector_type{1} << j;\n }\n }\n for(size_type i = 0; i < rest_bits; ++i){\n if(PM_work[pattern[(block_size - 1) * bit_width() + i]].empty()){\n PM_work[pattern[(block_size - 1) * bit_width() + i]].resize(block_size, 0);\n }\n PM_work[pattern[(block_size - 1) * bit_width() + i]].back() |= bitvector_type{1} << i;\n }\n\n PM.clear();\n for(const auto& p: PM_work){\n PM.push_back(p);\n }\n }\n\n distance_type distance_sp(string_type const &text) const\n {\n auto& w = work.front();\n w.reset();\n for(size_type i = 0; i < pattern_length; ++i){\n w.VP |= bitvector_type{1} << i;\n }\n\n distance_type D = pattern_length;\n for(auto c: text){\n auto X = find_value(PM, c, zeroes).front() | w.VN;\n\n w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X;\n w.HP = w.VN | ~(w.VP | w.D0);\n w.HN = w.VP & w.D0;\n\n X = (w.HP << 1) | 1;\n w.VP = (w.HN << 1) | ~(X | w.D0);\n w.VN = X & w.D0;\n\n if(w.HP & sink){\n ++D;\n }\n else if(w.HN & sink){\n --D;\n }\n }\n return D;\n }\n\n distance_type distance_lp(string_type const &text) const\n {\n constexpr bitvector_type msb = bitvector_type{1} << (bit_width() - 1);\n\n for(auto& w: work){\n w.reset();\n }\n for(size_type i = 0; i < rest_bits; ++i){\n work.back().VP |= bitvector_type{1} << i;\n }\n\n distance_type D = pattern_length;\n for(auto c: text){\n const auto& PMc = find_value(PM, c, zeroes);\n for(size_type r = 0; r < block_size; ++r){\n auto& w = work[r];\n auto X = PMc[r];\n if(r > 0 && (work[r - 1].HN & msb)){\n X |= 1;\n }\n\n w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X | w.VN;\n w.HP = w.VN | ~(w.VP | w.D0);\n w.HN = w.VP & w.D0;\n\n X = w.HP << 1;\n if(r == 0 || work[r - 1].HP & msb){\n X |= 1;\n }\n w.VP = (w.HN << 1) | ~(X | w.D0);\n if(r > 0 && (work[r - 1].HN & msb)){\n w.VP |= 1;\n }\n w.VN = X & w.D0;\n }\n\n if(work.back().HP & sink){\n ++D;\n }\n else if(work.back().HN & sink){\n --D;\n }\n }\n return D;\n }\n\n distance_type distance(string_type const &text) const\n {\n if(text.empty()){\n return pattern_length;\n }\n else if(pattern_length == 0){\n return text.size();\n }\n\n if(block_size == 1){\n return distance_sp(text);\n }\n else{\n return distance_lp(text);\n }\n }\n};\n\n}\n#endif\n<|endoftext|>"} {"text":"\/*\n * pHashTest.cpp\n *\n * Created on: 25 Jul 2013\n * Author: nicholas\n *\/\n\n#include \n#include \n#include \"..\/..\/include\/hash\/ImagePHash.hpp\"\n#include \n\n\nusing namespace Magick;\n\nTEST(ImagePHashTest, hashImage) {\n\tImagePHash iph;\n\tlong pHash = iph.getLongHash(\"src\/test\/hash\/testImage.jpg\");\n\tASSERT_EQ(7655956633439617023,pHash);\n}\n\nint main(int argc, char **argv) {\n\t BasicConfigurator config;\n\t config.configure();\n::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n\n\nChanged ImagePHash test for higher resolution (from 49 bit to 64 bit)\/*\n * pHashTest.cpp\n *\n * Created on: 25 Jul 2013\n * Author: nicholas\n *\/\n\n#include \n#include \n#include \"..\/..\/include\/hash\/ImagePHash.hpp\"\n#include \n\n\nusing namespace Magick;\n\nTEST(ImagePHashTest, hashImage) {\n\tImagePHash iph(32,9);\n\tlong pHash = iph.getLongHash(\"src\/test\/hash\/testImage.jpg\");\n\tASSERT_EQ(-2059292927385518081,pHash);\n}\n\nint main(int argc, char **argv) {\n\t BasicConfigurator config;\n\t config.configure();\n::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n\n\n<|endoftext|>"} {"text":"\/**\n * @file inverted_index_test.cpp\n * @author Sean Massung\n *\/\n\n#include \"test\/inverted_index_test.h\"\n\nnamespace meta\n{\nnamespace testing\n{\n\nvoid create_config(const std::string& corpus_type)\n{\n auto orig_config = cpptoml::parse_file(\"config.toml\");\n std::string config_filename{\"test-config.toml\"};\n std::ofstream config_file{config_filename};\n\n auto stop_words = orig_config.get_as(\"stop-words\");\n if(!stop_words)\n throw std::runtime_error{\"\\\"stop-words\\\" not in config\"};\n\n auto libsvm_modules = orig_config.get_as(\"libsvm-modules\");\n if(!libsvm_modules)\n throw std::runtime_error{\"\\\"libsvm-modules\\\" not in config\"};\n\n auto query_judgements = orig_config.get_as(\"query-judgements\");\n if(!query_judgements)\n throw std::runtime_error{\"\\\"query-judgements\\\" not in config\"};\n\n auto punctuation = orig_config.get_as(\"punctuation\");\n if (!punctuation)\n throw std::runtime_error{\"\\\"punctuation\\\" not in config\"};\n\n auto start_exeptions = orig_config.get_as(\"start-exceptions\");\n if (!start_exeptions)\n throw std::runtime_error{\"\\\"start-exceptions\\\" not in config\"};\n\n auto end_exceptions = orig_config.get_as(\"end-exceptions\");\n if (!end_exceptions)\n throw std::runtime_error{\"\\\"end-exceptions\\\" not in config\"};\n\n config_file << \"stop-words = \\\"\" << *stop_words\n << \"\\\"\\n\"\n << \"punctuation = \\\"\" << *punctuation << \"\\\"\\n\"\n << \"start-exceptions = \\\"\" << *start_exeptions << \"\\\"\\n\"\n << \"end-exceptions = \\\"\" << *end_exceptions << \"\\\"\\n\"\n << \"prefix = \\\"\" << *orig_config.get_as(\"prefix\")\n << \"\\\"\\n\"\n << \"query-judgements = \\\"\" << *query_judgements\n << \"\\\"\\n\"\n << \"libsvm-modules = \\\"\" << *libsvm_modules\n << \"\\\"\\n\"\n << \"corpus-type = \\\"\" << corpus_type << \"-corpus\\\"\\n\"\n << \"list= \\\"ceeaus\\\"\\n\"\n << \"dataset = \\\"ceeaus\\\"\\n\"\n << \"encoding = \\\"shift_jis\\\"\\n\"\n << \"forward-index = \\\"ceeaus-fwd\\\"\\n\"\n << \"inverted-index = \\\"ceeaus-inv\\\"\\n\"\n << \"[[analyzers]]\\n\"\n << \"method = \\\"ngram-word\\\"\\n\"\n << \"ngram = 1\\n\"\n << \"filter = \\\"default-chain\\\"\";\n}\n\ntemplate \nvoid check_ceeaus_expected(Index& idx)\n{\n double epsilon = 0.000001;\n ASSERT_EQUAL(idx.num_docs(), 1008);\n ASSERT_LESS(std::abs(idx.avg_doc_length() - 128.556), epsilon);\n ASSERT_EQUAL(idx.unique_terms(), 3944);\n\n std::ifstream in{\"..\/data\/ceeaus-metadata.txt\"};\n uint64_t size;\n uint64_t unique;\n doc_id id{0};\n while (in >> size >> unique)\n {\n ASSERT_EQUAL(idx.doc_size(id), size);\n ASSERT_EQUAL(idx.unique_terms(id), unique);\n ++id;\n }\n\n \/\/ make sure there's exactly the correct amount\n ASSERT_EQUAL(id, idx.num_docs());\n}\n\ntemplate \nvoid check_term_id(Index& idx)\n{\n term_id t_id = idx.get_term_id(\"japanes\");\n ASSERT_EQUAL(idx.doc_freq(t_id), 69);\n\n term_id first;\n double second;\n std::ifstream in{\"..\/data\/ceeaus-term-count.txt\"};\n auto pdata = idx.search_primary(t_id);\n for (auto& count : pdata->counts())\n {\n in >> first;\n in >> second;\n ASSERT_EQUAL(first, count.first);\n ASSERT_APPROX_EQUAL(second, count.second);\n }\n}\n\nint inverted_index_tests()\n{\n create_config(\"file\");\n\n int num_failed = 0;\n num_failed += testing::run_test(\"inverted-index-build-file-corpus\", [&]()\n {\n system(\"rm -rf ceeaus-inv\");\n auto idx =\n index::make_index(\n \"test-config.toml\", uint32_t{10000});\n check_ceeaus_expected(*idx);\n });\n\n num_failed += testing::run_test(\"inverted-index-read-file-corpus\", [&]()\n {\n auto idx =\n index::make_index(\n \"test-config.toml\", uint32_t{10000});\n check_ceeaus_expected(*idx);\n check_term_id(*idx);\n system(\"rm -rf ceeaus-inv test-config.toml\");\n });\n\n create_config(\"line\");\n system(\"rm -rf ceeaus-inv\");\n\n num_failed += testing::run_test(\"inverted-index-build-line-corpus\", [&]()\n {\n auto idx =\n index::make_index(\n \"test-config.toml\", uint32_t{10000});\n check_ceeaus_expected(*idx);\n });\n\n num_failed += testing::run_test(\"inverted-index-read-line-corpus\", [&]()\n {\n auto idx =\n index::make_index(\n \"test-config.toml\", uint32_t{10000});\n check_ceeaus_expected(*idx);\n check_term_id(*idx);\n check_term_id(*idx); \/\/ twice to check splay_caching\n });\n\n \/\/ test different caches\n\n num_failed += testing::run_test(\"inverted-index-dblru-cache\", [&]()\n {\n auto idx = index::make_index(\n \"test-config.toml\", uint64_t{1000});\n check_term_id(*idx);\n check_term_id(*idx);\n });\n\n num_failed += testing::run_test(\"inverted-index-no-evict-cache\", [&]()\n {\n auto idx =\n index::make_index(\n \"test-config.toml\");\n check_term_id(*idx);\n check_term_id(*idx);\n });\n\n num_failed += testing::run_test(\"inverted-index-shard-cache\", [&]()\n {\n auto idx = index::make_index(\n \"test-config.toml\", uint8_t{8});\n check_term_id(*idx);\n check_term_id(*idx);\n });\n\n system(\"rm -rf ceeaus-inv test-config.toml\");\n return num_failed;\n}\n}\n}\nfix error masked by wrong call to integer abs (should have been std::abs)\/**\n * @file inverted_index_test.cpp\n * @author Sean Massung\n *\/\n\n#include \"test\/inverted_index_test.h\"\n\nnamespace meta\n{\nnamespace testing\n{\n\nvoid create_config(const std::string& corpus_type)\n{\n auto orig_config = cpptoml::parse_file(\"config.toml\");\n std::string config_filename{\"test-config.toml\"};\n std::ofstream config_file{config_filename};\n\n auto stop_words = orig_config.get_as(\"stop-words\");\n if(!stop_words)\n throw std::runtime_error{\"\\\"stop-words\\\" not in config\"};\n\n auto libsvm_modules = orig_config.get_as(\"libsvm-modules\");\n if(!libsvm_modules)\n throw std::runtime_error{\"\\\"libsvm-modules\\\" not in config\"};\n\n auto query_judgements = orig_config.get_as(\"query-judgements\");\n if(!query_judgements)\n throw std::runtime_error{\"\\\"query-judgements\\\" not in config\"};\n\n auto punctuation = orig_config.get_as(\"punctuation\");\n if (!punctuation)\n throw std::runtime_error{\"\\\"punctuation\\\" not in config\"};\n\n auto start_exeptions = orig_config.get_as(\"start-exceptions\");\n if (!start_exeptions)\n throw std::runtime_error{\"\\\"start-exceptions\\\" not in config\"};\n\n auto end_exceptions = orig_config.get_as(\"end-exceptions\");\n if (!end_exceptions)\n throw std::runtime_error{\"\\\"end-exceptions\\\" not in config\"};\n\n config_file << \"stop-words = \\\"\" << *stop_words\n << \"\\\"\\n\"\n << \"punctuation = \\\"\" << *punctuation << \"\\\"\\n\"\n << \"start-exceptions = \\\"\" << *start_exeptions << \"\\\"\\n\"\n << \"end-exceptions = \\\"\" << *end_exceptions << \"\\\"\\n\"\n << \"prefix = \\\"\" << *orig_config.get_as(\"prefix\")\n << \"\\\"\\n\"\n << \"query-judgements = \\\"\" << *query_judgements\n << \"\\\"\\n\"\n << \"libsvm-modules = \\\"\" << *libsvm_modules\n << \"\\\"\\n\"\n << \"corpus-type = \\\"\" << corpus_type << \"-corpus\\\"\\n\"\n << \"list= \\\"ceeaus\\\"\\n\"\n << \"dataset = \\\"ceeaus\\\"\\n\"\n << \"encoding = \\\"shift_jis\\\"\\n\"\n << \"forward-index = \\\"ceeaus-fwd\\\"\\n\"\n << \"inverted-index = \\\"ceeaus-inv\\\"\\n\"\n << \"[[analyzers]]\\n\"\n << \"method = \\\"ngram-word\\\"\\n\"\n << \"ngram = 1\\n\"\n << \"filter = \\\"default-chain\\\"\";\n}\n\ntemplate \nvoid check_ceeaus_expected(Index& idx)\n{\n double epsilon = 0.000001;\n ASSERT_EQUAL(idx.num_docs(), 1008);\n ASSERT_LESS(std::abs(idx.avg_doc_length() - 128.236), epsilon);\n ASSERT_EQUAL(idx.unique_terms(), 3944);\n\n std::ifstream in{\"..\/data\/ceeaus-metadata.txt\"};\n uint64_t size;\n uint64_t unique;\n doc_id id{0};\n while (in >> size >> unique)\n {\n ASSERT_EQUAL(idx.doc_size(id), size);\n ASSERT_EQUAL(idx.unique_terms(id), unique);\n ++id;\n }\n\n \/\/ make sure there's exactly the correct amount\n ASSERT_EQUAL(id, idx.num_docs());\n}\n\ntemplate \nvoid check_term_id(Index& idx)\n{\n term_id t_id = idx.get_term_id(\"japanes\");\n ASSERT_EQUAL(idx.doc_freq(t_id), 69);\n\n term_id first;\n double second;\n std::ifstream in{\"..\/data\/ceeaus-term-count.txt\"};\n auto pdata = idx.search_primary(t_id);\n for (auto& count : pdata->counts())\n {\n in >> first;\n in >> second;\n ASSERT_EQUAL(first, count.first);\n ASSERT_APPROX_EQUAL(second, count.second);\n }\n}\n\nint inverted_index_tests()\n{\n create_config(\"file\");\n\n int num_failed = 0;\n num_failed += testing::run_test(\"inverted-index-build-file-corpus\", [&]()\n {\n system(\"rm -rf ceeaus-inv\");\n auto idx =\n index::make_index(\n \"test-config.toml\", uint32_t{10000});\n check_ceeaus_expected(*idx);\n });\n\n num_failed += testing::run_test(\"inverted-index-read-file-corpus\", [&]()\n {\n auto idx =\n index::make_index(\n \"test-config.toml\", uint32_t{10000});\n check_ceeaus_expected(*idx);\n check_term_id(*idx);\n system(\"rm -rf ceeaus-inv test-config.toml\");\n });\n\n create_config(\"line\");\n system(\"rm -rf ceeaus-inv\");\n\n num_failed += testing::run_test(\"inverted-index-build-line-corpus\", [&]()\n {\n auto idx =\n index::make_index(\n \"test-config.toml\", uint32_t{10000});\n check_ceeaus_expected(*idx);\n });\n\n num_failed += testing::run_test(\"inverted-index-read-line-corpus\", [&]()\n {\n auto idx =\n index::make_index(\n \"test-config.toml\", uint32_t{10000});\n check_ceeaus_expected(*idx);\n check_term_id(*idx);\n check_term_id(*idx); \/\/ twice to check splay_caching\n });\n\n \/\/ test different caches\n\n num_failed += testing::run_test(\"inverted-index-dblru-cache\", [&]()\n {\n auto idx = index::make_index(\n \"test-config.toml\", uint64_t{1000});\n check_term_id(*idx);\n check_term_id(*idx);\n });\n\n num_failed += testing::run_test(\"inverted-index-no-evict-cache\", [&]()\n {\n auto idx =\n index::make_index(\n \"test-config.toml\");\n check_term_id(*idx);\n check_term_id(*idx);\n });\n\n num_failed += testing::run_test(\"inverted-index-shard-cache\", [&]()\n {\n auto idx = index::make_index(\n \"test-config.toml\", uint8_t{8});\n check_term_id(*idx);\n check_term_id(*idx);\n });\n\n system(\"rm -rf ceeaus-inv test-config.toml\");\n return num_failed;\n}\n}\n}\n<|endoftext|>"} {"text":"\/\/ $Id$\n\/\/\n\/\/ Copyright (C) 2002-2008 Greg Landrum and Rational Discovery LLC\n\/\/ All Rights Reserved\n\/\/\n#ifdef WIN32\n#define CALGORITHMS_EXPORTS\n#endif\n#define PYTH_FILE_WITH_INIT\n#include \"Clustering.h\"\n#include \n\n#ifdef WIN32\nBOOL APIENTRY DllMain( HANDLE hModule, \n DWORD ul_reason_for_call, \n LPVOID lpReserved\n\t\t\t\t\t )\n{\n switch (ul_reason_for_call)\n\t{\n\t\tcase DLL_PROCESS_ATTACH:\n\t\tcase DLL_THREAD_ATTACH:\n\t\tcase DLL_THREAD_DETACH:\n\t\tcase DLL_PROCESS_DETACH:\n\t\t\tbreak;\n }\n return TRUE;\n}\n#endif\n\ntypedef double real;\n\n\n\nextern \"C\"\nvoid distdriver_(long int *n,long int *len,\n\t\t real *dists,\n\t\t long int *toggle,\n\t\t long int *ia,long int *ib,real *crit);\n\n\/\/\n\/\/ Rather than deal with any nonsense like trying to get\n\/\/ the distance matrix built properly on the f2c side of things\n\/\/ (thus drowning in the waves of f2c hate), we'll generate\n\/\/ the distance matrix on our own here and then call distdriver_\n\/\/\nvoid clusterit(real *dataP,long int n,long int m,long int iopt,\n\t long int *ia,long int *ib,real *crit){\n real *dists;\n long int len;\n long int pos = 0;\n long int i,j,k,iTab,jTab;\n double tmp;\n\n len = (n*(n-1))\/2;\n dists = (real *)calloc(len,sizeof(real));\n for(i=1;idata,nPts,sz,option,ia,ib,crit);\n\n dims[0] = nPts;\n res = PyTuple_New(3);\n\n \/\/ NOTE: these operations maintain pointers to the respective arrays,\n \/\/ that's why it's ok that we do not free them in this function,\n \/\/ Python will take care of it for us.\n \/\/\n tmp = PyArray_SimpleNewFromData(1,dims,NPY_LONG,(void *)ia);\n PyTuple_SetItem(res,0,(PyObject *)tmp);\n\n tmp = PyArray_SimpleNewFromData(1,dims,NPY_LONG,(void *)ib);\n PyTuple_SetItem(res,1,(PyObject *)tmp);\n\n tmp = PyArray_SimpleNewFromData(1,dims,NPY_DOUBLE,(void *)crit);\n PyTuple_SetItem(res,2,(PyObject *)tmp);\n\n Py_DECREF(dataContig);\n return res;\n};\n\n\n\nvoid distclusterit(real *dists,long int n,long int iopt,\n\t\t long int *ia,long int *ib,real *crit){\n long int len;\n\n len = (n*(n-1))\/2;\n distdriver_(&n,&len,dists,&iopt,ia,ib,crit);\n};\n\n\nstatic PyObject *\nClustering_MurtaghDistCluster(PyObject *self,PyObject *args)\n{\n PyArrayObject *dataContig;\n PyObject *data;\n long int nPts,option;\n long int *ia,*ib;\n real *crit;\n PyObject *res=PyTuple_New(3);\n PyObject *tmp;\n npy_intp dims[] = {1};\n\n if(!PyArg_ParseTuple(args,\"Oii\",&data,&nPts,&option))\n return NULL;\n\n dataContig = (PyArrayObject *)PyArray_ContiguousFromObject(data,PyArray_DOUBLE,1,1);\n ia = (long int *)calloc(nPts,sizeof(long int));\n ib = (long int *)calloc(nPts,sizeof(long int));\n crit = (real *)calloc(nPts,sizeof(real));\n distclusterit((real *)dataContig->data,nPts,option,ia,ib,crit);\n\n dims[0] = nPts;\n\n \/\/\n \/\/ NOTE: these operations maintain pointers to the respective arrays,\n \/\/ that's why it's ok that we do not free them in this function,\n \/\/ Python will take care of it for us.\n \/\/\n tmp = PyArray_SimpleNewFromData(1,dims,NPY_LONG,(void *)ia);\n PyTuple_SetItem(res,0,tmp);\n\n tmp = PyArray_SimpleNewFromData(1,dims,NPY_LONG,(void *)ib);\n PyTuple_SetItem(res,1,tmp);\n\n tmp = PyArray_SimpleNewFromData(1,dims,NPY_DOUBLE,(void *)crit);\n PyTuple_SetItem(res,2,tmp);\n \n Py_DECREF(dataContig);\n return res;\n};\n\nstatic PyMethodDef locMethods[] = {\n {\"MurtaghCluster\",Clustering_MurtaghCluster,METH_VARARGS},\n {\"MurtaghDistCluster\",Clustering_MurtaghDistCluster,METH_VARARGS},\n {NULL,NULL}\n};\n\nCALGORITHMS_API void initClustering()\n{\n (void) Py_InitModule(\"Clustering\",locMethods);\n#ifndef NO_IMPORT_ARRAY\n import_array();\n#endif\n}\n\nfix argument parsing problem on snow leopard\/\/ $Id$\n\/\/\n\/\/ Copyright (C) 2002-2010 Greg Landrum and Rational Discovery LLC\n\/\/ All Rights Reserved\n\/\/\n#ifdef WIN32\n#define CALGORITHMS_EXPORTS\n#endif\n#define PYTH_FILE_WITH_INIT\n#include \"Clustering.h\"\n#include \n#include \n#include \n\n#ifdef WIN32\nBOOL APIENTRY DllMain( HANDLE hModule, \n DWORD ul_reason_for_call, \n LPVOID lpReserved\n\t\t\t\t\t )\n{\n switch (ul_reason_for_call)\n\t{\n\t\tcase DLL_PROCESS_ATTACH:\n\t\tcase DLL_THREAD_ATTACH:\n\t\tcase DLL_THREAD_DETACH:\n\t\tcase DLL_PROCESS_DETACH:\n\t\t\tbreak;\n }\n return TRUE;\n}\n#endif\n\ntypedef double real;\n\n\n\nextern \"C\"\nvoid distdriver_(boost::int64_t *n,boost::int64_t *len,\n\t\t real *dists,\n\t\t boost::int64_t *toggle,\n\t\t boost::int64_t *ia,boost::int64_t *ib,real *crit);\n\n\/\/\n\/\/ Rather than deal with any nonsense like trying to get\n\/\/ the distance matrix built properly on the f2c side of things\n\/\/ (thus drowning in the waves of f2c hate), we'll generate\n\/\/ the distance matrix on our own here and then call distdriver_\n\/\/\nvoid clusterit(real *dataP,boost::int64_t n,boost::int64_t m,boost::int64_t iopt,\n\t boost::int64_t *ia,boost::int64_t *ib,real *crit){\n real *dists;\n boost::int64_t len;\n boost::int64_t pos = 0;\n boost::int64_t i,j,k,iTab,jTab;\n double tmp;\n len = (n*(n-1))\/2;\n dists = (real *)calloc(len,sizeof(real));\n for(i=1;idata,nPts,sz,option,ia,ib,crit);\n\n dims[0] = nPts;\n res = PyTuple_New(3);\n\n \/\/ NOTE: these operations maintain pointers to the respective arrays,\n \/\/ that's why it's ok that we do not free them in this function,\n \/\/ Python will take care of it for us.\n \/\/\n tmp = PyArray_SimpleNewFromData(1,dims,NPY_LONG,(void *)ia);\n PyTuple_SetItem(res,0,(PyObject *)tmp);\n\n tmp = PyArray_SimpleNewFromData(1,dims,NPY_LONG,(void *)ib);\n PyTuple_SetItem(res,1,(PyObject *)tmp);\n\n tmp = PyArray_SimpleNewFromData(1,dims,NPY_DOUBLE,(void *)crit);\n PyTuple_SetItem(res,2,(PyObject *)tmp);\n\n Py_DECREF(dataContig);\n return res;\n};\n\n\n\nvoid distclusterit(real *dists,boost::int64_t n,boost::int64_t iopt,\n\t\t boost::int64_t *ia,boost::int64_t *ib,real *crit){\n boost::int64_t len;\n\n len = (n*(n-1))\/2;\n distdriver_(&n,&len,dists,&iopt,ia,ib,crit);\n};\n\n\nstatic PyObject *\nClustering_MurtaghDistCluster(PyObject *self,PyObject *args)\n{\n PyArrayObject *dataContig;\n PyObject *data;\n int nPts,option;\n boost::int64_t *ia,*ib;\n real *crit;\n PyObject *res=PyTuple_New(3);\n PyObject *tmp;\n npy_intp dims[] = {1};\n\n if(!PyArg_ParseTuple(args,\"Oii\",&data,&nPts,&option))\n return NULL;\n\n dataContig = (PyArrayObject *)PyArray_ContiguousFromObject(data,PyArray_DOUBLE,1,1);\n ia = (boost::int64_t *)calloc(nPts,sizeof(boost::int64_t));\n ib = (boost::int64_t *)calloc(nPts,sizeof(boost::int64_t));\n crit = (real *)calloc(nPts,sizeof(real));\n distclusterit((real *)dataContig->data,nPts,option,ia,ib,crit);\n\n dims[0] = nPts;\n\n \/\/\n \/\/ NOTE: these operations maintain pointers to the respective arrays,\n \/\/ that's why it's ok that we do not free them in this function,\n \/\/ Python will take care of it for us.\n \/\/\n tmp = PyArray_SimpleNewFromData(1,dims,NPY_LONG,(void *)ia);\n PyTuple_SetItem(res,0,tmp);\n\n tmp = PyArray_SimpleNewFromData(1,dims,NPY_LONG,(void *)ib);\n PyTuple_SetItem(res,1,tmp);\n\n tmp = PyArray_SimpleNewFromData(1,dims,NPY_DOUBLE,(void *)crit);\n PyTuple_SetItem(res,2,tmp);\n \n Py_DECREF(dataContig);\n return res;\n};\n\nstatic PyMethodDef locMethods[] = {\n {\"MurtaghCluster\",Clustering_MurtaghCluster,METH_VARARGS},\n {\"MurtaghDistCluster\",Clustering_MurtaghDistCluster,METH_VARARGS},\n {NULL,NULL}\n};\n\nCALGORITHMS_API void initClustering()\n{\n (void) Py_InitModule(\"Clustering\",locMethods);\n#ifndef NO_IMPORT_ARRAY\n import_array();\n#endif\n}\n\n<|endoftext|>"} {"text":"#ifndef SILICIUM_ERROR_OR_HPP\n#define SILICIUM_ERROR_OR_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace Si\n{\n\tinline SILICIUM_NORETURN void throw_error(boost::system::error_code error)\n\t{\n\t\tboost::throw_exception(boost::system::system_error(error));\n\t}\n\n\tinline SILICIUM_NORETURN void throw_error(std::error_code error)\n\t{\n\t\tboost::throw_exception(std::system_error(error));\n\t}\n\n\ttemplate \n\tstruct error_or\n\t{\n\t\terror_or() BOOST_NOEXCEPT\n\t\t\t: value(Value()) \/\/initialize so that reading the value does not have undefined behaviour\n\t\t{\n\t\t}\n\n\t\ttemplate ::value, void>::type>\n\t\terror_or(ConvertibleToValue &&value) BOOST_NOEXCEPT\n\t\t\t: value(std::forward(value))\n\t\t{\n\t\t}\n\n\t\terror_or(Error error) BOOST_NOEXCEPT\n\t\t\t: error_(std::move(error))\n\t\t{\n\t\t}\n\n#ifdef _MSC_VER\n\t\terror_or(error_or &&other) BOOST_NOEXCEPT\n\t\t\t: error_(std::move(other.error_))\n\t\t\t, value(std::move(other.value))\n\t\t{\n\t\t}\n\n\t\terror_or(error_or const &other)\n\t\t\t: error_(other.error_)\n\t\t\t, value(other.value)\n\t\t{\n\t\t}\n\n\t\terror_or &operator = (error_or &&other) BOOST_NOEXCEPT\n\t\t{\n\t\t\terror_ = std::move(other.error_);\n\t\t\tvalue = std::move(other.value);\n\t\t\treturn *this;\n\t\t}\n\n\t\terror_or &operator = (error_or const &other)\n\t\t{\n\t\t\terror_ = other.error_;\n\t\t\tvalue = other.value;\n\t\t\treturn *this;\n\t\t}\n#endif\n\n\t\tbool is_error() const BOOST_NOEXCEPT\n\t\t{\n\t\t\treturn !!error_;\n\t\t}\n\n\t\tSi::optional error() const BOOST_NOEXCEPT\n\t\t{\n\t\t\tif (error_)\n\t\t\t{\n\t\t\t\treturn error_;\n\t\t\t}\n\t\t\treturn none;\n\t\t}\n\n\t\tValue &get()\n#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER\n\t\t\t&\n#endif\n\t\t{\n\t\t\tif (error_)\n\t\t\t{\n\t\t\t\tthrow_error(error_);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\n#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER\n\t\tValue &&get() &&\n\t\t{\n\t\t\tif (error_)\n\t\t\t{\n\t\t\t\tthrow_error(error_);\n\t\t\t}\n\t\t\treturn std::move(value);\n\t\t}\n#endif\n\n\t\tValue const &get() const\n#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER\n\t\t\t&\n#endif\n\t\t{\n\t\t\tif (error_)\n\t\t\t{\n\t\t\t\tthrow_error(error_);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\n\t\tValue *get_ptr() BOOST_NOEXCEPT\n\t\t{\n\t\t\tif (error_)\n\t\t\t{\n\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t\treturn &value;\n\t\t}\n\n\t\tValue const *get_ptr() const BOOST_NOEXCEPT\n\t\t{\n\t\t\tif (error_)\n\t\t\t{\n\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t\treturn &value;\n\t\t}\n\n\t\tValue *operator -> ()\n\t\t{\n\t\t\treturn &get();\n\t\t}\n\n\t\tValue const *operator -> () const\n\t\t{\n\t\t\treturn &get();\n\t\t}\n\n\t\tboost::optional get_optional()\n#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER\n\t\t\t&&\n#endif\n\t\t{\n\t\t\tauto *value = get_ptr();\n\t\t\tif (!value)\n\t\t\t{\n\t\t\t\treturn boost::none;\n\t\t\t}\n\t\t\treturn std::move(*value);\n\t\t}\n\n\t\tbool equals(error_or const &other) const\n\t\t{\n\t\t\tif (is_error() != other.is_error())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (is_error())\n\t\t\t{\n\t\t\t\treturn error_ == other.error_;\n\t\t\t}\n\t\t\treturn value == other.value;\n\t\t}\n\n\tprivate:\n\n\t\tError error_;\n\t\tValue value;\n\t};\n\n\tnamespace detail\n\t{\n\t\ttemplate \n\t\tFrom &&convert_if_necessary(From &&from, std::true_type)\n\t\t{\n\t\t\treturn std::forward(from);\n\t\t}\n\n\t\ttemplate \n\t\tTo convert_if_necessary(From &&from, std::false_type)\n\t\t{\n\t\t\treturn To(std::forward(from));\n\t\t}\n\t}\n\n\ttemplate \n\tbool operator == (error_or const &left, error_or const &right)\n\t{\n\t\treturn left.equals(right);\n\t}\n\n\ttemplate ::value, void>::type>\n\tbool operator == (error_or const &left, ConvertibleToValue const &right)\n\t{\n\t\tif (left.is_error())\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\treturn left.get() == detail::convert_if_necessary(right, std::is_same::type, typename std::decay::type>());\n\t}\n\n\ttemplate \n\tbool operator == (error_or const &left, Error const &right)\n\t{\n\t\tif (!left.is_error())\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\treturn *left.error() == right;\n\t}\n\n\ttemplate \n\tbool operator == (Anything const &left, error_or const &right)\n\t{\n\t\treturn (right == left);\n\t}\n\n\ttemplate \n\tbool operator != (Anything const &left, error_or const &right)\n\t{\n\t\treturn !(left == right);\n\t}\n\n\ttemplate \n\tbool operator != (error_or const &left, Anything const &right)\n\t{\n\t\treturn !(left == right);\n\t}\n\n\ttemplate \n\tstd::ostream &operator << (std::ostream &out, error_or const &value)\n\t{\n\t\tif (value.error())\n\t\t{\n\t\t\treturn out << *value.error();\n\t\t}\n\t\treturn out << value.get();\n\t}\n\n\ttemplate \n\tstruct is_error_or : std::false_type\n\t{\n\t};\n\n\ttemplate \n\tstruct is_error_or> : std::true_type\n\t{\n\t};\n\n\ttemplate ::type, class = typename std::enable_if::value, void>>\n\tauto map(ErrorOr &&maybe, OnValue &&on_value) -> CleanErrorOr\n\t{\n\t\tif (maybe.is_error())\n\t\t{\n\t\t\treturn *maybe.error();\n\t\t}\n\t\treturn std::forward(on_value)(std::forward(maybe).get());\n\t}\n}\n\n#endif\nfix infinite recursion bug in error_or operator ==#ifndef SILICIUM_ERROR_OR_HPP\n#define SILICIUM_ERROR_OR_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace Si\n{\n\tinline SILICIUM_NORETURN void throw_error(boost::system::error_code error)\n\t{\n\t\tboost::throw_exception(boost::system::system_error(error));\n\t}\n\n\tinline SILICIUM_NORETURN void throw_error(std::error_code error)\n\t{\n\t\tboost::throw_exception(std::system_error(error));\n\t}\n\n\tnamespace detail\n\t{\n\t\ttemplate \n\t\tFrom &&convert_if_necessary(From &&from, std::true_type)\n\t\t{\n\t\t\treturn std::forward(from);\n\t\t}\n\n\t\ttemplate \n\t\tTo convert_if_necessary(From &&from, std::false_type)\n\t\t{\n\t\t\treturn To(std::forward(from));\n\t\t}\n\t}\n\n\ttemplate \n\tstruct error_or\n\t{\n\t\terror_or() BOOST_NOEXCEPT\n\t\t\t: value(Value()) \/\/initialize so that reading the value does not have undefined behaviour\n\t\t{\n\t\t}\n\n\t\ttemplate ::value, void>::type>\n\t\terror_or(ConvertibleToValue &&value) BOOST_NOEXCEPT\n\t\t\t: value(std::forward(value))\n\t\t{\n\t\t}\n\n\t\terror_or(Error error) BOOST_NOEXCEPT\n\t\t\t: error_(std::move(error))\n\t\t{\n\t\t}\n\n#ifdef _MSC_VER\n\t\terror_or(error_or &&other) BOOST_NOEXCEPT\n\t\t\t: error_(std::move(other.error_))\n\t\t\t, value(std::move(other.value))\n\t\t{\n\t\t}\n\n\t\terror_or(error_or const &other)\n\t\t\t: error_(other.error_)\n\t\t\t, value(other.value)\n\t\t{\n\t\t}\n\n\t\terror_or &operator = (error_or &&other) BOOST_NOEXCEPT\n\t\t{\n\t\t\terror_ = std::move(other.error_);\n\t\t\tvalue = std::move(other.value);\n\t\t\treturn *this;\n\t\t}\n\n\t\terror_or &operator = (error_or const &other)\n\t\t{\n\t\t\terror_ = other.error_;\n\t\t\tvalue = other.value;\n\t\t\treturn *this;\n\t\t}\n#endif\n\n\t\tbool is_error() const BOOST_NOEXCEPT\n\t\t{\n\t\t\treturn !!error_;\n\t\t}\n\n\t\tSi::optional error() const BOOST_NOEXCEPT\n\t\t{\n\t\t\tif (error_)\n\t\t\t{\n\t\t\t\treturn error_;\n\t\t\t}\n\t\t\treturn none;\n\t\t}\n\n\t\tValue &get()\n#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER\n\t\t\t&\n#endif\n\t\t{\n\t\t\tif (error_)\n\t\t\t{\n\t\t\t\tthrow_error(error_);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\n#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER\n\t\tValue &&get() &&\n\t\t{\n\t\t\tif (error_)\n\t\t\t{\n\t\t\t\tthrow_error(error_);\n\t\t\t}\n\t\t\treturn std::move(value);\n\t\t}\n#endif\n\n\t\tValue const &get() const\n#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER\n\t\t\t&\n#endif\n\t\t{\n\t\t\tif (error_)\n\t\t\t{\n\t\t\t\tthrow_error(error_);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\n\t\tValue *get_ptr() BOOST_NOEXCEPT\n\t\t{\n\t\t\tif (error_)\n\t\t\t{\n\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t\treturn &value;\n\t\t}\n\n\t\tValue const *get_ptr() const BOOST_NOEXCEPT\n\t\t{\n\t\t\tif (error_)\n\t\t\t{\n\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t\treturn &value;\n\t\t}\n\n\t\tValue *operator -> ()\n\t\t{\n\t\t\treturn &get();\n\t\t}\n\n\t\tValue const *operator -> () const\n\t\t{\n\t\t\treturn &get();\n\t\t}\n\n\t\tboost::optional get_optional()\n#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER\n\t\t\t&&\n#endif\n\t\t{\n\t\t\tauto *value = get_ptr();\n\t\t\tif (!value)\n\t\t\t{\n\t\t\t\treturn boost::none;\n\t\t\t}\n\t\t\treturn std::move(*value);\n\t\t}\n\n\t\ttemplate \n\t\tbool equals(error_or const &other) const\n\t\t{\n\t\t\tif (is_error() != other.is_error())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (is_error())\n\t\t\t{\n\t\t\t\treturn error_ == *other.error();\n\t\t\t}\n\t\t\treturn value == other.get();\n\t\t}\n\n\t\ttemplate ::value, void>::type>\n\t\tbool equals(ConvertibleToValue const &right) const\n\t\t{\n\t\t\tif (is_error())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn get() == detail::convert_if_necessary(right, std::is_same::type, typename std::decay::type>());\n\t\t}\n\n\t\tbool equals(Error const &right) const\n\t\t{\n\t\t\tif (!is_error())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn *error() == right;\n\t\t}\n\n\tprivate:\n\n\t\tError error_;\n\t\tValue value;\n\t};\n\n\ttemplate \n\tstruct is_error_or : std::false_type\n\t{\n\t};\n\n\ttemplate \n\tstruct is_error_or> : std::true_type\n\t{\n\t};\n\n\ttemplate \n\tbool operator == (error_or const &left, Anything const &right)\n\t{\n\t\treturn left.equals(right);\n\t}\n\n\ttemplate ::value, void>::type>\n\tbool operator == (Anything const &left, error_or const &right)\n\t{\n\t\treturn right.equals(left);\n\t}\n\n\ttemplate \n\tbool operator != (Anything const &left, error_or const &right)\n\t{\n\t\treturn !(left == right);\n\t}\n\n\ttemplate \n\tbool operator != (error_or const &left, Anything const &right)\n\t{\n\t\treturn !(left == right);\n\t}\n\n\ttemplate \n\tstd::ostream &operator << (std::ostream &out, error_or const &value)\n\t{\n\t\tif (value.error())\n\t\t{\n\t\t\treturn out << *value.error();\n\t\t}\n\t\treturn out << value.get();\n\t}\n\n\ttemplate ::type, class = typename std::enable_if::value, void>>\n\tauto map(ErrorOr &&maybe, OnValue &&on_value) -> error_or(on_value)(std::forward(maybe).get()))>\n\t{\n\t\tif (maybe.is_error())\n\t\t{\n\t\t\treturn *maybe.error();\n\t\t}\n\t\treturn std::forward(on_value)(std::forward(maybe).get());\n\t}\n}\n\n#endif\n<|endoftext|>"} {"text":"\/***********************************************************************\n created: Wed, 8th Feb 2012\n author: Lukas E Meindl (based on code by Paul D Turner)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/RendererModules\/OpenGL\/RenderTarget.h\"\n#include \"CEGUI\/RenderQueue.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GeometryBufferBase.h\"\n\n#include \n\n#include \"glm\/glm.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nconst double OpenGLRenderTarget::d_yfov_tan = 0.267949192431123;\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nOpenGLRenderTarget::OpenGLRenderTarget(OpenGLRendererBase& owner) :\n d_owner(owner),\n d_area(0, 0, 0, 0),\n d_matrix(1.0f),\n d_matrixValid(false),\n d_viewDistance(0)\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nOpenGLRenderTarget::~OpenGLRenderTarget()\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::draw(const GeometryBuffer& buffer)\n{\n buffer.draw();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::draw(const RenderQueue& queue)\n{\n queue.draw();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::setArea(const Rectf& area)\n{\n d_area = area;\n d_matrixValid = false;\n\n RenderTargetEventArgs args(this);\n T::fireEvent(RenderTarget::EventAreaChanged, args);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nconst Rectf& OpenGLRenderTarget::getArea() const\n{\n return d_area;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::activate()\n{\n glViewport(static_cast(d_area.left()),\n static_cast(d_area.top()),\n static_cast(d_area.getWidth()),\n static_cast(d_area.getHeight()));\n\n if (!d_matrixValid)\n updateMatrix();\n\n d_owner.setViewProjectionMatrix(d_matrix);\n\n RenderTarget::activate();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::deactivate()\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::unprojectPoint(const GeometryBuffer& buff,\n const Vector2f& p_in, Vector2f& p_out) const\n{\n if (!d_matrixValid)\n updateMatrix();\n\n const OpenGLGeometryBufferBase& gb =\n static_cast(buff);\n\n const GLint vp[4] = {\n static_cast(d_area.left()),\n static_cast(d_area.top()),\n static_cast(d_area.getWidth()),\n static_cast(d_area.getHeight())\n };\n\n GLdouble in_x, in_y, in_z;\n\n glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]);\n const glm::mat4& projMatrix = d_matrix;\n const glm::mat4& modelMatrix = gb.getMatrix();\n\n \/\/ unproject the ends of the ray\n glm::vec3 unprojected1;\n glm::vec3 unprojected2;\n in_x = vp[2] * 0.5;\n in_y = vp[3] * 0.5;\n in_z = -d_viewDistance;\n unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = p_in.d_x;\n in_y = vp[3] - p_in.d_y;\n in_z = 0.0;\n unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n \/\/ project points to orientate them with GeometryBuffer plane\n glm::vec3 projected1;\n glm::vec3 projected2;\n glm::vec3 projected3;\n in_x = 0.0;\n in_y = 0.0;\n projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = 1.0;\n in_y = 0.0;\n projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = 0.0;\n in_y = 1.0;\n projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n \/\/ calculate vectors for generating the plane\n const glm::vec3 pv1 = projected2 - projected1;\n const glm::vec3 pv2 = projected3 - projected1;\n \/\/ given the vectors, calculate the plane normal\n const glm::vec3 planeNormal = glm::cross(pv1, pv2);\n \/\/ calculate plane\n const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal);\n const double pl_d = - glm::dot(projected1, planeNormalNormalized);\n \/\/ calculate vector of picking ray\n const glm::vec3 rv = unprojected1 - unprojected2;\n \/\/ calculate intersection of ray and plane\n const double pn_dot_r1 = glm::dot(unprojected1, planeNormal);\n const double pn_dot_rv = glm::dot(rv, planeNormal);\n const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) \/ pn_dot_rv : 0.0;\n const double is_x = unprojected1.x - rv.x * tmp1;\n const double is_y = unprojected1.y - rv.y * tmp1;\n\n p_out.d_x = static_cast(is_x);\n p_out.d_y = static_cast(is_y);\n\n p_out = p_in; \/\/ CrazyEddie wanted this\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::updateMatrix() const\n{\n const float w = d_area.getWidth();\n const float h = d_area.getHeight();\n\n \/\/ We need to check if width or height are zero and act accordingly to prevent running into issues\n \/\/ with divisions by zero which would lead to undefined values, as well as faulty clipping planes\n \/\/ This is mostly important for avoiding asserts\n const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f);\n\n const float aspect = widthAndHeightNotZero ? w \/ h : 1.0f;\n const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f;\n const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f;\n d_viewDistance = midx \/ (aspect * d_yfov_tan);\n\n glm::vec3 eye = glm::vec3(midx, midy, float(-d_viewDistance));\n glm::vec3 center = glm::vec3(midx, midy, 1);\n glm::vec3 up = glm::vec3(0, -1, 0);\n\n glm::mat4 projectionMatrix = glm::perspective(30.f, aspect, float(d_viewDistance * 0.5), float(d_viewDistance * 2.0));\n \/\/ Projection matrix abuse!\n glm::mat4 viewMatrix = glm::lookAt(eye, center, up);\n \n d_matrix = projectionMatrix * viewMatrix;\n\n d_matrixValid = true;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nRenderer& OpenGLRenderTarget::getOwner()\n{\n return d_owner;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\nMOD: Fixing activation counter\/***********************************************************************\n created: Wed, 8th Feb 2012\n author: Lukas E Meindl (based on code by Paul D Turner)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/RendererModules\/OpenGL\/RenderTarget.h\"\n#include \"CEGUI\/RenderQueue.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GeometryBufferBase.h\"\n\n#include \n\n#include \"glm\/glm.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nconst double OpenGLRenderTarget::d_yfov_tan = 0.267949192431123;\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nOpenGLRenderTarget::OpenGLRenderTarget(OpenGLRendererBase& owner) :\n d_owner(owner),\n d_area(0, 0, 0, 0),\n d_matrix(1.0f),\n d_matrixValid(false),\n d_viewDistance(0)\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nOpenGLRenderTarget::~OpenGLRenderTarget()\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::draw(const GeometryBuffer& buffer)\n{\n buffer.draw();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::draw(const RenderQueue& queue)\n{\n queue.draw();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::setArea(const Rectf& area)\n{\n d_area = area;\n d_matrixValid = false;\n\n RenderTargetEventArgs args(this);\n T::fireEvent(RenderTarget::EventAreaChanged, args);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nconst Rectf& OpenGLRenderTarget::getArea() const\n{\n return d_area;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::activate()\n{\n glViewport(static_cast(d_area.left()),\n static_cast(d_area.top()),\n static_cast(d_area.getWidth()),\n static_cast(d_area.getHeight()));\n\n if (!d_matrixValid)\n updateMatrix();\n\n d_owner.setViewProjectionMatrix(d_matrix);\n\n RenderTarget::activate();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::deactivate()\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::unprojectPoint(const GeometryBuffer& buff,\n const Vector2f& p_in, Vector2f& p_out) const\n{\n if (!d_matrixValid)\n updateMatrix();\n\n const OpenGLGeometryBufferBase& gb =\n static_cast(buff);\n\n const GLint vp[4] = {\n static_cast(d_area.left()),\n static_cast(d_area.top()),\n static_cast(d_area.getWidth()),\n static_cast(d_area.getHeight())\n };\n\n GLdouble in_x, in_y, in_z;\n\n glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]);\n const glm::mat4& projMatrix = d_matrix;\n const glm::mat4& modelMatrix = gb.getMatrix();\n\n \/\/ unproject the ends of the ray\n glm::vec3 unprojected1;\n glm::vec3 unprojected2;\n in_x = vp[2] * 0.5;\n in_y = vp[3] * 0.5;\n in_z = -d_viewDistance;\n unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = p_in.d_x;\n in_y = vp[3] - p_in.d_y;\n in_z = 0.0;\n unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n \/\/ project points to orientate them with GeometryBuffer plane\n glm::vec3 projected1;\n glm::vec3 projected2;\n glm::vec3 projected3;\n in_x = 0.0;\n in_y = 0.0;\n projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = 1.0;\n in_y = 0.0;\n projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = 0.0;\n in_y = 1.0;\n projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n \/\/ calculate vectors for generating the plane\n const glm::vec3 pv1 = projected2 - projected1;\n const glm::vec3 pv2 = projected3 - projected1;\n \/\/ given the vectors, calculate the plane normal\n const glm::vec3 planeNormal = glm::cross(pv1, pv2);\n \/\/ calculate plane\n const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal);\n const double pl_d = - glm::dot(projected1, planeNormalNormalized);\n \/\/ calculate vector of picking ray\n const glm::vec3 rv = unprojected1 - unprojected2;\n \/\/ calculate intersection of ray and plane\n const double pn_dot_r1 = glm::dot(unprojected1, planeNormal);\n const double pn_dot_rv = glm::dot(rv, planeNormal);\n const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) \/ pn_dot_rv : 0.0;\n const double is_x = unprojected1.x - rv.x * tmp1;\n const double is_y = unprojected1.y - rv.y * tmp1;\n\n p_out.d_x = static_cast(is_x);\n p_out.d_y = static_cast(is_y);\n\n p_out = p_in; \/\/ CrazyEddie wanted this\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::updateMatrix() const\n{\n const float w = d_area.getWidth();\n const float h = d_area.getHeight();\n\n \/\/ We need to check if width or height are zero and act accordingly to prevent running into issues\n \/\/ with divisions by zero which would lead to undefined values, as well as faulty clipping planes\n \/\/ This is mostly important for avoiding asserts\n const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f);\n\n const float aspect = widthAndHeightNotZero ? w \/ h : 1.0f;\n const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f;\n const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f;\n d_viewDistance = midx \/ (aspect * d_yfov_tan);\n\n glm::vec3 eye = glm::vec3(midx, midy, float(-d_viewDistance));\n glm::vec3 center = glm::vec3(midx, midy, 1);\n glm::vec3 up = glm::vec3(0, -1, 0);\n\n glm::mat4 projectionMatrix = glm::perspective(30.f, aspect, float(d_viewDistance * 0.5), float(d_viewDistance * 2.0));\n \/\/ Projection matrix abuse!\n glm::mat4 viewMatrix = glm::lookAt(eye, center, up);\n \n d_matrix = projectionMatrix * viewMatrix;\n\n d_matrixValid = true;\n \/\/! This triggers all GeometryBuffers to regenerate their matrices\n d_activationCounter = 0;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nRenderer& OpenGLRenderTarget::getOwner()\n{\n return d_owner;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\n<|endoftext|>"} {"text":"\/***********************************************************************\n created: Wed, 8th Feb 2012\n author: Lukas E Meindl (based on code by Paul D Turner)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/RendererModules\/OpenGL\/RenderTarget.h\"\n#include \"CEGUI\/RenderQueue.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GeometryBufferBase.h\"\n\n#include \n\n#include \"glm\/glm.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nconst double OpenGLRenderTarget::d_yfov_tan = 0.267949192431123;\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nOpenGLRenderTarget::OpenGLRenderTarget(OpenGLRendererBase& owner) :\n d_owner(owner),\n d_area(0, 0, 0, 0),\n d_matrix(1.0f),\n d_matrixValid(false),\n d_viewDistance(0)\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nOpenGLRenderTarget::~OpenGLRenderTarget()\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::draw(const GeometryBuffer& buffer)\n{\n buffer.draw();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::draw(const RenderQueue& queue)\n{\n queue.draw();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::setArea(const Rectf& area)\n{\n d_area = area;\n d_matrixValid = false;\n\n RenderTargetEventArgs args(this);\n T::fireEvent(RenderTarget::EventAreaChanged, args);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nconst Rectf& OpenGLRenderTarget::getArea() const\n{\n return d_area;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::activate()\n{\n glViewport(static_cast(d_area.left()),\n static_cast(d_area.top()),\n static_cast(d_area.getWidth()),\n static_cast(d_area.getHeight()));\n\n if (!d_matrixValid)\n updateMatrix();\n\n d_owner.setViewProjectionMatrix(d_matrix);\n\n RenderTarget::activate();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::deactivate()\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::unprojectPoint(const GeometryBuffer& buff,\n const Vector2f& p_in, Vector2f& p_out) const\n{\n if (!d_matrixValid)\n updateMatrix();\n\n const OpenGLGeometryBufferBase& gb =\n static_cast(buff);\n\n const GLint vp[4] = {\n static_cast(d_area.left()),\n static_cast(d_area.top()),\n static_cast(d_area.getWidth()),\n static_cast(d_area.getHeight())\n };\n\n GLdouble in_x, in_y, in_z;\n\n glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]);\n const glm::mat4& projMatrix = d_matrix;\n const glm::mat4& modelMatrix = gb.getModelMatrix();\n\n \/\/ unproject the ends of the ray\n glm::vec3 unprojected1;\n glm::vec3 unprojected2;\n in_x = vp[2] * 0.5;\n in_y = vp[3] * 0.5;\n in_z = -d_viewDistance;\n unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = p_in.d_x;\n in_y = vp[3] - p_in.d_y;\n in_z = 0.0;\n unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n \/\/ project points to orientate them with GeometryBuffer plane\n glm::vec3 projected1;\n glm::vec3 projected2;\n glm::vec3 projected3;\n in_x = 0.0;\n in_y = 0.0;\n projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = 1.0;\n in_y = 0.0;\n projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = 0.0;\n in_y = 1.0;\n projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n \/\/ calculate vectors for generating the plane\n const glm::vec3 pv1 = projected2 - projected1;\n const glm::vec3 pv2 = projected3 - projected1;\n \/\/ given the vectors, calculate the plane normal\n const glm::vec3 planeNormal = glm::cross(pv1, pv2);\n \/\/ calculate plane\n const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal);\n const double pl_d = - glm::dot(projected1, planeNormalNormalized);\n \/\/ calculate vector of picking ray\n const glm::vec3 rv = unprojected1 - unprojected2;\n \/\/ calculate intersection of ray and plane\n const double pn_dot_r1 = glm::dot(unprojected1, planeNormal);\n const double pn_dot_rv = glm::dot(rv, planeNormal);\n const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) \/ pn_dot_rv : 0.0;\n const double is_x = unprojected1.x - rv.x * tmp1;\n const double is_y = unprojected1.y - rv.y * tmp1;\n\n p_out.d_x = static_cast(is_x);\n p_out.d_y = static_cast(is_y);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::updateMatrix() const\n{\n const float w = d_area.getWidth();\n const float h = d_area.getHeight();\n\n \/\/ We need to check if width or height are zero and act accordingly to prevent running into issues\n \/\/ with divisions by zero which would lead to undefined values, as well as faulty clipping planes\n \/\/ This is mostly important for avoiding asserts\n const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f);\n\n const float aspect = widthAndHeightNotZero ? w \/ h : 1.0f;\n const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f;\n const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f;\n d_viewDistance = midx \/ (aspect * d_yfov_tan);\n\n glm::vec3 eye = glm::vec3(midx, midy, float(-d_viewDistance));\n glm::vec3 center = glm::vec3(midx, midy, 1);\n glm::vec3 up = glm::vec3(0, -1, 0);\n\n glm::mat4 projectionMatrix = glm::perspective(30.f, aspect, float(d_viewDistance * 0.5), float(d_viewDistance * 2.0));\n \/\/ Projection matrix abuse!\n glm::mat4 viewMatrix = glm::lookAt(eye, center, up);\n \n d_matrix = projectionMatrix * viewMatrix;\n\n d_matrixValid = true;\n \/\/! This triggers all GeometryBuffers to regenerate their matrices\n d_activationCounter = -1;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nRenderer& OpenGLRenderTarget::getOwner()\n{\n return d_owner;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\nMOD: Docu\/***********************************************************************\n created: Wed, 8th Feb 2012\n author: Lukas E Meindl (based on code by Paul D Turner)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/RendererModules\/OpenGL\/RenderTarget.h\"\n#include \"CEGUI\/RenderQueue.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GeometryBufferBase.h\"\n\n#include \n\n#include \"glm\/glm.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nconst double OpenGLRenderTarget::d_yfov_tan = 0.267949192431123;\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nOpenGLRenderTarget::OpenGLRenderTarget(OpenGLRendererBase& owner) :\n d_owner(owner),\n d_area(0, 0, 0, 0),\n d_matrix(1.0f),\n d_matrixValid(false),\n d_viewDistance(0)\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nOpenGLRenderTarget::~OpenGLRenderTarget()\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::draw(const GeometryBuffer& buffer)\n{\n buffer.draw();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::draw(const RenderQueue& queue)\n{\n queue.draw();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::setArea(const Rectf& area)\n{\n d_area = area;\n d_matrixValid = false;\n\n RenderTargetEventArgs args(this);\n T::fireEvent(RenderTarget::EventAreaChanged, args);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nconst Rectf& OpenGLRenderTarget::getArea() const\n{\n return d_area;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::activate()\n{\n glViewport(static_cast(d_area.left()),\n static_cast(d_area.top()),\n static_cast(d_area.getWidth()),\n static_cast(d_area.getHeight()));\n\n if (!d_matrixValid)\n updateMatrix();\n\n d_owner.setViewProjectionMatrix(d_matrix);\n\n RenderTarget::activate();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::deactivate()\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::unprojectPoint(const GeometryBuffer& buff,\n const Vector2f& p_in, Vector2f& p_out) const\n{\n if (!d_matrixValid)\n updateMatrix();\n\n const OpenGLGeometryBufferBase& gb =\n static_cast(buff);\n\n const GLint vp[4] = {\n static_cast(d_area.left()),\n static_cast(d_area.top()),\n static_cast(d_area.getWidth()),\n static_cast(d_area.getHeight())\n };\n\n GLdouble in_x, in_y, in_z;\n\n glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]);\n const glm::mat4& projMatrix = d_matrix;\n const glm::mat4& modelMatrix = gb.getModelMatrix();\n\n \/\/ unproject the ends of the ray\n glm::vec3 unprojected1;\n glm::vec3 unprojected2;\n in_x = vp[2] * 0.5;\n in_y = vp[3] * 0.5;\n in_z = -d_viewDistance;\n unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = p_in.d_x;\n in_y = vp[3] - p_in.d_y;\n in_z = 0.0;\n unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n \/\/ project points to orientate them with GeometryBuffer plane\n glm::vec3 projected1;\n glm::vec3 projected2;\n glm::vec3 projected3;\n in_x = 0.0;\n in_y = 0.0;\n projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = 1.0;\n in_y = 0.0;\n projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = 0.0;\n in_y = 1.0;\n projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n \/\/ calculate vectors for generating the plane\n const glm::vec3 pv1 = projected2 - projected1;\n const glm::vec3 pv2 = projected3 - projected1;\n \/\/ given the vectors, calculate the plane normal\n const glm::vec3 planeNormal = glm::cross(pv1, pv2);\n \/\/ calculate plane\n const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal);\n const double pl_d = - glm::dot(projected1, planeNormalNormalized);\n \/\/ calculate vector of picking ray\n const glm::vec3 rv = unprojected1 - unprojected2;\n \/\/ calculate intersection of ray and plane\n const double pn_dot_r1 = glm::dot(unprojected1, planeNormal);\n const double pn_dot_rv = glm::dot(rv, planeNormal);\n const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) \/ pn_dot_rv : 0.0;\n const double is_x = unprojected1.x - rv.x * tmp1;\n const double is_y = unprojected1.y - rv.y * tmp1;\n\n p_out.d_x = static_cast(is_x);\n p_out.d_y = static_cast(is_y);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nvoid OpenGLRenderTarget::updateMatrix() const\n{\n const float w = d_area.getWidth();\n const float h = d_area.getHeight();\n\n \/\/ We need to check if width or height are zero and act accordingly to prevent running into issues\n \/\/ with divisions by zero which would lead to undefined values, as well as faulty clipping planes\n \/\/ This is mostly important for avoiding asserts\n const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f);\n\n const float aspect = widthAndHeightNotZero ? w \/ h : 1.0f;\n const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f;\n const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f;\n d_viewDistance = midx \/ (aspect * d_yfov_tan);\n\n glm::vec3 eye = glm::vec3(midx, midy, float(-d_viewDistance));\n glm::vec3 center = glm::vec3(midx, midy, 1);\n glm::vec3 up = glm::vec3(0, -1, 0);\n\n glm::mat4 projectionMatrix = glm::perspective(30.f, aspect, float(d_viewDistance * 0.5), float(d_viewDistance * 2.0));\n \/\/ Projection matrix abuse!\n glm::mat4 viewMatrix = glm::lookAt(eye, center, up);\n \n d_matrix = projectionMatrix * viewMatrix;\n\n d_matrixValid = true;\n \/\/! This will trigger the RenderTarget to notify all of its GeometryBuffers to regenerate their matrices\n d_activationCounter = -1;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate \nRenderer& OpenGLRenderTarget::getOwner()\n{\n return d_owner;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\n<|endoftext|>"} {"text":"\/** @file\n\n Class to execute one (or more) remap plugin(s).\n\n @section license License\n\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n#include \"RemapPlugins.h\"\n\nClassAllocator pluginAllocator(\"RemapPluginsAlloc\");\n\nTSRemapStatus\nRemapPlugins::run_plugin(remap_plugin_info* plugin)\n{\n TSRemapStatus plugin_retcode;\n TSRemapRequestInfo rri;\n url_mapping *map = _s->url_map.getMapping();\n URL *map_from = &(map->fromURL);\n URL *map_to = _s->url_map.getToURL();\n\n \/\/ This is the equivalent of TSHttpTxnClientReqGet(), which every remap plugin would\n \/\/ have to call.\n rri.requestBufp = reinterpret_cast(_request_header);\n rri.requestHdrp = reinterpret_cast(_request_header->m_http);\n\n \/\/ Read-only URL's (TSMLoc's to the SDK)\n rri.mapFromUrl = reinterpret_cast(map_from->m_url_impl);\n rri.mapToUrl = reinterpret_cast(map_to->m_url_impl);\n rri.requestUrl = reinterpret_cast(_request_url->m_url_impl);\n\n rri.redirect = 0;\n\n \/\/ These are made to reflect the \"defaults\" that will be used in\n \/\/ the case where the plugins don't modify them. It's semi-weird\n \/\/ that the \"from\" and \"to\" URLs changes when chaining happens, but\n \/\/ it is necessary to get predictable behavior.\n#if 0\n if (_cur == 0) {\n rri.remap_from_host = map_from->host_get(&rri.remap_from_host_size);\n rri.remap_from_port = map_from->port_get();\n rri.remap_from_path = map_from->path_get(&rri.remap_from_path_size);\n rri.from_scheme = map_from->scheme_get(&rri.from_scheme_len);\n } else {\n rri.remap_from_host = _request_url->host_get(&rri.remap_from_host_size);\n rri.remap_from_port = _request_url->port_get();\n rri.remap_from_path = _request_url->path_get(&rri.remap_from_path_size);\n rri.from_scheme = _request_url->scheme_get(&rri.from_scheme_len);\n }\n#endif\n\n void* ih = map->get_instance(_cur);\n\n \/\/ Prepare State for the future\n if (_s && _cur == 0) {\n _s->fp_tsremap_os_response = plugin->fp_tsremap_os_response;\n _s->remap_plugin_instance = ih;\n }\n\n plugin_retcode = plugin->fp_tsremap_do_remap(ih, _s ? reinterpret_cast(_s->state_machine) : NULL, &rri);\n \/\/ TODO: Deal with negative return codes here\n if (plugin_retcode < 0)\n plugin_retcode = TSREMAP_NO_REMAP;\n\n \/\/ First step after plugin remap must be \"redirect url\" check\n if ((TSREMAP_DID_REMAP == plugin_retcode || TSREMAP_DID_REMAP_STOP == plugin_retcode) && rri.redirect)\n _s->remap_redirect = _request_url->string_get(NULL);\n\n return plugin_retcode;\n}\n\n\/**\n This is the equivalent of the old DoRemap().\n\n @return 1 when you are done doing crap (otherwise, you get re-called\n with scheudle_imm and i hope you have something more to do), else\n 0 if you have something more do do (this isnt strict and we check\n there actually *is* something to do).\n\n*\/\nint\nRemapPlugins::run_single_remap()\n{\n \/\/ I should patent this\n Debug(\"url_rewrite\", \"Running single remap rule for the %d%s time\", _cur, _cur == 1 ? \"st\" : _cur == 2 ? \"nd\" : _cur == 3 ? \"rd\" : \"th\");\n\n remap_plugin_info *plugin = NULL;\n TSRemapStatus plugin_retcode = TSREMAP_NO_REMAP;\n\n const char *requestPath;\n int requestPathLen;\n url_mapping *map = _s->url_map.getMapping();\n URL *map_from = &(map->fromURL);\n URL *map_to = _s->url_map.getToURL();\n\n int redirect_host_len;\n\n \/\/ Debugging vars\n bool debug_on = false;\n int retcode = 0; \/\/ 0 - no redirect, !=0 - redirected\n\n requestPath = _request_url->path_get(&requestPathLen);\n debug_on = is_debug_tag_set(\"url_rewrite\");\n\n if (_request_header)\n plugin = map->get_plugin(_cur); \/\/get the nth plugin in our list of plugins\n\n if (plugin) {\n Debug(\"url_rewrite\", \"Remapping rule id: %d matched; running it now\", map->map_id);\n plugin_retcode = run_plugin(plugin);\n } else if (_cur > 0) {\n _cur++;\n Debug(\"url_rewrite\", \"There wasn't a plugin available for us to run. Completing all remap processing immediately\");\n return 1;\n }\n\n if (_s->remap_redirect) \/\/if redirect was set, we need to use that.\n return 1;\n\n \/\/ skip the !plugin_modified_* stuff if we are on our 2nd plugin (or greater) and there's no more plugins\n if (_cur > 0 && (_cur + 1) >= map->_plugin_count)\n goto done;\n\n if (TSREMAP_NO_REMAP == plugin_retcode || TSREMAP_NO_REMAP_STOP == plugin_retcode) {\n if (_cur > 0 ) {\n \/\/plugin didn't do anything for us, but maybe another will down the chain so lets assume there is something more for us to process\n ++_cur;\n Debug(\"url_rewrite\", \"Plugin didn't change anything, but we'll try the next one right now\");\n return 0;\n }\n\n Debug(\"url_rewrite\", \"plugin did not change host, port or path, copying from mapping rule\");\n\n int fromPathLen;\n const char *toHost;\n const char *toPath;\n int toPathLen;\n int toHostLen;\n\n map_from->path_get(&fromPathLen);\n toHost = map_to->host_get(&toHostLen);\n toPath = map_to->path_get(&toPathLen);\n\n _request_url->host_set(toHost, toHostLen);\n\n int to_port = map_to->port_get_raw();\n\n if (to_port != _request_url->port_get_raw())\n _request_url->port_set(to_port);\n\n int to_scheme_len, from_scheme_len;\n const char *to_scheme = map_to->scheme_get(&to_scheme_len);\n\n if (to_scheme != map_from->scheme_get(&from_scheme_len))\n _request_url->scheme_set(to_scheme, to_scheme_len);\n\n \/\/ Extra byte is potentially needed for prefix path '\/'.\n \/\/ Added an extra 3 so that TS wouldn't crash in the field.\n \/\/ Allocate a large buffer to avoid problems.\n char newPathTmp[2048];\n char *newPath;\n char *newPathAlloc = NULL;\n unsigned int newPathLen = 0;\n unsigned int newPathLenNeed = (requestPathLen - fromPathLen) + toPathLen + 8; \/\/ 3 + some padding\n\n if (newPathLenNeed > sizeof(newPathTmp)) {\n newPath = (newPathAlloc = (char *)ats_malloc(newPathLenNeed));\n if (debug_on) {\n memset(newPath, 0, newPathLenNeed);\n }\n } else {\n newPath = &newPathTmp[0];\n if (debug_on) {\n memset(newPath, 0, sizeof(newPathTmp));\n }\n }\n\n *newPath = 0;\n\n \/\/ Purify load run with QT in a reverse proxy indicated\n \/\/ a UMR\/ABR\/MSE in the line where we do a *newPath == '\/' and the ink_strlcpy\n \/\/ that follows it. The problem occurs if\n \/\/ requestPathLen,fromPathLen,toPathLen are all 0; in this case, we never\n \/\/ initialize newPath, but still de-ref it in *newPath == '\/' comparison.\n \/\/ The memset fixes that problem.\n if (toPath) {\n memcpy(newPath, toPath, toPathLen);\n newPathLen += toPathLen;\n }\n \/\/ We might need to insert a trailing slash in the new portion of the path\n \/\/ if more will be added and none is present and one will be needed.\n if (!fromPathLen && requestPathLen && toPathLen && *(newPath + newPathLen - 1) != '\/') {\n *(newPath + newPathLen) = '\/';\n newPathLen++;\n }\n\n if (requestPath) {\n \/\/avoid adding another trailing slash if the requestPath already had one and so does the toPath\n if (requestPathLen < fromPathLen) {\n if (toPathLen && requestPath[requestPathLen - 1] == '\/' && toPath[toPathLen - 1] == '\/') {\n fromPathLen++;\n }\n } else {\n if (toPathLen && requestPath[fromPathLen] == '\/' && toPath[toPathLen - 1] == '\/') {\n fromPathLen++;\n }\n }\n \/\/ copy the end of the path past what has been mapped\n if ((requestPathLen - fromPathLen) > 0) {\n memcpy(newPath + newPathLen, requestPath + fromPathLen, requestPathLen - fromPathLen);\n newPathLen += (requestPathLen - fromPathLen);\n }\n }\n \/\/ We need to remove the leading slash in newPath if one is\n \/\/ present.\n if (*newPath == '\/') {\n memmove(newPath, newPath + 1, --newPathLen);\n }\n\n _request_url->path_set(newPath, newPathLen);\n\n \/\/ TODO: This is horribly wrong and broken, when can this trigger??? Check\n \/\/ above, we already return on _s->remap_redirect ... \n if (map->homePageRedirect && fromPathLen == requestPathLen && _s->remap_redirect) {\n URL redirect_url;\n\n redirect_url.create(NULL);\n redirect_url.copy(_request_url);\n\n ink_assert(fromPathLen > 0);\n\n \/\/ Extra byte for trailing '\/' in redirect\n if (newPathLen > 0 && newPath[newPathLen - 1] != '\/') {\n newPath[newPathLen] = '\/';\n newPath[++newPathLen] = '\\0';\n redirect_url.path_set(newPath, newPathLen);\n }\n \/\/ If we have host header information,\n \/\/ put it back into redirect URL\n \/\/\n if (_hh_ptr != NULL) {\n redirect_url.host_set(_hh_ptr->request_host, _hh_ptr->host_len);\n if (redirect_url.port_get() != _hh_ptr->request_port) {\n redirect_url.port_set(_hh_ptr->request_port);\n }\n }\n \/\/ If request came in without a host, send back\n \/\/ the redirect with the name the proxy is known by\n if (redirect_url.host_get(&redirect_host_len) == NULL)\n redirect_url.host_set(rewrite_table->ts_name, strlen(rewrite_table->ts_name));\n\n if ((_s->remap_redirect = redirect_url.string_get(NULL)) != NULL)\n retcode = strlen(_s->remap_redirect);\n Debug(\"url_rewrite\", \"Redirected %.*s to %.*s\", requestPathLen, requestPath, retcode, _s->remap_redirect);\n redirect_url.destroy();\n }\n\n ats_free(newPathAlloc);\n }\n\ndone:\n if (_cur > MAX_REMAP_PLUGIN_CHAIN) {\n Error(\"Called run_single_remap more than 10 times. Stopping this remapping insanity now\");\n Debug(\"url_rewrite\", \"Called run_single_remap more than 10 times. Stopping this remapping insanity now\");\n return 1;\n }\n\n if (++_cur >= map->_plugin_count) {\n \/\/normally, we would callback into this function but we dont have anything more to do!\n Debug(\"url_rewrite\", \"We completed all remap plugins for this rule\");\n return 1;\n } else {\n Debug(\"url_rewrite\", \"Completed single remap. Attempting another via immediate callback\");\n return 0;\n }\n\n return 1;\n ink_debug_assert(!\"not reached\");\n}\n\nint\nRemapPlugins::run_remap(int event, Event* e)\n{\n Debug(\"url_rewrite\", \"Inside RemapPlugins::run_remap with cur = %d\", _cur);\n\n ink_debug_assert(action.continuation);\n ink_assert(action.continuation);\n\n int ret = 0;\n\n \/* make sure we weren't cancelled *\/\n if (action.cancelled) {\n mutex.clear();\n pluginAllocator.free(this); \/\/ugly\n return EVENT_DONE;\n }\n\n switch (event) {\n case EVENT_IMMEDIATE:\n Debug(\"url_rewrite\", \"handling immediate event inside RemapPlugins::run_remap\");\n ret = run_single_remap();\n \/**\n * If ret !=0 then we are done with this processor and we call back into the SM;\n * otherwise, we call this function again immediately (which really isn't immediate)\n * thru the eventProcessor, thus forcing another run of run_single_remap() which will\n * then operate on _request_url, etc performing additional remaps (mainly another plugin run)\n **\/\n if (ret) {\n action.continuation->handleEvent(EVENT_REMAP_COMPLETE, NULL);\n mutex.clear();\n action.mutex.clear();\n mutex = NULL;\n action.mutex = NULL;\n \/\/THREAD_FREE(this, pluginAllocator, t);\n pluginAllocator.free(this); \/\/ugly\n return EVENT_DONE;\n } else {\n e->schedule_imm(event);\n return EVENT_CONT;\n }\n\n break;\n default:\n ink_assert(!\"unknown event type\");\n break;\n };\n return EVENT_DONE;\n}\nrequestPath needs to be set after modifying the _request_url or it maybe invalid. Moved setting of this variable\/** @file\n\n Class to execute one (or more) remap plugin(s).\n\n @section license License\n\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n#include \"RemapPlugins.h\"\n\nClassAllocator pluginAllocator(\"RemapPluginsAlloc\");\n\nTSRemapStatus\nRemapPlugins::run_plugin(remap_plugin_info* plugin)\n{\n TSRemapStatus plugin_retcode;\n TSRemapRequestInfo rri;\n url_mapping *map = _s->url_map.getMapping();\n URL *map_from = &(map->fromURL);\n URL *map_to = _s->url_map.getToURL();\n\n \/\/ This is the equivalent of TSHttpTxnClientReqGet(), which every remap plugin would\n \/\/ have to call.\n rri.requestBufp = reinterpret_cast(_request_header);\n rri.requestHdrp = reinterpret_cast(_request_header->m_http);\n\n \/\/ Read-only URL's (TSMLoc's to the SDK)\n rri.mapFromUrl = reinterpret_cast(map_from->m_url_impl);\n rri.mapToUrl = reinterpret_cast(map_to->m_url_impl);\n rri.requestUrl = reinterpret_cast(_request_url->m_url_impl);\n\n rri.redirect = 0;\n\n \/\/ These are made to reflect the \"defaults\" that will be used in\n \/\/ the case where the plugins don't modify them. It's semi-weird\n \/\/ that the \"from\" and \"to\" URLs changes when chaining happens, but\n \/\/ it is necessary to get predictable behavior.\n#if 0\n if (_cur == 0) {\n rri.remap_from_host = map_from->host_get(&rri.remap_from_host_size);\n rri.remap_from_port = map_from->port_get();\n rri.remap_from_path = map_from->path_get(&rri.remap_from_path_size);\n rri.from_scheme = map_from->scheme_get(&rri.from_scheme_len);\n } else {\n rri.remap_from_host = _request_url->host_get(&rri.remap_from_host_size);\n rri.remap_from_port = _request_url->port_get();\n rri.remap_from_path = _request_url->path_get(&rri.remap_from_path_size);\n rri.from_scheme = _request_url->scheme_get(&rri.from_scheme_len);\n }\n#endif\n\n void* ih = map->get_instance(_cur);\n\n \/\/ Prepare State for the future\n if (_s && _cur == 0) {\n _s->fp_tsremap_os_response = plugin->fp_tsremap_os_response;\n _s->remap_plugin_instance = ih;\n }\n\n plugin_retcode = plugin->fp_tsremap_do_remap(ih, _s ? reinterpret_cast(_s->state_machine) : NULL, &rri);\n \/\/ TODO: Deal with negative return codes here\n if (plugin_retcode < 0)\n plugin_retcode = TSREMAP_NO_REMAP;\n\n \/\/ First step after plugin remap must be \"redirect url\" check\n if ((TSREMAP_DID_REMAP == plugin_retcode || TSREMAP_DID_REMAP_STOP == plugin_retcode) && rri.redirect)\n _s->remap_redirect = _request_url->string_get(NULL);\n\n return plugin_retcode;\n}\n\n\/**\n This is the equivalent of the old DoRemap().\n\n @return 1 when you are done doing crap (otherwise, you get re-called\n with scheudle_imm and i hope you have something more to do), else\n 0 if you have something more do do (this isnt strict and we check\n there actually *is* something to do).\n\n*\/\nint\nRemapPlugins::run_single_remap()\n{\n \/\/ I should patent this\n Debug(\"url_rewrite\", \"Running single remap rule for the %d%s time\", _cur, _cur == 1 ? \"st\" : _cur == 2 ? \"nd\" : _cur == 3 ? \"rd\" : \"th\");\n\n remap_plugin_info *plugin = NULL;\n TSRemapStatus plugin_retcode = TSREMAP_NO_REMAP;\n\n const char *requestPath;\n int requestPathLen;\n url_mapping *map = _s->url_map.getMapping();\n URL *map_from = &(map->fromURL);\n URL *map_to = _s->url_map.getToURL();\n\n int redirect_host_len;\n\n \/\/ Debugging vars\n bool debug_on = false;\n int retcode = 0; \/\/ 0 - no redirect, !=0 - redirected\n\n debug_on = is_debug_tag_set(\"url_rewrite\");\n\n if (_request_header)\n plugin = map->get_plugin(_cur); \/\/get the nth plugin in our list of plugins\n\n if (plugin) {\n Debug(\"url_rewrite\", \"Remapping rule id: %d matched; running it now\", map->map_id);\n plugin_retcode = run_plugin(plugin);\n } else if (_cur > 0) {\n _cur++;\n Debug(\"url_rewrite\", \"There wasn't a plugin available for us to run. Completing all remap processing immediately\");\n return 1;\n }\n\n if (_s->remap_redirect) \/\/if redirect was set, we need to use that.\n return 1;\n\n \/\/ skip the !plugin_modified_* stuff if we are on our 2nd plugin (or greater) and there's no more plugins\n if (_cur > 0 && (_cur + 1) >= map->_plugin_count)\n goto done;\n\n if (TSREMAP_NO_REMAP == plugin_retcode || TSREMAP_NO_REMAP_STOP == plugin_retcode) {\n if (_cur > 0 ) {\n \/\/plugin didn't do anything for us, but maybe another will down the chain so lets assume there is something more for us to process\n ++_cur;\n Debug(\"url_rewrite\", \"Plugin didn't change anything, but we'll try the next one right now\");\n return 0;\n }\n\n Debug(\"url_rewrite\", \"plugin did not change host, port or path, copying from mapping rule\");\n\n int fromPathLen;\n const char *toHost;\n const char *toPath;\n int toPathLen;\n int toHostLen;\n\n map_from->path_get(&fromPathLen);\n toHost = map_to->host_get(&toHostLen);\n toPath = map_to->path_get(&toPathLen);\n\n _request_url->host_set(toHost, toHostLen);\n\n int to_port = map_to->port_get_raw();\n\n if (to_port != _request_url->port_get_raw())\n _request_url->port_set(to_port);\n\n int to_scheme_len, from_scheme_len;\n const char *to_scheme = map_to->scheme_get(&to_scheme_len);\n\n if (to_scheme != map_from->scheme_get(&from_scheme_len))\n _request_url->scheme_set(to_scheme, to_scheme_len);\n\n requestPath = _request_url->path_get(&requestPathLen);\n \/\/ Extra byte is potentially needed for prefix path '\/'.\n \/\/ Added an extra 3 so that TS wouldn't crash in the field.\n \/\/ Allocate a large buffer to avoid problems.\n char newPathTmp[2048];\n char *newPath;\n char *newPathAlloc = NULL;\n unsigned int newPathLen = 0;\n unsigned int newPathLenNeed = (requestPathLen - fromPathLen) + toPathLen + 8; \/\/ 3 + some padding\n\n if (newPathLenNeed > sizeof(newPathTmp)) {\n newPath = (newPathAlloc = (char *)ats_malloc(newPathLenNeed));\n if (debug_on) {\n memset(newPath, 0, newPathLenNeed);\n }\n } else {\n newPath = &newPathTmp[0];\n if (debug_on) {\n memset(newPath, 0, sizeof(newPathTmp));\n }\n }\n\n *newPath = 0;\n\n \/\/ Purify load run with QT in a reverse proxy indicated\n \/\/ a UMR\/ABR\/MSE in the line where we do a *newPath == '\/' and the ink_strlcpy\n \/\/ that follows it. The problem occurs if\n \/\/ requestPathLen,fromPathLen,toPathLen are all 0; in this case, we never\n \/\/ initialize newPath, but still de-ref it in *newPath == '\/' comparison.\n \/\/ The memset fixes that problem.\n if (toPath) {\n memcpy(newPath, toPath, toPathLen);\n newPathLen += toPathLen;\n }\n \/\/ We might need to insert a trailing slash in the new portion of the path\n \/\/ if more will be added and none is present and one will be needed.\n if (!fromPathLen && requestPathLen && toPathLen && *(newPath + newPathLen - 1) != '\/') {\n *(newPath + newPathLen) = '\/';\n newPathLen++;\n }\n\n if (requestPath) {\n \/\/avoid adding another trailing slash if the requestPath already had one and so does the toPath\n if (requestPathLen < fromPathLen) {\n if (toPathLen && requestPath[requestPathLen - 1] == '\/' && toPath[toPathLen - 1] == '\/') {\n fromPathLen++;\n }\n } else {\n if (toPathLen && requestPath[fromPathLen] == '\/' && toPath[toPathLen - 1] == '\/') {\n fromPathLen++;\n }\n }\n \/\/ copy the end of the path past what has been mapped\n if ((requestPathLen - fromPathLen) > 0) {\n memcpy(newPath + newPathLen, requestPath + fromPathLen, requestPathLen - fromPathLen);\n newPathLen += (requestPathLen - fromPathLen);\n }\n }\n \/\/ We need to remove the leading slash in newPath if one is\n \/\/ present.\n if (*newPath == '\/') {\n memmove(newPath, newPath + 1, --newPathLen);\n }\n\n _request_url->path_set(newPath, newPathLen);\n\n \/\/ TODO: This is horribly wrong and broken, when can this trigger??? Check\n \/\/ above, we already return on _s->remap_redirect ... \n if (map->homePageRedirect && fromPathLen == requestPathLen && _s->remap_redirect) {\n URL redirect_url;\n\n redirect_url.create(NULL);\n redirect_url.copy(_request_url);\n\n ink_assert(fromPathLen > 0);\n\n \/\/ Extra byte for trailing '\/' in redirect\n if (newPathLen > 0 && newPath[newPathLen - 1] != '\/') {\n newPath[newPathLen] = '\/';\n newPath[++newPathLen] = '\\0';\n redirect_url.path_set(newPath, newPathLen);\n }\n \/\/ If we have host header information,\n \/\/ put it back into redirect URL\n \/\/\n if (_hh_ptr != NULL) {\n redirect_url.host_set(_hh_ptr->request_host, _hh_ptr->host_len);\n if (redirect_url.port_get() != _hh_ptr->request_port) {\n redirect_url.port_set(_hh_ptr->request_port);\n }\n }\n \/\/ If request came in without a host, send back\n \/\/ the redirect with the name the proxy is known by\n if (redirect_url.host_get(&redirect_host_len) == NULL)\n redirect_url.host_set(rewrite_table->ts_name, strlen(rewrite_table->ts_name));\n\n if ((_s->remap_redirect = redirect_url.string_get(NULL)) != NULL)\n retcode = strlen(_s->remap_redirect);\n Debug(\"url_rewrite\", \"Redirected %.*s to %.*s\", requestPathLen, requestPath, retcode, _s->remap_redirect);\n redirect_url.destroy();\n }\n\n ats_free(newPathAlloc);\n }\n\ndone:\n if (_cur > MAX_REMAP_PLUGIN_CHAIN) {\n Error(\"Called run_single_remap more than 10 times. Stopping this remapping insanity now\");\n Debug(\"url_rewrite\", \"Called run_single_remap more than 10 times. Stopping this remapping insanity now\");\n return 1;\n }\n\n if (++_cur >= map->_plugin_count) {\n \/\/normally, we would callback into this function but we dont have anything more to do!\n Debug(\"url_rewrite\", \"We completed all remap plugins for this rule\");\n return 1;\n } else {\n Debug(\"url_rewrite\", \"Completed single remap. Attempting another via immediate callback\");\n return 0;\n }\n\n return 1;\n ink_debug_assert(!\"not reached\");\n}\n\nint\nRemapPlugins::run_remap(int event, Event* e)\n{\n Debug(\"url_rewrite\", \"Inside RemapPlugins::run_remap with cur = %d\", _cur);\n\n ink_debug_assert(action.continuation);\n ink_assert(action.continuation);\n\n int ret = 0;\n\n \/* make sure we weren't cancelled *\/\n if (action.cancelled) {\n mutex.clear();\n pluginAllocator.free(this); \/\/ugly\n return EVENT_DONE;\n }\n\n switch (event) {\n case EVENT_IMMEDIATE:\n Debug(\"url_rewrite\", \"handling immediate event inside RemapPlugins::run_remap\");\n ret = run_single_remap();\n \/**\n * If ret !=0 then we are done with this processor and we call back into the SM;\n * otherwise, we call this function again immediately (which really isn't immediate)\n * thru the eventProcessor, thus forcing another run of run_single_remap() which will\n * then operate on _request_url, etc performing additional remaps (mainly another plugin run)\n **\/\n if (ret) {\n action.continuation->handleEvent(EVENT_REMAP_COMPLETE, NULL);\n mutex.clear();\n action.mutex.clear();\n mutex = NULL;\n action.mutex = NULL;\n \/\/THREAD_FREE(this, pluginAllocator, t);\n pluginAllocator.free(this); \/\/ugly\n return EVENT_DONE;\n } else {\n e->schedule_imm(event);\n return EVENT_CONT;\n }\n\n break;\n default:\n ink_assert(!\"unknown event type\");\n break;\n };\n return EVENT_DONE;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#ifdef Q_OS_WIN\n#include \"BorderlessWindow.h\"\n#else\n#include \"UnixWindow.h\"\n#endif\n\nvoid g_loadFonts(QApplication* application)\n{\n \/\/ Font\n QFont mainFont = application->font();\n mainFont.setStyleStrategy(QFont::PreferAntialias);\n application->setFont(mainFont);\n\n \/\/ Dynamically load fonts\n QStringList list;\n list << \"Montserrat-Black.ttf\" <<\n \"Montserrat-Bold.ttf\" <<\n \"Montserrat-Light.ttf\" <<\n \"Montserrat-Regular.ttf\" <<\n \"Montserrat-Thin.ttf\" <<\n \"Roboto-BlackItalic.ttf\" <<\n \"Roboto-Black.ttf\" <<\n \"Roboto-BoldItalic.ttf\" <<\n \"Roboto-Bold.ttf\" <<\n \"Roboto-Italic.ttf\" <<\n \"Roboto-LightItalic.ttf\" <<\n \"Roboto-Light.ttf\" <<\n \"Roboto-MediumItalic.ttf\" <<\n \"Roboto-Medium.ttf\" <<\n \"Roboto-Regular.ttf\" <<\n \"Roboto-ThinItalic.ttf\" <<\n \"Roboto-Thin.ttf\" <<\n \"SourceCodePro-Black.ttf\" <<\n \"SourceCodePro-Bold.ttf\" <<\n \"SourceCodePro-ExtraLight.ttf\" <<\n \"SourceCodePro-Light.ttf\" <<\n \"SourceCodePro-Medium.ttf\" <<\n \"SourceCodePro-Regular.ttf\" <<\n \"SourceCodePro-Semibold.ttf\" <<\n \"SourceSansPro-BlackItalic.ttf\" <<\n \"SourceSansPro-Black.ttf\" <<\n \"SourceSansPro-BoldItalic.ttf\" <<\n \"SourceSansPro-Bold.ttf\" <<\n \"SourceSansPro-ExtraLightItalic.ttf\" <<\n \"SourceSansPro-ExtraLight.ttf\" <<\n \"SourceSansPro-Italic.ttf\" <<\n \"SourceSansPro-LightItalic.ttf\" <<\n \"SourceSansPro-Light.ttf\" <<\n \"SourceSansPro-Regular.ttf\" <<\n \"SourceSansPro-SemiboldItalic.ttf\" <<\n \"SourceSansPro-Semibold.ttf\";\n\n int fontID(-1);\n bool fontWarningShown(false);\n for (auto font : list)\n {\n QFile res(\":\/Typeface\/\" + font);\n if (!res.open(QIODevice::ReadOnly))\n {\n if (!fontWarningShown)\n {\n QMessageBox::warning(0, \"Application\", (QString) \"Warning: Unable to load font \" + QChar(0x00AB) + font + QChar(0x00BB) + \".\");\n fontWarningShown = true;\n }\n }\n else\n {\n fontID = QFontDatabase::addApplicationFontFromData(res.readAll());\n if (fontID == -1 && !fontWarningShown)\n {\n QMessageBox::warning(0, \"Application\", (QString) \"Warning: Unable to load font \" + QChar(0x00AB) + font + QChar(0x00BB) + \".\");\n fontWarningShown = true;\n }\n }\n }\n\n}\n\nint main(int argc, char* argv[])\n{\n QApplication::setStyle(\"fusion\");\n QApplication* application = new QApplication(argc, argv);\n\n \/\/ Stylesheet\n QFile stylesheet(\":\/Styles\/PAClient.css\");\n if (stylesheet.open(QFile::ReadOnly))\n {\n QString styleSheet = stylesheet.readAll();\n application->setStyleSheet(styleSheet);\n }\n\n g_loadFonts(application);\n\n #ifdef Q_OS_WIN\n \/\/ Background color\n \/\/ This is only for WinApi window, Qt widgets use BorderlessWindow.css stylesheet\n HBRUSH windowBackground = CreateSolidBrush(RGB(34, 38, 47));\n\n \/\/ Create a Win window\n BorderlessWindow window(application, windowBackground, 1152, 648);\n window.setMinimumSize(830, 550);\n #else\n \/\/ Create a Unix window\n UnixWindow window;\n QSize* size = new QSize(1152, 648);\n window.resize(*size);\n window.setMinimumSize(830, 550);\n #endif\n\n \/\/ Launch\n application->exec();\n\n return 0;\n}\nAdd icon to apps under unix\/linux#include \n#include \n#include \n#include \n#include \n\n#ifdef Q_OS_WIN\n#include \"BorderlessWindow.h\"\n#else\n#include \"UnixWindow.h\"\n#endif\n\nvoid g_loadFonts(QApplication* application)\n{\n \/\/ Font\n QFont mainFont = application->font();\n mainFont.setStyleStrategy(QFont::PreferAntialias);\n application->setFont(mainFont);\n\n \/\/ Dynamically load fonts\n QStringList list;\n list << \"Montserrat-Black.ttf\" <<\n \"Montserrat-Bold.ttf\" <<\n \"Montserrat-Light.ttf\" <<\n \"Montserrat-Regular.ttf\" <<\n \"Montserrat-Thin.ttf\" <<\n \"Roboto-BlackItalic.ttf\" <<\n \"Roboto-Black.ttf\" <<\n \"Roboto-BoldItalic.ttf\" <<\n \"Roboto-Bold.ttf\" <<\n \"Roboto-Italic.ttf\" <<\n \"Roboto-LightItalic.ttf\" <<\n \"Roboto-Light.ttf\" <<\n \"Roboto-MediumItalic.ttf\" <<\n \"Roboto-Medium.ttf\" <<\n \"Roboto-Regular.ttf\" <<\n \"Roboto-ThinItalic.ttf\" <<\n \"Roboto-Thin.ttf\" <<\n \"SourceCodePro-Black.ttf\" <<\n \"SourceCodePro-Bold.ttf\" <<\n \"SourceCodePro-ExtraLight.ttf\" <<\n \"SourceCodePro-Light.ttf\" <<\n \"SourceCodePro-Medium.ttf\" <<\n \"SourceCodePro-Regular.ttf\" <<\n \"SourceCodePro-Semibold.ttf\" <<\n \"SourceSansPro-BlackItalic.ttf\" <<\n \"SourceSansPro-Black.ttf\" <<\n \"SourceSansPro-BoldItalic.ttf\" <<\n \"SourceSansPro-Bold.ttf\" <<\n \"SourceSansPro-ExtraLightItalic.ttf\" <<\n \"SourceSansPro-ExtraLight.ttf\" <<\n \"SourceSansPro-Italic.ttf\" <<\n \"SourceSansPro-LightItalic.ttf\" <<\n \"SourceSansPro-Light.ttf\" <<\n \"SourceSansPro-Regular.ttf\" <<\n \"SourceSansPro-SemiboldItalic.ttf\" <<\n \"SourceSansPro-Semibold.ttf\";\n\n int fontID(-1);\n bool fontWarningShown(false);\n for (auto font : list)\n {\n QFile res(\":\/Typeface\/\" + font);\n if (!res.open(QIODevice::ReadOnly))\n {\n if (!fontWarningShown)\n {\n QMessageBox::warning(0, \"Application\", (QString) \"Warning: Unable to load font \" + QChar(0x00AB) + font + QChar(0x00BB) + \".\");\n fontWarningShown = true;\n }\n }\n else\n {\n fontID = QFontDatabase::addApplicationFontFromData(res.readAll());\n if (fontID == -1 && !fontWarningShown)\n {\n QMessageBox::warning(0, \"Application\", (QString) \"Warning: Unable to load font \" + QChar(0x00AB) + font + QChar(0x00BB) + \".\");\n fontWarningShown = true;\n }\n }\n }\n\n}\n\nint main(int argc, char* argv[])\n{\n QApplication::setStyle(\"fusion\");\n QApplication* application = new QApplication(argc, argv);\n\n #ifndef Q_OS_WIN\n \/\/ dynamic loading of the icon under Linux\/UNIX\n application->setWindowIcon(QIcon(\":\/SystemMenu\/Icons\/Ascension_Icon.ico\"));\n #endif\n\n \/\/ Stylesheet\n QFile stylesheet(\":\/Styles\/PAClient.css\");\n if (stylesheet.open(QFile::ReadOnly))\n {\n QString styleSheet = stylesheet.readAll();\n application->setStyleSheet(styleSheet);\n }\n\n g_loadFonts(application);\n\n #ifdef Q_OS_WIN\n \/\/ Background color\n \/\/ This is only for WinApi window, Qt widgets use BorderlessWindow.css stylesheet\n HBRUSH windowBackground = CreateSolidBrush(RGB(34, 38, 47));\n\n \/\/ Create a Win window\n BorderlessWindow window(application, windowBackground, 1152, 648);\n window.setMinimumSize(830, 550);\n #else\n \/\/ Create a Unix window\n UnixWindow window;\n QSize* size = new QSize(1152, 648);\n window.resize(*size);\n window.setMinimumSize(830, 550);\n #endif\n\n \/\/ Launch\n application->exec();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \n#include \n#include \n#include \"itkDiffusionTensor3D.h\"\n\nnamespace mitk \n{\n#ifndef DOXYGEN_SKIP\n template void CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n {\n AccessFixedDimensionByItk_1(mitkImage, _CastToItkImage2Access, ::itk::GetImageDimension::ImageDimension, itkOutputImage);\n }\n#endif \/\/DOXYGEN_SKIP\n\ntypedef itk::Image itkImageD2;\ntypedef itk::Image itkImageF2;\ntypedef itk::Image itkImageSI2;\ntypedef itk::Image itkImageUI2;\ntypedef itk::Image itkImageSS2;\ntypedef itk::Image itkImageUS2;\ntypedef itk::Image itkImageSC2;\ntypedef itk::Image itkImageUC2;\ntypedef itk::Image, 2> itkImageRGBUC2;\ntypedef itk::Image, 2> itkImageDTIF2;\ntypedef itk::Image, 2> itkImageDTID2;\n\ntypedef itk::Image itkImageD3;\ntypedef itk::Image itkImageF3;\ntypedef itk::Image itkImageSI3;\ntypedef itk::Image itkImageUI3;\ntypedef itk::Image itkImageSS3;\ntypedef itk::Image itkImageUS3;\ntypedef itk::Image itkImageSC3;\ntypedef itk::Image itkImageUC3;\ntypedef itk::Image, 3> itkImageRGBUC3;\ntypedef itk::Image, 3> itkImageDTIF3;\ntypedef itk::Image, 3> itkImageDTID3;\n\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\n\/\/template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\n\/\/template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate <> void CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n{\n typedef itkImageRGBUC2 ItkOutputImageType;\n AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::RGBPixel, ::itk::GetImageDimension::ImageDimension, itkOutputImage);\n}\ntemplate <> void CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n{\n typedef itkImageDTIF2 ItkOutputImageType;\n AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D, ::itk::GetImageDimension::ImageDimension, itkOutputImage);\n}\ntemplate <> void CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n{\n typedef itkImageRGBUC2 ItkOutputImageType;\n AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D, ::itk::GetImageDimension::ImageDimension, itkOutputImage);\n}\n\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\n\/\/template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\n\/\/template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate <> void MITK_CORE_EXPORT CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n{\n typedef itkImageRGBUC3 ItkOutputImageType;\n AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::RGBPixel, ::itk::GetImageDimension::ImageDimension, itkOutputImage);\n}\ntemplate <> void MITK_CORE_EXPORT CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n{\n typedef itkImageRGBUC3 ItkOutputImageType;\n AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D, ::itk::GetImageDimension::ImageDimension, itkOutputImage);\n}\ntemplate <> void MITK_CORE_EXPORT CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n{\n typedef itkImageRGBUC3 ItkOutputImageType;\n AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D, ::itk::GetImageDimension::ImageDimension, itkOutputImage);\n}\n\n\n#ifndef DOXYGEN_SKIP\n\/\/\/\/ Extension for RGB (and maybe also for vector types)\n\/\/\/\/ Does not work yet, see comment below and bug 320\n\/\/template void RGBCastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n\/\/{\n\/\/ assert(mitkImage->GetDimension()==::itk::GetImageDimension::ImageDimension);\n\/\/\n\/\/ assert(mitkImage->GetPixelType().GetNumberOfComponents() == 3);\n\/\/\n\/\/ const std::type_info& typeId=*mitkImage->GetPixelType().GetTypeId();\n\/\/\n\/\/ \/\/ Currently, the following line always fails, see bug 320\n\/\/ assert( typeId == typeid(ItkOutputImageType::PixelType) );\n\/\/\n\/\/ const mitk::Image* constImage = mitkImage;\n\/\/ const_cast(constImage)->Update();\n\/\/\n\/\/ typedef mitk::ImageToItk ImageToItkType;\n\/\/ itk::SmartPointer imagetoitk = ImageToItkType::New();\n\/\/ imagetoitk->SetInput(mitkImage);\n\/\/ imagetoitk->Update();\n\/\/ itkOutputImage = imagetoitk->GetOutput();\n\/\/}\n\/\/\n\/\/typedef itk::Image, 2> itkImageRGBUC2;\n\/\/typedef itk::Image, 3> itkImageRGBUC3;\n\/\/\n\/\/template <> void CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n\/\/{\n\/\/ typedef itkImageRGBUC2 ItkOutputImageType;\n\/\/ RGBCastToItkImage(mitkImage, itkOutputImage);\n\/\/}\n\/\/\n\/\/template <> void CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n\/\/{\n\/\/ typedef itkImageRGBUC3 ItkOutputImageType;\n\/\/ RGBCastToItkImage(mitkImage, itkOutputImage);\n\/\/}\n#endif \/\/DOXYGEN_SKIP\n\n}\nFIX (#320): fixed erroneous typedefs for ItkOutputImageType in case of itk::DiffusionTensor3D cast\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \n#include \n#include \n#include \"itkDiffusionTensor3D.h\"\n\nnamespace mitk \n{\n#ifndef DOXYGEN_SKIP\n template void CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n {\n AccessFixedDimensionByItk_1(mitkImage, _CastToItkImage2Access, ::itk::GetImageDimension::ImageDimension, itkOutputImage);\n }\n#endif \/\/DOXYGEN_SKIP\n\ntypedef itk::Image itkImageD2;\ntypedef itk::Image itkImageF2;\ntypedef itk::Image itkImageSI2;\ntypedef itk::Image itkImageUI2;\ntypedef itk::Image itkImageSS2;\ntypedef itk::Image itkImageUS2;\ntypedef itk::Image itkImageSC2;\ntypedef itk::Image itkImageUC2;\ntypedef itk::Image, 2> itkImageRGBUC2;\ntypedef itk::Image, 2> itkImageDTIF2;\ntypedef itk::Image, 2> itkImageDTID2;\n\ntypedef itk::Image itkImageD3;\ntypedef itk::Image itkImageF3;\ntypedef itk::Image itkImageSI3;\ntypedef itk::Image itkImageUI3;\ntypedef itk::Image itkImageSS3;\ntypedef itk::Image itkImageUS3;\ntypedef itk::Image itkImageSC3;\ntypedef itk::Image itkImageUC3;\ntypedef itk::Image, 3> itkImageRGBUC3;\ntypedef itk::Image, 3> itkImageDTIF3;\ntypedef itk::Image, 3> itkImageDTID3;\n\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate <> void CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n{\n typedef itkImageRGBUC2 ItkOutputImageType;\n AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::RGBPixel, ::itk::GetImageDimension::ImageDimension, itkOutputImage);\n}\ntemplate <> void CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n{\n typedef itkImageDTIF2 ItkOutputImageType;\n AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D, ::itk::GetImageDimension::ImageDimension, itkOutputImage);\n}\ntemplate <> void CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n{\n typedef itkImageDTID2 ItkOutputImageType;\n AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D, ::itk::GetImageDimension::ImageDimension, itkOutputImage);\n}\n\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer&);\ntemplate <> void MITK_CORE_EXPORT CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n{\n typedef itkImageRGBUC3 ItkOutputImageType;\n AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::RGBPixel, ::itk::GetImageDimension::ImageDimension, itkOutputImage);\n}\ntemplate <> void MITK_CORE_EXPORT CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n{\n typedef itkImageDTIF3 ItkOutputImageType;\n AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D, ::itk::GetImageDimension::ImageDimension, itkOutputImage);\n}\ntemplate <> void MITK_CORE_EXPORT CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n{\n typedef itkImageDTID3 ItkOutputImageType;\n AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D, ::itk::GetImageDimension::ImageDimension, itkOutputImage);\n}\n\n\n#ifndef DOXYGEN_SKIP\n\/\/\/\/ Extension for RGB (and maybe also for vector types)\n\/\/\/\/ Does not work yet, see comment below and bug 320\n\/\/template void RGBCastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n\/\/{\n\/\/ assert(mitkImage->GetDimension()==::itk::GetImageDimension::ImageDimension);\n\/\/\n\/\/ assert(mitkImage->GetPixelType().GetNumberOfComponents() == 3);\n\/\/\n\/\/ const std::type_info& typeId=*mitkImage->GetPixelType().GetTypeId();\n\/\/\n\/\/ \/\/ Currently, the following line always fails, see bug 320\n\/\/ assert( typeId == typeid(ItkOutputImageType::PixelType) );\n\/\/\n\/\/ const mitk::Image* constImage = mitkImage;\n\/\/ const_cast(constImage)->Update();\n\/\/\n\/\/ typedef mitk::ImageToItk ImageToItkType;\n\/\/ itk::SmartPointer imagetoitk = ImageToItkType::New();\n\/\/ imagetoitk->SetInput(mitkImage);\n\/\/ imagetoitk->Update();\n\/\/ itkOutputImage = imagetoitk->GetOutput();\n\/\/}\n\/\/\n\/\/typedef itk::Image, 2> itkImageRGBUC2;\n\/\/typedef itk::Image, 3> itkImageRGBUC3;\n\/\/\n\/\/template <> void CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n\/\/{\n\/\/ typedef itkImageRGBUC2 ItkOutputImageType;\n\/\/ RGBCastToItkImage(mitkImage, itkOutputImage);\n\/\/}\n\/\/\n\/\/template <> void CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer& itkOutputImage)\n\/\/{\n\/\/ typedef itkImageRGBUC3 ItkOutputImageType;\n\/\/ RGBCastToItkImage(mitkImage, itkOutputImage);\n\/\/}\n#endif \/\/DOXYGEN_SKIP\n\n}\n<|endoftext|>"} {"text":"\/\/ OPeNDAPDir.cc\n\n#include \n#include \n#include \n#include \n#include \n\nusing std::cout ;\nusing std::endl ;\n\n#include \"OPeNDAPDir.h\"\n#include \"GNURegex.h\"\n\nOPeNDAPDir::OPeNDAPDir( const string &dirName )\n : _dirName( dirName ),\n _fileExpr( \"\" ),\n _dirLoaded( false )\n{\n}\n\nOPeNDAPDir::OPeNDAPDir( const string &dirName, const string &fileExpr )\n : _dirName( dirName ),\n _fileExpr( fileExpr ),\n _dirLoaded( false )\n{\n}\n\nOPeNDAPDir::OPeNDAPDir( const OPeNDAPDir ©From )\n : _dirName( copyFrom._dirName ),\n _fileExpr( copyFrom._fileExpr ),\n _dirLoaded( false )\n{\n}\n\nOPeNDAPDir::~OPeNDAPDir()\n{\n}\n\nOPeNDAPDir::dirIterator\nOPeNDAPDir::beginOfDirList()\n{\n if( _dirLoaded == false )\n {\n\tloadDir() ;\n\t_dirLoaded = true ;\n }\n return _dirList.begin() ;\n}\n\nOPeNDAPDir::dirIterator\nOPeNDAPDir::endOfDirList()\n{\n if( _dirLoaded == false )\n {\n\tloadDir() ;\n\t_dirLoaded = true ;\n }\n return _dirList.end() ;\n}\n\nOPeNDAPDir::fileIterator\nOPeNDAPDir::beginOfFileList()\n{\n if( _dirLoaded == false )\n {\n\tloadDir() ;\n\t_dirLoaded = true ;\n }\n return _fileList.begin() ;\n}\n\nOPeNDAPDir::fileIterator\nOPeNDAPDir::endOfFileList()\n{\n if( _dirLoaded == false )\n {\n\tloadDir() ;\n\t_dirLoaded = true ;\n }\n return _fileList.end() ;\n}\n\nvoid\nOPeNDAPDir::loadDir()\n{\n DIR * dip;\n struct dirent *dit;\n\n \/\/ open a directory stream\n \/\/ make sure the directory is valid and readable\n if( ( dip = opendir( _dirName.c_str() ) ) == NULL )\n {\n\tstring err_str = \"ERROR: failed to open directory '\" + _dirName + \"'\" ;\n\tthrow err_str ;\n }\n else\n {\n\t\/\/ read in the files in this directory\n\t\/\/ add each filename to the list of filenames\n\twhile ( ( dit = readdir( dip ) ) != NULL )\n\t{\n\t struct stat buf;\n\t string dirEntry = dit->d_name ;\n\t if( dirEntry != \".\" && dirEntry != \"..\" )\n\t {\n\t\tstring fullPath = _dirName + \"\/\" + dirEntry ;\n\t\tstat( fullPath.c_str(), &buf ) ;\n\n\t\t\/\/ look at the mode and determine if this is a filename\n\t\t\/\/ or a directory name\n\t\tif ( S_ISDIR( buf.st_mode ) )\n\t\t{\n\t\t _dirList.push_back( OPeNDAPDir( fullPath ) ) ;\n\t\t}\n\t\telse\n\t\t{\n\t\t if( _fileExpr != \"\" )\n\t\t {\n\t\t\tRegex reg_expr( _fileExpr.c_str() ) ;\n\t\t\tif( reg_expr.match( dirEntry.c_str(),\n\t\t\t dirEntry.length() ) != -1 )\n\t\t\t{\n\t\t\t _fileList.push_back( OPeNDAPFile( _dirName, dirEntry ) );\n\t\t\t}\n\t\t }\n\t\t else\n\t\t {\n\t\t\t_fileList.push_back( OPeNDAPFile( _dirName, dirEntry ) ) ;\n\t\t }\n\t\t}\n\t }\n\t}\n }\n\n \/\/ close the directory\n closedir( dip ) ;\n}\n\nTweek for win32 port\/\/ OPeNDAPDir.cc\n\n#include \n#include \n#include \n#ifdef WIN32\n#include \/\/ for S_ISDIR macro\n#endif\n#include \n#include \n\nusing std::cout ;\nusing std::endl ;\n\n#include \"OPeNDAPDir.h\"\n#include \"GNURegex.h\"\n\nOPeNDAPDir::OPeNDAPDir( const string &dirName )\n : _dirName( dirName ),\n _fileExpr( \"\" ),\n _dirLoaded( false )\n{\n}\n\nOPeNDAPDir::OPeNDAPDir( const string &dirName, const string &fileExpr )\n : _dirName( dirName ),\n _fileExpr( fileExpr ),\n _dirLoaded( false )\n{\n}\n\nOPeNDAPDir::OPeNDAPDir( const OPeNDAPDir ©From )\n : _dirName( copyFrom._dirName ),\n _fileExpr( copyFrom._fileExpr ),\n _dirLoaded( false )\n{\n}\n\nOPeNDAPDir::~OPeNDAPDir()\n{\n}\n\nOPeNDAPDir::dirIterator\nOPeNDAPDir::beginOfDirList()\n{\n if( _dirLoaded == false )\n {\n\tloadDir() ;\n\t_dirLoaded = true ;\n }\n return _dirList.begin() ;\n}\n\nOPeNDAPDir::dirIterator\nOPeNDAPDir::endOfDirList()\n{\n if( _dirLoaded == false )\n {\n\tloadDir() ;\n\t_dirLoaded = true ;\n }\n return _dirList.end() ;\n}\n\nOPeNDAPDir::fileIterator\nOPeNDAPDir::beginOfFileList()\n{\n if( _dirLoaded == false )\n {\n\tloadDir() ;\n\t_dirLoaded = true ;\n }\n return _fileList.begin() ;\n}\n\nOPeNDAPDir::fileIterator\nOPeNDAPDir::endOfFileList()\n{\n if( _dirLoaded == false )\n {\n\tloadDir() ;\n\t_dirLoaded = true ;\n }\n return _fileList.end() ;\n}\n\nvoid\nOPeNDAPDir::loadDir()\n{\n DIR * dip;\n struct dirent *dit;\n\n \/\/ open a directory stream\n \/\/ make sure the directory is valid and readable\n if( ( dip = opendir( _dirName.c_str() ) ) == NULL )\n {\n\tstring err_str = \"ERROR: failed to open directory '\" + _dirName + \"'\" ;\n\tthrow err_str ;\n }\n else\n {\n\t\/\/ read in the files in this directory\n\t\/\/ add each filename to the list of filenames\n\twhile ( ( dit = readdir( dip ) ) != NULL )\n\t{\n\t struct stat buf;\n\t string dirEntry = dit->d_name ;\n\t if( dirEntry != \".\" && dirEntry != \"..\" )\n\t {\n\t\tstring fullPath = _dirName + \"\/\" + dirEntry ;\n\t\tstat( fullPath.c_str(), &buf ) ;\n\n\t\t\/\/ look at the mode and determine if this is a filename\n\t\t\/\/ or a directory name\n\t\tif ( S_ISDIR( buf.st_mode ) )\n\t\t{\n\t\t _dirList.push_back( OPeNDAPDir( fullPath ) ) ;\n\t\t}\n\t\telse\n\t\t{\n\t\t if( _fileExpr != \"\" )\n\t\t {\n\t\t\tRegex reg_expr( _fileExpr.c_str() ) ;\n\t\t\tif( reg_expr.match( dirEntry.c_str(),\n\t\t\t dirEntry.length() ) != -1 )\n\t\t\t{\n\t\t\t _fileList.push_back( OPeNDAPFile( _dirName, dirEntry ) );\n\t\t\t}\n\t\t }\n\t\t else\n\t\t {\n\t\t\t_fileList.push_back( OPeNDAPFile( _dirName, dirEntry ) ) ;\n\t\t }\n\t\t}\n\t }\n\t}\n }\n\n \/\/ close the directory\n closedir( dip ) ;\n}\n\n<|endoftext|>"} {"text":"#include \"StateMachine.h\"\n\n\/\/##ModelId=3E5B2DB301FD\nmitk::StateMachine::StateMachine(std::string type)\n: m_Type(type), m_CurrentState(0)\n{}\n\n\/\/##ModelId=3E5B2DE30378\nbool mitk::StateMachine::HandleEvent(StateEvent const* stateEvent)\n{\n\tconst Transition *tempTransition = m_CurrentState->GetTransition(stateEvent->GetId());\n\t\n\tState *tempState = tempTransition->GetNextState();\n\tif (tempState == NULL)\n\t\treturn false;\n\t\n\tint tempSideEffectId = tempTransition->GetSideEffectId();\n\n\t\/\/remember UNDO!!!!!\n\t\/*new Operation for StateChange and Operation*\/\n\tm_CurrentState = tempState;\n\n\t\/\/remember UNDO!!!!!\n\treturn Operation(tempSideEffectId);\n}\n\n\/\/##ModelId=3E5B2E660087\nstd::string mitk::StateMachine::GetName() const\n{\n\treturn m_Type;\n}\n\n\/\/##ModelId=3E5B2E170228\nbool mitk::StateMachine::ExecuteSideEffect(int sideEffectId)\n{\n\treturn true;\n}\n\nchanged handleEvent#include \"StateMachine.h\"\n\n\/\/##ModelId=3E5B2DB301FD\nmitk::StateMachine::StateMachine(std::string type)\n: m_Type(type), m_CurrentState(0)\n{}\n\n\/\/##ModelId=3E5B2DE30378\nbool mitk::StateMachine::HandleEvent(StateEvent const* stateEvent)\n{\n\tconst Transition *tempTransition = m_CurrentState->GetTransition(stateEvent->GetId());\n\t\n\tState *tempState = tempTransition->GetNextState();\n\tif (tempState == NULL)\n\t\treturn false;\n\t\n\tint tempSideEffectId = tempTransition->GetSideEffectId();\n\n\t\/\/remember UNDO!!!!!\n\t\/*first StateChange, then operation*\/\n\tm_CurrentState = tempState;\n\n\t\/\/remember UNDO!!!!!\n\tbool ok = ExecuteSideEffect(tempSideEffectId);\n\treturn ok;\n}\n\n\/\/##ModelId=3E5B2E660087\nstd::string mitk::StateMachine::GetName() const\n{\n\treturn m_Type;\n}\n\n\/\/##ModelId=3E5B2E170228\nbool mitk::StateMachine::ExecuteSideEffect(int sideEffectId)\n{\n\treturn true;\n}\n\n<|endoftext|>"} {"text":"\/*\n * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Affero General Public License as published by the\n * Free Software Foundation; either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program. If not, see .\n *\/\n\n#include \"MapUpdater.h\"\n#include \"LFGMgr.h\"\n#include \"Map.h\"\n#include \"Metric.h\"\n\nclass UpdateRequest\n{\npublic:\n UpdateRequest() = default;\n virtual ~UpdateRequest() = default;\n\n virtual void call() = 0;\n};\n\nclass MapUpdateRequest : public UpdateRequest\n{\npublic:\n MapUpdateRequest(Map& m, MapUpdater& u, uint32 d, uint32 sd)\n : m_map(m), m_updater(u), m_diff(d), s_diff(sd)\n {\n }\n\n void call() override\n {\n METRIC_TIMER(\"map_update_time_diff\", METRIC_TAG(\"map_id\", std::to_string(m_map.GetId())));\n m_map.Update(m_diff, s_diff);\n m_updater.update_finished();\n }\n\nprivate:\n Map& m_map;\n MapUpdater& m_updater;\n uint32 m_diff;\n uint32 s_diff;\n};\n\nclass LFGUpdateRequest : public UpdateRequest\n{\npublic:\n LFGUpdateRequest(MapUpdater& u, uint32 d) : m_updater(u), m_diff(d) {}\n\n void call() override\n {\n sLFGMgr->Update(m_diff, 1);\n m_updater.update_finished();\n }\nprivate:\n MapUpdater& m_updater;\n uint32 m_diff;\n};\n\nMapUpdater::MapUpdater(): pending_requests(0)\n{\n}\n\nvoid MapUpdater::activate(size_t num_threads)\n{\n _workerThreads.reserve(num_threads);\n for (size_t i = 0; i < num_threads; ++i)\n {\n _workerThreads.push_back(std::thread(&MapUpdater::WorkerThread, this));\n }\n}\n\nvoid MapUpdater::deactivate()\n{\n _cancelationToken = true;\n\n wait();\n\n _queue.Cancel();\n\n for (auto& thread : _workerThreads)\n {\n if (thread.joinable())\n {\n thread.join();\n }\n }\n}\n\nvoid MapUpdater::wait()\n{\n std::unique_lock guard(_lock);\n\n while (pending_requests > 0)\n _condition.wait(guard);\n\n guard.unlock();\n}\n\nvoid MapUpdater::schedule_update(Map& map, uint32 diff, uint32 s_diff)\n{\n std::lock_guard guard(_lock);\n\n ++pending_requests;\n\n _queue.Push(new MapUpdateRequest(map, *this, diff, s_diff));\n}\n\nvoid MapUpdater::schedule_lfg_update(uint32 diff)\n{\n std::lock_guard guard(_lock);\n\n ++pending_requests;\n\n _queue.Push(new LFGUpdateRequest(*this, diff));\n}\n\nbool MapUpdater::activated()\n{\n return _workerThreads.size() > 0;\n}\n\nvoid MapUpdater::update_finished()\n{\n std::lock_guard lock(_lock);\n\n --pending_requests;\n\n _condition.notify_all();\n}\n\nvoid MapUpdater::WorkerThread()\n{\n while (1)\n {\n UpdateRequest* request = nullptr;\n\n _queue.WaitAndPop(request);\n if (_cancelationToken)\n return;\n\n request->call();\n\n delete request;\n }\n}\nAdd (core\\logging): Log sync db queries in mapupdater (#13638)\/*\n * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Affero General Public License as published by the\n * Free Software Foundation; either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program. If not, see .\n *\/\n\n#include \"DatabaseEnv.h\"\n#include \"LFGMgr.h\"\n#include \"Map.h\"\n#include \"MapUpdater.h\"\n#include \"Metric.h\"\n\nclass UpdateRequest\n{\npublic:\n UpdateRequest() = default;\n virtual ~UpdateRequest() = default;\n\n virtual void call() = 0;\n};\n\nclass MapUpdateRequest : public UpdateRequest\n{\npublic:\n MapUpdateRequest(Map& m, MapUpdater& u, uint32 d, uint32 sd)\n : m_map(m), m_updater(u), m_diff(d), s_diff(sd)\n {\n }\n\n void call() override\n {\n METRIC_TIMER(\"map_update_time_diff\", METRIC_TAG(\"map_id\", std::to_string(m_map.GetId())));\n m_map.Update(m_diff, s_diff);\n m_updater.update_finished();\n }\n\nprivate:\n Map& m_map;\n MapUpdater& m_updater;\n uint32 m_diff;\n uint32 s_diff;\n};\n\nclass LFGUpdateRequest : public UpdateRequest\n{\npublic:\n LFGUpdateRequest(MapUpdater& u, uint32 d) : m_updater(u), m_diff(d) {}\n\n void call() override\n {\n sLFGMgr->Update(m_diff, 1);\n m_updater.update_finished();\n }\nprivate:\n MapUpdater& m_updater;\n uint32 m_diff;\n};\n\nMapUpdater::MapUpdater(): pending_requests(0)\n{\n}\n\nvoid MapUpdater::activate(size_t num_threads)\n{\n _workerThreads.reserve(num_threads);\n for (size_t i = 0; i < num_threads; ++i)\n {\n _workerThreads.push_back(std::thread(&MapUpdater::WorkerThread, this));\n }\n}\n\nvoid MapUpdater::deactivate()\n{\n _cancelationToken = true;\n\n wait();\n\n _queue.Cancel();\n\n for (auto& thread : _workerThreads)\n {\n if (thread.joinable())\n {\n thread.join();\n }\n }\n}\n\nvoid MapUpdater::wait()\n{\n std::unique_lock guard(_lock);\n\n while (pending_requests > 0)\n _condition.wait(guard);\n\n guard.unlock();\n}\n\nvoid MapUpdater::schedule_update(Map& map, uint32 diff, uint32 s_diff)\n{\n std::lock_guard guard(_lock);\n\n ++pending_requests;\n\n _queue.Push(new MapUpdateRequest(map, *this, diff, s_diff));\n}\n\nvoid MapUpdater::schedule_lfg_update(uint32 diff)\n{\n std::lock_guard guard(_lock);\n\n ++pending_requests;\n\n _queue.Push(new LFGUpdateRequest(*this, diff));\n}\n\nbool MapUpdater::activated()\n{\n return _workerThreads.size() > 0;\n}\n\nvoid MapUpdater::update_finished()\n{\n std::lock_guard lock(_lock);\n\n --pending_requests;\n\n _condition.notify_all();\n}\n\nvoid MapUpdater::WorkerThread()\n{\n LoginDatabase.WarnAboutSyncQueries(true);\n CharacterDatabase.WarnAboutSyncQueries(true);\n WorldDatabase.WarnAboutSyncQueries(true);\n\n while (1)\n {\n UpdateRequest* request = nullptr;\n\n _queue.WaitAndPop(request);\n if (_cancelationToken)\n return;\n\n request->call();\n\n delete request;\n }\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Medical Imaging & Interaction Toolkit\n Module: $RCSfile$\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/ for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"mitkStateMachine.h\"\n#include \"mitkStateMachineFactory.h\"\n#include \"mitkStateTransitionOperation.h\"\n#include \"mitkOperationEvent.h\"\n#include \"mitkUndoController.h\"\n#include \"mitkStatusBar.h\"\n#include \"mitkInteractionConst.h\"\n#include \n#include \"mitkInteractor.h\"\n\n\n\/\/##ModelId=3E5B2DB301FD\n\/\/##Documentation\n\/\/## Constructor\n\/\/## daclares a new StateMachine and connects\n\/\/## it to a StateMachine of Type type;\nmitk::StateMachine::StateMachine(const char * type) : m_CurrentState(NULL)\n{\n if(type!=NULL)\n {\n m_Type = type;\n\t m_CurrentState = mitk::StateMachineFactory::GetStartState(type);\n }\n else\n mitk::StatusBar::DisplayText(\"Error! Sender: StateMachine; Message: Type of StateMachine is NULL!\", 10000);\n \n m_UndoController = new UndoController(LIMITEDLINEARUNDO);\/\/switch to LLU or add LLU\n\tm_UndoEnabled = true;\n}\n\n\/\/##ModelId=3E5B2E660087\nstd::string mitk::StateMachine::GetType() const\n{\n\treturn m_Type;\n}\n\nconst mitk::State* mitk::StateMachine::GetCurrentState() const\n{\n if (m_CurrentState)\n return m_CurrentState;\n return NULL;\n}\n\n\/\/##ModelId=3E5B2DE30378\nbool mitk::StateMachine::HandleEvent(StateEvent const* stateEvent)\n{\n if (m_CurrentState == NULL)\n return false;\/\/m_CurrentState needs to be set first!\n\n \/\/get the Transition from m_CurrentState which waits for this EventId\n const Transition *tempTransition = m_CurrentState->GetTransition(stateEvent->GetId());\n if (tempTransition == NULL) \/\/no transition in this state for that EventId\n {\n return false;\n }\n\n \/\/get next State\n State *tempNextState = tempTransition->GetNextState();\n if (tempNextState == NULL) \/\/wrong built up statemachine!\n return false;\n\n \/\/and ActionId to execute later on\n if ( m_CurrentState->GetId() != tempNextState->GetId() )\/\/statechange only if there is a real statechange\n {\n if ( m_UndoEnabled )\t\/\/write to UndoMechanism if Undo is enabled\n {\n \/\/UNDO for this statechange; since we directly change the state, we don't need the do-Operation in case m_UndoEnables == false\n \t StateTransitionOperation* doOp = new StateTransitionOperation(OpSTATECHANGE, tempNextState);\n StateTransitionOperation* undoOp = new StateTransitionOperation(OpSTATECHANGE, m_CurrentState);\n\t OperationEvent *operationEvent = new OperationEvent(((mitk::OperationActor*)(this)), doOp, undoOp);\n\t m_UndoController->SetOperationEvent(operationEvent);\n }\n\n #ifdef INTERDEBUG\n \/\/Debug StateChanges through cout output! Thus very slow!\n std::cout<GetType()<<\": Changing from StateId \"<GetId()<<\" to StateId \"<GetId()<GetType()<<\": Changing from State \"<GetName()<<\" to State \"<GetName()<::iterator actionIdIterator = tempTransition->GetActionBeginIterator();\n const std::vector::iterator actionIdIteratorEnd = tempTransition->GetActionEndIterator();\n bool ok = true;\n\n while ( actionIdIterator != actionIdIteratorEnd ) \n {\n if ( !ExecuteAction(*actionIdIterator, stateEvent) )\n {\n #ifdef INTERDEBUG\n itkWarningMacro( << \"Warning: no action defind for \" << *actionIdIterator << \" in \" << m_Type );\n #endif\n\n ok = false;\n }\n actionIdIterator++;\n }\n return ok;\n}\n\n\/\/##ModelId=3EDCAECB0175\nvoid mitk::StateMachine::EnableUndo(bool enable)\n{\n\tm_UndoEnabled = enable;\n}\n\n\/\/##ModelId=3EF099EA03C0\nvoid mitk::StateMachine::IncCurrGroupEventId()\n{\n\tmitk::OperationEvent::IncCurrGroupEventId();\n}\n\nvoid mitk::StateMachine::ExecuteOperation(Operation* operation)\n{\n\tswitch (operation->GetOperationType())\n\t{\n\tcase OpNOTHING:\n\t\tbreak;\n\tcase OpSTATECHANGE:\n\t\t{\n\t\t\tmitk::StateTransitionOperation* stateTransOp = dynamic_cast(operation);\n\t\t\tif (stateTransOp == NULL)\n\t\t\t{\n\t\t\t\tmitk::StatusBar::DisplayText(\"Error! see mitkStateMachine.cpp\", 10000);\n\t\t\t\treturn;\n\t\t\t}\n#ifdef INTERDEBUG\n\/\/Debug StateChanges through cout output! Thus very slow!\nstd::cout<GetType()<<\": Undo: Changing from StateId \"<GetId()<<\" to StateId \"<GetState()->GetId()<GetType()<<\": Undo: Changing from State \"<GetName()<<\" to State \"<GetState()->GetName()<GetState();\n\t\t}\n\t\tbreak;\n case OpDELETE:\n {\n \/\/delete this!\n \/\/before all lower statemachines has to be deleted in a action\n \/\/this->Delete();\/\/might not work!!!check itk!\n }\n case OpUNDELETE:\n {\n \/\/this is just new! and now the m_CurrentState has to be set on a special State\n \/\/that way a delete of a StateMachine can be undone \n \/\/IMPORTANT: The type has to be the same!!!Done by a higher instance, that creates this!\n mitk::StateTransitionOperation* stateTransOp = dynamic_cast(operation);\n\t\t\tif (stateTransOp != NULL)\n {\n m_CurrentState = stateTransOp->GetState();\n }\n }\n\tdefault:\n\t\t;\n\t}\n}\ncode cleanup\/*=========================================================================\n\n Program: Medical Imaging & Interaction Toolkit\n Module: $RCSfile$\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/ for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"mitkStateMachine.h\"\n#include \"mitkStateMachineFactory.h\"\n#include \"mitkStateTransitionOperation.h\"\n#include \"mitkOperationEvent.h\"\n#include \"mitkUndoController.h\"\n#include \"mitkInteractionConst.h\"\n#include \n#include \"mitkInteractor.h\"\n\n\n\/\/##ModelId=3E5B2DB301FD\n\/\/##Documentation\n\/\/## Constructor\n\/\/## daclares a new StateMachine and connects\n\/\/## it to a StateMachine of Type type;\nmitk::StateMachine::StateMachine(const char * type) : m_CurrentState(NULL)\n{\n if(type!=NULL)\n {\n m_Type = type;\n\t m_CurrentState = mitk::StateMachineFactory::GetStartState(type);\n if (m_CurrentState == NULL)\n itkWarningMacro(\"Error from \"<GetNameOfClass()<<\"; Message: did not recieve a pointer for start-state\");\n }\n \/\/else\n \/\/ itkWarningMacro(\"Error from \"<GetNameOfClass()<<\"; Message: Type of StateMachine is NULL!\");\n \/\/\\*todo: check the process with BaseControllers, cause they are always instantiated with type ==NULL! So here we can't check and warn the user.\n \n m_UndoController = new UndoController(LIMITEDLINEARUNDO);\/\/switch to LLU or add LLU\n\tm_UndoEnabled = true;\n}\n\n\/\/##ModelId=3E5B2E660087\nstd::string mitk::StateMachine::GetType() const\n{\n\treturn m_Type;\n}\n\nconst mitk::State* mitk::StateMachine::GetCurrentState() const\n{\n if (m_CurrentState)\n return m_CurrentState;\n return NULL;\n}\n\n\/\/##ModelId=3E5B2DE30378\nbool mitk::StateMachine::HandleEvent(StateEvent const* stateEvent)\n{\n if (m_CurrentState == NULL)\n return false;\/\/m_CurrentState needs to be set first!\n\n \/\/get the Transition from m_CurrentState which waits for this EventId\n const Transition *tempTransition = m_CurrentState->GetTransition(stateEvent->GetId());\n if (tempTransition == NULL) \/\/no transition in this state for that EventId\n {\n return false;\n }\n\n \/\/get next State\n State *tempNextState = tempTransition->GetNextState();\n if (tempNextState == NULL) \/\/wrong built up statemachine!\n return false;\n\n \/\/and ActionId to execute later on\n if ( m_CurrentState->GetId() != tempNextState->GetId() )\/\/statechange only if there is a real statechange\n {\n if ( m_UndoEnabled )\t\/\/write to UndoMechanism if Undo is enabled\n {\n \/\/UNDO for this statechange; since we directly change the state, we don't need the do-Operation in case m_UndoEnables == false\n \t StateTransitionOperation* doOp = new StateTransitionOperation(OpSTATECHANGE, tempNextState);\n StateTransitionOperation* undoOp = new StateTransitionOperation(OpSTATECHANGE, m_CurrentState);\n\t OperationEvent *operationEvent = new OperationEvent(((mitk::OperationActor*)(this)), doOp, undoOp);\n\t m_UndoController->SetOperationEvent(operationEvent);\n }\n\n #ifdef INTERDEBUG\n \/\/Debug StateChanges through cout output! Thus very slow!\n std::cout<GetType()<<\": Changing from StateId \"<GetId()<<\" to StateId \"<GetId()<GetType()<<\": Changing from State \"<GetName()<<\" to State \"<GetName()<::iterator actionIdIterator = tempTransition->GetActionBeginIterator();\n const std::vector::iterator actionIdIteratorEnd = tempTransition->GetActionEndIterator();\n bool ok = true;\n\n while ( actionIdIterator != actionIdIteratorEnd ) \n {\n if ( !ExecuteAction(*actionIdIterator, stateEvent) )\n {\n #ifdef INTERDEBUG\n itkWarningMacro( << \"Warning: no action defind for \" << *actionIdIterator << \" in \" << m_Type );\n #endif\n\n ok = false;\n }\n actionIdIterator++;\n }\n return ok;\n}\n\n\/\/##ModelId=3EDCAECB0175\nvoid mitk::StateMachine::EnableUndo(bool enable)\n{\n\tm_UndoEnabled = enable;\n}\n\n\/\/##ModelId=3EF099EA03C0\nvoid mitk::StateMachine::IncCurrGroupEventId()\n{\n\tmitk::OperationEvent::IncCurrGroupEventId();\n}\n\nvoid mitk::StateMachine::ExecuteOperation(Operation* operation)\n{\n\tswitch (operation->GetOperationType())\n\t{\n\tcase OpNOTHING:\n\t\tbreak;\n\tcase OpSTATECHANGE:\n\t\t{\n\t\t\tmitk::StateTransitionOperation* stateTransOp = dynamic_cast(operation);\n\t\t\tif (stateTransOp == NULL)\n\t\t\t{\n\t\t\t\titkWarningMacro(\"Error! see mitkStateMachine.cpp\");\n\t\t\t\treturn;\n\t\t\t}\n#ifdef INTERDEBUG\n\/\/Debug StateChanges through cout output! Thus very slow!\nstd::cout<GetType()<<\": Undo: Changing from StateId \"<GetId()<<\" to StateId \"<GetState()->GetId()<GetType()<<\": Undo: Changing from State \"<GetName()<<\" to State \"<GetState()->GetName()<GetState();\n\t\t}\n\t\tbreak;\n case OpDELETE:\n {\n \/\/delete this!\n \/\/before all lower statemachines has to be deleted in a action\n \/\/this->Delete();\/\/might not work!!!check itk!\n }\n case OpUNDELETE:\n {\n \/\/this is just new! and now the m_CurrentState has to be set on a special State\n \/\/that way a delete of a StateMachine can be undone \n \/\/IMPORTANT: The type has to be the same!!!Done by a higher instance, that creates this!\n mitk::StateTransitionOperation* stateTransOp = dynamic_cast(operation);\n\t\t\tif (stateTransOp != NULL)\n {\n m_CurrentState = stateTransOp->GetState();\n }\n }\n\tdefault:\n\t\t;\n\t}\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: PlottingPositionHelper.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: bm $ $Date: 2004-01-26 09:13:21 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2003 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _CHART2_PLOTTINGPOSITIONHELPER_HXX\n#define _CHART2_PLOTTINGPOSITIONHELPER_HXX\n\n#include \"DoubleRectangle.hxx\"\n\n#ifndef _COM_SUN_STAR_CHART2_EXPLICITSCALEDATA_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CHART2_XTRANSFORMATION_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_DRAWING_HOMOGENMATRIX_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_POLYPOLYGONSHAPE3D_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_\n#include \n#endif\n\n#ifndef _B3D_HMATRIX_HXX\n#include \n#endif\n\/*\n\/\/for WeakImplHelper1\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include \n#endif\n*\/\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\n\/\/-----------------------------------------------------------------------------\n\/**\n*\/\n\nclass PlottingPositionHelper\n{\npublic:\n PlottingPositionHelper();\n virtual ~PlottingPositionHelper();\n\n void setTransformationSceneToScreen( const ::com::sun::star::drawing::HomogenMatrix& rMatrix);\n\n void setScales( const ::com::sun::star::uno::Sequence<\n ::com::sun::star::chart2::ExplicitScaleData >& rScales );\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::chart2::ExplicitScaleData >& getScales() const;\n\n inline bool isLogicVisible( double fX, double fY, double fZ ) const;\n inline void doLogicScaling( double* pX, double* pY, double* pZ ) const;\n inline void clipLogicValues( double* pX, double* pY, double* pZ ) const;\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >\n getTransformationLogicToScene() const;\n\n virtual ::com::sun::star::drawing::Position3D\n transformLogicToScene( double fX, double fY, double fZ, bool bClip ) const;\n\n void transformScaledLogicToScene( ::com::sun::star::drawing::PolyPolygonShape3D& rPoly ) const;\n\n inline double getLogicMinX() const;\n inline double getLogicMinY() const;\n inline double getLogicMinZ() const;\n inline double getLogicMaxX() const;\n inline double getLogicMaxY() const;\n inline double getLogicMaxZ() const;\n\n inline bool isMathematicalOrientationX() const;\n inline bool isMathematicalOrientationY() const;\n inline bool isMathematicalOrientationZ() const;\n\n DoubleRectangle getScaledLogicClipDoubleRect() const;\n\nprotected: \/\/member\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::chart2::ExplicitScaleData > m_aScales;\n Matrix4D m_aMatrixScreenToScene;\n\n \/\/this is calculated based on m_aScales and m_aMatrixScreenToScene\n mutable ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XTransformation > m_xTransformationLogicToScene;\n};\n\nclass PolarPlottingPositionHelper : public PlottingPositionHelper\n \/*\n , public ::cppu::WeakImplHelper1<\n ::com::sun::star::chart2::XTransformation >\n *\/\n{\npublic:\n PolarPlottingPositionHelper( bool bRadiusAxisMapsToFirstDimension );\n virtual ~PolarPlottingPositionHelper();\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >\n getTransformationLogicToScene() const;\n\n \/\/the resulting values should be used for input to the transformation\n \/\/received with 'getTransformationLogicToScene'\n double transformToRadius( double fLogicValueOnRadiusAxis ) const;\n double transformToAngleDegree( double fLogicValueOnAngleAxis ) const;\n double getWidthAngleDegree( double& fStartLogicValueOnAngleAxis, double& fEndLogicValueOnAngleAxis ) const;\n \/\/\n\n virtual ::com::sun::star::drawing::Position3D\n transformLogicToScene( double fX, double fY, double fZ, bool bClip ) const;\n ::com::sun::star::drawing::Position3D\n transformLogicToScene( double fLogicValueOnAngleAxis, double fLogicValueOnRadiusAxis, double fLogicZ ) const;\n\n double getInnerLogicRadius() const;\n double getOuterLogicRadius() const;\n\n \/*\n \/\/ ____ XTransformation ____\n \/\/\/ @see ::com::sun::star::chart2::XTransformation\n virtual ::com::sun::star::uno::Sequence< double > SAL_CALL transform(\n const ::com::sun::star::uno::Sequence< double >& rSourceValues )\n throw (::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n \/\/\/ @see ::com::sun::star::chart2::XTransformation\n virtual sal_Int32 SAL_CALL getSourceDimension()\n throw (::com::sun::star::uno::RuntimeException);\n \/\/\/ @see ::com::sun::star::chart2::XTransformation\n virtual sal_Int32 SAL_CALL getTargetDimension()\n throw (::com::sun::star::uno::RuntimeException);\n *\/\npublic:\n \/\/Offset for radius axis in absolute logic scaled values (1.0 == 1 category)\n double m_fRadiusOffset;\n \/\/Offset for angle axis in real degree\n double m_fAngleDegreeOffset;\n\nprivate:\n PolarPlottingPositionHelper();\n bool m_bRadiusAxisMapsToFirstDimension;\n};\n\nbool PlottingPositionHelper::isLogicVisible(\n double fX, double fY, double fZ ) const\n{\n return fX >= m_aScales[0].Minimum && fX <= m_aScales[0].Maximum\n && fY >= m_aScales[1].Minimum && fY <= m_aScales[1].Maximum\n && fZ >= m_aScales[2].Minimum && fZ <= m_aScales[2].Maximum;\n}\n\nvoid PlottingPositionHelper::doLogicScaling( double* pX, double* pY, double* pZ ) const\n{\n if(pX && m_aScales[0].Scaling.is())\n *pX = m_aScales[0].Scaling->doScaling(*pX);\n if(pY && m_aScales[1].Scaling.is())\n *pY = m_aScales[1].Scaling->doScaling(*pY);\n if(pZ && m_aScales[2].Scaling.is())\n *pZ = m_aScales[2].Scaling->doScaling(*pZ);\n}\n\nvoid PlottingPositionHelper::clipLogicValues( double* pX, double* pY, double* pZ ) const\n{\n if(pX)\n {\n if( *pX < m_aScales[0].Minimum )\n *pX = m_aScales[0].Minimum;\n else if( *pX > m_aScales[0].Maximum )\n *pX = m_aScales[0].Maximum;\n }\n if(pY)\n {\n if( *pY < m_aScales[1].Minimum )\n *pY = m_aScales[1].Minimum;\n else if( *pY > m_aScales[1].Maximum )\n *pY = m_aScales[1].Maximum;\n }\n if(pZ)\n {\n if( *pZ < m_aScales[2].Minimum )\n *pZ = m_aScales[2].Minimum;\n else if( *pZ > m_aScales[2].Maximum )\n *pZ = m_aScales[2].Maximum;\n }\n}\n\ninline double PlottingPositionHelper::getLogicMinX() const\n{\n return m_aScales[0].Minimum;\n}\ninline double PlottingPositionHelper::getLogicMinY() const\n{\n return m_aScales[1].Minimum;\n}\ninline double PlottingPositionHelper::getLogicMinZ() const\n{\n return m_aScales[2].Minimum;\n}\n\ninline double PlottingPositionHelper::getLogicMaxX() const\n{\n return m_aScales[0].Maximum;\n}\ninline double PlottingPositionHelper::getLogicMaxY() const\n{\n return m_aScales[1].Maximum;\n}\ninline double PlottingPositionHelper::getLogicMaxZ() const\n{\n return m_aScales[2].Maximum;\n}\ninline bool PlottingPositionHelper::isMathematicalOrientationX() const\n{\n return ::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[0].Orientation;\n}\ninline bool PlottingPositionHelper::isMathematicalOrientationY() const\n{\n return ::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[1].Orientation;\n}\ninline bool PlottingPositionHelper::isMathematicalOrientationZ() const\n{\n return ::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[2].Orientation;\n}\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n#endif\nINTEGRATION: CWS ooo19126 (1.7.110); FILE MERGED 2005\/09\/05 18:43:47 rt 1.7.110.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: PlottingPositionHelper.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 01:43:50 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _CHART2_PLOTTINGPOSITIONHELPER_HXX\n#define _CHART2_PLOTTINGPOSITIONHELPER_HXX\n\n#include \"DoubleRectangle.hxx\"\n\n#ifndef _COM_SUN_STAR_CHART2_EXPLICITSCALEDATA_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CHART2_XTRANSFORMATION_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_DRAWING_HOMOGENMATRIX_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_POLYPOLYGONSHAPE3D_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_\n#include \n#endif\n\n#ifndef _B3D_HMATRIX_HXX\n#include \n#endif\n\/*\n\/\/for WeakImplHelper1\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include \n#endif\n*\/\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\n\/\/-----------------------------------------------------------------------------\n\/**\n*\/\n\nclass PlottingPositionHelper\n{\npublic:\n PlottingPositionHelper();\n virtual ~PlottingPositionHelper();\n\n void setTransformationSceneToScreen( const ::com::sun::star::drawing::HomogenMatrix& rMatrix);\n\n void setScales( const ::com::sun::star::uno::Sequence<\n ::com::sun::star::chart2::ExplicitScaleData >& rScales );\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::chart2::ExplicitScaleData >& getScales() const;\n\n inline bool isLogicVisible( double fX, double fY, double fZ ) const;\n inline void doLogicScaling( double* pX, double* pY, double* pZ ) const;\n inline void clipLogicValues( double* pX, double* pY, double* pZ ) const;\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >\n getTransformationLogicToScene() const;\n\n virtual ::com::sun::star::drawing::Position3D\n transformLogicToScene( double fX, double fY, double fZ, bool bClip ) const;\n\n void transformScaledLogicToScene( ::com::sun::star::drawing::PolyPolygonShape3D& rPoly ) const;\n\n inline double getLogicMinX() const;\n inline double getLogicMinY() const;\n inline double getLogicMinZ() const;\n inline double getLogicMaxX() const;\n inline double getLogicMaxY() const;\n inline double getLogicMaxZ() const;\n\n inline bool isMathematicalOrientationX() const;\n inline bool isMathematicalOrientationY() const;\n inline bool isMathematicalOrientationZ() const;\n\n DoubleRectangle getScaledLogicClipDoubleRect() const;\n\nprotected: \/\/member\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::chart2::ExplicitScaleData > m_aScales;\n Matrix4D m_aMatrixScreenToScene;\n\n \/\/this is calculated based on m_aScales and m_aMatrixScreenToScene\n mutable ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XTransformation > m_xTransformationLogicToScene;\n};\n\nclass PolarPlottingPositionHelper : public PlottingPositionHelper\n \/*\n , public ::cppu::WeakImplHelper1<\n ::com::sun::star::chart2::XTransformation >\n *\/\n{\npublic:\n PolarPlottingPositionHelper( bool bRadiusAxisMapsToFirstDimension );\n virtual ~PolarPlottingPositionHelper();\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >\n getTransformationLogicToScene() const;\n\n \/\/the resulting values should be used for input to the transformation\n \/\/received with 'getTransformationLogicToScene'\n double transformToRadius( double fLogicValueOnRadiusAxis ) const;\n double transformToAngleDegree( double fLogicValueOnAngleAxis ) const;\n double getWidthAngleDegree( double& fStartLogicValueOnAngleAxis, double& fEndLogicValueOnAngleAxis ) const;\n \/\/\n\n virtual ::com::sun::star::drawing::Position3D\n transformLogicToScene( double fX, double fY, double fZ, bool bClip ) const;\n ::com::sun::star::drawing::Position3D\n transformLogicToScene( double fLogicValueOnAngleAxis, double fLogicValueOnRadiusAxis, double fLogicZ ) const;\n\n double getInnerLogicRadius() const;\n double getOuterLogicRadius() const;\n\n \/*\n \/\/ ____ XTransformation ____\n \/\/\/ @see ::com::sun::star::chart2::XTransformation\n virtual ::com::sun::star::uno::Sequence< double > SAL_CALL transform(\n const ::com::sun::star::uno::Sequence< double >& rSourceValues )\n throw (::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n \/\/\/ @see ::com::sun::star::chart2::XTransformation\n virtual sal_Int32 SAL_CALL getSourceDimension()\n throw (::com::sun::star::uno::RuntimeException);\n \/\/\/ @see ::com::sun::star::chart2::XTransformation\n virtual sal_Int32 SAL_CALL getTargetDimension()\n throw (::com::sun::star::uno::RuntimeException);\n *\/\npublic:\n \/\/Offset for radius axis in absolute logic scaled values (1.0 == 1 category)\n double m_fRadiusOffset;\n \/\/Offset for angle axis in real degree\n double m_fAngleDegreeOffset;\n\nprivate:\n PolarPlottingPositionHelper();\n bool m_bRadiusAxisMapsToFirstDimension;\n};\n\nbool PlottingPositionHelper::isLogicVisible(\n double fX, double fY, double fZ ) const\n{\n return fX >= m_aScales[0].Minimum && fX <= m_aScales[0].Maximum\n && fY >= m_aScales[1].Minimum && fY <= m_aScales[1].Maximum\n && fZ >= m_aScales[2].Minimum && fZ <= m_aScales[2].Maximum;\n}\n\nvoid PlottingPositionHelper::doLogicScaling( double* pX, double* pY, double* pZ ) const\n{\n if(pX && m_aScales[0].Scaling.is())\n *pX = m_aScales[0].Scaling->doScaling(*pX);\n if(pY && m_aScales[1].Scaling.is())\n *pY = m_aScales[1].Scaling->doScaling(*pY);\n if(pZ && m_aScales[2].Scaling.is())\n *pZ = m_aScales[2].Scaling->doScaling(*pZ);\n}\n\nvoid PlottingPositionHelper::clipLogicValues( double* pX, double* pY, double* pZ ) const\n{\n if(pX)\n {\n if( *pX < m_aScales[0].Minimum )\n *pX = m_aScales[0].Minimum;\n else if( *pX > m_aScales[0].Maximum )\n *pX = m_aScales[0].Maximum;\n }\n if(pY)\n {\n if( *pY < m_aScales[1].Minimum )\n *pY = m_aScales[1].Minimum;\n else if( *pY > m_aScales[1].Maximum )\n *pY = m_aScales[1].Maximum;\n }\n if(pZ)\n {\n if( *pZ < m_aScales[2].Minimum )\n *pZ = m_aScales[2].Minimum;\n else if( *pZ > m_aScales[2].Maximum )\n *pZ = m_aScales[2].Maximum;\n }\n}\n\ninline double PlottingPositionHelper::getLogicMinX() const\n{\n return m_aScales[0].Minimum;\n}\ninline double PlottingPositionHelper::getLogicMinY() const\n{\n return m_aScales[1].Minimum;\n}\ninline double PlottingPositionHelper::getLogicMinZ() const\n{\n return m_aScales[2].Minimum;\n}\n\ninline double PlottingPositionHelper::getLogicMaxX() const\n{\n return m_aScales[0].Maximum;\n}\ninline double PlottingPositionHelper::getLogicMaxY() const\n{\n return m_aScales[1].Maximum;\n}\ninline double PlottingPositionHelper::getLogicMaxZ() const\n{\n return m_aScales[2].Maximum;\n}\ninline bool PlottingPositionHelper::isMathematicalOrientationX() const\n{\n return ::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[0].Orientation;\n}\ninline bool PlottingPositionHelper::isMathematicalOrientationY() const\n{\n return ::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[1].Orientation;\n}\ninline bool PlottingPositionHelper::isMathematicalOrientationZ() const\n{\n return ::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[2].Orientation;\n}\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n#endif\n<|endoftext|>"} {"text":"\/*\n * This file is part of signon\n *\n * Copyright (C) 2009-2010 Nokia Corporation.\n *\n * Contact: Aurel Popirtac \n * Contact: Alberto Mardegan \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\/\n\n#include \"signondaemonadaptor.h\"\n#include \"accesscontrolmanager.h\"\n\nnamespace SignonDaemonNS {\n\n SignonDaemonAdaptor::SignonDaemonAdaptor(SignonDaemon *parent)\n : QDBusAbstractAdaptor(parent),\n m_parent(parent)\n {\n setAutoRelaySignals(false);\n }\n\n SignonDaemonAdaptor::~SignonDaemonAdaptor()\n {}\n\n bool SignonDaemonAdaptor::initSecureStorage(const QByteArray &lockCode)\n {\n return m_parent->initSecureStorage(lockCode);\n }\n\n void SignonDaemonAdaptor::registerNewIdentity(QDBusObjectPath &objectPath)\n {\n m_parent->registerNewIdentity(objectPath);\n }\n\n void SignonDaemonAdaptor::securityErrorReply(const char *failedMethodName)\n {\n QString errMsg;\n QTextStream(&errMsg) << SSO_DAEMON_PERMISSION_DENIED_ERR_STR\n << \"Method:\"\n << failedMethodName;\n\n QDBusMessage errReply =\n parentDBusContext().message().createErrorReply(\n SSO_DAEMON_PERMISSION_DENIED_ERR_NAME,\n errMsg);\n SIGNON_BUS.send(errReply);\n TRACE() << \"\\nMethod FAILED Access Control check:\\n\" << failedMethodName;\n }\n\n void SignonDaemonAdaptor::registerStoredIdentity(const quint32 id, QDBusObjectPath &objectPath, QList &identityData)\n {\n if (!AccessControlManager::isPeerAllowedToUseIdentity(\n parentDBusContext(), id)) {\n securityErrorReply(__func__);\n return;\n }\n\n m_parent->registerStoredIdentity(id, objectPath, identityData);\n }\n\n QStringList SignonDaemonAdaptor::queryMethods()\n {\n return m_parent->queryMethods();\n }\n\n QString SignonDaemonAdaptor::getAuthSessionObjectPath(const quint32 id, const QString &type)\n {\n \/* Access Control *\/\n if (id != SSO_NEW_IDENTITY) {\n if (!AccessControlManager::isPeerAllowedToUseAuthSession(\n parentDBusContext(), id)) {\n securityErrorReply(__func__);\n return QString();\n }\n }\n\n return m_parent->getAuthSessionObjectPath(id, type);\n }\n\n QStringList SignonDaemonAdaptor::queryMechanisms(const QString &method)\n {\n return m_parent->queryMechanisms(method);\n }\n\n QList SignonDaemonAdaptor::queryIdentities(const QMap &filter)\n {\n \/* Access Control *\/\n if (!AccessControlManager::isPeerKeychainWidget(parentDBusContext())) {\n securityErrorReply(__func__);\n return QList();\n }\n\n return m_parent->queryIdentities(filter);\n }\n\n bool SignonDaemonAdaptor::clear()\n {\n \/* Access Control *\/\n if (!AccessControlManager::isPeerKeychainWidget(parentDBusContext())) {\n securityErrorReply(__func__);\n return false;\n }\n\n return m_parent->clear();\n }\n\n bool SignonDaemonAdaptor::setDeviceLockCode(const QByteArray &oldLockCode,\n const QByteArray &newLockCode)\n {\n \/* TODO - this should be access controlled, too. Have to identify the\n caller process\/es. *\/\n return m_parent->setDeviceLockCode(oldLockCode, newLockCode);\n }\n\n bool SignonDaemonAdaptor::setSim(const QByteArray &simData,\n const QByteArray &checkData)\n {\n \/* TODO - this should be access controlled, too. Have to identify the\n caller process\/es. *\/\n return m_parent->setSim(simData, checkData);\n }\n\n bool SignonDaemonAdaptor::remoteLock(const QByteArray &lockCode)\n {\n \/* TODO - this should be access controlled, too. Have to identify the\n caller process\/es. *\/\n return m_parent->remoteLock(lockCode);\n }\n\n} \/\/namespace SignonDaemonNS\nCheck for disposable object in a few occasions\/*\n * This file is part of signon\n *\n * Copyright (C) 2009-2010 Nokia Corporation.\n *\n * Contact: Aurel Popirtac \n * Contact: Alberto Mardegan \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\/\n\n#include \"signondaemonadaptor.h\"\n#include \"signondisposable.h\"\n#include \"accesscontrolmanager.h\"\n\nnamespace SignonDaemonNS {\n\n SignonDaemonAdaptor::SignonDaemonAdaptor(SignonDaemon *parent)\n : QDBusAbstractAdaptor(parent),\n m_parent(parent)\n {\n setAutoRelaySignals(false);\n }\n\n SignonDaemonAdaptor::~SignonDaemonAdaptor()\n {}\n\n bool SignonDaemonAdaptor::initSecureStorage(const QByteArray &lockCode)\n {\n return m_parent->initSecureStorage(lockCode);\n }\n\n void SignonDaemonAdaptor::registerNewIdentity(QDBusObjectPath &objectPath)\n {\n SignonDisposable::destroyUnused();\n\n m_parent->registerNewIdentity(objectPath);\n }\n\n void SignonDaemonAdaptor::securityErrorReply(const char *failedMethodName)\n {\n QString errMsg;\n QTextStream(&errMsg) << SSO_DAEMON_PERMISSION_DENIED_ERR_STR\n << \"Method:\"\n << failedMethodName;\n\n QDBusMessage errReply =\n parentDBusContext().message().createErrorReply(\n SSO_DAEMON_PERMISSION_DENIED_ERR_NAME,\n errMsg);\n SIGNON_BUS.send(errReply);\n TRACE() << \"\\nMethod FAILED Access Control check:\\n\" << failedMethodName;\n }\n\n void SignonDaemonAdaptor::registerStoredIdentity(const quint32 id, QDBusObjectPath &objectPath, QList &identityData)\n {\n SignonDisposable::destroyUnused();\n\n if (!AccessControlManager::isPeerAllowedToUseIdentity(\n parentDBusContext(), id)) {\n securityErrorReply(__func__);\n return;\n }\n\n m_parent->registerStoredIdentity(id, objectPath, identityData);\n }\n\n QStringList SignonDaemonAdaptor::queryMethods()\n {\n return m_parent->queryMethods();\n }\n\n QString SignonDaemonAdaptor::getAuthSessionObjectPath(const quint32 id, const QString &type)\n {\n SignonDisposable::destroyUnused();\n\n \/* Access Control *\/\n if (id != SSO_NEW_IDENTITY) {\n if (!AccessControlManager::isPeerAllowedToUseAuthSession(\n parentDBusContext(), id)) {\n securityErrorReply(__func__);\n return QString();\n }\n }\n\n return m_parent->getAuthSessionObjectPath(id, type);\n }\n\n QStringList SignonDaemonAdaptor::queryMechanisms(const QString &method)\n {\n return m_parent->queryMechanisms(method);\n }\n\n QList SignonDaemonAdaptor::queryIdentities(const QMap &filter)\n {\n \/* Access Control *\/\n if (!AccessControlManager::isPeerKeychainWidget(parentDBusContext())) {\n securityErrorReply(__func__);\n return QList();\n }\n\n return m_parent->queryIdentities(filter);\n }\n\n bool SignonDaemonAdaptor::clear()\n {\n \/* Access Control *\/\n if (!AccessControlManager::isPeerKeychainWidget(parentDBusContext())) {\n securityErrorReply(__func__);\n return false;\n }\n\n return m_parent->clear();\n }\n\n bool SignonDaemonAdaptor::setDeviceLockCode(const QByteArray &oldLockCode,\n const QByteArray &newLockCode)\n {\n \/* TODO - this should be access controlled, too. Have to identify the\n caller process\/es. *\/\n return m_parent->setDeviceLockCode(oldLockCode, newLockCode);\n }\n\n bool SignonDaemonAdaptor::setSim(const QByteArray &simData,\n const QByteArray &checkData)\n {\n \/* TODO - this should be access controlled, too. Have to identify the\n caller process\/es. *\/\n return m_parent->setSim(simData, checkData);\n }\n\n bool SignonDaemonAdaptor::remoteLock(const QByteArray &lockCode)\n {\n \/* TODO - this should be access controlled, too. Have to identify the\n caller process\/es. *\/\n return m_parent->remoteLock(lockCode);\n }\n\n} \/\/namespace SignonDaemonNS\n<|endoftext|>"} {"text":"#include \n\nusing namespace std;\n\nvoid build_tree_from_preorder_inorder(string pre, string in) {\n int in_root_index = in.find(pre[0]);\n\n if (in.substr(0, in_root_index).length() > 0) {\n build_tree_from_preorder_inorder(\n pre.substr(1),\n in.substr(0, in_root_index));\n }\n if (in.substr(in_root_index + 1).length() > 0) {\n build_tree_from_preorder_inorder(\n pre.substr(in_root_index + 1),\n in.substr(in_root_index + 1));\n }\n\n cout << pre[0];\n}\n\nint main() {\n string pre, in;\n\n while (cin >> pre >> in) {\n build_tree_from_preorder_inorder(pre, in);\n cout << endl;\n }\n\n return 0;\n}\nRenomeia função de contrução da árvore.#include \n\nusing namespace std;\n\nvoid postorder_print_from_preorder_inorder(string pre, string in) {\n int in_root_index = in.find(pre[0]);\n\n if (in.substr(0, in_root_index).length() > 0) {\n postorder_print_from_preorder_inorder(\n pre.substr(1),\n in.substr(0, in_root_index));\n }\n if (in.substr(in_root_index + 1).length() > 0) {\n postorder_print_from_preorder_inorder(\n pre.substr(in_root_index + 1),\n in.substr(in_root_index + 1));\n }\n\n cout << pre[0];\n}\n\nint main() {\n string pre, in;\n\n while (cin >> pre >> in) {\n postorder_print_from_preorder_inorder(pre, in);\n cout << endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2017, Andrej Kislovskij\n *\n * This is PUBLIC DOMAIN software so use at your own risk as it comes\n * with no warranties. This code is yours to share, use and modify without\n * any restrictions or obligations.\n *\n * For more information see conwrap\/LICENSE or refer refer to http:\/\/unlicense.org\n *\n * Author: gimesketvirtadieni at gmail dot com (Andrej Kislovskij)\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \/\/ std::stringstream\n#include \n#include \n\n#include \"slim\/Chunk.hpp\"\n#include \"slim\/EncoderBase.hpp\"\n#include \"slim\/EncoderBuilder.hpp\"\n#include \"slim\/log\/log.hpp\"\n#include \"slim\/util\/BigInteger.hpp\"\n#include \"slim\/util\/BufferedAsyncWriter.hpp\"\n\n\nnamespace slim\n{\n\tnamespace proto\n\t{\n\t\tnamespace ts = type_safe;\n\n\t\ttemplate\n\t\tclass StreamingSession\n\t\t{\n\t\t\tpublic:\n\t\t\t\tStreamingSession(conwrap2::ProcessorProxy> pp, std::reference_wrapper co, std::string id, EncoderBuilder eb)\n\t\t\t\t: processorProxy{pp}\n\t\t\t\t, connection{co}\n\t\t\t\t, clientID{id}\n\t\t\t\t, bufferedWriter{co}\n\t\t\t\t{\n\t\t\t\t\tLOG(DEBUG) << LABELS{\"proto\"} << \"HTTP session object was created (id=\" << this << \")\";\n\n\t\t\t\t\teb.setEncodedCallback([&](auto* data, auto size)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ do not feed writer with more data if there is no room in transfer buffer\n\t\t\t\t\t\tif (bufferedWriter.isBufferAvailable())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbufferedWriter.writeAsync(data, size, [](auto error, auto written) {});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tLOG(WARNING) << LABELS{\"proto\"} << \"Transfer buffer is full - skipping encoded chunk\";\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tencoderPtr = std::move(eb.build());\n\t\t\t\t\tencoderPtr->start();\n\n\t\t\t\t\t\/\/ creating response string\n\t\t\t\t\tstd::stringstream ss;\n\t\t\t\t\tss << \"HTTP\/1.1 200 OK\\r\\n\"\n\t\t\t\t\t << \"Server: SlimStreamer (\"\n\t\t\t\t\t \/\/ TODO: provide version to the constructor\n\t\t\t\t\t << VERSION\n\t\t\t\t\t << \")\\r\\n\"\n\t\t\t\t\t << \"Connection: close\\r\\n\"\n\t\t\t\t\t << \"Content-Type: \" << encoderPtr->getMIME() << \"\\r\\n\"\n\t\t\t\t\t << \"\\r\\n\";\n\n\t\t\t\t\t\/\/ sending response string\n\t\t\t\t\tconnection.get().write(ss.str());\n\t\t\t\t}\n\n\t\t\t\t~StreamingSession()\n\t\t\t\t{\n\t\t\t\t\t\/\/ canceling deferred operation\n\t\t\t\t\tts::with(timer, [&](auto& timer)\n\t\t\t\t\t{\n\t\t\t\t\t\ttimer.cancel();\n\t\t\t\t\t});\n\n\t\t\t\t\tLOG(DEBUG) << LABELS{\"proto\"} << \"HTTP session object was deleted (id=\" << this << \")\";\n\t\t\t\t}\n\n\t\t\t\tStreamingSession(const StreamingSession&) = delete; \/\/ non-copyable\n\t\t\t\tStreamingSession& operator=(const StreamingSession&) = delete; \/\/ non-assignable\n\t\t\t\tStreamingSession(StreamingSession&& rhs) = delete; \/\/ non-movable\n\t\t\t\tStreamingSession& operator=(StreamingSession&& rhs) = delete; \/\/ non-movable-assignable\n\n\t\t\t\tinline auto getClientID()\n\t\t\t\t{\n\t\t\t\t\treturn clientID;\n\t\t\t\t}\n\n\t\t\t\tinline auto getFramesProvided()\n\t\t\t\t{\n\t\t\t\t\treturn framesProvided;\n\t\t\t\t}\n\n\t\t\t\tinline bool isRunning()\n\t\t\t\t{\n\t\t\t\t\treturn running;\n\t\t\t\t}\n\n\t\t\t\tinline void onRequest(unsigned char* data, std::size_t size)\n\t\t\t\t{\n\t\t\t\t\t\/\/ TODO: make more strick validation\n\t\t\t\t\tstd::string get{\"GET\"};\n\t\t\t\t\tstd::string s{(char*)data, get.size()};\n\t\t\t\t\tif (get.compare(s))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ stopping this session due an error\n\t\t\t\t\t\tLOG(WARNING) << LABELS{\"proto\"} << \"Wrong HTTP method provided\";\n\t\t\t\t\t\tstop([] {});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tstatic auto parseClientID(std::string header)\n\t\t\t\t{\n\t\t\t\t\tauto result{ts::optional{ts::nullopt}};\n\t\t\t\t\tauto separator{std::string{\"=\"}};\n\t\t\t\t\tauto index{header.find(separator)};\n\n\t\t\t\t\tif (index != std::string::npos)\n\t\t\t\t\t{\n\t\t\t\t\t\tresult = std::string{header.c_str() + index + separator.length(), header.length() - index - separator.length()};\n\t\t\t\t\t}\n\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tinline void start()\n\t\t\t\t{\n\t\t\t\t\trunning = true;\n\t\t\t\t}\n\n\t\t\t\ttemplate \n\t\t\t\tinline void stop(CallbackType callback)\n\t\t\t\t{\n\t\t\t\t\tif (running)\n\t\t\t\t\t{\n\t\t\t\t\t\tencoderPtr->stop([&, callback = std::move(callback)]\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tflush([&, callback = std::move(callback)]\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\trunning = false;\n\t\t\t\t\t\t\t\tcallback();\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcallback();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tinline void streamChunk(const Chunk& chunk)\n\t\t\t\t{\n\t\t\t\t\tif (chunk.getSamplingRate() == encoderPtr->getSamplingRate())\n\t\t\t\t\t{\n\t\t\t\t\t\tencoderPtr->encode(chunk.getData(), chunk.getSize());\n\t\t\t\t\t\tframesProvided += chunk.getFrames();\n\n\t\t\t\t\t\tif (chunk.isEndOfStream())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ stopping this session\n\t\t\t\t\t\t\tstop([] {});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tLOG(ERROR) << LABELS{\"proto\"} << \"Closing HTTP connection due to different sampling rate used by a client (session rate=\" << encoderPtr->getSamplingRate() << \"; data rate=\" << chunk.getSamplingRate() << \")\";\n\n\t\t\t\t\t\t\/\/ stopping this session\n\t\t\t\t\t\tstop([] {});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tprotected:\n\t\t\t\ttemplate \n\t\t\t\tvoid flush(CallbackType callback)\n\t\t\t\t{\n\t\t\t\t\tif (bufferedWriter.isBufferAvailable())\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ submitting an 'empty' chunk so that a callback gets invoked when all data has been transferred\n\t\t\t\t\t\tbufferedWriter.writeAsync(nullptr, 0, [callback = std::move(callback)](auto error, auto written)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcallback();\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ waiting until data is transferred so a new 'empty' chunk can be submitted\n\t\t\t\t\t\ttimer = ts::ref(processorProxy.processWithDelay([&, callback = std::move(callback)]\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tflush(std::move(callback));\n\t\t\t\t\t\t}, std::chrono::milliseconds{1}));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tprivate:\n\t\t\t\tconwrap2::ProcessorProxy> processorProxy;\n\t\t\t\tstd::reference_wrapper connection;\n\t\t\t\tstd::string clientID;\n\t\t\t\t\/\/ TODO: parameterize\n\t\t\t\tutil::BufferedAsyncWriter bufferedWriter;\n\t\t\t\tstd::unique_ptr encoderPtr;\n\t\t\t\t\/\/ TODO: implement more guards based on running\n\t\t\t\tbool running{false};\n\t\t\t\tts::optional_ref timer{ts::nullopt};\n\t\t\t\tutil::BigInteger framesProvided{0};\n\t\t};\n\t}\n}\nFixed a bug with End-of-Stream processing\/*\n * Copyright 2017, Andrej Kislovskij\n *\n * This is PUBLIC DOMAIN software so use at your own risk as it comes\n * with no warranties. This code is yours to share, use and modify without\n * any restrictions or obligations.\n *\n * For more information see conwrap\/LICENSE or refer refer to http:\/\/unlicense.org\n *\n * Author: gimesketvirtadieni at gmail dot com (Andrej Kislovskij)\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \/\/ std::stringstream\n#include \n#include \n\n#include \"slim\/Chunk.hpp\"\n#include \"slim\/EncoderBase.hpp\"\n#include \"slim\/EncoderBuilder.hpp\"\n#include \"slim\/log\/log.hpp\"\n#include \"slim\/util\/BigInteger.hpp\"\n#include \"slim\/util\/BufferedAsyncWriter.hpp\"\n\n\nnamespace slim\n{\n\tnamespace proto\n\t{\n\t\tnamespace ts = type_safe;\n\n\t\ttemplate\n\t\tclass StreamingSession\n\t\t{\n\t\t\tpublic:\n\t\t\t\tStreamingSession(conwrap2::ProcessorProxy> pp, std::reference_wrapper co, std::string id, EncoderBuilder eb)\n\t\t\t\t: processorProxy{pp}\n\t\t\t\t, connection{co}\n\t\t\t\t, clientID{id}\n\t\t\t\t, bufferedWriter{co}\n\t\t\t\t{\n\t\t\t\t\tLOG(DEBUG) << LABELS{\"proto\"} << \"HTTP session object was created (id=\" << this << \")\";\n\n\t\t\t\t\teb.setEncodedCallback([&](auto* data, auto size)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ do not feed writer with more data if there is no room in transfer buffer\n\t\t\t\t\t\tif (bufferedWriter.isBufferAvailable())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbufferedWriter.writeAsync(data, size, [](auto error, auto written) {});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tLOG(WARNING) << LABELS{\"proto\"} << \"Transfer buffer is full - skipping encoded chunk\";\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tencoderPtr = std::move(eb.build());\n\t\t\t\t\tencoderPtr->start();\n\n\t\t\t\t\t\/\/ creating response string\n\t\t\t\t\tstd::stringstream ss;\n\t\t\t\t\tss << \"HTTP\/1.1 200 OK\\r\\n\"\n\t\t\t\t\t << \"Server: SlimStreamer (\"\n\t\t\t\t\t \/\/ TODO: provide version to the constructor\n\t\t\t\t\t << VERSION\n\t\t\t\t\t << \")\\r\\n\"\n\t\t\t\t\t << \"Connection: close\\r\\n\"\n\t\t\t\t\t << \"Content-Type: \" << encoderPtr->getMIME() << \"\\r\\n\"\n\t\t\t\t\t << \"\\r\\n\";\n\n\t\t\t\t\t\/\/ sending response string\n\t\t\t\t\tconnection.get().write(ss.str());\n\t\t\t\t}\n\n\t\t\t\t~StreamingSession()\n\t\t\t\t{\n\t\t\t\t\t\/\/ canceling deferred operation\n\t\t\t\t\tts::with(timer, [&](auto& timer)\n\t\t\t\t\t{\n\t\t\t\t\t\ttimer.cancel();\n\t\t\t\t\t});\n\n\t\t\t\t\tLOG(DEBUG) << LABELS{\"proto\"} << \"HTTP session object was deleted (id=\" << this << \")\";\n\t\t\t\t}\n\n\t\t\t\tStreamingSession(const StreamingSession&) = delete; \/\/ non-copyable\n\t\t\t\tStreamingSession& operator=(const StreamingSession&) = delete; \/\/ non-assignable\n\t\t\t\tStreamingSession(StreamingSession&& rhs) = delete; \/\/ non-movable\n\t\t\t\tStreamingSession& operator=(StreamingSession&& rhs) = delete; \/\/ non-movable-assignable\n\n\t\t\t\tinline auto getClientID()\n\t\t\t\t{\n\t\t\t\t\treturn clientID;\n\t\t\t\t}\n\n\t\t\t\tinline auto getFramesProvided()\n\t\t\t\t{\n\t\t\t\t\treturn framesProvided;\n\t\t\t\t}\n\n\t\t\t\tinline bool isRunning()\n\t\t\t\t{\n\t\t\t\t\treturn running;\n\t\t\t\t}\n\n\t\t\t\tinline void onRequest(unsigned char* data, std::size_t size)\n\t\t\t\t{\n\t\t\t\t\t\/\/ TODO: make more strick validation\n\t\t\t\t\tstd::string get{\"GET\"};\n\t\t\t\t\tstd::string s{(char*)data, get.size()};\n\t\t\t\t\tif (get.compare(s))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ stopping this session due an error\n\t\t\t\t\t\tLOG(WARNING) << LABELS{\"proto\"} << \"Wrong HTTP method provided\";\n\t\t\t\t\t\tstop([] {});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tstatic auto parseClientID(std::string header)\n\t\t\t\t{\n\t\t\t\t\tauto result{ts::optional{ts::nullopt}};\n\t\t\t\t\tauto separator{std::string{\"=\"}};\n\t\t\t\t\tauto index{header.find(separator)};\n\n\t\t\t\t\tif (index != std::string::npos)\n\t\t\t\t\t{\n\t\t\t\t\t\tresult = std::string{header.c_str() + index + separator.length(), header.length() - index - separator.length()};\n\t\t\t\t\t}\n\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tinline void start()\n\t\t\t\t{\n\t\t\t\t\trunning = true;\n\t\t\t\t}\n\n\t\t\t\ttemplate \n\t\t\t\tinline void stop(CallbackType callback)\n\t\t\t\t{\n\t\t\t\t\tif (running)\n\t\t\t\t\t{\n\t\t\t\t\t\tencoderPtr->stop([&, callback = std::move(callback)]\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tflush([&, callback = std::move(callback)]\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\trunning = false;\n\t\t\t\t\t\t\t\tcallback();\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcallback();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tinline void streamChunk(const Chunk& chunk)\n\t\t\t\t{\n\t\t\t\t\tif (chunk.getSamplingRate() == encoderPtr->getSamplingRate())\n\t\t\t\t\t{\n\t\t\t\t\t\tencoderPtr->encode(chunk.getData(), chunk.getSize());\n\t\t\t\t\t\tframesProvided += chunk.getFrames();\n\n\t\t\t\t\t\tif (chunk.isEndOfStream())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ stopping this session\n\t\t\t\t\t\t\tstop([&]\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconnection.get().stop();\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tLOG(ERROR) << LABELS{\"proto\"} << \"Closing HTTP connection due to different sampling rate used by a client (session rate=\" << encoderPtr->getSamplingRate() << \"; data rate=\" << chunk.getSamplingRate() << \")\";\n\n\t\t\t\t\t\t\/\/ stopping this session\n\t\t\t\t\t\tstop([&]\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconnection.get().stop();\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tprotected:\n\t\t\t\ttemplate \n\t\t\t\tvoid flush(CallbackType callback)\n\t\t\t\t{\n\t\t\t\t\tif (bufferedWriter.isBufferAvailable())\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ submitting an 'empty' chunk so that a callback gets invoked when all data has been transferred\n\t\t\t\t\t\tbufferedWriter.writeAsync(nullptr, 0, [callback = std::move(callback)](auto error, auto written)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcallback();\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ waiting until data is transferred so a new 'empty' chunk can be submitted\n\t\t\t\t\t\ttimer = ts::ref(processorProxy.processWithDelay([&, callback = std::move(callback)]\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tflush(std::move(callback));\n\t\t\t\t\t\t}, std::chrono::milliseconds{1}));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tprivate:\n\t\t\t\tconwrap2::ProcessorProxy> processorProxy;\n\t\t\t\tstd::reference_wrapper connection;\n\t\t\t\tstd::string clientID;\n\t\t\t\t\/\/ TODO: parameterize\n\t\t\t\tutil::BufferedAsyncWriter bufferedWriter;\n\t\t\t\tstd::unique_ptr encoderPtr;\n\t\t\t\t\/\/ TODO: implement more guards based on running\n\t\t\t\tbool running{false};\n\t\t\t\tts::optional_ref timer{ts::nullopt};\n\t\t\t\tutil::BigInteger framesProvided{0};\n\t\t};\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n msn p2p protocol\n\n Copyright (c) 2003-2005 by Olivier Goffart \n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n\n#include \"msnp2p.h\"\n#include \"msnp2pdisplatcher.h\"\n#include \"msnp2pincoming.h\"\n\n\n\/\/ qt\n#include \n#include \n#include \n\n\/\/ kde\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/kopete\n#include \n\nMSNP2PIncoming::MSNP2PIncoming( unsigned long int sessionID , MSNP2PDisplatcher *parent )\n\t: MSNP2P(sessionID , parent)\n{\n\tm_file=0l;\n\tm_Rfile=0L;\n\tm_kopeteTransfer=0L;\n}\n\nMSNP2PIncoming::~MSNP2PIncoming()\n{\n\tif(m_kopeteTransfer)\n\t{\n\t\tm_kopeteTransfer->slotError( KIO::ERR_INTERNAL , i18n(\"Connection closed\") );\n\t}\n\n\tif(m_file)\n\t\tdelete m_file;\n\telse\n\t\tdelete m_Rfile;\n}\n\n\n\nvoid MSNP2PIncoming::parseMessage(MessageStruct &msgStr)\n{\n\tMSNP2P::parseMessage(msgStr);\n\n\tif(m_Rfile) \/\/we are already downloading something to this file\n\t{\t\t\t\/\/m_file->file()->writeBlock( (msg.data()+startBinHeader+48) , dataMessageSize );\n\t\tm_Rfile->writeBlock( (msgStr.message.data()+48) , msgStr.dataMessageSize );\n\n\t\tif(m_kopeteTransfer)\n\t\t\tm_kopeteTransfer->slotProcessed( msgStr.dataOffset+msgStr.dataMessageSize );\n\n\t\tif(msgStr.dataOffset+msgStr.dataMessageSize >= msgStr.totalSize) \/\/the file is complete\n\t\t{\n\t\t\tif(m_file)\n\t\t\t{\n\t\t\t\tm_file->close();\n\t\t\t\tm_parent->fileReceived(m_file , m_obj);\n\t\t\t\tm_file=0;\n\t\t\t\tm_Rfile=0L;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(m_kopeteTransfer) m_kopeteTransfer->slotComplete();\n\t\t\t\tm_Rfile->close();\n\t\t\t\tdelete m_Rfile;\n\t\t\t\tm_Rfile=0L;\n\t\t\t}\n\/*\n\t\t\tdelete m_file;*\/\n\n\t\t\t\t\/\/send the bye message\n\t\t\tmakeMSNSLPMessage(BYE, QString::null);\n\n\t\t\tm_parent->finished(this);\n\t\t\t\t\/\/deleteLater();\n\t\t}\n\t}\n\telse if(msgStr.message.data()[48] == '\\0' )\n\t{ \/\/This can be only the data preparaion message. prepare to download\n\t\tm_file=new KTempFile( locateLocal( \"tmp\", \"msnpicture-\" ), \".png\" );\n\t\tm_file->setAutoDelete(true);\n\t\tm_Rfile=m_file->file();\n\n\t}\n\telse\n\t{\n\t\tQString dataMessage=QCString((msgStr.message.data()+48) , msgStr.dataMessageSize);\n\t\tkdDebug(14141) << k_funcinfo <<\" dataMessage: \" << dataMessage << endl;\n\n\t\tif (dataMessage.contains(\"INVITE\") )\n\t\t{\n\t\t\tif(! m_kopeteTransfer )\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\/\/Parse the message to get some info for replying\n\t\t\tQRegExp rx(\";branch=\\\\{([0-9A-F\\\\-]*)\\\\}\\r\\n\");\n\t\t\trx.search( dataMessage );\n\t\t\tm_branch=rx.cap(1);\n\n\t\t\trx=QRegExp(\"Call-ID: \\\\{([0-9A-F\\\\-]*)\\\\}\\r\\n\");\n\t\t\trx.search( dataMessage );\n\t\t\tm_CallID=rx.cap(1);\n\n\t\t \/\/dirrect connection is not yet implemented, use the connection via MSNP2P\n\t\t\tQString content=\"Bridge: TCPv1\\r\\n\"\n\t\t\t\t\t\"Listening: false\\r\\n\"\n\t\t\t\t\t\"Nonce: {00000000-0000-0000-0000-000000000000}\\r\\n\\r\\n\";\n\n\t\t\tmakeMSNSLPMessage(OK, content);\n\n\t\t\tm_Rfile=new QFile( m_kopeteTransfer->destinationURL().path() );\n\t\t\tif(!m_Rfile->open(IO_WriteOnly))\n\t\t\t{\n\t\t\t\tif(m_kopeteTransfer)\n\t\t\t\t{\n\t\t\t\t\t\t\t\/\/TODO: handle the QFILE error\n\t\t\t\t\tm_kopeteTransfer->slotError( KIO::ERR_CANNOT_OPEN_FOR_WRITING , i18n(\"Cannot open file for writing\") );\n\t\t\t\t\tm_kopeteTransfer=0L;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tabortCurrentTransfer();\n\t\t\t}\n\t\t}\n\t\telse if (dataMessage.contains(\"BYE\"))\n\t\t{\n\t\t\tabortCurrentTransfer();\n\t\t}\n\t\telse if(dataMessage.contains(\"200 OK\"))\n\t\t{\n\t\t\t\/\/ignore\n\t\t}\n\t\telse\n\t\t{ \/\/this seems to be _probably_ (just a guess) a utf-16 message. we will download it completely.\n\t\t\t\/*\n\t\t\t * The message looks like this:\n\t\t\t *\n\t\t\tMIME-Version: 1.0\n\t\t\tContent-Type: image\/gif\n\t\t\t\\0\n\t\t\tbase64:[ENCODED-IMAGE]\n\t\t\t * Sometimes, the base64 ends with = sometimes it does not.\n\t\t\t *\/\n\n\t\t\tif(msgStr.dataOffset ==0)\n\t\t\t\tfullContentMessage=QString::null;\n\n\n\t\t\t\/*\n\t\t\t * The following line doesn't works, because, wihtout reason i understand, the string contains some \\0\n\t\t\t * (\\0\\0 in utf-16) between the Content-Type: and the Base64:\n\n\t\t\tQTextCodec *codec = QTextCodec::codecForName(\"ISO-10646-UCS-2\");\n\t\t\tif(!codec)\n\t\t\treturn; \/\/abort();\n\t\t\tfullContentMessage += codec->toUnicode(msg.data()+startBinHeader+48-1 , dataMessageSize)\n\n\n\t\t\t * Quick hack to parse utf-16 and remove \\0\\0 :\n\t\t\t * The message shouldn't contains non ASCII char (it's base64) so i think i could do like that.\n\t\t\t * FIXME: yes, this is not 100% correct\n\t\t\t *\/\n\t\t\tfor(unsigned int f= 48 ; f < 48 + msgStr.dataMessageSize ; f+=2)\n\t\t\t{\n\t\t\t\tif(msgStr.message[f] != 0)\n\t\t\t\t{\n\t\t\t\t\tfullContentMessage+=QChar( msgStr.message[f] );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/the message may be splitted\n\t\t\tif(msgStr.dataOffset+msgStr.dataMessageSize >= msgStr.totalSize)\n\t\t\t{ \/\/whe have the whole\n\n\t\t\t\tkdDebug(14141) << k_funcinfo <<\"Analyse the image message: \" << fullContentMessage << endl;\n\n\t\t\t\tQString ext;\n\t\t\t\tQRegExp rx(\"Content-Type: ([a-zA-Z0-9\/]*)\");\n\t\t\t\tif( rx.search( fullContentMessage ) != -1 )\n\t\t\t\t{\n\t\t\t\t\tQString contentType=rx.cap(1);\n\t\t\t\t\tif(contentType==\"image\/gif\")\n\t\t\t\t\t\text=\".gif\";\n\t\t\t\t\telse if(contentType==\"image\/png\")\n\t\t\t\t\t\text=\".png\";\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tkdWarning(14140) << k_funcinfo << contentType << \" is not recognized. A MSN message is not displayed\" << endl;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn;\n\n\t\t\t\trx=QRegExp(\"base64:([a-zA-Z0-9+\\\\-.*\/!]*)\");\n\t\t\t\tif( rx.search( fullContentMessage ) != -1 )\n\t\t\t\t{\n\t\t\t\t\tQString base64=rx.cap(1);\n\n\t\t\t\t\tQByteArray image;\n\t\t\t\t\tKCodecs::base64Decode( base64.utf8() , image );\n\n\t\t\t\t\tKTempFile *imageFile=new KTempFile( locateLocal( \"tmp\", \"msntypewrite-\" ), ext );\n\t\t\t\t\timageFile->setAutoDelete(true);\n\t\t\t\t\timageFile->file()->writeBlock( image.data() , image.size() );\n\t\t\t\t\timageFile->file()->close();\n\n\t\t\t\t\tm_parent->fileReceived( imageFile , \"typewrite\" );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n\nvoid MSNP2PIncoming::abortCurrentTransfer()\n{\n\tif(m_kopeteTransfer)\n\t{\n\t\tdelete m_Rfile;\n\t\tm_Rfile=0L;\n\n\t\t\/\/this need to be reseted before sending the BYE message.\n\t\tm_totalDataSize=0;\n\t\tm_offset=0;\n\t\tm_footer='\\0';\n\n\t\t\/\/FIXME: i'm not sure it's like that i should abort the transfer.\n\t\tmakeMSNSLPMessage(BYE, \"\\r\\n\\r\\n\" );\n\t}\n\tm_parent->finished(this);\n}\n\n\nvoid MSNP2PIncoming::slotKopeteTransferDestroyed()\n{\n\tm_kopeteTransfer=0L;\n\tkdDebug(14140) << k_funcinfo << endl;\n}\n\nvoid MSNP2PIncoming::error()\n{\n\tMSNP2P::error();\n\n\tif(m_kopeteTransfer)\n\t{\n\t\tm_kopeteTransfer->slotError( KIO::ERR_INTERNAL , i18n(\"Malformed packet received\") );\n\t\tm_kopeteTransfer=0L;\n\t}\n}\n\n#include \"msnp2pincoming.moc\"\nmake sure this is the data preparation message\/*\n msn p2p protocol\n\n Copyright (c) 2003-2005 by Olivier Goffart \n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n\n#include \"msnp2p.h\"\n#include \"msnp2pdisplatcher.h\"\n#include \"msnp2pincoming.h\"\n\n\n\/\/ qt\n#include \n#include \n#include \n\n\/\/ kde\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/kopete\n#include \n\nMSNP2PIncoming::MSNP2PIncoming( unsigned long int sessionID , MSNP2PDisplatcher *parent )\n\t: MSNP2P(sessionID , parent)\n{\n\tm_file=0l;\n\tm_Rfile=0L;\n\tm_kopeteTransfer=0L;\n}\n\nMSNP2PIncoming::~MSNP2PIncoming()\n{\n\tif(m_kopeteTransfer)\n\t{\n\t\tm_kopeteTransfer->slotError( KIO::ERR_INTERNAL , i18n(\"Connection closed\") );\n\t}\n\n\tif(m_file)\n\t\tdelete m_file;\n\telse\n\t\tdelete m_Rfile;\n}\n\n\n\nvoid MSNP2PIncoming::parseMessage(MessageStruct &msgStr)\n{\n\tMSNP2P::parseMessage(msgStr);\n\n\tif(m_Rfile) \/\/we are already downloading something to this file\n\t{\t\t\t\/\/m_file->file()->writeBlock( (msg.data()+startBinHeader+48) , dataMessageSize );\n\t\tm_Rfile->writeBlock( (msgStr.message.data()+48) , msgStr.dataMessageSize );\n\n\t\tif(m_kopeteTransfer)\n\t\t\tm_kopeteTransfer->slotProcessed( msgStr.dataOffset+msgStr.dataMessageSize );\n\n\t\tif(msgStr.dataOffset+msgStr.dataMessageSize >= msgStr.totalSize) \/\/the file is complete\n\t\t{\n\t\t\tif(m_file)\n\t\t\t{\n\t\t\t\tm_file->close();\n\t\t\t\tm_parent->fileReceived(m_file , m_obj);\n\t\t\t\tm_file=0;\n\t\t\t\tm_Rfile=0L;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(m_kopeteTransfer) m_kopeteTransfer->slotComplete();\n\t\t\t\tm_Rfile->close();\n\t\t\t\tdelete m_Rfile;\n\t\t\t\tm_Rfile=0L;\n\t\t\t}\n\/*\n\t\t\tdelete m_file;*\/\n\n\t\t\t\t\/\/send the bye message\n\t\t\tmakeMSNSLPMessage(BYE, QString::null);\n\n\t\t\tm_parent->finished(this);\n\t\t\t\t\/\/deleteLater();\n\t\t}\n\t}\n\telse if(msgStr.message.data()[48] == '\\0' && msgStr.dataMessageSize==4)\n\t{ \/\/This can be only the data preparaion message. prepare to download\n\t\tm_file=new KTempFile( locateLocal( \"tmp\", \"msnpicture-\" ), \".png\" );\n\t\tm_file->setAutoDelete(true);\n\t\tm_Rfile=m_file->file();\n\n\t}\n\telse\n\t{\n\t\tQString dataMessage=QCString((msgStr.message.data()+48) , msgStr.dataMessageSize);\n\t\tkdDebug(14141) << k_funcinfo <<\" dataMessage: \" << dataMessage << endl;\n\n\t\tif (dataMessage.contains(\"INVITE\") )\n\t\t{\n\t\t\tif(! m_kopeteTransfer )\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\/\/Parse the message to get some info for replying\n\t\t\tQRegExp rx(\";branch=\\\\{([0-9A-F\\\\-]*)\\\\}\\r\\n\");\n\t\t\trx.search( dataMessage );\n\t\t\tm_branch=rx.cap(1);\n\n\t\t\trx=QRegExp(\"Call-ID: \\\\{([0-9A-F\\\\-]*)\\\\}\\r\\n\");\n\t\t\trx.search( dataMessage );\n\t\t\tm_CallID=rx.cap(1);\n\n\t\t \/\/dirrect connection is not yet implemented, use the connection via MSNP2P\n\t\t\tQString content=\"Bridge: TCPv1\\r\\n\"\n\t\t\t\t\t\"Listening: false\\r\\n\"\n\t\t\t\t\t\"Nonce: {00000000-0000-0000-0000-000000000000}\\r\\n\\r\\n\";\n\n\t\t\tmakeMSNSLPMessage(OK, content);\n\n\t\t\tm_Rfile=new QFile( m_kopeteTransfer->destinationURL().path() );\n\t\t\tif(!m_Rfile->open(IO_WriteOnly))\n\t\t\t{\n\t\t\t\tif(m_kopeteTransfer)\n\t\t\t\t{\n\t\t\t\t\t\t\t\/\/TODO: handle the QFILE error\n\t\t\t\t\tm_kopeteTransfer->slotError( KIO::ERR_CANNOT_OPEN_FOR_WRITING , i18n(\"Cannot open file for writing\") );\n\t\t\t\t\tm_kopeteTransfer=0L;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tabortCurrentTransfer();\n\t\t\t}\n\t\t}\n\t\telse if (dataMessage.contains(\"BYE\"))\n\t\t{\n\t\t\tabortCurrentTransfer();\n\t\t}\n\t\telse if(dataMessage.contains(\"200 OK\"))\n\t\t{\n\t\t\t\/\/ignore\n\t\t}\n\t\telse\n\t\t{ \/\/this seems to be _probably_ (just a guess) a utf-16 message. we will download it completely.\n\t\t\t\/*\n\t\t\t * The message looks like this:\n\t\t\t *\n\t\t\tMIME-Version: 1.0\n\t\t\tContent-Type: image\/gif\n\t\t\t\\0\n\t\t\tbase64:[ENCODED-IMAGE]\n\t\t\t * Sometimes, the base64 ends with = sometimes it does not.\n\t\t\t *\/\n\n\t\t\tif(msgStr.dataOffset ==0)\n\t\t\t\tfullContentMessage=QString::null;\n\n\n\t\t\t\/*\n\t\t\t * The following line doesn't works, because, wihtout reason i understand, the string contains some \\0\n\t\t\t * (\\0\\0 in utf-16) between the Content-Type: and the Base64:\n\n\t\t\tQTextCodec *codec = QTextCodec::codecForName(\"ISO-10646-UCS-2\");\n\t\t\tif(!codec)\n\t\t\treturn; \/\/abort();\n\t\t\tfullContentMessage += codec->toUnicode(msg.data()+startBinHeader+48-1 , dataMessageSize)\n\n\n\t\t\t * Quick hack to parse utf-16 and remove \\0\\0 :\n\t\t\t * The message shouldn't contains non ASCII char (it's base64) so i think i could do like that.\n\t\t\t * FIXME: yes, this is not 100% correct\n\t\t\t *\/\n\t\t\tfor(unsigned int f= 48 ; f < 48 + msgStr.dataMessageSize ; f+=2)\n\t\t\t{\n\t\t\t\tif(msgStr.message[f] != 0)\n\t\t\t\t{\n\t\t\t\t\tfullContentMessage+=QChar( msgStr.message[f] );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/the message may be splitted\n\t\t\tif(msgStr.dataOffset+msgStr.dataMessageSize >= msgStr.totalSize)\n\t\t\t{ \/\/whe have the whole\n\n\t\t\t\tkdDebug(14141) << k_funcinfo <<\"Analyse the image message: \" << fullContentMessage << endl;\n\n\t\t\t\tQString ext;\n\t\t\t\tQRegExp rx(\"Content-Type: ([a-zA-Z0-9\/]*)\");\n\t\t\t\tif( rx.search( fullContentMessage ) != -1 )\n\t\t\t\t{\n\t\t\t\t\tQString contentType=rx.cap(1);\n\t\t\t\t\tif(contentType==\"image\/gif\")\n\t\t\t\t\t\text=\".gif\";\n\t\t\t\t\telse if(contentType==\"image\/png\")\n\t\t\t\t\t\text=\".png\";\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tkdWarning(14140) << k_funcinfo << contentType << \" is not recognized. A MSN message is not displayed\" << endl;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn;\n\n\t\t\t\trx=QRegExp(\"base64:([a-zA-Z0-9+\\\\-.*\/!]*)\");\n\t\t\t\tif( rx.search( fullContentMessage ) != -1 )\n\t\t\t\t{\n\t\t\t\t\tQString base64=rx.cap(1);\n\n\t\t\t\t\tQByteArray image;\n\t\t\t\t\tKCodecs::base64Decode( base64.utf8() , image );\n\n\t\t\t\t\tKTempFile *imageFile=new KTempFile( locateLocal( \"tmp\", \"msntypewrite-\" ), ext );\n\t\t\t\t\timageFile->setAutoDelete(true);\n\t\t\t\t\timageFile->file()->writeBlock( image.data() , image.size() );\n\t\t\t\t\timageFile->file()->close();\n\n\t\t\t\t\tm_parent->fileReceived( imageFile , \"typewrite\" );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n\nvoid MSNP2PIncoming::abortCurrentTransfer()\n{\n\tif(m_kopeteTransfer)\n\t{\n\t\tdelete m_Rfile;\n\t\tm_Rfile=0L;\n\n\t\t\/\/this need to be reseted before sending the BYE message.\n\t\tm_totalDataSize=0;\n\t\tm_offset=0;\n\t\tm_footer='\\0';\n\n\t\t\/\/FIXME: i'm not sure it's like that i should abort the transfer.\n\t\tmakeMSNSLPMessage(BYE, \"\\r\\n\\r\\n\" );\n\t}\n\tm_parent->finished(this);\n}\n\n\nvoid MSNP2PIncoming::slotKopeteTransferDestroyed()\n{\n\tm_kopeteTransfer=0L;\n\tkdDebug(14140) << k_funcinfo << endl;\n}\n\nvoid MSNP2PIncoming::error()\n{\n\tMSNP2P::error();\n\n\tif(m_kopeteTransfer)\n\t{\n\t\tm_kopeteTransfer->slotError( KIO::ERR_INTERNAL , i18n(\"Malformed packet received\") );\n\t\tm_kopeteTransfer=0L;\n\t}\n}\n\n#include \"msnp2pincoming.moc\"\n<|endoftext|>"} {"text":"#include \n#include \n\/\/#include \"LessParser.h\"\n#include \"Parser.h\"\nint\tmain() \n{\n\tstd::ifstream fs;\n\tfs.open(\"test1.less\", std::ios::in);\n\t\/\/Tokenizer(fs);\n\tParser lesparser = Parser(Tokenizer(fs));\n\tlesparser.printTree(lesparser.getRootNode());\n\t\/\/lesparser.showTokens();\n\treturn 0;\n}make Parser initialize right#include \n#include \n\/\/#include \"LessParser.h\"\n#include \"Parser.h\"\nint\tmain(int argc, char **argv) \n{\n\tstd::ifstream fs;\n\tfs.open(argv[1], std::ios::in);\n\tTokenizer tokenizer = Tokenizer(fs);\n\tParser lesparser = Parser(tokenizer);\n\tlesparser.printTree(lesparser.getRootNode());\n\t\/\/lesparser.showTokens();\n\treturn 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"codesearch.h\"\n#include \"metrics.h\"\n#include \"git_indexer.h\"\n#include \"smart_git.h\"\n#include \"debug.h\"\n\nnamespace {\n metric git_walk(\"timer.git.walk\");\n metric git_contents(\"timer.git.contents\");\n};\n\nusing namespace std;\n\nDEFINE_string(order_root, \"\", \"Walk top-level directories in this order.\");\nDEFINE_bool(revparse, false, \"Display parsed revisions, rather than as-provided\");\n\ngit_indexer::git_indexer(code_searcher *cs,\n const string& repopath,\n const string& name,\n json_object *metadata)\n : cs_(cs), repo_(0), name_(name), metadata_(metadata) {\n git_repository_open(&repo_, repopath.c_str());\n if (repo_ == NULL) {\n fprintf(stderr, \"Unable to open repo: %s\\n\", repopath.c_str());\n exit(1);\n }\n idx_repo_ = cs_->open_repo(name, metadata);\n\n int err;\n if ((err = git_threads_init()) != 0)\n die(\"git_threads_init: %s\", giterr_last()->message);\n git_libgit2_opts(GIT_OPT_SET_CACHE_OBJECT_LIMIT, GIT_OBJ_BLOB, 10*1024);\n git_libgit2_opts(GIT_OPT_SET_CACHE_OBJECT_LIMIT, GIT_OBJ_OFS_DELTA, 10*1024);\n git_libgit2_opts(GIT_OPT_SET_CACHE_OBJECT_LIMIT, GIT_OBJ_REF_DELTA, 10*1024);\n}\n\ngit_indexer::~git_indexer() {\n git_repository_free(repo_);\n}\n\nvoid git_indexer::walk(const string& ref) {\n smart_object commit;\n smart_object tree;\n git_revparse_single(commit, repo_, (ref + \"^0\").c_str());\n git_commit_tree(tree, commit);\n\n char oidstr[GIT_OID_HEXSZ+1];\n string name = FLAGS_revparse ?\n strdup(git_oid_tostr(oidstr, sizeof(oidstr), git_commit_id(commit))) : ref;\n if (name_.size())\n name = name_ + \":\" + name;\n\n idx_tree_ = cs_->open_revision(idx_repo_, ref);\n walk_root(name, tree);\n}\n\nvoid git_indexer::walk_root(const string& ref, git_tree *tree) {\n metric::timer tm_walk(git_walk);\n map root;\n vector ordered;\n int entries = git_tree_entrycount(tree);\n for (int i = 0; i < entries; ++i) {\n const git_tree_entry *ent = git_tree_entry_byindex(tree, i);\n root[git_tree_entry_name(ent)] = ent;\n }\n\n istringstream stream(FLAGS_order_root);\n string dir;\n while(stream >> dir) {\n map::iterator it = root.find(dir);\n if (it == root.end())\n continue;\n ordered.push_back(it->second);\n root.erase(it);\n }\n for (map::iterator it = root.begin();\n it != root.end(); ++it)\n ordered.push_back(it->second);\n for (vector::iterator it = ordered.begin();\n it != ordered.end(); ++it) {\n smart_object obj;\n git_tree_entry_to_object(obj, repo_, *it);\n string path = string(git_tree_entry_name(*it));\n tm_walk.pause();\n\n if (git_tree_entry_type(*it) == GIT_OBJ_TREE) {\n walk_tree(ref, path + \"\/\", obj);\n } else if (git_tree_entry_type(*it) == GIT_OBJ_BLOB) {\n metric::timer tm_content(git_contents);\n const char *data = static_cast(git_blob_rawcontent(obj));\n cs_->index_file(idx_tree_, path, StringPiece(data, git_blob_rawsize(obj)));\n }\n tm_walk.start();\n }\n}\n\nvoid git_indexer::walk_tree(const string& ref,\n const string& pfx,\n git_tree *tree) {\n metric::timer tm_walk(git_walk);\n string path;\n int entries = git_tree_entrycount(tree);\n int i;\n for (i = 0; i < entries; i++) {\n const git_tree_entry *ent = git_tree_entry_byindex(tree, i);\n path = pfx + git_tree_entry_name(ent);\n smart_object obj;\n git_tree_entry_to_object(obj, repo_, ent);\n tm_walk.pause();\n if (git_tree_entry_type(ent) == GIT_OBJ_TREE) {\n walk_tree(ref, path + \"\/\", obj);\n } else if (git_tree_entry_type(ent) == GIT_OBJ_BLOB) {\n metric::timer tm_contents(git_contents);\n const char *data = static_cast(git_blob_rawcontent(obj));\n cs_->index_file(idx_tree_, path, StringPiece(data, git_blob_rawsize(obj)));\n }\n tm_walk.start();\n }\n}\nlibgit2: init threads before using libgit2#include \n#include \n\n#include \"codesearch.h\"\n#include \"metrics.h\"\n#include \"git_indexer.h\"\n#include \"smart_git.h\"\n#include \"debug.h\"\n\nnamespace {\n metric git_walk(\"timer.git.walk\");\n metric git_contents(\"timer.git.contents\");\n};\n\nusing namespace std;\n\nDEFINE_string(order_root, \"\", \"Walk top-level directories in this order.\");\nDEFINE_bool(revparse, false, \"Display parsed revisions, rather than as-provided\");\n\ngit_indexer::git_indexer(code_searcher *cs,\n const string& repopath,\n const string& name,\n json_object *metadata)\n : cs_(cs), repo_(0), name_(name), metadata_(metadata) {\n int err;\n if ((err = git_threads_init()) != 0)\n die(\"git_threads_init: %s\", giterr_last()->message);\n\n git_repository_open(&repo_, repopath.c_str());\n if (repo_ == NULL) {\n fprintf(stderr, \"Unable to open repo: %s\\n\", repopath.c_str());\n exit(1);\n }\n idx_repo_ = cs_->open_repo(name, metadata);\n\n git_libgit2_opts(GIT_OPT_SET_CACHE_OBJECT_LIMIT, GIT_OBJ_BLOB, 10*1024);\n git_libgit2_opts(GIT_OPT_SET_CACHE_OBJECT_LIMIT, GIT_OBJ_OFS_DELTA, 10*1024);\n git_libgit2_opts(GIT_OPT_SET_CACHE_OBJECT_LIMIT, GIT_OBJ_REF_DELTA, 10*1024);\n}\n\ngit_indexer::~git_indexer() {\n git_repository_free(repo_);\n}\n\nvoid git_indexer::walk(const string& ref) {\n smart_object commit;\n smart_object tree;\n git_revparse_single(commit, repo_, (ref + \"^0\").c_str());\n git_commit_tree(tree, commit);\n\n char oidstr[GIT_OID_HEXSZ+1];\n string name = FLAGS_revparse ?\n strdup(git_oid_tostr(oidstr, sizeof(oidstr), git_commit_id(commit))) : ref;\n if (name_.size())\n name = name_ + \":\" + name;\n\n idx_tree_ = cs_->open_revision(idx_repo_, ref);\n walk_root(name, tree);\n}\n\nvoid git_indexer::walk_root(const string& ref, git_tree *tree) {\n metric::timer tm_walk(git_walk);\n map root;\n vector ordered;\n int entries = git_tree_entrycount(tree);\n for (int i = 0; i < entries; ++i) {\n const git_tree_entry *ent = git_tree_entry_byindex(tree, i);\n root[git_tree_entry_name(ent)] = ent;\n }\n\n istringstream stream(FLAGS_order_root);\n string dir;\n while(stream >> dir) {\n map::iterator it = root.find(dir);\n if (it == root.end())\n continue;\n ordered.push_back(it->second);\n root.erase(it);\n }\n for (map::iterator it = root.begin();\n it != root.end(); ++it)\n ordered.push_back(it->second);\n for (vector::iterator it = ordered.begin();\n it != ordered.end(); ++it) {\n smart_object obj;\n git_tree_entry_to_object(obj, repo_, *it);\n string path = string(git_tree_entry_name(*it));\n tm_walk.pause();\n\n if (git_tree_entry_type(*it) == GIT_OBJ_TREE) {\n walk_tree(ref, path + \"\/\", obj);\n } else if (git_tree_entry_type(*it) == GIT_OBJ_BLOB) {\n metric::timer tm_content(git_contents);\n const char *data = static_cast(git_blob_rawcontent(obj));\n cs_->index_file(idx_tree_, path, StringPiece(data, git_blob_rawsize(obj)));\n }\n tm_walk.start();\n }\n}\n\nvoid git_indexer::walk_tree(const string& ref,\n const string& pfx,\n git_tree *tree) {\n metric::timer tm_walk(git_walk);\n string path;\n int entries = git_tree_entrycount(tree);\n int i;\n for (i = 0; i < entries; i++) {\n const git_tree_entry *ent = git_tree_entry_byindex(tree, i);\n path = pfx + git_tree_entry_name(ent);\n smart_object obj;\n git_tree_entry_to_object(obj, repo_, ent);\n tm_walk.pause();\n if (git_tree_entry_type(ent) == GIT_OBJ_TREE) {\n walk_tree(ref, path + \"\/\", obj);\n } else if (git_tree_entry_type(ent) == GIT_OBJ_BLOB) {\n metric::timer tm_contents(git_contents);\n const char *data = static_cast(git_blob_rawcontent(obj));\n cs_->index_file(idx_tree_, path, StringPiece(data, git_blob_rawsize(obj)));\n }\n tm_walk.start();\n }\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n *\n * Copyright 2013-2014 RAD Game Tools and Valve Software\n * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n **************************************************************************\/\n\n\/\/ File: vogl_port_posix.cpp\n\n#if !defined(PLATFORM_POSIX)\n #error \"vogl_port_posix should not be compiled on non-POSIX platforms.\"\n#endif\n\n#include \"vogl_port.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nint plat_chdir(const char* path)\n{\n return chdir(path);\n}\n\nchar* plat_getcwd(char *buffer, int maxlen)\n{\n return getcwd(buffer, maxlen);\n}\n\nconst char* plat_gettmpdir()\n{\n static char s_tmpdir[PATH_MAX];\n\n if (!s_tmpdir[0])\n {\n const char *tmpdir = getenv(\"TMPDIR\");\n\n if (!tmpdir)\n {\n tmpdir = P_tmpdir;\n if (!tmpdir)\n tmpdir = _PATH_TMP;\n }\n\n strncpy(s_tmpdir, tmpdir, sizeof(s_tmpdir));\n s_tmpdir[sizeof(s_tmpdir) - 1] = 0;\n\n \/\/ Remove trailing slash.\n size_t slen = strlen(s_tmpdir);\n if ((slen > 0) && (s_tmpdir[slen - 1] == '\/'))\n s_tmpdir[--slen] = 0;\n }\n\n return s_tmpdir;\n}\n\nchar* plat_gettmpfname(char *buffer, int maxlen, const char *prefix)\n{\n struct timeval cur_time;\n vogl::uint32 rnd32 = plat_rand();\n const char *tmpdir = plat_gettmpdir();\n\n gettimeofday(&cur_time, NULL);\n\n uint64_t time64 = cur_time.tv_sec * 1000000ULL + cur_time.tv_usec;\n\n \/\/ Create a fileiname with THREADID & RAND32 & TIME64.\n snprintf(buffer, maxlen, \"%s\/_%s_%x_%x_%\" PRIx64 \".tmp\", tmpdir, prefix, plat_gettid(), rnd32, time64);\n buffer[maxlen - 1] = 0;\n return buffer;\n}\n\n\/\/ Tests for the existence of the specified path, returns true if it exists and false otherwise.\nbool plat_fexist(const char* path)\n{\n return access(path, F_OK) == 0;\n}\n\npid_t plat_gettid()\n{\n return static_cast(syscall(SYS_gettid));\n}\n\nuint64_t plat_posix_gettid()\n{\n return static_cast(pthread_self());\n}\n\npid_t plat_getpid()\n{\n return getpid();\n}\n\npid_t plat_getppid()\n{\n return getppid();\n}\n\nsize_t plat_rand_s(vogl::uint32* out_array, size_t out_array_length)\n{\n static __thread unsigned int s_seed = 0;\n\n if (s_seed == 0)\n {\n \/\/ Try to seed rand_r() with \/dev\/urandom.\n ssize_t nbytes = 0;\n int fd = open(\"\/dev\/urandom\", O_RDONLY);\n if (fd != -1)\n {\n nbytes = read(fd, &s_seed, sizeof(s_seed));\n close(fd);\n }\n\n \/\/ If that didn't work, fallback to time and thread id.\n if (nbytes != sizeof(s_seed))\n {\n struct timeval time;\n gettimeofday(&time, NULL);\n s_seed = plat_gettid() ^ ((time.tv_sec * 1000) + (time.tv_usec \/ 1000));\n }\n }\n\n for (size_t i = 0; i < out_array_length; ++i)\n out_array[i] = rand_r(&s_seed);\n\n return out_array_length;\n}\n\nvogl::uint32 plat_rand()\n{\n vogl::uint32 num;\n plat_rand_s(&num, 1);\n return num;\n}\n\n\/\/ Returns the size of a virtual page of memory.\nvogl::int32 plat_get_virtual_page_size()\n{\n return sysconf(_SC_PAGE_SIZE);\n}\n\nstatic int get_prot_from_access(vogl::uint32 access_flags)\n{\n int ret_flags = 0;\n if ((access_flags & PLAT_WRITE) == PLAT_WRITE)\n {\n ret_flags |= PROT_WRITE;\n access_flags &= ~PLAT_WRITE;\n }\n\n if ((access_flags & (PLAT_READ)) == (PLAT_READ))\n {\n ret_flags |= PROT_READ;\n access_flags &= ~(PLAT_READ);\n }\n\n \/\/ If this fires, it means the code above needs to be updated to support the flag being passed in.\n VOGL_VERIFY(access_flags == 0);\n\n return ret_flags;\n}\n\n\nvoid* plat_virtual_alloc(size_t size_requested, vogl::uint32 access_flags, size_t* out_size_provided)\n{\n const int prot = get_prot_from_access(access_flags);\n const int flags = MAP_ANON | MAP_SHARED;\n void *p = mmap(NULL, size_requested, prot, flags, -1, 0);\n\n if ((!p) || (p == MAP_FAILED))\n {\n uint e = errno;\n\n \/\/ Not using strerror_r because it fails when we're completely out of memory.\n char *pError_desc = strerror(e);\n\n char buf[256];\n sprintf(buf, \"%s: mmap() of %zu bytes failed! Reason: %s (errno 0x%x)\\n\", VOGL_FUNCTION_INFO_CSTR, size_requested, pError_desc, e);\n\n write(STDERR_FILENO, buf, strlen(buf));\n abort();\n }\n\n *out_size_provided = size_requested;\n\n return p;\n}\n\nvoid plat_virtual_free(void* free_addr, size_t size)\n{\n int res = munmap(free_addr, size);\n if (res != 0)\n {\n uint e = errno;\n\n \/\/ Not using strerror_r because it fails when we're completely out of memory.\n char *pError_desc = strerror(e);\n\n char buf[256];\n sprintf(buf, \"%s: munmap() free_addr 0x%\" PRIxPTR \" size 0x%\" PRIxPTR \" failed! Reason: %s (errno 0x%x)\\n\", VOGL_FUNCTION_INFO_CSTR, (uintptr_t)free_addr, size, pError_desc, e);\n\n write(STDERR_FILENO, buf, strlen(buf));\n abort();\n }\n}\n\n#if VOGL_USE_PTHREADS_API\n int plat_sem_post(sem_t* sem, vogl::uint32 release_count)\n {\n int status = 0;\n while (release_count > 0)\n {\n status = sem_post(sem);\n if (status)\n break;\n release_count--;\n }\n\n return status;\n }\n\n void plat_try_sem_post(sem_t* sem, vogl::uint32 release_count)\n {\n while (release_count > 0)\n {\n sem_post(sem);\n release_count--;\n }\n }\n#endif\n\nvoid* plat_dlsym(void* handle, const char* symbol)\n{\n return dlsym(handle, symbol);\n}\n\nAdded plat_load_system_gl implementation for posix platforms.\/**************************************************************************\n *\n * Copyright 2013-2014 RAD Game Tools and Valve Software\n * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n **************************************************************************\/\n\n\/\/ File: vogl_port_posix.cpp\n\n#if !defined(PLATFORM_POSIX)\n #error \"vogl_port_posix should not be compiled on non-POSIX platforms.\"\n#endif\n\n#include \"vogl_port.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nint plat_chdir(const char* path)\n{\n return chdir(path);\n}\n\nchar* plat_getcwd(char *buffer, int maxlen)\n{\n return getcwd(buffer, maxlen);\n}\n\nconst char* plat_gettmpdir()\n{\n static char s_tmpdir[PATH_MAX];\n\n if (!s_tmpdir[0])\n {\n const char *tmpdir = getenv(\"TMPDIR\");\n\n if (!tmpdir)\n {\n tmpdir = P_tmpdir;\n if (!tmpdir)\n tmpdir = _PATH_TMP;\n }\n\n strncpy(s_tmpdir, tmpdir, sizeof(s_tmpdir));\n s_tmpdir[sizeof(s_tmpdir) - 1] = 0;\n\n \/\/ Remove trailing slash.\n size_t slen = strlen(s_tmpdir);\n if ((slen > 0) && (s_tmpdir[slen - 1] == '\/'))\n s_tmpdir[--slen] = 0;\n }\n\n return s_tmpdir;\n}\n\nchar* plat_gettmpfname(char *buffer, int maxlen, const char *prefix)\n{\n struct timeval cur_time;\n vogl::uint32 rnd32 = plat_rand();\n const char *tmpdir = plat_gettmpdir();\n\n gettimeofday(&cur_time, NULL);\n\n uint64_t time64 = cur_time.tv_sec * 1000000ULL + cur_time.tv_usec;\n\n \/\/ Create a fileiname with THREADID & RAND32 & TIME64.\n snprintf(buffer, maxlen, \"%s\/_%s_%x_%x_%\" PRIx64 \".tmp\", tmpdir, prefix, plat_gettid(), rnd32, time64);\n buffer[maxlen - 1] = 0;\n return buffer;\n}\n\n\/\/ Tests for the existence of the specified path, returns true if it exists and false otherwise.\nbool plat_fexist(const char* path)\n{\n return access(path, F_OK) == 0;\n}\n\npid_t plat_gettid()\n{\n return static_cast(syscall(SYS_gettid));\n}\n\nuint64_t plat_posix_gettid()\n{\n return static_cast(pthread_self());\n}\n\npid_t plat_getpid()\n{\n return getpid();\n}\n\npid_t plat_getppid()\n{\n return getppid();\n}\n\nsize_t plat_rand_s(vogl::uint32* out_array, size_t out_array_length)\n{\n static __thread unsigned int s_seed = 0;\n\n if (s_seed == 0)\n {\n \/\/ Try to seed rand_r() with \/dev\/urandom.\n ssize_t nbytes = 0;\n int fd = open(\"\/dev\/urandom\", O_RDONLY);\n if (fd != -1)\n {\n nbytes = read(fd, &s_seed, sizeof(s_seed));\n close(fd);\n }\n\n \/\/ If that didn't work, fallback to time and thread id.\n if (nbytes != sizeof(s_seed))\n {\n struct timeval time;\n gettimeofday(&time, NULL);\n s_seed = plat_gettid() ^ ((time.tv_sec * 1000) + (time.tv_usec \/ 1000));\n }\n }\n\n for (size_t i = 0; i < out_array_length; ++i)\n out_array[i] = rand_r(&s_seed);\n\n return out_array_length;\n}\n\nvogl::uint32 plat_rand()\n{\n vogl::uint32 num;\n plat_rand_s(&num, 1);\n return num;\n}\n\n\/\/ Returns the size of a virtual page of memory.\nvogl::int32 plat_get_virtual_page_size()\n{\n return sysconf(_SC_PAGE_SIZE);\n}\n\nstatic int get_prot_from_access(vogl::uint32 access_flags)\n{\n int ret_flags = 0;\n if ((access_flags & PLAT_WRITE) == PLAT_WRITE)\n {\n ret_flags |= PROT_WRITE;\n access_flags &= ~PLAT_WRITE;\n }\n\n if ((access_flags & (PLAT_READ)) == (PLAT_READ))\n {\n ret_flags |= PROT_READ;\n access_flags &= ~(PLAT_READ);\n }\n\n \/\/ If this fires, it means the code above needs to be updated to support the flag being passed in.\n VOGL_VERIFY(access_flags == 0);\n\n return ret_flags;\n}\n\n\nvoid* plat_virtual_alloc(size_t size_requested, vogl::uint32 access_flags, size_t* out_size_provided)\n{\n const int prot = get_prot_from_access(access_flags);\n const int flags = MAP_ANON | MAP_SHARED;\n void *p = mmap(NULL, size_requested, prot, flags, -1, 0);\n\n if ((!p) || (p == MAP_FAILED))\n {\n uint e = errno;\n\n \/\/ Not using strerror_r because it fails when we're completely out of memory.\n char *pError_desc = strerror(e);\n\n char buf[256];\n sprintf(buf, \"%s: mmap() of %zu bytes failed! Reason: %s (errno 0x%x)\\n\", VOGL_FUNCTION_INFO_CSTR, size_requested, pError_desc, e);\n\n write(STDERR_FILENO, buf, strlen(buf));\n abort();\n }\n\n *out_size_provided = size_requested;\n\n return p;\n}\n\nvoid plat_virtual_free(void* free_addr, size_t size)\n{\n int res = munmap(free_addr, size);\n if (res != 0)\n {\n uint e = errno;\n\n \/\/ Not using strerror_r because it fails when we're completely out of memory.\n char *pError_desc = strerror(e);\n\n char buf[256];\n sprintf(buf, \"%s: munmap() free_addr 0x%\" PRIxPTR \" size 0x%\" PRIxPTR \" failed! Reason: %s (errno 0x%x)\\n\", VOGL_FUNCTION_INFO_CSTR, (uintptr_t)free_addr, size, pError_desc, e);\n\n write(STDERR_FILENO, buf, strlen(buf));\n abort();\n }\n}\n\n#if VOGL_USE_PTHREADS_API\n int plat_sem_post(sem_t* sem, vogl::uint32 release_count)\n {\n int status = 0;\n while (release_count > 0)\n {\n status = sem_post(sem);\n if (status)\n break;\n release_count--;\n }\n\n return status;\n }\n\n void plat_try_sem_post(sem_t* sem, vogl::uint32 release_count)\n {\n while (release_count > 0)\n {\n sem_post(sem);\n release_count--;\n }\n }\n#endif\n\nvoid* plat_dlsym(void* handle, const char* symbol)\n{\n return dlsym(handle, symbol);\n}\n\nvoid* plat_load_system_gl(int _flags)\n{\n return dlopen(plat_get_system_gl_module_name(), _flags);\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkRenderWindowInteractor.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkRenderWindowInteractor.hh\"\n#include \"vtkActor.hh\"\n#include \"vtkCellPicker.hh\"\n\n\/\/ Description:\n\/\/ Construct object so that light follows camera motion.\nvtkRenderWindowInteractor::vtkRenderWindowInteractor()\n{\n this->RenderWindow = NULL;\n this->CurrentCamera = NULL;\n this->CurrentLight = NULL;\n this->CurrentRenderer = NULL;\n\n this->LightFollowCamera = 1;\n this->Initialized = 0;\n this->DesiredUpdateRate = 15;\n this->StillUpdateRate = 0;\n \n this->SelfCreatedPicker = 0;\n this->Picker = this->CreateDefaultPicker();\n this->OutlineActor = NULL;\n this->OutlineMapper.SetInput(this->Outline.GetOutput());\n this->PickedRenderer = NULL;\n this->CurrentActor = NULL;\n\n this->StartPickMethod = NULL;\n this->StartPickMethodArgDelete = NULL;\n this->StartPickMethodArg = NULL;\n this->EndPickMethod = NULL;\n this->EndPickMethodArgDelete = NULL;\n this->EndPickMethodArg = NULL;\n this->UserMethod = NULL;\n this->UserMethodArgDelete = NULL;\n this->UserMethodArg = NULL;\n}\n\nvtkRenderWindowInteractor::~vtkRenderWindowInteractor()\n{\n if ( this->OutlineActor ) this->OutlineActor->Delete();\n if ( this->SelfCreatedPicker && this->Picker) this->Picker->Delete();\n}\n\nvoid vtkRenderWindowInteractor::FindPokedRenderer(int x,int y)\n{\n vtkRendererCollection *rc;\n vtkRenderer *aren;\n\n this->CurrentRenderer = NULL;\n\n rc = this->RenderWindow->GetRenderers();\n \n for (rc->InitTraversal(); \n ((aren = rc->GetNextItem())&&(!this->CurrentRenderer));)\n {\n if (aren->IsInViewport(x,y))\n {\n this->CurrentRenderer = aren;\n }\n }\n \n \/\/ we must have a value \n if (this->CurrentRenderer == NULL)\n {\n rc->InitTraversal();\n aren = rc->GetNextItem();\n this->CurrentRenderer = aren;\n }\n}\n\nvoid vtkRenderWindowInteractor::FindPokedCamera(int x,int y)\n{\n float *vp;\n vtkLightCollection *lc;\n\n this->FindPokedRenderer(x,y);\n vp = this->CurrentRenderer->GetViewport();\n\n this->CurrentCamera = this->CurrentRenderer->GetActiveCamera(); \n memcpy(this->Center,this->CurrentRenderer->GetCenter(),sizeof(int)*2);\n this->DeltaElevation = 20.0\/((vp[3] - vp[1])*this->Size[1]);\n this->DeltaAzimuth = 20.0\/((vp[2] - vp[0])*this->Size[0]);\n\n \/\/ as a side effect also set the light \n \/\/ in case they are using light follow camera \n lc = this->CurrentRenderer->GetLights();\n lc->InitTraversal();\n this->CurrentLight = lc->GetNextItem();\n}\n\n\/\/ Description:\n\/\/ When pick action successfully selects actor, this method highlights the \n\/\/ actor appropriately. Currently this is done by placing a bounding box\n\/\/ around the actor.\nvoid vtkRenderWindowInteractor::HighlightActor(vtkActor *actor)\n{\n if ( ! this->OutlineActor )\n {\n \/\/ have to defer creation to get right type\n this->OutlineActor = new vtkActor;\n this->OutlineActor->PickableOff();\n this->OutlineActor->DragableOff();\n this->OutlineActor->SetMapper(this->OutlineMapper);\n this->OutlineActor->GetProperty()->SetColor(1.0,1.0,1.0);\n this->OutlineActor->GetProperty()->SetAmbient(1.0);\n this->OutlineActor->GetProperty()->SetDiffuse(0.0);\n }\n\n if ( this->PickedRenderer ) \n this->PickedRenderer->RemoveActors(OutlineActor);\n\n if ( ! actor )\n {\n this->PickedRenderer = NULL;\n }\n else \n {\n this->PickedRenderer = this->CurrentRenderer;\n this->CurrentRenderer->AddActors(OutlineActor);\n this->Outline.SetBounds(actor->GetBounds());\n this->CurrentActor = actor;\n }\n this->RenderWindow->Render();\n}\n\n\/\/ Description:\n\/\/ Specify a method to be executed prior to the pick operation.\nvoid vtkRenderWindowInteractor::SetStartPickMethod(void (*f)(void *), void *arg)\n{\n if ( f != this->StartPickMethod || arg != this->StartPickMethodArg )\n {\n this->StartPickMethod = f;\n this->StartPickMethodArg = arg;\n this->Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Specify a method to be executed after the pick operation.\nvoid vtkRenderWindowInteractor::SetEndPickMethod(void (*f)(void *), void *arg)\n{\n if ( f != this->EndPickMethod || arg != this->EndPickMethodArg )\n {\n this->EndPickMethod = f;\n this->EndPickMethodArg = arg;\n this->Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Set the object used to perform pick operations. You can use this to \n\/\/ control what type of data is picked.\nvoid vtkRenderWindowInteractor::SetPicker(vtkPicker *picker)\n{\n if ( this->Picker != picker ) \n {\n if ( this->SelfCreatedPicker ) this->Picker->Delete();\n this->SelfCreatedPicker = 0;\n this->Picker = picker;\n this->Modified();\n }\n}\n\nvtkPicker *vtkRenderWindowInteractor::CreateDefaultPicker()\n{\n if ( this->SelfCreatedPicker ) this->Picker->Delete();\n this->SelfCreatedPicker = 1;\n return new vtkCellPicker;\n}\n\n\/\/ Description:\n\/\/ Set the user method. This method is invoked on a keypress.\nvoid vtkRenderWindowInteractor::SetUserMethod(void (*f)(void *), void *arg)\n{\n if ( f != this->UserMethod || arg != this->UserMethodArg )\n {\n \/\/ delete the current arg if there is one and a delete meth\n if ((this->UserMethodArg)&&(this->UserMethodArgDelete))\n {\n (*this->UserMethodArgDelete)(this->UserMethodArg);\n }\n this->UserMethod = f;\n this->UserMethodArg = arg;\n this->Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Called when a void* argument is being discarded. Lets the user free it.\nvoid vtkRenderWindowInteractor::SetUserMethodArgDelete(void (*f)(void *))\n{\n if ( f != this->UserMethodArgDelete)\n {\n this->UserMethodArgDelete = f;\n this->Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Called when a void* argument is being discarded. Lets the user free it.\nvoid vtkRenderWindowInteractor::SetStartPickMethodArgDelete(void (*f)(void *))\n{\n if ( f != this->StartPickMethodArgDelete)\n {\n this->StartPickMethodArgDelete = f;\n this->Modified();\n }\n}\n\/\/ Description:\n\/\/ Called when a void* argument is being discarded. Lets the user free it.\nvoid vtkRenderWindowInteractor::SetEndPickMethodArgDelete(void (*f)(void *))\n{\n if ( f != this->EndPickMethodArgDelete)\n {\n this->EndPickMethodArgDelete = f;\n this->Modified();\n }\n}\n\nvoid vtkRenderWindowInteractor::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkObject::PrintSelf(os,indent);\n\n os << indent << \"RenderWindow: \" << this->RenderWindow << \"\\n\";\n os << indent << \"CurrentCamera: \" << this->CurrentCamera << \"\\n\";\n os << indent << \"CurrentLight: \" << this->CurrentLight << \"\\n\";\n os << indent << \"CurrentRenderer: \" << this->CurrentRenderer << \"\\n\";\n os << indent << \"LightFollowCamera: \" << (this->LightFollowCamera ? \"On\\n\" : \"Off\\n\");\n os << indent << \"DesiredUpdateRate: \" << this->DesiredUpdateRate << \"\\n\";\n os << indent << \"StillUpdateRate: \" << this->StillUpdateRate << \"\\n\";\n}\n\nfixed camera azimuth and Elev\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkRenderWindowInteractor.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkRenderWindowInteractor.hh\"\n#include \"vtkActor.hh\"\n#include \"vtkCellPicker.hh\"\n\n\/\/ Description:\n\/\/ Construct object so that light follows camera motion.\nvtkRenderWindowInteractor::vtkRenderWindowInteractor()\n{\n this->RenderWindow = NULL;\n this->CurrentCamera = NULL;\n this->CurrentLight = NULL;\n this->CurrentRenderer = NULL;\n\n this->LightFollowCamera = 1;\n this->Initialized = 0;\n this->DesiredUpdateRate = 15;\n this->StillUpdateRate = 0;\n \n this->SelfCreatedPicker = 0;\n this->Picker = this->CreateDefaultPicker();\n this->OutlineActor = NULL;\n this->OutlineMapper.SetInput(this->Outline.GetOutput());\n this->PickedRenderer = NULL;\n this->CurrentActor = NULL;\n\n this->StartPickMethod = NULL;\n this->StartPickMethodArgDelete = NULL;\n this->StartPickMethodArg = NULL;\n this->EndPickMethod = NULL;\n this->EndPickMethodArgDelete = NULL;\n this->EndPickMethodArg = NULL;\n this->UserMethod = NULL;\n this->UserMethodArgDelete = NULL;\n this->UserMethodArg = NULL;\n}\n\nvtkRenderWindowInteractor::~vtkRenderWindowInteractor()\n{\n if ( this->OutlineActor ) this->OutlineActor->Delete();\n if ( this->SelfCreatedPicker && this->Picker) this->Picker->Delete();\n}\n\nvoid vtkRenderWindowInteractor::FindPokedRenderer(int x,int y)\n{\n vtkRendererCollection *rc;\n vtkRenderer *aren;\n\n this->CurrentRenderer = NULL;\n\n rc = this->RenderWindow->GetRenderers();\n \n for (rc->InitTraversal(); \n ((aren = rc->GetNextItem())&&(!this->CurrentRenderer));)\n {\n if (aren->IsInViewport(x,y))\n {\n this->CurrentRenderer = aren;\n }\n }\n \n \/\/ we must have a value \n if (this->CurrentRenderer == NULL)\n {\n rc->InitTraversal();\n aren = rc->GetNextItem();\n this->CurrentRenderer = aren;\n }\n}\n\nvoid vtkRenderWindowInteractor::FindPokedCamera(int x,int y)\n{\n float *vp;\n vtkLightCollection *lc;\n\n this->FindPokedRenderer(x,y);\n vp = this->CurrentRenderer->GetViewport();\n\n this->CurrentCamera = this->CurrentRenderer->GetActiveCamera(); \n memcpy(this->Center,this->CurrentRenderer->GetCenter(),sizeof(int)*2);\n this->DeltaElevation = -20.0\/((vp[3] - vp[1])*this->Size[1]);\n this->DeltaAzimuth = -20.0\/((vp[2] - vp[0])*this->Size[0]);\n\n \/\/ as a side effect also set the light \n \/\/ in case they are using light follow camera \n lc = this->CurrentRenderer->GetLights();\n lc->InitTraversal();\n this->CurrentLight = lc->GetNextItem();\n}\n\n\/\/ Description:\n\/\/ When pick action successfully selects actor, this method highlights the \n\/\/ actor appropriately. Currently this is done by placing a bounding box\n\/\/ around the actor.\nvoid vtkRenderWindowInteractor::HighlightActor(vtkActor *actor)\n{\n if ( ! this->OutlineActor )\n {\n \/\/ have to defer creation to get right type\n this->OutlineActor = new vtkActor;\n this->OutlineActor->PickableOff();\n this->OutlineActor->DragableOff();\n this->OutlineActor->SetMapper(this->OutlineMapper);\n this->OutlineActor->GetProperty()->SetColor(1.0,1.0,1.0);\n this->OutlineActor->GetProperty()->SetAmbient(1.0);\n this->OutlineActor->GetProperty()->SetDiffuse(0.0);\n }\n\n if ( this->PickedRenderer ) \n this->PickedRenderer->RemoveActors(OutlineActor);\n\n if ( ! actor )\n {\n this->PickedRenderer = NULL;\n }\n else \n {\n this->PickedRenderer = this->CurrentRenderer;\n this->CurrentRenderer->AddActors(OutlineActor);\n this->Outline.SetBounds(actor->GetBounds());\n this->CurrentActor = actor;\n }\n this->RenderWindow->Render();\n}\n\n\/\/ Description:\n\/\/ Specify a method to be executed prior to the pick operation.\nvoid vtkRenderWindowInteractor::SetStartPickMethod(void (*f)(void *), void *arg)\n{\n if ( f != this->StartPickMethod || arg != this->StartPickMethodArg )\n {\n this->StartPickMethod = f;\n this->StartPickMethodArg = arg;\n this->Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Specify a method to be executed after the pick operation.\nvoid vtkRenderWindowInteractor::SetEndPickMethod(void (*f)(void *), void *arg)\n{\n if ( f != this->EndPickMethod || arg != this->EndPickMethodArg )\n {\n this->EndPickMethod = f;\n this->EndPickMethodArg = arg;\n this->Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Set the object used to perform pick operations. You can use this to \n\/\/ control what type of data is picked.\nvoid vtkRenderWindowInteractor::SetPicker(vtkPicker *picker)\n{\n if ( this->Picker != picker ) \n {\n if ( this->SelfCreatedPicker ) this->Picker->Delete();\n this->SelfCreatedPicker = 0;\n this->Picker = picker;\n this->Modified();\n }\n}\n\nvtkPicker *vtkRenderWindowInteractor::CreateDefaultPicker()\n{\n if ( this->SelfCreatedPicker ) this->Picker->Delete();\n this->SelfCreatedPicker = 1;\n return new vtkCellPicker;\n}\n\n\/\/ Description:\n\/\/ Set the user method. This method is invoked on a keypress.\nvoid vtkRenderWindowInteractor::SetUserMethod(void (*f)(void *), void *arg)\n{\n if ( f != this->UserMethod || arg != this->UserMethodArg )\n {\n \/\/ delete the current arg if there is one and a delete meth\n if ((this->UserMethodArg)&&(this->UserMethodArgDelete))\n {\n (*this->UserMethodArgDelete)(this->UserMethodArg);\n }\n this->UserMethod = f;\n this->UserMethodArg = arg;\n this->Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Called when a void* argument is being discarded. Lets the user free it.\nvoid vtkRenderWindowInteractor::SetUserMethodArgDelete(void (*f)(void *))\n{\n if ( f != this->UserMethodArgDelete)\n {\n this->UserMethodArgDelete = f;\n this->Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Called when a void* argument is being discarded. Lets the user free it.\nvoid vtkRenderWindowInteractor::SetStartPickMethodArgDelete(void (*f)(void *))\n{\n if ( f != this->StartPickMethodArgDelete)\n {\n this->StartPickMethodArgDelete = f;\n this->Modified();\n }\n}\n\/\/ Description:\n\/\/ Called when a void* argument is being discarded. Lets the user free it.\nvoid vtkRenderWindowInteractor::SetEndPickMethodArgDelete(void (*f)(void *))\n{\n if ( f != this->EndPickMethodArgDelete)\n {\n this->EndPickMethodArgDelete = f;\n this->Modified();\n }\n}\n\nvoid vtkRenderWindowInteractor::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkObject::PrintSelf(os,indent);\n\n os << indent << \"RenderWindow: \" << this->RenderWindow << \"\\n\";\n os << indent << \"CurrentCamera: \" << this->CurrentCamera << \"\\n\";\n os << indent << \"CurrentLight: \" << this->CurrentLight << \"\\n\";\n os << indent << \"CurrentRenderer: \" << this->CurrentRenderer << \"\\n\";\n os << indent << \"LightFollowCamera: \" << (this->LightFollowCamera ? \"On\\n\" : \"Off\\n\");\n os << indent << \"DesiredUpdateRate: \" << this->DesiredUpdateRate << \"\\n\";\n os << indent << \"StillUpdateRate: \" << this->StillUpdateRate << \"\\n\";\n}\n\n<|endoftext|>"} {"text":"Remove unnecessary WebCore includes.<|endoftext|>"} {"text":"\/*\n Copyright (C) 2012 by Ivan Safrin\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n *\/\n \n#include \"TextureBrowser.h\"\n\nAssetEntry::AssetEntry(String assetPath, String assetName, String extension, Resource *resource) : UIElement() {\n\n this->resource = resource;\n\tthis->assetPath = assetPath;\n\n\tif(assetName.length() > 20)\n\t\tassetName = assetName.substr(0,20)+\"...\";\n\n\tselectShape = new UIRect(120, 100);\n\tselectShape->visible = false;\n\tselectShape->setAnchorPoint(-1.0, -1.0, 0.0);\n\taddChild(selectShape);\n\tselectShape->processInputEvents = true;\n\tselectShape->setColor(0.0, 0.0, 0.0, 0.5);\n selectShape->loadTexture(\"browserIcons\/large_selector.png\");\n selectShape->setBlendingMode(Renderer::BLEND_MODE_NORMAL);\n\n\timageShape = new UIRect(64,64);\n\timageShape->setAnchorPoint(-1.0, -1.0, 0.0);\n\taddChild(imageShape);\n\t\n\textension = extension.toLowerCase();\n\t\n\tif(extension == \"png\") {\n\t\timageShape->loadTexture(assetPath);\n\t} else if(extension == \"ogg\" || extension == \"wav\") {\n\t\timageShape->loadTexture(\"browserIcons\/sound_icon.png\");\n\t} else if(extension == \"entity\") {\n\t\timageShape->loadTexture(\"browserIcons\/entity_icon.png\");\n\t} else if(extension == \"sprite\") {\n\t\timageShape->loadTexture(\"browserIcons\/sprite_icon.png\");\n\t} else if(extension == \"ttf\" || extension == \"otf\") {\n\t\timageShape->loadTexture(\"browserIcons\/font_icon.png\");\n\t} else if(extension == \"vert\" || extension == \"frag\") {\n\t\timageShape->loadTexture(\"browserIcons\/shader_icon.png\");\n\t} else if(extension == \"mesh\") {\n\t\timageShape->loadTexture(\"browserIcons\/mesh_icon.png\");\n } else if(extension == \"mat\") {\n\t\timageShape->loadTexture(\"browserIcons\/materials_icon.png\");\n } else if(extension == \"material_resource\") {\n\t\timageShape->loadTexture(\"browserIcons\/material_resource_icon.png\");\n }\n\t\n\timageShape->setPosition(28, 10);\n imageShape->setBlendingMode(Renderer::BLEND_MODE_NORMAL);\n \n String name = assetName;\n if(name.length() > 15) {\n name = name.substr(0, 15)+\"...\";\n }\n\tnameLabel = new UILabel(name, 11);\n\taddChild(nameLabel);\n nameLabel->setPosition((120.0-nameLabel->getWidth())\/2.0, 80);\n \n}\n\nAssetEntry::~AssetEntry() {\n\tdelete imageShape;\n\tdelete nameLabel;\n\tdelete selectShape;\n}\n\nAssetList::AssetList() : UIElement() {\n\t \n\treloadButton = new UIImageButton(\"browserIcons\/reload_icon.png\", 1.0, 20, 20);\n\treloadButton->addEventListener(this, UIEvent::CLICK_EVENT);\n\taddChild(reloadButton);\t\n\treloadButton->setPosition(10, 5);\t\t\n\t\n}\n\nAssetList::~AssetList() {\n\n}\n\nResource *AssetList::getSelectedResource() {\n return selectedResource;\n}\n\nvoid AssetList::setExtensions(std::vector extensions) {\n\tthis->extensions = extensions;\n\tif(currentFolderPath != \"\") {\n\t\tshowFolder(currentFolderPath);\n\t}\n}\n\nbool AssetList::hasExtension(String extension) {\n\tfor(int i=0; i < extensions.size(); i++) {\n\t\tif(extensions[i] == extension.toLowerCase()) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid AssetList::showResourcePool(ResourcePool *pool, int resourceFilter) {\n\t\n clearList();\n \n\tNumber xPos = 20;\n\tNumber yPos = 30;\n\t\n std::vector resources = pool->getResources(resourceFilter);\n \n String extension;\n \n if(resourceFilter == Resource::RESOURCE_MATERIAL ) {\n extension = \"material_resource\";\n }\n \n\tfor(int i=0; i < resources.size(); i++) {\n AssetEntry *newEntry = new AssetEntry(\"\", resources[i]->getResourceName(), extension, resources[i]);\n newEntry->selectShape->addEventListener(this, InputEvent::EVENT_MOUSEDOWN);\n assetEntries.push_back(newEntry);\n newEntry->setPosition(xPos, yPos);\n xPos += 120;\n if(xPos > 500) {\n xPos = 20;\n yPos += 100;\n }\n addChild(newEntry);\n\t}\n\t\n\tsetWidth(640);\n\t\n\tif(xPos == 20) {\n\t\tsetHeight(yPos+20);\n\t} else {\n\t\tsetHeight(yPos + 120);\n\t}\n}\n\nvoid AssetList::clearList() {\n\tfor(int i=0; i < assetEntries.size(); i++) {\n\t\tremoveChild(assetEntries[i]);\n\t\tdelete assetEntries[i];\n\t}\n\tassetEntries.clear();\n\tcurrentEntry = NULL;\n selectedResource = NULL;\n}\n\nvoid AssetList::showFolder(String folderPath) {\n\n\tcurrentFolderPath = folderPath;\n\n clearList();\n\t\n\tvector assets = OSBasics::parseFolder(folderPath, false);\t\n\t\n\tNumber xPos = 20;\n\tNumber yPos = 30;\n\t\n\tfor(int i=0; i < assets.size(); i++) {\n\t\tOSFileEntry entry = assets[i];\n\t\tif(entry.type != OSFileEntry::TYPE_FOLDER) {\n\t\t\tif(hasExtension(entry.extension)) {\n\t\t\t\tAssetEntry *newEntry = new AssetEntry(entry.fullPath, entry.name, entry.extension, NULL);\n\t\t\t\tnewEntry->selectShape->addEventListener(this, InputEvent::EVENT_MOUSEDOWN);\n\t\t\t\tassetEntries.push_back(newEntry);\n\t\t\t\tnewEntry->setPosition(xPos, yPos);\n\t\t\t\txPos += 120;\n\t\t\t\tif(xPos > 500) {\n\t\t\t\t\txPos = 20;\n\t\t\t\t\tyPos += 100;\n\t\t\t\t}\n\t\t\t\taddChild(newEntry);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tsetWidth(640);\n\t\n\tif(xPos == 20) {\n\t\tsetHeight(yPos+20);\n\t} else {\n\t\tsetHeight(yPos + 120);\n\t}\n\n\t\n\trebuildTransformMatrix();\t\n}\n\nvoid AssetList::handleEvent(Event *event) {\n\tif(event->getDispatcher() == reloadButton && event->getEventCode() == UIEvent::CLICK_EVENT) {\n\t\tshowFolder(currentFolderPath);\n\t} else {\n\t\tfor(int i=0; i < assetEntries.size(); i++) {\n\t\t\tif(event->getDispatcher() == assetEntries[i]->selectShape && event->getEventCode() == InputEvent::EVENT_MOUSEDOWN) {\n\t\t\t\tassetEntries[i]->selectShape->visible = true;\n\t\t\t\tselectedPath = assetEntries[i]->assetPath;\n\t\t\t\tprintf(\"%s\\n\", selectedPath.c_str());\n\t\t\t\tif(currentEntry) {\n\t\t\t\t\tcurrentEntry->selectShape->visible = false;\n\t\t\t\t}\n\t\t\t\tcurrentEntry = assetEntries[i];\n selectedResource = assetEntries[i]->resource;\n\t\t\t}\n\t\t}\n\t}\n}\n\nAssetBrowser::AssetBrowser() : UIWindow(L\"Asset Browser\", 850, 500) {\n\tdefaultTemplateTree = NULL;\n \n browseMode = BROWSE_MODE_FILES;\n\t\n\tConfig *conf = CoreServices::getInstance()->getConfig();\t\n\tString fontName = conf->getStringValue(\"Polycode\", \"uiDefaultFontName\");\n\t\n\tcloseOnEscape = true;\t\n\t\n\ttemplateContainer = new UITreeContainer(\"boxIcon.png\", L\"Project\", 200, 480-topPadding-padding-padding);\t\n\t\n\tFolderUserData *data = new FolderUserData();\n\tdata->type = 0;\n\ttemplateContainer->getRootNode()->setUserData(data);\t\t\t\n\n\taddChild(templateContainer);\t\t\n\ttemplateContainer->setPosition(padding,topPadding+padding);\t\n\ttemplateContainer->getRootNode()->toggleCollapsed();\n\t\n\ttemplateContainer->getRootNode()->addEventListener(this, UITreeEvent::SELECTED_EVENT);\n\t\n\t\t\n\tassetList = new AssetList();\n\t\n\tlistContainer = new UIScrollContainer(assetList, false, true, 640, 480-topPadding-padding-padding);\n\tlistContainer->setPosition(220,topPadding+padding);\t\t\n\taddChild(listContainer);\n\n\tcancelButton = new UIButton(L\"Cancel\", 100);\n\tcancelButton->addEventListener(this, UIEvent::CLICK_EVENT);\n\taddChild(cancelButton);\n\tcancelButton->setPosition(850-80-padding-100-10, 485);\n\n\tokButton = new UIButton(L\"OK\", 100);\n\tokButton->addEventListener(this, UIEvent::CLICK_EVENT);\n\taddChild(okButton);\n\tokButton->setPosition(850-80-padding, 485);\t\n\t\n\n\t\t\t\n\tcurrentProject = NULL;\n}\n\nvoid AssetBrowser::setResourcePools(std::vector pools, int resourceFilter) {\n \n this->resourceFilter = resourceFilter;\n \n\ttemplateContainer->getRootNode()->clearTree();\n\ttemplateContainer->getRootNode()->setLabelText(\"Resource pools\");\n\ttemplateContainer->getRootNode()->setUserData(NULL);\n \n \n for(int i=0; i < pools.size(); i++) {\n ResourcePool *pool = pools[i];\n UITree *newChild = templateContainer->getRootNode()->addTreeChild(\"folder.png\", pool->getName(), (void*)pool);\n newChild->setUserData(pool);\n }\n \n}\n\nvoid AssetBrowser::setBrowseMode(unsigned int newBrowseMode) {\n if(browseMode != newBrowseMode) {\n assetList->clearList();\n browseMode = newBrowseMode;\n }\n}\n\nvoid AssetBrowser::setProject(PolycodeProject *project) {\n\t\n\ttemplateContainer->getRootNode()->clearTree();\n\n\tvector templates = OSBasics::parseFolder(project->getRootFolder(), false);\n\ttemplateContainer->getRootNode()->setLabelText(project->getProjectName());\n\t\t\n\tfor(int i=0; i < templates.size(); i++) {\n\t\tOSFileEntry entry = templates[i];\n\t\tif(entry.type == OSFileEntry::TYPE_FOLDER) {\n\t\t\tUITree *newChild = templateContainer->getRootNode()->addTreeChild(\"folder.png\", entry.name, NULL);\n\t\t\tFolderUserData *data = new FolderUserData();\n\t\t\tdata->type = 0;\n\t\t\tdata->folderPath = entry.fullPath;\n\t\t\tnewChild->setUserData(data);\t\t\t\n\t\t\tnewChild->toggleCollapsed();\n\t\t\tparseFolderIntoTree(newChild, entry);\n\t\t}\n\t}\t\n\t\n\tcurrentProject = project;\n templateContainer->getScrollContainer()->setScrollValue(0.0, 0.0); \n}\n\nAssetBrowser::~AssetBrowser() {\n\t\n}\n\nString AssetBrowser::getFileName() {\n\treturn \"\";\n}\n\nString AssetBrowser::getTemplatePath() {\n\treturn templatePath;\n}\n\nString AssetBrowser::getFullSelectedAssetPath() {\n\treturn assetList->selectedPath;\n}\n\nString AssetBrowser::getSelectedAssetPath() {\n\treturn assetList->selectedPath.replace(currentProject->getRootFolder()+\"\/\", \"\");\n}\n\nvoid AssetBrowser::setExtensions(std::vector extensions) {\n\tassetList->setExtensions(extensions);\n}\n\nResource *AssetBrowser::getSelectedResource() {\n\treturn assetList->getSelectedResource();\n \n}\n\nvoid AssetBrowser::handleEvent(Event *event) {\n\tif(event->getEventType() == \"UIEvent\") {\n\t\tif(event->getEventCode() == UIEvent::CLICK_EVENT) {\n\t\t\tif(event->getDispatcher() == okButton) {\n\t\t\t\tdispatchEvent(new UIEvent(), UIEvent::OK_EVENT);\t\t\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tif(event->getDispatcher() == cancelButton) {\n\t\t\t\tdispatchEvent(new UIEvent(), UIEvent::CLOSE_EVENT);\t\t\t\t\n\t\t\t}\t\t\t\t\t\t\t\t\t\n\t\t}\n\t}\n\t\n\tif(event->getEventType() == \"UITreeEvent\" && event->getEventCode() == UITreeEvent::SELECTED_EVENT) {\n\t\tif(event->getDispatcher() == templateContainer->getRootNode()) {\n\t\t\tUITreeEvent *treeEvent = (UITreeEvent*) event;\n \n if(browseMode == BROWSE_MODE_FILES) {\n FolderUserData *data = (FolderUserData *)treeEvent->selection->getUserData();\n if(data) {\n assetList->showFolder(data->folderPath);\n }\n } else {\n ResourcePool *pool = (ResourcePool*) treeEvent->selection->getUserData();\n if(pool) {\n assetList->showResourcePool(pool, resourceFilter);\n }\n }\n\t\t\tlistContainer->setContentSize(assetList->getWidth(), assetList->getHeight());\n\t\t\tlistContainer->setScrollValue(0,0);\n\t\t}\n\t}\n\t\n\tUIWindow::handleEvent(event);\t\n}\n\n\nvoid AssetBrowser::parseFolderIntoTree(UITree *tree, OSFileEntry folder) {\n\tvector templates = OSBasics::parseFolder(folder.fullPath, false);\n\tfor(int i=0; i < templates.size(); i++) {\n\t\tOSFileEntry entry = templates[i];\t\n\t\tif(entry.type == OSFileEntry::TYPE_FOLDER) {\n\t\t\tUITree *newChild = tree->addTreeChild(\"folder.png\", entry.nameWithoutExtension, NULL);\n\t\t\tFolderUserData *data = new FolderUserData();\n\t\t\tdata->type = 1;\n\t\t\tdata->folderPath = entry.fullPath;\n\t\t\tnewChild->setUserData(data);\n\t\t\tparseFolderIntoTree(newChild, entry);\n\t\t}\n\t}\t\n}\nFixed asset browser crashing in some scenarios\/*\n Copyright (C) 2012 by Ivan Safrin\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n *\/\n \n#include \"TextureBrowser.h\"\n\nAssetEntry::AssetEntry(String assetPath, String assetName, String extension, Resource *resource) : UIElement() {\n\n this->resource = resource;\n\tthis->assetPath = assetPath;\n\n\tif(assetName.length() > 20)\n\t\tassetName = assetName.substr(0,20)+\"...\";\n\n\tselectShape = new UIRect(120, 100);\n\tselectShape->visible = false;\n\tselectShape->setAnchorPoint(-1.0, -1.0, 0.0);\n\taddChild(selectShape);\n\tselectShape->processInputEvents = true;\n\tselectShape->setColor(0.0, 0.0, 0.0, 0.5);\n selectShape->loadTexture(\"browserIcons\/large_selector.png\");\n selectShape->setBlendingMode(Renderer::BLEND_MODE_NORMAL);\n\n\timageShape = new UIRect(64,64);\n\timageShape->setAnchorPoint(-1.0, -1.0, 0.0);\n\taddChild(imageShape);\n\t\n\textension = extension.toLowerCase();\n\t\n\tif(extension == \"png\") {\n\t\timageShape->loadTexture(assetPath);\n\t} else if(extension == \"ogg\" || extension == \"wav\") {\n\t\timageShape->loadTexture(\"browserIcons\/sound_icon.png\");\n\t} else if(extension == \"entity\") {\n\t\timageShape->loadTexture(\"browserIcons\/entity_icon.png\");\n\t} else if(extension == \"sprite\") {\n\t\timageShape->loadTexture(\"browserIcons\/sprite_icon.png\");\n\t} else if(extension == \"ttf\" || extension == \"otf\") {\n\t\timageShape->loadTexture(\"browserIcons\/font_icon.png\");\n\t} else if(extension == \"vert\" || extension == \"frag\") {\n\t\timageShape->loadTexture(\"browserIcons\/shader_icon.png\");\n\t} else if(extension == \"mesh\") {\n\t\timageShape->loadTexture(\"browserIcons\/mesh_icon.png\");\n } else if(extension == \"mat\") {\n\t\timageShape->loadTexture(\"browserIcons\/materials_icon.png\");\n } else if(extension == \"material_resource\") {\n\t\timageShape->loadTexture(\"browserIcons\/material_resource_icon.png\");\n }\n\t\n\timageShape->setPosition(28, 10);\n imageShape->setBlendingMode(Renderer::BLEND_MODE_NORMAL);\n \n String name = assetName;\n if(name.length() > 15) {\n name = name.substr(0, 15)+\"...\";\n }\n\tnameLabel = new UILabel(name, 11);\n\taddChild(nameLabel);\n nameLabel->setPosition((120.0-nameLabel->getWidth())\/2.0, 80);\n \n}\n\nAssetEntry::~AssetEntry() {\n\tdelete imageShape;\n\tdelete nameLabel;\n\tdelete selectShape;\n}\n\nAssetList::AssetList() : UIElement() {\n\t \n\treloadButton = new UIImageButton(\"browserIcons\/reload_icon.png\", 1.0, 20, 20);\n\treloadButton->addEventListener(this, UIEvent::CLICK_EVENT);\n\taddChild(reloadButton);\t\n\treloadButton->setPosition(10, 5);\t\t\n\t\n}\n\nAssetList::~AssetList() {\n\n}\n\nResource *AssetList::getSelectedResource() {\n return selectedResource;\n}\n\nvoid AssetList::setExtensions(std::vector extensions) {\n\tthis->extensions = extensions;\n\tif(currentFolderPath != \"\") {\n\t\tshowFolder(currentFolderPath);\n\t}\n}\n\nbool AssetList::hasExtension(String extension) {\n\tfor(int i=0; i < extensions.size(); i++) {\n\t\tif(extensions[i] == extension.toLowerCase()) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid AssetList::showResourcePool(ResourcePool *pool, int resourceFilter) {\n\t\n clearList();\n \n\tNumber xPos = 20;\n\tNumber yPos = 30;\n\t\n std::vector resources = pool->getResources(resourceFilter);\n \n String extension;\n \n if(resourceFilter == Resource::RESOURCE_MATERIAL ) {\n extension = \"material_resource\";\n }\n \n\tfor(int i=0; i < resources.size(); i++) {\n AssetEntry *newEntry = new AssetEntry(\"\", resources[i]->getResourceName(), extension, resources[i]);\n newEntry->selectShape->addEventListener(this, InputEvent::EVENT_MOUSEDOWN);\n assetEntries.push_back(newEntry);\n newEntry->setPosition(xPos, yPos);\n xPos += 120;\n if(xPos > 500) {\n xPos = 20;\n yPos += 100;\n }\n addChild(newEntry);\n\t}\n\t\n\tsetWidth(640);\n\t\n\tif(xPos == 20) {\n\t\tsetHeight(yPos+20);\n\t} else {\n\t\tsetHeight(yPos + 120);\n\t}\n}\n\nvoid AssetList::clearList() {\n\tfor(int i=0; i < assetEntries.size(); i++) {\n\t\tremoveChild(assetEntries[i]);\n\t\tdelete assetEntries[i];\n\t}\n\tassetEntries.clear();\n\tcurrentEntry = NULL;\n selectedResource = NULL;\n}\n\nvoid AssetList::showFolder(String folderPath) {\n\n\tcurrentFolderPath = folderPath;\n\n clearList();\n\t\n\tvector assets = OSBasics::parseFolder(folderPath, false);\t\n\t\n\tNumber xPos = 20;\n\tNumber yPos = 30;\n\t\n\tfor(int i=0; i < assets.size(); i++) {\n\t\tOSFileEntry entry = assets[i];\n\t\tif(entry.type != OSFileEntry::TYPE_FOLDER) {\n\t\t\tif(hasExtension(entry.extension)) {\n\t\t\t\tAssetEntry *newEntry = new AssetEntry(entry.fullPath, entry.name, entry.extension, NULL);\n\t\t\t\tnewEntry->selectShape->addEventListener(this, InputEvent::EVENT_MOUSEDOWN);\n\t\t\t\tassetEntries.push_back(newEntry);\n\t\t\t\tnewEntry->setPosition(xPos, yPos);\n\t\t\t\txPos += 120;\n\t\t\t\tif(xPos > 500) {\n\t\t\t\t\txPos = 20;\n\t\t\t\t\tyPos += 100;\n\t\t\t\t}\n\t\t\t\taddChild(newEntry);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tsetWidth(640);\n\t\n\tif(xPos == 20) {\n\t\tsetHeight(yPos+20);\n\t} else {\n\t\tsetHeight(yPos + 120);\n\t}\n\n\t\n\trebuildTransformMatrix();\t\n}\n\nvoid AssetList::handleEvent(Event *event) {\n\tif(event->getDispatcher() == reloadButton && event->getEventCode() == UIEvent::CLICK_EVENT) {\n\t\tshowFolder(currentFolderPath);\n\t} else {\n\t\tfor(int i=0; i < assetEntries.size(); i++) {\n\t\t\tif(event->getDispatcher() == assetEntries[i]->selectShape && event->getEventCode() == InputEvent::EVENT_MOUSEDOWN) {\n\t\t\t\tassetEntries[i]->selectShape->visible = true;\n\t\t\t\tselectedPath = assetEntries[i]->assetPath;\n\t\t\t\tprintf(\"%s\\n\", selectedPath.c_str());\n\t\t\t\tif(currentEntry) {\n\t\t\t\t\tcurrentEntry->selectShape->visible = false;\n\t\t\t\t}\n\t\t\t\tcurrentEntry = assetEntries[i];\n selectedResource = assetEntries[i]->resource;\n\t\t\t}\n\t\t}\n\t}\n}\n\nAssetBrowser::AssetBrowser() : UIWindow(L\"Asset Browser\", 850, 500) {\n\tdefaultTemplateTree = NULL;\n \n browseMode = BROWSE_MODE_FILES;\n\t\n\tConfig *conf = CoreServices::getInstance()->getConfig();\t\n\tString fontName = conf->getStringValue(\"Polycode\", \"uiDefaultFontName\");\n\t\n\tcloseOnEscape = true;\t\n\t\n\ttemplateContainer = new UITreeContainer(\"boxIcon.png\", L\"Project\", 200, 480-topPadding-padding-padding);\t\n\t\n\tFolderUserData *data = new FolderUserData();\n\tdata->type = 0;\n\ttemplateContainer->getRootNode()->setUserData(data);\t\t\t\n\n\taddChild(templateContainer);\t\t\n\ttemplateContainer->setPosition(padding,topPadding+padding);\t\n\ttemplateContainer->getRootNode()->toggleCollapsed();\n\t\n\ttemplateContainer->getRootNode()->addEventListener(this, UITreeEvent::SELECTED_EVENT);\n\t\n\t\t\n\tassetList = new AssetList();\n\t\n\tlistContainer = new UIScrollContainer(assetList, false, true, 640, 480-topPadding-padding-padding);\n\tlistContainer->setPosition(220,topPadding+padding);\t\t\n\taddChild(listContainer);\n\n\tcancelButton = new UIButton(L\"Cancel\", 100);\n\tcancelButton->addEventListener(this, UIEvent::CLICK_EVENT);\n\taddChild(cancelButton);\n\tcancelButton->setPosition(850-80-padding-100-10, 485);\n\n\tokButton = new UIButton(L\"OK\", 100);\n\tokButton->addEventListener(this, UIEvent::CLICK_EVENT);\n\taddChild(okButton);\n\tokButton->setPosition(850-80-padding, 485);\t\n\t\n\n\t\t\t\n\tcurrentProject = NULL;\n}\n\nvoid AssetBrowser::setResourcePools(std::vector pools, int resourceFilter) {\n \n this->resourceFilter = resourceFilter;\n \n\ttemplateContainer->getRootNode()->clearTree();\n\ttemplateContainer->getRootNode()->setLabelText(\"Resource pools\");\n\ttemplateContainer->getRootNode()->setUserData(NULL);\n \n \n for(int i=0; i < pools.size(); i++) {\n ResourcePool *pool = pools[i];\n UITree *newChild = templateContainer->getRootNode()->addTreeChild(\"folder.png\", pool->getName(), (void*)pool);\n newChild->setUserData(pool);\n }\n \n}\n\nvoid AssetBrowser::setBrowseMode(unsigned int newBrowseMode) {\n if(browseMode != newBrowseMode) {\n assetList->clearList();\n browseMode = newBrowseMode;\n }\n}\n\nvoid AssetBrowser::setProject(PolycodeProject *project) {\n\t\n\ttemplateContainer->getRootNode()->clearTree();\n\n\tvector templates = OSBasics::parseFolder(project->getRootFolder(), false);\n\ttemplateContainer->getRootNode()->setLabelText(project->getProjectName());\n\t\t\n\tfor(int i=0; i < templates.size(); i++) {\n\t\tOSFileEntry entry = templates[i];\n\t\tif(entry.type == OSFileEntry::TYPE_FOLDER) {\n\t\t\tUITree *newChild = templateContainer->getRootNode()->addTreeChild(\"folder.png\", entry.name, NULL);\n\t\t\tFolderUserData *data = new FolderUserData();\n\t\t\tdata->type = 0;\n\t\t\tdata->folderPath = entry.fullPath;\n\t\t\tnewChild->setUserData(data);\t\t\t\n\t\t\tnewChild->toggleCollapsed();\n\t\t\tparseFolderIntoTree(newChild, entry);\n\t\t}\n\t}\t\n\t\n\tcurrentProject = project;\n templateContainer->getScrollContainer()->setScrollValue(0.0, 0.0); \n}\n\nAssetBrowser::~AssetBrowser() {\n\t\n}\n\nString AssetBrowser::getFileName() {\n\treturn \"\";\n}\n\nString AssetBrowser::getTemplatePath() {\n\treturn templatePath;\n}\n\nString AssetBrowser::getFullSelectedAssetPath() {\n\treturn assetList->selectedPath;\n}\n\nString AssetBrowser::getSelectedAssetPath() {\n\treturn assetList->selectedPath.replace(currentProject->getRootFolder()+\"\/\", \"\");\n}\n\nvoid AssetBrowser::setExtensions(std::vector extensions) {\n\tassetList->setExtensions(extensions);\n}\n\nResource *AssetBrowser::getSelectedResource() {\n\treturn assetList->getSelectedResource();\n \n}\n\nvoid AssetBrowser::handleEvent(Event *event) {\n\tif(event->getEventType() == \"UIEvent\") {\n\t\tif(event->getEventCode() == UIEvent::CLICK_EVENT) {\n\t\t\tif(event->getDispatcher() == okButton) {\n\t\t\t\tdispatchEvent(new UIEvent(), UIEvent::OK_EVENT);\t\t\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tif(event->getDispatcher() == cancelButton) {\n\t\t\t\tdispatchEvent(new UIEvent(), UIEvent::CLOSE_EVENT);\n removeAllHandlers();\n\t\t\t}\t\t\t\t\t\t\t\t\t\n\t\t}\n\t}\n\t\n\tif(event->getEventType() == \"UITreeEvent\" && event->getEventCode() == UITreeEvent::SELECTED_EVENT) {\n\t\tif(event->getDispatcher() == templateContainer->getRootNode()) {\n\t\t\tUITreeEvent *treeEvent = (UITreeEvent*) event;\n \n if(browseMode == BROWSE_MODE_FILES) {\n FolderUserData *data = (FolderUserData *)treeEvent->selection->getUserData();\n if(data) {\n assetList->showFolder(data->folderPath);\n }\n } else {\n ResourcePool *pool = (ResourcePool*) treeEvent->selection->getUserData();\n if(pool) {\n assetList->showResourcePool(pool, resourceFilter);\n }\n }\n\t\t\tlistContainer->setContentSize(assetList->getWidth(), assetList->getHeight());\n\t\t\tlistContainer->setScrollValue(0,0);\n\t\t}\n\t}\n\t\n\tUIWindow::handleEvent(event);\t\n}\n\n\nvoid AssetBrowser::parseFolderIntoTree(UITree *tree, OSFileEntry folder) {\n\tvector templates = OSBasics::parseFolder(folder.fullPath, false);\n\tfor(int i=0; i < templates.size(); i++) {\n\t\tOSFileEntry entry = templates[i];\t\n\t\tif(entry.type == OSFileEntry::TYPE_FOLDER) {\n\t\t\tUITree *newChild = tree->addTreeChild(\"folder.png\", entry.nameWithoutExtension, NULL);\n\t\t\tFolderUserData *data = new FolderUserData();\n\t\t\tdata->type = 1;\n\t\t\tdata->folderPath = entry.fullPath;\n\t\t\tnewChild->setUserData(data);\n\t\t\tparseFolderIntoTree(newChild, entry);\n\t\t}\n\t}\t\n}\n<|endoftext|>"} {"text":"\/\/ @(#)root\/rint:$Name: $:$Id: TRint.cxx,v 1.41 2004\/08\/07 23:49:31 rdm Exp $\n\/\/ Author: Rene Brun 17\/02\/95\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ Rint \/\/\n\/\/ \/\/\n\/\/ Rint is the ROOT Interactive Interface. It allows interactive access \/\/\n\/\/ to the ROOT system via the CINT C\/C++ interpreter. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TROOT.h\"\n#include \"TClass.h\"\n#include \"TVirtualX.h\"\n#include \"Getline.h\"\n#include \"TStyle.h\"\n#include \"TObjectTable.h\"\n#include \"TClassTable.h\"\n#include \"TStopwatch.h\"\n#include \"TBenchmark.h\"\n#include \"TRint.h\"\n#include \"TSystem.h\"\n#include \"TEnv.h\"\n#include \"TSysEvtHandler.h\"\n#include \"TError.h\"\n#include \"TException.h\"\n#include \"TInterpreter.h\"\n#include \"TObjArray.h\"\n#include \"TObjString.h\"\n#include \"TFile.h\"\n#include \"TMapFile.h\"\n#include \"TTabCom.h\"\n#include \"TError.h\"\n\n#ifdef R__UNIX\n#include \n\nextern \"C\" {\n extern int G__get_security_error();\n extern int G__genericerror(const char* msg);\n}\n#endif\n\nstatic Int_t key_pressed(Int_t key) { gApplication->KeyPressed(key); return 0; }\n\n\n\/\/----- Interrupt signal handler -----------------------------------------------\n\/\/______________________________________________________________________________\nclass TInterruptHandler : public TSignalHandler {\npublic:\n TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { }\n Bool_t Notify();\n};\n\n\/\/______________________________________________________________________________\nBool_t TInterruptHandler::Notify()\n{\n \/\/ TRint interrupt handler.\n\n if (fDelay) {\n fDelay++;\n return kTRUE;\n }\n\n \/\/ make sure we use the sbrk heap (in case of mapped files)\n gMmallocDesc = 0;\n\n if (!G__get_security_error())\n G__genericerror(\"\\n *** Break *** keyboard interrupt\");\n else {\n Break(\"TInterruptHandler::Notify\", \"keyboard interrupt\");\n if (TROOT::Initialized()) {\n Getlinem(kInit, \"Root > \");\n gInterpreter->RewindDictionary();\n Throw(GetSignal());\n }\n }\n return kTRUE;\n}\n\n\/\/----- Terminal Input file handler --------------------------------------------\n\/\/______________________________________________________________________________\nclass TTermInputHandler : public TFileHandler {\npublic:\n TTermInputHandler(Int_t fd) : TFileHandler(fd, 1) { }\n Bool_t Notify();\n Bool_t ReadNotify() { return Notify(); }\n};\n\n\/\/______________________________________________________________________________\nBool_t TTermInputHandler::Notify()\n{\n return gApplication->HandleTermInput();\n}\n\n\nClassImp(TRint)\n\n\/\/______________________________________________________________________________\nTRint::TRint(const char *appClassName, Int_t *argc, char **argv, void *options,\n Int_t numOptions, Bool_t noLogo)\n : TApplication(appClassName, argc, argv, options, numOptions)\n{\n \/\/ Create an application environment. The TRint environment provides an\n \/\/ interface to the WM manager functionality and eventloop via inheritance\n \/\/ of TApplication and in addition provides interactive access to\n \/\/ the CINT C++ interpreter via the command line.\n\n fNcmd = 0;\n fDefaultPrompt = \"root [%d] \";\n fInterrupt = kFALSE;\n\n gBenchmark = new TBenchmark();\n\n if (!noLogo && !NoLogoOpt())\n PrintLogo();\n\n \/\/ Everybody expects iostream to be available, so load it...\n ProcessLine(\"#include \", kTRUE);\n ProcessLine(\"#include <_string>\", kTRUE); \/\/ for std::string iostream.\n\n \/\/ Allow the usage of ClassDef and ClassImp in interpreted macros\n ProcessLine(\"#include \", kTRUE);\n\n \/\/ Disallow the interpretation of Rtypes.h, TError.h and TGenericClassInfo.h\n ProcessLine(\"#define ROOT_Rtypes 0\", kTRUE);\n ProcessLine(\"#define ROOT_TError 0\", kTRUE);\n ProcessLine(\"#define ROOT_TGenericClassInfo 0\", kTRUE);\n\n \/\/ The following libs are also useful to have, make sure they are loaded...\n gROOT->LoadClass(\"TMinuit\", \"Minuit\");\n gROOT->LoadClass(\"TPostScript\", \"Postscript\");\n gROOT->LoadClass(\"THtml\", \"Html\");\n\n \/\/ Load user functions\n const char *logon;\n logon = gEnv->GetValue(\"Rint.Load\", (char*)0);\n if (logon) {\n char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);\n if (mac)\n ProcessLine(Form(\".L %s\",logon),kTRUE);\n delete [] mac;\n }\n\n \/\/ Execute logon macro\n logon = gEnv->GetValue(\"Rint.Logon\", (char*)0);\n if (logon && !NoLogOpt()) {\n char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);\n if (mac)\n ProcessFile(logon);\n delete [] mac;\n }\n\n \/\/ Save current interpreter context\n gInterpreter->SaveContext();\n gInterpreter->SaveGlobalsContext();\n\n \/\/ Install interrupt and terminal input handlers\n TInterruptHandler *ih = new TInterruptHandler();\n ih->Add();\n SetSignalHandler(ih);\n\n \/\/ Handle stdin events\n fInputHandler = new TTermInputHandler(0);\n fInputHandler->Add();\n\n \/\/ Goto into raw terminal input mode\n char defhist[128];\n#ifndef R__VMS\n sprintf(defhist, \"%s\/.root_hist\", gSystem->Getenv(\"HOME\"));\n#else\n sprintf(defhist, \"%s.root_hist\", gSystem->Getenv(\"HOME\"));\n#endif\n logon = gEnv->GetValue(\"Rint.History\", defhist);\n Gl_histinit((char *)logon);\n Gl_windowchanged();\n\n \/\/ Setup for tab completion\n gTabCom = new TTabCom;\n Gl_in_key = &key_pressed;\n}\n\n\/\/______________________________________________________________________________\nTRint::~TRint()\n{\n\n}\n\n\/\/______________________________________________________________________________\nvoid TRint::Run(Bool_t retrn)\n{\n \/\/ Main application eventloop. First process files given on the command\n \/\/ line and then go into the main application event loop, unless the -q\n \/\/ command line option was specfied in which case the program terminates.\n \/\/ When retrun is true this method returns even when -q was specified.\n \/\/\n \/\/ When QuitOpt is true and retrn is false, terminate the application with\n \/\/ an error code equal to either the ProcessLine error (if any) or the\n \/\/ return value of the command casted to a long.\n\n Getlinem(kInit, GetPrompt());\n\n Long_t retval = 0;\n Int_t error = 0;\n\n \/\/ Process shell command line input files\n if (InputFiles()) {\n Bool_t needGetlinemInit = kFALSE;\n TIter next(InputFiles());\n RETRY {\n retval = 0; error = 0;\n Int_t nfile = 0;\n TObjString *file;\n while ((file = (TObjString *)next())) {\n char cmd[256];\n if (!fNcmd)\n printf(\"\\n\");\n if (file->String().EndsWith(\".root\")) {\n const char *rfile = (const char*)file->String();\n Printf(\"Attaching file %s as _file%d...\", rfile, nfile);\n sprintf(cmd, \"TFile *_file%d = TFile::Open(\\\"%s\\\")\", nfile++, rfile);\n } else {\n Printf(\"Processing %s...\", (const char*)file->String());\n sprintf(cmd, \".x %s\", (const char*)file->String());\n }\n Getlinem(kCleanUp, 0);\n Gl_histadd(cmd);\n fNcmd++;\n\n \/\/ The ProcessLine might throw an 'exception'. In this case,\n \/\/ GetLinem(kInit,\"Root >\") is called and we are jump back\n \/\/ to RETRY ... and we have to avoid the Getlinem(kInit, GetPrompt());\n needGetlinemInit = kFALSE;\n retval = ProcessLine(cmd, kFALSE, &error);\n\n \/\/ The ProcessLine has successfully completed and we need\n \/\/ to call Getlinem(kInit, GetPrompt());\n needGetlinemInit = kTRUE;\n\n if (error != 0) break;\n }\n } ENDTRY;\n\n if (QuitOpt()) {\n if (retrn) return;\n Terminate(error == 0 ? retval : error);\n }\n\n ClearInputFiles();\n\n if (needGetlinemInit) Getlinem(kInit, GetPrompt());\n }\n\n if (QuitOpt()) {\n printf(\"\\n\");\n if (retrn) return;\n Terminate(0);\n }\n\n TApplication::Run(retrn);\n\n Getlinem(kCleanUp, 0);\n}\n\n\/\/______________________________________________________________________________\nvoid TRint::PrintLogo()\n{\n \/\/ Print the ROOT logo on standard output.\n\n Int_t iday,imonth,iyear;\n static const char *months[] = {\"January\",\"February\",\"March\",\"April\",\"May\",\n \"June\",\"July\",\"August\",\"September\",\"October\",\n \"November\",\"December\"};\n const char *root_version = gROOT->GetVersion();\n Int_t idatqq = gROOT->GetVersionDate();\n iday = idatqq%100;\n imonth = (idatqq\/100)%100;\n iyear = (idatqq\/10000);\n char *root_date = Form(\"%d %s %4d\",iday,months[imonth-1],iyear);\n\n Printf(\" *******************************************\");\n Printf(\" * *\");\n Printf(\" * W E L C O M E to R O O T *\");\n Printf(\" * *\");\n Printf(\" * Version%10s %17s *\", root_version, root_date);\n\/\/ Printf(\" * Development version *\");\n Printf(\" * *\");\n Printf(\" * You are welcome to visit our Web site *\");\n Printf(\" * http:\/\/root.cern.ch *\");\n Printf(\" * *\");\n Printf(\" *******************************************\");\n\n if (strstr(gVirtualX->GetName(), \"TTF\")) {\n Int_t major, minor, patch;\n \/\/TTF::Version(major, minor, patch);\n \/\/ avoid dependency on libGraf and hard code, will not change too often\n major = 2; minor = 1; patch = 3;\n Printf(\"\\nFreeType Engine v%d.%d.%d used to render TrueType fonts.\",\n major, minor, patch);\n }\n#ifdef _REENTRANT\n else\n printf(\"\\n\");\n Printf(\"Compiled for %s with thread support.\", gSystem->GetBuildArch());\n#else\n else\n printf(\"\\n\");\n Printf(\"Compiled for %s.\", gSystem->GetBuildArch());\n#endif\n\n gInterpreter->PrintIntro();\n\n#ifdef R__UNIX\n \/\/ Popdown X logo, only if started with -splash option\n for (int i = 0; i < Argc(); i++)\n if (!strcmp(Argv(i), \"-splash\"))\n kill(getppid(), SIGUSR1);\n#endif\n}\n\n\/\/______________________________________________________________________________\nchar *TRint::GetPrompt()\n{\n \/\/ Get prompt from interpreter. Either \"root [n]\" or \"end with '}'\".\n\n char *s = gInterpreter->GetPrompt();\n if (s[0])\n strcpy(fPrompt, s);\n else\n sprintf(fPrompt, fDefaultPrompt.Data(), fNcmd);\n\n return fPrompt;\n}\n\n\/\/______________________________________________________________________________\nconst char *TRint::SetPrompt(const char *newPrompt)\n{\n \/\/ Set a new default prompt. It returns the previous prompt.\n \/\/ The prompt may contain a %d which will be replaced by the commend\n \/\/ number. The default prompt is \"root [%d] \". The maximum length of\n \/\/ the prompt is 55 characters. To set the prompt in an interactive\n \/\/ session do:\n \/\/ root [0] ((TRint*)gROOT->GetApplication())->SetPrompt(\"aap> \")\n \/\/ aap>\n\n static TString op = fDefaultPrompt;\n\n if (newPrompt && strlen(newPrompt) <= 55)\n fDefaultPrompt = newPrompt;\n else\n Error(\"SetPrompt\", \"newPrompt too long (> 55 characters)\");\n\n return op.Data();\n}\n\n\/\/______________________________________________________________________________\nBool_t TRint::HandleTermInput()\n{\n \/\/ Handle input coming from terminal.\n\n static TStopwatch timer;\n char *line;\n\n if ((line = Getlinem(kOneChar, 0))) {\n if (line[0] == 0 && Gl_eof())\n Terminate(0);\n\n gVirtualX->SetKeyAutoRepeat(kTRUE);\n\n Gl_histadd(line);\n\n TString sline = line;\n line[0] = 0;\n\n \/\/ strip off '\\n' and leading and trailing blanks\n sline = sline.Chop();\n sline = sline.Strip(TString::kBoth);\n ReturnPressed((char*)sline.Data());\n\n fInterrupt = kFALSE;\n\n if (!gInterpreter->GetMore() && !sline.IsNull()) fNcmd++;\n\n \/\/ prevent recursive calling of this input handler\n fInputHandler->DeActivate();\n\n if (gROOT->Timer()) timer.Start();\n\n Bool_t added = kFALSE;\n#ifdef R__EH\n try {\n#endif\n TRY {\n ProcessLine(sline);\n } CATCH(excode) {\n \/\/ enable again input handler\n fInputHandler->Activate();\n added = kTRUE;\n Throw(excode);\n } ENDTRY;\n#ifdef R__EH\n }\n \/\/ handle every exception\n catch (...) {\n \/\/ enable again intput handler\n if (!added) fInputHandler->Activate();\n throw;\n }\n#endif\n\n if (gROOT->Timer()) timer.Print(\"u\");\n\n \/\/ enable again intput handler\n fInputHandler->Activate();\n\n if (!sline.BeginsWith(\".reset\"))\n gInterpreter->EndOfLineAction();\n\n gTabCom->ClearAll();\n Getlinem(kInit, GetPrompt());\n }\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nvoid TRint::Terminate(Int_t status)\n{\n \/\/ Terminate the application. Reset the terminal to sane mode and call\n \/\/ the logoff macro defined via Rint.Logoff environment variable.\n\n Getlinem(kCleanUp, 0);\n\n if (ReturnFromRun()) {\n gSystem->ExitLoop();\n } else {\n \/\/Execute logoff macro\n const char *logoff;\n logoff = gEnv->GetValue(\"Rint.Logoff\", (char*)0);\n if (logoff && !NoLogOpt()) {\n char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission);\n if (mac)\n ProcessFile(logoff);\n delete [] mac;\n }\n\n gSystem->Exit(status);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TRint::SetEchoMode(Bool_t mode)\n{\n \/\/ Set console mode:\n \/\/\n \/\/ mode = kTRUE - echo input symbols\n \/\/ mode = kFALSE - noecho input symbols\n\n Gl_config(\"noecho\", mode ? 0 : 1);\n}\nFrom Philippe: This patch insures that the temporary object created by a script given as an argument are deleted immediately (instead of __after__ the execution of the user's first command).\/\/ @(#)root\/rint:$Name: $:$Id: TRint.cxx,v 1.42 2005\/01\/05 01:28:12 rdm Exp $\n\/\/ Author: Rene Brun 17\/02\/95\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ Rint \/\/\n\/\/ \/\/\n\/\/ Rint is the ROOT Interactive Interface. It allows interactive access \/\/\n\/\/ to the ROOT system via the CINT C\/C++ interpreter. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TROOT.h\"\n#include \"TClass.h\"\n#include \"TVirtualX.h\"\n#include \"Getline.h\"\n#include \"TStyle.h\"\n#include \"TObjectTable.h\"\n#include \"TClassTable.h\"\n#include \"TStopwatch.h\"\n#include \"TBenchmark.h\"\n#include \"TRint.h\"\n#include \"TSystem.h\"\n#include \"TEnv.h\"\n#include \"TSysEvtHandler.h\"\n#include \"TError.h\"\n#include \"TException.h\"\n#include \"TInterpreter.h\"\n#include \"TObjArray.h\"\n#include \"TObjString.h\"\n#include \"TFile.h\"\n#include \"TMapFile.h\"\n#include \"TTabCom.h\"\n#include \"TError.h\"\n\n#ifdef R__UNIX\n#include \n\nextern \"C\" {\n extern int G__get_security_error();\n extern int G__genericerror(const char* msg);\n}\n#endif\n\nstatic Int_t key_pressed(Int_t key) { gApplication->KeyPressed(key); return 0; }\n\n\n\/\/----- Interrupt signal handler -----------------------------------------------\n\/\/______________________________________________________________________________\nclass TInterruptHandler : public TSignalHandler {\npublic:\n TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { }\n Bool_t Notify();\n};\n\n\/\/______________________________________________________________________________\nBool_t TInterruptHandler::Notify()\n{\n \/\/ TRint interrupt handler.\n\n if (fDelay) {\n fDelay++;\n return kTRUE;\n }\n\n \/\/ make sure we use the sbrk heap (in case of mapped files)\n gMmallocDesc = 0;\n\n if (!G__get_security_error())\n G__genericerror(\"\\n *** Break *** keyboard interrupt\");\n else {\n Break(\"TInterruptHandler::Notify\", \"keyboard interrupt\");\n if (TROOT::Initialized()) {\n Getlinem(kInit, \"Root > \");\n gInterpreter->RewindDictionary();\n Throw(GetSignal());\n }\n }\n return kTRUE;\n}\n\n\/\/----- Terminal Input file handler --------------------------------------------\n\/\/______________________________________________________________________________\nclass TTermInputHandler : public TFileHandler {\npublic:\n TTermInputHandler(Int_t fd) : TFileHandler(fd, 1) { }\n Bool_t Notify();\n Bool_t ReadNotify() { return Notify(); }\n};\n\n\/\/______________________________________________________________________________\nBool_t TTermInputHandler::Notify()\n{\n return gApplication->HandleTermInput();\n}\n\n\nClassImp(TRint)\n\n\/\/______________________________________________________________________________\nTRint::TRint(const char *appClassName, Int_t *argc, char **argv, void *options,\n Int_t numOptions, Bool_t noLogo)\n : TApplication(appClassName, argc, argv, options, numOptions)\n{\n \/\/ Create an application environment. The TRint environment provides an\n \/\/ interface to the WM manager functionality and eventloop via inheritance\n \/\/ of TApplication and in addition provides interactive access to\n \/\/ the CINT C++ interpreter via the command line.\n\n fNcmd = 0;\n fDefaultPrompt = \"root [%d] \";\n fInterrupt = kFALSE;\n\n gBenchmark = new TBenchmark();\n\n if (!noLogo && !NoLogoOpt())\n PrintLogo();\n\n \/\/ Everybody expects iostream to be available, so load it...\n ProcessLine(\"#include \", kTRUE);\n ProcessLine(\"#include <_string>\", kTRUE); \/\/ for std::string iostream.\n\n \/\/ Allow the usage of ClassDef and ClassImp in interpreted macros\n ProcessLine(\"#include \", kTRUE);\n\n \/\/ Disallow the interpretation of Rtypes.h, TError.h and TGenericClassInfo.h\n ProcessLine(\"#define ROOT_Rtypes 0\", kTRUE);\n ProcessLine(\"#define ROOT_TError 0\", kTRUE);\n ProcessLine(\"#define ROOT_TGenericClassInfo 0\", kTRUE);\n\n \/\/ The following libs are also useful to have, make sure they are loaded...\n gROOT->LoadClass(\"TMinuit\", \"Minuit\");\n gROOT->LoadClass(\"TPostScript\", \"Postscript\");\n gROOT->LoadClass(\"THtml\", \"Html\");\n\n \/\/ Load user functions\n const char *logon;\n logon = gEnv->GetValue(\"Rint.Load\", (char*)0);\n if (logon) {\n char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);\n if (mac)\n ProcessLine(Form(\".L %s\",logon),kTRUE);\n delete [] mac;\n }\n\n \/\/ Execute logon macro\n logon = gEnv->GetValue(\"Rint.Logon\", (char*)0);\n if (logon && !NoLogOpt()) {\n char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);\n if (mac)\n ProcessFile(logon);\n delete [] mac;\n }\n\n \/\/ Save current interpreter context\n gInterpreter->SaveContext();\n gInterpreter->SaveGlobalsContext();\n\n \/\/ Install interrupt and terminal input handlers\n TInterruptHandler *ih = new TInterruptHandler();\n ih->Add();\n SetSignalHandler(ih);\n\n \/\/ Handle stdin events\n fInputHandler = new TTermInputHandler(0);\n fInputHandler->Add();\n\n \/\/ Goto into raw terminal input mode\n char defhist[128];\n#ifndef R__VMS\n sprintf(defhist, \"%s\/.root_hist\", gSystem->Getenv(\"HOME\"));\n#else\n sprintf(defhist, \"%s.root_hist\", gSystem->Getenv(\"HOME\"));\n#endif\n logon = gEnv->GetValue(\"Rint.History\", defhist);\n Gl_histinit((char *)logon);\n Gl_windowchanged();\n\n \/\/ Setup for tab completion\n gTabCom = new TTabCom;\n Gl_in_key = &key_pressed;\n}\n\n\/\/______________________________________________________________________________\nTRint::~TRint()\n{\n\n}\n\n\/\/______________________________________________________________________________\nvoid TRint::Run(Bool_t retrn)\n{\n \/\/ Main application eventloop. First process files given on the command\n \/\/ line and then go into the main application event loop, unless the -q\n \/\/ command line option was specfied in which case the program terminates.\n \/\/ When retrun is true this method returns even when -q was specified.\n \/\/\n \/\/ When QuitOpt is true and retrn is false, terminate the application with\n \/\/ an error code equal to either the ProcessLine error (if any) or the\n \/\/ return value of the command casted to a long.\n\n Getlinem(kInit, GetPrompt());\n\n Long_t retval = 0;\n Int_t error = 0;\n\n \/\/ Process shell command line input files\n if (InputFiles()) {\n Bool_t needGetlinemInit = kFALSE;\n TIter next(InputFiles());\n RETRY {\n retval = 0; error = 0;\n Int_t nfile = 0;\n TObjString *file;\n while ((file = (TObjString *)next())) {\n char cmd[256];\n if (!fNcmd)\n printf(\"\\n\");\n if (file->String().EndsWith(\".root\")) {\n const char *rfile = (const char*)file->String();\n Printf(\"Attaching file %s as _file%d...\", rfile, nfile);\n sprintf(cmd, \"TFile *_file%d = TFile::Open(\\\"%s\\\")\", nfile++, rfile);\n } else {\n Printf(\"Processing %s...\", (const char*)file->String());\n sprintf(cmd, \".x %s\", (const char*)file->String());\n }\n Getlinem(kCleanUp, 0);\n Gl_histadd(cmd);\n fNcmd++;\n\n \/\/ The ProcessLine might throw an 'exception'. In this case,\n \/\/ GetLinem(kInit,\"Root >\") is called and we are jump back\n \/\/ to RETRY ... and we have to avoid the Getlinem(kInit, GetPrompt());\n needGetlinemInit = kFALSE;\n retval = ProcessLine(cmd, kFALSE, &error);\n\t gInterpreter->EndOfLineAction(); \n\n \/\/ The ProcessLine has successfully completed and we need\n \/\/ to call Getlinem(kInit, GetPrompt());\n needGetlinemInit = kTRUE;\n\n if (error != 0) break;\n }\n } ENDTRY;\n\n if (QuitOpt()) {\n if (retrn) return;\n Terminate(error == 0 ? retval : error);\n }\n\n ClearInputFiles();\n\n if (needGetlinemInit) Getlinem(kInit, GetPrompt());\n }\n\n if (QuitOpt()) {\n printf(\"\\n\");\n if (retrn) return;\n Terminate(0);\n }\n\n TApplication::Run(retrn);\n\n Getlinem(kCleanUp, 0);\n}\n\n\/\/______________________________________________________________________________\nvoid TRint::PrintLogo()\n{\n \/\/ Print the ROOT logo on standard output.\n\n Int_t iday,imonth,iyear;\n static const char *months[] = {\"January\",\"February\",\"March\",\"April\",\"May\",\n \"June\",\"July\",\"August\",\"September\",\"October\",\n \"November\",\"December\"};\n const char *root_version = gROOT->GetVersion();\n Int_t idatqq = gROOT->GetVersionDate();\n iday = idatqq%100;\n imonth = (idatqq\/100)%100;\n iyear = (idatqq\/10000);\n char *root_date = Form(\"%d %s %4d\",iday,months[imonth-1],iyear);\n\n Printf(\" *******************************************\");\n Printf(\" * *\");\n Printf(\" * W E L C O M E to R O O T *\");\n Printf(\" * *\");\n Printf(\" * Version%10s %17s *\", root_version, root_date);\n\/\/ Printf(\" * Development version *\");\n Printf(\" * *\");\n Printf(\" * You are welcome to visit our Web site *\");\n Printf(\" * http:\/\/root.cern.ch *\");\n Printf(\" * *\");\n Printf(\" *******************************************\");\n\n if (strstr(gVirtualX->GetName(), \"TTF\")) {\n Int_t major, minor, patch;\n \/\/TTF::Version(major, minor, patch);\n \/\/ avoid dependency on libGraf and hard code, will not change too often\n major = 2; minor = 1; patch = 3;\n Printf(\"\\nFreeType Engine v%d.%d.%d used to render TrueType fonts.\",\n major, minor, patch);\n }\n#ifdef _REENTRANT\n else\n printf(\"\\n\");\n Printf(\"Compiled for %s with thread support.\", gSystem->GetBuildArch());\n#else\n else\n printf(\"\\n\");\n Printf(\"Compiled for %s.\", gSystem->GetBuildArch());\n#endif\n\n gInterpreter->PrintIntro();\n\n#ifdef R__UNIX\n \/\/ Popdown X logo, only if started with -splash option\n for (int i = 0; i < Argc(); i++)\n if (!strcmp(Argv(i), \"-splash\"))\n kill(getppid(), SIGUSR1);\n#endif\n}\n\n\/\/______________________________________________________________________________\nchar *TRint::GetPrompt()\n{\n \/\/ Get prompt from interpreter. Either \"root [n]\" or \"end with '}'\".\n\n char *s = gInterpreter->GetPrompt();\n if (s[0])\n strcpy(fPrompt, s);\n else\n sprintf(fPrompt, fDefaultPrompt.Data(), fNcmd);\n\n return fPrompt;\n}\n\n\/\/______________________________________________________________________________\nconst char *TRint::SetPrompt(const char *newPrompt)\n{\n \/\/ Set a new default prompt. It returns the previous prompt.\n \/\/ The prompt may contain a %d which will be replaced by the commend\n \/\/ number. The default prompt is \"root [%d] \". The maximum length of\n \/\/ the prompt is 55 characters. To set the prompt in an interactive\n \/\/ session do:\n \/\/ root [0] ((TRint*)gROOT->GetApplication())->SetPrompt(\"aap> \")\n \/\/ aap>\n\n static TString op = fDefaultPrompt;\n\n if (newPrompt && strlen(newPrompt) <= 55)\n fDefaultPrompt = newPrompt;\n else\n Error(\"SetPrompt\", \"newPrompt too long (> 55 characters)\");\n\n return op.Data();\n}\n\n\/\/______________________________________________________________________________\nBool_t TRint::HandleTermInput()\n{\n \/\/ Handle input coming from terminal.\n\n static TStopwatch timer;\n char *line;\n\n if ((line = Getlinem(kOneChar, 0))) {\n if (line[0] == 0 && Gl_eof())\n Terminate(0);\n\n gVirtualX->SetKeyAutoRepeat(kTRUE);\n\n Gl_histadd(line);\n\n TString sline = line;\n line[0] = 0;\n\n \/\/ strip off '\\n' and leading and trailing blanks\n sline = sline.Chop();\n sline = sline.Strip(TString::kBoth);\n ReturnPressed((char*)sline.Data());\n\n fInterrupt = kFALSE;\n\n if (!gInterpreter->GetMore() && !sline.IsNull()) fNcmd++;\n\n \/\/ prevent recursive calling of this input handler\n fInputHandler->DeActivate();\n\n if (gROOT->Timer()) timer.Start();\n\n Bool_t added = kFALSE;\n#ifdef R__EH\n try {\n#endif\n TRY {\n ProcessLine(sline);\n } CATCH(excode) {\n \/\/ enable again input handler\n fInputHandler->Activate();\n added = kTRUE;\n Throw(excode);\n } ENDTRY;\n#ifdef R__EH\n }\n \/\/ handle every exception\n catch (...) {\n \/\/ enable again intput handler\n if (!added) fInputHandler->Activate();\n throw;\n }\n#endif\n\n if (gROOT->Timer()) timer.Print(\"u\");\n\n \/\/ enable again intput handler\n fInputHandler->Activate();\n\n if (!sline.BeginsWith(\".reset\"))\n gInterpreter->EndOfLineAction();\n\n gTabCom->ClearAll();\n Getlinem(kInit, GetPrompt());\n }\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nvoid TRint::Terminate(Int_t status)\n{\n \/\/ Terminate the application. Reset the terminal to sane mode and call\n \/\/ the logoff macro defined via Rint.Logoff environment variable.\n\n Getlinem(kCleanUp, 0);\n\n if (ReturnFromRun()) {\n gSystem->ExitLoop();\n } else {\n \/\/Execute logoff macro\n const char *logoff;\n logoff = gEnv->GetValue(\"Rint.Logoff\", (char*)0);\n if (logoff && !NoLogOpt()) {\n char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission);\n if (mac)\n ProcessFile(logoff);\n delete [] mac;\n }\n\n gSystem->Exit(status);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TRint::SetEchoMode(Bool_t mode)\n{\n \/\/ Set console mode:\n \/\/\n \/\/ mode = kTRUE - echo input symbols\n \/\/ mode = kFALSE - noecho input symbols\n\n Gl_config(\"noecho\", mode ? 0 : 1);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\n *\/\n\n#include \"net.hh\"\n#include \n\nusing std::move;\n\nnamespace net {\n\nl3_protocol::l3_protocol(interface* netif, eth_protocol_num proto_num)\n : _netif(netif), _proto_num(proto_num) {\n}\n\nsubscription l3_protocol::receive(\n std::function (packet p, ethernet_address from)> rx_fn,\n std::function forward) {\n return _netif->register_l3(_proto_num, std::move(rx_fn), std::move(forward));\n};\n\nfuture<> l3_protocol::send(ethernet_address to, packet p) {\n return _netif->send(_proto_num, to, std::move(p));\n}\n\ninterface::interface(std::shared_ptr dev)\n : _dev(dev)\n , _rx(_dev->receive([this] (packet p) { return dispatch_packet(std::move(p)); }))\n , _hw_address(_dev->hw_address())\n , _hw_features(_dev->hw_features()) {\n}\n\nsubscription\ninterface::register_l3(eth_protocol_num proto_num,\n std::function (packet p, ethernet_address from)> next,\n std::function forward) {\n auto i = _proto_map.emplace(std::piecewise_construct, std::make_tuple(uint16_t(proto_num)), std::forward_as_tuple(std::move(forward)));\n assert(i.second);\n l3_rx_stream& l3_rx = i.first->second;\n return l3_rx.packet_stream.listen(std::move(next));\n}\n\nvoid interface::forward(unsigned cpuid, packet p) {\n static __thread unsigned queue_depth;\n\n if (queue_depth < 1000) {\n queue_depth++;\n auto src_cpu = engine.cpu_id();\n smp::submit_to(cpuid, [this, p = std::move(p), src_cpu]() mutable {\n _dev->l2receive(p.free_on_cpu(src_cpu));\n }).then([] {\n queue_depth--;\n });\n }\n}\n\nfuture<> interface::dispatch_packet(packet p) {\n auto eh = p.get_header();\n if (eh) {\n auto i = _proto_map.find(ntoh(eh->eth_proto));\n if (i != _proto_map.end()) {\n l3_rx_stream& l3 = i->second;\n auto fw = _dev->local_queue().may_forward() ? l3.forward(p, sizeof(eth_hdr)) : engine.cpu_id();\n if (fw != engine.cpu_id() && fw < smp::count) {\n forward(fw, std::move(p));\n } else {\n if (fw != engine.cpu_id()) { \/\/ broadcast to all cpus\n for (unsigned i = 0; i< smp::count; i++) {\n if (i != engine.cpu_id()) {\n forward(i, p.share());\n }\n }\n }\n auto h = ntoh(*eh);\n auto from = h.src_mac;\n p.trim_front(sizeof(*eh));\n \/\/ avoid chaining, since queue lenth is unlimited\n \/\/ drop instead.\n if (l3.ready.available()) {\n l3.ready = l3.packet_stream.produce(std::move(p), from);\n }\n }\n }\n }\n return make_ready_future<>();\n}\n\nfuture<> interface::send(eth_protocol_num proto_num, ethernet_address to, packet p) {\n auto eh = p.prepend_header();\n eh->dst_mac = to;\n eh->src_mac = _hw_address;\n eh->eth_proto = uint16_t(proto_num);\n *eh = hton(*eh);\n return _dev->local_queue().send(std::move(p));\n}\n\n}\nnet: remove broadcast logic from forwarding path\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\n *\/\n\n#include \"net.hh\"\n#include \n\nusing std::move;\n\nnamespace net {\n\nl3_protocol::l3_protocol(interface* netif, eth_protocol_num proto_num)\n : _netif(netif), _proto_num(proto_num) {\n}\n\nsubscription l3_protocol::receive(\n std::function (packet p, ethernet_address from)> rx_fn,\n std::function forward) {\n return _netif->register_l3(_proto_num, std::move(rx_fn), std::move(forward));\n};\n\nfuture<> l3_protocol::send(ethernet_address to, packet p) {\n return _netif->send(_proto_num, to, std::move(p));\n}\n\ninterface::interface(std::shared_ptr dev)\n : _dev(dev)\n , _rx(_dev->receive([this] (packet p) { return dispatch_packet(std::move(p)); }))\n , _hw_address(_dev->hw_address())\n , _hw_features(_dev->hw_features()) {\n}\n\nsubscription\ninterface::register_l3(eth_protocol_num proto_num,\n std::function (packet p, ethernet_address from)> next,\n std::function forward) {\n auto i = _proto_map.emplace(std::piecewise_construct, std::make_tuple(uint16_t(proto_num)), std::forward_as_tuple(std::move(forward)));\n assert(i.second);\n l3_rx_stream& l3_rx = i.first->second;\n return l3_rx.packet_stream.listen(std::move(next));\n}\n\nvoid interface::forward(unsigned cpuid, packet p) {\n static __thread unsigned queue_depth;\n\n if (queue_depth < 1000) {\n queue_depth++;\n auto src_cpu = engine.cpu_id();\n smp::submit_to(cpuid, [this, p = std::move(p), src_cpu]() mutable {\n _dev->l2receive(p.free_on_cpu(src_cpu));\n }).then([] {\n queue_depth--;\n });\n }\n}\n\nfuture<> interface::dispatch_packet(packet p) {\n auto eh = p.get_header();\n if (eh) {\n auto i = _proto_map.find(ntoh(eh->eth_proto));\n if (i != _proto_map.end()) {\n l3_rx_stream& l3 = i->second;\n auto fw = _dev->local_queue().may_forward() ? l3.forward(p, sizeof(eth_hdr)) : engine.cpu_id();\n if (fw != engine.cpu_id()) {\n forward(fw, std::move(p));\n } else {\n auto h = ntoh(*eh);\n auto from = h.src_mac;\n p.trim_front(sizeof(*eh));\n \/\/ avoid chaining, since queue lenth is unlimited\n \/\/ drop instead.\n if (l3.ready.available()) {\n l3.ready = l3.packet_stream.produce(std::move(p), from);\n }\n }\n }\n }\n return make_ready_future<>();\n}\n\nfuture<> interface::send(eth_protocol_num proto_num, ethernet_address to, packet p) {\n auto eh = p.prepend_header();\n eh->dst_mac = to;\n eh->src_mac = _hw_address;\n eh->eth_proto = uint16_t(proto_num);\n *eh = hton(*eh);\n return _dev->local_queue().send(std::move(p));\n}\n\n}\n<|endoftext|>"} {"text":"#include \"test\/test_syscoin_services.h\"\n#include \"data\/utxo.json.h\"\n#include \"utiltime.h\"\n#include \"rpcserver.h\"\n#include \n#include \n\nextern UniValue read_json(const std::string& jsondata);\nBOOST_FIXTURE_TEST_SUITE (syscoin_snapshot_tests, SyscoinMainNetSetup)\nstruct PaymentAmount\n{\n\tstd::string address;\n\tstd::string amount;\n};\nvoid VerifySnapShot()\n{\n}\nvoid GenerateSnapShot()\n{\n}\nvoid GetUTXOs(std::vector &paymentAmounts)\n{\n UniValue tests = read_json(std::string(json_tests::utxo, json_tests::utxo + sizeof(json_tests::utxo)));\n for (unsigned int idx = 0; idx < tests.size(); idx++) {\n UniValue test = tests[idx];\n std::string strTest = test.write();\n if (test.size() < 2) \/\/ Allow for extra stuff (useful for comments)\n {\n BOOST_ERROR(\"Bad test: \" << strTest);\n continue;\n }\n\t\tPaymentAmount payment;\n payment.address = test[0].get_str();\n payment.amount = ValueFromAmount(test[1].get_int64()).write();\n\t\tpaymentAmounts.push_back(payment);\n }\n}\nbool IsMainNetAlreadyCreated()\n{\n\tint height;\n\tUniValue r;\n\tBOOST_CHECK_NO_THROW(r = CallRPC(\"mainnet1\", \"getinfo\", false));\n\theight = find_value(r.get_obj(), \"blocks\").get_int();\n\treturn height > 0;\n}\nBOOST_AUTO_TEST_CASE (generate_and_verify_snapshot)\n{\n\tstd::vector paymentAmounts;\n\tGetUTXOs(paymentAmounts);\n\tif(IsMainNetAlreadyCreated())\n\t{\n\t\tVerifySnapShot();\n\t}\n\telse\n\t{\n\t\tGenerateSnapShot();\n\t\tVerifySnapShot();\n\t}\n}\nBOOST_AUTO_TEST_SUITE_END ()send snapshot payment#include \"test\/test_syscoin_services.h\"\n#include \"data\/utxo.json.h\"\n#include \"utiltime.h\"\n#include \"rpcserver.h\"\n#include \n#include \nint currentTx = 0;\nextern UniValue read_json(const std::string& jsondata);\nBOOST_FIXTURE_TEST_SUITE (syscoin_snapshot_tests, SyscoinMainNetSetup)\nstruct PaymentAmount\n{\n\tstd::string address;\n\tstd::string amount;\n};\nvoid VerifySnapShot()\n{\n}\nvoid SendSnapShotPayment(const std::string &strSend)\n{\n\tcurrentTx++;\n\tstd::string strSendMany = \"sendmany \\\"\\\" \" + strSend + \"}\";\n\tstd::\n\tUniValue r;\n\tprintf(\"strSendMany #%d: %s\\n\", currentTx, strSendMany);\n\tBOOST_CHECK_NO_THROW(r = CallRPC(\"mainnet1\", strSendMany, false));\n}\nvoid GenerateSnapShot(const std::vector &paymentAmounts)\n{\n\tint numberOfTxPerBlock = 1000;\n\tstd::string sendManyString = \"\";\n\tfor(int i =0;i &paymentAmounts)\n{\n UniValue tests = read_json(std::string(json_tests::utxo, json_tests::utxo + sizeof(json_tests::utxo)));\n for (unsigned int idx = 0; idx < tests.size(); idx++) {\n UniValue test = tests[idx];\n std::string strTest = test.write();\n if (test.size() < 2) \/\/ Allow for extra stuff (useful for comments)\n {\n BOOST_ERROR(\"Bad test: \" << strTest);\n continue;\n }\n\t\tPaymentAmount payment;\n payment.address = test[0].get_str();\n payment.amount = ValueFromAmount(test[1].get_int64()).write();\n\t\tpaymentAmounts.push_back(payment);\n }\n}\nbool IsMainNetAlreadyCreated()\n{\n\tint height;\n\tUniValue r;\n\tBOOST_CHECK_NO_THROW(r = CallRPC(\"mainnet1\", \"getinfo\", false));\n\theight = find_value(r.get_obj(), \"blocks\").get_int();\n\treturn height > 0;\n}\nBOOST_AUTO_TEST_CASE (generate_and_verify_snapshot)\n{\n\tstd::vector paymentAmounts;\n\tGetUTXOs(paymentAmounts);\n\tif(IsMainNetAlreadyCreated())\n\t{\n\t\tVerifySnapShot();\n\t}\n\telse\n\t{\n\t\tGenerateSnapShot();\n\t\tVerifySnapShot();\n\t}\n}\nBOOST_AUTO_TEST_SUITE_END ()<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \"quicklook.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\n#ifdef __APPLE__\n\nvoid acmacs::quicklook(std::string_view aFilename, size_t aDelayInSeconds)\n{\n run_and_detach({\"\/usr\/bin\/qlmanage\", \"-p\", aFilename.data()}, 0);\n if (aDelayInSeconds) {\n using namespace std::chrono_literals;\n std::this_thread::sleep_for(1s * aDelayInSeconds);\n }\n\n} \/\/ acmacs::quicklook\n\nvoid acmacs::open(std::string_view aFilename, size_t aDelayBeforeInSeconds, size_t aDelayAfterInSeconds)\n{\n run_and_detach({\"\/usr\/bin\/open\", aFilename.data()}, aDelayBeforeInSeconds);\n if (aDelayAfterInSeconds) {\n using namespace std::chrono_literals;\n std::this_thread::sleep_for(1s * aDelayAfterInSeconds);\n }\n\n} \/\/ acmacs::quicklook\n\n#else\n\nvoid acmacs::quicklook(std::string_view \/*aFilename*\/, size_t \/*aDelayInSeconds*\/)\n{\n}\n\nvoid acmacs::open(std::string_view \/*aFilename*\/, size_t \/*aDelayBeforeInSeconds*\/, size_t \/*aDelayAfterInSeconds*\/)\n{\n}\n\n#endif\n\n\/\/ ----------------------------------------------------------------------\n\nvoid acmacs::run_and_detach(std::initializer_list argv, size_t aDelayBeforeInSeconds)\n{\n if (!fork()) {\n close(0);\n close(1);\n close(2);\n setsid();\n if (aDelayBeforeInSeconds) {\n using namespace std::chrono_literals;\n std::this_thread::sleep_for(1s * aDelayBeforeInSeconds);\n }\n std::vector argv_v{argv};\n argv_v.push_back(nullptr);\n execvp(argv_v[0], const_cast(argv_v.data()));\n perror(argv_v[0]);\n std::exit(-1);\n }\n\n} \/\/ acmacs::run_and_detach\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\nopen image in background#include \n#include \n#include \n#include \n#include \n\n#include \"quicklook.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\n#ifdef __APPLE__\n\nvoid acmacs::quicklook(std::string_view aFilename, size_t aDelayInSeconds)\n{\n run_and_detach({\"\/usr\/bin\/qlmanage\", \"-p\", aFilename.data()}, 0);\n if (aDelayInSeconds) {\n using namespace std::chrono_literals;\n std::this_thread::sleep_for(1s * aDelayInSeconds);\n }\n\n} \/\/ acmacs::quicklook\n\nvoid acmacs::open(std::string_view aFilename, size_t aDelayBeforeInSeconds, size_t aDelayAfterInSeconds)\n{\n run_and_detach({\"\/usr\/bin\/open\", \"-g\", aFilename.data()}, aDelayBeforeInSeconds);\n if (aDelayAfterInSeconds) {\n using namespace std::chrono_literals;\n std::this_thread::sleep_for(1s * aDelayAfterInSeconds);\n }\n\n} \/\/ acmacs::quicklook\n\n#else\n\nvoid acmacs::quicklook(std::string_view \/*aFilename*\/, size_t \/*aDelayInSeconds*\/)\n{\n}\n\nvoid acmacs::open(std::string_view \/*aFilename*\/, size_t \/*aDelayBeforeInSeconds*\/, size_t \/*aDelayAfterInSeconds*\/)\n{\n}\n\n#endif\n\n\/\/ ----------------------------------------------------------------------\n\nvoid acmacs::run_and_detach(std::initializer_list argv, size_t aDelayBeforeInSeconds)\n{\n if (!fork()) {\n close(0);\n close(1);\n close(2);\n setsid();\n if (aDelayBeforeInSeconds) {\n using namespace std::chrono_literals;\n std::this_thread::sleep_for(1s * aDelayBeforeInSeconds);\n }\n std::vector argv_v{argv};\n argv_v.push_back(nullptr);\n execvp(argv_v[0], const_cast(argv_v.data()));\n perror(argv_v[0]);\n std::exit(-1);\n }\n\n} \/\/ acmacs::run_and_detach\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"acmacs-base\/xz.hh\"\n#include \"acmacs-base\/bzip2.hh\"\n#include \"acmacs-base\/string.hh\"\n#include \"acmacs-base\/read-file.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nacmacs::file::read_access::read_access(std::string aFilename)\n{\n if (fs::exists(aFilename)) {\n len = fs::file_size(aFilename);\n fd = ::open(aFilename.c_str(), O_RDONLY);\n if (fd >= 0) {\n mapped = reinterpret_cast(mmap(nullptr, len, PROT_READ, MAP_FILE|MAP_PRIVATE, fd, 0));\n if (mapped == MAP_FAILED)\n throw cannot_read(aFilename + \": \" + strerror(errno));\n }\n else {\n throw not_opened(aFilename + \": \" + strerror(errno));\n }\n }\n else {\n throw not_found{aFilename};\n }\n\n} \/\/ acmacs::file::read_access\n\n\/\/ ----------------------------------------------------------------------\n\nacmacs::file::read_access::read_access(read_access&& other)\n : fd{other.fd}, len{other.len}, mapped{other.mapped}\n{\n other.fd = -1;\n other.len = 0;\n other.mapped = nullptr;\n\n} \/\/ acmacs::file::read_access::read_access\n\n\/\/ ----------------------------------------------------------------------\n\nacmacs::file::read_access::~read_access()\n{\n if (fd >= 0) {\n if (mapped)\n munmap(mapped, len);\n close(fd);\n }\n\n} \/\/ acmacs::file::read_access::~read_access\n\n\/\/ ----------------------------------------------------------------------\n\nacmacs::file::read_access& acmacs::file::read_access::operator=(read_access&& other)\n{\n fd = other.fd;\n len = other.len;\n mapped = other.mapped;\n\n other.fd = -1;\n other.len = 0;\n other.mapped = nullptr;\n\n return *this;\n\n} \/\/ acmacs::file::read_access::operator=\n\n\/\/ ----------------------------------------------------------------------\n\nstd::string acmacs::file::decompress_if_necessary(std::string_view aSource)\n{\n if (xz_compressed(aSource.data()))\n return xz_decompress(aSource);\n else if (bz2_compressed(aSource.data()))\n return bz2_decompress(aSource);\n else\n return std::string(aSource);\n\n} \/\/ acmacs::file::decompress_if_necessary\n\n\/\/ ----------------------------------------------------------------------\n\nstd::string acmacs::file::read_from_file_descriptor(int fd, size_t chunk_size)\n{\n std::string buffer;\n std::string::size_type offset = 0;\n for (;;) {\n buffer.resize(buffer.size() + chunk_size, ' ');\n const auto bytes_read = ::read(fd, (&*buffer.begin()) + offset, chunk_size);\n if (bytes_read < 0)\n throw std::runtime_error(std::string(\"Cannot read from file descriptor: \") + strerror(errno));\n if (static_cast(bytes_read) < chunk_size) {\n buffer.resize(buffer.size() - chunk_size + static_cast(bytes_read));\n break;\n }\n offset += static_cast(bytes_read);\n }\n return decompress_if_necessary(std::string_view(buffer));\n\n} \/\/ acmacs::file::read_from_file_descriptor\n\n\/\/ ----------------------------------------------------------------------\n\nvoid acmacs::file::backup(std::string aFilename)\n{\n fs::path to_backup{aFilename};\n if (fs::exists(to_backup)) {\n fs::path backup_dir = to_backup.parent_path() \/ \".backup\";\n create_directory(backup_dir);\n\n for (int version = 1; version < 1000; ++version) {\n char infix[10];\n std::sprintf(infix, \".~%03d~\", version);\n fs::path new_name = backup_dir \/ (to_backup.stem().string() + infix + to_backup.extension().string());\n if (!fs::exists(new_name) || version == 999) {\n fs::copy_file(to_backup, new_name, fs::copy_options::overwrite_existing);\n break;\n }\n }\n }\n\n} \/\/ acmacs::file::backup\n\n\/\/ ----------------------------------------------------------------------\n\nvoid acmacs::file::write(std::string aFilename, std::string_view aData, ForceCompression aForceCompression, BackupFile aBackupFile)\n{\n int f = -1;\n if (aFilename == \"-\") {\n f = 1;\n }\n else if (aFilename == \"=\") {\n f = 2;\n }\n else {\n if (aBackupFile == BackupFile::Yes)\n backup(aFilename);\n f = open(aFilename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0644);\n if (f < 0)\n throw std::runtime_error(std::string(\"Cannot open \") + aFilename + \": \" + strerror(errno));\n }\n try {\n if (aForceCompression == ForceCompression::Yes || (aFilename.size() > 3 && string::ends_with(aFilename, \".xz\"))) {\n const auto compressed = xz_compress(aData);\n if (::write(f, compressed.data(), compressed.size()) < 0)\n throw std::runtime_error(std::string(\"Cannot write \") + aFilename + \": \" + strerror(errno));\n }\n else {\n if (::write(f, aData.data(), aData.size()) < 0)\n throw std::runtime_error(std::string(\"Cannot write \") + aFilename + \": \" + strerror(errno));\n }\n if (f > 2)\n close(f);\n }\n catch (std::exception&) {\n if (f > 2)\n close(f);\n throw;\n }\n\n} \/\/ acmacs::file::write\n\n\/\/ ----------------------------------------------------------------------\n\nacmacs::file::temp::temp(std::string suffix)\n : name(make_template() + suffix), fd(mkstemps(const_cast(name.c_str()), static_cast(suffix.size())))\n{\n if (fd < 0)\n throw std::runtime_error(std::string(\"Cannot create temporary file using template \") + name + \": \" + strerror(errno));\n\n} \/\/ acmacs::file::temp::temp\n\n\/\/ ----------------------------------------------------------------------\n\nacmacs::file::temp::~temp()\n{\n if (!name.empty())\n fs::remove(name.c_str());\n\n} \/\/ acmacs::file::temp::~temp\n\n\/\/ ----------------------------------------------------------------------\n\nstd::string acmacs::file::temp::make_template()\n{\n const char* tdir = std::getenv(\"T\");\n if (!tdir)\n tdir = std::getenv(\"TMPDIR\");\n if (!tdir)\n tdir = \"\/tmp\";\n return tdir + std::string{\"\/AD.XXXXXXXX\"};\n\n} \/\/ acmacs::file::temp::make_template\n\n\/\/ ----------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\nbug fix#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"acmacs-base\/xz.hh\"\n#include \"acmacs-base\/bzip2.hh\"\n#include \"acmacs-base\/string.hh\"\n#include \"acmacs-base\/read-file.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nacmacs::file::read_access::read_access(std::string aFilename)\n{\n if (fs::exists(aFilename)) {\n len = fs::file_size(aFilename);\n fd = ::open(aFilename.c_str(), O_RDONLY);\n if (fd >= 0) {\n mapped = reinterpret_cast(mmap(nullptr, len, PROT_READ, MAP_FILE|MAP_PRIVATE, fd, 0));\n if (mapped == MAP_FAILED)\n throw cannot_read(aFilename + \": \" + strerror(errno));\n }\n else {\n throw not_opened(aFilename + \": \" + strerror(errno));\n }\n }\n else {\n throw not_found{aFilename};\n }\n\n} \/\/ acmacs::file::read_access\n\n\/\/ ----------------------------------------------------------------------\n\nacmacs::file::read_access::read_access(read_access&& other)\n : fd{other.fd}, len{other.len}, mapped{other.mapped}\n{\n other.fd = -1;\n other.len = 0;\n other.mapped = nullptr;\n\n} \/\/ acmacs::file::read_access::read_access\n\n\/\/ ----------------------------------------------------------------------\n\nacmacs::file::read_access::~read_access()\n{\n if (fd >= 0) {\n if (mapped)\n munmap(mapped, len);\n close(fd);\n }\n\n} \/\/ acmacs::file::read_access::~read_access\n\n\/\/ ----------------------------------------------------------------------\n\nacmacs::file::read_access& acmacs::file::read_access::operator=(read_access&& other)\n{\n fd = other.fd;\n len = other.len;\n mapped = other.mapped;\n\n other.fd = -1;\n other.len = 0;\n other.mapped = nullptr;\n\n return *this;\n\n} \/\/ acmacs::file::read_access::operator=\n\n\/\/ ----------------------------------------------------------------------\n\nstd::string acmacs::file::decompress_if_necessary(std::string_view aSource)\n{\n if (xz_compressed(aSource.data()))\n return xz_decompress(aSource);\n else if (bz2_compressed(aSource.data()))\n return bz2_decompress(aSource);\n else\n return std::string(aSource);\n\n} \/\/ acmacs::file::decompress_if_necessary\n\n\/\/ ----------------------------------------------------------------------\n\nstd::string acmacs::file::read_from_file_descriptor(int fd, size_t chunk_size)\n{\n std::string buffer;\n std::string::size_type offset = 0;\n for (;;) {\n buffer.resize(buffer.size() + chunk_size, ' ');\n const auto bytes_read = ::read(fd, (&*buffer.begin()) + offset, chunk_size);\n if (bytes_read < 0)\n throw std::runtime_error(std::string(\"Cannot read from file descriptor: \") + strerror(errno));\n if (static_cast(bytes_read) < chunk_size) {\n buffer.resize(buffer.size() - chunk_size + static_cast(bytes_read));\n break;\n }\n offset += static_cast(bytes_read);\n }\n return decompress_if_necessary(std::string_view(buffer));\n\n} \/\/ acmacs::file::read_from_file_descriptor\n\n\/\/ ----------------------------------------------------------------------\n\nvoid acmacs::file::backup(std::string aFilename)\n{\n fs::path to_backup{aFilename};\n if (fs::exists(to_backup)) {\n fs::path backup_dir = to_backup.parent_path() \/ \".backup\";\n create_directory(backup_dir);\n\n for (int version = 1; version < 1000; ++version) {\n char infix[10];\n std::sprintf(infix, \".~%03d~\", version);\n fs::path new_name = backup_dir \/ (to_backup.stem().string() + infix + to_backup.extension().string());\n if (!fs::exists(new_name) || version == 999) {\n fs::copy_file(to_backup, new_name, fs::copy_options::overwrite_existing);\n break;\n }\n }\n }\n\n} \/\/ acmacs::file::backup\n\n\/\/ ----------------------------------------------------------------------\n\nvoid acmacs::file::write(std::string aFilename, std::string_view aData, ForceCompression aForceCompression, BackupFile aBackupFile)\n{\n int f = -1;\n if (aFilename == \"-\") {\n f = 1;\n }\n else if (aFilename == \"=\") {\n f = 2;\n }\n else {\n if (aBackupFile == BackupFile::Yes)\n backup(aFilename);\n f = open(aFilename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0644);\n if (f < 0)\n throw std::runtime_error(std::string(\"Cannot open \") + aFilename + \": \" + strerror(errno));\n }\n try {\n if (aForceCompression == ForceCompression::Yes || (aFilename.size() > 3 && string::ends_with(aFilename, \".xz\"))) {\n const auto compressed = xz_compress(aData);\n if (::write(f, compressed.data(), compressed.size()) < 0)\n throw std::runtime_error(std::string(\"Cannot write \") + aFilename + \": \" + strerror(errno));\n }\n else {\n if (::write(f, aData.data(), aData.size()) < 0)\n throw std::runtime_error(std::string(\"Cannot write \") + aFilename + \": \" + strerror(errno));\n }\n if (f > 2)\n close(f);\n }\n catch (std::exception&) {\n if (f > 2)\n close(f);\n throw;\n }\n\n} \/\/ acmacs::file::write\n\n\/\/ ----------------------------------------------------------------------\n\nacmacs::file::temp::temp(std::string suffix)\n : name(make_template() + suffix), fd(mkstemps(const_cast(name.c_str()), static_cast(suffix.size())))\n{\n if (fd < 0)\n throw std::runtime_error(std::string(\"Cannot create temporary file using template \") + name + \": \" + strerror(errno));\n\n} \/\/ acmacs::file::temp::temp\n\n\/\/ ----------------------------------------------------------------------\n\nacmacs::file::temp::~temp()\n{\n if (!name.empty())\n fs::remove(name.c_str());\n\n} \/\/ acmacs::file::temp::~temp\n\n\/\/ ----------------------------------------------------------------------\n\nstd::string acmacs::file::temp::make_template()\n{\n const char* tdir = std::getenv(\"T\");\n if (!tdir || *tdir != '\/')\n tdir = std::getenv(\"TMPDIR\");\n if (!tdir)\n tdir = \"\/tmp\";\n return tdir + std::string{\"\/AD.XXXXXXXX\"};\n\n} \/\/ acmacs::file::temp::make_template\n\n\/\/ ----------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"#include \nusing namespace std;\n\nint main(void) {\n\tcout<<\"hello, world!\"<remove POJCoding.cpp<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"novoht.h\"\n\nNoVoHT::NoVoHT(){\n kvpairs = new kvpair*[1000];\n size = 1000;\n numEl = 0;\n magicNumber = 1000;\n resizeNum = -1;\n resizing = false;\n oldpairs = NULL;\n}\n\n\/*\nNoVoHT::NoVoHT(int s){\n kvpairs = new kvpair*[s];\n size = s;\n numEl=0;\n file = NULL;\n}\n\nNoVoHT::NoVoHT(char * f){\n kvpairs = new kvpair*[1000];\n size = 1000;\n numEl=0;\n file = f;\n readFile();\n}\n*\/\nNoVoHT::NoVoHT(string f,int s, int m){\n kvpairs = new kvpair*[s];\n for (int x = 0;x= size*resizeNum) {\n if (resizeNum !=0){\n printf(\"Resizing\\n\");\n resize(size*2);\n }\n }\n int slot;\n slot = hash(k)%size;\n kvpair *cur = kvpairs[slot];\n kvpair *add = new kvpair;\n add->key = k;\n add->val = v;\n add->next = NULL;\n if (cur == NULL){\n kvpairs[slot] = add;\n numEl++;\n return write(add);\n }\n while (cur->next != NULL){\n if (k.compare(cur->key) == 0) {delete add; return -1;}\n cur = cur->next;\n }\n if (k.compare(cur->key) == 0) {delete add; return -1;}\n cur->next = add;\n numEl++;\n return write(add);\n}\n\nstring* NoVoHT::get(string k){\n while(resizing){ \/* Wait till done *\/}\n int loc = hash(k)%size;\n kvpair *cur = kvpairs[loc];\n while (cur != NULL && !k.empty()){\n if (k.compare(cur->key) == 0) return &(cur->val);\n cur = cur->next;\n }\n return NULL;\n}\n\n\/\/return 0 for success, -1 fail to remove, -2+ write failure\nint NoVoHT::remove(string k){\n while(resizing){ \/* Wait till done *\/}\n int ret =0;\n int loc = hash(k)%size;\n kvpair *cur = kvpairs[loc];\n if (cur == NULL) return ret-1; \/\/not found\n if (k.compare(cur->key) ==0) {\n fpos_t toRem = kvpairs[loc]->pos;\n kvpairs[loc] = cur->next;\n numEl--;\n ret+=mark(toRem);\n delete cur;\n nRem++;\n if (nRem == magicNumber) ret+=writeFile(); \/\/write and save write success\n return ret;\n }\n while(cur != NULL){\n if (cur->next == NULL) return ret-1;\n else if (k.compare(cur->next->key)==0){\n kvpair *r = cur->next;\n cur->next = r->next;\n ret+=mark(r->pos); \/\/mark and sace status code\n delete r;\n numEl--;\n nRem++;\n if (nRem == magicNumber) ret+=writeFile(); \/\/mark and sace status code\n return ret;\n }\n cur = cur->next;\n }\n return ret-1; \/\/not found\n}\n\n\/\/return 0 if success -2 if failed\n\/\/write hashmap to file\nint NoVoHT::writeFile(){\n int ret =0;\n if (!dbfile)return (filename.compare(\"\") == 0 ? 0 : -2);\n rewind(dbfile);\n for (int i=0; ikey.empty() && !cur->val.empty()){\n fgetpos(dbfile, &(cur->pos));\n fprintf(dbfile, \"%s\\t%s\\t\", cur->key.c_str(), cur->val.c_str());\n }\n cur = cur->next;\n }\n }\n truncate(filename.c_str(), (off_t)SEEK_CUR-SEEK_SET-1);\n return ret;\n}\n\n\/\/success 0 fail -2\n\/\/resize the hashmap's base size\nvoid NoVoHT::resize(int ns){\n int olds = size;\n size = ns;\n oldpairs = kvpairs;\n resizing = true;\n kvpairs = new kvpair*[ns];\n for (int z=0; zkey)%size;\n kvpair * tmp = kvpairs[pos];\n kvpairs[pos] = cur;\n cur = cur->next;\n kvpairs[pos]->next = tmp;\n }\n }\n resizing = false;\n delete [] oldpairs;\n}\n\n\/\/success 0 fail -2\n\/\/write kvpair to file\nint NoVoHT::write(kvpair * p){\n if (!dbfile)return (filename.compare(\"\") == 0 ? 0 : -2);\n fseek(dbfile, 0, SEEK_END);\n fgetpos(dbfile, &(p->pos));\n fprintf(dbfile, \"%s\\t%s\\t\", p->key.c_str(), p->val.c_str());\n return 0;\n}\n\n\/\/success 0 fail -2\n\/\/mark line in file for deletion\nint NoVoHT::mark(fpos_t position){\n if (!dbfile)return (filename.compare(\"\") == 0 ? 0 : -2);\n fsetpos(dbfile, &position);\n fputc((int) '~', dbfile);\n return 0;\n}\nchar *readTabString(FILE *file, char *buffer){\n int n =0;\n char t;\n while((t=fgetc(file)) != EOF){\n if (t == '\\t') {\n buffer[n] = '\\0';\n return buffer;\n }\n buffer[n] = t;\n n++;\n }\n buffer[n] = '\\0';\n return (n == 0 ? NULL : buffer);\n}\n\nvoid NoVoHT::readFile(){\n if(!dbfile) return;\n char s[300];\n char v[300];\n while(readTabString(dbfile, s) != NULL){\n string key(s);\n if (readTabString(dbfile, v) == NULL) break;\n string val(v);\n if (key[0] != '~'){\n put(key,val);\n }\n cout << key << \":\" << val << endl;\n }\n writeFile();\n}\n\nunsigned long long hash(string k){ \/\/FNV hash\n#if SIZE_OF_LONG_LONG_INT==8\n#define FNV_PRIME 14695981039346656037\n#define FNV_OFFSET 1099511628211\n#else \/\/SIZE_OF_LONG_LONG_INT == 4\n#define FNV_PRIME 16777619\n#define FNV_OFFSET 2166136261\n#endif\n unsigned long long x = FNV_PRIME;\n for (unsigned int y=0;ynext);\n delete p;\n }\n}\n\tmodified: novoht.cxx#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"novoht.h\"\n\nNoVoHT::NoVoHT(){\n kvpairs = new kvpair*[1000];\n size = 1000;\n numEl = 0;\n magicNumber = 1000;\n resizeNum = -1;\n resizing = false;\n oldpairs = NULL;\n}\n\n\/*\nNoVoHT::NoVoHT(int s){\n kvpairs = new kvpair*[s];\n size = s;\n numEl=0;\n file = NULL;\n}\n\nNoVoHT::NoVoHT(char * f){\n kvpairs = new kvpair*[1000];\n size = 1000;\n numEl=0;\n file = f;\n readFile();\n}\n*\/\nNoVoHT::NoVoHT(string f,int s, int m){\n kvpairs = new kvpair*[s];\n for (int x = 0;x= size*resizeNum) {\n if (resizeNum !=0){\n printf(\"Resizing\\n\");\n resize(size*2);\n }\n }\n int slot;\n slot = hash(k)%size;\n kvpair *cur = kvpairs[slot];\n kvpair *add = new kvpair;\n add->key = k;\n add->val = v;\n add->next = NULL;\n if (cur == NULL){\n kvpairs[slot] = add;\n numEl++;\n return write(add);\n }\n while (cur->next != NULL){\n if (k.compare(cur->key) == 0) {delete add; return -1;}\n cur = cur->next;\n }\n if (k.compare(cur->key) == 0) {delete add; return -1;}\n cur->next = add;\n numEl++;\n return write(add);\n}\n\nstring* NoVoHT::get(string k){\n while(resizing){ \/* Wait till done *\/}\n int loc = hash(k)%size;\n kvpair *cur = kvpairs[loc];\n while (cur != NULL && !k.empty()){\n if (k.compare(cur->key) == 0) return &(cur->val);\n cur = cur->next;\n }\n return NULL;\n}\n\n\/\/return 0 for success, -1 fail to remove, -2+ write failure\nint NoVoHT::remove(string k){\n while(resizing){ \/* Wait till done *\/}\n int ret =0;\n int loc = hash(k)%size;\n kvpair *cur = kvpairs[loc];\n if (cur == NULL) return ret-1; \/\/not found\n if (k.compare(cur->key) ==0) {\n fpos_t toRem = kvpairs[loc]->pos;\n kvpairs[loc] = cur->next;\n numEl--;\n ret+=mark(toRem);\n delete cur;\n nRem++;\n if (nRem == magicNumber) ret+=writeFile(); \/\/write and save write success\n return ret;\n }\n while(cur != NULL){\n if (cur->next == NULL) return ret-1;\n else if (k.compare(cur->next->key)==0){\n kvpair *r = cur->next;\n cur->next = r->next;\n ret+=mark(r->pos); \/\/mark and sace status code\n delete r;\n numEl--;\n nRem++;\n if (nRem == magicNumber) ret+=writeFile(); \/\/mark and sace status code\n return ret;\n }\n cur = cur->next;\n }\n return ret-1; \/\/not found\n}\n\n\/\/return 0 if success -2 if failed\n\/\/write hashmap to file\nint NoVoHT::writeFile(){\n int ret =0;\n if (!dbfile)return (filename.compare(\"\") == 0 ? 0 : -2);\n rewind(dbfile);\n for (int i=0; ikey.empty() && !cur->val.empty()){\n fgetpos(dbfile, &(cur->pos));\n fprintf(dbfile, \"%s\\t%s\\t\", cur->key.c_str(), cur->val.c_str());\n }\n cur = cur->next;\n }\n }\n truncate(filename.c_str(), (off_t)SEEK_CUR-SEEK_SET-1);\n return ret;\n}\n\n\/\/success 0 fail -2\n\/\/resize the hashmap's base size\nvoid NoVoHT::resize(int ns){\n int olds = size;\n size = ns;\n oldpairs = kvpairs;\n resizing = true;\n kvpairs = new kvpair*[ns];\n for (int z=0; zkey)%size;\n kvpair * tmp = kvpairs[pos];\n kvpairs[pos] = cur;\n cur = cur->next;\n kvpairs[pos]->next = tmp;\n }\n }\n resizing = false;\n delete [] oldpairs;\n}\n\n\/\/success 0 fail -2\n\/\/write kvpair to file\nint NoVoHT::write(kvpair * p){\n if (!dbfile)return (filename.compare(\"\") == 0 ? 0 : -2);\n fseek(dbfile, 0, SEEK_END);\n fgetpos(dbfile, &(p->pos));\n fprintf(dbfile, \"%s\\t%s\\t\", p->key.c_str(), p->val.c_str());\n return 0;\n}\n\n\/\/success 0 fail -2\n\/\/mark line in file for deletion\nint NoVoHT::mark(fpos_t position){\n if (!dbfile)return (filename.compare(\"\") == 0 ? 0 : -2);\n fsetpos(dbfile, &position);\n fputc((int) '~', dbfile);\n return 0;\n}\nchar *readTabString(FILE *file, char *buffer){\n int n =0;\n char t;\n while((t=fgetc(file)) != EOF){\n if (t == '\\t') {\n buffer[n] = '\\0';\n return buffer;\n }\n buffer[n] = t;\n n++;\n }\n buffer[n] = '\\0';\n return (n == 0 ? NULL : buffer);\n}\n\nvoid NoVoHT::readFile(){\n if(!dbfile) return;\n char s[300];\n char v[300];\n while(readTabString(dbfile, s) != NULL){\n string key(s);\n if (readTabString(dbfile, v) == NULL) break;\n string val(v);\n if (key[0] != '~'){\n put(key,val);\n }\n }\n writeFile();\n}\n\nunsigned long long hash(string k){ \/\/FNV hash\n#if SIZE_OF_LONG_LONG_INT==8\n#define FNV_PRIME 14695981039346656037\n#define FNV_OFFSET 1099511628211\n#else \/\/SIZE_OF_LONG_LONG_INT == 4\n#define FNV_PRIME 16777619\n#define FNV_OFFSET 2166136261\n#endif\n unsigned long long x = FNV_PRIME;\n for (unsigned int y=0;ynext);\n delete p;\n }\n}\n<|endoftext|>"} {"text":"\/** @file dbfactory.cc\n * @brief Database factories for non-remote databases.\n *\/\n\/* Copyright 2002,2003,2004,2005,2006,2007,2008,2009,2011,2012,2013,2014,2015,2016,2017,2019 Olly Betts\n * Copyright 2008 Lemur Consulting Ltd\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n * USA\n *\/\n\n#include \"config.h\"\n\n#include \"xapian\/dbfactory.h\"\n\n#include \"xapian\/constants.h\"\n#include \"xapian\/database.h\"\n#include \"xapian\/error.h\"\n#include \"xapian\/version.h\" \/\/ For XAPIAN_HAS_XXX_BACKEND.\n\n#include \"xapian\/backends\/backends.h\"\n#include \"xapian\/backends\/databasehelpers.h\"\n#include \"xapian\/common\/debuglog.h\"\n#include \"xapian\/common\/filetests.h\"\n#include \"xapian\/common\/fileutils.h\"\n#include \"xapian\/common\/posixy_wrapper.h\"\n#include \"xapian\/common\/str.h\"\n\n#include \n#include \/\/ For atoi().\n\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n# include \"xapian\/backends\/glass\/glass_database.h\"\n#endif\n#include \"xapian\/backends\/glass\/glass_defs.h\"\n#ifdef XAPIAN_HAS_HONEY_BACKEND\n# include \"xapian\/backends\/honey\/honey_database.h\"\n#endif\n#include \"xapian\/backends\/honey\/honey_defs.h\"\n#ifdef XAPIAN_HAS_INMEMORY_BACKEND\n# include \"xapian\/backends\/inmemory\/inmemory_database.h\"\n#endif\n\/\/ Even if none of the above get included, we still need a definition of\n\/\/ Database::Internal.\n#include \"xapian\/backends\/databaseinternal.h\"\n\n#include \n#include \n\nusing namespace std;\n\nnamespace Xapian {\n\nstatic void\nopen_stub(Database& db, const string& file)\n{\n read_stub_file(file,\n\t\t [&db](const string& path) {\n\t\t db.add_database(Database(path));\n\t\t },\n\t\t [&db](const string& path) {\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n\t\t db.add_database(Database(new GlassDatabase(path)));\n#else\n\t\t (void)path;\n#endif\n\t\t },\n\t\t [&db](const string& path) {\n#ifdef XAPIAN_HAS_HONEY_BACKEND\n\t\t db.add_database(Database(new HoneyDatabase(path)));\n#else\n\t\t (void)path;\n#endif\n\t\t },\n\t\t [&db](const string& prog, const string& args) {\n#ifdef XAPIAN_HAS_REMOTE_BACKEND\n\t\t db.add_database(Remote::open(prog, args));\n#else\n\t\t (void)prog;\n\t\t (void)args;\n#endif\n\t\t },\n\t\t [&db](const string& host, unsigned port) {\n#ifdef XAPIAN_HAS_REMOTE_BACKEND\n\t\t db.add_database(Remote::open(host, port));\n#else\n\t\t (void)host;\n\t\t (void)port;\n#endif\n\t\t },\n\t\t [&db]() {\n#ifdef XAPIAN_HAS_INMEMORY_BACKEND\n\t\t db.add_database(Database(string(), DB_BACKEND_INMEMORY));\n#endif\n\t\t });\n\n \/\/ Allowing a stub database with no databases listed allows things like\n \/\/ a \"search all databases\" feature to be implemented by generating a\n \/\/ stub database file without having to special case there not being any\n \/\/ databases yet.\n \/\/\n \/\/ 1.0.x threw DatabaseOpeningError here, but with a \"Bad line\" message\n \/\/ with the line number just past the end of the file, which was a bit odd.\n}\n\nstatic void\nopen_stub(WritableDatabase& db, const string& file, int flags)\n{\n read_stub_file(file,\n\t\t [&db, flags](const string& path) {\n\t\t db.add_database(WritableDatabase(path, flags));\n\t\t },\n\t\t [&db, &flags](const string& path) {\n\t\t flags |= DB_BACKEND_GLASS;\n\t\t db.add_database(WritableDatabase(path, flags));\n\t\t },\n\t\t [](const string&) {\n\t\t auto msg = \"Honey databases don't support writing\";\n\t\t throw Xapian::DatabaseOpeningError(msg);\n\t\t },\n\t\t [&db, flags](const string& prog, const string& args) {\n#ifdef XAPIAN_HAS_REMOTE_BACKEND\n\t\t db.add_database(Remote::open_writable(prog, args,\n\t\t\t\t\t\t\t 0, flags));\n#else\n\t\t (void)prog;\n\t\t (void)args;\n#endif\n\t\t },\n\t\t [&db, flags](const string& host, unsigned port) {\n#ifdef XAPIAN_HAS_REMOTE_BACKEND\n\t\t db.add_database(Remote::open_writable(host, port,\n\t\t\t\t\t\t\t 0, 10000, flags));\n#else\n\t\t (void)host;\n\t\t (void)port;\n#endif\n\t\t },\n\t\t [&db]() {\n\t\t db.add_database(WritableDatabase(string(),\n\t\t\t\t\t\t\tDB_BACKEND_INMEMORY));\n\t\t });\n\n if (db.internal->size() == 0) {\n\tthrow DatabaseOpeningError(file + \": No databases listed\");\n }\n}\n\nDatabase::Database(const string& path, int flags)\n : Database()\n{\n LOGCALL_CTOR(API, \"Database\", path|flags);\n\n int type = flags & DB_BACKEND_MASK_;\n switch (type) {\n\tcase DB_BACKEND_CHERT:\n\t throw FeatureUnavailableError(\"Chert backend no longer supported\");\n\tcase DB_BACKEND_GLASS:\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n\t internal = new GlassDatabase(path);\n\t return;\n#else\n\t throw FeatureUnavailableError(\"Glass backend disabled\");\n#endif\n\tcase DB_BACKEND_HONEY:\n#ifdef XAPIAN_HAS_HONEY_BACKEND\n\t internal = new HoneyDatabase(path);\n\t return;\n#else\n\t throw FeatureUnavailableError(\"Honey backend disabled\");\n#endif\n\tcase DB_BACKEND_STUB:\n\t open_stub(*this, path);\n\t return;\n\tcase DB_BACKEND_INMEMORY:\n#ifdef XAPIAN_HAS_INMEMORY_BACKEND\n\t internal = new InMemoryDatabase();\n\t return;\n#else\n\t throw FeatureUnavailableError(\"Inmemory backend disabled\");\n#endif\n }\n\n struct stat statbuf;\n if (stat(path.c_str(), &statbuf) == -1) {\n\tthrow DatabaseOpeningError(\"Couldn't stat '\" + path + \"'\", errno);\n }\n\n if (S_ISREG(statbuf.st_mode)) {\n\t\/\/ Could be a stub database file, or a single file glass database.\n\n\t\/\/ Initialise to avoid bogus warning from GCC 4.9.2 with -Os.\n\tint fd = -1;\n\tswitch (test_if_single_file_db(statbuf, path, &fd)) {\n\t case BACKEND_GLASS:\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n\t\t\/\/ Single file glass format.\n\t\tinternal = new GlassDatabase(fd);\n\t\treturn;\n#else\n\t\tthrow FeatureUnavailableError(\"Glass backend disabled\");\n#endif\n\t case BACKEND_HONEY:\n#ifdef XAPIAN_HAS_HONEY_BACKEND\n\t\t\/\/ Single file honey format.\n\t\tinternal = new HoneyDatabase(fd);\n\t\treturn;\n#else\n\t\tthrow FeatureUnavailableError(\"Honey backend disabled\");\n#endif\n\t}\n\n\topen_stub(*this, path);\n\treturn;\n }\n\n if (rare(!S_ISDIR(statbuf.st_mode))) {\n\tthrow DatabaseOpeningError(\"Not a regular file or directory: '\" + path + \"'\");\n }\n\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n if (file_exists(path + \"\/iamglass\")) {\n\tinternal = new GlassDatabase(path);\n\treturn;\n }\n#endif\n\n#ifdef XAPIAN_HAS_HONEY_BACKEND\n if (file_exists(path + \"\/iamhoney\")) {\n\tinternal = new HoneyDatabase(path);\n\treturn;\n }\n#endif\n\n \/\/ Check for \"stub directories\".\n string stub_file = path;\n stub_file += \"\/XAPIANDB\";\n if (usual(file_exists(stub_file))) {\n\topen_stub(*this, stub_file);\n\treturn;\n }\n\n#ifndef XAPIAN_HAS_GLASS_BACKEND\n if (file_exists(path + \"\/iamglass\")) {\n\tthrow FeatureUnavailableError(\"Glass backend disabled\");\n }\n#endif\n#ifndef XAPIAN_HAS_HONEY_BACKEND\n if (file_exists(path + \"\/iamhoney\")) {\n\tthrow FeatureUnavailableError(\"Honey backend disabled\");\n }\n#endif\n if (file_exists(path + \"\/iamchert\")) {\n\tthrow FeatureUnavailableError(\"Chert backend no longer supported\");\n }\n if (file_exists(path + \"\/iamflint\")) {\n\tthrow FeatureUnavailableError(\"Flint backend no longer supported\");\n }\n\n throw DatabaseOpeningError(\"Couldn't detect type of database\");\n}\n\nDatabase::Database(int fd, int flags)\n{\n LOGCALL_CTOR(API, \"Database\", fd|flags);\n\n if (rare(fd < 0))\n\tthrow InvalidArgumentError(\"fd < 0\");\n\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n int type = flags & DB_BACKEND_MASK_;\n switch (type) {\n\tcase 0:\n\tcase DB_BACKEND_GLASS:\n\t internal = new GlassDatabase(fd);\n }\n#else\n (void)flags;\n#endif\n\n (void)::close(fd);\n throw DatabaseOpeningError(\"Couldn't detect type of database\");\n}\n\n#if defined XAPIAN_HAS_GLASS_BACKEND\n#define HAVE_DISK_BACKEND\n#endif\n\nWritableDatabase::WritableDatabase(const std::string &path, int flags, int block_size)\n : Database()\n{\n LOGCALL_CTOR(API, \"WritableDatabase\", path|flags|block_size);\n \/\/ Avoid warning if all disk-based backends are disabled.\n (void)block_size;\n int type = flags & DB_BACKEND_MASK_;\n \/\/ Clear the backend bits, so we just pass on other flags to open_stub, etc.\n flags &= ~DB_BACKEND_MASK_;\n if (type == 0) {\n\tstruct stat statbuf;\n\tif (stat(path.c_str(), &statbuf) == -1) {\n\t \/\/ ENOENT probably just means that we need to create the directory.\n\t if (errno != ENOENT)\n\t\tthrow DatabaseOpeningError(\"Couldn't stat '\" + path + \"'\", errno);\n\t} else {\n\t \/\/ File or directory already exists.\n\n\t if (S_ISREG(statbuf.st_mode)) {\n\t\t\/\/ The path is a file, so assume it is a stub database file.\n\t\topen_stub(*this, path, flags);\n\t\treturn;\n\t }\n\n\t if (rare(!S_ISDIR(statbuf.st_mode))) {\n\t\tthrow DatabaseOpeningError(\"Not a regular file or directory: '\" + path + \"'\");\n\t }\n\n\t if (file_exists(path + \"\/iamglass\")) {\n\t\t\/\/ Existing glass DB.\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n\t\ttype = DB_BACKEND_GLASS;\n#else\n\t\tthrow FeatureUnavailableError(\"Glass backend disabled\");\n#endif\n\t } else if (file_exists(path + \"\/iamhoney\")) {\n\t\t\/\/ Existing honey DB.\n\t\tthrow InvalidOperationError(\"Honey backend doesn't support \"\n\t\t\t\t\t \"updating existing databases\");\n\t } else if (file_exists(path + \"\/iamchert\")) {\n\t\t\/\/ Existing chert DB.\n\t\tthrow FeatureUnavailableError(\"Chert backend no longer supported\");\n\t } else if (file_exists(path + \"\/iamflint\")) {\n\t\t\/\/ Existing flint DB.\n\t\tthrow FeatureUnavailableError(\"Flint backend no longer supported\");\n\t } else {\n\t\t\/\/ Check for \"stub directories\".\n\t\tstring stub_file = path;\n\t\tstub_file += \"\/XAPIANDB\";\n\t\tif (usual(file_exists(stub_file))) {\n\t\t open_stub(*this, stub_file, flags);\n\t\t return;\n\t\t}\n\t }\n\t}\n }\n\n switch (type) {\n\tcase DB_BACKEND_STUB:\n\t open_stub(*this, path, flags);\n\t return;\n\tcase 0:\n\t \/\/ Fall through to first enabled case, so order the remaining cases\n\t \/\/ by preference.\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n\tcase DB_BACKEND_GLASS:\n\t internal = new GlassWritableDatabase(path, flags, block_size);\n\t return;\n#endif\n\tcase DB_BACKEND_HONEY:\n\t throw InvalidArgumentError(\"Honey backend doesn't support \"\n\t\t\t\t \"updating existing databases\");\n\tcase DB_BACKEND_CHERT:\n\t throw FeatureUnavailableError(\"Chert backend no longer supported\");\n\tcase DB_BACKEND_INMEMORY:\n#ifdef XAPIAN_HAS_INMEMORY_BACKEND\n\t internal = new InMemoryDatabase();\n\t return;\n#else\n\t throw FeatureUnavailableError(\"Inmemory backend disabled\");\n#endif\n }\n#ifndef HAVE_DISK_BACKEND\n throw FeatureUnavailableError(\"No disk-based writable backend is enabled\");\n#endif\n}\n\n}\nxapian-core: Throw DatabaseNotFoundError if directory doesn't exist\/** @file dbfactory.cc\n * @brief Database factories for non-remote databases.\n *\/\n\/* Copyright 2002,2003,2004,2005,2006,2007,2008,2009,2011,2012,2013,2014,2015,2016,2017,2019 Olly Betts\n * Copyright 2008 Lemur Consulting Ltd\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n * USA\n *\/\n\n#include \"config.h\"\n\n#include \"xapian\/dbfactory.h\"\n\n#include \"xapian\/constants.h\"\n#include \"xapian\/database.h\"\n#include \"xapian\/error.h\"\n#include \"xapian\/version.h\" \/\/ For XAPIAN_HAS_XXX_BACKEND.\n\n#include \"xapian\/backends\/backends.h\"\n#include \"xapian\/backends\/databasehelpers.h\"\n#include \"xapian\/common\/debuglog.h\"\n#include \"xapian\/common\/filetests.h\"\n#include \"xapian\/common\/fileutils.h\"\n#include \"xapian\/common\/posixy_wrapper.h\"\n#include \"xapian\/common\/str.h\"\n\n#include \n#include \/\/ For atoi().\n\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n# include \"xapian\/backends\/glass\/glass_database.h\"\n#endif\n#include \"xapian\/backends\/glass\/glass_defs.h\"\n#ifdef XAPIAN_HAS_HONEY_BACKEND\n# include \"xapian\/backends\/honey\/honey_database.h\"\n#endif\n#include \"xapian\/backends\/honey\/honey_defs.h\"\n#ifdef XAPIAN_HAS_INMEMORY_BACKEND\n# include \"xapian\/backends\/inmemory\/inmemory_database.h\"\n#endif\n\/\/ Even if none of the above get included, we still need a definition of\n\/\/ Database::Internal.\n#include \"xapian\/backends\/databaseinternal.h\"\n\n#include \n#include \n\nusing namespace std;\n\nnamespace Xapian {\n\nstatic void\nopen_stub(Database& db, const string& file)\n{\n read_stub_file(file,\n\t\t [&db](const string& path) {\n\t\t db.add_database(Database(path));\n\t\t },\n\t\t [&db](const string& path) {\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n\t\t db.add_database(Database(new GlassDatabase(path)));\n#else\n\t\t (void)path;\n#endif\n\t\t },\n\t\t [&db](const string& path) {\n#ifdef XAPIAN_HAS_HONEY_BACKEND\n\t\t db.add_database(Database(new HoneyDatabase(path)));\n#else\n\t\t (void)path;\n#endif\n\t\t },\n\t\t [&db](const string& prog, const string& args) {\n#ifdef XAPIAN_HAS_REMOTE_BACKEND\n\t\t db.add_database(Remote::open(prog, args));\n#else\n\t\t (void)prog;\n\t\t (void)args;\n#endif\n\t\t },\n\t\t [&db](const string& host, unsigned port) {\n#ifdef XAPIAN_HAS_REMOTE_BACKEND\n\t\t db.add_database(Remote::open(host, port));\n#else\n\t\t (void)host;\n\t\t (void)port;\n#endif\n\t\t },\n\t\t [&db]() {\n#ifdef XAPIAN_HAS_INMEMORY_BACKEND\n\t\t db.add_database(Database(string(), DB_BACKEND_INMEMORY));\n#endif\n\t\t });\n\n \/\/ Allowing a stub database with no databases listed allows things like\n \/\/ a \"search all databases\" feature to be implemented by generating a\n \/\/ stub database file without having to special case there not being any\n \/\/ databases yet.\n \/\/\n \/\/ 1.0.x threw DatabaseOpeningError here, but with a \"Bad line\" message\n \/\/ with the line number just past the end of the file, which was a bit odd.\n}\n\nstatic void\nopen_stub(WritableDatabase& db, const string& file, int flags)\n{\n read_stub_file(file,\n\t\t [&db, flags](const string& path) {\n\t\t db.add_database(WritableDatabase(path, flags));\n\t\t },\n\t\t [&db, &flags](const string& path) {\n\t\t flags |= DB_BACKEND_GLASS;\n\t\t db.add_database(WritableDatabase(path, flags));\n\t\t },\n\t\t [](const string&) {\n\t\t auto msg = \"Honey databases don't support writing\";\n\t\t throw Xapian::DatabaseOpeningError(msg);\n\t\t },\n\t\t [&db, flags](const string& prog, const string& args) {\n#ifdef XAPIAN_HAS_REMOTE_BACKEND\n\t\t db.add_database(Remote::open_writable(prog, args,\n\t\t\t\t\t\t\t 0, flags));\n#else\n\t\t (void)prog;\n\t\t (void)args;\n#endif\n\t\t },\n\t\t [&db, flags](const string& host, unsigned port) {\n#ifdef XAPIAN_HAS_REMOTE_BACKEND\n\t\t db.add_database(Remote::open_writable(host, port,\n\t\t\t\t\t\t\t 0, 10000, flags));\n#else\n\t\t (void)host;\n\t\t (void)port;\n#endif\n\t\t },\n\t\t [&db]() {\n\t\t db.add_database(WritableDatabase(string(),\n\t\t\t\t\t\t\tDB_BACKEND_INMEMORY));\n\t\t });\n\n if (db.internal->size() == 0) {\n\tthrow DatabaseOpeningError(file + \": No databases listed\");\n }\n}\n\nDatabase::Database(const string& path, int flags)\n : Database()\n{\n LOGCALL_CTOR(API, \"Database\", path|flags);\n\n int type = flags & DB_BACKEND_MASK_;\n switch (type) {\n\tcase DB_BACKEND_CHERT:\n\t throw FeatureUnavailableError(\"Chert backend no longer supported\");\n\tcase DB_BACKEND_GLASS:\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n\t internal = new GlassDatabase(path);\n\t return;\n#else\n\t throw FeatureUnavailableError(\"Glass backend disabled\");\n#endif\n\tcase DB_BACKEND_HONEY:\n#ifdef XAPIAN_HAS_HONEY_BACKEND\n\t internal = new HoneyDatabase(path);\n\t return;\n#else\n\t throw FeatureUnavailableError(\"Honey backend disabled\");\n#endif\n\tcase DB_BACKEND_STUB:\n\t open_stub(*this, path);\n\t return;\n\tcase DB_BACKEND_INMEMORY:\n#ifdef XAPIAN_HAS_INMEMORY_BACKEND\n\t internal = new InMemoryDatabase();\n\t return;\n#else\n\t throw FeatureUnavailableError(\"Inmemory backend disabled\");\n#endif\n }\n\n struct stat statbuf;\n if (stat(path.c_str(), &statbuf) == -1) {\n\tif (errno == ENOENT) {\n\t throw DatabaseNotFoundError(\"Couldn't stat '\" + path + \"'\", errno);\n\t} else {\n\t throw DatabaseOpeningError(\"Couldn't stat '\" + path + \"'\", errno);\n\t}\n }\n\n if (S_ISREG(statbuf.st_mode)) {\n\t\/\/ Could be a stub database file, or a single file glass database.\n\n\t\/\/ Initialise to avoid bogus warning from GCC 4.9.2 with -Os.\n\tint fd = -1;\n\tswitch (test_if_single_file_db(statbuf, path, &fd)) {\n\t case BACKEND_GLASS:\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n\t\t\/\/ Single file glass format.\n\t\tinternal = new GlassDatabase(fd);\n\t\treturn;\n#else\n\t\tthrow FeatureUnavailableError(\"Glass backend disabled\");\n#endif\n\t case BACKEND_HONEY:\n#ifdef XAPIAN_HAS_HONEY_BACKEND\n\t\t\/\/ Single file honey format.\n\t\tinternal = new HoneyDatabase(fd);\n\t\treturn;\n#else\n\t\tthrow FeatureUnavailableError(\"Honey backend disabled\");\n#endif\n\t}\n\n\topen_stub(*this, path);\n\treturn;\n }\n\n if (rare(!S_ISDIR(statbuf.st_mode))) {\n\tthrow DatabaseOpeningError(\"Not a regular file or directory: '\" + path + \"'\");\n }\n\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n if (file_exists(path + \"\/iamglass\")) {\n\tinternal = new GlassDatabase(path);\n\treturn;\n }\n#endif\n\n#ifdef XAPIAN_HAS_HONEY_BACKEND\n if (file_exists(path + \"\/iamhoney\")) {\n\tinternal = new HoneyDatabase(path);\n\treturn;\n }\n#endif\n\n \/\/ Check for \"stub directories\".\n string stub_file = path;\n stub_file += \"\/XAPIANDB\";\n if (usual(file_exists(stub_file))) {\n\topen_stub(*this, stub_file);\n\treturn;\n }\n\n#ifndef XAPIAN_HAS_GLASS_BACKEND\n if (file_exists(path + \"\/iamglass\")) {\n\tthrow FeatureUnavailableError(\"Glass backend disabled\");\n }\n#endif\n#ifndef XAPIAN_HAS_HONEY_BACKEND\n if (file_exists(path + \"\/iamhoney\")) {\n\tthrow FeatureUnavailableError(\"Honey backend disabled\");\n }\n#endif\n if (file_exists(path + \"\/iamchert\")) {\n\tthrow FeatureUnavailableError(\"Chert backend no longer supported\");\n }\n if (file_exists(path + \"\/iamflint\")) {\n\tthrow FeatureUnavailableError(\"Flint backend no longer supported\");\n }\n\n throw DatabaseNotFoundError(\"Couldn't detect type of database\");\n}\n\nDatabase::Database(int fd, int flags)\n{\n LOGCALL_CTOR(API, \"Database\", fd|flags);\n\n if (rare(fd < 0))\n\tthrow InvalidArgumentError(\"fd < 0\");\n\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n int type = flags & DB_BACKEND_MASK_;\n switch (type) {\n\tcase 0:\n\tcase DB_BACKEND_GLASS:\n\t internal = new GlassDatabase(fd);\n }\n#else\n (void)flags;\n#endif\n\n (void)::close(fd);\n throw DatabaseOpeningError(\"Couldn't detect type of database\");\n}\n\n#if defined XAPIAN_HAS_GLASS_BACKEND\n#define HAVE_DISK_BACKEND\n#endif\n\nWritableDatabase::WritableDatabase(const std::string &path, int flags, int block_size)\n : Database()\n{\n LOGCALL_CTOR(API, \"WritableDatabase\", path|flags|block_size);\n \/\/ Avoid warning if all disk-based backends are disabled.\n (void)block_size;\n int type = flags & DB_BACKEND_MASK_;\n \/\/ Clear the backend bits, so we just pass on other flags to open_stub, etc.\n flags &= ~DB_BACKEND_MASK_;\n if (type == 0) {\n\tstruct stat statbuf;\n\tif (stat(path.c_str(), &statbuf) == -1) {\n\t \/\/ ENOENT probably just means that we need to create the directory.\n\t if (errno != ENOENT)\n\t\tthrow DatabaseOpeningError(\"Couldn't stat '\" + path + \"'\", errno);\n\t} else {\n\t \/\/ File or directory already exists.\n\n\t if (S_ISREG(statbuf.st_mode)) {\n\t\t\/\/ The path is a file, so assume it is a stub database file.\n\t\topen_stub(*this, path, flags);\n\t\treturn;\n\t }\n\n\t if (rare(!S_ISDIR(statbuf.st_mode))) {\n\t\tthrow DatabaseOpeningError(\"Not a regular file or directory: '\" + path + \"'\");\n\t }\n\n\t if (file_exists(path + \"\/iamglass\")) {\n\t\t\/\/ Existing glass DB.\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n\t\ttype = DB_BACKEND_GLASS;\n#else\n\t\tthrow FeatureUnavailableError(\"Glass backend disabled\");\n#endif\n\t } else if (file_exists(path + \"\/iamhoney\")) {\n\t\t\/\/ Existing honey DB.\n\t\tthrow InvalidOperationError(\"Honey backend doesn't support \"\n\t\t\t\t\t \"updating existing databases\");\n\t } else if (file_exists(path + \"\/iamchert\")) {\n\t\t\/\/ Existing chert DB.\n\t\tthrow FeatureUnavailableError(\"Chert backend no longer supported\");\n\t } else if (file_exists(path + \"\/iamflint\")) {\n\t\t\/\/ Existing flint DB.\n\t\tthrow FeatureUnavailableError(\"Flint backend no longer supported\");\n\t } else {\n\t\t\/\/ Check for \"stub directories\".\n\t\tstring stub_file = path;\n\t\tstub_file += \"\/XAPIANDB\";\n\t\tif (usual(file_exists(stub_file))) {\n\t\t open_stub(*this, stub_file, flags);\n\t\t return;\n\t\t}\n\t }\n\t}\n }\n\n switch (type) {\n\tcase DB_BACKEND_STUB:\n\t open_stub(*this, path, flags);\n\t return;\n\tcase 0:\n\t \/\/ Fall through to first enabled case, so order the remaining cases\n\t \/\/ by preference.\n#ifdef XAPIAN_HAS_GLASS_BACKEND\n\tcase DB_BACKEND_GLASS:\n\t internal = new GlassWritableDatabase(path, flags, block_size);\n\t return;\n#endif\n\tcase DB_BACKEND_HONEY:\n\t throw InvalidArgumentError(\"Honey backend doesn't support \"\n\t\t\t\t \"updating existing databases\");\n\tcase DB_BACKEND_CHERT:\n\t throw FeatureUnavailableError(\"Chert backend no longer supported\");\n\tcase DB_BACKEND_INMEMORY:\n#ifdef XAPIAN_HAS_INMEMORY_BACKEND\n\t internal = new InMemoryDatabase();\n\t return;\n#else\n\t throw FeatureUnavailableError(\"Inmemory backend disabled\");\n#endif\n }\n#ifndef HAVE_DISK_BACKEND\n throw FeatureUnavailableError(\"No disk-based writable backend is enabled\");\n#endif\n}\n\n}\n<|endoftext|>"} {"text":"+ [wrd] add performance_test for prototyping of memory component.<|endoftext|>"} {"text":"proto<|endoftext|>"} {"text":"#pragma once\n\n#ifndef RAZ_LOGGER_HPP\n#define RAZ_LOGGER_HPP\n\n#include \n#include \n\nnamespace Raz {\n\nenum class LoggingLevel {\n NONE = 0, \/\/\/< Ignore all logs.\n ERROR, \/\/\/< Output logs of error category.\n WARNING, \/\/\/< Output logs of warning category & below.\n INFO, \/\/\/< Output logs of info category & below.\n DEBUG, \/\/\/< Output logs of debug category & below.\n ALL \/\/\/< Output all logs.\n};\n\nclass Logger {\npublic:\n Logger() = delete;\n\n static void setLoggingLevel(LoggingLevel level) { m_logLevel = level; }\n static void setLoggingFunction(std::function logFunc) { m_logFunc = std::move(logFunc); }\n static void resetLoggingFunction() { m_logFunc = nullptr; }\n\n \/\/\/ Prints an error message.\n \/\/\/ \\note Requires a logging level of \"error\" or above.\n \/\/\/ \\param message Message to be printed.\n static void error(const std::string& message);\n \/\/\/ Prints a warning message.\n \/\/\/ \\note Requires a logging level of \"warning\" or above.\n \/\/\/ \\param message Message to be printed.\n static void warn(const std::string& message);\n \/\/\/ Prints an information message.\n \/\/\/ \\note Requires a logging level of \"info\" or above.\n \/\/\/ \\param message Message to be printed.\n static void info(const std::string& message);\n#if defined(RAZ_CONFIG_DEBUG) || defined(RAZ_FORCE_DEBUG_LOG)\n \/\/\/ Prints a debug message.\n \/\/\/ \\note Does nothing in a configuration other than Debug, unless RAZ_FORCE_DEBUG_LOG is defined.\n \/\/\/ \\note Requires a logging level of \"debug\" or above.\n \/\/\/ \\param message Message to be printed.\n static void debug(const std::string& message);\n#else\n static void debug(const std::string&) {}\n#endif\n\n ~Logger() = delete;\n\nprivate:\n static inline LoggingLevel m_logLevel = LoggingLevel::ERROR;\n static inline std::function m_logFunc {};\n};\n\n} \/\/ namespace Raz\n\n#endif \/\/ RAZ_LOGGER_HPP\n[Utils\/Logger] Added a const char* debug() version#pragma once\n\n#ifndef RAZ_LOGGER_HPP\n#define RAZ_LOGGER_HPP\n\n#include \n#include \n\nnamespace Raz {\n\nenum class LoggingLevel {\n NONE = 0, \/\/\/< Ignore all logs.\n ERROR, \/\/\/< Output logs of error category.\n WARNING, \/\/\/< Output logs of warning category & below.\n INFO, \/\/\/< Output logs of info category & below.\n DEBUG, \/\/\/< Output logs of debug category & below.\n ALL \/\/\/< Output all logs.\n};\n\nclass Logger {\npublic:\n Logger() = delete;\n\n static void setLoggingLevel(LoggingLevel level) { m_logLevel = level; }\n static void setLoggingFunction(std::function logFunc) { m_logFunc = std::move(logFunc); }\n static void resetLoggingFunction() { m_logFunc = nullptr; }\n\n \/\/\/ Prints an error message.\n \/\/\/ \\note Requires a logging level of \"error\" or above.\n \/\/\/ \\param message Message to be printed.\n static void error(const std::string& message);\n \/\/\/ Prints a warning message.\n \/\/\/ \\note Requires a logging level of \"warning\" or above.\n \/\/\/ \\param message Message to be printed.\n static void warn(const std::string& message);\n \/\/\/ Prints an information message.\n \/\/\/ \\note Requires a logging level of \"info\" or above.\n \/\/\/ \\param message Message to be printed.\n static void info(const std::string& message);\n#if !defined(NDEBUG) || defined(RAZ_FORCE_DEBUG_LOG)\n \/\/\/ Prints a debug message.\n \/\/\/ \\note Does nothing in a configuration other than Debug, unless RAZ_FORCE_DEBUG_LOG is defined.\n \/\/\/ \\note Requires a logging level of \"debug\" or above.\n \/\/\/ \\param message Message to be printed.\n static void debug(const std::string& message);\n#else\n static void debug(const char*) {}\n static void debug(const std::string&) {}\n#endif\n\n ~Logger() = delete;\n\nprivate:\n static inline LoggingLevel m_logLevel = LoggingLevel::ERROR;\n static inline std::function m_logFunc {};\n};\n\n} \/\/ namespace Raz\n\n#endif \/\/ RAZ_LOGGER_HPP\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright © 2017 Arm Ltd. All rights reserved.\n\/\/ SPDX-License-Identifier: MIT\n\/\/\n#pragma once\n\n#include \n#include \n\n#include \n#include \n#include \n\nnamespace armnn\n{\n\nconstexpr char const* GetStatusAsCString(Status status)\n{\n switch (status)\n {\n case armnn::Status::Success: return \"Status::Success\";\n case armnn::Status::Failure: return \"Status::Failure\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetActivationFunctionAsCString(ActivationFunction activation)\n{\n switch (activation)\n {\n case ActivationFunction::Sigmoid: return \"Sigmoid\";\n case ActivationFunction::TanH: return \"TanH\";\n case ActivationFunction::Linear: return \"Linear\";\n case ActivationFunction::ReLu: return \"ReLu\";\n case ActivationFunction::BoundedReLu: return \"BoundedReLu\";\n case ActivationFunction::SoftReLu: return \"SoftReLu\";\n case ActivationFunction::LeakyReLu: return \"LeakyReLu\";\n case ActivationFunction::Abs: return \"Abs\";\n case ActivationFunction::Sqrt: return \"Sqrt\";\n case ActivationFunction::Square: return \"Square\";\n case ActivationFunction::Elu: return \"Elu\";\n case ActivationFunction::HardSwish: return \"HardSwish\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetArgMinMaxFunctionAsCString(ArgMinMaxFunction function)\n{\n switch (function)\n {\n case ArgMinMaxFunction::Max: return \"Max\";\n case ArgMinMaxFunction::Min: return \"Min\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetComparisonOperationAsCString(ComparisonOperation operation)\n{\n switch (operation)\n {\n case ComparisonOperation::Equal: return \"Equal\";\n case ComparisonOperation::Greater: return \"Greater\";\n case ComparisonOperation::GreaterOrEqual: return \"GreaterOrEqual\";\n case ComparisonOperation::Less: return \"Less\";\n case ComparisonOperation::LessOrEqual: return \"LessOrEqual\";\n case ComparisonOperation::NotEqual: return \"NotEqual\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetUnaryOperationAsCString(UnaryOperation operation)\n{\n switch (operation)\n {\n case UnaryOperation::Abs: return \"Abs\";\n case UnaryOperation::Exp: return \"Exp\";\n case UnaryOperation::Sqrt: return \"Sqrt\";\n case UnaryOperation::Rsqrt: return \"Rsqrt\";\n case UnaryOperation::Neg: return \"Neg\";\n case UnaryOperation::LogicalNot: return \"LogicalNot\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetLogicalBinaryOperationAsCString(LogicalBinaryOperation operation)\n{\n switch (operation)\n {\n case LogicalBinaryOperation::LogicalAnd: return \"LogicalAnd\";\n case LogicalBinaryOperation::LogicalOr: return \"LogicalOr\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetPoolingAlgorithmAsCString(PoolingAlgorithm pooling)\n{\n switch (pooling)\n {\n case PoolingAlgorithm::Average: return \"Average\";\n case PoolingAlgorithm::Max: return \"Max\";\n case PoolingAlgorithm::L2: return \"L2\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetOutputShapeRoundingAsCString(OutputShapeRounding rounding)\n{\n switch (rounding)\n {\n case OutputShapeRounding::Ceiling: return \"Ceiling\";\n case OutputShapeRounding::Floor: return \"Floor\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetPaddingMethodAsCString(PaddingMethod method)\n{\n switch (method)\n {\n case PaddingMethod::Exclude: return \"Exclude\";\n case PaddingMethod::IgnoreValue: return \"IgnoreValue\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetReduceOperationAsCString(ReduceOperation reduce_operation)\n{\n switch (reduce_operation)\n {\n case ReduceOperation::Sum: return \"Sum\";\n case ReduceOperation::Max: return \"Max\";\n case ReduceOperation::Mean: return \"Mean\";\n case ReduceOperation::Min: return \"Min\";\n default: return \"Unknown\";\n }\n}\nconstexpr unsigned int GetDataTypeSize(DataType dataType)\n{\n switch (dataType)\n {\n case DataType::BFloat16:\n case DataType::Float16: return 2U;\n case DataType::Float32:\n case DataType::Signed32: return 4U;\n case DataType::Signed64: return 8U;\n case DataType::QAsymmU8: return 1U;\n case DataType::QAsymmS8: return 1U;\n case DataType::QSymmS8: return 1U;\n ARMNN_NO_DEPRECATE_WARN_BEGIN\n case DataType::QuantizedSymm8PerAxis: return 1U;\n ARMNN_NO_DEPRECATE_WARN_END\n case DataType::QSymmS16: return 2U;\n case DataType::Boolean: return 1U;\n default: return 0U;\n }\n}\n\ntemplate \nconstexpr bool StrEqual(const char* strA, const char (&strB)[N])\n{\n bool isEqual = true;\n for (unsigned i = 0; isEqual && (i < N); ++i)\n {\n isEqual = (strA[i] == strB[i]);\n }\n return isEqual;\n}\n\n\/\/\/ Deprecated function that will be removed together with\n\/\/\/ the Compute enum\nconstexpr armnn::Compute ParseComputeDevice(const char* str)\n{\n if (armnn::StrEqual(str, \"CpuAcc\"))\n {\n return armnn::Compute::CpuAcc;\n }\n else if (armnn::StrEqual(str, \"CpuRef\"))\n {\n return armnn::Compute::CpuRef;\n }\n else if (armnn::StrEqual(str, \"GpuAcc\"))\n {\n return armnn::Compute::GpuAcc;\n }\n else\n {\n return armnn::Compute::Undefined;\n }\n}\n\nconstexpr const char* GetDataTypeName(DataType dataType)\n{\n switch (dataType)\n {\n case DataType::Float16: return \"Float16\";\n case DataType::Float32: return \"Float32\";\n case DataType::Signed64: return \"Signed64\";\n case DataType::QAsymmU8: return \"QAsymmU8\";\n case DataType::QAsymmS8: return \"QAsymmS8\";\n case DataType::QSymmS8: return \"QSymmS8\";\n ARMNN_NO_DEPRECATE_WARN_BEGIN\n case DataType::QuantizedSymm8PerAxis: return \"QSymm8PerAxis\";\n ARMNN_NO_DEPRECATE_WARN_END\n case DataType::QSymmS16: return \"QSymm16\";\n case DataType::Signed32: return \"Signed32\";\n case DataType::Boolean: return \"Boolean\";\n case DataType::BFloat16: return \"BFloat16\";\n\n default:\n return \"Unknown\";\n }\n}\n\nconstexpr const char* GetDataLayoutName(DataLayout dataLayout)\n{\n switch (dataLayout)\n {\n case DataLayout::NCHW: return \"NCHW\";\n case DataLayout::NHWC: return \"NHWC\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr const char* GetNormalizationAlgorithmChannelAsCString(NormalizationAlgorithmChannel channel)\n{\n switch (channel)\n {\n case NormalizationAlgorithmChannel::Across: return \"Across\";\n case NormalizationAlgorithmChannel::Within: return \"Within\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr const char* GetNormalizationAlgorithmMethodAsCString(NormalizationAlgorithmMethod method)\n{\n switch (method)\n {\n case NormalizationAlgorithmMethod::LocalBrightness: return \"LocalBrightness\";\n case NormalizationAlgorithmMethod::LocalContrast: return \"LocalContrast\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr const char* GetResizeMethodAsCString(ResizeMethod method)\n{\n switch (method)\n {\n case ResizeMethod::Bilinear: return \"Bilinear\";\n case ResizeMethod::NearestNeighbor: return \"NearestNeighbour\";\n default: return \"Unknown\";\n }\n}\n\ntemplate\nstruct IsHalfType\n : std::integral_constant::value && sizeof(T) == 2>\n{};\n\ntemplate\nconstexpr bool IsQuantizedType()\n{\n return std::is_integral::value;\n}\n\nconstexpr bool IsQuantized8BitType(DataType dataType)\n{\n ARMNN_NO_DEPRECATE_WARN_BEGIN\n return dataType == DataType::QAsymmU8 ||\n dataType == DataType::QAsymmS8 ||\n dataType == DataType::QSymmS8 ||\n dataType == DataType::QuantizedSymm8PerAxis;\n ARMNN_NO_DEPRECATE_WARN_END\n}\n\nconstexpr bool IsQuantizedType(DataType dataType)\n{\n return dataType == DataType::QSymmS16 || IsQuantized8BitType(dataType);\n}\n\ninline std::ostream& operator<<(std::ostream& os, Status stat)\n{\n os << GetStatusAsCString(stat);\n return os;\n}\n\n\ninline std::ostream & operator<<(std::ostream & os, const armnn::TensorShape & shape)\n{\n os << \"[\";\n for (uint32_t i=0; i\nQuantizedType Quantize(float value, float scale, int32_t offset);\n\n\/\/\/ Dequantize an 8-bit data type into a floating point data type.\n\/\/\/ @param value - The value to dequantize.\n\/\/\/ @param scale - The scale (must be non-zero).\n\/\/\/ @param offset - The offset.\n\/\/\/ @return - The dequantized value calculated as (value-offset)*scale.\n\/\/\/\ntemplate \nfloat Dequantize(QuantizedType value, float scale, int32_t offset);\n\ninline void VerifyTensorInfoDataType(const armnn::TensorInfo & info, armnn::DataType dataType)\n{\n if (info.GetDataType() != dataType)\n {\n std::stringstream ss;\n ss << \"Unexpected datatype:\" << armnn::GetDataTypeName(info.GetDataType())\n << \" for tensor:\" << info.GetShape()\n << \". The type expected to be: \" << armnn::GetDataTypeName(dataType);\n throw armnn::Exception(ss.str());\n }\n}\n\n} \/\/namespace armnn\nPrint Log and Sin Elementwise on dot graph\/\/\n\/\/ Copyright © 2017 Arm Ltd. All rights reserved.\n\/\/ SPDX-License-Identifier: MIT\n\/\/\n#pragma once\n\n#include \n#include \n\n#include \n#include \n#include \n\nnamespace armnn\n{\n\nconstexpr char const* GetStatusAsCString(Status status)\n{\n switch (status)\n {\n case armnn::Status::Success: return \"Status::Success\";\n case armnn::Status::Failure: return \"Status::Failure\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetActivationFunctionAsCString(ActivationFunction activation)\n{\n switch (activation)\n {\n case ActivationFunction::Sigmoid: return \"Sigmoid\";\n case ActivationFunction::TanH: return \"TanH\";\n case ActivationFunction::Linear: return \"Linear\";\n case ActivationFunction::ReLu: return \"ReLu\";\n case ActivationFunction::BoundedReLu: return \"BoundedReLu\";\n case ActivationFunction::SoftReLu: return \"SoftReLu\";\n case ActivationFunction::LeakyReLu: return \"LeakyReLu\";\n case ActivationFunction::Abs: return \"Abs\";\n case ActivationFunction::Sqrt: return \"Sqrt\";\n case ActivationFunction::Square: return \"Square\";\n case ActivationFunction::Elu: return \"Elu\";\n case ActivationFunction::HardSwish: return \"HardSwish\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetArgMinMaxFunctionAsCString(ArgMinMaxFunction function)\n{\n switch (function)\n {\n case ArgMinMaxFunction::Max: return \"Max\";\n case ArgMinMaxFunction::Min: return \"Min\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetComparisonOperationAsCString(ComparisonOperation operation)\n{\n switch (operation)\n {\n case ComparisonOperation::Equal: return \"Equal\";\n case ComparisonOperation::Greater: return \"Greater\";\n case ComparisonOperation::GreaterOrEqual: return \"GreaterOrEqual\";\n case ComparisonOperation::Less: return \"Less\";\n case ComparisonOperation::LessOrEqual: return \"LessOrEqual\";\n case ComparisonOperation::NotEqual: return \"NotEqual\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetUnaryOperationAsCString(UnaryOperation operation)\n{\n switch (operation)\n {\n case UnaryOperation::Abs: return \"Abs\";\n case UnaryOperation::Exp: return \"Exp\";\n case UnaryOperation::Sqrt: return \"Sqrt\";\n case UnaryOperation::Rsqrt: return \"Rsqrt\";\n case UnaryOperation::Neg: return \"Neg\";\n case UnaryOperation::Log: return \"Log\";\n case UnaryOperation::LogicalNot: return \"LogicalNot\";\n case UnaryOperation::Sin: return \"Sin\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetLogicalBinaryOperationAsCString(LogicalBinaryOperation operation)\n{\n switch (operation)\n {\n case LogicalBinaryOperation::LogicalAnd: return \"LogicalAnd\";\n case LogicalBinaryOperation::LogicalOr: return \"LogicalOr\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetPoolingAlgorithmAsCString(PoolingAlgorithm pooling)\n{\n switch (pooling)\n {\n case PoolingAlgorithm::Average: return \"Average\";\n case PoolingAlgorithm::Max: return \"Max\";\n case PoolingAlgorithm::L2: return \"L2\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetOutputShapeRoundingAsCString(OutputShapeRounding rounding)\n{\n switch (rounding)\n {\n case OutputShapeRounding::Ceiling: return \"Ceiling\";\n case OutputShapeRounding::Floor: return \"Floor\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetPaddingMethodAsCString(PaddingMethod method)\n{\n switch (method)\n {\n case PaddingMethod::Exclude: return \"Exclude\";\n case PaddingMethod::IgnoreValue: return \"IgnoreValue\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr char const* GetReduceOperationAsCString(ReduceOperation reduce_operation)\n{\n switch (reduce_operation)\n {\n case ReduceOperation::Sum: return \"Sum\";\n case ReduceOperation::Max: return \"Max\";\n case ReduceOperation::Mean: return \"Mean\";\n case ReduceOperation::Min: return \"Min\";\n default: return \"Unknown\";\n }\n}\nconstexpr unsigned int GetDataTypeSize(DataType dataType)\n{\n switch (dataType)\n {\n case DataType::BFloat16:\n case DataType::Float16: return 2U;\n case DataType::Float32:\n case DataType::Signed32: return 4U;\n case DataType::Signed64: return 8U;\n case DataType::QAsymmU8: return 1U;\n case DataType::QAsymmS8: return 1U;\n case DataType::QSymmS8: return 1U;\n ARMNN_NO_DEPRECATE_WARN_BEGIN\n case DataType::QuantizedSymm8PerAxis: return 1U;\n ARMNN_NO_DEPRECATE_WARN_END\n case DataType::QSymmS16: return 2U;\n case DataType::Boolean: return 1U;\n default: return 0U;\n }\n}\n\ntemplate \nconstexpr bool StrEqual(const char* strA, const char (&strB)[N])\n{\n bool isEqual = true;\n for (unsigned i = 0; isEqual && (i < N); ++i)\n {\n isEqual = (strA[i] == strB[i]);\n }\n return isEqual;\n}\n\n\/\/\/ Deprecated function that will be removed together with\n\/\/\/ the Compute enum\nconstexpr armnn::Compute ParseComputeDevice(const char* str)\n{\n if (armnn::StrEqual(str, \"CpuAcc\"))\n {\n return armnn::Compute::CpuAcc;\n }\n else if (armnn::StrEqual(str, \"CpuRef\"))\n {\n return armnn::Compute::CpuRef;\n }\n else if (armnn::StrEqual(str, \"GpuAcc\"))\n {\n return armnn::Compute::GpuAcc;\n }\n else\n {\n return armnn::Compute::Undefined;\n }\n}\n\nconstexpr const char* GetDataTypeName(DataType dataType)\n{\n switch (dataType)\n {\n case DataType::Float16: return \"Float16\";\n case DataType::Float32: return \"Float32\";\n case DataType::Signed64: return \"Signed64\";\n case DataType::QAsymmU8: return \"QAsymmU8\";\n case DataType::QAsymmS8: return \"QAsymmS8\";\n case DataType::QSymmS8: return \"QSymmS8\";\n ARMNN_NO_DEPRECATE_WARN_BEGIN\n case DataType::QuantizedSymm8PerAxis: return \"QSymm8PerAxis\";\n ARMNN_NO_DEPRECATE_WARN_END\n case DataType::QSymmS16: return \"QSymm16\";\n case DataType::Signed32: return \"Signed32\";\n case DataType::Boolean: return \"Boolean\";\n case DataType::BFloat16: return \"BFloat16\";\n\n default:\n return \"Unknown\";\n }\n}\n\nconstexpr const char* GetDataLayoutName(DataLayout dataLayout)\n{\n switch (dataLayout)\n {\n case DataLayout::NCHW: return \"NCHW\";\n case DataLayout::NHWC: return \"NHWC\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr const char* GetNormalizationAlgorithmChannelAsCString(NormalizationAlgorithmChannel channel)\n{\n switch (channel)\n {\n case NormalizationAlgorithmChannel::Across: return \"Across\";\n case NormalizationAlgorithmChannel::Within: return \"Within\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr const char* GetNormalizationAlgorithmMethodAsCString(NormalizationAlgorithmMethod method)\n{\n switch (method)\n {\n case NormalizationAlgorithmMethod::LocalBrightness: return \"LocalBrightness\";\n case NormalizationAlgorithmMethod::LocalContrast: return \"LocalContrast\";\n default: return \"Unknown\";\n }\n}\n\nconstexpr const char* GetResizeMethodAsCString(ResizeMethod method)\n{\n switch (method)\n {\n case ResizeMethod::Bilinear: return \"Bilinear\";\n case ResizeMethod::NearestNeighbor: return \"NearestNeighbour\";\n default: return \"Unknown\";\n }\n}\n\ntemplate\nstruct IsHalfType\n : std::integral_constant::value && sizeof(T) == 2>\n{};\n\ntemplate\nconstexpr bool IsQuantizedType()\n{\n return std::is_integral::value;\n}\n\nconstexpr bool IsQuantized8BitType(DataType dataType)\n{\n ARMNN_NO_DEPRECATE_WARN_BEGIN\n return dataType == DataType::QAsymmU8 ||\n dataType == DataType::QAsymmS8 ||\n dataType == DataType::QSymmS8 ||\n dataType == DataType::QuantizedSymm8PerAxis;\n ARMNN_NO_DEPRECATE_WARN_END\n}\n\nconstexpr bool IsQuantizedType(DataType dataType)\n{\n return dataType == DataType::QSymmS16 || IsQuantized8BitType(dataType);\n}\n\ninline std::ostream& operator<<(std::ostream& os, Status stat)\n{\n os << GetStatusAsCString(stat);\n return os;\n}\n\n\ninline std::ostream & operator<<(std::ostream & os, const armnn::TensorShape & shape)\n{\n os << \"[\";\n for (uint32_t i=0; i\nQuantizedType Quantize(float value, float scale, int32_t offset);\n\n\/\/\/ Dequantize an 8-bit data type into a floating point data type.\n\/\/\/ @param value - The value to dequantize.\n\/\/\/ @param scale - The scale (must be non-zero).\n\/\/\/ @param offset - The offset.\n\/\/\/ @return - The dequantized value calculated as (value-offset)*scale.\n\/\/\/\ntemplate \nfloat Dequantize(QuantizedType value, float scale, int32_t offset);\n\ninline void VerifyTensorInfoDataType(const armnn::TensorInfo & info, armnn::DataType dataType)\n{\n if (info.GetDataType() != dataType)\n {\n std::stringstream ss;\n ss << \"Unexpected datatype:\" << armnn::GetDataTypeName(info.GetDataType())\n << \" for tensor:\" << info.GetShape()\n << \". The type expected to be: \" << armnn::GetDataTypeName(dataType);\n throw armnn::Exception(ss.str());\n }\n}\n\n} \/\/namespace armnn\n<|endoftext|>"} {"text":"\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Julian Ganz\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n#ifndef CMOH_STRING_VIEW_HPP__\n#define CMOH_STRING_VIEW_HPP__\n\n\n\/\/ We try to detect whether a standard `string_view` is available, but only for\n\/\/ post-C++14 (we don't expect a C++14 STL to ship it). We don't consider the\n\/\/ `experimental\/string_view` header, since at least one implementation (the one\n\/\/ shipped with GCC), lacks `constexpr` in critical places.\n#if __cplusplus > 201402L\n# if __has_include()\n# define has_string_view 1\n# endif\n#endif\n\n\n\/\/ local includes\n#include \n\n\n\/\/ use one of the `string_view` implementations\n#ifdef has_string_view\n#include \nnamespace cmoh {\n template <\n typename CharT,\n typename Traits = char_traits\n >\n using basic_string_view = std::basic_string_view;\n}\n#else\n\n\n\/\/ std includes\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace cmoh {\n\n\n\/**\n * Predefinition of the C++17 std::basic_string_view type\n *\n * This template provides an optional type which is modeled after the\n * std::basic_string_view which is part of the C++17 standard proposal. Note\n * that only a subset of the interface is provided. Also note that the Traits\n * defaults to a custom `char_traits`, which has some additional compile\n * capabilities but is somewhat slow at run time.\n *\n * For documentation, refer to the C++17 proposal or your favorite STL\n * documentation site.\n *\/\ntemplate <\n typename CharT,\n typename Traits = char_traits\n>\nclass basic_string_view {\npublic:\n typedef Traits traits_type;\n\n \/\/ value types\n typedef CharT value_type;\n typedef CharT* pointer;\n typedef CharT const* const_pointer;\n typedef CharT& reference;\n typedef CharT const& const_reference;\n\n \/\/ TODO: iterator types\n\n typedef std::size_t size_type;\n typedef std::ptrdiff_t difference_type;\n\n\n constexpr basic_string_view() noexcept : _data(nullptr), _count(0) {}\n constexpr basic_string_view(const basic_string_view& other) noexcept =\n default;\n constexpr basic_string_view(const CharT* data, size_type count) noexcept :\n _data(data), _count(count) {}\n constexpr basic_string_view(const CharT* data) :\n _data(data), _count(traits_type::length(data)) {}\n\n basic_string_view& operator=( const basic_string_view& view ) = default;\n\n\n \/\/ TODO: iterators\n\n\n constexpr const_reference operator[](size_type pos) const {\n return _data[pos];\n }\n\n constexpr const_reference at(size_type pos) const {\n if (pos >= size())\n throw std::out_of_range(\"Access out-of-bounds element.\");\n return _data[pos];\n }\n\n constexpr const_reference front() const {\n return _data[0];\n }\n\n constexpr const_reference back() const {\n return _data[size() - 1];\n }\n\n constexpr const_pointer data() const noexcept {\n return _data;\n }\n\n\n constexpr size_type size() const noexcept {\n return _count;\n }\n\n constexpr size_type length() const noexcept {\n return size();\n }\n\n constexpr size_type max_size() const noexcept {\n return std::numeric_limits::max();\n }\n\n constexpr bool empty() const noexcept {\n return size() == 0;\n }\n\n\n constexpr void remove_prefix(size_type n) {\n _data+=n;\n _count-=n;\n }\n\n constexpr void remove_suffix(size_type n) {\n _count-=n;\n }\n\n constexpr void swap(basic_string_view& v) {\n const_pointer* data = v._data;\n size_type count = v._count;\n\n v._data = _data;\n v._count = _count;\n\n _data = data;\n _count = count;\n }\n\n\n size_type copy(CharT* dest, size_type count, size_type pos = 0) const {\n if (pos >= size())\n throw std::out_of_range(\"Access out-of-bounds element.\");\n count = std::min(count, size() - pos);\n traits_type::copy(\n dest,\n &_data[pos],\n count*sizeof(value_type)\/sizeof(char)\n );\n return count;\n }\n\n constexpr basic_string_view\n substr(size_type pos = 0, size_type count = npos) const {\n if (pos >= size())\n throw std::out_of_range(\"Access out-of-bounds element.\");\n return basic_string_view(_data + pos, std::min(count, size() - pos));\n }\n\n constexpr int compare(basic_string_view v) const noexcept {\n auto retval = traits_type::compare(\n data(),\n v.data(),\n std::min(size(), v.size())\n );\n if (retval != 0)\n return retval;\n if (size() == v.size())\n return 0;\n return size() < v.size() ? -1 : 1;\n }\n\n constexpr int\n compare(size_type pos1, size_type count1, basic_string_view v) const {\n return substr(pos1, count1).compare(v);\n }\n\n constexpr int\n compare(\n size_type pos1,\n size_type count1,\n basic_string_view v,\n size_type pos2,\n size_type count2\n ) const {\n return substr(pos1, count1).compare(v.substr(pos2, count2));\n }\n\n constexpr int compare(const_pointer s) const {\n return compare(basic_string_view(s));\n }\n\n constexpr int\n compare(size_type pos1, size_type count1, const_pointer s) const {\n return substr(pos1, count1).compare(s);\n }\n\n constexpr int\n compare(\n size_type pos1,\n size_type count1,\n const_pointer s,\n size_type count2\n ) const {\n return substr(pos1, count1).compare(basic_string_view(s, count2));\n }\n\n\n \/\/ TODO: find, rfind, ...\n\n\n static constexpr size_type npos = size_type(-1);\n\n\nprivate:\n value_type const* _data;\n size_type _count;\n};\n\n\n}\n\n\ntemplate<\n class CharT,\n class Traits\n>\nconstexpr bool operator == (\n cmoh::basic_string_view lhs,\n cmoh::basic_string_view rhs\n) noexcept {\n return lhs.compare(rhs) == 0;\n}\n\ntemplate<\n class CharT,\n class Traits\n>\nconstexpr bool operator != (\n cmoh::basic_string_view lhs,\n cmoh::basic_string_view rhs\n) noexcept {\n return lhs.compare(rhs) != 0;\n}\n\ntemplate<\n class CharT,\n class Traits\n>\nconstexpr bool operator < (\n cmoh::basic_string_view lhs,\n cmoh::basic_string_view rhs\n) noexcept {\n return lhs.compare(rhs) < 0;\n}\n\ntemplate<\n class CharT,\n class Traits\n>\nconstexpr bool operator <= (\n cmoh::basic_string_view lhs,\n cmoh::basic_string_view rhs\n) noexcept {\n return lhs.compare(rhs) <= 0;\n}\n\ntemplate<\n class CharT,\n class Traits\n>\nconstexpr bool operator > (\n cmoh::basic_string_view lhs,\n cmoh::basic_string_view rhs\n) noexcept {\n return lhs.compare(rhs) > 0;\n}\n\ntemplate<\n class CharT,\n class Traits\n>\nconstexpr bool operator >= (\n cmoh::basic_string_view lhs,\n cmoh::basic_string_view rhs\n) noexcept {\n return lhs.compare(rhs) >= 0;\n}\n\n\ntemplate <\n class CharT,\n class Traits\n>\nstd::basic_ostream&\noperator << (\n std::basic_ostream& stream,\n cmoh::basic_string_view view\n) {\n auto len = view.size();\n auto pos = view.data();\n\n while (len > 0) {\n stream.put(*pos);\n ++pos;\n --len;\n }\n\n return stream;\n}\n\n\n\/\/ TODO: hash\n\n\n#endif\n\n\n\n\nnamespace cmoh {\n typedef basic_string_view string_view;\n typedef basic_string_view wstring_view;\n typedef basic_string_view u16string_view;\n typedef basic_string_view u32string_view;\n}\n\n\n\n\n#endif\nRemove whitespace in declaration of operator << for basic_string_view\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Julian Ganz\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n#ifndef CMOH_STRING_VIEW_HPP__\n#define CMOH_STRING_VIEW_HPP__\n\n\n\/\/ We try to detect whether a standard `string_view` is available, but only for\n\/\/ post-C++14 (we don't expect a C++14 STL to ship it). We don't consider the\n\/\/ `experimental\/string_view` header, since at least one implementation (the one\n\/\/ shipped with GCC), lacks `constexpr` in critical places.\n#if __cplusplus > 201402L\n# if __has_include()\n# define has_string_view 1\n# endif\n#endif\n\n\n\/\/ local includes\n#include \n\n\n\/\/ use one of the `string_view` implementations\n#ifdef has_string_view\n#include \nnamespace cmoh {\n template <\n typename CharT,\n typename Traits = char_traits\n >\n using basic_string_view = std::basic_string_view;\n}\n#else\n\n\n\/\/ std includes\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace cmoh {\n\n\n\/**\n * Predefinition of the C++17 std::basic_string_view type\n *\n * This template provides an optional type which is modeled after the\n * std::basic_string_view which is part of the C++17 standard proposal. Note\n * that only a subset of the interface is provided. Also note that the Traits\n * defaults to a custom `char_traits`, which has some additional compile\n * capabilities but is somewhat slow at run time.\n *\n * For documentation, refer to the C++17 proposal or your favorite STL\n * documentation site.\n *\/\ntemplate <\n typename CharT,\n typename Traits = char_traits\n>\nclass basic_string_view {\npublic:\n typedef Traits traits_type;\n\n \/\/ value types\n typedef CharT value_type;\n typedef CharT* pointer;\n typedef CharT const* const_pointer;\n typedef CharT& reference;\n typedef CharT const& const_reference;\n\n \/\/ TODO: iterator types\n\n typedef std::size_t size_type;\n typedef std::ptrdiff_t difference_type;\n\n\n constexpr basic_string_view() noexcept : _data(nullptr), _count(0) {}\n constexpr basic_string_view(const basic_string_view& other) noexcept =\n default;\n constexpr basic_string_view(const CharT* data, size_type count) noexcept :\n _data(data), _count(count) {}\n constexpr basic_string_view(const CharT* data) :\n _data(data), _count(traits_type::length(data)) {}\n\n basic_string_view& operator=( const basic_string_view& view ) = default;\n\n\n \/\/ TODO: iterators\n\n\n constexpr const_reference operator[](size_type pos) const {\n return _data[pos];\n }\n\n constexpr const_reference at(size_type pos) const {\n if (pos >= size())\n throw std::out_of_range(\"Access out-of-bounds element.\");\n return _data[pos];\n }\n\n constexpr const_reference front() const {\n return _data[0];\n }\n\n constexpr const_reference back() const {\n return _data[size() - 1];\n }\n\n constexpr const_pointer data() const noexcept {\n return _data;\n }\n\n\n constexpr size_type size() const noexcept {\n return _count;\n }\n\n constexpr size_type length() const noexcept {\n return size();\n }\n\n constexpr size_type max_size() const noexcept {\n return std::numeric_limits::max();\n }\n\n constexpr bool empty() const noexcept {\n return size() == 0;\n }\n\n\n constexpr void remove_prefix(size_type n) {\n _data+=n;\n _count-=n;\n }\n\n constexpr void remove_suffix(size_type n) {\n _count-=n;\n }\n\n constexpr void swap(basic_string_view& v) {\n const_pointer* data = v._data;\n size_type count = v._count;\n\n v._data = _data;\n v._count = _count;\n\n _data = data;\n _count = count;\n }\n\n\n size_type copy(CharT* dest, size_type count, size_type pos = 0) const {\n if (pos >= size())\n throw std::out_of_range(\"Access out-of-bounds element.\");\n count = std::min(count, size() - pos);\n traits_type::copy(\n dest,\n &_data[pos],\n count*sizeof(value_type)\/sizeof(char)\n );\n return count;\n }\n\n constexpr basic_string_view\n substr(size_type pos = 0, size_type count = npos) const {\n if (pos >= size())\n throw std::out_of_range(\"Access out-of-bounds element.\");\n return basic_string_view(_data + pos, std::min(count, size() - pos));\n }\n\n constexpr int compare(basic_string_view v) const noexcept {\n auto retval = traits_type::compare(\n data(),\n v.data(),\n std::min(size(), v.size())\n );\n if (retval != 0)\n return retval;\n if (size() == v.size())\n return 0;\n return size() < v.size() ? -1 : 1;\n }\n\n constexpr int\n compare(size_type pos1, size_type count1, basic_string_view v) const {\n return substr(pos1, count1).compare(v);\n }\n\n constexpr int\n compare(\n size_type pos1,\n size_type count1,\n basic_string_view v,\n size_type pos2,\n size_type count2\n ) const {\n return substr(pos1, count1).compare(v.substr(pos2, count2));\n }\n\n constexpr int compare(const_pointer s) const {\n return compare(basic_string_view(s));\n }\n\n constexpr int\n compare(size_type pos1, size_type count1, const_pointer s) const {\n return substr(pos1, count1).compare(s);\n }\n\n constexpr int\n compare(\n size_type pos1,\n size_type count1,\n const_pointer s,\n size_type count2\n ) const {\n return substr(pos1, count1).compare(basic_string_view(s, count2));\n }\n\n\n \/\/ TODO: find, rfind, ...\n\n\n static constexpr size_type npos = size_type(-1);\n\n\nprivate:\n value_type const* _data;\n size_type _count;\n};\n\n\n}\n\n\ntemplate<\n class CharT,\n class Traits\n>\nconstexpr bool operator == (\n cmoh::basic_string_view lhs,\n cmoh::basic_string_view rhs\n) noexcept {\n return lhs.compare(rhs) == 0;\n}\n\ntemplate<\n class CharT,\n class Traits\n>\nconstexpr bool operator != (\n cmoh::basic_string_view lhs,\n cmoh::basic_string_view rhs\n) noexcept {\n return lhs.compare(rhs) != 0;\n}\n\ntemplate<\n class CharT,\n class Traits\n>\nconstexpr bool operator < (\n cmoh::basic_string_view lhs,\n cmoh::basic_string_view rhs\n) noexcept {\n return lhs.compare(rhs) < 0;\n}\n\ntemplate<\n class CharT,\n class Traits\n>\nconstexpr bool operator <= (\n cmoh::basic_string_view lhs,\n cmoh::basic_string_view rhs\n) noexcept {\n return lhs.compare(rhs) <= 0;\n}\n\ntemplate<\n class CharT,\n class Traits\n>\nconstexpr bool operator > (\n cmoh::basic_string_view lhs,\n cmoh::basic_string_view rhs\n) noexcept {\n return lhs.compare(rhs) > 0;\n}\n\ntemplate<\n class CharT,\n class Traits\n>\nconstexpr bool operator >= (\n cmoh::basic_string_view lhs,\n cmoh::basic_string_view rhs\n) noexcept {\n return lhs.compare(rhs) >= 0;\n}\n\n\ntemplate <\n class CharT,\n class Traits\n>\nstd::basic_ostream&\noperator << (\n std::basic_ostream& stream,\n cmoh::basic_string_view view\n) {\n auto len = view.size();\n auto pos = view.data();\n\n while (len > 0) {\n stream.put(*pos);\n ++pos;\n --len;\n }\n\n return stream;\n}\n\n\n\/\/ TODO: hash\n\n\n#endif\n\n\n\n\nnamespace cmoh {\n typedef basic_string_view string_view;\n typedef basic_string_view wstring_view;\n typedef basic_string_view u16string_view;\n typedef basic_string_view u32string_view;\n}\n\n\n\n\n#endif\n<|endoftext|>"} {"text":"\/**\n * \\file\n * \\brief Thread class header\n *\n * \\author Copyright (C) 2014 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2014-10-27\n *\/\n\n#ifndef INCLUDE_DISTORTOS_THREAD_HPP_\n#define INCLUDE_DISTORTOS_THREAD_HPP_\n\n#include \"distortos\/scheduler\/ThreadBase.hpp\"\n\n#include \n#include \n\nnamespace distortos\n{\n\n\/**\n * \\brief Thread class is a templated interface for thread\n *\n * \\param Function is the function that will be executed in separate thread\n * \\param Args are the arguments for Function\n *\/\n\ntemplate\nclass Thread : private scheduler::ThreadBase\n{\npublic:\n\n\t\/\/\/ base of Thread\n\tusing Base = ThreadBase;\n\n\t\/**\n\t * \\brief Thread's constructor\n\t *\n\t * \\param [in] function is a function that will be executed in separate thread\n\t * \\param [in] args are arguments for function\n\t *\/\n\n\tThread(void* const buffer, const size_t size, const uint8_t priority, Function&& function, Args&&... args) :\n\t\t\tThreadBase{buffer, size, priority},\n\t\t\tboundFunction_{std::bind(std::forward(function), std::forward(args)...)}\n\t{\n\n\t}\n\n\tusing ThreadBase::getPriority;\n\n\tusing ThreadBase::join;\n\n\tusing ThreadBase::setPriority;\n\n\tusing ThreadBase::start;\n\nprivate:\n\n\t\/**\n\t * \\brief Thread's internal function.\n\t *\n\t * Executes bound function object.\n\t *\/\n\n\tvirtual void run() override { boundFunction_(); }\n\n\t\/\/\/ bound function object\n\tdecltype(std::bind(std::declval(), std::declval()...)) boundFunction_;\n};\n\n\/**\n * \\brief Helper factory function to make Thread object with deduced template arguments\n *\n * \\param Function is the function that will be executed\n * \\param Args are the arguments for Function\n *\n * \\param [in] function is a function that will be executed in separate thread\n * \\param [in] args are arguments for function\n *\n * \\return Thread object with deduced template arguments\n *\/\n\ntemplate\nThread makeThread(void* const buffer, const size_t size, const uint8_t priority, Function&& function,\n\t\tArgs&&... args)\n{\n\treturn {buffer, size, priority, std::forward(function), std::forward(args)...};\n}\n\n}\t\/\/ namespace distortos\n\n#endif\t\/\/ INCLUDE_DISTORTOS_THREAD_HPP_\nThread: expose getEffectivePriority() from base class\/**\n * \\file\n * \\brief Thread class header\n *\n * \\author Copyright (C) 2014 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2014-11-11\n *\/\n\n#ifndef INCLUDE_DISTORTOS_THREAD_HPP_\n#define INCLUDE_DISTORTOS_THREAD_HPP_\n\n#include \"distortos\/scheduler\/ThreadBase.hpp\"\n\n#include \n#include \n\nnamespace distortos\n{\n\n\/**\n * \\brief Thread class is a templated interface for thread\n *\n * \\param Function is the function that will be executed in separate thread\n * \\param Args are the arguments for Function\n *\/\n\ntemplate\nclass Thread : private scheduler::ThreadBase\n{\npublic:\n\n\t\/\/\/ base of Thread\n\tusing Base = ThreadBase;\n\n\t\/**\n\t * \\brief Thread's constructor\n\t *\n\t * \\param [in] function is a function that will be executed in separate thread\n\t * \\param [in] args are arguments for function\n\t *\/\n\n\tThread(void* const buffer, const size_t size, const uint8_t priority, Function&& function, Args&&... args) :\n\t\t\tThreadBase{buffer, size, priority},\n\t\t\tboundFunction_{std::bind(std::forward(function), std::forward(args)...)}\n\t{\n\n\t}\n\n\tusing ThreadBase::getEffectivePriority;\n\n\tusing ThreadBase::getPriority;\n\n\tusing ThreadBase::join;\n\n\tusing ThreadBase::setPriority;\n\n\tusing ThreadBase::start;\n\nprivate:\n\n\t\/**\n\t * \\brief Thread's internal function.\n\t *\n\t * Executes bound function object.\n\t *\/\n\n\tvirtual void run() override { boundFunction_(); }\n\n\t\/\/\/ bound function object\n\tdecltype(std::bind(std::declval(), std::declval()...)) boundFunction_;\n};\n\n\/**\n * \\brief Helper factory function to make Thread object with deduced template arguments\n *\n * \\param Function is the function that will be executed\n * \\param Args are the arguments for Function\n *\n * \\param [in] function is a function that will be executed in separate thread\n * \\param [in] args are arguments for function\n *\n * \\return Thread object with deduced template arguments\n *\/\n\ntemplate\nThread makeThread(void* const buffer, const size_t size, const uint8_t priority, Function&& function,\n\t\tArgs&&... args)\n{\n\treturn {buffer, size, priority, std::forward(function), std::forward(args)...};\n}\n\n}\t\/\/ namespace distortos\n\n#endif\t\/\/ INCLUDE_DISTORTOS_THREAD_HPP_\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: c_vari.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2007-11-02 14:52:45 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef ARY_CPP_C_VARI_HXX\n#define ARY_CPP_C_VARI_HXX\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n#include \n \/\/ OTHER\n#include \n#include \n#include \n\n\n\nnamespace ary\n{\nnamespace cpp\n{\n\n\n\/** A C++ variable or constant declaration.\n*\/\nclass Variable : public CodeEntity\n{\n public:\n \/\/ LIFECYCLE\n enum E_ClassId { class_id = 1005 };\n\n Variable();\n Variable(\n const String & i_sLocalName,\n Ce_id i_nOwner,\n E_Protection i_eProtection,\n loc::Le_id i_nFile,\n Type_id i_nType,\n VariableFlags i_aFlags,\n const String & i_sArraySize,\n const String & i_sInitValue );\n ~Variable();\n\n\n \/\/ INQUIRY\n Type_id Type() const;\n const String & ArraySize() const;\n const String & Initialisation() const;\n E_Protection Protection() const { return eProtection; }\n\n private:\n \/\/ Interface csv::ConstProcessorClient\n virtual void do_Accept(\n csv::ProcessorIfc & io_processor ) const;\n\n \/\/ Interface ary::cpp::CodeEntity\n virtual const String &\n inq_LocalName() const;\n virtual Cid inq_Owner() const;\n virtual Lid inq_Location() const;\n\n \/\/ Interface ary::cpp::CppEntity\n virtual ClassId get_AryClass() const;\n\n \/\/ DATA\n CeEssentials aEssentials;\n Type_id nType;\n E_Protection eProtection;\n VariableFlags aFlags;\n String sArraySize;\n String sInitialisation;\n};\n\n\n\n\/\/ IMPLEMENTATION\ninline Type_id\nVariable::Type() const\n { return nType; }\ninline const String &\nVariable::ArraySize() const\n { return sArraySize; }\ninline const String &\nVariable::Initialisation() const\n { return sInitialisation; }\n\n\n\n} \/\/ namespace cpp\n} \/\/ namespace ary\n#endif\nINTEGRATION: CWS changefileheader (1.3.22); FILE MERGED 2008\/03\/28 16:01:06 rt 1.3.22.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: c_vari.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef ARY_CPP_C_VARI_HXX\n#define ARY_CPP_C_VARI_HXX\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n#include \n \/\/ OTHER\n#include \n#include \n#include \n\n\n\nnamespace ary\n{\nnamespace cpp\n{\n\n\n\/** A C++ variable or constant declaration.\n*\/\nclass Variable : public CodeEntity\n{\n public:\n \/\/ LIFECYCLE\n enum E_ClassId { class_id = 1005 };\n\n Variable();\n Variable(\n const String & i_sLocalName,\n Ce_id i_nOwner,\n E_Protection i_eProtection,\n loc::Le_id i_nFile,\n Type_id i_nType,\n VariableFlags i_aFlags,\n const String & i_sArraySize,\n const String & i_sInitValue );\n ~Variable();\n\n\n \/\/ INQUIRY\n Type_id Type() const;\n const String & ArraySize() const;\n const String & Initialisation() const;\n E_Protection Protection() const { return eProtection; }\n\n private:\n \/\/ Interface csv::ConstProcessorClient\n virtual void do_Accept(\n csv::ProcessorIfc & io_processor ) const;\n\n \/\/ Interface ary::cpp::CodeEntity\n virtual const String &\n inq_LocalName() const;\n virtual Cid inq_Owner() const;\n virtual Lid inq_Location() const;\n\n \/\/ Interface ary::cpp::CppEntity\n virtual ClassId get_AryClass() const;\n\n \/\/ DATA\n CeEssentials aEssentials;\n Type_id nType;\n E_Protection eProtection;\n VariableFlags aFlags;\n String sArraySize;\n String sInitialisation;\n};\n\n\n\n\/\/ IMPLEMENTATION\ninline Type_id\nVariable::Type() const\n { return nType; }\ninline const String &\nVariable::ArraySize() const\n { return sArraySize; }\ninline const String &\nVariable::Initialisation() const\n { return sInitialisation; }\n\n\n\n} \/\/ namespace cpp\n} \/\/ namespace ary\n#endif\n<|endoftext|>"} {"text":"fixed inconsistent use of preprocessor macro for entry::print<|endoftext|>"} {"text":"\/\/ Copyright (C) 2009-2010, Vaclav Haisman. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modifica-\n\/\/ tion, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,\n\/\/ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n\/\/ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n\/\/ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-\n\/\/ DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n\/\/ OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n\/\/ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\/\/ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef LOG4CPLUS_CONFIG_HXX\n#define LOG4CPLUS_CONFIG_HXX\n\n#if defined (_WIN32)\n# include \n#elif (defined(__MWERKS__) && defined(__MACOS__))\n# include \n#else\n# include \n#endif\n\n#if ! defined (UNICODE) && ! defined (LOG4CPLUS_HAVE_VSNPRINTF_S) \\\n && ! defined (LOG4CPLUS_HAVE__VSNPRINTF_S) \\\n && ! defined (LOG4CPLUS_HAVE_VSNPRINTF) \\\n && ! defined (LOG4CPLUS_HAVE__VSNPRINTF)\n# undef LOG4CPLUS_USE_POOR_MANS_SNPRINTF\n# define LOG4CPLUS_USE_POOR_MANS_SNPRINTF\n#endif\n\n# if ! defined (LOG4CPLUS_WORKING_LOCALE) \\\n && ! defined (LOG4CPLUS_WORKING_C_LOCALE) \\\n && ! defined (LOG4CPLUS_WITH_ICONV)\n# define LOG4CPLUS_POOR_MANS_CHCONV\n#endif\n\n#if !defined(_WIN32)\n# define LOG4CPLUS_USE_BSD_SOCKETS\n# if !defined(LOG4CPLUS_SINGLE_THREADED)\n# define LOG4CPLUS_USE_PTHREADS\n# endif\n# if defined (INSIDE_LOG4CPLUS)\n# define LOG4CPLUS_EXPORT LOG4CPLUS_DECLSPEC_EXPORT\n# else\n# define LOG4CPLUS_EXPORT LOG4CPLUS_DECLSPEC_IMPORT\n# endif \/\/ defined (INSIDE_LOG4CPLUS)\n\n#endif \/\/ !_WIN32\n\n#if defined (LOG4CPLUS_INLINES_ARE_EXPORTED)\n# define LOG4CPLUS_INLINE_EXPORT inline\n#else\n# define LOG4CPLUS_INLINE_EXPORT\n#endif\n\n#if defined (UNICODE)\n# if defined (_MSC_VER) && _MSC_VER >= 1400\n# define LOG4CPLUS_FSTREAM_ACCEPTS_WCHAR_T\n# endif\n# if defined (_MSC_VER) && _MSC_VER >= 1600\n# define LOG4CPLUS_HAVE_CODECVT_UTF8_FACET\n# define LOG4CPLUS_HAVE_CODECVT_UTF16_FACET\n# endif\n#endif\n\n\/\/ C++11 stuff\n\n#if ! defined (__has_feature)\n\/\/! __has_feature(X) is Clangs way for testing features.\n\/\/! Define it to 0 if it does not exist.\n# define __has_feature(X) 0\n#endif\n\n#if (defined (_MSC_VER) && _MSC_VER >= 1600) \\\n || defined (__GXX_EXPERIMENTAL_CXX0X__)\n# define LOG4CPLUS_HAVE_CXX11_SUPPORT\n#endif\n\n#if defined (LOG4CPLUS_HAVE_CXX11_SUPPORT) \\\n || __has_feature (cxx_rvalue_references)\n# define LOG4CPLUS_HAVE_RVALUE_REFS\n#endif\n\n#if ! defined (UNICODE) && defined (__GNUC__) && __GNUC__ >= 3\n# define LOG4CPLUS_FORMAT_ATTRIBUTE(archetype, format_index, first_arg_index) \\\n __attribute__ ((format (archetype, format_index, first_arg_index)))\n#else\n# define LOG4CPLUS_FORMAT_ATTRIBUTE(archetype, fmt_index, first_arg_index) \\\n \/* empty *\/\n#endif\n\n#include \n\n#if defined(__cplusplus)\nnamespace log4cplus\n{\n\n\/\/! Per thread cleanup function. Users should call this function before\n\/\/! a thread ends its execution. It frees resources allocated in thread local\n\/\/! storage. It is important only for multi-threaded static library builds\n\/\/! of log4cplus and user threads. In all other cases the clean up is provided\n\/\/! automatically by other means.\nLOG4CPLUS_EXPORT void threadCleanup ();\n\n} \/\/ namespace log4cplus\n\n#endif\n\n#endif \/\/ LOG4CPLUS_CONFIG_HXX\nconfig.hxx: Detect #pragma once usability using compiler version numbers.\/\/ Copyright (C) 2009-2010, Vaclav Haisman. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modifica-\n\/\/ tion, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,\n\/\/ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n\/\/ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n\/\/ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-\n\/\/ DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n\/\/ OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n\/\/ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\/\/ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef LOG4CPLUS_CONFIG_HXX\n#define LOG4CPLUS_CONFIG_HXX\n\n#if defined (_WIN32)\n# include \n#elif (defined(__MWERKS__) && defined(__MACOS__))\n# include \n#else\n# include \n#endif\n\n#if ! defined (UNICODE) && ! defined (LOG4CPLUS_HAVE_VSNPRINTF_S) \\\n && ! defined (LOG4CPLUS_HAVE__VSNPRINTF_S) \\\n && ! defined (LOG4CPLUS_HAVE_VSNPRINTF) \\\n && ! defined (LOG4CPLUS_HAVE__VSNPRINTF)\n# undef LOG4CPLUS_USE_POOR_MANS_SNPRINTF\n# define LOG4CPLUS_USE_POOR_MANS_SNPRINTF\n#endif\n\n# if ! defined (LOG4CPLUS_WORKING_LOCALE) \\\n && ! defined (LOG4CPLUS_WORKING_C_LOCALE) \\\n && ! defined (LOG4CPLUS_WITH_ICONV)\n# define LOG4CPLUS_POOR_MANS_CHCONV\n#endif\n\n#if !defined(_WIN32)\n# define LOG4CPLUS_USE_BSD_SOCKETS\n# if !defined(LOG4CPLUS_SINGLE_THREADED)\n# define LOG4CPLUS_USE_PTHREADS\n# endif\n# if defined (INSIDE_LOG4CPLUS)\n# define LOG4CPLUS_EXPORT LOG4CPLUS_DECLSPEC_EXPORT\n# else\n# define LOG4CPLUS_EXPORT LOG4CPLUS_DECLSPEC_IMPORT\n# endif \/\/ defined (INSIDE_LOG4CPLUS)\n\n#endif \/\/ !_WIN32\n\n#if defined (LOG4CPLUS_INLINES_ARE_EXPORTED)\n# define LOG4CPLUS_INLINE_EXPORT inline\n#else\n# define LOG4CPLUS_INLINE_EXPORT\n#endif\n\n#if defined (UNICODE)\n# if defined (_MSC_VER) && _MSC_VER >= 1400\n# define LOG4CPLUS_FSTREAM_ACCEPTS_WCHAR_T\n# endif\n# if defined (_MSC_VER) && _MSC_VER >= 1600\n# define LOG4CPLUS_HAVE_CODECVT_UTF8_FACET\n# define LOG4CPLUS_HAVE_CODECVT_UTF16_FACET\n# endif\n#endif\n\n\/\/ C++11 stuff\n\n#if ! defined (__has_feature)\n\/\/! __has_feature(X) is Clangs way for testing features.\n\/\/! Define it to 0 if it does not exist.\n# define __has_feature(X) 0\n#endif\n\n#if (defined (_MSC_VER) && _MSC_VER >= 1600) \\\n || defined (__GXX_EXPERIMENTAL_CXX0X__)\n# define LOG4CPLUS_HAVE_CXX11_SUPPORT\n#endif\n\n#if defined (LOG4CPLUS_HAVE_CXX11_SUPPORT) \\\n || __has_feature (cxx_rvalue_references)\n# define LOG4CPLUS_HAVE_RVALUE_REFS\n#endif\n\n#if ! defined (UNICODE) && defined (__GNUC__) && __GNUC__ >= 3\n# define LOG4CPLUS_FORMAT_ATTRIBUTE(archetype, format_index, first_arg_index) \\\n __attribute__ ((format (archetype, format_index, first_arg_index)))\n#else\n# define LOG4CPLUS_FORMAT_ATTRIBUTE(archetype, fmt_index, first_arg_index) \\\n \/* empty *\/\n#endif\n\n#if defined (_MSC_VER) \\\n || (defined (__COMO__) && __COMO_VERSION__ >= 400) \/* ??? *\/ \\\n || (defined (__DMC__) && __DMC__ >= 0x700) \/* ??? *\/ \\\n || (defined (__clang__) && __clang__major >= 3) \\\n || (defined (__GNUC__) && (__GNUC__ >= 4 \\\n || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)))\n# define LOG4CPLUS_HAVE_PRAGMA_ONCE\n# pragma once\n#endif\n\n#include \n\n#if defined(__cplusplus)\nnamespace log4cplus\n{\n\n\/\/! Per thread cleanup function. Users should call this function before\n\/\/! a thread ends its execution. It frees resources allocated in thread local\n\/\/! storage. It is important only for multi-threaded static library builds\n\/\/! of log4cplus and user threads. In all other cases the clean up is provided\n\/\/! automatically by other means.\nLOG4CPLUS_EXPORT void threadCleanup ();\n\n} \/\/ namespace log4cplus\n\n#endif\n\n#endif \/\/ LOG4CPLUS_CONFIG_HXX\n<|endoftext|>"} {"text":"\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see .\n*\/\n\/**\n * @author Christian \n * @date 2014\n * JSON interface for the solidity compiler to be used from Javascript.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace dev;\nusing namespace solidity;\n\nstring formatError(Exception const& _exception, string const& _name, CompilerStack const& _compiler)\n{\n\tostringstream errorOutput;\n\tSourceReferenceFormatter::printExceptionInformation(errorOutput, _exception, _name, _compiler);\n\n\tJson::Value output(Json::objectValue);\n\toutput[\"error\"] = errorOutput.str();\n\treturn Json::FastWriter().write(output);\n}\n\nstring compile(string _input, bool optimize)\n{\n\tStringMap sources;\n\tsources[\"\"] = _input;\n\n\tJson::Value output(Json::objectValue);\n\tCompilerStack compiler;\n\ttry\n\t{\n\t\tcompiler.compile(_input, optimize);\n\t}\n\tcatch (ParserError const& exception)\n\t{\n\t\treturn formatError(exception, \"Parser error\", compiler);\n\t}\n\tcatch (DeclarationError const& exception)\n\t{\n\t\treturn formatError(exception, \"Declaration error\", compiler);\n\t}\n\tcatch (TypeError const& exception)\n\t{\n\t\treturn formatError(exception, \"Type error\", compiler);\n\t}\n\tcatch (CompilerError const& exception)\n\t{\n\t\treturn formatError(exception, \"Compiler error\", compiler);\n\t}\n\tcatch (InternalCompilerError const& exception)\n\t{\n\t\treturn formatError(exception, \"Internal compiler error\", compiler);\n\t}\n\tcatch (Exception const& exception)\n\t{\n\t\toutput[\"error\"] = \"Exception during compilation: \" + boost::diagnostic_information(exception);\n\t\treturn Json::FastWriter().write(output);\n\t}\n\tcatch (...)\n\t{\n\t\toutput[\"error\"] = \"Unknown exception during compilation.\";\n\t\treturn Json::FastWriter().write(output);\n\t}\n\n\toutput[\"contracts\"] = Json::Value(Json::objectValue);\n\tfor (string const& contractName: compiler.getContractNames())\n\t{\n\t\tJson::Value contractData(Json::objectValue);\n\t\tcontractData[\"solidity_interface\"] = compiler.getSolidityInterface(contractName);\n\t\tcontractData[\"interface\"] = compiler.getInterface(contractName);\n\t\tcontractData[\"bytecode\"] = toHex(compiler.getBytecode(contractName));\n\t\tcontractData[\"opcodes\"] = eth::disassemble(compiler.getBytecode(contractName));\n\t\tostringstream unused;\n\t\tcontractData[\"assembly\"] = compiler.streamAssembly(unused, contractName, sources);\n\t\toutput[\"contracts\"][contractName] = contractData;\n\t}\n\n\toutput[\"sources\"] = Json::Value(Json::objectValue);\n\toutput[\"sources\"][\"\"] = Json::Value(Json::objectValue);\n\toutput[\"sources\"][\"\"][\"AST\"] = ASTJsonConverter(compiler.getAST(\"\")).json();\n\n\treturn Json::FastWriter().write(output);\n}\n\nstatic string outputBuffer;\n\nextern \"C\"\n{\nextern char const* compileJSON(char const* _input, bool optimize)\n{\n\toutputBuffer = compile(_input, optimize);\n\treturn outputBuffer.c_str();\n}\n}\nStyle fixes.\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see .\n*\/\n\/**\n * @author Christian \n * @date 2014\n * JSON interface for the solidity compiler to be used from Javascript.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace dev;\nusing namespace solidity;\n\nstring formatError(Exception const& _exception, string const& _name, CompilerStack const& _compiler)\n{\n\tostringstream errorOutput;\n\tSourceReferenceFormatter::printExceptionInformation(errorOutput, _exception, _name, _compiler);\n\n\tJson::Value output(Json::objectValue);\n\toutput[\"error\"] = errorOutput.str();\n\treturn Json::FastWriter().write(output);\n}\n\nstring compile(string _input, bool _optimize)\n{\n\tStringMap sources;\n\tsources[\"\"] = _input;\n\n\tJson::Value output(Json::objectValue);\n\tCompilerStack compiler;\n\ttry\n\t{\n\t\tcompiler.compile(_input, _optimize);\n\t}\n\tcatch (ParserError const& exception)\n\t{\n\t\treturn formatError(exception, \"Parser error\", compiler);\n\t}\n\tcatch (DeclarationError const& exception)\n\t{\n\t\treturn formatError(exception, \"Declaration error\", compiler);\n\t}\n\tcatch (TypeError const& exception)\n\t{\n\t\treturn formatError(exception, \"Type error\", compiler);\n\t}\n\tcatch (CompilerError const& exception)\n\t{\n\t\treturn formatError(exception, \"Compiler error\", compiler);\n\t}\n\tcatch (InternalCompilerError const& exception)\n\t{\n\t\treturn formatError(exception, \"Internal compiler error\", compiler);\n\t}\n\tcatch (Exception const& exception)\n\t{\n\t\toutput[\"error\"] = \"Exception during compilation: \" + boost::diagnostic_information(exception);\n\t\treturn Json::FastWriter().write(output);\n\t}\n\tcatch (...)\n\t{\n\t\toutput[\"error\"] = \"Unknown exception during compilation.\";\n\t\treturn Json::FastWriter().write(output);\n\t}\n\n\toutput[\"contracts\"] = Json::Value(Json::objectValue);\n\tfor (string const& contractName: compiler.getContractNames())\n\t{\n\t\tJson::Value contractData(Json::objectValue);\n\t\tcontractData[\"solidity_interface\"] = compiler.getSolidityInterface(contractName);\n\t\tcontractData[\"interface\"] = compiler.getInterface(contractName);\n\t\tcontractData[\"bytecode\"] = toHex(compiler.getBytecode(contractName));\n\t\tcontractData[\"opcodes\"] = eth::disassemble(compiler.getBytecode(contractName));\n\t\tostringstream unused;\n\t\tcontractData[\"assembly\"] = compiler.streamAssembly(unused, contractName, sources);\n\t\toutput[\"contracts\"][contractName] = contractData;\n\t}\n\n\toutput[\"sources\"] = Json::Value(Json::objectValue);\n\toutput[\"sources\"][\"\"] = Json::Value(Json::objectValue);\n\toutput[\"sources\"][\"\"][\"AST\"] = ASTJsonConverter(compiler.getAST(\"\")).json();\n\n\treturn Json::FastWriter().write(output);\n}\n\nstatic string outputBuffer;\n\nextern \"C\"\n{\nextern char const* compileJSON(char const* _input, bool _optimize)\n{\n\toutputBuffer = compile(_input, _optimize);\n\treturn outputBuffer.c_str();\n}\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkStructuredGrid.hh\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n\/\/ .NAME vtkStructuredGrid - topologically regular array of data\n\/\/ .SECTION Description\n\/\/ vtkStructuredGrid is a data object that is a concrete implementation of\n\/\/ vtkDataSet. vtkStructuredGrid represents a geometric structure that is a\n\/\/ topologically regular array of points. The topology is that of a cube that\n\/\/ has been subdivided into a regular array of smaller cubes. Each point\/cell\n\/\/ can be addressed with i-j-k indices. Examples include finite difference \n\/\/ grids.\n\n#ifndef __vtkStructuredGrid_h\n#define __vtkStructuredGrid_h\n\n#include \"vtkPointSet.hh\"\n#include \"vtkStructuredData.hh\"\n#include \"vtkBitScalars.hh\"\n\nclass vtkStructuredGrid : public vtkPointSet {\npublic:\n vtkStructuredGrid();\n vtkStructuredGrid(const vtkStructuredGrid& sg);\n ~vtkStructuredGrid();\n char *GetClassName() {return \"vtkStructuredGrid\";};\n char *GetDataType() {return \"vtkStructuredGrid\";};\n void PrintSelf(ostream& os, vtkIndent indent);\n \n \/\/ dataset interface\n vtkDataSet *MakeObject() {return new vtkStructuredGrid(*this);};\n void CopyStructure(vtkDataSet *ds);\n int GetNumberOfPoints() {return vtkPointSet::GetNumberOfPoints();};\n vtkCell *GetCell(int cellId);\n int GetCellType(int cellId);\n float *GetPoint(int ptId);\n void GetPoint(int ptId, float p[3]);\n int FindCell(float x[3], vtkCell *cell, float tol2, int& subId, \n float pcoords[3],float *weights);\n int GetNumberOfCells();\n void GetCellPoints(int cellId, vtkIdList& ptIds);\n void GetPointCells(int ptId, vtkIdList& cellIds);\n void Initialize();\n int GetMaxCellSize() {return 8;}; \/\/hexahedron is the largest\n\n \/\/ methods specific to structured grid\n void SetDimensions(int i, int j, int k);\n void SetDimensions(int dim[3]);\n\n \/\/ Description:\n \/\/ Get dimensions of this structured points dataset.\n vtkGetVectorMacro(Dimensions,int,3);\n\n int GetDataDimension();\n void BlankingOn();\n void BlankingOff();\n int GetBlanking() {return this->Blanking;};\n void BlankPoint(int ptId);\n void UnBlankPoint(int ptId);\n int IsPointVisible(int ptId);\n\nprotected:\n int Dimensions[3];\n int DataDescription;\n int Blanking;\n vtkBitScalars *PointVisibility;\n\n vtkStructuredData StructuredData; \/\/helper class\n};\n\ninline float *vtkStructuredGrid::GetPoint(int ptId) \n{\n return this->vtkPointSet::GetPoint(ptId);\n}\n\ninline void vtkStructuredGrid::GetPoint(int ptId, float p[3]) \n{\n this->vtkPointSet::GetPoint(ptId,p);\n}\n\ninline int vtkStructuredGrid::GetNumberOfCells() \n{\n int nCells=1;\n int i;\n\n for (i=0; i<3; i++)\n if (this->Dimensions[i] > 1)\n nCells *= (this->Dimensions[i]-1);\n\n return nCells;\n}\n\ninline int vtkStructuredGrid::GetDataDimension()\n{\n return this->StructuredData.GetDataDimension(this->DataDescription);\n}\n\ninline void vtkStructuredGrid::GetCellPoints(int cellId, vtkIdList& ptIds) \n{\n this->StructuredData.GetCellPoints(cellId,ptIds,this->DataDescription,\n this->Dimensions);\n}\n\ninline void vtkStructuredGrid::GetPointCells(int ptId, vtkIdList& cellIds) \n{\n this->StructuredData.GetPointCells(ptId,cellIds,this->Dimensions);\n}\n\ninline int vtkStructuredGrid::FindCell(float x[3], vtkCell *cell, float tol2, \n int& subId, float pcoords[3],\n float *weights)\n{\n return this->vtkPointSet::FindCell(x,cell,tol2,subId,pcoords,weights);\n}\n\n\/\/ Description:\n\/\/ Return non-zero value if specified point is visible.\ninline int vtkStructuredGrid::IsPointVisible(int ptId) \n{\n if (!this->Blanking) return 1; \n else return (int) this->PointVisibility->GetScalar(ptId);\n}\n\n#endif\n\n\n\n\nFixed a nasty bug\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkStructuredGrid.hh\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n\/\/ .NAME vtkStructuredGrid - topologically regular array of data\n\/\/ .SECTION Description\n\/\/ vtkStructuredGrid is a data object that is a concrete implementation of\n\/\/ vtkDataSet. vtkStructuredGrid represents a geometric structure that is a\n\/\/ topologically regular array of points. The topology is that of a cube that\n\/\/ has been subdivided into a regular array of smaller cubes. Each point\/cell\n\/\/ can be addressed with i-j-k indices. Examples include finite difference \n\/\/ grids.\n\n#ifndef __vtkStructuredGrid_h\n#define __vtkStructuredGrid_h\n\n#include \"vtkPointSet.hh\"\n#include \"vtkStructuredData.hh\"\n#include \"vtkBitScalars.hh\"\n\nclass vtkStructuredGrid : public vtkPointSet {\npublic:\n vtkStructuredGrid();\n vtkStructuredGrid(const vtkStructuredGrid& sg);\n ~vtkStructuredGrid();\n char *GetClassName() {return \"vtkStructuredGrid\";};\n char *GetDataType() {return \"vtkStructuredGrid\";};\n void PrintSelf(ostream& os, vtkIndent indent);\n \n \/\/ dataset interface\n vtkDataSet *MakeObject() {return new vtkStructuredGrid(*this);};\n void CopyStructure(vtkDataSet *ds);\n int GetNumberOfPoints() {return vtkPointSet::GetNumberOfPoints();};\n vtkCell *GetCell(int cellId);\n int GetCellType(int cellId);\n float *GetPoint(int ptId);\n void GetPoint(int ptId, float p[3]);\n int FindCell(float x[3], vtkCell *cell, float tol2, int& subId, \n float pcoords[3],float *weights);\n int GetNumberOfCells();\n void GetCellPoints(int cellId, vtkIdList& ptIds);\n void GetPointCells(int ptId, vtkIdList& cellIds);\n void Initialize();\n int GetMaxCellSize() {return 8;}; \/\/hexahedron is the largest\n\n \/\/ methods specific to structured grid\n void SetDimensions(int i, int j, int k);\n void SetDimensions(int dim[3]);\n\n \/\/ Description:\n \/\/ Get dimensions of this structured points dataset.\n vtkGetVectorMacro(Dimensions,int,3);\n\n int GetDataDimension();\n void BlankingOn();\n void BlankingOff();\n int GetBlanking() {return this->Blanking;};\n void BlankPoint(int ptId);\n void UnBlankPoint(int ptId);\n int IsPointVisible(int ptId);\n\nprotected:\n int Dimensions[3];\n int DataDescription;\n int Blanking;\n vtkBitScalars *PointVisibility;\n void AllocatePointVisibility();\n \n vtkStructuredData StructuredData; \/\/helper class\n};\n\ninline float *vtkStructuredGrid::GetPoint(int ptId) \n{\n return this->vtkPointSet::GetPoint(ptId);\n}\n\ninline void vtkStructuredGrid::GetPoint(int ptId, float p[3]) \n{\n this->vtkPointSet::GetPoint(ptId,p);\n}\n\ninline int vtkStructuredGrid::GetNumberOfCells() \n{\n int nCells=1;\n int i;\n\n for (i=0; i<3; i++)\n if (this->Dimensions[i] > 1)\n nCells *= (this->Dimensions[i]-1);\n\n return nCells;\n}\n\ninline int vtkStructuredGrid::GetDataDimension()\n{\n return this->StructuredData.GetDataDimension(this->DataDescription);\n}\n\ninline void vtkStructuredGrid::GetCellPoints(int cellId, vtkIdList& ptIds) \n{\n this->StructuredData.GetCellPoints(cellId,ptIds,this->DataDescription,\n this->Dimensions);\n}\n\ninline void vtkStructuredGrid::GetPointCells(int ptId, vtkIdList& cellIds) \n{\n this->StructuredData.GetPointCells(ptId,cellIds,this->Dimensions);\n}\n\ninline int vtkStructuredGrid::FindCell(float x[3], vtkCell *cell, float tol2, \n int& subId, float pcoords[3],\n float *weights)\n{\n return this->vtkPointSet::FindCell(x,cell,tol2,subId,pcoords,weights);\n}\n\n\/\/ Description:\n\/\/ Return non-zero value if specified point is visible.\ninline int vtkStructuredGrid::IsPointVisible(int ptId) \n{\n if (!this->Blanking) return 1; \n else return (int) this->PointVisibility->GetScalar(ptId);\n}\n\n#endif\n\n\n\n\n<|endoftext|>"} {"text":"#include \"CacheGlyph.h\"\n#include \"TextureMid.h\"\n#include \"DebugDraw.h\"\n#include \"RenderAPI.h\"\n#include \"DrawTexture.h\"\n\n#include \n\n#include \n\n#include \n\nnamespace dtex\n{\n\nstatic const int BUF_SZ = 128 * 128;\nstatic const int MAX_NODE_SIZE = 256;\n\nstatic const int PADDING = 1;\n\nCacheGlyph::CacheGlyph(int width, int height, const Callback& cb)\n\t: m_width(width)\n\t, m_height(height)\n\t, m_cb(cb)\n{\n\tm_buf = new uint32_t[BUF_SZ];\n\n\tm_bitmap = new uint32_t[width * height];\n\tm_tex = new TextureMid(width, height, true);\n\tm_tp = texpack_create(width, height, MAX_NODE_SIZE);\n\n\tInitDirtyRect();\n}\n\nCacheGlyph::~CacheGlyph()\n{\n\tdelete[] m_buf;\n\n\tdelete[] m_bitmap;\n\tdelete m_tex;\n\ttexpack_release(m_tp);\n}\n\nvoid CacheGlyph::DebugDraw() const\n{\n\tDebugDraw::Draw(m_tex->GetID(), 2);\n}\n\nvoid CacheGlyph::Clear()\n{\n\tmemset(m_buf, 0, BUF_SZ);\n\n\tmemset(m_bitmap, 0, sizeof(uint32_t) * m_width * m_height);\n\tDrawTexture::Instance()->ClearTex(m_tex);\n\ttexpack_clear(m_tp);\n\n\tm_exists.clear();\n\tm_nodes.clear();\n\n\tInitDirtyRect();\n}\n\nvoid CacheGlyph::Load(uint32_t* bitmap, int width, int height, uint64_t key)\n{\n\tstd::set::iterator itr = m_exists.find(key);\n\tif (itr != m_exists.end()) {\n\t\treturn;\n\t}\n\n\ttexpack_pos* pos = texpack_add(m_tp, width + PADDING * 2, height + PADDING * 2, false);\n\tif (!pos) \n\t{\n\t\tFlush();\n\t\tClear();\n\t\tpos = texpack_add(m_tp, width + PADDING * 2, height + PADDING * 2, false);\n\t\tif (!pos) {\n\t\t\treturn;\n\t\t}\n\t}\n\n\tm_exists.insert(key);\n\tm_nodes.push_back(Node(key, pos));\n\n\tint src_ptr = 0;\n\tfor (int y = 0; y < height; ++y) {\n\t\tfor (int x = 0; x < width; ++x) {\n\t\t\tuint32_t src = bitmap[src_ptr++];\n\t\t\tuint8_t r = (src >> 24) & 0xff;\n\t\t\tuint8_t g = (src >> 16) & 0xff;\n\t\t\tuint8_t b = (src >> 8) & 0xff;\n\t\t\tuint8_t a = src & 0xff;\n\t\t\tint dst_ptr = (pos->r.ymin + PADDING + y) * m_width + pos->r.xmin + PADDING + x;\n\t\t\tm_bitmap[dst_ptr] = a << 24 | b << 16 | g << 8 | r;\n\t\t}\n\t}\n\n\tUpdateDirtyRect(pos);\n}\n\nvoid CacheGlyph::Flush()\n{\n\tif (m_nodes.empty()) {\n\t\treturn;\n\t}\n\n\tUpdateTexture();\n\n\tm_cb.load_start();\n\tfor (int i = 0, n = m_nodes.size(); i < n; ++i) {\n\t\tconst Node& node = m_nodes[i];\n\t\tm_cb.load(m_tex->GetID(), m_tex->GetWidth(), m_tex->GetHeight(), node.GetRect(), node.Key());\n\t}\n\tm_cb.load_finish();\n\n\tm_exists.clear();\n\tm_nodes.clear();\n\n\tInitDirtyRect();\n}\n\nvoid CacheGlyph::InitDirtyRect()\n{\n\tm_dirty_rect.xmax = m_dirty_rect.ymax = 0;\n\tm_dirty_rect.xmin = m_width;\n\tm_dirty_rect.ymin = m_height;\n}\n\nvoid CacheGlyph::UpdateDirtyRect(const texpack_pos* pos)\n{\n\tif (pos->r.xmin < m_dirty_rect.xmin) {\n\t\tm_dirty_rect.xmin = pos->r.xmin;\n\t}\n\tif (pos->r.ymin < m_dirty_rect.ymin) {\n\t\tm_dirty_rect.ymin = pos->r.ymin;\n\t}\n\tif (pos->r.xmax > m_dirty_rect.xmax) {\n\t\tm_dirty_rect.xmax = pos->r.xmax;\n\t}\n\tif (pos->r.ymax > m_dirty_rect.ymax) {\n\t\tm_dirty_rect.ymax = pos->r.ymax;\n\t}\n}\n\nvoid CacheGlyph::UpdateTexture()\n{\n\tint x = m_dirty_rect.xmin,\n\t\ty = m_dirty_rect.ymin;\n\tint w = m_dirty_rect.xmax - m_dirty_rect.xmin,\n\t\th = m_dirty_rect.ymax - m_dirty_rect.ymin;\n\n\tif (w * h > BUF_SZ) {\n\t\tRenderAPI::UpdateTexture(m_bitmap, m_width, m_height, m_tex->GetID());\n\t\treturn;\n\t}\n\t\n\tint src = y * m_width + x,\n\t\tdst = 0;\n\tint line_sz = w * sizeof(uint32_t);\n\tfor (int i = 0; i < h; ++i) {\n\t\tmemcpy(&m_buf[dst], &m_bitmap[src], line_sz);\n\t\tsrc += m_width;\n\t\tdst += w;\n\t}\n\tRenderAPI::UpdateSubTex(m_buf, x, y, w, h, m_tex->GetID());\n}\n\n\/************************************************************************\/\n\/* class CacheGlyph::Node *\/\n\/************************************************************************\/\n\nCacheGlyph::Node::\nNode(uint64_t key, texpack_pos* pos) \n\t: m_key(key)\n{\n\tm_rect.xmin = pos->r.xmin + PADDING;\n\tm_rect.ymin = pos->r.ymin + PADDING;\n\tm_rect.xmax = pos->r.xmax - PADDING;\n\tm_rect.ymax = pos->r.ymax - PADDING;\n}\n\n}[ADDED] check null bmp#include \"CacheGlyph.h\"\n#include \"TextureMid.h\"\n#include \"DebugDraw.h\"\n#include \"RenderAPI.h\"\n#include \"DrawTexture.h\"\n\n#include \n\n#include \n\n#include \n\nnamespace dtex\n{\n\nstatic const int BUF_SZ = 128 * 128;\nstatic const int MAX_NODE_SIZE = 256;\n\nstatic const int PADDING = 1;\n\nCacheGlyph::CacheGlyph(int width, int height, const Callback& cb)\n\t: m_width(width)\n\t, m_height(height)\n\t, m_cb(cb)\n{\n\tm_buf = new uint32_t[BUF_SZ];\n\n\tm_bitmap = new uint32_t[width * height];\n\tm_tex = new TextureMid(width, height, true);\n\tm_tp = texpack_create(width, height, MAX_NODE_SIZE);\n\n\tInitDirtyRect();\n}\n\nCacheGlyph::~CacheGlyph()\n{\n\tdelete[] m_buf;\n\n\tdelete[] m_bitmap;\n\tdelete m_tex;\n\ttexpack_release(m_tp);\n}\n\nvoid CacheGlyph::DebugDraw() const\n{\n\tDebugDraw::Draw(m_tex->GetID(), 2);\n}\n\nvoid CacheGlyph::Clear()\n{\n\tmemset(m_buf, 0, BUF_SZ);\n\n\tmemset(m_bitmap, 0, sizeof(uint32_t) * m_width * m_height);\n\tDrawTexture::Instance()->ClearTex(m_tex);\n\ttexpack_clear(m_tp);\n\n\tm_exists.clear();\n\tm_nodes.clear();\n\n\tInitDirtyRect();\n}\n\nvoid CacheGlyph::Load(uint32_t* bitmap, int width, int height, uint64_t key)\n{\n\tif (!bitmap) {\n\t\treturn;\n\t}\n\n\tstd::set::iterator itr = m_exists.find(key);\n\tif (itr != m_exists.end()) {\n\t\treturn;\n\t}\n\n\ttexpack_pos* pos = texpack_add(m_tp, width + PADDING * 2, height + PADDING * 2, false);\n\tif (!pos) \n\t{\n\t\tFlush();\n\t\tClear();\n\t\tpos = texpack_add(m_tp, width + PADDING * 2, height + PADDING * 2, false);\n\t\tif (!pos) {\n\t\t\treturn;\n\t\t}\n\t}\n\n\tm_exists.insert(key);\n\tm_nodes.push_back(Node(key, pos));\n\n\tint src_ptr = 0;\n\tfor (int y = 0; y < height; ++y) {\n\t\tfor (int x = 0; x < width; ++x) {\n\t\t\tuint32_t src = bitmap[src_ptr++];\n\t\t\tuint8_t r = (src >> 24) & 0xff;\n\t\t\tuint8_t g = (src >> 16) & 0xff;\n\t\t\tuint8_t b = (src >> 8) & 0xff;\n\t\t\tuint8_t a = src & 0xff;\n\n\t\t\tint dst_ptr = (pos->r.ymin + PADDING + y) * m_width + pos->r.xmin + PADDING + x;\n\t\t\tm_bitmap[dst_ptr] = a << 24 | b << 16 | g << 8 | r;\n\t\t}\n\t}\n\n\tUpdateDirtyRect(pos);\n}\n\nvoid CacheGlyph::Flush()\n{\n\tif (m_nodes.empty()) {\n\t\treturn;\n\t}\n\n\tUpdateTexture();\n\n\tm_cb.load_start();\n\tfor (int i = 0, n = m_nodes.size(); i < n; ++i) {\n\t\tconst Node& node = m_nodes[i];\n\t\tm_cb.load(m_tex->GetID(), m_tex->GetWidth(), m_tex->GetHeight(), node.GetRect(), node.Key());\n\t}\n\tm_cb.load_finish();\n\n\tm_exists.clear();\n\tm_nodes.clear();\n\n\tInitDirtyRect();\n}\n\nvoid CacheGlyph::InitDirtyRect()\n{\n\tm_dirty_rect.xmax = m_dirty_rect.ymax = 0;\n\tm_dirty_rect.xmin = m_width;\n\tm_dirty_rect.ymin = m_height;\n}\n\nvoid CacheGlyph::UpdateDirtyRect(const texpack_pos* pos)\n{\n\tif (pos->r.xmin < m_dirty_rect.xmin) {\n\t\tm_dirty_rect.xmin = pos->r.xmin;\n\t}\n\tif (pos->r.ymin < m_dirty_rect.ymin) {\n\t\tm_dirty_rect.ymin = pos->r.ymin;\n\t}\n\tif (pos->r.xmax > m_dirty_rect.xmax) {\n\t\tm_dirty_rect.xmax = pos->r.xmax;\n\t}\n\tif (pos->r.ymax > m_dirty_rect.ymax) {\n\t\tm_dirty_rect.ymax = pos->r.ymax;\n\t}\n}\n\nvoid CacheGlyph::UpdateTexture()\n{\n\tint x = m_dirty_rect.xmin,\n\t\ty = m_dirty_rect.ymin;\n\tint w = m_dirty_rect.xmax - m_dirty_rect.xmin,\n\t\th = m_dirty_rect.ymax - m_dirty_rect.ymin;\n\n\tif (w * h > BUF_SZ) {\n\t\tRenderAPI::UpdateTexture(m_bitmap, m_width, m_height, m_tex->GetID());\n\t\treturn;\n\t}\n\t\n\tint src = y * m_width + x,\n\t\tdst = 0;\n\tint line_sz = w * sizeof(uint32_t);\n\tfor (int i = 0; i < h; ++i) {\n\t\tmemcpy(&m_buf[dst], &m_bitmap[src], line_sz);\n\t\tsrc += m_width;\n\t\tdst += w;\n\t}\n\tRenderAPI::UpdateSubTex(m_buf, x, y, w, h, m_tex->GetID());\n}\n\n\/************************************************************************\/\n\/* class CacheGlyph::Node *\/\n\/************************************************************************\/\n\nCacheGlyph::Node::\nNode(uint64_t key, texpack_pos* pos) \n\t: m_key(key)\n{\n\tm_rect.xmin = pos->r.xmin + PADDING;\n\tm_rect.ymin = pos->r.ymin + PADDING;\n\tm_rect.xmax = pos->r.xmax - PADDING;\n\tm_rect.ymax = pos->r.ymax - PADDING;\n}\n\n}<|endoftext|>"} {"text":"\/\/===-- Error.cpp -----------------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ C Includes\n#ifdef __APPLE__\n#include \n#endif\n\n\/\/ C++ Includes\n\/\/ Other libraries and framework includes\n\/\/ Project includes\n#include \"lldb\/Core\/Error.h\"\n#include \"lldb\/Core\/Log.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \n#include \n\n#if (defined (__arm__) || defined (__arm64__) || defined (__aarch64__)) && defined (__APPLE__)\n#include \n#endif\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nError::Error ():\n m_code (0),\n m_type (eErrorTypeInvalid),\n m_string ()\n{\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Default constructor\n\/\/----------------------------------------------------------------------\nError::Error(ValueType err, ErrorType type) :\n m_code (err),\n m_type (type),\n m_string ()\n{\n}\n\nError::Error (const Error &rhs) :\n m_code (rhs.m_code),\n m_type (rhs.m_type),\n m_string (rhs.m_string)\n{\n}\n\nError::Error (const char* format, ...):\n m_code (0),\n m_type (eErrorTypeInvalid),\n m_string ()\n{\n va_list args;\n va_start (args, format);\n SetErrorToGenericError ();\n SetErrorStringWithVarArg (format, args);\n va_end (args);\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Assignment operator\n\/\/----------------------------------------------------------------------\nconst Error&\nError::operator = (const Error& rhs)\n{\n if (this != &rhs)\n {\n m_code = rhs.m_code;\n m_type = rhs.m_type;\n m_string = rhs.m_string;\n }\n return *this;\n}\n\n\n\/\/----------------------------------------------------------------------\n\/\/ Assignment operator\n\/\/----------------------------------------------------------------------\nconst Error&\nError::operator = (uint32_t err)\n{\n m_code = err;\n m_type = eErrorTypeMachKernel;\n m_string.clear();\n return *this;\n}\n\nError::~Error()\n{\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Get the error value as a NULL C string. The error string will be\n\/\/ fetched and cached on demand. The cached error string value will\n\/\/ remain until the error value is changed or cleared.\n\/\/----------------------------------------------------------------------\nconst char *\nError::AsCString(const char *default_error_str) const\n{\n if (Success())\n return NULL;\n\n if (m_string.empty())\n {\n const char *s = NULL;\n switch (m_type)\n {\n case eErrorTypeMachKernel:\n#if defined (__APPLE__)\n s = ::mach_error_string (m_code);\n#endif\n break;\n\n case eErrorTypePOSIX:\n s = ::strerror (m_code);\n break;\n\n default:\n break;\n }\n if (s)\n m_string.assign(s);\n }\n if (m_string.empty())\n {\n if (default_error_str)\n m_string.assign(default_error_str);\n else\n return NULL; \/\/ User wanted a NULL string back...\n }\n return m_string.c_str();\n}\n\n\n\/\/----------------------------------------------------------------------\n\/\/ Clear the error and any cached error string that it might contain.\n\/\/----------------------------------------------------------------------\nvoid\nError::Clear ()\n{\n m_code = 0;\n m_type = eErrorTypeGeneric;\n m_string.clear();\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Access the error value.\n\/\/----------------------------------------------------------------------\nError::ValueType\nError::GetError () const\n{\n return m_code;\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Access the error type.\n\/\/----------------------------------------------------------------------\nErrorType\nError::GetType () const\n{\n return m_type;\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Retuns true if this object contains an value that describes an\n\/\/ error or otherwise non-success result.\n\/\/----------------------------------------------------------------------\nbool\nError::Fail () const\n{\n return m_code != 0;\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Log the error given a string with format. If the this object\n\/\/ contains an error code, update the error string to contain the\n\/\/ \"error: \" followed by the formatted string, followed by the error\n\/\/ value and any string that describes the current error. This\n\/\/ allows more context to be given to an error string that remains\n\/\/ cached in this object. Logging always occurs even when the error\n\/\/ code contains a non-error value.\n\/\/----------------------------------------------------------------------\nvoid\nError::PutToLog (Log *log, const char *format, ...)\n{\n char *arg_msg = NULL;\n va_list args;\n va_start (args, format);\n ::vasprintf (&arg_msg, format, args);\n va_end (args);\n\n if (arg_msg != NULL)\n {\n if (Fail())\n {\n const char *err_str = AsCString();\n if (err_str == NULL)\n err_str = \"???\";\n\n SetErrorStringWithFormat(\"error: %s err = %s (0x%8.8x)\", arg_msg, err_str, m_code);\n if (log)\n log->Error(\"%s\", m_string.c_str());\n }\n else\n {\n if (log)\n log->Printf(\"%s err = 0x%8.8x\", arg_msg, m_code);\n }\n ::free (arg_msg);\n }\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Log the error given a string with format. If the this object\n\/\/ contains an error code, update the error string to contain the\n\/\/ \"error: \" followed by the formatted string, followed by the error\n\/\/ value and any string that describes the current error. This\n\/\/ allows more context to be given to an error string that remains\n\/\/ cached in this object. Logging only occurs even when the error\n\/\/ code contains a error value.\n\/\/----------------------------------------------------------------------\nvoid\nError::LogIfError (Log *log, const char *format, ...)\n{\n if (Fail())\n {\n char *arg_msg = NULL;\n va_list args;\n va_start (args, format);\n ::vasprintf (&arg_msg, format, args);\n va_end (args);\n\n if (arg_msg != NULL)\n {\n const char *err_str = AsCString();\n if (err_str == NULL)\n err_str = \"???\";\n\n SetErrorStringWithFormat(\"%s err = %s (0x%8.8x)\", arg_msg, err_str, m_code);\n if (log)\n log->Error(\"%s\", m_string.c_str());\n\n ::free (arg_msg);\n }\n }\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Set accesssor for the error value to \"err\" and the type to\n\/\/ \"eErrorTypeMachKernel\"\n\/\/----------------------------------------------------------------------\nvoid\nError::SetMachError (uint32_t err)\n{\n m_code = err;\n m_type = eErrorTypeMachKernel;\n m_string.clear();\n}\n\nvoid\nError::SetExpressionError (lldb::ExpressionResults result, const char *mssg)\n{\n m_code = result;\n m_type = eErrorTypeExpression;\n m_string = mssg;\n}\n\nint\nError::SetExpressionErrorWithFormat (lldb::ExpressionResults result, const char *format, ...)\n{\n int length = 0;\n \n if (format && format[0])\n {\n va_list args;\n va_start (args, format);\n length = SetErrorStringWithVarArg (format, args);\n va_end (args);\n }\n else\n {\n m_string.clear();\n }\n m_code = result;\n m_type = eErrorTypeExpression;\n return length;\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Set accesssor for the error value and type.\n\/\/----------------------------------------------------------------------\nvoid\nError::SetError (ValueType err, ErrorType type)\n{\n m_code = err;\n m_type = type;\n m_string.clear();\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Update the error value to be \"errno\" and update the type to\n\/\/ be \"POSIX\".\n\/\/----------------------------------------------------------------------\nvoid\nError::SetErrorToErrno()\n{\n m_code = errno;\n m_type = eErrorTypePOSIX;\n m_string.clear();\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Update the error value to be LLDB_GENERIC_ERROR and update the type\n\/\/ to be \"Generic\".\n\/\/----------------------------------------------------------------------\nvoid\nError::SetErrorToGenericError ()\n{\n m_code = LLDB_GENERIC_ERROR;\n m_type = eErrorTypeGeneric;\n m_string.clear();\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Set accessor for the error string value for a specific error.\n\/\/ This allows any string to be supplied as an error explanation.\n\/\/ The error string value will remain until the error value is\n\/\/ cleared or a new error value\/type is assigned.\n\/\/----------------------------------------------------------------------\nvoid\nError::SetErrorString (const char *err_str)\n{\n if (err_str && err_str[0])\n {\n \/\/ If we have an error string, we should always at least have\n \/\/ an error set to a generic value.\n if (Success())\n SetErrorToGenericError();\n m_string = err_str;\n }\n else\n m_string.clear();\n}\n\n\/\/------------------------------------------------------------------\n\/\/\/ Set the current error string to a formatted error string.\n\/\/\/\n\/\/\/ @param format\n\/\/\/ A printf style format string\n\/\/------------------------------------------------------------------\nint\nError::SetErrorStringWithFormat (const char *format, ...)\n{\n if (format && format[0])\n {\n va_list args;\n va_start (args, format);\n int length = SetErrorStringWithVarArg (format, args);\n va_end (args);\n return length;\n }\n else\n {\n m_string.clear();\n }\n return 0;\n}\n\nint\nError::SetErrorStringWithVarArg (const char *format, va_list args)\n{\n if (format && format[0])\n {\n \/\/ If we have an error string, we should always at least have\n \/\/ an error set to a generic value.\n if (Success())\n SetErrorToGenericError();\n\n \/\/ Try and fit our error into a 1024 byte buffer first...\n llvm::SmallVector buf;\n buf.resize(1024);\n \/\/ Copy in case our first call to vsnprintf doesn't fit into our\n \/\/ allocated buffer above\n va_list copy_args;\n va_copy (copy_args, args);\n unsigned length = ::vsnprintf (buf.data(), buf.size(), format, args);\n if (length >= buf.size())\n {\n \/\/ The error formatted string didn't fit into our buffer, resize it\n \/\/ to the exact needed size, and retry\n buf.resize(length + 1);\n length = ::vsnprintf (buf.data(), buf.size(), format, copy_args);\n va_end (copy_args);\n assert (length < buf.size());\n }\n m_string.assign(buf.data(), length);\n va_end (args);\n return length;\n }\n else\n {\n m_string.clear();\n }\n return 0;\n}\n\n\n\/\/----------------------------------------------------------------------\n\/\/ Returns true if the error code in this object is considered a\n\/\/ successful return value.\n\/\/----------------------------------------------------------------------\nbool\nError::Success() const\n{\n return m_code == 0;\n}\n\nbool\nError::WasInterrupted() const\n{\n if (m_type == eErrorTypePOSIX && m_code == EINTR)\n return true;\n else\n return false;\n}\n\nError::Clear() should reset the type to invalid instead of generic.\/\/===-- Error.cpp -----------------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ C Includes\n#ifdef __APPLE__\n#include \n#endif\n\n\/\/ C++ Includes\n\/\/ Other libraries and framework includes\n\/\/ Project includes\n#include \"lldb\/Core\/Error.h\"\n#include \"lldb\/Core\/Log.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \n#include \n\n#if (defined (__arm__) || defined (__arm64__) || defined (__aarch64__)) && defined (__APPLE__)\n#include \n#endif\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nError::Error ():\n m_code (0),\n m_type (eErrorTypeInvalid),\n m_string ()\n{\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Default constructor\n\/\/----------------------------------------------------------------------\nError::Error(ValueType err, ErrorType type) :\n m_code (err),\n m_type (type),\n m_string ()\n{\n}\n\nError::Error (const Error &rhs) :\n m_code (rhs.m_code),\n m_type (rhs.m_type),\n m_string (rhs.m_string)\n{\n}\n\nError::Error (const char* format, ...):\n m_code (0),\n m_type (eErrorTypeInvalid),\n m_string ()\n{\n va_list args;\n va_start (args, format);\n SetErrorToGenericError ();\n SetErrorStringWithVarArg (format, args);\n va_end (args);\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Assignment operator\n\/\/----------------------------------------------------------------------\nconst Error&\nError::operator = (const Error& rhs)\n{\n if (this != &rhs)\n {\n m_code = rhs.m_code;\n m_type = rhs.m_type;\n m_string = rhs.m_string;\n }\n return *this;\n}\n\n\n\/\/----------------------------------------------------------------------\n\/\/ Assignment operator\n\/\/----------------------------------------------------------------------\nconst Error&\nError::operator = (uint32_t err)\n{\n m_code = err;\n m_type = eErrorTypeMachKernel;\n m_string.clear();\n return *this;\n}\n\nError::~Error()\n{\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Get the error value as a NULL C string. The error string will be\n\/\/ fetched and cached on demand. The cached error string value will\n\/\/ remain until the error value is changed or cleared.\n\/\/----------------------------------------------------------------------\nconst char *\nError::AsCString(const char *default_error_str) const\n{\n if (Success())\n return NULL;\n\n if (m_string.empty())\n {\n const char *s = NULL;\n switch (m_type)\n {\n case eErrorTypeMachKernel:\n#if defined (__APPLE__)\n s = ::mach_error_string (m_code);\n#endif\n break;\n\n case eErrorTypePOSIX:\n s = ::strerror (m_code);\n break;\n\n default:\n break;\n }\n if (s)\n m_string.assign(s);\n }\n if (m_string.empty())\n {\n if (default_error_str)\n m_string.assign(default_error_str);\n else\n return NULL; \/\/ User wanted a NULL string back...\n }\n return m_string.c_str();\n}\n\n\n\/\/----------------------------------------------------------------------\n\/\/ Clear the error and any cached error string that it might contain.\n\/\/----------------------------------------------------------------------\nvoid\nError::Clear ()\n{\n m_code = 0;\n m_type = eErrorTypeInvalid;\n m_string.clear();\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Access the error value.\n\/\/----------------------------------------------------------------------\nError::ValueType\nError::GetError () const\n{\n return m_code;\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Access the error type.\n\/\/----------------------------------------------------------------------\nErrorType\nError::GetType () const\n{\n return m_type;\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Retuns true if this object contains an value that describes an\n\/\/ error or otherwise non-success result.\n\/\/----------------------------------------------------------------------\nbool\nError::Fail () const\n{\n return m_code != 0;\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Log the error given a string with format. If the this object\n\/\/ contains an error code, update the error string to contain the\n\/\/ \"error: \" followed by the formatted string, followed by the error\n\/\/ value and any string that describes the current error. This\n\/\/ allows more context to be given to an error string that remains\n\/\/ cached in this object. Logging always occurs even when the error\n\/\/ code contains a non-error value.\n\/\/----------------------------------------------------------------------\nvoid\nError::PutToLog (Log *log, const char *format, ...)\n{\n char *arg_msg = NULL;\n va_list args;\n va_start (args, format);\n ::vasprintf (&arg_msg, format, args);\n va_end (args);\n\n if (arg_msg != NULL)\n {\n if (Fail())\n {\n const char *err_str = AsCString();\n if (err_str == NULL)\n err_str = \"???\";\n\n SetErrorStringWithFormat(\"error: %s err = %s (0x%8.8x)\", arg_msg, err_str, m_code);\n if (log)\n log->Error(\"%s\", m_string.c_str());\n }\n else\n {\n if (log)\n log->Printf(\"%s err = 0x%8.8x\", arg_msg, m_code);\n }\n ::free (arg_msg);\n }\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Log the error given a string with format. If the this object\n\/\/ contains an error code, update the error string to contain the\n\/\/ \"error: \" followed by the formatted string, followed by the error\n\/\/ value and any string that describes the current error. This\n\/\/ allows more context to be given to an error string that remains\n\/\/ cached in this object. Logging only occurs even when the error\n\/\/ code contains a error value.\n\/\/----------------------------------------------------------------------\nvoid\nError::LogIfError (Log *log, const char *format, ...)\n{\n if (Fail())\n {\n char *arg_msg = NULL;\n va_list args;\n va_start (args, format);\n ::vasprintf (&arg_msg, format, args);\n va_end (args);\n\n if (arg_msg != NULL)\n {\n const char *err_str = AsCString();\n if (err_str == NULL)\n err_str = \"???\";\n\n SetErrorStringWithFormat(\"%s err = %s (0x%8.8x)\", arg_msg, err_str, m_code);\n if (log)\n log->Error(\"%s\", m_string.c_str());\n\n ::free (arg_msg);\n }\n }\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Set accesssor for the error value to \"err\" and the type to\n\/\/ \"eErrorTypeMachKernel\"\n\/\/----------------------------------------------------------------------\nvoid\nError::SetMachError (uint32_t err)\n{\n m_code = err;\n m_type = eErrorTypeMachKernel;\n m_string.clear();\n}\n\nvoid\nError::SetExpressionError (lldb::ExpressionResults result, const char *mssg)\n{\n m_code = result;\n m_type = eErrorTypeExpression;\n m_string = mssg;\n}\n\nint\nError::SetExpressionErrorWithFormat (lldb::ExpressionResults result, const char *format, ...)\n{\n int length = 0;\n \n if (format && format[0])\n {\n va_list args;\n va_start (args, format);\n length = SetErrorStringWithVarArg (format, args);\n va_end (args);\n }\n else\n {\n m_string.clear();\n }\n m_code = result;\n m_type = eErrorTypeExpression;\n return length;\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Set accesssor for the error value and type.\n\/\/----------------------------------------------------------------------\nvoid\nError::SetError (ValueType err, ErrorType type)\n{\n m_code = err;\n m_type = type;\n m_string.clear();\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Update the error value to be \"errno\" and update the type to\n\/\/ be \"POSIX\".\n\/\/----------------------------------------------------------------------\nvoid\nError::SetErrorToErrno()\n{\n m_code = errno;\n m_type = eErrorTypePOSIX;\n m_string.clear();\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Update the error value to be LLDB_GENERIC_ERROR and update the type\n\/\/ to be \"Generic\".\n\/\/----------------------------------------------------------------------\nvoid\nError::SetErrorToGenericError ()\n{\n m_code = LLDB_GENERIC_ERROR;\n m_type = eErrorTypeGeneric;\n m_string.clear();\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Set accessor for the error string value for a specific error.\n\/\/ This allows any string to be supplied as an error explanation.\n\/\/ The error string value will remain until the error value is\n\/\/ cleared or a new error value\/type is assigned.\n\/\/----------------------------------------------------------------------\nvoid\nError::SetErrorString (const char *err_str)\n{\n if (err_str && err_str[0])\n {\n \/\/ If we have an error string, we should always at least have\n \/\/ an error set to a generic value.\n if (Success())\n SetErrorToGenericError();\n m_string = err_str;\n }\n else\n m_string.clear();\n}\n\n\/\/------------------------------------------------------------------\n\/\/\/ Set the current error string to a formatted error string.\n\/\/\/\n\/\/\/ @param format\n\/\/\/ A printf style format string\n\/\/------------------------------------------------------------------\nint\nError::SetErrorStringWithFormat (const char *format, ...)\n{\n if (format && format[0])\n {\n va_list args;\n va_start (args, format);\n int length = SetErrorStringWithVarArg (format, args);\n va_end (args);\n return length;\n }\n else\n {\n m_string.clear();\n }\n return 0;\n}\n\nint\nError::SetErrorStringWithVarArg (const char *format, va_list args)\n{\n if (format && format[0])\n {\n \/\/ If we have an error string, we should always at least have\n \/\/ an error set to a generic value.\n if (Success())\n SetErrorToGenericError();\n\n \/\/ Try and fit our error into a 1024 byte buffer first...\n llvm::SmallVector buf;\n buf.resize(1024);\n \/\/ Copy in case our first call to vsnprintf doesn't fit into our\n \/\/ allocated buffer above\n va_list copy_args;\n va_copy (copy_args, args);\n unsigned length = ::vsnprintf (buf.data(), buf.size(), format, args);\n if (length >= buf.size())\n {\n \/\/ The error formatted string didn't fit into our buffer, resize it\n \/\/ to the exact needed size, and retry\n buf.resize(length + 1);\n length = ::vsnprintf (buf.data(), buf.size(), format, copy_args);\n va_end (copy_args);\n assert (length < buf.size());\n }\n m_string.assign(buf.data(), length);\n va_end (args);\n return length;\n }\n else\n {\n m_string.clear();\n }\n return 0;\n}\n\n\n\/\/----------------------------------------------------------------------\n\/\/ Returns true if the error code in this object is considered a\n\/\/ successful return value.\n\/\/----------------------------------------------------------------------\nbool\nError::Success() const\n{\n return m_code == 0;\n}\n\nbool\nError::WasInterrupted() const\n{\n if (m_type == eErrorTypePOSIX && m_code == EINTR)\n return true;\n else\n return false;\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright 2004 The WebRTC Project Authors. All rights reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/base\/latebindingsymboltable.h\"\n\n#if defined(WEBRTC_POSIX)\n#include \n#endif\n\n#include \"webrtc\/base\/logging.h\"\n\nnamespace rtc {\n\n#if defined(WEBRTC_POSIX)\nstatic const DllHandle kInvalidDllHandle = NULL;\n#else\n#error Not implemented\n#endif\n\nstatic const char *GetDllError() {\n#if defined(WEBRTC_POSIX)\n const char *err = dlerror();\n if (err) {\n return err;\n } else {\n return \"No error\";\n }\n#else\n#error Not implemented\n#endif\n}\n\nstatic bool LoadSymbol(DllHandle handle,\n const char *symbol_name,\n void **symbol) {\n#if defined(WEBRTC_POSIX)\n *symbol = dlsym(handle, symbol_name);\n const char *err = dlerror();\n if (err) {\n LOG(LS_ERROR) << \"Error loading symbol \" << symbol_name << \": \" << err;\n return false;\n } else if (!*symbol) {\n \/\/ ELF allows for symbols to be NULL, but that should never happen for our\n \/\/ usage.\n LOG(LS_ERROR) << \"Symbol \" << symbol_name << \" is NULL\";\n return false;\n }\n return true;\n#else\n#error Not implemented\n#endif\n}\n\nLateBindingSymbolTable::LateBindingSymbolTable(const TableInfo *info,\n void **table)\n : info_(info),\n table_(table),\n handle_(kInvalidDllHandle),\n undefined_symbols_(false) {\n ClearSymbols();\n}\n\nLateBindingSymbolTable::~LateBindingSymbolTable() {\n Unload();\n}\n\nbool LateBindingSymbolTable::IsLoaded() const {\n return handle_ != kInvalidDllHandle;\n}\n\nbool LateBindingSymbolTable::Load() {\n ASSERT(info_->dll_name != NULL);\n return LoadFromPath(info_->dll_name);\n}\n\nbool LateBindingSymbolTable::LoadFromPath(const char *dll_path) {\n if (IsLoaded()) {\n return true;\n }\n if (undefined_symbols_) {\n \/\/ We do not attempt to load again because repeated attempts are not\n \/\/ likely to succeed and DLL loading is costly.\n LOG(LS_ERROR) << \"We know there are undefined symbols\";\n return false;\n }\n\n#if defined(WEBRTC_POSIX)\n handle_ = dlopen(dll_path,\n \/\/ RTLD_NOW front-loads symbol resolution so that errors are\n \/\/ caught early instead of causing a process abort later.\n \/\/ RTLD_LOCAL prevents other modules from automatically\n \/\/ seeing symbol definitions in the newly-loaded tree. This\n \/\/ is necessary for same-named symbols in different ABI\n \/\/ versions of the same library to not explode.\n RTLD_NOW|RTLD_LOCAL\n#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)\n \/\/ RTLD_DEEPBIND makes symbol dependencies in the\n \/\/ newly-loaded tree prefer to resolve to definitions within\n \/\/ that tree (the default on OS X). This is necessary for\n \/\/ same-named symbols in different ABI versions of the same\n \/\/ library to not explode.\n |RTLD_DEEPBIND\n#endif\n ); \/\/ NOLINT\n#else\n#error Not implemented\n#endif\n\n if (handle_ == kInvalidDllHandle) {\n LOG(LS_WARNING) << \"Can't load \" << dll_path << \": \"\n << GetDllError();\n return false;\n }\n#if defined(WEBRTC_POSIX)\n \/\/ Clear any old errors.\n dlerror();\n#endif\n for (int i = 0; i < info_->num_symbols; ++i) {\n if (!LoadSymbol(handle_, info_->symbol_names[i], &table_[i])) {\n undefined_symbols_ = true;\n Unload();\n return false;\n }\n }\n return true;\n}\n\nvoid LateBindingSymbolTable::Unload() {\n if (!IsLoaded()) {\n return;\n }\n\n#if defined(WEBRTC_POSIX)\n if (dlclose(handle_) != 0) {\n LOG(LS_ERROR) << GetDllError();\n }\n#else\n#error Not implemented\n#endif\n\n handle_ = kInvalidDllHandle;\n ClearSymbols();\n}\n\nvoid LateBindingSymbolTable::ClearSymbols() {\n memset(table_, 0, sizeof(void *) * info_->num_symbols);\n}\n\n} \/\/ namespace rtc\nLanding issue 15189004\/*\n * Copyright 2004 The WebRTC Project Authors. All rights reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/base\/latebindingsymboltable.h\"\n\n#if defined(WEBRTC_POSIX)\n#include \n#endif\n\n#include \"webrtc\/base\/logging.h\"\n\nnamespace rtc {\n\n#if defined(WEBRTC_POSIX)\nstatic const DllHandle kInvalidDllHandle = NULL;\n#else\n#error Not implemented\n#endif\n\nstatic const char *GetDllError() {\n#if defined(WEBRTC_POSIX)\n const char *err = dlerror();\n if (err) {\n return err;\n } else {\n return \"No error\";\n }\n#else\n#error Not implemented\n#endif\n}\n\nstatic bool LoadSymbol(DllHandle handle,\n const char *symbol_name,\n void **symbol) {\n#if defined(WEBRTC_POSIX)\n *symbol = dlsym(handle, symbol_name);\n const char *err = dlerror();\n if (err) {\n LOG(LS_ERROR) << \"Error loading symbol \" << symbol_name << \": \" << err;\n return false;\n } else if (!*symbol) {\n \/\/ ELF allows for symbols to be NULL, but that should never happen for our\n \/\/ usage.\n LOG(LS_ERROR) << \"Symbol \" << symbol_name << \" is NULL\";\n return false;\n }\n return true;\n#else\n#error Not implemented\n#endif\n}\n\nLateBindingSymbolTable::LateBindingSymbolTable(const TableInfo *info,\n void **table)\n : info_(info),\n table_(table),\n handle_(kInvalidDllHandle),\n undefined_symbols_(false) {\n ClearSymbols();\n}\n\nLateBindingSymbolTable::~LateBindingSymbolTable() {\n Unload();\n}\n\nbool LateBindingSymbolTable::IsLoaded() const {\n return handle_ != kInvalidDllHandle;\n}\n\nbool LateBindingSymbolTable::Load() {\n ASSERT(info_->dll_name != NULL);\n return LoadFromPath(info_->dll_name);\n}\n\nbool LateBindingSymbolTable::LoadFromPath(const char *dll_path) {\n if (IsLoaded()) {\n return true;\n }\n if (undefined_symbols_) {\n \/\/ We do not attempt to load again because repeated attempts are not\n \/\/ likely to succeed and DLL loading is costly.\n LOG(LS_ERROR) << \"We know there are undefined symbols\";\n return false;\n }\n\n#if defined(WEBRTC_POSIX)\n handle_ = dlopen(dll_path,\n \/\/ RTLD_NOW front-loads symbol resolution so that errors are\n \/\/ caught early instead of causing a process abort later.\n \/\/ RTLD_LOCAL prevents other modules from automatically\n \/\/ seeing symbol definitions in the newly-loaded tree. This\n \/\/ is necessary for same-named symbols in different ABI\n \/\/ versions of the same library to not explode.\n RTLD_NOW|RTLD_LOCAL\n#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID) && defined(RTLD_DEEPBIND)\n \/\/ RTLD_DEEPBIND makes symbol dependencies in the\n \/\/ newly-loaded tree prefer to resolve to definitions within\n \/\/ that tree (the default on OS X). This is necessary for\n \/\/ same-named symbols in different ABI versions of the same\n \/\/ library to not explode.\n |RTLD_DEEPBIND\n#endif\n ); \/\/ NOLINT\n#else\n#error Not implemented\n#endif\n\n if (handle_ == kInvalidDllHandle) {\n LOG(LS_WARNING) << \"Can't load \" << dll_path << \": \"\n << GetDllError();\n return false;\n }\n#if defined(WEBRTC_POSIX)\n \/\/ Clear any old errors.\n dlerror();\n#endif\n for (int i = 0; i < info_->num_symbols; ++i) {\n if (!LoadSymbol(handle_, info_->symbol_names[i], &table_[i])) {\n undefined_symbols_ = true;\n Unload();\n return false;\n }\n }\n return true;\n}\n\nvoid LateBindingSymbolTable::Unload() {\n if (!IsLoaded()) {\n return;\n }\n\n#if defined(WEBRTC_POSIX)\n if (dlclose(handle_) != 0) {\n LOG(LS_ERROR) << GetDllError();\n }\n#else\n#error Not implemented\n#endif\n\n handle_ = kInvalidDllHandle;\n ClearSymbols();\n}\n\nvoid LateBindingSymbolTable::ClearSymbols() {\n memset(table_, 0, sizeof(void *) * info_->num_symbols);\n}\n\n} \/\/ namespace rtc\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_GPU_OPENCL_CONTEXT_HPP\n#define STAN_MATH_GPU_OPENCL_CONTEXT_HPP\n#ifdef STAN_OPENCL\n#define __CL_ENABLE_EXCEPTIONS\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define DEVICE_FILTER CL_DEVICE_TYPE_GPU\n#ifndef OPENCL_DEVICE_ID\n#define OPENCL_DEVICE_ID 0\n#endif\n#ifndef OPENCL_PLATFORM_ID\n#define OPENCL_PLATFORM_ID 0\n#endif\n\n\/**\n * @file stan\/math\/gpu\/opencl_context.hpp\n * @brief Initialization for OpenCL:\n * 1. create context\n * 2. Find OpenCL platforms and devices available\n * 3. set up command queue\n * 4. initialize kernel groups\n *\/\n\nnamespace stan {\nnamespace math {\n\n\/**\n * The opencl_context<\/code> class represents the OpenCL context.\n *\n * See the OpenCL specification glossary for a list of terms:\n * https:\/\/www.khronos.org\/registry\/OpenCL\/specs\/opencl-1.2.pdf.\n * The context includes the set of devices available on the host, command\n * queues, manages kernels.\n *\n * This is designed so there's only one instance running on the host.\n *\n * Some design decisions that may need to be addressed later:\n * - we are assuming a single OpenCL platform. We may want to run on multiple\n * platforms simulatenously\n * - we are assuming a single OpenCL device. We may want to run on multiple\n * devices simulatenously\n *\/\nclass opencl_context {\n private:\n cl::Context context_; \/\/ Manages the the device, queue, platform, memory,etc.\n cl::CommandQueue command_queue_; \/\/ job queue for device, one per device\n std::vector platforms_; \/\/ Vector of available platforms\n cl::Platform platform_; \/\/ The platform for compiling kernels\n std::string platform_name_; \/\/ The platform such as NVIDIA OpenCL or AMD SDK\n std::vector devices_; \/\/ All available GPU devices\n cl::Device device_; \/\/ The selected GPU device\n std::string device_name_; \/\/ The name of the GPU\n size_t max_workgroup_size_; \/\/ The maximum size of a block of workers on GPU\n \/** Holds meta information about a kernel\n * @param exists a bool to identify whether a kernel has been compiled\n * @param group The name of the compilation group for the kernel\n * @param code The source code for the kernel\n *\/\n struct kernel_meta_info {\n bool exists;\n const char* group;\n const char* raw_code;\n };\n \/**\n * Map of a kernel name (first) and it's meta information (second).\n *\/\n typedef std::map map_kernel_info;\n \/**\n * map holding compiled kernels.\n *\/\n typedef std::map map_kernel;\n map_kernel_info kernel_info; \/\/ The meta kernel info\n map_kernel kernels; \/\/ The compiled kernels\n\n \/**\n * Construct the opencl_context by initializing the\n * OpenCL context, devices, command queues, and kernel\n * groups.\n *\n * This constructor does the following:\n * 1. Gets the available platforms and selects the platform\n * with id OPENCL_PLATFORM_ID\n * 2. Gets the available devices and selects the device with id\n * OPENCL_DEVICE_ID\n * 3. Creates the OpenCL context with the device\n * 4. Creates the OpenCL command queue for the selected device\n * 5. Initializes the kernel groups by filling the kernel_info <\/code>\n * map.\n * @throw std::system_error if an OpenCL error occurs\n *\/\n opencl_context() {\n try {\n \/\/ platform\n cl::Platform::get(&platforms_);\n platform_ = platforms_[OPENCL_PLATFORM_ID];\n platform_name_ = platform_.getInfo();\n platform_.getDevices(DEVICE_FILTER, &devices_);\n if (devices_.size() == 0) {\n system_error(\"OpenCL Initialization\", \"[Device]\", -1,\n \"CL_DEVICE_NOT_FOUND\");\n }\n device_ = devices_[OPENCL_DEVICE_ID];\n \/\/ context and queue\n context_ = cl::Context(device_);\n command_queue_ = cl::CommandQueue(context_, device_,\n CL_QUEUE_PROFILING_ENABLE, nullptr);\n \/\/ setup kernel groups\n init_kernel_groups();\n device_.getInfo(CL_DEVICE_MAX_WORK_GROUP_SIZE,\n &max_workgroup_size_);\n\n } catch (const cl::Error& e) {\n check_ocl_error(\"opencl_context\", e.what(), e.err());\n }\n }\n \/**\n * Initalizes the kernel_info <\/code> where each kernel is mapped to\n * a logical flag to mark if the kernel was already compiled,\n * the name of the kernel group, and the OpenCL kernel sources.\n *\/\n inline void init_kernel_groups() {\n kernel_info[\"dummy\"] = {\n false, \"timing\", \"__kernel void dummy(__global const int* foo) { };\"};\n kernel_info[\"dummy2\"] = {\n false, \"timing\", \"__kernel void dummy2(__global const int* foo) { };\"};\n }\n\n \/**\n * Compiles all the kernels in the specified. The side effect of this\n * method places all compiled kernels for a group inside of kernels\n * <\/code>.\n *\n * @param kernel_name[in] The kernel name\n *\n * @throw std::system_error if there are compilation errors\n * when compiling the specified kernel group sources\n *\/\n inline void compile_kernel_group(const char* kernel_name) {\n char temp[100];\n int local = 32;\n int gpu_local_max = sqrt(max_workgroup_size());\n if (gpu_local_max < local)\n local = gpu_local_max;\n snprintf(temp, sizeof(temp), \"-D TS=%d -D TS1=%d -D TS2=%d \", local, local,\n local);\n std::string kernel_source = \"\";\n const char* kernel_group = kernel_info[kernel_name].group;\n for (auto kern : kernel_info) {\n if (strcmp(kern.second.group, kernel_group) == 0) {\n kernel_source += kern.second.raw_code;\n }\n }\n\n try {\n cl::Program::Sources source(\n 1,\n std::make_pair(kernel_source.c_str(), strlen(kernel_source.c_str())));\n cl::Program program_ = cl::Program(context_ , source);\n program_.build({device_}, temp);\n\n cl_int err = CL_SUCCESS;\n \/\/ Iterate over the kernel list and get all the kernels from this group\n \/\/ and mark them as compiled.\n for (auto kern : kernel_info) {\n if (strcmp(kern.second.group, kernel_group) == 0) {\n kernels[(kern.first)] = cl::Kernel(program_, kern.first, &err);\n kern.second.exists = true;\n }\n }\n } catch (const cl::Error& e) {\n check_ocl_error(\"Kernel Compilation\", e.what(), e.err());\n }\n }\n\n public:\n\n \/**\n * Returns the kernel specified in kernel_name.\n * If the kernel has not yet been compiled, the kernel group is compiled\n * first.\n *\n * @brief Passing the name of a kernel compiles all kernels in the same group\n * as the selected kernel.\n * OpenCL kernels are compiled JIT, instead of compiling each kernel\n * individually this function will compile all kernels\n * in a predefined group. Groupings are made such that kernels commonly\n * called with one another will be compiled at the same time. For example,\n * An arithmetic group of kernels compiled together could contain the kernels\n * for add() <\/code>, subtract() <\/code>,\n * and multiply() <\/code>. This function will only return the kernel\n * which was called, but when a user asks for a kernel within the group those\n * kernels will already be compiled.\n *\n * @param[in] kernel_name The kernel name\n *\n * @return a copy of the cl::Kernel object\n *\/\n inline cl::Kernel get_kernel(const char* kernel_name) {\n \/\/ Compile the kernel group and return the kernel\n if (!kernel_info[kernel_name].exists) {\n compile_kernel_group(kernel_name);\n }\n return kernels[kernel_name];\n }\n\n \/\/ FIXME:(Steve\/Dan) should probably be deleted before merge\n void debug(std::ostream& s) {\n s << \"inside opencl_context\" << std::endl;\n s << \" * platform_name_: \" << platform_name_ << std::endl;\n }\n \/**\n * Initializes the OpenCL context. This is made with a static local singleton\n * design so that only one context is available.\n *\/\n static opencl_context& getInstance() {\n static opencl_context instance;\n return instance;\n }\n\n \/**\n * Returns the description of the OpenCL platform and device that is used.\n * Devices will be a GPU and Platforms are a specific OpenCL implimenation\n * such as AMD SDK's or Nvidia's OpenCL implimentation.\n *\/\n inline std::string description() const {\n std::ostringstream msg;\n msg << \"Platform ID: \" << OPENCL_DEVICE_ID << \"\\n\";\n msg << \"Platform Name: \" << platform_.getInfo() << \"\\n\";\n msg << \"Platform Vendor: \" << platform_.getInfo()\n << \"\\n\";\n msg << \"\\tDevice \" << OPENCL_DEVICE_ID << \": \"\n << \"\\n\";\n msg << \"\\t\\tDevice Name: \" << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Type: \" << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Vendor: \" << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Max Compute Units: \"\n << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Global Memory: \"\n << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Max Clock Frequency: \"\n << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Max Allocateable Memory: \"\n << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Local Memory: \"\n << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Available: \" << device_.getInfo()\n << \"\\n\";\n return msg.str();\n }\n\n \/**\n * Returns the description of the OpenCL platforms and devices that\n * are available. Devices will be a GPU and Platforms are a specific OpenCL\n * implimenation such as AMD SDK's or Nvidia's OpenCL implimentation.\n *\/\n inline std::string capabilities() const {\n std::vector all_platforms;\n cl::Platform::get(&all_platforms);\n std::ostringstream msg;\n int platform_id = 0;\n int device_id = 0;\n\n msg << \"Number of Platforms: \" << all_platforms.size() << \"\\n\";\n for (auto plat_iter : all_platforms) {\n cl::Platform platform(plat_iter);\n\n msg << \"Platform ID: \" << platform_id++ << \"\\n\";\n msg << \"Platform Name: \" << platform.getInfo() << \"\\n\";\n msg << \"Platform Vendor: \" << platform.getInfo()\n << \"\\n\";\n\n std::vector all_devices;\n platform.getDevices(CL_DEVICE_TYPE_GPU, &all_devices);\n\n for (auto device_iter : all_devices) {\n cl::Device device(device_iter);\n\n msg << \"\\tDevice \" << device_id++ << \": \"\n << \"\\n\";\n msg << \"\\t\\tDevice Name: \" << device.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Type: \" << device.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Vendor: \" << device.getInfo()\n << \"\\n\";\n msg << \"\\t\\tDevice Max Compute Units: \"\n << device.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Global Memory: \"\n << device.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Max Clock Frequency: \"\n << device.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Max Allocateable Memory: \"\n << device.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Local Memory: \"\n << device.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Available: \" << device.getInfo()\n << \"\\n\";\n }\n }\n return msg.str();\n }\n\n \/**\n * Returns the reference to the OpenCL context. The OpenCL context manages\n * objects such as the device, memory, command queue, program, and kernel\n * objects. For stan, there should only be one context, queue, device, and\n * program with multiple kernels.\n *\/\n inline cl::Context& context() { return context_; }\n \/**\n * Returns the reference to the active OpenCL command queue for the device.\n * One command queue will exist per device where\n * kernels are placed on the command queue and by default executed in order.\n *\/\n inline cl::CommandQueue& queue() { return command_queue_; }\n \/**\n * Returns the maximum workgroup size defined by CL_DEVICE_MAX_WORK_GROUP_SIZE\n * for the device in the context. This is the maximum product of work group\n * dimensions for a particular device. IE a max workgoup of 256 would allow\n * work groups of sizes (16,16), (128,2), (8, 32), etc.\n *\/\n inline int max_workgroup_size() { return max_workgroup_size_; }\n\n \/**\n * Returns a vector containing the OpenCL device used to create the context\n *\/\n inline std::vector device() { return {device_}; }\n\n \/**\n * Returns a vector containing the OpenCL platform used to create the context\n *\/\n inline std::vector platform() { return {platform_}; }\n};\n\nstatic opencl_context opencl_context\n = stan::math::opencl_context::getInstance();\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n#endif\nFix spelling#ifndef STAN_MATH_GPU_OPENCL_CONTEXT_HPP\n#define STAN_MATH_GPU_OPENCL_CONTEXT_HPP\n#ifdef STAN_OPENCL\n#define __CL_ENABLE_EXCEPTIONS\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define DEVICE_FILTER CL_DEVICE_TYPE_GPU\n#ifndef OPENCL_DEVICE_ID\n#define OPENCL_DEVICE_ID 0\n#endif\n#ifndef OPENCL_PLATFORM_ID\n#define OPENCL_PLATFORM_ID 0\n#endif\n\n\/**\n * @file stan\/math\/gpu\/opencl_context.hpp\n * @brief Initialization for OpenCL:\n * 1. create context\n * 2. Find OpenCL platforms and devices available\n * 3. set up command queue\n * 4. initialize kernel groups\n *\/\n\nnamespace stan {\nnamespace math {\n\n\/**\n * The opencl_context<\/code> class represents the OpenCL context.\n *\n * See the OpenCL specification glossary for a list of terms:\n * https:\/\/www.khronos.org\/registry\/OpenCL\/specs\/opencl-1.2.pdf.\n * The context includes the set of devices available on the host, command\n * queues, manages kernels.\n *\n * This is designed so there's only one instance running on the host.\n *\n * Some design decisions that may need to be addressed later:\n * - we are assuming a single OpenCL platform. We may want to run on multiple\n * platforms simulatenously\n * - we are assuming a single OpenCL device. We may want to run on multiple\n * devices simulatenously\n *\/\nclass opencl_context {\n private:\n cl::Context context_; \/\/ Manages the the device, queue, platform, memory,etc.\n cl::CommandQueue command_queue_; \/\/ job queue for device, one per device\n std::vector platforms_; \/\/ Vector of available platforms\n cl::Platform platform_; \/\/ The platform for compiling kernels\n std::string platform_name_; \/\/ The platform such as NVIDIA OpenCL or AMD SDK\n std::vector devices_; \/\/ All available GPU devices\n cl::Device device_; \/\/ The selected GPU device\n std::string device_name_; \/\/ The name of the GPU\n size_t max_workgroup_size_; \/\/ The maximum size of a block of workers on GPU\n \/** Holds meta information about a kernel.\n * @param exists a bool to identify whether a kernel has been compiled.\n * @param group The name of the compilation group for the kernel.\n * @param code The source code for the kernel.\n *\/\n struct kernel_meta_info {\n bool exists;\n const char* group;\n const char* raw_code;\n };\n \/**\n * Map of a kernel name (first) and it's meta information (second).\n *\/\n typedef std::map map_kernel_info;\n \/**\n * map holding compiled kernels.\n *\/\n typedef std::map map_kernel;\n map_kernel_info kernel_info; \/\/ The meta kernel info\n map_kernel kernels; \/\/ The compiled kernels\n\n \/**\n * Construct the opencl_context by initializing the\n * OpenCL context, devices, command queues, and kernel\n * groups.\n *\n * This constructor does the following:\n * 1. Gets the available platforms and selects the platform\n * with id OPENCL_PLATFORM_ID.\n * 2. Gets the available devices and selects the device with id\n * OPENCL_DEVICE_ID.\n * 3. Creates the OpenCL context with the device.\n * 4. Creates the OpenCL command queue for the selected device.\n * 5. Initializes the kernel groups by filling the kernel_info <\/code>\n * map.\n * @throw std::system_error if an OpenCL error occurs.\n *\/\n opencl_context() {\n try {\n \/\/ platform\n cl::Platform::get(&platforms_);\n platform_ = platforms_[OPENCL_PLATFORM_ID];\n platform_name_ = platform_.getInfo();\n platform_.getDevices(DEVICE_FILTER, &devices_);\n if (devices_.size() == 0) {\n system_error(\"OpenCL Initialization\", \"[Device]\", -1,\n \"CL_DEVICE_NOT_FOUND\");\n }\n device_ = devices_[OPENCL_DEVICE_ID];\n \/\/ context and queue\n context_ = cl::Context(device_);\n command_queue_ = cl::CommandQueue(context_, device_,\n CL_QUEUE_PROFILING_ENABLE, nullptr);\n \/\/ setup kernel groups\n init_kernel_groups();\n device_.getInfo(CL_DEVICE_MAX_WORK_GROUP_SIZE,\n &max_workgroup_size_);\n\n } catch (const cl::Error& e) {\n check_ocl_error(\"opencl_context\", e.what(), e.err());\n }\n }\n \/**\n * Initializes the kernel_info <\/code> where each kernel is mapped to\n * a logical flag to mark if the kernel was already compiled,\n * the name of the kernel group, and the OpenCL kernel sources.\n *\/\n inline void init_kernel_groups() {\n kernel_info[\"dummy\"] = {\n false, \"timing\", \"__kernel void dummy(__global const int* foo) { };\"};\n kernel_info[\"dummy2\"] = {\n false, \"timing\", \"__kernel void dummy2(__global const int* foo) { };\"};\n }\n\n \/**\n * Compiles all the kernels in the specified group. The side effect of this\n * method places all compiled kernels for a group inside of kernels\n * <\/code>.\n *\n * @param kernel_name[in] The kernel name.\n *\n * @throw std::system_error if there are compilation errors\n * when compiling the specified kernel group's source code.\n *\/\n inline void compile_kernel_group(const char* kernel_name) {\n char temp[100];\n int local = 32;\n int gpu_local_max = sqrt(max_workgroup_size());\n if (gpu_local_max < local)\n local = gpu_local_max;\n snprintf(temp, sizeof(temp), \"-D TS=%d -D TS1=%d -D TS2=%d \", local, local,\n local);\n std::string kernel_source = \"\";\n const char* kernel_group = kernel_info[kernel_name].group;\n for (auto kern : kernel_info) {\n if (strcmp(kern.second.group, kernel_group) == 0) {\n kernel_source += kern.second.raw_code;\n }\n }\n\n try {\n cl::Program::Sources source(\n 1,\n std::make_pair(kernel_source.c_str(), strlen(kernel_source.c_str())));\n cl::Program program_ = cl::Program(context_ , source);\n program_.build({device_}, temp);\n\n cl_int err = CL_SUCCESS;\n \/\/ Iterate over the kernel list and get all the kernels from this group\n \/\/ and mark them as compiled.\n for (auto kern : kernel_info) {\n if (strcmp(kern.second.group, kernel_group) == 0) {\n kernels[(kern.first)] = cl::Kernel(program_, kern.first, &err);\n kern.second.exists = true;\n }\n }\n } catch (const cl::Error& e) {\n check_ocl_error(\"Kernel Compilation\", e.what(), e.err());\n }\n }\n\n public:\n\n \/**\n * Returns the kernel specified in kernel_name.\n * If the kernel has not yet been compiled, the kernel group is compiled\n * first.\n *\n * @brief Passing the name of a kernel compiles all kernels in the same group\n * as the selected kernel.\n * OpenCL kernels are compiled JIT, instead of compiling each kernel\n * individually this function will compile all kernels\n * in a predefined group. Groupings are made such that kernels commonly\n * called with one another will be compiled at the same time. For example,\n * An arithmetic group of kernels compiled together could contain the kernels\n * for add() <\/code>, subtract() <\/code>,\n * and multiply() <\/code>. This function will only return the kernel\n * which was called, but when a user asks for a kernel within the group those\n * kernels will already be compiled.\n *\n * @param[in] kernel_name The kernel name\n *\n * @return a copy of the cl::Kernel object\n *\/\n inline cl::Kernel get_kernel(const char* kernel_name) {\n \/\/ Compile the kernel group and return the kernel\n if (!kernel_info[kernel_name].exists) {\n compile_kernel_group(kernel_name);\n }\n return kernels[kernel_name];\n }\n\n \/\/ FIXME:(Steve\/Dan) should probably be deleted before merge\n void debug(std::ostream& s) {\n s << \"inside opencl_context\" << std::endl;\n s << \" * platform_name_: \" << platform_name_ << std::endl;\n }\n \/**\n * Initializes the OpenCL context. This is made with a static local singleton\n * design so that only one context is available.\n *\/\n static opencl_context& getInstance() {\n static opencl_context instance;\n return instance;\n }\n\n \/**\n * Returns the description of the OpenCL platform and device that is used.\n * Devices will be a GPU and Platforms are a specific OpenCL implimenation\n * such as AMD SDK's or Nvidia's OpenCL implimentation.\n *\/\n inline std::string description() const {\n std::ostringstream msg;\n msg << \"Platform ID: \" << OPENCL_DEVICE_ID << \"\\n\";\n msg << \"Platform Name: \" << platform_.getInfo() << \"\\n\";\n msg << \"Platform Vendor: \" << platform_.getInfo()\n << \"\\n\";\n msg << \"\\tDevice \" << OPENCL_DEVICE_ID << \": \"\n << \"\\n\";\n msg << \"\\t\\tDevice Name: \" << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Type: \" << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Vendor: \" << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Max Compute Units: \"\n << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Global Memory: \"\n << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Max Clock Frequency: \"\n << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Max Allocateable Memory: \"\n << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Local Memory: \"\n << device_.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Available: \" << device_.getInfo()\n << \"\\n\";\n return msg.str();\n }\n\n \/**\n * Returns the description of the OpenCL platforms and devices that\n * are available. Devices will be a GPU and Platforms are a specific OpenCL\n * implimenation such as AMD SDK's or Nvidia's OpenCL implimentation.\n *\/\n inline std::string capabilities() const {\n std::vector all_platforms;\n cl::Platform::get(&all_platforms);\n std::ostringstream msg;\n int platform_id = 0;\n int device_id = 0;\n\n msg << \"Number of Platforms: \" << all_platforms.size() << \"\\n\";\n for (auto plat_iter : all_platforms) {\n cl::Platform platform(plat_iter);\n\n msg << \"Platform ID: \" << platform_id++ << \"\\n\";\n msg << \"Platform Name: \" << platform.getInfo() << \"\\n\";\n msg << \"Platform Vendor: \" << platform.getInfo()\n << \"\\n\";\n\n std::vector all_devices;\n platform.getDevices(CL_DEVICE_TYPE_GPU, &all_devices);\n\n for (auto device_iter : all_devices) {\n cl::Device device(device_iter);\n\n msg << \"\\tDevice \" << device_id++ << \": \"\n << \"\\n\";\n msg << \"\\t\\tDevice Name: \" << device.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Type: \" << device.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Vendor: \" << device.getInfo()\n << \"\\n\";\n msg << \"\\t\\tDevice Max Compute Units: \"\n << device.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Global Memory: \"\n << device.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Max Clock Frequency: \"\n << device.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Max Allocateable Memory: \"\n << device.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Local Memory: \"\n << device.getInfo() << \"\\n\";\n msg << \"\\t\\tDevice Available: \" << device.getInfo()\n << \"\\n\";\n }\n }\n return msg.str();\n }\n\n \/**\n * Returns the reference to the OpenCL context. The OpenCL context manages\n * objects such as the device, memory, command queue, program, and kernel\n * objects. For stan, there should only be one context, queue, device, and\n * program with multiple kernels.\n *\/\n inline cl::Context& context() { return context_; }\n \/**\n * Returns the reference to the active OpenCL command queue for the device.\n * One command queue will exist per device where\n * kernels are placed on the command queue and by default executed in order.\n *\/\n inline cl::CommandQueue& queue() { return command_queue_; }\n \/**\n * Returns the maximum workgroup size defined by CL_DEVICE_MAX_WORK_GROUP_SIZE\n * for the device in the context. This is the maximum product of work group\n * dimensions for a particular device. IE a max workgoup of 256 would allow\n * work groups of sizes (16,16), (128,2), (8, 32), etc.\n *\/\n inline int max_workgroup_size() { return max_workgroup_size_; }\n\n \/**\n * Returns a vector containing the OpenCL device used to create the context\n *\/\n inline std::vector device() { return {device_}; }\n\n \/**\n * Returns a vector containing the OpenCL platform used to create the context\n *\/\n inline std::vector platform() { return {platform_}; }\n};\n\nstatic opencl_context opencl_context\n = stan::math::opencl_context::getInstance();\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2008-2016 the MRtrix3 contributors\n * \n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n * \n * MRtrix is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * \n * For more details, see www.mrtrix.org\n * \n *\/\n\n\n#include \"command.h\"\n#include \"image.h\"\n#include \n#include \n\n#define DEFAULT_SIZE 5\n\nusing namespace MR;\nusing namespace App;\n\n\nvoid usage ()\n{\n DESCRIPTION\n + \"denoise DWI data and estimate the noise level based on the optimal threshold for PCA.\";\n\n \n AUTHOR = \"Daan Christiaens (daan.christiaens@kuleuven.be) & Jelle Veraart (jelle.veraart@nyumc.org) & J-Donald Tournier (jdtournier.gmail.com)\";\n \n \n ARGUMENTS\n + Argument (\"dwi\", \"the input diffusion-weighted image.\").type_image_in ()\n\n + Argument (\"out\", \"the output denoised DWI image.\").type_image_out ();\n\n\n OPTIONS\n + Option (\"size\", \"set the window size of the denoising filter. (default = \" + str(DEFAULT_SIZE) + \")\")\n + Argument (\"window\").type_integer (0, 50)\n \n + Option (\"noise\", \"the output noise map.\")\n + Argument (\"level\").type_image_out();\n\n}\n\n\ntypedef float value_type;\n\n\ntemplate \nclass DenoisingFunctor\n{\npublic:\n DenoisingFunctor (ImageType& dwi, int size)\n : extent(size\/2),\n m(dwi.size(3)),\n n(size*size*size),\n X(m,n), Xm(m),\n pos{0, 0, 0}\n { }\n \n void operator () (ImageType& dwi, ImageType& out)\n {\n \/\/ Load data in local window\n load_data(dwi);\n \/\/ Centre data\n Xm = X.rowwise().mean();\n X.colwise() -= Xm;\n \/\/ Compute SVD\n Eigen::JacobiSVD svd (X, Eigen::ComputeThinU | Eigen::ComputeThinV);\n Eigen::VectorXd s = svd.singularValues();\n \/\/ Simply threshold at 90% variance for now\n double thres = 0.90 * s.squaredNorm();\n double cumsum = 0.0;\n for (size_t i = 0; i < n; ++i) {\n if (cumsum <= thres)\n cumsum += s[i] * s[i];\n else\n s[i] = 0.0;\n }\n \/\/ Restore DWI data\n X = svd.matrixU() * s.asDiagonal() * svd.matrixV().adjoint();\n X.colwise() += Xm;\n \/\/ Store output\n assign_pos_of(dwi).to(out);\n out.row(3) = X.col(n\/2).template cast();\n }\n \n void load_data (ImageType& dwi)\n {\n pos[0] = dwi.index(0); pos[1] = dwi.index(1); pos[2] = dwi.index(2);\n X.setZero();\n ssize_t k = 0;\n for (dwi.index(2) = pos[2]-extent; dwi.index(2) <= pos[2]+extent; ++dwi.index(2))\n for (dwi.index(1) = pos[1]-extent; dwi.index(1) <= pos[1]+extent; ++dwi.index(1))\n for (dwi.index(0) = pos[0]-extent; dwi.index(0) <= pos[0]+extent; ++dwi.index(0), ++k)\n if (! is_out_of_bounds(dwi))\n X.col(k) = dwi.row(3).template cast();\n \/\/ reset image position\n dwi.index(0) = pos[0];\n dwi.index(1) = pos[1];\n dwi.index(2) = pos[2];\n }\n \nprivate:\n int extent;\n size_t m, n;\n Eigen::MatrixXd X;\n Eigen::VectorXd Xm;\n ssize_t pos[3];\n \n};\n\n\n\nvoid run ()\n{\n auto dwi_in = Image::open (argument[0]).with_direct_io(3);\n\n auto header = Header (dwi_in);\n header.datatype() = DataType::Float32;\n auto dwi_out = Image::create (argument[1], header);\n \n int extent = get_option_value(\"size\", DEFAULT_SIZE);\n \n DenoisingFunctor< Image > func (dwi_in, extent);\n \n ThreadedLoop (\"running MP-PCA denoising\", dwi_in, 0, 3)\n .run (func, dwi_in, dwi_out);\n\n}\n\n\nSwitch to single-precision floats.\/*\n * Copyright (c) 2008-2016 the MRtrix3 contributors\n * \n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n * \n * MRtrix is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * \n * For more details, see www.mrtrix.org\n * \n *\/\n\n\n#include \"command.h\"\n#include \"image.h\"\n#include \n#include \n\n#define DEFAULT_SIZE 5\n\nusing namespace MR;\nusing namespace App;\n\n\nvoid usage ()\n{\n DESCRIPTION\n + \"denoise DWI data and estimate the noise level based on the optimal threshold for PCA.\";\n\n \n AUTHOR = \"Daan Christiaens (daan.christiaens@kuleuven.be) & Jelle Veraart (jelle.veraart@nyumc.org) & J-Donald Tournier (jdtournier.gmail.com)\";\n \n \n ARGUMENTS\n + Argument (\"dwi\", \"the input diffusion-weighted image.\").type_image_in ()\n\n + Argument (\"out\", \"the output denoised DWI image.\").type_image_out ();\n\n\n OPTIONS\n + Option (\"size\", \"set the window size of the denoising filter. (default = \" + str(DEFAULT_SIZE) + \")\")\n + Argument (\"window\").type_integer (0, 50)\n \n + Option (\"noise\", \"the output noise map.\")\n + Argument (\"level\").type_image_out();\n\n}\n\n\ntypedef float value_type;\n\n\ntemplate \nclass DenoisingFunctor\n{\npublic:\n DenoisingFunctor (ImageType& dwi, int size)\n : extent(size\/2),\n m(dwi.size(3)),\n n(size*size*size),\n X(m,n), Xm(m),\n pos{0, 0, 0}\n { }\n \n void operator () (ImageType& dwi, ImageType& out)\n {\n \/\/ Load data in local window\n load_data(dwi);\n \/\/ Centre data\n Xm = X.rowwise().mean();\n X.colwise() -= Xm;\n \/\/ Compute SVD\n Eigen::JacobiSVD svd (X, Eigen::ComputeThinU | Eigen::ComputeThinV);\n Eigen::VectorXf s = svd.singularValues();\n \/\/ Simply threshold at 90% variance for now\n double thres = 0.90 * s.squaredNorm();\n double cumsum = 0.0;\n for (size_t i = 0; i < n; ++i) {\n if (cumsum <= thres)\n cumsum += s[i] * s[i];\n else\n s[i] = 0.0;\n }\n \/\/ Restore DWI data\n X = svd.matrixU() * s.asDiagonal() * svd.matrixV().adjoint();\n X.colwise() += Xm;\n \/\/ Store output\n assign_pos_of(dwi).to(out);\n out.row(3) = X.col(n\/2).template cast();\n }\n \n void load_data (ImageType& dwi)\n {\n pos[0] = dwi.index(0); pos[1] = dwi.index(1); pos[2] = dwi.index(2);\n X.setZero();\n ssize_t k = 0;\n for (dwi.index(2) = pos[2]-extent; dwi.index(2) <= pos[2]+extent; ++dwi.index(2))\n for (dwi.index(1) = pos[1]-extent; dwi.index(1) <= pos[1]+extent; ++dwi.index(1))\n for (dwi.index(0) = pos[0]-extent; dwi.index(0) <= pos[0]+extent; ++dwi.index(0), ++k)\n if (! is_out_of_bounds(dwi))\n X.col(k) = dwi.row(3).template cast();\n \/\/ reset image position\n dwi.index(0) = pos[0];\n dwi.index(1) = pos[1];\n dwi.index(2) = pos[2];\n }\n \nprivate:\n int extent;\n size_t m, n;\n Eigen::MatrixXf X;\n Eigen::VectorXf Xm;\n ssize_t pos[3];\n \n};\n\n\n\nvoid run ()\n{\n auto dwi_in = Image::open (argument[0]).with_direct_io(3);\n\n auto header = Header (dwi_in);\n header.datatype() = DataType::Float32;\n auto dwi_out = Image::create (argument[1], header);\n \n int extent = get_option_value(\"size\", DEFAULT_SIZE);\n \n DenoisingFunctor< Image > func (dwi_in, extent);\n \n ThreadedLoop (\"running MP-PCA denoising\", dwi_in, 0, 3)\n .run (func, dwi_in, dwi_out);\n\n}\n\n\n<|endoftext|>"} {"text":"\/*\n * CrissCross\n * A multi-purpose cross-platform library.\n *\n * A product of Uplink Laboratories.\n *\n * (c) 2006-2010 Steven Noonan.\n * Licensed under the New BSD License.\n *\n *\/\n\n#include \"header.h\"\n\nusing namespace CrissCross::Data;\nusing namespace CrissCross::IO;\nusing namespace CrissCross::System;\nusing namespace std;\n\nConsole *console = NULL;\n\ntypedef unsigned long ktype_t;\nconst size_t MaxSearches = 100000;\n\n#define XORSwap(x,y) { (x) = (x) ^ (y); (y) = (y) ^ (x); (x) = (x) ^ (y); }\n\nvoid shuffleElements(DArray *_array) \n{ \n\tktype_t temporary;\n\tsize_t randomNum, last, size = _array->used();\n\tDArray &array = *_array;\n\n\tfor (last = size; last > 1; last--) \n\t{ \n\t\trandomNum = RandomNumber() % last;\n\t\ttemporary = array[randomNum];\n\t\tarray[randomNum] = array[last - 1];\n\t\tarray[last - 1] = temporary;\n\t}\n}\n\ntemplate \nvoid TestTree(T _tree, DArray *dataset, unsigned long _size)\n{\n\tconsole->Write(\"%10lu \", _size);\n\t\n\t\/\/ fill tree\n\tStopwatch sw;\n\tsw.Start();\n\tfor (size_t i = 0; i < _size; i++) {\n\t\tktype_t item = dataset->get(i);\n\t\t_tree->insert(item, item);\n\t}\n\tsw.Stop();\n\tconsole->Write(\"%9.5lfs \", sw.Elapsed());\n\t\n\tDArray searchItems;\n\t\n\t\/\/ create valid item list\n\tsearchItems.empty();\n\twhile (searchItems.used() < MaxSearches) {\n\t\tunsigned long idx = RandomNumber() % _size;\n\t\tsearchItems.insert(dataset->get(idx));\n\t}\n\t\n\t\/\/ successful searches\n\tsw.Start();\n\tfor (size_t i = 0; i < MaxSearches; i++) {\n\t\t_tree->find(searchItems[i], 0);\n\t}\n\tsw.Stop();\n\tconsole->Write(\"%9.5lfs \", sw.Elapsed());\n\t\n\t\/\/ create mixed item list\n\tsearchItems.empty();\n\twhile (searchItems.used() < MaxSearches) {\n\t\tunsigned long idx;\n\t\t\n\t\tidx = RandomNumber() % _size;\n\t\tsearchItems.insert(dataset->get(idx));\n\t\t\n\t\tidx = _size + (RandomNumber() % _size);\n\t\tsearchItems.insert(dataset->get(idx));\n\t}\n\t\n\t\/\/ mixed success searches\n\tsw.Start();\n\tfor (size_t i = 0; i < MaxSearches; i++) {\n\t\t_tree->find(searchItems[i], 0);\n\t}\n\tsw.Stop();\n\tconsole->Write(\"%9.5lfs \", sw.Elapsed());\n\t\n\t\/\/ create invalid item list\n\tsearchItems.empty();\n\twhile (searchItems.used() < MaxSearches) {\n\t\tunsigned long idx = _size + (RandomNumber() % _size);\n\t\tsearchItems.insert(dataset->get(idx));\n\t}\n\t\n\t\/\/ invalid searches\n\tsw.Start();\n\tfor (size_t i = 0; i < MaxSearches; i++) {\n\t\t_tree->find(searchItems[i], 0);\n\t}\n\tsw.Stop();\n\tconsole->Write(\"%9.5lfs \", sw.Elapsed());\n\n\t\/\/ empty tree\n\tsw.Start();\n\t_tree->empty();\n\tsw.Stop();\n\tconsole->WriteLine(\"%9.5lfs\", sw.Elapsed());\n}\n\nint main(int argc, char * *argv)\n{\n\tconsole = new Console();\n\n\t\/* Begin your application here. *\/\n\n\tSeedRandom();\n\tStopwatch sw;\n\tsize_t sizes [] = {\n\t\t50000,\n\t\t100000,\n\t\t500000,\n\t\t1000000,\n\t\t5000000,\n\t\t10000000,\n\t\t0 };\n\tsize_t biggest = 0;\n\t\n\t\/\/ Locate the last element in the sizes list.\n\tfor (size_t *p = sizes; *p != 0; p++) {\n\t\tbiggest = max(biggest, *p);\n\t}\n\t\n\tDArray *dataset = new DArray(biggest*2);\n\tconsole->Write(\"Building data set of %lu items... \", biggest * 2);\n\tsw.Start();\n\tsize_t i = 0;\n\twhile (dataset->used() < biggest * 2) {\n\t\tdataset->insert(i++);\n\t}\n\tshuffleElements(dataset);\n\tsw.Stop();\n\tconsole->WriteLine(\"%8.5lfs\", sw.Elapsed());\n\n\tconsole->WriteLine();\n\tconsole->WriteLine(\"Testing AVLTree...\");\n\tconsole->WriteLine(\"%10s %10s %10s %10s %10s %10s\", \"size\", \"add\", \"srch+\", \"srch\", \"srch-\", \"empty\");\n\tAVLTree *avltree = new AVLTree();\n\tfor (size_t *p = sizes; *p != 0; p++) {\n\t\tTestTree *> (avltree, dataset, *p);\n\t}\n\tconsole->WriteLine(\"AVLTree tests complete.\");\n\tdelete avltree;\n\tavltree = NULL;\n\n\tconsole->WriteLine();\n\tconsole->WriteLine(\"Testing RedBlackTree...\");\n\tconsole->WriteLine(\"%10s %10s %10s %10s %10s %10s\", \"size\", \"add\", \"srch+\", \"srch\", \"srch-\", \"empty\");\n\tRedBlackTree *rbtree = new RedBlackTree();\n\tfor (size_t *p = sizes; *p != 0; p++) {\n\t\tTestTree *> (rbtree, dataset, *p);\n\t}\n\tconsole->WriteLine(\"RedBlackTree tests complete.\");\n\tdelete rbtree;\n\trbtree = NULL;\n\n\tconsole->WriteLine();\n\tconsole->WriteLine(\"Testing SplayTree...\");\n\tconsole->WriteLine(\"%10s %10s %10s %10s %10s %10s\", \"size\", \"add\", \"srch+\", \"srch\", \"srch-\", \"empty\");\n\tSplayTree *splaytree = new SplayTree();\n\tfor (size_t *p = sizes; *p != 0; p++) {\n\t\tTestTree *> (splaytree, dataset, *p);\n\t}\n\tconsole->WriteLine(\"SplayTree tests complete.\");\n\tdelete splaytree;\n\tsplaytree = NULL;\n\n\tconsole->WriteLine();\n\tconsole->WriteLine(\"Testing STree...\");\n\tconsole->WriteLine(\"%10s %10s %10s %10s %10s %10s\", \"size\", \"add\", \"srch+\", \"srch\", \"srch-\", \"empty\");\n\tSTree *stree = new STree();\n\tfor (size_t *p = sizes; *p != 0; p++) {\n\t\tTestTree *> (stree, dataset, *p);\n\t}\n\tconsole->WriteLine(\"STree tests complete.\");\n\tdelete stree;\n\tstree = NULL;\n\n#ifdef ENABLE_STLTREE\n\tconsole->WriteLine();\n\tconsole->WriteLine(\"Testing STLTree...\");\n\tconsole->WriteLine(\"%10s %10s %10s %10s %10s %10s\", \"size\", \"add\", \"srch+\", \"srch\", \"srch-\", \"empty\");\n\tSTLTree *stltree = new STLTree();\n\tfor (size_t *p = sizes; *p != 0; p++) {\n\t\tTestTree *> (stltree, dataset, *p);\n\t}\n\tconsole->WriteLine(\"STLTree tests complete.\");\n\tdelete stltree;\n\tstltree = NULL;\n#endif\n\t\n\tdelete dataset;\n\tconsole->WriteLine();\n\n\t\/* End your application here. *\/\n\n#ifdef TARGET_OS_WINDOWS\n\tsystem(\"pause\");\n#endif\n\n\tdelete console;\n\treturn 0;\n}\nTreeBenchmark: improve accuracy of results\/*\n * CrissCross\n * A multi-purpose cross-platform library.\n *\n * A product of Uplink Laboratories.\n *\n * (c) 2006-2010 Steven Noonan.\n * Licensed under the New BSD License.\n *\n *\/\n\n#include \"header.h\"\n\n#include \n\nusing namespace CrissCross::Data;\nusing namespace CrissCross::IO;\nusing namespace CrissCross::System;\nusing namespace std;\n\nConsole *console = NULL;\n\ntypedef unsigned long ktype_t;\n\n#define XORSwap(x,y) { (x) = (x) ^ (y); (y) = (y) ^ (x); (x) = (x) ^ (y); }\n\nvoid shuffleElements(ktype_t *_array, size_t size)\n{ \n\tktype_t temporary;\n\tsize_t randomNum, last;\n\n\tfor (last = size; last > 1; last--) \n\t{ \n\t\trandomNum = RandomNumber() % last;\n\t\ttemporary = _array[randomNum];\n\t\t_array[randomNum] = _array[last - 1];\n\t\t_array[last - 1] = temporary;\n\t}\n}\n\ntemplate \nvoid RunTestcase(T _tree, unsigned long _size, bool _ordered_insert)\n{\n\tconsole->Write(\"%10lu \", _size);\n\t\n\tunsigned long realsize = _size * 2;\n\n\tktype_t *elems = NULL;\n\tif (!_ordered_insert) {\n\t\telems = new ktype_t[_size + 1];\n\t\tfor (size_t i = 1; i < _size + 1; i++) {\n\t\t\telems[i] = 2*i;\n\t\t}\n\t\telems[_size] = 0;\n\t\tshuffleElements(elems, _size);\n\t}\n\n\t\/\/ fill tree\n\tStopwatch sw;\n\tsw.Start();\n\tif (_ordered_insert) {\n\t\tfor (size_t i = 0; i < _size; i++) {\n\t\t\t_tree->insert(2 * i, 1);\n\t\t}\n\t} else {\n\t\tfor (ktype_t *p = elems; *p; p++) {\n\t\t\t_tree->insert(*p, 1);\n\t\t}\n\t}\n\tsw.Stop();\n\tconsole->Write(\"%9.5lfs \", sw.Elapsed());\n\tdelete [] elems;\n\telems = NULL;\n\n\t\/\/ successful searches\n\tsw.Start();\n\tfor (size_t i = 0; i < _size; i++) {\n\t\t_tree->find((2 * RandomNumber()) % realsize, 0);\n\t}\n\tsw.Stop();\n\tconsole->Write(\"%9.5lfs \", sw.Elapsed());\n\n\t\/\/ mixed success searches\n\tsw.Start();\n\tfor (size_t i = 0; i < _size; i++) {\n\t\t_tree->find(RandomNumber() % realsize, 0);\n\t}\n\tsw.Stop();\n\tconsole->Write(\"%9.5lfs \", sw.Elapsed());\n\n\t\/\/ invalid searches\n\tsw.Start();\n\tfor (size_t i = 0; i < _size; i++) {\n\t\t_tree->find((1 + 2 * RandomNumber()) % realsize, 0);\n\t}\n\tsw.Stop();\n\tconsole->Write(\"%9.5lfs \", sw.Elapsed());\n\n\t\/\/ empty tree\n\tsw.Start();\n\t_tree->empty();\n\tsw.Stop();\n\tconsole->WriteLine(\"%9.5lfs\", sw.Elapsed());\n}\n\ntemplate \nvoid Test(const char *_name, size_t *sizes)\n{\n\tT *tree;\n\tconsole->WriteLine(\"Testing %s...\", _name);\n\tconsole->WriteLine();\n\tconsole->WriteLine(\"Dataset: Random\");\n\tconsole->WriteLine(\"%10s %10s %10s %10s %10s %10s\", \"size\", \"add\", \"srch+\", \"srch\", \"srch-\", \"empty\");\n\ttree = new T();\n\tfor (size_t *p = sizes; *p != 0; p++) {\n\t\tRunTestcase (tree, *p, false);\n\t}\n\tdelete tree;\n\ttree = NULL;\n\tconsole->WriteLine();\n\tconsole->WriteLine(\"Dataset: Ordered\");\n\tconsole->WriteLine(\"%10s %10s %10s %10s %10s %10s\", \"size\", \"add\", \"srch+\", \"srch\", \"srch-\", \"empty\");\n\ttree = new T();\n\tfor (size_t *p = sizes; *p != 0; p++) {\n\t\tRunTestcase (tree, *p, true);\n\t}\n\tdelete tree;\n\ttree = NULL;\n\tconsole->WriteLine();\n\tconsole->WriteLine(\"%s tests complete.\", _name);\n\tconsole->WriteLine();\n\tconsole->WriteLine();\n}\n\nint main(int argc, char * *argv)\n{\n\tconsole = new Console();\n\n\t\/* Begin your application here. *\/\n\n\tSeedRandom();\n\n\tconst size_t count = 11;\n\tsize_t *sizes = new size_t[count + 1];\n\tfor(size_t i = 0; i < count; i++) {\n\t\tsizes[i] = (size_t)pow(2.0,i+10.0);\n\t}\n\tsizes[count] = 0;\n\n\tTest< AVLTree >(\"AVLTree\", sizes);\n\tTest< RedBlackTree >(\"RedBlackTree\", sizes);\n\tTest< SplayTree >(\"SplayTree\", sizes);\n\/\/\tTest< STree >(\"STree\", sizes);\n#ifdef ENABLE_STLTREE\n\tTest< STLTree >(\"STLTree\", sizes);\n#endif\n\n\tconsole->WriteLine();\n\n\t\/* End your application here. *\/\n\n#ifdef TARGET_OS_WINDOWS\n\tsystem(\"pause\");\n#endif\n\n\tdelete console;\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\r\n\/\/ Copyright (c) 2002 Stanislav Shwartsman\r\n\/\/ Written by Stanislav Shwartsman \r\n\/\/\r\n\/\/ This library is free software; you can redistribute it and\/or\r\n\/\/ modify it under the terms of the GNU Lesser General Public\r\n\/\/ License as published by the Free Software Foundation; either\r\n\/\/ version 2 of the License, or (at your option) any later version.\r\n\/\/\r\n\/\/ This library is distributed in the hope that it will be useful,\r\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n\/\/ Lesser General Public License for more details.\r\n\/\/\r\n\/\/ You should have received a copy of the GNU Lesser General Public\r\n\/\/ License along with this library; if not, write to the Free Software\r\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r\n\/\/\r\n\r\n#define NEED_CPU_REG_SHORTCUTS 1\r\n#include \"bochs.h\"\r\n#define LOG_THIS BX_CPU_THIS_PTR\r\n\r\n#if BX_SUPPORT_3DNOW\r\n\r\nvoid BX_CPU_C::PFPNACC_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFPNACC_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PI2FW_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PI2FW_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PI2FD_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PI2FD_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PF2IW_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PF2IW_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PF2ID_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PF2ID_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFNACC_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFNACC_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFCMPGE_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFCMPGE_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFMIN_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFMIN_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFRCP_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFRCP_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFRSQRT_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFRSQRT_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFSUB_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFSUB_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFADD_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFADD_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFCMPGT_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFCMPGT_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFMAX_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFMAX_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFRCPIT1_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFRCPIT1_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFRSQIT1_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFRSQIT1_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFSUBR_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFSUBR_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFACC_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFACC_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFCMPEQ_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFCMPEQ_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFMUL_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFMUL_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFRCPIT2_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFRCPIT2_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\n\/* 0F 0F \/r B7 *\/\r\nvoid BX_CPU_C::PMULHRW_PqQq(bxInstruction_c *i)\r\n{\r\n BX_CPU_THIS_PTR prepareMMX();\r\n\r\n BxPackedMmxRegister op1 = BX_READ_MMX_REG(i->nnn()), op2, result;\r\n\r\n \/* op2 is a register or memory reference *\/\r\n if (i->modC0()) {\r\n op2 = BX_READ_MMX_REG(i->rm());\r\n }\r\n else {\r\n \/* pointer, segment address pair *\/\r\n read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op2);\r\n }\r\n\r\n Bit32s product1 = Bit32s(MMXSW0(op1)) * Bit32s(MMXSW0(op2)) + 0x8000;\r\n Bit32s product2 = Bit32s(MMXSW1(op1)) * Bit32s(MMXSW1(op2)) + 0x8000;\r\n Bit32s product3 = Bit32s(MMXSW2(op1)) * Bit32s(MMXSW2(op2)) + 0x8000;\r\n Bit32s product4 = Bit32s(MMXSW3(op1)) * Bit32s(MMXSW3(op2)) + 0x8000;\r\n\r\n MMXUW0(result) = Bit16u(product1 >> 16);\r\n MMXUW1(result) = Bit16u(product2 >> 16);\r\n MMXUW2(result) = Bit16u(product3 >> 16);\r\n MMXUW3(result) = Bit16u(product4 >> 16);\r\n\r\n \/* now write result back to destination *\/\r\n BX_WRITE_MMX_REG(i->nnn(), result);\r\n}\r\n\r\n\/* 0F 0F \/r BB *\/\r\nvoid BX_CPU_C::PSWAPD_PqQq(bxInstruction_c *i)\r\n{\r\n BX_CPU_THIS_PTR prepareMMX();\r\n\r\n BxPackedMmxRegister result, op;\r\n\r\n \/* op is a register or memory reference *\/\r\n if (i->modC0()) {\r\n op = BX_READ_MMX_REG(i->rm());\r\n }\r\n else {\r\n \/* pointer, segment address pair *\/\r\n read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op);\r\n }\r\n\r\n MMXUD0(result) = MMXUD1(op);\r\n MMXUD1(result) = MMXUD0(op);\r\n\r\n \/* now write result back to destination *\/\r\n BX_WRITE_MMX_REG(i->nnn(), result);\r\n}\r\n\r\n#endif\r\nImplement a few 3DNOW instructions\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\r\n\/\/ Copyright (c) 2002 Stanislav Shwartsman\r\n\/\/ Written by Stanislav Shwartsman \r\n\/\/\r\n\/\/ This library is free software; you can redistribute it and\/or\r\n\/\/ modify it under the terms of the GNU Lesser General Public\r\n\/\/ License as published by the Free Software Foundation; either\r\n\/\/ version 2 of the License, or (at your option) any later version.\r\n\/\/\r\n\/\/ This library is distributed in the hope that it will be useful,\r\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n\/\/ Lesser General Public License for more details.\r\n\/\/\r\n\/\/ You should have received a copy of the GNU Lesser General Public\r\n\/\/ License along with this library; if not, write to the Free Software\r\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r\n\/\/\r\n\r\n#define NEED_CPU_REG_SHORTCUTS 1\r\n#include \"bochs.h\"\r\n#define LOG_THIS BX_CPU_THIS_PTR\r\n\r\n#if BX_SUPPORT_3DNOW\r\n\r\n#include \"softfloat.h\"\r\n\r\nstatic void prepare_softfloat_status_word\r\n\t(softfloat_status_word_t &status_word, int rounding_mode)\r\n{\r\n status.float_detect_tininess = float_tininess_before_rounding;\r\n status.float_exception_flags = 0; \/\/ clear exceptions before execution\r\n status.float_nan_handling_mode = float_first_operand_nan;\r\n status.float_rounding_mode = rounding_mode;\r\n status.flush_underflow_to_zero = 0;\r\n}\r\n\r\nvoid BX_CPU_C::PFPNACC_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFPNACC_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\n\/* 0F 0F \/r 0C *\/\r\nvoid BX_CPU_C::PI2FW_PqQq(bxInstruction_c *i)\r\n{\r\n BxPackedMmxRegister result, op;\r\n\r\n \/* op is a register or memory reference *\/\r\n if (i->modC0()) {\r\n op = BX_READ_MMX_REG(i->rm());\r\n }\r\n else {\r\n \/* pointer, segment address pair *\/\r\n read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op);\r\n }\r\n\r\n softfloat_status_word_t status_word;\r\n prepare_softfloat_status_word(status_word, float_round_to_zero);\r\n\r\n MMXUD0(result) = \r\n int32_to_float32((Bit32s)(MMXSW0(op)), status_word);\r\n MMXUD1(result) = \r\n int32_to_float32((Bit32s)(MMXSW2(op)), status_word);\r\n\r\n \/* now write result back to destination *\/\r\n BX_WRITE_MMX_REG(i->nnn(), result);\r\n}\r\n\r\n\/* 0F 0F \/r 0D *\/\r\nvoid BX_CPU_C::PI2FD_PqQq(bxInstruction_c *i)\r\n{\r\n BxPackedMmxRegister result, op;\r\n\r\n \/* op is a register or memory reference *\/\r\n if (i->modC0()) {\r\n op = BX_READ_MMX_REG(i->rm());\r\n }\r\n else {\r\n \/* pointer, segment address pair *\/\r\n read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op);\r\n }\r\n\r\n softfloat_status_word_t status_word;\r\n prepare_softfloat_status_word(status_word, float_round_to_zero);\r\n\r\n MMXUD0(result) = \r\n int32_to_float32(MMXSD0(op), status_word);\r\n MMXUD1(result) = \r\n int32_to_float32(MMXSD1(op), status_word);\r\n\r\n \/* now write result back to destination *\/\r\n BX_WRITE_MMX_REG(i->nnn(), result);\r\n}\r\n\r\nvoid BX_CPU_C::PF2IW_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PF2IW_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\n\/* 0F 0F \/r 1D *\/\r\nvoid BX_CPU_C::PF2ID_PqQq(bxInstruction_c *i)\r\n{\r\n BxPackedMmxRegister result, op;\r\n\r\n \/* op is a register or memory reference *\/\r\n if (i->modC0()) {\r\n op = BX_READ_MMX_REG(i->rm());\r\n }\r\n else {\r\n \/* pointer, segment address pair *\/\r\n read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op);\r\n }\r\n\r\n softfloat_status_word_t status_word;\r\n prepare_softfloat_status_word(status_word, float_round_to_zero);\r\n\r\n MMXSD0(result) = \r\n float32_to_int32_round_to_zero(MMXUD0(op), status_word);\r\n MMXSD1(result) = \r\n float32_to_int32_round_to_zero(MMXUD1(op), status_word);\r\n\r\n \/* now write result back to destination *\/\r\n BX_WRITE_MMX_REG(i->nnn(), result);\r\n}\r\n\r\nvoid BX_CPU_C::PFNACC_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFNACC_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFCMPGE_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFCMPGE_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFMIN_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFMIN_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFRCP_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFRCP_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFRSQRT_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFRSQRT_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFSUB_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFSUB_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFADD_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFADD_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFCMPGT_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFCMPGT_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFMAX_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFMAX_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFRCPIT1_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFRCPIT1_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFRSQIT1_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFRSQIT1_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFSUBR_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFSUBR_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFACC_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFACC_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFCMPEQ_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFCMPEQ_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFMUL_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFMUL_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\nvoid BX_CPU_C::PFRCPIT2_PqQq(bxInstruction_c *i)\r\n{\r\n BX_PANIC((\"PFRCPIT2_PqQq: 3DNow! instruction still not implemented\"));\r\n}\r\n\r\n\/* 0F 0F \/r B7 *\/\r\nvoid BX_CPU_C::PMULHRW_PqQq(bxInstruction_c *i)\r\n{\r\n BX_CPU_THIS_PTR prepareMMX();\r\n\r\n BxPackedMmxRegister op1 = BX_READ_MMX_REG(i->nnn()), op2, result;\r\n\r\n \/* op2 is a register or memory reference *\/\r\n if (i->modC0()) {\r\n op2 = BX_READ_MMX_REG(i->rm());\r\n }\r\n else {\r\n \/* pointer, segment address pair *\/\r\n read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op2);\r\n }\r\n\r\n Bit32s product1 = Bit32s(MMXSW0(op1)) * Bit32s(MMXSW0(op2)) + 0x8000;\r\n Bit32s product2 = Bit32s(MMXSW1(op1)) * Bit32s(MMXSW1(op2)) + 0x8000;\r\n Bit32s product3 = Bit32s(MMXSW2(op1)) * Bit32s(MMXSW2(op2)) + 0x8000;\r\n Bit32s product4 = Bit32s(MMXSW3(op1)) * Bit32s(MMXSW3(op2)) + 0x8000;\r\n\r\n MMXUW0(result) = Bit16u(product1 >> 16);\r\n MMXUW1(result) = Bit16u(product2 >> 16);\r\n MMXUW2(result) = Bit16u(product3 >> 16);\r\n MMXUW3(result) = Bit16u(product4 >> 16);\r\n\r\n \/* now write result back to destination *\/\r\n BX_WRITE_MMX_REG(i->nnn(), result);\r\n}\r\n\r\n\/* 0F 0F \/r BB *\/\r\nvoid BX_CPU_C::PSWAPD_PqQq(bxInstruction_c *i)\r\n{\r\n BX_CPU_THIS_PTR prepareMMX();\r\n\r\n BxPackedMmxRegister result, op;\r\n\r\n \/* op is a register or memory reference *\/\r\n if (i->modC0()) {\r\n op = BX_READ_MMX_REG(i->rm());\r\n }\r\n else {\r\n \/* pointer, segment address pair *\/\r\n read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op);\r\n }\r\n\r\n MMXUD0(result) = MMXUD1(op);\r\n MMXUD1(result) = MMXUD0(op);\r\n\r\n \/* now write result back to destination *\/\r\n BX_WRITE_MMX_REG(i->nnn(), result);\r\n}\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"#include \"XXX\/kernel.h\"\n#include \"XXX\/rawsocket_protocol.h\"\n#include \"XXX\/wamp_connector.h\"\n#include \"XXX\/wamp_session.h\"\n#include \"XXX\/websocket_protocol.h\"\n\n#include \n#include \n\nusing namespace XXX;\n\nvoid rpc(wamp_invocation& invoke)\n{\n invoke.yield( { jalson::json_array({\"hello\", \"world\"}) ,{} } );\n}\n\nint main(int, char**)\n{\n try {\n\n std::unique_ptr the_kernel( new XXX::kernel({}, logger::nolog() ));\n the_kernel->start();\n\n \/\/ Attempt to make a socket connection & build a wamp_session\n auto wconn = wamp_connector::create( the_kernel.get(),\n \"127.0.0.1\", \"55555\",\n false );\n\n auto connect_status = wconn->completion_future().wait_for(std::chrono::milliseconds(100));\n\n if (connect_status == std::future_status::timeout)\n throw std::runtime_error(\"time-out during network connect\");\n\n std::promise promise_on_close;\n\n std::shared_ptr session = wconn->create_session(\n [&promise_on_close](XXX::session_handle, bool is_open){\n if (!is_open)\n promise_on_close.set_value();\n });\n\n \/\/ Logon to a WAMP realm, and wait for session to be deemed open\n client_credentials credentials;\n credentials.realm=\"default_realm\";\n credentials.authid=\"peter\";\n credentials.authmethods = {\"wampcra\"};\n credentials.secret_fn = []() -> std::string { return \"secret2\"; };\n\n auto session_open_fut = session->initiate_hello(credentials);\n\n if (session_open_fut.wait_for(std::chrono::milliseconds(5000)) == std::future_status::timeout)\n throw std::runtime_error(\"time-out during session logon\");\n\n \/\/ Session is now open, register an RPC\n session->provide(\"inline\", jalson::json_object(), rpc);\n\n \/\/ Wait until we get disconnected\n promise_on_close.get_future().wait();\n\n return 0;\n }\n catch (std::exception& e)\n {\n std::cout << e.what() << std::endl;\n return 1;\n }\n}\n\nupgrade to recent interface changes#include \"XXX\/kernel.h\"\n#include \"XXX\/rawsocket_protocol.h\"\n#include \"XXX\/wamp_connector.h\"\n#include \"XXX\/wamp_session.h\"\n#include \"XXX\/websocket_protocol.h\"\n\n#include \n#include \n\nusing namespace XXX;\n\nvoid rpc(wamp_invocation& invoke)\n{\n invoke.yield( { jalson::json_array({\"hello\", \"world\"}) ,{} } );\n}\n\nint main(int, char**)\n{\n try {\n\n std::unique_ptr the_kernel( new XXX::kernel({}, logger::nolog() ));\n\n \/\/ Attempt to make a socket connection & build a wamp_session\n auto wconn = wamp_connector::create( the_kernel.get(),\n \"127.0.0.1\", \"55555\",\n false );\n\n auto connect_status = wconn->completion_future().wait_for(std::chrono::milliseconds(100));\n\n if (connect_status == std::future_status::timeout)\n throw std::runtime_error(\"time-out during network connect\");\n\n std::promise promise_on_close;\n\n std::shared_ptr session = wconn->create_session(\n [&promise_on_close](XXX::session_handle, bool is_open){\n if (!is_open)\n promise_on_close.set_value();\n });\n\n \/\/ Logon to a WAMP realm, and wait for session to be deemed open\n client_credentials credentials;\n credentials.realm=\"default_realm\";\n credentials.authid=\"peter\";\n credentials.authmethods = {\"wampcra\"};\n credentials.secret_fn = []() -> std::string { return \"secret2\"; };\n\n auto session_open_fut = session->initiate_hello(credentials);\n\n if (session_open_fut.wait_for(std::chrono::milliseconds(5000)) == std::future_status::timeout)\n throw std::runtime_error(\"time-out during session logon\");\n\n \/\/ Session is now open, register an RPC\n session->provide(\"inline\", jalson::json_object(), rpc);\n\n \/\/ Wait until we get disconnected\n promise_on_close.get_future().wait();\n\n return 0;\n }\n catch (std::exception& e)\n {\n std::cout << e.what() << std::endl;\n return 1;\n }\n}\n\n<|endoftext|>"} {"text":"#include \"packet.h\"\n\n#include \n#include \n#include \n\n \/\/Constructor\n Packet::Packet () {\n\tsequenceNum = 0;\n\tcheckSum = 0;\n\tackNack = 0;\n dataBuff[512];\n }\n Packet::Packet (int sn, const char db[505]){\n sequenceNum = sn % 32;\n strcpy(dataBuff, db);\n checkSum = generateCheckSum();\n ackNack =0;\n }\n \/\/Setter Methods\n void Packet::setSequenceNum(int sn){\n sequenceNum = sn;\n }\n \n void Packet::setCheckSum(int cs){\n checkSum = cs;\n }\n \n void Packet::setAckNack(int an){\n ackNack = an;\n }\n\n void Packet::loadDataBuffer(char* data){\n strcpy(dataBuff, data);\n }\n char* Packet::getDataBuffer() {\n return dataBuff;\n }\n \/\/Attach header to the data array\n char* Packet::str(){\n\tstd::cout << \"sequenceNum in packet.str(): \" << sequenceNum << std::endl;\n std::string tempStr(dataBuff);\n std::string packetString;\n std::string csStr;\n\tstd::string sns;\n\t\n\tstd::cout << \"sequenceNum in packet.str(): \" << sequenceNum << std::endl;\n\tif (tempStr[0] == '\\0') return \"\\0\";\n\t\n\tstd::cout << \"sequenceNum in packet.str(): \" << sequenceNum << std::endl;\n csStr = std::to_string((long long int)checkSum);\n while(csStr.length() < 5) csStr += '0';\n\n\tstd::cout << \"sequenceNum in packet.str(): \" << sequenceNum << std::endl;\n\n\tsns = std::to_string((long long int)sequenceNum);\n\tif(sns.length() < 2) sns.insert(0, 1, '0');\n\n packetString = sns + csStr + std::to_string((long long int)ackNack) + tempStr;\n\n\tstd::cout << \"packetString: \" << packetString << std::endl;\n\n strcpy(packet, packetString.c_str());\n return packet;\n }\n \/\/Getter Methods\n int Packet::getSequenceNum(){\n return sequenceNum;\n }\n \n int Packet::getCheckSum(){\n return checkSum;\n }\n\n int Packet::getAckNack(){\n return ackNack;\n }\n bool Packet::chksm() {\n return (checkSum) == generateCheckSum();\n }\n int Packet::generateCheckSum() {\n int cs = 0;\n if(dataBuff == NULL){\n return -1;\n }\n \n for(int x = 0; x < sizeof(dataBuff); x++) {\n if(dataBuff[x] == '\\0') {\n x = sizeof(dataBuff);\n break;\n }\n cs += dataBuff[x];\n }\n\n if(cs <= 9999) cs *= 10;\n\n if(cs > 0) return cs;\n return -1;\n }\nKind of? Let's remove some testing text...#include \"packet.h\"\n\n#include \n#include \n#include \n\n \/\/Constructor\n Packet::Packet () {\n\tsequenceNum = 0;\n\tcheckSum = 0;\n\tackNack = 0;\n dataBuff[512];\n }\n Packet::Packet (int sn, const char db[505]){\n sequenceNum = sn % 32;\n strcpy(dataBuff, db);\n checkSum = generateCheckSum();\n ackNack =0;\n }\n \/\/Setter Methods\n void Packet::setSequenceNum(int sn){\n sequenceNum = sn;\n }\n \n void Packet::setCheckSum(int cs){\n checkSum = cs;\n }\n \n void Packet::setAckNack(int an){\n ackNack = an;\n }\n\n void Packet::loadDataBuffer(char* data){\n strcpy(dataBuff, data);\n }\n char* Packet::getDataBuffer() {\n return dataBuff;\n }\n \/\/Attach header to the data array\n char* Packet::str(){\n std::string tempStr(dataBuff);\n std::string packetString;\n std::string csStr;\n\tstd::string sns;\n\t\n\tif (tempStr[0] == '\\0') return \"\\0\";\n\t\n csStr = std::to_string((long long int)checkSum);\n while(csStr.length() < 5) csStr += '0';\n\n\tsns = std::to_string((long long int)sequenceNum);\n\tif(sns.length() < 2) sns.insert(0, 1, '0');\n\n packetString = sns + csStr + std::to_string((long long int)ackNack) + tempStr;\n\n strcpy(packet, packetString.c_str());\n return packet;\n }\n \/\/Getter Methods\n int Packet::getSequenceNum(){\n return sequenceNum;\n }\n \n int Packet::getCheckSum(){\n return checkSum;\n }\n\n int Packet::getAckNack(){\n return ackNack;\n }\n bool Packet::chksm() {\n return (checkSum) == generateCheckSum();\n }\n int Packet::generateCheckSum() {\n int cs = 0;\n if(dataBuff == NULL){\n return -1;\n }\n \n for(int x = 0; x < sizeof(dataBuff); x++) {\n if(dataBuff[x] == '\\0') {\n x = sizeof(dataBuff);\n break;\n }\n cs += dataBuff[x];\n }\n\n if(cs <= 9999) cs *= 10;\n\n if(cs > 0) return cs;\n return -1;\n }\n<|endoftext|>"} {"text":"#include \r\n\r\nint\r\nsumMultiples(){\r\n\tint z = 0;\r\n\tfor (int i = 1; i <= 1000; i++) {\r\n\t\tif ((i % 3 == 0) || (i % 5 == 0)) {\r\n\t\t\tz = i + z;\r\n\t\t\tstd::cout << z << std::endl;\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nint\r\nmain() {\r\n\tchar w;\r\n\tint z = 0;\r\n\r\n\tsumMultiples();\r\n\r\n\r\n\tstd::cin >> w;\r\n\treturn 0;\r\n};Update helloworld.cpp#include \r\n\r\nint\r\nsumMultiples(){\r\n\tint z = 0;\r\n\tfor (int i = 1; i <= 1000; i++) {\r\n\t\tif ((i % 3 == 0) || (i % 5 == 0)) {\r\n\t\t\tz = i + z;\r\n\t\t\tstd::cout << z << std::endl;\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nint\r\nmain() {\r\n\tchar w;\r\n\tint z = 0;\r\n\r\n\tsumMultiples();\r\n\r\n\r\n\tstd::cin >> w; \/\/auf Windows programmiert, Konsole soll sich nicht schließen\r\n\treturn 0;\r\n};\r\n<|endoftext|>"} {"text":"\/\/ \n\/\/ This file is part of MipTknzr Library Project\n\/\/ Copyright (c) Antonino Calderone (antonino.calderone@gmail.com)\n\/\/ All rights reserved. \n\/\/ Licensed under the MIT License. \n\/\/ See COPYING file in the project root for full license information.\n\/\/\n\n\n\/* -------------------------------------------------------------------------- *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef _UNICODE\n#include \n#include \n#include \n#endif\n\n#include \"mip_json_obj.h\"\n#include \"mip_json_parser.h\"\n\n\n\/* -------------------------------------------------------------------------- *\/\n\nint main(int argc, mip::char_t* argv[])\n{\n if (argc<2) {\n std::_cerr << _T(\"File name missing\") << std::endl;\n return 1;\n }\n\n mip::json_parser_t parser(& std::_cout);\n\n const mip::char_t* filename = argv[1];\n\n mip::_ifstream is(filename, std::ios::in | std::ios::binary);\n\n if (!is.is_open()) {\n std::_cerr << _T(\"Cannot open \") << filename << std::endl;\n return false;\n }\n\n#ifdef _UNICODE\n const std::locale utf16_locale\n = std::locale(\n std::locale(),\n new std::codecvt_utf16<\n wchar_t,\n 0x10ffff,\n std::codecvt_mode(std::little_endian | std::consume_header)>());\n\n is.imbue(utf16_locale);\n#endif\n\n if (!is.is_open() || is.bad()) {\n std::cerr << _T(\"error reading the input stream\");\n return false;\n }\n \n std::_cout << _T(\"Parsing ...\") << std::endl << std::endl;\n\n mip::_stringstream errlog;\n auto res = parser.parse(is, errlog);\n\n std::_cout \n << std::endl << std::endl \n << _T(\"...done\") \n << std::endl << std::endl;\n\n if (! res.first) {\n std::_cerr \n << std::endl \n << _T(\"JSON text is Invalid: \") \n << errlog.str()\n << std::endl;\n return 1;\n }\n\n std::_cout \n << std::endl \n << std::endl \n << _T(\"JSON is Valid\") \n << std::endl \n << std::endl;\n\n std::_cout \n << _T(\"Compact representation\")\n << std::endl \n << std::endl;\n\n if (res.second) {\n std::_cout \n << *res.second \n << std::endl;\n }\n else {\n std::_cout << _T(\"null\") << std::endl;\n }\n\n\n return 0;\n}\nUpdate jsonvalid.cc\/\/ \n\/\/ This file is part of MipTknzr Library Project\n\/\/ Copyright (c) Antonino Calderone (antonino.calderone@gmail.com)\n\/\/ All rights reserved. \n\/\/ Licensed under the MIT License. \n\/\/ See COPYING file in the project root for full license information.\n\/\/\n\n\n\/* -------------------------------------------------------------------------- *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef _UNICODE\n#include \n#include \n#include \n#endif\n\n#include \"mip_json_obj.h\"\n#include \"mip_json_parser.h\"\n\n\n\/* -------------------------------------------------------------------------- *\/\n\nint main(int argc, mip::char_t* argv[])\n{\n if (argc<2) {\n std::_cerr << _T(\"File name missing\") << std::endl;\n return 1;\n }\n\n mip::json_parser_t parser(& std::_cout);\n\n const mip::char_t* filename = argv[1];\n\n mip::_ifstream is(filename, std::ios::in | std::ios::binary);\n\n if (!is.is_open()) {\n std::_cerr << _T(\"Cannot open \") << filename << std::endl;\n return false;\n }\n\n#ifdef _UNICODE\n const std::locale utf16_locale\n = std::locale(\n std::locale(),\n new std::codecvt_utf16<\n wchar_t,\n 0x10ffff,\n std::codecvt_mode(std::little_endian | std::consume_header)>());\n\n is.imbue(utf16_locale);\n#endif\n\n if (!is.is_open() || is.bad()) {\n std::cerr << _T(\"error reading the input stream\");\n return 1;\n }\n \n std::_cout << _T(\"Parsing ...\") << std::endl << std::endl;\n\n mip::_stringstream errlog;\n auto res = parser.parse(is, errlog);\n\n std::_cout \n << std::endl << std::endl \n << _T(\"...done\") \n << std::endl << std::endl;\n\n if (! res.first) {\n std::_cerr \n << std::endl \n << _T(\"JSON text is Invalid: \") \n << errlog.str()\n << std::endl;\n return 1;\n }\n\n std::_cout \n << std::endl \n << std::endl \n << _T(\"JSON is Valid\") \n << std::endl \n << std::endl;\n\n std::_cout \n << _T(\"Compact representation\")\n << std::endl \n << std::endl;\n\n if (res.second) {\n std::_cout \n << *res.second \n << std::endl;\n }\n else {\n std::_cout << _T(\"null\") << std::endl;\n }\n\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n\nnamespace izenelib{\nnamespace util{\n\nclass TimerThread\n{\npublic:\n TimerThread(uint32_t due_time, uint32_t interval,\n const Timer::TimerCBType& cb)\n : due_time_(due_time),\n interval_(interval),\n callback_(cb),\n stop_(false)\n {\n thread_.reset(new boost::thread(boost::bind(&TimerThread::run, this)));\n }\n\n ~TimerThread() \n {\n }\n\n void stop(bool wait = false)\n {\n {\n boost::mutex::scoped_lock lock(mutex_);\n stop_ = true;\n cond_.notify_all();\n }\n if (!wait)\n return;\n if (boost::this_thread::get_id() == thread_->get_id())\n {\n return;\n }\n thread_->join();\n }\n\n void run()\n {\n {\n boost::mutex::scoped_lock lock(mutex_);\n cond_.timed_wait(lock,boost::get_system_time() + boost::posix_time::milliseconds(due_time_));\n if (stop_)\n {\n callback_ = NULL;\n return;\n }\n }\n\n callback_();\n\n if (interval_ == 0)\n {\n callback_ = NULL;\n return;\n }\n else\n {\n while (!stop_)\n {\n {\n boost::mutex::scoped_lock lock(mutex_);\n cond_.timed_wait(lock,boost::get_system_time() +\n boost::posix_time::milliseconds(interval_));\n if (stop_)\n {\n callback_ = NULL;\n return;\n }\n }\n \n callback_();\n }\n }\n callback_ = NULL;\n }\n\nprivate:\n boost::scoped_ptr thread_;\n uint32_t due_time_;\n uint32_t interval_;\n Timer::TimerCBType callback_;\n bool stop_;\n boost::condition_variable cond_;\n boost::mutex mutex_;\n};\n\nbool Timer::start(uint32_t due_time, uint32_t interval, const TimerCBType& cb)\n{\n if (timer_thread_ || cb == NULL)\n {\n \/\/ can not start timer twice or without timer callback.\n return false;\n }\n timer_thread_.reset(new TimerThread(due_time, interval, cb));\n return true;\n}\n\nvoid Timer::stop(bool wait)\n{\n if (!timer_thread_)\n {\n return;\n }\n timer_thread_->stop(wait);\n}\n\nTimer::Timer() {}\n\nTimer::~Timer()\n{\n}\n\n}\n}\nwait until timer thread exit, or maybe invalid memory access.#include \n\n#include \n\nnamespace izenelib{\nnamespace util{\n\nclass TimerThread\n{\npublic:\n TimerThread(uint32_t due_time, uint32_t interval,\n const Timer::TimerCBType& cb)\n : due_time_(due_time),\n interval_(interval),\n callback_(cb),\n stop_(false)\n {\n thread_.reset(new boost::thread(boost::bind(&TimerThread::run, this)));\n }\n\n ~TimerThread() \n {\n stop(true);\n }\n\n void stop(bool wait = false)\n {\n {\n boost::mutex::scoped_lock lock(mutex_);\n stop_ = true;\n cond_.notify_all();\n }\n if (!wait)\n return;\n if (boost::this_thread::get_id() == thread_->get_id())\n {\n return;\n }\n try{\n thread_->join();\n }catch(const std::exception& e)\n {\n std::cerr << \"join timer thread error: \" << e.what() << std::endl; \n }\n }\n\n void run()\n {\n {\n boost::mutex::scoped_lock lock(mutex_);\n cond_.timed_wait(lock,boost::get_system_time() + boost::posix_time::milliseconds(due_time_));\n if (stop_)\n {\n callback_ = NULL;\n return;\n }\n }\n\n callback_();\n\n if (interval_ == 0)\n {\n callback_ = NULL;\n return;\n }\n else\n {\n while (!stop_)\n {\n {\n boost::mutex::scoped_lock lock(mutex_);\n cond_.timed_wait(lock,boost::get_system_time() +\n boost::posix_time::milliseconds(interval_));\n if (stop_)\n {\n callback_ = NULL;\n return;\n }\n }\n \n callback_();\n }\n }\n callback_ = NULL;\n }\n\nprivate:\n boost::scoped_ptr thread_;\n uint32_t due_time_;\n uint32_t interval_;\n Timer::TimerCBType callback_;\n bool stop_;\n boost::condition_variable cond_;\n boost::mutex mutex_;\n};\n\nbool Timer::start(uint32_t due_time, uint32_t interval, const TimerCBType& cb)\n{\n if (timer_thread_ || cb == NULL)\n {\n \/\/ can not start timer twice or without timer callback.\n return false;\n }\n timer_thread_.reset(new TimerThread(due_time, interval, cb));\n return true;\n}\n\nvoid Timer::stop(bool wait)\n{\n if (!timer_thread_)\n {\n return;\n }\n timer_thread_->stop(wait);\n}\n\nTimer::Timer() {}\n\nTimer::~Timer()\n{\n}\n\n}\n}\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright (c) 2013-2020 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n\/*!\n * \\file string.hpp\n * \\brief Contains string manipulation functions.\n *\/\n\n#ifndef CPP_UTILS_STRING_HPP\n#define CPP_UTILS_STRING_HPP\n\n#include \n#include \n\nnamespace cpp {\n\n\/*!\n * \\brief Left trim the given string. \n * \\param s The string to modify\n * \\return a reference to the string (s)\n *\n * All the spaces on the left of the string will be removed.\n *\/\ntemplate \nstd::basic_string& ltrim(std::basic_string& s) {\n s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun(std::isspace))));\n return s;\n}\n\n\/*!\n * \\brief Right trim the given string. \n * \\param s The string to modify\n * \\return a reference to the string (s)\n *\n * All the spaces on the right of the string will be removed.\n *\/\ntemplate \nstd::basic_string& rtrim(std::basic_string& s) {\n s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun(std::isspace))).base(), s.end());\n return s;\n}\n\n\/*!\n * \\brief Trim the given string. \n * \\param s The string to modify\n * \\return a reference to the string (s)\n *\n * All the spaces on the left and the right of the string will be removed.\n *\/\ntemplate \nstd::basic_string& trim(std::basic_string& s) {\n return ltrim(rtrim(s));\n}\n\n} \/\/end of the cpp namespace\n\n#endif \/\/CPP_UTILS_STRING_HPP\nFixes for C++17 (#1)\/\/=======================================================================\n\/\/ Copyright (c) 2013-2020 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n\/*!\n * \\file string.hpp\n * \\brief Contains string manipulation functions.\n *\/\n\n#ifndef CPP_UTILS_STRING_HPP\n#define CPP_UTILS_STRING_HPP\n\n#include \n#include \n\nnamespace cpp {\n\n\/*!\n * \\brief Left trim the given string. \n * \\param s The string to modify\n * \\return a reference to the string (s)\n *\n * All the spaces on the left of the string will be removed.\n *\/\ntemplate \nstd::basic_string& ltrim(std::basic_string& s) {\n s.erase(s.begin(), std::find_if(s.begin(), s.end(),\n\t\t\t\t\t\t\t\t\t[](CharT c) {\n\t\t\t\t\t\t\t\t\t\treturn !std::isspace(c);\n\t\t\t\t\t\t\t\t\t}));\n return s;\n}\n\n\/*!\n * \\brief Right trim the given string. \n * \\param s The string to modify\n * \\return a reference to the string (s)\n *\n * All the spaces on the right of the string will be removed.\n *\/\ntemplate \nstd::basic_string& rtrim(std::basic_string& s) {\n s.erase(std::find_if(s.rbegin(), s.rend(),\n\t\t\t\t\t\t [](CharT c) {\n\t\t\t\t\t\t\t return !std::isspace(c);\n\t\t\t\t\t\t }).base(), s.end());\n return s;\n}\n\n\/*!\n * \\brief Trim the given string. \n * \\param s The string to modify\n * \\return a reference to the string (s)\n *\n * All the spaces on the left and the right of the string will be removed.\n *\/\ntemplate \nstd::basic_string& trim(std::basic_string& s) {\n return ltrim(rtrim(s));\n}\n\n} \/\/end of the cpp namespace\n\n#endif \/\/CPP_UTILS_STRING_HPP\n<|endoftext|>"} {"text":"\/\/\n\/\/ main.cpp\n\/\/ ResumeBuilder\n\/\/\n\/\/ Created by Terry Black on 9\/17\/15.\n\n\n#include \n#include \nusing std::string;\nusing namespace std;\n\n\nint NumOfGoals;\nint NumOfSkills;\nint NumOfAwards;\nint NumOfJobs;\nint NumOfDegrees;\nstring Age;\nstring PhoneNumber;\nstring SchoolName;\nstring Major;\nstring Concentration;\nstring Minor;\nstring GradDate;\nstring CommunityInvolvement;\nstring Name;\nstring Address;\nstring Email;\nstring Credentials;\nbool MajorBool;\nbool MinorBool;\nbool GradDateBool;\n\n\n\n\nint main() {\n \n cout << \"Hello, Welcome to Resume Builder!\\n\";\n cout << \"Input your name:\\n\";\n getline (cin, Name);\n cout << \"How old are you?\\n\";\n getline (cin, Age);\n cout << \"What is your Address?\\n\";\n getline (cin, Address);\n cout << \"What is your Phone Number?\\n\";\n getline (cin, PhoneNumber);\n cout << \"What is your email?\\n\";\n getline (cin, Email);\n cout << \"What is the name of your School?\\n\";\n getline (cin, SchoolName);\n cout << \"What is your Major? If you don't have one, type: 'none'\\n\";\n getline (cin, Major);\n if (Major == \"none\") {\n MajorBool = false;\n }else {\n MajorBool = true;\n }\n cout << \"What is your Minor? If you don't have one, type 'none'\\n\";\n getline (cin, Minor);\n if (Minor == \"none\") {\n MinorBool = false;\n } else {\n MinorBool = true;\n }\n cout << \"What is your graduation date? If you are still enrolled or something, type: 'none'\\n\";\n getline (cin, GradDate);\n if (GradDate == \"none\") {\n GradDateBool = false;\n } else {\n GradDateBool = true;\n }\n cout << \"How many degrees do you have?\\n\";\n cin >> numOfDegrees;\n \n \n \n \n \n return 0;\n}\n\nUpdate ResumeBuilder.cpp\/\/\n\/\/ main.cpp\n\/\/ ResumeBuilder\n\/\/\n\/\/ Created by Terry Black on 9\/17\/15.\n\n\n#include \nusing namespace std;\n\n\nint numOfGoals;\nint numOfSkills;\nint numOfAwards;\nint numOfJobs;\nint numOfDegrees;\nstring age;\nstring phoneNumber;\nstring schoolName;\nstring major;\nstring concentration;\nstring minor;\nstring gradDate;\nstring communityInvolvement;\nstring name;\nstring address;\nstring email;\nstring credentials;\nbool majorBool;\nbool minorBool;\nbool gradDateBool;\n\n\n\n\nint main() {\n \n cout << \"Hello, Welcome to Resume Builder!\\n\";\n cout << \"Input your name:\\n\";\n getline (cin, Name);\n cout << \"How old are you?\\n\";\n getline (cin, Age);\n cout << \"What is your Address?\\n\";\n getline (cin, Address);\n cout << \"What is your Phone Number?\\n\";\n getline (cin, PhoneNumber);\n cout << \"What is your email?\\n\";\n getline (cin, Email);\n cout << \"What is the name of your School?\\n\";\n getline (cin, SchoolName);\n cout << \"What is your Major? If you don't have one, type: 'none'\\n\";\n getline (cin, Major);\n if (Major == \"none\") {\n MajorBool = false;\n }else {\n MajorBool = true;\n }\n cout << \"What is your Minor? If you don't have one, type 'none'\\n\";\n getline (cin, Minor);\n if (Minor == \"none\") {\n MinorBool = false;\n } else {\n MinorBool = true;\n }\n cout << \"What is your graduation date? If you are still enrolled or something, type: 'none'\\n\";\n getline (cin, GradDate);\n if (GradDate == \"none\") {\n GradDateBool = false;\n } else {\n GradDateBool = true;\n }\n cout << \"How many degrees do you have?\\n\";\n cin >> numOfDegrees;\n \n \n \n \n \n return 0;\n}\n\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ \\file AddTaskPiLam.C\n\/\/\/ \\author Andrew Kubera, Ohio State University, andrew.kubera@cern.ch\n\/\/\/\n\n\/\/\/\n\/\/\/ \\brief Adds an AliAnalysisTaskFemto analysis object to the global\n\/\/\/ AliAnalysisManager.\n\/\/\/\n\/\/\/ This macro creates and returns an AliAnalysisTaskFemto object. The task\n\/\/\/ is given the config macro \"Train\/PionLambdaFemto\/ConfigFemtoAnalysis.C\"\n\/\/\/ which is run to create the analysis objects. This is fixed (for now), and\n\/\/\/ if an alternative is required, you should use the general AddTaskFemto.C\n\/\/\/ macro.\n\/\/\/\n\/\/\/ Subwagons are supported, the name of which will be appended to the task\n\/\/\/ name. The task name by default is \"TaskPiLamFemto\" which cannot be changed.\n\/\/\/\n\/\/\/ The output container name is fixed at the standard \"femtolist\".\n\/\/\/\n\/\/\/ \\param params A string forwarded to the ConfigFemtoAnalysis macro for\n\/\/\/ parsing. This string is wrapped in double-quotes so escaping\n\/\/\/ some to ensure results is a string is unneccessary.\n\/\/\/\n\/\/\/ \\param maco_filename The path to the femto-confuration macro, passed to the\n\/\/\/ created TaskFemto. If this parameter has no '\/' characters,\n\/\/\/ and the subwagon_suffix is empty, this is reinterpreted\n\/\/\/ as the subwagon_suffix.\n\/\/\/\n\/\/\/ \\param subwagon_suffix If this macro is run in a train with subwagons, this\n\/\/\/ will be set with the identifier. NOTE: This\n\/\/\/ parameter may be found in the macro_filename\n\/\/\/ variable as the suffix is simply the last argument\n\/\/\/ passed. To keep from always having to explicitly set\n\/\/\/ the macro_filename if using the default, this code\n\/\/\/ will switch the two parameters if there is no '\/'\n\/\/\/ characters in the macro_filename. As such, keep '\/'\n\/\/\/ out of the subwagon_suffix!\n\/\/\/\nAliAnalysisTaskFemto* AddTaskPiLam(TString params,\n TString macro_filename=\"\",\n TString subwagon_suffix=\"\")\n{ \/\/ Adds a Pion-Lambda Femtoscopy task to the manager\n\n const TString DEFAULT_MACRO = \"$ALICE_PHYSICS\/PWGCF\/FEMTOSCOPY\/macros\/Train\/PionLambdaFemto\/ConfigFemtoAnalysis.C\";\n\n \/\/ Get the global manager\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n Error(\"AddTaskPiLam\", \"Could not get the global AliAnalysisManager.\");\n return NULL;\n }\n\n const TString default_name = \"TaskPiLamFemto\";\n\n \/\/ If the macro_filename was set, use it, else use the default\n if (macro_filename == \"\") {\n macro_filename = DEFAULT_MACRO;\n }\n \/\/ If subwagon_suffix was not set and there are no '\/' characters in the\n \/\/ macro's path, interpret path as the subwagon_suffix and set default path\n if (subwagon_suffix == \"\" && !macro_filename.Contains(\"\/\")) {\n subwagon_suffix = macro_filename;\n macro_filename = DEFAULT_MACRO;\n }\n\n \/\/ build analysis name out of provided suffix\n const TString task_name = (subwagon_suffix == \"\")\n ? default_name\n : TString::Format(\"%s_%s\", default_name, subwagon_suffix);\n\n cout << \"[AddTaskPiLam]\\n\";\n cout << \" macro: '\" << macro_filename << \"'\\n\";\n cout << \" params: '\" << params << \"'\\n\";\n\n \/\/ The analysis config macro for PionLambdaFemto accepts a single string\n \/\/ argument, which it interprets.\n \/\/ This line escapes some escapable characters (backslash, newline, tab)\n \/\/ and wraps that string in double quotes, ensuring that the interpreter\n \/\/ reads a string when passing to the macro.\n const TString analysis_params = '\"' + params.ReplaceAll(\"\\\\\", \"\\\\\\\\\")\n .ReplaceAll(\"\\n\", \"\\\\n\")\n .ReplaceAll(\"\\t\", \"\\\\t\") + '\"';\n\n AliAnalysisTaskFemto *taskfemto = new AliAnalysisTaskFemto(\n task_name,\n macro_filename,\n analysis_params,\n kFALSE\n );\n\n mgr->AddTask(taskfemto);\n\n const char *filename = AliAnalysisManager::GetCommonFileName();\n const TString outputfile = TString::Format(\"%s:%s\", filename, \"PWG2FEMTO\");\n\n AliAnalysisDataContainer *cout_femto = mgr->CreateContainer(\"femtolist\",\n TList::Class(),\n AliAnalysisManager::kOutputContainer,\n outputfile);\n\n \/\/ connect task to the containers\n mgr->ConnectInput(taskfemto, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(taskfemto, 0, cout_femto);\n\n \/\/ Return the task pointer\n return taskfemto;\n}\nPWGCF: PionPionAnalysis - Macro options for output filename and ROOT subdir.\/\/\/\n\/\/\/ \\file AddTaskPiLam.C\n\/\/\/ \\author Andrew Kubera, Ohio State University, andrew.kubera@cern.ch\n\/\/\/\n\n\/\/\/\n\/\/\/ \\brief Adds an AliAnalysisTaskFemto analysis object to the global\n\/\/\/ AliAnalysisManager.\n\/\/\/\n\/\/\/ This macro creates and returns an AliAnalysisTaskFemto object. The task\n\/\/\/ is given the config macro \"Train\/PionLambdaFemto\/ConfigFemtoAnalysis.C\"\n\/\/\/ which is run to create the analysis objects. This is fixed (for now), and\n\/\/\/ if an alternative is required, you should use the general AddTaskFemto.C\n\/\/\/ macro.\n\/\/\/\n\/\/\/ Subwagons are supported, the name of which will be appended to the task\n\/\/\/ name. The task name by default is \"TaskPiLamFemto\" which cannot be changed.\n\/\/\/\n\/\/\/ The output container name is fixed at the standard \"femtolist\".\n\/\/\/\n\/\/\/ \\param params A string forwarded to the ConfigFemtoAnalysis macro for\n\/\/\/ parsing. This string is wrapped in double-quotes so escaping\n\/\/\/ some to ensure results is a string is unneccessary.\n\/\/\/\n\/\/\/ \\param maco_filename The path to the femto-confuration macro, passed to the\n\/\/\/ created TaskFemto. If this parameter has no '\/' characters,\n\/\/\/ and the subwagon_suffix is empty, this is reinterpreted\n\/\/\/ as the subwagon_suffix.\n\/\/\/\n\/\/\/ \\param subwagon_suffix If this macro is run in a train with subwagons, this\n\/\/\/ will be set with the identifier. NOTE: This\n\/\/\/ parameter may be found in the macro_filename\n\/\/\/ variable as the suffix is simply the last argument\n\/\/\/ passed. To keep from always having to explicitly set\n\/\/\/ the macro_filename if using the default, this code\n\/\/\/ will switch the two parameters if there is no '\/'\n\/\/\/ characters in the macro_filename. As such, keep '\/'\n\/\/\/ out of the subwagon_suffix!\n\/\/\/\nAliAnalysisTaskFemto* AddTaskPiLam(TString params,\n TString macro_filename=\"\",\n TString output_filename=\"\",\n TString output_container=\"PWG2FEMTO\",\n TString subwagon_suffix=\"\")\n{ \/\/ Adds a Pion-Lambda Femtoscopy task to the manager\n\n const TString DEFAULT_MACRO = \"$ALICE_PHYSICS\/PWGCF\/FEMTOSCOPY\/macros\/Train\/PionLambdaFemto\/ConfigFemtoAnalysis.C\";\n\n \/\/ Get the global manager\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n Error(\"AddTaskPiLam\", \"Could not get the global AliAnalysisManager.\");\n return NULL;\n }\n\n const TString default_name = \"TaskPiLamFemto\";\n\n \/\/ If the macro_filename was set, use it, else use the default\n if (macro_filename == \"\") {\n macro_filename = DEFAULT_MACRO;\n }\n \/\/ If subwagon_suffix was not set and there are no '\/' characters in the\n \/\/ macro's path, interpret path as the subwagon_suffix and set default path\n if (subwagon_suffix == \"\" && !macro_filename.Contains(\"\/\")) {\n subwagon_suffix = macro_filename;\n macro_filename = DEFAULT_MACRO;\n }\n\n \/\/ build analysis name out of provided suffix\n const TString task_name = (subwagon_suffix == \"\")\n ? default_name\n : TString::Format(\"%s_%s\", default_name, subwagon_suffix);\n\n cout << \"[AddTaskPiLam]\\n\";\n cout << \" macro: '\" << macro_filename << \"'\\n\";\n cout << \" params: '\" << params << \"'\\n\";\n\n \/\/ The analysis config macro for PionLambdaFemto accepts a single string\n \/\/ argument, which it interprets.\n \/\/ This line escapes some escapable characters (backslash, newline, tab)\n \/\/ and wraps that string in double quotes, ensuring that the interpreter\n \/\/ reads a string when passing to the macro.\n const TString analysis_params = '\"' + params.ReplaceAll(\"\\\\\", \"\\\\\\\\\")\n .ReplaceAll(\"\\n\", \"\\\\n\")\n .ReplaceAll(\"\\t\", \"\\\\t\") + '\"';\n\n AliAnalysisTaskFemto *taskfemto = new AliAnalysisTaskFemto(\n task_name,\n macro_filename,\n analysis_params,\n kFALSE\n );\n\n mgr->AddTask(taskfemto);\n\n if (output_filename == \"\") {\n output_filename = AliAnalysisManager::GetCommonFileName();\n }\n\n const TString outputfile = TString::Format(\"%s:%s\", output_filename.Data(), output_container.Data());\n\n AliAnalysisDataContainer *cout_femto = mgr->CreateContainer(\"femtolist\",\n TList::Class(),\n AliAnalysisManager::kOutputContainer,\n outputfile);\n\n \/\/ connect task to the containers\n mgr->ConnectInput(taskfemto, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(taskfemto, 0, cout_femto);\n\n \/\/ Return the task pointer\n return taskfemto;\n}\n<|endoftext|>"} {"text":"AliXiStar *AddTaskXiStar(bool MCcase=kFALSE, bool AODcase=kFALSE, int CutList=0) {\n \n \/\/===========================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskBF\", \"No analysis manager to connect to.\");\n return NULL;\n }\n \n \/\/____________________________________________\/\/\n \/\/ Create tasks\n AliXiStar *XiStarTask = new AliXiStar(\"XiStarTask\", AODcase, MCcase, CutList);\n if(!XiStarTask) exit(-1);\n mgr->AddTask(XiStarTask);\n\n\n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n outputFileName += \":PWGLF.outputXiStarAnalysis.root\";\n AliAnalysisDataContainer *coutXiStar = mgr->CreateContainer(\"XiStarOutput\", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());\n mgr->ConnectInput(XiStarTask, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(XiStarTask, 1, coutXiStar);\n \n\n \/\/ Add Physics Selection \n gROOT->LoadMacro(\"$ALICE_ROOT\/ANALYSIS\/macros\/AddTaskPhysicsSelection.C\");\n AliPhysicsSelectionTask* physSelTask = AddTaskPhysicsSelection(MCcase);\n mgr->ConnectInput(physSelTask,0,mgr->GetCommonInputContainer());\n \n \/\/ Return the task pointer\n return XiStarTask;\n}\nFix in AddTaskXiStar to remove physics selection (not needed)AliXiStar *AddTaskXiStar(bool MCcase=kFALSE, bool AODcase=kFALSE, int CutList=0) {\n \n \/\/===========================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskBF\", \"No analysis manager to connect to.\");\n return NULL;\n }\n \n \/\/____________________________________________\/\/\n \/\/ Create tasks\n AliXiStar *XiStarTask = new AliXiStar(\"XiStarTask\", AODcase, MCcase, CutList);\n if(!XiStarTask) exit(-1);\n mgr->AddTask(XiStarTask);\n\n\n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n outputFileName += \":PWGLF.outputXiStarAnalysis.root\";\n AliAnalysisDataContainer *coutXiStar = mgr->CreateContainer(\"XiStarOutput\", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());\n mgr->ConnectInput(XiStarTask, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(XiStarTask, 1, coutXiStar);\n \n \n \/\/ Return the task pointer\n return XiStarTask;\n}\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2012-, Open Perception, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\npcl::RobotEyeGrabber::RobotEyeGrabber ()\n : terminate_thread_ (false)\n , signal_point_cloud_size_ (1000)\n , data_port_ (443)\n , sensor_address_ (boost::asio::ip::address_v4::any ())\n{\n point_cloud_signal_ = createSignal ();\n resetPointCloud ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\npcl::RobotEyeGrabber::RobotEyeGrabber (const boost::asio::ip::address& ipAddress, unsigned short port)\n : terminate_thread_ (false)\n , signal_point_cloud_size_ (1000)\n , data_port_ (port)\n , sensor_address_ (ipAddress)\n{\n point_cloud_signal_ = createSignal ();\n resetPointCloud ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\npcl::RobotEyeGrabber::~RobotEyeGrabber () throw ()\n{\n stop ();\n disconnect_all_slots ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string\npcl::RobotEyeGrabber::getName () const\n{\n return (std::string (\"Ocular Robotics RobotEye Grabber\"));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nfloat\npcl::RobotEyeGrabber::getFramesPerSecond () const\n{\n return (0.0f);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\npcl::RobotEyeGrabber::isRunning () const\n{\n return (socket_thread_ != NULL);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nunsigned short\npcl::RobotEyeGrabber::getDataPort () const\n{\n return (data_port_);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::setDataPort (const unsigned short port)\n{\n data_port_ = port;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nconst boost::asio::ip::address&\npcl::RobotEyeGrabber::getSensorAddress () const\n{\n return (sensor_address_);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::setSensorAddress (const boost::asio::ip::address& ipAddress)\n{\n sensor_address_ = ipAddress;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::size_t\npcl::RobotEyeGrabber::getSignalPointCloudSize () const\n{\n return (signal_point_cloud_size_);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::setSignalPointCloudSize (std::size_t numberOfPoints)\n{\n signal_point_cloud_size_ = numberOfPoints;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nboost::shared_ptr >\npcl::RobotEyeGrabber::getPointCloud () const\n{\n return point_cloud_xyzi_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::resetPointCloud ()\n{\n point_cloud_xyzi_.reset (new pcl::PointCloud);\n point_cloud_xyzi_->is_dense = true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::consumerThreadLoop ()\n{\n while (true)\n {\n boost::shared_array data;\n if (!packet_queue_.dequeue (data))\n return;\n\n convertPacketData (data.get(), 464);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::convertPacketData (unsigned char *dataPacket, size_t length)\n{\n const size_t bytesPerPoint = 8;\n const size_t totalPoints = length \/ bytesPerPoint;\n\n for (int i = 0; i < totalPoints; ++i)\n {\n PointXYZI xyzi;\n computeXYZI (xyzi, dataPacket + i*bytesPerPoint);\n\n if (pcl::isFinite(xyzi))\n {\n point_cloud_xyzi_->push_back (xyzi);\n }\n }\n\n\n if (point_cloud_xyzi_->size () > signal_point_cloud_size_)\n {\n if (point_cloud_signal_->num_slots () > 0)\n point_cloud_signal_->operator() (point_cloud_xyzi_);\n\n resetPointCloud ();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::computeXYZI (pcl::PointXYZI& point, unsigned char* pointData)\n{\n uint16_t buffer = 0;\n double az = 0.0;\n double el = 0.0;\n double range = 0.0;\n uint16_t intensity = 0;\n\n buffer = 0x00;\n buffer = pointData[0] << 8;\n buffer |= pointData[1]; \/\/ First 2-byte read will be Azimuth\n az = (buffer \/ 100.0);\n\n buffer = 0x00;\n buffer = pointData[2] << 8;\n buffer |= pointData[3]; \/\/ Second 2-byte read will be Elevation\n el = (signed short int)buffer \/ 100.0;\n\n buffer = 0x00;\n buffer = pointData[4] << 8;\n buffer |= pointData[5]; \/\/ Third 2-byte read will be Range\n range = (signed short int)buffer \/ 100.0;\n\n buffer = 0x00;\n buffer = pointData[6] << 8;\n buffer |= pointData[7]; \/\/ Fourth 2-byte read will be Intensity\n intensity = buffer;\n\n point.x = range * std::cos (el * M_PI\/180) * std::sin (az * M_PI\/180);\n point.y = range * std::cos (el * M_PI\/180) * std::cos (az * M_PI\/180);\n point.z = range * std::sin (el * M_PI\/180);\n point.intensity = intensity;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::socketThreadLoop()\n{\n asyncSocketReceive();\n io_service_.reset();\n io_service_.run();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::asyncSocketReceive()\n{\n \/\/ expecting exactly 464 bytes, using a larger buffer so that if a\n \/\/ larger packet arrives unexpectedly we'll notice it.\n socket_->async_receive_from(boost::asio::buffer(receive_buffer_, 500), sender_endpoint_,\n boost::bind(&RobotEyeGrabber::socketCallback, this,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::socketCallback(const boost::system::error_code&, std::size_t numberOfBytes)\n{\n if (terminate_thread_)\n return;\n\n if (sensor_address_ == boost::asio::ip::address_v4::any ()\n || sensor_address_ == sender_endpoint_.address ())\n {\n if (numberOfBytes == 464)\n {\n unsigned char *dup = new unsigned char[numberOfBytes];\n memcpy (dup, receive_buffer_, numberOfBytes);\n packet_queue_.enqueue (boost::shared_array(dup));\n }\n }\n\n asyncSocketReceive ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::start ()\n{\n if (isRunning ())\n return;\n\n boost::asio::ip::udp::endpoint destinationEndpoint (boost::asio::ip::address_v4::any (), data_port_);\n\n try\n {\n\t socket_.reset (new boost::asio::ip::udp::socket (io_service_, destinationEndpoint));\n }\n catch (std::exception &e)\n {\n\t PCL_ERROR (\"[pcl::RobotEyeGrabber::start] Unable to bind to socket! %s\\n\", e.what ());\n return;\n }\n\n terminate_thread_ = false;\n resetPointCloud ();\n consumer_thread_.reset(new boost::thread (boost::bind (&RobotEyeGrabber::consumerThreadLoop, this)));\n socket_thread_.reset(new boost::thread (boost::bind (&RobotEyeGrabber::socketThreadLoop, this)));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::stop ()\n{\n if (!isRunning ())\n return;\n\n terminate_thread_ = true;\n\n\n socket_->close ();\n io_service_.stop ();\n socket_thread_->join ();\n socket_thread_.reset ();\n socket_.reset();\n\n packet_queue_.stopQueue ();\n consumer_thread_->join ();\n consumer_thread_.reset ();\n}\nFix warnings in io\/robot_eye_grabber.cpp\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2012-, Open Perception, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\npcl::RobotEyeGrabber::RobotEyeGrabber ()\n : terminate_thread_ (false)\n , signal_point_cloud_size_ (1000)\n , data_port_ (443)\n , sensor_address_ (boost::asio::ip::address_v4::any ())\n{\n point_cloud_signal_ = createSignal ();\n resetPointCloud ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\npcl::RobotEyeGrabber::RobotEyeGrabber (const boost::asio::ip::address& ipAddress, unsigned short port)\n : terminate_thread_ (false)\n , signal_point_cloud_size_ (1000)\n , data_port_ (port)\n , sensor_address_ (ipAddress)\n{\n point_cloud_signal_ = createSignal ();\n resetPointCloud ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\npcl::RobotEyeGrabber::~RobotEyeGrabber () throw ()\n{\n stop ();\n disconnect_all_slots ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string\npcl::RobotEyeGrabber::getName () const\n{\n return (std::string (\"Ocular Robotics RobotEye Grabber\"));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nfloat\npcl::RobotEyeGrabber::getFramesPerSecond () const\n{\n return (0.0f);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\npcl::RobotEyeGrabber::isRunning () const\n{\n return (socket_thread_ != NULL);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nunsigned short\npcl::RobotEyeGrabber::getDataPort () const\n{\n return (data_port_);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::setDataPort (const unsigned short port)\n{\n data_port_ = port;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nconst boost::asio::ip::address&\npcl::RobotEyeGrabber::getSensorAddress () const\n{\n return (sensor_address_);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::setSensorAddress (const boost::asio::ip::address& ipAddress)\n{\n sensor_address_ = ipAddress;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::size_t\npcl::RobotEyeGrabber::getSignalPointCloudSize () const\n{\n return (signal_point_cloud_size_);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::setSignalPointCloudSize (std::size_t numberOfPoints)\n{\n signal_point_cloud_size_ = numberOfPoints;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nboost::shared_ptr >\npcl::RobotEyeGrabber::getPointCloud () const\n{\n return point_cloud_xyzi_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::resetPointCloud ()\n{\n point_cloud_xyzi_.reset (new pcl::PointCloud);\n point_cloud_xyzi_->is_dense = true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::consumerThreadLoop ()\n{\n while (true)\n {\n boost::shared_array data;\n if (!packet_queue_.dequeue (data))\n return;\n\n convertPacketData (data.get(), 464);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::convertPacketData (unsigned char *dataPacket, size_t length)\n{\n const size_t bytesPerPoint = 8;\n const size_t totalPoints = length \/ bytesPerPoint;\n\n for (size_t i = 0; i < totalPoints; ++i)\n {\n PointXYZI xyzi;\n computeXYZI (xyzi, dataPacket + i*bytesPerPoint);\n\n if (pcl::isFinite(xyzi))\n {\n point_cloud_xyzi_->push_back (xyzi);\n }\n }\n\n\n if (point_cloud_xyzi_->size () > signal_point_cloud_size_)\n {\n if (point_cloud_signal_->num_slots () > 0)\n point_cloud_signal_->operator() (point_cloud_xyzi_);\n\n resetPointCloud ();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::computeXYZI (pcl::PointXYZI& point, unsigned char* pointData)\n{\n uint16_t buffer = 0;\n double az = 0.0;\n double el = 0.0;\n double range = 0.0;\n uint16_t intensity = 0;\n\n buffer = 0x00;\n buffer = pointData[0] << 8;\n buffer |= pointData[1]; \/\/ First 2-byte read will be Azimuth\n az = (buffer \/ 100.0);\n\n buffer = 0x00;\n buffer = pointData[2] << 8;\n buffer |= pointData[3]; \/\/ Second 2-byte read will be Elevation\n el = (signed short int)buffer \/ 100.0;\n\n buffer = 0x00;\n buffer = pointData[4] << 8;\n buffer |= pointData[5]; \/\/ Third 2-byte read will be Range\n range = (signed short int)buffer \/ 100.0;\n\n buffer = 0x00;\n buffer = pointData[6] << 8;\n buffer |= pointData[7]; \/\/ Fourth 2-byte read will be Intensity\n intensity = buffer;\n\n point.x = range * std::cos (el * M_PI\/180) * std::sin (az * M_PI\/180);\n point.y = range * std::cos (el * M_PI\/180) * std::cos (az * M_PI\/180);\n point.z = range * std::sin (el * M_PI\/180);\n point.intensity = intensity;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::socketThreadLoop()\n{\n asyncSocketReceive();\n io_service_.reset();\n io_service_.run();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::asyncSocketReceive()\n{\n \/\/ expecting exactly 464 bytes, using a larger buffer so that if a\n \/\/ larger packet arrives unexpectedly we'll notice it.\n socket_->async_receive_from(boost::asio::buffer(receive_buffer_, 500), sender_endpoint_,\n boost::bind(&RobotEyeGrabber::socketCallback, this,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::socketCallback(const boost::system::error_code&, std::size_t numberOfBytes)\n{\n if (terminate_thread_)\n return;\n\n if (sensor_address_ == boost::asio::ip::address_v4::any ()\n || sensor_address_ == sender_endpoint_.address ())\n {\n if (numberOfBytes == 464)\n {\n unsigned char *dup = new unsigned char[numberOfBytes];\n memcpy (dup, receive_buffer_, numberOfBytes);\n packet_queue_.enqueue (boost::shared_array(dup));\n }\n }\n\n asyncSocketReceive ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::start ()\n{\n if (isRunning ())\n return;\n\n boost::asio::ip::udp::endpoint destinationEndpoint (boost::asio::ip::address_v4::any (), data_port_);\n\n try\n {\n\t socket_.reset (new boost::asio::ip::udp::socket (io_service_, destinationEndpoint));\n }\n catch (std::exception &e)\n {\n\t PCL_ERROR (\"[pcl::RobotEyeGrabber::start] Unable to bind to socket! %s\\n\", e.what ());\n return;\n }\n\n terminate_thread_ = false;\n resetPointCloud ();\n consumer_thread_.reset(new boost::thread (boost::bind (&RobotEyeGrabber::consumerThreadLoop, this)));\n socket_thread_.reset(new boost::thread (boost::bind (&RobotEyeGrabber::socketThreadLoop, this)));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::RobotEyeGrabber::stop ()\n{\n if (!isRunning ())\n return;\n\n terminate_thread_ = true;\n\n\n socket_->close ();\n io_service_.stop ();\n socket_thread_->join ();\n socket_thread_.reset ();\n socket_.reset();\n\n packet_queue_.stopQueue ();\n consumer_thread_->join ();\n consumer_thread_.reset ();\n}\n<|endoftext|>"} {"text":"\/** @file\n\n A brief file description\n\n @section license License\n\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n\/****************************************************************************\n\n OneWayTunnel.cc\n\n A OneWayTunnel is a module that connects two virtual connections, a\n source vc and a target vc, and copies the data between source and target.\n\n This class used to be called HttpTunnelVC, but it doesn't seem to have\n anything to do with HTTP, so it has been renamed to OneWayTunnel.\n ****************************************************************************\/\n\n#include \"P_EventSystem.h\"\n#include \"I_OneWayTunnel.h\"\n\n\/\/ #define TEST\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ OneWayTunnel::OneWayTunnel()\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nClassAllocator OneWayTunnelAllocator(\"OneWayTunnelAllocator\");\n\ninline void\ntransfer_data(MIOBufferAccessor &in_buf, MIOBufferAccessor &out_buf)\n{\n ink_release_assert(!\"Not Implemented.\");\n\n int64_t n = in_buf.reader()->read_avail();\n int64_t o = out_buf.writer()->write_avail();\n\n if (n > o)\n n = o;\n if (!n)\n return;\n memcpy(in_buf.reader()->start(), out_buf.writer()->end(), n);\n in_buf.reader()->consume(n);\n out_buf.writer()->fill(n);\n}\n\nOneWayTunnel::OneWayTunnel()\n : Continuation(nullptr),\n vioSource(nullptr),\n vioTarget(nullptr),\n cont(nullptr),\n manipulate_fn(nullptr),\n n_connections(0),\n lerrno(0),\n single_buffer(false),\n close_source(false),\n close_target(false),\n tunnel_till_done(false),\n tunnel_peer(nullptr),\n free_vcs(true)\n{\n}\n\nOneWayTunnel *\nOneWayTunnel::OneWayTunnel_alloc()\n{\n return OneWayTunnelAllocator.alloc();\n}\n\nvoid\nOneWayTunnel::OneWayTunnel_free(OneWayTunnel *pOWT)\n{\n pOWT->mutex = nullptr;\n OneWayTunnelAllocator.free(pOWT);\n}\n\nvoid\nOneWayTunnel::SetupTwoWayTunnel(OneWayTunnel *east, OneWayTunnel *west)\n{\n \/\/ make sure the both use the same mutex\n ink_assert(east->mutex == west->mutex);\n\n east->tunnel_peer = west;\n west->tunnel_peer = east;\n}\n\nOneWayTunnel::~OneWayTunnel()\n{\n}\n\nOneWayTunnel::OneWayTunnel(Continuation *aCont, Transform_fn aManipulate_fn, bool aclose_source, bool aclose_target)\n : Continuation(aCont ? aCont->mutex.get() : new_ProxyMutex()),\n cont(aCont),\n manipulate_fn(aManipulate_fn),\n n_connections(2),\n lerrno(0),\n single_buffer(true),\n close_source(aclose_source),\n close_target(aclose_target),\n tunnel_till_done(false),\n free_vcs(false)\n{\n ink_assert(!\"This form of OneWayTunnel() constructor not supported\");\n}\n\nvoid\nOneWayTunnel::init(VConnection *vcSource, VConnection *vcTarget, Continuation *aCont, int size_estimate, ProxyMutex *aMutex,\n int64_t nbytes, bool asingle_buffer, bool aclose_source, bool aclose_target, Transform_fn aManipulate_fn,\n int water_mark)\n{\n mutex = aCont ? aCont->mutex.get() : (aMutex ? aMutex : new_ProxyMutex());\n cont = aMutex ? nullptr : aCont;\n single_buffer = asingle_buffer;\n manipulate_fn = aManipulate_fn;\n n_connections = 2;\n close_source = aclose_source;\n close_target = aclose_target;\n lerrno = 0;\n tunnel_till_done = (nbytes == TUNNEL_TILL_DONE);\n\n SET_HANDLER(&OneWayTunnel::startEvent);\n\n int64_t size_index = 0;\n\n if (size_estimate)\n size_index = buffer_size_to_index(size_estimate);\n else\n size_index = default_large_iobuffer_size;\n\n Debug(\"one_way_tunnel\", \"buffer size index [%\" PRId64 \"] [%d]\", size_index, size_estimate);\n\n \/\/ enqueue read request on vcSource.\n MIOBuffer *buf1 = new_MIOBuffer(size_index);\n MIOBuffer *buf2 = nullptr;\n if (single_buffer)\n buf2 = buf1;\n else\n buf2 = new_MIOBuffer(size_index);\n\n buf1->water_mark = water_mark;\n\n SCOPED_MUTEX_LOCK(lock, mutex, this_ethread());\n vioSource = vcSource->do_io_read(this, nbytes, buf1);\n vioTarget = vcTarget->do_io_write(this, nbytes, buf2->alloc_reader(), false);\n ink_assert(vioSource && vioTarget);\n\n return;\n}\n\nvoid\nOneWayTunnel::init(VConnection *vcSource, VConnection *vcTarget, Continuation *aCont, VIO *SourceVio, IOBufferReader *reader,\n bool aclose_source, bool aclose_target)\n{\n (void)vcSource;\n mutex = aCont ? aCont->mutex : make_ptr(new_ProxyMutex());\n cont = aCont;\n single_buffer = true;\n manipulate_fn = nullptr;\n n_connections = 2;\n close_source = aclose_source;\n close_target = aclose_target;\n tunnel_till_done = true;\n\n \/\/ Prior to constructing the OneWayTunnel, we initiated a do_io(VIO::READ)\n \/\/ on the source VC. We wish to use the same MIO buffer in the tunnel.\n\n \/\/ do_io() read already posted on vcSource.\n SET_HANDLER(&OneWayTunnel::startEvent);\n\n SourceVio->set_continuation(this);\n SCOPED_MUTEX_LOCK(lock, mutex, this_ethread());\n vioSource = SourceVio;\n\n vioTarget = vcTarget->do_io_write(this, TUNNEL_TILL_DONE, reader, false);\n ink_assert(vioSource && vioTarget);\n}\n\nvoid\nOneWayTunnel::init(Continuation *aCont, VIO *SourceVio, VIO *TargetVio, bool aclose_source, bool aclose_target)\n{\n mutex = aCont ? aCont->mutex : make_ptr(new_ProxyMutex());\n cont = aCont;\n single_buffer = true;\n manipulate_fn = nullptr;\n n_connections = 2;\n close_source = aclose_source;\n close_target = aclose_target;\n tunnel_till_done = true;\n\n \/\/ do_io_read() read already posted on vcSource.\n \/\/ do_io_write() already posted on vcTarget\n SET_HANDLER(&OneWayTunnel::startEvent);\n\n ink_assert(SourceVio && TargetVio);\n\n SourceVio->set_continuation(this);\n TargetVio->set_continuation(this);\n vioSource = SourceVio;\n vioTarget = TargetVio;\n}\n\nvoid\nOneWayTunnel::transform(MIOBufferAccessor &in_buf, MIOBufferAccessor &out_buf)\n{\n if (manipulate_fn)\n manipulate_fn(in_buf, out_buf);\n else if (in_buf.writer() != out_buf.writer())\n transfer_data(in_buf, out_buf);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ int OneWayTunnel::startEvent()\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\n\/\/ tunnel was invoked with an event\n\/\/\nint\nOneWayTunnel::startEvent(int event, void *data)\n{\n VIO *vio = (VIO *)data;\n int ret = VC_EVENT_DONE;\n int result = 0;\n\n#ifdef TEST\n const char *event_origin = (vio == vioSource ? \"source\" : \"target\"), *event_name = get_vc_event_name(event);\n printf(\"OneWayTunnel --- %s received from %s VC\\n\", event_name, event_origin);\n#endif\n\n if (!vioTarget)\n goto Lerror;\n\n \/\/ handle the event\n \/\/\n switch (event) {\n case ONE_WAY_TUNNEL_EVENT_PEER_CLOSE:\n \/* This event is sent out by our peer *\/\n ink_assert(tunnel_peer);\n tunnel_peer = nullptr;\n free_vcs = false;\n goto Ldone;\n\n case VC_EVENT_READ_READY:\n transform(vioSource->buffer, vioTarget->buffer);\n vioTarget->reenable();\n ret = VC_EVENT_CONT;\n break;\n\n case VC_EVENT_WRITE_READY:\n if (vioSource)\n vioSource->reenable();\n ret = VC_EVENT_CONT;\n break;\n\n case VC_EVENT_EOS:\n if (!tunnel_till_done && vio->ntodo())\n goto Lerror;\n if (vio == vioSource) {\n transform(vioSource->buffer, vioTarget->buffer);\n goto Lread_complete;\n } else\n goto Ldone;\n\n Lread_complete:\n case VC_EVENT_READ_COMPLETE:\n \/\/ set write nbytes to the current buffer size\n \/\/\n vioTarget->nbytes = vioTarget->ndone + vioTarget->buffer.reader()->read_avail();\n if (vioTarget->nbytes == vioTarget->ndone)\n goto Ldone;\n vioTarget->reenable();\n if (!tunnel_peer)\n close_source_vio(0);\n break;\n\n Lerror:\n case VC_EVENT_ERROR:\n lerrno = ((VIO *)data)->vc_server->lerrno;\n case VC_EVENT_INACTIVITY_TIMEOUT:\n case VC_EVENT_ACTIVE_TIMEOUT:\n result = -1;\n Ldone:\n case VC_EVENT_WRITE_COMPLETE:\n if (tunnel_peer) {\n \/\/ inform the peer:\n tunnel_peer->startEvent(ONE_WAY_TUNNEL_EVENT_PEER_CLOSE, data);\n }\n close_source_vio(result);\n close_target_vio(result);\n connection_closed(result);\n break;\n\n default:\n ink_assert(!\"bad case\");\n ret = VC_EVENT_CONT;\n break;\n }\n#ifdef TEST\n printf(\" (OneWayTunnel returning value: %s)\\n\", (ret == VC_EVENT_DONE ? \"VC_EVENT_DONE\" : \"VC_EVENT_CONT\"));\n#endif\n return ret;\n}\n\n\/\/ If result is Non-zero, the vc should be aborted.\nvoid\nOneWayTunnel::close_source_vio(int result)\n{\n if (vioSource) {\n if (last_connection() || !single_buffer) {\n free_MIOBuffer(vioSource->buffer.writer());\n vioSource->buffer.clear();\n }\n if (close_source && free_vcs) {\n vioSource->vc_server->do_io_close(result ? lerrno : -1);\n }\n vioSource = nullptr;\n n_connections--;\n }\n}\n\nvoid\nOneWayTunnel::close_target_vio(int result, VIO *vio)\n{\n (void)vio;\n if (vioTarget) {\n if (last_connection() || !single_buffer) {\n free_MIOBuffer(vioTarget->buffer.writer());\n vioTarget->buffer.clear();\n }\n if (close_target && free_vcs) {\n vioTarget->vc_server->do_io_close(result ? lerrno : -1);\n }\n vioTarget = nullptr;\n n_connections--;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ void OneWayTunnel::connection_closed\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nOneWayTunnel::connection_closed(int result)\n{\n if (cont) {\n#ifdef TEST\n cout << \"OneWayTunnel::connection_closed() ... calling cont\" << endl;\n#endif\n cont->handleEvent(result ? VC_EVENT_ERROR : VC_EVENT_EOS, this);\n } else {\n OneWayTunnel_free(this);\n }\n}\n\nvoid\nOneWayTunnel::reenable_all()\n{\n if (vioSource)\n vioSource->reenable();\n if (vioTarget)\n vioTarget->reenable();\n}\n\nbool\nOneWayTunnel::last_connection()\n{\n return n_connections == 1;\n}\ncoverity 1021916 : fix missing break\/** @file\n\n A brief file description\n\n @section license License\n\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n\/****************************************************************************\n\n OneWayTunnel.cc\n\n A OneWayTunnel is a module that connects two virtual connections, a\n source vc and a target vc, and copies the data between source and target.\n\n This class used to be called HttpTunnelVC, but it doesn't seem to have\n anything to do with HTTP, so it has been renamed to OneWayTunnel.\n ****************************************************************************\/\n\n#include \"P_EventSystem.h\"\n#include \"I_OneWayTunnel.h\"\n\n\/\/ #define TEST\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ OneWayTunnel::OneWayTunnel()\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nClassAllocator OneWayTunnelAllocator(\"OneWayTunnelAllocator\");\n\ninline void\ntransfer_data(MIOBufferAccessor &in_buf, MIOBufferAccessor &out_buf)\n{\n ink_release_assert(!\"Not Implemented.\");\n\n int64_t n = in_buf.reader()->read_avail();\n int64_t o = out_buf.writer()->write_avail();\n\n if (n > o)\n n = o;\n if (!n)\n return;\n memcpy(in_buf.reader()->start(), out_buf.writer()->end(), n);\n in_buf.reader()->consume(n);\n out_buf.writer()->fill(n);\n}\n\nOneWayTunnel::OneWayTunnel()\n : Continuation(nullptr),\n vioSource(nullptr),\n vioTarget(nullptr),\n cont(nullptr),\n manipulate_fn(nullptr),\n n_connections(0),\n lerrno(0),\n single_buffer(false),\n close_source(false),\n close_target(false),\n tunnel_till_done(false),\n tunnel_peer(nullptr),\n free_vcs(true)\n{\n}\n\nOneWayTunnel *\nOneWayTunnel::OneWayTunnel_alloc()\n{\n return OneWayTunnelAllocator.alloc();\n}\n\nvoid\nOneWayTunnel::OneWayTunnel_free(OneWayTunnel *pOWT)\n{\n pOWT->mutex = nullptr;\n OneWayTunnelAllocator.free(pOWT);\n}\n\nvoid\nOneWayTunnel::SetupTwoWayTunnel(OneWayTunnel *east, OneWayTunnel *west)\n{\n \/\/ make sure the both use the same mutex\n ink_assert(east->mutex == west->mutex);\n\n east->tunnel_peer = west;\n west->tunnel_peer = east;\n}\n\nOneWayTunnel::~OneWayTunnel()\n{\n}\n\nOneWayTunnel::OneWayTunnel(Continuation *aCont, Transform_fn aManipulate_fn, bool aclose_source, bool aclose_target)\n : Continuation(aCont ? aCont->mutex.get() : new_ProxyMutex()),\n cont(aCont),\n manipulate_fn(aManipulate_fn),\n n_connections(2),\n lerrno(0),\n single_buffer(true),\n close_source(aclose_source),\n close_target(aclose_target),\n tunnel_till_done(false),\n free_vcs(false)\n{\n ink_assert(!\"This form of OneWayTunnel() constructor not supported\");\n}\n\nvoid\nOneWayTunnel::init(VConnection *vcSource, VConnection *vcTarget, Continuation *aCont, int size_estimate, ProxyMutex *aMutex,\n int64_t nbytes, bool asingle_buffer, bool aclose_source, bool aclose_target, Transform_fn aManipulate_fn,\n int water_mark)\n{\n mutex = aCont ? aCont->mutex.get() : (aMutex ? aMutex : new_ProxyMutex());\n cont = aMutex ? nullptr : aCont;\n single_buffer = asingle_buffer;\n manipulate_fn = aManipulate_fn;\n n_connections = 2;\n close_source = aclose_source;\n close_target = aclose_target;\n lerrno = 0;\n tunnel_till_done = (nbytes == TUNNEL_TILL_DONE);\n\n SET_HANDLER(&OneWayTunnel::startEvent);\n\n int64_t size_index = 0;\n\n if (size_estimate)\n size_index = buffer_size_to_index(size_estimate);\n else\n size_index = default_large_iobuffer_size;\n\n Debug(\"one_way_tunnel\", \"buffer size index [%\" PRId64 \"] [%d]\", size_index, size_estimate);\n\n \/\/ enqueue read request on vcSource.\n MIOBuffer *buf1 = new_MIOBuffer(size_index);\n MIOBuffer *buf2 = nullptr;\n if (single_buffer)\n buf2 = buf1;\n else\n buf2 = new_MIOBuffer(size_index);\n\n buf1->water_mark = water_mark;\n\n SCOPED_MUTEX_LOCK(lock, mutex, this_ethread());\n vioSource = vcSource->do_io_read(this, nbytes, buf1);\n vioTarget = vcTarget->do_io_write(this, nbytes, buf2->alloc_reader(), false);\n ink_assert(vioSource && vioTarget);\n\n return;\n}\n\nvoid\nOneWayTunnel::init(VConnection *vcSource, VConnection *vcTarget, Continuation *aCont, VIO *SourceVio, IOBufferReader *reader,\n bool aclose_source, bool aclose_target)\n{\n (void)vcSource;\n mutex = aCont ? aCont->mutex : make_ptr(new_ProxyMutex());\n cont = aCont;\n single_buffer = true;\n manipulate_fn = nullptr;\n n_connections = 2;\n close_source = aclose_source;\n close_target = aclose_target;\n tunnel_till_done = true;\n\n \/\/ Prior to constructing the OneWayTunnel, we initiated a do_io(VIO::READ)\n \/\/ on the source VC. We wish to use the same MIO buffer in the tunnel.\n\n \/\/ do_io() read already posted on vcSource.\n SET_HANDLER(&OneWayTunnel::startEvent);\n\n SourceVio->set_continuation(this);\n SCOPED_MUTEX_LOCK(lock, mutex, this_ethread());\n vioSource = SourceVio;\n\n vioTarget = vcTarget->do_io_write(this, TUNNEL_TILL_DONE, reader, false);\n ink_assert(vioSource && vioTarget);\n}\n\nvoid\nOneWayTunnel::init(Continuation *aCont, VIO *SourceVio, VIO *TargetVio, bool aclose_source, bool aclose_target)\n{\n mutex = aCont ? aCont->mutex : make_ptr(new_ProxyMutex());\n cont = aCont;\n single_buffer = true;\n manipulate_fn = nullptr;\n n_connections = 2;\n close_source = aclose_source;\n close_target = aclose_target;\n tunnel_till_done = true;\n\n \/\/ do_io_read() read already posted on vcSource.\n \/\/ do_io_write() already posted on vcTarget\n SET_HANDLER(&OneWayTunnel::startEvent);\n\n ink_assert(SourceVio && TargetVio);\n\n SourceVio->set_continuation(this);\n TargetVio->set_continuation(this);\n vioSource = SourceVio;\n vioTarget = TargetVio;\n}\n\nvoid\nOneWayTunnel::transform(MIOBufferAccessor &in_buf, MIOBufferAccessor &out_buf)\n{\n if (manipulate_fn)\n manipulate_fn(in_buf, out_buf);\n else if (in_buf.writer() != out_buf.writer())\n transfer_data(in_buf, out_buf);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ int OneWayTunnel::startEvent()\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\n\/\/ tunnel was invoked with an event\n\/\/\nint\nOneWayTunnel::startEvent(int event, void *data)\n{\n VIO *vio = (VIO *)data;\n int ret = VC_EVENT_DONE;\n int result = 0;\n\n#ifdef TEST\n const char *event_origin = (vio == vioSource ? \"source\" : \"target\"), *event_name = get_vc_event_name(event);\n printf(\"OneWayTunnel --- %s received from %s VC\\n\", event_name, event_origin);\n#endif\n\n if (!vioTarget)\n goto Lerror;\n\n \/\/ handle the event\n \/\/\n switch (event) {\n case ONE_WAY_TUNNEL_EVENT_PEER_CLOSE:\n \/* This event is sent out by our peer *\/\n ink_assert(tunnel_peer);\n tunnel_peer = nullptr;\n free_vcs = false;\n goto Ldone;\n break; \/\/ fix coverity\n\n case VC_EVENT_READ_READY:\n transform(vioSource->buffer, vioTarget->buffer);\n vioTarget->reenable();\n ret = VC_EVENT_CONT;\n break;\n\n case VC_EVENT_WRITE_READY:\n if (vioSource)\n vioSource->reenable();\n ret = VC_EVENT_CONT;\n break;\n\n case VC_EVENT_EOS:\n if (!tunnel_till_done && vio->ntodo())\n goto Lerror;\n if (vio == vioSource) {\n transform(vioSource->buffer, vioTarget->buffer);\n goto Lread_complete;\n } else {\n goto Ldone;\n }\n break; \/\/ fix coverity\n case VC_EVENT_READ_COMPLETE:\n Lread_complete:\n \/\/ set write nbytes to the current buffer size\n \/\/\n vioTarget->nbytes = vioTarget->ndone + vioTarget->buffer.reader()->read_avail();\n if (vioTarget->nbytes == vioTarget->ndone)\n goto Ldone;\n vioTarget->reenable();\n if (!tunnel_peer)\n close_source_vio(0);\n break;\n\n case VC_EVENT_ERROR:\n Lerror:\n lerrno = ((VIO *)data)->vc_server->lerrno;\n case VC_EVENT_INACTIVITY_TIMEOUT:\n case VC_EVENT_ACTIVE_TIMEOUT:\n result = -1;\n case VC_EVENT_WRITE_COMPLETE:\n Ldone:\n if (tunnel_peer) {\n \/\/ inform the peer:\n tunnel_peer->startEvent(ONE_WAY_TUNNEL_EVENT_PEER_CLOSE, data);\n }\n close_source_vio(result);\n close_target_vio(result);\n connection_closed(result);\n break;\n\n default:\n ink_assert(!\"bad case\");\n ret = VC_EVENT_CONT;\n break;\n }\n#ifdef TEST\n printf(\" (OneWayTunnel returning value: %s)\\n\", (ret == VC_EVENT_DONE ? \"VC_EVENT_DONE\" : \"VC_EVENT_CONT\"));\n#endif\n return ret;\n}\n\n\/\/ If result is Non-zero, the vc should be aborted.\nvoid\nOneWayTunnel::close_source_vio(int result)\n{\n if (vioSource) {\n if (last_connection() || !single_buffer) {\n free_MIOBuffer(vioSource->buffer.writer());\n vioSource->buffer.clear();\n }\n if (close_source && free_vcs) {\n vioSource->vc_server->do_io_close(result ? lerrno : -1);\n }\n vioSource = nullptr;\n n_connections--;\n }\n}\n\nvoid\nOneWayTunnel::close_target_vio(int result, VIO *vio)\n{\n (void)vio;\n if (vioTarget) {\n if (last_connection() || !single_buffer) {\n free_MIOBuffer(vioTarget->buffer.writer());\n vioTarget->buffer.clear();\n }\n if (close_target && free_vcs) {\n vioTarget->vc_server->do_io_close(result ? lerrno : -1);\n }\n vioTarget = nullptr;\n n_connections--;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ void OneWayTunnel::connection_closed\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nOneWayTunnel::connection_closed(int result)\n{\n if (cont) {\n#ifdef TEST\n cout << \"OneWayTunnel::connection_closed() ... calling cont\" << endl;\n#endif\n cont->handleEvent(result ? VC_EVENT_ERROR : VC_EVENT_EOS, this);\n } else {\n OneWayTunnel_free(this);\n }\n}\n\nvoid\nOneWayTunnel::reenable_all()\n{\n if (vioSource)\n vioSource->reenable();\n if (vioTarget)\n vioTarget->reenable();\n}\n\nbool\nOneWayTunnel::last_connection()\n{\n return n_connections == 1;\n}\n<|endoftext|>"} {"text":"\/*++\n\nModule Name:\n\n FASTA.cpp\n\nAbstract:\n\n FASTA reader\n\nAuthors:\n\n Bill Bolosky, August, 2011\n\nEnvironment:\n\n User mode service.\n\nRevision History:\n\n Adapted from Matei Zaharia's Scala implementation.\n\n--*\/\n\n#include \"stdafx.h\"\n#include \"Compat.h\"\n#include \"FASTA.h\"\n\n const Genome *\nReadFASTAGenome(const char *fileName)\n{\n \/\/\n \/\/ We need to know a bound on the size of the genome before we create the Genome object.\n \/\/ A bound is the number of bytes in the FASTA file, because we store at most one base per\n \/\/ byte. Get the file size to use for this bound.\n \/\/\n _int64 fileSize = QueryFileSize(fileName);\n\n if (fileSize >> 32 != 0) {\n fprintf(stderr,\"This tool only works with genomes with 2^32 bases or fewer.\\n\");\n return NULL;\n }\n\n Genome *genome = new Genome((unsigned) fileSize, (unsigned)fileSize);\n\n FILE *fastaFile = fopen(fileName, \"r\");\n if (fastaFile == NULL) {\n fprintf(stderr,\"Unable to open FASTA file '%s' (even though we already got its size)\\n\",fileName);\n delete genome;\n return NULL;\n }\n\n const size_t lineBufferSize = 4096;\n char lineBuffer[lineBufferSize];\n\n while (NULL != fgets(lineBuffer,lineBufferSize,fastaFile)) {\n if (lineBuffer[0] == '>') {\n char* space = strchr(lineBuffer, ' ');\n char* tab = strchr(lineBuffer, '\\t');\n char* end = space !=NULL ? (tab != NULL ? min(space, tab) : space)\n : tab != NULL ? tab : NULL;\n \/\/ Go up to blank, or remove the trailing newline from fgets\n end = end != NULL ? end : (lineBuffer + strlen(lineBuffer) - 1);\n *end = '\\0';\n genome->startPiece(lineBuffer+1);\n } else {\n \/\/\n \/\/ Convert it to upper case and truncate the newline before adding it to the genome.\n \/\/\n\n char *newline = strchr(lineBuffer, '\\n');\n if (NULL != newline) {\n *newline = 0;\n }\n\n \/\/\n \/\/ But convert any 'N' to 'n'. This is so we don't match the N from the genome with N\n \/\/ in reads (where we just do a straight text comparison.\n \/\/\n size_t lineLen = strlen(lineBuffer);\n\n\t\t\tfor (unsigned i = 0; i < lineLen; i++) {\n lineBuffer[i] = toupper(lineBuffer[i]);\n }\n\n\t\t\tfor (unsigned i = 0; i < lineLen; i++) {\n if ('N' == lineBuffer[i]) {\n lineBuffer[i] = 'n';\n }\n }\n genome->addData(lineBuffer);\n }\n }\n\n fclose(fastaFile);\n return genome;\n}\n\n\/\/\n\/\/ TODO: Reduce code duplication with the mutator.\n\/\/ \nbool AppendFASTAGenome(const Genome *genome, FILE *fasta, const char *prefix=\"\")\n{\n int nPieces = genome->getNumPieces();\n const Genome::Piece *pieces = genome->getPieces();\n for (int i = 0; i < nPieces; ++i) {\n const Genome::Piece &piece = pieces[i];\n unsigned start = piece.beginningOffset;\n unsigned end = i + 1 < nPieces ? pieces[i + 1].beginningOffset : genome->getCountOfBases();\n unsigned size = end - start;\n const char *bases = genome->getSubstring(start, size);\n \n fprintf(fasta, \">%s%s\\n\", prefix, piece.name);\n fwrite(bases, 1, size, fasta);\n fputc('\\n', fasta);\n }\n return !ferror(fasta);\n}\nFix compile error due to added \"min\"\/*++\n\nModule Name:\n\n FASTA.cpp\n\nAbstract:\n\n FASTA reader\n\nAuthors:\n\n Bill Bolosky, August, 2011\n\nEnvironment:\n\n User mode service.\n\nRevision History:\n\n Adapted from Matei Zaharia's Scala implementation.\n\n--*\/\n\n#include \"stdafx.h\"\n#include \"Compat.h\"\n#include \"FASTA.h\"\n\nusing namespace std;\n\n const Genome *\nReadFASTAGenome(const char *fileName)\n{\n \/\/\n \/\/ We need to know a bound on the size of the genome before we create the Genome object.\n \/\/ A bound is the number of bytes in the FASTA file, because we store at most one base per\n \/\/ byte. Get the file size to use for this bound.\n \/\/\n _int64 fileSize = QueryFileSize(fileName);\n\n if (fileSize >> 32 != 0) {\n fprintf(stderr,\"This tool only works with genomes with 2^32 bases or fewer.\\n\");\n return NULL;\n }\n\n Genome *genome = new Genome((unsigned) fileSize, (unsigned)fileSize);\n\n FILE *fastaFile = fopen(fileName, \"r\");\n if (fastaFile == NULL) {\n fprintf(stderr,\"Unable to open FASTA file '%s' (even though we already got its size)\\n\",fileName);\n delete genome;\n return NULL;\n }\n\n const size_t lineBufferSize = 4096;\n char lineBuffer[lineBufferSize];\n\n while (NULL != fgets(lineBuffer,lineBufferSize,fastaFile)) {\n if (lineBuffer[0] == '>') {\n char* space = strchr(lineBuffer, ' ');\n char* tab = strchr(lineBuffer, '\\t');\n char* end = space !=NULL ? (tab != NULL ? min(space, tab) : space)\n : tab != NULL ? tab : NULL;\n \/\/ Go up to blank, or remove the trailing newline from fgets\n end = end != NULL ? end : (lineBuffer + strlen(lineBuffer) - 1);\n *end = '\\0';\n genome->startPiece(lineBuffer+1);\n } else {\n \/\/\n \/\/ Convert it to upper case and truncate the newline before adding it to the genome.\n \/\/\n\n char *newline = strchr(lineBuffer, '\\n');\n if (NULL != newline) {\n *newline = 0;\n }\n\n \/\/\n \/\/ But convert any 'N' to 'n'. This is so we don't match the N from the genome with N\n \/\/ in reads (where we just do a straight text comparison.\n \/\/\n size_t lineLen = strlen(lineBuffer);\n\n\t\t\tfor (unsigned i = 0; i < lineLen; i++) {\n lineBuffer[i] = toupper(lineBuffer[i]);\n }\n\n\t\t\tfor (unsigned i = 0; i < lineLen; i++) {\n if ('N' == lineBuffer[i]) {\n lineBuffer[i] = 'n';\n }\n }\n genome->addData(lineBuffer);\n }\n }\n\n fclose(fastaFile);\n return genome;\n}\n\n\/\/\n\/\/ TODO: Reduce code duplication with the mutator.\n\/\/\nbool AppendFASTAGenome(const Genome *genome, FILE *fasta, const char *prefix=\"\")\n{\n int nPieces = genome->getNumPieces();\n const Genome::Piece *pieces = genome->getPieces();\n for (int i = 0; i < nPieces; ++i) {\n const Genome::Piece &piece = pieces[i];\n unsigned start = piece.beginningOffset;\n unsigned end = i + 1 < nPieces ? pieces[i + 1].beginningOffset : genome->getCountOfBases();\n unsigned size = end - start;\n const char *bases = genome->getSubstring(start, size);\n\n fprintf(fasta, \">%s%s\\n\", prefix, piece.name);\n fwrite(bases, 1, size, fasta);\n fputc('\\n', fasta);\n }\n return !ferror(fasta);\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ CSwing.cpp\n\/\/ SwingGame\n\/\/\n\/\/ Created by Tim Brier on 31\/10\/2014.\n\/\/ Copyright (c) 2014 tbrier. All rights reserved.\n\/\/\n\n\/\/ =============================================================================\n\/\/ Include Files\n\/\/ -----------------------------------------------------------------------------\n#include \"CSwing.hpp\"\n#include \"CSwingGame.hpp\"\n#include \"CLevel.hpp\"\n#include \"CollisionHandler.hpp\"\n\n\/\/ =============================================================================\n\/\/ Static variables\n\/\/ -----------------------------------------------------------------------------\nstatic float sMaxLength = 500.0f;\nstatic float sClimbSpeed = 100.0f;\n\n\/\/ =============================================================================\n\/\/ CSwing constructor\/destructor\n\/\/ -----------------------------------------------------------------------------\nCSwing::CSwing(CPlayer *theBob, CLevel *theParentLevel)\n: mBob(theBob),\n mParentLevel(theParentLevel),\n mAttached(false)\n{\n \n}\n\nCSwing::~CSwing()\n{\n \/\/ Unregister this x-able\n if (mAttached)\n {\n CSwingGame::UnregisterRenderable(this);\n CSwingGame::UnregisterUpdateable(this);\n }\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::AttemptToAttach\n\/\/ Find the first point between the bob and the aim point to attach to\n\/\/ -----------------------------------------------------------------------------\nvoid CSwing::AttemptToAttach(CVector2f theAimPoint)\n{\n \/\/ Attach the swing if we can find a valid anchor point\n CVector2f anchorPoint;\n if (IsThereAValidAnchor(theAimPoint, &anchorPoint))\n {\n \/\/ Make sure we detach from any existing swing\n Detach();\n \n \/\/ Now attach\n mAttached = true;\n \n mOrigin = anchorPoint;\n mLength = GetDistanceToBob();\n \n \/\/ Throw away any velocity that isn't perpendicular to the swing\n CVector2f v = mBob->GetVelocity();\n CVector2f newV = v.GetComponentInDirection(GetPerpendicularDirection());\n mBob->SetVelocity(newV);\n \n \/\/ Register ourselves now we're active\n CSwingGame::RegisterRenderable(this);\n CSwingGame::RegisterUpdateable(this);\n }\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::Detach\n\/\/ -----------------------------------------------------------------------------\nvoid CSwing::Detach()\n{\n if (mAttached)\n {\n mAttached = false;\n CSwingGame::UnregisterUpdateable(this);\n CSwingGame::UnregisterRenderable(this);\n }\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::AttenuateGravity\n\/\/ Alter the affect of gravity based on the swings angle\n\/\/ -----------------------------------------------------------------------------\nCVector2f CSwing::AttenuateGravity(CVector2f gravity)\n{\n \/\/ If we're not attached then don't affect gravity\n if (!mAttached)\n {\n return gravity;\n }\n \n \/\/ Throw away any component of the gravity that isn't perpendicular to the\n \/\/ swing\n return gravity.GetComponentInDirection(GetPerpendicularDirection());\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::Draw\n\/\/ -----------------------------------------------------------------------------\nvoid CSwing::Draw(CWindow *theWindow)\n{\n theWindow->DrawLine(CLine(mOrigin, mBob->GetPosition()), CColour::Black);\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::Update\n\/\/ -----------------------------------------------------------------------------\nvoid CSwing::Update(CTime elapsedTime)\n{\n if (mAttached)\n {\n HandleInput(elapsedTime);\n \n \/\/ Adjust the velocity so it is perpendicular to the swing\n CVector2f v = mBob->GetVelocity();\n CVector2f newV = v.GetComponentInDirection(GetPerpendicularDirection());\n newV.Normalise();\n newV *= v.GetMagnitude();\n mBob->SetVelocity(newV);\n \n \/\/ Make sure the bob isn't further away from the origin than the length\n \/\/ of the swing\n CVector2f bobToOrigin = mOrigin - mBob->GetPosition();\n float distance = bobToOrigin.GetMagnitude();\n if (distance > mLength)\n {\n \/\/ Move by the difference between the distance and length\n float moveDistance = distance - mLength;\n bobToOrigin.Normalise();\n bobToOrigin *= moveDistance;\n mBob->GetShape()->move(bobToOrigin);\n }\n \n HandleCollisions();\n }\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::IsAttached\n\/\/ -----------------------------------------------------------------------------\nbool CSwing::IsAttached()\n{\n return mAttached;\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::GetDistanceToBob\n\/\/ -----------------------------------------------------------------------------\nfloat CSwing::GetDistanceToBob()\n{\n CVector2f bobPosition = mBob->GetPosition();\n CVector2f bobToOrigin = mOrigin - bobPosition;\n return bobToOrigin.GetMagnitude();\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::IsThereAValidAnchor\n\/\/ -----------------------------------------------------------------------------\nbool CSwing::IsThereAValidAnchor(CVector2f theAimPoint, CVector2f *anchor)\n{\n bool theResult = false;\n \n \/\/ Find the direction from the bob to the aim point\n CVector2f bobPosition = mBob->GetPosition();\n CVector2f aimDirection = theAimPoint - bobPosition;\n aimDirection.Normalise();\n \n \/\/ Create a line from the bob to the max distance away that a swing could\n \/\/ reach in the aim direction\n CLine longestPossile = CLine(bobPosition,\n bobPosition + (aimDirection * sMaxLength));\n \n \/\/ Find the closest intersection of this line and any obstacle lines to the\n \/\/ bob\n *anchor = longestPossile.GetEnd();\n float currentDistanceToAnchor = sMaxLength;\n \n std::list theObstacles = mParentLevel->GetObstacles();\n FOR_EACH_IN_LIST(CPhysicsBody*, theObstacles)\n {\n std::list theIntersections;\n if (CollisionHandler::AreIntersecting(longestPossile,\n *((*it)->GetShape()),\n &theIntersections))\n {\n theResult = true;\n FOR_EACH_IN_LIST(CVector2f, theIntersections)\n {\n CVector2f thisIntersection = (*it);\n CVector2f bobToThis = thisIntersection - bobPosition;\n float distanceToThis = bobToThis.GetMagnitude();\n if (distanceToThis < currentDistanceToAnchor)\n {\n *anchor = thisIntersection;\n currentDistanceToAnchor = distanceToThis;\n }\n }\n }\n }\n \n return theResult;\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::GetPerpendicularDirection\n\/\/ -----------------------------------------------------------------------------\nCVector2f CSwing::GetPerpendicularDirection()\n{\n CVector2f originToBob = mBob->GetPosition() - mOrigin;\n originToBob.Normalise();\n \n CVector2f perpendicularDirection;\n perpendicularDirection.x = originToBob.y;\n perpendicularDirection.y = -originToBob.x;\n \n return perpendicularDirection;\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::HandleInput\n\/\/ -----------------------------------------------------------------------------\nvoid CSwing::HandleInput(CTime elapsedTime)\n{\n CVector2f climbOffset = CVector2f(0.0f, 0.0f);\n CVector2f climbDirection = mOrigin - mBob->GetPosition();\n climbDirection.Normalise();\n \n \/\/ Climb while w is pressed\n if (CKeyboard::isKeyPressed(CKeyboard::W))\n {\n climbOffset += climbDirection * sClimbSpeed * elapsedTime.asSeconds();\n }\n \n \/\/ Descend while s is presses\n if (CKeyboard::isKeyPressed(CKeyboard::S))\n {\n climbOffset -= climbDirection * sClimbSpeed * elapsedTime.asSeconds();\n }\n \n if (climbOffset .GetMagnitude() > 0)\n {\n mBob->MoveFixedDistanceUntilCollision(climbOffset);\n mLength = GetDistanceToBob();\n }\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::HandleCollisions\n\/\/ -----------------------------------------------------------------------------\nvoid CSwing::HandleCollisions()\n{\n \n}Don't allow swing to extend beyon max length\/\/\n\/\/ CSwing.cpp\n\/\/ SwingGame\n\/\/\n\/\/ Created by Tim Brier on 31\/10\/2014.\n\/\/ Copyright (c) 2014 tbrier. All rights reserved.\n\/\/\n\n\/\/ =============================================================================\n\/\/ Include Files\n\/\/ -----------------------------------------------------------------------------\n#include \"CSwing.hpp\"\n#include \"CSwingGame.hpp\"\n#include \"CLevel.hpp\"\n#include \"CollisionHandler.hpp\"\n\n\/\/ =============================================================================\n\/\/ Static variables\n\/\/ -----------------------------------------------------------------------------\nstatic float sMaxLength = 500.0f;\nstatic float sClimbSpeed = 100.0f;\n\n\/\/ =============================================================================\n\/\/ CSwing constructor\/destructor\n\/\/ -----------------------------------------------------------------------------\nCSwing::CSwing(CPlayer *theBob, CLevel *theParentLevel)\n: mBob(theBob),\n mParentLevel(theParentLevel),\n mAttached(false)\n{\n \n}\n\nCSwing::~CSwing()\n{\n \/\/ Unregister this x-able\n if (mAttached)\n {\n CSwingGame::UnregisterRenderable(this);\n CSwingGame::UnregisterUpdateable(this);\n }\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::AttemptToAttach\n\/\/ Find the first point between the bob and the aim point to attach to\n\/\/ -----------------------------------------------------------------------------\nvoid CSwing::AttemptToAttach(CVector2f theAimPoint)\n{\n \/\/ Attach the swing if we can find a valid anchor point\n CVector2f anchorPoint;\n if (IsThereAValidAnchor(theAimPoint, &anchorPoint))\n {\n \/\/ Make sure we detach from any existing swing\n Detach();\n \n \/\/ Now attach\n mAttached = true;\n \n mOrigin = anchorPoint;\n mLength = GetDistanceToBob();\n \n \/\/ Throw away any velocity that isn't perpendicular to the swing\n CVector2f v = mBob->GetVelocity();\n CVector2f newV = v.GetComponentInDirection(GetPerpendicularDirection());\n mBob->SetVelocity(newV);\n \n \/\/ Register ourselves now we're active\n CSwingGame::RegisterRenderable(this);\n CSwingGame::RegisterUpdateable(this);\n }\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::Detach\n\/\/ -----------------------------------------------------------------------------\nvoid CSwing::Detach()\n{\n if (mAttached)\n {\n mAttached = false;\n CSwingGame::UnregisterUpdateable(this);\n CSwingGame::UnregisterRenderable(this);\n }\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::AttenuateGravity\n\/\/ Alter the affect of gravity based on the swings angle\n\/\/ -----------------------------------------------------------------------------\nCVector2f CSwing::AttenuateGravity(CVector2f gravity)\n{\n \/\/ If we're not attached then don't affect gravity\n if (!mAttached)\n {\n return gravity;\n }\n \n \/\/ Throw away any component of the gravity that isn't perpendicular to the\n \/\/ swing\n return gravity.GetComponentInDirection(GetPerpendicularDirection());\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::Draw\n\/\/ -----------------------------------------------------------------------------\nvoid CSwing::Draw(CWindow *theWindow)\n{\n theWindow->DrawLine(CLine(mOrigin, mBob->GetPosition()), CColour::Black);\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::Update\n\/\/ -----------------------------------------------------------------------------\nvoid CSwing::Update(CTime elapsedTime)\n{\n if (mAttached)\n {\n HandleInput(elapsedTime);\n \n \/\/ Adjust the velocity so it is perpendicular to the swing\n CVector2f v = mBob->GetVelocity();\n CVector2f newV = v.GetComponentInDirection(GetPerpendicularDirection());\n newV.Normalise();\n newV *= v.GetMagnitude();\n mBob->SetVelocity(newV);\n \n \/\/ Make sure the bob isn't further away from the origin than the length\n \/\/ of the swing\n CVector2f bobToOrigin = mOrigin - mBob->GetPosition();\n float distance = bobToOrigin.GetMagnitude();\n if (distance > mLength)\n {\n \/\/ Move by the difference between the distance and length\n float moveDistance = distance - mLength;\n bobToOrigin.Normalise();\n bobToOrigin *= moveDistance;\n mBob->GetShape()->move(bobToOrigin);\n }\n \n HandleCollisions();\n }\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::IsAttached\n\/\/ -----------------------------------------------------------------------------\nbool CSwing::IsAttached()\n{\n return mAttached;\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::GetDistanceToBob\n\/\/ -----------------------------------------------------------------------------\nfloat CSwing::GetDistanceToBob()\n{\n CVector2f bobPosition = mBob->GetPosition();\n CVector2f bobToOrigin = mOrigin - bobPosition;\n return bobToOrigin.GetMagnitude();\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::IsThereAValidAnchor\n\/\/ -----------------------------------------------------------------------------\nbool CSwing::IsThereAValidAnchor(CVector2f theAimPoint, CVector2f *anchor)\n{\n bool theResult = false;\n \n \/\/ Find the direction from the bob to the aim point\n CVector2f bobPosition = mBob->GetPosition();\n CVector2f aimDirection = theAimPoint - bobPosition;\n aimDirection.Normalise();\n \n \/\/ Create a line from the bob to the max distance away that a swing could\n \/\/ reach in the aim direction\n CLine longestPossile = CLine(bobPosition,\n bobPosition + (aimDirection * sMaxLength));\n \n \/\/ Find the closest intersection of this line and any obstacle lines to the\n \/\/ bob\n *anchor = longestPossile.GetEnd();\n float currentDistanceToAnchor = sMaxLength;\n \n std::list theObstacles = mParentLevel->GetObstacles();\n FOR_EACH_IN_LIST(CPhysicsBody*, theObstacles)\n {\n std::list theIntersections;\n if (CollisionHandler::AreIntersecting(longestPossile,\n *((*it)->GetShape()),\n &theIntersections))\n {\n theResult = true;\n FOR_EACH_IN_LIST(CVector2f, theIntersections)\n {\n CVector2f thisIntersection = (*it);\n CVector2f bobToThis = thisIntersection - bobPosition;\n float distanceToThis = bobToThis.GetMagnitude();\n if (distanceToThis < currentDistanceToAnchor)\n {\n *anchor = thisIntersection;\n currentDistanceToAnchor = distanceToThis;\n }\n }\n }\n }\n \n return theResult;\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::GetPerpendicularDirection\n\/\/ -----------------------------------------------------------------------------\nCVector2f CSwing::GetPerpendicularDirection()\n{\n CVector2f originToBob = mBob->GetPosition() - mOrigin;\n originToBob.Normalise();\n \n CVector2f perpendicularDirection;\n perpendicularDirection.x = originToBob.y;\n perpendicularDirection.y = -originToBob.x;\n \n return perpendicularDirection;\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::HandleInput\n\/\/ -----------------------------------------------------------------------------\nvoid CSwing::HandleInput(CTime elapsedTime)\n{\n CVector2f climbOffset = CVector2f(0.0f, 0.0f);\n CVector2f climbDirection = mOrigin - mBob->GetPosition();\n climbDirection.Normalise();\n \n \/\/ Climb while w is pressed\n if (CKeyboard::isKeyPressed(CKeyboard::W))\n {\n climbOffset += climbDirection * sClimbSpeed * elapsedTime.asSeconds();\n }\n \n \/\/ Descend while s is presses\n if (CKeyboard::isKeyPressed(CKeyboard::S))\n {\n climbOffset -= climbDirection * sClimbSpeed * elapsedTime.asSeconds();\n }\n \n if (climbOffset .GetMagnitude() > 0)\n {\n mBob->MoveFixedDistanceUntilCollision(climbOffset);\n mLength = GetDistanceToBob();\n mLength = std::min(mLength, sMaxLength);\n }\n}\n\n\/\/ =============================================================================\n\/\/ CSwing::HandleCollisions\n\/\/ -----------------------------------------------------------------------------\nvoid CSwing::HandleCollisions()\n{\n \n}<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ndarr.hxx,v $\n * $Revision: 1.19 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _NDARR_HXX\n#define _NDARR_HXX\n\n#include \n#include \n\n#ifndef _BPARR_HXX\n#include \n#endif\n#include \n\n#include \n#include \n\nclass Graphic;\nclass GraphicObject;\nclass String;\nclass SwAttrSet;\nclass SfxItemSet;\nclass SwCntntNode;\nclass SwDoc;\nclass SwGrfFmtColl;\nclass SwGrfNode;\nclass SwHistory;\nclass SwNode;\nclass SwNodeIndex;\nclass SwNodeRange;\nclass SwOLENode;\nclass SwOutlineNodes;\nclass SwPaM;\nclass SwSection;\nclass SwSectionFmt;\nclass SwSectionNode;\nclass SwStartNode;\nclass SwTableBoxFmt;\nclass SwTableFmt;\nclass SwTableLine;\nclass SwTableLineFmt;\nclass SwTableNode;\nclass SwTblToTxtSaves;\nclass SwTxtFmtColl;\nclass SwTxtNode;\nclass SwUndoTblToTxt;\nclass SwUndoTxtToTbl;\nstruct SwPosition;\n\n\n\/\/ --------------------\n\/\/ class SwNodes\n\/\/ --------------------\n\ntypedef SwNode * SwNodePtr;\ntypedef BOOL (*FnForEach_SwNodes)( const SwNodePtr&, void* pArgs );\n\nSV_DECL_PTRARR_SORT( SwOutlineNodes, SwNodePtr, 0, 10 )\n\nclass SwNodes: private BigPtrArray\n{\n friend class SwDoc;\n friend class SwNode;\n friend class SwNodeIndex;\n\n SwNodePtr operator[]( USHORT n ) const;\n SwNodePtr operator[]( int n ) const;\n\n SwNodeIndex* pRoot; \/\/ Liste aller Indizies auf Nodes\n\n \/\/ --> OD 2006-10-16 #137792#\n \/\/ - rename from to \n \/\/ - add 3rd optional parameter \n void InsertNode( const SwNodePtr pNode,\n const SwNodeIndex& rPos,\n const bool bSyncNumberAndNumRule = true );\n void InsertNode( const SwNodePtr pNode,\n ULONG nPos,\n const bool bSyncNumberAndNumRule = true);\n \/\/ <--\n\/\/ void Remove( const SwNodeIndex& rPos, USHORT nLen = 1 );\n\/\/ void Remove( ULONG nPos, USHORT nLen = 1 );\n\/\/ BOOL Move( const SwIndex & rOldPos, const SwIndex & rNewPos );\n\n\n SwDoc* pMyDoc; \/\/ in diesem Doc ist das Nodes-Array\n\n SwNode *pEndOfPostIts, *pEndOfInserts, \/\/ das sind die festen Bereiche\n *pEndOfAutotext, *pEndOfRedlines,\n *pEndOfContent;\n\n mutable SwOutlineNodes* pOutlineNds; \/\/ Array aller GliederiungsNodes\n\n BOOL bInNodesDel : 1; \/\/ falls rekursiv aufgerufen wird\n \/\/ Num\/Outline nicht aktualisierem\n BOOL bInDelUpdOutl : 1; \/\/ Flags fuers aktualisieren von Outl.\n BOOL bInDelUpdNum : 1; \/\/ Flags fuers aktualisieren von Outl.\n\n \/\/ fuer dier Verwaltung der Indizies\n void RegisterIndex( SwNodeIndex& rIdx );\n void DeRegisterIndex( SwNodeIndex& rIdx );\n void RemoveNode( ULONG nDelPos, ULONG nLen, BOOL bDel );\n\n \/\/ Aktionen auf die Nodes\n void SectionUpDown( const SwNodeIndex & aStart, const SwNodeIndex & aEnd );\n void DelNodes( const SwNodeIndex& rStart, ULONG nCnt = 1 );\n\n void ChgNode( SwNodeIndex& rDelPos, ULONG nSize,\n SwNodeIndex& rInsPos, BOOL bNewFrms );\n\n void UpdtOutlineIdx( const SwNode& ); \/\/ Update ab Node alle OutlineNodes\n\n void _CopyNodes( const SwNodeRange&, const SwNodeIndex&,\n BOOL bNewFrms = TRUE, BOOL bTblInsDummyNode = FALSE ) const;\n void _DelDummyNodes( const SwNodeRange& rRg );\n\nprotected:\n SwNodes( SwDoc* pDoc );\n\npublic:\n ~SwNodes();\n\n SwNodePtr operator[]( ULONG n ) const\n { return (SwNodePtr)BigPtrArray::operator[] ( n ); }\n\n\/\/JP 29.09.97: impl. steht im ndindex.hxx - sollte moeglichst bald auf die\n\/\/ neue Schnittstelle angepasst werden\n inline SwNodePtr operator[]( const SwNodeIndex& rIdx ) const;\n\n ULONG Count() const { return BigPtrArray::Count(); }\n void ForEach( FnForEach_SwNodes fnForEach, void* pArgs = 0 )\n {\n BigPtrArray::ForEach( 0, BigPtrArray::Count(),\n (FnForEach) fnForEach, pArgs );\n }\n void ForEach( ULONG nStt, ULONG nEnd, FnForEach_SwNodes fnForEach, void* pArgs = 0 )\n {\n BigPtrArray::ForEach( nStt, nEnd, (FnForEach) fnForEach, pArgs );\n }\n void ForEach( const SwNodeIndex& rStart, const SwNodeIndex& rEnd,\n FnForEach_SwNodes fnForEach, void* pArgs = 0 );\n\n \/\/ eine noch leere Section\n SwNode& GetEndOfPostIts() const { return *pEndOfPostIts; }\n \/\/ Section fuer alle Fussnoten\n SwNode& GetEndOfInserts() const { return *pEndOfInserts; }\n \/\/ Section fuer alle Flys\/Header\/Footers\n SwNode& GetEndOfAutotext() const { return *pEndOfAutotext; }\n \/\/ Section fuer alle Redlines\n SwNode& GetEndOfRedlines() const { return *pEndOfRedlines; }\n \/\/ das ist der letzte EndNode einer SonderSection. Hier nach kommt nur\n \/\/ noch die normale ContentSection (also der BodyText)\n SwNode& GetEndOfExtras() const { return *pEndOfRedlines; }\n \/\/ die normale ContentSection (also der BodyText)\n SwNode& GetEndOfContent() const { return *pEndOfContent; }\n\n \/\/ ist das NodesArray das normale vom Doc? (nicht das UndoNds, .. )\n \/\/ Implementierung steht im doc.hxx (weil man dazu Doc kennen muss) !\n BOOL IsDocNodes() const;\n\n USHORT GetSectionLevel(const SwNodeIndex &rIndex) const;\n void Delete(const SwNodeIndex &rPos, ULONG nNodes = 1);\n\n BOOL _MoveNodes( const SwNodeRange&, SwNodes& rNodes, const SwNodeIndex&,\n BOOL bNewFrms = TRUE );\n void Move( SwPaM&, SwPosition&, SwNodes& rNodes, BOOL bSplitNd=TRUE );\n\n void _Copy( const SwNodeRange& rRg, const SwNodeIndex& rInsPos,\n BOOL bNewFrms = TRUE ) const\n { _CopyNodes( rRg, rInsPos, bNewFrms ); }\n\n void SectionUp( SwNodeRange *);\n void SectionDown( SwNodeRange *pRange, SwStartNodeType = SwNormalStartNode );\n\n BOOL CheckNodesRange( const SwNodeIndex& rStt, const SwNodeIndex& rEnd ) const;\n\n void GoStartOfSection(SwNodeIndex *) const;\n void GoEndOfSection(SwNodeIndex *) const;\n\n SwCntntNode* GoNext(SwNodeIndex *) const;\n SwCntntNode* GoPrevious(SwNodeIndex *) const;\n\n \/\/Gehe zum naechsten\/vorherigen Cntnt\/Tabellennode, fuer den\n \/\/es LayoutFrames gibt, dabei Kopf-\/Fusszeilen\/Rahmen etc. nicht verlassen\n SwNode* GoNextWithFrm(SwNodeIndex *) const;\n SwNode* GoPreviousWithFrm(SwNodeIndex *) const;\n\n \/\/ zum naechsten Content-Node, der nicht geschuetzt oder versteckt ist\n \/\/ (beides auf FALSE ==> GoNext\/GoPrevious!!!)\n SwCntntNode* GoNextSection( SwNodeIndex *, int bSkipHidden = TRUE,\n int bSkipProtect = TRUE ) const;\n SwCntntNode* GoPrevSection( SwNodeIndex *, int bSkipHidden = TRUE,\n int bSkipProtect = TRUE ) const;\n\n \/\/ erzeuge ein leere Section von Start und EndNode. Darf nur gerufen\n \/\/ werden, wenn eine neue Section mit Inhalt erzeugt werden soll.\n \/\/ Zum Beispiel bei den Filtern\/Undo\/...\n SwStartNode* MakeEmptySection( const SwNodeIndex& rIdx,\n SwStartNodeType = SwNormalStartNode );\n\n \/\/ die Impl. von \"Make...Node\" stehen in den angegebenen .ccx-Files\n SwTxtNode *MakeTxtNode( const SwNodeIndex & rWhere,\n SwTxtFmtColl *pColl,\n SwAttrSet* pAutoAttr = 0 ); \/\/ in ndtxt.cxx\n SwStartNode* MakeTextSection( const SwNodeIndex & rWhere,\n SwStartNodeType eSttNdTyp,\n SwTxtFmtColl *pColl,\n SwAttrSet* pAutoAttr = 0 );\n\n SwGrfNode *MakeGrfNode( const SwNodeIndex & rWhere,\n const String& rGrfName,\n const String& rFltName,\n const Graphic* pGraphic,\n SwGrfFmtColl *pColl,\n SwAttrSet* pAutoAttr = 0,\n BOOL bDelayed = FALSE ); \/\/ in ndgrf.cxx\n\n SwGrfNode *MakeGrfNode( const SwNodeIndex & rWhere,\n const GraphicObject& rGrfObj,\n SwGrfFmtColl *pColl,\n SwAttrSet* pAutoAttr = 0 ); \/\/ in ndgrf.cxx\n\n SwOLENode *MakeOLENode( const SwNodeIndex & rWhere,\n const svt::EmbeddedObjectRef&,\n SwGrfFmtColl *pColl,\n SwAttrSet* pAutoAttr = 0 ); \/\/ in ndole.cxx\n SwOLENode *MakeOLENode( const SwNodeIndex & rWhere,\n const String &rName,\n sal_Int64 nAspect,\n SwGrfFmtColl *pColl,\n SwAttrSet* pAutoAttr ); \/\/ in ndole.cxx\n\n \/\/ Array aller GliederiungsNodes;\n const SwOutlineNodes& GetOutLineNds() const;\n\n void UpdateOutlineNode( const SwNode&, BYTE nOldLevel, BYTE nNewLevel );\n \/\/ alle Nodes Updaten - Rule\/Format-Aenderung\n void UpdateOutlineNode(SwNode & rNd);\n\n \/\/ fuege die Nodes fuer die Tabelle ein\n \/\/ wenn Lines angegeben, erzeuge die Matrix aus Lines & Boxen\n \/\/ ansonsten nur die Anzahl von Boxen.\n \/* #109161#\n\n New parameter pAttrSet: If pAttrSet is non-null and contains an\n adjust item it is propagated to the table cells. If there is an\n adjust in pCntntTxtColl or pHeadlineTxtColl this adjust item\n overrides the item in pAttrSet.\n\n *\/\n SwTableNode* InsertTable( const SwNodeIndex& rNdIdx,\n USHORT nBoxes, SwTxtFmtColl* pCntntTxtColl,\n USHORT nLines = 0, USHORT nRepeat = 0,\n SwTxtFmtColl* pHeadlineTxtColl = 0,\n const SwAttrSet * pAttrSet = 0);\n\n \/\/ erzeuge aus dem makierten Bereich eine ausgeglichene Tabelle\n SwTableNode* TextToTable( const SwNodeRange& rRange, sal_Unicode cCh,\n SwTableFmt* pTblFmt,\n SwTableLineFmt* pLineFmt,\n SwTableBoxFmt* pBoxFmt,\n SwTxtFmtColl* pTxtColl,\n SwUndoTxtToTbl* pUndo = 0 );\n \/\/create a table from a vector of NodeRanges - API support\n SwTableNode* TextToTable( const std::vector< std::vector >& rTableNodes,\n SwTableFmt* pTblFmt,\n SwTableLineFmt* pLineFmt,\n SwTableBoxFmt* pBoxFmt,\n SwTxtFmtColl* pTxtColl\n \/*, SwUndo... pUndo*\/ );\n\n \/\/ erzeuge aus der Tabelle wieder normalen Text\n BOOL TableToText( const SwNodeRange& rRange, sal_Unicode cCh,\n SwUndoTblToTxt* = 0 );\n \/\/ steht im untbl.cxx und darf nur vom Undoobject gerufen werden\n SwTableNode* UndoTableToText( ULONG nStt, ULONG nEnd,\n const SwTblToTxtSaves& rSavedData );\n\n \/\/ fuege in der Line, vor der InsPos eine neue Box ein. Das Format\n \/\/ wird von der nachfolgenden (vorhergenden;wenn an Ende) genommen\n \/\/ in der Line muss schon eine Box vorhanden sein !\n BOOL InsBoxen( SwTableNode*, SwTableLine*, SwTableBoxFmt*,\n \/\/ Formate fuer den TextNode der Box\n SwTxtFmtColl*, const SfxItemSet* pAutoAttr,\n USHORT nInsPos, USHORT nCnt = 1 );\n \/\/ Splittet eine Tabelle in der Grund-Zeile, in der der Index steht.\n \/\/ Alle GrundZeilen dahinter wandern in eine neue Tabelle\/-Node.\n \/\/ Ist das Flag bCalcNewSize auf TRUE, wird fuer beide neuen Tabellen\n \/\/ die neue SSize aus dem Max der Boxen errechnet; vorrausgesetzt,\n \/\/ die SSize ist \"absolut\" gesetzt (LONG_MAX)\n \/\/ (Wird zur Zeit nur fuer den RTF-Parser benoetigt)\n SwTableNode* SplitTable( const SwNodeIndex& rPos, BOOL bAfter = TRUE,\n BOOL bCalcNewSize = FALSE );\n \/\/ fuegt 2 Tabellen, die hintereinander stehen, wieder zusammen\n BOOL MergeTable( const SwNodeIndex& rPos, BOOL bWithPrev = TRUE,\n USHORT nMode = 0, SwHistory* pHistory = 0 );\n\n \/\/ fuege eine neue SwSection ein\n SwSectionNode* InsertSection( const SwNodeIndex& rNdIdx,\n SwSectionFmt& rSectionFmt,\n const SwSection&,\n const SwNodeIndex* pEnde,\n BOOL bInsAtStart = TRUE,\n BOOL bCreateFrms = TRUE );\n\n \/\/ in welchem Doc steht das Nodes-Array ?\n SwDoc* GetDoc() { return pMyDoc; }\n const SwDoc* GetDoc() const { return pMyDoc; }\n\n \/\/ suche den vorhergehenden [\/nachfolgenden ] ContentNode oder\n \/\/ TabellenNode mit Frames. Wird kein Ende angeben, dann wird mit\n \/\/ dem FrameIndex begonnen; ansonsten, wird mit dem vor rFrmIdx und\n \/\/ dem hintern pEnd die Suche gestartet. Sollte kein gueltiger Node\n \/\/ gefunden werden, wird 0 returnt. rFrmIdx zeigt auf dem Node mit\n \/\/ Frames\n SwNode* FindPrvNxtFrmNode( SwNodeIndex& rFrmIdx,\n const SwNode* pEnd = 0 ) const;\n\n \/\/-> #112139#\n SwNode * DocumentSectionStartNode(SwNode * pNode) const;\n SwNode * DocumentSectionEndNode(SwNode * pNode) const;\n \/\/<- #112139#\nprivate:\n \/\/ privater Constructor, weil nie kopiert werden darf !!\n SwNodes( const SwNodes & rNodes );\n};\n\n\n\n#endif\nINTEGRATION: CWS swlists01 (1.18.192); FILE MERGED 2008\/05\/14 12:41:50 od 1.18.192.3: #i86732# remove no longer needed code 2008\/05\/08 16:16:25 od 1.18.192.2: RESYNC: (1.18-1.19); FILE MERGED 2008\/03\/20 07:53:36 od 1.18.192.1: #i86732# class \t - refactoring: remove not needed private operators []\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ndarr.hxx,v $\n * $Revision: 1.20 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _NDARR_HXX\n#define _NDARR_HXX\n\n#include \n#include \n\n#ifndef _BPARR_HXX\n#include \n#endif\n#include \n\n#include \n#include \n\nclass Graphic;\nclass GraphicObject;\nclass String;\nclass SwAttrSet;\nclass SfxItemSet;\nclass SwCntntNode;\nclass SwDoc;\nclass SwGrfFmtColl;\nclass SwGrfNode;\nclass SwHistory;\nclass SwNode;\nclass SwNodeIndex;\nclass SwNodeRange;\nclass SwOLENode;\nclass SwOutlineNodes;\nclass SwPaM;\nclass SwSection;\nclass SwSectionFmt;\nclass SwSectionNode;\nclass SwStartNode;\nclass SwTableBoxFmt;\nclass SwTableFmt;\nclass SwTableLine;\nclass SwTableLineFmt;\nclass SwTableNode;\nclass SwTblToTxtSaves;\nclass SwTxtFmtColl;\nclass SwTxtNode;\nclass SwUndoTblToTxt;\nclass SwUndoTxtToTbl;\nstruct SwPosition;\n\n\n\/\/ --------------------\n\/\/ class SwNodes\n\/\/ --------------------\n\ntypedef SwNode * SwNodePtr;\ntypedef BOOL (*FnForEach_SwNodes)( const SwNodePtr&, void* pArgs );\n\nSV_DECL_PTRARR_SORT( SwOutlineNodes, SwNodePtr, 0, 10 )\n\nclass SwNodes: private BigPtrArray\n{\n friend class SwDoc;\n friend class SwNode;\n friend class SwNodeIndex;\n\n SwNodeIndex* pRoot; \/\/ Liste aller Indizies auf Nodes\n\n \/\/ --> OD 2008-05-14 #refactorlists# - removed \n void InsertNode( const SwNodePtr pNode,\n const SwNodeIndex& rPos );\n void InsertNode( const SwNodePtr pNode,\n ULONG nPos );\n \/\/ <--\n\n\n SwDoc* pMyDoc; \/\/ in diesem Doc ist das Nodes-Array\n\n SwNode *pEndOfPostIts, *pEndOfInserts, \/\/ das sind die festen Bereiche\n *pEndOfAutotext, *pEndOfRedlines,\n *pEndOfContent;\n\n mutable SwOutlineNodes* pOutlineNds; \/\/ Array aller GliederiungsNodes\n\n BOOL bInNodesDel : 1; \/\/ falls rekursiv aufgerufen wird\n \/\/ Num\/Outline nicht aktualisierem\n BOOL bInDelUpdOutl : 1; \/\/ Flags fuers aktualisieren von Outl.\n BOOL bInDelUpdNum : 1; \/\/ Flags fuers aktualisieren von Outl.\n\n \/\/ fuer dier Verwaltung der Indizies\n void RegisterIndex( SwNodeIndex& rIdx );\n void DeRegisterIndex( SwNodeIndex& rIdx );\n void RemoveNode( ULONG nDelPos, ULONG nLen, BOOL bDel );\n\n \/\/ Aktionen auf die Nodes\n void SectionUpDown( const SwNodeIndex & aStart, const SwNodeIndex & aEnd );\n void DelNodes( const SwNodeIndex& rStart, ULONG nCnt = 1 );\n\n void ChgNode( SwNodeIndex& rDelPos, ULONG nSize,\n SwNodeIndex& rInsPos, BOOL bNewFrms );\n\n void UpdtOutlineIdx( const SwNode& ); \/\/ Update ab Node alle OutlineNodes\n\n void _CopyNodes( const SwNodeRange&, const SwNodeIndex&,\n BOOL bNewFrms = TRUE, BOOL bTblInsDummyNode = FALSE ) const;\n void _DelDummyNodes( const SwNodeRange& rRg );\n\nprotected:\n SwNodes( SwDoc* pDoc );\n\npublic:\n ~SwNodes();\n\n SwNodePtr operator[]( ULONG n ) const\n { return (SwNodePtr)BigPtrArray::operator[] ( n ); }\n\n\/\/JP 29.09.97: impl. steht im ndindex.hxx - sollte moeglichst bald auf die\n\/\/ neue Schnittstelle angepasst werden\n inline SwNodePtr operator[]( const SwNodeIndex& rIdx ) const;\n\n ULONG Count() const { return BigPtrArray::Count(); }\n void ForEach( FnForEach_SwNodes fnForEach, void* pArgs = 0 )\n {\n BigPtrArray::ForEach( 0, BigPtrArray::Count(),\n (FnForEach) fnForEach, pArgs );\n }\n void ForEach( ULONG nStt, ULONG nEnd, FnForEach_SwNodes fnForEach, void* pArgs = 0 )\n {\n BigPtrArray::ForEach( nStt, nEnd, (FnForEach) fnForEach, pArgs );\n }\n void ForEach( const SwNodeIndex& rStart, const SwNodeIndex& rEnd,\n FnForEach_SwNodes fnForEach, void* pArgs = 0 );\n\n \/\/ eine noch leere Section\n SwNode& GetEndOfPostIts() const { return *pEndOfPostIts; }\n \/\/ Section fuer alle Fussnoten\n SwNode& GetEndOfInserts() const { return *pEndOfInserts; }\n \/\/ Section fuer alle Flys\/Header\/Footers\n SwNode& GetEndOfAutotext() const { return *pEndOfAutotext; }\n \/\/ Section fuer alle Redlines\n SwNode& GetEndOfRedlines() const { return *pEndOfRedlines; }\n \/\/ das ist der letzte EndNode einer SonderSection. Hier nach kommt nur\n \/\/ noch die normale ContentSection (also der BodyText)\n SwNode& GetEndOfExtras() const { return *pEndOfRedlines; }\n \/\/ die normale ContentSection (also der BodyText)\n SwNode& GetEndOfContent() const { return *pEndOfContent; }\n\n \/\/ ist das NodesArray das normale vom Doc? (nicht das UndoNds, .. )\n \/\/ Implementierung steht im doc.hxx (weil man dazu Doc kennen muss) !\n BOOL IsDocNodes() const;\n\n USHORT GetSectionLevel(const SwNodeIndex &rIndex) const;\n void Delete(const SwNodeIndex &rPos, ULONG nNodes = 1);\n\n BOOL _MoveNodes( const SwNodeRange&, SwNodes& rNodes, const SwNodeIndex&,\n BOOL bNewFrms = TRUE );\n void Move( SwPaM&, SwPosition&, SwNodes& rNodes, BOOL bSplitNd=TRUE );\n\n void _Copy( const SwNodeRange& rRg, const SwNodeIndex& rInsPos,\n BOOL bNewFrms = TRUE ) const\n { _CopyNodes( rRg, rInsPos, bNewFrms ); }\n\n void SectionUp( SwNodeRange *);\n void SectionDown( SwNodeRange *pRange, SwStartNodeType = SwNormalStartNode );\n\n BOOL CheckNodesRange( const SwNodeIndex& rStt, const SwNodeIndex& rEnd ) const;\n\n void GoStartOfSection(SwNodeIndex *) const;\n void GoEndOfSection(SwNodeIndex *) const;\n\n SwCntntNode* GoNext(SwNodeIndex *) const;\n SwCntntNode* GoPrevious(SwNodeIndex *) const;\n\n \/\/Gehe zum naechsten\/vorherigen Cntnt\/Tabellennode, fuer den\n \/\/es LayoutFrames gibt, dabei Kopf-\/Fusszeilen\/Rahmen etc. nicht verlassen\n SwNode* GoNextWithFrm(SwNodeIndex *) const;\n SwNode* GoPreviousWithFrm(SwNodeIndex *) const;\n\n \/\/ zum naechsten Content-Node, der nicht geschuetzt oder versteckt ist\n \/\/ (beides auf FALSE ==> GoNext\/GoPrevious!!!)\n SwCntntNode* GoNextSection( SwNodeIndex *, int bSkipHidden = TRUE,\n int bSkipProtect = TRUE ) const;\n SwCntntNode* GoPrevSection( SwNodeIndex *, int bSkipHidden = TRUE,\n int bSkipProtect = TRUE ) const;\n\n \/\/ erzeuge ein leere Section von Start und EndNode. Darf nur gerufen\n \/\/ werden, wenn eine neue Section mit Inhalt erzeugt werden soll.\n \/\/ Zum Beispiel bei den Filtern\/Undo\/...\n SwStartNode* MakeEmptySection( const SwNodeIndex& rIdx,\n SwStartNodeType = SwNormalStartNode );\n\n \/\/ die Impl. von \"Make...Node\" stehen in den angegebenen .ccx-Files\n SwTxtNode *MakeTxtNode( const SwNodeIndex & rWhere,\n SwTxtFmtColl *pColl,\n SwAttrSet* pAutoAttr = 0 ); \/\/ in ndtxt.cxx\n SwStartNode* MakeTextSection( const SwNodeIndex & rWhere,\n SwStartNodeType eSttNdTyp,\n SwTxtFmtColl *pColl,\n SwAttrSet* pAutoAttr = 0 );\n\n SwGrfNode *MakeGrfNode( const SwNodeIndex & rWhere,\n const String& rGrfName,\n const String& rFltName,\n const Graphic* pGraphic,\n SwGrfFmtColl *pColl,\n SwAttrSet* pAutoAttr = 0,\n BOOL bDelayed = FALSE ); \/\/ in ndgrf.cxx\n\n SwGrfNode *MakeGrfNode( const SwNodeIndex & rWhere,\n const GraphicObject& rGrfObj,\n SwGrfFmtColl *pColl,\n SwAttrSet* pAutoAttr = 0 ); \/\/ in ndgrf.cxx\n\n SwOLENode *MakeOLENode( const SwNodeIndex & rWhere,\n const svt::EmbeddedObjectRef&,\n SwGrfFmtColl *pColl,\n SwAttrSet* pAutoAttr = 0 ); \/\/ in ndole.cxx\n SwOLENode *MakeOLENode( const SwNodeIndex & rWhere,\n const String &rName,\n sal_Int64 nAspect,\n SwGrfFmtColl *pColl,\n SwAttrSet* pAutoAttr ); \/\/ in ndole.cxx\n\n \/\/ Array aller GliederiungsNodes;\n const SwOutlineNodes& GetOutLineNds() const;\n\n void UpdateOutlineNode( const SwNode&, BYTE nOldLevel, BYTE nNewLevel );\n \/\/ alle Nodes Updaten - Rule\/Format-Aenderung\n void UpdateOutlineNode(SwNode & rNd);\n\n \/\/ fuege die Nodes fuer die Tabelle ein\n \/\/ wenn Lines angegeben, erzeuge die Matrix aus Lines & Boxen\n \/\/ ansonsten nur die Anzahl von Boxen.\n \/* #109161#\n\n New parameter pAttrSet: If pAttrSet is non-null and contains an\n adjust item it is propagated to the table cells. If there is an\n adjust in pCntntTxtColl or pHeadlineTxtColl this adjust item\n overrides the item in pAttrSet.\n\n *\/\n SwTableNode* InsertTable( const SwNodeIndex& rNdIdx,\n USHORT nBoxes, SwTxtFmtColl* pCntntTxtColl,\n USHORT nLines = 0, USHORT nRepeat = 0,\n SwTxtFmtColl* pHeadlineTxtColl = 0,\n const SwAttrSet * pAttrSet = 0);\n\n \/\/ erzeuge aus dem makierten Bereich eine ausgeglichene Tabelle\n SwTableNode* TextToTable( const SwNodeRange& rRange, sal_Unicode cCh,\n SwTableFmt* pTblFmt,\n SwTableLineFmt* pLineFmt,\n SwTableBoxFmt* pBoxFmt,\n SwTxtFmtColl* pTxtColl,\n SwUndoTxtToTbl* pUndo = 0 );\n \/\/create a table from a vector of NodeRanges - API support\n SwTableNode* TextToTable( const std::vector< std::vector >& rTableNodes,\n SwTableFmt* pTblFmt,\n SwTableLineFmt* pLineFmt,\n SwTableBoxFmt* pBoxFmt,\n SwTxtFmtColl* pTxtColl\n \/*, SwUndo... pUndo*\/ );\n\n \/\/ erzeuge aus der Tabelle wieder normalen Text\n BOOL TableToText( const SwNodeRange& rRange, sal_Unicode cCh,\n SwUndoTblToTxt* = 0 );\n \/\/ steht im untbl.cxx und darf nur vom Undoobject gerufen werden\n SwTableNode* UndoTableToText( ULONG nStt, ULONG nEnd,\n const SwTblToTxtSaves& rSavedData );\n\n \/\/ fuege in der Line, vor der InsPos eine neue Box ein. Das Format\n \/\/ wird von der nachfolgenden (vorhergenden;wenn an Ende) genommen\n \/\/ in der Line muss schon eine Box vorhanden sein !\n BOOL InsBoxen( SwTableNode*, SwTableLine*, SwTableBoxFmt*,\n \/\/ Formate fuer den TextNode der Box\n SwTxtFmtColl*, const SfxItemSet* pAutoAttr,\n USHORT nInsPos, USHORT nCnt = 1 );\n \/\/ Splittet eine Tabelle in der Grund-Zeile, in der der Index steht.\n \/\/ Alle GrundZeilen dahinter wandern in eine neue Tabelle\/-Node.\n \/\/ Ist das Flag bCalcNewSize auf TRUE, wird fuer beide neuen Tabellen\n \/\/ die neue SSize aus dem Max der Boxen errechnet; vorrausgesetzt,\n \/\/ die SSize ist \"absolut\" gesetzt (LONG_MAX)\n \/\/ (Wird zur Zeit nur fuer den RTF-Parser benoetigt)\n SwTableNode* SplitTable( const SwNodeIndex& rPos, BOOL bAfter = TRUE,\n BOOL bCalcNewSize = FALSE );\n \/\/ fuegt 2 Tabellen, die hintereinander stehen, wieder zusammen\n BOOL MergeTable( const SwNodeIndex& rPos, BOOL bWithPrev = TRUE,\n USHORT nMode = 0, SwHistory* pHistory = 0 );\n\n \/\/ fuege eine neue SwSection ein\n SwSectionNode* InsertSection( const SwNodeIndex& rNdIdx,\n SwSectionFmt& rSectionFmt,\n const SwSection&,\n const SwNodeIndex* pEnde,\n BOOL bInsAtStart = TRUE,\n BOOL bCreateFrms = TRUE );\n\n \/\/ in welchem Doc steht das Nodes-Array ?\n SwDoc* GetDoc() { return pMyDoc; }\n const SwDoc* GetDoc() const { return pMyDoc; }\n\n \/\/ suche den vorhergehenden [\/nachfolgenden ] ContentNode oder\n \/\/ TabellenNode mit Frames. Wird kein Ende angeben, dann wird mit\n \/\/ dem FrameIndex begonnen; ansonsten, wird mit dem vor rFrmIdx und\n \/\/ dem hintern pEnd die Suche gestartet. Sollte kein gueltiger Node\n \/\/ gefunden werden, wird 0 returnt. rFrmIdx zeigt auf dem Node mit\n \/\/ Frames\n SwNode* FindPrvNxtFrmNode( SwNodeIndex& rFrmIdx,\n const SwNode* pEnd = 0 ) const;\n\n \/\/-> #112139#\n SwNode * DocumentSectionStartNode(SwNode * pNode) const;\n SwNode * DocumentSectionEndNode(SwNode * pNode) const;\n \/\/<- #112139#\nprivate:\n \/\/ privater Constructor, weil nie kopiert werden darf !!\n SwNodes( const SwNodes & rNodes );\n};\n\n\n\n#endif\n<|endoftext|>"} {"text":"#include \"shape\/vertex.h\"\n\n#define rb_array_p(x) RB_TYPE_P(x, T_ARRAY)\n\nVALUE sr_cVertex;\n\nSR_SHAPE_GET(Vertex, vertex)\nSR_SHAPE_CHECK(Vertex, vertex)\n\nbool siren_vertex_install()\n{\n SR_SHAPE_INIT(Vertex)\n rb_define_method(sr_cVertex, \"initialize\", RUBY_METHOD_FUNC(siren_vertex_init), -1);\n rb_define_method(sr_cVertex, \"xyz\", RUBY_METHOD_FUNC(siren_vertex_xyz), -1);\n rb_define_method(sr_cVertex, \"to_a\", RUBY_METHOD_FUNC(siren_vertex_xyz), -1);\n rb_define_method(sr_cVertex, \"to_v\", RUBY_METHOD_FUNC(siren_vertex_to_v), -1);\n return true;\n}\n\nVALUE siren_vertex_init(int argc, VALUE* argv, VALUE self)\n{\n VALUE* a;\n VALUE len;\n rb_scan_args(argc, argv, \"*\", &a, &len);\n\n Standard_Real x = 0.0, y = 0.0, z = 0.0;\n if (len > 0 && rb_array_p(a[0])) {\n gp_Pnt p = siren_ary_to_pnt(a[0]);\n x = p.X(); y = p.Y(); z = p.Z();\n }\n else {\n if (len >= 1) {\n if (FIXNUM_P(a[0]))\n x = DBL2NUM(a[0]);\n else if (RB_FLOAT_TYPE_P(a[0]))\n x = VALUE(a[0]);\n }\n if (len >= 2) {\n if (FIXNUM_P(a[1]))\n y = DBL2NUM(a[1]);\n else if (RB_FLOAT_TYPE_P(a[1]))\n y = VALUE(a[1]);\n }\n if (len >= 3) {\n if (FIXNUM_P(a[2]))\n z = DBL2NUM(a[2]);\n else if (RB_FLOAT_TYPE_P(a[2]))\n z = VALUE(a[2]);\n }\n }\n TopoDS_Vertex v = BRepBuilderAPI_MakeVertex(gp_Pnt(x, y, z));\n auto p = siren_shape_get(self);\n *p = v;\n return self;\n}\n\nVALUE siren_vertex_xyz(int argc, VALUE* argv, VALUE self)\n{\n TopoDS_Vertex vertex = siren_vertex_get(self);\n return siren_pnt_to_ary(BRep_Tool::Pnt(vertex));\n}\n\nVALUE siren_vertex_to_v(int argc, VALUE* argv, VALUE self)\n{\n TopoDS_Vertex vertex = siren_vertex_get(self);\n gp_Pnt p = BRep_Tool::Pnt(vertex);\n return siren_vec_new(p.X(), p.Y(), p.Z());\n}\nUpdate Siren::Vertex#initialize method.#include \"shape\/vertex.h\"\n\n#define rb_array_p(x) RB_TYPE_P(x, T_ARRAY)\n\nVALUE sr_cVertex;\n\nSR_SHAPE_GET(Vertex, vertex)\nSR_SHAPE_CHECK(Vertex, vertex)\n\nbool siren_vertex_install()\n{\n SR_SHAPE_INIT(Vertex)\n rb_define_method(sr_cVertex, \"initialize\", RUBY_METHOD_FUNC(siren_vertex_init), -1);\n rb_define_method(sr_cVertex, \"xyz\", RUBY_METHOD_FUNC(siren_vertex_xyz), -1);\n rb_define_method(sr_cVertex, \"to_a\", RUBY_METHOD_FUNC(siren_vertex_xyz), -1);\n rb_define_method(sr_cVertex, \"to_v\", RUBY_METHOD_FUNC(siren_vertex_to_v), -1);\n return true;\n}\n\nVALUE siren_vertex_init(int argc, VALUE* argv, VALUE self)\n{\n VALUE a, y, z;\n rb_scan_args(argc, argv, \"12\", &a, &y, &z);\n gp_Pnt pnt;\n if (argc == 1) {\n pnt = siren_ary_to_pnt(a);\n }\n else if (argc == 3) {\n pnt = gp_Pnt(NUM2DBL(a), NUM2DBL(y), NUM2DBL(z));\n }\n else {\n rb_raise(Qnil, \"wrong number of arguments specified.\");\n }\n TopoDS_Vertex v = BRepBuilderAPI_MakeVertex(pnt);\n auto p = siren_shape_get(self);\n *p = v;\n return self;\n}\n\nVALUE siren_vertex_xyz(int argc, VALUE* argv, VALUE self)\n{\n TopoDS_Vertex vertex = siren_vertex_get(self);\n return siren_pnt_to_ary(BRep_Tool::Pnt(vertex));\n}\n\nVALUE siren_vertex_to_v(int argc, VALUE* argv, VALUE self)\n{\n TopoDS_Vertex vertex = siren_vertex_get(self);\n gp_Pnt p = BRep_Tool::Pnt(vertex);\n return siren_vec_new(p.X(), p.Y(), p.Z());\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions Inc. 1990-2014. All rights reserved\n *\/\n\/\/ TEST Foundation::Memory\n#include \"Stroika\/Foundation\/StroikaPreComp.h\"\n\n#include \"Stroika\/Foundation\/Containers\/Mapping.h\"\n#include \"Stroika\/Foundation\/Debug\/Assertions.h\"\n#include \"Stroika\/Foundation\/Debug\/Trace.h\"\n\n#include \"Stroika\/Foundation\/Memory\/AnyVariantValue.h\"\n#include \"Stroika\/Foundation\/Memory\/Optional.h\"\n#include \"Stroika\/Foundation\/Memory\/SharedByValue.h\"\n\n#include \"..\/TestHarness\/SimpleClass.h\"\n#include \"..\/TestHarness\/TestHarness.h\"\n\n\n\n\nusing namespace Stroika;\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Memory;\n\n\n\/\/TODO: DOES IT EVEN NEED TO BE SAID? THese tests are a bit sparse ;-)\n\nnamespace {\n void Test1_Optional ()\n {\n {\n Optional x;\n VerifyTestResult (x.IsMissing ());\n x = 1;\n VerifyTestResult (not x.IsMissing ());\n VerifyTestResult (x.IsPresent ());\n VerifyTestResult (*x == 1);\n }\n {\n \/\/ Careful about self-assignment\n Optional x;\n x = 3;\n x = max (*x, 1);\n VerifyTestResult (x == 3);\n }\n }\n void Test2_SharedByValue ()\n {\n }\n void Test_4_Optional_Of_Mapping_Copy_Problem_ ()\n {\n using namespace Stroika::Foundation::Memory;\n using namespace Stroika::Foundation::Containers;\n Mapping ml1, ml2;\n ml1 = ml2;\n\n Optional> ol1, ol2;\n if (ol2.IsPresent ()) {\n ml1 = *ol2;\n }\n ol1 = ml1;\n Optional> xxxx2 (ml1);\n\n \/\/ fails to compile prior to 2013-09-09\n Optional> xxxx1 (ol1);\n \/\/ fails to compile prior to 2013-09-09\n ol1 = ol2;\n }\n void Test_5_AnyVariantValue_ ()\n {\n {\n VerifyTestResult (AnyVariantValue ().empty ());\n VerifyTestResult (not AnyVariantValue (1).empty ());\n VerifyTestResult (not AnyVariantValue (\"1\").empty ());\n \/\/VerifyTestResult (AnyVariantValue (\"1\").GetType () == typeid (\"1\")); \/\/ not sure why this fails but not worthy worrying about yet\n VerifyTestResult (AnyVariantValue (1).As () == 1);\n }\n {\n AnyVariantValue v;\n VerifyTestResult (v.empty ());\n v = AnyVariantValue (1);\n VerifyTestResult (not v.empty ());\n VerifyTestResult (v.GetType () == typeid (1));\n VerifyTestResult (v.As () == 1);\n v = AnyVariantValue (L\"a\");\n \/\/VerifyTestResult (v.GetType () == typeid (L\"a\")); \/\/ not sure why this fails but not worthy worrying about yet\n VerifyTestResult (not v.empty ());\n v.clear ();\n VerifyTestResult (v.empty ());\n VerifyTestResult (v.GetType () == typeid (void));\n }\n {\n struct JIM {\n int a;\n };\n AnyVariantValue v;\n VerifyTestResult (v.empty ());\n v = AnyVariantValue (JIM ());\n VerifyTestResult (v.GetType () == typeid (JIM));\n }\n {\n AnyVariantValue v;\n VerifyTestResult (v.empty ());\n v = AnyVariantValue (1);\n v = v;\n VerifyTestResult (v.GetType () == typeid (1));\n VerifyTestResult (v.As () == 1);\n v = AnyVariantValue (v);\n VerifyTestResult (v.GetType () == typeid (1));\n VerifyTestResult (v.As () == 1);\n }\n {\n static int nCopies = 0;\n struct Copyable {\n Copyable ()\n {\n ++nCopies;\n }\n Copyable (const Copyable&)\n {\n ++nCopies;\n }\n ~Copyable ()\n {\n --nCopies;\n }\n const Copyable& operator= (const Copyable&) = delete;\n };\n {\n AnyVariantValue v;\n VerifyTestResult (v.empty ());\n v = AnyVariantValue (Copyable ());\n v = v;\n v = AnyVariantValue (AnyVariantValue (v));\n v = AnyVariantValue (AnyVariantValue (Copyable ()));\n VerifyTestResult (v.GetType () == typeid (Copyable));\n }\n VerifyTestResult (0 == nCopies);\n }\n }\n}\n\n\nnamespace {\n\n void DoRegressionTests_ ()\n {\n Test1_Optional ();\n Test2_SharedByValue ();\n Test_4_Optional_Of_Mapping_Copy_Problem_ ();\n Test_5_AnyVariantValue_ ();\n }\n}\n\n\n\nint main (int argc, const char* argv[])\n{\n Stroika::TestHarness::Setup ();\n Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);\n return EXIT_SUCCESS;\n}\n\n\n\nadded testOptionalOfThingNotCopyable()\/*\n * Copyright(c) Sophist Solutions Inc. 1990-2014. All rights reserved\n *\/\n\/\/ TEST Foundation::Memory\n#include \"Stroika\/Foundation\/StroikaPreComp.h\"\n\n#include \"Stroika\/Foundation\/Containers\/Mapping.h\"\n#include \"Stroika\/Foundation\/Debug\/Assertions.h\"\n#include \"Stroika\/Foundation\/Debug\/Trace.h\"\n\n#include \"Stroika\/Foundation\/Memory\/AnyVariantValue.h\"\n#include \"Stroika\/Foundation\/Memory\/Optional.h\"\n#include \"Stroika\/Foundation\/Memory\/SharedByValue.h\"\n\n#include \"..\/TestHarness\/SimpleClass.h\"\n#include \"..\/TestHarness\/TestHarness.h\"\n\n\n\n\nusing namespace Stroika;\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Memory;\n\n\n\/\/TODO: DOES IT EVEN NEED TO BE SAID? THese tests are a bit sparse ;-)\n\nnamespace {\n void Test1_Optional ()\n {\n {\n Optional x;\n VerifyTestResult (x.IsMissing ());\n x = 1;\n VerifyTestResult (not x.IsMissing ());\n VerifyTestResult (x.IsPresent ());\n VerifyTestResult (*x == 1);\n }\n {\n \/\/ Careful about self-assignment\n Optional x;\n x = 3;\n x = max (*x, 1);\n VerifyTestResult (x == 3);\n }\n\t\tauto testOptionalOfThingNotCopyable = [] () {\n\t\t\tstruct NotCopyable {\n\t\t\t\tNotCopyable () {}\n\t\t\t\tNotCopyable (const NotCopyable&&) {}\t\/\/ but is moveable!\n\t\t\t\tNotCopyable (const NotCopyable&) = delete;\n\t\t\t\tconst NotCopyable& operator= (const NotCopyable&) = delete;\n\t\t\t};\n\t\t\tOptional\tn1;\n\t\t\tVerifyTestResult (n1.IsMissing ());\n\t\t\tOptional\tn2 (std::move (NotCopyable ()));\t\/\/ use r-value reference to move\n\t\t\tVerifyTestResult (n2.IsPresent ());\n\t\t};\n\t\ttestOptionalOfThingNotCopyable ();\n }\n void Test2_SharedByValue ()\n {\n }\n void Test_4_Optional_Of_Mapping_Copy_Problem_ ()\n {\n using namespace Stroika::Foundation::Memory;\n using namespace Stroika::Foundation::Containers;\n Mapping ml1, ml2;\n ml1 = ml2;\n\n Optional> ol1, ol2;\n if (ol2.IsPresent ()) {\n ml1 = *ol2;\n }\n ol1 = ml1;\n Optional> xxxx2 (ml1);\n\n \/\/ fails to compile prior to 2013-09-09\n Optional> xxxx1 (ol1);\n \/\/ fails to compile prior to 2013-09-09\n ol1 = ol2;\n }\n void Test_5_AnyVariantValue_ ()\n {\n {\n VerifyTestResult (AnyVariantValue ().empty ());\n VerifyTestResult (not AnyVariantValue (1).empty ());\n VerifyTestResult (not AnyVariantValue (\"1\").empty ());\n \/\/VerifyTestResult (AnyVariantValue (\"1\").GetType () == typeid (\"1\")); \/\/ not sure why this fails but not worthy worrying about yet\n VerifyTestResult (AnyVariantValue (1).As () == 1);\n }\n {\n AnyVariantValue v;\n VerifyTestResult (v.empty ());\n v = AnyVariantValue (1);\n VerifyTestResult (not v.empty ());\n VerifyTestResult (v.GetType () == typeid (1));\n VerifyTestResult (v.As () == 1);\n v = AnyVariantValue (L\"a\");\n \/\/VerifyTestResult (v.GetType () == typeid (L\"a\")); \/\/ not sure why this fails but not worthy worrying about yet\n VerifyTestResult (not v.empty ());\n v.clear ();\n VerifyTestResult (v.empty ());\n VerifyTestResult (v.GetType () == typeid (void));\n }\n {\n struct JIM {\n int a;\n };\n AnyVariantValue v;\n VerifyTestResult (v.empty ());\n v = AnyVariantValue (JIM ());\n VerifyTestResult (v.GetType () == typeid (JIM));\n }\n {\n AnyVariantValue v;\n VerifyTestResult (v.empty ());\n v = AnyVariantValue (1);\n v = v;\n VerifyTestResult (v.GetType () == typeid (1));\n VerifyTestResult (v.As () == 1);\n v = AnyVariantValue (v);\n VerifyTestResult (v.GetType () == typeid (1));\n VerifyTestResult (v.As () == 1);\n }\n {\n static int nCopies = 0;\n struct Copyable {\n Copyable ()\n {\n ++nCopies;\n }\n Copyable (const Copyable&)\n {\n ++nCopies;\n }\n ~Copyable ()\n {\n --nCopies;\n }\n const Copyable& operator= (const Copyable&) = delete;\n };\n {\n AnyVariantValue v;\n VerifyTestResult (v.empty ());\n v = AnyVariantValue (Copyable ());\n v = v;\n v = AnyVariantValue (AnyVariantValue (v));\n v = AnyVariantValue (AnyVariantValue (Copyable ()));\n VerifyTestResult (v.GetType () == typeid (Copyable));\n }\n VerifyTestResult (0 == nCopies);\n }\n }\n}\n\n\nnamespace {\n\n void DoRegressionTests_ ()\n {\n Test1_Optional ();\n Test2_SharedByValue ();\n Test_4_Optional_Of_Mapping_Copy_Problem_ ();\n Test_5_AnyVariantValue_ ();\n }\n}\n\n\n\nint main (int argc, const char* argv[])\n{\n Stroika::TestHarness::Setup ();\n Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);\n return EXIT_SUCCESS;\n}\n\n\n\n<|endoftext|>"} {"text":"\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXQt - a lightweight, Qt based, desktop toolset\n * https:\/\/lxqt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n * Alexander Sokoloff \n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n\n#include \"plugin.h\"\n#include \"ilxqtpanelplugin.h\"\n#include \"pluginsettings_p.h\"\n#include \"lxqtpanel.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n\/\/ statically linked built-in plugins\n#if defined(WITH_DESKTOPSWITCH_PLUGIN)\n#include \"..\/plugin-desktopswitch\/desktopswitch.h\" \/\/ desktopswitch\nextern void * loadPluginTranslation_desktopswitch_helper;\n#endif\n#if defined(WITH_MAINMENU_PLUGIN)\n#include \"..\/plugin-mainmenu\/lxqtmainmenu.h\" \/\/ mainmenu\nextern void * loadPluginTranslation_mainmenu_helper;\n#endif\n#if defined(WITH_QUICKLAUNCH_PLUGIN)\n#include \"..\/plugin-quicklaunch\/lxqtquicklaunchplugin.h\" \/\/ quicklaunch\nextern void * loadPluginTranslation_quicklaunch_helper;\n#endif\n#if defined(WITH_SHOWDESKTOP_PLUGIN)\n#include \"..\/plugin-showdesktop\/showdesktop.h\" \/\/ showdesktop\nextern void * loadPluginTranslation_showdesktop_helper;\n#endif\n#if defined(WITH_SPACER_PLUGIN)\n#include \"..\/plugin-spacer\/spacer.h\" \/\/ spacer\nextern void * loadPluginTranslation_spacer_helper;\n#endif\n#if defined(WITH_STATUSNOTIFIER_PLUGIN)\n#include \"..\/plugin-statusnotifier\/statusnotifier.h\" \/\/ statusnotifier\nextern void * loadPluginTranslation_statusnotifier_helper;\n#endif\n#if defined(WITH_TASKBAR_PLUGIN)\n#include \"..\/plugin-taskbar\/lxqttaskbarplugin.h\" \/\/ taskbar\nextern void * loadPluginTranslation_taskbar_helper;\n#endif\n#if defined(WITH_TRAY_PLUGIN)\n#include \"..\/plugin-tray\/lxqttrayplugin.h\" \/\/ tray\nextern void * loadPluginTranslation_tray_helper;\n#endif\n#if defined(WITH_WORLDCLOCK_PLUGIN)\n#include \"..\/plugin-worldclock\/lxqtworldclock.h\" \/\/ worldclock\nextern void * loadPluginTranslation_worldclock_helper;\n#endif\n\nQColor Plugin::mMoveMarkerColor= QColor(255, 0, 0, 255);\n\n\/************************************************\n\n ************************************************\/\nPlugin::Plugin(const LXQt::PluginInfo &desktopFile, LXQt::Settings *settings, const QString &settingsGroup, LXQtPanel *panel) :\n QFrame(panel),\n mDesktopFile(desktopFile),\n mPluginLoader(0),\n mPlugin(0),\n mPluginWidget(0),\n mAlignment(AlignLeft),\n mPanel(panel)\n{\n mSettings = PluginSettingsFactory::create(settings, settingsGroup);\n\n setWindowTitle(desktopFile.name());\n mName = desktopFile.name();\n\n QStringList dirs;\n dirs << QProcessEnvironment::systemEnvironment().value(\"LXQTPANEL_PLUGIN_PATH\").split(\":\");\n dirs << PLUGIN_DIR;\n\n bool found = false;\n if(ILXQtPanelPluginLibrary const * pluginLib = findStaticPlugin(desktopFile.id()))\n {\n \/\/ this is a static plugin\n found = true;\n loadLib(pluginLib);\n }\n else {\n \/\/ this plugin is a dynamically loadable module\n QString baseName = QString(\"lib%1.so\").arg(desktopFile.id());\n for(const QString &dirName : qAsConst(dirs))\n {\n QFileInfo fi(QDir(dirName), baseName);\n if (fi.exists())\n {\n found = true;\n if (loadModule(fi.absoluteFilePath()))\n break;\n }\n }\n }\n\n if (!isLoaded())\n {\n if (!found)\n qWarning() << QString(\"Plugin %1 not found in the\").arg(desktopFile.id()) << dirs;\n\n return;\n }\n\n setObjectName(mPlugin->themeId() + \"Plugin\");\n\n \/\/ plugin handle for easy context menu\n setProperty(\"NeedsHandle\", mPlugin->flags().testFlag(ILXQtPanelPlugin::NeedsHandle));\n\n QString s = mSettings->value(\"alignment\").toString();\n\n \/\/ Retrun default value\n if (s.isEmpty())\n {\n mAlignment = (mPlugin->flags().testFlag(ILXQtPanelPlugin::PreferRightAlignment)) ?\n Plugin::AlignRight :\n Plugin::AlignLeft;\n }\n else\n {\n mAlignment = (s.toUpper() == \"RIGHT\") ?\n Plugin::AlignRight :\n Plugin::AlignLeft;\n\n }\n\n if (mPluginWidget)\n {\n QGridLayout* layout = new QGridLayout(this);\n layout->setSpacing(0);\n layout->setContentsMargins(0, 0, 0, 0);\n setLayout(layout);\n layout->addWidget(mPluginWidget, 0, 0);\n }\n\n saveSettings();\n\n \/\/ delay the connection to settingsChanged to avoid conflicts\n \/\/ while the plugin is still being initialized\n connect(mSettings, &PluginSettings::settingsChanged,\n this, &Plugin::settingsChanged);\n}\n\n\n\/************************************************\n\n ************************************************\/\nPlugin::~Plugin()\n{\n delete mPlugin;\n delete mPluginLoader;\n delete mSettings;\n}\n\nvoid Plugin::setAlignment(Plugin::Alignment alignment)\n{\n mAlignment = alignment;\n saveSettings();\n}\n\n\n\/************************************************\n\n ************************************************\/\nnamespace\n{\n \/\/helper types for static plugins storage & binary search\n typedef std::unique_ptr plugin_ptr_t;\n typedef std::tuple plugin_tuple_t;\n\n \/\/NOTE: Please keep the plugins sorted by name while adding new plugins.\n \/\/NOTE2: we need to reference some (dummy) symbol from (autogenerated) LXQtPluginTranslationLoader.cpp\n \/\/ to be not stripped (as unused\/unreferenced) in static linking time\n static plugin_tuple_t const static_plugins[] = {\n#if defined(WITH_DESKTOPSWITCH_PLUGIN)\n std::make_tuple(QLatin1String(\"desktopswitch\"), plugin_ptr_t{new DesktopSwitchPluginLibrary}, loadPluginTranslation_desktopswitch_helper),\/\/ desktopswitch\n#endif\n#if defined(WITH_MAINMENU_PLUGIN)\n std::make_tuple(QLatin1String(\"mainmenu\"), plugin_ptr_t{new LXQtMainMenuPluginLibrary}, loadPluginTranslation_mainmenu_helper),\/\/ mainmenu\n#endif\n#if defined(WITH_QUICKLAUNCH_PLUGIN)\n std::make_tuple(QLatin1String(\"quicklaunch\"), plugin_ptr_t{new LXQtQuickLaunchPluginLibrary}, loadPluginTranslation_quicklaunch_helper),\/\/ quicklaunch\n#endif\n#if defined(WITH_SHOWDESKTOP_PLUGIN)\n std::make_tuple(QLatin1String(\"showdesktop\"), plugin_ptr_t{new ShowDesktopLibrary}, loadPluginTranslation_showdesktop_helper),\/\/ showdesktop\n#endif\n#if defined(WITH_SPACER_PLUGIN)\n std::make_tuple(QLatin1String(\"spacer\"), plugin_ptr_t{new SpacerPluginLibrary}, loadPluginTranslation_spacer_helper),\/\/ spacer\n#endif\n#if defined(WITH_STATUSNOTIFIER_PLUGIN)\n std::make_tuple(QLatin1String(\"statusnotifier\"), plugin_ptr_t{new StatusNotifierLibrary}, loadPluginTranslation_statusnotifier_helper),\/\/ statusnotifier\n#endif\n#if defined(WITH_TASKBAR_PLUGIN)\n std::make_tuple(QLatin1String(\"taskbar\"), plugin_ptr_t{new LXQtTaskBarPluginLibrary}, loadPluginTranslation_taskbar_helper),\/\/ taskbar\n#endif\n#if defined(WITH_TRAY_PLUGIN)\n std::make_tuple(QLatin1String(\"tray\"), plugin_ptr_t{new LXQtTrayPluginLibrary}, loadPluginTranslation_tray_helper),\/\/ tray\n#endif\n#if defined(WITH_WORLDCLOCK_PLUGIN)\n std::make_tuple(QLatin1String(\"worldclock\"), plugin_ptr_t{new LXQtWorldClockLibrary}, loadPluginTranslation_worldclock_helper),\/\/ worldclock\n#endif\n };\n static constexpr plugin_tuple_t const * const plugins_begin = static_plugins;\n static constexpr plugin_tuple_t const * const plugins_end = static_plugins + sizeof (static_plugins) \/ sizeof (static_plugins[0]);\n\n struct assert_helper\n {\n assert_helper()\n {\n Q_ASSERT(std::is_sorted(plugins_begin, plugins_end\n , [] (plugin_tuple_t const & p1, plugin_tuple_t const & p2) -> bool { return std::get<0>(p1) < std::get<0>(p2); }));\n }\n };\n static assert_helper h;\n}\n\nILXQtPanelPluginLibrary const * Plugin::findStaticPlugin(const QString &libraryName)\n{\n \/\/ find a static plugin library by name -> binary search\n plugin_tuple_t const * plugin = std::lower_bound(plugins_begin, plugins_end, libraryName\n , [] (plugin_tuple_t const & plugin, QString const & name) -> bool { return std::get<0>(plugin) < name; });\n if (plugins_end != plugin && libraryName == std::get<0>(*plugin))\n return std::get<1>(*plugin).get();\n return nullptr;\n}\n\n\/\/ load a plugin from a library\nbool Plugin::loadLib(ILXQtPanelPluginLibrary const * pluginLib)\n{\n ILXQtPanelPluginStartupInfo startupInfo;\n startupInfo.settings = mSettings;\n startupInfo.desktopFile = &mDesktopFile;\n startupInfo.lxqtPanel = mPanel;\n\n mPlugin = pluginLib->instance(startupInfo);\n if (!mPlugin)\n {\n qWarning() << QString(\"Can't load plugin \\\"%1\\\". Plugin can't build ILXQtPanelPlugin.\").arg(mDesktopFile.id());\n return false;\n }\n\n mPluginWidget = mPlugin->widget();\n if (mPluginWidget)\n {\n mPluginWidget->setObjectName(mPlugin->themeId());\n watchWidgets(mPluginWidget);\n }\n this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n return true;\n}\n\n\/\/ load dynamic plugin from a *.so module\nbool Plugin::loadModule(const QString &libraryName)\n{\n mPluginLoader = new QPluginLoader(libraryName);\n\n if (!mPluginLoader->load())\n {\n qWarning() << mPluginLoader->errorString();\n return false;\n }\n\n QObject *obj = mPluginLoader->instance();\n if (!obj)\n {\n qWarning() << mPluginLoader->errorString();\n return false;\n }\n\n ILXQtPanelPluginLibrary* pluginLib= qobject_cast(obj);\n if (!pluginLib)\n {\n qWarning() << QString(\"Can't load plugin \\\"%1\\\". Plugin is not a ILXQtPanelPluginLibrary.\").arg(mPluginLoader->fileName());\n delete obj;\n return false;\n }\n return loadLib(pluginLib);\n}\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::watchWidgets(QObject * const widget)\n{\n \/\/ the QWidget might not be fully constructed yet, but we can rely on the isWidgetType()\n if (!widget->isWidgetType())\n return;\n widget->installEventFilter(this);\n \/\/ watch also children (recursive)\n for (auto const & child : widget->children())\n {\n watchWidgets(child);\n }\n}\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::unwatchWidgets(QObject * const widget)\n{\n widget->removeEventFilter(this);\n \/\/ unwatch also children (recursive)\n for (auto const & child : widget->children())\n {\n unwatchWidgets(child);\n }\n}\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::settingsChanged()\n{\n mPlugin->settingsChanged();\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::saveSettings()\n{\n mSettings->setValue(\"alignment\", (mAlignment == AlignLeft) ? \"Left\" : \"Right\");\n mSettings->setValue(\"type\", mDesktopFile.id());\n mSettings->sync();\n\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::contextMenuEvent(QContextMenuEvent * \/*event*\/)\n{\n mPanel->showPopupMenu(this);\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::mousePressEvent(QMouseEvent *event)\n{\n switch (event->button())\n {\n case Qt::LeftButton:\n mPlugin->activated(ILXQtPanelPlugin::Trigger);\n break;\n\n case Qt::MidButton:\n mPlugin->activated(ILXQtPanelPlugin::MiddleClick);\n break;\n\n default:\n break;\n }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::mouseDoubleClickEvent(QMouseEvent*)\n{\n mPlugin->activated(ILXQtPanelPlugin::DoubleClick);\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::showEvent(QShowEvent *)\n{\n if (mPluginWidget)\n mPluginWidget->adjustSize();\n}\n\n\n\/************************************************\n\n ************************************************\/\nQMenu *Plugin::popupMenu() const\n{\n QString name = this->name().replace(\"&\", \"&&\");\n QMenu* menu = new QMenu(windowTitle());\n\n if (mPlugin->flags().testFlag(ILXQtPanelPlugin::HaveConfigDialog))\n {\n QAction* configAction = new QAction(\n XdgIcon::fromTheme(QLatin1String(\"preferences-other\")),\n tr(\"Configure \\\"%1\\\"\").arg(name), menu);\n menu->addAction(configAction);\n connect(configAction, SIGNAL(triggered()), this, SLOT(showConfigureDialog()));\n }\n\n QAction* moveAction = new QAction(XdgIcon::fromTheme(\"transform-move\"), tr(\"Move \\\"%1\\\"\").arg(name), menu);\n menu->addAction(moveAction);\n connect(moveAction, SIGNAL(triggered()), this, SIGNAL(startMove()));\n\n menu->addSeparator();\n\n QAction* removeAction = new QAction(\n XdgIcon::fromTheme(QLatin1String(\"list-remove\")),\n tr(\"Remove \\\"%1\\\"\").arg(name), menu);\n menu->addAction(removeAction);\n connect(removeAction, SIGNAL(triggered()), this, SLOT(requestRemove()));\n\n return menu;\n}\n\n\n\/************************************************\n\n ************************************************\/\nbool Plugin::isSeparate() const\n{\n return mPlugin->isSeparate();\n}\n\n\n\/************************************************\n\n ************************************************\/\nbool Plugin::isExpandable() const\n{\n return mPlugin->isExpandable();\n}\n\n\n\/************************************************\n\n ************************************************\/\nbool Plugin::eventFilter(QObject * \/*watched*\/, QEvent * event)\n{\n switch (event->type())\n {\n case QEvent::DragLeave:\n emit dragLeft();\n break;\n case QEvent::ChildAdded:\n watchWidgets(dynamic_cast(event)->child());\n break;\n case QEvent::ChildRemoved:\n unwatchWidgets(dynamic_cast(event)->child());\n break;\n default:\n break;\n }\n return false;\n}\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::realign()\n{\n if (mPlugin)\n mPlugin->realign();\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::showConfigureDialog()\n{\n if (!mConfigDialog)\n mConfigDialog = mPlugin->configureDialog();\n\n if (!mConfigDialog)\n return;\n\n connect(this, &Plugin::destroyed, mConfigDialog.data(), &QWidget::close);\n mPanel->willShowWindow(mConfigDialog);\n mConfigDialog->show();\n mConfigDialog->raise();\n mConfigDialog->activateWindow();\n\n WId wid = mConfigDialog->windowHandle()->winId();\n KWindowSystem::activateWindow(wid);\n KWindowSystem::setOnDesktop(wid, KWindowSystem::currentDesktop());\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::requestRemove()\n{\n emit remove();\n deleteLater();\n}\nFix a FTBFS when some plugins are not built\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXQt - a lightweight, Qt based, desktop toolset\n * https:\/\/lxqt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n * Alexander Sokoloff \n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n\n#include \"plugin.h\"\n#include \"ilxqtpanelplugin.h\"\n#include \"pluginsettings_p.h\"\n#include \"lxqtpanel.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n\/\/ statically linked built-in plugins\n#if defined(WITH_DESKTOPSWITCH_PLUGIN)\n#include \"..\/plugin-desktopswitch\/desktopswitch.h\" \/\/ desktopswitch\nextern void * loadPluginTranslation_desktopswitch_helper;\n#endif\n#if defined(WITH_MAINMENU_PLUGIN)\n#include \"..\/plugin-mainmenu\/lxqtmainmenu.h\" \/\/ mainmenu\nextern void * loadPluginTranslation_mainmenu_helper;\n#endif\n#if defined(WITH_QUICKLAUNCH_PLUGIN)\n#include \"..\/plugin-quicklaunch\/lxqtquicklaunchplugin.h\" \/\/ quicklaunch\nextern void * loadPluginTranslation_quicklaunch_helper;\n#endif\n#if defined(WITH_SHOWDESKTOP_PLUGIN)\n#include \"..\/plugin-showdesktop\/showdesktop.h\" \/\/ showdesktop\nextern void * loadPluginTranslation_showdesktop_helper;\n#endif\n#if defined(WITH_SPACER_PLUGIN)\n#include \"..\/plugin-spacer\/spacer.h\" \/\/ spacer\nextern void * loadPluginTranslation_spacer_helper;\n#endif\n#if defined(WITH_STATUSNOTIFIER_PLUGIN)\n#include \"..\/plugin-statusnotifier\/statusnotifier.h\" \/\/ statusnotifier\nextern void * loadPluginTranslation_statusnotifier_helper;\n#endif\n#if defined(WITH_TASKBAR_PLUGIN)\n#include \"..\/plugin-taskbar\/lxqttaskbarplugin.h\" \/\/ taskbar\nextern void * loadPluginTranslation_taskbar_helper;\n#endif\n#if defined(WITH_TRAY_PLUGIN)\n#include \"..\/plugin-tray\/lxqttrayplugin.h\" \/\/ tray\nextern void * loadPluginTranslation_tray_helper;\n#endif\n#if defined(WITH_WORLDCLOCK_PLUGIN)\n#include \"..\/plugin-worldclock\/lxqtworldclock.h\" \/\/ worldclock\nextern void * loadPluginTranslation_worldclock_helper;\n#endif\n\nQColor Plugin::mMoveMarkerColor= QColor(255, 0, 0, 255);\n\n\/************************************************\n\n ************************************************\/\nPlugin::Plugin(const LXQt::PluginInfo &desktopFile, LXQt::Settings *settings, const QString &settingsGroup, LXQtPanel *panel) :\n QFrame(panel),\n mDesktopFile(desktopFile),\n mPluginLoader(0),\n mPlugin(0),\n mPluginWidget(0),\n mAlignment(AlignLeft),\n mPanel(panel)\n{\n mSettings = PluginSettingsFactory::create(settings, settingsGroup);\n\n setWindowTitle(desktopFile.name());\n mName = desktopFile.name();\n\n QStringList dirs;\n dirs << QProcessEnvironment::systemEnvironment().value(\"LXQTPANEL_PLUGIN_PATH\").split(\":\");\n dirs << PLUGIN_DIR;\n\n bool found = false;\n if(ILXQtPanelPluginLibrary const * pluginLib = findStaticPlugin(desktopFile.id()))\n {\n \/\/ this is a static plugin\n found = true;\n loadLib(pluginLib);\n }\n else {\n \/\/ this plugin is a dynamically loadable module\n QString baseName = QString(\"lib%1.so\").arg(desktopFile.id());\n for(const QString &dirName : qAsConst(dirs))\n {\n QFileInfo fi(QDir(dirName), baseName);\n if (fi.exists())\n {\n found = true;\n if (loadModule(fi.absoluteFilePath()))\n break;\n }\n }\n }\n\n if (!isLoaded())\n {\n if (!found)\n qWarning() << QString(\"Plugin %1 not found in the\").arg(desktopFile.id()) << dirs;\n\n return;\n }\n\n setObjectName(mPlugin->themeId() + \"Plugin\");\n\n \/\/ plugin handle for easy context menu\n setProperty(\"NeedsHandle\", mPlugin->flags().testFlag(ILXQtPanelPlugin::NeedsHandle));\n\n QString s = mSettings->value(\"alignment\").toString();\n\n \/\/ Retrun default value\n if (s.isEmpty())\n {\n mAlignment = (mPlugin->flags().testFlag(ILXQtPanelPlugin::PreferRightAlignment)) ?\n Plugin::AlignRight :\n Plugin::AlignLeft;\n }\n else\n {\n mAlignment = (s.toUpper() == \"RIGHT\") ?\n Plugin::AlignRight :\n Plugin::AlignLeft;\n\n }\n\n if (mPluginWidget)\n {\n QGridLayout* layout = new QGridLayout(this);\n layout->setSpacing(0);\n layout->setContentsMargins(0, 0, 0, 0);\n setLayout(layout);\n layout->addWidget(mPluginWidget, 0, 0);\n }\n\n saveSettings();\n\n \/\/ delay the connection to settingsChanged to avoid conflicts\n \/\/ while the plugin is still being initialized\n connect(mSettings, &PluginSettings::settingsChanged,\n this, &Plugin::settingsChanged);\n}\n\n\n\/************************************************\n\n ************************************************\/\nPlugin::~Plugin()\n{\n delete mPlugin;\n delete mPluginLoader;\n delete mSettings;\n}\n\nvoid Plugin::setAlignment(Plugin::Alignment alignment)\n{\n mAlignment = alignment;\n saveSettings();\n}\n\n\n\/************************************************\n\n ************************************************\/\nnamespace\n{\n \/\/helper types for static plugins storage & binary search\n typedef std::unique_ptr plugin_ptr_t;\n typedef std::tuple plugin_tuple_t;\n\n \/\/NOTE: Please keep the plugins sorted by name while adding new plugins.\n \/\/NOTE2: we need to reference some (dummy) symbol from (autogenerated) LXQtPluginTranslationLoader.cpp\n \/\/ to be not stripped (as unused\/unreferenced) in static linking time\n static plugin_tuple_t const static_plugins[] = {\n#if defined(WITH_DESKTOPSWITCH_PLUGIN)\n std::make_tuple(QLatin1String(\"desktopswitch\"), plugin_ptr_t{new DesktopSwitchPluginLibrary}, loadPluginTranslation_desktopswitch_helper),\/\/ desktopswitch\n#endif\n#if defined(WITH_MAINMENU_PLUGIN)\n std::make_tuple(QLatin1String(\"mainmenu\"), plugin_ptr_t{new LXQtMainMenuPluginLibrary}, loadPluginTranslation_mainmenu_helper),\/\/ mainmenu\n#endif\n#if defined(WITH_QUICKLAUNCH_PLUGIN)\n std::make_tuple(QLatin1String(\"quicklaunch\"), plugin_ptr_t{new LXQtQuickLaunchPluginLibrary}, loadPluginTranslation_quicklaunch_helper),\/\/ quicklaunch\n#endif\n#if defined(WITH_SHOWDESKTOP_PLUGIN)\n std::make_tuple(QLatin1String(\"showdesktop\"), plugin_ptr_t{new ShowDesktopLibrary}, loadPluginTranslation_showdesktop_helper),\/\/ showdesktop\n#endif\n#if defined(WITH_SPACER_PLUGIN)\n std::make_tuple(QLatin1String(\"spacer\"), plugin_ptr_t{new SpacerPluginLibrary}, loadPluginTranslation_spacer_helper),\/\/ spacer\n#endif\n#if defined(WITH_STATUSNOTIFIER_PLUGIN)\n std::make_tuple(QLatin1String(\"statusnotifier\"), plugin_ptr_t{new StatusNotifierLibrary}, loadPluginTranslation_statusnotifier_helper),\/\/ statusnotifier\n#endif\n#if defined(WITH_TASKBAR_PLUGIN)\n std::make_tuple(QLatin1String(\"taskbar\"), plugin_ptr_t{new LXQtTaskBarPluginLibrary}, loadPluginTranslation_taskbar_helper),\/\/ taskbar\n#endif\n#if defined(WITH_TRAY_PLUGIN)\n std::make_tuple(QLatin1String(\"tray\"), plugin_ptr_t{new LXQtTrayPluginLibrary}, loadPluginTranslation_tray_helper),\/\/ tray\n#endif\n#if defined(WITH_WORLDCLOCK_PLUGIN)\n std::make_tuple(QLatin1String(\"worldclock\"), plugin_ptr_t{new LXQtWorldClockLibrary}, loadPluginTranslation_worldclock_helper),\/\/ worldclock\n#endif\n };\n static constexpr plugin_tuple_t const * const plugins_begin = static_plugins;\n static constexpr plugin_tuple_t const * const plugins_end = static_plugins + sizeof (static_plugins) \/ sizeof (static_plugins[0]);\n\n struct assert_helper\n {\n assert_helper()\n {\n Q_ASSERT(std::is_sorted(plugins_begin, plugins_end\n , [] (plugin_tuple_t const & p1, plugin_tuple_t const & p2) -> bool { return std::get<0>(p1) < std::get<0>(p2); }));\n }\n };\n static assert_helper h;\n}\n\nILXQtPanelPluginLibrary const * Plugin::findStaticPlugin(const QString &libraryName)\n{\n \/\/ find a static plugin library by name -> binary search\n plugin_tuple_t const * plugin = std::lower_bound(plugins_begin, plugins_end, libraryName\n , [] (plugin_tuple_t const & plugin, QString const & name) -> bool { return std::get<0>(plugin) < name; });\n if (plugins_end != plugin && libraryName == std::get<0>(*plugin))\n return std::get<1>(*plugin).get();\n return nullptr;\n}\n\n\/\/ load a plugin from a library\nbool Plugin::loadLib(ILXQtPanelPluginLibrary const * pluginLib)\n{\n ILXQtPanelPluginStartupInfo startupInfo;\n startupInfo.settings = mSettings;\n startupInfo.desktopFile = &mDesktopFile;\n startupInfo.lxqtPanel = mPanel;\n\n mPlugin = pluginLib->instance(startupInfo);\n if (!mPlugin)\n {\n qWarning() << QString(\"Can't load plugin \\\"%1\\\". Plugin can't build ILXQtPanelPlugin.\").arg(mDesktopFile.id());\n return false;\n }\n\n mPluginWidget = mPlugin->widget();\n if (mPluginWidget)\n {\n mPluginWidget->setObjectName(mPlugin->themeId());\n watchWidgets(mPluginWidget);\n }\n this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n return true;\n}\n\n\/\/ load dynamic plugin from a *.so module\nbool Plugin::loadModule(const QString &libraryName)\n{\n mPluginLoader = new QPluginLoader(libraryName);\n\n if (!mPluginLoader->load())\n {\n qWarning() << mPluginLoader->errorString();\n return false;\n }\n\n QObject *obj = mPluginLoader->instance();\n if (!obj)\n {\n qWarning() << mPluginLoader->errorString();\n return false;\n }\n\n ILXQtPanelPluginLibrary* pluginLib= qobject_cast(obj);\n if (!pluginLib)\n {\n qWarning() << QString(\"Can't load plugin \\\"%1\\\". Plugin is not a ILXQtPanelPluginLibrary.\").arg(mPluginLoader->fileName());\n delete obj;\n return false;\n }\n return loadLib(pluginLib);\n}\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::watchWidgets(QObject * const widget)\n{\n \/\/ the QWidget might not be fully constructed yet, but we can rely on the isWidgetType()\n if (!widget->isWidgetType())\n return;\n widget->installEventFilter(this);\n \/\/ watch also children (recursive)\n for (auto const & child : widget->children())\n {\n watchWidgets(child);\n }\n}\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::unwatchWidgets(QObject * const widget)\n{\n widget->removeEventFilter(this);\n \/\/ unwatch also children (recursive)\n for (auto const & child : widget->children())\n {\n unwatchWidgets(child);\n }\n}\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::settingsChanged()\n{\n mPlugin->settingsChanged();\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::saveSettings()\n{\n mSettings->setValue(\"alignment\", (mAlignment == AlignLeft) ? \"Left\" : \"Right\");\n mSettings->setValue(\"type\", mDesktopFile.id());\n mSettings->sync();\n\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::contextMenuEvent(QContextMenuEvent * \/*event*\/)\n{\n mPanel->showPopupMenu(this);\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::mousePressEvent(QMouseEvent *event)\n{\n switch (event->button())\n {\n case Qt::LeftButton:\n mPlugin->activated(ILXQtPanelPlugin::Trigger);\n break;\n\n case Qt::MidButton:\n mPlugin->activated(ILXQtPanelPlugin::MiddleClick);\n break;\n\n default:\n break;\n }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::mouseDoubleClickEvent(QMouseEvent*)\n{\n mPlugin->activated(ILXQtPanelPlugin::DoubleClick);\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::showEvent(QShowEvent *)\n{\n if (mPluginWidget)\n mPluginWidget->adjustSize();\n}\n\n\n\/************************************************\n\n ************************************************\/\nQMenu *Plugin::popupMenu() const\n{\n QString name = this->name().replace(\"&\", \"&&\");\n QMenu* menu = new QMenu(windowTitle());\n\n if (mPlugin->flags().testFlag(ILXQtPanelPlugin::HaveConfigDialog))\n {\n QAction* configAction = new QAction(\n XdgIcon::fromTheme(QLatin1String(\"preferences-other\")),\n tr(\"Configure \\\"%1\\\"\").arg(name), menu);\n menu->addAction(configAction);\n connect(configAction, SIGNAL(triggered()), this, SLOT(showConfigureDialog()));\n }\n\n QAction* moveAction = new QAction(XdgIcon::fromTheme(\"transform-move\"), tr(\"Move \\\"%1\\\"\").arg(name), menu);\n menu->addAction(moveAction);\n connect(moveAction, SIGNAL(triggered()), this, SIGNAL(startMove()));\n\n menu->addSeparator();\n\n QAction* removeAction = new QAction(\n XdgIcon::fromTheme(QLatin1String(\"list-remove\")),\n tr(\"Remove \\\"%1\\\"\").arg(name), menu);\n menu->addAction(removeAction);\n connect(removeAction, SIGNAL(triggered()), this, SLOT(requestRemove()));\n\n return menu;\n}\n\n\n\/************************************************\n\n ************************************************\/\nbool Plugin::isSeparate() const\n{\n return mPlugin->isSeparate();\n}\n\n\n\/************************************************\n\n ************************************************\/\nbool Plugin::isExpandable() const\n{\n return mPlugin->isExpandable();\n}\n\n\n\/************************************************\n\n ************************************************\/\nbool Plugin::eventFilter(QObject * \/*watched*\/, QEvent * event)\n{\n switch (event->type())\n {\n case QEvent::DragLeave:\n emit dragLeft();\n break;\n case QEvent::ChildAdded:\n watchWidgets(dynamic_cast(event)->child());\n break;\n case QEvent::ChildRemoved:\n unwatchWidgets(dynamic_cast(event)->child());\n break;\n default:\n break;\n }\n return false;\n}\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::realign()\n{\n if (mPlugin)\n mPlugin->realign();\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::showConfigureDialog()\n{\n if (!mConfigDialog)\n mConfigDialog = mPlugin->configureDialog();\n\n if (!mConfigDialog)\n return;\n\n connect(this, &Plugin::destroyed, mConfigDialog.data(), &QWidget::close);\n mPanel->willShowWindow(mConfigDialog);\n mConfigDialog->show();\n mConfigDialog->raise();\n mConfigDialog->activateWindow();\n\n WId wid = mConfigDialog->windowHandle()->winId();\n KWindowSystem::activateWindow(wid);\n KWindowSystem::setOnDesktop(wid, KWindowSystem::currentDesktop());\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Plugin::requestRemove()\n{\n emit remove();\n deleteLater();\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \"..\/include\/Game.h\"\n#include \"..\/include\/Common.h\"\n#include \"..\/include\/Console.h\"\n\n#include \"..\/include\/PlayerTypes\/PlayerTypes.h\"\n#include \"..\/include\/EnemyTypes\/EnemyTypes.h\"\n\n\nusing namespace std;\nusing namespace Common;\n\n\/\/ To avoid conflict with numeric_limits::max used in Game::GetChoice()\n#ifdef max\n#undef max\n#endif\n\n#define SKIP_TURN -2\n\nvoid Game::MainMenu(){\n \/\/ Main menu. Loops until you start\n \/\/ a game or quit.\n\t for (int choice=-1; choice!=0;){\n choice = GetChoice(MenuType::eMain);\n switch(choice){\n\t\t\tcase 1:\n \t\tStartGame();\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tHowToPlay();\n\t\t\t\tbreak;\n\t\t\tcase 0:\n\t\t\t\tbreak;\n }\n }\n}\n\nstring Game::InitializePlayerName() {\n\tClearScreen();\n\tstring name;\n\tcout << \"What is your name?\"\n\t\t<< endl << endl\n\t\t<< \"> \";\n\n cin.ignore();\n\tgetline(cin,name); \/\/ Change to full name\n\treturn name;\n}\n\nchar Game::InitializePlayerGender() {\n char gender;\n do {\n ClearScreen();\n cout << \"What is your gender (M or F)?\"\n << endl << endl\n << \"> \";\n\n cin >> gender;\n gender = toupper(gender);\n } while (gender != 'M' && gender != 'F');\n\n return gender;\n}\n\n\nint Game::InitializePlayerClass() {\n\t\/\/ Initializes the player's class through user choice.\n\tint player_class = 0;\n\tplayer_class = GetChoice(MenuType::ePlayerClass);\n\tSetPlayerClass(player_class);\n\treturn player_class;\n}\n\nvoid Game::SetPlayerClass(int player_class) {\n\t\/\/ Sets the Player class according to player code given.\n\tswitch (player_class) {\n\tcase 1:\n\t\t\/\/ Player's class is a warrior.\n\t\t_Player = new Warrior;\n\t\tbreak;\n\tcase 2:\n\t\t\/\/ Player's class is a rogue.\n\t\t_Player = new Rogue;\n\t\tbreak;\n\tcase 3:\n\t\t\/\/ Player's class is a healer.\n\t\t_Player = new Healer;\n\t\tbreak;\n\tcase 4:\n\t\t\/\/ Player's class is a debugger.\n\t\t\/\/ Used to easily defeat enemies. Only for development purposes.\n\t\t_Player = new Debugger;\n\t\tbreak;\n\tcase 5:\n\t\t\/\/ You are Saitama.\n\t\t\/\/ Do I have to explain??\n\t\t_Player = new Saitama;\n\t\tbreak;\n\tdefault:\n\t\t\/\/ If input does not equal any of the cases, the default class is a warrior.\n\t\t_Player = new Warrior;\n\t\tbreak;\n\t}\n}\n\nvoid Game::SetPlayerData(){\n\t\/* Data initialized in order of:\n\t* class code\n\t* name\n\t* level\n\t* experience\n\t* health\n\t* arrows\n\t* bombs\n\t* potions\n\t* whetstones\n\t* weaponstrength\n\t* coins\n\t*\/\n\n\tifstream ReadData;\n\tReadData.open(\"data.txt\");\n\n\t\/\/ Runs if user has never played the game before or data is not found.\n\tif (!ReadData) {\n\t\tReadData.close();\n\t\tofstream WriteData;\n\t\tWriteData.open(\"data.txt\");\n\n\t\tWriteData << InitializePlayerClass() << endl\n\t\t\t<< InitializePlayerName() << endl\n << InitializePlayerGender() << endl\n\t\t\t<< 1 << endl\n\t\t\t<< 0 << endl\n\t\t\t<< 100 << endl\n\t\t\t<< 10 << endl\n\t\t\t<< 1 << endl\n\t\t\t<< 1 << endl\n\t\t\t<< 1 << endl\n\t\t\t<< 100 << endl\n\t\t\t<< 0;\n\t\tWriteData.close();\n\t}\n\n\telse {\n\t\t\/\/ Initializes player type from class code given in data.txt\n\t\tint player_class;\n\t\tReadData >> player_class;\n\t\tSetPlayerClass(player_class);\n\t\tReadData.close();\n\t}\n}\n\nvoid Game::SetEnemy(){\n \/\/ Generates a random integer to determine class of the enemy.\n \/\/ The abstract class Enemy is morphed with one of its child classes.\n\n EnemyType selector = EnemyType(rand()%etNumEnemyTypes);\n switch(selector){\n\tcase etSlimeball:\n\t\/\/ Enemy is a slimeball.\n\t_Enemy = new Slimeball;\n break; \n case etCrab:\n \/\/ Enemy is a crab.\n _Enemy = new Crab;\n break;\n case etGiantCrab:\n \/\/ Enemy is a giant crab.\n _Enemy = new GiantCrab;\n break;\n case etSquid:\n \/\/ Enemy is a squid.\n _Enemy = new Squid;\n break;\n case etGiantSquid:\n \/\/ Enemy is a giant squid.\n _Enemy = new GiantSquid;\n break;\n\t\tcase etLich:\n\t\t\t\/\/ Enemy is a Lich\n\t\t\t_Enemy = new Lich;\n\t\t\tbreak;\n\t\tcase etMurloc:\n\t\t\t\/\/Enemy is a Murloc\n\t\t\t_Enemy = new Murloc;\n\t\t\tbreak;\n\t\tcase etPutnafer:\n\t\t\t\/\/ Enemy is a Putnafer\n\t\t\t_Enemy = new Putnafer;\n\t\t\tbreak;\n case etZombie:\n \/\/ Enemy is a Zombie\n _Enemy = new Zombie;\n break;\n\t\tcase etVampire:\n\t\t\t\/\/ Enemy is a Vampire\n\t\t\t_Enemy = new Vampire;\n\t\t\tbreak;\n\t\tcase etWerewolf:\n\t\t\t\/\/ Enemy is a Werewolf\n\t\t\t_Enemy = new Werewolf;\n\t\t\tbreak;\n\t\tcase etGoblin:\n\t\t\t\/\/ Enemy is a Goblin\n\t\t\t_Enemy = new Goblin;\n\t\t\tbreak;\n\t\tcase etGargoyle:\n\t\t\t\/\/ Enemy is a Goblin\n\t\t\t_Enemy = new Gargoyle;\n\t\t\tbreak;\n\t\tcase etCerberus:\n\t\t\t\/\/ Enemy is a Cerberus\n\t\t\t_Enemy = new Cerberus;\n\t\t\tbreak;\n\t\tcase etSkeleton:\n\t\t\t\/\/ Enemy is a Rat\n\t\t\t_Enemy = new Skeleton;\n\t\t\tbreak;\n\t\tcase etSmallRat:\n\t\t\t\/\/ Enemy is a Small Rat\n\t\t\t_Enemy = new SmallRat;\n\t\t\tbreak;\n default:\n \/\/ If the above cases do not match the selector for any reason,\n \/\/ the enemy defaults on the crab class.\n _Enemy = new Crab;\n break;\n }\n \/\/ Simply prints that the enemy's class was encountered.\n\tcout << _Enemy->GetIntro() << endl;\n\tSleep(SLEEP_MS);\n\tColourPrint(_Enemy->GetName(), Console::DarkGrey);\n cout << \" encountered!\" << endl << endl;\n Sleep(SLEEP_MS);\n}\n\nbool Game::PlayAgain(){\n \/\/ Returns a bool value to determine if the player wants to play again.\n\n char choice;\n cout << \"Keep going? (y\/n)\" << endl << endl;\n choice = (char)input();\n \/\/ Returns true if the player says yes (Y, y, 1).\n if (choice == 'y' || choice == 'Y' || choice == '1') return true;\n \/\/ Returns false otherwise, regardless of choice=='n'.\n return false;\n}\n\n\nvoid Game::Intermission(){\n \/\/ Saves game in case player unexpectedly quits (uses X instead of\n \/\/ in-game quit.\n _Player->SaveGame();\n\n \/\/ Loops until the player starts another battle or they quit (IsPlaying=false).\n for (int choice=0; IsPlaying;){\n ClearScreen();\n cout << \"*--------- Intermission ----------* \" << endl << endl;\n\n\t_Player->DisplayInventory();\n cout << \"1) Start battle\" << endl;\n cout << \"2) Store\" << endl;\n cout << \"3) Gamble\" << endl;\n\tcout << \"4) Use Item\" << endl;\n cout << \"0) Quit\" << endl << endl;\n\n choice = input();\n\n switch(choice){\n case 1:\n \/\/ Returns to StartGame()'s loop, calling Battle().\n return;\n case 2:\n \/\/ Goes to the store where the player can buy items.\n \/\/\/ Currently in working progress.\n _Store.StoreFront(_Player);\n break;\n case 3:\n \/\/ Goes to the gambling arena.\n \/\/ _Player is passed in to add items won to the player inventory.\n _Gambling.Gamble(_Player);\n break;\n\tcase 4:\n\t _Player->UseItem();\n\t _Player->SaveGame();\n\t break;\n case 0:\n \/\/ Breaks the loop in StartGame(), going back to MainMenu().\n IsPlaying=false;\n\t break;\n }\n }\n}\n\nvoid Game::StartGame(){\n \/\/ Starts the game by initializing values for a new game.\n\n \/\/ Seeds the random number generator for pseudo-random numbers.\n srand((unsigned int)time(NULL));\n IsPlaying=true;\n\n \/\/ SetPlayerData() initializes the variables in this end.\n ClearScreen();\n SetPlayerData();\n\n\t\/\/ This initializes the variables on the Player end.\n ClearScreen();\n _Player->SetPlayerData();\n\n\n \/\/ Loops while the game is still playing.\n \/\/ Alternates between battles and intermission (gambling, store, et)\n while(IsPlaying){\n\t\tIntermission();\n\t\tif (!IsPlaying)\n\t\t\tbreak;\n\t\tBattle();\n }\n\n \/\/ Saves the player's data to an external file before quitting.\n _Player->SaveGame();\n}\n\nvoid Game::Battle(){\n ClearScreen();\n \/\/ Uses random integers to determine class of the enemy.\n SetEnemy();\n\n \/\/ Loops the actual battle while playing.\n while(IsPlaying){\n ClearScreen();\n \/\/ Displays the name and health bar of the player and enemy.\n \/\/ The Enemy* argument is to display the enemy's\n \/\/ name. Explained more in _Player->DisplayHealthBar().\n _Player->DisplayHUD(_Enemy);\n _Enemy->DisplayHUD();\n\n\t\tint damagePlayer = _Player->Action();\n \/\/ Player's turn to attack Enemy or choose other action.\n\n\t\tif (damagePlayer != SKIP_TURN){\n\t\t\t_Enemy->TakeDamage(damagePlayer);\n\t\t\t\/\/ Pauses console and ignores user input for SLEEP_MS milliseconds.\n \t\tSleep(SLEEP_MS);\n\t\t}\n\n\n \/\/ Leaves battle if player chooses to.\n if (!IsPlaying){\n IsPlaying = true;\n return;\n }\n\n \/\/ Executes when the enemy's health is 0 or below.\n if (_Enemy->IsDead()){\n \/\/ Adds drops to player's inventory from defeated enemy.\n _Player->AddToInventory(_Enemy->GetDrops());\n \/\/ Adds points to player's experience.\n _Player->AddExperience(_Enemy->ReturnExperience());\n\t\t\t\/\/ Replenishes player's health for the next round.\n\t\t\t_Player->ReplenishHealth();\n\n\t\t\t\/\/ If player wants to battle again, it breaks the loop and uses tail recursion to play again.\n if (PlayAgain()) break;\n \/\/ Returns to StartGame()'s loop, and executes Intermission().\n return;\n }\n\n \/\/ Enemy's turn to attack player.\n\t\tif (damagePlayer != SKIP_TURN)\n\t\t\t_Player->TakeDamage(_Enemy->Action());\n Sleep(SLEEP_MS);\n\n \/\/ Executes when player's health is 0 or below.\n if (_Player->IsDead()){\n \/\/ Player loses the amount of experience points gained when you defeat the enemy.\n _Player->LoseExperience(_Enemy->ReturnExperience());\n\t\t\t\/\/ Replenishes player's health for the next round.\n\t\t\t_Player->ReplenishHealth();\n\n\t\t\tif (PlayAgain()) break;\n return;\n }\n }\n Battle();\n}\n\nvoid Game::HowToPlay() {\n\n\tGetChoice(MenuType::eHowToPlay);\n}\n\nint Game::GetChoice(MenuType menuType)\n{\n\tDisplayMenu(menuType);\n\tint choice = -1;\n\twhile (!(cin >> choice)) {\n\t\tcin.clear();\n\t\tcin.ignore(numeric_limits::max(), '\\n');\n\t\tcout << \"Invalid input. Please try again.\";\n\t\tSleep(SLEEP_MS);\n\t\tDisplayMenu(menuType);\n\t}\n\treturn choice;\n}\n\nvoid Game::DisplayMenu(MenuType menuType)\n{\n\tClearScreen();\n\tswitch (menuType)\n\t{\n\tcase Game::eMain:\n\t\tcout << \"========== TURN-BASED FIGHTING GAME ==========\" << endl << endl\n\t\t\t<< \"1) Start Game\" << endl\n\t\t\t<< \"2) How to play\" << endl\n\t\t\t<< \"0) Exit\" << endl << endl << \"> \";\n\t\tbreak;\n\tcase Game::ePlayerClass:\n\t\tcout << endl\n\t\t\t<< \"Which class do you want to play as?\" << endl\n\t\t\t<< \"1) Warrior (high damage, low healing capabilities)\" << endl\n\t\t\t<< \"2) Rogue (moderate damage, moderate healing capabilities)\" << endl\n\t\t\t<< \"3) Healer (low damage, high healing capabilities)\" << endl\n\t\t\t<< \"4) Debugger (INFINITE DAMAGE!!!!)\" << endl\n\t\t\t<< \"5) Saitama (self-explanatory)\" << endl\n\t\t\t<< endl << endl\n\t\t\t<< \"> \";\n\t\tbreak;\n\tcase Game::eHowToPlay:\n\t\tcout << \"============== HOW TO PLAY ==============\" << endl << endl\n\t\t\t<< \"Turn is a turn-based RPG game.\" << endl\n\t\t\t<< \"Create your character and start playing.\" << endl\n\t\t\t<< \"For playing you have to choose what to do by typing\" << endl\n\t\t\t<< \"the corresponding number.\" << endl\n\t\t\t<< \"You can perform actions and use items.\" << endl << endl\n\t\t\t<< \"-- Actions --\" << endl\n\t\t\t<< \"Attack: Regular attack\" << endl\n\t\t\t<< \"Risk Attack: Attack deals more damage, but with a chance of missing\" << endl\n\t\t\t<< \"Heal: Restore an amount of your HP\" << endl\n\t\t\t<< \"Flee: Run away from battle\" << endl << endl\n\t\t\t<< \"-- Items --\" << endl\n\t\t\t<< \"Bombs: Deals 50HP to your opponent with no chance of missing\" << endl\n\t\t\t<< \"Arrows: Deals 10-15HP to your opponent with no chance of missing\" << endl\n\t\t\t<< \"Potion: Replenishes your HP to 100\" << endl\n\t\t\t<< \"Whetstone: Restores your weapon's sharpness.\" << endl << endl\n\t\t\t<< \"Good luck and have fun!\" << endl << endl\n\t\t\t<< \"0) Quit\" << endl << endl << \"> \";\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\nUpdate Game.cpp#include \n#include \n#include \n#include \n#include \n\n#include \"..\/include\/Game.h\"\n#include \"..\/include\/Common.h\"\n#include \"..\/include\/Console.h\"\n\n#include \"..\/include\/PlayerTypes\/PlayerTypes.h\"\n#include \"..\/include\/EnemyTypes\/EnemyTypes.h\"\n\n\nusing namespace std;\nusing namespace Common;\n\n\/\/ To avoid conflict with numeric_limits::max used in Game::GetChoice()\n#ifdef max\n#undef max\n#endif\n\n#define SKIP_TURN -2\n\nvoid Game::MainMenu(){\n \/\/ Main menu. Loops until you start\n \/\/ a game or quit.\n\t for (int choice=-1; choice!=0;){\n choice = GetChoice(MenuType::eMain);\n switch(choice){\n\t\t\tcase 1:\n \t\tStartGame();\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tHowToPlay();\n\t\t\t\tbreak;\n\t\t\tcase 0:\n\t\t\t\tbreak;\n }\n }\n}\n\nstring Game::InitializePlayerName() {\n\tClearScreen();\n\tstring name;\n\tcout << \"What is your name?\"\n\t\t<< endl << endl\n\t\t<< \"> \";\n\n cin.ignore();\n\tgetline(cin,name); \/\/ Change to full name\n\treturn name;\n}\n\nchar Game::InitializePlayerGender() {\n char gender;\n do {\n ClearScreen();\n cout << \"What is your gender (M or F)?\"\n << endl << endl\n << \"> \";\n\n cin >> gender;\n gender = toupper(gender);\n } while (gender != 'M' && gender != 'F');\n\n return gender;\n}\n\n\nint Game::InitializePlayerClass() {\n\t\/\/ Initializes the player's class through user choice.\n\tint player_class = 0;\n\tplayer_class = GetChoice(MenuType::ePlayerClass);\n\tSetPlayerClass(player_class);\n\treturn player_class;\n}\n\nvoid Game::SetPlayerClass(int player_class) {\n\t\/\/ Sets the Player class according to player code given.\n\tswitch (player_class) {\n\tcase 1:\n\t\t\/\/ Player's class is a warrior.\n\t\t_Player = new Warrior;\n\t\tbreak;\n\tcase 2:\n\t\t\/\/ Player's class is a rogue.\n\t\t_Player = new Rogue;\n\t\tbreak;\n\tcase 3:\n\t\t\/\/ Player's class is a healer.\n\t\t_Player = new Healer;\n\t\tbreak;\n\tcase 4:\n\t\t\/\/ Player's class is a debugger.\n\t\t\/\/ Used to easily defeat enemies. Only for development purposes.\n\t\t_Player = new Debugger;\n\t\tbreak;\n\tcase 5:\n\t\t\/\/ You are Saitama.\n\t\t\/\/ Do I have to explain??\n\t\t_Player = new Saitama;\n\t\tbreak;\n\tdefault:\n\t\t\/\/ If input does not equal any of the cases, the default class is a warrior.\n\t\t_Player = new Warrior;\n\t\tbreak;\n\t}\n}\n\nvoid Game::SetPlayerData(){\n\t\/* Data initialized in order of:\n\t* class code\n\t* name\n\t* level\n\t* experience\n\t* health\n\t* arrows\n\t* bombs\n\t* potions\n\t* whetstones\n\t* weaponstrength\n\t* coins\n\t*\/\n\n\tifstream ReadData;\n\tReadData.open(\"data.txt\");\n\n\t\/\/ Runs if user has never played the game before or data is not found.\n\tif (!ReadData) {\n\t\tReadData.close();\n\t\tofstream WriteData;\n\t\tWriteData.open(\"data.txt\");\n\n\t\tWriteData << InitializePlayerClass() << endl\n\t\t\t<< InitializePlayerName() << endl\n << InitializePlayerGender() << endl\n\t\t\t<< 1 << endl\n\t\t\t<< 0 << endl\n\t\t\t<< 100 << endl\n\t\t\t<< 10 << endl\n\t\t\t<< 1 << endl\n\t\t\t<< 1 << endl\n\t\t\t<< 1 << endl\n\t\t\t<< 100 << endl\n\t\t\t<< 0;\n\t\tWriteData.close();\n\t}\n\n\telse {\n\t\t\/\/ Initializes player type from class code given in data.txt\n\t\tint player_class;\n\t\tReadData >> player_class;\n\t\tSetPlayerClass(player_class);\n\t\tReadData.close();\n\t}\n}\n\nvoid Game::SetEnemy(){\n \/\/ Generates a random integer to determine class of the enemy.\n \/\/ The abstract class Enemy is morphed with one of its child classes.\n\n EnemyType selector = EnemyType(rand()%etNumEnemyTypes);\n switch(selector){\n\tcase etSlimeball:\n\t \/\/ Enemy is a slimeball.\n\t _Enemy = new Slimeball;\n break; \n case etCrab:\n \/\/ Enemy is a crab.\n _Enemy = new Crab;\n break;\n case etGiantCrab:\n \/\/ Enemy is a giant crab.\n _Enemy = new GiantCrab;\n break;\n case etSquid:\n \/\/ Enemy is a squid.\n _Enemy = new Squid;\n break;\n case etGiantSquid:\n \/\/ Enemy is a giant squid.\n _Enemy = new GiantSquid;\n break;\n\t\tcase etLich:\n\t\t\t\/\/ Enemy is a Lich\n\t\t\t_Enemy = new Lich;\n\t\t\tbreak;\n\t\tcase etMurloc:\n\t\t\t\/\/Enemy is a Murloc\n\t\t\t_Enemy = new Murloc;\n\t\t\tbreak;\n\t\tcase etPutnafer:\n\t\t\t\/\/ Enemy is a Putnafer\n\t\t\t_Enemy = new Putnafer;\n\t\t\tbreak;\n case etZombie:\n \/\/ Enemy is a Zombie\n _Enemy = new Zombie;\n break;\n\t\tcase etVampire:\n\t\t\t\/\/ Enemy is a Vampire\n\t\t\t_Enemy = new Vampire;\n\t\t\tbreak;\n\t\tcase etWerewolf:\n\t\t\t\/\/ Enemy is a Werewolf\n\t\t\t_Enemy = new Werewolf;\n\t\t\tbreak;\n\t\tcase etGoblin:\n\t\t\t\/\/ Enemy is a Goblin\n\t\t\t_Enemy = new Goblin;\n\t\t\tbreak;\n\t\tcase etGargoyle:\n\t\t\t\/\/ Enemy is a Goblin\n\t\t\t_Enemy = new Gargoyle;\n\t\t\tbreak;\n\t\tcase etCerberus:\n\t\t\t\/\/ Enemy is a Cerberus\n\t\t\t_Enemy = new Cerberus;\n\t\t\tbreak;\n\t\tcase etSkeleton:\n\t\t\t\/\/ Enemy is a Rat\n\t\t\t_Enemy = new Skeleton;\n\t\t\tbreak;\n\t\tcase etSmallRat:\n\t\t\t\/\/ Enemy is a Small Rat\n\t\t\t_Enemy = new SmallRat;\n\t\t\tbreak;\n default:\n \/\/ If the above cases do not match the selector for any reason,\n \/\/ the enemy defaults on the crab class.\n _Enemy = new Crab;\n break;\n }\n \/\/ Simply prints that the enemy's class was encountered.\n\tcout << _Enemy->GetIntro() << endl;\n\tSleep(SLEEP_MS);\n\tColourPrint(_Enemy->GetName(), Console::DarkGrey);\n cout << \" encountered!\" << endl << endl;\n Sleep(SLEEP_MS);\n}\n\nbool Game::PlayAgain(){\n \/\/ Returns a bool value to determine if the player wants to play again.\n\n char choice;\n cout << \"Keep going? (y\/n)\" << endl << endl;\n choice = (char)input();\n \/\/ Returns true if the player says yes (Y, y, 1).\n if (choice == 'y' || choice == 'Y' || choice == '1') return true;\n \/\/ Returns false otherwise, regardless of choice=='n'.\n return false;\n}\n\n\nvoid Game::Intermission(){\n \/\/ Saves game in case player unexpectedly quits (uses X instead of\n \/\/ in-game quit.\n _Player->SaveGame();\n\n \/\/ Loops until the player starts another battle or they quit (IsPlaying=false).\n for (int choice=0; IsPlaying;){\n ClearScreen();\n cout << \"*--------- Intermission ----------* \" << endl << endl;\n\n\t_Player->DisplayInventory();\n cout << \"1) Start battle\" << endl;\n cout << \"2) Store\" << endl;\n cout << \"3) Gamble\" << endl;\n\tcout << \"4) Use Item\" << endl;\n cout << \"0) Quit\" << endl << endl;\n\n choice = input();\n\n switch(choice){\n case 1:\n \/\/ Returns to StartGame()'s loop, calling Battle().\n return;\n case 2:\n \/\/ Goes to the store where the player can buy items.\n \/\/\/ Currently in working progress.\n _Store.StoreFront(_Player);\n break;\n case 3:\n \/\/ Goes to the gambling arena.\n \/\/ _Player is passed in to add items won to the player inventory.\n _Gambling.Gamble(_Player);\n break;\n\tcase 4:\n\t _Player->UseItem();\n\t _Player->SaveGame();\n\t break;\n case 0:\n \/\/ Breaks the loop in StartGame(), going back to MainMenu().\n IsPlaying=false;\n\t break;\n }\n }\n}\n\nvoid Game::StartGame(){\n \/\/ Starts the game by initializing values for a new game.\n\n \/\/ Seeds the random number generator for pseudo-random numbers.\n srand((unsigned int)time(NULL));\n IsPlaying=true;\n\n \/\/ SetPlayerData() initializes the variables in this end.\n ClearScreen();\n SetPlayerData();\n\n\t\/\/ This initializes the variables on the Player end.\n ClearScreen();\n _Player->SetPlayerData();\n\n\n \/\/ Loops while the game is still playing.\n \/\/ Alternates between battles and intermission (gambling, store, et)\n while(IsPlaying){\n\t\tIntermission();\n\t\tif (!IsPlaying)\n\t\t\tbreak;\n\t\tBattle();\n }\n\n \/\/ Saves the player's data to an external file before quitting.\n _Player->SaveGame();\n}\n\nvoid Game::Battle(){\n ClearScreen();\n \/\/ Uses random integers to determine class of the enemy.\n SetEnemy();\n\n \/\/ Loops the actual battle while playing.\n while(IsPlaying){\n ClearScreen();\n \/\/ Displays the name and health bar of the player and enemy.\n \/\/ The Enemy* argument is to display the enemy's\n \/\/ name. Explained more in _Player->DisplayHealthBar().\n _Player->DisplayHUD(_Enemy);\n _Enemy->DisplayHUD();\n\n\t\tint damagePlayer = _Player->Action();\n \/\/ Player's turn to attack Enemy or choose other action.\n\n\t\tif (damagePlayer != SKIP_TURN){\n\t\t\t_Enemy->TakeDamage(damagePlayer);\n\t\t\t\/\/ Pauses console and ignores user input for SLEEP_MS milliseconds.\n \t\tSleep(SLEEP_MS);\n\t\t}\n\n\n \/\/ Leaves battle if player chooses to.\n if (!IsPlaying){\n IsPlaying = true;\n return;\n }\n\n \/\/ Executes when the enemy's health is 0 or below.\n if (_Enemy->IsDead()){\n \/\/ Adds drops to player's inventory from defeated enemy.\n _Player->AddToInventory(_Enemy->GetDrops());\n \/\/ Adds points to player's experience.\n _Player->AddExperience(_Enemy->ReturnExperience());\n\t\t\t\/\/ Replenishes player's health for the next round.\n\t\t\t_Player->ReplenishHealth();\n\n\t\t\t\/\/ If player wants to battle again, it breaks the loop and uses tail recursion to play again.\n if (PlayAgain()) break;\n \/\/ Returns to StartGame()'s loop, and executes Intermission().\n return;\n }\n\n \/\/ Enemy's turn to attack player.\n\t\tif (damagePlayer != SKIP_TURN)\n\t\t\t_Player->TakeDamage(_Enemy->Action());\n Sleep(SLEEP_MS);\n\n \/\/ Executes when player's health is 0 or below.\n if (_Player->IsDead()){\n \/\/ Player loses the amount of experience points gained when you defeat the enemy.\n _Player->LoseExperience(_Enemy->ReturnExperience());\n\t\t\t\/\/ Replenishes player's health for the next round.\n\t\t\t_Player->ReplenishHealth();\n\n\t\t\tif (PlayAgain()) break;\n return;\n }\n }\n Battle();\n}\n\nvoid Game::HowToPlay() {\n\n\tGetChoice(MenuType::eHowToPlay);\n}\n\nint Game::GetChoice(MenuType menuType)\n{\n\tDisplayMenu(menuType);\n\tint choice = -1;\n\twhile (!(cin >> choice)) {\n\t\tcin.clear();\n\t\tcin.ignore(numeric_limits::max(), '\\n');\n\t\tcout << \"Invalid input. Please try again.\";\n\t\tSleep(SLEEP_MS);\n\t\tDisplayMenu(menuType);\n\t}\n\treturn choice;\n}\n\nvoid Game::DisplayMenu(MenuType menuType)\n{\n\tClearScreen();\n\tswitch (menuType)\n\t{\n\tcase Game::eMain:\n\t\tcout << \"========== TURN-BASED FIGHTING GAME ==========\" << endl << endl\n\t\t\t<< \"1) Start Game\" << endl\n\t\t\t<< \"2) How to play\" << endl\n\t\t\t<< \"0) Exit\" << endl << endl << \"> \";\n\t\tbreak;\n\tcase Game::ePlayerClass:\n\t\tcout << endl\n\t\t\t<< \"Which class do you want to play as?\" << endl\n\t\t\t<< \"1) Warrior (high damage, low healing capabilities)\" << endl\n\t\t\t<< \"2) Rogue (moderate damage, moderate healing capabilities)\" << endl\n\t\t\t<< \"3) Healer (low damage, high healing capabilities)\" << endl\n\t\t\t<< \"4) Debugger (INFINITE DAMAGE!!!!)\" << endl\n\t\t\t<< \"5) Saitama (self-explanatory)\" << endl\n\t\t\t<< endl << endl\n\t\t\t<< \"> \";\n\t\tbreak;\n\tcase Game::eHowToPlay:\n\t\tcout << \"============== HOW TO PLAY ==============\" << endl << endl\n\t\t\t<< \"Turn is a turn-based RPG game.\" << endl\n\t\t\t<< \"Create your character and start playing.\" << endl\n\t\t\t<< \"For playing you have to choose what to do by typing\" << endl\n\t\t\t<< \"the corresponding number.\" << endl\n\t\t\t<< \"You can perform actions and use items.\" << endl << endl\n\t\t\t<< \"-- Actions --\" << endl\n\t\t\t<< \"Attack: Regular attack\" << endl\n\t\t\t<< \"Risk Attack: Attack deals more damage, but with a chance of missing\" << endl\n\t\t\t<< \"Heal: Restore an amount of your HP\" << endl\n\t\t\t<< \"Flee: Run away from battle\" << endl << endl\n\t\t\t<< \"-- Items --\" << endl\n\t\t\t<< \"Bombs: Deals 50HP to your opponent with no chance of missing\" << endl\n\t\t\t<< \"Arrows: Deals 10-15HP to your opponent with no chance of missing\" << endl\n\t\t\t<< \"Potion: Replenishes your HP to 100\" << endl\n\t\t\t<< \"Whetstone: Restores your weapon's sharpness.\" << endl << endl\n\t\t\t<< \"Good luck and have fun!\" << endl << endl\n\t\t\t<< \"0) Quit\" << endl << endl << \"> \";\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n<|endoftext|>"} {"text":"\/\/=============================================================================\n\/\/ ■ init.cpp\n\/\/-----------------------------------------------------------------------------\n\/\/ 所有初始化相关的代码都被放置在这里。\n\/\/=============================================================================\n\n#include \"global.hpp\"\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ● 设置视口\n\/\/-----------------------------------------------------------------------------\nvoid setup_viewport() {\n\tint width, height;\n\tglfwGetFramebufferSize(window, &width, &height);\n\tglViewport(0, 0, width, height);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ● GL数据查询\n\/\/-----------------------------------------------------------------------------\nvoid GL_info() {\n\tlog(\"==========================\");\n\tlog(\"OpenGL Info:\");\n\tGLint a, b;\n\tglGetIntegerv(GL_MAJOR_VERSION, &a);\n\tglGetIntegerv(GL_MINOR_VERSION, &b);\n\tlog(\"Supproted GL Version %d.%d\", a, b);\n\tlog(\"=====================================================\");\n\tglGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &a);\n\tlog(\"Maximum vertex attributes: %d\", a);\n\tglGetIntegerv(GL_MAX_VERTEX_OUTPUT_COMPONENTS, &a);\n\tif (VMDE->gl_ver == GL_43) {\n\t\tlog(\"Maximum vertex output components: %d\", a);\n\t\tglGetIntegerv(GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS, &a);\n\t}\n\tlog(\"Maximum fragment shader storage blocks: %d\", a);\n\tglGetIntegerv(GL_MAX_TEXTURE_SIZE, &a);\n\tlog(\"Maximum texture size: %d\", a);\n\tglGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &a);\n\tlog(\"Maximum texture unit: %d\", a);\n\tcheck_gl_error;\n\tlog(\"=====================================================\");\n\tlog(\n\t\t\"EXT_packed_stencil_depth: %s\",\n\t\tglfwExtensionSupported(\"EXT_packed_stencil_depth\") ? \"Supported\" : \"Unsupported\"\n\t);\n\tcheck_gl_error;\n\tlog(\"=====================================================\");\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ● 初始化图形\n\/\/-----------------------------------------------------------------------------\nvoid init_graphics(int w, int h, const char* title) {\n\tinit_vmde(w, h);\n\n\t\/\/ GLFW库初始化\n\tglfwSetErrorCallback(glfw_error_callback);\n\tif (!glfwInit()) {\n\t\tlog(\"glfwInit() failed\");\n\t\treturn;\n\t}\n\n\t\/\/ OpenGL 向前&向后兼容,使用GL 4.3 Core Profile,窗口大小不可变\n\t\/\/ 如果有更高版本就利用\n\t\/\/ 指定版本后便无需再检查是否支持指定版本,因为GLFW会处理此问题\n\tglfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);\n\tglfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\tglfwWindowHint(GLFW_RESIZABLE, GL_FALSE);\n\n\twindow = glfwCreateWindow(VMDE->width, VMDE->height, title, NULL, NULL);\n\tif (!window) {\n\t\t\/\/ 如果GL 4.3不行就回退到GL 3.3\n\t\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n\t\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\t\twindow = glfwCreateWindow(VMDE->width, VMDE->height, title, NULL, NULL);\n\t\tVMDE->gl_ver = GL_33;\n\t\tif (!window) {\n\t\t\tglfwTerminate();\n\t\t\terror(\"glfwCreateWindow() (GLFW Window Creation) failed. Your computer need OpenGL 3.3.\");\n\t\t\treturn;\n\t\t}\n\t\tlog(\"OpenGL API: 3.3\");\n\t} else {\n\t\tVMDE->gl_ver = GL_43;\n\t\tlog(\"OpenGL API: 4.3\");\n\t}\n\n\tVMSC::init_graphics_state();\n\n\tsetup_viewport();\n\n\t\/\/ Query GL info\n\tGL_info();\n\n\t\/\/ Setup API constants\n\tPostProcessingManager::init();\n\tglDepthRange(0.0f, 1.0f);\n\tglDepthMask(GL_TRUE);\n\tglClearDepth(1.0f);\n\n\tglDepthFunc(GL_LEQUAL);\n\n\tglFrontFace(GL_CCW);\n\tVMStateControl::enable_depth_test();\n\tVMStateControl::enable_stencil_test();\n\tVMStateControl::enable_cullface();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ● 初始化引擎\n\/\/-----------------------------------------------------------------------------\nvoid init_engine(int w, int h, const char* title) {\n\tUtil::init();\n\tlog(\"initializing the engine\");\n\tsrand(time(NULL));\n\tlog(\"The system is %s-endian.\", is_little_endian() ? \"little\" : \"big\");\n\n\tinit_vmde(w, h);\n\tinit_graphics(w, h, title);\n\tAudio::init();\n\n\tlog(\"initialized the engine\");\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ● 初始化VMDE结构体\n\/\/-----------------------------------------------------------------------------\nvoid init_vmde(int w, int h) {\n\tVMDE = new struct VMDE;\n\tVMDE->state.frozen = false;\n\tVMDE->state.brightness = 1.0;\n\tVMDE->frame_count = 0;\n\tVMDE->fps = 0;\n\tVMDE->width = w;\n\tVMDE->height = h;\n\tVMDE->done = false;\n}\n修复等号数量不一致\/\/=============================================================================\n\/\/ ■ init.cpp\n\/\/-----------------------------------------------------------------------------\n\/\/ 所有初始化相关的代码都被放置在这里。\n\/\/=============================================================================\n\n#include \"global.hpp\"\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ● 设置视口\n\/\/-----------------------------------------------------------------------------\nvoid setup_viewport() {\n\tint width, height;\n\tglfwGetFramebufferSize(window, &width, &height);\n\tglViewport(0, 0, width, height);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ● GL数据查询\n\/\/-----------------------------------------------------------------------------\nvoid GL_info() {\n\tlog(\"=====================================================\");\n\tlog(\"OpenGL Info:\");\n\tGLint a, b;\n\tglGetIntegerv(GL_MAJOR_VERSION, &a);\n\tglGetIntegerv(GL_MINOR_VERSION, &b);\n\tlog(\"Supproted GL Version %d.%d\", a, b);\n\tlog(\"=====================================================\");\n\tglGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &a);\n\tlog(\"Maximum vertex attributes: %d\", a);\n\tglGetIntegerv(GL_MAX_VERTEX_OUTPUT_COMPONENTS, &a);\n\tif (VMDE->gl_ver == GL_43) {\n\t\tlog(\"Maximum vertex output components: %d\", a);\n\t\tglGetIntegerv(GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS, &a);\n\t}\n\tlog(\"Maximum fragment shader storage blocks: %d\", a);\n\tglGetIntegerv(GL_MAX_TEXTURE_SIZE, &a);\n\tlog(\"Maximum texture size: %d\", a);\n\tglGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &a);\n\tlog(\"Maximum texture unit: %d\", a);\n\tcheck_gl_error;\n\tlog(\"=====================================================\");\n\tlog(\n\t\t\"EXT_packed_stencil_depth: %s\",\n\t\tglfwExtensionSupported(\"EXT_packed_stencil_depth\") ? \"Supported\" : \"Unsupported\"\n\t);\n\tcheck_gl_error;\n\tlog(\"=====================================================\");\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ● 初始化图形\n\/\/-----------------------------------------------------------------------------\nvoid init_graphics(int w, int h, const char* title) {\n\tinit_vmde(w, h);\n\n\t\/\/ GLFW库初始化\n\tglfwSetErrorCallback(glfw_error_callback);\n\tif (!glfwInit()) {\n\t\tlog(\"glfwInit() failed\");\n\t\treturn;\n\t}\n\n\t\/\/ OpenGL 向前&向后兼容,使用GL 4.3 Core Profile,窗口大小不可变\n\t\/\/ 如果有更高版本就利用\n\t\/\/ 指定版本后便无需再检查是否支持指定版本,因为GLFW会处理此问题\n\tglfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);\n\tglfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\tglfwWindowHint(GLFW_RESIZABLE, GL_FALSE);\n\n\twindow = glfwCreateWindow(VMDE->width, VMDE->height, title, NULL, NULL);\n\tif (!window) {\n\t\t\/\/ 如果GL 4.3不行就回退到GL 3.3\n\t\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n\t\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\t\twindow = glfwCreateWindow(VMDE->width, VMDE->height, title, NULL, NULL);\n\t\tVMDE->gl_ver = GL_33;\n\t\tif (!window) {\n\t\t\tglfwTerminate();\n\t\t\terror(\"glfwCreateWindow() (GLFW Window Creation) failed. Your computer need OpenGL 3.3.\");\n\t\t\treturn;\n\t\t}\n\t\tlog(\"OpenGL API: 3.3\");\n\t} else {\n\t\tVMDE->gl_ver = GL_43;\n\t\tlog(\"OpenGL API: 4.3\");\n\t}\n\n\tVMSC::init_graphics_state();\n\n\tsetup_viewport();\n\n\t\/\/ Query GL info\n\tGL_info();\n\n\t\/\/ Setup API constants\n\tPostProcessingManager::init();\n\tglDepthRange(0.0f, 1.0f);\n\tglDepthMask(GL_TRUE);\n\tglClearDepth(1.0f);\n\n\tglDepthFunc(GL_LEQUAL);\n\n\tglFrontFace(GL_CCW);\n\tVMStateControl::enable_depth_test();\n\tVMStateControl::enable_stencil_test();\n\tVMStateControl::enable_cullface();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ● 初始化引擎\n\/\/-----------------------------------------------------------------------------\nvoid init_engine(int w, int h, const char* title) {\n\tUtil::init();\n\tlog(\"initializing the engine\");\n\tsrand(time(NULL));\n\tlog(\"The system is %s-endian.\", is_little_endian() ? \"little\" : \"big\");\n\n\tinit_vmde(w, h);\n\tinit_graphics(w, h, title);\n\tAudio::init();\n\n\tlog(\"initialized the engine\");\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ● 初始化VMDE结构体\n\/\/-----------------------------------------------------------------------------\nvoid init_vmde(int w, int h) {\n\tVMDE = new struct VMDE;\n\tVMDE->state.frozen = false;\n\tVMDE->state.brightness = 1.0;\n\tVMDE->frame_count = 0;\n\tVMDE->fps = 0;\n\tVMDE->width = w;\n\tVMDE->height = h;\n\tVMDE->done = false;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"remoting\/host\/screen_recorder.h\"\n\n#include \n\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/stl_util-inl.h\"\n#include \"base\/task.h\"\n#include \"base\/time.h\"\n#include \"remoting\/base\/capture_data.h\"\n#include \"remoting\/base\/tracer.h\"\n#include \"remoting\/proto\/control.pb.h\"\n#include \"remoting\/proto\/video.pb.h\"\n#include \"remoting\/protocol\/client_stub.h\"\n#include \"remoting\/protocol\/connection_to_client.h\"\n#include \"remoting\/protocol\/message_decoder.h\"\n#include \"remoting\/protocol\/util.h\"\n\nusing remoting::protocol::ConnectionToClient;\n\nnamespace remoting {\n\n\/\/ By default we capture 20 times a second. This number is obtained by\n\/\/ experiment to provide good latency.\nstatic const double kDefaultCaptureRate = 20.0;\n\n\/\/ Maximum number of frames that can be processed similtaneously.\n\/\/ TODO(sergeyu): Should this be set to 1? Or should we change\n\/\/ dynamically depending on how fast network and CPU are? Experement\n\/\/ with it.\nstatic const int kMaxRecordings = 2;\n\nScreenRecorder::ScreenRecorder(\n MessageLoop* capture_loop,\n MessageLoop* encode_loop,\n MessageLoop* network_loop,\n Capturer* capturer,\n Encoder* encoder)\n : capture_loop_(capture_loop),\n encode_loop_(encode_loop),\n network_loop_(network_loop),\n capturer_(capturer),\n encoder_(encoder),\n is_recording_(false),\n network_stopped_(false),\n recordings_(0),\n frame_skipped_(false),\n max_rate_(kDefaultCaptureRate) {\n DCHECK(capture_loop_);\n DCHECK(encode_loop_);\n DCHECK(network_loop_);\n}\n\nScreenRecorder::~ScreenRecorder() {\n}\n\n\/\/ Public methods --------------------------------------------------------------\n\nvoid ScreenRecorder::Start() {\n capture_loop_->PostTask(\n FROM_HERE, NewTracedMethod(this, &ScreenRecorder::DoStart));\n}\n\nvoid ScreenRecorder::Stop(Task* done_task) {\n capture_loop_->PostTask(\n FROM_HERE, NewTracedMethod(this, &ScreenRecorder::DoStop, done_task));\n}\n\nvoid ScreenRecorder::SetMaxRate(double rate) {\n capture_loop_->PostTask(\n FROM_HERE, NewTracedMethod(this, &ScreenRecorder::DoSetMaxRate, rate));\n}\n\nvoid ScreenRecorder::AddConnection(\n scoped_refptr connection) {\n ScopedTracer tracer(\"AddConnection\");\n\n capture_loop_->PostTask(\n FROM_HERE,\n NewRunnableMethod(this, &ScreenRecorder::DoInvalidateFullScreen));\n\n \/\/ Add the client to the list so it can receive update stream.\n network_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoAddConnection, connection));\n}\n\nvoid ScreenRecorder::RemoveConnection(\n scoped_refptr connection) {\n network_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoRemoveClient, connection));\n}\n\nvoid ScreenRecorder::RemoveAllConnections() {\n network_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoRemoveAllClients));\n}\n\n\/\/ Private accessors -----------------------------------------------------------\n\nCapturer* ScreenRecorder::capturer() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n DCHECK(capturer_);\n return capturer_;\n}\n\nEncoder* ScreenRecorder::encoder() {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n DCHECK(encoder_.get());\n return encoder_.get();\n}\n\n\/\/ Capturer thread -------------------------------------------------------------\n\nvoid ScreenRecorder::DoStart() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n if (is_recording_) {\n NOTREACHED() << \"Record session already started.\";\n return;\n }\n\n is_recording_ = true;\n StartCaptureTimer();\n\n \/\/ Capture first frame immedately.\n DoCapture();\n}\n\nvoid ScreenRecorder::DoStop(Task* done_task) {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n \/\/ We might have not started when we receive a stop command, simply run the\n \/\/ task and then return.\n if (!is_recording_) {\n DoCompleteStop(done_task);\n return;\n }\n\n capture_timer_.Stop();\n is_recording_ = false;\n\n DCHECK_GE(recordings_, 0);\n if (recordings_) {\n network_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this,\n &ScreenRecorder::DoStopOnNetworkThread, done_task));\n return;\n }\n\n DoCompleteStop(done_task);\n}\n\nvoid ScreenRecorder::DoCompleteStop(Task* done_task) {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n if (done_task) {\n done_task->Run();\n delete done_task;\n }\n}\n\nvoid ScreenRecorder::DoSetMaxRate(double max_rate) {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n \/\/ TODO(hclam): Should also check for small epsilon.\n DCHECK_GT(max_rate, 0.0) << \"Rate is too small.\";\n\n max_rate_ = max_rate;\n\n \/\/ Restart the timer with the new rate.\n if (is_recording_) {\n capture_timer_.Stop();\n StartCaptureTimer();\n }\n}\n\nvoid ScreenRecorder::StartCaptureTimer() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n base::TimeDelta interval = base::TimeDelta::FromMilliseconds(\n static_cast(base::Time::kMillisecondsPerSecond \/ max_rate_));\n capture_timer_.Start(interval, this, &ScreenRecorder::DoCapture);\n}\n\nvoid ScreenRecorder::DoCapture() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n \/\/ Make sure we have at most two oustanding recordings. We can simply return\n \/\/ if we can't make a capture now, the next capture will be started by the\n \/\/ end of an encode operation.\n if (recordings_ >= kMaxRecordings || !is_recording_) {\n frame_skipped_ = true;\n return;\n }\n\n if (frame_skipped_) {\n frame_skipped_ = false;\n capture_timer_.Reset();\n }\n\n TraceContext::tracer()->PrintString(\"Capture Started\");\n\n \/\/ At this point we are going to perform one capture so save the current time.\n ++recordings_;\n DCHECK_LE(recordings_, kMaxRecordings);\n\n \/\/ And finally perform one capture.\n capture_start_time_ = base::Time::Now();\n capturer()->CaptureInvalidRects(\n NewCallback(this, &ScreenRecorder::CaptureDoneCallback));\n}\n\nvoid ScreenRecorder::CaptureDoneCallback(\n scoped_refptr capture_data) {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n if (!is_recording_)\n return;\n\n TraceContext::tracer()->PrintString(\"Capture Done\");\n int capture_time =\n (base::Time::Now() - capture_start_time_).InMilliseconds();\n capture_data->set_capture_time_ms(capture_time);\n encode_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoEncode, capture_data));\n}\n\nvoid ScreenRecorder::DoFinishOneRecording() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n if (!is_recording_)\n return;\n\n \/\/ Decrement the number of recording in process since we have completed\n \/\/ one cycle.\n --recordings_;\n DCHECK_GE(recordings_, 0);\n\n \/\/ Try to do a capture again only if |frame_skipped_| is set to true by\n \/\/ capture timer.\n if (frame_skipped_)\n DoCapture();\n}\n\nvoid ScreenRecorder::DoInvalidateFullScreen() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n capturer_->InvalidateFullScreen();\n}\n\n\/\/ Network thread --------------------------------------------------------------\n\nvoid ScreenRecorder::DoSendVideoPacket(VideoPacket* packet) {\n DCHECK_EQ(network_loop_, MessageLoop::current());\n\n TraceContext::tracer()->PrintString(\"DoSendVideoPacket\");\n\n bool last = (packet->flags() & VideoPacket::LAST_PARTITION) != 0;\n\n if (network_stopped_ || connections_.empty()) {\n delete packet;\n return;\n }\n\n for (ConnectionToClientList::const_iterator i = connections_.begin();\n i < connections_.end(); ++i) {\n Task* done_task = NULL;\n\n \/\/ Call FrameSentCallback() only for the last packet in the first\n \/\/ connection.\n if (last && i == connections_.begin()) {\n done_task = NewTracedMethod(this, &ScreenRecorder::FrameSentCallback,\n packet);\n } else {\n \/\/ TODO(hclam): Fix this code since it causes multiple deletion if there's\n \/\/ more than one connection.\n done_task = new DeleteTask(packet);\n }\n\n (*i)->video_stub()->ProcessVideoPacket(packet, done_task);\n }\n\n TraceContext::tracer()->PrintString(\"DoSendVideoPacket done\");\n}\n\nvoid ScreenRecorder::FrameSentCallback(VideoPacket* packet) {\n delete packet;\n\n if (network_stopped_)\n return;\n\n capture_loop_->PostTask(\n FROM_HERE, NewTracedMethod(this, &ScreenRecorder::DoFinishOneRecording));\n}\n\nvoid ScreenRecorder::DoAddConnection(\n scoped_refptr connection) {\n DCHECK_EQ(network_loop_, MessageLoop::current());\n\n connections_.push_back(connection);\n}\n\nvoid ScreenRecorder::DoRemoveClient(\n scoped_refptr connection) {\n DCHECK_EQ(network_loop_, MessageLoop::current());\n\n ConnectionToClientList::iterator it =\n std::find(connections_.begin(), connections_.end(), connection);\n if (it != connections_.end()) {\n connections_.erase(it);\n }\n}\n\nvoid ScreenRecorder::DoRemoveAllClients() {\n DCHECK_EQ(network_loop_, MessageLoop::current());\n\n \/\/ Clear the list of connections.\n connections_.clear();\n}\n\nvoid ScreenRecorder::DoStopOnNetworkThread(Task* done_task) {\n DCHECK_EQ(network_loop_, MessageLoop::current());\n\n \/\/ There could be tasks on the network thread when this method is being\n \/\/ executed. By setting the flag we'll not post anymore tasks from network\n \/\/ thread.\n \/\/\n \/\/ After that a task is posted on encode thread to continue the stop\n \/\/ sequence.\n network_stopped_ = true;\n\n encode_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoStopOnEncodeThread, done_task));\n}\n\n\/\/ Encoder thread --------------------------------------------------------------\n\nvoid ScreenRecorder::DoEncode(\n scoped_refptr capture_data) {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n TraceContext::tracer()->PrintString(\"DoEncode called\");\n\n \/\/ Early out if there's nothing to encode.\n if (!capture_data->dirty_rects().size()) {\n capture_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoFinishOneRecording));\n return;\n }\n\n TraceContext::tracer()->PrintString(\"Encode start\");\n encode_start_time_ = base::Time::Now();\n encoder()->Encode(\n capture_data, false,\n NewCallback(this, &ScreenRecorder::EncodedDataAvailableCallback));\n TraceContext::tracer()->PrintString(\"Encode Done\");\n}\n\nvoid ScreenRecorder::DoStopOnEncodeThread(Task* done_task) {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n\n \/\/ When this method is being executed there are no more tasks on encode thread\n \/\/ for this object. We can then post a task to capture thread to finish the\n \/\/ stop sequence.\n capture_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoCompleteStop, done_task));\n}\n\nvoid ScreenRecorder::EncodedDataAvailableCallback(VideoPacket* packet) {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n\n bool last = packet->flags() & VideoPacket::LAST_PACKET;\n if (last) {\n int encode_time =\n (base::Time::Now() - encode_start_time_).InMilliseconds();\n packet->set_encode_time_ms(encode_time);\n }\n\n network_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoSendVideoPacket, packet));\n}\n\n} \/\/ namespace remoting\nFix build breaks\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"remoting\/host\/screen_recorder.h\"\n\n#include \n\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/stl_util-inl.h\"\n#include \"base\/task.h\"\n#include \"base\/time.h\"\n#include \"remoting\/base\/capture_data.h\"\n#include \"remoting\/base\/tracer.h\"\n#include \"remoting\/proto\/control.pb.h\"\n#include \"remoting\/proto\/video.pb.h\"\n#include \"remoting\/protocol\/client_stub.h\"\n#include \"remoting\/protocol\/connection_to_client.h\"\n#include \"remoting\/protocol\/message_decoder.h\"\n#include \"remoting\/protocol\/util.h\"\n\nusing remoting::protocol::ConnectionToClient;\n\nnamespace remoting {\n\n\/\/ By default we capture 20 times a second. This number is obtained by\n\/\/ experiment to provide good latency.\nstatic const double kDefaultCaptureRate = 20.0;\n\n\/\/ Maximum number of frames that can be processed similtaneously.\n\/\/ TODO(sergeyu): Should this be set to 1? Or should we change\n\/\/ dynamically depending on how fast network and CPU are? Experement\n\/\/ with it.\nstatic const int kMaxRecordings = 2;\n\nScreenRecorder::ScreenRecorder(\n MessageLoop* capture_loop,\n MessageLoop* encode_loop,\n MessageLoop* network_loop,\n Capturer* capturer,\n Encoder* encoder)\n : capture_loop_(capture_loop),\n encode_loop_(encode_loop),\n network_loop_(network_loop),\n capturer_(capturer),\n encoder_(encoder),\n is_recording_(false),\n network_stopped_(false),\n recordings_(0),\n frame_skipped_(false),\n max_rate_(kDefaultCaptureRate) {\n DCHECK(capture_loop_);\n DCHECK(encode_loop_);\n DCHECK(network_loop_);\n}\n\nScreenRecorder::~ScreenRecorder() {\n}\n\n\/\/ Public methods --------------------------------------------------------------\n\nvoid ScreenRecorder::Start() {\n capture_loop_->PostTask(\n FROM_HERE, NewTracedMethod(this, &ScreenRecorder::DoStart));\n}\n\nvoid ScreenRecorder::Stop(Task* done_task) {\n capture_loop_->PostTask(\n FROM_HERE, NewTracedMethod(this, &ScreenRecorder::DoStop, done_task));\n}\n\nvoid ScreenRecorder::SetMaxRate(double rate) {\n capture_loop_->PostTask(\n FROM_HERE, NewTracedMethod(this, &ScreenRecorder::DoSetMaxRate, rate));\n}\n\nvoid ScreenRecorder::AddConnection(\n scoped_refptr connection) {\n ScopedTracer tracer(\"AddConnection\");\n\n capture_loop_->PostTask(\n FROM_HERE,\n NewRunnableMethod(this, &ScreenRecorder::DoInvalidateFullScreen));\n\n \/\/ Add the client to the list so it can receive update stream.\n network_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoAddConnection, connection));\n}\n\nvoid ScreenRecorder::RemoveConnection(\n scoped_refptr connection) {\n network_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoRemoveClient, connection));\n}\n\nvoid ScreenRecorder::RemoveAllConnections() {\n network_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoRemoveAllClients));\n}\n\n\/\/ Private accessors -----------------------------------------------------------\n\nCapturer* ScreenRecorder::capturer() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n DCHECK(capturer_);\n return capturer_;\n}\n\nEncoder* ScreenRecorder::encoder() {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n DCHECK(encoder_.get());\n return encoder_.get();\n}\n\n\/\/ Capturer thread -------------------------------------------------------------\n\nvoid ScreenRecorder::DoStart() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n if (is_recording_) {\n NOTREACHED() << \"Record session already started.\";\n return;\n }\n\n is_recording_ = true;\n StartCaptureTimer();\n\n \/\/ Capture first frame immedately.\n DoCapture();\n}\n\nvoid ScreenRecorder::DoStop(Task* done_task) {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n \/\/ We might have not started when we receive a stop command, simply run the\n \/\/ task and then return.\n if (!is_recording_) {\n DoCompleteStop(done_task);\n return;\n }\n\n capture_timer_.Stop();\n is_recording_ = false;\n\n DCHECK_GE(recordings_, 0);\n if (recordings_) {\n network_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this,\n &ScreenRecorder::DoStopOnNetworkThread, done_task));\n return;\n }\n\n DoCompleteStop(done_task);\n}\n\nvoid ScreenRecorder::DoCompleteStop(Task* done_task) {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n if (done_task) {\n done_task->Run();\n delete done_task;\n }\n}\n\nvoid ScreenRecorder::DoSetMaxRate(double max_rate) {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n \/\/ TODO(hclam): Should also check for small epsilon.\n DCHECK_GT(max_rate, 0.0) << \"Rate is too small.\";\n\n max_rate_ = max_rate;\n\n \/\/ Restart the timer with the new rate.\n if (is_recording_) {\n capture_timer_.Stop();\n StartCaptureTimer();\n }\n}\n\nvoid ScreenRecorder::StartCaptureTimer() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n base::TimeDelta interval = base::TimeDelta::FromMilliseconds(\n static_cast(base::Time::kMillisecondsPerSecond \/ max_rate_));\n capture_timer_.Start(interval, this, &ScreenRecorder::DoCapture);\n}\n\nvoid ScreenRecorder::DoCapture() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n \/\/ Make sure we have at most two oustanding recordings. We can simply return\n \/\/ if we can't make a capture now, the next capture will be started by the\n \/\/ end of an encode operation.\n if (recordings_ >= kMaxRecordings || !is_recording_) {\n frame_skipped_ = true;\n return;\n }\n\n if (frame_skipped_) {\n frame_skipped_ = false;\n capture_timer_.Reset();\n }\n\n TraceContext::tracer()->PrintString(\"Capture Started\");\n\n \/\/ At this point we are going to perform one capture so save the current time.\n ++recordings_;\n DCHECK_LE(recordings_, kMaxRecordings);\n\n \/\/ And finally perform one capture.\n capture_start_time_ = base::Time::Now();\n capturer()->CaptureInvalidRects(\n NewCallback(this, &ScreenRecorder::CaptureDoneCallback));\n}\n\nvoid ScreenRecorder::CaptureDoneCallback(\n scoped_refptr capture_data) {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n if (!is_recording_)\n return;\n\n TraceContext::tracer()->PrintString(\"Capture Done\");\n int capture_time = static_cast(\n (base::Time::Now() - capture_start_time_).InMilliseconds());\n capture_data->set_capture_time_ms(capture_time);\n encode_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoEncode, capture_data));\n}\n\nvoid ScreenRecorder::DoFinishOneRecording() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n if (!is_recording_)\n return;\n\n \/\/ Decrement the number of recording in process since we have completed\n \/\/ one cycle.\n --recordings_;\n DCHECK_GE(recordings_, 0);\n\n \/\/ Try to do a capture again only if |frame_skipped_| is set to true by\n \/\/ capture timer.\n if (frame_skipped_)\n DoCapture();\n}\n\nvoid ScreenRecorder::DoInvalidateFullScreen() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n capturer_->InvalidateFullScreen();\n}\n\n\/\/ Network thread --------------------------------------------------------------\n\nvoid ScreenRecorder::DoSendVideoPacket(VideoPacket* packet) {\n DCHECK_EQ(network_loop_, MessageLoop::current());\n\n TraceContext::tracer()->PrintString(\"DoSendVideoPacket\");\n\n bool last = (packet->flags() & VideoPacket::LAST_PARTITION) != 0;\n\n if (network_stopped_ || connections_.empty()) {\n delete packet;\n return;\n }\n\n for (ConnectionToClientList::const_iterator i = connections_.begin();\n i < connections_.end(); ++i) {\n Task* done_task = NULL;\n\n \/\/ Call FrameSentCallback() only for the last packet in the first\n \/\/ connection.\n if (last && i == connections_.begin()) {\n done_task = NewTracedMethod(this, &ScreenRecorder::FrameSentCallback,\n packet);\n } else {\n \/\/ TODO(hclam): Fix this code since it causes multiple deletion if there's\n \/\/ more than one connection.\n done_task = new DeleteTask(packet);\n }\n\n (*i)->video_stub()->ProcessVideoPacket(packet, done_task);\n }\n\n TraceContext::tracer()->PrintString(\"DoSendVideoPacket done\");\n}\n\nvoid ScreenRecorder::FrameSentCallback(VideoPacket* packet) {\n delete packet;\n\n if (network_stopped_)\n return;\n\n capture_loop_->PostTask(\n FROM_HERE, NewTracedMethod(this, &ScreenRecorder::DoFinishOneRecording));\n}\n\nvoid ScreenRecorder::DoAddConnection(\n scoped_refptr connection) {\n DCHECK_EQ(network_loop_, MessageLoop::current());\n\n connections_.push_back(connection);\n}\n\nvoid ScreenRecorder::DoRemoveClient(\n scoped_refptr connection) {\n DCHECK_EQ(network_loop_, MessageLoop::current());\n\n ConnectionToClientList::iterator it =\n std::find(connections_.begin(), connections_.end(), connection);\n if (it != connections_.end()) {\n connections_.erase(it);\n }\n}\n\nvoid ScreenRecorder::DoRemoveAllClients() {\n DCHECK_EQ(network_loop_, MessageLoop::current());\n\n \/\/ Clear the list of connections.\n connections_.clear();\n}\n\nvoid ScreenRecorder::DoStopOnNetworkThread(Task* done_task) {\n DCHECK_EQ(network_loop_, MessageLoop::current());\n\n \/\/ There could be tasks on the network thread when this method is being\n \/\/ executed. By setting the flag we'll not post anymore tasks from network\n \/\/ thread.\n \/\/\n \/\/ After that a task is posted on encode thread to continue the stop\n \/\/ sequence.\n network_stopped_ = true;\n\n encode_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoStopOnEncodeThread, done_task));\n}\n\n\/\/ Encoder thread --------------------------------------------------------------\n\nvoid ScreenRecorder::DoEncode(\n scoped_refptr capture_data) {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n TraceContext::tracer()->PrintString(\"DoEncode called\");\n\n \/\/ Early out if there's nothing to encode.\n if (!capture_data->dirty_rects().size()) {\n capture_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoFinishOneRecording));\n return;\n }\n\n TraceContext::tracer()->PrintString(\"Encode start\");\n encode_start_time_ = base::Time::Now();\n encoder()->Encode(\n capture_data, false,\n NewCallback(this, &ScreenRecorder::EncodedDataAvailableCallback));\n TraceContext::tracer()->PrintString(\"Encode Done\");\n}\n\nvoid ScreenRecorder::DoStopOnEncodeThread(Task* done_task) {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n\n \/\/ When this method is being executed there are no more tasks on encode thread\n \/\/ for this object. We can then post a task to capture thread to finish the\n \/\/ stop sequence.\n capture_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoCompleteStop, done_task));\n}\n\nvoid ScreenRecorder::EncodedDataAvailableCallback(VideoPacket* packet) {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n\n bool last = (packet->flags() & VideoPacket::LAST_PACKET) != 0;\n if (last) {\n int encode_time = static_cast(\n (base::Time::Now() - encode_start_time_).InMilliseconds());\n packet->set_encode_time_ms(encode_time);\n }\n\n network_loop_->PostTask(\n FROM_HERE,\n NewTracedMethod(this, &ScreenRecorder::DoSendVideoPacket, packet));\n}\n\n} \/\/ namespace remoting\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"remoting\/host\/screen_recorder.h\"\n\n#include \n\n#include \"base\/bind.h\"\n#include \"base\/callback.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop_proxy.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/sys_info.h\"\n#include \"base\/time.h\"\n#include \"remoting\/base\/capture_data.h\"\n#include \"remoting\/proto\/control.pb.h\"\n#include \"remoting\/proto\/video.pb.h\"\n#include \"remoting\/protocol\/client_stub.h\"\n#include \"remoting\/protocol\/connection_to_client.h\"\n#include \"remoting\/protocol\/message_decoder.h\"\n#include \"remoting\/protocol\/util.h\"\n\nusing remoting::protocol::ConnectionToClient;\n\nnamespace remoting {\n\n\/\/ Maximum number of frames that can be processed similtaneously.\n\/\/ TODO(hclam): Move this value to CaptureScheduler.\nstatic const int kMaxRecordings = 2;\n\nScreenRecorder::ScreenRecorder(\n MessageLoop* capture_loop,\n MessageLoop* encode_loop,\n base::MessageLoopProxy* network_loop,\n Capturer* capturer,\n Encoder* encoder)\n : capture_loop_(capture_loop),\n encode_loop_(encode_loop),\n network_loop_(network_loop),\n capturer_(capturer),\n encoder_(encoder),\n is_recording_(false),\n network_stopped_(false),\n encoder_stopped_(false),\n max_recordings_(kMaxRecordings),\n recordings_(0),\n frame_skipped_(false),\n sequence_number_(0) {\n DCHECK(capture_loop_);\n DCHECK(encode_loop_);\n DCHECK(network_loop_);\n}\n\nScreenRecorder::~ScreenRecorder() {\n}\n\n\/\/ Public methods --------------------------------------------------------------\n\nvoid ScreenRecorder::Start() {\n capture_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::DoStart, this));\n}\n\nvoid ScreenRecorder::Stop(const base::Closure& done_task) {\n if (MessageLoop::current() != capture_loop_) {\n capture_loop_->PostTask(FROM_HERE, base::Bind(\n &ScreenRecorder::Stop, this, done_task));\n return;\n }\n\n DCHECK(!done_task.is_null());\n\n capture_timer_.Stop();\n is_recording_ = false;\n\n network_loop_->PostTask(FROM_HERE, base::Bind(\n &ScreenRecorder::DoStopOnNetworkThread, this, done_task));\n}\n\nvoid ScreenRecorder::AddConnection(ConnectionToClient* connection) {\n DCHECK(network_loop_->BelongsToCurrentThread());\n connections_.push_back(connection);\n\n capture_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::DoInvalidateFullScreen, this));\n}\n\nvoid ScreenRecorder::RemoveConnection(ConnectionToClient* connection) {\n DCHECK(network_loop_->BelongsToCurrentThread());\n\n ConnectionToClientList::iterator it =\n std::find(connections_.begin(), connections_.end(), connection);\n if (it != connections_.end()) {\n connections_.erase(it);\n }\n}\n\nvoid ScreenRecorder::RemoveAllConnections() {\n DCHECK(network_loop_->BelongsToCurrentThread());\n connections_.clear();\n}\n\nvoid ScreenRecorder::UpdateSequenceNumber(int64 sequence_number) {\n \/\/ Sequence number is used and written only on the capture thread.\n if (MessageLoop::current() != capture_loop_) {\n capture_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::UpdateSequenceNumber,\n this, sequence_number));\n return;\n }\n\n sequence_number_ = sequence_number;\n}\n\n\/\/ Private accessors -----------------------------------------------------------\n\nCapturer* ScreenRecorder::capturer() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n DCHECK(capturer_);\n return capturer_;\n}\n\nEncoder* ScreenRecorder::encoder() {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n DCHECK(encoder_.get());\n return encoder_.get();\n}\n\n\/\/ Capturer thread -------------------------------------------------------------\n\nvoid ScreenRecorder::DoStart() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n if (is_recording_) {\n NOTREACHED() << \"Record session already started.\";\n return;\n }\n\n is_recording_ = true;\n\n \/\/ Capture first frame immedately.\n DoCapture();\n}\n\nvoid ScreenRecorder::StartCaptureTimer() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n capture_timer_.Start(FROM_HERE,\n scheduler_.NextCaptureDelay(),\n this,\n &ScreenRecorder::DoCapture);\n}\n\nvoid ScreenRecorder::DoCapture() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n \/\/ Make sure we have at most two oustanding recordings. We can simply return\n \/\/ if we can't make a capture now, the next capture will be started by the\n \/\/ end of an encode operation.\n if (recordings_ >= max_recordings_ || !is_recording_) {\n frame_skipped_ = true;\n return;\n }\n\n if (frame_skipped_)\n frame_skipped_ = false;\n\n \/\/ At this point we are going to perform one capture so save the current time.\n ++recordings_;\n DCHECK_LE(recordings_, max_recordings_);\n\n \/\/ Before doing a capture schedule for the next one.\n capture_timer_.Stop();\n capture_timer_.Start(FROM_HERE,\n scheduler_.NextCaptureDelay(),\n this,\n &ScreenRecorder::DoCapture);\n\n \/\/ And finally perform one capture.\n capture_start_time_ = base::Time::Now();\n capturer()->CaptureInvalidRegion(\n base::Bind(&ScreenRecorder::CaptureDoneCallback, this));\n}\n\nvoid ScreenRecorder::CaptureDoneCallback(\n scoped_refptr capture_data) {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n if (!is_recording_)\n return;\n\n if (capture_data) {\n base::TimeDelta capture_time = base::Time::Now() - capture_start_time_;\n int capture_time_ms =\n static_cast(capture_time.InMilliseconds());\n capture_data->set_capture_time_ms(capture_time_ms);\n scheduler_.RecordCaptureTime(capture_time);\n\n \/\/ The best way to get this value is by binding the sequence number to\n \/\/ the callback when calling CaptureInvalidRects(). However the callback\n \/\/ system doesn't allow this. Reading from the member variable is\n \/\/ accurate as long as capture is synchronous as the following statement\n \/\/ will obtain the most recent sequence number received.\n capture_data->set_client_sequence_number(sequence_number_);\n }\n\n encode_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::DoEncode, this, capture_data));\n}\n\nvoid ScreenRecorder::DoFinishOneRecording() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n if (!is_recording_)\n return;\n\n \/\/ Decrement the number of recording in process since we have completed\n \/\/ one cycle.\n --recordings_;\n DCHECK_GE(recordings_, 0);\n\n \/\/ Try to do a capture again only if |frame_skipped_| is set to true by\n \/\/ capture timer.\n if (frame_skipped_)\n DoCapture();\n}\n\nvoid ScreenRecorder::DoInvalidateFullScreen() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n capturer_->InvalidateFullScreen();\n}\n\n\/\/ Network thread --------------------------------------------------------------\n\nvoid ScreenRecorder::DoSendVideoPacket(scoped_ptr packet) {\n DCHECK(network_loop_->BelongsToCurrentThread());\n\n if (network_stopped_ || connections_.empty())\n return;\n\n \/\/ TODO(sergeyu): Currently we send the data only to the first\n \/\/ connection. Send it to all connections if necessary.\n connections_.front()->video_stub()->ProcessVideoPacket(\n packet.get(), base::Bind(\n &ScreenRecorder::VideoPacketSentCallback, this,\n base::Passed(packet.Pass())));\n}\n\nvoid ScreenRecorder::VideoPacketSentCallback(scoped_ptr packet) {\n if (network_stopped_)\n return;\n\n if ((packet->flags() & VideoPacket::LAST_PARTITION) != 0) {\n \/\/ Post DoFinishOneRecording() if that was the last packet for the\n \/\/ frame.\n capture_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::DoFinishOneRecording, this));\n }\n}\n\nvoid ScreenRecorder::DoStopOnNetworkThread(const base::Closure& done_task) {\n DCHECK(network_loop_->BelongsToCurrentThread());\n\n \/\/ There could be tasks on the network thread when this method is being\n \/\/ executed. By setting the flag we'll not post anymore tasks from network\n \/\/ thread.\n \/\/\n \/\/ After that a task is posted on encode thread to continue the stop\n \/\/ sequence.\n network_stopped_ = true;\n\n encode_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::DoStopOnEncodeThread,\n this, done_task));\n}\n\n\/\/ Encoder thread --------------------------------------------------------------\n\nvoid ScreenRecorder::DoEncode(\n scoped_refptr capture_data) {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n\n \/\/ Early out if there's nothing to encode.\n if (!capture_data || capture_data->dirty_region().isEmpty()) {\n \/\/ Send an empty video packet to keep network active.\n scoped_ptr packet(new VideoPacket());\n packet->set_flags(VideoPacket::LAST_PARTITION);\n network_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::DoSendVideoPacket,\n this, base::Passed(packet.Pass())));\n return;\n }\n\n encode_start_time_ = base::Time::Now();\n encoder()->Encode(\n capture_data, false,\n base::Bind(&ScreenRecorder::EncodedDataAvailableCallback, this));\n}\n\nvoid ScreenRecorder::DoStopOnEncodeThread(const base::Closure& done_task) {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n\n encoder_stopped_ = true;\n\n \/\/ When this method is being executed there are no more tasks on encode thread\n \/\/ for this object. We can then post a task to capture thread to finish the\n \/\/ stop sequence.\n capture_loop_->PostTask(FROM_HERE, done_task);\n}\n\nvoid ScreenRecorder::EncodedDataAvailableCallback(\n scoped_ptr packet) {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n\n if (encoder_stopped_)\n return;\n\n bool last = (packet->flags() & VideoPacket::LAST_PACKET) != 0;\n if (last) {\n base::TimeDelta encode_time = base::Time::Now() - encode_start_time_;\n int encode_time_ms =\n static_cast(encode_time.InMilliseconds());\n packet->set_encode_time_ms(encode_time_ms);\n scheduler_.RecordEncodeTime(encode_time);\n }\n\n network_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::DoSendVideoPacket, this,\n base::Passed(packet.Pass())));\n}\n\n} \/\/ namespace remoting\nFix crash caused by r127767 due to undefined order of argument parsing.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"remoting\/host\/screen_recorder.h\"\n\n#include \n\n#include \"base\/bind.h\"\n#include \"base\/callback.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop_proxy.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/sys_info.h\"\n#include \"base\/time.h\"\n#include \"remoting\/base\/capture_data.h\"\n#include \"remoting\/proto\/control.pb.h\"\n#include \"remoting\/proto\/video.pb.h\"\n#include \"remoting\/protocol\/client_stub.h\"\n#include \"remoting\/protocol\/connection_to_client.h\"\n#include \"remoting\/protocol\/message_decoder.h\"\n#include \"remoting\/protocol\/util.h\"\n\nusing remoting::protocol::ConnectionToClient;\n\nnamespace remoting {\n\n\/\/ Maximum number of frames that can be processed similtaneously.\n\/\/ TODO(hclam): Move this value to CaptureScheduler.\nstatic const int kMaxRecordings = 2;\n\nScreenRecorder::ScreenRecorder(\n MessageLoop* capture_loop,\n MessageLoop* encode_loop,\n base::MessageLoopProxy* network_loop,\n Capturer* capturer,\n Encoder* encoder)\n : capture_loop_(capture_loop),\n encode_loop_(encode_loop),\n network_loop_(network_loop),\n capturer_(capturer),\n encoder_(encoder),\n is_recording_(false),\n network_stopped_(false),\n encoder_stopped_(false),\n max_recordings_(kMaxRecordings),\n recordings_(0),\n frame_skipped_(false),\n sequence_number_(0) {\n DCHECK(capture_loop_);\n DCHECK(encode_loop_);\n DCHECK(network_loop_);\n}\n\nScreenRecorder::~ScreenRecorder() {\n}\n\n\/\/ Public methods --------------------------------------------------------------\n\nvoid ScreenRecorder::Start() {\n capture_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::DoStart, this));\n}\n\nvoid ScreenRecorder::Stop(const base::Closure& done_task) {\n if (MessageLoop::current() != capture_loop_) {\n capture_loop_->PostTask(FROM_HERE, base::Bind(\n &ScreenRecorder::Stop, this, done_task));\n return;\n }\n\n DCHECK(!done_task.is_null());\n\n capture_timer_.Stop();\n is_recording_ = false;\n\n network_loop_->PostTask(FROM_HERE, base::Bind(\n &ScreenRecorder::DoStopOnNetworkThread, this, done_task));\n}\n\nvoid ScreenRecorder::AddConnection(ConnectionToClient* connection) {\n DCHECK(network_loop_->BelongsToCurrentThread());\n connections_.push_back(connection);\n\n capture_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::DoInvalidateFullScreen, this));\n}\n\nvoid ScreenRecorder::RemoveConnection(ConnectionToClient* connection) {\n DCHECK(network_loop_->BelongsToCurrentThread());\n\n ConnectionToClientList::iterator it =\n std::find(connections_.begin(), connections_.end(), connection);\n if (it != connections_.end()) {\n connections_.erase(it);\n }\n}\n\nvoid ScreenRecorder::RemoveAllConnections() {\n DCHECK(network_loop_->BelongsToCurrentThread());\n connections_.clear();\n}\n\nvoid ScreenRecorder::UpdateSequenceNumber(int64 sequence_number) {\n \/\/ Sequence number is used and written only on the capture thread.\n if (MessageLoop::current() != capture_loop_) {\n capture_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::UpdateSequenceNumber,\n this, sequence_number));\n return;\n }\n\n sequence_number_ = sequence_number;\n}\n\n\/\/ Private accessors -----------------------------------------------------------\n\nCapturer* ScreenRecorder::capturer() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n DCHECK(capturer_);\n return capturer_;\n}\n\nEncoder* ScreenRecorder::encoder() {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n DCHECK(encoder_.get());\n return encoder_.get();\n}\n\n\/\/ Capturer thread -------------------------------------------------------------\n\nvoid ScreenRecorder::DoStart() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n if (is_recording_) {\n NOTREACHED() << \"Record session already started.\";\n return;\n }\n\n is_recording_ = true;\n\n \/\/ Capture first frame immedately.\n DoCapture();\n}\n\nvoid ScreenRecorder::StartCaptureTimer() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n capture_timer_.Start(FROM_HERE,\n scheduler_.NextCaptureDelay(),\n this,\n &ScreenRecorder::DoCapture);\n}\n\nvoid ScreenRecorder::DoCapture() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n \/\/ Make sure we have at most two oustanding recordings. We can simply return\n \/\/ if we can't make a capture now, the next capture will be started by the\n \/\/ end of an encode operation.\n if (recordings_ >= max_recordings_ || !is_recording_) {\n frame_skipped_ = true;\n return;\n }\n\n if (frame_skipped_)\n frame_skipped_ = false;\n\n \/\/ At this point we are going to perform one capture so save the current time.\n ++recordings_;\n DCHECK_LE(recordings_, max_recordings_);\n\n \/\/ Before doing a capture schedule for the next one.\n capture_timer_.Stop();\n capture_timer_.Start(FROM_HERE,\n scheduler_.NextCaptureDelay(),\n this,\n &ScreenRecorder::DoCapture);\n\n \/\/ And finally perform one capture.\n capture_start_time_ = base::Time::Now();\n capturer()->CaptureInvalidRegion(\n base::Bind(&ScreenRecorder::CaptureDoneCallback, this));\n}\n\nvoid ScreenRecorder::CaptureDoneCallback(\n scoped_refptr capture_data) {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n if (!is_recording_)\n return;\n\n if (capture_data) {\n base::TimeDelta capture_time = base::Time::Now() - capture_start_time_;\n int capture_time_ms =\n static_cast(capture_time.InMilliseconds());\n capture_data->set_capture_time_ms(capture_time_ms);\n scheduler_.RecordCaptureTime(capture_time);\n\n \/\/ The best way to get this value is by binding the sequence number to\n \/\/ the callback when calling CaptureInvalidRects(). However the callback\n \/\/ system doesn't allow this. Reading from the member variable is\n \/\/ accurate as long as capture is synchronous as the following statement\n \/\/ will obtain the most recent sequence number received.\n capture_data->set_client_sequence_number(sequence_number_);\n }\n\n encode_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::DoEncode, this, capture_data));\n}\n\nvoid ScreenRecorder::DoFinishOneRecording() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n if (!is_recording_)\n return;\n\n \/\/ Decrement the number of recording in process since we have completed\n \/\/ one cycle.\n --recordings_;\n DCHECK_GE(recordings_, 0);\n\n \/\/ Try to do a capture again only if |frame_skipped_| is set to true by\n \/\/ capture timer.\n if (frame_skipped_)\n DoCapture();\n}\n\nvoid ScreenRecorder::DoInvalidateFullScreen() {\n DCHECK_EQ(capture_loop_, MessageLoop::current());\n\n capturer_->InvalidateFullScreen();\n}\n\n\/\/ Network thread --------------------------------------------------------------\n\nvoid ScreenRecorder::DoSendVideoPacket(scoped_ptr packet) {\n DCHECK(network_loop_->BelongsToCurrentThread());\n\n if (network_stopped_ || connections_.empty())\n return;\n\n VideoPacket* packet_ptr = packet.get();\n\n \/\/ TODO(sergeyu): Currently we send the data only to the first\n \/\/ connection. Send it to all connections if necessary.\n connections_.front()->video_stub()->ProcessVideoPacket(\n packet_ptr, base::Bind(\n &ScreenRecorder::VideoPacketSentCallback, this,\n base::Passed(packet.Pass())));\n}\n\nvoid ScreenRecorder::VideoPacketSentCallback(scoped_ptr packet) {\n if (network_stopped_)\n return;\n\n if ((packet->flags() & VideoPacket::LAST_PARTITION) != 0) {\n \/\/ Post DoFinishOneRecording() if that was the last packet for the\n \/\/ frame.\n capture_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::DoFinishOneRecording, this));\n }\n}\n\nvoid ScreenRecorder::DoStopOnNetworkThread(const base::Closure& done_task) {\n DCHECK(network_loop_->BelongsToCurrentThread());\n\n \/\/ There could be tasks on the network thread when this method is being\n \/\/ executed. By setting the flag we'll not post anymore tasks from network\n \/\/ thread.\n \/\/\n \/\/ After that a task is posted on encode thread to continue the stop\n \/\/ sequence.\n network_stopped_ = true;\n\n encode_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::DoStopOnEncodeThread,\n this, done_task));\n}\n\n\/\/ Encoder thread --------------------------------------------------------------\n\nvoid ScreenRecorder::DoEncode(\n scoped_refptr capture_data) {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n\n \/\/ Early out if there's nothing to encode.\n if (!capture_data || capture_data->dirty_region().isEmpty()) {\n \/\/ Send an empty video packet to keep network active.\n scoped_ptr packet(new VideoPacket());\n packet->set_flags(VideoPacket::LAST_PARTITION);\n network_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::DoSendVideoPacket,\n this, base::Passed(packet.Pass())));\n return;\n }\n\n encode_start_time_ = base::Time::Now();\n encoder()->Encode(\n capture_data, false,\n base::Bind(&ScreenRecorder::EncodedDataAvailableCallback, this));\n}\n\nvoid ScreenRecorder::DoStopOnEncodeThread(const base::Closure& done_task) {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n\n encoder_stopped_ = true;\n\n \/\/ When this method is being executed there are no more tasks on encode thread\n \/\/ for this object. We can then post a task to capture thread to finish the\n \/\/ stop sequence.\n capture_loop_->PostTask(FROM_HERE, done_task);\n}\n\nvoid ScreenRecorder::EncodedDataAvailableCallback(\n scoped_ptr packet) {\n DCHECK_EQ(encode_loop_, MessageLoop::current());\n\n if (encoder_stopped_)\n return;\n\n bool last = (packet->flags() & VideoPacket::LAST_PACKET) != 0;\n if (last) {\n base::TimeDelta encode_time = base::Time::Now() - encode_start_time_;\n int encode_time_ms =\n static_cast(encode_time.InMilliseconds());\n packet->set_encode_time_ms(encode_time_ms);\n scheduler_.RecordEncodeTime(encode_time);\n }\n\n network_loop_->PostTask(\n FROM_HERE, base::Bind(&ScreenRecorder::DoSendVideoPacket, this,\n base::Passed(packet.Pass())));\n}\n\n} \/\/ namespace remoting\n<|endoftext|>"} {"text":"\/*\n Copyright 2008 Brain Research Institute, Melbourne, Australia\n\n Written by Robert E. Smith, 06\/02\/14.\n\n This file is part of MRtrix.\n\n MRtrix is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n MRtrix is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with MRtrix. If not, see .\n\n*\/\n\n\n#include \n\n#include \n\n#include \"app.h\"\n#include \"bitset.h\"\n#include \"command.h\"\n#include \"datatype.h\"\n#include \"progressbar.h\"\n#include \"ptr.h\"\n\n#include \"image\/buffer.h\"\n#include \"image\/buffer_scratch.h\"\n#include \"image\/header.h\"\n#include \"image\/loop.h\"\n#include \"image\/utils.h\"\n#include \"image\/voxel.h\"\n\n#include \"math\/SH.h\"\n\n\nusing namespace MR;\nusing namespace App;\n\n\nvoid usage ()\n{\n\n AUTHOR = \"Robert E. Smith (r.smith@brain.org.au)\";\n\n\n DESCRIPTION\n + \"examine the values in spherical harmonic images to estimate (and optionally change) the SH basis used.\"\n\n + \"In previous versions of MRtrix, the convention used for storing spherical harmonic \"\n \"coefficients was a non-orthonormal basis (the m!=0 coefficients were a factor of \"\n \"sqrt(2) too large). This error has been rectified in the new MRtrix (assuming that \"\n \"compilation was performed without the USE_NON_ORTHONORMAL_SH_BASIS symbol defined), \"\n \"but will cause issues if processing SH data that was generated using an older version \"\n \"of MRtrix (or vice-versa).\"\n\n + \"This command provides a mechanism for testing the basis used in storage of image data \"\n \"representing a spherical harmonic series per voxel, and allows the user to forcibly \"\n \"modify the raw image data to conform to the desired basis.\";\n\n\n ARGUMENTS\n + Argument (\"SH\", \"the input image of SH coefficients.\").allow_multiple().type_image_in();\n\n\n OPTIONS\n + Option (\"force_old\", \"force the image data to use the old (i.e. non-orthonormal) basis\")\n + Option (\"force_new\", \"force the image data to use the new (i.e. orthonormal) basis\")\n + Option (\"force_native\", \"force the image data to use the basis under which MRtrix is compiled\");\n\n}\n\n\n\n\n\n\/\/ Perform a linear regression on the power ratio in each order\n\/\/ Omit l=2 - tends to be abnormally small due to non-isotropic brain-wide fibre distribution\n\/\/ Use this to project the power ratio at l=0; better predictor for poor data\n\/\/ Also, if the regression has a substantial gradient, warn the user\n\/\/ Threshold on gradient will depend on the basis of the image\n\/\/\nstd::pair get_regression (const std::vector& ratios)\n{\n const size_t n = ratios.size() - 1;\n double x[n], y[n];\n for (size_t i = 1; i != ratios.size(); ++i) {\n x[i-1] = (2*i)+2;\n y[i-1] = ratios[i];\n }\n double c0, c1, cov00, cov01, cov11, sumsq;\n gsl_fit_linear (x, 1, y, 1, n, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);\n return std::make_pair (c0, c1);\n}\n\n\n\n\n\ntemplate \nvoid check_and_update (Image::Header& H, const bool force_old, const bool force_new)\n{\n\n const size_t lmax = Math::SH::LforN (H.dim(3));\n\n \/\/ Flag which volumes are m==0 and which are not\n const ssize_t N = H.dim(3);\n BitSet mzero_terms (N, false);\n for (size_t l = 2; l <= lmax; l += 2)\n mzero_terms[Math::SH::index (l, 0)] = true;\n\n typename Image::Buffer buffer (H, (force_old || force_new));\n typename Image::Buffer::voxel_type v (buffer);\n\n \/\/ Need to mask out voxels where the DC term is zero\n Image::Info info_mask (H);\n info_mask.set_ndim (3);\n info_mask.datatype() = DataType::Bit;\n Image::BufferScratch mask (info_mask);\n Image::BufferScratch::voxel_type v_mask (mask);\n size_t voxel_count = 0;\n {\n Image::LoopInOrder loop (v, \"Masking image based on DC term...\", 0, 3);\n for (loop.start (v, v_mask); loop.ok(); loop.next (v, v_mask)) {\n const value_type value = v.value();\n if (value && std::isfinite (value)) {\n v_mask.value() = true;\n ++voxel_count;\n } else {\n v_mask.value() = false;\n }\n }\n }\n\n \/\/ Get sums independently for each l\n \n \/\/ Each order has a different power, and a different number of m!=0 volumes.\n \/\/ Therefore, calculate the mean-square intensity for the m==0 and m!=0\n \/\/ volumes independently, and report ratio for each harmonic order\n Ptr progress;\n if (App::log_level > 0 && App::log_level < 2)\n progress = new ProgressBar (\"Evaluating SH basis of image \" + H.name() + \"...\", N-1);\n\n std::vector ratios;\n\n for (size_t l = 2; l <= lmax; l += 2) {\n\n double mzero_sum = 0.0, mnonzero_sum = 0.0;\n Image::LoopInOrder loop (v, 0, 3);\n for (v[3] = ssize_t (Math::SH::NforL(l-2)); v[3] != ssize_t (Math::SH::NforL(l)); ++v[3]) {\n double sum = 0.0;\n for (loop.start (v, v_mask); loop.ok(); loop.next (v, v_mask)) {\n if (v_mask.value())\n sum += Math::pow2 (value_type(v.value()));\n }\n if (mzero_terms[v[3]]) {\n mzero_sum += sum;\n DEBUG (\"Volume \" + str(v[3]) + \", m==0, sum \" + str(sum));\n } else {\n mnonzero_sum += sum;\n DEBUG (\"Volume \" + str(v[3]) + \", m!=0, sum \" + str(sum));\n }\n if (progress)\n ++*progress;\n }\n\n const double mnonzero_MSoS = mnonzero_sum \/ (2.0 * l);\n const float power_ratio = mnonzero_MSoS\/mzero_sum;\n ratios.push_back (power_ratio);\n\n INFO (\"SH order \" + str(l) + \", ratio of m!=0 to m==0 power: \" + str(power_ratio) +\n \", overall m=0 power: \" + str (mzero_sum));\n\n }\n\n if (progress)\n progress = NULL;\n\n \/\/ First is ratio to be used for SH basis decision, second is gradient of regression\n std::pair regression;\n size_t l_for_decision;\n\n \/\/ The gradient will change depending on the current basis, so the threshold needs to also\n \/\/ The gradient is as a function of l, not of even orders\n float grad_threshold = -0.02;\n\n switch (lmax) {\n\n \/\/ Lmax == 2: only one order to use\n case 2:\n regression = std::make_pair (ratios.front(), 0.0);\n l_for_decision = 2;\n break;\n\n \/\/ Lmax = 4: Use l=4 order to determine SH basis, can't check gradient since l=2 is untrustworthy\n case 4:\n regression = std::make_pair (ratios.back(), 0.0);\n l_for_decision = 4;\n break;\n\n \/\/ Lmax = 6: Use l=4 order to determine SH basis, but checking the gradient is not reliable:\n \/\/ artificially double the threshold so the power ratio at l=6 needs to be substantially\n \/\/ smaller than l=4 to throw a warning\n case 6:\n regression = std::make_pair (ratios[1], 0.5 * (ratios[2] - ratios[1]));\n l_for_decision = 4;\n grad_threshold *= 2.0;\n break;\n\n \/\/ Lmax >= 8: Do a linear regression from l=4 to l=lmax, project back to l=0\n \/\/ (this is a more reliable quantification on poor data than l=4 alone)\n default:\n regression = get_regression (ratios);\n l_for_decision = 0;\n break;\n\n }\n\n DEBUG (\"Power ratio for assessing SH basis is \" + str(regression.first) + \" as derived from l=\" + str(l_for_decision));\n if (regression.second)\n DEBUG (\"Gradient of regression is \" + str(regression.second) + \"; threshold is \" + str(grad_threshold));\n\n \/\/ Threshold to make decision on what basis is being used, if unambiguous\n value_type multiplier = 1.0;\n if ((regression.first > (5.0\/3.0)) && (regression.first < (7.0\/3.0))) {\n CONSOLE (\"Image \" + str(H.name()) + \" appears to be in the old non-orthonormal basis\");\n if (force_new)\n multiplier = 1.0 \/ M_SQRT2;\n grad_threshold *= 2.0;\n } else if ((regression.first > (2.0\/3.0)) && (regression.first < (4.0\/3.0))) {\n CONSOLE (\"Image \" + str(H.name()) + \" appears to be in the new orthonormal basis\");\n if (force_old)\n multiplier = M_SQRT2;\n } else {\n multiplier = 0.0;\n WARN (\"Cannot make unambiguous decision on SH basis of image \" + H.name()\n + \" (power ratio \" + (l_for_decision ? (\"in l=\" + str(l_for_decision)) : (\"regressed to l=0\")) + \" is \" + str(regression.first) + \")\");\n }\n\n \/\/ Decide whether the user needs to be warned about a poor diffusion encoding scheme\n if (regression.second < grad_threshold) {\n WARN (\"Image \" + H.name() + \" may have been derived from poor directional encoding\");\n WARN (\"(m==0 to m!=0 power ratio decreasing by \" + str(-2.0*regression.second) + \" per even order)\");\n }\n\n \/\/ Adjust the image data in-place if necessary\n if (multiplier && (multiplier != 1.0)) {\n\n Image::LoopInOrder loop (v, 0, 3);\n ProgressBar progress (\"Modifying SH basis of image \" + H.name() + \"...\", N-1);\n for (v[3] = 1; v[3] != N; ++v[3]) {\n if (!mzero_terms[v[3]]) {\n for (loop.start (v); loop.ok(); loop.next (v))\n v.value() *= multiplier;\n }\n ++progress;\n }\n\n } else if (multiplier && (force_old || force_new)) {\n INFO (\"Image \" + H.name() + \" already in desired basis; nothing to do\");\n }\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nvoid run ()\n{\n bool force_old = get_options (\"force_old\").size();\n bool force_new = get_options (\"force_new\").size();\n if (force_old && force_new)\n throw Exception (\"Options -force_old and -force_new are mutually exclusive\");\n if (get_options (\"force_native\").size()) {\n if (force_old || force_new)\n throw Exception (\"Option -force_native cannot be used in conjunction with one of the other -force options\");\n#ifndef USE_NON_ORTHONORMAL_SH_BASIS\n INFO (\"Forcing to new orthonormal basis (native)\");\n force_new = true;\n#else\n INFO (\"Forcing to old non-orthonormal basis (native)\");\n force_old = true;\n#endif\n }\n\n for (std::vector::const_iterator i = argument.begin(); i != argument.end(); ++i) {\n\n const std::string path = *i;\n Image::Header H (path);\n if (H.ndim() != 4)\n throw Exception (\"Image \" + H.name() + \" is not 4D and therefore cannot be an SH image\");\n const size_t lmax = Math::SH::LforN (H.dim(3));\n if (!lmax)\n throw Exception (\"Image \" + H.name() + \" does not contain enough volumes to be an SH image\");\n if (Math::SH::NforL (lmax) != size_t(H.dim(3)))\n throw Exception (\"Image \" + H.name() + \" does not contain a number of volumes appropriate for an SH image\");\n if (!H.datatype().is_floating_point())\n throw Exception (\"Image \" + H.name() + \" does not use a floating-point format and therefore cannot be an SH image\");\n\n if (H.datatype().bytes() == 4)\n check_and_update (H, force_old, force_new);\n else\n check_and_update (H, force_old, force_new);\n\n }\n\n};\n\nshbasis: Changes to permit conversion of erroneous data\/*\n Copyright 2008 Brain Research Institute, Melbourne, Australia\n\n Written by Robert E. Smith, 06\/02\/14.\n\n This file is part of MRtrix.\n\n MRtrix is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n MRtrix is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with MRtrix. If not, see .\n\n*\/\n\n\n#include \n\n#include \n\n#include \"app.h\"\n#include \"bitset.h\"\n#include \"command.h\"\n#include \"datatype.h\"\n#include \"progressbar.h\"\n#include \"ptr.h\"\n\n#include \"image\/buffer.h\"\n#include \"image\/buffer_scratch.h\"\n#include \"image\/header.h\"\n#include \"image\/loop.h\"\n#include \"image\/utils.h\"\n#include \"image\/voxel.h\"\n\n#include \"math\/SH.h\"\n\n\nusing namespace MR;\nusing namespace App;\n\n\nconst char* conversions[] = { \"old\", \"new\", \"native\", \"force_oldtonew\", \"force_newtoold\", NULL };\nenum conv_t { NONE, OLD, NEW, FORCE_OLDTONEW, FORCE_NEWTOOLD };\n\n\nvoid usage ()\n{\n\n AUTHOR = \"Robert E. Smith (r.smith@brain.org.au)\";\n\n\n DESCRIPTION\n + \"examine the values in spherical harmonic images to estimate (and optionally change) the SH basis used.\"\n\n + \"In previous versions of MRtrix, the convention used for storing spherical harmonic \"\n \"coefficients was a non-orthonormal basis (the m!=0 coefficients were a factor of \"\n \"sqrt(2) too large). This error has been rectified in the new MRtrix (assuming that \"\n \"compilation was performed without the USE_NON_ORTHONORMAL_SH_BASIS symbol defined), \"\n \"but will cause issues if processing SH data that was generated using an older version \"\n \"of MRtrix (or vice-versa).\"\n\n + \"This command provides a mechanism for testing the basis used in storage of image data \"\n \"representing a spherical harmonic series per voxel, and allows the user to forcibly \"\n \"modify the raw image data to conform to the desired basis.\";\n\n\n ARGUMENTS\n + Argument (\"SH\", \"the input image of SH coefficients.\").allow_multiple().type_image_in();\n\n\n OPTIONS\n + Option (\"convert\", \"convert the image data in-place to the desired basis (if necessary). \"\n \"Options are: old, new, native (whichever basis MRtrix is compiled for; \"\n \"most likely the new orthonormal basis), force_oldtonew, force_newtoold. \"\n \"Note that for the \\\"force_*\\\" choices should ideally only be used in \"\n \"cases where the command is unable to automatically determine the SH basis \"\n \"using the existing image data.\")\n + Argument (\"mode\").type_choice (conversions);\n\n}\n\n\n\n\n\n\/\/ Perform a linear regression on the power ratio in each order\n\/\/ Omit l=2 - tends to be abnormally small due to non-isotropic brain-wide fibre distribution\n\/\/ Use this to project the power ratio at l=0; better predictor for poor data\n\/\/ Also, if the regression has a substantial gradient, warn the user\n\/\/ Threshold on gradient will depend on the basis of the image\n\/\/\nstd::pair get_regression (const std::vector& ratios)\n{\n const size_t n = ratios.size() - 1;\n double x[n], y[n];\n for (size_t i = 1; i != ratios.size(); ++i) {\n x[i-1] = (2*i)+2;\n y[i-1] = ratios[i];\n }\n double c0, c1, cov00, cov01, cov11, sumsq;\n gsl_fit_linear (x, 1, y, 1, n, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);\n return std::make_pair (c0, c1);\n}\n\n\n\n\n\ntemplate \nvoid check_and_update (Image::Header& H, const conv_t conversion)\n{\n\n const size_t lmax = Math::SH::LforN (H.dim(3));\n\n \/\/ Flag which volumes are m==0 and which are not\n const ssize_t N = H.dim(3);\n BitSet mzero_terms (N, false);\n for (size_t l = 2; l <= lmax; l += 2)\n mzero_terms[Math::SH::index (l, 0)] = true;\n\n \/\/ Open in read-write mode if there's a chance of modification\n typename Image::Buffer buffer (H, (conversion != NONE));\n typename Image::Buffer::voxel_type v (buffer);\n\n \/\/ Need to mask out voxels where the DC term is zero\n Image::Info info_mask (H);\n info_mask.set_ndim (3);\n info_mask.datatype() = DataType::Bit;\n Image::BufferScratch mask (info_mask);\n Image::BufferScratch::voxel_type v_mask (mask);\n size_t voxel_count = 0;\n {\n Image::LoopInOrder loop (v, \"Masking image based on DC term...\", 0, 3);\n for (loop.start (v, v_mask); loop.ok(); loop.next (v, v_mask)) {\n const value_type value = v.value();\n if (value && std::isfinite (value)) {\n v_mask.value() = true;\n ++voxel_count;\n } else {\n v_mask.value() = false;\n }\n }\n }\n\n \/\/ Get sums independently for each l\n \n \/\/ Each order has a different power, and a different number of m!=0 volumes.\n \/\/ Therefore, calculate the mean-square intensity for the m==0 and m!=0\n \/\/ volumes independently, and report ratio for each harmonic order\n Ptr progress;\n if (App::log_level > 0 && App::log_level < 2)\n progress = new ProgressBar (\"Evaluating SH basis of image \\\"\" + H.name() + \"\\\"...\", N-1);\n\n std::vector ratios;\n\n for (size_t l = 2; l <= lmax; l += 2) {\n\n double mzero_sum = 0.0, mnonzero_sum = 0.0;\n Image::LoopInOrder loop (v, 0, 3);\n for (v[3] = ssize_t (Math::SH::NforL(l-2)); v[3] != ssize_t (Math::SH::NforL(l)); ++v[3]) {\n double sum = 0.0;\n for (loop.start (v, v_mask); loop.ok(); loop.next (v, v_mask)) {\n if (v_mask.value())\n sum += Math::pow2 (value_type(v.value()));\n }\n if (mzero_terms[v[3]]) {\n mzero_sum += sum;\n DEBUG (\"Volume \" + str(v[3]) + \", m==0, sum \" + str(sum));\n } else {\n mnonzero_sum += sum;\n DEBUG (\"Volume \" + str(v[3]) + \", m!=0, sum \" + str(sum));\n }\n if (progress)\n ++*progress;\n }\n\n const double mnonzero_MSoS = mnonzero_sum \/ (2.0 * l);\n const float power_ratio = mnonzero_MSoS\/mzero_sum;\n ratios.push_back (power_ratio);\n\n INFO (\"SH order \" + str(l) + \", ratio of m!=0 to m==0 power: \" + str(power_ratio) +\n \", m==0 power: \" + str (mzero_sum));\n\n }\n\n if (progress)\n progress = NULL;\n\n \/\/ First is ratio to be used for SH basis decision, second is gradient of regression\n std::pair regression;\n size_t l_for_decision;\n\n \/\/ The gradient will change depending on the current basis, so the threshold needs to also\n \/\/ The gradient is as a function of l, not of even orders\n float grad_threshold = -0.02;\n\n switch (lmax) {\n\n \/\/ Lmax == 2: only one order to use\n case 2:\n regression = std::make_pair (ratios.front(), 0.0);\n l_for_decision = 2;\n break;\n\n \/\/ Lmax = 4: Use l=4 order to determine SH basis, can't check gradient since l=2 is untrustworthy\n case 4:\n regression = std::make_pair (ratios.back(), 0.0);\n l_for_decision = 4;\n break;\n\n \/\/ Lmax = 6: Use l=4 order to determine SH basis, but checking the gradient is not reliable:\n \/\/ artificially double the threshold so the power ratio at l=6 needs to be substantially\n \/\/ smaller than l=4 to throw a warning\n case 6:\n regression = std::make_pair (ratios[1], 0.5 * (ratios[2] - ratios[1]));\n l_for_decision = 4;\n grad_threshold *= 2.0;\n break;\n\n \/\/ Lmax >= 8: Do a linear regression from l=4 to l=lmax, project back to l=0\n \/\/ (this is a more reliable quantification on poor data than l=4 alone)\n default:\n regression = get_regression (ratios);\n l_for_decision = 0;\n break;\n\n }\n\n DEBUG (\"Power ratio for assessing SH basis is \" + str(regression.first) + \" as derived from l=\" + str(l_for_decision));\n if (regression.second)\n DEBUG (\"Gradient of regression is \" + str(regression.second) + \"; threshold is \" + str(grad_threshold));\n\n \/\/ Threshold to make decision on what basis is being used, if unambiguous\n value_type multiplier = 1.0;\n if ((regression.first > (5.0\/3.0)) && (regression.first < (7.0\/3.0))) {\n\n CONSOLE (\"Image \\\"\" + str(H.name()) + \"\\\" appears to be in the old non-orthonormal basis\");\n switch (conversion) {\n case NONE: break;\n case OLD: break;\n case NEW: multiplier = 1.0 \/ M_SQRT2; break;\n case FORCE_OLDTONEW: multiplier = 1.0 \/ M_SQRT2; break;\n case FORCE_NEWTOOLD: WARN (\"Refusing to convert image \\\"\" + H.name() + \"\\\" from new to old basis, as data appear to already be in the old non-orthonormal basis\"); return;\n }\n grad_threshold *= 2.0;\n\n } else if ((regression.first > (2.0\/3.0)) && (regression.first < (4.0\/3.0))) {\n\n CONSOLE (\"Image \\\"\" + str(H.name()) + \"\\\" appears to be in the new orthonormal basis\");\n switch (conversion) {\n case NONE: break;\n case OLD: multiplier = M_SQRT2; break;\n case NEW: break;\n case FORCE_OLDTONEW: WARN (\"Refusing to convert image \\\"\" + H.name() + \"\\\" from old to new basis, as data appear to already be in the new orthonormal basis\"); return;\n case FORCE_NEWTOOLD: multiplier = M_SQRT2; break;\n }\n\n } else {\n\n multiplier = 0.0;\n WARN (\"Cannot make unambiguous decision on SH basis of image \\\"\" + H.name()\n + \"\\\" (power ratio \" + (l_for_decision ? (\"in l=\" + str(l_for_decision)) : (\"regressed to l=0\")) + \" is \" + str(regression.first) + \")\");\n\n if (conversion == FORCE_OLDTONEW) {\n WARN (\"Forcing conversion of image \\\"\" + H.name() + \"\\\" from old to new SH basis on user request; however NO GUARANTEE IS PROVIDED on appropriateness of this conversion!\");\n multiplier = 1.0 \/ M_SQRT2;\n } else if (conversion == FORCE_NEWTOOLD) {\n WARN (\"Forcing conversion of image \\\"\" + H.name() + \"\\\" from new to old SH basis on user request; however NO GUARANTEE IS PROVIDED on appropriateness of this conversion!\");\n multiplier = M_SQRT2;\n }\n\n }\n\n \/\/ Decide whether the user needs to be warned about a poor diffusion encoding scheme\n if (regression.second < grad_threshold) {\n WARN (\"Image \\\"\" + H.name() + \"\\\" may have been derived from poor directional encoding\");\n WARN (\"(m==0 to m!=0 power ratio decreasing by \" + str(-2.0*regression.second) + \" per even order)\");\n }\n\n \/\/ Adjust the image data in-place if necessary\n if (multiplier && (multiplier != 1.0)) {\n\n Image::LoopInOrder loop (v, 0, 3);\n ProgressBar progress (\"Modifying SH basis of image \\\"\" + H.name() + \"\\\"...\", N-1);\n for (v[3] = 1; v[3] != N; ++v[3]) {\n if (!mzero_terms[v[3]]) {\n for (loop.start (v); loop.ok(); loop.next (v))\n v.value() *= multiplier;\n }\n ++progress;\n }\n\n } else if (multiplier && (conversion != NONE)) {\n INFO (\"Image \\\"\" + H.name() + \"\\\" already in desired basis; nothing to do\");\n }\n\n}\n\n\n\n\n\n\n\n\n\nvoid run ()\n{\n conv_t conversion = NONE;\n Options opt = get_options (\"convert\");\n if (opt.size()) {\n switch (int(opt[0][0])) {\n case 0: conversion = OLD; break;\n case 1: conversion = NEW; break;\n case 2:\n#ifndef USE_NON_ORTHONORMAL_SH_BASIS\n conversion = NEW;\n#else\n conversion = OLD;\n#endif\n break;\n case 3: conversion = FORCE_OLDTONEW; break;\n case 4: conversion = FORCE_NEWTOOLD; break;\n default: assert (0); break;\n }\n }\n\n for (std::vector::const_iterator i = argument.begin(); i != argument.end(); ++i) {\n\n const std::string path = *i;\n Image::Header H (path);\n if (H.ndim() != 4) {\n WARN (\"Image \\\"\" + H.name() + \"\\\" is not 4D and therefore cannot be an SH image\");\n continue;\n }\n const size_t lmax = Math::SH::LforN (H.dim(3));\n if (!lmax) {\n WARN (\"Image \\\"\" + H.name() + \"\\\" does not contain enough volumes to be an SH image\");\n continue;\n }\n if (Math::SH::NforL (lmax) != size_t(H.dim(3))) {\n WARN (\"Image \\\"\" + H.name() + \"\\\" does not contain a number of volumes appropriate for an SH image\");\n continue;\n }\n if (!H.datatype().is_floating_point()) {\n WARN (\"Image \\\"\" + H.name() + \"\\\" does not use a floating-point data type and therefore cannot be an SH image\");\n continue;\n }\n\n if (H.datatype().bytes() == 4)\n check_and_update (H, conversion);\n else\n check_and_update (H, conversion);\n\n }\n\n};\n\n<|endoftext|>"} {"text":"\/\/ -*- mode: c++; coding: utf-8 -*-\n\/*! @file gridsearch.cpp\n @brief Implementation of GridSearch class\n*\/\n#include \"gridsearch.hpp\"\n#include \"util.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace likeligrid {\n\nvoid GridSearch::init(const std::pair& epistasis_pair) {HERE;\n if (epistasis_pair.first != epistasis_pair.second) {\n model_.set_epistasis(epistasis_pair);\n }\n mle_params_.resize(model_.names().size());\n mle_params_ = 1.0;\n}\n\nvoid GridSearch::run(const bool writing) {HERE;\n while (stage_ < STEPS.size()) {\n if (writing) {run_fout();} else {run_cout();}\n }\n --stage_;\n search_limits();\n}\n\nvoid GridSearch::run_fout() {HERE;\n const std::string outfile = init_meta();\n std::cerr << \"mle_params_: \" << mle_params_ << std::endl;\n if (outfile.empty()) return;\n const auto axes = make_vicinity(mle_params_, BREAKS.at(stage_), radius(stage_));\n for (size_t j=0; j chisq(1.0);\n const double diff95 = 0.5 * bmath::quantile(bmath::complement(chisq, 0.05));\n auto axis = wtl::round(wtl::lin_spaced(200, 2.0, 0.01), 100);\n axis = (axis * 100.0).apply(std::round) \/ 100.0;\n std::map> intersections;\n for (size_t i=0; i range = axis[logliks > threshold];\n auto bound_params = mle_params_;\n bound_params[i] = std::max(range.min() - 0.01, 0.01);\n intersections.emplace(model_.names()[i] + \"_L\", bound_params);\n bound_params[i] = std::min(range.max() + 0.01, 2.00);\n intersections.emplace(model_.names()[i] + \"_U\", bound_params);\n }\n for (const auto& p: intersections) {\n const std::string outfile = \"limit-\" + p.first + \".tsv.gz\";\n std::cerr << outfile << \": \" << p.second << std::endl;\n const auto axes = make_vicinity(p.second, 5, 0.02);\n wtl::ozfstream fout(outfile);\n \/\/TODO: if exists\n run_impl(fout, wtl::itertools::product(axes));\n }\n}\n\nvoid GridSearch::run_impl(std::ostream& ost, wtl::itertools::Generator>&& gen) {HERE;\n std::cerr << skip_ << \" to \" << gen.max_count() << std::endl;\n if (skip_ == 0) {\n write_header(ost, gen.max_count());\n }\n\n wtl::Semaphore semaphore(concurrency_);\n auto task = [this,&semaphore](const std::valarray th_path) {\n std::lock_guard scope_unlock(semaphore, std::adopt_lock);\n \/\/ argument and model are copied for each thread\n auto buffer = wtl::make_oss();\n auto model_copy = this->model_;\n buffer << model_copy.calc_loglik(th_path) << \"\\t\"\n << wtl::str_join(th_path, \"\\t\") << \"\\n\";\n return buffer.str();\n };\n\n std::deque> futures;\n const auto min_interval = std::chrono::seconds(1);\n auto next_time = std::chrono::system_clock::now() + min_interval;\n size_t stars = 0;\n for (const auto& th_path: gen(skip_)) {\n semaphore.lock();\n futures.push_back(std::async(std::launch::async, task, th_path));\n auto now = std::chrono::system_clock::now();\n if (now > next_time) {\n next_time = now + min_interval;\n while (!futures.empty() && wtl::is_ready(futures.front())) {\n ost << futures.front().get();\n futures.pop_front();\n }\n for (size_t n= 0.2 * gen.percent(); stars= STEPS.size()) return \"\";\n auto oss = wtl::make_oss(2, std::ios::fixed);\n oss << \"grid-\" << STEPS.at(stage_) << \".tsv.gz\";\n std::string outfile = oss.str();\n try {\n wtl::izfstream ist(outfile);\n std::cerr << \"Reading: \" << outfile << std::endl;\n read_results(ist);\n if (skip_ == 0) {\n ++stage_;\n outfile = init_meta();\n }\n } catch (std::ios::failure& e) {\n if (errno != 2) throw;\n }\n return outfile;\n}\n\nvoid GridSearch::read_results(std::istream& ist) {HERE;\n size_t max_count;\n double step;\n std::tie(std::ignore, std::ignore, max_count, step) = read_metadata(ist);\n stage_ = guess_stage(step);\n std::vector colnames;\n std::valarray mle_params;\n std::tie(skip_, colnames, mle_params) = read_body(ist);\n if (skip_ == max_count) { \/\/ is complete file\n skip_ = 0;\n mle_params_.swap(mle_params);\n }\n}\n\nvoid GridSearch::read_results(const std::string& infile) {\n wtl::izfstream ist(infile);\n read_results(ist);\n}\n\nvoid GridSearch::write_header(std::ostream& ost, const size_t max_count) const {\n ost << \"##genotype_file=\" << model_.filename() << \"\\n\";\n ost << \"##max_sites=\" << model_.max_sites() << \"\\n\";\n ost << \"##max_count=\" << max_count << \"\\n\";\n ost << \"##step=\" << STEPS.at(stage_) << \"\\n\";\n ost << \"loglik\\t\" << wtl::join(model_.names(), \"\\t\") << \"\\n\";\n}\n\nvoid GridSearch::test() {HERE;\n std::stringstream sst;\n sst <<\nR\"({\n \"pathway\": [\"A\", \"B\"],\n \"annotation\": [\"0011\", \"1100\"],\n \"sample\": [\"0011\", \"0101\", \"1001\", \"0110\", \"1010\", \"1100\"]\n})\";\n GridSearch searcher(sst, 4, {0, 1});\n searcher.run_cout();\n}\n\n} \/\/ namespace likeligrid\nPut newline after progress stars\/\/ -*- mode: c++; coding: utf-8 -*-\n\/*! @file gridsearch.cpp\n @brief Implementation of GridSearch class\n*\/\n#include \"gridsearch.hpp\"\n#include \"util.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace likeligrid {\n\nvoid GridSearch::init(const std::pair& epistasis_pair) {HERE;\n if (epistasis_pair.first != epistasis_pair.second) {\n model_.set_epistasis(epistasis_pair);\n }\n mle_params_.resize(model_.names().size());\n mle_params_ = 1.0;\n}\n\nvoid GridSearch::run(const bool writing) {HERE;\n while (stage_ < STEPS.size()) {\n if (writing) {run_fout();} else {run_cout();}\n }\n --stage_;\n search_limits();\n}\n\nvoid GridSearch::run_fout() {HERE;\n const std::string outfile = init_meta();\n std::cerr << \"mle_params_: \" << mle_params_ << std::endl;\n if (outfile.empty()) return;\n const auto axes = make_vicinity(mle_params_, BREAKS.at(stage_), radius(stage_));\n for (size_t j=0; j chisq(1.0);\n const double diff95 = 0.5 * bmath::quantile(bmath::complement(chisq, 0.05));\n auto axis = wtl::round(wtl::lin_spaced(200, 2.0, 0.01), 100);\n axis = (axis * 100.0).apply(std::round) \/ 100.0;\n std::map> intersections;\n for (size_t i=0; i range = axis[logliks > threshold];\n auto bound_params = mle_params_;\n bound_params[i] = std::max(range.min() - 0.01, 0.01);\n intersections.emplace(model_.names()[i] + \"_L\", bound_params);\n bound_params[i] = std::min(range.max() + 0.01, 2.00);\n intersections.emplace(model_.names()[i] + \"_U\", bound_params);\n }\n for (const auto& p: intersections) {\n const std::string outfile = \"limit-\" + p.first + \".tsv.gz\";\n std::cerr << outfile << \": \" << p.second << std::endl;\n const auto axes = make_vicinity(p.second, 5, 0.02);\n wtl::ozfstream fout(outfile);\n \/\/TODO: if exists\n run_impl(fout, wtl::itertools::product(axes));\n }\n}\n\nvoid GridSearch::run_impl(std::ostream& ost, wtl::itertools::Generator>&& gen) {HERE;\n std::cerr << skip_ << \" to \" << gen.max_count() << std::endl;\n if (skip_ == 0) {\n write_header(ost, gen.max_count());\n }\n\n wtl::Semaphore semaphore(concurrency_);\n auto task = [this,&semaphore](const std::valarray th_path) {\n std::lock_guard scope_unlock(semaphore, std::adopt_lock);\n \/\/ argument and model are copied for each thread\n auto buffer = wtl::make_oss();\n auto model_copy = this->model_;\n buffer << model_copy.calc_loglik(th_path) << \"\\t\"\n << wtl::str_join(th_path, \"\\t\") << \"\\n\";\n return buffer.str();\n };\n\n std::deque> futures;\n const auto min_interval = std::chrono::seconds(1);\n auto next_time = std::chrono::system_clock::now() + min_interval;\n size_t stars = 0;\n for (const auto& th_path: gen(skip_)) {\n semaphore.lock();\n futures.push_back(std::async(std::launch::async, task, th_path));\n auto now = std::chrono::system_clock::now();\n if (now > next_time) {\n next_time = now + min_interval;\n while (!futures.empty() && wtl::is_ready(futures.front())) {\n ost << futures.front().get();\n futures.pop_front();\n }\n for (size_t n= 0.2 * gen.percent(); stars= STEPS.size()) return \"\";\n auto oss = wtl::make_oss(2, std::ios::fixed);\n oss << \"grid-\" << STEPS.at(stage_) << \".tsv.gz\";\n std::string outfile = oss.str();\n try {\n wtl::izfstream ist(outfile);\n std::cerr << \"Reading: \" << outfile << std::endl;\n read_results(ist);\n if (skip_ == 0) {\n ++stage_;\n outfile = init_meta();\n }\n } catch (std::ios::failure& e) {\n if (errno != 2) throw;\n }\n return outfile;\n}\n\nvoid GridSearch::read_results(std::istream& ist) {HERE;\n size_t max_count;\n double step;\n std::tie(std::ignore, std::ignore, max_count, step) = read_metadata(ist);\n stage_ = guess_stage(step);\n std::vector colnames;\n std::valarray mle_params;\n std::tie(skip_, colnames, mle_params) = read_body(ist);\n if (skip_ == max_count) { \/\/ is complete file\n skip_ = 0;\n mle_params_.swap(mle_params);\n }\n}\n\nvoid GridSearch::read_results(const std::string& infile) {\n wtl::izfstream ist(infile);\n read_results(ist);\n}\n\nvoid GridSearch::write_header(std::ostream& ost, const size_t max_count) const {\n ost << \"##genotype_file=\" << model_.filename() << \"\\n\";\n ost << \"##max_sites=\" << model_.max_sites() << \"\\n\";\n ost << \"##max_count=\" << max_count << \"\\n\";\n ost << \"##step=\" << STEPS.at(stage_) << \"\\n\";\n ost << \"loglik\\t\" << wtl::join(model_.names(), \"\\t\") << \"\\n\";\n}\n\nvoid GridSearch::test() {HERE;\n std::stringstream sst;\n sst <<\nR\"({\n \"pathway\": [\"A\", \"B\"],\n \"annotation\": [\"0011\", \"1100\"],\n \"sample\": [\"0011\", \"0101\", \"1001\", \"0110\", \"1010\", \"1100\"]\n})\";\n GridSearch searcher(sst, 4, {0, 1});\n searcher.run_cout();\n}\n\n} \/\/ namespace likeligrid\n<|endoftext|>"} {"text":"#ifndef CPPUT_TESTHARNESS_HPP\n#define CPPUT_TESTHARNESS_HPP\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\n\/\/\/ \\brief A light-weight and easy to use unit testing framework for C++\n\/\/\/ \\details Header-only unit testing framework that makes unit testing easy\n\/\/\/ and quick to set up.\n\/\/\/ \\version 0.2.0\n\/\/\/ \\date December 2011\n\/\/\/ \\author Tommy Back\n\/\/\/\n\/\/\/\n\/\/\/ Simply include this header file to get started.\n\/\/\/\n\/\/\/ \\code\n\/\/\/ #include \n\/\/\/ #include \n\/\/\/\n\/\/\/ TEST(Foo, some_descriptive_name)\n\/\/\/ {\n\/\/\/ \/\/ Arrange\n\/\/\/ Foo foo;\n\/\/\/ \/\/ Act\n\/\/\/ bool result = foo.isBar();\n\/\/\/ \/\/ Assert\n\/\/\/ ASSERT_TRUE(result);\n\/\/\/ }\n\/\/\/ \\endcode\n\/\/\/\n\/\/\/ In case you want to keep a single file with tests that compile to an\n\/\/\/ executable you can also add the main function to the end of the file.\n\/\/\/ This is simple to do with the provided macro:\n\/\/\/\n\/\/\/ \\code\n\/\/\/ CPPUT_TEST_MAIN;\n\/\/\/ \\endcode\n\/\/\/\n\/\/\/ For larger test suits, it's recommended to group the tests per class\n\/\/\/ in separate files and let the compiler combine them into a single\n\/\/\/ executable which has a main.cpp file that only has the main function\n\/\/\/ declared.\n\/\/\/\n\/\/\/ \\example\n\/\/\/ [Test_Foo.cpp]\n\/\/\/\n\/\/\/ \\code\n\/\/\/ #include \n\/\/\/ #include \n\/\/\/\n\/\/\/ TEST(Foo, foo_bar_z)\n\/\/\/ {\n\/\/\/ ...\n\/\/\/ \\endcode\n\/\/\/\n\/\/\/ [main.cpp]\n\/\/\/\n\/\/\/ \\code\n\/\/\/ #include \n\/\/\/\n\/\/\/ CPPUT_TEST_MAIN;\n\/\/\/ \\endcode\n\/\/\/\n\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace cpput\n{\n\nstruct ResultWriter\n{\n virtual ~ResultWriter() {}\n \n virtual void startTest(const std::string& className, const std::string& name) = 0;\n virtual void endTest(bool success) = 0;\n \n virtual void failure(const std::string& filename, std::size_t line, const std::string& message) = 0;\n virtual int getNumberOfFailures() const = 0;\n};\n\n\/\/ ----------------------------------------------------------------------------\n\nclass TextResultWriter : public ResultWriter\n{\npublic:\n TextResultWriter()\n : testCount_(0)\n , failures_(0)\n {\n }\n\n virtual ~TextResultWriter()\n {\n if (failures_ == 0)\n {\n std::cout << \"\\nAll tests pass.\\n\";\n return;\n }\n std::cout << \"\\n\" << failures_ << \" out of \" << testCount_ << \" tests failed.\\n\";\n }\n\n virtual void startTest(const std::string&, const std::string&)\n {\n testCount_++;\n }\n\n virtual void endTest(bool success)\n {\n if (success)\n std::cout << '.';\n else\n std::cout << 'F';\n }\n\n virtual void failure(const std::string& filename, std::size_t line, const std::string& message)\n {\n failures_++;\n std::cout << \"Failure: \" << filename << \", line \" << line << \": \" << message << '\\n';\n }\n\n virtual int getNumberOfFailures() const { return failures_; }\n\nprivate:\n int testCount_;\n int failures_;\n};\n\n\/\/ ----------------------------------------------------------------------------\n\nclass XmlResultWriter : public ResultWriter\n{\npublic:\n XmlResultWriter()\n : startTime_(0)\n {\n std::cout << \"\\n\";\n std::cout << \"\\n\";\n }\n\n virtual ~XmlResultWriter()\n {\n std::cout << \"<\/testsuite>\\n\";\n }\n\n virtual void startTest(const std::string& className, const std::string& name)\n {\n startTime_ = std::clock();\n std::cout << \" (std::clock()-startTime_)\/CLOCKS_PER_SEC << \"\\\"\";\n std::cout << \"\/>\\n\";\n }\n else\n std::cout << \" <\/testcase>\\n\";\n }\n\n virtual void failure(const std::string& filename, std::size_t line, const std::string& message)\n {\n std::cout << static_cast(std::clock()-startTime_)\/CLOCKS_PER_SEC << \"\\\"\";\n std::cout << \">\\n\"\n << \" \"\n << message\n << \" in \"\n << filename\n << \", line \"\n << line\n << \"<\/failure>\\n\";\n failureCount_++;\n }\n\n virtual int getNumberOfFailures() const\n {\n return failureCount_;\n }\n\nprivate:\n std::clock_t startTime_;\n int failureCount_;\n};\n\n\/\/ ----------------------------------------------------------------------------\n\nstruct Result\n{\n Result(const std::string& testClassName,\n const std::string& testName,\n ResultWriter& out)\n : out_(out)\n , pass_(true)\n {\n out_.startTest(testClassName, testName);\n }\n \n ~Result()\n {\n out_.endTest(pass_);\n }\n\n template \n void addFailure(const char* filename,\n std::size_t line,\n T expected,\n U actual)\n {\n pass_ = false;\n std::stringstream ss;\n ss << std::setprecision(20)\n << \"failed comparison, expected \" << expected\n << \" got \" << actual << \"\\n\";\n out_.failure(filename, line, ss.str());\n }\n\n void addFailure(const char* filename,\n std::size_t line,\n const char* message)\n {\n pass_ = false;\n out_.failure(filename, line, message);\n }\n\n ResultWriter& out_;\n bool pass_;\n};\n\n\/\/ ----------------------------------------------------------------------------\n\nclass Repository;\n\nclass Test\n{\n friend class Repository;\n\npublic:\n Test(const char* className, const char* name);\n virtual ~Test() {}\n\n void run(ResultWriter& out)\n {\n Result result(test_unit_class_name_, test_unit_name_, out);\n try\n {\n do_run(result);\n }\n catch (const std::exception& e)\n {\n result.addFailure(__FILE__, __LINE__, std::string(\"Unexpected exception: \").append(e.what()).c_str());\n }\n catch (...)\n {\n result.addFailure(__FILE__, __LINE__, \"Unspecified exception!\");\n }\n }\n \n Test* next() { return test_unit_next_; }\n\nprivate:\n virtual void do_run(Result& testResult_) = 0;\n\nprivate:\n std::string test_unit_class_name_;\n std::string test_unit_name_;\n Test* test_unit_next_;\n};\n\n\/\/ ----------------------------------------------------------------------------\n\nclass Repository\n{\npublic:\n static Repository& instance()\n {\n static Repository repo;\n return repo;\n }\n \n void add(Test* tc)\n {\n if (!tests_)\n {\n tests_ = tc;\n return;\n }\n\n \/\/ add as last\n Test* tmp = tests_;\n while (tmp->test_unit_next_)\n tmp = tmp->test_unit_next_;\n tmp->test_unit_next_ = tc;\n }\n \n Test* getTests() { return tests_; }\n\nprivate:\n Repository() : tests_(0) {}\n Repository(const Repository& other);\n Repository& operator=(const Repository& rhs) const;\n\nprivate:\n Test* tests_;\n};\n\ninline Test::Test(const char* className, const char* name)\n : test_unit_class_name_(className)\n , test_unit_name_(name)\n , test_unit_next_(0)\n{\n Repository::instance().add(this);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ninline int runAllTests(ResultWriter& writer)\n{\n Test* c = Repository::instance().getTests();\n while (c)\n {\n c->run(writer);\n c = c->next();\n }\n return writer.getNumberOfFailures();\n}\n\n} \/\/ namespace cpput\n\n\/\/ Convenience macro to get main function.\n#define CPPUT_TEST_MAIN \\\nint main(int argc, char* argv[]) { \\\n if (argc == 2 && std::string(argv[1]) == \"--xml\") { \\\n cpput::XmlResultWriter writer; \\\n return ::cpput::runAllTests(writer); \\\n } \\\n cpput::TextResultWriter writer; \\\n return ::cpput::runAllTests(writer); \\\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Test Macros\n\/\/ ----------------------------------------------------------------------------\n\n\/\/\/ Stand-alone test case.\n\/\/\/\n#define TEST(group,name) \\\nclass group##name##Test : public cpput::Test \\\n{ \\\npublic: \\\n group##name##Test() : cpput::Test(#group,#name) {} \\\n virtual ~group##name##Test() {} \\\nprivate: \\\n virtual void do_run(cpput::Result& testResult_); \\\n} group##name##TestInstance; \\\ninline void group##name##Test::do_run(cpput::Result& testResult_)\n\n\/\/\/ Test case with fixture.\n\/\/\/\n#define TEST_F(group,name) \\\nclass group##name##FixtureTest : public group { \\\npublic: \\\n void do_run(cpput::Result& testResult_); \\\n}; \\\nclass group##name##Test : public cpput::Test { \\\npublic: \\\n group##name##Test() : Test(#group,#name) {} \\\n virtual void do_run(cpput::Result& testResult_); \\\n} group##name##TestInstance; \\\ninline void group##name##Test::do_run(cpput::Result& testResult_) { \\\n group##name##FixtureTest test; \\\n test.do_run(testResult_); \\\n} \\\ninline void group##name##FixtureTest::do_run(cpput::Result& testResult_)\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Assertion Macros\n\/\/ ----------------------------------------------------------------------------\n\n#define ASSERT_TRUE(expression) \\\n{ \\\n if (expression) \\\n return; \\\n testResult_.addFailure(__FILE__, __LINE__, #expression); \\\n}\n\n#define ASSERT_FALSE(expression) ASSERT_TRUE(!(expression))\n\n#define ASSERT_EQ(expected,actual) \\\n{ \\\n if (!((expected) == (actual))) \\\n { \\\n testResult_.addFailure(__FILE__, __LINE__, expected, actual); \\\n return; \\\n } \\\n}\n\n#define ASSERT_NEQ(expected,actual) \\\n{ \\\n if (((expected) == (actual))) \\\n { \\\n testResult_.addFailure(__FILE__, __LINE__, expected, actual); \\\n return; \\\n } \\\n}\n\n#define ASSERT_STREQ(expected,actual) { \\\n if (!(std::string(expected) == std::string(actual))) \\\n { \\\n testResult_.addFailure(__FILE__, __LINE__, expected, actual); \\\n return; \\\n } \\\n}\n\n#define ASSERT_NEAR(expected,actual,epsilon) \\\n{ \\\n double actualTmp = actual; \\\n double expectedTmp = expected; \\\n double diff = expectedTmp - actualTmp; \\\n if ((diff > epsilon) || (-diff > epsilon)) \\\n { \\\n testResult_.addFailure(__FILE__, __LINE__, expectedTmp, actualTmp); \\\n return; \\\n } \\\n}\n\n#endif \/\/ CPPUT_TESTHARNESS_HPP\nAdded license info into header file.\/*\n Copyright (c) 2011-2014 Tommy Back\n\n Permission is hereby granted, free of charge, to any person obtaining\n a copy of this software and associated documentation files (the\n \"Software\"), to deal in the Software without restriction, including\n without limitation the rights to use, copy, modify, merge, publish,\n distribute, sublicense, and\/or sell copies of the Software, and to\n permit persons to whom the Software is furnished to do so, subject to\n the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n\/******************************************************************************\n * \n * \\brief A light-weight and easy to use unit testing framework for C++\n * \\details Header-only unit testing framework that makes unit testing easy\n * and quick to set up.\n * \\version 0.2.0\n * \\author Tommy Back\n * \n * \n * Simply include this header file to get started.\n * \n * \\code\n * #include \n * #include \n * \n * TEST(Foo, some_descriptive_name)\n * {\n * \/\/ Arrange\n * Foo foo;\n * \/\/ Act\n * bool result = foo.isBar();\n * \/\/ Assert\n * ASSERT_TRUE(result);\n * }\n * \\endcode\n * \n * In case you want to keep a single file with tests that compile to an\n * executable you can also add the main function to the end of the file.\n * This is simple to do with the provided macro:\n * \n * \\code\n * CPPUT_TEST_MAIN;\n * \\endcode\n * \n * For larger test suits, it's recommended to group the tests per class\n * in separate files and let the compiler combine them into a single\n * executable which has a main.cpp file that only has the main function\n * declared.\n * \n * \\example\n * [Test_Foo.cpp]\n * \n * \\code\n * #include \n * #include \n * \n * TEST(Foo, foo_bar_z)\n * {\n * ...\n * \\endcode\n * \n * [main.cpp]\n * \n * \\code\n * #include \n * \n * CPPUT_TEST_MAIN;\n * \\endcode\n * \n *\/\n\n#ifndef CPPUT_TESTHARNESS_HPP\n#define CPPUT_TESTHARNESS_HPP\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace cpput\n{\n\nstruct ResultWriter\n{\n virtual ~ResultWriter() {}\n \n virtual void startTest(const std::string& className, const std::string& name) = 0;\n virtual void endTest(bool success) = 0;\n \n virtual void failure(const std::string& filename, std::size_t line, const std::string& message) = 0;\n virtual int getNumberOfFailures() const = 0;\n};\n\n\/\/ ----------------------------------------------------------------------------\n\nclass TextResultWriter : public ResultWriter\n{\npublic:\n TextResultWriter()\n : testCount_(0)\n , failures_(0)\n {\n }\n\n virtual ~TextResultWriter()\n {\n if (failures_ == 0)\n {\n std::cout << \"\\nAll tests pass.\\n\";\n return;\n }\n std::cout << \"\\n\" << failures_ << \" out of \" << testCount_ << \" tests failed.\\n\";\n }\n\n virtual void startTest(const std::string&, const std::string&)\n {\n testCount_++;\n }\n\n virtual void endTest(bool success)\n {\n if (success)\n std::cout << '.';\n else\n std::cout << 'F';\n }\n\n virtual void failure(const std::string& filename, std::size_t line, const std::string& message)\n {\n failures_++;\n std::cout << \"Failure: \" << filename << \", line \" << line << \": \" << message << '\\n';\n }\n\n virtual int getNumberOfFailures() const { return failures_; }\n\nprivate:\n int testCount_;\n int failures_;\n};\n\n\/\/ ----------------------------------------------------------------------------\n\nclass XmlResultWriter : public ResultWriter\n{\npublic:\n XmlResultWriter()\n : startTime_(0)\n {\n std::cout << \"\\n\";\n std::cout << \"\\n\";\n }\n\n virtual ~XmlResultWriter()\n {\n std::cout << \"<\/testsuite>\\n\";\n }\n\n virtual void startTest(const std::string& className, const std::string& name)\n {\n startTime_ = std::clock();\n std::cout << \" (std::clock()-startTime_)\/CLOCKS_PER_SEC << \"\\\"\";\n std::cout << \"\/>\\n\";\n }\n else\n std::cout << \" <\/testcase>\\n\";\n }\n\n virtual void failure(const std::string& filename, std::size_t line, const std::string& message)\n {\n std::cout << static_cast(std::clock()-startTime_)\/CLOCKS_PER_SEC << \"\\\"\";\n std::cout << \">\\n\"\n << \" \"\n << message\n << \" in \"\n << filename\n << \", line \"\n << line\n << \"<\/failure>\\n\";\n failureCount_++;\n }\n\n virtual int getNumberOfFailures() const\n {\n return failureCount_;\n }\n\nprivate:\n std::clock_t startTime_;\n int failureCount_;\n};\n\n\/\/ ----------------------------------------------------------------------------\n\nstruct Result\n{\n Result(const std::string& testClassName,\n const std::string& testName,\n ResultWriter& out)\n : out_(out)\n , pass_(true)\n {\n out_.startTest(testClassName, testName);\n }\n \n ~Result()\n {\n out_.endTest(pass_);\n }\n\n template \n void addFailure(const char* filename,\n std::size_t line,\n T expected,\n U actual)\n {\n pass_ = false;\n std::stringstream ss;\n ss << std::setprecision(20)\n << \"failed comparison, expected \" << expected\n << \" got \" << actual << \"\\n\";\n out_.failure(filename, line, ss.str());\n }\n\n void addFailure(const char* filename,\n std::size_t line,\n const char* message)\n {\n pass_ = false;\n out_.failure(filename, line, message);\n }\n\n ResultWriter& out_;\n bool pass_;\n};\n\n\/\/ ----------------------------------------------------------------------------\n\nclass Repository;\n\nclass Test\n{\n friend class Repository;\n\npublic:\n Test(const char* className, const char* name);\n virtual ~Test() {}\n\n void run(ResultWriter& out)\n {\n Result result(test_unit_class_name_, test_unit_name_, out);\n try\n {\n do_run(result);\n }\n catch (const std::exception& e)\n {\n result.addFailure(__FILE__, __LINE__, std::string(\"Unexpected exception: \").append(e.what()).c_str());\n }\n catch (...)\n {\n result.addFailure(__FILE__, __LINE__, \"Unspecified exception!\");\n }\n }\n \n Test* next() { return test_unit_next_; }\n\nprivate:\n virtual void do_run(Result& testResult_) = 0;\n\nprivate:\n std::string test_unit_class_name_;\n std::string test_unit_name_;\n Test* test_unit_next_;\n};\n\n\/\/ ----------------------------------------------------------------------------\n\nclass Repository\n{\npublic:\n static Repository& instance()\n {\n static Repository repo;\n return repo;\n }\n \n void add(Test* tc)\n {\n if (!tests_)\n {\n tests_ = tc;\n return;\n }\n\n \/\/ add as last\n Test* tmp = tests_;\n while (tmp->test_unit_next_)\n tmp = tmp->test_unit_next_;\n tmp->test_unit_next_ = tc;\n }\n \n Test* getTests() { return tests_; }\n\nprivate:\n Repository() : tests_(0) {}\n Repository(const Repository& other);\n Repository& operator=(const Repository& rhs) const;\n\nprivate:\n Test* tests_;\n};\n\ninline Test::Test(const char* className, const char* name)\n : test_unit_class_name_(className)\n , test_unit_name_(name)\n , test_unit_next_(0)\n{\n Repository::instance().add(this);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ninline int runAllTests(ResultWriter& writer)\n{\n Test* c = Repository::instance().getTests();\n while (c)\n {\n c->run(writer);\n c = c->next();\n }\n return writer.getNumberOfFailures();\n}\n\n} \/\/ namespace cpput\n\n\/\/ Convenience macro to get main function.\n#define CPPUT_TEST_MAIN \\\nint main(int argc, char* argv[]) { \\\n if (argc == 2 && std::string(argv[1]) == \"--xml\") { \\\n cpput::XmlResultWriter writer; \\\n return ::cpput::runAllTests(writer); \\\n } \\\n cpput::TextResultWriter writer; \\\n return ::cpput::runAllTests(writer); \\\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Test Macros\n\/\/ ----------------------------------------------------------------------------\n\n\/\/\/ Stand-alone test case.\n\/\/\/\n#define TEST(group,name) \\\nclass group##name##Test : public cpput::Test \\\n{ \\\npublic: \\\n group##name##Test() : cpput::Test(#group,#name) {} \\\n virtual ~group##name##Test() {} \\\nprivate: \\\n virtual void do_run(cpput::Result& testResult_); \\\n} group##name##TestInstance; \\\ninline void group##name##Test::do_run(cpput::Result& testResult_)\n\n\/\/\/ Test case with fixture.\n\/\/\/\n#define TEST_F(group,name) \\\nclass group##name##FixtureTest : public group { \\\npublic: \\\n void do_run(cpput::Result& testResult_); \\\n}; \\\nclass group##name##Test : public cpput::Test { \\\npublic: \\\n group##name##Test() : Test(#group,#name) {} \\\n virtual void do_run(cpput::Result& testResult_); \\\n} group##name##TestInstance; \\\ninline void group##name##Test::do_run(cpput::Result& testResult_) { \\\n group##name##FixtureTest test; \\\n test.do_run(testResult_); \\\n} \\\ninline void group##name##FixtureTest::do_run(cpput::Result& testResult_)\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Assertion Macros\n\/\/ ----------------------------------------------------------------------------\n\n#define ASSERT_TRUE(expression) \\\n{ \\\n if (expression) \\\n return; \\\n testResult_.addFailure(__FILE__, __LINE__, #expression); \\\n}\n\n#define ASSERT_FALSE(expression) ASSERT_TRUE(!(expression))\n\n#define ASSERT_EQ(expected,actual) \\\n{ \\\n if (!((expected) == (actual))) \\\n { \\\n testResult_.addFailure(__FILE__, __LINE__, expected, actual); \\\n return; \\\n } \\\n}\n\n#define ASSERT_NEQ(expected,actual) \\\n{ \\\n if (((expected) == (actual))) \\\n { \\\n testResult_.addFailure(__FILE__, __LINE__, expected, actual); \\\n return; \\\n } \\\n}\n\n#define ASSERT_STREQ(expected,actual) { \\\n if (!(std::string(expected) == std::string(actual))) \\\n { \\\n testResult_.addFailure(__FILE__, __LINE__, expected, actual); \\\n return; \\\n } \\\n}\n\n#define ASSERT_NEAR(expected,actual,epsilon) \\\n{ \\\n double actualTmp = actual; \\\n double expectedTmp = expected; \\\n double diff = expectedTmp - actualTmp; \\\n if ((diff > epsilon) || (-diff > epsilon)) \\\n { \\\n testResult_.addFailure(__FILE__, __LINE__, expectedTmp, actualTmp); \\\n return; \\\n } \\\n}\n\n#endif \/\/ CPPUT_TESTHARNESS_HPP\n<|endoftext|>"} {"text":"\/* ------------------------------------------------------------------------ *\/\n\/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\/\n\/* not use this file except in compliance with the License. You may obtain *\/\n\/* a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\/\n\/* See the License for the specific language governing permissions and *\/\n\/* limitations under the License. *\/\n\/* ------------------------------------------------------------------------ *\/\n\n#include \n#include \n\n#include \n#include \n\n#include \"Group.h\"\n#include \"Nebula.h\"\n\nconst char * Group::table = \"group_pool\";\n\nconst char * Group::db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\nconst char * Group::db_bootstrap = \"CREATE TABLE IF NOT EXISTS group_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name))\";\n\n\/* ************************************************************************ *\/\n\/* Group :: Database Access Functions *\/\n\/* ************************************************************************ *\/\n\nint Group::select(SqlDB * db)\n{\n int rc;\n\n rc = PoolObjectSQL::select(db);\n\n if ( rc != 0 )\n {\n return rc;\n }\n\n return quota.select(oid, db);\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\nint Group::select(SqlDB * db, const string& name, int uid)\n{\n int rc;\n\n rc = PoolObjectSQL::select(db,name,uid);\n\n if ( rc != 0 )\n {\n return rc;\n }\n\n return quota.select(oid, db);\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint Group::drop(SqlDB * db)\n{\n int rc;\n\n rc = PoolObjectSQL::drop(db);\n\n if ( rc == 0 )\n {\n rc += quota.drop(db);\n }\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint Group::insert(SqlDB *db, string& error_str)\n{\n int rc;\n\n rc = insert_replace(db, false, error_str);\n\n if (rc == 0)\n {\n rc = quota.insert(oid, db, error_str);\n }\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint Group::insert_replace(SqlDB *db, bool replace, string& error_str)\n{\n ostringstream oss;\n\n int rc;\n string xml_body;\n\n char * sql_name;\n char * sql_xml;\n\n \/\/ Set oneadmin as the owner\n set_user(0,\"\");\n\n \/\/ Set the Group ID as the group it belongs to\n set_group(oid, name);\n\n \/\/ Update the Group\n\n sql_name = db->escape_str(name.c_str());\n\n if ( sql_name == 0 )\n {\n goto error_name;\n }\n\n sql_xml = db->escape_str(to_xml(xml_body).c_str());\n\n if ( sql_xml == 0 )\n {\n goto error_body;\n }\n\n if ( validate_xml(sql_xml) != 0 )\n {\n goto error_xml;\n }\n\n if ( replace )\n {\n oss << \"REPLACE\";\n }\n else\n {\n oss << \"INSERT\";\n }\n\n \/\/ Construct the SQL statement to Insert or Replace\n\n oss <<\" INTO \"<exec(oss);\n\n db->free_str(sql_name);\n db->free_str(sql_xml);\n\n return rc;\n\nerror_xml:\n db->free_str(sql_name);\n db->free_str(sql_xml);\n\n error_str = \"Error transforming the Group to XML.\";\n\n goto error_common;\n\nerror_body:\n db->free_str(sql_name);\n goto error_generic;\n\nerror_name:\n goto error_generic;\n\nerror_generic:\n error_str = \"Error inserting Group in DB.\";\nerror_common:\n return -1;\n}\n\n\/* ------------------------------------------------------------------------ *\/\n\/* ------------------------------------------------------------------------ *\/\n\nstring& Group::to_xml(string& xml) const\n{\n return to_xml_extended(xml, false);\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nstring& Group::to_xml_extended(string& xml) const\n{\n return to_xml_extended(xml, true);\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nstring& Group::to_xml_extended(string& xml, bool extended) const\n{\n ostringstream oss;\n string collection_xml;\n string admins_xml;\n string template_xml;\n\n oss <<\n \"\" <<\n \"\" << oid << \"<\/ID>\" <<\n \"\" << name << \"<\/NAME>\" <<\n obj_template->to_xml(template_xml) <<\n users.to_xml(collection_xml) <<\n admins.to_xml(admins_xml);\n\n if (extended)\n {\n string quota_xml;\n string def_quota_xml;\n\n oss << quota.to_xml(quota_xml)\n << Nebula::instance().get_default_group_quota().to_xml(def_quota_xml);\n }\n\n oss << \"<\/GROUP>\";\n\n xml = oss.str();\n\n return xml;\n}\n\n\/* ------------------------------------------------------------------------ *\/\n\/* ------------------------------------------------------------------------ *\/\n\nint Group::from_xml(const string& xml)\n{\n int rc = 0;\n vector content;\n vector::iterator it;\n\n \/\/ Initialize the internal XML object\n update_from_str(xml);\n\n \/\/ Get class base attributes\n rc += xpath(oid, \"\/GROUP\/ID\", -1);\n rc += xpath(name,\"\/GROUP\/NAME\", \"not_found\");\n\n \/\/ Set oneadmin as the owner\n set_user(0,\"\");\n\n \/\/ Set the Group ID as the group it belongs to\n set_group(oid, name);\n\n \/\/ Set of IDs\n rc += users.from_xml(this, \"\/GROUP\/\");\n\n \/\/ Set of Admin IDs\n rc += admins.from_xml(this, \"\/GROUP\/\");\n\n \/\/ Get associated metadata for the group\n ObjectXML::get_nodes(\"\/GROUP\/TEMPLATE\", content);\n\n if (content.empty())\n {\n return -1;\n }\n\n rc += obj_template->from_xml_node(content[0]);\n\n ObjectXML::free_nodes(content);\n content.clear();\n\n if (rc != 0)\n {\n return -1;\n }\n\n return 0;\n}\n\n\/* ------------------------------------------------------------------------ *\/\n\/* ------------------------------------------------------------------------ *\/\n\nint Group::add_admin(int user_id, string& error_msg)\n{\n int rc;\n ostringstream oss;\n\n if ( users.contains(user_id) == false )\n {\n oss << \"User \" << user_id << \" is not part of Group \"\n << oid << \".\";\n\n error_msg = oss.str();\n\n return -1;\n }\n\n rc = admins.add(user_id);\n\n if (rc == -1)\n {\n oss << \"User \" << user_id << \" is already an administrator of Group \"\n << oid << \".\";\n\n error_msg = oss.str();\n\n return -1;\n }\n\n add_admin_rules(user_id);\n\n return 0;\n}\n\n\/* ------------------------------------------------------------------------ *\/\n\/* ------------------------------------------------------------------------ *\/\n\nvoid Group::add_admin_rules(int user_id)\n{\n int rc;\n string error_msg;\n\n AclManager* aclm = Nebula::instance().get_aclm();\n\n \/\/ # USER\/@ USE+MANAGE+ADMIN+CREATE *\n rc = aclm->add_rule(\n AclRule::INDIVIDUAL_ID |\n user_id,\n\n PoolObjectSQL::USER |\n AclRule::GROUP_ID |\n oid,\n\n AuthRequest::USE |\n AuthRequest::MANAGE |\n AuthRequest::ADMIN |\n AuthRequest::CREATE,\n\n AclRule::ALL_ID,\n\n error_msg);\n\n if (rc < 0)\n {\n NebulaLog::log(\"GROUP\",Log::ERROR,error_msg);\n }\n\n \/\/ # VM+NET+IMAGE+TEMPLATE+DOCUMENT+SECGROUP+VROUTER\/@ USE+MANAGE *\n rc = aclm->add_rule(\n AclRule::INDIVIDUAL_ID |\n user_id,\n\n PoolObjectSQL::VM |\n PoolObjectSQL::NET |\n PoolObjectSQL::IMAGE |\n PoolObjectSQL::TEMPLATE |\n PoolObjectSQL::DOCUMENT |\n PoolObjectSQL::SECGROUP |\n PoolObjectSQL::VROUTER |\n AclRule::GROUP_ID |\n oid,\n\n AuthRequest::USE |\n AuthRequest::MANAGE,\n\n AclRule::ALL_ID,\n\n error_msg);\n\n if (rc < 0)\n {\n NebulaLog::log(\"GROUP\",Log::ERROR,error_msg);\n }\n}\n\n\/* ------------------------------------------------------------------------ *\/\n\/* ------------------------------------------------------------------------ *\/\n\nint Group::del_admin(int user_id, string& error_msg)\n{\n int rc = admins.del(user_id);\n\n if (rc == -1)\n {\n ostringstream oss;\n oss << \"User \" << user_id << \" is not an administrator of Group \"\n << oid << \".\";\n\n error_msg = oss.str();\n\n return -1;\n }\n\n del_admin_rules(user_id);\n\n return 0;\n}\n\n\/* ------------------------------------------------------------------------ *\/\n\/* ------------------------------------------------------------------------ *\/\n\nvoid Group::del_admin_rules(int user_id)\n{\n int rc;\n string error_msg;\n\n AclManager* aclm = Nebula::instance().get_aclm();\n\n \/\/ # USER\/@ USE+MANAGE+ADMIN+CREATE *\n rc = aclm->del_rule(\n AclRule::INDIVIDUAL_ID |\n user_id,\n\n PoolObjectSQL::USER |\n AclRule::GROUP_ID |\n oid,\n\n AuthRequest::USE |\n AuthRequest::MANAGE |\n AuthRequest::ADMIN |\n AuthRequest::CREATE,\n\n AclRule::ALL_ID,\n\n error_msg);\n\n if (rc < 0)\n {\n NebulaLog::log(\"GROUP\",Log::ERROR,error_msg);\n }\n\n \/\/ # VM+NET+IMAGE+TEMPLATE+DOCUMENT+SECGROUP+VROUTER\/@ USE+MANAGE *\n rc = aclm->del_rule(\n AclRule::INDIVIDUAL_ID |\n user_id,\n\n PoolObjectSQL::VM |\n PoolObjectSQL::NET |\n PoolObjectSQL::IMAGE |\n PoolObjectSQL::TEMPLATE |\n PoolObjectSQL::DOCUMENT |\n PoolObjectSQL::SECGROUP |\n PoolObjectSQL::VROUTER |\n AclRule::GROUP_ID |\n oid,\n\n AuthRequest::USE |\n AuthRequest::MANAGE,\n\n AclRule::ALL_ID,\n\n error_msg);\n\n if (rc < 0)\n {\n NebulaLog::log(\"GROUP\",Log::ERROR,error_msg);\n }\n}\nbug #4477: Add\/del # VROUTER\/* CREATE * for group admins by default\/* ------------------------------------------------------------------------ *\/\n\/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\/\n\/* not use this file except in compliance with the License. You may obtain *\/\n\/* a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\/\n\/* See the License for the specific language governing permissions and *\/\n\/* limitations under the License. *\/\n\/* ------------------------------------------------------------------------ *\/\n\n#include \n#include \n\n#include \n#include \n\n#include \"Group.h\"\n#include \"Nebula.h\"\n\nconst char * Group::table = \"group_pool\";\n\nconst char * Group::db_names =\n \"oid, name, body, uid, gid, owner_u, group_u, other_u\";\n\nconst char * Group::db_bootstrap = \"CREATE TABLE IF NOT EXISTS group_pool (\"\n \"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, \"\n \"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, \"\n \"UNIQUE(name))\";\n\n\/* ************************************************************************ *\/\n\/* Group :: Database Access Functions *\/\n\/* ************************************************************************ *\/\n\nint Group::select(SqlDB * db)\n{\n int rc;\n\n rc = PoolObjectSQL::select(db);\n\n if ( rc != 0 )\n {\n return rc;\n }\n\n return quota.select(oid, db);\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\nint Group::select(SqlDB * db, const string& name, int uid)\n{\n int rc;\n\n rc = PoolObjectSQL::select(db,name,uid);\n\n if ( rc != 0 )\n {\n return rc;\n }\n\n return quota.select(oid, db);\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint Group::drop(SqlDB * db)\n{\n int rc;\n\n rc = PoolObjectSQL::drop(db);\n\n if ( rc == 0 )\n {\n rc += quota.drop(db);\n }\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint Group::insert(SqlDB *db, string& error_str)\n{\n int rc;\n\n rc = insert_replace(db, false, error_str);\n\n if (rc == 0)\n {\n rc = quota.insert(oid, db, error_str);\n }\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint Group::insert_replace(SqlDB *db, bool replace, string& error_str)\n{\n ostringstream oss;\n\n int rc;\n string xml_body;\n\n char * sql_name;\n char * sql_xml;\n\n \/\/ Set oneadmin as the owner\n set_user(0,\"\");\n\n \/\/ Set the Group ID as the group it belongs to\n set_group(oid, name);\n\n \/\/ Update the Group\n\n sql_name = db->escape_str(name.c_str());\n\n if ( sql_name == 0 )\n {\n goto error_name;\n }\n\n sql_xml = db->escape_str(to_xml(xml_body).c_str());\n\n if ( sql_xml == 0 )\n {\n goto error_body;\n }\n\n if ( validate_xml(sql_xml) != 0 )\n {\n goto error_xml;\n }\n\n if ( replace )\n {\n oss << \"REPLACE\";\n }\n else\n {\n oss << \"INSERT\";\n }\n\n \/\/ Construct the SQL statement to Insert or Replace\n\n oss <<\" INTO \"<
exec(oss);\n\n db->free_str(sql_name);\n db->free_str(sql_xml);\n\n return rc;\n\nerror_xml:\n db->free_str(sql_name);\n db->free_str(sql_xml);\n\n error_str = \"Error transforming the Group to XML.\";\n\n goto error_common;\n\nerror_body:\n db->free_str(sql_name);\n goto error_generic;\n\nerror_name:\n goto error_generic;\n\nerror_generic:\n error_str = \"Error inserting Group in DB.\";\nerror_common:\n return -1;\n}\n\n\/* ------------------------------------------------------------------------ *\/\n\/* ------------------------------------------------------------------------ *\/\n\nstring& Group::to_xml(string& xml) const\n{\n return to_xml_extended(xml, false);\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nstring& Group::to_xml_extended(string& xml) const\n{\n return to_xml_extended(xml, true);\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nstring& Group::to_xml_extended(string& xml, bool extended) const\n{\n ostringstream oss;\n string collection_xml;\n string admins_xml;\n string template_xml;\n\n oss <<\n \"\" <<\n \"\" << oid << \"<\/ID>\" <<\n \"\" << name << \"<\/NAME>\" <<\n obj_template->to_xml(template_xml) <<\n users.to_xml(collection_xml) <<\n admins.to_xml(admins_xml);\n\n if (extended)\n {\n string quota_xml;\n string def_quota_xml;\n\n oss << quota.to_xml(quota_xml)\n << Nebula::instance().get_default_group_quota().to_xml(def_quota_xml);\n }\n\n oss << \"<\/GROUP>\";\n\n xml = oss.str();\n\n return xml;\n}\n\n\/* ------------------------------------------------------------------------ *\/\n\/* ------------------------------------------------------------------------ *\/\n\nint Group::from_xml(const string& xml)\n{\n int rc = 0;\n vector content;\n vector::iterator it;\n\n \/\/ Initialize the internal XML object\n update_from_str(xml);\n\n \/\/ Get class base attributes\n rc += xpath(oid, \"\/GROUP\/ID\", -1);\n rc += xpath(name,\"\/GROUP\/NAME\", \"not_found\");\n\n \/\/ Set oneadmin as the owner\n set_user(0,\"\");\n\n \/\/ Set the Group ID as the group it belongs to\n set_group(oid, name);\n\n \/\/ Set of IDs\n rc += users.from_xml(this, \"\/GROUP\/\");\n\n \/\/ Set of Admin IDs\n rc += admins.from_xml(this, \"\/GROUP\/\");\n\n \/\/ Get associated metadata for the group\n ObjectXML::get_nodes(\"\/GROUP\/TEMPLATE\", content);\n\n if (content.empty())\n {\n return -1;\n }\n\n rc += obj_template->from_xml_node(content[0]);\n\n ObjectXML::free_nodes(content);\n content.clear();\n\n if (rc != 0)\n {\n return -1;\n }\n\n return 0;\n}\n\n\/* ------------------------------------------------------------------------ *\/\n\/* ------------------------------------------------------------------------ *\/\n\nint Group::add_admin(int user_id, string& error_msg)\n{\n int rc;\n ostringstream oss;\n\n if ( users.contains(user_id) == false )\n {\n oss << \"User \" << user_id << \" is not part of Group \"\n << oid << \".\";\n\n error_msg = oss.str();\n\n return -1;\n }\n\n rc = admins.add(user_id);\n\n if (rc == -1)\n {\n oss << \"User \" << user_id << \" is already an administrator of Group \"\n << oid << \".\";\n\n error_msg = oss.str();\n\n return -1;\n }\n\n add_admin_rules(user_id);\n\n return 0;\n}\n\n\/* ------------------------------------------------------------------------ *\/\n\/* ------------------------------------------------------------------------ *\/\n\nvoid Group::add_admin_rules(int user_id)\n{\n string error_msg;\n\n AclManager* aclm = Nebula::instance().get_aclm();\n\n \/\/ # USER\/@ USE+MANAGE+ADMIN+CREATE *\n if ( aclm->add_rule(\n AclRule::INDIVIDUAL_ID |\n user_id,\n\n PoolObjectSQL::USER |\n AclRule::GROUP_ID |\n oid,\n\n AuthRequest::USE |\n AuthRequest::MANAGE |\n AuthRequest::ADMIN |\n AuthRequest::CREATE,\n\n AclRule::ALL_ID,\n\n error_msg) < 0 )\n {\n NebulaLog::log(\"GROUP\",Log::ERROR,error_msg);\n }\n\n \/\/ # VM+NET+IMAGE+TEMPLATE+DOCUMENT+SECGROUP+VROUTER\/@ USE+MANAGE *\n if ( aclm->add_rule(\n AclRule::INDIVIDUAL_ID |\n user_id,\n\n PoolObjectSQL::VM |\n PoolObjectSQL::NET |\n PoolObjectSQL::IMAGE |\n PoolObjectSQL::TEMPLATE |\n PoolObjectSQL::DOCUMENT |\n PoolObjectSQL::SECGROUP |\n PoolObjectSQL::VROUTER |\n AclRule::GROUP_ID |\n oid,\n\n AuthRequest::USE |\n AuthRequest::MANAGE,\n\n AclRule::ALL_ID,\n\n error_msg) < 0 )\n {\n NebulaLog::log(\"GROUP\",Log::ERROR,error_msg);\n }\n\n \/\/ # VROUTER\/* CREATE *\n if ( aclm->add_rule(\n AclRule::INDIVIDUAL_ID |\n user_id,\n\n AclRule::ALL_ID |\n PoolObjectSQL::VROUTER,\n\n AuthRequest::CREATE,\n\n AclRule::ALL_ID,\n\n error_msg) < 0 )\n {\n NebulaLog::log(\"GROUP\",Log::ERROR,error_msg);\n }\n}\n\n\/* ------------------------------------------------------------------------ *\/\n\/* ------------------------------------------------------------------------ *\/\n\nint Group::del_admin(int user_id, string& error_msg)\n{\n int rc = admins.del(user_id);\n\n if (rc == -1)\n {\n ostringstream oss;\n oss << \"User \" << user_id << \" is not an administrator of Group \"\n << oid << \".\";\n\n error_msg = oss.str();\n\n return -1;\n }\n\n del_admin_rules(user_id);\n\n return 0;\n}\n\n\/* ------------------------------------------------------------------------ *\/\n\/* ------------------------------------------------------------------------ *\/\n\nvoid Group::del_admin_rules(int user_id)\n{\n string error_msg;\n\n AclManager *aclm = Nebula::instance().get_aclm();\n\n \/\/ # USER\/@ USE+MANAGE+ADMIN+CREATE *\n if ( aclm->del_rule(\n AclRule::INDIVIDUAL_ID |\n user_id,\n\n PoolObjectSQL::USER |\n AclRule::GROUP_ID |\n oid,\n\n AuthRequest::USE |\n AuthRequest::MANAGE |\n AuthRequest::ADMIN |\n AuthRequest::CREATE,\n\n AclRule::ALL_ID,\n\n error_msg) < 0)\n {\n NebulaLog::log(\"GROUP\",Log::ERROR,error_msg);\n }\n\n \/\/ # VM+NET+IMAGE+TEMPLATE+DOCUMENT+SECGROUP+VROUTER\/@ USE+MANAGE *\n if ( aclm->del_rule(\n AclRule::INDIVIDUAL_ID |\n user_id,\n\n PoolObjectSQL::VM |\n PoolObjectSQL::NET |\n PoolObjectSQL::IMAGE |\n PoolObjectSQL::TEMPLATE |\n PoolObjectSQL::DOCUMENT |\n PoolObjectSQL::SECGROUP |\n PoolObjectSQL::VROUTER |\n AclRule::GROUP_ID |\n oid,\n\n AuthRequest::USE |\n AuthRequest::MANAGE,\n\n AclRule::ALL_ID,\n\n error_msg) < 0)\n {\n NebulaLog::log(\"GROUP\",Log::ERROR,error_msg);\n }\n\n \/\/ # VROUTER\/* CREATE *\n if ( aclm->del_rule(\n AclRule::INDIVIDUAL_ID |\n user_id,\n\n AclRule::ALL_ID |\n PoolObjectSQL::VROUTER,\n\n AuthRequest::CREATE,\n\n AclRule::ALL_ID,\n\n error_msg) < 0 )\n {\n NebulaLog::log(\"GROUP\",Log::ERROR,error_msg);\n }\n}\n<|endoftext|>"} {"text":"Fix counter miscounting<|endoftext|>"} {"text":"\/***\nCopyright (C) 2013 Aniket Deole \nThis program is free software: you can redistribute it and\/or modify it\nunder the terms of the GNU Lesser General Public License version 2.1, as published\nby the Free Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranties of\nMERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR\nPURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along\nwith this program. If not, see .\n***\/\n\n#include \n#include \n\n#include \n\n#include \"maintoolbar.hh\"\n\n\nMainToolbar::MainToolbar () {\n\n \/\/Create the toolbar and add it to a container widget:\n Gtk::ToolButton* button = Gtk::manage(new Gtk::ToolButton());\n \/\/ TODO Change this later to set_icon_widget\n\/\/ button->set_icon_name(\"dialog-cancel\");\n button->set_label (\"Close\");\n button->signal_clicked().connect(sigc::mem_fun(*this,\n &MainToolbar::exitNotify) );\n add(*button);\n\n Gtk::SeparatorToolItem* sti = Gtk::manage (new Gtk::SeparatorToolItem ());\n sti->set_expand (false);\n sti->set_draw (true);\n add (*sti);\n\n button = Gtk::manage(new Gtk::ToolButton());\n button->set_size_request (40, 40);\n button->set_label (\"New Note\");\n button->signal_clicked().connect(sigc::mem_fun(*this,\n &MainToolbar::newNote) );\n add(*button);\n\n button = Gtk::manage(new Gtk::ToolButton());\n button->set_size_request (40, 40);\n button->set_label (\"New Notebook\");\n button->signal_clicked().connect(sigc::mem_fun(*this,\n &MainToolbar::newNotebook) );\n add(*button);\n\n sti = Gtk::manage (new Gtk::SeparatorToolItem ());\n sti->set_expand (true);\n sti->set_can_focus (false);\n sti->set_use_action_appearance (false);\n sti->set_visible (true);\n add (*sti);\n\n Gtk::ToolItem* searchEntryContainer = Gtk::manage (new Gtk::ToolItem ());\n\n searchEntry = Gtk::manage (new Gtk::Entry ());\n searchEntry->set_text (\"\");\n searchEntry->set_icon_from_icon_name (\"system-search\");\n searchEntry->signal_changed ().connect (sigc::mem_fun (*this, \n &MainToolbar::searchCallback));\n searchEntry->signal_activate ().connect (sigc::mem_fun (*this,\n &MainToolbar::searchEntryClicked));\n searchEntryActive = false;\n addCss (searchEntry, \"searchEntry\", \".searchEntry { color: #888; \\n}\\n\");\n searchEntryContainer->add (*searchEntry);\n add (*searchEntryContainer);\n\n button = Gtk::manage(new Gtk::ToolButton());\n button->set_size_request (40, 40);\n button->set_label (\"Maximize\");\n add (*button);\n\n\tGlib::RefPtr sc = get_style_context(); \n\tsc->add_class(\"primary-toolbar\");\n\n show_all ();\n}\n\nMainToolbar::~MainToolbar () {\n\n}\n\nvoid MainToolbar::exitNotify () {\n exit (0);\n}\n\nvoid MainToolbar::newNote () {\n app->nlpv->newNote ();\n}\n\nvoid MainToolbar::newNotebook () {\n app->lpv->newNotebook ();\n}\n\nvoid MainToolbar::searchCallback () {\n if (searchEntry->get_text().empty ()){\n return;\n }\n app->nlpv->noteSearch (searchEntry->get_text ());\n}\n\nvoid MainToolbar::searchEntryClicked () {\n if (!searchEntryActive) {\n searchEntry->set_text (\"\");\n searchEntryActive = true;\n }\n}Fixed issue with window not being draggable.\/***\nCopyright (C) 2013 Aniket Deole \nThis program is free software: you can redistribute it and\/or modify it\nunder the terms of the GNU Lesser General Public License version 2.1, as published\nby the Free Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranties of\nMERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR\nPURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along\nwith this program. If not, see .\n***\/\n\n#include \n#include \n\n#include \n\n#include \"maintoolbar.hh\"\n\n\nMainToolbar::MainToolbar () {\n\n \/\/Create the toolbar and add it to a container widget:\n Gtk::ToolButton* button = Gtk::manage(new Gtk::ToolButton());\n \/\/ TODO Change this later to set_icon_widget\n\/\/ button->set_icon_name(\"dialog-cancel\");\n button->set_label (\"Close\");\n button->signal_clicked().connect(sigc::mem_fun(*this,\n &MainToolbar::exitNotify) );\n add(*button);\n\n Gtk::SeparatorToolItem* sti = Gtk::manage (new Gtk::SeparatorToolItem ());\n sti->set_expand (false);\n sti->set_draw (true);\n add (*sti);\n\n button = Gtk::manage(new Gtk::ToolButton());\n button->set_size_request (40, 40);\n button->set_label (\"New Note\");\n button->signal_clicked().connect(sigc::mem_fun(*this,\n &MainToolbar::newNote) );\n add(*button);\n\n button = Gtk::manage(new Gtk::ToolButton());\n button->set_size_request (40, 40);\n button->set_label (\"New Notebook\");\n button->signal_clicked().connect(sigc::mem_fun(*this,\n &MainToolbar::newNotebook) );\n add(*button);\n\n Gtk::ToolItem* ti = Gtk::manage (new Gtk::ToolItem ());\n ti->set_expand (true);\n add (*ti);\n\n Gtk::ToolItem* searchEntryContainer = Gtk::manage (new Gtk::ToolItem ());\n\n searchEntry = Gtk::manage (new Gtk::Entry ());\n searchEntry->set_text (\"\");\n searchEntry->set_icon_from_icon_name (\"system-search\");\n searchEntry->signal_changed ().connect (sigc::mem_fun (*this, \n &MainToolbar::searchCallback));\n searchEntry->signal_activate ().connect (sigc::mem_fun (*this,\n &MainToolbar::searchEntryClicked));\n searchEntryActive = false;\n addCss (searchEntry, \"searchEntry\", \".searchEntry { color: #888; \\n}\\n\");\n searchEntryContainer->add (*searchEntry);\n add (*searchEntryContainer);\n\n button = Gtk::manage(new Gtk::ToolButton());\n button->set_size_request (40, 40);\n button->set_label (\"Maximize\");\n add (*button);\n\n\tGlib::RefPtr sc = get_style_context(); \n\tsc->add_class(\"primary-toolbar\");\n\n show_all ();\n}\n\nMainToolbar::~MainToolbar () {\n\n}\n\nvoid MainToolbar::exitNotify () {\n exit (0);\n}\n\nvoid MainToolbar::newNote () {\n app->nlpv->newNote ();\n}\n\nvoid MainToolbar::newNotebook () {\n app->lpv->newNotebook ();\n}\n\nvoid MainToolbar::searchCallback () {\n if (searchEntry->get_text().empty ()){\n return;\n }\n app->nlpv->noteSearch (searchEntry->get_text ());\n}\n\nvoid MainToolbar::searchEntryClicked () {\n if (!searchEntryActive) {\n searchEntry->set_text (\"\");\n searchEntryActive = true;\n }\n}<|endoftext|>"} {"text":"\/*\n * Main Send File Transfer Window\n *\n * Copyright (C) 2011 David Edmundson \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"flat-model-proxy.h\"\n\n#include \"common\/models\/accounts-model.h\"\n#include \"common\/models\/accounts-filter-model.h\"\n#include \"common\/models\/contact-model-item.h\"\n\n\/\/FIXME, copy and paste the approver code for loading this from a config file into this, the contact list and the chat handler.\n#define PREFERRED_FILETRANSFER_HANDLER \"org.freedesktop.Telepathy.Client.KDE.FileTransfer\"\n\n\nclass ContactGridDelegate : public QAbstractItemDelegate {\npublic:\n ContactGridDelegate(QObject *parent);\n void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;\n QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;\n};\n\nContactGridDelegate::ContactGridDelegate(QObject *parent)\n : QAbstractItemDelegate(parent)\n{\n\n}\n\nvoid ContactGridDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const\n{\n QStyle *style = QApplication::style();\n int textHeight = option.fontMetrics.height()*2;\n\n style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter);\n\n QRect avatarRect = option.rect.adjusted(0,0,0,-textHeight);\n QRect textRect = option.rect.adjusted(0,option.rect.height()-textHeight,0,-3);\n\n QPixmap avatar = index.data(Qt::DecorationRole).value();\n if (avatar.isNull()) {\n avatar = KIcon(\"im-user-online\").pixmap(QSize(70,70));\n }\n\n \/\/resize larger avatars\n if (avatar.width() > 80 || avatar.height()> 80) {\n avatar = avatar.scaled(QSize(80,80), Qt::KeepAspectRatio);\n \/\/draw leaving paddings on smaller (or non square) avatars\n }\n style->drawItemPixmap(painter, avatarRect, Qt::AlignCenter, avatar);\n\n\n QTextOption textOption;\n textOption.setAlignment(Qt::AlignCenter);\n textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);\n painter->drawText(textRect, index.data().toString(), textOption);\n\n}\n\nQSize ContactGridDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const\n{\n Q_UNUSED(index);\n int textHeight = option.fontMetrics.height()*2;\n return QSize(84, 80 + textHeight + 3);\n}\n\n\nMainWindow::MainWindow(const KUrl &url, QWidget *parent) :\n QWidget(parent),\n ui(new Ui::MainWindow),\n m_accountsModel(0)\n{\n Tp::registerTypes();\n\n ui->setupUi(this);\n setWindowTitle(i18n(\"Send file - %1\", url.fileName());\n\n kDebug() << KApplication::arguments();\n\n ui->fileNameLabel->setText(url.fileName());\n m_busyOverlay = new KPixmapSequenceOverlayPainter(this);\n m_busyOverlay->setSequence(KPixmapSequence(\"process-working\", 22));\n m_busyOverlay->setWidget(ui->filePreview);\n m_busyOverlay->start();\n\n KFileItem file(KFileItem::Unknown, KFileItem::Unknown, url);\n QStringList availablePlugins = KIO::PreviewJob::availablePlugins();\n KIO::PreviewJob* job = KIO::filePreview(KFileItemList() << file, QSize(280, 280), &availablePlugins);\n job->setOverlayIconAlpha(0);\n job->setScaleType(KIO::PreviewJob::Unscaled);\n connect(job, SIGNAL(gotPreview(KFileItem,QPixmap)),\n this, SLOT(onPreviewLoaded(KFileItem,QPixmap)));\n connect(job, SIGNAL(failed(KFileItem)),\n this, SLOT(onPreviewFailed(KFileItem)));\n\n\n Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),\n Tp::Features() << Tp::Account::FeatureCore\n << Tp::Account::FeatureAvatar\n << Tp::Account::FeatureProtocolInfo\n << Tp::Account::FeatureProfile);\n\n Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(),\n Tp::Features() << Tp::Connection::FeatureCore\n << Tp::Connection::FeatureRosterGroups\n << Tp::Connection::FeatureRoster\n << Tp::Connection::FeatureSelfContact);\n\n Tp::ContactFactoryPtr contactFactory = Tp::ContactFactory::create(Tp::Features() << Tp::Contact::FeatureAlias\n << Tp::Contact::FeatureAvatarData\n << Tp::Contact::FeatureSimplePresence\n << Tp::Contact::FeatureCapabilities);\n\n Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus());\n\n m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(),\n accountFactory,\n connectionFactory,\n channelFactory,\n contactFactory);\n\n\n connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady()));\n\n connect(ui->buttonBox, SIGNAL(accepted()), SLOT(onDialogAccepted()));\n connect(ui->buttonBox, SIGNAL(rejected()), SLOT(close()));\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::onAccountManagerReady()\n{\n m_accountsModel = new AccountsModel(m_accountManager, this);\n AccountsFilterModel *filterModel = new AccountsFilterModel(this);\n filterModel->setSourceModel(m_accountsModel);\n filterModel->setShowOfflineUsers(false);\n FlatModelProxy *flatProxyModel = new FlatModelProxy(filterModel);\n\n ui->listView->setModel(flatProxyModel);\n ui->listView->setItemDelegate(new ContactGridDelegate(this));\n}\n\nvoid MainWindow::onDialogAccepted()\n{\n \/\/ don't do anytghing if no contact has been selected\n if (!ui->listView->currentIndex().isValid()) {\n \/\/ show message box?\n return;\n }\n\n ContactModelItem *contactModelItem = ui->listView->currentIndex().data(AccountsModel::ItemRole).value();\n Tp::ContactPtr contact = contactModelItem->contact();\n Tp::AccountPtr sendingAccount = m_accountsModel->accountForContactItem(contactModelItem);\n\n if (sendingAccount.isNull()) {\n kDebug() << \"sending account: NULL\";\n } else {\n kDebug() << \"Account is: \" << sendingAccount->displayName();\n kDebug() << \"sending to: \" << contact->alias();\n }\n\n \/\/ start sending file\n QString filePath (KCmdLineArgs::parsedArgs()->arg(0));\n qDebug() << \"FILE TO SEND: \" << filePath;\n\n Tp::FileTransferChannelCreationProperties fileTransferProperties(filePath, KMimeType::findByFileContent(filePath)->name());\n\n Tp::PendingChannelRequest* channelRequest = sendingAccount->createFileTransfer(contact,\n fileTransferProperties,\n QDateTime::currentDateTime(),\n PREFERRED_FILETRANSFER_HANDLER);\n\n connect(channelRequest, SIGNAL(finished(Tp::PendingOperation*)), SLOT(slotFileTransferFinished(Tp::PendingOperation*)));\n\n \/\/disable the buttons\n foreach(QAbstractButton* button, ui->buttonBox->buttons()) {\n button->setEnabled(false);\n }\n}\n\nvoid MainWindow::slotFileTransferFinished(Tp::PendingOperation* op)\n{\n if (op->isError()) {\n \/\/FIXME map to human readable strings.\n QString errorMsg(op->errorName() + \": \" + op->errorMessage());\n kDebug() << \"ERROR!: \" << errorMsg;\n KMessageBox::error(this, i18n(\"Failed to send file\"), i18n(\"File Transfer Failed\"));\n close();\n } else {\n kDebug() << \"Transfer started\";\n \/\/ now I can close the dialog\n close();\n }\n}\n\nvoid MainWindow::onPreviewLoaded(const KFileItem& item, const QPixmap& preview)\n{\n Q_UNUSED(item);\n ui->filePreview->setPixmap(preview);\n m_busyOverlay->stop();\n}\n\nvoid MainWindow::onPreviewFailed(const KFileItem& item)\n{\n kWarning() << \"Loading thumb failed\" << item.name();\n ui->filePreview->setPixmap(KIconLoader::global()->loadIcon(item.iconName(), KIconLoader::Desktop, 128));\n m_busyOverlay->stop();\n}\nFix compile\/*\n * Main Send File Transfer Window\n *\n * Copyright (C) 2011 David Edmundson \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"flat-model-proxy.h\"\n\n#include \"common\/models\/accounts-model.h\"\n#include \"common\/models\/accounts-filter-model.h\"\n#include \"common\/models\/contact-model-item.h\"\n\n\/\/FIXME, copy and paste the approver code for loading this from a config file into this, the contact list and the chat handler.\n#define PREFERRED_FILETRANSFER_HANDLER \"org.freedesktop.Telepathy.Client.KDE.FileTransfer\"\n\n\nclass ContactGridDelegate : public QAbstractItemDelegate {\npublic:\n ContactGridDelegate(QObject *parent);\n void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;\n QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;\n};\n\nContactGridDelegate::ContactGridDelegate(QObject *parent)\n : QAbstractItemDelegate(parent)\n{\n\n}\n\nvoid ContactGridDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const\n{\n QStyle *style = QApplication::style();\n int textHeight = option.fontMetrics.height()*2;\n\n style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter);\n\n QRect avatarRect = option.rect.adjusted(0,0,0,-textHeight);\n QRect textRect = option.rect.adjusted(0,option.rect.height()-textHeight,0,-3);\n\n QPixmap avatar = index.data(Qt::DecorationRole).value();\n if (avatar.isNull()) {\n avatar = KIcon(\"im-user-online\").pixmap(QSize(70,70));\n }\n\n \/\/resize larger avatars\n if (avatar.width() > 80 || avatar.height()> 80) {\n avatar = avatar.scaled(QSize(80,80), Qt::KeepAspectRatio);\n \/\/draw leaving paddings on smaller (or non square) avatars\n }\n style->drawItemPixmap(painter, avatarRect, Qt::AlignCenter, avatar);\n\n\n QTextOption textOption;\n textOption.setAlignment(Qt::AlignCenter);\n textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);\n painter->drawText(textRect, index.data().toString(), textOption);\n\n}\n\nQSize ContactGridDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const\n{\n Q_UNUSED(index);\n int textHeight = option.fontMetrics.height()*2;\n return QSize(84, 80 + textHeight + 3);\n}\n\n\nMainWindow::MainWindow(const KUrl &url, QWidget *parent) :\n QWidget(parent),\n ui(new Ui::MainWindow),\n m_accountsModel(0)\n{\n Tp::registerTypes();\n\n ui->setupUi(this);\n setWindowTitle(i18n(\"Send file - %1\", url.fileName()));\n\n kDebug() << KApplication::arguments();\n\n ui->fileNameLabel->setText(url.fileName());\n m_busyOverlay = new KPixmapSequenceOverlayPainter(this);\n m_busyOverlay->setSequence(KPixmapSequence(\"process-working\", 22));\n m_busyOverlay->setWidget(ui->filePreview);\n m_busyOverlay->start();\n\n KFileItem file(KFileItem::Unknown, KFileItem::Unknown, url);\n QStringList availablePlugins = KIO::PreviewJob::availablePlugins();\n KIO::PreviewJob* job = KIO::filePreview(KFileItemList() << file, QSize(280, 280), &availablePlugins);\n job->setOverlayIconAlpha(0);\n job->setScaleType(KIO::PreviewJob::Unscaled);\n connect(job, SIGNAL(gotPreview(KFileItem,QPixmap)),\n this, SLOT(onPreviewLoaded(KFileItem,QPixmap)));\n connect(job, SIGNAL(failed(KFileItem)),\n this, SLOT(onPreviewFailed(KFileItem)));\n\n\n Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),\n Tp::Features() << Tp::Account::FeatureCore\n << Tp::Account::FeatureAvatar\n << Tp::Account::FeatureProtocolInfo\n << Tp::Account::FeatureProfile);\n\n Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(),\n Tp::Features() << Tp::Connection::FeatureCore\n << Tp::Connection::FeatureRosterGroups\n << Tp::Connection::FeatureRoster\n << Tp::Connection::FeatureSelfContact);\n\n Tp::ContactFactoryPtr contactFactory = Tp::ContactFactory::create(Tp::Features() << Tp::Contact::FeatureAlias\n << Tp::Contact::FeatureAvatarData\n << Tp::Contact::FeatureSimplePresence\n << Tp::Contact::FeatureCapabilities);\n\n Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus());\n\n m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(),\n accountFactory,\n connectionFactory,\n channelFactory,\n contactFactory);\n\n\n connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady()));\n\n connect(ui->buttonBox, SIGNAL(accepted()), SLOT(onDialogAccepted()));\n connect(ui->buttonBox, SIGNAL(rejected()), SLOT(close()));\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::onAccountManagerReady()\n{\n m_accountsModel = new AccountsModel(m_accountManager, this);\n AccountsFilterModel *filterModel = new AccountsFilterModel(this);\n filterModel->setSourceModel(m_accountsModel);\n filterModel->setShowOfflineUsers(false);\n FlatModelProxy *flatProxyModel = new FlatModelProxy(filterModel);\n\n ui->listView->setModel(flatProxyModel);\n ui->listView->setItemDelegate(new ContactGridDelegate(this));\n}\n\nvoid MainWindow::onDialogAccepted()\n{\n \/\/ don't do anytghing if no contact has been selected\n if (!ui->listView->currentIndex().isValid()) {\n \/\/ show message box?\n return;\n }\n\n ContactModelItem *contactModelItem = ui->listView->currentIndex().data(AccountsModel::ItemRole).value();\n Tp::ContactPtr contact = contactModelItem->contact();\n Tp::AccountPtr sendingAccount = m_accountsModel->accountForContactItem(contactModelItem);\n\n if (sendingAccount.isNull()) {\n kDebug() << \"sending account: NULL\";\n } else {\n kDebug() << \"Account is: \" << sendingAccount->displayName();\n kDebug() << \"sending to: \" << contact->alias();\n }\n\n \/\/ start sending file\n QString filePath (KCmdLineArgs::parsedArgs()->arg(0));\n qDebug() << \"FILE TO SEND: \" << filePath;\n\n Tp::FileTransferChannelCreationProperties fileTransferProperties(filePath, KMimeType::findByFileContent(filePath)->name());\n\n Tp::PendingChannelRequest* channelRequest = sendingAccount->createFileTransfer(contact,\n fileTransferProperties,\n QDateTime::currentDateTime(),\n PREFERRED_FILETRANSFER_HANDLER);\n\n connect(channelRequest, SIGNAL(finished(Tp::PendingOperation*)), SLOT(slotFileTransferFinished(Tp::PendingOperation*)));\n\n \/\/disable the buttons\n foreach(QAbstractButton* button, ui->buttonBox->buttons()) {\n button->setEnabled(false);\n }\n}\n\nvoid MainWindow::slotFileTransferFinished(Tp::PendingOperation* op)\n{\n if (op->isError()) {\n \/\/FIXME map to human readable strings.\n QString errorMsg(op->errorName() + \": \" + op->errorMessage());\n kDebug() << \"ERROR!: \" << errorMsg;\n KMessageBox::error(this, i18n(\"Failed to send file\"), i18n(\"File Transfer Failed\"));\n close();\n } else {\n kDebug() << \"Transfer started\";\n \/\/ now I can close the dialog\n close();\n }\n}\n\nvoid MainWindow::onPreviewLoaded(const KFileItem& item, const QPixmap& preview)\n{\n Q_UNUSED(item);\n ui->filePreview->setPixmap(preview);\n m_busyOverlay->stop();\n}\n\nvoid MainWindow::onPreviewFailed(const KFileItem& item)\n{\n kWarning() << \"Loading thumb failed\" << item.name();\n ui->filePreview->setPixmap(KIconLoader::global()->loadIcon(item.iconName(), KIconLoader::Desktop, 128));\n m_busyOverlay->stop();\n}\n<|endoftext|>"} {"text":"#include \n#include \"mainwindow.h\"\n#include \n#include \n#include \n#include \n#include \n\nWindow::Window(QWidget *parent) : QWidget(parent)\n{\n \/\/ Initalise database\n db.setDatabaseName(\"recipes.db\");\n\n \/\/ Initialise widgets\n searchBox = new SearchBox();\n searchBox->setPlaceholderText(\"Search for recipes\");\n recipeBox = new QComboBox();\n QStringList recipeCategories;\n recipeCategories << \"All Recipes\" << \"Beef\" << \"Chicken\" << \"Dessert\" << \"Lamb\" << \"Pork\" << \"Seafood\" << \"Turkey\" << \"Veggie\";\n recipeBox->addItems(recipeCategories);\n createRecipeList();\n numResults = new QLabel();\n\n \/\/ Set layout\n QGridLayout *mainLayout = new QGridLayout;\n mainLayout->addWidget(searchBox, 0, 0, 1, 6);\n mainLayout->addWidget(numResults, 0, 6, 1, 1);\n mainLayout->addWidget(recipeBox, 0, 7, 1, 1);\n mainLayout->addWidget(recipeList, 1, 0, 1, 8);\n setLayout(mainLayout);\n\n \/\/ Set window paramters\n setWindowTitle(tr(\"Find Recipes\"));\n setMinimumSize(600, 400);\n\n \/\/ Set signals\n connect(recipeList, &QListWidget::itemDoubleClicked, this, &Window::openFile);\n connect(searchBox, SIGNAL(inputText(QString)), this, SLOT(updateRecipesDiplay(QString)));\n connect(searchBox, SIGNAL(returnPressed()), recipeList, SLOT(setFocus()));\n connect(recipeBox, SIGNAL(currentTextChanged(QString)), searchBox, SLOT(recipeFiterChanged(QString)));\n\n \/\/ Populate list on start up\n updateRecipesDiplay(\"\");\n\n db_ops::update_database(&db);\n}\n\n\/\/ Get list of files according to glob patternn\nQStringList globVector(const std::string& pattern){\n glob_t glob_result;\n glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result);\n QStringList files;\n for(unsigned int i=0; iclear();\n\n QList recipes = getRecipeList(searchText);\n for (int i=0; iaddItem(recipes[i]);\n }\n\n if(searchText.isEmpty()){\n recipeList->sortItems();\n }\n\n QString text = QString(\"%1 recipes\").arg(recipes.size());\n if (recipes.size() == 1){\n text = \"1 recipe\";\n }\n numResults->setText(text);\n}\n\nQList Window::getRecipeList(QString searchText){\n QList recipes;\n if (searchText.isEmpty()) {\n recipes = getAllRecipes();\n }else{\n recipes = getMatchingRecipes(searchText);\n }\n return recipes;\n}\n\nQList Window::getAllRecipes(){\n QList recipes;\n\n \/\/ Open database and execute query\n db.open();\n QSqlQuery query = QSqlQuery();\n query.exec(\"select TITLE, IMG_PATH, FILE_PATH from RECIPES\");\n\n while(query.next()){\n \/\/ Extract info from query results\n QString title = query.value(0).toString();\n QString img_path = query.value(1).toString();\n QString file_path = query.value(2).toString();\n\n \/\/ Create QListWidgetItems\n QListWidgetItem *recipe = new QListWidgetItem;\n recipe->setText(title);\n recipe->setData(Qt::UserRole, file_path);\n\n QImage *img = new QImage();\n bool loaded = img->load(img_path);\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }else{\n \/\/ If image doesn't exist, use placeholder image\n bool loaded = img->load(\".\/Images\/Placeholder.jpg\");\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }\n }\n recipes.append(recipe);\n }\n db.close();\n return recipes;\n}\n\n\nQList Window::getMatchingRecipes(QString searchText){\n QList recipes;\n\n \/\/ Get matching recipes and their scores\n std::map matchingRecipes = findMatches(searchText);\n \/\/ Build QListWidgetItems and add to QList\n \/\/ By default the map should be in ascending order, so use reverse iterator to get highest matches first\n for (auto iter = matchingRecipes.rbegin(); iter != matchingRecipes.rend(); ++iter){\n QString path_name = iter->second;\n QString img_path = \"Images\/\" + path_name.split('\/')[1].replace(\" \", \"_\").replace(\".md\", \".jpg\");\n\n QListWidgetItem *recipe = new QListWidgetItem;\n recipe->setText(path_name.split('\/')[1].replace(\".md\", \"\"));\n recipe->setData(Qt::UserRole, path_name);\n\n QImage *img = new QImage();\n bool loaded = img->load(img_path);\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }else{\n \/\/ If image doesn't exist, use placeholder image\n bool loaded = img->load(\".\/Images\/Placeholder.jpg\");\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }\n }\n recipes.append(recipe);\n }\n\n return recipes;\n}\n\nstd::map Window::findMatches(QString text)\n{\n \/\/ Get all files in current recipe filter\n std::string pattern = \"*\/*.md\";\n if(recipeBox->currentText() != \"All Recipes\"){\n pattern = recipeBox->currentText().toStdString() + \"\/*.md\";\n }\n QStringList files = globVector(pattern);\n \/\/ Get matching files and their scores\n std::map matchingFiles;\n std::string txtstr = text.toStdString();\n for (int i=0; i 0){\n dbscore += 0.01;\n }\n matchingFiles[dbscore] = files[i];\n }\n }\n return matchingFiles;\n}\n\nvoid Window::createRecipeList()\n{\n recipeList = new QListWidget();\n recipeList->setViewMode(QListView::IconMode);\n recipeList->setIconSize(QSize(267, 150));\n recipeList->setGridSize(QSize(280, 185));\n recipeList->setWordWrap(true);\n recipeList->setTextElideMode(Qt::ElideNone);\n}\n\nvoid Window::openFile(QListWidgetItem *recipe)\n{\n \/\/ Read hidden data to find full file path\n QString path = recipe->data(Qt::UserRole).toString();\n QDesktopServices::openUrl(QUrl::fromLocalFile(currentDir.absoluteFilePath(path)));\n}\n\nvoid Window::resizeEvent(QResizeEvent *event){\n int iconWidth, iconHeight, gridWidth, gridHeight, columns;\n double gridRatio = 280.0\/185.0;\n double iconRatio = 267.0\/150.0;\n QSize recipeListSize = recipeList->size();\n\n if(recipeListSize.width()<=578){\n \/\/ Set defaults for minimum size\n columns = 2;\n iconWidth = 267;\n iconHeight = 150;\n gridWidth = 280;\n gridHeight = 185;\n }else{\n \/\/ Icons should never go larger than default, so set number of columns to round up\n columns = ceil(recipeListSize.width()\/280.0);\n \/\/ Width of grid is widget_width\/columns, with extra width removed to allow for scrollbar\n gridWidth = int(recipeListSize.width()\/columns) - ceil(18.0\/columns);\n \/\/ Calculate other parameters based on ratios of default values.\n gridHeight = int(gridWidth\/gridRatio);\n iconWidth = gridWidth - 13;\n iconHeight = int(iconWidth\/iconRatio);\n }\n\n recipeList->setIconSize(QSize(iconWidth, iconHeight));\n recipeList->setGridSize(QSize(gridWidth, gridHeight));\n}\n\nRemove line of code used to test database update function#include \n#include \"mainwindow.h\"\n#include \n#include \n#include \n#include \n#include \n\nWindow::Window(QWidget *parent) : QWidget(parent)\n{\n \/\/ Initalise database\n db.setDatabaseName(\"recipes.db\");\n\n \/\/ Initialise widgets\n searchBox = new SearchBox();\n searchBox->setPlaceholderText(\"Search for recipes\");\n recipeBox = new QComboBox();\n QStringList recipeCategories;\n recipeCategories << \"All Recipes\" << \"Beef\" << \"Chicken\" << \"Dessert\" << \"Lamb\" << \"Pork\" << \"Seafood\" << \"Turkey\" << \"Veggie\";\n recipeBox->addItems(recipeCategories);\n createRecipeList();\n numResults = new QLabel();\n\n \/\/ Set layout\n QGridLayout *mainLayout = new QGridLayout;\n mainLayout->addWidget(searchBox, 0, 0, 1, 6);\n mainLayout->addWidget(numResults, 0, 6, 1, 1);\n mainLayout->addWidget(recipeBox, 0, 7, 1, 1);\n mainLayout->addWidget(recipeList, 1, 0, 1, 8);\n setLayout(mainLayout);\n\n \/\/ Set window paramters\n setWindowTitle(tr(\"Find Recipes\"));\n setMinimumSize(600, 400);\n\n \/\/ Set signals\n connect(recipeList, &QListWidget::itemDoubleClicked, this, &Window::openFile);\n connect(searchBox, SIGNAL(inputText(QString)), this, SLOT(updateRecipesDiplay(QString)));\n connect(searchBox, SIGNAL(returnPressed()), recipeList, SLOT(setFocus()));\n connect(recipeBox, SIGNAL(currentTextChanged(QString)), searchBox, SLOT(recipeFiterChanged(QString)));\n\n \/\/ Populate list on start up\n updateRecipesDiplay(\"\");\n}\n\n\/\/ Get list of files according to glob patternn\nQStringList globVector(const std::string& pattern){\n glob_t glob_result;\n glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result);\n QStringList files;\n for(unsigned int i=0; iclear();\n\n QList recipes = getRecipeList(searchText);\n for (int i=0; iaddItem(recipes[i]);\n }\n\n if(searchText.isEmpty()){\n recipeList->sortItems();\n }\n\n QString text = QString(\"%1 recipes\").arg(recipes.size());\n if (recipes.size() == 1){\n text = \"1 recipe\";\n }\n numResults->setText(text);\n}\n\nQList Window::getRecipeList(QString searchText){\n QList recipes;\n if (searchText.isEmpty()) {\n recipes = getAllRecipes();\n }else{\n recipes = getMatchingRecipes(searchText);\n }\n return recipes;\n}\n\nQList Window::getAllRecipes(){\n QList recipes;\n\n \/\/ Open database and execute query\n db.open();\n QSqlQuery query = QSqlQuery();\n query.exec(\"select TITLE, IMG_PATH, FILE_PATH from RECIPES\");\n\n while(query.next()){\n \/\/ Extract info from query results\n QString title = query.value(0).toString();\n QString img_path = query.value(1).toString();\n QString file_path = query.value(2).toString();\n\n \/\/ Create QListWidgetItems\n QListWidgetItem *recipe = new QListWidgetItem;\n recipe->setText(title);\n recipe->setData(Qt::UserRole, file_path);\n\n QImage *img = new QImage();\n bool loaded = img->load(img_path);\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }else{\n \/\/ If image doesn't exist, use placeholder image\n bool loaded = img->load(\".\/Images\/Placeholder.jpg\");\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }\n }\n recipes.append(recipe);\n }\n db.close();\n return recipes;\n}\n\n\nQList Window::getMatchingRecipes(QString searchText){\n QList recipes;\n\n \/\/ Get matching recipes and their scores\n std::map matchingRecipes = findMatches(searchText);\n \/\/ Build QListWidgetItems and add to QList\n \/\/ By default the map should be in ascending order, so use reverse iterator to get highest matches first\n for (auto iter = matchingRecipes.rbegin(); iter != matchingRecipes.rend(); ++iter){\n QString path_name = iter->second;\n QString img_path = \"Images\/\" + path_name.split('\/')[1].replace(\" \", \"_\").replace(\".md\", \".jpg\");\n\n QListWidgetItem *recipe = new QListWidgetItem;\n recipe->setText(path_name.split('\/')[1].replace(\".md\", \"\"));\n recipe->setData(Qt::UserRole, path_name);\n\n QImage *img = new QImage();\n bool loaded = img->load(img_path);\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }else{\n \/\/ If image doesn't exist, use placeholder image\n bool loaded = img->load(\".\/Images\/Placeholder.jpg\");\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }\n }\n recipes.append(recipe);\n }\n\n return recipes;\n}\n\nstd::map Window::findMatches(QString text)\n{\n \/\/ Get all files in current recipe filter\n std::string pattern = \"*\/*.md\";\n if(recipeBox->currentText() != \"All Recipes\"){\n pattern = recipeBox->currentText().toStdString() + \"\/*.md\";\n }\n QStringList files = globVector(pattern);\n \/\/ Get matching files and their scores\n std::map matchingFiles;\n std::string txtstr = text.toStdString();\n for (int i=0; i 0){\n dbscore += 0.01;\n }\n matchingFiles[dbscore] = files[i];\n }\n }\n return matchingFiles;\n}\n\nvoid Window::createRecipeList()\n{\n recipeList = new QListWidget();\n recipeList->setViewMode(QListView::IconMode);\n recipeList->setIconSize(QSize(267, 150));\n recipeList->setGridSize(QSize(280, 185));\n recipeList->setWordWrap(true);\n recipeList->setTextElideMode(Qt::ElideNone);\n}\n\nvoid Window::openFile(QListWidgetItem *recipe)\n{\n \/\/ Read hidden data to find full file path\n QString path = recipe->data(Qt::UserRole).toString();\n QDesktopServices::openUrl(QUrl::fromLocalFile(currentDir.absoluteFilePath(path)));\n}\n\nvoid Window::resizeEvent(QResizeEvent *event){\n int iconWidth, iconHeight, gridWidth, gridHeight, columns;\n double gridRatio = 280.0\/185.0;\n double iconRatio = 267.0\/150.0;\n QSize recipeListSize = recipeList->size();\n\n if(recipeListSize.width()<=578){\n \/\/ Set defaults for minimum size\n columns = 2;\n iconWidth = 267;\n iconHeight = 150;\n gridWidth = 280;\n gridHeight = 185;\n }else{\n \/\/ Icons should never go larger than default, so set number of columns to round up\n columns = ceil(recipeListSize.width()\/280.0);\n \/\/ Width of grid is widget_width\/columns, with extra width removed to allow for scrollbar\n gridWidth = int(recipeListSize.width()\/columns) - ceil(18.0\/columns);\n \/\/ Calculate other parameters based on ratios of default values.\n gridHeight = int(gridWidth\/gridRatio);\n iconWidth = gridWidth - 13;\n iconHeight = int(iconWidth\/iconRatio);\n }\n\n recipeList->setIconSize(QSize(iconWidth, iconHeight));\n recipeList->setGridSize(QSize(gridWidth, gridHeight));\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: OStyle.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 13:28:04 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_chart2.hxx\"\n#include \"OStyle.hxx\"\n#include \"macros.hxx\"\n\n#ifndef _RTL_UUID_H_\n#include \n#endif\n#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_\n#include \n#endif\n#include \"com\/sun\/star\/uno\/RuntimeException.hpp\"\n\nusing namespace ::com::sun::star;\n\nusing ::com::sun::star::uno::Sequence;\nusing ::com::sun::star::uno::Reference;\nusing ::rtl::OUString;\nusing ::osl::MutexGuard;\n\nnamespace property\n{\n\nOStyle::OStyle( const Reference< container::XNameAccess > & xStyleFamily,\n ::osl::Mutex & _rMutex ) :\n OPropertySet( _rMutex ),\n m_xStyleFamily( xStyleFamily ),\n m_bUserDefined( false ),\n m_rMutex( _rMutex )\n{}\n\nOStyle::~OStyle()\n{}\n\n::osl::Mutex & OStyle::GetMutex()\n{\n return m_rMutex;\n}\n\n\/\/ ____ XStyle ____\nsal_Bool SAL_CALL OStyle::isUserDefined()\n throw (uno::RuntimeException)\n{\n \/\/ \/--\n MutexGuard aGuard( GetMutex() );\n return m_bUserDefined;\n \/\/ \\--\n}\n\nsal_Bool SAL_CALL OStyle::isInUse()\n throw (uno::RuntimeException)\n{\n \/\/ \/--\n MutexGuard aGuard( GetMutex() );\n\n \/\/ aBoundLC is a member of cppuhelper::OPropertySetHelper\n \/\/ it is assumed that a style is in use whenever some component is\n \/\/ registered here as listener\n return ( aBoundLC.getContainedTypes().getLength() > 0 );\n \/\/ \\--\n}\n\nOUString SAL_CALL OStyle::getParentStyle()\n throw (uno::RuntimeException)\n{\n \/\/ \/--\n MutexGuard aGuard( GetMutex() );\n return m_aParentStyleName;\n \/\/ \\--\n}\n\nvoid SAL_CALL OStyle::setParentStyle( const OUString& aParentStyle )\n throw (container::NoSuchElementException,\n uno::RuntimeException)\n{\n \/\/ \/--\n MutexGuard aGuard( GetMutex() );\n m_aParentStyleName = aParentStyle;\n \/\/ \\--\n}\n\n\/\/ ____ XNamed (base of XStyle) ____\n\nOUString SAL_CALL OStyle::getName()\n throw (uno::RuntimeException)\n{\n \/\/ \/--\n MutexGuard aGuard( GetMutex() );\n return m_aName;\n \/\/ \\--\n}\n\nvoid SAL_CALL OStyle::setName( const ::rtl::OUString& aName )\n throw (uno::RuntimeException)\n{\n \/\/ \/--\n MutexGuard aGuard( GetMutex() );\n OSL_ASSERT( m_xStyleFamily.is() );\n\n \/\/ note: RuntimeException is not very apropriate for this, but I have no\n \/\/ other choice\n if( m_xStyleFamily->hasByName( aName ))\n {\n OSL_ENSURE( false, \"Style name already exists!\" );\n throw uno::RuntimeException(\n C2U( \"Style name already exists: \" ) + aName,\n static_cast< style::XStyle * >( this ));\n }\n else\n {\n \/\/ ToDo: Change the name in the container (XStyleFamiliy)\n m_aName = aName;\n }\n \/\/ \\--\n}\n\n\/\/ ____ XInterface ____\nuno::Any SAL_CALL OStyle::queryInterface( const uno::Type& aType )\n throw (uno::RuntimeException)\n{\n uno::Any aResult = OPropertySet::queryInterface( aType );\n\n if( ! aResult.hasValue())\n {\n return ::cppu::queryInterface(\n aType,\n static_cast< style::XStyle * >( this ));\n }\n\n return aResult;\n}\n\n\/\/ void SAL_CALL OStyle::acquire() throw ()\n\/\/ {\n\/\/ OPropertySet::acquire();\n\/\/ }\n\n\/\/ void SAL_CALL OStyle::release() throw ()\n\/\/ {\n\/\/ OPropertySet::release();\n\/\/ }\n\n\n\n\/\/ ____ XServiceInfo ____\n\/\/ OUString SAL_CALL\n\/\/ OStyle::getImplementationName()\n\/\/ throw (uno::RuntimeException)\n\/\/ {\n\/\/ return OUString( RTL_CONSTASCII_USTRINGPARAM( \"property::OStyle\" ));\n\/\/ }\n\n\/\/ sal_Bool SAL_CALL\n\/\/ OStyle::supportsService( const OUString& ServiceName )\n\/\/ throw (uno::RuntimeException)\n\/\/ {\n\/\/ Sequence< OUString > aServices( getSupportedServiceNames() );\n\n\/\/ sal_Int32 nI = aServices.getLength() - 1;\n\/\/ for( ; nI >= 0; --nI )\n\/\/ {\n\/\/ if( aServices[ nI ].equals( ServiceName ))\n\/\/ return sal_True;\n\/\/ }\n\/\/ return sal_False;\n\/\/ }\n\n\/\/ Sequence< OUString > SAL_CALL\n\/\/ OStyle::getSupportedServiceNames()\n\/\/ throw (uno::RuntimeException)\n\/\/ {\n\/\/ Sequence< OUString > aServiceNames( 2 );\n\/\/ \/\/ from base OPropertySet\n\/\/ aServiceNames[ 0 ] = OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.beans.PropertySet\" ));\n\/\/ \/\/ new service\n\/\/ aServiceNames[ 1 ] = OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.style.Style\" ));\n\/\/ return aServiceNames;\n\/\/ }\n\n\n\/\/ ____ XTypeProvider ____\n\/\/ Sequence< uno::Type > SAL_CALL\n\/\/ OStyle::getTypes()\n\/\/ throw (uno::RuntimeException)\n\/\/ {\n\/\/ Sequence< uno::Type > aResult( OPropertySet::getTypes() );\n\/\/ aResult.realloc( aResult.getLength() + 1 );\n\/\/ aResult[ aResult.getLength() - 1 ] =\n\/\/ ::getCppuType( reinterpret_cast< const Reference< style::XStyle > *>(0));\n\n\/\/ return aResult;\n\/\/ }\n\n\/\/ Sequence< sal_Int8 > SAL_CALL\n\/\/ OStyle::getImplementationId()\n\/\/ throw (uno::RuntimeException)\n\/\/ {\n\/\/ static uno::Sequence< sal_Int8 > aId;\n\/\/ if( aId.getLength() == 0 )\n\/\/ {\n\/\/ aId.realloc( 16 );\n\/\/ rtl_createUuid( (sal_uInt8 *)aId.getArray(), 0, sal_True );\n\/\/ }\n\/\/ return aId;\n\/\/ }\n\n\n} \/\/ namespace property\nINTEGRATION: CWS chart2mst3 (1.3.12); FILE MERGED 2006\/10\/18 17:18:36 bm 1.3.12.2: RESYNC: (1.3-1.4); FILE MERGED 2006\/03\/07 12:35:35 bm 1.3.12.1: avoid variables starting with underscores. rMutex is a base-class member so use par_rMutex instead\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: OStyle.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: vg $ $Date: 2007-05-22 19:03:03 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_chart2.hxx\"\n#include \"OStyle.hxx\"\n#include \"macros.hxx\"\n\n#ifndef _RTL_UUID_H_\n#include \n#endif\n#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_\n#include \n#endif\n#include \"com\/sun\/star\/uno\/RuntimeException.hpp\"\n\nusing namespace ::com::sun::star;\n\nusing ::com::sun::star::uno::Sequence;\nusing ::com::sun::star::uno::Reference;\nusing ::rtl::OUString;\nusing ::osl::MutexGuard;\n\nnamespace property\n{\n\nOStyle::OStyle( const Reference< container::XNameAccess > & xStyleFamily,\n ::osl::Mutex & par_rMutex ) :\n OPropertySet( par_rMutex ),\n m_xStyleFamily( xStyleFamily ),\n m_bUserDefined( false ),\n m_rMutex( par_rMutex )\n{}\n\nOStyle::~OStyle()\n{}\n\n::osl::Mutex & OStyle::GetMutex()\n{\n return m_rMutex;\n}\n\n\/\/ ____ XStyle ____\nsal_Bool SAL_CALL OStyle::isUserDefined()\n throw (uno::RuntimeException)\n{\n \/\/ \/--\n MutexGuard aGuard( GetMutex() );\n return m_bUserDefined;\n \/\/ \\--\n}\n\nsal_Bool SAL_CALL OStyle::isInUse()\n throw (uno::RuntimeException)\n{\n \/\/ \/--\n MutexGuard aGuard( GetMutex() );\n\n \/\/ aBoundLC is a member of cppuhelper::OPropertySetHelper\n \/\/ it is assumed that a style is in use whenever some component is\n \/\/ registered here as listener\n return ( aBoundLC.getContainedTypes().getLength() > 0 );\n \/\/ \\--\n}\n\nOUString SAL_CALL OStyle::getParentStyle()\n throw (uno::RuntimeException)\n{\n \/\/ \/--\n MutexGuard aGuard( GetMutex() );\n return m_aParentStyleName;\n \/\/ \\--\n}\n\nvoid SAL_CALL OStyle::setParentStyle( const OUString& aParentStyle )\n throw (container::NoSuchElementException,\n uno::RuntimeException)\n{\n \/\/ \/--\n MutexGuard aGuard( GetMutex() );\n m_aParentStyleName = aParentStyle;\n \/\/ \\--\n}\n\n\/\/ ____ XNamed (base of XStyle) ____\n\nOUString SAL_CALL OStyle::getName()\n throw (uno::RuntimeException)\n{\n \/\/ \/--\n MutexGuard aGuard( GetMutex() );\n return m_aName;\n \/\/ \\--\n}\n\nvoid SAL_CALL OStyle::setName( const ::rtl::OUString& aName )\n throw (uno::RuntimeException)\n{\n \/\/ \/--\n MutexGuard aGuard( GetMutex() );\n OSL_ASSERT( m_xStyleFamily.is() );\n\n \/\/ note: RuntimeException is not very apropriate for this, but I have no\n \/\/ other choice\n if( m_xStyleFamily->hasByName( aName ))\n {\n OSL_ENSURE( false, \"Style name already exists!\" );\n throw uno::RuntimeException(\n C2U( \"Style name already exists: \" ) + aName,\n static_cast< style::XStyle * >( this ));\n }\n else\n {\n \/\/ ToDo: Change the name in the container (XStyleFamiliy)\n m_aName = aName;\n }\n \/\/ \\--\n}\n\n\/\/ ____ XInterface ____\nuno::Any SAL_CALL OStyle::queryInterface( const uno::Type& aType )\n throw (uno::RuntimeException)\n{\n uno::Any aResult = OPropertySet::queryInterface( aType );\n\n if( ! aResult.hasValue())\n {\n return ::cppu::queryInterface(\n aType,\n static_cast< style::XStyle * >( this ));\n }\n\n return aResult;\n}\n\n\/\/ void SAL_CALL OStyle::acquire() throw ()\n\/\/ {\n\/\/ OPropertySet::acquire();\n\/\/ }\n\n\/\/ void SAL_CALL OStyle::release() throw ()\n\/\/ {\n\/\/ OPropertySet::release();\n\/\/ }\n\n\n\n\/\/ ____ XServiceInfo ____\n\/\/ OUString SAL_CALL\n\/\/ OStyle::getImplementationName()\n\/\/ throw (uno::RuntimeException)\n\/\/ {\n\/\/ return OUString( RTL_CONSTASCII_USTRINGPARAM( \"property::OStyle\" ));\n\/\/ }\n\n\/\/ sal_Bool SAL_CALL\n\/\/ OStyle::supportsService( const OUString& ServiceName )\n\/\/ throw (uno::RuntimeException)\n\/\/ {\n\/\/ Sequence< OUString > aServices( getSupportedServiceNames() );\n\n\/\/ sal_Int32 nI = aServices.getLength() - 1;\n\/\/ for( ; nI >= 0; --nI )\n\/\/ {\n\/\/ if( aServices[ nI ].equals( ServiceName ))\n\/\/ return sal_True;\n\/\/ }\n\/\/ return sal_False;\n\/\/ }\n\n\/\/ Sequence< OUString > SAL_CALL\n\/\/ OStyle::getSupportedServiceNames()\n\/\/ throw (uno::RuntimeException)\n\/\/ {\n\/\/ Sequence< OUString > aServiceNames( 2 );\n\/\/ \/\/ from base OPropertySet\n\/\/ aServiceNames[ 0 ] = OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.beans.PropertySet\" ));\n\/\/ \/\/ new service\n\/\/ aServiceNames[ 1 ] = OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.style.Style\" ));\n\/\/ return aServiceNames;\n\/\/ }\n\n\n\/\/ ____ XTypeProvider ____\n\/\/ Sequence< uno::Type > SAL_CALL\n\/\/ OStyle::getTypes()\n\/\/ throw (uno::RuntimeException)\n\/\/ {\n\/\/ Sequence< uno::Type > aResult( OPropertySet::getTypes() );\n\/\/ aResult.realloc( aResult.getLength() + 1 );\n\/\/ aResult[ aResult.getLength() - 1 ] =\n\/\/ ::getCppuType( reinterpret_cast< const Reference< style::XStyle > *>(0));\n\n\/\/ return aResult;\n\/\/ }\n\n\/\/ Sequence< sal_Int8 > SAL_CALL\n\/\/ OStyle::getImplementationId()\n\/\/ throw (uno::RuntimeException)\n\/\/ {\n\/\/ static uno::Sequence< sal_Int8 > aId;\n\/\/ if( aId.getLength() == 0 )\n\/\/ {\n\/\/ aId.realloc( 16 );\n\/\/ rtl_createUuid( (sal_uInt8 *)aId.getArray(), 0, sal_True );\n\/\/ }\n\/\/ return aId;\n\/\/ }\n\n\n} \/\/ namespace property\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: itemdel.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2003-03-27 14:38:55 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SV_SVAPP_HXX \/\/autogen\n#include \n#endif\n#ifndef _ERRCODE_HXX \/\/autogen\n#include \n#endif\n#include \n\n#include \n\n#include \"svtdata.hxx\"\n#include \"svarray.hxx\"\n#include \"args.hxx\"\n#include \"itempool.hxx\"\n#include \"itemdel.hxx\"\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\nDBG_NAME(SfxItemDesruptor_Impl);\n\n\/\/ -----------------------------------------------------------------------\n\nclass SfxItemDesruptor_Impl\n{\n SfxPoolItem *pItem;\n Link aLink;\n\nprivate:\n DECL_LINK( Delete, void * );\n SfxItemDesruptor_Impl( const SfxItemDesruptor_Impl& ); \/\/ n.i.\n\npublic:\n SfxItemDesruptor_Impl( SfxPoolItem *pItemToDesrupt );\n ~SfxItemDesruptor_Impl();\n};\n\nSV_DECL_PTRARR( SfxItemDesruptorList_Impl, SfxItemDesruptor_Impl*, 4, 4 );\n\n\/\/ ------------------------------------------------------------------------\nSfxItemDesruptor_Impl::SfxItemDesruptor_Impl( SfxPoolItem *pItemToDesrupt ):\n pItem(pItemToDesrupt),\n aLink( LINK(this, SfxItemDesruptor_Impl, Delete) )\n{\n DBG_CTOR(SfxItemDesruptor_Impl, 0);\n\n DBG_ASSERT( 0 == pItem->GetRefCount(), \"desrupting pooled item\" );\n pItem->SetKind( SFX_ITEMS_DELETEONIDLE );\n\n \/\/ im Idle abarbeiten\n GetpApp()->InsertIdleHdl( aLink, 1 );\n\n \/\/ und in Liste eintragen (damit geflusht werden kann)\n SfxItemDesruptorList_Impl* &rpList = ImpSvtData::GetSvtData().pItemDesruptList;\n if ( !rpList )\n rpList = new SfxItemDesruptorList_Impl;\n const SfxItemDesruptor_Impl *pThis = this;\n rpList->Insert( pThis, rpList->Count() );\n}\n\n\/\/ ------------------------------------------------------------------------\nSfxItemDesruptor_Impl::~SfxItemDesruptor_Impl()\n{\n DBG_DTOR(SfxItemDesruptor_Impl, 0);\n\n \/\/ aus Idle-Handler austragen\n GetpApp()->RemoveIdleHdl( aLink );\n\n \/\/ und aus Liste austragen\n SfxItemDesruptorList_Impl* &rpList = ImpSvtData::GetSvtData().pItemDesruptList;\n DBG_ASSERT( rpList, \"no DesruptorList\" );\n const SfxItemDesruptor_Impl *pThis = this;\n if ( rpList ) HACK(warum?)\n rpList->Remove( rpList->GetPos(pThis) );\n\n \/\/ reset RefCount (was set to SFX_ITEMS_SPECIAL before!)\n pItem->SetRefCount( 0 );\n DBG_CHKOBJ( pItem, SfxPoolItem, 0 );\n delete pItem;\n}\n\n\/\/ ------------------------------------------------------------------------\nIMPL_LINK( SfxItemDesruptor_Impl, Delete, void *, pvoid )\n{\n {DBG_CHKTHIS(SfxItemDesruptor_Impl, 0);}\n delete this;\n return 0;\n}\n\n\/\/ ------------------------------------------------------------------------\nSfxPoolItem* DeleteItemOnIdle( SfxPoolItem* pItem )\n{\n DBG_ASSERT( 0 == pItem->GetRefCount(), \"deleting item in use\" );\n new SfxItemDesruptor_Impl( pItem );\n return pItem;\n}\n\n\/\/ ------------------------------------------------------------------------\nvoid DeleteOnIdleItems()\n{\n SfxItemDesruptorList_Impl* &rpList\n = ImpSvtData::GetSvtData().pItemDesruptList;\n if ( rpList )\n {\n USHORT n;\n while ( 0 != ( n = rpList->Count() ) )\n \/\/ Remove ist implizit im Dtor\n delete rpList->GetObject( n-1 );\n DELETEZ(rpList);\n }\n}\n\n\nINTEGRATION: CWS visibility03 (1.2.762); FILE MERGED 2005\/04\/01 13:03:43 mhu 1.2.762.1: #i45006# Removed unused include(s).\/*************************************************************************\n *\n * $RCSfile: itemdel.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2005-04-13 11:07:29 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"itemdel.hxx\"\n\n#ifndef _SV_SVAPP_HXX \/\/autogen\n#include \n#endif\n#ifndef _ERRCODE_HXX \/\/autogen\n#include \n#endif\n#include \n\n#include \"svtdata.hxx\"\n#include \"svarray.hxx\"\n#include \"itempool.hxx\"\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\nDBG_NAME(SfxItemDesruptor_Impl);\n\n\/\/ -----------------------------------------------------------------------\n\nclass SfxItemDesruptor_Impl\n{\n SfxPoolItem *pItem;\n Link aLink;\n\nprivate:\n DECL_LINK( Delete, void * );\n SfxItemDesruptor_Impl( const SfxItemDesruptor_Impl& ); \/\/ n.i.\n\npublic:\n SfxItemDesruptor_Impl( SfxPoolItem *pItemToDesrupt );\n ~SfxItemDesruptor_Impl();\n};\n\nSV_DECL_PTRARR( SfxItemDesruptorList_Impl, SfxItemDesruptor_Impl*, 4, 4 );\n\n\/\/ ------------------------------------------------------------------------\nSfxItemDesruptor_Impl::SfxItemDesruptor_Impl( SfxPoolItem *pItemToDesrupt ):\n pItem(pItemToDesrupt),\n aLink( LINK(this, SfxItemDesruptor_Impl, Delete) )\n{\n DBG_CTOR(SfxItemDesruptor_Impl, 0);\n\n DBG_ASSERT( 0 == pItem->GetRefCount(), \"desrupting pooled item\" );\n pItem->SetKind( SFX_ITEMS_DELETEONIDLE );\n\n \/\/ im Idle abarbeiten\n GetpApp()->InsertIdleHdl( aLink, 1 );\n\n \/\/ und in Liste eintragen (damit geflusht werden kann)\n SfxItemDesruptorList_Impl* &rpList = ImpSvtData::GetSvtData().pItemDesruptList;\n if ( !rpList )\n rpList = new SfxItemDesruptorList_Impl;\n const SfxItemDesruptor_Impl *pThis = this;\n rpList->Insert( pThis, rpList->Count() );\n}\n\n\/\/ ------------------------------------------------------------------------\nSfxItemDesruptor_Impl::~SfxItemDesruptor_Impl()\n{\n DBG_DTOR(SfxItemDesruptor_Impl, 0);\n\n \/\/ aus Idle-Handler austragen\n GetpApp()->RemoveIdleHdl( aLink );\n\n \/\/ und aus Liste austragen\n SfxItemDesruptorList_Impl* &rpList = ImpSvtData::GetSvtData().pItemDesruptList;\n DBG_ASSERT( rpList, \"no DesruptorList\" );\n const SfxItemDesruptor_Impl *pThis = this;\n if ( rpList ) HACK(warum?)\n rpList->Remove( rpList->GetPos(pThis) );\n\n \/\/ reset RefCount (was set to SFX_ITEMS_SPECIAL before!)\n pItem->SetRefCount( 0 );\n DBG_CHKOBJ( pItem, SfxPoolItem, 0 );\n delete pItem;\n}\n\n\/\/ ------------------------------------------------------------------------\nIMPL_LINK( SfxItemDesruptor_Impl, Delete, void *, pvoid )\n{\n {DBG_CHKTHIS(SfxItemDesruptor_Impl, 0);}\n delete this;\n return 0;\n}\n\n\/\/ ------------------------------------------------------------------------\nSfxPoolItem* DeleteItemOnIdle( SfxPoolItem* pItem )\n{\n DBG_ASSERT( 0 == pItem->GetRefCount(), \"deleting item in use\" );\n new SfxItemDesruptor_Impl( pItem );\n return pItem;\n}\n\n\/\/ ------------------------------------------------------------------------\nvoid DeleteOnIdleItems()\n{\n SfxItemDesruptorList_Impl* &rpList\n = ImpSvtData::GetSvtData().pItemDesruptList;\n if ( rpList )\n {\n USHORT n;\n while ( 0 != ( n = rpList->Count() ) )\n \/\/ Remove ist implizit im Dtor\n delete rpList->GetObject( n-1 );\n DELETEZ(rpList);\n }\n}\n\n\n<|endoftext|>"} {"text":"#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n topScene = new QGraphicsScene(this);\n ui->topView->setScene(topScene);\n rightScene = new QGraphicsScene(this);\n ui->rightView->setScene(rightScene);\n bottomScene = new QGraphicsScene(this);\n ui->bottomView->setScene(bottomScene);\n leftScene = new QGraphicsScene(this);\n ui->leftView->setScene(leftScene);\n diffuseScene = new QGraphicsScene(this);\n ui->diffuseView->setScene(diffuseScene);\n resultScene = new QGraphicsScene(this);\n ui->resultView->setScene(resultScene);\n timer = new QTimer(this);\n connect(timer, SIGNAL(timeout()), ui->oglWidget, SLOT(update()));\n timer->start(40);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nQFileInfo MainWindow::OpenFile(QPushButton* button, QImage& image, QGraphicsScene* scene, QGraphicsView* view)\n{\n\n QString filename = QFileDialog::getOpenFileName(this, tr(\"Open File\"), \"\/\", \"Image File (*.png)\");\n QFileInfo fi(filename);\n\n if(fi.exists())\n {\n button->setText(fi.fileName());\n image.load(fi.absoluteFilePath());\n scene->clear();\n scene->addPixmap(QPixmap::fromImage(image.scaled(QSize(100, 100))));\n view->show();\n }\n return fi;\n}\n\nvoid MainWindow::EnableGenerateButton(bool topPresent, bool rightPresent, bool bottomPresent, bool leftPresent)\n{\n if(topPresent && rightPresent && bottomPresent && leftPresent)\n {\n ui->generateButton->setEnabled(true);\n }\n}\n\nvoid MainWindow::on_topFileButton_clicked()\n{\n OpenFile(ui->topFileButton, topImage, topScene, ui->topView);\n EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());\n}\n\nvoid MainWindow::on_rightFileButton_clicked()\n{\n OpenFile(ui->rightFileButton, rightImage, rightScene, ui->rightView);\n EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());\n}\n\nvoid MainWindow::on_bottomFileButton_clicked()\n{\n OpenFile(ui->bottomFileButton, bottomImage, bottomScene, ui->bottomView);\n EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());\n}\n\nvoid MainWindow::on_leftFileButton_clicked()\n{\n OpenFile(ui->leftFileButton, leftImage, leftScene, ui->leftView);\n EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());\n}\n\nvoid MainWindow::on_diffuseFileButton_clicked()\n{\n QFileInfo fi = OpenFile(ui->diffuseFileButton, diffuseImage, diffuseScene, ui->diffuseView);\n ui->oglWidget->SetDiffuse(diffuseImage);\n}\n\nbool MainWindow::SameSize(QImage first, QImage second, QImage third, QImage fourth)\n{\n QSize k = first.size();\n return k == second.size() && k == third.size() && k == fourth.size();\n}\n\nvoid MainWindow::ProcessNormals(QImage image, int imagetype)\n{\n for(int y = 0; y < image.height(); y++)\n {\n for(int x = 0; x < image.width(); x++)\n {\n QColor color = image.pixel(x, y);\n double normal = color.valueF();\n normal -= 0.5;\n normal *= 2.0;\n if(imagetype == IMAGE::TOP)\n {\n QVector3D vector(0.0, normal, 0.0);\n normals[image.width() * y + x] = normals[image.width() * y + x] + vector;\n }\n\n if(imagetype == IMAGE::RIGHT)\n {\n QVector3D vector(normal, 0.0, 0.0);\n normals[image.width() * y + x] = normals[image.width() * y + x] + vector;\n }\n\n if(imagetype == IMAGE::BOTTOM)\n {\n QVector3D vector(0.0, -normal, 0.0);\n normals[image.width() * y + x] = normals[image.width() * y + x] + vector;\n }\n\n if(imagetype == IMAGE::LEFT)\n {\n QVector3D vector(-normal, 0.0, 0.0);\n normals[image.width() * y + x] = normals[image.width() * y + x] + vector;\n }\n }\n }\n}\n\nvoid MainWindow::on_generateButton_clicked()\n{\n \/\/Ensure all images are the same size\n if(!SameSize(topImage, rightImage, leftImage, bottomImage))\n {\n QMessageBox msgBox;\n msgBox.setText(\"Images are not the same size!\");\n msgBox.exec();\n return;\n }\n\n int normalMapSize = topImage.size().width()*topImage.size().height();\n normals = new QVector3D[normalMapSize];\n\n for(int i = 0; i < normalMapSize; i++)\n {\n \/\/Point all vectors -z\n normals[i].setZ(-1.0);\n normals[i].setY(0);\n normals[i].setX(0);\n }\n\n ProcessNormals(topImage, IMAGE::TOP);\n ProcessNormals(rightImage, IMAGE::RIGHT);\n ProcessNormals(bottomImage, IMAGE::BOTTOM);\n ProcessNormals(leftImage, IMAGE::LEFT);\n\n resultImage = QImage(topImage.width(), topImage.height(), QImage::Format_RGB32);\n\n for(int i = 0; i < normalMapSize; i++)\n {\n normals[i].normalize();\n QColor normColor;\n normColor.setRedF((normals[i].x()+1.0)\/2.0);\n normColor.setGreenF((normals[i].y()+1.0)\/2.0);\n normColor.setBlueF((-normals[i].z()+1.0)\/2.0);\n int yCoord = i \/ topImage.width();\n int xCoord = i % topImage.width();\n resultImage.setPixel(QPoint(xCoord, yCoord), normColor.rgb());\n }\n resultScene->addPixmap(QPixmap::fromImage(resultImage.scaled(QSize(100, 100))));\n ui->resultView->show();\n ui->oglWidget->SetNormalMap(resultImage);\n}\nNear-lossless optimize of generation#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n topScene = new QGraphicsScene(this);\n ui->topView->setScene(topScene);\n rightScene = new QGraphicsScene(this);\n ui->rightView->setScene(rightScene);\n bottomScene = new QGraphicsScene(this);\n ui->bottomView->setScene(bottomScene);\n leftScene = new QGraphicsScene(this);\n ui->leftView->setScene(leftScene);\n diffuseScene = new QGraphicsScene(this);\n ui->diffuseView->setScene(diffuseScene);\n resultScene = new QGraphicsScene(this);\n ui->resultView->setScene(resultScene);\n timer = new QTimer(this);\n connect(timer, SIGNAL(timeout()), ui->oglWidget, SLOT(update()));\n timer->start(40);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nQFileInfo MainWindow::OpenFile(QPushButton* button, QImage& image, QGraphicsScene* scene, QGraphicsView* view)\n{\n\n QString filename = QFileDialog::getOpenFileName(this, tr(\"Open File\"), \"\/\", \"Image File (*.png)\");\n QFileInfo fi(filename);\n\n if(fi.exists())\n {\n button->setText(fi.fileName());\n image.load(fi.absoluteFilePath());\n scene->clear();\n scene->addPixmap(QPixmap::fromImage(image.scaled(QSize(100, 100))));\n view->show();\n }\n return fi;\n}\n\nvoid MainWindow::EnableGenerateButton(bool topPresent, bool rightPresent, bool bottomPresent, bool leftPresent)\n{\n if(topPresent && rightPresent && bottomPresent && leftPresent)\n {\n ui->generateButton->setEnabled(true);\n }\n}\n\nvoid MainWindow::on_topFileButton_clicked()\n{\n OpenFile(ui->topFileButton, topImage, topScene, ui->topView);\n EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());\n}\n\nvoid MainWindow::on_rightFileButton_clicked()\n{\n OpenFile(ui->rightFileButton, rightImage, rightScene, ui->rightView);\n EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());\n}\n\nvoid MainWindow::on_bottomFileButton_clicked()\n{\n OpenFile(ui->bottomFileButton, bottomImage, bottomScene, ui->bottomView);\n EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());\n}\n\nvoid MainWindow::on_leftFileButton_clicked()\n{\n OpenFile(ui->leftFileButton, leftImage, leftScene, ui->leftView);\n EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());\n}\n\nvoid MainWindow::on_diffuseFileButton_clicked()\n{\n QFileInfo fi = OpenFile(ui->diffuseFileButton, diffuseImage, diffuseScene, ui->diffuseView);\n ui->oglWidget->SetDiffuse(diffuseImage);\n}\n\nbool MainWindow::SameSize(QImage first, QImage second, QImage third, QImage fourth)\n{\n QSize k = first.size();\n return k == second.size() && k == third.size() && k == fourth.size();\n}\n\nstatic inline int linearGray(QRgb rgb)\n{\n return std::max({qRed(rgb), qGreen(rgb), qBlue(rgb)});\n}\n\nvoid MainWindow::ProcessNormals(QImage image, int imagetype)\n{\n for(int y = 0; y < image.height(); y++)\n {\n for(int x = 0; x < image.width(); x++)\n {\n double normal = (double)linearGray(image.pixel(x, y)) \/ 255.0;\n normal -= 0.5;\n normal *= 2.0;\n if(imagetype == IMAGE::TOP)\n {\n QVector3D vector(0.0, normal, 0.0);\n normals[image.width() * y + x] = normals[image.width() * y + x] + vector;\n }\n\n if(imagetype == IMAGE::RIGHT)\n {\n QVector3D vector(normal, 0.0, 0.0);\n normals[image.width() * y + x] = normals[image.width() * y + x] + vector;\n }\n\n if(imagetype == IMAGE::BOTTOM)\n {\n QVector3D vector(0.0, -normal, 0.0);\n normals[image.width() * y + x] = normals[image.width() * y + x] + vector;\n }\n\n if(imagetype == IMAGE::LEFT)\n {\n QVector3D vector(-normal, 0.0, 0.0);\n normals[image.width() * y + x] = normals[image.width() * y + x] + vector;\n }\n }\n }\n}\n\nvoid MainWindow::on_generateButton_clicked()\n{\n \/\/Ensure all images are the same size\n if(!SameSize(topImage, rightImage, leftImage, bottomImage))\n {\n QMessageBox msgBox;\n msgBox.setText(\"Images are not the same size!\");\n msgBox.exec();\n return;\n }\n\n int normalMapSize = topImage.size().width()*topImage.size().height();\n normals = new QVector3D[normalMapSize];\n\n for(int i = 0; i < normalMapSize; i++)\n {\n \/\/Point all vectors -z\n normals[i].setZ(-1.0);\n normals[i].setY(0);\n normals[i].setX(0);\n }\n\n ProcessNormals(topImage, IMAGE::TOP);\n ProcessNormals(rightImage, IMAGE::RIGHT);\n ProcessNormals(bottomImage, IMAGE::BOTTOM);\n ProcessNormals(leftImage, IMAGE::LEFT);\n\n resultImage = QImage(topImage.width(), topImage.height(), QImage::Format_RGB32);\n\n for(int i = 0; i < normalMapSize; i++)\n {\n normals[i].normalize();\n QColor normColor;\n normColor.setRgbF((normals[i].x()+1.0)\/2.0,\n (normals[i].y()+1.0)\/2.0,\n (-normals[i].z()+1.0)\/2.0);\n int yCoord = i \/ topImage.width();\n int xCoord = i % topImage.width();\n resultImage.setPixel(QPoint(xCoord, yCoord), normColor.rgb());\n }\n resultScene->addPixmap(QPixmap::fromImage(resultImage.scaled(QSize(100, 100))));\n ui->resultView->show();\n ui->oglWidget->SetNormalMap(resultImage);\n}\n<|endoftext|>"} {"text":"\/*\n * ContextMerge.cpp\n *\n * Created on: Mar 26, 2014\n * Author: nek3d\n *\/\n\n\n#include \"ContextMerge.h\"\n\nContextMerge::ContextMerge()\n{\n\tsetUseMergedIntervals(true);\n\tsetColumnOpsMethods(true);\n\n\t\/\/merge has no default columnOps the way map does, so we'll need to clear those.\n\t_keyListOps->setColumns(\"\");\n\t_keyListOps->setOperations(\"\");\n\n}\n\nContextMerge::~ContextMerge()\n{\n\n}\n\n\nbool ContextMerge::parseCmdArgs(int argc, char **argv, int skipFirstArgs)\n{\n\t_argc = argc;\n\t_argv = argv;\n\t_skipFirstArgs = skipFirstArgs;\n\tif (_argc < 2) {\n\t\tsetShowHelp(true);\n\t\treturn false;\n\t}\n\n\tsetProgram(_programNames[argv[0]]);\n\n\t_argsProcessed.resize(_argc - _skipFirstArgs, false);\n\n\tfor (_i=_skipFirstArgs; _i < argc; _i++) {\n\t\tif (isUsed(_i - _skipFirstArgs)) {\n\t\t\tcontinue;\n\t\t}\n\t\telse if (strcmp(_argv[_i], \"-n\") == 0) {\n\t\t\tif (!handle_n()) return false;\n\t\t}\n\t\telse if (strcmp(_argv[_i], \"-nms\") == 0) {\n\t\t\tif (!handle_nms()) return false;\n\t\t}\n\t\telse if (strcmp(_argv[_i], \"-scores\") == 0) {\n\t\t\tif (!handle_scores()) return false;\n\t\t}\n\t\telse if (strcmp(_argv[_i], \"-delim\") == 0) {\n\t\t\tif (!handle_delim()) return false;\n\t\t}\n\t\telse if (strcmp(_argv[_i], \"-d\") == 0) {\n\t\t\tif (!handle_d()) return false;\n\t\t}\n\t\telse if (strcmp(_argv[_i], \"-s\") == 0) {\n\t\t\tif (!handle_s()) return false;\n\t\t}\n\t\telse if (strcmp(_argv[_i], \"-S\") == 0) {\n\t\t\tif (!handle_S()) return false;\n\t\t}\n\t}\n\treturn ContextBase::parseCmdArgs(argc, argv, _skipFirstArgs);\n}\n\nbool ContextMerge::isValidState()\n{\n\t\/\/ Special: The merge program does not have default\n\t\/\/column operations, so if none were entered, disable column ops.\n\tif (_keyListOps->getColumns().empty() && _keyListOps->getOperations().empty()) {\n\t\tsetColumnOpsMethods(false);\n\t\tdelete _keyListOps;\n\t\t_keyListOps = NULL;\n\t}\n\tif (!ContextBase::isValidState()) {\n\t\treturn false;\n\t}\n\tif (_files.size() != 1) {\n\t\t_errorMsg = \"\\n***** ERROR: input file not specified. *****\";\n\t\t\/\/ Allow only one input file for now\n\t\treturn false;\n\t}\n\n\t\/\/\n\t\/\/ Tests for stranded merge\n\t\/\/\n\tif (_desiredStrand != FileRecordMergeMgr::ANY_STRAND) { \/\/ requested stranded merge\n\t\t\/\/ make sure file has strand.\n\t\tif (!getFile(0)->recordsHaveStrand()) {\n\t\t\t_errorMsg = \"\\n***** ERROR: stranded merge requested, but input file records do not have strand. *****\";\n\t\t\treturn false;\n\t\t}\n\t\t\/\/make sure file is not VCF.\n\t\tif (getFile(0)->getFileType() == FileRecordTypeChecker::VCF_FILE_TYPE) {\n\t\t\t_errorMsg = \"\\n***** ERROR: stranded merge not supported for VCF files. *****\";\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/column operations not allowed with BAM input\n\tif (hasColumnOpsMethods() &&\n\t\t\tgetFile(0)->getFileType() == FileRecordTypeChecker::BAM_FILE_TYPE) {\n\t\t_errorMsg = \"\\n***** ERROR: stranded merge not supported for VCF files. *****\";\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n\nbool ContextMerge::handle_d() {\n if ((_i+1) < _argc) {\n \tif (isNumeric(_argv[_i+1])) {\n\t\t\tint dist = str2chrPos(_argv[_i+1]);\n\t\t\tif (dist >=0 ) {\n\t\t\t\t_maxDistance = dist;\n\t\t \tmarkUsed(_i - _skipFirstArgs);\n\t\t _i++;\n\t\t markUsed(_i - _skipFirstArgs);\n\t\t\t\treturn true;\n\t\t\t}\n \t}\n }\n\t_errorMsg = \"\\n***** ERROR: -d option must be followed by an integer value *****\";\n\treturn false;\n}\n\nbool ContextMerge::handle_n()\n{\n\tmarkUsed(_i - _skipFirstArgs);\n\t_errorMsg = \"\\n***** ERROR: -n option is deprecated. Please see the documentation for the -c and -o column operation options. *****\";\n return false;\n}\n\nbool ContextMerge::handle_nms()\n{\n\tmarkUsed(_i - _skipFirstArgs);\n\t_errorMsg = \"\\n***** ERROR: -nms option is deprecated. Please see the documentation for the -c and -o column operation options. *****\";\n return false;\n\n}\n\n\nbool ContextMerge::handle_scores()\n{\n\t\/\/ No longer supporting this deprecated option.\n\tmarkUsed(_i - _skipFirstArgs);\n\t_errorMsg = \"\\n***** ERROR: -scores option is deprecated. Please see the documentation for the -c and -o column operation options. *****\";\n return false;\n}\n\nbool ContextMerge::handle_s() {\n\t_desiredStrand = FileRecordMergeMgr::SAME_STRAND_EITHER;\n\tmarkUsed(_i - _skipFirstArgs);\n\treturn true;\n}\n\nbool ContextMerge::handle_S() {\n if ((_i+1) < _argc) {\n \tbool validChar = false;\n \tif (_argv[_i+1][0] == '+') {\n\t\t\t_desiredStrand = FileRecordMergeMgr::SAME_STRAND_FORWARD;\n\t\t\tvalidChar = true;\n \t} else if (_argv[_i+1][0] == '-') {\n \t\tvalidChar = true;\n\t\t\t_desiredStrand = FileRecordMergeMgr::SAME_STRAND_REVERSE;\n \t}\n \tif (validChar) {\n\t\t\tmarkUsed(_i - _skipFirstArgs);\n\t\t\t_i++;\n\t\t\tmarkUsed(_i - _skipFirstArgs);\n\t\t\treturn true;\n \t}\n }\n\t_errorMsg = \"\\n***** ERROR: -S option must be followed by + or -. *****\";\n\treturn false;\n}\nallow merge -d to have negative values for minimum overlap.\/*\n * ContextMerge.cpp\n *\n * Created on: Mar 26, 2014\n * Author: nek3d\n *\/\n\n\n#include \"ContextMerge.h\"\n\nContextMerge::ContextMerge()\n{\n\tsetUseMergedIntervals(true);\n\tsetColumnOpsMethods(true);\n\n\t\/\/merge has no default columnOps the way map does, so we'll need to clear those.\n\t_keyListOps->setColumns(\"\");\n\t_keyListOps->setOperations(\"\");\n\n}\n\nContextMerge::~ContextMerge()\n{\n\n}\n\n\nbool ContextMerge::parseCmdArgs(int argc, char **argv, int skipFirstArgs)\n{\n\t_argc = argc;\n\t_argv = argv;\n\t_skipFirstArgs = skipFirstArgs;\n\tif (_argc < 2) {\n\t\tsetShowHelp(true);\n\t\treturn false;\n\t}\n\n\tsetProgram(_programNames[argv[0]]);\n\n\t_argsProcessed.resize(_argc - _skipFirstArgs, false);\n\n\tfor (_i=_skipFirstArgs; _i < argc; _i++) {\n\t\tif (isUsed(_i - _skipFirstArgs)) {\n\t\t\tcontinue;\n\t\t}\n\t\telse if (strcmp(_argv[_i], \"-n\") == 0) {\n\t\t\tif (!handle_n()) return false;\n\t\t}\n\t\telse if (strcmp(_argv[_i], \"-nms\") == 0) {\n\t\t\tif (!handle_nms()) return false;\n\t\t}\n\t\telse if (strcmp(_argv[_i], \"-scores\") == 0) {\n\t\t\tif (!handle_scores()) return false;\n\t\t}\n\t\telse if (strcmp(_argv[_i], \"-delim\") == 0) {\n\t\t\tif (!handle_delim()) return false;\n\t\t}\n\t\telse if (strcmp(_argv[_i], \"-d\") == 0) {\n\t\t\tif (!handle_d()) return false;\n\t\t}\n\t\telse if (strcmp(_argv[_i], \"-s\") == 0) {\n\t\t\tif (!handle_s()) return false;\n\t\t}\n\t\telse if (strcmp(_argv[_i], \"-S\") == 0) {\n\t\t\tif (!handle_S()) return false;\n\t\t}\n\t}\n\treturn ContextBase::parseCmdArgs(argc, argv, _skipFirstArgs);\n}\n\nbool ContextMerge::isValidState()\n{\n\t\/\/ Special: The merge program does not have default\n\t\/\/column operations, so if none were entered, disable column ops.\n\tif (_keyListOps->getColumns().empty() && _keyListOps->getOperations().empty()) {\n\t\tsetColumnOpsMethods(false);\n\t\tdelete _keyListOps;\n\t\t_keyListOps = NULL;\n\t}\n\tif (!ContextBase::isValidState()) {\n\t\treturn false;\n\t}\n\tif (_files.size() != 1) {\n\t\t_errorMsg = \"\\n***** ERROR: input file not specified. *****\";\n\t\t\/\/ Allow only one input file for now\n\t\treturn false;\n\t}\n\n\t\/\/\n\t\/\/ Tests for stranded merge\n\t\/\/\n\tif (_desiredStrand != FileRecordMergeMgr::ANY_STRAND) { \/\/ requested stranded merge\n\t\t\/\/ make sure file has strand.\n\t\tif (!getFile(0)->recordsHaveStrand()) {\n\t\t\t_errorMsg = \"\\n***** ERROR: stranded merge requested, but input file records do not have strand. *****\";\n\t\t\treturn false;\n\t\t}\n\t\t\/\/make sure file is not VCF.\n\t\tif (getFile(0)->getFileType() == FileRecordTypeChecker::VCF_FILE_TYPE) {\n\t\t\t_errorMsg = \"\\n***** ERROR: stranded merge not supported for VCF files. *****\";\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/column operations not allowed with BAM input\n\tif (hasColumnOpsMethods() &&\n\t\t\tgetFile(0)->getFileType() == FileRecordTypeChecker::BAM_FILE_TYPE) {\n\t\t_errorMsg = \"\\n***** ERROR: stranded merge not supported for VCF files. *****\";\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n\nbool ContextMerge::handle_d() {\n if ((_i+1) < _argc) {\n \tif (isNumeric(_argv[_i+1])) {\n\t\t\tint dist = str2chrPos(_argv[_i+1]);\n\t\t\t\n\t\t\t_maxDistance = dist;\n\t \tmarkUsed(_i - _skipFirstArgs);\n\t _i++;\n\t markUsed(_i - _skipFirstArgs);\n\t\t\treturn true;\n \t}\n }\n\t_errorMsg = \"\\n***** ERROR: -d option must be followed by an integer value *****\";\n\treturn false;\n}\n\nbool ContextMerge::handle_n()\n{\n\tmarkUsed(_i - _skipFirstArgs);\n\t_errorMsg = \"\\n***** ERROR: -n option is deprecated. Please see the documentation for the -c and -o column operation options. *****\";\n return false;\n}\n\nbool ContextMerge::handle_nms()\n{\n\tmarkUsed(_i - _skipFirstArgs);\n\t_errorMsg = \"\\n***** ERROR: -nms option is deprecated. Please see the documentation for the -c and -o column operation options. *****\";\n return false;\n\n}\n\n\nbool ContextMerge::handle_scores()\n{\n\t\/\/ No longer supporting this deprecated option.\n\tmarkUsed(_i - _skipFirstArgs);\n\t_errorMsg = \"\\n***** ERROR: -scores option is deprecated. Please see the documentation for the -c and -o column operation options. *****\";\n return false;\n}\n\nbool ContextMerge::handle_s() {\n\t_desiredStrand = FileRecordMergeMgr::SAME_STRAND_EITHER;\n\tmarkUsed(_i - _skipFirstArgs);\n\treturn true;\n}\n\nbool ContextMerge::handle_S() {\n if ((_i+1) < _argc) {\n \tbool validChar = false;\n \tif (_argv[_i+1][0] == '+') {\n\t\t\t_desiredStrand = FileRecordMergeMgr::SAME_STRAND_FORWARD;\n\t\t\tvalidChar = true;\n \t} else if (_argv[_i+1][0] == '-') {\n \t\tvalidChar = true;\n\t\t\t_desiredStrand = FileRecordMergeMgr::SAME_STRAND_REVERSE;\n \t}\n \tif (validChar) {\n\t\t\tmarkUsed(_i - _skipFirstArgs);\n\t\t\t_i++;\n\t\t\tmarkUsed(_i - _skipFirstArgs);\n\t\t\treturn true;\n \t}\n }\n\t_errorMsg = \"\\n***** ERROR: -S option must be followed by + or -. *****\";\n\treturn false;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: brdcst.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: mh $ $Date: 2001-10-17 17:06:19 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#ifndef _DEBUG_HXX\n#include \n#endif\n\n#include \"hint.hxx\"\n#include \"smplhint.hxx\"\n#include \"lstner.hxx\"\n\nSV_DECL_PTRARR( SfxListenerArr_Impl, SfxListener*, 0, 2 );\n\n#define _SFX_BRDCST_CXX\n#include \"brdcst.hxx\"\n\n\/\/====================================================================\nDBG_NAME(SfxBroadcaster);\nTYPEINIT0(SfxBroadcaster);\n\n\/\/====================================================================\n\n\/\/====================================================================\n\/\/ broadcast immedeately\n\n\nvoid SfxBroadcaster::Broadcast( const SfxHint &rHint )\n{\n DBG_CHKTHIS(SfxBroadcaster, 0);\n\n \/\/ is anybody to notify?\n if ( aListeners.Count() \/*! || aGlobListeners.Count() *\/ )\n {\n \/\/ determine the type only once, because of its expensiveness\n const TypeId& rBCType = Type();\n const TypeId& rHintType = rHint.Type();\n\n \/\/ notify all registered listeners exactly once\n for ( USHORT n = 0; n < aListeners.Count(); ++n )\n {\n SfxListener* pListener = aListeners[n];\n if ( pListener )\n pListener->SFX_NOTIFY( *this, rBCType, rHint, rHintType );\n }\n }\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ broadcast after a timeout\n\n\nvoid SfxBroadcaster::BroadcastDelayed( const SfxHint& rHint )\n{\n DBG_WARNING( \"not implemented\" );\n Broadcast(rHint);\n}\n\/\/--------------------------------------------------------------------\n\n\/\/ broadcast in idle-handler\n\n\nvoid SfxBroadcaster::BroadcastInIdle( const SfxHint& rHint )\n{\n DBG_WARNING( \"not implemented\" );\n Broadcast(rHint);\n}\n\/\/--------------------------------------------------------------------\n\n\/\/ unregister all listeners\n\n\nSfxBroadcaster::~SfxBroadcaster()\n{\n DBG_DTOR(SfxBroadcaster, 0);\n\n Broadcast( SfxSimpleHint(SFX_HINT_DYING) );\n\n \/\/ remove all still registered listeners\n for ( USHORT nPos = 0; nPos < aListeners.Count(); ++nPos )\n {\n SfxListener *pListener = aListeners[nPos];\n if ( pListener )\n pListener->RemoveBroadcaster_Impl(*this);\n }\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ simple ctor of class SfxBroadcaster\n\n\nSfxBroadcaster::SfxBroadcaster()\n{\n DBG_CTOR(SfxBroadcaster, 0);\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ copy ctor of class SfxBroadcaster\n\n\nSfxBroadcaster::SfxBroadcaster( const SfxBroadcaster &rBC )\n{\n DBG_CTOR(SfxBroadcaster, 0);\n\n for ( USHORT n = 0; n < rBC.aListeners.Count(); ++n )\n {\n SfxListener *pListener = rBC.aListeners[n];\n if ( pListener )\n pListener->StartListening( *this );\n }\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ add a new SfxListener to the list\n\nBOOL SfxBroadcaster::AddListener( SfxListener& rListener )\n{\n DBG_CHKTHIS(SfxBroadcaster, 0);\n const SfxListener *pListener = &rListener;\n const SfxListener *pNull = 0;\n USHORT nFreePos = aListeners.GetPos( pNull );\n if ( nFreePos < aListeners.Count() )\n aListeners.GetData()[nFreePos] = pListener;\n else if ( aListeners.Count() < (USHRT_MAX-1) )\n aListeners.Insert( pListener, aListeners.Count() );\n else\n {\n DBG_ERROR( \"array overflow\" );\n return FALSE;\n }\n\n DBG_ASSERT( USHRT_MAX != aListeners.GetPos(pListener),\n \"AddListener failed\" );\n return TRUE;\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ called, if no more listeners exists\n\nvoid SfxBroadcaster::ListenersGone()\n{\n DBG_CHKTHIS(SfxBroadcaster,0);\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ forward a notification to all registered listeners\n\nvoid SfxBroadcaster::SFX_FORWARD(SfxBroadcaster& rBC, const TypeId& rBCType,\n const SfxHint& rHint, const TypeId& rHintType)\n{\n const USHORT nCount = aListeners.Count();\n for ( USHORT i = 0; i < nCount; ++i )\n {\n SfxListener *pListener = aListeners[i];\n if ( pListener )\n pListener->SFX_NOTIFY( rBC, rBCType, rHint, rHintType);\n }\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ remove one SfxListener from the list\n\nvoid SfxBroadcaster::RemoveListener( SfxListener& rListener )\n{\n {DBG_CHKTHIS(SfxBroadcaster, 0);}\n const SfxListener *pListener = &rListener;\n USHORT nPos = aListeners.GetPos(pListener);\n DBG_ASSERT( nPos != USHRT_MAX, \"RemoveListener: Listener unknown\" );\n aListeners.GetData()[nPos] = 0;\n if ( !HasListeners() )\n ListenersGone();\n}\n\n\/\/--------------------------------------------------------------------\n\n\nBOOL SfxBroadcaster::HasListeners() const\n{\n for ( USHORT n = 0; n < aListeners.Count(); ++n )\n if ( aListeners.GetObject(n) != 0 )\n return TRUE;\n return FALSE;\n}\n\n\/\/--------------------------------------------------------------------\n\n\nINTEGRATION: CWS ooo20040509 (1.2.566); FILE MERGED 2004\/05\/06 12:29:06 waratah 1.2.566.1: Bracket a pragma that is not valid for gcc to remove -Wall warning\/*************************************************************************\n *\n * $RCSfile: brdcst.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2004-06-16 10:25:31 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef GCC\n#pragma hdrstop\n#endif\n\n#ifndef _DEBUG_HXX\n#include \n#endif\n\n#include \"hint.hxx\"\n#include \"smplhint.hxx\"\n#include \"lstner.hxx\"\n\nSV_DECL_PTRARR( SfxListenerArr_Impl, SfxListener*, 0, 2 );\n\n#define _SFX_BRDCST_CXX\n#include \"brdcst.hxx\"\n\n\/\/====================================================================\nDBG_NAME(SfxBroadcaster);\nTYPEINIT0(SfxBroadcaster);\n\n\/\/====================================================================\n\n\/\/====================================================================\n\/\/ broadcast immediately\n\n\nvoid SfxBroadcaster::Broadcast( const SfxHint &rHint )\n{\n DBG_CHKTHIS(SfxBroadcaster, 0);\n\n \/\/ is anybody to notify?\n if ( aListeners.Count() \/*! || aGlobListeners.Count() *\/ )\n {\n \/\/ determine the type only once, because of its expensiveness\n const TypeId& rBCType = Type();\n const TypeId& rHintType = rHint.Type();\n\n \/\/ notify all registered listeners exactly once\n for ( USHORT n = 0; n < aListeners.Count(); ++n )\n {\n SfxListener* pListener = aListeners[n];\n if ( pListener )\n pListener->SFX_NOTIFY( *this, rBCType, rHint, rHintType );\n }\n }\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ broadcast after a timeout\n\n\nvoid SfxBroadcaster::BroadcastDelayed( const SfxHint& rHint )\n{\n DBG_WARNING( \"not implemented\" );\n Broadcast(rHint);\n}\n\/\/--------------------------------------------------------------------\n\n\/\/ broadcast in idle-handler\n\nvoid SfxBroadcaster::BroadcastInIdle( const SfxHint& rHint )\n{\n DBG_WARNING( \"not implemented\" );\n Broadcast(rHint);\n}\n\/\/--------------------------------------------------------------------\n\n\/\/ unregister all listeners\n\nSfxBroadcaster::~SfxBroadcaster()\n{\n DBG_DTOR(SfxBroadcaster, 0);\n\n Broadcast( SfxSimpleHint(SFX_HINT_DYING) );\n\n \/\/ remove all still registered listeners\n for ( USHORT nPos = 0; nPos < aListeners.Count(); ++nPos )\n {\n SfxListener *pListener = aListeners[nPos];\n if ( pListener )\n pListener->RemoveBroadcaster_Impl(*this);\n }\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ simple ctor of class SfxBroadcaster\n\nSfxBroadcaster::SfxBroadcaster()\n{\n DBG_CTOR(SfxBroadcaster, 0);\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ copy ctor of class SfxBroadcaster\n\n\nSfxBroadcaster::SfxBroadcaster( const SfxBroadcaster &rBC )\n{\n DBG_CTOR(SfxBroadcaster, 0);\n\n for ( USHORT n = 0; n < rBC.aListeners.Count(); ++n )\n {\n SfxListener *pListener = rBC.aListeners[n];\n if ( pListener )\n pListener->StartListening( *this );\n }\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ add a new SfxListener to the list\n\nBOOL SfxBroadcaster::AddListener( SfxListener& rListener )\n{\n DBG_CHKTHIS(SfxBroadcaster, 0);\n const SfxListener *pListener = &rListener;\n const SfxListener *pNull = 0;\n USHORT nFreePos = aListeners.GetPos( pNull );\n if ( nFreePos < aListeners.Count() )\n aListeners.GetData()[nFreePos] = pListener;\n else if ( aListeners.Count() < (USHRT_MAX-1) )\n aListeners.Insert( pListener, aListeners.Count() );\n else\n {\n DBG_ERROR( \"array overflow\" );\n return FALSE;\n }\n\n DBG_ASSERT( USHRT_MAX != aListeners.GetPos(pListener),\n \"AddListener failed\" );\n return TRUE;\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ called, if no more listeners exists\n\nvoid SfxBroadcaster::ListenersGone()\n{\n DBG_CHKTHIS(SfxBroadcaster,0);\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ forward a notification to all registered listeners\n\nvoid SfxBroadcaster::SFX_FORWARD(SfxBroadcaster& rBC, const TypeId& rBCType,\n const SfxHint& rHint, const TypeId& rHintType)\n{\n const USHORT nCount = aListeners.Count();\n for ( USHORT i = 0; i < nCount; ++i )\n {\n SfxListener *pListener = aListeners[i];\n if ( pListener )\n pListener->SFX_NOTIFY( rBC, rBCType, rHint, rHintType);\n }\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ remove one SfxListener from the list\n\nvoid SfxBroadcaster::RemoveListener( SfxListener& rListener )\n{\n {DBG_CHKTHIS(SfxBroadcaster, 0);}\n const SfxListener *pListener = &rListener;\n USHORT nPos = aListeners.GetPos(pListener);\n DBG_ASSERT( nPos != USHRT_MAX, \"RemoveListener: Listener unknown\" );\n aListeners.GetData()[nPos] = 0;\n if ( !HasListeners() )\n ListenersGone();\n}\n\n\/\/--------------------------------------------------------------------\n\nBOOL SfxBroadcaster::HasListeners() const\n{\n for ( USHORT n = 0; n < aListeners.Count(); ++n )\n if ( aListeners.GetObject(n) != 0 )\n return TRUE;\n return FALSE;\n}\n\n\/\/--------------------------------------------------------------------\n<|endoftext|>"} {"text":"INTEGRATION: CWS presenterscreen (1.2.4); FILE MERGED 2008\/04\/23 11:59:53 af 1.2.4.4: #i18486# Fixed mixup of uno\/rtl References and boost::shared_ptrs. 2008\/04\/22 08:36:00 af 1.2.4.3: #i18486# Split initialization off the PresenterToolBar constructor. 2008\/04\/22 08:24:53 af 1.2.4.2: RESYNC: (1.2-1.3); FILE MERGED 2008\/04\/16 16:11:13 af 1.2.4.1: #i18486# Tool bar entries can be vertical stacks of other entries.<|endoftext|>"} {"text":"#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"core\/models.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct named_model {\n const char *name;\n const bitNames_t *model;\n};\nconst struct named_model models[] = {\n { \"eflags\", &x86_eflags, },\n { \"cr0\", &x86_cr0, },\n { \"cr4\", &x86_cr4, },\n};\n\nconst QChar MainWindow::kFillChar('0');\nconst uint MainWindow::kBitCount = 32;\n\nstatic inline int\nhexLength(uint bits)\n{\n switch (bits) {\n case 8: return 2;\n case 16: return 4;\n case 32: return 8;\n };\n return 16;\n}\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow),\n signalMapper(new QSignalMapper(this)),\n valueWidth(kBitCount)\n{\n modelInit();\n uiInit();\n\n setValueWidth(kBitCount);\n namesChanged(0);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid\nMainWindow::modelInit(uint64_t initialValue)\n{\n model.setValue(initialValue);\n}\n\nvoid\nMainWindow::uiInit()\n{\n ui->setupUi(this);\n\n digitFont.setStyleHint(QFont::Monospace);\n#ifdef _WIN32\n digitFont.setFamily(QStringLiteral(\"Courier New\"));\n digitFont.setPointSize(11);\n#elif __APPLE__\n digitFont.setFamily(\"Menlo-Regular\");\n#endif\n ui->valueEdit->setFont(digitFont);\n ui->nameSummary->setFont(digitFont);\n\n uint64_t bit = 1ULL;\n for (uint i = 0; i < kBitCount; ++i) {\n int value = !!(model.value() & bit);\n QWidget *w;\n\n w = createBit(i, value);\n getBitLayout(i)->insertWidget(0, w);\n\n w = createName(i, value);\n ui->gridLayout->addWidget(w, i \/ 4, i % 4);\n\n bit <<= 1;\n }\n for (uint b = 8; b <= kBitCount; b <<= 1) {\n ui->bitComboBox->addItem(QString::number(b));\n }\n ui->bitComboBox->setCurrentIndex(ui->bitComboBox->count()-1);\n\n for (size_t i = 0; i < sizeof(models)\/sizeof(models[0]); i++) {\n ui->comboBox->addItem(QString(models[i].name));\n }\n\n connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(bitClicked(int)));\n connect(ui->valueEdit, SIGNAL(textEdited(QString)), this, SLOT(valueChanged(QString)));\n connect(ui->bitComboBox, SIGNAL(activated(int)), this, SLOT(valueWidthChanged(int)));\n connect(ui->comboBox, SIGNAL(activated(int)), this, SLOT(namesChanged(int)));\n}\n\nvoid\nMainWindow::setNames(const bitNames_t names)\n{\n model.setNames(names);\n updateBitNames();\n updateSummary();\n}\n\nvoid\nMainWindow::setValueWidth(uint width)\n{\n switch (width) {\n case 8: case 16: case 32: case 64:\n break;\n default:\n return;\n }\n for (uint i = valueWidth; i < width; i++) {\n ui->gridLayout->itemAt(i)->widget()->show();\n }\n for (uint i = width; i < kBitCount; i++) {\n ui->gridLayout->itemAt(i)->widget()->hide();\n }\n if (width > 16)\n ui->highWord->show();\n else\n ui->highWord->hide();\n if (width > 8) {\n for (int i = 0; i < ui->ahBits->count(); i++) {\n ui->ahBits->itemAt(i)->widget()->show();\n }\n } else {\n for (int i = 0; i < ui->ahBits->count(); i++) {\n ui->ahBits->itemAt(i)->widget()->hide();\n }\n }\n valueWidth = width;\n ui->valueEdit->setMaxLength(hexLength(valueWidth));\n ui->valueEdit->setInputMask(QString(hexLength(valueWidth), QChar('H')));\n updateValueEdit();\n}\n\nQHBoxLayout *\nMainWindow::getBitLayout(uint i){\n if (i >= 24)\n return ui->ehBits;\n if (i >= 16)\n return ui->elBits;\n if (i >= 8)\n return ui->ahBits;\n return ui->alBits;\n}\n\nQWidget *\nMainWindow::getBitWidget(uint i)\n{\n if (i >= 32)\n return 0;\n if (i >= 24)\n return ui->ehBits->itemAt(32-1-i)->widget();\n if (i >= 16)\n return ui->elBits->itemAt(24-1-i)->widget();\n if (i >= 8)\n return ui->ahBits->itemAt(16-1-i)->widget();\n return ui->alBits->itemAt(8-1-i)->widget();\n}\n\nQWidget *\nMainWindow::createBit(uint i, int value)\n{\n QPushButton *pushButton = new QPushButton(this);\n pushButton->setObjectName(QString(\"bitBtn%1\").arg(i, 2, 10, kFillChar));\n pushButton->setFont(digitFont);\n pushButton->setFlat(true);\n\n pushButton->setMinimumSize(QSize(20, 26));\n pushButton->setMaximumSize(QSize(20, 26));\n\n pushButton->setText(QString::number(value));\n pushButton->setToolTip(QString::number(i));\n\n signalMapper->setMapping(pushButton, i);\n connect(pushButton, SIGNAL(clicked()), signalMapper, SLOT(map()));\n\n return pushButton;\n}\n\nvoid\nMainWindow::toggleBit(uint i, int value)\n{\n QPushButton * b;\n b = qobject_cast(getBitWidget(i));\n b->setText(QString::number(value));\n\n b = qobject_cast(ui->gridLayout->itemAt(i)->widget());\n b->setChecked(value);\n}\n\nQWidget *\nMainWindow::createName(uint i, int value)\n{\n QPushButton *b = new QPushButton(getName(i));\n b->setObjectName(QString(\"nameBtn%1\").arg(i, 2, 10, kFillChar));\n b->setCheckable(true);\n b->setFlat(true);\n b->setChecked(value);\n b->setToolTip(getNameTip(i));\n\n signalMapper->setMapping(b, i);\n connect(b, SIGNAL(clicked()), signalMapper, SLOT(map()));\n\n return b;\n}\n\nQString\nMainWindow::getName(uint i) const\n{\n return model.bitName(i) ?\n QString(model.bitName(i)) :\n QString::number(i);\n}\n\nQString\nMainWindow::getNameTip(uint i) const\n{\n return hexToString(1ULL << i);\n}\n\nQString\nMainWindow::hexToString(uint64_t v) const\n{\n return QString(\"0x%1\").arg(v, hexLength(valueWidth), 16, kFillChar);\n}\n\nvoid\nMainWindow::updateBitNames()\n{\n for (uint i = 0; i < valueWidth; i++) {\n QPushButton *b = qobject_cast(ui->gridLayout->itemAt(i)->widget());\n b->setText(getName(i));\n }\n}\n\nvoid\nMainWindow::updateSummary()\n{\n QString summary;\n uint64_t rest = 0, bit = 1ULL;\n for (uint i = 0; i < valueWidth; i++) {\n if (model[i]) {\n if (model.bitName(i)) {\n summary.append('|').append(model.bitName(i));\n } else\n rest |= bit;\n }\n bit <<= 1;\n }\n summary.prepend(hexToString(rest));\n ui->nameSummary->setText(summary);\n}\n\nvoid\nMainWindow::bitClicked(int b)\n{\n model.toggleBit(b);\n updateValueEdit();\n toggleBit(b, model[b]);\n}\n\nvoid\nMainWindow::updateValueEdit()\n{\n int pos = ui->valueEdit->cursorPosition();\n ui->valueEdit->setText(QString(\"%1\").arg(model.value(), hexLength(valueWidth), 16, kFillChar));\n if (pos < 0 || pos >= hexLength(valueWidth))\n pos = 0;\n ui->valueEdit->setCursorPosition(pos);\n updateSummary();\n}\n\nvoid\nMainWindow::updateBits()\n{\n uint64_t bit = 1UL;\n for (uint i = 0; i < valueWidth; i++) {\n toggleBit(i, !!(model.value() & bit));\n bit <<= 1;\n }\n}\n\nvoid\nMainWindow::valueChanged(QString)\n{\n if (ui->valueEdit->cursorPosition() >= hexLength(valueWidth))\n ui->valueEdit->setCursorPosition(hexLength(valueWidth)-1);\n\n bool ok = true;\n uint64_t v = ui->valueEdit->text().toULongLong(&ok, 16);\n if (!ok)\n return;\n model.setValue(v);\n updateBits();\n updateSummary();\n}\n\nvoid\nMainWindow::namesChanged(int index)\n{\n if (index >= 0 && index < (int)(sizeof(models)\/sizeof(models[0])))\n setNames(*models[index].model);\n updateSummary();\n}\n\nvoid\nMainWindow::valueWidthChanged(int index)\n{\n if (index < 0)\n return;\n setValueWidth(8 << index);\n}\n\nvoid\nMainWindow::keyPressEvent(QKeyEvent *event)\n{\n if (event->matches(QKeySequence::Paste)) {\n event->ignore();\n QClipboard *clipboard = QApplication::clipboard();\n QString originalText = clipboard->text();\n bool ok = false;\n uint64_t v = originalText.toULongLong(&ok, 16);\n if (!ok)\n v = originalText.toULongLong(&ok, 10);\n\n if (ok) {\n model.setValue(v);\n updateValueEdit();\n updateBits();\n }\n }\n else return QMainWindow::keyPressEvent(event);\n}\nFix wrong high bit names after changing bit set while less than 32 bits#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"core\/models.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct named_model {\n const char *name;\n const bitNames_t *model;\n};\nconst struct named_model models[] = {\n { \"eflags\", &x86_eflags, },\n { \"cr0\", &x86_cr0, },\n { \"cr4\", &x86_cr4, },\n};\n\nconst QChar MainWindow::kFillChar('0');\nconst uint MainWindow::kBitCount = 32;\n\nstatic inline int\nhexLength(uint bits)\n{\n switch (bits) {\n case 8: return 2;\n case 16: return 4;\n case 32: return 8;\n };\n return 16;\n}\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow),\n signalMapper(new QSignalMapper(this)),\n valueWidth(kBitCount)\n{\n modelInit();\n uiInit();\n\n setValueWidth(kBitCount);\n namesChanged(0);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid\nMainWindow::modelInit(uint64_t initialValue)\n{\n model.setValue(initialValue);\n}\n\nvoid\nMainWindow::uiInit()\n{\n ui->setupUi(this);\n\n digitFont.setStyleHint(QFont::Monospace);\n#ifdef _WIN32\n digitFont.setFamily(QStringLiteral(\"Courier New\"));\n digitFont.setPointSize(11);\n#elif __APPLE__\n digitFont.setFamily(\"Menlo-Regular\");\n#endif\n ui->valueEdit->setFont(digitFont);\n ui->nameSummary->setFont(digitFont);\n\n uint64_t bit = 1ULL;\n for (uint i = 0; i < kBitCount; ++i) {\n int value = !!(model.value() & bit);\n QWidget *w;\n\n w = createBit(i, value);\n getBitLayout(i)->insertWidget(0, w);\n\n w = createName(i, value);\n ui->gridLayout->addWidget(w, i \/ 4, i % 4);\n\n bit <<= 1;\n }\n for (uint b = 8; b <= kBitCount; b <<= 1) {\n ui->bitComboBox->addItem(QString::number(b));\n }\n ui->bitComboBox->setCurrentIndex(ui->bitComboBox->count()-1);\n\n for (size_t i = 0; i < sizeof(models)\/sizeof(models[0]); i++) {\n ui->comboBox->addItem(QString(models[i].name));\n }\n\n connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(bitClicked(int)));\n connect(ui->valueEdit, SIGNAL(textEdited(QString)), this, SLOT(valueChanged(QString)));\n connect(ui->bitComboBox, SIGNAL(activated(int)), this, SLOT(valueWidthChanged(int)));\n connect(ui->comboBox, SIGNAL(activated(int)), this, SLOT(namesChanged(int)));\n}\n\nvoid\nMainWindow::setNames(const bitNames_t names)\n{\n model.setNames(names);\n updateBitNames();\n updateSummary();\n}\n\nvoid\nMainWindow::setValueWidth(uint width)\n{\n switch (width) {\n case 8: case 16: case 32: case 64:\n break;\n default:\n return;\n }\n for (uint i = valueWidth; i < width; i++) {\n ui->gridLayout->itemAt(i)->widget()->show();\n }\n for (uint i = width; i < kBitCount; i++) {\n ui->gridLayout->itemAt(i)->widget()->hide();\n }\n if (width > 16)\n ui->highWord->show();\n else\n ui->highWord->hide();\n if (width > 8) {\n for (int i = 0; i < ui->ahBits->count(); i++) {\n ui->ahBits->itemAt(i)->widget()->show();\n }\n } else {\n for (int i = 0; i < ui->ahBits->count(); i++) {\n ui->ahBits->itemAt(i)->widget()->hide();\n }\n }\n valueWidth = width;\n ui->valueEdit->setMaxLength(hexLength(valueWidth));\n ui->valueEdit->setInputMask(QString(hexLength(valueWidth), QChar('H')));\n updateValueEdit();\n}\n\nQHBoxLayout *\nMainWindow::getBitLayout(uint i){\n if (i >= 24)\n return ui->ehBits;\n if (i >= 16)\n return ui->elBits;\n if (i >= 8)\n return ui->ahBits;\n return ui->alBits;\n}\n\nQWidget *\nMainWindow::getBitWidget(uint i)\n{\n if (i >= 32)\n return 0;\n if (i >= 24)\n return ui->ehBits->itemAt(32-1-i)->widget();\n if (i >= 16)\n return ui->elBits->itemAt(24-1-i)->widget();\n if (i >= 8)\n return ui->ahBits->itemAt(16-1-i)->widget();\n return ui->alBits->itemAt(8-1-i)->widget();\n}\n\nQWidget *\nMainWindow::createBit(uint i, int value)\n{\n QPushButton *pushButton = new QPushButton(this);\n pushButton->setObjectName(QString(\"bitBtn%1\").arg(i, 2, 10, kFillChar));\n pushButton->setFont(digitFont);\n pushButton->setFlat(true);\n\n pushButton->setMinimumSize(QSize(20, 26));\n pushButton->setMaximumSize(QSize(20, 26));\n\n pushButton->setText(QString::number(value));\n pushButton->setToolTip(QString::number(i));\n\n signalMapper->setMapping(pushButton, i);\n connect(pushButton, SIGNAL(clicked()), signalMapper, SLOT(map()));\n\n return pushButton;\n}\n\nvoid\nMainWindow::toggleBit(uint i, int value)\n{\n QPushButton * b;\n b = qobject_cast(getBitWidget(i));\n b->setText(QString::number(value));\n\n b = qobject_cast(ui->gridLayout->itemAt(i)->widget());\n b->setChecked(value);\n}\n\nQWidget *\nMainWindow::createName(uint i, int value)\n{\n QPushButton *b = new QPushButton(getName(i));\n b->setObjectName(QString(\"nameBtn%1\").arg(i, 2, 10, kFillChar));\n b->setCheckable(true);\n b->setFlat(true);\n b->setChecked(value);\n b->setToolTip(getNameTip(i));\n\n signalMapper->setMapping(b, i);\n connect(b, SIGNAL(clicked()), signalMapper, SLOT(map()));\n\n return b;\n}\n\nQString\nMainWindow::getName(uint i) const\n{\n return model.bitName(i) ?\n QString(model.bitName(i)) :\n QString::number(i);\n}\n\nQString\nMainWindow::getNameTip(uint i) const\n{\n return hexToString(1ULL << i);\n}\n\nQString\nMainWindow::hexToString(uint64_t v) const\n{\n return QString(\"0x%1\").arg(v, hexLength(valueWidth), 16, kFillChar);\n}\n\nvoid\nMainWindow::updateBitNames()\n{\n for (uint i = 0; i < kBitCount; i++) {\n QPushButton *b = qobject_cast(ui->gridLayout->itemAt(i)->widget());\n b->setText(getName(i));\n }\n}\n\nvoid\nMainWindow::updateSummary()\n{\n QString summary;\n uint64_t rest = 0, bit = 1ULL;\n for (uint i = 0; i < valueWidth; i++) {\n if (model[i]) {\n if (model.bitName(i)) {\n summary.append('|').append(model.bitName(i));\n } else\n rest |= bit;\n }\n bit <<= 1;\n }\n summary.prepend(hexToString(rest));\n ui->nameSummary->setText(summary);\n}\n\nvoid\nMainWindow::bitClicked(int b)\n{\n model.toggleBit(b);\n updateValueEdit();\n toggleBit(b, model[b]);\n}\n\nvoid\nMainWindow::updateValueEdit()\n{\n int pos = ui->valueEdit->cursorPosition();\n ui->valueEdit->setText(QString(\"%1\").arg(model.value(), hexLength(valueWidth), 16, kFillChar));\n if (pos < 0 || pos >= hexLength(valueWidth))\n pos = 0;\n ui->valueEdit->setCursorPosition(pos);\n updateSummary();\n}\n\nvoid\nMainWindow::updateBits()\n{\n uint64_t bit = 1UL;\n for (uint i = 0; i < valueWidth; i++) {\n toggleBit(i, !!(model.value() & bit));\n bit <<= 1;\n }\n}\n\nvoid\nMainWindow::valueChanged(QString)\n{\n if (ui->valueEdit->cursorPosition() >= hexLength(valueWidth))\n ui->valueEdit->setCursorPosition(hexLength(valueWidth)-1);\n\n bool ok = true;\n uint64_t v = ui->valueEdit->text().toULongLong(&ok, 16);\n if (!ok)\n return;\n model.setValue(v);\n updateBits();\n updateSummary();\n}\n\nvoid\nMainWindow::namesChanged(int index)\n{\n if (index >= 0 && index < (int)(sizeof(models)\/sizeof(models[0])))\n setNames(*models[index].model);\n updateSummary();\n}\n\nvoid\nMainWindow::valueWidthChanged(int index)\n{\n if (index < 0)\n return;\n setValueWidth(8 << index);\n}\n\nvoid\nMainWindow::keyPressEvent(QKeyEvent *event)\n{\n if (event->matches(QKeySequence::Paste)) {\n event->ignore();\n QClipboard *clipboard = QApplication::clipboard();\n QString originalText = clipboard->text();\n bool ok = false;\n uint64_t v = originalText.toULongLong(&ok, 16);\n if (!ok)\n v = originalText.toULongLong(&ok, 10);\n\n if (ok) {\n model.setValue(v);\n updateValueEdit();\n updateBits();\n }\n }\n else return QMainWindow::keyPressEvent(event);\n}\n<|endoftext|>"} {"text":"changed memopt SA struct<|endoftext|>"} {"text":"\/*\nUselessMine\n Copyright (C) 2013-2017 Vladimir \"allejo\" Jimenez\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n *\/\n\n#include \n#include \n#include \n\n#include \"bzfsAPI.h\"\n#include \"bztoolkit\/bzToolkitAPI.h\"\n\n\/\/ Define plugin name\nconst std::string PLUGIN_NAME = \"Useless Mine\";\n\n\/\/ Define plugin version numbering\nconst int MAJOR = 1;\nconst int MINOR = 1;\nconst int REV = 0;\nconst int BUILD = 52;\n\n\/\/ A function to replace substrings in a string with another substring\nstd::string ReplaceString(std::string subject, const std::string& search, const std::string& replace)\n{\n size_t pos = 0;\n\n while ((pos = subject.find(search, pos)) != std::string::npos)\n {\n subject.replace(pos, search.length(), replace);\n pos += replace.length();\n }\n\n return subject;\n}\n\nclass UselessMine : public bz_Plugin, public bz_CustomSlashCommandHandler\n{\npublic:\n virtual const char* Name ();\n virtual void Init (const char* config);\n virtual void Event (bz_EventData *eventData);\n virtual void Cleanup (void);\n\n virtual bool SlashCommand (int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*);\n\n \/\/ The information each mine will contain\n struct Mine\n {\n bz_ApiString uid; \/\/ A unique ID for mine\n\n int owner; \/\/ The owner of the mine\n int defuserID; \/\/ The player who defused this mine\n int detonationID; \/\/ The shot ID of the world weapon that exploded when this mine was defused\/detonated\n float x, y, z; \/\/ The coordinates of where the mine was placed\n bz_eTeamType team; \/\/ The team of the mine owner\n bool defused; \/\/ True if the mine was defused with a Bomb Defusal flag\n bool detonated; \/\/ True if the mine was detonated by a player\n double detonationTime; \/\/ The time the mine was detonated\n\n Mine (int _owner, float _pos[3], bz_eTeamType _team) :\n owner(_owner),\n defuserID(-1),\n detonationID(-1),\n x(_pos[0]),\n y(_pos[1]),\n z(_pos[2]),\n team(_team),\n defused(false),\n detonated(false),\n detonationTime(-1)\n {\n uid.format(\"%d_%d\", owner, bz_getCurrentTime());\n }\n\n \/\/ Should a given player trigger this mine?\n \/\/ This function checks mine ownership, team loyalty, and player's alive-ness\n bool canPlayerTriggerMine(bz_BasePlayerRecord *pr, float pos[3])\n {\n if (owner != pr->playerID && (pr->team == eRogueTeam || pr->team != team || bz_getGameType() == eOpenFFAGame) && pr->spawned)\n {\n float playerPos[3] = {pos[0], pos[1], pos[2]};\n double shockRange = bz_getBZDBDouble(\"_shockOutRadius\") * 0.75;\n\n \/\/ Check if the player is in the detonation range\n bool inDetonationRange = ((playerPos[0] > x - shockRange && playerPos[0] < x + shockRange) &&\n (playerPos[1] > y - shockRange && playerPos[1] < y + shockRange) &&\n (playerPos[2] > z - shockRange && playerPos[2] < z + shockRange));\n\n return inDetonationRange;\n }\n\n return false;\n }\n\n bool defuse(int playerID)\n {\n if (bztk_isValidPlayerID(owner) && bz_getPlayerTeam(owner) != eObservers)\n {\n bz_BasePlayerRecord *pr = bz_getPlayerByIndex(owner);\n\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: Mine UID %s defused\", uid.c_str());\n\n defused = true;\n defuserID = playerID;\n detonationTime = bz_getCurrentTime();\n\n bz_fireWorldWep(\"SW\", 2.0, BZ_SERVER, pr->lastKnownState.pos, 0, 0, 0, &detonationID, 0, bz_getPlayerTeam(playerID));\n\n bz_freePlayerRecord(pr);\n\n return true;\n }\n\n return false;\n }\n\n bool detonate()\n {\n \/\/ Check that the mine owner exists and is not an observer\n if (bztk_isValidPlayerID(owner) && bz_getPlayerTeam(owner) != eObservers)\n {\n float minePos[3] = {x, y, z};\n\n \/\/ Only detonate a mine once\n if (!detonated)\n {\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: Mine UID %s detonated\", uid.c_str());\n\n detonated = true;\n detonationTime = bz_getCurrentTime();\n\n bz_fireWorldWep(\"SW\", 2.0, BZ_SERVER, minePos, 0, 0, 0, &detonationID, 0, team);\n\n return true;\n }\n }\n\n return false;\n }\n };\n\nprivate:\n int getMineCount (bool offset);\n void reloadDeathMessages (),\n removePlayerMines (int playerID),\n removeMine (Mine &mine),\n setMine (int owner, float pos[3], bz_eTeamType team);\n std::string formatDeathMessage (std::string msg, std::string victim, std::string owner);\n\n std::vector deathMessages; \/\/ A vector that will store all of the witty death messages\n std::vector activeMines; \/\/ A vector that will store all of the mines currently on the field\n std::string deathMessagesFile; \/\/ The path to the file containing death messages\n\n double playerSpawnTime[256]; \/\/ The time a player spawned last; used for _mineSafetyTime calculations\n};\n\nBZ_PLUGIN(UselessMine)\n\nconst char* UselessMine::Name (void)\n{\n static std::string pluginName;\n\n if (pluginName.empty())\n pluginName = bztk_pluginName(PLUGIN_NAME, MAJOR, MINOR, REV, BUILD);\n\n return pluginName.c_str();\n}\n\nvoid UselessMine::Init (const char* commandLine)\n{\n Register(bz_eFlagGrabbedEvent);\n Register(bz_ePlayerDieEvent);\n Register(bz_ePlayerPartEvent);\n Register(bz_ePlayerSpawnEvent);\n Register(bz_ePlayerUpdateEvent);\n\n bz_registerCustomSlashCommand(\"mine\", this);\n bz_registerCustomSlashCommand(\"reload\", this);\n\n bz_RegisterCustomFlag(\"BD\", \"Bomb Defusal\", \"Safely defuse enemy mines while killing the mine owners\", 0, eGoodFlag);\n\n bztk_registerCustomDoubleBZDB(\"_mineSafetyTime\", 5.0);\n\n \/\/ Save the location of the file so we can reload after\n deathMessagesFile = commandLine;\n\n reloadDeathMessages();\n\n if (deathMessages.empty())\n {\n bz_debugMessage(2, \"WARNING :: Useless Mine :: No witty death messages were loaded\");\n }\n else\n {\n bz_debugMessagef(2, \"DEBUG :: Useless Mine :: %d witty messages were loaded\", deathMessages.size());\n }\n}\n\nvoid UselessMine::Cleanup (void)\n{\n Flush();\n\n bz_removeCustomSlashCommand(\"mine\");\n bz_removeCustomSlashCommand(\"reload\");\n}\n\nvoid UselessMine::Event (bz_EventData *eventData)\n{\n switch (eventData->eventType)\n {\n case bz_eFlagGrabbedEvent:\n {\n bz_FlagGrabbedEventData_V1* flagGrabData = (bz_FlagGrabbedEventData_V1*)eventData;\n\n \/\/ If the user grabbed the Useless flag, let them know they can place a mine\n if (strcmp(flagGrabData->flagType, \"US\") == 0)\n {\n bz_sendTextMessage(BZ_SERVER, flagGrabData->playerID, \"You grabbed a Useless flag! Type \/mine at any time to set a useless mine!\");\n }\n }\n break;\n\n case bz_ePlayerDieEvent:\n {\n bz_PlayerDieEventData_V1* dieData = (bz_PlayerDieEventData_V1*)eventData;\n\n int playerID = dieData->playerID;\n\n for (Mine &mine : activeMines)\n {\n \/\/ This isn't the mine we're looking for since it hasn't been touched\n if (!mine.detonated && !mine.defused)\n {\n continue;\n }\n\n \/\/ If the shot IDs don't match, this mine wasn't the killer\n if (dieData->shotID != mine.detonationID)\n {\n continue;\n }\n\n \/\/ Get the callsigns of the players\n const char* owner = bz_getPlayerCallsign(mine.owner);\n const char* victim = bz_getPlayerCallsign(playerID);\n\n if (mine.detonated)\n {\n dieData->killerID = mine.owner;\n\n\n if (!deathMessages.empty() && playerID != mine.owner)\n {\n \/\/ The random number used to fetch a random taunting death message\n int randomNumber = rand() % deathMessages.size();\n\n \/\/ Get a random death message\n std::string deathMessage = deathMessages.at(randomNumber);\n bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, formatDeathMessage(deathMessage, victim, owner).c_str());\n }\n }\n else if (mine.defused)\n {\n dieData->killerID = mine.defuserID;\n\n bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, \"%s successfully defused %s's mine! [%d]\", bz_getPlayerCallsign(mine.defuserID), owner, getMineCount(true));\n }\n\n removeMine(mine);\n\n break;\n }\n }\n break;\n\n case bz_ePlayerPartEvent:\n {\n bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData;\n\n int playerID = partData->playerID;\n\n \/\/ Remove all the mines belonging to the player who just left\n removePlayerMines(playerID);\n playerSpawnTime[playerID] = -1;\n }\n break;\n\n case bz_ePlayerSpawnEvent:\n {\n bz_PlayerSpawnEventData_V1* spawnData = (bz_PlayerSpawnEventData_V1*)eventData;\n\n int playerID = spawnData->playerID;\n\n \/\/ Save the time the player spawned last\n playerSpawnTime[playerID] = bz_getCurrentTime();\n }\n break;\n\n case bz_ePlayerUpdateEvent:\n {\n bz_PlayerUpdateEventData_V1* updateData = (bz_PlayerUpdateEventData_V1*)eventData;\n\n int playerID = updateData->playerID;\n bz_BasePlayerRecord *pr = bz_getPlayerByIndex(playerID);\n\n for (Mine &mine : activeMines)\n {\n bool bypassSafetyTime = (playerSpawnTime[pr->playerID] + bz_getBZDBDouble(\"_mineSafetyTime\") <= bz_getCurrentTime());\n\n if (mine.canPlayerTriggerMine(pr, updateData->state.pos) && bypassSafetyTime)\n {\n (pr->currentFlag == \"Bomb Defusal (+BD)\") ? mine.defuse(playerID) : mine.detonate();\n }\n }\n\n bz_freePlayerRecord(pr);\n }\n break;\n\n default:\n break;\n }\n}\n\nbool UselessMine::SlashCommand(int playerID, bz_ApiString command, bz_ApiString \/*message*\/, bz_APIStringList *params)\n{\n if (command == \"mine\")\n {\n bz_BasePlayerRecord *pr = bz_getPlayerByIndex(playerID);\n\n if (pr->team != eObservers)\n {\n \/\/ Check if the player has the Useless flag\n if (pr->currentFlag == \"USeless (+US)\")\n {\n \/\/ Store their current position\n float currentPosition[3] = {pr->lastKnownState.pos[0], pr->lastKnownState.pos[1], pr->lastKnownState.pos[2]};\n\n setMine(playerID, currentPosition, pr->team);\n }\n else\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"You can't place a mine without the Useless flag!\");\n }\n }\n else\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"Silly observer, you can't place a mine.\");\n }\n\n bz_freePlayerRecord(pr);\n\n return true;\n }\n else if (command == \"reload\" && bz_hasPerm(playerID, \"setAll\"))\n {\n if (params->get(0) == \"deathmessages\")\n {\n reloadDeathMessages();\n bz_sendTextMessage(BZ_SERVER, playerID, \"Death messages reloaded\");\n return true;\n }\n else if (params->size() == 0)\n {\n reloadDeathMessages();\n }\n }\n\n return false;\n}\n\n\/\/ A function to format death messages in order to replace placeholders with callsigns and values\nstd::string UselessMine::formatDeathMessage(std::string msg, std::string victim, std::string owner)\n{\n \/\/ Replace the %victim% and %owner% placeholders\n std::string formattedMessage = ReplaceString(ReplaceString(msg, \"%victim%\", victim), \"%owner%\", owner);\n\n \/\/ If the message has a %minecount%, then replace it\n if (formattedMessage.find(\"%minecount%\") != std::string::npos)\n {\n formattedMessage = ReplaceString(formattedMessage, \"%minecount%\", std::to_string(getMineCount(true)));\n }\n\n return formattedMessage;\n}\n\nvoid UselessMine::reloadDeathMessages()\n{\n deathMessages.clear();\n\n if (!deathMessagesFile.empty())\n {\n bztk_fileToVector(deathMessagesFile.c_str(), deathMessages);\n }\n}\n\n\/\/ Get the amount of active mines that exist\n\/\/ Setting `offset` to true will subtract the current detonated\/defused mine that's queued for removal\nint UselessMine::getMineCount(bool offset = false)\n{\n if (offset && activeMines.size() == 0)\n {\n return 0;\n }\n\n return (int)activeMines.size() - (offset ? 1 : 0);\n}\n\n\/\/ Remove a specific mine\nvoid UselessMine::removeMine(Mine &mine)\n{\n const char* uid = mine.uid.c_str();\n\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: Removing mine UID: %s\", mine.uid.c_str());\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: mine count: %d\", getMineCount());\n\n activeMines.erase(\n std::remove_if(\n activeMines.begin(),\n activeMines.end(),\n [uid](Mine &m) { return m.uid == uid; }\n ),\n activeMines.end()\n );\n\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: new mine count: %d\", getMineCount());\n}\n\n\/\/ Remove all of the mines of a specific player\nvoid UselessMine::removePlayerMines(int playerID)\n{\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: Removing all mines for player %d\", playerID);\n\n activeMines.erase(\n std::remove_if(\n activeMines.begin(),\n activeMines.end(),\n [playerID](Mine &m) { return m.owner == playerID; }\n ),\n activeMines.end()\n );\n}\n\n\/\/ A shortcut to set a mine\nvoid UselessMine::setMine(int owner, float pos[3], bz_eTeamType team)\n{\n \/\/ Remove their flag because they \"converted\" it into a mine\n bz_removePlayerFlag(owner);\n\n Mine newMine(owner, pos, team);\n\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: Mine UID %s created by %d\", newMine.uid.c_str(), owner);\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: x, y, z => %0.2f, %0.2f, %0.2f\", pos[0], pos[1], pos[2]);\n\n activeMines.push_back(newMine);\n}\nFix incorrect license header in source file\/*\n Copyright (C) 2013-2017 Vladimir \"allejo\" Jimenez\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the “Software”), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n*\/\n\n#include \n#include \n#include \n\n#include \"bzfsAPI.h\"\n#include \"bztoolkit\/bzToolkitAPI.h\"\n\n\/\/ Define plugin name\nconst std::string PLUGIN_NAME = \"Useless Mine\";\n\n\/\/ Define plugin version numbering\nconst int MAJOR = 1;\nconst int MINOR = 1;\nconst int REV = 0;\nconst int BUILD = 59;\n\n\/\/ A function to replace substrings in a string with another substring\nstd::string ReplaceString(std::string subject, const std::string& search, const std::string& replace)\n{\n size_t pos = 0;\n\n while ((pos = subject.find(search, pos)) != std::string::npos)\n {\n subject.replace(pos, search.length(), replace);\n pos += replace.length();\n }\n\n return subject;\n}\n\nclass UselessMine : public bz_Plugin, public bz_CustomSlashCommandHandler\n{\npublic:\n virtual const char* Name ();\n virtual void Init (const char* config);\n virtual void Event (bz_EventData *eventData);\n virtual void Cleanup (void);\n\n virtual bool SlashCommand (int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*);\n\n \/\/ The information each mine will contain\n struct Mine\n {\n bz_ApiString uid; \/\/ A unique ID for mine\n\n int owner; \/\/ The owner of the mine\n int defuserID; \/\/ The player who defused this mine\n int detonationID; \/\/ The shot ID of the world weapon that exploded when this mine was defused\/detonated\n float x, y, z; \/\/ The coordinates of where the mine was placed\n bz_eTeamType team; \/\/ The team of the mine owner\n bool defused; \/\/ True if the mine was defused with a Bomb Defusal flag\n bool detonated; \/\/ True if the mine was detonated by a player\n double detonationTime; \/\/ The time the mine was detonated\n\n Mine (int _owner, float _pos[3], bz_eTeamType _team) :\n owner(_owner),\n defuserID(-1),\n detonationID(-1),\n x(_pos[0]),\n y(_pos[1]),\n z(_pos[2]),\n team(_team),\n defused(false),\n detonated(false),\n detonationTime(-1)\n {\n uid.format(\"%d_%d\", owner, bz_getCurrentTime());\n }\n\n \/\/ Should a given player trigger this mine?\n \/\/ This function checks mine ownership, team loyalty, and player's alive-ness\n bool canPlayerTriggerMine(bz_BasePlayerRecord *pr, float pos[3])\n {\n if (owner != pr->playerID && (pr->team == eRogueTeam || pr->team != team || bz_getGameType() == eOpenFFAGame) && pr->spawned)\n {\n float playerPos[3] = {pos[0], pos[1], pos[2]};\n double shockRange = bz_getBZDBDouble(\"_shockOutRadius\") * 0.75;\n\n \/\/ Check if the player is in the detonation range\n bool inDetonationRange = ((playerPos[0] > x - shockRange && playerPos[0] < x + shockRange) &&\n (playerPos[1] > y - shockRange && playerPos[1] < y + shockRange) &&\n (playerPos[2] > z - shockRange && playerPos[2] < z + shockRange));\n\n return inDetonationRange;\n }\n\n return false;\n }\n\n bool defuse(int playerID)\n {\n if (bztk_isValidPlayerID(owner) && bz_getPlayerTeam(owner) != eObservers)\n {\n bz_BasePlayerRecord *pr = bz_getPlayerByIndex(owner);\n\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: Mine UID %s defused\", uid.c_str());\n\n defused = true;\n defuserID = playerID;\n detonationTime = bz_getCurrentTime();\n\n bz_fireWorldWep(\"SW\", 2.0, BZ_SERVER, pr->lastKnownState.pos, 0, 0, 0, &detonationID, 0, bz_getPlayerTeam(playerID));\n\n bz_freePlayerRecord(pr);\n\n return true;\n }\n\n return false;\n }\n\n bool detonate()\n {\n \/\/ Check that the mine owner exists and is not an observer\n if (bztk_isValidPlayerID(owner) && bz_getPlayerTeam(owner) != eObservers)\n {\n float minePos[3] = {x, y, z};\n\n \/\/ Only detonate a mine once\n if (!detonated)\n {\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: Mine UID %s detonated\", uid.c_str());\n\n detonated = true;\n detonationTime = bz_getCurrentTime();\n\n bz_fireWorldWep(\"SW\", 2.0, BZ_SERVER, minePos, 0, 0, 0, &detonationID, 0, team);\n\n return true;\n }\n }\n\n return false;\n }\n };\n\nprivate:\n int getMineCount (bool offset);\n void reloadDeathMessages (),\n removePlayerMines (int playerID),\n removeMine (Mine &mine),\n setMine (int owner, float pos[3], bz_eTeamType team);\n std::string formatDeathMessage (std::string msg, std::string victim, std::string owner);\n\n std::vector deathMessages; \/\/ A vector that will store all of the witty death messages\n std::vector activeMines; \/\/ A vector that will store all of the mines currently on the field\n std::string deathMessagesFile; \/\/ The path to the file containing death messages\n\n double playerSpawnTime[256]; \/\/ The time a player spawned last; used for _mineSafetyTime calculations\n};\n\nBZ_PLUGIN(UselessMine)\n\nconst char* UselessMine::Name (void)\n{\n static std::string pluginName;\n\n if (pluginName.empty())\n pluginName = bztk_pluginName(PLUGIN_NAME, MAJOR, MINOR, REV, BUILD);\n\n return pluginName.c_str();\n}\n\nvoid UselessMine::Init (const char* commandLine)\n{\n Register(bz_eFlagGrabbedEvent);\n Register(bz_ePlayerDieEvent);\n Register(bz_ePlayerPartEvent);\n Register(bz_ePlayerSpawnEvent);\n Register(bz_ePlayerUpdateEvent);\n\n bz_registerCustomSlashCommand(\"mine\", this);\n bz_registerCustomSlashCommand(\"reload\", this);\n\n bz_RegisterCustomFlag(\"BD\", \"Bomb Defusal\", \"Safely defuse enemy mines while killing the mine owners\", 0, eGoodFlag);\n\n bztk_registerCustomDoubleBZDB(\"_mineSafetyTime\", 5.0);\n\n \/\/ Save the location of the file so we can reload after\n deathMessagesFile = commandLine;\n\n reloadDeathMessages();\n\n if (deathMessages.empty())\n {\n bz_debugMessage(2, \"WARNING :: Useless Mine :: No witty death messages were loaded\");\n }\n else\n {\n bz_debugMessagef(2, \"DEBUG :: Useless Mine :: %d witty messages were loaded\", deathMessages.size());\n }\n}\n\nvoid UselessMine::Cleanup (void)\n{\n Flush();\n\n bz_removeCustomSlashCommand(\"mine\");\n bz_removeCustomSlashCommand(\"reload\");\n}\n\nvoid UselessMine::Event (bz_EventData *eventData)\n{\n switch (eventData->eventType)\n {\n case bz_eFlagGrabbedEvent:\n {\n bz_FlagGrabbedEventData_V1* flagGrabData = (bz_FlagGrabbedEventData_V1*)eventData;\n\n \/\/ If the user grabbed the Useless flag, let them know they can place a mine\n if (strcmp(flagGrabData->flagType, \"US\") == 0)\n {\n bz_sendTextMessage(BZ_SERVER, flagGrabData->playerID, \"You grabbed a Useless flag! Type \/mine at any time to set a useless mine!\");\n }\n }\n break;\n\n case bz_ePlayerDieEvent:\n {\n bz_PlayerDieEventData_V1* dieData = (bz_PlayerDieEventData_V1*)eventData;\n\n int playerID = dieData->playerID;\n\n for (Mine &mine : activeMines)\n {\n \/\/ This isn't the mine we're looking for since it hasn't been touched\n if (!mine.detonated && !mine.defused)\n {\n continue;\n }\n\n \/\/ If the shot IDs don't match, this mine wasn't the killer\n if (dieData->shotID != mine.detonationID)\n {\n continue;\n }\n\n \/\/ Get the callsigns of the players\n const char* owner = bz_getPlayerCallsign(mine.owner);\n const char* victim = bz_getPlayerCallsign(playerID);\n\n if (mine.detonated)\n {\n dieData->killerID = mine.owner;\n\n\n if (!deathMessages.empty() && playerID != mine.owner)\n {\n \/\/ The random number used to fetch a random taunting death message\n int randomNumber = rand() % deathMessages.size();\n\n \/\/ Get a random death message\n std::string deathMessage = deathMessages.at(randomNumber);\n bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, formatDeathMessage(deathMessage, victim, owner).c_str());\n }\n }\n else if (mine.defused)\n {\n dieData->killerID = mine.defuserID;\n\n bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, \"%s successfully defused %s's mine! [%d]\", bz_getPlayerCallsign(mine.defuserID), owner, getMineCount(true));\n }\n\n removeMine(mine);\n\n break;\n }\n }\n break;\n\n case bz_ePlayerPartEvent:\n {\n bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData;\n\n int playerID = partData->playerID;\n\n \/\/ Remove all the mines belonging to the player who just left\n removePlayerMines(playerID);\n playerSpawnTime[playerID] = -1;\n }\n break;\n\n case bz_ePlayerSpawnEvent:\n {\n bz_PlayerSpawnEventData_V1* spawnData = (bz_PlayerSpawnEventData_V1*)eventData;\n\n int playerID = spawnData->playerID;\n\n \/\/ Save the time the player spawned last\n playerSpawnTime[playerID] = bz_getCurrentTime();\n }\n break;\n\n case bz_ePlayerUpdateEvent:\n {\n bz_PlayerUpdateEventData_V1* updateData = (bz_PlayerUpdateEventData_V1*)eventData;\n\n int playerID = updateData->playerID;\n bz_BasePlayerRecord *pr = bz_getPlayerByIndex(playerID);\n\n for (Mine &mine : activeMines)\n {\n bool bypassSafetyTime = (playerSpawnTime[pr->playerID] + bz_getBZDBDouble(\"_mineSafetyTime\") <= bz_getCurrentTime());\n\n if (mine.canPlayerTriggerMine(pr, updateData->state.pos) && bypassSafetyTime)\n {\n (pr->currentFlag == \"Bomb Defusal (+BD)\") ? mine.defuse(playerID) : mine.detonate();\n }\n }\n\n bz_freePlayerRecord(pr);\n }\n break;\n\n default:\n break;\n }\n}\n\nbool UselessMine::SlashCommand(int playerID, bz_ApiString command, bz_ApiString \/*message*\/, bz_APIStringList *params)\n{\n if (command == \"mine\")\n {\n bz_BasePlayerRecord *pr = bz_getPlayerByIndex(playerID);\n\n if (pr->team != eObservers)\n {\n \/\/ Check if the player has the Useless flag\n if (pr->currentFlag == \"USeless (+US)\")\n {\n \/\/ Store their current position\n float currentPosition[3] = {pr->lastKnownState.pos[0], pr->lastKnownState.pos[1], pr->lastKnownState.pos[2]};\n\n setMine(playerID, currentPosition, pr->team);\n }\n else\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"You can't place a mine without the Useless flag!\");\n }\n }\n else\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"Silly observer, you can't place a mine.\");\n }\n\n bz_freePlayerRecord(pr);\n\n return true;\n }\n else if (command == \"reload\" && bz_hasPerm(playerID, \"setAll\"))\n {\n if (params->get(0) == \"deathmessages\")\n {\n reloadDeathMessages();\n bz_sendTextMessage(BZ_SERVER, playerID, \"Death messages reloaded\");\n return true;\n }\n else if (params->size() == 0)\n {\n reloadDeathMessages();\n }\n }\n\n return false;\n}\n\n\/\/ A function to format death messages in order to replace placeholders with callsigns and values\nstd::string UselessMine::formatDeathMessage(std::string msg, std::string victim, std::string owner)\n{\n \/\/ Replace the %victim% and %owner% placeholders\n std::string formattedMessage = ReplaceString(ReplaceString(msg, \"%victim%\", victim), \"%owner%\", owner);\n\n \/\/ If the message has a %minecount%, then replace it\n if (formattedMessage.find(\"%minecount%\") != std::string::npos)\n {\n formattedMessage = ReplaceString(formattedMessage, \"%minecount%\", std::to_string(getMineCount(true)));\n }\n\n return formattedMessage;\n}\n\nvoid UselessMine::reloadDeathMessages()\n{\n deathMessages.clear();\n\n if (!deathMessagesFile.empty())\n {\n bztk_fileToVector(deathMessagesFile.c_str(), deathMessages);\n }\n}\n\n\/\/ Get the amount of active mines that exist\n\/\/ Setting `offset` to true will subtract the current detonated\/defused mine that's queued for removal\nint UselessMine::getMineCount(bool offset = false)\n{\n if (offset && activeMines.size() == 0)\n {\n return 0;\n }\n\n return (int)activeMines.size() - (offset ? 1 : 0);\n}\n\n\/\/ Remove a specific mine\nvoid UselessMine::removeMine(Mine &mine)\n{\n const char* uid = mine.uid.c_str();\n\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: Removing mine UID: %s\", mine.uid.c_str());\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: mine count: %d\", getMineCount());\n\n activeMines.erase(\n std::remove_if(\n activeMines.begin(),\n activeMines.end(),\n [uid](Mine &m) { return m.uid == uid; }\n ),\n activeMines.end()\n );\n\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: new mine count: %d\", getMineCount());\n}\n\n\/\/ Remove all of the mines of a specific player\nvoid UselessMine::removePlayerMines(int playerID)\n{\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: Removing all mines for player %d\", playerID);\n\n activeMines.erase(\n std::remove_if(\n activeMines.begin(),\n activeMines.end(),\n [playerID](Mine &m) { return m.owner == playerID; }\n ),\n activeMines.end()\n );\n}\n\n\/\/ A shortcut to set a mine\nvoid UselessMine::setMine(int owner, float pos[3], bz_eTeamType team)\n{\n \/\/ Remove their flag because they \"converted\" it into a mine\n bz_removePlayerFlag(owner);\n\n Mine newMine(owner, pos, team);\n\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: Mine UID %s created by %d\", newMine.uid.c_str(), owner);\n bz_debugMessagef(4, \"DEBUG :: Useless Mine :: x, y, z => %0.2f, %0.2f, %0.2f\", pos[0], pos[1], pos[2]);\n\n activeMines.push_back(newMine);\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: volume3d.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: ihi $ $Date: 2006-11-14 13:23:34 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n\n#ifndef _VOLUME3D_HXX\n#include \"volume3d.hxx\"\n#endif\n\n#ifndef _BGFX_POLYGON_B3DPOLYGON_HXX\n#include \n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n\n\/*************************************************************************\n|*\n|* Konstruktor 1: |\n|* rPos: Zentrum oder minimale Koordinate links, unten, hinten |__\n|* (abhaengig von bPosIsCenter) \/\n|*\n\\************************************************************************\/\n\nVolume3D::Volume3D(const basegfx::B3DPoint& rPos, const basegfx::B3DPoint& r3DSize, bool bPosIsCenter)\n: basegfx::B3DRange()\n{\n if(bPosIsCenter)\n {\n expand(rPos - r3DSize \/ 2.0);\n }\n else\n {\n expand(rPos);\n }\n\n expand(getMinimum() + r3DSize);\n}\n\nVolume3D::Volume3D(const basegfx::B3DRange& rVol)\n: basegfx::B3DRange(rVol)\n{\n}\n\n\/*************************************************************************\n|*\n|* Konstruktor 2 - leeres Volumen, Werte als ungueltig markieren\n|*\n\\************************************************************************\/\n\nVolume3D::Volume3D()\n: basegfx::B3DRange()\n{\n}\n\n\/*************************************************************************\n|*\n|* Transformation des Volumens berechnen und als neues Volumen\n|* zurueckgeben\n|*\n\\************************************************************************\/\n\nVolume3D Volume3D::GetTransformVolume(const basegfx::B3DHomMatrix& rTfMatrix) const\n{\n Volume3D aTfVol;\n\n if(!isEmpty())\n {\n basegfx::B3DPoint aTfVec;\n Vol3DPointIterator aIter(*this, &rTfMatrix);\n\n while(aIter.Next(aTfVec))\n {\n aTfVol.expand(aTfVec);\n }\n }\n return aTfVol;\n}\n\n\/*************************************************************************\n|*\n|* Drahtgitter-Linien fuer das Volumen berechnen und in rPoly3D ablegen\n|*\n\\************************************************************************\/\n\nvoid Volume3D::CreateWireframe(basegfx::B3DPolygon& rPoly3D, const basegfx::B3DHomMatrix* pTf) const\n{\n if(isEmpty())\n return;\n\n basegfx::B3DVector aDiff(getRange());\n basegfx::B3DPolygon aVolPnts;\n sal_uInt32 nZeroCnt(0L);\n\n \/\/ Alle Punkte holen\n Vol3DPointIterator aIter(*this, pTf);\n basegfx::B3DPoint aTfVec;\n\n while(aIter.Next(aTfVec))\n {\n aVolPnts.append(aTfVec);\n }\n\n \/\/ 0-Ausmasse des BoundVolumes zaehlen\n if(0.0 == aDiff.getX())\n nZeroCnt++;\n if(0.0 == aDiff.getY())\n nZeroCnt++;\n if(0.0 == aDiff.getZ())\n nZeroCnt++;\n\n \/\/ Die drei Ecksegemente des Volumens mit je drei Linien ausgeben;\n \/\/ falls Koordinatenanteile 0 sind, nicht alle Segmente verwenden,\n \/\/ um das gegenseitige Ausloeschen bei XOR-Ausgabe zu verhindern\n \/\/ 4\n \/\/ | Dieses Segment immer\n \/\/ |\n \/\/ 0---1\n \/\/ \/\n \/\/ 3\n \/\/ Die Liniensegmente eines Segments werden immer in der Reihenfolge\n \/\/ X-, Y- und dann Z-Richtung ausgegeben (gilt natuerlich nur fuer\n \/\/ untransformierte Koordinaten)\n\n rPoly3D.append(aVolPnts.getB3DPoint(0));\n\n if(nZeroCnt < 3L)\n {\n \/\/ wenn keine Ausdehnung, dann nur den ersten Punkt einfuegen\n rPoly3D.append(aVolPnts.getB3DPoint(1L));\n rPoly3D.append(aVolPnts.getB3DPoint(0L));\n rPoly3D.append(aVolPnts.getB3DPoint(4L));\n rPoly3D.append(aVolPnts.getB3DPoint(0L));\n rPoly3D.append(aVolPnts.getB3DPoint(3L));\n }\n if(nZeroCnt < 2L)\n {\n if(nZeroCnt == 0L || aDiff.getX() == 0.0)\n {\n \/\/ 4\n \/\/ \/\n \/\/ 7---6\n \/\/ |\n \/\/ |\n \/\/ 3\n rPoly3D.append(aVolPnts.getB3DPoint(7L));\n rPoly3D.append(aVolPnts.getB3DPoint(6L));\n rPoly3D.append(aVolPnts.getB3DPoint(7L));\n rPoly3D.append(aVolPnts.getB3DPoint(3L));\n rPoly3D.append(aVolPnts.getB3DPoint(7L));\n rPoly3D.append(aVolPnts.getB3DPoint(4L));\n }\n if(nZeroCnt == 0L || (aDiff.getY() == 0.0))\n {\n \/\/ 6\n \/\/ | 1\n \/\/ |\/\n \/\/ 3---2\n rPoly3D.append(aVolPnts.getB3DPoint(2L));\n rPoly3D.append(aVolPnts.getB3DPoint(3L));\n rPoly3D.append(aVolPnts.getB3DPoint(2L));\n rPoly3D.append(aVolPnts.getB3DPoint(6L));\n rPoly3D.append(aVolPnts.getB3DPoint(2L));\n rPoly3D.append(aVolPnts.getB3DPoint(1L));\n }\n if(nZeroCnt == 0L || (aDiff.getZ() == 0.0))\n {\n \/\/ 4---5\n \/\/ \/|\n \/\/ 6 |\n \/\/ 1\n rPoly3D.append(aVolPnts.getB3DPoint(5L));\n rPoly3D.append(aVolPnts.getB3DPoint(4L));\n rPoly3D.append(aVolPnts.getB3DPoint(5L));\n rPoly3D.append(aVolPnts.getB3DPoint(1L));\n rPoly3D.append(aVolPnts.getB3DPoint(5L));\n rPoly3D.append(aVolPnts.getB3DPoint(6L));\n }\n }\n}\n\n\/*************************************************************************\n|*\n|* Konstruktor des Point-Iterators\n|*\n\\************************************************************************\/\n\nVol3DPointIterator::Vol3DPointIterator(const basegfx::B3DRange& rVol, const basegfx::B3DHomMatrix* pTf)\n: rVolume(rVol),\n pTransform(pTf),\n nIndex(0)\n{\n DBG_ASSERT(!rVol.isEmpty(), \"Vol3DPointIterator-Aufruf mit ungueltigem Volume3D!\");\n a3DExtent = rVolume.getMaximum() - rVolume.getMinimum();\n}\n\n\/*************************************************************************\n|*\n|* Gibt die einzelnen Punkte des (ggf. transformierten) Volumens zurueck\n|*\n|* 4---5 -> Reihenfolge der Punktausgabe (untransformiert)\n|* \/| \/|\n|* 7---6 |\n|* | 0-|-1\n|* |\/ |\/\n|* 3---2\n|*\n\\************************************************************************\/\n\nbool Vol3DPointIterator::Next(basegfx::B3DPoint& rVec)\n{\n if(nIndex > 7)\n {\n return false;\n }\n else\n {\n rVec = rVolume.getMinimum();\n\n if(nIndex >= 4)\n {\n rVec.setY(rVec.getY() + a3DExtent.getY());\n }\n\n switch(nIndex)\n {\n case 6:\n case 2: rVec.setZ(rVec.getZ() + a3DExtent.getZ());\n case 5:\n case 1: rVec.setX(rVec.getX() + a3DExtent.getX());\n break;\n case 7:\n case 3: rVec.setZ(rVec.getZ() + a3DExtent.getZ());\n break;\n }\n nIndex++;\n\n if(pTransform)\n {\n rVec *= *pTransform;\n }\n\n return true;\n }\n}\n\n\/\/ eof\nINTEGRATION: CWS vgbugs07 (1.4.256); FILE MERGED 2007\/06\/04 13:26:53 vg 1.4.256.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: volume3d.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 18:07:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n\n#ifndef _VOLUME3D_HXX\n#include \n#endif\n\n#ifndef _BGFX_POLYGON_B3DPOLYGON_HXX\n#include \n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n\n\/*************************************************************************\n|*\n|* Konstruktor 1: |\n|* rPos: Zentrum oder minimale Koordinate links, unten, hinten |__\n|* (abhaengig von bPosIsCenter) \/\n|*\n\\************************************************************************\/\n\nVolume3D::Volume3D(const basegfx::B3DPoint& rPos, const basegfx::B3DPoint& r3DSize, bool bPosIsCenter)\n: basegfx::B3DRange()\n{\n if(bPosIsCenter)\n {\n expand(rPos - r3DSize \/ 2.0);\n }\n else\n {\n expand(rPos);\n }\n\n expand(getMinimum() + r3DSize);\n}\n\nVolume3D::Volume3D(const basegfx::B3DRange& rVol)\n: basegfx::B3DRange(rVol)\n{\n}\n\n\/*************************************************************************\n|*\n|* Konstruktor 2 - leeres Volumen, Werte als ungueltig markieren\n|*\n\\************************************************************************\/\n\nVolume3D::Volume3D()\n: basegfx::B3DRange()\n{\n}\n\n\/*************************************************************************\n|*\n|* Transformation des Volumens berechnen und als neues Volumen\n|* zurueckgeben\n|*\n\\************************************************************************\/\n\nVolume3D Volume3D::GetTransformVolume(const basegfx::B3DHomMatrix& rTfMatrix) const\n{\n Volume3D aTfVol;\n\n if(!isEmpty())\n {\n basegfx::B3DPoint aTfVec;\n Vol3DPointIterator aIter(*this, &rTfMatrix);\n\n while(aIter.Next(aTfVec))\n {\n aTfVol.expand(aTfVec);\n }\n }\n return aTfVol;\n}\n\n\/*************************************************************************\n|*\n|* Drahtgitter-Linien fuer das Volumen berechnen und in rPoly3D ablegen\n|*\n\\************************************************************************\/\n\nvoid Volume3D::CreateWireframe(basegfx::B3DPolygon& rPoly3D, const basegfx::B3DHomMatrix* pTf) const\n{\n if(isEmpty())\n return;\n\n basegfx::B3DVector aDiff(getRange());\n basegfx::B3DPolygon aVolPnts;\n sal_uInt32 nZeroCnt(0L);\n\n \/\/ Alle Punkte holen\n Vol3DPointIterator aIter(*this, pTf);\n basegfx::B3DPoint aTfVec;\n\n while(aIter.Next(aTfVec))\n {\n aVolPnts.append(aTfVec);\n }\n\n \/\/ 0-Ausmasse des BoundVolumes zaehlen\n if(0.0 == aDiff.getX())\n nZeroCnt++;\n if(0.0 == aDiff.getY())\n nZeroCnt++;\n if(0.0 == aDiff.getZ())\n nZeroCnt++;\n\n \/\/ Die drei Ecksegemente des Volumens mit je drei Linien ausgeben;\n \/\/ falls Koordinatenanteile 0 sind, nicht alle Segmente verwenden,\n \/\/ um das gegenseitige Ausloeschen bei XOR-Ausgabe zu verhindern\n \/\/ 4\n \/\/ | Dieses Segment immer\n \/\/ |\n \/\/ 0---1\n \/\/ \/\n \/\/ 3\n \/\/ Die Liniensegmente eines Segments werden immer in der Reihenfolge\n \/\/ X-, Y- und dann Z-Richtung ausgegeben (gilt natuerlich nur fuer\n \/\/ untransformierte Koordinaten)\n\n rPoly3D.append(aVolPnts.getB3DPoint(0));\n\n if(nZeroCnt < 3L)\n {\n \/\/ wenn keine Ausdehnung, dann nur den ersten Punkt einfuegen\n rPoly3D.append(aVolPnts.getB3DPoint(1L));\n rPoly3D.append(aVolPnts.getB3DPoint(0L));\n rPoly3D.append(aVolPnts.getB3DPoint(4L));\n rPoly3D.append(aVolPnts.getB3DPoint(0L));\n rPoly3D.append(aVolPnts.getB3DPoint(3L));\n }\n if(nZeroCnt < 2L)\n {\n if(nZeroCnt == 0L || aDiff.getX() == 0.0)\n {\n \/\/ 4\n \/\/ \/\n \/\/ 7---6\n \/\/ |\n \/\/ |\n \/\/ 3\n rPoly3D.append(aVolPnts.getB3DPoint(7L));\n rPoly3D.append(aVolPnts.getB3DPoint(6L));\n rPoly3D.append(aVolPnts.getB3DPoint(7L));\n rPoly3D.append(aVolPnts.getB3DPoint(3L));\n rPoly3D.append(aVolPnts.getB3DPoint(7L));\n rPoly3D.append(aVolPnts.getB3DPoint(4L));\n }\n if(nZeroCnt == 0L || (aDiff.getY() == 0.0))\n {\n \/\/ 6\n \/\/ | 1\n \/\/ |\/\n \/\/ 3---2\n rPoly3D.append(aVolPnts.getB3DPoint(2L));\n rPoly3D.append(aVolPnts.getB3DPoint(3L));\n rPoly3D.append(aVolPnts.getB3DPoint(2L));\n rPoly3D.append(aVolPnts.getB3DPoint(6L));\n rPoly3D.append(aVolPnts.getB3DPoint(2L));\n rPoly3D.append(aVolPnts.getB3DPoint(1L));\n }\n if(nZeroCnt == 0L || (aDiff.getZ() == 0.0))\n {\n \/\/ 4---5\n \/\/ \/|\n \/\/ 6 |\n \/\/ 1\n rPoly3D.append(aVolPnts.getB3DPoint(5L));\n rPoly3D.append(aVolPnts.getB3DPoint(4L));\n rPoly3D.append(aVolPnts.getB3DPoint(5L));\n rPoly3D.append(aVolPnts.getB3DPoint(1L));\n rPoly3D.append(aVolPnts.getB3DPoint(5L));\n rPoly3D.append(aVolPnts.getB3DPoint(6L));\n }\n }\n}\n\n\/*************************************************************************\n|*\n|* Konstruktor des Point-Iterators\n|*\n\\************************************************************************\/\n\nVol3DPointIterator::Vol3DPointIterator(const basegfx::B3DRange& rVol, const basegfx::B3DHomMatrix* pTf)\n: rVolume(rVol),\n pTransform(pTf),\n nIndex(0)\n{\n DBG_ASSERT(!rVol.isEmpty(), \"Vol3DPointIterator-Aufruf mit ungueltigem Volume3D!\");\n a3DExtent = rVolume.getMaximum() - rVolume.getMinimum();\n}\n\n\/*************************************************************************\n|*\n|* Gibt die einzelnen Punkte des (ggf. transformierten) Volumens zurueck\n|*\n|* 4---5 -> Reihenfolge der Punktausgabe (untransformiert)\n|* \/| \/|\n|* 7---6 |\n|* | 0-|-1\n|* |\/ |\/\n|* 3---2\n|*\n\\************************************************************************\/\n\nbool Vol3DPointIterator::Next(basegfx::B3DPoint& rVec)\n{\n if(nIndex > 7)\n {\n return false;\n }\n else\n {\n rVec = rVolume.getMinimum();\n\n if(nIndex >= 4)\n {\n rVec.setY(rVec.getY() + a3DExtent.getY());\n }\n\n switch(nIndex)\n {\n case 6:\n case 2: rVec.setZ(rVec.getZ() + a3DExtent.getZ());\n case 5:\n case 1: rVec.setX(rVec.getX() + a3DExtent.getX());\n break;\n case 7:\n case 3: rVec.setZ(rVec.getZ() + a3DExtent.getZ());\n break;\n }\n nIndex++;\n\n if(pTransform)\n {\n rVec *= *pTransform;\n }\n\n return true;\n }\n}\n\n\/\/ eof\n<|endoftext|>"} {"text":"#include \"mandelbrot.hpp\"\n\n\nint iter_for_point(const std::complex &c, const int MAX_ITER) {\n \n const double abs_c = abs(c - 0.25);\n if (abs_c * 2 < 1 - (real(c) - 0.25) \/ abs_c) {\n return MAX_ITER;\n }\n \n int i = 1;\n std::complex z_i = c;\n double sqr_abs = pow(real(z_i), 2) + pow(imag(z_i), 2);\n\n while ((i < MAX_ITER) && (sqr_abs < 4)) {\n std::complex sqr = z_i * z_i;\n z_i = sqr + c;\n ++i;\n sqr_abs = pow(real(z_i), 2) + pow(imag(z_i), 2);\n }\n \n return i;\n}\n\n\ndouble norm_iter_for_point(const double Re, const double Im, const int MAX_ITER) {\n \n std::complex z(Re, Im);\n return static_cast(iter_for_point(z, MAX_ITER)) \/ MAX_ITER;\n}\n\n\nvoid painting(const double x1, const double x2,\n const double y1, const double y2,\n const int32_t width, const int32_t height,\n const char* file_name, const bool progress_bar) {\n \n cimg_library::CImg img(width, height, 1, 3);\n \n const double dy = (y2 - y1) \/ height;\n const double dx = (x2 - x1) \/ width;\n \n const size_t horiz_steps = 60;\n const size_t line_for_one_step = width \/ horiz_steps * 4 \/ 3;\n const double pr_bar_dx = (x2 - x1) \/ horiz_steps;\n \n double y = y2;\n \n for (int32_t i = 0; i < height; ++i) {\n double x = x1;\n \n if (progress_bar && ((i + 1) % line_for_one_step == 0)) {\n double pr_bar_x = x1;\n for (size_t j = 0; j < horiz_steps; ++j) {\n if (norm_iter_for_point(pr_bar_x, y) > 0.95)\n { std::cout << '#'; }\n else { std::cout << ' '; }\n pr_bar_x += pr_bar_dx;\n }\n std::cout << std::endl;\n }\n \n for (int32_t j = 0; j < width; ++j) {\n const double norm_pnt = norm_iter_for_point(x, y);\n x += dx;\n \n const double clr = pow(1 - norm_pnt, 3);\n const unsigned char color = (unsigned char)(clr * 255);\n img(j, i, 0) = color; \/\/red\n img(j, i, 1) = color; \/\/green\n img(j, i, 2) = color; \/\/blue\n \n }\n \n y -= dy;\n }\n \n img.save_png(file_name);\n}Optimization (added check circle)#include \"mandelbrot.hpp\"\n\n\nint iter_for_point(const std::complex &c, const int MAX_ITER) {\n \n const double abs_c = abs(c - 0.25);\n if (abs_c * 2 < 1 - (real(c) - 0.25) \/ abs_c) {\n return MAX_ITER;\n }\n if (real(c + 1.) * real(c + 1.) + imag(c) * imag(c) < 1\/16.) {\n return MAX_ITER;\n }\n \n int i = 1;\n std::complex z_i = c;\n double sqr_abs = pow(real(z_i), 2) + pow(imag(z_i), 2);\n\n while ((i < MAX_ITER) && (sqr_abs < 4)) {\n std::complex sqr = z_i * z_i;\n z_i = sqr + c;\n ++i;\n sqr_abs = pow(real(z_i), 2) + pow(imag(z_i), 2);\n }\n \n return i;\n}\n\n\ndouble norm_iter_for_point(const double Re, const double Im, const int MAX_ITER) {\n \n std::complex z(Re, Im);\n return static_cast(iter_for_point(z, MAX_ITER)) \/ MAX_ITER;\n}\n\n\nvoid painting(const double x1, const double x2,\n const double y1, const double y2,\n const int32_t width, const int32_t height,\n const char* file_name, const bool progress_bar) {\n \n cimg_library::CImg img(width, height, 1, 3);\n \n const double dy = (y2 - y1) \/ height;\n const double dx = (x2 - x1) \/ width;\n \n const size_t horiz_steps = 60;\n const size_t line_for_one_step = width \/ horiz_steps * 4 \/ 3;\n const double pr_bar_dx = (x2 - x1) \/ horiz_steps;\n \n double y = y2;\n \n for (int32_t i = 0; i < height; ++i) {\n double x = x1;\n \n if (progress_bar && ((i + 1) % line_for_one_step == 0)) {\n double pr_bar_x = x1;\n for (size_t j = 0; j < horiz_steps; ++j) {\n if (norm_iter_for_point(pr_bar_x, y) > 0.95)\n { std::cout << '#'; }\n else { std::cout << ' '; }\n pr_bar_x += pr_bar_dx;\n }\n std::cout << std::endl;\n }\n \n for (int32_t j = 0; j < width; ++j) {\n const double norm_pnt = norm_iter_for_point(x, y);\n x += dx;\n \n const double clr = pow(1 - norm_pnt, 3);\n const unsigned char color = (unsigned char)(clr * 255);\n img(j, i, 0) = color; \/\/red\n img(j, i, 1) = color; \/\/green\n img(j, i, 2) = color; \/\/blue\n \n }\n \n y -= dy;\n }\n \n img.save_png(file_name);\n}<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \n#include \"nvml_stub.h\"\n\ntypedef nvmlReturn_t (*nvml_void)(void);\ntypedef nvmlReturn_t (*nvml_dghbi)(unsigned int, nvmlDevice_t *);\ntypedef nvmlReturn_t (*nvml_unsigned_int)(unsigned int *);\ntypedef nvmlReturn_t (*nvml_dgs)( nvmlDevice_t, nvmlSamplingType_t, unsigned long long, nvmlValueType_t *, unsigned int *, nvmlSample_t * );\ntypedef const char * (*cc_nvml)( nvmlReturn_t );\n\nnvml_dgs nvmlDeviceGetSamples = NULL;\nnvml_unsigned_int nvmlDeviceGetCount = NULL;\nnvml_dghbi nvmlDeviceGetHandleByIndex = NULL;\ncc_nvml nvmlErrorString = NULL;\n\nunsigned debug = 0;\nunsigned reportInterval = 10;\n\nint compareSamples( const void * vpA, const void * vpB ) {\n\tconst nvmlSample_t * a = (const nvmlSample_t *)vpA;\n\tconst nvmlSample_t * b = (const nvmlSample_t *)vpB;\n\tif( a->timeStamp < b->timeStamp ) {\n\t\treturn -1;\n\t} else if( a->timeStamp == b->timeStamp ) {\n\t\treturn 0;\n\t} else {\n\t\treturn 1;\n\t}\n}\n\nvoid fail() {\n\tfprintf( stderr, \"Hanging to prevent process churn.\\n\" );\n\twhile( 1 ) { sleep( 1204 ); }\n}\n\nnvmlReturn_t getElapsedTimeForDevice( nvmlDevice_t d, unsigned long long * lastSample, unsigned long long * elapsedTime, unsigned maxSampleCount ) {\n\tif( elapsedTime == NULL || lastSample == NULL ) {\n\t\treturn NVML_ERROR_INVALID_ARGUMENT;\n\t}\n\n\tunsigned sampleCount = maxSampleCount;\n\tnvmlSample_t samples[maxSampleCount];\n\tnvmlValueType_t sampleValueType;\n\n\tnvmlReturn_t r = nvmlDeviceGetSamples( d, NVML_GPU_UTILIZATION_SAMPLES, * lastSample, & sampleValueType, & sampleCount, samples );\n\tswitch( r ) {\n\t\tcase NVML_ERROR_NOT_FOUND:\n\t\t\treturn NVML_SUCCESS;\n\t\tcase NVML_SUCCESS:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn r;\n\t}\n\n\t\/\/ Samples are usually but not always in order.\n\tqsort( samples, sampleCount, sizeof( nvmlSample_t ), compareSamples );\n\n\t\/\/ Convert the percentage to elapsed time, since that's what we\n\t\/\/ actually care about (and the data representation is simpler).\n\tif( (*lastSample) == 0 && sampleCount > 0 ) {\n\t\t(*lastSample) = samples[0].timeStamp;\n\t}\n\tfor( unsigned i = 0; i < sampleCount; ++i ) {\n\t\t\/* debug fprintf( stderr, \"%llu + (%llu - %llu) * %f = \",\n\t\t\t* elapsedTime, samples[i].timeStamp, * lastSample,\n\t\t\t(double)(samples[i].sampleValue.uiVal)\/100.0 ); *\/\n\n\t\t(*elapsedTime) += (unsigned long long)(\n\t\t\t(samples[i].timeStamp - (*lastSample)) *\n\t\t\t((double)(samples[i].sampleValue.uiVal)\/100.0)\n\t\t);\n\n\t\t\/* debug fprintf( stderr, \"%llu\\n\", * elapsedTime ); *\/\n\n\t\t(*lastSample) = samples[i].timeStamp;\n\t}\n\n\treturn NVML_SUCCESS;\n}\n\n\/\/ int main( int argc, char ** argv ) {\nint main() {\n\tnvml_void nvmlInit = NULL;\n\tnvml_void nvmlShutdown = NULL;\n\n\tvoid * nvml_handle = NULL;\n\n\tconst char * nvml_library = \"libnvidia-ml.so\";\n\tnvml_handle = dlopen( nvml_library, RTLD_LAZY );\n\tif(! nvml_handle) {\n\t\tfprintf( stderr, \"Unable to load %s, aborting.\\n\", nvml_library );\n\t\tfail();\n\t}\n\tdlerror();\n\n\tnvmlInit\t\t = (nvml_void)dlsym( nvml_handle, \"nvmlInit\" );\n\tnvmlShutdown\t = (nvml_void)dlsym( nvml_handle, \"nvmlShutdown\" );\n\tnvmlDeviceGetSamples = (nvml_dgs)dlsym( nvml_handle, \"nvmlDeviceGetSamples\" );\n\tnvmlDeviceGetCount = (nvml_unsigned_int)dlsym( nvml_handle, \"nvmlDeviceGetCount\" );\n\tnvmlDeviceGetHandleByIndex = (nvml_dghbi)dlsym( nvml_handle, \"nvmlDeviceGetHandleByIndex\" );\n\tnvmlErrorString = (cc_nvml)dlsym( nvml_handle, \"nvmlErrorString\" );\n\n\tnvmlReturn_t r = nvmlInit();\n\tif( r != NVML_SUCCESS ) {\n\t\tfprintf( stderr, \"nvmlInit() failed, aborting.\\n\" );\n\t\tfail();\n\t}\n\n\tunsigned int deviceCount;\n\tr = nvmlDeviceGetCount( &deviceCount );\n\tif( r != NVML_SUCCESS ) {\n\t\tfprintf( stderr, \"nvmlDeviceGetCount() failed, aborting.\\n\" );\n\t\tfail();\n\t}\n\tif( deviceCount <= 0 ) {\n\t\tfprintf( stderr, \"Found 0 or fewer devices, aborting.\\n\" );\n\t\tfail();\n\t}\n\n\tnvmlDevice_t devices[deviceCount];\n\tunsigned maxSampleCounts[deviceCount];\n\tunsigned long long lastSamples[deviceCount];\n\tunsigned long long firstSamples[deviceCount];\n\tunsigned long long elapsedTimes[deviceCount];\n\tfor( unsigned i = 0; i < deviceCount; ++i ) {\n\t\tr = nvmlDeviceGetHandleByIndex( i, &(devices[i]) );\n\t\tif( r != NVML_SUCCESS ) {\n\t\t\tfprintf( stderr, \"nvmlGetDeviceHandleByIndex(%u) failed (%d: %s), aborting.\\n\", i, r, nvmlErrorString( r ) );\n\t\t\tfail();\n\t\t}\n\n\t\tlastSamples[i] = 0;\n\t\tfirstSamples[i] = 0;\n\t\telapsedTimes[i] = 0;\n\n\t\tnvmlValueType_t sampleValueType;\n\t\tr = nvmlDeviceGetSamples( devices[i], NVML_GPU_UTILIZATION_SAMPLES, 0, & sampleValueType, & maxSampleCounts[i], NULL );\n\t\tif( r != NVML_SUCCESS ) {\n\t\t\tfprintf( stderr, \"nvmlDeviceGetSamples(%u) failed while querying for the max sample count (%d: %s), aborting.\\n\", i, r, nvmlErrorString( r ) );\n\t\t\tfail();\n\t\t}\n\t\tif( sampleValueType != NVML_VALUE_TYPE_UNSIGNED_INT ) {\n\t\t\tfprintf( stderr, \"nvmlDeviceGetSamples(%u) returned an unexpected type (%d) of sample when querying for the max sample count, aborting.\\n\", i, sampleValueType );\n\t\t\tfail();\n\t\t}\n\t}\n\n\t\/\/ We deliberately ignore the first set of samples. Partly, I think we\n\t\/\/ can claim that they're from before we started monitoring. More\n\t\/\/ importantly, at least on a Tesla K40c (driver 384.81), initializing\n\t\/\/ the NVML library causes a one-second 99% usage spike on an other-\n\t\/\/ wise idle GPU. So we'll ignore as much of that as we easily can.\n\tfor( unsigned i = 0; i < deviceCount; ++i ) {\n\t\tr = getElapsedTimeForDevice( devices[i], &lastSamples[i], &elapsedTimes[i], maxSampleCounts[i] );\n\t\tfirstSamples[i] = lastSamples[i];\n\t\telapsedTimes[i] = 0;\n\t}\n\n\ttime_t lastReport = time( NULL );\n\twhile( 1 ) {\n\t\tusleep( 100000 );\n\n\t\tfor( unsigned i = 0; i < deviceCount; ++i ) {\n\t\t\tr = getElapsedTimeForDevice( devices[i], &lastSamples[i], &elapsedTimes[i], maxSampleCounts[i] );\n\t\t\tif( r != NVML_SUCCESS ) {\n\t\t\t\tfprintf( stderr, \"getElapsedTimeForDevice(%u) failed (%d: %s), aborting.\\n\", i, r, nvmlErrorString( r ) );\n\t\t\t\tfail();\n\t\t\t}\n\n\t\t\tif( debug ) {\n\t\t\t\tfprintf( stdout, \"device %u: %llu \/ %llu = %u%%.\\n\",\n\t\t\t\t\ti, elapsedTimes[i], lastSamples[i] - firstSamples[i],\n\t\t\t\t\t(unsigned)(((double)elapsedTimes[i]) \/ (lastSamples[i] - firstSamples[i]) * 100)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tif( time( NULL ) - lastReport >= reportInterval ) {\n\t\t\tfor( unsigned i = 0; i < deviceCount; ++i ) {\n\t\t\t\tfprintf( stdout, \"SlotMergeConstraint = StringListMember( \\\"CUDA%u\\\", AssignedGPUs )\\n\", i );\n\t\t\t\tfprintf( stdout, \"UptimeGPUsSeconds = %.6f\\n\", elapsedTimes[i] \/ 1000000.0 );\n\t\t\t\tfprintf( stdout, \"- GPUsSlot%u\\n\", i );\n\t\t\t\tfflush( stdout );\n\n\t\t\t\t\/\/ Report only the usage for each reporting period.\n\t\t\t\telapsedTimes[i] = 0;\n\t\t\t\tfirstSamples[i] = lastSamples[i];\n\t\t\t}\n\t\t\tlastReport = time( NULL );\n\t\t}\n\t}\n\n\tr = nvmlShutdown();\n\tif( r != NVML_SUCCESS ) {\n\t\tfprintf( stderr, \"nvmlShutdown() failed (%d: %s), aborting.\\n\", r, nvmlErrorString( r ) );\n\t\treturn 1;\n\t}\n\n\tdlclose( nvml_handle );\n\treturn 0;\n}\nFix small coverity kvetches #6345#include \n#include \n#include \n#include \n#include \n\n#include \n#include \"nvml_stub.h\"\n\ntypedef nvmlReturn_t (*nvml_void)(void);\ntypedef nvmlReturn_t (*nvml_dghbi)(unsigned int, nvmlDevice_t *);\ntypedef nvmlReturn_t (*nvml_unsigned_int)(unsigned int *);\ntypedef nvmlReturn_t (*nvml_dgs)( nvmlDevice_t, nvmlSamplingType_t, unsigned long long, nvmlValueType_t *, unsigned int *, nvmlSample_t * );\ntypedef const char * (*cc_nvml)( nvmlReturn_t );\n\nnvml_dgs nvmlDeviceGetSamples = NULL;\nnvml_unsigned_int nvmlDeviceGetCount = NULL;\nnvml_dghbi nvmlDeviceGetHandleByIndex = NULL;\ncc_nvml nvmlErrorString = NULL;\n\nunsigned debug = 0;\nunsigned reportInterval = 10;\n\nint compareSamples( const void * vpA, const void * vpB ) {\n\tconst nvmlSample_t * a = (const nvmlSample_t *)vpA;\n\tconst nvmlSample_t * b = (const nvmlSample_t *)vpB;\n\tif( a->timeStamp < b->timeStamp ) {\n\t\treturn -1;\n\t} else if( a->timeStamp == b->timeStamp ) {\n\t\treturn 0;\n\t} else {\n\t\treturn 1;\n\t}\n}\n\nvoid fail() __attribute__((__noreturn__));\n\nvoid fail() {\n\tfprintf( stderr, \"Hanging to prevent process churn.\\n\" );\n\twhile( 1 ) { sleep( 1204 ); }\n}\n\nnvmlReturn_t getElapsedTimeForDevice( nvmlDevice_t d, unsigned long long * lastSample, unsigned long long * elapsedTime, unsigned maxSampleCount ) {\n\tif( elapsedTime == NULL || lastSample == NULL ) {\n\t\treturn NVML_ERROR_INVALID_ARGUMENT;\n\t}\n\n\tunsigned sampleCount = maxSampleCount;\n\tnvmlSample_t samples[maxSampleCount];\n\tnvmlValueType_t sampleValueType;\n\n\tnvmlReturn_t r = nvmlDeviceGetSamples( d, NVML_GPU_UTILIZATION_SAMPLES, * lastSample, & sampleValueType, & sampleCount, samples );\n\tswitch( r ) {\n\t\tcase NVML_ERROR_NOT_FOUND:\n\t\t\treturn NVML_SUCCESS;\n\t\tcase NVML_SUCCESS:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn r;\n\t}\n\n\t\/\/ Samples are usually but not always in order.\n\tqsort( samples, sampleCount, sizeof( nvmlSample_t ), compareSamples );\n\n\t\/\/ Convert the percentage to elapsed time, since that's what we\n\t\/\/ actually care about (and the data representation is simpler).\n\tif( (*lastSample) == 0 && sampleCount > 0 ) {\n\t\t(*lastSample) = samples[0].timeStamp;\n\t}\n\tfor( unsigned i = 0; i < sampleCount; ++i ) {\n\t\t\/* debug fprintf( stderr, \"%llu + (%llu - %llu) * %f = \",\n\t\t\t* elapsedTime, samples[i].timeStamp, * lastSample,\n\t\t\t(double)(samples[i].sampleValue.uiVal)\/100.0 ); *\/\n\n\t\t(*elapsedTime) += (unsigned long long)(\n\t\t\t(samples[i].timeStamp - (*lastSample)) *\n\t\t\t((double)(samples[i].sampleValue.uiVal)\/100.0)\n\t\t);\n\n\t\t\/* debug fprintf( stderr, \"%llu\\n\", * elapsedTime ); *\/\n\n\t\t(*lastSample) = samples[i].timeStamp;\n\t}\n\n\treturn NVML_SUCCESS;\n}\n\n\/\/ int main( int argc, char ** argv ) {\nint main() {\n\tnvml_void nvmlInit = NULL;\n\tnvml_void nvmlShutdown = NULL;\n\n\tvoid * nvml_handle = NULL;\n\n\tconst char * nvml_library = \"libnvidia-ml.so\";\n\tnvml_handle = dlopen( nvml_library, RTLD_LAZY );\n\tif(! nvml_handle) {\n\t\tfprintf( stderr, \"Unable to load %s, aborting.\\n\", nvml_library );\n\t\tfail();\n\t}\n\tdlerror();\n\n\tnvmlInit\t\t = (nvml_void)dlsym( nvml_handle, \"nvmlInit\" );\n\tnvmlShutdown\t = (nvml_void)dlsym( nvml_handle, \"nvmlShutdown\" );\n\tnvmlDeviceGetSamples = (nvml_dgs)dlsym( nvml_handle, \"nvmlDeviceGetSamples\" );\n\tnvmlDeviceGetCount = (nvml_unsigned_int)dlsym( nvml_handle, \"nvmlDeviceGetCount\" );\n\tnvmlDeviceGetHandleByIndex = (nvml_dghbi)dlsym( nvml_handle, \"nvmlDeviceGetHandleByIndex\" );\n\tnvmlErrorString = (cc_nvml)dlsym( nvml_handle, \"nvmlErrorString\" );\n\n\tnvmlReturn_t r = nvmlInit();\n\tif( r != NVML_SUCCESS ) {\n\t\tfprintf( stderr, \"nvmlInit() failed, aborting.\\n\" );\n\t\tfail();\n\t}\n\n\tunsigned int deviceCount;\n\tr = nvmlDeviceGetCount( &deviceCount );\n\tif( r != NVML_SUCCESS ) {\n\t\tfprintf( stderr, \"nvmlDeviceGetCount() failed, aborting.\\n\" );\n\t\tfail();\n\t}\n\tif( deviceCount <= 0 ) {\n\t\tfprintf( stderr, \"Found 0 or fewer devices, aborting.\\n\" );\n\t\tfail();\n\t}\n\n\tnvmlDevice_t devices[deviceCount];\n\tunsigned maxSampleCounts[deviceCount];\n\tunsigned long long lastSamples[deviceCount];\n\tunsigned long long firstSamples[deviceCount];\n\tunsigned long long elapsedTimes[deviceCount];\n\tfor( unsigned i = 0; i < deviceCount; ++i ) {\n\t\tr = nvmlDeviceGetHandleByIndex( i, &(devices[i]) );\n\t\tif( r != NVML_SUCCESS ) {\n\t\t\tfprintf( stderr, \"nvmlGetDeviceHandleByIndex(%u) failed (%d: %s), aborting.\\n\", i, r, nvmlErrorString( r ) );\n\t\t\tfail();\n\t\t}\n\n\t\tlastSamples[i] = 0;\n\t\tfirstSamples[i] = 0;\n\t\telapsedTimes[i] = 0;\n\n\t\tnvmlValueType_t sampleValueType;\n\t\tr = nvmlDeviceGetSamples( devices[i], NVML_GPU_UTILIZATION_SAMPLES, 0, & sampleValueType, & maxSampleCounts[i], NULL );\n\t\tif( r != NVML_SUCCESS ) {\n\t\t\tfprintf( stderr, \"nvmlDeviceGetSamples(%u) failed while querying for the max sample count (%d: %s), aborting.\\n\", i, r, nvmlErrorString( r ) );\n\t\t\tfail();\n\t\t}\n\t\tif( sampleValueType != NVML_VALUE_TYPE_UNSIGNED_INT ) {\n\t\t\tfprintf( stderr, \"nvmlDeviceGetSamples(%u) returned an unexpected type (%d) of sample when querying for the max sample count, aborting.\\n\", i, sampleValueType );\n\t\t\tfail();\n\t\t}\n\t}\n\n\t\/\/ We deliberately ignore the first set of samples. Partly, I think we\n\t\/\/ can claim that they're from before we started monitoring. More\n\t\/\/ importantly, at least on a Tesla K40c (driver 384.81), initializing\n\t\/\/ the NVML library causes a one-second 99% usage spike on an other-\n\t\/\/ wise idle GPU. So we'll ignore as much of that as we easily can.\n\tfor( unsigned i = 0; i < deviceCount; ++i ) {\n\t\tgetElapsedTimeForDevice( devices[i], &lastSamples[i], &elapsedTimes[i], maxSampleCounts[i] );\n\t\tfirstSamples[i] = lastSamples[i];\n\t\telapsedTimes[i] = 0;\n\t}\n\n\ttime_t lastReport = time( NULL );\n\twhile( 1 ) {\n\t\tusleep( 100000 );\n\n\t\tfor( unsigned i = 0; i < deviceCount; ++i ) {\n\t\t\tr = getElapsedTimeForDevice( devices[i], &lastSamples[i], &elapsedTimes[i], maxSampleCounts[i] );\n\t\t\tif( r != NVML_SUCCESS ) {\n\t\t\t\tfprintf( stderr, \"getElapsedTimeForDevice(%u) failed (%d: %s), aborting.\\n\", i, r, nvmlErrorString( r ) );\n\t\t\t\tfail();\n\t\t\t}\n\n\t\t\tif( debug ) {\n\t\t\t\tfprintf( stdout, \"device %u: %llu \/ %llu = %u%%.\\n\",\n\t\t\t\t\ti, elapsedTimes[i], lastSamples[i] - firstSamples[i],\n\t\t\t\t\t(unsigned)(((double)elapsedTimes[i]) \/ (lastSamples[i] - firstSamples[i]) * 100)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tif( time( NULL ) - lastReport >= reportInterval ) {\n\t\t\tfor( unsigned i = 0; i < deviceCount; ++i ) {\n\t\t\t\tfprintf( stdout, \"SlotMergeConstraint = StringListMember( \\\"CUDA%u\\\", AssignedGPUs )\\n\", i );\n\t\t\t\tfprintf( stdout, \"UptimeGPUsSeconds = %.6f\\n\", elapsedTimes[i] \/ 1000000.0 );\n\t\t\t\tfprintf( stdout, \"- GPUsSlot%u\\n\", i );\n\t\t\t\tfflush( stdout );\n\n\t\t\t\t\/\/ Report only the usage for each reporting period.\n\t\t\t\telapsedTimes[i] = 0;\n\t\t\t\tfirstSamples[i] = lastSamples[i];\n\t\t\t}\n\t\t\tlastReport = time( NULL );\n\t\t}\n\t}\n\n\tr = nvmlShutdown();\n\tif( r != NVML_SUCCESS ) {\n\t\tfprintf( stderr, \"nvmlShutdown() failed (%d: %s), aborting.\\n\", r, nvmlErrorString( r ) );\n\t\treturn 1;\n\t}\n\n\tdlclose( nvml_handle );\n\treturn 0;\n}\n<|endoftext|>"} {"text":"#include \"robot.hpp\"\n#include \"console.hpp\"\n#include \"commands.hpp\"\n#include \"logger.hpp\"\n#include \"radio.hpp\"\n\nTicker lifeLight;\nDigitalOut ledOne(LED1);\nDigitalOut ledTwo(LED2);\n\nDigitalOut led(p20, 0);\n\n\/*\n * some forward declarations to make the code easier to read\n *\/\nvoid imAlive(void);\nvoid setISRPriorities(void);\nvoid initRadioThread(void);\nvoid initConsoleRoutine(void);\n\nvoid writeByte(DigitalInOut*, char);\nchar readByte(DigitalInOut* pin);\nunsigned int crc8_add(unsigned int acc, char b);\n\nconst int tREC = 5;\nconst int tSLOT = 65;\nconst int tRSTLmin = 480;\nconst int tRSTLmax = 640;\nconst int tRSTLavg = 540;\nconst int tPDHmin = 15;\nconst int tPDHmax = 60;\nconst int tPDHavg = 35;\nconst int tPDLmin = 60;\nconst int tPDLmax = 240;\nconst int tPDLavg = 150;\nconst int tFPD = 8;\nconst int tMSPmin = 60;\nconst int tMSPmax = 75;\nconst int tMSPavg = 68;\nconst int tRSTH = 480;\nconst int tW0Lmin = 60;\nconst int tW0Lmax = 120;\nconst int tW0Lavg = 90;\nconst int tW1Lmin = 5;\nconst int tW1Lmax = 15;\nconst int tW1Lavg = 10;\nconst int tRLmin = 5;\nconst int tRLmax = 15;\nconst int tRLavg = 6;\nconst int tMSR = 15;\n\n\/**\n * system entry point\n *\/\nint main(void) \n{\n\tsetISRPriorities();\n\tlifeLight.attach(&imAlive, 0.25);\n\n\tDigitalInOut idPin(p21, PIN_OUTPUT, PullUp, 1);\n\n\tprintf(\"\\033[2J\");\n\tprintf(\"Communicating with ID Chip...\\r\\n\");\n\n\t\/\/ Reset signal, low for 480us\n\tidPin = 0;\n\twait_us(tRSTLavg); \/\/ Trstl\n\tidPin = 1;\n\n\t\/\/ wait for presence response\n\twait_us(tMSPavg); \/\/ Tmsp\n\tidPin.input();\n\tif(idPin == 0) {\n\t\twait_us(tRSTH - tMSPavg); \/\/ wait for rest of tRSTH\n\n\t\twriteByte(&idPin, 0x33);\n\n\t\tchar family = readByte(&idPin);\n\n\t\tchar serial[6];\n\t\tfor(int i = 0; i < 6; i++)\n\t\t\tserial[i] = readByte(&idPin);\n\n\t\tchar crc = readByte(&idPin);\n\n\t\tprintf(\"Family byte : 0x%x\\r\\n\", family);\n\t\t\n\t\tprintf(\"Serial byte : 0x\");\n\t\tfor(int i = 5; i >= 0; i--)\n\t\t\tprintf(\"%x\", serial[i]);\n\n\t\tprintf(\"\\r\\nCRC : 0x%x \\r\\n\", crc);\n\n\t\tunsigned int calcCRC = crc8_add(0x0, family);\n\t\tfor(int i = 0; i < 6; i++)\n\t\t\tcalcCRC = crc8_add(calcCRC, serial[i]);\n\n\t\tprintf(\"CRCs match? : %d\\r\\n\", calcCRC == crc);\n\n\t\tfor(int i = 0; i < 17; i++)\n\t\t\tprintf(\"\\n\");\n\n\t\twhile(1) {\n\t\t\tled = !led;\n\t\t\twait(1.0);\n\t\t}\n\t}\n\telse {\n\t\tprintf(\"Failure :(\\r\\n\");\n\t\twhile(1) {\n\t\t\tled = !led;\n\t\t\twait(0.5);\n\t\t}\n\t}\n\n\tisLogging = true;\n\trjLogLevel = INF2;\n\t\n\t\/\/initRadioThread();\n\tinitConsoleRoutine();\n}\n\nvoid writeOne(DigitalInOut* pin) {\n\t*pin = 0;\n\twait_us(tW1Lavg);\n\t*pin = 1;\n\twait_us(tSLOT);\n}\n\nvoid writeZero(DigitalInOut* pin) {\n\t*pin = 0;\n\twait_us(tW0Lavg);\n\t*pin = 1;\n\twait_us(tREC);\n}\n\nvoid writeByte(DigitalInOut* pin, char b) {\n\tpin->output();\n\n\tfor(uint i = 1; i < 256; i <<= 1) {\n\t\tif((b & i) == i)\n\t\t\twriteOne(pin);\n\t\telse\n\t\t\twriteZero(pin);\n\t}\n\n\tprintf(\"Sent : 0x%x\\r\\n\", b);\n}\n\nchar readByte(DigitalInOut* pin) {\n\tchar value = 0;\n\tfor(int i = 0; i < 8; i++) {\n\t\tpin->output();\n\t\t*pin = 0;\n\t\twait_us(tRLavg);\n\t\t*pin = 1;\n\n\t\twait_us(tMSR - tRLavg);\n\t\tpin->input();\n\n\t\tint bit = *pin;\n\t\tvalue |= bit << i;\n\n\t\twait_us(tSLOT - tMSR);\n\t}\n\n\treturn value;\n}\n\nunsigned int crc8_add(unsigned int acc, char byte) {\n\tacc ^= byte;\n\n\tfor(int i = 0; i < 8; i++) {\n\t\tif(acc & 1) {\n\t\t\tacc = (acc >> 1) ^ 0x8c;\n\t\t}\n\t\telse {\n\t\t\tacc >>= 1;\n\t\t}\n\t}\n\n\treturn acc;\n}\n\n\/**\n * Initializes the peripheral nested vector interrupt controller (PNVIC) with \n * appropriate values. Low values have the higest priority (with system \n * interrupts having negative priority). All maskable interrupts are\n * diabled; do not intialize any interrupt frameworks before this funtion is\n * called. PNVIC interrupt priorities are independent of thread and NVIC \n * priorities.\n * \n * The PNVIC is independent of the NVIC responsible for system NMI's. The NVIC\n * is not accissable through the library, so in this context the NVIC functions\n * refer to the PNVIC. The configuration system for PNVIC priorities is strange\n * and different from X86. If you haven't already, look over \n * doc\/ARM-Cortex-M_Interrupt-Priorities.pdf from RJ root and the online \n * documentation regarding Interrupt Priority Registers (IPRs) first. \n *\/\nvoid setISRPriorities(void)\n{\n\t\/\/set two bits for preemptive data, two bits for priority as the\n\t\/\/structure for the IPRs. Grouping is global withing the IPRs so\n\t\/\/this value should only be changed here.\n\tNVIC_SetPriorityGrouping(5);\n\tuint32_t priorityGrouping = NVIC_GetPriorityGrouping();\n\n\t\/\/set preemptive priority default to 2 (0..3)\n\t\/\/set priority default to 1 (0..3)\n\tuint32_t defaultPriority = NVIC_EncodePriority(priorityGrouping, 2, 1);\n\n\t\/\/When the kernel initialzes the PNVIC, all ISRs are set to the\n\t\/\/highest priority, making it impossible to elevate a few over\n\t\/\/the rest, so the default priority is lowered globally for the\n\t\/\/table first.\n\t\/\/\n\t\/\/Consult LPC17xx.h under IRQn_Type for PNVIC ranges, this is LPC1768 \n\t\/\/specific\n\tfor (uint32_t IRQn = TIMER0_IRQn; IRQn <= CANActivity_IRQn; IRQn++)\n\t{\n\t\t\/\/set default priority\n\t\tNVIC_SetPriority((IRQn_Type) IRQn, defaultPriority);\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ begin raise priority section \/\/\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/reestablish watchdog\n\tNVIC_SetPriority(WDT_IRQn, NVIC_EncodePriority(priorityGrouping, 0, 0));\n\n\t\/\/TODO raise radio\n\t\/\/TODO raise others after discussion\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ begin lower priotity section \/\/\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/set UART (console) interrupts to minimal priority\n\t\/\/when debugging radio and other time sensitive operations, this\n\t\/\/interrupt will need to be deferred, especially given the number of\n\t\/\/calls to printf()\n\tNVIC_SetPriority(UART0_IRQn, NVIC_EncodePriority(priorityGrouping, 3, 0));\n\tNVIC_SetPriority(UART1_IRQn, NVIC_EncodePriority(priorityGrouping, 3, 2));\n\tNVIC_SetPriority(UART2_IRQn, NVIC_EncodePriority(priorityGrouping, 3, 2));\n\tNVIC_SetPriority(UART3_IRQn, NVIC_EncodePriority(priorityGrouping, 3, 1));\n\n\t\/\/TODO lower others after discussion\n\n\t\/\/NVIC_EnableIRQ(TIMER0_IRQn);\n\t\/\/NVIC_EnableIRQ(TIMER1_IRQn);\n\t\/\/NVIC_EnableIRQ(TIMER2_IRQn);\n\t\/\/NVIC_EnableIRQ(TIMER3_IRQn);\n}\n\n\/**\n * initializes the radio communications thread\n *\/\nvoid initRadioThread(void)\n{\n\tinitRadio();\n}\n\n\/**\n * initializes the console\n *\/\nvoid initConsoleRoutine(void)\n{\n\tif (!COMPETITION_DEPLOY)\n\t{\n\t\tinitConsole();\n\n\t\tfor (;;)\n\t\t{\n\t\t\t\/\/check console communications, currently does nothing\n\t\t\t\/\/then execute any active iterative command\n\t\t\tconComCheck();\n\t\t\t\/\/execute any active iterative command\n\t\t\texecuteIterativeCommand();\n\n\t\t\t\/\/check if a system stop is requested\n\t\t\tif (isSysStopReq() == true)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/main loop heartbeat\n\t\t\twait(0.1);\n\t\t\tledTwo = !ledTwo;\n\t \t}\n\n\t\t\/\/clear light for main loop (shows its complete)\n\t\tledTwo = false;\n\t}\n\telse\n\t{\n\t\tfor (;;);\n\t}\n}\n\n\/**\n * timer interrupt based light flicker. If this stops, the code triggered\n * a fault.\n *\/\nvoid imAlive()\n{\n\tledOne = !ledOne;\n}\nEdited robot2015's cpu's main.cpp to use DS2411 driver.#include \"robot.hpp\"\n#include \"console.hpp\"\n#include \"commands.hpp\"\n#include \"logger.hpp\"\n#include \"radio.hpp\"\n#include \"ds2411.hpp\"\n\nTicker lifeLight;\nDigitalOut ledOne(LED1);\nDigitalOut ledTwo(LED2);\n\nDigitalOut led(p20, 0);\n\n\/*\n * some forward declarations to make the code easier to read\n *\/\nvoid imAlive(void);\nvoid setISRPriorities(void);\nvoid initRadioThread(void);\nvoid initConsoleRoutine(void);\n\n\/**\n * system entry point\n *\/\nint main(void) \n{\n\tsetISRPriorities();\n\tlifeLight.attach(&imAlive, 0.25);\n\n\tDigitalInOut idPin(p21, PIN_OUTPUT, PullUp, 1);\n\n\tprintf(\"\\033[2J\");\n\tprintf(\"Communicating with ID Chip...\\r\\n\");\n\n\tDS2411_ID id;\n\tDS2411_Result result = ds2411_read_id(&idPin, &id);\n\n\tfloat waitTime;\n\tif(result == HANDSHAKE_FAIL) {\n\t\tprintf(\"Handshake failure!\\r\\n\");\n\t\twaitTime = 0.5;\n\t}\n\telse {\n\t\tprintf(\"Family byte : 0x%02X\\r\\n\", id.family);\n\t\t\n\t\tprintf(\"Serial byte : 0x\");\n\t\tfor(int i = 5; i >= 0; i--)\n\t\t\tprintf(\"%02X\", id.serial[i]);\n\n\t\tprintf(\"\\r\\nCRC : 0x%02X \\r\\n\", id.crc);\n\n\t\tprintf(\"CRCs match? : %d\\r\\n\", result == CRC_MATCH);\n\n\t\tfor(int i = 0; i < 18; i++)\n\t\t\tprintf(\"\\n\");\n\n\t\twaitTime = result == CRC_MATCH ? 1.0 : 0.5;\n\t}\n\n\twhile(1) {\n\t\tled = !led;\n\t\twait(waitTime);\n\t}\n\n\tisLogging = true;\n\trjLogLevel = INF2;\n\t\n\t\/\/initRadioThread();\n\tinitConsoleRoutine();\n}\n\n\/**\n * Initializes the peripheral nested vector interrupt controller (PNVIC) with \n * appropriate values. Low values have the higest priority (with system \n * interrupts having negative priority). All maskable interrupts are\n * diabled; do not intialize any interrupt frameworks before this funtion is\n * called. PNVIC interrupt priorities are independent of thread and NVIC \n * priorities.\n * \n * The PNVIC is independent of the NVIC responsible for system NMI's. The NVIC\n * is not accissable through the library, so in this context the NVIC functions\n * refer to the PNVIC. The configuration system for PNVIC priorities is strange\n * and different from X86. If you haven't already, look over \n * doc\/ARM-Cortex-M_Interrupt-Priorities.pdf from RJ root and the online \n * documentation regarding Interrupt Priority Registers (IPRs) first. \n *\/\nvoid setISRPriorities(void)\n{\n\t\/\/set two bits for preemptive data, two bits for priority as the\n\t\/\/structure for the IPRs. Grouping is global withing the IPRs so\n\t\/\/this value should only be changed here.\n\tNVIC_SetPriorityGrouping(5);\n\tuint32_t priorityGrouping = NVIC_GetPriorityGrouping();\n\n\t\/\/set preemptive priority default to 2 (0..3)\n\t\/\/set priority default to 1 (0..3)\n\tuint32_t defaultPriority = NVIC_EncodePriority(priorityGrouping, 2, 1);\n\n\t\/\/When the kernel initialzes the PNVIC, all ISRs are set to the\n\t\/\/highest priority, making it impossible to elevate a few over\n\t\/\/the rest, so the default priority is lowered globally for the\n\t\/\/table first.\n\t\/\/\n\t\/\/Consult LPC17xx.h under IRQn_Type for PNVIC ranges, this is LPC1768 \n\t\/\/specific\n\tfor (uint32_t IRQn = TIMER0_IRQn; IRQn <= CANActivity_IRQn; IRQn++)\n\t{\n\t\t\/\/set default priority\n\t\tNVIC_SetPriority((IRQn_Type) IRQn, defaultPriority);\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ begin raise priority section \/\/\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/reestablish watchdog\n\tNVIC_SetPriority(WDT_IRQn, NVIC_EncodePriority(priorityGrouping, 0, 0));\n\n\t\/\/TODO raise radio\n\t\/\/TODO raise others after discussion\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ begin lower priotity section \/\/\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/set UART (console) interrupts to minimal priority\n\t\/\/when debugging radio and other time sensitive operations, this\n\t\/\/interrupt will need to be deferred, especially given the number of\n\t\/\/calls to printf()\n\tNVIC_SetPriority(UART0_IRQn, NVIC_EncodePriority(priorityGrouping, 3, 0));\n\tNVIC_SetPriority(UART1_IRQn, NVIC_EncodePriority(priorityGrouping, 3, 2));\n\tNVIC_SetPriority(UART2_IRQn, NVIC_EncodePriority(priorityGrouping, 3, 2));\n\tNVIC_SetPriority(UART3_IRQn, NVIC_EncodePriority(priorityGrouping, 3, 1));\n\n\t\/\/TODO lower others after discussion\n\n\t\/\/NVIC_EnableIRQ(TIMER0_IRQn);\n\t\/\/NVIC_EnableIRQ(TIMER1_IRQn);\n\t\/\/NVIC_EnableIRQ(TIMER2_IRQn);\n\t\/\/NVIC_EnableIRQ(TIMER3_IRQn);\n}\n\n\/**\n * initializes the radio communications thread\n *\/\nvoid initRadioThread(void)\n{\n\tinitRadio();\n}\n\n\/**\n * initializes the console\n *\/\nvoid initConsoleRoutine(void)\n{\n\tif (!COMPETITION_DEPLOY)\n\t{\n\t\tinitConsole();\n\n\t\tfor (;;)\n\t\t{\n\t\t\t\/\/check console communications, currently does nothing\n\t\t\t\/\/then execute any active iterative command\n\t\t\tconComCheck();\n\t\t\t\/\/execute any active iterative command\n\t\t\texecuteIterativeCommand();\n\n\t\t\t\/\/check if a system stop is requested\n\t\t\tif (isSysStopReq() == true)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/main loop heartbeat\n\t\t\twait(0.1);\n\t\t\tledTwo = !ledTwo;\n\t \t}\n\n\t\t\/\/clear light for main loop (shows its complete)\n\t\tledTwo = false;\n\t}\n\telse\n\t{\n\t\tfor (;;);\n\t}\n}\n\n\/**\n * timer interrupt based light flicker. If this stops, the code triggered\n * a fault.\n *\/\nvoid imAlive()\n{\n\tledOne = !ledOne;\n}\n<|endoftext|>"} {"text":"#include \"util\/bitmap.h\"\n#include \"gui\/widget.h\"\n#include \n#include \"globals.h\"\n#include \"util\/token.h\"\n#include \"gui\/coordinate.h\"\n\nusing namespace Gui;\n\nstatic const double S_PI = 3.14159265358979323846;\nstatic const double DEG_TO_RAD = 180.0\/S_PI;\nstatic const double RAD_TO_DEG = S_PI\/180.0;\n\nstatic void round_double (double dbl_to_round , int &rounded_num) {\n\t\trounded_num = static_cast(dbl_to_round);\n\t\tif ((dbl_to_round - static_cast(rounded_num)) >= 0.5) {rounded_num++;}\n\t}\n\t\n\/\/! min (borrowed from allegro)\nstatic inline int Min(int x, int y){ return (((x) < (y)) ? (x) : (y)); }\n\n\/\/! max (borrowed from allegro)\nstatic inline int Max(int x, int y){ return (((x) > (y)) ? (x) : (y)); }\n\n\/\/! mid (borrowed from allegro)\nstatic inline int Mid(int x,int y,int z){ return (Max((x), Min((y), (z)))); }\n\nWidget::Widget() : workArea(0)\n{\n\t\/\/ Nothing yet\n}\n\t\t\nWidget::Widget( const Widget & w ){\n\tthis->location = w.location;\n\tthis->workArea = w.workArea;\n}\n\nWidget::~Widget(){\n\tif ( workArea ){\n\t\tdelete workArea;\n\t}\n}\n\n\/\/ copy\nWidget &Widget::operator=( const Widget ©){\n\tlocation = copy.location;\n\tworkArea = copy.workArea;\n\t\n\treturn *this;\n}\n\nvoid Widget::setCoordinates(Token * token){\n if ( *token == \"position\" ){\n int x, y, width, height;\n *token >> x >> y >> width >> height;\n AbsolutePoint pos(x, y);\n AbsolutePoint dimensions(x + width, y + height);\n location.setPosition(pos);\n location.setDimensions(dimensions);\n } else if ( *token == \"relative-position\" ){\n double x1, y1, x2, y2;\n *token >> x1 >> y1 >> x2 >> y2;\n RelativePoint pos(x1,y1);\n RelativePoint dimensions(x2,y2);\n location = Coordinate(pos, dimensions);\n } else if ( *token == \"coordinate\" ){\n Token * tok;\n *token >> tok;\n while (tok->hasTokens()){\n Token * coordToken;\n *tok >> coordToken;\n if (*coordToken == \"absolute\"){\n int x, y, width, height;\n *coordToken >> x >> y >> width >> height;\n AbsolutePoint pos(x, y);\n AbsolutePoint dimensions(x + width, y + height);\n location = Coordinate(pos, dimensions);\n } else if (*coordToken == \"relative\"){\n double x1, y1, x2, y2;\n *coordToken >> x1 >> y1 >> x2 >> y2;\n RelativePoint pos(x1,y1);\n RelativePoint dimensions(x2,y2);\n location = Coordinate(pos, dimensions); \n } else if (*coordToken == \"radius\"){\n double radius;\n *coordToken >> radius;\n location.setRadius(radius);\n } else if (*coordToken == \"z\"){\n double z;\n *coordToken >> z;\n location.setZ(z);\n }\n }\n }\n}\n\nvoid Widget::setColors(Token * token){\n if ( *token == \"position-body\" ) {\n \/\/ This handles the body color of the widget\n int r,g,b;\n *token >> r >> g >> b >> colors.bodyAlpha;\n colors.body = Bitmap::makeColor(r,g,b);\n } else if ( *token == \"position-border\" ) {\n \/\/ This handles the border color of the widget\n int r,g,b;\n *token >> r >> g >> b >> colors.borderAlpha;\n colors.border = Bitmap::makeColor(r,g,b);\n } \n}\n\nvoid Widget::arc( const Bitmap & work, int x, int y, double startAngle, int radius, int color )\n{\n\tint q = 0;\/\/ for counters\n\tdouble d_q = 0.0;\/\/ for percentage of loop completed\n\tdouble d_q_plus_one = 0.0;\n\t\n\tconst double d_angular_length_deg = 0.030;\n\tconst double d_start_angle_rad = startAngle*DEG_TO_RAD;\n\tconst double d_angular_length_rad = d_angular_length_deg*DEG_TO_RAD;\n\tconst double d_arc_distance_between_points = 0.25*pow(2.0 , static_cast(10) \/ 10.0);\n\tdouble d_angular_length_rad_per_segment = 0.0;\n\n\tdouble arc_length = radius*d_angular_length_rad;\n\tif (arc_length < 0.0) {arc_length *= -1.0;}\n\tconst double d_num_segments = arc_length \/ d_arc_distance_between_points;\n\n\tint num_segments = 0;\n\tround_double(d_num_segments , num_segments);\n\n\tif (num_segments == 0) {num_segments += 1;} \/\/ need at least one segment (two points)\n\tconst int num_points = num_segments + 1;\n\tconst double d_num_points_minus_one = static_cast(num_points - 1);\n\n\tint arc_point_x;\/\/[num_points];\n\tint arc_point_y;\/\/[num_points];\n\tint arc_point2_x;\/\/[num_points];\n\tint arc_point2_y;\/\/[num_points];\n\tdouble d_arc_point_x = 0.0;\n\tdouble d_arc_point_y = 0.0;\n\tdouble d_arc_point2_x = 0.0;\n\tdouble d_arc_point2_y = 0.0;\n\n\tdouble current_angle_rad = 0.0;\n\tdouble current_angle2_rad = 0.0;\n\n\tif (d_arc_distance_between_points <= 1.0) {\n\t\tfor (q = 0 ; q < num_points ; q++) {\n\t\t\td_q = static_cast(q);\n\t\t\tcurrent_angle_rad = d_start_angle_rad + (d_q \/ d_num_points_minus_one)*d_angular_length_rad;\n\t\t\td_arc_point_x = x + radius*cos(current_angle_rad);\n\t\t\td_arc_point_y = y + radius*sin(current_angle_rad);\n\n\t\t\tround_double(d_arc_point_x , arc_point_x);\n\t\t\tround_double(d_arc_point_y , arc_point_y);\n\n\t\t\twork.putPixel(arc_point_x,arc_point_y,color);\n\t\t}\n\t}\n\tif (d_arc_distance_between_points > 1.0) {\n\n\t\td_angular_length_rad_per_segment = d_angular_length_rad \/ d_num_points_minus_one;\n\t\tfor (q = 0 ; q < num_segments ; q++) {\n\t\t\td_q = static_cast(q);\n\t\t\td_q_plus_one = static_cast(q + 1);\n\n\t\t\tcurrent_angle_rad = d_start_angle_rad + d_q*d_angular_length_rad_per_segment;\n\t\t\tcurrent_angle2_rad = d_start_angle_rad + d_q_plus_one*d_angular_length_rad_per_segment;\n\n\t\t\td_arc_point_x = x + radius*cos(current_angle_rad);\n\t\t\td_arc_point_y = y + radius*sin(current_angle_rad);\n\n\t\t\tround_double(d_arc_point_x , arc_point_x);\n\t\t\tround_double(d_arc_point_y , arc_point_y);\n\n\t\t\td_arc_point2_x = x + radius*cos(current_angle2_rad);\n\t\t\td_arc_point2_y = y + radius*sin(current_angle2_rad);\n\n\t\t\tround_double(d_arc_point2_x , arc_point2_x);\n\t\t\tround_double(d_arc_point2_y , arc_point2_y);\n\n\t\t\twork.line(arc_point_x,arc_point_y, arc_point2_x, arc_point2_y,color);\n\t\t}\n\t}\n}\n\nvoid Widget::roundRect( const Bitmap & work, int radius, int x1, int y1, int x2, int y2, int color )\n{\n\t\n\tconst int width = x2 - x1;\n\tconst int height = y2 - y1;\n\tradius = Mid(0, radius, Min((x1+width - x1)\/2, (y1+height - y1)\/2));\n\twork.line(x1+radius, y1, x1+width-radius, y1, color);\n\twork.line(x1+radius, y1+height, x1+width-radius,y1+height, color);\n\twork.line(x1, y1+radius,x1, y1+height-radius, color);\n\twork.line(x1+width, y1+radius,x1+width, y1+height-radius, color);\n\tarc(work, x1+radius, y1+radius, S_PI-1.115, radius, color);\n\tarc(work, x1+radius + (width - radius *2), y1+radius, -S_PI\/2 +0.116, radius, color);\n\tarc(work, x1+width-radius, y1+height-radius, -0.110, radius ,color);\n\tarc(work, x1+radius, y1+height-radius, S_PI\/2-0.119, radius, color);\n\n}\n\nvoid Widget::roundRectFill( const Bitmap & work, int radius, int x1, int y1, int x2, int y2, int color )\n{\n\tconst int width = x2 - x1;\n\tconst int height = y2 - y1;\n\tradius = Mid(0, radius, Min((x1+width - x1)\/2, (y1+height - y1)\/2));\n\twork.circleFill(x1+radius, y1+radius, radius, color);\n\twork.circleFill((x1+width)-radius, y1+radius, radius, color);\n\twork.circleFill(x1+radius, (y1+height)-radius, radius, color);\n\twork.circleFill((x1+width)-radius, (y1+height)-radius, radius, color);\n\twork.rectangleFill( x1+radius, y1, x2-radius, y1+radius, color);\n\twork.rectangleFill( x1, y1+radius, x2, y2-radius, color);\n\twork.rectangleFill( x1+radius, y2-radius, x2-radius, y2, color);\n}\n\nvoid Widget::checkWorkArea()\n{\n \n if ( ! workArea ){\n\t\tworkArea = new Bitmap(location.getWidth(),location.getHeight());\n\t} else if(location.getWidth() < workArea->getWidth() || location.getHeight() < workArea->getHeight()) {\n\t\tdelete workArea;\n\t\tworkArea = new Bitmap(location.getWidth(), location.getHeight());\n\t} else if(location.getWidth() > workArea->getWidth() || location.getHeight() > workArea->getHeight()) {\n\t\tdelete workArea;\n\t\tworkArea = new Bitmap(location.getWidth(),location.getHeight());\n\t}\n\tif ( workArea ){\n\t\tworkArea->fill(Bitmap::makeColor(255,0,255));\n\t}\n}\nFix parsing of coordinate token.#include \"util\/bitmap.h\"\n#include \"gui\/widget.h\"\n#include \n#include \"globals.h\"\n#include \"util\/token.h\"\n#include \"gui\/coordinate.h\"\n\nusing namespace Gui;\n\nstatic const double S_PI = 3.14159265358979323846;\nstatic const double DEG_TO_RAD = 180.0\/S_PI;\nstatic const double RAD_TO_DEG = S_PI\/180.0;\n\nstatic void round_double (double dbl_to_round , int &rounded_num) {\n\t\trounded_num = static_cast(dbl_to_round);\n\t\tif ((dbl_to_round - static_cast(rounded_num)) >= 0.5) {rounded_num++;}\n\t}\n\t\n\/\/! min (borrowed from allegro)\nstatic inline int Min(int x, int y){ return (((x) < (y)) ? (x) : (y)); }\n\n\/\/! max (borrowed from allegro)\nstatic inline int Max(int x, int y){ return (((x) > (y)) ? (x) : (y)); }\n\n\/\/! mid (borrowed from allegro)\nstatic inline int Mid(int x,int y,int z){ return (Max((x), Min((y), (z)))); }\n\nWidget::Widget() : workArea(0)\n{\n\t\/\/ Nothing yet\n}\n\t\t\nWidget::Widget( const Widget & w ){\n\tthis->location = w.location;\n\tthis->workArea = w.workArea;\n}\n\nWidget::~Widget(){\n\tif ( workArea ){\n\t\tdelete workArea;\n\t}\n}\n\n\/\/ copy\nWidget &Widget::operator=( const Widget ©){\n\tlocation = copy.location;\n\tworkArea = copy.workArea;\n\t\n\treturn *this;\n}\n\nvoid Widget::setCoordinates(Token * token){\n if ( *token == \"position\" ){\n int x, y, width, height;\n *token >> x >> y >> width >> height;\n AbsolutePoint pos(x, y);\n AbsolutePoint dimensions(x + width, y + height);\n location.setPosition(pos);\n location.setDimensions(dimensions);\n } else if ( *token == \"relative-position\" ){\n double x1, y1, x2, y2;\n *token >> x1 >> y1 >> x2 >> y2;\n RelativePoint pos(x1,y1);\n RelativePoint dimensions(x2,y2);\n location = Coordinate(pos, dimensions);\n } else if ( *token == \"coordinate\" ){\n while (token->hasTokens()){\n Token * coordToken;\n *token >> coordToken;\n if (*coordToken == \"absolute\"){\n int x, y, width, height;\n *coordToken >> x >> y >> width >> height;\n AbsolutePoint pos(x, y);\n AbsolutePoint dimensions(x + width, y + height);\n location = Coordinate(pos, dimensions);\n } else if (*coordToken == \"relative\"){\n double x1, y1, x2, y2;\n *coordToken >> x1 >> y1 >> x2 >> y2;\n RelativePoint pos(x1,y1);\n RelativePoint dimensions(x2,y2);\n location = Coordinate(pos, dimensions); \n } else if (*coordToken == \"radius\"){\n double radius;\n *coordToken >> radius;\n location.setRadius(radius);\n } else if (*coordToken == \"z\"){\n double z;\n *coordToken >> z;\n location.setZ(z);\n }\n }\n }\n}\n\nvoid Widget::setColors(Token * token){\n if ( *token == \"position-body\" ) {\n \/\/ This handles the body color of the widget\n int r,g,b;\n *token >> r >> g >> b >> colors.bodyAlpha;\n colors.body = Bitmap::makeColor(r,g,b);\n } else if ( *token == \"position-border\" ) {\n \/\/ This handles the border color of the widget\n int r,g,b;\n *token >> r >> g >> b >> colors.borderAlpha;\n colors.border = Bitmap::makeColor(r,g,b);\n } \n}\n\nvoid Widget::arc( const Bitmap & work, int x, int y, double startAngle, int radius, int color )\n{\n\tint q = 0;\/\/ for counters\n\tdouble d_q = 0.0;\/\/ for percentage of loop completed\n\tdouble d_q_plus_one = 0.0;\n\t\n\tconst double d_angular_length_deg = 0.030;\n\tconst double d_start_angle_rad = startAngle*DEG_TO_RAD;\n\tconst double d_angular_length_rad = d_angular_length_deg*DEG_TO_RAD;\n\tconst double d_arc_distance_between_points = 0.25*pow(2.0 , static_cast(10) \/ 10.0);\n\tdouble d_angular_length_rad_per_segment = 0.0;\n\n\tdouble arc_length = radius*d_angular_length_rad;\n\tif (arc_length < 0.0) {arc_length *= -1.0;}\n\tconst double d_num_segments = arc_length \/ d_arc_distance_between_points;\n\n\tint num_segments = 0;\n\tround_double(d_num_segments , num_segments);\n\n\tif (num_segments == 0) {num_segments += 1;} \/\/ need at least one segment (two points)\n\tconst int num_points = num_segments + 1;\n\tconst double d_num_points_minus_one = static_cast(num_points - 1);\n\n\tint arc_point_x;\/\/[num_points];\n\tint arc_point_y;\/\/[num_points];\n\tint arc_point2_x;\/\/[num_points];\n\tint arc_point2_y;\/\/[num_points];\n\tdouble d_arc_point_x = 0.0;\n\tdouble d_arc_point_y = 0.0;\n\tdouble d_arc_point2_x = 0.0;\n\tdouble d_arc_point2_y = 0.0;\n\n\tdouble current_angle_rad = 0.0;\n\tdouble current_angle2_rad = 0.0;\n\n\tif (d_arc_distance_between_points <= 1.0) {\n\t\tfor (q = 0 ; q < num_points ; q++) {\n\t\t\td_q = static_cast(q);\n\t\t\tcurrent_angle_rad = d_start_angle_rad + (d_q \/ d_num_points_minus_one)*d_angular_length_rad;\n\t\t\td_arc_point_x = x + radius*cos(current_angle_rad);\n\t\t\td_arc_point_y = y + radius*sin(current_angle_rad);\n\n\t\t\tround_double(d_arc_point_x , arc_point_x);\n\t\t\tround_double(d_arc_point_y , arc_point_y);\n\n\t\t\twork.putPixel(arc_point_x,arc_point_y,color);\n\t\t}\n\t}\n\tif (d_arc_distance_between_points > 1.0) {\n\n\t\td_angular_length_rad_per_segment = d_angular_length_rad \/ d_num_points_minus_one;\n\t\tfor (q = 0 ; q < num_segments ; q++) {\n\t\t\td_q = static_cast(q);\n\t\t\td_q_plus_one = static_cast(q + 1);\n\n\t\t\tcurrent_angle_rad = d_start_angle_rad + d_q*d_angular_length_rad_per_segment;\n\t\t\tcurrent_angle2_rad = d_start_angle_rad + d_q_plus_one*d_angular_length_rad_per_segment;\n\n\t\t\td_arc_point_x = x + radius*cos(current_angle_rad);\n\t\t\td_arc_point_y = y + radius*sin(current_angle_rad);\n\n\t\t\tround_double(d_arc_point_x , arc_point_x);\n\t\t\tround_double(d_arc_point_y , arc_point_y);\n\n\t\t\td_arc_point2_x = x + radius*cos(current_angle2_rad);\n\t\t\td_arc_point2_y = y + radius*sin(current_angle2_rad);\n\n\t\t\tround_double(d_arc_point2_x , arc_point2_x);\n\t\t\tround_double(d_arc_point2_y , arc_point2_y);\n\n\t\t\twork.line(arc_point_x,arc_point_y, arc_point2_x, arc_point2_y,color);\n\t\t}\n\t}\n}\n\nvoid Widget::roundRect( const Bitmap & work, int radius, int x1, int y1, int x2, int y2, int color )\n{\n\t\n\tconst int width = x2 - x1;\n\tconst int height = y2 - y1;\n\tradius = Mid(0, radius, Min((x1+width - x1)\/2, (y1+height - y1)\/2));\n\twork.line(x1+radius, y1, x1+width-radius, y1, color);\n\twork.line(x1+radius, y1+height, x1+width-radius,y1+height, color);\n\twork.line(x1, y1+radius,x1, y1+height-radius, color);\n\twork.line(x1+width, y1+radius,x1+width, y1+height-radius, color);\n\tarc(work, x1+radius, y1+radius, S_PI-1.115, radius, color);\n\tarc(work, x1+radius + (width - radius *2), y1+radius, -S_PI\/2 +0.116, radius, color);\n\tarc(work, x1+width-radius, y1+height-radius, -0.110, radius ,color);\n\tarc(work, x1+radius, y1+height-radius, S_PI\/2-0.119, radius, color);\n\n}\n\nvoid Widget::roundRectFill( const Bitmap & work, int radius, int x1, int y1, int x2, int y2, int color )\n{\n\tconst int width = x2 - x1;\n\tconst int height = y2 - y1;\n\tradius = Mid(0, radius, Min((x1+width - x1)\/2, (y1+height - y1)\/2));\n\twork.circleFill(x1+radius, y1+radius, radius, color);\n\twork.circleFill((x1+width)-radius, y1+radius, radius, color);\n\twork.circleFill(x1+radius, (y1+height)-radius, radius, color);\n\twork.circleFill((x1+width)-radius, (y1+height)-radius, radius, color);\n\twork.rectangleFill( x1+radius, y1, x2-radius, y1+radius, color);\n\twork.rectangleFill( x1, y1+radius, x2, y2-radius, color);\n\twork.rectangleFill( x1+radius, y2-radius, x2-radius, y2, color);\n}\n\nvoid Widget::checkWorkArea()\n{\n \n if ( ! workArea ){\n\t\tworkArea = new Bitmap(location.getWidth(),location.getHeight());\n\t} else if(location.getWidth() < workArea->getWidth() || location.getHeight() < workArea->getHeight()) {\n\t\tdelete workArea;\n\t\tworkArea = new Bitmap(location.getWidth(), location.getHeight());\n\t} else if(location.getWidth() > workArea->getWidth() || location.getHeight() > workArea->getHeight()) {\n\t\tdelete workArea;\n\t\tworkArea = new Bitmap(location.getWidth(),location.getHeight());\n\t}\n\tif ( workArea ){\n\t\tworkArea->fill(Bitmap::makeColor(255,0,255));\n\t}\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: zoomctrl.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 00:20:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SHL_HXX \/\/autogen\n#include \n#endif\n#ifndef _STATUS_HXX \/\/autogen\n#include \n#endif\n#ifndef _MENU_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXDISPATCH_HXX \/\/autogen\n#include \n#endif\n#include \n#pragma hdrstop\n\n#include \"dialogs.hrc\"\n\n#include \"zoomctrl.hxx\"\n\/\/CHINA001 #include \"zoom.hxx\"\n#include \"zoomitem.hxx\"\n#include \"stbctrls.h\"\n#include \"dialmgr.hxx\"\n\nSFX_IMPL_STATUSBAR_CONTROL(SvxZoomStatusBarControl,SvxZoomItem);\n\n\/\/ class ZoomPopup_Impl --------------------------------------------------\n\nclass ZoomPopup_Impl : public PopupMenu\n{\npublic:\n ZoomPopup_Impl( USHORT nZ, USHORT nValueSet );\n\n USHORT GetZoom() const { return nZoom; }\n USHORT GetCurId() const { return nCurId; }\n\nprivate:\n USHORT nZoom;\n USHORT nCurId;\n\n virtual void Select();\n};\n\n\/\/ -----------------------------------------------------------------------\n\nZoomPopup_Impl::ZoomPopup_Impl( USHORT nZ, USHORT nValueSet )\n\n: PopupMenu( ResId( RID_SVXMNU_ZOOM, DIALOG_MGR() ) ),\n\n nZoom( nZ )\n{\n static USHORT aTable[] =\n {\n SVX_ZOOM_ENABLE_50, ZOOM_50,\n SVX_ZOOM_ENABLE_100, ZOOM_100,\n SVX_ZOOM_ENABLE_150, ZOOM_150,\n SVX_ZOOM_ENABLE_200, ZOOM_200,\n SVX_ZOOM_ENABLE_OPTIMAL, ZOOM_OPTIMAL,\n SVX_ZOOM_ENABLE_WHOLEPAGE, ZOOM_WHOLE_PAGE,\n SVX_ZOOM_ENABLE_PAGEWIDTH, ZOOM_PAGE_WIDTH\n };\n\n for ( USHORT nPos = 0; nPos < sizeof(aTable) \/ sizeof(USHORT); nPos += 2 )\n if ( ( aTable[nPos] != ( aTable[nPos] & nValueSet ) ) )\n EnableItem( aTable[nPos+1], FALSE );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ZoomPopup_Impl::Select()\n{\n nCurId = GetCurItemId();\n\n switch ( nCurId )\n {\n case ZOOM_200: nZoom = 200; break;\n case ZOOM_150: nZoom = 150; break;\n case ZOOM_100: nZoom = 100; break;\n case ZOOM_75: nZoom = 75; break;\n case ZOOM_50: nZoom = 50; break;\n\n case ZOOM_OPTIMAL:\n case ZOOM_PAGE_WIDTH:\n case ZOOM_WHOLE_PAGE: nZoom = 0; break;\n\n }\n}\n\n\/\/ class SvxZoomStatusBarControl ------------------------------------------\n\nSvxZoomStatusBarControl::SvxZoomStatusBarControl( USHORT nSlotId,\n USHORT nId,\n StatusBar& rStb ) :\n\n SfxStatusBarControl( nSlotId, nId, rStb ),\n nZoom( 100 ),\n nValueSet( SVX_ZOOM_ENABLE_ALL )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SvxZoomStatusBarControl::StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState )\n{\n if( SFX_ITEM_AVAILABLE != eState )\n {\n GetStatusBar().SetItemText( GetId(), String() );\n nValueSet = 0;\n }\n else if ( pState->ISA( SfxUInt16Item) )\n {\n const SfxUInt16Item* pItem = (const SfxUInt16Item*)pState;\n nZoom = pItem->GetValue();\n String aStr( String::CreateFromInt32(nZoom) );\n aStr += '%';\n GetStatusBar().SetItemText( GetId(), aStr );\n\n if ( pState->ISA(SvxZoomItem) )\n {\n nValueSet = ((const SvxZoomItem*)pState)->GetValueSet();\n SvxZoomType eType = ((const SvxZoomItem*)pState)->GetType();\n\n\/*!!!\n switch ( eType )\n {\n case SVX_ZOOM_OPTIMAL:\n GetStatusBar().SetItemText( GetId(), \"Opt.\" );\n break;\n case SVX_ZOOM_WHOLEPAGE:\n GetStatusBar().SetItemText( GetId(), \"Page\" );\n break;\n case SVX_ZOOM_PAGEWIDTH:\n GetStatusBar().SetItemText( GetId(), \"Width\" );\n break;\n }\n*\/\n }\n else\n {\n DBG_WARNING( \"use SfxZoomItem for SID_ATTR_ZOOM\" );\n nValueSet = SVX_ZOOM_ENABLE_ALL;\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SvxZoomStatusBarControl::Paint( const UserDrawEvent& rUsrEvt )\n{\n String aStr( String::CreateFromInt32( nZoom ));\n aStr += '%';\n GetStatusBar().SetItemText( GetId(), aStr );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SvxZoomStatusBarControl::Command( const CommandEvent& rCEvt )\n{\n if ( COMMAND_CONTEXTMENU & rCEvt.GetCommand() && 0 != nValueSet )\n {\n CaptureMouse();\n ZoomPopup_Impl aPop( nZoom, nValueSet );\n StatusBar& rStatusbar = GetStatusBar();\n\n if ( aPop.Execute( &rStatusbar, rCEvt.GetMousePosPixel() ) && ( nZoom != aPop.GetZoom() || !nZoom ) )\n {\n nZoom = aPop.GetZoom();\n SvxZoomItem aZoom( SVX_ZOOM_PERCENT, nZoom, GetId() );\n\n USHORT nId = aPop.GetCurId();\n\n if ( ZOOM_OPTIMAL == nId )\n aZoom.SetType( SVX_ZOOM_OPTIMAL );\n else if ( ZOOM_PAGE_WIDTH == nId )\n aZoom.SetType( SVX_ZOOM_PAGEWIDTH );\n else if ( ZOOM_WHOLE_PAGE == nId )\n aZoom.SetType( SVX_ZOOM_WHOLEPAGE );\n\n ::com::sun::star::uno::Any a;\n INetURLObject aObj( m_aCommandURL );\n\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs( 1 );\n aArgs[0].Name = aObj.GetURLPath();\n aZoom.QueryValue( a );\n aArgs[0].Value = a;\n\n execute( aArgs );\n }\n ReleaseMouse();\n }\n else\n SfxStatusBarControl::Command( rCEvt );\n}\n\nULONG SvxZoomStatusBarControl::GetDefItemWidth(const StatusBar& rStb)\n{\n long nWidth1 = rStb.GetTextWidth(String::CreateFromAscii(\"XXXXX%\"));\n return nWidth1;\n}\n\n\nINTEGRATION: CWS warnings01 (1.5.220); FILE MERGED 2006\/04\/20 14:50:01 cl 1.5.220.1: warning free code changes\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: zoomctrl.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 16:32:52 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SHL_HXX \/\/autogen\n#include \n#endif\n#ifndef _STATUS_HXX \/\/autogen\n#include \n#endif\n#ifndef _MENU_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXDISPATCH_HXX \/\/autogen\n#include \n#endif\n#include \n\n#include \"dialogs.hrc\"\n\n#include \"zoomctrl.hxx\"\n\/\/CHINA001 #include \"zoom.hxx\"\n#include \"zoomitem.hxx\"\n#include \"stbctrls.h\"\n#include \"dialmgr.hxx\"\n\nSFX_IMPL_STATUSBAR_CONTROL(SvxZoomStatusBarControl,SvxZoomItem);\n\n\/\/ class ZoomPopup_Impl --------------------------------------------------\n\nclass ZoomPopup_Impl : public PopupMenu\n{\npublic:\n ZoomPopup_Impl( USHORT nZ, USHORT nValueSet );\n\n USHORT GetZoom() const { return nZoom; }\n USHORT GetCurId() const { return nCurId; }\n\nprivate:\n USHORT nZoom;\n USHORT nCurId;\n\n virtual void Select();\n};\n\n\/\/ -----------------------------------------------------------------------\n\nZoomPopup_Impl::ZoomPopup_Impl( USHORT nZ, USHORT nValueSet )\n\n: PopupMenu( ResId( RID_SVXMNU_ZOOM, DIALOG_MGR() ) ),\n\n nZoom( nZ )\n{\n static USHORT aTable[] =\n {\n SVX_ZOOM_ENABLE_50, ZOOM_50,\n SVX_ZOOM_ENABLE_100, ZOOM_100,\n SVX_ZOOM_ENABLE_150, ZOOM_150,\n SVX_ZOOM_ENABLE_200, ZOOM_200,\n SVX_ZOOM_ENABLE_OPTIMAL, ZOOM_OPTIMAL,\n SVX_ZOOM_ENABLE_WHOLEPAGE, ZOOM_WHOLE_PAGE,\n SVX_ZOOM_ENABLE_PAGEWIDTH, ZOOM_PAGE_WIDTH\n };\n\n for ( USHORT nPos = 0; nPos < sizeof(aTable) \/ sizeof(USHORT); nPos += 2 )\n if ( ( aTable[nPos] != ( aTable[nPos] & nValueSet ) ) )\n EnableItem( aTable[nPos+1], FALSE );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ZoomPopup_Impl::Select()\n{\n nCurId = GetCurItemId();\n\n switch ( nCurId )\n {\n case ZOOM_200: nZoom = 200; break;\n case ZOOM_150: nZoom = 150; break;\n case ZOOM_100: nZoom = 100; break;\n case ZOOM_75: nZoom = 75; break;\n case ZOOM_50: nZoom = 50; break;\n\n case ZOOM_OPTIMAL:\n case ZOOM_PAGE_WIDTH:\n case ZOOM_WHOLE_PAGE: nZoom = 0; break;\n\n }\n}\n\n\/\/ class SvxZoomStatusBarControl ------------------------------------------\n\nSvxZoomStatusBarControl::SvxZoomStatusBarControl( USHORT nSlotId,\n USHORT nId,\n StatusBar& rStb ) :\n\n SfxStatusBarControl( nSlotId, nId, rStb ),\n nZoom( 100 ),\n nValueSet( SVX_ZOOM_ENABLE_ALL )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SvxZoomStatusBarControl::StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState )\n{\n if( SFX_ITEM_AVAILABLE != eState )\n {\n GetStatusBar().SetItemText( GetId(), String() );\n nValueSet = 0;\n }\n else if ( pState->ISA( SfxUInt16Item) )\n {\n const SfxUInt16Item* pItem = (const SfxUInt16Item*)pState;\n nZoom = pItem->GetValue();\n String aStr( String::CreateFromInt32(nZoom) );\n aStr += '%';\n GetStatusBar().SetItemText( GetId(), aStr );\n\n if ( pState->ISA(SvxZoomItem) )\n {\n nValueSet = ((const SvxZoomItem*)pState)->GetValueSet();\n SvxZoomType eType = ((const SvxZoomItem*)pState)->GetType();\n\n\/*!!!\n switch ( eType )\n {\n case SVX_ZOOM_OPTIMAL:\n GetStatusBar().SetItemText( GetId(), \"Opt.\" );\n break;\n case SVX_ZOOM_WHOLEPAGE:\n GetStatusBar().SetItemText( GetId(), \"Page\" );\n break;\n case SVX_ZOOM_PAGEWIDTH:\n GetStatusBar().SetItemText( GetId(), \"Width\" );\n break;\n }\n*\/\n }\n else\n {\n DBG_WARNING( \"use SfxZoomItem for SID_ATTR_ZOOM\" );\n nValueSet = SVX_ZOOM_ENABLE_ALL;\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SvxZoomStatusBarControl::Paint( const UserDrawEvent& rUsrEvt )\n{\n String aStr( String::CreateFromInt32( nZoom ));\n aStr += '%';\n GetStatusBar().SetItemText( GetId(), aStr );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SvxZoomStatusBarControl::Command( const CommandEvent& rCEvt )\n{\n if ( COMMAND_CONTEXTMENU & rCEvt.GetCommand() && 0 != nValueSet )\n {\n CaptureMouse();\n ZoomPopup_Impl aPop( nZoom, nValueSet );\n StatusBar& rStatusbar = GetStatusBar();\n\n if ( aPop.Execute( &rStatusbar, rCEvt.GetMousePosPixel() ) && ( nZoom != aPop.GetZoom() || !nZoom ) )\n {\n nZoom = aPop.GetZoom();\n SvxZoomItem aZoom( SVX_ZOOM_PERCENT, nZoom, GetId() );\n\n USHORT nId = aPop.GetCurId();\n\n if ( ZOOM_OPTIMAL == nId )\n aZoom.SetType( SVX_ZOOM_OPTIMAL );\n else if ( ZOOM_PAGE_WIDTH == nId )\n aZoom.SetType( SVX_ZOOM_PAGEWIDTH );\n else if ( ZOOM_WHOLE_PAGE == nId )\n aZoom.SetType( SVX_ZOOM_WHOLEPAGE );\n\n ::com::sun::star::uno::Any a;\n INetURLObject aObj( m_aCommandURL );\n\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs( 1 );\n aArgs[0].Name = aObj.GetURLPath();\n aZoom.QueryValue( a );\n aArgs[0].Value = a;\n\n execute( aArgs );\n }\n ReleaseMouse();\n }\n else\n SfxStatusBarControl::Command( rCEvt );\n}\n\nULONG SvxZoomStatusBarControl::GetDefItemWidth(const StatusBar& rStb)\n{\n long nWidth1 = rStb.GetTextWidth(String::CreateFromAscii(\"XXXXX%\"));\n return nWidth1;\n}\n\n\n<|endoftext|>"} {"text":"\/*\n * wlan Ljubljana firmware flasher\n *\/\n#include \"gui\/wizard.h\"\n\nFlashWizard::FlashWizard()\n : QWizard()\n{\n resize(640, 480);\n \n \/\/ Initialize the plan\n m_plan.append(\"init\");\n m_currentStep = m_plan.begin();\n \n \/\/ Connect signals\n connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(slotStepChanged(int)));\n}\n\nvoid FlashWizard::addPage(Step *page)\n{\n int pageId = QWizard::addPage(page);\n m_steps[page->getId()] = pageId;\n \n \/\/ Ensure that we start with init\n if (page->getId() == \"init\")\n setStartId(pageId);\n}\n\nint FlashWizard::nextId() const\n{\n if (m_currentStep + 1 == m_plan.end())\n return -1;\n \n return m_steps[*(m_currentStep + 1)];\n}\n\nPlan *FlashWizard::getPlan() const\n{\n return const_cast(&m_plan);\n}\n\nvoid FlashWizard::slotStepChanged(int id)\n{\n if (id == m_steps[\"init\"]) {\n \/\/ Wizard started\n m_currentStep = m_plan.begin();\n } else if (id == -1) {\n \/\/ TODO Wizard aborted\n } else if (id == m_steps[*(m_currentStep + 1)]) {\n \/\/ We have moved forward\n m_currentStep++;\n } else if (id == m_steps[*(m_currentStep - 1)]) {\n \/\/ We have moved backward\n m_currentStep--;\n }\n}\n\nStep::Step(const QString &id)\n : QWizardPage(),\n m_id(id)\n{\n}\n\nStep::~Step()\n{\n}\n\nQString Step::getId() const\n{\n return m_id;\n}\n\nFlashWizard *Step::flashWizard() const\n{\n return static_cast(QWizardPage::wizard());\n}\n\nPlan *Step::plan() const\n{\n return flashWizard()->getPlan();\n}\n\nDetect duplicate step identifiers and abort.\/*\n * wlan Ljubljana firmware flasher\n *\/\n#include \"gui\/wizard.h\"\n\nFlashWizard::FlashWizard()\n : QWizard()\n{\n resize(640, 480);\n \n \/\/ Initialize the plan\n m_plan.append(\"init\");\n m_currentStep = m_plan.begin();\n \n \/\/ Connect signals\n connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(slotStepChanged(int)));\n}\n\nvoid FlashWizard::addPage(Step *page)\n{\n if (m_steps.contains(page->getId()))\n qFatal(\"Attempted registration of step with duplicate identifier '%s'!\", page->getId().toAscii().data());\n \n int pageId = QWizard::addPage(page);\n m_steps[page->getId()] = pageId;\n \n \/\/ Ensure that we start with init\n if (page->getId() == \"init\")\n setStartId(pageId);\n}\n\nint FlashWizard::nextId() const\n{\n if (m_currentStep + 1 == m_plan.end())\n return -1;\n \n return m_steps[*(m_currentStep + 1)];\n}\n\nPlan *FlashWizard::getPlan() const\n{\n return const_cast(&m_plan);\n}\n\nvoid FlashWizard::slotStepChanged(int id)\n{\n if (id == m_steps[\"init\"]) {\n \/\/ Wizard started\n m_currentStep = m_plan.begin();\n } else if (id == -1) {\n \/\/ TODO Wizard aborted\n } else if (id == m_steps[*(m_currentStep + 1)]) {\n \/\/ We have moved forward\n m_currentStep++;\n } else if (id == m_steps[*(m_currentStep - 1)]) {\n \/\/ We have moved backward\n m_currentStep--;\n }\n}\n\nStep::Step(const QString &id)\n : QWizardPage(),\n m_id(id)\n{\n}\n\nStep::~Step()\n{\n}\n\nQString Step::getId() const\n{\n return m_id;\n}\n\nFlashWizard *Step::flashWizard() const\n{\n return static_cast(QWizardPage::wizard());\n}\n\nPlan *Step::plan() const\n{\n return flashWizard()->getPlan();\n}\n\n<|endoftext|>"} {"text":"#include \"CentralWidget.hpp\"\n#include \n#include \n\nCentralWidget::CentralWidget(QWidget* parent):\n QWidget(parent){\n \/\/sub dialogs\n addEnvdlg = new AddNewEnvDialog();\n changeDataDialog = new ChangeEnvDataDialog();\n\n connect(changeDataDialog,SIGNAL(changedData()),this,SLOT(update()));\n connect(addEnvdlg,SIGNAL(OKButtonIsPushed(AddNewEnvDialog_d*)),this,SLOT(AddNewEnvDialogIsSet(AddNewEnvDialog_d*)));\n connect(addEnvdlg,SIGNAL(CancelButtonIsPushed()),this,SLOT(setVisibleTrue()));\n currentEnvLabel = new QLabel(\"Current Environment \");\n currentEnvView = new QLineEdit();\n currentEnvView->setReadOnly(true);\n currentEnvView->setFrame(true);\n\n this->initEnvironments();\n this->initInformationViewer();\n this->initComboBox(this->mcenvs);\n this->initButtons();\n this->setupUI();\n this->update();\n}\n\nvoid CentralWidget::update(){\n MCEnv* cenv = mcenvs->getCurrentEnv();\n if(cenv == NULL){\n std::cerr<<\"MCSwitch can't load current env.\"<open();\n currentEnvView->setText(cenv->getName());\n QString c = selectEnvBox->currentText();\n int i = -1;\n selectEnvBox->clear();\n for(int n = 0;n < mcenvs->getNumberOfEnvironments();n++){\n selectEnvBox->addItem(mcenvs->getMCEnv(n)->getName());\n if(mcenvs->getMCEnv(n)->getName() == c){\n i = n;\n }\n }\n if(i != -1){\n selectEnvBox->setCurrentIndex(i);\n }\n}\n\nvoid CentralWidget::initEnvironments(){\n mcenvs = new Environments();\n}\n\nvoid CentralWidget::initButtons(){\n OKButton = new QPushButton(\"OK\");\n connect(OKButton,SIGNAL(clicked()),this,SLOT(OKButtonPushed()));\n\tAddButton = new QPushButton(\"Add\");\n connect(AddButton,SIGNAL(clicked()),this,SLOT(addNewEnvironment()));\n ChangeDataButton = new QPushButton(\"Change Data\");\n connect(ChangeDataButton,SIGNAL(clicked()),this,SLOT(callChangeEnvDataDialog()));\n ExitButton = new QPushButton(\"QUIT\");\n connect(ExitButton,SIGNAL(clicked()),this,SLOT(ExitButtonPushed()));\n}\n\nvoid CentralWidget::initComboBox(Environments* e_obj){\n selectEnvBox = new QComboBox();\n connect(selectEnvBox,SIGNAL(currentIndexChanged(const QString&)),this,SLOT(selectEnvBoxChanged(const QString&)));\n\tMCEnv* e = mcenvs->getCurrentEnv();\n\te->open();\n\tint b = 0;\n for(int i = 0;i < e_obj->getNumberOfEnvironments();i++){\n selectEnvBox->addItem(e_obj->getMCEnv(i)->getName());\n\t\tif(e_obj->getMCEnv(i)->getName() == e->getName()){\n\t\t\tb = i;\n\t\t}\n }\n\tdelete e;\n\tselectEnvBox->setCurrentIndex(b);\n}\n\nvoid CentralWidget::initInformationViewer(){\n this->mViewer = new QLabel(\"\");\n\n this->commentViewer = new QTextEdit();\n this->commentViewer->setReadOnly(true);\n\n this->versionViewer = new QLabel(\"VERSION \");\n}\n\nvoid CentralWidget::setupUI(){\n QHBoxLayout* currentEnvLayout = new QHBoxLayout();\n currentEnvLayout->addWidget(currentEnvLabel);\n currentEnvLayout->addWidget(currentEnvView);\n QHBoxLayout* buttonLayout = new QHBoxLayout();\n buttonLayout->addWidget(OKButton);\n buttonLayout->addWidget(ExitButton);\n\n\tQHBoxLayout* comboBoxLayout = new QHBoxLayout();\n\tcomboBoxLayout->addWidget(selectEnvBox);\n\tcomboBoxLayout->addWidget(AddButton);\n\n QVBoxLayout* mainLayout = new QVBoxLayout();\n mainLayout->addLayout(comboBoxLayout);\n mainLayout->addWidget(ChangeDataButton);\n mainLayout->addWidget(versionViewer);\n mainLayout->addWidget(mViewer);\n mainLayout->addWidget(commentViewer);\n mainLayout->addLayout(currentEnvLayout);\n mainLayout->addLayout(buttonLayout);\n\n setLayout(mainLayout);\n}\n\nvoid CentralWidget::AddNewEnvDialogIsSet(AddNewEnvDialog_d* data){\n Environments::createNewEnvironemnt(data->env_name,data->version,data->comment,data->mod);\n mcenvs->updateEnvData();\n if(data->copyFrom != COPYFROM_SELECT_NOTHING){\n if(!mcenvs->copyEnvContents(data->copyFrom,data->env_name)){\n QMessageBox::critical(this, \"ERROR\", \"Failed to copy environment's contents.\");\n }\n }\n emit requestToVisible();\n this->update();\n}\n\nvoid CentralWidget::ExitButtonPushed(){\n \/\/If you want to excuse something before exit,you should write it here.\n emit exitSignal();\n}\n\nvoid CentralWidget::OKButtonPushed(){\n \/\/When OKButton is pushed,this is called.\n if(!mcenvs->changeEnv(selectEnvBox->itemText(selectEnvBox->currentIndex()))){\n std::cerr<<\"fail to change environment\\n\";\n }\n this->update();\n}\n\nvoid CentralWidget::selectEnvBoxChanged(const QString& env_name){\n for(int n = 0;n < mcenvs->getNumberOfEnvironments();n++){\n if(mcenvs->getMCEnv(n)->getName() == env_name){\n MCEnv *e = mcenvs->getMCEnv(n);\n if(e->getMods())\n this->mViewer->setText(\"Mods are being installed to this environment.\");\n else\n this->mViewer->setText(\"Mods are not being installed to this environment.\");\n this->commentViewer->setPlainText(e->getComment());\/\/set commnet viewer's text.\n this->versionViewer->setText(\"VERSION \" + e->getVersion());\/\/set version info.\n }\n }\n}\n\n\/\/When AddButton is clicked,this is called.\nvoid CentralWidget::addNewEnvironment(){\n addEnvdlg->show();\n emit requestToInvisible();\n}\n\nvoid CentralWidget::callChangeEnvDataDialog(){\n MCEnv *env;\n for(int n = 0;n < mcenvs->getNumberOfEnvironments();n++){\n if(mcenvs->getMCEnv(n)->getName() == selectEnvBox->itemText(selectEnvBox->currentIndex())){\n env = mcenvs->getMCEnv(n);\n break;\n }\n }\n changeDataDialog->setTarget(env);\n changeDataDialog->setupDialog();\n changeDataDialog->show();\n}\n\n\nいくつかのエラーメッセージをQMessageBoxで表示するようにしてみた#include \"CentralWidget.hpp\"\n#include \n#include \n\nCentralWidget::CentralWidget(QWidget* parent):\n QWidget(parent){\n \/\/sub dialogs\n addEnvdlg = new AddNewEnvDialog();\n changeDataDialog = new ChangeEnvDataDialog();\n\n connect(changeDataDialog,SIGNAL(changedData()),this,SLOT(update()));\n connect(addEnvdlg,SIGNAL(OKButtonIsPushed(AddNewEnvDialog_d*)),this,SLOT(AddNewEnvDialogIsSet(AddNewEnvDialog_d*)));\n connect(addEnvdlg,SIGNAL(CancelButtonIsPushed()),this,SLOT(setVisibleTrue()));\n currentEnvLabel = new QLabel(\"Current Environment \");\n currentEnvView = new QLineEdit();\n currentEnvView->setReadOnly(true);\n currentEnvView->setFrame(true);\n\n this->initEnvironments();\n this->initInformationViewer();\n this->initComboBox(this->mcenvs);\n this->initButtons();\n this->setupUI();\n this->update();\n}\n\nvoid CentralWidget::update(){\n MCEnv* cenv = mcenvs->getCurrentEnv();\n if(cenv == NULL){\n QMessageBox::critical(this, \"ERROR\", \"MCSwitch cannot load currnet environment.\");\n exit(1);\n }\n cenv->open();\n currentEnvView->setText(cenv->getName());\n QString c = selectEnvBox->currentText();\n int i = -1;\n selectEnvBox->clear();\n for(int n = 0;n < mcenvs->getNumberOfEnvironments();n++){\n selectEnvBox->addItem(mcenvs->getMCEnv(n)->getName());\n if(mcenvs->getMCEnv(n)->getName() == c){\n i = n;\n }\n }\n if(i != -1){\n selectEnvBox->setCurrentIndex(i);\n }\n}\n\nvoid CentralWidget::initEnvironments(){\n mcenvs = new Environments();\n}\n\nvoid CentralWidget::initButtons(){\n OKButton = new QPushButton(\"OK\");\n connect(OKButton,SIGNAL(clicked()),this,SLOT(OKButtonPushed()));\n\tAddButton = new QPushButton(\"Add\");\n connect(AddButton,SIGNAL(clicked()),this,SLOT(addNewEnvironment()));\n ChangeDataButton = new QPushButton(\"Change Data\");\n connect(ChangeDataButton,SIGNAL(clicked()),this,SLOT(callChangeEnvDataDialog()));\n ExitButton = new QPushButton(\"QUIT\");\n connect(ExitButton,SIGNAL(clicked()),this,SLOT(ExitButtonPushed()));\n}\n\nvoid CentralWidget::initComboBox(Environments* e_obj){\n selectEnvBox = new QComboBox();\n connect(selectEnvBox,SIGNAL(currentIndexChanged(const QString&)),this,SLOT(selectEnvBoxChanged(const QString&)));\n\tMCEnv* e = mcenvs->getCurrentEnv();\n\te->open();\n\tint b = 0;\n for(int i = 0;i < e_obj->getNumberOfEnvironments();i++){\n selectEnvBox->addItem(e_obj->getMCEnv(i)->getName());\n\t\tif(e_obj->getMCEnv(i)->getName() == e->getName()){\n\t\t\tb = i;\n\t\t}\n }\n\tdelete e;\n\tselectEnvBox->setCurrentIndex(b);\n}\n\nvoid CentralWidget::initInformationViewer(){\n this->mViewer = new QLabel(\"\");\n\n this->commentViewer = new QTextEdit();\n this->commentViewer->setReadOnly(true);\n\n this->versionViewer = new QLabel(\"VERSION \");\n}\n\nvoid CentralWidget::setupUI(){\n QHBoxLayout* currentEnvLayout = new QHBoxLayout();\n currentEnvLayout->addWidget(currentEnvLabel);\n currentEnvLayout->addWidget(currentEnvView);\n QHBoxLayout* buttonLayout = new QHBoxLayout();\n buttonLayout->addWidget(OKButton);\n buttonLayout->addWidget(ExitButton);\n\n\tQHBoxLayout* comboBoxLayout = new QHBoxLayout();\n\tcomboBoxLayout->addWidget(selectEnvBox);\n\tcomboBoxLayout->addWidget(AddButton);\n\n QVBoxLayout* mainLayout = new QVBoxLayout();\n mainLayout->addLayout(comboBoxLayout);\n mainLayout->addWidget(ChangeDataButton);\n mainLayout->addWidget(versionViewer);\n mainLayout->addWidget(mViewer);\n mainLayout->addWidget(commentViewer);\n mainLayout->addLayout(currentEnvLayout);\n mainLayout->addLayout(buttonLayout);\n\n setLayout(mainLayout);\n}\n\nvoid CentralWidget::AddNewEnvDialogIsSet(AddNewEnvDialog_d* data){\n Environments::createNewEnvironemnt(data->env_name,data->version,data->comment,data->mod);\n mcenvs->updateEnvData();\n if(data->copyFrom != COPYFROM_SELECT_NOTHING){\n if(!mcenvs->copyEnvContents(data->copyFrom,data->env_name)){\n QMessageBox::critical(this, \"ERROR\", \"Failed to copy environment's contents.\");\n }\n }\n emit requestToVisible();\n this->update();\n}\n\nvoid CentralWidget::ExitButtonPushed(){\n \/\/If you want to excuse something before exit,you should write it here.\n emit exitSignal();\n}\n\nvoid CentralWidget::OKButtonPushed(){\n \/\/When OKButton is pushed,this is called.\n if(!mcenvs->changeEnv(selectEnvBox->itemText(selectEnvBox->currentIndex()))){\n QMessageBox::critical(this, \"ERROR\", \"Failed to change environment.\");\n }\n this->update();\n}\n\nvoid CentralWidget::selectEnvBoxChanged(const QString& env_name){\n for(int n = 0;n < mcenvs->getNumberOfEnvironments();n++){\n if(mcenvs->getMCEnv(n)->getName() == env_name){\n MCEnv *e = mcenvs->getMCEnv(n);\n if(e->getMods())\n this->mViewer->setText(\"Mods are being installed to this environment.\");\n else\n this->mViewer->setText(\"Mods are not being installed to this environment.\");\n this->commentViewer->setPlainText(e->getComment());\/\/set commnet viewer's text.\n this->versionViewer->setText(\"VERSION \" + e->getVersion());\/\/set version info.\n }\n }\n}\n\n\/\/When AddButton is clicked,this is called.\nvoid CentralWidget::addNewEnvironment(){\n addEnvdlg->show();\n emit requestToInvisible();\n}\n\nvoid CentralWidget::callChangeEnvDataDialog(){\n MCEnv *env;\n for(int n = 0;n < mcenvs->getNumberOfEnvironments();n++){\n if(mcenvs->getMCEnv(n)->getName() == selectEnvBox->itemText(selectEnvBox->currentIndex())){\n env = mcenvs->getMCEnv(n);\n break;\n }\n }\n changeDataDialog->setTarget(env);\n changeDataDialog->setupDialog();\n changeDataDialog->show();\n}\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: lboxctrl.cxx,v $\n *\n * $Revision: 1.20 $\n *\n * last change: $Author: obo $ $Date: 2004-07-06 13:19:31 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef _TOOLS_DEBUG_HXX\n#include \n#endif\n#ifndef _SV_LSTBOX_HXX\n#include \n#endif\n#ifndef _SV_TOOLBOX_HXX\n#include \n#endif\n#ifndef _SV_EVENT_HXX\n#include \n#endif\n#ifndef _SFXAPP_HXX\n#include \n#endif\n#ifndef _SFXTBXCTRL_HXX\n#include \n#endif\n#ifndef _SFX_BINDINGS_HXX\n#include \n#endif\n#ifndef _SFXDISPATCH_HXX\n#include \n#endif\n#ifndef _SFXVIEWSH_HXX\n#include \n#endif\n#ifndef _SV_GEN_HXX\n#include \n#endif\n#ifndef _SFXINTITEM_HXX\n#include \n#endif\n#ifndef _SFXENUMITEM_HXX\n#include \n#endif\n#ifndef _STDCTRL_HXX\n#include \n#endif\n#ifndef _SFXSLSTITM_HXX\n#include \n#endif\n#ifndef _SFXSTRITEM_HXX\n#include \n#endif\n\n#ifndef _SVX_DIALMGR_HXX\n#include \n#endif\n#ifndef _SVX_LBOXCTRL_HXX_\n#include \n#endif\n#ifndef _VCL_MNEMONIC_HXX_\n#include \n#endif\n#include \n\n#include \n#include \n\n#include \"lboxctrl.hrc\"\n\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::frame;\n\nclass SvxPopupWindowListBox;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass SvxPopupWindowListBox : public SfxPopupWindow\n{\n FixedInfo aInfo;\n ListBox * pListBox;\n ToolBox & rToolBox;\n BOOL bUserSel;\n USHORT nTbxId;\n rtl::OUString maCommandURL;\n \/\/ disallow copy-constructor and assignment-operator\n\n SvxPopupWindowListBox(const int& );\n SvxPopupWindowListBox & operator = (const int& );\n\n\/\/ SvxPopupWindowListBox( USHORT nSlotId, ToolBox& rTbx, USHORT nTbxItemId );\n\npublic:\n SvxPopupWindowListBox( USHORT nSlotId, const rtl::OUString& rCommandURL, USHORT nTbxId, ToolBox& rTbx );\n virtual ~SvxPopupWindowListBox();\n\n \/\/ SfxPopupWindow\n virtual SfxPopupWindow * Clone() const;\n virtual void PopupModeEnd();\n virtual void StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState );\n\n void StartSelection();\n inline ListBox & GetListBox() { return *pListBox; }\n inline FixedInfo & GetInfo() { return aInfo; }\n\n BOOL IsUserSelected() const { return bUserSel; }\n void SetUserSelected( BOOL bVal ) { bUserSel = bVal; }\n \/*virtual*\/Window* GetPreferredKeyInputWindow();\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSvxPopupWindowListBox::SvxPopupWindowListBox( USHORT nSlotId, const rtl::OUString& rCommandURL, USHORT nId, ToolBox& rTbx ) :\n SfxPopupWindow( nSlotId, Reference< XFrame >(), SVX_RES( RID_SVXTBX_UNDO_REDO_CTRL ) ),\n aInfo ( this, ResId( FT_NUM_OPERATIONS ) ),\n rToolBox ( rTbx ),\n bUserSel ( FALSE ),\n nTbxId ( nId ),\n maCommandURL( rCommandURL )\n{\n DBG_ASSERT( nSlotId == GetId(), \"id mismatch\" );\n pListBox = new ListBox( this, SVX_RES( LB_SVXTBX_UNDO_REDO_CTRL ) );\n FreeResource();\n pListBox->EnableMultiSelection( TRUE, TRUE );\n SetBackground( GetSettings().GetStyleSettings().GetDialogColor() );\n AddStatusListener( rCommandURL );\n}\n\n\nSvxPopupWindowListBox::~SvxPopupWindowListBox()\n{\n delete pListBox;\n}\n\n\nSfxPopupWindow* SvxPopupWindowListBox::Clone() const\n{\n return new SvxPopupWindowListBox( GetId(), maCommandURL, nTbxId, rToolBox );\n}\n\n\nvoid SvxPopupWindowListBox::PopupModeEnd()\n{\n rToolBox.EndSelection();\n SfxPopupWindow::PopupModeEnd();\n \/\/FloatingWindow::PopupModeEnd();\n\n Window* pShellWnd = SfxViewShell::Current()->GetWindow();\n if (pShellWnd)\n pShellWnd->GrabFocus();\n}\n\n\nvoid SvxPopupWindowListBox::StateChanged(\n USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )\n{\n rToolBox.EnableItem( nTbxId, ( SfxToolBoxControl::GetItemState( pState ) != SFX_ITEM_DISABLED) );\n SfxPopupWindow::StateChanged( nSID, eState, pState );\n}\n\n\nvoid SvxPopupWindowListBox::StartSelection()\n{\n rToolBox.StartSelection();\n}\n\nWindow* SvxPopupWindowListBox::GetPreferredKeyInputWindow()\n{\n \/\/ allows forwarding key events in the correct window\n \/\/ without setting the focus\n return pListBox->GetPreferredKeyInputWindow();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSFX_IMPL_TOOLBOX_CONTROL( SvxListBoxControl, SfxStringItem );\n\n\nSvxListBoxControl::SvxListBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx )\n :SfxToolBoxControl( nSlotId, nId, rTbx ),\n pPopupWin ( 0 )\n{\n rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );\n rTbx.Invalidate();\n}\n\n\nSvxListBoxControl::~SvxListBoxControl()\n{\n}\n\n\nSfxPopupWindow* SvxListBoxControl::CreatePopupWindow()\n{\n DBG_ERROR( \"not implemented\" );\n return 0;\n}\n\n\nSfxPopupWindowType SvxListBoxControl::GetPopupWindowType() const\n{\n return SFX_POPUPWINDOW_ONTIMEOUT;\n}\n\n\nvoid SvxListBoxControl::StateChanged(\n USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )\n{\n GetToolBox().EnableItem( GetId(),\n SFX_ITEM_DISABLED != GetItemState(pState) );\n}\n\n\nIMPL_LINK( SvxListBoxControl, PopupModeEndHdl, void *, EMPTYARG )\n{\n if( pPopupWin && 0 == pPopupWin->GetPopupModeFlags() &&\n pPopupWin->IsUserSelected() )\n {\n USHORT nCount = pPopupWin->GetListBox().GetSelectEntryCount();\n\n INetURLObject aObj( m_aCommandURL );\n\n Sequence< PropertyValue > aArgs( 1 );\n aArgs[0].Name = aObj.GetURLPath();\n aArgs[0].Value = makeAny( sal_Int16( nCount ));\n SfxToolBoxControl::Dispatch( m_aCommandURL, aArgs );\n }\n return 0;\n}\n\n\nvoid SvxListBoxControl::Impl_SetInfo( USHORT nCount )\n{\n DBG_ASSERT( pPopupWin, \"NULL pointer, PopupWindow missing\" );\n\n ListBox &rListBox = pPopupWin->GetListBox();\n\n USHORT nId;\n if (nCount == 1)\n nId = SID_UNDO == GetSlotId() ? RID_SVXSTR_NUM_UNDO_ACTION : RID_SVXSTR_NUM_REDO_ACTION;\n else\n nId = SID_UNDO == GetSlotId() ? RID_SVXSTR_NUM_UNDO_ACTIONS : RID_SVXSTR_NUM_REDO_ACTIONS;\n\n aActionStr = String(SVX_RES(nId));\n\n String aText( aActionStr );\n aText.SearchAndReplaceAllAscii( \"$(ARG1)\", String::CreateFromInt32( nCount ) );\n pPopupWin->GetInfo().SetText( aText );\n}\n\n\nIMPL_LINK( SvxListBoxControl, SelectHdl, void *, EMPTYARG )\n{\n if (pPopupWin)\n {\n \/\/pPopupWin->SetUserSelected( FALSE );\n\n ListBox &rListBox = pPopupWin->GetListBox();\n if (rListBox.IsTravelSelect())\n Impl_SetInfo( rListBox.GetSelectEntryCount() );\n else\n {\n pPopupWin->SetUserSelected( TRUE );\n pPopupWin->EndPopupMode( 0 );\n }\n }\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSFX_IMPL_TOOLBOX_CONTROL( SvxUndoRedoControl, SfxStringItem );\n\nSvxUndoRedoControl::SvxUndoRedoControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx )\n : SvxListBoxControl( nSlotId, nId, rTbx )\n{\n rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );\n rTbx.Invalidate();\n}\n\nSvxUndoRedoControl::~SvxUndoRedoControl()\n{\n}\n\nvoid SvxUndoRedoControl::StateChanged(\n USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )\n{\n if ( nSID == SID_UNDO || nSID == SID_REDO )\n {\n if ( pState && pState->ISA( SfxStringItem ))\n {\n SfxStringItem& rItem = *(SfxStringItem *)pState;\n ToolBox& rBox = GetToolBox();\n String aQuickHelpText = MnemonicGenerator::EraseAllMnemonicChars( rItem.GetValue() );\n rBox.SetQuickHelpText( GetId(), aQuickHelpText );\n }\n SvxListBoxControl::StateChanged( nSID, eState, pState );\n }\n else\n {\n aUndoRedoList.clear();\n\n SfxStringListItem &rItem = *(SfxStringListItem *)pState;\n const List* pLst = rItem.GetList();\n DBG_ASSERT( pLst, \"no undo actions available\" );\n if ( pLst )\n {\n for( long nI = 0, nEnd = pLst->Count(); nI < nEnd; ++nI )\n aUndoRedoList.push_back( rtl::OUString( *(String *)pLst->GetObject( nI )));\n }\n }\n}\n\nSfxPopupWindow* SvxUndoRedoControl::CreatePopupWindow()\n{\n DBG_ASSERT(( SID_UNDO == GetSlotId() || SID_REDO == GetSlotId() ), \"mismatching ids\" );\n\n if ( m_aCommandURL.equalsAscii( \".uno:Undo\" ))\n updateStatus( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:GetUndoStrings\" )));\n else\n updateStatus( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:GetRedoStrings\" )));\n\n ToolBox& rBox = GetToolBox();\n\n pPopupWin = new SvxPopupWindowListBox( GetSlotId(), m_aCommandURL, GetId(), rBox );\n pPopupWin->SetPopupModeEndHdl( LINK( this, SvxUndoRedoControl,\n PopupModeEndHdl ) );\n ListBox &rListBox = pPopupWin->GetListBox();\n rListBox.SetSelectHdl( LINK( this, SvxUndoRedoControl, SelectHdl ) );\n\n for( sal_uInt32 n = 0; n < aUndoRedoList.size(); n++ )\n rListBox.InsertEntry( String( aUndoRedoList[n] ));\n\n rListBox.SelectEntryPos( 0 );\n aActionStr = String( SVX_RES( SID_UNDO == GetSlotId() ?\n RID_SVXSTR_NUM_UNDO_ACTIONS : RID_SVXSTR_NUM_REDO_ACTIONS ) );\n Impl_SetInfo( rListBox.GetSelectEntryCount() );\n\n \/\/ move focus in floating window without\n \/\/ closing it (GrabFocus() would close it!)\n pPopupWin->StartPopupMode( &rBox, FLOATWIN_POPUPMODE_GRABFOCUS );\n \/\/pPopupWin->GetListBox().GrabFocus();\n\n return pPopupWin;\n}\nINTEGRATION: CWS tbe19 (1.20.448); FILE MERGED 2005\/01\/27 17:01:49 tbe 1.20.448.1: #i40118# undo & restore in basic\/*************************************************************************\n *\n * $RCSfile: lboxctrl.cxx,v $\n *\n * $Revision: 1.21 $\n *\n * last change: $Author: vg $ $Date: 2005-02-24 16:55:56 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef _TOOLS_DEBUG_HXX\n#include \n#endif\n#ifndef _SV_LSTBOX_HXX\n#include \n#endif\n#ifndef _SV_TOOLBOX_HXX\n#include \n#endif\n#ifndef _SV_EVENT_HXX\n#include \n#endif\n#ifndef _SFXAPP_HXX\n#include \n#endif\n#ifndef _SFXTBXCTRL_HXX\n#include \n#endif\n#ifndef _SFX_BINDINGS_HXX\n#include \n#endif\n#ifndef _SFXDISPATCH_HXX\n#include \n#endif\n#ifndef _SFXVIEWSH_HXX\n#include \n#endif\n#ifndef _SV_GEN_HXX\n#include \n#endif\n#ifndef _SFXINTITEM_HXX\n#include \n#endif\n#ifndef _SFXENUMITEM_HXX\n#include \n#endif\n#ifndef _STDCTRL_HXX\n#include \n#endif\n#ifndef _SFXSLSTITM_HXX\n#include \n#endif\n#ifndef _SFXSTRITEM_HXX\n#include \n#endif\n\n#ifndef _SVX_DIALMGR_HXX\n#include \n#endif\n#ifndef _SVX_LBOXCTRL_HXX_\n#include \n#endif\n#ifndef _VCL_MNEMONIC_HXX_\n#include \n#endif\n#include \n\n#include \n#include \n\n#include \"lboxctrl.hrc\"\n\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::frame;\n\nclass SvxPopupWindowListBox;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass SvxPopupWindowListBox : public SfxPopupWindow\n{\n FixedInfo aInfo;\n ListBox * pListBox;\n ToolBox & rToolBox;\n BOOL bUserSel;\n USHORT nTbxId;\n rtl::OUString maCommandURL;\n \/\/ disallow copy-constructor and assignment-operator\n\n SvxPopupWindowListBox(const int& );\n SvxPopupWindowListBox & operator = (const int& );\n\n\/\/ SvxPopupWindowListBox( USHORT nSlotId, ToolBox& rTbx, USHORT nTbxItemId );\n\npublic:\n SvxPopupWindowListBox( USHORT nSlotId, const rtl::OUString& rCommandURL, USHORT nTbxId, ToolBox& rTbx );\n virtual ~SvxPopupWindowListBox();\n\n \/\/ SfxPopupWindow\n virtual SfxPopupWindow * Clone() const;\n virtual void PopupModeEnd();\n virtual void StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState );\n\n void StartSelection();\n inline ListBox & GetListBox() { return *pListBox; }\n inline FixedInfo & GetInfo() { return aInfo; }\n\n BOOL IsUserSelected() const { return bUserSel; }\n void SetUserSelected( BOOL bVal ) { bUserSel = bVal; }\n \/*virtual*\/Window* GetPreferredKeyInputWindow();\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSvxPopupWindowListBox::SvxPopupWindowListBox( USHORT nSlotId, const rtl::OUString& rCommandURL, USHORT nId, ToolBox& rTbx ) :\n SfxPopupWindow( nSlotId, Reference< XFrame >(), SVX_RES( RID_SVXTBX_UNDO_REDO_CTRL ) ),\n aInfo ( this, ResId( FT_NUM_OPERATIONS ) ),\n rToolBox ( rTbx ),\n bUserSel ( FALSE ),\n nTbxId ( nId ),\n maCommandURL( rCommandURL )\n{\n DBG_ASSERT( nSlotId == GetId(), \"id mismatch\" );\n pListBox = new ListBox( this, SVX_RES( LB_SVXTBX_UNDO_REDO_CTRL ) );\n FreeResource();\n pListBox->EnableMultiSelection( TRUE, TRUE );\n SetBackground( GetSettings().GetStyleSettings().GetDialogColor() );\n AddStatusListener( rCommandURL );\n}\n\n\nSvxPopupWindowListBox::~SvxPopupWindowListBox()\n{\n delete pListBox;\n}\n\n\nSfxPopupWindow* SvxPopupWindowListBox::Clone() const\n{\n return new SvxPopupWindowListBox( GetId(), maCommandURL, nTbxId, rToolBox );\n}\n\n\nvoid SvxPopupWindowListBox::PopupModeEnd()\n{\n rToolBox.EndSelection();\n SfxPopupWindow::PopupModeEnd();\n \/\/FloatingWindow::PopupModeEnd();\n\n Window* pShellWnd = SfxViewShell::Current()->GetWindow();\n if (pShellWnd)\n pShellWnd->GrabFocus();\n}\n\n\nvoid SvxPopupWindowListBox::StateChanged(\n USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )\n{\n rToolBox.EnableItem( nTbxId, ( SfxToolBoxControl::GetItemState( pState ) != SFX_ITEM_DISABLED) );\n SfxPopupWindow::StateChanged( nSID, eState, pState );\n}\n\n\nvoid SvxPopupWindowListBox::StartSelection()\n{\n rToolBox.StartSelection();\n}\n\nWindow* SvxPopupWindowListBox::GetPreferredKeyInputWindow()\n{\n \/\/ allows forwarding key events in the correct window\n \/\/ without setting the focus\n return pListBox->GetPreferredKeyInputWindow();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSFX_IMPL_TOOLBOX_CONTROL( SvxListBoxControl, SfxStringItem );\n\n\nSvxListBoxControl::SvxListBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx )\n :SfxToolBoxControl( nSlotId, nId, rTbx ),\n pPopupWin ( 0 )\n{\n rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );\n rTbx.Invalidate();\n}\n\n\nSvxListBoxControl::~SvxListBoxControl()\n{\n}\n\n\nSfxPopupWindow* SvxListBoxControl::CreatePopupWindow()\n{\n DBG_ERROR( \"not implemented\" );\n return 0;\n}\n\n\nSfxPopupWindowType SvxListBoxControl::GetPopupWindowType() const\n{\n return SFX_POPUPWINDOW_ONTIMEOUT;\n}\n\n\nvoid SvxListBoxControl::StateChanged(\n USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )\n{\n GetToolBox().EnableItem( GetId(),\n SFX_ITEM_DISABLED != GetItemState(pState) );\n}\n\n\nIMPL_LINK( SvxListBoxControl, PopupModeEndHdl, void *, EMPTYARG )\n{\n if( pPopupWin && 0 == pPopupWin->GetPopupModeFlags() &&\n pPopupWin->IsUserSelected() )\n {\n USHORT nCount = pPopupWin->GetListBox().GetSelectEntryCount();\n\n INetURLObject aObj( m_aCommandURL );\n\n Sequence< PropertyValue > aArgs( 1 );\n aArgs[0].Name = aObj.GetURLPath();\n aArgs[0].Value = makeAny( sal_Int16( nCount ));\n SfxToolBoxControl::Dispatch( m_aCommandURL, aArgs );\n }\n return 0;\n}\n\n\nvoid SvxListBoxControl::Impl_SetInfo( USHORT nCount )\n{\n DBG_ASSERT( pPopupWin, \"NULL pointer, PopupWindow missing\" );\n\n ListBox &rListBox = pPopupWin->GetListBox();\n\n USHORT nId;\n if (nCount == 1)\n nId = SID_UNDO == GetSlotId() ? RID_SVXSTR_NUM_UNDO_ACTION : RID_SVXSTR_NUM_REDO_ACTION;\n else\n nId = SID_UNDO == GetSlotId() ? RID_SVXSTR_NUM_UNDO_ACTIONS : RID_SVXSTR_NUM_REDO_ACTIONS;\n\n aActionStr = String(SVX_RES(nId));\n\n String aText( aActionStr );\n aText.SearchAndReplaceAllAscii( \"$(ARG1)\", String::CreateFromInt32( nCount ) );\n pPopupWin->GetInfo().SetText( aText );\n}\n\n\nIMPL_LINK( SvxListBoxControl, SelectHdl, void *, EMPTYARG )\n{\n if (pPopupWin)\n {\n \/\/pPopupWin->SetUserSelected( FALSE );\n\n ListBox &rListBox = pPopupWin->GetListBox();\n if (rListBox.IsTravelSelect())\n Impl_SetInfo( rListBox.GetSelectEntryCount() );\n else\n {\n pPopupWin->SetUserSelected( TRUE );\n pPopupWin->EndPopupMode( 0 );\n }\n }\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSFX_IMPL_TOOLBOX_CONTROL( SvxUndoRedoControl, SfxStringItem );\n\nSvxUndoRedoControl::SvxUndoRedoControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx )\n : SvxListBoxControl( nSlotId, nId, rTbx )\n{\n rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );\n rTbx.Invalidate();\n aDefaultText = MnemonicGenerator::EraseAllMnemonicChars( rTbx.GetItemText( nId ) );\n}\n\nSvxUndoRedoControl::~SvxUndoRedoControl()\n{\n}\n\nvoid SvxUndoRedoControl::StateChanged(\n USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )\n{\n if ( nSID == SID_UNDO || nSID == SID_REDO )\n {\n if ( eState == SFX_ITEM_DISABLED )\n {\n ToolBox& rBox = GetToolBox();\n rBox.SetQuickHelpText( GetId(), aDefaultText );\n }\n else if ( pState && pState->ISA( SfxStringItem ) )\n {\n SfxStringItem& rItem = *(SfxStringItem *)pState;\n ToolBox& rBox = GetToolBox();\n String aQuickHelpText = MnemonicGenerator::EraseAllMnemonicChars( rItem.GetValue() );\n rBox.SetQuickHelpText( GetId(), aQuickHelpText );\n }\n SvxListBoxControl::StateChanged( nSID, eState, pState );\n }\n else\n {\n aUndoRedoList.clear();\n\n SfxStringListItem &rItem = *(SfxStringListItem *)pState;\n const List* pLst = rItem.GetList();\n DBG_ASSERT( pLst, \"no undo actions available\" );\n if ( pLst )\n {\n for( long nI = 0, nEnd = pLst->Count(); nI < nEnd; ++nI )\n aUndoRedoList.push_back( rtl::OUString( *(String *)pLst->GetObject( nI )));\n }\n }\n}\n\nSfxPopupWindow* SvxUndoRedoControl::CreatePopupWindow()\n{\n DBG_ASSERT(( SID_UNDO == GetSlotId() || SID_REDO == GetSlotId() ), \"mismatching ids\" );\n\n if ( m_aCommandURL.equalsAscii( \".uno:Undo\" ))\n updateStatus( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:GetUndoStrings\" )));\n else\n updateStatus( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:GetRedoStrings\" )));\n\n ToolBox& rBox = GetToolBox();\n\n pPopupWin = new SvxPopupWindowListBox( GetSlotId(), m_aCommandURL, GetId(), rBox );\n pPopupWin->SetPopupModeEndHdl( LINK( this, SvxUndoRedoControl,\n PopupModeEndHdl ) );\n ListBox &rListBox = pPopupWin->GetListBox();\n rListBox.SetSelectHdl( LINK( this, SvxUndoRedoControl, SelectHdl ) );\n\n for( sal_uInt32 n = 0; n < aUndoRedoList.size(); n++ )\n rListBox.InsertEntry( String( aUndoRedoList[n] ));\n\n rListBox.SelectEntryPos( 0 );\n aActionStr = String( SVX_RES( SID_UNDO == GetSlotId() ?\n RID_SVXSTR_NUM_UNDO_ACTIONS : RID_SVXSTR_NUM_REDO_ACTIONS ) );\n Impl_SetInfo( rListBox.GetSelectEntryCount() );\n\n \/\/ move focus in floating window without\n \/\/ closing it (GrabFocus() would close it!)\n pPopupWin->StartPopupMode( &rBox, FLOATWIN_POPUPMODE_GRABFOCUS );\n \/\/pPopupWin->GetListBox().GrabFocus();\n\n return pPopupWin;\n}\n<|endoftext|>"} {"text":"break out text drawing bit as UserDrawEntry<|endoftext|>"} {"text":"sw: oops, forgot to commit that<|endoftext|>"} {"text":"Fix (again) angular velocity.<|endoftext|>"} {"text":"Hack to suppress warnings from MSL compiler<|endoftext|>"} {"text":"fdo#75757: remove inheritance to std::map<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: swatrset.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 08:25:59 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n#include \n#include \n#ifndef _SVX_COLRITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVX_BRSHITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVX_BOLNITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVX_BOXITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _XTABLE_HXX \/\/autogen\n#include \n#endif\n#ifndef _FMTPDSC_HXX \/\/autogen\n#include \n#endif\n#ifndef _PAGEDESC_HXX \/\/autogen\n#include \n#endif\n#ifndef _CHARFMT_HXX\n#include \n#endif\n#ifndef _DOC_HXX\n#include \n#endif\n#ifndef _NODE_HXX \/\/autogen\n#include \n#endif\n#ifndef _PARATR_HXX\n#include \/\/ fuer SetModifyAtAttr\n#endif\n#ifndef _CELLATR_HXX\n#include \/\/ fuer SetModifyAtAttr\n#endif\n#ifndef _CMDID_H\n#include \n#endif\n#include \n\n\nSwAttrPool::SwAttrPool( SwDoc* pD )\n : SfxItemPool( String::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM( \"SWG\" )),\n POOLATTR_BEGIN, POOLATTR_END-1,\n aSlotTab, aAttrTab ),\n pDoc( pD )\n{\n SetVersionMap( 1, 1, 60, pVersionMap1 );\n SetVersionMap( 2, 1, 75, pVersionMap2 );\n SetVersionMap( 3, 1, 86, pVersionMap3 );\n SetVersionMap( 4, 1,121, pVersionMap4 );\n \/\/ OD 2004-01-21 #i18732# - apply new version map\n SetVersionMap( 5, 1,130, pVersionMap5 );\n}\n\n\nSwAttrSet::SwAttrSet( SwAttrPool& rPool, USHORT nWh1, USHORT nWh2 )\n : SfxItemSet( rPool, nWh1, nWh2 ), pOldSet( 0 ), pNewSet( 0 )\n{\n}\n\n\nSwAttrSet::SwAttrSet( SwAttrPool& rPool, const USHORT* nWhichPairTable )\n : SfxItemSet( rPool, nWhichPairTable ), pOldSet( 0 ), pNewSet( 0 )\n{\n}\n\n\nSwAttrSet::SwAttrSet( const SwAttrSet& rSet )\n : SfxItemSet( rSet ), pOldSet( 0 ), pNewSet( 0 )\n{\n}\n\nSfxItemSet* SwAttrSet::Clone( BOOL bItems, SfxItemPool *pToPool ) const\n{\n if ( pToPool && pToPool != GetPool() )\n {\n SwAttrPool* pAttrPool = dynamic_cast< SwAttrPool* >(pToPool);\n SfxItemSet* pTmpSet = 0;\n if ( !pAttrPool )\n pTmpSet = SfxItemSet::Clone( bItems, pToPool );\n else\n {\n pTmpSet = new SwAttrSet( *pAttrPool, GetRanges() );\n if ( bItems )\n {\n SfxWhichIter aIter(*pTmpSet);\n USHORT nWhich = aIter.FirstWhich();\n while ( nWhich )\n {\n const SfxPoolItem* pItem;\n if ( SFX_ITEM_SET == GetItemState( nWhich, FALSE, &pItem ) )\n pTmpSet->Put( *pItem, pItem->Which() );\n nWhich = aIter.NextWhich();\n }\n }\n }\n return pTmpSet;\n }\n else\n return bItems\n ? new SwAttrSet( *this )\n : new SwAttrSet( *GetPool(), GetRanges() );\n}\n\nint SwAttrSet::Put_BC( const SfxPoolItem& rAttr,\n SwAttrSet* pOld, SwAttrSet* pNew )\n{\n pNewSet = pNew;\n pOldSet = pOld;\n int nRet = 0 != SfxItemSet::Put( rAttr );\n pOldSet = pNewSet = 0;\n return nRet;\n}\n\n\nint SwAttrSet::Put_BC( const SfxItemSet& rSet,\n SwAttrSet* pOld, SwAttrSet* pNew )\n{\n pNewSet = pNew;\n pOldSet = pOld;\n int nRet = 0 != SfxItemSet::Put( rSet );\n pOldSet = pNewSet = 0;\n return nRet;\n}\n\n\n\nUSHORT SwAttrSet::ClearItem_BC( USHORT nWhich,\n SwAttrSet* pOld, SwAttrSet* pNew )\n{\n pNewSet = pNew;\n pOldSet = pOld;\n USHORT nRet = SfxItemSet::ClearItem( nWhich );\n pOldSet = pNewSet = 0;\n return nRet;\n}\n\n\nUSHORT SwAttrSet::ClearItem_BC( USHORT nWhich1, USHORT nWhich2,\n SwAttrSet* pOld, SwAttrSet* pNew )\n{\n ASSERT( nWhich1 <= nWhich2, \"kein gueltiger Bereich\" );\n pNewSet = pNew;\n pOldSet = pOld;\n USHORT nRet = 0;\n for( ; nWhich1 <= nWhich2; ++nWhich1 )\n nRet = nRet + SfxItemSet::ClearItem( nWhich1 );\n pOldSet = pNewSet = 0;\n return nRet;\n}\n\n\n\nint SwAttrSet::Intersect_BC( const SfxItemSet& rSet,\n SwAttrSet* pOld, SwAttrSet* pNew )\n{\n pNewSet = pNew;\n pOldSet = pOld;\n SfxItemSet::Intersect( rSet );\n pOldSet = pNewSet = 0;\n return pNew ? pNew->Count() : ( pOld ? pOld->Count() : 0 );\n}\n\n\/\/ Notification-Callback\nvoid SwAttrSet::Changed( const SfxPoolItem& rOld,\n const SfxPoolItem& rNew )\n{\n if( pOldSet )\n pOldSet->PutChgd( rOld );\n\n if( pNewSet )\n pNewSet->PutChgd( rNew );\n}\n\n\n\/\/ ----------------------------------------------------------------\n\/\/ Sonderbehandlung fuer einige Attribute\n\/\/ Setze den Modify-Pointer (alten pDefinedIn) bei folgenden Attributen:\n\/\/ - SwFmtDropCaps\n\/\/ - SwFmtPageDesc\n\/\/ (Wird beim Einfuegen in Formate\/Nodes gerufen)\n\/\/ ----------------------------------------------------------------\n\nbool SwAttrSet::SetModifyAtAttr( const SwModify* pModify )\n{\n bool bSet = false;\n\n const SfxPoolItem* pItem;\n if( SFX_ITEM_SET == GetItemState( RES_PAGEDESC, FALSE, &pItem ) &&\n ((SwFmtPageDesc*)pItem)->GetDefinedIn() != pModify )\n {\n ((SwFmtPageDesc*)pItem)->ChgDefinedIn( pModify );\n bSet = true;\n }\n\n if( SFX_ITEM_SET == GetItemState( RES_PARATR_NUMRULE, FALSE, &pItem ) &&\n ((SwNumRuleItem*)pItem)->GetDefinedIn() != pModify )\n {\n ((SwNumRuleItem*)pItem)->ChgDefinedIn( pModify );\n bSet = true;\n }\n\n if( SFX_ITEM_SET == GetItemState( RES_PARATR_DROP, FALSE, &pItem ) &&\n ((SwFmtDrop*)pItem)->GetDefinedIn() != pModify )\n {\n \/\/ CharFormat gesetzt und dann noch in unterschiedlichen\n \/\/ Attribut Pools, dann muss das CharFormat kopiert werden!\n SwCharFmt* pCharFmt;\n if( 0 != ( pCharFmt = ((SwFmtDrop*)pItem)->GetCharFmt() )\n && GetPool() != pCharFmt->GetAttrSet().GetPool() )\n {\n pCharFmt = GetDoc()->CopyCharFmt( *pCharFmt );\n ((SwFmtDrop*)pItem)->SetCharFmt( pCharFmt );\n }\n ((SwFmtDrop*)pItem)->ChgDefinedIn( pModify );\n bSet = true;\n }\n\n if( SFX_ITEM_SET == GetItemState( RES_BOXATR_FORMULA, FALSE, &pItem ) &&\n ((SwTblBoxFormula*)pItem)->GetDefinedIn() != pModify )\n {\n ((SwTblBoxFormula*)pItem)->ChgDefinedIn( pModify );\n bSet = true;\n }\n\n return bSet;\n}\n\nvoid SwAttrSet::CopyToModify( SwModify& rMod ) const\n{\n \/\/ kopiere die Attribute ggfs. ueber Dokumentgrenzen\n SwCntntNode* pCNd = PTR_CAST( SwCntntNode, &rMod );\n SwFmt* pFmt = PTR_CAST( SwFmt, &rMod );\n\n if( pCNd || pFmt )\n {\n if( Count() )\n {\n const SfxPoolItem* pItem;\n const SwDoc *pSrcDoc = GetDoc();\n SwDoc *pDstDoc = pCNd ? pCNd->GetDoc() : pFmt->GetDoc();\n\n \/\/ muss die NumRule kopiert werden?\n if( pSrcDoc != pDstDoc && SFX_ITEM_SET == GetItemState(\n RES_PARATR_NUMRULE, FALSE, &pItem ) )\n {\n const String& rNm = ((SwNumRuleItem*)pItem)->GetValue();\n if( rNm.Len() )\n {\n SwNumRule* pDestRule = pDstDoc->FindNumRulePtr( rNm );\n if( pDestRule )\n pDestRule->SetInvalidRule( TRUE );\n else\n pDstDoc->MakeNumRule( rNm,\n pSrcDoc->FindNumRulePtr( rNm ) );\n }\n }\n\n \/\/ JP 04.02.99: Task #61467# Seitenvorlagenwechsel mit kopieren\n \/\/ Gegenueber dem alten Verhalten, sie zu entfernen\n const SwPageDesc* pPgDesc;\n if( pSrcDoc != pDstDoc && SFX_ITEM_SET == GetItemState(\n RES_PAGEDESC, FALSE, &pItem ) &&\n 0 != ( pPgDesc = ((SwFmtPageDesc*)pItem)->GetPageDesc()) )\n {\n SfxItemSet aTmpSet( *this );\n\n \/\/ JP 09.02.99: und jetzt doch wieder nur entfernen\n aTmpSet.ClearItem( RES_PAGEDESC );\n\n\/*************************************************************************\n SwPageDesc* pDstPgDesc = pDstDoc->FindPageDescByName(\n pPgDesc->GetName() );\n if( !pDstPgDesc )\n {\n \/\/ dann kopieren, ansonsten den benutzen\n pDstPgDesc = &pDstDoc->_GetPageDesc( pDstDoc->MakePageDesc(\n pPgDesc->GetName() ));\n pDstDoc->CopyPageDesc( *pPgDesc, *pDstPgDesc );\n }\n SwFmtPageDesc aDesc( pDstPgDesc );\n aDesc.SetNumOffset( ((SwFmtPageDesc*)pItem)->GetNumOffset() );\n aTmpSet.Put( aDesc );\n************************************************************************\/\n\n if( pCNd )\n pCNd->SetAttr( aTmpSet );\n else\n pFmt->SetAttr( aTmpSet );\n }\n else if( pCNd )\n pCNd->SetAttr( *this );\n else\n pFmt->SetAttr( *this );\n }\n }\n#ifndef PRODUCT\n else\n ASSERT( !this, \"weder Format noch ContentNode - keine Attribute kopiert\");\n#endif\n}\n\n\/\/ check if ID is InRange of AttrSet-Ids\nBOOL IsInRange( const USHORT* pRange, const USHORT nId )\n{\n while( *pRange )\n {\n if( *pRange <= nId && nId <= *(pRange+1) )\n return TRUE;\n pRange += 2;\n }\n return FALSE;\n}\n\nINTEGRATION: CWS swnewlistlevelattrs_DEV300 (1.12.142); FILE MERGED 2008\/01\/31 12:39:23 od 1.12.142.1: #i85348# refactoring: adjust includes\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: swatrset.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: kz $ $Date: 2008-03-05 16:52:17 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n#include \n#include \n#ifndef _SVX_COLRITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVX_BRSHITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVX_BOLNITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVX_BOXITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _XTABLE_HXX \/\/autogen\n#include \n#endif\n#ifndef _FMTPDSC_HXX \/\/autogen\n#include \n#endif\n#ifndef _PAGEDESC_HXX \/\/autogen\n#include \n#endif\n#ifndef _CHARFMT_HXX\n#include \n#endif\n#ifndef _DOC_HXX\n#include \n#endif\n#ifndef _NODE_HXX \/\/autogen\n#include \n#endif\n#ifndef _PARATR_HXX\n#include \/\/ fuer SetModifyAtAttr\n#endif\n#ifndef _CELLATR_HXX\n#include \/\/ fuer SetModifyAtAttr\n#endif\n#ifndef _CMDID_H\n#include \n#endif\n#include \n#ifndef _NUMRULE_HXX\n#include \n#endif\n\n\nSwAttrPool::SwAttrPool( SwDoc* pD )\n : SfxItemPool( String::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM( \"SWG\" )),\n POOLATTR_BEGIN, POOLATTR_END-1,\n aSlotTab, aAttrTab ),\n pDoc( pD )\n{\n SetVersionMap( 1, 1, 60, pVersionMap1 );\n SetVersionMap( 2, 1, 75, pVersionMap2 );\n SetVersionMap( 3, 1, 86, pVersionMap3 );\n SetVersionMap( 4, 1,121, pVersionMap4 );\n \/\/ OD 2004-01-21 #i18732# - apply new version map\n SetVersionMap( 5, 1,130, pVersionMap5 );\n}\n\n\nSwAttrSet::SwAttrSet( SwAttrPool& rPool, USHORT nWh1, USHORT nWh2 )\n : SfxItemSet( rPool, nWh1, nWh2 ), pOldSet( 0 ), pNewSet( 0 )\n{\n}\n\n\nSwAttrSet::SwAttrSet( SwAttrPool& rPool, const USHORT* nWhichPairTable )\n : SfxItemSet( rPool, nWhichPairTable ), pOldSet( 0 ), pNewSet( 0 )\n{\n}\n\n\nSwAttrSet::SwAttrSet( const SwAttrSet& rSet )\n : SfxItemSet( rSet ), pOldSet( 0 ), pNewSet( 0 )\n{\n}\n\nSfxItemSet* SwAttrSet::Clone( BOOL bItems, SfxItemPool *pToPool ) const\n{\n if ( pToPool && pToPool != GetPool() )\n {\n SwAttrPool* pAttrPool = dynamic_cast< SwAttrPool* >(pToPool);\n SfxItemSet* pTmpSet = 0;\n if ( !pAttrPool )\n pTmpSet = SfxItemSet::Clone( bItems, pToPool );\n else\n {\n pTmpSet = new SwAttrSet( *pAttrPool, GetRanges() );\n if ( bItems )\n {\n SfxWhichIter aIter(*pTmpSet);\n USHORT nWhich = aIter.FirstWhich();\n while ( nWhich )\n {\n const SfxPoolItem* pItem;\n if ( SFX_ITEM_SET == GetItemState( nWhich, FALSE, &pItem ) )\n pTmpSet->Put( *pItem, pItem->Which() );\n nWhich = aIter.NextWhich();\n }\n }\n }\n return pTmpSet;\n }\n else\n return bItems\n ? new SwAttrSet( *this )\n : new SwAttrSet( *GetPool(), GetRanges() );\n}\n\nint SwAttrSet::Put_BC( const SfxPoolItem& rAttr,\n SwAttrSet* pOld, SwAttrSet* pNew )\n{\n pNewSet = pNew;\n pOldSet = pOld;\n int nRet = 0 != SfxItemSet::Put( rAttr );\n pOldSet = pNewSet = 0;\n return nRet;\n}\n\n\nint SwAttrSet::Put_BC( const SfxItemSet& rSet,\n SwAttrSet* pOld, SwAttrSet* pNew )\n{\n pNewSet = pNew;\n pOldSet = pOld;\n int nRet = 0 != SfxItemSet::Put( rSet );\n pOldSet = pNewSet = 0;\n return nRet;\n}\n\n\n\nUSHORT SwAttrSet::ClearItem_BC( USHORT nWhich,\n SwAttrSet* pOld, SwAttrSet* pNew )\n{\n pNewSet = pNew;\n pOldSet = pOld;\n USHORT nRet = SfxItemSet::ClearItem( nWhich );\n pOldSet = pNewSet = 0;\n return nRet;\n}\n\n\nUSHORT SwAttrSet::ClearItem_BC( USHORT nWhich1, USHORT nWhich2,\n SwAttrSet* pOld, SwAttrSet* pNew )\n{\n ASSERT( nWhich1 <= nWhich2, \"kein gueltiger Bereich\" );\n pNewSet = pNew;\n pOldSet = pOld;\n USHORT nRet = 0;\n for( ; nWhich1 <= nWhich2; ++nWhich1 )\n nRet = nRet + SfxItemSet::ClearItem( nWhich1 );\n pOldSet = pNewSet = 0;\n return nRet;\n}\n\n\n\nint SwAttrSet::Intersect_BC( const SfxItemSet& rSet,\n SwAttrSet* pOld, SwAttrSet* pNew )\n{\n pNewSet = pNew;\n pOldSet = pOld;\n SfxItemSet::Intersect( rSet );\n pOldSet = pNewSet = 0;\n return pNew ? pNew->Count() : ( pOld ? pOld->Count() : 0 );\n}\n\n\/\/ Notification-Callback\nvoid SwAttrSet::Changed( const SfxPoolItem& rOld,\n const SfxPoolItem& rNew )\n{\n if( pOldSet )\n pOldSet->PutChgd( rOld );\n\n if( pNewSet )\n pNewSet->PutChgd( rNew );\n}\n\n\n\/\/ ----------------------------------------------------------------\n\/\/ Sonderbehandlung fuer einige Attribute\n\/\/ Setze den Modify-Pointer (alten pDefinedIn) bei folgenden Attributen:\n\/\/ - SwFmtDropCaps\n\/\/ - SwFmtPageDesc\n\/\/ (Wird beim Einfuegen in Formate\/Nodes gerufen)\n\/\/ ----------------------------------------------------------------\n\nbool SwAttrSet::SetModifyAtAttr( const SwModify* pModify )\n{\n bool bSet = false;\n\n const SfxPoolItem* pItem;\n if( SFX_ITEM_SET == GetItemState( RES_PAGEDESC, FALSE, &pItem ) &&\n ((SwFmtPageDesc*)pItem)->GetDefinedIn() != pModify )\n {\n ((SwFmtPageDesc*)pItem)->ChgDefinedIn( pModify );\n bSet = true;\n }\n\n if( SFX_ITEM_SET == GetItemState( RES_PARATR_NUMRULE, FALSE, &pItem ) &&\n ((SwNumRuleItem*)pItem)->GetDefinedIn() != pModify )\n {\n ((SwNumRuleItem*)pItem)->ChgDefinedIn( pModify );\n bSet = true;\n }\n\n if( SFX_ITEM_SET == GetItemState( RES_PARATR_DROP, FALSE, &pItem ) &&\n ((SwFmtDrop*)pItem)->GetDefinedIn() != pModify )\n {\n \/\/ CharFormat gesetzt und dann noch in unterschiedlichen\n \/\/ Attribut Pools, dann muss das CharFormat kopiert werden!\n SwCharFmt* pCharFmt;\n if( 0 != ( pCharFmt = ((SwFmtDrop*)pItem)->GetCharFmt() )\n && GetPool() != pCharFmt->GetAttrSet().GetPool() )\n {\n pCharFmt = GetDoc()->CopyCharFmt( *pCharFmt );\n ((SwFmtDrop*)pItem)->SetCharFmt( pCharFmt );\n }\n ((SwFmtDrop*)pItem)->ChgDefinedIn( pModify );\n bSet = true;\n }\n\n if( SFX_ITEM_SET == GetItemState( RES_BOXATR_FORMULA, FALSE, &pItem ) &&\n ((SwTblBoxFormula*)pItem)->GetDefinedIn() != pModify )\n {\n ((SwTblBoxFormula*)pItem)->ChgDefinedIn( pModify );\n bSet = true;\n }\n\n return bSet;\n}\n\nvoid SwAttrSet::CopyToModify( SwModify& rMod ) const\n{\n \/\/ kopiere die Attribute ggfs. ueber Dokumentgrenzen\n SwCntntNode* pCNd = PTR_CAST( SwCntntNode, &rMod );\n SwFmt* pFmt = PTR_CAST( SwFmt, &rMod );\n\n if( pCNd || pFmt )\n {\n if( Count() )\n {\n const SfxPoolItem* pItem;\n const SwDoc *pSrcDoc = GetDoc();\n SwDoc *pDstDoc = pCNd ? pCNd->GetDoc() : pFmt->GetDoc();\n\n \/\/ muss die NumRule kopiert werden?\n if( pSrcDoc != pDstDoc && SFX_ITEM_SET == GetItemState(\n RES_PARATR_NUMRULE, FALSE, &pItem ) )\n {\n const String& rNm = ((SwNumRuleItem*)pItem)->GetValue();\n if( rNm.Len() )\n {\n SwNumRule* pDestRule = pDstDoc->FindNumRulePtr( rNm );\n if( pDestRule )\n pDestRule->SetInvalidRule( TRUE );\n else\n pDstDoc->MakeNumRule( rNm,\n pSrcDoc->FindNumRulePtr( rNm ) );\n }\n }\n\n \/\/ JP 04.02.99: Task #61467# Seitenvorlagenwechsel mit kopieren\n \/\/ Gegenueber dem alten Verhalten, sie zu entfernen\n const SwPageDesc* pPgDesc;\n if( pSrcDoc != pDstDoc && SFX_ITEM_SET == GetItemState(\n RES_PAGEDESC, FALSE, &pItem ) &&\n 0 != ( pPgDesc = ((SwFmtPageDesc*)pItem)->GetPageDesc()) )\n {\n SfxItemSet aTmpSet( *this );\n\n \/\/ JP 09.02.99: und jetzt doch wieder nur entfernen\n aTmpSet.ClearItem( RES_PAGEDESC );\n\n\/*************************************************************************\n SwPageDesc* pDstPgDesc = pDstDoc->FindPageDescByName(\n pPgDesc->GetName() );\n if( !pDstPgDesc )\n {\n \/\/ dann kopieren, ansonsten den benutzen\n pDstPgDesc = &pDstDoc->_GetPageDesc( pDstDoc->MakePageDesc(\n pPgDesc->GetName() ));\n pDstDoc->CopyPageDesc( *pPgDesc, *pDstPgDesc );\n }\n SwFmtPageDesc aDesc( pDstPgDesc );\n aDesc.SetNumOffset( ((SwFmtPageDesc*)pItem)->GetNumOffset() );\n aTmpSet.Put( aDesc );\n************************************************************************\/\n\n if( pCNd )\n pCNd->SetAttr( aTmpSet );\n else\n pFmt->SetAttr( aTmpSet );\n }\n else if( pCNd )\n pCNd->SetAttr( *this );\n else\n pFmt->SetAttr( *this );\n }\n }\n#ifndef PRODUCT\n else\n ASSERT( !this, \"weder Format noch ContentNode - keine Attribute kopiert\");\n#endif\n}\n\n\/\/ check if ID is InRange of AttrSet-Ids\nBOOL IsInRange( const USHORT* pRange, const USHORT nId )\n{\n while( *pRange )\n {\n if( *pRange <= nId && nId <= *(pRange+1) )\n return TRUE;\n pRange += 2;\n }\n return FALSE;\n}\n\n<|endoftext|>"} {"text":"#include \"VulkanHandler.hpp\"\r\n\r\n\/\/ Includes\r\n\/\/----------\r\n\/\/ 3rd Party Libraries\r\n\/\/ ---------------------\r\n\r\n#define GLFW_INCLUDE_VULKAN\r\n#include \r\n\r\n\/\/ Standard Libary\r\n\/\/ -----------------\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\/\/ Weird crap (see README.md to see my justification)\r\n\/\/----------------------------------------------------\r\n\r\n#define WHOLE(container) std::begin(container), std::end(container)\r\n#define CWHOLE(container) std::cbegin(container), std::cend(container)\r\nusing namespace std;\r\n\r\n\/\/ Constants\r\n\/\/-----------\r\n\r\nconst vector VulkanHandler::k_validation_layers{\r\n \"VK_LAYER_KHRONOS_validation\"};\r\n\r\n\/\/ Method Definitions\r\n\/\/--------------------\r\n\r\nvk::UniqueInstance createInstance();\r\n\/\/ is used by:\r\nVulkanHandler::VulkanHandler() : vk_instance_{createInstance()}\r\n{\r\n}\r\n\r\n\/\/ Helpers\r\n\/\/---------\r\n\r\nbool checkValidationLayerSupport();\r\nvector getExtensions();\r\n\/\/ are used by:\r\nvk::UniqueInstance createInstance()\r\n{\r\n if (VulkanHandler::k_enable_validation_layers\r\n && !checkValidationLayerSupport()) {\r\n throw std::runtime_error(\"validation layers requested, but not available!\");\r\n }\r\n\r\n vk::ApplicationInfo app_info{ \/\/\r\n \"Hello Triangle\", \/\/ pApplicationName\r\n VK_MAKE_VERSION(1, 0, 0), \/\/ application version\r\n \"No Engine\", \/\/\r\n VK_MAKE_VERSION(1, 0, 0), \/\/ engine version\r\n VK_API_VERSION_1_0}; \/\/\r\n\r\n auto extensions = getExtensions();\r\n\r\n vk::InstanceCreateInfo create_info{{}, &app_info, 0, {},\r\n static_cast(extensions.size()), extensions.data()};\r\n if (VulkanHandler::k_enable_validation_layers) {\r\n create_info.enabledLayerCount =\r\n static_cast(VulkanHandler::k_validation_layers.size());\r\n create_info.ppEnabledLayerNames = VulkanHandler::k_validation_layers.data();\r\n }\r\n\r\n return vk::createInstanceUnique(create_info);\r\n}\r\n\r\nbool checkValidationLayerSupport()\r\n{\r\n \/\/ set is sorted, and its elements are trivially comparable.\r\n std::set available_layer_names{};\r\n for (const auto& layer_properties : vk::enumerateInstanceLayerProperties()) {\r\n available_layer_names.emplace(layer_properties.layerName);\r\n }\r\n\r\n std::set validation_layers_sorted{};\r\n for (const auto& layer : VulkanHandler::k_validation_layers) {\r\n validation_layers_sorted.emplace(layer);\r\n }\r\n\r\n return std::includes(\r\n CWHOLE(available_layer_names), CWHOLE(validation_layers_sorted));\r\n}\r\n\r\nvector getExtensions()\r\n{\r\n uint32_t glfw_extension_count{};\r\n const char** glfw_extensions =\r\n glfwGetRequiredInstanceExtensions(&glfw_extension_count);\r\n\r\n vector extensions(glfw_extension_count);\r\n std::copy_n(glfw_extensions, glfw_extension_count, begin(extensions));\r\n\r\n return extensions;\r\n}\r\n\r\n\/\/ vim:set et ts=2 sw=0 sts=0:\r\n\r\nAssure that k_validation_layers is sorted#include \"VulkanHandler.hpp\"\r\n\r\n\/\/ Includes\r\n\/\/----------\r\n\/\/ 3rd Party Libraries\r\n\/\/ ---------------------\r\n\r\n#define GLFW_INCLUDE_VULKAN\r\n#include \r\n\r\n\/\/ Standard Libary\r\n\/\/ -----------------\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\/\/ Weird crap (see README.md to see my justification)\r\n\/\/----------------------------------------------------\r\n\r\n#define WHOLE(container) std::begin(container), std::end(container)\r\n#define CWHOLE(container) std::cbegin(container), std::cend(container)\r\nusing namespace std;\r\n\r\n\/\/ Constants\r\n\/\/-----------\r\n\r\nconst vector VulkanHandler::k_validation_layers = []() {\r\n const vector value{\"VK_LAYER_KHRONOS_validation\"};\r\n\r\n \/\/ Easier to compare. Same name makes the assertion fail output more readable.\r\n vector k_validation_layers(CWHOLE(value));\r\n assert(std::is_sorted(CWHOLE(k_validation_layers)));\r\n\r\n return value;\r\n}();\r\n\r\n\/\/ Method Definitions\r\n\/\/--------------------\r\n\r\nvk::UniqueInstance createInstance();\r\n\/\/ is used by:\r\nVulkanHandler::VulkanHandler() : vk_instance_{createInstance()}\r\n{\r\n}\r\n\r\n\/\/ Helpers\r\n\/\/---------\r\n\r\nbool checkValidationLayerSupport();\r\nvector getExtensions();\r\n\/\/ are used by:\r\nvk::UniqueInstance createInstance()\r\n{\r\n if (VulkanHandler::k_enable_validation_layers\r\n && !checkValidationLayerSupport()) {\r\n throw std::runtime_error(\"validation layers requested, but not available!\");\r\n }\r\n\r\n vk::ApplicationInfo app_info{ \/\/\r\n \"Hello Triangle\", \/\/ pApplicationName\r\n VK_MAKE_VERSION(1, 0, 0), \/\/ application version\r\n \"No Engine\", \/\/\r\n VK_MAKE_VERSION(1, 0, 0), \/\/ engine version\r\n VK_API_VERSION_1_0}; \/\/\r\n\r\n auto extensions = getExtensions();\r\n\r\n vk::InstanceCreateInfo create_info{{}, &app_info, 0, {},\r\n static_cast(extensions.size()), extensions.data()};\r\n if (VulkanHandler::k_enable_validation_layers) {\r\n create_info.enabledLayerCount =\r\n static_cast(VulkanHandler::k_validation_layers.size());\r\n create_info.ppEnabledLayerNames = VulkanHandler::k_validation_layers.data();\r\n }\r\n\r\n return vk::createInstanceUnique(create_info);\r\n}\r\n\r\nbool checkValidationLayerSupport()\r\n{\r\n \/\/ set is sorted, and its elements are trivially comparable.\r\n std::set available_layer_names{};\r\n for (const auto& layer_properties : vk::enumerateInstanceLayerProperties()) {\r\n available_layer_names.emplace(layer_properties.layerName);\r\n }\r\n\r\n return std::includes(CWHOLE(available_layer_names),\r\n CWHOLE(VulkanHandler::k_validation_layers));\r\n}\r\n\r\nvector getExtensions()\r\n{\r\n uint32_t glfw_extension_count{};\r\n const char** glfw_extensions =\r\n glfwGetRequiredInstanceExtensions(&glfw_extension_count);\r\n\r\n vector extensions(glfw_extension_count);\r\n std::copy_n(glfw_extensions, glfw_extension_count, begin(extensions));\r\n\r\n return extensions;\r\n}\r\n\r\n\/\/ vim:set et ts=2 sw=0 sts=0:\r\n\r\n<|endoftext|>"} {"text":"\/\/\r\n\/\/#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"GPIOClass.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid Pulse(GPIOClass* pin, double cycles);\r\nvoid Wait(double seconds);\r\nclock_t timer;\r\ndouble time_to_complete;\r\ndouble resolution = 1000;\r\n\r\n#define PI 4*atan(1)\r\n\r\nint main (int argc, char *argv[]) {\r\n\tstring type = argv[1];\r\n\ttransform(type.begin(), type.end(), type.begin(), :: tolower);\r\n\t\/\/ lets assume that the way to run this is\r\n\t\/\/ pwm.exe [rising\/falling\/sine\/constant]\r\n\tif (argc != 2) {\r\n\t\tcout << \"Usage: pwm [rising\/falling\/sine\/constant\/blink]\" << endl;\r\n\t\treturn -1;\r\n\t}\r\n\r\n\twhile (time_to_complete <= 0) {\r\n\t\tcout << \"Input How Long To Run (in seconds)\" << endl;\r\n\t\tcin >> time_to_complete;\r\n\t}\r\n\r\n\tGPIOClass* out1 = new GPIOClass(\"4\");\r\n\tGPIOClass* in2 = new GPIOClass(\"17\");\r\n\r\n\tout1->export_gpio();\r\n\tin2->export_gpio();\r\n\r\n\tout1->setdir_gpio(\"out\");\r\n\tin2->setdir_gpio(\"in\");\r\n\r\n\tcout << \"Pins are setup.\" << endl;\r\n\t\/\/ avoiding flickering will be at 100hz\r\n\t\/\/ aka turn on and off 100 times a sec\r\n\t\/\/ a cycle of 0 is off\r\n\t\/\/ a cycle of 100 is on\r\n\r\n\tif (type == \"rising\") {\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tfor(int i = 0 ; i < time_to_complete; i++ ){\r\n\t\t\t\tPulse(out1, sin((PI\/2) * (i\/time_to_complete)));\r\n\t\t\t\tWait(sin((PI\/2) * (i\/time_to_complete)));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (type == \"falling\") {\r\n\r\n\t}\r\n\tif (type == \"sine\") {\r\n\r\n\t}\r\n\tif (type == \"constant\") {\r\n\t\tout1->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(time_to_complete); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tout1->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t}\r\n\tif (type == \"blink\") { \/\/ aka. TESTR\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tPulse(out1, 1 * resolution);\r\n\t\t\tWait(0.5);\r\n\t\t}\r\n\t}\r\n\tcout << \"Done.\" << endl;\r\n}\r\n\r\n\/\/1 cycle is 1\/100th of a second\r\n\/\/100 cycles is 1 sec\r\nvoid Pulse(GPIOClass* pin, double cycles) {\r\n\tbool running = true;\r\n\twhile (running) {\r\n\t\tpin->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(cycles \/ resolution); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tpin->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t\trunning = false; \/\/ this is unnessesary but could be useful if modified a bit.\r\n\t}\r\n}\r\n\r\nvoid Wait ( double seconds )\r\n{\r\n\tclock_t endwait;\r\n\tendwait = clock () + seconds * CLOCKS_PER_SEC ;\r\n\twhile (clock() < endwait) {}\r\n}\r\nUpdate pwm.cpp\/\/\r\n\/\/#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"GPIOClass.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid Pulse(GPIOClass* pin, double cycles);\r\nvoid Wait(double seconds);\r\nclock_t timer;\r\ndouble time_to_complete;\r\ndouble resolution = 1000;\r\n\r\n#define PI 4*atan(1)\r\n\r\nint main (int argc, char *argv[]) {\r\n\tstring type = argv[1];\r\n\ttransform(type.begin(), type.end(), type.begin(), :: tolower);\r\n\t\/\/ lets assume that the way to run this is\r\n\t\/\/ pwm.exe [rising\/falling\/sine\/constant]\r\n\tif (argc != 2) {\r\n\t\tcout << \"Usage: pwm [rising\/falling\/sine\/constant\/blink]\" << endl;\r\n\t\treturn -1;\r\n\t}\r\n\r\n\twhile (time_to_complete <= 0) {\r\n\t\tcout << \"Input How Long To Run (in seconds)\" << endl;\r\n\t\tcin >> time_to_complete;\r\n\t}\r\n\r\n\tGPIOClass* out1 = new GPIOClass(\"4\");\r\n\tGPIOClass* in2 = new GPIOClass(\"17\");\r\n\r\n\tout1->export_gpio();\r\n\tin2->export_gpio();\r\n\r\n\tout1->setdir_gpio(\"out\");\r\n\tin2->setdir_gpio(\"in\");\r\n\r\n\tcout << \"Pins are setup.\" << endl;\r\n\t\/\/ avoiding flickering will be at 100hz\r\n\t\/\/ aka turn on and off 100 times a sec\r\n\t\/\/ a cycle of 0 is off\r\n\t\/\/ a cycle of 100 is on\r\n\r\n\tif (type == \"rising\") {\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\t\tPulse(out1, sin((PI\/2) * (time_to_complete\/finish)));\r\n\t\t\t\tWait(sin((PI\/2) * (time_to_complete\/finish)));\r\n\t\t}\r\n\t}\r\n\tif (type == \"falling\") {\r\n\r\n\t}\r\n\tif (type == \"sine\") {\r\n\r\n\t}\r\n\tif (type == \"constant\") {\r\n\t\tout1->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(time_to_complete); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tout1->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t}\r\n\tif (type == \"blink\") { \/\/ aka. TESTR\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tPulse(out1, 1 * resolution);\r\n\t\t\tWait(0.5);\r\n\t\t}\r\n\t}\r\n\tcout << \"Done.\" << endl;\r\n}\r\n\r\n\/\/1 cycle is 1\/100th of a second\r\n\/\/100 cycles is 1 sec\r\nvoid Pulse(GPIOClass* pin, double cycles) {\r\n\tbool running = true;\r\n\twhile (running) {\r\n\t\tpin->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(cycles \/ resolution); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tpin->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t\trunning = false; \/\/ this is unnessesary but could be useful if modified a bit.\r\n\t}\r\n}\r\n\r\nvoid Wait ( double seconds )\r\n{\r\n\tclock_t endwait;\r\n\tendwait = clock () + seconds * CLOCKS_PER_SEC ;\r\n\twhile (clock() < endwait) {}\r\n}\r\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_PRIM_ARR_FUN_VALUE_OF_HPP\n#define STAN_MATH_PRIM_ARR_FUN_VALUE_OF_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Convert a std::vector of type T to a std::vector of\n * child_type::type.\n *\n * @tparam T Scalar type in std::vector\n * @param[in] x std::vector to be converted\n * @return std::vector of values\n **\/\ntemplate \ninline std::vector::type> value_of(\n const std::vector& x) {\n size_t size = x.size();\n std::vector::type> result(size);\n for (size_t i = 0; i < size; i++)\n result[i] = value_of(x[i]);\n return result;\n}\n\n\/**\n * Return the specified argument.\n *\n *

See value_of(T)<\/code> for a polymorphic\n * implementation using static casts.\n *\n *

This inline pass-through no-op should be compiled away.\n *\n * @param x Specified std::vector.\n * @return Specified std::vector.\n *\/\ntemplate <>\ninline const std::vector& value_of(const std::vector& x) {\n return x;\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\nvalue_of for std::vectors didn't have a template to specialize from, so I made it just a plain overload and not a template specialization (Issue #968)#ifndef STAN_MATH_PRIM_ARR_FUN_VALUE_OF_HPP\n#define STAN_MATH_PRIM_ARR_FUN_VALUE_OF_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Convert a std::vector of type T to a std::vector of\n * child_type::type.\n *\n * @tparam T Scalar type in std::vector\n * @param[in] x std::vector to be converted\n * @return std::vector of values\n **\/\ntemplate \ninline std::vector::type> value_of(\n const std::vector& x) {\n size_t size = x.size();\n std::vector::type> result(size);\n for (size_t i = 0; i < size; i++)\n result[i] = value_of(x[i]);\n return result;\n}\n\n\/**\n * Return the specified argument.\n *\n *

See value_of(T)<\/code> for a polymorphic\n * implementation using static casts.\n *\n *

This inline pass-through no-op should be compiled away.\n *\n * @param x Specified std::vector.\n * @return Specified std::vector.\n *\/\ninline const std::vector& value_of(const std::vector& x) {\n return x;\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n<|endoftext|>"} {"text":"\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#include \"config.h\"\n\n#include \n#include \n\n#include \n\n#include \"common.hh\"\n\nvoid busywait(const int ms)\n{\n \/\/ \"round\" up to next full 10 ms to align with native timer res\n const int milliseconds = (ms\/10)*10 + 10;\n timeval start, end;\n gettimeofday(&start, NULL);\n do {\n gettimeofday(&end, NULL);\n } while (((end.tv_sec - start.tv_sec)*1e6) + ((end.tv_usec - start.tv_usec)) < milliseconds*1000);\n} \/\/ ... busywait(...)\n\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Test {\nnamespace internal {\n\n\nstd::pair< size_t, ssize_t > convert_to_scientific(const double number, const size_t precision)\n{\n \/\/ see http:\/\/www.mathworks.com\/matlabcentral\/newsreader\/view_thread\/151859\n const double sign = (number > 0.0) ? 1.0 : -1.0;\n const double tmp = std::log10(std::abs(number));\n ssize_t exponent = ((tmp > 0) ? 1 : -1) * std::floor(std::abs(tmp));\n double coefficient = sign * std::pow(10.0, tmp - exponent);\n if (std::abs(coefficient) < 1.0) {\n coefficient *= 10.0;\n exponent -= 1;\n }\n const double factor = std::pow(10, precision);\n\/\/ std::cout << \"number = \" << number << std::endl;\n\/\/ std::cout << \"exponent = \" << exponent << std::endl;\n\/\/ std::cout << \"coefficient = \" << coefficient << std::endl;\n\/\/ std::cout << \"scaled = \" << std::round(factor * coefficient) << std::endl;\n\/\/ std::cout << \"size_t(scaled) = \" << size_t(std::round(factor * coefficient)) << std::endl << std::endl;\n\n return std::make_pair(size_t(std::round(factor * coefficient)), exponent);\n} \/\/ ... convert_to_scientific(...)\n\n\n} \/\/ namespace internal\n\n\nvoid check_eoc_study_for_success(const Dune::Stuff::Common::ConvergenceStudy& study,\n const std::map< std::string, std::vector< double > >& results_map)\n{\n for (const auto& norm : study.used_norms()) {\n const auto expected_results = study.expected_results(norm);\n const auto results_search = results_map.find(norm);\n EXPECT_NE(results_search, results_map.end())\n << \" norm = \" << norm;\n const auto& actual_results = results_search->second;\n EXPECT_LE(actual_results.size(), expected_results.size())\n << \" norm = \" << norm;\n for (size_t ii = 0; ii < actual_results.size(); ++ii) {\n const auto actual_result = internal::convert_to_scientific(actual_results[ii], 2);\n const auto expected_result = internal::convert_to_scientific(expected_results[ii], 2);\n const auto actual_exponent = actual_result.second;\n const auto expected_exponent = expected_result.second;\n EXPECT_EQ(actual_exponent, expected_exponent)\n << \" Exponent comparison (in scientific notation, precision 2) failed for\\n\"\n << \" norm: \" << norm << \"\\n\"\n << \" actual_results[\" << ii << \"] = \" << actual_results[ii] << \"\\n\"\n << \" expected_results[\" << ii << \"] = \" << expected_results[ii];\n const auto actual_coefficient = actual_result.first;\n const auto expected_coefficient = expected_result.first;\n EXPECT_EQ(actual_coefficient, expected_coefficient)\n << \" Coefficient comparison (in scientific notation, precision 2) failed for\\n\"\n << \" norm: \" << norm << \"\\n\"\n << \" actual_results[\" << ii << \"] = \" << actual_results[ii] << \"\\n\"\n << \" expected_results[\" << ii << \"] = \" << expected_results[ii];\n }\n }\n} \/\/ ... check_for_success(...)\n\n\n} \/\/ namespace Test\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n[test.common] prevent check_eoc_study_for_success() from segfaulting\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#include \"config.h\"\n\n#include \n#include \n\n#include \n\n#include \"common.hh\"\n\nvoid busywait(const int ms)\n{\n \/\/ \"round\" up to next full 10 ms to align with native timer res\n const int milliseconds = (ms\/10)*10 + 10;\n timeval start, end;\n gettimeofday(&start, NULL);\n do {\n gettimeofday(&end, NULL);\n } while (((end.tv_sec - start.tv_sec)*1e6) + ((end.tv_usec - start.tv_usec)) < milliseconds*1000);\n} \/\/ ... busywait(...)\n\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Test {\nnamespace internal {\n\n\nstd::pair< size_t, ssize_t > convert_to_scientific(const double number, const size_t precision)\n{\n \/\/ see http:\/\/www.mathworks.com\/matlabcentral\/newsreader\/view_thread\/151859\n const double sign = (number > 0.0) ? 1.0 : -1.0;\n const double tmp = std::log10(std::abs(number));\n ssize_t exponent = ((tmp > 0) ? 1 : -1) * std::floor(std::abs(tmp));\n double coefficient = sign * std::pow(10.0, tmp - exponent);\n if (std::abs(coefficient) < 1.0) {\n coefficient *= 10.0;\n exponent -= 1;\n }\n const double factor = std::pow(10, precision);\n\/\/ std::cout << \"number = \" << number << std::endl;\n\/\/ std::cout << \"exponent = \" << exponent << std::endl;\n\/\/ std::cout << \"coefficient = \" << coefficient << std::endl;\n\/\/ std::cout << \"scaled = \" << std::round(factor * coefficient) << std::endl;\n\/\/ std::cout << \"size_t(scaled) = \" << size_t(std::round(factor * coefficient)) << std::endl << std::endl;\n\n return std::make_pair(size_t(std::round(factor * coefficient)), exponent);\n} \/\/ ... convert_to_scientific(...)\n\n\n} \/\/ namespace internal\n\n\nvoid check_eoc_study_for_success(const Dune::Stuff::Common::ConvergenceStudy& study,\n const std::map< std::string, std::vector< double > >& results_map)\n{\n for (const auto& norm : study.used_norms()) {\n const auto expected_results = study.expected_results(norm);\n const auto results_search = results_map.find(norm);\n EXPECT_NE(results_search, results_map.end())\n << \" norm = \" << norm;\n if (results_search == results_map.end())\n return;\n const auto& actual_results = results_search->second;\n EXPECT_LE(actual_results.size(), expected_results.size())\n << \" norm = \" << norm;\n if (actual_results.size() > expected_results.size())\n return;\n for (size_t ii = 0; ii < actual_results.size(); ++ii) {\n const auto actual_result = internal::convert_to_scientific(actual_results[ii], 2);\n const auto expected_result = internal::convert_to_scientific(expected_results[ii], 2);\n const auto actual_exponent = actual_result.second;\n const auto expected_exponent = expected_result.second;\n EXPECT_EQ(actual_exponent, expected_exponent)\n << \" Exponent comparison (in scientific notation, precision 2) failed for\\n\"\n << \" norm: \" << norm << \"\\n\"\n << \" actual_results[\" << ii << \"] = \" << actual_results[ii] << \"\\n\"\n << \" expected_results[\" << ii << \"] = \" << expected_results[ii];\n if (actual_exponent != expected_exponent)\n return;\n const auto actual_coefficient = actual_result.first;\n const auto expected_coefficient = expected_result.first;\n EXPECT_EQ(actual_coefficient, expected_coefficient)\n << \" Coefficient comparison (in scientific notation, precision 2) failed for\\n\"\n << \" norm: \" << norm << \"\\n\"\n << \" actual_results[\" << ii << \"] = \" << actual_results[ii] << \"\\n\"\n << \" expected_results[\" << ii << \"] = \" << expected_results[ii];\n }\n }\n} \/\/ ... check_for_success(...)\n\n\n} \/\/ namespace Test\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_REV_CORE_ARENA_MATRIX_HPP\n#define STAN_MATH_REV_CORE_ARENA_MATRIX_HPP\n\n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Equivalent to `Eigen::Matrix`, except that the data is stored on AD stack.\n * That makes these objects triviali destructible and usable in `vari`s.\n *\n * @tparam MatrixType Eigen matrix type this works as (`MatrixXd`, `VectorXd`\n * ...)\n *\/\ntemplate \nclass arena_matrix : public Eigen::Map {\n public:\n using Scalar = value_type_t;\n using Base = Eigen::Map;\n using PlainObject = std::decay_t;\n static constexpr int RowsAtCompileTime = MatrixType::RowsAtCompileTime;\n static constexpr int ColsAtCompileTime = MatrixType::ColsAtCompileTime;\n\n \/**\n * Default constructor.\n *\/\n arena_matrix()\n : Base::Map(nullptr,\n RowsAtCompileTime == Eigen::Dynamic ? 0 : RowsAtCompileTime,\n ColsAtCompileTime == Eigen::Dynamic ? 0 : ColsAtCompileTime) {\n }\n\n \/**\n * Constructs `arena_matrix` with given number of rows and columns.\n * @param rows number of rows\n * @param cols number of columns\n *\/\n arena_matrix(Eigen::Index rows, Eigen::Index cols)\n : Base::Map(ChainableStack::instance_->memalloc_.alloc_array(\n rows * cols),\n rows, cols) {}\n\n \/**\n * Constructs `arena_matrix` with given size. This only works if\n * `MatrixType` is row or col vector.\n * @param size number of elements\n *\/\n explicit arena_matrix(Eigen::Index size)\n : Base::Map(\n ChainableStack::instance_->memalloc_.alloc_array(size),\n size) {}\n\n \/**\n * Constructs `arena_matrix` from an expression.\n * @param other expression\n *\/\n template * = nullptr>\n arena_matrix(const T& other) \/\/ NOLINT\n : Base::Map(ChainableStack::instance_->memalloc_.alloc_array(\n other.size()),\n other.rows(), other.cols()) {\n *this = other;\n }\n \/**\n * Constructs `arena_matrix` from an expression.\n * @param other expression\n *\/\n arena_matrix(const Base& other) \/\/ NOLINT\n : Base::Map(other) {}\n\n \/**\n * Copy constructor.\n * @param other matrix to copy from\n *\/\n arena_matrix(const arena_matrix& other)\n : Base::Map(const_cast(other.data()), other.rows(),\n other.cols()) {}\n\n \/\/ without this using, compiler prefers combination of implicit construction\n \/\/ and copy assignment to the inherited operator when assigned an expression\n using Base::operator=;\n\n \/**\n * Copy assignment operator.\n * @param other matrix to copy from\n * @return `*this`\n *\/\n arena_matrix& operator=(const arena_matrix& other) {\n \/\/ placement new changes what data map points to - there is no allocation\n new (this)\n Base(const_cast(other.data()), other.rows(), other.cols());\n return *this;\n }\n\n \/**\n * Assignment operator for assigning an expression.\n * @param a expression to evaluate into this\n * @return `*this`\n *\/\n template \n arena_matrix& operator=(const T& a) {\n \/\/ placement new changes what data map points to - there is no allocation\n new (this)\n Base(ChainableStack::instance_->memalloc_.alloc_array(a.size()),\n a.rows(), a.cols());\n Base::operator=(a);\n return *this;\n }\n};\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\nnamespace Eigen {\nnamespace internal {\n\ntemplate \nstruct traits> {\n using base = traits>;\n enum {\n PlainObjectTypeInnerSize = base::PlainObjectTypeInnerSize,\n InnerStrideAtCompileTime = base::InnerStrideAtCompileTime,\n OuterStrideAtCompileTime = base::OuterStrideAtCompileTime,\n Alignment = base::Alignment,\n PlainObjectTypeInnerSize = base::Flags\n };\n};\n\n} \/\/ namespace internal\n} \/\/ namespace Eigen\n\n#endif\nanother typo#ifndef STAN_MATH_REV_CORE_ARENA_MATRIX_HPP\n#define STAN_MATH_REV_CORE_ARENA_MATRIX_HPP\n\n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Equivalent to `Eigen::Matrix`, except that the data is stored on AD stack.\n * That makes these objects triviali destructible and usable in `vari`s.\n *\n * @tparam MatrixType Eigen matrix type this works as (`MatrixXd`, `VectorXd`\n * ...)\n *\/\ntemplate \nclass arena_matrix : public Eigen::Map {\n public:\n using Scalar = value_type_t;\n using Base = Eigen::Map;\n using PlainObject = std::decay_t;\n static constexpr int RowsAtCompileTime = MatrixType::RowsAtCompileTime;\n static constexpr int ColsAtCompileTime = MatrixType::ColsAtCompileTime;\n\n \/**\n * Default constructor.\n *\/\n arena_matrix()\n : Base::Map(nullptr,\n RowsAtCompileTime == Eigen::Dynamic ? 0 : RowsAtCompileTime,\n ColsAtCompileTime == Eigen::Dynamic ? 0 : ColsAtCompileTime) {\n }\n\n \/**\n * Constructs `arena_matrix` with given number of rows and columns.\n * @param rows number of rows\n * @param cols number of columns\n *\/\n arena_matrix(Eigen::Index rows, Eigen::Index cols)\n : Base::Map(ChainableStack::instance_->memalloc_.alloc_array(\n rows * cols),\n rows, cols) {}\n\n \/**\n * Constructs `arena_matrix` with given size. This only works if\n * `MatrixType` is row or col vector.\n * @param size number of elements\n *\/\n explicit arena_matrix(Eigen::Index size)\n : Base::Map(\n ChainableStack::instance_->memalloc_.alloc_array(size),\n size) {}\n\n \/**\n * Constructs `arena_matrix` from an expression.\n * @param other expression\n *\/\n template * = nullptr>\n arena_matrix(const T& other) \/\/ NOLINT\n : Base::Map(ChainableStack::instance_->memalloc_.alloc_array(\n other.size()),\n other.rows(), other.cols()) {\n *this = other;\n }\n \/**\n * Constructs `arena_matrix` from an expression.\n * @param other expression\n *\/\n arena_matrix(const Base& other) \/\/ NOLINT\n : Base::Map(other) {}\n\n \/**\n * Copy constructor.\n * @param other matrix to copy from\n *\/\n arena_matrix(const arena_matrix& other)\n : Base::Map(const_cast(other.data()), other.rows(),\n other.cols()) {}\n\n \/\/ without this using, compiler prefers combination of implicit construction\n \/\/ and copy assignment to the inherited operator when assigned an expression\n using Base::operator=;\n\n \/**\n * Copy assignment operator.\n * @param other matrix to copy from\n * @return `*this`\n *\/\n arena_matrix& operator=(const arena_matrix& other) {\n \/\/ placement new changes what data map points to - there is no allocation\n new (this)\n Base(const_cast(other.data()), other.rows(), other.cols());\n return *this;\n }\n\n \/**\n * Assignment operator for assigning an expression.\n * @param a expression to evaluate into this\n * @return `*this`\n *\/\n template \n arena_matrix& operator=(const T& a) {\n \/\/ placement new changes what data map points to - there is no allocation\n new (this)\n Base(ChainableStack::instance_->memalloc_.alloc_array(a.size()),\n a.rows(), a.cols());\n Base::operator=(a);\n return *this;\n }\n};\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\nnamespace Eigen {\nnamespace internal {\n\ntemplate \nstruct traits> {\n using base = traits>;\n enum {\n PlainObjectTypeInnerSize = base::PlainObjectTypeInnerSize,\n InnerStrideAtCompileTime = base::InnerStrideAtCompileTime,\n OuterStrideAtCompileTime = base::OuterStrideAtCompileTime,\n Alignment = base::Alignment,\n Flags = base::Flags\n };\n};\n\n} \/\/ namespace internal\n} \/\/ namespace Eigen\n\n#endif\n<|endoftext|>"} {"text":"#include \"WinHTTPClient.h\"\n\n#include \"BasicAuth.h\"\n\n#include \n#include \n#include \n#include \n\n#if defined(WIN32) || defined(WIN64) \n#include \n#include \n\n#define strcasecmp _stricmp\n#endif\n\n#include \n#include \n#include \n\nusing namespace std;\n\nstatic wstring from_utf8(const std::string & s) {\n std::unique_ptr tmp(new wchar_t[s.size() + 1]);\n auto r = MultiByteToWideChar(CP_UTF8, 0, s.data(), -1, tmp.get(), s.size() + 1);\n return wstring(tmp.get(), static_cast(r));\n}\n\nstatic string to_utf8(const wstring & s) {\n std::unique_ptr tmp(new char[4 * s.size() + 1]);\n auto r = WideCharToMultiByte(CP_UTF8,\n\t\t\t 0,\n\t\t\t s.data(),\n\t\t\t -1,\n\t\t\t tmp.get(),\n\t\t\t 4*s.size() + 1,\n\t\t\t NULL,\n\t\t\t NULL);\n return string(tmp.get(), static_cast(r)); \n}\n\nstatic long long get_current_time_ms() {\n#ifdef WIN32\n FILETIME ft_now;\n GetSystemTimeAsFileTime(&ft_now);\n long long ll_now = (LONGLONG)ft_now.dwLowDateTime + (((LONGLONG)ft_now.dwHighDateTime) << 32LL);\n ll_now \/= 10000;\n return ll_now - 116444736000000000LL;\n#else\n struct timeval tv;\n int r = gettimeofday(&tv, 0);\n if (r == 0) {\n return (long long)1000 * tv.tv_sec + tv.tv_usec \/ 1000;\n } else {\n return 0;\n }\n#endif\n}\n\nclass WinHTTPClient : public HTTPClient {\n public:\n WinHTTPClient(const std::string& user_agent, bool enable_cookies = true, bool enable_keepalive = true)\n : HTTPClient(user_agent, enable_cookies, enable_keepalive)\n {\n auto ua_text = from_utf8(getUserAgent());\n \/\/ Use WinHttpOpen to obtain a session handle.\n session_ = WinHttpOpen(ua_text.c_str(),\n WINHTTP_ACCESS_TYPE_NO_PROXY,\n WINHTTP_NO_PROXY_NAME,\n WINHTTP_NO_PROXY_BYPASS, 0);\n\n DWORD decompression = WINHTTP_DECOMPRESSION_FLAG_ALL;\n WinHttpSetOption(session_, WINHTTP_OPTION_DECOMPRESSION, &decompression, sizeof(decompression));\n\n#if 0\n DWORD protocols = WINHTTP_PROTOCOL_FLAG_HTTP2;\n WinHttpSetOption(session_, WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL, &protocols, sizeof(protocols));\n DWORD secure_protocols = WINHTTP_FLAG_SECURE_PROTOCOL_ALL;\n WinHttpSetOption(session_, WINHTTP_OPTION_SECURE_PROTOCOLS, &secure_protocols, sizeof(secure_protocols));\n#endif\n }\n\n ~WinHTTPClient() {\n WinHttpCloseHandle(session_);\n }\n\n void request(const HTTPRequest & req, const Authorization & auth, HTTPClientInterface & callback) override {\n URI uri(req.getURI());\n \n auto target_scheme = uri.getScheme();\n auto target_host = from_utf8(uri.getDomain());\n auto target_port = uri.getPort();\n\n auto target_path0 = uri.getPath();\n if (!uri.getQueryString().empty()) target_path0 += \"?\" + uri.getQueryString();\n\n auto target_path = from_utf8(target_path0);\n\n bool is_secure = false;\n if (target_scheme == \"http\") {\n if (!target_port) target_port = INTERNET_DEFAULT_HTTP_PORT;\n } else if (target_scheme == \"https\") {\n if (!target_port) target_port = INTERNET_DEFAULT_HTTPS_PORT;\n is_secure = true;\n } else {\n return;\n }\n \n auto hConnect = WinHttpConnect(session_, target_host.c_str(), target_port, 0);\n if (hConnect) { \n string tmp0 = \"created handle for host: \" + uri.getDomain() + \", port: \" + to_string(target_port) + \"\\n\";\n OutputDebugStringA(tmp0.c_str());\n\n \/\/ WINHTTP_OPTION_CONNECT_TIMEOUT (ms)\n \/\/ WINHTTP_OPTION_RECEIVE_RESPONSE_TIMEOUT (ms)\n \/\/ WINHTTP_OPTION_RECEIVE_TIMEOUT (ms)\n \/\/ WINHTTP_OPTION_RESOLVE_TIMEOUT (ms)\n \/\/ WINHTTP_OPTION_SEND_TIMEOUT (ms)\n \n wstring request_type;\n bool has_data = true;\n switch (req.getType()) {\n case HTTPRequest::GET:\n\trequest_type = L\"GET\";\n\thas_data = false;\n\tbreak;\n case HTTPRequest::POST:\n\trequest_type = L\"POST\";\n\tbreak;\n case HTTPRequest::OPTIONS:\n\trequest_type = L\"OPTIONS\";\n\tbreak;\n } \n\n DWORD dwFlags = WINHTTP_FLAG_ESCAPE_DISABLE | WINHTTP_FLAG_ESCAPE_DISABLE_QUERY;\n if (is_secure) dwFlags |= WINHTTP_FLAG_SECURE;\n\t \n auto hRequest = WinHttpOpenRequest(hConnect, request_type.c_str(), target_path.c_str(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, dwFlags);\n if (hRequest) {\n\tDWORD disabled_features = 0;\n\tif (!req.getFollowLocation()) disabled_features |= WINHTTP_DISABLE_REDIRECTS;\n\tif (!enable_keepalive) disabled_features |= WINHTTP_DISABLE_KEEP_ALIVE;\n\tif (!enable_cookies) disabled_features |= WINHTTP_DISABLE_COOKIES;\n\tWinHttpSetOption(hRequest, WINHTTP_OPTION_DISABLE_FEATURE, &disabled_features, sizeof(disabled_features));\n\n\tstring tmp2 = \"created request, path: \" + target_path0 + \"\\n\";\n\tOutputDebugStringA(tmp2.c_str());\n\n\tmap combined_headers;\n\tfor (auto & hd : default_headers) {\n\t combined_headers[hd.first] = hd.second; \n\t}\n\tfor (auto & hd : req.getHeaders()) {\n\t combined_headers[hd.first] = hd.second;\n\t}\n\t \n\tif (req.getType() == HTTPRequest::POST || req.getType() == HTTPRequest::OPTIONS) {\n\t if (!req.getContentType().empty()) {\n\t combined_headers[\"Content-Type\"] = req.getContentType();\n\t }\n\t}\n\n\tconst BasicAuth * basic = dynamic_cast(&auth);\n\tif (basic) {\n\t \/\/ FIXME: implement\n\t} else {\n\t string auth_header = auth.createHeader();\n\t if (!auth_header.empty()) {\n\t combined_headers[auth.getHeaderName()] = auth_header;\n\t }\n\t}\n\n\tfor (auto & [ name, value ] : combined_headers) {\n\t auto header0 = name + \": \" + value;\n\t auto header = from_utf8(header0 + \"\\r\\n\");\n\t string tmp3 = \"adding header: \" + header0 + \"\\n\";\n\t OutputDebugStringA(tmp3.c_str());\n\n\t WinHttpAddRequestHeaders(hRequest, header.c_str(), -1, WINHTTP_ADDREQ_FLAG_REPLACE | WINHTTP_ADDREQ_FLAG_ADD);\n\t}\n\t \n\tauto & postData = req.getContent();\n\t\n\tOutputDebugStringA(\"Sending request\\n\");\n\n\tbool req_r = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, (void*)postData.data(), postData.size(), postData.size(), 0);\n\n\tif (is_secure && !req_r) {\n\t OutputDebugStringA(\"Retrying request\\n\");\n\t DWORD security_flags = SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE | SECURITY_FLAG_IGNORE_ALL_CERT_ERRORS;\n\t WinHttpSetOption(hRequest, WINHTTP_OPTION_SECURITY_FLAGS, &security_flags, sizeof(security_flags));\n\t req_r = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, (void*)postData.data(), postData.size(), postData.size(), 0);\n\t}\n\n\tif (req_r && WinHttpReceiveResponse(hRequest, NULL)) {\n\t OutputDebugStringA(\"Received response\\n\");\n\n\t bool terminate = false;\n\n#if 0\n\t DWORD dwStatusCode = 0;\n\t DWORD dwSize = sizeof(dwStatusCode);\n\n\t if (WinHttpQueryHeaders(hRequest,\n\t WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,\n\t WINHTTP_HEADER_NAME_BY_INDEX,\n\t &dwStatusCode, &dwSize, WINHTTP_NO_HEADER_INDEX)) {\n\t string tmp3 = \"got result code: \" + to_string(dwStatusCode) + \"\\n\";\n\t OutputDebugStringA(tmp3.c_str());\n\t callback.handleResultCode(dwStatusCode);\n\t }\n\t else {\n\t string tmp3 = \"failed to get response code: \" + to_string(GetLastError());\n\t OutputDebugStringA(tmp3.c_str());\n\t }\n#endif\n\t DWORD headerSize = 0;\n\t WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, WINHTTP_HEADER_NAME_BY_INDEX, NULL, &headerSize, WINHTTP_NO_HEADER_INDEX);\n\n\t string tmp3 = \"got header size: \" + to_string(headerSize) + \"\\n\";\n\t OutputDebugStringA(tmp3.c_str());\n\t \/\/ Allocate buffer by header length\n\t \/\/ If the function fails and ERROR_INSUFFICIENT_BUFFER is returned, lpdwBufferLength specifies the number of bytes that the application must allocate to receive the string.\n\t if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {\n\t wstring headerBuffer(headerSize \/ sizeof(wchar_t), 0);\n\t if (WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, WINHTTP_HEADER_NAME_BY_INDEX, headerBuffer.data(), &headerSize, WINHTTP_NO_HEADER_INDEX)) {\n\t string headers = to_utf8(headerBuffer);\n\t OutputDebugStringA(headers.c_str());\n\t if (!callback.handleHeaderChunk(headers.size(), headers.data())) {\n\t\tterminate = true;\n\t }\n\t } else {\n\t string tmp4 = \"Failed to get headers: \" + to_string(GetLastError()) + \"\\n\";\n\t OutputDebugStringA(tmp4.c_str());\n\t }\n\t } else {\n\t OutputDebugStringA(\"Failed to get headers\\n\");\n\t }\n\t \n\t while (!terminate) {\n\t \/\/ Check for available data to get data size in bytes\n\t DWORD dwSize = 0;\n\t if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) {\n\t break;\n\t }\n\t if (!dwSize) {\n\t break; \/\/data size 0 \n\t }\n\n\t \/\/ Allocate buffer by data size\n\t unique_ptr outBuffer(new char[dwSize + 1]);\n\t \/\/ Read data from server\n\t DWORD dwDownloaded = 0;\n\t if (WinHttpReadData(hRequest, outBuffer.get(), dwSize, &dwDownloaded)) {\n\t bool r = callback.handleChunk(dwDownloaded, outBuffer.get());\n\t if (!r) break;\n\t }\n\t else {\n\t break;\n\t }\n\n\t if (!dwDownloaded) break;\n\t if (!callback.onIdle()) break;\n\t }\n\n\t callback.handleDisconnect();\n\t} else {\n\t string tmp3 = \"connection failed: \" + to_string(GetLastError()) + \"\\n\";\n\t OutputDebugStringA(tmp3.c_str());\t \n\t}\n\t \n\tWinHttpCloseHandle(hRequest);\n }\n WinHttpCloseHandle(hConnect);\n }\n }\n \n void clearCookies() override {\n }\n \nprotected:\n HINTERNET session_;\n};\n \n\nstd::unique_ptr\nWinHTTPClientFactory::createClient2(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) {\n return std::unique_ptr(new WinHTTPClient(_user_agent, _enable_cookies, _enable_keepalive));\n}\nAdd error reporting#include \"WinHTTPClient.h\"\n\n#include \"BasicAuth.h\"\n\n#include \n#include \n#include \n#include \n\n#if defined(WIN32) || defined(WIN64) \n#include \n#include \n\n#define strcasecmp _stricmp\n#endif\n\n#include \n#include \n#include \n\nusing namespace std;\n\nstatic wstring from_utf8(const std::string & s) {\n std::unique_ptr tmp(new wchar_t[s.size() + 1]);\n auto r = MultiByteToWideChar(CP_UTF8, 0, s.data(), -1, tmp.get(), s.size() + 1);\n return wstring(tmp.get(), static_cast(r));\n}\n\nstatic string to_utf8(const wstring & s) {\n std::unique_ptr tmp(new char[4 * s.size() + 1]);\n auto r = WideCharToMultiByte(CP_UTF8,\n\t\t\t 0,\n\t\t\t s.data(),\n\t\t\t -1,\n\t\t\t tmp.get(),\n\t\t\t 4*s.size() + 1,\n\t\t\t NULL,\n\t\t\t NULL);\n return string(tmp.get(), static_cast(r)); \n}\n\nstatic long long get_current_time_ms() {\n#ifdef WIN32\n FILETIME ft_now;\n GetSystemTimeAsFileTime(&ft_now);\n long long ll_now = (LONGLONG)ft_now.dwLowDateTime + (((LONGLONG)ft_now.dwHighDateTime) << 32LL);\n ll_now \/= 10000;\n return ll_now - 116444736000000000LL;\n#else\n struct timeval tv;\n int r = gettimeofday(&tv, 0);\n if (r == 0) {\n return (long long)1000 * tv.tv_sec + tv.tv_usec \/ 1000;\n } else {\n return 0;\n }\n#endif\n}\n\nclass WinHTTPClient : public HTTPClient {\n public:\n WinHTTPClient(const std::string& user_agent, bool enable_cookies = true, bool enable_keepalive = true)\n : HTTPClient(user_agent, enable_cookies, enable_keepalive)\n {\n auto ua_text = from_utf8(getUserAgent());\n \/\/ Use WinHttpOpen to obtain a session handle.\n session_ = WinHttpOpen(ua_text.c_str(),\n WINHTTP_ACCESS_TYPE_NO_PROXY,\n WINHTTP_NO_PROXY_NAME,\n WINHTTP_NO_PROXY_BYPASS, 0);\n\n DWORD decompression = WINHTTP_DECOMPRESSION_FLAG_ALL;\n WinHttpSetOption(session_, WINHTTP_OPTION_DECOMPRESSION, &decompression, sizeof(decompression));\n\n#if 0\n DWORD protocols = WINHTTP_PROTOCOL_FLAG_HTTP2;\n WinHttpSetOption(session_, WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL, &protocols, sizeof(protocols));\n DWORD secure_protocols = WINHTTP_FLAG_SECURE_PROTOCOL_ALL;\n WinHttpSetOption(session_, WINHTTP_OPTION_SECURE_PROTOCOLS, &secure_protocols, sizeof(secure_protocols));\n#endif\n }\n\n ~WinHTTPClient() {\n if (session_) {\n WinHttpCloseHandle(session_);\n }\n }\n\n void request(const HTTPRequest & req, const Authorization & auth, HTTPClientInterface & callback) override {\n if (!session_) {\n callback.handleErrorText(\"Not initialized\");\n return;\n }\n URI uri(req.getURI());\n \n auto target_scheme = uri.getScheme();\n auto target_host = from_utf8(uri.getDomain());\n auto target_port = uri.getPort();\n\n auto target_path0 = uri.getPath();\n if (!uri.getQueryString().empty()) target_path0 += \"?\" + uri.getQueryString();\n\n auto target_path = from_utf8(target_path0);\n\n bool is_secure = false;\n if (target_scheme == \"http\") {\n if (!target_port) target_port = INTERNET_DEFAULT_HTTP_PORT;\n } else if (target_scheme == \"https\") {\n if (!target_port) target_port = INTERNET_DEFAULT_HTTPS_PORT;\n is_secure = true;\n } else {\n return;\n }\n \n auto hConnect = WinHttpConnect(session_, target_host.c_str(), target_port, 0);\n if (!hConnect) {\n callback.handleErrorText(\"Could not create connection handle: \" + to_string(GetLastError()));\n } else { \n \/\/ WINHTTP_OPTION_CONNECT_TIMEOUT (ms)\n \/\/ WINHTTP_OPTION_RECEIVE_RESPONSE_TIMEOUT (ms)\n \/\/ WINHTTP_OPTION_RECEIVE_TIMEOUT (ms)\n \/\/ WINHTTP_OPTION_RESOLVE_TIMEOUT (ms)\n \/\/ WINHTTP_OPTION_SEND_TIMEOUT (ms)\n \n wstring request_type;\n bool has_data = true;\n switch (req.getType()) {\n case HTTPRequest::GET:\n\trequest_type = L\"GET\";\n\thas_data = false;\n\tbreak;\n case HTTPRequest::POST:\n\trequest_type = L\"POST\";\n\tbreak;\n case HTTPRequest::OPTIONS:\n\trequest_type = L\"OPTIONS\";\n\tbreak;\n } \n\n DWORD dwFlags = WINHTTP_FLAG_ESCAPE_DISABLE | WINHTTP_FLAG_ESCAPE_DISABLE_QUERY;\n if (is_secure) dwFlags |= WINHTTP_FLAG_SECURE;\n\t \n auto hRequest = WinHttpOpenRequest(hConnect, request_type.c_str(), target_path.c_str(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, dwFlags);\n if (!hRequest) {\n\tcallback.handleErrorText(\"Could not create request: \" + to_string(GetLastError()));\n } else {\n\tDWORD disabled_features = 0;\n\tif (!req.getFollowLocation()) disabled_features |= WINHTTP_DISABLE_REDIRECTS;\n\tif (!enable_keepalive) disabled_features |= WINHTTP_DISABLE_KEEP_ALIVE;\n\tif (!enable_cookies) disabled_features |= WINHTTP_DISABLE_COOKIES;\n\tif (!WinHttpSetOption(hRequest, WINHTTP_OPTION_DISABLE_FEATURE, &disabled_features, sizeof(disabled_features))) {\n\t OutputDebugStringA(\"Could not set options\");\n\t}\n\n\tmap combined_headers;\n\tfor (auto & hd : default_headers) {\n\t combined_headers[hd.first] = hd.second; \n\t}\n\tfor (auto & hd : req.getHeaders()) {\n\t combined_headers[hd.first] = hd.second;\n\t}\n\t \n\tif (req.getType() == HTTPRequest::POST || req.getType() == HTTPRequest::OPTIONS) {\n\t if (!req.getContentType().empty()) {\n\t combined_headers[\"Content-Type\"] = req.getContentType();\n\t }\n\t}\n\n\tconst BasicAuth * basic = dynamic_cast(&auth);\n\tif (basic) {\n\t \/\/ FIXME: implement\n\t} else {\n\t string auth_header = auth.createHeader();\n\t if (!auth_header.empty()) {\n\t combined_headers[auth.getHeaderName()] = auth_header;\n\t }\n\t}\n\n\tfor (auto & [ name, value ] : combined_headers) {\n\t auto header0 = name + \": \" + value;\n\t auto header = from_utf8(header0 + \"\\r\\n\");\n\t string tmp3 = \"adding header: \" + header0 + \"\\n\";\n\t OutputDebugStringA(tmp3.c_str());\n\n\t WinHttpAddRequestHeaders(hRequest, header.c_str(), -1, WINHTTP_ADDREQ_FLAG_REPLACE | WINHTTP_ADDREQ_FLAG_ADD);\n\t}\n\t \n\tauto & postData = req.getContent();\n\t\n\tOutputDebugStringA(\"Sending request\\n\");\n\n\tbool req_r = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, (void*)postData.data(), postData.size(), postData.size(), 0);\n\n\tif (is_secure && !req_r && GetLastError() == 12175) {\n\t OutputDebugStringA(\"Retrying request\\n\");\n\t DWORD security_flags = SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE | SECURITY_FLAG_IGNORE_ALL_CERT_ERRORS;\n\t WinHttpSetOption(hRequest, WINHTTP_OPTION_SECURITY_FLAGS, &security_flags, sizeof(security_flags));\n\t req_r = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, (void*)postData.data(), postData.size(), postData.size(), 0);\n\t}\n\n\tif (!req_r) {\n\t callback.handleErrorText(\"Could not send request: \" + to_string(GetLastError()));\n\t} else if (WinHttpReceiveResponse(hRequest, NULL)) {\n\t OutputDebugStringA(\"Received response\\n\");\n\n\t bool terminate = false;\n\n\t DWORD headerSize = 0;\n\t WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, WINHTTP_HEADER_NAME_BY_INDEX, NULL, &headerSize, WINHTTP_NO_HEADER_INDEX);\n\n\t \/\/ Allocate buffer by header length\n\t \/\/ If the function fails and ERROR_INSUFFICIENT_BUFFER is returned, lpdwBufferLength specifies the number of bytes that the application must allocate to receive the string.\n\t if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {\n\t wstring headerBuffer(headerSize \/ sizeof(wchar_t), 0);\n\t if (WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, WINHTTP_HEADER_NAME_BY_INDEX, headerBuffer.data(), &headerSize, WINHTTP_NO_HEADER_INDEX)) {\n\t string headers = to_utf8(headerBuffer);\n\t OutputDebugStringA(headers.c_str());\n\t if (!callback.handleHeaderChunk(headers.size(), headers.data())) {\n\t\tterminate = true;\n\t }\n\t } else {\n\t callback.handleErrorText(\"Failed to get headers: \" + to_string(GetLastError()));\n\t terminate = true;\n\t }\n\t } else {\n\t callback.handleErrorText(\"Failed to get headers: no headers\");\n\t terminate = true;\n\t }\n\t \n\t while (!terminate) {\n\t \/\/ Check for available data to get data size in bytes\n\t DWORD dwSize = 0;\n\t if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) {\n\t break;\n\t }\n\t if (!dwSize) {\n\t break; \/\/data size 0 \n\t }\n\n\t \/\/ Allocate buffer by data size\n\t unique_ptr outBuffer(new char[dwSize + 1]);\n\t \/\/ Read data from server\n\t DWORD dwDownloaded = 0;\n\t if (WinHttpReadData(hRequest, outBuffer.get(), dwSize, &dwDownloaded)) {\n\t bool r = callback.handleChunk(dwDownloaded, outBuffer.get());\n\t if (!r) break;\n\t }\n\t else {\n\t break;\n\t }\n\n\t if (!dwDownloaded) break;\n\t if (!callback.onIdle()) break;\n\t }\n\n\t callback.handleDisconnect();\n\t} else {\n\t callback.handleErrorText(\"Failed to receive response: \" + to_string(GetLastError()));\n\t}\n\t \n\tWinHttpCloseHandle(hRequest);\n }\n WinHttpCloseHandle(hConnect);\n }\n }\n \n void clearCookies() override {\n }\n \nprotected:\n HINTERNET session_;\n};\n \n\nstd::unique_ptr\nWinHTTPClientFactory::createClient2(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) {\n return std::unique_ptr(new WinHTTPClient(_user_agent, _enable_cookies, _enable_keepalive));\n}\n<|endoftext|>"} {"text":"\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999-2002 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * .\n *\/\n\/\/ Class header file\n#include \"KeyTable.hpp\"\n\n\n\n#include \n\n\n\n#include \n#include \n#include \n#include \n\n\n\n#include \n\n\n\n#include \n\n\n\n#include \"KeyDeclaration.hpp\"\n#include \"StylesheetExecutionContext.hpp\"\n#include \"XSLTProcessorException.hpp\"\n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\nconst MutableNodeRefList\tKeyTable::s_dummyList;\n\n\n\nKeyTable::KeyTable(\n\t\t\tXalanNode*\t\t\t\t\t\t\tstartNode,\n\t\t\tconst PrefixResolver&\t\t\t\tresolver,\n\t\t\tconst KeyDeclarationVectorType&\t\tkeyDeclarations,\n\t\t\tStylesheetExecutionContext&\t\t\texecutionContext) :\n\tm_keys()\n{\n XalanNode*\tpos = startNode;\n\n\tconst KeyDeclarationVectorType::size_type\tnDeclarations =\n\t\t\tkeyDeclarations.size();\n\n \/\/ Do a non-recursive pre-walk over the tree.\n while(0 != pos)\n {\n\t\t\/\/ We're going to have to walk the attribute list \n\t\t\/\/ if it's an element, so get the attributes.\n\t\tconst XalanNamedNodeMap*\tattrs = 0;\n\n\t\tint\t\t\t\t\t\t\tnNodes = 0;\n\n\t\tif(XalanNode::ELEMENT_NODE == pos->getNodeType())\n\t\t{\n\t\t\tattrs = pos->getAttributes();\n\n\t\t\tnNodes = attrs->getLength();\n \n\t\t\tif(0 == nNodes)\n\t\t\t{\n\t\t\t\tattrs = 0;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Walk the primary node, and each of the attributes.\n\t\t\/\/ This loop is a little strange... it is meant to always \n\t\t\/\/ execute once, then execute for each of the attributes.\n\t\tXalanNode*\ttestNode = pos;\n\n\t\tfor(int nodeIndex = -1; nodeIndex < nNodes;)\n\t\t{\n\t\t\t\/\/ Walk through each of the declarations made with xsl:key\n\t\t\tfor(unsigned int i = 0; i < nDeclarations; ++i)\n\t\t\t{\n\t\t\t\tconst KeyDeclaration&\tkd = keyDeclarations[i];\n\n\t\t\t\tif (executionContext.getInConstruction(kd) == true)\t\t\t\n\t\t\t\t{\n\t\t\t\t\tthrow XSLTProcessorException(\n\t\t\t\t\t\t\tTranscodeFromLocalCodePage(\"The use of the key() function in the \\\"match\\\" or \\\"use\\\" attribute of xsl:key is illegal!\"),\n\t\t\t\t\t\t\tTranscodeFromLocalCodePage(\"XSLTKeyIllegalKeyFunctionException\"));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\texecutionContext.beginConstruction(kd);\n\n\t\t\t\t\t\/\/ See if our node matches the given key declaration according to \n\t\t\t\t\t\/\/ the match attribute on xsl:key.\n\t\t\t\t\tassert(kd.getMatchPattern() != 0);\n\n\t\t\t\t\tconst XPath::eMatchScore\tscore =\n\t\t\t\t\t\t\tkd.getMatchPattern()->getMatchScore(testNode,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tresolver,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\texecutionContext);\n\n\t\t\t\t\tif(score != XPath::eMatchScoreNone)\n\t\t\t\t\t{\n\t\t\t\t\t\tprocessKeyDeclaration(\n\t\t\t\t\t\t\tm_keys,\n\t\t\t\t\t\t\tkd,\n\t\t\t\t\t\t\ttestNode,\n\t\t\t\t\t\t\tresolver,\n\t\t\t\t\t\t\texecutionContext);\n\t\t\t\t\t}\n\n\t\t\t\t\texecutionContext.endConstruction(kd);\n\t\t\t\t} \/\/ if (kd.getInConstruction() == true)\n\t\t\t} \/\/ end for(int i = 0; i < nDeclarations; ++i)\n\n\t\t\t++nodeIndex;\n\n\t\t\tif(0 != attrs)\n\t\t\t{\n\t\t\t\ttestNode = attrs->item(nodeIndex);\n\t\t\t}\n\t\t} \/\/ for(int nodeIndex = -1; nodeIndex < nNodes;)\n\n\t\t\/\/ The rest of this is getting the next prewalk position in \n\t\t\/\/ the tree.\n\t\tXalanNode*\tnextNode = pos->getFirstChild();\n\n\t\twhile(0 == nextNode)\n\t\t{\n\t\t\tif(startNode == pos)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnextNode = pos->getNextSibling();\n\n\t\t\t\tif(0 == nextNode)\n\t\t\t\t{\n\t\t\t\t\tpos = pos->getParentNode();\n\n\t\t\t\t\tif((startNode == pos) || (0 == pos))\n\t\t\t\t\t{\n\t\t\t\t\t\tnextNode = 0;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpos = nextNode;\n } \/\/ while(0 != pos)\n\n\tif (m_keys.empty() == false)\n\t{\n\t\tconst KeysMapType::iterator\t\ttheEnd = m_keys.end();\n\t\tKeysMapType::iterator\t\t\ttheCurrent = m_keys.begin();\n\t\tassert(theCurrent != theEnd);\n\n\t\tdo\n\t\t{\n\t\t\tNodeListMapType&\ttheCurrentNodeListMap = (*theCurrent).second;\n\n\t\t\tif (theCurrentNodeListMap.empty() == false)\n\t\t\t{\n\t\t\t\tconst NodeListMapType::iterator\t\ttheEnd = theCurrentNodeListMap.end();\n\t\t\t\tNodeListMapType::iterator\t\t\ttheCurrent = theCurrentNodeListMap.begin();\n\t\t\t\tassert(theCurrent != theEnd);\n\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\t(*theCurrent).second.setDocumentOrder();\n\n\t\t\t\t\t++theCurrent;\n\t\t\t\t}\n\t\t\t\twhile(theCurrent != theEnd);\n\t\t\t}\n\n\t\t\t++theCurrent;\n\t\t}\n\t\twhile(theCurrent != theEnd);\n\t}\t\n} \/\/ end constructor\n\n\n\nKeyTable::~KeyTable()\n{\n}\n\n\n\nconst MutableNodeRefList&\nKeyTable::getNodeSetByKey(\n\t\t\t\t\t const XalanQName&\t\t\tqname, \n\t\t\t\t\t const XalanDOMString&\t\tref) const\n{\n\tconst KeysMapType::const_iterator\ti = m_keys.find(qname);\n\n\tif (i != m_keys.end())\n\t{\n\t\tconst NodeListMapType&\ttheMap = (*i).second;\n\n\t\tconst NodeListMapType::const_iterator\tj = theMap.find(ref);\n\n\t\tif (j != theMap.end())\n\t\t{\n\t\t\treturn (*j).second;\n\t\t}\n\t}\n\n\t\/\/ It makes things much easier if we always return\n\t\/\/ a list of nodes. So this is just an empty one\n\t\/\/ to return when the ref is not found.\n\treturn s_dummyList;\n}\n\n\n\ninline void\naddIfNotFound(\n\t\t\tStylesheetExecutionContext&\t\texecutionContext,\n\t\t\tMutableNodeRefList&\t\t\t\ttheNodeList,\n\t\t\tXalanNode*\t\t\t\t\t\ttheNode)\n{\n\ttheNodeList.addNodeInDocOrder(theNode, executionContext);\n}\n\n\n\nvoid\nKeyTable::processKeyDeclaration(\n\t\t\tKeysMapType&\t\t\t\t\ttheKeys,\n\t\t\tconst KeyDeclaration&\t\t\tkd,\n\t\t\tXalanNode*\t\t\t\t\t\ttestNode,\n\t\t\tconst PrefixResolver&\t\t\tresolver,\n\t\t\tStylesheetExecutionContext&\t\texecutionContext)\n{\n\t\/\/ Query from the node, according the the select pattern in the\n\t\/\/ use attribute in xsl:key.\n\tassert(kd.getUse() != 0);\n\n\tconst XObjectPtr\txuse(kd.getUse()->execute(testNode, resolver, NodeRefList(), executionContext));\n\n\tif(xuse->getType() != XObject::eTypeNodeSet)\n\t{\n\t\tassert(kd.getQName() != 0);\n\n\t\taddIfNotFound(\n\t\t\texecutionContext,\n\t\t\ttheKeys[*kd.getQName()][xuse->str()],\n\t\t\ttestNode);\n\t}\n\telse\n\t{\n\t\tconst NodeRefListBase&\tnl = xuse->nodeset();\n\n\t\t\/\/ Use each node in the node list as a key value that we'll be \n\t\t\/\/ able to use to look up the given node.\n\t\tconst NodeRefListBase::size_type\tnUseValues = nl.getLength();\n\n\t\tStylesheetExecutionContext::GetAndReleaseCachedString\ttheGuard(executionContext);\n\n\t\tXalanDOMString&\t\tnodeData = theGuard.get();\n\n\t\t\/\/ Use each node in the node list as a key value that we'll be \n\t\t\/\/ able to use to look up the given node.\n\t\tfor(unsigned int i = 0; i < nUseValues; ++i)\n\t\t{\n\t\t\t\/\/ Get the string value of the node to use as the result of the\n\t\t\t\/\/ expression.\n\t\t\tassert(nl.item(i) != 0);\n\n\t\t\tDOMServices::getNodeData(*nl.item(i), nodeData);\n\n\t\t\tassert(kd.getQName() != 0);\n\n\t\t\taddIfNotFound(\n\t\t\t\texecutionContext,\n\t\t\t\ttheKeys[*kd.getQName()][nodeData],\n\t\t\t\ttestNode);\n\n\t\t\tclear(nodeData);\n\t\t}\n\t} \n}\n\n\n\nXALAN_CPP_NAMESPACE_END\nReport line\/column number and URI in exception.\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999-2002 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * .\n *\/\n\/\/ Class header file\n#include \"KeyTable.hpp\"\n\n\n\n#include \n\n\n\n#include \n#include \n#include \n#include \n\n\n\n#include \n\n\n\n#include \n\n\n\n#include \"KeyDeclaration.hpp\"\n#include \"StylesheetExecutionContext.hpp\"\n#include \"XSLTProcessorException.hpp\"\n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\nconst MutableNodeRefList\tKeyTable::s_dummyList;\n\n\n\nKeyTable::KeyTable(\n\t\t\tXalanNode*\t\t\t\t\t\t\tstartNode,\n\t\t\tconst PrefixResolver&\t\t\t\tresolver,\n\t\t\tconst KeyDeclarationVectorType&\t\tkeyDeclarations,\n\t\t\tStylesheetExecutionContext&\t\t\texecutionContext) :\n\tm_keys()\n{\n XalanNode*\tpos = startNode;\n\n\tconst KeyDeclarationVectorType::size_type\tnDeclarations =\n\t\t\tkeyDeclarations.size();\n\n \/\/ Do a non-recursive pre-walk over the tree.\n while(0 != pos)\n {\n\t\t\/\/ We're going to have to walk the attribute list \n\t\t\/\/ if it's an element, so get the attributes.\n\t\tconst XalanNamedNodeMap*\tattrs = 0;\n\n\t\tint\t\t\t\t\t\t\tnNodes = 0;\n\n\t\tif(XalanNode::ELEMENT_NODE == pos->getNodeType())\n\t\t{\n\t\t\tattrs = pos->getAttributes();\n\n\t\t\tnNodes = attrs->getLength();\n \n\t\t\tif(0 == nNodes)\n\t\t\t{\n\t\t\t\tattrs = 0;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Walk the primary node, and each of the attributes.\n\t\t\/\/ This loop is a little strange... it is meant to always \n\t\t\/\/ execute once, then execute for each of the attributes.\n\t\tXalanNode*\ttestNode = pos;\n\n\t\tfor(int nodeIndex = -1; nodeIndex < nNodes;)\n\t\t{\n\t\t\t\/\/ Walk through each of the declarations made with xsl:key\n\t\t\tfor(unsigned int i = 0; i < nDeclarations; ++i)\n\t\t\t{\n\t\t\t\tconst KeyDeclaration&\tkd = keyDeclarations[i];\n\n\t\t\t\tif (executionContext.getInConstruction(kd) == true)\t\t\t\n\t\t\t\t{\n\t\t\t\t\tassert(kd.getURI() != 0);\n\n\t\t\t\t\tthrow XSLTProcessorException(\n\t\t\t\t\t\t\tTranscodeFromLocalCodePage(\"The use of the key() function in the \\\"match\\\" or \\\"use\\\" attribute of xsl:key is illegal!\"),\n\t\t\t\t\t\t\t*kd.getURI(),\n\t\t\t\t\t\t\tkd.getLineNumber(),\n\t\t\t\t\t\t\tkd.getColumnNumber(),\n\t\t\t\t\t\t\tTranscodeFromLocalCodePage(\"XSLTKeyIllegalKeyFunctionException\"));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\texecutionContext.beginConstruction(kd);\n\n\t\t\t\t\t\/\/ See if our node matches the given key declaration according to \n\t\t\t\t\t\/\/ the match attribute on xsl:key.\n\t\t\t\t\tassert(kd.getMatchPattern() != 0);\n\n\t\t\t\t\tconst XPath::eMatchScore\tscore =\n\t\t\t\t\t\t\tkd.getMatchPattern()->getMatchScore(testNode,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tresolver,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\texecutionContext);\n\n\t\t\t\t\tif(score != XPath::eMatchScoreNone)\n\t\t\t\t\t{\n\t\t\t\t\t\tprocessKeyDeclaration(\n\t\t\t\t\t\t\tm_keys,\n\t\t\t\t\t\t\tkd,\n\t\t\t\t\t\t\ttestNode,\n\t\t\t\t\t\t\tresolver,\n\t\t\t\t\t\t\texecutionContext);\n\t\t\t\t\t}\n\n\t\t\t\t\texecutionContext.endConstruction(kd);\n\t\t\t\t} \/\/ if (kd.getInConstruction() == true)\n\t\t\t} \/\/ end for(int i = 0; i < nDeclarations; ++i)\n\n\t\t\t++nodeIndex;\n\n\t\t\tif(0 != attrs)\n\t\t\t{\n\t\t\t\ttestNode = attrs->item(nodeIndex);\n\t\t\t}\n\t\t} \/\/ for(int nodeIndex = -1; nodeIndex < nNodes;)\n\n\t\t\/\/ The rest of this is getting the next prewalk position in \n\t\t\/\/ the tree.\n\t\tXalanNode*\tnextNode = pos->getFirstChild();\n\n\t\twhile(0 == nextNode)\n\t\t{\n\t\t\tif(startNode == pos)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnextNode = pos->getNextSibling();\n\n\t\t\t\tif(0 == nextNode)\n\t\t\t\t{\n\t\t\t\t\tpos = pos->getParentNode();\n\n\t\t\t\t\tif((startNode == pos) || (0 == pos))\n\t\t\t\t\t{\n\t\t\t\t\t\tnextNode = 0;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpos = nextNode;\n } \/\/ while(0 != pos)\n\n\tif (m_keys.empty() == false)\n\t{\n\t\tconst KeysMapType::iterator\t\ttheEnd = m_keys.end();\n\t\tKeysMapType::iterator\t\t\ttheCurrent = m_keys.begin();\n\t\tassert(theCurrent != theEnd);\n\n\t\tdo\n\t\t{\n\t\t\tNodeListMapType&\ttheCurrentNodeListMap = (*theCurrent).second;\n\n\t\t\tif (theCurrentNodeListMap.empty() == false)\n\t\t\t{\n\t\t\t\tconst NodeListMapType::iterator\t\ttheEnd = theCurrentNodeListMap.end();\n\t\t\t\tNodeListMapType::iterator\t\t\ttheCurrent = theCurrentNodeListMap.begin();\n\t\t\t\tassert(theCurrent != theEnd);\n\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\t(*theCurrent).second.setDocumentOrder();\n\n\t\t\t\t\t++theCurrent;\n\t\t\t\t}\n\t\t\t\twhile(theCurrent != theEnd);\n\t\t\t}\n\n\t\t\t++theCurrent;\n\t\t}\n\t\twhile(theCurrent != theEnd);\n\t}\t\n} \/\/ end constructor\n\n\n\nKeyTable::~KeyTable()\n{\n}\n\n\n\nconst MutableNodeRefList&\nKeyTable::getNodeSetByKey(\n\t\t\t\t\t const XalanQName&\t\t\tqname, \n\t\t\t\t\t const XalanDOMString&\t\tref) const\n{\n\tconst KeysMapType::const_iterator\ti = m_keys.find(qname);\n\n\tif (i != m_keys.end())\n\t{\n\t\tconst NodeListMapType&\ttheMap = (*i).second;\n\n\t\tconst NodeListMapType::const_iterator\tj = theMap.find(ref);\n\n\t\tif (j != theMap.end())\n\t\t{\n\t\t\treturn (*j).second;\n\t\t}\n\t}\n\n\t\/\/ It makes things much easier if we always return\n\t\/\/ a list of nodes. So this is just an empty one\n\t\/\/ to return when the ref is not found.\n\treturn s_dummyList;\n}\n\n\n\ninline void\naddIfNotFound(\n\t\t\tStylesheetExecutionContext&\t\texecutionContext,\n\t\t\tMutableNodeRefList&\t\t\t\ttheNodeList,\n\t\t\tXalanNode*\t\t\t\t\t\ttheNode)\n{\n\ttheNodeList.addNodeInDocOrder(theNode, executionContext);\n}\n\n\n\nvoid\nKeyTable::processKeyDeclaration(\n\t\t\tKeysMapType&\t\t\t\t\ttheKeys,\n\t\t\tconst KeyDeclaration&\t\t\tkd,\n\t\t\tXalanNode*\t\t\t\t\t\ttestNode,\n\t\t\tconst PrefixResolver&\t\t\tresolver,\n\t\t\tStylesheetExecutionContext&\t\texecutionContext)\n{\n\t\/\/ Query from the node, according the the select pattern in the\n\t\/\/ use attribute in xsl:key.\n\tassert(kd.getUse() != 0);\n\n\tconst XObjectPtr\txuse(kd.getUse()->execute(testNode, resolver, NodeRefList(), executionContext));\n\n\tif(xuse->getType() != XObject::eTypeNodeSet)\n\t{\n\t\tassert(kd.getQName() != 0);\n\n\t\taddIfNotFound(\n\t\t\texecutionContext,\n\t\t\ttheKeys[*kd.getQName()][xuse->str()],\n\t\t\ttestNode);\n\t}\n\telse\n\t{\n\t\tconst NodeRefListBase&\tnl = xuse->nodeset();\n\n\t\t\/\/ Use each node in the node list as a key value that we'll be \n\t\t\/\/ able to use to look up the given node.\n\t\tconst NodeRefListBase::size_type\tnUseValues = nl.getLength();\n\n\t\tStylesheetExecutionContext::GetAndReleaseCachedString\ttheGuard(executionContext);\n\n\t\tXalanDOMString&\t\tnodeData = theGuard.get();\n\n\t\t\/\/ Use each node in the node list as a key value that we'll be \n\t\t\/\/ able to use to look up the given node.\n\t\tfor(unsigned int i = 0; i < nUseValues; ++i)\n\t\t{\n\t\t\t\/\/ Get the string value of the node to use as the result of the\n\t\t\t\/\/ expression.\n\t\t\tassert(nl.item(i) != 0);\n\n\t\t\tDOMServices::getNodeData(*nl.item(i), nodeData);\n\n\t\t\tassert(kd.getQName() != 0);\n\n\t\t\taddIfNotFound(\n\t\t\t\texecutionContext,\n\t\t\t\ttheKeys[*kd.getQName()][nodeData],\n\t\t\t\ttestNode);\n\n\t\t\tclear(nodeData);\n\t\t}\n\t} \n}\n\n\n\nXALAN_CPP_NAMESPACE_END\n<|endoftext|>"} {"text":"coverity#704921 Dereference after null check<|endoftext|>"} {"text":"#include \r\n#include \r\n\r\n#include \"httpServer.h\"\r\n#include \"logging.h\"\r\n\r\nHttpServer::HttpServer(int portNr)\r\n{\r\n listenSocket.listen(static_cast(portNr));\r\n selector.add(listenSocket);\r\n}\r\n\r\nHttpServer::~HttpServer()\r\n{\r\n listenSocket.close();\r\n for(unsigned int n=0; nsocket) == sf::Socket::Done)\r\n {\r\n connections.push_back(connection);\r\n selector.add(connection->socket);\r\n }else{\r\n delete connection;\r\n }\r\n }\r\n for(unsigned int n=0; nsocket))\r\n {\r\n if (!connections[n]->read())\r\n {\r\n selector.remove(connections[n]->socket);\r\n delete connections[n];\r\n connections.erase(connections.begin() + n);\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nHttpServerConnection::HttpServerConnection(HttpServer* server)\n: server(server)\r\n{\r\n recvBufferCount = 0;\r\n status = METHOD;\r\n}\r\n\r\nbool HttpServerConnection::read()\r\n{\r\n char buffer[1024];\r\n size_t size;\r\n if (socket.receive(buffer, sizeof(buffer), size) != sf::Socket::Done)\r\n return false;\r\n if (recvBufferCount + size > recvBufferSize)\r\n size = recvBufferSize - recvBufferCount;\r\n if (size < 1)\r\n return false;\r\n memcpy(recvBuffer + recvBufferCount, buffer, size);\r\n recvBufferCount += size;\r\n\r\n while(true)\r\n {\r\n char* ptr = (char*)memchr(recvBuffer, '\\n', recvBufferCount);\r\n if (!ptr)\r\n break;\n *ptr = '\\0';\n string line(recvBuffer);\r\n ptr++;\n size_t len = ptr - recvBuffer;\r\n recvBufferCount -= len;\n memmove(recvBuffer, ptr, recvBufferCount);\n if (line.endswith(\"\\r\"))\n line = line.substr(0, -1);\r\n if (!handleLine(line))\r\n return false;\r\n }\r\n return true;\r\n}\r\n\r\n\/** \\brief Decode a percent-encoded URI\r\n * Uri decoding according to RFC1630, RFC1738, RFC2396\r\n * Credits: Jin Qing\r\n * \\param sSrc const string& Percent-encoded URI\r\n * \\return string Decoded URI-string\r\n *\r\n *\/\r\nstring HttpServerConnection::UriDecode(const string & sSrc)\r\n{\r\n \/\/ Note from RFC1630: \"Sequences which start with a percent\r\n \/\/ sign but are not followed by two hexadecimal characters\r\n \/\/ (0-9, A-F) are reserved for future extension\"\r\n\r\n const unsigned char * pSrc = (const unsigned char *)sSrc.c_str();\r\n const size_t SRC_LEN = sSrc.length();\r\n const unsigned char * const SRC_END = pSrc + SRC_LEN;\r\n \/\/ last decodable '%'\r\n const unsigned char * const SRC_LAST_DEC = SRC_END - 2;\r\n\r\n char * const pStart = new char[SRC_LEN];\r\n char * pEnd = pStart;\r\n\r\n while (pSrc < SRC_LAST_DEC)\r\n {\r\n if (*pSrc == '%')\r\n {\r\n char dec1, dec2;\r\n if (-1 != (dec1 = HEX2DEC[*(pSrc + 1)])\r\n && -1 != (dec2 = HEX2DEC[*(pSrc + 2)]))\r\n {\r\n *pEnd++ = (dec1 << 4) + dec2;\r\n pSrc += 3;\r\n continue;\r\n }\r\n }\r\n\r\n *pEnd++ = *pSrc++;\r\n }\r\n\r\n \/\/ the last 2- chars\r\n while (pSrc < SRC_END)\r\n *pEnd++ = *pSrc++;\r\n\r\n std::string sResult(pStart, pEnd);\r\n delete [] pStart;\r\n return (string) sResult;\r\n}\r\n\r\n\r\n\/**< Map to convert between character encodings *\/\r\nconst signed char HttpServerConnection::HEX2DEC[256] =\r\n{\r\n \/* 0 1 2 3 4 5 6 7 8 9 A B C D E F *\/\r\n \/* 0 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 1 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 2 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 3 *\/ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1,\r\n\r\n \/* 4 *\/ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 5 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 6 *\/ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 7 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n\r\n \/* 8 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* 9 *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* A *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* B *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n\r\n \/* C *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* D *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* E *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\r\n \/* F *\/ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1\r\n};\r\n\r\n\r\n\/** \\brief Parse a URL, splitting it in its part and optional parameters\r\n *\r\n * \\param sSrc const string& URL\r\n * \\return void\r\n *\r\n *\/\r\nvoid HttpServerConnection::parseUri(const string & sSrc)\r\n{\r\n string uri = UriDecode(sSrc);\r\n std::size_t found = uri.find('?');\r\n if (found==std::string::npos)\r\n {\r\n request.path = uri;\r\n return;\r\n }\r\n else\r\n {\r\n std::vector parts = uri.split(\"?\", 1);\r\n request.path = parts[0];\r\n\r\n std::vector parameters = parts[1].split(\"&\");\r\n for (unsigned int n=0; n parts = uri.split(\"?\", 1);\r\n request.path = parts[0];\r\n\r\n std::vector parameters;\r\n if (parts.size()>1)\r\n {\r\n parameters = parts[1].split(\"&\");\r\n }\r\n for (unsigned int n=0; n caf::actor {\n\treturn spawn_lactor(std::move(limpl));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ class\n\/\/\n\/\/\/ ctor -- pointee is specified by string path\nsym_link::sym_link(std::string name, std::string path, Flags f)\n\t: link(std::make_shared(std::move(name), std::move(path), f))\n{}\n\/\/\/ ctor -- pointee is specified directly - absolute path will be stored\nsym_link::sym_link(std::string name, const sp_link& src, Flags f)\n\t: sym_link(std::move(name), abspath(src), f)\n{}\n\nsym_link::sym_link()\n\t: super(std::make_shared(), false)\n{}\n\n\/\/\/ implement link's API\nsp_link sym_link::clone(bool deep) const {\n\t\/\/ no deep copy support for symbolic link\n\treturn std::make_shared(pimpl()->name_, pimpl()->path_, flags());\n}\n\nstd::string sym_link::type_id() const {\n\treturn \"sym_link\";\n}\n\nauto sym_link::pimpl() const -> sym_link_impl* {\n\treturn static_cast(super::pimpl());\n}\n\nbool sym_link::check_alive() {\n\tauto res = bool(deref_path(pimpl()->path_, owner()));\n\tauto S = res ? ReqStatus::OK : ReqStatus::Error;\n\trs_reset_if_neq(Req::Data, S, S);\n\treturn res;\n}\n\n\/\/\/ return stored pointee path\nstd::string sym_link::src_path(bool human_readable) const {\n\tif(!human_readable) return pimpl()->path_;\n\telse if(const auto parent = owner())\n\t\treturn convert_path(pimpl()->path_, parent->handle());\n\treturn {};\n}\n\nresult_or_err sym_link::propagate_handle() {\n\t\/\/ sym link cannot be a node's handle\n\treturn data_node_ex();\n}\n\nNAMESPACE_END(blue_sky::tree)\ntree\/sym_link: optimize delegatin messages to src link, fix inode getter\/\/\/ @file\n\/\/\/ @author uentity\n\/\/\/ @date 20.11.2017\n\/\/\/ @brief Symbolic link implementation\n\/\/\/ @copyright\n\/\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"link_actor.h\"\n\nOMIT_OBJ_SERIALIZATION\n\nNAMESPACE_BEGIN(blue_sky::tree)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ actor + impl\n\/\/\n\n\/\/ actor\nstruct sym_link_actor : public link_actor {\n\tusing super = link_actor;\n\n\tusing super::super;\n\n\tauto pointee() const -> result_or_err {\n\t\treturn static_cast(impl).pointee();\n\t}\n\n\t\/\/\/\/ make data request via source link\n\t\/\/auto data_ex(obj_processor_f cb, ReqOpts opts) -> void override {\n\t\/\/\tpointee().and_then([&](const sp_link& src_link) {\n\t\/\/\t\tif(enumval(opts & ReqOpts::DirectInvoke))\n\t\/\/\t\t\tcb(src_link->data_ex());\n\t\/\/\t\telse\n\t\/\/\t\t\tcaf::anon_send(src_link->actor(), a_lnk_data(), std::move(cb), opts);\n\t\/\/\t});\n\t\/\/}\n\n\t\/\/auto data_node_ex(node_processor_f cb, ReqOpts opts) -> void override {\n\t\/\/\tpointee().and_then([&](const sp_link& src_link) {\n\t\/\/\t\tif(enumval(opts & ReqOpts::DirectInvoke))\n\t\/\/\t\t\tcb(src_link->data_node_ex());\n\t\/\/\t\telse\n\t\/\/\t\t\tcaf::anon_send(src_link->actor(), a_lnk_dnode(), std::move(cb), opts);\n\t\/\/\t});\n\t\/\/}\n\n\ttemplate\n\tauto delegate_source(Args&&... args)\n\t-> std::enable_if_t::value, caf::result> {\n\t\tif(auto p = pointee())\n\t\t\treturn delegate(link::actor(*p.value()), std::forward(args)...);\n\t\telse\n\t\t\treturn R{ tl::unexpect, p.error() };\n\t}\n\n\ttemplate\n\tauto delegate_source(R errval, Args&&... args)\n\t-> std::enable_if_t::value, caf::result> {\n\t\tif(auto p = pointee())\n\t\t\treturn delegate(link::actor(*p.value()), std::forward(args)...);\n\t\telse\n\t\t\treturn errval;\n\t}\n\n\t\/\/ delegate name, OID, etc requests to source link\n\tauto make_behavior() -> caf::behavior override {\n\t\treturn caf::message_handler({\n\n\t\t\t[this](a_lnk_oid) -> caf::result {\n\t\t\t\treturn delegate_source(type_descriptor::nil().name, a_lnk_oid());\n\t\t\t},\n\n\t\t\t[this](a_lnk_otid) -> caf::result {\n\t\t\t\treturn delegate_source(type_descriptor::nil().name, a_lnk_otid());\n\t\t\t},\n\n\t\t\t[this](a_node_gid) -> caf::result< result_or_errbox > {\n\t\t\t\treturn delegate_source< result_or_errbox >(a_node_gid());\n\t\t\t},\n\n\t\t\t[this](a_lnk_inode) -> caf::result< result_or_errbox > {\n\t\t\t\treturn delegate_source< result_or_errbox >(a_lnk_inode());\n\t\t\t},\n\n\t\t}).or_else(super::make_behavior());\n\t}\n};\n\n\/\/ impl\nsym_link_impl::sym_link_impl(std::string name, std::string path, Flags f)\n\t: super(std::move(name), f), path_(std::move(path))\n{}\n\nsym_link_impl::sym_link_impl()\n\t: super()\n{}\n\nauto sym_link_impl::pointee() const -> result_or_err {\n\tconst auto parent = owner_.lock();\n\tif(!parent) return tl::make_unexpected( error::quiet(Error::UnboundSymLink) );\n\n\tsp_link src_link;\n\tif(auto er = error::eval_safe([&] { src_link = deref_path(path_, parent); }); er)\n\t\treturn tl::make_unexpected(std::move(er));\n\telse if(src_link)\n\t\treturn src_link;\n\treturn tl::make_unexpected( error::quiet(Error::LinkExpired) );\n}\n\nauto sym_link_impl::data() -> result_or_err {\n\tauto res = pointee().and_then([](const sp_link& src_link) {\n\t\treturn src_link->data_ex();\n\t});\n#if defined(_DEBUG)\n\tif(!res) {\n\t\tauto& er = res.error();\n\t\tstd::cout << \">>> \" << to_string(id_) << ' ' << er.what() << std::endl;\n\t\t\/\/std::cout << kernel::tools::get_backtrace(16) << std::endl;\n\t}\n#endif\n\treturn res;\n}\n\nauto sym_link_impl::spawn_actor(sp_limpl limpl) const -> caf::actor {\n\treturn spawn_lactor(std::move(limpl));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ class\n\/\/\n\/\/\/ ctor -- pointee is specified by string path\nsym_link::sym_link(std::string name, std::string path, Flags f)\n\t: link(std::make_shared(std::move(name), std::move(path), f))\n{}\n\/\/\/ ctor -- pointee is specified directly - absolute path will be stored\nsym_link::sym_link(std::string name, const sp_link& src, Flags f)\n\t: sym_link(std::move(name), abspath(src), f)\n{}\n\nsym_link::sym_link()\n\t: super(std::make_shared(), false)\n{}\n\n\/\/\/ implement link's API\nsp_link sym_link::clone(bool deep) const {\n\t\/\/ no deep copy support for symbolic link\n\treturn std::make_shared(pimpl()->name_, pimpl()->path_, flags());\n}\n\nstd::string sym_link::type_id() const {\n\treturn \"sym_link\";\n}\n\nauto sym_link::pimpl() const -> sym_link_impl* {\n\treturn static_cast(super::pimpl());\n}\n\nbool sym_link::check_alive() {\n\tauto res = bool(deref_path(pimpl()->path_, owner()));\n\tauto S = res ? ReqStatus::OK : ReqStatus::Error;\n\trs_reset_if_neq(Req::Data, S, S);\n\treturn res;\n}\n\n\/\/\/ return stored pointee path\nstd::string sym_link::src_path(bool human_readable) const {\n\tif(!human_readable) return pimpl()->path_;\n\telse if(const auto parent = owner())\n\t\treturn convert_path(pimpl()->path_, parent->handle());\n\treturn {};\n}\n\nauto sym_link::propagate_handle() -> result_or_err {\n\t\/\/ sym link cannot be a node's handle\n\treturn data_node_ex();\n}\n\nNAMESPACE_END(blue_sky::tree)\n<|endoftext|>"} {"text":"\/\/===-- BenchmarkResult.cpp -------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"BenchmarkResult.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ObjectYAML\/YAML.h\"\n#include \"llvm\/Support\/FileOutputBuffer.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Format.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nstatic constexpr const char kIntegerFormat[] = \"i_0x%\" PRId64 \"x\";\nstatic constexpr const char kDoubleFormat[] = \"f_%la\";\n\nstatic void serialize(const exegesis::BenchmarkResultContext &Context,\n const llvm::MCOperand &MCOperand, llvm::raw_ostream &OS) {\n if (MCOperand.isReg()) {\n OS << Context.getRegName(MCOperand.getReg());\n } else if (MCOperand.isImm()) {\n OS << llvm::format(kIntegerFormat, MCOperand.getImm());\n } else if (MCOperand.isFPImm()) {\n OS << llvm::format(kDoubleFormat, MCOperand.getFPImm());\n } else {\n OS << \"INVALID\";\n }\n}\n\nstatic void serialize(const exegesis::BenchmarkResultContext &Context,\n const llvm::MCInst &MCInst, llvm::raw_ostream &OS) {\n OS << Context.getInstrName(MCInst.getOpcode());\n for (const auto &Op : MCInst) {\n OS << ' ';\n serialize(Context, Op, OS);\n }\n}\n\nstatic llvm::MCOperand\ndeserialize(const exegesis::BenchmarkResultContext &Context,\n llvm::StringRef String) {\n assert(!String.empty());\n int64_t IntValue = 0;\n double DoubleValue = 0;\n if (sscanf(String.data(), kIntegerFormat, &IntValue) == 1)\n return llvm::MCOperand::createImm(IntValue);\n if (sscanf(String.data(), kDoubleFormat, &DoubleValue) == 1)\n return llvm::MCOperand::createFPImm(DoubleValue);\n if (unsigned RegNo = Context.getRegNo(String)) \/\/ Returns 0 if invalid.\n return llvm::MCOperand::createReg(RegNo);\n return {};\n}\n\nstatic llvm::StringRef\ndeserialize(const exegesis::BenchmarkResultContext &Context,\n llvm::StringRef String, llvm::MCInst &Value) {\n llvm::SmallVector Pieces;\n String.split(Pieces, \" \");\n if (Pieces.empty())\n return \"Invalid Instruction\";\n bool ProcessOpcode = true;\n for (llvm::StringRef Piece : Pieces) {\n if (ProcessOpcode) {\n ProcessOpcode = false;\n Value.setOpcode(Context.getInstrOpcode(Piece));\n if (Value.getOpcode() == 0)\n return \"Unknown Opcode Name\";\n } else {\n Value.addOperand(deserialize(Context, Piece));\n }\n }\n return {};\n}\n\n\/\/ YAML IO requires a mutable pointer to Context but we guarantee to not\n\/\/ modify it.\nstatic void *getUntypedContext(const exegesis::BenchmarkResultContext &Ctx) {\n return const_cast(&Ctx);\n}\n\nstatic const exegesis::BenchmarkResultContext &getTypedContext(void *Ctx) {\n assert(Ctx);\n return *static_cast(Ctx);\n}\n\n\/\/ Defining YAML traits for IO.\nnamespace llvm {\nnamespace yaml {\n\n\/\/ std::vector will be rendered as a list.\ntemplate <> struct SequenceElementTraits {\n static const bool flow = false;\n};\n\ntemplate <> struct ScalarTraits {\n\n static void output(const llvm::MCInst &Value, void *Ctx,\n llvm::raw_ostream &Out) {\n serialize(getTypedContext(Ctx), Value, Out);\n }\n\n static StringRef input(StringRef Scalar, void *Ctx, llvm::MCInst &Value) {\n return deserialize(getTypedContext(Ctx), Scalar, Value);\n }\n\n static QuotingType mustQuote(StringRef) { return QuotingType::Single; }\n\n static const bool flow = true;\n};\n\n\/\/ std::vector will be rendered as a list.\ntemplate <> struct SequenceElementTraits {\n static const bool flow = false;\n};\n\n\/\/ exegesis::Measure is rendererd as a flow instead of a list.\n\/\/ e.g. { \"key\": \"the key\", \"value\": 0123 }\ntemplate <> struct MappingTraits {\n static void mapping(IO &Io, exegesis::BenchmarkMeasure &Obj) {\n Io.mapRequired(\"key\", Obj.Key);\n Io.mapRequired(\"value\", Obj.Value);\n Io.mapOptional(\"debug_string\", Obj.DebugString);\n }\n static const bool flow = true;\n};\n\ntemplate <>\nstruct ScalarEnumerationTraits {\n static void enumeration(IO &Io,\n exegesis::InstructionBenchmark::ModeE &Value) {\n Io.enumCase(Value, \"\", exegesis::InstructionBenchmark::Unknown);\n Io.enumCase(Value, \"latency\", exegesis::InstructionBenchmark::Latency);\n Io.enumCase(Value, \"uops\", exegesis::InstructionBenchmark::Uops);\n }\n};\n\ntemplate <> struct MappingTraits {\n static void mapping(IO &Io, exegesis::InstructionBenchmarkKey &Obj) {\n Io.mapRequired(\"instructions\", Obj.Instructions);\n Io.mapOptional(\"config\", Obj.Config);\n }\n};\n\ntemplate <> struct MappingTraits {\n class NormalizedBinary {\n public:\n NormalizedBinary(IO &io) {}\n NormalizedBinary(IO &, std::vector &Data) : Binary(Data) {}\n std::vector denormalize(IO &) {\n std::vector Data;\n std::string Str;\n raw_string_ostream OSS(Str);\n Binary.writeAsBinary(OSS);\n OSS.flush();\n Data.assign(Str.begin(), Str.end());\n return Data;\n }\n\n BinaryRef Binary;\n };\n\n static void mapping(IO &Io, exegesis::InstructionBenchmark &Obj) {\n Io.mapRequired(\"mode\", Obj.Mode);\n Io.mapRequired(\"key\", Obj.Key);\n Io.mapRequired(\"cpu_name\", Obj.CpuName);\n Io.mapRequired(\"llvm_triple\", Obj.LLVMTriple);\n Io.mapRequired(\"num_repetitions\", Obj.NumRepetitions);\n Io.mapRequired(\"measurements\", Obj.Measurements);\n Io.mapRequired(\"error\", Obj.Error);\n Io.mapOptional(\"info\", Obj.Info);\n \/\/ AssembledSnippet\n MappingNormalization> BinaryString(\n Io, Obj.AssembledSnippet);\n Io.mapOptional(\"assembled_snippet\", BinaryString->Binary);\n }\n};\n\n} \/\/ namespace yaml\n} \/\/ namespace llvm\n\nLLVM_YAML_IS_DOCUMENT_LIST_VECTOR(exegesis::InstructionBenchmark)\n\nnamespace exegesis {\n\nvoid BenchmarkResultContext::addRegEntry(unsigned RegNo, llvm::StringRef Name) {\n assert(RegNoToName.find(RegNo) == RegNoToName.end());\n assert(RegNameToNo.find(Name) == RegNameToNo.end());\n RegNoToName[RegNo] = Name;\n RegNameToNo[Name] = RegNo;\n}\n\nllvm::StringRef BenchmarkResultContext::getRegName(unsigned RegNo) const {\n const auto Itr = RegNoToName.find(RegNo);\n if (Itr != RegNoToName.end())\n return Itr->second;\n return {};\n}\n\nunsigned BenchmarkResultContext::getRegNo(llvm::StringRef Name) const {\n const auto Itr = RegNameToNo.find(Name);\n if (Itr != RegNameToNo.end())\n return Itr->second;\n return 0;\n}\n\nvoid BenchmarkResultContext::addInstrEntry(unsigned Opcode,\n llvm::StringRef Name) {\n assert(InstrOpcodeToName.find(Opcode) == InstrOpcodeToName.end());\n assert(InstrNameToOpcode.find(Name) == InstrNameToOpcode.end());\n InstrOpcodeToName[Opcode] = Name;\n InstrNameToOpcode[Name] = Opcode;\n}\n\nllvm::StringRef BenchmarkResultContext::getInstrName(unsigned Opcode) const {\n const auto Itr = InstrOpcodeToName.find(Opcode);\n if (Itr != InstrOpcodeToName.end())\n return Itr->second;\n return {};\n}\n\nunsigned BenchmarkResultContext::getInstrOpcode(llvm::StringRef Name) const {\n const auto Itr = InstrNameToOpcode.find(Name);\n if (Itr != InstrNameToOpcode.end())\n return Itr->second;\n return 0;\n}\n\ntemplate \nstatic llvm::Expected\nreadYamlCommon(const BenchmarkResultContext &Context,\n llvm::StringRef Filename) {\n if (auto ExpectedMemoryBuffer =\n llvm::errorOrToExpected(llvm::MemoryBuffer::getFile(Filename))) {\n std::unique_ptr MemoryBuffer =\n std::move(ExpectedMemoryBuffer.get());\n llvm::yaml::Input Yin(*MemoryBuffer, getUntypedContext(Context));\n ObjectOrList Benchmark;\n Yin >> Benchmark;\n return Benchmark;\n } else {\n return ExpectedMemoryBuffer.takeError();\n }\n}\n\nllvm::Expected\nInstructionBenchmark::readYaml(const BenchmarkResultContext &Context,\n llvm::StringRef Filename) {\n return readYamlCommon(Context, Filename);\n}\n\nllvm::Expected>\nInstructionBenchmark::readYamls(const BenchmarkResultContext &Context,\n llvm::StringRef Filename) {\n return readYamlCommon>(Context, Filename);\n}\n\nvoid InstructionBenchmark::writeYamlTo(const BenchmarkResultContext &Context,\n llvm::raw_ostream &OS) {\n llvm::yaml::Output Yout(OS, getUntypedContext(Context));\n Yout << *this;\n}\n\nvoid InstructionBenchmark::readYamlFrom(const BenchmarkResultContext &Context,\n llvm::StringRef InputContent) {\n llvm::yaml::Input Yin(InputContent, getUntypedContext(Context));\n Yin >> *this;\n}\n\nllvm::Error\nInstructionBenchmark::writeYaml(const BenchmarkResultContext &Context,\n const llvm::StringRef Filename) {\n if (Filename == \"-\") {\n writeYamlTo(Context, llvm::outs());\n } else {\n int ResultFD = 0;\n if (auto E = llvm::errorCodeToError(\n openFileForWrite(Filename, ResultFD, llvm::sys::fs::CD_CreateAlways,\n llvm::sys::fs::F_Text))) {\n return E;\n }\n llvm::raw_fd_ostream Ostr(ResultFD, true \/*shouldClose*\/);\n writeYamlTo(Context, Ostr);\n }\n return llvm::Error::success();\n}\n\nvoid BenchmarkMeasureStats::push(const BenchmarkMeasure &BM) {\n if (Key.empty())\n Key = BM.Key;\n assert(Key == BM.Key);\n ++NumValues;\n SumValues += BM.Value;\n MaxValue = std::max(MaxValue, BM.Value);\n MinValue = std::min(MinValue, BM.Value);\n}\n\n} \/\/ namespace exegesis\n[llvm-exegesis] Ignore double spaced separators in asm strings\/\/===-- BenchmarkResult.cpp -------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"BenchmarkResult.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ObjectYAML\/YAML.h\"\n#include \"llvm\/Support\/FileOutputBuffer.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Format.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nstatic constexpr const char kIntegerFormat[] = \"i_0x%\" PRId64 \"x\";\nstatic constexpr const char kDoubleFormat[] = \"f_%la\";\n\nstatic void serialize(const exegesis::BenchmarkResultContext &Context,\n const llvm::MCOperand &MCOperand, llvm::raw_ostream &OS) {\n if (MCOperand.isReg()) {\n OS << Context.getRegName(MCOperand.getReg());\n } else if (MCOperand.isImm()) {\n OS << llvm::format(kIntegerFormat, MCOperand.getImm());\n } else if (MCOperand.isFPImm()) {\n OS << llvm::format(kDoubleFormat, MCOperand.getFPImm());\n } else {\n OS << \"INVALID\";\n }\n}\n\nstatic void serialize(const exegesis::BenchmarkResultContext &Context,\n const llvm::MCInst &MCInst, llvm::raw_ostream &OS) {\n OS << Context.getInstrName(MCInst.getOpcode());\n for (const auto &Op : MCInst) {\n OS << ' ';\n serialize(Context, Op, OS);\n }\n}\n\nstatic llvm::MCOperand\ndeserialize(const exegesis::BenchmarkResultContext &Context,\n llvm::StringRef String) {\n assert(!String.empty());\n int64_t IntValue = 0;\n double DoubleValue = 0;\n if (sscanf(String.data(), kIntegerFormat, &IntValue) == 1)\n return llvm::MCOperand::createImm(IntValue);\n if (sscanf(String.data(), kDoubleFormat, &DoubleValue) == 1)\n return llvm::MCOperand::createFPImm(DoubleValue);\n if (unsigned RegNo = Context.getRegNo(String)) \/\/ Returns 0 if invalid.\n return llvm::MCOperand::createReg(RegNo);\n return {};\n}\n\nstatic llvm::StringRef\ndeserialize(const exegesis::BenchmarkResultContext &Context,\n llvm::StringRef String, llvm::MCInst &Value) {\n llvm::SmallVector Pieces;\n String.split(Pieces, \" \", \/* MaxSplit *\/ -1, \/* KeepEmpty *\/ false);\n if (Pieces.empty())\n return \"Invalid Instruction\";\n bool ProcessOpcode = true;\n for (llvm::StringRef Piece : Pieces) {\n if (ProcessOpcode) {\n ProcessOpcode = false;\n Value.setOpcode(Context.getInstrOpcode(Piece));\n if (Value.getOpcode() == 0)\n return \"Unknown Opcode Name\";\n } else {\n Value.addOperand(deserialize(Context, Piece));\n }\n }\n return {};\n}\n\n\/\/ YAML IO requires a mutable pointer to Context but we guarantee to not\n\/\/ modify it.\nstatic void *getUntypedContext(const exegesis::BenchmarkResultContext &Ctx) {\n return const_cast(&Ctx);\n}\n\nstatic const exegesis::BenchmarkResultContext &getTypedContext(void *Ctx) {\n assert(Ctx);\n return *static_cast(Ctx);\n}\n\n\/\/ Defining YAML traits for IO.\nnamespace llvm {\nnamespace yaml {\n\n\/\/ std::vector will be rendered as a list.\ntemplate <> struct SequenceElementTraits {\n static const bool flow = false;\n};\n\ntemplate <> struct ScalarTraits {\n\n static void output(const llvm::MCInst &Value, void *Ctx,\n llvm::raw_ostream &Out) {\n serialize(getTypedContext(Ctx), Value, Out);\n }\n\n static StringRef input(StringRef Scalar, void *Ctx, llvm::MCInst &Value) {\n return deserialize(getTypedContext(Ctx), Scalar, Value);\n }\n\n static QuotingType mustQuote(StringRef) { return QuotingType::Single; }\n\n static const bool flow = true;\n};\n\n\/\/ std::vector will be rendered as a list.\ntemplate <> struct SequenceElementTraits {\n static const bool flow = false;\n};\n\n\/\/ exegesis::Measure is rendererd as a flow instead of a list.\n\/\/ e.g. { \"key\": \"the key\", \"value\": 0123 }\ntemplate <> struct MappingTraits {\n static void mapping(IO &Io, exegesis::BenchmarkMeasure &Obj) {\n Io.mapRequired(\"key\", Obj.Key);\n Io.mapRequired(\"value\", Obj.Value);\n Io.mapOptional(\"debug_string\", Obj.DebugString);\n }\n static const bool flow = true;\n};\n\ntemplate <>\nstruct ScalarEnumerationTraits {\n static void enumeration(IO &Io,\n exegesis::InstructionBenchmark::ModeE &Value) {\n Io.enumCase(Value, \"\", exegesis::InstructionBenchmark::Unknown);\n Io.enumCase(Value, \"latency\", exegesis::InstructionBenchmark::Latency);\n Io.enumCase(Value, \"uops\", exegesis::InstructionBenchmark::Uops);\n }\n};\n\ntemplate <> struct MappingTraits {\n static void mapping(IO &Io, exegesis::InstructionBenchmarkKey &Obj) {\n Io.mapRequired(\"instructions\", Obj.Instructions);\n Io.mapOptional(\"config\", Obj.Config);\n }\n};\n\ntemplate <> struct MappingTraits {\n class NormalizedBinary {\n public:\n NormalizedBinary(IO &io) {}\n NormalizedBinary(IO &, std::vector &Data) : Binary(Data) {}\n std::vector denormalize(IO &) {\n std::vector Data;\n std::string Str;\n raw_string_ostream OSS(Str);\n Binary.writeAsBinary(OSS);\n OSS.flush();\n Data.assign(Str.begin(), Str.end());\n return Data;\n }\n\n BinaryRef Binary;\n };\n\n static void mapping(IO &Io, exegesis::InstructionBenchmark &Obj) {\n Io.mapRequired(\"mode\", Obj.Mode);\n Io.mapRequired(\"key\", Obj.Key);\n Io.mapRequired(\"cpu_name\", Obj.CpuName);\n Io.mapRequired(\"llvm_triple\", Obj.LLVMTriple);\n Io.mapRequired(\"num_repetitions\", Obj.NumRepetitions);\n Io.mapRequired(\"measurements\", Obj.Measurements);\n Io.mapRequired(\"error\", Obj.Error);\n Io.mapOptional(\"info\", Obj.Info);\n \/\/ AssembledSnippet\n MappingNormalization> BinaryString(\n Io, Obj.AssembledSnippet);\n Io.mapOptional(\"assembled_snippet\", BinaryString->Binary);\n }\n};\n\n} \/\/ namespace yaml\n} \/\/ namespace llvm\n\nLLVM_YAML_IS_DOCUMENT_LIST_VECTOR(exegesis::InstructionBenchmark)\n\nnamespace exegesis {\n\nvoid BenchmarkResultContext::addRegEntry(unsigned RegNo, llvm::StringRef Name) {\n assert(RegNoToName.find(RegNo) == RegNoToName.end());\n assert(RegNameToNo.find(Name) == RegNameToNo.end());\n RegNoToName[RegNo] = Name;\n RegNameToNo[Name] = RegNo;\n}\n\nllvm::StringRef BenchmarkResultContext::getRegName(unsigned RegNo) const {\n const auto Itr = RegNoToName.find(RegNo);\n if (Itr != RegNoToName.end())\n return Itr->second;\n return {};\n}\n\nunsigned BenchmarkResultContext::getRegNo(llvm::StringRef Name) const {\n const auto Itr = RegNameToNo.find(Name);\n if (Itr != RegNameToNo.end())\n return Itr->second;\n return 0;\n}\n\nvoid BenchmarkResultContext::addInstrEntry(unsigned Opcode,\n llvm::StringRef Name) {\n assert(InstrOpcodeToName.find(Opcode) == InstrOpcodeToName.end());\n assert(InstrNameToOpcode.find(Name) == InstrNameToOpcode.end());\n InstrOpcodeToName[Opcode] = Name;\n InstrNameToOpcode[Name] = Opcode;\n}\n\nllvm::StringRef BenchmarkResultContext::getInstrName(unsigned Opcode) const {\n const auto Itr = InstrOpcodeToName.find(Opcode);\n if (Itr != InstrOpcodeToName.end())\n return Itr->second;\n return {};\n}\n\nunsigned BenchmarkResultContext::getInstrOpcode(llvm::StringRef Name) const {\n const auto Itr = InstrNameToOpcode.find(Name);\n if (Itr != InstrNameToOpcode.end())\n return Itr->second;\n return 0;\n}\n\ntemplate \nstatic llvm::Expected\nreadYamlCommon(const BenchmarkResultContext &Context,\n llvm::StringRef Filename) {\n if (auto ExpectedMemoryBuffer =\n llvm::errorOrToExpected(llvm::MemoryBuffer::getFile(Filename))) {\n std::unique_ptr MemoryBuffer =\n std::move(ExpectedMemoryBuffer.get());\n llvm::yaml::Input Yin(*MemoryBuffer, getUntypedContext(Context));\n ObjectOrList Benchmark;\n Yin >> Benchmark;\n return Benchmark;\n } else {\n return ExpectedMemoryBuffer.takeError();\n }\n}\n\nllvm::Expected\nInstructionBenchmark::readYaml(const BenchmarkResultContext &Context,\n llvm::StringRef Filename) {\n return readYamlCommon(Context, Filename);\n}\n\nllvm::Expected>\nInstructionBenchmark::readYamls(const BenchmarkResultContext &Context,\n llvm::StringRef Filename) {\n return readYamlCommon>(Context, Filename);\n}\n\nvoid InstructionBenchmark::writeYamlTo(const BenchmarkResultContext &Context,\n llvm::raw_ostream &OS) {\n llvm::yaml::Output Yout(OS, getUntypedContext(Context));\n Yout << *this;\n}\n\nvoid InstructionBenchmark::readYamlFrom(const BenchmarkResultContext &Context,\n llvm::StringRef InputContent) {\n llvm::yaml::Input Yin(InputContent, getUntypedContext(Context));\n Yin >> *this;\n}\n\nllvm::Error\nInstructionBenchmark::writeYaml(const BenchmarkResultContext &Context,\n const llvm::StringRef Filename) {\n if (Filename == \"-\") {\n writeYamlTo(Context, llvm::outs());\n } else {\n int ResultFD = 0;\n if (auto E = llvm::errorCodeToError(\n openFileForWrite(Filename, ResultFD, llvm::sys::fs::CD_CreateAlways,\n llvm::sys::fs::F_Text))) {\n return E;\n }\n llvm::raw_fd_ostream Ostr(ResultFD, true \/*shouldClose*\/);\n writeYamlTo(Context, Ostr);\n }\n return llvm::Error::success();\n}\n\nvoid BenchmarkMeasureStats::push(const BenchmarkMeasure &BM) {\n if (Key.empty())\n Key = BM.Key;\n assert(Key == BM.Key);\n ++NumValues;\n SumValues += BM.Value;\n MaxValue = std::max(MaxValue, BM.Value);\n MinValue = std::min(MinValue, BM.Value);\n}\n\n} \/\/ namespace exegesis\n<|endoftext|>"} {"text":"\/*\n* Copyright (C) 2008-2011 J-P Nurmi \n*\n* This library is free software; you can redistribute it and\/or modify it\n* under the terms of the GNU Lesser General Public License as published by\n* the Free Software Foundation; either version 2 of the License, or (at your\n* option) any later version.\n*\n* This library is distributed in the hope that it will be useful, but WITHOUT\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n* License for more details.\n*\/\n\n#include \"ircencoder_p.h\"\n#include \n\n#ifdef HAVE_ICU\n#include \n#endif \/\/ HAVE_ICU\n\nIrcEncoder::IrcEncoder()\n{\n d.detector = 0;\n#ifdef HAVE_ICU\n UErrorCode status = U_ZERO_ERROR;\n d.detector = ucsdet_open(&status);\n if (U_FAILURE(status))\n qWarning(\"IrcEncoder: ICU initialization failed: %s\", u_errorName(status));\n#endif \/\/ HAVE_ICU\n}\n\nIrcEncoder::~IrcEncoder()\n{\n#ifdef HAVE_ICU\n ucsdet_close(d.detector);\n#endif \/\/ HAVE_ICU\n}\n\nQString IrcEncoder::encode(const QByteArray& data) const\n{\n QByteArray enc = d.encoding;\n if (enc.isNull())\n enc = detectEncoding(data);\n QTextCodec *codec = QTextCodec::codecForName(d.encoding);\n if (!codec)\n codec = QTextCodec::codecForLocale();\n return codec->toUnicode(data);\n}\n\nQByteArray IrcEncoder::detectEncoding(const QByteArray& data) const\n{\n Q_UNUSED(data);\n QByteArray encoding;\n#ifdef HAVE_ICU\n UErrorCode status = U_ZERO_ERROR;\n if (d.detector)\n {\n ucsdet_setText(d.detector, data.constData(), data.length(), &status);\n if (!U_FAILURE(status))\n {\n const UCharsetMatch* match = ucsdet_detect(d.detector, &status);\n if (match && !U_FAILURE(status))\n encoding = ucsdet_getName(match, &status);\n }\n }\n if (U_FAILURE(status))\n qWarning(\"IrcEncoder::detectEncoding() failed: %s\", u_errorName(status));\n#endif \/\/ HAVE_ICU\n return encoding;\n}\nIrcEncoder: revised encoding auto-detection\/*\n* Copyright (C) 2008-2011 J-P Nurmi \n*\n* This library is free software; you can redistribute it and\/or modify it\n* under the terms of the GNU Lesser General Public License as published by\n* the Free Software Foundation; either version 2 of the License, or (at your\n* option) any later version.\n*\n* This library is distributed in the hope that it will be useful, but WITHOUT\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n* License for more details.\n*\/\n\n#include \"ircencoder_p.h\"\n#include \n\n#ifdef HAVE_ICU\n#include \n#endif \/\/ HAVE_ICU\n\nstatic bool isUtf8(const QByteArray& utf8);\n\nIrcEncoder::IrcEncoder()\n{\n d.detector = 0;\n#ifdef HAVE_ICU\n UErrorCode status = U_ZERO_ERROR;\n d.detector = ucsdet_open(&status);\n if (U_FAILURE(status))\n qWarning(\"IrcEncoder: ICU initialization failed: %s\", u_errorName(status));\n#endif \/\/ HAVE_ICU\n}\n\nIrcEncoder::~IrcEncoder()\n{\n#ifdef HAVE_ICU\n ucsdet_close(d.detector);\n#endif \/\/ HAVE_ICU\n}\n\nQString IrcEncoder::encode(const QByteArray& data) const\n{\n QByteArray enc = d.encoding;\n if (enc.isNull())\n enc = detectEncoding(data);\n QTextCodec *codec = QTextCodec::codecForName(enc);\n if (!codec)\n codec = QTextCodec::codecForLocale();\n return codec->toUnicode(data);\n}\n\nQByteArray IrcEncoder::detectEncoding(const QByteArray& data) const\n{\n QByteArray encoding(\"ISO 8859-1\");\n if (isUtf8(data))\n return \"UTF-8\";\n#ifdef HAVE_ICU\n UErrorCode status = U_ZERO_ERROR;\n if (d.detector)\n {\n ucsdet_setText(d.detector, data.constData(), data.length(), &status);\n if (!U_FAILURE(status))\n {\n const UCharsetMatch* match = ucsdet_detect(d.detector, &status);\n if (match && !U_FAILURE(status))\n encoding = ucsdet_getName(match, &status);\n }\n }\n if (U_FAILURE(status))\n qWarning(\"IrcEncoder::detectEncoding() failed: %s\", u_errorName(status));\n#endif \/\/ HAVE_ICU\n return encoding;\n}\n\n\/*\n The Original Code is mozilla.org code.\n See http:\/\/lxr.mozilla.org\/mozilla\/source\/modules\/rdf\/src\/utils.c\n\n Copyright (C) 1998 Netscape Communications Corporation\n*\/\n\n#define kLeft1BitMask 0x80\n#define kLeft2BitsMask 0xC0\n#define kLeft3BitsMask 0xE0\n#define kLeft4BitsMask 0xF0\n#define kLeft5BitsMask 0xF8\n#define kLeft6BitsMask 0xFC\n#define kLeft7BitsMask 0xFE\n\n#define k2BytesLeadByte kLeft2BitsMask\n#define k3BytesLeadByte kLeft3BitsMask\n#define k4BytesLeadByte kLeft4BitsMask\n#define k5BytesLeadByte kLeft5BitsMask\n#define k6BytesLeadByte kLeft6BitsMask\n#define kTrialByte kLeft1BitMask\n\n#define UTF8_1Byte(c) ( 0 == ((c) & kLeft1BitMask))\n#define UTF8_2Bytes(c) ( k2BytesLeadByte == ((c) & kLeft3BitsMask))\n#define UTF8_3Bytes(c) ( k3BytesLeadByte == ((c) & kLeft4BitsMask))\n#define UTF8_4Bytes(c) ( k4BytesLeadByte == ((c) & kLeft5BitsMask))\n#define UTF8_5Bytes(c) ( k5BytesLeadByte == ((c) & kLeft6BitsMask))\n#define UTF8_6Bytes(c) ( k6BytesLeadByte == ((c) & kLeft7BitsMask))\n#define UTF8_ValidTrialByte(c) ( kTrialByte == ((c) & kLeft2BitsMask))\n\nbool isUtf8(const QByteArray& utf8)\n{\n int clen = 0;\n for (int i = 0; i < utf8.length(); i += clen)\n {\n if (UTF8_1Byte(utf8[i]))\n {\n clen = 1;\n }\n else if (UTF8_2Bytes(utf8[i]))\n {\n clen = 2;\n \/\/ No enough trail bytes\n if ((i + clen) > utf8.length())\n return false;\n \/\/ 0000 0000 - 0000 007F : should encode in less bytes\n if (0 == (utf8[i] & 0x1E))\n return false;\n }\n else if (UTF8_3Bytes(utf8[i]))\n {\n clen = 3;\n \/\/ No enough trail bytes\n if ((i + clen) > utf8.length())\n return false;\n \/\/ a single Surrogate should not show in 3 bytes UTF8, instead,\n \/\/ the pair should be intepreted as one single UCS4 char and\n \/\/ encoded UTF8 in 4 bytes\n if ((0xED == utf8[i]) && (0xA0 == (utf8[i+1] & 0xA0)))\n return false;\n \/\/ 0000 0000 - 0000 07FF : should encode in less bytes\n if ((0 == (utf8[i] & 0x0F)) && (0 == (utf8[i+1] & 0x20)))\n return false;\n }\n else if (UTF8_4Bytes(utf8[i]))\n {\n clen = 4;\n \/\/ No enough trail bytes\n if ((i + clen) > utf8.length())\n return false;\n \/\/ 0000 0000 - 0000 FFFF : should encode in less bytes\n if ((0 == (utf8[i] & 0x07 )) && (0 == (utf8[i+1] & 0x30)))\n return false;\n }\n else if (UTF8_5Bytes(utf8[i]))\n {\n clen = 5;\n \/\/ No enough trail bytes\n if ((i + clen) > utf8.length())\n return false;\n \/\/ 0000 0000 - 001F FFFF : should encode in less bytes\n if ((0 == (utf8[i] & 0x03 )) && (0 == (utf8[i+1] & 0x38)))\n return false;\n }\n else if (UTF8_6Bytes(utf8[i]))\n {\n clen = 6;\n \/\/ No enough trail bytes\n if ((i + clen) > utf8.length())\n return false;\n \/\/ 0000 0000 - 03FF FFFF : should encode in less bytes\n if ((0 == (utf8[i] & 0x01)) && (0 == (utf8[i+1] & 0x3E)))\n return false;\n }\n else\n {\n return false;\n }\n for (int j = 1; j < clen; ++j)\n {\n if (!UTF8_ValidTrialByte(utf8[i+j])) \/\/ Trail bytes invalid\n return false;\n }\n }\n return true;\n}\n<|endoftext|>"} {"text":"\/*********************************************************************\n* Software License Agreement (BSD License)\n* \n* Copyright (c) 2008, Willow Garage, Inc.\n* All rights reserved.\n* \n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n* \n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Willow Garage nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n* \n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n\/* Author: Wim Meeussen *\/\n\n\n#include \"urdf\/link.h\"\n#include \n#include \n\nnamespace urdf{\n\nboost::shared_ptr parseGeometry(TiXmlElement *g)\n{\n boost::shared_ptr geom;\n if (!g) return geom;\n\n TiXmlElement *shape = g->FirstChildElement();\n if (!shape)\n {\n ROS_ERROR(\"Geometry tag contains no child element.\");\n return geom;\n }\n\n std::string type_name = shape->ValueStr();\n if (type_name == \"sphere\")\n geom.reset(new Sphere);\n else if (type_name == \"box\")\n geom.reset(new Box);\n else if (type_name == \"cylinder\")\n geom.reset(new Cylinder);\n else if (type_name == \"mesh\")\n geom.reset(new Mesh);\n else\n {\n ROS_ERROR(\"Unknown geometry type '%s'\", type_name.c_str());\n return geom;\n }\n\n \/\/ clear geom object when fails to initialize\n if (!geom->initXml(shape)){\n ROS_ERROR(\"Geometry failed to parse\");\n geom.reset();\n }\n\n return geom;\n}\n\nbool Material::initXml(TiXmlElement *config)\n{\n bool has_rgb = false;\n bool has_filename = false;\n\n this->clear();\n\n if (!config->Attribute(\"name\"))\n {\n ROS_ERROR(\"Material must contain a name attribute\");\n return false;\n }\n\n this->name = config->Attribute(\"name\");\n\n \/\/ texture\n TiXmlElement *t = config->FirstChildElement(\"texture\");\n if (t)\n {\n if (t->Attribute(\"filename\"))\n {\n this->texture_filename = t->Attribute(\"filename\");\n has_filename = true;\n }\n else\n {\n ROS_ERROR(\"texture has no filename for Material %s\",this->name.c_str());\n }\n }\n\n \/\/ color\n TiXmlElement *c = config->FirstChildElement(\"color\");\n if (c)\n {\n if (c->Attribute(\"rgba\"))\n {\n if (!this->color.init(c->Attribute(\"rgba\")))\n {\n ROS_ERROR(\"Material %s has malformed color rgba values.\",this->name.c_str());\n this->color.clear();\n return false;\n }\n else\n has_rgb = true;\n }\n else\n {\n ROS_ERROR(\"Material %s color has no rgba\",this->name.c_str());\n }\n }\n\n return (has_rgb || has_filename);\n}\n\nbool Inertial::initXml(TiXmlElement *config)\n{\n this->clear();\n\n \/\/ Origin\n TiXmlElement *o = config->FirstChildElement(\"origin\");\n if (!o)\n {\n ROS_DEBUG(\"Origin tag not present for inertial element, using default (Identity)\");\n this->origin.clear();\n }\n else\n {\n if (!this->origin.initXml(o))\n {\n ROS_ERROR(\"Inertial has a malformed origin tag\");\n this->origin.clear();\n return false;\n }\n }\n\n TiXmlElement *mass_xml = config->FirstChildElement(\"mass\");\n if (!mass_xml)\n {\n ROS_ERROR(\"Inertial element must have mass element\");\n return false;\n }\n if (!mass_xml->Attribute(\"value\"))\n {\n ROS_ERROR(\"Inertial: mass element must have value attributes\");\n return false;\n }\n\n try\n {\n mass = boost::lexical_cast(mass_xml->Attribute(\"value\"));\n }\n catch (boost::bad_lexical_cast &e)\n {\n ROS_ERROR(\"mass (%s) is not a float\",mass_xml->Attribute(\"value\"));\n return false;\n }\n\n TiXmlElement *inertia_xml = config->FirstChildElement(\"inertia\");\n if (!inertia_xml)\n {\n ROS_ERROR(\"Inertial element must have inertia element\");\n return false;\n }\n if (!(inertia_xml->Attribute(\"ixx\") && inertia_xml->Attribute(\"ixy\") && inertia_xml->Attribute(\"ixz\") &&\n inertia_xml->Attribute(\"iyy\") && inertia_xml->Attribute(\"iyz\") &&\n inertia_xml->Attribute(\"izz\")))\n {\n ROS_ERROR(\"Inertial: inertia element must have ixx,ixy,ixz,iyy,iyz,izz attributes\");\n return false;\n }\n try\n {\n ixx = boost::lexical_cast(inertia_xml->Attribute(\"ixx\"));\n ixy = boost::lexical_cast(inertia_xml->Attribute(\"ixy\"));\n ixz = boost::lexical_cast(inertia_xml->Attribute(\"ixz\"));\n iyy = boost::lexical_cast(inertia_xml->Attribute(\"iyy\"));\n iyz = boost::lexical_cast(inertia_xml->Attribute(\"iyz\"));\n izz = boost::lexical_cast(inertia_xml->Attribute(\"izz\"));\n }\n catch (boost::bad_lexical_cast &e)\n {\n ROS_ERROR(\"one of the inertia elements: ixx (%s) ixy (%s) ixz (%s) iyy (%s) iyz (%s) izz (%s) is not a valid double\",\n inertia_xml->Attribute(\"ixx\"),\n inertia_xml->Attribute(\"ixy\"),\n inertia_xml->Attribute(\"ixz\"),\n inertia_xml->Attribute(\"iyy\"),\n inertia_xml->Attribute(\"iyz\"),\n inertia_xml->Attribute(\"izz\"));\n return false;\n }\n\n return true;\n}\n\nbool Visual::initXml(TiXmlElement *config)\n{\n this->clear();\n\n \/\/ Origin\n TiXmlElement *o = config->FirstChildElement(\"origin\");\n if (!o)\n {\n ROS_DEBUG(\"Origin tag not present for visual element, using default (Identity)\");\n this->origin.clear();\n }\n else if (!this->origin.initXml(o))\n {\n ROS_ERROR(\"Visual has a malformed origin tag\");\n this->origin.clear();\n return false;\n }\n\n \/\/ Geometry\n TiXmlElement *geom = config->FirstChildElement(\"geometry\");\n geometry = parseGeometry(geom);\n if (!geometry)\n {\n ROS_ERROR(\"Malformed geometry for Visual element\");\n return false;\n }\n\n \/\/ Material\n TiXmlElement *mat = config->FirstChildElement(\"material\");\n if (!mat)\n {\n ROS_DEBUG(\"visual element has no material tag.\");\n }\n else\n {\n \/\/ get material name\n if (!mat->Attribute(\"name\"))\n {\n ROS_ERROR(\"Visual material must contain a name attribute\");\n return false;\n }\n this->material_name = mat->Attribute(\"name\");\n\n \/\/ try to parse material element in place\n this->material.reset(new Material);\n if (!this->material->initXml(mat))\n {\n ROS_DEBUG(\"Could not parse material element in Visual block, maybe defined outside.\");\n this->material.reset();\n }\n else\n {\n ROS_DEBUG(\"Parsed material element in Visual block.\");\n }\n }\n\n return true;\n}\n\nbool Collision::initXml(TiXmlElement* config)\n{\n this->clear();\n\n \/\/ Origin\n TiXmlElement *o = config->FirstChildElement(\"origin\");\n if (!o)\n {\n ROS_DEBUG(\"Origin tag not present for collision element, using default (Identity)\");\n this->origin.clear();\n }\n else if (!this->origin.initXml(o))\n {\n ROS_ERROR(\"Collision has a malformed origin tag\");\n this->origin.clear();\n return false;\n }\n\n \/\/ Geometry\n TiXmlElement *geom = config->FirstChildElement(\"geometry\");\n geometry = parseGeometry(geom);\n if (!geometry)\n {\n ROS_ERROR(\"Malformed geometry for Collision element\");\n return false;\n }\n\n \/\/ Group Tag (optional)\n \/\/ collision blocks without a group tag are designated to the \"default\" group\n const char *group_name_char = config->Attribute(\"group\");\n if (!group_name_char)\n group_name = std::string(\"default\");\n else\n group_name = std::string(group_name_char);\n\n return true;\n}\n\nbool Sphere::initXml(TiXmlElement *c)\n{\n this->clear();\n\n this->type = SPHERE;\n if (!c->Attribute(\"radius\"))\n {\n ROS_ERROR(\"Sphere shape must have a radius attribute\");\n return false;\n }\n\n try\n {\n radius = boost::lexical_cast(c->Attribute(\"radius\"));\n }\n catch (boost::bad_lexical_cast &e)\n {\n ROS_ERROR(\"radius (%s) is not a valid float\",c->Attribute(\"radius\"));\n return false;\n }\n\n return true;\n}\n\nbool Box::initXml(TiXmlElement *c)\n{\n this->clear();\n\n this->type = BOX;\n if (!c->Attribute(\"size\"))\n {\n ROS_ERROR(\"Box shape has no size attribute\");\n return false;\n }\n if (!dim.init(c->Attribute(\"size\")))\n {\n ROS_ERROR(\"Box shape has malformed size attribute\");\n dim.clear();\n return false;\n }\n return true;\n}\n\nbool Cylinder::initXml(TiXmlElement *c)\n{\n this->clear();\n\n this->type = CYLINDER;\n if (!c->Attribute(\"length\") ||\n !c->Attribute(\"radius\"))\n {\n ROS_ERROR(\"Cylinder shape must have both length and radius attributes\");\n return false;\n }\n\n try\n {\n length = boost::lexical_cast(c->Attribute(\"length\"));\n }\n catch (boost::bad_lexical_cast &e)\n {\n ROS_ERROR(\"length (%s) is not a valid float\",c->Attribute(\"length\"));\n return false;\n }\n\n try\n {\n radius = boost::lexical_cast(c->Attribute(\"radius\"));\n }\n catch (boost::bad_lexical_cast &e)\n {\n ROS_ERROR(\"radius (%s) is not a valid float\",c->Attribute(\"radius\"));\n return false;\n }\n\n return true;\n}\n\nbool Mesh::initXml(TiXmlElement *c)\n{\n this->clear();\n\n this->type = MESH;\n if (!c->Attribute(\"filename\"))\n {\n ROS_ERROR(\"Mesh must contain a filename attribute\");\n return false;\n }\n\n filename = c->Attribute(\"filename\");\n\n if (c->Attribute(\"scale\"))\n {\n if (!this->scale.init(c->Attribute(\"scale\")))\n {\n ROS_ERROR(\"Mesh scale was specified, but could not be parsed\");\n this->scale.clear();\n return false;\n }\n }\n else\n ROS_DEBUG(\"Mesh scale was not specified, default to (1,1,1)\");\n\n return true;\n}\n\n\nbool Link::initXml(TiXmlElement* config)\n{\n this->clear();\n\n const char *name_char = config->Attribute(\"name\");\n if (!name_char)\n {\n ROS_ERROR(\"No name given for the link.\");\n return false;\n }\n name = std::string(name_char);\n\n \/\/ Inertial (optional)\n TiXmlElement *i = config->FirstChildElement(\"inertial\");\n if (i)\n {\n inertial.reset(new Inertial);\n if (!inertial->initXml(i))\n {\n ROS_ERROR(\"Could not parse inertial element for Link '%s'\", this->name.c_str());\n return false;\n }\n }\n\n \/\/ Visual (optional)\n TiXmlElement *v = config->FirstChildElement(\"visual\");\n if (v)\n {\n visual.reset(new Visual);\n if (!visual->initXml(v))\n {\n ROS_ERROR(\"Could not parse visual element for Link '%s'\", this->name.c_str());\n return false;\n }\n }\n\n \/\/ Multiple Collisions (optional)\n for (TiXmlElement* col_xml = config->FirstChildElement(\"collision\"); col_xml; col_xml = col_xml->NextSiblingElement(\"collision\"))\n {\n boost::shared_ptr col;\n col.reset(new Collision);\n\n if (col->initXml(col_xml))\n {\n boost::shared_ptr > > cols = this->getCollision(col->group_name);\n if (!cols)\n {\n \/\/ group does not exist, create one and add to map\n cols.reset(new std::vector >);\n \/\/ new group name, create vector, add vector to map and add Collision to the vector\n this->collision_groups.insert(make_pair(col->group_name,cols));\n ROS_DEBUG(\"successfully added a new collision group name '%s'\",col->group_name.c_str());\n }\n\n \/\/ group exists, add Collision to the vector in the map\n cols->push_back(col);\n ROS_DEBUG(\"successfully added a new collision under group name '%s'\",col->group_name.c_str());\n }\n else\n {\n ROS_ERROR(\"Could not parse collision element for Link '%s'\", this->name.c_str());\n col.reset();\n return false;\n }\n }\n\n \/\/ Collision (optional)\n \/\/ Assign one single default collision pointer from the collision_groups map\n boost::shared_ptr > > default_collision = this->getCollision(\"default\");\n if (!default_collision)\n {\n ROS_DEBUG(\"No 'default' collision group for Link '%s'\", this->name.c_str());\n }\n else if (default_collision->empty())\n {\n ROS_DEBUG(\"'default' collision group is empty for Link '%s'\", this->name.c_str());\n }\n else\n this->collision = (*default_collision->begin());\n\n return true;\n}\n\nboost::shared_ptr > > Link::getCollision(const std::string& group_name) const\n{\n boost::shared_ptr > > ptr;\n if (this->collision_groups.find(group_name) == this->collision_groups.end())\n ptr.reset();\n else\n ptr = this->collision_groups.find(group_name)->second;\n return ptr;\n}\n\n\nvoid Link::setParent(boost::shared_ptr parent)\n{\n this->parent_link_ = parent;\n ROS_DEBUG(\"set parent Link '%s' for Link '%s'\", parent->name.c_str(), this->name.c_str());\n}\n\nvoid Link::setParentJoint(boost::shared_ptr parent)\n{\n this->parent_joint = parent;\n ROS_DEBUG(\"set parent joint '%s' to Link '%s'\", parent->name.c_str(), this->name.c_str());\n}\n\nvoid Link::addChild(boost::shared_ptr child)\n{\n this->child_links.push_back(child);\n ROS_DEBUG(\"added child Link '%s' to Link '%s'\", child->name.c_str(), this->name.c_str());\n}\n\nvoid Link::addChildJoint(boost::shared_ptr child)\n{\n this->child_joints.push_back(child);\n ROS_DEBUG(\"added child Joint '%s' to Link '%s'\", child->name.c_str(), this->name.c_str());\n}\n\n\n\n}\n\nforgot to reset collision\/*********************************************************************\n* Software License Agreement (BSD License)\n* \n* Copyright (c) 2008, Willow Garage, Inc.\n* All rights reserved.\n* \n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n* \n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Willow Garage nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n* \n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n\/* Author: Wim Meeussen *\/\n\n\n#include \"urdf\/link.h\"\n#include \n#include \n\nnamespace urdf{\n\nboost::shared_ptr parseGeometry(TiXmlElement *g)\n{\n boost::shared_ptr geom;\n if (!g) return geom;\n\n TiXmlElement *shape = g->FirstChildElement();\n if (!shape)\n {\n ROS_ERROR(\"Geometry tag contains no child element.\");\n return geom;\n }\n\n std::string type_name = shape->ValueStr();\n if (type_name == \"sphere\")\n geom.reset(new Sphere);\n else if (type_name == \"box\")\n geom.reset(new Box);\n else if (type_name == \"cylinder\")\n geom.reset(new Cylinder);\n else if (type_name == \"mesh\")\n geom.reset(new Mesh);\n else\n {\n ROS_ERROR(\"Unknown geometry type '%s'\", type_name.c_str());\n return geom;\n }\n\n \/\/ clear geom object when fails to initialize\n if (!geom->initXml(shape)){\n ROS_ERROR(\"Geometry failed to parse\");\n geom.reset();\n }\n\n return geom;\n}\n\nbool Material::initXml(TiXmlElement *config)\n{\n bool has_rgb = false;\n bool has_filename = false;\n\n this->clear();\n\n if (!config->Attribute(\"name\"))\n {\n ROS_ERROR(\"Material must contain a name attribute\");\n return false;\n }\n\n this->name = config->Attribute(\"name\");\n\n \/\/ texture\n TiXmlElement *t = config->FirstChildElement(\"texture\");\n if (t)\n {\n if (t->Attribute(\"filename\"))\n {\n this->texture_filename = t->Attribute(\"filename\");\n has_filename = true;\n }\n else\n {\n ROS_ERROR(\"texture has no filename for Material %s\",this->name.c_str());\n }\n }\n\n \/\/ color\n TiXmlElement *c = config->FirstChildElement(\"color\");\n if (c)\n {\n if (c->Attribute(\"rgba\"))\n {\n if (!this->color.init(c->Attribute(\"rgba\")))\n {\n ROS_ERROR(\"Material %s has malformed color rgba values.\",this->name.c_str());\n this->color.clear();\n return false;\n }\n else\n has_rgb = true;\n }\n else\n {\n ROS_ERROR(\"Material %s color has no rgba\",this->name.c_str());\n }\n }\n\n return (has_rgb || has_filename);\n}\n\nbool Inertial::initXml(TiXmlElement *config)\n{\n this->clear();\n\n \/\/ Origin\n TiXmlElement *o = config->FirstChildElement(\"origin\");\n if (!o)\n {\n ROS_DEBUG(\"Origin tag not present for inertial element, using default (Identity)\");\n this->origin.clear();\n }\n else\n {\n if (!this->origin.initXml(o))\n {\n ROS_ERROR(\"Inertial has a malformed origin tag\");\n this->origin.clear();\n return false;\n }\n }\n\n TiXmlElement *mass_xml = config->FirstChildElement(\"mass\");\n if (!mass_xml)\n {\n ROS_ERROR(\"Inertial element must have mass element\");\n return false;\n }\n if (!mass_xml->Attribute(\"value\"))\n {\n ROS_ERROR(\"Inertial: mass element must have value attributes\");\n return false;\n }\n\n try\n {\n mass = boost::lexical_cast(mass_xml->Attribute(\"value\"));\n }\n catch (boost::bad_lexical_cast &e)\n {\n ROS_ERROR(\"mass (%s) is not a float\",mass_xml->Attribute(\"value\"));\n return false;\n }\n\n TiXmlElement *inertia_xml = config->FirstChildElement(\"inertia\");\n if (!inertia_xml)\n {\n ROS_ERROR(\"Inertial element must have inertia element\");\n return false;\n }\n if (!(inertia_xml->Attribute(\"ixx\") && inertia_xml->Attribute(\"ixy\") && inertia_xml->Attribute(\"ixz\") &&\n inertia_xml->Attribute(\"iyy\") && inertia_xml->Attribute(\"iyz\") &&\n inertia_xml->Attribute(\"izz\")))\n {\n ROS_ERROR(\"Inertial: inertia element must have ixx,ixy,ixz,iyy,iyz,izz attributes\");\n return false;\n }\n try\n {\n ixx = boost::lexical_cast(inertia_xml->Attribute(\"ixx\"));\n ixy = boost::lexical_cast(inertia_xml->Attribute(\"ixy\"));\n ixz = boost::lexical_cast(inertia_xml->Attribute(\"ixz\"));\n iyy = boost::lexical_cast(inertia_xml->Attribute(\"iyy\"));\n iyz = boost::lexical_cast(inertia_xml->Attribute(\"iyz\"));\n izz = boost::lexical_cast(inertia_xml->Attribute(\"izz\"));\n }\n catch (boost::bad_lexical_cast &e)\n {\n ROS_ERROR(\"one of the inertia elements: ixx (%s) ixy (%s) ixz (%s) iyy (%s) iyz (%s) izz (%s) is not a valid double\",\n inertia_xml->Attribute(\"ixx\"),\n inertia_xml->Attribute(\"ixy\"),\n inertia_xml->Attribute(\"ixz\"),\n inertia_xml->Attribute(\"iyy\"),\n inertia_xml->Attribute(\"iyz\"),\n inertia_xml->Attribute(\"izz\"));\n return false;\n }\n\n return true;\n}\n\nbool Visual::initXml(TiXmlElement *config)\n{\n this->clear();\n\n \/\/ Origin\n TiXmlElement *o = config->FirstChildElement(\"origin\");\n if (!o)\n {\n ROS_DEBUG(\"Origin tag not present for visual element, using default (Identity)\");\n this->origin.clear();\n }\n else if (!this->origin.initXml(o))\n {\n ROS_ERROR(\"Visual has a malformed origin tag\");\n this->origin.clear();\n return false;\n }\n\n \/\/ Geometry\n TiXmlElement *geom = config->FirstChildElement(\"geometry\");\n geometry = parseGeometry(geom);\n if (!geometry)\n {\n ROS_ERROR(\"Malformed geometry for Visual element\");\n return false;\n }\n\n \/\/ Material\n TiXmlElement *mat = config->FirstChildElement(\"material\");\n if (!mat)\n {\n ROS_DEBUG(\"visual element has no material tag.\");\n }\n else\n {\n \/\/ get material name\n if (!mat->Attribute(\"name\"))\n {\n ROS_ERROR(\"Visual material must contain a name attribute\");\n return false;\n }\n this->material_name = mat->Attribute(\"name\");\n\n \/\/ try to parse material element in place\n this->material.reset(new Material);\n if (!this->material->initXml(mat))\n {\n ROS_DEBUG(\"Could not parse material element in Visual block, maybe defined outside.\");\n this->material.reset();\n }\n else\n {\n ROS_DEBUG(\"Parsed material element in Visual block.\");\n }\n }\n\n return true;\n}\n\nbool Collision::initXml(TiXmlElement* config)\n{\n this->clear();\n\n \/\/ Origin\n TiXmlElement *o = config->FirstChildElement(\"origin\");\n if (!o)\n {\n ROS_DEBUG(\"Origin tag not present for collision element, using default (Identity)\");\n this->origin.clear();\n }\n else if (!this->origin.initXml(o))\n {\n ROS_ERROR(\"Collision has a malformed origin tag\");\n this->origin.clear();\n return false;\n }\n\n \/\/ Geometry\n TiXmlElement *geom = config->FirstChildElement(\"geometry\");\n geometry = parseGeometry(geom);\n if (!geometry)\n {\n ROS_ERROR(\"Malformed geometry for Collision element\");\n return false;\n }\n\n \/\/ Group Tag (optional)\n \/\/ collision blocks without a group tag are designated to the \"default\" group\n const char *group_name_char = config->Attribute(\"group\");\n if (!group_name_char)\n group_name = std::string(\"default\");\n else\n group_name = std::string(group_name_char);\n\n return true;\n}\n\nbool Sphere::initXml(TiXmlElement *c)\n{\n this->clear();\n\n this->type = SPHERE;\n if (!c->Attribute(\"radius\"))\n {\n ROS_ERROR(\"Sphere shape must have a radius attribute\");\n return false;\n }\n\n try\n {\n radius = boost::lexical_cast(c->Attribute(\"radius\"));\n }\n catch (boost::bad_lexical_cast &e)\n {\n ROS_ERROR(\"radius (%s) is not a valid float\",c->Attribute(\"radius\"));\n return false;\n }\n\n return true;\n}\n\nbool Box::initXml(TiXmlElement *c)\n{\n this->clear();\n\n this->type = BOX;\n if (!c->Attribute(\"size\"))\n {\n ROS_ERROR(\"Box shape has no size attribute\");\n return false;\n }\n if (!dim.init(c->Attribute(\"size\")))\n {\n ROS_ERROR(\"Box shape has malformed size attribute\");\n dim.clear();\n return false;\n }\n return true;\n}\n\nbool Cylinder::initXml(TiXmlElement *c)\n{\n this->clear();\n\n this->type = CYLINDER;\n if (!c->Attribute(\"length\") ||\n !c->Attribute(\"radius\"))\n {\n ROS_ERROR(\"Cylinder shape must have both length and radius attributes\");\n return false;\n }\n\n try\n {\n length = boost::lexical_cast(c->Attribute(\"length\"));\n }\n catch (boost::bad_lexical_cast &e)\n {\n ROS_ERROR(\"length (%s) is not a valid float\",c->Attribute(\"length\"));\n return false;\n }\n\n try\n {\n radius = boost::lexical_cast(c->Attribute(\"radius\"));\n }\n catch (boost::bad_lexical_cast &e)\n {\n ROS_ERROR(\"radius (%s) is not a valid float\",c->Attribute(\"radius\"));\n return false;\n }\n\n return true;\n}\n\nbool Mesh::initXml(TiXmlElement *c)\n{\n this->clear();\n\n this->type = MESH;\n if (!c->Attribute(\"filename\"))\n {\n ROS_ERROR(\"Mesh must contain a filename attribute\");\n return false;\n }\n\n filename = c->Attribute(\"filename\");\n\n if (c->Attribute(\"scale\"))\n {\n if (!this->scale.init(c->Attribute(\"scale\")))\n {\n ROS_ERROR(\"Mesh scale was specified, but could not be parsed\");\n this->scale.clear();\n return false;\n }\n }\n else\n ROS_DEBUG(\"Mesh scale was not specified, default to (1,1,1)\");\n\n return true;\n}\n\n\nbool Link::initXml(TiXmlElement* config)\n{\n this->clear();\n\n const char *name_char = config->Attribute(\"name\");\n if (!name_char)\n {\n ROS_ERROR(\"No name given for the link.\");\n return false;\n }\n name = std::string(name_char);\n\n \/\/ Inertial (optional)\n TiXmlElement *i = config->FirstChildElement(\"inertial\");\n if (i)\n {\n inertial.reset(new Inertial);\n if (!inertial->initXml(i))\n {\n ROS_ERROR(\"Could not parse inertial element for Link '%s'\", this->name.c_str());\n return false;\n }\n }\n\n \/\/ Visual (optional)\n TiXmlElement *v = config->FirstChildElement(\"visual\");\n if (v)\n {\n visual.reset(new Visual);\n if (!visual->initXml(v))\n {\n ROS_ERROR(\"Could not parse visual element for Link '%s'\", this->name.c_str());\n return false;\n }\n }\n\n \/\/ Multiple Collisions (optional)\n for (TiXmlElement* col_xml = config->FirstChildElement(\"collision\"); col_xml; col_xml = col_xml->NextSiblingElement(\"collision\"))\n {\n boost::shared_ptr col;\n col.reset(new Collision);\n\n if (col->initXml(col_xml))\n {\n boost::shared_ptr > > cols = this->getCollision(col->group_name);\n if (!cols)\n {\n \/\/ group does not exist, create one and add to map\n cols.reset(new std::vector >);\n \/\/ new group name, create vector, add vector to map and add Collision to the vector\n this->collision_groups.insert(make_pair(col->group_name,cols));\n ROS_DEBUG(\"successfully added a new collision group name '%s'\",col->group_name.c_str());\n }\n\n \/\/ group exists, add Collision to the vector in the map\n cols->push_back(col);\n ROS_DEBUG(\"successfully added a new collision under group name '%s'\",col->group_name.c_str());\n }\n else\n {\n ROS_ERROR(\"Could not parse collision element for Link '%s'\", this->name.c_str());\n col.reset();\n return false;\n }\n }\n\n \/\/ Collision (optional)\n \/\/ Assign one single default collision pointer from the collision_groups map\n this->collision.reset();\n boost::shared_ptr > > default_collision = this->getCollision(\"default\");\n if (!default_collision)\n {\n ROS_DEBUG(\"No 'default' collision group for Link '%s'\", this->name.c_str());\n }\n else if (default_collision->empty())\n {\n ROS_DEBUG(\"'default' collision group is empty for Link '%s'\", this->name.c_str());\n }\n else\n this->collision = (*default_collision->begin());\n\n return true;\n}\n\nboost::shared_ptr > > Link::getCollision(const std::string& group_name) const\n{\n boost::shared_ptr > > ptr;\n if (this->collision_groups.find(group_name) == this->collision_groups.end())\n ptr.reset();\n else\n ptr = this->collision_groups.find(group_name)->second;\n return ptr;\n}\n\n\nvoid Link::setParent(boost::shared_ptr parent)\n{\n this->parent_link_ = parent;\n ROS_DEBUG(\"set parent Link '%s' for Link '%s'\", parent->name.c_str(), this->name.c_str());\n}\n\nvoid Link::setParentJoint(boost::shared_ptr parent)\n{\n this->parent_joint = parent;\n ROS_DEBUG(\"set parent joint '%s' to Link '%s'\", parent->name.c_str(), this->name.c_str());\n}\n\nvoid Link::addChild(boost::shared_ptr child)\n{\n this->child_links.push_back(child);\n ROS_DEBUG(\"added child Link '%s' to Link '%s'\", child->name.c_str(), this->name.c_str());\n}\n\nvoid Link::addChildJoint(boost::shared_ptr child)\n{\n this->child_joints.push_back(child);\n ROS_DEBUG(\"added child Joint '%s' to Link '%s'\", child->name.c_str(), this->name.c_str());\n}\n\n\n\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing mjolnir::operator\"\" _str;\n\nnamespace mjolnir\n{\n\nstd::vector split_chain_ids(const std::string& key)\n{\n if(key.size() == 1)\n {\n if(not std::isupper(key.front()))\n {\n throw std::runtime_error(\"jarngreipr::split_chain_ids: \"\n \"chain ID should be specified in upper case.\");\n }\n return std::vector{key.front()};\n }\n\n if(not (key.size() == 3 && (key.at(1) == '-' || key.at(1) == '&') &&\n std::isupper(key.front()) && std::isupper(key.back())))\n {\n throw std::runtime_error(\"jarngreipr::split_chain_ids: \"\n \"chain ID must be upper case and supplied in this way: \"\n \"'A', 'A-C', or 'A&D'\");\n }\n\n if(key.at(1) == '&')\n {\n \/\/ \"A&D\" -> {A, D}\n return std::vector{key.front(), key.back()};\n }\n\n \/\/ \"A-D\" -> {A, B, C, D}\n std::vector ids;\n for(char c = key.front(); c <= key.back(); ++c)\n {\n ids.push_back(c);\n }\n return ids;\n}\n\ntemplate\nstd::vector>>\nread_reference_structures(const std::vector& structures)\n{\n std::vector>> tables;\n for(const auto& conf : structures)\n {\n std::map> table;\n for(const auto& kvp : conf)\n {\n std::vector chIDs = split_chain_ids(kvp.first);\n const toml::Table val = toml::get(kvp.second);\n\n std::string filename;\n try\n {\n filename = toml::get(val.at(\"file\"));\n }\n catch(const std::exception& except)\n {\n throw std::runtime_error(\"jarngreipr::read_reference_structures: \"\n \"file is not specified for chain \" + kvp.first);\n }\n\n if(filename.substr(filename.size() - 4) == \".pdb\")\n {\n mjolnir::PDBReader pdb_reader(filename);\n if(not pdb_reader.is_good())\n {\n throw std::runtime_error(\n \"jarngreipr::read_reference_structures: \"\n \"file open error: filename = \" + filename);\n }\n while(not pdb_reader.is_eof())\n {\n const auto chain = pdb_reader.read_next_chain();\n const char chain_id = chain.chain_id();\n const auto found = std::find(\n chIDs.begin(), chIDs.end(), chain_id);\n if(found != chIDs.end())\n {\n table[*found] = chain;\n chIDs.erase(found);\n }\n }\n }\n else\n {\n throw std::runtime_error(\"jarngreipr::read_reference_structures: \"\n \"unrecognizable file: \" + filename);\n }\n\n if(not chIDs.empty())\n {\n std::string mes(\"jarngreipr::read_reference_structures: \"\n \"missing chains in : \");\n mes += filename;\n mes += \", ID = \";\n mes += std::string(chIDs.begin(), chIDs.end());\n throw std::runtime_error(mes);\n }\n }\n tables.push_back(std::move(table));\n }\n return tables;\n}\n\ntemplate\nstd::vector>>\nread_initial_structures(const std::vector& structures)\n{\n std::vector>> tables;\n for(const auto& conf : structures)\n {\n std::map> table;\n for(const auto& kvp : conf)\n {\n std::vector chIDs = split_chain_ids(kvp.first);\n const toml::Table val = toml::get(kvp.second);\n\n std::string filename;\n try\n {\n filename = toml::get(val.at(\"initial\"));\n }\n catch(const std::exception& except)\n {\n \/\/ do nothing. initial configuration is optional.\n }\n try\n {\n filename = toml::get(val.at(\"file\"));\n }\n catch(const std::exception& except)\n {\n throw std::runtime_error(\"jarngreipr::read_initial_structures: \"\n \"neither file nor initial exists for chain \" + kvp.first);\n }\n\n if(filename.substr(filename.size() - 4) == \".pdb\")\n {\n mjolnir::PDBReader pdb_reader(filename);\n if(not pdb_reader.is_good())\n {\n throw std::runtime_error(\n \"jarngreipr::read_reference_structures: \"\n \"file open error: \" + filename);\n }\n while(not pdb_reader.is_eof())\n {\n const auto chain = pdb_reader.read_next_chain();\n const char chain_id = chain.chain_id();\n const auto found = std::find(\n chIDs.begin(), chIDs.end(), chain_id);\n if(found != chIDs.end())\n {\n table[*found] = chain;\n chIDs.erase(found);\n }\n }\n }\n else\n {\n throw std::runtime_error(\"jarngreipr::read_reference_structures: \"\n \"unrecognizable file: \" + filename);\n }\n\n if(not chIDs.empty())\n {\n std::string mes(\"jarngreipr::read_reference_structures: \"\n \"missing chains in : \");\n mes += filename;\n mes += \", ID = \";\n mes += std::string(chIDs.begin(), chIDs.end());\n throw std::runtime_error(mes);\n }\n }\n\n tables.push_back(std::move(table));\n }\n return tables;\n}\n\ninline std::vector>\nread_coarse_grained_models(const std::vector& structures)\n{\n std::vector> tables;\n for(const auto& conf : structures)\n {\n std::map table;\n for(const auto& kvp : conf)\n {\n const std::vector chIDs = split_chain_ids(kvp.first);\n const toml::Table val = toml::get(kvp.second);\n\n std::string model_name;\n try\n {\n model_name = toml::get(val.at(\"model\"));\n }\n catch(const std::exception& except)\n {\n throw std::runtime_error(\"jarngreipr::read_coarse_grained model: \"\n \"model is not specified for chain \" + kvp.first);\n }\n\n for(char id : chIDs)\n {\n table[id] = model_name;\n }\n }\n tables.push_back(std::move(table));\n }\n return tables;\n}\n\ntemplate\nstd::vector>>\napply_coarse_grained_models(\n const std::vector>>& pdbs,\n const std::vector>& models)\n{\n assert(pdbs.size() == models.size());\n std::vector>> cgss;\n for(std::size_t i=0; i> cgs;\n const auto& pdb = pdbs.at(i);\n const auto& model = models.at(i);\n\n for(const auto& kv : pdb)\n {\n const auto chid = kv.first;\n const auto& ch = kv.second;\n cgs[chid] = make_coarse_grained(ch, model.at(chid));\n }\n\n std::size_t index = 0;\n for(auto& id_chain: cgs)\n {\n for(auto& bead : id_chain.second)\n {\n bead->index() = index;\n ++index;\n }\n }\n\n cgss.push_back(std::move(cgs));\n }\n return cgss;\n}\n\n} \/\/ mjolnir\n\nint main(int argc, char **argv)\n{\n typedef mjolnir::Vector coord_type;\n typedef mjolnir::PDBChain pdb_chain_type;\n typedef mjolnir::CGChain cg_chain_type;\n\n if(argc != 2)\n {\n std::cerr << \"Usage: $ jarngreipr [file.toml]\\n\";\n std::cerr << \" see input\/example.toml for the format\" << std::endl;\n return 1;\n }\n\n const auto input_data = toml::parse(std::string(argv[1]));\n\n \/* prepairing parameters *\/\n const auto general = toml::get(input_data.at(\"general\"));\n const auto file_name = toml::get(general.at(\"file_prefix\"));\n std::random_device devrand;\n std::mt19937 mt(devrand());\n\n \/* output general information *\/{\n std::cout << \"[general]\\n\";\n std::cout << \"file_name = \"\n << toml::get_or(general, \"file_prefix\", \"data\"_str) << '\\n';\n std::cout << \"output_path = \"\n << toml::get_or(general, \"output_path\", \".\/\"_str) << '\\n';\n std::cout << \"precision = \"\n << toml::get_or(general, \"precision\", \"double\"_str) << '\\n';\n std::cout << \"boundary = \"\n << toml::get_or(general, \"boundary\", \"Unlimited\"_str) << '\\n';\n std::cout << \"thread = \" << std::boolalpha\n << toml::get_or(general, \"thread\", false) << '\\n';\n std::cout << \"GPU = \" << std::boolalpha\n << toml::get_or(general, \"GPU\", false) << '\\n';\n const std::int64_t default_seed = devrand();\n std::cout << \"seed = \"\n << toml::get_or(general, \"seed\", default_seed) << '\\n';\n }\n\n\n const auto parameters =\n toml::parse(toml::get(general.at(\"parameters\")));\n const auto phys_paras = toml::get(parameters.at(\"physical_constants\"));\n const auto vac_permit = toml::get(phys_paras.at(\"ε0\"));\n\n const auto& mass =\n toml::get(parameters.at(\"mass\"));\n const auto& phys =\n toml::get(parameters.at(\"physical_constants\"));\n\n const auto system_config =\n toml::get>(input_data.at(\"systems\"));\n\n \/* generating coarse-grained structures *\/\n const auto structure_config =\n toml::get>(input_data.at(\"structures\"));\n\n \/\/ vector>>\n \/\/ in most cases, the size of vector is one.\n const auto ref_pdbs =\n mjolnir::read_reference_structures(structure_config);\n const auto ini_pdbs =\n mjolnir::read_initial_structures (structure_config);\n const auto models =\n mjolnir::read_coarse_grained_models(structure_config);\n\n \/\/ apply coarse-grained model to input pdbs\n const auto ref_cgss = mjolnir::apply_coarse_grained_models(ref_pdbs, models);\n const auto ini_cgss = mjolnir::apply_coarse_grained_models(ini_pdbs, models);\n\n \/\/ output system setting and cg structure\n assert(system_config.size() == ini_cgss.size());\n for(std::size_t i=0; i(sysconf.at(\"temperature\"));\n std::cout << \"temperature = \" << std::fixed << T << '\\n';\n std::cout << \"ionic_strength = \" << std::fixed\n << toml::get(sysconf.at(\"ionic_strength\")) << '\\n';\n std::cout << \"boundary = {\";\n for(const auto& kv : toml::get(sysconf.at(\"boundary\")))\n {\n if(kv.first == \"type\")\n {\n std::cout << kv.first << \"=\\\"\" << toml::get(kv.second) << '\\\"';\n }\n else\n {\n const auto& crd = toml::get>(kv.second);\n std::cout << kv.first << \"=[\" << crd[0] << ',' << crd[1] << ','\n << crd[2] << ']';\n }\n }\n std::cout << \"}\\n\";\n \/\/ }}}\n\n std::cout << \"particles = [\\n\";\n const auto& chain_table = ini_cgss.at(i);\n for(const auto& id_chain_pair : chain_table)\n {\n std::cerr << \"chain ID = \" << id_chain_pair.first;\n std::cerr << \" has \" << id_chain_pair.second.size() << \" beads.\" << std::endl;\n for(std::size_t j=0; j(phys.at(\"kB\"));\n const auto m = toml::get(mass.at(bead->name()));\n const auto p = bead->position();\n std::normal_distribution mxw_blz(0.0, std::sqrt(kB*T\/m));\n std::cout << \"{mass = \" << m\n << \", position = [\" << p[0] << ',' << p[1] << ',' << p[2]\n << \"], velocity = [\" << mxw_blz(mt) << ','\n << mxw_blz(mt) << ',' << mxw_blz(mt) << \"]},\\n\";\n }\n }\n std::cout << \"]\\n\";\n }\n\n const std::unique_ptr>\n ffgen = mjolnir::make_unique>();\n\n for(const auto& chains : ref_cgss)\n {\n std::cout << \"[[forcefields]]\\n\";\n for(const auto& idch : chains)\n {\n const auto& ch = idch.second;\n const auto connect = ffgen->generate(std::cout, ch);\n }\n }\n\n \/\/ output parameter\n\n return 0;\n}\nmake file_prefix required#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing mjolnir::operator\"\" _str;\n\nnamespace mjolnir\n{\n\nstd::vector split_chain_ids(const std::string& key)\n{\n if(key.size() == 1)\n {\n if(not std::isupper(key.front()))\n {\n throw std::runtime_error(\"jarngreipr::split_chain_ids: \"\n \"chain ID should be specified in upper case.\");\n }\n return std::vector{key.front()};\n }\n\n if(not (key.size() == 3 && (key.at(1) == '-' || key.at(1) == '&') &&\n std::isupper(key.front()) && std::isupper(key.back())))\n {\n throw std::runtime_error(\"jarngreipr::split_chain_ids: \"\n \"chain ID must be upper case and supplied in this way: \"\n \"'A', 'A-C', or 'A&D'\");\n }\n\n if(key.at(1) == '&')\n {\n \/\/ \"A&D\" -> {A, D}\n return std::vector{key.front(), key.back()};\n }\n\n \/\/ \"A-D\" -> {A, B, C, D}\n std::vector ids;\n for(char c = key.front(); c <= key.back(); ++c)\n {\n ids.push_back(c);\n }\n return ids;\n}\n\ntemplate\nstd::vector>>\nread_reference_structures(const std::vector& structures)\n{\n std::vector>> tables;\n for(const auto& conf : structures)\n {\n std::map> table;\n for(const auto& kvp : conf)\n {\n std::vector chIDs = split_chain_ids(kvp.first);\n const toml::Table val = toml::get(kvp.second);\n\n std::string filename;\n try\n {\n filename = toml::get(val.at(\"file\"));\n }\n catch(const std::exception& except)\n {\n throw std::runtime_error(\"jarngreipr::read_reference_structures: \"\n \"file is not specified for chain \" + kvp.first);\n }\n\n if(filename.substr(filename.size() - 4) == \".pdb\")\n {\n mjolnir::PDBReader pdb_reader(filename);\n if(not pdb_reader.is_good())\n {\n throw std::runtime_error(\n \"jarngreipr::read_reference_structures: \"\n \"file open error: filename = \" + filename);\n }\n while(not pdb_reader.is_eof())\n {\n const auto chain = pdb_reader.read_next_chain();\n const char chain_id = chain.chain_id();\n const auto found = std::find(\n chIDs.begin(), chIDs.end(), chain_id);\n if(found != chIDs.end())\n {\n table[*found] = chain;\n chIDs.erase(found);\n }\n }\n }\n else\n {\n throw std::runtime_error(\"jarngreipr::read_reference_structures: \"\n \"unrecognizable file: \" + filename);\n }\n\n if(not chIDs.empty())\n {\n std::string mes(\"jarngreipr::read_reference_structures: \"\n \"missing chains in : \");\n mes += filename;\n mes += \", ID = \";\n mes += std::string(chIDs.begin(), chIDs.end());\n throw std::runtime_error(mes);\n }\n }\n tables.push_back(std::move(table));\n }\n return tables;\n}\n\ntemplate\nstd::vector>>\nread_initial_structures(const std::vector& structures)\n{\n std::vector>> tables;\n for(const auto& conf : structures)\n {\n std::map> table;\n for(const auto& kvp : conf)\n {\n std::vector chIDs = split_chain_ids(kvp.first);\n const toml::Table val = toml::get(kvp.second);\n\n std::string filename;\n try\n {\n filename = toml::get(val.at(\"initial\"));\n }\n catch(const std::exception& except)\n {\n \/\/ do nothing. initial configuration is optional.\n }\n try\n {\n filename = toml::get(val.at(\"file\"));\n }\n catch(const std::exception& except)\n {\n throw std::runtime_error(\"jarngreipr::read_initial_structures: \"\n \"neither file nor initial exists for chain \" + kvp.first);\n }\n\n if(filename.substr(filename.size() - 4) == \".pdb\")\n {\n mjolnir::PDBReader pdb_reader(filename);\n if(not pdb_reader.is_good())\n {\n throw std::runtime_error(\n \"jarngreipr::read_reference_structures: \"\n \"file open error: \" + filename);\n }\n while(not pdb_reader.is_eof())\n {\n const auto chain = pdb_reader.read_next_chain();\n const char chain_id = chain.chain_id();\n const auto found = std::find(\n chIDs.begin(), chIDs.end(), chain_id);\n if(found != chIDs.end())\n {\n table[*found] = chain;\n chIDs.erase(found);\n }\n }\n }\n else\n {\n throw std::runtime_error(\"jarngreipr::read_reference_structures: \"\n \"unrecognizable file: \" + filename);\n }\n\n if(not chIDs.empty())\n {\n std::string mes(\"jarngreipr::read_reference_structures: \"\n \"missing chains in : \");\n mes += filename;\n mes += \", ID = \";\n mes += std::string(chIDs.begin(), chIDs.end());\n throw std::runtime_error(mes);\n }\n }\n\n tables.push_back(std::move(table));\n }\n return tables;\n}\n\ninline std::vector>\nread_coarse_grained_models(const std::vector& structures)\n{\n std::vector> tables;\n for(const auto& conf : structures)\n {\n std::map table;\n for(const auto& kvp : conf)\n {\n const std::vector chIDs = split_chain_ids(kvp.first);\n const toml::Table val = toml::get(kvp.second);\n\n std::string model_name;\n try\n {\n model_name = toml::get(val.at(\"model\"));\n }\n catch(const std::exception& except)\n {\n throw std::runtime_error(\"jarngreipr::read_coarse_grained model: \"\n \"model is not specified for chain \" + kvp.first);\n }\n\n for(char id : chIDs)\n {\n table[id] = model_name;\n }\n }\n tables.push_back(std::move(table));\n }\n return tables;\n}\n\ntemplate\nstd::vector>>\napply_coarse_grained_models(\n const std::vector>>& pdbs,\n const std::vector>& models)\n{\n assert(pdbs.size() == models.size());\n std::vector>> cgss;\n for(std::size_t i=0; i> cgs;\n const auto& pdb = pdbs.at(i);\n const auto& model = models.at(i);\n\n for(const auto& kv : pdb)\n {\n const auto chid = kv.first;\n const auto& ch = kv.second;\n cgs[chid] = make_coarse_grained(ch, model.at(chid));\n }\n\n std::size_t index = 0;\n for(auto& id_chain: cgs)\n {\n for(auto& bead : id_chain.second)\n {\n bead->index() = index;\n ++index;\n }\n }\n\n cgss.push_back(std::move(cgs));\n }\n return cgss;\n}\n\n} \/\/ mjolnir\n\nint main(int argc, char **argv)\n{\n typedef mjolnir::Vector coord_type;\n typedef mjolnir::PDBChain pdb_chain_type;\n typedef mjolnir::CGChain cg_chain_type;\n\n if(argc != 2)\n {\n std::cerr << \"Usage: $ jarngreipr [file.toml]\\n\";\n std::cerr << \" see input\/example.toml for the format\" << std::endl;\n return 1;\n }\n\n const auto input_data = toml::parse(std::string(argv[1]));\n\n \/* prepairing parameters *\/\n const auto general = toml::get(input_data.at(\"general\"));\n const auto file_name = toml::get(general.at(\"file_prefix\"));\n std::random_device devrand;\n std::mt19937 mt(devrand());\n\n \/* output general information *\/{\n std::cout << \"[general]\\n\";\n std::cout << \"file_name = \"\n << toml::get(general.at(\"file_prefix\")) << '\\n';\n std::cout << \"output_path = \"\n << toml::get_or(general, \"output_path\", \".\/\"_str) << '\\n';\n std::cout << \"precision = \"\n << toml::get_or(general, \"precision\", \"double\"_str) << '\\n';\n std::cout << \"boundary = \"\n << toml::get_or(general, \"boundary\", \"Unlimited\"_str) << '\\n';\n std::cout << \"thread = \" << std::boolalpha\n << toml::get_or(general, \"thread\", false) << '\\n';\n std::cout << \"GPU = \" << std::boolalpha\n << toml::get_or(general, \"GPU\", false) << '\\n';\n const std::int64_t default_seed = devrand();\n std::cout << \"seed = \"\n << toml::get_or(general, \"seed\", default_seed) << '\\n';\n }\n\n\n const auto parameters =\n toml::parse(toml::get(general.at(\"parameters\")));\n const auto phys_paras = toml::get(parameters.at(\"physical_constants\"));\n const auto vac_permit = toml::get(phys_paras.at(\"ε0\"));\n\n const auto& mass =\n toml::get(parameters.at(\"mass\"));\n const auto& phys =\n toml::get(parameters.at(\"physical_constants\"));\n\n const auto system_config =\n toml::get>(input_data.at(\"systems\"));\n\n \/* generating coarse-grained structures *\/\n const auto structure_config =\n toml::get>(input_data.at(\"structures\"));\n\n \/\/ vector>>\n \/\/ in most cases, the size of vector is one.\n const auto ref_pdbs =\n mjolnir::read_reference_structures(structure_config);\n const auto ini_pdbs =\n mjolnir::read_initial_structures (structure_config);\n const auto models =\n mjolnir::read_coarse_grained_models(structure_config);\n\n \/\/ apply coarse-grained model to input pdbs\n const auto ref_cgss = mjolnir::apply_coarse_grained_models(ref_pdbs, models);\n const auto ini_cgss = mjolnir::apply_coarse_grained_models(ini_pdbs, models);\n\n \/\/ output system setting and cg structure\n assert(system_config.size() == ini_cgss.size());\n for(std::size_t i=0; i(sysconf.at(\"temperature\"));\n std::cout << \"temperature = \" << std::fixed << T << '\\n';\n std::cout << \"ionic_strength = \" << std::fixed\n << toml::get(sysconf.at(\"ionic_strength\")) << '\\n';\n std::cout << \"boundary = {\";\n for(const auto& kv : toml::get(sysconf.at(\"boundary\")))\n {\n if(kv.first == \"type\")\n {\n std::cout << kv.first << \"=\\\"\" << toml::get(kv.second) << '\\\"';\n }\n else\n {\n const auto& crd = toml::get>(kv.second);\n std::cout << kv.first << \"=[\" << crd[0] << ',' << crd[1] << ','\n << crd[2] << ']';\n }\n }\n std::cout << \"}\\n\";\n \/\/ }}}\n\n std::cout << \"particles = [\\n\";\n const auto& chain_table = ini_cgss.at(i);\n for(const auto& id_chain_pair : chain_table)\n {\n std::cerr << \"chain ID = \" << id_chain_pair.first;\n std::cerr << \" has \" << id_chain_pair.second.size() << \" beads.\" << std::endl;\n for(std::size_t j=0; j(phys.at(\"kB\"));\n const auto m = toml::get(mass.at(bead->name()));\n const auto p = bead->position();\n std::normal_distribution mxw_blz(0.0, std::sqrt(kB*T\/m));\n std::cout << \"{mass = \" << m\n << \", position = [\" << p[0] << ',' << p[1] << ',' << p[2]\n << \"], velocity = [\" << mxw_blz(mt) << ','\n << mxw_blz(mt) << ',' << mxw_blz(mt) << \"]},\\n\";\n }\n }\n std::cout << \"]\\n\";\n }\n\n const std::unique_ptr>\n ffgen = mjolnir::make_unique>();\n\n for(const auto& chains : ref_cgss)\n {\n std::cout << \"[[forcefields]]\\n\";\n for(const auto& idch : chains)\n {\n const auto& ch = idch.second;\n const auto connect = ffgen->generate(std::cout, ch);\n }\n }\n\n \/\/ output parameter\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * OptimalSolver.cpp\n *\n * Created on: 2015-05-16\n * Author: legraina\n *\/\n\n#include \"main_test.h\"\n#include \"MyTools.h\"\n\n\/\/ n030w4 1 4 6 2 9 1 n030w4_1_6-2-9-1\n\/\/ Function for solving the optimal solution\nint main(int argc, char** argv)\n{\n\tstd::cout << \"# Launching Optimal Roster...\" << std::endl;\n\n int locINT;\n\n int k = 0;\n\n string inst = argv[++k];\n\n std::istringstream(argv[++k]) >> locINT;\n int historyID = locINT;\n\n std::istringstream(argv[++k]) >> locINT;\n int nbWeeks = locINT;\n if(5+nbWeeks > argc)\n Tools::throwError(\"Bad input format. Should be: instance_name historyID numberWeeks vectorweekIndices outdir prefix numberTest solver_options generation_options evaluations_options. After outdir, the arguments are optional.\");\n\n vector numberWeek;\n for(int i=0; i> locINT;\n numberWeek.push_back(locINT);\n }\n\n string outdir = argv[++k];\n\n int givenSeed;\n if(k+1 < argc){\n\t std::istringstream(argv[++k]) >> locINT;\n\t givenSeed = locINT;\n }\n\n int nbEval;\n if(k+1 < argc){\n\t std::istringstream(argv[++k]) >> locINT;\n\t nbEval = locINT;\n }\n\n string prefix = \"\";\n if(k+1 < argc)\n prefix = argv[++k];\n\n string data = \"datasets\/\";\n string scenarPath = data + inst + \"\/Sc-\" + inst + \".txt\";\n string outpath = \"outfiles\/Competition\/\"+outdir+\"\/\"+prefix;\n string outfile = outpath+\"sol-week\";\n string logfile = outpath+\"Log.txt\";\n string optionspath = data+\"optionFiles\/\";\n\n string stoOptionsFile = optionspath+\"stochastic_solver.txt\";\n string geneOptionsFile = optionspath+\"generation_solver.txt\";\n string evaOptionsFile = optionspath+\"evaluation_solver.txt\";\n\n \/\/ Time the complete execution of the algorithm\n Tools::Timer* timertotal = new Tools::Timer();\n timertotal->init();\n timertotal->start();\n\n\/\/ SolverParam optParam;\n\/\/ optParam.printEverySolution_ = true;\n\/\/ optParam.weekIndices_ = numberWeek;\n\/\/ optParam.outfile_ = outfile;\n\/\/ optParam.logfile_ = logfile;\n\/\/ optParam.solveToOptimality_ = true;\n\/\/ optParam.nbDiveIfMinGap_ = 2;\n\/\/ optParam.nbDiveIfRelGap_ = 8;\n\/\/ testMultipleWeeksDeterministic(data, inst, historyID, numberWeek, GENCOL, \"outfiles\/Competition\/\"+outdir+\"\/\"+prefix, optParam);\n\n\n srand(givenSeed);\n int seed = rand();\n\n pair p;\n\n \/*\n * Block for RK_SCORE\n *\/\n\n\/\/ StochasticSolverOptions stochasticSolverOptionsScore;\n\/\/ setStochasticSolverOptions(stochasticSolverOptionsScore, SUNGRID, inst, outfile, outpath,\n\/\/\t\t stoOptionsFile, geneOptionsFile, evaOptionsFile);\n\/\/\n\/\/ p = testMultipleWeeksStochastic(data, inst, historyID, numberWeek, stochasticSolverOptionsScore, outpath+\"score_\", seed);\n\/\/\n\/\/ char results[250];\n\/\/ sprintf(results, \"Seed %d; Cost %.2f; NbGene %d; NbEval %d; WeightStrat %d; RankStrat %d; nbDaysGeneration %d; nbDaysEvaluation %d;\",\n\/\/\t\t seed, p.first, p.second, stochasticSolverOptionsScore.nEvaluationDemands_,\n\/\/\t\t stochasticSolverOptionsScore.generationParameters_.weightStrategy_, stochasticSolverOptionsScore.rankingStrategy_,\n\/\/\t\t 7+stochasticSolverOptionsScore.nExtraDaysGenerationDemands_, stochasticSolverOptionsScore.nDaysEvaluation_);\n\/\/ string sensibilityOutfile = outpath+\"score_sensibility.txt\";\n\/\/ Tools::LogOutput sensibilityStream(sensibilityOutfile, true);\n\/\/ sensibilityStream << results << std::endl;\n\/\/\n\n \/*\n * Block for RK_MEAN\n *\/\n\n StochasticSolverOptions stochasticSolverOptionsMean;\n setStochasticSolverOptions(stochasticSolverOptionsMean, SUNGRID, inst, outfile, outpath,\n\t\t stoOptionsFile, geneOptionsFile, evaOptionsFile);\n\n stochasticSolverOptionsMean.rankingStrategy_ = RK_MEAN;\n\n p = testMultipleWeeksStochastic(data, inst, historyID, numberWeek, stochasticSolverOptionsMean, outpath+\"mean_\", seed);\n\n char results2[250];\n sprintf(results2, \"Seed %d; Cost %.2f; NbGene %d; NbEval %d; WeightStrat %d; RankStrat %d; nbDaysGeneration %d; nbDaysEvaluation %d;\",\n\t\t seed, p.first, p.second, stochasticSolverOptionsMean.nEvaluationDemands_,\n\t\t stochasticSolverOptionsMean.generationParameters_.weightStrategy_, stochasticSolverOptionsMean.rankingStrategy_,\n\t\t 7+stochasticSolverOptionsMean.nExtraDaysGenerationDemands_, stochasticSolverOptionsMean.nDaysEvaluation_);\n string sensibilityOutfile2 = outpath+\"mean_sensibility.txt\";\n Tools::LogOutput sensibilityStream2(sensibilityOutfile2, true);\n sensibilityStream2 << results2 << std::endl;\n\n \/\/ Display the total time spent in the algorithm\n timertotal->stop();\n std::cout << \"Total time spent in the algorithm : \" << timertotal->dSinceInit() << std::endl;\n\n \/\/ free the allocated pointers\n \/\/\n delete timertotal;\n\n\/\/vector instances =\n\/\/{\n\/\/ \"n030w4_1_6-2-9-1\", \"n030w4_1_6-7-5-3\", \"n030w8_1_2-7-0-9-3-6-0-6\", \"n030w8_1_6-7-5-3-5-6-2-9\",\n\/\/ \"n040w4_0_2-0-6-1\", \"n040w4_2_6-1-0-6\", \"n040w8_0_0-6-8-9-2-6-6-4\", \"n040w8_2_5-0-4-8-7-1-7-2\",\n\/\/ \"n050w4_0_0-4-8-7\", \"n050w4_0_7-2-7-2\", \"n050w8_1_1-7-8-5-7-4-1-8\", \"n050w8_1_9-7-5-3-8-8-3-1\",\n\/\/ \"n060w4_1_6-1-1-5\", \"n060w4_1_9-6-3-8\", \"n060w8_0_6-2-9-9-0-8-1-3\", \"n060w8_2_1-0-3-4-0-3-9-1\",\n\/\/ \"n080w4_2_4-3-3-3\", \"n080w4_2_6-0-4-8\", \"n080w8_1_4-4-9-9-3-6-0-5\", \"n080w8_2_0-4-0-9-1-9-6-2\",\n\/\/ \"n100w4_0_1-1-0-8\", \"n100w4_2_0-6-4-6\", \"n100w8_0_0-1-7-8-9-1-5-4\", \"n100w8_1_2-4-7-9-3-9-2-8\",\n\/\/ \"n120w4_1_4-6-2-6\", \"n120w4_1_5-6-9-8\", \"n120w8_0_0-9-9-4-5-1-0-3\", \"n120w8_1_7-2-6-4-5-2-0-2\"\n\/\/};\n\n}\nAL haaaaaaaaagggghhhhhh\/*\n * OptimalSolver.cpp\n *\n * Created on: 2015-05-16\n * Author: legraina\n *\/\n\n#include \"main_test.h\"\n#include \"MyTools.h\"\n\n\/\/ n030w4 1 4 6 2 9 1 n030w4_1_6-2-9-1\n\/\/ Function for solving the optimal solution\nint main(int argc, char** argv)\n{\n\tstd::cout << \"# Launching Optimal Roster...\" << std::endl;\n\n int locINT;\n\n int k = 0;\n\n string inst = argv[++k];\n\n std::istringstream(argv[++k]) >> locINT;\n int historyID = locINT;\n\n std::istringstream(argv[++k]) >> locINT;\n int nbWeeks = locINT;\n if(5+nbWeeks > argc)\n Tools::throwError(\"Bad input format. Should be: instance_name historyID numberWeeks vectorweekIndices outdir prefix numberTest solver_options generation_options evaluations_options. After outdir, the arguments are optional.\");\n\n vector numberWeek;\n for(int i=0; i> locINT;\n numberWeek.push_back(locINT);\n }\n\n string outdir = argv[++k];\n\n int givenSeed;\n if(k+1 < argc){\n\t std::istringstream(argv[++k]) >> locINT;\n\t givenSeed = locINT;\n }\n\n int nbEval;\n if(k+1 < argc){\n\t std::istringstream(argv[++k]) >> locINT;\n\t nbEval = locINT;\n }\n\n string prefix = \"\";\n if(k+1 < argc)\n prefix = argv[++k];\n\n string data = \"datasets\/\";\n string scenarPath = data + inst + \"\/Sc-\" + inst + \".txt\";\n string outpath = \"outfiles\/Competition\/\"+outdir+\"\/\"+prefix;\n string outfile = outpath+\"sol-week\";\n string logfile = outpath+\"Log.txt\";\n string optionspath = data+\"optionFiles\/\";\n\n string stoOptionsFile = optionspath+\"stochastic_solver.txt\";\n string geneOptionsFile = optionspath+\"generation_solver.txt\";\n string evaOptionsFile = optionspath+\"evaluation_solver.txt\";\n\n \/\/ Time the complete execution of the algorithm\n Tools::Timer* timertotal = new Tools::Timer();\n timertotal->init();\n timertotal->start();\n\n\/\/ SolverParam optParam;\n\/\/ optParam.printEverySolution_ = true;\n\/\/ optParam.weekIndices_ = numberWeek;\n\/\/ optParam.outfile_ = outfile;\n\/\/ optParam.logfile_ = logfile;\n\/\/ optParam.solveToOptimality_ = true;\n\/\/ optParam.nbDiveIfMinGap_ = 2;\n\/\/ optParam.nbDiveIfRelGap_ = 8;\n\/\/ testMultipleWeeksDeterministic(data, inst, historyID, numberWeek, GENCOL, \"outfiles\/Competition\/\"+outdir+\"\/\"+prefix, optParam);\n\n\n srand(givenSeed);\n int seed = rand();\n\n pair p;\n\n \/*\n * Block for RK_SCORE\n *\/\n\n\/\/ StochasticSolverOptions stochasticSolverOptionsScore;\n\/\/ setStochasticSolverOptions(stochasticSolverOptionsScore, SUNGRID, inst, outfile, outpath,\n\/\/\t\t stoOptionsFile, geneOptionsFile, evaOptionsFile);\n\/\/\n\/\/ stochasticSolverOptionsScore.nEvaluationDemands_ = nbEval;\n\/\/ p = testMultipleWeeksStochastic(data, inst, historyID, numberWeek, stochasticSolverOptionsScore, outpath+\"score_\", seed);\n\/\/\n\/\/ char results[250];\n\/\/ sprintf(results, \"Seed %d; Cost %.2f; NbGene %d; NbEval %d; WeightStrat %d; RankStrat %d; nbDaysGeneration %d; nbDaysEvaluation %d;\",\n\/\/\t\t seed, p.first, p.second, stochasticSolverOptionsScore.nEvaluationDemands_,\n\/\/\t\t stochasticSolverOptionsScore.generationParameters_.weightStrategy_, stochasticSolverOptionsScore.rankingStrategy_,\n\/\/\t\t 7+stochasticSolverOptionsScore.nExtraDaysGenerationDemands_, stochasticSolverOptionsScore.nDaysEvaluation_);\n\/\/ string sensibilityOutfile = outpath+\"score_sensibility.txt\";\n\/\/ Tools::LogOutput sensibilityStream(sensibilityOutfile, true);\n\/\/ sensibilityStream << results << std::endl;\n\/\/\n\n \/*\n * Block for RK_MEAN\n *\/\n\n StochasticSolverOptions stochasticSolverOptionsMean;\n setStochasticSolverOptions(stochasticSolverOptionsMean, SUNGRID, inst, outfile, outpath,\n\t\t stoOptionsFile, geneOptionsFile, evaOptionsFile);\n\n stochasticSolverOptionsMean.nEvaluationDemands_ = nbEval;\n stochasticSolverOptionsMean.rankingStrategy_ = RK_MEAN;\n\n p = testMultipleWeeksStochastic(data, inst, historyID, numberWeek, stochasticSolverOptionsMean, outpath+\"mean_\", seed);\n\n char results2[250];\n sprintf(results2, \"Seed %d; Cost %.2f; NbGene %d; NbEval %d; WeightStrat %d; RankStrat %d; nbDaysGeneration %d; nbDaysEvaluation %d;\",\n\t\t seed, p.first, p.second, stochasticSolverOptionsMean.nEvaluationDemands_,\n\t\t stochasticSolverOptionsMean.generationParameters_.weightStrategy_, stochasticSolverOptionsMean.rankingStrategy_,\n\t\t 7+stochasticSolverOptionsMean.nExtraDaysGenerationDemands_, stochasticSolverOptionsMean.nDaysEvaluation_);\n string sensibilityOutfile2 = outpath+\"mean_sensibility.txt\";\n Tools::LogOutput sensibilityStream2(sensibilityOutfile2, true);\n sensibilityStream2 << results2 << std::endl;\n\n \/\/ Display the total time spent in the algorithm\n timertotal->stop();\n std::cout << \"Total time spent in the algorithm : \" << timertotal->dSinceInit() << std::endl;\n\n \/\/ free the allocated pointers\n \/\/\n delete timertotal;\n\n\/\/vector instances =\n\/\/{\n\/\/ \"n030w4_1_6-2-9-1\", \"n030w4_1_6-7-5-3\", \"n030w8_1_2-7-0-9-3-6-0-6\", \"n030w8_1_6-7-5-3-5-6-2-9\",\n\/\/ \"n040w4_0_2-0-6-1\", \"n040w4_2_6-1-0-6\", \"n040w8_0_0-6-8-9-2-6-6-4\", \"n040w8_2_5-0-4-8-7-1-7-2\",\n\/\/ \"n050w4_0_0-4-8-7\", \"n050w4_0_7-2-7-2\", \"n050w8_1_1-7-8-5-7-4-1-8\", \"n050w8_1_9-7-5-3-8-8-3-1\",\n\/\/ \"n060w4_1_6-1-1-5\", \"n060w4_1_9-6-3-8\", \"n060w8_0_6-2-9-9-0-8-1-3\", \"n060w8_2_1-0-3-4-0-3-9-1\",\n\/\/ \"n080w4_2_4-3-3-3\", \"n080w4_2_6-0-4-8\", \"n080w8_1_4-4-9-9-3-6-0-5\", \"n080w8_2_0-4-0-9-1-9-6-2\",\n\/\/ \"n100w4_0_1-1-0-8\", \"n100w4_2_0-6-4-6\", \"n100w8_0_0-1-7-8-9-1-5-4\", \"n100w8_1_2-4-7-9-3-9-2-8\",\n\/\/ \"n120w4_1_4-6-2-6\", \"n120w4_1_5-6-9-8\", \"n120w8_0_0-9-9-4-5-1-0-3\", \"n120w8_1_7-2-6-4-5-2-0-2\"\n\/\/};\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n\nint main(){\n int n, a, b, c, d, r, num, den, num_r, den_r, j;\n char o, i;\n\n scanf(\"%d\", &n);\n while(n--){\n scanf(\"%d %c %d %c %d %c %d\", &a, &i, &b, &o, &c, &i, &d);\n if (o == '+'){\n num = (b * d) * a \/ b + (b * d) * c \/ d;\n den = b * d;\n } else if (o == '-'){\n num = (b * d) * a \/ b - (b * d) * c \/ d;\n den = b * d;\n } else if (o == '*'){\n num = a * c;\n den = b * d;\n } else {\n num = a * d;\n den = b * c;\n }\n\n if (std::abs(num) < std::abs(den))\n r = std::abs(num);\n else\n r = std::abs(den);\n\n num_r = num;\n den_r = den;\n\n j = 2;\n while (j <= r){\n if (num_r % j == 0 && den_r % j == 0){\n num_r = num_r \/ j;\n den_r = den_r \/ j;\n } else {\n j++;\n }\n }\n\n printf(\"%d\/%d = %d\/%d\\n\", num, den, num_r, den_r);\n }\n return 0;\n}\nPequena refatoração no 1022.#include \n#include \n\nint main(){\n int n, a, b, c, d, r, num, den, num_r, den_r, j;\n char o, i;\n\n scanf(\"%d\", &n);\n while(n--){\n scanf(\"%d %c %d %c %d %c %d\", &a, &i, &b, &o, &c, &i, &d);\n if (o == '+'){\n num = (b * d) * a \/ b + (b * d) * c \/ d;\n den = b * d;\n } else if (o == '-'){\n num = (b * d) * a \/ b - (b * d) * c \/ d;\n den = b * d;\n } else if (o == '*'){\n num = a * c;\n den = b * d;\n } else {\n num = a * d;\n den = b * c;\n }\n\n if (std::abs(num) < std::abs(den))\n r = std::abs(num);\n else\n r = std::abs(den);\n\n num_r = num;\n den_r = den;\n\n j = 2;\n while (j <= r \/ 2 + 1){\n if (num_r % j == 0 && den_r % j == 0){\n num_r = num_r \/ j;\n den_r = den_r \/ j;\n } else {\n j++;\n }\n }\n\n printf(\"%d\/%d = %d\/%d\\n\", num, den, num_r, den_r);\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Licensed to the .NET Foundation under one or more agreements.\n\/\/ The .NET Foundation licenses this file to you under the MIT license.\n\/\/ See the LICENSE file in the project root for more information.\n\n\/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\nXX XX\nXX UnwindInfo XX\nXX XX\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n*\/\n\n#include \"jitpch.h\"\n#ifdef _MSC_VER\n#pragma hdrstop\n#endif\n\n#if FEATURE_EH_FUNCLETS\n\n\/\/------------------------------------------------------------------------\n\/\/ Compiler::unwindGetFuncLocations: Get the start\/end emitter locations for this\n\/\/ function or funclet. If 'getHotSectionData' is true, get the start\/end locations\n\/\/ for the hot section. Otherwise, get the data for the cold section.\n\/\/\n\/\/ Note that we grab these locations before the prolog and epilogs are generated, so the\n\/\/ locations must remain correct after the prolog and epilogs are generated.\n\/\/\n\/\/ For the prolog, instructions are put in the special, preallocated, prolog instruction group.\n\/\/ We don't want to expose the emitPrologIG unnecessarily (locations are actually pointers to\n\/\/ emitter instruction groups). Since we know the offset of the start of the function\/funclet,\n\/\/ where the prolog is, will be zero, we use a nullptr start location to indicate that.\n\/\/\n\/\/ There is no instruction group beyond the end of the end of the function, so there is no\n\/\/ location to indicate that. Once again, use nullptr for that.\n\/\/\n\/\/ Intermediate locations point at the first instruction group of a funclet, which is a\n\/\/ placeholder IG. These are converted to real IGs, not deleted and replaced, so the location\n\/\/ remains valid.\n\/\/\n\/\/ Arguments:\n\/\/ func - main function or funclet to get locations for.\n\/\/ getHotSectionData - 'true' to get the hot section data, 'false' to get the cold section data.\n\/\/ ppStartLoc - OUT parameter. Set to the start emitter location.\n\/\/ ppEndLoc - OUT parameter. Set to the end emitter location (the location immediately\n\/\/ the range; the 'end' location is not inclusive).\n\/\/\n\/\/ Notes:\n\/\/ A start location of nullptr means the beginning of the code.\n\/\/ An end location of nullptr means the end of the code.\n\/\/\nvoid Compiler::unwindGetFuncLocations(FuncInfoDsc* func,\n bool getHotSectionData,\n \/* OUT *\/ emitLocation** ppStartLoc,\n \/* OUT *\/ emitLocation** ppEndLoc)\n{\n if (func->funKind == FUNC_ROOT)\n {\n \/\/ Since all funclets are pulled out of line, the main code size is everything\n \/\/ up to the first handler. If the function is hot\/cold split, we need to get the\n \/\/ appropriate sub-range.\n\n if (getHotSectionData)\n {\n *ppStartLoc = nullptr; \/\/ nullptr emit location means the beginning of the code. This is to handle the first\n \/\/ fragment prolog.\n\n if (fgFirstColdBlock != nullptr)\n {\n \/\/ The hot section only goes up to the cold section\n assert(fgFirstFuncletBB == nullptr);\n\n *ppEndLoc = new (this, CMK_UnwindInfo) emitLocation(ehEmitCookie(fgFirstColdBlock));\n }\n else\n {\n if (fgFirstFuncletBB != nullptr)\n {\n *ppEndLoc = new (this, CMK_UnwindInfo) emitLocation(ehEmitCookie(fgFirstFuncletBB));\n }\n else\n {\n *ppEndLoc = nullptr; \/\/ nullptr end location means the end of the code\n }\n }\n }\n else\n {\n assert(fgFirstFuncletBB == nullptr); \/\/ TODO-CQ: support hot\/cold splitting in functions with EH\n assert(fgFirstColdBlock != nullptr); \/\/ There better be a cold section!\n\n *ppStartLoc = new (this, CMK_UnwindInfo) emitLocation(ehEmitCookie(fgFirstColdBlock));\n *ppEndLoc = nullptr; \/\/ nullptr end location means the end of the code\n }\n }\n else\n {\n assert(getHotSectionData); \/\/ TODO-CQ: support funclets in cold section\n\n EHblkDsc* HBtab = ehGetDsc(func->funEHIndex);\n\n if (func->funKind == FUNC_FILTER)\n {\n assert(HBtab->HasFilter());\n *ppStartLoc = new (this, CMK_UnwindInfo) emitLocation(ehEmitCookie(HBtab->ebdFilter));\n *ppEndLoc = new (this, CMK_UnwindInfo) emitLocation(ehEmitCookie(HBtab->ebdHndBeg));\n }\n else\n {\n assert(func->funKind == FUNC_HANDLER);\n *ppStartLoc = new (this, CMK_UnwindInfo) emitLocation(ehEmitCookie(HBtab->ebdHndBeg));\n *ppEndLoc = (HBtab->ebdHndLast->bbNext == nullptr)\n ? nullptr\n : new (this, CMK_UnwindInfo) emitLocation(ehEmitCookie(HBtab->ebdHndLast->bbNext));\n }\n }\n}\n\n#endif \/\/ FEATURE_EH_FUNCLETS\n\n#if defined(_TARGET_UNIX_)\n\nvoid Compiler::createCfiCode(FuncInfoDsc* func, UCHAR codeOffset, UCHAR cfiOpcode, USHORT dwarfReg, INT offset)\n{\n CFI_CODE cfiEntry(codeOffset, cfiOpcode, dwarfReg, offset);\n func->cfiCodes->push_back(cfiEntry);\n}\n\nvoid Compiler::unwindPushCFI(regNumber reg)\n{\n assert(compGeneratingProlog);\n\n FuncInfoDsc* func = funCurrentFunc();\n\n unsigned int cbProlog = unwindGetCurrentOffset(func);\n noway_assert((BYTE)cbProlog == cbProlog);\n\n createCfiCode(func, cbProlog, CFI_ADJUST_CFA_OFFSET, DWARF_REG_ILLEGAL, REGSIZE_BYTES == 8 ? 8 : 4);\n if ((RBM_CALLEE_SAVED & genRegMask(reg))\n#if defined(UNIX_AMD64_ABI)\n#if ETW_EBP_FRAMED\n \/\/ In case of ETW_EBP_FRAMED defined the REG_FPBASE (RBP)\n \/\/ is excluded from the callee-save register list.\n \/\/ Make sure the register gets PUSH unwind info in this case,\n \/\/ since it is pushed as a frame register.\n || (reg == REG_FPBASE)\n#endif \/\/ ETW_EBP_FRAMED\n#endif\n )\n {\n createCfiCode(func, cbProlog, CFI_REL_OFFSET, mapRegNumToDwarfReg(reg));\n }\n}\n\ntemplate \ninline static T* allocate_any(jitstd::allocator& alloc, size_t count = 5)\n{\n return jitstd::allocator(alloc).allocate(count);\n}\n\ntypedef jitstd::vector CFICodeVector;\n\nvoid Compiler::unwindBegPrologCFI()\n{\n assert(compGeneratingProlog);\n\n#if FEATURE_EH_FUNCLETS\n FuncInfoDsc* func = funCurrentFunc();\n\n \/\/ There is only one prolog for a function\/funclet, and it comes first. So now is\n \/\/ a good time to initialize all the unwind data structures.\n\n unwindGetFuncLocations(func, true, &func->startLoc, &func->endLoc);\n\n if (fgFirstColdBlock != nullptr)\n {\n unwindGetFuncLocations(func, false, &func->coldStartLoc, &func->coldEndLoc);\n }\n\n jitstd::allocator allocator(getAllocator());\n\n func->cfiCodes = new (allocate_any(allocator), jitstd::placement_t()) CFICodeVector(allocator);\n#endif \/\/ FEATURE_EH_FUNCLETS\n}\n\nvoid Compiler::unwindPushMaskCFI(regMaskTP regMask, bool isFloat)\n{\n regMaskTP regBit = isFloat ? genRegMask(REG_FP_FIRST) : 1;\n\n for (regNumber regNum = isFloat ? REG_FP_FIRST : REG_FIRST; regNum < REG_COUNT;\n regNum = REG_NEXT(regNum), regBit <<= 1)\n {\n if (regBit > regMask)\n {\n break;\n }\n\n if (regBit & regMask)\n {\n unwindPushCFI(regNum);\n }\n }\n}\n\nvoid Compiler::unwindAllocStackCFI(unsigned size)\n{\n assert(compGeneratingProlog);\n\n FuncInfoDsc* func = funCurrentFunc();\n\n unsigned int cbProlog = unwindGetCurrentOffset(func);\n noway_assert((BYTE)cbProlog == cbProlog);\n createCfiCode(func, cbProlog, CFI_ADJUST_CFA_OFFSET, DWARF_REG_ILLEGAL, size);\n}\n\n\/\/------------------------------------------------------------------------\n\/\/ Compiler::unwindSetFrameRegCFI: Record a cfi info for a frame register set.\n\/\/\n\/\/ Arguments:\n\/\/ reg - The register being set as the frame register.\n\/\/ offset - The offset from the current stack pointer that the frame pointer will point at.\n\/\/\nvoid Compiler::unwindSetFrameRegCFI(regNumber reg, unsigned offset)\n{\n assert(compGeneratingProlog);\n FuncInfoDsc* func = funCurrentFunc();\n\n unsigned int cbProlog = unwindGetCurrentOffset(func);\n noway_assert((BYTE)cbProlog == cbProlog);\n\n createCfiCode(func, cbProlog, CFI_DEF_CFA_REGISTER, mapRegNumToDwarfReg(reg));\n if (offset != 0)\n {\n \/\/ before: cfa = rsp + old_cfa_offset;\n \/\/ rbp = rsp + offset;\n \/\/ after: cfa should be based on rbp, but points to the old address:\n \/\/ rsp + old_cfa_offset == rbp + old_cfa_offset + adjust;\n \/\/ adjust = -offset;\n int adjust = -(int)offset;\n createCfiCode(func, cbProlog, CFI_ADJUST_CFA_OFFSET, DWARF_REG_ILLEGAL, adjust);\n }\n}\n\nvoid Compiler::unwindEmitFuncCFI(FuncInfoDsc* func, void* pHotCode, void* pColdCode)\n{\n UNATIVE_OFFSET startOffset;\n UNATIVE_OFFSET endOffset;\n DWORD unwindCodeBytes = 0;\n BYTE* pUnwindBlock = nullptr;\n\n if (func->startLoc == nullptr)\n {\n startOffset = 0;\n }\n else\n {\n startOffset = func->startLoc->CodeOffset(genEmitter);\n }\n\n if (func->endLoc == nullptr)\n {\n endOffset = info.compNativeCodeSize;\n }\n else\n {\n endOffset = func->endLoc->CodeOffset(genEmitter);\n }\n\n DWORD size = (DWORD)func->cfiCodes->size();\n if (size > 0)\n {\n unwindCodeBytes = size * sizeof(CFI_CODE);\n pUnwindBlock = (BYTE*)&(*func->cfiCodes)[0];\n }\n\n#ifdef DEBUG\n if (opts.dspUnwind)\n {\n DumpCfiInfo(true \/*isHotCode*\/, startOffset, endOffset, unwindCodeBytes, (const CFI_CODE* const)pUnwindBlock);\n }\n#endif \/\/ DEBUG\n\n assert(endOffset <= info.compTotalHotCodeSize);\n\n eeAllocUnwindInfo((BYTE*)pHotCode, nullptr \/* pColdCode *\/, startOffset, endOffset, unwindCodeBytes, pUnwindBlock,\n (CorJitFuncKind)func->funKind);\n\n if (pColdCode != NULL)\n {\n assert(fgFirstColdBlock != nullptr);\n assert(func->funKind == FUNC_ROOT); \/\/ No splitting of funclets.\n\n unwindCodeBytes = 0;\n pUnwindBlock = nullptr;\n\n if (func->coldStartLoc == nullptr)\n {\n startOffset = 0;\n }\n else\n {\n startOffset = func->coldStartLoc->CodeOffset(genEmitter);\n }\n\n if (func->coldEndLoc == nullptr)\n {\n endOffset = info.compNativeCodeSize;\n }\n else\n {\n endOffset = func->coldEndLoc->CodeOffset(genEmitter);\n }\n\n#ifdef DEBUG\n if (opts.dspUnwind)\n {\n DumpCfiInfo(false \/*isHotCode*\/, startOffset, endOffset, unwindCodeBytes,\n (const CFI_CODE* const)pUnwindBlock);\n }\n#endif \/\/ DEBUG\n\n assert(startOffset >= info.compTotalHotCodeSize);\n startOffset -= info.compTotalHotCodeSize;\n endOffset -= info.compTotalHotCodeSize;\n\n eeAllocUnwindInfo((BYTE*)pHotCode, (BYTE*)pColdCode, startOffset, endOffset, unwindCodeBytes, pUnwindBlock,\n (CorJitFuncKind)func->funKind);\n }\n}\n\n#ifdef DEBUG\n\/\/------------------------------------------------------------------------\n\/\/ DumpCfiInfo: Dump the Cfi data.\n\/\/\n\/\/ Arguments:\n\/\/ isHotCode - true if this cfi data is for the hot section, false otherwise.\n\/\/ startOffset - byte offset of the code start that this cfi data represents.\n\/\/ endOffset - byte offset of the code end that this cfi data represents.\n\/\/ pcFiCode - pointer to the cfi data blob.\n\/\/\nvoid Compiler::DumpCfiInfo(bool isHotCode,\n UNATIVE_OFFSET startOffset,\n UNATIVE_OFFSET endOffset,\n DWORD cfiCodeBytes,\n const CFI_CODE* const pCfiCode)\n{\n printf(\"Cfi Info%s:\\n\", isHotCode ? \"\" : \" COLD\");\n printf(\" >> Start offset : 0x%06x \\n\", dspOffset(startOffset));\n printf(\" >> End offset : 0x%06x \\n\", dspOffset(endOffset));\n\n for (int i = 0; i < (int)(cfiCodeBytes \/ sizeof(CFI_CODE)); i++)\n {\n const CFI_CODE* const pCode = &(pCfiCode[i]);\n\n UCHAR codeOffset = pCode->CodeOffset;\n SHORT dwarfReg = pCode->DwarfReg;\n INT offset = pCode->Offset;\n\n switch (pCode->CfiOpCode)\n {\n case CFI_REL_OFFSET:\n printf(\" CodeOffset: 0x%02X Op: RelOffset DwarfReg:0x%x Offset:0x%X\\n\", codeOffset, dwarfReg,\n offset);\n break;\n case CFI_DEF_CFA_REGISTER:\n assert(offset == 0);\n printf(\" CodeOffset: 0x%02X Op: DefCfaRegister DwarfReg:0x%X\\n\", codeOffset, dwarfReg);\n break;\n case CFI_ADJUST_CFA_OFFSET:\n assert(dwarfReg == DWARF_REG_ILLEGAL);\n printf(\" CodeOffset: 0x%02X Op: AdjustCfaOffset Offset:0x%X\\n\", codeOffset, offset);\n break;\n default:\n printf(\" Unrecognized CFI_CODE: 0x%IX\\n\", *(UINT64*)pCode);\n break;\n }\n }\n}\n#endif \/\/ DEBUG\n\n#endif \/\/ _TARGET_UNIX_\n\n\/\/------------------------------------------------------------------------\n\/\/ Compiler::unwindGetCurrentOffset: Calculate the current byte offset of the\n\/\/ prolog being generated.\n\/\/\n\/\/ Arguments:\n\/\/ func - The main function or funclet of interest.\n\/\/\n\/\/ Return Value:\n\/\/ The byte offset of the prolog currently being generated.\n\/\/\nUNATIVE_OFFSET Compiler::unwindGetCurrentOffset(FuncInfoDsc* func)\n{\n assert(compGeneratingProlog);\n UNATIVE_OFFSET offset;\n if (func->funKind == FUNC_ROOT)\n {\n offset = genEmitter->emitGetPrologOffsetEstimate();\n }\n else\n {\n#if defined(_TARGET_AMD64_)\n assert(func->startLoc != nullptr);\n offset = func->startLoc->GetFuncletPrologOffset(genEmitter);\n#else\n offset = 0; \/\/ TODO ???\n#endif\n }\n\n return offset;\n}\n\n#if defined(_TARGET_AMD64_)\n\n\/\/ See unwindAmd64.cpp\n\n#elif defined(_TARGET_ARM64_)\n\n\/\/ See unwindArm64.cpp\n\n#elif defined(_TARGET_ARM_)\n\n\/\/ See unwindArm.cpp\n\n#elif defined(_TARGET_X86_)\n\n\/\/ See unwindX86.cpp\n\n#else \/\/ _TARGET_*\n\n#error Unsupported or unset target architecture\n\n#endif \/\/ _TARGET_*\nFix jit fromatting\/\/ Licensed to the .NET Foundation under one or more agreements.\n\/\/ The .NET Foundation licenses this file to you under the MIT license.\n\/\/ See the LICENSE file in the project root for more information.\n\n\/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\nXX XX\nXX UnwindInfo XX\nXX XX\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n*\/\n\n#include \"jitpch.h\"\n#ifdef _MSC_VER\n#pragma hdrstop\n#endif\n\n#if FEATURE_EH_FUNCLETS\n\n\/\/------------------------------------------------------------------------\n\/\/ Compiler::unwindGetFuncLocations: Get the start\/end emitter locations for this\n\/\/ function or funclet. If 'getHotSectionData' is true, get the start\/end locations\n\/\/ for the hot section. Otherwise, get the data for the cold section.\n\/\/\n\/\/ Note that we grab these locations before the prolog and epilogs are generated, so the\n\/\/ locations must remain correct after the prolog and epilogs are generated.\n\/\/\n\/\/ For the prolog, instructions are put in the special, preallocated, prolog instruction group.\n\/\/ We don't want to expose the emitPrologIG unnecessarily (locations are actually pointers to\n\/\/ emitter instruction groups). Since we know the offset of the start of the function\/funclet,\n\/\/ where the prolog is, will be zero, we use a nullptr start location to indicate that.\n\/\/\n\/\/ There is no instruction group beyond the end of the end of the function, so there is no\n\/\/ location to indicate that. Once again, use nullptr for that.\n\/\/\n\/\/ Intermediate locations point at the first instruction group of a funclet, which is a\n\/\/ placeholder IG. These are converted to real IGs, not deleted and replaced, so the location\n\/\/ remains valid.\n\/\/\n\/\/ Arguments:\n\/\/ func - main function or funclet to get locations for.\n\/\/ getHotSectionData - 'true' to get the hot section data, 'false' to get the cold section data.\n\/\/ ppStartLoc - OUT parameter. Set to the start emitter location.\n\/\/ ppEndLoc - OUT parameter. Set to the end emitter location (the location immediately\n\/\/ the range; the 'end' location is not inclusive).\n\/\/\n\/\/ Notes:\n\/\/ A start location of nullptr means the beginning of the code.\n\/\/ An end location of nullptr means the end of the code.\n\/\/\nvoid Compiler::unwindGetFuncLocations(FuncInfoDsc* func,\n bool getHotSectionData,\n \/* OUT *\/ emitLocation** ppStartLoc,\n \/* OUT *\/ emitLocation** ppEndLoc)\n{\n if (func->funKind == FUNC_ROOT)\n {\n \/\/ Since all funclets are pulled out of line, the main code size is everything\n \/\/ up to the first handler. If the function is hot\/cold split, we need to get the\n \/\/ appropriate sub-range.\n\n if (getHotSectionData)\n {\n *ppStartLoc = nullptr; \/\/ nullptr emit location means the beginning of the code. This is to handle the first\n \/\/ fragment prolog.\n\n if (fgFirstColdBlock != nullptr)\n {\n \/\/ The hot section only goes up to the cold section\n assert(fgFirstFuncletBB == nullptr);\n\n *ppEndLoc = new (this, CMK_UnwindInfo) emitLocation(ehEmitCookie(fgFirstColdBlock));\n }\n else\n {\n if (fgFirstFuncletBB != nullptr)\n {\n *ppEndLoc = new (this, CMK_UnwindInfo) emitLocation(ehEmitCookie(fgFirstFuncletBB));\n }\n else\n {\n *ppEndLoc = nullptr; \/\/ nullptr end location means the end of the code\n }\n }\n }\n else\n {\n assert(fgFirstFuncletBB == nullptr); \/\/ TODO-CQ: support hot\/cold splitting in functions with EH\n assert(fgFirstColdBlock != nullptr); \/\/ There better be a cold section!\n\n *ppStartLoc = new (this, CMK_UnwindInfo) emitLocation(ehEmitCookie(fgFirstColdBlock));\n *ppEndLoc = nullptr; \/\/ nullptr end location means the end of the code\n }\n }\n else\n {\n assert(getHotSectionData); \/\/ TODO-CQ: support funclets in cold section\n\n EHblkDsc* HBtab = ehGetDsc(func->funEHIndex);\n\n if (func->funKind == FUNC_FILTER)\n {\n assert(HBtab->HasFilter());\n *ppStartLoc = new (this, CMK_UnwindInfo) emitLocation(ehEmitCookie(HBtab->ebdFilter));\n *ppEndLoc = new (this, CMK_UnwindInfo) emitLocation(ehEmitCookie(HBtab->ebdHndBeg));\n }\n else\n {\n assert(func->funKind == FUNC_HANDLER);\n *ppStartLoc = new (this, CMK_UnwindInfo) emitLocation(ehEmitCookie(HBtab->ebdHndBeg));\n *ppEndLoc = (HBtab->ebdHndLast->bbNext == nullptr)\n ? nullptr\n : new (this, CMK_UnwindInfo) emitLocation(ehEmitCookie(HBtab->ebdHndLast->bbNext));\n }\n }\n}\n\n#endif \/\/ FEATURE_EH_FUNCLETS\n\n#if defined(_TARGET_UNIX_)\n\nvoid Compiler::createCfiCode(FuncInfoDsc* func, UCHAR codeOffset, UCHAR cfiOpcode, USHORT dwarfReg, INT offset)\n{\n CFI_CODE cfiEntry(codeOffset, cfiOpcode, dwarfReg, offset);\n func->cfiCodes->push_back(cfiEntry);\n}\n\nvoid Compiler::unwindPushCFI(regNumber reg)\n{\n assert(compGeneratingProlog);\n\n FuncInfoDsc* func = funCurrentFunc();\n\n unsigned int cbProlog = unwindGetCurrentOffset(func);\n noway_assert((BYTE)cbProlog == cbProlog);\n\n createCfiCode(func, cbProlog, CFI_ADJUST_CFA_OFFSET, DWARF_REG_ILLEGAL, REGSIZE_BYTES == 8 ? 8 : 4);\n if ((RBM_CALLEE_SAVED & genRegMask(reg))\n#if defined(UNIX_AMD64_ABI)\n#if ETW_EBP_FRAMED\n \/\/ In case of ETW_EBP_FRAMED defined the REG_FPBASE (RBP)\n \/\/ is excluded from the callee-save register list.\n \/\/ Make sure the register gets PUSH unwind info in this case,\n \/\/ since it is pushed as a frame register.\n || (reg == REG_FPBASE)\n#endif \/\/ ETW_EBP_FRAMED\n#endif\n )\n {\n createCfiCode(func, cbProlog, CFI_REL_OFFSET, mapRegNumToDwarfReg(reg));\n }\n}\n\ntemplate \ninline static T* allocate_any(jitstd::allocator& alloc, size_t count = 5)\n{\n return jitstd::allocator(alloc).allocate(count);\n}\n\ntypedef jitstd::vector CFICodeVector;\n\nvoid Compiler::unwindBegPrologCFI()\n{\n assert(compGeneratingProlog);\n\n#if FEATURE_EH_FUNCLETS\n FuncInfoDsc* func = funCurrentFunc();\n\n \/\/ There is only one prolog for a function\/funclet, and it comes first. So now is\n \/\/ a good time to initialize all the unwind data structures.\n\n unwindGetFuncLocations(func, true, &func->startLoc, &func->endLoc);\n\n if (fgFirstColdBlock != nullptr)\n {\n unwindGetFuncLocations(func, false, &func->coldStartLoc, &func->coldEndLoc);\n }\n\n jitstd::allocator allocator(getAllocator());\n\n func->cfiCodes = new (allocate_any(allocator), jitstd::placement_t()) CFICodeVector(allocator);\n#endif \/\/ FEATURE_EH_FUNCLETS\n}\n\nvoid Compiler::unwindPushMaskCFI(regMaskTP regMask, bool isFloat)\n{\n regMaskTP regBit = isFloat ? genRegMask(REG_FP_FIRST) : 1;\n\n for (regNumber regNum = isFloat ? REG_FP_FIRST : REG_FIRST; regNum < REG_COUNT;\n regNum = REG_NEXT(regNum), regBit <<= 1)\n {\n if (regBit > regMask)\n {\n break;\n }\n\n if (regBit & regMask)\n {\n unwindPushCFI(regNum);\n }\n }\n}\n\nvoid Compiler::unwindAllocStackCFI(unsigned size)\n{\n assert(compGeneratingProlog);\n\n FuncInfoDsc* func = funCurrentFunc();\n\n unsigned int cbProlog = unwindGetCurrentOffset(func);\n noway_assert((BYTE)cbProlog == cbProlog);\n createCfiCode(func, cbProlog, CFI_ADJUST_CFA_OFFSET, DWARF_REG_ILLEGAL, size);\n}\n\n\/\/------------------------------------------------------------------------\n\/\/ Compiler::unwindSetFrameRegCFI: Record a cfi info for a frame register set.\n\/\/\n\/\/ Arguments:\n\/\/ reg - The register being set as the frame register.\n\/\/ offset - The offset from the current stack pointer that the frame pointer will point at.\n\/\/\nvoid Compiler::unwindSetFrameRegCFI(regNumber reg, unsigned offset)\n{\n assert(compGeneratingProlog);\n FuncInfoDsc* func = funCurrentFunc();\n\n unsigned int cbProlog = unwindGetCurrentOffset(func);\n noway_assert((BYTE)cbProlog == cbProlog);\n\n createCfiCode(func, cbProlog, CFI_DEF_CFA_REGISTER, mapRegNumToDwarfReg(reg));\n if (offset != 0)\n {\n \/\/ before: cfa = rsp + old_cfa_offset;\n \/\/ rbp = rsp + offset;\n \/\/ after: cfa should be based on rbp, but points to the old address:\n \/\/ rsp + old_cfa_offset == rbp + old_cfa_offset + adjust;\n \/\/ adjust = -offset;\n int adjust = -(int)offset;\n createCfiCode(func, cbProlog, CFI_ADJUST_CFA_OFFSET, DWARF_REG_ILLEGAL, adjust);\n }\n}\n\nvoid Compiler::unwindEmitFuncCFI(FuncInfoDsc* func, void* pHotCode, void* pColdCode)\n{\n UNATIVE_OFFSET startOffset;\n UNATIVE_OFFSET endOffset;\n DWORD unwindCodeBytes = 0;\n BYTE* pUnwindBlock = nullptr;\n\n if (func->startLoc == nullptr)\n {\n startOffset = 0;\n }\n else\n {\n startOffset = func->startLoc->CodeOffset(genEmitter);\n }\n\n if (func->endLoc == nullptr)\n {\n endOffset = info.compNativeCodeSize;\n }\n else\n {\n endOffset = func->endLoc->CodeOffset(genEmitter);\n }\n\n DWORD size = (DWORD)func->cfiCodes->size();\n if (size > 0)\n {\n unwindCodeBytes = size * sizeof(CFI_CODE);\n pUnwindBlock = (BYTE*)&(*func->cfiCodes)[0];\n }\n\n#ifdef DEBUG\n if (opts.dspUnwind)\n {\n DumpCfiInfo(true \/*isHotCode*\/, startOffset, endOffset, unwindCodeBytes, (const CFI_CODE* const)pUnwindBlock);\n }\n#endif \/\/ DEBUG\n\n assert(endOffset <= info.compTotalHotCodeSize);\n\n eeAllocUnwindInfo((BYTE*)pHotCode, nullptr \/* pColdCode *\/, startOffset, endOffset, unwindCodeBytes, pUnwindBlock,\n (CorJitFuncKind)func->funKind);\n\n if (pColdCode != nullptr)\n {\n assert(fgFirstColdBlock != nullptr);\n assert(func->funKind == FUNC_ROOT); \/\/ No splitting of funclets.\n\n unwindCodeBytes = 0;\n pUnwindBlock = nullptr;\n\n if (func->coldStartLoc == nullptr)\n {\n startOffset = 0;\n }\n else\n {\n startOffset = func->coldStartLoc->CodeOffset(genEmitter);\n }\n\n if (func->coldEndLoc == nullptr)\n {\n endOffset = info.compNativeCodeSize;\n }\n else\n {\n endOffset = func->coldEndLoc->CodeOffset(genEmitter);\n }\n\n#ifdef DEBUG\n if (opts.dspUnwind)\n {\n DumpCfiInfo(false \/*isHotCode*\/, startOffset, endOffset, unwindCodeBytes,\n (const CFI_CODE* const)pUnwindBlock);\n }\n#endif \/\/ DEBUG\n\n assert(startOffset >= info.compTotalHotCodeSize);\n startOffset -= info.compTotalHotCodeSize;\n endOffset -= info.compTotalHotCodeSize;\n\n eeAllocUnwindInfo((BYTE*)pHotCode, (BYTE*)pColdCode, startOffset, endOffset, unwindCodeBytes, pUnwindBlock,\n (CorJitFuncKind)func->funKind);\n }\n}\n\n#ifdef DEBUG\n\/\/------------------------------------------------------------------------\n\/\/ DumpCfiInfo: Dump the Cfi data.\n\/\/\n\/\/ Arguments:\n\/\/ isHotCode - true if this cfi data is for the hot section, false otherwise.\n\/\/ startOffset - byte offset of the code start that this cfi data represents.\n\/\/ endOffset - byte offset of the code end that this cfi data represents.\n\/\/ pcFiCode - pointer to the cfi data blob.\n\/\/\nvoid Compiler::DumpCfiInfo(bool isHotCode,\n UNATIVE_OFFSET startOffset,\n UNATIVE_OFFSET endOffset,\n DWORD cfiCodeBytes,\n const CFI_CODE* const pCfiCode)\n{\n printf(\"Cfi Info%s:\\n\", isHotCode ? \"\" : \" COLD\");\n printf(\" >> Start offset : 0x%06x \\n\", dspOffset(startOffset));\n printf(\" >> End offset : 0x%06x \\n\", dspOffset(endOffset));\n\n for (int i = 0; i < (int)(cfiCodeBytes \/ sizeof(CFI_CODE)); i++)\n {\n const CFI_CODE* const pCode = &(pCfiCode[i]);\n\n UCHAR codeOffset = pCode->CodeOffset;\n SHORT dwarfReg = pCode->DwarfReg;\n INT offset = pCode->Offset;\n\n switch (pCode->CfiOpCode)\n {\n case CFI_REL_OFFSET:\n printf(\" CodeOffset: 0x%02X Op: RelOffset DwarfReg:0x%x Offset:0x%X\\n\", codeOffset, dwarfReg,\n offset);\n break;\n case CFI_DEF_CFA_REGISTER:\n assert(offset == 0);\n printf(\" CodeOffset: 0x%02X Op: DefCfaRegister DwarfReg:0x%X\\n\", codeOffset, dwarfReg);\n break;\n case CFI_ADJUST_CFA_OFFSET:\n assert(dwarfReg == DWARF_REG_ILLEGAL);\n printf(\" CodeOffset: 0x%02X Op: AdjustCfaOffset Offset:0x%X\\n\", codeOffset, offset);\n break;\n default:\n printf(\" Unrecognized CFI_CODE: 0x%IX\\n\", *(UINT64*)pCode);\n break;\n }\n }\n}\n#endif \/\/ DEBUG\n\n#endif \/\/ _TARGET_UNIX_\n\n\/\/------------------------------------------------------------------------\n\/\/ Compiler::unwindGetCurrentOffset: Calculate the current byte offset of the\n\/\/ prolog being generated.\n\/\/\n\/\/ Arguments:\n\/\/ func - The main function or funclet of interest.\n\/\/\n\/\/ Return Value:\n\/\/ The byte offset of the prolog currently being generated.\n\/\/\nUNATIVE_OFFSET Compiler::unwindGetCurrentOffset(FuncInfoDsc* func)\n{\n assert(compGeneratingProlog);\n UNATIVE_OFFSET offset;\n if (func->funKind == FUNC_ROOT)\n {\n offset = genEmitter->emitGetPrologOffsetEstimate();\n }\n else\n {\n#if defined(_TARGET_AMD64_)\n assert(func->startLoc != nullptr);\n offset = func->startLoc->GetFuncletPrologOffset(genEmitter);\n#else\n offset = 0; \/\/ TODO ???\n#endif\n }\n\n return offset;\n}\n\n#if defined(_TARGET_AMD64_)\n\n\/\/ See unwindAmd64.cpp\n\n#elif defined(_TARGET_ARM64_)\n\n\/\/ See unwindArm64.cpp\n\n#elif defined(_TARGET_ARM_)\n\n\/\/ See unwindArm.cpp\n\n#elif defined(_TARGET_X86_)\n\n\/\/ See unwindX86.cpp\n\n#else \/\/ _TARGET_*\n\n#error Unsupported or unset target architecture\n\n#endif \/\/ _TARGET_*\n<|endoftext|>"} {"text":"\/*\n Empath - Mailer for KDE\n \n Copyright (C) 1998, 1999 Rik Hemsley rik@kde.org\n \n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#ifdef __GNUG__\n# pragma implementation \"EmpathIndex.h\"\n#endif\n\n\/\/ Qt includes\n#include \n#include \n#include \n#include \n\n\/\/ KDE includes\n#include \n#include \n\n\/\/ Local includes\n#include \"EmpathIndexRecord.h\"\n#include \"EmpathIndex.h\"\n#include \"EmpathFolder.h\"\n#include \"Empath.h\"\n\n\/\/ Implementation note:\n\/\/\n\/\/ The value part is composed of an 8-bit byte, used for marking status,\n\/\/ plus a serialised version of an EmpathIndexRecord. This saves us\n\/\/ [de]serialising records when we only want to access the status.\n\nEmpathIndex::EmpathIndex()\n : blockSize_(1024),\n count_(0),\n unreadCount_(0),\n initialised_(false),\n dbf_(0)\n{\n \/\/ Empty.\n empathDebug(\"\");\n}\n\nEmpathIndex::EmpathIndex(const EmpathURL & folder)\n\t:\tblockSize_(1024),\n folder_(folder),\n count_(0),\n unreadCount_(0),\n initialised_(false),\n dbf_(0)\n{\n empathDebug(folder.asString());\n QString resDir =\n KGlobal::dirs()->saveLocation(\"indices\", folder.mailboxName(), true);\n\n QDir d(resDir);\n \n if (!d.exists()) {\n if (!d.mkdir(resDir)) {\n empathDebug(\"Cannot make index dir \" + resDir);\n return;\n }\n }\n \n QString legalName = folder.folderPath().replace(QRegExp(\"\/\"), \"_\");\n \n filename_ = resDir + \"\/\" + legalName;\n\n QFileInfo fi(filename_);\n\n if (!fi.exists())\n initialised_ = false;\n \n _open();\n}\n\nEmpathIndex::~EmpathIndex()\n{\n _close();\n}\n\n void\nEmpathIndex::setFilename(const QString & filename)\n{\n filename_ = filename;\n _close();\n _open();\n}\n\n void\nEmpathIndex::setFolder(const EmpathURL & folder)\n{\n folder_ = folder;\n}\n\n EmpathIndexRecord *\nEmpathIndex::record(const QCString & key)\n{\n if ((dbf_ == 0) && !_open()) {\n empathDebug(\"Index not open!\");\n return 0;\n }\n \n datum k;\n k.dptr = key.data();\n k.dsize = key.length();\n \n datum out = gdbm_fetch(dbf_, k);\n\n if (!out.dptr) {\n return 0;\n }\n \n QByteArray a;\n a.setRawData(out.dptr + 1, out.dsize - 1);\n \n EmpathIndexRecord * rec = new EmpathIndexRecord;\n\n QDataStream s(a, IO_ReadOnly);\n s >> *rec;\n \n a.resetRawData(out.dptr + 1, out.dsize - 1);\n \n rec->setStatus((RMM::MessageStatus)(out.dptr[0]));\n \n return rec;\n}\n\n Q_UINT32\nEmpathIndex::countUnread()\n{\n return unreadCount_;\n}\n\n Q_UINT32\nEmpathIndex::count()\n{\n return count_;\n}\n \n void\nEmpathIndex::sync()\n{\n if ((dbf_ == 0) && !_open()) {\n empathDebug(\"Index not open!\");\n return;\n }\n\n EmpathFolder * f = empath->folder(folder_);\n \n if (!f) {\n empathDebug(\"Can't access my folder :(\");\n return;\n }\n \n f->update();\n}\n\n void\nEmpathIndex::_close()\n{\n if (dbf_ == 0) {\n empathDebug(\"dbf is not open\");\n return;\n }\n \n gdbm_close(dbf_);\n \n count_ = unreadCount_ = 0;\n}\n\n bool\nEmpathIndex::_open()\n{\n if (dbf_ != 0) {\n empathDebug(\"Already open\");\n return true;\n }\n\n dbf_ = gdbm_open(\n filename_.local8Bit().data(), blockSize_, GDBM_WRCREAT, 0600, NULL);\n \n if (dbf_ == 0) {\n empathDebug(gdbm_strerror(gdbm_errno));\n return false;\n }\n\n count_ = unreadCount_ = 0;\n\n return true;\n}\n\n QStrList\nEmpathIndex::allKeys()\n{\n QStrList l; \n\n if ((dbf_ == 0) && !_open()) {\n empathDebug(\"Index not open!\");\n return l;\n }\n \n datum key = gdbm_firstkey(dbf_);\n\n while (key.dptr) {\n \n QCString s(key.dptr, key.dsize + 1);\n \n l.append(s);\n \n key = gdbm_nextkey(dbf_, key);\n }\n \n return l;\n}\n\n bool\nEmpathIndex::insert(const QCString & key, EmpathIndexRecord & rec)\n{\n if ((dbf_ == 0) && !_open()) {\n empathDebug(\"Index not open!\");\n return false;\n }\n\n datum k;\n k.dptr = key.data();\n k.dsize = key.length();\n \n QByteArray a;\n QDataStream s(a, IO_WriteOnly);\n s << rec;\n \n unsigned int dataSize = 1 + a.size();\n char * data = new char[dataSize];\n memcpy(data + 1, a.data(), a.size());\n data[0] = (unsigned char)(rec.status());\n \n datum d;\n d.dptr = data;\n d.dsize = dataSize;\n \n int retval = gdbm_store(dbf_, k, d, GDBM_REPLACE);\n \n if (retval == -1) {\n empathDebug(\"Could not insert record !\");\n return false;\n }\n\n ++count_;\n \n if (!(rec.status() & RMM::Read))\n ++unreadCount_;\n \n return true;\n}\n\n bool\nEmpathIndex::remove(const QCString & key)\n{ \n if ((dbf_ == 0) && !_open()) {\n empathDebug(\"Index not open!\");\n return false;\n }\n\n datum k;\n \n k.dptr = const_cast(key.data());\n k.dsize = key.length();\n \n datum die = gdbm_fetch(dbf_, k);\n\n if (!die.dptr) {\n empathDebug(\"Record does not exist\");\n return false;\n }\n \n RMM::MessageStatus status = (RMM::MessageStatus)(die.dptr[0]);\n\n bool ok = (gdbm_delete(dbf_, k) == 0);\n \n if (ok) {\n --count_;\n if (!(status & RMM::Read))\n --unreadCount_;\n \n } else {\n empathDebug(\"Could not delete record\");\n }\n \n return ok;\n}\n\n void\nEmpathIndex::clear()\n{\n if ((dbf_ == 0) && !_open()) {\n empathDebug(\"Index not open!\");\n return;\n }\n \n datum key = gdbm_firstkey(dbf_);\n\n while (key.dptr) {\n \n gdbm_delete(dbf_, key);\n key = gdbm_nextkey(dbf_, key);\n }\n\n count_ = unreadCount_ = 0;\n}\n\n void\nEmpathIndex::setStatus(const QString & id, RMM::MessageStatus status)\n{\n if ((dbf_ == 0) && !_open()) {\n empathDebug(\"Index not open!\");\n return;\n }\n \n datum k;\n k.dptr = const_cast(id.data());\n k.dsize = id.length();\n \n datum changer = gdbm_fetch(dbf_, k);\n\n if (!changer.dptr) {\n empathDebug(\"does not exist\");\n return;\n }\n \n bool wasRead = ((RMM::MessageStatus)(changer.dptr[0])) & RMM::Read;\n bool isRead = status & RMM::Read;\n \n changer.dptr[0] = (unsigned char)(status);\n\n int retval = gdbm_store(dbf_, k, changer, GDBM_REPLACE);\n\n if (retval == -1) {\n empathDebug(\"Couldn't replace record\");\n return;\n }\n \n if (wasRead && !isRead)\n unreadCount_++;\n \n if (!wasRead && isRead)\n unreadCount_--;\n}\n \n QDateTime\nEmpathIndex::lastModified() const\n{\n QFileInfo fi(filename_);\n return fi.lastModified();\n}\t \n\t\n\n\/\/ vim:ts=4:sw=4:tw=78\ngcc gave a warning about the initialization order. This helps.\/*\n Empath - Mailer for KDE\n \n Copyright (C) 1998, 1999 Rik Hemsley rik@kde.org\n \n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#ifdef __GNUG__\n# pragma implementation \"EmpathIndex.h\"\n#endif\n\n\/\/ Qt includes\n#include \n#include \n#include \n#include \n\n\/\/ KDE includes\n#include \n#include \n\n\/\/ Local includes\n#include \"EmpathIndexRecord.h\"\n#include \"EmpathIndex.h\"\n#include \"EmpathFolder.h\"\n#include \"Empath.h\"\n\n\/\/ Implementation note:\n\/\/\n\/\/ The value part is composed of an 8-bit byte, used for marking status,\n\/\/ plus a serialised version of an EmpathIndexRecord. This saves us\n\/\/ [de]serialising records when we only want to access the status.\n\nEmpathIndex::EmpathIndex()\n : blockSize_(1024),\n dbf_(0),\n count_(0),\n unreadCount_(0),\n initialised_(false)\n{\n \/\/ Empty.\n empathDebug(\"\");\n}\n\nEmpathIndex::EmpathIndex(const EmpathURL & folder)\n\t:\tblockSize_(1024),\n folder_(folder),\n dbf_(0),\n count_(0),\n unreadCount_(0),\n initialised_(false)\n{\n empathDebug(folder.asString());\n QString resDir =\n KGlobal::dirs()->saveLocation(\"indices\", folder.mailboxName(), true);\n\n QDir d(resDir);\n \n if (!d.exists()) {\n if (!d.mkdir(resDir)) {\n empathDebug(\"Cannot make index dir \" + resDir);\n return;\n }\n }\n \n QString legalName = folder.folderPath().replace(QRegExp(\"\/\"), \"_\");\n \n \/\/ filename_ = resDir + \"\/\" + legalName;\n filename_ = \"\/tmp\/\" + legalName;\n\n QFileInfo fi(filename_);\n\n if (!fi.exists())\n initialised_ = false;\n \n _open();\n}\n\nEmpathIndex::~EmpathIndex()\n{\n _close();\n}\n\n void\nEmpathIndex::setFilename(const QString & filename)\n{\n filename_ = filename;\n _close();\n _open();\n}\n\n void\nEmpathIndex::setFolder(const EmpathURL & folder)\n{\n folder_ = folder;\n}\n\n EmpathIndexRecord *\nEmpathIndex::record(const QCString & key)\n{\n if ((dbf_ == 0) && !_open()) {\n empathDebug(\"Index not open!\");\n return 0;\n }\n \n datum k;\n k.dptr = key.data();\n k.dsize = key.length();\n \n datum out = gdbm_fetch(dbf_, k);\n\n if (!out.dptr) {\n return 0;\n }\n \n QByteArray a;\n a.setRawData(out.dptr + 1, out.dsize - 1);\n \n EmpathIndexRecord * rec = new EmpathIndexRecord;\n\n QDataStream s(a, IO_ReadOnly);\n s >> *rec;\n \n a.resetRawData(out.dptr + 1, out.dsize - 1);\n \n rec->setStatus((RMM::MessageStatus)(out.dptr[0]));\n \n return rec;\n}\n\n Q_UINT32\nEmpathIndex::countUnread()\n{\n return unreadCount_;\n}\n\n Q_UINT32\nEmpathIndex::count()\n{\n return count_;\n}\n \n void\nEmpathIndex::sync()\n{\n if ((dbf_ == 0) && !_open()) {\n empathDebug(\"Index not open!\");\n return;\n }\n\n EmpathFolder * f = empath->folder(folder_);\n \n if (!f) {\n empathDebug(\"Can't access my folder :(\");\n return;\n }\n \n f->update();\n}\n\n void\nEmpathIndex::_close()\n{\n if (dbf_ == 0) {\n empathDebug(\"dbf is not open\");\n return;\n }\n \n gdbm_close(dbf_);\n \n count_ = unreadCount_ = 0;\n}\n\n bool\nEmpathIndex::_open()\n{\n if (dbf_ != 0) {\n empathDebug(\"Already open\");\n return true;\n }\n\n dbf_ = gdbm_open(\n filename_.local8Bit().data(), blockSize_, GDBM_WRCREAT, 0600, NULL);\n \n if (dbf_ == 0) {\n empathDebug(gdbm_strerror(gdbm_errno));\n return false;\n }\n\n count_ = unreadCount_ = 0;\n\n return true;\n}\n\n QStrList\nEmpathIndex::allKeys()\n{\n QStrList l; \n\n if ((dbf_ == 0) && !_open()) {\n empathDebug(\"Index not open!\");\n return l;\n }\n \n datum key = gdbm_firstkey(dbf_);\n\n while (key.dptr) {\n \n QCString s(key.dptr, key.dsize + 1);\n \n l.append(s);\n \n key = gdbm_nextkey(dbf_, key);\n }\n \n return l;\n}\n\n bool\nEmpathIndex::insert(const QCString & key, EmpathIndexRecord & rec)\n{\n if ((dbf_ == 0) && !_open()) {\n empathDebug(\"Index not open!\");\n return false;\n }\n\n datum k;\n k.dptr = key.data();\n k.dsize = key.length();\n \n QByteArray a;\n QDataStream s(a, IO_WriteOnly);\n s << rec;\n \n unsigned int dataSize = 1 + a.size();\n char * data = new char[dataSize];\n memcpy(data + 1, a.data(), a.size());\n data[0] = (unsigned char)(rec.status());\n \n datum d;\n d.dptr = data;\n d.dsize = dataSize;\n \n int retval = gdbm_store(dbf_, k, d, GDBM_REPLACE);\n \n if (retval == -1) {\n empathDebug(\"Could not insert record !\");\n return false;\n }\n\n ++count_;\n \n if (!(rec.status() & RMM::Read))\n ++unreadCount_;\n \n return true;\n}\n\n bool\nEmpathIndex::remove(const QCString & key)\n{ \n if ((dbf_ == 0) && !_open()) {\n empathDebug(\"Index not open!\");\n return false;\n }\n\n datum k;\n \n k.dptr = const_cast(key.data());\n k.dsize = key.length();\n \n datum die = gdbm_fetch(dbf_, k);\n\n if (!die.dptr) {\n empathDebug(\"Record does not exist\");\n return false;\n }\n \n RMM::MessageStatus status = (RMM::MessageStatus)(die.dptr[0]);\n\n bool ok = (gdbm_delete(dbf_, k) == 0);\n \n if (ok) {\n --count_;\n if (!(status & RMM::Read))\n --unreadCount_;\n \n } else {\n empathDebug(\"Could not delete record\");\n }\n \n return ok;\n}\n\n void\nEmpathIndex::clear()\n{\n if ((dbf_ == 0) && !_open()) {\n empathDebug(\"Index not open!\");\n return;\n }\n \n datum key = gdbm_firstkey(dbf_);\n\n while (key.dptr) {\n \n gdbm_delete(dbf_, key);\n key = gdbm_nextkey(dbf_, key);\n }\n\n count_ = unreadCount_ = 0;\n}\n\n void\nEmpathIndex::setStatus(const QString & id, RMM::MessageStatus status)\n{\n if ((dbf_ == 0) && !_open()) {\n empathDebug(\"Index not open!\");\n return;\n }\n \n datum k;\n k.dptr = const_cast(id.data());\n k.dsize = id.length();\n \n datum changer = gdbm_fetch(dbf_, k);\n\n if (!changer.dptr) {\n empathDebug(\"does not exist\");\n return;\n }\n \n bool wasRead = ((RMM::MessageStatus)(changer.dptr[0])) & RMM::Read;\n bool isRead = status & RMM::Read;\n \n changer.dptr[0] = (unsigned char)(status);\n\n int retval = gdbm_store(dbf_, k, changer, GDBM_REPLACE);\n\n if (retval == -1) {\n empathDebug(\"Couldn't replace record\");\n return;\n }\n \n if (wasRead && !isRead)\n unreadCount_++;\n \n if (!wasRead && isRead)\n unreadCount_--;\n}\n \n QDateTime\nEmpathIndex::lastModified() const\n{\n QFileInfo fi(filename_);\n return fi.lastModified();\n}\t \n\t\n\n\/\/ vim:ts=4:sw=4:tw=78\n<|endoftext|>"} {"text":"\/*\n This file is part of KOrganizer.\n\n Copyright (c) 2001, 2002, 2003 Cornelius Schumacher \n Copyright (C) 2003-2004 Reinhold Kainhofer \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"koeventeditor.h\"\n#include \"koprefs.h\"\n#include \"koeditorgeneralevent.h\"\n#include \"koeditoralarms.h\"\n#include \"koeditorrecurrence.h\"\n#include \"koeditordetails.h\"\n#include \"koeditorfreebusy.h\"\n#include \"kogroupware.h\"\n#include \"kohelper.h\"\n#include \"kodialogmanager.h\"\n#include \"incidencechanger.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nKOEventEditor::KOEventEditor( Calendar *calendar, QWidget *parent )\n : KOIncidenceEditor( QString(), calendar, parent ),\n mEvent( 0 ), mCalendar( 0 ), mGeneral( 0 ), mRecurrence( 0 ), mFreeBusy( 0 )\n{\n}\n\nKOEventEditor::~KOEventEditor()\n{\n if ( !mIsCounter ) {\n emit dialogClose( mEvent );\n }\n}\n\nbool KOEventEditor::incidenceModified() {\n Event *newEvent = 0;\n\n if ( mEvent ) {\n newEvent = mEvent->clone();\n fillEvent( newEvent );\n }\n return mEvent && !( *newEvent == *mEvent );\n}\n\nvoid KOEventEditor::init()\n{\n setupGeneral();\n setupRecurrence();\n setupFreeBusy();\n setupDesignerTabs( \"event\" );\n\n \/\/ Propagate date time settings to recurrence tab\n connect( mGeneral, SIGNAL(dateTimesChanged(const QDateTime&,const QDateTime& )),\n mRecurrence, SLOT(setDateTimes(const QDateTime&,const QDateTime&)) );\n connect( mGeneral, SIGNAL(dateTimeStrChanged(const QString&)),\n mRecurrence, SLOT(setDateTimeStr(const QString&)) );\n connect( mFreeBusy, SIGNAL(dateTimesChanged(const QDateTime&,const QDateTime&)),\n mRecurrence, SLOT(setDateTimes(const QDateTime&,const QDateTime&)) );\n\n \/\/ Propagate date time settings to gantt tab and back\n connect( mGeneral, SIGNAL(dateTimesChanged(const QDateTime&,const QDateTime&)),\n mFreeBusy, SLOT(slotUpdateGanttView(const QDateTime&,const QDateTime&)) );\n connect( mFreeBusy, SIGNAL(dateTimesChanged(const QDateTime&,const QDateTime&)),\n mGeneral, SLOT(setDateTimes(const QDateTime&,const QDateTime&)) );\n\n connect( mGeneral, SIGNAL(focusReceivedSignal()),\n SIGNAL(focusReceivedSignal()) );\n\n connect( mGeneral, SIGNAL(openCategoryDialog()),\n SIGNAL(editCategories()) );\n connect( this, SIGNAL(updateCategoryConfig()),\n mGeneral, SIGNAL(updateCategoryConfig()) );\n\n connect( mFreeBusy, SIGNAL(updateAttendeeSummary(int)),\n mGeneral, SLOT(updateAttendeeSummary(int)) );\n\n connect( mGeneral, SIGNAL(editRecurrence()),\n mRecurrenceDialog, SLOT(show()) );\n connect( mRecurrenceDialog, SIGNAL(okClicked()),\n SLOT(updateRecurrenceSummary()) );\n\n connect( mGeneral, SIGNAL(acceptInvitation()),\n mFreeBusy, SLOT(acceptForMe()) );\n connect( mGeneral, SIGNAL(declineInvitation()),\n mFreeBusy, SLOT(declineForMe()) );\n\n updateRecurrenceSummary();\n}\n\nvoid KOEventEditor::reload()\n{\n if ( mEvent ) {\n readEvent( mEvent, true );\n }\n}\n\nvoid KOEventEditor::setupGeneral()\n{\n mGeneral = new KOEditorGeneralEvent( mCalendar, this );\n\n if( KOPrefs::instance()->mCompactDialogs ) {\n QFrame *topFrame = new QFrame();\n addPage( topFrame, i18nc( \"@title:tab general event settings\", \"General\" ) );\n topFrame->setWhatsThis( i18nc( \"@info:whatsthis\",\n \"The General tab allows you to set the most \"\n \"common options for the event.\" ) );\n\n QBoxLayout *topLayout = new QVBoxLayout( topFrame );\n topLayout->setSpacing( spacingHint() );\n\n mGeneral->initHeader( topFrame, topLayout );\n mGeneral->initTime( topFrame, topLayout );\n mGeneral->initAlarm( topFrame, topLayout );\n mGeneral->enableAlarm( false );\n\n topLayout->addStretch( 1 );\n\n QFrame *topFrame2 = new QFrame();\n addPage( topFrame2, i18nc( \"@title:tab\", \"Details\" ) );\n\n QBoxLayout *topLayout2 = new QVBoxLayout( topFrame2 );\n topLayout2->setSpacing( spacingHint() );\n\n mGeneral->initClass( topFrame2, topLayout2 );\n mGeneral->initSecrecy( topFrame2, topLayout2 );\n mGeneral->initDescription( topFrame2, topLayout2 );\n } else {\n QFrame *topFrame = new QFrame();\n addPage( topFrame, i18nc( \"@title:tab general event settings\", \"&General\" ) );\n topFrame->setWhatsThis( i18nc( \"@info:whatsthis\",\n \"The General tab allows you to set the most \"\n \"common options for the event.\" ) );\n\n QBoxLayout *topLayout = new QVBoxLayout( topFrame );\n topLayout->setSpacing( spacingHint() );\n\n mGeneral->initInvitationBar( topFrame, topLayout );\n mGeneral->initHeader( topFrame, topLayout );\n mGeneral->initTime( topFrame, topLayout );\n mGeneral->initDescription( topFrame, topLayout );\n mGeneral->initAttachments( topFrame, topLayout );\n connect( mGeneral, SIGNAL(openURL(const KUrl&)),\n this, SLOT(openURL(const KUrl&)) );\n connect( this, SIGNAL(signalAddAttachments(const QStringList&,const QStringList&,bool)),\n mGeneral, SLOT(addAttachments(const QStringList&,const QStringList&,bool)) );\n }\n\n mGeneral->finishSetup();\n}\n\nvoid KOEventEditor::modified( int modification )\n{\n Q_UNUSED( modification );\n\n \/\/ Play dumb, just reload the event. This dialog has become so complicated\n \/\/ that there is no point in trying to be smart here...\n reload();\n}\n\nvoid KOEventEditor::setupRecurrence()\n{\n#if 0\n QFrame *topFrame = new QFrame();\n addPage( topFrame, i18nc( \"@title:tab\", \"Rec&urrence\" ) );\n\n topFrame->setWhatsThis( i18nc( \"@info:whatsthis\",\n \"The Recurrence tab allows you to set options \"\n \"on how often this event recurs.\" ) );\n\n QBoxLayout *topLayout = new QVBoxLayout( topFrame );\n\n mRecurrence = new KOEditorRecurrence( topFrame );\n topLayout->addWidget( mRecurrence );\n#endif\n mRecurrenceDialog = new KOEditorRecurrenceDialog( this );\n mRecurrenceDialog->hide();\n mRecurrence = mRecurrenceDialog->editor();\n}\n\nvoid KOEventEditor::setupFreeBusy()\n{\n QFrame *freeBusyPage = new QFrame();\n addPage( freeBusyPage, i18nc( \"@title:tab\", \"&Attendees\" ) );\n freeBusyPage->setWhatsThis( i18nc( \"@info:whatsthis\",\n \"The Free\/Busy tab allows you to see \"\n \"whether other attendees are free or busy \"\n \"during your event.\" ) );\n\n QBoxLayout *topLayout = new QVBoxLayout( freeBusyPage );\n\n mAttendeeEditor = mFreeBusy = new KOEditorFreeBusy( spacingHint(), freeBusyPage );\n topLayout->addWidget( mFreeBusy );\n}\n\nvoid KOEventEditor::editIncidence( Incidence *incidence, Calendar *calendar )\n{\n Event*event = dynamic_cast( incidence );\n if ( event ) {\n init();\n\n mEvent = event;\n mCalendar = calendar;\n readEvent( mEvent, false );\n }\n\n setCaption( i18nc( \"@title:window\",\n \"Edit Event : %1\", KOHelper::resourceLabel( calendar, incidence ) ) );\n}\n\nvoid KOEventEditor::newEvent()\n{\n init();\n mEvent = 0;\n loadDefaults();\n setCaption( i18nc( \"@title:window\", \"New Event\" ) );\n}\n\nvoid KOEventEditor::setDates( const QDateTime &from, const QDateTime &to, bool allDay )\n{\n mGeneral->setDefaults( from, to, allDay );\n mRecurrence->setDefaults( from, to, allDay );\n if ( mFreeBusy ) {\n if ( allDay ) {\n mFreeBusy->setDateTimes( from, to.addDays( 1 ) );\n } else {\n mFreeBusy->setDateTimes( from, to );\n }\n }\n}\n\nvoid KOEventEditor::setTexts( const QString &summary, const QString &description,\n bool richDescription )\n{\n if ( description.isEmpty() && summary.contains( \"\\n\" ) ) {\n mGeneral->setDescription( summary, richDescription );\n int pos = summary.indexOf( \"\\n\" );\n mGeneral->setSummary( summary.left( pos ) );\n } else {\n mGeneral->setSummary( summary );\n mGeneral->setDescription( description, richDescription );\n }\n}\n\nvoid KOEventEditor::loadDefaults()\n{\n QDateTime from( QDate::currentDate(), KOPrefs::instance()->mStartTime.time() );\n int addSecs = ( KOPrefs::instance()->mDefaultDuration.time().hour() * 3600 ) +\n ( KOPrefs::instance()->mDefaultDuration.time().minute() * 60 );\n QDateTime to( from.addSecs( addSecs ) );\n\n setDates( from, to, false );\n}\n\nbool KOEventEditor::processInput()\n{\n if ( !validateInput() || !mChanger ) {\n return false;\n }\n\n QPointer freeBusy( mFreeBusy );\n\n if ( mEvent ) {\n bool rc = true;\n Event *oldEvent = mEvent->clone();\n Event *event = mEvent->clone();\n\n fillEvent( event );\n\n if ( *event == *mEvent ) {\n \/\/ Don't do anything\n if ( mIsCounter ) {\n KMessageBox::information(\n this,\n i18n( \"You didn't change the event, \"\n \"thus no counter proposal has been sent to the organizer.\" ),\n i18n( \"No changes\" ) );\n }\n } else {\n \/\/IncidenceChanger::assignIncidence( mEvent, event );\n fillEvent( mEvent );\n if ( mIsCounter ) {\n KOGroupware::instance()->sendCounterProposal( mCalendar, oldEvent, mEvent );\n \/\/ add dummy event at the position of the counter proposal\n Event *event = mEvent->clone();\n event->clearAttendees();\n event->setSummary( i18n( \"My counter proposal for: %1\", mEvent->summary() ) );\n mChanger->addIncidence( event );\n } else {\n mChanger->changeIncidence( oldEvent, mEvent );\n }\n }\n delete event;\n delete oldEvent;\n return rc;\n } else {\n mEvent = new Event;\n mEvent->setOrganizer( Person( KOPrefs::instance()->fullName(),\n KOPrefs::instance()->email() ) );\n fillEvent( mEvent );\n if ( !mChanger->addIncidence( mEvent, this ) ) {\n delete mEvent;\n mEvent = 0;\n return false;\n }\n }\n \/\/ if \"this\" was deleted, freeBusy is 0 (being a guardedptr)\n if ( freeBusy ) {\n freeBusy->cancelReload();\n }\n\n return true;\n}\n\nvoid KOEventEditor::processCancel()\n{\n if ( mFreeBusy ) {\n mFreeBusy->cancelReload();\n }\n}\n\nvoid KOEventEditor::deleteEvent()\n{\n if ( mEvent ) {\n emit deleteIncidenceSignal( mEvent );\n }\n\n emit dialogClose( mEvent );\n reject();\n}\n\nvoid KOEventEditor::readEvent( Event *event, bool tmpl )\n{\n if ( !event ) {\n return;\n }\n\n mGeneral->readEvent( event, tmpl );\n mRecurrence->readIncidence( event );\n if ( mFreeBusy ) {\n mFreeBusy->readIncidence( event );\n mFreeBusy->triggerReload();\n }\n\n createEmbeddedURLPages( event );\n readDesignerFields( event );\n\n if ( mIsCounter ) {\n mGeneral->invitationBar()->hide();\n }\n}\n\nvoid KOEventEditor::fillEvent( Event *event )\n{\n mGeneral->fillEvent( event );\n if ( mFreeBusy ) {\n mFreeBusy->fillIncidence( event );\n }\n\n cancelRemovedAttendees( event );\n\n mRecurrence->fillIncidence( event );\n\n writeDesignerFields( event );\n}\n\nbool KOEventEditor::validateInput()\n{\n if ( !mGeneral->validateInput() ) {\n return false;\n }\n if ( !mDetails->validateInput() ) {\n return false;\n }\n if ( !mRecurrence->validateInput() ) {\n return false;\n }\n\n return true;\n}\n\nint KOEventEditor::msgItemDelete()\n{\n return KMessageBox::warningContinueCancel(\n this,\n i18nc( \"@info\", \"This item will be permanently deleted.\" ),\n i18nc( \"@title:window\", \"KOrganizer Confirmation\" ),\n KGuiItem( i18nc( \"@action:button\", \"Delete\" ), \"edit-delete\" ) );\n}\n\nvoid KOEventEditor::loadTemplate( CalendarLocal &cal )\n{\n Event::List events = cal.events();\n if ( events.count() == 0 ) {\n KMessageBox::error( this, i18nc( \"@info\", \"Template does not contain a valid event.\" ) );\n } else {\n readEvent( events.first(), true );\n }\n}\n\nQStringList &KOEventEditor::templates() const\n{\n return KOPrefs::instance()->mEventTemplates;\n}\n\nvoid KOEventEditor::slotSaveTemplate( const QString &templateName )\n{\n Event *event = new Event;\n fillEvent( event );\n saveAsTemplate( event, templateName );\n}\n\nQObject *KOEventEditor::typeAheadReceiver() const\n{\n return mGeneral->typeAheadReceiver();\n}\n\nvoid KOEventEditor::updateRecurrenceSummary()\n{\n Event *ev = new Event();\n fillEvent( ev );\n mGeneral->updateRecurrenceSummary( IncidenceFormatter::recurrenceString( ev ) );\n delete ev;\n}\n\nvoid KOEventEditor::selectInvitationCounterProposal( bool enable )\n{\n KOIncidenceEditor::selectInvitationCounterProposal( enable );\n if ( enable ) {\n mGeneral->invitationBar()->hide();\n }\n}\n\n#include \"koeventeditor.moc\"\n\"Do you really want to cancel\" was only working when editing events, not when creating a new one then canceling.\/*\n This file is part of KOrganizer.\n\n Copyright (c) 2001, 2002, 2003 Cornelius Schumacher \n Copyright (C) 2003-2004 Reinhold Kainhofer \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"koeventeditor.h\"\n#include \"koprefs.h\"\n#include \"koeditorgeneralevent.h\"\n#include \"koeditoralarms.h\"\n#include \"koeditorrecurrence.h\"\n#include \"koeditordetails.h\"\n#include \"koeditorfreebusy.h\"\n#include \"kogroupware.h\"\n#include \"kohelper.h\"\n#include \"kodialogmanager.h\"\n#include \"incidencechanger.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nKOEventEditor::KOEventEditor( Calendar *calendar, QWidget *parent )\n : KOIncidenceEditor( QString(), calendar, parent ),\n mEvent( 0 ), mCalendar( 0 ), mGeneral( 0 ), mRecurrence( 0 ), mFreeBusy( 0 )\n{\n}\n\nKOEventEditor::~KOEventEditor()\n{\n if ( !mIsCounter ) {\n emit dialogClose( mEvent );\n }\n}\n\nbool KOEventEditor::incidenceModified() {\n Event *newEvent = 0;\n\n if ( mEvent ) {\n newEvent = mEvent->clone();\n fillEvent( newEvent );\n }\n\n \/\/ If mEvent is 0 then it's a newly created event, lets count that as a modification\n \/\/ else, compare it with what the user entered in the editor\n\n return !mEvent || !( *newEvent == *mEvent );\n}\n\nvoid KOEventEditor::init()\n{\n setupGeneral();\n setupRecurrence();\n setupFreeBusy();\n setupDesignerTabs( \"event\" );\n\n \/\/ Propagate date time settings to recurrence tab\n connect( mGeneral, SIGNAL(dateTimesChanged(const QDateTime&,const QDateTime& )),\n mRecurrence, SLOT(setDateTimes(const QDateTime&,const QDateTime&)) );\n connect( mGeneral, SIGNAL(dateTimeStrChanged(const QString&)),\n mRecurrence, SLOT(setDateTimeStr(const QString&)) );\n connect( mFreeBusy, SIGNAL(dateTimesChanged(const QDateTime&,const QDateTime&)),\n mRecurrence, SLOT(setDateTimes(const QDateTime&,const QDateTime&)) );\n\n \/\/ Propagate date time settings to gantt tab and back\n connect( mGeneral, SIGNAL(dateTimesChanged(const QDateTime&,const QDateTime&)),\n mFreeBusy, SLOT(slotUpdateGanttView(const QDateTime&,const QDateTime&)) );\n connect( mFreeBusy, SIGNAL(dateTimesChanged(const QDateTime&,const QDateTime&)),\n mGeneral, SLOT(setDateTimes(const QDateTime&,const QDateTime&)) );\n\n connect( mGeneral, SIGNAL(focusReceivedSignal()),\n SIGNAL(focusReceivedSignal()) );\n\n connect( mGeneral, SIGNAL(openCategoryDialog()),\n SIGNAL(editCategories()) );\n connect( this, SIGNAL(updateCategoryConfig()),\n mGeneral, SIGNAL(updateCategoryConfig()) );\n\n connect( mFreeBusy, SIGNAL(updateAttendeeSummary(int)),\n mGeneral, SLOT(updateAttendeeSummary(int)) );\n\n connect( mGeneral, SIGNAL(editRecurrence()),\n mRecurrenceDialog, SLOT(show()) );\n connect( mRecurrenceDialog, SIGNAL(okClicked()),\n SLOT(updateRecurrenceSummary()) );\n\n connect( mGeneral, SIGNAL(acceptInvitation()),\n mFreeBusy, SLOT(acceptForMe()) );\n connect( mGeneral, SIGNAL(declineInvitation()),\n mFreeBusy, SLOT(declineForMe()) );\n\n updateRecurrenceSummary();\n}\n\nvoid KOEventEditor::reload()\n{\n if ( mEvent ) {\n readEvent( mEvent, true );\n }\n}\n\nvoid KOEventEditor::setupGeneral()\n{\n mGeneral = new KOEditorGeneralEvent( mCalendar, this );\n\n if( KOPrefs::instance()->mCompactDialogs ) {\n QFrame *topFrame = new QFrame();\n addPage( topFrame, i18nc( \"@title:tab general event settings\", \"General\" ) );\n topFrame->setWhatsThis( i18nc( \"@info:whatsthis\",\n \"The General tab allows you to set the most \"\n \"common options for the event.\" ) );\n\n QBoxLayout *topLayout = new QVBoxLayout( topFrame );\n topLayout->setSpacing( spacingHint() );\n\n mGeneral->initHeader( topFrame, topLayout );\n mGeneral->initTime( topFrame, topLayout );\n mGeneral->initAlarm( topFrame, topLayout );\n mGeneral->enableAlarm( false );\n\n topLayout->addStretch( 1 );\n\n QFrame *topFrame2 = new QFrame();\n addPage( topFrame2, i18nc( \"@title:tab\", \"Details\" ) );\n\n QBoxLayout *topLayout2 = new QVBoxLayout( topFrame2 );\n topLayout2->setSpacing( spacingHint() );\n\n mGeneral->initClass( topFrame2, topLayout2 );\n mGeneral->initSecrecy( topFrame2, topLayout2 );\n mGeneral->initDescription( topFrame2, topLayout2 );\n } else {\n QFrame *topFrame = new QFrame();\n addPage( topFrame, i18nc( \"@title:tab general event settings\", \"&General\" ) );\n topFrame->setWhatsThis( i18nc( \"@info:whatsthis\",\n \"The General tab allows you to set the most \"\n \"common options for the event.\" ) );\n\n QBoxLayout *topLayout = new QVBoxLayout( topFrame );\n topLayout->setSpacing( spacingHint() );\n\n mGeneral->initInvitationBar( topFrame, topLayout );\n mGeneral->initHeader( topFrame, topLayout );\n mGeneral->initTime( topFrame, topLayout );\n mGeneral->initDescription( topFrame, topLayout );\n mGeneral->initAttachments( topFrame, topLayout );\n connect( mGeneral, SIGNAL(openURL(const KUrl&)),\n this, SLOT(openURL(const KUrl&)) );\n connect( this, SIGNAL(signalAddAttachments(const QStringList&,const QStringList&,bool)),\n mGeneral, SLOT(addAttachments(const QStringList&,const QStringList&,bool)) );\n }\n\n mGeneral->finishSetup();\n}\n\nvoid KOEventEditor::modified( int modification )\n{\n Q_UNUSED( modification );\n\n \/\/ Play dumb, just reload the event. This dialog has become so complicated\n \/\/ that there is no point in trying to be smart here...\n reload();\n}\n\nvoid KOEventEditor::setupRecurrence()\n{\n#if 0\n QFrame *topFrame = new QFrame();\n addPage( topFrame, i18nc( \"@title:tab\", \"Rec&urrence\" ) );\n\n topFrame->setWhatsThis( i18nc( \"@info:whatsthis\",\n \"The Recurrence tab allows you to set options \"\n \"on how often this event recurs.\" ) );\n\n QBoxLayout *topLayout = new QVBoxLayout( topFrame );\n\n mRecurrence = new KOEditorRecurrence( topFrame );\n topLayout->addWidget( mRecurrence );\n#endif\n mRecurrenceDialog = new KOEditorRecurrenceDialog( this );\n mRecurrenceDialog->hide();\n mRecurrence = mRecurrenceDialog->editor();\n}\n\nvoid KOEventEditor::setupFreeBusy()\n{\n QFrame *freeBusyPage = new QFrame();\n addPage( freeBusyPage, i18nc( \"@title:tab\", \"&Attendees\" ) );\n freeBusyPage->setWhatsThis( i18nc( \"@info:whatsthis\",\n \"The Free\/Busy tab allows you to see \"\n \"whether other attendees are free or busy \"\n \"during your event.\" ) );\n\n QBoxLayout *topLayout = new QVBoxLayout( freeBusyPage );\n\n mAttendeeEditor = mFreeBusy = new KOEditorFreeBusy( spacingHint(), freeBusyPage );\n topLayout->addWidget( mFreeBusy );\n}\n\nvoid KOEventEditor::editIncidence( Incidence *incidence, Calendar *calendar )\n{\n Event*event = dynamic_cast( incidence );\n if ( event ) {\n init();\n\n mEvent = event;\n mCalendar = calendar;\n readEvent( mEvent, false );\n }\n\n setCaption( i18nc( \"@title:window\",\n \"Edit Event : %1\", KOHelper::resourceLabel( calendar, incidence ) ) );\n}\n\nvoid KOEventEditor::newEvent()\n{\n init();\n mEvent = 0;\n loadDefaults();\n setCaption( i18nc( \"@title:window\", \"New Event\" ) );\n}\n\nvoid KOEventEditor::setDates( const QDateTime &from, const QDateTime &to, bool allDay )\n{\n mGeneral->setDefaults( from, to, allDay );\n mRecurrence->setDefaults( from, to, allDay );\n if ( mFreeBusy ) {\n if ( allDay ) {\n mFreeBusy->setDateTimes( from, to.addDays( 1 ) );\n } else {\n mFreeBusy->setDateTimes( from, to );\n }\n }\n}\n\nvoid KOEventEditor::setTexts( const QString &summary, const QString &description,\n bool richDescription )\n{\n if ( description.isEmpty() && summary.contains( \"\\n\" ) ) {\n mGeneral->setDescription( summary, richDescription );\n int pos = summary.indexOf( \"\\n\" );\n mGeneral->setSummary( summary.left( pos ) );\n } else {\n mGeneral->setSummary( summary );\n mGeneral->setDescription( description, richDescription );\n }\n}\n\nvoid KOEventEditor::loadDefaults()\n{\n QDateTime from( QDate::currentDate(), KOPrefs::instance()->mStartTime.time() );\n int addSecs = ( KOPrefs::instance()->mDefaultDuration.time().hour() * 3600 ) +\n ( KOPrefs::instance()->mDefaultDuration.time().minute() * 60 );\n QDateTime to( from.addSecs( addSecs ) );\n\n setDates( from, to, false );\n}\n\nbool KOEventEditor::processInput()\n{\n if ( !validateInput() || !mChanger ) {\n return false;\n }\n\n QPointer freeBusy( mFreeBusy );\n\n if ( mEvent ) {\n bool rc = true;\n Event *oldEvent = mEvent->clone();\n Event *event = mEvent->clone();\n\n fillEvent( event );\n\n if ( *event == *mEvent ) {\n \/\/ Don't do anything\n if ( mIsCounter ) {\n KMessageBox::information(\n this,\n i18n( \"You didn't change the event, \"\n \"thus no counter proposal has been sent to the organizer.\" ),\n i18n( \"No changes\" ) );\n }\n } else {\n \/\/IncidenceChanger::assignIncidence( mEvent, event );\n fillEvent( mEvent );\n if ( mIsCounter ) {\n KOGroupware::instance()->sendCounterProposal( mCalendar, oldEvent, mEvent );\n \/\/ add dummy event at the position of the counter proposal\n Event *event = mEvent->clone();\n event->clearAttendees();\n event->setSummary( i18n( \"My counter proposal for: %1\", mEvent->summary() ) );\n mChanger->addIncidence( event );\n } else {\n mChanger->changeIncidence( oldEvent, mEvent );\n }\n }\n delete event;\n delete oldEvent;\n return rc;\n } else {\n mEvent = new Event;\n mEvent->setOrganizer( Person( KOPrefs::instance()->fullName(),\n KOPrefs::instance()->email() ) );\n fillEvent( mEvent );\n if ( !mChanger->addIncidence( mEvent, this ) ) {\n delete mEvent;\n mEvent = 0;\n return false;\n }\n }\n \/\/ if \"this\" was deleted, freeBusy is 0 (being a guardedptr)\n if ( freeBusy ) {\n freeBusy->cancelReload();\n }\n\n return true;\n}\n\nvoid KOEventEditor::processCancel()\n{\n if ( mFreeBusy ) {\n mFreeBusy->cancelReload();\n }\n}\n\nvoid KOEventEditor::deleteEvent()\n{\n if ( mEvent ) {\n emit deleteIncidenceSignal( mEvent );\n }\n\n emit dialogClose( mEvent );\n reject();\n}\n\nvoid KOEventEditor::readEvent( Event *event, bool tmpl )\n{\n if ( !event ) {\n return;\n }\n\n mGeneral->readEvent( event, tmpl );\n mRecurrence->readIncidence( event );\n if ( mFreeBusy ) {\n mFreeBusy->readIncidence( event );\n mFreeBusy->triggerReload();\n }\n\n createEmbeddedURLPages( event );\n readDesignerFields( event );\n\n if ( mIsCounter ) {\n mGeneral->invitationBar()->hide();\n }\n}\n\nvoid KOEventEditor::fillEvent( Event *event )\n{\n mGeneral->fillEvent( event );\n if ( mFreeBusy ) {\n mFreeBusy->fillIncidence( event );\n }\n\n cancelRemovedAttendees( event );\n\n mRecurrence->fillIncidence( event );\n\n writeDesignerFields( event );\n}\n\nbool KOEventEditor::validateInput()\n{\n if ( !mGeneral->validateInput() ) {\n return false;\n }\n if ( !mDetails->validateInput() ) {\n return false;\n }\n if ( !mRecurrence->validateInput() ) {\n return false;\n }\n\n return true;\n}\n\nint KOEventEditor::msgItemDelete()\n{\n return KMessageBox::warningContinueCancel(\n this,\n i18nc( \"@info\", \"This item will be permanently deleted.\" ),\n i18nc( \"@title:window\", \"KOrganizer Confirmation\" ),\n KGuiItem( i18nc( \"@action:button\", \"Delete\" ), \"edit-delete\" ) );\n}\n\nvoid KOEventEditor::loadTemplate( CalendarLocal &cal )\n{\n Event::List events = cal.events();\n if ( events.count() == 0 ) {\n KMessageBox::error( this, i18nc( \"@info\", \"Template does not contain a valid event.\" ) );\n } else {\n readEvent( events.first(), true );\n }\n}\n\nQStringList &KOEventEditor::templates() const\n{\n return KOPrefs::instance()->mEventTemplates;\n}\n\nvoid KOEventEditor::slotSaveTemplate( const QString &templateName )\n{\n Event *event = new Event;\n fillEvent( event );\n saveAsTemplate( event, templateName );\n}\n\nQObject *KOEventEditor::typeAheadReceiver() const\n{\n return mGeneral->typeAheadReceiver();\n}\n\nvoid KOEventEditor::updateRecurrenceSummary()\n{\n Event *ev = new Event();\n fillEvent( ev );\n mGeneral->updateRecurrenceSummary( IncidenceFormatter::recurrenceString( ev ) );\n delete ev;\n}\n\nvoid KOEventEditor::selectInvitationCounterProposal( bool enable )\n{\n KOIncidenceEditor::selectInvitationCounterProposal( enable );\n if ( enable ) {\n mGeneral->invitationBar()->hide();\n }\n}\n\n#include \"koeventeditor.moc\"\n<|endoftext|>"} {"text":"\/* -*- Mode:C++; c-file-style:\"gnu\"; indent-tabs-mode:nil; -*- *\/\n\n#include \"ns3\/object.h\"\n#include \"ns3\/global-value.h\"\n#include \"ns3\/core-module.h\"\n#include \"ns3\/csma-module.h\"\n#include \"ns3\/internet-module.h\"\n#include \"ns3\/applications-module.h\"\n#include \n#include \n\n\n#include \"Observador.h\"\n\n#define STARTTIME 2.0\n#define STOPTIME 10000.0\n#define T_STUDENT_VALUE 2.2622\n\ntypedef struct datos {\n double mediaNumIntentosTotales;\n double mediaTiempoEcoTotal;\n double mediaPorcentajeErrorClientes;\n} DATOS; \n\nusing namespace ns3;\n\nNS_LOG_COMPONENT_DEFINE (\"practica05\");\n\n\nDATOS simulacion (uint32_t nCsma, Time retardoProp, DataRate capacidad, \n uint32_t tamPaquete, Time intervalo, uint32_t maxReintentos) {\n \n NodeContainer csmaNodes;\n csmaNodes.Create (nCsma);\n\n CsmaHelper csma;\n csma.SetChannelAttribute (\"DataRate\", DataRateValue (capacidad));\n csma.SetChannelAttribute (\"Delay\", TimeValue (retardoProp));\n\n NetDeviceContainer csmaDevices;\n csmaDevices = csma.Install (csmaNodes);\n \/\/ Instalamos la pila TCP\/IP en todos los nodos\n InternetStackHelper stack;\n stack.Install (csmaNodes);\n \/\/ Y les asignamos direcciones\n Ipv4AddressHelper address;\n address.SetBase (\"10.1.2.0\", \"255.255.255.0\");\n Ipv4InterfaceContainer csmaInterfaces = address.Assign (csmaDevices);\n\n \/\/\/\/\/\/\/\/\/\/\/ Instalación de las aplicaciones\n \/\/ Servidor\n UdpEchoServerHelper echoServer (9);\n ApplicationContainer serverApp = echoServer.Install (csmaNodes.Get (nCsma - 1));\n serverApp.Start (Seconds (STARTTIME));\n serverApp.Stop (Seconds (STOPTIME));\n \/\/ Clientes\n UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (nCsma - 1), 9);\n echoClient.SetAttribute (\"MaxPackets\", UintegerValue (10000));\n echoClient.SetAttribute (\"Interval\", TimeValue (intervalo));\n echoClient.SetAttribute (\"PacketSize\", UintegerValue (tamPaquete));\n NodeContainer clientes;\n\n for (uint32_t i = 0; i < nCsma - 1; i++)\n {\n clientes.Add (csmaNodes.Get (i));\n }\n NS_LOG_FUNCTION (\"Fin bucle de creacion de observadores\");\n\n ApplicationContainer clientApps = echoClient.Install (clientes);\n NS_LOG_FUNCTION (\"Instalacion de clientes de echo realizada\");\n clientApps.Start (Seconds (STARTTIME));\n clientApps.Stop (Seconds (STOPTIME));\n\n \/\/ Cálculo de rutas\n Ipv4GlobalRoutingHelper::PopulateRoutingTables ();\n\n csma.EnablePcap (\"practica05\", csmaDevices.Get (nCsma - 1), true);\n\n Observador observadores[nCsma]; \n for (uint32_t i = 0; i < nCsma; i++) {\n csmaDevices.Get(i)->TraceConnectWithoutContext (\"PhyTxEnd\", MakeCallback(&Observador::PaqueteEnviado, &observadores[i]));\n csmaDevices.Get(i)->TraceConnectWithoutContext (\"PhyTxDrop\", MakeCallback(&Observador::PaquetePerdido, &observadores[i]));\n csmaDevices.Get(i)->TraceConnectWithoutContext (\"MacTxBackoff\", MakeCallback(&Observador::PaqueteEnBackoff, &observadores[i]));\n csmaDevices.Get(i)->TraceConnectWithoutContext (\"MacTx\", MakeCallback(&Observador::PaqueteParaEnviar, &observadores[i]));\n csmaDevices.Get(i)->TraceConnectWithoutContext (\"MacRx\", MakeCallback(&Observador::PaqueteRecibidoParaEntregar, &observadores[i])); \n \n Ptr csma_device = csmaDevices.Get(i)->GetObject();\n csma_device->SetBackoffParams (Time (\"1us\"), 10, 1000, 10, maxReintentos);\n }\n \n NS_LOG_FUNCTION (\"Va a comenzar la simulacion\");\n Simulator::Run ();\n Simulator::Destroy ();\n NS_LOG_FUNCTION (\"Finalizada simulacion\");\n\n\n Average numIntentosTotales;\n Average tiempoEcoTotal;\n Average porcentajeErrorClientes;\n Average porcentajeErrorEscenario;\n\n for (uint32_t i = 0; i < nCsma; i++) {\n \n double mediaNumIntentos = observadores[i].GetMediaNumIntentos();\n double mediaTiempoEco = observadores[i].GetMediaTiempoEco();\n double porcentajeError = observadores[i].GetPorcentajePaquetesPerdidos(); \n\n if (std::isnan(mediaNumIntentos)) {\n mediaNumIntentos = 0;\n }\n if (std::isnan(mediaTiempoEco)) {\n mediaTiempoEco = 0;\n }\n\n NS_LOG_INFO (\"Media de intentos en nodo \" << i << \": \" << mediaNumIntentos);\n porcentajeErrorEscenario.Update(porcentajeError);\n if (i < nCsma - 1) {\n NS_LOG_INFO (\"Tiempo medio de eco en nodo \" << i << \": \" << Time(mediaTiempoEco));\n if (i > 1) {\n porcentajeErrorClientes.Update(porcentajeError);\n tiempoEcoTotal.Update(mediaTiempoEco);\n numIntentosTotales.Update(mediaNumIntentos);\n }\n }\n NS_LOG_INFO (\"Porcentaje de paquetes perdidos en nodo \" << i << \": \" << porcentajeError << \" %\");\n NS_LOG_INFO (\"\");\n }\n\n double mediaNumIntentosTotales = numIntentosTotales.Mean();\n double mediaTiempoEcoTotal = tiempoEcoTotal.Mean();\n double mediaPorcentajeErrorClientes = porcentajeErrorClientes.Mean();\n double mediaPorcentajeErrorEscenario = porcentajeErrorEscenario.Mean(); \n\n if (std::isnan(mediaNumIntentosTotales)) {\n mediaNumIntentosTotales = 0;\n }\n if (std::isnan(mediaTiempoEcoTotal)) {\n mediaTiempoEcoTotal = 0;\n }\n if (std::isnan(mediaPorcentajeErrorClientes)) {\n mediaPorcentajeErrorClientes = 0;\n }\n if (std::isnan(mediaPorcentajeErrorEscenario)) {\n mediaPorcentajeErrorEscenario = 0;\n }\n \n NS_LOG_INFO (\"--------------------------------------------------------\");\n NS_LOG_INFO (\"Media de intentos de transmision en el escenario: \" << mediaNumIntentosTotales);\n NS_LOG_INFO (\"Tiempo de eco medio en el escenario: \" << Time(mediaTiempoEcoTotal));\n NS_LOG_INFO (\"Porcentaje de paquetes perdidos por los clientes: \" << mediaPorcentajeErrorClientes << \" %\");\n NS_LOG_INFO (\"Porcentaje de paquetes perdidos en el escenario: \" << mediaPorcentajeErrorEscenario << \" %\");\n NS_LOG_INFO (\"--------------------------------------------------------\");\n \n DATOS datos = { mediaNumIntentosTotales, mediaTiempoEcoTotal, mediaPorcentajeErrorClientes };\n return datos;\n}\n\nint\nmain (int argc, char *argv[])\n{\n GlobalValue::Bind(\"ChecksumEnabled\", BooleanValue(true));\n Time::SetResolution (Time::US);\n\n uint32_t seed = 1;\n\n uint32_t dni[8] = {3,1,4,8,2,2,0,3};\n NS_LOG_INFO (\"DNI: \" << dni[8]< numIntentosTotales;\n Average tiempoEcoTotal;\n Average porcentajeErrorClientes;\n for (int i = 0; i < 10; i++) {\n DATOS datos;\n \/\/Modificamos la semilla de la simulacion\n SeedManager::SetRun (seed++);\n datos = simulacion(nCsma, retardoProp, capacidad, tamPaquete, intervalo, maxReintentos);\n numIntentosTotales.Update (datos.mediaNumIntentosTotales);\n tiempoEcoTotal.Update (datos.mediaTiempoEcoTotal);\n porcentajeErrorClientes.Update (datos.mediaPorcentajeErrorClientes);\n }\n double z[3];\n z[0] = T_STUDENT_VALUE * std::sqrt (numIntentosTotales.Var() \/ 10);\n dataset[0].Add(maxReintentos, numIntentosTotales.Mean(), 2 * z[0]);\n z[1] = T_STUDENT_VALUE * std::sqrt (tiempoEcoTotal.Var() \/ 10);\n dataset[1].Add(maxReintentos, tiempoEcoTotal.Mean(), 2 * z[1]);\n z[2] = T_STUDENT_VALUE * std::sqrt (porcentajeErrorClientes.Var() \/ 10);\n dataset[2].Add(maxReintentos, porcentajeErrorClientes.Mean(), 2 * z[2]);\n NS_LOG_DEBUG (numIntentosTotales.Mean() - z[0] << \" < numIntentosTotales < \" << numIntentosTotales.Mean() + z[0]);\n NS_LOG_DEBUG (tiempoEcoTotal.Mean() - z[1] << \" < tiempoEcoTotal < \" << tiempoEcoTotal.Mean() + z[1]);\n NS_LOG_DEBUG (porcentajeErrorClientes.Mean() - z[2] << \" < porcentajeErrorClientes < \" << porcentajeErrorClientes.Mean() + z[2]);\n NS_LOG_DEBUG (\"\");\n }\n\n plot[0].AddDataset (dataset[0]);\n std::ofstream plotFile1 (\"practica05-01.plt\");\n plot[0].GenerateOutput (plotFile1);\n plotFile1 << \"pause -1\" << std::endl;\n plotFile1.close ();\n \n \n plot[1].AddDataset (dataset[1]);\n std::ofstream plotFile2 (\"practica05-02.plt\");\n plot[1].GenerateOutput (plotFile2);\n plotFile2 << \"pause -1\" << std::endl;\n plotFile2.close ();\n \n \n plot[2].AddDataset (dataset[2]);\n std::ofstream plotFile3 (\"practica05-03.plt\");\n plot[2].GenerateOutput (plotFile3);\n plotFile3 << \"pause -1\" << std::endl;\n plotFile3.close ();\n \n return 0;\n}\nP05 añadido tiempo de simulacion como parametro\/* -*- Mode:C++; c-file-style:\"gnu\"; indent-tabs-mode:nil; -*- *\/\n\n#include \"ns3\/object.h\"\n#include \"ns3\/global-value.h\"\n#include \"ns3\/core-module.h\"\n#include \"ns3\/csma-module.h\"\n#include \"ns3\/internet-module.h\"\n#include \"ns3\/applications-module.h\"\n#include \n#include \n\n\n#include \"Observador.h\"\n\n#define STARTTIME 2.0\n#define STOPTIME 10000.0\n#define T_STUDENT_VALUE 2.2622\n\ntypedef struct datos {\n double mediaNumIntentosTotales;\n double mediaTiempoEcoTotal;\n double mediaPorcentajeErrorClientes;\n} DATOS; \n\nusing namespace ns3;\n\nNS_LOG_COMPONENT_DEFINE (\"practica05\");\n\n\nDATOS simulacion (uint32_t nCsma, Time retardoProp, DataRate capacidad, \n uint32_t tamPaquete, Time intervalo, uint32_t maxReintentos, double tSimulacion) {\n \n NodeContainer csmaNodes;\n csmaNodes.Create (nCsma);\n\n CsmaHelper csma;\n csma.SetChannelAttribute (\"DataRate\", DataRateValue (capacidad));\n csma.SetChannelAttribute (\"Delay\", TimeValue (retardoProp));\n\n NetDeviceContainer csmaDevices;\n csmaDevices = csma.Install (csmaNodes);\n \/\/ Instalamos la pila TCP\/IP en todos los nodos\n InternetStackHelper stack;\n stack.Install (csmaNodes);\n \/\/ Y les asignamos direcciones\n Ipv4AddressHelper address;\n address.SetBase (\"10.1.2.0\", \"255.255.255.0\");\n Ipv4InterfaceContainer csmaInterfaces = address.Assign (csmaDevices);\n\n \/\/\/\/\/\/\/\/\/\/\/ Instalación de las aplicaciones\n \/\/ Servidor\n UdpEchoServerHelper echoServer (9);\n ApplicationContainer serverApp = echoServer.Install (csmaNodes.Get (nCsma - 1));\n serverApp.Start (Seconds (STARTTIME));\n serverApp.Stop (Seconds (STARTTIME + tSimulacion));\n \/\/ Clientes\n UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (nCsma - 1), 9);\n echoClient.SetAttribute (\"MaxPackets\", UintegerValue (10000));\n echoClient.SetAttribute (\"Interval\", TimeValue (intervalo));\n echoClient.SetAttribute (\"PacketSize\", UintegerValue (tamPaquete));\n NodeContainer clientes;\n\n for (uint32_t i = 0; i < nCsma - 1; i++)\n {\n clientes.Add (csmaNodes.Get (i));\n }\n NS_LOG_FUNCTION (\"Fin bucle de creacion de observadores\");\n\n ApplicationContainer clientApps = echoClient.Install (clientes);\n NS_LOG_FUNCTION (\"Instalacion de clientes de echo realizada\");\n clientApps.Start (Seconds (STARTTIME));\n clientApps.Stop (Seconds (STARTTIME + tSimulacion));\n\n \/\/ Cálculo de rutas\n Ipv4GlobalRoutingHelper::PopulateRoutingTables ();\n\n csma.EnablePcap (\"practica05\", csmaDevices.Get (nCsma - 1), true);\n\n Observador observadores[nCsma]; \n for (uint32_t i = 0; i < nCsma; i++) {\n csmaDevices.Get(i)->TraceConnectWithoutContext (\"PhyTxEnd\", MakeCallback(&Observador::PaqueteEnviado, &observadores[i]));\n csmaDevices.Get(i)->TraceConnectWithoutContext (\"PhyTxDrop\", MakeCallback(&Observador::PaquetePerdido, &observadores[i]));\n csmaDevices.Get(i)->TraceConnectWithoutContext (\"MacTxBackoff\", MakeCallback(&Observador::PaqueteEnBackoff, &observadores[i]));\n csmaDevices.Get(i)->TraceConnectWithoutContext (\"MacTx\", MakeCallback(&Observador::PaqueteParaEnviar, &observadores[i]));\n csmaDevices.Get(i)->TraceConnectWithoutContext (\"MacRx\", MakeCallback(&Observador::PaqueteRecibidoParaEntregar, &observadores[i])); \n \n Ptr csma_device = csmaDevices.Get(i)->GetObject();\n csma_device->SetBackoffParams (Time (\"1us\"), 10, 1000, 10, maxReintentos);\n }\n \n NS_LOG_FUNCTION (\"Va a comenzar la simulacion\");\n Simulator::Run ();\n Simulator::Destroy ();\n NS_LOG_FUNCTION (\"Finalizada simulacion\");\n\n\n Average numIntentosTotales;\n Average tiempoEcoTotal;\n Average porcentajeErrorClientes;\n Average porcentajeErrorEscenario;\n\n for (uint32_t i = 0; i < nCsma; i++) {\n \n double mediaNumIntentos = observadores[i].GetMediaNumIntentos();\n double mediaTiempoEco = observadores[i].GetMediaTiempoEco();\n double porcentajeError = observadores[i].GetPorcentajePaquetesPerdidos(); \n\n if (std::isnan(mediaNumIntentos)) {\n mediaNumIntentos = 0;\n }\n if (std::isnan(mediaTiempoEco)) {\n mediaTiempoEco = 0;\n }\n\n NS_LOG_INFO (\"Media de intentos en nodo \" << i << \": \" << mediaNumIntentos);\n porcentajeErrorEscenario.Update(porcentajeError);\n if (i < nCsma - 1) {\n NS_LOG_INFO (\"Tiempo medio de eco en nodo \" << i << \": \" << Time(mediaTiempoEco));\n if (i > 1) {\n porcentajeErrorClientes.Update(porcentajeError);\n tiempoEcoTotal.Update(mediaTiempoEco);\n numIntentosTotales.Update(mediaNumIntentos);\n }\n }\n NS_LOG_INFO (\"Porcentaje de paquetes perdidos en nodo \" << i << \": \" << porcentajeError << \" %\");\n NS_LOG_INFO (\"\");\n }\n\n double mediaNumIntentosTotales = numIntentosTotales.Mean();\n double mediaTiempoEcoTotal = tiempoEcoTotal.Mean();\n double mediaPorcentajeErrorClientes = porcentajeErrorClientes.Mean();\n double mediaPorcentajeErrorEscenario = porcentajeErrorEscenario.Mean(); \n\n if (std::isnan(mediaNumIntentosTotales)) {\n mediaNumIntentosTotales = 0;\n }\n if (std::isnan(mediaTiempoEcoTotal)) {\n mediaTiempoEcoTotal = 0;\n }\n if (std::isnan(mediaPorcentajeErrorClientes)) {\n mediaPorcentajeErrorClientes = 0;\n }\n if (std::isnan(mediaPorcentajeErrorEscenario)) {\n mediaPorcentajeErrorEscenario = 0;\n }\n \n NS_LOG_INFO (\"--------------------------------------------------------\");\n NS_LOG_INFO (\"Media de intentos de transmision en el escenario: \" << mediaNumIntentosTotales);\n NS_LOG_INFO (\"Tiempo de eco medio en el escenario: \" << Time(mediaTiempoEcoTotal));\n NS_LOG_INFO (\"Porcentaje de paquetes perdidos por los clientes: \" << mediaPorcentajeErrorClientes << \" %\");\n NS_LOG_INFO (\"Porcentaje de paquetes perdidos en el escenario: \" << mediaPorcentajeErrorEscenario << \" %\");\n NS_LOG_INFO (\"--------------------------------------------------------\");\n \n DATOS datos = { mediaNumIntentosTotales, mediaTiempoEcoTotal, mediaPorcentajeErrorClientes };\n return datos;\n}\n\nint\nmain (int argc, char *argv[])\n{\n GlobalValue::Bind(\"ChecksumEnabled\", BooleanValue(true));\n Time::SetResolution (Time::US);\n\n uint32_t seed = 1;\n\n uint32_t dni[8] = {3,1,4,8,2,2,0,3};\n NS_LOG_INFO (\"DNI: \" << dni[8]< numIntentosTotales;\n Average tiempoEcoTotal;\n Average porcentajeErrorClientes;\n for (int i = 0; i < 10; i++) {\n DATOS datos;\n \/\/Modificamos la semilla de la simulacion\n SeedManager::SetRun (seed++);\n datos = simulacion(nCsma, retardoProp, capacidad, tamPaquete, intervalo, maxReintentos, tSimulacion);\n numIntentosTotales.Update (datos.mediaNumIntentosTotales);\n tiempoEcoTotal.Update (datos.mediaTiempoEcoTotal);\n porcentajeErrorClientes.Update (datos.mediaPorcentajeErrorClientes);\n }\n double z[3];\n z[0] = T_STUDENT_VALUE * std::sqrt (numIntentosTotales.Var() \/ 10);\n dataset[0].Add(maxReintentos, numIntentosTotales.Mean(), 2 * z[0]);\n z[1] = T_STUDENT_VALUE * std::sqrt (tiempoEcoTotal.Var() \/ 10);\n dataset[1].Add(maxReintentos, tiempoEcoTotal.Mean(), 2 * z[1]);\n z[2] = T_STUDENT_VALUE * std::sqrt (porcentajeErrorClientes.Var() \/ 10);\n dataset[2].Add(maxReintentos, porcentajeErrorClientes.Mean(), 2 * z[2]);\n NS_LOG_DEBUG (numIntentosTotales.Mean() - z[0] << \" < numIntentosTotales < \" << numIntentosTotales.Mean() + z[0]);\n NS_LOG_DEBUG (tiempoEcoTotal.Mean() - z[1] << \" < tiempoEcoTotal < \" << tiempoEcoTotal.Mean() + z[1]);\n NS_LOG_DEBUG (porcentajeErrorClientes.Mean() - z[2] << \" < porcentajeErrorClientes < \" << porcentajeErrorClientes.Mean() + z[2]);\n NS_LOG_DEBUG (\"\");\n }\n\n plot[0].AddDataset (dataset[0]);\n std::ofstream plotFile1 (\"practica05-01.plt\");\n plot[0].GenerateOutput (plotFile1);\n plotFile1 << \"pause -1\" << std::endl;\n plotFile1.close ();\n \n \n plot[1].AddDataset (dataset[1]);\n std::ofstream plotFile2 (\"practica05-02.plt\");\n plot[1].GenerateOutput (plotFile2);\n plotFile2 << \"pause -1\" << std::endl;\n plotFile2.close ();\n \n \n plot[2].AddDataset (dataset[2]);\n std::ofstream plotFile3 (\"practica05-03.plt\");\n plot[2].GenerateOutput (plotFile3);\n plotFile3 << \"pause -1\" << std::endl;\n plotFile3.close ();\n \n return 0;\n}\n<|endoftext|>"} {"text":"coverity#708296 Uninitialized pointer field<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n * Manjeet Dahiya\n *\n * Source:\n * http:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n\n#include \"QXmppPresence.h\"\n#include \"QXmppUtils.h\"\n#include \n#include \n#include \n#include \"QXmppConstants.h\"\n\nQXmppPresence::QXmppPresence(QXmppPresence::Type type,\n const QXmppPresence::Status& status)\n : QXmppStanza(), m_type(type), m_status(status)\n{\n\n}\n\nQXmppPresence::~QXmppPresence()\n{\n\n}\n\nQXmppPresence::Type QXmppPresence::type() const\n{\n return m_type;\n}\n\nvoid QXmppPresence::setType(QXmppPresence::Type type)\n{\n m_type = type;\n}\n\nconst QXmppPresence::Status& QXmppPresence::status() const\n{\n return m_status;\n}\n\nQXmppPresence::Status& QXmppPresence::status()\n{\n return m_status;\n}\n\nvoid QXmppPresence::setStatus(const QXmppPresence::Status& status)\n{\n m_status = status;\n}\n\nvoid QXmppPresence::parse(const QDomElement &element)\n{\n QXmppStanza::parse(element);\n\n setTypeFromStr(element.attribute(\"type\"));\n m_status.parse(element);\n\n QXmppElementList extensions;\n QDomElement xElement = element.firstChildElement();\n m_vCardUpdateType = VCardUpdateNone;\n while(!xElement.isNull())\n {\n \/\/ XEP-0153: vCard-Based Avatars\n if(xElement.namespaceURI() == ns_vcard_update)\n {\n QDomElement photoElement = xElement.firstChildElement(\"photo\");\n if(!photoElement.isNull())\n {\n m_photoHash = photoElement.text().toUtf8();\n if(m_photoHash.isEmpty())\n m_vCardUpdateType = PhotoNotAdvertized;\n else\n m_vCardUpdateType = PhotoAdvertised;\n }\n else\n {\n m_photoHash = \"\";\n m_vCardUpdateType = PhotoNotReady;\n }\n }\n else\n {\n \/\/ other extensions\n extensions << QXmppElement(xElement);\n }\n xElement = xElement.nextSiblingElement();\n }\n setExtensions(extensions);\n}\n\nvoid QXmppPresence::toXml(QXmlStreamWriter *xmlWriter) const\n{\n xmlWriter->writeStartElement(\"presence\");\n helperToXmlAddAttribute(xmlWriter,\"xml:lang\", lang());\n helperToXmlAddAttribute(xmlWriter,\"id\", id());\n helperToXmlAddAttribute(xmlWriter,\"to\", to());\n helperToXmlAddAttribute(xmlWriter,\"from\", from());\n helperToXmlAddAttribute(xmlWriter,\"type\", getTypeStr());\n m_status.toXml(xmlWriter);\n\n error().toXml(xmlWriter);\n\n \/\/ XEP-0153: vCard-Based Avatars\n if(m_vCardUpdateType != VCardUpdateNone)\n {\n xmlWriter->writeStartElement(\"x\");\n helperToXmlAddAttribute(xmlWriter, \"xmlns\", ns_vcard_update);\n switch(m_vCardUpdateType)\n {\n case PhotoNotAdvertized:\n helperToXmlAddTextElement(xmlWriter, \"photo\", \"\");\n break;\n case PhotoAdvertised:\n helperToXmlAddTextElement(xmlWriter, \"photo\", m_photoHash);\n break;\n case PhotoNotReady:\n break;\n default:\n break;\n }\n xmlWriter->writeEndElement();\n }\n\n foreach (const QXmppElement &extension, extensions())\n extension.toXml(xmlWriter);\n\n xmlWriter->writeEndElement();\n}\n\nQString QXmppPresence::getTypeStr() const\n{\n QString text;\n switch(m_type)\n {\n case QXmppPresence::Error:\n text = \"error\"; \n break;\n case QXmppPresence::Available:\n \/\/ no type-attribute if available\n text = \"\"; \n break;\n case QXmppPresence::Unavailable:\n text = \"unavailable\"; \n break;\n case QXmppPresence::Subscribe:\n text = \"subscribe\"; \n break;\n case QXmppPresence::Subscribed:\n text = \"subscribed\"; \n break;\n case QXmppPresence::Unsubscribe:\n text = \"unsubscribe\"; \n break;\n case QXmppPresence::Unsubscribed:\n text = \"unsubscribed\"; \n break;\n case QXmppPresence::Probe:\n text = \"probe\"; \n break;\n default:\n qWarning(\"QXmppPresence::getTypeStr() invalid type %d\", (int)m_type);\n break;\n }\n return text;\n}\n\nvoid QXmppPresence::setTypeFromStr(const QString& str)\n{\n QXmppPresence::Type type;\n if(str == \"error\")\n {\n type = QXmppPresence::Error;\n setType(type);\n return;\n }\n else if(str == \"unavailable\")\n {\n type = QXmppPresence::Unavailable;\n setType(type);\n return;\n }\n else if(str == \"subscribe\")\n {\n type = QXmppPresence::Subscribe;\n setType(type);\n return;\n }\n else if(str == \"subscribed\")\n {\n type = QXmppPresence::Subscribed;\n setType(type);\n return;\n }\n else if(str == \"unsubscribe\")\n {\n type = QXmppPresence::Unsubscribe;\n setType(type);\n return;\n }\n else if(str == \"unsubscribed\")\n {\n type = QXmppPresence::Unsubscribed;\n setType(type);\n return;\n }\n else if(str == \"probe\")\n {\n type = QXmppPresence::Probe;\n setType(type);\n return;\n }\n else if(str == \"\")\n {\n type = QXmppPresence::Available;\n setType(type);\n return;\n }\n else\n {\n type = static_cast(-1);\n qWarning(\"QXmppPresence::setTypeFromStr() invalid input string type: %s\",\n qPrintable(str));\n setType(type);\n return;\n }\n}\n\nQXmppPresence::Status::Status(QXmppPresence::Status::Type type,\n const QString statusText, int priority) :\n m_type(type),\n m_statusText(statusText), m_priority(priority)\n{\n}\n\nQXmppPresence::Status::Type QXmppPresence::Status::type() const\n{\n return m_type;\n}\n\nvoid QXmppPresence::Status::setType(QXmppPresence::Status::Type type)\n{\n m_type = type;\n}\n\nvoid QXmppPresence::Status::setTypeFromStr(const QString& str)\n{\n \/\/ there is no keyword for Offline\n\n QXmppPresence::Status::Type type;\n if(str == \"\") \/\/ not type-attribute means online\n {\n type = QXmppPresence::Status::Online;\n setType(type);\n return;\n }\n else if(str == \"away\")\n {\n type = QXmppPresence::Status::Away;\n setType(type);\n return;\n }\n else if(str == \"xa\")\n {\n type = QXmppPresence::Status::XA;\n setType(type);\n return;\n }\n else if(str == \"dnd\")\n {\n type = QXmppPresence::Status::DND;\n setType(type);\n return;\n }\n else if(str == \"chat\")\n {\n type = QXmppPresence::Status::Chat;\n setType(type);\n return;\n }\n else\n {\n type = static_cast(-1);\n qWarning(\"QXmppPresence::Status::setTypeFromStr() invalid input string type %s\", \n qPrintable(str));\n setType(type);\n }\n}\n\nQString QXmppPresence::Status::getTypeStr() const\n{\n QString text;\n switch(m_type)\n {\n case QXmppPresence::Status::Online:\n \/\/ no type-attribute if available\n text = \"\"; \n break;\n case QXmppPresence::Status::Offline:\n text = \"\"; \n break;\n case QXmppPresence::Status::Away:\n text = \"away\"; \n break;\n case QXmppPresence::Status::XA:\n text = \"xa\"; \n break;\n case QXmppPresence::Status::DND:\n text = \"dnd\"; \n break;\n case QXmppPresence::Status::Chat:\n text = \"chat\"; \n break;\n default:\n qWarning(\"QXmppPresence::Status::getTypeStr() invalid type %d\",\n (int)m_type);\n break;\n }\n return text;\n}\n\nQString QXmppPresence::Status::statusText() const\n{\n return m_statusText;\n}\n\nvoid QXmppPresence::Status::setStatusText(const QString& str)\n{\n m_statusText = str;\n}\n\nint QXmppPresence::Status::priority() const\n{\n return m_priority;\n}\n\nvoid QXmppPresence::Status::setPriority(int priority)\n{\n m_priority = priority;\n}\n\nvoid QXmppPresence::Status::parse(const QDomElement &element)\n{\n setTypeFromStr(element.firstChildElement(\"show\").text());\n m_statusText = element.firstChildElement(\"status\").text();\n m_priority = element.firstChildElement(\"priority\").text().toInt();\n}\n\nvoid QXmppPresence::Status::toXml(QXmlStreamWriter *xmlWriter) const\n{\n const QString show = getTypeStr();\n if (!show.isEmpty())\n helperToXmlAddTextElement(xmlWriter, \"show\", getTypeStr());\n if (!m_statusText.isEmpty())\n helperToXmlAddTextElement(xmlWriter, \"status\", m_statusText);\n if (m_priority != 0)\n helperToXmlAddNumberElement(xmlWriter, \"priority\", m_priority);\n}\n\nQByteArray QXmppPresence::photoHash() const\n{\n return m_photoHash;\n}\n\nvoid QXmppPresence::setPhotoHash(const QByteArray& photoHash)\n{\n m_photoHash = photoHash;\n}\n\nQXmppPresence::VCardUpdateType QXmppPresence::vCardUpdateType()\n{\n return m_vCardUpdateType;\n}\n\nvoid QXmppPresence::setVCardUpdateType(VCardUpdateType type)\n{\n m_vCardUpdateType = type;\n}\n\n\/\/\/ \\cond\n\nQXmppPresence::Type QXmppPresence::getType() const\n{\n return m_type;\n}\n\nconst QXmppPresence::Status& QXmppPresence::getStatus() const\n{\n return m_status;\n}\n\nQXmppPresence::Status& QXmppPresence::getStatus()\n{\n return m_status;\n}\n\nQXmppPresence::Status::Type QXmppPresence::Status::getType() const\n{\n return m_type;\n}\n\nQString QXmppPresence::Status::getStatusText() const\n{\n return m_statusText;\n}\n\nint QXmppPresence::Status::getPriority() const\n{\n return m_priority;\n}\n\n\/\/\/ \\endcond\nthe \"error\" element in a presence stanza is already handled by QXmppStanza::parse(), don't include it in the extensions\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n * Manjeet Dahiya\n *\n * Source:\n * http:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n\n#include \"QXmppPresence.h\"\n#include \"QXmppUtils.h\"\n#include \n#include \n#include \n#include \"QXmppConstants.h\"\n\nQXmppPresence::QXmppPresence(QXmppPresence::Type type,\n const QXmppPresence::Status& status)\n : QXmppStanza(), m_type(type), m_status(status)\n{\n\n}\n\nQXmppPresence::~QXmppPresence()\n{\n\n}\n\nQXmppPresence::Type QXmppPresence::type() const\n{\n return m_type;\n}\n\nvoid QXmppPresence::setType(QXmppPresence::Type type)\n{\n m_type = type;\n}\n\nconst QXmppPresence::Status& QXmppPresence::status() const\n{\n return m_status;\n}\n\nQXmppPresence::Status& QXmppPresence::status()\n{\n return m_status;\n}\n\nvoid QXmppPresence::setStatus(const QXmppPresence::Status& status)\n{\n m_status = status;\n}\n\nvoid QXmppPresence::parse(const QDomElement &element)\n{\n QXmppStanza::parse(element);\n\n setTypeFromStr(element.attribute(\"type\"));\n m_status.parse(element);\n\n QXmppElementList extensions;\n QDomElement xElement = element.firstChildElement();\n m_vCardUpdateType = VCardUpdateNone;\n while(!xElement.isNull())\n {\n \/\/ XEP-0153: vCard-Based Avatars\n if(xElement.namespaceURI() == ns_vcard_update)\n {\n QDomElement photoElement = xElement.firstChildElement(\"photo\");\n if(!photoElement.isNull())\n {\n m_photoHash = photoElement.text().toUtf8();\n if(m_photoHash.isEmpty())\n m_vCardUpdateType = PhotoNotAdvertized;\n else\n m_vCardUpdateType = PhotoAdvertised;\n }\n else\n {\n m_photoHash = \"\";\n m_vCardUpdateType = PhotoNotReady;\n }\n }\n else if (xElement.tagName() != \"error\")\n {\n \/\/ other extensions\n extensions << QXmppElement(xElement);\n }\n xElement = xElement.nextSiblingElement();\n }\n setExtensions(extensions);\n}\n\nvoid QXmppPresence::toXml(QXmlStreamWriter *xmlWriter) const\n{\n xmlWriter->writeStartElement(\"presence\");\n helperToXmlAddAttribute(xmlWriter,\"xml:lang\", lang());\n helperToXmlAddAttribute(xmlWriter,\"id\", id());\n helperToXmlAddAttribute(xmlWriter,\"to\", to());\n helperToXmlAddAttribute(xmlWriter,\"from\", from());\n helperToXmlAddAttribute(xmlWriter,\"type\", getTypeStr());\n m_status.toXml(xmlWriter);\n\n error().toXml(xmlWriter);\n\n \/\/ XEP-0153: vCard-Based Avatars\n if(m_vCardUpdateType != VCardUpdateNone)\n {\n xmlWriter->writeStartElement(\"x\");\n helperToXmlAddAttribute(xmlWriter, \"xmlns\", ns_vcard_update);\n switch(m_vCardUpdateType)\n {\n case PhotoNotAdvertized:\n helperToXmlAddTextElement(xmlWriter, \"photo\", \"\");\n break;\n case PhotoAdvertised:\n helperToXmlAddTextElement(xmlWriter, \"photo\", m_photoHash);\n break;\n case PhotoNotReady:\n break;\n default:\n break;\n }\n xmlWriter->writeEndElement();\n }\n\n foreach (const QXmppElement &extension, extensions())\n extension.toXml(xmlWriter);\n\n xmlWriter->writeEndElement();\n}\n\nQString QXmppPresence::getTypeStr() const\n{\n QString text;\n switch(m_type)\n {\n case QXmppPresence::Error:\n text = \"error\"; \n break;\n case QXmppPresence::Available:\n \/\/ no type-attribute if available\n text = \"\"; \n break;\n case QXmppPresence::Unavailable:\n text = \"unavailable\"; \n break;\n case QXmppPresence::Subscribe:\n text = \"subscribe\"; \n break;\n case QXmppPresence::Subscribed:\n text = \"subscribed\"; \n break;\n case QXmppPresence::Unsubscribe:\n text = \"unsubscribe\"; \n break;\n case QXmppPresence::Unsubscribed:\n text = \"unsubscribed\"; \n break;\n case QXmppPresence::Probe:\n text = \"probe\"; \n break;\n default:\n qWarning(\"QXmppPresence::getTypeStr() invalid type %d\", (int)m_type);\n break;\n }\n return text;\n}\n\nvoid QXmppPresence::setTypeFromStr(const QString& str)\n{\n QXmppPresence::Type type;\n if(str == \"error\")\n {\n type = QXmppPresence::Error;\n setType(type);\n return;\n }\n else if(str == \"unavailable\")\n {\n type = QXmppPresence::Unavailable;\n setType(type);\n return;\n }\n else if(str == \"subscribe\")\n {\n type = QXmppPresence::Subscribe;\n setType(type);\n return;\n }\n else if(str == \"subscribed\")\n {\n type = QXmppPresence::Subscribed;\n setType(type);\n return;\n }\n else if(str == \"unsubscribe\")\n {\n type = QXmppPresence::Unsubscribe;\n setType(type);\n return;\n }\n else if(str == \"unsubscribed\")\n {\n type = QXmppPresence::Unsubscribed;\n setType(type);\n return;\n }\n else if(str == \"probe\")\n {\n type = QXmppPresence::Probe;\n setType(type);\n return;\n }\n else if(str == \"\")\n {\n type = QXmppPresence::Available;\n setType(type);\n return;\n }\n else\n {\n type = static_cast(-1);\n qWarning(\"QXmppPresence::setTypeFromStr() invalid input string type: %s\",\n qPrintable(str));\n setType(type);\n return;\n }\n}\n\nQXmppPresence::Status::Status(QXmppPresence::Status::Type type,\n const QString statusText, int priority) :\n m_type(type),\n m_statusText(statusText), m_priority(priority)\n{\n}\n\nQXmppPresence::Status::Type QXmppPresence::Status::type() const\n{\n return m_type;\n}\n\nvoid QXmppPresence::Status::setType(QXmppPresence::Status::Type type)\n{\n m_type = type;\n}\n\nvoid QXmppPresence::Status::setTypeFromStr(const QString& str)\n{\n \/\/ there is no keyword for Offline\n\n QXmppPresence::Status::Type type;\n if(str == \"\") \/\/ not type-attribute means online\n {\n type = QXmppPresence::Status::Online;\n setType(type);\n return;\n }\n else if(str == \"away\")\n {\n type = QXmppPresence::Status::Away;\n setType(type);\n return;\n }\n else if(str == \"xa\")\n {\n type = QXmppPresence::Status::XA;\n setType(type);\n return;\n }\n else if(str == \"dnd\")\n {\n type = QXmppPresence::Status::DND;\n setType(type);\n return;\n }\n else if(str == \"chat\")\n {\n type = QXmppPresence::Status::Chat;\n setType(type);\n return;\n }\n else\n {\n type = static_cast(-1);\n qWarning(\"QXmppPresence::Status::setTypeFromStr() invalid input string type %s\", \n qPrintable(str));\n setType(type);\n }\n}\n\nQString QXmppPresence::Status::getTypeStr() const\n{\n QString text;\n switch(m_type)\n {\n case QXmppPresence::Status::Online:\n \/\/ no type-attribute if available\n text = \"\"; \n break;\n case QXmppPresence::Status::Offline:\n text = \"\"; \n break;\n case QXmppPresence::Status::Away:\n text = \"away\"; \n break;\n case QXmppPresence::Status::XA:\n text = \"xa\"; \n break;\n case QXmppPresence::Status::DND:\n text = \"dnd\"; \n break;\n case QXmppPresence::Status::Chat:\n text = \"chat\"; \n break;\n default:\n qWarning(\"QXmppPresence::Status::getTypeStr() invalid type %d\",\n (int)m_type);\n break;\n }\n return text;\n}\n\nQString QXmppPresence::Status::statusText() const\n{\n return m_statusText;\n}\n\nvoid QXmppPresence::Status::setStatusText(const QString& str)\n{\n m_statusText = str;\n}\n\nint QXmppPresence::Status::priority() const\n{\n return m_priority;\n}\n\nvoid QXmppPresence::Status::setPriority(int priority)\n{\n m_priority = priority;\n}\n\nvoid QXmppPresence::Status::parse(const QDomElement &element)\n{\n setTypeFromStr(element.firstChildElement(\"show\").text());\n m_statusText = element.firstChildElement(\"status\").text();\n m_priority = element.firstChildElement(\"priority\").text().toInt();\n}\n\nvoid QXmppPresence::Status::toXml(QXmlStreamWriter *xmlWriter) const\n{\n const QString show = getTypeStr();\n if (!show.isEmpty())\n helperToXmlAddTextElement(xmlWriter, \"show\", getTypeStr());\n if (!m_statusText.isEmpty())\n helperToXmlAddTextElement(xmlWriter, \"status\", m_statusText);\n if (m_priority != 0)\n helperToXmlAddNumberElement(xmlWriter, \"priority\", m_priority);\n}\n\nQByteArray QXmppPresence::photoHash() const\n{\n return m_photoHash;\n}\n\nvoid QXmppPresence::setPhotoHash(const QByteArray& photoHash)\n{\n m_photoHash = photoHash;\n}\n\nQXmppPresence::VCardUpdateType QXmppPresence::vCardUpdateType()\n{\n return m_vCardUpdateType;\n}\n\nvoid QXmppPresence::setVCardUpdateType(VCardUpdateType type)\n{\n m_vCardUpdateType = type;\n}\n\n\/\/\/ \\cond\n\nQXmppPresence::Type QXmppPresence::getType() const\n{\n return m_type;\n}\n\nconst QXmppPresence::Status& QXmppPresence::getStatus() const\n{\n return m_status;\n}\n\nQXmppPresence::Status& QXmppPresence::getStatus()\n{\n return m_status;\n}\n\nQXmppPresence::Status::Type QXmppPresence::Status::getType() const\n{\n return m_type;\n}\n\nQString QXmppPresence::Status::getStatusText() const\n{\n return m_statusText;\n}\n\nint QXmppPresence::Status::getPriority() const\n{\n return m_priority;\n}\n\n\/\/\/ \\endcond\n<|endoftext|>"} {"text":"\/*=========================================================================\n *\n * Copyright RTK Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#ifndef __rtkBinningImageFilter_cxx\n#define __rtkBinningImageFilter_cxx\n\n#include \n#include \n#include \n#include \n\n\nnamespace rtk\n{\n\nBinningImageFilter::BinningImageFilter()\n{\n m_BinningFactors[0]=2;\n m_BinningFactors[1]=2;\n}\n\nvoid BinningImageFilter::GenerateInputRequestedRegion()\n{\n ImageType::Pointer inputPtr = const_cast(this->GetInput());\n const ImageType::Pointer outputPtr = const_cast(this->GetOutput());\n\n ImageType::RegionType inputReqRegion = inputPtr->GetLargestPossibleRegion();\n const ImageType::RegionType outputReqRegion = outputPtr->GetRequestedRegion();\n const ImageType::RegionType outputLPRegion = outputPtr->GetLargestPossibleRegion();\n for (unsigned int i = 0; i < ImageType::ImageDimension; i++)\n {\n inputReqRegion.SetSize(i, outputReqRegion.GetSize(i) * m_BinningFactors[i]);\n inputReqRegion.SetIndex(i, inputReqRegion.GetIndex(i) +\n m_BinningFactors[i] * ( outputReqRegion.GetIndex(i) -\n outputLPRegion.GetIndex(i) ) );\n }\n inputPtr->SetRequestedRegion( inputReqRegion );\n}\n\nvoid BinningImageFilter::GenerateOutputInformation()\n{\n const ImageType::SpacingType& inputSpacing = this->GetInput()->GetSpacing();\n const ImageType::SizeType& inputSize = this->GetInput()->GetLargestPossibleRegion().GetSize();\n const ImageType::IndexType& inputStartIndex = this->GetInput()->GetLargestPossibleRegion().GetIndex();\n const ImageType::PointType& inputOrigin = this->GetInput()->GetOrigin();\n\n ImageType::SpacingType outputSpacing;\n ImageType::SizeType outputSize;\n ImageType::IndexType outputStartIndex;\n ImageType::PointType outputOrigin;\n\n for (unsigned int i = 0; i < ImageType::ImageDimension; i++)\n {\n outputSpacing[i] = inputSpacing[i] * m_BinningFactors[i];\n outputOrigin[i] = inputOrigin[i] - 0.5*inputSpacing[i] + 0.5*outputSpacing[i];\n if(inputSize[i]%m_BinningFactors[i] != 0)\n {\n itkExceptionMacro(<< \"Binning currently works only for integer divisions\")\n }\n else\n outputSize[i] = inputSize[i] \/ m_BinningFactors[i];\n\n outputStartIndex[i] = 0;\n }\n\n this->GetOutput()->SetSpacing( outputSpacing );\n this->GetOutput()->SetOrigin( outputOrigin );\n\n \/\/ Set region\n ImageType::RegionType outputLargestPossibleRegion;\n outputLargestPossibleRegion.SetSize( outputSize );\n outputLargestPossibleRegion.SetIndex( outputStartIndex );\n this->GetOutput()->SetLargestPossibleRegion( outputLargestPossibleRegion );\n}\n\nvoid BinningImageFilter\n::ThreadedGenerateData(const OutputImageRegionType& itkNotUsed(outputRegionForThread), ThreadIdType threadId )\n{\n\n int inputSize[2], binSize[2];\n inputSize[0] = this->GetInput()->GetLargestPossibleRegion().GetSize()[0];\n inputSize[1] = this->GetInput()->GetLargestPossibleRegion().GetSize()[1];\n binSize[0] = (inputSize[0]>>1);\n binSize[1] = (inputSize[1]>>1);\n\n typedef ImageType::PixelType inputPixel;\n typedef ImageType::PixelType outputPixel;\n\n \/\/this->GenerateOutputInformation();\n const inputPixel *bufferIn = this->GetInput()->GetBufferPointer();\n outputPixel *bufferOut = this->GetOutput()->GetBufferPointer();\n\n int initX = threadId*inputSize[0]*inputSize[1]\/(this->GetNumberOfThreads()*m_BinningFactors[0]);\n int endX = initX + binSize[0]*inputSize[1]\/this->GetNumberOfThreads();\n int initY = threadId*binSize[1]\/this->GetNumberOfThreads();\n int endY = initY + binSize[1]\/this->GetNumberOfThreads();\n\n \/\/ Binning 2x2\n if(m_BinningFactors[0]==2 && m_BinningFactors[1]==2)\n {\n const int Vlength = endX-initX;\n std::vector V(Vlength,0);\n\n int i, j, idx, pos, vj;\n for (i=0, idx=initX*m_BinningFactors[0]; i < Vlength; i++, idx+=2) \/\/ Only works if number of pixels per line multiple of 2\n {\n V[i] = ( (bufferIn[idx])+(bufferIn[idx+1]) );\n }\n for (j=initY, vj=0; j>2;\n }\n }\n }\n\n \/\/ Binning 2x1\n else if(m_BinningFactors[0]==2 && m_BinningFactors[1]==1)\n {\n int i, idx;\n for (i=initX, idx=initX*m_BinningFactors[0]; i < endX; i++, idx+=2) \/\/ Only works if number of pixels per line multiple of 2\n bufferOut[i] = ( (bufferIn[idx])+(bufferIn[idx+1]) )>>1;\n }\n\n \/\/ Binning 1x2\n else if(m_BinningFactors[0]==1 && m_BinningFactors[1]==2)\n {\n int i, j, pos;\n for (j=initY; j>1;\n }\n }\n else\n {\n itkExceptionMacro(<< \"Binning factors mismatch! Current factors: \"\n << m_BinningFactors[0] << \"x\"\n << m_BinningFactors[1] << \" \"\n << \"accepted modes [2x2] [2x1] and [1x2]\")\n }\n}\n\n} \/\/ end namespace rtk\n\n#endif \/\/ __rtkBinningImageFilter_cxx\nUse itk regions in binning\/*=========================================================================\n *\n * Copyright RTK Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#ifndef __rtkBinningImageFilter_cxx\n#define __rtkBinningImageFilter_cxx\n\n#include \n#include \n#include \n#include \n\n\nnamespace rtk\n{\n\nBinningImageFilter::BinningImageFilter()\n{\n m_BinningFactors[0]=2;\n m_BinningFactors[1]=2;\n}\n\nvoid BinningImageFilter::GenerateInputRequestedRegion()\n{\n ImageType::Pointer inputPtr = const_cast(this->GetInput());\n const ImageType::Pointer outputPtr = const_cast(this->GetOutput());\n\n ImageType::RegionType inputReqRegion = inputPtr->GetLargestPossibleRegion();\n const ImageType::RegionType outputReqRegion = outputPtr->GetRequestedRegion();\n const ImageType::RegionType outputLPRegion = outputPtr->GetLargestPossibleRegion();\n for (unsigned int i = 0; i < ImageType::ImageDimension; i++)\n {\n inputReqRegion.SetSize(i, outputReqRegion.GetSize(i) * m_BinningFactors[i]);\n inputReqRegion.SetIndex(i, inputReqRegion.GetIndex(i) +\n m_BinningFactors[i] * ( outputReqRegion.GetIndex(i) -\n outputLPRegion.GetIndex(i) ) );\n }\n inputPtr->SetRequestedRegion( inputReqRegion );\n}\n\nvoid BinningImageFilter::GenerateOutputInformation()\n{\n const ImageType::SpacingType& inputSpacing = this->GetInput()->GetSpacing();\n const ImageType::SizeType& inputSize = this->GetInput()->GetLargestPossibleRegion().GetSize();\n const ImageType::IndexType& inputStartIndex = this->GetInput()->GetLargestPossibleRegion().GetIndex();\n const ImageType::PointType& inputOrigin = this->GetInput()->GetOrigin();\n\n ImageType::SpacingType outputSpacing;\n ImageType::SizeType outputSize;\n ImageType::IndexType outputStartIndex;\n ImageType::PointType outputOrigin;\n\n for (unsigned int i = 0; i < ImageType::ImageDimension; i++)\n {\n outputSpacing[i] = inputSpacing[i] * m_BinningFactors[i];\n outputOrigin[i] = inputOrigin[i] - 0.5*inputSpacing[i] + 0.5*outputSpacing[i];\n if(inputSize[i]%m_BinningFactors[i] != 0)\n {\n itkExceptionMacro(<< \"Binning currently works only for integer divisions\")\n }\n else\n outputSize[i] = inputSize[i] \/ m_BinningFactors[i];\n\n outputStartIndex[i] = 0;\n }\n\n this->GetOutput()->SetSpacing( outputSpacing );\n this->GetOutput()->SetOrigin( outputOrigin );\n\n \/\/ Set region\n ImageType::RegionType outputLargestPossibleRegion;\n outputLargestPossibleRegion.SetSize( outputSize );\n outputLargestPossibleRegion.SetIndex( outputStartIndex );\n this->GetOutput()->SetLargestPossibleRegion( outputLargestPossibleRegion );\n}\n\nvoid BinningImageFilter\n::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, ThreadIdType itkNotUsed(threadId) )\n{\n const ImageType::PixelType *pIn = this->GetInput()->GetBufferPointer();\n ImageType::PixelType *pOut = this->GetOutput()->GetBufferPointer();\n\n \/\/ Move pointers to beginning of region\n ImageType::RegionType inputRegion;\n for(unsigned int i=0; iGetOutput()->GetOffsetTable()[i];\n pIn += outputRegionForThread.GetIndex(i) * this->GetInput() ->GetOffsetTable()[i] * m_BinningFactors[i];\n\n \/\/ Account for difference between buffered and largest possible regions\n pOut -= this->GetOutput()->GetOffsetTable()[i] *\n (this->GetOutput()->GetBufferedRegion().GetIndex()[i] -\n this->GetOutput()->GetLargestPossibleRegion().GetIndex()[i]);\n pIn -= this->GetInput()->GetOffsetTable()[i] *\n (this->GetInput()->GetBufferedRegion().GetIndex()[i] -\n this->GetInput()->GetLargestPossibleRegion().GetIndex()[i]);\n }\n\n \/\/ Binning 2x2\n if(m_BinningFactors[0]==2 && m_BinningFactors[1]==2)\n {\n const size_t buffSize = outputRegionForThread.GetNumberOfPixels()*2;\n int *buffer = new int[buffSize];\n for(unsigned int j=0; jGetInput()->GetOffsetTable()[1])\n for(unsigned int i=0; iGetOutput()->GetOffsetTable()[1],\n buffer += 2*outputRegionForThread.GetSize(0))\n for(unsigned int i=0; i> 2;\n\n buffer -= buffSize; \/\/ Back to original position\n delete buffer;\n }\n\n \/\/ Binning 2x1\n else if(m_BinningFactors[0]==2 && m_BinningFactors[1]==1)\n {\n for(unsigned int j=0; jGetInput()->GetOffsetTable()[1])\n for(unsigned int i=0; i>1;\n }\n\n \/\/ Binning 1x2\n else if(m_BinningFactors[0]==1 && m_BinningFactors[1]==2)\n {\n for(unsigned int j=0; jGetOutput()->GetOffsetTable()[1],\n pIn += 2*this->GetInput()->GetOffsetTable()[1])\n for(unsigned int i=0; iGetInput()->GetOffsetTable()[1]]) >> 1;\n }\n else\n {\n itkExceptionMacro(<< \"Binning factors mismatch! Current factors: \"\n << m_BinningFactors[0] << \"x\"\n << m_BinningFactors[1] << \" \"\n << \"accepted modes [2x2] [2x1] and [1x2]\")\n }\n}\n\n} \/\/ end namespace rtk\n\n#endif \/\/ __rtkBinningImageFilter_cxx\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace fpgui {\nnamespace chai {\n\nclass Chai_Impl\n{\n public:\n\n Chai_Impl(const char* chai_script):\n chai_script_(chai_script)\n {\n init();\n }\n\n ~Chai_Impl()\n {\n deinit();\n }\n\n int compare(const std::string& msg1, const std::string& msg2)\n {\n std::lock_guard lock(mutex_);\n compare_result_ = -3;\n\n std::string log_msg1_escaped(msg1);\n std::string log_msg2_escaped(msg2);\n\n fpgui::generic_util::escape_quotes(log_msg1_escaped);\n fpgui::generic_util::escape_quotes(log_msg2_escaped);\n\n std::string std_format(\"log_msg1=\\\"%s\\\";\\nfplog_message1 = from_json(log_msg1);\\nlog_msg2=\\\"%s\\\";\\nfplog_message2 = from_json(log_msg2);\\n\");\n\n retry_parsing:\n\n int chai_len = static_cast(log_msg1_escaped.length() + log_msg2_escaped.length() + 256);\n\n char* chai_script = new char[chai_len];\n memset(chai_script, 0, chai_len);\n std::auto_ptr chai_script_ptr(chai_script);\n#ifndef _LINUX\n _snprintf(chai_script, chai_len - 1, std_format.c_str(), log_msg1_escaped.c_str(), log_msg2_escaped.c_str());\n#else\n sprintf(chai_script, std_format.c_str(), log_msg1_escaped.c_str(), log_msg2_escaped.c_str());\n#endif\n std::string full_script(chai_script + chai_script_);\n\n try\n {\n chai_->eval(full_script);\n }\n catch (chaiscript::exception::eval_error&)\n {\n std_format = \"var log_msg1=\\\"%s\\\";\\nvar fplog_message1 = from_json(log_msg1);\\nvar log_msg2=\\\"%s\\\";\\nvar fplog_message2 = from_json(log_msg2);\\n\";\n goto retry_parsing;\n }\n catch (std::exception& e)\n {\n std::cout << e.what() << std::endl;\n std::cout << full_script << std::endl;\n }\n\n return compare_result_;\n }\n\n\n private:\n\n int compare_result_;\n std::recursive_mutex mutex_;\n chaiscript::ChaiScript* chai_;\n\n void init()\n {\n std::lock_guard lock(mutex_);\n\n chai_ = new chaiscript::ChaiScript(chaiscript::Std_Lib::library());\n chai_->add(chaiscript::var(std::ref(compare_result_)), \"compare_result\");\n chai_->add(chaiscript::fun(&generic_utils::date_time::iso_timestamp_to_ms), \"iso_timestamp_to_ms\");\n }\n\n void deinit()\n {\n std::lock_guard lock(mutex_);\n\n delete chai_;\n }\n\n std::string chai_script_;\n};\n\nstatic std::recursive_mutex g_chai_mutex;\nstatic std::auto_ptr g_chai;\n\nvoid load_from_file(const std::string& filename)\n{\n std::lock_guard lock(g_chai_mutex);\n\n std::ifstream infile(filename);\n std::string line, script;\n\n while (std::getline(infile, line))\n script += (line + \"\\n\");\n\n g_chai.reset(new Chai_Impl(script.c_str()));\n}\n\nint compare_json_strings(const std::string& json_str1, const std::string& json_str2)\n{\n if (!g_chai.get())\n return 0;\n\n return g_chai->compare(json_str1, json_str2);\n}\n\n}\n}\nMissed include.#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace fpgui {\nnamespace chai {\n\nclass Chai_Impl\n{\n public:\n\n Chai_Impl(const char* chai_script):\n chai_script_(chai_script)\n {\n init();\n }\n\n ~Chai_Impl()\n {\n deinit();\n }\n\n int compare(const std::string& msg1, const std::string& msg2)\n {\n std::lock_guard lock(mutex_);\n compare_result_ = -3;\n\n std::string log_msg1_escaped(msg1);\n std::string log_msg2_escaped(msg2);\n\n fpgui::generic_util::escape_quotes(log_msg1_escaped);\n fpgui::generic_util::escape_quotes(log_msg2_escaped);\n\n std::string std_format(\"log_msg1=\\\"%s\\\";\\nfplog_message1 = from_json(log_msg1);\\nlog_msg2=\\\"%s\\\";\\nfplog_message2 = from_json(log_msg2);\\n\");\n\n retry_parsing:\n\n int chai_len = static_cast(log_msg1_escaped.length() + log_msg2_escaped.length() + 256);\n\n char* chai_script = new char[chai_len];\n memset(chai_script, 0, chai_len);\n std::auto_ptr chai_script_ptr(chai_script);\n#ifndef _LINUX\n _snprintf(chai_script, chai_len - 1, std_format.c_str(), log_msg1_escaped.c_str(), log_msg2_escaped.c_str());\n#else\n sprintf(chai_script, std_format.c_str(), log_msg1_escaped.c_str(), log_msg2_escaped.c_str());\n#endif\n std::string full_script(chai_script + chai_script_);\n\n try\n {\n chai_->eval(full_script);\n }\n catch (chaiscript::exception::eval_error&)\n {\n std_format = \"var log_msg1=\\\"%s\\\";\\nvar fplog_message1 = from_json(log_msg1);\\nvar log_msg2=\\\"%s\\\";\\nvar fplog_message2 = from_json(log_msg2);\\n\";\n goto retry_parsing;\n }\n catch (std::exception& e)\n {\n std::cout << e.what() << std::endl;\n std::cout << full_script << std::endl;\n }\n\n return compare_result_;\n }\n\n\n private:\n\n int compare_result_;\n std::recursive_mutex mutex_;\n chaiscript::ChaiScript* chai_;\n\n void init()\n {\n std::lock_guard lock(mutex_);\n\n chai_ = new chaiscript::ChaiScript(chaiscript::Std_Lib::library());\n chai_->add(chaiscript::var(std::ref(compare_result_)), \"compare_result\");\n chai_->add(chaiscript::fun(&generic_utils::date_time::iso_timestamp_to_ms), \"iso_timestamp_to_ms\");\n }\n\n void deinit()\n {\n std::lock_guard lock(mutex_);\n\n delete chai_;\n }\n\n std::string chai_script_;\n};\n\nstatic std::recursive_mutex g_chai_mutex;\nstatic std::auto_ptr g_chai;\n\nvoid load_from_file(const std::string& filename)\n{\n std::lock_guard lock(g_chai_mutex);\n\n std::ifstream infile(filename);\n std::string line, script;\n\n while (std::getline(infile, line))\n script += (line + \"\\n\");\n\n g_chai.reset(new Chai_Impl(script.c_str()));\n}\n\nint compare_json_strings(const std::string& json_str1, const std::string& json_str2)\n{\n if (!g_chai.get())\n return 0;\n\n return g_chai->compare(json_str1, json_str2);\n}\n\n}\n}\n<|endoftext|>"} {"text":"swpagerelsize: fix RelativeHeightRelation UNO API<|endoftext|>"} {"text":"sal_uInt16 to more proper types, constify, avoid unneeded casts<|endoftext|>"} {"text":"\/*BEGIN_LEGAL \nIntel Open Source License \n\nCopyright (c) 2002-2013 Intel Corporation. All rights reserved.\n \nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\nRedistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer. Redistributions\nin binary form must reproduce the above copyright notice, this list of\nconditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution. Neither the name of\nthe Intel Corporation nor the names of its contributors may be used to\nendorse or promote products derived from this software without\nspecific prior written permission.\n \nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR\nITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nEND_LEGAL *\/\n#include \n#include \n#include \"pin.H\"\n\nofstream OutFile;\n\n\/\/ The running count of instructions is kept here\n\/\/ make it static to help the compiler optimize docount\nstatic UINT64 ccount = 0;\n\nstatic bool isMain = false;\n\n\nstatic VOID ImageLoad(IMG img, VOID * v)\n{\n\tcout << \"Loading \" << IMG_Name(img) << \", Image id = \" << IMG_Id(img) << endl;\n\tfor(SEC sec = IMG_SecHead(img); SEC_Valid(sec); sec = SEC_Next(sec)){\n\t\t\/\/cout << \"SEC: \" << SEC_Name(sec) << \", SEC size = \" << SEC_Size(sec) << endl;\n\t\tfor(RTN rtn = SEC_RtnHead(sec); RTN_Valid(rtn); rtn = RTN_Next(rtn)){\n\t\t\tcout << \"\\tRTN: \" << RTN_Name(rtn) << endl;\n\t\t}\n\t}\n\t\n\tRTN mainRtn = RTN_FindByName(img, \"_init\");\n if (RTN_Valid(mainRtn)){\n \tisMain = true;\n\t\tcout << \"main is valid\" << endl;\n\t}else{\n\t\tcout << \"main is invalid\" << endl;\n\t}\n}\n\n\/\/ This function is called before every instruction is executed\nVOID docount()\n{\n\tccount++;\n}\n \n\/\/ This function is called before every call instruction is executed\nVOID print_RETURN_IP(ADDRINT ret_ip)\n{\n\tOutFile << \"Return: 0x\" << hex << ret_ip << endl;\n\t\/*\t\n\tREGVAL regval;\n\tREG reg = (REG)REG_EIP;\n PIN_GetContextRegval(ctxt, reg, ®val);\n UINT64 val;\n PIN_ReadRegvalQWord(®val, &val, 0);\n OutFile << REG_StringShort(reg) << \": 0x\" << hex << val << endl;\n\t*\/\n}\n \n\/\/ This function is called before every return instruction is executed\nVOID printRet(const CONTEXT * ctxt)\n{\n\tREGVAL regval;\n\tREG reg = (REG)REG_EIP;\n PIN_GetContextRegval(ctxt, reg, ®val);\n UINT64 val;\n PIN_ReadRegvalQWord(®val, &val, 0);\n OutFile << REG_StringShort(reg) << \": 0x\" << hex << val << endl;\n}\n \n\/\/ Pin calls this function every time a call instruction is encountered\nVOID Instruction(INS ins, VOID *v)\n{\t\n\tif(!isMain) return;\n \/\/ Insert a call to docount before every call instruction, no arguments are passed\n\tif(INS_IsCall(ins)){\n \t\tINS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)docount, IARG_END);\n\t\tINS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)print_RETURN_IP, IARG_RETURN_IP, IARG_END);\t\n\t}\n\telse if(INS_IsRet(ins)){\n\t\tINS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)printRet, IARG_CONST_CONTEXT, IARG_END);\n\t}\n}\n\nKNOB KnobOutputFile(KNOB_MODE_WRITEONCE, \"pintool\",\n \"o\", \"maincallcount.out\", \"specify output file name\");\n\n\/\/ This function is called when the application exits\nVOID Fini(INT32 code, VOID *v)\n{\n \/\/ Write to a file since cout and cerr maybe closed by the application\n OutFile.setf(ios::showbase);\n OutFile << \"Count \" << dec << ccount << endl;\n OutFile.close();\n}\n\n\/* ===================================================================== *\/\n\/* Print Help Message *\/\n\/* ===================================================================== *\/\n\nINT32 Usage()\n{\n cerr << \"This tool counts the number of dynamic instructions executed\" << endl;\n cerr << endl << KNOB_BASE::StringKnobSummary() << endl;\n return -1;\n}\n\n\/* ===================================================================== *\/\n\/* Main *\/\n\/* ===================================================================== *\/\n\/* argc, argv are the entire command line: pin -t -- ... *\/\n\/* ===================================================================== *\/\n\nint main(int argc, char * argv[])\n{\n \/\/ Initialize pin\n if (PIN_Init(argc, argv)) return Usage();\n\n OutFile.open(KnobOutputFile.Value().c_str());\n\t\n\t\/\/ Instruction to start only at main\n\tIMG_AddInstrumentFunction(ImageLoad, 0);\n\n \/\/ Register Instruction to be called to instrument instructions\n INS_AddInstrumentFunction(Instruction, 0);\n\n \/\/ Register Fini to be called when the application exits\n PIN_AddFiniFunction(Fini, 0);\n \n \/\/ Start the program, never returns\n PIN_StartProgram();\n \n return 0;\n}\ncorrectly saves\/checks return address before call\/ret instructions\/*BEGIN_LEGAL \nIntel Open Source License \n\nCopyright (c) 2002-2013 Intel Corporation. All rights reserved.\n \nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\nRedistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer. Redistributions\nin binary form must reproduce the above copyright notice, this list of\nconditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution. Neither the name of\nthe Intel Corporation nor the names of its contributors may be used to\nendorse or promote products derived from this software without\nspecific prior written permission.\n \nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR\nITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nEND_LEGAL *\/\n#include \n#include \n#include \"pin.H\"\n\nofstream OutFile;\n\n\/\/ The running count of instructions is kept here\n\/\/ make it static to help the compiler optimize docount\nstatic UINT64 ccount = 0;\n\n\/\/ This function is called before every instruction is executed\nVOID docount()\n{\n\tccount++;\n}\n\nVOID saveCall(ADDRINT nextip)\n{\n\tOutFile << \"Return set: 0x\" << hex << nextip << endl;\n}\n\nVOID checkRet(ADDRINT *rsp, UINT32 framesize)\n{\n\tADDRINT retval;\n\n\tADDRINT rspval = *rsp;\n\tADDRINT *psp = (ADDRINT *)rspval;\n\tretval = *psp;\n\tOutFile << \"Return to: 0x\" << hex << retval << endl;\n}\n\n\/\/ Pin calls this function every time a call instruction is encountered\nVOID Instruction(INS ins, VOID *v)\n{\t\n\t\/\/ Insert a call to docount before every call instruction, no arguments are passed\n\tif (INS_IsCall(ins))\n\t{\t\n\t\tINS_InsertCall(ins, IPOINT_BEFORE,\n\t\t\t(AFUNPTR)docount,\n\t\t\tIARG_END);\n\t\tINS_InsertCall(ins, IPOINT_BEFORE,\n\t\t\tAFUNPTR(saveCall),\n\t\t\tIARG_ADDRINT, INS_NextAddress(ins),\n\t\t\tIARG_END);\n\t}\n\telse if (INS_IsRet(ins))\n\t{\n\t\tUINT64 imm = 0;\n\t\tif (INS_OperandCount(ins) > 0 && INS_OperandIsImmediate(ins, 0))\n\t\t\timm = INS_OperandImmediate(ins, 0);\n\n\t\tINS_InsertCall(ins, IPOINT_BEFORE,\n\t\t\tAFUNPTR(checkRet),\n\t\t\tIARG_CALL_ORDER, CALL_ORDER_FIRST,\n\t\t\tIARG_REG_REFERENCE, REG_STACK_PTR,\n\t\t\tIARG_ADDRINT, (ADDRINT)imm,\n\t\t\tIARG_END);\n\t}\n}\n\nKNOB KnobOutputFile(KNOB_MODE_WRITEONCE, \"pintool\",\n \"o\", \"callcount.out\", \"specify output file name\");\n\n\/\/ This function is called when the application exits\nVOID Fini(INT32 code, VOID *v)\n{\n \/\/ Write to a file since cout and cerr maybe closed by the application\n OutFile.setf(ios::showbase);\n OutFile << \"Count \" << dec << ccount << endl;\n OutFile.close();\n}\n\n\/* ===================================================================== *\/\n\/* Print Help Message *\/\n\/* ===================================================================== *\/\n\nINT32 Usage()\n{\n cerr << \"This tool counts the number of dynamic instructions executed\" << endl;\n cerr << endl << KNOB_BASE::StringKnobSummary() << endl;\n return -1;\n}\n\n\/* ===================================================================== *\/\n\/* Main *\/\n\/* ===================================================================== *\/\n\/* argc, argv are the entire command line: pin -t -- ... *\/\n\/* ===================================================================== *\/\n\nint main(int argc, char * argv[])\n{\n \/\/ Initialize pin\n if (PIN_Init(argc, argv)) return Usage();\n\n OutFile.open(KnobOutputFile.Value().c_str());\n\n \/\/ Register Instruction to be called to instrument instructions\n INS_AddInstrumentFunction(Instruction, 0);\n\n \/\/ Register Fini to be called when the application exits\n PIN_AddFiniFunction(Fini, 0);\n \n \/\/ Start the program, never returns\n PIN_StartProgram();\n \n return 0;\n}\n<|endoftext|>"} {"text":"#include \n\n#define DLL_EXPORT extern \"C\"\n\nstruct S {\n\tint n;\n\tuint8_t b;\n};\nclass C {\npublic:\n\tint n;\n\tuint8_t b;\n};\n\nDLL_EXPORT void Func0()\n{\n\tstd::cout << \"Native: \" << __PRETTY_FUNCTION__ << std::endl;\n}\n\nDLL_EXPORT void Func1(int n)\n{\n\tstd::cout << \"Native: \" << __PRETTY_FUNCTION__ << std::endl;\n\tstd::cout << \" n = \" << n << std::endl;\n\tn = 456;\n\tstd::cout << \" => \" << n << std::endl;\n}\n\nDLL_EXPORT void Func2(int *p)\n{\n\tstd::cout << \"Native: \" << __PRETTY_FUNCTION__ << std::endl;\n\tstd::cout << \" p = \" << p << std::endl;\n\tstd::cout << \" *p = \" << *p << std::endl;\n\tif (p != nullptr) {\n\t\t*p = 456;\n\t\tstd::cout << \" => \" << *p << std::endl;\n\t}\n}\n\nDLL_EXPORT void Func3(int *p)\n{\n\tstd::cout << \"Native: \" << __PRETTY_FUNCTION__ << std::endl;\n\tstd::cout << \" p = \" << p << std::endl;\n\tstd::cout << \" *p = \" << *p << std::endl;\n\tif (p != nullptr) {\n\t\t*p = 456;\n\t\tstd::cout << \" => \" << *p << std::endl;\n\t}\n}\n\nDLL_EXPORT void Func4(int n)\n{\n\tstd::cout << \"Native: \" << __PRETTY_FUNCTION__ << std::endl;\n\tstd::cout << \" n = \" << n << std::endl;\n\tn = 456;\n\tstd::cout << \" => \" << n << std::endl;\n}\n\nDLL_EXPORT void Func5(int *p)\n{\n\tstd::cout << \"Native: \" << __PRETTY_FUNCTION__ << std::endl;\n\tstd::cout << \" p = \" << p << std::endl;\n\tstd::cout << \" *p = \" << *p << std::endl;\n\tif (p != nullptr) {\n\t\t*p = 456;\n\t\tstd::cout << \" => \" << *p << std::endl;\n\t}\n}\n\nDLL_EXPORT void Func6(S s)\n{\n\tstd::cout << \"Native: \" << __PRETTY_FUNCTION__ << std::endl;\n\tstd::cout << \" s.n = \" << s.n << std::endl;\n\ts.n = 456;\n\tstd::cout << \" => \" << s.n << std::endl;\n}\n\nDLL_EXPORT void Func7(S *p)\n{\n\tstd::cout << \"Native: \" << __PRETTY_FUNCTION__ << std::endl;\n\tstd::cout << \" p = \" << p << std::endl;\n\tif (p != nullptr) {\n\t\tstd::cout << \" p->n = \" << p->n << std::endl;\n\t\tp->n = 456;\n\t\tstd::cout << \" => \" << p->n << std::endl;\n\t}\n}\n\nDLL_EXPORT void Func8(S *p)\n{\n\tstd::cout << \"Native: \" << __PRETTY_FUNCTION__ << std::endl;\n\tstd::cout << \" p = \" << p << std::endl;\n\tif (p != nullptr) {\n\t\tstd::cout << \" p->n = \" << p->n << std::endl;\n\t\tp->n = 456;\n\t\tstd::cout << \" => \" << p->n << std::endl;\n\t}\n}\n\nDLL_EXPORT void Func9(S s)\n{\n\tstd::cout << \"Native: \" << __PRETTY_FUNCTION__ << std::endl;\n\tstd::cout << \" s.n = \" << s.n << std::endl;\n\ts.n = 456;\n\tstd::cout << \" => \" << s.n << std::endl;\n}\n\nDLL_EXPORT void Func10(S *p)\n{\n\tstd::cout << \"Native: \" << __PRETTY_FUNCTION__ << std::endl;\n\tstd::cout << \" p = \" << p << std::endl;\n\tif (p != nullptr) {\n\t\tstd::cout << \" p->n = \" << p->n << std::endl;\n\t\tp->n = 678;\n\t\tstd::cout << \" => \" << p->n << std::endl;\n\t\tstd::cout << \" p->b = \" << (int)p->b << std::endl;\n\t\tp->b = 90;\n\t\tstd::cout << \" => \" << (int)p->b << std::endl;\n\t}\n}\n\nDLL_EXPORT void Func11(C *p)\n{\n\tstd::cout << \"Native: \" << __PRETTY_FUNCTION__ << std::endl;\n\tstd::cout << \" p = \" << p << std::endl;\n\tif (p != nullptr) {\n\t\tstd::cout << \" p->n = \" << p->n << std::endl;\n\t\tp->n = 678;\n\t\tstd::cout << \" => \" << p->n << std::endl;\n\t\tstd::cout << \" p->b = \" << (int)p->b << std::endl;\n\t\tp->b = 90;\n\t\tstd::cout << \" => \" << (int)p->b << std::endl;\n\t}\n}\n\nDLL_EXPORT void Func12(C **pp)\n{\n\tstd::cout << \"Native: \" << __PRETTY_FUNCTION__ << std::endl;\n\tstd::cout << \" pp = \" << pp << std::endl;\n\tif (pp != nullptr) {\n\t\tC *p = *pp;\n\t\tstd::cout << \" p = \" << p << std::endl;\n\t\tif (p != nullptr) {\n\t\t\tstd::cout << \" p->n = \" << p->n << std::endl;\n\t\t\tp->n = 678;\n\t\t\tstd::cout << \" => \" << p->n << std::endl;\n\t\t\tstd::cout << \" p->b = \" << (int)p->b << std::endl;\n\t\t\tp->b = 90;\n\t\t\tstd::cout << \" => \" << (int)p->b << std::endl;\n\t\t}\n\t}\n}\n\n\/\/ Local variables:\n\/\/ mode: c++\n\/\/ coding: utf-8-with-signature\n\/\/ c-file-style: \"bsd\"\n\/\/ c-basic-offset: 4\n\/\/ c-file-offsets: ((inextern-lang . 0)(innamespace . 0))\n\/\/ indent-tabs-mode: t\n\/\/ tab-width: 4\n\/\/ End:\nVisual Studio 2012でビルドできるように変更しました。#include \n#include \n\n#if defined(_MSC_VER)\n#define DLL_EXPORT extern \"C\" _declspec(dllexport)\n#else\n#define DLL_EXPORT extern \"C\"\n#endif\n\nstruct S {\n\tint n;\n\tuint8_t b;\n};\nclass C {\npublic:\n\tint n;\n\tuint8_t b;\n};\n\nDLL_EXPORT void Func0()\n{\n\tstd::cout << \"Native: \" << __FUNCTION__ << std::endl;\n}\n\nDLL_EXPORT void Func1(int n)\n{\n\tstd::cout << \"Native: \" << __FUNCTION__ << std::endl;\n\tstd::cout << \" n = \" << n << std::endl;\n\tn = 456;\n\tstd::cout << \" => \" << n << std::endl;\n}\n\nDLL_EXPORT void Func2(int *p)\n{\n\tstd::cout << \"Native: \" << __FUNCTION__ << std::endl;\n\tstd::cout << \" p = \" << p << std::endl;\n\tstd::cout << \" *p = \" << *p << std::endl;\n\tif (p != nullptr) {\n\t\t*p = 456;\n\t\tstd::cout << \" => \" << *p << std::endl;\n\t}\n}\n\nDLL_EXPORT void Func3(int *p)\n{\n\tstd::cout << \"Native: \" << __FUNCTION__ << std::endl;\n\tstd::cout << \" p = \" << p << std::endl;\n\tstd::cout << \" *p = \" << *p << std::endl;\n\tif (p != nullptr) {\n\t\t*p = 456;\n\t\tstd::cout << \" => \" << *p << std::endl;\n\t}\n}\n\nDLL_EXPORT void Func4(int n)\n{\n\tstd::cout << \"Native: \" << __FUNCTION__ << std::endl;\n\tstd::cout << \" n = \" << n << std::endl;\n\tn = 456;\n\tstd::cout << \" => \" << n << std::endl;\n}\n\nDLL_EXPORT void Func5(int *p)\n{\n\tstd::cout << \"Native: \" << __FUNCTION__ << std::endl;\n\tstd::cout << \" p = \" << p << std::endl;\n\tstd::cout << \" *p = \" << *p << std::endl;\n\tif (p != nullptr) {\n\t\t*p = 456;\n\t\tstd::cout << \" => \" << *p << std::endl;\n\t}\n}\n\nDLL_EXPORT void Func6(S s)\n{\n\tstd::cout << \"Native: \" << __FUNCTION__ << std::endl;\n\tstd::cout << \" s.n = \" << s.n << std::endl;\n\ts.n = 456;\n\tstd::cout << \" => \" << s.n << std::endl;\n}\n\nDLL_EXPORT void Func7(S *p)\n{\n\tstd::cout << \"Native: \" << __FUNCTION__ << std::endl;\n\tstd::cout << \" p = \" << p << std::endl;\n\tif (p != nullptr) {\n\t\tstd::cout << \" p->n = \" << p->n << std::endl;\n\t\tp->n = 456;\n\t\tstd::cout << \" => \" << p->n << std::endl;\n\t}\n}\n\nDLL_EXPORT void Func8(S *p)\n{\n\tstd::cout << \"Native: \" << __FUNCTION__ << std::endl;\n\tstd::cout << \" p = \" << p << std::endl;\n\tif (p != nullptr) {\n\t\tstd::cout << \" p->n = \" << p->n << std::endl;\n\t\tp->n = 456;\n\t\tstd::cout << \" => \" << p->n << std::endl;\n\t}\n}\n\nDLL_EXPORT void Func9(S s)\n{\n\tstd::cout << \"Native: \" << __FUNCTION__ << std::endl;\n\tstd::cout << \" s.n = \" << s.n << std::endl;\n\ts.n = 456;\n\tstd::cout << \" => \" << s.n << std::endl;\n}\n\nDLL_EXPORT void Func10(S *p)\n{\n\tstd::cout << \"Native: \" << __FUNCTION__ << std::endl;\n\tstd::cout << \" p = \" << p << std::endl;\n\tif (p != nullptr) {\n\t\tstd::cout << \" p->n = \" << p->n << std::endl;\n\t\tp->n = 678;\n\t\tstd::cout << \" => \" << p->n << std::endl;\n\t\tstd::cout << \" p->b = \" << (int)p->b << std::endl;\n\t\tp->b = 90;\n\t\tstd::cout << \" => \" << (int)p->b << std::endl;\n\t}\n}\n\nDLL_EXPORT void Func11(C *p)\n{\n\tstd::cout << \"Native: \" << __FUNCTION__ << std::endl;\n\tstd::cout << \" p = \" << p << std::endl;\n\tif (p != nullptr) {\n\t\tstd::cout << \" p->n = \" << p->n << std::endl;\n\t\tp->n = 678;\n\t\tstd::cout << \" => \" << p->n << std::endl;\n\t\tstd::cout << \" p->b = \" << (int)p->b << std::endl;\n\t\tp->b = 90;\n\t\tstd::cout << \" => \" << (int)p->b << std::endl;\n\t}\n}\n\nDLL_EXPORT void Func12(C **pp)\n{\n\tstd::cout << \"Native: \" << __FUNCTION__ << std::endl;\n\tstd::cout << \" pp = \" << pp << std::endl;\n\tif (pp != nullptr) {\n\t\tC *p = *pp;\n\t\tstd::cout << \" p = \" << p << std::endl;\n\t\tif (p != nullptr) {\n\t\t\tstd::cout << \" p->n = \" << p->n << std::endl;\n\t\t\tp->n = 678;\n\t\t\tstd::cout << \" => \" << p->n << std::endl;\n\t\t\tstd::cout << \" p->b = \" << (int)p->b << std::endl;\n\t\t\tp->b = 90;\n\t\t\tstd::cout << \" => \" << (int)p->b << std::endl;\n\t\t}\n\t}\n}\n\n\/\/ Local variables:\n\/\/ mode: c++\n\/\/ coding: utf-8-with-signature\n\/\/ c-file-style: \"bsd\"\n\/\/ c-basic-offset: 4\n\/\/ c-file-offsets: ((inextern-lang . 0)(innamespace . 0))\n\/\/ indent-tabs-mode: t\n\/\/ tab-width: 4\n\/\/ End:\n<|endoftext|>"} {"text":"#include \"SlidingWindow.h\"\n#include \"IRMutator.h\"\n#include \"IROperator.h\"\n#include \"Scope.h\"\n#include \"Debug.h\"\n#include \"Substitute.h\"\n#include \"IRPrinter.h\"\n#include \"Simplify.h\"\n#include \"Monotonic.h\"\n#include \"Bounds.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::string;\nusing std::map;\n\nnamespace {\n\n\/\/ Does an expression depend on a particular variable?\nclass ExprDependsOnVar : public IRVisitor {\n using IRVisitor::visit;\n\n void visit(const Variable *op) {\n if (op->name == var) result = true;\n }\n\n void visit(const Let *op) {\n op->value.accept(this);\n \/\/ The name might be hidden within the body of the let, in\n \/\/ which case there's no point descending.\n if (op->name != var) {\n op->body.accept(this);\n }\n }\npublic:\n\n bool result;\n string var;\n\n ExprDependsOnVar(string v) : result(false), var(v) {\n }\n};\n\nbool expr_depends_on_var(Expr e, string v) {\n ExprDependsOnVar depends(v);\n e.accept(&depends);\n return depends.result;\n}\n\n\nclass ExpandExpr : public IRMutator {\n using IRMutator::visit;\n const Scope &scope;\n\n void visit(const Variable *var) {\n if (scope.contains(var->name)) {\n expr = scope.get(var->name);\n debug(3) << \"Fully expanded \" << var->name << \" -> \" << expr << \"\\n\";\n } else {\n expr = var;\n }\n }\n\npublic:\n ExpandExpr(const Scope &s) : scope(s) {}\n\n};\n\n\/\/ Perform all the substitutions in a scope\nExpr expand_expr(Expr e, const Scope &scope) {\n ExpandExpr ee(scope);\n Expr result = ee.mutate(e);\n debug(3) << \"Expanded \" << e << \" into \" << result << \"\\n\";\n return result;\n}\n\n}\n\n\/\/ Perform sliding window optimization for a function over a\n\/\/ particular serial for loop\nclass SlidingWindowOnFunctionAndLoop : public IRMutator {\n Function func;\n string loop_var;\n Expr loop_min;\n Scope scope;\n\n map replacements;\n\n using IRMutator::visit;\n\n \/\/ Check if the dimension at index 'dim_idx' is always pure (i.e. equal to 'dim')\n \/\/ in the definition (including in its specializations)\n bool is_dim_always_pure(const Definition &def, const string& dim, int dim_idx) {\n const Variable *var = def.args()[dim_idx].as();\n if ((!var) || (var->name != dim)) {\n return false;\n }\n\n for (const auto &s : def.specializations()) {\n bool pure = is_dim_always_pure(s.definition, dim, dim_idx);\n if (!pure) {\n return false;\n }\n }\n return true;\n }\n\n void visit(const ProducerConsumer *op) {\n if (op->name != func.name()) {\n IRMutator::visit(op);\n } else {\n\n stmt = op;\n\n \/\/ We're interested in the case where exactly one of the\n \/\/ dimensions of the buffer has a min\/extent that depends\n \/\/ on the loop_var.\n string dim = \"\";\n int dim_idx = 0;\n Expr min_required, max_required;\n\n debug(3) << \"Considering sliding \" << func.name()\n << \" along loop variable \" << loop_var << \"\\n\"\n << \"Region provided:\\n\";\n\n string prefix = func.name() + \".s\" + std::to_string(func.updates().size()) + \".\";\n const std::vector func_args = func.args();\n for (int i = 0; i < func.dimensions(); i++) {\n \/\/ Look up the region required of this function's last stage\n string var = prefix + func_args[i];\n internal_assert(scope.contains(var + \".min\") && scope.contains(var + \".max\"));\n Expr min_req = scope.get(var + \".min\");\n Expr max_req = scope.get(var + \".max\");\n min_req = expand_expr(min_req, scope);\n max_req = expand_expr(max_req, scope);\n\n debug(3) << func_args[i] << \":\" << min_req << \", \" << max_req << \"\\n\";\n if (expr_depends_on_var(min_req, loop_var) ||\n expr_depends_on_var(max_req, loop_var)) {\n if (!dim.empty()) {\n dim = \"\";\n min_required = Expr();\n max_required = Expr();\n break;\n } else {\n dim = func_args[i];\n dim_idx = i;\n min_required = min_req;\n max_required = max_req;\n }\n }\n }\n\n if (!min_required.defined()) {\n debug(3) << \"Could not perform sliding window optimization of \"\n << func.name() << \" over \" << loop_var << \" because either zero \"\n << \"or many dimensions of the function dependended on the loop var\\n\";\n return;\n }\n\n \/\/ If the function is not pure in the given dimension, give up. We also\n \/\/ need to make sure that it is pure in all the specializations\n bool pure = true;\n for (const Definition &def : func.updates()) {\n pure = is_dim_always_pure(def, dim, dim_idx);\n if (!pure) {\n break;\n }\n }\n if (!pure) {\n debug(3) << \"Could not performance sliding window optimization of \"\n << func.name() << \" over \" << loop_var << \" because the function \"\n << \"scatters along the related axis.\\n\";\n return;\n }\n\n bool can_slide_up = false;\n bool can_slide_down = false;\n\n Monotonic monotonic_min = is_monotonic(min_required, loop_var);\n Monotonic monotonic_max = is_monotonic(max_required, loop_var);\n\n if (monotonic_min == Monotonic::Increasing ||\n monotonic_min == Monotonic::Constant) {\n can_slide_up = true;\n }\n\n if (monotonic_max == Monotonic::Decreasing ||\n monotonic_max == Monotonic::Constant) {\n can_slide_down = true;\n }\n\n if (!can_slide_up && !can_slide_down) {\n debug(3) << \"Not sliding \" << func.name()\n << \" over dimension \" << dim\n << \" along loop variable \" << loop_var\n << \" because I couldn't prove it moved monotonically along that dimension\\n\"\n << \"Min is \" << min_required << \"\\n\"\n << \"Max is \" << max_required << \"\\n\";\n return;\n }\n\n \/\/ Ok, we've isolated a function, a dimension to slide\n \/\/ along, and loop variable to slide over.\n debug(3) << \"Sliding \" << func.name()\n << \" over dimension \" << dim\n << \" along loop variable \" << loop_var << \"\\n\";\n\n Expr loop_var_expr = Variable::make(Int(32), loop_var);\n\n Expr prev_max_plus_one = substitute(loop_var, loop_var_expr - 1, max_required) + 1;\n Expr prev_min_minus_one = substitute(loop_var, loop_var_expr - 1, min_required) - 1;\n\n \/\/ If there's no overlap between adjacent iterations, we shouldn't slide.\n if (can_prove(min_required >= prev_max_plus_one) ||\n can_prove(max_required <= prev_min_minus_one)) {\n debug(3) << \"Not sliding \" << func.name()\n << \" over dimension \" << dim\n << \" along loop variable \" << loop_var\n << \" there's no overlap in the region computed across iterations\\n\"\n << \"Min is \" << min_required << \"\\n\"\n << \"Max is \" << max_required << \"\\n\";\n return;\n }\n\n Expr new_min, new_max;\n if (can_slide_up) {\n new_min = select(loop_var_expr <= loop_min, min_required, likely(prev_max_plus_one));\n new_max = max_required;\n } else {\n new_min = min_required;\n new_max = select(loop_var_expr <= loop_min, max_required, likely(prev_min_minus_one));\n }\n\n Expr early_stages_min_required = new_min;\n Expr early_stages_max_required = new_max;\n\n debug(3) << \"Sliding \" << func.name() << \", \" << dim << \"\\n\"\n << \"Pushing min up from \" << min_required << \" to \" << new_min << \"\\n\"\n << \"Shrinking max from \" << max_required << \" to \" << new_max << \"\\n\";\n\n \/\/ Now redefine the appropriate regions required\n if (can_slide_up) {\n replacements[prefix + dim + \".min\"] = new_min;\n } else {\n replacements[prefix + dim + \".max\"] = new_max;\n }\n\n for (size_t i = 0; i < func.updates().size(); i++) {\n string n = func.name() + \".s\" + std::to_string(i) + \".\" + dim;\n replacements[n + \".min\"] = Variable::make(Int(32), prefix + dim + \".min\");\n replacements[n + \".max\"] = Variable::make(Int(32), prefix + dim + \".max\");\n }\n\n \/\/ Ok, we have a new min\/max required and we're going to\n \/\/ rewrite all the lets that define bounds required. Now\n \/\/ we need to additionally expand the bounds required of\n \/\/ the last stage to cover values produced by stages\n \/\/ before the last one. Because, e.g., an intermediate\n \/\/ stage may be unrolled, expanding its bounds provided.\n if (op->update.defined()) {\n Box b = box_provided(op->produce, func.name());\n merge_boxes(b, box_provided(op->update, func.name()));\n if (can_slide_up) {\n string n = prefix + dim + \".min\";\n Expr var = Variable::make(Int(32), n);\n stmt = LetStmt::make(n, min(var, b[dim_idx].min), stmt);\n } else {\n string n = prefix + dim + \".max\";\n Expr var = Variable::make(Int(32), n);\n stmt = LetStmt::make(n, max(var, b[dim_idx].max), stmt);\n }\n }\n\n\n }\n }\n\n void visit(const For *op) {\n \/\/ It's not safe to enter an inner loop whose bounds depend on\n \/\/ the var we're sliding over.\n Expr min = expand_expr(op->min, scope);\n Expr extent = expand_expr(op->extent, scope);\n if (is_one(extent)) {\n \/\/ Just treat it like a let\n Stmt s = LetStmt::make(op->name, min, op->body);\n s = mutate(s);\n \/\/ Unpack it back into the for\n const LetStmt *l = s.as();\n internal_assert(l);\n stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, l->body);\n } else if (is_monotonic(min, loop_var) != Monotonic::Constant ||\n is_monotonic(extent, loop_var) != Monotonic::Constant) {\n debug(3) << \"Not entering loop over \" << op->name\n << \" because the bounds depend on the var we're sliding over: \"\n << min << \", \" << extent << \"\\n\";\n stmt = op;\n } else {\n IRMutator::visit(op);\n\n }\n }\n\n void visit(const LetStmt *op) {\n scope.push(op->name, simplify(expand_expr(op->value, scope)));\n Stmt new_body = mutate(op->body);\n\n Expr value = op->value;\n\n map::iterator iter = replacements.find(op->name);\n if (iter != replacements.end()) {\n value = iter->second;\n replacements.erase(iter);\n }\n\n if (new_body.same_as(op->body) && value.same_as(op->value)) {\n stmt = op;\n } else {\n stmt = LetStmt::make(op->name, value, new_body);\n }\n scope.pop(op->name);\n }\n\npublic:\n SlidingWindowOnFunctionAndLoop(Function f, string v, Expr v_min) : func(f), loop_var(v), loop_min(v_min) {}\n};\n\n\/\/ Perform sliding window optimization for a particular function\nclass SlidingWindowOnFunction : public IRMutator {\n Function func;\n\n\n using IRMutator::visit;\n\n void visit(const For *op) {\n debug(3) << \" Doing sliding window analysis over loop: \" << op->name << \"\\n\";\n\n Stmt new_body = op->body;\n\n new_body = mutate(new_body);\n\n if (op->for_type == ForType::Serial ||\n op->for_type == ForType::Unrolled) {\n new_body = SlidingWindowOnFunctionAndLoop(func, op->name, op->min).mutate(new_body);\n }\n\n if (new_body.same_as(op->body)) {\n stmt = op;\n } else {\n stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, new_body);\n }\n }\n\npublic:\n SlidingWindowOnFunction(Function f) : func(f) {}\n};\n\n\/\/ Perform sliding window optimization for all functions\nclass SlidingWindow : public IRMutator {\n const map &env;\n\n using IRMutator::visit;\n\n void visit(const Realize *op) {\n \/\/ Find the args for this function\n map::const_iterator iter = env.find(op->name);\n\n \/\/ If it's not in the environment it's some anonymous\n \/\/ realization that we should skip (e.g. an inlined reduction)\n if (iter == env.end()) {\n IRMutator::visit(op);\n return;\n }\n\n \/\/ If the Function in question has the same compute_at level\n \/\/ as its store_at level, skip it.\n const Schedule &sched = iter->second.schedule();\n if (sched.compute_level() == sched.store_level()) {\n IRMutator::visit(op);\n return;\n }\n\n Stmt new_body = op->body;\n\n debug(3) << \"Doing sliding window analysis on realization of \" << op->name << \"\\n\";\n\n new_body = SlidingWindowOnFunction(iter->second).mutate(new_body);\n\n new_body = mutate(new_body);\n\n if (new_body.same_as(op->body)) {\n stmt = op;\n } else {\n stmt = Realize::make(op->name, op->types, op->bounds, op->condition, new_body);\n }\n }\npublic:\n SlidingWindow(const map &e) : env(e) {}\n\n};\n\nStmt sliding_window(Stmt s, const map &env) {\n return SlidingWindow(env).mutate(s);\n}\n\n}\n}\nUse likely_if_innermost for sliding window warmup branch.#include \"SlidingWindow.h\"\n#include \"IRMutator.h\"\n#include \"IROperator.h\"\n#include \"Scope.h\"\n#include \"Debug.h\"\n#include \"Substitute.h\"\n#include \"IRPrinter.h\"\n#include \"Simplify.h\"\n#include \"Monotonic.h\"\n#include \"Bounds.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::string;\nusing std::map;\n\nnamespace {\n\n\/\/ Does an expression depend on a particular variable?\nclass ExprDependsOnVar : public IRVisitor {\n using IRVisitor::visit;\n\n void visit(const Variable *op) {\n if (op->name == var) result = true;\n }\n\n void visit(const Let *op) {\n op->value.accept(this);\n \/\/ The name might be hidden within the body of the let, in\n \/\/ which case there's no point descending.\n if (op->name != var) {\n op->body.accept(this);\n }\n }\npublic:\n\n bool result;\n string var;\n\n ExprDependsOnVar(string v) : result(false), var(v) {\n }\n};\n\nbool expr_depends_on_var(Expr e, string v) {\n ExprDependsOnVar depends(v);\n e.accept(&depends);\n return depends.result;\n}\n\n\nclass ExpandExpr : public IRMutator {\n using IRMutator::visit;\n const Scope &scope;\n\n void visit(const Variable *var) {\n if (scope.contains(var->name)) {\n expr = scope.get(var->name);\n debug(3) << \"Fully expanded \" << var->name << \" -> \" << expr << \"\\n\";\n } else {\n expr = var;\n }\n }\n\npublic:\n ExpandExpr(const Scope &s) : scope(s) {}\n\n};\n\n\/\/ Perform all the substitutions in a scope\nExpr expand_expr(Expr e, const Scope &scope) {\n ExpandExpr ee(scope);\n Expr result = ee.mutate(e);\n debug(3) << \"Expanded \" << e << \" into \" << result << \"\\n\";\n return result;\n}\n\n}\n\n\/\/ Perform sliding window optimization for a function over a\n\/\/ particular serial for loop\nclass SlidingWindowOnFunctionAndLoop : public IRMutator {\n Function func;\n string loop_var;\n Expr loop_min;\n Scope scope;\n\n map replacements;\n\n using IRMutator::visit;\n\n \/\/ Check if the dimension at index 'dim_idx' is always pure (i.e. equal to 'dim')\n \/\/ in the definition (including in its specializations)\n bool is_dim_always_pure(const Definition &def, const string& dim, int dim_idx) {\n const Variable *var = def.args()[dim_idx].as();\n if ((!var) || (var->name != dim)) {\n return false;\n }\n\n for (const auto &s : def.specializations()) {\n bool pure = is_dim_always_pure(s.definition, dim, dim_idx);\n if (!pure) {\n return false;\n }\n }\n return true;\n }\n\n void visit(const ProducerConsumer *op) {\n if (op->name != func.name()) {\n IRMutator::visit(op);\n } else {\n\n stmt = op;\n\n \/\/ We're interested in the case where exactly one of the\n \/\/ dimensions of the buffer has a min\/extent that depends\n \/\/ on the loop_var.\n string dim = \"\";\n int dim_idx = 0;\n Expr min_required, max_required;\n\n debug(3) << \"Considering sliding \" << func.name()\n << \" along loop variable \" << loop_var << \"\\n\"\n << \"Region provided:\\n\";\n\n string prefix = func.name() + \".s\" + std::to_string(func.updates().size()) + \".\";\n const std::vector func_args = func.args();\n for (int i = 0; i < func.dimensions(); i++) {\n \/\/ Look up the region required of this function's last stage\n string var = prefix + func_args[i];\n internal_assert(scope.contains(var + \".min\") && scope.contains(var + \".max\"));\n Expr min_req = scope.get(var + \".min\");\n Expr max_req = scope.get(var + \".max\");\n min_req = expand_expr(min_req, scope);\n max_req = expand_expr(max_req, scope);\n\n debug(3) << func_args[i] << \":\" << min_req << \", \" << max_req << \"\\n\";\n if (expr_depends_on_var(min_req, loop_var) ||\n expr_depends_on_var(max_req, loop_var)) {\n if (!dim.empty()) {\n dim = \"\";\n min_required = Expr();\n max_required = Expr();\n break;\n } else {\n dim = func_args[i];\n dim_idx = i;\n min_required = min_req;\n max_required = max_req;\n }\n }\n }\n\n if (!min_required.defined()) {\n debug(3) << \"Could not perform sliding window optimization of \"\n << func.name() << \" over \" << loop_var << \" because either zero \"\n << \"or many dimensions of the function dependended on the loop var\\n\";\n return;\n }\n\n \/\/ If the function is not pure in the given dimension, give up. We also\n \/\/ need to make sure that it is pure in all the specializations\n bool pure = true;\n for (const Definition &def : func.updates()) {\n pure = is_dim_always_pure(def, dim, dim_idx);\n if (!pure) {\n break;\n }\n }\n if (!pure) {\n debug(3) << \"Could not performance sliding window optimization of \"\n << func.name() << \" over \" << loop_var << \" because the function \"\n << \"scatters along the related axis.\\n\";\n return;\n }\n\n bool can_slide_up = false;\n bool can_slide_down = false;\n\n Monotonic monotonic_min = is_monotonic(min_required, loop_var);\n Monotonic monotonic_max = is_monotonic(max_required, loop_var);\n\n if (monotonic_min == Monotonic::Increasing ||\n monotonic_min == Monotonic::Constant) {\n can_slide_up = true;\n }\n\n if (monotonic_max == Monotonic::Decreasing ||\n monotonic_max == Monotonic::Constant) {\n can_slide_down = true;\n }\n\n if (!can_slide_up && !can_slide_down) {\n debug(3) << \"Not sliding \" << func.name()\n << \" over dimension \" << dim\n << \" along loop variable \" << loop_var\n << \" because I couldn't prove it moved monotonically along that dimension\\n\"\n << \"Min is \" << min_required << \"\\n\"\n << \"Max is \" << max_required << \"\\n\";\n return;\n }\n\n \/\/ Ok, we've isolated a function, a dimension to slide\n \/\/ along, and loop variable to slide over.\n debug(3) << \"Sliding \" << func.name()\n << \" over dimension \" << dim\n << \" along loop variable \" << loop_var << \"\\n\";\n\n Expr loop_var_expr = Variable::make(Int(32), loop_var);\n\n Expr prev_max_plus_one = substitute(loop_var, loop_var_expr - 1, max_required) + 1;\n Expr prev_min_minus_one = substitute(loop_var, loop_var_expr - 1, min_required) - 1;\n\n \/\/ If there's no overlap between adjacent iterations, we shouldn't slide.\n if (can_prove(min_required >= prev_max_plus_one) ||\n can_prove(max_required <= prev_min_minus_one)) {\n debug(3) << \"Not sliding \" << func.name()\n << \" over dimension \" << dim\n << \" along loop variable \" << loop_var\n << \" there's no overlap in the region computed across iterations\\n\"\n << \"Min is \" << min_required << \"\\n\"\n << \"Max is \" << max_required << \"\\n\";\n return;\n }\n\n Expr new_min, new_max;\n if (can_slide_up) {\n new_min = select(loop_var_expr <= loop_min, min_required, likely_if_innermost(prev_max_plus_one));\n new_max = max_required;\n } else {\n new_min = min_required;\n new_max = select(loop_var_expr <= loop_min, max_required, likely_if_innermost(prev_min_minus_one));\n }\n\n Expr early_stages_min_required = new_min;\n Expr early_stages_max_required = new_max;\n\n debug(3) << \"Sliding \" << func.name() << \", \" << dim << \"\\n\"\n << \"Pushing min up from \" << min_required << \" to \" << new_min << \"\\n\"\n << \"Shrinking max from \" << max_required << \" to \" << new_max << \"\\n\";\n\n \/\/ Now redefine the appropriate regions required\n if (can_slide_up) {\n replacements[prefix + dim + \".min\"] = new_min;\n } else {\n replacements[prefix + dim + \".max\"] = new_max;\n }\n\n for (size_t i = 0; i < func.updates().size(); i++) {\n string n = func.name() + \".s\" + std::to_string(i) + \".\" + dim;\n replacements[n + \".min\"] = Variable::make(Int(32), prefix + dim + \".min\");\n replacements[n + \".max\"] = Variable::make(Int(32), prefix + dim + \".max\");\n }\n\n \/\/ Ok, we have a new min\/max required and we're going to\n \/\/ rewrite all the lets that define bounds required. Now\n \/\/ we need to additionally expand the bounds required of\n \/\/ the last stage to cover values produced by stages\n \/\/ before the last one. Because, e.g., an intermediate\n \/\/ stage may be unrolled, expanding its bounds provided.\n if (op->update.defined()) {\n Box b = box_provided(op->produce, func.name());\n merge_boxes(b, box_provided(op->update, func.name()));\n if (can_slide_up) {\n string n = prefix + dim + \".min\";\n Expr var = Variable::make(Int(32), n);\n stmt = LetStmt::make(n, min(var, b[dim_idx].min), stmt);\n } else {\n string n = prefix + dim + \".max\";\n Expr var = Variable::make(Int(32), n);\n stmt = LetStmt::make(n, max(var, b[dim_idx].max), stmt);\n }\n }\n\n\n }\n }\n\n void visit(const For *op) {\n \/\/ It's not safe to enter an inner loop whose bounds depend on\n \/\/ the var we're sliding over.\n Expr min = expand_expr(op->min, scope);\n Expr extent = expand_expr(op->extent, scope);\n if (is_one(extent)) {\n \/\/ Just treat it like a let\n Stmt s = LetStmt::make(op->name, min, op->body);\n s = mutate(s);\n \/\/ Unpack it back into the for\n const LetStmt *l = s.as();\n internal_assert(l);\n stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, l->body);\n } else if (is_monotonic(min, loop_var) != Monotonic::Constant ||\n is_monotonic(extent, loop_var) != Monotonic::Constant) {\n debug(3) << \"Not entering loop over \" << op->name\n << \" because the bounds depend on the var we're sliding over: \"\n << min << \", \" << extent << \"\\n\";\n stmt = op;\n } else {\n IRMutator::visit(op);\n\n }\n }\n\n void visit(const LetStmt *op) {\n scope.push(op->name, simplify(expand_expr(op->value, scope)));\n Stmt new_body = mutate(op->body);\n\n Expr value = op->value;\n\n map::iterator iter = replacements.find(op->name);\n if (iter != replacements.end()) {\n value = iter->second;\n replacements.erase(iter);\n }\n\n if (new_body.same_as(op->body) && value.same_as(op->value)) {\n stmt = op;\n } else {\n stmt = LetStmt::make(op->name, value, new_body);\n }\n scope.pop(op->name);\n }\n\npublic:\n SlidingWindowOnFunctionAndLoop(Function f, string v, Expr v_min) : func(f), loop_var(v), loop_min(v_min) {}\n};\n\n\/\/ Perform sliding window optimization for a particular function\nclass SlidingWindowOnFunction : public IRMutator {\n Function func;\n\n\n using IRMutator::visit;\n\n void visit(const For *op) {\n debug(3) << \" Doing sliding window analysis over loop: \" << op->name << \"\\n\";\n\n Stmt new_body = op->body;\n\n new_body = mutate(new_body);\n\n if (op->for_type == ForType::Serial ||\n op->for_type == ForType::Unrolled) {\n new_body = SlidingWindowOnFunctionAndLoop(func, op->name, op->min).mutate(new_body);\n }\n\n if (new_body.same_as(op->body)) {\n stmt = op;\n } else {\n stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, new_body);\n }\n }\n\npublic:\n SlidingWindowOnFunction(Function f) : func(f) {}\n};\n\n\/\/ Perform sliding window optimization for all functions\nclass SlidingWindow : public IRMutator {\n const map &env;\n\n using IRMutator::visit;\n\n void visit(const Realize *op) {\n \/\/ Find the args for this function\n map::const_iterator iter = env.find(op->name);\n\n \/\/ If it's not in the environment it's some anonymous\n \/\/ realization that we should skip (e.g. an inlined reduction)\n if (iter == env.end()) {\n IRMutator::visit(op);\n return;\n }\n\n \/\/ If the Function in question has the same compute_at level\n \/\/ as its store_at level, skip it.\n const Schedule &sched = iter->second.schedule();\n if (sched.compute_level() == sched.store_level()) {\n IRMutator::visit(op);\n return;\n }\n\n Stmt new_body = op->body;\n\n debug(3) << \"Doing sliding window analysis on realization of \" << op->name << \"\\n\";\n\n new_body = SlidingWindowOnFunction(iter->second).mutate(new_body);\n\n new_body = mutate(new_body);\n\n if (new_body.same_as(op->body)) {\n stmt = op;\n } else {\n stmt = Realize::make(op->name, op->types, op->bounds, op->condition, new_body);\n }\n }\npublic:\n SlidingWindow(const map &e) : env(e) {}\n\n};\n\nStmt sliding_window(Stmt s, const map &env) {\n return SlidingWindow(env).mutate(s);\n}\n\n}\n}\n<|endoftext|>"} {"text":"\/\/ ToolbarHandler for fluxbox\n\/\/ Copyright (c) 2003 Simon Bowden (rathnor at fluxbox.org)\n\/\/ and Henrik Kinnunen (fluxgen at fluxbox.org)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id: ToolbarHandler.cc,v 1.2 2003\/03\/10 21:38:47 rathnor Exp $\n\n\/**\n * The ToolbarHandler class acts as a rough interface to the toolbar.\n * It deals with whether it should be there or not, so anything that\n * always needs to be accessible must come through the handler.\n *\/\n\n#include \"ToolbarHandler.hh\"\n#include \"Window.hh\"\n#include \"Screen.hh\"\n#include \"Workspace.hh\"\n#include \"MenuItem.hh\"\n#include \"Menu.hh\"\n#include \"FbCommands.hh\"\n#include \"RefCount.hh\"\n#include \"SimpleCommand.hh\"\n#include \"MacroCommand.hh\"\n#include \"IntResMenuItem.hh\"\n#include \"BoolMenuItem.hh\"\n\nnamespace {\n\nclass ToolbarModeMenuItem : public FbTk::MenuItem {\npublic:\n ToolbarModeMenuItem(const char *label, ToolbarHandler &handler, ToolbarHandler::ToolbarMode mode, FbTk::RefCount &cmd):\n FbTk::MenuItem(label, cmd), m_handler(handler), m_mode(mode) {\n }\n bool isEnabled() const { return m_handler.getMode() != m_mode; }\n void click(int button, int time) {\n m_handler.setMode(m_mode);\n FbTk::MenuItem::click(button, time);\n }\n\nprivate:\n ToolbarHandler &m_handler;\n ToolbarHandler::ToolbarMode m_mode;\n};\n\nvoid setupModeMenu(FbTk::Menu &menu, ToolbarHandler &handler) {\n \/\/I18n *i18n = I18n::instance();\n \/\/using namespace FBNLS;\n using namespace FbTk;\n\n RefCount saverc_cmd(new SimpleCommand(\n *Fluxbox::instance(), \n &Fluxbox::save_rc));\n \n \/\/TODO: nls\n menu.insert(new ToolbarModeMenuItem(\"Off\", handler, \n ToolbarHandler::OFF, saverc_cmd));\n menu.insert(new ToolbarModeMenuItem(\"None\", handler, \n ToolbarHandler::NONE, saverc_cmd));\n menu.insert(new ToolbarModeMenuItem(\"Icons\", handler, \n ToolbarHandler::ICONS, saverc_cmd));\n menu.insert(new ToolbarModeMenuItem(\"Workspace Icons\", handler, \n ToolbarHandler::WORKSPACEICONS, saverc_cmd));\n menu.insert(new ToolbarModeMenuItem(\"Workspace\", handler, \n ToolbarHandler::WORKSPACE, saverc_cmd));\n menu.insert(new ToolbarModeMenuItem(\"All Windows\", handler, \n ToolbarHandler::ALLWINDOWS, saverc_cmd));\n menu.update();\n}\n \n}; \/\/ end anonymous namespace\n\nToolbarHandler::ToolbarHandler(BScreen &screen, ToolbarMode mode) \n : m_screen(screen), m_mode(mode), m_toolbar(0), m_current_workspace(0),\n m_modemenu(*screen.menuTheme(),\n screen.getScreenNumber(), *screen.getImageControl()),\n m_toolbarmenu(*screen.menuTheme(),\n screen.getScreenNumber(), *screen.getImageControl())\n{\n m_modemenu.setInternalMenu();\n setupModeMenu(m_modemenu, *this);\n setMode(mode, false); \/\/ the atomhandler part will initialise it shortly\n}\n\nvoid ToolbarHandler::setMode(ToolbarMode mode, bool initialise) {\n if (mode < 0 || mode >= LASTMODE || (mode == m_mode && initialise)) return;\n if (mode == OFF) {\n m_toolbarmenu.removeAll();\n \/\/TODO: nls\n m_toolbarmenu.insert(\"Mode...\", &m_modemenu);\n m_toolbar.reset(0);\n m_toolbarmenu.update();\n return;\n } else if (!m_toolbar.get()) {\n m_toolbarmenu.removeAll();\n\n m_toolbarmenu.insert(\"Mode...\", &m_modemenu);\n m_toolbar.reset(new Toolbar(m_screen, \n *m_screen.layerManager().getLayer(m_screen.getToolbarLayerNum()), m_toolbarmenu));\n\n }\n \n\n if (mode == NONE) {\n \/\/ disableIconBar will clean up\n m_toolbar->disableIconBar();\n } else {\n \/\/ rebuild it\n \/\/ be sure the iconbar is on\n m_toolbar->enableIconBar();\n m_toolbar->delAllIcons();\n }\n \/\/ reset Toolbar, and reload it (initForScreen)\n m_mode = mode;\n if (initialise)\n initForScreen(m_screen);\n}\n\nvoid ToolbarHandler::initForScreen(BScreen &screen) {\n if (&m_screen != &screen) return;\n switch (m_mode) {\n case OFF:\n break;\n case NONE:\n break;\n case ALLWINDOWS:\n {\n BScreen::Workspaces::const_iterator workspace_it = m_screen.getWorkspacesList().begin();\n BScreen::Workspaces::const_iterator workspace_it_end = m_screen.getWorkspacesList().end();\n for (; workspace_it != workspace_it_end; ++workspace_it) {\n Workspace::Windows &wins = (*workspace_it)->getWindowList();\n Workspace::Windows::iterator wit = wins.begin();\n Workspace::Windows::iterator wit_end = wins.end();\n for (; wit != wit_end; ++wit) {\n m_toolbar->addIcon(*wit);\n }\n }\n }\n \/\/ fall through and add icons\n case LASTMODE:\n case ICONS: \n {\n BScreen::Icons &iconlist = m_screen.getIconList();\n BScreen::Icons::iterator iconit = iconlist.begin();\n BScreen::Icons::iterator iconit_end = iconlist.end();\n for(; iconit != iconit_end; ++iconit) {\n m_toolbar->addIcon(*iconit);\n }\n }\n break;\n case WORKSPACE:\n {\n Workspace::Windows &wins = m_screen.getCurrentWorkspace()->getWindowList();\n Workspace::Windows::iterator wit = wins.begin();\n Workspace::Windows::iterator wit_end = wins.end();\n for (; wit != wit_end; ++wit) {\n m_toolbar->addIcon(*wit);\n }\n }\n \/\/ fall through and add icons for this workspace\n case WORKSPACEICONS:\n {\n m_current_workspace = m_screen.getCurrentWorkspaceID();\n \n BScreen::Icons &wiconlist = m_screen.getIconList();\n BScreen::Icons::iterator iconit = wiconlist.begin();\n BScreen::Icons::iterator iconit_end = wiconlist.end();\n for(; iconit != iconit_end; ++iconit) {\n if ((*iconit)->getWorkspaceNumber() == m_current_workspace)\n m_toolbar->addIcon(*iconit);\n }\n }\n break;\n }\n}\n\nvoid ToolbarHandler::setupWindow(FluxboxWindow &win) {\n if (win.getScreen() != &m_screen) return;\n switch (m_mode) {\n case OFF:\n case NONE:\n break;\n case WORKSPACE:\n if (win.getWorkspaceNumber() == m_current_workspace) \n m_toolbar->addIcon(&win);\n break;\n case WORKSPACEICONS:\n if (win.getWorkspaceNumber() != m_current_workspace) \n break;\n \/\/ else fall through and add the icon\n case LASTMODE:\n case ICONS:\n if (win.isIconic()) {\n m_toolbar->addIcon(&win);\n }\n break;\n case ALLWINDOWS:\n m_toolbar->addIcon(&win);\n break;\n }\n}\n\nvoid ToolbarHandler::updateWindowClose(FluxboxWindow &win) {\n if (win.getScreen() != &m_screen) return;\n \/\/ check status of window (in current workspace, etc) and remove if necessary\n switch (m_mode) {\n case OFF:\n case NONE:\n break;\n case WORKSPACEICONS:\n if (win.getWorkspaceNumber() != m_current_workspace) \n break;\n \/\/ else fall through and remove the icon\n case LASTMODE:\n case ICONS:\n if (win.isIconic()) {\n m_toolbar->delIcon(&win);\n }\n break;\n case WORKSPACE:\n if (win.getWorkspaceNumber() == m_current_workspace)\n m_toolbar->delIcon(&win);\n break;\n case ALLWINDOWS:\n m_toolbar->delIcon(&win);\n break;\n }\n}\n\nvoid ToolbarHandler::updateState(FluxboxWindow &win) {\n if (win.getScreen() != &m_screen) return;\n\n \/\/ this function only relevant for icons\n switch (m_mode) {\n case OFF:\n case NONE:\n case WORKSPACE:\n case ALLWINDOWS:\n break;\n case WORKSPACEICONS:\n if (win.getWorkspaceNumber() != m_current_workspace) break;\n \/\/ else fall through and do the same as icons (knowing it is the right ws)\n case LASTMODE:\n case ICONS:\n \/\/ if the window is iconic (it mustn't have been before), then add it\n \/\/ else remove it\n if (win.isIconic()) {\n if (!m_toolbar->containsIcon(win)) {\n m_toolbar->addIcon(&win);\n }\n } else {\n m_toolbar->delIcon(&win);\n }\n break;\n }\n}\n \n\nvoid ToolbarHandler::updateWorkspace(FluxboxWindow &win) {\n if (win.getScreen() != &m_screen) return;\n \/\/ don't care about current workspace except if in workspace mode\n if (m_mode != WORKSPACE) return;\n if (win.getWorkspaceNumber() == m_current_workspace) {\n m_toolbar->addIcon(&win);\n } else {\n \/\/ relies on the fact that this runs but does nothing if window isn't contained.\n m_toolbar->delIcon(&win);\n }\n}\n\nvoid ToolbarHandler::updateCurrentWorkspace(BScreen &screen) {\n if (&screen != &m_screen) return;\n \/\/ if only displaying current workspace, update list\n \/\/ otherwise ignore it\n if (m_mode != WORKSPACE && m_mode != WORKSPACEICONS) return;\n m_toolbar->delAllIcons();\n initForScreen(m_screen);\n}\n\nworkaround another bug until can be rearranged properly\/\/ ToolbarHandler for fluxbox\n\/\/ Copyright (c) 2003 Simon Bowden (rathnor at fluxbox.org)\n\/\/ and Henrik Kinnunen (fluxgen at fluxbox.org)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id: ToolbarHandler.cc,v 1.3 2003\/03\/10 22:25:18 rathnor Exp $\n\n\/**\n * The ToolbarHandler class acts as a rough interface to the toolbar.\n * It deals with whether it should be there or not, so anything that\n * always needs to be accessible must come through the handler.\n *\/\n\n#include \"ToolbarHandler.hh\"\n#include \"Window.hh\"\n#include \"Screen.hh\"\n#include \"Workspace.hh\"\n#include \"MenuItem.hh\"\n#include \"Menu.hh\"\n#include \"FbCommands.hh\"\n#include \"RefCount.hh\"\n#include \"SimpleCommand.hh\"\n#include \"MacroCommand.hh\"\n#include \"IntResMenuItem.hh\"\n#include \"BoolMenuItem.hh\"\n\nnamespace {\n\nclass ToolbarModeMenuItem : public FbTk::MenuItem {\npublic:\n ToolbarModeMenuItem(const char *label, ToolbarHandler &handler, ToolbarHandler::ToolbarMode mode, FbTk::RefCount &cmd):\n FbTk::MenuItem(label, cmd), m_handler(handler), m_mode(mode) {\n }\n bool isEnabled() const { return m_handler.getMode() != m_mode; }\n void click(int button, int time) {\n m_handler.setMode(m_mode);\n FbTk::MenuItem::click(button, time);\n }\n\nprivate:\n ToolbarHandler &m_handler;\n ToolbarHandler::ToolbarMode m_mode;\n};\n\nvoid setupModeMenu(FbTk::Menu &menu, ToolbarHandler &handler) {\n \/\/I18n *i18n = I18n::instance();\n \/\/using namespace FBNLS;\n using namespace FbTk;\n\n RefCount saverc_cmd(new SimpleCommand(\n *Fluxbox::instance(), \n &Fluxbox::save_rc));\n \n \/\/TODO: nls\n menu.insert(new ToolbarModeMenuItem(\"Off\", handler, \n ToolbarHandler::OFF, saverc_cmd));\n menu.insert(new ToolbarModeMenuItem(\"None\", handler, \n ToolbarHandler::NONE, saverc_cmd));\n menu.insert(new ToolbarModeMenuItem(\"Icons\", handler, \n ToolbarHandler::ICONS, saverc_cmd));\n menu.insert(new ToolbarModeMenuItem(\"Workspace Icons\", handler, \n ToolbarHandler::WORKSPACEICONS, saverc_cmd));\n menu.insert(new ToolbarModeMenuItem(\"Workspace\", handler, \n ToolbarHandler::WORKSPACE, saverc_cmd));\n menu.insert(new ToolbarModeMenuItem(\"All Windows\", handler, \n ToolbarHandler::ALLWINDOWS, saverc_cmd));\n menu.update();\n}\n \n}; \/\/ end anonymous namespace\n\nToolbarHandler::ToolbarHandler(BScreen &screen, ToolbarMode mode) \n : m_screen(screen), m_mode(mode), m_toolbar(0), m_current_workspace(0),\n m_modemenu(*screen.menuTheme(),\n screen.getScreenNumber(), *screen.getImageControl()),\n m_toolbarmenu(*screen.menuTheme(),\n screen.getScreenNumber(), *screen.getImageControl())\n{\n m_modemenu.setInternalMenu();\n setupModeMenu(m_modemenu, *this);\n setMode(mode, false); \/\/ the atomhandler part will initialise it shortly\n}\n\nvoid ToolbarHandler::setMode(ToolbarMode mode, bool initialise) {\n if (mode < 0 || mode >= LASTMODE || (mode == m_mode && initialise)) return;\n if (mode == OFF) {\n m_toolbarmenu.removeAll();\n \/\/TODO: nls\n m_toolbarmenu.insert(\"Mode...\", &m_modemenu);\n m_toolbar.reset(0);\n m_toolbarmenu.update();\n return;\n } else if (!m_toolbar.get()) {\n m_toolbarmenu.removeAll();\n\n m_toolbarmenu.insert(\"Mode...\", &m_modemenu);\n m_toolbar.reset(new Toolbar(m_screen, \n *m_screen.layerManager().getLayer(m_screen.getToolbarLayerNum()), m_toolbarmenu));\n\n }\n \n\n if (mode == NONE) {\n \/\/ disableIconBar will clean up\n m_toolbar->disableIconBar();\n } else {\n \/\/ rebuild it\n \/\/ be sure the iconbar is on\n m_toolbar->enableIconBar();\n m_toolbar->delAllIcons();\n }\n \/\/ reset Toolbar, and reload it (initForScreen)\n m_mode = mode;\n if (initialise)\n initForScreen(m_screen);\n}\n\nvoid ToolbarHandler::initForScreen(BScreen &screen) {\n if (&m_screen != &screen) return;\n switch (m_mode) {\n case OFF:\n break;\n case NONE:\n break;\n case ALLWINDOWS:\n {\n BScreen::Workspaces::const_iterator workspace_it = m_screen.getWorkspacesList().begin();\n BScreen::Workspaces::const_iterator workspace_it_end = m_screen.getWorkspacesList().end();\n for (; workspace_it != workspace_it_end; ++workspace_it) {\n Workspace::Windows &wins = (*workspace_it)->getWindowList();\n Workspace::Windows::iterator wit = wins.begin();\n Workspace::Windows::iterator wit_end = wins.end();\n for (; wit != wit_end; ++wit) {\n m_toolbar->addIcon(*wit);\n }\n }\n }\n \/\/ fall through and add icons\n case LASTMODE:\n case ICONS: \n {\n BScreen::Icons &iconlist = m_screen.getIconList();\n BScreen::Icons::iterator iconit = iconlist.begin();\n BScreen::Icons::iterator iconit_end = iconlist.end();\n for(; iconit != iconit_end; ++iconit) {\n m_toolbar->addIcon(*iconit);\n }\n }\n break;\n case WORKSPACE:\n {\n Workspace::Windows &wins = m_screen.getCurrentWorkspace()->getWindowList();\n Workspace::Windows::iterator wit = wins.begin();\n Workspace::Windows::iterator wit_end = wins.end();\n for (; wit != wit_end; ++wit) {\n m_toolbar->addIcon(*wit);\n }\n }\n \/\/ fall through and add icons for this workspace\n case WORKSPACEICONS:\n {\n m_current_workspace = m_screen.getCurrentWorkspaceID();\n \n BScreen::Icons &wiconlist = m_screen.getIconList();\n BScreen::Icons::iterator iconit = wiconlist.begin();\n BScreen::Icons::iterator iconit_end = wiconlist.end();\n for(; iconit != iconit_end; ++iconit) {\n if ((*iconit)->getWorkspaceNumber() == m_current_workspace)\n m_toolbar->addIcon(*iconit);\n }\n }\n break;\n }\n}\n\nvoid ToolbarHandler::setupWindow(FluxboxWindow &win) {\n if (win.getScreen() != &m_screen) return;\n switch (m_mode) {\n case OFF:\n case NONE:\n break;\n case WORKSPACE:\n if (win.getWorkspaceNumber() == m_current_workspace) \n m_toolbar->addIcon(&win);\n break;\n case WORKSPACEICONS:\n if (win.getWorkspaceNumber() != m_current_workspace) \n break;\n \/\/ else fall through and add the icon\n case LASTMODE:\n case ICONS:\n if (win.isIconic()) {\n m_toolbar->addIcon(&win);\n }\n break;\n case ALLWINDOWS:\n m_toolbar->addIcon(&win);\n break;\n }\n}\n\nvoid ToolbarHandler::updateWindowClose(FluxboxWindow &win) {\n if (win.getScreen() != &m_screen) return;\n \/\/ check status of window (in current workspace, etc) and remove if necessary\n switch (m_mode) {\n case OFF:\n case NONE:\n break;\n case WORKSPACEICONS:\n if (win.getWorkspaceNumber() != m_current_workspace) \n break;\n \/\/ else fall through and remove the icon\n case LASTMODE:\n case ICONS:\n if (win.isIconic()) {\n m_toolbar->delIcon(&win);\n }\n break;\n case WORKSPACE:\n if (win.getWorkspaceNumber() == m_current_workspace)\n m_toolbar->delIcon(&win);\n break;\n case ALLWINDOWS:\n m_toolbar->delIcon(&win);\n break;\n }\n}\n\nvoid ToolbarHandler::updateState(FluxboxWindow &win) {\n if (win.getScreen() != &m_screen) return;\n\n \/\/ this function only relevant for icons\n switch (m_mode) {\n case OFF:\n case NONE:\n case WORKSPACE:\n case ALLWINDOWS:\n break;\n case WORKSPACEICONS:\n if (win.getWorkspaceNumber() != m_current_workspace) break;\n \/\/ else fall through and do the same as icons (knowing it is the right ws)\n case LASTMODE:\n case ICONS:\n \/\/ if the window is iconic (it mustn't have been before), then add it\n \/\/ else remove it\n if (win.isIconic()) {\n if (!m_toolbar->containsIcon(win)) {\n m_toolbar->addIcon(&win);\n }\n } else {\n m_toolbar->delIcon(&win);\n }\n break;\n }\n}\n \n\nvoid ToolbarHandler::updateWorkspace(FluxboxWindow &win) {\n if (win.getScreen() != &m_screen) return;\n \/\/ don't care about current workspace except if in workspace mode\n if (!(m_mode == WORKSPACE || (m_mode == WORKSPACEICONS && win.isIconic()))) return;\n \n if (win.getWorkspaceNumber() == m_current_workspace) {\n \/\/ TODO\n \/\/ this shouldn't be needed, but is until Workspaces get fixed so that\n \/\/ you only move between them, you don't 'add' and 'remove'\n \/\/ alternatively, fix reassocaiteWindow so that the iconic stuff is\n \/\/ done elsewhere\n if (!m_toolbar->containsIcon(win))\n m_toolbar->addIcon(&win);\n } else {\n \/\/ relies on the fact that this runs but does nothing if window isn't contained.\n m_toolbar->delIcon(&win);\n }\n}\n\nvoid ToolbarHandler::updateCurrentWorkspace(BScreen &screen) {\n if (&screen != &m_screen) return;\n \/\/ if only displaying current workspace, update list\n \/\/ otherwise ignore it\n if (m_mode != WORKSPACE && m_mode != WORKSPACEICONS) return;\n m_toolbar->delAllIcons();\n initForScreen(m_screen);\n}\n\n<|endoftext|>"} {"text":"\/*\r\nGiven an integer n, return a string array answer (1-indexed) where:\r\n\r\nanswer[i] == \"FizzBuzz\" if i is divisible by 3 and 5.\r\nanswer[i] == \"Fizz\" if i is divisible by 3.\r\nanswer[i] == \"Buzz\" if i is divisible by 5.\r\nanswer[i] == i (as a string) if none of the above conditions are true.\r\n*\/\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace std;\r\nclass Solution {\r\npublic:\r\n vector fizzBuzz(int n) {\r\n vector ans;\r\n for (int i = 1; i <= n; i++) {\r\n if ((i % 3 == 0) && (i % 5 == 0)) {\r\n ans.push_back(\"FizzBuzz\");\r\n } else if (i % 3 == 0) {\r\n ans.push_back(\"Fizz\");\r\n } else if (i % 5 == 0) {\r\n ans.push_back(\"Buzz\");\r\n } else {\r\n ans.push_back(to_string(i));\r\n }\r\n }\r\n return ans;\r\n }\r\n};\r\n\r\nint main() {\r\n\tint test[] = { 1, 7, 4, 6, 3, 10, 2 };\r\n Solution sol;\r\n auto fizzBuzz = sol.fizzBuzz(15);\r\n\r\n cout << \"Fizzbuzz\" << endl;\r\n std::ostream_iterator out_it (std::cout,\", \");\r\n copy ( fizzBuzz.begin(), fizzBuzz.end(), out_it );\r\n\treturn 0;\r\n}Shuffle\/*\r\nGiven an integer n, return a string array answer (1-indexed) where:\r\n\r\nanswer[i] == \"FizzBuzz\" if i is divisible by 3 and 5.\r\nanswer[i] == \"Fizz\" if i is divisible by 3.\r\nanswer[i] == \"Buzz\" if i is divisible by 5.\r\nanswer[i] == i (as a string) if none of the above conditions are true.\r\n*\/\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace std;\r\nclass Solution {\r\npublic:\r\n vector fizzBuzz(int n) {\r\n vector ans;\r\n for (int i = 1; i <= n; i++) {\r\n if ((i % 3 == 0) && (i % 5 == 0)) {\r\n ans.push_back(\"FizzBuzz\");\r\n } else if (i % 3 == 0) {\r\n ans.push_back(\"Fizz\");\r\n } else if (i % 5 == 0) {\r\n ans.push_back(\"Buzz\");\r\n } else {\r\n ans.push_back(to_string(i));\r\n }\r\n }\r\n return ans;\r\n }\r\n};\r\n\r\n\/*\r\nGiven an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.\r\n\r\nImplement the Solution class:\r\n\r\nSolution(int[] nums) Initializes the object with the integer array nums.\r\nint[] reset() Resets the array to its original configuration and returns it.\r\nint[] shuffle() Returns a random shuffling of the array.\r\n\r\nInput\r\n[\"Solution\", \"shuffle\", \"reset\", \"shuffle\"]\r\n[[[1, 2, 3]], [], [], []]\r\nOutput\r\n[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]\r\n\r\nExplanation\r\nSolution solution = new Solution([1, 2, 3]);\r\nsolution.shuffle(); \/\/ Shuffle the array [1,2,3] and return its result.\r\n \/\/ Any permutation of [1,2,3] must be equally likely to be returned.\r\n \/\/ Example: return [3, 1, 2]\r\nsolution.reset(); \/\/ Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]\r\nsolution.shuffle(); \/\/ Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]\r\n\r\nNote that the input is a ref, not const so you must change the passed in deck\r\n*\/\r\n\r\n#include \r\n#include \/\/ std::default_random_engine\r\n#include \/\/ std::chrono::system_clock\r\n\r\nclass ShuffleSolution {\r\npublic:\r\n ShuffleSolution(vector& nums) : _originalNums(nums) {\r\n \/\/ std::vector ivec(nums.size());\r\n \/\/std::iota(ivec.begin(), ivec.end(), 0);\r\n _positions = _originalNums;\r\n }\r\n \r\n vector reset() {\r\n _originalNums = _positions;\r\n return _originalNums;\r\n }\r\n \r\n vector shuffle() {\r\n auto seed = std::chrono::system_clock::now().time_since_epoch().count();\r\n std::shuffle(_originalNums.begin(), _originalNums.end(), std::default_random_engine(seed));\r\n return _originalNums;\r\n }\r\nprivate:\r\n vector &_originalNums;\r\n vector _positions;\r\n};\r\n\r\n\/**\r\n * Your Solution object will be instantiated and called as such:\r\n * Solution* obj = new Solution(nums);\r\n * vector param_1 = obj->reset();\r\n * vector param_2 = obj->shuffle();\r\n *\/\r\n\r\nint main() {\r\n\tint test[] = { 1, 7, 4, 6, 3, 10, 2 };\r\n Solution sol;\r\n auto fizzBuzz = sol.fizzBuzz(15);\r\n\r\n cout << \"Fizzbuzz\" << endl;\r\n std::ostream_iterator out_it (std::cout,\", \");\r\n copy ( fizzBuzz.begin(), fizzBuzz.end(), out_it );\r\n\treturn 0;\r\n}<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2017-2018 dresden elektronik ingenieurtechnik gmbh.\n * All rights reserved.\n *\n * The software in this package is published under the terms of the BSD\n * style license a copy of which has been included with this distribution in\n * the LICENSE.txt file.\n *\n *\/\n\n#include \"poll_manager.h\"\n#include \"de_web_plugin_private.h\"\n\n\/*! Constructor.\n *\/\nPollManager::PollManager(QObject *parent) :\n QObject(parent)\n{\n pollState = StateIdle;\n timer = new QTimer(this);\n timer->setSingleShot(true);\n connect(timer, SIGNAL(timeout()), this, SLOT(pollTimerFired()));\n plugin = qobject_cast(parent);\n}\n\n\/*! Queues polling of the node.\n \\param restNode - the node to poll\n *\/\nvoid PollManager::poll(RestNodeBase *restNode, const QDateTime &tStart)\n{\n Resource *r = dynamic_cast(restNode);\n DBG_Assert(r);\n if (!r || !restNode->node())\n {\n return;\n }\n\n PollItem pitem;\n\n if (!restNode->node()->nodeDescriptor().receiverOnWhenIdle())\n {\n return;\n }\n\n LightNode *lightNode = nullptr;\n Sensor *sensor = nullptr;\n\n if (r->prefix() == RLights)\n {\n lightNode = dynamic_cast(restNode);\n DBG_Assert(lightNode);\n pitem.endpoint = lightNode->haEndpoint().endpoint();\n DBG_Printf(DBG_INFO_L2, \">>>> Poll light node %s\\n\", qPrintable(lightNode->name()));\n }\n else if (r->prefix() == RSensors)\n {\n sensor = dynamic_cast(restNode);\n DBG_Assert(sensor);\n pitem.endpoint = sensor->fingerPrint().endpoint;\n DBG_Printf(DBG_INFO_L2, \">>>> Poll %s sensor node %s\\n\", qPrintable(sensor->type()), qPrintable(sensor->name()));\n }\n else\n {\n return;\n }\n\n pitem.id = restNode->id();\n pitem.prefix = r->prefix();\n pitem.address = restNode->address();\n pitem.tStart = tStart;\n\n for (int i = 0; i < r->itemCount(); i++)\n {\n const ResourceItem *item = r->itemForIndex(i);\n const char *suffix = item ? item->descriptor().suffix : nullptr;\n\n if (suffix == RStateOn ||\n suffix == RStateBri ||\n suffix == RStateColorMode ||\n (suffix == RStateConsumption && sensor && sensor->type() == QLatin1String(\"ZHAConsumption\")) ||\n (suffix == RStatePower && sensor && sensor->type() == QLatin1String(\"ZHAPower\")) ||\n (suffix == RStatePresence && sensor && sensor->type() == QLatin1String(\"ZHAPresence\")) ||\n (suffix == RStateLightLevel && sensor && sensor->type() == QLatin1String(\"ZHALightLevel\")) ||\n suffix == RAttrModelId ||\n suffix == RAttrSwVersion)\n {\n \/\/ DBG_Printf(DBG_INFO_L2, \" attribute %s\\n\", suffix);\n pitem.items.push_back(suffix);\n }\n }\n\n for (PollItem &i : items)\n {\n if (i.prefix == r->prefix() && i.id == restNode->id())\n {\n i.items = pitem.items; \/\/ update\n if (tStart.isValid())\n {\n i.tStart = tStart;\n }\n return;\n }\n }\n\n items.push_back(pitem);\n\n if (!timer->isActive())\n {\n timer->start(1);\n }\n}\n\n\/*! Delays polling for \\p ms milliseconds.\n *\/\nvoid PollManager::delay(int ms)\n{\n timer->stop();\n timer->start(ms);\n}\n\n\/*! Handle APS confirm if related to polling.\n *\/\nvoid PollManager::apsdeDataConfirm(const deCONZ::ApsDataConfirm &conf)\n{\n if (pollState != StateWait)\n {\n return;\n }\n\n if (apsReqId != conf.id())\n {\n return;\n }\n\n if (dstAddr.hasExt() && conf.dstAddress().hasExt()\n && dstAddr.ext() != conf.dstAddress().ext())\n {\n\n }\n\n else if (dstAddr.hasNwk() && conf.dstAddress().hasNwk()\n && dstAddr.nwk() != conf.dstAddress().nwk())\n {\n\n }\n\n DBG_Printf(DBG_INFO_L2, \"Poll APS confirm %u status: 0x%02X\\n\", conf.id(), conf.status());\n\n pollState = StateIdle;\n timer->stop();\n timer->start(1);\n}\n\n\/*! Timer callback to proceed polling.\n *\/\nvoid PollManager::pollTimerFired()\n{\n if (pollState == StateWait)\n {\n DBG_Printf(DBG_INFO, \"timeout on poll APS confirm\\n\");\n pollState = StateIdle;\n }\n\n DBG_Assert(pollState == StateIdle);\n\n if (items.empty())\n {\n return;\n }\n\n QDateTime now = QDateTime::currentDateTime();\n PollItem &pitem = items.front();\n Resource *r = plugin->getResource(pitem.prefix, pitem.id);\n ResourceItem *item = nullptr;\n RestNodeBase *restNode = nullptr;\n const LightNode *lightNode = nullptr;\n if (r && r->prefix() == RLights)\n {\n restNode = plugin->getLightNodeForId(pitem.id);\n lightNode = dynamic_cast(restNode);\n item = r->item(RStateReachable);\n }\n else if (r && r->prefix() == RSensors)\n {\n restNode = plugin->getSensorNodeForId(pitem.id);\n item = r->item(RConfigReachable);\n }\n\n if (pitem.tStart.isValid() && pitem.tStart > now)\n {\n if (items.size() > 1)\n {\n PollItem tmp = pitem;\n items.front() = items.back();\n items.back() = tmp;\n }\n timer->start(1);\n return;\n }\n\n if (!r || pitem.items.empty() ||\n !restNode ||\n \/\/!restNode->lastRx().isValid() ||\n !item || !item->toBool()) \/\/ not reachable\n {\n items.front() = items.back();\n items.pop_back();\n timer->start(1);\n return;\n }\n\n const auto dtReachable = item->lastSet().secsTo(now);\n\n quint16 clusterId = 0xffff; \/\/ invalid\n std::vector attributes;\n\n item = r->item(RStateOn);\n bool isOn = item ? item->toBool() : false;\n const char *&suffix = pitem.items[0];\n\n for (size_t i = 0; pitem.items[0] == nullptr && i < pitem.items.size(); i++)\n {\n if (pitem.items[i] != nullptr)\n {\n pitem.items[0] = pitem.items[i]; \/\/ move to front\n pitem.items[i] = nullptr; \/\/ clear\n break;\n }\n }\n\n if (!suffix)\n {\n pitem.items.clear(); \/\/ all done\n }\n\n if (suffix == RStateOn)\n {\n if (lightNode && lightNode->manufacturerCode() != VENDOR_115F) \/\/ reports\n {\n clusterId = ONOFF_CLUSTER_ID;\n attributes.push_back(0x0000); \/\/ onOff\n }\n }\n else if (suffix == RStateBri && isOn)\n {\n NodeValue &val = restNode->getZclValue(LEVEL_CLUSTER_ID, 0x0000);\n\n if (isOn || !val.timestamp.isValid())\n {\n clusterId = LEVEL_CLUSTER_ID;\n attributes.push_back(0x0000); \/\/ current level\n }\n }\n else if (suffix == RStateColorMode && lightNode)\n {\n clusterId = COLOR_CLUSTER_ID;\n item = r->item(RConfigColorCapabilities);\n\n if (!item || item->toNumber() <= 0)\n {\n attributes.push_back(0x0008); \/\/ color mode\n attributes.push_back(0x4001); \/\/ enhanced color mode\n attributes.push_back(0x400a); \/\/ color capabilities\n attributes.push_back(0x400b); \/\/ color temperature min\n attributes.push_back(0x400c); \/\/ color temperature max\n }\n else\n {\n quint16 cap = item->toNumber();\n std::vector toCheck;\n if (cap & 0x0002) \/\/ enhanced hue supported\n {\n toCheck.push_back(0x4001); \/\/ enhanced color mode\n toCheck.push_back(0x4000); \/\/ enhanced hue\n toCheck.push_back(0x0001); \/\/ saturation\n }\n else if (cap & 0x0001)\n {\n toCheck.push_back(0x0000); \/\/ hue\n toCheck.push_back(0x0001); \/\/ saturation\n toCheck.push_back(0x0008); \/\/ color mode\n }\n else\n {\n toCheck.push_back(0x0008); \/\/ color mode\n }\n\n if (cap & 0x0004)\n {\n toCheck.push_back(0x4002); \/\/ Color loop active\n }\n\n if (cap & 0x0008)\n {\n toCheck.push_back(0x0003); \/\/ currentX\n toCheck.push_back(0x0004); \/\/ currentY\n }\n\n if (cap & 0x0010)\n {\n toCheck.push_back(0x0007); \/\/ color temperature\n }\n\n for (const deCONZ::ZclCluster &cl : lightNode->haEndpoint().inClusters())\n {\n if (cl.id() != COLOR_CLUSTER_ID)\n {\n continue;\n }\n\n for (const deCONZ::ZclAttribute &attr : cl.attributes())\n {\n for (quint16 attrId : toCheck)\n {\n \/\/ discard attributes which are not be available\n if (attrId == attr.id() && attr.isAvailable())\n {\n NodeValue &val = restNode->getZclValue(clusterId, attrId);\n if (isOn || !val.timestamp.isValid())\n {\n attributes.push_back(attrId);\n }\n }\n }\n }\n\n break;\n }\n }\n }\n else if (suffix == RStatePresence)\n {\n clusterId = OCCUPANCY_SENSING_CLUSTER_ID;\n attributes.push_back(0x0000); \/\/ Occupancy\n attributes.push_back(0x0010); \/\/ PIR Occupied To Unoccupied Delay\n }\n else if (suffix == RStateLightLevel)\n {\n clusterId = ILLUMINANCE_MEASUREMENT_CLUSTER_ID;\n attributes.push_back(0x0000); \/\/ Measured Value\n }\n else if (suffix == RStateConsumption)\n {\n clusterId = METERING_CLUSTER_ID;\n attributes.push_back(0x0000); \/\/ Curent Summation Delivered\n attributes.push_back(0x0400); \/\/ Instantaneous Demand\n }\n else if (suffix == RStatePower)\n {\n clusterId = ELECTRICAL_MEASUREMENT_CLUSTER_ID;\n attributes.push_back(0x050b); \/\/ Active Power\n item = r->item(RAttrModelId);\n if (! item->toString().startsWith(QLatin1String(\"Plug\"))) \/\/ OSRAM plug\n {\n attributes.push_back(0x0505); \/\/ RMS Voltage\n attributes.push_back(0x0508); \/\/ RMS Current\n }\n }\n else if (suffix == RAttrModelId)\n {\n item = r->item(RAttrModelId);\n if (item && (item->toString().isEmpty() || item->toString() == QLatin1String(\"unknown\") ||\n (item->lastSet().secsTo(now) > READ_MODEL_ID_INTERVAL && item->toString().startsWith(\"FLS-A\")) \/\/ dynamic model ids\n ))\n {\n clusterId = BASIC_CLUSTER_ID;\n \/\/attributes.push_back(0x0004); \/\/ manufacturer\n attributes.push_back(0x0005); \/\/ model id\n }\n }\n else if (suffix == RAttrSwVersion && lightNode)\n {\n item = r->item(RAttrSwVersion);\n if (item && (item->toString().isEmpty() ||\n (item->lastSet().secsTo(now) > READ_SWBUILD_ID_INTERVAL))) \/\/ dynamic\n {\n\n if (lightNode->manufacturerCode() == VENDOR_UBISYS ||\n lightNode->manufacturerCode() == VENDOR_EMBER ||\n lightNode->manufacturerCode() == VENDOR_120B ||\n lightNode->manufacturerCode() == VENDOR_115F ||\n lightNode->manufacturer().startsWith(QLatin1String(\"Climax\")))\n {\n if (item->toString().isEmpty())\n {\n attributes.push_back(0x0006); \/\/ date code\n clusterId = BASIC_CLUSTER_ID;\n }\n }\n else\n {\n if (item->toString().isEmpty() ||\n lightNode->manufacturerCode() == VENDOR_XAL ||\n lightNode->manufacturerCode() == VENDOR_DDEL)\n {\n attributes.push_back(0x4000); \/\/ sw build id\n clusterId = BASIC_CLUSTER_ID;\n }\n }\n }\n }\n\n size_t fresh = 0;\n const int reportWaitTime = 360;\n for (quint16 attrId : attributes)\n {\n \/\/ force polling after node becomes reachable, since reporting might not be active\n if (dtReachable < reportWaitTime)\n {\n break;\n }\n\n NodeValue &val = restNode->getZclValue(clusterId, attrId);\n\n if (val.timestampLastReport.isValid() && val.timestampLastReport.secsTo(now) < reportWaitTime)\n {\n fresh++;\n }\n }\n\n \/\/ check that cluster exists on endpoint\n if (clusterId != 0xffff)\n {\n bool found = false;\n deCONZ::SimpleDescriptor sd;\n if (restNode->node()->copySimpleDescriptor(pitem.endpoint, &sd) == 0)\n {\n for (const auto &cl : sd.inClusters())\n {\n if (cl.id() == clusterId)\n {\n found = true;\n break;\n }\n }\n }\n\n if (!found)\n {\n DBG_Printf(DBG_INFO, \"Poll APS request to 0x%016llX cluster: 0x%04X dropped, cluster doesn't exist\\n\", pitem.address.ext(), clusterId);\n clusterId = 0xffff;\n }\n }\n\n if (clusterId != 0xffff && fresh > 0 && fresh == attributes.size())\n {\n DBG_Printf(DBG_INFO, \"Poll APS request to 0x%016llX cluster: 0x%04X dropped, values are fresh enough\\n\", pitem.address.ext(), clusterId);\n suffix = nullptr; \/\/ clear\n timer->start(100);\n }\n else if (!attributes.empty() && clusterId != 0xffff &&\n plugin->readAttributes(restNode, pitem.endpoint, clusterId, attributes))\n {\n pollState = StateWait;\n \/\/ TODO this hack to get aps request id\n DBG_Assert(plugin->tasks.back().taskType == TaskReadAttributes);\n apsReqId = plugin->tasks.back().req.id();\n dstAddr = pitem.address;\n timer->start(60 * 1000); \/\/ wait for confirm\n suffix = nullptr; \/\/ clear\n DBG_Printf(DBG_INFO_L2, \"Poll APS request %u to 0x%016llX cluster: 0x%04X\\n\", apsReqId, dstAddr.ext(), clusterId);\n }\n else if (suffix)\n {\n suffix = nullptr; \/\/ clear\n timer->start(100);\n }\n else\n {\n if (clusterId != 0xffff)\n {\n DBG_Printf(DBG_INFO, \"Poll APS request to 0x%016llX cluster: 0x%04X dropped\\n\", pitem.address.ext(), clusterId);\n }\n timer->start(100);\n items.front() = items.back();\n items.pop_back();\n }\n}\nQuery color cluster of ZHA lights like OSRAM LEDVANCE (US)\/*\n * Copyright (c) 2017-2018 dresden elektronik ingenieurtechnik gmbh.\n * All rights reserved.\n *\n * The software in this package is published under the terms of the BSD\n * style license a copy of which has been included with this distribution in\n * the LICENSE.txt file.\n *\n *\/\n\n#include \"poll_manager.h\"\n#include \"de_web_plugin_private.h\"\n\n\/*! Constructor.\n *\/\nPollManager::PollManager(QObject *parent) :\n QObject(parent)\n{\n pollState = StateIdle;\n timer = new QTimer(this);\n timer->setSingleShot(true);\n connect(timer, SIGNAL(timeout()), this, SLOT(pollTimerFired()));\n plugin = qobject_cast(parent);\n}\n\n\/*! Queues polling of the node.\n \\param restNode - the node to poll\n *\/\nvoid PollManager::poll(RestNodeBase *restNode, const QDateTime &tStart)\n{\n Resource *r = dynamic_cast(restNode);\n DBG_Assert(r);\n if (!r || !restNode->node())\n {\n return;\n }\n\n PollItem pitem;\n\n if (!restNode->node()->nodeDescriptor().receiverOnWhenIdle())\n {\n return;\n }\n\n LightNode *lightNode = nullptr;\n Sensor *sensor = nullptr;\n\n if (r->prefix() == RLights)\n {\n lightNode = dynamic_cast(restNode);\n DBG_Assert(lightNode);\n pitem.endpoint = lightNode->haEndpoint().endpoint();\n DBG_Printf(DBG_INFO_L2, \">>>> Poll light node %s\\n\", qPrintable(lightNode->name()));\n }\n else if (r->prefix() == RSensors)\n {\n sensor = dynamic_cast(restNode);\n DBG_Assert(sensor);\n pitem.endpoint = sensor->fingerPrint().endpoint;\n DBG_Printf(DBG_INFO_L2, \">>>> Poll %s sensor node %s\\n\", qPrintable(sensor->type()), qPrintable(sensor->name()));\n }\n else\n {\n return;\n }\n\n pitem.id = restNode->id();\n pitem.prefix = r->prefix();\n pitem.address = restNode->address();\n pitem.tStart = tStart;\n\n for (int i = 0; i < r->itemCount(); i++)\n {\n const ResourceItem *item = r->itemForIndex(i);\n const char *suffix = item ? item->descriptor().suffix : nullptr;\n\n if (suffix == RStateOn ||\n suffix == RStateBri ||\n suffix == RStateColorMode ||\n (suffix == RStateConsumption && sensor && sensor->type() == QLatin1String(\"ZHAConsumption\")) ||\n (suffix == RStatePower && sensor && sensor->type() == QLatin1String(\"ZHAPower\")) ||\n (suffix == RStatePresence && sensor && sensor->type() == QLatin1String(\"ZHAPresence\")) ||\n (suffix == RStateLightLevel && sensor && sensor->type() == QLatin1String(\"ZHALightLevel\")) ||\n suffix == RAttrModelId ||\n suffix == RAttrSwVersion)\n {\n \/\/ DBG_Printf(DBG_INFO_L2, \" attribute %s\\n\", suffix);\n pitem.items.push_back(suffix);\n }\n }\n\n for (PollItem &i : items)\n {\n if (i.prefix == r->prefix() && i.id == restNode->id())\n {\n i.items = pitem.items; \/\/ update\n if (tStart.isValid())\n {\n i.tStart = tStart;\n }\n return;\n }\n }\n\n items.push_back(pitem);\n\n if (!timer->isActive())\n {\n timer->start(1);\n }\n}\n\n\/*! Delays polling for \\p ms milliseconds.\n *\/\nvoid PollManager::delay(int ms)\n{\n timer->stop();\n timer->start(ms);\n}\n\n\/*! Handle APS confirm if related to polling.\n *\/\nvoid PollManager::apsdeDataConfirm(const deCONZ::ApsDataConfirm &conf)\n{\n if (pollState != StateWait)\n {\n return;\n }\n\n if (apsReqId != conf.id())\n {\n return;\n }\n\n if (dstAddr.hasExt() && conf.dstAddress().hasExt()\n && dstAddr.ext() != conf.dstAddress().ext())\n {\n\n }\n\n else if (dstAddr.hasNwk() && conf.dstAddress().hasNwk()\n && dstAddr.nwk() != conf.dstAddress().nwk())\n {\n\n }\n\n DBG_Printf(DBG_INFO_L2, \"Poll APS confirm %u status: 0x%02X\\n\", conf.id(), conf.status());\n\n pollState = StateIdle;\n timer->stop();\n timer->start(1);\n}\n\n\/*! Timer callback to proceed polling.\n *\/\nvoid PollManager::pollTimerFired()\n{\n if (pollState == StateWait)\n {\n DBG_Printf(DBG_INFO, \"timeout on poll APS confirm\\n\");\n pollState = StateIdle;\n }\n\n DBG_Assert(pollState == StateIdle);\n\n if (items.empty())\n {\n return;\n }\n\n QDateTime now = QDateTime::currentDateTime();\n PollItem &pitem = items.front();\n Resource *r = plugin->getResource(pitem.prefix, pitem.id);\n ResourceItem *item = nullptr;\n RestNodeBase *restNode = nullptr;\n const LightNode *lightNode = nullptr;\n if (r && r->prefix() == RLights)\n {\n restNode = plugin->getLightNodeForId(pitem.id);\n lightNode = dynamic_cast(restNode);\n item = r->item(RStateReachable);\n }\n else if (r && r->prefix() == RSensors)\n {\n restNode = plugin->getSensorNodeForId(pitem.id);\n item = r->item(RConfigReachable);\n }\n\n if (pitem.tStart.isValid() && pitem.tStart > now)\n {\n if (items.size() > 1)\n {\n PollItem tmp = pitem;\n items.front() = items.back();\n items.back() = tmp;\n }\n timer->start(1);\n return;\n }\n\n if (!r || pitem.items.empty() ||\n !restNode ||\n \/\/!restNode->lastRx().isValid() ||\n !item || !item->toBool()) \/\/ not reachable\n {\n items.front() = items.back();\n items.pop_back();\n timer->start(1);\n return;\n }\n\n const auto dtReachable = item->lastSet().secsTo(now);\n\n quint16 clusterId = 0xffff; \/\/ invalid\n std::vector attributes;\n\n item = r->item(RStateOn);\n bool isOn = item ? item->toBool() : false;\n const char *&suffix = pitem.items[0];\n\n for (size_t i = 0; pitem.items[0] == nullptr && i < pitem.items.size(); i++)\n {\n if (pitem.items[i] != nullptr)\n {\n pitem.items[0] = pitem.items[i]; \/\/ move to front\n pitem.items[i] = nullptr; \/\/ clear\n break;\n }\n }\n\n if (!suffix)\n {\n pitem.items.clear(); \/\/ all done\n }\n\n if (suffix == RStateOn)\n {\n if (lightNode && lightNode->manufacturerCode() != VENDOR_115F) \/\/ reports\n {\n clusterId = ONOFF_CLUSTER_ID;\n attributes.push_back(0x0000); \/\/ onOff\n }\n }\n else if (suffix == RStateBri && isOn)\n {\n NodeValue &val = restNode->getZclValue(LEVEL_CLUSTER_ID, 0x0000);\n\n if (isOn || !val.timestamp.isValid())\n {\n clusterId = LEVEL_CLUSTER_ID;\n attributes.push_back(0x0000); \/\/ current level\n }\n }\n else if (suffix == RStateColorMode && lightNode)\n {\n clusterId = COLOR_CLUSTER_ID;\n item = r->item(RConfigColorCapabilities);\n\n if ((!item || item->toNumber() <= 0) && lightNode->haEndpoint().profileId() != HA_PROFILE_ID)\n {\n attributes.push_back(0x0008); \/\/ color mode\n attributes.push_back(0x4001); \/\/ enhanced color mode\n attributes.push_back(0x400a); \/\/ color capabilities\n attributes.push_back(0x400b); \/\/ color temperature min\n attributes.push_back(0x400c); \/\/ color temperature max\n }\n else\n {\n quint16 cap = item ? static_cast(item->toNumber()) : 0;\n\n if (cap == 0 && lightNode->haEndpoint().profileId() == HA_PROFILE_ID)\n {\n \/\/ e.g. OSRAM US version\n \/\/ DEV_ID_HA_COLOR_DIMMABLE_LIGHT\n cap = (0x0001 | 0x0008); \/\/ hue, saturation, color mode, xy\n }\n\n std::vector toCheck;\n if (cap & 0x0002) \/\/ enhanced hue supported\n {\n toCheck.push_back(0x4001); \/\/ enhanced color mode\n toCheck.push_back(0x4000); \/\/ enhanced hue\n toCheck.push_back(0x0001); \/\/ saturation\n }\n else if (cap & 0x0001)\n {\n toCheck.push_back(0x0000); \/\/ hue\n toCheck.push_back(0x0001); \/\/ saturation\n toCheck.push_back(0x0008); \/\/ color mode\n }\n else\n {\n toCheck.push_back(0x0008); \/\/ color mode\n }\n\n if (cap & 0x0004)\n {\n toCheck.push_back(0x4002); \/\/ Color loop active\n }\n\n if (cap & 0x0008)\n {\n toCheck.push_back(0x0003); \/\/ currentX\n toCheck.push_back(0x0004); \/\/ currentY\n }\n\n if (cap & 0x0010)\n {\n toCheck.push_back(0x0007); \/\/ color temperature\n }\n\n for (const deCONZ::ZclCluster &cl : lightNode->haEndpoint().inClusters())\n {\n if (cl.id() != COLOR_CLUSTER_ID)\n {\n continue;\n }\n\n for (const deCONZ::ZclAttribute &attr : cl.attributes())\n {\n for (quint16 attrId : toCheck)\n {\n \/\/ discard attributes which are not be available\n if (attrId == attr.id() && attr.isAvailable())\n {\n NodeValue &val = restNode->getZclValue(clusterId, attrId);\n if (isOn || !val.timestamp.isValid())\n {\n attributes.push_back(attrId);\n }\n }\n }\n }\n\n break;\n }\n }\n }\n else if (suffix == RStatePresence)\n {\n clusterId = OCCUPANCY_SENSING_CLUSTER_ID;\n attributes.push_back(0x0000); \/\/ Occupancy\n attributes.push_back(0x0010); \/\/ PIR Occupied To Unoccupied Delay\n }\n else if (suffix == RStateLightLevel)\n {\n clusterId = ILLUMINANCE_MEASUREMENT_CLUSTER_ID;\n attributes.push_back(0x0000); \/\/ Measured Value\n }\n else if (suffix == RStateConsumption)\n {\n clusterId = METERING_CLUSTER_ID;\n attributes.push_back(0x0000); \/\/ Curent Summation Delivered\n attributes.push_back(0x0400); \/\/ Instantaneous Demand\n }\n else if (suffix == RStatePower)\n {\n clusterId = ELECTRICAL_MEASUREMENT_CLUSTER_ID;\n attributes.push_back(0x050b); \/\/ Active Power\n item = r->item(RAttrModelId);\n if (! item->toString().startsWith(QLatin1String(\"Plug\"))) \/\/ OSRAM plug\n {\n attributes.push_back(0x0505); \/\/ RMS Voltage\n attributes.push_back(0x0508); \/\/ RMS Current\n }\n }\n else if (suffix == RAttrModelId)\n {\n item = r->item(RAttrModelId);\n if (item && (item->toString().isEmpty() || item->toString() == QLatin1String(\"unknown\") ||\n (item->lastSet().secsTo(now) > READ_MODEL_ID_INTERVAL && item->toString().startsWith(\"FLS-A\")) \/\/ dynamic model ids\n ))\n {\n clusterId = BASIC_CLUSTER_ID;\n \/\/attributes.push_back(0x0004); \/\/ manufacturer\n attributes.push_back(0x0005); \/\/ model id\n }\n }\n else if (suffix == RAttrSwVersion && lightNode)\n {\n item = r->item(RAttrSwVersion);\n if (item && (item->toString().isEmpty() ||\n (item->lastSet().secsTo(now) > READ_SWBUILD_ID_INTERVAL))) \/\/ dynamic\n {\n\n if (lightNode->manufacturerCode() == VENDOR_UBISYS ||\n lightNode->manufacturerCode() == VENDOR_EMBER ||\n lightNode->manufacturerCode() == VENDOR_120B ||\n lightNode->manufacturerCode() == VENDOR_115F ||\n lightNode->manufacturer().startsWith(QLatin1String(\"Climax\")))\n {\n if (item->toString().isEmpty())\n {\n attributes.push_back(0x0006); \/\/ date code\n clusterId = BASIC_CLUSTER_ID;\n }\n }\n else\n {\n if (item->toString().isEmpty() ||\n lightNode->manufacturerCode() == VENDOR_XAL ||\n lightNode->manufacturerCode() == VENDOR_DDEL)\n {\n attributes.push_back(0x4000); \/\/ sw build id\n clusterId = BASIC_CLUSTER_ID;\n }\n }\n }\n }\n\n size_t fresh = 0;\n const int reportWaitTime = 360;\n for (quint16 attrId : attributes)\n {\n \/\/ force polling after node becomes reachable, since reporting might not be active\n if (dtReachable < reportWaitTime)\n {\n break;\n }\n\n NodeValue &val = restNode->getZclValue(clusterId, attrId);\n\n if (val.timestampLastReport.isValid() && val.timestampLastReport.secsTo(now) < reportWaitTime)\n {\n fresh++;\n }\n }\n\n \/\/ check that cluster exists on endpoint\n if (clusterId != 0xffff)\n {\n bool found = false;\n deCONZ::SimpleDescriptor sd;\n if (restNode->node()->copySimpleDescriptor(pitem.endpoint, &sd) == 0)\n {\n for (const auto &cl : sd.inClusters())\n {\n if (cl.id() == clusterId)\n {\n found = true;\n break;\n }\n }\n }\n\n if (!found)\n {\n DBG_Printf(DBG_INFO, \"Poll APS request to 0x%016llX cluster: 0x%04X dropped, cluster doesn't exist\\n\", pitem.address.ext(), clusterId);\n clusterId = 0xffff;\n }\n }\n\n if (clusterId != 0xffff && fresh > 0 && fresh == attributes.size())\n {\n DBG_Printf(DBG_INFO, \"Poll APS request to 0x%016llX cluster: 0x%04X dropped, values are fresh enough\\n\", pitem.address.ext(), clusterId);\n suffix = nullptr; \/\/ clear\n timer->start(100);\n }\n else if (!attributes.empty() && clusterId != 0xffff &&\n plugin->readAttributes(restNode, pitem.endpoint, clusterId, attributes))\n {\n pollState = StateWait;\n \/\/ TODO this hack to get aps request id\n DBG_Assert(plugin->tasks.back().taskType == TaskReadAttributes);\n apsReqId = plugin->tasks.back().req.id();\n dstAddr = pitem.address;\n timer->start(60 * 1000); \/\/ wait for confirm\n suffix = nullptr; \/\/ clear\n DBG_Printf(DBG_INFO_L2, \"Poll APS request %u to 0x%016llX cluster: 0x%04X\\n\", apsReqId, dstAddr.ext(), clusterId);\n }\n else if (suffix)\n {\n suffix = nullptr; \/\/ clear\n timer->start(100);\n }\n else\n {\n if (clusterId != 0xffff)\n {\n DBG_Printf(DBG_INFO, \"Poll APS request to 0x%016llX cluster: 0x%04X dropped\\n\", pitem.address.ext(), clusterId);\n }\n timer->start(100);\n items.front() = items.back();\n items.pop_back();\n }\n}\n<|endoftext|>"} {"text":"\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"linux\/perf.hpp\"\n\nusing std::list;\nusing std::ostringstream;\nusing std::set;\nusing std::string;\nusing std::vector;\n\nusing namespace process;\n\nnamespace perf {\n\n\/\/ Delimiter for fields in perf stat output.\nconst string PERF_DELIMITER = \",\";\n\n\/\/ Use an empty string as the key for the parse output when sampling a\n\/\/ set of pids. No valid cgroup can be an empty string.\nconst string PIDS_KEY = \"\";\n\nnamespace internal {\n\nstring command(\n const set& events,\n const set& cgroups,\n const Duration& duration)\n{\n ostringstream command;\n\n command << \"perf stat -x\" << PERF_DELIMITER << \" -a\";\n command << \" --log-fd 1\"; \/\/ Ensure all output goes to stdout.\n \/\/ Nested loop to produce all pairings of event and cgroup.\n foreach (const string& event, events) {\n foreach (const string& cgroup, cgroups) {\n command << \" --event \" << event\n << \" --cgroup \" << cgroup;\n }\n }\n command << \" -- sleep \" << stringify(duration.secs());\n\n return command.str();\n}\n\n\nstring command(\n const set& events,\n const string& cgroup,\n const Duration& duration)\n{\n set cgroups;\n cgroups.insert(cgroup);\n\n return command(events, cgroups, duration);\n}\n\n\nstring command(\n const set& events,\n const set& pids,\n const Duration& duration)\n{\n ostringstream command;\n\n command << \"perf stat -x\" << PERF_DELIMITER << \" -a\";\n command << \" --log-fd 1\"; \/\/ Ensure all output goes to stdout.\n command << \" --event \" << strings::join(\",\", events);\n command << \" --pid \" << strings::join(\",\", pids);\n command << \" -- sleep \" << stringify(duration.secs());\n\n return command.str();\n}\n\n\n\/\/ Normalize a perf event name. After normalization the event name\n\/\/ should match an event field in the PerfStatistics protobuf.\ninline string normalize(const string& s)\n{\n string lower = strings::lower(s);\n return strings::replace(lower, \"-\", \"_\");\n}\n\n\nclass PerfSampler : public Process\n{\npublic:\n PerfSampler(const string& _command, const Duration& _duration)\n : command(_command), duration(_duration) {}\n\n virtual ~PerfSampler() {}\n\n Future> future()\n {\n return promise.future();\n }\n\nprotected:\n virtual void initialize()\n {\n \/\/ Stop when no one cares.\n promise.future().onDiscard(lambda::bind(\n static_cast(terminate), self(), true));\n\n if (duration < Seconds(0)) {\n promise.fail(\"Perf sample duration cannot be negative: '\" +\n stringify(duration.secs()) + \"'\");\n terminate(self());\n return;\n }\n\n start = Clock::now();\n\n sample();\n }\n\n virtual void finalize()\n {\n discard(output);\n\n \/\/ Kill the perf process if it's still running.\n if (perf.isSome() && perf.get().status().isPending()) {\n kill(perf.get().pid(), SIGKILL);\n }\n\n promise.discard();\n }\n\nprivate:\n void sample()\n {\n Try _perf = subprocess(\n command,\n Subprocess::PIPE(),\n Subprocess::PIPE(),\n Subprocess::PIPE());\n\n if (_perf.isError()) {\n promise.fail(\"Failed to launch perf process: \" + _perf.error());\n terminate(self());\n return;\n }\n perf = _perf.get();\n\n \/\/ Start reading from stdout and stderr now. We don't use stderr\n \/\/ but must read from it to avoid the subprocess blocking on the\n \/\/ pipe.\n output.push_back(process::io::read(perf.get().out().get()));\n output.push_back(process::io::read(perf.get().err().get()));\n\n \/\/ Wait for the process to exit.\n perf.get().status()\n .onAny(defer(self(), &Self::_sample, lambda::_1));\n }\n\n void _sample(const Future>& status)\n {\n if (!status.isReady()) {\n promise.fail(\"Failed to get exit status of perf process: \" +\n (status.isFailed() ? status.failure() : \"discarded\"));\n terminate(self());\n return;\n }\n\n if (status.get().get() != 0) {\n promise.fail(\"Failed to execute perf, exit status: \" +\n stringify(WEXITSTATUS(status.get().get())));\n\n terminate(self());\n return;\n }\n\n \/\/ Wait until we collect all output.\n collect(output).onAny(defer(self(), &Self::__sample, lambda::_1));\n }\n\n void __sample(const Future>& future)\n {\n if (!future.isReady()) {\n promise.fail(\"Failed to collect output of perf process: \" +\n (future.isFailed() ? future.failure() : \"discarded\"));\n terminate(self());\n return;\n }\n\n \/\/ Parse output from stdout.\n Try> parse =\n perf::parse(output.front().get());\n if (parse.isError()) {\n promise.fail(\"Failed to parse perf output: \" + parse.error());\n terminate(self());\n return;\n }\n\n \/\/ Create a non-const copy from the Try<> so we can set the\n \/\/ timestamp and duration.\n hashmap statistics = parse.get();\n foreachvalue (mesos::PerfStatistics& s, statistics) {\n s.set_timestamp(start.secs());\n s.set_duration(duration.secs());\n }\n\n promise.set(statistics);\n terminate(self());\n return;\n }\n\n const string command;\n const Duration duration;\n Time start;\n Option perf;\n Promise> promise;\n list> output;\n};\n\n\n\/\/ Helper to select a single key from the hashmap of perf statistics.\nFuture select(\n const string& key,\n const hashmap& statistics)\n{\n return statistics.get(key).get();\n}\n\n} \/\/ namespace internal {\n\n\nFuture sample(\n const set& events,\n pid_t pid,\n const Duration& duration)\n{\n set pids;\n pids.insert(pid);\n return sample(events, pids, duration);\n}\n\n\nFuture sample(\n const set& events,\n const set& pids,\n const Duration& duration)\n{\n if (!supported()) {\n return Failure(\"Perf is not supported\");\n }\n\n const string command = internal::command(events, pids, duration);\n internal::PerfSampler* sampler = new internal::PerfSampler(command, duration);\n Future> future = sampler->future();\n spawn(sampler, true);\n return future\n .then(lambda::bind(&internal::select, PIDS_KEY, lambda::_1));\n}\n\n\nFuture sample(\n const set& events,\n const string& cgroup,\n const Duration& duration)\n{\n set cgroups;\n cgroups.insert(cgroup);\n return sample(events, cgroups, duration)\n .then(lambda::bind(&internal::select, cgroup, lambda::_1));\n}\n\n\nFuture> sample(\n const set& events,\n const set& cgroups,\n const Duration& duration)\n{\n if (!supported()) {\n return Failure(\"Perf is not supported\");\n }\n\n const string command = internal::command(events, cgroups, duration);\n internal::PerfSampler* sampler = new internal::PerfSampler(command, duration);\n Future> future = sampler->future();\n spawn(sampler, true);\n return future;\n}\n\n\nbool valid(const set& events)\n{\n ostringstream command;\n\n \/\/ Log everything to stderr which is then redirected to \/dev\/null.\n command << \"perf stat --log-fd 2\";\n foreach (const string& event, events) {\n command << \" --event \" << event;\n }\n command << \" true 2>\/dev\/null\";\n\n return (os::system(command.str()) == 0);\n}\n\n\nbool supported()\n{\n \/\/ Require Linux kernel version >= 2.6.38 for \"-x\" and >= 2.6.39 for\n \/\/ \"--cgroup\"\n Try release = os::release();\n\n \/\/ This is not expected to ever be an Error.\n CHECK_SOME(release);\n\n return release.get() >= Version(2, 6, 39);\n}\n\n\nTry> parse(const string& output)\n{\n hashmap statistics;\n\n foreach (const string& line, strings::tokenize(output, \"\\n\")) {\n vector tokens = strings::tokenize(line, PERF_DELIMITER);\n \/\/ Expected format for an output line is either:\n \/\/ value,event (when sampling pids)\n \/\/ value,event,cgroup (when sampling a cgroup)\n \/\/ assuming PERF_DELIMITER = \",\".\n if (tokens.size() < 2 || tokens.size() > 3) {\n return Error(\"Unexpected perf output at line: \" + line);\n }\n\n const string value = tokens[0];\n const string event = internal::normalize(tokens[1]);\n \/\/ Use the special PIDS_KEY when sampling pids.\n const string cgroup = (tokens.size() == 3 ? tokens[2] : PIDS_KEY);\n\n if (!statistics.contains(cgroup)) {\n statistics.put(cgroup, mesos::PerfStatistics());\n }\n\n const google::protobuf::Reflection* reflection =\n statistics[cgroup].GetReflection();\n const google::protobuf::FieldDescriptor* field =\n statistics[cgroup].GetDescriptor()->FindFieldByName(event);\n if (!field) {\n return Error(\"Unexpected perf output at line: \" + line);\n }\n\n if (value == \"\") {\n LOG(WARNING) << \"Unsupported perf counter, ignoring: \" << line;\n continue;\n }\n\n switch (field->type()) {\n case google::protobuf::FieldDescriptor::TYPE_DOUBLE:\n {\n Try number =\n (value == \"\") ? 0 : numify(value);\n\n if (number.isError()) {\n return Error(\"Unable to parse perf value at line: \" + line);\n }\n\n reflection->SetDouble(&(statistics[cgroup]), field, number.get());\n break;\n }\n case google::protobuf::FieldDescriptor::TYPE_UINT64:\n {\n Try number =\n (value == \"\") ? 0 : numify(value);\n\n if (number.isError()) {\n return Error(\"Unable to parse perf value at line: \" + line);\n }\n\n reflection->SetUInt64(&(statistics[cgroup]), field, number.get());\n break;\n }\n default:\n return Error(\"Unsupported perf field type at line: \" + line);\n }\n }\n\n return statistics;\n}\n\n} \/\/ namespace perf {\nUsed the argv version of subprocess for linux perf utilities.\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"linux\/perf.hpp\"\n\nusing std::list;\nusing std::ostringstream;\nusing std::set;\nusing std::string;\nusing std::vector;\n\nusing namespace process;\n\nnamespace perf {\n\n\/\/ Delimiter for fields in perf stat output.\nconst string PERF_DELIMITER = \",\";\n\n\/\/ Use an empty string as the key for the parse output when sampling a\n\/\/ set of pids. No valid cgroup can be an empty string.\nconst string PIDS_KEY = \"\";\n\nnamespace internal {\n\nvector argv(\n const set& events,\n const set& cgroups,\n const Duration& duration)\n{\n vector argv = {\n \"perf\", \"stat\",\n\n \/\/ System-wide collection from all CPUs.\n \"--all-cpus\",\n\n \/\/ Print counts using a CSV-style output to make it easy to import\n \/\/ directly into spreadsheets. Columns are separated by the string\n \/\/ specified in PERF_DELIMITER.\n \"--field-separator\", PERF_DELIMITER,\n\n \/\/ Ensure all output goes to stdout.\n \"--log-fd\", \"1\"\n };\n\n \/\/ Nested loop to produce all pairings of event and cgroup.\n foreach (const string& event, events) {\n foreach (const string& cgroup, cgroups) {\n argv.push_back(\"--event\");\n argv.push_back(event);\n argv.push_back(\"--cgroup\");\n argv.push_back(cgroup);\n }\n }\n\n argv.push_back(\"--\");\n argv.push_back(\"sleep\");\n argv.push_back(stringify(duration.secs()));\n\n return argv;\n}\n\n\nvector argv(\n const set& events,\n const string& cgroup,\n const Duration& duration)\n{\n set cgroups;\n cgroups.insert(cgroup);\n\n return argv(events, cgroups, duration);\n}\n\n\nvector argv(\n const set& events,\n const set& pids,\n const Duration& duration)\n{\n vector argv = {\n \"perf\", \"stat\",\n\n \/\/ System-wide collection from all CPUs.\n \"--all-cpus\",\n\n \/\/ Print counts using a CSV-style output to make it easy to import\n \/\/ directly into spreadsheets. Columns are separated by the string\n \/\/ specified in PERF_DELIMITER.\n \"--field-separator\", PERF_DELIMITER,\n\n \/\/ Ensure all output goes to stdout.\n \"--log-fd\", \"1\",\n\n \"--event\", strings::join(\",\", events),\n \"--pid\", strings::join(\",\", pids),\n \"--\",\n \"sleep\", stringify(duration.secs())\n };\n\n return argv;\n}\n\n\n\/\/ Normalize a perf event name. After normalization the event name\n\/\/ should match an event field in the PerfStatistics protobuf.\ninline string normalize(const string& s)\n{\n string lower = strings::lower(s);\n return strings::replace(lower, \"-\", \"_\");\n}\n\n\nclass PerfSampler : public Process\n{\npublic:\n PerfSampler(const vector& _argv, const Duration& _duration)\n : argv(_argv), duration(_duration) {}\n\n virtual ~PerfSampler() {}\n\n Future> future()\n {\n return promise.future();\n }\n\nprotected:\n virtual void initialize()\n {\n \/\/ Stop when no one cares.\n promise.future().onDiscard(lambda::bind(\n static_cast(terminate), self(), true));\n\n if (duration < Seconds(0)) {\n promise.fail(\"Perf sample duration cannot be negative: '\" +\n stringify(duration.secs()) + \"'\");\n terminate(self());\n return;\n }\n\n start = Clock::now();\n\n sample();\n }\n\n virtual void finalize()\n {\n discard(output);\n\n \/\/ Kill the perf process if it's still running.\n if (perf.isSome() && perf.get().status().isPending()) {\n kill(perf.get().pid(), SIGKILL);\n }\n\n promise.discard();\n }\n\nprivate:\n void sample()\n {\n Try _perf = subprocess(\n \"perf\",\n argv,\n Subprocess::PIPE(),\n Subprocess::PIPE(),\n Subprocess::PIPE());\n\n if (_perf.isError()) {\n promise.fail(\"Failed to launch perf process: \" + _perf.error());\n terminate(self());\n return;\n }\n perf = _perf.get();\n\n \/\/ Start reading from stdout and stderr now. We don't use stderr\n \/\/ but must read from it to avoid the subprocess blocking on the\n \/\/ pipe.\n output.push_back(process::io::read(perf.get().out().get()));\n output.push_back(process::io::read(perf.get().err().get()));\n\n \/\/ Wait for the process to exit.\n perf.get().status()\n .onAny(defer(self(), &Self::_sample, lambda::_1));\n }\n\n void _sample(const Future>& status)\n {\n if (!status.isReady()) {\n promise.fail(\"Failed to get exit status of perf process: \" +\n (status.isFailed() ? status.failure() : \"discarded\"));\n terminate(self());\n return;\n }\n\n if (status.get().get() != 0) {\n promise.fail(\"Failed to execute perf, exit status: \" +\n stringify(WEXITSTATUS(status.get().get())));\n\n terminate(self());\n return;\n }\n\n \/\/ Wait until we collect all output.\n collect(output).onAny(defer(self(), &Self::__sample, lambda::_1));\n }\n\n void __sample(const Future>& future)\n {\n if (!future.isReady()) {\n promise.fail(\"Failed to collect output of perf process: \" +\n (future.isFailed() ? future.failure() : \"discarded\"));\n terminate(self());\n return;\n }\n\n \/\/ Parse output from stdout.\n Try> parse =\n perf::parse(output.front().get());\n if (parse.isError()) {\n promise.fail(\"Failed to parse perf output: \" + parse.error());\n terminate(self());\n return;\n }\n\n \/\/ Create a non-const copy from the Try<> so we can set the\n \/\/ timestamp and duration.\n hashmap statistics = parse.get();\n foreachvalue (mesos::PerfStatistics& s, statistics) {\n s.set_timestamp(start.secs());\n s.set_duration(duration.secs());\n }\n\n promise.set(statistics);\n terminate(self());\n return;\n }\n\n const vector argv;\n const Duration duration;\n Time start;\n Option perf;\n Promise> promise;\n list> output;\n};\n\n\n\/\/ Helper to select a single key from the hashmap of perf statistics.\nFuture select(\n const string& key,\n const hashmap& statistics)\n{\n return statistics.get(key).get();\n}\n\n} \/\/ namespace internal {\n\n\nFuture sample(\n const set& events,\n pid_t pid,\n const Duration& duration)\n{\n set pids;\n pids.insert(pid);\n return sample(events, pids, duration);\n}\n\n\nFuture sample(\n const set& events,\n const set& pids,\n const Duration& duration)\n{\n if (!supported()) {\n return Failure(\"Perf is not supported\");\n }\n\n const vector argv = internal::argv(events, pids, duration);\n internal::PerfSampler* sampler = new internal::PerfSampler(argv, duration);\n Future> future = sampler->future();\n spawn(sampler, true);\n return future\n .then(lambda::bind(&internal::select, PIDS_KEY, lambda::_1));\n}\n\n\nFuture sample(\n const set& events,\n const string& cgroup,\n const Duration& duration)\n{\n set cgroups;\n cgroups.insert(cgroup);\n return sample(events, cgroups, duration)\n .then(lambda::bind(&internal::select, cgroup, lambda::_1));\n}\n\n\nFuture> sample(\n const set& events,\n const set& cgroups,\n const Duration& duration)\n{\n if (!supported()) {\n return Failure(\"Perf is not supported\");\n }\n\n const vector argv = internal::argv(events, cgroups, duration);\n internal::PerfSampler* sampler = new internal::PerfSampler(argv, duration);\n Future> future = sampler->future();\n spawn(sampler, true);\n return future;\n}\n\n\nbool valid(const set& events)\n{\n ostringstream command;\n\n \/\/ Log everything to stderr which is then redirected to \/dev\/null.\n command << \"perf stat --log-fd 2\";\n foreach (const string& event, events) {\n command << \" --event \" << event;\n }\n command << \" true 2>\/dev\/null\";\n\n return (os::system(command.str()) == 0);\n}\n\n\nbool supported()\n{\n \/\/ Require Linux kernel version >= 2.6.38 for \"-x\" and >= 2.6.39 for\n \/\/ \"--cgroup\"\n Try release = os::release();\n\n \/\/ This is not expected to ever be an Error.\n CHECK_SOME(release);\n\n return release.get() >= Version(2, 6, 39);\n}\n\n\nTry> parse(const string& output)\n{\n hashmap statistics;\n\n foreach (const string& line, strings::tokenize(output, \"\\n\")) {\n vector tokens = strings::tokenize(line, PERF_DELIMITER);\n \/\/ Expected format for an output line is either:\n \/\/ value,event (when sampling pids)\n \/\/ value,event,cgroup (when sampling a cgroup)\n \/\/ assuming PERF_DELIMITER = \",\".\n if (tokens.size() < 2 || tokens.size() > 3) {\n return Error(\"Unexpected perf output at line: \" + line);\n }\n\n const string value = tokens[0];\n const string event = internal::normalize(tokens[1]);\n \/\/ Use the special PIDS_KEY when sampling pids.\n const string cgroup = (tokens.size() == 3 ? tokens[2] : PIDS_KEY);\n\n if (!statistics.contains(cgroup)) {\n statistics.put(cgroup, mesos::PerfStatistics());\n }\n\n const google::protobuf::Reflection* reflection =\n statistics[cgroup].GetReflection();\n const google::protobuf::FieldDescriptor* field =\n statistics[cgroup].GetDescriptor()->FindFieldByName(event);\n if (!field) {\n return Error(\"Unexpected perf output at line: \" + line);\n }\n\n if (value == \"\") {\n LOG(WARNING) << \"Unsupported perf counter, ignoring: \" << line;\n continue;\n }\n\n switch (field->type()) {\n case google::protobuf::FieldDescriptor::TYPE_DOUBLE:\n {\n Try number =\n (value == \"\") ? 0 : numify(value);\n\n if (number.isError()) {\n return Error(\"Unable to parse perf value at line: \" + line);\n }\n\n reflection->SetDouble(&(statistics[cgroup]), field, number.get());\n break;\n }\n case google::protobuf::FieldDescriptor::TYPE_UINT64:\n {\n Try number =\n (value == \"\") ? 0 : numify(value);\n\n if (number.isError()) {\n return Error(\"Unable to parse perf value at line: \" + line);\n }\n\n reflection->SetUInt64(&(statistics[cgroup]), field, number.get());\n break;\n }\n default:\n return Error(\"Unsupported perf field type at line: \" + line);\n }\n }\n\n return statistics;\n}\n\n} \/\/ namespace perf {\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2020 Ultimaker B.V.\n\/\/ CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \/\/For std::partition_copy and std::min_element.\n#include \n\n#include \"WallToolPaths.h\"\n\n#include \"SkeletalTrapezoidation.h\"\n#include \"BeadingStrategy\/BeadingOrderOptimizer.h\"\n#include \"utils\/SparsePointGrid.h\" \/\/To stitch the inner contour.\n#include \"utils\/polygonUtils.h\"\n#include \"ExtruderTrain.h\"\n\nnamespace cura\n{\nconstexpr coord_t transition_length_multiplier = 2;\n\nWallToolPaths::WallToolPaths(const Polygons& outline, const coord_t nominal_bead_width, const size_t inset_count,\n const Settings& settings)\n : outline(outline)\n , bead_width_0(nominal_bead_width)\n , bead_width_x(nominal_bead_width)\n , inset_count(inset_count)\n , strategy_type(settings.get(\"beading_strategy_type\"))\n , print_thin_walls(settings.get(\"fill_outline_gaps\"))\n , min_feature_size(settings.get(\"min_feature_size\"))\n , min_bead_width(settings.get(\"min_bead_width\"))\n , small_area_length(INT2MM(static_cast(nominal_bead_width) \/ 2))\n , transition_length(transition_length_multiplier * nominal_bead_width)\n , toolpaths_generated(false)\n , settings(settings)\n{\n}\n\nWallToolPaths::WallToolPaths(const Polygons& outline, const coord_t bead_width_0, const coord_t bead_width_x,\n const size_t inset_count, const Settings& settings)\n : outline(outline)\n , bead_width_0(bead_width_0)\n , bead_width_x(bead_width_x)\n , inset_count(inset_count)\n , strategy_type(settings.get(\"beading_strategy_type\"))\n , print_thin_walls(settings.get(\"fill_outline_gaps\"))\n , min_feature_size(settings.get(\"min_feature_size\"))\n , min_bead_width(settings.get(\"min_bead_width\"))\n , small_area_length(INT2MM(static_cast(bead_width_0) \/ 2))\n , transition_length(transition_length_multiplier * bead_width_0)\n , toolpaths_generated(false)\n , settings(settings)\n{\n}\n\nconst VariableWidthPaths& WallToolPaths::generate()\n{\n constexpr coord_t smallest_segment = 50;\n constexpr coord_t allowed_distance = 50;\n constexpr coord_t epsilon_offset = (allowed_distance \/ 2) - 1;\n constexpr float transitioning_angle = 0.5;\n constexpr coord_t discretization_step_size = 200;\n\n \/\/ Simplify outline for boost::voronoi consumption. Absolutely no self intersections or near-self intersections allowed:\n \/\/ TODO: Open question: Does this indeed fix all (or all-but-one-in-a-million) cases for manifold but otherwise possibly complex polygons?\n Polygons prepared_outline = outline.offset(-epsilon_offset).offset(epsilon_offset);\n prepared_outline.simplify(smallest_segment, allowed_distance);\n PolygonUtils::fixSelfIntersections(epsilon_offset, prepared_outline);\n prepared_outline.removeDegenerateVerts();\n prepared_outline.removeColinearEdges();\n prepared_outline.removeSmallAreas(small_area_length * small_area_length, false);\n\n if (prepared_outline.area() > 0)\n {\n const size_t max_bead_count = 2 * inset_count;\n const auto beading_strat = std::unique_ptr(BeadingStrategyFactory::makeStrategy(\n strategy_type, bead_width_0, bead_width_x, transition_length, transitioning_angle, print_thin_walls, min_bead_width,\n min_feature_size, max_bead_count));\n const coord_t transition_filter_dist = beading_strat->optimal_width * 5;\n SkeletalTrapezoidation wall_maker(prepared_outline, *beading_strat, beading_strat->transitioning_angle, discretization_step_size, transition_filter_dist);\n wall_maker.generateToolpaths(toolpaths);\n computeInnerContour();\n }\n simplifyToolPaths(toolpaths, settings);\n\n removeEmptyToolPaths(toolpaths);\n toolpaths_generated = true;\n return toolpaths;\n}\n\nvoid WallToolPaths::simplifyToolPaths(VariableWidthPaths& toolpaths, const Settings& settings)\n{\n for (size_t toolpaths_idx = 0; toolpaths_idx < toolpaths.size(); ++toolpaths_idx)\n {\n const ExtruderTrain& train_wall = settings.get(toolpaths_idx == 0 ? \"wall_0_extruder_nr\" : \"wall_x_extruder_nr\");\n const coord_t maximum_resolution = train_wall.settings.get(\"meshfix_maximum_resolution\");\n const coord_t maximum_deviation = train_wall.settings.get(\"meshfix_maximum_deviation\");\n const coord_t maximum_extrusion_area_deviation = train_wall.settings.get(\"meshfix_maximum_extrusion_area_deviation\"); \/\/ unit: μm²\n for (auto& line : toolpaths[toolpaths_idx])\n {\n line.simplify(maximum_resolution, maximum_deviation, maximum_extrusion_area_deviation);\n }\n }\n}\n\nconst VariableWidthPaths& WallToolPaths::getToolPaths()\n{\n if (!toolpaths_generated)\n {\n return generate();\n }\n return toolpaths;\n}\n\nvoid WallToolPaths::computeInnerContour()\n{\n \/\/We'll remove all 0-width paths from the original toolpaths and store them separately as polygons.\n VariableWidthPaths actual_toolpaths;\n actual_toolpaths.reserve(toolpaths.size()); \/\/A bit too much, but the correct order of magnitude.\n VariableWidthPaths contour_paths;\n contour_paths.reserve(toolpaths.size() \/ inset_count);\n std::partition_copy(toolpaths.begin(), toolpaths.end(), std::back_inserter(actual_toolpaths), std::back_inserter(contour_paths),\n [](const VariableWidthLines& path)\n {\n for(const ExtrusionLine& line : path)\n {\n for(const ExtrusionJunction& junction : line.junctions)\n {\n return junction.w != 0; \/\/On the first actual junction, decide: If it's got 0 width, this is a contour. Otherwise it is an actual toolpath.\n }\n }\n return true; \/\/No junctions with any vertices? Classify it as a toolpath then.\n });\n toolpaths = std::move(actual_toolpaths); \/\/Filtered out the 0-width paths.\n\n \/\/Now convert the contour_paths to Polygons to denote the inner contour of the walled areas.\n inner_contour.clear();\n\n \/\/We're going to have to stitch these paths since not all walls may be closed contours.\n \/\/Since these walls have 0 width they should theoretically be closed. But there may be rounding errors.\n const coord_t minimum_line_width = bead_width_0 \/ 2;\n stitchContours(contour_paths, minimum_line_width, inner_contour);\n\n \/\/The output walls from the skeletal trapezoidation have no known winding order, especially if they are joined together from polylines.\n \/\/They can be in any direction, clockwise or counter-clockwise, regardless of whether the shapes are positive or negative.\n \/\/To get a correct shape, we need to make the outside contour positive and any holes inside negative.\n \/\/This can be done by applying the even-odd rule to the shape. This rule is not sensitive to the winding order of the polygon.\n \/\/The even-odd rule would be incorrect if the polygon self-intersects, but that should never be generated by the skeletal trapezoidation.\n inner_contour = inner_contour.unionPolygons(Polygons(), ClipperLib::pftEvenOdd);\n}\n\nconst Polygons& WallToolPaths::getInnerContour()\n{\n if (!toolpaths_generated && inset_count > 0)\n {\n generate();\n }\n else if(inset_count == 0)\n {\n return outline;\n }\n return inner_contour;\n}\n\nbool WallToolPaths::removeEmptyToolPaths(VariableWidthPaths& toolpaths)\n{\n toolpaths.erase(std::remove_if(toolpaths.begin(), toolpaths.end(), [](const VariableWidthLines& lines)\n {\n return lines.empty();\n }), toolpaths.end());\n return toolpaths.empty();\n}\n\nvoid WallToolPaths::stitchContours(const VariableWidthPaths& input, const coord_t stitch_distance, Polygons& output) const\n{\n \/\/Create a bucket grid to find endpoints that are close together.\n struct ExtrusionLineStartLocator\n {\n Point operator()(const ExtrusionLine* line)\n {\n return Point(line->junctions.front().p);\n }\n };\n struct ExtrusionLineEndLocator\n {\n Point operator()(const ExtrusionLine* line)\n {\n return Point(line->junctions.back().p);\n }\n };\n SparsePointGrid line_starts(stitch_distance); \/\/Only find endpoints closer than minimum_line_width, so we can't ever accidentally make crossing contours.\n SparsePointGrid line_ends(stitch_distance);\n for(const VariableWidthLines& path : input)\n {\n for(const ExtrusionLine& line : path)\n {\n line_starts.insert(&line);\n line_ends.insert(&line);\n }\n }\n \/\/Then go through all lines and construct chains of polylines if the endpoints are nearby.\n std::unordered_set processed_lines; \/\/Track which lines were already processed to not process them twice.\n for(const VariableWidthLines& path : input)\n {\n for(const ExtrusionLine& line : path)\n {\n if(processed_lines.find(&line) != processed_lines.end()) \/\/We already added this line before. It got added as a nearby line.\n {\n continue;\n }\n \/\/We'll create a chain of polylines that get joined together. We can add polylines on both ends!\n std::deque chain;\n std::deque is_reversed; \/\/Lines could need to be inserted in reverse. Must coincide with the `chain` deque.\n const ExtrusionLine* nearest = &line; \/\/At every iteration, add the polyline that joins together most closely.\n bool nearest_reverse = false; \/\/Whether the next line to insert must be inserted in reverse.\n bool nearest_before = false; \/\/Whether the next line to insert must be inserted in the front of the chain.\n while(nearest)\n {\n if(processed_lines.find(nearest) != processed_lines.end())\n {\n break; \/\/Looping. This contour is already processed.\n }\n processed_lines.insert(nearest);\n if(nearest_before)\n {\n chain.push_front(nearest);\n is_reversed.push_front(nearest_reverse);\n }\n else\n {\n chain.push_back(nearest);\n is_reversed.push_back(nearest_reverse);\n }\n\n \/\/Find any nearby lines to attach. Look on both ends of our current chain and find both ends of polylines.\n const Point chain_start = is_reversed.front() ? chain.front()->junctions.back().p : chain.front()->junctions.front().p;\n const Point chain_end = is_reversed.back() ? chain.back()->junctions.front().p : chain.back()->junctions.back().p;\n std::vector starts_near_start = line_starts.getNearby(chain_start, stitch_distance);\n std::vector ends_near_start = line_ends.getNearby(chain_start, stitch_distance);\n std::vector starts_near_end = line_starts.getNearby(chain_end, stitch_distance);\n std::vector ends_near_end = line_ends.getNearby(chain_end, stitch_distance);\n\n nearest = nullptr;\n coord_t nearest_dist2 = std::numeric_limits::max();\n for(const ExtrusionLine* candidate : starts_near_start)\n {\n if(processed_lines.find(candidate) != processed_lines.end())\n {\n continue; \/\/Already processed this line before. It's linked to something else.\n }\n const coord_t dist2 = vSize2(candidate->junctions.front().p - chain_start);\n if(dist2 < nearest_dist2)\n {\n nearest = candidate;\n nearest_dist2 = dist2;\n nearest_reverse = true;\n nearest_before = true;\n }\n }\n for(const ExtrusionLine* candidate : ends_near_start)\n {\n if(processed_lines.find(candidate) != processed_lines.end())\n {\n continue;\n }\n const coord_t dist2 = vSize2(candidate->junctions.back().p - chain_start);\n if(dist2 < nearest_dist2)\n {\n nearest = candidate;\n nearest_dist2 = dist2;\n nearest_reverse = false;\n nearest_before = true;\n }\n }\n for(const ExtrusionLine* candidate : starts_near_end)\n {\n if(processed_lines.find(candidate) != processed_lines.end())\n {\n continue; \/\/Already processed this line before. It's linked to something else.\n }\n const coord_t dist2 = vSize2(candidate->junctions.front().p - chain_start);\n if(dist2 < nearest_dist2)\n {\n nearest = candidate;\n nearest_dist2 = dist2;\n nearest_reverse = false;\n nearest_before = false;\n }\n }\n for(const ExtrusionLine* candidate : ends_near_end)\n {\n if(processed_lines.find(candidate) != processed_lines.end())\n {\n continue;\n }\n const coord_t dist2 = vSize2(candidate->junctions.back().p - chain_start);\n if(dist2 < nearest_dist2)\n {\n nearest = candidate;\n nearest_dist2 = dist2;\n nearest_reverse = true;\n nearest_before = false;\n }\n }\n }\n\n \/\/Now serialize the entire chain into one polygon.\n output.emplace_back();\n for(size_t i = 0; i < chain.size(); ++i)\n {\n if(!is_reversed[i])\n {\n for(const ExtrusionJunction& junction : chain[i]->junctions)\n {\n output.back().add(junction.p);\n }\n }\n else\n {\n for(auto junction = chain[i]->junctions.rbegin(); junction != chain[i]->junctions.rend(); ++junction)\n {\n output.back().add(junction->p);\n }\n }\n }\n }\n }\n}\n\n\n} \/\/ namespace cura\nRemove some hardcoded values\/\/ Copyright (c) 2020 Ultimaker B.V.\n\/\/ CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \/\/For std::partition_copy and std::min_element.\n#include \n\n#include \"WallToolPaths.h\"\n\n#include \"SkeletalTrapezoidation.h\"\n#include \"BeadingStrategy\/BeadingOrderOptimizer.h\"\n#include \"utils\/SparsePointGrid.h\" \/\/To stitch the inner contour.\n#include \"utils\/polygonUtils.h\"\n#include \"ExtruderTrain.h\"\n\nnamespace cura\n{\nconstexpr coord_t transition_length_multiplier = 2;\n\nWallToolPaths::WallToolPaths(const Polygons& outline, const coord_t nominal_bead_width, const size_t inset_count,\n const Settings& settings)\n : outline(outline)\n , bead_width_0(nominal_bead_width)\n , bead_width_x(nominal_bead_width)\n , inset_count(inset_count)\n , strategy_type(settings.get(\"beading_strategy_type\"))\n , print_thin_walls(settings.get(\"fill_outline_gaps\"))\n , min_feature_size(settings.get(\"min_feature_size\"))\n , min_bead_width(settings.get(\"min_bead_width\"))\n , small_area_length(INT2MM(static_cast(nominal_bead_width) \/ 2))\n , transition_length(transition_length_multiplier * nominal_bead_width)\n , toolpaths_generated(false)\n , settings(settings)\n{\n}\n\nWallToolPaths::WallToolPaths(const Polygons& outline, const coord_t bead_width_0, const coord_t bead_width_x,\n const size_t inset_count, const Settings& settings)\n : outline(outline)\n , bead_width_0(bead_width_0)\n , bead_width_x(bead_width_x)\n , inset_count(inset_count)\n , strategy_type(settings.get(\"beading_strategy_type\"))\n , print_thin_walls(settings.get(\"fill_outline_gaps\"))\n , min_feature_size(settings.get(\"min_feature_size\"))\n , min_bead_width(settings.get(\"min_bead_width\"))\n , small_area_length(INT2MM(static_cast(bead_width_0) \/ 2))\n , transition_length(transition_length_multiplier * bead_width_0)\n , toolpaths_generated(false)\n , settings(settings)\n{\n}\n\nconst VariableWidthPaths& WallToolPaths::generate()\n{\n const coord_t smallest_segment = settings.get(\"meshfix_maximum_resolution\");\n const coord_t allowed_distance = settings.get(\"meshfix_maximum_deviation\");\n const coord_t epsilon_offset = (allowed_distance \/ 2) - 1;\n constexpr float transitioning_angle = 0.5;\n constexpr coord_t discretization_step_size = 200;\n\n \/\/ Simplify outline for boost::voronoi consumption. Absolutely no self intersections or near-self intersections allowed:\n \/\/ TODO: Open question: Does this indeed fix all (or all-but-one-in-a-million) cases for manifold but otherwise possibly complex polygons?\n Polygons prepared_outline = outline.offset(-epsilon_offset).offset(epsilon_offset);\n prepared_outline.simplify(smallest_segment, allowed_distance);\n PolygonUtils::fixSelfIntersections(epsilon_offset, prepared_outline);\n prepared_outline.removeDegenerateVerts();\n prepared_outline.removeColinearEdges();\n prepared_outline.removeSmallAreas(small_area_length * small_area_length, false);\n\n if (prepared_outline.area() > 0)\n {\n const size_t max_bead_count = 2 * inset_count;\n const auto beading_strat = std::unique_ptr(BeadingStrategyFactory::makeStrategy(\n strategy_type, bead_width_0, bead_width_x, transition_length, transitioning_angle, print_thin_walls, min_bead_width,\n min_feature_size, max_bead_count));\n const coord_t transition_filter_dist = beading_strat->optimal_width * 5;\n SkeletalTrapezoidation wall_maker(prepared_outline, *beading_strat, beading_strat->transitioning_angle, discretization_step_size, transition_filter_dist);\n wall_maker.generateToolpaths(toolpaths);\n computeInnerContour();\n }\n simplifyToolPaths(toolpaths, settings);\n\n removeEmptyToolPaths(toolpaths);\n toolpaths_generated = true;\n return toolpaths;\n}\n\nvoid WallToolPaths::simplifyToolPaths(VariableWidthPaths& toolpaths, const Settings& settings)\n{\n for (size_t toolpaths_idx = 0; toolpaths_idx < toolpaths.size(); ++toolpaths_idx)\n {\n const ExtruderTrain& train_wall = settings.get(toolpaths_idx == 0 ? \"wall_0_extruder_nr\" : \"wall_x_extruder_nr\");\n const coord_t maximum_resolution = train_wall.settings.get(\"meshfix_maximum_resolution\");\n const coord_t maximum_deviation = train_wall.settings.get(\"meshfix_maximum_deviation\");\n const coord_t maximum_extrusion_area_deviation = train_wall.settings.get(\"meshfix_maximum_extrusion_area_deviation\"); \/\/ unit: μm²\n for (auto& line : toolpaths[toolpaths_idx])\n {\n line.simplify(maximum_resolution, maximum_deviation, maximum_extrusion_area_deviation);\n }\n }\n}\n\nconst VariableWidthPaths& WallToolPaths::getToolPaths()\n{\n if (!toolpaths_generated)\n {\n return generate();\n }\n return toolpaths;\n}\n\nvoid WallToolPaths::computeInnerContour()\n{\n \/\/We'll remove all 0-width paths from the original toolpaths and store them separately as polygons.\n VariableWidthPaths actual_toolpaths;\n actual_toolpaths.reserve(toolpaths.size()); \/\/A bit too much, but the correct order of magnitude.\n VariableWidthPaths contour_paths;\n contour_paths.reserve(toolpaths.size() \/ inset_count);\n std::partition_copy(toolpaths.begin(), toolpaths.end(), std::back_inserter(actual_toolpaths), std::back_inserter(contour_paths),\n [](const VariableWidthLines& path)\n {\n for(const ExtrusionLine& line : path)\n {\n for(const ExtrusionJunction& junction : line.junctions)\n {\n return junction.w != 0; \/\/On the first actual junction, decide: If it's got 0 width, this is a contour. Otherwise it is an actual toolpath.\n }\n }\n return true; \/\/No junctions with any vertices? Classify it as a toolpath then.\n });\n toolpaths = std::move(actual_toolpaths); \/\/Filtered out the 0-width paths.\n\n \/\/Now convert the contour_paths to Polygons to denote the inner contour of the walled areas.\n inner_contour.clear();\n\n \/\/We're going to have to stitch these paths since not all walls may be closed contours.\n \/\/Since these walls have 0 width they should theoretically be closed. But there may be rounding errors.\n const coord_t minimum_line_width = bead_width_0 \/ 2;\n stitchContours(contour_paths, minimum_line_width, inner_contour);\n\n \/\/The output walls from the skeletal trapezoidation have no known winding order, especially if they are joined together from polylines.\n \/\/They can be in any direction, clockwise or counter-clockwise, regardless of whether the shapes are positive or negative.\n \/\/To get a correct shape, we need to make the outside contour positive and any holes inside negative.\n \/\/This can be done by applying the even-odd rule to the shape. This rule is not sensitive to the winding order of the polygon.\n \/\/The even-odd rule would be incorrect if the polygon self-intersects, but that should never be generated by the skeletal trapezoidation.\n inner_contour = inner_contour.unionPolygons(Polygons(), ClipperLib::pftEvenOdd);\n}\n\nconst Polygons& WallToolPaths::getInnerContour()\n{\n if (!toolpaths_generated && inset_count > 0)\n {\n generate();\n }\n else if(inset_count == 0)\n {\n return outline;\n }\n return inner_contour;\n}\n\nbool WallToolPaths::removeEmptyToolPaths(VariableWidthPaths& toolpaths)\n{\n toolpaths.erase(std::remove_if(toolpaths.begin(), toolpaths.end(), [](const VariableWidthLines& lines)\n {\n return lines.empty();\n }), toolpaths.end());\n return toolpaths.empty();\n}\n\nvoid WallToolPaths::stitchContours(const VariableWidthPaths& input, const coord_t stitch_distance, Polygons& output) const\n{\n \/\/Create a bucket grid to find endpoints that are close together.\n struct ExtrusionLineStartLocator\n {\n Point operator()(const ExtrusionLine* line)\n {\n return Point(line->junctions.front().p);\n }\n };\n struct ExtrusionLineEndLocator\n {\n Point operator()(const ExtrusionLine* line)\n {\n return Point(line->junctions.back().p);\n }\n };\n SparsePointGrid line_starts(stitch_distance); \/\/Only find endpoints closer than minimum_line_width, so we can't ever accidentally make crossing contours.\n SparsePointGrid line_ends(stitch_distance);\n for(const VariableWidthLines& path : input)\n {\n for(const ExtrusionLine& line : path)\n {\n line_starts.insert(&line);\n line_ends.insert(&line);\n }\n }\n \/\/Then go through all lines and construct chains of polylines if the endpoints are nearby.\n std::unordered_set processed_lines; \/\/Track which lines were already processed to not process them twice.\n for(const VariableWidthLines& path : input)\n {\n for(const ExtrusionLine& line : path)\n {\n if(processed_lines.find(&line) != processed_lines.end()) \/\/We already added this line before. It got added as a nearby line.\n {\n continue;\n }\n \/\/We'll create a chain of polylines that get joined together. We can add polylines on both ends!\n std::deque chain;\n std::deque is_reversed; \/\/Lines could need to be inserted in reverse. Must coincide with the `chain` deque.\n const ExtrusionLine* nearest = &line; \/\/At every iteration, add the polyline that joins together most closely.\n bool nearest_reverse = false; \/\/Whether the next line to insert must be inserted in reverse.\n bool nearest_before = false; \/\/Whether the next line to insert must be inserted in the front of the chain.\n while(nearest)\n {\n if(processed_lines.find(nearest) != processed_lines.end())\n {\n break; \/\/Looping. This contour is already processed.\n }\n processed_lines.insert(nearest);\n if(nearest_before)\n {\n chain.push_front(nearest);\n is_reversed.push_front(nearest_reverse);\n }\n else\n {\n chain.push_back(nearest);\n is_reversed.push_back(nearest_reverse);\n }\n\n \/\/Find any nearby lines to attach. Look on both ends of our current chain and find both ends of polylines.\n const Point chain_start = is_reversed.front() ? chain.front()->junctions.back().p : chain.front()->junctions.front().p;\n const Point chain_end = is_reversed.back() ? chain.back()->junctions.front().p : chain.back()->junctions.back().p;\n std::vector starts_near_start = line_starts.getNearby(chain_start, stitch_distance);\n std::vector ends_near_start = line_ends.getNearby(chain_start, stitch_distance);\n std::vector starts_near_end = line_starts.getNearby(chain_end, stitch_distance);\n std::vector ends_near_end = line_ends.getNearby(chain_end, stitch_distance);\n\n nearest = nullptr;\n coord_t nearest_dist2 = std::numeric_limits::max();\n for(const ExtrusionLine* candidate : starts_near_start)\n {\n if(processed_lines.find(candidate) != processed_lines.end())\n {\n continue; \/\/Already processed this line before. It's linked to something else.\n }\n const coord_t dist2 = vSize2(candidate->junctions.front().p - chain_start);\n if(dist2 < nearest_dist2)\n {\n nearest = candidate;\n nearest_dist2 = dist2;\n nearest_reverse = true;\n nearest_before = true;\n }\n }\n for(const ExtrusionLine* candidate : ends_near_start)\n {\n if(processed_lines.find(candidate) != processed_lines.end())\n {\n continue;\n }\n const coord_t dist2 = vSize2(candidate->junctions.back().p - chain_start);\n if(dist2 < nearest_dist2)\n {\n nearest = candidate;\n nearest_dist2 = dist2;\n nearest_reverse = false;\n nearest_before = true;\n }\n }\n for(const ExtrusionLine* candidate : starts_near_end)\n {\n if(processed_lines.find(candidate) != processed_lines.end())\n {\n continue; \/\/Already processed this line before. It's linked to something else.\n }\n const coord_t dist2 = vSize2(candidate->junctions.front().p - chain_start);\n if(dist2 < nearest_dist2)\n {\n nearest = candidate;\n nearest_dist2 = dist2;\n nearest_reverse = false;\n nearest_before = false;\n }\n }\n for(const ExtrusionLine* candidate : ends_near_end)\n {\n if(processed_lines.find(candidate) != processed_lines.end())\n {\n continue;\n }\n const coord_t dist2 = vSize2(candidate->junctions.back().p - chain_start);\n if(dist2 < nearest_dist2)\n {\n nearest = candidate;\n nearest_dist2 = dist2;\n nearest_reverse = true;\n nearest_before = false;\n }\n }\n }\n\n \/\/Now serialize the entire chain into one polygon.\n output.emplace_back();\n for(size_t i = 0; i < chain.size(); ++i)\n {\n if(!is_reversed[i])\n {\n for(const ExtrusionJunction& junction : chain[i]->junctions)\n {\n output.back().add(junction.p);\n }\n }\n else\n {\n for(auto junction = chain[i]->junctions.rbegin(); junction != chain[i]->junctions.rend(); ++junction)\n {\n output.back().add(junction->p);\n }\n }\n }\n }\n }\n}\n\n\n} \/\/ namespace cura\n<|endoftext|>"} {"text":"\/\/===-- ManifestLoader.cpp ------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llbuild\/Ninja\/ManifestLoader.h\"\n\n#include \"llbuild\/Ninja\/Lexer.h\"\n#include \"llbuild\/Ninja\/Parser.h\"\n\n#include \n#include \n#include \n\nusing namespace llbuild;\nusing namespace llbuild::ninja;\n\n#pragma mark - ManifestLoaderActions\n\nManifestLoaderActions::~ManifestLoaderActions() {\n}\n\n#pragma mark - ManifestLoader Implementation\n\nnamespace {\n\n\/\/\/ Manifest loader implementation.\n\/\/\/\n\/\/\/ For simplicity, we just directly implement the parser actions interface.\nclass ManifestLoaderImpl: public ParseActions {\n struct IncludeEntry {\n \/\/\/ The file that is being processed.\n std::string Filename;\n \/\/\/ An owning reference to the data consumed by the parser.\n std::unique_ptr Data;\n \/\/\/ The parser for the file.\n std::unique_ptr Parser;\n\n IncludeEntry(const std::string& Filename,\n std::unique_ptr Data,\n std::unique_ptr Parser)\n : Filename(Filename), Data(std::move(Data)), Parser(std::move(Parser)) {}\n };\n\n std::string MainFilename;\n ManifestLoaderActions &Actions;\n std::unique_ptr TheManifest;\n std::vector IncludeStack;\n\npublic:\n ManifestLoaderImpl(std::string MainFilename, ManifestLoaderActions &Actions)\n : MainFilename(MainFilename), Actions(Actions), TheManifest(nullptr)\n {\n }\n\n std::unique_ptr load() {\n \/\/ Create the manifest.\n TheManifest.reset(new Manifest);\n\n \/\/ Enter the main file.\n if (!enterFile(MainFilename))\n return nullptr;\n\n \/\/ Run the parser.\n assert(IncludeStack.size() == 1);\n getCurrentParser()->parse();\n assert(IncludeStack.size() == 0);\n\n return std::move(TheManifest);\n }\n\n bool enterFile(const std::string& Filename,\n const Token* ForToken = nullptr) {\n \/\/ Load the file data.\n std::unique_ptr Data;\n uint64_t Length;\n std::string FromFilename = IncludeStack.empty() ? Filename :\n getCurrentFilename();\n if (!Actions.readFileContents(FromFilename, Filename, ForToken, &Data,\n &Length))\n return false;\n\n \/\/ Push a new entry onto the include stack.\n std::unique_ptr FileParser(new Parser(Data.get(), Length, *this));\n IncludeStack.push_back(IncludeEntry(Filename, std::move(Data),\n std::move(FileParser)));\n\n return true;\n }\n\n void exitCurrentFile() {\n IncludeStack.pop_back();\n }\n\n ManifestLoaderActions& getActions() { return Actions; }\n Parser* getCurrentParser() const {\n assert(!IncludeStack.empty());\n return IncludeStack.back().Parser.get();\n }\n const std::string& getCurrentFilename() const {\n assert(!IncludeStack.empty());\n return IncludeStack.back().Filename;\n }\n\n \/\/\/ Given a string template token, evaluate it against the given \\arg Bindings\n \/\/\/ and return the resulting string.\n std::string evalString(const Token& Value, const BindingSet& Bindings) {\n assert(Value.TokenKind == Token::Kind::String && \"invalid token kind\");\n\n \/\/ Scan the string for escape sequences or variable references, accumulating\n \/\/ output pieces as we go.\n \/\/\n \/\/ FIXME: Rewrite this with StringRef once we have it, and make efficient.\n std::stringstream Result;\n const char* Start = Value.Start;\n const char* End = Value.Start + Value.Length;\n const char* Pos = Start;\n while (Pos != End) {\n \/\/ Find the next '$'.\n const char* PieceStart = Pos;\n for (; Pos != End; ++Pos) {\n if (*Pos == '$')\n break;\n }\n\n \/\/ Add the current piece, if non-empty.\n if (Pos != PieceStart)\n Result << std::string(PieceStart, Pos);\n\n \/\/ If we are at the end, we are done.\n if (Pos == End)\n break;\n\n \/\/ Otherwise, we have a '$' character to handle.\n ++Pos;\n if (Pos == End) {\n error(\"invalid '$'-escape at end of string\", Value);\n break;\n }\n\n \/\/ If this is a newline continuation, skip it and all leading space.\n char Char = *Pos;\n if (Char == '\\n') {\n ++Pos;\n while (Pos != End && isspace(*Pos))\n ++Pos;\n continue;\n }\n\n \/\/ If this is single character escape, honor it.\n if (Char == ' ' || Char == ':' || Char == '$') {\n Result << Char;\n ++Pos;\n continue;\n }\n\n \/\/ If this is a braced variable reference, expand it.\n if (Char == '{') {\n \/\/ Scan until the end of the reference, checking validity of the\n \/\/ identifier name as we go.\n ++Pos;\n const char* VarStart = Pos;\n bool IsValid = true;\n while (true) {\n \/\/ If we reached the end of the string, this is an error.\n if (Pos == End) {\n error(\"invalid variable reference in string (missing trailing '}')\",\n Value);\n break;\n }\n\n \/\/ If we found the end of the reference, resolve it.\n char Char = *Pos;\n if (Char == '}') {\n \/\/ If this identifier isn't valid, emit an error.\n if (!IsValid) {\n error(\"invalid variable name in reference\", Value);\n } else {\n Result << Bindings.lookup(std::string(VarStart, Pos - VarStart));\n }\n ++Pos;\n break;\n }\n\n \/\/ Track whether this is a valid identifier.\n if (!Lexer::isIdentifierChar(Char))\n IsValid = false;\n\n ++Pos;\n }\n continue;\n }\n\n \/\/ If this is a simple variable reference, expand it.\n if (Lexer::isSimpleIdentifierChar(Char)) {\n const char* VarStart = Pos;\n \/\/ Scan until the end of the simple identifier.\n ++Pos;\n while (Pos != End && Lexer::isSimpleIdentifierChar(*Pos))\n ++Pos;\n Result << Bindings.lookup(std::string(VarStart, Pos-VarStart));\n continue;\n }\n\n \/\/ Otherwise, we have an invalid '$' escape.\n error(\"invalid '$'-escape (literal '$' should be written as '$$')\",\n Value);\n break;\n }\n\n return Result.str();\n }\n\n \/\/\/ @name Parse Actions Interfaces\n \/\/\/ @{\n\n virtual void initialize(ninja::Parser *Parser) override { }\n\n virtual void error(std::string Message, const Token &At) override {\n Actions.error(getCurrentFilename(), Message, At);\n }\n\n virtual void actOnBeginManifest(std::string Name) override { }\n\n virtual void actOnEndManifest() override {\n exitCurrentFile();\n }\n\n virtual void actOnBindingDecl(const Token& NameTok,\n const Token& ValueTok) override {\n \/\/ Extract the name string.\n std::string Name(NameTok.Start, NameTok.Length);\n\n \/\/ Evaluate the value string with the current top-level bindings.\n std::string Value(evalString(ValueTok, TheManifest->getBindings()));\n\n TheManifest->getBindings().insert(Name, Value);\n }\n\n virtual void actOnDefaultDecl(const std::vector& NameToks) override {\n \/\/ Resolve all of the inputs and outputs.\n for (auto& NameTok: NameToks) {\n std::string Name(NameTok.Start, NameTok.Length);\n\n auto it = TheManifest->getNodes().find(Name);\n if (it == TheManifest->getNodes().end()) {\n error(\"unknown target name\", NameTok);\n continue;\n }\n\n TheManifest->getDefaultTargets().push_back(it->second.get());\n }\n }\n\n virtual void actOnIncludeDecl(bool IsInclude,\n const Token& PathTok) override {\n std::string Path = evalString(PathTok, TheManifest->getBindings());\n\n \/\/ Enter the new file.\n \/\/\n \/\/ FIXME: Need to handle proper changes to the binding scope.\n if (enterFile(Path, &PathTok)) {\n \/\/ Run the parser for the included file.\n getCurrentParser()->parse();\n }\n }\n\n virtual BuildResult\n actOnBeginBuildDecl(const Token& NameTok,\n const std::vector &OutputTokens,\n const std::vector &InputTokens,\n unsigned NumExplicitInputs,\n unsigned NumImplicitInputs) override {\n std::string Name(NameTok.Start, NameTok.Length);\n\n \/\/ Resolve the rule.\n auto it = TheManifest->getRules().find(Name);\n Rule *Rule;\n if (it == TheManifest->getRules().end()) {\n error(\"unknown rule\", NameTok);\n\n \/\/ Ensure we always have a rule for each command.\n Rule = TheManifest->getPhonyRule();\n } else {\n Rule = it->second.get();\n }\n\n \/\/ Resolve all of the inputs and outputs.\n std::vector Outputs;\n std::vector Inputs;\n for (auto& Token: OutputTokens) {\n \/\/ Evaluate the token string.\n std::string Path = evalString(Token, TheManifest->getBindings());\n Outputs.push_back(TheManifest->getOrCreateNode(Path));\n }\n for (auto& Token: InputTokens) {\n \/\/ Evaluate the token string.\n std::string Path = evalString(Token, TheManifest->getBindings());\n Inputs.push_back(TheManifest->getOrCreateNode(Path));\n }\n\n Command *Decl = new Command(Rule, Outputs, Inputs, NumExplicitInputs,\n NumImplicitInputs);\n TheManifest->getCommands().push_back(std::unique_ptr(Decl));\n\n return Decl;\n }\n\n virtual void actOnBuildBindingDecl(BuildResult AbstractDecl,\n const Token& NameTok,\n const Token& ValueTok) override {\n Command* Decl = static_cast(AbstractDecl);\n\n std::string Name(NameTok.Start, NameTok.Length);\n\n \/\/ FIXME: It probably should be an error to assign to the same parameter\n \/\/ multiple times, but Ninja doesn't diagnose this.\n\n \/\/ The value in a build decl is always evaluated immediately, but only in\n \/\/ the context of the top-level bindings.\n \/\/\n \/\/ FIXME: This needs to be the inherited bindings, once we support includes.\n Decl->getParameters()[Name] = evalString(ValueTok,\n TheManifest->getBindings());\n }\n\n virtual void actOnEndBuildDecl(PoolResult Decl,\n const Token& StartTok) override { }\n\n virtual PoolResult actOnBeginPoolDecl(const Token& NameTok) override {\n std::string Name(NameTok.Start, NameTok.Length);\n\n \/\/ Find the hash slot.\n auto& Result = TheManifest->getPools()[Name];\n\n \/\/ Diagnose if the pool already exists (we still create a new one).\n if (Result.get()) {\n \/\/ The ppol already exists.\n error(\"duplicate pool\", NameTok);\n }\n\n \/\/ Insert the new pool.\n Pool* Decl = new Pool(Name);\n Result.reset(Decl);\n return static_cast(Decl);\n }\n\n virtual void actOnPoolBindingDecl(PoolResult AbstractDecl,\n const Token& NameTok,\n const Token& ValueTok) override {\n Pool* Decl = static_cast(AbstractDecl);\n\n std::string Name(NameTok.Start, NameTok.Length);\n\n \/\/ Evaluate the value string with the current top-level bindings.\n std::string Value(evalString(ValueTok, TheManifest->getBindings()));\n\n if (Name == \"depth\") {\n const char* Start = Value.c_str();\n char* End;\n long IntValue = ::strtol(Start, &End, 10);\n if (*End != '\\0' || IntValue <= 0) {\n error(\"invalid depth\", ValueTok);\n } else {\n Decl->setDepth(static_cast(IntValue));\n }\n } else {\n error(\"unexpected variable\", NameTok);\n }\n }\n\n virtual void actOnEndPoolDecl(PoolResult AbstractDecl,\n const Token& StartTok) override {\n Pool* Decl = static_cast(AbstractDecl);\n\n \/\/ It is an error to not specify the pool depth.\n if (Decl->getDepth() == 0) {\n error(\"missing 'depth' variable assignment\", StartTok);\n }\n }\n\n virtual RuleResult actOnBeginRuleDecl(const Token& NameTok) override {\n std::string Name(NameTok.Start, NameTok.Length);\n\n \/\/ Find the hash slot.\n auto& Result = TheManifest->getRules()[Name];\n\n \/\/ Diagnose if the rule already exists (we still create a new one).\n if (Result.get()) {\n \/\/ The rule already exists.\n error(\"duplicate rule\", NameTok);\n }\n\n \/\/ Insert the new rule.\n Rule* Decl = new Rule(Name);\n Result.reset(Decl);\n return static_cast(Decl);\n }\n\n virtual void actOnRuleBindingDecl(RuleResult AbstractDecl,\n const Token& NameTok,\n const Token& ValueTok) override {\n Rule* Decl = static_cast(AbstractDecl);\n\n std::string Name(NameTok.Start, NameTok.Length);\n \/\/ FIXME: It probably should be an error to assign to the same parameter\n \/\/ multiple times, but Ninja doesn't diagnose this.\n if (Rule::isValidParameterName(Name)) {\n Decl->getParameters()[Name] = std::string(ValueTok.Start,\n ValueTok.Length);\n } else {\n error(\"unexpected variable\", NameTok);\n }\n }\n\n virtual void actOnEndRuleDecl(RuleResult AbstractDecl,\n const Token& StartTok) override {\n Rule* Decl = static_cast(AbstractDecl);\n\n if (!Decl->getParameters().count(\"command\")) {\n error(\"missing 'command' variable assignment\", StartTok);\n }\n }\n\n \/\/\/ @}\n};\n\n}\n\n#pragma mark - ManifestLoader\n\nManifestLoader::ManifestLoader(std::string Filename,\n ManifestLoaderActions &Actions)\n : Impl(static_cast(new ManifestLoaderImpl(Filename, Actions)))\n{\n}\n\nManifestLoader::~ManifestLoader() {\n delete static_cast(Impl);\n}\n\nstd::unique_ptr ManifestLoader::load() {\n \/\/ Initialize the actions.\n static_cast(Impl)->getActions().initialize(this);\n\n return static_cast(Impl)->load();\n}\n\nconst Parser* ManifestLoader::getCurrentParser() const {\n return static_cast(Impl)->getCurrentParser();\n}\n\n[Ninja\/ManifestLoader] Update include stack to also track active binding set.\/\/===-- ManifestLoader.cpp ------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llbuild\/Ninja\/ManifestLoader.h\"\n\n#include \"llbuild\/Ninja\/Lexer.h\"\n#include \"llbuild\/Ninja\/Parser.h\"\n\n#include \n#include \n#include \n\nusing namespace llbuild;\nusing namespace llbuild::ninja;\n\n#pragma mark - ManifestLoaderActions\n\nManifestLoaderActions::~ManifestLoaderActions() {\n}\n\n#pragma mark - ManifestLoader Implementation\n\nnamespace {\n\n\/\/\/ Manifest loader implementation.\n\/\/\/\n\/\/\/ For simplicity, we just directly implement the parser actions interface.\nclass ManifestLoaderImpl: public ParseActions {\n struct IncludeEntry {\n \/\/\/ The file that is being processed.\n std::string Filename;\n \/\/\/ An owning reference to the data consumed by the parser.\n std::unique_ptr Data;\n \/\/\/ The parser for the file.\n std::unique_ptr Parser;\n \/\/\/ The active binding set.\n BindingSet &Bindings;\n\n IncludeEntry(const std::string& Filename,\n std::unique_ptr Data,\n std::unique_ptr Parser,\n BindingSet &Bindings)\n : Filename(Filename), Data(std::move(Data)), Parser(std::move(Parser)),\n Bindings(Bindings) {}\n };\n\n std::string MainFilename;\n ManifestLoaderActions &Actions;\n std::unique_ptr TheManifest;\n std::vector IncludeStack;\n\npublic:\n ManifestLoaderImpl(std::string MainFilename, ManifestLoaderActions &Actions)\n : MainFilename(MainFilename), Actions(Actions), TheManifest(nullptr)\n {\n }\n\n std::unique_ptr load() {\n \/\/ Create the manifest.\n TheManifest.reset(new Manifest);\n\n \/\/ Enter the main file.\n if (!enterFile(MainFilename, TheManifest->getBindings()))\n return nullptr;\n\n \/\/ Run the parser.\n assert(IncludeStack.size() == 1);\n getCurrentParser()->parse();\n assert(IncludeStack.size() == 0);\n\n return std::move(TheManifest);\n }\n\n bool enterFile(const std::string& Filename, BindingSet& Bindings,\n const Token* ForToken = nullptr) {\n \/\/ Load the file data.\n std::unique_ptr Data;\n uint64_t Length;\n std::string FromFilename = IncludeStack.empty() ? Filename :\n getCurrentFilename();\n if (!Actions.readFileContents(FromFilename, Filename, ForToken, &Data,\n &Length))\n return false;\n\n \/\/ Push a new entry onto the include stack.\n std::unique_ptr FileParser(new Parser(Data.get(), Length, *this));\n IncludeStack.push_back(IncludeEntry(Filename, std::move(Data),\n std::move(FileParser),\n Bindings));\n\n return true;\n }\n\n void exitCurrentFile() {\n IncludeStack.pop_back();\n }\n\n ManifestLoaderActions& getActions() { return Actions; }\n Parser* getCurrentParser() const {\n assert(!IncludeStack.empty());\n return IncludeStack.back().Parser.get();\n }\n const std::string& getCurrentFilename() const {\n assert(!IncludeStack.empty());\n return IncludeStack.back().Filename;\n }\n BindingSet& getCurrentBindings() const {\n assert(!IncludeStack.empty());\n return IncludeStack.back().Bindings;\n }\n\n \/\/\/ Given a string template token, evaluate it against the given \\arg Bindings\n \/\/\/ and return the resulting string.\n std::string evalString(const Token& Value, const BindingSet& Bindings) {\n assert(Value.TokenKind == Token::Kind::String && \"invalid token kind\");\n\n \/\/ Scan the string for escape sequences or variable references, accumulating\n \/\/ output pieces as we go.\n \/\/\n \/\/ FIXME: Rewrite this with StringRef once we have it, and make efficient.\n std::stringstream Result;\n const char* Start = Value.Start;\n const char* End = Value.Start + Value.Length;\n const char* Pos = Start;\n while (Pos != End) {\n \/\/ Find the next '$'.\n const char* PieceStart = Pos;\n for (; Pos != End; ++Pos) {\n if (*Pos == '$')\n break;\n }\n\n \/\/ Add the current piece, if non-empty.\n if (Pos != PieceStart)\n Result << std::string(PieceStart, Pos);\n\n \/\/ If we are at the end, we are done.\n if (Pos == End)\n break;\n\n \/\/ Otherwise, we have a '$' character to handle.\n ++Pos;\n if (Pos == End) {\n error(\"invalid '$'-escape at end of string\", Value);\n break;\n }\n\n \/\/ If this is a newline continuation, skip it and all leading space.\n char Char = *Pos;\n if (Char == '\\n') {\n ++Pos;\n while (Pos != End && isspace(*Pos))\n ++Pos;\n continue;\n }\n\n \/\/ If this is single character escape, honor it.\n if (Char == ' ' || Char == ':' || Char == '$') {\n Result << Char;\n ++Pos;\n continue;\n }\n\n \/\/ If this is a braced variable reference, expand it.\n if (Char == '{') {\n \/\/ Scan until the end of the reference, checking validity of the\n \/\/ identifier name as we go.\n ++Pos;\n const char* VarStart = Pos;\n bool IsValid = true;\n while (true) {\n \/\/ If we reached the end of the string, this is an error.\n if (Pos == End) {\n error(\"invalid variable reference in string (missing trailing '}')\",\n Value);\n break;\n }\n\n \/\/ If we found the end of the reference, resolve it.\n char Char = *Pos;\n if (Char == '}') {\n \/\/ If this identifier isn't valid, emit an error.\n if (!IsValid) {\n error(\"invalid variable name in reference\", Value);\n } else {\n Result << Bindings.lookup(std::string(VarStart, Pos - VarStart));\n }\n ++Pos;\n break;\n }\n\n \/\/ Track whether this is a valid identifier.\n if (!Lexer::isIdentifierChar(Char))\n IsValid = false;\n\n ++Pos;\n }\n continue;\n }\n\n \/\/ If this is a simple variable reference, expand it.\n if (Lexer::isSimpleIdentifierChar(Char)) {\n const char* VarStart = Pos;\n \/\/ Scan until the end of the simple identifier.\n ++Pos;\n while (Pos != End && Lexer::isSimpleIdentifierChar(*Pos))\n ++Pos;\n Result << Bindings.lookup(std::string(VarStart, Pos-VarStart));\n continue;\n }\n\n \/\/ Otherwise, we have an invalid '$' escape.\n error(\"invalid '$'-escape (literal '$' should be written as '$$')\",\n Value);\n break;\n }\n\n return Result.str();\n }\n\n \/\/\/ @name Parse Actions Interfaces\n \/\/\/ @{\n\n virtual void initialize(ninja::Parser *Parser) override { }\n\n virtual void error(std::string Message, const Token &At) override {\n Actions.error(getCurrentFilename(), Message, At);\n }\n\n virtual void actOnBeginManifest(std::string Name) override { }\n\n virtual void actOnEndManifest() override {\n exitCurrentFile();\n }\n\n virtual void actOnBindingDecl(const Token& NameTok,\n const Token& ValueTok) override {\n \/\/ Extract the name string.\n std::string Name(NameTok.Start, NameTok.Length);\n\n \/\/ Evaluate the value string with the current top-level bindings.\n std::string Value(evalString(ValueTok, getCurrentBindings()));\n\n getCurrentBindings().insert(Name, Value);\n }\n\n virtual void actOnDefaultDecl(const std::vector& NameToks) override {\n \/\/ Resolve all of the inputs and outputs.\n for (auto& NameTok: NameToks) {\n std::string Name(NameTok.Start, NameTok.Length);\n\n auto it = TheManifest->getNodes().find(Name);\n if (it == TheManifest->getNodes().end()) {\n error(\"unknown target name\", NameTok);\n continue;\n }\n\n TheManifest->getDefaultTargets().push_back(it->second.get());\n }\n }\n\n virtual void actOnIncludeDecl(bool IsInclude,\n const Token& PathTok) override {\n std::string Path = evalString(PathTok, getCurrentBindings());\n\n \/\/ Enter the new file.\n \/\/\n \/\/ FIXME: Need to handle proper changes to the binding scope.\n if (enterFile(Path, getCurrentBindings(), &PathTok)) {\n \/\/ Run the parser for the included file.\n getCurrentParser()->parse();\n }\n }\n\n virtual BuildResult\n actOnBeginBuildDecl(const Token& NameTok,\n const std::vector &OutputTokens,\n const std::vector &InputTokens,\n unsigned NumExplicitInputs,\n unsigned NumImplicitInputs) override {\n std::string Name(NameTok.Start, NameTok.Length);\n\n \/\/ Resolve the rule.\n auto it = TheManifest->getRules().find(Name);\n Rule *Rule;\n if (it == TheManifest->getRules().end()) {\n error(\"unknown rule\", NameTok);\n\n \/\/ Ensure we always have a rule for each command.\n Rule = TheManifest->getPhonyRule();\n } else {\n Rule = it->second.get();\n }\n\n \/\/ Resolve all of the inputs and outputs.\n std::vector Outputs;\n std::vector Inputs;\n for (auto& Token: OutputTokens) {\n \/\/ Evaluate the token string.\n std::string Path = evalString(Token, getCurrentBindings());\n Outputs.push_back(TheManifest->getOrCreateNode(Path));\n }\n for (auto& Token: InputTokens) {\n \/\/ Evaluate the token string.\n std::string Path = evalString(Token, getCurrentBindings());\n Inputs.push_back(TheManifest->getOrCreateNode(Path));\n }\n\n Command *Decl = new Command(Rule, Outputs, Inputs, NumExplicitInputs,\n NumImplicitInputs);\n TheManifest->getCommands().push_back(std::unique_ptr(Decl));\n\n return Decl;\n }\n\n virtual void actOnBuildBindingDecl(BuildResult AbstractDecl,\n const Token& NameTok,\n const Token& ValueTok) override {\n Command* Decl = static_cast(AbstractDecl);\n\n std::string Name(NameTok.Start, NameTok.Length);\n\n \/\/ FIXME: It probably should be an error to assign to the same parameter\n \/\/ multiple times, but Ninja doesn't diagnose this.\n\n \/\/ The value in a build decl is always evaluated immediately, but only in\n \/\/ the context of the top-level bindings.\n \/\/\n \/\/ FIXME: This needs to be the inherited bindings, once we support includes.\n Decl->getParameters()[Name] = evalString(ValueTok,\n getCurrentBindings());\n }\n\n virtual void actOnEndBuildDecl(PoolResult Decl,\n const Token& StartTok) override { }\n\n virtual PoolResult actOnBeginPoolDecl(const Token& NameTok) override {\n std::string Name(NameTok.Start, NameTok.Length);\n\n \/\/ Find the hash slot.\n auto& Result = TheManifest->getPools()[Name];\n\n \/\/ Diagnose if the pool already exists (we still create a new one).\n if (Result.get()) {\n \/\/ The ppol already exists.\n error(\"duplicate pool\", NameTok);\n }\n\n \/\/ Insert the new pool.\n Pool* Decl = new Pool(Name);\n Result.reset(Decl);\n return static_cast(Decl);\n }\n\n virtual void actOnPoolBindingDecl(PoolResult AbstractDecl,\n const Token& NameTok,\n const Token& ValueTok) override {\n Pool* Decl = static_cast(AbstractDecl);\n\n std::string Name(NameTok.Start, NameTok.Length);\n\n \/\/ Evaluate the value string with the current top-level bindings.\n std::string Value(evalString(ValueTok, getCurrentBindings()));\n\n if (Name == \"depth\") {\n const char* Start = Value.c_str();\n char* End;\n long IntValue = ::strtol(Start, &End, 10);\n if (*End != '\\0' || IntValue <= 0) {\n error(\"invalid depth\", ValueTok);\n } else {\n Decl->setDepth(static_cast(IntValue));\n }\n } else {\n error(\"unexpected variable\", NameTok);\n }\n }\n\n virtual void actOnEndPoolDecl(PoolResult AbstractDecl,\n const Token& StartTok) override {\n Pool* Decl = static_cast(AbstractDecl);\n\n \/\/ It is an error to not specify the pool depth.\n if (Decl->getDepth() == 0) {\n error(\"missing 'depth' variable assignment\", StartTok);\n }\n }\n\n virtual RuleResult actOnBeginRuleDecl(const Token& NameTok) override {\n std::string Name(NameTok.Start, NameTok.Length);\n\n \/\/ Find the hash slot.\n auto& Result = TheManifest->getRules()[Name];\n\n \/\/ Diagnose if the rule already exists (we still create a new one).\n if (Result.get()) {\n \/\/ The rule already exists.\n error(\"duplicate rule\", NameTok);\n }\n\n \/\/ Insert the new rule.\n Rule* Decl = new Rule(Name);\n Result.reset(Decl);\n return static_cast(Decl);\n }\n\n virtual void actOnRuleBindingDecl(RuleResult AbstractDecl,\n const Token& NameTok,\n const Token& ValueTok) override {\n Rule* Decl = static_cast(AbstractDecl);\n\n std::string Name(NameTok.Start, NameTok.Length);\n \/\/ FIXME: It probably should be an error to assign to the same parameter\n \/\/ multiple times, but Ninja doesn't diagnose this.\n if (Rule::isValidParameterName(Name)) {\n Decl->getParameters()[Name] = std::string(ValueTok.Start,\n ValueTok.Length);\n } else {\n error(\"unexpected variable\", NameTok);\n }\n }\n\n virtual void actOnEndRuleDecl(RuleResult AbstractDecl,\n const Token& StartTok) override {\n Rule* Decl = static_cast(AbstractDecl);\n\n if (!Decl->getParameters().count(\"command\")) {\n error(\"missing 'command' variable assignment\", StartTok);\n }\n }\n\n \/\/\/ @}\n};\n\n}\n\n#pragma mark - ManifestLoader\n\nManifestLoader::ManifestLoader(std::string Filename,\n ManifestLoaderActions &Actions)\n : Impl(static_cast(new ManifestLoaderImpl(Filename, Actions)))\n{\n}\n\nManifestLoader::~ManifestLoader() {\n delete static_cast(Impl);\n}\n\nstd::unique_ptr ManifestLoader::load() {\n \/\/ Initialize the actions.\n static_cast(Impl)->getActions().initialize(this);\n\n return static_cast(Impl)->load();\n}\n\nconst Parser* ManifestLoader::getCurrentParser() const {\n return static_cast(Impl)->getCurrentParser();\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n\/\/ This program generates an mconfig.h file. It is used in the build process.\n\n\/\/ Map of variable name to value. Variables are passed via command line and stored\n\/\/ in this map.\nstd::unordered_map vars;\n\nchar to_hex_digit(int i)\n{\n if (i < 10) return i + '0';\n return i - 10 + 'A';\n}\n\n\/\/ turn a string into a C++-source string, eg:\n\/\/ he said \"hello\"\n\/\/ becomes\n\/\/ \"he said \\\"hello\\\"\"\nstatic std::string stringify(std::string a)\n{\n std::string out = \"\\\"\";\n\n for (std::string::size_type i = 0; i < a.length(); i++) {\n char c = a[i];\n if (c == '\\n') out += \"\\\\n\";\n else if (c == '\\t') out += \"\\\\t\";\n else if (c == '\\\"') out += \"\\\\\\\"\";\n else if (c < 0x20) {\n out += \"\\\\x\" ;\n out += to_hex_digit((c & 0xF0) >> 4);\n out += to_hex_digit((c & 0x0F));\n }\n else out += c;\n }\n\n out += \"\\\"\";\n return out;\n}\n\n\/\/ parse a NAME=VALUE argument and store in the variable map\nvoid parse_arg(std::string arg)\n{\n auto idx = arg.find(\"=\", 0, 1);\n if (idx == std::string::npos) {\n throw std::string(\"Couldn't parse argument: \") + arg;\n }\n\n auto name = arg.substr(0, idx);\n auto value = arg.substr(idx + 1);\n vars.emplace(std::move(name), std::move(value));\n}\n\nint main(int argc, char **argv)\n{\n for (int i = 1; i < argc; i++) {\n parse_arg(argv[i]);\n }\n\n using namespace std;\n cout << \"\/\/ This file is auto-generated by mconfig-gen.cc.\" << endl;\n cout << \"const static char SYSCONTROLSOCKET[] = \" << stringify(vars[\"SYSCONTROLSOCKET\"]) << \";\" << endl;\n cout << \"const static char SBINDIR[] = \" << stringify(vars[\"SBINDIR\"]) << \";\" << endl;\n return 0;\n}\nmconfig-gen: generate constexpr declarations.#include \n#include \n#include \n\n\/\/ This program generates an mconfig.h file. It is used in the build process.\n\n\/\/ Map of variable name to value. Variables are passed via command line and stored\n\/\/ in this map.\nstd::unordered_map vars;\n\nchar to_hex_digit(int i)\n{\n if (i < 10) return i + '0';\n return i - 10 + 'A';\n}\n\n\/\/ turn a string into a C++-source string, eg:\n\/\/ he said \"hello\"\n\/\/ becomes\n\/\/ \"he said \\\"hello\\\"\"\nstatic std::string stringify(std::string a)\n{\n std::string out = \"\\\"\";\n\n for (std::string::size_type i = 0; i < a.length(); i++) {\n char c = a[i];\n if (c == '\\n') out += \"\\\\n\";\n else if (c == '\\t') out += \"\\\\t\";\n else if (c == '\\\"') out += \"\\\\\\\"\";\n else if (c < 0x20) {\n out += \"\\\\x\" ;\n out += to_hex_digit((c & 0xF0) >> 4);\n out += to_hex_digit((c & 0x0F));\n }\n else out += c;\n }\n\n out += \"\\\"\";\n return out;\n}\n\n\/\/ parse a NAME=VALUE argument and store in the variable map\nvoid parse_arg(std::string arg)\n{\n auto idx = arg.find(\"=\", 0, 1);\n if (idx == std::string::npos) {\n throw std::string(\"Couldn't parse argument: \") + arg;\n }\n\n auto name = arg.substr(0, idx);\n auto value = arg.substr(idx + 1);\n vars.emplace(std::move(name), std::move(value));\n}\n\nint main(int argc, char **argv)\n{\n for (int i = 1; i < argc; i++) {\n parse_arg(argv[i]);\n }\n\n using namespace std;\n cout << \"\/\/ This file is auto-generated by mconfig-gen.cc.\" << endl;\n cout << \"constexpr static char SYSCONTROLSOCKET[] = \" << stringify(vars[\"SYSCONTROLSOCKET\"]) << \";\" << endl;\n cout << \"constexpr static char SBINDIR[] = \" << stringify(vars[\"SBINDIR\"]) << \";\" << endl;\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/===-------------------------- SILCombine --------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ A port of LLVM's InstCombine pass to SIL. Its main purpose is for performing\n\/\/ small combining operations\/peepholes at the SIL level. It additionally DCEs\n\/\/ before in order to reduce compile time.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sil-combine\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"swift\/SIL\/SILBuilder.h\"\n#include \"swift\/SIL\/SILVisitor.h\"\n#include \"swift\/SILPasses\/Utils\/Local.h\"\n#include \"swift\/Subsystems.h\"\n\nusing namespace swift;\n\nSTATISTIC(NumCombined, \"Number of instructions combined.\");\nSTATISTIC(NumDeadInst, \"Num dead insts eliminated.\");\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ SILCombineWorklist\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace swift {\n\n\/\/\/ This is the worklist management logic for SILCombine.\nclass SILCombineWorklist {\n llvm::SmallVector Worklist;\n llvm::DenseMap WorklistMap;\n llvm::SmallVector TrackingList;\n\n void operator=(const SILCombineWorklist&RHS) = delete;\n SILCombineWorklist(const SILCombineWorklist&) = delete;\npublic:\n SILCombineWorklist() {}\n\n \/\/\/ Returns true if the worklist is empty.\n bool isEmpty() const { return Worklist.empty(); }\n\n \/\/\/ Add the specified instruction to the worklist if it isn't already in it.\n void add(SILInstruction *I) {\n if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {\n DEBUG(llvm::dbgs() << \"SC: ADD: \" << *I << '\\n');\n Worklist.push_back(I);\n }\n }\n\n \/\/\/ Add the given ValueBase if it is an instruction to the worklist if it is a\n \/\/\/ SILInstruction.\n void addValue(ValueBase *V) {\n if (SILInstruction *I = llvm::dyn_cast(V))\n add(I);\n }\n\n \/\/\/ Add the specified batch of stuff in reverse order. which should only be\n \/\/\/ done when the worklist is empty and when the group has no duplicates.\n void addInitialGroup(SILInstruction *const *List, unsigned NumEntries) {\n assert(Worklist.empty() && \"Worklist must be empty to add initial group\");\n Worklist.reserve(NumEntries+16);\n WorklistMap.resize(NumEntries);\n DEBUG(llvm::dbgs() << \"SC: ADDING: \" << NumEntries\n << \" instrs to worklist\\n\");\n for (unsigned Idx = 0; NumEntries; --NumEntries) {\n SILInstruction *I = List[NumEntries-1];\n WorklistMap.insert(std::make_pair(I, Idx++));\n Worklist.push_back(I);\n }\n }\n\n \/\/ Remove I from the worklist if it exists.\n void remove(SILInstruction *I) {\n auto It = WorklistMap.find(I);\n if (It == WorklistMap.end()) return; \/\/ Not in worklist.\n\n \/\/ Don't bother moving everything down, just null out the slot. We will\n \/\/ check before we process any instruction if it is 0 allowing us to not\n \/\/ have to shift all of the elements of our worklist down everytime an\n \/\/ instruction is removed.\n Worklist[It->second] = 0;\n\n WorklistMap.erase(It);\n }\n\n \/\/\/ Remove the top element from the worklist.\n SILInstruction *removeOne() {\n SILInstruction *I = Worklist.pop_back_val();\n WorklistMap.erase(I);\n return I;\n }\n\n \/\/\/ When an instruction is simplified, add all users of the instruction to the\n \/\/\/ work lists because they might get more simplified now.\n void addUsersToWorklist(SILInstruction &I) {\n for (auto UI : I.getUses())\n add(llvm::cast(UI->getUser()));\n }\n\n \/\/\/ Check that the worklist is empty and nuke the backing store for the map if\n \/\/\/ it is large.\n void zap() {\n assert(WorklistMap.empty() && \"Worklist empty, but the map is not?\");\n\n \/\/ Do an explicit clear, this shrinks the map if needed.\n WorklistMap.clear();\n }\n};\n\n} \/\/ end namespace swift\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ SILCombiner\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace swift {\n\n\/\/\/ This is a class which maintains the state of the combine and simplifies many\n\/\/\/ operations such as removing\/adding instructions and syncing that with the\n\/\/\/ worklist.\nclass SILCombiner :\n public SILInstructionVisitor {\npublic:\n SILCombiner() : Worklist(), MadeChange(false), Iteration(0), Builder(0) { }\n\n bool runOnFunction(SILFunction &F) {\n bool MadeActualChange = false;\n Iteration = 0;\n\n \/\/ Create a SILBuilder for F and initialize the TrackingList.\n SILBuilder B(F);\n B.setTrackingList(&TrackingList);\n Builder = &B;\n\n \/\/ Perform iterations until we do not make any changes.\n while (doOneIteration(F, Iteration)) {\n Iteration++;\n MadeActualChange = true;\n }\n\n \/\/ Cleanup builder and return whether or not we made any changes.\n Builder = 0;\n return MadeActualChange;\n }\n\n void clear() {\n Iteration = 0;\n Worklist.zap();\n MadeChange = false;\n }\n\n \/\/ Insert the instruction New before instruction Old in the program. Add the\n \/\/ new instruction to the worklist.\n SILInstruction *insertNewInstBefore(SILInstruction *New,\n SILInstruction &Old) {\n assert(New && New->getParent() == 0 &&\n \"New instruction already inserted into a basic block!\");\n SILBasicBlock *BB = Old.getParent();\n BB->getInstList().insert(&Old, New); \/\/ Insert inst\n Worklist.add(New);\n return New;\n }\n\n \/\/ This method is to be used when an instruction is found to be dead,\n \/\/ replacable with another preexisting expression. Here we add all uses of I\n \/\/ to the worklist, replace all uses of I with the new value, then return I,\n \/\/ so that the inst combiner will know that I was modified.\n SILInstruction *replaceInstUsesWith(SILInstruction &I, ValueBase *V) {\n Worklist.addUsersToWorklist(I); \/\/ Add all modified instrs to worklist.\n\n DEBUG(llvm::dbgs() << \"SC: Replacing \" << I << \"\\n\"\n \" with \" << *V << '\\n');\n\n SILValue(&I, 0).replaceAllUsesWith(V);\n return &I;\n }\n\n \/\/ When dealing with an instruction that has side effects or produces a void\n \/\/ value, we can't rely on DCE to delete the instruction. Instead, visit\n \/\/ methods should return the value returned by this function.\n SILInstruction *eraseInstFromFunction(SILInstruction &I) {\n DEBUG(llvm::dbgs() << \"SC: ERASE \" << I << '\\n');\n\n assert(I.use_empty() && \"Cannot erase instruction that is used!\");\n \/\/ Make sure that we reprocess all operands now that we reduced their\n \/\/ use counts.\n if (I.getNumOperands() < 8) {\n for (auto &OpI : I.getAllOperands())\n if (SILInstruction *Op = llvm::dyn_cast(&*OpI.get()))\n Worklist.add(Op);\n }\n Worklist.remove(&I);\n I.eraseFromParent();\n MadeChange = true;\n return 0; \/\/ Don't do anything with FI\n }\n\n void addInitialGroup(SILInstruction *const *List, unsigned NumEntries) {\n Worklist.addInitialGroup(List, NumEntries);\n }\n\n \/\/\/ Base visitor that does not do anything.\n SILInstruction *visitValueBase(ValueBase *V) { return nullptr; }\n\nprivate:\n \/\/\/ Perform one SILCombine iteration.\n bool doOneIteration(SILFunction &F, unsigned Iteration);\n\n \/\/\/ All of the instructions that need to be simplified.\n SILCombineWorklist Worklist;\n \/\/\/ Did we make a chanbge?\n bool MadeChange;\n \/\/\/ What is the current iteration of the SILCombine we are on.\n unsigned Iteration;\n \/\/\/ Builder used to insert instructions.\n SILBuilder *Builder;\n \/\/\/ A list that the builder puts newly created instructions into. Its contents\n \/\/\/ are added to the worklist after every iteration and then is cleared.\n llvm::SmallVector TrackingList;\n};\n\n} \/\/ end namespace swift\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ SILCombine Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ addReachableCodeToWorklist - Walk the function in depth-first order, adding\n\/\/\/ all reachable code to the worklist.\n\/\/\/\n\/\/\/ This has a couple of tricks to make the code faster and more powerful. In\n\/\/\/ particular, we DCE instructions as we go, to avoid adding them to the\n\/\/\/ worklist (this significantly speeds up instcombine on code where many\n\/\/\/ instructions are dead or constant).\nstatic void addReachableCodeToWorklist(SILBasicBlock *BB, SILCombiner &IC) {\n llvm::SmallVector Worklist;\n llvm::SmallVector InstrsForInstCombineWorklist;\n llvm::SmallPtrSet Visited;\n\n Worklist.push_back(BB);\n do {\n BB = Worklist.pop_back_val();\n\n \/\/ We have now visited this block! If we've already been here, ignore it.\n if (!Visited.insert(BB)) continue;\n\n for (SILBasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {\n SILInstruction *Inst = BBI++;\n\n \/\/ DCE instruction if trivially dead.\n if (isInstructionTriviallyDead(Inst)) {\n ++NumDeadInst;\n DEBUG(llvm::dbgs() << \"SC: DCE: \" << *Inst << '\\n');\n Inst->eraseFromParent();\n continue;\n }\n\n InstrsForInstCombineWorklist.push_back(Inst);\n }\n\n \/\/ Recursively visit successors.\n for (auto SI = BB->succ_begin(), SE = BB->succ_end(); SI != SE; ++SI)\n Worklist.push_back(*SI);\n } while (!Worklist.empty());\n\n \/\/ Once we've found all of the instructions to add to SILCombine's worklist,\n \/\/ add them in reverse order. This way SILCombine will visit from the top of\n \/\/ the function down. This jives well with the way that it adds all uses of\n \/\/ instructions to the worklist after doing a transformation, thus avoiding\n \/\/ some N^2 behavior in pathological cases.\n IC.addInitialGroup(&InstrsForInstCombineWorklist[0],\n InstrsForInstCombineWorklist.size());\n}\n\nbool SILCombiner::doOneIteration(SILFunction &F, unsigned Iteration) {\n MadeChange = false;\n\n DEBUG(llvm::dbgs() << \"\\n\\nSILCOMBINE ITERATION #\" << Iteration << \" on \"\n << F.getName() << \"\\n\");\n\n \/\/ Add reachable instructions to our worklist.\n addReachableCodeToWorklist(F.begin(), *this);\n\n \/\/ Process until we run out of items in our worklist.\n while (!Worklist.isEmpty()) {\n SILInstruction *I = Worklist.removeOne();\n\n \/\/ When we erase an instruction, we use the map in the worklist to check if\n \/\/ the instruction is in the worklist. If it is, we replace it with 0\n \/\/ instead of shifting all members of the worklist towards the front. This\n \/\/ check makes sure that if we run into any such residual null pointers, we\n \/\/ skip them.\n if (I == 0)\n continue;\n\n \/\/ Check to see if we can DCE the instruction.\n if (isInstructionTriviallyDead(I)) {\n DEBUG(llvm::dbgs() << \"SC: DCE: \" << *I << '\\n');\n eraseInstFromFunction(*I);\n ++NumDeadInst;\n MadeChange = true;\n continue;\n }\n\n \/\/ Now that we have an instruction, try simplifying it.\n Builder->setInsertionPoint(I->getParent(), I);\n\n#ifndef NDEBUG\n std::string OrigI;\n#endif\n DEBUG(llvm::raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););\n DEBUG(llvm::dbgs() << \"SC: Visiting: \" << OrigI << '\\n');\n\n if (SILInstruction *Result = visit(I)) {\n ++NumCombined;\n \/\/ Should we replace the old instruction with a new one?\n if (Result != I) {\n DEBUG(llvm::dbgs() << \"SC: Old = \" << *I << '\\n'\n << \" New = \" << *Result << '\\n');\n\n \/\/ Everything uses the new instruction now.\n replaceInstUsesWith(*I, Result);\n\n \/\/ Push the new instruction and any users onto the worklist.\n Worklist.add(Result);\n Worklist.addUsersToWorklist(*Result);\n\n \/\/ Insert the new instruction into the basic block...\n SILBasicBlock *InstParent = I->getParent();\n SILBasicBlock::iterator InsertPos = I;\n\n InstParent->getInstList().insert(InsertPos, Result);\n\n eraseInstFromFunction(*I);\n } else {\n DEBUG(llvm::dbgs() << \"SC: Mod = \" << OrigI << '\\n'\n << \" New = \" << *I << '\\n');\n\n \/\/ If the instruction was modified, it's possible that it is now dead.\n \/\/ if so, remove it.\n if (isInstructionTriviallyDead(I)) {\n eraseInstFromFunction(*I);\n } else {\n Worklist.add(I);\n Worklist.addUsersToWorklist(*I);\n }\n }\n MadeChange = true;\n }\n\n \/\/ Our tracking list which has been accumulating instructions created by the\n \/\/ SILBuilder doing this iteration. Go through the tracking list and add\n \/\/ them to the worklist and then clear the TrackingList in preparation for\n \/\/ the next iteration.\n for (SILInstruction *I : TrackingList) {\n Worklist.add(I);\n }\n TrackingList.clear();\n }\n\n Worklist.zap();\n return MadeChange;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Top Level Driver\n\/\/===----------------------------------------------------------------------===\/\/\n\nbool swift::performSILCombine(SILModule *M) {\n bool MadeChange = false;\n SILCombiner Combiner;\n\n \/\/ Process each function in M.\n for (SILFunction &F : *M) {\n \/\/ If F is just a declaration without any basic blocks, skip it.\n if (!F.size())\n continue;\n\n \/\/ Clear the combiner just in case.\n Combiner.clear();\n \/\/ Record if we made any changes.\n MadeChange |= Combiner.runOnFunction(F);\n }\n\n \/\/ Return true if we made any changes.\n return MadeChange;\n}\n[sil-combine] Fix comments.\/\/===-------------------------- SILCombine --------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ A port of LLVM's InstCombine pass to SIL. Its main purpose is for performing\n\/\/ small combining operations\/peepholes at the SIL level. It additionally\n\/\/ performs dead code elimination when it initially adds instructions to the\n\/\/ work queue in order to reduce compile time by not visiting trivially dead\n\/\/ instructions.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sil-combine\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"swift\/SIL\/SILBuilder.h\"\n#include \"swift\/SIL\/SILVisitor.h\"\n#include \"swift\/SILPasses\/Utils\/Local.h\"\n#include \"swift\/Subsystems.h\"\n\nusing namespace swift;\n\nSTATISTIC(NumCombined, \"Number of instructions combined.\");\nSTATISTIC(NumDeadInst, \"Num dead insts eliminated.\");\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ SILCombineWorklist\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace swift {\n\n\/\/\/ This is the worklist management logic for SILCombine.\nclass SILCombineWorklist {\n llvm::SmallVector Worklist;\n llvm::DenseMap WorklistMap;\n llvm::SmallVector TrackingList;\n\n void operator=(const SILCombineWorklist&RHS) = delete;\n SILCombineWorklist(const SILCombineWorklist&) = delete;\npublic:\n SILCombineWorklist() {}\n\n \/\/\/ Returns true if the worklist is empty.\n bool isEmpty() const { return Worklist.empty(); }\n\n \/\/\/ Add the specified instruction to the worklist if it isn't already in it.\n void add(SILInstruction *I) {\n if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {\n DEBUG(llvm::dbgs() << \"SC: ADD: \" << *I << '\\n');\n Worklist.push_back(I);\n }\n }\n\n \/\/\/ If the given ValueBase is a SILInstruction add it to the worklist.\n void addValue(ValueBase *V) {\n if (SILInstruction *I = llvm::dyn_cast(V))\n add(I);\n }\n\n \/\/\/ Add the given list of instructions in reverse order to the worklist. This\n \/\/\/ routine assumes that the worklist is empty and the given list has no\n \/\/\/ duplicates.\n void addInitialGroup(SILInstruction *const *List, unsigned NumEntries) {\n assert(Worklist.empty() && \"Worklist must be empty to add initial group\");\n Worklist.reserve(NumEntries+16);\n WorklistMap.resize(NumEntries);\n DEBUG(llvm::dbgs() << \"SC: ADDING: \" << NumEntries\n << \" instrs to worklist\\n\");\n for (unsigned Idx = 0; NumEntries; --NumEntries) {\n SILInstruction *I = List[NumEntries-1];\n WorklistMap.insert(std::make_pair(I, Idx++));\n Worklist.push_back(I);\n }\n }\n\n \/\/ If I is in the worklist, remove it.\n void remove(SILInstruction *I) {\n auto It = WorklistMap.find(I);\n if (It == WorklistMap.end()) return; \/\/ Not in worklist.\n\n \/\/ Don't bother moving everything down, just null out the slot. We will\n \/\/ check before we process any instruction if it is 0.\n Worklist[It->second] = 0;\n\n WorklistMap.erase(It);\n }\n\n \/\/\/ Remove the top element from the worklist.\n SILInstruction *removeOne() {\n SILInstruction *I = Worklist.pop_back_val();\n WorklistMap.erase(I);\n return I;\n }\n\n \/\/\/ When an instruction has been simplified, add all of its users to the\n \/\/\/ worklist since additional simplifications of its users may have been\n \/\/\/ exposed.\n void addUsersToWorklist(SILInstruction &I) {\n for (auto UI : I.getUses())\n add(llvm::cast(UI->getUser()));\n }\n\n \/\/\/ Check that the worklist is empty and nuke the backing store for the map if\n \/\/\/ it is large.\n void zap() {\n assert(WorklistMap.empty() && \"Worklist empty, but the map is not?\");\n\n \/\/ Do an explicit clear, this shrinks the map if needed.\n WorklistMap.clear();\n }\n};\n\n} \/\/ end namespace swift\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ SILCombiner\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace swift {\n\n\/\/\/ This is a class which maintains the state of the combiner and simplifies\n\/\/\/ many operations such as removing\/adding instructions and syncing them with\n\/\/\/ the worklist.\nclass SILCombiner :\n public SILInstructionVisitor {\npublic:\n SILCombiner() : Worklist(), MadeChange(false), Iteration(0), Builder(0) { }\n\n bool runOnFunction(SILFunction &F) {\n bool MadeActualChange = false;\n Iteration = 0;\n\n \/\/ Create a SILBuilder for F and initialize the tracking list.\n SILBuilder B(F);\n B.setTrackingList(&TrackingList);\n Builder = &B;\n\n \/\/ Perform iterations until we do not make any changes.\n while (doOneIteration(F, Iteration)) {\n Iteration++;\n MadeActualChange = true;\n }\n\n \/\/ Cleanup the builder and return whether or not we made any changes.\n Builder = 0;\n return MadeActualChange;\n }\n\n void clear() {\n Iteration = 0;\n Worklist.zap();\n MadeChange = false;\n }\n\n \/\/ Insert the instruction New before instruction Old in Old's parent BB. Add\n \/\/ New to the worklist.\n SILInstruction *insertNewInstBefore(SILInstruction *New,\n SILInstruction &Old) {\n assert(New && New->getParent() == 0 &&\n \"New instruction already inserted into a basic block!\");\n SILBasicBlock *BB = Old.getParent();\n BB->getInstList().insert(&Old, New); \/\/ Insert inst\n Worklist.add(New);\n return New;\n }\n\n \/\/ This method is to be used when an instruction is found to be dead,\n \/\/ replacable with another preexisting expression. Here we add all uses of I\n \/\/ to the worklist, replace all uses of I with the new value, then return I,\n \/\/ so that the combiner will know that I was modified.\n SILInstruction *replaceInstUsesWith(SILInstruction &I, ValueBase *V) {\n Worklist.addUsersToWorklist(I); \/\/ Add all modified instrs to worklist.\n\n DEBUG(llvm::dbgs() << \"SC: Replacing \" << I << \"\\n\"\n \" with \" << *V << '\\n');\n\n SILValue(&I, 0).replaceAllUsesWith(V);\n return &I;\n }\n\n \/\/ Some instructions can never be \"trivially dead\" due to side effects or\n \/\/ producing a void value. In those cases, since we can not rely on\n \/\/ SILCombines trivially dead instruction DCE in order to delete the\n \/\/ instruction, visit methods should use this method to delete the given\n \/\/ instruction and upon completion of their peephole return the value returned\n \/\/ by this method.\n SILInstruction *eraseInstFromFunction(SILInstruction &I) {\n DEBUG(llvm::dbgs() << \"SC: ERASE \" << I << '\\n');\n\n assert(I.use_empty() && \"Cannot erase instruction that is used!\");\n \/\/ Make sure that we reprocess all operands now that we reduced their\n \/\/ use counts.\n if (I.getNumOperands() < 8) {\n for (auto &OpI : I.getAllOperands())\n if (SILInstruction *Op = llvm::dyn_cast(&*OpI.get()))\n Worklist.add(Op);\n }\n Worklist.remove(&I);\n I.eraseFromParent();\n MadeChange = true;\n return 0; \/\/ Don't do anything with I\n }\n\n void addInitialGroup(SILInstruction *const *List, unsigned NumEntries) {\n Worklist.addInitialGroup(List, NumEntries);\n }\n\n \/\/\/ Base visitor that does not do anything.\n SILInstruction *visitValueBase(ValueBase *V) { return nullptr; }\n\nprivate:\n \/\/\/ Perform one SILCombine iteration.\n bool doOneIteration(SILFunction &F, unsigned Iteration);\n\n \/\/\/ Worklist containing all of the instructions primed for simplification.\n SILCombineWorklist Worklist;\n \/\/\/ Variable to track if the SILCombiner made any changes.\n bool MadeChange;\n \/\/\/ The current iteration of the SILCombine.\n unsigned Iteration;\n \/\/\/ Builder used to insert instructions.\n SILBuilder *Builder;\n \/\/\/ A list that the builder inserts newly created instructions into. Its\n \/\/\/ contents are added to the worklist after every iteration and then the list\n \/\/\/ is cleared.\n llvm::SmallVector TrackingList;\n};\n\n} \/\/ end namespace swift\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ SILCombine Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ addReachableCodeToWorklist - Walk the function in depth-first order, adding\n\/\/\/ all reachable code to the worklist.\n\/\/\/\n\/\/\/ This has a couple of tricks to make the code faster and more powerful. In\n\/\/\/ particular, we DCE instructions as we go, to avoid adding them to the\n\/\/\/ worklist (this significantly speeds up SILCombine on code where many\n\/\/\/ instructions are dead or constant).\nstatic void addReachableCodeToWorklist(SILBasicBlock *BB, SILCombiner &SC) {\n llvm::SmallVector Worklist;\n llvm::SmallVector InstrsForSILCombineWorklist;\n llvm::SmallPtrSet Visited;\n\n Worklist.push_back(BB);\n do {\n BB = Worklist.pop_back_val();\n\n \/\/ We have now visited this block! If we've already been here, ignore it.\n if (!Visited.insert(BB)) continue;\n\n for (SILBasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {\n SILInstruction *Inst = BBI++;\n\n \/\/ DCE instruction if trivially dead.\n if (isInstructionTriviallyDead(Inst)) {\n ++NumDeadInst;\n DEBUG(llvm::dbgs() << \"SC: DCE: \" << *Inst << '\\n');\n Inst->eraseFromParent();\n continue;\n }\n\n InstrsForSILCombineWorklist.push_back(Inst);\n }\n\n \/\/ Recursively visit successors.\n for (auto SI = BB->succ_begin(), SE = BB->succ_end(); SI != SE; ++SI)\n Worklist.push_back(*SI);\n } while (!Worklist.empty());\n\n \/\/ Once we've found all of the instructions to add to the worklist, add them\n \/\/ in reverse order. This way SILCombine will visit from the top of the\n \/\/ function down. This jives well with the way that it adds all uses of\n \/\/ instructions to the worklist after doing a transformation, thus avoiding\n \/\/ some N^2 behavior in pathological cases.\n SC.addInitialGroup(&InstrsForSILCombineWorklist[0],\n InstrsForSILCombineWorklist.size());\n}\n\nbool SILCombiner::doOneIteration(SILFunction &F, unsigned Iteration) {\n MadeChange = false;\n\n DEBUG(llvm::dbgs() << \"\\n\\nSILCOMBINE ITERATION #\" << Iteration << \" on \"\n << F.getName() << \"\\n\");\n\n \/\/ Add reachable instructions to our worklist.\n addReachableCodeToWorklist(F.begin(), *this);\n\n \/\/ Process until we run out of items in our worklist.\n while (!Worklist.isEmpty()) {\n SILInstruction *I = Worklist.removeOne();\n\n \/\/ When we erase an instruction, we use the map in the worklist to check if\n \/\/ the instruction is in the worklist. If it is, we replace it with 0\n \/\/ instead of shifting all members of the worklist towards the front. This\n \/\/ check makes sure that if we run into any such residual null pointers, we\n \/\/ skip them.\n if (I == 0)\n continue;\n\n \/\/ Check to see if we can DCE the instruction.\n if (isInstructionTriviallyDead(I)) {\n DEBUG(llvm::dbgs() << \"SC: DCE: \" << *I << '\\n');\n eraseInstFromFunction(*I);\n ++NumDeadInst;\n MadeChange = true;\n continue;\n }\n\n \/\/ Now that we have an instruction, try simplifying it.\n Builder->setInsertionPoint(I->getParent(), I);\n\n#ifndef NDEBUG\n std::string OrigI;\n#endif\n DEBUG(llvm::raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););\n DEBUG(llvm::dbgs() << \"SC: Visiting: \" << OrigI << '\\n');\n\n if (SILInstruction *Result = visit(I)) {\n ++NumCombined;\n \/\/ Should we replace the old instruction with a new one?\n if (Result != I) {\n DEBUG(llvm::dbgs() << \"SC: Old = \" << *I << '\\n'\n << \" New = \" << *Result << '\\n');\n\n \/\/ Everything uses the new instruction now.\n replaceInstUsesWith(*I, Result);\n\n \/\/ Push the new instruction and any users onto the worklist.\n Worklist.add(Result);\n Worklist.addUsersToWorklist(*Result);\n\n \/\/ Insert the new instruction into the basic block...\n SILBasicBlock *InstParent = I->getParent();\n SILBasicBlock::iterator InsertPos = I;\n\n InstParent->getInstList().insert(InsertPos, Result);\n\n eraseInstFromFunction(*I);\n } else {\n DEBUG(llvm::dbgs() << \"SC: Mod = \" << OrigI << '\\n'\n << \" New = \" << *I << '\\n');\n\n \/\/ If the instruction was modified, it's possible that it is now dead.\n \/\/ if so, remove it.\n if (isInstructionTriviallyDead(I)) {\n eraseInstFromFunction(*I);\n } else {\n Worklist.add(I);\n Worklist.addUsersToWorklist(*I);\n }\n }\n MadeChange = true;\n }\n\n \/\/ Our tracking list has been accumulating instructions created by the\n \/\/ SILBuilder during this iteration. Go through the tracking list and add\n \/\/ its contents to the worklist and then clear said list in preparation for\n \/\/ the next iteration.\n for (SILInstruction *I : TrackingList) {\n Worklist.add(I);\n }\n TrackingList.clear();\n }\n\n Worklist.zap();\n return MadeChange;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Top Level Driver\n\/\/===----------------------------------------------------------------------===\/\/\n\nbool swift::performSILCombine(SILModule *M) {\n bool MadeChange = false;\n SILCombiner Combiner;\n\n \/\/ Process each function in M.\n for (SILFunction &F : *M) {\n \/\/ If F is just a declaration without any basic blocks, skip it.\n if (!F.size())\n continue;\n\n \/\/ Clear the combiner just in case.\n Combiner.clear();\n \/\/ Record if we made any changes.\n MadeChange |= Combiner.runOnFunction(F);\n }\n\n \/\/ Return true if we made any changes.\n return MadeChange;\n}\n<|endoftext|>"} {"text":"\/\/===- lib\/Trace\/TracedFunction.cpp ---------------------------------------===\/\/\n\/\/\n\/\/ SeeC\n\/\/\n\/\/ This file is distributed under The MIT License (MIT). See LICENSE.TXT for\n\/\/ details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"seec\/Trace\/TracedFunction.hpp\"\n#include \"seec\/Trace\/TraceThreadListener.hpp\"\n\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Instruction.h\"\n\n#define SEEC_DEBUG_PTROBJ 0\n\n\nnamespace seec {\n\nnamespace trace {\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Support getCurrentRuntimeValue.\n\/\/===----------------------------------------------------------------------===\/\/\n\nuintptr_t\nTracedFunction::getRuntimeAddress(llvm::GlobalVariable const *GV) const\n{\n return ThreadListener.getRuntimeAddress(GV);\n}\n\nuintptr_t TracedFunction::getRuntimeAddress(llvm::Function const *F) const\n{\n return ThreadListener.getRuntimeAddress(F);\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Accessors for active-only information.\n\/\/===----------------------------------------------------------------------===\/\/\n\nseec::Maybe\nTracedFunction::getContainingMemoryArea(uintptr_t Address) const\n{\n std::lock_guard Lock(StackMutex);\n \n if (Address < StackLow || Address > StackHigh) {\n \/\/ Not occupied by our stack, but may belong to a byval argument.\n for (auto const &Arg : ByValArgs) {\n if (Arg.getArea().contains(Address)) {\n return Arg.getArea();\n }\n }\n }\n else {\n \/\/ May be occupied by our stack.\n for (auto const &Alloca : Allocas) {\n auto AllocaArea = Alloca.area();\n if (AllocaArea.contains(Address)) {\n return AllocaArea;\n }\n }\n }\n \n return seec::Maybe();\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ byval argument memory area tracking.\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid TracedFunction::addByValArg(llvm::Argument const * const Arg,\n MemoryArea const &Area)\n{\n assert(!EventOffsetEnd && \"Function has finished recording!\");\n \n std::lock_guard Lock(StackMutex);\n \n ByValArgs.emplace_back(Arg, std::move(Area));\n}\n\nseec::Maybe\nTracedFunction::getParamByValArea(llvm::Argument const *Arg) const\n{\n assert(!EventOffsetEnd && \"Function has finished recording!\");\n\n std::lock_guard Lock(StackMutex);\n\n for (auto const &PBV : ByValArgs)\n if (PBV.getArgument() == Arg)\n return PBV.getArea();\n\n return seec::Maybe();\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Pointer origin tracking.\n\/\/===----------------------------------------------------------------------===\/\/\n\nuintptr_t TracedFunction::getPointerObject(llvm::Argument const *A) const\n{\n auto const It = ArgPointerObjects.find(A);\n return It != ArgPointerObjects.end() ? It->second : 0;\n}\n\nvoid TracedFunction::setPointerObject(llvm::Argument const *A,\n uintptr_t const Object)\n{\n ArgPointerObjects[A] = Object;\n#if SEEC_DEBUG_PTROBJ\n llvm::errs() << \"set ptr \" << Object << \" for argument \" << *A << \"\\n\";\n#endif\n}\n\nuintptr_t TracedFunction::getPointerObject(llvm::Instruction const *I) const\n{\n auto const It = PointerObjects.find(I);\n return It != PointerObjects.end() ? It->second : 0;\n}\n\nvoid TracedFunction::setPointerObject(llvm::Instruction const *I,\n uintptr_t const Object)\n{\n PointerObjects[I] = Object;\n#if SEEC_DEBUG_PTROBJ\n llvm::errs() << \"set ptr \" << Object << \" for instruction \" << *I << \"\\n\";\n#endif\n}\n\nuintptr_t TracedFunction::getPointerObject(llvm::Value const *V) const\n{\n if (auto const I = llvm::dyn_cast(V))\n return getPointerObject(I);\n else if (auto const A = llvm::dyn_cast(V))\n return getPointerObject(A);\n else if (auto const C = llvm::dyn_cast(V)) {\n if (auto const CE = llvm::dyn_cast(V)) {\n if (CE->isCast()) {\n return getPointerObject(CE->getOperand(0));\n }\n }\n }\n return ThreadListener.getProcessListener().getPointerObject(V);\n}\n\nuintptr_t TracedFunction::transferPointerObject(llvm::Value const *From,\n llvm::Instruction const *To)\n{\n auto const Object = getPointerObject(From);\n if (Object)\n setPointerObject(To, Object);\n return Object;\n}\n\nuintptr_t TracedFunction::transferArgPointerObjectToCall(unsigned const ArgNo)\n{\n auto const Call = llvm::dyn_cast(ActiveInstruction);\n assert(Call && \"No CallInst active!\");\n\n return transferPointerObject(Call->getArgOperand(ArgNo), Call);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Mutators.\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid TracedFunction::finishRecording(offset_uint EventOffsetEnd,\n uint64_t ThreadTimeExited) {\n assert(!this->EventOffsetEnd && \"Function has finished recording!\");\n \n std::lock_guard Lock(StackMutex);\n \n this->EventOffsetEnd = EventOffsetEnd;\n this->ThreadTimeExited = ThreadTimeExited;\n \n \/\/ clear active-only information\n ActiveInstruction = nullptr;\n Allocas.clear();\n ByValArgs.clear();\n StackLow = 0;\n StackHigh = 0;\n CurrentValues.clear();\n ArgPointerObjects.clear();\n PointerObjects.clear();\n}\n\nvoid TracedFunction::addAlloca(TracedAlloca Alloca) {\n assert(!EventOffsetEnd && \"Function has finished recording!\");\n \n std::lock_guard Lock(StackMutex);\n \n auto const &Area = Alloca.area();\n \n if (Area.address() < StackLow || !StackLow)\n StackLow = Area.address();\n \n if (Area.lastAddress() > StackHigh || !StackHigh)\n StackHigh = Area.lastAddress();\n \n Allocas.push_back(std::move(Alloca));\n}\n\nvoid TracedFunction::stackSave(uintptr_t Key) {\n assert(!EventOffsetEnd && \"Function has finished recording!\");\n \n std::lock_guard Lock(StackMutex);\n \n StackSaves[Key] = Allocas;\n}\n\nMemoryArea TracedFunction::stackRestore(uintptr_t Key) {\n assert(!EventOffsetEnd && \"Function has finished recording!\");\n \n std::lock_guard Lock(StackMutex);\n \n auto const &RestoreAllocas = StackSaves[Key];\n \n \/\/ Calculate invalidated memory area. This is the area occupied by all\n \/\/ allocas that are currently active, but will be removed by the restore.\n uintptr_t ClearLow = 0;\n uintptr_t ClearHigh = 0;\n \n for (std::size_t i = 0; i < Allocas.size(); ++i) {\n if (i >= RestoreAllocas.size() || Allocas[i] != RestoreAllocas[i]) {\n auto FirstArea = Allocas[i].area();\n auto FinalArea = Allocas.back().area();\n \n ClearLow = std::min(FirstArea.address(), FinalArea.address());\n ClearHigh = std::max(FirstArea.lastAddress(), FinalArea.lastAddress());\n \n break;\n }\n }\n \n \/\/ Restore saved allocas.\n Allocas = RestoreAllocas;\n \n return MemoryArea(ClearLow, (ClearHigh - ClearLow) + 1);\n}\n\n\n} \/\/ namespace trace (in seec)\n\n} \/\/ namespace seec\nUpdate pointer object for byval argument pointers (because it will differ from the caller's pointer, but is valid).\/\/===- lib\/Trace\/TracedFunction.cpp ---------------------------------------===\/\/\n\/\/\n\/\/ SeeC\n\/\/\n\/\/ This file is distributed under The MIT License (MIT). See LICENSE.TXT for\n\/\/ details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"seec\/Trace\/TracedFunction.hpp\"\n#include \"seec\/Trace\/TraceThreadListener.hpp\"\n\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Instruction.h\"\n\n#define SEEC_DEBUG_PTROBJ 0\n\n\nnamespace seec {\n\nnamespace trace {\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Support getCurrentRuntimeValue.\n\/\/===----------------------------------------------------------------------===\/\/\n\nuintptr_t\nTracedFunction::getRuntimeAddress(llvm::GlobalVariable const *GV) const\n{\n return ThreadListener.getRuntimeAddress(GV);\n}\n\nuintptr_t TracedFunction::getRuntimeAddress(llvm::Function const *F) const\n{\n return ThreadListener.getRuntimeAddress(F);\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Accessors for active-only information.\n\/\/===----------------------------------------------------------------------===\/\/\n\nseec::Maybe\nTracedFunction::getContainingMemoryArea(uintptr_t Address) const\n{\n std::lock_guard Lock(StackMutex);\n \n if (Address < StackLow || Address > StackHigh) {\n \/\/ Not occupied by our stack, but may belong to a byval argument.\n for (auto const &Arg : ByValArgs) {\n if (Arg.getArea().contains(Address)) {\n return Arg.getArea();\n }\n }\n }\n else {\n \/\/ May be occupied by our stack.\n for (auto const &Alloca : Allocas) {\n auto AllocaArea = Alloca.area();\n if (AllocaArea.contains(Address)) {\n return AllocaArea;\n }\n }\n }\n \n return seec::Maybe();\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ byval argument memory area tracking.\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid TracedFunction::addByValArg(llvm::Argument const * const Arg,\n MemoryArea const &Area)\n{\n assert(!EventOffsetEnd && \"Function has finished recording!\");\n \n ArgPointerObjects[Arg] = Area.start();\n\n std::lock_guard Lock(StackMutex);\n \n ByValArgs.emplace_back(Arg, std::move(Area));\n}\n\nseec::Maybe\nTracedFunction::getParamByValArea(llvm::Argument const *Arg) const\n{\n assert(!EventOffsetEnd && \"Function has finished recording!\");\n\n std::lock_guard Lock(StackMutex);\n\n for (auto const &PBV : ByValArgs)\n if (PBV.getArgument() == Arg)\n return PBV.getArea();\n\n return seec::Maybe();\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Pointer origin tracking.\n\/\/===----------------------------------------------------------------------===\/\/\n\nuintptr_t TracedFunction::getPointerObject(llvm::Argument const *A) const\n{\n auto const It = ArgPointerObjects.find(A);\n return It != ArgPointerObjects.end() ? It->second : 0;\n}\n\nvoid TracedFunction::setPointerObject(llvm::Argument const *A,\n uintptr_t const Object)\n{\n ArgPointerObjects[A] = Object;\n#if SEEC_DEBUG_PTROBJ\n llvm::errs() << \"set ptr \" << Object << \" for argument \" << *A << \"\\n\";\n#endif\n}\n\nuintptr_t TracedFunction::getPointerObject(llvm::Instruction const *I) const\n{\n auto const It = PointerObjects.find(I);\n return It != PointerObjects.end() ? It->second : 0;\n}\n\nvoid TracedFunction::setPointerObject(llvm::Instruction const *I,\n uintptr_t const Object)\n{\n PointerObjects[I] = Object;\n#if SEEC_DEBUG_PTROBJ\n llvm::errs() << \"set ptr \" << Object << \" for instruction \" << *I << \"\\n\";\n#endif\n}\n\nuintptr_t TracedFunction::getPointerObject(llvm::Value const *V) const\n{\n if (auto const I = llvm::dyn_cast(V))\n return getPointerObject(I);\n else if (auto const A = llvm::dyn_cast(V))\n return getPointerObject(A);\n else if (auto const C = llvm::dyn_cast(V)) {\n if (auto const CE = llvm::dyn_cast(V)) {\n if (CE->isCast()) {\n return getPointerObject(CE->getOperand(0));\n }\n }\n }\n return ThreadListener.getProcessListener().getPointerObject(V);\n}\n\nuintptr_t TracedFunction::transferPointerObject(llvm::Value const *From,\n llvm::Instruction const *To)\n{\n auto const Object = getPointerObject(From);\n if (Object)\n setPointerObject(To, Object);\n return Object;\n}\n\nuintptr_t TracedFunction::transferArgPointerObjectToCall(unsigned const ArgNo)\n{\n auto const Call = llvm::dyn_cast(ActiveInstruction);\n assert(Call && \"No CallInst active!\");\n\n return transferPointerObject(Call->getArgOperand(ArgNo), Call);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Mutators.\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid TracedFunction::finishRecording(offset_uint EventOffsetEnd,\n uint64_t ThreadTimeExited) {\n assert(!this->EventOffsetEnd && \"Function has finished recording!\");\n \n std::lock_guard Lock(StackMutex);\n \n this->EventOffsetEnd = EventOffsetEnd;\n this->ThreadTimeExited = ThreadTimeExited;\n \n \/\/ clear active-only information\n ActiveInstruction = nullptr;\n Allocas.clear();\n ByValArgs.clear();\n StackLow = 0;\n StackHigh = 0;\n CurrentValues.clear();\n ArgPointerObjects.clear();\n PointerObjects.clear();\n}\n\nvoid TracedFunction::addAlloca(TracedAlloca Alloca) {\n assert(!EventOffsetEnd && \"Function has finished recording!\");\n \n std::lock_guard Lock(StackMutex);\n \n auto const &Area = Alloca.area();\n \n if (Area.address() < StackLow || !StackLow)\n StackLow = Area.address();\n \n if (Area.lastAddress() > StackHigh || !StackHigh)\n StackHigh = Area.lastAddress();\n \n Allocas.push_back(std::move(Alloca));\n}\n\nvoid TracedFunction::stackSave(uintptr_t Key) {\n assert(!EventOffsetEnd && \"Function has finished recording!\");\n \n std::lock_guard Lock(StackMutex);\n \n StackSaves[Key] = Allocas;\n}\n\nMemoryArea TracedFunction::stackRestore(uintptr_t Key) {\n assert(!EventOffsetEnd && \"Function has finished recording!\");\n \n std::lock_guard Lock(StackMutex);\n \n auto const &RestoreAllocas = StackSaves[Key];\n \n \/\/ Calculate invalidated memory area. This is the area occupied by all\n \/\/ allocas that are currently active, but will be removed by the restore.\n uintptr_t ClearLow = 0;\n uintptr_t ClearHigh = 0;\n \n for (std::size_t i = 0; i < Allocas.size(); ++i) {\n if (i >= RestoreAllocas.size() || Allocas[i] != RestoreAllocas[i]) {\n auto FirstArea = Allocas[i].area();\n auto FinalArea = Allocas.back().area();\n \n ClearLow = std::min(FirstArea.address(), FinalArea.address());\n ClearHigh = std::max(FirstArea.lastAddress(), FinalArea.lastAddress());\n \n break;\n }\n }\n \n \/\/ Restore saved allocas.\n Allocas = RestoreAllocas;\n \n return MemoryArea(ClearLow, (ClearHigh - ClearLow) + 1);\n}\n\n\n} \/\/ namespace trace (in seec)\n\n} \/\/ namespace seec\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2017, Ubiquity Robotics\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met: \n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. \n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution. \n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are\n * those of the authors and should not be interpreted as representing official\n * policies, either expressed or implied, of the FreeBSD Project.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\nusing namespace std;\n\n\n\/\/ Radians to degrees\n\nstatic double rad2deg(double rad)\n{\n return rad * 180.0 \/ M_PI;\n}\n\n\/\/ retreive the 3 DOF we are interested in from a Transform\n\nstatic void getPose(const tf2::Transform& T, double& x, double& y, double& yaw)\n{\n tf2::Vector3 trans = T.getOrigin();\n x = trans.x();\n y = trans.y();\n\n double roll, pitch;\n T.getBasis().getRPY(roll, pitch, yaw);\n}\n\n\nclass MoveBasic {\n private:\n ros::Subscriber goalSub;\n ros::Publisher cmdPub;\n\n double angularVelocity;\n double angularTolerance;\n\n double linearVelocity;\n double linearTolerance;\n\n tf2_ros::Buffer tfBuffer;\n tf2_ros::TransformListener listener;\n\n tf2::Transform goalOdom;\n bool haveGoal;\n\n void goalCallback(const geometry_msgs::PoseStamped::ConstPtr &msg);\n void sendCmd(double angular, double linear);\n\n bool getTransform(const std::string& from, const std::string& to,\n tf2::Transform& tf);\n\n public:\n MoveBasic(ros::NodeHandle &nh);\n\n void run();\n\n bool handleRotation();\n bool handleLinear();\n};\n\n\n\/\/ Constructor\n\nMoveBasic::MoveBasic(ros::NodeHandle &nh): tfBuffer(ros::Duration(30.0)),\n listener(tfBuffer), haveGoal(false)\n{\n nh.param(\"angular_velocity\", angularVelocity, 0.3);\n nh.param(\"angular_tolerance\", angularTolerance, 0.01);\n\n nh.param(\"linear_velocity\", linearVelocity, 0.4);\n nh.param(\"linear_tolerance\", linearTolerance, 0.01);\n\n cmdPub = ros::Publisher(nh.advertise(\"\/cmd_vel\", 1));\n\n goalSub = nh.subscribe(\"\/move_base_simple\/goal\", 1,\n &MoveBasic::goalCallback, this);\n\n ROS_INFO(\"Move Basic ready\");\n}\n\n\n\/\/ Lookup the specified transform, returns true on success\n\nbool MoveBasic::getTransform(const std::string& from, const std::string& to,\n tf2::Transform& tf)\n{\n try {\n geometry_msgs::TransformStamped tfs =\n tfBuffer.lookupTransform(to, from, ros::Time(0));\n tf2::fromMsg(tfs.transform, tf);\n return true;\n }\n catch (tf2::TransformException &ex) {\n ROS_WARN(\"%s\", ex.what());\n return false;\n }\n}\n\n\/\/ Called when a simple goal message is received\n\nvoid MoveBasic::goalCallback(const geometry_msgs::PoseStamped::ConstPtr &msg)\n{\n tf2::Transform goal;\n tf2::fromMsg(msg->pose, goal);\n string frameId = msg->header.frame_id;\n\n double x, y, yaw;\n getPose(goal, x, y, yaw);\n ROS_INFO(\"Received goal %f %f %f\", x, y, rad2deg(yaw));\n\n tf2::Transform tfMapOdom;\n if (!getTransform(frameId, \"odom\", tfMapOdom)) {\n ROS_WARN(\"Cannot determine robot pose\");\n return;\n }\n goalOdom = tfMapOdom * goal;\n\n \/\/goalOdom = goal;\n getPose(goalOdom, x, y, yaw);\n ROS_INFO(\"Goal in odom %f %f %f\", x, y, rad2deg(yaw));\n haveGoal = true;\n}\n\n\/\/ Send a motion command\n\nvoid MoveBasic::sendCmd(double angular, double linear)\n{\n geometry_msgs::Twist msg;\n msg.angular.z = angular;\n msg.linear.x = linear;\n\n cmdPub.publish(msg);\n}\n\n\/\/ Main loop\n\nvoid MoveBasic::run()\n{\n ros::Rate r(20);\n while (ros::ok()) {\n ros::spinOnce();\n r.sleep();\n\n if (haveGoal) {\n haveGoal = false;\n handleRotation();\n handleLinear();\n }\n }\n}\n\n\/\/ Do angular part of goal\n\nbool MoveBasic::handleRotation()\n{\n bool done = false;\n ros::Rate r(50);\n\n while (!done && ros::ok()) {\n ros::spinOnce();\n r.sleep();\n\n tf2::Transform poseOdom;\n if (!getTransform(\"base_link\", \"odom\", poseOdom)) {\n ROS_WARN(\"Cannot determine robot pose for rotation\");\n continue;\n }\n\n tf2::Vector3 linear = goalOdom.getOrigin() - poseOdom.getOrigin();\n double requestedYaw = atan2(linear.y(), linear.x());\n \n double x, y, currentYaw;\n getPose(poseOdom, x, y, currentYaw);\n\n double demand = requestedYaw - currentYaw;\n if (demand < -M_PI) demand += 2 * M_PI;\n if (demand > M_PI) demand -= 2 * M_PI;\n\n double velocity = 0;\n if (demand < 0) {\n velocity = -angularVelocity;\n }\n else {\n velocity = angularVelocity;\n }\n\n if (haveGoal) { \/\/ new goal received\n ROS_INFO(\"Stopping rotation due to new goal\");\n done = true;\n velocity = 0;\n }\n\/\/ ROS_INFO(\"Demand %f %f %f\", rad2deg(demand), demand, velocity);\n if (fabs(demand) < angularTolerance) {\n velocity = 0;\n done = true;\n ROS_INFO(\"Done rotation, error %f radians %f degrees\", demand, rad2deg(demand));\n }\n sendCmd(velocity, 0);\n }\n return done;\n}\n\n\n\/\/ Do linear part of goal\n\nbool MoveBasic::handleLinear()\n{\n bool done = false;\n ros::Rate r(50);\n\n tf2::Transform poseOdomInitial;\n if (!getTransform(\"base_link\", \"odom\", poseOdomInitial)) {\n ROS_WARN(\"Cannot determine robot pose for linrar\");\n return false;\n }\n\n tf2::Vector3 linear = goalOdom.getOrigin() - poseOdomInitial.getOrigin();\n double requestedDist = linear.length();;\n ROS_INFO(\"Requested distance %f\", requestedDist);\n\n while (!done && ros::ok()) {\n ros::spinOnce();\n r.sleep();\n\n tf2::Transform poseOdom;\n if (!getTransform(\"base_link\", \"odom\", poseOdom)) {\n ROS_WARN(\"Cannot determine robot pose for linear\");\n continue;\n }\n\n tf2::Vector3 travelled = poseOdomInitial.getOrigin() - poseOdom.getOrigin();\n double distTravelled = travelled.length();;\n \n double demand = requestedDist - distTravelled;\n double velocity = linearVelocity;\n\n if (haveGoal) { \/\/ new goal received\n ROS_INFO(\"Stopping rotation due to new goal\");\n done = true;\n velocity = 0;\n }\n\n\/\/ ROS_INFO(\"Demand %f %f\", requestedDist-distTravelled, velocity);\n\n if (distTravelled > requestedDist - linearTolerance) {\n velocity = 0;\n done = true;\n ROS_INFO(\"Done linear, error %f meters\", demand);\n }\n sendCmd(0, velocity);\n }\n return done;\n}\n\n\nint main(int argc, char ** argv) {\n ros::init(argc, argv, \"move_basic\");\n ros::NodeHandle nh(\"~\");\n MoveBasic node(nh);\n node.run();\n\n return 0;\n}\nAddress Rohan's comments: final rotation, std::abs(), publish path\/*\n * Copyright (c) 2017, Ubiquity Robotics\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met: \n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. \n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution. \n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are\n * those of the authors and should not be interpreted as representing official\n * policies, either expressed or implied, of the FreeBSD Project.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n\nclass MoveBasic {\n private:\n ros::Subscriber goalSub;\n ros::Publisher cmdPub;\n ros::Publisher pathPub;\n\n double angularVelocity;\n double angularTolerance;\n\n double linearVelocity;\n double linearTolerance;\n\n tf2_ros::Buffer tfBuffer;\n tf2_ros::TransformListener listener;\n\n tf2::Transform goalOdom;\n bool haveGoal;\n\n void goalCallback(const geometry_msgs::PoseStamped::ConstPtr &msg);\n void sendCmd(double angular, double linear);\n\n bool getTransform(const std::string& from, const std::string& to,\n tf2::Transform& tf);\n\n bool handleRotation();\n bool handleLinear();\n\n public:\n MoveBasic(ros::NodeHandle &nh);\n\n void run();\n\n bool moveLinear(double requestedDistance);\n bool rotateTo(double requestedYaw);\n bool rotateRel(double yaw);\n};\n\n\n\/\/ Radians to degrees\n\nstatic double rad2deg(double rad)\n{\n return rad * 180.0 \/ M_PI;\n}\n\n\n\/\/ Adjust angle to be between -PI and PI\n\nstatic void normalizeAngle(double& angle)\n{\n if (angle < -M_PI) {\n angle += 2 * M_PI;\n }\n if (angle > M_PI) {\n angle -= 2 * M_PI;\n }\n}\n\n\n\/\/ retreive the 3 DOF we are interested in from a Transform\n\nstatic void getPose(const tf2::Transform& tf, double& x, double& y, double& yaw)\n{\n tf2::Vector3 trans = tf.getOrigin();\n x = trans.x();\n y = trans.y();\n\n double roll, pitch;\n tf.getBasis().getRPY(roll, pitch, yaw);\n}\n\n\/\/ Constructor\n\nMoveBasic::MoveBasic(ros::NodeHandle &nh): tfBuffer(ros::Duration(30.0)),\n listener(tfBuffer), haveGoal(false)\n{\n nh.param(\"angular_velocity\", angularVelocity, 0.3);\n nh.param(\"angular_tolerance\", angularTolerance, 0.01);\n\n nh.param(\"linear_velocity\", linearVelocity, 0.4);\n nh.param(\"linear_tolerance\", linearTolerance, 0.01);\n\n cmdPub = ros::Publisher(nh.advertise(\"\/cmd_vel\", 1));\n\n pathPub = ros::Publisher(nh.advertise(\"\/plan\", 1));\n\n goalSub = nh.subscribe(\"\/move_base_simple\/goal\", 1,\n &MoveBasic::goalCallback, this);\n\n ROS_INFO(\"Move Basic ready\");\n}\n\n\n\/\/ Lookup the specified transform, returns true on success\n\nbool MoveBasic::getTransform(const std::string& from, const std::string& to,\n tf2::Transform& tf)\n{\n try {\n geometry_msgs::TransformStamped tfs =\n tfBuffer.lookupTransform(to, from, ros::Time(0));\n tf2::fromMsg(tfs.transform, tf);\n return true;\n }\n catch (tf2::TransformException &ex) {\n ROS_WARN(\"%s\", ex.what());\n return false;\n }\n}\n\n\n\/\/ Called when a simple goal message is received\n\nvoid MoveBasic::goalCallback(const geometry_msgs::PoseStamped::ConstPtr &msg)\n{\n tf2::Transform goal;\n tf2::fromMsg(msg->pose, goal);\n std::string frameId = msg->header.frame_id;\n\n double x, y, yaw;\n getPose(goal, x, y, yaw);\n ROS_INFO(\"Received goal %f %f %f\", x, y, rad2deg(yaw));\n\n tf2::Transform tfMapOdom;\n if (!getTransform(frameId, \"odom\", tfMapOdom)) {\n ROS_WARN(\"Cannot determine robot pose\");\n return;\n }\n goalOdom = tfMapOdom * goal;\n\n getPose(goalOdom, x, y, yaw);\n ROS_INFO(\"Goal in odom %f %f %f\", x, y, rad2deg(yaw));\n haveGoal = true;\n\n nav_msgs::Path path;\n geometry_msgs::PoseStamped p0, p1;\n path.header.frame_id = \"odom\";\n p0.pose.position.x = x;\n p0.pose.position.y = y;\n path.poses.push_back(p0);\n\n tf2::Transform poseOdom;\n if (!getTransform(\"base_link\", \"odom\", poseOdom)) {\n ROS_WARN(\"Cannot determine robot pose for rotation\");\n return;\n }\n getPose(poseOdom, x, y, yaw);\n p1.pose.position.x = x;\n p1.pose.position.y = y;\n path.poses.push_back(p1);\n\n pathPub.publish(path);\n}\n\n\n\/\/ Send a motion command\n\nvoid MoveBasic::sendCmd(double angular, double linear)\n{\n geometry_msgs::Twist msg;\n msg.angular.z = angular;\n msg.linear.x = linear;\n\n cmdPub.publish(msg);\n}\n\n\n\/\/ Main loop\n\nvoid MoveBasic::run()\n{\n ros::Rate r(20);\n while (ros::ok()) {\n ros::spinOnce();\n r.sleep();\n\n if (haveGoal) {\n haveGoal = false;\n if (!handleRotation()) {\n continue;\n }\n if (!handleLinear()) {\n continue;\n }\n double x, y, yaw;\n getPose(goalOdom, x, y, yaw);\n rotateTo(yaw);\n }\n }\n}\n\n\n\/\/ Do angular part of goal\n\nbool MoveBasic::handleRotation()\n{\n tf2::Transform poseOdom;\n if (!getTransform(\"base_link\", \"odom\", poseOdom)) {\n ROS_WARN(\"Cannot determine robot pose for rotation\");\n return false;\n }\n\n tf2::Vector3 linear = goalOdom.getOrigin() - poseOdom.getOrigin();\n double requestedYaw = atan2(linear.y(), linear.x());\n \n return rotateTo(requestedYaw);\n}\n\n\n\/\/ Rotate relative to current orientation\n\nbool MoveBasic::rotateRel(double yaw)\n{\n tf2::Transform poseOdom;\n if (!getTransform(\"base_link\", \"odom\", poseOdom)) {\n ROS_WARN(\"Cannot determine robot pose for rotation\");\n return false;\n }\n\n double x, y, currentYaw;\n getPose(poseOdom, x, y, currentYaw);\n double requestedYaw = currentYaw + yaw;\n normalizeAngle(requestedYaw);\n\n return rotateTo(requestedYaw);\n}\n\n\n\/\/ Rotate to specified orientation (in radians)\n\nbool MoveBasic::rotateTo(double requestedYaw)\n{\n bool done = false;\n ros::Rate r(50);\n\n while (!done && ros::ok()) {\n ros::spinOnce();\n r.sleep();\n\n double x, y, currentYaw;\n tf2::Transform poseOdom;\n if (!getTransform(\"base_link\", \"odom\", poseOdom)) {\n ROS_WARN(\"Cannot determine robot pose for rotation\");\n return false;\n }\n getPose(poseOdom, x, y, currentYaw);\n\n double demand = requestedYaw - currentYaw;\n normalizeAngle(demand);\n\n double velocity = 0;\n if (demand < 0) {\n velocity = -angularVelocity;\n }\n else {\n velocity = angularVelocity;\n }\n\n if (haveGoal) { \/\/ new goal received\n ROS_INFO(\"Stopping rotation due to new goal\");\n done = true;\n velocity = 0;\n }\n\/\/ ROS_INFO(\"Demand %f %f %f\", rad2deg(demand), demand, velocity);\n if (std::abs(demand) < angularTolerance) {\n velocity = 0;\n done = true;\n ROS_INFO(\"Done rotation, error %f radians %f degrees\", demand, rad2deg(demand));\n }\n sendCmd(velocity, 0);\n }\n return done;\n}\n\n\n\/\/ Do linear part of goal\n\nbool MoveBasic::handleLinear()\n{\n bool done = false;\n\n tf2::Transform poseOdomInitial;\n if (!getTransform(\"base_link\", \"odom\", poseOdomInitial)) {\n ROS_WARN(\"Cannot determine robot pose for linrar\");\n return false;\n }\n\n tf2::Vector3 linear = goalOdom.getOrigin() - poseOdomInitial.getOrigin();\n double requestedDistance = linear.length();;\n ROS_INFO(\"Requested distance %f\", requestedDistance);\n\n return moveLinear(requestedDistance);\n}\n\n\n\/\/ Move foreward specified distance\n\nbool MoveBasic::moveLinear(double requestedDistance)\n{\n bool done = false;\n ros::Rate r(50);\n\n tf2::Transform poseOdomInitial;\n if (!getTransform(\"base_link\", \"odom\", poseOdomInitial)) {\n ROS_WARN(\"Cannot determine robot pose for linrar\");\n return false;\n }\n\n while (!done && ros::ok()) {\n ros::spinOnce();\n r.sleep();\n\n tf2::Transform poseOdom;\n if (!getTransform(\"base_link\", \"odom\", poseOdom)) {\n ROS_WARN(\"Cannot determine robot pose for linear\");\n continue;\n }\n\n tf2::Vector3 travelled = poseOdomInitial.getOrigin() - poseOdom.getOrigin();\n double distTravelled = travelled.length();;\n\n double demand = requestedDistance - distTravelled;\n double velocity = linearVelocity;\n\n if (haveGoal) { \/\/ new goal received\n ROS_INFO(\"Stopping rotation due to new goal\");\n done = true;\n velocity = 0;\n }\n\n\/\/ ROS_INFO(\"Demand %f %f\", requestedDist-distTravelled, velocity);\n\n if (distTravelled > requestedDistance - linearTolerance) {\n velocity = 0;\n done = true;\n ROS_INFO(\"Done linear, error %f meters\", demand);\n }\n sendCmd(0, velocity);\n }\n return done;\n}\n\n\nint main(int argc, char ** argv) {\n ros::init(argc, argv, \"move_basic\");\n ros::NodeHandle nh(\"~\");\n MoveBasic node(nh);\n node.run();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*********************************\/\n\/* Motion flow computation class *\/\n\/*********************************\/\n#include \"nebulaFlow.h\"\n\nvoid nebulaFlow::setup(){\n \/\/ setup flow parameter GUI\n guiGrp.setName(\"Motion flow parameters\");\n guiGrp.add(enabled.set(\"enable\",true));\n guiGrp.add(forceCPU.set(\"Force CPU\", false));\n guiGrp.add(fbPyrScale.set(\"fbPyrScale\", .5, 0, .99));\n guiGrp.add(fbLevels.set(\"fbLevels\", 4, 1, 8));\n guiGrp.add(fbIterations.set(\"fbIterations\", 2, 1, 8));\n guiGrp.add(fbPolyN.set(\"fbPolyN\", 7, 5, 10));\n guiGrp.add(fbPolySigma.set(\"fbPolySigma\", 1.5, 1.1, 2));\n guiGrp.add(fbUseGaussian.set(\"fbUseGaussian\", false));\n guiGrp.add(fbWinSize.set(\"winSize\", 32, 4, 64));\n\n \/\/ OpenCL setup\n cv::initModule_video();\n cv::setUseOptimized(true);\n cv::setNumThreads(8);\n\n cv::ocl::DevicesInfo devicesInfo;\n cv::ocl::getOpenCLDevices(devicesInfo);\n ofLogNotice(\"nebulaFlow\") << \"Found \" << devicesInfo.size() << \" OpenCL device(s).\";\n for ( size_t i = 0; i < devicesInfo.size(); i++){\n ofLogNotice(\"nebulaFlow\") << devicesInfo[i]->deviceVendor << \" \" << devicesInfo[i];\n }\n\n if ( devicesInfo.size() == 0 ){\n ofLogNotice(\"nebulaFlow\") << \"can't find OpenCL device, switch to CPU mode\";\n gpuMode = false;\n } else {\n gpuMode = true;\n }\n}\n\nvoid nebulaFlow::update(ofPixels &img){\n if(!enabled) return;\n\n if ( gpuMode ){\n oclFbFlow.pyrScale=fbPyrScale;\n oclFbFlow.numLevels=fbLevels;\n oclFbFlow.winSize=fbWinSize;\n oclFbFlow.numIters=fbIterations;\n oclFbFlow.polyN=fbPolyN;\n oclFbFlow.polySigma=fbPolySigma;\n\n cv::Mat input = ofxCv::toCv(img), gray;\n if(input.channels() == 1){\n gray = input;\n } else {\n cv::cvtColor(input, gray, CV_RGB2GRAY);\n }\n d_input = gray;\n if ( m_flow.size() != d_input.size() ) m_flow.create(d_input.size(), CV_32FC2);\n if ( d_flow.size() != d_input.size() ) d_flow.create(d_input.size(), CV_32FC2);\n if ( d_prev.size() != d_input.size() ) d_prev.create(d_input.size(), CV_8UC1);\n if ( d_flowx.size() != d_input.size() ) d_flowx.create(d_input.size(), CV_32FC1);\n if ( d_flowy.size() != d_input.size() ) d_flowy.create(d_input.size(), CV_32FC1);\n oclFbFlow(d_prev, d_input, d_flowx, d_flowy);\n const vector matVec = { d_flowx, d_flowy };\n cv::ocl::merge(matVec, d_flow);\n d_flow.download(m_flow);\n d_input.copyTo(d_prev); \/\/ TODO use copyTo to apply mask\n } else {\n flow.setPyramidScale(fbPyrScale);\n flow.setNumLevels(fbLevels);\n flow.setWindowSize(fbWinSize);\n flow.setNumIterations(fbIterations);\n flow.setPolyN(fbPolyN);\n flow.setPolySigma(fbPolySigma);\n flow.setUseGaussian(fbUseGaussian);\n\n flow.calcOpticalFlow(img);\n }\n}\n\nvoid nebulaFlow::draw(int x, int y, int w, int h){\n if(!enabled) return;\n flow.draw(x,y,w,h);\n if ( gpuMode )\n ofDrawBitmapStringHighlight(\"GPU Mode\", ofPoint(x+10,y+10), ofColor(255,0,0), ofColor(255,255,255));\n}\ndraw GPU flow\/*********************************\/\n\/* Motion flow computation class *\/\n\/*********************************\/\n#include \"nebulaFlow.h\"\n\nvoid nebulaFlow::setup(){\n \/\/ setup flow parameter GUI\n guiGrp.setName(\"Motion flow parameters\");\n guiGrp.add(enabled.set(\"enable\",true));\n guiGrp.add(forceCPU.set(\"Force CPU\", false));\n guiGrp.add(fbPyrScale.set(\"fbPyrScale\", .5, 0, .99));\n guiGrp.add(fbLevels.set(\"fbLevels\", 4, 1, 8));\n guiGrp.add(fbIterations.set(\"fbIterations\", 2, 1, 8));\n guiGrp.add(fbPolyN.set(\"fbPolyN\", 7, 5, 10));\n guiGrp.add(fbPolySigma.set(\"fbPolySigma\", 1.5, 1.1, 2));\n guiGrp.add(fbUseGaussian.set(\"fbUseGaussian\", false));\n guiGrp.add(fbWinSize.set(\"winSize\", 32, 4, 64));\n\n \/\/ OpenCL setup\n cv::initModule_video();\n cv::setUseOptimized(true);\n cv::setNumThreads(8);\n\n cv::ocl::DevicesInfo devicesInfo;\n cv::ocl::getOpenCLDevices(devicesInfo);\n ofLogNotice(\"nebulaFlow\") << \"Found \" << devicesInfo.size() << \" OpenCL device(s).\";\n for ( size_t i = 0; i < devicesInfo.size(); i++){\n ofLogNotice(\"nebulaFlow\") << devicesInfo[i]->deviceVendor << \" \" << devicesInfo[i];\n }\n\n if ( devicesInfo.size() == 0 ){\n ofLogNotice(\"nebulaFlow\") << \"can't find OpenCL device, switch to CPU mode\";\n gpuMode = false;\n } else {\n gpuMode = true;\n }\n}\n\nvoid nebulaFlow::update(ofPixels &img){\n if(!enabled) return;\n\n if ( gpuMode ){\n oclFbFlow.pyrScale=fbPyrScale;\n oclFbFlow.numLevels=fbLevels;\n oclFbFlow.winSize=fbWinSize;\n oclFbFlow.numIters=fbIterations;\n oclFbFlow.polyN=fbPolyN;\n oclFbFlow.polySigma=fbPolySigma;\n\n cv::Mat input = ofxCv::toCv(img), gray;\n if(input.channels() == 1){\n gray = input;\n } else {\n cv::cvtColor(input, gray, CV_RGB2GRAY);\n }\n d_input = gray;\n if ( m_flow.size() != d_input.size() ) m_flow.create(d_input.size(), CV_32FC2);\n if ( d_flow.size() != d_input.size() ) d_flow.create(d_input.size(), CV_32FC2);\n if ( d_prev.size() != d_input.size() ) d_prev.create(d_input.size(), CV_8UC1);\n if ( d_flowx.size() != d_input.size() ) d_flowx.create(d_input.size(), CV_32FC1);\n if ( d_flowy.size() != d_input.size() ) d_flowy.create(d_input.size(), CV_32FC1);\n oclFbFlow(d_prev, d_input, d_flowx, d_flowy);\n const vector matVec = { d_flowx, d_flowy };\n cv::ocl::merge(matVec, d_flow);\n d_flow.download(m_flow);\n d_input.copyTo(d_prev); \/\/ TODO use copyTo to apply mask\n } else {\n flow.setPyramidScale(fbPyrScale);\n flow.setNumLevels(fbLevels);\n flow.setWindowSize(fbWinSize);\n flow.setNumIterations(fbIterations);\n flow.setPolyN(fbPolyN);\n flow.setPolySigma(fbPolySigma);\n flow.setUseGaussian(fbUseGaussian);\n\n flow.calcOpticalFlow(img);\n }\n}\n\nvoid nebulaFlow::draw(int x, int y, int w, int h){\n if(!enabled) return;\n if ( gpuMode ){\n ofDrawBitmapStringHighlight(\"GPU Mode\", ofPoint(x+10,y+10), ofColor(255,0,0), ofColor(255,255,255));\n ofRectangle rect(x,y,w,h);\n ofVec2f offset(rect.x,rect.y);\n ofVec2f scale(rect.width\/m_flow.cols, rect.height\/m_flow.rows);\n int stepSize = 4; \/\/TODO: make class-level parameteric\n for(int y = 0; y < m_flow.rows; y += stepSize) {\n for(int x = 0; x < m_flow.cols; x += stepSize) {\n ofVec2f cur = ofVec2f(x, y) * scale + offset;\n const cv::Vec2f& vec = m_flow.at(y, x);\n ofDrawLine(cur, ofVec2f(x + vec[0], y + vec[1]) * scale + offset);\n }\n }\n } else {\n flow.draw(x,y,w,h);\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"camera.hpp\"\n#include \"color.hpp\"\n#include \"ray.hpp\"\n#include \"ray_tracer.hpp\"\n#include \"shape.hpp\"\n#include \"sphere.hpp\"\n\nusing V2 = Eigen::Vector2f;\n\n#define EPSILON 0.00001\n#define NOTHING_TO_SEND 32767\n\n\/\/ Helper\nstatic void gen_rand_samples(int bins_per_side, std::vector& points);\n\nRay_Tracer::Ray_Tracer(const Camera& cam, unsigned int x_res, unsigned int y_res,\n Color background_col, unsigned int sample_bins, unsigned int depth_limit) {\n this->cam = cam;\n this->x_res = x_res;\n this->y_res = y_res;\n image_buf.resize(x_res);\n for (std::vector& y_buf: image_buf) {\n y_buf.resize(y_res, Color(0,0,0));\n }\n\n this->background_col = background_col;\n this->sample_bins = sample_bins;\n this->depth_limit = depth_limit;\n}\n\nRay_Tracer& Ray_Tracer::operator=(const Ray_Tracer& rt) {\n\n this->cam = rt.cam;\n this->x_res = rt.x_res;\n this->y_res = rt.y_res;\n image_buf.resize(x_res);\n for (std::vector& y_buf: image_buf)\n y_buf.resize(y_res);\n\n this->background_col = rt.background_col;\n this->sample_bins = rt.sample_bins;\n this->depth_limit = rt.depth_limit;\n\n return *this;\n}\n\nvoid Ray_Tracer::add_shape(Shape* shape) {\n shapes.push_back(shape);\n if (shape->is_light) \n lights.push_back(shape);\n}\n\nvoid Ray_Tracer::add_light(Sphere* sphere) {\n shapes.push_back(sphere);\n if (sphere->is_light) \n lights.push_back(sphere);\n}\n\nvoid Ray_Tracer::free_shapes() {\n for (Shape* shape : shapes)\n delete shape;\n}\n\nbool Ray_Tracer::trace(const Ray& r, float t_min, float t_max, \n Ray_Hit& rh, bool shadow) const {\n bool hit_once = false;\n Ray r2 = r;\n return kd->hit_local(r2, this, t_min, t_max, rh, shadow);\n return hit_once;\n}\n\nvoid Ray_Tracer::worker() {\n\n MPI_Barrier(MPI_COMM_WORLD);\n std::stack rts;\n std::vector rhrs;\n while (true) {\n MPI_Status status;\n int flag;\n MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);\n if (flag) {\n Ray_Trace rt;\n MPI_Recv(&rt, sizeof(Ray_Trace), MPI_BYTE, MPI_ANY_SOURCE,\n MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n\n if (rt.t_min == -1 && rt.t_max == -1)\n break;\n\n rts.push(rt);\n\n\n \/\/ Removed because interleaving comms and work is slow\n \/\/ continue;\n } \/*else {\n if (!rts.empty()) {\n Ray_Trace rt = rts.top();\n rts.pop();\n Ray_Hit rh;\n Ray_Hit_Remote rhr;\n if (!(kd->hit_local(rt.r, this, rt.t_min, rt.t_max, rh, false))) {\n rhr.t = FLT_MAX;\n } else {\n rhr.t = rh.t;\n rhr.col = rh.col;\n rhr.ray_id = rt.ray_id;\n rhrs.push_back(rhr);\n }\n }\n }\n *\/\n }\n\n std::cout << \"Just processing now\" << std::endl;\n \n \/\/ Process remaining rays\n while (!rts.empty()) {\n Ray_Trace rt = rts.top();\n rts.pop();\n Ray_Hit rh;\n Ray_Hit_Remote rhr;\n if (!(kd->hit_local(rt.r, this, rt.t_min, rt.t_max, rh, false))) {\n rhr.t = FLT_MAX;\n } else {\n rhr.t = rh.t;\n rhr.col = rh.col;\n rhr.ray_id = rt.ray_id;\n rhrs.push_back(rhr);\n }\n }\n\n std::cout << \"Done processing, gonna send now\" << std::endl;\n\n if (!rhrs.empty()) {\n \/\/ Send back ray info\n MPI_Ssend(rhrs.data(), sizeof(rhrs[0]) * rhrs.size(), \n MPI_BYTE, 0, 0, MPI_COMM_WORLD);\n } else {\n \/\/ Send a message staying we're done, but have nothing to sedn\n unsigned int done = 0xFFFFFFFF;\n MPI_Ssend(&done, 1, MPI_INT, 0, NOTHING_TO_SEND, MPI_COMM_WORLD);\n }\n\n\/*\n MPI_Barrier(MPI_COMM_WORLD);\n while (true) {\n Ray_Trace rt;\n MPI_Status status;\n MPI_Recv(&rt, sizeof(Ray_Trace), MPI_BYTE, MPI_ANY_SOURCE,\n MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n\n if (rt.t_min == -1 && rt.t_max == -1)\n break;\n \n\n Ray_Hit rh;\n Ray_Hit_Remote rhr;\n if (!(kd->hit_local(rt.r, this, rt.t_min, rt.t_max, rh, false))) {\n rhr.t = FLT_MAX;\n } else {\n rhr.t = rh.t;\n }\n\n rhr.col = rh.col;\n \n MPI_Send(&rhr, sizeof(Ray_Hit_Remote), MPI_BYTE, status.MPI_SOURCE,\n status.MPI_TAG, MPI_COMM_WORLD);\n }\n*\/\n}\n\nvoid Ray_Tracer::trace_all(int rank, int np) {\n\n std::cout << \"hi\" << std::endl;\n if (rank != 0) {\n worker();\n return;\n }\n\n std::vector points;\n MPI_Barrier(MPI_COMM_WORLD);\n for (unsigned int i = 0; i < x_res; ++i) {\n for (unsigned int j = 0; j < x_res; ++j) {\n points.clear();\n gen_rand_samples(sample_bins, points);\n\n Color total;\n for (unsigned int k = 0; k < points.size(); ++k) {\n V2& p = points[k];\n Ray r = cam.make_ray((i + p.x() + 0.5)\/x_res, (j + p.y() + 0.5)\/y_res);\n local_rays.push(r);\n local_dest.push(Int_pair(i, j));\n Ray_Hit rh;\n unsigned int ray_id = i << 19 | j << 6 | k;\n kd->hit(r, this, EPSILON, FLT_MAX, rh, false, ray_id);\n \/\/trace(r, EPSILON, FLT_MAX, rh, false);\n \/\/total += rh.col;\n }\n\/\/ image_buf[i][j] = total \/ points.size();\n }\n }\n\n \/\/ Tell all workers to start processing\n Ray_Trace rt;\n Ray r;\n rt.r = r; \/\/ dummy\n rt.t_min = -1;\n rt.t_max = -1;\n rt.ray_id = 0; \/\/ dummy\n std::cout << \"Done sending Rays\" << std::endl;\n for (int i = 1; i < np; ++i) {\n MPI_Ssend(&rt, sizeof(Ray_Trace), MPI_BYTE, i, 0, MPI_COMM_WORLD);\n }\n\n std::map rhrs;\n\n int procs_to_recv = np - 1;\n while (procs_to_recv > 0) {\n MPI_Status status;\n MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n if (status.MPI_TAG == NOTHING_TO_SEND) {\n int dummy;\n MPI_Recv(&dummy, 1, MPI_INT, MPI_ANY_SOURCE, \n MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n procs_to_recv--;\n continue;\n } else {\n int byte_count;\n MPI_Get_count(&status, MPI_BYTE, &byte_count);\n int elements = byte_count \/ sizeof(Ray_Hit_Remote);\n Ray_Hit_Remote* rhr = new Ray_Hit_Remote[elements]; \n MPI_Recv(rhr, byte_count, MPI_BYTE, status.MPI_SOURCE, \n status.MPI_TAG, MPI_COMM_WORLD, &status);\n\n for (int i = 0; i < elements; ++i) {\n std::pair p;\n p.first = rhr[i].ray_id;\n p.second = rhr[i];\n auto res = rhrs.insert(p); \n if (!res.second) { \/\/ already exists\n if (res.first->second.t > rhr[i].t)\n res.first->second = rhr[i];\n }\n }\n procs_to_recv--;\n }\n }\n\n int samples = points.size();\n for (auto& r : rhrs) {\n int x = r.first >> 19;\n int y = (r.first >> 6) & 0x00001FFF;\n image_buf[x][y] += r.second.col\/ samples;\n }\n\n \/*\n Ray r;\n Ray_Hit rh;\n Int_pair dest;\n int samples = sample_bins*sample_bins;\n omp_set_num_threads(1);\n #pragma omp parallel \n {\n #pragma omp single private(r, dest, rh)\n {\n std::cout << \"hi\" << std::endl;\n while (!(local_rays.empty())) {\n r = local_rays.top();\n local_rays.pop();\n dest = local_dest.top();\n local_dest.pop();\n #pragma omp task firstprivate(r, dest, rh)\n {\n if (trace(r, EPSILON, FLT_MAX, rh, false)) {\n image_buf[dest.first][dest.second] += rh.col \/ samples;\n }\n }\n }\n }\n }\n *\/\n\n return;\n\n}\n\nvoid Ray_Tracer::write_buffer(std::string filename) {\n png::image< png::rgb_pixel > ray_image(x_res, y_res);\n for (unsigned int i = 0; i < x_res; ++i) {\n for (unsigned int j = 0; j < y_res; ++j) {\n ray_image[i][j] = image_buf[i][j].to_png_pixel();\n }\n }\n ray_image.write(filename);\n}\n\nstatic void gen_rand_samples(int bins_per_side, std::vector& points) {\n static std::random_device rd;\n static std::mt19937 gen(rd());\n static std::uniform_real_distribution<> dis(0, 1);\n\n float bin_length = 1.0f \/ bins_per_side;\n\n float bin_x = 0.0;\n float bin_y = 0.0;\n \n for (int i = 0; i < bins_per_side; ++i) { \n for (int j = 0; j < bins_per_side; ++j) { \n float rand_num_unit = dis(gen); \n bin_x = i * bin_length + bin_length*rand_num_unit - 0.5;\n rand_num_unit = dis(gen); \n bin_y = j * bin_length + bin_length*rand_num_unit - 0.5;\n points.push_back(V2(bin_x, bin_y));\n } \n } \n}\nfixed bug where tracing y range is set wrong, this bug doesnt show when tracing a square image#include \n#include \n#include \n#include \n\n#include \"camera.hpp\"\n#include \"color.hpp\"\n#include \"ray.hpp\"\n#include \"ray_tracer.hpp\"\n#include \"shape.hpp\"\n#include \"sphere.hpp\"\n\nusing V2 = Eigen::Vector2f;\n\n#define EPSILON 0.00001\n#define NOTHING_TO_SEND 32767\n\n\/\/ Helper\nstatic void gen_rand_samples(int bins_per_side, std::vector& points);\n\nRay_Tracer::Ray_Tracer(const Camera& cam, unsigned int x_res, unsigned int y_res,\n Color background_col, unsigned int sample_bins, unsigned int depth_limit) {\n this->cam = cam;\n this->x_res = x_res;\n this->y_res = y_res;\n image_buf.resize(x_res);\n for (std::vector& y_buf: image_buf) {\n y_buf.resize(y_res, Color(0,0,0));\n }\n\n this->background_col = background_col;\n this->sample_bins = sample_bins;\n this->depth_limit = depth_limit;\n}\n\nRay_Tracer& Ray_Tracer::operator=(const Ray_Tracer& rt) {\n\n this->cam = rt.cam;\n this->x_res = rt.x_res;\n this->y_res = rt.y_res;\n image_buf.resize(x_res);\n for (std::vector& y_buf: image_buf)\n y_buf.resize(y_res);\n\n this->background_col = rt.background_col;\n this->sample_bins = rt.sample_bins;\n this->depth_limit = rt.depth_limit;\n\n return *this;\n}\n\nvoid Ray_Tracer::add_shape(Shape* shape) {\n shapes.push_back(shape);\n if (shape->is_light) \n lights.push_back(shape);\n}\n\nvoid Ray_Tracer::add_light(Sphere* sphere) {\n shapes.push_back(sphere);\n if (sphere->is_light) \n lights.push_back(sphere);\n}\n\nvoid Ray_Tracer::free_shapes() {\n for (Shape* shape : shapes)\n delete shape;\n}\n\nbool Ray_Tracer::trace(const Ray& r, float t_min, float t_max, \n Ray_Hit& rh, bool shadow) const {\n bool hit_once = false;\n Ray r2 = r;\n return kd->hit_local(r2, this, t_min, t_max, rh, shadow);\n return hit_once;\n}\n\nvoid Ray_Tracer::worker() {\n\n MPI_Barrier(MPI_COMM_WORLD);\n std::stack rts;\n std::vector rhrs;\n while (true) {\n MPI_Status status;\n int flag;\n MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);\n if (flag) {\n Ray_Trace rt;\n MPI_Recv(&rt, sizeof(Ray_Trace), MPI_BYTE, MPI_ANY_SOURCE,\n MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n\n if (rt.t_min == -1 && rt.t_max == -1)\n break;\n\n rts.push(rt);\n\n\n \/\/ Removed because interleaving comms and work is slow\n \/\/ continue;\n } \/*else {\n if (!rts.empty()) {\n Ray_Trace rt = rts.top();\n rts.pop();\n Ray_Hit rh;\n Ray_Hit_Remote rhr;\n if (!(kd->hit_local(rt.r, this, rt.t_min, rt.t_max, rh, false))) {\n rhr.t = FLT_MAX;\n } else {\n rhr.t = rh.t;\n rhr.col = rh.col;\n rhr.ray_id = rt.ray_id;\n rhrs.push_back(rhr);\n }\n }\n }\n *\/\n }\n\n std::cout << \"Just processing now\" << std::endl;\n \n \/\/ Process remaining rays\n while (!rts.empty()) {\n Ray_Trace rt = rts.top();\n rts.pop();\n Ray_Hit rh;\n Ray_Hit_Remote rhr;\n if (!(kd->hit_local(rt.r, this, rt.t_min, rt.t_max, rh, false))) {\n rhr.t = FLT_MAX;\n } else {\n rhr.t = rh.t;\n rhr.col = rh.col;\n rhr.ray_id = rt.ray_id;\n rhrs.push_back(rhr);\n }\n }\n\n std::cout << \"Done processing, gonna send now\" << std::endl;\n\n if (!rhrs.empty()) {\n \/\/ Send back ray info\n MPI_Ssend(rhrs.data(), sizeof(rhrs[0]) * rhrs.size(), \n MPI_BYTE, 0, 0, MPI_COMM_WORLD);\n } else {\n \/\/ Send a message staying we're done, but have nothing to sedn\n unsigned int done = 0xFFFFFFFF;\n MPI_Ssend(&done, 1, MPI_INT, 0, NOTHING_TO_SEND, MPI_COMM_WORLD);\n }\n\n\/*\n MPI_Barrier(MPI_COMM_WORLD);\n while (true) {\n Ray_Trace rt;\n MPI_Status status;\n MPI_Recv(&rt, sizeof(Ray_Trace), MPI_BYTE, MPI_ANY_SOURCE,\n MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n\n if (rt.t_min == -1 && rt.t_max == -1)\n break;\n \n\n Ray_Hit rh;\n Ray_Hit_Remote rhr;\n if (!(kd->hit_local(rt.r, this, rt.t_min, rt.t_max, rh, false))) {\n rhr.t = FLT_MAX;\n } else {\n rhr.t = rh.t;\n }\n\n rhr.col = rh.col;\n \n MPI_Send(&rhr, sizeof(Ray_Hit_Remote), MPI_BYTE, status.MPI_SOURCE,\n status.MPI_TAG, MPI_COMM_WORLD);\n }\n*\/\n}\n\nvoid Ray_Tracer::trace_all(int rank, int np) {\n\n std::cout << \"hi\" << std::endl;\n if (rank != 0) {\n worker();\n return;\n }\n\n std::vector points;\n MPI_Barrier(MPI_COMM_WORLD);\n for (unsigned int i = 0; i < x_res; ++i) {\n for (unsigned int j = 0; j < y_res; ++j) {\n points.clear();\n gen_rand_samples(sample_bins, points);\n\n Color total;\n for (unsigned int k = 0; k < points.size(); ++k) {\n V2& p = points[k];\n Ray r = cam.make_ray((i + p.x() + 0.5)\/x_res, (j + p.y() + 0.5)\/y_res);\n local_rays.push(r);\n local_dest.push(Int_pair(i, j));\n Ray_Hit rh;\n unsigned int ray_id = i << 19 | j << 6 | k;\n kd->hit(r, this, EPSILON, FLT_MAX, rh, false, ray_id);\n \/\/trace(r, EPSILON, FLT_MAX, rh, false);\n \/\/total += rh.col;\n }\n\/\/ image_buf[i][j] = total \/ points.size();\n }\n }\n\n \/\/ Tell all workers to start processing\n Ray_Trace rt;\n Ray r;\n rt.r = r; \/\/ dummy\n rt.t_min = -1;\n rt.t_max = -1;\n rt.ray_id = 0; \/\/ dummy\n std::cout << \"Done sending Rays\" << std::endl;\n for (int i = 1; i < np; ++i) {\n MPI_Ssend(&rt, sizeof(Ray_Trace), MPI_BYTE, i, 0, MPI_COMM_WORLD);\n }\n\n std::map rhrs;\n\n int procs_to_recv = np - 1;\n while (procs_to_recv > 0) {\n MPI_Status status;\n MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n if (status.MPI_TAG == NOTHING_TO_SEND) {\n int dummy;\n MPI_Recv(&dummy, 1, MPI_INT, MPI_ANY_SOURCE, \n MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n procs_to_recv--;\n continue;\n } else {\n int byte_count;\n MPI_Get_count(&status, MPI_BYTE, &byte_count);\n int elements = byte_count \/ sizeof(Ray_Hit_Remote);\n Ray_Hit_Remote* rhr = new Ray_Hit_Remote[elements]; \n MPI_Recv(rhr, byte_count, MPI_BYTE, status.MPI_SOURCE, \n status.MPI_TAG, MPI_COMM_WORLD, &status);\n\n for (int i = 0; i < elements; ++i) {\n std::pair p;\n p.first = rhr[i].ray_id;\n p.second = rhr[i];\n auto res = rhrs.insert(p); \n if (!res.second) { \/\/ already exists\n if (res.first->second.t > rhr[i].t)\n res.first->second = rhr[i];\n }\n }\n procs_to_recv--;\n }\n }\n\n int samples = points.size();\n for (auto& r : rhrs) {\n int x = r.first >> 19;\n int y = (r.first >> 6) & 0x00001FFF;\n image_buf[x][y] += r.second.col\/ samples;\n }\n\n \/*\n Ray r;\n Ray_Hit rh;\n Int_pair dest;\n int samples = sample_bins*sample_bins;\n omp_set_num_threads(1);\n #pragma omp parallel \n {\n #pragma omp single private(r, dest, rh)\n {\n std::cout << \"hi\" << std::endl;\n while (!(local_rays.empty())) {\n r = local_rays.top();\n local_rays.pop();\n dest = local_dest.top();\n local_dest.pop();\n #pragma omp task firstprivate(r, dest, rh)\n {\n if (trace(r, EPSILON, FLT_MAX, rh, false)) {\n image_buf[dest.first][dest.second] += rh.col \/ samples;\n }\n }\n }\n }\n }\n *\/\n\n return;\n\n}\n\nvoid Ray_Tracer::write_buffer(std::string filename) {\n png::image< png::rgb_pixel > ray_image(x_res, y_res);\n for (unsigned int i = 0; i < x_res; ++i) {\n for (unsigned int j = 0; j < y_res; ++j) {\n ray_image[i][j] = image_buf[i][j].to_png_pixel();\n }\n }\n ray_image.write(filename);\n}\n\nstatic void gen_rand_samples(int bins_per_side, std::vector& points) {\n static std::random_device rd;\n static std::mt19937 gen(rd());\n static std::uniform_real_distribution<> dis(0, 1);\n\n float bin_length = 1.0f \/ bins_per_side;\n\n float bin_x = 0.0;\n float bin_y = 0.0;\n \n for (int i = 0; i < bins_per_side; ++i) { \n for (int j = 0; j < bins_per_side; ++j) { \n float rand_num_unit = dis(gen); \n bin_x = i * bin_length + bin_length*rand_num_unit - 0.5;\n rand_num_unit = dis(gen); \n bin_y = j * bin_length + bin_length*rand_num_unit - 0.5;\n points.push_back(V2(bin_x, bin_y));\n } \n } \n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2015-2018 Dubalu LLC. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"replication.h\"\n\n#ifdef XAPIAND_CLUSTERING\n\n#include \"io_utils.h\"\n#include \"length.h\"\n\n\n\/* ____ _ _ _ _\n * | _ \\ ___ _ __ | (_) ___ __ _| |_(_) ___ _ __\n * | |_) \/ _ \\ '_ \\| | |\/ __\/ _` | __| |\/ _ \\| '_ \\\n * | _ < __\/ |_) | | | (_| (_| | |_| | (_) | | | |\n * |_| \\_\\___| .__\/|_|_|\\___\\__,_|\\__|_|\\___\/|_| |_|\n * |_|\n *\/\n\n\nusing dispatch_func = void (Replication::*)(const std::string&);\n\n\nReplication::Replication(BinaryClient* client_)\n\t: client(client_)\n{\n\t\tL_OBJ(\"CREATED REPLICATION OBJ!\");\n}\n\n\nReplication::~Replication()\n{\n\tL_OBJ(\"DELETED REPLICATION OBJ!\");\n}\n\n\nvoid\nReplication::replication_server(ReplicationMessageType type, const std::string &message)\n{\n\tstatic const dispatch_func dispatch[] = {\n\t\t&Replication::msg_get_changesets,\n\t};\n\ttry {\n\t\tif (static_cast(type) >= sizeof(dispatch) \/ sizeof(dispatch[0])) {\n\t\t\tstd::string errmsg(\"Unexpected message type \");\n\t\t\terrmsg += std::to_string(toUType(type));\n\t\t\tTHROW(InvalidArgumentError, errmsg);\n\t\t}\n\t\t(this->*(dispatch[static_cast(type)]))(message);\n\t} catch (...) {\n\t\tclient->checkin_database();\n\t\tthrow;\n\t}\n}\n\n\nvoid\nReplication::msg_get_changesets(const std::string &)\n{\n\tL_REPLICATION(\"Replication::msg_get_changesets\");\n\n\t\/\/ Xapian::Database *db_;\n\t\/\/ const char *p = message.c_str();\n\t\/\/ const char *p_end = p + message.size();\n\n\t\/\/ size_t len = unserialise_length(&p, p_end, true);\n\t\/\/ std::string uuid(p, len);\n\t\/\/ p += len;\n\n\t\/\/ len = unserialise_length(&p, p_end, true);\n\t\/\/ std::string from_revision(p, len);\n\t\/\/ p += len;\n\n\t\/\/ len = unserialise_length(&p, p_end, true);\n\t\/\/ std::string index_path(p, len);\n\t\/\/ p += len;\n\n\t\/\/ \/\/ Select endpoints and get database\n\t\/\/ try {\n\t\/\/ \tendpoints.clear();\n\t\/\/ \tEndpoint endpoint(index_path);\n\t\/\/ \tendpoints.add(endpoint);\n\t\/\/ \tdb_ = get_db();\n\t\/\/ \tif (!db_)\n\t\/\/ \t\tTHROW(InvalidOperationError, \"Server has no open database\");\n\t\/\/ } catch (...) {\n\t\/\/ \tthrow;\n\t\/\/ }\n\n\t\/\/ char path[] = \"\/tmp\/xapian_changesets_sent.XXXXXX\";\n\t\/\/ int fd = mkstemp(path);\n\t\/\/ try {\n\t\/\/ \tstd::string to_revision = databases[db_]->checkout_revision;\n\t\/\/ \tL_REPLICATION(\"Replication::msg_get_changesets for %s (%s) from rev:%s to rev:%s [%d]\", endpoints.as_string(), uuid, repr(from_revision, false), repr(to_revision, false), need_whole_db);\n\n\t\/\/ \tif (fd == -1) {\n\t\/\/ \t\tL_ERR(\"Cannot write to %s (1)\", path);\n\t\/\/ \t\treturn;\n\t\/\/ \t}\n\t\/\/ \t\/\/ db_->write_changesets_to_fd(fd, from_revision, uuid != db_->get_uuid().to_string()); \/\/ FIXME: Implement Replication\n\t\/\/ } catch (...) {\n\t\/\/ \trelease_db(db_);\n\t\/\/ \tio::close(fd);\n\t\/\/ \tio::unlink(path);\n\t\/\/ \tthrow;\n\t\/\/ }\n\t\/\/ release_db(db_);\n\n\t\/\/ send_file(fd);\n\n\t\/\/ io::close(fd);\n\t\/\/ io::unlink(path);\n}\n\n\nvoid\nReplication::replication_client(ReplicationReplyType type, const std::string &message)\n{\n\tstatic const dispatch_func dispatch[] = {\n\t\t&Replication::reply_end_of_changes,\n\t\t&Replication::reply_fail,\n\t\t&Replication::reply_db_header,\n\t\t&Replication::reply_db_filename,\n\t\t&Replication::reply_db_filedata,\n\t\t&Replication::reply_db_footer,\n\t\t&Replication::reply_changeset,\n\t};\n\ttry {\n\t\tif (static_cast(type) >= sizeof(dispatch) \/ sizeof(dispatch[0])) {\n\t\t\tstd::string errmsg(\"Unexpected message type \");\n\t\t\terrmsg += std::to_string(toUType(type));\n\t\t\tTHROW(InvalidArgumentError, errmsg);\n\t\t}\n\t\t(this->*(dispatch[static_cast(type)]))(message);\n\t} catch (...) {\n\t\tclient->checkin_database();\n\t\tthrow;\n\t}\n}\n\n\nvoid\nReplication::reply_end_of_changes(const std::string &)\n{\n\tL_REPLICATION(\"Replication::reply_end_of_changes\");\n\n\t\/\/ if (repl_switched_db) {\n\t\/\/ \tXapiandManager::manager->database_pool.switch_db(*endpoints.cbegin());\n\t\/\/ }\n\n\t\/\/ client->checkin_database();\n\n\t\/\/ shutdown();\n}\n\n\nvoid\nReplication::reply_fail(const std::string &)\n{\n\tL_REPLICATION(\"Replication::reply_fail\");\n\n\t\/\/ L_ERR(\"Replication failure!\");\n\t\/\/ client->checkin_database();\n\n\t\/\/ shutdown();\n}\n\n\nvoid\nReplication::reply_db_header(const std::string &)\n{\n\tL_REPLICATION(\"Replication::reply_db_header\");\n\n\t\/\/ const char *p = message.data();\n\t\/\/ const char *p_end = p + message.size();\n\t\/\/ size_t length = unserialise_length(&p, p_end, true);\n\t\/\/ repl_db_uuid.assign(p, length);\n\t\/\/ p += length;\n\t\/\/ repl_db_revision = unserialise_length(&p, p_end);\n\t\/\/ repl_db_filename.clear();\n\n\t\/\/ Endpoint& endpoint = endpoints[0];\n\t\/\/ std::string path_tmp = endpoint.path + \"\/.tmp\";\n\n\t\/\/ int dir = ::mkdir(path_tmp.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);\n\t\/\/ if (dir == 0) {\n\t\/\/ \tL_DEBUG(\"Directory %s created\", path_tmp);\n\t\/\/ } else if (errno == EEXIST) {\n\t\/\/ \tdelete_files(path_tmp.c_str());\n\t\/\/ \tdir = ::mkdir(path_tmp.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);\n\t\/\/ \tif (dir == 0) {\n\t\/\/ \t\tL_DEBUG(\"Directory %s created\", path_tmp);\n\t\/\/ \t}\n\t\/\/ } else {\n\t\/\/ \tL_ERR(\"Directory %s not created (%s)\", path_tmp, strerror(errno));\n\t\/\/ }\n}\n\n\nvoid\nReplication::reply_db_filename(const std::string &)\n{\n\tL_REPLICATION(\"Replication::reply_db_filename\");\n\n\t\/\/ const char *p = message.data();\n\t\/\/ const char *p_end = p + message.size();\n\t\/\/ repl_db_filename.assign(p, p_end - p);\n}\n\n\nvoid\nReplication::reply_db_filedata(const std::string &)\n{\n\tL_REPLICATION(\"Replication::reply_db_filedata\");\n\n\t\/\/ const char *p = message.data();\n\t\/\/ const char *p_end = p + message.size();\n\n\t\/\/ const Endpoint& endpoint = endpoints[0];\n\n\t\/\/ std::string path = endpoint.path + \"\/.tmp\/\";\n\t\/\/ std::string path_filename = path + repl_db_filename;\n\n\t\/\/ int fd = io::open(path_filename.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644);\n\t\/\/ if (fd != -1) {\n\t\/\/ \tL_REPLICATION(\"path_filename %s\", path_filename);\n\t\/\/ \tif (io::write(fd, p, p_end - p) != p_end - p) {\n\t\/\/ \t\tL_ERR(\"Cannot write to %s\", repl_db_filename);\n\t\/\/ \t\treturn;\n\t\/\/ \t}\n\t\/\/ \tio::close(fd);\n\t\/\/ }\n}\n\n\nvoid\nReplication::reply_db_footer(const std::string &)\n{\n\tL_REPLICATION(\"Replication::reply_db_footer\");\n\n\t\/\/ \/\/ const char *p = message.data();\n\t\/\/ \/\/ const char *p_end = p + message.size();\n\t\/\/ \/\/ size_t revision = unserialise_length(&p, p_end);\n\t\/\/ \/\/ Indicates the end of a DB copy operation, signal switch\n\n\t\/\/ Endpoints endpoints_tmp;\n\t\/\/ Endpoint& endpoint_tmp = endpoints[0];\n\t\/\/ endpoint_tmp.path.append(\"\/.tmp\");\n\t\/\/ endpoints_tmp.insert(endpoint_tmp);\n\n\t\/\/ if (!repl_database_tmp) {\n\t\/\/ \ttry {\n\t\/\/ \t\tXapiandManager::manager->database_pool.checkout(repl_database_tmp, endpoints_tmp, DB_WRITABLE | DB_VOLATILE);\n\t\/\/ \t} catch (const CheckoutError&)\n\t\/\/ \t\tL_ERR(\"Cannot checkout tmp %s\", endpoint_tmp.path);\n\t\/\/ \t}\n\t\/\/ }\n\n\t\/\/ repl_switched_db = true;\n\t\/\/ repl_just_switched_db = true;\n}\n\n\nvoid\nReplication::reply_changeset(const std::string &)\n{\n\tL_REPLICATION(\"Replication::reply_changeset\");\n\n\t\/\/ Xapian::WritableDatabase *wdb_;\n\t\/\/ if (repl_database_tmp) {\n\t\/\/ \twdb_ = static_cast(repl_database_tmp->db.get());\n\t\/\/ } else {\n\t\/\/ \twdb_ = static_cast(database);\n\t\/\/ }\n\n\t\/\/ char path[] = \"\/tmp\/xapian_changes.XXXXXX\";\n\t\/\/ int fd = mkstemp(path);\n\t\/\/ if (fd == -1) {\n\t\/\/ \tL_ERR(\"Cannot write to %s (1)\", path);\n\t\/\/ \treturn;\n\t\/\/ }\n\n\t\/\/ std::string header;\n\t\/\/ header += toUType(ReplicationMessageType::REPLY_CHANGESET);\n\t\/\/ header += serialise_length(message.size());\n\n\t\/\/ if (io::write(fd, header.data(), header.size()) != static_cast(header.size())) {\n\t\/\/ \tL_ERR(\"Cannot write to %s (2)\", path);\n\t\/\/ \treturn;\n\t\/\/ }\n\n\t\/\/ if (io::write(fd, message.data(), message.size()) != static_cast(message.size())) {\n\t\/\/ \tL_ERR(\"Cannot write to %s (3)\", path);\n\t\/\/ \treturn;\n\t\/\/ }\n\n\t\/\/ io::lseek(fd, 0, SEEK_SET);\n\n\t\/\/ try {\n\t\/\/ \t\/\/ wdb_->apply_changeset_from_fd(fd, !repl_just_switched_db); \/\/ FIXME: Implement Replication\n\t\/\/ \trepl_just_switched_db = false;\n\t\/\/ } catch (const MSG_NetworkError& exc) {\n\t\/\/ \tL_EXC(\"ERROR: %s\", exc.get_description());\n\t\/\/ \tio::close(fd);\n\t\/\/ \tio::unlink(path);\n\t\/\/ \tthrow;\n\t\/\/ } catch (const Xapian::DatabaseError& exc) {\n\t\/\/ \tL_EXC(\"ERROR: %s\", exc.get_description());\n\t\/\/ \tio::close(fd);\n\t\/\/ \tio::unlink(path);\n\t\/\/ \tthrow;\n\t\/\/ } catch (...) {\n\t\/\/ \tio::close(fd);\n\t\/\/ \tio::unlink(path);\n\t\/\/ \tthrow;\n\t\/\/ }\n\n\t\/\/ io::close(fd);\n\t\/\/ io::unlink(path);\n}\n\n\nvoid\nReplication::replication_client_file_done()\n{\n\tL_REPLICATION(\"Replication::replication_client_file_done\");\n\n\tchar buf[1024];\n\tconst char *p;\n\tconst char *p_end;\n\tstd::string buffer;\n\n\tssize_t size = io::read(client->file_descriptor, buf, sizeof(buf));\n\tbuffer.append(buf, size);\n\tp = buffer.data();\n\tp_end = p + buffer.size();\n\tconst char *s = p;\n\n\twhile (p != p_end) {\n\t\tReplicationReplyType type = static_cast(*p++);\n\t\tssize_t len = unserialise_length(&p, p_end);\n\t\tsize_t pos = p - s;\n\t\twhile (p_end - p < len || static_cast(p_end - p) < sizeof(buf) \/ 2) {\n\t\t\tsize = io::read(client->file_descriptor, buf, sizeof(buf));\n\t\t\tif (!size) break;\n\t\t\tbuffer.append(buf, size);\n\t\t\ts = p = buffer.data();\n\t\t\tp_end = p + buffer.size();\n\t\t\tp += pos;\n\t\t}\n\t\tif (p_end - p < len) {\n\t\t\tTHROW(Error, \"Replication failure!\");\n\t\t}\n\t\tstd::string msg(p, len);\n\t\tp += len;\n\n\t\treplication_client(type, msg);\n\n\t\tbuffer.erase(0, p - s);\n\t\ts = p = buffer.data();\n\t\tp_end = p + buffer.size();\n\t}\n}\n\n\n#endif \/* XAPIAND_CLUSTERING *\/\nReplication: Added L_CALLs\/*\n * Copyright (C) 2015-2018 Dubalu LLC. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"replication.h\"\n\n#ifdef XAPIAND_CLUSTERING\n\n#include \"io_utils.h\"\n#include \"length.h\"\n\n\n\/* ____ _ _ _ _\n * | _ \\ ___ _ __ | (_) ___ __ _| |_(_) ___ _ __\n * | |_) \/ _ \\ '_ \\| | |\/ __\/ _` | __| |\/ _ \\| '_ \\\n * | _ < __\/ |_) | | | (_| (_| | |_| | (_) | | | |\n * |_| \\_\\___| .__\/|_|_|\\___\\__,_|\\__|_|\\___\/|_| |_|\n * |_|\n *\/\n\n\nusing dispatch_func = void (Replication::*)(const std::string&);\n\n\nReplication::Replication(BinaryClient* client_)\n\t: client(client_)\n{\n\tL_OBJ(\"CREATED REPLICATION OBJ!\");\n}\n\n\nReplication::~Replication()\n{\n\tL_OBJ(\"DELETED REPLICATION OBJ!\");\n}\n\n\nvoid\nReplication::replication_server(ReplicationMessageType type, const std::string &message)\n{\n\tL_CALL(\"Replication::replication_server(%s, )\", ReplicationMessageTypeNames[static_cast(type)]);\n\n\tstatic const dispatch_func dispatch[] = {\n\t\t&Replication::msg_get_changesets,\n\t};\n\ttry {\n\t\tif (static_cast(type) >= sizeof(dispatch) \/ sizeof(dispatch[0])) {\n\t\t\tstd::string errmsg(\"Unexpected message type \");\n\t\t\terrmsg += std::to_string(toUType(type));\n\t\t\tTHROW(InvalidArgumentError, errmsg);\n\t\t}\n\t\t(this->*(dispatch[static_cast(type)]))(message);\n\t} catch (...) {\n\t\tclient->checkin_database();\n\t\tthrow;\n\t}\n}\n\n\nvoid\nReplication::msg_get_changesets(const std::string &)\n{\n\tL_CALL(\"Replication::msg_get_changesets()\");\n\n\tL_REPLICATION(\"Replication::msg_get_changesets\");\n\n\t\/\/ Xapian::Database *db_;\n\t\/\/ const char *p = message.c_str();\n\t\/\/ const char *p_end = p + message.size();\n\n\t\/\/ size_t len = unserialise_length(&p, p_end, true);\n\t\/\/ std::string uuid(p, len);\n\t\/\/ p += len;\n\n\t\/\/ len = unserialise_length(&p, p_end, true);\n\t\/\/ std::string from_revision(p, len);\n\t\/\/ p += len;\n\n\t\/\/ len = unserialise_length(&p, p_end, true);\n\t\/\/ std::string index_path(p, len);\n\t\/\/ p += len;\n\n\t\/\/ \/\/ Select endpoints and get database\n\t\/\/ try {\n\t\/\/ \tendpoints.clear();\n\t\/\/ \tEndpoint endpoint(index_path);\n\t\/\/ \tendpoints.add(endpoint);\n\t\/\/ \tdb_ = get_db();\n\t\/\/ \tif (!db_)\n\t\/\/ \t\tTHROW(InvalidOperationError, \"Server has no open database\");\n\t\/\/ } catch (...) {\n\t\/\/ \tthrow;\n\t\/\/ }\n\n\t\/\/ char path[] = \"\/tmp\/xapian_changesets_sent.XXXXXX\";\n\t\/\/ int fd = mkstemp(path);\n\t\/\/ try {\n\t\/\/ \tstd::string to_revision = databases[db_]->checkout_revision;\n\t\/\/ \tL_REPLICATION(\"Replication::msg_get_changesets for %s (%s) from rev:%s to rev:%s [%d]\", endpoints.as_string(), uuid, repr(from_revision, false), repr(to_revision, false), need_whole_db);\n\n\t\/\/ \tif (fd == -1) {\n\t\/\/ \t\tL_ERR(\"Cannot write to %s (1)\", path);\n\t\/\/ \t\treturn;\n\t\/\/ \t}\n\t\/\/ \t\/\/ db_->write_changesets_to_fd(fd, from_revision, uuid != db_->get_uuid().to_string()); \/\/ FIXME: Implement Replication\n\t\/\/ } catch (...) {\n\t\/\/ \trelease_db(db_);\n\t\/\/ \tio::close(fd);\n\t\/\/ \tio::unlink(path);\n\t\/\/ \tthrow;\n\t\/\/ }\n\t\/\/ release_db(db_);\n\n\t\/\/ send_file(fd);\n\n\t\/\/ io::close(fd);\n\t\/\/ io::unlink(path);\n}\n\n\nvoid\nReplication::replication_client(ReplicationReplyType type, const std::string &message)\n{\n\tL_CALL(\"Replication::replication_client(%s, )\", ReplicationMessageTypeNames[static_cast(type)]);\n\n\tstatic const dispatch_func dispatch[] = {\n\t\t&Replication::reply_end_of_changes,\n\t\t&Replication::reply_fail,\n\t\t&Replication::reply_db_header,\n\t\t&Replication::reply_db_filename,\n\t\t&Replication::reply_db_filedata,\n\t\t&Replication::reply_db_footer,\n\t\t&Replication::reply_changeset,\n\t};\n\ttry {\n\t\tif (static_cast(type) >= sizeof(dispatch) \/ sizeof(dispatch[0])) {\n\t\t\tstd::string errmsg(\"Unexpected message type \");\n\t\t\terrmsg += std::to_string(toUType(type));\n\t\t\tTHROW(InvalidArgumentError, errmsg);\n\t\t}\n\t\t(this->*(dispatch[static_cast(type)]))(message);\n\t} catch (...) {\n\t\tclient->checkin_database();\n\t\tthrow;\n\t}\n}\n\n\nvoid\nReplication::reply_end_of_changes(const std::string &)\n{\n\tL_CALL(\"Replication::reply_end_of_changes()\");\n\n\tL_REPLICATION(\"Replication::reply_end_of_changes\");\n\n\t\/\/ if (repl_switched_db) {\n\t\/\/ \tXapiandManager::manager->database_pool.switch_db(*endpoints.cbegin());\n\t\/\/ }\n\n\t\/\/ client->checkin_database();\n\n\t\/\/ shutdown();\n}\n\n\nvoid\nReplication::reply_fail(const std::string &)\n{\n\tL_CALL(\"Replication::reply_fail()\");\n\n\tL_REPLICATION(\"Replication::reply_fail\");\n\n\t\/\/ L_ERR(\"Replication failure!\");\n\t\/\/ client->checkin_database();\n\n\t\/\/ shutdown();\n}\n\n\nvoid\nReplication::reply_db_header(const std::string &)\n{\n\tL_CALL(\"Replication::reply_db_header()\");\n\n\tL_REPLICATION(\"Replication::reply_db_header\");\n\n\t\/\/ const char *p = message.data();\n\t\/\/ const char *p_end = p + message.size();\n\t\/\/ size_t length = unserialise_length(&p, p_end, true);\n\t\/\/ repl_db_uuid.assign(p, length);\n\t\/\/ p += length;\n\t\/\/ repl_db_revision = unserialise_length(&p, p_end);\n\t\/\/ repl_db_filename.clear();\n\n\t\/\/ Endpoint& endpoint = endpoints[0];\n\t\/\/ std::string path_tmp = endpoint.path + \"\/.tmp\";\n\n\t\/\/ int dir = ::mkdir(path_tmp.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);\n\t\/\/ if (dir == 0) {\n\t\/\/ \tL_DEBUG(\"Directory %s created\", path_tmp);\n\t\/\/ } else if (errno == EEXIST) {\n\t\/\/ \tdelete_files(path_tmp.c_str());\n\t\/\/ \tdir = ::mkdir(path_tmp.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);\n\t\/\/ \tif (dir == 0) {\n\t\/\/ \t\tL_DEBUG(\"Directory %s created\", path_tmp);\n\t\/\/ \t}\n\t\/\/ } else {\n\t\/\/ \tL_ERR(\"Directory %s not created (%s)\", path_tmp, strerror(errno));\n\t\/\/ }\n}\n\n\nvoid\nReplication::reply_db_filename(const std::string &)\n{\n\tL_CALL(\"Replication::reply_db_filename()\");\n\n\tL_REPLICATION(\"Replication::reply_db_filename\");\n\n\t\/\/ const char *p = message.data();\n\t\/\/ const char *p_end = p + message.size();\n\t\/\/ repl_db_filename.assign(p, p_end - p);\n}\n\n\nvoid\nReplication::reply_db_filedata(const std::string &)\n{\n\tL_CALL(\"Replication::reply_db_filedata()\");\n\n\tL_REPLICATION(\"Replication::reply_db_filedata\");\n\n\t\/\/ const char *p = message.data();\n\t\/\/ const char *p_end = p + message.size();\n\n\t\/\/ const Endpoint& endpoint = endpoints[0];\n\n\t\/\/ std::string path = endpoint.path + \"\/.tmp\/\";\n\t\/\/ std::string path_filename = path + repl_db_filename;\n\n\t\/\/ int fd = io::open(path_filename.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644);\n\t\/\/ if (fd != -1) {\n\t\/\/ \tL_REPLICATION(\"path_filename %s\", path_filename);\n\t\/\/ \tif (io::write(fd, p, p_end - p) != p_end - p) {\n\t\/\/ \t\tL_ERR(\"Cannot write to %s\", repl_db_filename);\n\t\/\/ \t\treturn;\n\t\/\/ \t}\n\t\/\/ \tio::close(fd);\n\t\/\/ }\n}\n\n\nvoid\nReplication::reply_db_footer(const std::string &)\n{\n\tL_CALL(\"Replication::reply_db_footer()\");\n\n\tL_REPLICATION(\"Replication::reply_db_footer\");\n\n\t\/\/ \/\/ const char *p = message.data();\n\t\/\/ \/\/ const char *p_end = p + message.size();\n\t\/\/ \/\/ size_t revision = unserialise_length(&p, p_end);\n\t\/\/ \/\/ Indicates the end of a DB copy operation, signal switch\n\n\t\/\/ Endpoints endpoints_tmp;\n\t\/\/ Endpoint& endpoint_tmp = endpoints[0];\n\t\/\/ endpoint_tmp.path.append(\"\/.tmp\");\n\t\/\/ endpoints_tmp.insert(endpoint_tmp);\n\n\t\/\/ if (!repl_database_tmp) {\n\t\/\/ \ttry {\n\t\/\/ \t\tXapiandManager::manager->database_pool.checkout(repl_database_tmp, endpoints_tmp, DB_WRITABLE | DB_VOLATILE);\n\t\/\/ \t} catch (const CheckoutError&)\n\t\/\/ \t\tL_ERR(\"Cannot checkout tmp %s\", endpoint_tmp.path);\n\t\/\/ \t}\n\t\/\/ }\n\n\t\/\/ repl_switched_db = true;\n\t\/\/ repl_just_switched_db = true;\n}\n\n\nvoid\nReplication::reply_changeset(const std::string &)\n{\n\tL_CALL(\"Replication::reply_changeset()\");\n\n\tL_REPLICATION(\"Replication::reply_changeset\");\n\n\t\/\/ Xapian::WritableDatabase *wdb_;\n\t\/\/ if (repl_database_tmp) {\n\t\/\/ \twdb_ = static_cast(repl_database_tmp->db.get());\n\t\/\/ } else {\n\t\/\/ \twdb_ = static_cast(database);\n\t\/\/ }\n\n\t\/\/ char path[] = \"\/tmp\/xapian_changes.XXXXXX\";\n\t\/\/ int fd = mkstemp(path);\n\t\/\/ if (fd == -1) {\n\t\/\/ \tL_ERR(\"Cannot write to %s (1)\", path);\n\t\/\/ \treturn;\n\t\/\/ }\n\n\t\/\/ std::string header;\n\t\/\/ header += toUType(ReplicationMessageType::REPLY_CHANGESET);\n\t\/\/ header += serialise_length(message.size());\n\n\t\/\/ if (io::write(fd, header.data(), header.size()) != static_cast(header.size())) {\n\t\/\/ \tL_ERR(\"Cannot write to %s (2)\", path);\n\t\/\/ \treturn;\n\t\/\/ }\n\n\t\/\/ if (io::write(fd, message.data(), message.size()) != static_cast(message.size())) {\n\t\/\/ \tL_ERR(\"Cannot write to %s (3)\", path);\n\t\/\/ \treturn;\n\t\/\/ }\n\n\t\/\/ io::lseek(fd, 0, SEEK_SET);\n\n\t\/\/ try {\n\t\/\/ \t\/\/ wdb_->apply_changeset_from_fd(fd, !repl_just_switched_db); \/\/ FIXME: Implement Replication\n\t\/\/ \trepl_just_switched_db = false;\n\t\/\/ } catch (const MSG_NetworkError& exc) {\n\t\/\/ \tL_EXC(\"ERROR: %s\", exc.get_description());\n\t\/\/ \tio::close(fd);\n\t\/\/ \tio::unlink(path);\n\t\/\/ \tthrow;\n\t\/\/ } catch (const Xapian::DatabaseError& exc) {\n\t\/\/ \tL_EXC(\"ERROR: %s\", exc.get_description());\n\t\/\/ \tio::close(fd);\n\t\/\/ \tio::unlink(path);\n\t\/\/ \tthrow;\n\t\/\/ } catch (...) {\n\t\/\/ \tio::close(fd);\n\t\/\/ \tio::unlink(path);\n\t\/\/ \tthrow;\n\t\/\/ }\n\n\t\/\/ io::close(fd);\n\t\/\/ io::unlink(path);\n}\n\n\nvoid\nReplication::replication_client_file_done()\n{\n\tL_CALL(\"Replication::replication_client_file_done()\");\n\n\tL_REPLICATION(\"Replication::replication_client_file_done\");\n\n\tchar buf[1024];\n\tconst char *p;\n\tconst char *p_end;\n\tstd::string buffer;\n\n\tssize_t size = io::read(client->file_descriptor, buf, sizeof(buf));\n\tbuffer.append(buf, size);\n\tp = buffer.data();\n\tp_end = p + buffer.size();\n\tconst char *s = p;\n\n\twhile (p != p_end) {\n\t\tReplicationReplyType type = static_cast(*p++);\n\t\tssize_t len = unserialise_length(&p, p_end);\n\t\tsize_t pos = p - s;\n\t\twhile (p_end - p < len || static_cast(p_end - p) < sizeof(buf) \/ 2) {\n\t\t\tsize = io::read(client->file_descriptor, buf, sizeof(buf));\n\t\t\tif (!size) break;\n\t\t\tbuffer.append(buf, size);\n\t\t\ts = p = buffer.data();\n\t\t\tp_end = p + buffer.size();\n\t\t\tp += pos;\n\t\t}\n\t\tif (p_end - p < len) {\n\t\t\tTHROW(Error, \"Replication failure!\");\n\t\t}\n\t\tstd::string msg(p, len);\n\t\tp += len;\n\n\t\treplication_client(type, msg);\n\n\t\tbuffer.erase(0, p - s);\n\t\ts = p = buffer.data();\n\t\tp_end = p + buffer.size();\n\t}\n}\n\n\n#endif \/* XAPIAND_CLUSTERING *\/\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2018 The Syscoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n\n#include \n#include \n\nclass CRPCConvertParam\n{\npublic:\n std::string methodName; \/\/!< method whose params want conversion\n int paramIdx; \/\/!< 0-based idx of param to convert\n std::string paramName; \/\/!< parameter name\n};\n\n\/\/ clang-format off\n\/**\n * Specify a (method, idx, name) here if the argument is a non-string RPC\n * argument and needs to be converted from JSON.\n *\n * @note Parameter indexes start from 0.\n *\/\nstatic const CRPCConvertParam vRPCConvertParams[] =\n{\n { \"setmocktime\", 0, \"timestamp\" },\n { \"generate\", 0, \"nblocks\" },\n { \"generate\", 1, \"maxtries\" },\n { \"generatetoaddress\", 0, \"nblocks\" },\n { \"generatetoaddress\", 2, \"maxtries\" },\n { \"getnetworkhashps\", 0, \"nblocks\" },\n { \"getnetworkhashps\", 1, \"height\" },\n { \"sendtoaddress\", 1, \"amount\" },\n { \"sendtoaddress\", 4, \"subtractfeefromamount\" },\n { \"sendtoaddress\", 5 , \"replaceable\" },\n { \"sendtoaddress\", 6 , \"conf_target\" },\n { \"settxfee\", 0, \"amount\" },\n { \"sethdseed\", 0, \"newkeypool\" },\n { \"getreceivedbyaddress\", 1, \"minconf\" },\n { \"getreceivedbylabel\", 1, \"minconf\" },\n { \"listreceivedbyaddress\", 0, \"minconf\" },\n { \"listreceivedbyaddress\", 1, \"include_empty\" },\n { \"listreceivedbyaddress\", 2, \"include_watchonly\" },\n { \"listreceivedbylabel\", 0, \"minconf\" },\n { \"listreceivedbylabel\", 1, \"include_empty\" },\n { \"listreceivedbylabel\", 2, \"include_watchonly\" },\n { \"getbalance\", 1, \"minconf\" },\n { \"getbalance\", 2, \"include_watchonly\" },\n { \"getblockhash\", 0, \"height\" },\n { \"waitforblockheight\", 0, \"height\" },\n { \"waitforblockheight\", 1, \"timeout\" },\n { \"waitforblock\", 1, \"timeout\" },\n { \"waitfornewblock\", 0, \"timeout\" },\n { \"listtransactions\", 1, \"count\" },\n { \"listtransactions\", 2, \"skip\" },\n { \"listtransactions\", 3, \"include_watchonly\" },\n { \"walletpassphrase\", 1, \"timeout\" },\n { \"getblocktemplate\", 0, \"template_request\" },\n { \"listsinceblock\", 1, \"target_confirmations\" },\n { \"listsinceblock\", 2, \"include_watchonly\" },\n { \"listsinceblock\", 3, \"include_removed\" },\n { \"sendmany\", 1, \"amounts\" },\n { \"sendmany\", 2, \"minconf\" },\n { \"sendmany\", 4, \"subtractfeefrom\" },\n { \"sendmany\", 5 , \"replaceable\" },\n { \"sendmany\", 6 , \"conf_target\" },\n { \"deriveaddresses\", 1, \"range\" },\n { \"scantxoutset\", 1, \"scanobjects\" },\n { \"addmultisigaddress\", 0, \"nrequired\" },\n { \"addmultisigaddress\", 1, \"keys\" },\n { \"createmultisig\", 0, \"nrequired\" },\n { \"createmultisig\", 1, \"keys\" },\n { \"listunspent\", 0, \"minconf\" },\n { \"listunspent\", 1, \"maxconf\" },\n { \"listunspent\", 2, \"addresses\" },\n { \"listunspent\", 3, \"include_unsafe\" },\n { \"listunspent\", 4, \"query_options\" },\n { \"getblock\", 1, \"verbosity\" },\n { \"getblock\", 1, \"verbose\" },\n { \"getblockheader\", 1, \"verbose\" },\n { \"getchaintxstats\", 0, \"nblocks\" },\n { \"gettransaction\", 1, \"include_watchonly\" },\n { \"getrawtransaction\", 1, \"verbose\" },\n { \"createrawtransaction\", 0, \"inputs\" },\n { \"createrawtransaction\", 1, \"outputs\" },\n { \"createrawtransaction\", 2, \"locktime\" },\n { \"createrawtransaction\", 3, \"replaceable\" },\n { \"decoderawtransaction\", 1, \"iswitness\" },\n { \"signrawtransactionwithkey\", 1, \"privkeys\" },\n { \"signrawtransactionwithkey\", 2, \"prevtxs\" },\n { \"signrawtransactionwithwallet\", 1, \"prevtxs\" },\n { \"sendrawtransaction\", 1, \"allowhighfees\" },\n { \"sendrawtransaction\", 1, \"maxfeerate\" },\n { \"testmempoolaccept\", 0, \"rawtxs\" },\n { \"testmempoolaccept\", 1, \"allowhighfees\" },\n { \"testmempoolaccept\", 1, \"maxfeerate\" },\n { \"combinerawtransaction\", 0, \"txs\" },\n { \"fundrawtransaction\", 1, \"options\" },\n { \"fundrawtransaction\", 2, \"iswitness\" },\n { \"walletcreatefundedpsbt\", 0, \"inputs\" },\n { \"walletcreatefundedpsbt\", 1, \"outputs\" },\n { \"walletcreatefundedpsbt\", 2, \"locktime\" },\n { \"walletcreatefundedpsbt\", 3, \"options\" },\n { \"walletcreatefundedpsbt\", 4, \"bip32derivs\" },\n { \"walletprocesspsbt\", 1, \"sign\" },\n { \"walletprocesspsbt\", 3, \"bip32derivs\" },\n { \"createpsbt\", 0, \"inputs\" },\n { \"createpsbt\", 1, \"outputs\" },\n { \"createpsbt\", 2, \"locktime\" },\n { \"createpsbt\", 3, \"replaceable\" },\n { \"combinepsbt\", 0, \"txs\"},\n { \"joinpsbts\", 0, \"txs\"},\n { \"finalizepsbt\", 1, \"extract\"},\n { \"converttopsbt\", 1, \"permitsigdata\"},\n { \"converttopsbt\", 2, \"iswitness\"},\n { \"gettxout\", 1, \"n\" },\n { \"gettxout\", 2, \"include_mempool\" },\n { \"gettxoutproof\", 0, \"txids\" },\n { \"lockunspent\", 0, \"unlock\" },\n { \"lockunspent\", 1, \"transactions\" },\n { \"importprivkey\", 2, \"rescan\" },\n { \"importaddress\", 2, \"rescan\" },\n { \"importaddress\", 3, \"p2sh\" },\n { \"importpubkey\", 2, \"rescan\" },\n { \"importmulti\", 0, \"requests\" },\n { \"importmulti\", 1, \"options\" },\n { \"verifychain\", 0, \"checklevel\" },\n { \"verifychain\", 1, \"nblocks\" },\n { \"getblockstats\", 0, \"hash_or_height\" },\n { \"getblockstats\", 1, \"stats\" },\n { \"pruneblockchain\", 0, \"height\" },\n { \"keypoolrefill\", 0, \"newsize\" },\n { \"getrawmempool\", 0, \"verbose\" },\n { \"estimatesmartfee\", 0, \"conf_target\" },\n { \"estimaterawfee\", 0, \"conf_target\" },\n { \"estimaterawfee\", 1, \"threshold\" },\n { \"prioritisetransaction\", 1, \"dummy\" },\n { \"prioritisetransaction\", 2, \"fee_delta\" },\n { \"setban\", 2, \"bantime\" },\n { \"setban\", 3, \"absolute\" },\n { \"setnetworkactive\", 0, \"state\" },\n { \"getmempoolancestors\", 1, \"verbose\" },\n { \"getmempooldescendants\", 1, \"verbose\" },\n { \"bumpfee\", 1, \"options\" },\n { \"logging\", 0, \"include\" },\n { \"logging\", 1, \"exclude\" },\n { \"disconnectnode\", 1, \"nodeid\" },\n \/\/ Echo with conversion (For testing only)\n { \"echojson\", 0, \"arg0\" },\n { \"echojson\", 1, \"arg1\" },\n { \"echojson\", 2, \"arg2\" },\n { \"echojson\", 3, \"arg3\" },\n { \"echojson\", 4, \"arg4\" },\n { \"echojson\", 5, \"arg5\" },\n { \"echojson\", 6, \"arg6\" },\n { \"echojson\", 7, \"arg7\" },\n { \"echojson\", 8, \"arg8\" },\n { \"echojson\", 9, \"arg9\" },\n { \"rescanblockchain\", 0, \"start_height\"},\n { \"rescanblockchain\", 1, \"stop_height\"},\n { \"createwallet\", 1, \"disable_private_keys\"},\n { \"createwallet\", 2, \"blank\"},\n { \"getnodeaddresses\", 0, \"count\"},\n { \"stop\", 0, \"wait\" },\n { \"getsuperblockbudget\", 0, \"index\" },\n { \"spork\", 1, \"value\" },\n { \"voteraw\", 1, \"tx_index\" },\n { \"voteraw\", 5, \"time\" },\n { \"syscoinmint\", 2, \"blocknumber\" },\n { \"syscointxfund\", 2, \"output_index\" },\n { \"assetallocationlock\", 0, \"asset_guid\" },\n\t{ \"assetallocationlock\", 3, \"output_index\" },\n { \"assetallocationsend\", 0, \"asset_guid\" },\n { \"assetallocationsendmany\", 0, \"asset_guid\" },\n { \"assetallocationsendmany\", 2, \"inputs\" },\n { \"assetallocationburn\", 0, \"asset_guid\" },\n { \"assetallocationmint\", 0, \"asset_guid\" },\n { \"assetallocationmint\", 3, \"blocknumber\" },\n { \"assetallocationinfo\", 0, \"asset_guid\" },\n { \"assetallocationbalance\", 0, \"asset_guid\" },\n { \"assetallocationsenderstatus\", 0, \"asset_guid\" },\n { \"listassetallocations\", 0, \"count\" },\n { \"listassetallocations\", 1, \"from\" },\n { \"listassetallocations\", 2, \"options\" },\n { \"listassetallocationmempoolbalances\", 0, \"count\" },\n { \"listassetallocationmempoolbalances\", 1, \"from\" },\n { \"listassetallocationmempoolbalances\", 2, \"options\" }, \n { \"assetnew\", 3, \"precision\" },\n { \"assetnew\", 6, \"update_flags\" },\n { \"assetupdate\", 0, \"asset_guid\" },\n { \"assetupdate\", 4, \"update_flags\" },\n { \"assettransfer\", 0, \"asset_guid\" },\n { \"assetsend\", 0, \"asset_guid\" },\n { \"assetsendmany\", 0, \"asset_guid\" },\n { \"assetsendmany\", 1, \"inputs\" },\n { \"assetinfo\", 0, \"asset_guid\" },\n { \"sentinelping\", 0, \"version\" },\n { \"listassets\", 0, \"count\" },\n { \"listassets\", 1, \"from\" },\n { \"listassets\", 2, \"options\" },\n { \"tpstestadd\", 0, \"starttime\" },\n { \"tpstestadd\", 1, \"rawtxs\" },\n { \"tpstestsetenabled\", 0, \"enabled\" },\n { \"syscoinsetethstatus\", 1, \"highestBlock\" },\n { \"syscoinsetethheaders\", 0, \"headers\" },\n { \"listassetindex\", 0, \"page\" },\n { \"listassetindex\", 1, \"options\" },\n};\n\/\/ clang-format on\n\nclass CRPCConvertTable\n{\nprivate:\n std::set> members;\n std::set> membersByName;\n\npublic:\n CRPCConvertTable();\n\n bool convert(const std::string& method, int idx) {\n return (members.count(std::make_pair(method, idx)) > 0);\n }\n bool convert(const std::string& method, const std::string& name) {\n return (membersByName.count(std::make_pair(method, name)) > 0);\n }\n};\n\nCRPCConvertTable::CRPCConvertTable()\n{\n const unsigned int n_elem =\n (sizeof(vRPCConvertParams) \/ sizeof(vRPCConvertParams[0]));\n\n for (unsigned int i = 0; i < n_elem; i++) {\n members.insert(std::make_pair(vRPCConvertParams[i].methodName,\n vRPCConvertParams[i].paramIdx));\n membersByName.insert(std::make_pair(vRPCConvertParams[i].methodName,\n vRPCConvertParams[i].paramName));\n }\n}\n\nstatic CRPCConvertTable rpcCvtTable;\n\n\/** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null)\n * as well as objects and arrays.\n *\/\nUniValue ParseNonRFCJSONValue(const std::string& strVal)\n{\n UniValue jVal;\n if (!jVal.read(std::string(\"[\")+strVal+std::string(\"]\")) ||\n !jVal.isArray() || jVal.size()!=1)\n throw std::runtime_error(std::string(\"Error parsing JSON:\")+strVal);\n return jVal[0];\n}\n\nUniValue RPCConvertValues(const std::string &strMethod, const std::vector &strParams)\n{\n UniValue params(UniValue::VARR);\n\n for (unsigned int idx = 0; idx < strParams.size(); idx++) {\n const std::string& strVal = strParams[idx];\n\n if (!rpcCvtTable.convert(strMethod, idx)) {\n \/\/ insert string value directly\n params.push_back(strVal);\n } else {\n \/\/ parse string as JSON, insert bool\/number\/object\/etc. value\n params.push_back(ParseNonRFCJSONValue(strVal));\n }\n }\n\n return params;\n}\n\nUniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector &strParams)\n{\n UniValue params(UniValue::VOBJ);\n\n for (const std::string &s: strParams) {\n size_t pos = s.find('=');\n if (pos == std::string::npos) {\n throw(std::runtime_error(\"No '=' in named argument '\"+s+\"', this needs to be present for every argument (even if it is empty)\"));\n }\n\n std::string name = s.substr(0, pos);\n std::string value = s.substr(pos+1);\n\n if (!rpcCvtTable.convert(strMethod, name)) {\n \/\/ insert string value directly\n params.pushKV(name, value);\n } else {\n \/\/ parse string as JSON, insert bool\/number\/object\/etc. value\n params.pushKV(name, ParseNonRFCJSONValue(value));\n }\n }\n\n return params;\n}\nFixed tab to spaces\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2018 The Syscoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n\n#include \n#include \n\nclass CRPCConvertParam\n{\npublic:\n std::string methodName; \/\/!< method whose params want conversion\n int paramIdx; \/\/!< 0-based idx of param to convert\n std::string paramName; \/\/!< parameter name\n};\n\n\/\/ clang-format off\n\/**\n * Specify a (method, idx, name) here if the argument is a non-string RPC\n * argument and needs to be converted from JSON.\n *\n * @note Parameter indexes start from 0.\n *\/\nstatic const CRPCConvertParam vRPCConvertParams[] =\n{\n { \"setmocktime\", 0, \"timestamp\" },\n { \"generate\", 0, \"nblocks\" },\n { \"generate\", 1, \"maxtries\" },\n { \"generatetoaddress\", 0, \"nblocks\" },\n { \"generatetoaddress\", 2, \"maxtries\" },\n { \"getnetworkhashps\", 0, \"nblocks\" },\n { \"getnetworkhashps\", 1, \"height\" },\n { \"sendtoaddress\", 1, \"amount\" },\n { \"sendtoaddress\", 4, \"subtractfeefromamount\" },\n { \"sendtoaddress\", 5 , \"replaceable\" },\n { \"sendtoaddress\", 6 , \"conf_target\" },\n { \"settxfee\", 0, \"amount\" },\n { \"sethdseed\", 0, \"newkeypool\" },\n { \"getreceivedbyaddress\", 1, \"minconf\" },\n { \"getreceivedbylabel\", 1, \"minconf\" },\n { \"listreceivedbyaddress\", 0, \"minconf\" },\n { \"listreceivedbyaddress\", 1, \"include_empty\" },\n { \"listreceivedbyaddress\", 2, \"include_watchonly\" },\n { \"listreceivedbylabel\", 0, \"minconf\" },\n { \"listreceivedbylabel\", 1, \"include_empty\" },\n { \"listreceivedbylabel\", 2, \"include_watchonly\" },\n { \"getbalance\", 1, \"minconf\" },\n { \"getbalance\", 2, \"include_watchonly\" },\n { \"getblockhash\", 0, \"height\" },\n { \"waitforblockheight\", 0, \"height\" },\n { \"waitforblockheight\", 1, \"timeout\" },\n { \"waitforblock\", 1, \"timeout\" },\n { \"waitfornewblock\", 0, \"timeout\" },\n { \"listtransactions\", 1, \"count\" },\n { \"listtransactions\", 2, \"skip\" },\n { \"listtransactions\", 3, \"include_watchonly\" },\n { \"walletpassphrase\", 1, \"timeout\" },\n { \"getblocktemplate\", 0, \"template_request\" },\n { \"listsinceblock\", 1, \"target_confirmations\" },\n { \"listsinceblock\", 2, \"include_watchonly\" },\n { \"listsinceblock\", 3, \"include_removed\" },\n { \"sendmany\", 1, \"amounts\" },\n { \"sendmany\", 2, \"minconf\" },\n { \"sendmany\", 4, \"subtractfeefrom\" },\n { \"sendmany\", 5 , \"replaceable\" },\n { \"sendmany\", 6 , \"conf_target\" },\n { \"deriveaddresses\", 1, \"range\" },\n { \"scantxoutset\", 1, \"scanobjects\" },\n { \"addmultisigaddress\", 0, \"nrequired\" },\n { \"addmultisigaddress\", 1, \"keys\" },\n { \"createmultisig\", 0, \"nrequired\" },\n { \"createmultisig\", 1, \"keys\" },\n { \"listunspent\", 0, \"minconf\" },\n { \"listunspent\", 1, \"maxconf\" },\n { \"listunspent\", 2, \"addresses\" },\n { \"listunspent\", 3, \"include_unsafe\" },\n { \"listunspent\", 4, \"query_options\" },\n { \"getblock\", 1, \"verbosity\" },\n { \"getblock\", 1, \"verbose\" },\n { \"getblockheader\", 1, \"verbose\" },\n { \"getchaintxstats\", 0, \"nblocks\" },\n { \"gettransaction\", 1, \"include_watchonly\" },\n { \"getrawtransaction\", 1, \"verbose\" },\n { \"createrawtransaction\", 0, \"inputs\" },\n { \"createrawtransaction\", 1, \"outputs\" },\n { \"createrawtransaction\", 2, \"locktime\" },\n { \"createrawtransaction\", 3, \"replaceable\" },\n { \"decoderawtransaction\", 1, \"iswitness\" },\n { \"signrawtransactionwithkey\", 1, \"privkeys\" },\n { \"signrawtransactionwithkey\", 2, \"prevtxs\" },\n { \"signrawtransactionwithwallet\", 1, \"prevtxs\" },\n { \"sendrawtransaction\", 1, \"allowhighfees\" },\n { \"sendrawtransaction\", 1, \"maxfeerate\" },\n { \"testmempoolaccept\", 0, \"rawtxs\" },\n { \"testmempoolaccept\", 1, \"allowhighfees\" },\n { \"testmempoolaccept\", 1, \"maxfeerate\" },\n { \"combinerawtransaction\", 0, \"txs\" },\n { \"fundrawtransaction\", 1, \"options\" },\n { \"fundrawtransaction\", 2, \"iswitness\" },\n { \"walletcreatefundedpsbt\", 0, \"inputs\" },\n { \"walletcreatefundedpsbt\", 1, \"outputs\" },\n { \"walletcreatefundedpsbt\", 2, \"locktime\" },\n { \"walletcreatefundedpsbt\", 3, \"options\" },\n { \"walletcreatefundedpsbt\", 4, \"bip32derivs\" },\n { \"walletprocesspsbt\", 1, \"sign\" },\n { \"walletprocesspsbt\", 3, \"bip32derivs\" },\n { \"createpsbt\", 0, \"inputs\" },\n { \"createpsbt\", 1, \"outputs\" },\n { \"createpsbt\", 2, \"locktime\" },\n { \"createpsbt\", 3, \"replaceable\" },\n { \"combinepsbt\", 0, \"txs\"},\n { \"joinpsbts\", 0, \"txs\"},\n { \"finalizepsbt\", 1, \"extract\"},\n { \"converttopsbt\", 1, \"permitsigdata\"},\n { \"converttopsbt\", 2, \"iswitness\"},\n { \"gettxout\", 1, \"n\" },\n { \"gettxout\", 2, \"include_mempool\" },\n { \"gettxoutproof\", 0, \"txids\" },\n { \"lockunspent\", 0, \"unlock\" },\n { \"lockunspent\", 1, \"transactions\" },\n { \"importprivkey\", 2, \"rescan\" },\n { \"importaddress\", 2, \"rescan\" },\n { \"importaddress\", 3, \"p2sh\" },\n { \"importpubkey\", 2, \"rescan\" },\n { \"importmulti\", 0, \"requests\" },\n { \"importmulti\", 1, \"options\" },\n { \"verifychain\", 0, \"checklevel\" },\n { \"verifychain\", 1, \"nblocks\" },\n { \"getblockstats\", 0, \"hash_or_height\" },\n { \"getblockstats\", 1, \"stats\" },\n { \"pruneblockchain\", 0, \"height\" },\n { \"keypoolrefill\", 0, \"newsize\" },\n { \"getrawmempool\", 0, \"verbose\" },\n { \"estimatesmartfee\", 0, \"conf_target\" },\n { \"estimaterawfee\", 0, \"conf_target\" },\n { \"estimaterawfee\", 1, \"threshold\" },\n { \"prioritisetransaction\", 1, \"dummy\" },\n { \"prioritisetransaction\", 2, \"fee_delta\" },\n { \"setban\", 2, \"bantime\" },\n { \"setban\", 3, \"absolute\" },\n { \"setnetworkactive\", 0, \"state\" },\n { \"getmempoolancestors\", 1, \"verbose\" },\n { \"getmempooldescendants\", 1, \"verbose\" },\n { \"bumpfee\", 1, \"options\" },\n { \"logging\", 0, \"include\" },\n { \"logging\", 1, \"exclude\" },\n { \"disconnectnode\", 1, \"nodeid\" },\n \/\/ Echo with conversion (For testing only)\n { \"echojson\", 0, \"arg0\" },\n { \"echojson\", 1, \"arg1\" },\n { \"echojson\", 2, \"arg2\" },\n { \"echojson\", 3, \"arg3\" },\n { \"echojson\", 4, \"arg4\" },\n { \"echojson\", 5, \"arg5\" },\n { \"echojson\", 6, \"arg6\" },\n { \"echojson\", 7, \"arg7\" },\n { \"echojson\", 8, \"arg8\" },\n { \"echojson\", 9, \"arg9\" },\n { \"rescanblockchain\", 0, \"start_height\"},\n { \"rescanblockchain\", 1, \"stop_height\"},\n { \"createwallet\", 1, \"disable_private_keys\"},\n { \"createwallet\", 2, \"blank\"},\n { \"getnodeaddresses\", 0, \"count\"},\n { \"stop\", 0, \"wait\" },\n { \"getsuperblockbudget\", 0, \"index\" },\n { \"spork\", 1, \"value\" },\n { \"voteraw\", 1, \"tx_index\" },\n { \"voteraw\", 5, \"time\" },\n { \"syscoinmint\", 2, \"blocknumber\" },\n { \"syscointxfund\", 2, \"output_index\" },\n { \"assetallocationlock\", 0, \"asset_guid\" },\n { \"assetallocationlock\", 3, \"output_index\" },\n { \"assetallocationsend\", 0, \"asset_guid\" },\n { \"assetallocationsendmany\", 0, \"asset_guid\" },\n { \"assetallocationsendmany\", 2, \"inputs\" },\n { \"assetallocationburn\", 0, \"asset_guid\" },\n { \"assetallocationmint\", 0, \"asset_guid\" },\n { \"assetallocationmint\", 3, \"blocknumber\" },\n { \"assetallocationinfo\", 0, \"asset_guid\" },\n { \"assetallocationbalance\", 0, \"asset_guid\" },\n { \"assetallocationsenderstatus\", 0, \"asset_guid\" },\n { \"listassetallocations\", 0, \"count\" },\n { \"listassetallocations\", 1, \"from\" },\n { \"listassetallocations\", 2, \"options\" },\n { \"listassetallocationmempoolbalances\", 0, \"count\" },\n { \"listassetallocationmempoolbalances\", 1, \"from\" },\n { \"listassetallocationmempoolbalances\", 2, \"options\" }, \n { \"assetnew\", 3, \"precision\" },\n { \"assetnew\", 6, \"update_flags\" },\n { \"assetupdate\", 0, \"asset_guid\" },\n { \"assetupdate\", 4, \"update_flags\" },\n { \"assettransfer\", 0, \"asset_guid\" },\n { \"assetsend\", 0, \"asset_guid\" },\n { \"assetsendmany\", 0, \"asset_guid\" },\n { \"assetsendmany\", 1, \"inputs\" },\n { \"assetinfo\", 0, \"asset_guid\" },\n { \"sentinelping\", 0, \"version\" },\n { \"listassets\", 0, \"count\" },\n { \"listassets\", 1, \"from\" },\n { \"listassets\", 2, \"options\" },\n { \"tpstestadd\", 0, \"starttime\" },\n { \"tpstestadd\", 1, \"rawtxs\" },\n { \"tpstestsetenabled\", 0, \"enabled\" },\n { \"syscoinsetethstatus\", 1, \"highestBlock\" },\n { \"syscoinsetethheaders\", 0, \"headers\" },\n { \"listassetindex\", 0, \"page\" },\n { \"listassetindex\", 1, \"options\" },\n};\n\/\/ clang-format on\n\nclass CRPCConvertTable\n{\nprivate:\n std::set> members;\n std::set> membersByName;\n\npublic:\n CRPCConvertTable();\n\n bool convert(const std::string& method, int idx) {\n return (members.count(std::make_pair(method, idx)) > 0);\n }\n bool convert(const std::string& method, const std::string& name) {\n return (membersByName.count(std::make_pair(method, name)) > 0);\n }\n};\n\nCRPCConvertTable::CRPCConvertTable()\n{\n const unsigned int n_elem =\n (sizeof(vRPCConvertParams) \/ sizeof(vRPCConvertParams[0]));\n\n for (unsigned int i = 0; i < n_elem; i++) {\n members.insert(std::make_pair(vRPCConvertParams[i].methodName,\n vRPCConvertParams[i].paramIdx));\n membersByName.insert(std::make_pair(vRPCConvertParams[i].methodName,\n vRPCConvertParams[i].paramName));\n }\n}\n\nstatic CRPCConvertTable rpcCvtTable;\n\n\/** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null)\n * as well as objects and arrays.\n *\/\nUniValue ParseNonRFCJSONValue(const std::string& strVal)\n{\n UniValue jVal;\n if (!jVal.read(std::string(\"[\")+strVal+std::string(\"]\")) ||\n !jVal.isArray() || jVal.size()!=1)\n throw std::runtime_error(std::string(\"Error parsing JSON:\")+strVal);\n return jVal[0];\n}\n\nUniValue RPCConvertValues(const std::string &strMethod, const std::vector &strParams)\n{\n UniValue params(UniValue::VARR);\n\n for (unsigned int idx = 0; idx < strParams.size(); idx++) {\n const std::string& strVal = strParams[idx];\n\n if (!rpcCvtTable.convert(strMethod, idx)) {\n \/\/ insert string value directly\n params.push_back(strVal);\n } else {\n \/\/ parse string as JSON, insert bool\/number\/object\/etc. value\n params.push_back(ParseNonRFCJSONValue(strVal));\n }\n }\n\n return params;\n}\n\nUniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector &strParams)\n{\n UniValue params(UniValue::VOBJ);\n\n for (const std::string &s: strParams) {\n size_t pos = s.find('=');\n if (pos == std::string::npos) {\n throw(std::runtime_error(\"No '=' in named argument '\"+s+\"', this needs to be present for every argument (even if it is empty)\"));\n }\n\n std::string name = s.substr(0, pos);\n std::string value = s.substr(pos+1);\n\n if (!rpcCvtTable.convert(strMethod, name)) {\n \/\/ insert string value directly\n params.pushKV(name, value);\n } else {\n \/\/ parse string as JSON, insert bool\/number\/object\/etc. value\n params.pushKV(name, ParseNonRFCJSONValue(value));\n }\n }\n\n return params;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \"debug.h\"\n#include \"utils.h\"\n\n#include \"scheduling.h\"\n\n#define UPDATED_LAUNCHD_PATH_LONG \\\n \"The OS X launchd scheduling service contained an out-of-date link to \" \\\n \"Tarsnap GUI (did you upgrade it recently?).\\n\\nThis has been updated to \" \\\n \"point to the current Tarsnap GUI.\"\n\n#define UPDATED_LAUNCHD_PATH_SHORT \"Updated launchd path to Tarsnap GUI\"\n\n#define UPDATED_LAUNCHD_PATH_ERROR \\\n \"An error occurred while attempting to \" \\\n \"update the OS X launchd path.\"\n\nstruct cmdinfo\n{\n int exit_code;\n QByteArray stderr_msg;\n QByteArray stdout_msg;\n};\n\nstatic struct cmdinfo runCmd(QString cmd, QStringList args,\n const QByteArray *stdin_msg = nullptr)\n{\n QProcess proc;\n struct cmdinfo info;\n proc.start(cmd, args);\n\n \/\/ We can want stdin_msg to be empty but non-null; for example if we're\n \/\/ disabling the scheduling and therefore writing an empty crontab file.\n if(stdin_msg != nullptr)\n {\n proc.write(*stdin_msg);\n proc.closeWriteChannel();\n }\n proc.waitForFinished(-1);\n\n \/\/ Get exit code, working around QProcess not having a valid exitCode()\n \/\/ if there's a crash.\n info.exit_code = proc.exitCode();\n if(proc.exitStatus() != QProcess::NormalExit)\n info.exit_code = -1;\n\n info.stderr_msg = proc.readAllStandardError();\n info.stdout_msg = proc.readAllStandardOutput();\n\n return (info);\n}\n\n\/\/ This is an awkward hack which is an intermediate step towards separating\n\/\/ the front-end and back-end code. Return values:\n\/\/ 0: everything ok\n\/\/ 1: failed to load\n\/\/ 2: failed to start\nstatic int launchdLoad()\n{\n struct cmdinfo pinfo;\n QString launchdPlistFileName =\n QDir::homePath() + \"\/Library\/LaunchAgents\/com.tarsnap.gui.plist\";\n\n pinfo = runCmd(\"launchctl\", QStringList() << \"load\" << launchdPlistFileName);\n if(pinfo.exit_code != 0)\n return (1);\n\n pinfo = runCmd(\"launchctl\", QStringList() << \"start\"\n << \"com.tarsnap.gui\");\n if(pinfo.exit_code != 0)\n return (2);\n\n return (0);\n}\n\n\/\/ Return values:\n\/\/ 0: everything ok\n\/\/ 1: failed to unload\nstatic int launchdUnload()\n{\n struct cmdinfo pinfo;\n QString launchdPlistFileName =\n QDir::homePath() + \"\/Library\/LaunchAgents\/com.tarsnap.gui.plist\";\n\n pinfo =\n runCmd(\"launchctl\", QStringList() << \"unload\" << launchdPlistFileName);\n if(pinfo.exit_code != 0)\n return (1);\n\n return (0);\n}\n\n#if defined(Q_OS_OSX)\nstatic bool launchdLoaded()\n{\n struct cmdinfo pinfo;\n\n pinfo = runCmd(\"launchctl\", QStringList() << \"list\"\n << \"com.tarsnap.gui\");\n if(pinfo.exit_code != 0)\n return (false);\n\n return (true);\n}\n#endif\n\nstruct scheduleinfo launchdEnable()\n{\n struct scheduleinfo info = {SCHEDULE_OK, \"\", \"\"};\n\n QFile launchdPlist(\":\/com.tarsnap.gui.plist\");\n launchdPlist.open(QIODevice::ReadOnly | QIODevice::Text);\n QFile launchdPlistFile(QDir::homePath()\n + \"\/Library\/LaunchAgents\/com.tarsnap.gui.plist\");\n if(launchdPlistFile.exists())\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(\"Looks like scheduling is already enabled.\"\n \" Nothing to do.\\n\\n%1\")\n .arg(CRON_MARKER_HELP);\n return info;\n }\n if(!launchdPlistFile.open(QIODevice::WriteOnly | QIODevice::Text))\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Failed to write service file %1. Aborting operation.\")\n .arg(launchdPlistFile.fileName());\n return info;\n }\n launchdPlistFile.write(\n launchdPlist.readAll()\n .replace(\"%1\", QCoreApplication::applicationFilePath().toLatin1())\n .replace(\"%2\", QDir::homePath().toLatin1()));\n launchdPlist.close();\n launchdPlistFile.close();\n\n int ret = launchdLoad();\n if(ret == 1)\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(\"Failed to load launchd service file.\");\n return info;\n }\n else if(ret == 2)\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(\"Failed to start launchd service file.\");\n return info;\n }\n return info;\n}\n\nstruct scheduleinfo launchdDisable()\n{\n struct scheduleinfo info = {SCHEDULE_OK, \"\", \"\"};\n\n QFile launchdPlistFile(QDir::homePath()\n + \"\/Library\/LaunchAgents\/com.tarsnap.gui.plist\");\n if(!launchdPlistFile.exists())\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Launchd service file not found:\\n%1\\n Nothing to do.\")\n .arg(launchdPlistFile.fileName());\n return info;\n }\n\n int ret = launchdUnload();\n if(ret == 1)\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(\"Failed to unload launchd service.\");\n return info;\n }\n\n if(!launchdPlistFile.remove())\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Cannot remove service file:\\n%1\\nAborting operation.\")\n .arg(launchdPlistFile.fileName());\n return info;\n }\n return info;\n}\n\nstruct scheduleinfo cronEnable()\n{\n struct scheduleinfo info = {SCHEDULE_OK, \"\", \"\"};\n\n struct cmdinfo pinfo;\n pinfo = runCmd(\"crontab\", QStringList() << \"-l\");\n if(pinfo.exit_code != 0)\n {\n QString error(pinfo.stderr_msg);\n \/* On some distros crontab -l exits with error 1 and message\n * \"no crontab for username\" if there's no crontab installed\n * for the current user. If parent is the case proceed and don't err.\n *\/\n if(-1 == error.indexOf(QRegExp(\"^(crontab: )?no crontab for\")))\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Failed to list current crontab: %1\").arg(error);\n return info;\n }\n }\n QString currentCrontab(pinfo.stdout_msg);\n\n QRegExp rx(QString(\"\\n?%1.+%2\\n?\")\n .arg(QRegExp::escape(CRON_MARKER_BEGIN))\n .arg(QRegExp::escape(CRON_MARKER_END)));\n rx.setMinimal(true);\n if(-1 != rx.indexIn(currentCrontab))\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Looks like scheduling is already enabled for the\"\n \" current user's crontab. Nothing to do.\"\n \"\\n%1\")\n .arg(CRON_MARKER_HELP);\n return info;\n }\n\n QString cronLine(CRON_LINE);\n QProcessEnvironment env = QProcessEnvironment::systemEnvironment();\n cronLine =\n cronLine\n .arg(env.contains(\"SCREEN\") ? \"SCREEN=\" + env.value(\"SCREEN\") : \"\")\n .arg(env.contains(\"DISPLAY\") ? \"DISPLAY=\" + env.value(\"DISPLAY\")\n : \"\")\n .arg(env.contains(\"XAUTHORITY\")\n ? \"XAUTHORITY=\" + env.value(\"XAUTHORITY\")\n : \"\")\n .arg(QCoreApplication::applicationFilePath());\n\n QString cronBlock(\"\\n%1\\n%2\\n%3\\n%4\\n\");\n cronBlock = cronBlock.arg(CRON_MARKER_BEGIN)\n .arg(CRON_MARKER_HELP)\n .arg(cronLine)\n .arg(CRON_MARKER_END);\n\n info.status = SCHEDULE_NEED_INFO;\n info.message = cronBlock;\n info.extra = currentCrontab;\n\n return info;\n}\n\nstruct scheduleinfo cronEnable_p2(QString cronBlock, QString currentCrontab)\n{\n struct scheduleinfo info = {SCHEDULE_OK, \"\", \"\"};\n struct cmdinfo pinfo;\n\n currentCrontab.append(cronBlock.toLatin1());\n QByteArray newCrontab = currentCrontab.toLatin1();\n\n pinfo = runCmd(\"crontab\", QStringList() << \"-\", &newCrontab);\n if(pinfo.exit_code != 0)\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(\"Failed to update crontab: %1\")\n .arg(QString(pinfo.stderr_msg));\n return info;\n }\n return info;\n}\n\nstruct scheduleinfo cronDisable()\n{\n struct scheduleinfo info = {SCHEDULE_OK, \"\", \"\"};\n struct cmdinfo pinfo;\n\n pinfo = runCmd(\"crontab\", QStringList() << \"-l\");\n if(pinfo.exit_code != 0)\n {\n QString error(pinfo.stderr_msg);\n \/* On some distros crontab -l exits with error 1 and message\n * \"no crontab for username\" if there's no crontab installed\n * for the current user. If parent is the case proceed and don't err.\n *\/\n if(error.startsWith(QLatin1String(\"no crontab for\")))\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"There's no crontab for the current user.\"\n \" Nothing to do.\\n\\n%1\")\n .arg(CRON_MARKER_HELP);\n return info;\n }\n else\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Failed to list current crontab: %1\").arg(error);\n return info;\n }\n }\n QString currentCrontab(pinfo.stdout_msg);\n if(currentCrontab.isEmpty())\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Looks like the crontab for the current user is\"\n \" empty. Nothing to do.\\n\\n%1\")\n .arg(CRON_MARKER_HELP);\n return info;\n }\n\n QRegExp rx(QString(\"\\n?%1.+%2\\n?\")\n .arg(QRegExp::escape(CRON_MARKER_BEGIN))\n .arg(QRegExp::escape(CRON_MARKER_END)));\n \/\/ rx.setMinimal(true);\n QString linesToRemove;\n int pos = 0;\n while((pos = rx.indexIn(currentCrontab, pos)) != -1)\n {\n linesToRemove += rx.cap();\n pos += rx.matchedLength();\n }\n\n if(linesToRemove.isEmpty())\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Looks like Job scheduling hasn't been enabled\"\n \" yet. Nothing to do. \\n\\n%1\")\n .arg(CRON_MARKER_HELP);\n return info;\n }\n info.status = SCHEDULE_NEED_INFO;\n info.message = linesToRemove;\n info.extra = currentCrontab;\n return info;\n}\n\nstruct scheduleinfo cronDisable_p2(QString linesToRemove, QString currentCrontab)\n{\n struct scheduleinfo info = {SCHEDULE_OK, \"\", \"\"};\n struct cmdinfo pinfo;\n\n currentCrontab.remove(linesToRemove);\n DEBUG << currentCrontab;\n QByteArray newCrontab = currentCrontab.toLatin1();\n\n pinfo = runCmd(\"crontab\", QStringList() << \"-\", &newCrontab);\n if(pinfo.exit_code != 0)\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(\"Failed to update crontab: %1\")\n .arg(QString(pinfo.stderr_msg));\n return info;\n }\n return info;\n}\n\nstruct scheduleinfo correctedSchedulingPath()\n{\n struct scheduleinfo info = {SCHEDULE_NOTHING_HAPPENED, \"\", \"\"};\n#if defined(Q_OS_OSX)\n QSettings launchdPlist(QDir::homePath()\n + \"\/Library\/LaunchAgents\/com.tarsnap.gui.plist\",\n QSettings::NativeFormat);\n\n \/\/ Bail if the file doesn't exist\n if(!launchdPlist.contains(\"ProgramArguments\"))\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(UPDATED_LAUNCHD_PATH_ERROR);\n return (info);\n }\n\n \/\/ Get path, bail if it still exists (we assume it's still executable)\n QStringList args =\n launchdPlist.value(\"ProgramArguments\").value();\n if(QFile::exists(args.at(0)))\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(UPDATED_LAUNCHD_PATH_ERROR);\n return (info);\n }\n\n \/\/ Update the path\n args.replace(0, QCoreApplication::applicationFilePath().toLatin1());\n launchdPlist.setValue(\"ProgramArguments\", args);\n launchdPlist.sync();\n\n \/\/ Stop launchd script if it's loaded\n if(launchdLoaded())\n {\n if(launchdUnload() != 0)\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(UPDATED_LAUNCHD_PATH_ERROR);\n return (info);\n }\n }\n\n \/\/ Load (and start) new program\n if(launchdLoad() != 0)\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(UPDATED_LAUNCHD_PATH_ERROR);\n return (info);\n }\n\n info.status = SCHEDULE_OK;\n info.message = tr(UPDATED_LAUNCHD_PATH_LONG);\n info.extra = tr(UPDATED_LAUNCHED_PATH_SHORT);\n return (0);\n#else\n return (info);\n#endif\n}\nScheduling.cpp: fix OSX compile#include \n#include \n#include \n#include \n#include \n\n#include \"debug.h\"\n#include \"utils.h\"\n\n#include \"scheduling.h\"\n\n#define UPDATED_LAUNCHD_PATH_LONG \\\n \"The OS X launchd scheduling service contained an out-of-date link to \" \\\n \"Tarsnap GUI (did you upgrade it recently?).\\n\\nThis has been updated to \" \\\n \"point to the current Tarsnap GUI.\"\n\n#define UPDATED_LAUNCHD_PATH_SHORT \"Updated launchd path to Tarsnap GUI\"\n\n#define UPDATED_LAUNCHD_PATH_ERROR \\\n \"An error occurred while attempting to \" \\\n \"update the OS X launchd path.\"\n\nstruct cmdinfo\n{\n int exit_code;\n QByteArray stderr_msg;\n QByteArray stdout_msg;\n};\n\nstatic struct cmdinfo runCmd(QString cmd, QStringList args,\n const QByteArray *stdin_msg = nullptr)\n{\n QProcess proc;\n struct cmdinfo info;\n proc.start(cmd, args);\n\n \/\/ We can want stdin_msg to be empty but non-null; for example if we're\n \/\/ disabling the scheduling and therefore writing an empty crontab file.\n if(stdin_msg != nullptr)\n {\n proc.write(*stdin_msg);\n proc.closeWriteChannel();\n }\n proc.waitForFinished(-1);\n\n \/\/ Get exit code, working around QProcess not having a valid exitCode()\n \/\/ if there's a crash.\n info.exit_code = proc.exitCode();\n if(proc.exitStatus() != QProcess::NormalExit)\n info.exit_code = -1;\n\n info.stderr_msg = proc.readAllStandardError();\n info.stdout_msg = proc.readAllStandardOutput();\n\n return (info);\n}\n\n\/\/ This is an awkward hack which is an intermediate step towards separating\n\/\/ the front-end and back-end code. Return values:\n\/\/ 0: everything ok\n\/\/ 1: failed to load\n\/\/ 2: failed to start\nstatic int launchdLoad()\n{\n struct cmdinfo pinfo;\n QString launchdPlistFileName =\n QDir::homePath() + \"\/Library\/LaunchAgents\/com.tarsnap.gui.plist\";\n\n pinfo = runCmd(\"launchctl\", QStringList() << \"load\" << launchdPlistFileName);\n if(pinfo.exit_code != 0)\n return (1);\n\n pinfo = runCmd(\"launchctl\", QStringList() << \"start\"\n << \"com.tarsnap.gui\");\n if(pinfo.exit_code != 0)\n return (2);\n\n return (0);\n}\n\n\/\/ Return values:\n\/\/ 0: everything ok\n\/\/ 1: failed to unload\nstatic int launchdUnload()\n{\n struct cmdinfo pinfo;\n QString launchdPlistFileName =\n QDir::homePath() + \"\/Library\/LaunchAgents\/com.tarsnap.gui.plist\";\n\n pinfo =\n runCmd(\"launchctl\", QStringList() << \"unload\" << launchdPlistFileName);\n if(pinfo.exit_code != 0)\n return (1);\n\n return (0);\n}\n\n#if defined(Q_OS_OSX)\nstatic bool launchdLoaded()\n{\n struct cmdinfo pinfo;\n\n pinfo = runCmd(\"launchctl\", QStringList() << \"list\"\n << \"com.tarsnap.gui\");\n if(pinfo.exit_code != 0)\n return (false);\n\n return (true);\n}\n#endif\n\nstruct scheduleinfo launchdEnable()\n{\n struct scheduleinfo info = {SCHEDULE_OK, \"\", \"\"};\n\n QFile launchdPlist(\":\/com.tarsnap.gui.plist\");\n launchdPlist.open(QIODevice::ReadOnly | QIODevice::Text);\n QFile launchdPlistFile(QDir::homePath()\n + \"\/Library\/LaunchAgents\/com.tarsnap.gui.plist\");\n if(launchdPlistFile.exists())\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(\"Looks like scheduling is already enabled.\"\n \" Nothing to do.\\n\\n%1\")\n .arg(CRON_MARKER_HELP);\n return info;\n }\n if(!launchdPlistFile.open(QIODevice::WriteOnly | QIODevice::Text))\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Failed to write service file %1. Aborting operation.\")\n .arg(launchdPlistFile.fileName());\n return info;\n }\n launchdPlistFile.write(\n launchdPlist.readAll()\n .replace(\"%1\", QCoreApplication::applicationFilePath().toLatin1())\n .replace(\"%2\", QDir::homePath().toLatin1()));\n launchdPlist.close();\n launchdPlistFile.close();\n\n int ret = launchdLoad();\n if(ret == 1)\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(\"Failed to load launchd service file.\");\n return info;\n }\n else if(ret == 2)\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(\"Failed to start launchd service file.\");\n return info;\n }\n return info;\n}\n\nstruct scheduleinfo launchdDisable()\n{\n struct scheduleinfo info = {SCHEDULE_OK, \"\", \"\"};\n\n QFile launchdPlistFile(QDir::homePath()\n + \"\/Library\/LaunchAgents\/com.tarsnap.gui.plist\");\n if(!launchdPlistFile.exists())\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Launchd service file not found:\\n%1\\n Nothing to do.\")\n .arg(launchdPlistFile.fileName());\n return info;\n }\n\n int ret = launchdUnload();\n if(ret == 1)\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(\"Failed to unload launchd service.\");\n return info;\n }\n\n if(!launchdPlistFile.remove())\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Cannot remove service file:\\n%1\\nAborting operation.\")\n .arg(launchdPlistFile.fileName());\n return info;\n }\n return info;\n}\n\nstruct scheduleinfo cronEnable()\n{\n struct scheduleinfo info = {SCHEDULE_OK, \"\", \"\"};\n\n struct cmdinfo pinfo;\n pinfo = runCmd(\"crontab\", QStringList() << \"-l\");\n if(pinfo.exit_code != 0)\n {\n QString error(pinfo.stderr_msg);\n \/* On some distros crontab -l exits with error 1 and message\n * \"no crontab for username\" if there's no crontab installed\n * for the current user. If parent is the case proceed and don't err.\n *\/\n if(-1 == error.indexOf(QRegExp(\"^(crontab: )?no crontab for\")))\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Failed to list current crontab: %1\").arg(error);\n return info;\n }\n }\n QString currentCrontab(pinfo.stdout_msg);\n\n QRegExp rx(QString(\"\\n?%1.+%2\\n?\")\n .arg(QRegExp::escape(CRON_MARKER_BEGIN))\n .arg(QRegExp::escape(CRON_MARKER_END)));\n rx.setMinimal(true);\n if(-1 != rx.indexIn(currentCrontab))\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Looks like scheduling is already enabled for the\"\n \" current user's crontab. Nothing to do.\"\n \"\\n%1\")\n .arg(CRON_MARKER_HELP);\n return info;\n }\n\n QString cronLine(CRON_LINE);\n QProcessEnvironment env = QProcessEnvironment::systemEnvironment();\n cronLine =\n cronLine\n .arg(env.contains(\"SCREEN\") ? \"SCREEN=\" + env.value(\"SCREEN\") : \"\")\n .arg(env.contains(\"DISPLAY\") ? \"DISPLAY=\" + env.value(\"DISPLAY\")\n : \"\")\n .arg(env.contains(\"XAUTHORITY\")\n ? \"XAUTHORITY=\" + env.value(\"XAUTHORITY\")\n : \"\")\n .arg(QCoreApplication::applicationFilePath());\n\n QString cronBlock(\"\\n%1\\n%2\\n%3\\n%4\\n\");\n cronBlock = cronBlock.arg(CRON_MARKER_BEGIN)\n .arg(CRON_MARKER_HELP)\n .arg(cronLine)\n .arg(CRON_MARKER_END);\n\n info.status = SCHEDULE_NEED_INFO;\n info.message = cronBlock;\n info.extra = currentCrontab;\n\n return info;\n}\n\nstruct scheduleinfo cronEnable_p2(QString cronBlock, QString currentCrontab)\n{\n struct scheduleinfo info = {SCHEDULE_OK, \"\", \"\"};\n struct cmdinfo pinfo;\n\n currentCrontab.append(cronBlock.toLatin1());\n QByteArray newCrontab = currentCrontab.toLatin1();\n\n pinfo = runCmd(\"crontab\", QStringList() << \"-\", &newCrontab);\n if(pinfo.exit_code != 0)\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(\"Failed to update crontab: %1\")\n .arg(QString(pinfo.stderr_msg));\n return info;\n }\n return info;\n}\n\nstruct scheduleinfo cronDisable()\n{\n struct scheduleinfo info = {SCHEDULE_OK, \"\", \"\"};\n struct cmdinfo pinfo;\n\n pinfo = runCmd(\"crontab\", QStringList() << \"-l\");\n if(pinfo.exit_code != 0)\n {\n QString error(pinfo.stderr_msg);\n \/* On some distros crontab -l exits with error 1 and message\n * \"no crontab for username\" if there's no crontab installed\n * for the current user. If parent is the case proceed and don't err.\n *\/\n if(error.startsWith(QLatin1String(\"no crontab for\")))\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"There's no crontab for the current user.\"\n \" Nothing to do.\\n\\n%1\")\n .arg(CRON_MARKER_HELP);\n return info;\n }\n else\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Failed to list current crontab: %1\").arg(error);\n return info;\n }\n }\n QString currentCrontab(pinfo.stdout_msg);\n if(currentCrontab.isEmpty())\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Looks like the crontab for the current user is\"\n \" empty. Nothing to do.\\n\\n%1\")\n .arg(CRON_MARKER_HELP);\n return info;\n }\n\n QRegExp rx(QString(\"\\n?%1.+%2\\n?\")\n .arg(QRegExp::escape(CRON_MARKER_BEGIN))\n .arg(QRegExp::escape(CRON_MARKER_END)));\n \/\/ rx.setMinimal(true);\n QString linesToRemove;\n int pos = 0;\n while((pos = rx.indexIn(currentCrontab, pos)) != -1)\n {\n linesToRemove += rx.cap();\n pos += rx.matchedLength();\n }\n\n if(linesToRemove.isEmpty())\n {\n info.status = SCHEDULE_ERROR;\n info.message =\n QObject::tr(\"Looks like Job scheduling hasn't been enabled\"\n \" yet. Nothing to do. \\n\\n%1\")\n .arg(CRON_MARKER_HELP);\n return info;\n }\n info.status = SCHEDULE_NEED_INFO;\n info.message = linesToRemove;\n info.extra = currentCrontab;\n return info;\n}\n\nstruct scheduleinfo cronDisable_p2(QString linesToRemove, QString currentCrontab)\n{\n struct scheduleinfo info = {SCHEDULE_OK, \"\", \"\"};\n struct cmdinfo pinfo;\n\n currentCrontab.remove(linesToRemove);\n DEBUG << currentCrontab;\n QByteArray newCrontab = currentCrontab.toLatin1();\n\n pinfo = runCmd(\"crontab\", QStringList() << \"-\", &newCrontab);\n if(pinfo.exit_code != 0)\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(\"Failed to update crontab: %1\")\n .arg(QString(pinfo.stderr_msg));\n return info;\n }\n return info;\n}\n\nstruct scheduleinfo correctedSchedulingPath()\n{\n struct scheduleinfo info = {SCHEDULE_NOTHING_HAPPENED, \"\", \"\"};\n#if defined(Q_OS_OSX)\n QSettings launchdPlist(QDir::homePath()\n + \"\/Library\/LaunchAgents\/com.tarsnap.gui.plist\",\n QSettings::NativeFormat);\n\n \/\/ Bail if the file doesn't exist\n if(!launchdPlist.contains(\"ProgramArguments\"))\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(UPDATED_LAUNCHD_PATH_ERROR);\n return (info);\n }\n\n \/\/ Get path, bail if it still exists (we assume it's still executable)\n QStringList args =\n launchdPlist.value(\"ProgramArguments\").value();\n if(QFile::exists(args.at(0)))\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(UPDATED_LAUNCHD_PATH_ERROR);\n return (info);\n }\n\n \/\/ Update the path\n args.replace(0, QCoreApplication::applicationFilePath().toLatin1());\n launchdPlist.setValue(\"ProgramArguments\", args);\n launchdPlist.sync();\n\n \/\/ Stop launchd script if it's loaded\n if(launchdLoaded())\n {\n if(launchdUnload() != 0)\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(UPDATED_LAUNCHD_PATH_ERROR);\n return (info);\n }\n }\n\n \/\/ Load (and start) new program\n if(launchdLoad() != 0)\n {\n info.status = SCHEDULE_ERROR;\n info.message = QObject::tr(UPDATED_LAUNCHD_PATH_ERROR);\n return (info);\n }\n\n info.status = SCHEDULE_OK;\n info.message = QObject::tr(UPDATED_LAUNCHD_PATH_LONG);\n info.extra = QObject::tr(UPDATED_LAUNCHD_PATH_SHORT);\n return (info);\n#else\n return (info);\n#endif\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"libzlog.h\"\n#include \"zlog.pb.h\"\n\nnamespace po = boost::program_options;\n\nclass Sequence {\n public:\n Sequence() : seq_(0) {}\n Sequence(uint64_t seq) : seq_(seq) {}\n\n uint64_t read() {\n return seq_;\n }\n\n void inc() {\n seq_++;\n }\n\n private:\n uint64_t seq_;\n};\n\nclass LogManager {\n public:\n LogManager() {\n thread_ = boost::thread(&LogManager::Run, this);\n }\n\n \/*\n * Read and optionally increment the log sequence number.\n *\/\n uint64_t ReadSequence(const std::string& pool, const std::string& name,\n uint64_t epoch, bool increment, uint64_t *seq) {\n\n boost::unique_lock g(lock_);\n\n std::map, Log>::iterator it =\n logs_.find(std::make_pair(pool, name));\n\n if (it == logs_.end()) {\n QueueLogInit(pool, name);\n return -EAGAIN;\n }\n\n if (epoch < it->second.epoch)\n return -ERANGE;\n\n if (increment)\n it->second.seq.inc();\n\n *seq = it->second.seq.read();\n\n return 0;\n }\n\n private:\n struct Log {\n Log() {}\n Log(uint64_t pos, uint64_t epoch) : seq(pos), epoch(epoch) {}\n Sequence seq;\n uint64_t epoch;\n };\n\n \/*\n * Prepare the log for this sequencer. After this function runs a new\n * epoch has been allocated, each storage device is sealed with the new\n * epoch, and the maximum position written to prior to the new epoch is\n * found. The sequencer must not be allowed to hand out new positions until\n * these steps are completed successfully.\n *\/\n int InitLog(const std::string& pool, const std::string& name,\n uint64_t *pepoch, uint64_t *pposition) {\n\n librados::Rados rados;\n int ret = rados.init(NULL);\n if (ret) {\n std::cerr << \"could not initialize rados client\" << std::endl;\n return ret;\n }\n\n rados.conf_read_file(NULL);\n\n ret = rados.connect();\n if (ret) {\n std::cerr << \"rados client could not connect\" << std::endl;\n return ret;\n }\n\n librados::IoCtx ioctx;\n ret = rados.ioctx_create(pool.c_str(), ioctx);\n if (ret) {\n std::cerr << \"failed to connect to pool \" << pool\n << \" ret \" << ret << std::endl;\n return ret;\n }\n\n zlog::Log log;\n ret = zlog::Log::Open(ioctx, name, NULL, log);\n if (ret) {\n std::cerr << \"failed to open log \" << name << std::endl;\n return ret;\n }\n\n uint64_t epoch;\n ret = log.SetProjection(&epoch);\n if (ret) {\n std::cerr << \"failed to set new projection \" << ret << std::endl;\n return ret;\n }\n\n ret = log.Seal(epoch);\n if (ret) {\n std::cerr << \"failed to seal the store \" << ret << std::endl;\n return ret;\n }\n\n uint64_t position;\n ret = log.FindMaxPosition(epoch, &position);\n if (ret) {\n std::cerr << \"failed to find max position \" << ret << std::endl;\n return ret;\n }\n\n *pepoch = epoch;\n *pposition = position;\n\n ioctx.close();\n rados.shutdown();\n\n return 0;\n }\n\n \/*\n * Queue a log to be initialized.\n *\/\n void QueueLogInit(const std::string& pool, const std::string& name) {\n pending_logs_.insert(std::make_pair(pool, name));\n cond_.notify_one();\n }\n\n void Run() {\n for (;;) {\n std::string pool, name;\n\n {\n boost::unique_lock g(lock_);\n while (pending_logs_.empty())\n cond_.wait(g);\n std::set >::iterator it =\n pending_logs_.begin();\n assert(it != pending_logs_.end());\n pool = it->first;\n name = it->second;\n }\n\n uint64_t position, epoch;\n int ret = InitLog(pool, name, &epoch, &position);\n if (ret) {\n boost::unique_lock g(lock_);\n pending_logs_.erase(std::make_pair(pool, name));\n std::cerr << \"failed to init log\" << std::endl;\n continue;\n }\n\n {\n boost::unique_lock g(lock_);\n std::pair key = std::make_pair(pool, name);\n assert(pending_logs_.count(key) == 1);\n pending_logs_.erase(key);\n assert(logs_.count(key) == 0);\n Log log(position, epoch);\n logs_[key] = log;\n }\n }\n }\n\n boost::thread thread_;\n boost::mutex lock_;\n boost::condition_variable cond_;\n std::map, LogManager::Log > logs_;\n std::set > pending_logs_;\n};\n\nstatic LogManager *log_mgr;\n\nclass Session {\n public:\n Session(boost::asio::io_service& io_service)\n : socket_(io_service)\n {}\n\n boost::asio::ip::tcp::socket& socket() {\n return socket_;\n }\n\n void start() {\n boost::asio::async_read(socket_,\n boost::asio::buffer(buffer_, sizeof(uint32_t)),\n boost::bind(&Session::handle_hdr, this,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n }\n\n private:\n void handle_hdr(const boost::system::error_code& err, size_t size) {\n if (err) {\n delete this;\n return;\n }\n\n uint32_t msg_size = ntohl(*((uint32_t*)buffer_));\n\n if (msg_size > sizeof(buffer_)) {\n std::cerr << \"message is too large\" << std::endl;\n delete this;\n return;\n }\n\n boost::asio::async_read(socket_,\n boost::asio::buffer(buffer_, msg_size),\n boost::bind(&Session::handle_msg, this,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n }\n\n void handle_msg(const boost::system::error_code& err, size_t size) {\n if (err) {\n delete this;\n return;\n }\n\n req_.Clear();\n\n if (!req_.ParseFromArray(buffer_, size)) {\n std::cerr << \"failed to parse message\" << std::endl;\n delete this;\n return;\n }\n\n if (!req_.IsInitialized()) {\n std::cerr << \"received incomplete message\" << std::endl;\n delete this;\n return;\n }\n\n reply_.Clear();\n\n uint64_t seq;\n\n int ret = log_mgr->ReadSequence(req_.pool(), req_.name(),\n req_.epoch(), req_.next(), &seq);\n if (ret == -EAGAIN)\n reply_.set_status(zlog_proto::MSeqReply::INIT_LOG);\n else if (ret == -ERANGE)\n reply_.set_status(zlog_proto::MSeqReply::STALE_EPOCH);\n else\n assert(!ret);\n\n reply_.set_position(seq);\n\n assert(reply_.IsInitialized());\n\n uint32_t msg_size = reply_.ByteSize();\n assert(msg_size < sizeof(buffer_));\n assert(reply_.SerializeToArray(buffer_, msg_size));\n\n \/\/ scatter\/gather buffers\n std::vector out;\n be_msg_size_ = htonl(msg_size);\n out.push_back(boost::asio::buffer(&be_msg_size_, sizeof(be_msg_size_)));\n out.push_back(boost::asio::buffer(buffer_, msg_size));\n\n boost::asio::async_write(socket_, out,\n boost::bind(&Session::handle_reply, this,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n }\n\n void handle_reply(const boost::system::error_code& err, size_t size) {\n if (err) {\n delete this;\n return;\n }\n\n start();\n }\n\n boost::asio::ip::tcp::socket socket_;\n\n char buffer_[1024];\n uint32_t be_msg_size_;\n\n zlog_proto::MSeqRequest req_;\n zlog_proto::MSeqReply reply_;\n};\n\nclass Server {\n public:\n Server(boost::asio::io_service& io_service, short port)\n : io_service_(io_service),\n acceptor_(io_service,\n boost::asio::ip::tcp::endpoint(\n boost::asio::ip::tcp::v4(), port))\n {\n start_accept();\n }\n\n private:\n void start_accept() {\n Session* new_session = new Session(io_service_);\n acceptor_.async_accept(new_session->socket(),\n boost::bind(&Server::handle_accept, this, new_session,\n boost::asio::placeholders::error));\n }\n\n void handle_accept(Session* new_session,\n const boost::system::error_code& error) {\n if (!error)\n new_session->start();\n else\n delete new_session;\n start_accept();\n }\n\n boost::asio::io_service& io_service_;\n boost::asio::ip::tcp::acceptor acceptor_;\n};\n\nint main(int argc, char* argv[])\n{\n int port;\n std::string host;\n\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"port\", po::value(&port)->required(), \"Server port\")\n (\"daemon,d\", \"Run in background\")\n ;\n\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n\n boost::asio::io_service io_service;\n Server s(io_service, port);\n\n if (vm.count(\"daemon\")) {\n io_service.notify_fork(boost::asio::io_service::fork_prepare);\n\n pid_t pid = fork();\n if (pid < 0) {\n exit(EXIT_FAILURE);\n }\n\n if (pid > 0) {\n exit(EXIT_SUCCESS);\n }\n\n pid_t sid = setsid();\n if (sid < 0) {\n exit(EXIT_FAILURE);\n }\n\n umask(0);\n\n close(0);\n close(1);\n close(2);\n\n io_service.notify_fork(boost::asio::io_service::fork_child);\n }\n\n log_mgr = new LogManager();\n\n io_service.run();\n\n return 0;\n}\nseqr: add basic performance monitor#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"libzlog.h\"\n#include \"zlog.pb.h\"\n\nnamespace po = boost::program_options;\n\nstatic uint64_t get_time(void)\n{\n struct timespec ts;\n int ret = clock_gettime(CLOCK_MONOTONIC, &ts);\n assert(ret == 0);\n uint64_t nsec = ((uint64_t)ts.tv_sec) * ((uint64_t)1000000000);\n nsec += ts.tv_nsec;\n return nsec;\n}\n\nclass Sequence {\n public:\n Sequence() : seq_(0) {}\n Sequence(uint64_t seq) : seq_(seq) {}\n\n uint64_t read() {\n return seq_;\n }\n\n void inc() {\n seq_++;\n }\n\n private:\n uint64_t seq_;\n};\n\nclass LogManager {\n public:\n LogManager() {\n thread_ = boost::thread(&LogManager::Run, this);\n bench_thread_ = boost::thread(&LogManager::BenchMonitor, this);\n }\n\n \/*\n * Read and optionally increment the log sequence number.\n *\/\n uint64_t ReadSequence(const std::string& pool, const std::string& name,\n uint64_t epoch, bool increment, uint64_t *seq) {\n\n boost::unique_lock g(lock_);\n\n std::map, Log>::iterator it =\n logs_.find(std::make_pair(pool, name));\n\n if (it == logs_.end()) {\n QueueLogInit(pool, name);\n return -EAGAIN;\n }\n\n if (epoch < it->second.epoch)\n return -ERANGE;\n\n if (increment)\n it->second.seq.inc();\n\n *seq = it->second.seq.read();\n\n return 0;\n }\n\n private:\n struct Log {\n Log() {}\n Log(uint64_t pos, uint64_t epoch) : seq(pos), epoch(epoch) {}\n Sequence seq;\n uint64_t epoch;\n };\n\n \/*\n * Prepare the log for this sequencer. After this function runs a new\n * epoch has been allocated, each storage device is sealed with the new\n * epoch, and the maximum position written to prior to the new epoch is\n * found. The sequencer must not be allowed to hand out new positions until\n * these steps are completed successfully.\n *\/\n int InitLog(const std::string& pool, const std::string& name,\n uint64_t *pepoch, uint64_t *pposition) {\n\n librados::Rados rados;\n int ret = rados.init(NULL);\n if (ret) {\n std::cerr << \"could not initialize rados client\" << std::endl;\n return ret;\n }\n\n rados.conf_read_file(NULL);\n\n ret = rados.connect();\n if (ret) {\n std::cerr << \"rados client could not connect\" << std::endl;\n return ret;\n }\n\n librados::IoCtx ioctx;\n ret = rados.ioctx_create(pool.c_str(), ioctx);\n if (ret) {\n std::cerr << \"failed to connect to pool \" << pool\n << \" ret \" << ret << std::endl;\n return ret;\n }\n\n zlog::Log log;\n ret = zlog::Log::Open(ioctx, name, NULL, log);\n if (ret) {\n std::cerr << \"failed to open log \" << name << std::endl;\n return ret;\n }\n\n uint64_t epoch;\n ret = log.SetProjection(&epoch);\n if (ret) {\n std::cerr << \"failed to set new projection \" << ret << std::endl;\n return ret;\n }\n\n ret = log.Seal(epoch);\n if (ret) {\n std::cerr << \"failed to seal the store \" << ret << std::endl;\n return ret;\n }\n\n uint64_t position;\n ret = log.FindMaxPosition(epoch, &position);\n if (ret) {\n std::cerr << \"failed to find max position \" << ret << std::endl;\n return ret;\n }\n\n *pepoch = epoch;\n *pposition = position;\n\n ioctx.close();\n rados.shutdown();\n\n return 0;\n }\n\n \/*\n * Queue a log to be initialized.\n *\/\n void QueueLogInit(const std::string& pool, const std::string& name) {\n pending_logs_.insert(std::make_pair(pool, name));\n cond_.notify_one();\n }\n\n \/*\n * Monitors the performance of the sequencer.\n *\n * It looks at all the sequence states and then computes how many sequences\n * were handed out over a period of time.\n *\n * FIXME: Note that this currently doesn't take into account new logs that\n * are registered during the sleep period.\n *\/\n void BenchMonitor() {\n for (;;) {\n uint64_t start_ns;\n uint64_t start_seq;\n\n \/\/ starting state of all the current sequences\n {\n boost::unique_lock g(lock_);\n\n start_ns = get_time();\n start_seq = 0;\n\n std::map, LogManager::Log >::iterator it;\n for (it = logs_.begin(); it != logs_.end(); it++) {\n start_seq += it->second.seq.read();\n }\n }\n\n sleep(60);\n\n uint64_t end_ns;\n uint64_t end_seq;\n int num_logs;\n\n \/\/ ending state of all the current sequences\n {\n boost::unique_lock g(lock_);\n\n end_ns = get_time();\n end_seq = 0;\n num_logs = logs_.size();\n\n std::map, LogManager::Log >::iterator it;\n for (it = logs_.begin(); it != logs_.end(); it++) {\n end_seq += it->second.seq.read();\n }\n }\n\n uint64_t elapsed_ns = end_ns - start_ns;\n uint64_t total_seqs = end_seq - start_seq;\n uint64_t rate = (total_seqs * 1000000000ULL) \/ elapsed_ns;\n std::cout << \"seqr rate = \" << rate << \" seqs\/sec\" << std::endl;\n }\n }\n\n void Run() {\n for (;;) {\n std::string pool, name;\n\n {\n boost::unique_lock g(lock_);\n while (pending_logs_.empty())\n cond_.wait(g);\n std::set >::iterator it =\n pending_logs_.begin();\n assert(it != pending_logs_.end());\n pool = it->first;\n name = it->second;\n }\n\n uint64_t position, epoch;\n int ret = InitLog(pool, name, &epoch, &position);\n if (ret) {\n boost::unique_lock g(lock_);\n pending_logs_.erase(std::make_pair(pool, name));\n std::cerr << \"failed to init log\" << std::endl;\n continue;\n }\n\n {\n boost::unique_lock g(lock_);\n std::pair key = std::make_pair(pool, name);\n assert(pending_logs_.count(key) == 1);\n pending_logs_.erase(key);\n assert(logs_.count(key) == 0);\n Log log(position, epoch);\n logs_[key] = log;\n }\n }\n }\n\n boost::thread thread_;\n boost::thread bench_thread_;\n boost::mutex lock_;\n boost::condition_variable cond_;\n std::map, LogManager::Log > logs_;\n std::set > pending_logs_;\n};\n\nstatic LogManager *log_mgr;\n\nclass Session {\n public:\n Session(boost::asio::io_service& io_service)\n : socket_(io_service)\n {}\n\n boost::asio::ip::tcp::socket& socket() {\n return socket_;\n }\n\n void start() {\n boost::asio::async_read(socket_,\n boost::asio::buffer(buffer_, sizeof(uint32_t)),\n boost::bind(&Session::handle_hdr, this,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n }\n\n private:\n void handle_hdr(const boost::system::error_code& err, size_t size) {\n if (err) {\n delete this;\n return;\n }\n\n uint32_t msg_size = ntohl(*((uint32_t*)buffer_));\n\n if (msg_size > sizeof(buffer_)) {\n std::cerr << \"message is too large\" << std::endl;\n delete this;\n return;\n }\n\n boost::asio::async_read(socket_,\n boost::asio::buffer(buffer_, msg_size),\n boost::bind(&Session::handle_msg, this,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n }\n\n void handle_msg(const boost::system::error_code& err, size_t size) {\n if (err) {\n delete this;\n return;\n }\n\n req_.Clear();\n\n if (!req_.ParseFromArray(buffer_, size)) {\n std::cerr << \"failed to parse message\" << std::endl;\n delete this;\n return;\n }\n\n if (!req_.IsInitialized()) {\n std::cerr << \"received incomplete message\" << std::endl;\n delete this;\n return;\n }\n\n reply_.Clear();\n\n uint64_t seq;\n\n int ret = log_mgr->ReadSequence(req_.pool(), req_.name(),\n req_.epoch(), req_.next(), &seq);\n if (ret == -EAGAIN)\n reply_.set_status(zlog_proto::MSeqReply::INIT_LOG);\n else if (ret == -ERANGE)\n reply_.set_status(zlog_proto::MSeqReply::STALE_EPOCH);\n else\n assert(!ret);\n\n reply_.set_position(seq);\n\n assert(reply_.IsInitialized());\n\n uint32_t msg_size = reply_.ByteSize();\n assert(msg_size < sizeof(buffer_));\n assert(reply_.SerializeToArray(buffer_, msg_size));\n\n \/\/ scatter\/gather buffers\n std::vector out;\n be_msg_size_ = htonl(msg_size);\n out.push_back(boost::asio::buffer(&be_msg_size_, sizeof(be_msg_size_)));\n out.push_back(boost::asio::buffer(buffer_, msg_size));\n\n boost::asio::async_write(socket_, out,\n boost::bind(&Session::handle_reply, this,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n }\n\n void handle_reply(const boost::system::error_code& err, size_t size) {\n if (err) {\n delete this;\n return;\n }\n\n start();\n }\n\n boost::asio::ip::tcp::socket socket_;\n\n char buffer_[1024];\n uint32_t be_msg_size_;\n\n zlog_proto::MSeqRequest req_;\n zlog_proto::MSeqReply reply_;\n};\n\nclass Server {\n public:\n Server(boost::asio::io_service& io_service, short port)\n : io_service_(io_service),\n acceptor_(io_service,\n boost::asio::ip::tcp::endpoint(\n boost::asio::ip::tcp::v4(), port))\n {\n start_accept();\n }\n\n private:\n void start_accept() {\n Session* new_session = new Session(io_service_);\n acceptor_.async_accept(new_session->socket(),\n boost::bind(&Server::handle_accept, this, new_session,\n boost::asio::placeholders::error));\n }\n\n void handle_accept(Session* new_session,\n const boost::system::error_code& error) {\n if (!error)\n new_session->start();\n else\n delete new_session;\n start_accept();\n }\n\n boost::asio::io_service& io_service_;\n boost::asio::ip::tcp::acceptor acceptor_;\n};\n\nint main(int argc, char* argv[])\n{\n int port;\n std::string host;\n\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"port\", po::value(&port)->required(), \"Server port\")\n (\"daemon,d\", \"Run in background\")\n ;\n\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n\n boost::asio::io_service io_service;\n Server s(io_service, port);\n\n if (vm.count(\"daemon\")) {\n io_service.notify_fork(boost::asio::io_service::fork_prepare);\n\n pid_t pid = fork();\n if (pid < 0) {\n exit(EXIT_FAILURE);\n }\n\n if (pid > 0) {\n exit(EXIT_SUCCESS);\n }\n\n pid_t sid = setsid();\n if (sid < 0) {\n exit(EXIT_FAILURE);\n }\n\n umask(0);\n\n close(0);\n close(1);\n close(2);\n\n io_service.notify_fork(boost::asio::io_service::fork_child);\n }\n\n log_mgr = new LogManager();\n\n io_service.run();\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \"boost\/chrono.hpp\"\n#include \"boost\/lexical_cast.hpp\"\n#include \"boost\/thread.hpp\"\n\n#include \"dsb\/comm.hpp\"\n#include \"dsb\/control.hpp\"\n#include \"dsb\/error.hpp\"\n#include \"dsb\/protobuf.hpp\"\n#include \"dsb\/util.hpp\"\n\n#include \"control.pb.h\"\n\n#include \"mock_slaves.hpp\"\n\n\n#if defined(_MSC_VER) && _MSC_VER <= 1800\n# define noexcept\n#endif\n\nclass Shutdown : std::exception\n{\npublic:\n const char* what() const noexcept override { return \"Normal shutdown requested by master\"; }\n};\n\n\nuint16_t NormalMessageType(const std::deque& msg)\n{\n const auto mt = dsb::control::NonErrorMessageType(msg);\n if (mt == dsbproto::control::MSG_TERMINATE) throw Shutdown();\n return mt;\n}\n\n\nvoid EnforceMessageType(\n const std::deque& msg,\n dsbproto::control::MessageType expectedType)\n{\n if (NormalMessageType(msg) != expectedType) {\n throw dsb::error::ProtocolViolationException(\n \"Invalid reply from master\");\n }\n}\n\n\nint main(int argc, const char** argv)\n{\ntry {\n if (argc < 7) {\n std::cerr << \"Usage: \" << argv[0] << \" \\n\"\n << \" id = a number in the range 0 - 65535\\n\"\n << \" control = Control socket endpoint (e.g. tcp:\/\/myhost:5432)\\n\"\n << \" data pub = Publisher socket endpoint\\n\"\n << \" data sub = Subscriber socket endpoint\\n\"\n << \" slave type = mass_1d or spring_1d\\n\"\n << \" other slave = ID of other slave\"\n << std::endl;\n return 0;\n }\n const auto id = std::string(argv[1]);\n const auto controlEndpoint = std::string(argv[2]);\n const auto dataPubEndpoint = std::string(argv[3]);\n const auto dataSubEndpoint = std::string(argv[4]);\n const auto slaveType = std::string(argv[5]);\n const auto otherSlaveId = boost::lexical_cast(argv[6]);\n\n auto slaveInstance = NewSlave(slaveType);\n\n auto context = zmq::context_t();\n auto control = zmq::socket_t(context, ZMQ_REQ);\n control.setsockopt(ZMQ_IDENTITY, id.data(), id.size());\n control.connect(controlEndpoint.c_str());\n auto dataPub = zmq::socket_t(context, ZMQ_PUB);\n dataPub.connect(dataPubEndpoint.c_str());\n auto dataSub = zmq::socket_t(context, ZMQ_SUB);\n dataSub.connect(dataSubEndpoint.c_str());\n\n \/\/ Send HELLO\n std::deque msg;\n dsb::control::CreateHelloMessage(msg, 0);\n dsb::comm::Send(control, msg);\n\n \/\/ Receive HELLO\n dsb::comm::Receive(control, msg);\n if (dsb::control::ParseProtocolVersion(msg.front()) != 0) {\n throw std::runtime_error(\"Master required unsupported protocol\");\n }\n\n \/\/ Send MSG_INIT_READY\n dsb::control::CreateMessage(msg, dsbproto::control::MSG_INIT_READY);\n dsb::comm::Send(control, msg);\n\n \/\/ Receive MSG_INIT_DONE\n dsb::comm::Receive(control, msg);\n EnforceMessageType(msg, dsbproto::control::MSG_INIT_DONE);\n\n \/\/ -------------------------------------------------------------------------\n \/\/ Temporary faked code\n const uint16_t inVarRef = 0;\n const uint16_t outVarRef = 1;\n const size_t dataHeaderSize = 4;\n\n \/\/ Build a header to use for subscribing to the other slave's output.\n char otherHeader[dataHeaderSize];\n dsb::util::EncodeUint16(otherSlaveId, otherHeader);\n dsb::util::EncodeUint16(outVarRef, otherHeader + 2);\n dataSub.setsockopt(ZMQ_SUBSCRIBE, otherHeader, dataHeaderSize);\n\n \/\/ Build a header to use for our own output.\n char myHeader[dataHeaderSize];\n dsb::util::EncodeUint16(boost::lexical_cast(id), myHeader);\n dsb::util::EncodeUint16(outVarRef, myHeader + 2);\n \/\/ -------------------------------------------------------------------------\n\n \/\/ MSG_READY loop\n for (;;) {\n dsb::control::CreateMessage(msg, dsbproto::control::MSG_READY);\n dsb::comm::Send(control, msg);\n\n dsb::comm::Receive(control, msg);\n const auto msgType = NormalMessageType(msg);\n switch (msgType) {\n case dsbproto::control::MSG_STEP: {\n \/\/ Extract DoStep message from second (body) frame.\n assert (msg.size() == 2);\n dsbproto::control::StepData stepInfo;\n dsb::protobuf::ParseFromFrame(msg[1], stepInfo);\n\n \/\/ Perform time step\n slaveInstance->DoStep(stepInfo.timepoint(), stepInfo.stepsize());\n \/\/ Pretend to work really hard\n boost::this_thread::sleep_for(boost::chrono::milliseconds(10));\n const auto newTime = stepInfo.timepoint() + stepInfo.stepsize();\n std::cout << newTime << \" \" << slaveInstance->GetVariable(outVarRef) << std::endl;\n\n \/\/ Get value of output variable\n dsbproto::variable::TimestampedValue outVar;\n outVar.set_timestamp(newTime);\n outVar.mutable_value()->set_real_value(slaveInstance->GetVariable(outVarRef));\n\n \/\/ Build data message to be published\n std::deque dataMsg;\n \/\/ Header\n dataMsg.push_back(zmq::message_t(dataHeaderSize));\n std::copy(myHeader, myHeader+dataHeaderSize,\n static_cast(dataMsg.back().data()));\n \/\/ Body\n dataMsg.push_back(zmq::message_t());\n dsb::protobuf::SerializeToFrame(outVar, dataMsg.back());\n \/\/ Send it\n dsb::comm::Send(dataPub, dataMsg);\n\n \/\/ Send STEP_OK message\n std::deque stepOkMsg;\n dsb::control::CreateMessage(stepOkMsg, dsbproto::control::MSG_STEP_OK);\n dsb::comm::Send(control, stepOkMsg);\n\n \/\/ Wait for RECV_VARS command\n std::deque recvVarsMsg;\n dsb::comm::Receive(control, recvVarsMsg);\n EnforceMessageType(recvVarsMsg, dsbproto::control::MSG_RECV_VARS);\n\n \/\/ Receive message from other and store the body in inVar.\n const auto allowedTimeError = stepInfo.stepsize() * 1e-6;\n dsbproto::variable::TimestampedValue inVar;\n do {\n dsb::comm::Receive(dataSub, dataMsg);\n dsb::protobuf::ParseFromFrame(dataMsg.back(), inVar);\n assert (inVar.timestamp() < newTime + allowedTimeError\n && \"Data received from the future\");\n \/\/ If the message has been queued up from a previous time\n \/\/ step, which could happen if we have joined the simulation\n \/\/ while it's in progress, discard it and retry.\n } while (inVar.timestamp() < newTime - allowedTimeError);\n\n \/\/ Set our input variable.\n slaveInstance->SetVariable(inVarRef, inVar.value().real_value());\n break; }\n default:\n throw dsb::error::ProtocolViolationException(\n \"Invalid reply from master\");\n }\n }\n} catch (const Shutdown& e) {\n std::cerr << \"Shutdown: \" << e.what() << std::endl;\n}\n}\nRefactored \"slave\"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"boost\/chrono.hpp\"\n#include \"boost\/lexical_cast.hpp\"\n#include \"boost\/thread.hpp\"\n\n#include \"dsb\/comm.hpp\"\n#include \"dsb\/control.hpp\"\n#include \"dsb\/error.hpp\"\n#include \"dsb\/protobuf.hpp\"\n#include \"dsb\/util.hpp\"\n\n#include \"control.pb.h\"\n\n#include \"mock_slaves.hpp\"\n\n\n#if defined(_MSC_VER) && _MSC_VER <= 1800\n# define noexcept\n#endif\n\nclass Shutdown : std::exception\n{\npublic:\n const char* what() const noexcept override { return \"Normal shutdown requested by master\"; }\n};\n\n\nuint16_t NormalMessageType(const std::deque& msg)\n{\n const auto mt = dsb::control::NonErrorMessageType(msg);\n if (mt == dsbproto::control::MSG_TERMINATE) throw Shutdown();\n return mt;\n}\n\n\nvoid EnforceMessageType(\n const std::deque& msg,\n dsbproto::control::MessageType expectedType)\n{\n if (NormalMessageType(msg) != expectedType) {\n throw dsb::error::ProtocolViolationException(\n \"Invalid reply from master\");\n }\n}\n\n\n\/**\n\\brief A class which contains the state of the slave and takes care of\n responding to requests from the master node in an appropriate manner.\n*\/\nclass Slave\n{\npublic:\n \/**\n \\brief Constructs a new Slave.\n\n \\param [in] id The slave ID.\n \\param [in] dataSub A SUB socket to be used for receiving variables.\n \\param [in] dataPub A PUB socket to be used for sending variables.\n \\param [in] slaveInstance (Temporary) A pointer to the object which\n contains the slave's mathematical model.\n \\param [in] otherSlaveId (Temporary) The ID of the slave which this\n slave should be connected to.\n *\/\n Slave(\n uint16_t id,\n zmq::socket_t dataSub,\n zmq::socket_t dataPub,\n std::unique_ptr slaveInstance,\n uint16_t otherSlaveId\n );\n\n \/**\n \\brief Prepares the first message (HELLO) which is to be sent to the master\n and stores it in `msg`.\n *\/\n void Start(std::deque& msg);\n\n \/**\n \\brief Responds to a message from the master.\n \n On input, `msg` must be the message received from master, and on output,\n it will contain the slave's reply. Internally, the function forwards to\n the handler function that corresponds to the slave's current state.\n *\/\n void RequestReply(std::deque& msg);\n\nprivate:\n \/\/ Each of these functions correspond to one of the slave's possible states.\n \/\/ On input, `msg` is a message from the master node, and when the function\n \/\/ returns, `msg` must contain the reply. If the message triggers a state\n \/\/ change, the handler function must update m_stateHandler to point to the\n \/\/ function for the new state.\n void ConnectingHandler(std::deque& msg);\n void InitHandler(std::deque& msg);\n void ReadyHandler(std::deque& msg);\n void PublishedHandler(std::deque& msg);\n\n \/\/ Performs the time step for ReadyHandler()\n void Step(const dsbproto::control::StepData& stepData);\n\n \/\/ A pointer to the handler function for the current state.\n void (Slave::* m_stateHandler)(std::deque&);\n\n zmq::socket_t m_dataSub;\n zmq::socket_t m_dataPub;\n std::unique_ptr m_slaveInstance;\n double m_currentTime;\n double m_lastStepSize;\n\n \/\/ -------------------------------------------------------------------------\n \/\/ Temporary\n static const uint16_t IN_VAR_REF = 0;\n static const uint16_t OUT_VAR_REF = 1;\n static const size_t DATA_HEADER_SIZE = 4;\n\n char otherHeader[DATA_HEADER_SIZE];\n char myHeader[DATA_HEADER_SIZE];\n};\n\n\nint main(int argc, const char** argv)\n{\ntry {\n if (argc < 7) {\n std::cerr << \"Usage: \" << argv[0] << \" \\n\"\n << \" id = a number in the range 0 - 65535\\n\"\n << \" control = Control socket endpoint (e.g. tcp:\/\/myhost:5432)\\n\"\n << \" data pub = Publisher socket endpoint\\n\"\n << \" data sub = Subscriber socket endpoint\\n\"\n << \" slave type = mass_1d or spring_1d\\n\"\n << \" other slave = ID of other slave\"\n << std::endl;\n return 0;\n }\n const auto id = std::string(argv[1]);\n const auto controlEndpoint = std::string(argv[2]);\n const auto dataPubEndpoint = std::string(argv[3]);\n const auto dataSubEndpoint = std::string(argv[4]);\n const auto slaveType = std::string(argv[5]);\n const auto otherSlaveId = boost::lexical_cast(argv[6]);\n\n auto context = zmq::context_t();\n auto control = zmq::socket_t(context, ZMQ_REQ);\n control.setsockopt(ZMQ_IDENTITY, id.data(), id.size());\n control.connect(controlEndpoint.c_str());\n auto dataPub = zmq::socket_t(context, ZMQ_PUB);\n dataPub.connect(dataPubEndpoint.c_str());\n auto dataSub = zmq::socket_t(context, ZMQ_SUB);\n dataSub.connect(dataSubEndpoint.c_str());\n\n Slave slave(boost::lexical_cast(id),\n std::move(dataSub),\n std::move(dataPub),\n NewSlave(slaveType),\n otherSlaveId);\n std::deque msg;\n slave.Start(msg);\n for (;;) {\n dsb::comm::Send(control, msg);\n dsb::comm::Receive(control, msg);\n slave.RequestReply(msg);\n }\n} catch (const Shutdown& e) {\n std::cerr << \"Shutdown: \" << e.what() << std::endl;\n}\n}\n\n\n\/\/ =============================================================================\n\/\/ Slave class function implementations\n\/\/ =============================================================================\n\nSlave::Slave(\n uint16_t id,\n zmq::socket_t dataSub_,\n zmq::socket_t dataPub_,\n std::unique_ptr slaveInstance_,\n uint16_t otherSlaveId)\n : m_dataSub(std::move(dataSub_)),\n m_dataPub(std::move(dataPub_)),\n m_slaveInstance(std::move(slaveInstance_)),\n m_currentTime(std::numeric_limits::signaling_NaN()),\n m_lastStepSize(std::numeric_limits::signaling_NaN())\n{\n\n \/\/ -------------------------------------------------------------------------\n \/\/ Temporary\n\n \/\/ Build a header to use for subscribing to the other slave's output.\n dsb::util::EncodeUint16(otherSlaveId, otherHeader);\n dsb::util::EncodeUint16(OUT_VAR_REF, otherHeader + 2);\n m_dataSub.setsockopt(ZMQ_SUBSCRIBE, otherHeader, DATA_HEADER_SIZE);\n\n \/\/ Build a header to use for our own output.\n dsb::util::EncodeUint16(id, myHeader);\n dsb::util::EncodeUint16(OUT_VAR_REF, myHeader + 2);\n \/\/ -------------------------------------------------------------------------\n}\n\n\nvoid Slave::Start(std::deque& msg)\n{\n dsb::control::CreateHelloMessage(msg, 0);\n m_stateHandler = &Slave::ConnectingHandler;\n}\n\n\nvoid Slave::RequestReply(std::deque& msg)\n{\n (this->*m_stateHandler)(msg);\n}\n\n\nvoid Slave::ConnectingHandler(std::deque& msg)\n{\n if (dsb::control::ParseProtocolVersion(msg.front()) != 0) {\n throw std::runtime_error(\"Master required unsupported protocol\");\n }\n dsb::control::CreateMessage(msg, dsbproto::control::MSG_INIT_READY);\n m_stateHandler = &Slave::InitHandler;\n}\n\n\nvoid Slave::InitHandler(std::deque& msg)\n{\n EnforceMessageType(msg, dsbproto::control::MSG_INIT_DONE);\n dsb::control::CreateMessage(msg, dsbproto::control::MSG_READY);\n m_stateHandler = &Slave::ReadyHandler;\n}\n\n\nvoid Slave::ReadyHandler(std::deque& msg)\n{\n switch (NormalMessageType(msg)) {\n case dsbproto::control::MSG_STEP: {\n if (msg.size() != 2) {\n throw dsb::error::ProtocolViolationException(\n \"Wrong number of frames in STEP message\");\n }\n dsbproto::control::StepData stepData;\n dsb::protobuf::ParseFromFrame(msg[1], stepData);\n Step(stepData);\n dsb::control::CreateMessage(msg, dsbproto::control::MSG_STEP_OK);\n m_stateHandler = &Slave::PublishedHandler;\n break; }\n default:\n throw dsb::error::ProtocolViolationException(\n \"Invalid reply from master\");\n }\n}\n\n\nvoid Slave::PublishedHandler(std::deque& msg)\n{\n EnforceMessageType(msg, dsbproto::control::MSG_RECV_VARS);\n\n \/\/ Receive message from other and store the body in inVar.\n const auto allowedTimeError = m_lastStepSize * 1e-6;\n std::deque dataMsg;\n dsbproto::variable::TimestampedValue inVar;\n do {\n dsb::comm::Receive(m_dataSub, dataMsg);\n dsb::protobuf::ParseFromFrame(dataMsg.back(), inVar);\n assert (inVar.timestamp() < m_currentTime + allowedTimeError\n && \"Data received from the future\");\n \/\/ If the message has been queued up from a previous time\n \/\/ step, which could happen if we have joined the simulation\n \/\/ while it's in progress, discard it and retry.\n } while (inVar.timestamp() < m_currentTime - allowedTimeError);\n\n \/\/ Set our input variable.\n m_slaveInstance->SetVariable(IN_VAR_REF, inVar.value().real_value());\n\n \/\/ Send READY message and change state again.\n dsb::control::CreateMessage(msg, dsbproto::control::MSG_READY);\n m_stateHandler = &Slave::ReadyHandler;\n}\n\n\nvoid Slave::Step(const dsbproto::control::StepData& stepInfo)\n{\n \/\/ Perform time step\n m_slaveInstance->DoStep(stepInfo.timepoint(), stepInfo.stepsize());\n \/\/ Pretend to work really hard\n boost::this_thread::sleep_for(boost::chrono::milliseconds(10));\n m_currentTime = stepInfo.timepoint() + stepInfo.stepsize();\n m_lastStepSize = stepInfo.stepsize();\n std::cout << m_currentTime << \" \" << m_slaveInstance->GetVariable(OUT_VAR_REF) << std::endl;\n\n \/\/ Get value of output variable\n dsbproto::variable::TimestampedValue outVar;\n outVar.set_timestamp(m_currentTime);\n outVar.mutable_value()->set_real_value(m_slaveInstance->GetVariable(OUT_VAR_REF));\n\n \/\/ Build data message to be published\n std::deque dataMsg;\n \/\/ Header\n dataMsg.push_back(zmq::message_t(DATA_HEADER_SIZE));\n std::copy(myHeader, myHeader+DATA_HEADER_SIZE,\n static_cast(dataMsg.back().data()));\n \/\/ Body\n dataMsg.push_back(zmq::message_t());\n dsb::protobuf::SerializeToFrame(outVar, dataMsg.back());\n \/\/ Send it\n dsb::comm::Send(m_dataPub, dataMsg);\n}\n<|endoftext|>"} {"text":"\/*\n * soundpatty.cpp\n *\n * Copyright (c) 2010 Motiejus Jakštys\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\n *\/\n\n\n#include \"soundpatty.h\"\n#include \"input.h\"\n\nvoid *SoundPatty::go_thread(void *args) {\n \/\/ This is the new function that is created in new thread\n SoundPatty *inst = (SoundPatty*) args;\n\n LOG_DEBUG(\"Launching SoundPatty::go\");\n if (inst->go() == 2) {\n LOG_WARN(\"Timed out\");\n }\n LOG_DEBUG(\"Terminating SoundPatty instance\");\n \/\/ Process is over - either timeout or catch. Callbacks launched already.\n \/\/ Must terminate SoundPatty and Input instances\n delete inst;\n LOG_DEBUG(\"SoundPatty and Input instances deleted. Exiting thread\");\n return NULL;\n}\n\nvoid SoundPatty::dump_out(const treshold_t args) { \/\/ STATIC\n printf (\"%d;%.6f;%.6f\\n\", args.r, args.place, args.sec);\n fflush(stdout);\n}\n\n\nSoundPatty::SoundPatty(action_t action, Input *input, all_cfg_t *all_cfg,\n void *params_uni) {\n _action = action;\n _input = input;\n if (action == ACTION_DUMP) {\n \/\/sp_params_dump_t *params = (sp_params_dump_t*)params_uni;\n } else if (action == ACTION_CAPTURE) {\n sp_params_capture_t *params = (sp_params_capture_t*)params_uni;\n exit_after_capture = params->exit_after_capture;\n vals = params->vals;\n _callback = params->fn;\n }\n\n findings = deque();\n\tcfg = all_cfg->first;\n\tvolume = all_cfg->second;\n gSCounter = gMCounter = 0;\n\n _input->WAVE = _input->SAMPLE_RATE * cfg[\"minwavelen\"];\n _input->CHUNKSIZE = cfg[\"chunklen\"] * _input->SAMPLE_RATE;\n}\n\nSoundPatty::~SoundPatty() {\n delete _input;\n}\n\n\nall_cfg_t SoundPatty::read_cfg (const char * filename) {\n\tmap cfg;\n\tvector volume;\n ifstream file;\n file.exceptions(ifstream::failbit | ifstream::badbit);\n try {\n file.open(filename);\n } catch (ifstream::failure e) {\n LOG_FATAL(\"Could not read config file %s\", filename);\n exit(1);\n }\n\n string line;\n int x;\n while (! file.eof() ) {\n getline(file, line);\n x = line.find(\":\");\n if (x == -1) break; \/\/ Last line, exit\n istringstream i(line.substr(x+2));\n double tmp; i >> tmp;\n cfg[line.substr(0,x)] = tmp;\n }\n LOG_DEBUG(\"Read %d config values from %s\", cfg.size(), filename);\n\n \/* Licensed code. *\/\n cfg[\"sampletimeout\"] = 120.1;\n\n sVolumes tmp;\n tmp.head = tmp.tail = tmp.max = tmp.min = tmp.proc = 0;\n volume.assign(cfg.size(), tmp); \/\/ Assign a bit more then nescesarry\n int max_index = -1; \/\/ Number of different tresholds\n for(map::iterator C = cfg.begin(); C != cfg.end(); C++) {\n \/\/ Failed to use boost::regex :(\n if (C->first.find(\"treshold\") == 0) {\n istringstream tmp(C->first.substr(8));\n int i; tmp >> i;\n max_index = max(max_index, i);\n if (C->first.find(\"_min\") != string::npos) {\n volume[i].min = C->second;\n } else {\n volume[i].max = C->second;\n }\n }\n }\n if (max_index == -1) {\n LOG_FATAL(\"ERROR. Length of vol array: 0\\n\");\n }\n volume.assign(volume.begin(), volume.begin()+max_index+1);\n\treturn all_cfg_t(cfg, volume);\n}\n\n\nint SoundPatty::setInput(Input * input) {\n _input = input;\n return 0;\n}\n\n\nint SoundPatty::go() {\n\n string which_timeout (_action == ACTION_CAPTURE ?\n \"catchtimeout\" : \"sampletimeout\");\n buffer_t buf;\n\n while (_input->giveInput(&buf) != 0) { \/\/ Have pointer to data\n LOG_TRACE(\"Got buffer, length: %d, seconds processed: %f\",\n buf.nframes, sec_processed());\n treshold_t ret;\n\n for (unsigned int i = 0; i < buf.nframes; gSCounter++, i++) {\n sample_t cur = buf.buf[i]<0?-buf.buf[i]:buf.buf[i];\n \/\/printf(\"Cur: %f, second: %f, frame: %d\\n\",\n \/\/ cur, sec_processed(), i);\n \/\/ Special handling of last bit, because we might still be in a\n \/\/ wave which we do not want to miss\n bool last_sample = _input->reading_over && i == buf.nframes - 1;\n if (search_patterns(cur, &ret, last_sample))\n {\n LOG_TRACE(\"Found pattern (%-.3f) %-.3f; %.6f; %.6f\",\n ret.b, ret.r, ret.place, ret.sec);\n\n if (_action == ACTION_DUMP)\n SoundPatty::dump_out(ret);\n else if (_action == ACTION_AGGREGATE)\n this->findings.push_back(ret);\n else if (_action == ACTION_CAPTURE)\n if (SoundPatty::do_checking(ret))\n \/\/ Caught pattern\n if (exit_after_capture)\n return 1;\n }\n }\n if (buf.delete_me) {\n delete(buf.buf);\n }\n\n if (sec_processed() > cfg[which_timeout]) {\n \/\/ Timeout. Return 2\n return 2;\n }\n }\n return 0;\n}\n\ndouble SoundPatty::sec_processed() {\n return (double)gSCounter\/_input->SAMPLE_RATE;\n}\n\nvals_t SoundPatty::read_captured_values(const char * filename) {\n vals_t vals;\n\n ifstream file;\n file.open(filename);\n string line;\n for (int i = 0; !file.eof(); i++) {\n getline(file, line);\n if (line.size() == 0) break;\n vector numbers = explode(\";\", line);\n istringstream num(numbers[0]);\n istringstream place(numbers[1]);\n istringstream range(numbers[2]);\n\n double tmp2;\n pair,valsitm_t > tmp;\n num >> tmp2; tmp.first.first = tmp2; \/\/ Index in volume\n range >> tmp2; tmp.first.second = Range(tmp2);\n place >> tmp.second.place; \/\/ Place in the stream\n tmp.second.c = i; \/\/ Counter in the stream\n vals.insert(tmp);\n }\n return vals;\n}\n\n\n\/*\n * last means that we are processing the last bit of the file\n *\/\nint SoundPatty::search_patterns (sample_t cur, treshold_t * ret, bool last) {\n int v = 0; \/\/ Counter for volume\n for (vector::iterator V = volume.begin(); V != volume.end(); V++, v++) {\n if (!last && V->min <= cur && cur <= V->max) {\n \/\/ ------------------------------------------------------------\n \/\/ If it's first item in this wave (proc = processing started)\n \/\/\n if (!V->proc) {\n V->tail = gSCounter;\n V->proc = true;\n }\n \/\/ ------------------------------------------------------------\n \/\/ Here we are just normally in the wave.\n \/\/\n V->head = gSCounter;\n } else { \/\/ We are not in the wave\n if (last || (V->proc &&\n (V->min < 0.001 || gSCounter - V->head > _input->WAVE)))\n {\n\n \/\/------------------------------------------------------------\n \/\/ This wave is over\n \/\/\n \/\/ Stop processing for both cases: found and not\n V->proc = false;\n\n if (gSCounter - V->tail >= _input->CHUNKSIZE) {\n \/\/ ---------------------------------------------------------\n \/\/ The previous chunk is big enough to be noticed\n \/\/\n ret->r = v;\n ret->place = (double)V->tail\/_input->SAMPLE_RATE;\n ret->sec = (double)(V->head - V->tail)\/_input->SAMPLE_RATE;\n ret->b = gMCounter++;\n return 1;\n } \n \/\/ ------------------------------------------------------------\n \/\/ Else it is too small, but we don't want to do anything\n \/\/ So therefore we just say that wave processing is over\n \/\/\n }\n }\n }\n return 0;\n}\n\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ This gets called every time there is a treshold found.\n\/\/ Work array is global\n\/\/\n\/\/ int r - id of treshold found (in config.cfg: treshold_(\\d)_(min|max))\n\/\/ double place - place of sample from the stream start (sec)\n\/\/ double sec - length of a found sample (sec)\n\/\/ int b - index (overall) of sample found\n\/\/\nint SoundPatty::do_checking(const treshold_t tr) {\n \/\/pair pa = vals.equal_range(pair(r,sec));\n \/\/ Manually searching for matching values because with that pairs equal_range doesnt work\n \/\/ Iterate through pa\n\n unsigned long b = tr.b; vals_t fina; \/\/ FoundInA\n Range demorange(tr.sec);\n pair sample(tr.r, demorange);\n for (vals_t::iterator it1 = vals.begin(); it1 != vals.end(); it1++) {\n if (it1->first == sample) {\n fina.insert(*it1);\n }\n }\n \/\/------------------------------------------------------------\n \/\/ We put a indexes here that we use for continued threads\n \/\/ (we don't want to create a new \"thread\" with already\n \/\/ used length of a sample)\n \/\/\n set used_a; \n\n \/\/------------------------------------------------------------\n \/\/ Iterating through samples that match the found sample\n \/\/\n for (vals_t::iterator in_a = fina.begin(); in_a != fina.end(); in_a++)\n {\n LOG_TRACE(\"%.6f (%d) matches %.6f (%d)\",tr.sec,in_a->first.first,in_a->first.second.tm,in_a->second.c);\n int a = in_a->second.c;\n \/\/------------------------------------------------------------\n \/\/ Check if it exists in our work array\n \/\/\n int i = 0; \/\/ Work list counter\n for (list::iterator w = work.begin(); w != work.end(); i++) {\n if (b - w->b > round(cfg[\"maxsteps\"])) {\n LOG_TRACE(\"Work item %d removed, no match for a long time\", i);\n work.erase(w); w = work.begin(); continue;\n }\n if (b == w->b || a - w->a > round(cfg[\"maxsteps\"]) || w->a >= a) { w++; continue; }\n \/\/ ------------------------------------------------------------\n \/\/ We fit the \"region\" here. We either finished,\n \/\/ or just increasing len\n \/\/\n w->a = a; w->b = b;\n w->trace.push_back(pair(a,b));\n LOG_TRACE(\"Work item %d expanded to %d items\", i, w->len+1);\n if (++(w->len) < round(cfg[\"matchme\"])) { \/\/ Proceeding with the \"thread\"\n used_a.insert(a);\n } else { \/\/ This means the treshold is reached\n \/\/ This kind of function is called when the pattern is recognized\n _callback (_input->name, tr.place + tr.sec);\n return 1;\n }\n w++;\n \/\/ End of work iteration array\n }\n if (used_a.find(a) == used_a.end()) {\n work.push_back(workitm(a,b));\n }\n }\n return 0;\n}\n\n\nvector explode(const string &delimiter, const string &str) { \/\/ Found somewhere on NET\n vector arr;\n int strleng = str.length();\n int delleng = delimiter.length();\n if (delleng == 0)\n return arr; \/\/no change\n int i = 0, k = 0;\n while (i < strleng) {\n int j = 0;\n while (i+j < strleng && j < delleng && str[i+j] == delimiter[j])\n j++;\n if (j == delleng) {\n arr.push_back(str.substr(k, i-k));\n i += delleng;\n k = i;\n } else {\n i++;\n }\n }\n arr.push_back(str.substr(k, i-k));\n return arr;\n}\n\n\nworkitm::workitm(const int a, const unsigned long b) {\n this->a = a; this->b = b;\n len = 0;\n trace.push_back(pair(a,b));\n}\nRemove corporate code\/*\n * soundpatty.cpp\n *\n * Copyright (c) 2010 Motiejus Jakštys\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\n *\/\n\n\n#include \"soundpatty.h\"\n#include \"input.h\"\n\nvoid *SoundPatty::go_thread(void *args) {\n \/\/ This is the new function that is created in new thread\n SoundPatty *inst = (SoundPatty*) args;\n\n LOG_DEBUG(\"Launching SoundPatty::go\");\n if (inst->go() == 2) {\n LOG_WARN(\"Timed out\");\n }\n LOG_DEBUG(\"Terminating SoundPatty instance\");\n \/\/ Process is over - either timeout or catch. Callbacks launched already.\n \/\/ Must terminate SoundPatty and Input instances\n delete inst;\n LOG_DEBUG(\"SoundPatty and Input instances deleted. Exiting thread\");\n return NULL;\n}\n\nvoid SoundPatty::dump_out(const treshold_t args) { \/\/ STATIC\n printf (\"%d;%.6f;%.6f\\n\", args.r, args.place, args.sec);\n fflush(stdout);\n}\n\n\nSoundPatty::SoundPatty(action_t action, Input *input, all_cfg_t *all_cfg,\n void *params_uni) {\n _action = action;\n _input = input;\n if (action == ACTION_DUMP) {\n \/\/sp_params_dump_t *params = (sp_params_dump_t*)params_uni;\n } else if (action == ACTION_CAPTURE) {\n sp_params_capture_t *params = (sp_params_capture_t*)params_uni;\n exit_after_capture = params->exit_after_capture;\n vals = params->vals;\n _callback = params->fn;\n }\n\n findings = deque();\n\tcfg = all_cfg->first;\n\tvolume = all_cfg->second;\n gSCounter = gMCounter = 0;\n\n _input->WAVE = _input->SAMPLE_RATE * cfg[\"minwavelen\"];\n _input->CHUNKSIZE = cfg[\"chunklen\"] * _input->SAMPLE_RATE;\n}\n\nSoundPatty::~SoundPatty() {\n delete _input;\n}\n\n\nall_cfg_t SoundPatty::read_cfg (const char * filename) {\n\tmap cfg;\n\tvector volume;\n ifstream file;\n file.exceptions(ifstream::failbit | ifstream::badbit);\n try {\n file.open(filename);\n } catch (ifstream::failure e) {\n LOG_FATAL(\"Could not read config file %s\", filename);\n exit(1);\n }\n\n string line;\n int x;\n while (! file.eof() ) {\n getline(file, line);\n x = line.find(\":\");\n if (x == -1) break; \/\/ Last line, exit\n istringstream i(line.substr(x+2));\n double tmp; i >> tmp;\n cfg[line.substr(0,x)] = tmp;\n }\n LOG_DEBUG(\"Read %d config values from %s\", cfg.size(), filename);\n\n sVolumes tmp;\n tmp.head = tmp.tail = tmp.max = tmp.min = tmp.proc = 0;\n volume.assign(cfg.size(), tmp); \/\/ Assign a bit more then nescesarry\n int max_index = -1; \/\/ Number of different tresholds\n for(map::iterator C = cfg.begin(); C != cfg.end(); C++) {\n \/\/ Failed to use boost::regex :(\n if (C->first.find(\"treshold\") == 0) {\n istringstream tmp(C->first.substr(8));\n int i; tmp >> i;\n max_index = max(max_index, i);\n if (C->first.find(\"_min\") != string::npos) {\n volume[i].min = C->second;\n } else {\n volume[i].max = C->second;\n }\n }\n }\n if (max_index == -1) {\n LOG_FATAL(\"ERROR. Length of vol array: 0\\n\");\n }\n volume.assign(volume.begin(), volume.begin()+max_index+1);\n\treturn all_cfg_t(cfg, volume);\n}\n\n\nint SoundPatty::setInput(Input * input) {\n _input = input;\n return 0;\n}\n\n\nint SoundPatty::go() {\n\n string which_timeout (_action == ACTION_CAPTURE ?\n \"catchtimeout\" : \"sampletimeout\");\n buffer_t buf;\n\n while (_input->giveInput(&buf) != 0) { \/\/ Have pointer to data\n LOG_TRACE(\"Got buffer, length: %d, seconds processed: %f\",\n buf.nframes, sec_processed());\n treshold_t ret;\n\n for (unsigned int i = 0; i < buf.nframes; gSCounter++, i++) {\n sample_t cur = buf.buf[i]<0?-buf.buf[i]:buf.buf[i];\n \/\/printf(\"Cur: %f, second: %f, frame: %d\\n\",\n \/\/ cur, sec_processed(), i);\n \/\/ Special handling of last bit, because we might still be in a\n \/\/ wave which we do not want to miss\n bool last_sample = _input->reading_over && i == buf.nframes - 1;\n if (search_patterns(cur, &ret, last_sample))\n {\n LOG_TRACE(\"Found pattern (%-.3f) %-.3f; %.6f; %.6f\",\n ret.b, ret.r, ret.place, ret.sec);\n\n if (_action == ACTION_DUMP)\n SoundPatty::dump_out(ret);\n else if (_action == ACTION_AGGREGATE)\n this->findings.push_back(ret);\n else if (_action == ACTION_CAPTURE)\n if (SoundPatty::do_checking(ret))\n \/\/ Caught pattern\n if (exit_after_capture)\n return 1;\n }\n }\n if (buf.delete_me) {\n delete(buf.buf);\n }\n\n if (sec_processed() > cfg[which_timeout]) {\n \/\/ Timeout. Return 2\n return 2;\n }\n }\n return 0;\n}\n\ndouble SoundPatty::sec_processed() {\n return (double)gSCounter\/_input->SAMPLE_RATE;\n}\n\nvals_t SoundPatty::read_captured_values(const char * filename) {\n vals_t vals;\n\n ifstream file;\n file.open(filename);\n string line;\n for (int i = 0; !file.eof(); i++) {\n getline(file, line);\n if (line.size() == 0) break;\n vector numbers = explode(\";\", line);\n istringstream num(numbers[0]);\n istringstream place(numbers[1]);\n istringstream range(numbers[2]);\n\n double tmp2;\n pair,valsitm_t > tmp;\n num >> tmp2; tmp.first.first = tmp2; \/\/ Index in volume\n range >> tmp2; tmp.first.second = Range(tmp2);\n place >> tmp.second.place; \/\/ Place in the stream\n tmp.second.c = i; \/\/ Counter in the stream\n vals.insert(tmp);\n }\n return vals;\n}\n\n\n\/*\n * last means that we are processing the last bit of the file\n *\/\nint SoundPatty::search_patterns (sample_t cur, treshold_t * ret, bool last) {\n int v = 0; \/\/ Counter for volume\n for (vector::iterator V = volume.begin(); V != volume.end(); V++, v++) {\n if (!last && V->min <= cur && cur <= V->max) {\n \/\/ ------------------------------------------------------------\n \/\/ If it's first item in this wave (proc = processing started)\n \/\/\n if (!V->proc) {\n V->tail = gSCounter;\n V->proc = true;\n }\n \/\/ ------------------------------------------------------------\n \/\/ Here we are just normally in the wave.\n \/\/\n V->head = gSCounter;\n } else { \/\/ We are not in the wave\n if (last || (V->proc &&\n (V->min < 0.001 || gSCounter - V->head > _input->WAVE)))\n {\n\n \/\/------------------------------------------------------------\n \/\/ This wave is over\n \/\/\n \/\/ Stop processing for both cases: found and not\n V->proc = false;\n\n if (gSCounter - V->tail >= _input->CHUNKSIZE) {\n \/\/ ---------------------------------------------------------\n \/\/ The previous chunk is big enough to be noticed\n \/\/\n ret->r = v;\n ret->place = (double)V->tail\/_input->SAMPLE_RATE;\n ret->sec = (double)(V->head - V->tail)\/_input->SAMPLE_RATE;\n ret->b = gMCounter++;\n return 1;\n } \n \/\/ ------------------------------------------------------------\n \/\/ Else it is too small, but we don't want to do anything\n \/\/ So therefore we just say that wave processing is over\n \/\/\n }\n }\n }\n return 0;\n}\n\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ This gets called every time there is a treshold found.\n\/\/ Work array is global\n\/\/\n\/\/ int r - id of treshold found (in config.cfg: treshold_(\\d)_(min|max))\n\/\/ double place - place of sample from the stream start (sec)\n\/\/ double sec - length of a found sample (sec)\n\/\/ int b - index (overall) of sample found\n\/\/\nint SoundPatty::do_checking(const treshold_t tr) {\n \/\/pair pa = vals.equal_range(pair(r,sec));\n \/\/ Manually searching for matching values because with that pairs equal_range doesnt work\n \/\/ Iterate through pa\n\n unsigned long b = tr.b; vals_t fina; \/\/ FoundInA\n Range demorange(tr.sec);\n pair sample(tr.r, demorange);\n for (vals_t::iterator it1 = vals.begin(); it1 != vals.end(); it1++) {\n if (it1->first == sample) {\n fina.insert(*it1);\n }\n }\n \/\/------------------------------------------------------------\n \/\/ We put a indexes here that we use for continued threads\n \/\/ (we don't want to create a new \"thread\" with already\n \/\/ used length of a sample)\n \/\/\n set used_a; \n\n \/\/------------------------------------------------------------\n \/\/ Iterating through samples that match the found sample\n \/\/\n for (vals_t::iterator in_a = fina.begin(); in_a != fina.end(); in_a++)\n {\n LOG_TRACE(\"%.6f (%d) matches %.6f (%d)\",tr.sec,in_a->first.first,in_a->first.second.tm,in_a->second.c);\n int a = in_a->second.c;\n \/\/------------------------------------------------------------\n \/\/ Check if it exists in our work array\n \/\/\n int i = 0; \/\/ Work list counter\n for (list::iterator w = work.begin(); w != work.end(); i++) {\n if (b - w->b > round(cfg[\"maxsteps\"])) {\n LOG_TRACE(\"Work item %d removed, no match for a long time\", i);\n work.erase(w); w = work.begin(); continue;\n }\n if (b == w->b || a - w->a > round(cfg[\"maxsteps\"]) || w->a >= a) { w++; continue; }\n \/\/ ------------------------------------------------------------\n \/\/ We fit the \"region\" here. We either finished,\n \/\/ or just increasing len\n \/\/\n w->a = a; w->b = b;\n w->trace.push_back(pair(a,b));\n LOG_TRACE(\"Work item %d expanded to %d items\", i, w->len+1);\n if (++(w->len) < round(cfg[\"matchme\"])) { \/\/ Proceeding with the \"thread\"\n used_a.insert(a);\n } else { \/\/ This means the treshold is reached\n \/\/ This kind of function is called when the pattern is recognized\n _callback (_input->name, tr.place + tr.sec);\n return 1;\n }\n w++;\n \/\/ End of work iteration array\n }\n if (used_a.find(a) == used_a.end()) {\n work.push_back(workitm(a,b));\n }\n }\n return 0;\n}\n\n\nvector explode(const string &delimiter, const string &str) { \/\/ Found somewhere on NET\n vector arr;\n int strleng = str.length();\n int delleng = delimiter.length();\n if (delleng == 0)\n return arr; \/\/no change\n int i = 0, k = 0;\n while (i < strleng) {\n int j = 0;\n while (i+j < strleng && j < delleng && str[i+j] == delimiter[j])\n j++;\n if (j == delleng) {\n arr.push_back(str.substr(k, i-k));\n i += delleng;\n k = i;\n } else {\n i++;\n }\n }\n arr.push_back(str.substr(k, i-k));\n return arr;\n}\n\n\nworkitm::workitm(const int a, const unsigned long b) {\n this->a = a; this->b = b;\n len = 0;\n trace.push_back(pair(a,b));\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2016 Fixstars Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp :\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \n\n#include \n\n#include \"internal.h\"\n#include \"sgm.hpp\"\n\nnamespace sgm {\n\tstatic bool is_cuda_input(EXECUTE_INOUT type) { return (int)type & 0x1; }\n\tstatic bool is_cuda_output(EXECUTE_INOUT type) { return (int)type & 0x2; }\n\n\tclass SemiGlobalMatchingBase {\n\tpublic:\n\t\tusing output_type = uint8_t;\n\t\tvirtual void execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R, \n\t\t\tsize_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) = 0;\n\t};\n\n\tclass SemiGlobalMatching_8_64 : public SemiGlobalMatchingBase {\n\tpublic:\n\t\tvoid execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,\n\t\t\tsize_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) override\n\t\t{\n\t\t\tsgm_engine_.execute(dst_L, dst_R, (const uint8_t*)src_L, (const uint8_t*)src_R, w, h, P1, P2, uniqueness);\n\t\t}\n\tprivate:\n\t\tSemiGlobalMatching sgm_engine_;\n\t};\n\n\tclass SemiGlobalMatching_8_128 : public SemiGlobalMatchingBase {\n\tpublic:\n\t\tvoid execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,\n\t\t\tsize_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) override\n\t\t{\n\t\t\tsgm_engine_.execute(dst_L, dst_R, (const uint8_t*)src_L, (const uint8_t*)src_R, w, h, P1, P2, uniqueness);\n\t\t}\n\tprivate:\n\t\tSemiGlobalMatching sgm_engine_;\n\t};\n\n\tclass SemiGlobalMatching_16_64 : public SemiGlobalMatchingBase {\n\tpublic:\n\t\tvoid execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,\n\t\t\tsize_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) override\n\t\t{\n\t\t\tsgm_engine_.execute(dst_L, dst_R, (const uint16_t*)src_L, (const uint16_t*)src_R, w, h, P1, P2, uniqueness);\n\t\t}\n\tprivate:\n\t\tSemiGlobalMatching sgm_engine_;\n\t};\n\n\tclass SemiGlobalMatching_16_128 : public SemiGlobalMatchingBase {\n\tpublic:\n\t\tvoid execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,\n\t\t\tsize_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) override\n\t\t{\n\t\t\tsgm_engine_.execute(dst_L, dst_R, (const uint16_t*)src_L, (const uint16_t*)src_R, w, h, P1, P2, uniqueness);\n\t\t}\n\tprivate:\n\t\tSemiGlobalMatching sgm_engine_;\n\t};\n\n\tstruct CudaStereoSGMResources {\n\t\tvoid* d_src_left;\n\t\tvoid* d_src_right;\n\t\tvoid* d_left;\n\t\tvoid* d_right;\n\t\tvoid* d_scost;\n\t\tvoid* d_matching_cost;\n\t\tvoid* d_left_disp;\n\t\tvoid* d_right_disp;\n\n\t\tvoid* d_tmp_left_disp;\n\t\tvoid* d_tmp_right_disp;\n\n\t\tcudaStream_t cuda_streams[8];\n\n\t\tuint16_t* h_output_16bit_buffer;\n\n\t\tSemiGlobalMatchingBase* sgm_engine;\n\n\t\tCudaStereoSGMResources(int width_, int height_, int disparity_size_, int input_depth_bits_, int output_depth_bits_, EXECUTE_INOUT inout_type_) {\n\n\t\t\tif (input_depth_bits_ == 8 && disparity_size_ == 64)\n\t\t\t\tsgm_engine = new SemiGlobalMatching_8_64();\n\t\t\telse if (input_depth_bits_ == 8 && disparity_size_ == 128)\n\t\t\t\tsgm_engine = new SemiGlobalMatching_8_128();\n\t\t\telse if (input_depth_bits_ == 16 && disparity_size_ == 64)\n\t\t\t\tsgm_engine = new SemiGlobalMatching_16_64();\n\t\t\telse if (input_depth_bits_ == 16 && disparity_size_ == 128)\n\t\t\t\tsgm_engine = new SemiGlobalMatching_16_128();\n\t\t\telse\n\t\t\t\tabort();\n\n\t\t\tif (is_cuda_input(inout_type_)) {\n\t\t\t\tthis->d_src_left = NULL;\n\t\t\t\tthis->d_src_right = NULL;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tCudaSafeCall(cudaMalloc(&this->d_src_left, input_depth_bits_ \/ 8 * width_ * height_));\n\t\t\t\tCudaSafeCall(cudaMalloc(&this->d_src_right, input_depth_bits_ \/ 8 * width_ * height_));\n\t\t\t}\n\t\t\t\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_left, sizeof(uint64_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_right, sizeof(uint64_t) * width_ * height_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_matching_cost, sizeof(uint8_t) * width_ * height_ * disparity_size_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_scost, sizeof(uint16_t) * width_ * height_ * disparity_size_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_left_disp, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_right_disp, sizeof(uint16_t) * width_ * height_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_tmp_left_disp, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_tmp_right_disp, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMemset(this->d_tmp_left_disp, 0, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMemset(this->d_tmp_right_disp, 0, sizeof(uint16_t) * width_ * height_));\n\n\t\t\tfor (int i = 0; i < 8; i++) {\n\t\t\t\tCudaSafeCall(cudaStreamCreate(&this->cuda_streams[i]));\n\t\t\t}\n\n\t\t\t\/\/ create temporary buffer when dst type is 8bit host pointer\n\t\t\tif (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\t\tthis->h_output_16bit_buffer = (uint16_t*)malloc(sizeof(uint16_t) * width_ * height_);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis->h_output_16bit_buffer = NULL;\n\t\t\t}\n\t\t}\n\n\t\t~CudaStereoSGMResources() {\n\t\t\tCudaSafeCall(cudaFree(this->d_src_left));\n\t\t\tCudaSafeCall(cudaFree(this->d_src_right));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_left));\n\t\t\tCudaSafeCall(cudaFree(this->d_right));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_matching_cost));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_scost));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_left_disp));\n\t\t\tCudaSafeCall(cudaFree(this->d_right_disp));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_tmp_left_disp));\n\t\t\tCudaSafeCall(cudaFree(this->d_tmp_right_disp));\n\n\t\t\tfor (int i = 0; i < 8; i++) {\n\t\t\t\tCudaSafeCall(cudaStreamDestroy(this->cuda_streams[i]));\n\t\t\t}\n\n\t\t\tfree(h_output_16bit_buffer);\n\n\t\t\tdelete sgm_engine;\n\t\t}\n\t};\n\n\tStereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits, \n\t\tEXECUTE_INOUT inout_type, const Parameters& param) :\n\t\twidth_(width),\n\t\theight_(height),\n\t\tdisparity_size_(disparity_size),\n\t\tinput_depth_bits_(input_depth_bits),\n\t\toutput_depth_bits_(output_depth_bits),\n\t\tinout_type_(inout_type),\n\t\tparam_(param),\n\t\tcu_res_(NULL)\n\t{\n\t\t\/\/ check values\n\t\tif (width_ % 2 != 0 || height_ % 2 != 0) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::runtime_error(\"width and height must be even\");\n\t\t}\n\t\tif (input_depth_bits_ != 8 && input_depth_bits_ != 16 && output_depth_bits_ != 8 && output_depth_bits_ != 16) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::runtime_error(\"depth bits must be 8 or 16\");\n\t\t}\n\t\tif (disparity_size_ != 64 && disparity_size_ != 128) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::runtime_error(\"disparity size must be 64 or 128\");\n\t\t}\n\n\t\tcu_res_ = new CudaStereoSGMResources(width_, height_, disparity_size_, input_depth_bits_, output_depth_bits_, inout_type_);\n\t}\n\n\tStereoSGM::~StereoSGM() {\n\t\tif (cu_res_) { delete cu_res_; }\n\t}\n\n\t\n\tvoid StereoSGM::execute(const void* left_pixels, const void* right_pixels, void** dst) {\n\n\t\tconst void *d_input_left, *d_input_right;\n\n\t\tif (is_cuda_input(inout_type_)) {\n\t\t\td_input_left = left_pixels;\n\t\t\td_input_right = right_pixels;\n\t\t}\n\t\telse {\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->d_src_left, left_pixels, input_depth_bits_ \/ 8 * width_ * height_, cudaMemcpyHostToDevice));\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->d_src_right, right_pixels, input_depth_bits_ \/ 8 * width_ * height_, cudaMemcpyHostToDevice));\n\t\t\td_input_left = cu_res_->d_src_left;\n\t\t\td_input_right = cu_res_->d_src_right;\n\t\t}\n\t\t\n\t\tcu_res_->sgm_engine->execute((uint8_t*)cu_res_->d_left_disp, (uint8_t*)cu_res_->d_right_disp,\n\t\t\td_input_left, d_input_right, width_, height_, param_.P1, param_.P2, param_.uniqueness);\n\n\t\tsgm::details::median_filter((uint8_t*)cu_res_->d_left_disp, (uint8_t*)cu_res_->d_tmp_left_disp, width_, height_);\n\t\tsgm::details::median_filter((uint8_t*)cu_res_->d_right_disp, (uint8_t*)cu_res_->d_tmp_right_disp, width_, height_);\n\t\tsgm::details::check_consistency((uint8_t*)cu_res_->d_tmp_left_disp, (uint8_t*)cu_res_->d_tmp_right_disp, d_input_left, width_, height_, input_depth_bits_);\n\n\t\t\/\/ output disparity image\n\t\tvoid* disparity_image = cu_res_->d_tmp_left_disp;\n\n\t\tif (!is_cuda_output(inout_type_) && output_depth_bits_ == 16) {\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->h_output_16bit_buffer, disparity_image, sizeof(uint8_t) * width_ * height_, cudaMemcpyDeviceToHost));\n\t\t\tfor (int i = 0; i < width_ * height_; i++) { ((uint16_t*)*dst)[i] = (uint16_t)cu_res_->h_output_16bit_buffer[i]; }\n\t\t}\n\t\telse if (is_cuda_output(inout_type_) && output_depth_bits_ == 16) {\n\t\t\tsgm::details::cast_8bit_16bit_array((const uint8_t*)disparity_image, (uint16_t*)*dst, width_ * height_);\n\t\t}\n\t\telse if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\tCudaSafeCall(cudaMemcpy(*dst, disparity_image, sizeof(uint8_t) * width_ * height_, cudaMemcpyDeviceToHost));\n\t\t}\n\t\telse if (is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\t*dst = disparity_image; \/\/ optimize! no-copy!\n\t\t}\n\t\telse {\n\t\t\tstd::cerr << \"not impl\" << std::endl;\n\t\t}\n\t}\n}\nRemove warning\/*\nCopyright 2016 Fixstars Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp :\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \n\n#include \n\n#include \"internal.h\"\n#include \"sgm.hpp\"\n\nnamespace sgm {\n\tstatic bool is_cuda_input(EXECUTE_INOUT type) { return (int)type & 0x1; }\n\tstatic bool is_cuda_output(EXECUTE_INOUT type) { return (int)type & 0x2; }\n\n\tclass SemiGlobalMatchingBase {\n\tpublic:\n\t\tusing output_type = uint8_t;\n\t\tvirtual void execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R, \n\t\t\tsize_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) = 0;\n\n\t\tvirtual ~SemiGlobalMatchingBase();\n\t};\n\n\tclass SemiGlobalMatching_8_64 : public SemiGlobalMatchingBase {\n\tpublic:\n\t\tvoid execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,\n\t\t\tsize_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) override\n\t\t{\n\t\t\tsgm_engine_.execute(dst_L, dst_R, (const uint8_t*)src_L, (const uint8_t*)src_R, w, h, P1, P2, uniqueness);\n\t\t}\n\tprivate:\n\t\tSemiGlobalMatching sgm_engine_;\n\t};\n\n\tclass SemiGlobalMatching_8_128 : public SemiGlobalMatchingBase {\n\tpublic:\n\t\tvoid execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,\n\t\t\tsize_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) override\n\t\t{\n\t\t\tsgm_engine_.execute(dst_L, dst_R, (const uint8_t*)src_L, (const uint8_t*)src_R, w, h, P1, P2, uniqueness);\n\t\t}\n\tprivate:\n\t\tSemiGlobalMatching sgm_engine_;\n\t};\n\n\tclass SemiGlobalMatching_16_64 : public SemiGlobalMatchingBase {\n\tpublic:\n\t\tvoid execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,\n\t\t\tsize_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) override\n\t\t{\n\t\t\tsgm_engine_.execute(dst_L, dst_R, (const uint16_t*)src_L, (const uint16_t*)src_R, w, h, P1, P2, uniqueness);\n\t\t}\n\tprivate:\n\t\tSemiGlobalMatching sgm_engine_;\n\t};\n\n\tclass SemiGlobalMatching_16_128 : public SemiGlobalMatchingBase {\n\tpublic:\n\t\tvoid execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,\n\t\t\tsize_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) override\n\t\t{\n\t\t\tsgm_engine_.execute(dst_L, dst_R, (const uint16_t*)src_L, (const uint16_t*)src_R, w, h, P1, P2, uniqueness);\n\t\t}\n\tprivate:\n\t\tSemiGlobalMatching sgm_engine_;\n\t};\n\n\tstruct CudaStereoSGMResources {\n\t\tvoid* d_src_left;\n\t\tvoid* d_src_right;\n\t\tvoid* d_left;\n\t\tvoid* d_right;\n\t\tvoid* d_scost;\n\t\tvoid* d_matching_cost;\n\t\tvoid* d_left_disp;\n\t\tvoid* d_right_disp;\n\n\t\tvoid* d_tmp_left_disp;\n\t\tvoid* d_tmp_right_disp;\n\n\t\tcudaStream_t cuda_streams[8];\n\n\t\tuint16_t* h_output_16bit_buffer;\n\n\t\tSemiGlobalMatchingBase* sgm_engine;\n\n\t\tCudaStereoSGMResources(int width_, int height_, int disparity_size_, int input_depth_bits_, int output_depth_bits_, EXECUTE_INOUT inout_type_) {\n\n\t\t\tif (input_depth_bits_ == 8 && disparity_size_ == 64)\n\t\t\t\tsgm_engine = new SemiGlobalMatching_8_64();\n\t\t\telse if (input_depth_bits_ == 8 && disparity_size_ == 128)\n\t\t\t\tsgm_engine = new SemiGlobalMatching_8_128();\n\t\t\telse if (input_depth_bits_ == 16 && disparity_size_ == 64)\n\t\t\t\tsgm_engine = new SemiGlobalMatching_16_64();\n\t\t\telse if (input_depth_bits_ == 16 && disparity_size_ == 128)\n\t\t\t\tsgm_engine = new SemiGlobalMatching_16_128();\n\t\t\telse\n\t\t\t\tabort();\n\n\t\t\tif (is_cuda_input(inout_type_)) {\n\t\t\t\tthis->d_src_left = NULL;\n\t\t\t\tthis->d_src_right = NULL;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tCudaSafeCall(cudaMalloc(&this->d_src_left, input_depth_bits_ \/ 8 * width_ * height_));\n\t\t\t\tCudaSafeCall(cudaMalloc(&this->d_src_right, input_depth_bits_ \/ 8 * width_ * height_));\n\t\t\t}\n\t\t\t\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_left, sizeof(uint64_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_right, sizeof(uint64_t) * width_ * height_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_matching_cost, sizeof(uint8_t) * width_ * height_ * disparity_size_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_scost, sizeof(uint16_t) * width_ * height_ * disparity_size_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_left_disp, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_right_disp, sizeof(uint16_t) * width_ * height_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_tmp_left_disp, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_tmp_right_disp, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMemset(this->d_tmp_left_disp, 0, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMemset(this->d_tmp_right_disp, 0, sizeof(uint16_t) * width_ * height_));\n\n\t\t\tfor (int i = 0; i < 8; i++) {\n\t\t\t\tCudaSafeCall(cudaStreamCreate(&this->cuda_streams[i]));\n\t\t\t}\n\n\t\t\t\/\/ create temporary buffer when dst type is 8bit host pointer\n\t\t\tif (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\t\tthis->h_output_16bit_buffer = (uint16_t*)malloc(sizeof(uint16_t) * width_ * height_);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis->h_output_16bit_buffer = NULL;\n\t\t\t}\n\t\t}\n\n\t\t~CudaStereoSGMResources() {\n\t\t\tCudaSafeCall(cudaFree(this->d_src_left));\n\t\t\tCudaSafeCall(cudaFree(this->d_src_right));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_left));\n\t\t\tCudaSafeCall(cudaFree(this->d_right));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_matching_cost));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_scost));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_left_disp));\n\t\t\tCudaSafeCall(cudaFree(this->d_right_disp));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_tmp_left_disp));\n\t\t\tCudaSafeCall(cudaFree(this->d_tmp_right_disp));\n\n\t\t\tfor (int i = 0; i < 8; i++) {\n\t\t\t\tCudaSafeCall(cudaStreamDestroy(this->cuda_streams[i]));\n\t\t\t}\n\n\t\t\tfree(h_output_16bit_buffer);\n\n\t\t\tdelete sgm_engine;\n\t\t}\n\t};\n\n\tStereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits, \n\t\tEXECUTE_INOUT inout_type, const Parameters& param) :\n\t\tcu_res_(NULL),\n\t\twidth_(width),\n\t\theight_(height),\n\t\tdisparity_size_(disparity_size),\n\t\tinput_depth_bits_(input_depth_bits),\n\t\toutput_depth_bits_(output_depth_bits),\n\t\tinout_type_(inout_type),\n\t\tparam_(param)\n\t{\n\t\t\/\/ check values\n\t\tif (width_ % 2 != 0 || height_ % 2 != 0) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::runtime_error(\"width and height must be even\");\n\t\t}\n\t\tif (input_depth_bits_ != 8 && input_depth_bits_ != 16 && output_depth_bits_ != 8 && output_depth_bits_ != 16) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::runtime_error(\"depth bits must be 8 or 16\");\n\t\t}\n\t\tif (disparity_size_ != 64 && disparity_size_ != 128) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::runtime_error(\"disparity size must be 64 or 128\");\n\t\t}\n\n\t\tcu_res_ = new CudaStereoSGMResources(width_, height_, disparity_size_, input_depth_bits_, output_depth_bits_, inout_type_);\n\t}\n\n\tStereoSGM::~StereoSGM() {\n\t\tif (cu_res_) { delete cu_res_; }\n\t}\n\n\t\n\tvoid StereoSGM::execute(const void* left_pixels, const void* right_pixels, void** dst) {\n\n\t\tconst void *d_input_left, *d_input_right;\n\n\t\tif (is_cuda_input(inout_type_)) {\n\t\t\td_input_left = left_pixels;\n\t\t\td_input_right = right_pixels;\n\t\t}\n\t\telse {\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->d_src_left, left_pixels, input_depth_bits_ \/ 8 * width_ * height_, cudaMemcpyHostToDevice));\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->d_src_right, right_pixels, input_depth_bits_ \/ 8 * width_ * height_, cudaMemcpyHostToDevice));\n\t\t\td_input_left = cu_res_->d_src_left;\n\t\t\td_input_right = cu_res_->d_src_right;\n\t\t}\n\t\t\n\t\tcu_res_->sgm_engine->execute((uint8_t*)cu_res_->d_left_disp, (uint8_t*)cu_res_->d_right_disp,\n\t\t\td_input_left, d_input_right, width_, height_, param_.P1, param_.P2, param_.uniqueness);\n\n\t\tsgm::details::median_filter((uint8_t*)cu_res_->d_left_disp, (uint8_t*)cu_res_->d_tmp_left_disp, width_, height_);\n\t\tsgm::details::median_filter((uint8_t*)cu_res_->d_right_disp, (uint8_t*)cu_res_->d_tmp_right_disp, width_, height_);\n\t\tsgm::details::check_consistency((uint8_t*)cu_res_->d_tmp_left_disp, (uint8_t*)cu_res_->d_tmp_right_disp, d_input_left, width_, height_, input_depth_bits_);\n\n\t\t\/\/ output disparity image\n\t\tvoid* disparity_image = cu_res_->d_tmp_left_disp;\n\n\t\tif (!is_cuda_output(inout_type_) && output_depth_bits_ == 16) {\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->h_output_16bit_buffer, disparity_image, sizeof(uint8_t) * width_ * height_, cudaMemcpyDeviceToHost));\n\t\t\tfor (int i = 0; i < width_ * height_; i++) { ((uint16_t*)*dst)[i] = (uint16_t)cu_res_->h_output_16bit_buffer[i]; }\n\t\t}\n\t\telse if (is_cuda_output(inout_type_) && output_depth_bits_ == 16) {\n\t\t\tsgm::details::cast_8bit_16bit_array((const uint8_t*)disparity_image, (uint16_t*)*dst, width_ * height_);\n\t\t}\n\t\telse if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\tCudaSafeCall(cudaMemcpy(*dst, disparity_image, sizeof(uint8_t) * width_ * height_, cudaMemcpyDeviceToHost));\n\t\t}\n\t\telse if (is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\t*dst = disparity_image; \/\/ optimize! no-copy!\n\t\t}\n\t\telse {\n\t\t\tstd::cerr << \"not impl\" << std::endl;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2018 WebAssembly Community Group participants\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"gtest\/gtest.h\"\n\n#include \n\n#include \"src\/binary-reader.h\"\n#include \"src\/binary-reader-interp.h\"\n#include \"src\/cast.h\"\n#include \"src\/error-handler.h\"\n#include \"src\/interp.h\"\n#include \"src\/make-unique.h\"\n\nusing namespace wabt;\n\nnamespace {\n\ninterp::Result TrapCallback(const interp::HostFunc* func,\n const interp::FuncSignature* sig,\n const interp::TypedValues& args,\n interp::TypedValues& results) {\n return interp::Result::TrapHostTrapped;\n}\n\nclass HostTrapTest : public ::testing::Test {\n protected:\n virtual void SetUp() {\n interp::HostModule* host_module = env_.AppendHostModule(\"host\");\n host_module->AppendFuncExport(\"a\", {{}, {}}, TrapCallback);\n executor_ = MakeUnique(&env_);\n }\n\n virtual void TearDown() {}\n\n interp::ExecResult LoadModuleAndRunStartFunction(\n const std::vector& data) {\n ErrorHandlerFile error_handler(Location::Type::Binary);\n interp::DefinedModule* module = nullptr;\n ReadBinaryOptions options;\n Result result = ReadBinaryInterp(&env_, data.data(), data.size(), options,\n &error_handler, &module);\n EXPECT_EQ(Result::Ok, result);\n\n if (result == Result::Ok) {\n return executor_->RunStartFunction(module);\n } else {\n return {};\n }\n }\n\n interp::Environment env_;\n std::unique_ptr executor_;\n};\n\n} \/\/ end of anonymous namespace\n\nTEST_F(HostTrapTest, Call) {\n \/\/ (import \"host\" \"a\" (func $0))\n \/\/ (func $1 call $0)\n \/\/ (start $1)\n std::vector data = {\n 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x04, 0x01,\n 0x60, 0x00, 0x00, 0x02, 0x0a, 0x01, 0x04, 0x68, 0x6f, 0x73, 0x74,\n 0x01, 0x61, 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, 0x08, 0x01, 0x01,\n 0x0a, 0x06, 0x01, 0x04, 0x00, 0x10, 0x00, 0x0b,\n };\n ASSERT_EQ(interp::Result::TrapHostTrapped,\n LoadModuleAndRunStartFunction(data).result);\n}\n\nTEST_F(HostTrapTest, CallIndirect) {\n \/\/ (import \"host\" \"a\" (func $0))\n \/\/ (table anyfunc (elem $0))\n \/\/ (func $1 i32.const 0 call_indirect)\n \/\/ (start $1)\n std::vector data = {\n 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x04, 0x01, 0x60,\n 0x00, 0x00, 0x02, 0x0a, 0x01, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x01, 0x61,\n 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, 0x04, 0x05, 0x01, 0x70, 0x01, 0x01,\n 0x01, 0x08, 0x01, 0x01, 0x09, 0x07, 0x01, 0x00, 0x41, 0x00, 0x0b, 0x01,\n 0x00, 0x0a, 0x09, 0x01, 0x07, 0x00, 0x41, 0x00, 0x11, 0x00, 0x00, 0x0b,\n };\n ASSERT_EQ(interp::Result::TrapHostTrapped,\n LoadModuleAndRunStartFunction(data).result);\n}\n[interp] Add rot13 interpreter example (#890)\/*\n * Copyright 2018 WebAssembly Community Group participants\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"gtest\/gtest.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"src\/binary-reader.h\"\n#include \"src\/binary-reader-interp.h\"\n#include \"src\/cast.h\"\n#include \"src\/error-handler.h\"\n#include \"src\/interp.h\"\n#include \"src\/make-unique.h\"\n\nusing namespace wabt;\n\nnamespace {\n\ninterp::Result TrapCallback(const interp::HostFunc* func,\n const interp::FuncSignature* sig,\n const interp::TypedValues& args,\n interp::TypedValues& results) {\n return interp::Result::TrapHostTrapped;\n}\n\nclass HostTrapTest : public ::testing::Test {\n protected:\n virtual void SetUp() {\n interp::HostModule* host_module = env_.AppendHostModule(\"host\");\n host_module->AppendFuncExport(\"a\", {{}, {}}, TrapCallback);\n }\n\n virtual void TearDown() {}\n\n interp::ExecResult LoadModuleAndRunStartFunction(\n const std::vector& data) {\n ErrorHandlerFile error_handler(Location::Type::Binary);\n interp::DefinedModule* module = nullptr;\n ReadBinaryOptions options;\n Result result = ReadBinaryInterp(&env_, data.data(), data.size(), options,\n &error_handler, &module);\n EXPECT_EQ(Result::Ok, result);\n\n if (result == Result::Ok) {\n interp::Executor executor(&env_);\n return executor.RunStartFunction(module);\n } else {\n return {};\n }\n }\n\n interp::Environment env_;\n};\n\n} \/\/ end of anonymous namespace\n\nTEST_F(HostTrapTest, Call) {\n \/\/ (import \"host\" \"a\" (func $0))\n \/\/ (func $1 call $0)\n \/\/ (start $1)\n std::vector data = {\n 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x04, 0x01,\n 0x60, 0x00, 0x00, 0x02, 0x0a, 0x01, 0x04, 0x68, 0x6f, 0x73, 0x74,\n 0x01, 0x61, 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, 0x08, 0x01, 0x01,\n 0x0a, 0x06, 0x01, 0x04, 0x00, 0x10, 0x00, 0x0b,\n };\n ASSERT_EQ(interp::Result::TrapHostTrapped,\n LoadModuleAndRunStartFunction(data).result);\n}\n\nTEST_F(HostTrapTest, CallIndirect) {\n \/\/ (import \"host\" \"a\" (func $0))\n \/\/ (table anyfunc (elem $0))\n \/\/ (func $1 i32.const 0 call_indirect)\n \/\/ (start $1)\n std::vector data = {\n 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x04, 0x01, 0x60,\n 0x00, 0x00, 0x02, 0x0a, 0x01, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x01, 0x61,\n 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, 0x04, 0x05, 0x01, 0x70, 0x01, 0x01,\n 0x01, 0x08, 0x01, 0x01, 0x09, 0x07, 0x01, 0x00, 0x41, 0x00, 0x0b, 0x01,\n 0x00, 0x0a, 0x09, 0x01, 0x07, 0x00, 0x41, 0x00, 0x11, 0x00, 0x00, 0x0b,\n };\n ASSERT_EQ(interp::Result::TrapHostTrapped,\n LoadModuleAndRunStartFunction(data).result);\n}\n\nnamespace {\n\nclass HostMemoryTest : public ::testing::Test {\n protected:\n virtual void SetUp() {\n interp::HostModule* host_module = env_.AppendHostModule(\"host\");\n executor_ = MakeUnique(&env_);\n std::pair pair =\n host_module->AppendMemoryExport(\"mem\", Limits(1));\n\n using namespace std::placeholders;\n\n host_module->AppendFuncExport(\n \"fill_buf\", {{Type::I32, Type::I32}, {Type::I32}},\n std::bind(&HostMemoryTest::FillBufCallback, this, _1, _2, _3, _4));\n host_module->AppendFuncExport(\n \"buf_done\", {{Type::I32, Type::I32}, {}},\n std::bind(&HostMemoryTest::BufDoneCallback, this, _1, _2, _3, _4));\n memory_ = pair.first;\n }\n\n virtual void TearDown() {\n executor_.reset();\n }\n\n Result LoadModule(const std::vector& data) {\n ErrorHandlerFile error_handler(Location::Type::Binary);\n ReadBinaryOptions options;\n return ReadBinaryInterp(&env_, data.data(), data.size(), options,\n &error_handler, &module_);\n }\n\n std::string string_data;\n\n interp::Result FillBufCallback(const interp::HostFunc* func,\n const interp::FuncSignature* sig,\n const interp::TypedValues& args,\n interp::TypedValues& results) {\n \/\/ (param $ptr i32) (param $max_size i32) (result $size i32)\n EXPECT_EQ(2u, args.size());\n EXPECT_EQ(Type::I32, args[0].type);\n EXPECT_EQ(Type::I32, args[1].type);\n EXPECT_EQ(1u, results.size());\n EXPECT_EQ(Type::I32, results[0].type);\n\n uint32_t ptr = args[0].get_i32();\n uint32_t max_size = args[1].get_i32();\n uint32_t size = std::min(max_size, uint32_t(string_data.size()));\n\n EXPECT_LT(ptr + size, memory_->data.size());\n\n std::copy(string_data.begin(), string_data.begin() + size,\n memory_->data.begin() + ptr);\n\n results[0].set_i32(size);\n return interp::Result::Ok;\n }\n\n interp::Result BufDoneCallback(const interp::HostFunc* func,\n const interp::FuncSignature* sig,\n const interp::TypedValues& args,\n interp::TypedValues& results) {\n \/\/ (param $ptr i32) (param $size i32)\n EXPECT_EQ(2u, args.size());\n EXPECT_EQ(Type::I32, args[0].type);\n EXPECT_EQ(Type::I32, args[1].type);\n EXPECT_EQ(0u, results.size());\n\n uint32_t ptr = args[0].get_i32();\n uint32_t size = args[1].get_i32();\n\n EXPECT_LT(ptr + size, memory_->data.size());\n\n string_data.resize(size);\n std::copy(memory_->data.begin() + ptr, memory_->data.begin() + ptr + size,\n string_data.begin());\n\n return interp::Result::Ok;\n }\n\n interp::Environment env_;\n interp::Memory* memory_;\n interp::DefinedModule* module_;\n std::unique_ptr executor_;\n};\n\n} \/\/ end of anonymous namespace\n\nTEST_F(HostMemoryTest, Rot13) {\n \/\/ (import \"host\" \"mem\" (memory $mem 1))\n \/\/ (import \"host\" \"fill_buf\" (func $fill_buf (param i32 i32) (result i32)))\n \/\/ (import \"host\" \"buf_done\" (func $buf_done (param i32 i32)))\n \/\/\n \/\/ (func $rot13c (param $c i32) (result i32)\n \/\/ (local $uc i32)\n \/\/\n \/\/ ;; No change if < 'A'.\n \/\/ (if (i32.lt_u (get_local $c) (i32.const 65))\n \/\/ (return (get_local $c)))\n \/\/\n \/\/ ;; Clear 5th bit of c, to force uppercase. 0xdf = 0b11011111\n \/\/ (set_local $uc (i32.and (get_local $c) (i32.const 0xdf)))\n \/\/\n \/\/ ;; In range ['A', 'M'] return |c| + 13.\n \/\/ (if (i32.le_u (get_local $uc) (i32.const 77))\n \/\/ (return (i32.add (get_local $c) (i32.const 13))))\n \/\/\n \/\/ ;; In range ['N', 'Z'] return |c| - 13.\n \/\/ (if (i32.le_u (get_local $uc) (i32.const 90))\n \/\/ (return (i32.sub (get_local $c) (i32.const 13))))\n \/\/\n \/\/ ;; No change for everything else.\n \/\/ (return (get_local $c))\n \/\/ )\n \/\/\n \/\/ (func (export \"rot13\")\n \/\/ (local $size i32)\n \/\/ (local $i i32)\n \/\/\n \/\/ ;; Ask host to fill memory [0, 1024) with data.\n \/\/ (call $fill_buf (i32.const 0) (i32.const 1024))\n \/\/\n \/\/ ;; The host returns the size filled.\n \/\/ (set_local $size)\n \/\/\n \/\/ ;; Loop over all bytes and rot13 them.\n \/\/ (block $exit\n \/\/ (loop $top\n \/\/ ;; if (i >= size) break\n \/\/ (if (i32.ge_u (get_local $i) (get_local $size)) (br $exit))\n \/\/\n \/\/ ;; mem[i] = rot13c(mem[i])\n \/\/ (i32.store8\n \/\/ (get_local $i)\n \/\/ (call $rot13c\n \/\/ (i32.load8_u (get_local $i))))\n \/\/\n \/\/ ;; i++\n \/\/ (set_local $i (i32.add (get_local $i) (i32.const 1)))\n \/\/ (br $top)\n \/\/ )\n \/\/ )\n \/\/\n \/\/ (call $buf_done (i32.const 0) (get_local $size))\n \/\/ )\n std::vector data = {\n 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x14, 0x04, 0x60,\n 0x02, 0x7f, 0x7f, 0x01, 0x7f, 0x60, 0x02, 0x7f, 0x7f, 0x00, 0x60, 0x01,\n 0x7f, 0x01, 0x7f, 0x60, 0x00, 0x00, 0x02, 0x2d, 0x03, 0x04, 0x68, 0x6f,\n 0x73, 0x74, 0x03, 0x6d, 0x65, 0x6d, 0x02, 0x00, 0x01, 0x04, 0x68, 0x6f,\n 0x73, 0x74, 0x08, 0x66, 0x69, 0x6c, 0x6c, 0x5f, 0x62, 0x75, 0x66, 0x00,\n 0x00, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x08, 0x62, 0x75, 0x66, 0x5f, 0x64,\n 0x6f, 0x6e, 0x65, 0x00, 0x01, 0x03, 0x03, 0x02, 0x02, 0x03, 0x07, 0x09,\n 0x01, 0x05, 0x72, 0x6f, 0x74, 0x31, 0x33, 0x00, 0x03, 0x0a, 0x74, 0x02,\n 0x39, 0x01, 0x01, 0x7f, 0x20, 0x00, 0x41, 0xc1, 0x00, 0x49, 0x04, 0x40,\n 0x20, 0x00, 0x0f, 0x0b, 0x20, 0x00, 0x41, 0xdf, 0x01, 0x71, 0x21, 0x01,\n 0x20, 0x01, 0x41, 0xcd, 0x00, 0x4d, 0x04, 0x40, 0x20, 0x00, 0x41, 0x0d,\n 0x6a, 0x0f, 0x0b, 0x20, 0x01, 0x41, 0xda, 0x00, 0x4d, 0x04, 0x40, 0x20,\n 0x00, 0x41, 0x0d, 0x6b, 0x0f, 0x0b, 0x20, 0x00, 0x0f, 0x0b, 0x38, 0x01,\n 0x02, 0x7f, 0x41, 0x00, 0x41, 0x80, 0x08, 0x10, 0x00, 0x21, 0x00, 0x02,\n 0x40, 0x03, 0x40, 0x20, 0x01, 0x20, 0x00, 0x4f, 0x04, 0x40, 0x0c, 0x02,\n 0x0b, 0x20, 0x01, 0x20, 0x01, 0x2d, 0x00, 0x00, 0x10, 0x02, 0x3a, 0x00,\n 0x00, 0x20, 0x01, 0x41, 0x01, 0x6a, 0x21, 0x01, 0x0c, 0x00, 0x0b, 0x0b,\n 0x41, 0x00, 0x20, 0x00, 0x10, 0x01, 0x0b,\n };\n\n ASSERT_EQ(Result::Ok, LoadModule(data));\n\n string_data = \"Hello, WebAssembly!\";\n\n ASSERT_EQ(interp::Result::Ok,\n executor_->RunExportByName(module_, \"rot13\", {}).result);\n\n ASSERT_EQ(\"Uryyb, JroNffrzoyl!\", string_data);\n\n ASSERT_EQ(interp::Result::Ok,\n executor_->RunExportByName(module_, \"rot13\", {}).result);\n\n ASSERT_EQ(\"Hello, WebAssembly!\", string_data);\n}\n<|endoftext|>"} {"text":"\/\/ (C) Copyright Ullrich Koethe 2001, Gennadiy Rozental 2001-2002.\n\/\/ Permission to copy, use, modify, sell and distribute this software\n\/\/ is granted provided this copyright notice appears in all copies.\n\/\/ This software is provided \"as is\" without express or implied warranty,\n\/\/ and with no claim as to its suitability for any purpose.\n\n\/\/ See http:\/\/www.boost.org for updates, documentation, and revision history.\n\/\/\n\/\/ File : $RCSfile$\n\/\/\n\/\/ Version : $Id$\n\/\/\n\/\/ Description : supplies offline implemtation for the Test Tools\n\/\/ ***************************************************************************\n\n\/\/ Boost.Test\n#include \n#include \n\n\/\/ BOOST\n#include \n\n\/\/ STL\n#include \n#include \n#include \n#include \n#include \n\n# ifdef BOOST_NO_STDC_NAMESPACE\nnamespace std { using ::strcmp; using ::strncmp; using ::strlen; }\n# endif\n\nnamespace boost {\n\nnamespace test_toolbox {\n\nnamespace detail {\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** TOOL BOX Implementation ************** \/\/\n\/\/ ************************************************************************** \/\/\n\nvoid\ncheckpoint_impl( wrap_stringstream& message, c_string_literal file_name, int line_num )\n{\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::report_test_suites )\n unit_test_framework::checkpoint( message.str() )\n BOOST_UT_LOG_END\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\nmessage_impl( wrap_stringstream& message, c_string_literal file_name, int line_num )\n{\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::report_messages )\n message.str()\n BOOST_UT_LOG_END\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\nwarn_and_continue_impl( bool predicate, wrap_stringstream& message,\n c_string_literal file_name, int line_num, bool add_fail_pass )\n{\n if( !predicate ) {\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::report_warnings )\n (add_fail_pass ? \"condition \" : \"\") << message.str() << (add_fail_pass ? \" is not satisfied\" : \"\" )\n BOOST_UT_LOG_END\n }\n else {\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::report_successful_tests )\n \"condition \" << message.str() << \" is satisfied\"\n BOOST_UT_LOG_END\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\nwarn_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message, c_string_literal file_name, int line_num,\n bool add_fail_pass )\n{\n warn_and_continue_impl( !!v,\n message << (add_fail_pass && !v ? \" is not satisfied\" : \"\" ) << *(v.p_message),\n file_name, line_num, false );\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\ntest_and_continue_impl( bool predicate, wrap_stringstream& message,\n c_string_literal file_name, int line_num,\n bool add_fail_pass, unit_test_framework::report_level loglevel )\n{\n if( !predicate ) {\n unit_test_framework::unit_test_result::instance().inc_failed_assertions();\n\n BOOST_UT_LOG_BEGIN( file_name, line_num, loglevel )\n (add_fail_pass ? \"test \" : \"\") << message.str() << (add_fail_pass ? \" failed\" : \"\")\n BOOST_UT_LOG_END\n\n return true;\n }\n else {\n unit_test_framework::unit_test_result::instance().inc_passed_assertions();\n\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::report_successful_tests )\n (add_fail_pass ? \"test \" : \"\") << message.str() << (add_fail_pass ? \" passed\" : \"\")\n BOOST_UT_LOG_END\n\n return false;\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\ntest_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message,\n c_string_literal file_name, int line_num,\n bool add_fail_pass, unit_test_framework::report_level loglevel )\n{\n return test_and_continue_impl( !!v,\n message << (add_fail_pass ? (!v ? \" failed\" : \" passed\") : \"\") << *(v.p_message),\n file_name, line_num, false, loglevel );\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\ntest_and_throw_impl( bool predicate, wrap_stringstream& message,\n c_string_literal file_name, int line_num,\n bool add_fail_pass, unit_test_framework::report_level loglevel )\n{\n if( test_and_continue_impl( predicate, message, file_name, line_num, add_fail_pass, loglevel ) ) {\n throw test_tool_failed( \"\" ); \/\/ error already reported by test_and_continue_impl\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\ntest_and_throw_impl( extended_predicate_value const& v, wrap_stringstream& message,\n c_string_literal file_name, int line_num,\n bool add_fail_pass, unit_test_framework::report_level loglevel )\n{\n if( test_and_continue_impl( v, message, file_name, line_num, add_fail_pass, loglevel ) ) {\n throw test_tool_failed( \"\" ); \/\/ error already reported by test_and_continue_impl\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nequal_and_continue_impl( c_string_literal left, c_string_literal right, wrap_stringstream& message,\n c_string_literal file_name, int line_num,\n unit_test_framework::report_level loglevel )\n{\n bool predicate = (left && right) ? std::strcmp( left, right ) == 0 : (left == right);\n\n left = left ? left : \"null string\";\n right = right ? right : \"null string\";\n\n if( !predicate ) {\n return test_and_continue_impl( predicate,\n wrap_stringstream().ref() << \"test \" << message.str() << \" failed [\" << left << \" != \" << right << \"]\",\n file_name, line_num, false, loglevel );\n }\n\n return test_and_continue_impl( predicate, message, file_name, line_num, true, loglevel );\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nis_defined_impl( c_string_literal symbol_name, c_string_literal symbol_value )\n{\n return std::strcmp( symbol_name, symbol_value+1 ) != 0;\n}\n\n\/\/____________________________________________________________________________\/\/\n\n} \/\/ namespace detail\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** output_test_stream ************** \/\/\n\/\/ ************************************************************************** \/\/\n\nstruct output_test_stream::Impl\n{\n std::fstream m_pattern_to_match_or_save;\n bool m_match_or_save;\n std::string m_synced_string;\n\n void check_and_fill( detail::extended_predicate_value& res )\n {\n if( !res.p_predicate_value.get() )\n *(res.p_message) << \". Output content: \\\"\" << m_synced_string << '\\\"';\n }\n};\n\n\/\/____________________________________________________________________________\/\/\n\noutput_test_stream::output_test_stream( c_string_literal pattern_file, bool match_or_save )\n: m_pimpl( new Impl )\n{\n if( pattern_file && pattern_file[0] != '\\0' )\n m_pimpl->m_pattern_to_match_or_save.open( pattern_file, match_or_save ? std::ios::in : std::ios::out );\n m_pimpl->m_match_or_save = match_or_save;\n}\n\n\/\/____________________________________________________________________________\/\/\n\noutput_test_stream::~output_test_stream()\n{\n}\n\n\/\/____________________________________________________________________________\/\/\n\ndetail::extended_predicate_value\noutput_test_stream::is_empty( bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string.empty() );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ndetail::extended_predicate_value\noutput_test_stream::check_length( std::size_t length_, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string.length() == length_ );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ndetail::extended_predicate_value\noutput_test_stream::is_equal( c_string_literal arg, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string == arg );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ndetail::extended_predicate_value\noutput_test_stream::is_equal( std::string const& arg, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string == arg );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ndetail::extended_predicate_value\noutput_test_stream::is_equal( c_string_literal arg, std::size_t n, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string == std::string( arg, n ) );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\noutput_test_stream::match_pattern( bool flush_stream )\n{\n sync();\n\n bool result = true;\n\n if( !m_pimpl->m_pattern_to_match_or_save.is_open() )\n result = false;\n else {\n if( m_pimpl->m_match_or_save ) {\n c_string_literal ptr = m_pimpl->m_synced_string.c_str();\n\n for( std::size_t i = 0; i != m_pimpl->m_synced_string.length(); i++, ptr++ ) {\n char c;\n m_pimpl->m_pattern_to_match_or_save.get( c );\n\n if( m_pimpl->m_pattern_to_match_or_save.fail() ||\n m_pimpl->m_pattern_to_match_or_save.eof() )\n {\n result = false;\n break;\n }\n\n if( *ptr != c ) {\n result = false;\n }\n }\n }\n else {\n m_pimpl->m_pattern_to_match_or_save.write( m_pimpl->m_synced_string.c_str(), \n static_cast( m_pimpl->m_synced_string.length() ) );\n m_pimpl->m_pattern_to_match_or_save.flush();\n }\n }\n\n if( flush_stream )\n flush();\n\n return result;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\noutput_test_stream::flush()\n{\n m_pimpl->m_synced_string.erase();\n\n#ifndef BOOST_NO_STRINGSTREAM\n str( std::string() );\n#else\n seekp( 0, std::ios::beg );\n#endif\n}\n\n\/\/____________________________________________________________________________\/\/\n\nstd::size_t\noutput_test_stream::length()\n{\n sync();\n\n return m_pimpl->m_synced_string.length();\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\noutput_test_stream::sync()\n{\n#ifdef BOOST_NO_STRINGSTREAM\n m_pimpl->m_synced_string.assign( str(), pcount() );\n freeze( false );\n#else\n m_pimpl->m_synced_string = str();\n#endif\n}\n\n\/\/____________________________________________________________________________\/\/\n\n} \/\/ namespace test_toolbox\n\n} \/\/ namespace boost\n\n\/\/ ***************************************************************************\n\/\/ Revision History :\n\/\/ \n\/\/ $Log$\n\/\/ Revision 1.12 2002\/12\/08 18:20:30 rogeeff\n\/\/ wrapstratream separated in standalone file and renamed\n\/\/ switched to use c_string_literal\n\/\/\n\/\/ Revision 1.11 2002\/11\/02 20:23:24 rogeeff\n\/\/ wrapstream copy constructor isuue fix reworked\n\/\/\n\/\/ Revision 1.10 2002\/11\/02 20:04:41 rogeeff\n\/\/ release 1.29.0 merged into the main trank\n\/\/\n\n\/\/ ***************************************************************************\n\n\/\/ EOF\nBOOST_BITWIZE_EQUAL introduced BOOST_CHECK_NO_THROW introduced C string literals eliminated report_level -> log_level other minor fixes\/\/ (C) Copyright Ullrich Koethe 2001, Gennadiy Rozental 2001-2002.\n\/\/ Permission to copy, use, modify, sell and distribute this software\n\/\/ is granted provided this copyright notice appears in all copies.\n\/\/ This software is provided \"as is\" without express or implied warranty,\n\/\/ and with no claim as to its suitability for any purpose.\n\n\/\/ See http:\/\/www.boost.org for updates, documentation, and revision history.\n\/\/\n\/\/ File : $RCSfile$\n\/\/\n\/\/ Version : $Id$\n\/\/\n\/\/ Description : supplies offline implemtation for the Test Tools\n\/\/ ***************************************************************************\n\n\/\/ Boost.Test\n#include \n#include \n\n\/\/ BOOST\n#include \n\n\/\/ STL\n#include \n#include \n#include \n#include \n#include \n\n# ifdef BOOST_NO_STDC_NAMESPACE\nnamespace std { using ::strcmp; using ::strncmp; using ::strlen; }\n# endif\n\nnamespace boost {\n\nnamespace test_toolbox {\n\nnamespace detail {\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** TOOL BOX Implementation ************** \/\/\n\/\/ ************************************************************************** \/\/\n\nvoid\ncheckpoint_impl( wrap_stringstream& message, c_string_literal file_name, int line_num )\n{\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_test_suites )\n unit_test_framework::checkpoint( message.str() )\n BOOST_UT_LOG_END\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\nmessage_impl( wrap_stringstream& message, c_string_literal file_name, int line_num )\n{\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_messages )\n message.str()\n BOOST_UT_LOG_END\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\nwarn_and_continue_impl( bool predicate, wrap_stringstream& message,\n c_string_literal file_name, int line_num, bool add_fail_pass )\n{\n if( !predicate ) {\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_warnings )\n (add_fail_pass ? \"condition \" : \"\") << message.str() << (add_fail_pass ? \" is not satisfied\" : \"\" )\n BOOST_UT_LOG_END\n }\n else {\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_successful_tests )\n \"condition \" << message.str() << \" is satisfied\"\n BOOST_UT_LOG_END\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\nwarn_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message, c_string_literal file_name, int line_num,\n bool add_fail_pass )\n{\n warn_and_continue_impl( !!v,\n message << (add_fail_pass && !v ? \" is not satisfied. \" : \"\" ) << *(v.p_message),\n file_name, line_num, false );\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\ntest_and_continue_impl( bool predicate, wrap_stringstream& message,\n c_string_literal file_name, int line_num,\n bool add_fail_pass, unit_test_framework::log_level loglevel )\n{\n if( !predicate ) {\n unit_test_framework::unit_test_result::instance().inc_failed_assertions();\n\n BOOST_UT_LOG_BEGIN( file_name, line_num, loglevel )\n (add_fail_pass ? \"test \" : \"\") << message.str() << (add_fail_pass ? \" failed\" : \"\")\n BOOST_UT_LOG_END\n\n return true;\n }\n else {\n unit_test_framework::unit_test_result::instance().inc_passed_assertions();\n\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_successful_tests )\n (add_fail_pass ? \"test \" : \"\") << message.str() << (add_fail_pass ? \" passed\" : \"\")\n BOOST_UT_LOG_END\n\n return false;\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\ntest_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message,\n c_string_literal file_name, int line_num,\n bool add_fail_pass, unit_test_framework::log_level loglevel )\n{\n return test_and_continue_impl( !!v,\n message << (add_fail_pass ? (!v ? \" failed. \" : \" passed. \") : \"\") << *(v.p_message),\n file_name, line_num, false, loglevel );\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\ntest_and_throw_impl( bool predicate, wrap_stringstream& message,\n c_string_literal file_name, int line_num,\n bool add_fail_pass, unit_test_framework::log_level loglevel )\n{\n if( test_and_continue_impl( predicate, message, file_name, line_num, add_fail_pass, loglevel ) ) {\n throw test_tool_failed(); \/\/ error already reported by test_and_continue_impl\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\ntest_and_throw_impl( extended_predicate_value const& v, wrap_stringstream& message,\n c_string_literal file_name, int line_num,\n bool add_fail_pass, unit_test_framework::log_level loglevel )\n{\n if( test_and_continue_impl( v, message, file_name, line_num, add_fail_pass, loglevel ) ) {\n throw test_tool_failed(); \/\/ error already reported by test_and_continue_impl\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nequal_and_continue_impl( c_string_literal left, c_string_literal right, wrap_stringstream& message,\n c_string_literal file_name, int line_num,\n unit_test_framework::log_level loglevel )\n{\n bool predicate = (left && right) ? std::strcmp( left, right ) == 0 : (left == right);\n\n left = left ? left : \"null string\";\n right = right ? right : \"null string\";\n\n if( !predicate ) {\n return test_and_continue_impl( false,\n wrap_stringstream().ref() << \"test \" << message.str() << \" failed [\" << left << \" != \" << right << \"]\",\n file_name, line_num, false, loglevel );\n }\n\n return test_and_continue_impl( true, message, file_name, line_num, true, loglevel );\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nis_defined_impl( c_string_literal symbol_name, c_string_literal symbol_value )\n{\n return std::strcmp( symbol_name, symbol_value+1 ) != 0;\n}\n\n\/\/____________________________________________________________________________\/\/\n\n} \/\/ namespace detail\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** output_test_stream ************** \/\/\n\/\/ ************************************************************************** \/\/\n\nstruct output_test_stream::Impl\n{\n std::fstream m_pattern_to_match_or_save;\n bool m_match_or_save;\n std::string m_synced_string;\n\n void check_and_fill( detail::extended_predicate_value& res )\n {\n if( !res.p_predicate_value.get() )\n *(res.p_message) << \"Output content: \\\"\" << m_synced_string << '\\\"';\n }\n};\n\n\/\/____________________________________________________________________________\/\/\n\noutput_test_stream::output_test_stream( std::string const& pattern_file_name, bool match_or_save )\n: m_pimpl( new Impl )\n{\n if( !pattern_file_name.empty() )\n m_pimpl->m_pattern_to_match_or_save.open( pattern_file_name.c_str(), match_or_save ? std::ios::in : std::ios::out );\n\n m_pimpl->m_match_or_save = match_or_save;\n}\n\n\/\/____________________________________________________________________________\/\/\n\noutput_test_stream::output_test_stream( c_string_literal pattern_file_name, bool match_or_save )\n: m_pimpl( new Impl )\n{\n if( pattern_file_name && pattern_file_name[0] != '\\0' )\n m_pimpl->m_pattern_to_match_or_save.open( pattern_file_name, match_or_save ? std::ios::in : std::ios::out );\n\n m_pimpl->m_match_or_save = match_or_save;\n}\n\n\/\/____________________________________________________________________________\/\/\n\noutput_test_stream::~output_test_stream()\n{\n}\n\n\/\/____________________________________________________________________________\/\/\n\ndetail::extended_predicate_value\noutput_test_stream::is_empty( bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string.empty() );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ndetail::extended_predicate_value\noutput_test_stream::check_length( std::size_t length_, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string.length() == length_ );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ndetail::extended_predicate_value\noutput_test_stream::is_equal( c_string_literal arg, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string == arg );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ndetail::extended_predicate_value\noutput_test_stream::is_equal( std::string const& arg, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string == arg );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ndetail::extended_predicate_value\noutput_test_stream::is_equal( c_string_literal arg, std::size_t n, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string == std::string( arg, n ) );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\noutput_test_stream::match_pattern( bool flush_stream )\n{\n sync();\n\n bool result = true;\n\n if( !m_pimpl->m_pattern_to_match_or_save.is_open() )\n result = false;\n else {\n if( m_pimpl->m_match_or_save ) {\n c_string_literal ptr = m_pimpl->m_synced_string.c_str();\n\n for( std::size_t i = 0; i != m_pimpl->m_synced_string.length(); i++, ptr++ ) {\n char c;\n m_pimpl->m_pattern_to_match_or_save.get( c );\n\n if( m_pimpl->m_pattern_to_match_or_save.fail() ||\n m_pimpl->m_pattern_to_match_or_save.eof() )\n {\n result = false;\n break;\n }\n\n if( *ptr != c ) {\n result = false;\n }\n }\n }\n else {\n m_pimpl->m_pattern_to_match_or_save.write( m_pimpl->m_synced_string.c_str(), \n static_cast( m_pimpl->m_synced_string.length() ) );\n m_pimpl->m_pattern_to_match_or_save.flush();\n }\n }\n\n if( flush_stream )\n flush();\n\n return result;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\noutput_test_stream::flush()\n{\n m_pimpl->m_synced_string.erase();\n\n#ifndef BOOST_NO_STRINGSTREAM\n str( std::string() );\n#else\n seekp( 0, std::ios::beg );\n#endif\n}\n\n\/\/____________________________________________________________________________\/\/\n\nstd::size_t\noutput_test_stream::length()\n{\n sync();\n\n return m_pimpl->m_synced_string.length();\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\noutput_test_stream::sync()\n{\n#ifdef BOOST_NO_STRINGSTREAM\n m_pimpl->m_synced_string.assign( str(), pcount() );\n freeze( false );\n#else\n m_pimpl->m_synced_string = str();\n#endif\n}\n\n\/\/____________________________________________________________________________\/\/\n\n} \/\/ namespace test_toolbox\n\n} \/\/ namespace boost\n\n\/\/ ***************************************************************************\n\/\/ Revision History :\n\/\/ \n\/\/ $Log$\n\/\/ Revision 1.13 2003\/02\/13 08:15:25 rogeeff\n\/\/ BOOST_BITWIZE_EQUAL introduced\n\/\/ BOOST_CHECK_NO_THROW introduced\n\/\/ C string literals eliminated\n\/\/ report_level -> log_level\n\/\/ other minor fixes\n\/\/\n\/\/ Revision 1.12 2002\/12\/08 18:20:30 rogeeff\n\/\/ wrapstratream separated in standalone file and renamed\n\/\/ switched to use c_string_literal\n\/\/\n\/\/ Revision 1.11 2002\/11\/02 20:23:24 rogeeff\n\/\/ wrapstream copy constructor isuue fix reworked\n\/\/\n\/\/ Revision 1.10 2002\/11\/02 20:04:41 rogeeff\n\/\/ release 1.29.0 merged into the main trank\n\/\/\n\n\/\/ ***************************************************************************\n\n\/\/ EOF\n<|endoftext|>"} {"text":"#include \"02.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Includes \/\/\n#include \n\n#include \"..\/parser.hpp\"\n#include \"..\/json.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\n\/\/ Code \/\/\n\n\/\/ Checking if a value is around the target.\nbool around(double target, double num, double range) {\n return num >= target - range &&\n num <= target + range;\n}\n\n\/\/ Testing the parseJSON function for parsing a number.\nint runTest02() {\n JValue positiveVal = parseJSON(\"12345\");\n JValue negativeVal = parseJSON(\"-12345\");\n JValue floatingPosVal = parseJSON(\"54321.12345\");\n JValue floatingNegVal = parseJSON(\"-54321.12345\");\n\n std::cout << positiveVal.jNumber() << std::endl;\n std::cout << negativeVal.jNumber() << std::endl;\n std::cout << floatingPosVal.jNumber() << std::endl;\n std::cout << floatingNegVal.jNumber() << std::endl;\n\n if (!positiveVal.isNumber() || !around(12345, positiveVal.jNumber(), 1))\n return 1;\n\n if (!negativeVal.isNumber() || !around(-12345, negativeVal.jNumber(), 1))\n return 1;\n\n if (!floatingPosVal.isNumber() || !around(54321.12345, floatingPosVal.jNumber(), 1))\n return 1;\n\n if (!floatingNegVal.isNumber() || !around(-54321.12345, floatingNegVal.jNumber(), 1))\n return 1;\n \n return 0;\n}\nRemoved some printing stuff#include \"02.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Includes \/\/\n#include \"..\/parser.hpp\"\n#include \"..\/json.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\n\/\/ Code \/\/\n\n\/\/ Checking if a value is around the target.\nbool around(double target, double num, double range) {\n return num >= target - range &&\n num <= target + range;\n}\n\n\/\/ Testing the parseJSON function for parsing a number.\nint runTest02() {\n JValue positiveVal = parseJSON(\"12345\");\n JValue negativeVal = parseJSON(\"-12345\");\n JValue floatingPosVal = parseJSON(\"54321.12345\");\n JValue floatingNegVal = parseJSON(\"-54321.12345\");\n\n if (!positiveVal.isNumber() || !around(12345, positiveVal.jNumber(), 1))\n return 1;\n\n if (!negativeVal.isNumber() || !around(-12345, negativeVal.jNumber(), 1))\n return 1;\n\n if (!floatingPosVal.isNumber() || !around(54321.12345, floatingPosVal.jNumber(), 1))\n return 1;\n\n if (!floatingNegVal.isNumber() || !around(-54321.12345, floatingNegVal.jNumber(), 1))\n return 1;\n \n return 0;\n}\n<|endoftext|>"} {"text":"#include \"includes\/truthtable.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"includes\/symbols.h\"\n#include \"includes\/tokenizer.h\"\n\nTruthTable::TruthTable()\n : m_operator_map(std::map()),\n m_keywords_set(std::set()),\n m_operator_precedence_map(std::map()),\n m_operands(std::vector()),\n m_expression_tree(nullptr),\n m_pretty_print(false)\n{\n m_operator_map[symbol::AND] = Op::AND;\n m_operator_map[symbol::OR] = Op::OR;\n m_operator_map[symbol::NOT] = Op::NOT;\n m_operator_map[symbol::XOR] = Op::XOR;\n m_operator_map[symbol::IMPLICATION] = Op::IMPLICATION;\n m_operator_map[symbol::EQUIVALENCE] = Op::EQUIVALENCE;\n\n for (const auto &entry : m_operator_map)\n {\n m_keywords_set.insert(entry.first);\n }\n m_keywords_set.insert(symbol::LEFT_PAREN);\n m_keywords_set.insert(symbol::RIGHT_PAREN);\n\n m_operator_precedence_map[symbol::NOT] = 1;\n m_operator_precedence_map[symbol::AND] = 2;\n m_operator_precedence_map[symbol::OR] = 3;\n m_operator_precedence_map[symbol::IMPLICATION] = 4;\n m_operator_precedence_map[symbol::EQUIVALENCE] = 5;\n}\n\nTruthTable::~TruthTable()\n{\n delete_expression_tree(m_expression_tree);\n}\n\nbool TruthTable::generate(const std::string &input)\n{\n m_operands.clear();\n\n Tokenizer tokenizer(input);\n if (!tokenizer.tokenize())\n {\n return false;\n }\n\n std::vector tokens = tokenizer.get();\n std::set operands;\n for (const auto &t : tokens)\n {\n if (is_operand(t))\n {\n operands.insert(t);\n }\n }\n\n std::for_each(std::begin(operands), std::end(operands), [this](std::string s) { m_operands.push_back(s); });\n std::sort(m_operands.begin(), m_operands.end());\n\n std::vector postfix = to_post_fix(tokens);\n if (postfix.empty())\n {\n return false;\n }\n\n \/\/ print_container(postfix);\n\n m_expression_tree = to_expression_tree(postfix);\n if (!m_expression_tree)\n {\n return false;\n }\n\n generate(tokens);\n\n return true;\n}\n\nstd::vector TruthTable::to_post_fix(const std::vector &tokens)\n{\n std::stack op_stack;\n std::vector postfix;\n std::string last_symbol;\n\n bool error_possibility = false;\n unsigned int i = 0;\n while (i < tokens.size())\n {\n auto symbol = tokens[i++];\n if (is_operand(symbol))\n {\n error_possibility = false;\n postfix.push_back(symbol);\n }\n else\n {\n if (error_possibility && symbol != symbol::NOT)\n {\n postfix.clear();\n return postfix;\n }\n\n if (last_symbol == symbol::NOT)\n {\n error_possibility = true;\n }\n\n if (op_stack.empty() || op_stack.top() == symbol::LEFT_PAREN)\n {\n op_stack.push(symbol);\n }\n else if (symbol == symbol::LEFT_PAREN)\n {\n op_stack.push(symbol);\n }\n else if (symbol == symbol::RIGHT_PAREN)\n {\n for (std::string &top = op_stack.top(); top != symbol::LEFT_PAREN; top = op_stack.top())\n {\n postfix.push_back(top);\n op_stack.pop();\n }\n op_stack.pop(); \/\/ discard left parenthesis\n }\n else if (has_higher_precendence(symbol, op_stack.top()) || has_equal_precendence(symbol, op_stack.top()))\n {\n op_stack.push(symbol);\n }\n else\n {\n std::string &top = op_stack.top();\n postfix.push_back(top);\n op_stack.pop();\n --i;\n }\n }\n last_symbol = symbol;\n }\n\n if (last_symbol == symbol::NOT)\n {\n postfix.clear();\n return postfix;\n }\n\n while (op_stack.size() > 0)\n {\n std::string &top = op_stack.top();\n if (top == symbol::LEFT_PAREN || top == symbol::RIGHT_PAREN)\n {\n postfix.clear();\n break;\n }\n\n postfix.push_back(top);\n op_stack.pop();\n }\n\n return postfix;\n}\n\nTruthTable::Node *TruthTable::to_expression_tree(std::vector postfix)\n{\n std::stack expression_stack;\n for (const auto &symbol : postfix)\n {\n if (is_operand(symbol))\n {\n expression_stack.push(new Node(symbol));\n }\n else\n {\n if (expression_stack.empty())\n {\n return nullptr;\n }\n\n Node *node = new Node(symbol);\n Node *left = expression_stack.top();\n expression_stack.pop();\n node->left = left;\n\n if (symbol != symbol::NOT) \/\/ special case\n {\n if (expression_stack.empty())\n {\n return nullptr;\n }\n\n Node *right = expression_stack.top();\n expression_stack.pop();\n node->right = right;\n }\n\n expression_stack.push(node);\n }\n }\n if (expression_stack.size() > 1)\n {\n Node *node = expression_stack.top();\n expression_stack.pop();\n while (!expression_stack.empty())\n {\n delete_expression_tree(node);\n node = expression_stack.top();\n expression_stack.pop();\n }\n return nullptr;\n }\n return expression_stack.top();\n}\n\nvoid TruthTable::delete_expression_tree(TruthTable::Node *node)\n{\n if (node)\n {\n delete_expression_tree(node->left);\n delete_expression_tree(node->right);\n delete node;\n }\n}\n\nvoid TruthTable::print_expression_tree(TruthTable::Node *node, std::string indent)\n{\n if (node)\n {\n print_expression_tree(node->left, indent += \" \");\n std::cout << indent << node->value << std::endl;\n print_expression_tree(node->right, indent += \" \");\n }\n}\n\nbool TruthTable::calculate(bool left, Op op, bool right)\n{\n switch (op)\n {\n case Op::NOT:\n {\n return !left;\n }\n case Op::AND:\n {\n return left && right;\n }\n case Op::OR:\n {\n return left || right;\n }\n case Op::XOR:\n {\n return (left || right) && !(left && right);\n }\n case Op::IMPLICATION:\n {\n return !left || right;\n }\n case Op::EQUIVALENCE:\n {\n return !((left || right) && !(left && right));\n }\n default:\n {\n assert(!\"Error: invalid code path\");\n return false;\n }\n }\n}\n\nvoid TruthTable::generate(std::vector &tokens)\n{\n std::ostream &os = std::cout;\n\n unsigned int max_operand_text_width = 0;\n std::string input;\n\n if (m_pretty_print)\n {\n expression_tree_to_string(m_expression_tree, input);\n for (const auto &operand : m_operands)\n {\n if (operand.size() > max_operand_text_width)\n {\n max_operand_text_width = static_cast(operand.size());\n }\n }\n max_operand_text_width += 1;\n }\n\n unsigned int input_text_width = static_cast(input.size());\n\n unsigned long operand_count = m_operands.size();\n\n unsigned int max_chars = static_cast(operand_count) * max_operand_text_width + input_text_width +\n static_cast(operand_count) + 2;\n\n auto print_row_separator = [&]() {\n for (unsigned int i = 0; i < max_chars; ++i)\n {\n if ((i < (max_chars - input_text_width) && i % (max_operand_text_width + 1) == 0) || i == max_chars - 1)\n {\n os << \"+\";\n }\n else\n {\n os << \"-\";\n }\n }\n os << std::endl;\n };\n\n if (m_pretty_print)\n {\n print_row_separator();\n\n for (const auto &s : m_operands)\n {\n os << \"|\";\n os << std::setw(max_operand_text_width) << s;\n }\n os << \"|\" << std::setw(input_text_width) << input << \"|\" << std::endl;\n\n print_row_separator();\n }\n\n unsigned long num_permutations = 1;\n unsigned long interval_count = 0;\n for (const auto &operand : m_operands)\n {\n if (operand != symbol::TRUE && operand != symbol::FALSE)\n {\n num_permutations *= 2;\n ++interval_count;\n }\n }\n\n bool intervals[interval_count];\n for (unsigned long i = 0; i < interval_count; ++i)\n {\n intervals[i] = true;\n }\n\n unsigned long counters[interval_count];\n counters[0] = 1;\n for (unsigned long i = 1; i < interval_count; ++i)\n {\n counters[i] = counters[i - 1] * 2;\n }\n\n std::map map;\n for (unsigned long i = 0; i < num_permutations; ++i)\n {\n for (unsigned long j = 0; j < interval_count; ++j)\n {\n if (i % counters[j] == 0)\n {\n intervals[j] = !intervals[j];\n }\n }\n\n map.clear();\n\n int index = 0;\n for (const auto &operand : m_operands)\n {\n if (operand == symbol::FALSE)\n {\n map[operand] = false;\n }\n else if (operand == symbol::TRUE)\n {\n map[operand] = true;\n }\n else\n {\n map[operand] = intervals[index];\n ++index;\n }\n }\n\n bool result = solve_helper(map, m_expression_tree);\n\n if (m_pretty_print)\n {\n os << \"|\";\n\n for (unsigned long j = 0; j < operand_count; ++j)\n {\n os << std::setw(max_operand_text_width) << std::internal << map[m_operands[j]];\n os << \"|\";\n }\n\n os << std::setw(input_text_width) << result;\n\n os << \"|\";\n }\n else\n {\n for (unsigned long j = 0; j < operand_count; ++j)\n {\n os << map[m_operands[j]];\n }\n\n os << result;\n }\n os << std::endl;\n }\n\n if (m_pretty_print)\n {\n print_row_separator();\n }\n}\n\nbool TruthTable::solve_helper(std::map &value_map, TruthTable::Node *node)\n{\n if (is_operand(node->value))\n {\n return value_map[node->value];\n }\n bool result_left = solve_helper(value_map, node->left);\n bool result_right = false;\n if (node->right)\n {\n result_right = solve_helper(value_map, node->right);\n }\n return calculate(result_left, m_operator_map[node->value], result_right);\n}\n\nvoid TruthTable::expression_tree_to_string(TruthTable::Node *node, std::string &result, int depth)\n{\n if (node)\n {\n bool can_print_paren = (node->left || node->right) && depth > 0;\n if (can_print_paren)\n {\n result += symbol::LEFT_PAREN;\n }\n expression_tree_to_string(node->right, result, depth + 1);\n result += node->value;\n expression_tree_to_string(node->left, result, depth + 1);\n if (can_print_paren)\n {\n result += symbol::RIGHT_PAREN;\n }\n }\n}\n\ntemplate \nvoid TruthTable::print_container(const T &v)\n{\n auto itr = std::begin(v);\n if (itr != std::end(v))\n {\n while (true)\n {\n std::cout << *itr;\n ++itr;\n if (itr != std::end(v))\n {\n std::cout << \", \";\n }\n else\n {\n break;\n }\n }\n std::cout << std::endl;\n }\n}\nFixed memory leak#include \"includes\/truthtable.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"includes\/symbols.h\"\n#include \"includes\/tokenizer.h\"\n\nTruthTable::TruthTable()\n : m_operator_map(std::map()),\n m_keywords_set(std::set()),\n m_operator_precedence_map(std::map()),\n m_operands(std::vector()),\n m_expression_tree(nullptr),\n m_pretty_print(false)\n{\n m_operator_map[symbol::AND] = Op::AND;\n m_operator_map[symbol::OR] = Op::OR;\n m_operator_map[symbol::NOT] = Op::NOT;\n m_operator_map[symbol::XOR] = Op::XOR;\n m_operator_map[symbol::IMPLICATION] = Op::IMPLICATION;\n m_operator_map[symbol::EQUIVALENCE] = Op::EQUIVALENCE;\n\n for (const auto &entry : m_operator_map)\n {\n m_keywords_set.insert(entry.first);\n }\n m_keywords_set.insert(symbol::LEFT_PAREN);\n m_keywords_set.insert(symbol::RIGHT_PAREN);\n\n m_operator_precedence_map[symbol::NOT] = 1;\n m_operator_precedence_map[symbol::AND] = 2;\n m_operator_precedence_map[symbol::OR] = 3;\n m_operator_precedence_map[symbol::IMPLICATION] = 4;\n m_operator_precedence_map[symbol::EQUIVALENCE] = 5;\n}\n\nTruthTable::~TruthTable()\n{\n delete_expression_tree(m_expression_tree);\n}\n\nbool TruthTable::generate(const std::string &input)\n{\n m_operands.clear();\n\n Tokenizer tokenizer(input);\n if (!tokenizer.tokenize())\n {\n return false;\n }\n\n std::vector tokens = tokenizer.get();\n std::set operands;\n for (const auto &t : tokens)\n {\n if (is_operand(t))\n {\n operands.insert(t);\n }\n }\n\n std::for_each(std::begin(operands), std::end(operands), [this](std::string s) { m_operands.push_back(s); });\n std::sort(m_operands.begin(), m_operands.end());\n\n std::vector postfix = to_post_fix(tokens);\n if (postfix.empty())\n {\n return false;\n }\n\n \/\/ print_container(postfix);\n\n m_expression_tree = to_expression_tree(postfix);\n if (!m_expression_tree)\n {\n return false;\n }\n\n generate(tokens);\n\n return true;\n}\n\nstd::vector TruthTable::to_post_fix(const std::vector &tokens)\n{\n std::stack op_stack;\n std::vector postfix;\n std::string last_symbol;\n\n bool error_possibility = false;\n unsigned int i = 0;\n while (i < tokens.size())\n {\n auto symbol = tokens[i++];\n if (is_operand(symbol))\n {\n error_possibility = false;\n postfix.push_back(symbol);\n }\n else\n {\n if (error_possibility && symbol != symbol::NOT)\n {\n postfix.clear();\n return postfix;\n }\n\n if (last_symbol == symbol::NOT)\n {\n error_possibility = true;\n }\n\n if (op_stack.empty() || op_stack.top() == symbol::LEFT_PAREN)\n {\n op_stack.push(symbol);\n }\n else if (symbol == symbol::LEFT_PAREN)\n {\n op_stack.push(symbol);\n }\n else if (symbol == symbol::RIGHT_PAREN)\n {\n for (std::string &top = op_stack.top(); top != symbol::LEFT_PAREN; top = op_stack.top())\n {\n postfix.push_back(top);\n op_stack.pop();\n }\n op_stack.pop(); \/\/ discard left parenthesis\n }\n else if (has_higher_precendence(symbol, op_stack.top()) || has_equal_precendence(symbol, op_stack.top()))\n {\n op_stack.push(symbol);\n }\n else\n {\n std::string &top = op_stack.top();\n postfix.push_back(top);\n op_stack.pop();\n --i;\n }\n }\n last_symbol = symbol;\n }\n\n if (last_symbol == symbol::NOT)\n {\n postfix.clear();\n return postfix;\n }\n\n while (op_stack.size() > 0)\n {\n std::string &top = op_stack.top();\n if (top == symbol::LEFT_PAREN || top == symbol::RIGHT_PAREN)\n {\n postfix.clear();\n break;\n }\n\n postfix.push_back(top);\n op_stack.pop();\n }\n\n return postfix;\n}\n\nTruthTable::Node *TruthTable::to_expression_tree(std::vector postfix)\n{\n std::stack expression_stack;\n\n auto cleanup_stack = [&expression_stack, this]()\n {\n while (!expression_stack.empty())\n {\n Node *node = expression_stack.top();\n delete_expression_tree(node);\n expression_stack.pop();\n }\n };\n\n for (const auto &symbol : postfix)\n {\n if (is_operand(symbol))\n {\n expression_stack.push(new Node(symbol));\n }\n else\n {\n if (expression_stack.empty())\n {\n cleanup_stack();\n return nullptr;\n }\n\n Node *node = new Node(symbol);\n Node *left = expression_stack.top();\n expression_stack.pop();\n node->left = left;\n\n if (symbol != symbol::NOT) \/\/ special case\n {\n if (expression_stack.empty())\n {\n delete_expression_tree(node);\n cleanup_stack();\n return nullptr;\n }\n\n Node *right = expression_stack.top();\n expression_stack.pop();\n node->right = right;\n }\n\n expression_stack.push(node);\n }\n }\n if (expression_stack.size() > 1)\n {\n cleanup_stack();\n return nullptr;\n }\n return expression_stack.top();\n}\n\nvoid TruthTable::delete_expression_tree(TruthTable::Node *node)\n{\n if (node)\n {\n delete_expression_tree(node->left);\n delete_expression_tree(node->right);\n delete node;\n }\n}\n\nvoid TruthTable::print_expression_tree(TruthTable::Node *node, std::string indent)\n{\n if (node)\n {\n print_expression_tree(node->left, indent += \" \");\n std::cout << indent << node->value << std::endl;\n print_expression_tree(node->right, indent += \" \");\n }\n}\n\nbool TruthTable::calculate(bool left, Op op, bool right)\n{\n switch (op)\n {\n case Op::NOT:\n {\n return !left;\n }\n case Op::AND:\n {\n return left && right;\n }\n case Op::OR:\n {\n return left || right;\n }\n case Op::XOR:\n {\n return (left || right) && !(left && right);\n }\n case Op::IMPLICATION:\n {\n return !left || right;\n }\n case Op::EQUIVALENCE:\n {\n return !((left || right) && !(left && right));\n }\n default:\n {\n assert(!\"Error: invalid code path\");\n return false;\n }\n }\n}\n\nvoid TruthTable::generate(std::vector &tokens)\n{\n std::ostream &os = std::cout;\n\n unsigned int max_operand_text_width = 0;\n std::string input;\n\n if (m_pretty_print)\n {\n expression_tree_to_string(m_expression_tree, input);\n for (const auto &operand : m_operands)\n {\n if (operand.size() > max_operand_text_width)\n {\n max_operand_text_width = static_cast(operand.size());\n }\n }\n max_operand_text_width += 1;\n }\n\n unsigned int input_text_width = static_cast(input.size());\n\n unsigned long operand_count = m_operands.size();\n\n unsigned int max_chars = static_cast(operand_count) * max_operand_text_width + input_text_width +\n static_cast(operand_count) + 2;\n\n auto print_row_separator = [&]() {\n for (unsigned int i = 0; i < max_chars; ++i)\n {\n if ((i < (max_chars - input_text_width) && i % (max_operand_text_width + 1) == 0) || i == max_chars - 1)\n {\n os << \"+\";\n }\n else\n {\n os << \"-\";\n }\n }\n os << std::endl;\n };\n\n if (m_pretty_print)\n {\n print_row_separator();\n\n for (const auto &s : m_operands)\n {\n os << \"|\";\n os << std::setw(max_operand_text_width) << s;\n }\n os << \"|\" << std::setw(input_text_width) << input << \"|\" << std::endl;\n\n print_row_separator();\n }\n\n unsigned long num_permutations = 1;\n unsigned long interval_count = 0;\n for (const auto &operand : m_operands)\n {\n if (operand != symbol::TRUE && operand != symbol::FALSE)\n {\n num_permutations *= 2;\n ++interval_count;\n }\n }\n\n bool intervals[interval_count];\n for (unsigned long i = 0; i < interval_count; ++i)\n {\n intervals[i] = true;\n }\n\n unsigned long counters[interval_count];\n counters[0] = 1;\n for (unsigned long i = 1; i < interval_count; ++i)\n {\n counters[i] = counters[i - 1] * 2;\n }\n\n std::map map;\n for (unsigned long i = 0; i < num_permutations; ++i)\n {\n for (unsigned long j = 0; j < interval_count; ++j)\n {\n if (i % counters[j] == 0)\n {\n intervals[j] = !intervals[j];\n }\n }\n\n map.clear();\n\n int index = 0;\n for (const auto &operand : m_operands)\n {\n if (operand == symbol::FALSE)\n {\n map[operand] = false;\n }\n else if (operand == symbol::TRUE)\n {\n map[operand] = true;\n }\n else\n {\n map[operand] = intervals[index];\n ++index;\n }\n }\n\n bool result = solve_helper(map, m_expression_tree);\n\n if (m_pretty_print)\n {\n os << \"|\";\n\n for (unsigned long j = 0; j < operand_count; ++j)\n {\n os << std::setw(max_operand_text_width) << std::internal << map[m_operands[j]];\n os << \"|\";\n }\n\n os << std::setw(input_text_width) << result;\n\n os << \"|\";\n }\n else\n {\n for (unsigned long j = 0; j < operand_count; ++j)\n {\n os << map[m_operands[j]];\n }\n\n os << result;\n }\n os << std::endl;\n }\n\n if (m_pretty_print)\n {\n print_row_separator();\n }\n}\n\nbool TruthTable::solve_helper(std::map &value_map, TruthTable::Node *node)\n{\n if (is_operand(node->value))\n {\n return value_map[node->value];\n }\n bool result_left = solve_helper(value_map, node->left);\n bool result_right = false;\n if (node->right)\n {\n result_right = solve_helper(value_map, node->right);\n }\n return calculate(result_left, m_operator_map[node->value], result_right);\n}\n\nvoid TruthTable::expression_tree_to_string(TruthTable::Node *node, std::string &result, int depth)\n{\n if (node)\n {\n bool can_print_paren = (node->left || node->right) && depth > 0;\n if (can_print_paren)\n {\n result += symbol::LEFT_PAREN;\n }\n expression_tree_to_string(node->right, result, depth + 1);\n result += node->value;\n expression_tree_to_string(node->left, result, depth + 1);\n if (can_print_paren)\n {\n result += symbol::RIGHT_PAREN;\n }\n }\n}\n\ntemplate \nvoid TruthTable::print_container(const T &v)\n{\n auto itr = std::begin(v);\n if (itr != std::end(v))\n {\n while (true)\n {\n std::cout << *itr;\n ++itr;\n if (itr != std::end(v))\n {\n std::cout << \", \";\n }\n else\n {\n break;\n }\n }\n std::cout << std::endl;\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2011 by Toshiro Yamada\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n#include \"udp_client.hpp\"\n\n#include \n\nusing namespace am;\n\nnamespace asio = boost::asio;\n\n\/\/-----------------------------------------------------------------------------\nUDPClient::AsyncUDPClient::AsyncUDPClient(asio::io_service& io_service,\n boost::condition_variable& cond, boost::mutex& mut)\n: io_service_(io_service)\n, socket_(io_service_)\n, write_in_progress_(false)\n, write_progress_cond_(cond)\n, write_progress_mut_(mut)\n{\n socket_.open(asio::ip::udp::v4());\n}\n\nUDPClient::AsyncUDPClient::~AsyncUDPClient()\n{\n socket_.close();\n}\n\nvoid UDPClient::AsyncUDPClient::SetEndpoint(asio::ip::udp::endpoint& endpoint)\n{\n endpoint_ = endpoint;\n}\n\nvoid UDPClient::AsyncUDPClient::Send(const std::vector& msg)\n{\n io_service_.post(boost::bind(&AsyncUDPClient::DoSend, this, msg));\n}\n\nvoid UDPClient::AsyncUDPClient::DoSend(const std::vector msg)\n{\n write_in_progress_ = !write_msgs_.empty();\n write_msgs_.push_back(msg);\n if (!write_in_progress_) {\n socket_.async_send_to(asio::buffer(write_msgs_.front()), endpoint_,\n boost::bind(&AsyncUDPClient::HandlerWrite, this,\n asio::placeholders::error,\n asio::placeholders::bytes_transferred));\n }\n}\n\nvoid UDPClient::AsyncUDPClient::HandlerWrite(\n const boost::system::error_code& error,\n std::size_t bytes_transferred)\n{\n if (!error) {\n write_msgs_.pop_front();\n if (!write_msgs_.empty()) {\n socket_.async_send_to(asio::buffer(write_msgs_.front()), endpoint_,\n boost::bind(&AsyncUDPClient::HandlerWrite, this,\n asio::placeholders::error,\n asio::placeholders::bytes_transferred));\n } else {\n { \n boost::lock_guard lock(write_progress_mut_);\n write_in_progress_ = false;\n }\n write_progress_cond_.notify_all();\n }\n } else {\n { \n boost::lock_guard lock(write_progress_mut_);\n write_in_progress_ = false;\n }\n write_progress_cond_.notify_all();\n socket_.close();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nUDPClient::UDPClient(const std::string& host, int port)\n: host_(host)\n, port_(port)\n, client_(io_service_, write_progress_cond_, write_progress_mut_)\n, service_is_ready_(false)\n, thread_is_running_(false)\n{\n}\n\nUDPClient::~UDPClient()\n{\n if (thread_is_running_) {\n if (service_is_ready_) {\n io_service_.stop();\n thread_.join();\n } else {\n thread_.timed_join(boost::posix_time::seconds(0));\n }\n }\n}\n\nvoid UDPClient::Send(const std::vector& msg)\n{\n if (!thread_is_running_ && !RunThread()) return;\n client_.Send(msg);\n}\n\nvoid UDPClient::BlockUntilQueueIsEmpty()\n{\n \/\/ Block until IO thread reached a ready state\n while (thread_is_running_ && !service_is_ready_);\n\n boost::unique_lock lock(write_progress_mut_);\n while (client_.WriteInProgress()) {\n write_progress_cond_.wait(lock);\n }\n}\n\nbool UDPClient::RunThread()\n{\n bool success = true;;\n thread_is_running_ = true;\n try {\n thread_ = boost::thread(boost::bind(&UDPClient::Run, this));\n } catch (std::exception& e) {\n std::cerr << \"UDPClient::RunThread(): exception -> \" << e.what() << \"\\n\";\n success = false;\n thread_is_running_ = false;\n }\n\n return success;\n}\n\nvoid UDPClient::Run()\n{\n std::stringstream port_string;\n port_string << port_;\n\n using asio::ip::udp;\n try {\n udp::resolver resolver(io_service_);\n udp::resolver::query query(host_, port_string.str());\n udp::endpoint endpoint = *resolver.resolve(query);\n client_.SetEndpoint(endpoint);\n asio::io_service::work work(io_service_);\n service_is_ready_ = true;\n io_service_.run();\n } catch (std::exception& e) {\n std::cerr << \"UDPClient::Run(): exception -> \" << e.what() << \"\\n\";\n }\n io_service_.reset();\n service_is_ready_ = false;\n thread_is_running_ = false;\n}\n\nReorder initialization list to avoid compiler warning\/\/ Copyright (C) 2011 by Toshiro Yamada\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n#include \"udp_client.hpp\"\n\n#include \n\nusing namespace am;\n\nnamespace asio = boost::asio;\n\n\/\/-----------------------------------------------------------------------------\nUDPClient::AsyncUDPClient::AsyncUDPClient(asio::io_service& io_service,\n boost::condition_variable& cond, boost::mutex& mut)\n: write_in_progress_(false)\n, io_service_(io_service)\n, socket_(io_service_)\n, write_progress_cond_(cond)\n, write_progress_mut_(mut)\n{\n socket_.open(asio::ip::udp::v4());\n}\n\nUDPClient::AsyncUDPClient::~AsyncUDPClient()\n{\n socket_.close();\n}\n\nvoid UDPClient::AsyncUDPClient::SetEndpoint(asio::ip::udp::endpoint& endpoint)\n{\n endpoint_ = endpoint;\n}\n\nvoid UDPClient::AsyncUDPClient::Send(const std::vector& msg)\n{\n io_service_.post(boost::bind(&AsyncUDPClient::DoSend, this, msg));\n}\n\nvoid UDPClient::AsyncUDPClient::DoSend(const std::vector msg)\n{\n write_in_progress_ = !write_msgs_.empty();\n write_msgs_.push_back(msg);\n if (!write_in_progress_) {\n socket_.async_send_to(asio::buffer(write_msgs_.front()), endpoint_,\n boost::bind(&AsyncUDPClient::HandlerWrite, this,\n asio::placeholders::error,\n asio::placeholders::bytes_transferred));\n }\n}\n\nvoid UDPClient::AsyncUDPClient::HandlerWrite(\n const boost::system::error_code& error,\n std::size_t bytes_transferred)\n{\n if (!error) {\n write_msgs_.pop_front();\n if (!write_msgs_.empty()) {\n socket_.async_send_to(asio::buffer(write_msgs_.front()), endpoint_,\n boost::bind(&AsyncUDPClient::HandlerWrite, this,\n asio::placeholders::error,\n asio::placeholders::bytes_transferred));\n } else {\n { \n boost::lock_guard lock(write_progress_mut_);\n write_in_progress_ = false;\n }\n write_progress_cond_.notify_all();\n }\n } else {\n { \n boost::lock_guard lock(write_progress_mut_);\n write_in_progress_ = false;\n }\n write_progress_cond_.notify_all();\n socket_.close();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nUDPClient::UDPClient(const std::string& host, int port)\n: host_(host)\n, port_(port)\n, client_(io_service_, write_progress_cond_, write_progress_mut_)\n, service_is_ready_(false)\n, thread_is_running_(false)\n{\n}\n\nUDPClient::~UDPClient()\n{\n if (thread_is_running_) {\n if (service_is_ready_) {\n io_service_.stop();\n thread_.join();\n } else {\n thread_.timed_join(boost::posix_time::seconds(0));\n }\n }\n}\n\nvoid UDPClient::Send(const std::vector& msg)\n{\n if (!thread_is_running_ && !RunThread()) return;\n client_.Send(msg);\n}\n\nvoid UDPClient::BlockUntilQueueIsEmpty()\n{\n \/\/ Block until IO thread reached a ready state\n while (thread_is_running_ && !service_is_ready_);\n\n boost::unique_lock lock(write_progress_mut_);\n while (client_.WriteInProgress()) {\n write_progress_cond_.wait(lock);\n }\n}\n\nbool UDPClient::RunThread()\n{\n bool success = true;;\n thread_is_running_ = true;\n try {\n thread_ = boost::thread(boost::bind(&UDPClient::Run, this));\n } catch (std::exception& e) {\n std::cerr << \"UDPClient::RunThread(): exception -> \" << e.what() << \"\\n\";\n success = false;\n thread_is_running_ = false;\n }\n\n return success;\n}\n\nvoid UDPClient::Run()\n{\n std::stringstream port_string;\n port_string << port_;\n\n using asio::ip::udp;\n try {\n udp::resolver resolver(io_service_);\n udp::resolver::query query(host_, port_string.str());\n udp::endpoint endpoint = *resolver.resolve(query);\n client_.SetEndpoint(endpoint);\n asio::io_service::work work(io_service_);\n service_is_ready_ = true;\n io_service_.run();\n } catch (std::exception& e) {\n std::cerr << \"UDPClient::Run(): exception -> \" << e.what() << \"\\n\";\n }\n io_service_.reset();\n service_is_ready_ = false;\n thread_is_running_ = false;\n}\n\n<|endoftext|>"} {"text":"\/\/ vpack-node.cpp\n#include \n#include \"nan.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"v8-vpack.h\"\n\nnamespace VPackNode {\n\nusing v8::Context;\nusing v8::Exception;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::Handle;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid decode(const FunctionCallbackInfo& args) {\n Isolate* isolate = args.GetIsolate();\n\n \/\/ Check the number of arguments passed.\n if (args.Length() < 1) {\n \/\/ Throw an Error that is passed back to JavaScript\n isolate->ThrowException(Exception::TypeError(\n String::NewFromUtf8(isolate, \"Wrong number of arguments\")));\n return;\n }\n\n char* buf = node::Buffer::Data(args[0]);\n\n VPackSlice slice(buf);\n \n std::string json = slice.toJson();\n args.GetReturnValue().Set(TRI_VPackToV8(isolate, slice));\n}\n\nvoid encode(const FunctionCallbackInfo& args) {\n Isolate* isolate = args.GetIsolate();\n\n \/\/ Check the number of arguments passed.\n if (args.Length() < 1) {\n \/\/ Throw an Error that is passed back to JavaScript\n isolate->ThrowException(Exception::TypeError(\n String::NewFromUtf8(isolate, \"Wrong number of arguments\")));\n return;\n }\n \n VPackBuilder builder;\n if (TRI_V8ToVPack(isolate, builder, args[0], false) != TRI_ERROR_NO_ERROR) {\n \/\/ Throw an Error that is passed back to JavaScript\n isolate->ThrowException(Exception::TypeError(\n String::NewFromUtf8(isolate, \"Failed transforming to vpack\")));\n return;\n }\n \n auto buffer = builder.buffer();\n args.GetReturnValue().Set(Nan::CopyBuffer(\n (char*)buffer->data(), buffer->size()).ToLocalChecked()\n );\n}\n\nvoid init(Local exports) {\n NODE_SET_METHOD(exports, \"encode\", encode);\n NODE_SET_METHOD(exports, \"decode\", decode);\n}\n\nNODE_MODULE(addon, init)\n\n} \/\/ namespace VPackNode\nRemove useless debug leftovers\/\/ vpack-node.cpp\n#include \n#include \"nan.h\"\n\n#include \n\n#include \n#include \n\n#include \"v8-vpack.h\"\n\nnamespace VPackNode {\n\nusing v8::Context;\nusing v8::Exception;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::Handle;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid decode(const FunctionCallbackInfo& args) {\n Isolate* isolate = args.GetIsolate();\n\n \/\/ Check the number of arguments passed.\n if (args.Length() < 1) {\n \/\/ Throw an Error that is passed back to JavaScript\n isolate->ThrowException(Exception::TypeError(\n String::NewFromUtf8(isolate, \"Wrong number of arguments\")));\n return;\n }\n\n char* buf = node::Buffer::Data(args[0]);\n VPackSlice slice(buf);\n args.GetReturnValue().Set(TRI_VPackToV8(isolate, slice));\n}\n\nvoid encode(const FunctionCallbackInfo& args) {\n Isolate* isolate = args.GetIsolate();\n\n \/\/ Check the number of arguments passed.\n if (args.Length() < 1) {\n \/\/ Throw an Error that is passed back to JavaScript\n isolate->ThrowException(Exception::TypeError(\n String::NewFromUtf8(isolate, \"Wrong number of arguments\")));\n return;\n }\n \n VPackBuilder builder;\n if (TRI_V8ToVPack(isolate, builder, args[0], false) != TRI_ERROR_NO_ERROR) {\n \/\/ Throw an Error that is passed back to JavaScript\n isolate->ThrowException(Exception::TypeError(\n String::NewFromUtf8(isolate, \"Failed transforming to vpack\")));\n return;\n }\n \n auto buffer = builder.buffer();\n args.GetReturnValue().Set(Nan::CopyBuffer(\n (char*)buffer->data(), buffer->size()).ToLocalChecked()\n );\n}\n\nvoid init(Local exports) {\n NODE_SET_METHOD(exports, \"encode\", encode);\n NODE_SET_METHOD(exports, \"decode\", decode);\n}\n\nNODE_MODULE(addon, init)\n\n} \/\/ namespace VPackNode\n<|endoftext|>"} {"text":"\/\/ Copyright 2018 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"bloaty.h\"\n\n#include \"absl\/strings\/substitute.h\"\n\nABSL_ATTRIBUTE_NORETURN\nstatic void Throw(const char *str, int line) {\n throw bloaty::Error(str, __FILE__, line);\n}\n\n#define THROW(msg) Throw(msg, __LINE__)\n#define THROWF(...) Throw(absl::Substitute(__VA_ARGS__).c_str(), __LINE__)\n#define WARN(x) fprintf(stderr, \"bloaty: %s\\n\", x);\n\nusing absl::string_view;\n\nnamespace bloaty {\nnamespace wasm {\n\ntemplate \nT ReadMemcpy(string_view* data) {\n T ret;\n if (data->size() < sizeof(T)) {\n THROW(\"premature EOF reading fixed-length wasm data\");\n }\n memcpy(&ret, data->data(), sizeof(T));\n data->remove_prefix(sizeof(T));\n return ret;\n}\n\nuint64_t ReadLEB128Internal(bool is_signed, size_t size, string_view* data) {\n uint64_t ret = 0;\n int shift = 0;\n int maxshift = 70;\n const char* ptr = data->data();\n const char* limit = ptr + data->size();\n\n while (ptr < limit && shift < maxshift) {\n char byte = *(ptr++);\n ret |= static_cast(byte & 0x7f) << shift;\n shift += 7;\n if ((byte & 0x80) == 0) {\n data->remove_prefix(ptr - data->data());\n if (is_signed && shift < size && (byte & 0x40)) {\n ret |= -(1ULL << shift);\n }\n return ret;\n }\n }\n\n THROW(\"corrupt wasm data, unterminated LEB128\");\n}\n\nbool ReadVarUInt1(string_view* data) {\n return static_cast(ReadLEB128Internal(false, 1, data));\n}\n\nuint8_t ReadVarUInt7(string_view* data) {\n return static_cast(ReadLEB128Internal(false, 7, data));\n}\n\nuint32_t ReadVarUInt32(string_view* data) {\n return static_cast(ReadLEB128Internal(false, 32, data));\n}\n\nint8_t ReadVarint7(string_view* data) {\n return static_cast(ReadLEB128Internal(true, 7, data));\n}\n\nstring_view ReadPiece(size_t bytes, string_view* data) {\n if(data->size() < bytes) {\n THROW(\"premature EOF reading variable-length DWARF data\");\n }\n string_view ret = data->substr(0, bytes);\n data->remove_prefix(bytes);\n return ret;\n}\n\nbool ReadMagic(string_view* data) {\n const uint32_t wasm_magic = 0x6d736100;\n uint32_t magic = ReadMemcpy(data);\n\n if (magic != wasm_magic) {\n return false;\n }\n\n \/\/ TODO(haberman): do we need to fail if this is >1?\n uint32_t version = ReadMemcpy(data);\n (void)version;\n\n return true;\n}\n\nclass Section {\n public:\n uint32_t id;\n std::string name;\n string_view data;\n string_view contents;\n\n static Section Read(string_view* data_param) {\n Section ret;\n string_view data = *data_param;\n string_view section_data = data;\n\n ret.id = ReadVarUInt7(&data);\n uint32_t size = ReadVarUInt32(&data);\n ret.contents = ReadPiece(size, &data);\n size_t header_size = ret.contents.data() - section_data.data();\n ret.data = section_data.substr(0, size + header_size);\n\n if (ret.id == 0) {\n uint32_t name_len = ReadVarUInt32(&ret.contents);\n ret.name = std::string(ReadPiece(name_len, &ret.contents));\n } else if (ret.id <= 11) {\n ret.name = names[ret.id];\n } else {\n THROWF(\"Unknown section id: $0\", ret.id);\n }\n\n *data_param = data;\n return ret;\n }\n\n enum Name {\n kType = 1,\n kImport = 2,\n kFunction = 3,\n kTable = 4,\n kMemory = 5,\n kGlobal = 6,\n kExport = 7,\n kStart = 8,\n kElement = 9,\n kCode = 10,\n kData = 11,\n };\n\n static const char* names[];\n};\n\nconst char* Section::names[] = {\n \"\", \/\/ 0\n \"Type\", \/\/ 1\n \"Import\", \/\/ 2\n \"Function\", \/\/ 3\n \"Table\", \/\/ 4\n \"Memory\", \/\/ 5\n \"Global\", \/\/ 6\n \"Export\", \/\/ 7\n \"Start\", \/\/ 8\n \"Element\", \/\/ 9\n \"Code\", \/\/ 10\n \"Data\", \/\/ 11\n};\n\nstruct ExternalKind {\n enum Kind {\n kFunction = 0,\n kTable = 1,\n kMemory = 2,\n kGlobal = 3,\n };\n};\n\ntemplate \nvoid ForEachSection(string_view file, Func&& section_func) {\n string_view data = file;\n ReadMagic(&data);\n\n while (!data.empty()) {\n Section section = Section::Read(&data);\n section_func(section);\n }\n}\n\nvoid ParseSections(RangeSink* sink) {\n ForEachSection(sink->input_file().data(), [sink](const Section& section) {\n sink->AddFileRange(\"wasm_sections\", section.name, section.data);\n });\n}\n\ntypedef std::unordered_map FuncNames;\n\nvoid ReadFunctionNames(const Section& section, FuncNames* names,\n RangeSink* sink) {\n enum class NameType {\n kModule = 0,\n kFunction = 1,\n kLocal = 2,\n };\n\n string_view data = section.contents;\n\n while (!data.empty()) {\n char type = ReadVarUInt7(&data);\n uint32_t size = ReadVarUInt32(&data);\n string_view section = data.substr(0, size);\n data = data.substr(size);\n\n if (static_cast(type) == NameType::kFunction) {\n uint32_t count = ReadVarUInt32(§ion);\n for (uint32_t i = 0; i < count; i++) {\n string_view entry = section;\n uint32_t index = ReadVarUInt32(§ion);\n uint32_t name_len = ReadVarUInt32(§ion);\n string_view name = ReadPiece(name_len, §ion);\n entry = entry.substr(0, name.data() - entry.data() + name.size());\n sink->AddFileRange(\"wasm_funcname\", name, entry);\n (*names)[index] = std::string(name);\n }\n }\n }\n}\n\nint ReadValueType(string_view* data) {\n return ReadVarint7(data);\n}\n\nint ReadElemType(string_view* data) {\n return ReadVarint7(data);\n}\n\nvoid ReadResizableLimits(string_view* data) {\n auto flags = ReadVarUInt1(data);\n ReadVarUInt32(data);\n if (flags) {\n ReadVarUInt32(data);\n }\n}\n\nvoid ReadGlobalType(string_view* data) {\n ReadValueType(data);\n ReadVarUInt1(data);\n}\n\nvoid ReadTableType(string_view* data) {\n ReadElemType(data);\n ReadResizableLimits(data);\n}\n\nvoid ReadMemoryType(string_view* data) {\n ReadResizableLimits(data);\n}\n\nuint32_t GetNumFunctionImports(const Section& section) {\n assert(section.id == Section::kImport);\n string_view data = section.contents;\n\n uint32_t count = ReadVarUInt32(&data);\n uint32_t func_count = 0;\n\n for (uint32_t i = 0; i < count; i++) {\n uint32_t module_len = ReadVarUInt32(&data);\n ReadPiece(module_len, &data);\n uint32_t field_len = ReadVarUInt32(&data);\n ReadPiece(field_len, &data);\n auto kind = ReadMemcpy(&data);\n\n switch (kind) {\n case ExternalKind::kFunction:\n func_count++;\n ReadVarUInt32(&data);\n break;\n case ExternalKind::kTable:\n ReadTableType(&data);\n break;\n case ExternalKind::kMemory:\n ReadMemoryType(&data);\n break;\n case ExternalKind::kGlobal:\n ReadGlobalType(&data);\n break;\n default:\n THROWF(\"Unrecognized import kind: $0\", kind);\n }\n }\n\n return func_count;\n}\n\nvoid ReadCodeSection(const Section& section, const FuncNames& names,\n uint32_t num_imports, RangeSink* sink) {\n string_view data = section.contents;\n\n uint32_t count = ReadVarUInt32(&data);\n\n for (uint32_t i = 0; i < count; i++) {\n string_view func = data;\n uint32_t size = ReadVarUInt32(&data);\n uint32_t total_size = size + (data.data() - func.data());\n\n func = func.substr(0, total_size);\n data = data.substr(size);\n\n auto iter = names.find(num_imports + i);\n\n if (iter == names.end()) {\n std::string name = \"func[\" + std::to_string(i) + \"]\";\n sink->AddFileRange(\"wasm_function\", name, func);\n } else {\n sink->AddFileRange(\"wasm_function\", ItaniumDemangle(iter->second, sink->data_source()), func);\n }\n }\n}\n\nvoid ParseSymbols(RangeSink* sink) {\n \/\/ First pass: read the custom naming section to get function names.\n std::unordered_map func_names;\n uint32_t num_imports = 0;\n\n ForEachSection(sink->input_file().data(),\n [&func_names, sink](const Section& section) {\n if (section.name == \"name\") {\n ReadFunctionNames(section, &func_names, sink);\n }\n });\n\n \/\/ Second pass: read the function\/code sections.\n ForEachSection(sink->input_file().data(),\n [&func_names, &num_imports, sink](const Section& section) {\n if (section.id == Section::kImport) {\n num_imports = GetNumFunctionImports(section);\n } else if (section.id == Section::kCode) {\n ReadCodeSection(section, func_names, num_imports, sink);\n }\n });\n}\n\nvoid AddWebAssemblyFallback(RangeSink* sink) {\n ForEachSection(sink->input_file().data(), [sink](const Section& section) {\n std::string name2 =\n std::string(\"[section \") + std::string(section.name) + std::string(\"]\");\n sink->AddFileRange(\"wasm_overhead\", name2, section.data);\n });\n sink->AddFileRange(\"wasm_overhead\", \"[WASM Header]\",\n sink->input_file().data().substr(0, 8));\n}\n\nclass WebAssemblyObjectFile : public ObjectFile {\n public:\n WebAssemblyObjectFile(std::unique_ptr file_data)\n : ObjectFile(std::move(file_data)) {}\n\n std::string GetBuildId() const override {\n \/\/ TODO(haberman): does WebAssembly support this?\n return std::string();\n }\n\n void ProcessFile(const std::vector& sinks) const override {\n for (auto sink : sinks) {\n switch (sink->data_source()) {\n case DataSource::kSegments:\n case DataSource::kSections:\n ParseSections(sink);\n break;\n case DataSource::kSymbols:\n case DataSource::kRawSymbols:\n case DataSource::kShortSymbols:\n case DataSource::kFullSymbols:\n ParseSymbols(sink);\n break;\n case DataSource::kArchiveMembers:\n case DataSource::kCompileUnits:\n case DataSource::kInlines:\n default:\n THROW(\"WebAssembly doesn't support this data source\");\n }\n AddWebAssemblyFallback(sink);\n }\n }\n\n bool GetDisassemblyInfo(absl::string_view \/*symbol*\/,\n DataSource \/*symbol_source*\/,\n DisassemblyInfo* \/*info*\/) const override {\n WARN(\"WebAssembly files do not support disassembly yet\");\n return false;\n }\n};\n\n} \/\/ namespace wasm\n\nstd::unique_ptr TryOpenWebAssemblyFile(\n std::unique_ptr& file) {\n string_view data = file->data();\n if (wasm::ReadMagic(&data)) {\n return std::unique_ptr(\n new wasm::WebAssemblyObjectFile(std::move(file)));\n }\n\n return nullptr;\n}\n\n} \/\/ namespace bloaty\nRecognize new WASM sections\/\/ Copyright 2018 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"bloaty.h\"\n\n#include \"absl\/strings\/substitute.h\"\n\nABSL_ATTRIBUTE_NORETURN\nstatic void Throw(const char *str, int line) {\n throw bloaty::Error(str, __FILE__, line);\n}\n\n#define THROW(msg) Throw(msg, __LINE__)\n#define THROWF(...) Throw(absl::Substitute(__VA_ARGS__).c_str(), __LINE__)\n#define WARN(x) fprintf(stderr, \"bloaty: %s\\n\", x);\n\nusing absl::string_view;\n\nnamespace bloaty {\nnamespace wasm {\n\ntemplate \nT ReadMemcpy(string_view* data) {\n T ret;\n if (data->size() < sizeof(T)) {\n THROW(\"premature EOF reading fixed-length wasm data\");\n }\n memcpy(&ret, data->data(), sizeof(T));\n data->remove_prefix(sizeof(T));\n return ret;\n}\n\nuint64_t ReadLEB128Internal(bool is_signed, size_t size, string_view* data) {\n uint64_t ret = 0;\n int shift = 0;\n int maxshift = 70;\n const char* ptr = data->data();\n const char* limit = ptr + data->size();\n\n while (ptr < limit && shift < maxshift) {\n char byte = *(ptr++);\n ret |= static_cast(byte & 0x7f) << shift;\n shift += 7;\n if ((byte & 0x80) == 0) {\n data->remove_prefix(ptr - data->data());\n if (is_signed && shift < size && (byte & 0x40)) {\n ret |= -(1ULL << shift);\n }\n return ret;\n }\n }\n\n THROW(\"corrupt wasm data, unterminated LEB128\");\n}\n\nbool ReadVarUInt1(string_view* data) {\n return static_cast(ReadLEB128Internal(false, 1, data));\n}\n\nuint8_t ReadVarUInt7(string_view* data) {\n return static_cast(ReadLEB128Internal(false, 7, data));\n}\n\nuint32_t ReadVarUInt32(string_view* data) {\n return static_cast(ReadLEB128Internal(false, 32, data));\n}\n\nint8_t ReadVarint7(string_view* data) {\n return static_cast(ReadLEB128Internal(true, 7, data));\n}\n\nstring_view ReadPiece(size_t bytes, string_view* data) {\n if(data->size() < bytes) {\n THROW(\"premature EOF reading variable-length DWARF data\");\n }\n string_view ret = data->substr(0, bytes);\n data->remove_prefix(bytes);\n return ret;\n}\n\nbool ReadMagic(string_view* data) {\n const uint32_t wasm_magic = 0x6d736100;\n uint32_t magic = ReadMemcpy(data);\n\n if (magic != wasm_magic) {\n return false;\n }\n\n \/\/ TODO(haberman): do we need to fail if this is >1?\n uint32_t version = ReadMemcpy(data);\n (void)version;\n\n return true;\n}\n\nclass Section {\n public:\n uint32_t id;\n std::string name;\n string_view data;\n string_view contents;\n\n static Section Read(string_view* data_param) {\n Section ret;\n string_view data = *data_param;\n string_view section_data = data;\n\n ret.id = ReadVarUInt7(&data);\n uint32_t size = ReadVarUInt32(&data);\n ret.contents = ReadPiece(size, &data);\n size_t header_size = ret.contents.data() - section_data.data();\n ret.data = section_data.substr(0, size + header_size);\n\n if (ret.id == 0) {\n uint32_t name_len = ReadVarUInt32(&ret.contents);\n ret.name = std::string(ReadPiece(name_len, &ret.contents));\n } else if (ret.id <= 13) {\n ret.name = names[ret.id];\n } else {\n THROWF(\"Unknown section id: $0\", ret.id);\n }\n\n *data_param = data;\n return ret;\n }\n\n enum Name {\n kType = 1,\n kImport = 2,\n kFunction = 3,\n kTable = 4,\n kMemory = 5,\n kGlobal = 6,\n kExport = 7,\n kStart = 8,\n kElement = 9,\n kCode = 10,\n kData = 11,\n kDataCount = 12,\n kEvent = 13,\n };\n\n static const char* names[];\n};\n\nconst char* Section::names[] = {\n \"\", \/\/ 0\n \"Type\", \/\/ 1\n \"Import\", \/\/ 2\n \"Function\", \/\/ 3\n \"Table\", \/\/ 4\n \"Memory\", \/\/ 5\n \"Global\", \/\/ 6\n \"Export\", \/\/ 7\n \"Start\", \/\/ 8\n \"Element\", \/\/ 9\n \"Code\", \/\/ 10\n \"Data\", \/\/ 11\n \"DataCount\", \/\/ 12\n \"Event\", \/\/ 13\n};\n\nstruct ExternalKind {\n enum Kind {\n kFunction = 0,\n kTable = 1,\n kMemory = 2,\n kGlobal = 3,\n };\n};\n\ntemplate \nvoid ForEachSection(string_view file, Func&& section_func) {\n string_view data = file;\n ReadMagic(&data);\n\n while (!data.empty()) {\n Section section = Section::Read(&data);\n section_func(section);\n }\n}\n\nvoid ParseSections(RangeSink* sink) {\n ForEachSection(sink->input_file().data(), [sink](const Section& section) {\n sink->AddFileRange(\"wasm_sections\", section.name, section.data);\n });\n}\n\ntypedef std::unordered_map FuncNames;\n\nvoid ReadFunctionNames(const Section& section, FuncNames* names,\n RangeSink* sink) {\n enum class NameType {\n kModule = 0,\n kFunction = 1,\n kLocal = 2,\n };\n\n string_view data = section.contents;\n\n while (!data.empty()) {\n char type = ReadVarUInt7(&data);\n uint32_t size = ReadVarUInt32(&data);\n string_view section = data.substr(0, size);\n data = data.substr(size);\n\n if (static_cast(type) == NameType::kFunction) {\n uint32_t count = ReadVarUInt32(§ion);\n for (uint32_t i = 0; i < count; i++) {\n string_view entry = section;\n uint32_t index = ReadVarUInt32(§ion);\n uint32_t name_len = ReadVarUInt32(§ion);\n string_view name = ReadPiece(name_len, §ion);\n entry = entry.substr(0, name.data() - entry.data() + name.size());\n sink->AddFileRange(\"wasm_funcname\", name, entry);\n (*names)[index] = std::string(name);\n }\n }\n }\n}\n\nint ReadValueType(string_view* data) {\n return ReadVarint7(data);\n}\n\nint ReadElemType(string_view* data) {\n return ReadVarint7(data);\n}\n\nvoid ReadResizableLimits(string_view* data) {\n auto flags = ReadVarUInt1(data);\n ReadVarUInt32(data);\n if (flags) {\n ReadVarUInt32(data);\n }\n}\n\nvoid ReadGlobalType(string_view* data) {\n ReadValueType(data);\n ReadVarUInt1(data);\n}\n\nvoid ReadTableType(string_view* data) {\n ReadElemType(data);\n ReadResizableLimits(data);\n}\n\nvoid ReadMemoryType(string_view* data) {\n ReadResizableLimits(data);\n}\n\nuint32_t GetNumFunctionImports(const Section& section) {\n assert(section.id == Section::kImport);\n string_view data = section.contents;\n\n uint32_t count = ReadVarUInt32(&data);\n uint32_t func_count = 0;\n\n for (uint32_t i = 0; i < count; i++) {\n uint32_t module_len = ReadVarUInt32(&data);\n ReadPiece(module_len, &data);\n uint32_t field_len = ReadVarUInt32(&data);\n ReadPiece(field_len, &data);\n auto kind = ReadMemcpy(&data);\n\n switch (kind) {\n case ExternalKind::kFunction:\n func_count++;\n ReadVarUInt32(&data);\n break;\n case ExternalKind::kTable:\n ReadTableType(&data);\n break;\n case ExternalKind::kMemory:\n ReadMemoryType(&data);\n break;\n case ExternalKind::kGlobal:\n ReadGlobalType(&data);\n break;\n default:\n THROWF(\"Unrecognized import kind: $0\", kind);\n }\n }\n\n return func_count;\n}\n\nvoid ReadCodeSection(const Section& section, const FuncNames& names,\n uint32_t num_imports, RangeSink* sink) {\n string_view data = section.contents;\n\n uint32_t count = ReadVarUInt32(&data);\n\n for (uint32_t i = 0; i < count; i++) {\n string_view func = data;\n uint32_t size = ReadVarUInt32(&data);\n uint32_t total_size = size + (data.data() - func.data());\n\n func = func.substr(0, total_size);\n data = data.substr(size);\n\n auto iter = names.find(num_imports + i);\n\n if (iter == names.end()) {\n std::string name = \"func[\" + std::to_string(i) + \"]\";\n sink->AddFileRange(\"wasm_function\", name, func);\n } else {\n sink->AddFileRange(\"wasm_function\", ItaniumDemangle(iter->second, sink->data_source()), func);\n }\n }\n}\n\nvoid ParseSymbols(RangeSink* sink) {\n \/\/ First pass: read the custom naming section to get function names.\n std::unordered_map func_names;\n uint32_t num_imports = 0;\n\n ForEachSection(sink->input_file().data(),\n [&func_names, sink](const Section& section) {\n if (section.name == \"name\") {\n ReadFunctionNames(section, &func_names, sink);\n }\n });\n\n \/\/ Second pass: read the function\/code sections.\n ForEachSection(sink->input_file().data(),\n [&func_names, &num_imports, sink](const Section& section) {\n if (section.id == Section::kImport) {\n num_imports = GetNumFunctionImports(section);\n } else if (section.id == Section::kCode) {\n ReadCodeSection(section, func_names, num_imports, sink);\n }\n });\n}\n\nvoid AddWebAssemblyFallback(RangeSink* sink) {\n ForEachSection(sink->input_file().data(), [sink](const Section& section) {\n std::string name2 =\n std::string(\"[section \") + std::string(section.name) + std::string(\"]\");\n sink->AddFileRange(\"wasm_overhead\", name2, section.data);\n });\n sink->AddFileRange(\"wasm_overhead\", \"[WASM Header]\",\n sink->input_file().data().substr(0, 8));\n}\n\nclass WebAssemblyObjectFile : public ObjectFile {\n public:\n WebAssemblyObjectFile(std::unique_ptr file_data)\n : ObjectFile(std::move(file_data)) {}\n\n std::string GetBuildId() const override {\n \/\/ TODO(haberman): does WebAssembly support this?\n return std::string();\n }\n\n void ProcessFile(const std::vector& sinks) const override {\n for (auto sink : sinks) {\n switch (sink->data_source()) {\n case DataSource::kSegments:\n case DataSource::kSections:\n ParseSections(sink);\n break;\n case DataSource::kSymbols:\n case DataSource::kRawSymbols:\n case DataSource::kShortSymbols:\n case DataSource::kFullSymbols:\n ParseSymbols(sink);\n break;\n case DataSource::kArchiveMembers:\n case DataSource::kCompileUnits:\n case DataSource::kInlines:\n default:\n THROW(\"WebAssembly doesn't support this data source\");\n }\n AddWebAssemblyFallback(sink);\n }\n }\n\n bool GetDisassemblyInfo(absl::string_view \/*symbol*\/,\n DataSource \/*symbol_source*\/,\n DisassemblyInfo* \/*info*\/) const override {\n WARN(\"WebAssembly files do not support disassembly yet\");\n return false;\n }\n};\n\n} \/\/ namespace wasm\n\nstd::unique_ptr TryOpenWebAssemblyFile(\n std::unique_ptr& file) {\n string_view data = file->data();\n if (wasm::ReadMagic(&data)) {\n return std::unique_ptr(\n new wasm::WebAssemblyObjectFile(std::move(file)));\n }\n\n return nullptr;\n}\n\n} \/\/ namespace bloaty\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \n#include \n\n\/\/ for debug only\n#include \n#include \n\nusing namespace std;\n\n\/**\n* Конструктор потока\n*\/\nXMPPStream::XMPPStream(XMPPServer *srv, int sock): AsyncXMLStream(sock), server(srv), XMLWriter(1024)\n{\n\tdepth = 0;\n\tbuilder = new ATTagBuilder();\n}\n\n\/**\n* Деструктор потока\n*\/\nXMPPStream::~XMPPStream()\n{\n\tdelete builder;\n}\n\n\/**\n* Запись XML\n*\/\nvoid XMPPStream::onWriteXML(const char *data, size_t len)\n{\n\t\/\/cout << string(data, len) << endl;\n\tint r = write(data, len);\n\tif ( r != len ) onError(\"write fault\");\n\tcout << \"written: \" << string(data, len) << endl;\n}\n\n\/**\n* Событие готовности к записи\n*\n* Вызывается, когда в поток готов принять\n* данные для записи без блокировки\n*\/\nvoid XMPPStream::onWrite()\n{\n\tcerr << \"not implemented XMPPStream::onWrite()\" << endl;\n}\n\n\/**\n* Событие закрытие соединения\n*\n* Вызывается если peer закрыл соединение\n*\/\nvoid XMPPStream::onShutdown()\n{\n\tAsyncXMLStream::onShutdown();\n\tXMLWriter::flush();\n\tcerr << \"[TestStream]: peer shutdown connection\" << endl;\n\tif ( shutdown(fd, SHUT_RDWR) != 0 )\n\t{\n\t\tstderror();\n\t}\n\tserver->daemon->removeObject(this);\n\tdelete this;\n}\n\n\/**\n* Обработчик открытия тега\n*\/\nvoid XMPPStream::onStartElement(const std::string &name, const attributtes_t &attributes)\n{\n\tdepth ++;\n\tswitch ( depth )\n\t{\n\tcase 1:\n\t\tonStartStream(name, attributes);\n\t\tbreak;\n\tcase 2: \/\/ начало станзы\n\t\tbuilder->startElement(name, attributes, depth);\n\tbreak;\n\tdefault: \/\/ добавить тег в станзу\n\t\tbuilder->startElement(name, attributes, depth);\n\t\tcout << \"onStartElement(\" << name << \")\" << endl;\n\t}\n}\n\n\/**\n* Обработчик символьных данных\n*\/\nvoid XMPPStream::onCharacterData(const std::string &cdata)\n{\n\tbuilder->characterData(cdata);\n\tcout << \"cdata: \" << cdata << endl;\n}\n\n\/**\n* Обработчик закрытия тега\n*\/\nvoid XMPPStream::onEndElement(const std::string &name)\n{\n\tswitch (depth)\n\t{\n\tcase 1:\n\t\tonEndStream();\n\t\tbreak;\n\tcase 2:\n\t\tbuilder->endElement(name);\n\t\tonStanza(builder->fetchResult());\n\t\tbreak;\n\tdefault:\n\t\tbuilder->endElement(name);\n\t\tcout << \"onEndElement(\" << name << \")\" << endl;\n\t}\n\tdepth --;\n}\n\n\/**\n* Обработчик станз\n*\/\nvoid XMPPStream::onStanza(ATXmlTag *tag)\n{\n\tcout << \"stanza: \" << tag->name() << endl;\n\tif ( tag->name() == \"auth\" ) onAuthStanza(tag);\n\telse ; \/\/ ...\n}\n\n\/**\n* Обработчик авторизации\n*\/\nvoid XMPPStream::onAuthStanza(ATXmlTag *tag)\n{\n\tstring password = nanosoft::base64_decode(tag->getCharacterData());\n\t\/\/cout << \"auth password: \" << password << endl;\n\t\n\tstartElement(\"success\");\n\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-sasl\");\n\tendElement(\"success\");\n\tflush();\n\t\n\tresetWriter();\n\tstate = authorized;\n\tresetParser();\n\tdepth = 0;\n}\n\n\/**\n* Событие: начало потока\n*\/\nvoid XMPPStream::onStartStream(const std::string &name, const attributes_t &attributes)\n{\n\tcout << \"new stream\" << endl;\n\tinitXML();\n\tstartElement(\"stream:stream\");\n\tsetAttribute(\"xmlns\", \"jabber:client\");\n\tsetAttribute(\"xmlns:stream\", \"http:\/\/etherx.jabber.org\/streams\");\n\tsetAttribute(\"id\", \"123456\"); \/\/ Требования к id — непредсказуемость и уникальность\n\tsetAttribute(\"from\", \"localhost\");\n\tsetAttribute(\"version\", \"1.0\");\n\tsetAttribute(\"xml:lang\", \"en\");\n\t\n\tstartElement(\"stream:features\");\n\tif ( state == init )\n\t{\n\t\tstartElement(\"mechanisms\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-sasl\");\n\t\t\taddElement(\"mechanism\", \"PLAIN\");\n\t\tendElement(\"mechanisms\");\n\t\tstartElement(\"register\");\n\t\t\tsetAttribute(\"xmlns\", \"http:\/\/jabber.org\/features\/iq-register\");\n\t\tendElement(\"register\");\n\t}\n\telse\n\t{\n\t\tstartElement(\"bind\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-bind\");\n\t\tendElement(\"bind\");\n\t\tstartElement(\"session\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-session\");\n\t\tendElement(\"session\");\n\t}\n\tendElement(\"stream:features\");\n\tflush();\n}\n\n\/**\n* Событие: конец потока\n*\/\nvoid XMPPStream::onEndStream()\n{\n\tcout << \"session closed\" << endl;\n\tendElement(\"stream:stream\");\n}\nвыделение в консоли исходящих сообщений\n#include \n#include \n#include \n#include \n\n\/\/ for debug only\n#include \n#include \n\nusing namespace std;\n\n\/**\n* Конструктор потока\n*\/\nXMPPStream::XMPPStream(XMPPServer *srv, int sock): AsyncXMLStream(sock), server(srv), XMLWriter(1024)\n{\n\tdepth = 0;\n\tbuilder = new ATTagBuilder();\n}\n\n\/**\n* Деструктор потока\n*\/\nXMPPStream::~XMPPStream()\n{\n\tdelete builder;\n}\n\n\/**\n* Запись XML\n*\/\nvoid XMPPStream::onWriteXML(const char *data, size_t len)\n{\n\tint r = write(data, len);\n\tif ( r != len ) onError(\"write fault\");\n\tcout << \"written: \\033[22;34m\" << string(data, len) << \"\\033[0m\\n\";\n}\n\n\/**\n* Событие готовности к записи\n*\n* Вызывается, когда в поток готов принять\n* данные для записи без блокировки\n*\/\nvoid XMPPStream::onWrite()\n{\n\tcerr << \"not implemented XMPPStream::onWrite()\" << endl;\n}\n\n\/**\n* Событие закрытие соединения\n*\n* Вызывается если peer закрыл соединение\n*\/\nvoid XMPPStream::onShutdown()\n{\n\tAsyncXMLStream::onShutdown();\n\tXMLWriter::flush();\n\tcerr << \"[TestStream]: peer shutdown connection\" << endl;\n\tif ( shutdown(fd, SHUT_RDWR) != 0 )\n\t{\n\t\tstderror();\n\t}\n\tserver->daemon->removeObject(this);\n\tdelete this;\n}\n\n\/**\n* Обработчик открытия тега\n*\/\nvoid XMPPStream::onStartElement(const std::string &name, const attributtes_t &attributes)\n{\n\tdepth ++;\n\tswitch ( depth )\n\t{\n\tcase 1:\n\t\tonStartStream(name, attributes);\n\t\tbreak;\n\tcase 2: \/\/ начало станзы\n\t\tbuilder->startElement(name, attributes, depth);\n\tbreak;\n\tdefault: \/\/ добавить тег в станзу\n\t\tbuilder->startElement(name, attributes, depth);\n\t\tcout << \"onStartElement(\" << name << \")\" << endl;\n\t}\n}\n\n\/**\n* Обработчик символьных данных\n*\/\nvoid XMPPStream::onCharacterData(const std::string &cdata)\n{\n\tbuilder->characterData(cdata);\n\tcout << \"cdata: \" << cdata << endl;\n}\n\n\/**\n* Обработчик закрытия тега\n*\/\nvoid XMPPStream::onEndElement(const std::string &name)\n{\n\tswitch (depth)\n\t{\n\tcase 1:\n\t\tonEndStream();\n\t\tbreak;\n\tcase 2:\n\t\tbuilder->endElement(name);\n\t\tonStanza(builder->fetchResult());\n\t\tbreak;\n\tdefault:\n\t\tbuilder->endElement(name);\n\t\tcout << \"onEndElement(\" << name << \")\" << endl;\n\t}\n\tdepth --;\n}\n\n\/**\n* Обработчик станз\n*\/\nvoid XMPPStream::onStanza(ATXmlTag *tag)\n{\n\tcout << \"stanza: \" << tag->name() << endl;\n\tif ( tag->name() == \"auth\" ) onAuthStanza(tag);\n\telse ; \/\/ ...\n}\n\n\/**\n* Обработчик авторизации\n*\/\nvoid XMPPStream::onAuthStanza(ATXmlTag *tag)\n{\n\tstring password = nanosoft::base64_decode(tag->getCharacterData());\n\t\/\/cout << \"auth password: \" << password << endl;\n\t\n\tstartElement(\"success\");\n\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-sasl\");\n\tendElement(\"success\");\n\tflush();\n\t\n\tresetWriter();\n\tstate = authorized;\n\tresetParser();\n\tdepth = 0;\n}\n\n\/**\n* Событие: начало потока\n*\/\nvoid XMPPStream::onStartStream(const std::string &name, const attributes_t &attributes)\n{\n\tcout << \"new stream\" << endl;\n\tinitXML();\n\tstartElement(\"stream:stream\");\n\tsetAttribute(\"xmlns\", \"jabber:client\");\n\tsetAttribute(\"xmlns:stream\", \"http:\/\/etherx.jabber.org\/streams\");\n\tsetAttribute(\"id\", \"123456\"); \/\/ Требования к id — непредсказуемость и уникальность\n\tsetAttribute(\"from\", \"localhost\");\n\tsetAttribute(\"version\", \"1.0\");\n\tsetAttribute(\"xml:lang\", \"en\");\n\t\n\tstartElement(\"stream:features\");\n\tif ( state == init )\n\t{\n\t\tstartElement(\"mechanisms\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-sasl\");\n\t\t\taddElement(\"mechanism\", \"PLAIN\");\n\t\tendElement(\"mechanisms\");\n\t\tstartElement(\"register\");\n\t\t\tsetAttribute(\"xmlns\", \"http:\/\/jabber.org\/features\/iq-register\");\n\t\tendElement(\"register\");\n\t}\n\telse\n\t{\n\t\tstartElement(\"bind\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-bind\");\n\t\tendElement(\"bind\");\n\t\tstartElement(\"session\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-session\");\n\t\tendElement(\"session\");\n\t}\n\tendElement(\"stream:features\");\n\tflush();\n}\n\n\/**\n* Событие: конец потока\n*\/\nvoid XMPPStream::onEndStream()\n{\n\tcout << \"session closed\" << endl;\n\tendElement(\"stream:stream\");\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ Author: yanshiguang02@baidu.com\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"dfs.h\"\n\nconst char* so_path = \".\/bfs_wrapper.so\";\n\/\/const char* dfs_conf = \"yq01-tera60.yq01:8828\";\nconst char* dfs_conf = \"127.0.0.1:8828\";\n\nconst std::string test_path(\"\/test\");\n\nTEST(TERA_SO_TEST, TERA_SO) {\n dlerror();\n void* handle = dlopen(so_path, RTLD_LAZY | RTLD_DEEPBIND | RTLD_LOCAL);\n const char* err = dlerror();\n ASSERT_TRUE(handle != NULL);\n\n leveldb::DfsCreator creator = (leveldb::DfsCreator)dlsym(handle, \"NewDfs\");\n err = dlerror();\n ASSERT_TRUE(err == NULL);\n\n leveldb::Dfs* dfs = (*creator)(dfs_conf);\n \n \/\/\/ Create dir\n ASSERT_TRUE(dfs != NULL);\n ASSERT_TRUE(0 == dfs->CreateDirectory(test_path));\n\n \/\/\/ Open\n std::string file1 = test_path + \"\/file1\";\n std::string file2 = test_path + \"\/file2\";\n std::string file3 = test_path + \"\/file3\";\n\n if (0 == dfs->Exists(file1)) {\n ASSERT_TRUE(0 == dfs->Delete(file1));\n }\n\n leveldb::DfsFile* fp = dfs->OpenFile(file1, leveldb::WRONLY);\n ASSERT_TRUE(fp != NULL);\n \n \/\/\/ Write&Sync\n char content1[] = \"File1 content\";\n char content2[] = \"Content for read\";\n const int c1len = sizeof(content1);\n const int c2len = sizeof(content2);\n ASSERT_TRUE(c1len == fp->Write(content1, c1len));\n ASSERT_TRUE(0 == fp->Flush());\n ASSERT_TRUE(0 == fp->Sync());\n ASSERT_TRUE(c2len == fp->Write(content2, c2len));\n\n long lbuf[1024];\n int buflen = sizeof(lbuf);\n int bufnum = 1024;\n for (int i = 0; i < 1024; i++) {\n for (int j = 0; j < 1024; j++) {\n lbuf[j] = ((rand() << 16) | rand());\n }\n buflen = sizeof(lbuf);\n ASSERT_TRUE(buflen == fp->Write(reinterpret_cast(lbuf), buflen));\n }\n\n \/\/\/ Close\n ASSERT_TRUE(0 == fp->CloseFile());\n delete fp;\n fp = NULL;\n\n \/\/\/ Rename\n if (0 == dfs->Exists(file2)) {\n ASSERT_TRUE(0 == dfs->Delete(file2));\n }\n ASSERT_TRUE(0 == dfs->Rename(file1, file2));\n ASSERT_TRUE(0 == dfs->Exists(file2));\n ASSERT_TRUE(0 != dfs->Exists(file1));\n\n \/\/\/ GetFileSize\n uint64_t fsize = 0;\n ASSERT_TRUE(0 == dfs->GetFileSize(file2, &fsize));\n ASSERT_TRUE(c1len + c2len + buflen * bufnum == static_cast(fsize));\n\n \/\/\/ Read\n fp = dfs->OpenFile(file2, leveldb::RDONLY);\n ASSERT_TRUE(fp != NULL);\n char buf[128];\n ASSERT_TRUE(c1len == fp->Read(buf, c1len));\n ASSERT_TRUE(0 == strncmp(buf, content1, c1len));\n ASSERT_TRUE(c2len == fp->Read(buf, c2len));\n printf(\"content2= %s, content_read= %s\\n\", content2, buf);\n ASSERT_TRUE(0 == strncmp(buf, content2, c2len));\n ASSERT_TRUE(c2len == fp->Pread(c1len, buf, c2len));\n ASSERT_TRUE(0 == strncmp(buf, content2, c2len));\n ASSERT_TRUE(0 == fp->CloseFile());\n delete fp;\n fp = NULL;\n \n \/\/\/ Sync\n dfs->Delete(file3);\n fp = dfs->OpenFile(file3, leveldb::WRONLY);\n ASSERT_TRUE(fp != NULL);\n ASSERT_TRUE(c1len == fp->Write(content1, c1len));\n ASSERT_TRUE(0 == fp->Flush());\n ASSERT_TRUE(0 == fp->Sync());\n uint64_t file_size = 0;\n ASSERT_TRUE(0 == dfs->GetFileSize(file3, &file_size));\n ASSERT_TRUE(file_size == (uint64_t)c1len);\n ASSERT_TRUE(c2len == fp->Write(content2, c2len));\n \n leveldb::DfsFile* nfp = dfs->OpenFile(file3, leveldb::RDONLY);\n ASSERT_TRUE(nfp != NULL);\n ASSERT_TRUE(c1len == nfp->Read(buf, c1len));\n ASSERT_TRUE(0 == strncmp(buf, content1, c1len));\n nfp->Read(buf, c2len); \/\/ Undefined\n ASSERT_TRUE(0 == nfp->Read(buf, c2len));\n ASSERT_TRUE(0 == nfp->CloseFile());\n\n \/\/\/ List directory\n std::vector result;\n ASSERT_TRUE(0 == dfs->ListDirectory(test_path, &result));\n ASSERT_TRUE(2 == result.size());\n ASSERT_TRUE(file2.substr(file2.rfind('\/')+1) == result[0]);\n\n \/\/\/ Delete\n ASSERT_TRUE(0 == dfs->Delete(file2));\n ASSERT_TRUE(0 != dfs->Exists(file2));\n\n \/\/\/ Delete directory\n result.clear();\n ASSERT_TRUE(0 == dfs->DeleteDirectory(test_path));\n ASSERT_TRUE(0 != dfs->ListDirectory(test_path, &result));\n}\n\nint main(int argc, char* argv[]) {\n testing::InitGoogleTest(&argc, argv);\n if (argc > 1) {\n dfs_conf = argv[1];\n }\n return RUN_ALL_TESTS();\n}\n\n\/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: *\/\nFix bfs_test\/\/ Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ Author: yanshiguang02@baidu.com\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"dfs.h\"\n\nconst char* so_path = \".\/bfs_wrapper.so\";\n\/\/const char* dfs_conf = \"yq01-tera60.yq01:8828\";\nconst char* dfs_conf = \"127.0.0.1:8827,127.0.0.1:8828,127.0.0.1:8829\";\n\nconst std::string test_path(\"\/test\");\n\nTEST(TERA_SO_TEST, TERA_SO) {\n dlerror();\n void* handle = dlopen(so_path, RTLD_LAZY | RTLD_DEEPBIND | RTLD_LOCAL);\n const char* err = dlerror();\n ASSERT_TRUE(handle != NULL);\n\n leveldb::DfsCreator creator = (leveldb::DfsCreator)dlsym(handle, \"NewDfs\");\n err = dlerror();\n ASSERT_TRUE(err == NULL);\n\n leveldb::Dfs* dfs = (*creator)(dfs_conf);\n \n \/\/\/ Create dir\n ASSERT_TRUE(dfs != NULL);\n ASSERT_TRUE(0 == dfs->CreateDirectory(test_path));\n\n \/\/\/ Open\n std::string file1 = test_path + \"\/file1\";\n std::string file2 = test_path + \"\/file2\";\n std::string file3 = test_path + \"\/file3\";\n\n if (0 == dfs->Exists(file1)) {\n ASSERT_TRUE(0 == dfs->Delete(file1));\n }\n\n leveldb::DfsFile* fp = dfs->OpenFile(file1, leveldb::WRONLY);\n ASSERT_TRUE(fp != NULL);\n \n \/\/\/ Write&Sync\n char content1[] = \"File1 content\";\n char content2[] = \"Content for read\";\n const int c1len = sizeof(content1);\n const int c2len = sizeof(content2);\n ASSERT_TRUE(c1len == fp->Write(content1, c1len));\n ASSERT_TRUE(0 == fp->Flush());\n ASSERT_TRUE(0 == fp->Sync());\n ASSERT_TRUE(c2len == fp->Write(content2, c2len));\n\n long lbuf[1024];\n int buflen = sizeof(lbuf);\n int bufnum = 1024;\n for (int i = 0; i < 1024; i++) {\n for (int j = 0; j < 1024; j++) {\n lbuf[j] = ((rand() << 16) | rand());\n }\n buflen = sizeof(lbuf);\n ASSERT_TRUE(buflen == fp->Write(reinterpret_cast(lbuf), buflen));\n }\n\n \/\/\/ Close\n ASSERT_TRUE(0 == fp->CloseFile());\n delete fp;\n fp = NULL;\n\n \/\/\/ Rename\n if (0 == dfs->Exists(file2)) {\n ASSERT_TRUE(0 == dfs->Delete(file2));\n }\n ASSERT_TRUE(0 == dfs->Rename(file1, file2));\n ASSERT_TRUE(0 == dfs->Exists(file2));\n ASSERT_TRUE(0 != dfs->Exists(file1));\n\n \/\/\/ GetFileSize\n uint64_t fsize = 0;\n ASSERT_TRUE(0 == dfs->GetFileSize(file2, &fsize));\n ASSERT_TRUE(c1len + c2len + buflen * bufnum == static_cast(fsize));\n\n \/\/\/ Read\n fp = dfs->OpenFile(file2, leveldb::RDONLY);\n ASSERT_TRUE(fp != NULL);\n char buf[128];\n ASSERT_TRUE(c1len == fp->Read(buf, c1len));\n ASSERT_TRUE(0 == strncmp(buf, content1, c1len));\n ASSERT_TRUE(c2len == fp->Read(buf, c2len));\n printf(\"content2= %s, content_read= %s\\n\", content2, buf);\n ASSERT_TRUE(0 == strncmp(buf, content2, c2len));\n ASSERT_TRUE(c2len == fp->Pread(c1len, buf, c2len));\n ASSERT_TRUE(0 == strncmp(buf, content2, c2len));\n ASSERT_TRUE(0 == fp->CloseFile());\n delete fp;\n fp = NULL;\n \n \/\/\/ Sync\n dfs->Delete(file3);\n fp = dfs->OpenFile(file3, leveldb::WRONLY);\n ASSERT_TRUE(fp != NULL);\n ASSERT_TRUE(c1len == fp->Write(content1, c1len));\n ASSERT_TRUE(0 == fp->Flush());\n ASSERT_TRUE(0 == fp->Sync());\n uint64_t file_size = 0;\n ASSERT_TRUE(0 == dfs->GetFileSize(file3, &file_size));\n ASSERT_TRUE(file_size == (uint64_t)c1len);\n ASSERT_TRUE(c2len == fp->Write(content2, c2len));\n \n leveldb::DfsFile* nfp = dfs->OpenFile(file3, leveldb::RDONLY);\n ASSERT_TRUE(nfp != NULL);\n ASSERT_TRUE(c1len == nfp->Read(buf, c1len));\n ASSERT_TRUE(0 == strncmp(buf, content1, c1len));\n nfp->Read(buf, c2len); \/\/ Undefined\n ASSERT_TRUE(0 == nfp->Read(buf, c2len));\n ASSERT_TRUE(0 == nfp->CloseFile());\n\n \/\/\/ List directory\n std::vector result;\n ASSERT_TRUE(0 == dfs->ListDirectory(test_path, &result));\n ASSERT_TRUE(2 == result.size());\n ASSERT_TRUE(file2.substr(file2.rfind('\/')+1) == result[0]);\n\n \/\/\/ Delete\n ASSERT_TRUE(0 == dfs->Delete(file2));\n ASSERT_TRUE(0 != dfs->Exists(file2));\n\n \/\/\/ Delete directory\n result.clear();\n ASSERT_TRUE(0 == dfs->DeleteDirectory(test_path));\n ASSERT_TRUE(0 != dfs->ListDirectory(test_path, &result));\n}\n\nint main(int argc, char* argv[]) {\n testing::InitGoogleTest(&argc, argv);\n if (argc > 1) {\n dfs_conf = argv[1];\n }\n return RUN_ALL_TESTS();\n}\n\n\/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: *\/\n<|endoftext|>"} {"text":"\/* -------------------------------------------------------------------------- *\/\n\/* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\/\n\/* not use this file except in compliance with the License. You may obtain *\/\n\/* a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\/\n\/* See the License for the specific language governing permissions and *\/\n\/* limitations under the License. *\/\n\/* -------------------------------------------------------------------------- *\/\n\n#include \n\n#include \"AclManager.h\"\n#include \"NebulaLog.h\"\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nconst char * AclManager::table = \"acl\";\n\nconst char * AclManager::db_names = \"oid, user, resource, rights\";\n\nconst char * AclManager::db_bootstrap = \"CREATE TABLE IF NOT EXISTS \"\n \"acl (oid INT PRIMARY KEY, user BIGINT, resource BIGINT, rights BIGINT)\";\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint AclManager::init_cb(void *nil, int num, char **values, char **names)\n{\n lastOID = -1;\n\n if ( values[0] != 0 )\n {\n lastOID = atoi(values[0]);\n }\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\nAclManager::AclManager(SqlDB * _db) :\n db(_db), lastOID(-1)\n{\n ostringstream oss;\n\n \/\/ TODO:\n \/\/ pthread_mutex_init(&mutex, 0);\n\n set_callback(static_cast (&AclManager::init_cb));\n\n oss << \"SELECT last_oid FROM pool_control WHERE tablename='\" << table\n << \"'\";\n\n db->exec(oss, this);\n\n unset_callback();\n}\n;\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint AclManager::start()\n{\n return select();\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nAclManager::~AclManager()\n{\n multimap::iterator it;\n\n for ( it = acl_rules.begin(); it != acl_rules.end(); it++ )\n {\n delete it->second;\n }\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nconst bool AclManager::authorize(int uid, const set &user_groups,\n AuthRequest::Object obj_type, int obj_id, int obj_gid,\n AuthRequest::Operation op)\n{\n ostringstream oss;\n\n multimap::iterator it;\n pair::iterator,\n multimap::iterator> index;\n\n bool auth = false;\n\n \/\/ Build masks for request\n long long user_req;\n long long resource_oid_req = obj_type + AclRule::INDIVIDUAL_ID + obj_id;\n long long resource_gid_req = obj_type + AclRule::GROUP_ID + obj_gid;\n long long resource_all_req = obj_type + AclRule::ALL_ID;\n long long rights_req = op;\n\n long long individual_obj_type =\n ( obj_type | AclRule::INDIVIDUAL_ID | 0xFFFFFFFF );\n\n long long group_obj_type =\n ( obj_type | AclRule::GROUP_ID | 0xFFFFFFFF );\n\n\n\n AclRule request_rule(-1, AclRule::INDIVIDUAL_ID + uid, resource_oid_req,\n rights_req);\n oss << \"Request \" << request_rule.to_str();\n NebulaLog::log(\"ACL\",Log::DEBUG,oss);\n\n\n \/\/ Look for rules that apply to everyone\n\n user_req = AclRule::ALL_ID;\n auth = match_rules(user_req, resource_oid_req, resource_gid_req,\n resource_all_req, rights_req, individual_obj_type, group_obj_type);\n\n if ( auth == true )\n {\n return true;\n }\n\n \/\/ Look for rules that apply to the individual user id\n user_req = AclRule::INDIVIDUAL_ID + uid;\n\n auth = match_rules(user_req, resource_oid_req, resource_gid_req,\n resource_all_req, rights_req, individual_obj_type, group_obj_type);\n\n if ( auth == true )\n {\n return true;\n }\n\n\n \/\/ Look for rules that apply to each one of the user's groups\n\n set::iterator g_it;\n\n for (g_it = user_groups.begin(); g_it != user_groups.end(); g_it++)\n {\n user_req = AclRule::GROUP_ID + *g_it;\n\n auth = match_rules(user_req, resource_oid_req, resource_gid_req,\n resource_all_req, rights_req, individual_obj_type,\n group_obj_type);\n\n if ( auth == true )\n {\n return true;\n }\n }\n\n\n oss.str(\"No more rules, permission not granted \");\n NebulaLog::log(\"ACL\",Log::DEBUG,oss);\n\n return false;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nbool AclManager::match_rules(\n long long user_req,\n long long resource_oid_req,\n long long resource_gid_req,\n long long resource_all_req,\n long long rights_req,\n long long individual_obj_type,\n long long group_obj_type)\n\n{\n bool auth;\n ostringstream oss;\n\n multimap::iterator it;\n\n pair::iterator,\n multimap::iterator> index;\n\n index = acl_rules.equal_range( user_req );\n\n for ( it = index.first; it != index.second; it++)\n {\n oss.str(\"\");\n oss << \"> Rule \" << it->second->to_str();\n NebulaLog::log(\"ACL\",Log::DEBUG,oss);\n\n auth =\n \/\/ Rule grants the requested rights\n ( ( it->second->rights & rights_req ) == rights_req )\n &&\n (\n \/\/ Rule grants permission for all objects of this type\n ( it->second->resource == resource_all_req )\n ||\n \/\/ Or rule's object type and group object ID match\n ( ( it->second->resource & group_obj_type ) == resource_gid_req )\n ||\n \/\/ Or rule's object type and individual object ID match\n ( ( it->second->resource & individual_obj_type ) == resource_oid_req )\n );\n\n if ( auth == true )\n {\n oss.str(\"Permission granted\");\n NebulaLog::log(\"ACL\",Log::DEBUG,oss);\n\n return true;\n }\n }\n\n return false;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint AclManager::add_rule(long long user, long long resource, long long rights,\n string& error_str)\n{\n if (lastOID == INT_MAX)\n {\n lastOID = -1;\n }\n\n AclRule * rule = new AclRule(++lastOID, user, resource, rights);\n\n ostringstream oss;\n int rc;\n\n multimap::iterator it;\n pair::iterator,\n multimap::iterator> index;\n\n bool found = false;\n\n index = acl_rules.equal_range( user );\n\n for ( it = index.first; (it != index.second && !found); it++)\n {\n found = *(it->second) == *rule;\n if ( it->second->resource == resource &&\n it->second->rights == rights )\n {\n found = true;\n }\n }\n\n if ( found )\n {\n goto error_duplicated;\n }\n\n if ( rule->malformed(error_str) )\n {\n goto error_malformed;\n }\n\n\n rc = insert(rule);\n\n if ( rc != 0 )\n {\n goto error_insert;\n }\n\n acl_rules.insert( make_pair(rule->user, rule) );\n acl_rules_oids.insert( make_pair(rule->oid, rule) );\n\n update_lastOID();\n\n return lastOID;\n\n\nerror_duplicated:\n oss << \"Rule \" << rule->to_str() << \" already exists\";\n rc = -1;\n\n goto error_common;\n\nerror_malformed:\n oss << \"Rule \" << rule->to_str() << \" is malformed: \" << error_str;\n rc = -2;\n\n goto error_common;\n\nerror_insert:\n oss << \"Error inserting rule in DB\";\n rc = -3;\n\n goto error_common;\n\nerror_common:\n error_str = oss.str();\n\n delete rule;\n lastOID--;\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\n\nint AclManager::del_rule(int oid, string& error_str)\n{\n\n multimap::iterator it;\n pair::iterator,\n multimap::iterator> index;\n\n AclRule * rule;\n int rc;\n bool found = false;\n\n \/\/ Check the rule exists\n found = acl_rules_oids.count(oid) > 0;\n\n if ( !found )\n {\n ostringstream oss;\n oss << \"Rule \" << oid << \" does not exist\";\n error_str = oss.str();\n\n return -1;\n }\n\n rule = acl_rules_oids[oid];\n\n \/\/ Look for it in the multimap\n\n found = false;\n\n index = acl_rules.equal_range( rule->user );\n\n it = index.first;\n while ( !found && it != index.second )\n {\n found = *rule == *(it->second);\n\n\n if ( !found )\n {\n it++;\n }\n }\n\n if ( !found )\n {\n ostringstream oss;\n oss << \"Internal error: ACL Rule \" << oid\n << \" indexed by oid, but not in by user attribute\";\n\n NebulaLog::log(\"ACL\",Log::ERROR,oss);\n\n return -1;\n }\n\n\n rc = drop( oid );\n\n if ( rc != 0 )\n {\n error_str = \"SQL DB error\";\n return -1;\n }\n\n delete it->second;\n\n acl_rules.erase( it );\n acl_rules_oids.erase( oid );\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid AclManager::update_lastOID()\n{\n \/\/ db->escape_str is not used for 'table' since its name can't be set in\n \/\/ any way by the user, it is hardcoded.\n\n ostringstream oss;\n\n oss << \"REPLACE INTO pool_control (tablename, last_oid) VALUES (\"\n << \"'\" << table << \"',\"\n << lastOID << \")\";\n\n db->exec(oss);\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint AclManager::select_cb(void *nil, int num, char **values, char **names)\n{\n if ( (num != 4) ||\n (!values[0]) ||\n (!values[1]) ||\n (!values[2]) ||\n (!values[3]) )\n {\n return -1;\n }\n\n ostringstream oss;\n istringstream iss;\n\n int oid = atoi(values[0]);\n\n long long rule_values[3];\n\n for ( int i = 0; i < 3; i++ )\n {\n iss.str( values[i+1] );\n\n iss >> rule_values[i];\n\n if ( iss.fail() == true )\n {\n return -1;\n }\n\n iss.clear();\n }\n\n \/\/ TODO: Use add_rule() instead, to check possible errors, or assume\n \/\/ that anything that was stored into the DB is trustworthy?\n AclRule * rule = new AclRule(oid, rule_values[0], rule_values[1],\n rule_values[2]);\n\n\n oss << \"Loading ACL Rule \" << rule->to_str();\n NebulaLog::log(\"ACL\",Log::DDEBUG,oss);\n\n acl_rules.insert( make_pair(rule->user, rule) );\n acl_rules_oids.insert( make_pair(rule->oid, rule) );\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint AclManager::select()\n{\n ostringstream oss;\n int rc;\n\n oss << \"SELECT \" << db_names << \" FROM \" << table;\n\n set_callback(static_cast(&AclManager::select_cb));\n\n rc = db->exec(oss,this);\n\n unset_callback();\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint AclManager::insert(AclRule * rule)\n{\n ostringstream oss;\n int rc;\n\n \/\/ Construct the SQL statement to Insert\n\n oss << \"INSERT INTO \" << table <<\" (\"<< db_names <<\") VALUES (\"\n << rule->oid << \",\"\n << rule->user << \",\"\n << rule->resource << \",\"\n << rule->rights << \")\";\n\n rc = db->exec(oss);\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\n\nint AclManager::drop(int oid)\n{\n ostringstream oss;\n int rc;\n\n oss << \"DELETE FROM \" << table << \" WHERE \"\n << \"oid=\" << oid;\n\n rc = db->exec(oss);\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint AclManager::dump(ostringstream& oss)\n{\n map::iterator it;\n string xml;\n\n oss << \"\";\n\n for ( it = acl_rules_oids.begin() ; it != acl_rules_oids.end(); it++ )\n {\n oss << it->second->to_xml(xml);\n }\n\n oss << \"<\/ACL_POOL>\";\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\nFeature #687: Remove duplicated search test in AclManager::add_rule\/* -------------------------------------------------------------------------- *\/\n\/* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\/\n\/* not use this file except in compliance with the License. You may obtain *\/\n\/* a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\/\n\/* See the License for the specific language governing permissions and *\/\n\/* limitations under the License. *\/\n\/* -------------------------------------------------------------------------- *\/\n\n#include \n\n#include \"AclManager.h\"\n#include \"NebulaLog.h\"\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nconst char * AclManager::table = \"acl\";\n\nconst char * AclManager::db_names = \"oid, user, resource, rights\";\n\nconst char * AclManager::db_bootstrap = \"CREATE TABLE IF NOT EXISTS \"\n \"acl (oid INT PRIMARY KEY, user BIGINT, resource BIGINT, rights BIGINT)\";\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint AclManager::init_cb(void *nil, int num, char **values, char **names)\n{\n lastOID = -1;\n\n if ( values[0] != 0 )\n {\n lastOID = atoi(values[0]);\n }\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\nAclManager::AclManager(SqlDB * _db) :\n db(_db), lastOID(-1)\n{\n ostringstream oss;\n\n \/\/ TODO:\n \/\/ pthread_mutex_init(&mutex, 0);\n\n set_callback(static_cast (&AclManager::init_cb));\n\n oss << \"SELECT last_oid FROM pool_control WHERE tablename='\" << table\n << \"'\";\n\n db->exec(oss, this);\n\n unset_callback();\n}\n;\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint AclManager::start()\n{\n return select();\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nAclManager::~AclManager()\n{\n multimap::iterator it;\n\n for ( it = acl_rules.begin(); it != acl_rules.end(); it++ )\n {\n delete it->second;\n }\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nconst bool AclManager::authorize(int uid, const set &user_groups,\n AuthRequest::Object obj_type, int obj_id, int obj_gid,\n AuthRequest::Operation op)\n{\n ostringstream oss;\n\n multimap::iterator it;\n pair::iterator,\n multimap::iterator> index;\n\n bool auth = false;\n\n \/\/ Build masks for request\n long long user_req;\n long long resource_oid_req = obj_type + AclRule::INDIVIDUAL_ID + obj_id;\n long long resource_gid_req = obj_type + AclRule::GROUP_ID + obj_gid;\n long long resource_all_req = obj_type + AclRule::ALL_ID;\n long long rights_req = op;\n\n long long individual_obj_type =\n ( obj_type | AclRule::INDIVIDUAL_ID | 0xFFFFFFFF );\n\n long long group_obj_type =\n ( obj_type | AclRule::GROUP_ID | 0xFFFFFFFF );\n\n\n\n AclRule request_rule(-1, AclRule::INDIVIDUAL_ID + uid, resource_oid_req,\n rights_req);\n oss << \"Request \" << request_rule.to_str();\n NebulaLog::log(\"ACL\",Log::DEBUG,oss);\n\n\n \/\/ Look for rules that apply to everyone\n\n user_req = AclRule::ALL_ID;\n auth = match_rules(user_req, resource_oid_req, resource_gid_req,\n resource_all_req, rights_req, individual_obj_type, group_obj_type);\n\n if ( auth == true )\n {\n return true;\n }\n\n \/\/ Look for rules that apply to the individual user id\n user_req = AclRule::INDIVIDUAL_ID + uid;\n\n auth = match_rules(user_req, resource_oid_req, resource_gid_req,\n resource_all_req, rights_req, individual_obj_type, group_obj_type);\n\n if ( auth == true )\n {\n return true;\n }\n\n\n \/\/ Look for rules that apply to each one of the user's groups\n\n set::iterator g_it;\n\n for (g_it = user_groups.begin(); g_it != user_groups.end(); g_it++)\n {\n user_req = AclRule::GROUP_ID + *g_it;\n\n auth = match_rules(user_req, resource_oid_req, resource_gid_req,\n resource_all_req, rights_req, individual_obj_type,\n group_obj_type);\n\n if ( auth == true )\n {\n return true;\n }\n }\n\n\n oss.str(\"No more rules, permission not granted \");\n NebulaLog::log(\"ACL\",Log::DEBUG,oss);\n\n return false;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nbool AclManager::match_rules(\n long long user_req,\n long long resource_oid_req,\n long long resource_gid_req,\n long long resource_all_req,\n long long rights_req,\n long long individual_obj_type,\n long long group_obj_type)\n\n{\n bool auth;\n ostringstream oss;\n\n multimap::iterator it;\n\n pair::iterator,\n multimap::iterator> index;\n\n index = acl_rules.equal_range( user_req );\n\n for ( it = index.first; it != index.second; it++)\n {\n oss.str(\"\");\n oss << \"> Rule \" << it->second->to_str();\n NebulaLog::log(\"ACL\",Log::DEBUG,oss);\n\n auth =\n \/\/ Rule grants the requested rights\n ( ( it->second->rights & rights_req ) == rights_req )\n &&\n (\n \/\/ Rule grants permission for all objects of this type\n ( it->second->resource == resource_all_req )\n ||\n \/\/ Or rule's object type and group object ID match\n ( ( it->second->resource & group_obj_type ) == resource_gid_req )\n ||\n \/\/ Or rule's object type and individual object ID match\n ( ( it->second->resource & individual_obj_type ) == resource_oid_req )\n );\n\n if ( auth == true )\n {\n oss.str(\"Permission granted\");\n NebulaLog::log(\"ACL\",Log::DEBUG,oss);\n\n return true;\n }\n }\n\n return false;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint AclManager::add_rule(long long user, long long resource, long long rights,\n string& error_str)\n{\n if (lastOID == INT_MAX)\n {\n lastOID = -1;\n }\n\n AclRule * rule = new AclRule(++lastOID, user, resource, rights);\n\n ostringstream oss;\n int rc;\n\n multimap::iterator it;\n pair::iterator,\n multimap::iterator> index;\n\n bool found = false;\n\n index = acl_rules.equal_range( user );\n\n for ( it = index.first; (it != index.second && !found); it++)\n {\n found = *(it->second) == *rule;\n }\n\n if ( found )\n {\n goto error_duplicated;\n }\n\n if ( rule->malformed(error_str) )\n {\n goto error_malformed;\n }\n\n\n rc = insert(rule);\n\n if ( rc != 0 )\n {\n goto error_insert;\n }\n\n acl_rules.insert( make_pair(rule->user, rule) );\n acl_rules_oids.insert( make_pair(rule->oid, rule) );\n\n update_lastOID();\n\n return lastOID;\n\n\nerror_duplicated:\n oss << \"Rule \" << rule->to_str() << \" already exists\";\n rc = -1;\n\n goto error_common;\n\nerror_malformed:\n oss << \"Rule \" << rule->to_str() << \" is malformed: \" << error_str;\n rc = -2;\n\n goto error_common;\n\nerror_insert:\n oss << \"Error inserting rule in DB\";\n rc = -3;\n\n goto error_common;\n\nerror_common:\n error_str = oss.str();\n\n delete rule;\n lastOID--;\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\n\nint AclManager::del_rule(int oid, string& error_str)\n{\n\n multimap::iterator it;\n pair::iterator,\n multimap::iterator> index;\n\n AclRule * rule;\n int rc;\n bool found = false;\n\n \/\/ Check the rule exists\n found = acl_rules_oids.count(oid) > 0;\n\n if ( !found )\n {\n ostringstream oss;\n oss << \"Rule \" << oid << \" does not exist\";\n error_str = oss.str();\n\n return -1;\n }\n\n rule = acl_rules_oids[oid];\n\n \/\/ Look for it in the multimap\n\n found = false;\n\n index = acl_rules.equal_range( rule->user );\n\n it = index.first;\n while ( !found && it != index.second )\n {\n found = *rule == *(it->second);\n\n\n if ( !found )\n {\n it++;\n }\n }\n\n if ( !found )\n {\n ostringstream oss;\n oss << \"Internal error: ACL Rule \" << oid\n << \" indexed by oid, but not in by user attribute\";\n\n NebulaLog::log(\"ACL\",Log::ERROR,oss);\n\n return -1;\n }\n\n\n rc = drop( oid );\n\n if ( rc != 0 )\n {\n error_str = \"SQL DB error\";\n return -1;\n }\n\n delete it->second;\n\n acl_rules.erase( it );\n acl_rules_oids.erase( oid );\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid AclManager::update_lastOID()\n{\n \/\/ db->escape_str is not used for 'table' since its name can't be set in\n \/\/ any way by the user, it is hardcoded.\n\n ostringstream oss;\n\n oss << \"REPLACE INTO pool_control (tablename, last_oid) VALUES (\"\n << \"'\" << table << \"',\"\n << lastOID << \")\";\n\n db->exec(oss);\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint AclManager::select_cb(void *nil, int num, char **values, char **names)\n{\n if ( (num != 4) ||\n (!values[0]) ||\n (!values[1]) ||\n (!values[2]) ||\n (!values[3]) )\n {\n return -1;\n }\n\n ostringstream oss;\n istringstream iss;\n\n int oid = atoi(values[0]);\n\n long long rule_values[3];\n\n for ( int i = 0; i < 3; i++ )\n {\n iss.str( values[i+1] );\n\n iss >> rule_values[i];\n\n if ( iss.fail() == true )\n {\n return -1;\n }\n\n iss.clear();\n }\n\n \/\/ TODO: Use add_rule() instead, to check possible errors, or assume\n \/\/ that anything that was stored into the DB is trustworthy?\n AclRule * rule = new AclRule(oid, rule_values[0], rule_values[1],\n rule_values[2]);\n\n\n oss << \"Loading ACL Rule \" << rule->to_str();\n NebulaLog::log(\"ACL\",Log::DDEBUG,oss);\n\n acl_rules.insert( make_pair(rule->user, rule) );\n acl_rules_oids.insert( make_pair(rule->oid, rule) );\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint AclManager::select()\n{\n ostringstream oss;\n int rc;\n\n oss << \"SELECT \" << db_names << \" FROM \" << table;\n\n set_callback(static_cast(&AclManager::select_cb));\n\n rc = db->exec(oss,this);\n\n unset_callback();\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint AclManager::insert(AclRule * rule)\n{\n ostringstream oss;\n int rc;\n\n \/\/ Construct the SQL statement to Insert\n\n oss << \"INSERT INTO \" << table <<\" (\"<< db_names <<\") VALUES (\"\n << rule->oid << \",\"\n << rule->user << \",\"\n << rule->resource << \",\"\n << rule->rights << \")\";\n\n rc = db->exec(oss);\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\n\nint AclManager::drop(int oid)\n{\n ostringstream oss;\n int rc;\n\n oss << \"DELETE FROM \" << table << \" WHERE \"\n << \"oid=\" << oid;\n\n rc = db->exec(oss);\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint AclManager::dump(ostringstream& oss)\n{\n map::iterator it;\n string xml;\n\n oss << \"\";\n\n for ( it = acl_rules_oids.begin() ; it != acl_rules_oids.end(); it++ )\n {\n oss << it->second->to_xml(xml);\n }\n\n oss << \"<\/ACL_POOL>\";\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n<|endoftext|>"} {"text":"\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright 2016 ScyllaDB\n *\/\n\n#pragma once\n\n#define UNW_LOCAL_ONLY\n#include \n#include \n#include \n\n#include \"core\/sstring.hh\"\n\nnamespace seastar {\n\nstruct shared_object {\n sstring name;\n uintptr_t begin;\n uintptr_t end; \/\/ C++-style, last addr + 1\n};\n\nstruct frame {\n const shared_object* so;\n uintptr_t addr;\n};\n\nbool operator==(const frame& a, const frame& b);\n\n\n\/\/ If addr doesn't seem to belong to any of the provided shared objects, it\n\/\/ will be considered as part of the executable.\nframe decorate(uintptr_t addr);\n\n\/\/ Invokes func for each frame passing it as argument.\ntemplate\nvoid backtrace(Func&& func) noexcept(noexcept(func(frame()))) {\n unw_context_t context;\n if (unw_getcontext(&context) < 0) {\n return;\n }\n\n unw_cursor_t cursor;\n if (unw_init_local(&cursor, &context) < 0) {\n return;\n }\n\n while (unw_step(&cursor) > 0) {\n unw_word_t ip;\n if (unw_get_reg(&cursor, UNW_REG_IP, &ip) < 0) {\n break;\n }\n if (!ip) {\n break;\n }\n func(decorate(ip - 1));\n }\n}\n\nclass saved_backtrace {\npublic:\n using vector_type = boost::container::static_vector;\nprivate:\n vector_type _frames;\npublic:\n saved_backtrace() = default;\n saved_backtrace(vector_type f) : _frames(std::move(f)) {}\n size_t hash() const;\n\n friend std::ostream& operator<<(std::ostream& out, const saved_backtrace&);\n\n bool operator==(const saved_backtrace& o) const {\n return _frames == o._frames;\n }\n\n bool operator!=(const saved_backtrace& o) const {\n return !(*this == o);\n }\n};\n\n}\n\nnamespace std {\n\ntemplate<>\nstruct hash {\n size_t operator()(const seastar::saved_backtrace& b) const {\n return b.hash();\n }\n};\n\n}\n\nnamespace seastar {\n\nsaved_backtrace current_backtrace() noexcept;\nstd::ostream& operator<<(std::ostream& out, const saved_backtrace& b);\n\n}\nutil: Add throw_with_backtrace helper to add backtraces to exceptions.\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright 2016 ScyllaDB\n *\/\n\n#pragma once\n\n#define UNW_LOCAL_ONLY\n#include \n#include \n#include \n\n#include \"core\/sstring.hh\"\n#include \"core\/print.hh\"\n\nnamespace seastar {\n\nstruct shared_object {\n sstring name;\n uintptr_t begin;\n uintptr_t end; \/\/ C++-style, last addr + 1\n};\n\nstruct frame {\n const shared_object* so;\n uintptr_t addr;\n};\n\nbool operator==(const frame& a, const frame& b);\n\n\n\/\/ If addr doesn't seem to belong to any of the provided shared objects, it\n\/\/ will be considered as part of the executable.\nframe decorate(uintptr_t addr);\n\n\/\/ Invokes func for each frame passing it as argument.\ntemplate\nvoid backtrace(Func&& func) noexcept(noexcept(func(frame()))) {\n unw_context_t context;\n if (unw_getcontext(&context) < 0) {\n return;\n }\n\n unw_cursor_t cursor;\n if (unw_init_local(&cursor, &context) < 0) {\n return;\n }\n\n while (unw_step(&cursor) > 0) {\n unw_word_t ip;\n if (unw_get_reg(&cursor, UNW_REG_IP, &ip) < 0) {\n break;\n }\n if (!ip) {\n break;\n }\n func(decorate(ip - 1));\n }\n}\n\nclass saved_backtrace {\npublic:\n using vector_type = boost::container::static_vector;\nprivate:\n vector_type _frames;\npublic:\n saved_backtrace() = default;\n saved_backtrace(vector_type f) : _frames(std::move(f)) {}\n size_t hash() const;\n\n friend std::ostream& operator<<(std::ostream& out, const saved_backtrace&);\n\n bool operator==(const saved_backtrace& o) const {\n return _frames == o._frames;\n }\n\n bool operator!=(const saved_backtrace& o) const {\n return !(*this == o);\n }\n};\n\n}\n\nnamespace std {\n\ntemplate<>\nstruct hash {\n size_t operator()(const seastar::saved_backtrace& b) const {\n return b.hash();\n }\n};\n\n}\n\nnamespace seastar {\n\nsaved_backtrace current_backtrace() noexcept;\nstd::ostream& operator<<(std::ostream& out, const saved_backtrace& b);\n\nnamespace internal {\n\ntemplate\nclass backtraced : public Exc {\n std::shared_ptr _backtrace;\npublic:\n template\n backtraced(Args&&... args)\n : Exc(std::forward(args)...)\n , _backtrace(std::make_shared(sprint(\"%s Backtrace: %s\", Exc::what(), current_backtrace()))) {}\n\n \/**\n * Returns the original exception message with a backtrace appended to it\n *\n * @return original exception message followed by a backtrace\n *\/\n virtual const char* what() const noexcept override {\n assert(_backtrace);\n return _backtrace->c_str();\n }\n};\n\n}\n\n \/**\n * Throws an exception of unspecified type that is derived from the Exc type\n * with a backtrace attached to its message\n *\n * @tparam Exc exception type to be caught at the receiving side\n * @tparam Args types of arguments forwarded to the constructor of Exc\n * @param args arguments forwarded to the constructor of Exc\n * @return never returns (throws an exception)\n *\/\ntemplate \n[[noreturn]]\nvoid\nthrow_with_backtrace(Args&&... args) {\n using exc_type = std::decay_t;\n static_assert(std::is_base_of::value,\n \"throw_with_backtrace only works with exception types\");\n throw internal::backtraced(std::forward(args)...);\n};\n\n}\n<|endoftext|>"} {"text":"\/**\n * @file\n * @copyright defined in eosio\/LICENSE.txt\n *\/\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"config.hpp\"\n\nusing namespace appbase;\nusing namespace eosio;\n\nnamespace fc {\n std::unordered_map& get_appender_map();\n}\n\nnamespace detail {\n\nvoid configure_logging(const bfs::path& config_path)\n{\n try {\n try {\n fc::configure_logging(config_path);\n } catch (...) {\n elog(\"Error reloading logging.json\");\n throw;\n }\n } catch (const fc::exception& e) {\n elog(\"${e}\", (\"e\",e.to_detail_string()));\n } catch (const boost::exception& e) {\n elog(\"${e}\", (\"e\",boost::diagnostic_information(e)));\n } catch (const std::exception& e) {\n elog(\"${e}\", (\"e\",e.what()));\n } catch (...) {\n \/\/ empty\n }\n}\n\n} \/\/ namespace detail\n\nvoid logging_conf_handler()\n{\n ilog(\"Received HUP. Reloading logging configuration.\");\n auto config_path = app().get_logging_conf();\n if(fc::exists(config_path))\n ::detail::configure_logging(config_path);\n for(auto iter : fc::get_appender_map())\n iter.second->initialize(app().get_io_service());\n}\n\nvoid initialize_logging()\n{\n auto config_path = app().get_logging_conf();\n if(fc::exists(config_path))\n fc::configure_logging(config_path); \/\/ intentionally allowing exceptions to escape\n for(auto iter : fc::get_appender_map())\n iter.second->initialize(app().get_io_service());\n\n app().set_sighup_callback(logging_conf_handler);\n}\n\nenum return_codes {\n OTHER_FAIL = -2,\n INITIALIZE_FAIL = -1,\n SUCCESS = 0,\n BAD_ALLOC = 1,\n DATABASE_DIRTY = 2,\n FIXED_REVERSIBLE = 3,\n EXTRACTED_GENESIS = 4,\n NODE_MANAGEMENT_SUCCESS = 5\n};\n\nint main(int argc, char** argv)\n{\n try {\n fc::set_os_thread_name( \"main\" );\n app().set_version(eosio::nodeos::config::version);\n\n auto root = fc::app_path();\n app().set_default_data_dir(root \/ \"eosio\/nodeos\/data\" );\n app().set_default_config_dir(root \/ \"eosio\/nodeos\/config\" );\n http_plugin::set_defaults({\n .default_unix_socket_path = \"\",\n .default_http_port = 8888\n });\n if(!app().initialize(argc, argv))\n return INITIALIZE_FAIL;\n initialize_logging();\n ilog(\"nodeos version ${ver}\", (\"ver\", app().version_string()));\n ilog(\"eosio root is ${root}\", (\"root\", root.string()));\n ilog(\"nodeos using configuration file ${c}\", (\"c\", app().full_config_file_path().string()));\n ilog(\"nodeos data directory is ${d}\", (\"d\", app().data_dir().string()));\n app().startup();\n app().exec();\n } catch( const extract_genesis_state_exception& e ) {\n return EXTRACTED_GENESIS;\n } catch( const fixed_reversible_db_exception& e ) {\n return FIXED_REVERSIBLE;\n } catch( const node_management_success& e ) {\n return NODE_MANAGEMENT_SUCCESS;\n } catch( const fc::exception& e ) {\n if( e.code() == fc::std_exception_code ) {\n if( e.top_message().find( \"database dirty flag set\" ) != std::string::npos ) {\n elog( \"database dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n } else if( e.top_message().find( \"database metadata dirty flag set\" ) != std::string::npos ) {\n elog( \"database metadata dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n }\n }\n elog( \"${e}\", (\"e\", e.to_detail_string()));\n return OTHER_FAIL;\n } catch( const boost::interprocess::bad_alloc& e ) {\n elog(\"bad alloc\");\n return BAD_ALLOC;\n } catch( const boost::exception& e ) {\n elog(\"${e}\", (\"e\",boost::diagnostic_information(e)));\n return OTHER_FAIL;\n } catch( const std::runtime_error& e ) {\n if( std::string(e.what()) == \"database dirty flag set\" ) {\n elog( \"database dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n } else if( std::string(e.what()) == \"database metadata dirty flag set\" ) {\n elog( \"database metadata dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n } else {\n elog( \"${e}\", (\"e\",e.what()));\n }\n return OTHER_FAIL;\n } catch( const std::exception& e ) {\n elog(\"${e}\", (\"e\",e.what()));\n return OTHER_FAIL;\n } catch( ... ) {\n elog(\"unknown exception\");\n return OTHER_FAIL;\n }\n\n ilog(\"nodeos successfully exiting\");\n return SUCCESS;\n}\nDo not name main thread since some tests expect it to be nodeos\/**\n * @file\n * @copyright defined in eosio\/LICENSE.txt\n *\/\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"config.hpp\"\n\nusing namespace appbase;\nusing namespace eosio;\n\nnamespace fc {\n std::unordered_map& get_appender_map();\n}\n\nnamespace detail {\n\nvoid configure_logging(const bfs::path& config_path)\n{\n try {\n try {\n fc::configure_logging(config_path);\n } catch (...) {\n elog(\"Error reloading logging.json\");\n throw;\n }\n } catch (const fc::exception& e) {\n elog(\"${e}\", (\"e\",e.to_detail_string()));\n } catch (const boost::exception& e) {\n elog(\"${e}\", (\"e\",boost::diagnostic_information(e)));\n } catch (const std::exception& e) {\n elog(\"${e}\", (\"e\",e.what()));\n } catch (...) {\n \/\/ empty\n }\n}\n\n} \/\/ namespace detail\n\nvoid logging_conf_handler()\n{\n ilog(\"Received HUP. Reloading logging configuration.\");\n auto config_path = app().get_logging_conf();\n if(fc::exists(config_path))\n ::detail::configure_logging(config_path);\n for(auto iter : fc::get_appender_map())\n iter.second->initialize(app().get_io_service());\n}\n\nvoid initialize_logging()\n{\n auto config_path = app().get_logging_conf();\n if(fc::exists(config_path))\n fc::configure_logging(config_path); \/\/ intentionally allowing exceptions to escape\n for(auto iter : fc::get_appender_map())\n iter.second->initialize(app().get_io_service());\n\n app().set_sighup_callback(logging_conf_handler);\n}\n\nenum return_codes {\n OTHER_FAIL = -2,\n INITIALIZE_FAIL = -1,\n SUCCESS = 0,\n BAD_ALLOC = 1,\n DATABASE_DIRTY = 2,\n FIXED_REVERSIBLE = 3,\n EXTRACTED_GENESIS = 4,\n NODE_MANAGEMENT_SUCCESS = 5\n};\n\nint main(int argc, char** argv)\n{\n try {\n app().set_version(eosio::nodeos::config::version);\n\n auto root = fc::app_path();\n app().set_default_data_dir(root \/ \"eosio\/nodeos\/data\" );\n app().set_default_config_dir(root \/ \"eosio\/nodeos\/config\" );\n http_plugin::set_defaults({\n .default_unix_socket_path = \"\",\n .default_http_port = 8888\n });\n if(!app().initialize(argc, argv))\n return INITIALIZE_FAIL;\n initialize_logging();\n ilog(\"nodeos version ${ver}\", (\"ver\", app().version_string()));\n ilog(\"eosio root is ${root}\", (\"root\", root.string()));\n ilog(\"nodeos using configuration file ${c}\", (\"c\", app().full_config_file_path().string()));\n ilog(\"nodeos data directory is ${d}\", (\"d\", app().data_dir().string()));\n app().startup();\n app().exec();\n } catch( const extract_genesis_state_exception& e ) {\n return EXTRACTED_GENESIS;\n } catch( const fixed_reversible_db_exception& e ) {\n return FIXED_REVERSIBLE;\n } catch( const node_management_success& e ) {\n return NODE_MANAGEMENT_SUCCESS;\n } catch( const fc::exception& e ) {\n if( e.code() == fc::std_exception_code ) {\n if( e.top_message().find( \"database dirty flag set\" ) != std::string::npos ) {\n elog( \"database dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n } else if( e.top_message().find( \"database metadata dirty flag set\" ) != std::string::npos ) {\n elog( \"database metadata dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n }\n }\n elog( \"${e}\", (\"e\", e.to_detail_string()));\n return OTHER_FAIL;\n } catch( const boost::interprocess::bad_alloc& e ) {\n elog(\"bad alloc\");\n return BAD_ALLOC;\n } catch( const boost::exception& e ) {\n elog(\"${e}\", (\"e\",boost::diagnostic_information(e)));\n return OTHER_FAIL;\n } catch( const std::runtime_error& e ) {\n if( std::string(e.what()) == \"database dirty flag set\" ) {\n elog( \"database dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n } else if( std::string(e.what()) == \"database metadata dirty flag set\" ) {\n elog( \"database metadata dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n } else {\n elog( \"${e}\", (\"e\",e.what()));\n }\n return OTHER_FAIL;\n } catch( const std::exception& e ) {\n elog(\"${e}\", (\"e\",e.what()));\n return OTHER_FAIL;\n } catch( ... ) {\n elog(\"unknown exception\");\n return OTHER_FAIL;\n }\n\n ilog(\"nodeos successfully exiting\");\n return SUCCESS;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2016 The Imaging Source Europe GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"devicelibrary.h\"\n\n#include \"AravisDevice.h\"\n#include \"aravis_utils.h\"\n\n\n\n#include \n\nDeviceInterface* open_device (const struct tcam_device_info* device)\n{\n return new AravisDevice(DeviceInfo(*device));\n}\n\n\nsize_t get_device_list_size ()\n{\n auto vec = get_gige_device_list();\n return vec.size();\n}\n\n\n\/**\n * @return number of copied device_infos\n *\/\nsize_t get_device_list (struct tcam_device_info* array, size_t array_size)\n{\n auto vec = get_gige_device_list();\n\n if (vec.size() > array_size)\n {\n return 0;\n }\n\n for (const auto v : vec)\n {\n auto i = v.get_info();\n memcpy(array, &i, sizeof(struct tcam_device_info));\n array++;\n }\n\n return vec.size();\n}\n\n\nstruct libinfo_v1* get_library_functions_v1 ()\n{\n struct libinfo_v1* info = new libinfo_v1();\n\n info->open_device = &open_device;\n info->get_device_list_size = &get_device_list_size;\n info->get_device_list = &get_device_list;\n\n return info;\n}\nSwitch aravislibrary::get_device_list_size to get_gige_device_count\/*\n * Copyright 2016 The Imaging Source Europe GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"devicelibrary.h\"\n\n#include \"AravisDevice.h\"\n#include \"aravis_utils.h\"\n\n\n\n#include \n\nDeviceInterface* open_device (const struct tcam_device_info* device)\n{\n return new AravisDevice(DeviceInfo(*device));\n}\n\n\nsize_t get_device_list_size ()\n{\n return get_gige_device_count();\n}\n\n\n\/**\n * @return number of copied device_infos\n *\/\nsize_t get_device_list (struct tcam_device_info* array, size_t array_size)\n{\n auto vec = get_gige_device_list();\n\n if (vec.size() > array_size)\n {\n return 0;\n }\n\n for (const auto v : vec)\n {\n auto i = v.get_info();\n memcpy(array, &i, sizeof(struct tcam_device_info));\n array++;\n }\n\n return vec.size();\n}\n\n\nstruct libinfo_v1* get_library_functions_v1 ()\n{\n struct libinfo_v1* info = new libinfo_v1();\n\n info->open_device = &open_device;\n info->get_device_list_size = &get_device_list_size;\n info->get_device_list = &get_device_list;\n\n return info;\n}\n<|endoftext|>"} {"text":"#include \"main.h\"\n#include \"AppDelegate.h\"\n#include \"CCEGLView.h\"\n\nUSING_NS_CC;\n\nint APIENTRY _tWinMain(HINSTANCE hInstance,\n HINSTANCE hPrevInstance,\n LPTSTR lpCmdLine,\n int nCmdShow)\n{\n UNREFERENCED_PARAMETER(hPrevInstance);\n UNREFERENCED_PARAMETER(lpCmdLine);\n\n \/\/ create the application instance\n AppDelegate app;\n CCEGLView* eglView = CCEGLView::sharedOpenGLView();\n eglView->setViewName(\"CowboyScene\");\n eglView->setFrameSize(480, 320);\n return CCApplication::sharedApplication()->run();\n}\nDemoCowboy: fix window size for win32#include \"main.h\"\n#include \"AppDelegate.h\"\n#include \"CCEGLView.h\"\n\nUSING_NS_CC;\n\nint APIENTRY _tWinMain(HINSTANCE hInstance,\n HINSTANCE hPrevInstance,\n LPTSTR lpCmdLine,\n int nCmdShow)\n{\n UNREFERENCED_PARAMETER(hPrevInstance);\n UNREFERENCED_PARAMETER(lpCmdLine);\n\n \/\/ create the application instance\n AppDelegate app;\n CCEGLView* eglView = CCEGLView::sharedOpenGLView();\n eglView->setViewName(\"CowboyScene\");\n eglView->setFrameSize(960, 640);\n return CCApplication::sharedApplication()->run();\n}\n<|endoftext|>"} {"text":"\/\/ Project specific\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/ Third party\n\n\/\/ Standard\n#include \nusing namespace std;\n\nnamespace Doremi\n{\n namespace Core\n {\n TriggerManager::TriggerManager(const DoremiEngine::Core::SharedContext& p_sharedContext) : Manager(p_sharedContext, \"TriggerManager\") {}\n\n TriggerManager::~TriggerManager() {}\n\n\n void TriggerManager::Update(double p_dt)\n {\n \/\/ TODOXX If a trigger has the same wall as another trigger it acts weird. It will(tried it once) trigger one triggertype on the way out\n \/\/ and one on the\n \/\/ way in\n \/\/ Loop through all entities\n const size_t length = EntityHandler::GetInstance().GetLastEntityIndex();\n for(size_t i = 0; i < length; i++)\n {\n \/\/ collisionTriggerPairs[k].firstID\n \/\/ Check that the current entity has the relevant components\n if(EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::Trigger | (int)ComponentType::Transform | (int)ComponentType::RigidBody))\n {\n std::vector collisionTriggerPairs = m_sharedContext.GetPhysicsModule().GetTriggerPairs();\n size_t collisionListLength = collisionTriggerPairs.size();\n for(size_t k = 0; k < collisionListLength; ++k)\n {\n if(i == collisionTriggerPairs[k].firstID)\n {\n\n TriggerEventStruct* myEvent = new TriggerEventStruct();\n TriggerComponent* triggComp = EntityHandler::GetInstance().GetComponentFromStorage(i);\n myEvent->triggerType = triggComp->triggerType;\n myEvent->entityID = collisionTriggerPairs[k].secondID;\n EventHandler::GetInstance()->BroadcastEvent(myEvent);\n }\n else\n {\n \/\/ DO nathiiing\n }\n }\n }\n else\n {\n \/\/ do nuting\n }\n }\n }\n void TriggerManager::OnEvent(Event* p_event)\n {\n \/\/ Check to see what event was received and do something with it (Might be changed to callback functions instead)\n switch(p_event->eventType)\n {\n\n default:\n break;\n }\n }\n }\n}Added comments to triggermanager.cpp\/\/ Project specific\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/ Third party\n\n\/\/ Standard\n#include \nusing namespace std;\n\nnamespace Doremi\n{\n namespace Core\n {\n TriggerManager::TriggerManager(const DoremiEngine::Core::SharedContext& p_sharedContext) : Manager(p_sharedContext, \"TriggerManager\") {}\n\n TriggerManager::~TriggerManager() {}\n\n\n void TriggerManager::Update(double p_dt)\n {\n \/\/ TODOXX If a trigger has the same wall as another trigger it acts weird. It will(tried it once) trigger one triggertype on the way out\n \/\/ and one on the\n \/\/ way in\n \/\/ Loop through all entities\n const size_t length = EntityHandler::GetInstance().GetLastEntityIndex();\n for(size_t i = 0; i < length; i++)\n {\n \/\/ Check that the current entity has the relevant components\n if(EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::Trigger | (int)ComponentType::Transform | (int)ComponentType::RigidBody))\n {\n\n \/\/ Get the collisionpairs from physicmodule\n std::vector collisionTriggerPairs = m_sharedContext.GetPhysicsModule().GetTriggerPairs();\n size_t collisionListLength = collisionTriggerPairs.size();\n for(size_t k = 0; k < collisionListLength; ++k)\n {\n \/\/ The first id will always be the trigger.\n if(i == collisionTriggerPairs[k].firstID)\n {\n \/\/ setting up an event to broadcast the triggertype from the component trigger.\n TriggerEventStruct* myEvent = new TriggerEventStruct();\n TriggerComponent* triggComp = EntityHandler::GetInstance().GetComponentFromStorage(i);\n myEvent->triggerType = triggComp->triggerType;\n myEvent->entityID = collisionTriggerPairs[k].secondID;\n EventHandler::GetInstance()->BroadcastEvent(myEvent);\n }\n else\n {\n \/\/ DO nathiiing\n }\n }\n }\n else\n {\n \/\/ do nuting\n }\n }\n }\n void TriggerManager::OnEvent(Event* p_event)\n {\n \/\/ Check to see what event was received and do something with it (Might be changed to callback functions instead)\n switch(p_event->eventType)\n {\n\n default:\n break;\n }\n }\n }\n}<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2019-present ScyllaDB\n *\/\n\n#include \"build_id.hh\"\n#include \n#include \n#include \n#include \n#include \n\nusing namespace seastar;\n\nstatic const Elf64_Nhdr* get_nt_build_id(dl_phdr_info* info) {\n auto base = info->dlpi_addr;\n const auto* h = info->dlpi_phdr;\n auto num_headers = info->dlpi_phnum;\n for (int i = 0; i != num_headers; ++i, ++h) {\n if (h->p_type != PT_NOTE) {\n continue;\n }\n\n auto* p = reinterpret_cast(base + h->p_vaddr);\n auto* e = p + h->p_memsz;\n while (p != e) {\n const auto* n = reinterpret_cast(p);\n if (n->n_type == NT_GNU_BUILD_ID) {\n return n;\n }\n\n p += sizeof(Elf64_Nhdr);\n\n p += n->n_namesz;\n p = align_up(p, 4);\n\n p += n->n_descsz;\n p = align_up(p, 4);\n }\n }\n\n assert(0 && \"no NT_GNU_BUILD_ID note\");\n}\n\nstatic int callback(dl_phdr_info* info, size_t size, void* data) {\n std::string& ret = *(std::string*)data;\n std::ostringstream os;\n\n \/\/ The first DSO is always the main program, which has an empty name.\n assert(strlen(info->dlpi_name) == 0);\n\n auto* n = get_nt_build_id(info);\n auto* p = reinterpret_cast(n);\n\n p += sizeof(Elf64_Nhdr);\n\n p += n->n_namesz;\n p = align_up(p, 4);\n\n auto* desc = p;\n auto* desc_end = p + n->n_descsz;\n while (desc < desc_end) {\n fmt::print(os, \"{:02x}\", *desc++);\n }\n ret = os.str();\n return 1;\n}\n\nstd::string get_build_id() {\n std::string ret;\n int r = dl_iterate_phdr(callback, &ret);\n assert(r == 1);\n return ret;\n}\nbuild_id: cache the value\/*\n * Copyright (C) 2019-present ScyllaDB\n *\/\n\n#include \"build_id.hh\"\n#include \n#include \n#include \n#include \n#include \n\nusing namespace seastar;\n\nstatic const Elf64_Nhdr* get_nt_build_id(dl_phdr_info* info) {\n auto base = info->dlpi_addr;\n const auto* h = info->dlpi_phdr;\n auto num_headers = info->dlpi_phnum;\n for (int i = 0; i != num_headers; ++i, ++h) {\n if (h->p_type != PT_NOTE) {\n continue;\n }\n\n auto* p = reinterpret_cast(base + h->p_vaddr);\n auto* e = p + h->p_memsz;\n while (p != e) {\n const auto* n = reinterpret_cast(p);\n if (n->n_type == NT_GNU_BUILD_ID) {\n return n;\n }\n\n p += sizeof(Elf64_Nhdr);\n\n p += n->n_namesz;\n p = align_up(p, 4);\n\n p += n->n_descsz;\n p = align_up(p, 4);\n }\n }\n\n assert(0 && \"no NT_GNU_BUILD_ID note\");\n}\n\nstatic int callback(dl_phdr_info* info, size_t size, void* data) {\n std::string& ret = *(std::string*)data;\n std::ostringstream os;\n\n \/\/ The first DSO is always the main program, which has an empty name.\n assert(strlen(info->dlpi_name) == 0);\n\n auto* n = get_nt_build_id(info);\n auto* p = reinterpret_cast(n);\n\n p += sizeof(Elf64_Nhdr);\n\n p += n->n_namesz;\n p = align_up(p, 4);\n\n auto* desc = p;\n auto* desc_end = p + n->n_descsz;\n while (desc < desc_end) {\n fmt::print(os, \"{:02x}\", *desc++);\n }\n ret = os.str();\n return 1;\n}\n\nstatic std::string really_get_build_id() {\n std::string ret;\n int r = dl_iterate_phdr(callback, &ret);\n assert(r == 1);\n return ret;\n}\n\nstd::string get_build_id() {\n static thread_local std::string cache;\n if (cache.empty()) {\n cache = really_get_build_id();\n }\n return cache;\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2006-2008 Benoit Jacob \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#define EIGEN_NO_STATIC_ASSERT\n\n#include \"main.h\"\n\ntemplate void adjoint(const MatrixType& m)\n{\n \/* this test covers the following files:\n Transpose.h Conjugate.h Dot.h\n *\/\n using std::abs;\n typedef typename MatrixType::Index Index;\n typedef typename MatrixType::Scalar Scalar;\n typedef typename NumTraits::Real RealScalar;\n typedef Matrix VectorType;\n typedef Matrix SquareMatrixType;\n \n Index rows = m.rows();\n Index cols = m.cols();\n\n MatrixType m1 = MatrixType::Random(rows, cols),\n m2 = MatrixType::Random(rows, cols),\n m3(rows, cols),\n square = SquareMatrixType::Random(rows, rows);\n VectorType v1 = VectorType::Random(rows),\n v2 = VectorType::Random(rows),\n v3 = VectorType::Random(rows),\n vzero = VectorType::Zero(rows);\n\n Scalar s1 = internal::random(),\n s2 = internal::random();\n\n \/\/ check basic compatibility of adjoint, transpose, conjugate\n VERIFY_IS_APPROX(m1.transpose().conjugate().adjoint(), m1);\n VERIFY_IS_APPROX(m1.adjoint().conjugate().transpose(), m1);\n\n \/\/ check multiplicative behavior\n VERIFY_IS_APPROX((m1.adjoint() * m2).adjoint(), m2.adjoint() * m1);\n VERIFY_IS_APPROX((s1 * m1).adjoint(), internal::conj(s1) * m1.adjoint());\n\n \/\/ check basic properties of dot, norm, norm2\n typedef typename NumTraits::Real RealScalar;\n \n RealScalar ref = NumTraits::IsInteger ? RealScalar(0) : (std::max)((s1 * v1 + s2 * v2).norm(),v3.norm());\n VERIFY(test_isApproxWithRef((s1 * v1 + s2 * v2).dot(v3), internal::conj(s1) * v1.dot(v3) + internal::conj(s2) * v2.dot(v3), ref));\n VERIFY(test_isApproxWithRef(v3.dot(s1 * v1 + s2 * v2), s1*v3.dot(v1)+s2*v3.dot(v2), ref));\n VERIFY_IS_APPROX(internal::conj(v1.dot(v2)), v2.dot(v1));\n VERIFY_IS_APPROX(internal::real(v1.dot(v1)), v1.squaredNorm());\n if(!NumTraits::IsInteger) {\n VERIFY_IS_APPROX(v1.squaredNorm(), v1.norm() * v1.norm());\n \/\/ check normalized() and normalize()\n VERIFY_IS_APPROX(v1, v1.norm() * v1.normalized());\n v3 = v1;\n v3.normalize();\n VERIFY_IS_APPROX(v1, v1.norm() * v3);\n VERIFY_IS_APPROX(v3, v1.normalized());\n VERIFY_IS_APPROX(v3.norm(), RealScalar(1));\n }\n VERIFY_IS_MUCH_SMALLER_THAN(abs(vzero.dot(v1)), static_cast(1));\n \n \/\/ check compatibility of dot and adjoint\n \n ref = NumTraits::IsInteger ? 0 : (std::max)((std::max)(v1.norm(),v2.norm()),(std::max)((square * v2).norm(),(square.adjoint() * v1).norm()));\n VERIFY(test_isApproxWithRef(v1.dot(square * v2), (square.adjoint() * v1).dot(v2), ref));\n\n \/\/ like in testBasicStuff, test operator() to check const-qualification\n Index r = internal::random(0, rows-1),\n c = internal::random(0, cols-1);\n VERIFY_IS_APPROX(m1.conjugate()(r,c), internal::conj(m1(r,c)));\n VERIFY_IS_APPROX(m1.adjoint()(c,r), internal::conj(m1(r,c)));\n\n if(!NumTraits::IsInteger)\n {\n \/\/ check that Random().normalized() works: tricky as the random xpr must be evaluated by\n \/\/ normalized() in order to produce a consistent result.\n VERIFY_IS_APPROX(VectorType::Random(rows).normalized().norm(), RealScalar(1));\n }\n\n \/\/ check inplace transpose\n m3 = m1;\n m3.transposeInPlace();\n VERIFY_IS_APPROX(m3,m1.transpose());\n m3.transposeInPlace();\n VERIFY_IS_APPROX(m3,m1);\n\n \/\/ check inplace adjoint\n m3 = m1;\n m3.adjointInPlace();\n VERIFY_IS_APPROX(m3,m1.adjoint());\n m3.transposeInPlace();\n VERIFY_IS_APPROX(m3,m1.conjugate());\n\n \/\/ check mixed dot product\n typedef Matrix RealVectorType;\n RealVectorType rv1 = RealVectorType::Random(rows);\n VERIFY_IS_APPROX(v1.dot(rv1.template cast()), v1.dot(rv1));\n VERIFY_IS_APPROX(rv1.template cast().dot(v1), rv1.dot(v1));\n}\n\nvoid test_adjoint()\n{\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST_1( adjoint(Matrix()) );\n CALL_SUBTEST_2( adjoint(Matrix3d()) );\n CALL_SUBTEST_3( adjoint(Matrix4f()) );\n CALL_SUBTEST_4( adjoint(MatrixXcf(internal::random(1,EIGEN_TEST_MAX_SIZE\/2), internal::random(1,EIGEN_TEST_MAX_SIZE\/2))) );\n CALL_SUBTEST_5( adjoint(MatrixXi(internal::random(1,EIGEN_TEST_MAX_SIZE), internal::random(1,EIGEN_TEST_MAX_SIZE))) );\n CALL_SUBTEST_6( adjoint(MatrixXf(internal::random(1,EIGEN_TEST_MAX_SIZE), internal::random(1,EIGEN_TEST_MAX_SIZE))) );\n }\n \/\/ test a large static matrix only once\n CALL_SUBTEST_7( adjoint(Matrix()) );\n\n#ifdef EIGEN_TEST_PART_4\n {\n MatrixXcf a(10,10), b(10,10);\n VERIFY_RAISES_ASSERT(a = a.transpose());\n VERIFY_RAISES_ASSERT(a = a.transpose() + b);\n VERIFY_RAISES_ASSERT(a = b + a.transpose());\n VERIFY_RAISES_ASSERT(a = a.conjugate().transpose());\n VERIFY_RAISES_ASSERT(a = a.adjoint());\n VERIFY_RAISES_ASSERT(a = a.adjoint() + b);\n VERIFY_RAISES_ASSERT(a = b + a.adjoint());\n\n \/\/ no assertion should be triggered for these cases:\n a.transpose() = a.transpose();\n a.transpose() += a.transpose();\n a.transpose() += a.transpose() + b;\n a.transpose() = a.adjoint();\n a.transpose() += a.adjoint();\n a.transpose() += a.adjoint() + b;\n }\n#endif\n}\n\nUpdate adjoint unit test to avoid instantiating sqrt(int)\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2006-2008 Benoit Jacob \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#define EIGEN_NO_STATIC_ASSERT\n\n#include \"main.h\"\n\ntemplate struct adjoint_specific;\n\ntemplate<> struct adjoint_specific {\n template\n static void run(const Vec& v1, const Vec& v2, Vec& v3, const Mat& square, Scalar s1, Scalar s2) {\n VERIFY(test_isApproxWithRef((s1 * v1 + s2 * v2).dot(v3), internal::conj(s1) * v1.dot(v3) + internal::conj(s2) * v2.dot(v3), 0));\n VERIFY(test_isApproxWithRef(v3.dot(s1 * v1 + s2 * v2), s1*v3.dot(v1)+s2*v3.dot(v2), 0));\n \n \/\/ check compatibility of dot and adjoint\n VERIFY(test_isApproxWithRef(v1.dot(square * v2), (square.adjoint() * v1).dot(v2), 0));\n }\n};\n\ntemplate<> struct adjoint_specific {\n template\n static void run(const Vec& v1, const Vec& v2, Vec& v3, const Mat& square, Scalar s1, Scalar s2) {\n typedef typename NumTraits::Real RealScalar;\n \n RealScalar ref = NumTraits::IsInteger ? RealScalar(0) : (std::max)((s1 * v1 + s2 * v2).norm(),v3.norm());\n VERIFY(test_isApproxWithRef((s1 * v1 + s2 * v2).dot(v3), internal::conj(s1) * v1.dot(v3) + internal::conj(s2) * v2.dot(v3), ref));\n VERIFY(test_isApproxWithRef(v3.dot(s1 * v1 + s2 * v2), s1*v3.dot(v1)+s2*v3.dot(v2), ref));\n \n VERIFY_IS_APPROX(v1.squaredNorm(), v1.norm() * v1.norm());\n \/\/ check normalized() and normalize()\n VERIFY_IS_APPROX(v1, v1.norm() * v1.normalized());\n v3 = v1;\n v3.normalize();\n VERIFY_IS_APPROX(v1, v1.norm() * v3);\n VERIFY_IS_APPROX(v3, v1.normalized());\n VERIFY_IS_APPROX(v3.norm(), RealScalar(1));\n \n \/\/ check compatibility of dot and adjoint\n ref = NumTraits::IsInteger ? 0 : (std::max)((std::max)(v1.norm(),v2.norm()),(std::max)((square * v2).norm(),(square.adjoint() * v1).norm()));\n VERIFY(test_isApproxWithRef(v1.dot(square * v2), (square.adjoint() * v1).dot(v2), ref));\n \n \/\/ check that Random().normalized() works: tricky as the random xpr must be evaluated by\n \/\/ normalized() in order to produce a consistent result.\n VERIFY_IS_APPROX(Vec::Random(v1.size()).normalized().norm(), RealScalar(1));\n }\n};\n\ntemplate void adjoint(const MatrixType& m)\n{\n \/* this test covers the following files:\n Transpose.h Conjugate.h Dot.h\n *\/\n using std::abs;\n typedef typename MatrixType::Index Index;\n typedef typename MatrixType::Scalar Scalar;\n typedef typename NumTraits::Real RealScalar;\n typedef Matrix VectorType;\n typedef Matrix SquareMatrixType;\n \n Index rows = m.rows();\n Index cols = m.cols();\n\n MatrixType m1 = MatrixType::Random(rows, cols),\n m2 = MatrixType::Random(rows, cols),\n m3(rows, cols),\n square = SquareMatrixType::Random(rows, rows);\n VectorType v1 = VectorType::Random(rows),\n v2 = VectorType::Random(rows),\n v3 = VectorType::Random(rows),\n vzero = VectorType::Zero(rows);\n\n Scalar s1 = internal::random(),\n s2 = internal::random();\n\n \/\/ check basic compatibility of adjoint, transpose, conjugate\n VERIFY_IS_APPROX(m1.transpose().conjugate().adjoint(), m1);\n VERIFY_IS_APPROX(m1.adjoint().conjugate().transpose(), m1);\n\n \/\/ check multiplicative behavior\n VERIFY_IS_APPROX((m1.adjoint() * m2).adjoint(), m2.adjoint() * m1);\n VERIFY_IS_APPROX((s1 * m1).adjoint(), internal::conj(s1) * m1.adjoint());\n\n \/\/ check basic properties of dot, squaredNorm\n VERIFY_IS_APPROX(internal::conj(v1.dot(v2)), v2.dot(v1));\n VERIFY_IS_APPROX(internal::real(v1.dot(v1)), v1.squaredNorm());\n \n adjoint_specific::IsInteger>::run(v1, v2, v3, square, s1, s2);\n \n VERIFY_IS_MUCH_SMALLER_THAN(abs(vzero.dot(v1)), static_cast(1));\n \n \/\/ like in testBasicStuff, test operator() to check const-qualification\n Index r = internal::random(0, rows-1),\n c = internal::random(0, cols-1);\n VERIFY_IS_APPROX(m1.conjugate()(r,c), internal::conj(m1(r,c)));\n VERIFY_IS_APPROX(m1.adjoint()(c,r), internal::conj(m1(r,c)));\n\n \/\/ check inplace transpose\n m3 = m1;\n m3.transposeInPlace();\n VERIFY_IS_APPROX(m3,m1.transpose());\n m3.transposeInPlace();\n VERIFY_IS_APPROX(m3,m1);\n\n \/\/ check inplace adjoint\n m3 = m1;\n m3.adjointInPlace();\n VERIFY_IS_APPROX(m3,m1.adjoint());\n m3.transposeInPlace();\n VERIFY_IS_APPROX(m3,m1.conjugate());\n\n \/\/ check mixed dot product\n typedef Matrix RealVectorType;\n RealVectorType rv1 = RealVectorType::Random(rows);\n VERIFY_IS_APPROX(v1.dot(rv1.template cast()), v1.dot(rv1));\n VERIFY_IS_APPROX(rv1.template cast().dot(v1), rv1.dot(v1));\n}\n\nvoid test_adjoint()\n{\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST_1( adjoint(Matrix()) );\n CALL_SUBTEST_2( adjoint(Matrix3d()) );\n CALL_SUBTEST_3( adjoint(Matrix4f()) );\n CALL_SUBTEST_4( adjoint(MatrixXcf(internal::random(1,EIGEN_TEST_MAX_SIZE\/2), internal::random(1,EIGEN_TEST_MAX_SIZE\/2))) );\n CALL_SUBTEST_5( adjoint(MatrixXi(internal::random(1,EIGEN_TEST_MAX_SIZE), internal::random(1,EIGEN_TEST_MAX_SIZE))) );\n CALL_SUBTEST_6( adjoint(MatrixXf(internal::random(1,EIGEN_TEST_MAX_SIZE), internal::random(1,EIGEN_TEST_MAX_SIZE))) );\n }\n \/\/ test a large static matrix only once\n CALL_SUBTEST_7( adjoint(Matrix()) );\n\n#ifdef EIGEN_TEST_PART_4\n {\n MatrixXcf a(10,10), b(10,10);\n VERIFY_RAISES_ASSERT(a = a.transpose());\n VERIFY_RAISES_ASSERT(a = a.transpose() + b);\n VERIFY_RAISES_ASSERT(a = b + a.transpose());\n VERIFY_RAISES_ASSERT(a = a.conjugate().transpose());\n VERIFY_RAISES_ASSERT(a = a.adjoint());\n VERIFY_RAISES_ASSERT(a = a.adjoint() + b);\n VERIFY_RAISES_ASSERT(a = b + a.adjoint());\n\n \/\/ no assertion should be triggered for these cases:\n a.transpose() = a.transpose();\n a.transpose() += a.transpose();\n a.transpose() += a.transpose() + b;\n a.transpose() = a.adjoint();\n a.transpose() += a.adjoint();\n a.transpose() += a.adjoint() + b;\n }\n#endif\n}\n\n<|endoftext|>"} {"text":"\n\/\/\/\/using the C++ API\n\n#include \"zorba\/zorba_api.h\"\n\n\/\/for debug\n\/\/#include \"..\/src\/compiler\/parser\/xquery_driver.h\"\n#include \"..\/src\/util\/logging\/loggermanager.hh\"\n#include \"timer.h\"\n#include \"error_display.h\"\n#include \"zorba\/util\/properties.h\"\n\n#ifdef WIN32\n\t#include \"..\/src\/util\/win32\/compatib_defs.h\"\n#endif\n\n#include \n#include \n#include \n\nusing namespace xqp;\nusing namespace std;\n\nint apitest_alert_callback(ZorbaAlert *alert_mess, \n XQuery* current_xquery,\n XQueryExecution* current_xqueryresult,\n void *param)\n{\n#ifndef NDEBUG\n if((alert_mess->alert_type != ZorbaAlert::USER_ERROR_ALERT) &&\n (alert_mess->alert_type != ZorbaAlert::USER_TRACE_ALERT))\n {\n cerr << g_error_in_file << \" : \" << g_error_at_line << endl;\n }\n#endif\n cerr << endl;\n\n DisplayOneAlert(alert_mess);\n\n cerr.flush();\n\n return -1;\n}\n\nvoid set_var (string name, string val, DynamicQueryContext_t dctx, XQueryExecution_t result) {\n if (name [name.size () - 1] == ':' && dctx != NULL) {\n dctx->SetVariable (name.substr (0, name.size () - 1), xqp_string (val));\n } else if (name [name.size () - 1] != ':' && result != NULL) {\n ifstream is (val.c_str ());\n assert (is);\n result->SetVariable (name, is);\n }\n}\n\n#ifndef _WIN32_WCE\nint main(int argc, char* argv[])\n#else\nint _tmain(int argc, _TCHAR* argv[])\n#endif\n{\n Timer timer;\n timer.start();\n\n\n if (!Properties::load(argc,argv))\n return 1;\n \n Properties* lProp = Properties::instance();\n \n xqp::LoggerManager::logmanager()->setLoggerConfig(\"#1#logging.log\");\n\n ofstream* resultFile = NULL;\n string query_text = \"1+2\"; \/\/ the default query if no file or query is specified\n\n#ifndef NDEBUG\n g_abort_when_fatal_error = lProp->abortWhenFatalError();\n#endif\n\n const char* fname = lProp->getQuery().c_str();\n#ifndef UNICODE\n if (lProp->inlineQuery())\n query_text = fname; \n#endif\n\n#ifdef UNICODE\n if(! lProp->inlineQuery())\n {\n char testfile[1024];\n WideCharToMultiByte(CP_ACP, 0, \/\/ or CP_UTF8\n *argv, -1, \n testfile, sizeof(testfile)\/sizeof(char),\n NULL, NULL);\n fname = testfile;\n }\n#endif\n if(! lProp->inlineQuery())\n { \n \/\/ read the file\n ifstream qfile(fname);\n \n if(!qfile.is_open())\n query_text = fname;\n else {\n string temp;\n query_text = \"\";\n \n \/\/ warning: this method of reading a file might trim the \n \/\/ whitespace at the end of lines\n while (getline(qfile, temp)) {\n if (query_text != \"\")\n query_text += \"\\n\";\n \n query_text += temp;\n } \n } \n }\n \n if (lProp->printQuery())\n std::cout << query_text << std::endl;\n\n\n \/\/\/ now start the zorba engine\n\n ZorbaEngine& zorba_factory = ZorbaEngine::getInstance();\n\n \/\/\/ thread specific\n\n zorba_factory.initThread();\n\n \/\/\/ register the alerts callback\n ZorbaAlertsManager& errmanager = zorba_factory.getAlertsManagerForCurrentThread();\n\n errmanager.RegisterAlertCallback(apitest_alert_callback, (void*)101);\n\n StaticQueryContext_t sctx1;\n\n sctx1 = zorba_factory.createStaticContext();\n sctx1->AddCollation(\"http:\/\/www.flworfound.org\/apitest\/coll1\", \"en\");\n sctx1->AddCollation(\"http:\/\/www.flworfound.org\/apitest\/coll2\", \"de\");\n sctx1->AddCollation(\"http:\/\/www.flworfound.org\/apitest\/coll2\", \"fr\");\n sctx1->SetOrderingMode(StaticQueryContext::unordered);\n StaticQueryContext::xpath1_0compatib_mode_t default_compatib_mode;\n default_compatib_mode = sctx1->GetXPath1_0CompatibMode();\n\n vector > ext_vars = lProp->getExternalVars ();\n\n XQuery_t query;\n XQueryExecution_t result = NULL;\n\n DynamicQueryContext_t dctx = zorba_factory.createDynamicContext ();\n for (vector >::iterator iter = ext_vars.begin ();\n iter != ext_vars.end (); iter++)\n set_var (iter->first, iter->second, dctx, NULL);\n\n \/\/ create a compiled query\n query = zorba_factory.createQuery(query_text.c_str(), sctx1);\n\n if(query.isNull())\n {\n goto DisplayErrorsAndExit;\n }\n\n result = query->createExecution(dctx);\n if(result.isNull())\n {\n goto DisplayErrorsAndExit;\n }\n\n for (vector >::iterator iter = ext_vars.begin ();\n iter != ext_vars.end (); iter++)\n set_var (iter->first, iter->second, NULL, result);\n\n result->setAlertsParam(result.get_ptr());\/\/\/to be passed to alerts callback when error occurs\n\n if (lProp->useResultFile())\n resultFile = new ofstream(lProp->getResultFile().c_str());\n\n\n if (lProp->useSerializer()) {\n if (lProp->useResultFile()) {\n result->serialize(*resultFile);\n \/\/ endl should not be sent when serializing!\n }\n else result->serialize(std::cout);\n }\n else {\n while( true )\n {\n Item_t it = result->next();\n if(it == NULL)\n break;\n\n if (resultFile != NULL)\n *resultFile << it->show() << endl;\n else\n cout << it->show() << endl;\n }\n }\n if(result->isError()) {\n goto DisplayErrorsAndExit;\n }\n\n \/\/ delete result;\n \/\/ delete query;\n \/\/ zorba_factory.destroyQuery(query);\n\n zorba_factory.uninitThread();\n zorba_factory.shutdown();\n\n timer.end();\n\n if (lProp->printTime())\n timer.print(cout);\n \n if (resultFile != NULL) {\n resultFile->close();\n delete resultFile;\n }\n\n return 0;\n\nDisplayErrorsAndExit:\n cerr << endl << \"Error list:\" << endl;\n\n DisplayErrorListForCurrentThread();\n\n zorba_factory.uninitThread();\n zorba_factory.shutdown();\n\n timer.end();\n if (lProp->printTime())\n timer.print(cout);\n \n return 0;\n}\n\nRemoved apitest \"feature\" that assumes a file name is an actual query when the file cannot be open.\n\/\/\/\/using the C++ API\n\n#include \"zorba\/zorba_api.h\"\n\n\/\/for debug\n\/\/#include \"..\/src\/compiler\/parser\/xquery_driver.h\"\n#include \"..\/src\/util\/logging\/loggermanager.hh\"\n#include \"timer.h\"\n#include \"error_display.h\"\n#include \"zorba\/util\/properties.h\"\n\n#ifdef WIN32\n\t#include \"..\/src\/util\/win32\/compatib_defs.h\"\n#endif\n\n#include \n#include \n#include \n\nusing namespace xqp;\nusing namespace std;\n\nint apitest_alert_callback(ZorbaAlert *alert_mess, \n XQuery* current_xquery,\n XQueryExecution* current_xqueryresult,\n void *param)\n{\n#ifndef NDEBUG\n if((alert_mess->alert_type != ZorbaAlert::USER_ERROR_ALERT) &&\n (alert_mess->alert_type != ZorbaAlert::USER_TRACE_ALERT))\n {\n cerr << g_error_in_file << \" : \" << g_error_at_line << endl;\n }\n#endif\n cerr << endl;\n\n DisplayOneAlert(alert_mess);\n\n cerr.flush();\n\n return -1;\n}\n\nvoid set_var (string name, string val, DynamicQueryContext_t dctx, XQueryExecution_t result) {\n if (name [name.size () - 1] == ':' && dctx != NULL) {\n dctx->SetVariable (name.substr (0, name.size () - 1), xqp_string (val));\n } else if (name [name.size () - 1] != ':' && result != NULL) {\n ifstream is (val.c_str ());\n assert (is);\n result->SetVariable (name, is);\n }\n}\n\n#ifndef _WIN32_WCE\nint main(int argc, char* argv[])\n#else\nint _tmain(int argc, _TCHAR* argv[])\n#endif\n{\n Timer timer;\n timer.start();\n\n\n if (!Properties::load(argc,argv))\n return 1;\n \n Properties* lProp = Properties::instance();\n \n xqp::LoggerManager::logmanager()->setLoggerConfig(\"#1#logging.log\");\n\n ofstream* resultFile = NULL;\n string query_text = \"1+2\"; \/\/ the default query if no file or query is specified\n\n#ifndef NDEBUG\n g_abort_when_fatal_error = lProp->abortWhenFatalError();\n#endif\n\n const char* fname = lProp->getQuery().c_str();\n#ifndef UNICODE\n if (lProp->inlineQuery())\n query_text = fname; \n#endif\n\n#ifdef UNICODE\n if(! lProp->inlineQuery())\n {\n char testfile[1024];\n WideCharToMultiByte(CP_ACP, 0, \/\/ or CP_UTF8\n *argv, -1, \n testfile, sizeof(testfile)\/sizeof(char),\n NULL, NULL);\n fname = testfile;\n }\n#endif\n if(! lProp->inlineQuery()) {\n \/\/ read the file\n ifstream qfile(fname);\n assert (qfile);\n \n {\n string temp;\n query_text = \"\";\n \n \/\/ warning: this method of reading a file might trim the \n \/\/ whitespace at the end of lines\n while (getline(qfile, temp)) {\n if (query_text != \"\")\n query_text += \"\\n\";\n \n query_text += temp;\n } \n } \n }\n \n if (lProp->printQuery())\n std::cout << query_text << std::endl;\n\n\n \/\/\/ now start the zorba engine\n\n ZorbaEngine& zorba_factory = ZorbaEngine::getInstance();\n\n \/\/\/ thread specific\n\n zorba_factory.initThread();\n\n \/\/\/ register the alerts callback\n ZorbaAlertsManager& errmanager = zorba_factory.getAlertsManagerForCurrentThread();\n\n errmanager.RegisterAlertCallback(apitest_alert_callback, (void*)101);\n\n StaticQueryContext_t sctx1;\n\n sctx1 = zorba_factory.createStaticContext();\n sctx1->AddCollation(\"http:\/\/www.flworfound.org\/apitest\/coll1\", \"en\");\n sctx1->AddCollation(\"http:\/\/www.flworfound.org\/apitest\/coll2\", \"de\");\n sctx1->AddCollation(\"http:\/\/www.flworfound.org\/apitest\/coll2\", \"fr\");\n sctx1->SetOrderingMode(StaticQueryContext::unordered);\n StaticQueryContext::xpath1_0compatib_mode_t default_compatib_mode;\n default_compatib_mode = sctx1->GetXPath1_0CompatibMode();\n\n vector > ext_vars = lProp->getExternalVars ();\n\n XQuery_t query;\n XQueryExecution_t result = NULL;\n\n DynamicQueryContext_t dctx = zorba_factory.createDynamicContext ();\n for (vector >::iterator iter = ext_vars.begin ();\n iter != ext_vars.end (); iter++)\n set_var (iter->first, iter->second, dctx, NULL);\n\n \/\/ create a compiled query\n query = zorba_factory.createQuery(query_text.c_str(), sctx1);\n\n if(query.isNull())\n {\n goto DisplayErrorsAndExit;\n }\n\n result = query->createExecution(dctx);\n if(result.isNull())\n {\n goto DisplayErrorsAndExit;\n }\n\n for (vector >::iterator iter = ext_vars.begin ();\n iter != ext_vars.end (); iter++)\n set_var (iter->first, iter->second, NULL, result);\n\n result->setAlertsParam(result.get_ptr());\/\/\/to be passed to alerts callback when error occurs\n\n if (lProp->useResultFile())\n resultFile = new ofstream(lProp->getResultFile().c_str());\n\n\n if (lProp->useSerializer()) {\n if (lProp->useResultFile()) {\n result->serialize(*resultFile);\n \/\/ endl should not be sent when serializing!\n }\n else result->serialize(std::cout);\n }\n else {\n while( true )\n {\n Item_t it = result->next();\n if(it == NULL)\n break;\n\n if (resultFile != NULL)\n *resultFile << it->show() << endl;\n else\n cout << it->show() << endl;\n }\n }\n if(result->isError()) {\n goto DisplayErrorsAndExit;\n }\n\n \/\/ delete result;\n \/\/ delete query;\n \/\/ zorba_factory.destroyQuery(query);\n\n zorba_factory.uninitThread();\n zorba_factory.shutdown();\n\n timer.end();\n\n if (lProp->printTime())\n timer.print(cout);\n \n if (resultFile != NULL) {\n resultFile->close();\n delete resultFile;\n }\n\n return 0;\n\nDisplayErrorsAndExit:\n cerr << endl << \"Error list:\" << endl;\n\n DisplayErrorListForCurrentThread();\n\n zorba_factory.uninitThread();\n zorba_factory.shutdown();\n\n timer.end();\n if (lProp->printTime())\n timer.print(cout);\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \"applesoftfile.h\"\n#include \n\nApplesoftFile::ApplesoftFile(QByteArray data) : GenericFile(data)\n{\n if (m_tokens.size() == 0)\n {\n makeTokens();\n }\n\n if (!data.isEmpty())\n {\n setData(data);\n }\n}\n\nvoid ApplesoftFile::setData(QByteArray data)\n{\n GenericFile::setData(data);\n\n quint8 addlo = m_data.at(0);\n quint8 addhi = m_data.at(1);\n m_length = addlo + (addhi * 256);\n m_data.remove(0,2);\n m_detokenized = detokenize();\n}\n\nQList ApplesoftFile::detokenize()\n{\n QList retval;\n\n\/*\n qDebug() << \"Length: \" << m_length;\n for (int idx = 0; idx < m_length; idx += 8)\n {\n qDebug()\n << QString(\"%1 (%2): %3 %4 %5 %6 %7 %8 %9 %10\")\n .arg((quint16) idx + 0x801,4,16,QChar('0')).toUpper()\n .arg((quint16) idx + 0x801,4,10,QChar('0'))\n .arg((quint8) m_data[idx],2,16,QChar('0')).toUpper()\n .arg((quint8) m_data[idx+1],2,16,QChar('0')).toUpper()\n .arg((quint8) m_data[idx+2],2,16,QChar('0')).toUpper()\n .arg((quint8) m_data[idx+3],2,16,QChar('0')).toUpper()\n .arg((quint8) m_data[idx+4],2,16,QChar('0')).toUpper()\n .arg((quint8) m_data[idx+5],2,16,QChar('0')).toUpper()\n .arg((quint8) m_data[idx+6],2,16,QChar('0')).toUpper()\n .arg((quint8) m_data[idx+7],2,16,QChar('0')).toUpper();\n\n }\n*\/\n int idx = 0;\n quint8 val = 0;\n while (idx < m_data.length()) {\n ApplesoftLine line;\n line.next_address = (quint8) m_data[idx] + (((quint8) m_data[idx+1]) *256);\n line.tokens.append(m_data[idx]);\n line.tokens.append(m_data[idx+1]);\n idx++; idx++;\n line.linenum = (quint8) m_data[idx] + (((quint8) m_data[idx+1])*256);\n line.tokens.append(m_data[idx]);\n line.tokens.append(m_data[idx+1]);\n idx++; idx++;\n if (line.next_address == 0x00) { break; }\n do {\n val = m_data[idx++];\n line.tokens.append(val);\n if (val >= 0x80) {\n line.detokenized_line.append(\" \" + m_tokens[val]);\n } else {\n if (val >= 0x20) {\n line.detokenized_line.append(val);\n } else if (val == 0x7F) {\n QChar ch = QChar(0x2401);\n line.detokenized_line.append(ch);\n }else if (val > 0x00) {\n QChar ch = QChar(0x00 + val);\n line.detokenized_line.append(ch);\n }\n }\n } while (val != 0x00);\n retval.append(line);\n }\n\n m_data_end = idx;\n\n if (idx < m_data.length()) {\n qDebug() << QString(\"%1 byte(s) unaccounted for.\").arg(m_data.length() - idx);\n }\n\n return retval;\n}\n\nvoid ApplesoftFile::list() {\n foreach (ApplesoftLine line,detokenized()) {\n QString debugline = QString(\"%1 %2 %3\").arg(line.next_address,4,16,QChar('0')).arg(line.linenum).arg(line.detokenized_line);\n qDebug() << debugline;\n\/*\n debugline = \"\";\n foreach (quint8 val, line.tokens) {\n debugline.append(QString(\"%1 \").arg(val,2,16,QChar('0')));\n }\n qDebug() << \" \" << debugline;\n qDebug() << \"\\n\";\n*\/\n }\n\n qDebug() << extraDataHexValues().join(\"\\n\");\n}\n\nQStringList ApplesoftFile::extraDataHexValues() {\n QStringList retval;\n\n QString debugline = \"\";\n int count = 0;\n foreach (quint8 val, extraData()) {\n debugline.append(QString(\"%1\").arg(val,2,16,QChar('0')).toUpper());\n count++;\n if (count == 16) {\n retval.append(debugline);\n debugline = \"\";\n count = 0;\n } else {\n debugline.append(\" \");\n }\n }\n if (!debugline.simplified().isEmpty()) {\n retval.append(debugline);\n }\n return retval;\n}\n\nQByteArray ApplesoftFile::extraData()\n{\n return m_data.mid(m_data_end);\n}\n\nvoid ApplesoftFile::makeTokens()\n{\n m_tokens[0x80] = \"END \"; m_tokens[0x81] = \"FOR \"; m_tokens[0x82] = \"NEXT \";\n m_tokens[0x83] = \"DATA \"; m_tokens[0x84] = \"INPUT \"; m_tokens[0x85] = \" DEL \";\n m_tokens[0x86] = \"DIM \"; m_tokens[0x87] = \"READ \"; m_tokens[0x88] = \"GR \";\n m_tokens[0x89] = \"TEXT \"; m_tokens[0x8A] = \"PR# \"; m_tokens[0x8B] = \"IN# \";\n m_tokens[0x8C] = \"CALL \"; m_tokens[0x8D] = \"PLOT \"; m_tokens[0x8E] = \"HLIN \";\n m_tokens[0x8F] = \"VLIN \"; m_tokens[0x90] = \"HGR2 \"; m_tokens[0x91] = \"HGR \";\n m_tokens[0x92] = \"HCOLOR= \"; m_tokens[0x93] = \"HPLOT \"; m_tokens[0x94] = \"DRAW \";\n m_tokens[0x95] = \"XDRAW \"; m_tokens[0x96] = \"HTAB \"; m_tokens[0x97] = \"HOME \";\n m_tokens[0x98] = \"ROT= \"; m_tokens[0x99] = \"SCALE= \"; m_tokens[0x9A] = \"SHLOAD \";\n m_tokens[0x9B] = \"TRACE \"; m_tokens[0x9C] = \"NOTRACE \"; m_tokens[0x9D] = \"NORMAL \";\n m_tokens[0x9E] = \"INVERSE \"; m_tokens[0x9F] = \"FLASH \"; m_tokens[0xA0] = \"COLOR= \";\n m_tokens[0xA1] = \"POP \"; m_tokens[0xA2] = \"VTAB \"; m_tokens[0xA3] = \"HIMEM: \";\n m_tokens[0xA4] = \"LOMEM: \"; m_tokens[0xA5] = \"ONERR \"; m_tokens[0xA6] = \"RESUME \";\n m_tokens[0xA7] = \"RECALL \"; m_tokens[0xA8] = \"STORE \"; m_tokens[0xA9] = \"SPEED= \";\n m_tokens[0xAA] = \"LET \"; m_tokens[0xAB] = \"GOTO \"; m_tokens[0xAC] = \"RUN \";\n m_tokens[0xAD] = \"IF \"; m_tokens[0xAE] = \"RESTORE \"; m_tokens[0xAF] = \"& \";\n m_tokens[0xB0] = \"GOSUB \"; m_tokens[0xB1] = \"RETURN \"; m_tokens[0xB2] = \"REM \";\n m_tokens[0xB3] = \"STOP \"; m_tokens[0xB4] = \"ON \"; m_tokens[0xB5] = \"WAIT \";\n m_tokens[0xB6] = \"LOAD \"; m_tokens[0xB7] = \"SAVE \"; m_tokens[0xB8] = \"DEF \";\n m_tokens[0xB9] = \"POKE \"; m_tokens[0xBA] = \"PRINT \"; m_tokens[0xBB] = \"CONT \";\n m_tokens[0xBC] = \"LIST \"; m_tokens[0xBD] = \"CLEAR \"; m_tokens[0xBE] = \"GET \";\n m_tokens[0xBF] = \"NEW \"; m_tokens[0xC0] = \"TAB \"; m_tokens[0xC1] = \" TO \";\n m_tokens[0xC2] = \"FN \"; m_tokens[0xC3] = \"SPC( \"; m_tokens[0xC4] = \"THEN \";\n m_tokens[0xC5] = \" AT \"; m_tokens[0xC6] = \"NOT \"; m_tokens[0xC7] = \" STEP \";\n m_tokens[0xC8] = \"+ \"; m_tokens[0xC9] = \"- \"; m_tokens[0xCA] = \"* \";\n m_tokens[0xCB] = \"\/ \"; m_tokens[0xCC] = \"^ \"; m_tokens[0xCD] = \" AND\";\n m_tokens[0xCE] = \" OR\"; m_tokens[0xCF] = \"> \"; m_tokens[0xD0] = \"= \";\n m_tokens[0xD1] = \"< \"; m_tokens[0xD2] = \"SGN \"; m_tokens[0xD3] = \"INT \";\n m_tokens[0xD4] = \"ABS \"; m_tokens[0xD5] = \"USR \"; m_tokens[0xD6] = \"FRE \";\n m_tokens[0xD7] = \"SCRN ( \"; m_tokens[0xD8] = \"PDL \"; m_tokens[0xD9] = \"POS \";\n m_tokens[0xDA] = \"SQR \"; m_tokens[0xDB] = \"RND \"; m_tokens[0xDC] = \"LOG \";\n m_tokens[0xDD] = \"EXP \"; m_tokens[0xDE] = \"COS \"; m_tokens[0xDF] = \"SIN \";\n m_tokens[0xE0] = \"TAN \"; m_tokens[0xE1] = \"ATN \"; m_tokens[0xE2] = \"PEEK \";\n m_tokens[0xE3] = \"LEN \"; m_tokens[0xE4] = \"STR$ \"; m_tokens[0xE5] = \"VAL \";\n m_tokens[0xE6] = \"ASC \"; m_tokens[0xE7] = \"CHR$ \"; m_tokens[0xE8] = \"LEFT$ \";\n m_tokens[0xE9] = \"RIGHT$ \"; m_tokens[0xEA] = \"MID$ \"; m_tokens[0xEB] = \"{Token 0xEB} \";\n m_tokens[0xEC] = \"{Token 0xEC} \";\n m_tokens[0xED] = \"{Token 0xED} \";\n m_tokens[0xEE] = \"{Token 0xEE} \";\n m_tokens[0xEF] = \"{Token 0xEF} \";\n m_tokens[0xF0] = \"{Token 0xF0} \";\n m_tokens[0xF1] = \"{Token 0xF1} \";\n m_tokens[0xF2] = \"{Token 0xF2} \";\n m_tokens[0xF3] = \"{Token 0xF3} \";\n m_tokens[0xF4] = \"{Token 0xF4} \";\n m_tokens[0xF5] = \"{Token 0xF5} \";\n m_tokens[0xF6] = \"{Token 0xF6} \";\n m_tokens[0xF7] = \"{Token 0xF7} \";\n m_tokens[0xF8] = \"{Token 0xF8} \";\n m_tokens[0xF9] = \"{Token 0xF9} \";\n m_tokens[0xFA] = \"{Token 0xFA} \";\n m_tokens[0xFB] = \"{Token 0xFB} \";\n m_tokens[0xFC] = \"{Token 0xFC} \";\n m_tokens[0xFD] = \"{Token 0xFD} \";\n m_tokens[0xFE] = \"{Token 0xFE} \";\n m_tokens[0xFF] = \"{Token 0xFF} \";\n}\nUdpated token values#include \"applesoftfile.h\"\n#include \n\nApplesoftFile::ApplesoftFile(QByteArray data) : GenericFile(data)\n{\n if (m_tokens.size() == 0)\n {\n makeTokens();\n }\n\n if (!data.isEmpty())\n {\n setData(data);\n }\n}\n\nvoid ApplesoftFile::setData(QByteArray data)\n{\n GenericFile::setData(data);\n\n quint8 addlo = m_data.at(0);\n quint8 addhi = m_data.at(1);\n m_length = addlo + (addhi * 256);\n m_data.remove(0,2);\n m_detokenized = detokenize();\n}\n\nQList ApplesoftFile::detokenize()\n{\n QList retval;\n\n\/*\n qDebug() << \"Length: \" << m_length;\n for (int idx = 0; idx < m_length; idx += 8)\n {\n qDebug()\n << QString(\"%1 (%2): %3 %4 %5 %6 %7 %8 %9 %10\")\n .arg((quint16) idx + 0x801,4,16,QChar('0')).toUpper()\n .arg((quint16) idx + 0x801,4,10,QChar('0'))\n .arg((quint8) m_data[idx],2,16,QChar('0')).toUpper()\n .arg((quint8) m_data[idx+1],2,16,QChar('0')).toUpper()\n .arg((quint8) m_data[idx+2],2,16,QChar('0')).toUpper()\n .arg((quint8) m_data[idx+3],2,16,QChar('0')).toUpper()\n .arg((quint8) m_data[idx+4],2,16,QChar('0')).toUpper()\n .arg((quint8) m_data[idx+5],2,16,QChar('0')).toUpper()\n .arg((quint8) m_data[idx+6],2,16,QChar('0')).toUpper()\n .arg((quint8) m_data[idx+7],2,16,QChar('0')).toUpper();\n\n }\n*\/\n int idx = 0;\n quint8 val = 0;\n while (idx < m_data.length()) {\n ApplesoftLine line;\n line.next_address = (quint8) m_data[idx] + (((quint8) m_data[idx+1]) *256);\n line.tokens.append(m_data[idx]);\n line.tokens.append(m_data[idx+1]);\n idx++; idx++;\n line.linenum = (quint8) m_data[idx] + (((quint8) m_data[idx+1])*256);\n line.tokens.append(m_data[idx]);\n line.tokens.append(m_data[idx+1]);\n idx++; idx++;\n if (line.next_address == 0x00) { break; }\n do {\n val = m_data[idx++];\n line.tokens.append(val);\n if (val >= 0x80) {\n line.detokenized_line.append(\" \" + m_tokens[val]);\n } else {\n if (val >= 0x20) {\n line.detokenized_line.append(val);\n } else if (val == 0x7F) {\n QChar ch = QChar(0x2401);\n line.detokenized_line.append(ch);\n }else if (val > 0x00) {\n QChar ch = QChar(0x00 + val);\n line.detokenized_line.append(ch);\n }\n }\n } while (val != 0x00);\n retval.append(line);\n }\n\n m_data_end = idx;\n\n if (idx < m_data.length()) {\n qDebug() << QString(\"%1 byte(s) unaccounted for.\").arg(m_data.length() - idx);\n }\n\n return retval;\n}\n\nvoid ApplesoftFile::list() {\n foreach (ApplesoftLine line,detokenized()) {\n QString debugline = QString(\"%1 %2 %3\").arg(line.next_address,4,16,QChar('0')).arg(line.linenum).arg(line.detokenized_line);\n qDebug() << debugline;\n\/*\n debugline = \"\";\n foreach (quint8 val, line.tokens) {\n debugline.append(QString(\"%1 \").arg(val,2,16,QChar('0')));\n }\n qDebug() << \" \" << debugline;\n qDebug() << \"\\n\";\n*\/\n }\n\n qDebug() << extraDataHexValues().join(\"\\n\");\n}\n\nQStringList ApplesoftFile::extraDataHexValues() {\n QStringList retval;\n\n QString debugline = \"\";\n int count = 0;\n foreach (quint8 val, extraData()) {\n debugline.append(QString(\"%1\").arg(val,2,16,QChar('0')).toUpper());\n count++;\n if (count == 16) {\n retval.append(debugline);\n debugline = \"\";\n count = 0;\n } else {\n debugline.append(\" \");\n }\n }\n if (!debugline.simplified().isEmpty()) {\n retval.append(debugline);\n }\n return retval;\n}\n\nQByteArray ApplesoftFile::extraData()\n{\n return m_data.mid(m_data_end);\n}\n\nvoid ApplesoftFile::makeTokens()\n{\n m_tokens[0x80] = \" END \"; m_tokens[0x81] = \" FOR \"; m_tokens[0x82] = \" NEXT \";\n m_tokens[0x83] = \" DATA \"; m_tokens[0x84] = \" INPUT \"; m_tokens[0x85] = \" DEL \";\n m_tokens[0x86] = \" DIM \"; m_tokens[0x87] = \" READ \"; m_tokens[0x88] = \" GR \";\n m_tokens[0x89] = \" TEXT \"; m_tokens[0x8A] = \" PR# \"; m_tokens[0x8B] = \" IN# \";\n m_tokens[0x8C] = \" CALL \"; m_tokens[0x8D] = \" PLOT \"; m_tokens[0x8E] = \" HLIN \";\n m_tokens[0x8F] = \" VLIN \"; m_tokens[0x90] = \" HGR2 \"; m_tokens[0x91] = \" HGR \";\n m_tokens[0x92] = \" HCOLOR= \"; m_tokens[0x93] = \" HPLOT \"; m_tokens[0x94] = \" DRAW \";\n m_tokens[0x95] = \" XDRAW \"; m_tokens[0x96] = \" HTAB \"; m_tokens[0x97] = \" HOME \";\n m_tokens[0x98] = \" ROT= \"; m_tokens[0x99] = \" SCALE= \"; m_tokens[0x9A] = \" SHLOAD \";\n m_tokens[0x9B] = \" TRACE \"; m_tokens[0x9C] = \" NOTRACE \"; m_tokens[0x9D] = \" NORMAL \";\n m_tokens[0x9E] = \" INVERSE \"; m_tokens[0x9F] = \" FLASH \"; m_tokens[0xA0] = \" COLOR= \";\n m_tokens[0xA1] = \" POP \"; m_tokens[0xA2] = \" VTAB \"; m_tokens[0xA3] = \" HIMEM: \";\n m_tokens[0xA4] = \" LOMEM: \"; m_tokens[0xA5] = \" ONERR \"; m_tokens[0xA6] = \" RESUME \";\n m_tokens[0xA7] = \" RECALL \"; m_tokens[0xA8] = \" STORE \"; m_tokens[0xA9] = \" SPEED= \";\n m_tokens[0xAA] = \" LET \"; m_tokens[0xAB] = \" GOTO \"; m_tokens[0xAC] = \" RUN \";\n m_tokens[0xAD] = \" IF \"; m_tokens[0xAE] = \" RESTORE \"; m_tokens[0xAF] = \" & \";\n m_tokens[0xB0] = \" GOSUB \"; m_tokens[0xB1] = \" RETURN \"; m_tokens[0xB2] = \" REM \";\n m_tokens[0xB3] = \" STOP \"; m_tokens[0xB4] = \" ON \"; m_tokens[0xB5] = \" WAIT \";\n m_tokens[0xB6] = \" LOAD \"; m_tokens[0xB7] = \" SAVE \"; m_tokens[0xB8] = \" DEF \";\n m_tokens[0xB9] = \" POKE \"; m_tokens[0xBA] = \" PRINT \"; m_tokens[0xBB] = \" CONT \";\n m_tokens[0xBC] = \" LIST \"; m_tokens[0xBD] = \" CLEAR \"; m_tokens[0xBE] = \" GET \";\n m_tokens[0xBF] = \" NEW \"; m_tokens[0xC0] = \" TAB \"; m_tokens[0xC1] = \" TO \";\n m_tokens[0xC2] = \" FN \"; m_tokens[0xC3] = \" SPC( \"; m_tokens[0xC4] = \" THEN \";\n m_tokens[0xC5] = \" AT \"; m_tokens[0xC6] = \" NOT \"; m_tokens[0xC7] = \" STEP \";\n m_tokens[0xC8] = \" +\"; m_tokens[0xC9] = \" -\"; m_tokens[0xCA] = \" *\";\n m_tokens[0xCB] = \" \/\"; m_tokens[0xCC] = \" ^\"; m_tokens[0xCD] = \" AND \";\n m_tokens[0xCE] = \" OR \"; m_tokens[0xCF] = \" >\"; m_tokens[0xD0] = \" =\";\n m_tokens[0xD1] = \" <\"; m_tokens[0xD2] = \" SGN\"; m_tokens[0xD3] = \" INT\";\n m_tokens[0xD4] = \" ABS\"; m_tokens[0xD5] = \" USR\"; m_tokens[0xD6] = \" FRE\";\n m_tokens[0xD7] = \" SCRN( \"; m_tokens[0xD8] = \" PDL\"; m_tokens[0xD9] = \" POS\";\n m_tokens[0xDA] = \" SQR\"; m_tokens[0xDB] = \" RND\"; m_tokens[0xDC] = \" LOG\";\n m_tokens[0xDD] = \" EXP\"; m_tokens[0xDE] = \" COS\"; m_tokens[0xDF] = \" SIN\";\n m_tokens[0xE0] = \" TAN\"; m_tokens[0xE1] = \" ATN\"; m_tokens[0xE2] = \" PEEK\";\n m_tokens[0xE3] = \" LEN\"; m_tokens[0xE4] = \" STR$\"; m_tokens[0xE5] = \" VAL\";\n m_tokens[0xE6] = \" ASC\"; m_tokens[0xE7] = \" CHR$\"; m_tokens[0xE8] = \" LEFT$ \";\n m_tokens[0xE9] = \" RIGHT$ \"; m_tokens[0xEA] = \" MID$ \"; m_tokens[0xEB] = \"{Token 0xEB} \";\n m_tokens[0xEC] = \"{Token 0xEC} \";\n m_tokens[0xED] = \"{Token 0xED} \";\n m_tokens[0xEE] = \"{Token 0xEE} \";\n m_tokens[0xEF] = \"{Token 0xEF} \";\n m_tokens[0xF0] = \"{Token 0xF0} \";\n m_tokens[0xF1] = \"{Token 0xF1} \";\n m_tokens[0xF2] = \"{Token 0xF2} \";\n m_tokens[0xF3] = \"{Token 0xF3} \";\n m_tokens[0xF4] = \"{Token 0xF4} \";\n m_tokens[0xF5] = \"{Token 0xF5} \";\n m_tokens[0xF6] = \"{Token 0xF6} \";\n m_tokens[0xF7] = \"{Token 0xF7} \";\n m_tokens[0xF8] = \"{Token 0xF8} \";\n m_tokens[0xF9] = \"{Token 0xF9} \";\n m_tokens[0xFA] = \"{Token 0xFA} \";\n m_tokens[0xFB] = \"{Token 0xFB} \";\n m_tokens[0xFC] = \"{Token 0xFC} \";\n m_tokens[0xFD] = \"{Token 0xFD} \";\n m_tokens[0xFE] = \"{Token 0xFE} \";\n m_tokens[0xFF] = \"{Token 0xFF} \";\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) 2015-present Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#include \n\n#include \"hip_event.hpp\"\n\nnamespace hip {\n\nbool Event::ready() {\n if (event_->status() != CL_COMPLETE) {\n event_->notifyCmdQueue();\n }\n\n return (event_->status() == CL_COMPLETE);\n}\n\nhipError_t Event::query() {\n amd::ScopedLock lock(lock_);\n\n if (event_ == nullptr) {\n return hipErrorInvalidHandle;\n }\n\n return ready() ? hipSuccess : hipErrorNotReady;\n}\n\nhipError_t Event::synchronize() {\n amd::ScopedLock lock(lock_);\n\n if (event_ == nullptr) {\n return hipErrorInvalidHandle;\n }\n\n event_->awaitCompletion();\n\n return hipSuccess;\n}\n\nhipError_t Event::elapsedTime(Event& eStop, float& ms) {\n amd::ScopedLock startLock(lock_);\n\n if (this == &eStop) {\n if (event_ == nullptr) {\n return hipErrorInvalidHandle;\n }\n\n if (flags & hipEventDisableTiming) {\n return hipErrorInvalidHandle;\n }\n\n if (!ready()) {\n return hipErrorNotReady;\n }\n\n ms = 0.f;\n return hipSuccess;\n }\n amd::ScopedLock stopLock(eStop.lock_);\n\n if (event_ == nullptr ||\n eStop.event_ == nullptr) {\n return hipErrorInvalidHandle;\n }\n\n if ((flags | eStop.flags) & hipEventDisableTiming) {\n return hipErrorInvalidHandle;\n }\n\n if (!ready() || !eStop.ready()) {\n return hipErrorNotReady;\n }\n\n ms = static_cast(static_cast(eStop.event_->profilingInfo().end_ -\n event_->profilingInfo().start_))\/1000000.f;\n\n return hipSuccess;\n}\n\nhipError_t Event::streamWait(amd::HostQueue* hostQueue, uint flags) {\n if ((event_ == nullptr) || (event_->command().queue() == hostQueue)) {\n return hipSuccess;\n }\n\n amd::ScopedLock lock(lock_);\n bool retain = false;\n\n if (!event_->notifyCmdQueue()) {\n return hipErrorLaunchOutOfResources;\n }\n amd::Command::EventWaitList eventWaitList;\n eventWaitList.push_back(event_);\n\n amd::Command* command = new amd::Marker(*hostQueue, false, eventWaitList);\n if (command == NULL) {\n return hipErrorOutOfMemory;\n }\n command->enqueue();\n command->release();\n\n return hipSuccess;\n}\n\nvoid Event::addMarker(amd::HostQueue* queue, amd::Command* command) {\n amd::ScopedLock lock(lock_);\n\n if (event_ == &command->event()) return;\n\n if (event_ != nullptr) {\n event_->release();\n }\n\n event_ = &command->event();\n}\n\n}\n\nhipError_t ihipEventCreateWithFlags(hipEvent_t* event, unsigned flags) {\n if (event == nullptr) {\n return hipErrorInvalidValue;\n }\n\n unsigned supportedFlags = hipEventDefault | hipEventBlockingSync | hipEventDisableTiming |\n hipEventReleaseToDevice | hipEventReleaseToSystem;\n const unsigned releaseFlags = (hipEventReleaseToDevice | hipEventReleaseToSystem);\n\n const bool illegalFlags =\n (flags & ~supportedFlags) || \/\/ can't set any unsupported flags.\n (flags & releaseFlags) == releaseFlags; \/\/ can't set both release flags\n\n if (!illegalFlags) {\n hip::Event* e = new hip::Event(flags);\n\n if (e == nullptr) {\n return hipErrorOutOfMemory;\n }\n\n *event = reinterpret_cast(e);\n } else {\n return hipErrorInvalidValue;\n }\n return hipSuccess;\n}\n\nhipError_t ihipEventQuery(hipEvent_t event) {\n if (event == nullptr) {\n return hipErrorInvalidHandle;\n }\n\n hip::Event* e = reinterpret_cast(event);\n\n return e->query();\n}\n\nhipError_t hipEventCreateWithFlags(hipEvent_t* event, unsigned flags) {\n HIP_INIT_API(hipEventCreateWithFlags, event, flags);\n\n HIP_RETURN(ihipEventCreateWithFlags(event, flags));\n}\n\nhipError_t hipEventCreate(hipEvent_t* event) {\n HIP_INIT_API(hipEventCreate, event);\n\n HIP_RETURN(ihipEventCreateWithFlags(event, 0));\n}\n\nhipError_t hipEventDestroy(hipEvent_t event) {\n HIP_INIT_API(hipEventDestroy, event);\n\n if (event == nullptr) {\n HIP_RETURN(hipErrorInvalidHandle);\n }\n\n delete reinterpret_cast(event);\n\n HIP_RETURN(hipSuccess);\n}\n\nhipError_t hipEventElapsedTime(float *ms, hipEvent_t start, hipEvent_t stop) {\n HIP_INIT_API(hipEventElapsedTime, ms, start, stop);\n\n if (start == nullptr || stop == nullptr) {\n HIP_RETURN(hipErrorInvalidHandle);\n }\n\n if (ms == nullptr) {\n HIP_RETURN(hipErrorInvalidValue);\n }\n\n hip::Event* eStart = reinterpret_cast(start);\n hip::Event* eStop = reinterpret_cast(stop);\n\n HIP_RETURN(eStart->elapsedTime(*eStop, *ms));\n}\n\nhipError_t hipEventRecord(hipEvent_t event, hipStream_t stream) {\n HIP_INIT_API(hipEventRecord, event, stream);\n\n if (event == nullptr) {\n HIP_RETURN(hipErrorInvalidHandle);\n }\n\n hip::Event* e = reinterpret_cast(event);\n\n hip::Stream* s = reinterpret_cast(stream);\n amd::HostQueue* queue = hip::getQueue(stream);\n\n amd::Command* command = (s != nullptr && (s->flags & hipStreamNonBlocking)) ?\n queue->getLastQueuedCommand(true) : nullptr;\n\n if (command == nullptr) {\n command = new amd::Marker(*queue, false);\n command->enqueue();\n }\n\n e->addMarker(queue, command);\n\n HIP_RETURN(hipSuccess);\n}\n\nhipError_t hipEventSynchronize(hipEvent_t event) {\n HIP_INIT_API(hipEventSynchronize, event);\n\n if (event == nullptr) {\n HIP_RETURN(hipErrorInvalidHandle);\n }\n\n hip::Event* e = reinterpret_cast(event);\n\n HIP_RETURN(e->synchronize());\n}\n\nhipError_t hipEventQuery(hipEvent_t event) {\n HIP_INIT_API(hipEventQuery, event);\n\n HIP_RETURN(ihipEventQuery(event));\n}\nWake up commandQueue before returning\/* Copyright (c) 2015-present Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#include \n\n#include \"hip_event.hpp\"\n\nnamespace hip {\n\nbool Event::ready() {\n if (event_->status() != CL_COMPLETE) {\n event_->notifyCmdQueue();\n }\n\n return (event_->status() == CL_COMPLETE);\n}\n\nhipError_t Event::query() {\n amd::ScopedLock lock(lock_);\n\n if (event_ == nullptr) {\n return hipErrorInvalidHandle;\n }\n\n return ready() ? hipSuccess : hipErrorNotReady;\n}\n\nhipError_t Event::synchronize() {\n amd::ScopedLock lock(lock_);\n\n if (event_ == nullptr) {\n return hipErrorInvalidHandle;\n }\n\n event_->awaitCompletion();\n\n return hipSuccess;\n}\n\nhipError_t Event::elapsedTime(Event& eStop, float& ms) {\n amd::ScopedLock startLock(lock_);\n\n if (this == &eStop) {\n if (event_ == nullptr) {\n return hipErrorInvalidHandle;\n }\n\n if (flags & hipEventDisableTiming) {\n return hipErrorInvalidHandle;\n }\n\n if (!ready()) {\n return hipErrorNotReady;\n }\n\n ms = 0.f;\n return hipSuccess;\n }\n amd::ScopedLock stopLock(eStop.lock_);\n\n if (event_ == nullptr ||\n eStop.event_ == nullptr) {\n return hipErrorInvalidHandle;\n }\n\n if ((flags | eStop.flags) & hipEventDisableTiming) {\n return hipErrorInvalidHandle;\n }\n\n if (!ready() || !eStop.ready()) {\n return hipErrorNotReady;\n }\n\n ms = static_cast(static_cast(eStop.event_->profilingInfo().end_ -\n event_->profilingInfo().start_))\/1000000.f;\n\n return hipSuccess;\n}\n\nhipError_t Event::streamWait(amd::HostQueue* hostQueue, uint flags) {\n \/\/ Effective no-op if event is NULL\n if (event_ == nullptr) {\n return hipSuccess;\n }\n\n amd::ScopedLock lock(lock_);\n\n if (event_->command().queue() == hostQueue) {\n \/\/ Wake up commandQueue thread\n if (!event_->notifyCmdQueue()) {\n return hipErrorLaunchOutOfResources;\n }\n return hipSuccess;\n }\n\n if (!event_->notifyCmdQueue()) {\n return hipErrorLaunchOutOfResources;\n }\n amd::Command::EventWaitList eventWaitList;\n eventWaitList.push_back(event_);\n\n amd::Command* command = new amd::Marker(*hostQueue, false, eventWaitList);\n if (command == NULL) {\n return hipErrorOutOfMemory;\n }\n command->enqueue();\n command->release();\n\n return hipSuccess;\n}\n\nvoid Event::addMarker(amd::HostQueue* queue, amd::Command* command) {\n amd::ScopedLock lock(lock_);\n\n if (event_ == &command->event()) return;\n\n if (event_ != nullptr) {\n event_->release();\n }\n\n event_ = &command->event();\n}\n\n}\n\nhipError_t ihipEventCreateWithFlags(hipEvent_t* event, unsigned flags) {\n if (event == nullptr) {\n return hipErrorInvalidValue;\n }\n\n unsigned supportedFlags = hipEventDefault | hipEventBlockingSync | hipEventDisableTiming |\n hipEventReleaseToDevice | hipEventReleaseToSystem;\n const unsigned releaseFlags = (hipEventReleaseToDevice | hipEventReleaseToSystem);\n\n const bool illegalFlags =\n (flags & ~supportedFlags) || \/\/ can't set any unsupported flags.\n (flags & releaseFlags) == releaseFlags; \/\/ can't set both release flags\n\n if (!illegalFlags) {\n hip::Event* e = new hip::Event(flags);\n\n if (e == nullptr) {\n return hipErrorOutOfMemory;\n }\n\n *event = reinterpret_cast(e);\n } else {\n return hipErrorInvalidValue;\n }\n return hipSuccess;\n}\n\nhipError_t ihipEventQuery(hipEvent_t event) {\n if (event == nullptr) {\n return hipErrorInvalidHandle;\n }\n\n hip::Event* e = reinterpret_cast(event);\n\n return e->query();\n}\n\nhipError_t hipEventCreateWithFlags(hipEvent_t* event, unsigned flags) {\n HIP_INIT_API(hipEventCreateWithFlags, event, flags);\n\n HIP_RETURN(ihipEventCreateWithFlags(event, flags));\n}\n\nhipError_t hipEventCreate(hipEvent_t* event) {\n HIP_INIT_API(hipEventCreate, event);\n\n HIP_RETURN(ihipEventCreateWithFlags(event, 0));\n}\n\nhipError_t hipEventDestroy(hipEvent_t event) {\n HIP_INIT_API(hipEventDestroy, event);\n\n if (event == nullptr) {\n HIP_RETURN(hipErrorInvalidHandle);\n }\n\n delete reinterpret_cast(event);\n\n HIP_RETURN(hipSuccess);\n}\n\nhipError_t hipEventElapsedTime(float *ms, hipEvent_t start, hipEvent_t stop) {\n HIP_INIT_API(hipEventElapsedTime, ms, start, stop);\n\n if (start == nullptr || stop == nullptr) {\n HIP_RETURN(hipErrorInvalidHandle);\n }\n\n if (ms == nullptr) {\n HIP_RETURN(hipErrorInvalidValue);\n }\n\n hip::Event* eStart = reinterpret_cast(start);\n hip::Event* eStop = reinterpret_cast(stop);\n\n HIP_RETURN(eStart->elapsedTime(*eStop, *ms));\n}\n\nhipError_t hipEventRecord(hipEvent_t event, hipStream_t stream) {\n HIP_INIT_API(hipEventRecord, event, stream);\n\n if (event == nullptr) {\n HIP_RETURN(hipErrorInvalidHandle);\n }\n\n hip::Event* e = reinterpret_cast(event);\n\n hip::Stream* s = reinterpret_cast(stream);\n amd::HostQueue* queue = hip::getQueue(stream);\n\n amd::Command* command = (s != nullptr && (s->flags & hipStreamNonBlocking)) ?\n queue->getLastQueuedCommand(true) : nullptr;\n\n if (command == nullptr) {\n command = new amd::Marker(*queue, false);\n command->enqueue();\n }\n\n e->addMarker(queue, command);\n\n HIP_RETURN(hipSuccess);\n}\n\nhipError_t hipEventSynchronize(hipEvent_t event) {\n HIP_INIT_API(hipEventSynchronize, event);\n\n if (event == nullptr) {\n HIP_RETURN(hipErrorInvalidHandle);\n }\n\n hip::Event* e = reinterpret_cast(event);\n\n HIP_RETURN(e->synchronize());\n}\n\nhipError_t hipEventQuery(hipEvent_t event) {\n HIP_INIT_API(hipEventQuery, event);\n\n HIP_RETURN(ihipEventQuery(event));\n}\n<|endoftext|>"} {"text":"#pragma ident \"$Id$\"\n\n\/\/============================================================================\n\/\/\n\/\/ This file is part of GPSTk, the GPS Toolkit.\n\/\/\n\/\/ The GPSTk is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2.1 of the License, or\n\/\/ any later version.\n\/\/\n\/\/ The GPSTk is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with GPSTk; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/ \n\/\/ Copyright 2004, The University of Texas at Austin\n\/\/\n\/\/============================================================================\n\n\/\/============================================================================\n\/\/\n\/\/This software developed by Applied Research Laboratories at the University of\n\/\/Texas at Austin, under contract to an agency or agencies within the U.S. \n\/\/Department of Defense. The U.S. Government retains all rights to use,\n\/\/duplicate, distribute, disclose, or release this software. \n\/\/\n\/\/Pursuant to DoD Directive 523024 \n\/\/\n\/\/ DISTRIBUTION STATEMENT A: This software has been approved for public \n\/\/ release, distribution is unlimited.\n\/\/\n\/\/=============================================================================\n\n\/** @file Translates between various similiar objects *\/\n\n#include \"StringUtils.hpp\"\n#include \"RinexObsID.hpp\"\n\n#include \"RinexConverters.hpp\"\n\nusing namespace std;\n\nnamespace gpstk\n{\n short snr2ssi(float x)\n {\n \/\/ These values were obtained from the comments in a RINEX obs file that was\n \/\/ generated from a TurboBinary file recorded on an AOA Benchmark receiver\n if (x>316) return 9;\n if (x>100) return 8;\n if (x>31.6) return 7;\n if (x>10) return 6;\n if (x>3.2) return 5;\n if (x>0) return 4;\n return 0;\n }\n\n RinexObsData::RinexObsTypeMap makeRinexObsTypeMap(const MDPObsEpoch& moe) throw()\n {\n gpstk::RinexObsData::RinexObsTypeMap rotm;\n MDPObsEpoch::ObsMap ol=moe.obs;\n MDPObsEpoch::ObsMap::const_iterator j;\n\n \/\/ The C1 Rinex obs is easy\n j = ol.find(MDPObsEpoch::ObsKey(ccL1,rcCA));\n if (j!=ol.end())\n {\n rotm[gpstk::RinexObsHeader::C1].data = j->second.pseudorange;\n rotm[gpstk::RinexObsHeader::C1].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::C1].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::L1].data = j->second.phase;\n rotm[gpstk::RinexObsHeader::L1].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::L1].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::D1].data = j->second.doppler;\n rotm[gpstk::RinexObsHeader::D1].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::D1].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::S1].data = j->second.snr;\n }\n\n \/\/ Now get the P1, L1, D1, S1 obs\n j = ol.find(MDPObsEpoch::ObsKey(ccL1, rcYcode));\n if (j == ol.end())\n j = ol.find(MDPObsEpoch::ObsKey(ccL1, rcPcode));\n if (j == ol.end())\n j = ol.find(MDPObsEpoch::ObsKey(ccL1, rcCodeless));\n if (j != ol.end())\n {\n rotm[gpstk::RinexObsHeader::P1].data = j->second.pseudorange;\n rotm[gpstk::RinexObsHeader::P1].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::P1].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::L1].data = j->second.phase;\n rotm[gpstk::RinexObsHeader::L1].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::L1].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::D1].data = j->second.doppler;\n rotm[gpstk::RinexObsHeader::D1].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::D1].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::S1].data = j->second.snr;\n }\n \n \/\/ Now get the P2, L2, D2, S2 obs\n j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcYcode));\n if (j == ol.end())\n j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcPcode));\n if (j == ol.end())\n j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCodeless));\n if (j != ol.end())\n {\n rotm[gpstk::RinexObsHeader::P2].data = j->second.pseudorange;\n rotm[gpstk::RinexObsHeader::P2].lli = j->second.lockCount ? 0 : 1;\n rotm[gpstk::RinexObsHeader::P2].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::L2].data = j->second.phase;\n rotm[gpstk::RinexObsHeader::L2].lli = j->second.lockCount ? 0 : 1;\n rotm[gpstk::RinexObsHeader::L2].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::D2].data = j->second.doppler;\n rotm[gpstk::RinexObsHeader::D2].lli = j->second.lockCount ? 0 : 1;\n rotm[gpstk::RinexObsHeader::D2].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::S2].data = j->second.snr;\n }\n\n \/\/ Now get the C2\n j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCM));\n if (j == ol.end())\n j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCL));\n if (j == ol.end())\n j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCMCL));\n if (j != ol.end())\n {\n rotm[gpstk::RinexObsHeader::C2].data = j->second.pseudorange;\n rotm[gpstk::RinexObsHeader::C2].lli = j->second.lockCount ? 0 : 1;\n rotm[gpstk::RinexObsHeader::C2].ssi = snr2ssi(j->second.snr);\n }\n return rotm;\n }\n\n RinexObsData makeRinexObsData(const gpstk::MDPEpoch& mdp)\n {\n RinexObsData rod;\n\n rod.clockOffset=0;\n rod.numSvs = mdp.size();\n rod.epochFlag = 0;\n rod.time = mdp.begin()->second.time;\n\n for (MDPEpoch::const_iterator i=mdp.begin(); i!=mdp.end(); i++)\n {\n const MDPObsEpoch& moe = i->second;\n gpstk::SatID svid(moe.prn, gpstk::SatID::systemGPS);\n rod.obs[svid] = makeRinexObsTypeMap(moe);\n }\n return rod;\n }\n\n \/\/ Try to convert the given pages into an EngAlmanc object. Returns true\n \/\/ upon success. This routine is tuned for two different types of nav data.\n \/\/\n \/\/ The first is for a receiver that outputs all 4\/5 subframes from a given\n \/\/ code\/carrier. Basically it looks for a 12.5 minute cycle that starts\n \/\/ with page 1 from subframe 4. It makes sure that there hasn't been a\n \/\/ cutover during it by checking that all sv pages (i.e. svid 1-32) have\n \/\/ the same toa as the last page 25 (svid 51). This mode is the default and\n \/\/ is set with the requireFull parameter.\n \/\/\n \/\/ The second is for a receiver that only puts out a set of 4\/5 subframes\n \/\/ that \"should\" be a complete almanac. Note that it doesn't output pages\n \/\/ for SVs that are set to the default data.\n \/\/\n \/\/ The only receiver that this has been tested on is the Ashtech Z(Y)12.\n \/\/ \n \/\/ In the IS-GPS-200D, see pages 72-79, 82, 105\n bool makeEngAlmanac(EngAlmanac& alm,\n const AlmanacPages& pages,\n bool requireFull) throw()\n {\n AlmanacPages::const_iterator sf4p1 = pages.find(SubframePage(4, 1));\n AlmanacPages::const_iterator sf4p18 = pages.find(SubframePage(4, 18));\n AlmanacPages::const_iterator sf4p25 = pages.find(SubframePage(4, 25));\n AlmanacPages::const_iterator sf5p25 = pages.find(SubframePage(5, 25));\n\n \/\/ These pages are required for a reasonable alm\n if (sf4p18==pages.end() || sf4p25==pages.end() || sf5p25==pages.end())\n return false;\n\n long sf4p1sow=0;\n if (requireFull)\n {\n if (sf4p1==pages.end())\n return false;\n else\n sf4p1sow = sf4p1->second.getHOWTime();\n }\n\n int week=sf4p18->second.time.GPSfullweek();\n \n for (int p=1; p<=25; p++)\n {\n for (int sf=4; sf<=5; sf++)\n {\n AlmanacPages::const_iterator i = pages.find(SubframePage(sf, p));\n if (i == pages.end())\n {\n if (requireFull)\n return false;\n else\n continue;\n }\n\n \/\/ All pages have to be contingious for the full alm mode.\n if (requireFull)\n {\n long sow = i->second.getHOWTime(); \n if (sow != sf4p1sow + (sf-4)*6 + (p-1)*30)\n return false;\n }\n\n long sfa[10];\n long long_sfa[10];\n i->second.fillArray(sfa);\n copy( &sfa[0], &sfa[10], long_sfa);\n if (!alm.addSubframe(long_sfa, week))\n return false;\n }\n }\n return true;\n }\n\n \/\/ Try to convert the given pages into an EngEphemeris object. Returns true\n \/\/ upon success.\n bool makeEngEphemeris(EngEphemeris& eph, const EphemerisPages& pages)\n {\n EphemerisPages::const_iterator sf[4];\n\n sf[1] = pages.find(1);\n if (sf[1] == pages.end())\n return false;\n \n sf[2] = pages.find(2);\n if (sf[2] == pages.end())\n return false;\n\n sf[3] = pages.find(3);\n if (sf[3] == pages.end())\n return false;\n\n long t1 = sf[1]->second.getHOWTime();\n long t2 = sf[2]->second.getHOWTime();\n long t3 = sf[3]->second.getHOWTime();\n if (t2 != t1+6 || t3 != t1+12)\n return false;\n\n int prn = sf[1]->second.prn;\n int week = sf[1]->second.time.GPSfullweek();\n long sfa[10];\n long long_sfa[10];\n\n for (int i=1; i<=3; i++)\n {\n sf[i]->second.fillArray(sfa);\n for( int j = 0; j < 10; j++ )\n long_sfa[j] = static_cast( sfa[j] );\n if (!eph.addSubframe(long_sfa, week, prn, 0))\n return false;\n }\n\n if (eph.isData(1) && eph.isData(2) && eph.isData(3))\n return true;\n\n return false;\n }\n} \/\/ end of namespace gpstk\nA conditional expression was being used backwards in makeRinexObsTypeMap, causing the LLI to be set incorrectly for L2 observables. #pragma ident \"$Id$\"\n\n\/\/============================================================================\n\/\/\n\/\/ This file is part of GPSTk, the GPS Toolkit.\n\/\/\n\/\/ The GPSTk is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2.1 of the License, or\n\/\/ any later version.\n\/\/\n\/\/ The GPSTk is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with GPSTk; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/ \n\/\/ Copyright 2004, The University of Texas at Austin\n\/\/\n\/\/============================================================================\n\n\/\/============================================================================\n\/\/\n\/\/This software developed by Applied Research Laboratories at the University of\n\/\/Texas at Austin, under contract to an agency or agencies within the U.S. \n\/\/Department of Defense. The U.S. Government retains all rights to use,\n\/\/duplicate, distribute, disclose, or release this software. \n\/\/\n\/\/Pursuant to DoD Directive 523024 \n\/\/\n\/\/ DISTRIBUTION STATEMENT A: This software has been approved for public \n\/\/ release, distribution is unlimited.\n\/\/\n\/\/=============================================================================\n\n\/** @file Translates between various similiar objects *\/\n\n#include \"StringUtils.hpp\"\n#include \"RinexObsID.hpp\"\n\n#include \"RinexConverters.hpp\"\n\nusing namespace std;\n\nnamespace gpstk\n{\n short snr2ssi(float x)\n {\n \/\/ These values were obtained from the comments in a RINEX obs file that was\n \/\/ generated from a TurboBinary file recorded on an AOA Benchmark receiver\n if (x>316) return 9;\n if (x>100) return 8;\n if (x>31.6) return 7;\n if (x>10) return 6;\n if (x>3.2) return 5;\n if (x>0) return 4;\n return 0;\n }\n\n RinexObsData::RinexObsTypeMap makeRinexObsTypeMap(const MDPObsEpoch& moe) throw()\n {\n gpstk::RinexObsData::RinexObsTypeMap rotm;\n MDPObsEpoch::ObsMap ol=moe.obs;\n MDPObsEpoch::ObsMap::const_iterator j;\n\n \/\/ The C1 Rinex obs is easy\n j = ol.find(MDPObsEpoch::ObsKey(ccL1,rcCA));\n if (j!=ol.end())\n {\n rotm[gpstk::RinexObsHeader::C1].data = j->second.pseudorange;\n rotm[gpstk::RinexObsHeader::C1].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::C1].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::L1].data = j->second.phase;\n rotm[gpstk::RinexObsHeader::L1].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::L1].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::D1].data = j->second.doppler;\n rotm[gpstk::RinexObsHeader::D1].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::D1].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::S1].data = j->second.snr;\n }\n\n \/\/ Now get the P1, L1, D1, S1 obs\n j = ol.find(MDPObsEpoch::ObsKey(ccL1, rcYcode));\n if (j == ol.end())\n j = ol.find(MDPObsEpoch::ObsKey(ccL1, rcPcode));\n if (j == ol.end())\n j = ol.find(MDPObsEpoch::ObsKey(ccL1, rcCodeless));\n if (j != ol.end())\n {\n rotm[gpstk::RinexObsHeader::P1].data = j->second.pseudorange;\n rotm[gpstk::RinexObsHeader::P1].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::P1].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::L1].data = j->second.phase;\n rotm[gpstk::RinexObsHeader::L1].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::L1].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::D1].data = j->second.doppler;\n rotm[gpstk::RinexObsHeader::D1].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::D1].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::S1].data = j->second.snr;\n }\n \n \/\/ Now get the P2, L2, D2, S2 obs\n j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcYcode));\n if (j == ol.end())\n j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcPcode));\n if (j == ol.end())\n j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCodeless));\n if (j != ol.end())\n {\n rotm[gpstk::RinexObsHeader::P2].data = j->second.pseudorange;\n rotm[gpstk::RinexObsHeader::P2].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::P2].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::L2].data = j->second.phase;\n rotm[gpstk::RinexObsHeader::L2].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::L2].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::D2].data = j->second.doppler;\n rotm[gpstk::RinexObsHeader::D2].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::D2].ssi = snr2ssi(j->second.snr);\n\n rotm[gpstk::RinexObsHeader::S2].data = j->second.snr;\n }\n\n \/\/ Now get the C2\n j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCM));\n if (j == ol.end())\n j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCL));\n if (j == ol.end())\n j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCMCL));\n if (j != ol.end())\n {\n rotm[gpstk::RinexObsHeader::C2].data = j->second.pseudorange;\n rotm[gpstk::RinexObsHeader::C2].lli = j->second.lockCount ? 1 : 0;\n rotm[gpstk::RinexObsHeader::C2].ssi = snr2ssi(j->second.snr);\n }\n return rotm;\n }\n\n RinexObsData makeRinexObsData(const gpstk::MDPEpoch& mdp)\n {\n RinexObsData rod;\n\n rod.clockOffset=0;\n rod.numSvs = mdp.size();\n rod.epochFlag = 0;\n rod.time = mdp.begin()->second.time;\n\n for (MDPEpoch::const_iterator i=mdp.begin(); i!=mdp.end(); i++)\n {\n const MDPObsEpoch& moe = i->second;\n gpstk::SatID svid(moe.prn, gpstk::SatID::systemGPS);\n rod.obs[svid] = makeRinexObsTypeMap(moe);\n }\n return rod;\n }\n\n \/\/ Try to convert the given pages into an EngAlmanc object. Returns true\n \/\/ upon success. This routine is tuned for two different types of nav data.\n \/\/\n \/\/ The first is for a receiver that outputs all 4\/5 subframes from a given\n \/\/ code\/carrier. Basically it looks for a 12.5 minute cycle that starts\n \/\/ with page 1 from subframe 4. It makes sure that there hasn't been a\n \/\/ cutover during it by checking that all sv pages (i.e. svid 1-32) have\n \/\/ the same toa as the last page 25 (svid 51). This mode is the default and\n \/\/ is set with the requireFull parameter.\n \/\/\n \/\/ The second is for a receiver that only puts out a set of 4\/5 subframes\n \/\/ that \"should\" be a complete almanac. Note that it doesn't output pages\n \/\/ for SVs that are set to the default data.\n \/\/\n \/\/ The only receiver that this has been tested on is the Ashtech Z(Y)12.\n \/\/ \n \/\/ In the IS-GPS-200D, see pages 72-79, 82, 105\n bool makeEngAlmanac(EngAlmanac& alm,\n const AlmanacPages& pages,\n bool requireFull) throw()\n {\n AlmanacPages::const_iterator sf4p1 = pages.find(SubframePage(4, 1));\n AlmanacPages::const_iterator sf4p18 = pages.find(SubframePage(4, 18));\n AlmanacPages::const_iterator sf4p25 = pages.find(SubframePage(4, 25));\n AlmanacPages::const_iterator sf5p25 = pages.find(SubframePage(5, 25));\n\n \/\/ These pages are required for a reasonable alm\n if (sf4p18==pages.end() || sf4p25==pages.end() || sf5p25==pages.end())\n return false;\n\n long sf4p1sow=0;\n if (requireFull)\n {\n if (sf4p1==pages.end())\n return false;\n else\n sf4p1sow = sf4p1->second.getHOWTime();\n }\n\n int week=sf4p18->second.time.GPSfullweek();\n \n for (int p=1; p<=25; p++)\n {\n for (int sf=4; sf<=5; sf++)\n {\n AlmanacPages::const_iterator i = pages.find(SubframePage(sf, p));\n if (i == pages.end())\n {\n if (requireFull)\n return false;\n else\n continue;\n }\n\n \/\/ All pages have to be contingious for the full alm mode.\n if (requireFull)\n {\n long sow = i->second.getHOWTime(); \n if (sow != sf4p1sow + (sf-4)*6 + (p-1)*30)\n return false;\n }\n\n long sfa[10];\n long long_sfa[10];\n i->second.fillArray(sfa);\n copy( &sfa[0], &sfa[10], long_sfa);\n if (!alm.addSubframe(long_sfa, week))\n return false;\n }\n }\n return true;\n }\n\n \/\/ Try to convert the given pages into an EngEphemeris object. Returns true\n \/\/ upon success.\n bool makeEngEphemeris(EngEphemeris& eph, const EphemerisPages& pages)\n {\n EphemerisPages::const_iterator sf[4];\n\n sf[1] = pages.find(1);\n if (sf[1] == pages.end())\n return false;\n \n sf[2] = pages.find(2);\n if (sf[2] == pages.end())\n return false;\n\n sf[3] = pages.find(3);\n if (sf[3] == pages.end())\n return false;\n\n long t1 = sf[1]->second.getHOWTime();\n long t2 = sf[2]->second.getHOWTime();\n long t3 = sf[3]->second.getHOWTime();\n if (t2 != t1+6 || t3 != t1+12)\n return false;\n\n int prn = sf[1]->second.prn;\n int week = sf[1]->second.time.GPSfullweek();\n long sfa[10];\n long long_sfa[10];\n\n for (int i=1; i<=3; i++)\n {\n sf[i]->second.fillArray(sfa);\n for( int j = 0; j < 10; j++ )\n long_sfa[j] = static_cast( sfa[j] );\n if (!eph.addSubframe(long_sfa, week, prn, 0))\n return false;\n }\n\n if (eph.isData(1) && eph.isData(2) && eph.isData(3))\n return true;\n\n return false;\n }\n} \/\/ end of namespace gpstk\n<|endoftext|>"} {"text":"Cleaned up handling of GUI toggles.<|endoftext|>"} {"text":"#include \"Cache.h\"\n\n#include \"preprocessor\/llvm_includes_start.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"preprocessor\/llvm_includes_end.h\"\n\n#include \"ExecutionEngine.h\"\n#include \"Utils.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nnamespace\n{\n\tllvm::MemoryBuffer* g_lastObject;\n\tExecutionEngineListener* g_listener;\n}\n\nObjectCache* Cache::getObjectCache(ExecutionEngineListener* _listener)\n{\n\tstatic ObjectCache objectCache;\n\tg_listener = _listener;\n\treturn &objectCache;\n}\n\nstd::unique_ptr Cache::getObject(std::string const& id)\n{\n\tif (g_listener)\n\t\tg_listener->stateChanged(ExecState::CacheLoad);\n\n\tDLOG(cache) << id << \": search\\n\";\n\tif (!CHECK(!g_lastObject))\n\t\tg_lastObject = nullptr;\n\n\tllvm::SmallString<256> cachePath;\n\tllvm::sys::path::system_temp_directory(false, cachePath);\n\tllvm::sys::path::append(cachePath, \"evm_objs\", id);\n\n#if defined(__GNUC__) && !defined(NDEBUG)\n\tllvm::sys::fs::file_status st;\n\tauto err = llvm::sys::fs::status(cachePath.str(), st);\n\tif (err)\n\t\treturn nullptr;\n\tauto mtime = st.getLastModificationTime().toEpochTime();\n\n\tstd::tm tm;\n\tstrptime(__DATE__ __TIME__, \" %b %d %Y %H:%M:%S\", &tm);\n\tauto btime = (uint64_t)std::mktime(&tm);\n\tif (btime > mtime)\n\t\treturn nullptr;\n#endif\n\n\tif (auto r = llvm::MemoryBuffer::getFile(cachePath.str(), -1, false))\n\t\tg_lastObject = llvm::MemoryBuffer::getMemBufferCopy(r.get()->getBuffer());\n\telse if (r.getError() != std::make_error_code(std::errc::no_such_file_or_directory))\n\t\tstd::cerr << r.getError().message(); \/\/ TODO: Add log\n\n\tif (g_lastObject) \/\/ if object found create fake module\n\t{\n\t\tDLOG(cache) << id << \": found\\n\";\n\t\tauto&& context = llvm::getGlobalContext();\n\t\tauto module = std::unique_ptr(new llvm::Module(id, context));\n\t\tauto mainFuncType = llvm::FunctionType::get(llvm::Type::getVoidTy(context), {}, false);\n\t\tauto mainFunc = llvm::Function::Create(mainFuncType, llvm::Function::ExternalLinkage, id, module.get());\n\t\tauto bb = llvm::BasicBlock::Create(context, {}, mainFunc);\n\t\tbb->getInstList().push_back(new llvm::UnreachableInst{context});\n\t\treturn module;\n\t}\n\tDLOG(cache) << id << \": not found\\n\";\n\treturn nullptr;\n}\n\n\nvoid ObjectCache::notifyObjectCompiled(llvm::Module const* _module, llvm::MemoryBuffer const* _object)\n{\n\tif (g_listener)\n\t\tg_listener->stateChanged(ExecState::CacheWrite);\n\n\tauto&& id = _module->getModuleIdentifier();\n\tllvm::SmallString<256> cachePath;\n\tllvm::sys::path::system_temp_directory(false, cachePath);\n\tllvm::sys::path::append(cachePath, \"evm_objs\");\n\n\tif (llvm::sys::fs::create_directory(cachePath.str()))\n\t\treturn; \/\/ TODO: Add log\n\n\tllvm::sys::path::append(cachePath, id);\n\n\tDLOG(cache) << id << \": write\\n\";\n\tstd::string error;\n\tllvm::raw_fd_ostream cacheFile(cachePath.c_str(), error, llvm::sys::fs::F_None);\n\tcacheFile << _object->getBuffer();\n}\n\nllvm::MemoryBuffer* ObjectCache::getObject(llvm::Module const* _module)\n{\n\tDLOG(cache) << _module->getModuleIdentifier() << \": use\\n\";\n\tauto o = g_lastObject;\n\tg_lastObject = nullptr;\n\treturn o;\n}\n\n}\n}\n}\nAdd library version stamp to cached objects#include \"Cache.h\"\n\n#include \"preprocessor\/llvm_includes_start.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"preprocessor\/llvm_includes_end.h\"\n\n#include \"ExecutionEngine.h\"\n#include \"Utils.h\"\n#include \"BuildInfo.gen.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nnamespace\n{\n\tllvm::MemoryBuffer* g_lastObject;\n\tExecutionEngineListener* g_listener;\n\tstatic const size_t c_versionStampLength = 32;\n\n\tllvm::StringRef getLibVersionStamp()\n\t{\n\t\tstatic auto version = llvm::SmallString{};\n\t\tif (version.empty())\n\t\t{\n\t\t\tversion = EVMJIT_VERSION_FULL;\n\t\t\tversion.resize(c_versionStampLength);\n\t\t}\n\t\treturn version;\n\t}\n}\n\nObjectCache* Cache::getObjectCache(ExecutionEngineListener* _listener)\n{\n\tstatic ObjectCache objectCache;\n\tg_listener = _listener;\n\treturn &objectCache;\n}\n\nstd::unique_ptr Cache::getObject(std::string const& id)\n{\n\tif (g_listener)\n\t\tg_listener->stateChanged(ExecState::CacheLoad);\n\n\tDLOG(cache) << id << \": search\\n\";\n\tif (!CHECK(!g_lastObject))\n\t\tg_lastObject = nullptr;\n\n\tllvm::SmallString<256> cachePath;\n\tllvm::sys::path::system_temp_directory(false, cachePath);\n\tllvm::sys::path::append(cachePath, \"evm_objs\", id);\n\n\tif (auto r = llvm::MemoryBuffer::getFile(cachePath.str(), -1, false))\n\t{\n\t\tauto& buf = r.get();\n\t\tauto objVersionStamp = buf->getBufferSize() >= c_versionStampLength ? llvm::StringRef{buf->getBufferEnd() - c_versionStampLength, c_versionStampLength} : llvm::StringRef{};\n\t\tif (objVersionStamp == getLibVersionStamp())\n\t\t\tg_lastObject = llvm::MemoryBuffer::getMemBufferCopy(r.get()->getBuffer());\n\t\telse\n\t\t\tDLOG(cache) << \"Unmatched version: \" << objVersionStamp.str() << \", expected \" << getLibVersionStamp().str() << \"\\n\";\n\t}\n\telse if (r.getError() != std::make_error_code(std::errc::no_such_file_or_directory))\n\t{\n\t\tDLOG(cache) << r.getError().message(); \/\/ TODO: Add warning log\n\t}\n\n\tif (g_lastObject) \/\/ if object found create fake module\n\t{\n\t\tDLOG(cache) << id << \": found\\n\";\n\t\tauto&& context = llvm::getGlobalContext();\n\t\tauto module = std::unique_ptr(new llvm::Module(id, context));\n\t\tauto mainFuncType = llvm::FunctionType::get(llvm::Type::getVoidTy(context), {}, false);\n\t\tauto mainFunc = llvm::Function::Create(mainFuncType, llvm::Function::ExternalLinkage, id, module.get());\n\t\tauto bb = llvm::BasicBlock::Create(context, {}, mainFunc);\n\t\tbb->getInstList().push_back(new llvm::UnreachableInst{context});\n\t\treturn module;\n\t}\n\tDLOG(cache) << id << \": not found\\n\";\n\treturn nullptr;\n}\n\n\nvoid ObjectCache::notifyObjectCompiled(llvm::Module const* _module, llvm::MemoryBuffer const* _object)\n{\n\tif (g_listener)\n\t\tg_listener->stateChanged(ExecState::CacheWrite);\n\n\tauto&& id = _module->getModuleIdentifier();\n\tllvm::SmallString<256> cachePath;\n\tllvm::sys::path::system_temp_directory(false, cachePath);\n\tllvm::sys::path::append(cachePath, \"evm_objs\");\n\n\tif (llvm::sys::fs::create_directory(cachePath.str()))\n\t\tDLOG(cache) << \"Cannot create cache dir \" << cachePath.str().str() << \"\\n\";\n\n\tllvm::sys::path::append(cachePath, id);\n\n\tDLOG(cache) << id << \": write\\n\";\n\tstd::string error;\n\tllvm::raw_fd_ostream cacheFile(cachePath.c_str(), error, llvm::sys::fs::F_None);\n\tcacheFile << _object->getBuffer() << getLibVersionStamp();\n}\n\nllvm::MemoryBuffer* ObjectCache::getObject(llvm::Module const* _module)\n{\n\tDLOG(cache) << _module->getModuleIdentifier() << \": use\\n\";\n\tauto o = g_lastObject;\n\tg_lastObject = nullptr;\n\treturn o;\n}\n\n}\n}\n}\n<|endoftext|>"} {"text":"#include \"matcher.h\"\n\n#include \"3rd-party\/catch.hpp\"\n\n#include \"matchable.h\"\n#include \"matcherexception.h\"\n\nusing namespace newsboat;\n\nstruct testMatchable : public Matchable {\n\tvirtual bool has_attribute(const std::string& attribname)\n\t{\n\t\tif (attribname == \"abcd\" || attribname == \"AAAA\" ||\n\t\t\tattribname == \"tags\")\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\tvirtual std::string get_attribute(const std::string& attribname)\n\t{\n\t\tif (attribname == \"abcd\")\n\t\t\treturn \"xyz\";\n\t\tif (attribname == \"AAAA\")\n\t\t\treturn \"12345\";\n\t\tif (attribname == \"tags\")\n\t\t\treturn \"foo bar baz quux\";\n\t\treturn \"\";\n\t}\n};\n\nTEST_CASE(\"Operator `=` checks if field has given value\", \"[Matcher]\")\n{\n\ttestMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"abcd = \\\"xyz\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"abcd = \\\"uiop\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n}\n\nTEST_CASE(\"Operator `!=` checks if field doesn't have given value\", \"[Matcher]\")\n{\n\ttestMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"abcd != \\\"uiop\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"abcd != \\\"xyz\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n}\n\nTEST_CASE(\"Operator `=~` checks if field matches given regex\", \"[Matcher]\")\n{\n\ttestMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"AAAA =~ \\\".\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA =~ \\\"123\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA =~ \\\"234\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA =~ \\\"45\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA =~ \\\"^12345$\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA =~ \\\"^123456$\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n}\n\nTEST_CASE(\"Matcher throws if expression contains undefined fields\", \"[Matcher]\")\n{\n\ttestMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"BBBB =~ \\\"foo\\\"\");\n\tREQUIRE_THROWS_AS(m.matches(&mock), MatcherException);\n\n\tm.parse(\"BBBB # \\\"foo\\\"\");\n\tREQUIRE_THROWS_AS(m.matches(&mock), MatcherException);\n\n\tm.parse(\"BBBB < 0\");\n\tREQUIRE_THROWS_AS(m.matches(&mock), MatcherException);\n\n\tm.parse(\"BBBB > 0\");\n\tREQUIRE_THROWS_AS(m.matches(&mock), MatcherException);\n\n\tm.parse(\"BBBB between 1:23\");\n\tREQUIRE_THROWS_AS(m.matches(&mock), MatcherException);\n}\n\nTEST_CASE(\"Matcher throws if regex passed to `=~` or `!~` is invalid\",\n\t\"[Matcher]\")\n{\n\ttestMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"AAAA =~ \\\"[[\\\"\");\n\tREQUIRE_THROWS_AS(m.matches(&mock), MatcherException);\n\n\tm.parse(\"AAAA !~ \\\"[[\\\"\");\n\tREQUIRE_THROWS_AS(m.matches(&mock), MatcherException);\n}\n\nTEST_CASE(\"Operator `!~` checks if field doesn't match given regex\",\n\t\"[Matcher]\")\n{\n\ttestMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"AAAA !~ \\\".\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA !~ \\\"123\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA !~ \\\"234\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA !~ \\\"45\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA !~ \\\"^12345$\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n}\n\nTEST_CASE(\"Operator `#` checks if \\\"tags\\\" field contains given value\",\n\t\"[Matcher]\")\n{\n\ttestMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"tags # \\\"foo\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"tags # \\\"baz\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"tags # \\\"quux\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"tags # \\\"xyz\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"tags # \\\"foo bar\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"tags # \\\"foo\\\" and tags # \\\"bar\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"tags # \\\"foo\\\" and tags # \\\"xyz\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"tags # \\\"foo\\\" or tags # \\\"xyz\\\"\");\n\tREQUIRE(m.matches(&mock));\n}\n\nTEST_CASE(\"Operator `!#` checks if \\\"tags\\\" field doesn't contain given value\",\n\t\"[Matcher]\")\n{\n\ttestMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"tags !# \\\"nein\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"tags !# \\\"foo\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n}\n\nTEST_CASE(\n\t\"Operators `>`, `>=`, `<` and `<=` comparee field's value to given \"\n\t\"value\",\n\t\"[Matcher]\")\n{\n\ttestMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"AAAA > 12344\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA > 12345\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA >= 12345\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA < 12345\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA <= 12345\");\n\tREQUIRE(m.matches(&mock));\n}\n\nTEST_CASE(\"Operator `between` checks if field's value is in given range\",\n\t\"[Matcher]\")\n{\n\ttestMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"AAAA between 0:12345\");\n\tREQUIRE(m.get_parse_error() == \"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA between 12345:12345\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA between 23:12344\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA between 0\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA between 12346:12344\");\n\tREQUIRE(m.matches(&mock));\n}\n\nTEST_CASE(\"Invalid expression results in parsing error\", \"[Matcher]\")\n{\n\tMatcher m;\n\n\tREQUIRE_FALSE(m.parse(\"AAAA between 0:15:30\"));\n\tREQUIRE(m.get_parse_error() != \"\");\n}\n\nTEST_CASE(\"get_expression() returns previously parsed expression\", \"[Matcher]\")\n{\n\tMatcher m2(\"AAAA between 1:30000\");\n\tREQUIRE(m2.get_expression() == \"AAAA between 1:30000\");\n}\nGive mock Matchable in Matcher tests a unique name#include \"matcher.h\"\n\n#include \"3rd-party\/catch.hpp\"\n\n#include \"matchable.h\"\n#include \"matcherexception.h\"\n\nusing namespace newsboat;\n\nstruct MatcherMockMatchable : public Matchable {\n\tvirtual bool has_attribute(const std::string& attribname)\n\t{\n\t\tif (attribname == \"abcd\" || attribname == \"AAAA\" ||\n\t\t\tattribname == \"tags\") {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tvirtual std::string get_attribute(const std::string& attribname)\n\t{\n\t\tif (attribname == \"abcd\") {\n\t\t\treturn \"xyz\";\n\t\t} else if (attribname == \"AAAA\") {\n\t\t\treturn \"12345\";\n\t\t} else if (attribname == \"tags\") {\n\t\t\treturn \"foo bar baz quux\";\n\t\t}\n\t\treturn \"\";\n\t}\n};\n\nTEST_CASE(\"Operator `=` checks if field has given value\", \"[Matcher]\")\n{\n\tMatcherMockMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"abcd = \\\"xyz\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"abcd = \\\"uiop\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n}\n\nTEST_CASE(\"Operator `!=` checks if field doesn't have given value\", \"[Matcher]\")\n{\n\tMatcherMockMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"abcd != \\\"uiop\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"abcd != \\\"xyz\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n}\n\nTEST_CASE(\"Operator `=~` checks if field matches given regex\", \"[Matcher]\")\n{\n\tMatcherMockMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"AAAA =~ \\\".\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA =~ \\\"123\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA =~ \\\"234\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA =~ \\\"45\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA =~ \\\"^12345$\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA =~ \\\"^123456$\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n}\n\nTEST_CASE(\"Matcher throws if expression contains undefined fields\", \"[Matcher]\")\n{\n\tMatcherMockMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"BBBB =~ \\\"foo\\\"\");\n\tREQUIRE_THROWS_AS(m.matches(&mock), MatcherException);\n\n\tm.parse(\"BBBB # \\\"foo\\\"\");\n\tREQUIRE_THROWS_AS(m.matches(&mock), MatcherException);\n\n\tm.parse(\"BBBB < 0\");\n\tREQUIRE_THROWS_AS(m.matches(&mock), MatcherException);\n\n\tm.parse(\"BBBB > 0\");\n\tREQUIRE_THROWS_AS(m.matches(&mock), MatcherException);\n\n\tm.parse(\"BBBB between 1:23\");\n\tREQUIRE_THROWS_AS(m.matches(&mock), MatcherException);\n}\n\nTEST_CASE(\"Matcher throws if regex passed to `=~` or `!~` is invalid\",\n\t\"[Matcher]\")\n{\n\tMatcherMockMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"AAAA =~ \\\"[[\\\"\");\n\tREQUIRE_THROWS_AS(m.matches(&mock), MatcherException);\n\n\tm.parse(\"AAAA !~ \\\"[[\\\"\");\n\tREQUIRE_THROWS_AS(m.matches(&mock), MatcherException);\n}\n\nTEST_CASE(\"Operator `!~` checks if field doesn't match given regex\",\n\t\"[Matcher]\")\n{\n\tMatcherMockMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"AAAA !~ \\\".\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA !~ \\\"123\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA !~ \\\"234\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA !~ \\\"45\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA !~ \\\"^12345$\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n}\n\nTEST_CASE(\"Operator `#` checks if \\\"tags\\\" field contains given value\",\n\t\"[Matcher]\")\n{\n\tMatcherMockMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"tags # \\\"foo\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"tags # \\\"baz\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"tags # \\\"quux\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"tags # \\\"xyz\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"tags # \\\"foo bar\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"tags # \\\"foo\\\" and tags # \\\"bar\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"tags # \\\"foo\\\" and tags # \\\"xyz\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"tags # \\\"foo\\\" or tags # \\\"xyz\\\"\");\n\tREQUIRE(m.matches(&mock));\n}\n\nTEST_CASE(\"Operator `!#` checks if \\\"tags\\\" field doesn't contain given value\",\n\t\"[Matcher]\")\n{\n\tMatcherMockMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"tags !# \\\"nein\\\"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"tags !# \\\"foo\\\"\");\n\tREQUIRE_FALSE(m.matches(&mock));\n}\n\nTEST_CASE(\n\t\"Operators `>`, `>=`, `<` and `<=` comparee field's value to given \"\n\t\"value\",\n\t\"[Matcher]\")\n{\n\tMatcherMockMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"AAAA > 12344\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA > 12345\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA >= 12345\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA < 12345\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA <= 12345\");\n\tREQUIRE(m.matches(&mock));\n}\n\nTEST_CASE(\"Operator `between` checks if field's value is in given range\",\n\t\"[Matcher]\")\n{\n\tMatcherMockMatchable mock;\n\tMatcher m;\n\n\tm.parse(\"AAAA between 0:12345\");\n\tREQUIRE(m.get_parse_error() == \"\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA between 12345:12345\");\n\tREQUIRE(m.matches(&mock));\n\n\tm.parse(\"AAAA between 23:12344\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA between 0\");\n\tREQUIRE_FALSE(m.matches(&mock));\n\n\tm.parse(\"AAAA between 12346:12344\");\n\tREQUIRE(m.matches(&mock));\n}\n\nTEST_CASE(\"Invalid expression results in parsing error\", \"[Matcher]\")\n{\n\tMatcher m;\n\n\tREQUIRE_FALSE(m.parse(\"AAAA between 0:15:30\"));\n\tREQUIRE(m.get_parse_error() != \"\");\n}\n\nTEST_CASE(\"get_expression() returns previously parsed expression\", \"[Matcher]\")\n{\n\tMatcher m2(\"AAAA between 1:30000\");\n\tREQUIRE(m2.get_expression() == \"AAAA between 1:30000\");\n}\n<|endoftext|>"} {"text":"#ifndef __TEST_REQUIRE_HPP__\n#define __TEST_REQUIRE_HPP__\n\nnamespace test\n{\n\n\/\/ bool, long, double, string, void*\n\nclass Comparison\n{\npublic:\n Comparison( const char* expression );\n\nprotected:\n const char* m_Comparison;\n};\n\nclass BoolComparison : public Comparison\n{\npublic:\n BoolComparison( const char* expression, bool value );\n BoolComparison& is( bool value );\n BoolComparison& equals( bool value );\n\nprivate:\n bool m_Value;\n};\n\n\n#define RequireThat( E ) RequireThat_(#E, E)\nBoolComparison RequireThat_( const char* expression, bool value );\n\n\n\/\/ ---- bool implementation ----\n\nBoolComparison::BoolComparison( const char* expression, bool value ) :\n Comparison(expression),\n m_Value(value)\n{\n}\n\nBoolComparison& BoolComparison::is( bool value )\n{\n return equals(value);\n}\n\nBoolComparison& BoolComparison::equals( bool value )\n{\n const char* expected = (value == true) ? \"true\" : \"false\";\n const char* got = (m_Value == true) ? \"true\" : \"false\";\n\n if(m_Value != value)\n testFail(\"Expected %s to be %s, but it was %s.\",\n m_Comparison,\n expected,\n got);\n return *this;\n}\n\nBoolComparison RequireThat_( const char* expression, bool value )\n{\n return BoolComparison(expression, value);\n}\n\n\n\/\/ ---- int implementation ----\n\nIntComparison::IntComparison( const char* expression, long value ) :\n Comparison(expression),\n m_Value(value)\n{\n}\n\nBoolComparison& BoolComparison::isTrue()\n{\n return equals(true);\n}\n\nBoolComparison& BoolComparison::isFalse()\n{\n return equals(false);\n}\n\nBoolComparison& BoolComparison::equals( bool value )\n{\n const char* expected = (value == true) ? \"true\" : \"false\";\n const char* got = (m_Value == true) ? \"true\" : \"false\";\n\n if(m_Value != value)\n testFail(\"Expected %s to be %s, but it was %s.\",\n m_Comparison,\n expected,\n got);\n return *this;\n}\n\nBoolComparison RequireThat_( const char* expression, bool value )\n{\n return BoolComparison(expression, value);\n}\n\n\n}\n\n#endif\nExtended require.hpp#ifndef __TEST_REQUIRE_HPP__\n#define __TEST_REQUIRE_HPP__\n\nnamespace test\n{\n\n\/\/ bool, long, double, string, void*\n\n\nclass Requirement\n{\npublic:\n Requirement( const char* expression );\n\nprotected:\n const char* m_Expression;\n};\n\n\nclass BoolRequirement : public Requirement\n{\npublic:\n BoolRequirement( const char* expression, bool value );\n BoolRequirement& is( bool value );\n BoolRequirement& isNot( bool value );\n BoolRequirement& equals( bool value );\n\nprivate:\n bool m_Value;\n};\n\nclass IntRequirement : public Requirement\n{\npublic:\n IntRequirement( const char* expression, long value );\n IntRequirement& is( long value );\n IntRequirement& isNot( long value );\n IntRequirement& equals( long value );\n IntRequirement& isGreaterThan( long value );\n IntRequirement& isGreaterOrEqualTo( long value );\n IntRequirement& isSmallerThan( long value );\n IntRequirement& isSmallerOrEqualTo( long value );\n\nprivate:\n long m_Value;\n};\n\nclass FloatRequirement : public Requirement\n{\npublic:\n FloatRequirement( const char* expression, double value );\n FloatRequirement& withEpsilon( double epsilon );\n FloatRequirement& is( double value );\n FloatRequirement& isNot( double value );\n FloatRequirement& equals( double value );\n FloatRequirement& isGreaterThan( double value );\n FloatRequirement& isGreaterOrEqualTo( double value );\n FloatRequirement& isSmallerThan( double value );\n FloatRequirement& isSmallerOrEqualTo( double value );\n\nprivate:\n double m_Value;\n double m_Epsilon;\n};\n\nclass StringRequirement : public Requirement\n{\npublic:\n StringRequirement( const char* expression, const char* value );\n StringRequirement& is( const char* value );\n StringRequirement& isNot( const char* value );\n StringRequirement& equals( const char* value );\n StringRequirement& beginsWith( const char* value );\n StringRequirement& endsWith( const char* value );\n StringRequirement& contains( const char* value );\n StringRequirement& matches( const char* value );\n\nprivate:\n const char* m_Value;\n};\n\nclass PointerRequirement : public Requirement\n{\npublic:\n StringRequirement( const char* expression, const void* value );\n StringRequirement& is( const void* value );\n StringRequirement& isNot( const void* value );\n StringRequirement& equals( const void* value );\n\nprivate:\n const void* m_Value;\n};\n\n\n#define RequireThat( E ) RequireThat_(#E, E)\nBoolRequirement RequireThat_( const char* expression, bool value );\nIntRequirement RequireThat_( const char* expression, long value );\nFloatRequirement RequireThat_( const char* expression, double value );\nStringRequirement RequireThat_( const char* expression, const char* value );\nPointerRequirement RequireThat_( const char* expression, const void* value );\n\n\n\/\/ ---- bool implementation ----\n\nBoolRequirement::BoolRequirement( const char* expression, bool value ) :\n Requirement(expression),\n m_Value(value)\n{\n}\n\nBoolRequirement& BoolRequirement::is( bool value )\n{\n const char* expected = (value == true) ? \"true\" : \"false\";\n const char* got = (m_Value == true) ? \"true\" : \"false\";\n\n if(m_Value != value)\n testAbortCase(TEST_FAIL_CASE, \"Expected %s to be %s, but it was %s.\",\n m_Expression,\n expected,\n got);\n return *this;\n}\n\nBoolRequirement& BoolRequirement::isNot( bool value )\n{\n const char* expected = (value == true) ? \"true\" : \"false\";\n const char* got = (m_Value == true) ? \"true\" : \"false\";\n\n if(m_Value == value)\n testAbortCase(TEST_FAIL_CASE, \"Expected %s to be %s, but it was %s.\",\n m_Expression,\n expected,\n got);\n return *this;\n}\n\nBoolRequirement& BoolRequirement::equals( bool value )\n{\n return is(value);\n}\n\nBoolRequirement RequireThat_( const char* expression, bool value )\n{\n return BoolRequirement(expression, value);\n}\n\n\n\/\/ ---- int implementation ----\n\nIntRequirement::IntRequirement( const char* expression, long value ) :\n Requirement(expression),\n m_Value(value)\n{\n}\n\nIntRequirement( const char* expression, long value )\n{\n\n}\n\nIntRequirement& IntRequirement::is( long value )\n{\n}\n\nIntRequirement& IntRequirement::isNot( long value )\n{\n}\n\nIntRequirement& IntRequirement::equals( long value )\n{\n}\n\nIntRequirement& IntRequirement::isGreaterThan( long value )\n{\n}\n\nIntRequirement& IntRequirement::isGreaterOrEqualTo( long value )\n{\n}\n\nIntRequirement& IntRequirement::isSmallerThan( long value )\n{\n}\n\nIntRequirement& IntRequirement::isSmallerOrEqualTo( long value )\n{\n}\n\n\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \"viewer.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nViewer::~Viewer() {\n TTF_Quit();\n SDL_DestroyTexture(m_render_tex);\n SDL_DestroyRenderer(m_render);\n SDL_DestroyWindow(m_window);\n IMG_Quit();\n SDL_Quit();\n}\n\nint Viewer::init() {\n std::cout << \"Start init\" << std::endl;\n\n if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) {\n std::cerr << \"SDL_Init error: \" << SDL_GetError() << std::endl;\n return 1;\n }\n\n int width = 600;\n int height = 400;\n\n m_window = SDL_CreateWindow(\"trac0r\", 100, 100, width, height, SDL_WINDOW_SHOWN);\n if (m_window == nullptr) {\n std::cerr << \"SDL_CreateWindow error: \" << SDL_GetError() << std::endl;\n SDL_Quit();\n return 1;\n }\n\n \/\/ m_render = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED |\n \/\/ SDL_RENDERER_PRESENTVSYNC);\n m_render = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED);\n m_render_tex = SDL_CreateTexture(m_render, SDL_PIXELFORMAT_ARGB8888,\n SDL_TEXTUREACCESS_STREAMING, width, height);\n m_pixels.resize(width * height, 0);\n\n if (m_render == nullptr) {\n SDL_DestroyWindow(m_window);\n std::cerr << \"SDL_CreateRenderer error: \" << SDL_GetError() << std::endl;\n SDL_Quit();\n return 1;\n }\n\n if (TTF_Init() != 0) {\n std::cerr << \"SDL_ttf could not initialize! SDL_ttf error: \" << SDL_GetError() << std::endl;\n return 1;\n }\n\n \/\/ Setup scene\n SDL_SetRelativeMouseMode(SDL_TRUE);\n setup_scene();\n\n std::cout << \"Finish init\" << std::endl;\n\n return 0;\n}\n\nvoid Viewer::setup_scene() {\n auto triangle = std::make_unique(glm::vec3{0.f, 5.f, 0.f}, glm::vec3{0.5f, 5.f, 0.f},\n glm::vec3{0.5f, 5.f, 0.5f}, glm::vec3{0.3, 0.3, 0.3},\n glm::vec3{0.2, 0.2, 0.2});\n m_scene.push_back(std::move(triangle));\n \/\/ for (auto i = 0; i < 2; i++) {\n \/\/ auto triangle = std::make_unique(glm::ballRand(5.f), glm::ballRand(5.f),\n \/\/ glm::ballRand(5.f), glm::vec3{0.8, 0.3, 0.3}, glm::vec3{0.5, 0.5, 0.5});\n \/\/ m_scene.push_back(std::move(triangle));\n \/\/ }\n\n m_camera.pos = {0, 0, 0};\n m_camera.dir = {0, 1, 0};\n m_camera.up = {0, 0, 1};\n m_camera.fov = 90.f;\n m_camera.near_plane_dist = 0.1f;\n m_camera.far_plane_dist = 100.f;\n}\n\nglm::vec3 Viewer::intersect_scene(glm::vec3 &ray_pos, glm::vec3 &ray_dir, int depth) {\n const auto MAX_DEPTH = 5;\n\n if (depth == MAX_DEPTH)\n return {0, 0, 0};\n\n \/\/ check all triangles for collision\n bool collided = false;\n glm::vec3 ret_color;\n for (const auto &tri : m_scene) {\n glm::vec3 bary_pos;\n collided =\n glm::intersectRayTriangle(ray_pos, ray_dir, tri->m_v1, tri->m_v2, tri->m_v3, bary_pos);\n\n if (collided) {\n glm::vec3 new_ray_pos = ray_pos + ray_dir * bary_pos.z;\n auto new_ray_dir = tri->m_normal;\n new_ray_dir = glm::rotateX(tri->m_normal, glm::linearRand(-90.f, 90.f));\n new_ray_dir = glm::rotateY(tri->m_normal, glm::linearRand(-90.f, 90.f));\n\n float cos_theta = glm::dot(new_ray_dir, tri->m_normal);\n glm::vec3 brdf = 2.f * tri->m_reflectance * cos_theta;\n glm::vec3 reflected = intersect_scene(new_ray_pos, new_ray_dir, depth + 1);\n\n ret_color = tri->m_emittance + (brdf * reflected);\n break;\n }\n }\n\n if (collided) {\n return ret_color;\n } else {\n return {0, 0, 0};\n }\n}\n\nvoid Viewer::mainloop() {\n \/\/ Input\n SDL_Event e;\n while (SDL_PollEvent(&e)) {\n if (e.type == SDL_QUIT) {\n shutdown();\n }\n if (e.type == SDL_KEYDOWN) {\n if (e.key.keysym.sym == SDLK_ESCAPE) {\n shutdown();\n }\n }\n }\n\n glm::vec3 cam_velocity{0};\n const uint8_t *keystates = SDL_GetKeyboardState(0);\n if (keystates[SDL_SCANCODE_A])\n cam_velocity.x += -1;\n else if (keystates[SDL_SCANCODE_D])\n cam_velocity.x += 1;\n\n if (keystates[SDL_SCANCODE_W])\n cam_velocity.y += 1;\n else if (keystates[SDL_SCANCODE_S])\n cam_velocity.y += -1;\n\n m_camera.pos += cam_velocity;\n\n \/\/ Rendering here\n int width;\n int height;\n SDL_GetWindowSize(m_window, &width, &height);\n auto aspect_ratio = (float)width \/ (float)height;\n\n int mouse_x;\n int mouse_y;\n SDL_GetRelativeMouseState(&mouse_x, &mouse_y);\n\n m_camera.dir = glm::rotateX(m_camera.dir, mouse_y * 0.001f);\n m_camera.dir = glm::rotateZ(m_camera.dir, mouse_x * -0.001f);\n\n std::cout << glm::to_string(m_camera.pos) << std::endl;\n std::cout << glm::to_string(m_camera.dir) << std::endl;\n\n glm::mat4 projection_matrix = glm::perspective(\n m_camera.fov, aspect_ratio, m_camera.near_plane_dist, m_camera.far_plane_dist);\n glm::mat4 view_matrix = glm::lookAt(m_camera.pos, m_camera.pos + m_camera.dir, m_camera.up);\n\n \/\/ Sort by distance to camera\n std::sort(m_scene.begin(), m_scene.end(), [this](const auto &tri1, const auto &tri2) {\n return glm::distance(m_camera.pos, tri1->m_centroid) <\n glm::distance(m_camera.pos, tri2->m_centroid);\n });\n for (auto sample_cnt = 0; sample_cnt < 2; sample_cnt++) {\n for (auto x = 0; x < width; x++) {\n for (auto y = 0; y < height; y++) {\n glm::vec3 win_coords{x, y, 0};\n glm::mat4 model{1.0f};\n glm::vec4 viewport{0, 0, width, height};\n glm::vec3 object_coords =\n glm::unProject(win_coords, model * view_matrix, projection_matrix, viewport);\n glm::vec3 color = intersect_scene(object_coords, m_camera.dir, 0);\n \/\/ std::cout << \"r: \" << color.r << \" g: \" << color.g << \" b: \" << color.b <<\n \/\/ std::endl;\n m_pixels[y * width + x] = 0xff << 24 | int(color.r * 255) << 16 |\n int(color.g * 255) << 8 | int(color.b * 255);\n }\n }\n }\n\n SDL_SetRenderDrawColor(m_render, glm::linearRand(0, 255), glm::linearRand(0, 255),\n glm::linearRand(0, 255), 255);\n SDL_RenderClear(m_render);\n SDL_UpdateTexture(m_render_tex, 0, m_pixels.data(), width * sizeof(uint32_t));\n SDL_RenderCopy(m_render, m_render_tex, 0, 0);\n\n SDL_RenderPresent(m_render);\n\n int current_time = SDL_GetTicks();\n double dt = (current_time - m_last_frame_time) \/ 1000.0;\n (void)dt;\n m_last_frame_time = current_time;\n\n std::cout << \"FPS: \" << 1. \/ dt << std::endl;\n}\n\nSDL_Renderer *Viewer::renderer() {\n return m_render;\n}\n\nSDL_Window *Viewer::window() {\n return m_window;\n}\n\nbool Viewer::is_running() {\n return m_running;\n}\n\nvoid Viewer::shutdown() {\n m_running = false;\n}\nSlower movement#include \"viewer.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nViewer::~Viewer() {\n TTF_Quit();\n SDL_DestroyTexture(m_render_tex);\n SDL_DestroyRenderer(m_render);\n SDL_DestroyWindow(m_window);\n IMG_Quit();\n SDL_Quit();\n}\n\nint Viewer::init() {\n std::cout << \"Start init\" << std::endl;\n\n if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) {\n std::cerr << \"SDL_Init error: \" << SDL_GetError() << std::endl;\n return 1;\n }\n\n int width = 600;\n int height = 400;\n\n m_window = SDL_CreateWindow(\"trac0r\", 100, 100, width, height, SDL_WINDOW_SHOWN);\n if (m_window == nullptr) {\n std::cerr << \"SDL_CreateWindow error: \" << SDL_GetError() << std::endl;\n SDL_Quit();\n return 1;\n }\n\n \/\/ m_render = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED |\n \/\/ SDL_RENDERER_PRESENTVSYNC);\n m_render = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED);\n m_render_tex = SDL_CreateTexture(m_render, SDL_PIXELFORMAT_ARGB8888,\n SDL_TEXTUREACCESS_STREAMING, width, height);\n m_pixels.resize(width * height, 0);\n\n if (m_render == nullptr) {\n SDL_DestroyWindow(m_window);\n std::cerr << \"SDL_CreateRenderer error: \" << SDL_GetError() << std::endl;\n SDL_Quit();\n return 1;\n }\n\n if (TTF_Init() != 0) {\n std::cerr << \"SDL_ttf could not initialize! SDL_ttf error: \" << SDL_GetError() << std::endl;\n return 1;\n }\n\n \/\/ Setup scene\n SDL_SetRelativeMouseMode(SDL_TRUE);\n setup_scene();\n\n std::cout << \"Finish init\" << std::endl;\n\n return 0;\n}\n\nvoid Viewer::setup_scene() {\n auto triangle = std::make_unique(glm::vec3{0.f, 5.f, 0.f}, glm::vec3{0.5f, 5.f, 0.f},\n glm::vec3{0.5f, 5.f, 0.5f}, glm::vec3{0.3, 0.3, 0.3},\n glm::vec3{0.2, 0.2, 0.2});\n m_scene.push_back(std::move(triangle));\n \/\/ for (auto i = 0; i < 2; i++) {\n \/\/ auto triangle = std::make_unique(glm::ballRand(5.f), glm::ballRand(5.f),\n \/\/ glm::ballRand(5.f), glm::vec3{0.8, 0.3, 0.3}, glm::vec3{0.5, 0.5, 0.5});\n \/\/ m_scene.push_back(std::move(triangle));\n \/\/ }\n\n m_camera.pos = {0, 0, 0};\n m_camera.dir = {0, 1, 0};\n m_camera.up = {0, 0, 1};\n m_camera.fov = 90.f;\n m_camera.near_plane_dist = 0.1f;\n m_camera.far_plane_dist = 100.f;\n}\n\nglm::vec3 Viewer::intersect_scene(glm::vec3 &ray_pos, glm::vec3 &ray_dir, int depth) {\n const auto MAX_DEPTH = 5;\n\n if (depth == MAX_DEPTH)\n return {0, 0, 0};\n\n \/\/ check all triangles for collision\n bool collided = false;\n glm::vec3 ret_color;\n for (const auto &tri : m_scene) {\n glm::vec3 bary_pos;\n collided =\n glm::intersectRayTriangle(ray_pos, ray_dir, tri->m_v1, tri->m_v2, tri->m_v3, bary_pos);\n\n if (collided) {\n glm::vec3 new_ray_pos = ray_pos + ray_dir * bary_pos.z;\n auto new_ray_dir = tri->m_normal;\n new_ray_dir = glm::rotateX(tri->m_normal, glm::linearRand(-90.f, 90.f));\n new_ray_dir = glm::rotateY(tri->m_normal, glm::linearRand(-90.f, 90.f));\n\n float cos_theta = glm::dot(new_ray_dir, tri->m_normal);\n glm::vec3 brdf = 2.f * tri->m_reflectance * cos_theta;\n glm::vec3 reflected = intersect_scene(new_ray_pos, new_ray_dir, depth + 1);\n\n ret_color = tri->m_emittance + (brdf * reflected);\n break;\n }\n }\n\n if (collided) {\n return ret_color;\n } else {\n return {0, 0, 0};\n }\n}\n\nvoid Viewer::mainloop() {\n \/\/ Input\n SDL_Event e;\n while (SDL_PollEvent(&e)) {\n if (e.type == SDL_QUIT) {\n shutdown();\n }\n if (e.type == SDL_KEYDOWN) {\n if (e.key.keysym.sym == SDLK_ESCAPE) {\n shutdown();\n }\n }\n }\n\n glm::vec3 cam_velocity{0};\n const uint8_t *keystates = SDL_GetKeyboardState(0);\n if (keystates[SDL_SCANCODE_A])\n cam_velocity.x += -0.2f;\n else if (keystates[SDL_SCANCODE_D])\n cam_velocity.x += 0.2f;\n\n if (keystates[SDL_SCANCODE_W])\n cam_velocity.y += 0.2f;\n else if (keystates[SDL_SCANCODE_S])\n cam_velocity.y += -0.2f;\n\n m_camera.pos += cam_velocity;\n\n \/\/ Rendering here\n int width;\n int height;\n SDL_GetWindowSize(m_window, &width, &height);\n auto aspect_ratio = (float)width \/ (float)height;\n\n int mouse_x;\n int mouse_y;\n SDL_GetRelativeMouseState(&mouse_x, &mouse_y);\n\n m_camera.dir = glm::rotateX(m_camera.dir, mouse_y * 0.001f);\n m_camera.dir = glm::rotateZ(m_camera.dir, mouse_x * -0.001f);\n\n std::cout << glm::to_string(m_camera.pos) << std::endl;\n std::cout << glm::to_string(m_camera.dir) << std::endl;\n\n glm::mat4 projection_matrix = glm::perspective(\n m_camera.fov, aspect_ratio, m_camera.near_plane_dist, m_camera.far_plane_dist);\n glm::mat4 view_matrix = glm::lookAt(m_camera.pos, m_camera.pos + m_camera.dir, m_camera.up);\n\n \/\/ Sort by distance to camera\n std::sort(m_scene.begin(), m_scene.end(), [this](const auto &tri1, const auto &tri2) {\n return glm::distance(m_camera.pos, tri1->m_centroid) <\n glm::distance(m_camera.pos, tri2->m_centroid);\n });\n for (auto sample_cnt = 0; sample_cnt < 2; sample_cnt++) {\n for (auto x = 0; x < width; x++) {\n for (auto y = 0; y < height; y++) {\n glm::vec3 win_coords{x, y, 0};\n glm::mat4 model{1.0f};\n glm::vec4 viewport{0, 0, width, height};\n glm::vec3 object_coords =\n glm::unProject(win_coords, model * view_matrix, projection_matrix, viewport);\n glm::vec3 color = intersect_scene(object_coords, m_camera.dir, 0);\n \/\/ std::cout << \"r: \" << color.r << \" g: \" << color.g << \" b: \" << color.b <<\n \/\/ std::endl;\n m_pixels[y * width + x] = 0xff << 24 | int(color.r * 255) << 16 |\n int(color.g * 255) << 8 | int(color.b * 255);\n }\n }\n }\n\n SDL_SetRenderDrawColor(m_render, glm::linearRand(0, 255), glm::linearRand(0, 255),\n glm::linearRand(0, 255), 255);\n SDL_RenderClear(m_render);\n SDL_UpdateTexture(m_render_tex, 0, m_pixels.data(), width * sizeof(uint32_t));\n SDL_RenderCopy(m_render, m_render_tex, 0, 0);\n\n SDL_RenderPresent(m_render);\n\n int current_time = SDL_GetTicks();\n double dt = (current_time - m_last_frame_time) \/ 1000.0;\n (void)dt;\n m_last_frame_time = current_time;\n\n std::cout << \"FPS: \" << 1. \/ dt << std::endl;\n}\n\nSDL_Renderer *Viewer::renderer() {\n return m_render;\n}\n\nSDL_Window *Viewer::window() {\n return m_window;\n}\n\nbool Viewer::is_running() {\n return m_running;\n}\n\nvoid Viewer::shutdown() {\n m_running = false;\n}\n<|endoftext|>"} {"text":"sw: update hintids.hxx comments to match reality<|endoftext|>"} {"text":"#include \"biobj_simplex.hpp\"\n\nusing namespace std;\n\nBiobj_simplex::Biobj_simplex() {\n model = new OsiClpSolverInterface;\n}\n\n\nBiobj_simplex::~Biobj_simplex() {\n delete model;\n delete[] cost1;\n delete[] cost2;\n delete[] work_col;\n delete[] basics;\n}\n\n\ndouble Biobj_simplex::getInfinity() {\n return model->getInfinity();\n}\n\n\nvoid Biobj_simplex::loadProblem(const CoinPackedMatrix &matrix,\n const double *col_lb,\n const double *col_ub,\n const double *objective1,\n const double *objective2,\n const double *row_lb,\n const double *row_ub) {\n num_cols = matrix.getNumCols();\n num_rows = matrix.getNumRows();\n\n \/\/ load the problem as a single objective one\n model->loadProblem(matrix, col_lb, col_ub, objective1, row_lb, row_ub);\n \/\/ artificially add the second objective function as a dummy ubounded constraint\n CoinPackedVector obj2(num_cols, objective2);\n model->addRow(obj2, -1.0 * model->getInfinity(), model->getInfinity());\n\n \/\/ allocate memory for working arrays\n cost1 = new double[num_cols + num_rows];\n cost2 = new double[num_cols + num_rows];\n work_col = new double[num_cols];\n basics = new int[num_rows];\n\n \/\/ tell Osi and Clp to be quiet\n model->messageHandler()->setLogLevel(0);\n}\n\n\nvoid Biobj_simplex::updateCosts() {\n \/\/ the first array of reduced costs\n \/\/TODO copy all array at once\n for (int i = 0; i < num_cols; i++) {\n cost1[i] = model->getReducedCost()[i];\n }\n for (int i = 0; i < num_rows; i++) {\n cost1[num_cols + i] = -model->getRowPrice()[i];\n }\n\n \/\/ get the second array of reduced costs from the dummy constraint\n model->getBInvARow(num_rows, cost2, (double*)(cost2 + num_cols));\n}\n\n\nvoid Biobj_simplex::solve() {\n \/\/ phases 1 and 2: check whether the problem is feasible and compute\n \/\/ the first efficient solution\n model->initialSolve();\n\n \/\/ tell model to allow us to do extra things\n model->enableSimplexInterface(true);\n\n \/\/ gather data to update reduced costs\n const double* upper = model->getRowUpper();\n const double* solution = model->getColSolution();\n const double* activity = model->getRowActivity();\n updateCosts();\n\n model->getBasics(basics);\n\n \/\/ manually compute b values of the simplex tableau\n vector b;\n for ( int i = 0; i < num_rows; i++ ) {\n \/\/ the value depends on whether i is in the basis the index of a\n \/\/ regular variable ( < num_cols ) or a slack variable ( >= )\n if(basics[i] < num_cols)\n b.push_back(solution[basics[i]]);\n else\n b.push_back(upper[i] - activity[i]);\n }\n \/\/ gather in s the values in decision space of the current solution\n vector s (solution, solution + num_cols);\n\n \/\/ create the corresponding solution with its objective values\n BVect sol(\/*-1.0 **\/ model->getObjValue(), \/*-1.0 **\/ activity[num_rows], s);\n solutions.push_back(sol);\n\n \/\/ compute candidate variables to enter the basis\n while (computeVarIn()){\n \/\/ while at least one such variables does exist, \n \/\/ compute the corresponding leaving variable\n computeVarOut();\n\n \/\/ perform pivot\n int outstatus = 1;\n model->pivot(var_in, basics[var_out], outstatus);\n\n \/\/ update data used to compute reduced costs\n upper = model->getRowUpper();\n solution = model->getColSolution();\n activity = model->getRowActivity();\n model->getBasics(basics);\n for ( int i = 0; i < num_rows; i++ ) {\n if(basics[i] < num_cols)\n b.push_back(solution[basics[i]]);\n else\n b.push_back(upper[i] - activity[i]);\n }\n \/\/ create the newly obtained solution\n vector s (solution, solution + num_cols);\n\n BVect sol2(\/*-1.0 **\/ model->getObjValue(), \/*-1.0 **\/ activity[num_rows], s);\n solutions.push_back(sol2);\n updateCosts();\n }\n}\n\n\nvector Biobj_simplex::getSols() {\n return solutions;\n}\n\n\nbool Biobj_simplex::computeVarIn() {\n lambda = 0;\n bool var_in_found = false;\n for( int i = 0; i < num_cols; i++ ) {\n if ( (cost1[i] > 0) && (cost2[i] < 0) ) {\n \/\/ the current variable is eligible to enter the basis\n double candidateLambda = (-cost2[i]\/(cost1[i]-cost2[i]));\n var_in_found = true;\n if (candidateLambda > lambda) {\n \/\/ the entering variable to select has the greatest lambda value\n lambda = candidateLambda;\n var_in = i;\n }\n }\n }\n return var_in_found;\n}\n\n\nvoid Biobj_simplex::computeVarOut() {\n \/\/ update work_col to represent the column of var_in\n model->getBInvACol(var_in, work_col);\n\n double current_ratio;\n double min_ratio;\n bool one_out_found = false;\n\n \/\/ update data (a little redundant, isn't it?)\n const double* upper = model->getRowUpper();\n const double* solution = model->getColSolution();\n const double* activity = model->getRowActivity();\n vector b;\n model->getBasics(basics);\n for ( int i = 0; i < num_rows; i++ ) {\n if(basics[i] < num_cols)\n b.push_back(solution[basics[i]]);\n else\n b.push_back(upper[i] - activity[i]);\n }\n\n for( int i = 0; i < num_rows; i++ ){\n if( work_col[i] > 0){\n \/\/ the current variable is eligible to leave the basis\n current_ratio = b[basics[i]]\/work_col[i];\n if( !one_out_found ){\n one_out_found = true;\n var_out = i;\n min_ratio = current_ratio;\n } else if( current_ratio < min_ratio ) {\n \/\/ the leaving variable to select has the lowest ratio\n var_out = i;\n min_ratio = current_ratio;\n }\n }\n }\n}\nAlso search for pivot among slack vars#include \"biobj_simplex.hpp\"\n\nusing namespace std;\n\nBiobj_simplex::Biobj_simplex() {\n model = new OsiClpSolverInterface;\n}\n\n\nBiobj_simplex::~Biobj_simplex() {\n delete model;\n delete[] cost1;\n delete[] cost2;\n delete[] work_col;\n delete[] basics;\n}\n\n\ndouble Biobj_simplex::getInfinity() {\n return model->getInfinity();\n}\n\n\nvoid Biobj_simplex::loadProblem(const CoinPackedMatrix &matrix,\n const double *col_lb,\n const double *col_ub,\n const double *objective1,\n const double *objective2,\n const double *row_lb,\n const double *row_ub) {\n num_cols = matrix.getNumCols();\n num_rows = matrix.getNumRows();\n\n \/\/ load the problem as a single objective one\n model->loadProblem(matrix, col_lb, col_ub, objective1, row_lb, row_ub);\n \/\/ artificially add the second objective function as a dummy ubounded constraint\n CoinPackedVector obj2(num_cols, objective2);\n model->addRow(obj2, -1.0 * model->getInfinity(), model->getInfinity());\n\n \/\/ allocate memory for working arrays\n cost1 = new double[num_cols + num_rows];\n cost2 = new double[num_cols + num_rows];\n work_col = new double[num_cols];\n basics = new int[num_rows];\n\n \/\/ tell Osi and Clp to be quiet\n model->messageHandler()->setLogLevel(0);\n}\n\n\nvoid Biobj_simplex::updateCosts() {\n \/\/ the first array of reduced costs\n \/\/TODO copy all array at once\n for (int i = 0; i < num_cols; i++) {\n cost1[i] = model->getReducedCost()[i];\n }\n for (int i = 0; i < num_rows; i++) {\n cost1[num_cols + i] = -model->getRowPrice()[i];\n }\n\n \/\/ get the second array of reduced costs from the dummy constraint\n model->getBInvARow(num_rows, cost2, (double*)(cost2 + num_cols));\n}\n\n\nvoid Biobj_simplex::solve() {\n \/\/ phases 1 and 2: check whether the problem is feasible and compute\n \/\/ the first efficient solution\n model->initialSolve();\n\n \/\/ tell model to allow us to do extra things\n model->enableSimplexInterface(true);\n\n \/\/ gather data to update reduced costs\n const double* upper = model->getRowUpper();\n const double* solution = model->getColSolution();\n const double* activity = model->getRowActivity();\n updateCosts();\n\n model->getBasics(basics);\n\n \/\/ manually compute b values of the simplex tableau\n vector b;\n for ( int i = 0; i < num_rows; i++ ) {\n \/\/ the value depends on whether i is in the basis the index of a\n \/\/ regular variable ( < num_cols ) or a slack variable ( >= )\n if(basics[i] < num_cols)\n b.push_back(solution[basics[i]]);\n else\n b.push_back(upper[i] - activity[i]);\n }\n \/\/ gather in s the values in decision space of the current solution\n vector s (solution, solution + num_cols);\n\n \/\/ create the corresponding solution with its objective values\n BVect sol(\/*-1.0 **\/ model->getObjValue(), \/*-1.0 **\/ activity[num_rows], s);\n solutions.push_back(sol);\n\n \/\/ compute candidate variables to enter the basis\n while (computeVarIn()){\n \/\/ while at least one such variables does exist, \n \/\/ compute the corresponding leaving variable\n computeVarOut();\n\n \/\/ perform pivot\n int outstatus = 1;\n model->pivot(var_in, basics[var_out], outstatus);\n\n \/\/ update data used to compute reduced costs\n upper = model->getRowUpper();\n solution = model->getColSolution();\n activity = model->getRowActivity();\n model->getBasics(basics);\n for ( int i = 0; i < num_rows; i++ ) {\n if(basics[i] < num_cols)\n b.push_back(solution[basics[i]]);\n else\n b.push_back(upper[i] - activity[i]);\n }\n \/\/ create the newly obtained solution\n vector s (solution, solution + num_cols);\n\n BVect sol2(\/*-1.0 **\/ model->getObjValue(), \/*-1.0 **\/ activity[num_rows], s);\n solutions.push_back(sol2);\n updateCosts();\n }\n}\n\n\nvector Biobj_simplex::getSols() {\n return solutions;\n}\n\n\nbool Biobj_simplex::computeVarIn() {\n lambda = 0;\n bool var_in_found = false;\n for( int i = 0; i < num_cols + num_rows; i++ ) {\n if ( (cost1[i] >= 0) && (cost2[i] < 0) ) {\n \/\/ the current variable is eligible to enter the basis\n double candidateLambda = (-cost2[i]\/(cost1[i]-cost2[i]));\n var_in_found = true;\n if (candidateLambda > lambda) {\n \/\/ the entering variable to select has the greatest lambda value\n lambda = candidateLambda;\n var_in = i;\n }\n }\n }\n return var_in_found;\n}\n\n\nvoid Biobj_simplex::computeVarOut() {\n \/\/ update work_col to represent the column of var_in\n model->getBInvACol(var_in, work_col);\n\n double current_ratio;\n double min_ratio;\n bool one_out_found = false;\n\n \/\/ update data (a little redundant, isn't it?)\n const double* upper = model->getRowUpper();\n const double* solution = model->getColSolution();\n const double* activity = model->getRowActivity();\n vector b;\n model->getBasics(basics);\n for ( int i = 0; i < num_rows; i++ ) {\n if(basics[i] < num_cols)\n b.push_back(solution[basics[i]]);\n else\n b.push_back(upper[i] - activity[i]);\n }\n\n for( int i = 0; i < num_rows; i++ ){\n if( work_col[i] > 0){\n \/\/ the current variable is eligible to leave the basis\n current_ratio = b[basics[i]]\/work_col[i];\n if( !one_out_found ){\n one_out_found = true;\n var_out = i;\n min_ratio = current_ratio;\n } else if( current_ratio < min_ratio ) {\n \/\/ the leaving variable to select has the lowest ratio\n var_out = i;\n min_ratio = current_ratio;\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/** @file\n *\n * @ingroup dspSoundFileLib\n *\n * @brief Loads soundfile data into a sample matrix\n *\n * @details This object collaborates with #TTSampleMatrix to load values from a sound file into the sample matrix.\n *\n * @see TTSampleMatrix\n *\n * @authors Nathan Wolek\n *\n * @copyright Copyright © 2013 by Nathan Wolek @n\n * This code is licensed under the terms of the \"New BSD License\" @n\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTSoundfileLoader.h\"\n\n#define thisTTClass\t\t\tTTSoundfileLoader\n#define thisTTClassName\t\t\"soundfile.loader\"\n#define thisTTClassTags\t\t\"audio, soundfile, buffer\"\n\nTTObjectBasePtr TTSoundfileLoader::instantiate(TTSymbol& name, TTValue& arguments)\n{\n\treturn new TTSoundfileLoader(arguments);\n}\n\n\nextern \"C\" void TTSoundfileLoader::registerClass()\n{\n\tTTClassRegister(thisTTClassName, thisTTClassTags, TTSoundfileLoader::instantiate);\n}\n\n\nTTSoundfileLoader::TTSoundfileLoader(TTValue& arguments) :\nTTSoundfile(arguments),\nmTargetMatrix(NULL)\n{ \n \/\/ add the attributes and messages here\n \/\/addMessageWithArguments(load);\n \n \/\/ initialize happens as part of the load\n}\n\nTTSoundfileLoader::~TTSoundfileLoader()\n{\n\tmTargetMatrix = NULL; \/\/ reset to NULL for reference counting\n}\n\n\/**\tInternal method that sets the class's pointer to the target sample matrix for loading sound file data. Because only TTMatrixPtr is allowed to be passed using TTValue, we perform a test to ensure that it is indeed a TTSampleMatrix before setting the new pointer.\n @param newTargetMatrix pointer to the new matrix\n @return TTErr kTTErrNone if the pointer was updated. kTTErrInvalidValue is the pointer was not to a TTSampleMatrix.\n *\/\nTTErr TTSoundfileLoader::setTargetMatrix(const TTMatrixPtr newTargetMatrix)\n{\n if (newTargetMatrix->getName() != \"samplematrix\")\n {\n return kTTErrInvalidValue;\n } else {\n mTargetMatrix = (TTSampleMatrixPtr)&newTargetMatrix;\n return kTTErrNone;\n }\n}\n\n\/**\tPublic method used to trigger the load process. Copies samples from a sound file on the hard drive into a TTSampleMatrix. \n @param[in] input requires 2 items: TTSymbol containing the file path, TTMatrixPtr to the target matrix.\n @param[out] unusedOutput not used \n @return TTErr kTTErrNone load was successful. kTTErrInvalidFilepath if the filepath was invalid. kTTErrInvalidValue if the pointer to TTSampleMatrix was invalid.\n *\/\nTTErr TTSoundfileLoader::load(const TTValueRef input, TTValueRef unusedOutput)\n{\n \/\/ sort out the two input values\n TTValue newFilePath = input[0];\n TTMatrixPtr newTargetMatrix = input[1];\n TTErr err = kTTErrNone;\n \n \/\/ set the mFilePath\n err = setFilePath(newFilePath);\n \n \/\/ set the mTargetMatrix\n if (!err)\n err = setTargetMatrix(newTargetMatrix);\n \n \/\/ set the start and end points in source file\n \n \/\/ set the start and end points in mTargetMatrix\n \n \/\/ copy the samples (one at a time initially, to be optimized later)\n \n \/\/ QUESTIONS to consider\n \/\/ how will we handle multi channels?\n \/\/ should the sample rate get copied across?\n \/\/ if the size is different, what is the desired behavior?\n \n \/\/ reset? should mFilePath & mTargetMatrix be reset at the conclusion?\n \n return err;\n}first functioning code for TTSoundfileLoader:load()\/** @file\n *\n * @ingroup dspSoundFileLib\n *\n * @brief Loads soundfile data into a sample matrix\n *\n * @details This object collaborates with #TTSampleMatrix to load values from a sound file into the sample matrix.\n *\n * @see TTSampleMatrix\n *\n * @authors Nathan Wolek\n *\n * @copyright Copyright © 2013 by Nathan Wolek @n\n * This code is licensed under the terms of the \"New BSD License\" @n\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTSoundfileLoader.h\"\n\n#define thisTTClass\t\t\tTTSoundfileLoader\n#define thisTTClassName\t\t\"soundfile.loader\"\n#define thisTTClassTags\t\t\"audio, soundfile, buffer\"\n\nTTObjectBasePtr TTSoundfileLoader::instantiate(TTSymbol& name, TTValue& arguments)\n{\n\treturn new TTSoundfileLoader(arguments);\n}\n\n\nextern \"C\" void TTSoundfileLoader::registerClass()\n{\n\tTTClassRegister(thisTTClassName, thisTTClassTags, TTSoundfileLoader::instantiate);\n}\n\n\nTTSoundfileLoader::TTSoundfileLoader(TTValue& arguments) :\nTTSoundfile(arguments),\nmTargetMatrix(NULL)\n{ \n \/\/ add the attributes and messages here\n \/\/addMessageWithArguments(load);\n \n \/\/ initialize happens as part of the load\n}\n\nTTSoundfileLoader::~TTSoundfileLoader()\n{\n\tmTargetMatrix = NULL; \/\/ reset to NULL for reference counting\n}\n\n\/**\tInternal method that sets the class's pointer to the target sample matrix for loading sound file data. Because only TTMatrixPtr is allowed to be passed using TTValue, we perform a test to ensure that it is indeed a TTSampleMatrix before setting the new pointer.\n @param newTargetMatrix pointer to the new matrix\n @return TTErr kTTErrNone if the pointer was updated. kTTErrInvalidValue is the pointer was not to a TTSampleMatrix.\n *\/\nTTErr TTSoundfileLoader::setTargetMatrix(const TTMatrixPtr newTargetMatrix)\n{\n if (newTargetMatrix->getName() != \"samplematrix\")\n {\n return kTTErrInvalidValue;\n } else {\n mTargetMatrix = (TTSampleMatrixPtr)&newTargetMatrix;\n return kTTErrNone;\n }\n}\n\n\/**\tPublic method used to trigger the load process. Copies samples from a sound file on the hard drive into a TTSampleMatrix. \n @param[in] input requires 2 items: TTSymbol containing the file path, TTMatrixPtr to the target matrix.\n @param[out] unusedOutput not used \n @return TTErr kTTErrNone load was successful. kTTErrInvalidFilepath if the filepath was invalid. kTTErrInvalidValue if the pointer to TTSampleMatrix was invalid.\n *\/\nTTErr TTSoundfileLoader::load(const TTValueRef input, TTValueRef unusedOutput)\n{\n \/\/ sort out the two input values\n TTValue newFilePath = input[0];\n TTMatrixPtr newTargetMatrix = input[1];\n TTErr err = kTTErrNone;\n \n \/\/ set the mFilePath\n err = setFilePath(newFilePath);\n \n \/\/ set the mTargetMatrix\n if (!err)\n err = setTargetMatrix(newTargetMatrix);\n \n \/\/ set the start and end points in source file\n \n \/\/ set the start and end points in mTargetMatrix\n \n \/\/ copy the samples (one at a time initially, to be optimized later)\n \/\/ NOTE: we will temporarily assume that channel counts match\n TTUInt32 targetMatrixLength = mTargetMatrix->getComponentCount();\n \n if (this->getLengthInSamples() < targetMatrixLength)\n {\n \/\/ we will throw an error because we are only interested in completely filling the SampleMartix, for now\n err = kTTErrGeneric;\n } else {\n TTSampleValue valueToMove;\n \n for (int sample=0;sample TTSampleMatrix:poke()\n this->peek(sample,0,valueToMove);\n mTargetMatrix->poke(sample,0,valueToMove);\n }\n }\n \n \/\/ QUESTIONS to consider\n \/\/ how will we handle multi channels?\n \/\/ should the sample rate get copied across?\n \/\/ if the size is different, what is the desired behavior?\n \n \/\/ reset? should mFilePath & mTargetMatrix be reset at the conclusion?\n \n return err;\n}<|endoftext|>"} {"text":"For touch implement a simpler add bookmark until new Views based widgets are available<|endoftext|>"} {"text":"\/*****************************************************************************\n * VLC backend for the Phonon library *\n * Copyright (C) 2007-2008 Tanguy Krotoff *\n * Copyright (C) 2008 Lukas Durfina *\n * Copyright (C) 2009 Fathi Boudra *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 3 of the License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this package; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *\n *****************************************************************************\/\n\n#include \"vlcloader.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Global variables\nlibvlc_instance_t *vlc_instance = 0;\nlibvlc_media_player_t *vlc_current_media_player = 0;\n\nnamespace Phonon\n{\nnamespace VLC {\n\nbool vlcInit()\n{\n \/\/ Global variables\n vlc_instance = 0;\n\n QString path = vlcPath();\n if (!path.isEmpty()) {\n QString pluginsPath = QString(\"--plugin-path=\") + QDir::toNativeSeparators(QFileInfo(vlcPath()).dir().path());\n#if defined(Q_OS_UNIX)\n pluginsPath.append(\"\/vlc\");\n#elif defined(Q_OS_WIN)\n pluginsPath.append(\"\\\\plugins\");\n#endif\n QByteArray p = path.toLatin1();\n QByteArray pp = pluginsPath.toLatin1();\n \/\/ VLC command line options. See vlc --full-help\n const char *vlcArgs[] = {\n p.constData(),\n pp.constData(),\n \"--verbose=2\",\n \"--intf=dummy\",\n \"--extraintf=logger\",\n \"--ignore-config\",\n \"--reset-plugins-cache\",\n \"--no-media-library\",\n \"--no-one-instance\",\n \"--no-osd\",\n \"--no-stats\",\n \"--no-video-title-show\"\n };\n\n \/\/ Create and initialize a libvlc instance (it should be done only once)\n vlc_instance = libvlc_new(sizeof(vlcArgs) \/ sizeof(*vlcArgs), vlcArgs);\n if(!vlc_instance)\n qDebug() << \"libvlc exception:\" << libvlc_errmsg();\n\n return true;\n } else {\n return false;\n }\n}\n\nvoid vlcRelease()\n{\n libvlc_release(vlc_instance);\n vlcUnload();\n}\n\n#if defined(Q_OS_UNIX)\nstatic bool libGreaterThan(const QString &lhs, const QString &rhs)\n{\n QStringList lhsparts = lhs.split(QLatin1Char('.'));\n QStringList rhsparts = rhs.split(QLatin1Char('.'));\n Q_ASSERT(lhsparts.count() > 1 && rhsparts.count() > 1);\n\n for (int i = 1; i < rhsparts.count(); ++i) {\n if (lhsparts.count() <= i)\n \/\/ left hand side is shorter, so it's less than rhs\n return false;\n\n bool ok = false;\n int b = 0;\n int a = lhsparts.at(i).toInt(&ok);\n if (ok)\n b = rhsparts.at(i).toInt(&ok);\n if (ok) {\n \/\/ both toInt succeeded\n if (a == b)\n continue;\n return a > b;\n } else {\n \/\/ compare as strings;\n if (lhsparts.at(i) == rhsparts.at(i))\n continue;\n return lhsparts.at(i) > rhsparts.at(i);\n }\n }\n\n \/\/ they compared strictly equally so far\n \/\/ lhs cannot be less than rhs\n return true;\n}\n#endif\n\nstatic QStringList findAllLibVlc()\n{\n QStringList paths;\n#if defined(Q_OS_UNIX)\n paths = QString::fromLatin1(qgetenv(\"LD_LIBRARY_PATH\"))\n .split(QLatin1Char(':'), QString::SkipEmptyParts);\n paths << QLatin1String(PHONON_LIB_INSTALL_DIR) << QLatin1String(\"\/usr\/lib\") << QLatin1String(\"\/usr\/local\/lib\");\n\n QStringList foundVlcs;\n foreach (const QString &path, paths) {\n QDir dir = QDir(path);\n QStringList entryList = dir.entryList(QStringList() << QLatin1String(\"libvlc.*\"), QDir::Files);\n\n qSort(entryList.begin(), entryList.end(), libGreaterThan);\n foreach (const QString &entry, entryList)\n foundVlcs << path + QLatin1Char('\/') + entry;\n }\n\n return foundVlcs;\n#elif defined(Q_OS_WIN)\n \/\/ Read VLC version and installation directory from Windows registry\n QSettings settings(QSettings::SystemScope, \"VideoLAN\", \"VLC\");\n QString vlcVersion = settings.value(\"Version\").toString();\n QString vlcInstallDir = settings.value(\"InstallDir\").toString();\n if (vlcVersion.startsWith(\"1.0\") && !vlcInstallDir.isEmpty()) {\n paths << vlcInstallDir + QLatin1Char('\\\\') + \"libvlc.dll\"; \n return paths;\n }else{\n \/\/If nothing is found in the registry try %PATH%\n QStringList searchPaths = QString::fromLatin1(qgetenv(\"PATH\"))\n .split(QLatin1Char(';'), QString::SkipEmptyParts);\n QStringList foundVlcs;\n foreach (const QString &sp, searchPaths) {\n QDir dir = QDir(sp);\n QStringList entryList = dir.entryList(QStringList() << QLatin1String(\"libvlc.dll\"), QDir::Files);\n foreach (const QString &entry, entryList)\n foundVlcs << sp + QLatin1Char('\\\\') + entry;\n }\n paths<setFileName(path);\n\n if (vlcLibrary->resolve(\"libvlc_get_version\")) {\n \/\/TODO:call libvlc_get_version to test version?\n return path;\n } else {\n qDebug(\"Cannot resolve the symbol or load VLC library\");\n }\n qWarning() << vlcLibrary->errorString();\n }\n\n vlcUnload();\n\n return QString();\n}\n\nvoid vlcUnload()\n{\n vlcLibrary->unload();\n delete vlcLibrary;\n vlcLibrary = 0;\n}\n\n}\n} \/\/ Namespace Phonon::VLC\nchanges in libvlc validation\/*****************************************************************************\n * VLC backend for the Phonon library *\n * Copyright (C) 2007-2008 Tanguy Krotoff *\n * Copyright (C) 2008 Lukas Durfina *\n * Copyright (C) 2009 Fathi Boudra *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 3 of the License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this package; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *\n *****************************************************************************\/\n\n#include \"vlcloader.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Global variables\nlibvlc_instance_t *vlc_instance = 0;\nlibvlc_media_player_t *vlc_current_media_player = 0;\n\nnamespace Phonon\n{\nnamespace VLC {\n\nbool vlcInit()\n{\n \/\/ Global variables\n vlc_instance = 0;\n\n QString path = vlcPath();\n if (!path.isEmpty()) {\n QString pluginsPath = QString(\"--plugin-path=\") + QDir::toNativeSeparators(QFileInfo(vlcPath()).dir().path());\n#if defined(Q_OS_UNIX)\n pluginsPath.append(\"\/vlc\");\n#elif defined(Q_OS_WIN)\n pluginsPath.append(\"\\\\plugins\");\n#endif\n QByteArray p = path.toLatin1();\n QByteArray pp = pluginsPath.toLatin1();\n \/\/ VLC command line options. See vlc --full-help\n const char *vlcArgs[] = {\n p.constData(),\n pp.constData(),\n \"--verbose=2\",\n \"--intf=dummy\",\n \"--extraintf=logger\",\n \"--ignore-config\",\n \"--reset-plugins-cache\",\n \"--no-media-library\",\n \"--no-one-instance\",\n \"--no-osd\",\n \"--no-stats\",\n \"--no-video-title-show\"\n };\n\n \/\/ Create and initialize a libvlc instance (it should be done only once)\n vlc_instance = libvlc_new(sizeof(vlcArgs) \/ sizeof(*vlcArgs), vlcArgs);\n if(!vlc_instance)\n qDebug() << \"libvlc exception:\" << libvlc_errmsg();\n\n return true;\n } else {\n return false;\n }\n}\n\nvoid vlcRelease()\n{\n libvlc_release(vlc_instance);\n vlcUnload();\n}\n\n#if defined(Q_OS_UNIX)\nstatic bool libGreaterThan(const QString &lhs, const QString &rhs)\n{\n QStringList lhsparts = lhs.split(QLatin1Char('.'));\n QStringList rhsparts = rhs.split(QLatin1Char('.'));\n Q_ASSERT(lhsparts.count() > 1 && rhsparts.count() > 1);\n\n for (int i = 1; i < rhsparts.count(); ++i) {\n if (lhsparts.count() <= i)\n \/\/ left hand side is shorter, so it's less than rhs\n return false;\n\n bool ok = false;\n int b = 0;\n int a = lhsparts.at(i).toInt(&ok);\n if (ok)\n b = rhsparts.at(i).toInt(&ok);\n if (ok) {\n \/\/ both toInt succeeded\n if (a == b)\n continue;\n return a > b;\n } else {\n \/\/ compare as strings;\n if (lhsparts.at(i) == rhsparts.at(i))\n continue;\n return lhsparts.at(i) > rhsparts.at(i);\n }\n }\n\n \/\/ they compared strictly equally so far\n \/\/ lhs cannot be less than rhs\n return true;\n}\n#endif\n\nstatic QStringList findAllLibVlc()\n{\n QStringList paths;\n#if defined(Q_OS_UNIX)\n paths = QString::fromLatin1(qgetenv(\"LD_LIBRARY_PATH\"))\n .split(QLatin1Char(':'), QString::SkipEmptyParts);\n paths << QLatin1String(PHONON_LIB_INSTALL_DIR) << QLatin1String(\"\/usr\/lib\") << QLatin1String(\"\/usr\/local\/lib\");\n\n QStringList foundVlcs;\n foreach (const QString &path, paths) {\n QDir dir = QDir(path);\n QStringList entryList = dir.entryList(QStringList() << QLatin1String(\"libvlc.*\"), QDir::Files);\n\n qSort(entryList.begin(), entryList.end(), libGreaterThan);\n foreach (const QString &entry, entryList)\n foundVlcs << path + QLatin1Char('\/') + entry;\n }\n\n return foundVlcs;\n#elif defined(Q_OS_WIN)\n \/\/ Read VLC version and installation directory from Windows registry\n QSettings settings(QSettings::SystemScope, \"VideoLAN\", \"VLC\");\n QString vlcVersion = settings.value(\"Version\").toString();\n QString vlcInstallDir = settings.value(\"InstallDir\").toString();\n if (vlcVersion.startsWith(\"1.0\") && !vlcInstallDir.isEmpty()) {\n paths << vlcInstallDir + QLatin1Char('\\\\') + \"libvlc.dll\"; \n return paths;\n }else{\n \/\/If nothing is found in the registry try %PATH%\n QStringList searchPaths = QString::fromLatin1(qgetenv(\"PATH\"))\n .split(QLatin1Char(';'), QString::SkipEmptyParts);\n QStringList foundVlcs;\n foreach (const QString &sp, searchPaths) {\n QDir dir = QDir(sp);\n QStringList entryList = dir.entryList(QStringList() << QLatin1String(\"libvlc.dll\"), QDir::Files);\n foreach (const QString &entry, entryList)\n foundVlcs << sp + QLatin1Char('\\\\') + entry;\n }\n paths<setFileName(path);\n\n if (!vlcLibrary->resolve(\"libvlc_exception_init\")) {\/\/\"libvlc_exception_init\" not contained in 1.1+\n return path;\n } else {\n qDebug(\"Cannot resolve the symbol or load VLC library\");\n }\n qWarning() << vlcLibrary->errorString();\n }\n\n vlcUnload();\n\n return QString();\n}\n\nvoid vlcUnload()\n{\n vlcLibrary->unload();\n delete vlcLibrary;\n vlcLibrary = 0;\n}\n\n}\n} \/\/ Namespace Phonon::VLC\n<|endoftext|>"} {"text":"\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include \n\n#include \"tensorflow\/lite\/c\/builtin_op_data.h\"\n#include \"tensorflow\/lite\/c\/common.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/optimized\/optimized_ops.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/reference\/reference_ops.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/tensor.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/tensor_ctypes.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/types.h\"\n#include \"tensorflow\/lite\/kernels\/kernel_util.h\"\n\nnamespace tflite {\nnamespace ops {\nnamespace builtin {\nnamespace split {\n\nstruct OpContext {\n OpContext(TfLiteContext* context, TfLiteNode* node) {\n params = reinterpret_cast(node->builtin_data);\n axis = GetInput(context, node, 0);\n input = GetInput(context, node, 1);\n }\n TfLiteSplitParams* params;\n const TfLiteTensor* axis;\n const TfLiteTensor* input;\n};\n\nTfLiteStatus UseDynamicOutputTensors(TfLiteContext* context, TfLiteNode* node) {\n for (int i = 0; i < NumOutputs(node); ++i) {\n TfLiteTensor* tensor;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, i, &tensor));\n SetTensorToDynamic(tensor);\n }\n return kTfLiteOk;\n}\n\nTfLiteStatus ResizeOutputTensors(TfLiteContext* context, TfLiteNode* node,\n const TfLiteTensor* axis,\n const TfLiteTensor* input, int num_splits) {\n int axis_value = GetTensorData(axis)[0];\n if (axis_value < 0) {\n axis_value += NumDimensions(input);\n }\n\n TF_LITE_ENSURE(context, axis_value >= 0);\n TF_LITE_ENSURE(context, axis_value < NumDimensions(input));\n\n const int input_size = SizeOfDimension(input, axis_value);\n TF_LITE_ENSURE_MSG(context, input_size % num_splits == 0,\n \"Not an even split\");\n const int slice_size = input_size \/ num_splits;\n\n for (int i = 0; i < NumOutputs(node); ++i) {\n TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input->dims);\n output_dims->data[axis_value] = slice_size;\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, i, &output));\n TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_dims));\n }\n\n return kTfLiteOk;\n}\n\nTfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n\n OpContext op_context(context, node);\n\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), op_context.params->num_splits);\n\n auto input_type = op_context.input->type;\n TF_LITE_ENSURE(context,\n input_type == kTfLiteFloat32 || input_type == kTfLiteUInt8 ||\n input_type == kTfLiteInt8 || input_type == kTfLiteInt16 ||\n input_type == kTfLiteInt32);\n for (int i = 0; i < NumOutputs(node); ++i) {\n TfLiteTensor* tensor;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, i, &tensor));\n tensor->type = input_type;\n }\n\n \/\/ If we know the contents of the 'axis' tensor, resize all outputs.\n \/\/ Otherwise, wait until Eval().\n if (IsConstantTensor(op_context.axis)) {\n return ResizeOutputTensors(context, node, op_context.axis, op_context.input,\n op_context.params->num_splits);\n } else {\n return UseDynamicOutputTensors(context, node);\n }\n}\n\nTfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n OpContext op_context(context, node);\n\n \/\/ When the 'axis' tensor is non-const we can't resize output tensors in\n \/\/ Prepare(), and we have to do it now.\n if (!IsConstantTensor(op_context.axis)) {\n TF_LITE_ENSURE_OK(\n context,\n ResizeOutputTensors(context, node, op_context.axis, op_context.input,\n op_context.params->num_splits));\n }\n\n int axis_value = GetTensorData(op_context.axis)[0];\n if (axis_value < 0) {\n axis_value += NumDimensions(op_context.input);\n }\n\n TF_LITE_ENSURE(context, axis_value >= 0);\n TF_LITE_ENSURE(context, axis_value < NumDimensions(op_context.input));\n\n \/\/ TODO(b\/173221795): Our usage of VectorOfTensors could be optimized by\n \/\/ calculating it in Prepare, unless we defer shape calculation.\n \/\/ We can improve the optimized_ops version to handle other\n \/\/ cases too.\n#define TF_LITE_SPLIT(scalar) \\\n VectorOfTensors all_outputs(*context, *node->outputs); \\\n tflite::SplitParams op_params; \\\n op_params.num_split = NumOutputs(node); \\\n op_params.axis = axis_value; \\\n reference_ops::Split(op_params, GetTensorShape(op_context.input), \\\n GetTensorData(op_context.input), \\\n all_outputs.shapes(), all_outputs.data());\n\n switch (op_context.input->type) {\n case kTfLiteFloat32: {\n TF_LITE_SPLIT(float);\n break;\n }\n case kTfLiteUInt8: {\n TF_LITE_SPLIT(uint8_t);\n break;\n }\n case kTfLiteInt8: {\n TF_LITE_SPLIT(int8_t);\n break;\n }\n case kTfLiteInt16: {\n TF_LITE_SPLIT(int16_t);\n break;\n }\n case kTfLiteInt32: {\n TF_LITE_SPLIT(int32_t);\n break;\n }\n default:\n context->ReportError(context, \"Type %s currently not supported.\",\n TfLiteTypeGetName(op_context.input->type));\n return kTfLiteError;\n }\n#undef TF_LITE_SPLIT\n\n return kTfLiteOk;\n}\n\n} \/\/ namespace split\n\nTfLiteRegistration* Register_SPLIT() {\n static TfLiteRegistration r = {nullptr, nullptr, split::Prepare, split::Eval};\n return &r;\n}\n\n} \/\/ namespace builtin\n} \/\/ namespace ops\n} \/\/ namespace tflite\nPrevent division by 0\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include \n\n#include \"tensorflow\/lite\/c\/builtin_op_data.h\"\n#include \"tensorflow\/lite\/c\/common.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/optimized\/optimized_ops.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/reference\/reference_ops.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/tensor.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/tensor_ctypes.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/types.h\"\n#include \"tensorflow\/lite\/kernels\/kernel_util.h\"\n\nnamespace tflite {\nnamespace ops {\nnamespace builtin {\nnamespace split {\n\nstruct OpContext {\n OpContext(TfLiteContext* context, TfLiteNode* node) {\n params = reinterpret_cast(node->builtin_data);\n axis = GetInput(context, node, 0);\n input = GetInput(context, node, 1);\n }\n TfLiteSplitParams* params;\n const TfLiteTensor* axis;\n const TfLiteTensor* input;\n};\n\nTfLiteStatus UseDynamicOutputTensors(TfLiteContext* context, TfLiteNode* node) {\n for (int i = 0; i < NumOutputs(node); ++i) {\n TfLiteTensor* tensor;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, i, &tensor));\n SetTensorToDynamic(tensor);\n }\n return kTfLiteOk;\n}\n\nTfLiteStatus ResizeOutputTensors(TfLiteContext* context, TfLiteNode* node,\n const TfLiteTensor* axis,\n const TfLiteTensor* input, int num_splits) {\n int axis_value = GetTensorData(axis)[0];\n if (axis_value < 0) {\n axis_value += NumDimensions(input);\n }\n\n TF_LITE_ENSURE(context, axis_value >= 0);\n TF_LITE_ENSURE(context, axis_value < NumDimensions(input));\n\n const int input_size = SizeOfDimension(input, axis_value);\n TF_LITE_ENSURE(context, num_splits != 0);\n TF_LITE_ENSURE_MSG(context, input_size % num_splits == 0,\n \"Not an even split\");\n const int slice_size = input_size \/ num_splits;\n\n for (int i = 0; i < NumOutputs(node); ++i) {\n TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input->dims);\n output_dims->data[axis_value] = slice_size;\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, i, &output));\n TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_dims));\n }\n\n return kTfLiteOk;\n}\n\nTfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n\n OpContext op_context(context, node);\n\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), op_context.params->num_splits);\n\n auto input_type = op_context.input->type;\n TF_LITE_ENSURE(context,\n input_type == kTfLiteFloat32 || input_type == kTfLiteUInt8 ||\n input_type == kTfLiteInt8 || input_type == kTfLiteInt16 ||\n input_type == kTfLiteInt32);\n for (int i = 0; i < NumOutputs(node); ++i) {\n TfLiteTensor* tensor;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, i, &tensor));\n tensor->type = input_type;\n }\n\n \/\/ If we know the contents of the 'axis' tensor, resize all outputs.\n \/\/ Otherwise, wait until Eval().\n if (IsConstantTensor(op_context.axis)) {\n return ResizeOutputTensors(context, node, op_context.axis, op_context.input,\n op_context.params->num_splits);\n } else {\n return UseDynamicOutputTensors(context, node);\n }\n}\n\nTfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n OpContext op_context(context, node);\n\n \/\/ When the 'axis' tensor is non-const we can't resize output tensors in\n \/\/ Prepare(), and we have to do it now.\n if (!IsConstantTensor(op_context.axis)) {\n TF_LITE_ENSURE_OK(\n context,\n ResizeOutputTensors(context, node, op_context.axis, op_context.input,\n op_context.params->num_splits));\n }\n\n int axis_value = GetTensorData(op_context.axis)[0];\n if (axis_value < 0) {\n axis_value += NumDimensions(op_context.input);\n }\n\n TF_LITE_ENSURE(context, axis_value >= 0);\n TF_LITE_ENSURE(context, axis_value < NumDimensions(op_context.input));\n\n \/\/ TODO(b\/173221795): Our usage of VectorOfTensors could be optimized by\n \/\/ calculating it in Prepare, unless we defer shape calculation.\n \/\/ We can improve the optimized_ops version to handle other\n \/\/ cases too.\n#define TF_LITE_SPLIT(scalar) \\\n VectorOfTensors all_outputs(*context, *node->outputs); \\\n tflite::SplitParams op_params; \\\n op_params.num_split = NumOutputs(node); \\\n op_params.axis = axis_value; \\\n reference_ops::Split(op_params, GetTensorShape(op_context.input), \\\n GetTensorData(op_context.input), \\\n all_outputs.shapes(), all_outputs.data());\n\n switch (op_context.input->type) {\n case kTfLiteFloat32: {\n TF_LITE_SPLIT(float);\n break;\n }\n case kTfLiteUInt8: {\n TF_LITE_SPLIT(uint8_t);\n break;\n }\n case kTfLiteInt8: {\n TF_LITE_SPLIT(int8_t);\n break;\n }\n case kTfLiteInt16: {\n TF_LITE_SPLIT(int16_t);\n break;\n }\n case kTfLiteInt32: {\n TF_LITE_SPLIT(int32_t);\n break;\n }\n default:\n context->ReportError(context, \"Type %s currently not supported.\",\n TfLiteTypeGetName(op_context.input->type));\n return kTfLiteError;\n }\n#undef TF_LITE_SPLIT\n\n return kTfLiteOk;\n}\n\n} \/\/ namespace split\n\nTfLiteRegistration* Register_SPLIT() {\n static TfLiteRegistration r = {nullptr, nullptr, split::Prepare, split::Eval};\n return &r;\n}\n\n} \/\/ namespace builtin\n} \/\/ namespace ops\n} \/\/ namespace tflite\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n **\/\n\n#include \"modules\/planning\/tasks\/traffic_decider\/traffic_decider.h\"\n\n#include \"modules\/common\/configs\/vehicle_config_helper.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n\nnamespace apollo {\nnamespace planning {\nusing apollo::common::Status;\n\nTrafficDecider::TrafficDecider(const std::string &name) : Task(name) {}\n\nPathObstacle *TrafficDecider::CreateDestinationObstacle() {\n \/\/ set destination point\n const auto &routing_response = frame_->routing_response();\n if (!routing_response.routing_request().has_end()) {\n ADEBUG << \"routing_request has no end\";\n return nullptr;\n }\n common::math::Vec2d destination;\n destination.set_x(routing_response.routing_request().end().pose().x());\n destination.set_y(routing_response.routing_request().end().pose().y());\n\n \/\/ check if destination point is in planning range\n common::SLPoint destination_sl;\n const auto &reference_line = reference_line_info_->reference_line();\n reference_line.get_point_in_frenet_frame(destination, &destination_sl);\n double destination_s = destination_sl.s();\n if (destination_s < 0 || destination_s > reference_line.length()) {\n AINFO << \"destination(s[:\" << destination_sl.s()\n << \"]) out of planning range. Skip\";\n return nullptr;\n }\n\n \/\/ adjust destination based on adc_front_s\n common::SLPoint adc_sl;\n auto &adc_position = common::VehicleState::instance()->pose().position();\n reference_line.get_point_in_frenet_frame({adc_position.x(), adc_position.y()},\n &adc_sl);\n const auto &vehicle_param =\n common::VehicleConfigHelper::instance()->GetConfig().vehicle_param();\n double adc_front_s = adc_sl.s() + vehicle_param.front_edge_to_center();\n if (destination_sl.s() <= adc_front_s) {\n destination_s = adc_front_s + FLAGS_destination_adjust_distance_buffer;\n }\n\n const std::string id =\n FLAGS_destination_obstacle_id + \"_\" + reference_line_info_->Id();\n std::unique_ptr obstacle_ptr =\n reference_line_info_->CreateVirtualObstacle(\n id, destination_s, FLAGS_virtual_stop_wall_length,\n FLAGS_virtual_stop_wall_width, FLAGS_virtual_stop_wall_height);\n const auto *obstacle = obstacle_ptr.get();\n if (!frame_->AddObstacle(std::move(obstacle_ptr))) {\n AERROR << \"Failed to add destination obstacle: \" << id;\n return nullptr;\n }\n auto *ptr = reference_line_info_->AddObstacle(obstacle);\n if (!ptr) {\n AERROR << \"Failed to add destination obstacle: \" << id << \"'s projection\";\n return nullptr;\n }\n return ptr;\n}\n\napollo::common::Status TrafficDecider::Optimize(\n Frame *frame, ReferenceLineInfo *reference_line_info) {\n frame_ = frame;\n reference_line_info_ = reference_line_info;\n\n \/\/ 1. add destination stop\n if (!MakeDestinationStopDecision()) {\n AINFO << \"There is no destination stop\";\n } else {\n AINFO << \"destination is created\";\n }\n return Status::OK();\n}\n\nbool TrafficDecider::MakeDestinationStopDecision() {\n auto *path_obstacle = CreateDestinationObstacle();\n if (!path_obstacle) {\n AINFO << \"The path obstacle is not found\";\n return false;\n }\n const auto &obstacle = path_obstacle->Obstacle();\n const auto &reference_line = reference_line_info_->reference_line();\n\n \/\/ check stop_posision on reference line\n auto stop_position = obstacle->Perception().position();\n common::SLPoint stop_line_sl;\n reference_line.get_point_in_frenet_frame(\n {stop_position.x(), stop_position.x()}, &stop_line_sl);\n if (!reference_line.is_on_road(stop_line_sl)) {\n return false;\n }\n\n \/\/ check stop_line_s vs adc_s. stop_line_s must be ahead of adc_front_s\n common::SLPoint adc_sl;\n auto &adc_position = common::VehicleState::instance()->pose().position();\n reference_line.get_point_in_frenet_frame({adc_position.x(), adc_position.y()},\n &adc_sl);\n const auto &vehicle_param =\n common::VehicleConfigHelper::instance()->GetConfig().vehicle_param();\n double adc_front_s = adc_sl.s() + vehicle_param.front_edge_to_center();\n if (stop_line_sl.s() <= adc_front_s) {\n ADEBUG << \"skip: object:\" << obstacle->Id() << \" fence route_s[\"\n << stop_line_sl.s() << \"] behind adc_front_s[\" << adc_front_s << \"]\";\n return false;\n }\n\n ObjectDecisionType object_stop;\n ObjectStop *object_stop_ptr = object_stop.mutable_stop();\n object_stop_ptr->set_distance_s(FLAGS_stop_line_min_distance);\n object_stop_ptr->set_reason_code(StopReasonCode::STOP_REASON_DESTINATION);\n\n auto stop_ref_point =\n reference_line.get_reference_point(stop_position.x(), stop_position.y());\n object_stop_ptr->mutable_stop_point()->set_x(stop_ref_point.x());\n object_stop_ptr->mutable_stop_point()->set_y(stop_ref_point.y());\n object_stop_ptr->set_stop_heading(stop_ref_point.heading());\n\n reference_line_info_->path_decision()->AddLongitudinalDecision(\n \"Destination\", obstacle->Id(), object_stop);\n\n return true;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\nfix a bug in Destination Stop\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n **\/\n\n#include \"modules\/planning\/tasks\/traffic_decider\/traffic_decider.h\"\n\n#include \"modules\/common\/configs\/vehicle_config_helper.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n\nnamespace apollo {\nnamespace planning {\nusing apollo::common::Status;\n\nTrafficDecider::TrafficDecider(const std::string &name) : Task(name) {}\n\nPathObstacle *TrafficDecider::CreateDestinationObstacle() {\n \/\/ set destination point\n const auto &routing_response = frame_->routing_response();\n if (!routing_response.routing_request().has_end()) {\n ADEBUG << \"routing_request has no end\";\n return nullptr;\n }\n common::math::Vec2d destination;\n destination.set_x(routing_response.routing_request().end().pose().x());\n destination.set_y(routing_response.routing_request().end().pose().y());\n\n \/\/ check if destination point is in planning range\n common::SLPoint destination_sl;\n const auto &reference_line = reference_line_info_->reference_line();\n reference_line.get_point_in_frenet_frame(destination, &destination_sl);\n double destination_s = destination_sl.s();\n if (destination_s < 0 || destination_s > reference_line.length()) {\n AINFO << \"destination(s[:\" << destination_sl.s()\n << \"]) out of planning range. Skip\";\n return nullptr;\n }\n\n \/\/ adjust destination based on adc_front_s\n common::SLPoint adc_sl;\n auto &adc_position = common::VehicleState::instance()->pose().position();\n reference_line.get_point_in_frenet_frame({adc_position.x(), adc_position.y()},\n &adc_sl);\n const auto &vehicle_param =\n common::VehicleConfigHelper::instance()->GetConfig().vehicle_param();\n double adc_front_s = adc_sl.s() + vehicle_param.front_edge_to_center();\n if (destination_sl.s() <= adc_front_s) {\n destination_s = adc_front_s + FLAGS_destination_adjust_distance_buffer;\n }\n\n const std::string id =\n FLAGS_destination_obstacle_id + \"_\" + reference_line_info_->Id();\n std::unique_ptr obstacle_ptr =\n reference_line_info_->CreateVirtualObstacle(\n id, destination_s, FLAGS_virtual_stop_wall_length,\n FLAGS_virtual_stop_wall_width, FLAGS_virtual_stop_wall_height);\n const auto *obstacle = obstacle_ptr.get();\n if (!frame_->AddObstacle(std::move(obstacle_ptr))) {\n AERROR << \"Failed to add destination obstacle: \" << id;\n return nullptr;\n }\n auto *ptr = reference_line_info_->AddObstacle(obstacle);\n if (!ptr) {\n AERROR << \"Failed to add destination obstacle: \" << id << \"'s projection\";\n return nullptr;\n }\n return ptr;\n}\n\napollo::common::Status TrafficDecider::Optimize(\n Frame *frame, ReferenceLineInfo *reference_line_info) {\n frame_ = frame;\n reference_line_info_ = reference_line_info;\n\n \/\/ 1. add destination stop\n if (!MakeDestinationStopDecision()) {\n AINFO << \"There is no destination stop\";\n } else {\n AINFO << \"destination is created\";\n }\n return Status::OK();\n}\n\nbool TrafficDecider::MakeDestinationStopDecision() {\n auto *path_obstacle = CreateDestinationObstacle();\n if (!path_obstacle) {\n AINFO << \"The path obstacle is not found\";\n return false;\n }\n const auto &obstacle = path_obstacle->Obstacle();\n const auto &reference_line = reference_line_info_->reference_line();\n\n \/\/ check stop_posision on reference line\n auto stop_position = obstacle->Perception().position();\n common::SLPoint stop_line_sl;\n reference_line.get_point_in_frenet_frame(\n {stop_position.x(), stop_position.y()}, &stop_line_sl);\n if (!reference_line.is_on_road(stop_line_sl)) {\n return false;\n }\n\n \/\/ check stop_line_s vs adc_s. stop_line_s must be ahead of adc_front_s\n common::SLPoint adc_sl;\n auto &adc_position = common::VehicleState::instance()->pose().position();\n reference_line.get_point_in_frenet_frame({adc_position.x(), adc_position.y()},\n &adc_sl);\n const auto &vehicle_param =\n common::VehicleConfigHelper::instance()->GetConfig().vehicle_param();\n double adc_front_s = adc_sl.s() + vehicle_param.front_edge_to_center();\n if (stop_line_sl.s() <= adc_front_s) {\n ADEBUG << \"skip: object:\" << obstacle->Id() << \" fence route_s[\"\n << stop_line_sl.s() << \"] behind adc_front_s[\" << adc_front_s << \"]\";\n return false;\n }\n\n ObjectDecisionType object_stop;\n ObjectStop *object_stop_ptr = object_stop.mutable_stop();\n object_stop_ptr->set_distance_s(FLAGS_stop_line_min_distance);\n object_stop_ptr->set_reason_code(StopReasonCode::STOP_REASON_DESTINATION);\n\n auto stop_ref_point =\n reference_line.get_reference_point(stop_position.x(), stop_position.y());\n object_stop_ptr->mutable_stop_point()->set_x(stop_ref_point.x());\n object_stop_ptr->mutable_stop_point()->set_y(stop_ref_point.y());\n object_stop_ptr->set_stop_heading(stop_ref_point.heading());\n\n reference_line_info_->path_decision()->AddLongitudinalDecision(\n \"Destination\", obstacle->Id(), object_stop);\n\n return true;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"spatial_resampler.h\"\n\n\nnamespace webrtc {\n\nVPMSimpleSpatialResampler::VPMSimpleSpatialResampler()\n:\n_resamplingMode(kFastRescaling),\n_targetWidth(0),\n_targetHeight(0),\n_scaler()\n{\n}\n\nVPMSimpleSpatialResampler::~VPMSimpleSpatialResampler()\n{\n \/\/\n}\n\n\nWebRtc_Word32\nVPMSimpleSpatialResampler::SetTargetFrameSize(WebRtc_Word32 width,\n WebRtc_Word32 height)\n{\n if (_resamplingMode == kNoRescaling) {\n return VPM_OK;\n }\n\n if (width < 1 || height < 1) {\n return VPM_PARAMETER_ERROR;\n }\n\n _targetWidth = width;\n _targetHeight = height;\n\n return VPM_OK;\n}\n\nvoid\nVPMSimpleSpatialResampler::SetInputFrameResampleMode(VideoFrameResampling\n resamplingMode)\n{\n _resamplingMode = resamplingMode;\n}\n\nvoid\nVPMSimpleSpatialResampler::Reset()\n{\n _resamplingMode = kFastRescaling;\n _targetWidth = 0;\n _targetHeight = 0;\n}\n\nWebRtc_Word32\nVPMSimpleSpatialResampler::ResampleFrame(const I420VideoFrame& inFrame,\n I420VideoFrame* outFrame)\n{\n if (_resamplingMode == kNoRescaling)\n return outFrame->CopyFrame(inFrame);\n \/\/ Check if re-sampling is needed\n if ((inFrame.width() == _targetWidth) &&\n (inFrame.height() == _targetHeight)) {\n return outFrame->CopyFrame(inFrame);\n }\n\n \/\/ Setting scaler\n \/\/ TODO(mikhal\/marpan): Should we allow for setting the filter mode in\n \/\/ _scale.Set() with |_resamplingMode|?\n int retVal = 0;\n retVal = _scaler.Set(inFrame.width(), inFrame.height(),\n _targetWidth, _targetHeight, kI420, kI420, kScaleBox);\n if (retVal < 0)\n return retVal;\n\n \/\/ Setting time parameters to the output frame - all the rest will be\n \/\/ set by the scaler.\n outFrame->set_timestamp(inFrame.timestamp());\n outFrame->set_render_time_ms(inFrame.render_time_ms());\n\n retVal = _scaler.Scale(inFrame, outFrame);\n if (retVal == 0)\n return VPM_OK;\n else\n return VPM_SCALE_ERROR;\n}\n\nWebRtc_Word32\nVPMSimpleSpatialResampler::TargetHeight()\n{\n return _targetHeight;\n}\n\nWebRtc_Word32\nVPMSimpleSpatialResampler::TargetWidth()\n{\n return _targetWidth;\n}\n\nbool\nVPMSimpleSpatialResampler::ApplyResample(WebRtc_Word32 width,\n WebRtc_Word32 height)\n{\n if ((width == _targetWidth && height == _targetHeight) ||\n _resamplingMode == kNoRescaling)\n return false;\n else\n return true;\n}\n\n} \/\/namespace\nFix a bug in spatial_resampler where we should set the timestamp after Scale.\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"spatial_resampler.h\"\n\n\nnamespace webrtc {\n\nVPMSimpleSpatialResampler::VPMSimpleSpatialResampler()\n:\n_resamplingMode(kFastRescaling),\n_targetWidth(0),\n_targetHeight(0),\n_scaler()\n{\n}\n\nVPMSimpleSpatialResampler::~VPMSimpleSpatialResampler()\n{\n \/\/\n}\n\n\nWebRtc_Word32\nVPMSimpleSpatialResampler::SetTargetFrameSize(WebRtc_Word32 width,\n WebRtc_Word32 height)\n{\n if (_resamplingMode == kNoRescaling) {\n return VPM_OK;\n }\n\n if (width < 1 || height < 1) {\n return VPM_PARAMETER_ERROR;\n }\n\n _targetWidth = width;\n _targetHeight = height;\n\n return VPM_OK;\n}\n\nvoid\nVPMSimpleSpatialResampler::SetInputFrameResampleMode(VideoFrameResampling\n resamplingMode)\n{\n _resamplingMode = resamplingMode;\n}\n\nvoid\nVPMSimpleSpatialResampler::Reset()\n{\n _resamplingMode = kFastRescaling;\n _targetWidth = 0;\n _targetHeight = 0;\n}\n\nWebRtc_Word32\nVPMSimpleSpatialResampler::ResampleFrame(const I420VideoFrame& inFrame,\n I420VideoFrame* outFrame)\n{\n if (_resamplingMode == kNoRescaling)\n return outFrame->CopyFrame(inFrame);\n \/\/ Check if re-sampling is needed\n if ((inFrame.width() == _targetWidth) &&\n (inFrame.height() == _targetHeight)) {\n return outFrame->CopyFrame(inFrame);\n }\n\n \/\/ Setting scaler\n \/\/ TODO(mikhal\/marpan): Should we allow for setting the filter mode in\n \/\/ _scale.Set() with |_resamplingMode|?\n int retVal = 0;\n retVal = _scaler.Set(inFrame.width(), inFrame.height(),\n _targetWidth, _targetHeight, kI420, kI420, kScaleBox);\n if (retVal < 0)\n return retVal;\n\n retVal = _scaler.Scale(inFrame, outFrame);\n\n \/\/ Setting time parameters to the output frame.\n \/\/ Timestamp will be reset in Scale call above, so we should set it after.\n outFrame->set_timestamp(inFrame.timestamp());\n outFrame->set_render_time_ms(inFrame.render_time_ms());\n\n if (retVal == 0)\n return VPM_OK;\n else\n return VPM_SCALE_ERROR;\n}\n\nWebRtc_Word32\nVPMSimpleSpatialResampler::TargetHeight()\n{\n return _targetHeight;\n}\n\nWebRtc_Word32\nVPMSimpleSpatialResampler::TargetWidth()\n{\n return _targetWidth;\n}\n\nbool\nVPMSimpleSpatialResampler::ApplyResample(WebRtc_Word32 width,\n WebRtc_Word32 height)\n{\n if ((width == _targetWidth && height == _targetHeight) ||\n _resamplingMode == kNoRescaling)\n return false;\n else\n return true;\n}\n\n} \/\/namespace\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/..\/Foundation\/Characters\/String_Constant.h\"\n#include \"..\/..\/..\/Foundation\/Characters\/String2Float.h\"\n#include \"..\/..\/..\/Foundation\/Containers\/Mapping.h\"\n#include \"..\/..\/..\/Foundation\/Containers\/Sequence.h\"\n#include \"..\/..\/..\/Foundation\/Containers\/Set.h\"\n#include \"..\/..\/..\/Foundation\/Debug\/Assertions.h\"\n#include \"..\/..\/..\/Foundation\/Debug\/Trace.h\"\n#include \"..\/..\/..\/Foundation\/DataExchange\/CharacterDelimitedLines\/Reader.h\"\n#include \"..\/..\/..\/Foundation\/IO\/FileSystem\/BinaryFileInputStream.h\"\n#include \"..\/..\/..\/Foundation\/Streams\/BinaryInputStream.h\"\n\n#include \"..\/CommonMeasurementTypes.h\"\n\n#include \"Memory.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::DataExchange;\nusing namespace Stroika::Foundation::Memory;\n\nusing namespace Stroika::Frameworks;\nusing namespace Stroika::Frameworks::SystemPerformance;\n\n\nusing Characters::Character;\nusing Characters::String_Constant;\nusing Containers::Mapping;\nusing Containers::Sequence;\nusing Containers::Set;\n\n\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\n\n\nnamespace {\n template \n void ReadX_ (Optional* result, const String& n, const Sequence& line)\n {\n if (line.size () >= 3 and line[0] == n) {\n String unit = line[2];\n double factor = (unit == L\"kB\") ? 1024 : 1;\n *result = static_cast (round (Characters::String2Float (line[1]) * factor));\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"Set %s = %ld\", n.c_str (), static_cast (**result));\n#endif\n }\n }\n Instruments::Memory::Info capture_ ()\n {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx (SDKSTR (\"Instruments::Memory::Info capture_\"));\n#endif\n Instruments::Memory::Info result;\n#if qPlatform_POSIX\n DataExchange::CharacterDelimitedLines::Reader reader {{ ':', ' ', '\\t' }};\n const String_Constant kProcMemInfoFileName_ { L\"\/proc\/meminfo\" };\n \/\/const String_Constant kProcMemInfoFileName_ { L\"c:\\\\Sandbox\\\\VMSharedFolder\\\\meminfo\" };\n for (Sequence line : reader.ReadAs2DArray (IO::FileSystem::BinaryFileInputStream (kProcMemInfoFileName_))) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s\", line.size(), line.empty () ? L\"\" : line[0].c_str ());\n#endif\n ReadX_ (&result.fFreePhysicalMemory, String_Constant (L\"MemFree\"), line);\n ReadX_ (&result.fTotalVirtualMemory, String_Constant (L\"VmallocTotal\"), line);\n ReadX_ (&result.fUsedVirtualMemory, String_Constant (L\"VmallocUsed\"), line);\n ReadX_ (&result.fLargestAvailableVirtualChunk, String_Constant (L\"VmallocChunk\"), line);\n }\n#elif qPlatform_Windows\n#endif\n return result;\n }\n}\n\n\n\n\nconst MeasurementType Instruments::Memory::kSystemMemoryMeasurement = MeasurementType (String_Constant (L\"System-Memory\"));\n\n\n\n\n\/*\n ********************************************************************************\n ******************** Instruments::Memory::GetObjectVariantMapper ***************\n ********************************************************************************\n *\/\nObjectVariantMapper Instruments::Memory::GetObjectVariantMapper ()\n{\n using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo;\n ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper {\n ObjectVariantMapper mapper;\n mapper.AddCommonType> ();\n mapper.AddCommonType> ();\n DISABLE_COMPILER_CLANG_WARNING_START(\"clang diagnostic ignored \\\"-Winvalid-offsetof\\\"\"); \/\/ Really probably an issue, but not to debug here -- LGP 2014-01-04\n DISABLE_COMPILER_GCC_WARNING_START(\"GCC diagnostic ignored \\\"-Winvalid-offsetof\\\"\"); \/\/ Really probably an issue, but not to debug here -- LGP 2014-01-04\n mapper.AddClass (initializer_list {\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fFreePhysicalMemory), String_Constant (L\"Free-Physical-Memory\") },\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fTotalVirtualMemory), String_Constant (L\"Total-Virtual-Memory\") },\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fUsedVirtualMemory), String_Constant (L\"UsedV-irtual-Memory\") },\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fLargestAvailableVirtualChunk), String_Constant (L\"Largest-Available-Virtual-Chunk\") },\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsSinceBoot), String_Constant (L\"Major-Page-Faults-Since-Boot\") },\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsSinceBoot), String_Constant (L\"Minor-Page-Faults-Since-Boot\") },\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsPerSecond), String_Constant (L\"Major-Page-Faults-Per-Second\") },\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsPerSecond), String_Constant (L\"Minor-Page-Faults-Per-Second\") },\n });\n DISABLE_COMPILER_GCC_WARNING_END(\"GCC diagnostic ignored \\\"-Winvalid-offsetof\\\"\");\n DISABLE_COMPILER_CLANG_WARNING_END(\"clang diagnostic ignored \\\"-Winvalid-offsetof\\\"\");\n return mapper;\n } ();\n return sMapper_;\n}\n\n\n\n\n\/*\n ********************************************************************************\n ******************* Instruments::Memory::GetInstrument *************************\n ********************************************************************************\n *\/\nInstrument SystemPerformance::Instruments::Memory::GetInstrument ()\n{\n static Instrument kInstrument_ = Instrument (\n InstrumentNameType (String_Constant (L\"Memory\")),\n [] () -> MeasurementSet {\n MeasurementSet results;\n DateTime before = DateTime::Now ();\n Instruments::Memory::Info rawMeasurement = capture_ ();\n results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());\n Measurement m;\n m.fValue = GetObjectVariantMapper ().FromObject (rawMeasurement);\n m.fType = kSystemMemoryMeasurement;\n results.fMeasurements.Add (m);\n return results;\n },\n {kMemoryUsage}\n );\n return kInstrument_;\n}\nfixed problem reading \/proc\/meminfo - must avoid SEEK! - use trick of BufferedBinaryInputStream for now to avoid, but must fix better\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/..\/Foundation\/Characters\/String_Constant.h\"\n#include \"..\/..\/..\/Foundation\/Characters\/String2Float.h\"\n#include \"..\/..\/..\/Foundation\/Containers\/Mapping.h\"\n#include \"..\/..\/..\/Foundation\/Containers\/Sequence.h\"\n#include \"..\/..\/..\/Foundation\/Containers\/Set.h\"\n#include \"..\/..\/..\/Foundation\/Debug\/Assertions.h\"\n#include \"..\/..\/..\/Foundation\/Debug\/Trace.h\"\n#include \"..\/..\/..\/Foundation\/DataExchange\/CharacterDelimitedLines\/Reader.h\"\n#include \"..\/..\/..\/Foundation\/IO\/FileSystem\/BinaryFileInputStream.h\"\n#include \"..\/..\/..\/Foundation\/Streams\/BinaryInputStream.h\"\n#include \"..\/..\/..\/Foundation\/Streams\/BufferedBinaryInputStream.h\"\n\n#include \"..\/CommonMeasurementTypes.h\"\n\n#include \"Memory.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::DataExchange;\nusing namespace Stroika::Foundation::Memory;\n\nusing namespace Stroika::Frameworks;\nusing namespace Stroika::Frameworks::SystemPerformance;\n\n\nusing Characters::Character;\nusing Characters::String_Constant;\nusing Containers::Mapping;\nusing Containers::Sequence;\nusing Containers::Set;\n\n\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\n\n\nnamespace {\n template \n void ReadX_ (Optional* result, const String& n, const Sequence& line)\n {\n if (line.size () >= 3 and line[0] == n) {\n String unit = line[2];\n double factor = (unit == L\"kB\") ? 1024 : 1;\n *result = static_cast (round (Characters::String2Float (line[1]) * factor));\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"Set %s = %ld\", n.c_str (), static_cast (**result));\n#endif\n }\n }\n Instruments::Memory::Info capture_ ()\n {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx (SDKSTR (\"Instruments::Memory::Info capture_\"));\n#endif\n Instruments::Memory::Info result;\n#if qPlatform_POSIX\n DataExchange::CharacterDelimitedLines::Reader reader {{ ':', ' ', '\\t' }};\n const String_Constant kProcMemInfoFileName_ { L\"\/proc\/meminfo\" };\n \/\/const String_Constant kProcMemInfoFileName_ { L\"c:\\\\Sandbox\\\\VMSharedFolder\\\\meminfo\" };\n\n \/\/ @todo - NOTE - MUST use Streams::BufferedBinaryInputStream because otherwise code will SEEK. REAL fix is to add attributes to BinaryFileInputStream saying if seekable, and \/proc\/xx files are NOT\n\n for (Sequence line : reader.ReadAs2DArray (Streams::BufferedBinaryInputStream (IO::FileSystem::BinaryFileInputStream (kProcMemInfoFileName_)))) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s\", line.size(), line.empty () ? L\"\" : line[0].c_str ());\n#endif\n ReadX_ (&result.fFreePhysicalMemory, String_Constant (L\"MemFree\"), line);\n ReadX_ (&result.fTotalVirtualMemory, String_Constant (L\"VmallocTotal\"), line);\n ReadX_ (&result.fUsedVirtualMemory, String_Constant (L\"VmallocUsed\"), line);\n ReadX_ (&result.fLargestAvailableVirtualChunk, String_Constant (L\"VmallocChunk\"), line);\n }\n#elif qPlatform_Windows\n#endif\n return result;\n }\n}\n\n\n\n\nconst MeasurementType Instruments::Memory::kSystemMemoryMeasurement = MeasurementType (String_Constant (L\"System-Memory\"));\n\n\n\n\n\/*\n ********************************************************************************\n ******************** Instruments::Memory::GetObjectVariantMapper ***************\n ********************************************************************************\n *\/\nObjectVariantMapper Instruments::Memory::GetObjectVariantMapper ()\n{\n using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo;\n ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper {\n ObjectVariantMapper mapper;\n mapper.AddCommonType> ();\n mapper.AddCommonType> ();\n DISABLE_COMPILER_CLANG_WARNING_START(\"clang diagnostic ignored \\\"-Winvalid-offsetof\\\"\"); \/\/ Really probably an issue, but not to debug here -- LGP 2014-01-04\n DISABLE_COMPILER_GCC_WARNING_START(\"GCC diagnostic ignored \\\"-Winvalid-offsetof\\\"\"); \/\/ Really probably an issue, but not to debug here -- LGP 2014-01-04\n mapper.AddClass (initializer_list {\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fFreePhysicalMemory), String_Constant (L\"Free-Physical-Memory\") },\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fTotalVirtualMemory), String_Constant (L\"Total-Virtual-Memory\") },\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fUsedVirtualMemory), String_Constant (L\"UsedV-irtual-Memory\") },\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fLargestAvailableVirtualChunk), String_Constant (L\"Largest-Available-Virtual-Chunk\") },\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsSinceBoot), String_Constant (L\"Major-Page-Faults-Since-Boot\") },\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsSinceBoot), String_Constant (L\"Minor-Page-Faults-Since-Boot\") },\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsPerSecond), String_Constant (L\"Major-Page-Faults-Per-Second\") },\n { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsPerSecond), String_Constant (L\"Minor-Page-Faults-Per-Second\") },\n });\n DISABLE_COMPILER_GCC_WARNING_END(\"GCC diagnostic ignored \\\"-Winvalid-offsetof\\\"\");\n DISABLE_COMPILER_CLANG_WARNING_END(\"clang diagnostic ignored \\\"-Winvalid-offsetof\\\"\");\n return mapper;\n } ();\n return sMapper_;\n}\n\n\n\n\n\/*\n ********************************************************************************\n ******************* Instruments::Memory::GetInstrument *************************\n ********************************************************************************\n *\/\nInstrument SystemPerformance::Instruments::Memory::GetInstrument ()\n{\n static Instrument kInstrument_ = Instrument (\n InstrumentNameType (String_Constant (L\"Memory\")),\n [] () -> MeasurementSet {\n MeasurementSet results;\n DateTime before = DateTime::Now ();\n Instruments::Memory::Info rawMeasurement = capture_ ();\n results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());\n Measurement m;\n m.fValue = GetObjectVariantMapper ().FromObject (rawMeasurement);\n m.fType = kSystemMemoryMeasurement;\n results.fMeasurements.Add (m);\n return results;\n },\n {kMemoryUsage}\n );\n return kInstrument_;\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2009, The Barbarian Group\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"cinder\/Serial.h\"\n#include \"cinder\/Timer.h\"\n#include \"cinder\/Thread.h\"\n#include \"cinder\/Utilities.h\"\n\n#include \n#include \n#include \n\n#if defined( CINDER_MAC )\n\t#include \n\t#include \n\t#include \n\t#include \n#elif defined( CINDER_MSW )\n\t#include \n\t#pragma comment(lib, \"setupapi.lib\")\n#endif\n\n#include \nusing namespace std;\n\nnamespace cinder {\n\nbool\t\t\t\t\t\t\tSerial::sDevicesInited = false;\nstd::vector\t\tSerial::sDevices;\n\nSerial::Serial( const Serial::Device &device, int baudRate )\n\t: mObj( new Obj( device, baudRate ) )\n{\n}\n\nSerial::Obj::Obj( const Serial::Device &device, int baudRate )\n\t: mDevice( device )\n{\n#if defined( CINDER_MAC )\n\tmFd = open( ( \"\/dev\/\" + device.getName() ).c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK );\n\tif( mFd == -1 ) {\n\t\tthrow SerialExcOpenFailed();\n\t}\n\t\n\ttermios options;\n\ttcgetattr( mFd, &mSavedOptions );\n\toptions = mSavedOptions;\n\tmap baudToConstant;\n\tbaudToConstant[300] = B300;\n\tbaudToConstant[1200] = B1200;\n\tbaudToConstant[2400] = B2400;\n\tbaudToConstant[4800] = B4800;\n\tbaudToConstant[9600] = B9600;\t\t\t\n\tbaudToConstant[19200] = B19200;\n\tbaudToConstant[28800] = B28800;\n\tbaudToConstant[38400] = B38400;\n\tbaudToConstant[57600] = B57600;\n\tbaudToConstant[115200] = B115200;\n\tbaudToConstant[230400] = B230400;\t\n\t\n\tint rateConstant = B9600;\n\tif( baudToConstant.find( baudRate ) != baudToConstant.end() )\n\t\trateConstant = baudToConstant[baudRate];\n\t\n\t::cfsetispeed( &options, rateConstant );\n\t::cfsetospeed( &options, rateConstant );\n\t\n\toptions.c_cflag |= (CLOCAL | CREAD);\n\toptions.c_cflag &= ~PARENB;\n\toptions.c_cflag &= ~CSTOPB;\n\toptions.c_cflag &= ~CSIZE;\n\toptions.c_cflag |= CS8;\n\t::tcsetattr( mFd, TCSANOW, &options );\n#elif defined( CINDER_MSW )\n\tmDeviceHandle = ::CreateFileA( mDevice.getPath().c_str(), GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0 );\n\tif( mDeviceHandle == INVALID_HANDLE_VALUE ) {\n\t\tthrow SerialExcOpenFailed();\n\t}\n\t\n\t::COMMCONFIG config;\n\t::DWORD configSize = sizeof( ::COMMCONFIG );\n\t::GetCommConfig( mDeviceHandle, &config, &configSize );\n\t\n\tstring settingsStr = string(\"baud=\") + toString( baudRate ) + \" parity=N data=8 stop=1\";\n\tif( ! ::BuildCommDCBA( settingsStr.c_str(), &config.dcb ) ) {\n\t\tthrow SerialExcOpenFailed();\t\n\t}\t\n\t\n\tif( ! ::SetCommState( mDeviceHandle, &config.dcb ) ) {\n\t\tthrow SerialExcOpenFailed();\n\t}\n\t\n\t::GetCommTimeouts( mDeviceHandle, &mSavedTimeouts );\n\t::COMMTIMEOUTS timeOuts( mSavedTimeouts );\n\n\ttimeOuts.ReadIntervalTimeout = MAXDWORD;\n\ttimeOuts.ReadTotalTimeoutMultiplier = 0;\n\ttimeOuts.ReadTotalTimeoutConstant = 0;\n\t::SetCommTimeouts( mDeviceHandle, &timeOuts );\n#endif\n}\n\nSerial::Device Serial::findDeviceByName( const std::string &name, bool forceRefresh )\n{\n\tconst std::vector &devices = getDevices( forceRefresh );\n\tfor( std::vector::const_iterator deviceIt = devices.begin(); deviceIt != devices.end(); ++deviceIt ) {\n\t\tif( deviceIt->getName() == name )\n\t\t\treturn *deviceIt;\n\t}\n\t\n\treturn Serial::Device();\n}\n\nSerial::Device Serial::findDeviceByNameContains( const std::string &searchString, bool forceRefresh )\n{\n\tconst std::vector &devices = getDevices( forceRefresh );\n\tfor( std::vector::const_iterator deviceIt = devices.begin(); deviceIt != devices.end(); ++deviceIt ) {\n\t\tif( deviceIt->getName().find( searchString ) != std::string::npos )\n\t\t\treturn *deviceIt;\n\t}\n\t\n\treturn Serial::Device();\n}\n\t\nconst std::vector& Serial::getDevices( bool forceRefresh )\n{\n\tif( ( ! forceRefresh ) && ( sDevicesInited ) )\n\t\treturn sDevices;\n\n\tsDevices.clear();\n\n#if defined( CINDER_MAC )\t\n\t::DIR *dir;\n\t::dirent *entry;\n\tdir = ::opendir( \"\/dev\" );\n\n\tif( ! dir ) {\n\t\tthrow SerialExcDeviceEnumerationFailed();\n\t}\n\telse {\n\t\twhile( ( entry = ::readdir( dir ) ) != NULL ) {\n\t\t\tstd::string str( (char *)entry->d_name );\n\t\t\tif( ( str.substr( 0, 4 ) == \"tty.\" ) || ( str.substr( 0, 3 ) == \"cu.\" ) ) {\n\t\t\t\tsDevices.push_back( Serial::Device( str ) );\n\t\t\t}\n\t\t}\n\t}\n\t\n#elif defined( CINDER_MSW )\n\t::HDEVINFO devInfoSet;\n\t::DWORD devCount = 0;\n\t::SP_DEVINFO_DATA devInfo;\n\t::SP_DEVICE_INTERFACE_DATA devInterface;\n\tDWORD size = 0;\n\n\tdevInfoSet = ::SetupDiGetClassDevs( &GUID_SERENUM_BUS_ENUMERATOR, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE );\n\tif( devInfoSet == INVALID_HANDLE_VALUE )\n\t\tthrow SerialExcDeviceEnumerationFailed();\n\t\n\tdevInterface.cbSize = sizeof( ::SP_DEVICE_INTERFACE_DATA );\n\twhile( ::SetupDiEnumDeviceInterfaces( devInfoSet, 0, &GUID_SERENUM_BUS_ENUMERATOR, devCount++, &devInterface ) ) {\n\t\t\/\/ See how large a buffer we require for the device interface details\n\t\t::SetupDiGetDeviceInterfaceDetail( devInfoSet, &devInterface, 0, 0, &size, 0 );\n\t\tdevInfo.cbSize = sizeof( ::SP_DEVINFO_DATA );\n\t\tshared_ptr<::SP_DEVICE_INTERFACE_DETAIL_DATA> interfaceDetail( (::SP_DEVICE_INTERFACE_DETAIL_DATA*)calloc( 1, size ), free );\n\t\tif( interfaceDetail ) {\n\t\t\tinterfaceDetail->cbSize = sizeof( ::SP_DEVICE_INTERFACE_DETAIL_DATA );\n\t\t\tdevInfo.cbSize = sizeof( ::SP_DEVINFO_DATA );\n\t\t\tif( ! ::SetupDiGetDeviceInterfaceDetail( devInfoSet, &devInterface, interfaceDetail.get(), size, 0, &devInfo ) ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tchar friendlyName[2048];\n\t\t\tsize = sizeof( friendlyName );\n\t\t\tfriendlyName[0] = 0;\n\t\t\t::DWORD propertyDataType;\n\t\t\tif( ! ::SetupDiGetDeviceRegistryPropertyA( devInfoSet, &devInfo, SPDRP_FRIENDLYNAME, &propertyDataType, (LPBYTE)friendlyName, size, 0 ) ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tsDevices.push_back( Serial::Device( string( friendlyName ), toUtf8( interfaceDetail->DevicePath ) ) );\n\t\t}\n\t}\n\t\n\t::SetupDiDestroyDeviceInfoList(devInfoSet);\n\n#endif\n\n\tsDevicesInited = true;\n\treturn sDevices;\n}\n\nSerial::Obj::~Obj()\n{\n#if defined( CINDER_MAC )\n\t\/\/ restore the termios from before we opened the port\n\t::tcsetattr( mFd, TCSANOW, &mSavedOptions );\n\t::close( mFd );\n#elif defined( CINDER_MSW )\n\t::SetCommTimeouts( mDeviceHandle, &mSavedTimeouts );\n\t::CloseHandle( mDeviceHandle );\n#endif\n}\n\nconst Serial::Device& Serial::getDevice() const\n{\n\treturn mObj->mDevice;\n}\n\nvoid Serial::writeBytes( const void *data, size_t numBytes )\n{\n\tsize_t totalBytesWritten = 0;\n\t\n\twhile( totalBytesWritten < numBytes ) {\n#if defined( CINDER_MAC )\n\t\tint bytesWritten = ::write( mObj->mFd, data, numBytes - totalBytesWritten );\n\t\tif( ( bytesWritten == -1 ) && ( errno != EAGAIN ) )\n\t\t\tthrow SerialExcReadFailure();\t\n#elif defined( CINDER_MSW )\n\t\t::DWORD bytesWritten;\n\t\tif( ! ::WriteFile( mObj->mDeviceHandle, data, numBytes - totalBytesWritten, &bytesWritten, 0 ) )\n\t\t\tthrow SerialExcWriteFailure();\n#endif\n\t\ttotalBytesWritten += bytesWritten;\n\t}\n}\n\nvoid Serial::readBytes( void *data, size_t numBytes )\n{\n\tsize_t totalBytesRead = 0;\n\twhile( totalBytesRead < numBytes ) {\n#if defined( CINDER_MAC )\n\t\tint bytesRead = ::read( mObj->mFd, data, numBytes - totalBytesRead );\n\t\tif( ( bytesRead == -1 ) && ( errno != EAGAIN ) )\n\t\t\tthrow SerialExcReadFailure();\n#elif defined( CINDER_MSW )\n\t\t::DWORD bytesRead = 0;\n\t\tif( ! ::ReadFile( mObj->mDeviceHandle, data, numBytes - totalBytesRead, &bytesRead, 0 ) )\n\t\t\tthrow SerialExcReadFailure();\n#endif\n\t\ttotalBytesRead += bytesRead;\n\t\t\n\t\t\/\/ yield thread time to the system\n\t\tthis_thread::yield();\n\t}\n}\n\nsize_t Serial::readAvailableBytes( void *data, size_t maximumBytes )\n{\n#if defined( CINDER_MAC )\n\tint bytesRead = ::read( mObj->mFd, data, maximumBytes );\n#elif defined( CINDER_MSW )\n\t::DWORD bytesRead = 0;\n\tif( ! ::ReadFile( mObj->mDeviceHandle, data, maximumBytes, &bytesRead, 0 ) )\n\t\tthrow SerialExcReadFailure();\n#endif\n\n\tif( bytesRead < 0 )\n\t\tbytesRead = 0;\n\t\t\n\treturn (size_t)bytesRead;\n}\n\nvoid Serial::writeByte( uint8_t data )\n{\n\twriteBytes( &data, 1 );\n}\n\nuint8_t Serial::readByte()\n{\n\tuint8_t result;\n\treadBytes( &result, 1 );\n\treturn result;\n}\n\nstd::string Serial::readStringUntil( char token, size_t maxLength, double timeoutSeconds )\n{\n\tsize_t bufferSize = 1024, bufferOffset = 0;\n\tshared_ptr buffer( (char*)malloc( bufferSize ), free );\n\n\tbool useMaxLength = maxLength > 0;\n\tbool useTimer = timeoutSeconds > 0;\n\tTimer timer;\n\tif( useTimer )\n\t\ttimer.start();\n\n\tbool done = false;\n\twhile( ! done ) {\n\t\tchar v = readChar();\n\t\tbuffer.get()[bufferOffset++] = v;\n\t\tif( v == token ) {\n\t\t\tdone = true;\n\t\t}\n\t\telse if( useMaxLength && ( bufferOffset == maxLength ) ) {\n\t\t\tdone = true;\n\t\t}\n\t\telse if( useTimer && ( timer.getSeconds() > timeoutSeconds ) )\n\t\t\tthrow SerialTimeoutExc();\n\n\t\t\/\/ we need to reallocate even if this happens to be the last byte, because we need room for a null-terminator\n\t\tif( bufferOffset == bufferSize ) {\n\t\t\tchar *newBuffer = (char*)malloc( bufferSize * 2 );\n\t\t\tmemcpy( newBuffer, buffer.get(), bufferSize );\n\t\t\tbufferSize *= 2;\n\t\t\tbuffer = shared_ptr( newBuffer, free );\n\t\t}\n\t}\n\n\tbuffer.get()[bufferOffset] = 0; \/\/ need to null terminate this thing\n\tstd::string result( buffer.get() );\n\n\treturn result;\n}\n\nvoid Serial::writeString( const std::string &str )\n{\n\tfor( string::const_iterator strIt = str.begin(); strIt != str.end(); ++strIt )\n\t\twriteByte( *strIt );\n}\n\nsize_t Serial::getNumBytesAvailable() const\n{\n\tint result;\n\t\n#if defined( CINDER_MAC )\n\t::ioctl( mObj->mFd, FIONREAD, &result );\n#elif defined( CINDER_MSW )\n\t::COMSTAT status;\n\t::DWORD error;\n\tif( ! ::ClearCommError( mObj->mDeviceHandle, &error, &status ) )\n\t\tthrow SerialExc();\n\telse\n\t\tresult = status.cbInQue;\n#endif\n\t\n\treturn result;\n}\n\t\nvoid Serial::flush( bool input, bool output )\n{\n#if defined( CINDER_MAC )\n\tint queue;\n\tif( input && output )\n\t\tqueue = TCIOFLUSH;\n\telse if( input )\n\t\tqueue = TCIFLUSH;\n\telse if( output )\n\t\tqueue = TCOFLUSH;\n\telse\n\t\treturn;\n\t\n\t::tcflush( mObj->mFd, queue );\n#elif defined( CINDER_MSW )\n\t::DWORD flags = 0;\n\tflags |= ( input ) ? PURGE_RXCLEAR : 0;\n\tflags |= ( output ) ? PURGE_TXCLEAR : 0;\n\t\n\tif( input || output )\n\t\t::PurgeComm( mObj->mDeviceHandle, flags );\n#endif\n}\n\n} \/\/ namespace cinderFixing Mac serial issue when ReadFile returns EAGAIN\/*\n Copyright (c) 2009, The Barbarian Group\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"cinder\/Serial.h\"\n#include \"cinder\/Timer.h\"\n#include \"cinder\/Thread.h\"\n#include \"cinder\/Utilities.h\"\n\n#include \n#include \n#include \n\n#if defined( CINDER_MAC )\n\t#include \n\t#include \n\t#include \n\t#include \n#elif defined( CINDER_MSW )\n\t#include \n\t#pragma comment(lib, \"setupapi.lib\")\n#endif\n\n#include \nusing namespace std;\n\nnamespace cinder {\n\nbool\t\t\t\t\t\t\tSerial::sDevicesInited = false;\nstd::vector\t\tSerial::sDevices;\n\nSerial::Serial( const Serial::Device &device, int baudRate )\n\t: mObj( new Obj( device, baudRate ) )\n{\n}\n\nSerial::Obj::Obj( const Serial::Device &device, int baudRate )\n\t: mDevice( device )\n{\n#if defined( CINDER_MAC )\n\tmFd = open( ( \"\/dev\/\" + device.getName() ).c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK );\n\tif( mFd == -1 ) {\n\t\tthrow SerialExcOpenFailed();\n\t}\n\t\n\ttermios options;\n\ttcgetattr( mFd, &mSavedOptions );\n\toptions = mSavedOptions;\n\tmap baudToConstant;\n\tbaudToConstant[300] = B300;\n\tbaudToConstant[1200] = B1200;\n\tbaudToConstant[2400] = B2400;\n\tbaudToConstant[4800] = B4800;\n\tbaudToConstant[9600] = B9600;\t\t\t\n\tbaudToConstant[19200] = B19200;\n\tbaudToConstant[28800] = B28800;\n\tbaudToConstant[38400] = B38400;\n\tbaudToConstant[57600] = B57600;\n\tbaudToConstant[115200] = B115200;\n\tbaudToConstant[230400] = B230400;\t\n\t\n\tint rateConstant = B9600;\n\tif( baudToConstant.find( baudRate ) != baudToConstant.end() )\n\t\trateConstant = baudToConstant[baudRate];\n\t\n\t::cfsetispeed( &options, rateConstant );\n\t::cfsetospeed( &options, rateConstant );\n\t\n\toptions.c_cflag |= (CLOCAL | CREAD);\n\toptions.c_cflag &= ~PARENB;\n\toptions.c_cflag &= ~CSTOPB;\n\toptions.c_cflag &= ~CSIZE;\n\toptions.c_cflag |= CS8;\n\t::tcsetattr( mFd, TCSANOW, &options );\n#elif defined( CINDER_MSW )\n\tmDeviceHandle = ::CreateFileA( mDevice.getPath().c_str(), GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0 );\n\tif( mDeviceHandle == INVALID_HANDLE_VALUE ) {\n\t\tthrow SerialExcOpenFailed();\n\t}\n\t\n\t::COMMCONFIG config;\n\t::DWORD configSize = sizeof( ::COMMCONFIG );\n\t::GetCommConfig( mDeviceHandle, &config, &configSize );\n\t\n\tstring settingsStr = string(\"baud=\") + toString( baudRate ) + \" parity=N data=8 stop=1\";\n\tif( ! ::BuildCommDCBA( settingsStr.c_str(), &config.dcb ) ) {\n\t\tthrow SerialExcOpenFailed();\t\n\t}\t\n\t\n\tif( ! ::SetCommState( mDeviceHandle, &config.dcb ) ) {\n\t\tthrow SerialExcOpenFailed();\n\t}\n\t\n\t::GetCommTimeouts( mDeviceHandle, &mSavedTimeouts );\n\t::COMMTIMEOUTS timeOuts( mSavedTimeouts );\n\n\ttimeOuts.ReadIntervalTimeout = MAXDWORD;\n\ttimeOuts.ReadTotalTimeoutMultiplier = 0;\n\ttimeOuts.ReadTotalTimeoutConstant = 0;\n\t::SetCommTimeouts( mDeviceHandle, &timeOuts );\n#endif\n}\n\nSerial::Device Serial::findDeviceByName( const std::string &name, bool forceRefresh )\n{\n\tconst std::vector &devices = getDevices( forceRefresh );\n\tfor( std::vector::const_iterator deviceIt = devices.begin(); deviceIt != devices.end(); ++deviceIt ) {\n\t\tif( deviceIt->getName() == name )\n\t\t\treturn *deviceIt;\n\t}\n\t\n\treturn Serial::Device();\n}\n\nSerial::Device Serial::findDeviceByNameContains( const std::string &searchString, bool forceRefresh )\n{\n\tconst std::vector &devices = getDevices( forceRefresh );\n\tfor( std::vector::const_iterator deviceIt = devices.begin(); deviceIt != devices.end(); ++deviceIt ) {\n\t\tif( deviceIt->getName().find( searchString ) != std::string::npos )\n\t\t\treturn *deviceIt;\n\t}\n\t\n\treturn Serial::Device();\n}\n\t\nconst std::vector& Serial::getDevices( bool forceRefresh )\n{\n\tif( ( ! forceRefresh ) && ( sDevicesInited ) )\n\t\treturn sDevices;\n\n\tsDevices.clear();\n\n#if defined( CINDER_MAC )\t\n\t::DIR *dir;\n\t::dirent *entry;\n\tdir = ::opendir( \"\/dev\" );\n\n\tif( ! dir ) {\n\t\tthrow SerialExcDeviceEnumerationFailed();\n\t}\n\telse {\n\t\twhile( ( entry = ::readdir( dir ) ) != NULL ) {\n\t\t\tstd::string str( (char *)entry->d_name );\n\t\t\tif( ( str.substr( 0, 4 ) == \"tty.\" ) || ( str.substr( 0, 3 ) == \"cu.\" ) ) {\n\t\t\t\tsDevices.push_back( Serial::Device( str ) );\n\t\t\t}\n\t\t}\n\t}\n\t\n#elif defined( CINDER_MSW )\n\t::HDEVINFO devInfoSet;\n\t::DWORD devCount = 0;\n\t::SP_DEVINFO_DATA devInfo;\n\t::SP_DEVICE_INTERFACE_DATA devInterface;\n\tDWORD size = 0;\n\n\tdevInfoSet = ::SetupDiGetClassDevs( &GUID_SERENUM_BUS_ENUMERATOR, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE );\n\tif( devInfoSet == INVALID_HANDLE_VALUE )\n\t\tthrow SerialExcDeviceEnumerationFailed();\n\t\n\tdevInterface.cbSize = sizeof( ::SP_DEVICE_INTERFACE_DATA );\n\twhile( ::SetupDiEnumDeviceInterfaces( devInfoSet, 0, &GUID_SERENUM_BUS_ENUMERATOR, devCount++, &devInterface ) ) {\n\t\t\/\/ See how large a buffer we require for the device interface details\n\t\t::SetupDiGetDeviceInterfaceDetail( devInfoSet, &devInterface, 0, 0, &size, 0 );\n\t\tdevInfo.cbSize = sizeof( ::SP_DEVINFO_DATA );\n\t\tshared_ptr<::SP_DEVICE_INTERFACE_DETAIL_DATA> interfaceDetail( (::SP_DEVICE_INTERFACE_DETAIL_DATA*)calloc( 1, size ), free );\n\t\tif( interfaceDetail ) {\n\t\t\tinterfaceDetail->cbSize = sizeof( ::SP_DEVICE_INTERFACE_DETAIL_DATA );\n\t\t\tdevInfo.cbSize = sizeof( ::SP_DEVINFO_DATA );\n\t\t\tif( ! ::SetupDiGetDeviceInterfaceDetail( devInfoSet, &devInterface, interfaceDetail.get(), size, 0, &devInfo ) ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tchar friendlyName[2048];\n\t\t\tsize = sizeof( friendlyName );\n\t\t\tfriendlyName[0] = 0;\n\t\t\t::DWORD propertyDataType;\n\t\t\tif( ! ::SetupDiGetDeviceRegistryPropertyA( devInfoSet, &devInfo, SPDRP_FRIENDLYNAME, &propertyDataType, (LPBYTE)friendlyName, size, 0 ) ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tsDevices.push_back( Serial::Device( string( friendlyName ), toUtf8( interfaceDetail->DevicePath ) ) );\n\t\t}\n\t}\n\t\n\t::SetupDiDestroyDeviceInfoList(devInfoSet);\n\n#endif\n\n\tsDevicesInited = true;\n\treturn sDevices;\n}\n\nSerial::Obj::~Obj()\n{\n#if defined( CINDER_MAC )\n\t\/\/ restore the termios from before we opened the port\n\t::tcsetattr( mFd, TCSANOW, &mSavedOptions );\n\t::close( mFd );\n#elif defined( CINDER_MSW )\n\t::SetCommTimeouts( mDeviceHandle, &mSavedTimeouts );\n\t::CloseHandle( mDeviceHandle );\n#endif\n}\n\nconst Serial::Device& Serial::getDevice() const\n{\n\treturn mObj->mDevice;\n}\n\nvoid Serial::writeBytes( const void *data, size_t numBytes )\n{\n\tsize_t totalBytesWritten = 0;\n\t\n\twhile( totalBytesWritten < numBytes ) {\n#if defined( CINDER_MAC )\n\t\tint bytesWritten = ::write( mObj->mFd, data, numBytes - totalBytesWritten );\n\t\tif( ( bytesWritten == -1 ) && ( errno != EAGAIN ) )\n\t\t\tthrow SerialExcReadFailure();\t\n#elif defined( CINDER_MSW )\n\t\t::DWORD bytesWritten;\n\t\tif( ! ::WriteFile( mObj->mDeviceHandle, data, numBytes - totalBytesWritten, &bytesWritten, 0 ) )\n\t\t\tthrow SerialExcWriteFailure();\n#endif\n\t\ttotalBytesWritten += bytesWritten;\n\t}\n}\n\nvoid Serial::readBytes( void *data, size_t numBytes )\n{\n\tsize_t totalBytesRead = 0;\n\twhile( totalBytesRead < numBytes ) {\n#if defined( CINDER_MAC )\n\t\tint bytesRead = ::read( mObj->mFd, data, numBytes - totalBytesRead );\n\t\tif( ( bytesRead == -1 ) && ( errno != EAGAIN ) )\n\t\t\tthrow SerialExcReadFailure();\n#elif defined( CINDER_MSW )\n\t\t::DWORD bytesRead = 0;\n\t\tif( ! ::ReadFile( mObj->mDeviceHandle, data, numBytes - totalBytesRead, &bytesRead, 0 ) )\n\t\t\tthrow SerialExcReadFailure();\n#endif\n\t\tif( bytesRead != -1 )\n\t\t\ttotalBytesRead += bytesRead;\n\t\t\n\t\t\/\/ yield thread time to the system\n\t\tthis_thread::yield();\n\t}\n}\n\nsize_t Serial::readAvailableBytes( void *data, size_t maximumBytes )\n{\n#if defined( CINDER_MAC )\n\tint bytesRead = ::read( mObj->mFd, data, maximumBytes );\n#elif defined( CINDER_MSW )\n\t::DWORD bytesRead = 0;\n\tif( ! ::ReadFile( mObj->mDeviceHandle, data, maximumBytes, &bytesRead, 0 ) )\n\t\tthrow SerialExcReadFailure();\n#endif\n\n\tif( bytesRead < 0 )\n\t\tbytesRead = 0;\n\t\t\n\treturn (size_t)bytesRead;\n}\n\nvoid Serial::writeByte( uint8_t data )\n{\n\twriteBytes( &data, 1 );\n}\n\nuint8_t Serial::readByte()\n{\n\tuint8_t result;\n\treadBytes( &result, 1 );\n\treturn result;\n}\n\nstd::string Serial::readStringUntil( char token, size_t maxLength, double timeoutSeconds )\n{\n\tsize_t bufferSize = 1024, bufferOffset = 0;\n\tshared_ptr buffer( (char*)malloc( bufferSize ), free );\n\n\tbool useMaxLength = maxLength > 0;\n\tbool useTimer = timeoutSeconds > 0;\n\tTimer timer;\n\tif( useTimer )\n\t\ttimer.start();\n\n\tbool done = false;\n\twhile( ! done ) {\n\t\tchar v = readChar();\n\t\tbuffer.get()[bufferOffset++] = v;\n\t\tif( v == token ) {\n\t\t\tdone = true;\n\t\t}\n\t\telse if( useMaxLength && ( bufferOffset == maxLength ) ) {\n\t\t\tdone = true;\n\t\t}\n\t\telse if( useTimer && ( timer.getSeconds() > timeoutSeconds ) )\n\t\t\tthrow SerialTimeoutExc();\n\n\t\t\/\/ we need to reallocate even if this happens to be the last byte, because we need room for a null-terminator\n\t\tif( bufferOffset == bufferSize ) {\n\t\t\tchar *newBuffer = (char*)malloc( bufferSize * 2 );\n\t\t\tmemcpy( newBuffer, buffer.get(), bufferSize );\n\t\t\tbufferSize *= 2;\n\t\t\tbuffer = shared_ptr( newBuffer, free );\n\t\t}\n\t}\n\n\tbuffer.get()[bufferOffset] = 0; \/\/ need to null terminate this thing\n\tstd::string result( buffer.get() );\n\n\treturn result;\n}\n\nvoid Serial::writeString( const std::string &str )\n{\n\tfor( string::const_iterator strIt = str.begin(); strIt != str.end(); ++strIt )\n\t\twriteByte( *strIt );\n}\n\nsize_t Serial::getNumBytesAvailable() const\n{\n\tint result;\n\t\n#if defined( CINDER_MAC )\n\t::ioctl( mObj->mFd, FIONREAD, &result );\n#elif defined( CINDER_MSW )\n\t::COMSTAT status;\n\t::DWORD error;\n\tif( ! ::ClearCommError( mObj->mDeviceHandle, &error, &status ) )\n\t\tthrow SerialExc();\n\telse\n\t\tresult = status.cbInQue;\n#endif\n\t\n\treturn result;\n}\n\t\nvoid Serial::flush( bool input, bool output )\n{\n#if defined( CINDER_MAC )\n\tint queue;\n\tif( input && output )\n\t\tqueue = TCIOFLUSH;\n\telse if( input )\n\t\tqueue = TCIFLUSH;\n\telse if( output )\n\t\tqueue = TCOFLUSH;\n\telse\n\t\treturn;\n\t\n\t::tcflush( mObj->mFd, queue );\n#elif defined( CINDER_MSW )\n\t::DWORD flags = 0;\n\tflags |= ( input ) ? PURGE_RXCLEAR : 0;\n\tflags |= ( output ) ? PURGE_TXCLEAR : 0;\n\t\n\tif( input || output )\n\t\t::PurgeComm( mObj->mDeviceHandle, flags );\n#endif\n}\n\n} \/\/ namespace cinder<|endoftext|>"} {"text":"\/*****************************************************************************\n * Copyright (C) 2013 Michael Krufky\n *\n * Author: Michael Krufky \n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * version 2 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \n#include \n#include \n#include \"hlsinput.h\"\n\nint main(int argc, char *argv[])\n{\n int opt;\n bool feed_stdout = false;\n char url[2048] = { 0 };\n\n while ((opt = getopt(argc, argv, \"i:o\")) != -1) {\n switch (opt) {\n case 'i':\n if (!optarg) {\n fprintf(stderr, \"missing argument\\n\");\n return -1;\n }\n strncpy(url, optarg, sizeof(url));\n break;\n case 'o':\n feed_stdout = true;\n break;\n }\n }\n\n hlsinput hls(feed_stdout);\n hls.get(url);\n}\nwalk_hls: tiny whitespace cleanup\/*****************************************************************************\n * Copyright (C) 2013 Michael Krufky\n *\n * Author: Michael Krufky \n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * version 2 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \n#include \n#include \n#include \"hlsinput.h\"\n\nint main(int argc, char *argv[])\n{\n int opt;\n bool feed_stdout = false;\n char url[2048] = { 0 };\n\n while ((opt = getopt(argc, argv, \"i:o\")) != -1) {\n switch (opt) {\n case 'i':\n if (!optarg) {\n\tfprintf(stderr, \"missing argument\\n\");\n\treturn -1;\n }\n strncpy(url, optarg, sizeof(url));\n break;\n case 'o':\n feed_stdout = true;\n break;\n }\n }\n\n hlsinput hls(feed_stdout);\n hls.get(url);\n}\n<|endoftext|>"} {"text":"\/**\n * Test suite for the iterator_concepts_ordering.hpp header.\n *\/\n\n#include \n\n#include \n\n\nBOOST_MPL_ASSERT((duck::is_more_specific_than<\n duck::BidirectionalIterator,\n duck::RandomAccessIterator>));\n\nBOOST_MPL_ASSERT((duck::is_more_specific_than<\n duck::IncrementableIterator,\n duck::RandomAccessIterator>));\n\n\nBOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<\n duck::RandomAccessIterator,\n duck::BidirectionalIterator>));\n\nBOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<\n duck::RandomAccessIterator,\n duck::IncrementableIterator>));\n\nBOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<\n duck::ForwardIterator,\n duck::ForwardIterator>));\nAdd more iterator concept ordering tests.\/**\n * Test suite for the iterator_concepts_ordering.hpp header.\n *\/\n\n#include \n\n#include \n\n\nBOOST_MPL_ASSERT((duck::is_more_specific_than<\n duck::BidirectionalIterator,\n duck::RandomAccessIterator>));\n\nBOOST_MPL_ASSERT((duck::is_more_specific_than<\n duck::IncrementableIterator,\n duck::RandomAccessIterator>));\n\nBOOST_MPL_ASSERT((duck::is_more_specific_than<\n duck::ForwardIterator,\n duck::RandomAccessIterator>));\n\n\nBOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<\n duck::RandomAccessIterator,\n duck::BidirectionalIterator>));\n\nBOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<\n duck::RandomAccessIterator,\n duck::IncrementableIterator>));\n\nBOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<\n duck::ForwardIterator,\n duck::ForwardIterator>));\n\nBOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<\n duck::RandomAccessIterator,\n duck::ForwardIterator>));\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: ZipPackageFolderEnumeration.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: mtg $ $Date: 2001-11-15 20:30:34 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _ZIP_PACKAGE_FOLDER_ENUMERATION_HXX\n#define _ZIP_PACKAGE_FOLDER_ENUMERATION_HXX\n\n#ifndef _CPPUHELPER_IMPLBASE2_HXX_\n#include \/\/ helper for implementations\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XPSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _HASH_MAPS_HXX\n#include \n#endif\n\nclass ZipPackageFolderEnumeration : public cppu::WeakImplHelper2\n<\n com::sun::star::container::XEnumeration,\n com::sun::star::lang::XServiceInfo\n>\n{\nprotected:\n ContentHash &rContents;\n ContentHash::const_iterator aIterator;\npublic:\n \/\/ZipPackageFolderEnumeration (std::hash_map < rtl::OUString, com::sun::star::uno::Reference < com::sun::star::container::XNamed >, hashFunc, eqFunc > &rInput);\n ZipPackageFolderEnumeration (ContentHash &rInput);\n virtual ~ZipPackageFolderEnumeration( void );\n\n \/\/ XEnumeration\n virtual sal_Bool SAL_CALL hasMoreElements( )\n throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL nextElement( )\n throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )\n throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )\n throw (::com::sun::star::uno::RuntimeException);\n\n};\n#endif\nINTEGRATION: CWS mav09 (1.4.136); FILE MERGED 2004\/05\/13 15:10:03 mav 1.4.136.1: #112768# remove dangerous references\/*************************************************************************\n *\n * $RCSfile: ZipPackageFolderEnumeration.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: kz $ $Date: 2004-10-04 21:10:22 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _ZIP_PACKAGE_FOLDER_ENUMERATION_HXX\n#define _ZIP_PACKAGE_FOLDER_ENUMERATION_HXX\n\n#ifndef _CPPUHELPER_IMPLBASE2_HXX_\n#include \/\/ helper for implementations\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XPSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _HASH_MAPS_HXX\n#include \n#endif\n\nclass ZipPackageFolderEnumeration : public cppu::WeakImplHelper2\n<\n com::sun::star::container::XEnumeration,\n com::sun::star::lang::XServiceInfo\n>\n{\nprotected:\n ContentHash rContents;\n ContentHash::const_iterator aIterator;\npublic:\n \/\/ZipPackageFolderEnumeration (std::hash_map < rtl::OUString, com::sun::star::uno::Reference < com::sun::star::container::XNamed >, hashFunc, eqFunc > &rInput);\n ZipPackageFolderEnumeration (ContentHash &rInput);\n virtual ~ZipPackageFolderEnumeration( void );\n\n \/\/ XEnumeration\n virtual sal_Bool SAL_CALL hasMoreElements( )\n throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL nextElement( )\n throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )\n throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )\n throw (::com::sun::star::uno::RuntimeException);\n\n};\n#endif\n<|endoftext|>"} {"text":"\/\/ -*- C++ -*-\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ Test that _LIBCPP_ALIGNOF acts the same as the C++11 keyword `alignof`, and\n\/\/ not as the GNU extension `__alignof`. The former returns the minimal required\n\/\/ alignment for a type, whereas the latter returns the preferred alignment.\n\/\/\n\/\/ See llvm.org\/PR39713\n\n#include \n#include \"test_macros.h\"\n\ntemplate \nvoid test() {\n static_assert(_LIBCPP_ALIGNOF(T) == std::alignment_of::value, \"\");\n static_assert(_LIBCPP_ALIGNOF(T) == TEST_ALIGNOF(T), \"\");\n static_assert(alignof(T) == __alignof(T), \"\");\n#if TEST_STD_VER >= 11\n static_assert(_LIBCPP_ALIGNOF(T) == alignof(T), \"\");\n#endif\n#ifdef TEST_COMPILER_CLANG\n static_assert(_LIBCPP_ALIGNOF(T) == _Alignof(T), \"\");\n#endif\n}\n\nint main() {\n test();\n test();\n test();\n test();\n}\nFix bad _LIBCPP_ALIGNOF test\/\/ -*- C++ -*-\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ Test that _LIBCPP_ALIGNOF acts the same as the C++11 keyword `alignof`, and\n\/\/ not as the GNU extension `__alignof`. The former returns the minimal required\n\/\/ alignment for a type, whereas the latter returns the preferred alignment.\n\/\/\n\/\/ See llvm.org\/PR39713\n\n#include \n#include \"test_macros.h\"\n\ntemplate \nvoid test() {\n static_assert(_LIBCPP_ALIGNOF(T) == std::alignment_of::value, \"\");\n static_assert(_LIBCPP_ALIGNOF(T) == TEST_ALIGNOF(T), \"\");\n#if TEST_STD_VER >= 11\n static_assert(_LIBCPP_ALIGNOF(T) == alignof(T), \"\");\n#endif\n#ifdef TEST_COMPILER_CLANG\n static_assert(_LIBCPP_ALIGNOF(T) == _Alignof(T), \"\");\n#endif\n}\n\nint main() {\n test();\n test();\n test();\n test();\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of the dune-hdd project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-hdd\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_HH\n#define DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_HH\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"linearelliptic.hh\"\n\nnamespace Dune {\nnamespace HDD {\nnamespace LinearElliptic {\nnamespace Tests {\nnamespace internal {\n\n\ntemplate< class TestCaseType, int polOrder, Stuff::LA::ChooseBackend la_backend >\nclass DiscretizationBlockSWIPDG\n{\n typedef typename TestCaseType::GridType GridType;\n typedef typename TestCaseType::RangeFieldType RangeFieldType;\n static const unsigned int dimRange = TestCaseType::dimRange;\npublic:\n typedef Discretizations::BlockSWIPDG< GridType, RangeFieldType, dimRange, polOrder, la_backend > Type;\n}; \/\/ class DiscretizationBlockSWIPDG\n\n\n} \/\/ namespace internal\n\n\ntemplate< class TestCaseType, int polOrder, Stuff::LA::ChooseBackend la_backend >\nclass EocStudyBlockSWIPDG\n : public MultiscaleEocStudyBase< TestCaseType,\n typename internal::DiscretizationBlockSWIPDG< TestCaseType,\n polOrder,\n la_backend >::Type >\n{\n typedef EocStudyBlockSWIPDG< TestCaseType, polOrder, la_backend > ThisType;\n typedef MultiscaleEocStudyBase\n < TestCaseType,\n typename internal::DiscretizationBlockSWIPDG< TestCaseType, polOrder, la_backend >::Type > BaseType;\n\n typedef typename BaseType::DiscretizationType DiscretizationType;\n typedef typename DiscretizationType::GridViewType GridViewType;\n typedef typename BaseType::FunctionType FunctionType;\n typedef typename BaseType::VectorType VectorType;\n\npublic:\n EocStudyBlockSWIPDG(const TestCaseType& test_case,\n const std::vector< std::string > only_these_norms = std::vector< std::string >())\n : BaseType(test_case, only_these_norms)\n {}\n\n virtual ~EocStudyBlockSWIPDG() {}\n\n virtual std::string identifier() const DS_OVERRIDE DS_FINAL\n {\n return DiscretizationType::static_id()\n + \" (polorder \" + Stuff::Common::toString(polOrder)\n + \", \" + this->test_case_.partitioning() + \" partitioning)\";\n } \/\/ ... identifier(...)\n\n virtual size_t expected_rate(const std::string type) const DS_OVERRIDE DS_FINAL\n {\n if (type == \"L2\")\n return polOrder + 1;\n else if (type == \"H1_semi\")\n return polOrder;\n else if (type == \"energy\")\n return polOrder;\n else if (type == \"eta_NC_OS2014\")\n return polOrder;\n else if (type == \"eta_R_OS2014\")\n return polOrder + 1;\n else if (type == \"eta_DF_OS2014\")\n return polOrder;\n else if (type == \"eta_OS2014\")\n return polOrder;\n else if (type == \"eff_OS2014\")\n return 0;\n else\n DUNE_THROW(Stuff::Exceptions::wrong_input_given, \"Wrong type '\" << type << \"' requested!\");\n } \/\/ ... expected_rate(...)\n\n virtual std::vector< double > expected_results(const std::string type) const DS_OVERRIDE DS_FINAL\n {\n if (std::is_same< TestCaseType, TestCases::ESV2007Multiscale< ALUConformGrid< 2, 2 > > >::value\n || std::is_same< TestCaseType, TestCases::ESV2007Multiscale< ALUGrid< 2, 2, simplex, conforming > > >::value) {\n if (this->test_case_.partitioning() == \"[1 1 1]\") {\n if (polOrder == 1) {\n if (type == \"energy\")\n return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};\n else if (type == \"eta_NC_OS2014\")\n return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};\n else if (type == \"eta_R_OS2014\")\n return {5.80e-01, 2.91e-01, 1.46e-01, 7.28e-02};\n else if (type == \"eta_DF_OS2014\")\n return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};\n else if (type == \"eta_OS2014\")\n return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};\n else if (type == \"eff_OS2014\")\n return {3.36, 3.38, 3.39, 3.40};\n else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, type);\n } else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);\n } else if (this->test_case_.partitioning() == \"[2 2 1]\") {\n if (polOrder == 1) {\n if (type == \"energy\")\n return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};\n else if (type == \"eta_NC_OS2014\")\n return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};\n else if (type == \"eta_R_OS2014\")\n return {2.90e-01, 1.46e-01, 7.28e-02, 3.64e-02};\n else if (type == \"eta_DF_OS2014\")\n return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};\n else if (type == \"eta_OS2014\")\n return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};\n else if (type == \"eff_OS2014\")\n return {2.48, 2.48, 2.49, 2.49};\n else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, type);\n } else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);\n } else if (this->test_case_.partitioning() == \"[4 4 1]\") {\n if (polOrder == 1) {\n if (type == \"energy\")\n return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};\n else if (type == \"eta_NC_OS2014\")\n return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};\n else if (type == \"eta_R_OS2014\")\n return {1.46e-01, 7.27e-02, 3.64e-02, 1.82e-02};\n else if (type == \"eta_DF_OS2014\")\n return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};\n else if (type == \"eta_OS2014\")\n return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};\n else if (type == \"eff_OS2014\")\n return {2.04, 2.03, 2.03, 2.04};\n else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, type);\n } else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);\n } else if (this->test_case_.partitioning() == \"[8 8 1]\") {\n if (polOrder == 1) {\n if (type == \"energy\")\n return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};\n else if (type == \"eta_NC_OS2014\")\n return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};\n else if (type == \"eta_R_OS2014\")\n return {7.24e-02, 3.64e-02, 1.83e-02, 9.10e-03};\n else if (type == \"eta_DF_OS2014\")\n return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};\n else if (type == \"eta_OS2014\")\n return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};\n else if (type == \"eff_OS2014\")\n return {1.82, 1.81, 1.81, 1.81};\n else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, type);\n } else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);\n } else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, this->test_case_.partitioning());\n } else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, Stuff::Common::Typename< TestCaseType >::value());\n } \/\/ ... expected_results(...)\n\nprivate:\n virtual std::vector< std::string > available_norms() const DS_OVERRIDE DS_FINAL\n {\n return {\"L2\", \"H1_semi\", \"energy\"};\n }\n\n virtual double compute_norm(const GridViewType& grid_view,\n const FunctionType& function,\n const std::string type) const DS_OVERRIDE DS_FINAL\n {\n using namespace GDT;\n typedef typename TestCaseType::ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType;\n typedef typename TestCaseType::ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType;\n if (type == \"L2\") {\n return Products::L2< GridViewType >(grid_view).induced_norm(function);\n } else if (type == \"H1_semi\") {\n return Products::H1SemiGeneric< GridViewType >(grid_view).induced_norm(function);\n } else if (type == \"energy\") {\n const auto& diffusion_factor = *(this->test_case_.problem().diffusion_factor());\n assert(!diffusion_factor.parametric());\n assert(diffusion_factor.has_affine_part());\n const auto& diffusion_tensor = *(this->test_case_.problem().diffusion_tensor());\n assert(!diffusion_tensor.parametric());\n assert(diffusion_tensor.has_affine_part());\n Products::Elliptic< DiffusionFactorType, GridViewType, double, DiffusionTensorType >\n elliptic_product(*diffusion_factor.affine_part(), *diffusion_tensor.affine_part(), grid_view);\n return elliptic_product.induced_norm(function);\n } else\n DUNE_THROW(Stuff::Exceptions::wrong_input_given, \"Wrong type '\" << type << \"' requested!\");\n }\n\n virtual std::vector< std::string > available_estimators() const DS_OVERRIDE DS_FINAL\n {\n auto ret = DiscretizationType::available_estimators();\n if (std::find(ret.begin(), ret.end(), \"eta_OS2014\") != ret.end())\n ret.push_back(\"eff_OS2014\");\n if (std::find(ret.begin(), ret.end(), \"eta_OS2014_alt\") != ret.end())\n ret.push_back(\"eff_OS2014_alt\");\n return ret;\n } \/\/ ... available_estimators(..)\n\n virtual double estimate(const VectorType& vector, const std::string type) const DS_OVERRIDE DS_FINAL\n {\n if (type == \"eff_OS2014\")\n return estimate(vector, \"eta_OS2014\") \/ const_cast< ThisType& >(*this).current_error_norm(\"energy\");\n else if (type == \"eff_OS2014_alt\")\n return estimate(vector, \"eta_OS2014_alt\") \/ const_cast< ThisType& >(*this).current_error_norm(\"energy\");\n else {\n assert(this->current_discretization_);\n return this->current_discretization_->estimate(vector, type);\n }\n } \/\/ ... estimate(...)\n}; \/\/ class EocStudyBlockSWIPDG\n\n\n} \/\/ namespace Tests\n} \/\/ namespace LinearElliptic\n} \/\/ namespace HDD\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_HH\n[test.linearelliptic-block-swipdg] use new estimator\/\/ This file is part of the dune-hdd project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-hdd\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_HH\n#define DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_HH\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"linearelliptic.hh\"\n\nnamespace Dune {\nnamespace HDD {\nnamespace LinearElliptic {\nnamespace Tests {\nnamespace internal {\n\n\ntemplate< class TestCaseType, int polOrder, Stuff::LA::ChooseBackend la_backend >\nclass DiscretizationBlockSWIPDG\n{\n typedef typename TestCaseType::GridType GridType;\n typedef typename TestCaseType::RangeFieldType RangeFieldType;\n static const unsigned int dimRange = TestCaseType::dimRange;\npublic:\n typedef Discretizations::BlockSWIPDG< GridType, RangeFieldType, dimRange, polOrder, la_backend > Type;\n}; \/\/ class DiscretizationBlockSWIPDG\n\n\n} \/\/ namespace internal\n\n\ntemplate< class TestCaseType, int polOrder, Stuff::LA::ChooseBackend la_backend >\nclass EocStudyBlockSWIPDG\n : public MultiscaleEocStudyBase< TestCaseType,\n typename internal::DiscretizationBlockSWIPDG< TestCaseType,\n polOrder,\n la_backend >::Type >\n{\n typedef EocStudyBlockSWIPDG< TestCaseType, polOrder, la_backend > ThisType;\n typedef MultiscaleEocStudyBase\n < TestCaseType,\n typename internal::DiscretizationBlockSWIPDG< TestCaseType, polOrder, la_backend >::Type > BaseType;\n\n typedef typename BaseType::DiscretizationType DiscretizationType;\n typedef typename DiscretizationType::EstimatorType EstimatorType;\n typedef typename DiscretizationType::GridViewType GridViewType;\n typedef typename BaseType::FunctionType FunctionType;\n typedef typename BaseType::VectorType VectorType;\n\npublic:\n EocStudyBlockSWIPDG(const TestCaseType& test_case,\n const std::vector< std::string > only_these_norms = std::vector< std::string >())\n : BaseType(test_case, only_these_norms)\n {}\n\n virtual ~EocStudyBlockSWIPDG() {}\n\n virtual std::string identifier() const DS_OVERRIDE DS_FINAL\n {\n return DiscretizationType::static_id()\n + \" (polorder \" + Stuff::Common::toString(polOrder)\n + \", \" + this->test_case_.partitioning() + \" partitioning)\";\n } \/\/ ... identifier(...)\n\n virtual size_t expected_rate(const std::string type) const DS_OVERRIDE DS_FINAL\n {\n if (type == \"L2\")\n return polOrder + 1;\n else if (type == \"H1_semi\")\n return polOrder;\n else if (type == \"energy\")\n return polOrder;\n else if (type == \"eta_NC_OS2014\")\n return polOrder;\n else if (type == \"eta_R_OS2014\")\n return polOrder + 1;\n else if (type == \"eta_DF_OS2014\")\n return polOrder;\n else if (type == \"eta_OS2014\")\n return polOrder;\n else if (type == \"eff_OS2014\")\n return 0;\n else\n DUNE_THROW(Stuff::Exceptions::wrong_input_given, \"Wrong type '\" << type << \"' requested!\");\n } \/\/ ... expected_rate(...)\n\n virtual std::vector< double > expected_results(const std::string type) const DS_OVERRIDE DS_FINAL\n {\n if (std::is_same< TestCaseType, TestCases::ESV2007Multiscale< ALUConformGrid< 2, 2 > > >::value\n || std::is_same< TestCaseType, TestCases::ESV2007Multiscale< ALUGrid< 2, 2, simplex, conforming > > >::value) {\n if (this->test_case_.partitioning() == \"[1 1 1]\") {\n if (polOrder == 1) {\n if (type == \"energy\")\n return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};\n else if (type == \"eta_NC_OS2014\")\n return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};\n else if (type == \"eta_R_OS2014\")\n return {5.80e-01, 2.91e-01, 1.46e-01, 7.28e-02};\n else if (type == \"eta_DF_OS2014\")\n return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};\n else if (type == \"eta_OS2014\")\n return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};\n else if (type == \"eff_OS2014\")\n return {3.36, 3.38, 3.39, 3.40};\n else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, type);\n } else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);\n } else if (this->test_case_.partitioning() == \"[2 2 1]\") {\n if (polOrder == 1) {\n if (type == \"energy\")\n return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};\n else if (type == \"eta_NC_OS2014\")\n return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};\n else if (type == \"eta_R_OS2014\")\n return {2.90e-01, 1.46e-01, 7.28e-02, 3.64e-02};\n else if (type == \"eta_DF_OS2014\")\n return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};\n else if (type == \"eta_OS2014\")\n return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};\n else if (type == \"eff_OS2014\")\n return {2.48, 2.48, 2.49, 2.49};\n else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, type);\n } else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);\n } else if (this->test_case_.partitioning() == \"[4 4 1]\") {\n if (polOrder == 1) {\n if (type == \"energy\")\n return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};\n else if (type == \"eta_NC_OS2014\")\n return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};\n else if (type == \"eta_R_OS2014\")\n return {1.46e-01, 7.27e-02, 3.64e-02, 1.82e-02};\n else if (type == \"eta_DF_OS2014\")\n return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};\n else if (type == \"eta_OS2014\")\n return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};\n else if (type == \"eff_OS2014\")\n return {2.04, 2.03, 2.03, 2.04};\n else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, type);\n } else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);\n } else if (this->test_case_.partitioning() == \"[8 8 1]\") {\n if (polOrder == 1) {\n if (type == \"energy\")\n return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};\n else if (type == \"eta_NC_OS2014\")\n return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};\n else if (type == \"eta_R_OS2014\")\n return {7.24e-02, 3.64e-02, 1.83e-02, 9.10e-03};\n else if (type == \"eta_DF_OS2014\")\n return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};\n else if (type == \"eta_OS2014\")\n return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};\n else if (type == \"eff_OS2014\")\n return {1.82, 1.81, 1.81, 1.81};\n else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, type);\n } else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);\n } else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, this->test_case_.partitioning());\n } else\n DUNE_THROW(Stuff::Exceptions::test_results_missing, Stuff::Common::Typename< TestCaseType >::value());\n } \/\/ ... expected_results(...)\n\nprivate:\n virtual std::vector< std::string > available_norms() const DS_OVERRIDE DS_FINAL\n {\n return {\"L2\", \"H1_semi\", \"energy\"};\n }\n\n virtual double compute_norm(const GridViewType& grid_view,\n const FunctionType& function,\n const std::string type) const DS_OVERRIDE DS_FINAL\n {\n using namespace GDT;\n typedef typename TestCaseType::ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType;\n typedef typename TestCaseType::ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType;\n if (type == \"L2\") {\n return Products::L2< GridViewType >(grid_view).induced_norm(function);\n } else if (type == \"H1_semi\") {\n return Products::H1SemiGeneric< GridViewType >(grid_view).induced_norm(function);\n } else if (type == \"energy\") {\n const auto& diffusion_factor = *(this->test_case_.problem().diffusion_factor());\n assert(!diffusion_factor.parametric());\n assert(diffusion_factor.has_affine_part());\n const auto& diffusion_tensor = *(this->test_case_.problem().diffusion_tensor());\n assert(!diffusion_tensor.parametric());\n assert(diffusion_tensor.has_affine_part());\n Products::Elliptic< DiffusionFactorType, GridViewType, double, DiffusionTensorType >\n elliptic_product(*diffusion_factor.affine_part(), *diffusion_tensor.affine_part(), grid_view);\n return elliptic_product.induced_norm(function);\n } else\n DUNE_THROW(Stuff::Exceptions::wrong_input_given, \"Wrong type '\" << type << \"' requested!\");\n }\n\n virtual std::vector< std::string > available_estimators() const DS_OVERRIDE DS_FINAL\n {\n auto ret = EstimatorType::available();\n if (std::find(ret.begin(), ret.end(), \"eta_OS2014\") != ret.end())\n ret.push_back(\"eff_OS2014\");\n if (std::find(ret.begin(), ret.end(), \"eta_OS2014_alt\") != ret.end())\n ret.push_back(\"eff_OS2014_alt\");\n return ret;\n } \/\/ ... available_estimators(..)\n\n virtual double estimate(const VectorType& vector, const std::string type) const DS_OVERRIDE DS_FINAL\n {\n if (type == \"eff_OS2014\")\n return estimate(vector, \"eta_OS2014\") \/ const_cast< ThisType& >(*this).current_error_norm(\"energy\");\n else if (type == \"eff_OS2014_alt\")\n return estimate(vector, \"eta_OS2014_alt\") \/ const_cast< ThisType& >(*this).current_error_norm(\"energy\");\n else {\n assert(this->current_discretization_);\n return EstimatorType::estimate(*this->current_discretization_->ansatz_space(),\n vector,\n this->test_case_.problem(),\n type);\n }\n } \/\/ ... estimate(...)\n}; \/\/ class EocStudyBlockSWIPDG\n\n\n} \/\/ namespace Tests\n} \/\/ namespace LinearElliptic\n} \/\/ namespace HDD\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_HH\n<|endoftext|>"} {"text":"\/\/ -*- C++ -*-\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\nint main()\n{\n}\ntest commit\/\/ -*- C++ -*-\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\nint main()\n{\n}\n\n<|endoftext|>"} {"text":"\n#include \"catch.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if defined(HAVE_CAIRO)\n#include \n#include \n#endif\n\n#pragma GCC diagnostic push\n#include \n#include \n#include \n#pragma GCC diagnostic pop\n\ninline bool make_directory(std::string const& dir) {\n return boost::filesystem::create_directory(dir);\n}\n\nTEST_CASE(\"image io\") {\n\nSECTION(\"readers\") {\n\n std::string should_throw;\n boost::optional type;\n try\n {\n mapnik::image_rgba8 im_og;\n auto im_size = mapnik::image_rgba8::pixel_size * im_og.width() * im_og.height();\n mapnik::detail::buffer buf(im_og.bytes(), im_size);\n mapnik::image_rgba8 im2(im_og.width(), im_og.height(), buf.data());\n CHECK( im2.bytes() == im_og.bytes() );\n#if defined(HAVE_JPEG)\n should_throw = \".\/test\/data\/images\/blank.jpg\";\n REQUIRE( mapnik::util::exists( should_throw ) );\n type = mapnik::type_from_filename(should_throw);\n REQUIRE( type );\n REQUIRE_THROWS(std::unique_ptr reader(mapnik::get_image_reader(should_throw,*type)));\n\n \/\/ actually a png so jpeg reader should throw\n should_throw = \".\/test\/data\/images\/landusepattern.jpg\";\n REQUIRE( mapnik::util::exists( should_throw ) );\n type = mapnik::type_from_filename(should_throw);\n REQUIRE( type );\n try\n {\n std::unique_ptr reader(mapnik::get_image_reader(should_throw,*type));\n REQUIRE(false);\n }\n catch (std::exception const& ex)\n {\n REQUIRE( std::string(ex.what()) == std::string(\"JPEG Reader: libjpeg could not read image: Not a JPEG file: starts with 0x89 0x50\") );\n }\n\n#endif\n\n REQUIRE_THROWS(mapnik::image_rgba8 im(-10,-10)); \/\/ should throw rather than overflow\n\n#if defined(HAVE_CAIRO)\n mapnik::cairo_surface_ptr image_surface(\n cairo_image_surface_create(CAIRO_FORMAT_ARGB32,256,257),\n mapnik::cairo_surface_closer());\n mapnik::image_rgba8 im_data(cairo_image_surface_get_width(&*image_surface), cairo_image_surface_get_height(&*image_surface));\n im_data.set(1);\n REQUIRE( (unsigned)im_data(0,0) == unsigned(1) );\n \/\/ Should set back to fully transparent\n mapnik::cairo_image_to_rgba8(im_data, image_surface);\n REQUIRE( (unsigned)im_data(0,0) == unsigned(0) );\n#endif\n\n#if defined(HAVE_PNG)\n should_throw = \".\/test\/data\/images\/blank.png\";\n REQUIRE( mapnik::util::exists( should_throw ) );\n type = mapnik::type_from_filename(should_throw);\n REQUIRE( type );\n REQUIRE_THROWS(std::unique_ptr reader(mapnik::get_image_reader(should_throw,*type)));\n\n should_throw = \".\/test\/data\/images\/xcode-CgBI.png\";\n REQUIRE( mapnik::util::exists( should_throw ) );\n type = mapnik::type_from_filename(should_throw);\n REQUIRE( type );\n REQUIRE_THROWS(std::unique_ptr reader(mapnik::get_image_reader(should_throw,*type)));\n#endif\n\n#if defined(HAVE_TIFF)\n should_throw = \".\/test\/data\/images\/blank.tiff\";\n REQUIRE( mapnik::util::exists( should_throw ) );\n type = mapnik::type_from_filename(should_throw);\n REQUIRE( type );\n REQUIRE_THROWS(std::unique_ptr reader(mapnik::get_image_reader(should_throw,*type)));\n#endif\n\n#if defined(HAVE_WEBP)\n should_throw = \".\/test\/data\/images\/blank.webp\";\n REQUIRE( mapnik::util::exists( should_throw ) );\n type = mapnik::type_from_filename(should_throw);\n REQUIRE( type );\n REQUIRE_THROWS(std::unique_ptr reader(mapnik::get_image_reader(should_throw,*type)));\n#endif\n }\n catch (std::exception const & ex)\n {\n std::clog << ex.what() << \"\\n\";\n REQUIRE(false);\n }\n\n} \/\/ END SECTION\n\nSECTION(\"writers options\")\n{\n#if defined(HAVE_JPEG)\n \/\/ test we can parse both jpegXX and quality=XX options\n REQUIRE_THROWS(mapnik::detail::parse_jpeg_quality(\"jpegXX\"));\n REQUIRE_THROWS(mapnik::detail::parse_jpeg_quality(\"jpeg:quality=XX\"));\n int q0 = mapnik::detail::parse_jpeg_quality(\"jpeg50\");\n int q1 = mapnik::detail::parse_jpeg_quality(\"jpeg:quality=50\");\n REQUIRE(q0 == q1);\n#endif\n} \/\/ END SECTION\n\n\nSECTION(\"image_util : save_to_file\/save_to_stream\/save_to_string\")\n{\n mapnik::image_rgba8 im(256,256);\n std::string named_color = \"lightblue\";\n mapnik::fill(im, mapnik::color(named_color).rgba());\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n std::vector > supported_types;\n#if defined(HAVE_PNG)\n supported_types.push_back(std::make_tuple(\"png\",\"png\"));\n supported_types.push_back(std::make_tuple(\"png\",\"png24\"));\n supported_types.push_back(std::make_tuple(\"png\",\"png32\"));\n supported_types.push_back(std::make_tuple(\"png\",\"png8\"));\n supported_types.push_back(std::make_tuple(\"png\",\"png256\"));\n#endif\n#if defined(HAVE_JPEG)\n supported_types.push_back(std::make_tuple(\"jpeg\",\"jpeg\"));\n supported_types.push_back(std::make_tuple(\"jpeg\",\"jpeg80\"));\n supported_types.push_back(std::make_tuple(\"jpeg\",\"jpeg90\"));\n#endif\n#if defined(HAVE_TIFF)\n supported_types.push_back(std::make_tuple(\"tiff\",\"tiff\"));\n#endif\n#if defined(HAVE_WEBP)\n supported_types.push_back(std::make_tuple(\"webp\",\"webp\"));\n#endif\n\n REQUIRE(make_directory(\"\/tmp\/mapnik-tests\/\"));\n\n for (auto const& info : supported_types)\n {\n std::string extension;\n std::string format;\n std::tie(extension, format) = info;\n std::string filename = (boost::format(\"\/tmp\/mapnik-tests\/mapnik-%1%.%2%\") % named_color % extension).str();\n mapnik::save_to_file(im, filename);\n std::string str = mapnik::save_to_string(im, format);\n std::ostringstream ss;\n mapnik::save_to_stream(im, ss, format);\n CHECK(str.length() == ss.str().length());\n std::unique_ptr reader(mapnik::get_image_reader(filename, extension));\n unsigned w = reader->width();\n unsigned h = reader->height();\n auto im2 = reader->read(0, 0, w, h);\n CHECK(im2.size() == im.size());\n if (extension == \"png\" || extension == \"tiff\")\n {\n CHECK(0 == std::memcmp(im2.bytes(), im.bytes(), im.width() * im.height()));\n }\n if (mapnik::util::exists(filename))\n {\n mapnik::util::remove(filename);\n }\n }\n}\n} \/\/ END TEST_CASE\nfix directory assertion logic\n#include \"catch.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if defined(HAVE_CAIRO)\n#include \n#include \n#endif\n\n#pragma GCC diagnostic push\n#include \n#include \n#include \n#pragma GCC diagnostic pop\n\ninline void make_directory(std::string const& dir) {\n boost::filesystem::create_directory(dir);\n}\n\nTEST_CASE(\"image io\") {\n\nSECTION(\"readers\") {\n\n std::string should_throw;\n boost::optional type;\n try\n {\n mapnik::image_rgba8 im_og;\n auto im_size = mapnik::image_rgba8::pixel_size * im_og.width() * im_og.height();\n mapnik::detail::buffer buf(im_og.bytes(), im_size);\n mapnik::image_rgba8 im2(im_og.width(), im_og.height(), buf.data());\n CHECK( im2.bytes() == im_og.bytes() );\n#if defined(HAVE_JPEG)\n should_throw = \".\/test\/data\/images\/blank.jpg\";\n REQUIRE( mapnik::util::exists( should_throw ) );\n type = mapnik::type_from_filename(should_throw);\n REQUIRE( type );\n REQUIRE_THROWS(std::unique_ptr reader(mapnik::get_image_reader(should_throw,*type)));\n\n \/\/ actually a png so jpeg reader should throw\n should_throw = \".\/test\/data\/images\/landusepattern.jpg\";\n REQUIRE( mapnik::util::exists( should_throw ) );\n type = mapnik::type_from_filename(should_throw);\n REQUIRE( type );\n try\n {\n std::unique_ptr reader(mapnik::get_image_reader(should_throw,*type));\n REQUIRE(false);\n }\n catch (std::exception const& ex)\n {\n REQUIRE( std::string(ex.what()) == std::string(\"JPEG Reader: libjpeg could not read image: Not a JPEG file: starts with 0x89 0x50\") );\n }\n\n#endif\n\n REQUIRE_THROWS(mapnik::image_rgba8 im(-10,-10)); \/\/ should throw rather than overflow\n\n#if defined(HAVE_CAIRO)\n mapnik::cairo_surface_ptr image_surface(\n cairo_image_surface_create(CAIRO_FORMAT_ARGB32,256,257),\n mapnik::cairo_surface_closer());\n mapnik::image_rgba8 im_data(cairo_image_surface_get_width(&*image_surface), cairo_image_surface_get_height(&*image_surface));\n im_data.set(1);\n REQUIRE( (unsigned)im_data(0,0) == unsigned(1) );\n \/\/ Should set back to fully transparent\n mapnik::cairo_image_to_rgba8(im_data, image_surface);\n REQUIRE( (unsigned)im_data(0,0) == unsigned(0) );\n#endif\n\n#if defined(HAVE_PNG)\n should_throw = \".\/test\/data\/images\/blank.png\";\n REQUIRE( mapnik::util::exists( should_throw ) );\n type = mapnik::type_from_filename(should_throw);\n REQUIRE( type );\n REQUIRE_THROWS(std::unique_ptr reader(mapnik::get_image_reader(should_throw,*type)));\n\n should_throw = \".\/test\/data\/images\/xcode-CgBI.png\";\n REQUIRE( mapnik::util::exists( should_throw ) );\n type = mapnik::type_from_filename(should_throw);\n REQUIRE( type );\n REQUIRE_THROWS(std::unique_ptr reader(mapnik::get_image_reader(should_throw,*type)));\n#endif\n\n#if defined(HAVE_TIFF)\n should_throw = \".\/test\/data\/images\/blank.tiff\";\n REQUIRE( mapnik::util::exists( should_throw ) );\n type = mapnik::type_from_filename(should_throw);\n REQUIRE( type );\n REQUIRE_THROWS(std::unique_ptr reader(mapnik::get_image_reader(should_throw,*type)));\n#endif\n\n#if defined(HAVE_WEBP)\n should_throw = \".\/test\/data\/images\/blank.webp\";\n REQUIRE( mapnik::util::exists( should_throw ) );\n type = mapnik::type_from_filename(should_throw);\n REQUIRE( type );\n REQUIRE_THROWS(std::unique_ptr reader(mapnik::get_image_reader(should_throw,*type)));\n#endif\n }\n catch (std::exception const & ex)\n {\n std::clog << ex.what() << \"\\n\";\n REQUIRE(false);\n }\n\n} \/\/ END SECTION\n\nSECTION(\"writers options\")\n{\n#if defined(HAVE_JPEG)\n \/\/ test we can parse both jpegXX and quality=XX options\n REQUIRE_THROWS(mapnik::detail::parse_jpeg_quality(\"jpegXX\"));\n REQUIRE_THROWS(mapnik::detail::parse_jpeg_quality(\"jpeg:quality=XX\"));\n int q0 = mapnik::detail::parse_jpeg_quality(\"jpeg50\");\n int q1 = mapnik::detail::parse_jpeg_quality(\"jpeg:quality=50\");\n REQUIRE(q0 == q1);\n#endif\n} \/\/ END SECTION\n\n\nSECTION(\"image_util : save_to_file\/save_to_stream\/save_to_string\")\n{\n mapnik::image_rgba8 im(256,256);\n std::string named_color = \"lightblue\";\n mapnik::fill(im, mapnik::color(named_color).rgba());\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n std::vector > supported_types;\n#if defined(HAVE_PNG)\n supported_types.push_back(std::make_tuple(\"png\",\"png\"));\n supported_types.push_back(std::make_tuple(\"png\",\"png24\"));\n supported_types.push_back(std::make_tuple(\"png\",\"png32\"));\n supported_types.push_back(std::make_tuple(\"png\",\"png8\"));\n supported_types.push_back(std::make_tuple(\"png\",\"png256\"));\n#endif\n#if defined(HAVE_JPEG)\n supported_types.push_back(std::make_tuple(\"jpeg\",\"jpeg\"));\n supported_types.push_back(std::make_tuple(\"jpeg\",\"jpeg80\"));\n supported_types.push_back(std::make_tuple(\"jpeg\",\"jpeg90\"));\n#endif\n#if defined(HAVE_TIFF)\n supported_types.push_back(std::make_tuple(\"tiff\",\"tiff\"));\n#endif\n#if defined(HAVE_WEBP)\n supported_types.push_back(std::make_tuple(\"webp\",\"webp\"));\n#endif\n\n std::string directory_name(\"\/tmp\/mapnik-tests\/\");\n make_directory(directory_name);\n REQUIRE(mapnik::util::exists(directory_name));\n\n for (auto const& info : supported_types)\n {\n std::string extension;\n std::string format;\n std::tie(extension, format) = info;\n std::string filename = (boost::format(directory_name + \"mapnik-%1%.%2%\") % named_color % extension).str();\n mapnik::save_to_file(im, filename);\n std::string str = mapnik::save_to_string(im, format);\n std::ostringstream ss;\n mapnik::save_to_stream(im, ss, format);\n CHECK(str.length() == ss.str().length());\n std::unique_ptr reader(mapnik::get_image_reader(filename, extension));\n unsigned w = reader->width();\n unsigned h = reader->height();\n auto im2 = reader->read(0, 0, w, h);\n CHECK(im2.size() == im.size());\n if (extension == \"png\" || extension == \"tiff\")\n {\n CHECK(0 == std::memcmp(im2.bytes(), im.bytes(), im.width() * im.height()));\n }\n if (mapnik::util::exists(filename))\n {\n mapnik::util::remove(filename);\n }\n }\n}\n} \/\/ END TEST_CASE\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\nTEST(mixFun, absBasics) {\n using stan::math::abs;\n int a = abs(1);\n\n double b = abs(-2.3);\n\n Eigen::Matrix x(2, 3);\n x << 1, 2, 3, 4, 5, 6;\n Eigen::Matrix y = abs(x);\n\n std::vector u{1, 2, 3, 4};\n std::vector v = abs(u);\n}\n\ntemplate \nusing is_complex_and_base_ret = stan::bool_constant<\n(!stan::is_complex>>::value)\n || (stan::is_complex>>::value &&\n !stan::is_complex>>::value)>;\nTEST(mixFun, abs) {\n auto f = [](const auto& x) {\n auto xx = stan::math::abs(x);\n static_assert(is_complex_and_base_ret::value, \"NO!\");\n return xx;\n };\n stan::test::expect_common_nonzero_unary(f);\n \/\/ 0 (no derivative at 0)\n stan::test::expect_value(f, 0);\n stan::test::expect_value(f, 0.0);\n\n stan::test::expect_ad(f, -3);\n stan::test::expect_ad(f, -2);\n stan::test::expect_ad(f, 2);\n\n stan::test::expect_ad(f, -17.3);\n stan::test::expect_ad(f, -0.68);\n stan::test::expect_ad(f, 0.68);\n stan::test::expect_ad(f, 2.0);\n stan::test::expect_ad(f, 4.0);\n\n \/\/ complex tests\n for (double re : std::vector{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {\n for (double im : std::vector{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {\n stan::test::expect_ad(f, std::complex(re, im));\n }\n }\n\n \/\/ vector\n using svd_t = std::vector;\n stan::test::expect_ad(f, svd_t{});\n stan::test::expect_ad(f, svd_t{1.0});\n stan::test::expect_ad(f, svd_t{1.9, -2.3});\n\n \/\/ vector>\n using svvd_t = std::vector;\n stan::test::expect_ad(f, svvd_t{});\n stan::test::expect_ad(f, svvd_t{svd_t{}});\n stan::test::expect_ad(f, svvd_t{svd_t{1.9, 4.8}});\n stan::test::expect_ad(f, svvd_t{svd_t{1.9}, svd_t{-13.987}});\n stan::test::expect_ad(f, svvd_t{svd_t{1.9, -2.7}, svd_t{-13.987, 8.8}});\n\n \/\/ vector>\n using c_t = std::complex;\n using svc_t = std::vector;\n stan::test::expect_ad(f, svc_t{});\n stan::test::expect_ad(f, svc_t{c_t{1.0, -1.9}});\n stan::test::expect_ad(f, svc_t{c_t{1.0, -1.9}, c_t{-9.3, -128.987654}});\n\n \/\/ vector>>\n using svvc_t = std::vector;\n stan::test::expect_ad(f, svvc_t{});\n stan::test::expect_ad(f, svvc_t{{}});\n stan::test::expect_ad(f, svvc_t{svc_t{c_t{1.2, -2.3}, c_t{-32.8, 1}}});\n stan::test::expect_ad(f, svvc_t{svc_t{c_t{1.2, -2.3}, c_t{-32.8, 1}},\n svc_t{c_t{9.3, 9.4}, c_t{182, -95}}});\n\n \/\/ VectorXd\n using v_t = Eigen::VectorXd;\n v_t a0(0);\n stan::test::expect_ad(f, a0);\n stan::test::expect_ad_matvar(f, a0);\n v_t a1(1);\n a1 << 1.9;\n stan::test::expect_ad(f, a1);\n stan::test::expect_ad_matvar(f, a1);\n v_t a2(2);\n a2 << 1.9, -2.3;\n stan::test::expect_ad(f, a2);\n stan::test::expect_ad_matvar(f, a2);\n\n \/\/ RowVectorXd\n using rv_t = Eigen::RowVectorXd;\n rv_t b0(0);\n stan::test::expect_ad(f, b0);\n stan::test::expect_ad_matvar(f, b0);\n rv_t b1(1);\n b1 << 1.9;\n stan::test::expect_ad(f, b1);\n stan::test::expect_ad_matvar(f, b1);\n rv_t b2(2);\n b2 << 1.9, -2.3;\n stan::test::expect_ad(f, b2);\n stan::test::expect_ad_matvar(f, b2);\n\n \/\/ MatrixXd\n using m_t = Eigen::MatrixXd;\n m_t c0(0, 0);\n stan::test::expect_ad(f, c0);\n stan::test::expect_ad_matvar(f, c0);\n m_t c0i(0, 2);\n stan::test::expect_ad(f, c0i);\n stan::test::expect_ad_matvar(f, c0i);\n m_t c0ii(2, 0);\n stan::test::expect_ad(f, c0ii);\n stan::test::expect_ad_matvar(f, c0ii);\n m_t c2(2, 1);\n c2 << 1.3, -2.9;\n stan::test::expect_ad(f, c2);\n stan::test::expect_ad_matvar(f, c2);\n m_t c6(3, 2);\n c6 << 1.3, 2.9, -13.456, 1.898, -0.01, 1.87e21;\n stan::test::expect_ad(f, c6);\n stan::test::expect_ad_matvar(f, c6);\n\n \/\/ vector\n using av_t = std::vector;\n av_t d0;\n stan::test::expect_ad(f, d0);\n stan::test::expect_ad_matvar(f, d0);\n av_t d1{a0};\n stan::test::expect_ad(f, d1);\n stan::test::expect_ad_matvar(f, d1);\n av_t d2{a1, a2};\n stan::test::expect_ad(f, d2);\n stan::test::expect_ad_matvar(f, d2);\n\n \/\/ vector\n using arv_t = std::vector;\n arv_t e0;\n stan::test::expect_ad(f, e0);\n stan::test::expect_ad_matvar(f, e0);\n arv_t e1{b0};\n stan::test::expect_ad(f, e1);\n stan::test::expect_ad_matvar(f, e1);\n arv_t e2{b1, b2};\n stan::test::expect_ad(f, e2);\n stan::test::expect_ad_matvar(f, e2);\n\n \/\/ vector\n using am_t = std::vector;\n am_t g0;\n stan::test::expect_ad(f, g0);\n stan::test::expect_ad_matvar(f, g0);\n am_t g1{c0};\n stan::test::expect_ad(f, g1);\n stan::test::expect_ad_matvar(f, g1);\n am_t g2{c2, c6};\n stan::test::expect_ad(f, g2);\n stan::test::expect_ad_matvar(f, g2);\n\n \/\/ VectorXcd\n using vc_t = Eigen::VectorXcd;\n vc_t h0(0);\n stan::test::expect_ad(f, h0);\n vc_t h1(1);\n h1 << c_t{1.9, -1.8};\n stan::test::expect_ad(f, h1);\n vc_t h2(2);\n h2 << c_t{1.9, -1.8}, c_t{-128.7, 1.3};\n stan::test::expect_ad(f, h2);\n\n \/\/ RowVectorXcd\n using rvc_t = Eigen::RowVectorXcd;\n rvc_t j0(0);\n stan::test::expect_ad(f, j0);\n rvc_t j1(1);\n j1 << c_t{1.9, -1.8};\n stan::test::expect_ad(f, j1);\n rvc_t j2(2);\n j2 << c_t{1.9, -1.8}, c_t{-128.7, 1.3};\n stan::test::expect_ad(f, j2);\n\n \/\/ MatrixXcd\n using mc_t = Eigen::MatrixXcd;\n mc_t k0(0, 0);\n stan::test::expect_ad(f, k0);\n mc_t k2(1, 2);\n k2 << c_t{1.9, -1.8}, c_t{128.735, 128.734};\n stan::test::expect_ad(f, k2);\n mc_t k6(3, 2);\n k6 << c_t{1.9, -1.8}, c_t{-128.7, 1.3}, c_t{1, 2}, c_t{0.3, -0.5},\n c_t{-13, 125.7}, c_t{-12.5, -10.5};\n stan::test::expect_ad(f, k6);\n\n \/\/ vector\n using avc_t = std::vector;\n avc_t m0;\n stan::test::expect_ad(f, m0);\n avc_t m1{h1};\n stan::test::expect_ad(f, m1);\n avc_t m2{h1, h2};\n stan::test::expect_ad(f, m2);\n\n \/\/ vector\n using arvc_t = std::vector;\n arvc_t p0(0);\n stan::test::expect_ad(f, p0);\n arvc_t p1{j1};\n stan::test::expect_ad(f, p1);\n arvc_t p2{j1, j2};\n stan::test::expect_ad(f, p2);\n\n \/\/ vector\n using amc_t = std::vector;\n amc_t q0;\n stan::test::expect_ad(f, q0);\n amc_t q1{k2};\n stan::test::expect_ad(f, q1);\n amc_t q2{k2, k6};\n stan::test::expect_ad(f, q2);\n}\nTEST(mixFun, absReturnType) {\n \/\/ validate return types not overpromoted to complex by assignability\n std::complex a = 3;\n stan::math::var b = abs(a);\n\n std::complex> c = 3;\n stan::math::fvar d = abs(c);\n SUCCEED();\n}\n\nTEST(mathMixMatFun, abs_varmat) {\n using stan::math::vec_concat;\n using stan::test::expect_ad_vector_matvar;\n using stan::test::internal::common_nonzero_args;\n auto f = [](const auto& x1) {\n using stan::math::abs;\n return abs(x1);\n };\n std::vector com_args = common_nonzero_args();\n std::vector args{-3, 2, -0.68, 1};\n auto all_args = vec_concat(com_args, args);\n Eigen::VectorXd A(all_args.size());\n for (int i = 0; i < all_args.size(); ++i) {\n A(i) = all_args[i];\n }\n expect_ad_vector_matvar(f, A);\n}\nwording fix#include \n#include \n#include \n#include \n#include \n\nTEST(mixFun, absBasics) {\n using stan::math::abs;\n int a = abs(1);\n\n double b = abs(-2.3);\n\n Eigen::Matrix x(2, 3);\n x << 1, 2, 3, 4, 5, 6;\n Eigen::Matrix y = abs(x);\n\n std::vector u{1, 2, 3, 4};\n std::vector v = abs(u);\n}\n\ntemplate \nusing is_complex_and_base_ret = stan::bool_constant<\n(!stan::is_complex>>::value)\n || (stan::is_complex>>::value &&\n !stan::is_complex>>::value)>;\nTEST(mixFun, abs) {\n auto f = [](const auto& x) {\n auto xx = stan::math::abs(x);\n static_assert(is_complex_and_base_ret::value, \"if x is complex the return must not be T!\");\n return xx;\n };\n stan::test::expect_common_nonzero_unary(f);\n \/\/ 0 (no derivative at 0)\n stan::test::expect_value(f, 0);\n stan::test::expect_value(f, 0.0);\n\n stan::test::expect_ad(f, -3);\n stan::test::expect_ad(f, -2);\n stan::test::expect_ad(f, 2);\n\n stan::test::expect_ad(f, -17.3);\n stan::test::expect_ad(f, -0.68);\n stan::test::expect_ad(f, 0.68);\n stan::test::expect_ad(f, 2.0);\n stan::test::expect_ad(f, 4.0);\n\n \/\/ complex tests\n for (double re : std::vector{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {\n for (double im : std::vector{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {\n stan::test::expect_ad(f, std::complex(re, im));\n }\n }\n\n \/\/ vector\n using svd_t = std::vector;\n stan::test::expect_ad(f, svd_t{});\n stan::test::expect_ad(f, svd_t{1.0});\n stan::test::expect_ad(f, svd_t{1.9, -2.3});\n\n \/\/ vector>\n using svvd_t = std::vector;\n stan::test::expect_ad(f, svvd_t{});\n stan::test::expect_ad(f, svvd_t{svd_t{}});\n stan::test::expect_ad(f, svvd_t{svd_t{1.9, 4.8}});\n stan::test::expect_ad(f, svvd_t{svd_t{1.9}, svd_t{-13.987}});\n stan::test::expect_ad(f, svvd_t{svd_t{1.9, -2.7}, svd_t{-13.987, 8.8}});\n\n \/\/ vector>\n using c_t = std::complex;\n using svc_t = std::vector;\n stan::test::expect_ad(f, svc_t{});\n stan::test::expect_ad(f, svc_t{c_t{1.0, -1.9}});\n stan::test::expect_ad(f, svc_t{c_t{1.0, -1.9}, c_t{-9.3, -128.987654}});\n\n \/\/ vector>>\n using svvc_t = std::vector;\n stan::test::expect_ad(f, svvc_t{});\n stan::test::expect_ad(f, svvc_t{{}});\n stan::test::expect_ad(f, svvc_t{svc_t{c_t{1.2, -2.3}, c_t{-32.8, 1}}});\n stan::test::expect_ad(f, svvc_t{svc_t{c_t{1.2, -2.3}, c_t{-32.8, 1}},\n svc_t{c_t{9.3, 9.4}, c_t{182, -95}}});\n\n \/\/ VectorXd\n using v_t = Eigen::VectorXd;\n v_t a0(0);\n stan::test::expect_ad(f, a0);\n stan::test::expect_ad_matvar(f, a0);\n v_t a1(1);\n a1 << 1.9;\n stan::test::expect_ad(f, a1);\n stan::test::expect_ad_matvar(f, a1);\n v_t a2(2);\n a2 << 1.9, -2.3;\n stan::test::expect_ad(f, a2);\n stan::test::expect_ad_matvar(f, a2);\n\n \/\/ RowVectorXd\n using rv_t = Eigen::RowVectorXd;\n rv_t b0(0);\n stan::test::expect_ad(f, b0);\n stan::test::expect_ad_matvar(f, b0);\n rv_t b1(1);\n b1 << 1.9;\n stan::test::expect_ad(f, b1);\n stan::test::expect_ad_matvar(f, b1);\n rv_t b2(2);\n b2 << 1.9, -2.3;\n stan::test::expect_ad(f, b2);\n stan::test::expect_ad_matvar(f, b2);\n\n \/\/ MatrixXd\n using m_t = Eigen::MatrixXd;\n m_t c0(0, 0);\n stan::test::expect_ad(f, c0);\n stan::test::expect_ad_matvar(f, c0);\n m_t c0i(0, 2);\n stan::test::expect_ad(f, c0i);\n stan::test::expect_ad_matvar(f, c0i);\n m_t c0ii(2, 0);\n stan::test::expect_ad(f, c0ii);\n stan::test::expect_ad_matvar(f, c0ii);\n m_t c2(2, 1);\n c2 << 1.3, -2.9;\n stan::test::expect_ad(f, c2);\n stan::test::expect_ad_matvar(f, c2);\n m_t c6(3, 2);\n c6 << 1.3, 2.9, -13.456, 1.898, -0.01, 1.87e21;\n stan::test::expect_ad(f, c6);\n stan::test::expect_ad_matvar(f, c6);\n\n \/\/ vector\n using av_t = std::vector;\n av_t d0;\n stan::test::expect_ad(f, d0);\n stan::test::expect_ad_matvar(f, d0);\n av_t d1{a0};\n stan::test::expect_ad(f, d1);\n stan::test::expect_ad_matvar(f, d1);\n av_t d2{a1, a2};\n stan::test::expect_ad(f, d2);\n stan::test::expect_ad_matvar(f, d2);\n\n \/\/ vector\n using arv_t = std::vector;\n arv_t e0;\n stan::test::expect_ad(f, e0);\n stan::test::expect_ad_matvar(f, e0);\n arv_t e1{b0};\n stan::test::expect_ad(f, e1);\n stan::test::expect_ad_matvar(f, e1);\n arv_t e2{b1, b2};\n stan::test::expect_ad(f, e2);\n stan::test::expect_ad_matvar(f, e2);\n\n \/\/ vector\n using am_t = std::vector;\n am_t g0;\n stan::test::expect_ad(f, g0);\n stan::test::expect_ad_matvar(f, g0);\n am_t g1{c0};\n stan::test::expect_ad(f, g1);\n stan::test::expect_ad_matvar(f, g1);\n am_t g2{c2, c6};\n stan::test::expect_ad(f, g2);\n stan::test::expect_ad_matvar(f, g2);\n\n \/\/ VectorXcd\n using vc_t = Eigen::VectorXcd;\n vc_t h0(0);\n stan::test::expect_ad(f, h0);\n vc_t h1(1);\n h1 << c_t{1.9, -1.8};\n stan::test::expect_ad(f, h1);\n vc_t h2(2);\n h2 << c_t{1.9, -1.8}, c_t{-128.7, 1.3};\n stan::test::expect_ad(f, h2);\n\n \/\/ RowVectorXcd\n using rvc_t = Eigen::RowVectorXcd;\n rvc_t j0(0);\n stan::test::expect_ad(f, j0);\n rvc_t j1(1);\n j1 << c_t{1.9, -1.8};\n stan::test::expect_ad(f, j1);\n rvc_t j2(2);\n j2 << c_t{1.9, -1.8}, c_t{-128.7, 1.3};\n stan::test::expect_ad(f, j2);\n\n \/\/ MatrixXcd\n using mc_t = Eigen::MatrixXcd;\n mc_t k0(0, 0);\n stan::test::expect_ad(f, k0);\n mc_t k2(1, 2);\n k2 << c_t{1.9, -1.8}, c_t{128.735, 128.734};\n stan::test::expect_ad(f, k2);\n mc_t k6(3, 2);\n k6 << c_t{1.9, -1.8}, c_t{-128.7, 1.3}, c_t{1, 2}, c_t{0.3, -0.5},\n c_t{-13, 125.7}, c_t{-12.5, -10.5};\n stan::test::expect_ad(f, k6);\n\n \/\/ vector\n using avc_t = std::vector;\n avc_t m0;\n stan::test::expect_ad(f, m0);\n avc_t m1{h1};\n stan::test::expect_ad(f, m1);\n avc_t m2{h1, h2};\n stan::test::expect_ad(f, m2);\n\n \/\/ vector\n using arvc_t = std::vector;\n arvc_t p0(0);\n stan::test::expect_ad(f, p0);\n arvc_t p1{j1};\n stan::test::expect_ad(f, p1);\n arvc_t p2{j1, j2};\n stan::test::expect_ad(f, p2);\n\n \/\/ vector\n using amc_t = std::vector;\n amc_t q0;\n stan::test::expect_ad(f, q0);\n amc_t q1{k2};\n stan::test::expect_ad(f, q1);\n amc_t q2{k2, k6};\n stan::test::expect_ad(f, q2);\n}\nTEST(mixFun, absReturnType) {\n \/\/ validate return types not overpromoted to complex by assignability\n std::complex a = 3;\n stan::math::var b = abs(a);\n\n std::complex> c = 3;\n stan::math::fvar d = abs(c);\n SUCCEED();\n}\n\nTEST(mathMixMatFun, abs_varmat) {\n using stan::math::vec_concat;\n using stan::test::expect_ad_vector_matvar;\n using stan::test::internal::common_nonzero_args;\n auto f = [](const auto& x1) {\n using stan::math::abs;\n return abs(x1);\n };\n std::vector com_args = common_nonzero_args();\n std::vector args{-3, 2, -0.68, 1};\n auto all_args = vec_concat(com_args, args);\n Eigen::VectorXd A(all_args.size());\n for (int i = 0; i < all_args.size(); ++i) {\n A(i) = all_args[i];\n }\n expect_ad_vector_matvar(f, A);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2020 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/tracing\/core\/data_source_config.h\"\n#include \"src\/base\/test\/test_task_runner.h\"\n#include \"test\/cts\/utils.h\"\n#include \"test\/gtest_and_gmock.h\"\n#include \"test\/test_helper.h\"\n\n#include \"protos\/perfetto\/config\/profiling\/perf_event_config.gen.h\"\n#include \"protos\/perfetto\/trace\/profiling\/profile_common.gen.h\"\n#include \"protos\/perfetto\/trace\/profiling\/profile_packet.gen.h\"\n#include \"protos\/perfetto\/trace\/trace_packet.gen.h\"\n\nnamespace perfetto {\nnamespace {\n\n\/\/ Skip these tests if the device in question doesn't have the necessary kernel\n\/\/ LSM hooks in perf_event_open. This comes up when a device with an older\n\/\/ kernel upgrades to R.\nbool HasPerfLsmHooks() {\n char buf[PROP_VALUE_MAX + 1] = {};\n int ret = __system_property_get(\"sys.init.perf_lsm_hooks\", buf);\n PERFETTO_CHECK(ret >= 0);\n return std::string(buf) == \"1\";\n}\n\nstd::vector ProfileSystemWide(std::string app_name) {\n base::TestTaskRunner task_runner;\n\n \/\/ (re)start the target app's main activity\n if (IsAppRunning(app_name)) {\n StopApp(app_name, \"old.app.stopped\", &task_runner);\n task_runner.RunUntilCheckpoint(\"old.app.stopped\", 1000 \/*ms*\/);\n }\n StartAppActivity(app_name, \"BusyWaitActivity\", \"target.app.running\",\n &task_runner,\n \/*delay_ms=*\/100);\n task_runner.RunUntilCheckpoint(\"target.app.running\", 1000 \/*ms*\/);\n\n \/\/ set up tracing\n TestHelper helper(&task_runner);\n helper.ConnectConsumer();\n helper.WaitForConsumerConnect();\n\n TraceConfig trace_config;\n trace_config.add_buffers()->set_size_kb(20 * 1024);\n trace_config.set_duration_ms(3000);\n trace_config.set_data_source_stop_timeout_ms(8000);\n\n auto* ds_config = trace_config.add_data_sources()->mutable_config();\n ds_config->set_name(\"linux.perf\");\n ds_config->set_target_buffer(0);\n\n protos::gen::PerfEventConfig perf_config;\n\n perf_config.set_all_cpus(true);\n perf_config.set_sampling_frequency(10); \/\/ Hz\n ds_config->set_perf_event_config_raw(perf_config.SerializeAsString());\n\n \/\/ start tracing\n helper.StartTracing(trace_config);\n helper.WaitForTracingDisabled(15000 \/*ms*\/);\n helper.ReadData();\n helper.WaitForReadData();\n\n return helper.trace();\n}\n\nvoid AssertHasSampledStacksForPid(std::vector packets,\n int target_pid) {\n ASSERT_GT(packets.size(), 0u);\n\n int total_perf_packets = 0;\n int total_samples = 0;\n int target_samples = 0;\n for (const auto& packet : packets) {\n if (!packet.has_perf_sample())\n continue;\n\n total_perf_packets++;\n EXPECT_GT(packet.timestamp(), 0u) << \"all packets should have a timestamp\";\n const auto& sample = packet.perf_sample();\n if (sample.has_kernel_records_lost())\n continue;\n if (sample.has_sample_skipped_reason())\n continue;\n\n total_samples++;\n EXPECT_GT(sample.tid(), 0u);\n EXPECT_GT(sample.callstack_iid(), 0u);\n\n if (sample.pid() == static_cast(target_pid))\n target_samples++;\n }\n\n EXPECT_GT(target_samples, 0) << \"packets.size(): \" << packets.size()\n << \", total_perf_packets: \" << total_perf_packets\n << \", total_samples: \" << total_samples << \"\\n\";\n}\n\nvoid AssertNoStacksForPid(std::vector packets,\n int target_pid) {\n \/\/ The process can still be sampled, but the stacks should be discarded\n \/\/ without unwinding.\n for (const auto& packet : packets) {\n if (packet.perf_sample().pid() == static_cast(target_pid)) {\n EXPECT_EQ(packet.perf_sample().callstack_iid(), 0u);\n EXPECT_TRUE(packet.perf_sample().has_sample_skipped_reason());\n }\n }\n}\n\nTEST(TracedPerfCtsTest, SystemWideDebuggableApp) {\n if (!HasPerfLsmHooks())\n return;\n\n std::string app_name = \"android.perfetto.cts.app.debuggable\";\n const auto& packets = ProfileSystemWide(app_name);\n int app_pid = PidForProcessName(app_name);\n ASSERT_GT(app_pid, 0) << \"failed to find pid for target process\";\n\n AssertHasSampledStacksForPid(packets, app_pid);\n StopApp(app_name);\n}\n\nTEST(TracedPerfCtsTest, SystemWideProfileableApp) {\n if (!HasPerfLsmHooks())\n return;\n\n std::string app_name = \"android.perfetto.cts.app.profileable\";\n const auto& packets = ProfileSystemWide(app_name);\n int app_pid = PidForProcessName(app_name);\n ASSERT_GT(app_pid, 0) << \"failed to find pid for target process\";\n\n AssertHasSampledStacksForPid(packets, app_pid);\n StopApp(app_name);\n}\n\nTEST(TracedPerfCtsTest, SystemWideReleaseApp) {\n if (!HasPerfLsmHooks())\n return;\n\n std::string app_name = \"android.perfetto.cts.app.release\";\n const auto& packets = ProfileSystemWide(app_name);\n int app_pid = PidForProcessName(app_name);\n ASSERT_GT(app_pid, 0) << \"failed to find pid for target process\";\n\n if (IsDebuggableBuild())\n AssertHasSampledStacksForPid(packets, app_pid);\n else\n AssertNoStacksForPid(packets, app_pid);\n\n StopApp(app_name);\n}\n\n} \/\/ namespace\n} \/\/ namespace perfetto\nUse GTEST_SKIP when skipping perf cts tests\/*\n * Copyright (C) 2020 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/tracing\/core\/data_source_config.h\"\n#include \"src\/base\/test\/test_task_runner.h\"\n#include \"test\/cts\/utils.h\"\n#include \"test\/gtest_and_gmock.h\"\n#include \"test\/test_helper.h\"\n\n#include \"protos\/perfetto\/config\/profiling\/perf_event_config.gen.h\"\n#include \"protos\/perfetto\/trace\/profiling\/profile_common.gen.h\"\n#include \"protos\/perfetto\/trace\/profiling\/profile_packet.gen.h\"\n#include \"protos\/perfetto\/trace\/trace_packet.gen.h\"\n\nnamespace perfetto {\nnamespace {\n\n\/\/ Skip these tests if the device in question doesn't have the necessary kernel\n\/\/ LSM hooks in perf_event_open. This comes up when a device with an older\n\/\/ kernel upgrades to R.\nbool HasPerfLsmHooks() {\n char buf[PROP_VALUE_MAX + 1] = {};\n int ret = __system_property_get(\"sys.init.perf_lsm_hooks\", buf);\n PERFETTO_CHECK(ret >= 0);\n return std::string(buf) == \"1\";\n}\n\nstd::vector ProfileSystemWide(std::string app_name) {\n base::TestTaskRunner task_runner;\n\n \/\/ (re)start the target app's main activity\n if (IsAppRunning(app_name)) {\n StopApp(app_name, \"old.app.stopped\", &task_runner);\n task_runner.RunUntilCheckpoint(\"old.app.stopped\", 1000 \/*ms*\/);\n }\n StartAppActivity(app_name, \"BusyWaitActivity\", \"target.app.running\",\n &task_runner,\n \/*delay_ms=*\/100);\n task_runner.RunUntilCheckpoint(\"target.app.running\", 1000 \/*ms*\/);\n\n \/\/ set up tracing\n TestHelper helper(&task_runner);\n helper.ConnectConsumer();\n helper.WaitForConsumerConnect();\n\n TraceConfig trace_config;\n trace_config.add_buffers()->set_size_kb(20 * 1024);\n trace_config.set_duration_ms(3000);\n trace_config.set_data_source_stop_timeout_ms(8000);\n\n auto* ds_config = trace_config.add_data_sources()->mutable_config();\n ds_config->set_name(\"linux.perf\");\n ds_config->set_target_buffer(0);\n\n protos::gen::PerfEventConfig perf_config;\n\n perf_config.set_all_cpus(true);\n perf_config.set_sampling_frequency(10); \/\/ Hz\n ds_config->set_perf_event_config_raw(perf_config.SerializeAsString());\n\n \/\/ start tracing\n helper.StartTracing(trace_config);\n helper.WaitForTracingDisabled(15000 \/*ms*\/);\n helper.ReadData();\n helper.WaitForReadData();\n\n return helper.trace();\n}\n\nvoid AssertHasSampledStacksForPid(std::vector packets,\n int target_pid) {\n ASSERT_GT(packets.size(), 0u);\n\n int total_perf_packets = 0;\n int total_samples = 0;\n int target_samples = 0;\n for (const auto& packet : packets) {\n if (!packet.has_perf_sample())\n continue;\n\n total_perf_packets++;\n EXPECT_GT(packet.timestamp(), 0u) << \"all packets should have a timestamp\";\n const auto& sample = packet.perf_sample();\n if (sample.has_kernel_records_lost())\n continue;\n if (sample.has_sample_skipped_reason())\n continue;\n\n total_samples++;\n EXPECT_GT(sample.tid(), 0u);\n EXPECT_GT(sample.callstack_iid(), 0u);\n\n if (sample.pid() == static_cast(target_pid))\n target_samples++;\n }\n\n EXPECT_GT(target_samples, 0) << \"packets.size(): \" << packets.size()\n << \", total_perf_packets: \" << total_perf_packets\n << \", total_samples: \" << total_samples << \"\\n\";\n}\n\nvoid AssertNoStacksForPid(std::vector packets,\n int target_pid) {\n \/\/ The process can still be sampled, but the stacks should be discarded\n \/\/ without unwinding.\n for (const auto& packet : packets) {\n if (packet.perf_sample().pid() == static_cast(target_pid)) {\n EXPECT_EQ(packet.perf_sample().callstack_iid(), 0u);\n EXPECT_TRUE(packet.perf_sample().has_sample_skipped_reason());\n }\n }\n}\n\nTEST(TracedPerfCtsTest, SystemWideDebuggableApp) {\n if (!HasPerfLsmHooks())\n GTEST_SKIP() << \"skipped due to lack of perf_event_open LSM hooks\";\n\n std::string app_name = \"android.perfetto.cts.app.debuggable\";\n const auto& packets = ProfileSystemWide(app_name);\n int app_pid = PidForProcessName(app_name);\n ASSERT_GT(app_pid, 0) << \"failed to find pid for target process\";\n\n AssertHasSampledStacksForPid(packets, app_pid);\n StopApp(app_name);\n}\n\nTEST(TracedPerfCtsTest, SystemWideProfileableApp) {\n if (!HasPerfLsmHooks())\n GTEST_SKIP() << \"skipped due to lack of perf_event_open LSM hooks\";\n\n std::string app_name = \"android.perfetto.cts.app.profileable\";\n const auto& packets = ProfileSystemWide(app_name);\n int app_pid = PidForProcessName(app_name);\n ASSERT_GT(app_pid, 0) << \"failed to find pid for target process\";\n\n AssertHasSampledStacksForPid(packets, app_pid);\n StopApp(app_name);\n}\n\nTEST(TracedPerfCtsTest, SystemWideReleaseApp) {\n if (!HasPerfLsmHooks())\n GTEST_SKIP() << \"skipped due to lack of perf_event_open LSM hooks\";\n\n std::string app_name = \"android.perfetto.cts.app.release\";\n const auto& packets = ProfileSystemWide(app_name);\n int app_pid = PidForProcessName(app_name);\n ASSERT_GT(app_pid, 0) << \"failed to find pid for target process\";\n\n if (IsDebuggableBuild())\n AssertHasSampledStacksForPid(packets, app_pid);\n else\n AssertNoStacksForPid(packets, app_pid);\n\n StopApp(app_name);\n}\n\n} \/\/ namespace\n} \/\/ namespace perfetto\n<|endoftext|>"} {"text":"#include \"FanController.h\"\n\nFanController::FanController(Servo _yaw, Servo _pitch):\n yaw(_yaw),\n pitch(_pitch){\n \n }\n\nvoid FanController::initialize(){\n \n}\n\nvoid FanController::up(){\n \n}\n\nvoid FanController::down(){\n \n}\n\nvoid FanController::left(){\n \n}\n\nvoid FanController::right(){\n \n}\n\n\nthis is not for the robot#include \"FanController.h\"\n\nFanController::FanController(Servo _yaw, Servo _pitch):\n yaw(_yaw),\n pitch(_pitch){\n \n }\n\nvoid FanController::initialize(){\n \n}\n\nint FanController::reportPitchAngle(){\n \n}\n\nint FanController::reportYawAngle(){\n \n}\n\nfloat FanController::getCandleDistance(){\n \n}\n\nboolean FanController::findCandle(){\n \n}\n\nvoid FanController::up(){\n \n}\n\nvoid FanController::down(){\n \n}\n\nvoid FanController::left(){\n \n}\n\nvoid FanController::right(){\n \n}\n\n\n<|endoftext|>"} {"text":"#include \"kwm.h\"\n#include \n\nkwm_code KWMCode;\nexport_table ExportTable;\nstd::string KwmFilePath;\nstd::string HotkeySOFullFilePath;\n\nstd::vector DisplayLst;\nstd::vector WindowLst;\nstd::map > SpacesOfWindow;\nint CurrentSpace = 0;\nint PrevSpace = -1;\n\nProcessSerialNumber FocusedPSN;\nAXUIElementRef FocusedWindowRef;\nwindow_info *FocusedWindow;\nint MarkedWindowID = -1;\n\nuint32_t MaxDisplayCount = 5;\nuint32_t ActiveDisplaysCount;\nCGDirectDisplayID ActiveDisplays[5];\n\npthread_t BackgroundThread;\n\nCGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)\n{\n switch(Type)\n {\n case kCGEventKeyDown:\n {\n CGEventFlags Flags = CGEventGetFlags(Event);\n bool CmdKey = (Flags & kCGEventFlagMaskCommand) == kCGEventFlagMaskCommand;\n bool AltKey = (Flags & kCGEventFlagMaskAlternate) == kCGEventFlagMaskAlternate;\n bool CtrlKey = (Flags & kCGEventFlagMaskControl) == kCGEventFlagMaskControl;\n CGKeyCode Keycode = (CGKeyCode)CGEventGetIntegerValueField(Event, kCGKeyboardEventKeycode);\n\n std::string NewHotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());\n if(NewHotkeySOFileTime != KWMCode.HotkeySOFileTime)\n {\n DEBUG(\"Reloading hotkeys.so\")\n UnloadKwmCode(&KWMCode);\n KWMCode = LoadKwmCode();\n }\n\n if(KWMCode.IsValid)\n {\n \/\/ Toggle keytap on | off\n if(KWMCode.KWMHotkeyCommands(&ExportTable, CmdKey, CtrlKey, AltKey, Keycode))\n return NULL;\n\n \/\/ capture custom hotkeys\n if(KWMCode.CustomHotkeyCommands(&ExportTable, CmdKey, CtrlKey, AltKey, Keycode))\n return NULL;\n\n \/\/ Let system hotkeys pass through as normal\n if(KWMCode.SystemHotkeyCommands(&ExportTable, CmdKey, CtrlKey, AltKey, Keycode))\n return Event;\n }\n\n if(ExportTable.KwmFocusMode == FocusFollowsMouse)\n {\n CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);\n CGEventPostToPSN(&FocusedPSN, Event);\n return NULL;\n }\n } break;\n case kCGEventMouseMoved:\n {\n if(ExportTable.KwmFocusMode != FocusDisabled)\n {\n FocusWindowBelowCursor();\n }\n } break;\n }\n\n return Event;\n}\n\nkwm_code LoadKwmCode()\n{\n kwm_code Code = {};\n\n Code.HotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());\n Code.KwmHotkeySO = dlopen(HotkeySOFullFilePath.c_str(), RTLD_LAZY);\n if(Code.KwmHotkeySO)\n {\n Code.KWMHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, \"KWMHotkeyCommands\");\n Code.SystemHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, \"SystemHotkeyCommands\");\n Code.CustomHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, \"CustomHotkeyCommands\");\n }\n else\n {\n DEBUG(\"LoadKwmCode() Could not open '\" << HotkeySOFullFilePath << \"'\")\n }\n\n Code.IsValid = (Code.KWMHotkeyCommands && Code.SystemHotkeyCommands && Code.CustomHotkeyCommands);\n return Code;\n}\n\nvoid UnloadKwmCode(kwm_code *Code)\n{\n if(Code->KwmHotkeySO)\n {\n dlclose(Code->KwmHotkeySO);\n }\n\n Code->HotkeySOFileTime = \"\";\n Code->KWMHotkeyCommands = 0;\n Code->SystemHotkeyCommands = 0;\n Code->CustomHotkeyCommands = 0;\n Code->IsValid = 0;\n}\n\nstd::string KwmGetFileTime(const char *File)\n{\n struct stat attr;\n stat(File, &attr);\n\n return ctime(&attr.st_mtime);\n}\n\nvoid BuildExportTable()\n{\n ExportTable.KwmFilePath = KwmFilePath;\n ExportTable.KwmFocusMode = FocusAutoraise;;\n ExportTable.FocusedWindowRef = FocusedWindowRef;\n ExportTable.FocusedWindow = FocusedWindow;\n\n ExportTable.FocusWindowBelowCursor = &FocusWindowBelowCursor;\n ExportTable.SetWindowDimensions = &SetWindowDimensions;\n ExportTable.ToggleFocusedWindowFullscreen = &ToggleFocusedWindowFullscreen;\n ExportTable.SwapFocusedWindowWithNearest = &SwapFocusedWindowWithNearest;\n ExportTable.ShiftWindowFocus = &ShiftWindowFocus;\n ExportTable.CycleFocusedWindowDisplay = &CycleFocusedWindowDisplay;\n ExportTable.AddWindowToTree = &AddWindowToTree;\n ExportTable.RemoveWindowFromTree = &RemoveWindowFromTree;\n ExportTable.MarkWindowContainer = &MarkWindowContainer;\n ExportTable.KwmRestart = &KwmRestart;\n}\n\nvoid KwmRestart()\n{\n DEBUG(\"KWM Restarting..\")\n const char **ExecArgs = new const char*[2];\n ExecArgs[0] = \"kwm\";\n ExecArgs[1] = NULL;\n std::string KwmBinPath = KwmFilePath + \"\/kwm\";\n execv(KwmBinPath.c_str(), (char**)ExecArgs);\n}\n\nvoid * KwmWindowMonitor(void*)\n{\n while(1)\n {\n DEBUG(\"KwmWindowMonitor()\")\n UpdateWindowTree();\n usleep(200000);\n }\n}\n\nvoid KwmInit()\n{\n if(!CheckPrivileges())\n Fatal(\"Could not access OSX Accessibility!\"); \n\n KwmFilePath = getcwd(NULL, 0);\n HotkeySOFullFilePath = KwmFilePath + \"\/hotkeys.so\";\n \n KWMCode = LoadKwmCode();\n BuildExportTable();\n\n GetActiveSpaces();\n GetActiveDisplays();\n\n UpdateWindowTree();\n FocusWindowBelowCursor();\n\n pthread_create(&BackgroundThread, NULL, &KwmWindowMonitor, NULL);\n}\n\nbool CheckPrivileges()\n{\n const void * Keys[] = { kAXTrustedCheckOptionPrompt };\n const void * Values[] = { kCFBooleanTrue };\n\n CFDictionaryRef Options;\n Options = CFDictionaryCreate(kCFAllocatorDefault, \n Keys, Values, sizeof(Keys) \/ sizeof(*Keys),\n &kCFCopyStringDictionaryKeyCallBacks,\n &kCFTypeDictionaryValueCallBacks);\n\n return AXIsProcessTrustedWithOptions(Options);\n}\n\nvoid Fatal(const std::string &Err)\n{\n std::cout << Err << std::endl;\n exit(1);\n}\n\nint main(int argc, char **argv)\n{\n KwmInit();\n\n CFMachPortRef EventTap;\n CGEventMask EventMask;\n CFRunLoopSourceRef RunLoopSource;\n\n EventMask = ((1 << kCGEventKeyDown) | (1 << kCGEventMouseMoved));\n EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, EventMask, CGEventCallback, NULL);\n\n if(!EventTap || !CGEventTapIsEnabled(EventTap))\n Fatal(\"ERROR: Could not create event-tap!\");\n\n RunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, EventTap, 0);\n CFRunLoopAddSource(CFRunLoopGetCurrent(), RunLoopSource, kCFRunLoopCommonModes);\n CGEventTapEnable(EventTap, true);\n CFRunLoopRun();\n return 0;\n}\nremoved debug print to prevent random useless spam#include \"kwm.h\"\n#include \n\nkwm_code KWMCode;\nexport_table ExportTable;\nstd::string KwmFilePath;\nstd::string HotkeySOFullFilePath;\n\nstd::vector DisplayLst;\nstd::vector WindowLst;\nstd::map > SpacesOfWindow;\nint CurrentSpace = 0;\nint PrevSpace = -1;\n\nProcessSerialNumber FocusedPSN;\nAXUIElementRef FocusedWindowRef;\nwindow_info *FocusedWindow;\nint MarkedWindowID = -1;\n\nuint32_t MaxDisplayCount = 5;\nuint32_t ActiveDisplaysCount;\nCGDirectDisplayID ActiveDisplays[5];\n\npthread_t BackgroundThread;\n\nCGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)\n{\n switch(Type)\n {\n case kCGEventKeyDown:\n {\n CGEventFlags Flags = CGEventGetFlags(Event);\n bool CmdKey = (Flags & kCGEventFlagMaskCommand) == kCGEventFlagMaskCommand;\n bool AltKey = (Flags & kCGEventFlagMaskAlternate) == kCGEventFlagMaskAlternate;\n bool CtrlKey = (Flags & kCGEventFlagMaskControl) == kCGEventFlagMaskControl;\n CGKeyCode Keycode = (CGKeyCode)CGEventGetIntegerValueField(Event, kCGKeyboardEventKeycode);\n\n std::string NewHotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());\n if(NewHotkeySOFileTime != KWMCode.HotkeySOFileTime)\n {\n DEBUG(\"Reloading hotkeys.so\")\n UnloadKwmCode(&KWMCode);\n KWMCode = LoadKwmCode();\n }\n\n if(KWMCode.IsValid)\n {\n \/\/ Toggle keytap on | off\n if(KWMCode.KWMHotkeyCommands(&ExportTable, CmdKey, CtrlKey, AltKey, Keycode))\n return NULL;\n\n \/\/ capture custom hotkeys\n if(KWMCode.CustomHotkeyCommands(&ExportTable, CmdKey, CtrlKey, AltKey, Keycode))\n return NULL;\n\n \/\/ Let system hotkeys pass through as normal\n if(KWMCode.SystemHotkeyCommands(&ExportTable, CmdKey, CtrlKey, AltKey, Keycode))\n return Event;\n }\n\n if(ExportTable.KwmFocusMode == FocusFollowsMouse)\n {\n CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);\n CGEventPostToPSN(&FocusedPSN, Event);\n return NULL;\n }\n } break;\n case kCGEventMouseMoved:\n {\n if(ExportTable.KwmFocusMode != FocusDisabled)\n {\n FocusWindowBelowCursor();\n }\n } break;\n }\n\n return Event;\n}\n\nkwm_code LoadKwmCode()\n{\n kwm_code Code = {};\n\n Code.HotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());\n Code.KwmHotkeySO = dlopen(HotkeySOFullFilePath.c_str(), RTLD_LAZY);\n if(Code.KwmHotkeySO)\n {\n Code.KWMHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, \"KWMHotkeyCommands\");\n Code.SystemHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, \"SystemHotkeyCommands\");\n Code.CustomHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, \"CustomHotkeyCommands\");\n }\n else\n {\n DEBUG(\"LoadKwmCode() Could not open '\" << HotkeySOFullFilePath << \"'\")\n }\n\n Code.IsValid = (Code.KWMHotkeyCommands && Code.SystemHotkeyCommands && Code.CustomHotkeyCommands);\n return Code;\n}\n\nvoid UnloadKwmCode(kwm_code *Code)\n{\n if(Code->KwmHotkeySO)\n {\n dlclose(Code->KwmHotkeySO);\n }\n\n Code->HotkeySOFileTime = \"\";\n Code->KWMHotkeyCommands = 0;\n Code->SystemHotkeyCommands = 0;\n Code->CustomHotkeyCommands = 0;\n Code->IsValid = 0;\n}\n\nstd::string KwmGetFileTime(const char *File)\n{\n struct stat attr;\n stat(File, &attr);\n\n return ctime(&attr.st_mtime);\n}\n\nvoid BuildExportTable()\n{\n ExportTable.KwmFilePath = KwmFilePath;\n ExportTable.KwmFocusMode = FocusAutoraise;;\n ExportTable.FocusedWindowRef = FocusedWindowRef;\n ExportTable.FocusedWindow = FocusedWindow;\n\n ExportTable.FocusWindowBelowCursor = &FocusWindowBelowCursor;\n ExportTable.SetWindowDimensions = &SetWindowDimensions;\n ExportTable.ToggleFocusedWindowFullscreen = &ToggleFocusedWindowFullscreen;\n ExportTable.SwapFocusedWindowWithNearest = &SwapFocusedWindowWithNearest;\n ExportTable.ShiftWindowFocus = &ShiftWindowFocus;\n ExportTable.CycleFocusedWindowDisplay = &CycleFocusedWindowDisplay;\n ExportTable.AddWindowToTree = &AddWindowToTree;\n ExportTable.RemoveWindowFromTree = &RemoveWindowFromTree;\n ExportTable.MarkWindowContainer = &MarkWindowContainer;\n ExportTable.KwmRestart = &KwmRestart;\n}\n\nvoid KwmRestart()\n{\n DEBUG(\"KWM Restarting..\")\n const char **ExecArgs = new const char*[2];\n ExecArgs[0] = \"kwm\";\n ExecArgs[1] = NULL;\n std::string KwmBinPath = KwmFilePath + \"\/kwm\";\n execv(KwmBinPath.c_str(), (char**)ExecArgs);\n}\n\nvoid * KwmWindowMonitor(void*)\n{\n while(1)\n {\n \/\/DEBUG(\"KwmWindowMonitor()\")\n UpdateWindowTree();\n usleep(200000);\n }\n}\n\nvoid KwmInit()\n{\n if(!CheckPrivileges())\n Fatal(\"Could not access OSX Accessibility!\"); \n\n KwmFilePath = getcwd(NULL, 0);\n HotkeySOFullFilePath = KwmFilePath + \"\/hotkeys.so\";\n \n KWMCode = LoadKwmCode();\n BuildExportTable();\n\n GetActiveSpaces();\n GetActiveDisplays();\n\n UpdateWindowTree();\n FocusWindowBelowCursor();\n\n pthread_create(&BackgroundThread, NULL, &KwmWindowMonitor, NULL);\n}\n\nbool CheckPrivileges()\n{\n const void * Keys[] = { kAXTrustedCheckOptionPrompt };\n const void * Values[] = { kCFBooleanTrue };\n\n CFDictionaryRef Options;\n Options = CFDictionaryCreate(kCFAllocatorDefault, \n Keys, Values, sizeof(Keys) \/ sizeof(*Keys),\n &kCFCopyStringDictionaryKeyCallBacks,\n &kCFTypeDictionaryValueCallBacks);\n\n return AXIsProcessTrustedWithOptions(Options);\n}\n\nvoid Fatal(const std::string &Err)\n{\n std::cout << Err << std::endl;\n exit(1);\n}\n\nint main(int argc, char **argv)\n{\n KwmInit();\n\n CFMachPortRef EventTap;\n CGEventMask EventMask;\n CFRunLoopSourceRef RunLoopSource;\n\n EventMask = ((1 << kCGEventKeyDown) | (1 << kCGEventMouseMoved));\n EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, EventMask, CGEventCallback, NULL);\n\n if(!EventTap || !CGEventTapIsEnabled(EventTap))\n Fatal(\"ERROR: Could not create event-tap!\");\n\n RunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, EventTap, 0);\n CFRunLoopAddSource(CFRunLoopGetCurrent(), RunLoopSource, kCFRunLoopCommonModes);\n CGEventTapEnable(EventTap, true);\n CFRunLoopRun();\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n\/\/ with these settings it works up to size 16\ntypedef uint32_t pos_t; \/\/ increase the size of this for larger boards\nconstexpr pos_t CELL_WIDTH = 2; \/\/ number of bits per cell\n\nconstexpr pos_t CELL_MAX = (1 << CELL_WIDTH) - 1; \/\/ max value of a cell\nconstexpr pos_t MAX_SIZE = sizeof(pos_t) * 8 \/ CELL_WIDTH; \/\/ max board size\n\nenum Cell : pos_t { EMPTY = 0, BLACK = 1, WHITE = 2 };\n\nstruct Board {\n pos_t board = 0;\n inline Cell get(const pos_t pos) const { return Cell(board >> pos * CELL_WIDTH & CELL_MAX); }\n inline void set(const pos_t pos, const Cell color) {\n board ^= board & CELL_MAX << pos * CELL_WIDTH ^ color << pos * CELL_WIDTH;\n }\n bool operator==(const Board o) const { return o.board == board; }\n};\n\nstruct BoardHasher {\n size_t operator()(const Board b) const { return b.board; }\n};\n\nstruct History {\n std::unordered_set states;\n void add(const Board s) { states.insert(s); }\n bool check(const Board s) const { return states.find(s) != states.end(); }\n};\nAdd basic state and move structs#include \n#include \n\n\/\/ with these settings it works up to size 16\ntypedef uint32_t pos_t; \/\/ increase the size of this for larger boards\nconstexpr pos_t CELL_WIDTH = 2; \/\/ number of bits per cell\n\nconstexpr pos_t CELL_MAX = (1 << CELL_WIDTH) - 1; \/\/ max value of a cell\nconstexpr pos_t MAX_SIZE = sizeof(pos_t) * 8 \/ CELL_WIDTH; \/\/ max board size\n\nenum Cell : pos_t { EMPTY = 0, BLACK = 1, WHITE = 2 };\n\nstruct Board {\n pos_t board = 0;\n inline Cell get(const pos_t pos) const { return Cell(board >> pos * CELL_WIDTH & CELL_MAX); }\n inline void set(const pos_t pos, const Cell color) {\n board ^= board & CELL_MAX << pos * CELL_WIDTH ^ color << pos * CELL_WIDTH;\n }\n bool operator==(const Board o) const { return o.board == board; }\n};\n\nstruct BoardHasher {\n size_t operator()(const Board b) const { return b.board; }\n};\n\nstruct History {\n std::unordered_set states;\n void add(const Board s) { states.insert(s); }\n bool check(const Board s) const { return states.find(s) != states.end(); }\n};\n\nstruct State {\n Board board;\n History history;\n enum GameState { ALIVE, PASS, GAME_OVER } gameState;\n};\n\nstruct Move {\n Move(Cell color, pos_t position, bool pass) : color(color), position(position), pass(pass) {}\n Cell color;\n pos_t position;\n bool pass;\n};\n<|endoftext|>"} {"text":"\/**\n * Copyright (c) 2015 - The CM Authors \n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \n#include \n#include \n#include \n#include \"fnord-base\/io\/fileutil.h\"\n#include \"fnord-base\/application.h\"\n#include \"fnord-base\/logging.h\"\n#include \"fnord-base\/cli\/flagparser.h\"\n#include \"fnord-base\/util\/SimpleRateLimit.h\"\n#include \"fnord-base\/InternMap.h\"\n#include \"fnord-json\/json.h\"\n#include \"fnord-mdb\/MDB.h\"\n#include \"fnord-mdb\/MDBUtil.h\"\n#include \"fnord-sstable\/sstablereader.h\"\n#include \"fnord-sstable\/sstablewriter.h\"\n#include \"fnord-sstable\/SSTableColumnSchema.h\"\n#include \"fnord-sstable\/SSTableColumnReader.h\"\n#include \"fnord-sstable\/SSTableColumnWriter.h\"\n#include \"fnord-cstable\/BitPackedIntColumnReader.h\"\n#include \"fnord-cstable\/BitPackedIntColumnWriter.h\"\n#include \"fnord-cstable\/UInt32ColumnReader.h\"\n#include \"fnord-cstable\/UInt32ColumnWriter.h\"\n#include \"fnord-cstable\/BooleanColumnReader.h\"\n#include \"fnord-cstable\/BooleanColumnWriter.h\"\n#include \"fnord-cstable\/CSTableWriter.h\"\n#include \"fnord-cstable\/CSTableReader.h\"\n#include \"common.h\"\n#include \"CustomerNamespace.h\"\n#include \"FeatureSchema.h\"\n#include \"JoinedQuery.h\"\n#include \"CTRCounter.h\"\n#include \"analytics\/AnalyticsTableScan.h\"\n#include \"analytics\/CTRByPositionQuery.h\"\n\nusing namespace cm;\nusing namespace fnord;\n\nint main(int argc, const char** argv) {\n fnord::Application::init();\n fnord::Application::logToStderr();\n\n fnord::cli::FlagParser flags;\n\n flags.defineFlag(\n \"input_file\",\n fnord::cli::FlagParser::T_STRING,\n true,\n \"i\",\n NULL,\n \"file\",\n \"\");\n\n flags.defineFlag(\n \"output_file\",\n fnord::cli::FlagParser::T_STRING,\n true,\n \"o\",\n NULL,\n \"file\",\n \"\");\n\n flags.defineFlag(\n \"loglevel\",\n fnord::cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"\");\n\n flags.parseArgv(argc, argv);\n\n Logger::get()->setMinimumLogLevel(\n strToLogLevel(flags.getString(\"loglevel\")));\n\n size_t debug_n = 0;\n size_t debug_z = 0;\n\n \/* query level *\/\n cstable::UInt32ColumnWriter jq_time_col(1, 1);\n cstable::BitPackedIntColumnWriter jq_page_col(1, 1, 100);\n cstable::BitPackedIntColumnWriter jq_lang_col(1, 1, kMaxLanguage);\n cstable::BitPackedIntColumnWriter jq_numitems_col(1, 1, 250);\n cstable::BitPackedIntColumnWriter jq_numitemclicks_col(1, 1, 250);\n cstable::BitPackedIntColumnWriter jq_abtestgroup_col(1, 1, 100);\n cstable::BitPackedIntColumnWriter jq_devicetype_col(1, 1, kMaxDeviceType);\n cstable::BitPackedIntColumnWriter jq_pagetype_col(1, 1, kMaxPageType);\n\n \/* query item level *\/\n cstable::BitPackedIntColumnWriter jqi_position_col(2, 2, 64);\n cstable::BooleanColumnWriter jqi_clicked_col(2, 2);\n\n uint64_t r = 0;\n uint64_t n = 0;\n\n auto add_session = [&] (const cm::JoinedSession& sess) {\n ++n;\n\n for (const auto& q : sess.queries) {\n \/* queries.time *\/\n jq_time_col.addDatum(r, 1, q.time.unixMicros() \/ kMicrosPerSecond);\n\n \/* queries.num_item_clicks, queries.num_items *\/\n size_t nitems = 0;\n size_t nclicks = 0;\n for (const auto& i : q.items) {\n ++nitems;\n nclicks += i.clicked;\n }\n jq_numitems_col.addDatum(r, 1, nitems);\n jq_numitemclicks_col.addDatum(r, 1, nclicks);\n\n \/* queries.page *\/\n auto pg_str = cm::extractAttr(q.attrs, \"pg\");\n if (pg_str.isEmpty()) {\n jq_page_col.addNull(r, 1);\n } else {\n jq_page_col.addDatum(r, 1, std::stoul(pg_str.get()));\n }\n\n \/* queries.ab_test_group *\/\n auto abgrp = cm::extractABTestGroup(q.attrs);\n if (abgrp.isEmpty()) {\n jq_abtestgroup_col.addNull(r, 1);\n } else {\n jq_abtestgroup_col.addDatum(r, 1, abgrp.get());\n }\n\n \/* queries.device_type *\/\n jq_devicetype_col.addDatum(r, 1, (uint32_t) extractDeviceType(q.attrs));\n\n \/* queries.page_type *\/\n jq_pagetype_col.addDatum(r, 1, (uint32_t) extractPageType(q.attrs));\n\n \/* queries.language *\/\n auto lang = cm::extractLanguage(q.attrs);\n uint32_t l = (uint16_t) lang;\n jq_lang_col.addDatum(r, 1, l);\n\n if (q.items.size() == 0) {\n jqi_position_col.addNull(r, 1);\n jqi_clicked_col.addNull(r, 1);\n }\n\n for (const auto& i : q.items) {\n jqi_position_col.addDatum(r, 2, i.position);\n jqi_clicked_col.addDatum(r, 2, i.clicked);\n r = 2;\n }\n\n r = 1;\n }\n\n r = 0;\n };\n\n\n \/* read input tables *\/\n int row_idx = 0;\n\n const auto& sstable = flags.getString(\"input_file\");\n fnord::logInfo(\"cm.jqcolumnize\", \"Importing sstable: $0\", sstable);\n\n \/* read sstable header *\/\n sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));\n\n if (reader.bodySize() == 0) {\n fnord::logCritical(\"cm.jqcolumnize\", \"unfinished sstable: $0\", sstable);\n exit(1);\n }\n\n \/* get sstable cursor *\/\n auto cursor = reader.getCursor();\n auto body_size = reader.bodySize();\n\n \/* status line *\/\n util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {\n fnord::logInfo(\n \"cm.jqcolumnize\",\n \"[$0%] Reading sstable... rows=$1\",\n (size_t) ((cursor->position() \/ (double) body_size) * 100),\n row_idx);\n });\n\n \/* read sstable rows *\/\n for (; cursor->valid(); ++row_idx) {\n status_line.runMaybe();\n\n auto key = cursor->getKeyString();\n auto val = cursor->getDataBuffer();\n Option q;\n\n try {\n q = Some(json::fromJSON(val));\n } catch (const Exception& e) {\n fnord::logWarning(\"cm.jqcolumnize\", e, \"invalid json: $0\", val.toString());\n }\n\n if (!q.isEmpty()) {\n cm::JoinedSession s;\n s.queries.emplace_back(q.get());\n add_session(s);\n }\n\n if (!cursor->next()) {\n break;\n }\n }\n\n status_line.runForce();\n\n {\n cstable::CSTableWriter writer(flags.getString(\"output_file\") + \"~\", n);\n writer.addColumn(\"queries.time\", &jq_time_col);\n writer.addColumn(\"queries.page\", &jq_page_col);\n writer.addColumn(\"queries.language\", &jq_lang_col);\n writer.addColumn(\"queries.num_items\", &jq_numitems_col);\n writer.addColumn(\"queries.num_items_clicked\", &jq_numitemclicks_col);\n writer.addColumn(\"queries.ab_test_group\", &jq_abtestgroup_col);\n writer.addColumn(\"queries.device_type\", &jq_devicetype_col);\n writer.addColumn(\"queries.page_type\", &jq_pagetype_col);\n writer.addColumn(\"queries.items.position\", &jqi_position_col);\n writer.addColumn(\"queries.items.clicked\", &jqi_clicked_col);\n writer.commit();\n }\n\n FileUtil::mv(\n flags.getString(\"output_file\") + \"~\",\n flags.getString(\"output_file\"));\n\n \/\/{\n \/\/ cstable::CSTableReader reader(flags.getString(\"output_file\"));\n \/\/ auto t0 = WallClock::unixMicros();\n\n \/\/ cm::AnalyticsTableScan aq;\n \/\/ cm::CTRByGroupResult res;\n \/\/ cm::CTRByPositionQuery q(&aq, &res);\n \/\/ aq.scanTable(&reader);\n \/\/ auto t1 = WallClock::unixMicros();\n \/\/ fnord::iputs(\"scanned $0 rows in $1 ms\", res.rows_scanned, (t1 - t0) \/ 1000.0f);\n \/\/ for (const auto& p : res.counters) {\n \/\/ fnord::iputs(\n \/\/ \"pos: $0, views: $1, clicks: $2, ctr: $3\", \n \/\/ p.first, p.second.num_views,\n \/\/ p.second.num_clicks,\n \/\/ p.second.num_clicks \/ (double) p.second.num_views);\n \/\/ }\n \/\/}\n\n return 0;\n}\n\nindex qcat{1,2,3}\/**\n * Copyright (c) 2015 - The CM Authors \n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \n#include \n#include \n#include \n#include \"fnord-base\/io\/fileutil.h\"\n#include \"fnord-base\/application.h\"\n#include \"fnord-base\/logging.h\"\n#include \"fnord-base\/cli\/flagparser.h\"\n#include \"fnord-base\/util\/SimpleRateLimit.h\"\n#include \"fnord-base\/InternMap.h\"\n#include \"fnord-json\/json.h\"\n#include \"fnord-mdb\/MDB.h\"\n#include \"fnord-mdb\/MDBUtil.h\"\n#include \"fnord-sstable\/sstablereader.h\"\n#include \"fnord-sstable\/sstablewriter.h\"\n#include \"fnord-sstable\/SSTableColumnSchema.h\"\n#include \"fnord-sstable\/SSTableColumnReader.h\"\n#include \"fnord-sstable\/SSTableColumnWriter.h\"\n#include \"fnord-cstable\/BitPackedIntColumnReader.h\"\n#include \"fnord-cstable\/BitPackedIntColumnWriter.h\"\n#include \"fnord-cstable\/UInt32ColumnReader.h\"\n#include \"fnord-cstable\/UInt32ColumnWriter.h\"\n#include \"fnord-cstable\/BooleanColumnReader.h\"\n#include \"fnord-cstable\/BooleanColumnWriter.h\"\n#include \"fnord-cstable\/CSTableWriter.h\"\n#include \"fnord-cstable\/CSTableReader.h\"\n#include \"common.h\"\n#include \"CustomerNamespace.h\"\n#include \"FeatureSchema.h\"\n#include \"JoinedQuery.h\"\n#include \"CTRCounter.h\"\n#include \"analytics\/AnalyticsTableScan.h\"\n#include \"analytics\/CTRByPositionQuery.h\"\n\nusing namespace cm;\nusing namespace fnord;\n\nint main(int argc, const char** argv) {\n fnord::Application::init();\n fnord::Application::logToStderr();\n\n fnord::cli::FlagParser flags;\n\n flags.defineFlag(\n \"input_file\",\n fnord::cli::FlagParser::T_STRING,\n true,\n \"i\",\n NULL,\n \"file\",\n \"\");\n\n flags.defineFlag(\n \"output_file\",\n fnord::cli::FlagParser::T_STRING,\n true,\n \"o\",\n NULL,\n \"file\",\n \"\");\n\n flags.defineFlag(\n \"loglevel\",\n fnord::cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"\");\n\n flags.parseArgv(argc, argv);\n\n Logger::get()->setMinimumLogLevel(\n strToLogLevel(flags.getString(\"loglevel\")));\n\n size_t debug_n = 0;\n size_t debug_z = 0;\n\n \/* query level *\/\n cstable::UInt32ColumnWriter jq_time_col(1, 1);\n cstable::BitPackedIntColumnWriter jq_page_col(1, 1, 100);\n cstable::BitPackedIntColumnWriter jq_lang_col(1, 1, kMaxLanguage);\n cstable::BitPackedIntColumnWriter jq_numitems_col(1, 1, 250);\n cstable::BitPackedIntColumnWriter jq_numitemclicks_col(1, 1, 250);\n cstable::BitPackedIntColumnWriter jq_abtestgroup_col(1, 1, 100);\n cstable::BitPackedIntColumnWriter jq_devicetype_col(1, 1, kMaxDeviceType);\n cstable::BitPackedIntColumnWriter jq_pagetype_col(1, 1, kMaxPageType);\n cstable::BitPackedIntColumnWriter jq_cat1_col(1, 1, 0xffff);\n cstable::BitPackedIntColumnWriter jq_cat2_col(1, 1, 0xffff);\n cstable::BitPackedIntColumnWriter jq_cat3_col(1, 1, 0xffff);\n\n \/* query item level *\/\n cstable::BitPackedIntColumnWriter jqi_position_col(2, 2, 64);\n cstable::BooleanColumnWriter jqi_clicked_col(2, 2);\n\n uint64_t r = 0;\n uint64_t n = 0;\n\n auto add_session = [&] (const cm::JoinedSession& sess) {\n ++n;\n\n for (const auto& q : sess.queries) {\n \/* queries.time *\/\n jq_time_col.addDatum(r, 1, q.time.unixMicros() \/ kMicrosPerSecond);\n\n \/* queries.num_item_clicks, queries.num_items *\/\n size_t nitems = 0;\n size_t nclicks = 0;\n for (const auto& i : q.items) {\n ++nitems;\n nclicks += i.clicked;\n }\n jq_numitems_col.addDatum(r, 1, nitems);\n jq_numitemclicks_col.addDatum(r, 1, nclicks);\n\n \/* queries.page *\/\n auto pg_str = cm::extractAttr(q.attrs, \"pg\");\n if (pg_str.isEmpty()) {\n jq_page_col.addNull(r, 1);\n } else {\n jq_page_col.addDatum(r, 1, std::stoul(pg_str.get()));\n }\n\n \/* queries.ab_test_group *\/\n auto abgrp = cm::extractABTestGroup(q.attrs);\n if (abgrp.isEmpty()) {\n jq_abtestgroup_col.addNull(r, 1);\n } else {\n jq_abtestgroup_col.addDatum(r, 1, abgrp.get());\n }\n\n \/* queries.category1 *\/\n auto qcat1 = cm::extractAttr(q.attrs, \"q_cat1\");\n if (qcat1.isEmpty()) {\n jq_cat1_col.addNull(r, 1);\n } else {\n jq_cat1_col.addDatum(r, 1, std::stoul(qcat1.get()));\n }\n\n \/* queries.category2 *\/\n auto qcat2 = cm::extractAttr(q.attrs, \"q_cat2\");\n if (qcat2.isEmpty()) {\n jq_cat2_col.addNull(r, 1);\n } else {\n jq_cat2_col.addDatum(r, 1, std::stoul(qcat2.get()));\n }\n\n \/* queries.category3 *\/\n auto qcat3 = cm::extractAttr(q.attrs, \"q_cat3\");\n if (qcat3.isEmpty()) {\n jq_cat3_col.addNull(r, 1);\n } else {\n jq_cat3_col.addDatum(r, 1, std::stoul(qcat3.get()));\n }\n\n \/* queries.device_type *\/\n jq_devicetype_col.addDatum(r, 1, (uint32_t) extractDeviceType(q.attrs));\n\n \/* queries.page_type *\/\n jq_pagetype_col.addDatum(r, 1, (uint32_t) extractPageType(q.attrs));\n\n \/* queries.language *\/\n auto lang = cm::extractLanguage(q.attrs);\n uint32_t l = (uint16_t) lang;\n jq_lang_col.addDatum(r, 1, l);\n\n if (q.items.size() == 0) {\n jqi_position_col.addNull(r, 1);\n jqi_clicked_col.addNull(r, 1);\n }\n\n for (const auto& i : q.items) {\n jqi_position_col.addDatum(r, 2, i.position);\n jqi_clicked_col.addDatum(r, 2, i.clicked);\n r = 2;\n }\n\n r = 1;\n }\n\n r = 0;\n };\n\n\n \/* read input tables *\/\n int row_idx = 0;\n\n const auto& sstable = flags.getString(\"input_file\");\n fnord::logInfo(\"cm.jqcolumnize\", \"Importing sstable: $0\", sstable);\n\n \/* read sstable header *\/\n sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));\n\n if (reader.bodySize() == 0) {\n fnord::logCritical(\"cm.jqcolumnize\", \"unfinished sstable: $0\", sstable);\n exit(1);\n }\n\n \/* get sstable cursor *\/\n auto cursor = reader.getCursor();\n auto body_size = reader.bodySize();\n\n \/* status line *\/\n util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {\n fnord::logInfo(\n \"cm.jqcolumnize\",\n \"[$0%] Reading sstable... rows=$1\",\n (size_t) ((cursor->position() \/ (double) body_size) * 100),\n row_idx);\n });\n\n \/* read sstable rows *\/\n for (; cursor->valid(); ++row_idx) {\n status_line.runMaybe();\n\n auto key = cursor->getKeyString();\n auto val = cursor->getDataBuffer();\n Option q;\n\n try {\n q = Some(json::fromJSON(val));\n } catch (const Exception& e) {\n fnord::logWarning(\"cm.jqcolumnize\", e, \"invalid json: $0\", val.toString());\n }\n\n if (!q.isEmpty()) {\n cm::JoinedSession s;\n s.queries.emplace_back(q.get());\n add_session(s);\n }\n\n if (!cursor->next()) {\n break;\n }\n }\n\n status_line.runForce();\n\n {\n cstable::CSTableWriter writer(flags.getString(\"output_file\") + \"~\", n);\n writer.addColumn(\"queries.time\", &jq_time_col);\n writer.addColumn(\"queries.page\", &jq_page_col);\n writer.addColumn(\"queries.language\", &jq_lang_col);\n writer.addColumn(\"queries.num_items\", &jq_numitems_col);\n writer.addColumn(\"queries.num_items_clicked\", &jq_numitemclicks_col);\n writer.addColumn(\"queries.ab_test_group\", &jq_abtestgroup_col);\n writer.addColumn(\"queries.device_type\", &jq_devicetype_col);\n writer.addColumn(\"queries.page_type\", &jq_pagetype_col);\n writer.addColumn(\"queries.category1\", &jq_cat1_col);\n writer.addColumn(\"queries.category2\", &jq_cat2_col);\n writer.addColumn(\"queries.category3\", &jq_cat3_col);\n writer.addColumn(\"queries.items.position\", &jqi_position_col);\n writer.addColumn(\"queries.items.clicked\", &jqi_clicked_col);\n writer.commit();\n }\n\n FileUtil::mv(\n flags.getString(\"output_file\") + \"~\",\n flags.getString(\"output_file\"));\n\n \/\/{\n \/\/ cstable::CSTableReader reader(flags.getString(\"output_file\"));\n \/\/ auto t0 = WallClock::unixMicros();\n\n \/\/ cm::AnalyticsTableScan aq;\n \/\/ cm::CTRByGroupResult res;\n \/\/ cm::CTRByPositionQuery q(&aq, &res);\n \/\/ aq.scanTable(&reader);\n \/\/ auto t1 = WallClock::unixMicros();\n \/\/ fnord::iputs(\"scanned $0 rows in $1 ms\", res.rows_scanned, (t1 - t0) \/ 1000.0f);\n \/\/ for (const auto& p : res.counters) {\n \/\/ fnord::iputs(\n \/\/ \"pos: $0, views: $1, clicks: $2, ctr: $3\", \n \/\/ p.first, p.second.num_views,\n \/\/ p.second.num_clicks,\n \/\/ p.second.num_clicks \/ (double) p.second.num_views);\n \/\/ }\n \/\/}\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \"utils\/logoutput.h\"\n#include \"commandSocket.h\"\n#include \"FffProcessor.h\"\n#include \"Progress.h\"\n\n#include \n#include \n\n#include \n\n#include \/\/ stoi\n\n#ifdef _WIN32\n#include \n#endif\n\n#define DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR(x) \n\/\/ std::cerr << x;\n\nnamespace cura {\n\n#define BYTES_PER_FLOAT 4\n#define FLOATS_PER_VECTOR 3\n#define VECTORS_PER_FACE 3\n \nclass CommandSocket::Private\n{\npublic:\n Private()\n : socket(nullptr)\n , object_count(0)\n , current_sliced_object(nullptr)\n , sliced_objects(0)\n , current_layer_count(0)\n , current_layer_offset(0)\n { }\n\n cura::proto::Layer* getLayerById(int id);\n\n Arcus::Socket* socket;\n \n \/\/ Number of objects that need to be sliced\n int object_count;\n \n \/\/ Message that holds a list of sliced objects\n std::shared_ptr sliced_object_list;\n \n \/\/ Message that holds the currently sliced object (to be added to sliced_object_list)\n cura::proto::SlicedObject* current_sliced_object;\n \n \/\/ Number of sliced objects for this sliced object list\n int sliced_objects;\n\n \/\/ Number of layers sent to the front end so far\n \/\/ Used for incrementing the current layer in one at a time mode\n int current_layer_count;\n int current_layer_offset;\n \n \/\/ Ids of the sliced objects\n std::vector object_ids;\n\n std::string temp_gcode_file;\n std::ostringstream gcode_output_stream;\n \n \/\/ Print object that olds one or more meshes that need to be sliced. \n std::vector< std::shared_ptr > objects_to_slice;\n};\n\nCommandSocket::CommandSocket()\n : d(new Private)\n{\n FffProcessor::getInstance()->setCommandSocket(this);\n}\n\nvoid CommandSocket::connect(const std::string& ip, int port)\n{\n d->socket = new Arcus::Socket();\n \/\/d->socket->registerMessageType(1, &Cura::ObjectList::default_instance());\n d->socket->registerMessageType(1, &cura::proto::Slice::default_instance());\n d->socket->registerMessageType(2, &cura::proto::SlicedObjectList::default_instance());\n d->socket->registerMessageType(3, &cura::proto::Progress::default_instance());\n d->socket->registerMessageType(4, &cura::proto::GCodeLayer::default_instance());\n d->socket->registerMessageType(5, &cura::proto::ObjectPrintTime::default_instance());\n d->socket->registerMessageType(6, &cura::proto::SettingList::default_instance());\n d->socket->registerMessageType(7, &cura::proto::GCodePrefix::default_instance());\n\n d->socket->connect(ip, port);\n \n \/\/ Start & continue listening as long as socket is not closed and there is no error.\n while(d->socket->state() != Arcus::SocketState::Closed && d->socket->state() != Arcus::SocketState::Error)\n {\n \/\/If there is an object to slice, do so.\n if(d->objects_to_slice.size())\n {\n FffProcessor::getInstance()->resetFileNumber();\n for(auto object : d->objects_to_slice)\n {\n if(!FffProcessor::getInstance()->processMeshGroup(object.get()))\n {\n logError(\"Slicing mesh group failed!\");\n }\n }\n d->objects_to_slice.clear();\n FffProcessor::getInstance()->finalize();\n sendGCodeLayer();\n sendPrintTime();\n \/\/TODO: Support all-at-once\/one-at-a-time printing\n \/\/d->processor->processModel(d->object_to_slice.get());\n \/\/d->object_to_slice.reset();\n \/\/d->processor->resetFileNumber();\n\n \/\/sendPrintTime();\n }\n \n \/\/ Actually start handling messages.\n Arcus::MessagePtr message = d->socket->takeNextMessage();\n cura::proto::SettingList* setting_list = dynamic_cast(message.get());\n if(setting_list)\n {\n handleSettingList(setting_list);\n }\n\n \/*cura::proto::ObjectList* object_list = dynamic_cast(message.get());\n if(object_list)\n {\n handleObjectList(object_list);\n }*\/\n \n cura::proto::Slice* slice = dynamic_cast(message.get());\n if(slice)\n {\n \/\/ Reset object counts\n d->object_count = 0;\n d->object_ids.clear();\n for(auto object : slice->object_lists())\n {\n handleObjectList(&object);\n }\n }\n\n std::this_thread::sleep_for(std::chrono::milliseconds(250));\n\n if(!d->socket->errorString().empty()) \n {\n logError(\"%s\\n\", d->socket->errorString().data());\n d->socket->clearError();\n }\n }\n}\n\nvoid CommandSocket::handleObjectList(cura::proto::ObjectList* list)\n{\n FMatrix3x3 matrix;\n \/\/d->object_count = 0;\n \/\/d->object_ids.clear();\n d->objects_to_slice.push_back(std::make_shared(FffProcessor::getInstance()));\n MeshGroup* meshgroup = d->objects_to_slice.back().get();\n \n for(auto setting : list->settings())\n {\n meshgroup->setSetting(setting.name(), setting.value());\n }\n \n for (int extruder_nr = 0; extruder_nr < FffProcessor::getInstance()->getSettingAsCount(\"machine_extruder_count\"); extruder_nr++)\n { \/\/ initialize remaining extruder trains and load the defaults\n meshgroup->createExtruderTrain(extruder_nr)->setExtruderTrainDefaults(extruder_nr); \/\/ create new extruder train objects or use already existing ones\n }\n \n for(auto object : list->objects())\n {\n DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR(\"solid Cura_out\\n\");\n int extruder_train_nr = 0; \/\/ TODO: make primary extruder configurable!\n for(auto setting : object.settings())\n {\n if (setting.name() == \"extruder_nr\")\n {\n extruder_train_nr = std::stoi(setting.value());\n break;\n }\n }\n SettingsBase* extruder_train = meshgroup->getExtruderTrain(extruder_train_nr);\n\n meshgroup->meshes.push_back(extruder_train); \/\/Construct a new mesh (with the corresponding extruder train as settings parent object) and put it into MeshGroup's mesh list.\n Mesh& mesh = meshgroup->meshes.back();\n\n int bytes_per_face = BYTES_PER_FLOAT * FLOATS_PER_VECTOR * VECTORS_PER_FACE;\n int face_count = object.vertices().size() \/ bytes_per_face;\n for(int i = 0; i < face_count; ++i)\n {\n \/\/TODO: Apply matrix\n std::string data = object.vertices().substr(i * bytes_per_face, bytes_per_face);\n const FPoint3* float_vertices = reinterpret_cast(data.data());\n\n Point3 verts[3];\n verts[0] = matrix.apply(float_vertices[0]);\n verts[1] = matrix.apply(float_vertices[1]);\n verts[2] = matrix.apply(float_vertices[2]);\n mesh.addFace(verts[0], verts[1], verts[2]);\n\n DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR(\" facet normal -1 0 0\\n\");\n DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR(\" outer loop\\n\");\n DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR(\" vertex \"<object_ids.push_back(object.id());\n mesh.finish();\n }\n\n d->object_count++;\n meshgroup->finalize();\n}\n\nvoid CommandSocket::handleSettingList(cura::proto::SettingList* list)\n{\n for(auto setting : list->settings())\n {\n FffProcessor::getInstance()->setSetting(setting.name(), setting.value());\n }\n}\n\nvoid CommandSocket::sendLayerInfo(int layer_nr, int32_t z, int32_t height)\n{\n if(!d->current_sliced_object)\n {\n return;\n }\n \n cura::proto::Layer* layer = d->getLayerById(layer_nr);\n layer->set_height(z);\n layer->set_thickness(height);\n}\n\nvoid CommandSocket::sendPolygons(PolygonType type, int layer_nr, Polygons& polygons, int line_width)\n{\n if(!d->current_sliced_object)\n return;\n \n if (polygons.size() == 0)\n return;\n\n cura::proto::Layer* layer = d->getLayerById(layer_nr);\n\n for(unsigned int i = 0; i < polygons.size(); ++i)\n {\n cura::proto::Polygon* p = layer->add_polygons();\n p->set_type(static_cast(type));\n std::string polydata;\n polydata.append(reinterpret_cast(polygons[i].data()), polygons[i].size() * sizeof(Point));\n p->set_points(polydata);\n p->set_line_width(line_width);\n }\n}\n\nvoid CommandSocket::sendProgress(float amount)\n{\n auto message = std::make_shared();\n amount \/= d->object_count;\n amount += d->sliced_objects * (1. \/ d->object_count);\n message->set_amount(amount);\n d->socket->sendMessage(message);\n}\n\nvoid CommandSocket::sendProgressStage(Progress::Stage stage)\n{\n \/\/ TODO\n}\n\nvoid CommandSocket::sendPrintTime()\n{\n auto message = std::make_shared();\n message->set_time(FffProcessor::getInstance()->getTotalPrintTime());\n message->set_material_amount(FffProcessor::getInstance()->getTotalFilamentUsed(0));\n d->socket->sendMessage(message);\n}\n\nvoid CommandSocket::sendPrintMaterialForObject(int index, int extruder_nr, float print_time)\n{\n\/\/ socket.sendInt32(CMD_OBJECT_PRINT_MATERIAL);\n\/\/ socket.sendInt32(12);\n\/\/ socket.sendInt32(index);\n\/\/ socket.sendInt32(extruder_nr);\n\/\/ socket.sendFloat32(print_time);\n}\n\nvoid CommandSocket::beginSendSlicedObject()\n{\n if(!d->sliced_object_list)\n {\n d->sliced_object_list = std::make_shared();\n }\n\n d->current_sliced_object = d->sliced_object_list->add_objects();\n d->current_sliced_object->set_id(d->object_ids[d->sliced_objects]);\n}\n\nvoid CommandSocket::endSendSlicedObject()\n{\n d->sliced_objects++;\n d->current_layer_offset = d->current_layer_count;\n std::cout << \"End sliced object called. sliced objects \" << d->sliced_objects << \" object count: \" << d->object_count << std::endl;\n\n std::cout << \"current layer count\" << d->current_layer_count << std::endl;\n std::cout << \"current layer offset\" << d->current_layer_offset << std::endl;\n\n if(d->sliced_objects >= d->object_count)\n {\n d->socket->sendMessage(d->sliced_object_list);\n d->sliced_objects = 0;\n d->current_layer_count = 0;\n d->current_layer_offset = 0;\n d->sliced_object_list.reset();\n d->current_sliced_object = nullptr;\n }\n}\n\nvoid CommandSocket::beginGCode()\n{\n FffProcessor::getInstance()->setTargetStream(&d->gcode_output_stream);\n}\n\nvoid CommandSocket::sendGCodeLayer()\n{\n auto message = std::make_shared();\n message->set_id(d->object_ids[0]);\n message->set_data(d->gcode_output_stream.str());\n d->socket->sendMessage(message);\n \n d->gcode_output_stream.str(\"\");\n}\n\nvoid CommandSocket::sendGCodePrefix(std::string prefix)\n{\n auto message = std::make_shared();\n message->set_data(prefix);\n d->socket->sendMessage(message);\n}\n\ncura::proto::Layer* CommandSocket::Private::getLayerById(int id)\n{\n id += current_layer_offset;\n\n auto itr = std::find_if(current_sliced_object->mutable_layers()->begin(), current_sliced_object->mutable_layers()->end(), [id](cura::proto::Layer& l) { return l.id() == id; });\n\n cura::proto::Layer* layer = nullptr;\n if(itr != current_sliced_object->mutable_layers()->end())\n {\n layer = &(*itr);\n }\n else\n {\n layer = current_sliced_object->add_layers();\n layer->set_id(id);\n current_layer_count++;\n }\n\n return layer;\n}\n\n}\/\/namespace cura\nenforce single slicing by commandSocket.#include \"utils\/logoutput.h\"\n#include \"commandSocket.h\"\n#include \"FffProcessor.h\"\n#include \"Progress.h\"\n\n#include \n#include \n\n#include \n\n#include \/\/ stoi\n\n#ifdef _WIN32\n#include \n#endif\n\n#define DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR(x) \n\/\/ std::cerr << x;\n\nnamespace cura {\n\n#define BYTES_PER_FLOAT 4\n#define FLOATS_PER_VECTOR 3\n#define VECTORS_PER_FACE 3\n \nclass CommandSocket::Private\n{\npublic:\n Private()\n : socket(nullptr)\n , object_count(0)\n , current_sliced_object(nullptr)\n , sliced_objects(0)\n , current_layer_count(0)\n , current_layer_offset(0)\n { }\n\n cura::proto::Layer* getLayerById(int id);\n\n Arcus::Socket* socket;\n \n \/\/ Number of objects that need to be sliced\n int object_count;\n \n \/\/ Message that holds a list of sliced objects\n std::shared_ptr sliced_object_list;\n \n \/\/ Message that holds the currently sliced object (to be added to sliced_object_list)\n cura::proto::SlicedObject* current_sliced_object;\n \n \/\/ Number of sliced objects for this sliced object list\n int sliced_objects;\n\n \/\/ Number of layers sent to the front end so far\n \/\/ Used for incrementing the current layer in one at a time mode\n int current_layer_count;\n int current_layer_offset;\n \n \/\/ Ids of the sliced objects\n std::vector object_ids;\n\n std::string temp_gcode_file;\n std::ostringstream gcode_output_stream;\n \n \/\/ Print object that olds one or more meshes that need to be sliced. \n std::vector< std::shared_ptr > objects_to_slice;\n};\n\nCommandSocket::CommandSocket()\n : d(new Private)\n{\n FffProcessor::getInstance()->setCommandSocket(this);\n}\n\nvoid CommandSocket::connect(const std::string& ip, int port)\n{\n d->socket = new Arcus::Socket();\n \/\/d->socket->registerMessageType(1, &Cura::ObjectList::default_instance());\n d->socket->registerMessageType(1, &cura::proto::Slice::default_instance());\n d->socket->registerMessageType(2, &cura::proto::SlicedObjectList::default_instance());\n d->socket->registerMessageType(3, &cura::proto::Progress::default_instance());\n d->socket->registerMessageType(4, &cura::proto::GCodeLayer::default_instance());\n d->socket->registerMessageType(5, &cura::proto::ObjectPrintTime::default_instance());\n d->socket->registerMessageType(6, &cura::proto::SettingList::default_instance());\n d->socket->registerMessageType(7, &cura::proto::GCodePrefix::default_instance());\n\n d->socket->connect(ip, port);\n \n bool slice_another_time = true;\n \n \/\/ Start & continue listening as long as socket is not closed and there is no error.\n while(d->socket->state() != Arcus::SocketState::Closed && d->socket->state() != Arcus::SocketState::Error && slice_another_time)\n {\n \/\/If there is an object to slice, do so.\n if(d->objects_to_slice.size())\n {\n FffProcessor::getInstance()->resetFileNumber();\n for(auto object : d->objects_to_slice)\n {\n if(!FffProcessor::getInstance()->processMeshGroup(object.get()))\n {\n logError(\"Slicing mesh group failed!\");\n }\n }\n d->objects_to_slice.clear();\n FffProcessor::getInstance()->finalize();\n sendGCodeLayer();\n sendPrintTime();\n slice_another_time = false; \/\/ TODO: remove this when multiple slicing with CuraEngine is safe\n \/\/TODO: Support all-at-once\/one-at-a-time printing\n \/\/d->processor->processModel(d->object_to_slice.get());\n \/\/d->object_to_slice.reset();\n \/\/d->processor->resetFileNumber();\n\n \/\/sendPrintTime();\n }\n \n \/\/ Actually start handling messages.\n Arcus::MessagePtr message = d->socket->takeNextMessage();\n cura::proto::SettingList* setting_list = dynamic_cast(message.get());\n if(setting_list)\n {\n handleSettingList(setting_list);\n }\n\n \/*cura::proto::ObjectList* object_list = dynamic_cast(message.get());\n if(object_list)\n {\n handleObjectList(object_list);\n }*\/\n \n cura::proto::Slice* slice = dynamic_cast(message.get());\n if(slice)\n {\n \/\/ Reset object counts\n d->object_count = 0;\n d->object_ids.clear();\n for(auto object : slice->object_lists())\n {\n handleObjectList(&object);\n }\n }\n\n std::this_thread::sleep_for(std::chrono::milliseconds(250));\n\n if(!d->socket->errorString().empty()) \n {\n logError(\"%s\\n\", d->socket->errorString().data());\n d->socket->clearError();\n }\n }\n}\n\nvoid CommandSocket::handleObjectList(cura::proto::ObjectList* list)\n{\n FMatrix3x3 matrix;\n \/\/d->object_count = 0;\n \/\/d->object_ids.clear();\n d->objects_to_slice.push_back(std::make_shared(FffProcessor::getInstance()));\n MeshGroup* meshgroup = d->objects_to_slice.back().get();\n \n for(auto setting : list->settings())\n {\n meshgroup->setSetting(setting.name(), setting.value());\n }\n \n for (int extruder_nr = 0; extruder_nr < FffProcessor::getInstance()->getSettingAsCount(\"machine_extruder_count\"); extruder_nr++)\n { \/\/ initialize remaining extruder trains and load the defaults\n meshgroup->createExtruderTrain(extruder_nr)->setExtruderTrainDefaults(extruder_nr); \/\/ create new extruder train objects or use already existing ones\n }\n \n for(auto object : list->objects())\n {\n DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR(\"solid Cura_out\\n\");\n int extruder_train_nr = 0; \/\/ TODO: make primary extruder configurable!\n for(auto setting : object.settings())\n {\n if (setting.name() == \"extruder_nr\")\n {\n extruder_train_nr = std::stoi(setting.value());\n break;\n }\n }\n SettingsBase* extruder_train = meshgroup->getExtruderTrain(extruder_train_nr);\n\n meshgroup->meshes.push_back(extruder_train); \/\/Construct a new mesh (with the corresponding extruder train as settings parent object) and put it into MeshGroup's mesh list.\n Mesh& mesh = meshgroup->meshes.back();\n\n int bytes_per_face = BYTES_PER_FLOAT * FLOATS_PER_VECTOR * VECTORS_PER_FACE;\n int face_count = object.vertices().size() \/ bytes_per_face;\n for(int i = 0; i < face_count; ++i)\n {\n \/\/TODO: Apply matrix\n std::string data = object.vertices().substr(i * bytes_per_face, bytes_per_face);\n const FPoint3* float_vertices = reinterpret_cast(data.data());\n\n Point3 verts[3];\n verts[0] = matrix.apply(float_vertices[0]);\n verts[1] = matrix.apply(float_vertices[1]);\n verts[2] = matrix.apply(float_vertices[2]);\n mesh.addFace(verts[0], verts[1], verts[2]);\n\n DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR(\" facet normal -1 0 0\\n\");\n DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR(\" outer loop\\n\");\n DEBUG_OUTPUT_OBJECT_STL_THROUGH_CERR(\" vertex \"<object_ids.push_back(object.id());\n mesh.finish();\n }\n\n d->object_count++;\n meshgroup->finalize();\n}\n\nvoid CommandSocket::handleSettingList(cura::proto::SettingList* list)\n{\n for(auto setting : list->settings())\n {\n FffProcessor::getInstance()->setSetting(setting.name(), setting.value());\n }\n}\n\nvoid CommandSocket::sendLayerInfo(int layer_nr, int32_t z, int32_t height)\n{\n if(!d->current_sliced_object)\n {\n return;\n }\n \n cura::proto::Layer* layer = d->getLayerById(layer_nr);\n layer->set_height(z);\n layer->set_thickness(height);\n}\n\nvoid CommandSocket::sendPolygons(PolygonType type, int layer_nr, Polygons& polygons, int line_width)\n{\n if(!d->current_sliced_object)\n return;\n \n if (polygons.size() == 0)\n return;\n\n cura::proto::Layer* layer = d->getLayerById(layer_nr);\n\n for(unsigned int i = 0; i < polygons.size(); ++i)\n {\n cura::proto::Polygon* p = layer->add_polygons();\n p->set_type(static_cast(type));\n std::string polydata;\n polydata.append(reinterpret_cast(polygons[i].data()), polygons[i].size() * sizeof(Point));\n p->set_points(polydata);\n p->set_line_width(line_width);\n }\n}\n\nvoid CommandSocket::sendProgress(float amount)\n{\n auto message = std::make_shared();\n amount \/= d->object_count;\n amount += d->sliced_objects * (1. \/ d->object_count);\n message->set_amount(amount);\n d->socket->sendMessage(message);\n}\n\nvoid CommandSocket::sendProgressStage(Progress::Stage stage)\n{\n \/\/ TODO\n}\n\nvoid CommandSocket::sendPrintTime()\n{\n auto message = std::make_shared();\n message->set_time(FffProcessor::getInstance()->getTotalPrintTime());\n message->set_material_amount(FffProcessor::getInstance()->getTotalFilamentUsed(0));\n d->socket->sendMessage(message);\n}\n\nvoid CommandSocket::sendPrintMaterialForObject(int index, int extruder_nr, float print_time)\n{\n\/\/ socket.sendInt32(CMD_OBJECT_PRINT_MATERIAL);\n\/\/ socket.sendInt32(12);\n\/\/ socket.sendInt32(index);\n\/\/ socket.sendInt32(extruder_nr);\n\/\/ socket.sendFloat32(print_time);\n}\n\nvoid CommandSocket::beginSendSlicedObject()\n{\n if(!d->sliced_object_list)\n {\n d->sliced_object_list = std::make_shared();\n }\n\n d->current_sliced_object = d->sliced_object_list->add_objects();\n d->current_sliced_object->set_id(d->object_ids[d->sliced_objects]);\n}\n\nvoid CommandSocket::endSendSlicedObject()\n{\n d->sliced_objects++;\n d->current_layer_offset = d->current_layer_count;\n std::cout << \"End sliced object called. sliced objects \" << d->sliced_objects << \" object count: \" << d->object_count << std::endl;\n\n std::cout << \"current layer count\" << d->current_layer_count << std::endl;\n std::cout << \"current layer offset\" << d->current_layer_offset << std::endl;\n\n if(d->sliced_objects >= d->object_count)\n {\n d->socket->sendMessage(d->sliced_object_list);\n d->sliced_objects = 0;\n d->current_layer_count = 0;\n d->current_layer_offset = 0;\n d->sliced_object_list.reset();\n d->current_sliced_object = nullptr;\n }\n}\n\nvoid CommandSocket::beginGCode()\n{\n FffProcessor::getInstance()->setTargetStream(&d->gcode_output_stream);\n}\n\nvoid CommandSocket::sendGCodeLayer()\n{\n auto message = std::make_shared();\n message->set_id(d->object_ids[0]);\n message->set_data(d->gcode_output_stream.str());\n d->socket->sendMessage(message);\n \n d->gcode_output_stream.str(\"\");\n}\n\nvoid CommandSocket::sendGCodePrefix(std::string prefix)\n{\n auto message = std::make_shared();\n message->set_data(prefix);\n d->socket->sendMessage(message);\n}\n\ncura::proto::Layer* CommandSocket::Private::getLayerById(int id)\n{\n id += current_layer_offset;\n\n auto itr = std::find_if(current_sliced_object->mutable_layers()->begin(), current_sliced_object->mutable_layers()->end(), [id](cura::proto::Layer& l) { return l.id() == id; });\n\n cura::proto::Layer* layer = nullptr;\n if(itr != current_sliced_object->mutable_layers()->end())\n {\n layer = &(*itr);\n }\n else\n {\n layer = current_sliced_object->add_layers();\n layer->set_id(id);\n current_layer_count++;\n }\n\n return layer;\n}\n\n}\/\/namespace cura\n<|endoftext|>"} {"text":"\/\/---------------------------- rt_5.cc ---------------------------\n\/\/ rt_5.cc,v 1.1 2003\/06\/09 15:59:07 wolf Exp\n\/\/ Version: \n\/\/\n\/\/ Copyright (C) 2003, 2004, 2005 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------- rt_5.cc ---------------------------\n\n\n\/\/ Just output the restriction matrices of the RT element\n\n#include \"..\/tests.h\"\n#include \n#include \n\n#include \n#include \n\n#define PRECISION 2\n\n\n\ntemplate\nvoid\ntest(const unsigned int degree)\n{\n deallog << \"FE_RaviartThomas<\" << dim << \"> (\" << degree << \")\"\n\t << std::endl;\n \n FE_RaviartThomas fe_rt(degree);\n\n for (unsigned int c=0; c::children_per_cell; ++c)\n {\n const FullMatrix & m = fe_rt.get_restriction_matrix(c);\n\n for (unsigned int i=0; i(degree);\n\/\/ test<3>(degree);\n \n return 0;\n}\n\n\n\noutput matrices for higher order\/\/---------------------------- rt_5.cc ---------------------------\n\/\/ rt_5.cc,v 1.1 2003\/06\/09 15:59:07 wolf Exp\n\/\/ Version: \n\/\/\n\/\/ Copyright (C) 2003, 2004, 2005, 2006 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------- rt_5.cc ---------------------------\n\n\n\/\/ Just output the restriction matrices of the RT element\n\n#include \"..\/tests.h\"\n#include \n#include \n\n#include \n#include \n\n#define PRECISION 2\n\n\n\ntemplate\nvoid\ntest(const unsigned int degree)\n{\n deallog << \"FE_RaviartThomas<\" << dim << \"> (\" << degree << \")\"\n\t << std::endl;\n \n FE_RaviartThomas fe_rt(degree);\n\n if (false)\n for (unsigned int c=0; c::children_per_cell; ++c)\n {\n const FullMatrix & m = fe_rt.get_restriction_matrix(c);\n\n for (unsigned int i=0; i(degree);\n\/\/ test<3>(degree);\n }\n \n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n*Component meta data.\n*Used to hold global properties for all components.\n*Includes OLC, so that OLC entries do not have to be defined on each instance of the component, as well as\n*instance data specific to components.\n*\/\n#pragma once\n#ifndef COMPONENT_META_H\n#define COMPONENT_META_H\n#include \n#include \n#include \n#include \n#include \"mud.h\"\n#include \"conf.h\"\n#include \"olcGroup.h\"\n#include \"olc.h\"\n#include \"serializer.h\"\n#include \"serializationHelpers.h\"\n\nclass IComponentMeta:public ISerializable\n{\npublic:\n virtual ~IComponentMeta() { }\n virtual Component* Create() = 0;\n virtual void Initialize() = 0;\n virtual std::string GetName() const = 0;\n virtual BOOL AddDependency(const std::string &dependency) = 0;\n virtual void GetDependencies(std::vector* out) const = 0;\n virtual OLCGROUP GetOlcGroup() const = 0;\n};\n\ntemplate \nclass ComponentMeta:public IComponentMeta\n{\n std::string _name;\n std::vector _dependencies; \/\/component dependencies.\npublic:\n ComponentMeta(const std::string &name)\n {\n _name = name;\n }\n ~ComponentMeta()\n {\n }\n void SetName(const std::string &name)\n {\n _name = name;\n }\n std::string GetName() const\n {\n return _name;\n }\n \/*\n *Checks to see if the specified dependency is located in the dependencies list.\n *Param: [in] the name of the dependency.\n *Return: True if the dependency exists in the dependencies list, false otherwise.\n *\/\n BOOL DependencyExists(const std::string &name) const\n {\n std::vector::const_iterator it, itEnd;\n\n itEnd = _dependencies.end();\n for (it = _dependencies.begin(); it != itEnd; ++it)\n {\n if ((*it) == name)\n {\n return true;\n }\n }\n\n return false;\n }\n\n \/*\n *Will add the specified dependency to the list.\n *Param: [in] The name of the component to add as a dependency.\n *\/\n BOOL AddDependency(const std::string &dependency)\n {\n if (DependencyExists(dependency))\n {\n return false;\n }\n\n _dependencies.push_back(dependency);\n return true;\n }\n\n \/*\n *Returns a pointer to a vector of dependency names.\n *Return: a pointer to the vector of strings containing the names of the dependencies associated with the component.\n *\/\n void GetDependencies(std::vector* out) const\n {\n std::copy(_dependencies.begin(), _dependencies.end(), out->end());\n }\n\n \/*\n *Called to create an instance of the component.\n *Param: [in] a pointer to the instance of the ComponentMeta object responsible for the component.\n *\/\n virtual T* Create()\n {\n T* ret = new T(this);\n ret->Initialize();\n return ret;\n }\n\n \/*\n *Does all the initialization for a component once it's added\n *to the component factory.\n *\/\n virtual void Initialize()\n {\n }\n\n virtual OLCGROUP GetOlcGroup() const\n {\n return OLCGROUP::NONE;\n }\n virtual void Serialize(tinyxml2::XMLElement* root)\n {\n tinyxml2::XMLDocument* doc = root->GetDocument();\n tinyxml2::XMLElement* ent = doc->NewElement(\"cmeta\");\n ent->SetAttribute(\"name\", _name.c_str());\n\n SerializeList>(\"dependencies\", \"dependency\", ent, _dependencies);\n root->InsertEndChild(ent);\n }\n virtual void Deserialize(tinyxml2::XMLElement* root)\n {\n _name = root->Attribute(\"name\");\n\n DeserializeCollection(root, \"dependencies\", [this](tinyxml2::XMLElement* visitor)\n {\n AddDependency(visitor->Attribute(\"name\"));\n });\n }\n};\n#endif\nUpdated component meta to fix a serialization issue where the wrong function was called.\/*\n*Component meta data.\n*Used to hold global properties for all components.\n*Includes OLC, so that OLC entries do not have to be defined on each instance of the component, as well as\n*instance data specific to components.\n*\/\n#pragma once\n#ifndef COMPONENT_META_H\n#define COMPONENT_META_H\n#include \n#include \n#include \n#include \n#include \"mud.h\"\n#include \"conf.h\"\n#include \"olcGroup.h\"\n#include \"olc.h\"\n#include \"serializer.h\"\n#include \"serializationHelpers.h\"\n\nclass IComponentMeta:public ISerializable\n{\npublic:\n virtual ~IComponentMeta() { }\n virtual Component* Create() = 0;\n virtual void Initialize() = 0;\n virtual std::string GetName() const = 0;\n virtual BOOL AddDependency(const std::string &dependency) = 0;\n virtual void GetDependencies(std::vector* out) const = 0;\n virtual OLCGROUP GetOlcGroup() const = 0;\n};\n\ntemplate \nclass ComponentMeta:public IComponentMeta\n{\n std::string _name;\n std::vector _dependencies; \/\/component dependencies.\npublic:\n ComponentMeta(const std::string &name)\n {\n _name = name;\n }\n ~ComponentMeta()\n {\n }\n void SetName(const std::string &name)\n {\n _name = name;\n }\n std::string GetName() const\n {\n return _name;\n }\n \/*\n *Checks to see if the specified dependency is located in the dependencies list.\n *Param: [in] the name of the dependency.\n *Return: True if the dependency exists in the dependencies list, false otherwise.\n *\/\n BOOL DependencyExists(const std::string &name) const\n {\n std::vector::const_iterator it, itEnd;\n\n itEnd = _dependencies.end();\n for (it = _dependencies.begin(); it != itEnd; ++it)\n {\n if ((*it) == name)\n {\n return true;\n }\n }\n\n return false;\n }\n\n \/*\n *Will add the specified dependency to the list.\n *Param: [in] The name of the component to add as a dependency.\n *\/\n BOOL AddDependency(const std::string &dependency)\n {\n if (DependencyExists(dependency))\n {\n return false;\n }\n\n _dependencies.push_back(dependency);\n return true;\n }\n\n \/*\n *Returns a pointer to a vector of dependency names.\n *Return: a pointer to the vector of strings containing the names of the dependencies associated with the component.\n *\/\n void GetDependencies(std::vector* out) const\n {\n std::copy(_dependencies.begin(), _dependencies.end(), out->end());\n }\n\n \/*\n *Called to create an instance of the component.\n *Param: [in] a pointer to the instance of the ComponentMeta object responsible for the component.\n *\/\n virtual T* Create()\n {\n T* ret = new T(this);\n ret->Initialize();\n return ret;\n }\n\n \/*\n *Does all the initialization for a component once it's added\n *to the component factory.\n *\/\n virtual void Initialize()\n {\n }\n\n virtual OLCGROUP GetOlcGroup() const\n {\n return OLCGROUP::NONE;\n }\n virtual void Serialize(tinyxml2::XMLElement* root)\n {\n tinyxml2::XMLDocument* doc = root->GetDocument();\n tinyxml2::XMLElement* ent = doc->NewElement(\"cmeta\");\n ent->SetAttribute(\"name\", _name.c_str());\n\n SerializeCollection, std::string>(\"dependencies\", \"dependency\", root, _dependencies, [this](tinyxml2::XMLElement* visitor, const std::string& dep)\n {\n visitor->SetAttribute(\"name\", dep.c_str());\n });\n root->InsertEndChild(ent);\n }\n virtual void Deserialize(tinyxml2::XMLElement* root)\n {\n _name = root->Attribute(\"name\");\n\n DeserializeCollection(root, \"dependencies\", [this](tinyxml2::XMLElement* visitor)\n {\n AddDependency(visitor->Attribute(\"name\"));\n });\n }\n};\n#endif\n<|endoftext|>"} {"text":"#pragma once\n#define ENABLE_WAWL_BASETYPE\n\n#include \n#include \n\n\/\/ WinAPI Header\n#define NOMINMAX\n#include \n#include \n#undef NOMINMAX\n\nnamespace wawl {\n\tnamespace base {\n\n\t\t\/\/ ascii char type\n\t\tusing Achar = ::CHAR;\n\t\t\/\/ wide char type\n\t\tusing Wchar = ::WCHAR;\n\t\t\/\/ generic char type\n\t\tusing Tchar = ::TCHAR;\n\n\t\t\/\/ ascii string type\n\t\tusing Astring = std::basic_string;\n\t\t\/\/ wide string type\n\t\tusing Wstring = std::basic_string;\n\t\t\/\/ generic string type\n\t\tusing Tstring = std::basic_string;\n\n\t\t\/\/ signed 64bit int\n\t\tusing Int64 = std::int64_t;\n\n\t\t\/\/ unsigned int\n\t\tusing Uint = unsigned int;\n\t\t\/\/ unsigned 8bit int\n\t\tusing Uint8 = ::BYTE;\n\t\t\/\/ unsigned 16bit int\n\t\tusing Uint16 = ::WORD;\n\t\t\/\/ unsigned 32bit int\n\t\tusing Uint32 = ::DWORD;\n\t\t\/\/ unsigned 64bit int\n\t\tusing Uint64 = std::uint64_t;\n\n\t\t\/\/ integer which can contain pointer\n\t\tusing IntPtr = ::INT_PTR;\n\t\t\/\/ unsigned integer which cantain pointer\n\t\tusing UintPtr = ::UINT_PTR;\n\t\t\/\/ larger than IntPtr\n\t\tusing LongPtr = ::LONG_PTR;\n\n\t\t\/\/ any handle\n\t\tusing Handle = ::HANDLE;\n\t\tconstexpr Handle InvalidHandle = INVALID_HANDLE_VALUE;\n\t\tinline bool closeHandle(Handle h) {\n\t\t\treturn ::CloseHandle(h) != 0;\n\t\t}\n\n\t\t\/\/ application handle\n\t\tusing AppHandle = ::HINSTANCE;\n\t\tusing ModuleHandle = ::HINSTANCE;\n\n\t\tstruct Position {\n\t\t\tint x, y;\n\n\t\t\tPosition operator + (const Position& p) {\n\t\t\t\treturn Position{ x + p.x, y + p.y };\n\t\t\t}\n\t\t\tPosition& operator += (const Position& p) {\n\t\t\t\tx += p.x;\n\t\t\t\ty += p.y;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tPosition operator - (const Position& p) {\n\t\t\t\treturn Position{ x - p.x, y - p.y };\n\t\t\t}\n\t\t\tPosition& operator -= (const Position& p) {\n\t\t\t\tx -= p.x;\n\t\t\t\ty -= p.y;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t};\n\t\tusing Size = Position;\n\n\t\tstruct Rect {\n\t\t\tint x, y;\n\t\t\tint w, h;\n\t\t};\n\n\t} \/\/ ::wawl::base\n\n\tusing namespace base;\n\n} \/\/ ::wawladd some basetypes#pragma once\n#define ENABLE_WAWL_BASETYPE\n\n#include \n#include \n\n\/\/ WinAPI Header\n#define NOMINMAX\n#include \n#include \n#undef NOMINMAX\n\nnamespace wawl {\n\tnamespace base {\n\n\t\t\/\/ ascii char type\n\t\tusing Achar = ::CHAR;\n\t\t\/\/ wide char type\n\t\tusing Wchar = ::WCHAR;\n\t\t\/\/ generic char type\n\t\tusing Tchar = ::TCHAR;\n\n\t\t\/\/ ascii string type\n\t\tusing Astring = std::basic_string;\n\t\t\/\/ wide string type\n\t\tusing Wstring = std::basic_string;\n\t\t\/\/ generic string type\n\t\tusing Tstring = std::basic_string;\n\t\t\n\t\t\/\/ signed 8bit int\n\t\tusing Int8 = std::int8_t;\n\t\t\/\/ signed 16bit int\n\t\tusing Int16 = std::int16_t;\n\t\t\/\/ signed 32bit int\n\t\tusing Int32 = std::int32_t;\n\t\t\/\/ signed 64bit int\n\t\tusing Int64 = std::int64_t;\n\n\t\t\/\/ unsigned int\n\t\tusing Uint = unsigned int;\n\t\t\/\/ unsigned 8bit int\n\t\tusing Uint8 = ::BYTE;\n\t\t\/\/ unsigned 16bit int\n\t\tusing Uint16 = ::WORD;\n\t\t\/\/ unsigned 32bit int\n\t\tusing Uint32 = ::DWORD;\n\t\t\/\/ unsigned 64bit int\n\t\tusing Uint64 = std::uint64_t;\n\n\t\t\/\/ integer which can contain pointer\n\t\tusing IntPtr = ::INT_PTR;\n\t\t\/\/ unsigned integer which cantain pointer\n\t\tusing UintPtr = ::UINT_PTR;\n\t\t\/\/ larger than IntPtr\n\t\tusing LongPtr = ::LONG_PTR;\n\n\t\t\/\/ any handle\n\t\tusing Handle = ::HANDLE;\n\t\tconstexpr Handle InvalidHandle = INVALID_HANDLE_VALUE;\n\t\tinline bool closeHandle(Handle h) {\n\t\t\treturn ::CloseHandle(h) != 0;\n\t\t}\n\n\t\t\/\/ application handle\n\t\tusing AppHandle = ::HINSTANCE;\n\t\tusing ModuleHandle = ::HINSTANCE;\n\n\t\tstruct Position {\n\t\t\tint x, y;\n\n\t\t\tPosition operator + (const Position& p) {\n\t\t\t\treturn Position{ x + p.x, y + p.y };\n\t\t\t}\n\t\t\tPosition& operator += (const Position& p) {\n\t\t\t\tx += p.x;\n\t\t\t\ty += p.y;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tPosition operator - (const Position& p) {\n\t\t\t\treturn Position{ x - p.x, y - p.y };\n\t\t\t}\n\t\t\tPosition& operator -= (const Position& p) {\n\t\t\t\tx -= p.x;\n\t\t\t\ty -= p.y;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t};\n\t\tusing Size = Position;\n\n\t\tstruct Rect {\n\t\t\tint x, y;\n\t\t\tint w, h;\n\t\t};\n\n\t} \/\/ ::wawl::base\n\n\tusing namespace base;\n\n} \/\/ ::wawl<|endoftext|>"} {"text":"\/\/ Licensed GNU LGPL v3 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#ifndef __RAPICORN_STRINGS_HH__\n#define __RAPICORN_STRINGS_HH__\n\n#include \n#include \n#include \n\nnamespace Rapicorn {\n\n\/\/ == i18n ==\nconst char* rapicorn_gettext (const char *text) RAPICORN_FORMAT (1);\n#ifdef __RAPICORN_BUILD__\n#define _(str) Rapicorn::rapicorn_gettext (str)\n#define N_(str) (str)\n#endif\n\n\/\/ == Macros ==\n#ifdef RAPICORN_CONVENIENCE\n\/\/\/ Produce a const char* string, wrapping @a str into C-style double quotes.\n#define CQUOTE(str) RAPICORN_CQUOTE(str)\n\/\/\/ Create a Rapicorn::StringVector, from a const char* C-style array.\n#define STRING_VECTOR_FROM_ARRAY(ConstCharArray) RAPICORN_STRING_VECTOR_FROM_ARRAY(ConstCharArray)\n#endif \/\/ RAPICORN_CONVENIENCE\n\n\/\/ == C-String ==\nbool \t\t\tcstring_to_bool (const char *string, bool fallback = false);\n\n\/\/ == String ==\nString string_multiply (const String &s, uint64 count);\nString string_canonify (const String &s, const String &valid_chars, const String &substitute);\nString string_set_a2z ();\nString string_set_A2Z ();\nString string_set_ascii_alnum ();\nString \t\t\tstring_tolower (const String &str);\nString \t\t\tstring_toupper (const String &str);\nString \t\t\tstring_totitle (const String &str);\nString \t\t\tstring_printf (const char *format, ...) RAPICORN_PRINTF (1, 2);\nString \t\t\tstring_vprintf (const char *format, va_list vargs);\nString \t\t\tstring_locale_printf (const char *format, ...) RAPICORN_PRINTF (1, 2);\nString \t\t\tstring_locale_vprintf (const char *format, va_list vargs);\nStringVector \t\t\tstring_split (const String &string, const String &splitter = \"\");\nString \t\t\tstring_join (const String &junctor, const StringVector &strvec);\nbool \t\t\tstring_to_bool (const String &string, bool fallback = false);\nString \t\t\tstring_from_bool (bool value);\nuint64 \t\t\tstring_to_uint (const String &string, uint base = 10);\nString \t\t\tstring_from_uint (uint64 value);\nbool \t\t\tstring_has_int (const String &string);\nint64 \t\t\tstring_to_int (const String &string, uint base = 10);\nString \t\t\tstring_from_int (int64 value);\nString \t\t\tstring_from_float (float value);\ndouble \t\t\tstring_to_double (const String &string);\ndouble \t\t\tstring_to_double (const char *dblstring, const char **endptr);\nString string_from_double (double value);\ninline String string_from_float (double value) { return string_from_double (value); }\ninline double string_to_float (const String &string) { return string_to_double (string); }\ntemplate Type string_to_type (const String &string);\ntemplate String string_from_type (Type value);\ntemplate<> inline double string_to_type (const String &string) { return string_to_double (string); }\ntemplate<> inline String string_from_type (double value) { return string_from_double (value); }\ntemplate<> inline float string_to_type (const String &string) { return string_to_float (string); }\ntemplate<> inline String string_from_type (float value) { return string_from_float (value); }\ntemplate<> inline bool string_to_type (const String &string) { return string_to_bool (string); }\ntemplate<> inline String string_from_type (bool value) { return string_from_bool (value); }\ntemplate<> inline int16 string_to_type (const String &string) { return string_to_int (string); }\ntemplate<> inline String string_from_type (int16 value) { return string_from_int (value); }\ntemplate<> inline uint16 string_to_type (const String &string) { return string_to_uint (string); }\ntemplate<> inline String string_from_type (uint16 value) { return string_from_uint (value); }\ntemplate<> inline int string_to_type (const String &string) { return string_to_int (string); }\ntemplate<> inline String string_from_type (int value) { return string_from_int (value); }\ntemplate<> inline uint string_to_type (const String &string) { return string_to_uint (string); }\ntemplate<> inline String string_from_type (uint value) { return string_from_uint (value); }\ntemplate<> inline int64 string_to_type (const String &string) { return string_to_int (string); }\ntemplate<> inline String string_from_type (int64 value) { return string_from_int (value); }\ntemplate<> inline uint64 string_to_type (const String &string) { return string_to_uint (string); }\ntemplate<> inline String string_from_type (uint64 value) { return string_from_uint (value); }\ntemplate<> inline String string_to_type (const String &string) { return string; }\ntemplate<> inline String string_from_type (String value) { return value; }\nvector string_to_double_vector (const String &string);\nString string_from_double_vector(const vector &dvec,\n const String &delim = \" \");\nString \t\t\tstring_from_errno (int errno_val);\nbool string_is_uuid (const String &uuid_string); \/* check uuid formatting *\/\nint string_cmp_uuid (const String &uuid_string1,\n const String &uuid_string2); \/* -1=smaller, 0=equal, +1=greater (assuming valid uuid strings) *\/\nbool string_startswith (const String &string, const String &fragment);\nbool string_endswith (const String &string, const String &fragment);\nbool string_match_identifier (const String &ident1, const String &ident2);\nbool string_match_identifier_tail (const String &ident, const String &tail);\nString string_from_pretty_function_name (const char *gnuc_pretty_function);\nString string_to_cescape (const String &str);\nString string_to_cquote (const String &str);\nString string_from_cquote (const String &input);\nString string_hexdump (const void *addr, size_t length, size_t initial_offset = 0);\nString string_lstrip (const String &input);\nString string_rstrip (const String &input);\nString string_strip (const String &input);\nString string_substitute_char (const String &input, const char match, const char subst);\nString string_vector_find (const StringVector &svector, const String &key, const String &fallback);\nStringVector cstrings_to_vector (const char*, ...) RAPICORN_SENTINEL;\nvoid memset4\t\t(uint32 *mem, uint32 filler, uint length);\nlong double posix_locale_strtold (const char *nptr, char **endptr);\nlong double current_locale_strtold (const char *nptr, char **endptr);\n\n\/\/ == String Options ==\nbool string_option_check (const String &option_string,\n const String &option);\nString string_option_get (const String &option_string,\n const String &option);\nvoid string_options_split (const String &option_string,\n vector &option_names,\n vector &option_values,\n const String &empty_default = \"\");\n\n\/\/ == Strings ==\n\/\/\/ Convenience Constructor for StringSeq or std::vector\nclass Strings : public std::vector\n{\n typedef const std::string CS;\npublic:\n explicit Strings (CS &s1);\n explicit Strings (CS &s1, CS &s2);\n explicit Strings (CS &s1, CS &s2, CS &s3);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9, CS &sA);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9, CS &sA, CS &sB);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9, CS &sA, CS &sB, CS &sC);\n};\n\n\/\/ == Charset Conversions ==\nbool text_convert (const String &to_charset,\n String &output_string,\n const String &from_charset,\n const String &input_string,\n const String &fallback_charset = \"ISO-8859-15\",\n const String &output_mark = \"\");\n\n\/\/ == C strings ==\nusing ::strerror; \/\/ introduce (const char* strerror (int))\nconst char* strerror (); \/\/ simple wrapper for strerror (errno)\n\n\/\/ == Implementations ==\n#define RAPICORN_STRING_VECTOR_FROM_ARRAY(ConstCharArray) ({ \\\n Rapicorn::StringVector __a; \\\n const Rapicorn::uint64 __l = RAPICORN_ARRAY_SIZE (ConstCharArray); \\\n for (Rapicorn::uint64 __ai = 0; __ai < __l; __ai++) \\\n __a.push_back (ConstCharArray[__ai]); \\\n __a; })\n#define RAPICORN_CQUOTE(str) (Rapicorn::string_to_cquote (str).c_str())\n\n} \/\/ Rapicorn\n\n#endif \/* __RAPICORN_STRINGS_HH__ *\/\nRCORE: add string_format() for type safe printf-like formatting\/\/ Licensed GNU LGPL v3 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#ifndef __RAPICORN_STRINGS_HH__\n#define __RAPICORN_STRINGS_HH__\n\n#include \n#include \n#include \n#include \n\nnamespace Rapicorn {\n\n\/\/ == i18n ==\nconst char* rapicorn_gettext (const char *text) RAPICORN_FORMAT (1);\n#ifdef __RAPICORN_BUILD__\n#define _(str) Rapicorn::rapicorn_gettext (str)\n#define N_(str) (str)\n#endif\n\n\/\/ == Macros ==\n#ifdef RAPICORN_CONVENIENCE\n\/\/\/ Produce a const char* string, wrapping @a str into C-style double quotes.\n#define CQUOTE(str) RAPICORN_CQUOTE(str)\n\/\/\/ Create a Rapicorn::StringVector, from a const char* C-style array.\n#define STRING_VECTOR_FROM_ARRAY(ConstCharArray) RAPICORN_STRING_VECTOR_FROM_ARRAY(ConstCharArray)\n#endif \/\/ RAPICORN_CONVENIENCE\n\n\/\/ == C-String ==\nbool \t\t\tcstring_to_bool (const char *string, bool fallback = false);\n\n\/\/ == String Formatting ==\ntemplate RAPICORN_PRINTF (1, 0) String string_format (const char *format, Args... args);\n\n\/\/ == String ==\nString string_multiply (const String &s, uint64 count);\nString string_canonify (const String &s, const String &valid_chars, const String &substitute);\nString string_set_a2z ();\nString string_set_A2Z ();\nString string_set_ascii_alnum ();\nString \t\t\tstring_tolower (const String &str);\nString \t\t\tstring_toupper (const String &str);\nString \t\t\tstring_totitle (const String &str);\nString \t\t\tstring_printf (const char *format, ...) RAPICORN_PRINTF (1, 2);\nString \t\t\tstring_vprintf (const char *format, va_list vargs);\nString \t\t\tstring_locale_printf (const char *format, ...) RAPICORN_PRINTF (1, 2);\nString \t\t\tstring_locale_vprintf (const char *format, va_list vargs);\nStringVector \t\t\tstring_split (const String &string, const String &splitter = \"\");\nString \t\t\tstring_join (const String &junctor, const StringVector &strvec);\nbool \t\t\tstring_to_bool (const String &string, bool fallback = false);\nString \t\t\tstring_from_bool (bool value);\nuint64 \t\t\tstring_to_uint (const String &string, uint base = 10);\nString \t\t\tstring_from_uint (uint64 value);\nbool \t\t\tstring_has_int (const String &string);\nint64 \t\t\tstring_to_int (const String &string, uint base = 10);\nString \t\t\tstring_from_int (int64 value);\nString \t\t\tstring_from_float (float value);\ndouble \t\t\tstring_to_double (const String &string);\ndouble \t\t\tstring_to_double (const char *dblstring, const char **endptr);\nString string_from_double (double value);\ninline String string_from_float (double value) { return string_from_double (value); }\ninline double string_to_float (const String &string) { return string_to_double (string); }\ntemplate Type string_to_type (const String &string);\ntemplate String string_from_type (Type value);\ntemplate<> inline double string_to_type (const String &string) { return string_to_double (string); }\ntemplate<> inline String string_from_type (double value) { return string_from_double (value); }\ntemplate<> inline float string_to_type (const String &string) { return string_to_float (string); }\ntemplate<> inline String string_from_type (float value) { return string_from_float (value); }\ntemplate<> inline bool string_to_type (const String &string) { return string_to_bool (string); }\ntemplate<> inline String string_from_type (bool value) { return string_from_bool (value); }\ntemplate<> inline int16 string_to_type (const String &string) { return string_to_int (string); }\ntemplate<> inline String string_from_type (int16 value) { return string_from_int (value); }\ntemplate<> inline uint16 string_to_type (const String &string) { return string_to_uint (string); }\ntemplate<> inline String string_from_type (uint16 value) { return string_from_uint (value); }\ntemplate<> inline int string_to_type (const String &string) { return string_to_int (string); }\ntemplate<> inline String string_from_type (int value) { return string_from_int (value); }\ntemplate<> inline uint string_to_type (const String &string) { return string_to_uint (string); }\ntemplate<> inline String string_from_type (uint value) { return string_from_uint (value); }\ntemplate<> inline int64 string_to_type (const String &string) { return string_to_int (string); }\ntemplate<> inline String string_from_type (int64 value) { return string_from_int (value); }\ntemplate<> inline uint64 string_to_type (const String &string) { return string_to_uint (string); }\ntemplate<> inline String string_from_type (uint64 value) { return string_from_uint (value); }\ntemplate<> inline String string_to_type (const String &string) { return string; }\ntemplate<> inline String string_from_type (String value) { return value; }\nvector string_to_double_vector (const String &string);\nString string_from_double_vector(const vector &dvec,\n const String &delim = \" \");\nString \t\t\tstring_from_errno (int errno_val);\nbool string_is_uuid (const String &uuid_string); \/* check uuid formatting *\/\nint string_cmp_uuid (const String &uuid_string1,\n const String &uuid_string2); \/* -1=smaller, 0=equal, +1=greater (assuming valid uuid strings) *\/\nbool string_startswith (const String &string, const String &fragment);\nbool string_endswith (const String &string, const String &fragment);\nbool string_match_identifier (const String &ident1, const String &ident2);\nbool string_match_identifier_tail (const String &ident, const String &tail);\nString string_from_pretty_function_name (const char *gnuc_pretty_function);\nString string_to_cescape (const String &str);\nString string_to_cquote (const String &str);\nString string_from_cquote (const String &input);\nString string_hexdump (const void *addr, size_t length, size_t initial_offset = 0);\nString string_lstrip (const String &input);\nString string_rstrip (const String &input);\nString string_strip (const String &input);\nString string_substitute_char (const String &input, const char match, const char subst);\nString string_vector_find (const StringVector &svector, const String &key, const String &fallback);\nStringVector cstrings_to_vector (const char*, ...) RAPICORN_SENTINEL;\nvoid memset4\t\t(uint32 *mem, uint32 filler, uint length);\nlong double posix_locale_strtold (const char *nptr, char **endptr);\nlong double current_locale_strtold (const char *nptr, char **endptr);\n\n\/\/ == String Options ==\nbool string_option_check (const String &option_string,\n const String &option);\nString string_option_get (const String &option_string,\n const String &option);\nvoid string_options_split (const String &option_string,\n vector &option_names,\n vector &option_values,\n const String &empty_default = \"\");\n\n\/\/ == Strings ==\n\/\/\/ Convenience Constructor for StringSeq or std::vector\nclass Strings : public std::vector\n{\n typedef const std::string CS;\npublic:\n explicit Strings (CS &s1);\n explicit Strings (CS &s1, CS &s2);\n explicit Strings (CS &s1, CS &s2, CS &s3);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9, CS &sA);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9, CS &sA, CS &sB);\n explicit Strings (CS &s1, CS &s2, CS &s3, CS &s4, CS &s5, CS &s6, CS &s7, CS &s8, CS &s9, CS &sA, CS &sB, CS &sC);\n};\n\n\/\/ == Charset Conversions ==\nbool text_convert (const String &to_charset,\n String &output_string,\n const String &from_charset,\n const String &input_string,\n const String &fallback_charset = \"ISO-8859-15\",\n const String &output_mark = \"\");\n\n\/\/ == C strings ==\nusing ::strerror; \/\/ introduce (const char* strerror (int))\nconst char* strerror (); \/\/ simple wrapper for strerror (errno)\n\n\/\/ == Implementations ==\n#define RAPICORN_STRING_VECTOR_FROM_ARRAY(ConstCharArray) ({ \\\n Rapicorn::StringVector __a; \\\n const Rapicorn::uint64 __l = RAPICORN_ARRAY_SIZE (ConstCharArray); \\\n for (Rapicorn::uint64 __ai = 0; __ai < __l; __ai++) \\\n __a.push_back (ConstCharArray[__ai]); \\\n __a; })\n#define RAPICORN_CQUOTE(str) (Rapicorn::string_to_cquote (str).c_str())\n\ntemplate String\nstring_format (const char *format, Args... args)\n{\n return Lib::StringFormatter::format (format, args...);\n}\n\n\n} \/\/ Rapicorn\n\n#endif \/* __RAPICORN_STRINGS_HH__ *\/\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n #include \"config.h\"\n #include \"debug.h\"\n #include \"util.h\"\n #include \"loop.h\"\n #include \"process.h\"\n #include \"profile.h\"\n #include \"socket.h\"\n #include \"msg.h\"\n #include \"iface.h\"\n #include \"id.h\"\n}\n#include \"gtest\/gtest.h\"\n\nextern co_socket_t unix_socket_proto;\n\n\n\/*\n * POA\n * * List socket functions that need testing @\n * * Come up with general order of testing @ \n * * Determine set up variables and functions\n * * Determine tear down process\n * \n * \n * Functions to test:\n * co_obj_t *co_socket_create(size_t size, co_socket_t proto);\n * int co_socket_send(co_obj_t *self, char *outgoing, size_t length);\n * int co_socket_receive(co_obj_t * self, co_obj_t *fd, char *incoming, size_t length);\n * int co_socket_hangup(co_obj_t *self, co_obj_t *context); \n * int co_socket_destroy(co_obj_t *self);\n * \n * \n *\/\n\n\nclass SocketTest : public ::testing::Test\n{\nprotected:\n int ret;\n \n void Send();\n \n co_socket_t *socket1;\n \n SocketTest()\n {\n socket1 = (co_socket_t*)co_socket_create(sizeof(co_socket_t), unix_socket_proto);\n \/\/ socket1->register_cb = co_loop_add_socket;\n socket1->bind((co_obj_t*)socket1, \"commotiontest2.sock\");\n }\n \n virtual void SetUp()\n {\n }\n \n ~SocketTest()\n {\n co_socket_destroy((co_obj_t *)socket1);\n }\n \n\n};\n \nvoid SocketTest::Send()\n{\n \n ASSERT_EQ(1, 1);\n}\n\nTEST_F(SocketTest, Send)\n{\n Send();\n}completed first draft of socket testing#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n #include \"config.h\"\n #include \"debug.h\"\n #include \"util.h\"\n #include \"loop.h\"\n #include \"process.h\"\n #include \"profile.h\"\n #include \"socket.h\"\n #include \"msg.h\"\n #include \"iface.h\"\n #include \"id.h\"\n #include \"list.h\"\n}\n#include \"gtest\/gtest.h\"\n\nextern co_socket_t unix_socket_proto;\n\n\n\/*\n * POA\n * * List socket functions that need testing @\n * * Come up with general order of testing @ \n * * Determine set up variables and functions\n * * Determine tear down process\n * \n * \n * Functions to test:\n * co_obj_t *co_socket_create(size_t size, co_socket_t proto);\n * int co_socket_send(co_obj_t *self, char *outgoing, size_t length);\n * int co_socket_receive(co_obj_t * self, co_obj_t *fd, char *incoming, size_t length);\n * int co_socket_hangup(co_obj_t *self, co_obj_t *context); \n * int co_socket_destroy(co_obj_t *self);\n * \n * \n *\/\n\n\nclass SocketTest : public ::testing::Test\n{\nprotected:\n int ret;\n \n #define MAX_MESSAGE 100\n \n char message1[MAX_MESSAGE];\n \n void SendReceive();\n \n co_socket_t *socket1;\n co_socket_t *socket2;\n \n SocketTest()\n {\n socket1 = (co_socket_t*)co_socket_create(sizeof(co_socket_t), unix_socket_proto);\n \/\/ socket1->register_cb = co_loop_add_socket;\n socket1->bind((co_obj_t*)socket1, \"commotiontest.sock\");\n \n socket2 = (co_socket_t*)co_socket_create(sizeof(co_socket_t), unix_socket_proto);\n socket2->connect((co_obj_t*)socket2, \"commotiontest.sock\");\n \/\/ socket1->register_cb = co_loop_add_socket;\n \/\/ socket2->bind((co_obj_t*)socket2, \"commotiontest.sock\");\n }\n \n virtual void SetUp()\n {\n }\n \n ~SocketTest()\n {\n co_socket_destroy((co_obj_t *)socket1);\n }\n \n\n};\n \nvoid SocketTest::SendReceive()\n{\n char buffer[14];\n int length = 14;\n int received = 0;\n \n char *test_message = \"test message\";\n \n ret = co_socket_send((co_obj_t *)socket2->fd, \"test message\", sizeof(\"test message\"));\n ASSERT_EQ(sizeof(\"test message\"), ret);\n\n received = co_socket_receive((co_obj_t *)socket1, (co_obj_t *)socket1->fd, buffer, length);\n \n received = co_socket_receive((co_obj_t *)socket1, (co_obj_t *)co_list_get_first(socket1->rfd_lst), buffer, length);\n \n DEBUG(\"\\n\\nSent %d bytes.\\n\", ret);\n DEBUG(\"\\n\\nReceived %d bytes.\\n\", received);\n \n ASSERT_STREQ(test_message, buffer);\n \n co_socket_hangup\n}\n\nTEST_F(SocketTest, SendReceive)\n{\n SendReceive();\n}<|endoftext|>"} {"text":"\/\/ Copyright © 2014 German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\/\/\n\/\/ Author: Christian Kellner \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/* ************************************ *\/\n\nclass Stopwatch {\n\npublic:\n typedef std::chrono::high_resolution_clock::time_point time_point_t;\n typedef std::chrono::high_resolution_clock clock_t;\n\n Stopwatch() : t_start(clock_t::now()) { };\n\n ssize_t ms() {\n time_point_t t_end = clock_t::now();\n ssize_t count = std::chrono::duration_cast(t_end - t_start).count();\n return count;\n }\n\nprivate:\n time_point_t t_start;\n};\n\n\/* ************************************ *\/\n\nclass RndGenBase {\npublic:\n RndGenBase() : rd(), rd_gen(rd()) { };\n\nprotected:\n std::random_device rd;\n std::mt19937 rd_gen;\n};\n\ntemplate\nclass RndGen { };\n\ntemplate\nclass RndGen::value >::type> : RndGenBase {\npublic:\n RndGen() : dis(-1024.0, +1024.0) { };\n\n T operator()(void) {\n return dis(rd_gen);\n };\n\nprivate:\n std::uniform_real_distribution dis;\n};\n\ntemplate\nclass RndGen::value >::type> : RndGenBase {\npublic:\n RndGen() : dis(-1024, +1024) { };\n\n T operator()(void) {\n return dis(rd_gen);\n };\n\nprivate:\n std::uniform_real_distribution dis;\n};\n\n\/* ************************************ *\/\n\ntemplate\nclass BlockGenerator {\npublic:\n\n BlockGenerator(size_t blocksize, size_t bufsize) : blocksize(blocksize), bufsize(bufsize) { };\n\n std::vector make_block() {\n std::vector block(blocksize);\n std::generate(block.begin(), block.end(), std::ref(rnd_gen));\n return block;\n }\n\n std::vector next_block() {\n std::unique_lock lock(mtx);\n\n if (queue.empty()) {\n cnd.wait(lock, [this]{ return !queue.empty(); });\n }\n\n std::vector x(std::move(queue.front()));\n queue.pop();\n cnd.notify_all();\n return x;\n }\n\n void worker_thread() {\n while (do_run) {\n std::unique_lock lock(mtx);\n std::vector block = make_block();\n\n if (queue.size() > bufsize) {\n \/\/wait until there is room\n cnd.wait(lock, [this]{ return !do_run || queue.size() < bufsize;});\n if (!do_run) {\n return;\n }\n }\n\n queue.push(std::move(block));\n cnd.notify_all();\n }\n }\n\n void start_worker() {\n workers.emplace_back(&BlockGenerator::worker_thread, this);\n }\n\n ~BlockGenerator() {\n do_run = false;\n cnd.notify_all();\n for (auto &w : workers) {\n w.join();\n }\n }\n\n double speed_test() {\n\n Stopwatch sw;\n\n size_t N = 100;\n size_t iterations = 0;\n\n do {\n Stopwatch inner;\n\n for (size_t i = 0; i < N; i++) {\n std::vector block = next_block();\n iterations++;\n }\n\n if (inner.ms() < 100) {\n N *= 2;\n }\n\n } while (sw.ms() < 1000);\n\n ssize_t count = sw.ms();\n return iterations * blocksize * sizeof(T) * (1000.0\/count) \/ (1024.0*1024.0);\n }\n\nprivate:\n bool do_run = true;\n size_t blocksize;\n size_t bufsize;\n RndGen rnd_gen;\n std::mutex mtx;\n std::condition_variable cnd;\n std::queue> queue;\n std::vector workers;\n};\n\nclass Config {\n\npublic:\n Config(nix::DataType data_type, const nix::NDSize &blocksize)\n : data_type(data_type), block_size(blocksize) {\n\n sdim = find_single_dim();\n shape = blocksize;\n shape[sdim] = 0;\n\n make_name();\n };\n\n size_t find_single_dim() {\n size_t sdim;\n bool have_rdim = false;\n for (size_t i = 0; i < block_size.size(); i ++) {\n if (block_size[i] == 1) {\n sdim = i;\n have_rdim = true;\n }\n }\n\n if (!have_rdim) {\n throw std::runtime_error(\"Could not find singelton dimension\");\n }\n return sdim;\n }\n\n nix::DataType dtype() const { return data_type; }\n const nix::NDSize& size() const { return block_size; }\n const nix::NDSize& extend() const { return shape; }\n size_t singleton_dimension() const { return sdim; }\n const std::string & name() const { return my_name; };\n\nprivate:\n void make_name() {\n std::stringstream s;\n\n s << data_type << \"@{ \";\n for (auto x : block_size) {\n s << x << \" \";\n }\n s << \"}\";\n\n my_name = s.str();\n }\n\nprivate:\n const nix::DataType data_type;\n const nix::NDSize block_size;\n\n size_t sdim;\n nix::NDSize shape;\n\n std::string my_name;\n};\n\nclass Benchmark {\n\npublic:\n Benchmark(const Config &cfg)\n : config(cfg) {\n };\n\n void test_write_io(nix::Block block) {\n block_id = block.id();\n\n nix::DataArray da = block.createDataArray(config.name(), \"nix.test.da\", config.dtype(), config.extend());\n dset_id = da.id();\n\n switch (config.dtype()) {\n\n case nix::DataType::Double:\n do_write_test(da);\n break;\n\n default:\n throw std::runtime_error(\"Unsupported DataType!\");\n }\n }\n\n void test_read_io(nix::File fd) {\n nix::Block block = fd.getBlock(block_id);\n nix::DataArray da = block.getDataArray(dset_id);\n\n speed_read = test_read_io(da);\n }\n\n double test_read_io(nix::DataArray da) {\n\n nix::NDArray array(config.dtype(), config.size());\n nix::NDSize extend = da.dataExtent();\n size_t N = extend[config.singleton_dimension()];\n\n nix::NDSize pos = {0, 0};\n\n ssize_t ms = time_it([this, &da, &N, &pos, &array] {\n for(size_t i = 0; i < N; i++) {\n da.getData(config.dtype(), array.data(), config.size(), pos);\n pos[config.singleton_dimension()] += 1;\n }\n });\n\n return calc_speed_mbs(ms, N);\n }\n\n void test_read_io_polynom(nix::File fd) {\n nix::Block block = fd.getBlock(block_id);\n nix::DataArray da = block.getDataArray(dset_id);\n\n da.polynomCoefficients({3, 4, 5, 6});\n\n speed_read_poly = test_read_io(da);\n }\n\n\n void report() {\n std::cout << config.name() << \": \"\n << \"G: \" << speed_generator << \" MB\/s, \"\n << \"W: \" << speed_write << \" MB\/s, \"\n << \"R: \" << speed_read << \" MB\/s, \"\n << \"P: \" << speed_read_poly << \" MB\/s\" << std::endl;\n }\n\n template\n ssize_t time_it(F func) {\n Stopwatch watch;\n func();\n return watch.ms();\n }\n\nprivate:\n template\n void do_write_test(nix::DataArray da) {\n size_t nelms = config.size().nelms();\n BlockGenerator generator(nelms, 10);\n generator.start_worker();\n speed_generator = generator.speed_test();\n\n\n size_t N = 100;\n size_t iterations = 0;\n\n nix::NDSize pos = {0, 0};\n Stopwatch sw;\n ssize_t ms = 0;\n do {\n Stopwatch inner;\n\n for (size_t i = 0; i < N; i++) {\n std::vector block = generator.next_block();\n da.dataExtent(config.size() + pos);\n da.setData(config.dtype(), block.data(), config.size(), pos);\n pos[config.singleton_dimension()] += 1;\n iterations++;\n }\n\n if (inner.ms() < 100) {\n N *= 2;\n }\n\n } while ((ms = sw.ms()) < 3*1000);\n speed_write = calc_speed_mbs(ms, iterations);\n }\n\n double calc_speed_mbs(ssize_t ms, size_t iterations) {\n return iterations * config.size().nelms() * nix::data_type_to_size(config.dtype()) * (1000.0\/ms) \/\n (1024.0*1024.0);\n }\n\nprivate:\n\n const Config config;\n\n std::string dset_id;\n std::string block_id;\n\n double speed_write;\n double speed_read;\n double speed_generator;\n double speed_read_poly;\n};\n\n\/* ************************************ *\/\n\nstatic std::vector make_benchmarks() {\n std::vector marks;\n\n \/\/TODO: auto-generate\n marks.emplace_back(Config(nix::DataType::Double, nix::NDSize{2048, 1}));\n marks.emplace_back(Config(nix::DataType::Double, nix::NDSize{1, 2048}));\n\n return marks;\n}\n\nint main(int argc, char **argv)\n{\n nix::File fd = nix::File::open(\"iospeed.h5\", nix::FileMode::Overwrite);\n nix::Block block = fd.createBlock(\"speed\", \"nix.test\");\n\n std::vector marks = make_benchmarks();\n\n std::cout << \"Performing write tests...\" << std::endl;\n for (Benchmark &mark : marks) {\n mark.test_write_io(block);\n }\n\n std::cout << \"Performing read tests...\" << std::endl;\n for (Benchmark &mark : marks) {\n mark.test_read_io(fd);\n }\n\n std::cout << \"Performing read (poly) tests...\" << std::endl;\n for (Benchmark &mark : marks) {\n mark.test_read_io_polynom(fd);\n }\n\n std::cout << \" === Reports ===\" << std::endl;\n for (Benchmark &mark : marks) {\n mark.report();\n }\n\n return 0;\n}\n[test] Benchmark: extract Benchmark base class\/\/ Copyright © 2014 German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\/\/\n\/\/ Author: Christian Kellner \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/* ************************************ *\/\n\nclass Stopwatch {\n\npublic:\n typedef std::chrono::high_resolution_clock::time_point time_point_t;\n typedef std::chrono::high_resolution_clock clock_t;\n\n Stopwatch() : t_start(clock_t::now()) { };\n\n ssize_t ms() {\n time_point_t t_end = clock_t::now();\n ssize_t count = std::chrono::duration_cast(t_end - t_start).count();\n return count;\n }\n\nprivate:\n time_point_t t_start;\n};\n\n\/* ************************************ *\/\n\nclass RndGenBase {\npublic:\n RndGenBase() : rd(), rd_gen(rd()) { };\n\nprotected:\n std::random_device rd;\n std::mt19937 rd_gen;\n};\n\ntemplate\nclass RndGen { };\n\ntemplate\nclass RndGen::value >::type> : RndGenBase {\npublic:\n RndGen() : dis(-1024.0, +1024.0) { };\n\n T operator()(void) {\n return dis(rd_gen);\n };\n\nprivate:\n std::uniform_real_distribution dis;\n};\n\ntemplate\nclass RndGen::value >::type> : RndGenBase {\npublic:\n RndGen() : dis(-1024, +1024) { };\n\n T operator()(void) {\n return dis(rd_gen);\n };\n\nprivate:\n std::uniform_real_distribution dis;\n};\n\n\/* ************************************ *\/\n\ntemplate\nclass BlockGenerator {\npublic:\n\n BlockGenerator(size_t blocksize, size_t bufsize) : blocksize(blocksize), bufsize(bufsize) { };\n\n std::vector make_block() {\n std::vector block(blocksize);\n std::generate(block.begin(), block.end(), std::ref(rnd_gen));\n return block;\n }\n\n std::vector next_block() {\n std::unique_lock lock(mtx);\n\n if (queue.empty()) {\n cnd.wait(lock, [this]{ return !queue.empty(); });\n }\n\n std::vector x(std::move(queue.front()));\n queue.pop();\n cnd.notify_all();\n return x;\n }\n\n void worker_thread() {\n while (do_run) {\n std::unique_lock lock(mtx);\n std::vector block = make_block();\n\n if (queue.size() > bufsize) {\n \/\/wait until there is room\n cnd.wait(lock, [this]{ return !do_run || queue.size() < bufsize;});\n if (!do_run) {\n return;\n }\n }\n\n queue.push(std::move(block));\n cnd.notify_all();\n }\n }\n\n void start_worker() {\n workers.emplace_back(&BlockGenerator::worker_thread, this);\n }\n\n ~BlockGenerator() {\n do_run = false;\n cnd.notify_all();\n for (auto &w : workers) {\n w.join();\n }\n }\n\n double speed_test() {\n\n Stopwatch sw;\n\n size_t N = 100;\n size_t iterations = 0;\n\n do {\n Stopwatch inner;\n\n for (size_t i = 0; i < N; i++) {\n std::vector block = next_block();\n iterations++;\n }\n\n if (inner.ms() < 100) {\n N *= 2;\n }\n\n } while (sw.ms() < 1000);\n\n ssize_t count = sw.ms();\n return iterations * blocksize * sizeof(T) * (1000.0\/count) \/ (1024.0*1024.0);\n }\n\nprivate:\n bool do_run = true;\n size_t blocksize;\n size_t bufsize;\n RndGen rnd_gen;\n std::mutex mtx;\n std::condition_variable cnd;\n std::queue> queue;\n std::vector workers;\n};\n\nclass Config {\n\npublic:\n Config(nix::DataType data_type, const nix::NDSize &blocksize)\n : data_type(data_type), block_size(blocksize) {\n\n sdim = find_single_dim();\n shape = blocksize;\n shape[sdim] = 0;\n\n make_name();\n };\n\n size_t find_single_dim() {\n size_t sdim;\n bool have_rdim = false;\n for (size_t i = 0; i < block_size.size(); i ++) {\n if (block_size[i] == 1) {\n sdim = i;\n have_rdim = true;\n }\n }\n\n if (!have_rdim) {\n throw std::runtime_error(\"Could not find singelton dimension\");\n }\n return sdim;\n }\n\n nix::DataType dtype() const { return data_type; }\n const nix::NDSize& size() const { return block_size; }\n const nix::NDSize& extend() const { return shape; }\n size_t singleton_dimension() const { return sdim; }\n const std::string & name() const { return my_name; };\n\nprivate:\n void make_name() {\n std::stringstream s;\n\n s << data_type << \"@{ \";\n for (auto x : block_size) {\n s << x << \" \";\n }\n s << \"}\";\n\n my_name = s.str();\n }\n\nprivate:\n const nix::DataType data_type;\n const nix::NDSize block_size;\n\n size_t sdim;\n nix::NDSize shape;\n\n std::string my_name;\n};\n\n\nclass Benchmark {\npublic:\n Benchmark(const Config &cfg) : config(cfg) { }\n const Config & cfg() const { return config; }\n\n virtual ~Benchmark() { }\n\n double speed_in_mbs() {\n return count * config.size().nelms() * nix::data_type_to_size(config.dtype()) *\n (1000.0\/millis) \/ (1024 * 1024);\n }\n\n template\n ssize_t time_it(F func) {\n Stopwatch watch;\n func();\n return watch.ms();\n }\n\n\nprotected:\n const Config config;\n size_t count;\n double millis;\n};\n\nclass IOBenchmark : Benchmark {\n\npublic:\n IOBenchmark(const Config &cfg)\n : Benchmark(cfg) {\n };\n\n void test_write_io(nix::Block block) {\n block_id = block.id();\n\n nix::DataArray da = block.createDataArray(config.name(), \"nix.test.da\", config.dtype(), config.extend());\n dset_id = da.id();\n\n switch (config.dtype()) {\n\n case nix::DataType::Double:\n do_write_test(da);\n break;\n\n default:\n throw std::runtime_error(\"Unsupported DataType!\");\n }\n }\n\n void test_read_io(nix::File fd) {\n nix::Block block = fd.getBlock(block_id);\n nix::DataArray da = block.getDataArray(dset_id);\n\n speed_read = test_read_io(da);\n }\n\n double test_read_io(nix::DataArray da) {\n\n nix::NDArray array(config.dtype(), config.size());\n nix::NDSize extend = da.dataExtent();\n size_t N = extend[config.singleton_dimension()];\n\n nix::NDSize pos = {0, 0};\n\n ssize_t ms = time_it([this, &da, &N, &pos, &array] {\n for(size_t i = 0; i < N; i++) {\n da.getData(config.dtype(), array.data(), config.size(), pos);\n pos[config.singleton_dimension()] += 1;\n }\n });\n\n return calc_speed_mbs(ms, N);\n }\n\n void test_read_io_polynom(nix::File fd) {\n nix::Block block = fd.getBlock(block_id);\n nix::DataArray da = block.getDataArray(dset_id);\n\n da.polynomCoefficients({3, 4, 5, 6});\n\n speed_read_poly = test_read_io(da);\n }\n\n\n void report() {\n std::cout << config.name() << \": \"\n << \"G: \" << speed_generator << \" MB\/s, \"\n << \"W: \" << speed_write << \" MB\/s, \"\n << \"R: \" << speed_read << \" MB\/s, \"\n << \"P: \" << speed_read_poly << \" MB\/s\" << std::endl;\n }\n\nprivate:\n template\n void do_write_test(nix::DataArray da) {\n size_t nelms = config.size().nelms();\n BlockGenerator generator(nelms, 10);\n generator.start_worker();\n speed_generator = generator.speed_test();\n\n\n size_t N = 100;\n size_t iterations = 0;\n\n nix::NDSize pos = {0, 0};\n Stopwatch sw;\n ssize_t ms = 0;\n do {\n Stopwatch inner;\n\n for (size_t i = 0; i < N; i++) {\n std::vector block = generator.next_block();\n da.dataExtent(config.size() + pos);\n da.setData(config.dtype(), block.data(), config.size(), pos);\n pos[config.singleton_dimension()] += 1;\n iterations++;\n }\n\n if (inner.ms() < 100) {\n N *= 2;\n }\n\n } while ((ms = sw.ms()) < 3*1000);\n speed_write = calc_speed_mbs(ms, iterations);\n }\n\n double calc_speed_mbs(ssize_t ms, size_t iterations) {\n return iterations * config.size().nelms() * nix::data_type_to_size(config.dtype()) * (1000.0\/ms) \/\n (1024.0*1024.0);\n }\n\nprivate:\n std::string dset_id;\n std::string block_id;\n\n double speed_write;\n double speed_read;\n double speed_generator;\n double speed_read_poly;\n};\n\n\/* ************************************ *\/\n\nstatic std::vector make_benchmarks() {\n std::vector marks;\n\n \/\/TODO: auto-generate\n marks.emplace_back(Config(nix::DataType::Double, nix::NDSize{2048, 1}));\n marks.emplace_back(Config(nix::DataType::Double, nix::NDSize{1, 2048}));\n\n return marks;\n}\n\nint main(int argc, char **argv)\n{\n nix::File fd = nix::File::open(\"iospeed.h5\", nix::FileMode::Overwrite);\n nix::Block block = fd.createBlock(\"speed\", \"nix.test\");\n\n std::vector marks = make_benchmarks();\n\n std::cout << \"Performing write tests...\" << std::endl;\n for (IOBenchmark &mark : marks) {\n mark.test_write_io(block);\n }\n\n std::cout << \"Performing read tests...\" << std::endl;\n for (IOBenchmark &mark : marks) {\n mark.test_read_io(fd);\n }\n\n std::cout << \"Performing read (poly) tests...\" << std::endl;\n for (IOBenchmark &mark : marks) {\n mark.test_read_io_polynom(fd);\n }\n\n std::cout << \" === Reports ===\" << std::endl;\n for (IOBenchmark &mark : marks) {\n mark.report();\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \"..\/ris_lib\/ris_late.h\"\n\n#include \n#include \n\ntypedef std::unordered_map default_context_t;\n\nTEST_CASE(\"splitting along simple mustache tags and skipping others\") {\n const char* temp = R\"(Hello {{name}}\nYou have just won {{value }} dollars!\n{{#in_ca}}\n Well, {{ taxed_value }} dollars, after taxes.\n{{\/in_ca}}\n)\";\n\n const char* expected = R\"(Hello John\nYou have just won 33 dollars!\n\n Well, 42 dollars, after taxes.\n\n)\";\n\n default_context_t context {\n { \"name\", \"John\" },\n { \"taxed_value\", \"42\" },\n { \"value\", \"33\" }\n };\n\n\n std::stringstream output;\n ris::render(temp, context, output);\n\n std::string output_str(output.str());\n CHECK(output_str == expected);\n}\n\nTEST_CASE(\"newlines are preserved and non-variables are ignored\") {\n std::stringstream output;\n default_context_t context;\n ris::render(\"\\n{{#a}}\\n\", context, output);\n\n CHECK(output.str() == \"\\n\\n\");\n}\n\nTEST_CASE(\"spaces in tags are allowed\") {\n std::stringstream output;\n default_context_t context{ \n { \"a\", \"42\" }\n };\n ris::render(\"{{a}}{{ a }}\", context, output);\n\n CHECK(output.str() == \"4242\");\n}\n\nTEST_CASE(\"empty templates are ok\") {\n std::stringstream output;\n default_context_t context;\n REQUIRE_NOTHROW(ris::render(\"\", context, output));\n\n CHECK(output.str() == \"\");\n}\nconfusion avoidance tests#include \n#include \"..\/ris_lib\/ris_late.h\"\n\n#include \n#include \n\ntypedef std::unordered_map default_context_t;\n\nTEST_CASE(\"splitting along simple mustache tags and skipping others\") {\n const char* temp = R\"(Hello {{name}}\nYou have just won {{value }} dollars!\n{{#in_ca}}\n Well, {{ taxed_value }} dollars, after taxes.\n{{\/in_ca}}\n)\";\n\n const char* expected = R\"(Hello John\nYou have just won 33 dollars!\n\n Well, 42 dollars, after taxes.\n\n)\";\n\n default_context_t context {\n { \"name\", \"John\" },\n { \"taxed_value\", \"42\" },\n { \"value\", \"33\" }\n };\n\n\n std::stringstream output;\n ris::render(temp, context, output);\n\n std::string output_str(output.str());\n CHECK(output_str == expected);\n}\n\nTEST_CASE(\"newlines are preserved and non-variables are ignored\") {\n std::stringstream output;\n default_context_t context;\n ris::render(\"\\n{{#a}}\\n\", context, output);\n\n CHECK(output.str() == \"\\n\\n\");\n}\n\nTEST_CASE(\"spaces in tags are allowed\") {\n std::stringstream output;\n default_context_t context{ \n { \"a\", \"42\" }\n };\n ris::render(\"{{a}}{{ a }}\", context, output);\n\n CHECK(output.str() == \"4242\");\n}\n\nTEST_CASE(\"empty templates are ok\") {\n std::stringstream output;\n default_context_t context;\n REQUIRE_NOTHROW(ris::render(\"\", context, output));\n\n CHECK(output.str() == \"\");\n}\n\nTEST_CASE(\"confusion avoidance\") {\n std::stringstream output;\n default_context_t context;\n ris::render(\"{{{a}}\", context, output);\n\n CHECK(output.str() == \"{\");\n \n output.str(\"\");\n ris::render(\"{{{a }}}\", context, output);\n CHECK(output.str() == \"{}\");\n}\n<|endoftext|>"} {"text":"\/\/#include \"closedlist.hpp\"\n#include \"plat2d.hpp\"\n#include \"..\/search\/main.hpp\"\n#include \"..\/utils\/utils.hpp\"\n#include \n#include \n\nconst char *lvl = NULL;\n\nstatic void parseargs(int, const char*[]);\n\nint main(int argc, const char *argv[]) {\n\tparseargs(argc, argv);\n\n\tFILE *infile = stdin;\n\tif (lvl) {\n\t\tinfile = fopen(lvl, \"r\");\n\t\tif (!infile)\n\t\t\tfatalx(errno, \"Failed to open %s for reading\", lvl);\n\t\tdfpair(stdout, \"level\", \"%s\", lvl);\n\t}\n\n\tPlat2d d(infile);\n\tif (infile != stdin)\n\t\tfclose(infile);\n\n\tResult res = search(d, argc, argv);\n\n\tstd::vector controls;\n\tPlayer p(2 * Tile::Width + Player::Offx, 2 * Tile::Height + Player::Offy,\n\t\t0, Player::Width, Player::Height);\n\tfor (int i = res.ops.size() - 1; i >= 0; i--) {\n\t\tcontrols.push_back(res.ops[i]);\n\t\tp.act(d.level(), res.ops[i]);\n\t\tassert(p == res.path[i].player);\n\t}\n\tconst Player &final = res.path[0].player;\n\tassert(d.level().majorblk(final.body.z, final.body.bbox).tile.flags &\n\t\t\tTile::Down);\n\n\tdfpair(stdout, \"final x loc\", \"%g\", final.body.bbox.min.x);\n\tdfpair(stdout, \"final y loc\", \"%g\", final.body.bbox.min.y);\n\tdfpair(stdout, \"controls\", \"%s\", controlstr(controls).c_str());\n\n\treturn 0;\n}\n\nstatic void parseargs(int argc, const char *argv[]) {\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (i < argc - 1 && strcmp(argv[i], \"-lvl\") == 0)\n\t\t\tlvl = argv[++i];\n\t}\n}\nplat2d: don't use the closed list for now. This needs some more thought to make sure that hashing is fast and such.#include \"closedlist.hpp\"\n#include \"..\/search\/main.hpp\"\n#include \"..\/utils\/utils.hpp\"\n#include \n#include \n\nconst char *lvl = NULL;\n\nstatic void parseargs(int, const char*[]);\n\nint main(int argc, const char *argv[]) {\n\tparseargs(argc, argv);\n\n\tFILE *infile = stdin;\n\tif (lvl) {\n\t\tinfile = fopen(lvl, \"r\");\n\t\tif (!infile)\n\t\t\tfatalx(errno, \"Failed to open %s for reading\", lvl);\n\t\tdfpair(stdout, \"level\", \"%s\", lvl);\n\t}\n\n\tPlat2d d(infile);\n\tif (infile != stdin)\n\t\tfclose(infile);\n\n\tResult res = search(d, argc, argv);\n\n\tstd::vector controls;\n\tPlayer p(2 * Tile::Width + Player::Offx, 2 * Tile::Height + Player::Offy,\n\t\t0, Player::Width, Player::Height);\n\tfor (int i = res.ops.size() - 1; i >= 0; i--) {\n\t\tcontrols.push_back(res.ops[i]);\n\t\tp.act(d.level(), res.ops[i]);\n\t\tassert(p == res.path[i].player);\n\t}\n\tconst Player &final = res.path[0].player;\n\tassert(d.level().majorblk(final.body.z, final.body.bbox).tile.flags &\n\t\t\tTile::Down);\n\n\tdfpair(stdout, \"final x loc\", \"%g\", final.body.bbox.min.x);\n\tdfpair(stdout, \"final y loc\", \"%g\", final.body.bbox.min.y);\n\tdfpair(stdout, \"controls\", \"%s\", controlstr(controls).c_str());\n\n\treturn 0;\n}\n\nstatic void parseargs(int argc, const char *argv[]) {\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (i < argc - 1 && strcmp(argv[i], \"-lvl\") == 0)\n\t\t\tlvl = argv[++i];\n\t}\n}\n<|endoftext|>"} {"text":"#define cimg_display 0 \n#include \n#include \n#include \"CImg.h\"\nusing namespace cimg_library;\n\n#include \n#include \n#include \nusing namespace std;\n\n#if !cimg_display\n#include \n#endif\n\n#define ROUND_NUM 10\n#define SCR_WIDTH 16\n#define SCR_HEIGHT 12\n\n#define MOLE_COL 4\n#define MOLE_ROW 3\n\n#define MOLE_MAX (MOLE_COL * MOLE_ROW)\n\n#define MOLE_WIDTH (SCR_WIDTH \/ MOLE_COL)\n#define MOLE_HEIGHT (SCR_HEIGHT \/ MOLE_ROW)\n\n#define MOLE_PIC \"mole.bmp\"\n#define MOLE_HIT_PIC \"mole_hit.bmp\"\n\ntypedef unsigned char * color_t;\n\nCImg canvas(SCR_WIDTH, SCR_HEIGHT, 1, 3, 0);\nCImg mole_pic;\nCImg mole_hit_pic;\n\nclass mole_t \n{\n public:\n int idx;\n int col, row;\n int width, height;\n bool touched;\n\n mole_t(int i);\n mole_t(int c, int w);\n};\n\ntypedef list mole_list_t;\n\nmole_t::mole_t(int i)\n{\n idx = i;\n width = MOLE_WIDTH;\n height = MOLE_HEIGHT;\n col = idx % MOLE_COL * MOLE_WIDTH;\n row = idx \/ MOLE_COL * MOLE_HEIGHT;\n touched = false;\n}\n\nmole_t::mole_t(int c, int w)\n{\n idx = -1;\n width = mole_pic.width();\n height = mole_pic.height();\n \n col = c;\n row = w;\n}\n\nclass score_t\n{\n public:\n int touched;\n int all;\n void reset();\n};\n\nvoid score_t::reset()\n{\n touched = 0;\n all = 0;\n}\n\npthread_mutex_t mutex;\n\nvoid my_lock() \n{\n static int i = 0;\n pthread_mutex_lock(&mutex);\n printf(\"locked %d\\n\", i++);\n}\n\nvoid my_unlock() \n{\n static int i = 0;\n pthread_mutex_unlock(&mutex);\n printf(\"unlocked %d\\n\", i++);\n}\n\n#define LOCK_ pthread_mutex_lock(&mutex)\n#define UNLOCK_ pthread_mutex_unlock(&mutex)\n\/\/#define LOCK_ my_lock()\n\/\/#define UNLOCK_ my_unlock()\nmole_list_t mole_list;\nscore_t score;\nint round_num = ROUND_NUM;\n#if !cimg_display\nhandle_t disp_handle;\n#endif\nhandle_t touch_handle;\n\nvoid draw_mole(mole_t *mole, CImg *pic) \n{\n canvas.draw_image(mole->col, mole->row, 0, 0,\n *pic);\n}\n\nvoid draw_all(CImg *pic)\n{\n for(mole_list_t::iterator itr = mole_list.begin();\n itr != mole_list.end();\n itr++) {\n draw_mole(&(*itr), pic);\n }\n}\n\nvoid save_canvas(int i)\n{\n char fname[256];\n \n sprintf(fname, \"save_%d.bmp\", i);\n\n canvas.save(fname);\n}\n\n#if cimg_display\nvoid disp_canvas()\n{\n CImgDisplay draw_disp(canvas, \"mole\");\n\n while(!draw_disp.is_closed()) {\n draw_disp.wait();\n }\n}\n#else\nvoid disp_canvas()\n{\n mug_disp_cimg(disp_handle, &canvas); \n}\n#endif\n\n\nvoid clear_canvas()\n{\n canvas.draw_rectangle(0, 0, 0,\n SCR_WIDTH, SCR_HEIGHT, 0,\n black);\n\n}\n\nmole_t* is_in(int c, int r)\n{\n for(mole_list_t::iterator itr = mole_list.begin();\n itr != mole_list.end();\n itr++) {\n if( (*itr).col <= c && c < (*itr).col + (*itr).width\n && (*itr).row <= r && r < (*itr).row + (*itr).height) {\n return &(*itr);\n }\n }\n\n return NULL;\n}\n\nvoid gen_round_mole(int *x, int *y)\n{\n}\n\nvoid next_round(int num)\n{\n LOCK_;\n\n printf(\"-------\\n\");\n clear_canvas();\n mole_list.clear();\n score.all += num;\n \n int col = rand() % (SCR_WIDTH - mole_pic.width());\n int row = rand() % (SCR_HEIGHT - mole_pic.height());\n\n for(int i = 0; i < num; i++) {\n while(is_in(col, row)) {\n col = rand() % (SCR_WIDTH - mole_pic.width());\n row = rand() % (SCR_HEIGHT - mole_pic.height());\n }\n printf(\"(%d, %d)\\n\", col, row);\n mole_t mole(col, row);\n mole_list.push_back(mole); \n }\n\n draw_all(&mole_pic);\n\n disp_canvas();\n\n UNLOCK_;\n}\n\nvoid show_result()\n{\n printf(\"%d \/ %d\\n\", score.touched, score.all);\n\n clear_canvas();\n\n int width, height;\n mug_number_text_shape(&width, &height);\n\n char temp[4];\n sprintf(temp, \"%02d\", score.touched);\n mug_draw_number_cimg(&canvas, 0, 0, temp, red);\n\n sprintf(temp, \"%02d\", score.all);\n mug_draw_number_cimg(&canvas, width * 2 , 0, temp, green);\n\n disp_canvas();\n}\n\nvoid touch_on(int x, int y, int id)\n{\n if(id != 0) return;\n LOCK_;\n\n mole_t *mole;\n bool changed = false;\n\n mole = is_in(x, y);\n\n if(mole && !mole->touched) {\n changed = true;\n mole->touched = true;\n score.touched++;\n printf(\"(%d, %d) -> (%d, %d)\\n\", x, y, mole->col, mole->row);\n draw_mole(mole, &mole_hit_pic);\n }\n\n if(changed)\n disp_canvas();\n\n UNLOCK_;\n}\n\nvoid *touch_thread(void *arg)\t\n{\n mug_run_touch_thread(touch_handle);\n}\n\nvoid init()\n{\n\n string proc_dir(get_proc_dir());\n \n mole_pic.load((proc_dir + \"\/\" + MOLE_PIC).c_str());\n mole_hit_pic.load((proc_dir + \"\/\" + MOLE_HIT_PIC).c_str());\n pthread_mutex_init(&mutex, NULL);\n\n#if !cimg_display\n disp_handle = mug_disp_init();\n touch_handle = mug_touch_init();\n mug_touch_on(touch_handle, touch_on);\n\n#ifdef USE_LIBUV \n pthread_t hdl;\n pthread_create(&hdl, NULL, touch_thread, NULL);\n#else\n mug_run_touch_thread();\n#endif\n\n#endif\n\n}\n\nvoid finish()\n{\n mug_stop_touch_thread(touch_handle);\n pthread_mutex_destroy(&mutex);\n}\n\nint main(int argc, char **argv)\n{\n if(argc == 2) {\n round_num = atoi(argv[1]);\n }\n\n init();\n \n for(int i = 0; i < round_num; i++) {\n next_round(2);\n usleep(1000*1000);\n }\n\n show_result();\n\n finish();\n}\n- added welcome display to mole#define cimg_display 0 \n#include \n#include \n#include \"CImg.h\"\nusing namespace cimg_library;\n\n#include \n#include \n#include \nusing namespace std;\n\n#if !cimg_display\n#include \n#endif\n\n#define ROUND_NUM 10\n#define SCR_WIDTH 16\n#define SCR_HEIGHT 12\n\n#define MOLE_COL 4\n#define MOLE_ROW 3\n\n#define MOLE_MAX (MOLE_COL * MOLE_ROW)\n\n#define MOLE_WIDTH (SCR_WIDTH \/ MOLE_COL)\n#define MOLE_HEIGHT (SCR_HEIGHT \/ MOLE_ROW)\n\n#define MOLE_PIC \"mole.bmp\"\n#define MOLE_HIT_PIC \"mole_hit.bmp\"\n\ntypedef unsigned char * color_t;\n\nCImg canvas(SCR_WIDTH, SCR_HEIGHT, 1, 3, 0);\nCImg mole_pic;\nCImg mole_hit_pic;\n\nclass mole_t \n{\n public:\n int idx;\n int col, row;\n int width, height;\n bool touched;\n\n mole_t(int i);\n mole_t(int c, int w);\n};\n\ntypedef list mole_list_t;\n\nmole_t::mole_t(int i)\n{\n idx = i;\n width = MOLE_WIDTH;\n height = MOLE_HEIGHT;\n col = idx % MOLE_COL * MOLE_WIDTH;\n row = idx \/ MOLE_COL * MOLE_HEIGHT;\n touched = false;\n}\n\nmole_t::mole_t(int c, int w)\n{\n idx = -1;\n width = mole_pic.width();\n height = mole_pic.height();\n \n col = c;\n row = w;\n}\n\nclass score_t\n{\n public:\n int touched;\n int all;\n void reset();\n};\n\nvoid score_t::reset()\n{\n touched = 0;\n all = 0;\n}\n\npthread_mutex_t mutex;\n\nvoid my_lock() \n{\n static int i = 0;\n pthread_mutex_lock(&mutex);\n printf(\"locked %d\\n\", i++);\n}\n\nvoid my_unlock() \n{\n static int i = 0;\n pthread_mutex_unlock(&mutex);\n printf(\"unlocked %d\\n\", i++);\n}\n\n#define LOCK_ pthread_mutex_lock(&mutex)\n#define UNLOCK_ pthread_mutex_unlock(&mutex)\n\/\/#define LOCK_ my_lock()\n\/\/#define UNLOCK_ my_unlock()\nmole_list_t mole_list;\nscore_t score;\nint round_num = ROUND_NUM;\n#if !cimg_display\nhandle_t disp_handle;\n#endif\nhandle_t touch_handle;\n\nvoid draw_mole(mole_t *mole, CImg *pic) \n{\n canvas.draw_image(mole->col, mole->row, 0, 0,\n *pic);\n}\n\nvoid draw_all(CImg *pic)\n{\n for(mole_list_t::iterator itr = mole_list.begin();\n itr != mole_list.end();\n itr++) {\n draw_mole(&(*itr), pic);\n }\n}\n\nvoid save_canvas(int i)\n{\n char fname[256];\n \n sprintf(fname, \"save_%d.bmp\", i);\n\n canvas.save(fname);\n}\n\n#if cimg_display\nvoid disp_canvas()\n{\n CImgDisplay draw_disp(canvas, \"mole\");\n\n while(!draw_disp.is_closed()) {\n draw_disp.wait();\n }\n}\n#else\nvoid disp_canvas()\n{\n mug_disp_cimg(disp_handle, &canvas); \n}\n#endif\n\n\nvoid clear_canvas()\n{\n canvas.draw_rectangle(0, 0, 0,\n SCR_WIDTH, SCR_HEIGHT, 0,\n black);\n\n}\n\nmole_t* is_in(int c, int r)\n{\n for(mole_list_t::iterator itr = mole_list.begin();\n itr != mole_list.end();\n itr++) {\n if( (*itr).col <= c && c < (*itr).col + (*itr).width\n && (*itr).row <= r && r < (*itr).row + (*itr).height) {\n return &(*itr);\n }\n }\n\n return NULL;\n}\n\nvoid gen_round_mole(int *x, int *y)\n{\n}\n\nvoid next_round(int num)\n{\n LOCK_;\n\n printf(\"-------\\n\");\n clear_canvas();\n mole_list.clear();\n score.all += num;\n \n int col = rand() % (SCR_WIDTH - mole_pic.width());\n int row = rand() % (SCR_HEIGHT - mole_pic.height());\n\n for(int i = 0; i < num; i++) {\n while(is_in(col, row)) {\n col = rand() % (SCR_WIDTH - mole_pic.width());\n row = rand() % (SCR_HEIGHT - mole_pic.height());\n }\n printf(\"(%d, %d)\\n\", col, row);\n mole_t mole(col, row);\n mole_list.push_back(mole); \n }\n\n draw_all(&mole_pic);\n\n disp_canvas();\n\n UNLOCK_;\n}\n\nvoid show_result()\n{\n printf(\"%d \/ %d\\n\", score.touched, score.all);\n\n clear_canvas();\n\n int width, height;\n mug_number_text_shape(&width, &height);\n\n char temp[4];\n sprintf(temp, \"%02d\", score.touched);\n mug_draw_number_cimg(&canvas, 0, 0, temp, red);\n\n sprintf(temp, \"%02d\", score.all);\n mug_draw_number_cimg(&canvas, width * 2 , 0, temp, green);\n\n disp_canvas();\n}\n\nvoid touch_on(int x, int y, int id)\n{\n if(id != 0) return;\n LOCK_;\n\n mole_t *mole;\n bool changed = false;\n\n mole = is_in(x, y);\n\n if(mole && !mole->touched) {\n changed = true;\n mole->touched = true;\n score.touched++;\n printf(\"(%d, %d) -> (%d, %d)\\n\", x, y, mole->col, mole->row);\n draw_mole(mole, &mole_hit_pic);\n }\n\n if(changed)\n disp_canvas();\n\n UNLOCK_;\n}\n\nvoid *touch_thread(void *arg)\t\n{\n mug_run_touch_thread(touch_handle);\n}\n\nvoid init()\n{\n\n string proc_dir(get_proc_dir());\n \n mole_pic.load((proc_dir + \"\/\" + MOLE_PIC).c_str());\n mole_hit_pic.load((proc_dir + \"\/\" + MOLE_HIT_PIC).c_str());\n pthread_mutex_init(&mutex, NULL);\n\n#if !cimg_display\n disp_handle = mug_disp_init();\n touch_handle = mug_touch_init();\n mug_touch_on(touch_handle, touch_on);\n\n#ifdef USE_LIBUV \n pthread_t hdl;\n pthread_create(&hdl, NULL, touch_thread, NULL);\n#else\n mug_run_touch_thread();\n#endif\n\n#endif\n\n}\n\nvoid finish()\n{\n mug_stop_touch_thread(touch_handle);\n pthread_mutex_destroy(&mutex);\n}\n\nint main(int argc, char **argv)\n{\n if(argc == 2) {\n round_num = atoi(argv[1]);\n }\n\n init();\n\n clear_canvas();\n canvas.draw_text(0, 0, \"ok?\", yellow, 1.0, 6);\n disp_canvas();\n usleep(1000 * 1000);\n\n clear_canvas();\n canvas.draw_text(0, 0, \"GO!\", magenta, 1.0, 6);\n disp_canvas();\n usleep(1000 * 1000);\n \n for(int i = 0; i < round_num; i++) {\n next_round(2);\n usleep(1000*1000);\n }\n\n show_result();\n\n finish();\n}\n<|endoftext|>"} {"text":"#include \n#include \"AADate.h\"\n#include \"sexagesimal.h\"\n#include \"AACoordinateTransformation.h\"\n#include \"AA3DCoordinate.h\"\n#include \"solar_system.h\"\n#include \"AAParallax.h\"\n#include \"AAGlobe.h\"\n#include \"AASidereal.h\"\n#include \n#include \"binary_tidbits.h\"\n#include \"horizontal_parallax.h\"\n\nusing std::cout;\nusing std::endl;\n\n\n\/* \n Write up the caculationa again, this time returning the Coordinates, not the Delta Coordinates.\n *\/\nCAA2DCoordinate Equatorial2TopocentricRigorousVerbose(double Alpha, double Delta, double Distance, double Longitude, double Latitude, double Height, double JD){\n \/\/ g_AAParallax_C1 is a constant and probably shouldn't be repetitively defined.\n double g_AAParallax_C1 = sin(CAACoordinateTransformation::DegreesToRadians(CAACoordinateTransformation::DMSToDegrees(0, 0, 8.794)));\n\n double RhoSinThetaPrime = CAAGlobe::RhoSinThetaPrime(Latitude, Height);\n double RhoCosThetaPrime = CAAGlobe::RhoCosThetaPrime(Latitude, Height);\n\n const double declination_degrees_geocentric = Delta;\n printf( \"\\nApril 4, 2015 New Code:\\n\");\n printf( \"declination_degrees_geocentric = %18.9lf\\n\", declination_degrees_geocentric);\n printf( \" RhoSinThetaPrime = %18.9lf\\n\", RhoSinThetaPrime);\n printf( \" RhoCosThetaPrime = %18.9lf\\n\", RhoCosThetaPrime);\n\n\n \/\/Calculate the Sidereal time\n double theta = CAASidereal::ApparentGreenwichSiderealTime(JD);\n printf( \" theta = %18.9lf\\n\", theta);\n cout << \"Apparent Greenwich Sidereal Time \" << sexagesimal::Sexagesimal(theta).to_string() << endl;\n \/\/Convert to radians\n printf( \" Delta = %18.9lf Degrees\\n\", Delta);\n Delta = CAACoordinateTransformation::DegreesToRadians(Delta);\n printf( \" Delta = %18.9lf Radians\\n\", Delta);\n double cosDelta = cos(Delta);\n double sinDelta = sin(Delta);\n printf( \" sinDelta = %18.9lf\\n\", sinDelta);\n printf( \" cosDelta = %18.9lf\\n\", cosDelta);\n \/\/Calculate the Parallax\n\n double pi = asin(g_AAParallax_C1 \/ Distance);\n\n printf( \" pi = %18.9lf\\n\", pi);\n\n \/\/Calculate the hour angle\n double H;\n if( binary_tidbits::west_longitude_is_positive() ){\n H = CAACoordinateTransformation::HoursToRadians(theta - Longitude\/15 - Alpha);\n }else{\n H = CAACoordinateTransformation::HoursToRadians(theta + Longitude\/15 - Alpha);\n }\n double cosH = cos(H);\n double sinH = sin(H);\n\n double sin_pi = sin( pi );\n printf( \" H = %18.9lf\\n\", H);\n printf( \" cosH = %18.9lf\\n\", cosH);\n printf( \" sinH = %18.9lf\\n\", sinH);\n \/* \n denominator is that of equations 40.2 and 40.3.\n Jean Meeus, Astronomical Algorithms 2nd ed. pp.279 \n *\/\n double denominator = cosDelta - RhoCosThetaPrime *sin_pi*cosH;\n double arg = ( -RhoCosThetaPrime * sin_pi * sinH )\/denominator; \/\/ RHS of eq. 40.2.\n \/*\n In variable name delta_alpha, delta indciates it is a change in the \n Value of alpha, the Right Ascension. (celestial longitude expressed as hours.)\n *\/\n double delta_alpha = atan( arg );\n double cos_delta_alpha = cos( delta_alpha );\n delta_alpha = CAACoordinateTransformation::RadiansToHours( delta_alpha );\n printf( \" delta_alpha = %18.9lf Hours Right Ascension\\n\", delta_alpha);\n\n\n arg = ((sinDelta - RhoSinThetaPrime * sin_pi )*cos_delta_alpha)\/denominator; \/\/ RHS of eq. 40.3\n \/*\n In variable name delta_prime, delta indicates it is a declination, not a difference.\n *\/\n double delta_prime = atan(arg);\n delta_prime = CAACoordinateTransformation::RadiansToDegrees( delta_prime );\n printf( \" delta_prime = %18.9lf\\n\", delta_prime);\n\n CAA2DCoordinate Topocentric_RA_Dec;\n \/\/ pack the return value.\n Topocentric_RA_Dec.X = Alpha + delta_alpha;\n Topocentric_RA_Dec.Y = delta_prime;\n return Topocentric_RA_Dec;\n}\n\n\nCAA2DCoordinate Equatorial2TopocentricDeltaRigorous(double Alpha, double Delta, double Distance, double Longitude, double Latitude, double Height, double JD)\n{\n double g_AAParallax_C1 = sin(CAACoordinateTransformation::DegreesToRadians(CAACoordinateTransformation::DMSToDegrees(0, 0, 8.794)));\n double RhoSinThetaPrime = CAAGlobe::RhoSinThetaPrime(Latitude, Height);\n double RhoCosThetaPrime = CAAGlobe::RhoCosThetaPrime(Latitude, Height);\n\n double declination_degrees_geocentric = Delta;\n\n printf( \"RhoSinThetaPrime = %18.9lf\\n\", RhoSinThetaPrime);\n printf( \"RhoCosThetaPrime = %18.9lf\\n\", RhoCosThetaPrime);\n\n \/\/Calculate the Sidereal time\n double theta = CAASidereal::ApparentGreenwichSiderealTime(JD);\n printf( \" theta = %18.9lf\\n\", theta);\n cout << \"Apparent Greenwich Sidereal Time \" << sexagesimal::Sexagesimal(theta).to_string() << endl;\n \/\/Convert to radians\n printf( \" Delta = %18.9lf Degrees\\n\", Delta);\n Delta = CAACoordinateTransformation::DegreesToRadians(Delta);\n printf( \" Delta = %18.9lf Radians\\n\", Delta);\n double cosDelta = cos(Delta);\n double sinDelta = sin(Delta);\n printf( \" cosDelta = %18.9lf\\n\", cosDelta);\n \/\/Calculate the Parallax\n double pi = asin(g_AAParallax_C1 \/ Distance);\n\n printf( \" pi = %18.9lf\\n\", pi);\n\n\n \/\/Calculate the hour angle\n double H;\n if( binary_tidbits::west_longitude_is_positive() ){\n H = CAACoordinateTransformation::HoursToRadians(theta - Longitude\/15 - Alpha);\n }else{\n H = CAACoordinateTransformation::HoursToRadians(theta + Longitude\/15 - Alpha);\n }\n double cosH = cos(H);\n double sinH = sin(H);\n\n double sin_pi = sin( pi );\n printf( \" H = %18.9lf\\n\", H);\n printf( \" cosH = %18.9lf\\n\", cosH);\n printf( \" sinH = %18.9lf\\n\", sinH);\n double denominator = cosDelta - RhoCosThetaPrime *sin_pi*cosH;\n double arg = ( -RhoCosThetaPrime * sin_pi * sinH )\/denominator;\n double delta_alpha = atan( arg );\n double cos_delta_alpha = cos( delta_alpha );\n delta_alpha = CAACoordinateTransformation::RadiansToHours( delta_alpha );\n printf( \" delta_alpha = %18.9lf\\n\", delta_alpha);\n\n\n arg = ((sinDelta - RhoSinThetaPrime * sin_pi )*cos_delta_alpha)\/denominator;\n double delta_prime = atan(arg);\n delta_prime = CAACoordinateTransformation::RadiansToDegrees( delta_prime );\n printf( \" delta_prime = %18.9lf\\n\", delta_prime);\n\n\n CAA2DCoordinate DeltaTopocentric;\n DeltaTopocentric.X = delta_alpha;\n DeltaTopocentric.Y = delta_prime - declination_degrees_geocentric;\n return DeltaTopocentric;\n}\n\n\n\/* \n *\n *\/\nint main( int argc, char **argv){\n long check;\n long unix_time = time( &check ); \n CAADate unix_epoch {1970,1,1, true};\n\n CAADate timestamp;\n\n if( 1 ){\n timestamp = CAADate( unix_epoch.Julian() + static_cast(unix_time)\/86400.0, true );\n }else{\n \/\/ timestamp = CAADate( 2015,3,31,15,55,0.0, true );\n timestamp = CAADate( 1992,4,12,0,0,0.0, true );\n }\n printf( \"Julian Date = %18.9lf\\n\", timestamp.Julian() );\n double hour = timestamp.Hour();\n hour += static_cast(timestamp.Minute())\/60.0;\n hour += static_cast(timestamp.Second())\/3600.0;\n sexagesimal::Sexagesimal time{hour};\n\n \n\n cout << timestamp.Year() << \" \";\n cout << timestamp.Month() << \" \";\n cout << timestamp.Day() << \" \";\n cout << time.to_string() << endl;\n cout << endl;\n\n CAA3DCoordinate RA_Dec_Dist = solar_system::calculate_moon_RA_Dec_Dist(timestamp.Julian());\n\n \/\/ cout << \"Lunar Distance = \" << RA_Dec_Dist.Z << endl;\n printf( \"Lunar Distance = %12.6lf km\\n\", RA_Dec_Dist.Z );\n cout << \" Geocentric RA \" << sexagesimal::Sexagesimal(RA_Dec_Dist.X).to_string() << endl;\n printf( \"%12.6f km\\n\", RA_Dec_Dist.X );\n cout << \"Geocentric Declination \" << sexagesimal::Sexagesimal(RA_Dec_Dist.Y).to_string() << endl;\n printf( \"%12.6f km\\n\", RA_Dec_Dist.Y );\n double distance_AU = RA_Dec_Dist.Z\/solar_system::AU_kilometers;\n printf( \"Lunar Distance = %12.6lf Astronomical Units\\n\", distance_AU );\n double altitude = 0.0;\n\n \/\/ Sexagesimal( int32_t hhh, uint8_t mm, uint8_t ss, uint16_t xxx);\n sexagesimal::Sexagesimal longitude{ 93, 6, 6, 0}; \/* Saint Paul, Minnesota West Longitude is negative per Meeus *\/\n sexagesimal::Sexagesimal latitude{ 44, 57, 19, 0}; \n if( 0 ){\n longitude = sexagesimal::Sexagesimal{ 0, 0, 0, 0}; \/* Greenwich *\/\n latitude = sexagesimal::Sexagesimal{ 51, 28, 6, 0}; \n }\n cout << altitude << endl;\n\n cout << \"Longitude: \" << longitude.to_string() << endl;\n printf( \"%f\\n\", longitude.to_double() );\n cout << \" Latitude: \" << latitude.to_string() << endl;\n printf( \"%f\\n\", latitude.to_double() );\n double lat = CAACoordinateTransformation::DegreesToRadians(latitude.to_double());\n double rho = 0.9983271 + .0016764*cos(2.0*lat) -.0000035*cos(4*lat);\n cout << rho << endl;\n\n CAA2DCoordinate correction = CAAParallax::Equatorial2TopocentricDelta( RA_Dec_Dist.X, \n\t\t\t\t\t\t\t\t\t RA_Dec_Dist.Y, \n\t\t\t\t\t\t\t\t\t distance_AU,\n\t\t\t\t\t\t\t\t\t longitude.to_double(),\n\t\t\t\t\t\t\t\t\t latitude.to_double(),\n\t\t\t\t\t\t\t\t\t 0.0,\n\t\t\t\t\t\t\t\t\t timestamp.Julian());\n cout << \"Corrections for parallax\" << endl;\n\n printf( \" X = %18.9f\\n\", correction.X);\n printf( \" Y = %18.9f\\n\", correction.Y);\n \n\n RA_Dec_Dist.X += correction.X;\n RA_Dec_Dist.Y += correction.Y;\n\n cout << \" Topocentric RA \" << sexagesimal::Sexagesimal(RA_Dec_Dist.X).to_string() << endl;\n cout << \"Topocentric Declination \" << sexagesimal::Sexagesimal(RA_Dec_Dist.Y).to_string() << endl;\n\n cout << \"Do Over!\" << endl;\n RA_Dec_Dist = solar_system::calculate_moon_RA_Dec_Dist(timestamp.Julian());\n CAA2DCoordinate correction_rigorous = Equatorial2TopocentricDeltaRigorous( RA_Dec_Dist.X, \n\t\t\t\t\t\t\t\t\t RA_Dec_Dist.Y, \n\t\t\t\t\t\t\t\t\t RA_Dec_Dist.Z\/solar_system::AU_kilometers,\n\t\t\t\t\t\t\t\t\t longitude.to_double(),\n\t\t\t\t\t\t\t\t\t latitude.to_double(),\n\t\t\t\t\t\t\t\t\t 0.0,\n\t\t\t\t\t\t\t\t\t timestamp.Julian());\n cout << \"Local Corrections for parallax\" << endl;\n\n printf( \" X = %18.9f\\n\", correction_rigorous.X);\n printf( \" Y = %18.9f\\n\", correction_rigorous.Y);\n\n RA_Dec_Dist.X += correction_rigorous.X;\n RA_Dec_Dist.Y += correction_rigorous.Y;\n\n cout << \" Topocentric RA \" << sexagesimal::Sexagesimal(RA_Dec_Dist.X).to_string() << endl;\n cout << \"Topocentric Declination \" << sexagesimal::Sexagesimal(RA_Dec_Dist.Y).to_string() << endl;\n\n\n cout << \"\\nDo Over! Again!\" << endl;\n RA_Dec_Dist = solar_system::calculate_moon_RA_Dec_Dist(timestamp.Julian());\n CAA2DCoordinate Topocentric_RA_Dec = Equatorial2TopocentricRigorousVerbose( RA_Dec_Dist.X, \n\t\t\t\t\t\t\t\t\t RA_Dec_Dist.Y, \n\t\t\t\t\t\t\t\t\t RA_Dec_Dist.Z\/solar_system::AU_kilometers,\n\t\t\t\t\t\t\t\t\t longitude.to_double(),\n\t\t\t\t\t\t\t\t\t latitude.to_double(),\n\t\t\t\t\t\t\t\t\t 0.0,\n\t\t\t\t\t\t\t\t\t timestamp.Julian());\n\n cout << \" Topocentric RA \" << sexagesimal::Sexagesimal(Topocentric_RA_Dec.X).to_string() << endl;\n cout << \"Topocentric Declination \" << sexagesimal::Sexagesimal(Topocentric_RA_Dec.Y).to_string() << endl;\n\n cout << \"\\nDo Over! Non Rigorous Method \" << endl;\n cout << \"This time with the actual uC code.\" << endl;\n RA_Dec_Dist = solar_system::calculate_moon_RA_Dec_Dist(timestamp.Julian());\n Topocentric_RA_Dec = Equatorial2TopocentricNonRigorous( RA_Dec_Dist.X, \n\t\t\t\t\t\t\t RA_Dec_Dist.Y, \n\t\t\t\t\t\t\t RA_Dec_Dist.Z\/solar_system::AU_kilometers,\n\t\t\t\t\t\t\t longitude.to_double(),\n\t\t\t\t\t\t\t latitude.to_double(),\n\t\t\t\t\t\t\t 0.0,\n\t\t\t\t\t\t\t timestamp.Julian());\n\n printf( \"Julian Date = %18.9lf\\n\", timestamp.Julian() );\n cout << \" Topocentric RA \" << sexagesimal::Sexagesimal(Topocentric_RA_Dec.X).to_string() << endl;\n cout << \"Topocentric Declination \" << sexagesimal::Sexagesimal(Topocentric_RA_Dec.Y).to_string() << endl;\n\n\n\n cout << \"\\nDo Over! Yet Again!!\" << endl;\n cout << \"This time with the actual uC code.\" << endl;\n RA_Dec_Dist = solar_system::calculate_moon_RA_Dec_Dist(timestamp.Julian());\n Topocentric_RA_Dec = Equatorial2TopocentricRigorous( RA_Dec_Dist.X, \n\t\t\t\t\t\t\t RA_Dec_Dist.Y, \n\t\t\t\t\t\t\t RA_Dec_Dist.Z\/solar_system::AU_kilometers,\n\t\t\t\t\t\t\t longitude.to_double(),\n\t\t\t\t\t\t\t latitude.to_double(),\n\t\t\t\t\t\t\t 0.0,\n\t\t\t\t\t\t\t timestamp.Julian());\n\n printf( \"Julian Date = %18.9lf\\n\", timestamp.Julian() );\n cout << \" Topocentric RA \" << sexagesimal::Sexagesimal(Topocentric_RA_Dec.X).to_string() << endl;\n cout << \"Topocentric Declination \" << sexagesimal::Sexagesimal(Topocentric_RA_Dec.Y).to_string() << endl;\n\n\n cout << \"\\nDo Over! Yet Again!!! Alternative \" << endl;\n cout << \"This time with the actual uC code.\" << endl;\n RA_Dec_Dist = solar_system::calculate_moon_RA_Dec_Dist(timestamp.Julian());\n Topocentric_RA_Dec = Equatorial2TopocentricRigorousAlternative( RA_Dec_Dist.X, \n\t\t\t\t\t\t\t RA_Dec_Dist.Y, \n\t\t\t\t\t\t\t RA_Dec_Dist.Z\/solar_system::AU_kilometers,\n\t\t\t\t\t\t\t longitude.to_double(),\n\t\t\t\t\t\t\t latitude.to_double(),\n\t\t\t\t\t\t\t 0.0,\n\t\t\t\t\t\t\t timestamp.Julian());\n\n printf( \"Julian Date = %18.9lf\\n\", timestamp.Julian() );\n cout << \" Topocentric RA \" << sexagesimal::Sexagesimal(Topocentric_RA_Dec.X).to_string() << endl;\n cout << \"Topocentric Declination \" << sexagesimal::Sexagesimal(Topocentric_RA_Dec.Y).to_string() << endl;\n\n\n\n cout << \"\\nDo Over! Yet Again!!! PJ Naughter method \" << endl;\n cout << \"This time with the actual uC code.\" << endl;\n RA_Dec_Dist = solar_system::calculate_moon_RA_Dec_Dist(timestamp.Julian());\n Topocentric_RA_Dec = Equatorial2TopocentricRigorous_PJ( RA_Dec_Dist.X, \n\t\t\t\t\t\t\t RA_Dec_Dist.Y, \n\t\t\t\t\t\t\t RA_Dec_Dist.Z\/solar_system::AU_kilometers,\n\t\t\t\t\t\t\t longitude.to_double(),\n\t\t\t\t\t\t\t latitude.to_double(),\n\t\t\t\t\t\t\t 0.0,\n\t\t\t\t\t\t\t timestamp.Julian());\n\n printf( \"Julian Date = %18.9lf\\n\", timestamp.Julian() );\n cout << \" Topocentric RA \" << sexagesimal::Sexagesimal(Topocentric_RA_Dec.X).to_string() << endl;\n cout << \"Topocentric Declination \" << sexagesimal::Sexagesimal(Topocentric_RA_Dec.Y).to_string() << endl;\n\n\n return 0;\n}\nRemoved crust from moon_test.cpp#include \n#include \"AADate.h\"\n#include \"sexagesimal.h\"\n#include \"AACoordinateTransformation.h\"\n#include \"AA3DCoordinate.h\"\n#include \"solar_system.h\"\n#include \"AAParallax.h\"\n#include \"AAGlobe.h\"\n#include \"AASidereal.h\"\n#include \n#include \"binary_tidbits.h\"\n#include \"horizontal_parallax.h\"\n\nusing std::cout;\nusing std::endl;\n\n\nint main( int argc, char **argv){\n long check;\n long unix_time = time( &check ); \n CAADate unix_epoch {1970,1,1, true};\n\n CAADate timestamp;\n\n if( 1 ){\n timestamp = CAADate( unix_epoch.Julian() + static_cast(unix_time)\/86400.0, true );\n }else{\n \/\/ timestamp = CAADate( 2015,3,31,15,55,0.0, true );\n timestamp = CAADate( 1992,4,12,0,0,0.0, true );\n }\n printf( \"Julian Date = %18.9lf\\n\", timestamp.Julian() );\n double hour = timestamp.Hour();\n hour += static_cast(timestamp.Minute())\/60.0;\n hour += static_cast(timestamp.Second())\/3600.0;\n sexagesimal::Sexagesimal time{hour};\n\n \n\n cout << timestamp.Year() << \" \";\n cout << timestamp.Month() << \" \";\n cout << timestamp.Day() << \" \";\n cout << time.to_string() << endl;\n cout << endl;\n\n CAA3DCoordinate RA_Dec_Dist = solar_system::calculate_moon_RA_Dec_Dist(timestamp.Julian());\n\n \/\/ cout << \"Lunar Distance = \" << RA_Dec_Dist.Z << endl;\n printf( \"Lunar Distance = %12.6lf km\\n\", RA_Dec_Dist.Z );\n cout << \" Geocentric RA \" << sexagesimal::Sexagesimal(RA_Dec_Dist.X).to_string() << endl;\n printf( \"%12.6f \\n\", RA_Dec_Dist.X );\n cout << \"Geocentric Declination \" << sexagesimal::Sexagesimal(RA_Dec_Dist.Y).to_string() << endl;\n printf( \"%12.6f \\n\", RA_Dec_Dist.Y );\n double distance_AU = RA_Dec_Dist.Z\/solar_system::AU_kilometers;\n printf( \"Lunar Distance = %12.6lf Astronomical Units\\n\", distance_AU );\n double altitude_asl = 0.0; \/* Above Sea Level *\/\n\n \/\/ Sexagesimal( int32_t hhh, uint8_t mm, uint8_t ss, uint16_t xxx);\n sexagesimal::Sexagesimal longitude{ 93, 6, 6, 0}; \/* Saint Paul, Minnesota West Longitude is negative per Meeus *\/\n sexagesimal::Sexagesimal latitude{ 44, 57, 19, 0}; \n if( 0 ){\n longitude = sexagesimal::Sexagesimal{ 0, 0, 0, 0}; \/* Greenwich *\/\n latitude = sexagesimal::Sexagesimal{ 51, 28, 6, 0}; \n }\n cout << \"altitude = \" << altitude_asl << \" meters above sea level. \" << endl;\n\n cout << \"Longitude: \" << longitude.to_string() << endl;\n printf( \"%f\\n\", longitude.to_double() );\n cout << \" Latitude: \" << latitude.to_string() << endl;\n printf( \"%f\\n\", latitude.to_double() );\n\n CAA2DCoordinate correction = CAAParallax::Equatorial2TopocentricDelta( RA_Dec_Dist.X, \n\t\t\t\t\t\t\t\t\t RA_Dec_Dist.Y, \n\t\t\t\t\t\t\t\t\t distance_AU,\n\t\t\t\t\t\t\t\t\t longitude.to_double(),\n\t\t\t\t\t\t\t\t\t latitude.to_double(),\n\t\t\t\t\t\t\t\t\t 0.0,\n\t\t\t\t\t\t\t\t\t timestamp.Julian());\n cout << \"Corrections for parallax\" << endl;\n\n printf( \" X = %18.9f\\n\", correction.X);\n printf( \" Y = %18.9f\\n\", correction.Y);\n \n\n RA_Dec_Dist.X += correction.X;\n RA_Dec_Dist.Y += correction.Y;\n\n cout << \" Topocentric RA \" << sexagesimal::Sexagesimal(RA_Dec_Dist.X).to_string() << endl;\n cout << \"Topocentric Declination \" << sexagesimal::Sexagesimal(RA_Dec_Dist.Y).to_string() << endl;\n\n cout << \"\\nDo Over, RigorousAlternative ... \" << endl;\n cout << \"using actual uC code.\" << endl;\n RA_Dec_Dist = solar_system::calculate_moon_RA_Dec_Dist(timestamp.Julian());\n CAA2DCoordinate Topocentric_RA_Dec;\n Topocentric_RA_Dec = Equatorial2TopocentricRigorousAlternative( RA_Dec_Dist.X, \n\t\t\t\t\t\t\t RA_Dec_Dist.Y, \n\t\t\t\t\t\t\t RA_Dec_Dist.Z\/solar_system::AU_kilometers,\n\t\t\t\t\t\t\t longitude.to_double(),\n\t\t\t\t\t\t\t latitude.to_double(),\n\t\t\t\t\t\t\t 0.0,\n\t\t\t\t\t\t\t timestamp.Julian());\n\n printf( \"Julian Date = %18.9lf\\n\", timestamp.Julian() );\n cout << \" Topocentric RA \" << sexagesimal::Sexagesimal(Topocentric_RA_Dec.X).to_string() << endl;\n cout << \"Topocentric Declination \" << sexagesimal::Sexagesimal(Topocentric_RA_Dec.Y).to_string() << endl;\n\n\n\n cout << \"\\nDo Over! Yet Again!!! PJ Naughter method \" << endl;\n cout << \"This time with the actual uC code.\" << endl;\n RA_Dec_Dist = solar_system::calculate_moon_RA_Dec_Dist(timestamp.Julian());\n Topocentric_RA_Dec = Equatorial2TopocentricRigorous_PJ( RA_Dec_Dist.X, \n\t\t\t\t\t\t\t RA_Dec_Dist.Y, \n\t\t\t\t\t\t\t RA_Dec_Dist.Z\/solar_system::AU_kilometers,\n\t\t\t\t\t\t\t longitude.to_double(),\n\t\t\t\t\t\t\t latitude.to_double(),\n\t\t\t\t\t\t\t 0.0,\n\t\t\t\t\t\t\t timestamp.Julian());\n\n printf( \"Julian Date = %18.9lf\\n\", timestamp.Julian() );\n cout << \" Topocentric RA \" << sexagesimal::Sexagesimal(Topocentric_RA_Dec.X).to_string() << endl;\n cout << \"Topocentric Declination \" << sexagesimal::Sexagesimal(Topocentric_RA_Dec.Y).to_string() << endl;\n\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"board.h\"\n#include \"movegen.h\"\n#include \"catch.hpp\"\n\nint perft(int depth, Board board) {\n if (depth == 0) {\n return 1;\n }\n\n MoveGen movegen(board);\n\n int nodes = 0;\n for (auto move : movegen.getMoves()) {\n Board tempBoard = board;\n tempBoard.doMove(move);\n\n if (!tempBoard.WHITE_TO_MOVE && tempBoard.whiteIsInCheck()) {\n continue;\n } else if (tempBoard.WHITE_TO_MOVE && tempBoard.blackIsInCheck()) {\n continue;\n }\n\n nodes += perft(depth - 1, tempBoard);\n }\n\n return nodes;\n}\n\nTEST_CASE(\"Perft is correct\") {\n Board board;\n\n SECTION(\"Perft is correct from the starting position\") {\n board.setToStartPos();\n REQUIRE(perft(1, board) == 20);\n REQUIRE(perft(2, board) == 400);\n REQUIRE(perft(3, board) == 8902);\n REQUIRE(perft(4, board) == 197281);\n }\n\n SECTION(\"Perft is correct from r3k2r\/p1ppqpb1\/bn2pnp1\/3PN3\/1p2P3\/2N2Q1p\/PPPBBPPP\/R3K2R w KQkq -\") {\n board.setToFen(\"r3k2r\/p1ppqpb1\/bn2pnp1\/3PN3\/1p2P3\/2N2Q1p\/PPPBBPPP\/R3K2R w KQkq -\");\n\n REQUIRE(perft(1, board) == 48);\n REQUIRE(perft(2, board) == 2039);\n REQUIRE(perft(3, board) == 97862);\n REQUIRE(perft(4, board) == 4085603);\n \/\/ REQUIRE(perft(5, board) == 193690690); \/\/ SLOW\n }\n\n SECTION(\"Perft is correct from 8\/2p5\/3p4\/KP5r\/1R3p1k\/8\/4P1P1\/8 w - -\") {\n board.setToFen(\"8\/2p5\/3p4\/KP5r\/1R3p1k\/8\/4P1P1\/8 w - -\");\n\n REQUIRE(perft(1, board) == 14);\n REQUIRE(perft(2, board) == 191);\n REQUIRE(perft(3, board) == 2812);\n REQUIRE(perft(4, board) == 43238);\n REQUIRE(perft(5, board) == 674624);\n \/\/ REQUIRE(perft(6, board) == 11030083); \/\/ SLOW\n }\n\n SECTION(\"Perft is correct from r3k2r\/Pppp1ppp\/1b3nbN\/nP6\/BBP1P3\/q4N2\/Pp1P2PP\/R2Q1RK1 w kq - 0 1\") {\n board.setToFen(\"r3k2r\/Pppp1ppp\/1b3nbN\/nP6\/BBP1P3\/q4N2\/Pp1P2PP\/R2Q1RK1 w kq - 0 1\");\n\n REQUIRE(perft(1, board) == 6);\n REQUIRE(perft(2, board) == 264);\n REQUIRE(perft(3, board) == 9467);\n REQUIRE(perft(4, board) == 422333);\n \/\/ REQUIRE(perft(5, board) == 15833292); \/\/ SLOW\n }\n\n SECTION(\"Perft is correct from rnbq1k1r\/pp1Pbppp\/2p5\/8\/2B5\/8\/PPP1NnPP\/RNBQK2R w KQ - 1 8 \") {\n board.setToFen(\"rnbq1k1r\/pp1Pbppp\/2p5\/8\/2B5\/8\/PPP1NnPP\/RNBQK2R w KQ - 1 8 \");\n\n REQUIRE(perft(1, board) == 44);\n REQUIRE(perft(2, board) == 1486);\n REQUIRE(perft(3, board) == 62379);\n REQUIRE(perft(4, board) == 2103487);\n \/\/ REQUIRE(perft(5, board) == 89941194); \/\/ SLOW\n }\n\n SECTION(\"Perft is correct from r4rk1\/1pp1qppp\/p1np1n2\/2b1p1B1\/2B1P1b1\/P1NP1N2\/1PP1QPPP\/R4RK1 w - - 0 10\") {\n board.setToFen(\"r4rk1\/1pp1qppp\/p1np1n2\/2b1p1B1\/2B1P1b1\/P1NP1N2\/1PP1QPPP\/R4RK1 w - - 0 10\");\n\n REQUIRE(perft(1, board) == 46);\n REQUIRE(perft(2, board) == 2079);\n REQUIRE(perft(3, board) == 89890);\n REQUIRE(perft(4, board) == 3894594);\n }\n}\nAdd more perft tests#include \"board.h\"\n#include \"movegen.h\"\n#include \"catch.hpp\"\n\nint perft(int depth, Board board) {\n if (depth == 0) {\n return 1;\n }\n\n MoveGen movegen(board);\n\n int nodes = 0;\n for (auto move : movegen.getMoves()) {\n Board tempBoard = board;\n tempBoard.doMove(move);\n\n if (!tempBoard.WHITE_TO_MOVE && tempBoard.whiteIsInCheck()) {\n continue;\n } else if (tempBoard.WHITE_TO_MOVE && tempBoard.blackIsInCheck()) {\n continue;\n }\n\n nodes += perft(depth - 1, tempBoard);\n }\n\n return nodes;\n}\n\nTEST_CASE(\"Perft is correct\") {\n Board board;\n\n SECTION(\"Perft is correct from the starting position\") {\n board.setToStartPos();\n\n REQUIRE(perft(1, board) == 20);\n REQUIRE(perft(2, board) == 400);\n REQUIRE(perft(3, board) == 8902);\n REQUIRE(perft(4, board) == 197281);\n\n \/\/ SLOW\n \/\/ REQUIRE(perft(5, board) == 4865609);\n \/\/ REQUIRE(perft(6, board) == 119060324);\n \/\/ REQUIRE(perft(7, board) == 3195901860);\n \/\/ REQUIRE(perft(8, board) == 84998978956);\n }\n\n SECTION(\"Perft is correct from r3k2r\/p1ppqpb1\/bn2pnp1\/3PN3\/1p2P3\/2N2Q1p\/PPPBBPPP\/R3K2R w KQkq -\") {\n board.setToFen(\"r3k2r\/p1ppqpb1\/bn2pnp1\/3PN3\/1p2P3\/2N2Q1p\/PPPBBPPP\/R3K2R w KQkq -\");\n\n REQUIRE(perft(1, board) == 48);\n REQUIRE(perft(2, board) == 2039);\n REQUIRE(perft(3, board) == 97862);\n REQUIRE(perft(4, board) == 4085603);\n\n \/\/ SLOW\n \/\/ REQUIRE(perft(5, board) == 193690690);\n }\n\n SECTION(\"Perft is correct from 8\/2p5\/3p4\/KP5r\/1R3p1k\/8\/4P1P1\/8 w - -\") {\n board.setToFen(\"8\/2p5\/3p4\/KP5r\/1R3p1k\/8\/4P1P1\/8 w - -\");\n\n REQUIRE(perft(1, board) == 14);\n REQUIRE(perft(2, board) == 191);\n REQUIRE(perft(3, board) == 2812);\n REQUIRE(perft(4, board) == 43238);\n REQUIRE(perft(5, board) == 674624);\n\n \/\/ SLOW\n \/\/ REQUIRE(perft(7, board) == 178633661);\n \/\/ REQUIRE(perft(6, board) == 11030083); \/\/ SLOW\n }\n\n SECTION(\"Perft is correct from r3k2r\/Pppp1ppp\/1b3nbN\/nP6\/BBP1P3\/q4N2\/Pp1P2PP\/R2Q1RK1 w kq - 0 1\") {\n board.setToFen(\"r3k2r\/Pppp1ppp\/1b3nbN\/nP6\/BBP1P3\/q4N2\/Pp1P2PP\/R2Q1RK1 w kq - 0 1\");\n\n REQUIRE(perft(1, board) == 6);\n REQUIRE(perft(2, board) == 264);\n REQUIRE(perft(3, board) == 9467);\n REQUIRE(perft(4, board) == 422333);\n\n \/\/ SLOW\n \/\/ REQUIRE(perft(5, board) == 15833292);\n \/\/ REQUIRE(perft(6, board) == 706045033);\n }\n\n SECTION(\"Perft is correct from rnbq1k1r\/pp1Pbppp\/2p5\/8\/2B5\/8\/PPP1NnPP\/RNBQK2R w KQ - 1 8 \") {\n board.setToFen(\"rnbq1k1r\/pp1Pbppp\/2p5\/8\/2B5\/8\/PPP1NnPP\/RNBQK2R w KQ - 1 8 \");\n\n REQUIRE(perft(1, board) == 44);\n REQUIRE(perft(2, board) == 1486);\n REQUIRE(perft(3, board) == 62379);\n REQUIRE(perft(4, board) == 2103487);\n\n \/\/ SLOW\n \/\/ REQUIRE(perft(5, board) == 89941194);\n }\n\n SECTION(\"Perft is correct from r4rk1\/1pp1qppp\/p1np1n2\/2b1p1B1\/2B1P1b1\/P1NP1N2\/1PP1QPPP\/R4RK1 w - - 0 10\") {\n board.setToFen(\"r4rk1\/1pp1qppp\/p1np1n2\/2b1p1B1\/2B1P1b1\/P1NP1N2\/1PP1QPPP\/R4RK1 w - - 0 10\");\n\n REQUIRE(perft(1, board) == 46);\n REQUIRE(perft(2, board) == 2079);\n REQUIRE(perft(3, board) == 89890);\n REQUIRE(perft(4, board) == 3894594);\n\n \/\/ SLOW\n \/\/ REQUIRE(perft(5, board) == 164075551);\n \/\/ REQUIRE(perft(6, board) == 6923051137);\n \/\/ REQUIRE(perft(7, board) == 287188994746);\n \/\/ REQUIRE(perft(8, board) == 11923589843526);\n \/\/ REQUIRE(perft(9, board) == 490154852788714);\n }\n\n SECTION(\"Perft is correct from n1n5\/PPPk4\/8\/8\/8\/8\/4Kppp\/5N1N b - - 0 1\") {\n board.setToFen(\"n1n5\/PPPk4\/8\/8\/8\/8\/4Kppp\/5N1N b - - 0 1\");\n\n REQUIRE(perft(1, board) == 24);\n REQUIRE(perft(2, board) == 496);\n REQUIRE(perft(3, board) == 9483);\n REQUIRE(perft(4, board) == 182838);\n\n \/\/ SLOW\n \/\/ REQUIRE(perft(5, board) == 3605103);\n \/\/ REQUIRE(perft(6, board) == 71179139);\n }\n\n SECTION(\"Perft is correct from k1q4b\/1qq3bR\/qq3b1R\/r2Rr2R\/r2rR2R\/r1B3QQ\/rB3QQ1\/B4Q1K w - -\") {\n board.setToFen(\"k1q4b\/1qQ3bR\/qQ3b1R\/r2RR2R\/r2rr2R\/r1B3qQ\/rB3qQ1\/B4Q1K w - -\");\n\n REQUIRE(perft(1, board) == 78);\n REQUIRE(perft(2, board) == 5451);\n REQUIRE(perft(3, board) == 388081);\n\n \/\/ SLOW\n \/\/ REQUIRE(perft(4, board) == 26438936);\n }\n\n}\n<|endoftext|>"} {"text":"\/\/ pc.cpp: show standard posit components: show the sign\/scale\/regime\/exponent\/fraction components of a posit \n\/\/\n\/\/ Copyright (C) 2017 Stillwater Supercomputing, Inc.\n\/\/\n\/\/ This file is part of the universal numbers project, which is released under an MIT Open Source license.\n\n#include \"stdafx.h\"\n\n#include \n\nusing namespace std;\nusing namespace sw::unum;\n\ntypedef std::numeric_limits< double > dbl;\n\n\/\/ receive a float and print its components\nint main(int argc, char** argv)\ntry {\n\tif (argc != 2) {\n\t\tcerr << \"Show the sign\/scale\/regime\/exponent\/fraction components of a posit.\" << endl;\n\t cerr << \"Usage: pc float_value\" << endl;\n\t\tcerr << \"Example: pc -1.123456789e17\" << endl;\n\t\tcerr << \"posit< 8,0>: \" << endl;\n\t\tcerr << \"posit<16,1>: \" << endl;\n\t\tcerr << \"posit<32,2>: \" << endl;\n\t\tcerr << \"posit<64,3>: \" << endl;\n\t\treturn EXIT_SUCCESS; \/\/ signal successful completion for ctest\n\t}\n\tdouble d = atof(argv[1]);\n\tposit<8, 0> p8(d);\n\tposit<16, 1> p16(d);\n\tposit<32, 2> p32(d);\n\tposit<48, 2> p48(d);\n\t\/\/posit<64, 3> p64(d);\n\n\tint precision = dbl::max_digits10;\n\tcout << \"posit< 8,0> = \" << pretty_print(p8, precision) << endl;\n\tcout << \"posit<16,1> = \" << pretty_print(p16, precision) << endl;\n\tcout << \"posit<32,2> = \" << pretty_print(p32, precision) << endl;\n\tcout << \"posit<48,2> = \" << pretty_print(p48, precision) << endl;\n\t\/\/cout << \"posit<64,3> = \" << pretty_print(p64, precision) << endl;\n\n\treturn EXIT_SUCCESS;\n}\ncatch (char* msg) {\n\tcerr << msg << endl;\n\treturn EXIT_FAILURE;\n}\nAdding a collection of standard posit configs to compare\/\/ pc.cpp: show standard posit components: show the sign\/scale\/regime\/exponent\/fraction components of a posit \n\/\/\n\/\/ Copyright (C) 2017 Stillwater Supercomputing, Inc.\n\/\/\n\/\/ This file is part of the universal numbers project, which is released under an MIT Open Source license.\n\n#include \"stdafx.h\"\n\n#include \n\nusing namespace std;\nusing namespace sw::unum;\n\ntypedef std::numeric_limits< double > dbl;\n\n\/\/ receive a float and print its components\nint main(int argc, char** argv)\ntry {\n\tif (argc != 2) {\n\t\tcerr << \"Show the sign\/scale\/regime\/exponent\/fraction components of a posit.\" << endl;\n\t cerr << \"Usage: pc float_value\" << endl;\n\t\tcerr << \"Example: pc -1.123456789e17\" << endl;\n\t\tcerr << \"posit< 8,0>: \" << endl;\n\t\tcerr << \"posit<16,1>: \" << endl;\n\t\tcerr << \"posit<32,2>: \" << endl;\n\t\tcerr << \"posit<64,3>: \" << endl;\n\t\treturn EXIT_SUCCESS; \/\/ signal successful completion for ctest\n\t}\n\tdouble d = atof(argv[1]);\n\tposit<8, 0> p8_0(d);\n\tposit<8, 1> p8_1(d);\n\tposit<8, 2> p8_2(d);\n\tposit<8, 3> p8_3(d);\n\tposit<16, 1> p16_1(d);\n\tposit<16, 2> p16_2(d);\n\tposit<16, 3> p16_3(d);\n\tposit<32, 1> p32_1(d);\n\tposit<32, 2> p32_2(d);\n\tposit<32, 3> p32_3(d);\n\tposit<48, 1> p48_1(d);\n\tposit<48, 2> p48_2(d);\n\tposit<48, 3> p48_3(d);\n\tposit<64, 1> p64_1(d);\n\tposit<64, 2> p64_2(d);\n\tposit<64, 3> p64_3(d);\n\n\tint precision = dbl::max_digits10;\n\tcout << \"posit< 8,0> = \" << pretty_print(p8_0, precision) << endl;\n\tcout << \"posit< 8,1> = \" << pretty_print(p8_1, precision) << endl;\n\tcout << \"posit< 8,2> = \" << pretty_print(p8_2, precision) << endl;\n\tcout << \"posit< 8,3> = \" << pretty_print(p8_3, precision) << endl;\n\tcout << \"posit<16,1> = \" << pretty_print(p16_1, precision) << endl;\n\tcout << \"posit<16,2> = \" << pretty_print(p16_2, precision) << endl;\n\tcout << \"posit<16,3> = \" << pretty_print(p16_3, precision) << endl;\n\tcout << \"posit<32,1> = \" << pretty_print(p32_1, precision) << endl;\n\tcout << \"posit<32,2> = \" << pretty_print(p32_2, precision) << endl;\n\tcout << \"posit<32,3> = \" << pretty_print(p32_3, precision) << endl;\n\tcout << \"posit<48,1> = \" << pretty_print(p48_1, precision) << endl;\n\tcout << \"posit<48,2> = \" << pretty_print(p48_2, precision) << endl;\n\tcout << \"posit<48,3> = \" << pretty_print(p48_3, precision) << endl;\n\tcout << \"posit<64,1> = \" << pretty_print(p64_1, precision) << endl;\n\tcout << \"posit<64,2> = \" << pretty_print(p64_2, precision) << endl;\n\tcout << \"posit<64,3> = \" << pretty_print(p64_3, precision) << endl;\n\n\treturn EXIT_SUCCESS;\n}\ncatch (char* msg) {\n\tcerr << msg << endl;\n\treturn EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"\/\/ Brock Ferrell\n\/\/ CS2401\n\/\/ November 23, 2015\n\/\/ Project7\n\n#include \"game.h\"\n#include \"othello.h\"\nusing namespace main_savitch_14;\n\n\nint main()\n{\n\tOthello theGame;\n\ttheGame.restart();\n\ttheGame.play();\n}\nUpdated main.cc\/\/ Brock Ferrell\n\/\/ CS2401\n\/\/ November 23, 2015\n\/\/ Project7\n\n\/*! \n\t@file main.cc\n\t@brief Main function to run othello\n\t@author \n*\/\n\n#include \"game.h\"\n#include \"othello.h\"\nusing namespace main_savitch_14;\n\n\/*!\n\t@brief \n*\/\nint main()\n{\n\tOthello theGame;\n\ttheGame.restart();\n\ttheGame.play();\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n** irexec.c ****************************************************************\n****************************************************************************\n*\n* irexec - execute programs according to the pressed remote control buttons\n*\n* Copyright (C) 1998 Trent Piepho \n* Copyright (C) 1998 Christoph Bartelmus \n*\n*\/\n\n#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif\n\n#ifdef HAVE_CONFIG_H\n# include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"lirc_client.h\"\n#include \"lirc_log.h\"\n\nstatic const logchannel_t logchannel = LOG_APP;\n\nstatic const char* const USAGE =\n\t\"Usage: irexec [options] [lircrc config_file]\\n\"\n\t\"\\t-d --daemon\\t\\tRun in background\\n\"\n\t\"\\t-D --loglevel=level\\t'error', 'info', 'notice',... or 0..10\\n\"\n\t\"\\t-n --name=progname\\tUse this program name for lircrc matching\\n\"\n\t\"\\t-h --help\\t\\tDisplay usage summary\\n\"\n\t\"\\t-v --version\\t\\tDisplay version\\n\";\n\nstatic const struct option options[] = {\n\t{ \"help\", no_argument,\t NULL, 'h' },\n\t{ \"version\", no_argument,\t NULL, 'v' },\n\t{ \"daemon\", no_argument,\t NULL, 'd' },\n\t{ \"name\", required_argument, NULL, 'n' },\n\t{ \"loglevel\", required_argument, NULL, 'D' },\n\t{ 0, 0,\t\t 0, 0 }\n};\n\nstatic int opt_daemonize\t= 0;\nstatic loglevel_t opt_loglevel\t= LIRC_NOLOG;\nstatic const char* opt_progname\t= \"irexec\";\n\nstatic char path[256] = {0};\n\n\n\/** Run shell command line in isolated process using double fork(). *\/\nstatic void run_command(const char* cmd)\n{\n\tpid_t pid1;\n\tpid_t pid2;\n\n\tpid1 = fork();\n\tif (pid1 < 0) {\n\t\tlog_perror_err(\"Cannot fork\");\n\t\tperror(\"Cannot fork()\");\n\t\texit(EXIT_FAILURE);\n\t}\n\tif (pid1 == 0) {\n\t\tpid2 = fork();\n\t\tif (pid2 < 0) {\n\t\t\tlog_perror_err(\"Cannot do secondary fork()\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tif (pid2 == 0) {\n\t\t\tlog_debug(\"Execing command \\\"%s\\\"\", cmd);\n\t\t\tchar* const vp[] = {strdup(SH_PATH),\n\t\t\t strdup(\"-c\"),\n\t\t\t strdup(cmd),\n\t\t\t NULL\n\t\t\t};\n\t\t\texecvp(SH_PATH, vp);\n\t\t\t\/* not reached *\/\n\t\t\tlog_perror_err(\"execvp failed\");\n\t\t\tfputs(\"execvp failed\\n\", stderr);\n\t\t} else {\n\t\t\twaitpid(pid2, NULL, WNOHANG);\n\t\t\texit(0);\n\t\t}\n\t} else {\n\t\twaitpid(pid1, NULL, 0);\n\t}\n}\n\n\n\/** Get buttonclick messages from lircd socket and process them. *\/\nstatic void process_input(struct lirc_config* config)\n{\n\tchar* code;\n\tchar* c;\n\tint r;\n\n\twhile (lirc_nextcode(&code) == 0) {\n\t\tif (code == NULL)\n\t\t\tcontinue;\n\t\tr = lirc_code2char(config, code, &c);\n\t\twhile (r == 0 && c != NULL) {\n\t\t\trun_command(c);\n\t\t\tr = lirc_code2char(config, code, &c);\n\t\t}\n\t\tfree(code);\n\t\tif (r == -1)\n\t\t\tbreak;\n\t}\n}\n\n\nint irexec(const char* configfile)\n{\n\tstruct lirc_config* config;\n\n\tif (opt_daemonize) {\n\t\tif (daemon(0, 0) == -1) {\n\t\t\tperror(\"Can't daemonize\");\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tif (lirc_init(opt_progname, opt_daemonize ? 0 : 1) == -1)\n\t\treturn EXIT_FAILURE;\n\n\tif (lirc_readconfig(configfile, &config, NULL) != 0) {\n\t\tfputs(\"Cannot parse config file\\n\", stderr);\n\t\treturn EXIT_FAILURE;\n\t}\n\tlirc_log_get_clientlog(\"irexec\", path, sizeof(path));\n\tunlink(path);\n\tlirc_log_set_file(path);\n\tlirc_log_open(\"irexec\", 1, opt_loglevel);\n\n\tprocess_input(config);\n\tlirc_deinit();\n\n\tlirc_freeconfig(config);\n\treturn EXIT_SUCCESS;\n}\n\n\nint main(int argc, char* argv[])\n{\n\tint c;\n\n\twhile ((c = getopt_long(argc, argv, \"D:hvdn:\", options, NULL)) != -1) {\n\t\tswitch (c) {\n\t\tcase 'h':\n\t\t\tputs(USAGE);\n\t\t\treturn EXIT_SUCCESS;\n\t\tcase 'v':\n\t\t\tputs(\"irexec \" VERSION);\n\t\t\treturn EXIT_SUCCESS;\n\t\tcase 'd':\n\t\t\topt_daemonize = 1;\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\topt_progname = optarg;\n\t\t\tbreak;\n\t\tcase 'D':\n\t\t\topt_loglevel = string2loglevel(optarg);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfputs(USAGE, stderr);\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tif (optind < argc - 1) {\n\t\tfputs(\"Too many arguments\\n\", stderr);\n\t\treturn EXIT_FAILURE;\n\t}\n\tif (opt_loglevel == LIRC_BADLEVEL) {\n\t\tfprintf(stderr, \"Bad debug level: %s\\n\", optarg);\n\t\treturn EXIT_FAILURE;\n\t}\n\treturn irexec(optind != argc ? argv[optind] : NULL);\n}\nirexec: Handle non-working shells gracefully (#314).\/****************************************************************************\n** irexec.c ****************************************************************\n****************************************************************************\n*\n* irexec - execute programs according to the pressed remote control buttons\n*\n* Copyright (C) 1998 Trent Piepho \n* Copyright (C) 1998 Christoph Bartelmus \n*\n*\/\n\n#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif\n\n#ifdef HAVE_CONFIG_H\n# include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"lirc_client.h\"\n#include \"lirc_log.h\"\n\nstatic const logchannel_t logchannel = LOG_APP;\n\nstatic const char* const USAGE =\n\t\"Usage: irexec [options] [lircrc config_file]\\n\"\n\t\"\\t-d --daemon\\t\\tRun in background\\n\"\n\t\"\\t-D --loglevel=level\\t'error', 'info', 'notice',... or 0..10\\n\"\n\t\"\\t-n --name=progname\\tUse this program name for lircrc matching\\n\"\n\t\"\\t-h --help\\t\\tDisplay usage summary\\n\"\n\t\"\\t-v --version\\t\\tDisplay version\\n\";\n\nstatic const struct option options[] = {\n\t{ \"help\", no_argument,\t NULL, 'h' },\n\t{ \"version\", no_argument,\t NULL, 'v' },\n\t{ \"daemon\", no_argument,\t NULL, 'd' },\n\t{ \"name\", required_argument, NULL, 'n' },\n\t{ \"loglevel\", required_argument, NULL, 'D' },\n\t{ 0, 0,\t\t 0, 0 }\n};\n\nstatic int opt_daemonize\t= 0;\nstatic loglevel_t opt_loglevel\t= LIRC_NOLOG;\nstatic const char* opt_progname\t= \"irexec\";\n\nstatic char path[256] = {0};\n\n\n\/** Run shell command line in isolated process using double fork(). *\/\nstatic void run_command(const char* cmd)\n{\n\tpid_t pid1;\n\tpid_t pid2;\n\n\tpid1 = fork();\n\tif (pid1 < 0) {\n\t\tlog_perror_err(\"Cannot fork\");\n\t\tperror(\"Cannot fork()\");\n\t\texit(EXIT_FAILURE);\n\t}\n\tif (pid1 == 0) {\n\t\tpid2 = fork();\n\t\tif (pid2 < 0) {\n\t\t\tlog_perror_err(\"Cannot do secondary fork()\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tif (pid2 == 0) {\n\t\t\tlog_debug(\"Execing command \\\"%s\\\"\", cmd);\n\t\t\tchar* const vp[] = {strdup(SH_PATH),\n\t\t\t strdup(\"-c\"),\n\t\t\t strdup(cmd),\n\t\t\t NULL\n\t\t\t};\n\t\t\texecvp(SH_PATH, vp);\n\t\t\t\/* not reached, unless there was an error *\/\n\t\t\tlog_perror_err(\"execvp failed\");\n\t\t\tfputs(\"execvp failed\\n\", stderr);\n\t\t\texit(EXIT_FAILURE);\n\t\t} else {\n\t\t\twaitpid(pid2, NULL, WNOHANG);\n\t\t\texit(0);\n\t\t}\n\t} else {\n\t\twaitpid(pid1, NULL, 0);\n\t}\n}\n\n\n\/** Get buttonclick messages from lircd socket and process them. *\/\nstatic void process_input(struct lirc_config* config)\n{\n\tchar* code;\n\tchar* c;\n\tint r;\n\n\twhile (lirc_nextcode(&code) == 0) {\n\t\tif (code == NULL)\n\t\t\tcontinue;\n\t\tr = lirc_code2char(config, code, &c);\n\t\twhile (r == 0 && c != NULL) {\n\t\t\trun_command(c);\n\t\t\tr = lirc_code2char(config, code, &c);\n\t\t}\n\t\tfree(code);\n\t\tif (r == -1)\n\t\t\tbreak;\n\t}\n}\n\n\nint irexec(const char* configfile)\n{\n\tstruct lirc_config* config;\n\n\tif (opt_daemonize) {\n\t\tif (daemon(0, 0) == -1) {\n\t\t\tperror(\"Can't daemonize\");\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tif (lirc_init(opt_progname, opt_daemonize ? 0 : 1) == -1)\n\t\treturn EXIT_FAILURE;\n\n\tif (lirc_readconfig(configfile, &config, NULL) != 0) {\n\t\tfputs(\"Cannot parse config file\\n\", stderr);\n\t\treturn EXIT_FAILURE;\n\t}\n\tlirc_log_get_clientlog(\"irexec\", path, sizeof(path));\n\tunlink(path);\n\tlirc_log_set_file(path);\n\tlirc_log_open(\"irexec\", 1, opt_loglevel);\n\n\tprocess_input(config);\n\tlirc_deinit();\n\n\tlirc_freeconfig(config);\n\treturn EXIT_SUCCESS;\n}\n\n\nint main(int argc, char* argv[])\n{\n\tint c;\n\n\twhile ((c = getopt_long(argc, argv, \"D:hvdn:\", options, NULL)) != -1) {\n\t\tswitch (c) {\n\t\tcase 'h':\n\t\t\tputs(USAGE);\n\t\t\treturn EXIT_SUCCESS;\n\t\tcase 'v':\n\t\t\tputs(\"irexec \" VERSION);\n\t\t\treturn EXIT_SUCCESS;\n\t\tcase 'd':\n\t\t\topt_daemonize = 1;\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\topt_progname = optarg;\n\t\t\tbreak;\n\t\tcase 'D':\n\t\t\topt_loglevel = string2loglevel(optarg);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfputs(USAGE, stderr);\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tif (optind < argc - 1) {\n\t\tfputs(\"Too many arguments\\n\", stderr);\n\t\treturn EXIT_FAILURE;\n\t}\n\tif (opt_loglevel == LIRC_BADLEVEL) {\n\t\tfprintf(stderr, \"Bad debug level: %s\\n\", optarg);\n\t\treturn EXIT_FAILURE;\n\t}\n\treturn irexec(optind != argc ? argv[optind] : NULL);\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2013 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n\n#include \n\n#include \n\n\nint main()\n{\n auto time_now(mlk::tm::time_stmp()); \/\/ get current time as long long; f.e.: 1385206783049705\n \n \n auto start(mlk::tm::time_pnt());\n\n std::this_thread::sleep_for(std::chrono::milliseconds(5000)); \/\/ do work\n \n auto end(mlk::tm::time_pnt());\n\n \n std::cout << mlk::tm::duration(start, end) << std::endl; \/\/ prints 5000\n \/\/ use mlk::tm::duration(start, end) to get microseconds etc..\n std::cout << mlk::tm::timed_out(start, 1000) << std::endl; \/\/ prints 1 because the duration of start and now is higher than 1000\n \n \n std::cout << mlk::tm::time_str() << std::endl; \/\/ prints the current time as string; f.e.: Sat Nov 32 12:13:44 2013\n}adapted test_time.cpp\/\/\n\/\/ Copyright (c) 2013 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n\n#include \n\n#include \n\n\nint main()\n{\n auto time_now(mlk::tm::time_stmp()); \/\/ get current time as long long; f.e.: 1385206783049705\n \n \n auto start(mlk::tm::time_pnt());\n\n mlk::tm::sleep(5000); \/\/ do work\n \n auto end(mlk::tm::time_pnt());\n\n \n std::cout << mlk::tm::duration(start, end) << std::endl; \/\/ prints 5000\n \/\/ use mlk::tm::duration(start, end) to get microseconds etc..\n std::cout << mlk::tm::timed_out(start, 1000) << std::endl; \/\/ prints 1 because the duration of start and now is higher than 1000\n \n \n std::cout << mlk::tm::time_str() << std::endl; \/\/ prints the current time as string; f.e.: Sat Nov 32 12:13:44 2013\n}<|endoftext|>"} {"text":"#ifndef UTILS_HPP\n#define UTILS_HPP\n\n#include \n\n#include \n\n#include \n#include \n\n#ifdef OPENCL\n#include \n#endif\n\n#include \n#include \n#include \n#include \n\nnamespace trac0r {\n\ninline void print_sysinfo() {\n fmt::print(\"Rendering on\\n\");\n#ifdef OPENCL\n auto device = boost::compute::system::default_device();\n const auto &devices = boost::compute::system::devices();\n for (size_t i = 0; i < devices.size(); i++) {\n fmt::print(\" GPU (Device {}: {}, OpenCL version: {}, driver version: {})\\n\", i + 1,\n devices[i].name(), devices[i].version(), devices[i].driver_version());\n }\n#else\n auto threads = std::thread::hardware_concurrency();\n fmt::print(\" CPU ({} threads)\\n\", threads);\n#endif\n}\n\ninline SDL_Texture *make_text(SDL_Renderer *renderer, TTF_Font *font, std::string text,\n const SDL_Color &color) {\n auto text_surface = TTF_RenderText_Blended(font, text.c_str(), color);\n auto text_tex = SDL_CreateTextureFromSurface(renderer, text_surface);\n SDL_FreeSurface(text_surface);\n\n return text_tex;\n}\n\ninline void render_text(SDL_Renderer *renderer, SDL_Texture *texture, int pos_x, int pos_y) {\n int tex_width;\n int tex_height;\n\n SDL_QueryTexture(texture, 0, 0, &tex_width, &tex_height);\n SDL_Rect rect{pos_x, pos_y, tex_width, tex_height};\n SDL_RenderCopy(renderer, texture, 0, &rect);\n}\n\ninline uint32_t pack_color_argb(uint8_t a, uint8_t r, uint8_t g, uint8_t b) {\n uint32_t new_color = a << 24 | r << 16 | g << 8 | b;\n return new_color;\n}\n\ninline uint32_t pack_color_argb(glm::i8vec4 color) {\n uint32_t new_color = color.a << 24 | color.r << 16 | color.g << 8 | color.b;\n return new_color;\n}\n\ninline uint32_t pack_color_rgba(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {\n uint32_t packed_color = r << 24 | g << 16 | b << 8 | a;\n return packed_color;\n}\n\ninline uint32_t pack_color_rgba(glm::i8vec4 color) {\n uint32_t packed_color = color.r << 24 | color.g << 16 | color.b << 8 | color.a;\n return packed_color;\n}\n\ninline uint32_t pack_color_rgba(glm::vec4 color) {\n uint32_t packed_color =\n static_cast(glm::round(glm::clamp(color.r, 0.f, 1.f) * 255)) << 24 |\n static_cast(glm::round(glm::clamp(color.g, 0.f, 1.f) * 255)) << 16 |\n static_cast(glm::round(glm::clamp(color.b, 0.f, 1.f) * 255)) << 8 |\n static_cast(glm::round(glm::clamp(color.a, 0.f, 1.f) * 255));\n return packed_color;\n}\n\ninline uint32_t pack_color_argb(glm::vec4 color) {\n uint32_t packed_color =\n static_cast(glm::round(glm::clamp(color.a, 0.f, 1.f) * 255)) << 24 |\n static_cast(glm::round(glm::clamp(color.r, 0.f, 1.f) * 255)) << 16 |\n static_cast(glm::round(glm::clamp(color.g, 0.f, 1.f) * 255)) << 8 |\n static_cast(glm::round(glm::clamp(color.b, 0.f, 1.f) * 255));\n return packed_color;\n}\n\ninline glm::i8vec4 unpack_color_rgba_to_i8vec4(uint32_t packed_color_rgba) {\n glm::i8vec4 unpacked_color;\n unpacked_color.r = packed_color_rgba >> 24 & 0xFF;\n unpacked_color.g = packed_color_rgba >> 16 & 0xFF;\n unpacked_color.b = packed_color_rgba >> 8 & 0xFF;\n unpacked_color.a = packed_color_rgba & 0xFF;\n return unpacked_color;\n}\n\ninline glm::i8vec4 unpack_color_argb_to_i8vec4(uint32_t packed_color_argb) {\n glm::i8vec4 unpacked_color;\n unpacked_color.a = packed_color_argb >> 24 & 0xFF;\n unpacked_color.r = packed_color_argb >> 16 & 0xFF;\n unpacked_color.g = packed_color_argb >> 8 & 0xFF;\n unpacked_color.b = packed_color_argb & 0xFF;\n return unpacked_color;\n}\n\ninline glm::vec4 unpack_color_rgbb_to_vec4(uint32_t packed_color_rgba) {\n glm::i8vec4 unpacked_color;\n unpacked_color.r = (packed_color_rgba >> 24 & 0xFF) \/ 255.f;\n unpacked_color.g = (packed_color_rgba >> 16 & 0xFF) \/ 255.f;\n unpacked_color.b = (packed_color_rgba >> 8 & 0xFF) \/ 255.f;\n unpacked_color.a = (packed_color_rgba & 0xFF) \/ 255.f;\n return unpacked_color;\n}\n\ninline glm::vec4 unpack_color_argb_to_vec4(uint32_t packed_color_argb) {\n glm::vec4 unpacked_color;\n unpacked_color.a = (packed_color_argb >> 24 & 0xFF) \/ 255.f;\n unpacked_color.r = (packed_color_argb >> 16 & 0xFF) \/ 255.f;\n unpacked_color.g = (packed_color_argb >> 8 & 0xFF) \/ 255.f;\n unpacked_color.b = (packed_color_argb & 0xFF) \/ 255.f;\n return unpacked_color;\n}\n}\n\n#endif \/* end of include guard: UTILS_HPP *\/\nBetter names for accelerators#ifndef UTILS_HPP\n#define UTILS_HPP\n\n#include \n\n#include \n\n#include \n#include \n\n#ifdef OPENCL\n#include \n#endif\n\n#include \n#include \n#include \n#include \n\nnamespace trac0r {\n\ninline void print_sysinfo() {\n fmt::print(\"Rendering on\\n\");\n#ifdef OPENCL\n auto device = boost::compute::system::default_device();\n const auto &devices = boost::compute::system::devices();\n for (size_t i = 0; i < devices.size(); i++) {\n fmt::print(\" OpenCL (Device {}: {}, OpenCL version: {}, driver version: {})\\n\", i + 1,\n devices[i].name(), devices[i].version(), devices[i].driver_version());\n }\n#else\n auto threads = std::thread::hardware_concurrency();\n fmt::print(\" OpenMP ({} threads)\\n\", threads);\n#endif\n}\n\ninline SDL_Texture *make_text(SDL_Renderer *renderer, TTF_Font *font, std::string text,\n const SDL_Color &color) {\n auto text_surface = TTF_RenderText_Blended(font, text.c_str(), color);\n auto text_tex = SDL_CreateTextureFromSurface(renderer, text_surface);\n SDL_FreeSurface(text_surface);\n\n return text_tex;\n}\n\ninline void render_text(SDL_Renderer *renderer, SDL_Texture *texture, int pos_x, int pos_y) {\n int tex_width;\n int tex_height;\n\n SDL_QueryTexture(texture, 0, 0, &tex_width, &tex_height);\n SDL_Rect rect{pos_x, pos_y, tex_width, tex_height};\n SDL_RenderCopy(renderer, texture, 0, &rect);\n}\n\ninline uint32_t pack_color_argb(uint8_t a, uint8_t r, uint8_t g, uint8_t b) {\n uint32_t new_color = a << 24 | r << 16 | g << 8 | b;\n return new_color;\n}\n\ninline uint32_t pack_color_argb(glm::i8vec4 color) {\n uint32_t new_color = color.a << 24 | color.r << 16 | color.g << 8 | color.b;\n return new_color;\n}\n\ninline uint32_t pack_color_rgba(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {\n uint32_t packed_color = r << 24 | g << 16 | b << 8 | a;\n return packed_color;\n}\n\ninline uint32_t pack_color_rgba(glm::i8vec4 color) {\n uint32_t packed_color = color.r << 24 | color.g << 16 | color.b << 8 | color.a;\n return packed_color;\n}\n\ninline uint32_t pack_color_rgba(glm::vec4 color) {\n uint32_t packed_color =\n static_cast(glm::round(glm::clamp(color.r, 0.f, 1.f) * 255)) << 24 |\n static_cast(glm::round(glm::clamp(color.g, 0.f, 1.f) * 255)) << 16 |\n static_cast(glm::round(glm::clamp(color.b, 0.f, 1.f) * 255)) << 8 |\n static_cast(glm::round(glm::clamp(color.a, 0.f, 1.f) * 255));\n return packed_color;\n}\n\ninline uint32_t pack_color_argb(glm::vec4 color) {\n uint32_t packed_color =\n static_cast(glm::round(glm::clamp(color.a, 0.f, 1.f) * 255)) << 24 |\n static_cast(glm::round(glm::clamp(color.r, 0.f, 1.f) * 255)) << 16 |\n static_cast(glm::round(glm::clamp(color.g, 0.f, 1.f) * 255)) << 8 |\n static_cast(glm::round(glm::clamp(color.b, 0.f, 1.f) * 255));\n return packed_color;\n}\n\ninline glm::i8vec4 unpack_color_rgba_to_i8vec4(uint32_t packed_color_rgba) {\n glm::i8vec4 unpacked_color;\n unpacked_color.r = packed_color_rgba >> 24 & 0xFF;\n unpacked_color.g = packed_color_rgba >> 16 & 0xFF;\n unpacked_color.b = packed_color_rgba >> 8 & 0xFF;\n unpacked_color.a = packed_color_rgba & 0xFF;\n return unpacked_color;\n}\n\ninline glm::i8vec4 unpack_color_argb_to_i8vec4(uint32_t packed_color_argb) {\n glm::i8vec4 unpacked_color;\n unpacked_color.a = packed_color_argb >> 24 & 0xFF;\n unpacked_color.r = packed_color_argb >> 16 & 0xFF;\n unpacked_color.g = packed_color_argb >> 8 & 0xFF;\n unpacked_color.b = packed_color_argb & 0xFF;\n return unpacked_color;\n}\n\ninline glm::vec4 unpack_color_rgbb_to_vec4(uint32_t packed_color_rgba) {\n glm::i8vec4 unpacked_color;\n unpacked_color.r = (packed_color_rgba >> 24 & 0xFF) \/ 255.f;\n unpacked_color.g = (packed_color_rgba >> 16 & 0xFF) \/ 255.f;\n unpacked_color.b = (packed_color_rgba >> 8 & 0xFF) \/ 255.f;\n unpacked_color.a = (packed_color_rgba & 0xFF) \/ 255.f;\n return unpacked_color;\n}\n\ninline glm::vec4 unpack_color_argb_to_vec4(uint32_t packed_color_argb) {\n glm::vec4 unpacked_color;\n unpacked_color.a = (packed_color_argb >> 24 & 0xFF) \/ 255.f;\n unpacked_color.r = (packed_color_argb >> 16 & 0xFF) \/ 255.f;\n unpacked_color.g = (packed_color_argb >> 8 & 0xFF) \/ 255.f;\n unpacked_color.b = (packed_color_argb & 0xFF) \/ 255.f;\n return unpacked_color;\n}\n}\n\n#endif \/* end of include guard: UTILS_HPP *\/\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n\n#include \n\n\/\/ signum function\ntemplate int sgn(T val) {\n return (T(0) < val) - (val < T(0));\n}\n\n\/\/\n\/\/ Pixel struct definition\nDrawingAlgoApp::Pixel::Pixel()\n : R(0), G(0), B(0)\n{}\n\nDrawingAlgoApp::Pixel::Pixel(uint R, uint G, uint B)\n : R(R), G(G), B(B)\n{}\n\nDrawingAlgoApp::Pixel::Pixel(uint hex) {\n R = (hex & 0xFF0000) >> 2*8;\n G = (hex & 0x00FF00) >> 8;\n B = hex & 0x0000FF;\n}\n\n\/\/\n\/\/ DrawingAlgoApp class definition\nDrawingAlgoApp::DrawingAlgoApp()\n : Super(800u, 600u, \"Drawing Algorithms\", sf::Style::Close),\n _num_pixels(_width*_height),\n _draw_type(DrawingType::None),\n _mouse_pos_cache(0, 0)\n{\n _pixel_data.reset(new Pixel[_width*_height]);\n\n ClearPixelData();\n}\n\nDrawingAlgoApp::~DrawingAlgoApp()\n{}\n\n\/\/\n\/\/ render loop events\nbool DrawingAlgoApp::OnInit() {\n if (!Super::OnInit())\n return false;\n\n \/\/ adjusting help text\n const auto append_text = R\"(\nC = Clear Pixelbuffer\nX = Capture Screen\nModes:\n1 = None\n2 = Line\n3 = Circle\n4 = Bezier\n)\";\n\n auto help = _help_text.getString();\n help.insert(help.getSize(), append_text);\n _help_text.setString(help);\n\n \/\/ Set the screen color for clearing\n glClearColor(0.0f, 0.0f, 0.0f, 1.0f); \/\/ rgba\n\n return true;\n}\n\nvoid DrawingAlgoApp::OnRender() {\n \/\/ render the pixel buffer \n RenderPixelArray();\n\n \/\/ render \"HUD\"\n Super::RenderHelpText();\n Super::RenderFPS();\n Super::RenderMousePos();\n}\n\n\/\/\n\/\/ drawing helper\nvoid DrawingAlgoApp::SetPixel(uint x, uint y, const Pixel &pix) {\n if (x >= _width || y >= _height)\n return;\n\n auto idx = (_height - 1 - y) * _width + x;\n idx = std::min(idx, _num_pixels-1);\n\n auto size = sizeof(pix);\n memcpy(&_pixel_data[idx], &pix, size);\n}\n\nvoid DrawingAlgoApp::ClearPixelData() {\n memset(_pixel_data.get(), 0, sizeof(Pixel)*_width*_height);\n}\n\nvoid DrawingAlgoApp::RenderPixelArray() {\n \/\/ draw pixel data\n glDrawPixels(_width, _height, GL_RGB, GL_UNSIGNED_BYTE, _pixel_data.get());\n\n \/\/ Flush drawing commands\n glFlush();\n}\n\nvoid DrawingAlgoApp::SaveAsPPM(const char* filename) {\n using std::endl;\n \n const auto magic_number = \"P6\";\n const auto bytes_per_pixel = 3;\n\n std::stringstream ss;\n ss << _width;\n const auto width = ss.str();\n\n ss = std::stringstream();\n ss << _height;\n const auto height = ss.str();\n\n ss = std::stringstream();\n ss << 255;\n const auto max_color = ss.str();\n\n std::ofstream out(filename);\n out << magic_number << endl;\n out << width << \" \" << height << endl;\n out << max_color << \"\\n\";\n\n for (auto h = 0U; h < _height; ++h) {\n for (auto w = 0U; w < _width; ++w) {\n auto& pix = _pixel_data[(_height - h - 1)*_width + w];\n out << pix.G << pix.B << pix.R;\n }\n }\n}\n\n\/\/\n\/\/ drawing algorithms\nvoid DrawingAlgoApp::DrawLineBresenham(uint x1, uint y1, uint x2, uint y2, const Pixel& pix) {\n \/\/ Startpunkt\n int x = x1, y = y1;\n\n int dx = x2 - x1;\n int dy = y2 - y1;\n\n \/\/ Schrittrichtung fr Diagonalschritt ermitteln (sgn liefert -1, 0, 1)\n int diagonal_dx = sgn(dx);\n int diagonal_dy = sgn(dy);\n\n int errSR, errLR; \/\/ Fehleranpassung in schneller Richtung (SR) und langsamer Richtung (LR)\n int parallel_dx, parallel_dy; \/\/ Schrittweite fr Parallelschritt \n int num_elements; \/\/ Anzahl zu zeichnender Pixel\n\n \/\/ Unterscheidung zwischen schneller und langsamer Richtung\n if (std::abs(dx) > std::abs(dy)) {\n \/\/ x ist schnelle Richtung, d.h. mache keinen Schritt in y-Richtung bei Parallelschritt\n parallel_dx = diagonal_dx;\n parallel_dy = 0;\n errSR = std::abs(dx)*2;\n errLR = std::abs(dy)*2;\n num_elements = std::abs(dx); \/\/ Anzahl zu zeichnender Pixel in schneller Richtung\n } else {\n \/\/ y ist schnelle Richtung, d.h. mache keinen Schritt in x-Richtung bei Parallelschritt\n parallel_dx = 0;\n parallel_dy = diagonal_dy;\n errSR = std::abs(dy)*2;\n errLR = std::abs(dx)*2;\n num_elements = std::abs(dy); \/\/ Anzahl zu zeichnender Pixel in schneller Richtung\n }\n\n \/\/ Fehlervariable initialisieren\n int error = errLR - num_elements;\n\n for (int i = 0; i < num_elements; ++i) {\n SetPixel(x, y, pix);\n \n \/\/ Fehlervariable aktualisieren (Schritt in schneller Richtung)\n error += errLR;\n if(error <= 0) {\n \/\/ Nur Schritt in schnelle Richtung (nur parallel)\n x += parallel_dx;\n y += parallel_dy;\n }\n else {\n \/\/ Schritt in langsame und schnelle Richtung (diagonal)\n x += diagonal_dx;\n y += diagonal_dy;\n\n \/\/ Fehlervariable aktualisieren (Schritt in langsamer Richtung)\n error -= errSR;\n }\n }\n}\n\nvoid DrawingAlgoApp::DrawLineMidpoint(uint x1, uint y1, uint x2, uint y2, const Pixel& pix) {\n int x = x1;\n int y = y1;\n int dx = x2 - x1;\n int dy = y2 - y1;\n int f = dy - dx\/2;\n\n \/\/ immer Schritt in schnelle Richtung, gelegentlich in langsame Richtung\n for (int i = 1; i <= dx; ++i) { \n SetPixel(x, y, pix);\n x++;\n if (f > 0) { \n y += 1;\n f -= dx; }\n f += dy;\n }\n}\n\nvoid DrawingAlgoApp::DrawCircle(uint posx, uint posy, uint radius, const Pixel& pix) {\n int x1 = 0;\n int y1 = radius;\n int f = 1 - radius;\n int dx = 3;\n int dy = 2 - 2*radius;\n\n while(x1 <= y1) {\n \/\/ drawing each possible arc\n SetPixel(posx+x1, posy-y1, pix);\n SetPixel(posx+x1, posy+y1, pix);\n SetPixel(posx-x1, posy-y1, pix);\n SetPixel(posx-x1, posy+y1, pix);\n SetPixel(posx+y1, posy-x1, pix);\n SetPixel(posx+y1, posy+x1, pix);\n SetPixel(posx-y1, posy-x1, pix);\n SetPixel(posx-y1, posy+x1, pix);\n\n x1++;\n if(f > 0) {\n y1--;\n f += dy;\n dy += 2;\n }\n f += dx;\n dx +=2;\n }\n}\n\nvoid DrawingAlgoApp::DrawBezier(const std::vector& support_points) {\n const auto t_stepsize = .01f;\n const auto size = support_points.size();\n \n \/\/ TODO: rasterize curve\n std::vector points;\n\n if (size < 2U)\n return;\n\n std::unique_ptr[]> b(new std::unique_ptr[size]);\n for (auto i = 0U; i < size; ++i)\n b[i].reset(new Point2D[size]);\n\n for (float t = .0f; t <= 1.f; t += t_stepsize) {\n \/\/ de Casteljau algorithm\n \/\/ for i = 0 .. n\n for (auto i = 0u; i < size; ++i) {\n \/\/ b(i,0) = bi\n b[i][0] = support_points[i];\n }\n\n \/\/ for j = 1 .. n\n for (auto j = 1u; j < size; ++j) {\n \/\/ for i = j .. n\n for (auto i = j; i < size; ++i) { \n \/\/ b(i,j) = (1-t) * b(i-1,j-1) + t * b(i,j-1)\n b[i][j] = (1.f - t) * b[i-1][j-1] + t * b[i][j-1];\n }\n }\n\n \/\/ p(t) = b(n,n)\n points.push_back(b[size-1][size-1]);\n }\n\n \/\/ render support points in red\n for (auto& p: support_points) {\n DrawCircle(static_cast(p.x), static_cast(p.y), 1, Pixel(0xFF0000));\n }\n\n \/\/ render curve\n auto p0 = *points.cbegin();\n for (auto it = points.cbegin() + 1; it != points.cend(); ++it) {\n auto& p1 = *it;\n\n DrawLineBresenham(static_cast(p0.x),\n static_cast(p0.y),\n static_cast(p1.x),\n static_cast(p1.y));\n\n p0 = p1;\n }\n \n}\n\n\/\/\n\/\/ event handler\nvoid DrawingAlgoApp::OnKeyReleased(sf::Keyboard::Key key, bool ctrl, bool alt, bool shift, bool system) {\n typedef sf::Keyboard::Key Key;\n \n \/\/ key 'h' and 'f' are handled by SFMLApp\n Super::OnKeyReleased(key, ctrl, alt, shift, system);\n\n switch (key) {\n case Key::C:\n ClearPixelData();\n \n \/\/ clear bezier points\n _bezier_points.clear();\n break;\n case Key::X:\n SaveAsPPM();\n break;\n case Key::Num1:\n _draw_type = DrawingType::None;\n break;\n case Key::Num2:\n _draw_type = DrawingType::Line;\n break;\n case Key::Num3:\n _draw_type = DrawingType::Circle;\n break;\n case Key::Num4:\n _draw_type = DrawingType::Bezier;\n break;\n }\n}\n\nvoid DrawingAlgoApp::OnMouseButtonPressed(sf::Mouse::Button button, int x, int y) {\n _mouse_pos_cache.x = x;\n _mouse_pos_cache.y = y;\n}\n\nvoid DrawingAlgoApp::OnMouseButtonReleased(sf::Mouse::Button button, int x, int y) {\n auto& cachex = _mouse_pos_cache.x;\n auto& cachey = _mouse_pos_cache.y;\n\n switch (_draw_type) {\n case DrawingType::Line:\n DrawLineBresenham(cachex, cachey, x, y);\n break;\n case DrawingType::Circle:\n {\n \/\/ calc distance between cache and current point\n auto dx = cachex - x;\n auto dy = cachey - y;\n auto radius = std::sqrt(dx*dx + dy*dy);\n\n DrawCircle(cachex, cachey, static_cast(radius));\n }\n break;\n case DrawingType::Bezier:\n \/\/ add point to support_points!\n _bezier_points.push_back(Point2D(cachex, cachey));\n\n \/\/ clear pixeldata\n ClearPixelData();\n\n \/\/ render bezier\n DrawBezier(_bezier_points);\n break;\n }\n}converted encoding to UTF8 without BOM#include \n\n#include \n#include \n#include \n\n#include \n\n\/\/ signum function\ntemplate int sgn(T val) {\n return (T(0) < val) - (val < T(0));\n}\n\n\/\/\n\/\/ Pixel struct definition\nDrawingAlgoApp::Pixel::Pixel()\n : R(0), G(0), B(0)\n{}\n\nDrawingAlgoApp::Pixel::Pixel(uint R, uint G, uint B)\n : R(R), G(G), B(B)\n{}\n\nDrawingAlgoApp::Pixel::Pixel(uint hex) {\n R = (hex & 0xFF0000) >> 2*8;\n G = (hex & 0x00FF00) >> 8;\n B = hex & 0x0000FF;\n}\n\n\/\/\n\/\/ DrawingAlgoApp class definition\nDrawingAlgoApp::DrawingAlgoApp()\n : Super(800u, 600u, \"Drawing Algorithms\", sf::Style::Close),\n _num_pixels(_width*_height),\n _draw_type(DrawingType::None),\n _mouse_pos_cache(0, 0)\n{\n _pixel_data.reset(new Pixel[_width*_height]);\n\n ClearPixelData();\n}\n\nDrawingAlgoApp::~DrawingAlgoApp()\n{}\n\n\/\/\n\/\/ render loop events\nbool DrawingAlgoApp::OnInit() {\n if (!Super::OnInit())\n return false;\n\n \/\/ adjusting help text\n const auto append_text = R\"(\nC = Clear Pixelbuffer\nX = Capture Screen\nModes:\n1 = None\n2 = Line\n3 = Circle\n4 = Bezier\n)\";\n\n auto help = _help_text.getString();\n help.insert(help.getSize(), append_text);\n _help_text.setString(help);\n\n \/\/ Set the screen color for clearing\n glClearColor(0.0f, 0.0f, 0.0f, 1.0f); \/\/ rgba\n\n return true;\n}\n\nvoid DrawingAlgoApp::OnRender() {\n \/\/ render the pixel buffer \n RenderPixelArray();\n\n \/\/ render \"HUD\"\n Super::RenderHelpText();\n Super::RenderFPS();\n Super::RenderMousePos();\n}\n\n\/\/\n\/\/ drawing helper\nvoid DrawingAlgoApp::SetPixel(uint x, uint y, const Pixel &pix) {\n if (x >= _width || y >= _height)\n return;\n\n auto idx = (_height - 1 - y) * _width + x;\n idx = std::min(idx, _num_pixels-1);\n\n auto size = sizeof(pix);\n memcpy(&_pixel_data[idx], &pix, size);\n}\n\nvoid DrawingAlgoApp::ClearPixelData() {\n memset(_pixel_data.get(), 0, sizeof(Pixel)*_width*_height);\n}\n\nvoid DrawingAlgoApp::RenderPixelArray() {\n \/\/ draw pixel data\n glDrawPixels(_width, _height, GL_RGB, GL_UNSIGNED_BYTE, _pixel_data.get());\n\n \/\/ Flush drawing commands\n glFlush();\n}\n\nvoid DrawingAlgoApp::SaveAsPPM(const char* filename) {\n using std::endl;\n \n const auto magic_number = \"P6\";\n const auto bytes_per_pixel = 3;\n\n std::stringstream ss;\n ss << _width;\n const auto width = ss.str();\n\n ss = std::stringstream();\n ss << _height;\n const auto height = ss.str();\n\n ss = std::stringstream();\n ss << 255;\n const auto max_color = ss.str();\n\n std::ofstream out(filename);\n out << magic_number << endl;\n out << width << \" \" << height << endl;\n out << max_color << \"\\n\";\n\n for (auto h = 0U; h < _height; ++h) {\n for (auto w = 0U; w < _width; ++w) {\n auto& pix = _pixel_data[(_height - h - 1)*_width + w];\n out << pix.G << pix.B << pix.R;\n }\n }\n}\n\n\/\/\n\/\/ drawing algorithms\nvoid DrawingAlgoApp::DrawLineBresenham(uint x1, uint y1, uint x2, uint y2, const Pixel& pix) {\n \/\/ Startpunkt\n int x = x1, y = y1;\n\n int dx = x2 - x1;\n int dy = y2 - y1;\n\n \/\/ Schrittrichtung für Diagonalschritt ermitteln (sgn liefert -1, 0, 1)\n int diagonal_dx = sgn(dx);\n int diagonal_dy = sgn(dy);\n\n int errSR, errLR; \/\/ Fehleranpassung in schneller Richtung (SR) und langsamer Richtung (LR)\n int parallel_dx, parallel_dy; \/\/ Schrittweite für Parallelschritt \n int num_elements; \/\/ Anzahl zu zeichnender Pixel\n\n \/\/ Unterscheidung zwischen schneller und langsamer Richtung\n if (std::abs(dx) > std::abs(dy)) {\n \/\/ x ist schnelle Richtung, d.h. mache keinen Schritt in y-Richtung bei Parallelschritt\n parallel_dx = diagonal_dx;\n parallel_dy = 0;\n errSR = std::abs(dx)*2;\n errLR = std::abs(dy)*2;\n num_elements = std::abs(dx); \/\/ Anzahl zu zeichnender Pixel in schneller Richtung\n } else {\n \/\/ y ist schnelle Richtung, d.h. mache keinen Schritt in x-Richtung bei Parallelschritt\n parallel_dx = 0;\n parallel_dy = diagonal_dy;\n errSR = std::abs(dy)*2;\n errLR = std::abs(dx)*2;\n num_elements = std::abs(dy); \/\/ Anzahl zu zeichnender Pixel in schneller Richtung\n }\n\n \/\/ Fehlervariable initialisieren\n int error = errLR - num_elements;\n\n for (int i = 0; i < num_elements; ++i) {\n SetPixel(x, y, pix);\n \n \/\/ Fehlervariable aktualisieren (Schritt in schneller Richtung)\n error += errLR;\n if(error <= 0) {\n \/\/ Nur Schritt in schnelle Richtung (nur parallel)\n x += parallel_dx;\n y += parallel_dy;\n }\n else {\n \/\/ Schritt in langsame und schnelle Richtung (diagonal)\n x += diagonal_dx;\n y += diagonal_dy;\n\n \/\/ Fehlervariable aktualisieren (Schritt in langsamer Richtung)\n error -= errSR;\n }\n }\n}\n\nvoid DrawingAlgoApp::DrawLineMidpoint(uint x1, uint y1, uint x2, uint y2, const Pixel& pix) {\n int x = x1;\n int y = y1;\n int dx = x2 - x1;\n int dy = y2 - y1;\n int f = dy - dx\/2;\n\n \/\/ immer Schritt in schnelle Richtung, gelegentlich in langsame Richtung\n for (int i = 1; i <= dx; ++i) { \n SetPixel(x, y, pix);\n x++;\n if (f > 0) { \n y += 1;\n f -= dx; }\n f += dy;\n }\n}\n\nvoid DrawingAlgoApp::DrawCircle(uint posx, uint posy, uint radius, const Pixel& pix) {\n int x1 = 0;\n int y1 = radius;\n int f = 1 - radius;\n int dx = 3;\n int dy = 2 - 2*radius;\n\n while(x1 <= y1) {\n \/\/ drawing each possible arc\n SetPixel(posx+x1, posy-y1, pix);\n SetPixel(posx+x1, posy+y1, pix);\n SetPixel(posx-x1, posy-y1, pix);\n SetPixel(posx-x1, posy+y1, pix);\n SetPixel(posx+y1, posy-x1, pix);\n SetPixel(posx+y1, posy+x1, pix);\n SetPixel(posx-y1, posy-x1, pix);\n SetPixel(posx-y1, posy+x1, pix);\n\n x1++;\n if(f > 0) {\n y1--;\n f += dy;\n dy += 2;\n }\n f += dx;\n dx +=2;\n }\n}\n\nvoid DrawingAlgoApp::DrawBezier(const std::vector& support_points) {\n const auto t_stepsize = .01f;\n const auto size = support_points.size();\n \n \/\/ TODO: rasterize curve\n std::vector points;\n\n if (size < 2U)\n return;\n\n std::unique_ptr[]> b(new std::unique_ptr[size]);\n for (auto i = 0U; i < size; ++i)\n b[i].reset(new Point2D[size]);\n\n for (float t = .0f; t <= 1.f; t += t_stepsize) {\n \/\/ de Casteljau algorithm\n \/\/ for i = 0 .. n\n for (auto i = 0u; i < size; ++i) {\n \/\/ b(i,0) = bi\n b[i][0] = support_points[i];\n }\n\n \/\/ for j = 1 .. n\n for (auto j = 1u; j < size; ++j) {\n \/\/ for i = j .. n\n for (auto i = j; i < size; ++i) { \n \/\/ b(i,j) = (1-t) * b(i-1,j-1) + t * b(i,j-1)\n b[i][j] = (1.f - t) * b[i-1][j-1] + t * b[i][j-1];\n }\n }\n\n \/\/ p(t) = b(n,n)\n points.push_back(b[size-1][size-1]);\n }\n\n \/\/ render support points in red\n for (auto& p: support_points) {\n DrawCircle(static_cast(p.x), static_cast(p.y), 1, Pixel(0xFF0000));\n }\n\n \/\/ render curve\n auto p0 = *points.cbegin();\n for (auto it = points.cbegin() + 1; it != points.cend(); ++it) {\n auto& p1 = *it;\n\n DrawLineBresenham(static_cast(p0.x),\n static_cast(p0.y),\n static_cast(p1.x),\n static_cast(p1.y));\n\n p0 = p1;\n }\n \n}\n\n\/\/\n\/\/ event handler\nvoid DrawingAlgoApp::OnKeyReleased(sf::Keyboard::Key key, bool ctrl, bool alt, bool shift, bool system) {\n typedef sf::Keyboard::Key Key;\n \n \/\/ key 'h' and 'f' are handled by SFMLApp\n Super::OnKeyReleased(key, ctrl, alt, shift, system);\n\n switch (key) {\n case Key::C:\n ClearPixelData();\n \n \/\/ clear bezier points\n _bezier_points.clear();\n break;\n case Key::X:\n SaveAsPPM();\n break;\n case Key::Num1:\n _draw_type = DrawingType::None;\n break;\n case Key::Num2:\n _draw_type = DrawingType::Line;\n break;\n case Key::Num3:\n _draw_type = DrawingType::Circle;\n break;\n case Key::Num4:\n _draw_type = DrawingType::Bezier;\n break;\n }\n}\n\nvoid DrawingAlgoApp::OnMouseButtonPressed(sf::Mouse::Button button, int x, int y) {\n _mouse_pos_cache.x = x;\n _mouse_pos_cache.y = y;\n}\n\nvoid DrawingAlgoApp::OnMouseButtonReleased(sf::Mouse::Button button, int x, int y) {\n auto& cachex = _mouse_pos_cache.x;\n auto& cachey = _mouse_pos_cache.y;\n\n switch (_draw_type) {\n case DrawingType::Line:\n DrawLineBresenham(cachex, cachey, x, y);\n break;\n case DrawingType::Circle:\n {\n \/\/ calc distance between cache and current point\n auto dx = cachex - x;\n auto dy = cachey - y;\n auto radius = std::sqrt(dx*dx + dy*dy);\n\n DrawCircle(cachex, cachey, static_cast(radius));\n }\n break;\n case DrawingType::Bezier:\n \/\/ add point to support_points!\n _bezier_points.push_back(Point2D(cachex, cachey));\n\n \/\/ clear pixeldata\n ClearPixelData();\n\n \/\/ render bezier\n DrawBezier(_bezier_points);\n break;\n }\n}<|endoftext|>"} {"text":"\/*============================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center (DKFZ)\nAll rights reserved.\n\nUse of this source code is governed by a 3-clause BSD license that can be\nfound in the LICENSE file.\n\n============================================================================*\/\n\n#include \"vtkActor.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkSphereSource.h\"\n#include \"vtkUnsignedCharArray.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \nint mitkVtkPropRendererTest(int argc, char *argv[])\n{\n \/\/ independently read header of pic file\n mitkIpPicDescriptor *picheader = nullptr;\n if (argc >= 1)\n {\n if (itksys::SystemTools::LowerCase(itksys::SystemTools::GetFilenameExtension(argv[1])).find(\".pic\") !=\n std::string::npos)\n picheader = mitkIpPicGetHeader(argv[1], nullptr);\n }\n if (picheader == nullptr)\n {\n std::cout << \"file not found\/not a pic-file - test not applied [PASSED]\" << std::endl;\n std::cout << \"[TEST DONE]\" << std::endl;\n return EXIT_SUCCESS;\n }\n\n static long int sum_orig_Pic3D_pic_gz = 14685408;\n\n mitkIpPicGetTags(argv[1], picheader);\n\n \/\/ Read pic-Image from file\n std::cout << \"Reading image: \";\n mitk::PicFileReader::Pointer reader = mitk::PicFileReader::New();\n reader->SetFileName(argv[1]);\n reader->Update();\n std::cout << \"[PASSED]\" << std::endl;\n\n mitk::Image::Pointer image = reader->GetOutput();\n\n std::cout << \"Creating node: \";\n mitk::DataNode::Pointer node = mitk::DataNode::New();\n node->SetData(image);\n std::cout << \"[PASSED]\" << std::endl;\n\n std::cout << \"Creating DataStorage: \";\n mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New();\n std::cout << \"[PASSED]\" << std::endl;\n\n std::cout << \"Adding node via DataStorage: \";\n ds->Add(node);\n std::cout << \"[PASSED]\" << std::endl;\n\n std::cout << \"Adding level-window property: \";\n mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New();\n mitk::LevelWindow levelwindow;\n levelwindow.SetAuto(image);\n levWinProp->SetLevelWindow(levelwindow);\n node->GetPropertyList()->SetProperty(\"levelwindow\", levWinProp);\n std::cout << \"[PASSED]\" << std::endl;\n\n std::cout << \"Creating a vtk sphere: \";\n vtkSphereSource *sphere = vtkSphereSource::New();\n sphere->SetRadius(1.0);\n sphere->SetThetaResolution(18);\n sphere->SetPhiResolution(18);\n\n vtkPolyDataMapper *map = vtkPolyDataMapper::New();\n map->SetInput(sphere->GetOutput());\n sphere->Delete();\n\n vtkActor *aSphere = vtkActor::New();\n aSphere->SetMapper(map);\n map->Delete();\n aSphere->GetProperty()->SetColor(0, 0, 1); \/\/ sphere color blue\n std::cout << \"[PASSED]\" << std::endl;\n\n std::cout << \"Creating a renderer for the sphere: \";\n vtkRenderer *sphereRenderer = vtkRenderer::New();\n sphereRenderer->AddActor(aSphere);\n aSphere->Delete();\n \/\/ sphereRenderer->SetBackground(1,1,1); \/\/ Background color white\n std::cout << \"[PASSED]\" << std::endl;\n\n std::cout << \"Creating vtkRenderWindow and VtkPropRenderer: \";\n vtkRenderWindow *renderWindow = vtkRenderWindow::New();\n mitk::VtkPropRenderer::Pointer propRenderer = mitk::VtkPropRenderer::New(\"the renderer\", renderWindow);\n \/\/ propRenderer->SetMapperID(2);\n std::cout << \"[PASSED]\" << std::endl;\n\n \/\/ renderWindow->AddRenderer(sphereRenderer);\n \/\/ renderWindow->SetErase(0);\n\n std::cout << \"BaseRenderer::SetData(iterator): \";\n propRenderer->SetDataStorage(ds);\n std::cout << \"[PASSED]\" << std::endl;\n\n std::cout << \"Creating vtkMitkRenderProp and connecting it to the VtkPropRenderer: \";\n vtkMitkRenderProp *renderProp = vtkMitkRenderProp::New();\n renderProp->SetPropRenderer(propRenderer);\n propRenderer->GetVtkRenderer()->AddViewProp(renderProp);\n std::cout << \"[PASSED]\" << std::endl;\n\n std::cout << \"Inserting the sphere into the foreground of the VtkLayerController: \";\n mitk::VtkLayerController::GetInstance(renderWindow)->InsertForegroundRenderer(sphereRenderer, true);\n std::cout << \"[PASSED]\" << std::endl;\n\n \/\/ mouse interaction for debugging\n \/\/ vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();\n \/\/ iren->SetRenderWindow(renderWindow);\n\n std::cout << \"Setting and getting size of renderWindow: \";\n renderWindow->SetSize(400, 400);\n int *size = renderWindow->GetSize();\n std::cout << \"[PASSED]\" << std::endl;\n\n std::cout << \"Do the rendering: \";\n renderWindow->Render();\n std::cout << \"[PASSED]\" << std::endl;\n\n \/\/ iren->Start();\n\n std::cout << \"Testing to pick a world position: \";\n mitk::Point2D p;\n mitk::Point3D p_mm;\n p[0] = 10;\n p[1] = 10;\n propRenderer->PickWorldPoint(p, p_mm);\n std::cout << \"returned world position: \" << p_mm << \"\\n\";\n\n std::cout << \"Creating vtkUnsignedCharArray: \";\n vtkUnsignedCharArray *vtkImage = vtkUnsignedCharArray::New();\n std::cout << \"[PASSED]\" << std::endl;\n\n cout << \"Reading image from renderWindow\" << std::endl;\n renderWindow->GetRGBACharPixelData(0, 0, size[0] - 1, size[1] - 1, 0, vtkImage);\n cout << \"Read \" << size[0] * size[1] << \" data points\\n\";\n\n cout << \"Computing sum of all RGBA values..\\n\";\n long int sum_now = 0;\n for (int i = 0; i < size[0] * size[1]; i++)\n sum_now += vtkImage->GetValue(i);\n std::cout << \"Sum of all RGBA values: \" << sum_now << \"\\n\";\n std::cout << \"Sum should be: \" << sum_orig_Pic3D_pic_gz << \"\\n\";\n\n \/\/ std::string Pic3d_pic_gz_str(\"Pic3D.pic.gz\");\n \/\/ std::cout << \"pic3d \" << Pic3d_pic_gz_str << \"\\n\";\n \/\/ std::cout << \"argv \" << argv_str << \"\\n\";\n \/\/ std::cout << \"find \" << (int) argv_str.find(\"Pic3D.pic.gz\") << \"\\n\";\n \/\/ std::cout << \"size \" << argv_str.size() << \"\\n\";\n\n \/\/ if(argv_str.size() - ((int) argv_str.find(\"Pic3D.pic.gz\")) == 12)\n \/\/{\n \/\/ std::cout << \"Input image is Pic3D.pic.gz\\n\";\n \/\/ std::cout << \"Sum should be: \" << sum_orig_Pic3D_pic_gz << \"\\n\";\n \/\/ if(sum_orig_Pic3D_pic_gz!=sum_now)\n \/\/ {\n \/\/ std::cout<<\"[FAILED]\"<GetVtkRenderer()->RemoveViewProp(renderProp);\n renderProp->Delete();\n propRenderer = nullptr;\n sphereRenderer->Delete();\n\n renderWindow->Delete();\n\n vtkImage->Delete();\n ds = nullptr;\n\n std::cout << \"[TEST DONE]\" << std::endl;\n return EXIT_SUCCESS;\n}\nRemove dangling test cpp file<|endoftext|>"} {"text":"void Pi0SpectrumLHC11h(const char* dataset=\"collection.xml\",\n\t\t bool recompile = false\n)\n{\n TStopwatch timer;\n timer.Start();\n\n\n TStringToken libs(\"Core,Tree,Geom,VMC,Physics,Minuit,Gui,XMLParser,Minuit2,Proof,STEERBase,ESD,AOD,OADB,ANALYSIS,ANALYSISalice,CDB,RAWDatabase,STEER,CORRFW,PHOSUtils,PHOSbase,PHOSpi0Calib,PHOSrec,PHOSshuttle,PHOSsim,PWGGAPHOSTasks\", \",\");\n while( libs.NextToken() )\n gSystem->Load( Form(\"lib%s\", libs.Data()) );\n\n gSystem->Load(\"libTree.so\");\n gSystem->Load(\"libGeom.so\");\n gSystem->Load(\"libVMC.so\");\n gSystem->Load(\"libPhysics.so\");\n \n \/\/load analysis framework\n gSystem->Load(\"libANALYSIS\");\n gSystem->Load(\"libANALYSISalice\"); \/\/AliAnalysisTaskSE\n \n gSystem->AddIncludePath(\"-I$ALICE_ROOT\/include -I$ALICE_ROOT\/PHOS\");\n\n \/\/ A task can be compiled dynamically with AClic\n if( recompile ) {\n gROOT->LoadMacro(\"AliCaloPhoton.cxx+g\");\n gROOT->LoadMacro(\"AliAnalysisTaskPi0Flow.cxx+g\");\n }\n else {\n gSystem->Load(\"libPWGGAPHOSTasks.so\");\n }\n \n \/\/ Connect to alien\n TString token = gSystem->Getenv(\"GRID_TOKEN\") ;\n if (1) \/\/ token == \"OK\" ) \n TGrid::Connect(\"alien:\/\/\");\n else \n AliInfo(\"You are not connected to the GRID\") ; \n\n cout << \"Pi0Analysis: processing collection \" << dataset << endl;\n\n \/\/ Create the chain\n TChain* chain = new TChain(\"aodTree\");\n\n TGridCollection * collection = dynamic_cast(TAlienCollection::Open(dataset));\n \n TAlienResult* result = collection->GetGridResult(\"\",0 ,0);\n TList* rawFileList = result->GetFileInfoList();\n \n for (Int_t counter=0 ; counter < rawFileList->GetEntries() ; counter++) {\n TFileInfo * fi = static_cast(rawFileList->At(counter)) ; \n const char * rawFile = fi->GetCurrentUrl()->GetUrl() ; \n printf(\"Processing %s\\n\", rawFile) ;\n chain->Add(rawFile);\n printf(\"Chain: %d entries.\\n\",chain->GetEntriesFast()); \n }\n\n \/\/ Make the analysis manager\n AliAnalysisManager *mgr = new AliAnalysisManager(\"Pi0Spectrum\");\n mgr->SetCommonFileName(\"histos.root\");\n \n \/\/ AOD input handler\n AliAODInputHandler* aodH = new AliAODInputHandler();\n mgr->SetInputEventHandler(aodH);\n\n \n \/\/ Debug level\n mgr->SetDebugLevel(999999);\n\n gROOT->LoadMacro(\"$ALICE_ROOT\/ANALYSIS\/macros\/AddTaskEventplane.C\");\n AliEPSelectionTask *taskEP = AddTaskEventplane() ; \n\n gROOT->LoadMacro(\"$ALICE_ROOT\/ANALYSIS\/macros\/AddTaskVZEROEPSelection.C\");\n AliVZEROEPSelectionTask *selTask = AddTaskVZEROEPSelection(); \n\n \/\/ Add my task\n AliAnalysisTaskPi0Flow* task;\n if ( recompile ) {\n task = new AliAnalysisTaskPi0Flow(\"AliAnalysisTaskPi0Flow\");\n \/\/task->SetPeriod(AliAnalysisTaskPi0Flow::kLHC11h);\n mgr->AddTask(task);\n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 1, mgr->CreateContainer(\"outCont1\", TList::Class(),AliAnalysisManager::kOutputContainer,\"output.root\"));\n } else {\n gROOT->LoadMacro(\"$ALICE_ROOT\/PWGGA\/PHOSTasks\/PHOS_PbPb\/AddTaskPHOSPi0Flow.C\");\n task = AddTaskPHOSPi0Flow();\n }\n\n\/*\n TFile *fBadMap = TFile::Open(\"alien:\/\/\/alice\/cern.ch\/user\/p\/prsnko\/BadMaps\/BadMap_LHC10h_period1.root\");\n \/\/ TFile *fBadMap = TFile::Open(\"BadMap_LHC10h_period1.root\");\n if(fBadMap->IsOpen()){\n printf(\"\\n\\n...Adding PHOS bad channel map \\n\") ;\n gROOT->cd();\n char key[55] ;\n for(Int_t mod=1;mod<4; mod++){\n sprintf(key,\"PHOS_BadMap_mod%d\",mod) ;\n TH2I * h = (TH2I*)fBadMap->Get(key) ;\n if(h)\n task1->SetPHOSBadMap(mod,h) ;\n }\n fBadMap->Close() ;\n }\n*\/\n\n\n \n \/\/ \/\/ Create containers for input\/output\n \/\/ AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); \n \/\/ AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(\"pi0SpecOut1\",TList::Class(),AliAnalysisManager::kOutputContainer,\"histos.root\");\n \n \/\/ \/\/ Connect input\/output\n \/\/ mgr->ConnectInput(task1 , 0, cinput);\n \/\/ mgr->ConnectOutput(task1, 1, coutput1);\n \n if (mgr->InitAnalysis()) {\n mgr->PrintStatus();\n mgr->StartAnalysis(\"local\", chain);\n }\n\n timer.Stop();\n timer.Print();\n}\nAdded AliPHOSEPFlattener recompilation to Pi0SpectrumLHC11h.C,void Pi0SpectrumLHC11h(const char* dataset=\"collection.xml\",\n\t\t bool recompile = true\n)\n{\n TStopwatch timer;\n timer.Start();\n\n\n TStringToken libs(\"Core,Tree,Geom,VMC,Physics,Minuit,Gui,XMLParser,Minuit2,Proof,STEERBase,ESD,AOD,OADB,ANALYSIS,ANALYSISalice,CDB,RAWDatabase,STEER,CORRFW,PHOSUtils,PHOSbase,PHOSpi0Calib,PHOSrec,PHOSshuttle,PHOSsim,PWGGAPHOSTasks\", \",\");\n while( libs.NextToken() )\n gSystem->Load( Form(\"lib%s\", libs.Data()) );\n\n gSystem->Load(\"libTree.so\");\n gSystem->Load(\"libGeom.so\");\n gSystem->Load(\"libVMC.so\");\n gSystem->Load(\"libPhysics.so\");\n \n \/\/load analysis framework\n gSystem->Load(\"libANALYSIS\");\n gSystem->Load(\"libANALYSISalice\"); \/\/AliAnalysisTaskSE\n \n gSystem->AddIncludePath(\"-I$ALICE_ROOT\/include -I$ALICE_ROOT\/PHOS\");\n\n \/\/ A task can be compiled dynamically with AClic\n if( recompile ) {\n gROOT->LoadMacro(\"AliCaloPhoton.cxx+g\");\n gROOT->LoadMacro(\"AliAnalysisTaskPi0Flow.cxx+g\");\n gROOT->LoadMacro(\"AliPHOSEPFlattener.cxx+g\");\n }\n else {\n gSystem->Load(\"libPWGGAPHOSTasks.so\");\n }\n \n \/\/ Connect to alien\n TString token = gSystem->Getenv(\"GRID_TOKEN\") ;\n if (1) \/\/ token == \"OK\" ) \n TGrid::Connect(\"alien:\/\/\");\n else \n AliInfo(\"You are not connected to the GRID\") ; \n\n cout << \"Pi0Analysis: processing collection \" << dataset << endl;\n\n \/\/ Create the chain\n TChain* chain = new TChain(\"aodTree\");\n\n TGridCollection * collection = dynamic_cast(TAlienCollection::Open(dataset));\n \n TAlienResult* result = collection->GetGridResult(\"\",0 ,0);\n TList* rawFileList = result->GetFileInfoList();\n \n for (Int_t counter=0 ; counter < rawFileList->GetEntries() ; counter++) {\n TFileInfo * fi = static_cast(rawFileList->At(counter)) ; \n const char * rawFile = fi->GetCurrentUrl()->GetUrl() ; \n printf(\"Processing %s\\n\", rawFile) ;\n chain->Add(rawFile);\n printf(\"Chain: %d entries.\\n\",chain->GetEntriesFast()); \n }\n\n \/\/ Make the analysis manager\n AliAnalysisManager *mgr = new AliAnalysisManager(\"Pi0Spectrum\");\n mgr->SetCommonFileName(\"histos.root\");\n \n \/\/ AOD input handler\n AliAODInputHandler* aodH = new AliAODInputHandler();\n mgr->SetInputEventHandler(aodH);\n\n \n \/\/ Debug level\n mgr->SetDebugLevel(999999);\n\n gROOT->LoadMacro(\"$ALICE_ROOT\/ANALYSIS\/macros\/AddTaskEventplane.C\");\n AliEPSelectionTask *taskEP = AddTaskEventplane() ; \n\n gROOT->LoadMacro(\"$ALICE_ROOT\/ANALYSIS\/macros\/AddTaskVZEROEPSelection.C\");\n AliVZEROEPSelectionTask *selTask = AddTaskVZEROEPSelection(); \n\n \/\/ Add my task\n AliAnalysisTaskPi0Flow* task;\n if ( recompile ) {\n task = new AliAnalysisTaskPi0Flow(\"AliAnalysisTaskPi0Flow\");\n \/\/task->SetPeriod(AliAnalysisTaskPi0Flow::kLHC11h);\n mgr->AddTask(task);\n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 1, mgr->CreateContainer(\"outCont1\", TList::Class(),AliAnalysisManager::kOutputContainer,\"output.root\"));\n } else {\n gROOT->LoadMacro(\"$ALICE_ROOT\/PWGGA\/PHOSTasks\/PHOS_PbPb\/AddTaskPHOSPi0Flow.C\");\n task = AddTaskPHOSPi0Flow();\n }\n\n\/*\n TFile *fBadMap = TFile::Open(\"alien:\/\/\/alice\/cern.ch\/user\/p\/prsnko\/BadMaps\/BadMap_LHC10h_period1.root\");\n \/\/ TFile *fBadMap = TFile::Open(\"BadMap_LHC10h_period1.root\");\n if(fBadMap->IsOpen()){\n printf(\"\\n\\n...Adding PHOS bad channel map \\n\") ;\n gROOT->cd();\n char key[55] ;\n for(Int_t mod=1;mod<4; mod++){\n sprintf(key,\"PHOS_BadMap_mod%d\",mod) ;\n TH2I * h = (TH2I*)fBadMap->Get(key) ;\n if(h)\n task1->SetPHOSBadMap(mod,h) ;\n }\n fBadMap->Close() ;\n }\n*\/\n\n\n \n \/\/ \/\/ Create containers for input\/output\n \/\/ AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); \n \/\/ AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(\"pi0SpecOut1\",TList::Class(),AliAnalysisManager::kOutputContainer,\"histos.root\");\n \n \/\/ \/\/ Connect input\/output\n \/\/ mgr->ConnectInput(task1 , 0, cinput);\n \/\/ mgr->ConnectOutput(task1, 1, coutput1);\n \n if (mgr->InitAnalysis()) {\n mgr->PrintStatus();\n mgr->StartAnalysis(\"local\", chain);\n }\n\n timer.Stop();\n timer.Print();\n}\n<|endoftext|>"} {"text":"ClientAuthOperation: Stop warning on invalid auto requestAuthCode call<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#ifndef REMOVE_VALUES\n#ifndef CHECK_VALUES\n#error \"define one of REMOVE_VALUES or CHECK_VALUES\"\n#endif\n#endif\n\n#ifdef REMOVE_VALUES\n#ifdef CHECK_VALUES\n#error \"define either REMOVE_VALUES or CHECK_VALUES\"\n#endif\n#endif\n\nint main()\n{\n\tstd::vector myValues;\n for ( long int i=0L; i<100000000L; ++i )\n\t\tmyValues.push_back(i%3);\n\t\n\tint iOriginalSize = myValues.size();\n#ifdef REMOVE_VALUES\n\tmyValues.erase(std::remove_if(myValues.begin(),myValues.end(),[](int i) { return i == 2; }),myValues.end());\n#endif\n\tint sum = 0;\n for ( unsigned int i=0; iCheck vs Remove - not so not so clear#include \n#include \n#include \n\n#ifndef REMOVE_VALUES\n#ifndef CHECK_VALUES\n#error \"define one of REMOVE_VALUES or CHECK_VALUES\"\n#endif\n#endif\n\n#ifdef REMOVE_VALUES\n#ifdef CHECK_VALUES\n#error \"define either REMOVE_VALUES or CHECK_VALUES\"\n#endif\n#endif\n\nint main()\n{\n\tstd::vector myValues;\n\tfor ( long int i=0L; i<10000000L; ++i )\n\t\tmyValues.push_back(i%3);\n\n\tint iOriginalSize = myValues.size();\n#ifdef REMOVE_VALUES\n\tmyValues.erase(std::remove_if(myValues.begin(),myValues.end(),[](int i) { return i == 2; }),myValues.end());\n#endif\n\n\tconst int iterations = 100;\n\tfor ( int iteration=0; iteration < iterations; ++iteration )\n\t{\n\t\tint sum = 0;\n\t\tfor ( unsigned int i=0; i"} {"text":"#include \n#include \n#include \n#include \"nfa.h\"\n#include \"utils.cpp\"\n\nstring error_message = \"NFA Creation Error : \";\n\nvoid verify_state_set(const set& states, const set& state_set) {\n\n set::const_iterator it;\n for (it = state_set.begin(); it != state_set.end(); ++it) {\n if(!states.count(*it))\n throw error_message + \"State '\" + *it + \"' does not belong to Q!\";\n }\n}\n\nvoid verify_states(set states, set initial, set final) {\n if(initial.size() != 1)\n throw error_message + \"There should be one and only one initial state!\";\n\n if(final.size() < 1 || final.size() > states.size() )\n throw error_message + \"Final states should be between 1 and total number of states!\";\n\n \/\/ Verify if all the states in initial and final belong to state vector\n\n if (!states.count(*initial.begin()))\n throw error_message + \"Initial state '\" + *initial.begin() + \"' does not belong to Q!\";\n\n try {\n verify_state_set(states, final);\n } catch (const string& message) {\n cout << \"Invalid Final State!\" << endl;\n throw;\n }\n}\n\nvoid nfa::set_states(const set &states, const set &initial, const set &final) {\n verify_states(states, initial, final);\n\n this->states = states;\n this->final = final;\n this->initial = *initial.begin();\n}\n\nvoid nfa::set_alphabet(const set &alphabet) {\n if(alphabet.count(\"e\"))\n throw \"NFA Parse Error : Language alphabet 'e' clashes with keyword for epsilon!\";\n\n this->alphabet = alphabet;\n}\n\nvoid nfa::add_transition(const string& current_state, const string& alphabet, const set& result) {\n verify_state_set(states, result);\n transitions[make_pair(current_state, alphabet)] = result;\n}\n\nconst set nfa::get_states(const string& state, const string& alphabet) {\n pair key = make_pair(state, alphabet);\n if(!transitions.count(key))\n throw \"NFA Error : Invalid Transition!\";\n\n return transitions[key];\n}\n\nconst set nfa::get_states(const set &states, const string &alphabet) {\n set compound_states;\n\n set::const_iterator it;\n for(it = states.begin(); it != states.end(); ++it) {\n set out_state = get_states(*it, alphabet);\n compound_states.insert(out_state.begin(), out_state.end());\n }\n\n return compound_states;\n}\n\nconst set nfa::get_epsilon_closure(const string &state) {\n set key;\n key.insert(state);\n\n if(epsilon_closures.count(key))\n return epsilon_closures[key];\n\n set epsilon_states;\n\n queue remaining;\n remaining.push(state);\n\n while (!remaining.empty()) {\n string current = remaining.front();\n\n epsilon_states.insert(current);\n\n set epsilon_moves = get_states(current, \"e\");\n set::const_iterator it;\n for(it = epsilon_moves.begin(); it != epsilon_moves.end(); ++it) {\n if(!epsilon_states.count(*it))\n remaining.push(*it);\n }\n\n remaining.pop();\n }\n\n epsilon_closures[key] = epsilon_states;\n\n return epsilon_states;\n}\n\nconst set nfa::get_epsilon_closure(const set &states) {\n if (epsilon_closures.count(states))\n return epsilon_closures[states];\n\n set epsilon_states;\n\n set::const_iterator it;\n for(it = states.begin(); it != states.end(); ++it) {\n set current_states = get_epsilon_closure(*it);\n epsilon_states.insert(current_states.begin(), current_states.end());\n }\n\n epsilon_closures[states] = epsilon_states;\n\n return epsilon_states;\n}\n\nbool nfa::is_final(const set &states) {\n set::const_iterator it;\n\n for(it = states.begin(); it != states.end(); ++it) {\n if(contains(final, *it))\n return true;\n }\n\n return false;\n}\n\nstring nfa::format_output(ostringstream& oss, vector< set >& dfa_states) {\n cout << \"\\nInitial State : \" << endl;\n string initial_state = to_string(dfa_states[0], ',');\n cout << \"{ \" << initial_state << \" }\" << endl;\n\n oss << (string) \"Q0 : { \" << initial_state << \" }\" << endl;\n oss << \"F : {\";\n\n cout << \"Final States : \" << endl;\n string prefix = \"Q : {\";\n const char* delim = \" \";\n for (int i = 0; i < dfa_states.size(); ++i) {\n set current = dfa_states[i];\n\n prefix+= \" { \" + to_string(current, ',') + \" },\";\n\n if(is_final(current)) {\n string final_state = to_string(current, ',');\n cout << \"{ \" << final_state << \" }\" << endl;\n\n oss << delim << \"{ \" << final_state << \" }\";\n delim = \", \";\n }\n }\n oss << \" }\" << endl;\n\n \/\/ Add states and languages to output\n unsigned long index = prefix.length()-1;\n if(prefix[index] == ',')\n prefix.erase(prefix.begin() + index);\n prefix += \" }\\n\";\n prefix += \"E : { \" + to_string(alphabet, ',') + \" }\\n\";\n\n return prefix + \"\\n\" + oss.str();\n}\n\nstring nfa::to_dfa() {\n ostringstream oss;\n cout << \"DFA Conversion : \\n\" << endl;\n set initial = get_epsilon_closure(this->initial);\n\n queue< set > remaining;\n remaining.push(initial);\n\n vector< set > dfa_states;\n\n set::const_iterator it;\n\n while(!remaining.empty()) {\n set current = remaining.front();\n remaining.pop();\n\n if(contains(dfa_states, current))\n continue;\n\n string current_set = to_string(current, ',');\n cout << \"For state : { \" << current_set << \" }\" << endl;\n for (it = alphabet.begin(); it != alphabet.end(); ++it) {\n set epsilon_state = get_epsilon_closure(get_states(current, *it));\n\n string epsilon_set = to_string(epsilon_state, ',');\n cout << \" \" << *it << \" -> { \" << epsilon_set << \" }\" << endl;\n\n oss << (string) \"T({ \" << current_set << \" }, \" << *it << \" ) : { \" << epsilon_set << \" }\" << endl;\n\n if (!contains(dfa_states, epsilon_state) && !epsilon_state.empty())\n remaining.push(epsilon_state);\n }\n\n dfa_states.push_back(current);\n cout << endl;\n oss<, set > m) {\n string output;\n map< pair, set >::const_iterator it;\n\n for(it = m.begin(); it != m.end(); ++it) {\n output += \"(\" + it->first.first + \", \" + it->first.second + \") -> { \" + to_string(it->second, ',') + \" }\\n\";\n }\n\n return output;\n}\n\nstring nfa::tostring() {\n return \"Alphabet:\\n\"\n \"{ \" + to_string(alphabet, ',') + \" }\"\n \"\\n\\nStates:\\n\"\n \"{ \" + to_string(states, ',') + \" }\"\n \"\\n\\nInitial State : \\n\" +\n initial +\n \"\\n\\nFinal States:\\n\"\n \"{ \" + to_string(final, ',') + \" }\"\n \"\\n\\nTransitions:\\n\" +\n get_transition_string(transitions);\n}Added phi as a state in DFA#include \n#include \n#include \n#include \"nfa.h\"\n#include \"utils.cpp\"\n\nstring error_message = \"NFA Creation Error : \";\n\nvoid verify_state_set(const set& states, const set& state_set) {\n\n set::const_iterator it;\n for (it = state_set.begin(); it != state_set.end(); ++it) {\n if(!states.count(*it))\n throw error_message + \"State '\" + *it + \"' does not belong to Q!\";\n }\n}\n\nvoid verify_states(set states, set initial, set final) {\n if(initial.size() != 1)\n throw error_message + \"There should be one and only one initial state!\";\n\n if(final.size() < 1 || final.size() > states.size() )\n throw error_message + \"Final states should be between 1 and total number of states!\";\n\n \/\/ Verify if all the states in initial and final belong to state vector\n\n if (!states.count(*initial.begin()))\n throw error_message + \"Initial state '\" + *initial.begin() + \"' does not belong to Q!\";\n\n try {\n verify_state_set(states, final);\n } catch (const string& message) {\n cout << \"Invalid Final State!\" << endl;\n throw;\n }\n}\n\nvoid nfa::set_states(const set &states, const set &initial, const set &final) {\n verify_states(states, initial, final);\n\n this->states = states;\n this->final = final;\n this->initial = *initial.begin();\n}\n\nvoid nfa::set_alphabet(const set &alphabet) {\n if(alphabet.count(\"e\"))\n throw \"NFA Parse Error : Language alphabet 'e' clashes with keyword for epsilon!\";\n\n this->alphabet = alphabet;\n}\n\nvoid nfa::add_transition(const string& current_state, const string& alphabet, const set& result) {\n verify_state_set(states, result);\n transitions[make_pair(current_state, alphabet)] = result;\n}\n\nconst set nfa::get_states(const string& state, const string& alphabet) {\n pair key = make_pair(state, alphabet);\n if(!transitions.count(key))\n throw \"NFA Error : Invalid Transition!\";\n\n return transitions[key];\n}\n\nconst set nfa::get_states(const set &states, const string &alphabet) {\n set compound_states;\n\n set::const_iterator it;\n for(it = states.begin(); it != states.end(); ++it) {\n set out_state = get_states(*it, alphabet);\n compound_states.insert(out_state.begin(), out_state.end());\n }\n\n return compound_states;\n}\n\nconst set nfa::get_epsilon_closure(const string &state) {\n set key;\n key.insert(state);\n\n if(epsilon_closures.count(key))\n return epsilon_closures[key];\n\n set epsilon_states;\n\n queue remaining;\n remaining.push(state);\n\n while (!remaining.empty()) {\n string current = remaining.front();\n\n epsilon_states.insert(current);\n\n set epsilon_moves = get_states(current, \"e\");\n set::const_iterator it;\n for(it = epsilon_moves.begin(); it != epsilon_moves.end(); ++it) {\n if(!epsilon_states.count(*it))\n remaining.push(*it);\n }\n\n remaining.pop();\n }\n\n epsilon_closures[key] = epsilon_states;\n\n return epsilon_states;\n}\n\nconst set nfa::get_epsilon_closure(const set &states) {\n if (epsilon_closures.count(states))\n return epsilon_closures[states];\n\n set epsilon_states;\n\n set::const_iterator it;\n for(it = states.begin(); it != states.end(); ++it) {\n set current_states = get_epsilon_closure(*it);\n epsilon_states.insert(current_states.begin(), current_states.end());\n }\n\n epsilon_closures[states] = epsilon_states;\n\n return epsilon_states;\n}\n\nbool nfa::is_final(const set &states) {\n set::const_iterator it;\n\n for(it = states.begin(); it != states.end(); ++it) {\n if(contains(final, *it))\n return true;\n }\n\n return false;\n}\n\nstring nfa::format_output(ostringstream& oss, vector< set >& dfa_states) {\n cout << \"\\nInitial State : \" << endl;\n string initial_state = to_string(dfa_states[0], ',');\n cout << \"{ \" << initial_state << \" }\" << endl;\n\n oss << (string) \"Q0 : { \" << initial_state << \" }\" << endl;\n oss << \"F : {\";\n\n cout << \"Final States : \" << endl;\n string prefix = \"Q : {\";\n const char* delim = \" \";\n for (int i = 0; i < dfa_states.size(); ++i) {\n set current = dfa_states[i];\n\n prefix+= \" { \" + to_string(current, ',') + \" },\";\n\n if(is_final(current)) {\n string final_state = to_string(current, ',');\n cout << \"{ \" << final_state << \" }\" << endl;\n\n oss << delim << \"{ \" << final_state << \" }\";\n delim = \", \";\n }\n }\n oss << \" }\" << endl;\n\n \/\/ Add states and languages to output\n unsigned long index = prefix.length()-1;\n if(prefix[index] == ',')\n prefix.erase(prefix.begin() + index);\n prefix += \" }\\n\";\n prefix += \"E : { \" + to_string(alphabet, ',') + \" }\\n\";\n\n return prefix + \"\\n\" + oss.str();\n}\n\nstring nfa::to_dfa() {\n ostringstream oss;\n cout << \"DFA Conversion : \\n\" << endl;\n set initial = get_epsilon_closure(this->initial);\n\n queue< set > remaining;\n remaining.push(initial);\n\n vector< set > dfa_states;\n\n set::const_iterator it;\n\n while(!remaining.empty()) {\n set current = remaining.front();\n remaining.pop();\n\n if(contains(dfa_states, current))\n continue;\n\n dfa_states.push_back(current);\n\n if(current.empty())\n continue;\n\n string current_set = to_string(current, ',');\n cout << \"For state : { \" << current_set << \" }\" << endl;\n for (it = alphabet.begin(); it != alphabet.end(); ++it) {\n set epsilon_state = get_epsilon_closure(get_states(current, *it));\n\n string epsilon_set = to_string(epsilon_state, ',');\n cout << \" \" << *it << \" -> { \" << epsilon_set << \" }\" << endl;\n\n oss << (string) \"T({ \" << current_set << \" }, \" << *it << \" ) : { \" << epsilon_set << \" }\" << endl;\n\n if (!contains(dfa_states, epsilon_state))\n remaining.push(epsilon_state);\n }\n\n cout << endl;\n oss << endl;\n }\n\n return format_output(oss, dfa_states);\n}\n\nconst string get_transition_string(const map< pair, set > m) {\n string output;\n map< pair, set >::const_iterator it;\n\n for(it = m.begin(); it != m.end(); ++it) {\n output += \"(\" + it->first.first + \", \" + it->first.second + \") -> { \" + to_string(it->second, ',') + \" }\\n\";\n }\n\n return output;\n}\n\nstring nfa::tostring() {\n return \"Alphabet:\\n\"\n \"{ \" + to_string(alphabet, ',') + \" }\"\n \"\\n\\nStates:\\n\"\n \"{ \" + to_string(states, ',') + \" }\"\n \"\\n\\nInitial State : \\n\" +\n initial +\n \"\\n\\nFinal States:\\n\"\n \"{ \" + to_string(final, ',') + \" }\"\n \"\\n\\nTransitions:\\n\" +\n get_transition_string(transitions);\n}<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkScalarImageToHistogramGeneratorTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n\n#include \"itkScalarImageToHistogramGenerator.h\"\n#include \"itkImage.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n\nint itkScalarImageToHistogramGeneratorTest( int , char * [] )\n{\n\n\n {\n typedef unsigned long PixelType;\n const unsigned int imageSize=256;\n const unsigned int Dimension = 2;\n\n typedef itk::Image< PixelType, Dimension > ImageType;\n\n\n ImageType::Pointer image = ImageType::New();\n\n ImageType::RegionType region;\n ImageType::SizeType size;\n ImageType::IndexType start;\n\n size[0] = imageSize;\n size[1] = imageSize;\n\n start[0] = 0;\n start[1] = 0;\n\n region.SetIndex( start );\n region.SetSize( size );\n\n image->SetRegions( region );\n image->Allocate();\n\n \/\/ Now fill up the image will all the combinations of \n \/\/ values from 0-imageSize.\n itk::ImageRegionIteratorWithIndex< ImageType > it( image, region );\n it.GoToBegin();\n\n while( !it.IsAtEnd() )\n {\n it.Set( it.GetIndex()[0] );\n ++it;\n }\n\n\n\n typedef itk::Statistics::ScalarImageToHistogramGenerator< \n ImageType \n > HistogramGeneratorType;\n\n\n HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New();\n\n histogramGenerator->SetInput( image );\n\n histogramGenerator->SetNumberOfBins( imageSize );\n histogramGenerator->SetMarginalScale( 10.0 );\n histogramGenerator->Compute();\n\n typedef HistogramGeneratorType::HistogramType HistogramType;\n\n const HistogramType * histogram = histogramGenerator->GetOutput();\n\n const unsigned int histogramSize = histogram->Size();\n\n std::cout << \"Histogram size \" << histogramSize << std::endl;\n\n const unsigned int channel = 0; \/\/ the only channel\n\n for( unsigned int bin=0; bin < histogramSize; bin++ )\n {\n if( histogram->GetFrequency( bin, channel ) != imageSize ) \n {\n std::cerr << \"Error in bin= \" << bin << \" channel = \" << channel << std::endl;\n std::cerr << \"Frequency was= \" << histogram->GetFrequency( bin, channel ) << \" Instead of the expected \" << imageSize << std::endl;\n return EXIT_FAILURE;\n }\n }\n }\n {\n const unsigned int NumberOfBins=4;\n typedef unsigned long PixelType;\n \/\/ NOTE : it is not uncommon to have a 3D image with more than 4096 * 4096 voxels in the background (i.e. 0'th histogram bin), and this causes an overflow event\n const unsigned int imageSize=4096+NumberOfBins; \/\/ Note 4096^2 = 16777216, which is greater than the number that can be accurately incremented by a floating point number.\n \/\/const unsigned int imageSize=406+NumberOfBins; \/\/ Note 4096^2 = 16777216, which is greater than the number that can be accurately incremented by a floating point number.\n const unsigned int Dimension = 2;\n\n typedef itk::Image< PixelType, Dimension > ImageType;\n\n\n ImageType::Pointer image = ImageType::New();\n\n ImageType::RegionType region;\n ImageType::SizeType size;\n ImageType::IndexType start;\n\n size[0] = imageSize;\n size[1] = imageSize;\n\n start[0] = 0;\n start[1] = 0;\n\n region.SetIndex( start );\n region.SetSize( size );\n\n image->SetRegions( region );\n image->Allocate();\n\n \/\/ Now fill up the image will all the combinations of \n \/\/ values from 0-imageSize.\n itk::ImageRegionIteratorWithIndex< ImageType > it( image, region );\n\n it.GoToBegin();\n for(unsigned int temp=0;temp HistogramGeneratorType;\n\n\n HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New();\n\n histogramGenerator->SetInput( image );\n\n histogramGenerator->SetNumberOfBins( 4 );\n histogramGenerator->SetMarginalScale( 10.0 );\n histogramGenerator->Compute();\n\n typedef HistogramGeneratorType::HistogramType HistogramType;\n\n const HistogramType * histogram = histogramGenerator->GetOutput();\n\n const unsigned int histogramSize = histogram->Size();\n\n std::cout << \"Histogram size \" << histogramSize << std::endl;\n\n const unsigned int channel = 0; \/\/ the only channel\n\n int status=EXIT_SUCCESS;\n {\n const unsigned int bin=0;\n if( histogram->GetFrequency( bin, channel ) == 16777216 ) {\n std::cerr << \"Error in bin= \" << bin << \" channel = \" << channel << std::endl;\n std::cerr << \"Frequency was= \" << (unsigned int)histogram->GetFrequency( bin, channel ) \n << \" which is the maximum integer value representable by a 32bit floating point number \" << std::endl;\n status=EXIT_FAILURE;\n }\n\n if( histogram->GetFrequency( bin, channel ) != imageSize*imageSize - NumberOfBins +1)\n {\n std::cerr << \"Error in bin= \" << bin << \" channel = \" << channel << std::endl;\n std::cerr << \"Frequency was= \" << (unsigned int)histogram->GetFrequency( bin, channel ) << \" Instead of the expected \" << imageSize*imageSize - NumberOfBins +1 << std::endl;\n status=EXIT_FAILURE;\n }\n }\n for( unsigned int bin=1; bin < histogramSize; bin++ )\n {\n if( histogram->GetFrequency( bin, channel ) != 1 )\n {\n std::cerr << \"Error in bin= \" << bin << \" channel = \" << channel << std::endl;\n std::cerr << \"Frequency was= \" << (unsigned int)histogram->GetFrequency( bin, channel ) << \" Instead of the expected \" << 1 << std::endl;\n status=EXIT_FAILURE;\n }\n }\n return status;\n }\n\n return EXIT_SUCCESS;\n\n}\n\n\nSTYLE: Improving formating.\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkScalarImageToHistogramGeneratorTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n\n#include \"itkScalarImageToHistogramGenerator.h\"\n#include \"itkImage.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n\nint itkScalarImageToHistogramGeneratorTest( int , char * [] )\n{\n\n\n {\n typedef unsigned long PixelType;\n const unsigned int imageSize=256;\n const unsigned int Dimension = 2;\n\n typedef itk::Image< PixelType, Dimension > ImageType;\n\n\n ImageType::Pointer image = ImageType::New();\n\n ImageType::RegionType region;\n ImageType::SizeType size;\n ImageType::IndexType start;\n\n size[0] = imageSize;\n size[1] = imageSize;\n\n start[0] = 0;\n start[1] = 0;\n\n region.SetIndex( start );\n region.SetSize( size );\n\n image->SetRegions( region );\n image->Allocate();\n\n \/\/ Now fill up the image will all the combinations of \n \/\/ values from 0-imageSize.\n itk::ImageRegionIteratorWithIndex< ImageType > it( image, region );\n it.GoToBegin();\n\n while( !it.IsAtEnd() )\n {\n it.Set( it.GetIndex()[0] );\n ++it;\n }\n\n\n\n typedef itk::Statistics::ScalarImageToHistogramGenerator< \n ImageType \n > HistogramGeneratorType;\n\n\n HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New();\n\n histogramGenerator->SetInput( image );\n\n histogramGenerator->SetNumberOfBins( imageSize );\n histogramGenerator->SetMarginalScale( 10.0 );\n histogramGenerator->Compute();\n\n typedef HistogramGeneratorType::HistogramType HistogramType;\n\n const HistogramType * histogram = histogramGenerator->GetOutput();\n\n const unsigned int histogramSize = histogram->Size();\n\n std::cout << \"Histogram size \" << histogramSize << std::endl;\n\n const unsigned int channel = 0; \/\/ the only channel\n\n for( unsigned int bin=0; bin < histogramSize; bin++ )\n {\n if( histogram->GetFrequency( bin, channel ) != imageSize ) \n {\n std::cerr << \"Error in bin= \" << bin << \" channel = \" << channel << std::endl;\n std::cerr << \"Frequency was= \" << histogram->GetFrequency( bin, channel ) << \" Instead of the expected \" << imageSize << std::endl;\n return EXIT_FAILURE;\n }\n }\n }\n\n {\n const unsigned int NumberOfBins = 4;\n typedef unsigned long PixelType;\n\n \/\/ NOTE : it is not uncommon to have a 3D image with more than 4096 * 4096\n \/\/ voxels in the background (i.e. 0'th histogram bin), and this causes an\n \/\/ overflow event\n const unsigned int imageSize=4096+NumberOfBins; \n\n \/\/ Note 4096^2 = 16777216, which is greater than the number that can be\n \/\/ accurately incremented by a floating point number.\n \/\/const unsigned int imageSize=406+NumberOfBins; \/\/ Note 4096^2 =\n \/\/16777216, which is greater than the number that can be accurately\n \/\/incremented by a floating point number.\n const unsigned int Dimension = 2;\n\n typedef itk::Image< PixelType, Dimension > ImageType;\n\n\n ImageType::Pointer image = ImageType::New();\n\n ImageType::RegionType region;\n ImageType::SizeType size;\n ImageType::IndexType start;\n\n size[0] = imageSize;\n size[1] = imageSize;\n\n start[0] = 0;\n start[1] = 0;\n\n region.SetIndex( start );\n region.SetSize( size );\n\n image->SetRegions( region );\n image->Allocate();\n\n \/\/ Now fill up the image will all the combinations of \n \/\/ values from 0-imageSize.\n itk::ImageRegionIteratorWithIndex< ImageType > it( image, region );\n\n it.GoToBegin();\n for(unsigned int temp=0;temp HistogramGeneratorType;\n\n\n HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New();\n\n histogramGenerator->SetInput( image );\n\n histogramGenerator->SetNumberOfBins( 4 );\n histogramGenerator->SetMarginalScale( 10.0 );\n\n try\n {\n histogramGenerator->Compute();\n std::cout << \"Failed to catch expected exception about saturation of counters\" << std::endl;\n }\n catch( itk::ExceptionObject & excp )\n {\n std::cout << \"Get Expected Exception\" << std::endl;\n std::cout << excp << std::endl;\n }\n\n typedef HistogramGeneratorType::HistogramType HistogramType;\n\n const HistogramType * histogram = histogramGenerator->GetOutput();\n\n const unsigned int histogramSize = histogram->Size();\n\n std::cout << \"Histogram size \" << histogramSize << std::endl;\n\n const unsigned int channel = 0; \/\/ the only channel\n\n int status=EXIT_SUCCESS;\n {\n\n const unsigned int bin = 0;\n\n if( histogram->GetFrequency( bin, channel ) == 16777216 ) \n {\n std::cerr << \"Error in bin= \" << bin << \" channel = \" << channel << std::endl;\n std::cerr << \"Frequency was= \" << (unsigned int)histogram->GetFrequency( bin, channel ) \n << \" which is the maximum integer value representable by a 32bit floating point number \" << std::endl;\n status = EXIT_FAILURE;\n }\n\n if( histogram->GetFrequency( bin, channel ) != imageSize*imageSize - NumberOfBins + 1 )\n {\n std::cerr << \"Error in bin= \" << bin << \" channel = \" << channel << std::endl;\n std::cerr << \"Frequency was= \" << (unsigned int)histogram->GetFrequency( bin, channel ) << \" Instead of the expected \" << imageSize*imageSize - NumberOfBins +1 << std::endl;\n status = EXIT_FAILURE;\n }\n }\n\n for( unsigned int bin=1; bin < histogramSize; bin++ )\n {\n if( histogram->GetFrequency( bin, channel ) != 1 )\n {\n std::cerr << \"Error in bin= \" << bin << \" channel = \" << channel << std::endl;\n std::cerr << \"Frequency was= \" << (unsigned int)histogram->GetFrequency( bin, channel ) << \" Instead of the expected \" << 1 << std::endl;\n status = EXIT_FAILURE;\n }\n }\n\n return status;\n }\n\n return EXIT_SUCCESS;\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: attributes.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 16:28:42 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#ifndef _CONFIGMGR_MISC_ATTRIBUTES_HXX_\n#define _CONFIGMGR_MISC_ATTRIBUTES_HXX_\n\n#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_\n#include \n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include \n#endif\n\n\/*----------------------------------------\n*\n* Attributlist implementation\n*\n*----------------------------------------*\/\n\nusing namespace ::cppu;\nusing namespace ::rtl;\nusing namespace ::com::sun::star::xml::sax;\nusing namespace ::com::sun::star::uno;\n\nstruct AttributeListImpl_impl;\nclass AttributeListImpl : public WeakImplHelper1< XAttributeList >\n{\nprotected:\n ~AttributeListImpl();\n\npublic:\n AttributeListImpl();\n AttributeListImpl( const AttributeListImpl & );\n\npublic:\n virtual sal_Int16 SAL_CALL getLength(void) throw (RuntimeException);\n virtual OUString SAL_CALL getNameByIndex(sal_Int16 i) throw (RuntimeException);\n virtual OUString SAL_CALL getTypeByIndex(sal_Int16 i) throw (RuntimeException);\n virtual OUString SAL_CALL getTypeByName(const OUString& aName) throw (RuntimeException);\n virtual OUString SAL_CALL getValueByIndex(sal_Int16 i) throw (RuntimeException);\n virtual OUString SAL_CALL getValueByName(const OUString& aName) throw (RuntimeException);\n\npublic:\n void addAttribute( const OUString &sName , const OUString &sType , const OUString &sValue );\n void clear();\n\nprivate:\n struct AttributeListImpl_impl *m_pImpl;\n};\n\n#endif \/\/ _CONFIGMGR_MISC_ATTRIBUTES_HXX_\n\n\nINTEGRATION: CWS changefileheader (1.2.58); FILE MERGED 2008\/04\/01 15:19:45 thb 1.2.58.3: #i85898# Stripping all external header guards 2008\/04\/01 10:58:41 thb 1.2.58.2: #i85898# Stripping all external header guards 2008\/03\/28 15:36:37 rt 1.2.58.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: attributes.hxx,v $\n * $Revision: 1.3 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#ifndef _CONFIGMGR_MISC_ATTRIBUTES_HXX_\n#define _CONFIGMGR_MISC_ATTRIBUTES_HXX_\n\n#include \n#include \n\n\/*----------------------------------------\n*\n* Attributlist implementation\n*\n*----------------------------------------*\/\n\nusing namespace ::cppu;\nusing namespace ::rtl;\nusing namespace ::com::sun::star::xml::sax;\nusing namespace ::com::sun::star::uno;\n\nstruct AttributeListImpl_impl;\nclass AttributeListImpl : public WeakImplHelper1< XAttributeList >\n{\nprotected:\n ~AttributeListImpl();\n\npublic:\n AttributeListImpl();\n AttributeListImpl( const AttributeListImpl & );\n\npublic:\n virtual sal_Int16 SAL_CALL getLength(void) throw (RuntimeException);\n virtual OUString SAL_CALL getNameByIndex(sal_Int16 i) throw (RuntimeException);\n virtual OUString SAL_CALL getTypeByIndex(sal_Int16 i) throw (RuntimeException);\n virtual OUString SAL_CALL getTypeByName(const OUString& aName) throw (RuntimeException);\n virtual OUString SAL_CALL getValueByIndex(sal_Int16 i) throw (RuntimeException);\n virtual OUString SAL_CALL getValueByName(const OUString& aName) throw (RuntimeException);\n\npublic:\n void addAttribute( const OUString &sName , const OUString &sType , const OUString &sValue );\n void clear();\n\nprivate:\n struct AttributeListImpl_impl *m_pImpl;\n};\n\n#endif \/\/ _CONFIGMGR_MISC_ATTRIBUTES_HXX_\n\n\n<|endoftext|>"} {"text":"#ifndef Bull_Constants_hpp\n#define Bull_Constants_hpp\n\n#include \n\nnamespace Bull\n{\n constexpr float Pi = std::acos(-1);\n}\n\n#endif \/\/ Bull_Constants_hpp\nMath\/Constants Add more constants#ifndef Bull_Constants_hpp\n#define Bull_Constants_hpp\n\n#include \n\nnamespace Bull\n{\n constexpr float Pi = std::acos(-1.f);\n\n constexpr float PiPow2 = std::pow(Pi, 2.f);\n\n constexpr float PiPow3 = std::pow(Pi, 3.f);\n\n constexpr float Sqrt2 = std::sqrt(2.f);\n\n constexpr float Sqrt3 = std::sqrt(3.f);\n}\n\n#endif \/\/ Bull_Constants_hpp\n<|endoftext|>"} {"text":"\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include \n#include \n#include \n#include \/\/ memcpy\n\n#ifndef NDEBUG\n#include \n#include \n#endif\n\n#ifndef __SYNTHESIS__\n\/\/#include \n\/\/#include \n#endif\n\n#include \"..\/rand_iterator.h\"\n\nnamespace burst\n{\nnamespace memory\n{\n\n\/\/enum { N = 1024 };\n\n#ifndef __SYNTHESIS__\n\/\/static boost::mutex mtx;\n#endif\n\nstruct node;\ntypedef node* node_ptr;\n\n\n\/\/ node ---------------------------------------------------\n\nstruct node\n{\n region::size_type pos;\n region::size_type size;\n region::size_type pred_pos;\n region::size_type allocated;\n};\n\ninline void make_node(\n volatile uint8_t* mem,\n region::size_type pos,\n region::size_type size,\n region::size_type pred_pos,\n bool allocated\n )\n{\n#pragma HLS INLINE\n node n;\n n.pos = pos;\n n.size = size;\n n.pred_pos = pred_pos;\n n.allocated = allocated;\n {\n#ifndef __SYNTHESIS__\n\/\/ boost::lock_guard l(mtx);\n#endif\n memcpy((uint8_t*)mem + pos, &n, sizeof(n));\n }\n}\n\n\/\/ Order matters!\ninline void merge_nodes(\n volatile uint8_t* mem,\n node const& n1,\n node const& n2,\n bool allocated\n )\n{\n#pragma HLS INLINE\n make_node(mem, n1.pos, n1.size + n2.size, n1.pred_pos, allocated);\n}\n\ninline node get_node(volatile uint8_t* mem, region::size_type pos)\n{\n#pragma HLS INLINE\n node n;\n {\n#ifndef __SYNTHESIS__\n\/\/ boost::lock_guard l(mtx);\n#endif\n memcpy(&n, (uint8_t*)mem + pos, sizeof(n));\n }\n return n;\n}\n\ninline node get_node_from_ptr(volatile void const* ptr)\n{\n#pragma HLS INLINE\n node n;\n {\n#ifndef __SYNTHESIS__\n\/\/ boost::lock_guard l(mtx);\n#endif\n memcpy(&n, (void const*)ptr, sizeof(n));\n }\n return n;\n}\n\ninline node prev_node(volatile uint8_t* mem, node const& n)\n{\n#pragma HLS INLINE\n return get_node(mem, n.pred_pos);\n}\n\ninline node next_node(volatile uint8_t* mem, node const& n)\n{\n#pragma HLS INLINE\n\tregion::size_type addr = n.pos + n.size;\n return get_node(mem, addr);\n}\n\ninline region::size_type get_data_addr(node const& n)\n{\n#pragma HLS INLINE\n return n.pos + sizeof(n);\n}\n\ninline bool operator!=(node const& n1, node const& n2)\n{\n return n1.pos != n2.pos ||\n n1.size != n2.size ||\n n1.pred_pos != n2.pred_pos ||\n n1.allocated != n2.allocated\n ;\n}\n\n#ifndef NDEBUG\ninline std::ostream& operator<<(std::ostream& out, node n)\n{\n out << '(' << n.pos\n << ',' << n.size\n << ',' << n.pred_pos\n << ',' << n.allocated\n << ')';\n return out;\n}\n#endif\n\n\n\/\/ list ---------------------------------------------------\n\nstatic bool free_list_initialized = false;\n\ninline void free_list_init(volatile uint8_t* mem, region::size_type N)\n{\n#pragma HLS INLINE\n make_node(mem, 0, N, 0, false);\n}\n\n\ninline node free_list_insert_first(volatile uint8_t* mem, region::size_type size)\n{\n#pragma HLS INLINE\n\tregion::size_type addr = 0;\n\n node n = get_node(mem, addr);\n\n while (n.size < size || n.allocated)\n {\n n = next_node(mem, n);\n }\n\n\n node n1;\n n1.pos = n.pos;\n n1.size = size;\n n1.pred_pos = n.pred_pos;\n n1.allocated = true;\n\n node n2;\n n2.pos = n.pos + size;\n n2.size = n.size - size;\n n2.pred_pos = n.pos;\n n2.allocated = n.allocated;\n\n make_node(mem, n1.pos, n1.size, n1.pred_pos, n1.allocated);\n make_node(mem, n2.pos, n2.size, n2.pred_pos, n2.allocated);\n\n return n1;\n}\n\n#ifndef NDEBUG\ninline void free_list_print(volatile uint8_t* mem, region::size_type N)\n{\n#ifndef __SYNTHESIS__\n node n = get_node(mem, 0);\n std::cout << \"n= get_node(0): \"<\ninline rand_iterator region::allocate(region::size_type n)\n{\n if (!free_list_initialized)\n {\n free_list_init(data, N);\n free_list_initialized = true;\n }\n \n \/\/ Bytes\n region::size_type size = n * sizeof(T);\n\n node nd = free_list_insert_first(data, size + sizeof(node));\n\n return rand_iterator(\n data,\n static_cast(get_data_addr(nd) \/ sizeof(T)) \/\/ TODO!\n );\n}\n\ntemplate \ninline void region::deallocate(rand_iterator ptr)\n{\n if (!free_list_initialized)\n {\n free_list_init(data, N);\n free_list_initialized = true;\n }\n\n volatile uint8_t* ptr8 = ptr.data() + ptr.pos() * sizeof(T);\n node n1 = get_node_from_ptr(ptr8 - sizeof(node));\n node n2 = next_node(data, n1);\n\n make_node(data, n1.pos, n1.size, n1.pred_pos, false);\n\n if (!n2.allocated)\n merge_nodes(data, n1, n2, false);\n\n n1 = get_node(data, n1.pos);\n node n3 = prev_node(data, n1);\n\n if (!n3.allocated && n1 != n3)\n merge_nodes(data, n3, n1, false);\n}\n\ninline bool region::valid() const\n{\n\treturn data != nullptr;\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Allocate\/deallocate on one of the default memory regions\n\/\/\n\ntemplate \ninline rand_iterator allocate(region::size_type n, region_id id)\n{\n assert(id < RegionMax);\n\n return default_regions[id].allocate(n);\n}\n\ntemplate \ninline void deallocate(rand_iterator ptr, region_id id)\n{\n assert(id < RegionMax);\n\n default_regions[id].deallocate(ptr);\n}\n\n} \/\/ namespace memory\n} \/\/ namespace burst\nPrevent overly strong optimization..\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include \n#include \n#include \n#include \/\/ memcpy\n\n#ifndef NDEBUG\n#include \n#include \n#endif\n\n#ifndef __SYNTHESIS__\n\/\/#include \n\/\/#include \n#endif\n\n#include \"..\/rand_iterator.h\"\n\nnamespace burst\n{\nnamespace memory\n{\n\n\/\/enum { N = 1024 };\n\n#ifndef __SYNTHESIS__\n\/\/static boost::mutex mtx;\n#endif\n\nstruct node;\ntypedef node* node_ptr;\n\n\n\/\/ node ---------------------------------------------------\n\nstruct node\n{\n region::size_type pos;\n region::size_type size;\n region::size_type pred_pos;\n region::size_type allocated;\n};\n\ninline void make_node(\n volatile uint8_t* mem,\n region::size_type pos,\n region::size_type size,\n region::size_type pred_pos,\n bool allocated\n )\n{\n#pragma HLS INLINE\n node n;\n n.pos = pos;\n n.size = size;\n n.pred_pos = pred_pos;\n n.allocated = allocated;\n {\n#ifndef __SYNTHESIS__\n\/\/ boost::lock_guard l(mtx);\n#endif\n memcpy((uint8_t*)mem + pos, &n, sizeof(n));\n }\n}\n\n\/\/ Order matters!\ninline void merge_nodes(\n volatile uint8_t* mem,\n node const& n1,\n node const& n2,\n bool allocated\n )\n{\n#pragma HLS INLINE\n make_node(mem, n1.pos, n1.size + n2.size, n1.pred_pos, allocated);\n}\n\ninline node get_node(volatile uint8_t* mem, region::size_type pos)\n{\n#pragma HLS INLINE\n node n;\n {\n#ifndef __SYNTHESIS__\n\/\/ boost::lock_guard l(mtx);\n#endif\n memcpy(&n, (uint8_t*)mem + pos, sizeof(n));\n }\n return n;\n}\n\ninline node get_node_from_ptr(volatile void const* ptr)\n{\n#pragma HLS INLINE\n node n;\n {\n#ifndef __SYNTHESIS__\n\/\/ boost::lock_guard l(mtx);\n#endif\n memcpy(&n, (void const*)ptr, sizeof(n));\n }\n return n;\n}\n\ninline node prev_node(volatile uint8_t* mem, node const& n)\n{\n#pragma HLS INLINE\n return get_node(mem, n.pred_pos);\n}\n\ninline node next_node(volatile uint8_t* mem, node const& n)\n{\n#pragma HLS INLINE\n\tregion::size_type addr = n.pos + n.size;\n return get_node(mem, addr);\n}\n\ninline region::size_type get_data_addr(node const& n)\n{\n#pragma HLS INLINE\n return n.pos + sizeof(n);\n}\n\ninline bool operator!=(node const& n1, node const& n2)\n{\n return n1.pos != n2.pos ||\n n1.size != n2.size ||\n n1.pred_pos != n2.pred_pos ||\n n1.allocated != n2.allocated\n ;\n}\n\n#ifndef NDEBUG\ninline std::ostream& operator<<(std::ostream& out, node n)\n{\n out << '(' << n.pos\n << ',' << n.size\n << ',' << n.pred_pos\n << ',' << n.allocated\n << ')';\n return out;\n}\n#endif\n\n\n\/\/ list ---------------------------------------------------\n\nstatic bool free_list_initialized = false;\n\ninline void free_list_init(volatile uint8_t* mem, region::size_type N)\n{\n#pragma HLS INLINE\n make_node(mem, 0, N, 0, false);\n}\n\n\ninline node free_list_insert_first(volatile uint8_t* mem, region::size_type size)\n{\n#pragma HLS INLINE\n\tregion::size_type addr = 0;\n\n node n = get_node(mem, addr);\n\n while (n.size < size || n.allocated)\n {\n n = next_node(mem, n);\n }\n\n\n node n1;\n n1.pos = n.pos;\n n1.size = size;\n n1.pred_pos = n.pred_pos;\n n1.allocated = true;\n\n node n2;\n n2.pos = n.pos + size;\n n2.size = n.size - size;\n n2.pred_pos = n.pos;\n n2.allocated = n.allocated;\n\n make_node(mem, n1.pos, n1.size, n1.pred_pos, n1.allocated);\n make_node(mem, n2.pos, n2.size, n2.pred_pos, n2.allocated);\n\n return n1;\n}\n\n#ifndef NDEBUG\ninline void free_list_print(volatile uint8_t* mem, region::size_type N)\n{\n#ifndef __SYNTHESIS__\n node n = get_node(mem, 0);\n std::cout << \"n= get_node(0): \"<\ninline rand_iterator region::allocate(region::size_type n)\n{\n if (!free_list_initialized)\n {\n free_list_init(data, N);\n free_list_initialized = true;\n }\n \n \/\/ Bytes\n region::size_type size = n * sizeof(T);\n\n node nd = free_list_insert_first(data, size + sizeof(node));\n\n return rand_iterator(\n data,\n static_cast(get_data_addr(nd) \/ sizeof(T)) \/\/ TODO!\n );\n}\n\ntemplate \ninline void region::deallocate(rand_iterator ptr)\n{\n if (!free_list_initialized)\n {\n free_list_init(data, N);\n free_list_initialized = true;\n }\n\n volatile uint8_t* ptr8 = ptr.data() + ptr.pos() * sizeof(T);\n node n1 = get_node_from_ptr(ptr8 - sizeof(node));\n node n2 = next_node(data, n1);\n\n make_node(data, n1.pos, n1.size, n1.pred_pos, false);\n\n if (!n2.allocated)\n merge_nodes(data, n1, n2, false);\n\n n1 = get_node(data, n1.pos);\n node n3 = prev_node(data, n1);\n\n if (!n3.allocated && n1 != n3)\n merge_nodes(data, n3, n1, false);\n}\n\ninline bool region::valid() const\n{\n\treturn data != nullptr;\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Allocate\/deallocate on one of the default memory regions\n\/\/\n\ntemplate \ninline rand_iterator allocate(region::size_type n, region_id id)\n{\n assert(id < RegionMax);\n\n auto reg = default_regions[id]; \/\/ Local copy, HLS seems to optimize\n \/\/ this away otherwise..\n return reg.allocate(n);\n}\n\ntemplate \ninline void deallocate(rand_iterator ptr, region_id id)\n{\n assert(id < RegionMax);\n\n default_regions[id].deallocate(ptr);\n}\n\n} \/\/ namespace memory\n} \/\/ namespace burst\n<|endoftext|>"} {"text":"\n\/\/ =================================================================================================\n\/\/ This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This\n\/\/ project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-\n\/\/ width of 100 characters per line.\n\/\/\n\/\/ Author(s):\n\/\/ Cedric Nugteren \n\/\/\n\/\/ This file implements a class with static methods to describe the Xinvert routine. Examples of\n\/\/ such 'descriptions' are how to calculate the size a of buffer or how to run the routine. These\n\/\/ static methods are used by the correctness tester and the performance tester.\n\/\/\n\/\/ =================================================================================================\n\n#ifndef CLBLAST_TEST_ROUTINES_XINVERT_H_\n#define CLBLAST_TEST_ROUTINES_XINVERT_H_\n\n#include \n#include \n\n#include \"utilities\/utilities.hpp\"\n\nnamespace clblast {\n\/\/ =================================================================================================\n\ntemplate \nStatusCode RunReference(const Arguments &args, Buffers &buffers, Queue &queue) {\n const bool is_upper = ((args.triangle == Triangle::kUpper && args.layout != Layout::kRowMajor) ||\n (args.triangle == Triangle::kLower && args.layout == Layout::kRowMajor));\n\n \/\/ Data transfer from OpenCL to std::vector\n std::vector a_mat_cpu(args.a_size, T{0.0});\n buffers.a_mat.Read(queue, args.a_size, a_mat_cpu);\n\n \/\/ Creates the output buffer\n std::vector b_mat_cpu(args.b_size, T{0.0});\n\n \/\/ Helper variables\n const auto block_size = args.m;\n const auto num_blocks = CeilDiv(args.n, block_size);\n const auto a_ld = args.a_ld;\n const auto b_ld = block_size;\n\n \/\/ Checks for valid arguments\n if ((block_size == 0) || (args.n == 0)) {\n return StatusCode::kInvalidDimension;\n }\n if ((block_size % 16 != 0) || (block_size > 128)) {\n return StatusCode::kUnknownError;\n }\n\n \/\/ Loops over the amount of diagonal blocks of size args.m by args.m each\n for (auto block_id = size_t{0}; block_id < num_blocks; ++block_id) {\n const auto a_offset = block_id * (block_size + a_ld * block_size) + args.a_offset;\n const auto b_offset = block_id * block_size * block_size;\n\n \/\/ Inverts the diagonal elements of the matrix\n for (auto i = size_t{0}; i < block_size; ++i) {\n auto a_value = T{1.0};\n if (args.diagonal == Diagonal::kNonUnit) {\n if (i + block_id * block_size < args.n) {\n if (a_mat_cpu[i * a_ld + i + a_offset] == T{0.0}) { return StatusCode::kUnknownError; }\n a_value = T{1.0} \/ a_mat_cpu[i * a_ld + i + a_offset];\n }\n }\n b_mat_cpu[i * b_ld + i + b_offset] = a_value;\n }\n\n \/\/ Inverts the upper triangle row by row\n if (is_upper) {\n for (int i = static_cast(block_size) - 2; i >= 0; --i) {\n for (auto j = static_cast(block_size) - 1; j > i; --j) {\n auto sum = T{0.0};\n for (auto k = i + 1; k <= j; ++k) {\n auto a_value = T{0.0};\n if ((i + block_id * block_size < args.n) && (k + block_id * block_size < args.n)) {\n a_value = a_mat_cpu[k * a_ld + i + a_offset];\n }\n sum += a_value * b_mat_cpu[j * b_ld + k + b_offset];\n }\n b_mat_cpu[j * b_ld + i + b_offset] = - sum * b_mat_cpu[i * b_ld + i + b_offset];\n }\n }\n }\n\n \/\/ Inverts the lower triangle row by row\n else {\n for (auto i = size_t{1}; i < block_size; ++i) {\n for (auto j = size_t{0}; j < i; ++j) {\n auto sum = T{0.0};\n for (auto k = j; k < i; ++k) {\n auto a_value = T{0.0};\n if ((i + block_id * block_size < args.n) && (k + block_id * block_size < args.n)) {\n a_value = a_mat_cpu[k * a_ld + i + a_offset];\n }\n sum += a_value * b_mat_cpu[j * b_ld + k + b_offset];\n }\n b_mat_cpu[j * b_ld + i + b_offset] = - sum * b_mat_cpu[i * b_ld + i + b_offset];\n }\n }\n }\n }\n\n \/\/ Data transfer back to OpenCL\n buffers.b_mat.Write(queue, args.b_size, b_mat_cpu);\n return StatusCode::kSuccess;\n}\n\n\/\/ Half-precision version calling the above reference implementation after conversions\ntemplate <>\nStatusCode RunReference(const Arguments &args, Buffers &buffers, Queue &queue) {\n auto a_buffer2 = HalfToFloatBuffer(buffers.a_mat, queue());\n auto b_buffer2 = HalfToFloatBuffer(buffers.b_mat, queue());\n auto dummy = clblast::Buffer(0);\n auto buffers2 = Buffers{dummy, dummy, a_buffer2, b_buffer2, dummy, dummy, dummy};\n auto args2 = Arguments();\n args2.a_size = args.a_size; args2.b_size = args.b_size;\n args2.a_ld = args.a_ld; args2.m = args.m; args2.n = args.n;\n args2.a_offset = args.a_offset;\n args2.layout = args.layout; args2.triangle = args.triangle; args2.diagonal = args.diagonal;\n auto status = RunReference(args2, buffers2, queue);\n FloatToHalfBuffer(buffers.b_mat, b_buffer2, queue());\n return status;\n}\n\n\/\/ =================================================================================================\n\n\/\/ See comment at top of file for a description of the class\ntemplate \nclass TestXinvert {\n public:\n\n \/\/ The BLAS level: 4 for the extra routines\n static size_t BLASLevel() { return 4; }\n\n \/\/ The list of arguments relevant for this routine\n static std::vector GetOptions() {\n return {kArgN, kArgM,\n kArgLayout, kArgTriangle, kArgDiagonal,\n kArgALeadDim, kArgAOffset};\n }\n\n \/\/ Describes how to obtain the sizes of the buffers\n static size_t GetSizeA(const Arguments &args) {\n return args.n * args.a_ld + args.a_offset;\n }\n static size_t GetSizeB(const Arguments &args) {\n const auto block_size = args.m;\n const auto num_blocks = CeilDiv(args.n, block_size);\n return num_blocks * block_size * block_size;\n }\n\n \/\/ Describes how to set the sizes of all the buffers\n static void SetSizes(Arguments &args) {\n args.a_size = GetSizeA(args);\n args.b_size = GetSizeB(args);\n }\n\n \/\/ Describes what the default values of the leading dimensions of the matrices are\n static size_t DefaultLDA(const Arguments &args) { return args.n; }\n static size_t DefaultLDB(const Arguments &) { return 1; } \/\/ N\/A for this routine\n static size_t DefaultLDC(const Arguments &) { return 1; } \/\/ N\/A for this routine\n\n \/\/ Describes which omatcopyose options are relevant for this routine\n using Transposes = std::vector;\n static Transposes GetATransposes(const Transposes &) { return {}; } \/\/ N\/A for this routine\n static Transposes GetBTransposes(const Transposes &) { return {}; } \/\/ N\/A for this routine\n\n \/\/ Describes how to prepare the input data\n static void PrepareData(const Arguments&, Queue&, const int, std::vector&,\n std::vector&, std::vector&, std::vector&, std::vector&,\n std::vector&, std::vector&) {} \/\/ N\/A for this routine\n\n \/\/ Describes how to run the CLBlast routine\n static StatusCode RunRoutine(const Arguments &args, Buffers &buffers, Queue &queue) {\n try {\n auto event = cl_event{};\n auto inverter = Xinvert(queue, &event);\n inverter.InvertMatrixDiagonalBlocks(args.layout, args.triangle, args.diagonal,\n args.n, args.m,\n buffers.a_mat, args.a_offset, args.a_ld,\n buffers.b_mat);\n clWaitForEvents(1, &event);\n clReleaseEvent(event);\n } catch (...) { return DispatchException(); }\n return StatusCode::kSuccess;\n }\n\n \/\/ Describes how to run a naive version of the routine (for correctness\/performance comparison).\n \/\/ Note that a proper clBLAS or CPU BLAS comparison is not available for non-BLAS routines.\n static StatusCode RunReference1(const Arguments &args, Buffers &buffers, Queue &queue) {\n return RunReference(args, buffers[0], queue);\n }\n\n static StatusCode RunReference2(const Arguments &args, Buffers &buffers, Queue &queue) {\n return RunReference(args, buffers[0], queue);\n }\n\n \/\/ Describes how to download the results of the computation (more importantly: which buffer)\n static std::vector DownloadResult(const Arguments &args, Buffers &buffers, Queue &queue) {\n std::vector result(args.b_size, static_cast(0));\n buffers.b_mat.Read(queue, args.b_size, result);\n return result;\n }\n\n \/\/ Describes how to compute the indices of the result buffer\n static size_t ResultID1(const Arguments &args) { return args.m; }\n static size_t ResultID2(const Arguments &args) { return Ceil(args.n, args.m); }\n static size_t GetResultIndex(const Arguments &args, const size_t id1, const size_t id2) {\n return id1 * Ceil(args.n, args.m) + id2;\n }\n\n \/\/ Describes how to compute performance metrics\n static size_t GetFlops(const Arguments &args) {\n const auto block_size = args.m;\n const auto num_blocks = CeilDiv(args.n, block_size);\n return num_blocks * (block_size * (block_size \/ 2) * (block_size \/ 2));\n }\n static size_t GetBytes(const Arguments &args) {\n return (args.a_size * args.b_size) * sizeof(T);\n }\n};\n\n\/\/ =================================================================================================\n} \/\/ namespace clblast\n\n\/\/ CLBLAST_TEST_ROUTINES_XINVERT_H_\n#endif\nSmall fix for a file that isn't currently compiled anymore\n\/\/ =================================================================================================\n\/\/ This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This\n\/\/ project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-\n\/\/ width of 100 characters per line.\n\/\/\n\/\/ Author(s):\n\/\/ Cedric Nugteren \n\/\/\n\/\/ This file implements a class with static methods to describe the Xinvert routine. Examples of\n\/\/ such 'descriptions' are how to calculate the size a of buffer or how to run the routine. These\n\/\/ static methods are used by the correctness tester and the performance tester.\n\/\/\n\/\/ =================================================================================================\n\n#ifndef CLBLAST_TEST_ROUTINES_XINVERT_H_\n#define CLBLAST_TEST_ROUTINES_XINVERT_H_\n\n#include \n#include \n\n#include \"utilities\/utilities.hpp\"\n\nnamespace clblast {\n\/\/ =================================================================================================\n\ntemplate \nStatusCode RunReference(const Arguments &args, Buffers &buffers, Queue &queue) {\n const bool is_upper = ((args.triangle == Triangle::kUpper && args.layout != Layout::kRowMajor) ||\n (args.triangle == Triangle::kLower && args.layout == Layout::kRowMajor));\n\n \/\/ Data transfer from OpenCL to std::vector\n std::vector a_mat_cpu(args.a_size, T{0.0});\n buffers.a_mat.Read(queue, args.a_size, a_mat_cpu);\n\n \/\/ Creates the output buffer\n std::vector b_mat_cpu(args.b_size, T{0.0});\n\n \/\/ Helper variables\n const auto block_size = args.m;\n const auto num_blocks = CeilDiv(args.n, block_size);\n const auto a_ld = args.a_ld;\n const auto b_ld = block_size;\n\n \/\/ Checks for valid arguments\n if ((block_size == 0) || (args.n == 0)) {\n return StatusCode::kInvalidDimension;\n }\n if ((block_size % 16 != 0) || (block_size > 128)) {\n return StatusCode::kUnknownError;\n }\n\n \/\/ Loops over the amount of diagonal blocks of size args.m by args.m each\n for (auto block_id = size_t{0}; block_id < num_blocks; ++block_id) {\n const auto a_offset = block_id * (block_size + a_ld * block_size) + args.a_offset;\n const auto b_offset = block_id * block_size * block_size;\n\n \/\/ Inverts the diagonal elements of the matrix\n for (auto i = size_t{0}; i < block_size; ++i) {\n auto a_value = T{1.0};\n if (args.diagonal == Diagonal::kNonUnit) {\n if (i + block_id * block_size < args.n) {\n if (a_mat_cpu[i * a_ld + i + a_offset] == T{0.0}) { return StatusCode::kUnknownError; }\n a_value = T{1.0} \/ a_mat_cpu[i * a_ld + i + a_offset];\n }\n }\n b_mat_cpu[i * b_ld + i + b_offset] = a_value;\n }\n\n \/\/ Inverts the upper triangle row by row\n if (is_upper) {\n for (int i = static_cast(block_size) - 2; i >= 0; --i) {\n for (auto j = static_cast(block_size) - 1; j > i; --j) {\n auto sum = T{0.0};\n for (auto k = i + 1; k <= j; ++k) {\n auto a_value = T{0.0};\n if ((i + block_id * block_size < args.n) && (k + block_id * block_size < args.n)) {\n a_value = a_mat_cpu[k * a_ld + i + a_offset];\n }\n sum += a_value * b_mat_cpu[j * b_ld + k + b_offset];\n }\n b_mat_cpu[j * b_ld + i + b_offset] = - sum * b_mat_cpu[i * b_ld + i + b_offset];\n }\n }\n }\n\n \/\/ Inverts the lower triangle row by row\n else {\n for (auto i = size_t{1}; i < block_size; ++i) {\n for (auto j = size_t{0}; j < i; ++j) {\n auto sum = T{0.0};\n for (auto k = j; k < i; ++k) {\n auto a_value = T{0.0};\n if ((i + block_id * block_size < args.n) && (k + block_id * block_size < args.n)) {\n a_value = a_mat_cpu[k * a_ld + i + a_offset];\n }\n sum += a_value * b_mat_cpu[j * b_ld + k + b_offset];\n }\n b_mat_cpu[j * b_ld + i + b_offset] = - sum * b_mat_cpu[i * b_ld + i + b_offset];\n }\n }\n }\n }\n\n \/\/ Data transfer back to OpenCL\n buffers.b_mat.Write(queue, args.b_size, b_mat_cpu);\n return StatusCode::kSuccess;\n}\n\n\/\/ Half-precision version calling the above reference implementation after conversions\ntemplate <>\nStatusCode RunReference(const Arguments &args, Buffers &buffers, Queue &queue) {\n auto a_buffer2 = HalfToFloatBuffer(buffers.a_mat, queue());\n auto b_buffer2 = HalfToFloatBuffer(buffers.b_mat, queue());\n auto dummy = clblast::Buffer(0);\n auto buffers2 = Buffers{dummy, dummy, a_buffer2, b_buffer2, dummy, dummy, dummy};\n auto args2 = Arguments();\n args2.a_size = args.a_size; args2.b_size = args.b_size;\n args2.a_ld = args.a_ld; args2.m = args.m; args2.n = args.n;\n args2.a_offset = args.a_offset;\n args2.layout = args.layout; args2.triangle = args.triangle; args2.diagonal = args.diagonal;\n auto status = RunReference(args2, buffers2, queue);\n FloatToHalfBuffer(buffers.b_mat, b_buffer2, queue());\n return status;\n}\n\n\/\/ =================================================================================================\n\n\/\/ See comment at top of file for a description of the class\ntemplate \nclass TestXinvert {\n public:\n\n \/\/ The BLAS level: 4 for the extra routines\n static size_t BLASLevel() { return 4; }\n\n \/\/ The list of arguments relevant for this routine\n static std::vector GetOptions() {\n return {kArgN, kArgM,\n kArgLayout, kArgTriangle, kArgDiagonal,\n kArgALeadDim, kArgAOffset};\n }\n\n \/\/ Describes how to obtain the sizes of the buffers\n static size_t GetSizeA(const Arguments &args) {\n return args.n * args.a_ld + args.a_offset;\n }\n static size_t GetSizeB(const Arguments &args) {\n const auto block_size = args.m;\n const auto num_blocks = CeilDiv(args.n, block_size);\n return num_blocks * block_size * block_size;\n }\n\n \/\/ Describes how to set the sizes of all the buffers\n static void SetSizes(Arguments &args) {\n args.a_size = GetSizeA(args);\n args.b_size = GetSizeB(args);\n }\n\n \/\/ Describes what the default values of the leading dimensions of the matrices are\n static size_t DefaultLDA(const Arguments &args) { return args.n; }\n static size_t DefaultLDB(const Arguments &) { return 1; } \/\/ N\/A for this routine\n static size_t DefaultLDC(const Arguments &) { return 1; } \/\/ N\/A for this routine\n\n \/\/ Describes which omatcopyose options are relevant for this routine\n using Transposes = std::vector;\n static Transposes GetATransposes(const Transposes &) { return {}; } \/\/ N\/A for this routine\n static Transposes GetBTransposes(const Transposes &) { return {}; } \/\/ N\/A for this routine\n\n \/\/ Describes how to prepare the input data\n static void PrepareData(const Arguments&, Queue&, const int, std::vector&,\n std::vector&, std::vector&, std::vector&, std::vector&,\n std::vector&, std::vector&) {} \/\/ N\/A for this routine\n\n \/\/ Describes how to run the CLBlast routine\n static StatusCode RunRoutine(const Arguments &args, Buffers &buffers, Queue &queue) {\n try {\n auto event = cl_event{};\n auto inverter = Xinvert(queue, &event);\n inverter.InvertMatrixDiagonalBlocks(args.layout, args.triangle, args.diagonal,\n args.n, args.m,\n buffers.a_mat, args.a_offset, args.a_ld,\n buffers.b_mat);\n clWaitForEvents(1, &event);\n clReleaseEvent(event);\n } catch (...) { return DispatchException(); }\n return StatusCode::kSuccess;\n }\n\n \/\/ Describes how to run a naive version of the routine (for correctness\/performance comparison).\n \/\/ Note that a proper clBLAS or CPU BLAS comparison is not available for non-BLAS routines.\n static StatusCode RunReference1(const Arguments &args, Buffers &buffers, Queue &queue) {\n return RunReference(args, buffers, queue);\n }\n\n static StatusCode RunReference2(const Arguments &args, Buffers &buffers, Queue &queue) {\n return RunReference(args, buffers, queue);\n }\n\n \/\/ Describes how to download the results of the computation (more importantly: which buffer)\n static std::vector DownloadResult(const Arguments &args, Buffers &buffers, Queue &queue) {\n std::vector result(args.b_size, static_cast(0));\n buffers.b_mat.Read(queue, args.b_size, result);\n return result;\n }\n\n \/\/ Describes how to compute the indices of the result buffer\n static size_t ResultID1(const Arguments &args) { return args.m; }\n static size_t ResultID2(const Arguments &args) { return Ceil(args.n, args.m); }\n static size_t GetResultIndex(const Arguments &args, const size_t id1, const size_t id2) {\n return id1 * Ceil(args.n, args.m) + id2;\n }\n\n \/\/ Describes how to compute performance metrics\n static size_t GetFlops(const Arguments &args) {\n const auto block_size = args.m;\n const auto num_blocks = CeilDiv(args.n, block_size);\n return num_blocks * (block_size * (block_size \/ 2) * (block_size \/ 2));\n }\n static size_t GetBytes(const Arguments &args) {\n return (args.a_size * args.b_size) * sizeof(T);\n }\n};\n\n\/\/ =================================================================================================\n} \/\/ namespace clblast\n\n\/\/ CLBLAST_TEST_ROUTINES_XINVERT_H_\n#endif\n<|endoftext|>"} {"text":"#ifndef CTHREADRINGBUF\n#define CTHREADRINGBUF\n#include\n#include\t\/\/allocator\n#include\n#include\n#include\t\/\/forward, move, move_if_noexcept, pair\n#include\"CAtomic_stack.hpp\"\n#include\"..\/algorithm\/algorithm.hpp\"\t\/\/for_each_val\n\nnamespace nThread\n{\n\t\/\/a fixed-sized and cannot overwrite when buffer is full\n\ttemplate\n\tclass CThreadRingBuf\n\t{\n\tpublic:\n\t\tusing allocator_type=std::allocator;\n\t\tusing size_type=typename std::allocator::size_type;\n\t\tusing value_type=T;\n\tprivate:\n\t\tusing pointer=typename std::allocator::pointer;\n\t\tstatic allocator_type alloc_;\n\t\tconst pointer begin_;\n\t\tconst size_type size_;\n\t\tstd::mutex mut_;\n\t\tstd::queue queue_;\n\t\tstd::condition_variable read_cv_;\n\t\tCAtomic_stack> stack_;\n\tpublic:\n\t\texplicit CThreadRingBuf(const size_type size)\n\t\t\t:begin_{alloc_.allocate(size)},size_{size}\n\t\t{\n\t\t\tnAlgorithm::for_each_val(begin_,begin_+size,[this](const auto p){\n\t\t\t\tstack_.emplace_not_ts(false,p);\n\t\t\t});\n\t\t}\n\t\tinline bool empty() const noexcept\n\t\t{\n\t\t\treturn queue_.empty();\n\t\t}\n\t\tinline size_type available() const noexcept\n\t\t{\n\t\t\treturn static_cast(queue_.size());\n\t\t}\n\t\t\/\/if constructor or assignment operator you use here is not noexcept, it may not be exception safety\n\t\tvalue_type wait_and_read()\n\t\t{\n\t\t\ttypename CAtomic_stack>::CNode node;\n\t\t\tstd::unique_lock lock{mut_};\n\t\t\tread_cv_.wait(lock,[this]() noexcept{return available();});\n\t\t\tconst pointer p{queue_.front()};\n\t\t\t\/\/1. if move constructor is noexcept, it is exception safety\n\t\t\t\/\/2. if move constructor is not noexcept and copy constructor exists, it is exception safety\n\t\t\t\/\/3. if move constructor is not noexcept and copy constructor does not exist, it may not be exception safety\n\t\t\tconst auto temp{std::move_if_noexcept(*p)};\n\t\t\tqueue_.pop();\n\t\t\tlock.unlock();\n\t\t\tnode.get_data()=std::make_pair(true,std::move(p));\n\t\t\tstack_.emplace_CNode(std::move(node));\n\t\t\treturn temp;\n\t\t}\n\t\tinline size_type size() const noexcept\n\t\t{\n\t\t\treturn size_;\n\t\t}\n\t\t\/\/can only be used when your write will not overwrite the data\n\t\ttemplate\n\t\tvoid write_and_notify(Args &&...args)\n\t\t{\n\t\t\ttypename CAtomic_stack>::CNode node;\n\t\t\tstd::pair p{stack_.pop()};\n\t\t\tif(p.first)\n\t\t\t{\n\t\t\t\talloc_.destroy(p.second);\n\t\t\t\tp.first=false;\n\t\t\t}\n\t\t\ttry\n\t\t\t{\n\t\t\t\talloc_.construct(p.second,std::forward(args)...);\n\t\t\t}catch(...)\n\t\t\t{\n\t\t\t\tnode.get_data()=std::move(p);\n\t\t\t\tstack_.emplace_CNode(std::move(node));\n\t\t\t\tthrow ;\n\t\t\t}\n\t\t\tstd::lock_guard lock{mut_};\n\t\t\tqueue_.emplace(p.second);\n\t\t\tif(queue_.size()==1)\n\t\t\t\tread_cv_.notify_all();\n\t\t}\n\t\t~CThreadRingBuf()\n\t\t{\n\t\t\twhile(!stack_.empty())\n\t\t\t{\n\t\t\t\tconst std::pair p{stack_.pop()};\n\t\t\t\tif(p.first)\n\t\t\t\t\talloc_.destroy(p.second);\n\t\t\t}\n\t\t\twhile(available())\n\t\t\t{\n\t\t\t\talloc_.destroy(queue_.front());\n\t\t\t\tqueue_.pop();\n\t\t\t}\n\t\t\talloc_.deallocate(begin_,size());\n\t\t}\n\t};\n\n\ttemplate\n\ttypename CThreadRingBuf::allocator_type CThreadRingBuf::alloc_;\n}\n\n#endifupdate#ifndef CTHREADRINGBUF\n#define CTHREADRINGBUF\n#include\n#include\t\/\/allocator\n#include\n#include\n#include\n#include\t\/\/forward, move, move_if_noexcept, pair\n#include\"CAtomic_stack.hpp\"\n#include\"..\/algorithm\/algorithm.hpp\"\t\/\/for_each_val\n\nnamespace nThread\n{\n\t\/\/a fixed-sized and cannot overwrite when buffer is full\n\ttemplate\n\tclass CThreadRingBuf\n\t{\n\tpublic:\n\t\tusing allocator_type=std::allocator;\n\t\tusing size_type=typename allocator_type::size_type;\n\t\tusing value_type=T;\n\tprivate:\n\t\tusing pointer=typename allocator_type::pointer;\n\t\tstatic allocator_type alloc_;\n\t\tconst pointer begin_;\n\t\tconst size_type size_;\n\t\tstd::mutex mut_;\n\t\tstd::queue queue_;\n\t\tstd::condition_variable read_cv_;\n\t\tCAtomic_stack> stack_;\n\t\tpointer pop_and_destroy_() noexcept\n\t\t{\n\t\t\tstd::pair p{stack_.pop()};\n\t\t\tif(p.first)\n\t\t\t\talloc_.destroy(p.second);\n\t\t\treturn p.second;\n\t\t}\n\t\ttemplate\n\t\tpointer write_(std::true_type,Args &&...args) noexcept\n\t\t{\n\t\t\tconst pointer p{pop_and_destroy_()};\n\t\t\talloc_.construct(p,std::forward(args)...);\n\t\t\treturn p;\n\t\t}\n\t\ttemplate\n\t\tpointer write_(std::false_type,Args &&...args)\n\t\t{\n\t\t\ttypename CAtomic_stack>::CNode node;\n\t\t\tconst pointer p{pop_and_destroy_()};\n\t\t\ttry\n\t\t\t{\n\t\t\t\talloc_.construct(p,std::forward(args)...);\n\t\t\t}catch(...)\n\t\t\t{\n\t\t\t\tstack_.emplace(std::move(node),false,p);\n\t\t\t\tthrow ;\n\t\t\t}\n\t\t\treturn p;\n\t\t}\n\t\tvoid write_and_notify_queue_(const pointer p)\n\t\t{\n\t\t\tstd::lock_guard lock{mut_};\n\t\t\tqueue_.emplace(p);\n\t\t\tif(queue_.size()==1)\n\t\t\t\tread_cv_.notify_all();\n\t\t}\n\t\tvoid write_queue_(const pointer p)\n\t\t{\n\t\t\tstd::lock_guard lock{mut_};\n\t\t\tqueue_.emplace(p);\n\t\t}\n\tpublic:\n\t\texplicit CThreadRingBuf(const size_type size)\n\t\t\t:begin_{alloc_.allocate(size)},size_{size}\n\t\t{\n\t\t\tnAlgorithm::for_each_val(begin_,begin_+size,[this](const auto p){\n\t\t\t\tstack_.emplace_not_ts(false,p);\n\t\t\t});\n\t\t}\n\t\tinline size_type available() const noexcept\n\t\t{\n\t\t\treturn static_cast(queue_.size());\n\t\t}\n\t\tinline bool empty() const noexcept\n\t\t{\n\t\t\treturn queue_.empty();\n\t\t}\n\t\tinline size_type size() const noexcept\n\t\t{\n\t\t\treturn size_;\n\t\t}\n\t\t\/\/if constructor or assignment operator you use here is not noexcept, it may not be exception safety\n\t\tvalue_type read()\n\t\t{\n\t\t\ttypename CAtomic_stack>::CNode node;\n\t\t\tstd::lock_guard lock{mut_};\n\t\t\tconst pointer p{queue_.front()};\n\t\t\tconst auto temp{std::move_if_noexcept(*p)};\n\t\t\tqueue_.pop();\n\t\t\tlock.unlock();\n\t\t\tstack_.emplace(std::move(node),true,p);\n\t\t\treturn temp;\n\t\t}\n\t\t\/\/if constructor or assignment operator you use here is not noexcept, it may not be exception safety\n\t\tvalue_type wait_and_read()\n\t\t{\n\t\t\ttypename CAtomic_stack>::CNode node;\n\t\t\tstd::unique_lock lock{mut_};\n\t\t\tread_cv_.wait(lock,[this]() noexcept{return available();});\n\t\t\tconst pointer p{queue_.front()};\n\t\t\tconst auto temp{std::move_if_noexcept(*p)};\n\t\t\tqueue_.pop();\n\t\t\tlock.unlock();\n\t\t\tstack_.emplace(std::move(node),true,p);\n\t\t\treturn temp;\n\t\t}\n\t\t\/\/can only be used when your write will not overwrite the data\n\t\ttemplate\n\t\tinline void write(Args &&...args)\n\t\t{\n\t\t\twrite_queue_(write_(std::is_nothrow_constructible{},std::forward(args)...));\n\t\t}\n\t\t\/\/can only be used when your write will not overwrite the data\n\t\ttemplate\n\t\tinline void write_and_notify(Args &&...args)\n\t\t{\n\t\t\twrite_and_notify_queue_(write_(std::is_nothrow_constructible{},std::forward(args)...));\n\t\t}\n\t\t~CThreadRingBuf()\n\t\t{\n\t\t\twhile(!stack_.empty())\n\t\t\t{\n\t\t\t\tconst std::pair p{stack_.pop()};\n\t\t\t\tif(p.first)\n\t\t\t\t\talloc_.destroy(p.second);\n\t\t\t}\n\t\t\twhile(available())\n\t\t\t{\n\t\t\t\talloc_.destroy(queue_.front());\n\t\t\t\tqueue_.pop();\n\t\t\t}\n\t\t\talloc_.deallocate(begin_,size());\n\t\t}\n\t};\n\n\ttemplate\n\ttypename CThreadRingBuf::allocator_type CThreadRingBuf::alloc_;\n}\n\n#endif<|endoftext|>"} {"text":"\/----------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$ \n\/\/\n\/\/ Copyright (C) 2003, 2004, 2005, 2007 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/----------------------------------------------------------------------\n\n\/\/ test output of curved cells at the boundary and in the inner of the domain,\n\/\/ where the last one is only relevant for mappings of type MappingQEulerian\n\n#include \"..\/tests.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace dealii;\n\n\n\/\/ this is copied from GridGenerator\nvoid laplace_solve (const SparseMatrix &S,\n\t\t const std::map &m,\n\t\t Vector &u)\n{\n const unsigned int n_dofs=S.n();\n FilteredMatrix > SF (S);\n PreconditionJacobi > prec;\n prec.initialize(S, 1.2);\n FilteredMatrix > PF (prec);\n \n SolverControl control (10000, 1.e-10, false, false);\n GrowingVectorMemory > mem;\n SolverCG > solver (control, mem);\n \n Vector f(n_dofs);\n \n SF.add_constraints(m);\n SF.apply_constraints (f, true);\n solver.solve(SF, u, f, PF);\n}\n\n\n\/\/ create a rinf grid and compute a MappingQEuler to represent the inner\n\/\/ boundary\nvoid curved_grid (std::ofstream &out)\n{\n\t\t\t\t \/\/ number of cells in radial and\n\t\t\t\t \/\/ circumferential direction\n const unsigned int n_phi=4,\n\t\t n_r=8;\n\t\t\t\t \/\/ inner and outer radius \n const double r_i=0.5,\n\t r_a=2.0;\n\t\t\t\t \/\/ we want to increase the radial extent of\n\t\t\t\t \/\/ each cell by 'factor'. compute, how large\n\t\t\t\t \/\/ the first extent 'dr' has to be\n double factor=2.,\n\t sum=0;\n for (unsigned int j=0; j r(n_r+1,r_i);\n for (unsigned int j=1; j > vertices(n_phi*(n_r+1));\n for (unsigned int j=0; j(r[j]*cos(alpha),r[j]*sin(alpha));\n }\n\t\t\t\t \/\/ create connectivity\n std::vector > cells(n_phi*n_r);\n for (unsigned int j=0; j triangulation;\n triangulation.create_triangulation_compatibility(vertices,cells,SubCellData());\n\t\t\t\t \/\/ now provide everything that is\n\t\t\t\t \/\/ needed for solving a Laplace\n\t\t\t\t \/\/ equation. \n MappingQ1<2> mapping_q1; \n FE_Q<2> fe(2);\n DoFHandler<2> dof_handler(triangulation);\n dof_handler.distribute_dofs(fe);\n SparsityPattern sparsity_pattern (dof_handler.n_dofs (), dof_handler.n_dofs (),\n\t\t\t\t dof_handler.max_couplings_between_dofs());\n DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);\n sparsity_pattern.compress ();\n SparseMatrix S(sparsity_pattern);\n QGauss4<2> quadrature;\n MatrixCreator::create_laplace_matrix(mapping_q1, dof_handler, quadrature, S);\n\t\t\t\t \/\/ set up the boundary values for\n\t\t\t\t \/\/ the laplace problem\n std::vector > m(2);\n\t\t\t\t \/\/ fill these maps: on the inner boundary try\n\t\t\t\t \/\/ to approximate a circle, on the outer\n\t\t\t\t \/\/ boundary use straight lines\n DoFHandler<2>::cell_iterator cell=dof_handler.begin_active(),\n\t\t\t\t\t endc=dof_handler.end();\n DoFHandler<2>::face_iterator face;\n for (; cell!=endc; ++cell)\n {\n\t\t\t\t \/\/ fix all vertices\n for (unsigned int vertex_no=0;\n\t vertex_no::vertices_per_cell; ++vertex_no)\n\t{\n\t for (unsigned int i=0; i<2; ++i)\n\t m[i][cell->vertex_dof_index(vertex_no, 0)]=0.;\n\t}\n\n if (cell->at_boundary())\n\tfor (unsigned int face_no=0; face_no::faces_per_cell; ++face_no)\n\t {\n\t face=cell->face(face_no);\n\t\t\t\t\t\t \/\/ insert a modifiued value for\n\t\t\t\t\t\t \/\/ the middle point of boundary\n\t\t\t\t\t\t \/\/ faces\n\t if (face->at_boundary())\n\t {\n\t\tconst double eps=1e-4;\n\t\tif (std::fabs(face->vertex(1).norm()-r_i)dof_index(0)]= (face->center()*(r_i\/face->center().norm()-1))(i);\n \t\telse if (std::fabs(face->vertex(1).norm()-r_a)dof_index(0)]=0.;\n \t\telse\n \t\t Assert(false, ExcInternalError());\n\t }\n\t }\n }\n\t\t\t\t \/\/ solve the 2 problems with\n\t\t\t\t \/\/ different right hand sides.\n Vector us[2];\n for (unsigned int i=0; i<2; ++i)\n us[i].reinit (dof_handler.n_dofs());\n\t\t\t\t \/\/ solve linear systems in parallel\n Threads::ThreadGroup<> threads;\n for (unsigned int i=0; i<2; ++i)\n threads += Threads::spawn (&laplace_solve)(S, m[i], us[i]);\n threads.join_all ();\n\t\t\t\t \/\/ create a new DoFHandler for the combined\n\t\t\t\t \/\/ system\n FESystem<2> cfe(FE_Q<2>(2),2);\n DoFHandler<2> cdh(triangulation);\n cdh.distribute_dofs(cfe);\n Vector displacements(cdh.n_dofs()),\n dx(fe.dofs_per_cell),\n dy(fe.dofs_per_cell),\n dxy(cfe.dofs_per_cell);\n DoFHandler<2>::active_cell_iterator component_cell=dof_handler.begin_active(),\n\t\t\t\t\t\tend_c=dof_handler.end(),\n\t\t\t\t combined_cell=cdh.begin_active();\n for (; component_cell!=end_c; ++component_cell, ++combined_cell)\n {\n component_cell->get_dof_values (us[0], dx);\n component_cell->get_dof_values (us[1], dy);\n for (unsigned int i=0; iset_dof_values (dxy, displacements);\n }\n\t\t\t\t \/\/ and create the MappingQEulerian\n MappingQEulerian<2> euler(2, displacements, cdh);\n\t\t\t\t \/\/ now the actual test\n DataOut<2> data_out;\n data_out.attach_dof_handler(cdh);\n std::vector names;\n names.push_back(\"x_displacement\");\n names.push_back(\"y_displacement\");\n data_out.add_data_vector(displacements,names);\n\t\t\t\t \/\/ output with no mapping\n data_out.build_patches(5);\n data_out.write_gnuplot(out);\n\t\t\t\t \/\/ output with no curved cells\n data_out.build_patches(euler,5,multithread_info.n_default_threads,DataOut<2>::no_curved_cells);\n data_out.write_gnuplot(out);\n \t\t\t\t \/\/ output with curved cells at the boundary\n \t\t\t\t \/\/ (default)\n data_out.build_patches(euler,5);\n data_out.write_gnuplot(out);\n \t\t\t\t \/\/ output with all cells curved\n data_out.build_patches(euler,5,multithread_info.n_default_threads,DataOut<2>::curved_inner_cells);\n data_out.write_gnuplot(out);\n}\n\n\n\nint main () \n{\n std::ofstream logfile(\"data_out_curved_cells\/output\");\n deallog.attach(logfile);\n deallog << std::setprecision (4);\n logfile << std::setprecision (4);\n deallog.depth_console(0);\n deallog.threshold_double(1.e-10);\n\n curved_grid (logfile);\n}\n\n\nFix testcase for good this time.\/\/----------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$ \n\/\/\n\/\/ Copyright (C) 2003, 2004, 2005, 2007 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/----------------------------------------------------------------------\n\n\/\/ test output of curved cells at the boundary and in the inner of the domain,\n\/\/ where the last one is only relevant for mappings of type MappingQEulerian\n\n#include \"..\/tests.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace dealii;\n\n\n\/\/ this is copied from GridGenerator\nvoid laplace_solve (const SparseMatrix &S,\n\t\t const std::map &m,\n\t\t Vector &u)\n{\n const unsigned int n_dofs=S.n();\n FilteredMatrix > SF (S);\n PreconditionJacobi > prec;\n prec.initialize(S, 1.2);\n FilteredMatrix > PF (prec);\n \n SolverControl control (10000, 1.e-10, false, false);\n GrowingVectorMemory > mem;\n SolverCG > solver (control, mem);\n \n Vector f(n_dofs);\n \n SF.add_constraints(m);\n SF.apply_constraints (f, true);\n solver.solve(SF, u, f, PF);\n}\n\n\n\/\/ create a rinf grid and compute a MappingQEuler to represent the inner\n\/\/ boundary\nvoid curved_grid (std::ofstream &out)\n{\n\t\t\t\t \/\/ number of cells in radial and\n\t\t\t\t \/\/ circumferential direction\n const unsigned int n_phi=4,\n\t\t n_r=8;\n\t\t\t\t \/\/ inner and outer radius \n const double r_i=0.5,\n\t r_a=2.0;\n\t\t\t\t \/\/ we want to increase the radial extent of\n\t\t\t\t \/\/ each cell by 'factor'. compute, how large\n\t\t\t\t \/\/ the first extent 'dr' has to be\n double factor=2.,\n\t sum=0;\n for (unsigned int j=0; j r(n_r+1,r_i);\n for (unsigned int j=1; j > vertices(n_phi*(n_r+1));\n for (unsigned int j=0; j(r[j]*cos(alpha),r[j]*sin(alpha));\n }\n\t\t\t\t \/\/ create connectivity\n std::vector > cells(n_phi*n_r);\n for (unsigned int j=0; j triangulation;\n triangulation.create_triangulation_compatibility(vertices,cells,SubCellData());\n\t\t\t\t \/\/ now provide everything that is\n\t\t\t\t \/\/ needed for solving a Laplace\n\t\t\t\t \/\/ equation. \n MappingQ1<2> mapping_q1; \n FE_Q<2> fe(2);\n DoFHandler<2> dof_handler(triangulation);\n dof_handler.distribute_dofs(fe);\n SparsityPattern sparsity_pattern (dof_handler.n_dofs (), dof_handler.n_dofs (),\n\t\t\t\t dof_handler.max_couplings_between_dofs());\n DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);\n sparsity_pattern.compress ();\n SparseMatrix S(sparsity_pattern);\n QGauss4<2> quadrature;\n MatrixCreator::create_laplace_matrix(mapping_q1, dof_handler, quadrature, S);\n\t\t\t\t \/\/ set up the boundary values for\n\t\t\t\t \/\/ the laplace problem\n std::vector > m(2);\n\t\t\t\t \/\/ fill these maps: on the inner boundary try\n\t\t\t\t \/\/ to approximate a circle, on the outer\n\t\t\t\t \/\/ boundary use straight lines\n DoFHandler<2>::cell_iterator cell=dof_handler.begin_active(),\n\t\t\t\t\t endc=dof_handler.end();\n DoFHandler<2>::face_iterator face;\n for (; cell!=endc; ++cell)\n {\n\t\t\t\t \/\/ fix all vertices\n for (unsigned int vertex_no=0;\n\t vertex_no::vertices_per_cell; ++vertex_no)\n\t{\n\t for (unsigned int i=0; i<2; ++i)\n\t m[i][cell->vertex_dof_index(vertex_no, 0)]=0.;\n\t}\n\n if (cell->at_boundary())\n\tfor (unsigned int face_no=0; face_no::faces_per_cell; ++face_no)\n\t {\n\t face=cell->face(face_no);\n\t\t\t\t\t\t \/\/ insert a modifiued value for\n\t\t\t\t\t\t \/\/ the middle point of boundary\n\t\t\t\t\t\t \/\/ faces\n\t if (face->at_boundary())\n\t {\n\t\tconst double eps=1e-4;\n\t\tif (std::fabs(face->vertex(1).norm()-r_i)dof_index(0)]= (face->center()*(r_i\/face->center().norm()-1))(i);\n \t\telse if (std::fabs(face->vertex(1).norm()-r_a)dof_index(0)]=0.;\n \t\telse\n \t\t Assert(false, ExcInternalError());\n\t }\n\t }\n }\n\t\t\t\t \/\/ solve the 2 problems with\n\t\t\t\t \/\/ different right hand sides.\n Vector us[2];\n for (unsigned int i=0; i<2; ++i)\n us[i].reinit (dof_handler.n_dofs());\n\t\t\t\t \/\/ solve linear systems in parallel\n Threads::ThreadGroup<> threads;\n for (unsigned int i=0; i<2; ++i)\n threads += Threads::spawn (&laplace_solve)(S, m[i], us[i]);\n threads.join_all ();\n\t\t\t\t \/\/ create a new DoFHandler for the combined\n\t\t\t\t \/\/ system\n FESystem<2> cfe(FE_Q<2>(2),2);\n DoFHandler<2> cdh(triangulation);\n cdh.distribute_dofs(cfe);\n Vector displacements(cdh.n_dofs()),\n dx(fe.dofs_per_cell),\n dy(fe.dofs_per_cell),\n dxy(cfe.dofs_per_cell);\n DoFHandler<2>::active_cell_iterator component_cell=dof_handler.begin_active(),\n\t\t\t\t\t\tend_c=dof_handler.end(),\n\t\t\t\t combined_cell=cdh.begin_active();\n for (; component_cell!=end_c; ++component_cell, ++combined_cell)\n {\n component_cell->get_dof_values (us[0], dx);\n component_cell->get_dof_values (us[1], dy);\n for (unsigned int i=0; iset_dof_values (dxy, displacements);\n }\n\t\t\t\t \/\/ and create the MappingQEulerian\n MappingQEulerian<2> euler(2, displacements, cdh);\n\t\t\t\t \/\/ now the actual test\n DataOut<2> data_out;\n data_out.attach_dof_handler(cdh);\n std::vector names;\n names.push_back(\"x_displacement\");\n names.push_back(\"y_displacement\");\n data_out.add_data_vector(displacements,names);\n\t\t\t\t \/\/ output with no mapping\n data_out.build_patches(5);\n data_out.write_gnuplot(out);\n\t\t\t\t \/\/ output with no curved cells\n data_out.build_patches(euler,5,DataOut<2>::no_curved_cells);\n data_out.write_gnuplot(out);\n \t\t\t\t \/\/ output with curved cells at the boundary\n \t\t\t\t \/\/ (default)\n data_out.build_patches(euler,5);\n data_out.write_gnuplot(out);\n \t\t\t\t \/\/ output with all cells curved\n data_out.build_patches(euler,5,DataOut<2>::curved_inner_cells);\n data_out.write_gnuplot(out);\n}\n\n\n\nint main () \n{\n std::ofstream logfile(\"data_out_curved_cells\/output\");\n deallog.attach(logfile);\n deallog << std::setprecision (4);\n logfile << std::setprecision (4);\n deallog.depth_console(0);\n deallog.threshold_double(1.e-10);\n\n curved_grid (logfile);\n}\n\n\n<|endoftext|>"} {"text":"\/*\n * CampSiteActiveAreaImplementation.cpp\n *\n * Created on: Jan 1, 2012\n * Author: Kyle\n *\/\n\n#include \"server\/zone\/objects\/area\/CampSiteActiveArea.h\"\n#include \"server\/zone\/objects\/area\/CampSiteObserver.h\"\n#include \"server\/zone\/objects\/structure\/StructureObject.h\"\n#include \"server\/zone\/managers\/player\/PlayerManager.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n#include \"server\/zone\/objects\/player\/PlayerObject.h\"\n#include \"server\/zone\/managers\/structure\/StructureManager.h\"\n#include \"server\/zone\/objects\/tangible\/terminal\/Terminal.h\"\n#include \"server\/zone\/Zone.h\"\n#include \"server\/zone\/objects\/area\/events\/CampAbandonTask.h\"\n#include \"server\/zone\/objects\/area\/events\/CampDespawnTask.h\"\n\nvoid CampSiteActiveAreaImplementation::initializeTransientMembers() {\n\tstartTasks();\n}\n\nvoid CampSiteActiveAreaImplementation::init(CampStructureTemplate* campData) {\n\tcampStructureData = campData;\n\tsetRadius(campStructureData->getRadius());\n\tstartTasks();\n}\n\nvoid CampSiteActiveAreaImplementation::startTasks() {\n\tLocker locker(&taskMutex);\n\n\tif(despawnTask == NULL) {\n\t\tdespawnTask = new CampDespawnTask(_this.get());\n\t} else {\n\t\tif(despawnTask->isScheduled())\n\t\t\tdespawnTask->cancel();\n\t}\n\n\n\tif(abandonTask == NULL) {\n\t\tabandonTask = new CampAbandonTask(_this.get());\n\t} else {\n\t\tif(abandonTask->isScheduled())\n\t\t\tabandonTask->cancel();\n\t}\n\n\tdespawnTask->schedule(CampSiteActiveArea::DESPAWNTIME);\n\tabandonTask->schedule(CampSiteActiveArea::ABANDONTIME);\n\n}\n\nvoid CampSiteActiveAreaImplementation::notifyEnter(SceneObject* object) {\n\tif (!object->isPlayerCreature())\n\t\treturn;\n\n\tif (camp == NULL || terminal == NULL)\n\t\treturn;\n\n\tCreatureObject* player = cast (object);\n\n\tif (player == NULL)\n\t\treturn;\n\n\tif (camp != NULL)\n\t\tcamp->addTemplateSkillMods(player);\n\n\tif (campObserver == NULL) {\n\t\tcampObserver = new CampSiteObserver(_this.get());\n\t\tcampObserver->deploy();\n\t}\n\n\tif(object == campOwner && !abandoned) {\n\n\t\tLocker locker(&taskMutex);\n\n\t\tif(abandonTask != NULL && abandonTask->isScheduled())\n\t\t\tabandonTask->cancel();\n\n\t\tobject->registerObserver(ObserverEventType::STARTCOMBAT, campObserver);\n\n\t} else {\n\n\t\tStringIdChatParameter stringID(\"camp\", \"prose_camp_enter\");\n\t\tstringID.setTO(terminal->getDisplayedName());\n\t\tplayer->sendSystemMessage(stringID);\n\n\t\tplayer->sendSystemMessage(\"@camp:sys_camp_heal\"); \/\/ While in the camp, medics and entertainers can heal your wounds.\n\n\t}\n\n\tif (object->isPlayerCreature() && !visitors.contains(object->getObjectID()))\n\t\tvisitors.add(object->getObjectID());\n\n\n\tif (object->isPlayerCreature())\n\t\tobject->registerObserver(ObserverEventType::HEALINGPERFORMED, campObserver);\n}\n\nvoid CampSiteActiveAreaImplementation::notifyExit(SceneObject* object) {\n\tobject->dropObserver(ObserverEventType::HEALINGPERFORMED, campObserver);\n\n\tif (!object->isPlayerCreature())\n\t\treturn;\n\n\tif (camp == NULL || terminal == NULL)\n\t\treturn;\n\n\tCreatureObject* player = cast (object);\n\n\tif (player == NULL)\n\t\treturn;\n\n\tif (camp != NULL)\n\t\tcamp->removeTemplateSkillMods(player);\n\n\tif(abandoned || object != campOwner) {\n\t\tStringIdChatParameter stringID(\"camp\", \"prose_camp_exit\");\n\t\tstringID.setTO(terminal->getDisplayedName());\n\t\tplayer->sendSystemMessage(stringID);\n\t\treturn;\n\t}\n\n\tLocker locker(&taskMutex);\n\n\tif(!abandoned && abandonTask != NULL && !abandonTask->isScheduled()) {\n\t\ttry {\n\t\t\tabandonTask->schedule(CampSiteActiveArea::ABANDONTIME);\n\t\t} catch (Exception& e) {\n\n\t\t}\n\t}\n}\n\nint CampSiteActiveAreaImplementation::notifyHealEvent(int64 quantity) {\n\t\/\/ Increase XP Pool for heals\n\tcurrentXp += (campStructureData->getExperience() \/ 180);\n\treturn 1;\n}\n\nint CampSiteActiveAreaImplementation::notifyCombatEvent() {\n\tabandonCamp();\n\n\tLocker locker(&taskMutex);\n\n\tif(abandonTask != NULL)\n\t\tif(abandonTask->isScheduled())\n\t\t\tabandonTask->cancel();\n\n\tif(campOwner != NULL)\n\t\tcampOwner->sendSystemMessage(\"@camp:sys_abandoned_camp\"); \/\/ Your camp has been abandoned.\n\n\treturn 1;\n}\n\nvoid CampSiteActiveAreaImplementation::abandonCamp() {\n\tabandoned = true;\n\n\tcurrentXp = 0;\n\n\tLocker locker(&taskMutex);\n\n\tif(despawnTask != NULL && despawnTask->isScheduled()) {\n\t\tdespawnTask->cancel();\n\t\tint newTime = (CampSiteActiveArea::DESPAWNTIME \/ 6);\n\t\tint maxTime = CampSiteActiveArea::DESPAWNTIME - ((System::getTime() - timeCreated) * 1000);\n\n\t\tdespawnTask->schedule(newTime < maxTime ? newTime : maxTime);\n\t}\n\n\tif(terminal != NULL)\n\t\tterminal->setCustomObjectName(\"Abandoned Camp\", true);\n\n\tif(campOwner != NULL) {\n\t\tcampOwner->dropObserver(ObserverEventType::STARTCOMBAT, campObserver);\n\t\tcampOwner->sendSystemMessage(\"@camp:sys_abandoned_camp\"); \/\/ Your camp has been abandoned.\n\t}\n}\n\nbool CampSiteActiveAreaImplementation::despawnCamp() {\n\tLocker locker(_this.get());\n\n\tif(!abandoned && campOwner != NULL && campOwner->getZoneServer() != NULL) {\n\t\t\/\/\/ Get Player Manager\n\t\tPlayerManager* playerManager = campOwner->getZoneServer()->getPlayerManager();\n\t\tif (playerManager == NULL) {\n\t\t\terror(\"playerManager is null\");\n\t\t\treturn false;\n\t\t}\n\n\t\tfloat durationUsed = ((float)(System::getTime() - timeCreated)) \/ (campStructureData->getDuration() \/ 4);\n\t\tif (durationUsed > 1)\n\t\t\tdurationUsed = 1;\n\n\t\tint amount = 0;\n\t\tint campXp = campStructureData->getExperience();\n\t\tamount = (int)(campXp * durationUsed);\n\n\t\tamount += (int)((visitors.size() -1) * (campXp \/ 30) * durationUsed);\n\t\tamount += (int)(currentXp * durationUsed);\n\n\t\tplayerManager->awardExperience(campOwner, \"camp\", amount, true);\n\t}\n\n\tLocker tlocker(&taskMutex);\n\n\tif(despawnTask != NULL ) {\n\t\tif(despawnTask->isScheduled())\n\t\t\tdespawnTask->cancel();\n\t\tdespawnTask = NULL;\n\t}\n\n\n\tif(abandonTask != NULL) {\n\t\tif(abandonTask->isScheduled())\n\t\t\tabandonTask->cancel();\n\t\tabandonTask = NULL;\n\t}\n\n\ttlocker.release();\n\n\tif(campOwner != NULL)\n\t\tcampOwner->dropObserver(ObserverEventType::STARTCOMBAT, campObserver);\n\n\tif (camp != NULL) {\n\t\tif(camp->getZone() == NULL)\n\t\t\treturn false;\n\n\t\tStructureManager::instance()->destroyStructure(camp);\n\t}\n\n\tdestroyObjectFromWorld(true);\n\tdestroyObjectFromDatabase(true);\n\n\n\treturn true;\n}\n\nvoid CampSiteActiveAreaImplementation::assumeOwnership(CreatureObject* player) {\n\tif (camp == NULL || player == NULL)\n\t\treturn;\n\n\tif (player->getSkillMod(\"camp\") < campStructureData->getSkillRequired()) {\n\t\tplayer->sendSystemMessage(\"@camp:error_too_big\"); \/\/ You cannot assume ownership of this camp. You lack the skill to maintain a camp of this size.\n\t\treturn;\n\t}\n\n\tPlayerObject* playerGhost = player->getPlayerObject();\n\n\tif (playerGhost == NULL)\n\t\treturn;\n\n\tfor (int i = 0; i < playerGhost->getTotalOwnedStructureCount(); ++i) {\n\t\tuint64 oid = playerGhost->getOwnedStructure(i);\n\n\t\tManagedReference structure = playerGhost->getZoneServer()->getObject(oid).castTo();\n\n\t\tif (structure->isCampStructure()) {\n\t\t\tplayer->sendSystemMessage(\"@camp:sys_already_camping\"); \/\/ But you already have a camp established elsewhere!\n\t\t\treturn;\n\t\t}\n\t}\n\n\tPlayerObject* ownerGhost = campOwner->getPlayerObject();\n\n\tif (ownerGhost != NULL) {\n\t\townerGhost->removeOwnedStructure(camp);\n\t}\n\n\tsetOwner(player);\n\n\tabandoned = false;\n\tcurrentXp = 0;\n\tvisitors.removeAll();\n\n\tReference >*> closeObjects = new SortedVector >();\n\tzone->getInRangeObjects(camp->getWorldPositionX(), camp->getWorldPositionY(), campStructureData->getRadius(), closeObjects, true);\n\n\tfor (int i = 0; i < closeObjects->size(); ++i) {\n\t\tSceneObject* scno = cast(closeObjects->get(i).get());\n\t\tif (scno->isPlayerCreature())\n\t\t\tvisitors.add(scno->getObjectID());\n\t}\n\n\tplayerGhost->addOwnedStructure(camp);\n\n\tcampOwner->registerObserver(ObserverEventType::STARTCOMBAT, campObserver);\n\n\tLocker locker(&taskMutex);\n\n\tif(abandonTask != NULL && abandonTask->isScheduled())\n\t\tabandonTask->cancel();\n\n\tif(despawnTask != NULL && despawnTask->isScheduled())\n\t\tdespawnTask->cancel();\n\n\ttimeCreated = System::getTime();\n\tdespawnTask->schedule(CampSiteActiveArea::DESPAWNTIME);\n\n\tif(terminal != NULL) {\n\t\tString campName = campOwner->getFirstName();\n\t\tif(!campOwner->getLastName().isEmpty())\n\t\t\tcampName += \" \" + campOwner->getLastName();\n\t\tcampName += \"'s Camp\";\n\t\tterminal->setCustomObjectName(campName, true);\n\t}\n\n\tplayer->sendSystemMessage(\"@camp:assuming_ownership\"); \/\/You assume ownership of the camp.\n}\n[Fixed] players to receive system messages when entering\/exiting their own camp - mantis 2083\/*\n * CampSiteActiveAreaImplementation.cpp\n *\n * Created on: Jan 1, 2012\n * Author: Kyle\n *\/\n\n#include \"server\/zone\/objects\/area\/CampSiteActiveArea.h\"\n#include \"server\/zone\/objects\/area\/CampSiteObserver.h\"\n#include \"server\/zone\/objects\/structure\/StructureObject.h\"\n#include \"server\/zone\/managers\/player\/PlayerManager.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n#include \"server\/zone\/objects\/player\/PlayerObject.h\"\n#include \"server\/zone\/managers\/structure\/StructureManager.h\"\n#include \"server\/zone\/objects\/tangible\/terminal\/Terminal.h\"\n#include \"server\/zone\/Zone.h\"\n#include \"server\/zone\/objects\/area\/events\/CampAbandonTask.h\"\n#include \"server\/zone\/objects\/area\/events\/CampDespawnTask.h\"\n\nvoid CampSiteActiveAreaImplementation::initializeTransientMembers() {\n\tstartTasks();\n}\n\nvoid CampSiteActiveAreaImplementation::init(CampStructureTemplate* campData) {\n\tcampStructureData = campData;\n\tsetRadius(campStructureData->getRadius());\n\tstartTasks();\n}\n\nvoid CampSiteActiveAreaImplementation::startTasks() {\n\tLocker locker(&taskMutex);\n\n\tif(despawnTask == NULL) {\n\t\tdespawnTask = new CampDespawnTask(_this.get());\n\t} else {\n\t\tif(despawnTask->isScheduled())\n\t\t\tdespawnTask->cancel();\n\t}\n\n\n\tif(abandonTask == NULL) {\n\t\tabandonTask = new CampAbandonTask(_this.get());\n\t} else {\n\t\tif(abandonTask->isScheduled())\n\t\t\tabandonTask->cancel();\n\t}\n\n\tdespawnTask->schedule(CampSiteActiveArea::DESPAWNTIME);\n\tabandonTask->schedule(CampSiteActiveArea::ABANDONTIME);\n\n}\n\nvoid CampSiteActiveAreaImplementation::notifyEnter(SceneObject* object) {\n\tif (!object->isPlayerCreature())\n\t\treturn;\n\n\tif (camp == NULL || terminal == NULL)\n\t\treturn;\n\n\tCreatureObject* player = cast (object);\n\n\tif (player == NULL)\n\t\treturn;\n\n\tif (camp != NULL)\n\t\tcamp->addTemplateSkillMods(player);\n\n\tif (campObserver == NULL) {\n\t\tcampObserver = new CampSiteObserver(_this.get());\n\t\tcampObserver->deploy();\n\t}\n\n\tif(object == campOwner && !abandoned) {\n\n\t\tLocker locker(&taskMutex);\n\n\t\tif(abandonTask != NULL && abandonTask->isScheduled())\n\t\t\tabandonTask->cancel();\n\n\t\tobject->registerObserver(ObserverEventType::STARTCOMBAT, campObserver);\n\n\t}\n\n\tStringIdChatParameter stringID(\"camp\", \"prose_camp_enter\");\n\tstringID.setTO(terminal->getDisplayedName());\n\tplayer->sendSystemMessage(stringID);\n\n\tplayer->sendSystemMessage(\"@camp:sys_camp_heal\"); \/\/ While in the camp, medics and entertainers can heal your wounds.\n\n\n\tif (object->isPlayerCreature() && !visitors.contains(object->getObjectID()))\n\t\tvisitors.add(object->getObjectID());\n\n\n\tif (object->isPlayerCreature())\n\t\tobject->registerObserver(ObserverEventType::HEALINGPERFORMED, campObserver);\n}\n\nvoid CampSiteActiveAreaImplementation::notifyExit(SceneObject* object) {\n\tobject->dropObserver(ObserverEventType::HEALINGPERFORMED, campObserver);\n\n\tif (!object->isPlayerCreature())\n\t\treturn;\n\n\tif (camp == NULL || terminal == NULL)\n\t\treturn;\n\n\tCreatureObject* player = cast (object);\n\n\tif (player == NULL)\n\t\treturn;\n\n\tif (camp != NULL)\n\t\tcamp->removeTemplateSkillMods(player);\n\n\tStringIdChatParameter stringID(\"camp\", \"prose_camp_exit\");\n\tstringID.setTO(terminal->getDisplayedName());\n\tplayer->sendSystemMessage(stringID);\n\n\tif(abandoned || object != campOwner)\n\t\treturn;\n\n\tLocker locker(&taskMutex);\n\n\tif(!abandoned && abandonTask != NULL && !abandonTask->isScheduled()) {\n\t\ttry {\n\t\t\tabandonTask->schedule(CampSiteActiveArea::ABANDONTIME);\n\t\t} catch (Exception& e) {\n\n\t\t}\n\t}\n}\n\nint CampSiteActiveAreaImplementation::notifyHealEvent(int64 quantity) {\n\t\/\/ Increase XP Pool for heals\n\tcurrentXp += (campStructureData->getExperience() \/ 180);\n\treturn 1;\n}\n\nint CampSiteActiveAreaImplementation::notifyCombatEvent() {\n\tabandonCamp();\n\n\tLocker locker(&taskMutex);\n\n\tif(abandonTask != NULL)\n\t\tif(abandonTask->isScheduled())\n\t\t\tabandonTask->cancel();\n\n\tif(campOwner != NULL)\n\t\tcampOwner->sendSystemMessage(\"@camp:sys_abandoned_camp\"); \/\/ Your camp has been abandoned.\n\n\treturn 1;\n}\n\nvoid CampSiteActiveAreaImplementation::abandonCamp() {\n\tabandoned = true;\n\n\tcurrentXp = 0;\n\n\tLocker locker(&taskMutex);\n\n\tif(despawnTask != NULL && despawnTask->isScheduled()) {\n\t\tdespawnTask->cancel();\n\t\tint newTime = (CampSiteActiveArea::DESPAWNTIME \/ 6);\n\t\tint maxTime = CampSiteActiveArea::DESPAWNTIME - ((System::getTime() - timeCreated) * 1000);\n\n\t\tdespawnTask->schedule(newTime < maxTime ? newTime : maxTime);\n\t}\n\n\tif(terminal != NULL)\n\t\tterminal->setCustomObjectName(\"Abandoned Camp\", true);\n\n\tif(campOwner != NULL) {\n\t\tcampOwner->dropObserver(ObserverEventType::STARTCOMBAT, campObserver);\n\t\tcampOwner->sendSystemMessage(\"@camp:sys_abandoned_camp\"); \/\/ Your camp has been abandoned.\n\t}\n}\n\nbool CampSiteActiveAreaImplementation::despawnCamp() {\n\tLocker locker(_this.get());\n\n\tif(!abandoned && campOwner != NULL && campOwner->getZoneServer() != NULL) {\n\t\t\/\/\/ Get Player Manager\n\t\tPlayerManager* playerManager = campOwner->getZoneServer()->getPlayerManager();\n\t\tif (playerManager == NULL) {\n\t\t\terror(\"playerManager is null\");\n\t\t\treturn false;\n\t\t}\n\n\t\tfloat durationUsed = ((float)(System::getTime() - timeCreated)) \/ (campStructureData->getDuration() \/ 4);\n\t\tif (durationUsed > 1)\n\t\t\tdurationUsed = 1;\n\n\t\tint amount = 0;\n\t\tint campXp = campStructureData->getExperience();\n\t\tamount = (int)(campXp * durationUsed);\n\n\t\tamount += (int)((visitors.size() -1) * (campXp \/ 30) * durationUsed);\n\t\tamount += (int)(currentXp * durationUsed);\n\n\t\tplayerManager->awardExperience(campOwner, \"camp\", amount, true);\n\t}\n\n\tLocker tlocker(&taskMutex);\n\n\tif(despawnTask != NULL ) {\n\t\tif(despawnTask->isScheduled())\n\t\t\tdespawnTask->cancel();\n\t\tdespawnTask = NULL;\n\t}\n\n\n\tif(abandonTask != NULL) {\n\t\tif(abandonTask->isScheduled())\n\t\t\tabandonTask->cancel();\n\t\tabandonTask = NULL;\n\t}\n\n\ttlocker.release();\n\n\tif(campOwner != NULL)\n\t\tcampOwner->dropObserver(ObserverEventType::STARTCOMBAT, campObserver);\n\n\tif (camp != NULL) {\n\t\tif(camp->getZone() == NULL)\n\t\t\treturn false;\n\n\t\tStructureManager::instance()->destroyStructure(camp);\n\t}\n\n\tdestroyObjectFromWorld(true);\n\tdestroyObjectFromDatabase(true);\n\n\n\treturn true;\n}\n\nvoid CampSiteActiveAreaImplementation::assumeOwnership(CreatureObject* player) {\n\tif (camp == NULL || player == NULL)\n\t\treturn;\n\n\tif (player->getSkillMod(\"camp\") < campStructureData->getSkillRequired()) {\n\t\tplayer->sendSystemMessage(\"@camp:error_too_big\"); \/\/ You cannot assume ownership of this camp. You lack the skill to maintain a camp of this size.\n\t\treturn;\n\t}\n\n\tPlayerObject* playerGhost = player->getPlayerObject();\n\n\tif (playerGhost == NULL)\n\t\treturn;\n\n\tfor (int i = 0; i < playerGhost->getTotalOwnedStructureCount(); ++i) {\n\t\tuint64 oid = playerGhost->getOwnedStructure(i);\n\n\t\tManagedReference structure = playerGhost->getZoneServer()->getObject(oid).castTo();\n\n\t\tif (structure->isCampStructure()) {\n\t\t\tplayer->sendSystemMessage(\"@camp:sys_already_camping\"); \/\/ But you already have a camp established elsewhere!\n\t\t\treturn;\n\t\t}\n\t}\n\n\tPlayerObject* ownerGhost = campOwner->getPlayerObject();\n\n\tif (ownerGhost != NULL) {\n\t\townerGhost->removeOwnedStructure(camp);\n\t}\n\n\tsetOwner(player);\n\n\tabandoned = false;\n\tcurrentXp = 0;\n\tvisitors.removeAll();\n\n\tReference >*> closeObjects = new SortedVector >();\n\tzone->getInRangeObjects(camp->getWorldPositionX(), camp->getWorldPositionY(), campStructureData->getRadius(), closeObjects, true);\n\n\tfor (int i = 0; i < closeObjects->size(); ++i) {\n\t\tSceneObject* scno = cast(closeObjects->get(i).get());\n\t\tif (scno->isPlayerCreature())\n\t\t\tvisitors.add(scno->getObjectID());\n\t}\n\n\tplayerGhost->addOwnedStructure(camp);\n\n\tcampOwner->registerObserver(ObserverEventType::STARTCOMBAT, campObserver);\n\n\tLocker locker(&taskMutex);\n\n\tif(abandonTask != NULL && abandonTask->isScheduled())\n\t\tabandonTask->cancel();\n\n\tif(despawnTask != NULL && despawnTask->isScheduled())\n\t\tdespawnTask->cancel();\n\n\ttimeCreated = System::getTime();\n\tdespawnTask->schedule(CampSiteActiveArea::DESPAWNTIME);\n\n\tif(terminal != NULL) {\n\t\tString campName = campOwner->getFirstName();\n\t\tif(!campOwner->getLastName().isEmpty())\n\t\t\tcampName += \" \" + campOwner->getLastName();\n\t\tcampName += \"'s Camp\";\n\t\tterminal->setCustomObjectName(campName, true);\n\t}\n\n\tplayer->sendSystemMessage(\"@camp:assuming_ownership\"); \/\/You assume ownership of the camp.\n}\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \n#include \n#include \n#include \n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n#include \"libtorrent\/extensions\/metadata_transfer.hpp\"\n#include \"libtorrent\/extensions\/ut_metadata.hpp\"\n#include \"libtorrent\/extensions\/lt_trackers.hpp\"\n\nusing boost::filesystem::remove_all;\nusing boost::tuples::ignore;\n\nvoid test_main()\n{\n\tusing namespace libtorrent;\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48130, 49000), \"0.0.0.0\", 0);\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49130, 50000), \"0.0.0.0\", 0);\n\tses1.add_extension(create_lt_trackers_plugin);\n\tses2.add_extension(create_lt_trackers_plugin);\n\n\tadd_torrent_params atp;\n\tatp.info_hash = sha1_hash(\"12345678901234567890\");\n\tatp.save_path = \".\/\";\n\ttorrent_handle tor1 = ses1.add_torrent(atp);\n\tatp.tracker_url = \"http:\/\/test.non-existent.com\/announce\";\n\ttorrent_handle tor2 = ses2.add_torrent(atp);\n\ttor2.connect_peer(tcp::endpoint(address_v4::from_string(\"127.0.0.1\"), ses1.listen_port()));\n\n\tfor (int i = 0; i < 130; ++i)\n\t{\n\t\t\/\/ make sure this function can be called on\n\t\t\/\/ torrents without metadata\n\t\tprint_alerts(ses1, \"ses1\", false, true);\n\t\tprint_alerts(ses2, \"ses2\", false, true);\n\n\t\tif (tor1.trackers().size() == 1) break;\n\t\ttest_sleep(1000);\n\t}\n\n\tTEST_CHECK(tor1.trackers().size() == 1);\n}\n\nfixed test_trackers_extension\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \n#include \n#include \n#include \n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n#include \"libtorrent\/extensions\/metadata_transfer.hpp\"\n#include \"libtorrent\/extensions\/ut_metadata.hpp\"\n#include \"libtorrent\/extensions\/lt_trackers.hpp\"\n\nusing boost::filesystem::remove_all;\nusing boost::tuples::ignore;\n\nint test_main()\n{\n\tusing namespace libtorrent;\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48130, 49000), \"0.0.0.0\", 0);\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49130, 50000), \"0.0.0.0\", 0);\n\tses1.add_extension(create_lt_trackers_plugin);\n\tses2.add_extension(create_lt_trackers_plugin);\n\n\tadd_torrent_params atp;\n\tatp.info_hash = sha1_hash(\"12345678901234567890\");\n\tatp.save_path = \".\/\";\n\ttorrent_handle tor1 = ses1.add_torrent(atp);\n\tatp.tracker_url = \"http:\/\/test.non-existent.com\/announce\";\n\ttorrent_handle tor2 = ses2.add_torrent(atp);\n\ttor2.connect_peer(tcp::endpoint(address_v4::from_string(\"127.0.0.1\"), ses1.listen_port()));\n\n\tfor (int i = 0; i < 130; ++i)\n\t{\n\t\t\/\/ make sure this function can be called on\n\t\t\/\/ torrents without metadata\n\t\tprint_alerts(ses1, \"ses1\", false, true);\n\t\tprint_alerts(ses2, \"ses2\", false, true);\n\n\t\tif (tor1.trackers().size() == 1) break;\n\t\ttest_sleep(1000);\n\t}\n\n\tTEST_CHECK(tor1.trackers().size() == 1);\n}\n\n<|endoftext|>"} {"text":"\/\/===- Expressions.cpp - Expression Analysis Utilities ----------------------=\/\/\n\/\/\n\/\/ This file defines a package of expression analysis utilties:\n\/\/\n\/\/ ClassifyExpression: Analyze an expression to determine the complexity of the\n\/\/ expression, and which other variables it depends on. \n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/Expressions.h\"\n#include \"llvm\/Optimizations\/ConstantHandling.h\"\n#include \"llvm\/ConstantPool.h\"\n#include \"llvm\/Method.h\"\n#include \"llvm\/BasicBlock.h\"\n\nusing namespace opt; \/\/ Get all the constant handling stuff\nusing namespace analysis;\n\nclass DefVal {\n const ConstPoolInt * const Val;\n ConstantPool &CP;\n const Type * const Ty;\nprotected:\n inline DefVal(const ConstPoolInt *val, ConstantPool &cp, const Type *ty)\n : Val(val), CP(cp), Ty(ty) {}\npublic:\n inline const Type *getType() const { return Ty; }\n inline ConstantPool &getCP() const { return CP; }\n inline const ConstPoolInt *getVal() const { return Val; }\n inline operator const ConstPoolInt * () const { return Val; }\n inline const ConstPoolInt *operator->() const { return Val; }\n};\n\nstruct DefZero : public DefVal {\n inline DefZero(const ConstPoolInt *val, ConstantPool &cp, const Type *ty)\n : DefVal(val, cp, ty) {}\n inline DefZero(const ConstPoolInt *val)\n : DefVal(val, (ConstantPool&)val->getParent()->getConstantPool(),\n\t val->getType()) {}\n};\n\nstruct DefOne : public DefVal {\n inline DefOne(const ConstPoolInt *val, ConstantPool &cp, const Type *ty)\n : DefVal(val, cp, ty) {}\n};\n\n\n\/\/ getIntegralConstant - Wrapper around the ConstPoolInt member of the same\n\/\/ name. This method first checks to see if the desired constant is already in\n\/\/ the constant pool. If it is, it is quickly recycled, otherwise a new one\n\/\/ is allocated and added to the constant pool.\n\/\/\nstatic ConstPoolInt *getIntegralConstant(ConstantPool &CP, unsigned char V,\n\t\t\t\t\t const Type *Ty) {\n \/\/ FIXME: Lookup prexisting constant in table!\n\n ConstPoolInt *CPI = ConstPoolInt::get(Ty, V);\n CP.insert(CPI);\n return CPI;\n}\n\nstatic ConstPoolInt *getUnsignedConstant(ConstantPool &CP, uint64_t V,\n\t\t\t\t\t const Type *Ty) {\n \/\/ FIXME: Lookup prexisting constant in table!\n\n ConstPoolInt *CPI;\n CPI = Ty->isSigned() ? new ConstPoolSInt(Ty, V) : new ConstPoolUInt(Ty, V);\n CP.insert(CPI);\n return CPI;\n}\n\n\/\/ Add - Helper function to make later code simpler. Basically it just adds\n\/\/ the two constants together, inserts the result into the constant pool, and\n\/\/ returns it. Of course life is not simple, and this is no exception. Factors\n\/\/ that complicate matters:\n\/\/ 1. Either argument may be null. If this is the case, the null argument is\n\/\/ treated as either 0 (if DefOne = false) or 1 (if DefOne = true)\n\/\/ 2. Types get in the way. We want to do arithmetic operations without\n\/\/ regard for the underlying types. It is assumed that the constants are\n\/\/ integral constants. The new value takes the type of the left argument.\n\/\/ 3. If DefOne is true, a null return value indicates a value of 1, if DefOne\n\/\/ is false, a null return value indicates a value of 0.\n\/\/\nstatic const ConstPoolInt *Add(ConstantPool &CP, const ConstPoolInt *Arg1,\n\t\t\t const ConstPoolInt *Arg2, bool DefOne) {\n assert(Arg1 && Arg2 && \"No null arguments should exist now!\");\n assert(Arg1->getType() == Arg2->getType() && \"Types must be compatible!\");\n\n \/\/ Actually perform the computation now!\n ConstPoolVal *Result = *Arg1 + *Arg2;\n assert(Result && Result->getType() == Arg1->getType() &&\n\t \"Couldn't perform addition!\");\n ConstPoolInt *ResultI = (ConstPoolInt*)Result;\n\n \/\/ Check to see if the result is one of the special cases that we want to\n \/\/ recognize...\n if (ResultI->equalsInt(DefOne ? 1 : 0)) {\n \/\/ Yes it is, simply delete the constant and return null.\n delete ResultI;\n return 0;\n }\n\n CP.insert(ResultI);\n return ResultI;\n}\n\ninline const ConstPoolInt *operator+(const DefZero &L, const DefZero &R) {\n if (L == 0) return R;\n if (R == 0) return L;\n return Add(L.getCP(), L, R, false);\n}\n\ninline const ConstPoolInt *operator+(const DefOne &L, const DefOne &R) {\n if (L == 0) {\n if (R == 0)\n return getIntegralConstant(L.getCP(), 2, L.getType());\n else\n return Add(L.getCP(), getIntegralConstant(L.getCP(), 1, L.getType()),\n\t\t R, true);\n } else if (R == 0) {\n return Add(L.getCP(), L,\n\t getIntegralConstant(L.getCP(), 1, L.getType()), true);\n }\n return Add(L.getCP(), L, R, true);\n}\n\n\n\/\/ Mul - Helper function to make later code simpler. Basically it just\n\/\/ multiplies the two constants together, inserts the result into the constant\n\/\/ pool, and returns it. Of course life is not simple, and this is no\n\/\/ exception. Factors that complicate matters:\n\/\/ 1. Either argument may be null. If this is the case, the null argument is\n\/\/ treated as either 0 (if DefOne = false) or 1 (if DefOne = true)\n\/\/ 2. Types get in the way. We want to do arithmetic operations without\n\/\/ regard for the underlying types. It is assumed that the constants are\n\/\/ integral constants.\n\/\/ 3. If DefOne is true, a null return value indicates a value of 1, if DefOne\n\/\/ is false, a null return value indicates a value of 0.\n\/\/\ninline const ConstPoolInt *Mul(ConstantPool &CP, const ConstPoolInt *Arg1, \n\t\t\t const ConstPoolInt *Arg2, bool DefOne = false) {\n assert(Arg1 && Arg2 && \"No null arguments should exist now!\");\n assert(Arg1->getType() == Arg2->getType() && \"Types must be compatible!\");\n\n \/\/ Actually perform the computation now!\n ConstPoolVal *Result = *Arg1 * *Arg2;\n assert(Result && Result->getType() == Arg1->getType() && \n\t \"Couldn't perform mult!\");\n ConstPoolInt *ResultI = (ConstPoolInt*)Result;\n\n \/\/ Check to see if the result is one of the special cases that we want to\n \/\/ recognize...\n if (ResultI->equalsInt(DefOne ? 1 : 0)) {\n \/\/ Yes it is, simply delete the constant and return null.\n delete ResultI;\n return 0;\n }\n\n CP.insert(ResultI);\n return ResultI;\n}\n\ninline const ConstPoolInt *operator*(const DefZero &L, const DefZero &R) {\n if (L == 0 || R == 0) return 0;\n return Mul(L.getCP(), L, R, false);\n}\ninline const ConstPoolInt *operator*(const DefOne &L, const DefZero &R) {\n if (R == 0) return getIntegralConstant(L.getCP(), 0, L.getType());\n if (L == 0) return R->equalsInt(1) ? 0 : R.getVal();\n return Mul(L.getCP(), L, R, false);\n}\ninline const ConstPoolInt *operator*(const DefZero &L, const DefOne &R) {\n return R*L;\n}\n\n\n\n\/\/ ClassifyExpression: Analyze an expression to determine the complexity of the\n\/\/ expression, and which other values it depends on. \n\/\/\n\/\/ Note that this analysis cannot get into infinite loops because it treats PHI\n\/\/ nodes as being an unknown linear expression.\n\/\/\nExprType analysis::ClassifyExpression(Value *Expr) {\n assert(Expr != 0 && \"Can't classify a null expression!\");\n switch (Expr->getValueType()) {\n case Value::InstructionVal: break; \/\/ Instruction... hmmm... investigate.\n case Value::TypeVal: case Value::BasicBlockVal:\n case Value::MethodVal: case Value::ModuleVal:\n assert(0 && \"Unexpected expression type to classify!\");\n case Value::MethodArgumentVal: \/\/ Method arg: nothing known, return var\n return Expr;\n case Value::ConstantVal: \/\/ Constant value, just return constant\n ConstPoolVal *CPV = Expr->castConstantAsserting();\n if (CPV->getType()->isIntegral()) { \/\/ It's an integral constant!\n ConstPoolInt *CPI = (ConstPoolInt*)Expr;\n return ExprType(CPI->equalsInt(0) ? 0 : (ConstPoolInt*)Expr);\n }\n return Expr;\n }\n \n Instruction *I = Expr->castInstructionAsserting();\n ConstantPool &CP = I->getParent()->getParent()->getConstantPool();\n const Type *Ty = I->getType();\n\n switch (I->getOpcode()) { \/\/ Handle each instruction type seperately\n case Instruction::Add: {\n ExprType Left (ClassifyExpression(I->getOperand(0)));\n ExprType Right(ClassifyExpression(I->getOperand(1)));\n if (Left.ExprTy > Right.ExprTy)\n swap(Left, Right); \/\/ Make left be simpler than right\n\n switch (Left.ExprTy) {\n case ExprType::Constant:\n return ExprType(Right.Scale, Right.Var,\n\t\t DefZero(Right.Offset,CP,Ty) + DefZero(Left.Offset, CP,Ty));\n case ExprType::Linear: \/\/ RHS side must be linear or scaled\n case ExprType::ScaledLinear: \/\/ RHS must be scaled\n if (Left.Var != Right.Var) \/\/ Are they the same variables?\n\treturn ExprType(I); \/\/ if not, we don't know anything!\n\n return ExprType(DefOne(Left.Scale ,CP,Ty) + DefOne(Right.Scale , CP,Ty),\n\t\t Left.Var,\n\t DefZero(Left.Offset,CP,Ty) + DefZero(Right.Offset, CP,Ty));\n }\n } \/\/ end case Instruction::Add\n\n case Instruction::Shl: { \n ExprType Right(ClassifyExpression(I->getOperand(1)));\n if (Right.ExprTy != ExprType::Constant) break;\n ExprType Left(ClassifyExpression(I->getOperand(0)));\n if (Right.Offset == 0) return Left; \/\/ shl x, 0 = x\n assert(Right.Offset->getType() == Type::UByteTy &&\n\t \"Shift amount must always be a unsigned byte!\");\n uint64_t ShiftAmount = ((ConstPoolUInt*)Right.Offset)->getValue();\n ConstPoolInt *Multiplier = getUnsignedConstant(CP, 1ULL << ShiftAmount, Ty);\n \n return ExprType(DefOne(Left.Scale, CP, Ty) * Multiplier,\n\t\t Left.Var,\n\t\t DefZero(Left.Offset, CP, Ty) * Multiplier);\n } \/\/ end case Instruction::Shl\n\n case Instruction::Mul: {\n ExprType Left (ClassifyExpression(I->getOperand(0)));\n ExprType Right(ClassifyExpression(I->getOperand(1)));\n if (Left.ExprTy > Right.ExprTy)\n swap(Left, Right); \/\/ Make left be simpler than right\n\n if (Left.ExprTy != ExprType::Constant) \/\/ RHS must be > constant\n return I; \/\/ Quadratic eqn! :(\n\n const ConstPoolInt *Offs = Left.Offset;\n if (Offs == 0) return ExprType();\n return ExprType(DefOne(Right.Scale, CP, Ty) * Offs,\n\t\t Right.Var,\n\t\t DefZero(Right.Offset, CP, Ty) * Offs);\n } \/\/ end case Instruction::Mul\n\n case Instruction::Cast: {\n ExprType Src(ClassifyExpression(I->getOperand(0)));\n if (Src.ExprTy != ExprType::Constant)\n return I;\n const ConstPoolInt *Offs = Src.Offset;\n if (Offs == 0) return ExprType();\n\n if (I->getType()->isPointerType())\n return Offs; \/\/ Pointer types do not lose precision\n\n assert(I->getType()->isIntegral() && \"Can only handle integral types!\");\n\n const ConstPoolVal *CPV = ConstRules::get(*Offs)->castTo(Offs, I->getType());\n if (!CPV) return I;\n assert(CPV->getType()->isIntegral() && \"Must have an integral type!\");\n return (ConstPoolInt*)CPV;\n } \/\/ end case Instruction::Cast\n \/\/ TODO: Handle SUB (at least!)\n\n } \/\/ end switch\n\n \/\/ Otherwise, I don't know anything about this value!\n return I;\n}\nFix a bug when compiling 'shl ubyte * %var, ubyte 2'\/\/===- Expressions.cpp - Expression Analysis Utilities ----------------------=\/\/\n\/\/\n\/\/ This file defines a package of expression analysis utilties:\n\/\/\n\/\/ ClassifyExpression: Analyze an expression to determine the complexity of the\n\/\/ expression, and which other variables it depends on. \n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/Expressions.h\"\n#include \"llvm\/Optimizations\/ConstantHandling.h\"\n#include \"llvm\/ConstantPool.h\"\n#include \"llvm\/Method.h\"\n#include \"llvm\/BasicBlock.h\"\n\nusing namespace opt; \/\/ Get all the constant handling stuff\nusing namespace analysis;\n\nclass DefVal {\n const ConstPoolInt * const Val;\n ConstantPool &CP;\n const Type * const Ty;\nprotected:\n inline DefVal(const ConstPoolInt *val, ConstantPool &cp, const Type *ty)\n : Val(val), CP(cp), Ty(ty) {}\npublic:\n inline const Type *getType() const { return Ty; }\n inline ConstantPool &getCP() const { return CP; }\n inline const ConstPoolInt *getVal() const { return Val; }\n inline operator const ConstPoolInt * () const { return Val; }\n inline const ConstPoolInt *operator->() const { return Val; }\n};\n\nstruct DefZero : public DefVal {\n inline DefZero(const ConstPoolInt *val, ConstantPool &cp, const Type *ty)\n : DefVal(val, cp, ty) {}\n inline DefZero(const ConstPoolInt *val)\n : DefVal(val, (ConstantPool&)val->getParent()->getConstantPool(),\n\t val->getType()) {}\n};\n\nstruct DefOne : public DefVal {\n inline DefOne(const ConstPoolInt *val, ConstantPool &cp, const Type *ty)\n : DefVal(val, cp, ty) {}\n};\n\n\n\/\/ getIntegralConstant - Wrapper around the ConstPoolInt member of the same\n\/\/ name. This method first checks to see if the desired constant is already in\n\/\/ the constant pool. If it is, it is quickly recycled, otherwise a new one\n\/\/ is allocated and added to the constant pool.\n\/\/\nstatic ConstPoolInt *getIntegralConstant(ConstantPool &CP, unsigned char V,\n\t\t\t\t\t const Type *Ty) {\n \/\/ FIXME: Lookup prexisting constant in table!\n\n ConstPoolInt *CPI = ConstPoolInt::get(Ty, V);\n CP.insert(CPI);\n return CPI;\n}\n\nstatic ConstPoolInt *getUnsignedConstant(ConstantPool &CP, uint64_t V,\n\t\t\t\t\t const Type *Ty) {\n \/\/ FIXME: Lookup prexisting constant in table!\n if (Ty->isPointerType()) Ty = Type::ULongTy;\n\n ConstPoolInt *CPI;\n CPI = Ty->isSigned() ? new ConstPoolSInt(Ty, V) : new ConstPoolUInt(Ty, V);\n CP.insert(CPI);\n return CPI;\n}\n\n\/\/ Add - Helper function to make later code simpler. Basically it just adds\n\/\/ the two constants together, inserts the result into the constant pool, and\n\/\/ returns it. Of course life is not simple, and this is no exception. Factors\n\/\/ that complicate matters:\n\/\/ 1. Either argument may be null. If this is the case, the null argument is\n\/\/ treated as either 0 (if DefOne = false) or 1 (if DefOne = true)\n\/\/ 2. Types get in the way. We want to do arithmetic operations without\n\/\/ regard for the underlying types. It is assumed that the constants are\n\/\/ integral constants. The new value takes the type of the left argument.\n\/\/ 3. If DefOne is true, a null return value indicates a value of 1, if DefOne\n\/\/ is false, a null return value indicates a value of 0.\n\/\/\nstatic const ConstPoolInt *Add(ConstantPool &CP, const ConstPoolInt *Arg1,\n\t\t\t const ConstPoolInt *Arg2, bool DefOne) {\n assert(Arg1 && Arg2 && \"No null arguments should exist now!\");\n assert(Arg1->getType() == Arg2->getType() && \"Types must be compatible!\");\n\n \/\/ Actually perform the computation now!\n ConstPoolVal *Result = *Arg1 + *Arg2;\n assert(Result && Result->getType() == Arg1->getType() &&\n\t \"Couldn't perform addition!\");\n ConstPoolInt *ResultI = (ConstPoolInt*)Result;\n\n \/\/ Check to see if the result is one of the special cases that we want to\n \/\/ recognize...\n if (ResultI->equalsInt(DefOne ? 1 : 0)) {\n \/\/ Yes it is, simply delete the constant and return null.\n delete ResultI;\n return 0;\n }\n\n CP.insert(ResultI);\n return ResultI;\n}\n\ninline const ConstPoolInt *operator+(const DefZero &L, const DefZero &R) {\n if (L == 0) return R;\n if (R == 0) return L;\n return Add(L.getCP(), L, R, false);\n}\n\ninline const ConstPoolInt *operator+(const DefOne &L, const DefOne &R) {\n if (L == 0) {\n if (R == 0)\n return getIntegralConstant(L.getCP(), 2, L.getType());\n else\n return Add(L.getCP(), getIntegralConstant(L.getCP(), 1, L.getType()),\n\t\t R, true);\n } else if (R == 0) {\n return Add(L.getCP(), L,\n\t getIntegralConstant(L.getCP(), 1, L.getType()), true);\n }\n return Add(L.getCP(), L, R, true);\n}\n\n\n\/\/ Mul - Helper function to make later code simpler. Basically it just\n\/\/ multiplies the two constants together, inserts the result into the constant\n\/\/ pool, and returns it. Of course life is not simple, and this is no\n\/\/ exception. Factors that complicate matters:\n\/\/ 1. Either argument may be null. If this is the case, the null argument is\n\/\/ treated as either 0 (if DefOne = false) or 1 (if DefOne = true)\n\/\/ 2. Types get in the way. We want to do arithmetic operations without\n\/\/ regard for the underlying types. It is assumed that the constants are\n\/\/ integral constants.\n\/\/ 3. If DefOne is true, a null return value indicates a value of 1, if DefOne\n\/\/ is false, a null return value indicates a value of 0.\n\/\/\ninline const ConstPoolInt *Mul(ConstantPool &CP, const ConstPoolInt *Arg1, \n\t\t\t const ConstPoolInt *Arg2, bool DefOne = false) {\n assert(Arg1 && Arg2 && \"No null arguments should exist now!\");\n assert(Arg1->getType() == Arg2->getType() && \"Types must be compatible!\");\n\n \/\/ Actually perform the computation now!\n ConstPoolVal *Result = *Arg1 * *Arg2;\n assert(Result && Result->getType() == Arg1->getType() && \n\t \"Couldn't perform mult!\");\n ConstPoolInt *ResultI = (ConstPoolInt*)Result;\n\n \/\/ Check to see if the result is one of the special cases that we want to\n \/\/ recognize...\n if (ResultI->equalsInt(DefOne ? 1 : 0)) {\n \/\/ Yes it is, simply delete the constant and return null.\n delete ResultI;\n return 0;\n }\n\n CP.insert(ResultI);\n return ResultI;\n}\n\ninline const ConstPoolInt *operator*(const DefZero &L, const DefZero &R) {\n if (L == 0 || R == 0) return 0;\n return Mul(L.getCP(), L, R, false);\n}\ninline const ConstPoolInt *operator*(const DefOne &L, const DefZero &R) {\n if (R == 0) return getIntegralConstant(L.getCP(), 0, L.getType());\n if (L == 0) return R->equalsInt(1) ? 0 : R.getVal();\n return Mul(L.getCP(), L, R, false);\n}\ninline const ConstPoolInt *operator*(const DefZero &L, const DefOne &R) {\n return R*L;\n}\n\n\n\n\/\/ ClassifyExpression: Analyze an expression to determine the complexity of the\n\/\/ expression, and which other values it depends on. \n\/\/\n\/\/ Note that this analysis cannot get into infinite loops because it treats PHI\n\/\/ nodes as being an unknown linear expression.\n\/\/\nExprType analysis::ClassifyExpression(Value *Expr) {\n assert(Expr != 0 && \"Can't classify a null expression!\");\n switch (Expr->getValueType()) {\n case Value::InstructionVal: break; \/\/ Instruction... hmmm... investigate.\n case Value::TypeVal: case Value::BasicBlockVal:\n case Value::MethodVal: case Value::ModuleVal:\n assert(0 && \"Unexpected expression type to classify!\");\n case Value::MethodArgumentVal: \/\/ Method arg: nothing known, return var\n return Expr;\n case Value::ConstantVal: \/\/ Constant value, just return constant\n ConstPoolVal *CPV = Expr->castConstantAsserting();\n if (CPV->getType()->isIntegral()) { \/\/ It's an integral constant!\n ConstPoolInt *CPI = (ConstPoolInt*)Expr;\n return ExprType(CPI->equalsInt(0) ? 0 : (ConstPoolInt*)Expr);\n }\n return Expr;\n }\n \n Instruction *I = Expr->castInstructionAsserting();\n ConstantPool &CP = I->getParent()->getParent()->getConstantPool();\n const Type *Ty = I->getType();\n\n switch (I->getOpcode()) { \/\/ Handle each instruction type seperately\n case Instruction::Add: {\n ExprType Left (ClassifyExpression(I->getOperand(0)));\n ExprType Right(ClassifyExpression(I->getOperand(1)));\n if (Left.ExprTy > Right.ExprTy)\n swap(Left, Right); \/\/ Make left be simpler than right\n\n switch (Left.ExprTy) {\n case ExprType::Constant:\n return ExprType(Right.Scale, Right.Var,\n\t\t DefZero(Right.Offset,CP,Ty) + DefZero(Left.Offset, CP,Ty));\n case ExprType::Linear: \/\/ RHS side must be linear or scaled\n case ExprType::ScaledLinear: \/\/ RHS must be scaled\n if (Left.Var != Right.Var) \/\/ Are they the same variables?\n\treturn ExprType(I); \/\/ if not, we don't know anything!\n\n return ExprType(DefOne(Left.Scale ,CP,Ty) + DefOne(Right.Scale , CP,Ty),\n\t\t Left.Var,\n\t DefZero(Left.Offset,CP,Ty) + DefZero(Right.Offset, CP,Ty));\n }\n } \/\/ end case Instruction::Add\n\n case Instruction::Shl: { \n ExprType Right(ClassifyExpression(I->getOperand(1)));\n if (Right.ExprTy != ExprType::Constant) break;\n ExprType Left(ClassifyExpression(I->getOperand(0)));\n if (Right.Offset == 0) return Left; \/\/ shl x, 0 = x\n assert(Right.Offset->getType() == Type::UByteTy &&\n\t \"Shift amount must always be a unsigned byte!\");\n uint64_t ShiftAmount = ((ConstPoolUInt*)Right.Offset)->getValue();\n ConstPoolInt *Multiplier = getUnsignedConstant(CP, 1ULL << ShiftAmount, Ty);\n \n return ExprType(DefOne(Left.Scale, CP, Ty) * Multiplier,\n\t\t Left.Var,\n\t\t DefZero(Left.Offset, CP, Ty) * Multiplier);\n } \/\/ end case Instruction::Shl\n\n case Instruction::Mul: {\n ExprType Left (ClassifyExpression(I->getOperand(0)));\n ExprType Right(ClassifyExpression(I->getOperand(1)));\n if (Left.ExprTy > Right.ExprTy)\n swap(Left, Right); \/\/ Make left be simpler than right\n\n if (Left.ExprTy != ExprType::Constant) \/\/ RHS must be > constant\n return I; \/\/ Quadratic eqn! :(\n\n const ConstPoolInt *Offs = Left.Offset;\n if (Offs == 0) return ExprType();\n return ExprType(DefOne(Right.Scale, CP, Ty) * Offs,\n\t\t Right.Var,\n\t\t DefZero(Right.Offset, CP, Ty) * Offs);\n } \/\/ end case Instruction::Mul\n\n case Instruction::Cast: {\n ExprType Src(ClassifyExpression(I->getOperand(0)));\n if (Src.ExprTy != ExprType::Constant)\n return I;\n const ConstPoolInt *Offs = Src.Offset;\n if (Offs == 0) return ExprType();\n\n if (I->getType()->isPointerType())\n return Offs; \/\/ Pointer types do not lose precision\n\n assert(I->getType()->isIntegral() && \"Can only handle integral types!\");\n\n const ConstPoolVal *CPV = ConstRules::get(*Offs)->castTo(Offs, I->getType());\n if (!CPV) return I;\n assert(CPV->getType()->isIntegral() && \"Must have an integral type!\");\n return (ConstPoolInt*)CPV;\n } \/\/ end case Instruction::Cast\n \/\/ TODO: Handle SUB, SHR?\n\n } \/\/ end switch\n\n \/\/ Otherwise, I don't know anything about this value!\n return I;\n}\n<|endoftext|>"} {"text":"\/*\n * fetcher.cpp\n *\n * Created on: Nov 21, 2012\n * Author: partio\n *\/\n\n#include \"fetcher.h\"\n#include \"plugin_factory.h\"\n#include \"logger_factory.h\"\n#include \n#include \n#include \n#include \"util.h\"\n\n#define HIMAN_AUXILIARY_INCLUDE\n\n#include \"grib.h\"\n#include \"neons.h\"\n#include \"param.h\"\n#include \"cache.h\"\n#include \"querydata.h\"\n\n#undef HIMAN_AUXILIARY_INCLUDE\n\nusing namespace himan::plugin;\nusing namespace std;\n\nconst unsigned int sleepSeconds = 10;\n\nfetcher::fetcher()\n{\n itsLogger = std::unique_ptr (logger_factory::Instance()->GetLog(\"fetcher\"));\n}\n\nshared_ptr fetcher::Fetch(shared_ptr config,\n const forecast_time& requestedTime,\n const level& requestedLevel,\n const param& requestedParam)\n{\n\n const search_options opts { requestedTime, requestedParam, requestedLevel, config } ;\n\n vector> theInfos;\n\n for (unsigned int waitedSeconds = 0; waitedSeconds < config->FileWaitTimeout() * 60; waitedSeconds += sleepSeconds)\n {\n \t\/\/ 1. Fetch data from cache\n\n \t\/\/ theInfos = FromCache()\n\n \t\/*\n \t * 2. Fetch data from auxiliary files specified at command line\n \t *\n \t * Even if file_wait_timeout is specified, auxiliary files is searched\n \t * only once.\n \t *\/\n\n \tif (config->AuxiliaryFiles().size() && waitedSeconds == 0)\n \t{\n \t\ttheInfos = FromFile(config->AuxiliaryFiles(), opts, true);\n\n \t\tif (theInfos.size())\n \t\t{\n \t\t\titsLogger->Debug(\"Data found from auxiliary file(s)\");\n \t\t\tbreak;\n \t\t}\n \t\telse\n \t\t{\n \t\t\titsLogger->Warning(\"Data not found from auxiliary file(s)\");\n \t\t}\n \t}\n\n\t\t\/\/ 3. Fetch data from Neons\n\n\t\tvector files;\n\n\t\tif (config->ReadDataFromDatabase())\n\t\t{\n\t\t\tshared_ptr n = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"neons\"));\n\n\t\t\tfiles = n->Files(opts);\n\n\t\t\tif (!files.empty())\n\t\t\t{\n\t\t\t\ttheInfos = FromFile(files, opts, true);\n\n\t\t\t\tbreak;\n\t\t\t}\n\t \telse if (config->ReadDataFromDatabase())\n\t \t{\n\t \t\titsLogger->Debug(\"Could not find file(s) from Neons matching requested parameters\");\n\t \t}\n\t\t}\n\n\t\tif (config->FileWaitTimeout() > 0)\n\t\t{\n\t\t\titsLogger->Debug(\"Sleeping for \" + boost::lexical_cast (sleepSeconds) + \" seconds (cumulative: \" + boost::lexical_cast (waitedSeconds) + \")\");\n\n\t\t\tif (!config->ReadDataFromDatabase())\n\t\t\t{\n\t\t\t\titsLogger->Warning(\"file_wait_timeout specified but file read from Neons is disabled\");\n\t\t\t}\n\n\t\t\tsleep(sleepSeconds);\n\t\t}\n }\n\n \/*\n * Safeguard; later in the code we do not check whether the data requested\n * was actually what was requested.\n *\/\n\n\tif (theInfos.size() == 0)\n\t{\n\t\tstring optsStr = \"producer: \" + boost::lexical_cast (config->SourceProducer());\n\t\toptsStr += \" origintime: \" + requestedTime.OriginDateTime()->String() + \", step: \" + boost::lexical_cast (requestedTime.Step());\n\t\toptsStr += \" param: \" + requestedParam.Name();\n\t\toptsStr += \" level: \" + string(himan::HPLevelTypeToString.at(requestedLevel.Type())) + \" \" + boost::lexical_cast (requestedLevel.Value());\n\n\t\titsLogger->Warning(\"No valid data found with given search options \" + optsStr);\n\n\t\tthrow kFileDataNotFound;\n\t}\n\n \/\/ assert(theConfiguration->SourceProducer() == theInfos[0]->Producer());\n\n assert((theInfos[0]->Level()) == requestedLevel);\n\n assert((theInfos[0]->Time()) == requestedTime);\n\n assert((theInfos[0]->Param()) == requestedParam);\n\n return theInfos[0];\n\n}\n\n\/*\n * FromFile()\n *\n * Get data and metadata from a file. Returns a vector of infos, mainly because one grib file can\n * contain many grib messages. If read file is querydata, the vector size is always one (or zero if the\n * read fails).\n *\/\n\nvector> fetcher::FromFile(const vector& files, const search_options& options, bool readContents)\n{\n\n vector> allInfos ;\n\n for (size_t i = 0; i < files.size(); i++)\n {\n string inputFile = files[i];\n\n if (!boost::filesystem::exists(inputFile))\n {\n itsLogger->Error(\"Input file '\" + inputFile + \"' does not exist\");\n continue;\n }\n\n vector> curInfos;\n\n switch (util::FileType(inputFile))\n {\n\n case kGRIB:\n case kGRIB1:\n case kGRIB2:\n {\n\n curInfos = FromGrib(inputFile, options, readContents);\n break;\n\n }\n\n case kQueryData:\n {\n\n curInfos = FromQueryData(inputFile, options, readContents);\n break;\n }\n\n case kNetCDF:\n cout << \"File is NetCDF\" << endl;\n break;\n\n default:\n \/\/ Unknown file type, cannot proceed\n throw runtime_error(\"Input file is neither GRID, NetCDF nor QueryData\");\n break;\n }\n\n allInfos.insert(allInfos.end(), curInfos.begin(), curInfos.end());\n\n if (curInfos.size())\n {\n break; \/\/ We found what we were looking for\n }\n\n }\n\n return allInfos;\n}\n\nvector > fetcher::FromGrib(const string& inputFile, const search_options& options, bool readContents)\n{\n\n shared_ptr g = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"grib\"));\n\n vector> infos = g->FromFile(inputFile, options, readContents);\n\n return infos;\n}\n\nvector> fetcher::FromQueryData(const string& inputFile, const search_options& options, bool readContents)\n{\n\n shared_ptr q = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"querydata\"));\n\n shared_ptr i = q->FromFile(inputFile, options, readContents);\n\n vector> theInfos;\n\n theInfos.push_back(i);\n\n return theInfos;\n}\nchange for to do\/while\/*\n * fetcher.cpp\n *\n * Created on: Nov 21, 2012\n * Author: partio\n *\/\n\n#include \"fetcher.h\"\n#include \"plugin_factory.h\"\n#include \"logger_factory.h\"\n#include \n#include \n#include \n#include \"util.h\"\n\n#define HIMAN_AUXILIARY_INCLUDE\n\n#include \"grib.h\"\n#include \"neons.h\"\n#include \"param.h\"\n#include \"cache.h\"\n#include \"querydata.h\"\n\n#undef HIMAN_AUXILIARY_INCLUDE\n\nusing namespace himan::plugin;\nusing namespace std;\n\nconst unsigned int sleepSeconds = 10;\n\nfetcher::fetcher()\n{\n itsLogger = std::unique_ptr (logger_factory::Instance()->GetLog(\"fetcher\"));\n}\n\nshared_ptr fetcher::Fetch(shared_ptr config,\n const forecast_time& requestedTime,\n const level& requestedLevel,\n const param& requestedParam)\n{\n\n const search_options opts { requestedTime, requestedParam, requestedLevel, config } ;\n\n vector> theInfos;\n unsigned int waitedSeconds = 0;\n\n do\n {\n \t\/\/ 1. Fetch data from cache\n\n \t\/\/ theInfos = FromCache()\n\n \t\/*\n \t * 2. Fetch data from auxiliary files specified at command line\n \t *\n \t * Even if file_wait_timeout is specified, auxiliary files is searched\n \t * only once.\n \t *\/\n\n \tif (config->AuxiliaryFiles().size() && waitedSeconds == 0)\n \t{\n \t\ttheInfos = FromFile(config->AuxiliaryFiles(), opts, true);\n\n \t\tif (theInfos.size())\n \t\t{\n \t\t\titsLogger->Debug(\"Data found from auxiliary file(s)\");\n \t\t\tbreak;\n \t\t}\n \t\telse\n \t\t{\n \t\t\titsLogger->Warning(\"Data not found from auxiliary file(s)\");\n \t\t}\n \t}\n\n\t\t\/\/ 3. Fetch data from Neons\n\n\t\tvector files;\n\n\t\tif (config->ReadDataFromDatabase())\n\t\t{\n\t\t\tshared_ptr n = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"neons\"));\n\n\t\t\tfiles = n->Files(opts);\n\n\t\t\tif (!files.empty())\n\t\t\t{\n\t\t\t\ttheInfos = FromFile(files, opts, true);\n\n\t\t\t\tbreak;\n\t\t\t}\n\t \telse if (config->ReadDataFromDatabase())\n\t \t{\n\t \t\titsLogger->Debug(\"Could not find file(s) from Neons matching requested parameters\");\n\t \t}\n\t\t}\n\n\t\tif (config->FileWaitTimeout() > 0)\n\t\t{\n\t\t\titsLogger->Debug(\"Sleeping for \" + boost::lexical_cast (sleepSeconds) + \" seconds (cumulative: \" + boost::lexical_cast (waitedSeconds) + \")\");\n\n\t\t\tif (!config->ReadDataFromDatabase())\n\t\t\t{\n\t\t\t\titsLogger->Warning(\"file_wait_timeout specified but file read from Neons is disabled\");\n\t\t\t}\n\n\t\t\tsleep(sleepSeconds);\n\t\t}\n\n\t\twaitedSeconds += sleepSeconds;\n }\n while (waitedSeconds < config->FileWaitTimeout() * 60);\n\n \/*\n * Safeguard; later in the code we do not check whether the data requested\n * was actually what was requested.\n *\/\n\n\tif (theInfos.size() == 0)\n\t{\n\t\tstring optsStr = \"producer: \" + boost::lexical_cast (config->SourceProducer());\n\t\toptsStr += \" origintime: \" + requestedTime.OriginDateTime()->String() + \", step: \" + boost::lexical_cast (requestedTime.Step());\n\t\toptsStr += \" param: \" + requestedParam.Name();\n\t\toptsStr += \" level: \" + string(himan::HPLevelTypeToString.at(requestedLevel.Type())) + \" \" + boost::lexical_cast (requestedLevel.Value());\n\n\t\titsLogger->Warning(\"No valid data found with given search options \" + optsStr);\n\n\t\tthrow kFileDataNotFound;\n\t}\n\n \/\/ assert(theConfiguration->SourceProducer() == theInfos[0]->Producer());\n\n assert((theInfos[0]->Level()) == requestedLevel);\n\n assert((theInfos[0]->Time()) == requestedTime);\n\n assert((theInfos[0]->Param()) == requestedParam);\n\n return theInfos[0];\n\n}\n\n\/*\n * FromFile()\n *\n * Get data and metadata from a file. Returns a vector of infos, mainly because one grib file can\n * contain many grib messages. If read file is querydata, the vector size is always one (or zero if the\n * read fails).\n *\/\n\nvector> fetcher::FromFile(const vector& files, const search_options& options, bool readContents)\n{\n\n vector> allInfos ;\n\n for (size_t i = 0; i < files.size(); i++)\n {\n string inputFile = files[i];\n\n if (!boost::filesystem::exists(inputFile))\n {\n itsLogger->Error(\"Input file '\" + inputFile + \"' does not exist\");\n continue;\n }\n\n vector> curInfos;\n\n switch (util::FileType(inputFile))\n {\n\n case kGRIB:\n case kGRIB1:\n case kGRIB2:\n {\n\n curInfos = FromGrib(inputFile, options, readContents);\n break;\n\n }\n\n case kQueryData:\n {\n\n curInfos = FromQueryData(inputFile, options, readContents);\n break;\n }\n\n case kNetCDF:\n cout << \"File is NetCDF\" << endl;\n break;\n\n default:\n \/\/ Unknown file type, cannot proceed\n throw runtime_error(\"Input file is neither GRID, NetCDF nor QueryData\");\n break;\n }\n\n allInfos.insert(allInfos.end(), curInfos.begin(), curInfos.end());\n\n if (curInfos.size())\n {\n break; \/\/ We found what we were looking for\n }\n\n }\n\n return allInfos;\n}\n\nvector > fetcher::FromGrib(const string& inputFile, const search_options& options, bool readContents)\n{\n\n shared_ptr g = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"grib\"));\n\n vector> infos = g->FromFile(inputFile, options, readContents);\n\n return infos;\n}\n\nvector> fetcher::FromQueryData(const string& inputFile, const search_options& options, bool readContents)\n{\n\n shared_ptr q = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"querydata\"));\n\n shared_ptr i = q->FromFile(inputFile, options, readContents);\n\n vector> theInfos;\n\n theInfos.push_back(i);\n\n return theInfos;\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n* Copyright (c) 2013, Howard Butler (hobu.inc@gmail.com)\n* Copyright (c) 2014, Bradley J Chambers (brad.chambers@gmail.com)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nQuery is OBE\/******************************************************************************\n* Copyright (c) 2013, Howard Butler (hobu.inc@gmail.com)\n* Copyright (c) 2014, Bradley J Chambers (brad.chambers@gmail.com)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n<|endoftext|>"} {"text":"\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"catch.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nTEST_CASE(\"geojson\") {\n\n std::string geojson_plugin(\".\/plugins\/input\/geojson.input\");\n if (mapnik::util::exists(geojson_plugin))\n {\n SECTION(\"json feature cache-feature=\\\"true\\\"\")\n {\n \/\/ Create datasource\n mapnik::parameters params;\n params[\"type\"] = \"geojson\";\n params[\"file\"] = \".\/test\/data\/json\/feature.json\";\n params[\"cache-features\"] = true;\n auto ds = mapnik::datasource_cache::instance().create(params);\n REQUIRE(bool(ds));\n auto fields = ds->get_descriptor().get_descriptors();\n mapnik::query query(ds->envelope());\n for (auto const &field : fields)\n {\n query.add_property_name(field.get_name());\n }\n auto features = ds->features(query);\n REQUIRE(features != nullptr);\n auto feature = features->next();\n REQUIRE(feature != nullptr);\n }\n\n SECTION(\"json feature cache-feature=\\\"false\\\"\")\n {\n mapnik::parameters params;\n params[\"type\"] = \"geojson\";\n params[\"file\"] = \".\/test\/data\/json\/feature.json\";\n params[\"cache-features\"] = false;\n auto ds = mapnik::datasource_cache::instance().create(params);\n REQUIRE(bool(ds));\n auto fields = ds->get_descriptor().get_descriptors();\n mapnik::query query(ds->envelope());\n for (auto const &field : fields)\n {\n query.add_property_name(field.get_name());\n }\n auto features = ds->features(query);\n REQUIRE(features != nullptr);\n auto feature = features->next();\n REQUIRE(feature != nullptr);\n }\n\n SECTION(\"json extra properties cache-feature=\\\"true\\\"\")\n {\n \/\/ Create datasource\n mapnik::parameters params;\n params[\"type\"] = \"geojson\";\n params[\"file\"] = \".\/test\/data\/json\/feature_collection_extra_properties.json\";\n params[\"cache-features\"] = true;\n auto ds = mapnik::datasource_cache::instance().create(params);\n REQUIRE(bool(ds));\n auto fields = ds->get_descriptor().get_descriptors();\n mapnik::query query(ds->envelope());\n for (auto const &field : fields)\n {\n query.add_property_name(field.get_name());\n }\n auto features = ds->features(query);\n REQUIRE(features != nullptr);\n auto feature = features->next();\n REQUIRE(feature != nullptr);\n REQUIRE(feature->envelope() == mapnik::box2d(123,456,123,456));\n }\n\n SECTION(\"json extra properties cache-feature=\\\"false\\\"\")\n {\n \/\/ Create datasource\n mapnik::parameters params;\n params[\"type\"] = \"geojson\";\n params[\"file\"] = \".\/test\/data\/json\/feature_collection_extra_properties.json\";\n params[\"cache-features\"] = false;\n auto ds = mapnik::datasource_cache::instance().create(params);\n REQUIRE(bool(ds));\n auto fields = ds->get_descriptor().get_descriptors();\n mapnik::query query(ds->envelope());\n for (auto const &field : fields)\n {\n query.add_property_name(field.get_name());\n }\n auto features = ds->features(query);\n REQUIRE(features != nullptr);\n auto feature = features->next();\n REQUIRE(feature != nullptr);\n REQUIRE(feature->envelope() == mapnik::box2d(123,456,123,456));\n }\n SECTION(\"json - ensure input fully consumed and throw exception otherwise\")\n {\n mapnik::parameters params;\n params[\"type\"] = \"geojson\";\n params[\"file\"] = \".\/test\/data\/json\/points-malformed.geojson\"; \/\/ mismatched parentheses\n params[\"cache-features\"] = false;\n REQUIRE_THROWS(mapnik::datasource_cache::instance().create(params));\n params[\"cache-features\"] = true;\n REQUIRE_THROWS(mapnik::datasource_cache::instance().create(params));\n }\n }\n}\nunit test(geojson) - add tests reading all geometry primitives\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"catch.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace detail {\n\nmapnik::feature_ptr fetch_first_feature(std::string const& filename, bool cache_features)\n{\n mapnik::parameters params;\n params[\"type\"] = \"geojson\";\n params[\"file\"] = filename;\n params[\"cache-features\"] = cache_features;\n auto ds = mapnik::datasource_cache::instance().create(params);\n auto fields = ds->get_descriptor().get_descriptors();\n mapnik::query query(ds->envelope());\n for (auto const& field : fields)\n {\n query.add_property_name(field.get_name());\n }\n auto features = ds->features(query);\n auto feature = features->next();\n return feature;\n}\n\n}\n\nTEST_CASE(\"geojson\") {\n\n std::string geojson_plugin(\".\/plugins\/input\/geojson.input\");\n if (mapnik::util::exists(geojson_plugin))\n {\n SECTION(\"GeoJSON Point\")\n {\n {\n \/\/ cache features in memory\n auto feature = detail::fetch_first_feature(\".\/test\/data\/json\/point.json\", true);\n \/\/ test\n auto const& geometry = feature->get_geometry();\n REQUIRE(mapnik::geometry::geometry_type(geometry) == mapnik::geometry::Point);\n auto const& pt = mapnik::util::get >(geometry);\n REQUIRE(pt.x == 100);\n REQUIRE(pt.y == 0);\n }\n {\n \/\/ on-fly in-memory r-tree index + read features from disk\n auto feature = detail::fetch_first_feature(\".\/test\/data\/json\/point.json\", false);\n \/\/ test\n auto const& geometry = feature->get_geometry();\n REQUIRE(mapnik::geometry::geometry_type(geometry) == mapnik::geometry::Point);\n auto const& pt = mapnik::util::get >(geometry);\n REQUIRE(pt.x == 100);\n REQUIRE(pt.y == 0);\n }\n }\n\n SECTION(\"GeoJSON LineString\")\n {\n mapnik::parameters params;\n params[\"type\"] = \"geojson\";\n params[\"file\"] = \".\/test\/data\/json\/linestring.json\";\n\n {\n \/\/ cache features in memory\n auto feature = detail::fetch_first_feature(\".\/test\/data\/json\/linestring.json\", true);\n \/\/ test\n auto const& geometry = feature->get_geometry();\n REQUIRE(mapnik::geometry::geometry_type(geometry) == mapnik::geometry::LineString);\n auto const& line = mapnik::util::get >(geometry);\n REQUIRE(line.size() == 2);\n REQUIRE(mapnik::geometry::envelope(line) == mapnik::box2d(100,0,101,1));\n\n }\n {\n \/\/ on-fly in-memory r-tree index + read features from disk\n auto feature = detail::fetch_first_feature(\".\/test\/data\/json\/linestring.json\", false);\n \/\/ test\n auto const& geometry = feature->get_geometry();\n REQUIRE(mapnik::geometry::geometry_type(geometry) == mapnik::geometry::LineString);\n auto const& line = mapnik::util::get >(geometry);\n REQUIRE(line.size() == 2);\n REQUIRE(mapnik::geometry::envelope(line) == mapnik::box2d(100,0,101,1));\n }\n }\n\n SECTION(\"GeoJSON Polygon\")\n {\n mapnik::parameters params;\n params[\"type\"] = \"geojson\";\n params[\"file\"] = \".\/test\/data\/json\/polygon.json\";\n\n {\n \/\/ cache features in memory\n auto feature = detail::fetch_first_feature(\".\/test\/data\/json\/polygon.json\", true);\n \/\/ test\n auto const& geometry = feature->get_geometry();\n REQUIRE(mapnik::geometry::geometry_type(geometry) == mapnik::geometry::Polygon);\n auto const& poly = mapnik::util::get >(geometry);\n REQUIRE(poly.num_rings() == 2);\n REQUIRE(poly.exterior_ring.size() == 5);\n REQUIRE(poly.interior_rings.size() == 1);\n REQUIRE(poly.interior_rings[0].size() == 5);\n REQUIRE(mapnik::geometry::envelope(poly) == mapnik::box2d(100,0,101,1));\n\n }\n {\n \/\/ on-fly in-memory r-tree index + read features from disk\n auto feature = detail::fetch_first_feature(\".\/test\/data\/json\/polygon.json\", false);\n \/\/ test\n auto const& geometry = feature->get_geometry();\n REQUIRE(mapnik::geometry::geometry_type(geometry) == mapnik::geometry::Polygon);\n auto const& poly = mapnik::util::get >(geometry);\n REQUIRE(poly.num_rings() == 2);\n REQUIRE(poly.exterior_ring.size() == 5);\n REQUIRE(poly.interior_rings.size() == 1);\n REQUIRE(poly.interior_rings[0].size() == 5);\n REQUIRE(mapnik::geometry::envelope(poly) == mapnik::box2d(100,0,101,1));\n }\n }\n\n SECTION(\"GeoJSON MultiPoint\")\n {\n {\n \/\/ cache features in memory\n auto feature = detail::fetch_first_feature(\".\/test\/data\/json\/multipoint.json\", true);\n \/\/ test\n auto const& geometry = feature->get_geometry();\n REQUIRE(mapnik::geometry::geometry_type(geometry) == mapnik::geometry::MultiPoint);\n auto const& multi_pt = mapnik::util::get >(geometry);\n REQUIRE(multi_pt.size() == 2);\n REQUIRE(mapnik::geometry::envelope(multi_pt) == mapnik::box2d(100,0,101,1));\n }\n {\n \/\/ on-fly in-memory r-tree index + read features from disk\n auto feature = detail::fetch_first_feature(\".\/test\/data\/json\/multipoint.json\", false);\n \/\/ test\n auto const& geometry = feature->get_geometry();\n REQUIRE(mapnik::geometry::geometry_type(geometry) == mapnik::geometry::MultiPoint);\n auto const& multi_pt = mapnik::util::get >(geometry);\n REQUIRE(multi_pt.size() == 2);\n REQUIRE(mapnik::geometry::envelope(multi_pt) == mapnik::box2d(100,0,101,1));\n }\n }\n\n SECTION(\"GeoJSON MultiLineString\")\n {\n {\n \/\/ cache features in memory\n auto feature = detail::fetch_first_feature(\".\/test\/data\/json\/multilinestring.json\", true);\n \/\/ test\n auto const& geometry = feature->get_geometry();\n REQUIRE(mapnik::geometry::geometry_type(geometry) == mapnik::geometry::MultiLineString);\n auto const& multi_line = mapnik::util::get >(geometry);\n REQUIRE(multi_line.size() == 2);\n REQUIRE(multi_line[0].size() == 2);\n REQUIRE(multi_line[1].size() == 2);\n REQUIRE(mapnik::geometry::envelope(multi_line) == mapnik::box2d(100,0,103,3));\n\n }\n {\n \/\/ on-fly in-memory r-tree index + read features from disk\n auto feature = detail::fetch_first_feature(\".\/test\/data\/json\/multilinestring.json\", false);\n \/\/ test\n auto const& geometry = feature->get_geometry();\n REQUIRE(mapnik::geometry::geometry_type(geometry) == mapnik::geometry::MultiLineString);\n auto const& multi_line = mapnik::util::get >(geometry);\n REQUIRE(multi_line.size() == 2);\n REQUIRE(multi_line[0].size() == 2);\n REQUIRE(multi_line[1].size() == 2);\n REQUIRE(mapnik::geometry::envelope(multi_line) == mapnik::box2d(100,0,103,3));\n }\n }\n\n SECTION(\"GeoJSON MultiPolygon\")\n {\n {\n \/\/ cache features in memory\n auto feature = detail::fetch_first_feature(\".\/test\/data\/json\/multipolygon.json\", true);\n \/\/ test\n auto const& geometry = feature->get_geometry();\n REQUIRE(mapnik::geometry::geometry_type(geometry) == mapnik::geometry::MultiPolygon);\n auto const& multi_poly = mapnik::util::get >(geometry);\n REQUIRE(multi_poly.size() == 2);\n REQUIRE(multi_poly[0].num_rings() == 1);\n REQUIRE(multi_poly[1].num_rings() == 2);\n REQUIRE(mapnik::geometry::envelope(multi_poly) == mapnik::box2d(100,0,103,3));\n\n }\n {\n \/\/ on-fly in-memory r-tree index + read features from disk\n auto feature = detail::fetch_first_feature(\".\/test\/data\/json\/multipolygon.json\", false);\n \/\/ test\n auto const& geometry = feature->get_geometry();\n REQUIRE(mapnik::geometry::geometry_type(geometry) == mapnik::geometry::MultiPolygon);\n auto const& multi_poly = mapnik::util::get >(geometry);\n REQUIRE(multi_poly.size() == 2);\n REQUIRE(multi_poly[0].num_rings() == 1);\n REQUIRE(multi_poly[1].num_rings() == 2);\n REQUIRE(mapnik::geometry::envelope(multi_poly) == mapnik::box2d(100,0,103,3));\n }\n }\n\n SECTION(\"GeoJSON GeometryCollection\")\n {\n {\n \/\/ cache features in memory\n auto feature = detail::fetch_first_feature(\".\/test\/data\/json\/geometrycollection.json\", true);\n \/\/ test\n auto const& geometry = feature->get_geometry();\n REQUIRE(mapnik::geometry::geometry_type(geometry) == mapnik::geometry::GeometryCollection);\n auto const& collection = mapnik::util::get >(geometry);\n REQUIRE(collection.size() == 2);\n REQUIRE(mapnik::geometry::geometry_type(collection[0]) == mapnik::geometry::Point);\n REQUIRE(mapnik::geometry::geometry_type(collection[1]) == mapnik::geometry::LineString);\n REQUIRE(mapnik::geometry::envelope(collection) == mapnik::box2d(100,0,102,1));\n }\n {\n \/\/ cache features in memory\n auto feature = detail::fetch_first_feature(\".\/test\/data\/json\/geometrycollection.json\", false);\n \/\/ test\n auto const& geometry = feature->get_geometry();\n REQUIRE(mapnik::geometry::geometry_type(geometry) == mapnik::geometry::GeometryCollection);\n auto const& collection = mapnik::util::get >(geometry);\n REQUIRE(collection.size() == 2);\n REQUIRE(mapnik::geometry::geometry_type(collection[0]) == mapnik::geometry::Point);\n REQUIRE(mapnik::geometry::geometry_type(collection[1]) == mapnik::geometry::LineString);\n REQUIRE(mapnik::geometry::envelope(collection) == mapnik::box2d(100,0,102,1));\n }\n }\n\n SECTION(\"json feature cache-feature=\\\"true\\\"\")\n {\n \/\/ Create datasource\n mapnik::parameters params;\n params[\"type\"] = \"geojson\";\n params[\"file\"] = \".\/test\/data\/json\/feature.json\";\n params[\"cache-features\"] = true;\n auto ds = mapnik::datasource_cache::instance().create(params);\n REQUIRE(bool(ds));\n auto fields = ds->get_descriptor().get_descriptors();\n mapnik::query query(ds->envelope());\n for (auto const& field : fields)\n {\n query.add_property_name(field.get_name());\n }\n auto features = ds->features(query);\n REQUIRE(features != nullptr);\n auto feature = features->next();\n REQUIRE(feature != nullptr);\n }\n\n SECTION(\"json feature cache-feature=\\\"false\\\"\")\n {\n mapnik::parameters params;\n params[\"type\"] = \"geojson\";\n params[\"file\"] = \".\/test\/data\/json\/feature.json\";\n params[\"cache-features\"] = false;\n auto ds = mapnik::datasource_cache::instance().create(params);\n REQUIRE(bool(ds));\n auto fields = ds->get_descriptor().get_descriptors();\n mapnik::query query(ds->envelope());\n for (auto const& field : fields)\n {\n query.add_property_name(field.get_name());\n }\n auto features = ds->features(query);\n REQUIRE(features != nullptr);\n auto feature = features->next();\n REQUIRE(feature != nullptr);\n }\n\n SECTION(\"json extra properties cache-feature=\\\"true\\\"\")\n {\n \/\/ Create datasource\n mapnik::parameters params;\n params[\"type\"] = \"geojson\";\n params[\"file\"] = \".\/test\/data\/json\/feature_collection_extra_properties.json\";\n params[\"cache-features\"] = true;\n auto ds = mapnik::datasource_cache::instance().create(params);\n REQUIRE(bool(ds));\n auto fields = ds->get_descriptor().get_descriptors();\n mapnik::query query(ds->envelope());\n for (auto const& field : fields)\n {\n query.add_property_name(field.get_name());\n }\n auto features = ds->features(query);\n REQUIRE(features != nullptr);\n auto feature = features->next();\n REQUIRE(feature != nullptr);\n REQUIRE(feature->envelope() == mapnik::box2d(123,456,123,456));\n }\n\n SECTION(\"json extra properties cache-feature=\\\"false\\\"\")\n {\n \/\/ Create datasource\n mapnik::parameters params;\n params[\"type\"] = \"geojson\";\n params[\"file\"] = \".\/test\/data\/json\/feature_collection_extra_properties.json\";\n params[\"cache-features\"] = false;\n auto ds = mapnik::datasource_cache::instance().create(params);\n REQUIRE(bool(ds));\n auto fields = ds->get_descriptor().get_descriptors();\n mapnik::query query(ds->envelope());\n for (auto const& field : fields)\n {\n query.add_property_name(field.get_name());\n }\n auto features = ds->features(query);\n REQUIRE(features != nullptr);\n auto feature = features->next();\n REQUIRE(feature != nullptr);\n REQUIRE(feature->envelope() == mapnik::box2d(123,456,123,456));\n }\n SECTION(\"json - ensure input fully consumed and throw exception otherwise\")\n {\n mapnik::parameters params;\n params[\"type\"] = \"geojson\";\n params[\"file\"] = \".\/test\/data\/json\/points-malformed.geojson\"; \/\/ mismatched parentheses\n params[\"cache-features\"] = false;\n REQUIRE_THROWS(mapnik::datasource_cache::instance().create(params));\n params[\"cache-features\"] = true;\n REQUIRE_THROWS(mapnik::datasource_cache::instance().create(params));\n }\n }\n}\n<|endoftext|>"} {"text":"Fix a bug in TF1Convolution::SetExtraRange<|endoftext|>"} {"text":"\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/policy\/remote_commands\/device_command_reboot_job.h\"\n\n#include \n\n#include \"base\/bind.h\"\n#include \"base\/location.h\"\n#include \"base\/logging.h\"\n#include \"base\/sys_info.h\"\n#include \"base\/time\/time.h\"\n#include \"chromeos\/dbus\/power_manager_client.h\"\n#include \"policy\/proto\/device_management_backend.pb.h\"\n\nnamespace policy {\n\nnamespace {\n\n\/\/ Determines the time, measured from the time of issue, after which the command\n\/\/ queue will consider this command expired if the command has not been started.\nconst int kCommandExpirationTimeInMinutes = 10;\n\n\/\/ Determines the minimum uptime after which a reboot might be scheduled. Note:\n\/\/ |kCommandExpirationTimeInMinutes| >= |kMinimumUptimeInMinutes| as\n\/\/ otherwise, a valid command issued right after boot may time out.\nconst int kMinimumUptimeInMinutes = 10;\n\n} \/\/ namespace\n\nDeviceCommandRebootJob::DeviceCommandRebootJob(\n chromeos::PowerManagerClient* power_manager_client)\n : power_manager_client_(power_manager_client), weak_ptr_factory_(this) {\n CHECK(power_manager_client_);\n}\n\nDeviceCommandRebootJob::~DeviceCommandRebootJob() {\n}\n\nenterprise_management::RemoteCommand_Type DeviceCommandRebootJob::GetType()\n const {\n return enterprise_management::RemoteCommand_Type_DEVICE_REBOOT;\n}\n\nbool DeviceCommandRebootJob::IsExpired(base::Time now) {\n return now > issued_time() + base::TimeDelta::FromMinutes(\n kCommandExpirationTimeInMinutes);\n}\n\nvoid DeviceCommandRebootJob::RunImpl(\n const SucceededCallback& succeeded_callback,\n const FailedCallback& failed_callback) {\n \/\/ Determines the time delta between the command having been issued and the\n \/\/ boot time of the system.\n const base::TimeDelta uptime =\n base::TimeDelta::FromMilliseconds(base::SysInfo::Uptime());\n const base::Time boot_time = base::Time::Now() - uptime;\n const base::TimeDelta delta = boot_time - issued_time();\n \/\/ If the reboot command was issued before the system booted, we inform the\n \/\/ server that the reboot succeeded. Otherwise, the reboot must still be\n \/\/ performed and we invoke it. |kMinimumUptimeInMinutes| defines a lower limit\n \/\/ on the uptime to avoid uninterruptable reboot loops.\n if (delta > base::TimeDelta()) {\n succeeded_callback.Run(nullptr);\n return;\n }\n\n const base::TimeDelta kZeroTimeDelta;\n reboot_timer_.Start(\n FROM_HERE,\n std::max(base::TimeDelta::FromMinutes(kMinimumUptimeInMinutes) - uptime,\n kZeroTimeDelta),\n base::Bind(&DeviceCommandRebootJob::Reboot,\n weak_ptr_factory_.GetWeakPtr()));\n}\n\nvoid DeviceCommandRebootJob::TerminateImpl() {\n weak_ptr_factory_.InvalidateWeakPtrs();\n}\n\nbase::TimeDelta DeviceCommandRebootJob::GetCommmandTimeout() const {\n return base::TimeDelta::FromMinutes(kMinimumUptimeInMinutes);\n}\n\nvoid DeviceCommandRebootJob::Reboot() const {\n power_manager_client_->RequestRestart();\n}\n\n} \/\/ namespace policy\nCall callback asynchronously for device reboot command\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/policy\/remote_commands\/device_command_reboot_job.h\"\n\n#include \n\n#include \"base\/bind.h\"\n#include \"base\/location.h\"\n#include \"base\/logging.h\"\n#include \"base\/single_thread_task_runner.h\"\n#include \"base\/sys_info.h\"\n#include \"base\/thread_task_runner_handle.h\"\n#include \"base\/time\/time.h\"\n#include \"chromeos\/dbus\/power_manager_client.h\"\n#include \"policy\/proto\/device_management_backend.pb.h\"\n\nnamespace policy {\n\nnamespace {\n\n\/\/ Determines the time, measured from the time of issue, after which the command\n\/\/ queue will consider this command expired if the command has not been started.\nconst int kCommandExpirationTimeInMinutes = 10;\n\n\/\/ Determines the minimum uptime after which a reboot might be scheduled. Note:\n\/\/ |kCommandExpirationTimeInMinutes| >= |kMinimumUptimeInMinutes| as\n\/\/ otherwise, a valid command issued right after boot may time out.\nconst int kMinimumUptimeInMinutes = 10;\n\n} \/\/ namespace\n\nDeviceCommandRebootJob::DeviceCommandRebootJob(\n chromeos::PowerManagerClient* power_manager_client)\n : power_manager_client_(power_manager_client), weak_ptr_factory_(this) {\n CHECK(power_manager_client_);\n}\n\nDeviceCommandRebootJob::~DeviceCommandRebootJob() {\n}\n\nenterprise_management::RemoteCommand_Type DeviceCommandRebootJob::GetType()\n const {\n return enterprise_management::RemoteCommand_Type_DEVICE_REBOOT;\n}\n\nbool DeviceCommandRebootJob::IsExpired(base::Time now) {\n return now > issued_time() + base::TimeDelta::FromMinutes(\n kCommandExpirationTimeInMinutes);\n}\n\nvoid DeviceCommandRebootJob::RunImpl(\n const SucceededCallback& succeeded_callback,\n const FailedCallback& failed_callback) {\n \/\/ Determines the time delta between the command having been issued and the\n \/\/ boot time of the system.\n const base::TimeDelta uptime =\n base::TimeDelta::FromMilliseconds(base::SysInfo::Uptime());\n const base::Time boot_time = base::Time::Now() - uptime;\n const base::TimeDelta delta = boot_time - issued_time();\n \/\/ If the reboot command was issued before the system booted, we inform the\n \/\/ server that the reboot succeeded. Otherwise, the reboot must still be\n \/\/ performed and we invoke it. |kMinimumUptimeInMinutes| defines a lower limit\n \/\/ on the uptime to avoid uninterruptable reboot loops.\n if (delta > base::TimeDelta()) {\n base::ThreadTaskRunnerHandle::Get()->PostTask(\n FROM_HERE, base::Bind(succeeded_callback, nullptr));\n return;\n }\n\n const base::TimeDelta kZeroTimeDelta;\n reboot_timer_.Start(\n FROM_HERE,\n std::max(base::TimeDelta::FromMinutes(kMinimumUptimeInMinutes) - uptime,\n kZeroTimeDelta),\n base::Bind(&DeviceCommandRebootJob::Reboot,\n weak_ptr_factory_.GetWeakPtr()));\n}\n\nvoid DeviceCommandRebootJob::TerminateImpl() {\n weak_ptr_factory_.InvalidateWeakPtrs();\n}\n\nbase::TimeDelta DeviceCommandRebootJob::GetCommmandTimeout() const {\n return base::TimeDelta::FromMinutes(kMinimumUptimeInMinutes);\n}\n\nvoid DeviceCommandRebootJob::Reboot() const {\n power_manager_client_->RequestRestart();\n}\n\n} \/\/ namespace policy\n<|endoftext|>"} {"text":"#include \"RTSAttackComponent.h\"\n#include \"RTSPluginPCH.h\"\n\n#include \"Engine\/World.h\"\n#include \"GameFramework\/Pawn.h\"\n\n#include \"RTSProjectile.h\"\n\n\nURTSAttackComponent::URTSAttackComponent(const FObjectInitializer& ObjectInitializer)\n\t: Super(ObjectInitializer)\n{\n\tPrimaryComponentTick.bCanEverTick = true;\n}\n\nvoid URTSAttackComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)\n{\n\t\/\/ Update cooldown timer.\n\tif (RemainingCooldown > 0)\n\t{\n\t\tRemainingCooldown -= DeltaTime;\n\n\t\tif (RemainingCooldown <= 0)\n\t\t{\n\t\t\tUE_LOG(LogRTS, Log, TEXT(\"Actor %s attack is ready again.\"), *GetOwner()->GetName());\n\n\t\t\t\/\/ Notify listeners.\n\t\t\tOnCooldownReady.Broadcast();\n\t\t}\n\t}\n}\n\nvoid URTSAttackComponent::UseAttack(int32 AttackIndex, AActor* Target)\n{\n\tAActor* Owner = GetOwner();\n\tAPawn* OwnerPawn = Cast(Owner);\n\tAController* OwnerController = OwnerPawn ? OwnerPawn->GetController() : nullptr;\n\n\tif (!IsValid(Target))\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ Check cooldown.\n\tif (RemainingCooldown > 0)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ Use attack.\n\tUE_LOG(LogRTS, Log, TEXT(\"Actor %s attacks %s.\"), *Owner->GetName(), *Target->GetName());\n\n\tconst FRTSAttackData& Attack = Attacks[0];\n\n\tARTSProjectile* SpawnedProjectile = nullptr;\n\n\tif (Attack.ProjectileClass != nullptr)\n\t{\n\t\t\/\/ Fire projectile.\n\t\t\/\/ Build spawn transform.\n\t\tFVector SpawnLocation = Owner->GetActorLocation();\n\t\tFRotator SpawnRotation = Owner->GetActorRotation();\n\t\tFTransform SpawnTransform = FTransform(SpawnRotation, SpawnLocation);\n\n\t\t\/\/ Build spawn info.\n\t\tFActorSpawnParameters SpawnInfo;\n\t\tSpawnInfo.Instigator = OwnerPawn;\n\t\tSpawnInfo.ObjectFlags |= RF_Transient;\n\n\t\t\/\/ Spawn projectile.\n\t\tSpawnedProjectile = GetWorld()->SpawnActor(Attack.ProjectileClass, SpawnTransform, SpawnInfo);\n\n\t\tif (SpawnedProjectile)\n\t\t{\n\t\t\tUE_LOG(LogRTS, Log, TEXT(\"%s fired projectile %s at target %s.\"), *Owner->GetName(), *SpawnedProjectile->GetName(), *Target->GetName());\n\n\t\t\t\/\/ Aim at target.\n\t\t\tSpawnedProjectile->FireAt(\n\t\t\t\tTarget,\n\t\t\t\tAttack.Damage,\n\t\t\t\tAttack.DamageType,\n\t\t\t\tOwnerController,\n\t\t\t\tOwner);\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ Deal damage immediately.\n\t\tTarget->TakeDamage(Attack.Damage, FDamageEvent(Attack.DamageType), OwnerController, Owner);\n\t}\n\n\t\/\/ Start cooldown timer.\n\tRemainingCooldown = Attack.Cooldown;\n\n\t\/\/ Notify listeners.\n\tOnAttackUsed.Broadcast(Attack, Target, SpawnedProjectile);\n}\nMove pre-compiled header first in attack component.#include \"RTSPluginPCH.h\"\n#include \"RTSAttackComponent.h\"\n\n#include \"Engine\/World.h\"\n#include \"GameFramework\/Pawn.h\"\n\n#include \"RTSProjectile.h\"\n\n\nURTSAttackComponent::URTSAttackComponent(const FObjectInitializer& ObjectInitializer)\n\t: Super(ObjectInitializer)\n{\n\tPrimaryComponentTick.bCanEverTick = true;\n}\n\nvoid URTSAttackComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)\n{\n\t\/\/ Update cooldown timer.\n\tif (RemainingCooldown > 0)\n\t{\n\t\tRemainingCooldown -= DeltaTime;\n\n\t\tif (RemainingCooldown <= 0)\n\t\t{\n\t\t\tUE_LOG(LogRTS, Log, TEXT(\"Actor %s attack is ready again.\"), *GetOwner()->GetName());\n\n\t\t\t\/\/ Notify listeners.\n\t\t\tOnCooldownReady.Broadcast();\n\t\t}\n\t}\n}\n\nvoid URTSAttackComponent::UseAttack(int32 AttackIndex, AActor* Target)\n{\n\tAActor* Owner = GetOwner();\n\tAPawn* OwnerPawn = Cast(Owner);\n\tAController* OwnerController = OwnerPawn ? OwnerPawn->GetController() : nullptr;\n\n\tif (!IsValid(Target))\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ Check cooldown.\n\tif (RemainingCooldown > 0)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ Use attack.\n\tUE_LOG(LogRTS, Log, TEXT(\"Actor %s attacks %s.\"), *Owner->GetName(), *Target->GetName());\n\n\tconst FRTSAttackData& Attack = Attacks[0];\n\n\tARTSProjectile* SpawnedProjectile = nullptr;\n\n\tif (Attack.ProjectileClass != nullptr)\n\t{\n\t\t\/\/ Fire projectile.\n\t\t\/\/ Build spawn transform.\n\t\tFVector SpawnLocation = Owner->GetActorLocation();\n\t\tFRotator SpawnRotation = Owner->GetActorRotation();\n\t\tFTransform SpawnTransform = FTransform(SpawnRotation, SpawnLocation);\n\n\t\t\/\/ Build spawn info.\n\t\tFActorSpawnParameters SpawnInfo;\n\t\tSpawnInfo.Instigator = OwnerPawn;\n\t\tSpawnInfo.ObjectFlags |= RF_Transient;\n\n\t\t\/\/ Spawn projectile.\n\t\tSpawnedProjectile = GetWorld()->SpawnActor(Attack.ProjectileClass, SpawnTransform, SpawnInfo);\n\n\t\tif (SpawnedProjectile)\n\t\t{\n\t\t\tUE_LOG(LogRTS, Log, TEXT(\"%s fired projectile %s at target %s.\"), *Owner->GetName(), *SpawnedProjectile->GetName(), *Target->GetName());\n\n\t\t\t\/\/ Aim at target.\n\t\t\tSpawnedProjectile->FireAt(\n\t\t\t\tTarget,\n\t\t\t\tAttack.Damage,\n\t\t\t\tAttack.DamageType,\n\t\t\t\tOwnerController,\n\t\t\t\tOwner);\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ Deal damage immediately.\n\t\tTarget->TakeDamage(Attack.Damage, FDamageEvent(Attack.DamageType), OwnerController, Owner);\n\t}\n\n\t\/\/ Start cooldown timer.\n\tRemainingCooldown = Attack.Cooldown;\n\n\t\/\/ Notify listeners.\n\tOnAttackUsed.Broadcast(Attack, Target, SpawnedProjectile);\n}\n<|endoftext|>"} {"text":"\/\/ $Id$\n\/\/***************************************************************************\n\/\/ File:\n\/\/\tMachineInstr.cpp\n\/\/ \n\/\/ Purpose:\n\/\/\t\n\/\/ \n\/\/ Strategy:\n\/\/ \n\/\/ History:\n\/\/\t7\/2\/01\t - Vikram Adve - Created\n\/\/**************************************************************************\/\n\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/ConstPoolVals.h\"\n#include \"llvm\/Instruction.h\"\n#include \n\n\/\/************************ Class Implementations **************************\/\n\n\/\/ Constructor for instructions with fixed #operands (nearly all)\nMachineInstr::MachineInstr(MachineOpCode _opCode,\n\t\t\t OpCodeMask _opCodeMask)\n : opCode(_opCode),\n opCodeMask(_opCodeMask),\n operands(TargetInstrDescriptors[_opCode].numOperands)\n{\n assert(TargetInstrDescriptors[_opCode].numOperands >= 0);\n}\n\n\/\/ Constructor for instructions with variable #operands\nMachineInstr::MachineInstr(MachineOpCode _opCode,\n\t\t\t unsigned\t numOperands,\n\t\t\t OpCodeMask _opCodeMask)\n : opCode(_opCode),\n opCodeMask(_opCodeMask),\n operands(numOperands)\n{\n}\n\nvoid\nMachineInstr::SetMachineOperand(unsigned int i,\n\t\t\t\tMachineOperand::MachineOperandType operandType,\n\t\t\t\tValue* _val, bool isdef=false)\n{\n assert(i < operands.size());\n operands[i].Initialize(operandType, _val);\n operands[i].isDef = isdef;\n}\n\nvoid\nMachineInstr::SetMachineOperand(unsigned int i,\n\t\t\t\tMachineOperand::MachineOperandType operandType,\n\t\t\t\tint64_t intValue, bool isdef=false)\n{\n assert(i < operands.size());\n operands[i].InitializeConst(operandType, intValue);\n operands[i].isDef = isdef;\n}\n\nvoid\nMachineInstr::SetMachineOperand(unsigned int i,\n\t\t\t\tunsigned int regNum, bool isdef=false)\n{\n assert(i < operands.size());\n operands[i].InitializeReg(regNum);\n operands[i].isDef = isdef;\n}\n\nvoid\nMachineInstr::dump(unsigned int indent) const \n{\n for (unsigned i=0; i < indent; i++)\n cout << \" \";\n \n cout << *this;\n}\n\nostream&\noperator<< (ostream& os, const MachineInstr& minstr)\n{\n os << TargetInstrDescriptors[minstr.opCode].opCodeString;\n \n for (unsigned i=0, N=minstr.getNumOperands(); i < N; i++)\n os << \"\\t\" << minstr.getOperand(i);\n \n#undef DEBUG_VAL_OP_ITERATOR\n#ifdef DEBUG_VAL_OP_ITERATOR\n os << endl << \"\\tValue operands are: \";\n for (MachineInstr::val_op_const_iterator vo(&minstr); ! vo.done(); ++vo)\n {\n const Value* val = *vo;\n os << val << (vo.isDef()? \"(def), \" : \", \");\n }\n os << endl;\n#endif\n \n return os;\n}\n\nostream&\noperator<< (ostream& os, const MachineOperand& mop)\n{\n strstream regInfo;\n if (mop.opType == MachineOperand::MO_VirtualRegister)\n regInfo << \"(val \" << mop.value << \")\" << ends;\n else if (mop.opType == MachineOperand::MO_MachineRegister)\n regInfo << \"(\" << mop.regNum << \")\" << ends;\n else if (mop.opType == MachineOperand::MO_CCRegister)\n regInfo << \"(val \" << mop.value << \")\" << ends;\n \n switch(mop.opType)\n {\n case MachineOperand::MO_VirtualRegister:\n case MachineOperand::MO_MachineRegister:\n os << \"%reg\" << regInfo.str();\n free(regInfo.str());\n break;\n \n case MachineOperand::MO_CCRegister:\n os << \"%ccreg\" << regInfo.str();\n free(regInfo.str());\n break;\n\n case MachineOperand::MO_SignExtendedImmed:\n os << mop.immedVal;\n break;\n\n case MachineOperand::MO_UnextendedImmed:\n os << mop.immedVal;\n break;\n\n case MachineOperand::MO_PCRelativeDisp:\n os << \"%disp(label \" << mop.value << \")\";\n break;\n\n default:\n assert(0 && \"Unrecognized operand type\");\n break;\n }\n\n return os;\n}\n\n\n\/\/---------------------------------------------------------------------------\n\/\/ Target-independent utility routines for creating machine instructions\n\/\/---------------------------------------------------------------------------\n\n\n\/\/------------------------------------------------------------------------ \n\/\/ Function Set2OperandsFromInstr\n\/\/ Function Set3OperandsFromInstr\n\/\/ \n\/\/ For the common case of 2- and 3-operand arithmetic\/logical instructions,\n\/\/ set the m\/c instr. operands directly from the VM instruction's operands.\n\/\/ Check whether the first or second operand is 0 and can use a dedicated \"0\" register.\n\/\/ Check whether the second operand should use an immediate field or register.\n\/\/ (First and third operands are never immediates for such instructions.)\n\/\/ \n\/\/ Arguments:\n\/\/ canDiscardResult: Specifies that the result operand can be discarded\n\/\/\t\t by using the dedicated \"0\"\n\/\/ \n\/\/ op1position, op2position and resultPosition: Specify in which position\n\/\/\t\t in the machine instruction the 3 operands (arg1, arg2\n\/\/\t\t and result) should go.\n\/\/ \n\/\/ RETURN VALUE: unsigned int flags, where\n\/\/\tflags & 0x01\t=> operand 1 is constant and needs a register\n\/\/\tflags & 0x02\t=> operand 2 is constant and needs a register\n\/\/------------------------------------------------------------------------ \n\nvoid\nSet2OperandsFromInstr(MachineInstr* minstr,\n\t\t InstructionNode* vmInstrNode,\n\t\t const TargetMachine& target,\n\t\t bool canDiscardResult,\n\t\t int op1Position,\n\t\t int resultPosition)\n{\n Set3OperandsFromInstr(minstr, vmInstrNode, target,\n\t\t\tcanDiscardResult, op1Position,\n\t\t\t\/*op2Position*\/ -1, resultPosition);\n}\n\n#undef REVERT_TO_EXPLICIT_CONSTANT_CHECKS\n#ifdef REVERT_TO_EXPLICIT_CONSTANT_CHECKS\nunsigned\nSet3OperandsFromInstrJUNK(MachineInstr* minstr,\n\t\t InstructionNode* vmInstrNode,\n\t\t const TargetMachine& target,\n\t\t bool canDiscardResult,\n\t\t int op1Position,\n\t\t int op2Position,\n\t\t int resultPosition)\n{\n assert(op1Position >= 0);\n assert(resultPosition >= 0);\n \n unsigned returnFlags = 0x0;\n \n \/\/ Check if operand 1 is 0 and if so, try to use the register that gives 0, if any.\n Value* op1Value = vmInstrNode->leftChild()->getValue();\n bool isValidConstant;\n int64_t intValue = GetConstantValueAsSignedInt(op1Value, isValidConstant);\n if (isValidConstant && intValue == 0 && target.zeroRegNum >= 0)\n minstr->SetMachineOperand(op1Position, \/*regNum*\/ target.zeroRegNum);\n else\n {\n if (op1Value->getValueType() == Value::ConstantVal)\n\t{\/\/ value is constant and must be loaded from constant pool\n\t returnFlags = returnFlags | (1 << op1Position);\n\t}\n minstr->SetMachineOperand(op1Position,MachineOperand::MO_VirtualRegister,\n\t\t\t\t\t op1Value);\n }\n \n \/\/ Check if operand 2 (if any) fits in the immediate field of the instruction,\n \/\/ of if it is 0 and can use a dedicated machine register\n if (op2Position >= 0)\n {\n Value* op2Value = vmInstrNode->rightChild()->getValue();\n int64_t immedValue;\n unsigned int machineRegNum;\n \n MachineOperand::MachineOperandType\n\top2type = ChooseRegOrImmed(op2Value, minstr->getOpCode(), target,\n\t\t\t\t \/*canUseImmed*\/ true,\n\t\t\t\t machineRegNum, immedValue);\n \n if (op2type == MachineOperand::MO_MachineRegister)\n\tminstr->SetMachineOperand(op2Position, machineRegNum);\n else if (op2type == MachineOperand::MO_VirtualRegister)\n\t{\n\t if (op2Value->getValueType() == Value::ConstantVal)\n\t {\/\/ value is constant and must be loaded from constant pool\n\t returnFlags = returnFlags | (1 << op2Position);\n\t }\n\t minstr->SetMachineOperand(op2Position, op2type, op2Value);\n\t}\n else\n\t{\n\t assert(op2type != MO_CCRegister);\n\t minstr->SetMachineOperand(op2Position, op2type, immedValue);\n\t}\n }\n \n \/\/ If operand 3 (result) can be discarded, use a dead register if one exists\n if (canDiscardResult && target.zeroRegNum >= 0)\n minstr->SetMachineOperand(resultPosition, target.zeroRegNum);\n else\n minstr->SetMachineOperand(resultPosition, MachineOperand::MO_VirtualRegister, vmInstrNode->getValue());\n\n return returnFlags;\n}\n#endif\n\n\nvoid\nSet3OperandsFromInstr(MachineInstr* minstr,\n\t\t InstructionNode* vmInstrNode,\n\t\t const TargetMachine& target,\n\t\t bool canDiscardResult,\n\t\t int op1Position,\n\t\t int op2Position,\n\t\t int resultPosition)\n{\n assert(op1Position >= 0);\n assert(resultPosition >= 0);\n \n \/\/ operand 1\n minstr->SetMachineOperand(op1Position, MachineOperand::MO_VirtualRegister,\n\t\t\t vmInstrNode->leftChild()->getValue()); \n \n \/\/ operand 2 (if any)\n if (op2Position >= 0)\n minstr->SetMachineOperand(op2Position, MachineOperand::MO_VirtualRegister,\n\t\t\t vmInstrNode->rightChild()->getValue()); \n \n \/\/ result operand: if it can be discarded, use a dead register if one exists\n if (canDiscardResult && target.zeroRegNum >= 0)\n minstr->SetMachineOperand(resultPosition, target.zeroRegNum);\n else\n minstr->SetMachineOperand(resultPosition, MachineOperand::MO_VirtualRegister, vmInstrNode->getValue());\n}\n\n\nMachineOperand::MachineOperandType\nChooseRegOrImmed(Value* val,\n\t\t MachineOpCode opCode,\n\t\t const TargetMachine& target,\n\t\t bool canUseImmed,\n\t\t unsigned int& getMachineRegNum,\n\t\t int64_t& getImmedValue)\n{\n MachineOperand::MachineOperandType opType =\n MachineOperand::MO_VirtualRegister;\n getMachineRegNum = 0;\n getImmedValue = 0;\n \n \/\/ Check for the common case first: argument is not constant\n \/\/ \n if (val->getValueType() != Value::ConstantVal)\n return opType;\n \n \/\/ Now get the constant value and check if it fits in the IMMED field.\n \/\/ Take advantage of the fact that the max unsigned value will rarely\n \/\/ fit into any IMMED field and ignore that case (i.e., cast smaller\n \/\/ unsigned constants to signed).\n \/\/ \n bool isValidConstant;\n int64_t intValue = GetConstantValueAsSignedInt(val, isValidConstant);\n \n if (isValidConstant)\n {\n if (intValue == 0 && target.zeroRegNum >= 0)\n\t{\n\t opType = MachineOperand::MO_MachineRegister;\n\t getMachineRegNum = target.zeroRegNum;\n\t}\n else if (canUseImmed &&\n\t target.getInstrInfo().constantFitsInImmedField(opCode,intValue))\n\t{\n\t opType = MachineOperand::MO_SignExtendedImmed;\n\t getImmedValue = intValue;\n\t}\n }\n \n return opType;\n}\nChanged SetMachineOpernad calls in Set3OperandsFromInstr so that the result position is a def (i.e., added true to the end of call) -- Ruchira\/\/ $Id$\n\/\/***************************************************************************\n\/\/ File:\n\/\/\tMachineInstr.cpp\n\/\/ \n\/\/ Purpose:\n\/\/\t\n\/\/ \n\/\/ Strategy:\n\/\/ \n\/\/ History:\n\/\/\t7\/2\/01\t - Vikram Adve - Created\n\/\/**************************************************************************\/\n\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/ConstPoolVals.h\"\n#include \"llvm\/Instruction.h\"\n#include \n\n\/\/************************ Class Implementations **************************\/\n\n\/\/ Constructor for instructions with fixed #operands (nearly all)\nMachineInstr::MachineInstr(MachineOpCode _opCode,\n\t\t\t OpCodeMask _opCodeMask)\n : opCode(_opCode),\n opCodeMask(_opCodeMask),\n operands(TargetInstrDescriptors[_opCode].numOperands)\n{\n assert(TargetInstrDescriptors[_opCode].numOperands >= 0);\n}\n\n\/\/ Constructor for instructions with variable #operands\nMachineInstr::MachineInstr(MachineOpCode _opCode,\n\t\t\t unsigned\t numOperands,\n\t\t\t OpCodeMask _opCodeMask)\n : opCode(_opCode),\n opCodeMask(_opCodeMask),\n operands(numOperands)\n{\n}\n\nvoid\nMachineInstr::SetMachineOperand(unsigned int i,\n\t\t\t\tMachineOperand::MachineOperandType operandType,\n\t\t\t\tValue* _val, bool isdef=false)\n{\n assert(i < operands.size());\n operands[i].Initialize(operandType, _val);\n operands[i].isDef = isdef;\n}\n\nvoid\nMachineInstr::SetMachineOperand(unsigned int i,\n\t\t\t\tMachineOperand::MachineOperandType operandType,\n\t\t\t\tint64_t intValue, bool isdef=false)\n{\n assert(i < operands.size());\n operands[i].InitializeConst(operandType, intValue);\n operands[i].isDef = isdef;\n}\n\nvoid\nMachineInstr::SetMachineOperand(unsigned int i,\n\t\t\t\tunsigned int regNum, bool isdef=false)\n{\n assert(i < operands.size());\n operands[i].InitializeReg(regNum);\n operands[i].isDef = isdef;\n}\n\nvoid\nMachineInstr::dump(unsigned int indent) const \n{\n for (unsigned i=0; i < indent; i++)\n cout << \" \";\n \n cout << *this;\n}\n\nostream&\noperator<< (ostream& os, const MachineInstr& minstr)\n{\n os << TargetInstrDescriptors[minstr.opCode].opCodeString;\n \n for (unsigned i=0, N=minstr.getNumOperands(); i < N; i++)\n os << \"\\t\" << minstr.getOperand(i);\n \n#undef DEBUG_VAL_OP_ITERATOR\n#ifdef DEBUG_VAL_OP_ITERATOR\n os << endl << \"\\tValue operands are: \";\n for (MachineInstr::val_op_const_iterator vo(&minstr); ! vo.done(); ++vo)\n {\n const Value* val = *vo;\n os << val << (vo.isDef()? \"(def), \" : \", \");\n }\n os << endl;\n#endif\n \n return os;\n}\n\nostream&\noperator<< (ostream& os, const MachineOperand& mop)\n{\n strstream regInfo;\n if (mop.opType == MachineOperand::MO_VirtualRegister)\n regInfo << \"(val \" << mop.value << \")\" << ends;\n else if (mop.opType == MachineOperand::MO_MachineRegister)\n regInfo << \"(\" << mop.regNum << \")\" << ends;\n else if (mop.opType == MachineOperand::MO_CCRegister)\n regInfo << \"(val \" << mop.value << \")\" << ends;\n \n switch(mop.opType)\n {\n case MachineOperand::MO_VirtualRegister:\n case MachineOperand::MO_MachineRegister:\n os << \"%reg\" << regInfo.str();\n free(regInfo.str());\n break;\n \n case MachineOperand::MO_CCRegister:\n os << \"%ccreg\" << regInfo.str();\n free(regInfo.str());\n break;\n\n case MachineOperand::MO_SignExtendedImmed:\n os << mop.immedVal;\n break;\n\n case MachineOperand::MO_UnextendedImmed:\n os << mop.immedVal;\n break;\n\n case MachineOperand::MO_PCRelativeDisp:\n os << \"%disp(label \" << mop.value << \")\";\n break;\n\n default:\n assert(0 && \"Unrecognized operand type\");\n break;\n }\n\n return os;\n}\n\n\n\/\/---------------------------------------------------------------------------\n\/\/ Target-independent utility routines for creating machine instructions\n\/\/---------------------------------------------------------------------------\n\n\n\/\/------------------------------------------------------------------------ \n\/\/ Function Set2OperandsFromInstr\n\/\/ Function Set3OperandsFromInstr\n\/\/ \n\/\/ For the common case of 2- and 3-operand arithmetic\/logical instructions,\n\/\/ set the m\/c instr. operands directly from the VM instruction's operands.\n\/\/ Check whether the first or second operand is 0 and can use a dedicated \"0\" register.\n\/\/ Check whether the second operand should use an immediate field or register.\n\/\/ (First and third operands are never immediates for such instructions.)\n\/\/ \n\/\/ Arguments:\n\/\/ canDiscardResult: Specifies that the result operand can be discarded\n\/\/\t\t by using the dedicated \"0\"\n\/\/ \n\/\/ op1position, op2position and resultPosition: Specify in which position\n\/\/\t\t in the machine instruction the 3 operands (arg1, arg2\n\/\/\t\t and result) should go.\n\/\/ \n\/\/ RETURN VALUE: unsigned int flags, where\n\/\/\tflags & 0x01\t=> operand 1 is constant and needs a register\n\/\/\tflags & 0x02\t=> operand 2 is constant and needs a register\n\/\/------------------------------------------------------------------------ \n\nvoid\nSet2OperandsFromInstr(MachineInstr* minstr,\n\t\t InstructionNode* vmInstrNode,\n\t\t const TargetMachine& target,\n\t\t bool canDiscardResult,\n\t\t int op1Position,\n\t\t int resultPosition)\n{\n Set3OperandsFromInstr(minstr, vmInstrNode, target,\n\t\t\tcanDiscardResult, op1Position,\n\t\t\t\/*op2Position*\/ -1, resultPosition);\n}\n\n#undef REVERT_TO_EXPLICIT_CONSTANT_CHECKS\n#ifdef REVERT_TO_EXPLICIT_CONSTANT_CHECKS\nunsigned\nSet3OperandsFromInstrJUNK(MachineInstr* minstr,\n\t\t InstructionNode* vmInstrNode,\n\t\t const TargetMachine& target,\n\t\t bool canDiscardResult,\n\t\t int op1Position,\n\t\t int op2Position,\n\t\t int resultPosition)\n{\n assert(op1Position >= 0);\n assert(resultPosition >= 0);\n \n unsigned returnFlags = 0x0;\n \n \/\/ Check if operand 1 is 0 and if so, try to use the register that gives 0, if any.\n Value* op1Value = vmInstrNode->leftChild()->getValue();\n bool isValidConstant;\n int64_t intValue = GetConstantValueAsSignedInt(op1Value, isValidConstant);\n if (isValidConstant && intValue == 0 && target.zeroRegNum >= 0)\n minstr->SetMachineOperand(op1Position, \/*regNum*\/ target.zeroRegNum);\n else\n {\n if (op1Value->getValueType() == Value::ConstantVal)\n\t{\/\/ value is constant and must be loaded from constant pool\n\t returnFlags = returnFlags | (1 << op1Position);\n\t}\n minstr->SetMachineOperand(op1Position,MachineOperand::MO_VirtualRegister,\n\t\t\t\t\t op1Value);\n }\n \n \/\/ Check if operand 2 (if any) fits in the immediate field of the instruction,\n \/\/ of if it is 0 and can use a dedicated machine register\n if (op2Position >= 0)\n {\n Value* op2Value = vmInstrNode->rightChild()->getValue();\n int64_t immedValue;\n unsigned int machineRegNum;\n \n MachineOperand::MachineOperandType\n\top2type = ChooseRegOrImmed(op2Value, minstr->getOpCode(), target,\n\t\t\t\t \/*canUseImmed*\/ true,\n\t\t\t\t machineRegNum, immedValue);\n \n if (op2type == MachineOperand::MO_MachineRegister)\n\tminstr->SetMachineOperand(op2Position, machineRegNum);\n else if (op2type == MachineOperand::MO_VirtualRegister)\n\t{\n\t if (op2Value->getValueType() == Value::ConstantVal)\n\t {\/\/ value is constant and must be loaded from constant pool\n\t returnFlags = returnFlags | (1 << op2Position);\n\t }\n\t minstr->SetMachineOperand(op2Position, op2type, op2Value);\n\t}\n else\n\t{\n\t assert(op2type != MO_CCRegister);\n\t minstr->SetMachineOperand(op2Position, op2type, immedValue);\n\t}\n }\n \n \/\/ If operand 3 (result) can be discarded, use a dead register if one exists\n if (canDiscardResult && target.zeroRegNum >= 0)\n minstr->SetMachineOperand(resultPosition, target.zeroRegNum, true);\n else\n minstr->SetMachineOperand(resultPosition, MachineOperand::MO_VirtualRegister, vmInstrNode->getValue(), true);\n\n return returnFlags;\n}\n#endif\n\n\nvoid\nSet3OperandsFromInstr(MachineInstr* minstr,\n\t\t InstructionNode* vmInstrNode,\n\t\t const TargetMachine& target,\n\t\t bool canDiscardResult,\n\t\t int op1Position,\n\t\t int op2Position,\n\t\t int resultPosition)\n{\n assert(op1Position >= 0);\n assert(resultPosition >= 0);\n \n \/\/ operand 1\n minstr->SetMachineOperand(op1Position, MachineOperand::MO_VirtualRegister,\n\t\t\t vmInstrNode->leftChild()->getValue()); \n \n \/\/ operand 2 (if any)\n if (op2Position >= 0)\n minstr->SetMachineOperand(op2Position, MachineOperand::MO_VirtualRegister,\n\t\t\t vmInstrNode->rightChild()->getValue()); \n \n \/\/ result operand: if it can be discarded, use a dead register if one exists\n if (canDiscardResult && target.zeroRegNum >= 0)\n minstr->SetMachineOperand(resultPosition, target.zeroRegNum, true);\n else\n minstr->SetMachineOperand(resultPosition, MachineOperand::MO_VirtualRegister, vmInstrNode->getValue(), true);\n}\n\n\nMachineOperand::MachineOperandType\nChooseRegOrImmed(Value* val,\n\t\t MachineOpCode opCode,\n\t\t const TargetMachine& target,\n\t\t bool canUseImmed,\n\t\t unsigned int& getMachineRegNum,\n\t\t int64_t& getImmedValue)\n{\n MachineOperand::MachineOperandType opType =\n MachineOperand::MO_VirtualRegister;\n getMachineRegNum = 0;\n getImmedValue = 0;\n \n \/\/ Check for the common case first: argument is not constant\n \/\/ \n if (val->getValueType() != Value::ConstantVal)\n return opType;\n \n \/\/ Now get the constant value and check if it fits in the IMMED field.\n \/\/ Take advantage of the fact that the max unsigned value will rarely\n \/\/ fit into any IMMED field and ignore that case (i.e., cast smaller\n \/\/ unsigned constants to signed).\n \/\/ \n bool isValidConstant;\n int64_t intValue = GetConstantValueAsSignedInt(val, isValidConstant);\n \n if (isValidConstant)\n {\n if (intValue == 0 && target.zeroRegNum >= 0)\n\t{\n\t opType = MachineOperand::MO_MachineRegister;\n\t getMachineRegNum = target.zeroRegNum;\n\t}\n else if (canUseImmed &&\n\t target.getInstrInfo().constantFitsInImmedField(opCode,intValue))\n\t{\n\t opType = MachineOperand::MO_SignExtendedImmed;\n\t getImmedValue = intValue;\n\t}\n }\n \n return opType;\n}\n<|endoftext|>"} {"text":"\/*\r\n * roimodel.cpp\r\n *\r\n * Created on: 02.02.2013\r\n * @author Ralph Schurade\r\n *\/\r\n#include \"roimodel.h\"\r\n\r\n#include \"models.h\"\r\n\r\n#include \"roibox.h\"\r\n#include \"vptr.h\"\r\n\r\n#include \"..\/gui\/gl\/glfunctions.h\"\r\n\r\n#include \r\n\r\nROIModel::ROIModel() :\r\n m_count( 0 )\r\n{\r\n\r\n}\r\n\r\nROIModel::~ROIModel()\r\n{\r\n}\r\n\r\nint ROIModel::rowCount( const QModelIndex &parent ) const\r\n{\r\n if ( parent.isValid() )\r\n {\r\n if ( (int)parent.internalId() == - 1 )\r\n {\r\n return m_rois[parent.row()].size() - 1;\r\n }\r\n else\r\n {\r\n return 0;\r\n }\r\n }\r\n else\r\n {\r\n return m_rois.size();\r\n }\r\n}\r\n\r\nint ROIModel::columnCount( const QModelIndex &parent ) const\r\n{\r\n return 1;\r\n}\r\n\r\nQModelIndex ROIModel::index( int row, int column, const QModelIndex & parent ) const\r\n{\r\n if ( parent.isValid() )\r\n {\r\n return createIndex( row, column, parent.row() );\r\n }\r\n else\r\n {\r\n return createIndex( row, column, -1 );\r\n }\r\n}\r\n\r\nQModelIndex ROIModel::parent( const QModelIndex & index ) const\r\n{\r\n if ( (int)index.internalId() == -1 )\r\n {\r\n return QModelIndex();\r\n }\r\n else\r\n {\r\n return createIndex( index.internalId(), index.column(), -1 );\r\n }\r\n}\r\n\r\nQVariant ROIModel::data( const QModelIndex &index, int role ) const\r\n{\r\n QVariant roi;\r\n if ( (int)index.internalId() == -1 )\r\n {\r\n if ( index.row() < m_rois.size() )\r\n {\r\n if ( m_rois[index.row()].size() > 0 )\r\n {\r\n roi = m_rois[index.row()][0];\r\n }\r\n }\r\n }\r\n else\r\n {\r\n if ( (int)index.internalId() < m_rois.size() )\r\n {\r\n if ( m_rois[index.internalId()].size() > index.row()+1 )\r\n {\r\n roi = m_rois[index.internalId()][index.row()+1];\r\n }\r\n }\r\n\r\n }\r\n switch ( role )\r\n {\r\n case Qt::CheckStateRole:\r\n {\r\n return VPtr::asPtr( roi )->properties()->get( Fn::Property::D_ACTIVE );\r\n break;\r\n }\r\n case Qt::BackgroundColorRole:\r\n {\r\n return VPtr::asPtr( roi )->properties()->get( Fn::Property::D_COLOR );\r\n break;\r\n }\r\n case Qt::DisplayRole:\r\n {\r\n switch ( (Fn::Property)index.column() )\r\n {\r\n case Fn::Property::D_POINTER:\r\n {\r\n return roi;\r\n break;\r\n }\r\n default:\r\n {\r\n return VPtr::asPtr( roi )->properties()->get( (Fn::Property)index.column() );\r\n break;\r\n }\r\n }\r\n break;\r\n }\r\n default:\r\n break;\r\n }\r\n return QVariant();\r\n}\r\n\r\nQVariant ROIModel::headerData( int section, Qt::Orientation orientation, int role ) const\r\n{\r\n switch ( role )\r\n {\r\n case Qt::DisplayRole:\r\n {\r\n if ( orientation == Qt::Horizontal )\r\n {\r\n return QString( Fn::Prop2String::s( (Fn::Property)section ) );\r\n }\r\n break;\r\n }\r\n }\r\n return QVariant();\r\n}\r\n\r\nbool ROIModel::setData( const QModelIndex &index, const QVariant &value, int role )\r\n{\r\n switch ( role )\r\n {\r\n case Qt::CheckStateRole:\r\n {\r\n if ( (int)index.internalId() == -1 )\r\n {\r\n VPtr::asPtr( m_rois[index.row()][0] )->properties()->set( Fn::Property::D_ACTIVE, !VPtr::asPtr( m_rois[index.row()][0] )->properties()->get( Fn::Property::D_ACTIVE ).toBool() );\r\n }\r\n else\r\n {\r\n VPtr::asPtr( m_rois[index.internalId()][index.row()+1] )->properties()->set( Fn::Property::D_ACTIVE, !VPtr::asPtr( m_rois[index.internalId()][index.row()+1] )->properties()->get( Fn::Property::D_ACTIVE ).toBool() );\r\n }\r\n break;\r\n }\r\n case Qt::DisplayRole:\r\n {\r\n if ( index.column() == (int)Fn::Property::D_POINTER )\r\n {\r\n if ( (int)index.internalId() == -1 )\r\n {\r\n m_rois[index.row()][0] = value;\r\n }\r\n else\r\n {\r\n qDebug() << index.internalId() << index.row()+1;\r\n m_rois[index.internalId()][index.row()+1] = value;\r\n }\r\n\r\n emit( dataChanged( QModelIndex(), QModelIndex() ) );\r\n return true;\r\n }\r\n\r\n if ( index.column() == (int)Fn::Property::D_UPDATED )\r\n {\r\n emit( dataChanged( QModelIndex(), QModelIndex() ) );\r\n return true;\r\n }\r\n if ( (int)index.internalId() == -1 )\r\n {\r\n VPtr::asPtr( m_rois[index.row()][0] )->properties()->set( (Fn::Property)index.column(), value );\r\n }\r\n else\r\n {\r\n VPtr::asPtr( m_rois[index.internalId()][index.row()+1] )->properties()->set( (Fn::Property)index.column(), value );\r\n }\r\n break;\r\n }\r\n }\r\n\r\n emit( dataChanged( index, index ) );\r\n\r\n return true;\r\n}\r\n\r\nQt::ItemFlags ROIModel::flags( const QModelIndex& index ) const\r\n{\r\n if ( !index.isValid() )\r\n {\r\n return Qt::ItemIsEnabled | Qt::ItemIsDropEnabled ;\r\n }\r\n\r\n Qt::ItemFlags defaultFlags = Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDropEnabled;\r\n if ( index.parent().isValid() )\r\n {\r\n defaultFlags |= Qt::ItemIsDragEnabled;\r\n }\r\n else\r\n {\r\n if ( m_rois.size() > index.row() && m_rois[index.row()].size() == 1 )\r\n {\r\n defaultFlags |= Qt::ItemIsDragEnabled;\r\n }\r\n }\r\n\r\n if ( index.column() == 0 )\r\n {\r\n defaultFlags |= Qt::ItemIsUserCheckable;\r\n }\r\n\r\n return defaultFlags;\r\n}\r\n\r\nbool ROIModel::insertRows( int row, int count, const QModelIndex &parent )\r\n{\r\n ROI* newROI;\r\n if ( count == 0 )\r\n {\r\n \/\/newROI = new ROIBox();\r\n newROI = GLFunctions::roi;\r\n }\r\n else\r\n {\r\n return false;\r\n }\r\n connect( newROI, SIGNAL( signalPropChanged( int ) ), this, SLOT( propChanged( int ) ) );\r\n\r\n if ( parent.isValid() )\r\n {\r\n \/\/ child box\r\n if ( parent.parent().isValid() )\r\n {\r\n \/\/ child box selected\r\n beginInsertRows( parent.parent(), m_rois[parent.parent().row()].size(), m_rois[parent.parent().row()].size() );\r\n newROI->properties()->set( Fn::Property::D_COLOR, VPtr::asPtr( m_rois[parent.parent().row()][0] )->properties()->get( Fn::Property::D_COLOR ) );\r\n m_rois[parent.parent().row()].push_back( VPtr::asQVariant( newROI ) );\r\n endInsertRows();\r\n }\r\n else\r\n {\r\n \/\/ top box selected\r\n beginInsertRows( parent, m_rois[parent.row()].size(), m_rois[parent.row()].size() );\r\n newROI->properties()->set( Fn::Property::D_COLOR, VPtr::asPtr( m_rois[parent.row()][0] )->properties()->get( Fn::Property::D_COLOR ) );\r\n m_rois[parent.row()].push_back( VPtr::asQVariant( newROI ) );\r\n endInsertRows();\r\n }\r\n }\r\n else\r\n {\r\n \/\/ nothing selected, insert top box\r\n QListl;\r\n l.push_back( VPtr::asQVariant( newROI ) );\r\n beginInsertRows( QModelIndex(), m_rois.size(), m_rois.size() );\r\n m_rois.push_back( l );\r\n endInsertRows();\r\n\r\n }\r\n emit ( dataChanged( index( 0, 0 ), index( 0, 0 ) ) );\r\n return true;\r\n}\r\n\r\nbool ROIModel::removeRows( int row, int count, const QModelIndex &parent )\r\n{\r\n if ( !parent.isValid() )\r\n {\r\n beginRemoveRows( QModelIndex(), row, row );\r\n m_rois.removeAt( row );\r\n endRemoveRows();\r\n }\r\n else\r\n {\r\n beginRemoveRows( parent, row, row );\r\n m_rois[parent.row()].removeAt( row + 1 );\r\n endRemoveRows();\r\n }\r\n\r\n emit ( dataChanged( QModelIndex(), QModelIndex() ) );\r\n return true;\r\n}\r\n\r\nvoid ROIModel::propChanged( int value )\r\n{\r\n bool found = false;\r\n int ii = -1;\r\n int kk = -1;\r\n for ( int i = 0; i < m_rois.size(); ++i )\r\n {\r\n for ( int k = 0; k < m_rois[i].size(); ++k )\r\n {\r\n if ( value == VPtr::asPtr( m_rois[i][k] )->properties()->get( Fn::Property::D_ID ).toInt() )\r\n {\r\n found = true;\r\n kk = k;\r\n break;\r\n }\r\n }\r\n if ( found )\r\n {\r\n ii = i;\r\n break;\r\n }\r\n }\r\n if ( found )\r\n {\r\n if ( kk == 0 )\r\n {\r\n\r\n QModelIndex parent;\r\n QModelIndex index = this->index( ii, 0, parent );\r\n emit ( dataChanged( index, index ) );\r\n }\r\n else\r\n {\r\n QModelIndex parent = this->index( ii, 0, QModelIndex() );\r\n QModelIndex index = this->index( kk - 1, 0, parent );\r\n emit ( dataChanged( index, index ) );\r\n }\r\n }\r\n}\r\n\r\nQModelIndexList ROIModel::match( const QModelIndex &start, int role, const QVariant &value, int hits, Qt::MatchFlags flags ) const\r\n{\r\n QModelIndexList l;\r\n\r\n if ( role == Qt::DisplayRole )\r\n {\r\n for ( int i = 0; i < m_rois.size(); ++i )\r\n {\r\n for ( int k = 0; k < m_rois[i].size(); ++k )\r\n {\r\n if ( value.toInt() == VPtr::asPtr( m_rois[i][k] )->properties()->get( Fn::Property::D_PICK_ID ).toInt() )\r\n {\r\n if ( k == 0 )\r\n {\r\n l.push_back( createIndex( i, 0, -1 ) );\r\n }\r\n else\r\n {\r\n l.push_back( createIndex( k-1, 0, i ) );\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return l;\r\n}\r\n\r\nROI* ROIModel::getRoi( int branch, int pos )\r\n{\r\n qDebug() << m_rois.size() << m_rois[branch].size() << branch << pos;\r\n if ( branch < m_rois.size() && pos < m_rois[branch].size() )\r\n {\r\n qDebug() << \"huhu\";\r\n return VPtr::asPtr( m_rois[branch][pos] );\r\n }\r\n else\r\n {\r\n return NULL;\r\n }\r\n}\r\nremoved debug messages\/*\r\n * roimodel.cpp\r\n *\r\n * Created on: 02.02.2013\r\n * @author Ralph Schurade\r\n *\/\r\n#include \"roimodel.h\"\r\n\r\n#include \"models.h\"\r\n\r\n#include \"roibox.h\"\r\n#include \"vptr.h\"\r\n\r\n#include \"..\/gui\/gl\/glfunctions.h\"\r\n\r\n#include \r\n\r\nROIModel::ROIModel() :\r\n m_count( 0 )\r\n{\r\n\r\n}\r\n\r\nROIModel::~ROIModel()\r\n{\r\n}\r\n\r\nint ROIModel::rowCount( const QModelIndex &parent ) const\r\n{\r\n if ( parent.isValid() )\r\n {\r\n if ( (int)parent.internalId() == - 1 )\r\n {\r\n return m_rois[parent.row()].size() - 1;\r\n }\r\n else\r\n {\r\n return 0;\r\n }\r\n }\r\n else\r\n {\r\n return m_rois.size();\r\n }\r\n}\r\n\r\nint ROIModel::columnCount( const QModelIndex &parent ) const\r\n{\r\n return 1;\r\n}\r\n\r\nQModelIndex ROIModel::index( int row, int column, const QModelIndex & parent ) const\r\n{\r\n if ( parent.isValid() )\r\n {\r\n return createIndex( row, column, parent.row() );\r\n }\r\n else\r\n {\r\n return createIndex( row, column, -1 );\r\n }\r\n}\r\n\r\nQModelIndex ROIModel::parent( const QModelIndex & index ) const\r\n{\r\n if ( (int)index.internalId() == -1 )\r\n {\r\n return QModelIndex();\r\n }\r\n else\r\n {\r\n return createIndex( index.internalId(), index.column(), -1 );\r\n }\r\n}\r\n\r\nQVariant ROIModel::data( const QModelIndex &index, int role ) const\r\n{\r\n QVariant roi;\r\n if ( (int)index.internalId() == -1 )\r\n {\r\n if ( index.row() < m_rois.size() )\r\n {\r\n if ( m_rois[index.row()].size() > 0 )\r\n {\r\n roi = m_rois[index.row()][0];\r\n }\r\n }\r\n }\r\n else\r\n {\r\n if ( (int)index.internalId() < m_rois.size() )\r\n {\r\n if ( m_rois[index.internalId()].size() > index.row()+1 )\r\n {\r\n roi = m_rois[index.internalId()][index.row()+1];\r\n }\r\n }\r\n\r\n }\r\n switch ( role )\r\n {\r\n case Qt::CheckStateRole:\r\n {\r\n return VPtr::asPtr( roi )->properties()->get( Fn::Property::D_ACTIVE );\r\n break;\r\n }\r\n case Qt::BackgroundColorRole:\r\n {\r\n return VPtr::asPtr( roi )->properties()->get( Fn::Property::D_COLOR );\r\n break;\r\n }\r\n case Qt::DisplayRole:\r\n {\r\n switch ( (Fn::Property)index.column() )\r\n {\r\n case Fn::Property::D_POINTER:\r\n {\r\n return roi;\r\n break;\r\n }\r\n default:\r\n {\r\n return VPtr::asPtr( roi )->properties()->get( (Fn::Property)index.column() );\r\n break;\r\n }\r\n }\r\n break;\r\n }\r\n default:\r\n break;\r\n }\r\n return QVariant();\r\n}\r\n\r\nQVariant ROIModel::headerData( int section, Qt::Orientation orientation, int role ) const\r\n{\r\n switch ( role )\r\n {\r\n case Qt::DisplayRole:\r\n {\r\n if ( orientation == Qt::Horizontal )\r\n {\r\n return QString( Fn::Prop2String::s( (Fn::Property)section ) );\r\n }\r\n break;\r\n }\r\n }\r\n return QVariant();\r\n}\r\n\r\nbool ROIModel::setData( const QModelIndex &index, const QVariant &value, int role )\r\n{\r\n switch ( role )\r\n {\r\n case Qt::CheckStateRole:\r\n {\r\n if ( (int)index.internalId() == -1 )\r\n {\r\n VPtr::asPtr( m_rois[index.row()][0] )->properties()->set( Fn::Property::D_ACTIVE, !VPtr::asPtr( m_rois[index.row()][0] )->properties()->get( Fn::Property::D_ACTIVE ).toBool() );\r\n }\r\n else\r\n {\r\n VPtr::asPtr( m_rois[index.internalId()][index.row()+1] )->properties()->set( Fn::Property::D_ACTIVE, !VPtr::asPtr( m_rois[index.internalId()][index.row()+1] )->properties()->get( Fn::Property::D_ACTIVE ).toBool() );\r\n }\r\n break;\r\n }\r\n case Qt::DisplayRole:\r\n {\r\n if ( index.column() == (int)Fn::Property::D_POINTER )\r\n {\r\n if ( (int)index.internalId() == -1 )\r\n {\r\n m_rois[index.row()][0] = value;\r\n }\r\n else\r\n {\r\n qDebug() << index.internalId() << index.row()+1;\r\n m_rois[index.internalId()][index.row()+1] = value;\r\n }\r\n\r\n emit( dataChanged( QModelIndex(), QModelIndex() ) );\r\n return true;\r\n }\r\n\r\n if ( index.column() == (int)Fn::Property::D_UPDATED )\r\n {\r\n emit( dataChanged( QModelIndex(), QModelIndex() ) );\r\n return true;\r\n }\r\n if ( (int)index.internalId() == -1 )\r\n {\r\n VPtr::asPtr( m_rois[index.row()][0] )->properties()->set( (Fn::Property)index.column(), value );\r\n }\r\n else\r\n {\r\n VPtr::asPtr( m_rois[index.internalId()][index.row()+1] )->properties()->set( (Fn::Property)index.column(), value );\r\n }\r\n break;\r\n }\r\n }\r\n\r\n emit( dataChanged( index, index ) );\r\n\r\n return true;\r\n}\r\n\r\nQt::ItemFlags ROIModel::flags( const QModelIndex& index ) const\r\n{\r\n if ( !index.isValid() )\r\n {\r\n return Qt::ItemIsEnabled | Qt::ItemIsDropEnabled ;\r\n }\r\n\r\n Qt::ItemFlags defaultFlags = Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDropEnabled;\r\n if ( index.parent().isValid() )\r\n {\r\n defaultFlags |= Qt::ItemIsDragEnabled;\r\n }\r\n else\r\n {\r\n if ( m_rois.size() > index.row() && m_rois[index.row()].size() == 1 )\r\n {\r\n defaultFlags |= Qt::ItemIsDragEnabled;\r\n }\r\n }\r\n\r\n if ( index.column() == 0 )\r\n {\r\n defaultFlags |= Qt::ItemIsUserCheckable;\r\n }\r\n\r\n return defaultFlags;\r\n}\r\n\r\nbool ROIModel::insertRows( int row, int count, const QModelIndex &parent )\r\n{\r\n ROI* newROI;\r\n if ( count == 0 )\r\n {\r\n \/\/newROI = new ROIBox();\r\n newROI = GLFunctions::roi;\r\n }\r\n else\r\n {\r\n return false;\r\n }\r\n connect( newROI, SIGNAL( signalPropChanged( int ) ), this, SLOT( propChanged( int ) ) );\r\n\r\n if ( parent.isValid() )\r\n {\r\n \/\/ child box\r\n if ( parent.parent().isValid() )\r\n {\r\n \/\/ child box selected\r\n beginInsertRows( parent.parent(), m_rois[parent.parent().row()].size(), m_rois[parent.parent().row()].size() );\r\n newROI->properties()->set( Fn::Property::D_COLOR, VPtr::asPtr( m_rois[parent.parent().row()][0] )->properties()->get( Fn::Property::D_COLOR ) );\r\n m_rois[parent.parent().row()].push_back( VPtr::asQVariant( newROI ) );\r\n endInsertRows();\r\n }\r\n else\r\n {\r\n \/\/ top box selected\r\n beginInsertRows( parent, m_rois[parent.row()].size(), m_rois[parent.row()].size() );\r\n newROI->properties()->set( Fn::Property::D_COLOR, VPtr::asPtr( m_rois[parent.row()][0] )->properties()->get( Fn::Property::D_COLOR ) );\r\n m_rois[parent.row()].push_back( VPtr::asQVariant( newROI ) );\r\n endInsertRows();\r\n }\r\n }\r\n else\r\n {\r\n \/\/ nothing selected, insert top box\r\n QListl;\r\n l.push_back( VPtr::asQVariant( newROI ) );\r\n beginInsertRows( QModelIndex(), m_rois.size(), m_rois.size() );\r\n m_rois.push_back( l );\r\n endInsertRows();\r\n\r\n }\r\n emit ( dataChanged( index( 0, 0 ), index( 0, 0 ) ) );\r\n return true;\r\n}\r\n\r\nbool ROIModel::removeRows( int row, int count, const QModelIndex &parent )\r\n{\r\n if ( !parent.isValid() )\r\n {\r\n beginRemoveRows( QModelIndex(), row, row );\r\n m_rois.removeAt( row );\r\n endRemoveRows();\r\n }\r\n else\r\n {\r\n beginRemoveRows( parent, row, row );\r\n m_rois[parent.row()].removeAt( row + 1 );\r\n endRemoveRows();\r\n }\r\n\r\n emit ( dataChanged( QModelIndex(), QModelIndex() ) );\r\n return true;\r\n}\r\n\r\nvoid ROIModel::propChanged( int value )\r\n{\r\n bool found = false;\r\n int ii = -1;\r\n int kk = -1;\r\n for ( int i = 0; i < m_rois.size(); ++i )\r\n {\r\n for ( int k = 0; k < m_rois[i].size(); ++k )\r\n {\r\n if ( value == VPtr::asPtr( m_rois[i][k] )->properties()->get( Fn::Property::D_ID ).toInt() )\r\n {\r\n found = true;\r\n kk = k;\r\n break;\r\n }\r\n }\r\n if ( found )\r\n {\r\n ii = i;\r\n break;\r\n }\r\n }\r\n if ( found )\r\n {\r\n if ( kk == 0 )\r\n {\r\n\r\n QModelIndex parent;\r\n QModelIndex index = this->index( ii, 0, parent );\r\n emit ( dataChanged( index, index ) );\r\n }\r\n else\r\n {\r\n QModelIndex parent = this->index( ii, 0, QModelIndex() );\r\n QModelIndex index = this->index( kk - 1, 0, parent );\r\n emit ( dataChanged( index, index ) );\r\n }\r\n }\r\n}\r\n\r\nQModelIndexList ROIModel::match( const QModelIndex &start, int role, const QVariant &value, int hits, Qt::MatchFlags flags ) const\r\n{\r\n QModelIndexList l;\r\n\r\n if ( role == Qt::DisplayRole )\r\n {\r\n for ( int i = 0; i < m_rois.size(); ++i )\r\n {\r\n for ( int k = 0; k < m_rois[i].size(); ++k )\r\n {\r\n if ( value.toInt() == VPtr::asPtr( m_rois[i][k] )->properties()->get( Fn::Property::D_PICK_ID ).toInt() )\r\n {\r\n if ( k == 0 )\r\n {\r\n l.push_back( createIndex( i, 0, -1 ) );\r\n }\r\n else\r\n {\r\n l.push_back( createIndex( k-1, 0, i ) );\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return l;\r\n}\r\n\r\nROI* ROIModel::getRoi( int branch, int pos )\r\n{\r\n if ( branch < m_rois.size() && pos < m_rois[branch].size() )\r\n {\r\n return VPtr::asPtr( m_rois[branch][pos] );\r\n }\r\n else\r\n {\r\n return NULL;\r\n }\r\n}\r\n<|endoftext|>"} {"text":"\/** \n* @file llspeakbutton.cpp\n* @brief LLSpeakButton class implementation\n*\n* $LicenseInfo:firstyear=2002&license=viewergpl$\n* \n* Copyright (c) 2002-2009, Linden Research, Inc.\n* \n* Second Life Viewer Source Code\n* The source code in this file (\"Source Code\") is provided by Linden Lab\n* to you under the terms of the GNU General Public License, version 2.0\n* (\"GPL\"), unless you have obtained a separate licensing agreement\n* (\"Other License\"), formally executed by you and Linden Lab. Terms of\n* the GPL can be found in doc\/GPL-license.txt in this distribution, or\n* online at http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/gplv2\n* \n* There are special exceptions to the terms and conditions of the GPL as\n* it is applied to this Source Code. View the full text of the exception\n* in the file doc\/FLOSS-exception.txt in this software distribution, or\n* online at\n* http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/flossexception\n* \n* By copying, modifying or distributing this software, you acknowledge\n* that you have read and understood your obligations described above,\n* and agree to abide by those obligations.\n* \n* ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n* COMPLETENESS OR PERFORMANCE.\n* $\/LicenseInfo$\n*\/\n\n#include \"llviewerprecompiledheaders.h\" \/\/ must be first include\n\n#include \"llbutton.h\"\n#include \"llfloaterreg.h\"\n\n#include \"llagent.h\"\n#include \"llbottomtray.h\"\n#include \"llcallfloater.h\"\n#include \"lloutputmonitorctrl.h\"\n#include \"lltransientfloatermgr.h\"\n\n#include \"llspeakbutton.h\"\n\nstatic LLDefaultChildRegistry::Register t1(\"talk_button\");\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLLSpeakButton::Params::Params()\n : speak_button(\"speak_button\")\n , show_button(\"show_button\")\n , monitor(\"monitor\")\n{\n\t\/\/ See widgets\/talk_button.xml\n}\n\nvoid LLSpeakButton::draw()\n{\n\t\/\/ gVoiceClient is the authoritative global source of info regarding our open-mic state, we merely reflect that state.\n\tbool openmic = gVoiceClient->getUserPTTState();\n\tmSpeakBtn->setToggleState(openmic);\n\tLLUICtrl::draw();\n}\n\nLLSpeakButton::LLSpeakButton(const Params& p)\n: LLUICtrl(p)\n, mOutputMonitor(NULL)\n, mSpeakBtn(NULL)\n, mShowBtn(NULL)\n{\n\tLLRect rect = p.rect();\n\tLLRect speak_rect(0, rect.getHeight(), rect.getWidth(), 0);\n\tLLRect show_rect = p.show_button.rect();\n\tshow_rect.set(0, rect.getHeight(), show_rect.getWidth(), 0);\n\n\tspeak_rect.mRight -= show_rect.getWidth();\n\tshow_rect.mLeft = speak_rect.getWidth();\n\tshow_rect.mRight = rect.getWidth();\n\n\tLLButton::Params speak_params = p.speak_button;\n\tspeak_params.rect(speak_rect);\n\tmSpeakBtn = LLUICtrlFactory::create(speak_params);\n\taddChild(mSpeakBtn);\n\tLLTransientFloaterMgr::getInstance()->addControlView(mSpeakBtn);\n\n\tmSpeakBtn->setMouseDownCallback(boost::bind(&LLSpeakButton::onMouseDown_SpeakBtn, this));\n\tmSpeakBtn->setMouseUpCallback(boost::bind(&LLSpeakButton::onMouseUp_SpeakBtn, this));\n\tmSpeakBtn->setToggleState(FALSE);\n\n\tLLButton::Params show_params = p.show_button;\n\tshow_params.rect(show_rect);\n\tmShowBtn = LLUICtrlFactory::create(show_params);\n\taddChild(mShowBtn);\n\tLLTransientFloaterMgr::getInstance()->addControlView(mShowBtn);\n\n\/\/ \tmShowBtn->setClickedCallback(boost::bind(&LLSpeakButton::onClick_ShowBtn, this));\n\/\/ \tmShowBtn->setToggleState(FALSE);\n\n\tstatic const S32 MONITOR_RIGHT_PAD = 2;\n\n\tLLRect monitor_rect = p.monitor.rect();\n\tS32 monitor_height = monitor_rect.getHeight();\n\tmonitor_rect.mLeft = speak_rect.getWidth() - monitor_rect.getWidth() - MONITOR_RIGHT_PAD;\n\tmonitor_rect.mRight = speak_rect.getWidth() - MONITOR_RIGHT_PAD;\n\tmonitor_rect.mBottom = (rect.getHeight() \/ 2) - (monitor_height \/ 2);\n\tmonitor_rect.mTop = monitor_rect.mBottom + monitor_height;\n\n\tLLOutputMonitorCtrl::Params monitor_params = p.monitor;\n\tmonitor_params.draw_border(false);\n\tmonitor_params.rect(monitor_rect);\n\tmonitor_params.auto_update(true);\n\tmonitor_params.speaker_id(gAgentID);\n\tmOutputMonitor = LLUICtrlFactory::create(monitor_params);\n\tmSpeakBtn->addChild(mOutputMonitor);\n\n\t\/\/ never show \"muted\" because you can't mute yourself\n\tmOutputMonitor->setIsMuted(false);\n\tmOutputMonitor->setIsAgentControl(true);\n\n\t\/\/*TODO find a better place to do that\n\tLLVoiceChannel::setCurrentVoiceChannelChangedCallback(boost::bind(&LLCallFloater::sOnCurrentChannelChanged, _1));\n}\n\nLLSpeakButton::~LLSpeakButton()\n{\n\tLLTransientFloaterMgr::getInstance()->removeControlView(mSpeakBtn);\n\tLLTransientFloaterMgr::getInstance()->removeControlView(mShowBtn);\n}\n\nvoid LLSpeakButton::setSpeakToolTip(const std::string& msg)\n{\n\tmSpeakBtn->setToolTip(msg);\n}\n\nvoid LLSpeakButton::setShowToolTip(const std::string& msg)\n{\n\tmShowBtn->setToolTip(msg);\n}\n\nvoid LLSpeakButton::setLabelVisible(bool visible)\n{\n\tstatic std::string label_selected = mSpeakBtn->getLabelSelected();\n\tstatic std::string label_unselected = mSpeakBtn->getLabelUnselected();\n\n\tif (visible)\n\t{\n\t\tmSpeakBtn->setLabelSelected(label_selected);\n\t\tmSpeakBtn->setLabelUnselected(label_unselected);\n\t}\n\telse\n\t{\n\t\tstatic LLStringExplicit empty_string(\"\");\n\t\tmSpeakBtn->setLabelSelected(empty_string);\n\t\tmSpeakBtn->setLabelUnselected(empty_string);\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ PROTECTED SECTION\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid LLSpeakButton::onMouseDown_SpeakBtn()\n{\n\tbool down = true;\n\tgVoiceClient->inputUserControlState(down); \/\/ this method knows\/care about whether this translates into a toggle-to-talk or down-to-talk\n}\nvoid LLSpeakButton::onMouseUp_SpeakBtn()\n{\n\tbool down = false;\n\tgVoiceClient->inputUserControlState(down);\n}\n\nDEV-44564 'speak' button PTT-toggles and displays voice monitor even when voice disabled, gives wrong impression that you should be able to talk\/** \n* @file llspeakbutton.cpp\n* @brief LLSpeakButton class implementation\n*\n* $LicenseInfo:firstyear=2002&license=viewergpl$\n* \n* Copyright (c) 2002-2009, Linden Research, Inc.\n* \n* Second Life Viewer Source Code\n* The source code in this file (\"Source Code\") is provided by Linden Lab\n* to you under the terms of the GNU General Public License, version 2.0\n* (\"GPL\"), unless you have obtained a separate licensing agreement\n* (\"Other License\"), formally executed by you and Linden Lab. Terms of\n* the GPL can be found in doc\/GPL-license.txt in this distribution, or\n* online at http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/gplv2\n* \n* There are special exceptions to the terms and conditions of the GPL as\n* it is applied to this Source Code. View the full text of the exception\n* in the file doc\/FLOSS-exception.txt in this software distribution, or\n* online at\n* http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/flossexception\n* \n* By copying, modifying or distributing this software, you acknowledge\n* that you have read and understood your obligations described above,\n* and agree to abide by those obligations.\n* \n* ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n* COMPLETENESS OR PERFORMANCE.\n* $\/LicenseInfo$\n*\/\n\n#include \"llviewerprecompiledheaders.h\" \/\/ must be first include\n\n#include \"llbutton.h\"\n#include \"llfloaterreg.h\"\n\n#include \"llagent.h\"\n#include \"llbottomtray.h\"\n#include \"llcallfloater.h\"\n#include \"lloutputmonitorctrl.h\"\n#include \"lltransientfloatermgr.h\"\n\n#include \"llspeakbutton.h\"\n\nstatic LLDefaultChildRegistry::Register t1(\"talk_button\");\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLLSpeakButton::Params::Params()\n : speak_button(\"speak_button\")\n , show_button(\"show_button\")\n , monitor(\"monitor\")\n{\n\t\/\/ See widgets\/talk_button.xml\n}\n\nvoid LLSpeakButton::draw()\n{\n\t\/\/ gVoiceClient is the authoritative global source of info regarding our open-mic state, we merely reflect that state.\n\tbool openmic = gVoiceClient->getUserPTTState();\n\tbool voiceenabled = gVoiceClient->voiceEnabled();\n\tmSpeakBtn->setToggleState(openmic && voiceenabled);\n\tmOutputMonitor->setIsMuted(!voiceenabled);\n\tLLUICtrl::draw();\n}\n\nLLSpeakButton::LLSpeakButton(const Params& p)\n: LLUICtrl(p)\n, mOutputMonitor(NULL)\n, mSpeakBtn(NULL)\n, mShowBtn(NULL)\n{\n\tLLRect rect = p.rect();\n\tLLRect speak_rect(0, rect.getHeight(), rect.getWidth(), 0);\n\tLLRect show_rect = p.show_button.rect();\n\tshow_rect.set(0, rect.getHeight(), show_rect.getWidth(), 0);\n\n\tspeak_rect.mRight -= show_rect.getWidth();\n\tshow_rect.mLeft = speak_rect.getWidth();\n\tshow_rect.mRight = rect.getWidth();\n\n\tLLButton::Params speak_params = p.speak_button;\n\tspeak_params.rect(speak_rect);\n\tmSpeakBtn = LLUICtrlFactory::create(speak_params);\n\taddChild(mSpeakBtn);\n\tLLTransientFloaterMgr::getInstance()->addControlView(mSpeakBtn);\n\n\tmSpeakBtn->setMouseDownCallback(boost::bind(&LLSpeakButton::onMouseDown_SpeakBtn, this));\n\tmSpeakBtn->setMouseUpCallback(boost::bind(&LLSpeakButton::onMouseUp_SpeakBtn, this));\n\tmSpeakBtn->setToggleState(FALSE);\n\n\tLLButton::Params show_params = p.show_button;\n\tshow_params.rect(show_rect);\n\tmShowBtn = LLUICtrlFactory::create(show_params);\n\taddChild(mShowBtn);\n\tLLTransientFloaterMgr::getInstance()->addControlView(mShowBtn);\n\n\/\/ \tmShowBtn->setClickedCallback(boost::bind(&LLSpeakButton::onClick_ShowBtn, this));\n\/\/ \tmShowBtn->setToggleState(FALSE);\n\n\tstatic const S32 MONITOR_RIGHT_PAD = 2;\n\n\tLLRect monitor_rect = p.monitor.rect();\n\tS32 monitor_height = monitor_rect.getHeight();\n\tmonitor_rect.mLeft = speak_rect.getWidth() - monitor_rect.getWidth() - MONITOR_RIGHT_PAD;\n\tmonitor_rect.mRight = speak_rect.getWidth() - MONITOR_RIGHT_PAD;\n\tmonitor_rect.mBottom = (rect.getHeight() \/ 2) - (monitor_height \/ 2);\n\tmonitor_rect.mTop = monitor_rect.mBottom + monitor_height;\n\n\tLLOutputMonitorCtrl::Params monitor_params = p.monitor;\n\tmonitor_params.draw_border(false);\n\tmonitor_params.rect(monitor_rect);\n\tmonitor_params.auto_update(true);\n\tmonitor_params.speaker_id(gAgentID);\n\tmOutputMonitor = LLUICtrlFactory::create(monitor_params);\n\tmSpeakBtn->addChild(mOutputMonitor);\n\n\t\/\/ never show \"muted\" because you can't mute yourself\n\tmOutputMonitor->setIsMuted(false);\n\tmOutputMonitor->setIsAgentControl(true);\n\n\t\/\/*TODO find a better place to do that\n\tLLVoiceChannel::setCurrentVoiceChannelChangedCallback(boost::bind(&LLCallFloater::sOnCurrentChannelChanged, _1));\n}\n\nLLSpeakButton::~LLSpeakButton()\n{\n\tLLTransientFloaterMgr::getInstance()->removeControlView(mSpeakBtn);\n\tLLTransientFloaterMgr::getInstance()->removeControlView(mShowBtn);\n}\n\nvoid LLSpeakButton::setSpeakToolTip(const std::string& msg)\n{\n\tmSpeakBtn->setToolTip(msg);\n}\n\nvoid LLSpeakButton::setShowToolTip(const std::string& msg)\n{\n\tmShowBtn->setToolTip(msg);\n}\n\nvoid LLSpeakButton::setLabelVisible(bool visible)\n{\n\tstatic std::string label_selected = mSpeakBtn->getLabelSelected();\n\tstatic std::string label_unselected = mSpeakBtn->getLabelUnselected();\n\n\tif (visible)\n\t{\n\t\tmSpeakBtn->setLabelSelected(label_selected);\n\t\tmSpeakBtn->setLabelUnselected(label_unselected);\n\t}\n\telse\n\t{\n\t\tstatic LLStringExplicit empty_string(\"\");\n\t\tmSpeakBtn->setLabelSelected(empty_string);\n\t\tmSpeakBtn->setLabelUnselected(empty_string);\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ PROTECTED SECTION\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid LLSpeakButton::onMouseDown_SpeakBtn()\n{\n\tbool down = true;\n\tgVoiceClient->inputUserControlState(down); \/\/ this method knows\/care about whether this translates into a toggle-to-talk or down-to-talk\n}\nvoid LLSpeakButton::onMouseUp_SpeakBtn()\n{\n\tbool down = false;\n\tgVoiceClient->inputUserControlState(down);\n}\n\n<|endoftext|>"} {"text":"p9_htm_setup (L2) - Part 2: HTM setup\/reset\/start<|endoftext|>"} {"text":"#ifdef _WIN32\n#include \n#else\n#include \n#endif\n\n#include \"sass_interface.h\"\n#include \"context.hpp\"\n#include \"inspect.hpp\"\n\n#ifndef SASS_ERROR_HANDLING\n#include \"error_handling.hpp\"\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nextern \"C\" {\n using namespace std;\n\n sass_context* sass_new_context()\n { return (sass_context*) calloc(1, sizeof(sass_context)); }\n\n void free_string_array(char ** arr, int num) {\n if(!arr)\n return;\n\n for(int i = 0; i < num; i++) {\n free(arr[i]);\n }\n\n free(arr);\n }\n\n void sass_free_context(sass_context* ctx)\n {\n if (ctx->output_string) free(ctx->output_string);\n if (ctx->source_map_string) free(ctx->source_map_string);\n if (ctx->error_message) free(ctx->error_message);\n if (ctx->c_functions) free(ctx->c_functions);\n\n free_string_array(ctx->included_files, ctx->num_included_files);\n\n free(ctx);\n }\n\n sass_file_context* sass_new_file_context()\n { return (sass_file_context*) calloc(1, sizeof(sass_file_context)); }\n\n void sass_free_file_context(sass_file_context* ctx)\n {\n if (ctx->output_string) free(ctx->output_string);\n if (ctx->source_map_string) free(ctx->source_map_string);\n if (ctx->error_message) free(ctx->error_message);\n if (ctx->c_functions) free(ctx->c_functions);\n\n free_string_array(ctx->included_files, ctx->num_included_files);\n\n free(ctx);\n }\n\n sass_folder_context* sass_new_folder_context()\n { return (sass_folder_context*) calloc(1, sizeof(sass_folder_context)); }\n\n void sass_free_folder_context(sass_folder_context* ctx)\n {\n free_string_array(ctx->included_files, ctx->num_included_files);\n free(ctx);\n }\n\n void copy_strings(const std::vector& strings, char*** array, int* n, int skip = 0) {\n int num = static_cast(strings.size());\n char** arr = (char**) malloc(sizeof(char*)* num);\n\n for(int i = skip; i < num; i++) {\n arr[i-skip] = (char*) malloc(sizeof(char) * strings[i].size() + 1);\n std::copy(strings[i].begin(), strings[i].end(), arr[i-skip]);\n arr[i-skip][strings[i].size()] = '\\0';\n }\n\n *array = arr;\n *n = num - skip;\n }\n\n \/\/ helper for safe access to c_ctx\n const char* safe_str (const char* str) {\n return str == NULL ? \"\" : str;\n }\n\n int sass_compile(sass_context* c_ctx)\n {\n using namespace Sass;\n try {\n string input_path = safe_str(c_ctx->input_path);\n int lastindex = static_cast(input_path.find_last_of(\".\"));\n string output_path;\n if (!c_ctx->output_path) {\n if (input_path != \"\") {\n output_path = (lastindex > -1 ? input_path.substr(0, lastindex) : input_path) + \".css\";\n }\n }\n else {\n output_path = c_ctx->output_path;\n }\n Context cpp_ctx(\n Context::Data().source_c_str(c_ctx->source_string)\n .output_path(output_path)\n .output_style((Output_Style) c_ctx->options.output_style)\n .is_indented_syntax_src(c_ctx->options.is_indented_syntax_src)\n .source_comments(c_ctx->options.source_comments)\n .source_map_file(safe_str(c_ctx->options.source_map_file))\n .omit_source_map_url(c_ctx->options.omit_source_map_url)\n .image_path(safe_str(c_ctx->options.image_path))\n .include_paths_c_str(c_ctx->options.include_paths)\n .include_paths_array(0)\n .include_paths(vector())\n .precision(c_ctx->options.precision ? c_ctx->options.precision : 5)\n );\n if (c_ctx->c_functions) {\n struct Sass_C_Function_Descriptor* this_func_data = c_ctx->c_functions;\n while (this_func_data->signature && this_func_data->function) {\n cpp_ctx.c_functions.push_back(*this_func_data);\n ++this_func_data;\n }\n }\n \/\/ by checking c_ctx->input_path, implementors can pass in an empty string\n c_ctx->output_string = c_ctx->input_path ? cpp_ctx.compile_string(input_path) :\n cpp_ctx.compile_string();\n c_ctx->source_map_string = cpp_ctx.generate_source_map();\n c_ctx->error_message = 0;\n c_ctx->error_status = 0;\n\n copy_strings(cpp_ctx.get_included_files(), &c_ctx->included_files, &c_ctx->num_included_files, 1);\n }\n catch (Error& e) {\n stringstream msg_stream;\n msg_stream << e.path << \":\" << e.position.line << \": \" << e.message << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch(bad_alloc& ba) {\n stringstream msg_stream;\n msg_stream << \"Unable to allocate memory: \" << ba.what() << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch (std::exception& e) {\n stringstream msg_stream;\n msg_stream << \"Error: \" << e.what() << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch (string& e) {\n stringstream msg_stream;\n msg_stream << \"Error: \" << e << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch (...) {\n \/\/ couldn't find the specified file in the include paths; report an error\n stringstream msg_stream;\n msg_stream << \"Unknown error occurred\" << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n return 0;\n }\n\n int sass_compile_file(sass_file_context* c_ctx)\n {\n using namespace Sass;\n try {\n string input_path = safe_str(c_ctx->input_path);\n int lastindex = static_cast(input_path.find_last_of(\".\"));\n string output_path;\n if (!c_ctx->output_path) {\n output_path = (lastindex > -1 ? input_path.substr(0, lastindex) : input_path) + \".css\";\n }\n else {\n output_path = c_ctx->output_path;\n }\n Context cpp_ctx(\n Context::Data().entry_point(input_path)\n .output_path(output_path)\n .output_style((Output_Style) c_ctx->options.output_style)\n .source_comments(c_ctx->options.source_comments)\n .source_map_file(safe_str(c_ctx->options.source_map_file))\n .source_map_embed(c_ctx->options.source_map_embed)\n .source_map_contents(c_ctx->options.source_map_contents)\n .omit_source_map_url(c_ctx->options.omit_source_map_url)\n .image_path(safe_str(c_ctx->options.image_path))\n .include_paths_c_str(c_ctx->options.include_paths)\n .include_paths_array(0)\n .include_paths(vector())\n .precision(c_ctx->options.precision ? c_ctx->options.precision : 5)\n );\n if (c_ctx->c_functions) {\n struct Sass_C_Function_Descriptor* this_func_data = c_ctx->c_functions;\n while (this_func_data->signature && this_func_data->function) {\n cpp_ctx.c_functions.push_back(*this_func_data);\n ++this_func_data;\n }\n }\n c_ctx->output_string = cpp_ctx.compile_file();\n c_ctx->source_map_string = cpp_ctx.generate_source_map();\n c_ctx->error_message = 0;\n c_ctx->error_status = 0;\n\n copy_strings(cpp_ctx.get_included_files(), &c_ctx->included_files, &c_ctx->num_included_files);\n }\n catch (Error& e) {\n stringstream msg_stream;\n msg_stream << e.path << \":\" << e.position.line << \": \" << e.message << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch(bad_alloc& ba) {\n stringstream msg_stream;\n msg_stream << \"Unable to allocate memory: \" << ba.what() << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch (std::exception& e) {\n stringstream msg_stream;\n msg_stream << \"Error: \" << e.what() << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch (string& e) {\n stringstream msg_stream;\n msg_stream << \"Error: \" << e << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch (...) {\n \/\/ couldn't find the specified file in the include paths; report an error\n stringstream msg_stream;\n msg_stream << \"Unknown error occurred\" << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n return 0;\n }\n\n int sass_compile_folder(sass_folder_context* c_ctx)\n {\n return 1;\n }\n\n \/\/ caller must free the returned memory\n char* quote (const char *str, const char quotemark) {\n string quoted = Sass::quote(str, quotemark);\n char *cstr = (char*) malloc(quoted.length() + 1);\n std::strcpy(cstr, quoted.c_str());\n return cstr;\n }\n\n \/\/ caller must free the returned memory\n char* unquote (const char *str) {\n string unquoted = Sass::unquote(str);\n char *cstr = (char*) malloc(unquoted.length() + 1);\n std::strcpy(cstr, unquoted.c_str());\n return cstr;\n }\n\n}\nAdds missing options on sass_interfaces#ifdef _WIN32\n#include \n#else\n#include \n#endif\n\n#include \"sass_interface.h\"\n#include \"context.hpp\"\n#include \"inspect.hpp\"\n\n#ifndef SASS_ERROR_HANDLING\n#include \"error_handling.hpp\"\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nextern \"C\" {\n using namespace std;\n\n sass_context* sass_new_context()\n { return (sass_context*) calloc(1, sizeof(sass_context)); }\n\n void free_string_array(char ** arr, int num) {\n if(!arr)\n return;\n\n for(int i = 0; i < num; i++) {\n free(arr[i]);\n }\n\n free(arr);\n }\n\n void sass_free_context(sass_context* ctx)\n {\n if (ctx->output_string) free(ctx->output_string);\n if (ctx->source_map_string) free(ctx->source_map_string);\n if (ctx->error_message) free(ctx->error_message);\n if (ctx->c_functions) free(ctx->c_functions);\n\n free_string_array(ctx->included_files, ctx->num_included_files);\n\n free(ctx);\n }\n\n sass_file_context* sass_new_file_context()\n { return (sass_file_context*) calloc(1, sizeof(sass_file_context)); }\n\n void sass_free_file_context(sass_file_context* ctx)\n {\n if (ctx->output_string) free(ctx->output_string);\n if (ctx->source_map_string) free(ctx->source_map_string);\n if (ctx->error_message) free(ctx->error_message);\n if (ctx->c_functions) free(ctx->c_functions);\n\n free_string_array(ctx->included_files, ctx->num_included_files);\n\n free(ctx);\n }\n\n sass_folder_context* sass_new_folder_context()\n { return (sass_folder_context*) calloc(1, sizeof(sass_folder_context)); }\n\n void sass_free_folder_context(sass_folder_context* ctx)\n {\n free_string_array(ctx->included_files, ctx->num_included_files);\n free(ctx);\n }\n\n void copy_strings(const std::vector& strings, char*** array, int* n, int skip = 0) {\n int num = static_cast(strings.size());\n char** arr = (char**) malloc(sizeof(char*)* num);\n\n for(int i = skip; i < num; i++) {\n arr[i-skip] = (char*) malloc(sizeof(char) * strings[i].size() + 1);\n std::copy(strings[i].begin(), strings[i].end(), arr[i-skip]);\n arr[i-skip][strings[i].size()] = '\\0';\n }\n\n *array = arr;\n *n = num - skip;\n }\n\n \/\/ helper for safe access to c_ctx\n const char* safe_str (const char* str) {\n return str == NULL ? \"\" : str;\n }\n\n int sass_compile(sass_context* c_ctx)\n {\n using namespace Sass;\n try {\n string input_path = safe_str(c_ctx->input_path);\n int lastindex = static_cast(input_path.find_last_of(\".\"));\n string output_path;\n if (!c_ctx->output_path) {\n if (input_path != \"\") {\n output_path = (lastindex > -1 ? input_path.substr(0, lastindex) : input_path) + \".css\";\n }\n }\n else {\n output_path = c_ctx->output_path;\n }\n Context cpp_ctx(\n Context::Data().source_c_str(c_ctx->source_string)\n .output_path(output_path)\n .output_style((Output_Style) c_ctx->options.output_style)\n .is_indented_syntax_src(c_ctx->options.is_indented_syntax_src)\n .source_comments(c_ctx->options.source_comments)\n .source_map_file(safe_str(c_ctx->options.source_map_file))\n .source_map_embed(c_ctx->options.source_map_embed)\n .source_map_contents(c_ctx->options.source_map_contents)\n .omit_source_map_url(c_ctx->options.omit_source_map_url)\n .image_path(safe_str(c_ctx->options.image_path))\n .include_paths_c_str(c_ctx->options.include_paths)\n .include_paths_array(0)\n .include_paths(vector())\n .precision(c_ctx->options.precision ? c_ctx->options.precision : 5)\n );\n if (c_ctx->c_functions) {\n struct Sass_C_Function_Descriptor* this_func_data = c_ctx->c_functions;\n while (this_func_data->signature && this_func_data->function) {\n cpp_ctx.c_functions.push_back(*this_func_data);\n ++this_func_data;\n }\n }\n \/\/ by checking c_ctx->input_path, implementors can pass in an empty string\n c_ctx->output_string = c_ctx->input_path ? cpp_ctx.compile_string(input_path) :\n cpp_ctx.compile_string();\n c_ctx->source_map_string = cpp_ctx.generate_source_map();\n c_ctx->error_message = 0;\n c_ctx->error_status = 0;\n\n copy_strings(cpp_ctx.get_included_files(), &c_ctx->included_files, &c_ctx->num_included_files, 1);\n }\n catch (Error& e) {\n stringstream msg_stream;\n msg_stream << e.path << \":\" << e.position.line << \": \" << e.message << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch(bad_alloc& ba) {\n stringstream msg_stream;\n msg_stream << \"Unable to allocate memory: \" << ba.what() << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch (std::exception& e) {\n stringstream msg_stream;\n msg_stream << \"Error: \" << e.what() << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch (string& e) {\n stringstream msg_stream;\n msg_stream << \"Error: \" << e << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch (...) {\n \/\/ couldn't find the specified file in the include paths; report an error\n stringstream msg_stream;\n msg_stream << \"Unknown error occurred\" << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n return 0;\n }\n\n int sass_compile_file(sass_file_context* c_ctx)\n {\n using namespace Sass;\n try {\n string input_path = safe_str(c_ctx->input_path);\n int lastindex = static_cast(input_path.find_last_of(\".\"));\n string output_path;\n if (!c_ctx->output_path) {\n output_path = (lastindex > -1 ? input_path.substr(0, lastindex) : input_path) + \".css\";\n }\n else {\n output_path = c_ctx->output_path;\n }\n Context cpp_ctx(\n Context::Data().entry_point(input_path)\n .output_path(output_path)\n .output_style((Output_Style) c_ctx->options.output_style)\n .is_indented_syntax_src(c_ctx->options.is_indented_syntax_src)\n .source_comments(c_ctx->options.source_comments)\n .source_map_file(safe_str(c_ctx->options.source_map_file))\n .source_map_embed(c_ctx->options.source_map_embed)\n .source_map_contents(c_ctx->options.source_map_contents)\n .omit_source_map_url(c_ctx->options.omit_source_map_url)\n .image_path(safe_str(c_ctx->options.image_path))\n .include_paths_c_str(c_ctx->options.include_paths)\n .include_paths_array(0)\n .include_paths(vector())\n .precision(c_ctx->options.precision ? c_ctx->options.precision : 5)\n );\n if (c_ctx->c_functions) {\n struct Sass_C_Function_Descriptor* this_func_data = c_ctx->c_functions;\n while (this_func_data->signature && this_func_data->function) {\n cpp_ctx.c_functions.push_back(*this_func_data);\n ++this_func_data;\n }\n }\n c_ctx->output_string = cpp_ctx.compile_file();\n c_ctx->source_map_string = cpp_ctx.generate_source_map();\n c_ctx->error_message = 0;\n c_ctx->error_status = 0;\n\n copy_strings(cpp_ctx.get_included_files(), &c_ctx->included_files, &c_ctx->num_included_files);\n }\n catch (Error& e) {\n stringstream msg_stream;\n msg_stream << e.path << \":\" << e.position.line << \": \" << e.message << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch(bad_alloc& ba) {\n stringstream msg_stream;\n msg_stream << \"Unable to allocate memory: \" << ba.what() << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch (std::exception& e) {\n stringstream msg_stream;\n msg_stream << \"Error: \" << e.what() << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch (string& e) {\n stringstream msg_stream;\n msg_stream << \"Error: \" << e << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n catch (...) {\n \/\/ couldn't find the specified file in the include paths; report an error\n stringstream msg_stream;\n msg_stream << \"Unknown error occurred\" << endl;\n c_ctx->error_message = strdup(msg_stream.str().c_str());\n c_ctx->error_status = 1;\n c_ctx->output_string = 0;\n c_ctx->source_map_string = 0;\n }\n return 0;\n }\n\n int sass_compile_folder(sass_folder_context* c_ctx)\n {\n return 1;\n }\n\n \/\/ caller must free the returned memory\n char* quote (const char *str, const char quotemark) {\n string quoted = Sass::quote(str, quotemark);\n char *cstr = (char*) malloc(quoted.length() + 1);\n std::strcpy(cstr, quoted.c_str());\n return cstr;\n }\n\n \/\/ caller must free the returned memory\n char* unquote (const char *str) {\n string unquoted = Sass::unquote(str);\n char *cstr = (char*) malloc(unquoted.length() + 1);\n std::strcpy(cstr, unquoted.c_str());\n return cstr;\n }\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\nFunction::Function() {\n _head = NULL;\n _end = NULL;\n BB_computed = false;\n BB_pred_succ = false;\n dom_computed = false;\n}\n\nFunction::~Function() {}\n\nvoid Function::set_head(Line *head) { _head = head; }\n\nvoid Function::set_end(Line *end) { _end = end; }\n\nLine *Function::get_head() { return _head; }\n\nBasic_block *Function::get_firstBB() { return _myBB.front(); }\n\nLine *Function::get_end() { return _end; }\nvoid Function::display() {\n cout << \"Begin Function\" << endl;\n Line *element = _head;\n\n if (element == _end)\n cout << _head->get_content() << endl;\n\n while (element != _end) {\n cout << element->get_content() << endl;\n\n if (element->get_next() == _end) {\n cout << element->get_next()->get_content() << endl;\n break;\n } else\n element = element->get_next();\n }\n cout << \"End Function\\n\\n\" << endl;\n}\n\nint Function::size() {\n Line *element = _head;\n int lenght = 0;\n while (element != _end) {\n lenght++;\n if (element->get_next() == _end)\n break;\n else\n element = element->get_next();\n }\n return lenght;\n}\n\nvoid Function::restitution(string const filename) {\n\n Line *element = _head;\n ofstream monflux(filename.c_str(), ios::app);\n\n if (monflux) {\n monflux << \"Begin\" << endl;\n if (element == _end)\n monflux << _head->get_content() << endl;\n while (element != _end) {\n if (element->isInst() || element->isDirective())\n monflux << \"\\t\";\n\n monflux << element->get_content();\n\n if (element->get_content().compare(\"nop\"))\n monflux << endl;\n\n if (element->get_next() == _end) {\n if (element->get_next()->isInst() || element->get_next()->isDirective())\n monflux << \"\\t\";\n monflux << element->get_next()->get_content() << endl;\n break;\n } else\n element = element->get_next();\n }\n monflux << \"End\\n\\n\" << endl;\n\n }\n\n else {\n cout << \"Error cannot open the file\" << endl;\n }\n\n monflux.close();\n}\n\nvoid Function::comput_label() {\n Line *element = _head;\n\n if (element == _end && element->isLabel())\n _list_lab.push_back(getLabel(element));\n while (element != _end) {\n\n if (element->isLabel())\n _list_lab.push_back(getLabel(element));\n\n if (element->get_next() == _end) {\n if (element->isLabel())\n _list_lab.push_back(getLabel(element));\n break;\n } else\n element = element->get_next();\n }\n}\n\nint Function::nbr_label() { return _list_lab.size(); }\n\nLabel *Function::get_label(int index) {\n\n list

\\n\\n\\n
\\n
\\n1\\n\";\n\t\tstring input, tmp;\n\t\tgetline(file, input);\n\t\tunsigned line=1;\n\t\twhile(file.good())\n\t\t{\n\t\t\tcout << ++line << '\\n';\n\t\t\tinput+='\\n';\n\t\t\tgetline(file, tmp);\n\t\t\tinput+=tmp;\n\t\t}\n\t\tcout << \"<\/pre>\\n<\/td>\\n
\\n
\\n\";\n\t\tcoloring::color_code(input, cout);\n\t\tcout << \"<\/pre><\/td><\/tr><\/tbody><\/table>\";\n\t}\n\telse cout << \"Cannot open file\" << endl;\nreturn 0;\n}Little 'const'#include \"main.hpp\"\n\nconst bool is_name[256]={false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false},\n\tis_true_name[256]={false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true,true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false};\n\nint main(int argc, char const **argv)\n{\n\tios_base::sync_with_stdio(false);\n\tif(argc<2)\n\t{\n\t\tcerr << \"Usage:\\ncr \" << endl;\n\t\treturn 1;\n\t}\n\tstring file_name=argv[1];\n\t\/\/ cin >> file_name;\n\tfstream file(file_name.c_str(), ios::in);\n\tif(file.good())\n\t{\n\t\tcoloring::init();\n\t\t\/\/ fstream out((file_name+\".html\").c_str(), ios::out);\n\t\tcout << \"\\n\\n\\n
\\n
\\n1\\n\";\n\t\tstring input, tmp;\n\t\tgetline(file, input);\n\t\tunsigned line=1;\n\t\twhile(file.good())\n\t\t{\n\t\t\tcout << ++line << '\\n';\n\t\t\tinput+='\\n';\n\t\t\tgetline(file, tmp);\n\t\t\tinput+=tmp;\n\t\t}\n\t\tcout << \"<\/pre>\\n<\/td>\\n
\\n
\\n\";\n\t\tcoloring::color_code(input, cout);\n\t\tcout << \"<\/pre><\/td><\/tr><\/tbody><\/table>\";\n\t}\n\telse cout << \"Cannot open file\" << endl;\nreturn 0;\n}<|endoftext|>"}
{"text":"\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing boost::posix_time::ptime;\nusing boost::posix_time::time_duration;\nusing boost::posix_time::microsec_clock;\nusing boost::posix_time::seconds;\nusing boost::posix_time::milliseconds;\nusing boost::shared_ptr;\nusing boost::bind;\n\nnamespace libtorrent { namespace dht\n{\n\nnamespace io = libtorrent::detail;\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\nTORRENT_DEFINE_LOG(rpc)\n#endif\n\nnode_id generate_id();\n\nrpc_manager::rpc_manager(fun const& f, node_id const& our_id\n\t, routing_table& table, send_fun const& sf)\n\t: m_next_transaction_id(rand() % max_transactions)\n\t, m_oldest_transaction_id(m_next_transaction_id)\n\t, m_incoming(f)\n\t, m_send(sf)\n\t, m_our_id(our_id)\n\t, m_table(table)\n\t, m_timer(boost::posix_time::microsec_clock::universal_time())\n\t, m_random_number(generate_id())\n\t, m_destructing(false)\n{\n\tstd::srand(time(0));\n}\n\nrpc_manager::~rpc_manager()\n{\n\tm_destructing = true;\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\tTORRENT_LOG(rpc) << \"Destructing\";\n#endif\n\tstd::for_each(m_aborted_transactions.begin(), m_aborted_transactions.end()\n\t\t, bind(&observer::abort, _1));\n\t\n\tfor (transactions_t::iterator i = m_transactions.begin()\n\t\t, end(m_transactions.end()); i != end; ++i)\n\t{\n\t\tif (*i) (*i)->abort();\n\t}\n}\n\n#ifndef NDEBUG\nvoid rpc_manager::check_invariant() const\n{\n\tassert(m_oldest_transaction_id >= 0);\n\tassert(m_oldest_transaction_id < max_transactions);\n\tassert(m_next_transaction_id >= 0);\n\tassert(m_next_transaction_id < max_transactions);\n\tassert(!m_transactions[m_next_transaction_id]);\n\n\tfor (int i = (m_next_transaction_id + 1) % max_transactions;\n\t\ti != m_oldest_transaction_id; i = (i + 1) % max_transactions)\n\t{\n\t\tassert(!m_transactions[i]);\n\t}\n}\n#endif\n\nbool rpc_manager::incoming(msg const& m)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return false;\n\n\tif (m.reply)\n\t{\n\t\t\/\/ if we don't have the transaction id in our\n\t\t\/\/ request list, ignore the packet\n\n\t\tif (m.transaction_id.size() != 2)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with invalid transaction id size: \" \n\t\t\t\t<< m.transaction_id.size() << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\n\t\tstd::string::const_iterator i = m.transaction_id.begin();\t\n\t\tint tid = io::read_uint16(i);\n\n\t\tif (tid >= (int)m_transactions.size()\n\t\t\t|| tid < 0)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with unknown transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tboost::shared_ptr o = m_transactions[tid];\n\n\t\tif (!o)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with unknown transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif (m.addr != o->target_addr)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with incorrect address and valid transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tstd::ofstream reply_stats(\"libtorrent_logs\/round_trip_ms.log\", std::ios::app);\n\t\treply_stats << m.addr << \"\\t\" << (microsec_clock::universal_time()\n\t\t\t- o->sent).total_milliseconds() << std::endl;\n#endif\n\t\to->reply(m);\n\t\tm_transactions[tid].reset();\n\t\t\n\t\tif (m.piggy_backed_ping)\n\t\t{\n\t\t\t\/\/ there is a ping request piggy\n\t\t\t\/\/ backed in this reply\n\t\t\tmsg ph;\n\t\t\tph.message_id = messages::ping;\n\t\t\tph.transaction_id = m.ping_transaction_id;\n\t\t\tph.id = m_our_id;\n\t\t\tph.addr = m.addr;\n\n\t\t\tmsg empty;\n\t\t\t\n\t\t\treply(empty, ph);\n\t\t}\n\t\treturn m_table.node_seen(m.id, m.addr);\n\t}\n\telse\n\t{\n\t\t\/\/ this is an incoming request\n\t\tm_incoming(m);\n\t}\n\treturn false;\n}\n\ntime_duration rpc_manager::tick()\n{\n\tINVARIANT_CHECK;\n\n\tusing boost::posix_time::microsec_clock;\n\n\tconst int timeout_ms = 20 * 1000;\n\n\t\/\/\tlook for observers that has timed out\n\n\tif (m_next_transaction_id == m_oldest_transaction_id) return milliseconds(timeout_ms);\n\n\tstd::vector > timeouts;\n\n\tfor (;m_next_transaction_id != m_oldest_transaction_id;\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions)\n\t{\n\t\tassert(m_oldest_transaction_id >= 0);\n\t\tassert(m_oldest_transaction_id < max_transactions);\n\n\t\tboost::shared_ptr o = m_transactions[m_oldest_transaction_id];\n\t\tif (!o) continue;\n\n\t\ttime_duration diff = o->sent + milliseconds(timeout_ms)\n\t\t\t- microsec_clock::universal_time();\n\t\tif (diff > seconds(0))\n\t\t{\n\t\t\tif (diff < seconds(1)) return seconds(1);\n\t\t\treturn diff;\n\t\t}\n\t\t\n\t\ttry\n\t\t{\n\t\t\tm_transactions[m_oldest_transaction_id].reset();\n\t\t\ttimeouts.push_back(o);\n\t\t} catch (std::exception) {}\n\t}\n\t\n\tcheck_invariant();\n\n\tstd::for_each(timeouts.begin(), timeouts.end(), bind(&observer::timeout, _1));\n\ttimeouts.clear();\n\t\n\t\/\/ clear the aborted transactions, will likely\n\t\/\/ generate new requests. We need to swap, since the\n\t\/\/ destrutors may add more observers to the m_aborted_transactions\n\tstd::vector >().swap(m_aborted_transactions);\n\treturn milliseconds(timeout_ms);\n}\n\nunsigned int rpc_manager::new_transaction_id(shared_ptr o)\n{\n\tINVARIANT_CHECK;\n\n\tunsigned int tid = m_next_transaction_id;\n\tm_next_transaction_id = (m_next_transaction_id + 1) % max_transactions;\n\tif (m_transactions[m_next_transaction_id])\n\t{\n\t\t\/\/ moving the observer into the set of aborted transactions\n\t\t\/\/ it will prevent it from spawning new requests right now,\n\t\t\/\/ since that would break the invariant\n\t\tm_aborted_transactions.push_back(m_transactions[m_next_transaction_id]);\n\t\tm_transactions[m_next_transaction_id].reset();\n\t\tassert(m_oldest_transaction_id == m_next_transaction_id);\n\t}\n\tassert(!m_transactions[tid]);\n\tm_transactions[tid] = o;\n\tif (m_oldest_transaction_id == m_next_transaction_id)\n\t{\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions;\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(rpc) << \"WARNING: transaction limit reached! Too many concurrent\"\n\t\t\t\" messages! limit: \" << (int)max_transactions;\n#endif\n\t\tupdate_oldest_transaction_id();\n\t}\n\n\treturn tid;\n}\n\nvoid rpc_manager::update_oldest_transaction_id()\n{\n\tINVARIANT_CHECK;\n\n\tassert(m_oldest_transaction_id != m_next_transaction_id);\n\twhile (!m_transactions[m_oldest_transaction_id])\n\t{\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1)\n\t\t\t% max_transactions;\n\t\tif (m_oldest_transaction_id == m_next_transaction_id)\n\t\t\tbreak;\n\t}\n}\n\nvoid rpc_manager::invoke(int message_id, udp::endpoint target_addr\n\t, shared_ptr o)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing)\n\t{\n\t\to->abort();\n\t\treturn;\n\t}\n\n\tmsg m;\n\tm.message_id = message_id;\n\tm.reply = false;\n\tm.id = m_our_id;\n\tm.addr = target_addr;\n\tassert(!m_transactions[m_next_transaction_id]);\n\ttry\n\t{\n\t\tm.transaction_id.clear();\n\t\tstd::back_insert_iterator out(m.transaction_id);\n\t\tio::write_uint16(m_next_transaction_id, out);\n\t\t\n\t\to->send(m);\n\n\t\to->sent = boost::posix_time::microsec_clock::universal_time();\n\t\to->target_addr = target_addr;\n\n\t#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(rpc) << \"Invoking \" << messages::ids[message_id] \n\t\t\t<< \" -> \" << target_addr;\n\t#endif\t\n\t\tm_send(m);\n\t\tnew_transaction_id(o);\n\t}\n\tcatch (std::exception&)\n\t{\n\t\tassert(false);\n\t}\n}\n\nvoid rpc_manager::reply(msg& m, msg const& reply_to)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return;\n\n\tif (m.message_id != messages::error)\n\t\tm.message_id = reply_to.message_id;\n\tm.addr = reply_to.addr;\n\tm.reply = true;\n\tm.piggy_backed_ping = false;\n\tm.id = m_our_id;\n\tm.transaction_id = reply_to.transaction_id;\n\t\n\tm_send(m);\n}\n\nnamespace\n{\n\tstruct dummy_observer : observer\n\t{\n\t\tvirtual void reply(msg const&) {}\n\t\tvirtual void timeout() {}\n\t\tvirtual void send(msg&) {}\n\t\tvoid abort() {}\n\t};\n}\n\nvoid rpc_manager::reply_with_ping(msg& m, msg const& reply_to)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return;\n\n\tif (m.message_id != messages::error)\n\t\tm.message_id = reply_to.message_id;\n\tm.addr = reply_to.addr;\n\tm.reply = true;\n\tm.piggy_backed_ping = true;\n\tm.id = m_our_id;\n\tm.transaction_id = reply_to.transaction_id;\n\n\ttry\n\t{\n\t\tm.ping_transaction_id.clear();\n\t\tstd::back_insert_iterator out(m.ping_transaction_id);\n\t\tio::write_uint16(m_next_transaction_id, out);\n\n\t\tboost::shared_ptr o(new dummy_observer);\n\t\tassert(!m_transactions[m_next_transaction_id]);\n\t\to->sent = boost::posix_time::microsec_clock::universal_time();\n\t\to->target_addr = m.addr;\n\t\t\n\t\tm_send(m);\n\t\tnew_transaction_id(o);\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tassert(false);\n\t}\n}\n\n\n\n} } \/\/ namespace libtorrent::dht\n\nremoved invariant_check() left in by mistake\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing boost::posix_time::ptime;\nusing boost::posix_time::time_duration;\nusing boost::posix_time::microsec_clock;\nusing boost::posix_time::seconds;\nusing boost::posix_time::milliseconds;\nusing boost::shared_ptr;\nusing boost::bind;\n\nnamespace libtorrent { namespace dht\n{\n\nnamespace io = libtorrent::detail;\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\nTORRENT_DEFINE_LOG(rpc)\n#endif\n\nnode_id generate_id();\n\nrpc_manager::rpc_manager(fun const& f, node_id const& our_id\n\t, routing_table& table, send_fun const& sf)\n\t: m_next_transaction_id(rand() % max_transactions)\n\t, m_oldest_transaction_id(m_next_transaction_id)\n\t, m_incoming(f)\n\t, m_send(sf)\n\t, m_our_id(our_id)\n\t, m_table(table)\n\t, m_timer(boost::posix_time::microsec_clock::universal_time())\n\t, m_random_number(generate_id())\n\t, m_destructing(false)\n{\n\tstd::srand(time(0));\n}\n\nrpc_manager::~rpc_manager()\n{\n\tm_destructing = true;\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\tTORRENT_LOG(rpc) << \"Destructing\";\n#endif\n\tstd::for_each(m_aborted_transactions.begin(), m_aborted_transactions.end()\n\t\t, bind(&observer::abort, _1));\n\t\n\tfor (transactions_t::iterator i = m_transactions.begin()\n\t\t, end(m_transactions.end()); i != end; ++i)\n\t{\n\t\tif (*i) (*i)->abort();\n\t}\n}\n\n#ifndef NDEBUG\nvoid rpc_manager::check_invariant() const\n{\n\tassert(m_oldest_transaction_id >= 0);\n\tassert(m_oldest_transaction_id < max_transactions);\n\tassert(m_next_transaction_id >= 0);\n\tassert(m_next_transaction_id < max_transactions);\n\tassert(!m_transactions[m_next_transaction_id]);\n\n\tfor (int i = (m_next_transaction_id + 1) % max_transactions;\n\t\ti != m_oldest_transaction_id; i = (i + 1) % max_transactions)\n\t{\n\t\tassert(!m_transactions[i]);\n\t}\n}\n#endif\n\nbool rpc_manager::incoming(msg const& m)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return false;\n\n\tif (m.reply)\n\t{\n\t\t\/\/ if we don't have the transaction id in our\n\t\t\/\/ request list, ignore the packet\n\n\t\tif (m.transaction_id.size() != 2)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with invalid transaction id size: \" \n\t\t\t\t<< m.transaction_id.size() << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\n\t\tstd::string::const_iterator i = m.transaction_id.begin();\t\n\t\tint tid = io::read_uint16(i);\n\n\t\tif (tid >= (int)m_transactions.size()\n\t\t\t|| tid < 0)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with unknown transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tboost::shared_ptr o = m_transactions[tid];\n\n\t\tif (!o)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with unknown transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif (m.addr != o->target_addr)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with incorrect address and valid transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tstd::ofstream reply_stats(\"libtorrent_logs\/round_trip_ms.log\", std::ios::app);\n\t\treply_stats << m.addr << \"\\t\" << (microsec_clock::universal_time()\n\t\t\t- o->sent).total_milliseconds() << std::endl;\n#endif\n\t\to->reply(m);\n\t\tm_transactions[tid].reset();\n\t\t\n\t\tif (m.piggy_backed_ping)\n\t\t{\n\t\t\t\/\/ there is a ping request piggy\n\t\t\t\/\/ backed in this reply\n\t\t\tmsg ph;\n\t\t\tph.message_id = messages::ping;\n\t\t\tph.transaction_id = m.ping_transaction_id;\n\t\t\tph.id = m_our_id;\n\t\t\tph.addr = m.addr;\n\n\t\t\tmsg empty;\n\t\t\t\n\t\t\treply(empty, ph);\n\t\t}\n\t\treturn m_table.node_seen(m.id, m.addr);\n\t}\n\telse\n\t{\n\t\t\/\/ this is an incoming request\n\t\tm_incoming(m);\n\t}\n\treturn false;\n}\n\ntime_duration rpc_manager::tick()\n{\n\tINVARIANT_CHECK;\n\n\tusing boost::posix_time::microsec_clock;\n\n\tconst int timeout_ms = 20 * 1000;\n\n\t\/\/\tlook for observers that has timed out\n\n\tif (m_next_transaction_id == m_oldest_transaction_id) return milliseconds(timeout_ms);\n\n\tstd::vector > timeouts;\n\n\tfor (;m_next_transaction_id != m_oldest_transaction_id;\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions)\n\t{\n\t\tassert(m_oldest_transaction_id >= 0);\n\t\tassert(m_oldest_transaction_id < max_transactions);\n\n\t\tboost::shared_ptr o = m_transactions[m_oldest_transaction_id];\n\t\tif (!o) continue;\n\n\t\ttime_duration diff = o->sent + milliseconds(timeout_ms)\n\t\t\t- microsec_clock::universal_time();\n\t\tif (diff > seconds(0))\n\t\t{\n\t\t\tif (diff < seconds(1)) return seconds(1);\n\t\t\treturn diff;\n\t\t}\n\t\t\n\t\ttry\n\t\t{\n\t\t\tm_transactions[m_oldest_transaction_id].reset();\n\t\t\ttimeouts.push_back(o);\n\t\t} catch (std::exception) {}\n\t}\n\t\n\tstd::for_each(timeouts.begin(), timeouts.end(), bind(&observer::timeout, _1));\n\ttimeouts.clear();\n\t\n\t\/\/ clear the aborted transactions, will likely\n\t\/\/ generate new requests. We need to swap, since the\n\t\/\/ destrutors may add more observers to the m_aborted_transactions\n\tstd::vector >().swap(m_aborted_transactions);\n\treturn milliseconds(timeout_ms);\n}\n\nunsigned int rpc_manager::new_transaction_id(shared_ptr o)\n{\n\tINVARIANT_CHECK;\n\n\tunsigned int tid = m_next_transaction_id;\n\tm_next_transaction_id = (m_next_transaction_id + 1) % max_transactions;\n\tif (m_transactions[m_next_transaction_id])\n\t{\n\t\t\/\/ moving the observer into the set of aborted transactions\n\t\t\/\/ it will prevent it from spawning new requests right now,\n\t\t\/\/ since that would break the invariant\n\t\tm_aborted_transactions.push_back(m_transactions[m_next_transaction_id]);\n\t\tm_transactions[m_next_transaction_id].reset();\n\t\tassert(m_oldest_transaction_id == m_next_transaction_id);\n\t}\n\tassert(!m_transactions[tid]);\n\tm_transactions[tid] = o;\n\tif (m_oldest_transaction_id == m_next_transaction_id)\n\t{\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions;\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(rpc) << \"WARNING: transaction limit reached! Too many concurrent\"\n\t\t\t\" messages! limit: \" << (int)max_transactions;\n#endif\n\t\tupdate_oldest_transaction_id();\n\t}\n\n\treturn tid;\n}\n\nvoid rpc_manager::update_oldest_transaction_id()\n{\n\tINVARIANT_CHECK;\n\n\tassert(m_oldest_transaction_id != m_next_transaction_id);\n\twhile (!m_transactions[m_oldest_transaction_id])\n\t{\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1)\n\t\t\t% max_transactions;\n\t\tif (m_oldest_transaction_id == m_next_transaction_id)\n\t\t\tbreak;\n\t}\n}\n\nvoid rpc_manager::invoke(int message_id, udp::endpoint target_addr\n\t, shared_ptr o)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing)\n\t{\n\t\to->abort();\n\t\treturn;\n\t}\n\n\tmsg m;\n\tm.message_id = message_id;\n\tm.reply = false;\n\tm.id = m_our_id;\n\tm.addr = target_addr;\n\tassert(!m_transactions[m_next_transaction_id]);\n\ttry\n\t{\n\t\tm.transaction_id.clear();\n\t\tstd::back_insert_iterator out(m.transaction_id);\n\t\tio::write_uint16(m_next_transaction_id, out);\n\t\t\n\t\to->send(m);\n\n\t\to->sent = boost::posix_time::microsec_clock::universal_time();\n\t\to->target_addr = target_addr;\n\n\t#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(rpc) << \"Invoking \" << messages::ids[message_id] \n\t\t\t<< \" -> \" << target_addr;\n\t#endif\t\n\t\tm_send(m);\n\t\tnew_transaction_id(o);\n\t}\n\tcatch (std::exception&)\n\t{\n\t\tassert(false);\n\t}\n}\n\nvoid rpc_manager::reply(msg& m, msg const& reply_to)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return;\n\n\tif (m.message_id != messages::error)\n\t\tm.message_id = reply_to.message_id;\n\tm.addr = reply_to.addr;\n\tm.reply = true;\n\tm.piggy_backed_ping = false;\n\tm.id = m_our_id;\n\tm.transaction_id = reply_to.transaction_id;\n\t\n\tm_send(m);\n}\n\nnamespace\n{\n\tstruct dummy_observer : observer\n\t{\n\t\tvirtual void reply(msg const&) {}\n\t\tvirtual void timeout() {}\n\t\tvirtual void send(msg&) {}\n\t\tvoid abort() {}\n\t};\n}\n\nvoid rpc_manager::reply_with_ping(msg& m, msg const& reply_to)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return;\n\n\tif (m.message_id != messages::error)\n\t\tm.message_id = reply_to.message_id;\n\tm.addr = reply_to.addr;\n\tm.reply = true;\n\tm.piggy_backed_ping = true;\n\tm.id = m_our_id;\n\tm.transaction_id = reply_to.transaction_id;\n\n\ttry\n\t{\n\t\tm.ping_transaction_id.clear();\n\t\tstd::back_insert_iterator out(m.ping_transaction_id);\n\t\tio::write_uint16(m_next_transaction_id, out);\n\n\t\tboost::shared_ptr o(new dummy_observer);\n\t\tassert(!m_transactions[m_next_transaction_id]);\n\t\to->sent = boost::posix_time::microsec_clock::universal_time();\n\t\to->target_addr = m.addr;\n\t\t\n\t\tm_send(m);\n\t\tnew_transaction_id(o);\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tassert(false);\n\t}\n}\n\n\n\n} } \/\/ namespace libtorrent::dht\n\n<|endoftext|>"}
{"text":"#include \"dlib\/bam_util.h\"\n#include \n#include \n\nint usage(char **argv, int retcode=EXIT_FAILURE) {\n    fprintf(stderr, \"bmftools %s <-l output_compression_level> in.bam out.bam\\n\"\n                    \"Use - for stdin or stdout.\\n\", argv[0]);\n    return retcode;\n}\n\nstruct opts {\n    uint32_t minFM:14;\n    uint32_t v:1;\n    uint32_t skip_flag:16;\n    uint32_t require_flag:16;\n    uint32_t minMQ:8;\n};\n\n#define TEST(b, options) \\\n        (bam_itag(b, \"FM\") < (int)((opts *)options)->minFM ||\\\n                   b->core.qual < ((opts *)options)->minMQ ||\\\n                   (b->core.flag & ((opts *)options)->skip_flag) ||\\\n                   ((b->core.flag & ((opts *)options)->require_flag) == 0))\nint bam_test(bam1_t *b, void *options) {\n    return ((opts *)options)->v ? !TEST(b, options): TEST(b, options);\n}\n\n#undef TEST\n\nint filter_main(int argc, char *argv[]) {\n    if(argc < 3) {\n        return usage(argv);\n    }\n    if(strcmp(argv[1], \"--help\") == 0) {\n        return usage(argv, EXIT_SUCCESS);\n    }\n    int c;\n    char out_mode[4] = \"wb\";\n    opts param = {0};\n    while((c = getopt(argc, argv, \"m:F:f:l:hv?\")) > -1) {\n        switch(c) {\n        case 'm': param.minMQ = strtoul(optarg, NULL, 0); break;\n        case 'F': param.skip_flag = strtoul(optarg, NULL, 0); break;\n        case 'f': param.require_flag = strtoul(optarg, NULL, 0); break;\n        case 'v': param.v = 1; break;\n        case 'l': out_mode[2] = atoi(optarg) % 10 + '0'; break;\n        case 'h': case '?': return usage(argv, EXIT_SUCCESS);\n        }\n    }\n    if(argc - 2 != optind) {\n        LOG_EXIT(\"Required: precisely two positional arguments (in bam, out bam).\\n\");\n    }\n    \/\/ Actually this function. You can't really apply a null function....\n    \/\/ Actually create your type for data and then provide it if needed.\n    dlib::bam_apply_function(argv[optind], argv[optind + 1], bam_test, (void *)¶m, out_mode);\n    return EXIT_SUCCESS;\n}\n\nAdded bed region test to bmftools filter.#include \"dlib\/bam_util.h\"\n#include \"dlib\/bed_util.h\"\n#include \n#include \n\nint usage(char **argv, int retcode=EXIT_FAILURE) {\n    fprintf(stderr, \"bmftools %s <-l output_compression_level> in.bam out.bam\\n\"\n                    \"Use - for stdin or stdout.\\n\", argv[0]);\n    return retcode;\n}\n\nstruct opts {\n    uint32_t minFM:14;\n    uint32_t v:1;\n    uint32_t skip_flag:16;\n    uint32_t require_flag:16;\n    uint32_t minMQ:8;\n    khash_t(bed) *bed;\n};\n\n#define TEST(b, options) \\\n        (\\\n             bam_itag(b, \"FM\") < (int)((opts *)options)->minFM ||\\\n             b->core.qual < ((opts *)options)->minMQ ||\\\n             (b->core.flag & ((opts *)options)->skip_flag) ||\\\n             ((b->core.flag & ((opts *)options)->require_flag) == 0) ||\\\n             !bed_test(b, ((opts *)options)->bed)\\\n        )\n\nint bam_test(bam1_t *b, void *options) {\n    return ((opts *)options)->v ? !TEST(b, options): TEST(b, options);\n}\n\n#undef TEST\n\nint filter_main(int argc, char *argv[]) {\n    if(argc < 3) {\n        return usage(argv);\n    }\n    if(strcmp(argv[1], \"--help\") == 0) {\n        return usage(argv, EXIT_SUCCESS);\n    }\n    int c;\n    char out_mode[4] = \"wb\";\n    opts param = {0};\n    char *bedpath = NULL;\n    while((c = getopt(argc, argv, \"b:m:F:f:l:hv?\")) > -1) {\n        switch(c) {\n        case 'b': bedpath = optarg; break;\n        case 'm': param.minMQ = strtoul(optarg, NULL, 0); break;\n        case 'F': param.skip_flag = strtoul(optarg, NULL, 0); break;\n        case 'f': param.require_flag = strtoul(optarg, NULL, 0); break;\n        case 'v': param.v = 1; break;\n        case 'l': out_mode[2] = atoi(optarg) % 10 + '0'; break;\n        case 'h': case '?': return usage(argv, EXIT_SUCCESS);\n        }\n    }\n    if(argc - 2 != optind) {\n        LOG_EXIT(\"Required: precisely two positional arguments (in bam, out bam).\\n\");\n    }\n    if(bedpath) {\n        \/\/ This doesn't properly handle streaming....\n        samFile *fp = sam_open(argv[optind], \"r\");\n        bam_hdr_t *hdr = sam_hdr_read(fp);\n        sam_close(fp);\n        param.bed = parse_bed_hash(bedpath, hdr, 0);\n        bam_hdr_destroy(hdr);\n    }\n    \/\/ Actually this function. You can't really apply a null function....\n    \/\/ Actually create your type for data and then provide it if needed.\n    dlib::bam_apply_function(argv[optind], argv[optind + 1], bam_test, (void *)¶m, out_mode);\n    if(param.bed) bed_destroy_hash((void *)param.bed);\n    return EXIT_SUCCESS;\n}\n\n<|endoftext|>"}
{"text":"\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"bp_control.hxx\"\n#include \"bp_stats.hxx\"\n#include \"control_distribute.hxx\"\n#include \"control_server.hxx\"\n#include \"control_local.hxx\"\n#include \"bp_instance.hxx\"\n#include \"translation\/Request.hxx\"\n#include \"translation\/Cache.hxx\"\n#include \"translation\/Protocol.hxx\"\n#include \"translation\/InvalidateParser.hxx\"\n#include \"tpool.hxx\"\n#include \"pool.hxx\"\n#include \"net\/UdpDistribute.hxx\"\n#include \"net\/SocketAddress.hxx\"\n#include \"net\/IPv4Address.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n#include \"util\/Exception.hxx\"\n#include \"util\/Macros.hxx\"\n\n#include \n\n#include \n#include \n\nstatic void\ncontrol_tcache_invalidate(BpInstance *instance,\n                          const void *payload, size_t payload_length)\n{\n    if (payload_length == 0) {\n        \/* flush the translation cache if the payload is empty *\/\n        translate_cache_flush(*instance->translate_cache);\n        return;\n    }\n\n    const AutoRewindPool auto_rewind(*tpool);\n\n    TranslationInvalidateRequest request;\n\n    try {\n        request = ParseTranslationInvalidateRequest(*tpool,\n                                                    payload, payload_length);\n    } catch (...) {\n        daemon_log(2, \"malformed TCACHE_INVALIDATE control packet: %s\\n\",\n                   GetFullMessage(std::current_exception()).c_str());\n        return;\n    }\n\n    translate_cache_invalidate(*instance->translate_cache, request,\n                               ConstBuffer(request.commands.raw(),\n                                                               request.commands.size()),\n                               request.site);\n}\n\nstatic void\nquery_stats(BpInstance *instance, ControlServer *server,\n            SocketAddress address)\n{\n    if (address.GetSize() == 0)\n        \/* TODO: this packet was forwarded by the master process, and\n           has no source address; however, the master process must get\n           statistics from all worker processes (even those that have\n           exited already) *\/\n        return;\n\n    struct beng_control_stats stats;\n    bp_get_stats(instance, &stats);\n\n    try {\n        server->Reply(address,\n                      CONTROL_STATS, &stats, sizeof(stats));\n    } catch (const std::runtime_error &e) {\n        daemon_log(3, \"%s\\n\", e.what());\n    }\n}\n\nstatic void\nhandle_control_packet(BpInstance *instance, ControlServer *server,\n                      enum beng_control_command command,\n                      const void *payload, size_t payload_length,\n                      SocketAddress address)\n{\n    daemon_log(5, \"control command=%d payload_length=%zu\\n\",\n               command, payload_length);\n\n    \/* only local clients are allowed to use most commands *\/\n    const bool is_privileged = address.GetFamily() == AF_LOCAL;\n\n    switch (command) {\n    case CONTROL_NOP:\n        \/* duh! *\/\n        break;\n\n    case CONTROL_TCACHE_INVALIDATE:\n        control_tcache_invalidate(instance, payload, payload_length);\n        break;\n\n    case CONTROL_DUMP_POOLS:\n        if (is_privileged)\n            pool_dump_tree(instance->root_pool);\n        break;\n\n    case CONTROL_ENABLE_NODE:\n    case CONTROL_FADE_NODE:\n    case CONTROL_NODE_STATUS:\n        \/* only for beng-lb *\/\n        break;\n\n    case CONTROL_STATS:\n        query_stats(instance, server, address);\n        break;\n\n    case CONTROL_VERBOSE:\n        if (is_privileged && payload_length == 1)\n            daemon_log_config.verbose = *(const uint8_t *)payload;\n        break;\n\n    case CONTROL_FADE_CHILDREN:\n        if (payload_length > 0)\n            \/* tagged fade is allowed for any unprivileged client *\/\n            instance->FadeTaggedChildren(std::string((const char *)payload,\n                                                     payload_length).c_str());\n        else if (is_privileged)\n            \/* unconditional fade is only allowed for privileged\n               clients *\/\n            instance->FadeChildren();\n        break;\n    }\n}\n\nvoid\nBpInstance::OnControlPacket(ControlServer &_control_server,\n                            enum beng_control_command command,\n                            const void *payload, size_t payload_length,\n                            SocketAddress address)\n{\n    handle_control_packet(this, &_control_server,\n                          command, payload, payload_length,\n                          address);\n}\n\nvoid\nBpInstance::OnControlError(std::exception_ptr ep)\n{\n    daemon_log(2, \"%s\\n\", GetFullMessage(ep).c_str());\n}\n\nvoid\nglobal_control_handler_init(BpInstance *instance)\n{\n    if (instance->config.control_listen.empty())\n        return;\n\n    instance->control_distribute = new ControlDistribute(instance->event_loop,\n                                                         *instance);\n\n    for (const auto &control_listen : instance->config.control_listen) {\n        instance->control_servers.emplace_front(instance->event_loop,\n                                                *instance->control_distribute,\n                                                control_listen);\n    }\n}\n\nvoid\nglobal_control_handler_deinit(BpInstance *instance)\n{\n    instance->control_servers.clear();\n    delete instance->control_distribute;\n}\n\nvoid\nglobal_control_handler_enable(BpInstance &instance)\n{\n    for (auto &c : instance.control_servers)\n        c.Enable();\n}\n\nvoid\nglobal_control_handler_disable(BpInstance &instance)\n{\n    for (auto &c : instance.control_servers)\n        c.Disable();\n}\n\nUniqueSocketDescriptor\nglobal_control_handler_add_fd(BpInstance *instance)\n{\n    assert(!instance->control_servers.empty());\n    assert(instance->control_distribute != nullptr);\n\n    return instance->control_distribute->Add();\n}\n\nvoid\nglobal_control_handler_set_fd(BpInstance *instance,\n                              UniqueSocketDescriptor &&fd)\n{\n    assert(!instance->control_servers.empty());\n    assert(instance->control_distribute != nullptr);\n\n    instance->control_distribute->Clear();\n\n    \/* erase all but one *\/\n    instance->control_servers.erase_after(instance->control_servers.begin(),\n                                          instance->control_servers.end());\n\n    \/* replace the one *\/\n    instance->control_servers.front().SetFd(std::move(fd));\n}\n\n\/*\n * local (implicit) control channel\n *\/\n\nvoid\nlocal_control_handler_init(BpInstance *instance)\n{\n    instance->local_control_server =\n        control_local_new(\"beng_control:pid=\", *instance);\n}\n\nvoid\nlocal_control_handler_deinit(BpInstance *instance)\n{\n    control_local_free(instance->local_control_server);\n}\n\nvoid\nlocal_control_handler_open(BpInstance *instance)\n{\n    control_local_open(instance->local_control_server,\n                       instance->event_loop);\n}\nbp_control: use the Logger library instead of libdaemon\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"bp_control.hxx\"\n#include \"bp_stats.hxx\"\n#include \"control_distribute.hxx\"\n#include \"control_server.hxx\"\n#include \"control_local.hxx\"\n#include \"bp_instance.hxx\"\n#include \"translation\/Request.hxx\"\n#include \"translation\/Cache.hxx\"\n#include \"translation\/Protocol.hxx\"\n#include \"translation\/InvalidateParser.hxx\"\n#include \"tpool.hxx\"\n#include \"pool.hxx\"\n#include \"net\/UdpDistribute.hxx\"\n#include \"net\/SocketAddress.hxx\"\n#include \"net\/IPv4Address.hxx\"\n#include \"io\/Logger.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n#include \"util\/Exception.hxx\"\n#include \"util\/Macros.hxx\"\n\n#include \n#include \n\nstatic void\ncontrol_tcache_invalidate(BpInstance *instance,\n                          const void *payload, size_t payload_length)\n{\n    if (payload_length == 0) {\n        \/* flush the translation cache if the payload is empty *\/\n        translate_cache_flush(*instance->translate_cache);\n        return;\n    }\n\n    const AutoRewindPool auto_rewind(*tpool);\n\n    TranslationInvalidateRequest request;\n\n    try {\n        request = ParseTranslationInvalidateRequest(*tpool,\n                                                    payload, payload_length);\n    } catch (...) {\n        LogConcat(2, \"control\",\n                  \"malformed TCACHE_INVALIDATE control packet: \",\n                  std::current_exception());\n        return;\n    }\n\n    translate_cache_invalidate(*instance->translate_cache, request,\n                               ConstBuffer(request.commands.raw(),\n                                                               request.commands.size()),\n                               request.site);\n}\n\nstatic void\nquery_stats(BpInstance *instance, ControlServer *server,\n            SocketAddress address)\n{\n    if (address.GetSize() == 0)\n        \/* TODO: this packet was forwarded by the master process, and\n           has no source address; however, the master process must get\n           statistics from all worker processes (even those that have\n           exited already) *\/\n        return;\n\n    struct beng_control_stats stats;\n    bp_get_stats(instance, &stats);\n\n    try {\n        server->Reply(address,\n                      CONTROL_STATS, &stats, sizeof(stats));\n    } catch (...) {\n        LogConcat(3, \"control\", std::current_exception());\n    }\n}\n\nstatic void\nhandle_control_packet(BpInstance *instance, ControlServer *server,\n                      enum beng_control_command command,\n                      const void *payload, size_t payload_length,\n                      SocketAddress address)\n{\n    LogConcat(5, \"control\", \"command=\", int(command),\n              \" payload_length=\", unsigned(payload_length));\n\n    \/* only local clients are allowed to use most commands *\/\n    const bool is_privileged = address.GetFamily() == AF_LOCAL;\n\n    switch (command) {\n    case CONTROL_NOP:\n        \/* duh! *\/\n        break;\n\n    case CONTROL_TCACHE_INVALIDATE:\n        control_tcache_invalidate(instance, payload, payload_length);\n        break;\n\n    case CONTROL_DUMP_POOLS:\n        if (is_privileged)\n            pool_dump_tree(instance->root_pool);\n        break;\n\n    case CONTROL_ENABLE_NODE:\n    case CONTROL_FADE_NODE:\n    case CONTROL_NODE_STATUS:\n        \/* only for beng-lb *\/\n        break;\n\n    case CONTROL_STATS:\n        query_stats(instance, server, address);\n        break;\n\n    case CONTROL_VERBOSE:\n        if (is_privileged && payload_length == 1)\n            SetLogLevel(*(const uint8_t *)payload);\n        break;\n\n    case CONTROL_FADE_CHILDREN:\n        if (payload_length > 0)\n            \/* tagged fade is allowed for any unprivileged client *\/\n            instance->FadeTaggedChildren(std::string((const char *)payload,\n                                                     payload_length).c_str());\n        else if (is_privileged)\n            \/* unconditional fade is only allowed for privileged\n               clients *\/\n            instance->FadeChildren();\n        break;\n    }\n}\n\nvoid\nBpInstance::OnControlPacket(ControlServer &_control_server,\n                            enum beng_control_command command,\n                            const void *payload, size_t payload_length,\n                            SocketAddress address)\n{\n    handle_control_packet(this, &_control_server,\n                          command, payload, payload_length,\n                          address);\n}\n\nvoid\nBpInstance::OnControlError(std::exception_ptr ep)\n{\n    LogConcat(2, \"control\", ep);\n}\n\nvoid\nglobal_control_handler_init(BpInstance *instance)\n{\n    if (instance->config.control_listen.empty())\n        return;\n\n    instance->control_distribute = new ControlDistribute(instance->event_loop,\n                                                         *instance);\n\n    for (const auto &control_listen : instance->config.control_listen) {\n        instance->control_servers.emplace_front(instance->event_loop,\n                                                *instance->control_distribute,\n                                                control_listen);\n    }\n}\n\nvoid\nglobal_control_handler_deinit(BpInstance *instance)\n{\n    instance->control_servers.clear();\n    delete instance->control_distribute;\n}\n\nvoid\nglobal_control_handler_enable(BpInstance &instance)\n{\n    for (auto &c : instance.control_servers)\n        c.Enable();\n}\n\nvoid\nglobal_control_handler_disable(BpInstance &instance)\n{\n    for (auto &c : instance.control_servers)\n        c.Disable();\n}\n\nUniqueSocketDescriptor\nglobal_control_handler_add_fd(BpInstance *instance)\n{\n    assert(!instance->control_servers.empty());\n    assert(instance->control_distribute != nullptr);\n\n    return instance->control_distribute->Add();\n}\n\nvoid\nglobal_control_handler_set_fd(BpInstance *instance,\n                              UniqueSocketDescriptor &&fd)\n{\n    assert(!instance->control_servers.empty());\n    assert(instance->control_distribute != nullptr);\n\n    instance->control_distribute->Clear();\n\n    \/* erase all but one *\/\n    instance->control_servers.erase_after(instance->control_servers.begin(),\n                                          instance->control_servers.end());\n\n    \/* replace the one *\/\n    instance->control_servers.front().SetFd(std::move(fd));\n}\n\n\/*\n * local (implicit) control channel\n *\/\n\nvoid\nlocal_control_handler_init(BpInstance *instance)\n{\n    instance->local_control_server =\n        control_local_new(\"beng_control:pid=\", *instance);\n}\n\nvoid\nlocal_control_handler_deinit(BpInstance *instance)\n{\n    control_local_free(instance->local_control_server);\n}\n\nvoid\nlocal_control_handler_open(BpInstance *instance)\n{\n    control_local_open(instance->local_control_server,\n                       instance->event_loop);\n}\n<|endoftext|>"}
{"text":"\/\/ -*-Mode: C++;-*-\n\n\/\/ * BeginRiceCopyright *****************************************************\n\/\/\n\/\/ $HeadURL$\n\/\/ $Id$\n\/\/\n\/\/ -----------------------------------\n\/\/ Part of HPCToolkit (hpctoolkit.org)\n\/\/ -----------------------------------\n\/\/ \n\/\/ Copyright ((c)) 2002-2010, Rice University \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/   notice, this list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/   notice, this list of conditions and the following disclaimer in the\n\/\/   documentation and\/or other materials provided with the distribution.\n\/\/ \n\/\/ * Neither the name of Rice University (RICE) nor the names of its\n\/\/   contributors may be used to endorse or promote products derived from\n\/\/   this software without specific prior written permission.\n\/\/ \n\/\/ This software is provided by RICE and contributors \"as is\" and any\n\/\/ express or implied warranties, including, but not limited to, the\n\/\/ implied warranties of merchantability and fitness for a particular\n\/\/ purpose are disclaimed. In no event shall RICE or contributors be\n\/\/ liable for any direct, indirect, incidental, special, exemplary, or\n\/\/ consequential damages (including, but not limited to, procurement of\n\/\/ substitute goods or services; loss of use, data, or profits; or\n\/\/ business interruption) however caused and on any theory of liability,\n\/\/ whether in contract, strict liability, or tort (including negligence\n\/\/ or otherwise) arising in any way out of the use of this software, even\n\/\/ if advised of the possibility of such damage. \n\/\/ \n\/\/ ******************************************************* EndRiceCopyright *\n\n\/\/***************************************************************************\n\n\/\/************************* System Include Files ****************************\n\n#include \n\n#include  \/\/ for 'mkstemp' (not technically visible in C++)\n#include   \/\/ for 'tmpnam', 'rename'\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \nusing std::string;\n\n\/\/*************************** User Include Files ****************************\n\n#include \"FileUtil.hpp\"\n\n#include \"diagnostics.h\"\n#include \"StrUtil.hpp\"\n#include \"Trace.hpp\"\n\n\/\/*************************** Forward Declarations **************************\n\nusing std::endl;\n\n\/\/***************************************************************************\n\/\/\n\/\/***************************************************************************\n\nnamespace FileUtil {\n\nstring\nbasename(const char* fName)\n{\n  string baseFileName;\n\n  const char* lastSlash = strrchr(fName, '\/');\n  if (lastSlash) {\n    \/\/ valid: \"\/foo\" || \"...\/foo\" AND invalid: \"\/\" || \"...\/\"\n    baseFileName = lastSlash + 1;\n  }\n  else {\n    \/\/ filename contains no slashes, already in short form\n    baseFileName = fName;\n  }\n  return baseFileName;\n\n#if 0\n  \/\/ A \"more C++\" implementation (Gaurav)\n  std::string\n  PathFindMgr::getFileName(const std::string& path) const\n  {\n    size_t in = path.find_last_of(\"\/\");\n    if (in != path.npos && path.length() > 1)\n      return path.substr(in + 1);\n    \n    return path;\n  }\n#endif\n}\n\n\nstring\nrmSuffix(const char* fName)\n{\n  string baseFileName = fName;\n\n  size_t pos = baseFileName.find_last_of('.');\n  if (pos != string::npos) {\n    baseFileName = baseFileName.substr(0, pos);\n  }\n  return baseFileName;\n}\n\n\nstring\ndirname(const char* fName)\n{\n  const char* lastSlash = strrchr(fName, '\/');\n  string pathComponent = \".\";\n  if (lastSlash) {\n    pathComponent = fName;\n    pathComponent.resize(lastSlash - fName);\n  }\n  return pathComponent;\n}\n\n\nbool\nfnmatch(const std::vector& patternVec,\n\tconst char* string, int flags)\n{\n  for (uint i = 0; i < patternVec.size(); ++i) {\n    const std::string& pat = patternVec[i];\n    bool fnd = FileUtil::fnmatch(pat, string, flags);\n    if (fnd) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\n} \/\/ end of FileUtil namespace\n\n\n\/\/***************************************************************************\n\/\/\n\/\/***************************************************************************\n\nnamespace FileUtil {\n\nbool\nisReadable(const char* path)\n{\n  struct stat sbuf;\n  if (stat(path, &sbuf) == 0) {\n    return true; \/\/ the file is readable\n  }\n  return false;\n}\n\n\nbool\nisDir(const char* path)\n{\n  struct stat sbuf;\n  if (stat(path, &sbuf) == 0) {\n    return (S_ISDIR(sbuf.st_mode)\n\t    \/*|| S_ISLNK(sbuf.st_mode) && isDir(readlink(path))*\/);\n  }\n  return false; \/\/ unknown\n}\n\n\nint\ncountChar(const char* path, char c)\n{\n  int srcFd = open(path, O_RDONLY); \n  if (srcFd < 0) {\n    return -1; \n  } \n  int count = 0;\n  char buf[256]; \n  ssize_t nRead; \n  while ((nRead = read(srcFd, buf, 256)) > 0) {\n    for (int i = 0; i < nRead; i++) {\n      if (buf[i] == c) count++; \n    }\n  }\n  return count; \n} \n\n} \/\/ end of FileUtil namespace\n\n\n\/\/***************************************************************************\n\/\/\n\/\/***************************************************************************\n\nstatic void\ncpy(int srcFd, int dstFd)\n{\n  static const int bufSz = 4096;\n  char buf[bufSz];\n  ssize_t nRead;\n  while ((nRead = read(srcFd, buf, bufSz)) > 0) {\n    write(dstFd, buf, nRead);\n  }\n}\n\n\nnamespace FileUtil {\n\nvoid\ncopy(const char* dst, ...)\n{\n  va_list srcFnmList;\n  va_start(srcFnmList, dst);\n  \n  DIAG_MsgIf(0, \"FileUtil::copy: ... -> \" << dst);\n\n  int dstFd = open(dst, O_WRONLY | O_CREAT | O_TRUNC,\n\t\t   S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);\n  if (dstFd < 0) {\n    DIAG_Throw(\"could not open destination '\" << dst << \"' (\"\n\t       << strerror(errno) << \")\");\n  }\n\n  string errorMsg;\n\n  char* srcFnm;\n  while ( (srcFnm = va_arg(srcFnmList, char*)) ) {\n    int srcFd = open(srcFnm, O_RDONLY);\n    if ((srcFd < 0) || (dstFd < 0)) {\n      errorMsg += (string(\"could not open '\") + srcFnm + \"' (\" \n\t\t   + strerror(errno) + \")\");\n    }\n    else {\n      cpy(srcFd, dstFd);\n      close(srcFd);\n    }\n  }\n\n  va_end(srcFnmList);\n  close(dstFd);\n\n  if (!errorMsg.empty()) {\n    DIAG_Throw(\"could not open source files: \" << errorMsg);\n  }\n}\n\n\nvoid\nmove(const char* dst, const char* src)\n{\n  int ret = rename(src, dst);\n  if (ret != 0) {\n    DIAG_Throw(\"moving '\" << src << \"' -> '\" << dst << \"'\");\n  }\n}\n\n\nint\nremove(const char* file)\n{ \n  return unlink(file);\n}\n\n\nint\nmkdir(const char* dir)\n{\n  if (!dir) {\n    DIAG_Throw(\"Invalid mkdir argument: (NULL)\");\n  }\n\n  string pathStr = dir;\n  bool isAbsPath = (dir[0] == '\/');\n\n  \/\/ -------------------------------------------------------\n  \/\/ 1. Convert path string to vector of path components\n  \/\/    \"\/p0\/p1\/p2\/...\/pn\/px\" ==> [p0 p1 p2 ... pn px]\n  \/\/    \"\/p0\"                 ==> [p0]\n  \/\/    \"p0\"                  ==> [p0]\n  \/\/    \".\/p0\"                ==> [. p0]\n  \/\/\n  \/\/ Note: we could do tokenization in place (string::find_last_of()),\n  \/\/ but (1) this is more elegant and (2) sytem calls and disk\n  \/\/ accesses will overwhelm any possible difference in performance.\n  \/\/ -------------------------------------------------------\n  std::vector pathVec;\n  StrUtil::tokenize_char(pathStr, \"\/\", pathVec);\n\n  DIAG_Assert(!pathVec.empty(), DIAG_UnexpectedInput);\n\n  \/\/ -------------------------------------------------------\n  \/\/ 2. Find 'curIdx' such that all paths before pathVec[curIdx] have\n  \/\/ been created.\n  \/\/\n  \/\/ Note: Start search from the last path component, assuming that in\n  \/\/ the common case, intermediate directories are already created.\n  \/\/\n  \/\/ Note: Could make this a binary search, but it would likely have\n  \/\/ insignificant effects.\n  \/\/ -------------------------------------------------------\n  size_t begIdx = 0;\n  size_t endIdx = pathVec.size() - 1;\n\n  size_t curIdx = endIdx;\n  for ( ; curIdx >= begIdx; --curIdx) {\n    string x = StrUtil::join(pathVec, \"\/\", 0, curIdx + 1);\n    if (isAbsPath) {\n      x = \"\/\" + x;\n    }\n    \n    if (isDir(x)) {\n      break; \/\/ FIXME: double check: what if this is a symlink?\n    }\n  }\n\n  curIdx++;\n\n  \/\/ -------------------------------------------------------\n  \/\/ 3. Build directories from pathVec[curIdx ... endIdx]\n  \/\/ -------------------------------------------------------\n  mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;\n\n  for ( ; curIdx <= endIdx; ++curIdx) {\n    string x = StrUtil::join(pathVec, \"\/\", 0, curIdx + 1);\n    if (isAbsPath) {\n      x = \"\/\" + x;\n    }\n\n    int ret = ::mkdir(x.c_str(), mode);\n    if (ret != 0) {\n      DIAG_Throw(\"While mkdir-ing '\" << pathStr << \"': Could not mkdir '\"\n\t\t << x << \"' (\" << strerror(errno) << \")\");\n    }\n  }\n\n  return 0;\n}\n\n\nstd::pair\nmkdirUnique(const char* dirnm)\n{\n  string dirnm_new = dirnm;\n  bool is_done = false;\n\n  mode_t mkmode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;\n\n  int ret = ::mkdir(dirnm, mkmode);\n  if (ret == -1) {\n    if (errno == EEXIST) {\n      \/\/ attempt to create dirnm+pid;\n      pid_t pid = getpid();\n      string pid_str = StrUtil::toStr(pid);\n      dirnm_new = dirnm_new + \"-\" + pid_str;\n      DIAG_Msg(1, \"Directory '\" << dirnm << \"' already exists. Trying \" << dirnm_new);\n      ret = ::mkdir(dirnm_new.c_str(), mkmode);\n      if (ret == -1) {\n\tDIAG_Die(\"Could not create alternate directory \" << dirnm_new);\n      }\n      else {\n\tDIAG_Msg(1, \"Created directory: \" << dirnm_new);\n\tis_done = true;\n      }\n    } \n    else {\n      DIAG_Die(\"Could not create database directory \" << dirnm);\n    }\n  }\n  \n  return make_pair(dirnm_new, is_done);\n}\n\n\nconst char*\ntmpname()\n{\n  \/\/ below is a hack to replace the deprecated tmpnam which g++ 3.2.2 will\n  \/\/ no longer allow. the mkstemp routine, which is touted as the replacement\n  \/\/ for tmpnam, provides a file descriptor as a return value. there is\n  \/\/ unfortunately no way to interface this with the ofstream class constructor\n  \/\/ which requires a filename. thus, a hack is born ...\n  \/\/ John Mellor-Crummey 5\/7\/2003\n  \n  \/\/ eraxxon: GNU is right that 'tmpnam' can be dangerous, but\n  \/\/ 'mkstemp' is not strictly part of C++! We could create an\n  \/\/ interface to 'mkstemp' within a C file, but this is getting\n  \/\/ cumbersome... and 'tmpnam' is not quite a WMD.\n\n#ifdef __GNUC__\n  static char tmpfilename[MAXPATHLEN];\n\n  \/\/ creating a unique temp name with the new mkstemp interface now \n  \/\/ requires opening, closing, and deleting a file when all we want\n  \/\/ is the filename. sigh ...\n  strcpy(tmpfilename,\"\/tmp\/hpcviewtmpXXXXXX\");\n  close(mkstemp(tmpfilename));\n  unlink(tmpfilename);\n\n  return tmpfilename;\n#else\n  return tmpnam(NULL); \n#endif\n}\n\n\n} \/\/ end of FileUtil namespace\n\nTweak several error messages.\/\/ -*-Mode: C++;-*-\n\n\/\/ * BeginRiceCopyright *****************************************************\n\/\/\n\/\/ $HeadURL$\n\/\/ $Id$\n\/\/\n\/\/ -----------------------------------\n\/\/ Part of HPCToolkit (hpctoolkit.org)\n\/\/ -----------------------------------\n\/\/ \n\/\/ Copyright ((c)) 2002-2010, Rice University \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/   notice, this list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/   notice, this list of conditions and the following disclaimer in the\n\/\/   documentation and\/or other materials provided with the distribution.\n\/\/ \n\/\/ * Neither the name of Rice University (RICE) nor the names of its\n\/\/   contributors may be used to endorse or promote products derived from\n\/\/   this software without specific prior written permission.\n\/\/ \n\/\/ This software is provided by RICE and contributors \"as is\" and any\n\/\/ express or implied warranties, including, but not limited to, the\n\/\/ implied warranties of merchantability and fitness for a particular\n\/\/ purpose are disclaimed. In no event shall RICE or contributors be\n\/\/ liable for any direct, indirect, incidental, special, exemplary, or\n\/\/ consequential damages (including, but not limited to, procurement of\n\/\/ substitute goods or services; loss of use, data, or profits; or\n\/\/ business interruption) however caused and on any theory of liability,\n\/\/ whether in contract, strict liability, or tort (including negligence\n\/\/ or otherwise) arising in any way out of the use of this software, even\n\/\/ if advised of the possibility of such damage. \n\/\/ \n\/\/ ******************************************************* EndRiceCopyright *\n\n\/\/***************************************************************************\n\n\/\/************************* System Include Files ****************************\n\n#include \n\n#include  \/\/ for 'mkstemp' (not technically visible in C++)\n#include   \/\/ for 'tmpnam', 'rename'\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \nusing std::string;\n\n\/\/*************************** User Include Files ****************************\n\n#include \"FileUtil.hpp\"\n\n#include \"diagnostics.h\"\n#include \"StrUtil.hpp\"\n#include \"Trace.hpp\"\n\n\/\/*************************** Forward Declarations **************************\n\nusing std::endl;\n\n\/\/***************************************************************************\n\/\/\n\/\/***************************************************************************\n\nnamespace FileUtil {\n\nstring\nbasename(const char* fName)\n{\n  string baseFileName;\n\n  const char* lastSlash = strrchr(fName, '\/');\n  if (lastSlash) {\n    \/\/ valid: \"\/foo\" || \"...\/foo\" AND invalid: \"\/\" || \"...\/\"\n    baseFileName = lastSlash + 1;\n  }\n  else {\n    \/\/ filename contains no slashes, already in short form\n    baseFileName = fName;\n  }\n  return baseFileName;\n\n#if 0\n  \/\/ A \"more C++\" implementation (Gaurav)\n  std::string\n  PathFindMgr::getFileName(const std::string& path) const\n  {\n    size_t in = path.find_last_of(\"\/\");\n    if (in != path.npos && path.length() > 1)\n      return path.substr(in + 1);\n    \n    return path;\n  }\n#endif\n}\n\n\nstring\nrmSuffix(const char* fName)\n{\n  string baseFileName = fName;\n\n  size_t pos = baseFileName.find_last_of('.');\n  if (pos != string::npos) {\n    baseFileName = baseFileName.substr(0, pos);\n  }\n  return baseFileName;\n}\n\n\nstring\ndirname(const char* fName)\n{\n  const char* lastSlash = strrchr(fName, '\/');\n  string pathComponent = \".\";\n  if (lastSlash) {\n    pathComponent = fName;\n    pathComponent.resize(lastSlash - fName);\n  }\n  return pathComponent;\n}\n\n\nbool\nfnmatch(const std::vector& patternVec,\n\tconst char* string, int flags)\n{\n  for (uint i = 0; i < patternVec.size(); ++i) {\n    const std::string& pat = patternVec[i];\n    bool fnd = FileUtil::fnmatch(pat, string, flags);\n    if (fnd) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\n} \/\/ end of FileUtil namespace\n\n\n\/\/***************************************************************************\n\/\/\n\/\/***************************************************************************\n\nnamespace FileUtil {\n\nbool\nisReadable(const char* path)\n{\n  struct stat sbuf;\n  if (stat(path, &sbuf) == 0) {\n    return true; \/\/ the file is readable\n  }\n  return false;\n}\n\n\nbool\nisDir(const char* path)\n{\n  struct stat sbuf;\n  if (stat(path, &sbuf) == 0) {\n    return (S_ISDIR(sbuf.st_mode)\n\t    \/*|| S_ISLNK(sbuf.st_mode) && isDir(readlink(path))*\/);\n  }\n  return false; \/\/ unknown\n}\n\n\nint\ncountChar(const char* path, char c)\n{\n  int srcFd = open(path, O_RDONLY); \n  if (srcFd < 0) {\n    return -1; \n  } \n  int count = 0;\n  char buf[256]; \n  ssize_t nRead; \n  while ((nRead = read(srcFd, buf, 256)) > 0) {\n    for (int i = 0; i < nRead; i++) {\n      if (buf[i] == c) count++; \n    }\n  }\n  return count; \n} \n\n} \/\/ end of FileUtil namespace\n\n\n\/\/***************************************************************************\n\/\/\n\/\/***************************************************************************\n\nstatic void\ncpy(int srcFd, int dstFd)\n{\n  static const int bufSz = 4096;\n  char buf[bufSz];\n  ssize_t nRead;\n  while ((nRead = read(srcFd, buf, bufSz)) > 0) {\n    write(dstFd, buf, nRead);\n  }\n}\n\n\nnamespace FileUtil {\n\nvoid\ncopy(const char* dst, ...)\n{\n  va_list srcFnmList;\n  va_start(srcFnmList, dst);\n  \n  DIAG_MsgIf(0, \"FileUtil::copy: ... -> \" << dst);\n\n  int dstFd = open(dst, O_WRONLY | O_CREAT | O_TRUNC,\n\t\t   S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);\n  if (dstFd < 0) {\n    DIAG_Throw(\"[FileUtil::copy] could not open destination file '\"\n\t       << dst << \"' (\" << strerror(errno) << \")\");\n  }\n\n  string errorMsg;\n\n  char* srcFnm;\n  while ( (srcFnm = va_arg(srcFnmList, char*)) ) {\n    int srcFd = open(srcFnm, O_RDONLY);\n    if ((srcFd < 0) || (dstFd < 0)) {\n      errorMsg += (string(\"could not open '\") + srcFnm + \"' (\" \n\t\t   + strerror(errno) + \")\");\n    }\n    else {\n      cpy(srcFd, dstFd);\n      close(srcFd);\n    }\n  }\n\n  va_end(srcFnmList);\n  close(dstFd);\n\n  if (!errorMsg.empty()) {\n    DIAG_Throw(\"[FileUtil::copy] could not open source files: \" << errorMsg);\n  }\n}\n\n\nvoid\nmove(const char* dst, const char* src)\n{\n  int ret = rename(src, dst);\n  if (ret != 0) {\n    DIAG_Throw(\"[FileUtil::move] '\" << src << \"' -> '\" << dst << \"'\");\n  }\n}\n\n\nint\nremove(const char* file)\n{ \n  return unlink(file);\n}\n\n\nint\nmkdir(const char* dir)\n{\n  if (!dir) {\n    DIAG_Throw(\"Invalid mkdir argument: (NULL)\");\n  }\n\n  string pathStr = dir;\n  bool isAbsPath = (dir[0] == '\/');\n\n  \/\/ -------------------------------------------------------\n  \/\/ 1. Convert path string to vector of path components\n  \/\/    \"\/p0\/p1\/p2\/...\/pn\/px\" ==> [p0 p1 p2 ... pn px]\n  \/\/    \"\/p0\"                 ==> [p0]\n  \/\/    \"p0\"                  ==> [p0]\n  \/\/    \".\/p0\"                ==> [. p0]\n  \/\/\n  \/\/ Note: we could do tokenization in place (string::find_last_of()),\n  \/\/ but (1) this is more elegant and (2) sytem calls and disk\n  \/\/ accesses will overwhelm any possible difference in performance.\n  \/\/ -------------------------------------------------------\n  std::vector pathVec;\n  StrUtil::tokenize_char(pathStr, \"\/\", pathVec);\n\n  DIAG_Assert(!pathVec.empty(), DIAG_UnexpectedInput);\n\n  \/\/ -------------------------------------------------------\n  \/\/ 2. Find 'curIdx' such that all paths before pathVec[curIdx] have\n  \/\/ been created.\n  \/\/\n  \/\/ Note: Start search from the last path component, assuming that in\n  \/\/ the common case, intermediate directories are already created.\n  \/\/\n  \/\/ Note: Could make this a binary search, but it would likely have\n  \/\/ insignificant effects.\n  \/\/ -------------------------------------------------------\n  size_t begIdx = 0;\n  size_t endIdx = pathVec.size() - 1;\n\n  size_t curIdx = endIdx;\n  for ( ; curIdx >= begIdx; --curIdx) {\n    string x = StrUtil::join(pathVec, \"\/\", 0, curIdx + 1);\n    if (isAbsPath) {\n      x = \"\/\" + x;\n    }\n    \n    if (isDir(x)) {\n      break; \/\/ FIXME: double check: what if this is a symlink?\n    }\n  }\n\n  curIdx++;\n\n  \/\/ -------------------------------------------------------\n  \/\/ 3. Build directories from pathVec[curIdx ... endIdx]\n  \/\/ -------------------------------------------------------\n  mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;\n\n  for ( ; curIdx <= endIdx; ++curIdx) {\n    string x = StrUtil::join(pathVec, \"\/\", 0, curIdx + 1);\n    if (isAbsPath) {\n      x = \"\/\" + x;\n    }\n\n    int ret = ::mkdir(x.c_str(), mode);\n    if (ret != 0) {\n      DIAG_Throw(\"[FileUtil::mkdir] '\" << pathStr << \"': Could not mkdir '\"\n\t\t << x << \"' (\" << strerror(errno) << \")\");\n    }\n  }\n\n  return 0;\n}\n\n\nstd::pair\nmkdirUnique(const char* dirnm)\n{\n  string dirnm_new = dirnm;\n  bool is_done = false;\n\n  mode_t mkmode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;\n\n  int ret = ::mkdir(dirnm, mkmode);\n  if (ret == -1) {\n    if (errno == EEXIST) {\n      \/\/ attempt to create dirnm+pid;\n      pid_t pid = getpid();\n      string pid_str = StrUtil::toStr(pid);\n      dirnm_new = dirnm_new + \"-\" + pid_str;\n      DIAG_Msg(1, \"Directory '\" << dirnm << \"' already exists. Trying \" << dirnm_new);\n      ret = ::mkdir(dirnm_new.c_str(), mkmode);\n      if (ret == -1) {\n\tDIAG_Die(\"Could not create alternate directory \" << dirnm_new);\n      }\n      else {\n\tDIAG_Msg(1, \"Created directory: \" << dirnm_new);\n\tis_done = true;\n      }\n    } \n    else {\n      DIAG_Die(\"Could not create database directory \" << dirnm);\n    }\n  }\n  \n  return make_pair(dirnm_new, is_done);\n}\n\n\nconst char*\ntmpname()\n{\n  \/\/ below is a hack to replace the deprecated tmpnam which g++ 3.2.2 will\n  \/\/ no longer allow. the mkstemp routine, which is touted as the replacement\n  \/\/ for tmpnam, provides a file descriptor as a return value. there is\n  \/\/ unfortunately no way to interface this with the ofstream class constructor\n  \/\/ which requires a filename. thus, a hack is born ...\n  \/\/ John Mellor-Crummey 5\/7\/2003\n  \n  \/\/ eraxxon: GNU is right that 'tmpnam' can be dangerous, but\n  \/\/ 'mkstemp' is not strictly part of C++! We could create an\n  \/\/ interface to 'mkstemp' within a C file, but this is getting\n  \/\/ cumbersome... and 'tmpnam' is not quite a WMD.\n\n#ifdef __GNUC__\n  static char tmpfilename[MAXPATHLEN];\n\n  \/\/ creating a unique temp name with the new mkstemp interface now \n  \/\/ requires opening, closing, and deleting a file when all we want\n  \/\/ is the filename. sigh ...\n  strcpy(tmpfilename,\"\/tmp\/hpcviewtmpXXXXXX\");\n  close(mkstemp(tmpfilename));\n  unlink(tmpfilename);\n\n  return tmpfilename;\n#else\n  return tmpnam(NULL); \n#endif\n}\n\n\n} \/\/ end of FileUtil namespace\n\n<|endoftext|>"}
{"text":"#include \"consoleui.h\"\n\nusing namespace std;\n\n\/\/ Presentation layer\n\/\/constructor\nConsoleUI::ConsoleUI()\n{\n}\n\/\/runs the whole program\nvoid ConsoleUI::run()\n{\n    string command;\n    bool loop = true;\n\n    bool openFileWorks= _service.load();\n\n    if (openFileWorks)\n    {\n        while(loop == true)\n        {\n            cout << \"Choose a command:\\n\";\n            cout << endl;\n            cout << \"register\\t- Register a scientist\\n\";\n            cout << \"list\\t\\t- Display the list of scientists\\n\";\n            cout << \"search\\t\\t- Search\\n\";\n            cout << \"edit\\t\\t- Edit scientist\\n\";\n            cout << \"delete\\t\\t- Delete scientist\\n\";\n            cout << \"quit\\t\\t- Exit program\\n\";\n            cout << endl;\n\n            cin >> command;\n\n            \/\/ The user can use one lowe case letter for shortcut\n            if (command == \"list\" || command == \"List\" || command == \"l\")\n            {\n                List();\n            }\n            else if (command == \"register\" || command == \"Register\" || command == \"r\")\n            {\n                Register();\n            }\n            else if (command == \"search\" || command == \"Search\" || command == \"s\")\n            {\n                Search();\n            }\n            else if (command == \"edit\" || command == \"Edit\" || command == \"e\")\n            {\n                Edit();\n            }\n            else if (command == \"delete\" || command == \"Delete\" || command == \"d\")\n            {\n                Delete();\n            }\n            else if (command == \"quit\" || command == \"Quit\" || command == \"q\")\n            {\n                loop = false;\n            }\n            else\n            {\n                cout << \"Please choose one of the given options!\\n\";\n            }\n        }\n    }\n    else\n    {\n        cout << \"Error with opening file\" << endl;\n    }\n}\n\/\/direction for edit scientist\nvoid ConsoleUI::Edit()\n{\n    \/\/ To Do edit functionality\n    cout << \"Edit registered scientist\" << endl;\n    int index;\n    string change, input;\n    \/\/Possible to do list or search\n    cout << \"Enter the index number of the scientist you want to change: \" << endl;\n    cin >> index;\n    \/\/Write the number of the scientist you want to change\n    cout << \"Enter what it is that you want to change about the scientist: (name\/gender\/birth\/death) \" << endl;\n    cin >> change;\n    cout << \"Enter the new value: \" << endl;\n    cin >> input;\n    \/\/What do you want to change about this scientist\n    string message = _service.editScientist(index, change, input);\n    cout << message << endl;\n}\n\/\/direction to delete scientist\nvoid ConsoleUI::Delete()\n{\n    int index;\n    char confirm;\n\n    cout << \"Delete registered scientist\" << endl;\n    cout << endl;\n    cout << \"Enter scientist number to delete: \";\n    cin >> index;\n\n    if (index < _service.getSize())\n    {\n\n        cout << \"Are you sure you want to delete \" << _service.getScientist(index).getName() << \"? (y\/n): \";\n        cin >> confirm;\n\n        if (confirm == 'y' || confirm == 'Y')\n        {\n            _service.deleteScientist(index);\n\n            cout << endl;\n            cout << \"Successfully deleted!\\n\";\n            cout << endl;\n        }\n    }\n    else if (index > _service.getSize())\n    {\n        cout << \"Exceeded number of entries!\\n\";\n        cout << endl;\n    }\n}\n\/\/direction to search for scientist\nvoid ConsoleUI::Search()\n{\n    string searchData;\n    \/\/Call the function searchScientists\n    cout << \"Searching by first letter\/s in the name\" << endl;\n    cout << \"Please write the letter\/s of the scientist\/s that you want to display\" << endl;\n    cin >> searchData;\n\n    vector foundScientists = _service.searchScientists(searchData);\n\n    cout << endl;\n\n    printFrame();\n\n    for (size_t i = 0; i < foundScientists.size(); i++)\n    {\n        cout.fill('0');\n        cout.width(2);\n        cout << right << foundScientists[i] << \". \";\n        cout.fill(' ');\n        cout.width(25);\n        cout << left;\n        cout << _service.getScientist(foundScientists[i]).getName();\n        cout << \"\\t\";\n        cout << _service.getScientist(foundScientists[i]).getGender();\n        cout << \"\\t\";\n        cout << left << _service.getScientist(foundScientists[i]).getYearOfBirth();\n        cout << \"\\t\";\n        cout << left << _service.getScientist(foundScientists[i]).getYearOfDeath();\n        cout << endl;\n    }\n\n    printFrame();\n\n    cout << endl;\n}\n\/\/direction to sort list\nvoid ConsoleUI::List()\n{\n    string sort;\n\n    while(sort != \"return\" && sort!= \"Return\" && sort != \"r\")\n    {\n        cout << endl;\n        cout << \"Write the option how you want your list sorted\\n\";\n        cout << endl;\n        cout << \"name\\t\\t- Sort by name\\n\";\n        cout << \"age\\t\\t- Sort by age\\n\";\n        cout << \"birth\\t\\t- Sort by year of birth\\n\";\n        cout << \"death\\t\\t- Sort by year of death\\n\";\n        cout << \"return\\t\\t- Return to main menu\\n\";\n        cout << endl;\n\n        cin >> sort;\n        vector _AllScientist = _service.getScientistVector();\n        _AllScientist = SortVector( _AllScientist, sort);\n\n        displayListOfScientist();\n    }\n}\n\/\/direction to register scientist\nvoid ConsoleUI::Register()\n{\n    string name;\n    string gender;\n    int yearOfBirth;\n    int yearOfDeath;\n\n    cout << \"Enter the name of the person:\" << endl;\n    cin.ignore();\n    getline(cin,name);\n\n    cout << \"Enter gender (m for male, f for female):\" << endl;\n    cin >> gender;\n    while (gender != \"m\" && gender != \"M\" && gender != \"f\" && gender != \"F\")\n    {\n        cout << \"Please enter either m or f!\\n\";\n        cin.clear();\n        cin >> gender;\n    }\n\n    cout << \"Enter year of birth:\" << endl;\n    cin >> yearOfBirth;\n    while (cin.fail())\n    {\n        cout << \"ERROR!! Please enter a valid option!\\n\";\n        cin.clear();\n        cin.ignore(256, '\\n');\n        cin >> yearOfBirth;\n    }\n    while (yearOfBirth > _time.getYearToDay() || yearOfBirth < 0)\n    {\n        cout << \"ERROR!! Please enter a valid year of birth!\\n\";\n        cin.clear();\n        cin >> yearOfBirth;\n    }\n\n    cout << \"Enter year of death or 0 if the person is still alive:\" << endl;\n    cin >> yearOfDeath;\n    while (cin.fail())\n    {\n        cout << \"ERROR!! Please enter a valid option!\\n\";\n        cin.clear();\n        cin.ignore(256, '\\n');\n        cin >> yearOfDeath;\n    }\n    while (yearOfDeath > _time.getYearToDay() || ((yearOfDeath < yearOfBirth) && yearOfDeath != 0) )\n    {\n        cout << \"ERROR!! Please enter a valid year of death!\\n\";\n        cin.clear();\n        cin >> yearOfDeath;\n    }\n\n    Scientist scientist(name, gender, yearOfBirth, yearOfDeath);\n    _service.addScientist(scientist);\n\n    cout << \"Scientist added!\" << endl;\n    cout << endl;\n}\n\/\/dislpays list of scientist\nvoid ConsoleUI::displayListOfScientist()\n{\n    \/\/vector _scientists = _service.getScientistVector();\n\n    printFrame();\n\n    cout << \"Nr. Scientist name\\t\\tGender\\tBirth\\tDeath\\tAge\" << endl;\n    cout <<\"\\t\\t\\t\\t\\tYear\\tYear\" << endl;\n\n    for (size_t i = 0; i < _service.getSize() - 1; i++)\n    {\n        cout.fill('0');\n        cout.width(2);\n        cout << right << i << \". \";\n        cout.fill(' ');\n        cout.width(25);\n        cout << left;\n        cout << _service.getScientist(i).getName();\n        cout << \"\\t\";\n        cout << _service.getScientist(i).getGender();\n        cout << \"\\t\";\n        cout << left << _service.getScientist(i).getYearOfBirth();\n        cout << \"\\t\";\n        cout << left << _service.getScientist(i).getYearOfDeath();\n        cout << \"\\t\";\n        cout << left << _service.getScientist(i).getAge();\n        cout << endl;\n    }\n\n    printFrame();\n}\n\nvoid ConsoleUI::printFrame()\n{\n    cout.fill('=');\n    cout.width(63);\n    cout << left << \"=\";\n    cout << endl;\n    cout.fill(' ');\n}\n\n\nvector ConsoleUI::SortVector(vector _listOfScientist,string sort)\n{\n   return _service.sortScientists(_listOfScientist, sort);\n}\nSmall text changes#include \"consoleui.h\"\n\nusing namespace std;\n\n\/\/ Presentation layer\n\/\/constructor\nConsoleUI::ConsoleUI()\n{\n}\n\/\/runs the whole program\nvoid ConsoleUI::run()\n{\n    string command;\n    bool loop = true;\n\n    bool openFileWorks= _service.load();\n\n    if (openFileWorks)\n    {\n        while(loop == true)\n        {\n            cout << \"Choose a command:\\n\";\n            cout << endl;\n            cout << \"register\\t- Register a scientist\\n\";\n            cout << \"list\\t\\t- Display the list of scientists\\n\";\n            cout << \"search\\t\\t- Search\\n\";\n            cout << \"edit\\t\\t- Edit scientist\\n\";\n            cout << \"delete\\t\\t- Delete scientist\\n\";\n            cout << \"quit\\t\\t- Exit program\\n\";\n            cout << endl;\n\n            cin >> command;\n\n            \/\/ The user can use one lowe case letter for shortcut\n            if (command == \"list\" || command == \"List\" || command == \"l\")\n            {\n                List();\n            }\n            else if (command == \"register\" || command == \"Register\" || command == \"r\")\n            {\n                Register();\n            }\n            else if (command == \"search\" || command == \"Search\" || command == \"s\")\n            {\n                Search();\n            }\n            else if (command == \"edit\" || command == \"Edit\" || command == \"e\")\n            {\n                Edit();\n            }\n            else if (command == \"delete\" || command == \"Delete\" || command == \"d\")\n            {\n                Delete();\n            }\n            else if (command == \"quit\" || command == \"Quit\" || command == \"q\")\n            {\n                loop = false;\n            }\n            else\n            {\n                cout << \"Please choose one of the given options!\\n\";\n            }\n        }\n    }\n    else\n    {\n        cout << \"Error with opening file\" << endl;\n    }\n}\n\/\/direction for edit scientist\nvoid ConsoleUI::Edit()\n{\n    \/\/ To Do edit functionality\n    cout << \"Edit registered scientist\" << endl;\n    int index;\n    string change, input;\n    \/\/Possible to do list or search\n    cout << \"Enter the index number of the scientist you want to change: \" << endl;\n    cin >> index;\n    \/\/Write the number of the scientist you want to change\n    cout << \"Enter what it is that you want to change about the scientist: (name\/gender\/birth\/death) \" << endl;\n    cin >> change;\n    cout << \"Enter the new value: \" << endl;\n    cin >> input;\n    \/\/What do you want to change about this scientist\n    string message = _service.editScientist(index, change, input);\n    cout << message << endl;\n}\n\/\/direction to delete scientist\nvoid ConsoleUI::Delete()\n{\n    int index;\n    char confirm;\n\n    cout << \"Delete registered scientist\" << endl;\n    cout << endl;\n    cout << \"Enter scientist number to delete: \";\n    cin >> index;\n\n    if (index < _service.getSize())\n    {\n\n        cout << \"Are you sure you want to delete \" << _service.getScientist(index).getName() << \"? (y\/n): \";\n        cin >> confirm;\n\n        if (confirm == 'y' || confirm == 'Y')\n        {\n            _service.deleteScientist(index);\n\n            cout << endl;\n            cout << \"Successfully deleted!\" << endl;\n            cout << endl;\n        }\n    }\n    else if (index > _service.getSize())\n    {\n        cout << \"Index out of range!\" << endl;\n        cout << endl;\n    }\n}\n\/\/direction to search for scientist\nvoid ConsoleUI::Search()\n{\n    string searchData;\n    \/\/Call the function searchScientists\n    cout << \"Searching by first letter\/s in the name\" << endl;\n    cout << \"Please write the letter\/s of the scientist\/s that you want to display\" << endl;\n    cin >> searchData;\n\n    vector foundScientists = _service.searchScientists(searchData);\n\n    cout << endl;\n\n    printFrame();\n\n    for (size_t i = 0; i < foundScientists.size(); i++)\n    {\n        cout.fill('0');\n        cout.width(2);\n        cout << right << foundScientists[i] << \". \";\n        cout.fill(' ');\n        cout.width(25);\n        cout << left;\n        cout << _service.getScientist(foundScientists[i]).getName();\n        cout << \"\\t\";\n        cout << _service.getScientist(foundScientists[i]).getGender();\n        cout << \"\\t\";\n        cout << left << _service.getScientist(foundScientists[i]).getYearOfBirth();\n        cout << \"\\t\";\n        cout << left << _service.getScientist(foundScientists[i]).getYearOfDeath();\n        cout << endl;\n    }\n\n    printFrame();\n\n    cout << endl;\n}\n\/\/direction to sort list\nvoid ConsoleUI::List()\n{\n    string sort;\n\n    while(sort != \"return\" && sort!= \"Return\" && sort != \"r\")\n    {\n        cout << endl;\n        cout << \"Write the option how you want your list sorted\\n\";\n        cout << endl;\n        cout << \"name\\t\\t- Sort by name\\n\";\n        cout << \"age\\t\\t- Sort by age\\n\";\n        cout << \"birth\\t\\t- Sort by year of birth\\n\";\n        cout << \"death\\t\\t- Sort by year of death\\n\";\n        cout << \"return\\t\\t- Return to main menu\\n\";\n        cout << endl;\n\n        cin >> sort;\n        vector _AllScientist = _service.getScientistVector();\n        _AllScientist = SortVector( _AllScientist, sort);\n\n        displayListOfScientist();\n    }\n}\n\/\/direction to register scientist\nvoid ConsoleUI::Register()\n{\n    string name;\n    string gender;\n    int yearOfBirth;\n    int yearOfDeath;\n\n    cout << \"Enter the name of the person:\" << endl;\n    cin.ignore();\n    getline(cin,name);\n\n    cout << \"Enter gender (m for male, f for female):\" << endl;\n    cin >> gender;\n    while (gender != \"m\" && gender != \"M\" && gender != \"f\" && gender != \"F\")\n    {\n        cout << \"Please enter either m or f!\\n\";\n        cin.clear();\n        cin >> gender;\n    }\n\n    cout << \"Enter year of birth:\" << endl;\n    cin >> yearOfBirth;\n    while (cin.fail())\n    {\n        cout << \"ERROR!! Please enter a valid option!\\n\";\n        cin.clear();\n        cin.ignore(256, '\\n');\n        cin >> yearOfBirth;\n    }\n    while (yearOfBirth > _time.getYearToDay() || yearOfBirth < 0)\n    {\n        cout << \"ERROR!! Please enter a valid year of birth!\\n\";\n        cin.clear();\n        cin >> yearOfBirth;\n    }\n\n    cout << \"Enter year of death or 0 if the person is still alive:\" << endl;\n    cin >> yearOfDeath;\n    while (cin.fail())\n    {\n        cout << \"ERROR!! Please enter a valid option!\\n\";\n        cin.clear();\n        cin.ignore(256, '\\n');\n        cin >> yearOfDeath;\n    }\n    while (yearOfDeath > _time.getYearToDay() || ((yearOfDeath < yearOfBirth) && yearOfDeath != 0) )\n    {\n        cout << \"ERROR!! Please enter a valid year of death!\\n\";\n        cin.clear();\n        cin >> yearOfDeath;\n    }\n\n    Scientist scientist(name, gender, yearOfBirth, yearOfDeath);\n    _service.addScientist(scientist);\n\n    cout << \"Scientist added!\" << endl;\n    cout << endl;\n}\n\/\/dislpays list of scientist\nvoid ConsoleUI::displayListOfScientist()\n{\n    \/\/vector _scientists = _service.getScientistVector();\n\n    printFrame();\n\n    cout << \"Nr. Scientist name\\t\\tGender\\tBirth\\tDeath\\tAge\" << endl;\n    cout <<\"\\t\\t\\t\\t\\tYear\\tYear\" << endl;\n\n    for (size_t i = 0; i < _service.getSize() - 1; i++)\n    {\n        cout.fill('0');\n        cout.width(2);\n        cout << right << i << \". \";\n        cout.fill(' ');\n        cout.width(25);\n        cout << left;\n        cout << _service.getScientist(i).getName();\n        cout << \"\\t\";\n        cout << _service.getScientist(i).getGender();\n        cout << \"\\t\";\n        cout << left << _service.getScientist(i).getYearOfBirth();\n        cout << \"\\t\";\n        cout << left << _service.getScientist(i).getYearOfDeath();\n        cout << \"\\t\";\n        cout << left << _service.getScientist(i).getAge();\n        cout << endl;\n    }\n\n    printFrame();\n}\n\nvoid ConsoleUI::printFrame()\n{\n    cout.fill('=');\n    cout.width(63);\n    cout << left << \"=\";\n    cout << endl;\n    cout.fill(' ');\n}\n\nvector ConsoleUI::SortVector(vector _listOfScientist,string sort)\n{\n   return _service.sortScientists(_listOfScientist, sort);\n}\n<|endoftext|>"}
{"text":"\/\/ Licensed GNU LGPL v3 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#ifndef __RAPICORN_THREADLIB_HH__\n#define __RAPICORN_THREADLIB_HH__\n\n#include \n\nnamespace Rapicorn {\nnamespace Lib {\n\n#define RAPICORN_CACHE_LINE_ALIGNMENT   128\n#define RAPICORN_MFENCE    __sync_synchronize() \/\/\/< Memory Fence - prevent processor (and compiler) from reordering loads\/stores (read\/write barrier).\n#define RAPICORN_SFENCE    RAPICORN_X86SFENCE   \/\/\/< Store Fence - prevent processor (and compiler) from reordering stores (write barrier).\n#define RAPICORN_LFENCE    RAPICORN_X86LFENCE   \/\/\/< Load Fence - prevent processor (and compiler) from reordering loads (read barrier).\n#define RAPICORN_CFENCE    __asm__ __volatile__ (\"\" ::: \"memory\") \/\/\/< Compiler Fence, prevent compiler from reordering non-volatiles loads\/stores.\n#define RAPICORN_X86LFENCE __asm__ __volatile__ (\"lfence\" ::: \"memory\") \/\/\/< X86 lfence - prevent processor from reordering loads (read barrier).\n#define RAPICORN_X86SFENCE __asm__ __volatile__ (\"sfence\" ::: \"memory\") \/\/\/< X86 sfence - prevent processor from reordering stores (write barrier).\n\ntemplate T    atomic_load  (T volatile *p)      { RAPICORN_CFENCE; T t = *p; RAPICORN_LFENCE; return t; }\ntemplate void atomic_store (T volatile *p, T i) { RAPICORN_SFENCE; *p = i;  RAPICORN_CFENCE; }\n\ntemplate\nclass Atomic {\n  T volatile v;\n  \/*ctor*\/  Atomic    () = delete;\n  \/*ctor*\/  Atomic    (T&&) = delete;\nprotected:\n  constexpr Atomic    (T i) : v (i) {}\n  Atomic& operator=(Atomic &o) { store (o.load()); return *this; }\n  Atomic volatile& operator=(Atomic &o) volatile { store (o.load()); return *this; }\npublic:\n  T         load      () const volatile { return atomic_load (&v); }\n  void      store     (T i)    volatile { atomic_store (&v, i); }\n  bool      cas  (T o, T n)    volatile { return __sync_bool_compare_and_swap (&v, o, n); }\n  T         operator+=(T i)    volatile { return __sync_add_and_fetch (&v, i); }\n  T         operator-=(T i)    volatile { return __sync_sub_and_fetch (&v, i); }\n  T         operator&=(T i)    volatile { return __sync_and_and_fetch (&v, i); }\n  T         operator^=(T i)    volatile { return __sync_xor_and_fetch (&v, i); }\n  T         operator|=(T i)    volatile { return __sync_or_and_fetch  (&v, i); }\n  T         operator++()       volatile { return __sync_add_and_fetch (&v, 1); }\n  T         operator++(int)    volatile { return __sync_fetch_and_add (&v, 1); }\n  T         operator--()       volatile { return __sync_sub_and_fetch (&v, 1); }\n  T         operator--(int)    volatile { return __sync_fetch_and_sub (&v, 1); }\n  void      operator= (T i)    volatile { store (i); }\n  operator  T         () const volatile { return load(); }\n};\n\n\/\/ == Once Scope ==\nvoid once_list_enter  ();\nbool once_list_bounce (volatile void *ptr);\nbool once_list_leave  (volatile void *ptr);\n\nclass OnceScope {\n  \/*ctor*\/       OnceScope (const OnceScope&) = delete;\n  OnceScope&     operator= (const OnceScope&) = delete;\n  volatile char *volatile flagp;\n  bool           entered_once;\npublic:\n  OnceScope (volatile char *volatile p) : flagp (p), entered_once (false) {}\n  inline bool\n  operator() ()\n  {\n    if (RAPICORN_LIKELY (*flagp != 0))\n      return false;\n    if (entered_once > 0)       \/\/ second or later invocation from for()\n      {\n        const bool is_first_initialization = __sync_bool_compare_and_swap (flagp, 0, 1);\n        const bool found_and_removed = once_list_leave (flagp);\n        if (!is_first_initialization || !found_and_removed)\n          printerr (\"__once: %s: assertion failed during leave: %d %d\", __func__, is_first_initialization, found_and_removed);\n      }\n    entered_once = 1;           \/\/ mark first invocation\n    once_list_enter();\n    const bool initialized = atomic_load (flagp) != 0;\n    const bool needs_init = once_list_bounce (initialized ? NULL : flagp);\n    return needs_init;\n  }\n};\n\n#define RAPICORN_ASECTION(bytes)    __attribute__ ((section (\".data.aligned\" #bytes), aligned (bytes)))\n#define RAPICORN_DO_ONCE_COUNTER    ({ static volatile char RAPICORN_ASECTION (1) __rapicorn_oncebyte_ = 0; &__rapicorn_oncebyte_; })\n#define RAPICORN_DO_ONCE   for (Rapicorn::Lib::OnceScope __rapicorn_oncescope_ (RAPICORN_DO_ONCE_COUNTER); __rapicorn_oncescope_(); )\n\n} \/\/ Lib\n} \/\/ Rapicorn\n\n\n#endif \/\/ __RAPICORN_THREADLIB_HH__\nRCORE: document Lib namespace as internal\/\/ Licensed GNU LGPL v3 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#ifndef __RAPICORN_THREADLIB_HH__\n#define __RAPICORN_THREADLIB_HH__\n\n#include \n\nnamespace Rapicorn {\nnamespace Lib { \/\/ Namespace for implementation internals\n\n#define RAPICORN_CACHE_LINE_ALIGNMENT   128\n#define RAPICORN_MFENCE    __sync_synchronize() \/\/\/< Memory Fence - prevent processor (and compiler) from reordering loads\/stores (read\/write barrier).\n#define RAPICORN_SFENCE    RAPICORN_X86SFENCE   \/\/\/< Store Fence - prevent processor (and compiler) from reordering stores (write barrier).\n#define RAPICORN_LFENCE    RAPICORN_X86LFENCE   \/\/\/< Load Fence - prevent processor (and compiler) from reordering loads (read barrier).\n#define RAPICORN_CFENCE    __asm__ __volatile__ (\"\" ::: \"memory\") \/\/\/< Compiler Fence, prevent compiler from reordering non-volatiles loads\/stores.\n#define RAPICORN_X86LFENCE __asm__ __volatile__ (\"lfence\" ::: \"memory\") \/\/\/< X86 lfence - prevent processor from reordering loads (read barrier).\n#define RAPICORN_X86SFENCE __asm__ __volatile__ (\"sfence\" ::: \"memory\") \/\/\/< X86 sfence - prevent processor from reordering stores (write barrier).\n\ntemplate T    atomic_load  (T volatile *p)      { RAPICORN_CFENCE; T t = *p; RAPICORN_LFENCE; return t; }\ntemplate void atomic_store (T volatile *p, T i) { RAPICORN_SFENCE; *p = i;  RAPICORN_CFENCE; }\n\ntemplate\nclass Atomic {\n  T volatile v;\n  \/*ctor*\/  Atomic    () = delete;\n  \/*ctor*\/  Atomic    (T&&) = delete;\nprotected:\n  constexpr Atomic    (T i) : v (i) {}\n  Atomic& operator=(Atomic &o) { store (o.load()); return *this; }\n  Atomic volatile& operator=(Atomic &o) volatile { store (o.load()); return *this; }\npublic:\n  T         load      () const volatile { return atomic_load (&v); }\n  void      store     (T i)    volatile { atomic_store (&v, i); }\n  bool      cas  (T o, T n)    volatile { return __sync_bool_compare_and_swap (&v, o, n); }\n  T         operator+=(T i)    volatile { return __sync_add_and_fetch (&v, i); }\n  T         operator-=(T i)    volatile { return __sync_sub_and_fetch (&v, i); }\n  T         operator&=(T i)    volatile { return __sync_and_and_fetch (&v, i); }\n  T         operator^=(T i)    volatile { return __sync_xor_and_fetch (&v, i); }\n  T         operator|=(T i)    volatile { return __sync_or_and_fetch  (&v, i); }\n  T         operator++()       volatile { return __sync_add_and_fetch (&v, 1); }\n  T         operator++(int)    volatile { return __sync_fetch_and_add (&v, 1); }\n  T         operator--()       volatile { return __sync_sub_and_fetch (&v, 1); }\n  T         operator--(int)    volatile { return __sync_fetch_and_sub (&v, 1); }\n  void      operator= (T i)    volatile { store (i); }\n  operator  T         () const volatile { return load(); }\n};\n\n\/\/ == Once Scope ==\nvoid once_list_enter  ();\nbool once_list_bounce (volatile void *ptr);\nbool once_list_leave  (volatile void *ptr);\n\nclass OnceScope {\n  \/*ctor*\/       OnceScope (const OnceScope&) = delete;\n  OnceScope&     operator= (const OnceScope&) = delete;\n  volatile char *volatile flagp;\n  bool           entered_once;\npublic:\n  OnceScope (volatile char *volatile p) : flagp (p), entered_once (false) {}\n  inline bool\n  operator() ()\n  {\n    if (RAPICORN_LIKELY (*flagp != 0))\n      return false;\n    if (entered_once > 0)       \/\/ second or later invocation from for()\n      {\n        const bool is_first_initialization = __sync_bool_compare_and_swap (flagp, 0, 1);\n        const bool found_and_removed = once_list_leave (flagp);\n        if (!is_first_initialization || !found_and_removed)\n          printerr (\"__once: %s: assertion failed during leave: %d %d\", __func__, is_first_initialization, found_and_removed);\n      }\n    entered_once = 1;           \/\/ mark first invocation\n    once_list_enter();\n    const bool initialized = atomic_load (flagp) != 0;\n    const bool needs_init = once_list_bounce (initialized ? NULL : flagp);\n    return needs_init;\n  }\n};\n\n#define RAPICORN_ASECTION(bytes)    __attribute__ ((section (\".data.aligned\" #bytes), aligned (bytes)))\n#define RAPICORN_DO_ONCE_COUNTER    ({ static volatile char RAPICORN_ASECTION (1) __rapicorn_oncebyte_ = 0; &__rapicorn_oncebyte_; })\n#define RAPICORN_DO_ONCE   for (Rapicorn::Lib::OnceScope __rapicorn_oncescope_ (RAPICORN_DO_ONCE_COUNTER); __rapicorn_oncescope_(); )\n\n} \/\/ Lib\n} \/\/ Rapicorn\n\n\n#endif \/\/ __RAPICORN_THREADLIB_HH__\n<|endoftext|>"}
{"text":"#include \"callwindow.h\"\n#include \"ui_callwindow.h\"\n\n#include \"ui_callingwidget.h\"\n\n#include \"statisticswindow.h\"\n\n#include \n#include \n#include \n#include \n\n\nconst uint16_t MAXOPENPORTS = 42;\nconst uint16_t PORTSPERPARTICIPANT = 4;\n\nCallWindow::CallWindow(QWidget *parent, uint16_t width, uint16_t height, QString name) :\n  QMainWindow(parent),\n  ui_(new Ui::CallWindow),\n  stats_(new StatisticsWindow(this)),\n  conference_(this),\n  callNeg_(),\n  media_(stats_),\n  timer_(new QTimer(this)),\n  currentResolution_(),\n  portsOpen_(0),\n  name_(name)\n{\n  ui_->setupUi(this);\n\n  currentResolution_ = QSize(width, height);\n\n  \/\/ GUI updates are handled solely by timer\n  timer_->setInterval(10);\n  timer_->setSingleShot(false);\n  connect(timer_, SIGNAL(timeout()), this, SLOT(update()));\n  connect(timer_, SIGNAL(timeout()), stats_, SLOT(update()));\n  timer_->start();\n\n  connect(ui_->stats, SIGNAL(clicked()), this, SLOT(openStatistics()));\n}\n\nCallWindow::~CallWindow()\n{\n  timer_->stop();\n  delete timer_;\n  stats_->close();\n  delete stats_;\n  delete ui_;\n\n  media_.uninit();\n}\n\nvoid CallWindow::startStream()\n{\n  Ui::CallerWidget *ui_widget = new Ui::CallerWidget;\n  QWidget* holderWidget = new QWidget;\n  ui_widget->setupUi(holderWidget);\n  connect(ui_widget->AcceptButton, SIGNAL(clicked()), this, SLOT(acceptCall()));\n  connect(ui_widget->DeclineButton, SIGNAL(clicked()), this, SLOT(rejectCall()));\n\n  callNeg_.init(name_);\n\n  QObject::connect(&callNeg_, SIGNAL(incomingINVITE(QString, QString)),\n                   this, SLOT(incomingCall(QString, QString)));\n\n  QObject::connect(&callNeg_, SIGNAL(callingOurselves(QString, std::shared_ptr)),\n                   this, SLOT(callOurselves(QString, std::shared_ptr)));\n\n  QObject::connect(&callNeg_, SIGNAL(callNegotiated(QString, std::shared_ptr,\n                                                              std::shared_ptr)),\n                   this, SLOT(callNegotiated(QString, std::shared_ptr,\n                                                      std::shared_ptr)));\n\n  QObject::connect(&callNeg_, SIGNAL(ringing(QString)),\n                   this, SLOT(ringing(QString)));\n\n  QObject::connect(&callNeg_, SIGNAL(ourCallAccepted(QString, std::shared_ptr,\n                                                               std::shared_ptr)),\n                   this, SLOT(callNegotiated(QString, std::shared_ptr,\n                                                      std::shared_ptr)));\n\n  QObject::connect(&callNeg_, SIGNAL(ourCallRejected(QString)),\n                   this, SLOT(ourCallRejected(QString)));\n\n  QObject::connect(&callNeg_, SIGNAL(callEnded(QString, QString)),\n                   this, SLOT(endCall(QString, QString)));\n\n  conferenceMutex_.lock();\n  conference_.init(ui_->participantLayout, ui_->participants, ui_widget, holderWidget);\n  conferenceMutex_.unlock();\n\n  media_.init();\n  media_.startCall(ui_->SelfView, currentResolution_);\n}\n\n\nvoid CallWindow::addParticipant()\n{\n\n  if(portsOpen_ <= MAXOPENPORTS)\n  {\n    QString ip_str = ui_->ip->toPlainText();\n\n    Contact con;\n    con.contactAddress = ip_str;\n    con.name = \"Unknown\";\n    if(!name_.isEmpty())\n    {\n      con.name = name_;\n    }\n    con.username = \"unknown\";\n\n    QList list;\n    list.append(con);\n\n    \/\/start negotiations for this connection\n\n    QList callIDs = callNeg_.startCall(list);\n\n    for(auto callID : callIDs)\n    {\n      conferenceMutex_.lock();\n      conference_.callingTo(callID, con.name);\n      conferenceMutex_.unlock();\n    }\n  }\n}\n\nvoid CallWindow::createParticipant(QString& callID, std::shared_ptr peerInfo,\n                                   const std::shared_ptr localInfo)\n{\n  qDebug() << \"Adding participant to conference.\";\n\n  QHostAddress address;\n  address.setAddress(peerInfo->globalAddress);\n\n  in_addr ip;\n  ip.S_un.S_addr = qToBigEndian(address.toIPv4Address());\n\n  conferenceMutex_.lock();\n  VideoWidget* view = conference_.addVideoStream(callID);\n  conferenceMutex_.unlock();\n\n  if(view == NULL)\n  {\n    qWarning() << \"WARNING: NULL widget got from\";\n    return;\n  }\n\n  \/\/ TODO: have these be arrays and send video to all of them in case SDP describes it so\n  uint16_t sendAudioPort = 0;\n  uint16_t recvAudioPort = 0;\n  uint16_t sendVideoPort = 0;\n  uint16_t recvVideoPort = 0;\n\n  for(auto media : localInfo->media)\n  {\n    if(media.type == \"audio\" && recvAudioPort == 0)\n    {\n      recvAudioPort = media.port;\n    }\n    else if(media.type == \"video\" && recvVideoPort == 0)\n    {\n      recvVideoPort = media.port;\n    }\n  }\n\n  for(auto media : peerInfo->media)\n  {\n    if(media.type == \"audio\" && sendAudioPort == 0)\n    {\n      sendAudioPort = media.port;\n    }\n    else if(media.type == \"video\" && sendVideoPort == 0)\n    {\n      sendVideoPort = media.port;\n    }\n  }\n\n  \/\/ TODO send all the media if more than one are specified and if required to more than one participant.\n  if(sendAudioPort == 0 || recvAudioPort == 0 || sendVideoPort == 0 || recvVideoPort == 0)\n  {\n    qWarning() << \"WARNING: All media ports were not found in given SDP. SendAudio:\" << sendAudioPort\n               << \"recvAudio:\" << recvAudioPort << \"SendVideo:\" << sendVideoPort << \"RecvVideo:\" << recvVideoPort;\n    return;\n  }\n\n  if(stats_)\n    stats_->addParticipant(peerInfo->globalAddress,\n                           QString::number(sendAudioPort),\n                           QString::number(sendVideoPort));\n\n  qDebug() << \"Sending mediastreams to:\" << peerInfo->globalAddress << \"audioPort:\" << sendAudioPort\n           << \"VideoPort:\" << sendVideoPort;\n  media_.addParticipant(callID, ip, sendAudioPort, recvAudioPort, sendVideoPort, recvVideoPort, view);\n}\n\nvoid CallWindow::openStatistics()\n{\n  stats_->show();\n}\n\nvoid CallWindow::micState()\n{\n  bool state = media_.toggleMic();\n\n  if(state)\n  {\n    ui_->mic->setText(\"Turn mic off\");\n  }\n  else\n  {\n    ui_->mic->setText(\"Turn mic on\");\n  }\n}\n\nvoid CallWindow::cameraState()\n{\n  bool state = media_.toggleCamera();\n  if(state)\n  {\n    ui_->camera->setText(\"Turn camera off\");\n  }\n  else\n  {\n    ui_->camera->setText(\"Turn camera on\");\n  }\n}\n\nvoid CallWindow::closeEvent(QCloseEvent *event)\n{\n  callNeg_.endAllCalls();\n\n  callNeg_.uninit();\n\n  media_.uninit();\n\n  stats_->hide();\n  stats_->finished(0);\n\n  conferenceMutex_.lock();\n  conference_.close();\n  conferenceMutex_.unlock();\n\n  QMainWindow::closeEvent(event);\n}\n\nvoid CallWindow::incomingCall(QString callID, QString caller)\n{\n  portsOpen_ +=PORTSPERPARTICIPANT;\n\n  if(portsOpen_ > MAXOPENPORTS)\n  {\n    qWarning() << \"WARNING: Ran out of ports:\" << portsOpen_ << \"\/\" << MAXOPENPORTS;\n    rejectCall(); \/\/ TODO: send a not possible message instead of reject.\n    return;\n  }\n\n  conferenceMutex_.lock();\n  conference_.incomingCall(callID, caller);\n  conferenceMutex_.unlock();\n}\n\nvoid CallWindow::callOurselves(QString callID, std::shared_ptr info)\n{\n  portsOpen_ +=PORTSPERPARTICIPANT;\n\n  if(portsOpen_ <= MAXOPENPORTS)\n  {\n    qDebug() << \"Calling ourselves, how boring.\";\n    createParticipant(callID, info, info);\n  }\n}\n\nvoid CallWindow::acceptCall()\n{\n  qDebug() << \"We accepted\";\n  conferenceMutex_.lock();\n  QString callID = conference_.acceptNewest();\n  conferenceMutex_.unlock();\n  callNeg_.acceptCall(callID);\n}\n\nvoid CallWindow::rejectCall()\n{\n  qDebug() << \"We rejected\";\n  conferenceMutex_.lock();\n  QString callID = conference_.rejectNewest();\n  conferenceMutex_.unlock();\n  callNeg_.rejectCall(callID);\n}\n\nvoid CallWindow::ringing(QString callID)\n{\n  qDebug() << \"call is ringing. TODO: display it to user\";\n}\n\nvoid CallWindow::ourCallRejected(QString callID)\n{\n  qDebug() << \"Our Call was rejected. TODO: display it to user\";\n  conferenceMutex_.lock();\n  conference_.removeCaller(callID);\n  conferenceMutex_.unlock();\n}\n\nvoid CallWindow::callNegotiated(QString callID, std::shared_ptr peerInfo,\n                                std::shared_ptr localInfo)\n{\n  qDebug() << \"Our call has been accepted.\";\n\n  qDebug() << \"Sending media to IP:\" << peerInfo->globalAddress\n           << \"to port:\" << peerInfo->media.first().port;\n\n  \/\/ TODO check the SDP info and do ports and rtp numbers properly\n  createParticipant(callID, peerInfo, localInfo);\n}\n\nvoid CallWindow::endCall(QString callID, QString ip)\n{\n  qDebug() << \"Received the end of call message\";\n\n  media_.endCall(callID); \/\/ must be ended first because of the view.\n\n  conferenceMutex_.lock();\n  conference_.removeCaller(callID);\n  conferenceMutex_.unlock();\n\n  stats_->removeParticipant(ip);\n}\nRemoved unnecessary uninit of media.#include \"callwindow.h\"\n#include \"ui_callwindow.h\"\n\n#include \"ui_callingwidget.h\"\n\n#include \"statisticswindow.h\"\n\n#include \n#include \n#include \n#include \n\n\nconst uint16_t MAXOPENPORTS = 42;\nconst uint16_t PORTSPERPARTICIPANT = 4;\n\nCallWindow::CallWindow(QWidget *parent, uint16_t width, uint16_t height, QString name) :\n  QMainWindow(parent),\n  ui_(new Ui::CallWindow),\n  stats_(new StatisticsWindow(this)),\n  conference_(this),\n  callNeg_(),\n  media_(stats_),\n  timer_(new QTimer(this)),\n  currentResolution_(),\n  portsOpen_(0),\n  name_(name)\n{\n  ui_->setupUi(this);\n\n  currentResolution_ = QSize(width, height);\n\n  \/\/ GUI updates are handled solely by timer\n  timer_->setInterval(10);\n  timer_->setSingleShot(false);\n  connect(timer_, SIGNAL(timeout()), this, SLOT(update()));\n  connect(timer_, SIGNAL(timeout()), stats_, SLOT(update()));\n  timer_->start();\n\n  connect(ui_->stats, SIGNAL(clicked()), this, SLOT(openStatistics()));\n}\n\nCallWindow::~CallWindow()\n{\n  timer_->stop();\n  delete timer_;\n  stats_->close();\n  delete stats_;\n  delete ui_;\n}\n\nvoid CallWindow::startStream()\n{\n  Ui::CallerWidget *ui_widget = new Ui::CallerWidget;\n  QWidget* holderWidget = new QWidget;\n  ui_widget->setupUi(holderWidget);\n  connect(ui_widget->AcceptButton, SIGNAL(clicked()), this, SLOT(acceptCall()));\n  connect(ui_widget->DeclineButton, SIGNAL(clicked()), this, SLOT(rejectCall()));\n\n  callNeg_.init(name_);\n\n  QObject::connect(&callNeg_, SIGNAL(incomingINVITE(QString, QString)),\n                   this, SLOT(incomingCall(QString, QString)));\n\n  QObject::connect(&callNeg_, SIGNAL(callingOurselves(QString, std::shared_ptr)),\n                   this, SLOT(callOurselves(QString, std::shared_ptr)));\n\n  QObject::connect(&callNeg_, SIGNAL(callNegotiated(QString, std::shared_ptr,\n                                                              std::shared_ptr)),\n                   this, SLOT(callNegotiated(QString, std::shared_ptr,\n                                                      std::shared_ptr)));\n\n  QObject::connect(&callNeg_, SIGNAL(ringing(QString)),\n                   this, SLOT(ringing(QString)));\n\n  QObject::connect(&callNeg_, SIGNAL(ourCallAccepted(QString, std::shared_ptr,\n                                                               std::shared_ptr)),\n                   this, SLOT(callNegotiated(QString, std::shared_ptr,\n                                                      std::shared_ptr)));\n\n  QObject::connect(&callNeg_, SIGNAL(ourCallRejected(QString)),\n                   this, SLOT(ourCallRejected(QString)));\n\n  QObject::connect(&callNeg_, SIGNAL(callEnded(QString, QString)),\n                   this, SLOT(endCall(QString, QString)));\n\n  conferenceMutex_.lock();\n  conference_.init(ui_->participantLayout, ui_->participants, ui_widget, holderWidget);\n  conferenceMutex_.unlock();\n\n  media_.init();\n  media_.startCall(ui_->SelfView, currentResolution_);\n}\n\n\nvoid CallWindow::addParticipant()\n{\n\n  if(portsOpen_ <= MAXOPENPORTS)\n  {\n    QString ip_str = ui_->ip->toPlainText();\n\n    Contact con;\n    con.contactAddress = ip_str;\n    con.name = \"Unknown\";\n    if(!name_.isEmpty())\n    {\n      con.name = name_;\n    }\n    con.username = \"unknown\";\n\n    QList list;\n    list.append(con);\n\n    \/\/start negotiations for this connection\n\n    QList callIDs = callNeg_.startCall(list);\n\n    for(auto callID : callIDs)\n    {\n      conferenceMutex_.lock();\n      conference_.callingTo(callID, con.name);\n      conferenceMutex_.unlock();\n    }\n  }\n}\n\nvoid CallWindow::createParticipant(QString& callID, std::shared_ptr peerInfo,\n                                   const std::shared_ptr localInfo)\n{\n  qDebug() << \"Adding participant to conference.\";\n\n  QHostAddress address;\n  address.setAddress(peerInfo->globalAddress);\n\n  in_addr ip;\n  ip.S_un.S_addr = qToBigEndian(address.toIPv4Address());\n\n  conferenceMutex_.lock();\n  VideoWidget* view = conference_.addVideoStream(callID);\n  conferenceMutex_.unlock();\n\n  if(view == NULL)\n  {\n    qWarning() << \"WARNING: NULL widget got from\";\n    return;\n  }\n\n  \/\/ TODO: have these be arrays and send video to all of them in case SDP describes it so\n  uint16_t sendAudioPort = 0;\n  uint16_t recvAudioPort = 0;\n  uint16_t sendVideoPort = 0;\n  uint16_t recvVideoPort = 0;\n\n  for(auto media : localInfo->media)\n  {\n    if(media.type == \"audio\" && recvAudioPort == 0)\n    {\n      recvAudioPort = media.port;\n    }\n    else if(media.type == \"video\" && recvVideoPort == 0)\n    {\n      recvVideoPort = media.port;\n    }\n  }\n\n  for(auto media : peerInfo->media)\n  {\n    if(media.type == \"audio\" && sendAudioPort == 0)\n    {\n      sendAudioPort = media.port;\n    }\n    else if(media.type == \"video\" && sendVideoPort == 0)\n    {\n      sendVideoPort = media.port;\n    }\n  }\n\n  \/\/ TODO send all the media if more than one are specified and if required to more than one participant.\n  if(sendAudioPort == 0 || recvAudioPort == 0 || sendVideoPort == 0 || recvVideoPort == 0)\n  {\n    qWarning() << \"WARNING: All media ports were not found in given SDP. SendAudio:\" << sendAudioPort\n               << \"recvAudio:\" << recvAudioPort << \"SendVideo:\" << sendVideoPort << \"RecvVideo:\" << recvVideoPort;\n    return;\n  }\n\n  if(stats_)\n    stats_->addParticipant(peerInfo->globalAddress,\n                           QString::number(sendAudioPort),\n                           QString::number(sendVideoPort));\n\n  qDebug() << \"Sending mediastreams to:\" << peerInfo->globalAddress << \"audioPort:\" << sendAudioPort\n           << \"VideoPort:\" << sendVideoPort;\n  media_.addParticipant(callID, ip, sendAudioPort, recvAudioPort, sendVideoPort, recvVideoPort, view);\n}\n\nvoid CallWindow::openStatistics()\n{\n  stats_->show();\n}\n\nvoid CallWindow::micState()\n{\n  bool state = media_.toggleMic();\n\n  if(state)\n  {\n    ui_->mic->setText(\"Turn mic off\");\n  }\n  else\n  {\n    ui_->mic->setText(\"Turn mic on\");\n  }\n}\n\nvoid CallWindow::cameraState()\n{\n  bool state = media_.toggleCamera();\n  if(state)\n  {\n    ui_->camera->setText(\"Turn camera off\");\n  }\n  else\n  {\n    ui_->camera->setText(\"Turn camera on\");\n  }\n}\n\nvoid CallWindow::closeEvent(QCloseEvent *event)\n{\n  callNeg_.endAllCalls();\n\n  callNeg_.uninit();\n\n  media_.uninit();\n\n  stats_->hide();\n  stats_->finished(0);\n\n  conferenceMutex_.lock();\n  conference_.close();\n  conferenceMutex_.unlock();\n\n  QMainWindow::closeEvent(event);\n}\n\nvoid CallWindow::incomingCall(QString callID, QString caller)\n{\n  portsOpen_ +=PORTSPERPARTICIPANT;\n\n  if(portsOpen_ > MAXOPENPORTS)\n  {\n    qWarning() << \"WARNING: Ran out of ports:\" << portsOpen_ << \"\/\" << MAXOPENPORTS;\n    rejectCall(); \/\/ TODO: send a not possible message instead of reject.\n    return;\n  }\n\n  conferenceMutex_.lock();\n  conference_.incomingCall(callID, caller);\n  conferenceMutex_.unlock();\n}\n\nvoid CallWindow::callOurselves(QString callID, std::shared_ptr info)\n{\n  portsOpen_ +=PORTSPERPARTICIPANT;\n\n  if(portsOpen_ <= MAXOPENPORTS)\n  {\n    qDebug() << \"Calling ourselves, how boring.\";\n    createParticipant(callID, info, info);\n  }\n}\n\nvoid CallWindow::acceptCall()\n{\n  qDebug() << \"We accepted\";\n  conferenceMutex_.lock();\n  QString callID = conference_.acceptNewest();\n  conferenceMutex_.unlock();\n  callNeg_.acceptCall(callID);\n}\n\nvoid CallWindow::rejectCall()\n{\n  qDebug() << \"We rejected\";\n  conferenceMutex_.lock();\n  QString callID = conference_.rejectNewest();\n  conferenceMutex_.unlock();\n  callNeg_.rejectCall(callID);\n}\n\nvoid CallWindow::ringing(QString callID)\n{\n  qDebug() << \"call is ringing. TODO: display it to user\";\n}\n\nvoid CallWindow::ourCallRejected(QString callID)\n{\n  qDebug() << \"Our Call was rejected. TODO: display it to user\";\n  conferenceMutex_.lock();\n  conference_.removeCaller(callID);\n  conferenceMutex_.unlock();\n}\n\nvoid CallWindow::callNegotiated(QString callID, std::shared_ptr peerInfo,\n                                std::shared_ptr localInfo)\n{\n  qDebug() << \"Our call has been accepted.\";\n\n  qDebug() << \"Sending media to IP:\" << peerInfo->globalAddress\n           << \"to port:\" << peerInfo->media.first().port;\n\n  \/\/ TODO check the SDP info and do ports and rtp numbers properly\n  createParticipant(callID, peerInfo, localInfo);\n}\n\nvoid CallWindow::endCall(QString callID, QString ip)\n{\n  qDebug() << \"Received the end of call message\";\n\n  media_.endCall(callID); \/\/ must be ended first because of the view.\n\n  conferenceMutex_.lock();\n  conference_.removeCaller(callID);\n  conferenceMutex_.unlock();\n\n  stats_->removeParticipant(ip);\n}\n<|endoftext|>"}
{"text":"#ifndef CTHREAD_FORWARD_LIST\n#define CTHREAD_FORWARD_LIST\n#include\n#include\n#include\t\/\/allocator\n#include\n#include\t\/\/forward, move_if_noexcept\n\/\/#include\n\/\/#include\n\/\/#include\t\/\/shared_ptr\n\/\/#include\n\/\/#include\n\/\/#include\t\/\/forward, move, swap\n\nnamespace nThread\n{\n\ttemplate>\n\tclass CThread_forward_list\t\/\/a thread-safe std::forward_list\n\t{\n\tpublic:\n\t\tusing allocator_type=Alloc;\n\t\tusing value_type=T;\n\tprivate:\n\t\tstd::condition_variable insert_;\n\t\tstd::mutex insertMut_;\n\t\tstd::forward_list fwd_list_;\n\tpublic:\n\t\tCThread_forward_list()\n\t\t\t:CThread_forward_list{allocator_type()}{}\n\t\texplicit CThread_forward_list(const allocator_type &alloc)\n\t\t\t:fwd_list_{alloc}{}\n\t\ttemplate\n\t\tvoid emplace_front(Args &&...args)\n\t\t{\n\t\t\tbool notify;\n\t\t\tstd::lock_guard lock{insertMut_};\n\t\t\tnotify=fwd_list_.empty();\n\t\t\tfwd_list_.emplace_front(std::forward(args)...);\n\t\t\tif(notify)\n\t\t\t\tinsert_.notify_all();\n\t\t}\n\t\tinline bool empty() const noexcept\n\t\t{\n\t\t\treturn fwd_list_.empty();\n\t\t}\n\t\ttemplate\n\t\tvoid remove_if(UnaryPred &&pred)\n\t\t{\n\t\t\tstd::lock_guard lock{insertMut_};\n\t\t\tfwd_list_.remove_if(std::forward(pred));\n\t\t}\n\t\t\/\/if constructor or assignment operator you use here is not noexcept, it may not be exception safety\n\t\tvalue_type wait_and_pop_front()\n\t\t{\n\t\t\tstd::unique_lock lock{insertMut_};\n\t\t\tinsert_.wait(lock,[this]() noexcept{return !empty();});\n\t\t\t\/\/1. if move constructor is noexcept, it is exception safety\n\t\t\t\/\/2. if move constructor is not noexcept and copy constructor exists, it is exception safety\n\t\t\t\/\/3. if move constructor is not noexcept and copy constructor does not exist, it may not be exception safety\n\t\t\tconst auto temp{std::move_if_noexcept(fwd_list_.front())};\n\t\t\tfwd_list_.pop_front();\n\t\t\tlock.unlock();\n\t\t\treturn temp;\n\t\t}\n\t};\n\n\t\/\/template\n\t\/\/class CThread_forward_list\n\t\/\/{\n\t\/\/public:\n\t\/\/\tusing value_type=T;\n\t\/\/private:\n\t\/\/\tstruct Node\n\t\/\/\t{\n\t\/\/\t\tvalue_type data;\n\t\/\/\t\tstd::shared_ptr next;\n\t\/\/\t\ttemplate\n\t\/\/\t\tNode(shared_ptrFwdRef &&next_,Args &&...args)\n\t\/\/\t\t\t:data{std::forward(args)...},next{std::forward(next_)}{}\n\t\/\/\t\t~Node()\n\t\/\/\t\t{\n\t\/\/\t\t\twhile(next.use_count()==1)\n\t\/\/\t\t\t{\n\t\/\/\t\t\t\tstd::shared_ptr p{std::move(next->next)};\n\t\/\/\t\t\t\tnext.reset();\n\t\/\/\t\t\t\tnext=std::move(p);\n\t\/\/\t\t\t}\n\t\/\/\t\t}\n\t\/\/\t};\n\t\/\/\tstd::shared_ptr begin_;\n\t\/\/\tstd::condition_variable cv_;\n\t\/\/\tstd::shared_mutex remove_mut_;\n\t\/\/\tstd::mutex wait_mut_;\n\t\/\/public:\n\t\/\/\tCThread_forward_list()=default;\n\t\/\/\tCThread_forward_list(const CThread_forward_list &)=delete;\n\t\/\/\ttemplate\n\t\/\/\tvoid emplace_front(Args &&...args)\n\t\/\/\t{\n\t\/\/\t\tconst std::shared_ptr node{std::make_shared(std::atomic_load_explicit(&begin_,std::memory_order_relaxed),std::forward(args)...)};\n\t\/\/\t\tstd::shared_lock lock{remove_mut_};\n\t\/\/\t\twhile(!std::atomic_compare_exchange_weak_explicit(&begin_,&node->next,node,std::memory_order_release,std::memory_order_relaxed))\n\t\/\/\t\t\t;\n\t\/\/\t\tcv_.notify_one();\n\t\/\/\t}\n\t\/\/\t\/\/1. do not call emplace_not_ts with greater than or equal to 2 threads at same time\n\t\/\/\t\/\/2. do not call CAtomic_stack::pop_front, CAtomic_stack::remove, CAtomic_stack::remove_if or CAtomic_stack::wait_and_pop_front at same time\n\t\/\/\ttemplate\n\t\/\/\tinline void emplace_not_ts(Args &&...args)\n\t\/\/\t{\n\t\/\/\t\tbegin_=std::make_shared(begin_,std::forward(args)...);\n\t\/\/\t}\n\t\/\/\tinline bool empty() const noexcept\n\t\/\/\t{\n\t\/\/\t\treturn !begin_.operator bool();\n\t\/\/\t}\n\t\/\/\t\/\/if constructor or assignment operator you use here is not noexcept, it may not be exception safety\n\t\/\/\tvalue_type pop_front()\n\t\/\/\t{\n\t\/\/\t\tstd::shared_ptr node{std::atomic_load_explicit(&begin_,std::memory_order_relaxed)};\n\t\/\/\t\tstd::shared_lock lock{remove_mut_};\n\t\/\/\t\twhile(!std::atomic_compare_exchange_weak_explicit(&begin_,&node,node->next,std::memory_order_acquire,std::memory_order_relaxed))\n\t\/\/\t\t\t;\n\t\/\/\t\treturn std::move(node->data);\n\t\/\/\t}\n\t\/\/\tinline void remove(const value_type &remove_val)\n\t\/\/\t{\n\t\/\/\t\tremove_if([&](const auto &val) noexcept{return val==remove_val;});\n\t\/\/\t}\n\t\/\/\t\/\/will block CAtomic_stack::emplace_front, CAtomic_stack::pop_front and CAtomic_stack::wait_and_pop_front\n\t\/\/\ttemplate\n\t\/\/\tvoid remove_if(const UnaryPred pred)\n\t\/\/\t{\n\t\/\/\t\tstd::lock lock{remove_mut_};\n\t\/\/\t\tfor(std::shared_ptr bef{begin_},iter{bef};iter;)\n\t\/\/\t\t\tif(pred(iter->data))\n\t\/\/\t\t\t\tif(begin_==iter)\n\t\/\/\t\t\t\t{\n\t\/\/\t\t\t\t\titer=iter->next;\n\t\/\/\t\t\t\t\tbegin_=bef=iter;\n\t\/\/\t\t\t\t}\n\t\/\/\t\t\t\telse\n\t\/\/\t\t\t\t{\n\t\/\/\t\t\t\t\tstd::swap(bef->next,iter->next);\n\t\/\/\t\t\t\t\titer=bef->next;\n\t\/\/\t\t\t\t}\n\t\/\/\t\t\telse\n\t\/\/\t\t\t{\n\t\/\/\t\t\t\tbef=iter;\n\t\/\/\t\t\t\titer=iter->next;\n\t\/\/\t\t\t}\n\t\/\/\t}\n\t\/\/\t\/\/1. if constructor or assignment operator you use here is not noexcept, it may not be exception safety\n\t\/\/\t\/\/2. will block wait_and_pop_front\n\t\/\/\tvalue_type wait_and_pop_front()\n\t\/\/\t{\n\t\/\/\t\tstd::unique_lock lock{wait_mut_};\n\t\/\/\t\tcv_.wait(lock,[this]() noexcept{return !empty();});\n\t\/\/\t\t\/\/1. if move constructor is noexcept, it is exception safety\n\t\/\/\t\t\/\/2. if move constructor is not noexcept and copy constructor exists, it is exception safety\n\t\/\/\t\t\/\/3. if move constructor is not noexcept and copy constructor does not exist, it may not be exception safety\n\t\/\/\t\tconst auto temp{pop_front()};\n\t\/\/\t\tlock.unlock();\n\t\/\/\t\treturn temp;\n\t\/\/\t}\n\t\/\/\tCThread_forward_list& operator=(const CThread_forward_list &)=delete;\n\t\/\/};\n}\n\n#endiffix emplace_front#ifndef CTHREAD_FORWARD_LIST\n#define CTHREAD_FORWARD_LIST\n#include\n#include\n#include\t\/\/allocator\n#include\n#include\t\/\/forward, move_if_noexcept\n\/\/#include\n\/\/#include\n\/\/#include\t\/\/shared_ptr\n\/\/#include\n\/\/#include\n\/\/#include\t\/\/forward, move, swap\n\nnamespace nThread\n{\n\ttemplate>\n\tclass CThread_forward_list\t\/\/a thread-safe std::forward_list\n\t{\n\tpublic:\n\t\tusing allocator_type=Alloc;\n\t\tusing value_type=T;\n\tprivate:\n\t\tstd::condition_variable insert_;\n\t\tstd::mutex insertMut_;\n\t\tstd::forward_list fwd_list_;\n\tpublic:\n\t\tCThread_forward_list()\n\t\t\t:CThread_forward_list{allocator_type()}{}\n\t\texplicit CThread_forward_list(const allocator_type &alloc)\n\t\t\t:fwd_list_{alloc}{}\n\t\ttemplate\n\t\tvoid emplace_front(Args &&...args)\n\t\t{\n\t\t\tbool notify;\n\t\t\tstd::lock_guard lock{insertMut_};\n\t\t\tnotify=fwd_list_.empty();\n\t\t\tfwd_list_.emplace_front(std::forward(args)...);\n\t\t\tif(notify)\n\t\t\t\tinsert_.notify_all();\n\t\t}\n\t\tinline bool empty() const noexcept\n\t\t{\n\t\t\treturn fwd_list_.empty();\n\t\t}\n\t\ttemplate\n\t\tvoid remove_if(UnaryPred &&pred)\n\t\t{\n\t\t\tstd::lock_guard lock{insertMut_};\n\t\t\tfwd_list_.remove_if(std::forward(pred));\n\t\t}\n\t\t\/\/if constructor or assignment operator you use here is not noexcept, it may not be exception safety\n\t\tvalue_type wait_and_pop_front()\n\t\t{\n\t\t\tstd::unique_lock lock{insertMut_};\n\t\t\tinsert_.wait(lock,[this]() noexcept{return !empty();});\n\t\t\t\/\/1. if move constructor is noexcept, it is exception safety\n\t\t\t\/\/2. if move constructor is not noexcept and copy constructor exists, it is exception safety\n\t\t\t\/\/3. if move constructor is not noexcept and copy constructor does not exist, it may not be exception safety\n\t\t\tconst auto temp{std::move_if_noexcept(fwd_list_.front())};\n\t\t\tfwd_list_.pop_front();\n\t\t\tlock.unlock();\n\t\t\treturn temp;\n\t\t}\n\t};\n\n\t\/\/template\n\t\/\/class CThread_forward_list\n\t\/\/{\n\t\/\/public:\n\t\/\/\tusing value_type=T;\n\t\/\/private:\n\t\/\/\tstruct Node\n\t\/\/\t{\n\t\/\/\t\tvalue_type data;\n\t\/\/\t\tstd::shared_ptr next;\n\t\/\/\t\ttemplate\n\t\/\/\t\tNode(shared_ptrFwdRef &&next_,Args &&...args)\n\t\/\/\t\t\t:data{std::forward(args)...},next{std::forward(next_)}{}\n\t\/\/\t\t~Node()\n\t\/\/\t\t{\n\t\/\/\t\t\twhile(next.use_count()==1)\n\t\/\/\t\t\t{\n\t\/\/\t\t\t\tstd::shared_ptr p{std::move(next->next)};\n\t\/\/\t\t\t\tnext.reset();\n\t\/\/\t\t\t\tnext=std::move(p);\n\t\/\/\t\t\t}\n\t\/\/\t\t}\n\t\/\/\t};\n\t\/\/\tstd::shared_ptr begin_;\n\t\/\/\tstd::condition_variable cv_;\n\t\/\/\tstd::shared_mutex remove_mut_;\n\t\/\/\tstd::mutex wait_mut_;\n\t\/\/public:\n\t\/\/\tCThread_forward_list()=default;\n\t\/\/\tCThread_forward_list(const CThread_forward_list &)=delete;\n\t\/\/\ttemplate\n\t\/\/\tvoid emplace_front(Args &&...args)\n\t\/\/\t{\n\t\/\/\t\tconst std::shared_ptr node{std::make_shared(std::atomic_load_explicit(&begin_,std::memory_order_relaxed),std::forward(args)...)};\n\t\/\/\t\tstd::shared_lock lock{remove_mut_};\n\t\/\/\t\twhile(!std::atomic_compare_exchange_weak_explicit(&begin_,&node->next,node,std::memory_order_release,std::memory_order_relaxed))\n\t\/\/\t\t\t;\n\t\/\/\t\tstd::lock_guard lock{wait_mut_};\n\t\/\/\t\tcv_.notify_one();\n\t\/\/\t}\n\t\/\/\t\/\/1. do not call emplace_not_ts with greater than or equal to 2 threads at same time\n\t\/\/\t\/\/2. do not call CAtomic_stack::pop_front, CAtomic_stack::remove, CAtomic_stack::remove_if or CAtomic_stack::wait_and_pop_front at same time\n\t\/\/\ttemplate\n\t\/\/\tinline void emplace_not_ts(Args &&...args)\n\t\/\/\t{\n\t\/\/\t\tbegin_=std::make_shared(begin_,std::forward(args)...);\n\t\/\/\t}\n\t\/\/\tinline bool empty() const noexcept\n\t\/\/\t{\n\t\/\/\t\treturn !begin_.operator bool();\n\t\/\/\t}\n\t\/\/\t\/\/if constructor or assignment operator you use here is not noexcept, it may not be exception safety\n\t\/\/\tvalue_type pop_front()\n\t\/\/\t{\n\t\/\/\t\tstd::shared_ptr node{std::atomic_load_explicit(&begin_,std::memory_order_relaxed)};\n\t\/\/\t\tstd::shared_lock lock{remove_mut_};\n\t\/\/\t\twhile(!std::atomic_compare_exchange_weak_explicit(&begin_,&node,node->next,std::memory_order_acquire,std::memory_order_relaxed))\n\t\/\/\t\t\t;\n\t\/\/\t\treturn std::move(node->data);\n\t\/\/\t}\n\t\/\/\tinline void remove(const value_type &remove_val)\n\t\/\/\t{\n\t\/\/\t\tremove_if([&](const auto &val) noexcept{return val==remove_val;});\n\t\/\/\t}\n\t\/\/\t\/\/will block CAtomic_stack::emplace_front, CAtomic_stack::pop_front and CAtomic_stack::wait_and_pop_front\n\t\/\/\ttemplate\n\t\/\/\tvoid remove_if(const UnaryPred pred)\n\t\/\/\t{\n\t\/\/\t\tstd::lock lock{remove_mut_};\n\t\/\/\t\tfor(std::shared_ptr bef{begin_},iter{bef};iter;)\n\t\/\/\t\t\tif(pred(iter->data))\n\t\/\/\t\t\t\tif(begin_==iter)\n\t\/\/\t\t\t\t{\n\t\/\/\t\t\t\t\titer=iter->next;\n\t\/\/\t\t\t\t\tbegin_=bef=iter;\n\t\/\/\t\t\t\t}\n\t\/\/\t\t\t\telse\n\t\/\/\t\t\t\t{\n\t\/\/\t\t\t\t\tstd::swap(bef->next,iter->next);\n\t\/\/\t\t\t\t\titer=bef->next;\n\t\/\/\t\t\t\t}\n\t\/\/\t\t\telse\n\t\/\/\t\t\t{\n\t\/\/\t\t\t\tbef=iter;\n\t\/\/\t\t\t\titer=iter->next;\n\t\/\/\t\t\t}\n\t\/\/\t}\n\t\/\/\t\/\/1. if constructor or assignment operator you use here is not noexcept, it may not be exception safety\n\t\/\/\t\/\/2. will block wait_and_pop_front\n\t\/\/\tvalue_type wait_and_pop_front()\n\t\/\/\t{\n\t\/\/\t\tstd::unique_lock lock{wait_mut_};\n\t\/\/\t\tcv_.wait(lock,[this]() noexcept{return !empty();});\n\t\/\/\t\t\/\/1. if move constructor is noexcept, it is exception safety\n\t\/\/\t\t\/\/2. if move constructor is not noexcept and copy constructor exists, it is exception safety\n\t\/\/\t\t\/\/3. if move constructor is not noexcept and copy constructor does not exist, it may not be exception safety\n\t\/\/\t\tconst auto temp{pop_front()};\n\t\/\/\t\tlock.unlock();\n\t\/\/\t\treturn temp;\n\t\/\/\t}\n\t\/\/\tCThread_forward_list& operator=(const CThread_forward_list &)=delete;\n\t\/\/};\n}\n\n#endif<|endoftext|>"}
{"text":"#include \nprograminit()\n\n\tfunction main() {\n\n\tvar timestarted = time();\n\n\tvar db1 = COMMAND.a(2);\n\tvar db2 = COMMAND.a(3);\n\n\tvar silent = OPTIONS.index(\"S\");\n\n\tif (not silent)\n\t\tlogputl(\"compdbs says 'Hello World!'\");\n\n\tif (not(db1.connect())) {\n\t\tcall fsmsg();\n\t\tstop(1);\n\t}\n\n\tif (not(db2.connect())) {\n\t\tcall fsmsg();\n\t\tstop(1);\n\t}\n\n\tint nerrors = 0;\n\n\tvar filenames = COMMAND.field(FM, 4, 9999);\n\tif (not filenames)\n\t\tfilenames = db1.listfiles();\n\tfor (var filename : filenames) {\n\n\t\tif (not silent)\n\t\t\toutputl(\"\\n\", filename);\n\n\t\tif (filename.substr(1,10) eq \"preselect_\" or filename.substr(1,14) eq \"select_stage2_\" or filename eq \"dict_all\" or filename eq \"processes\")\n\t\t\tcontinue;\n\n\t\tvar file1;\n\t\tif (not file1.open(filename, db1)) {\n\t\t\tcall fsmsg();\n\t\t\tstop(1);\n\t\t}\n\n\t\tvar reccount = file1.reccount();\n\n\t\tvar file2;\n\t\tif (not file2.open(filename, db2)) {\n\t\t\tcall fsmsg();\n\t\t\tstop(1);\n\t\t}\n\n\t\t\/\/var keys;\n\t\t\/\/if (keys.osread(\"qwerty\")) {\n\t\t\/\/\tkeys.converter(\"\\n\", FM);\n\t\t\/\/\tfile1.makelist(\"\", keys);\n\t\t\/\/} else\n\t\t\tfile1.select(\"SELECT \" ^ filename ^ \" (SR)\");\n\n\t\tvar recn = 0;\n\t\twhile (file1.readnext(RECORD, ID, MV)) {\n\n\t\t\tif (esctoexit())\n\t\t\t\tstop(1);\n\n\t\t\trecn++;\n\t\t\tif (not silent) {\n\t\t\t\toutput(at(-40), recn, \"\/\", reccount, \" \", ID);\n\t\t\t\t\/\/printl(\"\",RECORD.length());\n\t\t\t\tif ((recn % 1000) eq 1)\n\t\t\t\t\tosflush();\n\t\t\t}\n\n\t\t\tif (not RECORD) {\n\t\t\t\tif (not RECORD.read(file1, ID)) {\n\t\t\t\t\terrputl(ID, \"missing from filename\", db1.a(1));\n\t\t\t\t\tnerrors++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar rec2;\n\t\t\tif (not read(rec2, file2, ID)) {\n\t\t\t\terrputl(ID, \" missing from\", db2.a(1), filename);\n\t\t\t\tnerrors++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (rec2 ne RECORD and ID.substr(-5,5) != \"_XREF\") {\n\n\t\t\t\t\/*\n\t\t\t\t\/\/revert both records to leading zero 0.1, -0.1 instead of old pickos .1 and -.1;\n\t\t\t\tRECORD.replacer(\"([\\x1A-\\x1F]-?)0\\\\.\", \"$1.\");\n\t\t\t\trec2.replacer(\"([\\x1A-\\x1F]-?)0\\\\.\", \"$1.\");\n\n\t\t\t\t\/\/RECORD is db1 and rec2 is db2\n\n\t\t\t\t\/\/temp suppress ads field 56\n\t\t\t\tif (filename eq \"ads\") {\n\t\t\t\t\tRECORD.r(56, rec2.a(56));\n\t\t\t\t\tRECORD.swapper(\".000\", \"\");\n\t\t\t\t\trec2.swapper(\".000\", \"\");\n\t\t\t\t\tRECORD.replacer(\"\\\\.00([\\x1A-\\x1F])\", \"$1\");\n\t\t\t\t\trec2.replacer(\"\\\\.00([\\x1A-\\x1F])\", \"$1\");\n\t\t\t\t} else if (filename eq \"brands\") {\n\t\t\t\t\tRECORD.r(14, rec2.a(14));\n\t\t\t\t\tRECORD.r(15, rec2.a(15));\n\t\t\t\t}\n\n\t\t\t\t\/\/if still different, output\n\t\t\t\tRECORD.cropper();\n\t\t\t\trec2.cropper();\n\t\t\t\t*\/\n\t\t\t\tif (rec2 ne RECORD) {\n\t\t\t\t\tnerrors++;\n\t\t\t\t\t\/\/errputl(\" \", ID, \" different.\");\n\t\t\t\t\t\/\/printl(RECORD);\n\t\t\t\t\t\/\/printl(rec2);\n\t\t\t\t\tvar nfs = dcount(RECORD, FM);\n\t\t\t\t\tvar nfs2 = dcount(rec2, FM);\n\t\t\t\t\tif (nfs2 gt nfs)\n\t\t\t\t\t\tnfs = nfs2;\n\t\t\t\t\tfor (var fn = 1; fn <= nfs; ++fn) {\n\t\t\t\t\t\tvar f1 = RECORD.a(fn);\n\t\t\t\t\t\tvar f2 = rec2.a(fn);\n\t\t\t\t\t\tif (f1 ne f2) {\n\t\t\t\t\t\t\terrputl();\n\t\t\t\t\t\t\terrputl(filename, \" \", ID, \" \", fn, \"-\", f1);\n\t\t\t\t\t\t\terrputl(filename, \" \", ID, \" \", fn, \"+\", f2);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/call stopper(\"\",timestarted,datestarted);\n\n\tif (not silent) {\n\t\tlogputl();\n\t\tvar seconds = time() - timestarted;\n\t\twhile (seconds < 0)\n\t\t\tseconds += 86400;\n\t\tlogputl(\"Finished in\", int(seconds \/ 60), \"minutes and\", mod(seconds, 60), \"seconds.\");\n\t}\n\n\treturn nerrors;\n\n}\n\nprogramexit()\nexclude locks and statistics from dbcomp to allow dbcomp with running database#include \nprograminit()\n\n\tfunction main() {\n\n\tvar timestarted = time();\n\n\tvar db1 = COMMAND.a(2);\n\tvar db2 = COMMAND.a(3);\n\n\tvar silent = OPTIONS.index(\"S\");\n\n\tif (not silent)\n\t\tlogputl(\"dbcomp says 'Hello World!'\");\n\n\tif (not(db1.connect())) {\n\t\tcall fsmsg();\n\t\tstop(1);\n\t}\n\n\tif (not(db2.connect())) {\n\t\tcall fsmsg();\n\t\tstop(1);\n\t}\n\n\tint nerrors = 0;\n\n\tvar exclude_filenames=\"dict_all\";\n\tvar filenames = COMMAND.field(FM, 4, 9999);\n\tif (not filenames) {\n\t\tfilenames = db1.listfiles();\n\t\t\/\/TODO get from command line somehow to avoid hardcoding\n\t\texclude_filenames ^= _VM_ \"processes\" _VM_ \"locks\" _VM_ \"statistics\" _VM_ \"requestlog\";\n\t}\n\tfor (var filename : filenames) {\n\n\t\tif (not silent)\n\t\t\toutputl(\"\\n\", filename);\n\n\t\tif (filename.substr(1,10) eq \"preselect_\" or filename.substr(1,14) eq \"select_stage2_\" or locate(filename,exclude_filenames))\n\t\t\tcontinue;\n\n\t\tvar file1;\n\t\tif (not file1.open(filename, db1)) {\n\t\t\tcall fsmsg();\n\t\t\tstop(1);\n\t\t}\n\n\t\tvar reccount = file1.reccount();\n\n\t\tvar file2;\n\t\tif (not file2.open(filename, db2)) {\n\t\t\tcall fsmsg();\n\t\t\tstop(1);\n\t\t}\n\n\t\t\/\/var keys;\n\t\t\/\/if (keys.osread(\"qwerty\")) {\n\t\t\/\/\tkeys.converter(\"\\n\", FM);\n\t\t\/\/\tfile1.makelist(\"\", keys);\n\t\t\/\/} else\n\t\t\tfile1.select(\"SELECT \" ^ filename ^ \" (SR)\");\n\n\t\tvar recn = 0;\n\t\twhile (file1.readnext(RECORD, ID, MV)) {\n\n\t\t\tif (esctoexit())\n\t\t\t\tstop(1);\n\n\t\t\trecn++;\n\t\t\tif (not silent) {\n\t\t\t\toutput(at(-40), recn, \"\/\", reccount, \" \", ID);\n\t\t\t\t\/\/printl(\"\",RECORD.length());\n\t\t\t\tif ((recn % 1000) eq 1)\n\t\t\t\t\tosflush();\n\t\t\t}\n\n\t\t\tif (not RECORD) {\n\t\t\t\tif (not RECORD.read(file1, ID)) {\n\t\t\t\t\terrputl(ID, \"missing from filename\", db1.a(1));\n\t\t\t\t\tnerrors++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar rec2;\n\t\t\tif (not read(rec2, file2, ID)) {\n\t\t\t\terrputl(ID, \" missing from\", db2.a(1), filename);\n\t\t\t\tnerrors++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (rec2 ne RECORD and ID.substr(-5,5) != \"_XREF\") {\n\n\t\t\t\t\/*\n\t\t\t\t\/\/revert both records to leading zero 0.1, -0.1 instead of old pickos .1 and -.1;\n\t\t\t\tRECORD.replacer(\"([\\x1A-\\x1F]-?)0\\\\.\", \"$1.\");\n\t\t\t\trec2.replacer(\"([\\x1A-\\x1F]-?)0\\\\.\", \"$1.\");\n\n\t\t\t\t\/\/RECORD is db1 and rec2 is db2\n\n\t\t\t\t\/\/temp suppress ads field 56\n\t\t\t\tif (filename eq \"ads\") {\n\t\t\t\t\tRECORD.r(56, rec2.a(56));\n\t\t\t\t\tRECORD.swapper(\".000\", \"\");\n\t\t\t\t\trec2.swapper(\".000\", \"\");\n\t\t\t\t\tRECORD.replacer(\"\\\\.00([\\x1A-\\x1F])\", \"$1\");\n\t\t\t\t\trec2.replacer(\"\\\\.00([\\x1A-\\x1F])\", \"$1\");\n\t\t\t\t} else if (filename eq \"brands\") {\n\t\t\t\t\tRECORD.r(14, rec2.a(14));\n\t\t\t\t\tRECORD.r(15, rec2.a(15));\n\t\t\t\t}\n\n\t\t\t\t\/\/if still different, output\n\t\t\t\tRECORD.cropper();\n\t\t\t\trec2.cropper();\n\t\t\t\t*\/\n\t\t\t\tif (rec2 ne RECORD) {\n\t\t\t\t\tnerrors++;\n\t\t\t\t\t\/\/errputl(\" \", ID, \" different.\");\n\t\t\t\t\t\/\/printl(RECORD);\n\t\t\t\t\t\/\/printl(rec2);\n\t\t\t\t\tvar nfs = dcount(RECORD, FM);\n\t\t\t\t\tvar nfs2 = dcount(rec2, FM);\n\t\t\t\t\tif (nfs2 gt nfs)\n\t\t\t\t\t\tnfs = nfs2;\n\t\t\t\t\tfor (var fn = 1; fn <= nfs; ++fn) {\n\t\t\t\t\t\tvar f1 = RECORD.a(fn);\n\t\t\t\t\t\tvar f2 = rec2.a(fn);\n\t\t\t\t\t\tif (f1 ne f2) {\n\t\t\t\t\t\t\terrputl();\n\t\t\t\t\t\t\terrputl(filename, \" \", ID, \" \", fn, \"-\", f1);\n\t\t\t\t\t\t\terrputl(filename, \" \", ID, \" \", fn, \"+\", f2);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/call stopper(\"\",timestarted,datestarted);\n\n\tif (not silent) {\n\t\tlogputl();\n\t\tvar seconds = time() - timestarted;\n\t\twhile (seconds < 0)\n\t\t\tseconds += 86400;\n\t\tlogputl(\"Finished in\", int(seconds \/ 60), \"minutes and\", mod(seconds, 60), \"seconds.\");\n\t}\n\n\treturn nerrors;\n\n}\n\nprogramexit()\n<|endoftext|>"}
{"text":"#include \r\n#include \r\nusing namespace std;\r\n#define N 10000\r\nclass Timer\r\n{\r\npublic:\r\n\tTimer()\r\n\t\t: start_(std::chrono::high_resolution_clock::now())\r\n\t{\r\n\t}\r\n\r\n\t~Timer()\r\n\t{\r\n\t\tconst auto finish = std::chrono::high_resolution_clock::now();\r\n\t\tstd::cout << std::chrono::duration_cast(finish - start_).count() << \" us\" << std::endl;\r\n\t}\r\n\r\nprivate:\r\n\tconst std::chrono::high_resolution_clock::time_point start_;\r\n};\r\n\r\nint main() {\r\n\tint** firstMatrix = new int*[N]; \r\n\r\n\tfor (int i = 0; i < N; ++i) {\r\n\t\tfirstMatrix[i] = new int[N];\r\n\t\t\r\n\t\tfor (int j = 0; j < N; ++j) { \r\n\t\t\tfirstMatrix[i][j] = 1;\r\n\t\t\t\r\n\t\t}\r\n\t}\r\n\tint sum = 0;\r\n\t{\r\n\t\tTimer t;\r\n\t\tfor (int i = 0; i < N; ++i) {\r\n\t\t\tfor (int j = 0; j < N; ++j) {\t\t\t\t\r\n\t\t\t\tsum += firstMatrix[j][i]; \r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < N; ++i) {\r\n\t\tdelete[] firstMatrix[i];\r\n\t\t\r\n\t}\r\n\tdelete[] firstMatrix;\r\n\tcout << sum << endl;\r\n\treturn 0;\r\n}\r\nUpdate sum_by_columns.cpp#include \r\n#include \r\nusing namespace std;\r\n#define N 10000\r\nclass Timer\r\n{\r\npublic:\r\n\tTimer()\r\n\t\t: start_(std::chrono::high_resolution_clock::now())\r\n\t{\r\n\t}\r\n\r\n\t~Timer()\r\n\t{\r\n\t\tconst auto finish = std::chrono::high_resolution_clock::now();\r\n\t\tstd::cout << std::chrono::duration_cast(finish - start_).count() << \" us\" << std::endl;\r\n\t}\r\n\r\nprivate:\r\n\tconst std::chrono::high_resolution_clock::time_point start_;\r\n};\r\n\r\nint main() {\r\n\tint** matrix = new int*[N]; \r\n\r\n\tfor (int i = 0; i < N; ++i) {\r\n\t\tmatrix[i] = new int[N];\r\n\t\t\r\n\t\tfor (int j = 0; j < N; ++j) { \r\n\t\t\tmatrix[i][j] = 1;\r\n\t\t\t\r\n\t\t}\r\n\t}\r\n\tint sum = 0;\r\n\t{\r\n\t\tTimer t;\r\n\t\tfor (int i = 0; i < N; ++i) {\r\n\t\t\tfor (int j = 0; j < N; ++j) {\t\t\t\t\r\n\t\t\t\tsum += matrix[j][i]; \r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < N; ++i) {\r\n\t\tdelete[] matrix[i];\r\n\t\t\r\n\t}\r\n\tdelete[] matrix;\r\n\tcout << sum << endl;\r\n\treturn 0;\r\n}\r\n<|endoftext|>"}
{"text":"#include \"asocket.h\"\n\n\/\/ STL\n#include \n#include \n#include \n#include \n\n\/\/ PDTK\n#include \"cxxutils\/error_helpers.h\"\n#include \"cxxutils\/streamcolors.h\"\n#include \"nonposix\/getpeercred.h\"\n\n#ifndef CMSG_LEN\n#define CMSG_ALIGN(len) (((len) + sizeof(size_t) - 1) & (size_t) ~ (sizeof(size_t) - 1))\n#define CMSG_SPACE(len) (CMSG_ALIGN (len) + CMSG_ALIGN (sizeof (struct cmsghdr)))\n#define CMSG_LEN(len)   (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len))\n#endif\n\nstatic_assert(sizeof(uint8_t) == sizeof(char), \"size mismatch!\");\n\nnamespace posix\n{\n  inline bool getpeercred(fd_t sockfd, proccred_t& cred)\n    { return ::getpeercred(sockfd, cred) == posix::success; }\n}\n\nAsyncSocket::AsyncSocket(void)\n  : AsyncSocket(posix::socket(EDomain::unix, EType::stream, EProtocol::unspec, 0))\n{\n}\n\nAsyncSocket::AsyncSocket(posix::fd_t socket)\n  : m_socket(socket)\n{\n}\n\nAsyncSocket::~AsyncSocket(void)\n{\n  if(m_read.is_connected())\n    m_read.disconnect();\n  if(m_write.is_connected())\n    m_write.disconnect();\n  if(m_socket != posix::invalid_descriptor)\n    posix::close(m_socket);\n  m_socket = posix::invalid_descriptor;\n  m_accept.detach();\n}\n\nbool AsyncSocket::bind(const char *socket_path, int socket_backlog)\n{\n  if(m_read.is_connected())\n    return false;\n\n  assert(std::strlen(socket_path) < sizeof(sockaddr_un::sun_path));\n  m_selfaddr = socket_path;\n  m_selfaddr = EDomain::unix;\n  bool ok = posix::bind(m_socket, m_selfaddr, m_selfaddr.size());\n  ok = ok && posix::listen(m_socket, socket_backlog);\n  if(ok)\n    m_accept = std::thread(&AsyncSocket::async_accept, this);\n  return ok;\n}\n\nvoid AsyncSocket::async_accept(void)\n{\n  posix::sockaddr_t m_peeraddr;\n  proccred_t m_peercred;\n\n  socklen_t addrlen;\n  m_read.connection = posix::accept(m_socket, m_peeraddr, &addrlen);\n  m_write.connection = ::dup(m_read.connection);\n  if(m_read.is_connected() &&\n     posix::getpeercred(m_read.connection, m_peercred))\n  {\n    enqueue(connectedToPeer, m_peeraddr, m_peercred);\n    m_read .thread = std::thread(&AsyncSocket::async_read , this);\n    m_write.thread = std::thread(&AsyncSocket::async_write, this);\n  }\n}\n\nbool AsyncSocket::connect(const char *socket_path)\n{\n  if(m_read.is_connected())\n    return false;\n\n  assert(std::strlen(socket_path) < sizeof(sockaddr_un::sun_path));\n  proccred_t m_peercred;\n  posix::sockaddr_t m_peeraddr;\n  m_peeraddr = socket_path;\n  m_peeraddr = EDomain::unix;\n\n  m_read.connection = m_socket;\n  bool ok = m_read.connect(m_peeraddr);\n  ok = ok && posix::getpeercred(m_read.connection, m_peercred);\n  if(ok)\n  {\n    m_write.connection = ::dup(m_read.connection);\n    enqueue(connectedToPeer, m_peeraddr, m_peercred);\n    m_read .thread = std::thread(&AsyncSocket::async_read , this);\n    m_write.thread = std::thread(&AsyncSocket::async_write, this);\n  }\n  else\n    m_read.connection = posix::invalid_descriptor;\n  return ok;\n}\n\nvoid AsyncSocket::async_read(void)\n{\n  std::mutex m;\n  msghdr msg = {};\n  iovec iov = {};\n\n  msg.msg_iov = &iov;\n  msg.msg_iovlen = 1;\n\n  for(;;)\n  {\n    m_read.buffer.allocate(); \/\/ allocate 64KB buffer\n    std::unique_lock lk(m);\n    m_read.condition.wait(lk, [this] { return m_read.is_connected(); } );\n\n    iov.iov_base = m_read.buffer.data();\n    iov.iov_len = m_read.buffer.capacity();\n    if(m_read.buffer.expand(posix::recvmsg(m_read.connection, &msg, 0)))\n    {\n      if(msg.msg_controllen == CMSG_SPACE(sizeof(int)))\n      {\n        cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);\n        if(cmsg->cmsg_level == SOL_SOCKET &&\n           cmsg->cmsg_type == SCM_RIGHTS &&\n           cmsg->cmsg_len == CMSG_LEN(sizeof(int)))\n         m_read.fd = *reinterpret_cast(CMSG_DATA(cmsg));\n      }\n      else\n        m_read.fd = posix::invalid_descriptor;\n      enqueue(readFinished, m_read.buffer, m_read.fd);\n    }\n    else \/\/ error\n      std::cout << std::flush << std::endl << std::red << \"error: \" << ::strerror(errno) << std::none << std::endl << std::flush;\n  }\n}\n\nvoid AsyncSocket::async_write(void)\n{\n  std::mutex m;\n  msghdr msg = {};\n  iovec iov = {};\n  char aux_buffer[CMSG_SPACE(sizeof(int)) + CMSG_SPACE(sizeof(ucred))] = { 0 };\n\n  msg.msg_iov = &iov;\n  msg.msg_iovlen = 1;\n  msg.msg_control = aux_buffer;\n\n  for(;;)\n  {\n    std::unique_lock lk(m);\n    m_write.condition.wait(lk, [this] { return m_write.is_connected() && !m_write.buffer.empty(); } );\n\n    iov.iov_base = m_write.buffer.begin();\n    iov.iov_len = m_write.buffer.size();\n\n    msg.msg_controllen = 0;\n\n    if(m_write.fd != posix::invalid_descriptor)\n    {\n      msg.msg_controllen = CMSG_SPACE(sizeof(int));\n      cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);\n      cmsg->cmsg_level = SOL_SOCKET;\n      cmsg->cmsg_type = SCM_RIGHTS;\n      cmsg->cmsg_len = CMSG_LEN(sizeof(int));\n      *reinterpret_cast(CMSG_DATA(cmsg)) = m_write.fd;\n    }\n\n    int count = posix::sendmsg(m_write.connection, &msg, 0);\n    if(count == posix::error_response) \/\/ error\n      std::cout << std::flush << std::endl << std::red << \"error: \" << ::strerror(errno) << std::none << std::endl << std::flush;\n    else\n      enqueue(writeFinished, count);\n    m_write.buffer.resize(0);\n  }\n}\n\nbool AsyncSocket::read(void)\n{\n  if(!m_read.is_connected())\n    return false;\n  m_read.condition.notify_one();\n  return true;\n}\n\nbool AsyncSocket::write(vqueue& buffer, posix::fd_t fd)\n{\n  if(!m_read.is_connected())\n    return false;\n\n  m_write.fd = fd;\n  m_write.buffer = buffer; \/\/ share buffer memory\n  m_write.condition.notify_one();\n  return true;\n}\nunlike socket file on exit#include \"asocket.h\"\n\n\/\/ STL\n#include \n#include \n#include \n#include \n\n\/\/ PDTK\n#include \"cxxutils\/error_helpers.h\"\n#include \"cxxutils\/streamcolors.h\"\n#include \"nonposix\/getpeercred.h\"\n\n#ifndef CMSG_LEN\n#define CMSG_ALIGN(len) (((len) + sizeof(size_t) - 1) & (size_t) ~ (sizeof(size_t) - 1))\n#define CMSG_SPACE(len) (CMSG_ALIGN (len) + CMSG_ALIGN (sizeof (struct cmsghdr)))\n#define CMSG_LEN(len)   (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len))\n#endif\n\nstatic_assert(sizeof(uint8_t) == sizeof(char), \"size mismatch!\");\n\nnamespace posix\n{\n  inline bool getpeercred(fd_t sockfd, proccred_t& cred)\n    { return ::getpeercred(sockfd, cred) == posix::success; }\n}\n\nAsyncSocket::AsyncSocket(void)\n{\n  const int enable = 1;\n  m_socket = posix::socket(EDomain::unix, EType::stream, EProtocol::unspec, 0);\n  assert(setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) == posix::success);\n}\n\nAsyncSocket::AsyncSocket(posix::fd_t socket)\n  : m_socket(socket)\n{\n}\n\nAsyncSocket::~AsyncSocket(void)\n{\n  if(m_read.is_connected())\n    m_read.disconnect();\n  if(m_write.is_connected())\n    m_write.disconnect();\n  if(m_socket != posix::invalid_descriptor)\n    posix::close(m_socket);\n  m_socket = posix::invalid_descriptor;\n  if(m_selfaddr != EDomain::unspec)\n    ::unlink(m_selfaddr.sun_path);\n  m_accept.detach();\n\n}\n\nbool AsyncSocket::bind(const char *socket_path, int socket_backlog)\n{\n  if(m_read.is_connected())\n    return false;\n\n  assert(std::strlen(socket_path) < sizeof(sockaddr_un::sun_path));\n  m_selfaddr = socket_path;\n  m_selfaddr = EDomain::unix;\n  bool ok = posix::bind(m_socket, m_selfaddr, m_selfaddr.size());\n  ok = ok && posix::listen(m_socket, socket_backlog);\n  if(ok)\n    m_accept = std::thread(&AsyncSocket::async_accept, this);\n  return ok;\n}\n\nvoid AsyncSocket::async_accept(void)\n{\n  posix::sockaddr_t m_peeraddr;\n  proccred_t m_peercred;\n\n  socklen_t addrlen;\n  m_read.connection = posix::accept(m_socket, m_peeraddr, &addrlen);\n  m_write.connection = ::dup(m_read.connection);\n  if(m_read.is_connected() &&\n     posix::getpeercred(m_read.connection, m_peercred))\n  {\n    enqueue(connectedToPeer, m_peeraddr, m_peercred);\n    m_read .thread = std::thread(&AsyncSocket::async_read , this);\n    m_write.thread = std::thread(&AsyncSocket::async_write, this);\n  }\n}\n\nbool AsyncSocket::connect(const char *socket_path)\n{\n  if(m_read.is_connected())\n    return false;\n\n  assert(std::strlen(socket_path) < sizeof(sockaddr_un::sun_path));\n  proccred_t m_peercred;\n  posix::sockaddr_t m_peeraddr;\n  m_peeraddr = socket_path;\n  m_peeraddr = EDomain::unix;\n  m_selfaddr = EDomain::unspec;\n\n  m_read.connection = m_socket;\n  bool ok = m_read.connect(m_peeraddr);\n  ok = ok && posix::getpeercred(m_read.connection, m_peercred);\n  if(ok)\n  {\n    m_write.connection = ::dup(m_read.connection);\n    enqueue(connectedToPeer, m_peeraddr, m_peercred);\n    m_read .thread = std::thread(&AsyncSocket::async_read , this);\n    m_write.thread = std::thread(&AsyncSocket::async_write, this);\n  }\n  else\n    m_read.connection = posix::invalid_descriptor;\n  return ok;\n}\n\nvoid AsyncSocket::async_read(void)\n{\n  std::mutex m;\n  msghdr msg = {};\n  iovec iov = {};\n\n  msg.msg_iov = &iov;\n  msg.msg_iovlen = 1;\n\n  for(;;)\n  {\n    m_read.buffer.allocate(); \/\/ allocate 64KB buffer\n    std::unique_lock lk(m);\n    m_read.condition.wait(lk, [this] { return m_read.is_connected(); } );\n\n    iov.iov_base = m_read.buffer.data();\n    iov.iov_len = m_read.buffer.capacity();\n    if(m_read.buffer.expand(posix::recvmsg(m_read.connection, &msg, 0)))\n    {\n      if(msg.msg_controllen == CMSG_SPACE(sizeof(int)))\n      {\n        cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);\n        if(cmsg->cmsg_level == SOL_SOCKET &&\n           cmsg->cmsg_type == SCM_RIGHTS &&\n           cmsg->cmsg_len == CMSG_LEN(sizeof(int)))\n         m_read.fd = *reinterpret_cast(CMSG_DATA(cmsg));\n      }\n      else\n        m_read.fd = posix::invalid_descriptor;\n      enqueue(readFinished, m_read.buffer, m_read.fd);\n    }\n    else \/\/ error\n      std::cout << std::flush << std::endl << std::red << \"error: \" << ::strerror(errno) << std::none << std::endl << std::flush;\n  }\n}\n\nvoid AsyncSocket::async_write(void)\n{\n  std::mutex m;\n  msghdr msg = {};\n  iovec iov = {};\n  char aux_buffer[CMSG_SPACE(sizeof(int)) + CMSG_SPACE(sizeof(ucred))] = { 0 };\n\n  msg.msg_iov = &iov;\n  msg.msg_iovlen = 1;\n  msg.msg_control = aux_buffer;\n\n  for(;;)\n  {\n    std::unique_lock lk(m);\n    m_write.condition.wait(lk, [this] { return m_write.is_connected() && !m_write.buffer.empty(); } );\n\n    iov.iov_base = m_write.buffer.begin();\n    iov.iov_len = m_write.buffer.size();\n\n    msg.msg_controllen = 0;\n\n    if(m_write.fd != posix::invalid_descriptor)\n    {\n      msg.msg_controllen = CMSG_SPACE(sizeof(int));\n      cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);\n      cmsg->cmsg_level = SOL_SOCKET;\n      cmsg->cmsg_type = SCM_RIGHTS;\n      cmsg->cmsg_len = CMSG_LEN(sizeof(int));\n      *reinterpret_cast(CMSG_DATA(cmsg)) = m_write.fd;\n    }\n\n    int count = posix::sendmsg(m_write.connection, &msg, 0);\n    if(count == posix::error_response) \/\/ error\n      std::cout << std::flush << std::endl << std::red << \"error: \" << ::strerror(errno) << std::none << std::endl << std::flush;\n    else\n      enqueue(writeFinished, count);\n    m_write.buffer.resize(0);\n  }\n}\n\nbool AsyncSocket::read(void)\n{\n  if(!m_read.is_connected())\n    return false;\n  m_read.condition.notify_one();\n  return true;\n}\n\nbool AsyncSocket::write(vqueue& buffer, posix::fd_t fd)\n{\n  if(!m_read.is_connected())\n    return false;\n\n  m_write.fd = fd;\n  m_write.buffer = buffer; \/\/ share buffer memory\n  m_write.condition.notify_one();\n  return true;\n}\n<|endoftext|>"}
{"text":"\/*************************************************************************\n *\n *  $RCSfile: tbxctl.cxx,v $\n *\n *  $Revision: 1.11 $\n *\n *  last change: $Author: kz $ $Date: 2005-03-01 19:18:59 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#include \n\n#pragma hdrstop\n\n#define _BASIDE_POPUPWINDOWTBX\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace ::com::sun::star::uno;\n\n\nstatic ::rtl::OUString aSubToolBarResName( RTL_CONSTASCII_USTRINGPARAM( \"private:resource\/toolbar\/insertcontrolsbar\" ) );\n\nSFX_IMPL_TOOLBOX_CONTROL( TbxControls, SfxAllEnumItem )\n\n\/*************************************************************************\n|*\n|* WorkWindow Alignment\n|*\n\\************************************************************************\/\n\/*\nIMPL_LINK( PopupWindowTbx, SelectHdl, void*, EMPTYARG )\n{\n    if ( IsInPopupMode() )\n        EndPopupMode();\n\n    aSelectLink.Call( &aTbx.GetToolBox() );\n\n    return 0;\n}\n\nPopupWindowTbx::PopupWindowTbx( USHORT nId, WindowAlign eAlign,\n                                ResId aRIdWin, ResId aRIdTbx,\n                                SfxBindings& rBind ) :\n                SfxPopupWindow  ( nId, aRIdWin, rBind ),\n                aTbx            ( this, GetBindings(), aRIdTbx )\n{\n    FreeResource();\n    aTbx.Initialize();\n\n    ToolBox& rBox = aTbx.GetToolBox();\n    rBox.SetAlign( eAlign );\n    if( eAlign == WINDOWALIGN_LEFT )\n        SetText( String() );\n\n    Size aSize = aTbx.CalcWindowSizePixel();\n    rBox.SetSizePixel( aSize );\n    SetOutputSizePixel( aSize );\n    aSelectLink = rBox.GetSelectHdl();\n    rBox.SetSelectHdl( LINK( this, PopupWindowTbx, SelectHdl ) );\n}\n\nSfxPopupWindow* PopupWindowTbx::Clone() const\n{\n    return new PopupWindowTbx( GetId(), aTbx.GetAlign(),\n                        IDEResId( RID_TBXCONTROLS ),\n                        IDEResId( RID_TOOLBOX ),\n                        (SfxBindings&) GetBindings() );\n}\n\nvoid PopupWindowTbx::PopupModeEnd()\n{\n    aTbx.GetToolBox().EndSelection();\n    SfxPopupWindow::PopupModeEnd();\n}\n\nvoid PopupWindowTbx::Update()\n{\n    ToolBox *pBox = &aTbx.GetToolBox();\n    aTbx.Activate( pBox );\n    aTbx.Deactivate( pBox );\n}\n\nPopupWindowTbx::~PopupWindowTbx()\n{\n}\n*\/\n\/*************************************************************************\n|*\n|* Klasse fuer Toolbox\n|*\n\\************************************************************************\/\n\nTbxControls::TbxControls( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) :\n        SfxToolBoxControl( nSlotId, nId, rTbx )\n{\n    nLastSlot = USHRT_MAX;\n\n    rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );\n    rTbx.Invalidate();\n}\n\n\/*************************************************************************\n|*\n|* Wenn man ein PopupWindow erzeugen will\n|*\n\\************************************************************************\/\nSfxPopupWindowType TbxControls::GetPopupWindowType() const\n{\n    if( nLastSlot == USHRT_MAX )\n        return(SFX_POPUPWINDOW_ONCLICK);\n    return(SFX_POPUPWINDOW_ONTIMEOUT);\n}\n\nIMPL_STATIC_LINK( TbxControls, StateChangedHdl_Impl, StateChangedInfo*, pStateChangedInfo )\n{\n    try\n    {\n        if ( pStateChangedInfo )\n        {\n            Reference< ::com::sun::star::frame::XLayoutManager > xLayoutManager( pStateChangedInfo->xLayoutManager );\n            if ( xLayoutManager.is() )\n            {\n                if ( pStateChangedInfo->bDisabled )\n                {\n                    xLayoutManager->destroyElement( aSubToolBarResName );\n                }\n                else\n                {\n                    xLayoutManager->createElement( aSubToolBarResName );\n                    xLayoutManager->requestElement( aSubToolBarResName );\n                }\n            }\n        }\n    }\n    catch ( Exception& )\n    {\n        \/\/ no update\n    }\n\n    delete pStateChangedInfo;\n\n    return 0;\n}\n\nvoid TbxControls::StateChanged( USHORT nSID, SfxItemState eState,\n  const SfxPoolItem* pState )\n{\n    if ( nSID == SID_CHOOSE_CONTROLS )\n    {\n        StateChangedInfo* pStateChangedInfo = new StateChangedInfo;\n        pStateChangedInfo->xLayoutManager = getLayoutManager();\n        pStateChangedInfo->bDisabled = eState & SFX_ITEM_DISABLED;\n        Application::PostUserEvent( STATIC_LINK( 0, TbxControls, StateChangedHdl_Impl ), pStateChangedInfo );\n    }\n\n    if( pState )\n    {\n        SfxAllEnumItem* pItem = PTR_CAST(SfxAllEnumItem, pState);\n        if( pItem )\n        {\n            USHORT nLastEnum = pItem->GetValue();\n            USHORT nTemp = 0;\n            switch( nLastEnum )\n            {\n                case SVX_SNAP_PUSHBUTTON:       nTemp = SID_INSERT_PUSHBUTTON; break;\n                case SVX_SNAP_CHECKBOX:         nTemp = SID_INSERT_CHECKBOX; break;\n                case SVX_SNAP_RADIOBUTTON:      nTemp = SID_INSERT_RADIOBUTTON; break;\n                case SVX_SNAP_SPINBUTTON:       nTemp = SID_INSERT_SPINBUTTON; break;\n                case SVX_SNAP_FIXEDTEXT:        nTemp = SID_INSERT_FIXEDTEXT; break;\n                case SVX_SNAP_GROUPBOX:         nTemp = SID_INSERT_GROUPBOX; break;\n                case SVX_SNAP_LISTBOX:          nTemp = SID_INSERT_LISTBOX; break;\n                case SVX_SNAP_COMBOBOX:         nTemp = SID_INSERT_COMBOBOX; break;\n                case SVX_SNAP_EDIT:             nTemp = SID_INSERT_EDIT; break;\n                case SVX_SNAP_HSCROLLBAR:       nTemp = SID_INSERT_HSCROLLBAR; break;\n                case SVX_SNAP_VSCROLLBAR:       nTemp = SID_INSERT_VSCROLLBAR; break;\n                case SVX_SNAP_PREVIEW:          nTemp = SID_INSERT_PREVIEW; break;\n                case SVX_SNAP_URLBUTTON:        nTemp = SID_INSERT_URLBUTTON; break;\n                case SVX_SNAP_IMAGECONTROL:     nTemp = SID_INSERT_IMAGECONTROL; break;\n                case SVX_SNAP_PROGRESSBAR:      nTemp = SID_INSERT_PROGRESSBAR; break;\n                case SVX_SNAP_HFIXEDLINE:       nTemp = SID_INSERT_HFIXEDLINE; break;\n                case SVX_SNAP_VFIXEDLINE:       nTemp = SID_INSERT_VFIXEDLINE; break;\n                case SVX_SNAP_DATEFIELD:        nTemp = SID_INSERT_DATEFIELD; break;\n                case SVX_SNAP_TIMEFIELD:        nTemp = SID_INSERT_TIMEFIELD; break;\n                case SVX_SNAP_NUMERICFIELD:     nTemp = SID_INSERT_NUMERICFIELD; break;\n                case SVX_SNAP_CURRENCYFIELD:    nTemp = SID_INSERT_CURRENCYFIELD; break;\n                case SVX_SNAP_FORMATTEDFIELD:   nTemp = SID_INSERT_FORMATTEDFIELD; break;\n                case SVX_SNAP_PATTERNFIELD:     nTemp = SID_INSERT_PATTERNFIELD; break;\n                case SVX_SNAP_FILECONTROL:      nTemp = SID_INSERT_FILECONTROL; break;\n            }\n            if( nTemp )\n            {\n                rtl::OUString aSlotURL( RTL_CONSTASCII_USTRINGPARAM( \"slot:\" ));\n                aSlotURL += rtl::OUString::valueOf( sal_Int32( nTemp ));\n                Image aImage = GetImage( m_xFrame,\n                                         aSlotURL,\n                                         hasBigImages(),\n                                         GetToolBox().GetDisplayBackground().GetColor().IsDark() );\n                ToolBox& rBox = GetToolBox();\n                rBox.SetItemImage(GetId(), aImage);\n                nLastSlot = nLastEnum;\n            }\n        }\n    }\n    SfxToolBoxControl::StateChanged( nSID, eState,pState );\n}\n\nvoid TbxControls::Select( USHORT nModifier )\n{\n    SfxAllEnumItem aItem( SID_CHOOSE_CONTROLS, nLastSlot );\n    SfxViewFrame* pCurFrame = SfxViewFrame::Current();\n    DBG_ASSERT( pCurFrame != NULL, \"No current view frame!\" );\n    SfxDispatcher* pDispatcher = pCurFrame ? pCurFrame->GetDispatcher() : NULL;\n    if( pDispatcher )\n    {\n        pDispatcher->Execute( SID_CHOOSE_CONTROLS, SFX_CALLMODE_SYNCHRON, &aItem, 0L );\n    }\n}\n\n\/*************************************************************************\n|*\n|* Hier wird das Fenster erzeugt\n|* Lage der Toolbox mit GetToolBox() abfragbar\n|* rItemRect sind die Screen-Koordinaten\n|*\n\\************************************************************************\/\nSfxPopupWindow* TbxControls::CreatePopupWindow()\n{\n    if ( GetSlotId() == SID_CHOOSE_CONTROLS )\n        createAndPositionSubToolBar( aSubToolBarResName );\n\n\/*\n    if (GetId() == SID_CHOOSE_CONTROLS)\n    {\n        PopupWindowTbx *pWin =\n            new PopupWindowTbx( GetId(),\n                                GetToolBox().IsHorizontal() ?\n                                    WINDOWALIGN_LEFT : WINDOWALIGN_TOP,\n                                IDEResId( RID_TBXCONTROLS ),\n                                IDEResId( RID_TOOLBOX ),\n                                GetBindings() );\n        pWin->StartPopupMode(&GetToolBox(), TRUE);\n        pWin->Update();\n        pWin->StartSelection();\n        pWin->Show();\n        return(pWin);\n    }\n*\/\n    return(0);\n}\n\n\nINTEGRATION: CWS ooo19126 (1.11.60); FILE MERGED 2005\/09\/05 13:55:49 rt 1.11.60.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: tbxctl.cxx,v $\n *\n *  $Revision: 1.12 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-07 20:11:16 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\n#include \n\n#pragma hdrstop\n\n#define _BASIDE_POPUPWINDOWTBX\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace ::com::sun::star::uno;\n\n\nstatic ::rtl::OUString aSubToolBarResName( RTL_CONSTASCII_USTRINGPARAM( \"private:resource\/toolbar\/insertcontrolsbar\" ) );\n\nSFX_IMPL_TOOLBOX_CONTROL( TbxControls, SfxAllEnumItem )\n\n\/*************************************************************************\n|*\n|* WorkWindow Alignment\n|*\n\\************************************************************************\/\n\/*\nIMPL_LINK( PopupWindowTbx, SelectHdl, void*, EMPTYARG )\n{\n    if ( IsInPopupMode() )\n        EndPopupMode();\n\n    aSelectLink.Call( &aTbx.GetToolBox() );\n\n    return 0;\n}\n\nPopupWindowTbx::PopupWindowTbx( USHORT nId, WindowAlign eAlign,\n                                ResId aRIdWin, ResId aRIdTbx,\n                                SfxBindings& rBind ) :\n                SfxPopupWindow  ( nId, aRIdWin, rBind ),\n                aTbx            ( this, GetBindings(), aRIdTbx )\n{\n    FreeResource();\n    aTbx.Initialize();\n\n    ToolBox& rBox = aTbx.GetToolBox();\n    rBox.SetAlign( eAlign );\n    if( eAlign == WINDOWALIGN_LEFT )\n        SetText( String() );\n\n    Size aSize = aTbx.CalcWindowSizePixel();\n    rBox.SetSizePixel( aSize );\n    SetOutputSizePixel( aSize );\n    aSelectLink = rBox.GetSelectHdl();\n    rBox.SetSelectHdl( LINK( this, PopupWindowTbx, SelectHdl ) );\n}\n\nSfxPopupWindow* PopupWindowTbx::Clone() const\n{\n    return new PopupWindowTbx( GetId(), aTbx.GetAlign(),\n                        IDEResId( RID_TBXCONTROLS ),\n                        IDEResId( RID_TOOLBOX ),\n                        (SfxBindings&) GetBindings() );\n}\n\nvoid PopupWindowTbx::PopupModeEnd()\n{\n    aTbx.GetToolBox().EndSelection();\n    SfxPopupWindow::PopupModeEnd();\n}\n\nvoid PopupWindowTbx::Update()\n{\n    ToolBox *pBox = &aTbx.GetToolBox();\n    aTbx.Activate( pBox );\n    aTbx.Deactivate( pBox );\n}\n\nPopupWindowTbx::~PopupWindowTbx()\n{\n}\n*\/\n\/*************************************************************************\n|*\n|* Klasse fuer Toolbox\n|*\n\\************************************************************************\/\n\nTbxControls::TbxControls( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) :\n        SfxToolBoxControl( nSlotId, nId, rTbx )\n{\n    nLastSlot = USHRT_MAX;\n\n    rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );\n    rTbx.Invalidate();\n}\n\n\/*************************************************************************\n|*\n|* Wenn man ein PopupWindow erzeugen will\n|*\n\\************************************************************************\/\nSfxPopupWindowType TbxControls::GetPopupWindowType() const\n{\n    if( nLastSlot == USHRT_MAX )\n        return(SFX_POPUPWINDOW_ONCLICK);\n    return(SFX_POPUPWINDOW_ONTIMEOUT);\n}\n\nIMPL_STATIC_LINK( TbxControls, StateChangedHdl_Impl, StateChangedInfo*, pStateChangedInfo )\n{\n    try\n    {\n        if ( pStateChangedInfo )\n        {\n            Reference< ::com::sun::star::frame::XLayoutManager > xLayoutManager( pStateChangedInfo->xLayoutManager );\n            if ( xLayoutManager.is() )\n            {\n                if ( pStateChangedInfo->bDisabled )\n                {\n                    xLayoutManager->destroyElement( aSubToolBarResName );\n                }\n                else\n                {\n                    xLayoutManager->createElement( aSubToolBarResName );\n                    xLayoutManager->requestElement( aSubToolBarResName );\n                }\n            }\n        }\n    }\n    catch ( Exception& )\n    {\n        \/\/ no update\n    }\n\n    delete pStateChangedInfo;\n\n    return 0;\n}\n\nvoid TbxControls::StateChanged( USHORT nSID, SfxItemState eState,\n  const SfxPoolItem* pState )\n{\n    if ( nSID == SID_CHOOSE_CONTROLS )\n    {\n        StateChangedInfo* pStateChangedInfo = new StateChangedInfo;\n        pStateChangedInfo->xLayoutManager = getLayoutManager();\n        pStateChangedInfo->bDisabled = eState & SFX_ITEM_DISABLED;\n        Application::PostUserEvent( STATIC_LINK( 0, TbxControls, StateChangedHdl_Impl ), pStateChangedInfo );\n    }\n\n    if( pState )\n    {\n        SfxAllEnumItem* pItem = PTR_CAST(SfxAllEnumItem, pState);\n        if( pItem )\n        {\n            USHORT nLastEnum = pItem->GetValue();\n            USHORT nTemp = 0;\n            switch( nLastEnum )\n            {\n                case SVX_SNAP_PUSHBUTTON:       nTemp = SID_INSERT_PUSHBUTTON; break;\n                case SVX_SNAP_CHECKBOX:         nTemp = SID_INSERT_CHECKBOX; break;\n                case SVX_SNAP_RADIOBUTTON:      nTemp = SID_INSERT_RADIOBUTTON; break;\n                case SVX_SNAP_SPINBUTTON:       nTemp = SID_INSERT_SPINBUTTON; break;\n                case SVX_SNAP_FIXEDTEXT:        nTemp = SID_INSERT_FIXEDTEXT; break;\n                case SVX_SNAP_GROUPBOX:         nTemp = SID_INSERT_GROUPBOX; break;\n                case SVX_SNAP_LISTBOX:          nTemp = SID_INSERT_LISTBOX; break;\n                case SVX_SNAP_COMBOBOX:         nTemp = SID_INSERT_COMBOBOX; break;\n                case SVX_SNAP_EDIT:             nTemp = SID_INSERT_EDIT; break;\n                case SVX_SNAP_HSCROLLBAR:       nTemp = SID_INSERT_HSCROLLBAR; break;\n                case SVX_SNAP_VSCROLLBAR:       nTemp = SID_INSERT_VSCROLLBAR; break;\n                case SVX_SNAP_PREVIEW:          nTemp = SID_INSERT_PREVIEW; break;\n                case SVX_SNAP_URLBUTTON:        nTemp = SID_INSERT_URLBUTTON; break;\n                case SVX_SNAP_IMAGECONTROL:     nTemp = SID_INSERT_IMAGECONTROL; break;\n                case SVX_SNAP_PROGRESSBAR:      nTemp = SID_INSERT_PROGRESSBAR; break;\n                case SVX_SNAP_HFIXEDLINE:       nTemp = SID_INSERT_HFIXEDLINE; break;\n                case SVX_SNAP_VFIXEDLINE:       nTemp = SID_INSERT_VFIXEDLINE; break;\n                case SVX_SNAP_DATEFIELD:        nTemp = SID_INSERT_DATEFIELD; break;\n                case SVX_SNAP_TIMEFIELD:        nTemp = SID_INSERT_TIMEFIELD; break;\n                case SVX_SNAP_NUMERICFIELD:     nTemp = SID_INSERT_NUMERICFIELD; break;\n                case SVX_SNAP_CURRENCYFIELD:    nTemp = SID_INSERT_CURRENCYFIELD; break;\n                case SVX_SNAP_FORMATTEDFIELD:   nTemp = SID_INSERT_FORMATTEDFIELD; break;\n                case SVX_SNAP_PATTERNFIELD:     nTemp = SID_INSERT_PATTERNFIELD; break;\n                case SVX_SNAP_FILECONTROL:      nTemp = SID_INSERT_FILECONTROL; break;\n            }\n            if( nTemp )\n            {\n                rtl::OUString aSlotURL( RTL_CONSTASCII_USTRINGPARAM( \"slot:\" ));\n                aSlotURL += rtl::OUString::valueOf( sal_Int32( nTemp ));\n                Image aImage = GetImage( m_xFrame,\n                                         aSlotURL,\n                                         hasBigImages(),\n                                         GetToolBox().GetDisplayBackground().GetColor().IsDark() );\n                ToolBox& rBox = GetToolBox();\n                rBox.SetItemImage(GetId(), aImage);\n                nLastSlot = nLastEnum;\n            }\n        }\n    }\n    SfxToolBoxControl::StateChanged( nSID, eState,pState );\n}\n\nvoid TbxControls::Select( USHORT nModifier )\n{\n    SfxAllEnumItem aItem( SID_CHOOSE_CONTROLS, nLastSlot );\n    SfxViewFrame* pCurFrame = SfxViewFrame::Current();\n    DBG_ASSERT( pCurFrame != NULL, \"No current view frame!\" );\n    SfxDispatcher* pDispatcher = pCurFrame ? pCurFrame->GetDispatcher() : NULL;\n    if( pDispatcher )\n    {\n        pDispatcher->Execute( SID_CHOOSE_CONTROLS, SFX_CALLMODE_SYNCHRON, &aItem, 0L );\n    }\n}\n\n\/*************************************************************************\n|*\n|* Hier wird das Fenster erzeugt\n|* Lage der Toolbox mit GetToolBox() abfragbar\n|* rItemRect sind die Screen-Koordinaten\n|*\n\\************************************************************************\/\nSfxPopupWindow* TbxControls::CreatePopupWindow()\n{\n    if ( GetSlotId() == SID_CHOOSE_CONTROLS )\n        createAndPositionSubToolBar( aSubToolBarResName );\n\n\/*\n    if (GetId() == SID_CHOOSE_CONTROLS)\n    {\n        PopupWindowTbx *pWin =\n            new PopupWindowTbx( GetId(),\n                                GetToolBox().IsHorizontal() ?\n                                    WINDOWALIGN_LEFT : WINDOWALIGN_TOP,\n                                IDEResId( RID_TBXCONTROLS ),\n                                IDEResId( RID_TOOLBOX ),\n                                GetBindings() );\n        pWin->StartPopupMode(&GetToolBox(), TRUE);\n        pWin->Update();\n        pWin->StartSelection();\n        pWin->Show();\n        return(pWin);\n    }\n*\/\n    return(0);\n}\n\n\n<|endoftext|>"}
{"text":"\/\/=======================================================================\n\/\/ Copyright (c) 2014 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n\n#define DLL_PARALLEL\n#define DLL_SVM_SUPPORT\n\n#include \"dll\/conv_rbm.hpp\"\n#include \"dll\/conv_dbn.hpp\"\n#include \"dll\/test.hpp\"\n#include \"dll\/cpp_utils\/algorithm.hpp\"\n#include \"dll\/cpp_utils\/data.hpp\"\n\n#include \"icdar\/icdar_reader.hpp\"\n\nconstexpr const std::size_t context = 5;\nconstexpr const std::size_t window = context * 2 + 1;\n\ntemplate\nbool is_text(const Label& label, std::size_t x, std::size_t y){\n    for(auto& rectangle : label.rectangles){\n        if(x >= rectangle.left && x <= rectangle.right && y >= rectangle.top && y <= rectangle.bottom){\n            return true;\n        }\n    }\n\n    return false;\n}\n\nint main(){\n    auto dataset = icdar::read_2013_dataset(\n        \"\/home\/wichtounet\/datasets\/icdar_2013_natural\/train\",\n        \"\/home\/wichtounet\/datasets\/icdar_2013_natural\/test\", 5, 1);\n\n    if(dataset.training_labels.empty() || dataset.training_images.empty()){\n        std::cout << \"Problem while reading the dataset\" << std::endl;\n\n        return -1;\n    }\n\n    std::cout << \"Dataset\" << std::endl;\n    std::cout << dataset.training_images.size() << \" training images\" << std::endl;\n    std::cout << dataset.test_images.size() << \" test images\" << std::endl;\n\n    std::vector> windows;\n    std::vector labels;\n\n    for(std::size_t image_id = 0; image_id < dataset.training_images.size(); ++image_id){\n        auto& image = dataset.training_images[image_id];\n\n        windows.reserve(windows.size() + image.width * image.height);\n\n        for(std::size_t i = context; i < image.width - context; ++i){\n            for(std::size_t j = context; j < image.height - context; ++j){\n\n                windows.emplace_back(window * window);\n\n                labels.push_back(is_text(dataset.training_labels[image_id], i, j) ? 1 : 0);\n\n                for(std::size_t a = i - context; a < i - context + window; ++a){\n                    for(std::size_t b = j - context; b < j - context + window; ++b){\n                        auto w_i = (a - (i - context));\n                        auto w_j = (b - (j - context));\n                        windows.back().at(w_i * window + w_j) = image.pixels.at(a * image.height + b).r;\n                    }\n                }\n            }\n        }\n    }\n\n    std::cout << window << std::endl;\n\n    windows.resize(1000);\n    labels.resize(1000);\n\n    cpp::normalize_each(windows);\n\n    std::cout << \"Extraction\" << std::endl;\n    std::cout << dataset.training_images.size() << \" images\" << std::endl;\n    std::cout << window << \"x\" << window << \" windows\" << std::endl;\n    std::cout << windows.size() << \" windows and labels extracted\" << std::endl;\n\n    typedef dll::conv_dbn_desc<\n        dll::dbn_layers<\n            dll::conv_rbm_desc\n                , dll::weight_decay\n                , dll::visible\n                , dll::sparsity\n            >::rbm_t\n            >>::dbn_t dbn_t;\n\n    auto dbn = std::make_unique();\n\n    std::cout << \"DBN is \" << sizeof(dbn_t) << \" bytes long\" << std::endl;\n    std::cout << \"DBN input is \" << dbn->input_size() << std::endl;\n    std::cout << \"DBN output is \" << dbn->output_size() << std::endl;\n\n    dbn->layer<0>().pbias = 0.05;\n    dbn->layer<0>().pbias_lambda = 100;\n\n    \/\/TODO What about randomization ?\n\n    dbn->pretrain(windows, 50);\n    dbn->svm_train(windows, labels);\n\n    double error = dll::test_set(dbn, windows, labels, dll::svm_predictor());\n    std::cout << \"Pixel error:\" << error << std::endl;\n\n    return 0;\n}\nUpdates\/\/=======================================================================\n\/\/ Copyright (c) 2014 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n\n#define DLL_PARALLEL\n#define DLL_SVM_SUPPORT\n\n#include \"dll\/conv_rbm.hpp\"\n#include \"dll\/conv_dbn.hpp\"\n#include \"dll\/test.hpp\"\n#include \"dll\/cpp_utils\/algorithm.hpp\"\n#include \"dll\/cpp_utils\/data.hpp\"\n\n#include \"icdar\/icdar_reader.hpp\"\n\nconstexpr const std::size_t context = 5;\nconstexpr const std::size_t window = context * 2 + 1;\n\ntemplate\nbool is_text(const Label& label, std::size_t x, std::size_t y){\n    for(auto& rectangle : label.rectangles){\n        if(x >= rectangle.left && x <= rectangle.right && y >= rectangle.top && y <= rectangle.bottom){\n            return true;\n        }\n    }\n\n    return false;\n}\n\ntemplate\nvoid extract(std::vector>& windows, std::vector& labels, Images& d_images, Labels& d_labels){\n    for(std::size_t image_id = 0; image_id < d_images.size(); ++image_id){\n        auto& image = d_images[image_id];\n\n        windows.reserve(windows.size() + image.width * image.height);\n\n        for(std::size_t i = context; i < image.width - context; ++i){\n            for(std::size_t j = context; j < image.height - context; ++j){\n\n                windows.emplace_back(window * window);\n\n                labels.push_back(is_text(d_labels[image_id], i, j) ? 1 : 0);\n\n                for(std::size_t a = i - context; a < i - context + window; ++a){\n                    for(std::size_t b = j - context; b < j - context + window; ++b){\n                        auto w_i = (a - (i - context));\n                        auto w_j = (b - (j - context));\n                        windows.back().at(w_i * window + w_j) = image.pixels.at(a * image.height + b).r;\n                    }\n                }\n            }\n        }\n    }\n}\n\nint main(){\n    auto dataset = icdar::read_2013_dataset(\n        \"\/home\/wichtounet\/datasets\/icdar_2013_natural\/train\",\n        \"\/home\/wichtounet\/datasets\/icdar_2013_natural\/test\", 5, 1);\n\n    if(dataset.training_labels.empty() || dataset.training_images.empty()){\n        std::cout << \"Problem while reading the dataset\" << std::endl;\n\n        return -1;\n    }\n\n    std::cout << window << \"x\" << window << \" window dimension\" << std::endl;\n\n    std::cout << \"Dataset\" << std::endl;\n    std::cout << dataset.training_images.size() << \" training images\" << std::endl;\n    std::cout << dataset.test_images.size() << \" test images\" << std::endl;\n\n    std::vector> training_windows;\n    std::vector training_labels;\n\n    std::vector> test_windows;\n    std::vector test_labels;\n\n    extract(training_windows, training_labels, dataset.training_images, dataset.training_labels);\n\n    training_windows.resize(5000);\n    training_labels.resize(5000);\n\n    extract(test_windows, test_labels, dataset.test_images, dataset.test_labels);\n\n    test_windows.resize(5000);\n    test_labels.resize(5000);\n\n    cpp::normalize_each(training_windows);\n    cpp::normalize_each(test_windows);\n\n    std::cout << \"Extraction\" << std::endl;\n    std::cout << dataset.training_images.size() << \" training images\" << std::endl;\n    std::cout << training_windows.size() << \" training windows and labels extracted\" << std::endl;\n\n    std::cout << dataset.test_images.size() << \" test images\" << std::endl;\n    std::cout << test_windows.size() << \" test windows and labels extracted\" << std::endl;\n\n    typedef dll::conv_dbn_desc<\n        dll::dbn_layers<\n            dll::conv_rbm_desc\n                , dll::weight_decay\n                , dll::visible\n                , dll::sparsity\n            >::rbm_t\n            >>::dbn_t dbn_t;\n\n    auto dbn = std::make_unique();\n\n    std::cout << \"DBN is \" << sizeof(dbn_t) << \" bytes long\" << std::endl;\n    std::cout << \"DBN input is \" << dbn->input_size() << std::endl;\n    std::cout << \"DBN output is \" << dbn->output_size() << std::endl;\n\n    dbn->layer<0>().pbias = 0.05;\n    dbn->layer<0>().pbias_lambda = 100;\n\n    \/\/TODO What about randomization ?\n\n    dbn->pretrain(training_windows, 50);\n    dbn->svm_train(training_windows, training_labels);\n\n    double training_error = dll::test_set(dbn, training_windows, training_labels, dll::svm_predictor());\n    std::cout << \"Pixel error (training):\" << training_error << std::endl;\n\n    double test_error = dll::test_set(dbn, test_windows, test_labels, dll::svm_predictor());\n    std::cout << \"Pixel error (test):\" << test_error << std::endl;\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"\/*\n    Copyright © 2010, 2011, 2012 Vladimír Vondruš \n\n    This file is part of Magnum.\n\n    Magnum is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Lesser General Public License version 3\n    only, as published by the Free Software Foundation.\n\n    Magnum is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU Lesser General Public License version 3 for more details.\n*\/\n\n#include \n#include \n#include \n\n#include \"PluginManager\/PluginManager.h\"\n#include \"Scene.h\"\n#include \"Camera.h\"\n#include \"Trade\/AbstractImporter.h\"\n#include \"Trade\/MeshData.h\"\n#include \"MeshTools\/Tipsify.h\"\n#include \"MeshTools\/Interleave.h\"\n#include \"MeshTools\/CompressIndices.h\"\n#include \"Shaders\/PhongShader.h\"\n\n#include \"AbstractExample.h\"\n#include \"ViewedObject.h\"\n#include \"configure.h\"\n\nusing namespace std;\nusing namespace Corrade::PluginManager;\nusing namespace Corrade::Utility;\nusing namespace Magnum;\nusing namespace Magnum::Shaders;\nusing namespace Magnum::Examples;\n\nnamespace Magnum { namespace Examples {\n\nclass ViewerExample: public AbstractExample {\n    public:\n        ViewerExample(int& argc, char** argv): AbstractExample(argc, argv, \"Magnum Viewer\"), wireframe(false), fps(false) {\n            if(argc != 2) {\n                cout << \"Usage: \" << argv[0] << \" file.dae\" << endl;\n                exit(0);\n            }\n\n            \/* Instance ColladaImporter plugin *\/\n            PluginManager manager(PLUGIN_IMPORTER_DIR);\n            if(manager.load(\"ColladaImporter\") != AbstractPluginManager::LoadOk) {\n                Error() << \"Could not load ColladaImporter plugin\";\n                exit(1);\n            }\n            unique_ptr colladaImporter(manager.instance(\"ColladaImporter\"));\n            if(!colladaImporter) {\n                Error() << \"Could not instance ColladaImporter plugin\";\n                exit(2);\n            }\n            if(!(colladaImporter->features() & Trade::AbstractImporter::OpenFile)) {\n                Error() << \"ColladaImporter cannot open files\";\n                exit(3);\n            }\n\n            scene.setFeature(Scene::DepthTest, true);\n\n            \/* Every scene needs a camera *\/\n            camera = new Camera(&scene);\n            camera->setPerspective(deg(35.0f), 0.001f, 100);\n            camera->translate(Vector3::zAxis(5));\n\n            \/* Load file *\/\n            if(!colladaImporter->open(argv[1]))\n                exit(4);\n\n            if(colladaImporter->meshCount() == 0)\n                exit(5);\n\n            Trade::MeshData* data = colladaImporter->mesh(0);\n            if(!data || !data->indices() || !data->vertexArrayCount() || !data->normalArrayCount())\n                exit(6);\n\n            \/* Optimize vertices *\/\n            Debug() << \"Optimizing mesh vertices using Tipsify algorithm (cache size 24)...\";\n            MeshTools::tipsify(*data->indices(), data->vertices(0)->size(), 24);\n\n            \/* Interleave mesh data *\/\n            Buffer* buffer = mesh.addBuffer(true);\n            mesh.bindAttribute(buffer);\n            mesh.bindAttribute(buffer);\n            MeshTools::interleave(&mesh, buffer, Buffer::Usage::StaticDraw, *data->vertices(0), *data->normals(0));\n\n            \/* Compress indices *\/\n            MeshTools::compressIndices(&mesh, Buffer::Usage::StaticDraw, *data->indices());\n\n            \/* Get material or create default one *\/\n            Trade::PhongMaterialData* material = static_cast(colladaImporter->material(0));\n            if(!material) material = new Trade::PhongMaterialData({0.0f, 0.0f, 0.0f}, {0.9f, 0.9f, 0.9f}, {1.0f, 1.0f, 1.0f}, 50.0f);\n\n            o = new ViewedObject(&mesh, static_cast(material), &shader, &scene);\n\n            colladaImporter->close();\n            delete colladaImporter.release();\n        }\n\n    protected:\n        inline void viewportEvent(const Math::Vector2& size) {\n            camera->setViewport(size);\n        }\n\n        void drawEvent() {\n            if(fps) {\n                chrono::high_resolution_clock::time_point now = chrono::high_resolution_clock::now();\n                double duration = chrono::duration(now-before).count();\n                if(duration > 3.5) {\n                    cout << frames << \" frames in \" << duration << \" sec: \"\n                        << frames\/duration << \" FPS         \\r\";\n                    cout.flush();\n                    totalfps += frames\/duration;\n                    before = now;\n                    frames = 0;\n                    ++totalmeasurecount;\n                }\n            }\n            camera->draw();\n            swapBuffers();\n\n            if(fps) {\n                ++frames;\n                redraw();\n            }\n        }\n\n        void keyEvent(Key key, const Math::Vector2& position) {\n            switch(key) {\n                case Key::Up:\n                    o->rotate(deg(10.0f), Vector3::xAxis(-1));\n                    break;\n                case Key::Down:\n                    o->rotate(deg(10.0f), Vector3::xAxis(1));\n                    break;\n                case Key::Left:\n                    o->rotate(deg(10.0f), Vector3::yAxis(-1), false);\n                    break;\n                case Key::Right:\n                    o->rotate(deg(10.0f), Vector3::yAxis(1), false);\n                    break;\n                case Key::PageUp:\n                    camera->translate(Vector3::zAxis(-0.5));\n                    break;\n                case Key::PageDown:\n                    camera->translate(Vector3::zAxis(0.5));\n                    break;\n                case Key::Home:\n                    glPolygonMode(GL_FRONT_AND_BACK, wireframe ? GL_FILL : GL_LINE);\n                    wireframe = !wireframe;\n                    break;\n                case Key::End:\n                    if(fps) cout << \"Average FPS on \" << camera->viewport().x()\n                        << 'x' << camera->viewport().y() << \" from \"\n                        << totalmeasurecount << \" measures: \"\n                        << totalfps\/totalmeasurecount << \"          \" << endl;\n                    else before = chrono::high_resolution_clock::now();\n\n                    fps = !fps;\n                    frames = totalmeasurecount = 0;\n                    totalfps = 0;\n                    break;\n            }\n\n            redraw();\n        }\n\n        void mouseEvent(MouseButton button, MouseState state, const Math::Vector2& position) {\n            switch(button) {\n                case MouseButton::Left:\n                    if(state == MouseState::Down) previousPosition = positionOnSphere(position);\n                    else previousPosition = Vector3();\n                    break;\n                case MouseButton::WheelUp:\n                case MouseButton::WheelDown: {\n                    if(state == MouseState::Up) return;\n\n                    \/* Distance between origin and near camera clipping plane *\/\n                    GLfloat distance = camera->transformation().at(3).z()-0-camera->near();\n\n                    \/* Move 15% of the distance back or forward *\/\n                    if(button == MouseButton::WheelUp)\n                        distance *= 1 - 1\/0.85f;\n                    else\n                        distance *= 1 - 0.85f;\n                    camera->translate(Vector3::zAxis(distance));\n\n                    redraw();\n                    break;\n                }\n                default: ;\n            }\n        }\n\n        void mouseMoveEvent(const Math::Vector2& position) {\n            Vector3 currentPosition = positionOnSphere(position);\n\n            Vector3 axis = Vector3::cross(previousPosition, currentPosition);\n\n            if(previousPosition.length() < 0.001f || axis.length() < 0.001f) return;\n\n            GLfloat angle = acos(previousPosition*currentPosition);\n            o->rotate(angle, axis);\n\n            previousPosition = currentPosition;\n\n            redraw();\n        }\n\n    private:\n        Vector3 positionOnSphere(const Math::Vector2& _position) const {\n            Math::Vector2 viewport = camera->viewport();\n            Vector2 position(_position.x()*2.0f\/viewport.x() - 1.0f,\n                             _position.y()*2.0f\/viewport.y() - 1.0f);\n\n            GLfloat length = position.length();\n            Vector3 result(length > 1.0f ? position : Vector3(position, 1.0f - length));\n            result.setY(-result.y());\n            return result.normalized();\n        }\n\n        Scene scene;\n        Camera* camera;\n        PhongShader shader;\n        IndexedMesh mesh;\n        Object* o;\n        chrono::high_resolution_clock::time_point before;\n        bool wireframe, fps;\n        size_t frames;\n        double totalfps;\n        size_t totalmeasurecount;\n        Vector3 previousPosition;\n};\n\n}}\n\nMAGNUM_EXAMPLE_MAIN(Magnum::Examples::ViewerExample)\nMoved function definition out of the class body.\/*\n    Copyright © 2010, 2011, 2012 Vladimír Vondruš \n\n    This file is part of Magnum.\n\n    Magnum is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Lesser General Public License version 3\n    only, as published by the Free Software Foundation.\n\n    Magnum is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU Lesser General Public License version 3 for more details.\n*\/\n\n#include \n#include \n#include \n\n#include \"PluginManager\/PluginManager.h\"\n#include \"Scene.h\"\n#include \"Camera.h\"\n#include \"Trade\/AbstractImporter.h\"\n#include \"Trade\/MeshData.h\"\n#include \"MeshTools\/Tipsify.h\"\n#include \"MeshTools\/Interleave.h\"\n#include \"MeshTools\/CompressIndices.h\"\n#include \"Shaders\/PhongShader.h\"\n\n#include \"AbstractExample.h\"\n#include \"ViewedObject.h\"\n#include \"configure.h\"\n\nusing namespace std;\nusing namespace Corrade::PluginManager;\nusing namespace Corrade::Utility;\nusing namespace Magnum;\nusing namespace Magnum::Shaders;\nusing namespace Magnum::Examples;\n\nnamespace Magnum { namespace Examples {\n\nclass ViewerExample: public AbstractExample {\n    public:\n        ViewerExample(int& argc, char** argv);\n\n    protected:\n        inline void viewportEvent(const Math::Vector2& size) {\n            camera->setViewport(size);\n        }\n\n        void drawEvent() {\n            if(fps) {\n                chrono::high_resolution_clock::time_point now = chrono::high_resolution_clock::now();\n                double duration = chrono::duration(now-before).count();\n                if(duration > 3.5) {\n                    cout << frames << \" frames in \" << duration << \" sec: \"\n                        << frames\/duration << \" FPS         \\r\";\n                    cout.flush();\n                    totalfps += frames\/duration;\n                    before = now;\n                    frames = 0;\n                    ++totalmeasurecount;\n                }\n            }\n            camera->draw();\n            swapBuffers();\n\n            if(fps) {\n                ++frames;\n                redraw();\n            }\n        }\n\n        void keyEvent(Key key, const Math::Vector2& position) {\n            switch(key) {\n                case Key::Up:\n                    o->rotate(deg(10.0f), Vector3::xAxis(-1));\n                    break;\n                case Key::Down:\n                    o->rotate(deg(10.0f), Vector3::xAxis(1));\n                    break;\n                case Key::Left:\n                    o->rotate(deg(10.0f), Vector3::yAxis(-1), false);\n                    break;\n                case Key::Right:\n                    o->rotate(deg(10.0f), Vector3::yAxis(1), false);\n                    break;\n                case Key::PageUp:\n                    camera->translate(Vector3::zAxis(-0.5));\n                    break;\n                case Key::PageDown:\n                    camera->translate(Vector3::zAxis(0.5));\n                    break;\n                case Key::Home:\n                    glPolygonMode(GL_FRONT_AND_BACK, wireframe ? GL_FILL : GL_LINE);\n                    wireframe = !wireframe;\n                    break;\n                case Key::End:\n                    if(fps) cout << \"Average FPS on \" << camera->viewport().x()\n                        << 'x' << camera->viewport().y() << \" from \"\n                        << totalmeasurecount << \" measures: \"\n                        << totalfps\/totalmeasurecount << \"          \" << endl;\n                    else before = chrono::high_resolution_clock::now();\n\n                    fps = !fps;\n                    frames = totalmeasurecount = 0;\n                    totalfps = 0;\n                    break;\n            }\n\n            redraw();\n        }\n\n        void mouseEvent(MouseButton button, MouseState state, const Math::Vector2& position) {\n            switch(button) {\n                case MouseButton::Left:\n                    if(state == MouseState::Down) previousPosition = positionOnSphere(position);\n                    else previousPosition = Vector3();\n                    break;\n                case MouseButton::WheelUp:\n                case MouseButton::WheelDown: {\n                    if(state == MouseState::Up) return;\n\n                    \/* Distance between origin and near camera clipping plane *\/\n                    GLfloat distance = camera->transformation().at(3).z()-0-camera->near();\n\n                    \/* Move 15% of the distance back or forward *\/\n                    if(button == MouseButton::WheelUp)\n                        distance *= 1 - 1\/0.85f;\n                    else\n                        distance *= 1 - 0.85f;\n                    camera->translate(Vector3::zAxis(distance));\n\n                    redraw();\n                    break;\n                }\n                default: ;\n            }\n        }\n\n        void mouseMoveEvent(const Math::Vector2& position) {\n            Vector3 currentPosition = positionOnSphere(position);\n\n            Vector3 axis = Vector3::cross(previousPosition, currentPosition);\n\n            if(previousPosition.length() < 0.001f || axis.length() < 0.001f) return;\n\n            GLfloat angle = acos(previousPosition*currentPosition);\n            o->rotate(angle, axis);\n\n            previousPosition = currentPosition;\n\n            redraw();\n        }\n\n    private:\n        Vector3 positionOnSphere(const Math::Vector2& _position) const {\n            Math::Vector2 viewport = camera->viewport();\n            Vector2 position(_position.x()*2.0f\/viewport.x() - 1.0f,\n                             _position.y()*2.0f\/viewport.y() - 1.0f);\n\n            GLfloat length = position.length();\n            Vector3 result(length > 1.0f ? position : Vector3(position, 1.0f - length));\n            result.setY(-result.y());\n            return result.normalized();\n        }\n\n        Scene scene;\n        Camera* camera;\n        PhongShader shader;\n        IndexedMesh mesh;\n        Object* o;\n        chrono::high_resolution_clock::time_point before;\n        bool wireframe, fps;\n        size_t frames;\n        double totalfps;\n        size_t totalmeasurecount;\n        Vector3 previousPosition;\n};\n\nViewerExample::ViewerExample(int& argc, char** argv): AbstractExample(argc, argv, \"Magnum Viewer\"), wireframe(false), fps(false) {\n    if(argc != 2) {\n        cout << \"Usage: \" << argv[0] << \" file.dae\" << endl;\n        exit(0);\n    }\n\n    \/* Instance ColladaImporter plugin *\/\n    PluginManager manager(PLUGIN_IMPORTER_DIR);\n    if(manager.load(\"ColladaImporter\") != AbstractPluginManager::LoadOk) {\n        Error() << \"Could not load ColladaImporter plugin\";\n        exit(1);\n    }\n    unique_ptr colladaImporter(manager.instance(\"ColladaImporter\"));\n    if(!colladaImporter) {\n        Error() << \"Could not instance ColladaImporter plugin\";\n        exit(2);\n    }\n    if(!(colladaImporter->features() & Trade::AbstractImporter::OpenFile)) {\n        Error() << \"ColladaImporter cannot open files\";\n        exit(3);\n    }\n\n    scene.setFeature(Scene::DepthTest, true);\n\n    \/* Every scene needs a camera *\/\n    camera = new Camera(&scene);\n    camera->setPerspective(deg(35.0f), 0.001f, 100);\n    camera->translate(Vector3::zAxis(5));\n\n    \/* Load file *\/\n    if(!colladaImporter->open(argv[1]))\n        exit(4);\n\n    if(colladaImporter->meshCount() == 0)\n        exit(5);\n\n    Trade::MeshData* data = colladaImporter->mesh(0);\n    if(!data || !data->indices() || !data->vertexArrayCount() || !data->normalArrayCount())\n        exit(6);\n\n    \/* Optimize vertices *\/\n    Debug() << \"Optimizing mesh vertices using Tipsify algorithm (cache size 24)...\";\n    MeshTools::tipsify(*data->indices(), data->vertices(0)->size(), 24);\n\n    \/* Interleave mesh data *\/\n    Buffer* buffer = mesh.addBuffer(true);\n    mesh.bindAttribute(buffer);\n    mesh.bindAttribute(buffer);\n    MeshTools::interleave(&mesh, buffer, Buffer::Usage::StaticDraw, *data->vertices(0), *data->normals(0));\n\n    \/* Compress indices *\/\n    MeshTools::compressIndices(&mesh, Buffer::Usage::StaticDraw, *data->indices());\n\n    \/* Get material or create default one *\/\n    Trade::PhongMaterialData* material = static_cast(colladaImporter->material(0));\n    if(!material) material = new Trade::PhongMaterialData({0.0f, 0.0f, 0.0f}, {0.9f, 0.9f, 0.9f}, {1.0f, 1.0f, 1.0f}, 50.0f);\n\n    o = new ViewedObject(&mesh, static_cast(material), &shader, &scene);\n\n    colladaImporter->close();\n    delete colladaImporter.release();\n}\n\n}}\n\nMAGNUM_EXAMPLE_MAIN(Magnum::Examples::ViewerExample)\n<|endoftext|>"}
{"text":"#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tルネサス RX 選択\r\n    @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2016, 2017 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"common\/byte_order.h\"\r\n#include \"common\/vect.h\"\r\n#include \"common\/delay.hpp\"\r\n\r\n#if defined(SIG_RX621)\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX621\/system.hpp\"\r\n#include \"RX621\/sci.hpp\"\r\n#include \"RX621\/icu.hpp\"\r\n\r\n#elif defined(SIG_RX24T)\r\n#include \"RX24T\/peripheral.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX24T\/system.hpp\"\r\n#include \"RX24T\/dtc.hpp\"\r\n#include \"RX24T\/icu.hpp\"\r\n#include \"RX24T\/mtu3.hpp\"\r\n#include \"RX24T\/poe3.hpp\"\r\n#include \"RX24T\/tmr.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX24T\/sci.hpp\"\r\n#include \"RX24T\/riic.hpp\"\r\n#include \"RX24T\/rspi.hpp\"\r\n#include \"RX24T\/crc.hpp\"\r\n#include \"RX24T\/s12ad.hpp\"\r\n#include \"RX24T\/adc_io.hpp\"\r\n#include \"RX24T\/da.hpp\"\r\n#include \"RX24T\/cmpc.hpp\"\r\n#include \"RX24T\/doc.hpp\"\r\n#include \"RX24T\/port_map.hpp\"\r\n#include \"RX24T\/power_cfg.hpp\"\r\n#include \"RX24T\/icu_mgr.hpp\"\r\n#include \"RX24T\/flash.hpp\"\r\n#include \"RX24T\/flash_io.hpp\"\r\n\r\n#elif defined(SIG_RX63T)\r\n#include \"RX63T\/peripheral.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX63T\/system.hpp\"\r\n#include \"RX63T\/sci.hpp\"\r\n#include \"RX63T\/icu.hpp\"\r\n#include \"RX63T\/port_map.hpp\"\r\n#include \"RX63T\/power_cfg.hpp\"\r\n#include \"RX63T\/icu_mgr.hpp\"\r\n\r\n#elif defined(SIG_RX64M)\r\n#include \"RX64M\/peripheral.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX64M\/system.hpp\"\r\n#include \"RX64M\/system_io.hpp\"\r\n#include \"RX64M\/bus.hpp\"\r\n#include \"RX64M\/mpc.hpp\"\r\n#include \"RX64M\/icu.hpp\"\r\n#include \"RX64M\/sci.hpp\"\r\n#include \"RX64M\/riic.hpp\"\r\n#include \"RX64M\/rspi.hpp\"\r\n#include \"RX64M\/port_map.hpp\"\r\n#include \"RX64M\/power_cfg.hpp\"\r\n#include \"RX64M\/icu_mgr.hpp\"\r\n#include \"RX64M\/sdhi.hpp\"\r\n#include \"RX64M\/s12adc.hpp\"\r\n#include \"RX64M\/r12da.hpp\"\r\n#include \"RX64M\/adc_io.hpp\"\r\n#include \"RX64M\/sdram.hpp\"\r\n#include \"RX64M\/etherc.hpp\"\r\n#include \"RX64M\/edmac.hpp\"\r\n#include \"RX64M\/rtc.hpp\"\r\n#include \"RX64M\/rtc_io.hpp\"\r\n#include \"RX64M\/flash.hpp\"\r\n#include \"RX64M\/flash_io.hpp\"\r\n#include \"RX64M\/ether_io.hpp\"\r\n\r\n#else\r\n#  error \"Requires SIG_XXX to be defined\"\r\n#endif\r\nadd GPT#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tルネサス RX 選択\r\n    @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2016, 2017 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"common\/byte_order.h\"\r\n#include \"common\/vect.h\"\r\n#include \"common\/delay.hpp\"\r\n\r\n#if defined(SIG_RX621)\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX621\/system.hpp\"\r\n#include \"RX621\/sci.hpp\"\r\n#include \"RX621\/icu.hpp\"\r\n\r\n#elif defined(SIG_RX24T)\r\n#include \"RX24T\/peripheral.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX24T\/system.hpp\"\r\n#include \"RX24T\/dtc.hpp\"\r\n#include \"RX24T\/icu.hpp\"\r\n#include \"RX24T\/mtu3.hpp\"\r\n#include \"RX24T\/poe3.hpp\"\r\n#include \"RX24T\/gpt.hpp\"\r\n#include \"RX24T\/tmr.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX24T\/sci.hpp\"\r\n#include \"RX24T\/riic.hpp\"\r\n#include \"RX24T\/rspi.hpp\"\r\n#include \"RX24T\/crc.hpp\"\r\n#include \"RX24T\/s12ad.hpp\"\r\n#include \"RX24T\/adc_io.hpp\"\r\n#include \"RX24T\/da.hpp\"\r\n#include \"RX24T\/cmpc.hpp\"\r\n#include \"RX24T\/doc.hpp\"\r\n#include \"RX24T\/port_map.hpp\"\r\n#include \"RX24T\/power_cfg.hpp\"\r\n#include \"RX24T\/icu_mgr.hpp\"\r\n#include \"RX24T\/flash.hpp\"\r\n#include \"RX24T\/flash_io.hpp\"\r\n\r\n#elif defined(SIG_RX63T)\r\n#include \"RX63T\/peripheral.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX63T\/system.hpp\"\r\n#include \"RX63T\/sci.hpp\"\r\n#include \"RX63T\/icu.hpp\"\r\n#include \"RX63T\/port_map.hpp\"\r\n#include \"RX63T\/power_cfg.hpp\"\r\n#include \"RX63T\/icu_mgr.hpp\"\r\n\r\n#elif defined(SIG_RX64M)\r\n#include \"RX64M\/peripheral.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX64M\/system.hpp\"\r\n#include \"RX64M\/system_io.hpp\"\r\n#include \"RX64M\/bus.hpp\"\r\n#include \"RX64M\/mpc.hpp\"\r\n#include \"RX64M\/icu.hpp\"\r\n#include \"RX64M\/sci.hpp\"\r\n#include \"RX64M\/riic.hpp\"\r\n#include \"RX64M\/rspi.hpp\"\r\n#include \"RX64M\/port_map.hpp\"\r\n#include \"RX64M\/power_cfg.hpp\"\r\n#include \"RX64M\/icu_mgr.hpp\"\r\n#include \"RX64M\/sdhi.hpp\"\r\n#include \"RX64M\/s12adc.hpp\"\r\n#include \"RX64M\/r12da.hpp\"\r\n#include \"RX64M\/adc_io.hpp\"\r\n#include \"RX64M\/sdram.hpp\"\r\n#include \"RX64M\/etherc.hpp\"\r\n#include \"RX64M\/edmac.hpp\"\r\n#include \"RX64M\/rtc.hpp\"\r\n#include \"RX64M\/rtc_io.hpp\"\r\n#include \"RX64M\/flash.hpp\"\r\n#include \"RX64M\/flash_io.hpp\"\r\n#include \"RX64M\/ether_io.hpp\"\r\n\r\n#else\r\n#  error \"Requires SIG_XXX to be defined\"\r\n#endif\r\n<|endoftext|>"}
{"text":"\/***************************************************************************\n**\n** Copyright (C) 2010, 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n#include \"meditortoolbar.h\"\n#include \"mtopleveloverlay.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nMEditorToolbar::MEditorToolbar(const MWidget &followWidget)\n    : overlay(new MTopLevelOverlay(followWidget.sceneManager())),\n      followWidget(followWidget),\n      buttonLayoutPolicy(new MLinearLayoutPolicy(new MLayout(this),\n                                                 Qt::Horizontal)),\n      arrow(new MEditorToolbarArrow(this)),\n      buttonUpdateQueued(false),\n      temporarilyDisappeared(false)\n{\n    setFlag(QGraphicsItem::ItemHasNoContents, true);\n    overlay->hide();\n    hide();\n    followWidget.scene()->addItem(overlay);\n    setParentItem(overlay);\n\n    \/\/ Set z value for arrow higher than default since\n    \/\/ it needs to float on top of buttons.\n    arrow->setZValue(1.0f);\n\n    \/\/ The policy notifies the widgets of their relative position inside the layout,\n    \/\/ this causes the buttons to be rendered with different backgrounds for each position\n    buttonLayoutPolicy->setNotifyWidgetsOfLayoutPositionEnabled(true);\n\n    \/\/ Don't add extra margins or spacings for buttons.\n    buttonLayoutPolicy->setContentsMargins(0.0f, 0.0f, 0.0f, 0.0f);\n    buttonLayoutPolicy->setSpacing(0.0f);\n\n    QObject::connect(sceneManager(), SIGNAL(orientationChanged(M::Orientation)),\n                     this, SLOT(updateGeometry()));\n\n    updateArrow(MEditorToolbarArrow::ArrowDown);\n}\n\nMEditorToolbar::~MEditorToolbar()\n{\n    hideEditorItem();\n    \/\/ Before destroying parent, detach so it doesn't try to destroy us.\n    setParentItem(0);\n    if (overlay) {\n        overlay->deleteLater();\n    }\n    qDeleteAll(buttons);\n}\n\nvoid MEditorToolbar::setPosition(const QPointF &pos,\n                                 MEditorToolbarArrow::ArrowDirection direction)\n{\n    setPos(followWidget.mapToItem(overlay, pos));\n    updateArrow(direction);\n}\n\nvoid MEditorToolbar::appear()\n{\n    overlay->show();\n    updateEditorItemVisibility();\n    temporarilyDisappeared = false;\n}\n\nvoid MEditorToolbar::disappear()\n{\n    hideEditorItem();\n    overlay->hide();\n    temporarilyDisappeared = false;\n}\n\nvoid MEditorToolbar::disappearTemporarily()\n{\n    if (isAppeared()) {\n        disappear();\n        temporarilyDisappeared = true;\n    }\n}\n\nvoid MEditorToolbar::removeTemporaryDisappearance()\n{\n    if (temporarilyDisappeared) {\n        appear();\n    }\n}\n\nbool MEditorToolbar::isAppeared() const\n{\n    return overlay->isVisible();\n}\n\nvoid MEditorToolbar::updateArrow(MEditorToolbarArrow::ArrowDirection direction)\n{\n    \/\/ Clear local transforms.\n    setTransform(QTransform());\n\n    \/\/ Style mode is different with regarding to top and bottom margins.\n    if (direction == MEditorToolbarArrow::ArrowUp) {\n        style().setModeEditorUnderCursor();\n    } else {\n        style().setModeDefault();\n    }\n    MStylableWidget::applyStyle();\n\n    const QRectF contentsRectangle = contentsRect();\n\n    \/\/ Update horizontally, make sure widget is inside screen.\n    qreal center = contentsRectangle.center().x();\n    QRectF mappedSceneRect = mapRectFromScene(\n        QRectF(QPointF(), sceneManager()->visibleSceneSize(M::Landscape)));\n    mappedSceneRect.translate(center, 0.0f);\n\n    qreal offscreenLeft = qMax(0.0f, mappedSceneRect.left());\n    qreal offscreenRight = qMax(0.0f, (effectiveSizeHint(Qt::PreferredSize).width()\n                                              - mappedSceneRect.right()));\n    \/\/ Screen rectangle in overlay coordinate system, just like we are\n    const QRectF screenRectInOverlay(\n        overlay->mapRectFromScene(QRectF(QPointF(), sceneManager()->visibleSceneSize(M::Landscape))));\n    qreal x;\n\n    if (size().width() < screenRectInOverlay.width()) {\n        \/\/ The widget won't be off the screen from both ends at the same time.\n        \/\/ Width is restricted to screen width.\n        x = center - arrow->size().width() \/ 2.0f\n            - offscreenLeft + offscreenRight;\n        x = qBound(contentsRectangle.left(),\n                          x,\n                          contentsRectangle.right() - arrow->size().width());\n    } else {\n        x = geometry().center().x() - screenRectInOverlay.center().x() - arrow->size().width() \/ 2.0f;\n    }\n\n    \/\/ Update vertically. Arrow graphics are designed to be aligned to either\n    \/\/ top or bottom of buttons, completely overlapping them.\n    arrow->setDirection(direction);\n\n    switch (arrow->direction()) {\n    case MEditorToolbarArrow::ArrowUp:\n        arrow->setPos(x, contentsRectangle.top());\n        break;\n    case MEditorToolbarArrow::ArrowDown:\n        arrow->setPos(x, contentsRectangle.bottom() - arrow->size().height());\n        break;\n    }\n\n    \/\/ Arrow has changed position, update widget origin.\n    updateWidgetOrigin();\n}\n\nvoid MEditorToolbar::updateWidgetOrigin()\n{\n    \/\/ We include margin to arrow tip position.\n    QPointF arrowTip(arrow->size().width() \/ 2.0f, 0);\n    \/\/ We need to round to an integer coordinate to avoid graphics glitches; if\n    \/\/ widgetOrigin.x() is for example 75.5, in portrait mode with German language with\n    \/\/ Cut, Copy & Paste buttons visible the one pixel thick button separator lines cannot\n    \/\/ be seen.\n    const QPoint widgetOrigin(QPointF(mapFromItem(arrow, arrowTip).x(),\n                                      arrow->direction() == MEditorToolbarArrow::ArrowUp\n                                      ? 0.0f : size().height()).toPoint());\n\n    setTransform(QTransform::fromTranslate(-widgetOrigin.x(),\n                                           -widgetOrigin.y()));\n}\n\nbool MEditorToolbar::event(QEvent *event)\n{\n    switch (event->type()) {\n    case QEvent::ActionAdded:\n    {\n        QActionEvent *actionEvent(static_cast(event));\n        Q_ASSERT(actionEvent);\n        Q_ASSERT(!actionEvent->before()); \/\/ we support appending only\n        QAction *action(qobject_cast(actionEvent->action()));\n        Q_ASSERT(action);\n\n        buttons << new MButton(action->text());\n        QObject::connect(buttons.back(), SIGNAL(clicked(bool)), action, SLOT(trigger()));\n        buttons.back()->setStyleName(action->objectName());\n        if (action->isVisible()) {\n            visibilityUpdated();\n        }\n        break;\n    }\n    case QEvent::ActionRemoved:\n    {\n        QActionEvent *actionEvent(static_cast(event));\n        const int actionIndex = actions().indexOf(actionEvent->action());\n        if (actionIndex >= 0) {\n            \/\/ Actions list is in sync with buttons list so we can\n            \/\/ use the same index to delete the corresponding button.\n            Q_ASSERT(actionIndex < buttons.count());\n            delete buttons.at(actionIndex);\n            buttons.removeAt(actionIndex);\n        }\n\n        if (actionEvent->action()->isVisible()) {\n            \/\/ Action was visible before removal, need to update widget.\n            visibilityUpdated();\n        }\n        break;\n    }\n    case QEvent::ActionChanged:\n    {\n        QActionEvent *actionEvent(static_cast(event));\n\n        \/\/ Name of action might have been changed.\n        const int actionIndex = actions().indexOf(actionEvent->action());\n        Q_ASSERT(actionIndex >= 0 && actionIndex < buttons.count());\n        MButton *button(buttons.at(actionIndex));\n        if (button->text() != actionEvent->action()->text()) {\n            button->setText(actionEvent->action()->text());\n        }\n\n        \/\/ Update visibility of buttons to match visibility of actions.\n        visibilityUpdated();\n        break;\n    }\n    default:\n        return MStylableWidget::event(event);\n        break;\n    }\n\n    event->accept();\n    return true;\n}\n\nvoid MEditorToolbar::mousePressEvent(QGraphicsSceneMouseEvent *)\n{\n    \/\/ Stop mouse event propagation.\n}\n\nvoid MEditorToolbar::updateAvailableButtons()\n{\n    buttonUpdateQueued = false;\n\n    while (buttonLayoutPolicy->count() > 0) {\n        buttonLayoutPolicy->removeAt(buttonLayoutPolicy->count() - 1);\n    }\n\n    QList actionList(actions());\n    Q_ASSERT(actionList.count() == buttons.count());\n\n    for (int i = 0; i < buttons.count(); ++i) {\n        MButton *button = buttons.at(i);\n\n        if (actionList.at(i)->isCheckable()) {\n            button->setCheckable(true);\n            button->setChecked(actionList.at(i)->isChecked());\n        }\n\n        if (actionList.at(i)->isVisible()) {\n            buttonLayoutPolicy->addItem(button);\n            button->show();\n        } else {\n            button->hide();\n        }\n    }\n\n    \/\/ Resize manually since this widget is not managed by layout.\n    resize(preferredSize());\n\n    \/\/ Hide if there is no buttons.\n    updateEditorItemVisibility();\n}\n\nvoid MEditorToolbar::visibilityUpdated()\n{\n    if (!buttonUpdateQueued) {\n        buttonUpdateQueued = true;\n        QMetaObject::invokeMethod(this, \"updateAvailableButtons\", Qt::QueuedConnection);\n    }\n}\n\nvoid MEditorToolbar::updateGeometry()\n{\n    MStylableWidget::updateGeometry();\n}\n\nQSizeF MEditorToolbar::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const\n{\n    QSizeF hint;\n    switch (which) {\n    case Qt::MinimumSize:\n    case Qt::PreferredSize: {\n            qreal width = 0;\n            qreal height = 0;\n            for (int i = 0; i < buttonLayoutPolicy->count(); ++i) {\n                QSizeF buttonHint = buttonLayoutPolicy->itemAt(i)->effectiveSizeHint(Qt::PreferredSize);\n                width += buttonHint.width();\n                height = qMax(height, buttonHint.height());\n            }\n            width += style()->marginLeft() + style()->marginRight();\n            height += style()->marginTop() + style()->marginBottom();\n            hint.setWidth(width);\n            hint.setHeight(height);\n        }\n        break;\n    case Qt::MaximumSize:\n        hint = QSizeF(sceneManager() ? sceneManager()->visibleSceneSize().width() : QWIDGETSIZE_MAX,\n                      QWIDGETSIZE_MAX);\n        if (constraint.width() > 0.0f) {\n            hint.setWidth(constraint.width());\n        } else {\n            hint.setWidth(QWIDGETSIZE_MAX);\n        }\n        if (constraint.height() > 0.0f) {\n            hint.setHeight(constraint.height());\n        } else {\n            hint.setHeight(QWIDGETSIZE_MAX);\n        }\n        break;\n    default:\n        break;\n    }\n\n    return hint;\n}\n\nvoid MEditorToolbar::resizeEvent(QGraphicsSceneResizeEvent *)\n{\n    emit sizeChanged();\n}\n\nvoid MEditorToolbar::updateEditorItemVisibility()\n{\n    \/\/ Visibility of editor item is determined solely by existence of buttons.\n    if (buttonLayoutPolicy->count() > 0) {\n        showEditorItem();\n    } else {\n        hideEditorItem();\n    }\n}\n\nvoid MEditorToolbar::showEditorItem()\n{\n    \/\/ Set focus proxy so that input widget doesn't lose focus.\n    setFocusPolicy(Qt::ClickFocus);\n    setFocusProxy(&const_cast(followWidget));\n    show();\n}\n\nvoid MEditorToolbar::hideEditorItem()\n{\n    setFocusProxy(0);\n    setFocusPolicy(Qt::NoFocus);\n    hide();\n}\nFixes: NB#266547, Rich Text bubble cut when placed in empty composer\/***************************************************************************\n**\n** Copyright (C) 2010, 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n#include \"meditortoolbar.h\"\n#include \"mtopleveloverlay.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nMEditorToolbar::MEditorToolbar(const MWidget &followWidget)\n    : overlay(new MTopLevelOverlay(followWidget.sceneManager())),\n      followWidget(followWidget),\n      buttonLayoutPolicy(new MLinearLayoutPolicy(new MLayout(this),\n                                                 Qt::Horizontal)),\n      arrow(new MEditorToolbarArrow(this)),\n      buttonUpdateQueued(false),\n      temporarilyDisappeared(false)\n{\n    setFlag(QGraphicsItem::ItemHasNoContents, true);\n    overlay->hide();\n    hide();\n    followWidget.scene()->addItem(overlay);\n    setParentItem(overlay);\n\n    \/\/ Set z value for arrow higher than default since\n    \/\/ it needs to float on top of buttons.\n    arrow->setZValue(1.0f);\n\n    \/\/ The policy notifies the widgets of their relative position inside the layout,\n    \/\/ this causes the buttons to be rendered with different backgrounds for each position\n    buttonLayoutPolicy->setNotifyWidgetsOfLayoutPositionEnabled(true);\n\n    \/\/ Don't add extra margins or spacings for buttons.\n    buttonLayoutPolicy->setContentsMargins(0.0f, 0.0f, 0.0f, 0.0f);\n    buttonLayoutPolicy->setSpacing(0.0f);\n\n    QObject::connect(sceneManager(), SIGNAL(orientationChanged(M::Orientation)),\n                     this, SLOT(updateGeometry()));\n\n    updateArrow(MEditorToolbarArrow::ArrowDown);\n}\n\nMEditorToolbar::~MEditorToolbar()\n{\n    hideEditorItem();\n    \/\/ Before destroying parent, detach so it doesn't try to destroy us.\n    setParentItem(0);\n    if (overlay) {\n        overlay->deleteLater();\n    }\n    qDeleteAll(buttons);\n}\n\nvoid MEditorToolbar::setPosition(const QPointF &pos,\n                                 MEditorToolbarArrow::ArrowDirection direction)\n{\n    setPos(followWidget.mapToItem(overlay, pos));\n    updateArrow(direction);\n}\n\nvoid MEditorToolbar::appear()\n{\n    overlay->show();\n    updateEditorItemVisibility();\n    temporarilyDisappeared = false;\n}\n\nvoid MEditorToolbar::disappear()\n{\n    hideEditorItem();\n    overlay->hide();\n    temporarilyDisappeared = false;\n}\n\nvoid MEditorToolbar::disappearTemporarily()\n{\n    if (isAppeared()) {\n        disappear();\n        temporarilyDisappeared = true;\n    }\n}\n\nvoid MEditorToolbar::removeTemporaryDisappearance()\n{\n    if (temporarilyDisappeared) {\n        appear();\n    }\n}\n\nbool MEditorToolbar::isAppeared() const\n{\n    return overlay->isVisible();\n}\n\nvoid MEditorToolbar::updateArrow(MEditorToolbarArrow::ArrowDirection direction)\n{\n    \/\/ Clear local transforms.\n    setTransform(QTransform());\n\n    \/\/ Style mode is different with regarding to top and bottom margins.\n    if (direction == MEditorToolbarArrow::ArrowUp) {\n        style().setModeEditorUnderCursor();\n    } else {\n        style().setModeDefault();\n    }\n    MStylableWidget::applyStyle();\n\n    const QRectF contentsRectangle = contentsRect();\n\n    \/\/ Update horizontally, make sure widget is inside screen.\n    qreal center = contentsRectangle.center().x();\n    QRectF mappedSceneRect = mapRectFromScene(\n        QRectF(QPointF(), sceneManager()->visibleSceneSize(M::Landscape)));\n    mappedSceneRect.translate(center, 0.0f);\n\n    qreal offscreenLeft = qMax(0.0f, mappedSceneRect.left());\n    qreal offscreenRight = qMax(0.0f, (effectiveSizeHint(Qt::PreferredSize).width()\n                                              - mappedSceneRect.right()));\n    \/\/ Screen rectangle in overlay coordinate system, just like we are\n    const QRectF screenRectInOverlay(\n        overlay->mapRectFromScene(QRectF(QPointF(), sceneManager()->visibleSceneSize(M::Landscape))));\n    qreal x;\n\n    if (size().width() < screenRectInOverlay.width()) {\n        \/\/ The widget won't be off the screen from both ends at the same time.\n        \/\/ Width is restricted to screen width.\n        x = center - arrow->size().width() \/ 2.0f\n            - offscreenLeft + offscreenRight;\n        x = qBound(contentsRectangle.left(),\n                          x,\n                          contentsRectangle.right() - arrow->size().width());\n    } else {\n        x = geometry().center().x() - screenRectInOverlay.center().x() - arrow->size().width() \/ 2.0f;\n    }\n\n    \/\/ Update vertically. Arrow graphics are designed to be aligned to either\n    \/\/ top or bottom of buttons, completely overlapping them.\n    arrow->setDirection(direction);\n\n    switch (arrow->direction()) {\n    case MEditorToolbarArrow::ArrowUp:\n        arrow->setPos(x, contentsRectangle.top());\n        break;\n    case MEditorToolbarArrow::ArrowDown:\n        arrow->setPos(x, contentsRectangle.bottom() - arrow->size().height());\n        break;\n    }\n\n    \/\/ Arrow has changed position, update widget origin.\n    updateWidgetOrigin();\n}\n\nvoid MEditorToolbar::updateWidgetOrigin()\n{\n    \/\/ We include margin to arrow tip position.\n    QPointF arrowTip(arrow->size().width() \/ 2.0f, 0);\n    arrowTip = mapFromItem(arrow, arrowTip);\n\n    qreal translateX = arrowTip.x();\n\n    const QRectF screenRectInOverlay(\n        overlay->mapRectFromScene(QRectF(QPointF(), sceneManager()->visibleSceneSize(M::Landscape))));\n\n    \/\/ Avoid editor toolbar clipping when possible\n    if (size().width() < screenRectInOverlay.width()) {\n        if (pos().x() < (screenRectInOverlay.width() - size().width())) {\n            \/\/ Don't allow editor toolbar to go over the left edge of the screen\n            translateX = qMin(translateX, pos().x());\n        } else {\n            \/\/ Don't allow editor toolbar to go over the right edge of the screen\n            translateX = qMax(translateX, size().width() + pos().x() - screenRectInOverlay.width());\n        }\n    }\n\n    \/\/ We need to round to an integer coordinate to avoid graphics glitches; if\n    \/\/ widgetOrigin.x() is for example 75.5, in portrait mode with German language with\n    \/\/ Cut, Copy & Paste buttons visible the one pixel thick button separator lines cannot\n    \/\/ be seen.\n    const QPoint widgetOrigin(QPointF(translateX,\n                                      arrow->direction() == MEditorToolbarArrow::ArrowUp\n                                      ? 0.0f : size().height()).toPoint());\n\n    setTransform(QTransform::fromTranslate(-widgetOrigin.x(),\n                                           -widgetOrigin.y()));\n}\n\nbool MEditorToolbar::event(QEvent *event)\n{\n    switch (event->type()) {\n    case QEvent::ActionAdded:\n    {\n        QActionEvent *actionEvent(static_cast(event));\n        Q_ASSERT(actionEvent);\n        Q_ASSERT(!actionEvent->before()); \/\/ we support appending only\n        QAction *action(qobject_cast(actionEvent->action()));\n        Q_ASSERT(action);\n\n        buttons << new MButton(action->text());\n        QObject::connect(buttons.back(), SIGNAL(clicked(bool)), action, SLOT(trigger()));\n        buttons.back()->setStyleName(action->objectName());\n        if (action->isVisible()) {\n            visibilityUpdated();\n        }\n        break;\n    }\n    case QEvent::ActionRemoved:\n    {\n        QActionEvent *actionEvent(static_cast(event));\n        const int actionIndex = actions().indexOf(actionEvent->action());\n        if (actionIndex >= 0) {\n            \/\/ Actions list is in sync with buttons list so we can\n            \/\/ use the same index to delete the corresponding button.\n            Q_ASSERT(actionIndex < buttons.count());\n            delete buttons.at(actionIndex);\n            buttons.removeAt(actionIndex);\n        }\n\n        if (actionEvent->action()->isVisible()) {\n            \/\/ Action was visible before removal, need to update widget.\n            visibilityUpdated();\n        }\n        break;\n    }\n    case QEvent::ActionChanged:\n    {\n        QActionEvent *actionEvent(static_cast(event));\n\n        \/\/ Name of action might have been changed.\n        const int actionIndex = actions().indexOf(actionEvent->action());\n        Q_ASSERT(actionIndex >= 0 && actionIndex < buttons.count());\n        MButton *button(buttons.at(actionIndex));\n        if (button->text() != actionEvent->action()->text()) {\n            button->setText(actionEvent->action()->text());\n        }\n\n        \/\/ Update visibility of buttons to match visibility of actions.\n        visibilityUpdated();\n        break;\n    }\n    default:\n        return MStylableWidget::event(event);\n        break;\n    }\n\n    event->accept();\n    return true;\n}\n\nvoid MEditorToolbar::mousePressEvent(QGraphicsSceneMouseEvent *)\n{\n    \/\/ Stop mouse event propagation.\n}\n\nvoid MEditorToolbar::updateAvailableButtons()\n{\n    buttonUpdateQueued = false;\n\n    while (buttonLayoutPolicy->count() > 0) {\n        buttonLayoutPolicy->removeAt(buttonLayoutPolicy->count() - 1);\n    }\n\n    QList actionList(actions());\n    Q_ASSERT(actionList.count() == buttons.count());\n\n    for (int i = 0; i < buttons.count(); ++i) {\n        MButton *button = buttons.at(i);\n\n        if (actionList.at(i)->isCheckable()) {\n            button->setCheckable(true);\n            button->setChecked(actionList.at(i)->isChecked());\n        }\n\n        if (actionList.at(i)->isVisible()) {\n            buttonLayoutPolicy->addItem(button);\n            button->show();\n        } else {\n            button->hide();\n        }\n    }\n\n    \/\/ Resize manually since this widget is not managed by layout.\n    resize(preferredSize());\n\n    \/\/ Hide if there is no buttons.\n    updateEditorItemVisibility();\n}\n\nvoid MEditorToolbar::visibilityUpdated()\n{\n    if (!buttonUpdateQueued) {\n        buttonUpdateQueued = true;\n        QMetaObject::invokeMethod(this, \"updateAvailableButtons\", Qt::QueuedConnection);\n    }\n}\n\nvoid MEditorToolbar::updateGeometry()\n{\n    MStylableWidget::updateGeometry();\n}\n\nQSizeF MEditorToolbar::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const\n{\n    QSizeF hint;\n    switch (which) {\n    case Qt::MinimumSize:\n    case Qt::PreferredSize: {\n            qreal width = 0;\n            qreal height = 0;\n            for (int i = 0; i < buttonLayoutPolicy->count(); ++i) {\n                QSizeF buttonHint = buttonLayoutPolicy->itemAt(i)->effectiveSizeHint(Qt::PreferredSize);\n                width += buttonHint.width();\n                height = qMax(height, buttonHint.height());\n            }\n            width += style()->marginLeft() + style()->marginRight();\n            height += style()->marginTop() + style()->marginBottom();\n            hint.setWidth(width);\n            hint.setHeight(height);\n        }\n        break;\n    case Qt::MaximumSize:\n        hint = QSizeF(sceneManager() ? sceneManager()->visibleSceneSize().width() : QWIDGETSIZE_MAX,\n                      QWIDGETSIZE_MAX);\n        if (constraint.width() > 0.0f) {\n            hint.setWidth(constraint.width());\n        } else {\n            hint.setWidth(QWIDGETSIZE_MAX);\n        }\n        if (constraint.height() > 0.0f) {\n            hint.setHeight(constraint.height());\n        } else {\n            hint.setHeight(QWIDGETSIZE_MAX);\n        }\n        break;\n    default:\n        break;\n    }\n\n    return hint;\n}\n\nvoid MEditorToolbar::resizeEvent(QGraphicsSceneResizeEvent *)\n{\n    emit sizeChanged();\n}\n\nvoid MEditorToolbar::updateEditorItemVisibility()\n{\n    \/\/ Visibility of editor item is determined solely by existence of buttons.\n    if (buttonLayoutPolicy->count() > 0) {\n        showEditorItem();\n    } else {\n        hideEditorItem();\n    }\n}\n\nvoid MEditorToolbar::showEditorItem()\n{\n    \/\/ Set focus proxy so that input widget doesn't lose focus.\n    setFocusPolicy(Qt::ClickFocus);\n    setFocusProxy(&const_cast(followWidget));\n    show();\n}\n\nvoid MEditorToolbar::hideEditorItem()\n{\n    setFocusProxy(0);\n    setFocusPolicy(Qt::NoFocus);\n    hide();\n}\n<|endoftext|>"}
{"text":"#include \"vlc_video_source.h\"\n#include \n#include \n#include \n#include \n\nnamespace gg\n{\n\nVideoSourceVLC::VideoSourceVLC(const std::string path)\n    : _vlc_inst(nullptr)\n    , _vlc_mp(nullptr)\n    , _video_buffer(nullptr)\n    , _data_length(0)\n    , _cols(0)\n    , _rows(0)\n    , _sub(nullptr)\n    , _path(path)\n{\n    this->init_vlc();\n    this->run_vlc();\n}\n\n\nVideoSourceVLC::~VideoSourceVLC()\n{\n    stop_vlc();\n    release_vlc();\n}\n\n\nbool VideoSourceVLC::get_frame_dimensions(int & width, int & height)\n{\n    \/\/\/\\todo mutex\n\n    if(this->_cols == 0 || this->_rows == 0)\n        return false;\n\n    width = this->_cols;\n    height = this->_rows;\n    return true;\n}\n\n\nbool VideoSourceVLC::get_frame(VideoFrame_BGRA & frame)\n{\n    throw VideoSourceError(\"VLC video source supports only I420 colour space\");\n\n    \/\/ TODO\n\n    \/\/\/\\todo mutex\n\n    if (_cols == 0 || _rows == 0 || _video_buffer == nullptr)\n        return false;\n\n    \/\/ allocate and fill the image\n    if (_cols * _rows * 4 == this->_data_length)\n        frame = VideoFrame_BGRA(this->_video_buffer, this->_cols, this->_rows);\n    else\n        throw VideoSourceError(\"VLC video source does not support padded images\");\n\n    return true;\n}\n\n\nbool VideoSourceVLC::get_frame(VideoFrame_I420 & frame)\n{\n    if (_data_length > 0)\n    {\n        \/\/ TODO manage data?\n        frame = VideoFrame_I420(_video_buffer, _data_length, _cols, _rows, false);\n        return true;\n    }\n    else\n        return false;\n\n    \/\/ TODO #86\n}\n\n\ndouble VideoSourceVLC::get_frame_rate()\n{\n    \/\/return libvlc_media_player_get_rate( m_mp );\n    return libvlc_media_player_get_fps(_vlc_mp);\n    \/\/throw std::runtime_error(\"get_frame_rate to be implemented\");\n    \/\/return 0.0;\n}\n\n\nvoid VideoSourceVLC::set_sub_frame(int x, int y, int width, int height)\n{\n    \/\/ TODO mutex?\n\n    if (x >= _full.x and x + width <= _full.x + _full.width and\n        y >= _full.y and y + height <= _full.y + _full.height)\n    {\n        stop_vlc();\n        release_vlc();\n        if (_sub == nullptr) _sub = new FrameBox;\n        _sub->x = x;\n        _sub->y = y;\n        _sub->width = width;\n        _sub->height = height;\n        init_vlc();\n        run_vlc();\n    }\n}\n\n\nvoid VideoSourceVLC::get_full_frame()\n{\n    \/\/ TODO mutex?\n    stop_vlc();\n    release_vlc();\n    if (_sub)\n    {\n        delete _sub;\n        _sub = nullptr;\n    }\n    init_vlc();\n    run_vlc();\n}\n\n\nvoid VideoSourceVLC::init_vlc()\n{\n    \/\/ VLC pointers\n    libvlc_media_t * vlc_media = nullptr;\n\n    \/\/ VLC options\n    char smem_options[512];\n\n    sprintf(smem_options, \"#\");\n    if (_sub != nullptr)\n    {\n        unsigned int croptop = _sub->y,\n                     cropbottom = _full.height - (_sub->y + _sub->height),\n                     cropleft = _sub->x,\n                     cropright = _full.width - (_sub->x + _sub->width);\n        sprintf(smem_options,\n                \"%stranscode{vcodec=I420,vfilter=croppadd{\",\n                smem_options);\n        sprintf(smem_options,\n                \"%scroptop=%u,cropbottom=%u,cropleft=%u,cropright=%u}}:\",\n                smem_options,\n                croptop, cropbottom, cropleft, cropright);\n    }\n    sprintf(smem_options,\n            \"%ssmem{video-data=%lld,video-prerender-callback=%lld,video-postrender-callback=%lld}\",\n            smem_options,\n            (long long int)(intptr_t)(void*) this,\n            (long long int)(intptr_t)(void*) &VideoSourceVLC::prepareRender,\n            (long long int)(intptr_t)(void*) &VideoSourceVLC::handleStream );\n\n    const char * const vlc_args[] = {\n        \"-I\", \"dummy\", \/\/ Don't use any interface\n        \"--ignore-config\", \/\/ Don't use VLC's config\n        \"--extraintf=logger\", \/\/ Log anything\n        \/\/ TODO - what about the options below?\n        \/\/\"--verbose=2\", \/\/ Be much more verbose then normal for debugging purpose\n        \/\/\"--clock-jitter=0\",\n        \/\/\"--file-caching=150\",\n        \"--no-audio\",\n        \"--sout\", smem_options \/\/ Stream to memory\n    };\n\n    \/\/ We launch VLC\n    _vlc_inst = libvlc_new(sizeof(vlc_args) \/ sizeof(vlc_args[0]), vlc_args);\n    if (_vlc_inst == nullptr)\n        throw VideoSourceError(\"Could not create VLC engine\");\n\n    \/\/ If path contains a colon (:), it will be treated as a\n    \/\/ URL. Else, it will be considered as a local path.\n    if (_path.find(\":\") == std::string::npos)\n        vlc_media = libvlc_media_new_path(_vlc_inst, _path.c_str());\n    else\n        vlc_media = libvlc_media_new_location(_vlc_inst, _path.c_str());\n    if (vlc_media == nullptr)\n        throw VideoSourceError(std::string(\"Could not open \").append(_path));\n\n    libvlc_media_add_option(vlc_media, \":noaudio\");\n    libvlc_media_add_option(vlc_media, \":no-video-title-show\");\n\n    \/\/ Create a media player playing environement\n    _vlc_mp = libvlc_media_player_new_from_media(vlc_media);\n    if (_vlc_mp == nullptr)\n        throw VideoSourceError(\"Could create VLC media player\");\n\n    \/\/ No need to keep the media now\n    libvlc_media_release( vlc_media );\n}\n\n\nvoid VideoSourceVLC::run_vlc()\n{\n    \/\/ play the media_player\n    if (libvlc_media_player_play(_vlc_mp) != 0)\n        throw VideoSourceError(\"Could not start VLC media player\");\n\n    \/\/ empirically determined value that allows for initialisation\n    \/\/ to succeed before any API functions are called on this object\n    std::this_thread::sleep_for(std::chrono::milliseconds(350));\n    unsigned int width, height;\n    if (libvlc_video_get_size(_vlc_mp, 0, &width, &height) != 0)\n        throw VideoSourceError(\"Could not get video dimensions\");\n\n    _full.x = 0;\n    _full.y = 0;\n    _full.width = width;\n    _full.height = height;\n}\n\n\nvoid VideoSourceVLC::stop_vlc()\n{\n    if (libvlc_media_player_is_playing(_vlc_mp) == 1)\n        \/\/ stop playing\n        libvlc_media_player_stop(_vlc_mp);\n}\n\n\nvoid VideoSourceVLC::release_vlc()\n{\n    \/\/ free media player\n    if (_vlc_mp)\n        libvlc_media_player_release(_vlc_mp);\n\n    \/\/ free engine\n    if (_vlc_inst)\n        libvlc_release(_vlc_inst);\n\n    \/\/ free buffer\n    if (_video_buffer != nullptr)\n        delete[] _video_buffer;\n}\n\n\nvoid VideoSourceVLC::prepareRender(VideoSourceVLC * p_video_data,\n                                   uint8_t ** pp_pixel_buffer,\n                                   size_t size)\n{\n    \/\/\/\\todo create mutex guard\n\n    if (size != p_video_data->_data_length)\n    {\n        unsigned int width,height;\n        if (libvlc_video_get_size(p_video_data->_vlc_mp, 0, &width, &height) != 0)\n            return;\n\n        \/\/ TODO deallocate previous data?\n        p_video_data->_video_buffer = new uint8_t[size];\n        p_video_data->_data_length = size;\n        p_video_data->_cols = width;\n        p_video_data->_rows = height;\n    }\n\n    *pp_pixel_buffer = p_video_data->_video_buffer;\n}\n\n\nvoid VideoSourceVLC::handleStream(VideoSourceVLC * p_video_data,\n                                  uint8_t * p_pixel_buffer,\n                                  size_t cols,\n                                  size_t rows,\n                                  size_t colour_depth,\n                                  size_t size)\n{\n    \/\/ TODO: explain how data should be handled (see #86)\n    \/\/ TODO: Unlock the mutex\n}\n\n\nstd::string VideoSourceVLC::encode_psz_geometry(int x, int y, int width, int height)\n{\n    std::string psz_geometry;\n    psz_geometry.append(std::to_string(width)).append(\"x\")\n                .append(std::to_string(height))\n                .append(\"+\").append(std::to_string(x))\n                .append(\"+\").append(std::to_string(y));\n    return psz_geometry;\n}\n\n}\nIssue #83: using realloc instead of new when size of new data larger than existing allocation, also width and height assigned on their own to prevent potential issue where e.g. two combinations of different sizes lead to same data length#include \"vlc_video_source.h\"\n#include \n#include \n#include \n#include \n\nnamespace gg\n{\n\nVideoSourceVLC::VideoSourceVLC(const std::string path)\n    : _vlc_inst(nullptr)\n    , _vlc_mp(nullptr)\n    , _video_buffer(nullptr)\n    , _data_length(0)\n    , _cols(0)\n    , _rows(0)\n    , _sub(nullptr)\n    , _path(path)\n{\n    this->init_vlc();\n    this->run_vlc();\n}\n\n\nVideoSourceVLC::~VideoSourceVLC()\n{\n    stop_vlc();\n    release_vlc();\n}\n\n\nbool VideoSourceVLC::get_frame_dimensions(int & width, int & height)\n{\n    \/\/\/\\todo mutex\n\n    if(this->_cols == 0 || this->_rows == 0)\n        return false;\n\n    width = this->_cols;\n    height = this->_rows;\n    return true;\n}\n\n\nbool VideoSourceVLC::get_frame(VideoFrame_BGRA & frame)\n{\n    throw VideoSourceError(\"VLC video source supports only I420 colour space\");\n\n    \/\/ TODO\n\n    \/\/\/\\todo mutex\n\n    if (_cols == 0 || _rows == 0 || _video_buffer == nullptr)\n        return false;\n\n    \/\/ allocate and fill the image\n    if (_cols * _rows * 4 == this->_data_length)\n        frame = VideoFrame_BGRA(this->_video_buffer, this->_cols, this->_rows);\n    else\n        throw VideoSourceError(\"VLC video source does not support padded images\");\n\n    return true;\n}\n\n\nbool VideoSourceVLC::get_frame(VideoFrame_I420 & frame)\n{\n    if (_data_length > 0)\n    {\n        \/\/ TODO manage data?\n        frame = VideoFrame_I420(_video_buffer, _data_length, _cols, _rows, false);\n        return true;\n    }\n    else\n        return false;\n\n    \/\/ TODO #86\n}\n\n\ndouble VideoSourceVLC::get_frame_rate()\n{\n    \/\/return libvlc_media_player_get_rate( m_mp );\n    return libvlc_media_player_get_fps(_vlc_mp);\n    \/\/throw std::runtime_error(\"get_frame_rate to be implemented\");\n    \/\/return 0.0;\n}\n\n\nvoid VideoSourceVLC::set_sub_frame(int x, int y, int width, int height)\n{\n    \/\/ TODO mutex?\n\n    if (x >= _full.x and x + width <= _full.x + _full.width and\n        y >= _full.y and y + height <= _full.y + _full.height)\n    {\n        stop_vlc();\n        release_vlc();\n        if (_sub == nullptr) _sub = new FrameBox;\n        _sub->x = x;\n        _sub->y = y;\n        _sub->width = width;\n        _sub->height = height;\n        init_vlc();\n        run_vlc();\n    }\n}\n\n\nvoid VideoSourceVLC::get_full_frame()\n{\n    \/\/ TODO mutex?\n    stop_vlc();\n    release_vlc();\n    if (_sub)\n    {\n        delete _sub;\n        _sub = nullptr;\n    }\n    init_vlc();\n    run_vlc();\n}\n\n\nvoid VideoSourceVLC::init_vlc()\n{\n    \/\/ VLC pointers\n    libvlc_media_t * vlc_media = nullptr;\n\n    \/\/ VLC options\n    char smem_options[512];\n\n    sprintf(smem_options, \"#\");\n    if (_sub != nullptr)\n    {\n        unsigned int croptop = _sub->y,\n                     cropbottom = _full.height - (_sub->y + _sub->height),\n                     cropleft = _sub->x,\n                     cropright = _full.width - (_sub->x + _sub->width);\n        sprintf(smem_options,\n                \"%stranscode{vcodec=I420,vfilter=croppadd{\",\n                smem_options);\n        sprintf(smem_options,\n                \"%scroptop=%u,cropbottom=%u,cropleft=%u,cropright=%u}}:\",\n                smem_options,\n                croptop, cropbottom, cropleft, cropright);\n    }\n    sprintf(smem_options,\n            \"%ssmem{video-data=%lld,video-prerender-callback=%lld,video-postrender-callback=%lld}\",\n            smem_options,\n            (long long int)(intptr_t)(void*) this,\n            (long long int)(intptr_t)(void*) &VideoSourceVLC::prepareRender,\n            (long long int)(intptr_t)(void*) &VideoSourceVLC::handleStream );\n\n    const char * const vlc_args[] = {\n        \"-I\", \"dummy\", \/\/ Don't use any interface\n        \"--ignore-config\", \/\/ Don't use VLC's config\n        \"--extraintf=logger\", \/\/ Log anything\n        \/\/ TODO - what about the options below?\n        \/\/\"--verbose=2\", \/\/ Be much more verbose then normal for debugging purpose\n        \/\/\"--clock-jitter=0\",\n        \/\/\"--file-caching=150\",\n        \"--no-audio\",\n        \"--sout\", smem_options \/\/ Stream to memory\n    };\n\n    \/\/ We launch VLC\n    _vlc_inst = libvlc_new(sizeof(vlc_args) \/ sizeof(vlc_args[0]), vlc_args);\n    if (_vlc_inst == nullptr)\n        throw VideoSourceError(\"Could not create VLC engine\");\n\n    \/\/ If path contains a colon (:), it will be treated as a\n    \/\/ URL. Else, it will be considered as a local path.\n    if (_path.find(\":\") == std::string::npos)\n        vlc_media = libvlc_media_new_path(_vlc_inst, _path.c_str());\n    else\n        vlc_media = libvlc_media_new_location(_vlc_inst, _path.c_str());\n    if (vlc_media == nullptr)\n        throw VideoSourceError(std::string(\"Could not open \").append(_path));\n\n    libvlc_media_add_option(vlc_media, \":noaudio\");\n    libvlc_media_add_option(vlc_media, \":no-video-title-show\");\n\n    \/\/ Create a media player playing environement\n    _vlc_mp = libvlc_media_player_new_from_media(vlc_media);\n    if (_vlc_mp == nullptr)\n        throw VideoSourceError(\"Could create VLC media player\");\n\n    \/\/ No need to keep the media now\n    libvlc_media_release( vlc_media );\n}\n\n\nvoid VideoSourceVLC::run_vlc()\n{\n    \/\/ play the media_player\n    if (libvlc_media_player_play(_vlc_mp) != 0)\n        throw VideoSourceError(\"Could not start VLC media player\");\n\n    \/\/ empirically determined value that allows for initialisation\n    \/\/ to succeed before any API functions are called on this object\n    std::this_thread::sleep_for(std::chrono::milliseconds(350));\n    unsigned int width, height;\n    if (libvlc_video_get_size(_vlc_mp, 0, &width, &height) != 0)\n        throw VideoSourceError(\"Could not get video dimensions\");\n\n    _full.x = 0;\n    _full.y = 0;\n    _full.width = width;\n    _full.height = height;\n}\n\n\nvoid VideoSourceVLC::stop_vlc()\n{\n    if (libvlc_media_player_is_playing(_vlc_mp) == 1)\n        \/\/ stop playing\n        libvlc_media_player_stop(_vlc_mp);\n}\n\n\nvoid VideoSourceVLC::release_vlc()\n{\n    \/\/ free media player\n    if (_vlc_mp)\n        libvlc_media_player_release(_vlc_mp);\n\n    \/\/ free engine\n    if (_vlc_inst)\n        libvlc_release(_vlc_inst);\n\n    \/\/ free buffer\n    if (_video_buffer != nullptr)\n        delete[] _video_buffer;\n}\n\n\nvoid VideoSourceVLC::prepareRender(VideoSourceVLC * p_video_data,\n                                   uint8_t ** pp_pixel_buffer,\n                                   size_t size)\n{\n    \/\/\/\\todo create mutex guard\n\n    unsigned int width, height;\n    if (libvlc_video_get_size(p_video_data->_vlc_mp, 0, &width, &height) != 0)\n        return;\n    p_video_data->_cols = width;\n    p_video_data->_rows = height;\n\n    if (size > p_video_data->_data_length)\n        p_video_data->_video_buffer = realloc(p_video_data->_video_buffer, size * sizeof(uint8_t));\n    p_video_data->_data_length = size;\n\n    *pp_pixel_buffer = p_video_data->_video_buffer;\n}\n\n\nvoid VideoSourceVLC::handleStream(VideoSourceVLC * p_video_data,\n                                  uint8_t * p_pixel_buffer,\n                                  size_t cols,\n                                  size_t rows,\n                                  size_t colour_depth,\n                                  size_t size)\n{\n    \/\/ TODO: explain how data should be handled (see #86)\n    \/\/ TODO: Unlock the mutex\n}\n\n\nstd::string VideoSourceVLC::encode_psz_geometry(int x, int y, int width, int height)\n{\n    std::string psz_geometry;\n    psz_geometry.append(std::to_string(width)).append(\"x\")\n                .append(std::to_string(height))\n                .append(\"+\").append(std::to_string(x))\n                .append(\"+\").append(std::to_string(y));\n    return psz_geometry;\n}\n\n}\n<|endoftext|>"}
{"text":"Adding code with dynamic programming for color trees with all comments<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2017-2019 The Khronos Group Inc.\n\/\/ Copyright (c) 2017-2019 Valve Corporation\n\/\/ Copyright (c) 2017-2019 LunarG, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Author: Mark Young \n\/\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/ Use internal versions of flags similar to XR_EXT_debug_utils so that\n\/\/ we're not tightly coupled to that extension.  This way, if the extension\n\/\/ changes or gets replaced, we can be flexible in the loader.\n#define XR_LOADER_LOG_MESSAGE_SEVERITY_VERBOSE_BIT 0x00000001\n#define XR_LOADER_LOG_MESSAGE_SEVERITY_INFO_BIT 0x00000010\n#define XR_LOADER_LOG_MESSAGE_SEVERITY_WARNING_BIT 0x00000100\n#define XR_LOADER_LOG_MESSAGE_SEVERITY_ERROR_BIT 0x00001000\ntypedef XrFlags64 XrLoaderLogMessageSeverityFlagBits;\ntypedef XrFlags64 XrLoaderLogMessageSeverityFlags;\n\n#define XR_LOADER_LOG_MESSAGE_TYPE_GENERAL_BIT 0x00000001\n#define XR_LOADER_LOG_MESSAGE_TYPE_SPECIFICATION_BIT 0x00000002\n#define XR_LOADER_LOG_MESSAGE_TYPE_PERFORMANCE_BIT 0x00000004\ntypedef XrFlags64 XrLoaderLogMessageTypeFlagBits;\ntypedef XrFlags64 XrLoaderLogMessageTypeFlags;\n\n\/\/! Turns a uint64_t into a string formatted as hex.\n\/\/!\n\/\/! The core of the HandleToString implementation is in here.\nstd::string Uint64ToHexString(uint64_t val);\n\ntemplate \nstatic inline std::string HandleToString(T handle) {\n    return Uint64ToHexString(reinterpret_cast(handle));\n}\n\nstruct XrLoaderLogObjectInfo {\n    \/\/! Type-erased handle value\n    uint64_t handle;\n\n    \/\/! Kind of object this handle refers to\n    XrObjectType type;\n\n    \/\/! To be assigned by the application - not part of this object's identity\n    std::string name;\n\n    \/\/\/ Un-erase the type of the handle and get it properly typed again.\n    \/\/\/\n    \/\/\/ Note: Does not check the type before doing it!\n    template \n    HandleType& GetTypedHandle() {\n        return reinterpret_cast(handle);\n    }\n\n    \/\/! @overload\n    template \n    HandleType const& GetTypedHandle() const {\n        return reinterpret_cast(handle);\n    }\n\n    XrLoaderLogObjectInfo() = default;\n\n    template \n    XrLoaderLogObjectInfo(T h, XrObjectType t) : handle(reinterpret_cast(h)), type(t) {}\n\n    std::string ToString() const;\n};\n\n\/\/! True if the two object infos have the same handle value and handle type\nstatic inline bool Equivalent(XrLoaderLogObjectInfo const& a, XrLoaderLogObjectInfo const& b) {\n    return a.handle == b.handle && a.type == b.type;\n}\n\/\/! @overload\nstatic inline bool Equivalent(XrDebugUtilsObjectNameInfoEXT const& a, XrLoaderLogObjectInfo const& b) {\n    return a.objectHandle == b.handle && a.objectType == b.type;\n}\n\/\/! @overload\nstatic inline bool Equivalent(XrLoaderLogObjectInfo const& a, XrDebugUtilsObjectNameInfoEXT const& b) { return Equivalent(b, a); }\n\nstruct XrLoaderLogMessengerCallbackData {\n    const char* message_id;\n    const char* command_name;\n    const char* message;\n    uint8_t object_count;\n    XrLoaderLogObjectInfo* objects;\n    uint8_t session_labels_count;\n    XrDebugUtilsLabelEXT* session_labels;\n};\n\nenum XrLoaderLogType {\n    XR_LOADER_LOG_UNKNOWN = 0,\n    XR_LOADER_LOG_STDERR,\n    XR_LOADER_LOG_STDOUT,\n    XR_LOADER_LOG_DEBUG_UTILS,\n};\n\nclass LoaderLogRecorder {\n   public:\n    LoaderLogRecorder(XrLoaderLogType type, void* user_data, XrLoaderLogMessageSeverityFlags message_severities,\n                      XrLoaderLogMessageTypeFlags message_types) {\n        _active = false;\n        _user_data = user_data;\n        _type = type;\n        _unique_id = 0;\n        _message_severities = message_severities;\n        _message_types = message_types;\n    }\n    virtual ~LoaderLogRecorder() {}\n\n    XrLoaderLogType Type() { return _type; }\n    uint64_t UniqueId() { return _unique_id; }\n    XrLoaderLogMessageSeverityFlags MessageSeverities() { return _message_severities; }\n    XrLoaderLogMessageTypeFlags MessageTypes() { return _message_types; }\n\n    virtual void Start() { _active = true; }\n    bool IsPaused() { return _active; }\n    virtual void Pause() { _active = false; }\n    virtual void Resume() { _active = true; }\n    virtual void Stop() { _active = false; }\n\n    virtual bool LogMessage(XrLoaderLogMessageSeverityFlagBits message_severity, XrLoaderLogMessageTypeFlags message_type,\n                            const XrLoaderLogMessengerCallbackData* callback_data) = 0;\n\n   protected:\n    bool _active;\n    XrLoaderLogType _type;\n    uint64_t _unique_id;\n    void* _user_data;\n    XrLoaderLogMessageSeverityFlags _message_severities;\n    XrLoaderLogMessageTypeFlags _message_types;\n};\n\n\/\/ Standard Error logger, always on for now\nclass StdErrLoaderLogRecorder : public LoaderLogRecorder {\n   public:\n    StdErrLoaderLogRecorder(void* user_data);\n    ~StdErrLoaderLogRecorder() {}\n\n    virtual bool LogMessage(XrLoaderLogMessageSeverityFlagBits message_severity, XrLoaderLogMessageTypeFlags message_type,\n                            const XrLoaderLogMessengerCallbackData* callback_data);\n};\n\n\/\/ Standard Output logger used with XR_LOADER_DEBUG\nclass StdOutLoaderLogRecorder : public LoaderLogRecorder {\n   public:\n    StdOutLoaderLogRecorder(void* user_data, XrLoaderLogMessageSeverityFlags flags);\n    ~StdOutLoaderLogRecorder() {}\n\n    virtual bool LogMessage(XrLoaderLogMessageSeverityFlagBits message_severity, XrLoaderLogMessageTypeFlags message_type,\n                            const XrLoaderLogMessengerCallbackData* callback_data);\n};\n\n\/\/ Debug Utils logger used with XR_EXT_debug_utils\nclass DebugUtilsLogRecorder : public LoaderLogRecorder {\n   public:\n    DebugUtilsLogRecorder(const XrDebugUtilsMessengerCreateInfoEXT* create_info, XrDebugUtilsMessengerEXT debug_messenger);\n    ~DebugUtilsLogRecorder() {}\n\n    virtual bool LogMessage(XrLoaderLogMessageSeverityFlagBits message_severity, XrLoaderLogMessageTypeFlags message_type,\n                            const XrLoaderLogMessengerCallbackData* callback_data);\n\n    \/\/ Extension-specific logging functions\n    bool LogDebugUtilsMessage(XrDebugUtilsMessageSeverityFlagsEXT message_severity, XrDebugUtilsMessageTypeFlagsEXT message_type,\n                              const XrDebugUtilsMessengerCallbackDataEXT* callback_data);\n\n   private:\n    PFN_xrDebugUtilsMessengerCallbackEXT _user_callback;\n};\n\n\/\/ TODO: Add other Derived classes:\n\/\/  - FileLoaderLogRecorder     - During\/after xrCreateInstance\n\/\/  - PipeLoaderLogRecorder?    - During\/after xrCreateInstance\n\nclass ObjectInfoCollection {\n   public:\n    \/\/! Called from LoaderXrTermSetDebugUtilsObjectNameEXT - an empty name means remove\n    void AddObjectName(uint64_t object_handle, XrObjectType object_type, const std::string& object_name);\n\n    \/\/! Find the stored object info, if any, matching handle and type.\n    \/\/! Return nullptr if not found.\n    XrLoaderLogObjectInfo const* LookUpStoredObjectInfo(XrLoaderLogObjectInfo const& info) const;\n    \/\/! Find the stored object info, if any, matching handle and type.\n    \/\/! Return nullptr if not found.\n    XrLoaderLogObjectInfo* LookUpStoredObjectInfo(XrLoaderLogObjectInfo const& info);\n\n    \/\/! Find the stored object info, if any.\n    \/\/! Return nullptr if not found.\n    XrLoaderLogObjectInfo const* LookUpStoredObjectInfo(uint64_t handle, XrObjectType type) const {\n        return LookUpStoredObjectInfo({handle, type});\n    }\n\n    \/\/! Find the object name, if any, and update debug utils info accordingly.\n    \/\/! Return true if found and updated.\n    bool LookUpObjectName(XrDebugUtilsObjectNameInfoEXT& info) const;\n\n    \/\/! Find the object name, if any, and update logging info accordingly.\n    \/\/! Return true if found and updated.\n    bool LookUpObjectName(XrLoaderLogObjectInfo& info) const;\n\n    \/\/! Is the collection empty?\n    bool Empty() const { return _object_info.empty(); }\n\n   private:\n    \/\/ Object names that have been set for given objects\n    std::vector _object_info;\n};\nclass LoaderLogger {\n   public:\n    static LoaderLogger& GetInstance() {\n        std::call_once(LoaderLogger::_once_flag, []() { _instance.reset(new LoaderLogger); });\n        return *(_instance.get());\n    }\n\n    void AddLogRecorder(std::unique_ptr& recorder);\n    void RemoveLogRecorder(uint64_t unique_id);\n\n    \/\/! Called from LoaderXrTermSetDebugUtilsObjectNameEXT - an empty name means remove\n    void AddObjectName(uint64_t object_handle, XrObjectType object_type, const std::string& object_name);\n    void BeginLabelRegion(XrSession session, const XrDebugUtilsLabelEXT* label_info);\n    void EndLabelRegion(XrSession session);\n    void InsertLabel(XrSession session, const XrDebugUtilsLabelEXT* label_info);\n    void DeleteSessionLabels(XrSession session);\n\n\n    bool LogMessage(XrLoaderLogMessageSeverityFlagBits message_severity, XrLoaderLogMessageTypeFlags message_type,\n                    const std::string& message_id, const std::string& command_name, const std::string& message,\n                    const std::vector& objects = {});\n    static bool LogErrorMessage(const std::string& command_name, const std::string& message,\n                                const std::vector& objects = {}) {\n        return GetInstance().LogMessage(XR_LOADER_LOG_MESSAGE_SEVERITY_ERROR_BIT, XR_LOADER_LOG_MESSAGE_TYPE_GENERAL_BIT,\n                                        \"OpenXR-Loader\", command_name, message, objects);\n    }\n    static bool LogWarningMessage(const std::string& command_name, const std::string& message,\n                                  const std::vector& objects = {}) {\n        return GetInstance().LogMessage(XR_LOADER_LOG_MESSAGE_SEVERITY_WARNING_BIT, XR_LOADER_LOG_MESSAGE_TYPE_GENERAL_BIT,\n                                        \"OpenXR-Loader\", command_name, message, objects);\n    }\n    static bool LogInfoMessage(const std::string& command_name, const std::string& message,\n                               const std::vector& objects = {}) {\n        return GetInstance().LogMessage(XR_LOADER_LOG_MESSAGE_SEVERITY_INFO_BIT, XR_LOADER_LOG_MESSAGE_TYPE_GENERAL_BIT,\n                                        \"OpenXR-Loader\", command_name, message, objects);\n    }\n    static bool LogVerboseMessage(const std::string& command_name, const std::string& message,\n                                  const std::vector& objects = {}) {\n        return GetInstance().LogMessage(XR_LOADER_LOG_MESSAGE_SEVERITY_VERBOSE_BIT, XR_LOADER_LOG_MESSAGE_TYPE_GENERAL_BIT,\n                                        \"OpenXR-Loader\", command_name, message, objects);\n    }\n    static bool LogValidationErrorMessage(const std::string& vuid, const std::string& command_name, const std::string& message,\n                                          const std::vector& objects = {}) {\n        return GetInstance().LogMessage(XR_LOADER_LOG_MESSAGE_SEVERITY_ERROR_BIT, XR_LOADER_LOG_MESSAGE_TYPE_SPECIFICATION_BIT,\n                                        vuid, command_name, message, objects);\n    }\n    static bool LogValidationWarningMessage(const std::string& vuid, const std::string& command_name, const std::string& message,\n                                            const std::vector& objects = {}) {\n        return GetInstance().LogMessage(XR_LOADER_LOG_MESSAGE_SEVERITY_WARNING_BIT, XR_LOADER_LOG_MESSAGE_TYPE_SPECIFICATION_BIT,\n                                        vuid, command_name, message, objects);\n    }\n\n    \/\/ Extension-specific logging functions\n    bool LogDebugUtilsMessage(XrDebugUtilsMessageSeverityFlagsEXT message_severity, XrDebugUtilsMessageTypeFlagsEXT message_type,\n                              const XrDebugUtilsMessengerCallbackDataEXT* callback_data);\n\n   private:\n    struct InternalSessionLabel {\n        XrDebugUtilsLabelEXT debug_utils_label;\n        std::string label_name;\n        bool is_individual_label;\n    };\n\n    LoaderLogger();\n    LoaderLogger(const LoaderLogger&) = delete;\n    LoaderLogger& operator=(const LoaderLogger&) = delete;\n\n    \/\/\/ Retrieve labels for the given session, if any, and push them in reverse order on the vector.\n    void LookUpSessionLabels(XrSession session, std::vector& labels) const;\n\n    void RemoveIndividualLabel(std::vector* label_vec);\n\n    static std::unique_ptr _instance;\n    static std::once_flag _once_flag;\n\n    \/\/ List of available recorder objects\n    std::vector> _recorders;\n\n    ObjectInfoCollection _object_names;\n    \/\/ Session labels\n    std::unordered_map*> _session_labels;\n};\n\n\/\/ Utility functions for converting to\/from XR_EXT_debug_utils values\nXrLoaderLogMessageSeverityFlags DebugUtilsSeveritiesToLoaderLogMessageSeverities(\n    XrDebugUtilsMessageSeverityFlagsEXT utils_severities);\nXrDebugUtilsMessageSeverityFlagsEXT LoaderLogMessageSeveritiesToDebugUtilsMessageSeverities(\n    XrLoaderLogMessageSeverityFlags log_severities);\nXrLoaderLogMessageTypeFlagBits DebugUtilsMessageTypesToLoaderLogMessageTypes(XrDebugUtilsMessageTypeFlagsEXT utils_types);\nXrDebugUtilsMessageTypeFlagsEXT LoaderLogMessageTypesToDebugUtilsMessageTypes(XrLoaderLogMessageTypeFlagBits log_types);\nloader: Add another XrLoaderLogObjectInfo constructor from integers\/\/ Copyright (c) 2017-2019 The Khronos Group Inc.\n\/\/ Copyright (c) 2017-2019 Valve Corporation\n\/\/ Copyright (c) 2017-2019 LunarG, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Author: Mark Young \n\/\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/ Use internal versions of flags similar to XR_EXT_debug_utils so that\n\/\/ we're not tightly coupled to that extension.  This way, if the extension\n\/\/ changes or gets replaced, we can be flexible in the loader.\n#define XR_LOADER_LOG_MESSAGE_SEVERITY_VERBOSE_BIT 0x00000001\n#define XR_LOADER_LOG_MESSAGE_SEVERITY_INFO_BIT 0x00000010\n#define XR_LOADER_LOG_MESSAGE_SEVERITY_WARNING_BIT 0x00000100\n#define XR_LOADER_LOG_MESSAGE_SEVERITY_ERROR_BIT 0x00001000\ntypedef XrFlags64 XrLoaderLogMessageSeverityFlagBits;\ntypedef XrFlags64 XrLoaderLogMessageSeverityFlags;\n\n#define XR_LOADER_LOG_MESSAGE_TYPE_GENERAL_BIT 0x00000001\n#define XR_LOADER_LOG_MESSAGE_TYPE_SPECIFICATION_BIT 0x00000002\n#define XR_LOADER_LOG_MESSAGE_TYPE_PERFORMANCE_BIT 0x00000004\ntypedef XrFlags64 XrLoaderLogMessageTypeFlagBits;\ntypedef XrFlags64 XrLoaderLogMessageTypeFlags;\n\n\/\/! Turns a uint64_t into a string formatted as hex.\n\/\/!\n\/\/! The core of the HandleToString implementation is in here.\nstd::string Uint64ToHexString(uint64_t val);\n\ntemplate \nstatic inline std::string HandleToString(T handle) {\n    return Uint64ToHexString(reinterpret_cast(handle));\n}\n\nstruct XrLoaderLogObjectInfo {\n    \/\/! Type-erased handle value\n    uint64_t handle;\n\n    \/\/! Kind of object this handle refers to\n    XrObjectType type;\n\n    \/\/! To be assigned by the application - not part of this object's identity\n    std::string name;\n\n    \/\/\/ Un-erase the type of the handle and get it properly typed again.\n    \/\/\/\n    \/\/\/ Note: Does not check the type before doing it!\n    template \n    HandleType& GetTypedHandle() {\n        return reinterpret_cast(handle);\n    }\n\n    \/\/! @overload\n    template \n    HandleType const& GetTypedHandle() const {\n        return reinterpret_cast(handle);\n    }\n\n    XrLoaderLogObjectInfo() = default;\n\n    \/\/! Create from a typed handle and object type\n    template \n    XrLoaderLogObjectInfo(T h, XrObjectType t) : handle(reinterpret_cast(h)), type(t) {}\n\n    \/\/! Create from an untyped handle value (integer) and object type\n    XrLoaderLogObjectInfo(uint64_t h, XrObjectType t) : handle(h), type(t) {}\n\n    std::string ToString() const;\n};\n\n\/\/! True if the two object infos have the same handle value and handle type\nstatic inline bool Equivalent(XrLoaderLogObjectInfo const& a, XrLoaderLogObjectInfo const& b) {\n    return a.handle == b.handle && a.type == b.type;\n}\n\/\/! @overload\nstatic inline bool Equivalent(XrDebugUtilsObjectNameInfoEXT const& a, XrLoaderLogObjectInfo const& b) {\n    return a.objectHandle == b.handle && a.objectType == b.type;\n}\n\/\/! @overload\nstatic inline bool Equivalent(XrLoaderLogObjectInfo const& a, XrDebugUtilsObjectNameInfoEXT const& b) { return Equivalent(b, a); }\n\nstruct XrLoaderLogMessengerCallbackData {\n    const char* message_id;\n    const char* command_name;\n    const char* message;\n    uint8_t object_count;\n    XrLoaderLogObjectInfo* objects;\n    uint8_t session_labels_count;\n    XrDebugUtilsLabelEXT* session_labels;\n};\n\nenum XrLoaderLogType {\n    XR_LOADER_LOG_UNKNOWN = 0,\n    XR_LOADER_LOG_STDERR,\n    XR_LOADER_LOG_STDOUT,\n    XR_LOADER_LOG_DEBUG_UTILS,\n};\n\nclass LoaderLogRecorder {\n   public:\n    LoaderLogRecorder(XrLoaderLogType type, void* user_data, XrLoaderLogMessageSeverityFlags message_severities,\n                      XrLoaderLogMessageTypeFlags message_types) {\n        _active = false;\n        _user_data = user_data;\n        _type = type;\n        _unique_id = 0;\n        _message_severities = message_severities;\n        _message_types = message_types;\n    }\n    virtual ~LoaderLogRecorder() {}\n\n    XrLoaderLogType Type() { return _type; }\n    uint64_t UniqueId() { return _unique_id; }\n    XrLoaderLogMessageSeverityFlags MessageSeverities() { return _message_severities; }\n    XrLoaderLogMessageTypeFlags MessageTypes() { return _message_types; }\n\n    virtual void Start() { _active = true; }\n    bool IsPaused() { return _active; }\n    virtual void Pause() { _active = false; }\n    virtual void Resume() { _active = true; }\n    virtual void Stop() { _active = false; }\n\n    virtual bool LogMessage(XrLoaderLogMessageSeverityFlagBits message_severity, XrLoaderLogMessageTypeFlags message_type,\n                            const XrLoaderLogMessengerCallbackData* callback_data) = 0;\n\n   protected:\n    bool _active;\n    XrLoaderLogType _type;\n    uint64_t _unique_id;\n    void* _user_data;\n    XrLoaderLogMessageSeverityFlags _message_severities;\n    XrLoaderLogMessageTypeFlags _message_types;\n};\n\n\/\/ Standard Error logger, always on for now\nclass StdErrLoaderLogRecorder : public LoaderLogRecorder {\n   public:\n    StdErrLoaderLogRecorder(void* user_data);\n    ~StdErrLoaderLogRecorder() {}\n\n    virtual bool LogMessage(XrLoaderLogMessageSeverityFlagBits message_severity, XrLoaderLogMessageTypeFlags message_type,\n                            const XrLoaderLogMessengerCallbackData* callback_data);\n};\n\n\/\/ Standard Output logger used with XR_LOADER_DEBUG\nclass StdOutLoaderLogRecorder : public LoaderLogRecorder {\n   public:\n    StdOutLoaderLogRecorder(void* user_data, XrLoaderLogMessageSeverityFlags flags);\n    ~StdOutLoaderLogRecorder() {}\n\n    virtual bool LogMessage(XrLoaderLogMessageSeverityFlagBits message_severity, XrLoaderLogMessageTypeFlags message_type,\n                            const XrLoaderLogMessengerCallbackData* callback_data);\n};\n\n\/\/ Debug Utils logger used with XR_EXT_debug_utils\nclass DebugUtilsLogRecorder : public LoaderLogRecorder {\n   public:\n    DebugUtilsLogRecorder(const XrDebugUtilsMessengerCreateInfoEXT* create_info, XrDebugUtilsMessengerEXT debug_messenger);\n    ~DebugUtilsLogRecorder() {}\n\n    virtual bool LogMessage(XrLoaderLogMessageSeverityFlagBits message_severity, XrLoaderLogMessageTypeFlags message_type,\n                            const XrLoaderLogMessengerCallbackData* callback_data);\n\n    \/\/ Extension-specific logging functions\n    bool LogDebugUtilsMessage(XrDebugUtilsMessageSeverityFlagsEXT message_severity, XrDebugUtilsMessageTypeFlagsEXT message_type,\n                              const XrDebugUtilsMessengerCallbackDataEXT* callback_data);\n\n   private:\n    PFN_xrDebugUtilsMessengerCallbackEXT _user_callback;\n};\n\n\/\/ TODO: Add other Derived classes:\n\/\/  - FileLoaderLogRecorder     - During\/after xrCreateInstance\n\/\/  - PipeLoaderLogRecorder?    - During\/after xrCreateInstance\n\nclass ObjectInfoCollection {\n   public:\n    \/\/! Called from LoaderXrTermSetDebugUtilsObjectNameEXT - an empty name means remove\n    void AddObjectName(uint64_t object_handle, XrObjectType object_type, const std::string& object_name);\n\n    \/\/! Find the stored object info, if any, matching handle and type.\n    \/\/! Return nullptr if not found.\n    XrLoaderLogObjectInfo const* LookUpStoredObjectInfo(XrLoaderLogObjectInfo const& info) const;\n    \/\/! Find the stored object info, if any, matching handle and type.\n    \/\/! Return nullptr if not found.\n    XrLoaderLogObjectInfo* LookUpStoredObjectInfo(XrLoaderLogObjectInfo const& info);\n\n    \/\/! Find the stored object info, if any.\n    \/\/! Return nullptr if not found.\n    XrLoaderLogObjectInfo const* LookUpStoredObjectInfo(uint64_t handle, XrObjectType type) const {\n        return LookUpStoredObjectInfo({handle, type});\n    }\n\n    \/\/! Find the object name, if any, and update debug utils info accordingly.\n    \/\/! Return true if found and updated.\n    bool LookUpObjectName(XrDebugUtilsObjectNameInfoEXT& info) const;\n\n    \/\/! Find the object name, if any, and update logging info accordingly.\n    \/\/! Return true if found and updated.\n    bool LookUpObjectName(XrLoaderLogObjectInfo& info) const;\n\n    \/\/! Is the collection empty?\n    bool Empty() const { return _object_info.empty(); }\n\n   private:\n    \/\/ Object names that have been set for given objects\n    std::vector _object_info;\n};\nclass LoaderLogger {\n   public:\n    static LoaderLogger& GetInstance() {\n        std::call_once(LoaderLogger::_once_flag, []() { _instance.reset(new LoaderLogger); });\n        return *(_instance.get());\n    }\n\n    void AddLogRecorder(std::unique_ptr& recorder);\n    void RemoveLogRecorder(uint64_t unique_id);\n\n    \/\/! Called from LoaderXrTermSetDebugUtilsObjectNameEXT - an empty name means remove\n    void AddObjectName(uint64_t object_handle, XrObjectType object_type, const std::string& object_name);\n    void BeginLabelRegion(XrSession session, const XrDebugUtilsLabelEXT* label_info);\n    void EndLabelRegion(XrSession session);\n    void InsertLabel(XrSession session, const XrDebugUtilsLabelEXT* label_info);\n    void DeleteSessionLabels(XrSession session);\n\n\n    bool LogMessage(XrLoaderLogMessageSeverityFlagBits message_severity, XrLoaderLogMessageTypeFlags message_type,\n                    const std::string& message_id, const std::string& command_name, const std::string& message,\n                    const std::vector& objects = {});\n    static bool LogErrorMessage(const std::string& command_name, const std::string& message,\n                                const std::vector& objects = {}) {\n        return GetInstance().LogMessage(XR_LOADER_LOG_MESSAGE_SEVERITY_ERROR_BIT, XR_LOADER_LOG_MESSAGE_TYPE_GENERAL_BIT,\n                                        \"OpenXR-Loader\", command_name, message, objects);\n    }\n    static bool LogWarningMessage(const std::string& command_name, const std::string& message,\n                                  const std::vector& objects = {}) {\n        return GetInstance().LogMessage(XR_LOADER_LOG_MESSAGE_SEVERITY_WARNING_BIT, XR_LOADER_LOG_MESSAGE_TYPE_GENERAL_BIT,\n                                        \"OpenXR-Loader\", command_name, message, objects);\n    }\n    static bool LogInfoMessage(const std::string& command_name, const std::string& message,\n                               const std::vector& objects = {}) {\n        return GetInstance().LogMessage(XR_LOADER_LOG_MESSAGE_SEVERITY_INFO_BIT, XR_LOADER_LOG_MESSAGE_TYPE_GENERAL_BIT,\n                                        \"OpenXR-Loader\", command_name, message, objects);\n    }\n    static bool LogVerboseMessage(const std::string& command_name, const std::string& message,\n                                  const std::vector& objects = {}) {\n        return GetInstance().LogMessage(XR_LOADER_LOG_MESSAGE_SEVERITY_VERBOSE_BIT, XR_LOADER_LOG_MESSAGE_TYPE_GENERAL_BIT,\n                                        \"OpenXR-Loader\", command_name, message, objects);\n    }\n    static bool LogValidationErrorMessage(const std::string& vuid, const std::string& command_name, const std::string& message,\n                                          const std::vector& objects = {}) {\n        return GetInstance().LogMessage(XR_LOADER_LOG_MESSAGE_SEVERITY_ERROR_BIT, XR_LOADER_LOG_MESSAGE_TYPE_SPECIFICATION_BIT,\n                                        vuid, command_name, message, objects);\n    }\n    static bool LogValidationWarningMessage(const std::string& vuid, const std::string& command_name, const std::string& message,\n                                            const std::vector& objects = {}) {\n        return GetInstance().LogMessage(XR_LOADER_LOG_MESSAGE_SEVERITY_WARNING_BIT, XR_LOADER_LOG_MESSAGE_TYPE_SPECIFICATION_BIT,\n                                        vuid, command_name, message, objects);\n    }\n\n    \/\/ Extension-specific logging functions\n    bool LogDebugUtilsMessage(XrDebugUtilsMessageSeverityFlagsEXT message_severity, XrDebugUtilsMessageTypeFlagsEXT message_type,\n                              const XrDebugUtilsMessengerCallbackDataEXT* callback_data);\n\n   private:\n    struct InternalSessionLabel {\n        XrDebugUtilsLabelEXT debug_utils_label;\n        std::string label_name;\n        bool is_individual_label;\n    };\n\n    LoaderLogger();\n    LoaderLogger(const LoaderLogger&) = delete;\n    LoaderLogger& operator=(const LoaderLogger&) = delete;\n\n    \/\/\/ Retrieve labels for the given session, if any, and push them in reverse order on the vector.\n    void LookUpSessionLabels(XrSession session, std::vector& labels) const;\n\n    void RemoveIndividualLabel(std::vector* label_vec);\n\n    static std::unique_ptr _instance;\n    static std::once_flag _once_flag;\n\n    \/\/ List of available recorder objects\n    std::vector> _recorders;\n\n    ObjectInfoCollection _object_names;\n    \/\/ Session labels\n    std::unordered_map*> _session_labels;\n};\n\n\/\/ Utility functions for converting to\/from XR_EXT_debug_utils values\nXrLoaderLogMessageSeverityFlags DebugUtilsSeveritiesToLoaderLogMessageSeverities(\n    XrDebugUtilsMessageSeverityFlagsEXT utils_severities);\nXrDebugUtilsMessageSeverityFlagsEXT LoaderLogMessageSeveritiesToDebugUtilsMessageSeverities(\n    XrLoaderLogMessageSeverityFlags log_severities);\nXrLoaderLogMessageTypeFlagBits DebugUtilsMessageTypesToLoaderLogMessageTypes(XrDebugUtilsMessageTypeFlagsEXT utils_types);\nXrDebugUtilsMessageTypeFlagsEXT LoaderLogMessageTypesToDebugUtilsMessageTypes(XrLoaderLogMessageTypeFlagBits log_types);\n<|endoftext|>"}
{"text":"\/* SPDX-License-Identifier: LGPL-2.1-or-later *\/\n\/*\n * This file is part of libgpiod.\n *\n * Copyright (C) 2019 Bartosz Golaszewski \n *\/\n\n#include \n#include \n\n#include \"gpio-mockup.hpp\"\n\nusing ::gpiod::test::mockup;\n\nnamespace {\n\nconst ::std::string consumer = \"line-test\";\n\n} \/* namespace *\/\n\nTEST_CASE(\"Global find_line() function works\", \"[line]\")\n{\n\tmockup::probe_guard mockup_chips({ 8, 8, 8, 8, 8 }, mockup::FLAG_NAMED_LINES);\n\n\tauto line = ::gpiod::find_line(\"gpio-mockup-C-5\");\n\tREQUIRE(line.offset() == 5);\n\tREQUIRE(line.name() == \"gpio-mockup-C-5\");\n\tREQUIRE(line.get_chip().label() == \"gpio-mockup-C\");\n}\n\nTEST_CASE(\"Line information can be correctly retrieved\", \"[line]\")\n{\n\tmockup::probe_guard mockup_chips({ 8 }, mockup::FLAG_NAMED_LINES);\n\t::gpiod::chip chip(mockup::instance().chip_name(0));\n\tauto line = chip.get_line(4);\n\n\tSECTION(\"unexported line\")\n\t{\n\t\tREQUIRE(line.offset() == 4);\n\t\tREQUIRE(line.name() == \"gpio-mockup-A-4\");\n\t\tREQUIRE(line.direction() == ::gpiod::line::DIRECTION_INPUT);\n\t\tREQUIRE(line.active_state() == ::gpiod::line::ACTIVE_HIGH);\n\t\tREQUIRE(line.consumer().empty());\n\t\tREQUIRE_FALSE(line.is_requested());\n\t\tREQUIRE_FALSE(line.is_used());\n\t}\n\n\tSECTION(\"exported line\")\n\t{\n\t\t::gpiod::line_request config;\n\n\t\tconfig.consumer = consumer.c_str();\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_OUTPUT;\n\t\tline.request(config);\n\n\t\tREQUIRE(line.offset() == 4);\n\t\tREQUIRE(line.name() == \"gpio-mockup-A-4\");\n\t\tREQUIRE(line.direction() == ::gpiod::line::DIRECTION_OUTPUT);\n\t\tREQUIRE(line.active_state() == ::gpiod::line::ACTIVE_HIGH);\n\t\tREQUIRE(line.is_requested());\n\t\tREQUIRE(line.is_used());\n\t}\n\n\tSECTION(\"exported line with flags\")\n\t{\n\t\t::gpiod::line_request config;\n\n\t\tconfig.consumer = consumer.c_str();\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_OUTPUT;\n\t\tconfig.flags = ::gpiod::line_request::FLAG_ACTIVE_LOW |\n\t\t\t       ::gpiod::line_request::FLAG_OPEN_DRAIN;\n\t\tline.request(config);\n\n\t\tREQUIRE(line.offset() == 4);\n\t\tREQUIRE(line.name() == \"gpio-mockup-A-4\");\n\t\t\/* FIXME Uncomment the line below once this issue is fixed in the kernel. *\/\n\t\t\/\/REQUIRE(line.direction() == ::gpiod::line::DIRECTION_OUTPUT);\n\t\tREQUIRE(line.active_state() == ::gpiod::line::ACTIVE_LOW);\n\t\tREQUIRE(line.is_requested());\n\t\tREQUIRE(line.is_used());\n\t\tREQUIRE(line.is_open_drain());\n\t\tREQUIRE_FALSE(line.is_open_source());\n\t}\n}\n\nTEST_CASE(\"Line bulk object works correctly\", \"[line][bulk]\")\n{\n\tmockup::probe_guard mockup_chips({ 8 }, mockup::FLAG_NAMED_LINES);\n\t::gpiod::chip chip(mockup::instance().chip_name(0));\n\n\tSECTION(\"lines can be added, accessed and cleared\")\n\t{\n\t\t::gpiod::line_bulk lines;\n\n\t\tREQUIRE(lines.empty());\n\n\t\tlines.append(chip.get_line(0));\n\t\tlines.append(chip.get_line(1));\n\t\tlines.append(chip.get_line(2));\n\n\t\tREQUIRE(lines.size() == 3);\n\t\tREQUIRE(lines.get(1).name() == \"gpio-mockup-A-1\");\n\t\tREQUIRE(lines[2].name() == \"gpio-mockup-A-2\");\n\n\t\tlines.clear();\n\n\t\tREQUIRE(lines.empty());\n\t}\n\n\tSECTION(\"bulk iterator works\")\n\t{\n\t\tauto lines = chip.get_all_lines();\n\t\tint count = 0;\n\n\t\tfor (auto& it: lines)\n\t\t\tREQUIRE(it.offset() == count++);\n\n\t\tREQUIRE(count == chip.num_lines());\n\t}\n\n\tSECTION(\"accessing lines out of range throws exception\")\n\t{\n\t\tauto lines = chip.get_all_lines();\n\n\t\tREQUIRE_THROWS_AS(lines.get(11), ::std::out_of_range&);\n\t}\n}\n\nTEST_CASE(\"Line values can be set and read\", \"[line]\")\n{\n\tmockup::probe_guard mockup_chips({ 8 });\n\t::gpiod::chip chip(mockup::instance().chip_name(0));\n\t::gpiod::line_request config;\n\n\tconfig.consumer = consumer.c_str();\n\n\tSECTION(\"get value (single line)\")\n\t{\n\t\tauto line = chip.get_line(3);\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_INPUT;\n\t\tline.request(config);\n\t\tREQUIRE(line.get_value() == 0);\n\t\tmockup::instance().chip_set_pull(0, 3, 1);\n\t\tREQUIRE(line.get_value() == 1);\n\t}\n\n\tSECTION(\"set value (single line)\")\n\t{\n\t\tauto line = chip.get_line(3);\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_OUTPUT;\n\t\tline.request(config);\n\t\tline.set_value(1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 3) == 1);\n\t\tline.set_value(0);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 3) == 0);\n\t}\n\n\tSECTION(\"set value with default value parameter\")\n\t{\n\t\tauto line = chip.get_line(3);\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_OUTPUT;\n\t\tline.request(config, 1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 3) == 1);\n\t}\n\n\tSECTION(\"get multiple values at once\")\n\t{\n\t\tauto lines = chip.get_lines({ 0, 1, 2, 3, 4 });\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_INPUT;\n\t\tlines.request(config);\n\t\tREQUIRE(lines.get_values() == ::std::vector({ 0, 0, 0, 0, 0 }));\n\t\tmockup::instance().chip_set_pull(0, 1, 1);\n\t\tmockup::instance().chip_set_pull(0, 3, 1);\n\t\tmockup::instance().chip_set_pull(0, 4, 1);\n\t\tREQUIRE(lines.get_values() == ::std::vector({ 0, 1, 0, 1, 1 }));\n\t}\n\n\tSECTION(\"set multiple values at once\")\n\t{\n\t\tauto lines = chip.get_lines({ 0, 1, 2, 6, 7 });\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_OUTPUT;\n\t\tlines.request(config);\n\t\tlines.set_values({ 1, 1, 0, 1, 0 });\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 0) == 1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 1) == 1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 2) == 0);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 6) == 1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 7) == 0);\n\t}\n\n\tSECTION(\"set multiple values with default values paramter\")\n\t{\n\t\tauto lines = chip.get_lines({ 1, 2, 4, 6, 7 });\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_OUTPUT;\n\t\tlines.request(config, { 1, 1, 0, 1, 0 });\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 1) == 1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 2) == 1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 4) == 0);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 6) == 1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 7) == 0);\n\t}\n\n\tSECTION(\"get value (single line, active-low\")\n\t{\n\t\tauto line = chip.get_line(4);\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_INPUT;\n\t\tconfig.flags = ::gpiod::line_request::FLAG_ACTIVE_LOW;\n\t\tline.request(config);\n\t\tREQUIRE(line.get_value() == 1);\n\t\tmockup::instance().chip_set_pull(0, 4, 1);\n\t\tREQUIRE(line.get_value() == 0);\n\t}\n\n\tSECTION(\"set value (single line, active-low)\")\n\t{\n\t\tauto line = chip.get_line(3);\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_OUTPUT;\n\t\tconfig.flags = ::gpiod::line_request::FLAG_ACTIVE_LOW;\n\t\tline.request(config);\n\t\tline.set_value(1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 3) == 0);\n\t\tline.set_value(0);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 3) == 1);\n\t}\n}\n\nTEST_CASE(\"Exported line can be released\", \"[line]\")\n{\n\tmockup::probe_guard mockup_chips({ 8 });\n\t::gpiod::chip chip(mockup::instance().chip_name(0));\n\tauto line = chip.get_line(4);\n\t::gpiod::line_request config;\n\n\tconfig.consumer = consumer.c_str();\n\tconfig.request_type = ::gpiod::line_request::DIRECTION_INPUT;\n\n\tline.request(config);\n\n\tREQUIRE(line.is_requested());\n\tREQUIRE(line.get_value() == 0);\n\n\tline.release();\n\n\tREQUIRE_FALSE(line.is_requested());\n\tREQUIRE_THROWS_AS(line.get_value(), ::std::system_error&);\n}\n\nTEST_CASE(\"Uninitialized GPIO line behaves correctly\", \"[line]\")\n{\n\t::gpiod::line line;\n\n\tSECTION(\"uninitialized line is 'false'\")\n\t{\n\t\tREQUIRE_FALSE(line);\n\t}\n\n\tSECTION(\"using uninitialized line throws logic_error\")\n\t{\n\t\tREQUIRE_THROWS_AS(line.name(), ::std::logic_error&);\n\t}\n}\n\nTEST_CASE(\"Uninitialized GPIO line_bulk behaves correctly\", \"[line][bulk]\")\n{\n\t::gpiod::line_bulk bulk;\n\n\tSECTION(\"uninitialized line_bulk is 'false'\")\n\t{\n\t\tREQUIRE_FALSE(bulk);\n\t}\n\n\tSECTION(\"using uninitialized line_bulk throws logic_error\")\n\t{\n\t\tREQUIRE_THROWS_AS(bulk.get(0), ::std::logic_error&);\n\t}\n}\n\nTEST_CASE(\"Cannot request the same line twice\", \"[line]\")\n{\n\tmockup::probe_guard mockup_chips({ 8 });\n\t::gpiod::chip chip(mockup::instance().chip_name(0));\n\t::gpiod::line_request config;\n\n\tconfig.consumer = consumer.c_str();\n\tconfig.request_type = ::gpiod::line_request::DIRECTION_INPUT;\n\n\tSECTION(\"two separate calls to request()\")\n\t{\n\t\tauto line = chip.get_line(3);\n\n\t\tREQUIRE_NOTHROW(line.request(config));\n\t\tREQUIRE_THROWS_AS(line.request(config), ::std::system_error&);\n\t}\n\n\tSECTION(\"request the same line twice in line_bulk\")\n\t{\n\t\t\/*\n\t\t * While a line_bulk object can hold two or more line objects\n\t\t * representing the same line - requesting it will fail.\n\t\t *\/\n\t\tauto lines = chip.get_lines({ 2, 3, 4, 4 });\n\n\t\tREQUIRE_THROWS_AS(lines.request(config), ::std::system_error&);\n\t}\n}\n\nTEST_CASE(\"Cannot get\/set values of unrequested lines\", \"[line]\")\n{\n\tmockup::probe_guard mockup_chips({ 8 });\n\t::gpiod::chip chip(mockup::instance().chip_name(0));\n\tauto line = chip.get_line(3);\n\n\tSECTION(\"get value\")\n\t{\n\t\tREQUIRE_THROWS_AS(line.get_value(), ::std::system_error&);\n\t}\n\n\tSECTION(\"set value\")\n\t{\n\t\tREQUIRE_THROWS_AS(line.set_value(1), ::std::system_error&);\n\t}\n}\n\nTEST_CASE(\"Line objects can be compared\")\n{\n\tmockup::probe_guard mockup_chips({ 8 });\n\t::gpiod::chip chip(mockup::instance().chip_name(0));\n\tauto line1 = chip.get_line(3);\n\tauto line2 = chip.get_line(3);\n\tauto line3 = chip.get_line(4);\n\n\tREQUIRE(line1 == line2);\n\tREQUIRE(line2 != line3);\n}\nbindings: cxx: tests: extend the test case for global find_line()\/* SPDX-License-Identifier: LGPL-2.1-or-later *\/\n\/*\n * This file is part of libgpiod.\n *\n * Copyright (C) 2019 Bartosz Golaszewski \n *\/\n\n#include \n#include \n\n#include \"gpio-mockup.hpp\"\n\nusing ::gpiod::test::mockup;\n\nnamespace {\n\nconst ::std::string consumer = \"line-test\";\n\n} \/* namespace *\/\n\nTEST_CASE(\"Global find_line() function works\", \"[line]\")\n{\n\tmockup::probe_guard mockup_chips({ 8, 8, 8, 8, 8 }, mockup::FLAG_NAMED_LINES);\n\n\tSECTION(\"line found\")\n\t{\n\t\tauto line = ::gpiod::find_line(\"gpio-mockup-C-5\");\n\t\tREQUIRE(line.offset() == 5);\n\t\tREQUIRE(line.name() == \"gpio-mockup-C-5\");\n\t\tREQUIRE(line.get_chip().label() == \"gpio-mockup-C\");\n\t}\n\n\tSECTION(\"line not found\")\n\t{\n\t\tauto line = ::gpiod::find_line(\"nonexistent-line\");\n\t\tREQUIRE_FALSE(line);\n\t}\n}\n\nTEST_CASE(\"Line information can be correctly retrieved\", \"[line]\")\n{\n\tmockup::probe_guard mockup_chips({ 8 }, mockup::FLAG_NAMED_LINES);\n\t::gpiod::chip chip(mockup::instance().chip_name(0));\n\tauto line = chip.get_line(4);\n\n\tSECTION(\"unexported line\")\n\t{\n\t\tREQUIRE(line.offset() == 4);\n\t\tREQUIRE(line.name() == \"gpio-mockup-A-4\");\n\t\tREQUIRE(line.direction() == ::gpiod::line::DIRECTION_INPUT);\n\t\tREQUIRE(line.active_state() == ::gpiod::line::ACTIVE_HIGH);\n\t\tREQUIRE(line.consumer().empty());\n\t\tREQUIRE_FALSE(line.is_requested());\n\t\tREQUIRE_FALSE(line.is_used());\n\t}\n\n\tSECTION(\"exported line\")\n\t{\n\t\t::gpiod::line_request config;\n\n\t\tconfig.consumer = consumer.c_str();\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_OUTPUT;\n\t\tline.request(config);\n\n\t\tREQUIRE(line.offset() == 4);\n\t\tREQUIRE(line.name() == \"gpio-mockup-A-4\");\n\t\tREQUIRE(line.direction() == ::gpiod::line::DIRECTION_OUTPUT);\n\t\tREQUIRE(line.active_state() == ::gpiod::line::ACTIVE_HIGH);\n\t\tREQUIRE(line.is_requested());\n\t\tREQUIRE(line.is_used());\n\t}\n\n\tSECTION(\"exported line with flags\")\n\t{\n\t\t::gpiod::line_request config;\n\n\t\tconfig.consumer = consumer.c_str();\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_OUTPUT;\n\t\tconfig.flags = ::gpiod::line_request::FLAG_ACTIVE_LOW |\n\t\t\t       ::gpiod::line_request::FLAG_OPEN_DRAIN;\n\t\tline.request(config);\n\n\t\tREQUIRE(line.offset() == 4);\n\t\tREQUIRE(line.name() == \"gpio-mockup-A-4\");\n\t\t\/* FIXME Uncomment the line below once this issue is fixed in the kernel. *\/\n\t\t\/\/REQUIRE(line.direction() == ::gpiod::line::DIRECTION_OUTPUT);\n\t\tREQUIRE(line.active_state() == ::gpiod::line::ACTIVE_LOW);\n\t\tREQUIRE(line.is_requested());\n\t\tREQUIRE(line.is_used());\n\t\tREQUIRE(line.is_open_drain());\n\t\tREQUIRE_FALSE(line.is_open_source());\n\t}\n}\n\nTEST_CASE(\"Line bulk object works correctly\", \"[line][bulk]\")\n{\n\tmockup::probe_guard mockup_chips({ 8 }, mockup::FLAG_NAMED_LINES);\n\t::gpiod::chip chip(mockup::instance().chip_name(0));\n\n\tSECTION(\"lines can be added, accessed and cleared\")\n\t{\n\t\t::gpiod::line_bulk lines;\n\n\t\tREQUIRE(lines.empty());\n\n\t\tlines.append(chip.get_line(0));\n\t\tlines.append(chip.get_line(1));\n\t\tlines.append(chip.get_line(2));\n\n\t\tREQUIRE(lines.size() == 3);\n\t\tREQUIRE(lines.get(1).name() == \"gpio-mockup-A-1\");\n\t\tREQUIRE(lines[2].name() == \"gpio-mockup-A-2\");\n\n\t\tlines.clear();\n\n\t\tREQUIRE(lines.empty());\n\t}\n\n\tSECTION(\"bulk iterator works\")\n\t{\n\t\tauto lines = chip.get_all_lines();\n\t\tint count = 0;\n\n\t\tfor (auto& it: lines)\n\t\t\tREQUIRE(it.offset() == count++);\n\n\t\tREQUIRE(count == chip.num_lines());\n\t}\n\n\tSECTION(\"accessing lines out of range throws exception\")\n\t{\n\t\tauto lines = chip.get_all_lines();\n\n\t\tREQUIRE_THROWS_AS(lines.get(11), ::std::out_of_range&);\n\t}\n}\n\nTEST_CASE(\"Line values can be set and read\", \"[line]\")\n{\n\tmockup::probe_guard mockup_chips({ 8 });\n\t::gpiod::chip chip(mockup::instance().chip_name(0));\n\t::gpiod::line_request config;\n\n\tconfig.consumer = consumer.c_str();\n\n\tSECTION(\"get value (single line)\")\n\t{\n\t\tauto line = chip.get_line(3);\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_INPUT;\n\t\tline.request(config);\n\t\tREQUIRE(line.get_value() == 0);\n\t\tmockup::instance().chip_set_pull(0, 3, 1);\n\t\tREQUIRE(line.get_value() == 1);\n\t}\n\n\tSECTION(\"set value (single line)\")\n\t{\n\t\tauto line = chip.get_line(3);\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_OUTPUT;\n\t\tline.request(config);\n\t\tline.set_value(1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 3) == 1);\n\t\tline.set_value(0);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 3) == 0);\n\t}\n\n\tSECTION(\"set value with default value parameter\")\n\t{\n\t\tauto line = chip.get_line(3);\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_OUTPUT;\n\t\tline.request(config, 1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 3) == 1);\n\t}\n\n\tSECTION(\"get multiple values at once\")\n\t{\n\t\tauto lines = chip.get_lines({ 0, 1, 2, 3, 4 });\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_INPUT;\n\t\tlines.request(config);\n\t\tREQUIRE(lines.get_values() == ::std::vector({ 0, 0, 0, 0, 0 }));\n\t\tmockup::instance().chip_set_pull(0, 1, 1);\n\t\tmockup::instance().chip_set_pull(0, 3, 1);\n\t\tmockup::instance().chip_set_pull(0, 4, 1);\n\t\tREQUIRE(lines.get_values() == ::std::vector({ 0, 1, 0, 1, 1 }));\n\t}\n\n\tSECTION(\"set multiple values at once\")\n\t{\n\t\tauto lines = chip.get_lines({ 0, 1, 2, 6, 7 });\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_OUTPUT;\n\t\tlines.request(config);\n\t\tlines.set_values({ 1, 1, 0, 1, 0 });\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 0) == 1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 1) == 1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 2) == 0);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 6) == 1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 7) == 0);\n\t}\n\n\tSECTION(\"set multiple values with default values paramter\")\n\t{\n\t\tauto lines = chip.get_lines({ 1, 2, 4, 6, 7 });\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_OUTPUT;\n\t\tlines.request(config, { 1, 1, 0, 1, 0 });\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 1) == 1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 2) == 1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 4) == 0);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 6) == 1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 7) == 0);\n\t}\n\n\tSECTION(\"get value (single line, active-low\")\n\t{\n\t\tauto line = chip.get_line(4);\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_INPUT;\n\t\tconfig.flags = ::gpiod::line_request::FLAG_ACTIVE_LOW;\n\t\tline.request(config);\n\t\tREQUIRE(line.get_value() == 1);\n\t\tmockup::instance().chip_set_pull(0, 4, 1);\n\t\tREQUIRE(line.get_value() == 0);\n\t}\n\n\tSECTION(\"set value (single line, active-low)\")\n\t{\n\t\tauto line = chip.get_line(3);\n\t\tconfig.request_type = ::gpiod::line_request::DIRECTION_OUTPUT;\n\t\tconfig.flags = ::gpiod::line_request::FLAG_ACTIVE_LOW;\n\t\tline.request(config);\n\t\tline.set_value(1);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 3) == 0);\n\t\tline.set_value(0);\n\t\tREQUIRE(mockup::instance().chip_get_value(0, 3) == 1);\n\t}\n}\n\nTEST_CASE(\"Exported line can be released\", \"[line]\")\n{\n\tmockup::probe_guard mockup_chips({ 8 });\n\t::gpiod::chip chip(mockup::instance().chip_name(0));\n\tauto line = chip.get_line(4);\n\t::gpiod::line_request config;\n\n\tconfig.consumer = consumer.c_str();\n\tconfig.request_type = ::gpiod::line_request::DIRECTION_INPUT;\n\n\tline.request(config);\n\n\tREQUIRE(line.is_requested());\n\tREQUIRE(line.get_value() == 0);\n\n\tline.release();\n\n\tREQUIRE_FALSE(line.is_requested());\n\tREQUIRE_THROWS_AS(line.get_value(), ::std::system_error&);\n}\n\nTEST_CASE(\"Uninitialized GPIO line behaves correctly\", \"[line]\")\n{\n\t::gpiod::line line;\n\n\tSECTION(\"uninitialized line is 'false'\")\n\t{\n\t\tREQUIRE_FALSE(line);\n\t}\n\n\tSECTION(\"using uninitialized line throws logic_error\")\n\t{\n\t\tREQUIRE_THROWS_AS(line.name(), ::std::logic_error&);\n\t}\n}\n\nTEST_CASE(\"Uninitialized GPIO line_bulk behaves correctly\", \"[line][bulk]\")\n{\n\t::gpiod::line_bulk bulk;\n\n\tSECTION(\"uninitialized line_bulk is 'false'\")\n\t{\n\t\tREQUIRE_FALSE(bulk);\n\t}\n\n\tSECTION(\"using uninitialized line_bulk throws logic_error\")\n\t{\n\t\tREQUIRE_THROWS_AS(bulk.get(0), ::std::logic_error&);\n\t}\n}\n\nTEST_CASE(\"Cannot request the same line twice\", \"[line]\")\n{\n\tmockup::probe_guard mockup_chips({ 8 });\n\t::gpiod::chip chip(mockup::instance().chip_name(0));\n\t::gpiod::line_request config;\n\n\tconfig.consumer = consumer.c_str();\n\tconfig.request_type = ::gpiod::line_request::DIRECTION_INPUT;\n\n\tSECTION(\"two separate calls to request()\")\n\t{\n\t\tauto line = chip.get_line(3);\n\n\t\tREQUIRE_NOTHROW(line.request(config));\n\t\tREQUIRE_THROWS_AS(line.request(config), ::std::system_error&);\n\t}\n\n\tSECTION(\"request the same line twice in line_bulk\")\n\t{\n\t\t\/*\n\t\t * While a line_bulk object can hold two or more line objects\n\t\t * representing the same line - requesting it will fail.\n\t\t *\/\n\t\tauto lines = chip.get_lines({ 2, 3, 4, 4 });\n\n\t\tREQUIRE_THROWS_AS(lines.request(config), ::std::system_error&);\n\t}\n}\n\nTEST_CASE(\"Cannot get\/set values of unrequested lines\", \"[line]\")\n{\n\tmockup::probe_guard mockup_chips({ 8 });\n\t::gpiod::chip chip(mockup::instance().chip_name(0));\n\tauto line = chip.get_line(3);\n\n\tSECTION(\"get value\")\n\t{\n\t\tREQUIRE_THROWS_AS(line.get_value(), ::std::system_error&);\n\t}\n\n\tSECTION(\"set value\")\n\t{\n\t\tREQUIRE_THROWS_AS(line.set_value(1), ::std::system_error&);\n\t}\n}\n\nTEST_CASE(\"Line objects can be compared\")\n{\n\tmockup::probe_guard mockup_chips({ 8 });\n\t::gpiod::chip chip(mockup::instance().chip_name(0));\n\tauto line1 = chip.get_line(3);\n\tauto line2 = chip.get_line(3);\n\tauto line3 = chip.get_line(4);\n\n\tREQUIRE(line1 == line2);\n\tREQUIRE(line2 != line3);\n}\n<|endoftext|>"}
{"text":"\/*\nCopyright (C) 2016,2017 Rodrigo Jose Hernandez Cordoba\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"PngImage.h\"\n\nnamespace AeonGames\n{\n    struct png_read_memory_struct\n    {\n        uint8_t* buffer;\n        uint8_t* pointer;\n        png_size_t size;\n    };\n\n    static void png_read_memory_data ( png_structp png_ptr, png_bytep data, png_size_t length )\n    {\n        if ( png_ptr == nullptr )\n        {\n            std::cout << __FUNCTION__ << \" got NULL png_ptr pointer.\" << std::endl;\n            png_warning ( png_ptr, \"Got NULL png_ptr pointer.\" );\n            return;\n        }\n        png_read_memory_struct* read_struct = static_cast ( png_get_io_ptr ( png_ptr ) );\n        \/\/ Clip lenght not to get passed the end of the buffer.\n        png_size_t real_length = std::min ( ( ( read_struct->buffer + read_struct->size ) - read_struct->pointer ), length );\n        if ( length < 1 )\n        {\n            std::cout << __FUNCTION__ << \" tried to read past end of file\" << std::endl;\n            png_warning ( png_ptr, \"Tried to read past end of file\" );\n            return;\n        }\n        memcpy ( data, read_struct->pointer, real_length );\n        if ( real_length < length )\n        {\n            std::cout << __FUNCTION__ << \" Returning \" << real_length << \" bytes instead of requested \" << length << \" because of end of memory\" << std::endl;\n            memset ( data + real_length, 0, length - real_length );\n        }\n        read_struct->pointer += real_length;\n    }\n\n    PngImage::PngImage ( const std::string & aFileName )\n    {\n        \/\/--------------------------------------------------------\n        \/\/ File loading code\n        std::ifstream file ( aFileName, std::ios::binary );\n        std::vector buffer ( (\n                                          std::istreambuf_iterator ( file ) ),\n                                      ( std::istreambuf_iterator() ) );\n        file.close();\n        \/\/--------------------------------------------------------\n\n        if ( png_sig_cmp ( buffer.data(), 0, 8 ) == 0 )\n        {\n            png_structp png_ptr =\n                png_create_read_struct ( PNG_LIBPNG_VER_STRING,\n                                         nullptr, nullptr, nullptr );\n            if ( png_ptr == nullptr )\n            {\n                throw std::runtime_error ( \"png_create_read_struct failed.\" );\n            }\n            png_infop info_ptr = png_create_info_struct ( png_ptr );\n            if ( info_ptr == nullptr )\n            {\n                throw std::runtime_error ( \"png_create_info_struct failed.\" );\n            }\n            if ( setjmp ( png_jmpbuf ( png_ptr ) ) )\n            {\n                throw std::runtime_error ( \"Error during init_io.\" );\n            }\n            png_read_memory_struct read_memory_struct = {buffer.data(), buffer.data() + 8,\n                                                         static_cast ( buffer.size() *sizeof ( uint8_t ) )\n                                                        };\n            png_set_read_fn ( png_ptr, &read_memory_struct, png_read_memory_data );\n            png_set_sig_bytes ( png_ptr, 8 );\n\n            png_read_info ( png_ptr, info_ptr );\n\n            mWidth = png_get_image_width ( png_ptr, info_ptr );\n            mHeight = png_get_image_height ( png_ptr, info_ptr );\n            png_byte color_type = png_get_color_type ( png_ptr, info_ptr );\n            png_byte bit_depth = png_get_bit_depth ( png_ptr, info_ptr );\n\n            if ( ( color_type == PNG_COLOR_TYPE_RGB ) || ( color_type == PNG_COLOR_TYPE_RGBA ) )\n            {\n                mFormat = ( color_type == PNG_COLOR_TYPE_RGB ) ? ImageFormat::RGB : ImageFormat::RGBA;\n                mType   = ( bit_depth == 8 ) ? ImageType::UNSIGNED_BYTE : ImageType::UNSIGNED_SHORT;\n            }\n            else\n            {\n                throw std::runtime_error ( \"PNG image color type not supported...yet\" );\n            }\n\n            \/*int number_of_passes =*\/ png_set_interlace_handling ( png_ptr );\n            png_read_update_info ( png_ptr, info_ptr );\n\n            \/* read file *\/\n            if ( setjmp ( png_jmpbuf ( png_ptr ) ) )\n            {\n                throw std::runtime_error ( \"Error during read_image.\" );\n            }\n            \/\/ --------------------------------------\n            \/\/ This has to be changed to create a single buffer to which all row_pointers point at.\n            \/\/ See http:\/\/www.piko3d.com\/tutorials\/libpng-tutorial-loading-png-files-from-streams\n            png_size_t rowbytes = png_get_rowbytes ( png_ptr, info_ptr );\n            std::vector row_pointers ( sizeof ( png_bytep ) * mHeight );\n            mData.resize ( rowbytes * mHeight );\n            for ( png_uint_32 y = 0; y < mHeight; ++y )\n            {\n                row_pointers[y] = mData.data() + ( rowbytes * y );\n            }\n            \/\/ --------------------------------------\n            png_read_image ( png_ptr, row_pointers.data() );\n            png_destroy_read_struct ( &png_ptr, &info_ptr, ( png_infopp ) nullptr );\n        }\n        else\n        {\n            throw std::runtime_error ( \"Image format not supported...yet\" );\n        }\n    }\n    PngImage::~PngImage()\n        = default;\n    uint32_t PngImage::Width() const\n    {\n        return mWidth;\n    }\n    uint32_t PngImage::Height() const\n    {\n        return mHeight;\n    }\n    Image::ImageFormat PngImage::Format() const\n    {\n        return mFormat;\n    }\n    Image::ImageType PngImage::Type() const\n    {\n        return mType;\n    }\n    const uint8_t* PngImage::Data() const\n    {\n        return mData.data();\n    }\n    const size_t PngImage::DataSize() const\n    {\n        return mData.size();\n    }\n}\nAdded exception check when opening PNG images.\/*\nCopyright (C) 2016,2017 Rodrigo Jose Hernandez Cordoba\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"PngImage.h\"\n\nnamespace AeonGames\n{\n    struct png_read_memory_struct\n    {\n        uint8_t* buffer;\n        uint8_t* pointer;\n        png_size_t size;\n    };\n\n    static void png_read_memory_data ( png_structp png_ptr, png_bytep data, png_size_t length )\n    {\n        if ( png_ptr == nullptr )\n        {\n            std::cout << __FUNCTION__ << \" got NULL png_ptr pointer.\" << std::endl;\n            png_warning ( png_ptr, \"Got NULL png_ptr pointer.\" );\n            return;\n        }\n        png_read_memory_struct* read_struct = static_cast ( png_get_io_ptr ( png_ptr ) );\n        \/\/ Clip lenght not to get passed the end of the buffer.\n        png_size_t real_length = std::min ( ( ( read_struct->buffer + read_struct->size ) - read_struct->pointer ), length );\n        if ( length < 1 )\n        {\n            std::cout << __FUNCTION__ << \" tried to read past end of file\" << std::endl;\n            png_warning ( png_ptr, \"Tried to read past end of file\" );\n            return;\n        }\n        memcpy ( data, read_struct->pointer, real_length );\n        if ( real_length < length )\n        {\n            std::cout << __FUNCTION__ << \" Returning \" << real_length << \" bytes instead of requested \" << length << \" because of end of memory\" << std::endl;\n            memset ( data + real_length, 0, length - real_length );\n        }\n        read_struct->pointer += real_length;\n    }\n\n    PngImage::PngImage ( const std::string & aFileName )\n    {\n        \/\/--------------------------------------------------------\n        \/\/ File loading code\n        std::ifstream file;\n        file.exceptions ( std::ifstream::failbit | std::ifstream::badbit );\n        file.open ( aFileName, std::ios::binary );\n        std::vector buffer ( (\n                                          std::istreambuf_iterator ( file ) ),\n                                      ( std::istreambuf_iterator() ) );\n        file.close();\n        \/\/--------------------------------------------------------\n\n        if ( png_sig_cmp ( buffer.data(), 0, 8 ) == 0 )\n        {\n            png_structp png_ptr =\n                png_create_read_struct ( PNG_LIBPNG_VER_STRING,\n                                         nullptr, nullptr, nullptr );\n            if ( png_ptr == nullptr )\n            {\n                throw std::runtime_error ( \"png_create_read_struct failed.\" );\n            }\n            png_infop info_ptr = png_create_info_struct ( png_ptr );\n            if ( info_ptr == nullptr )\n            {\n                throw std::runtime_error ( \"png_create_info_struct failed.\" );\n            }\n            if ( setjmp ( png_jmpbuf ( png_ptr ) ) )\n            {\n                throw std::runtime_error ( \"Error during init_io.\" );\n            }\n            png_read_memory_struct read_memory_struct = {buffer.data(), buffer.data() + 8,\n                                                         static_cast ( buffer.size() *sizeof ( uint8_t ) )\n                                                        };\n            png_set_read_fn ( png_ptr, &read_memory_struct, png_read_memory_data );\n            png_set_sig_bytes ( png_ptr, 8 );\n\n            png_read_info ( png_ptr, info_ptr );\n\n            mWidth = png_get_image_width ( png_ptr, info_ptr );\n            mHeight = png_get_image_height ( png_ptr, info_ptr );\n            png_byte color_type = png_get_color_type ( png_ptr, info_ptr );\n            png_byte bit_depth = png_get_bit_depth ( png_ptr, info_ptr );\n\n            if ( ( color_type == PNG_COLOR_TYPE_RGB ) || ( color_type == PNG_COLOR_TYPE_RGBA ) )\n            {\n                mFormat = ( color_type == PNG_COLOR_TYPE_RGB ) ? ImageFormat::RGB : ImageFormat::RGBA;\n                mType   = ( bit_depth == 8 ) ? ImageType::UNSIGNED_BYTE : ImageType::UNSIGNED_SHORT;\n            }\n            else\n            {\n                throw std::runtime_error ( \"PNG image color type not supported...yet\" );\n            }\n\n            \/*int number_of_passes =*\/ png_set_interlace_handling ( png_ptr );\n            png_read_update_info ( png_ptr, info_ptr );\n\n            \/* read file *\/\n            if ( setjmp ( png_jmpbuf ( png_ptr ) ) )\n            {\n                throw std::runtime_error ( \"Error during read_image.\" );\n            }\n            \/\/ --------------------------------------\n            \/\/ This has to be changed to create a single buffer to which all row_pointers point at.\n            \/\/ See http:\/\/www.piko3d.com\/tutorials\/libpng-tutorial-loading-png-files-from-streams\n            png_size_t rowbytes = png_get_rowbytes ( png_ptr, info_ptr );\n            std::vector row_pointers ( sizeof ( png_bytep ) * mHeight );\n            mData.resize ( rowbytes * mHeight );\n            for ( png_uint_32 y = 0; y < mHeight; ++y )\n            {\n                row_pointers[y] = mData.data() + ( rowbytes * y );\n            }\n            \/\/ --------------------------------------\n            png_read_image ( png_ptr, row_pointers.data() );\n            png_destroy_read_struct ( &png_ptr, &info_ptr, ( png_infopp ) nullptr );\n        }\n        else\n        {\n            throw std::runtime_error ( \"Image format not supported...yet\" );\n        }\n    }\n    PngImage::~PngImage()\n        = default;\n    uint32_t PngImage::Width() const\n    {\n        return mWidth;\n    }\n    uint32_t PngImage::Height() const\n    {\n        return mHeight;\n    }\n    Image::ImageFormat PngImage::Format() const\n    {\n        return mFormat;\n    }\n    Image::ImageType PngImage::Type() const\n    {\n        return mType;\n    }\n    const uint8_t* PngImage::Data() const\n    {\n        return mData.data();\n    }\n    const size_t PngImage::DataSize() const\n    {\n        return mData.size();\n    }\n}\n<|endoftext|>"}
{"text":"\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: aryattrs.cxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: vg $ $Date: 2007-09-18 13:49:59 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#include \n#include \"aryattrs.hxx\"\n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"strconst.hxx\"\n\n\n\n\/\/********************       HtmlDisplay_Impl        *********************\/\/\n\n\n\nconst char *\nGet_ClassTypeKey( const ary::cpp::Class & i_rClass )\n{\n    return i_rClass.ClassKey() == ary::cpp::CK_class\n                            ?   C_sHFTypeTitle_Class\n                            :   i_rClass.ClassKey() == ary::cpp::CK_struct\n                                    ?   C_sHFTypeTitle_Struct\n                                    :   C_sHFTypeTitle_Union;\n\n}\n\nconst char *\nGet_TypeKey( const ary::CodeEntity & i_rCe )\n{\n    if ( i_rCe.RC() == ary::cpp::Class::RC_() )\n    {\n        csv_assert( dynamic_cast< const ary::cpp::Class* >(&i_rCe) != 0  );\n        return Get_ClassTypeKey(\n                    static_cast< const ary::cpp::Class& >(i_rCe) );\n    }\n    if ( i_rCe.RC() == ary::cpp::Enum::RC_() )\n    {\n         return \"enum\";\n    }\n    return \"\";\n}\n\nbool\nCe_IsInternal( const ary::CodeEntity & i_rCe )\n{\n    return NOT i_rCe.IsVisible();\n}\n\nconst char *\nNamespace_DisplayName( const ary::cpp::Namespace & i_rNsp )\n{\n     return i_rNsp.Depth() > 0\n                ?   i_rNsp.LocalName().c_str()\n                :   \"GlobalNamespace of C++\";\n}\n\nconst char *\nTypeText( ary::Tid                      i_nId,\n          const ary::cpp::DisplayGate & i_rAryGate )\n{\n     static StreamStr sResult(2000);\n    sResult.seekp(0);\n    i_rAryGate.Get_TypeText(sResult, i_nId);\n\n    return sResult.c_str();\n}\n\nconst char *\nSyntaxText_PreName( const ary::cpp::Function &      i_rFunction,\n                    const ary::cpp::DisplayGate &   i_rAryGate )\n{\n    static StreamStr  sResult( 150 );\n    sResult.seekp(0);\n\n    \/\/ write pre-name:\n    const ary::cpp::FunctionFlags & rFlags = i_rFunction.Flags();\n    if ( rFlags.IsStaticLocal() OR rFlags.IsStaticMember() )\n        sResult << \"static \";\n    if ( rFlags.IsExplicit() )\n        sResult << \"explicit \";\n    if ( rFlags.IsMutable() )\n        sResult << \"mutable \";\n    if ( i_rFunction.Virtuality() != ary::cpp::VIRTUAL_none )\n        sResult << \"virtual \";\n    i_rAryGate.Get_TypeText( sResult, i_rFunction.ReturnType() );\n    sResult << \" \";\n\n    return sResult.c_str();\n}\n\nconst char *\nSyntaxText_PostName( const ary::cpp::Function &     i_rFunction,\n                     const ary::cpp::DisplayGate &  i_rAryGate )\n{\n    static StreamStr  sResult( 850 );\n    sResult.seekp(0);\n\n    \/\/ parameters and con_vol\n    i_rAryGate.Get_SignatureText( sResult, i_rFunction.Signature(), &i_rFunction.ParamInfos() );\n\n    \/\/ write Exceptions:\n    const std::vector< ary::Tid > *\n            pThrow = i_rFunction.Exceptions();\n    if ( pThrow)\n    {\n\n        std::vector< ary::Tid >::const_iterator\n                it = pThrow->begin();\n        std::vector< ary::Tid >::const_iterator\n                it_end = pThrow->end();\n\n        if (it != it_end)\n        {\n            sResult << \" throw( \";\n            i_rAryGate.Get_TypeText(sResult, *it);\n\n            for ( ++it; it != it_end; ++it )\n            {\n                sResult << \", \";\n                i_rAryGate.Get_TypeText(sResult, *it);\n            }\n            sResult << \" )\";\n        }\n        else\n        {\n            sResult << \" throw( )\";\n        }\n    }   \/\/ endif \/\/ pThrow\n\n    \/\/ abstractness:\n    if ( i_rFunction.Virtuality() == ary::cpp::VIRTUAL_abstract )\n        sResult << \" = 0\";\n\n    \/\/ finish:\n    sResult << \";\";\n\n    return sResult.c_str();\n}\n\nbool\nGet_TypeText( const char * &                o_rPreName,\n              const char * &                o_rName,\n              const char * &                o_rPostName,\n              ary::Tid                      i_nTypeid,\n              const ary::cpp::DisplayGate & i_rAryGate )\n{\n    static StreamStr       sResult_PreName(250);\n    static StreamStr       sResult_Name(250);\n    static StreamStr       sResult_PostName(250);\n\n    sResult_PreName.seekp(0);\n    sResult_Name.seekp(0);\n    sResult_PostName.seekp(0);\n\n    bool    ret = i_rAryGate.Get_TypeText(\n                                sResult_PreName,\n                                sResult_Name,\n                                sResult_PostName,\n                                i_nTypeid );\n    if ( sResult_PreName.tellp() > 0 )\n    {\n        char cLast = *( sResult_PreName.c_str() + (sResult_PreName.tellp() - 1) );\n        if (cLast != ':' AND cLast != ' ')\n            sResult_PreName << \" \";\n    }\n\n\n    if (ret)\n    {\n        o_rPreName  = sResult_PreName.c_str();\n        o_rName     = sResult_Name.c_str();\n        o_rPostName = sResult_PostName.c_str();\n    }\n    else\n    {\n        o_rPreName  =  o_rName =  o_rPostName = \"\";\n    }\n    return ret;\n}\n\n\n\n\n\/\/*********************         FunctionParam_Iterator      *****************\/\/\n\n\nFunctionParam_Iterator::FunctionParam_Iterator()\n    :   \/\/ itTypes\n        \/\/ itTypes_end\n        \/\/ itNames_andMore\n        \/\/ itNames_andMore_end\n        eConVol(ary::cpp::CONVOL_none)\n{\n    static std::vector    aTypesNull_;\n    static StringVector             aNamesNull_;\n\n    itTypes = itTypes_end = aTypesNull_.end();\n    itNames_andMore = itNames_andMore_end = aNamesNull_.end();\n}\n\nFunctionParam_Iterator::~FunctionParam_Iterator()\n{\n}\n\nFunctionParam_Iterator &\nFunctionParam_Iterator::operator++()\n{\n    if ( IsValid() )\n    {\n        ++itTypes;\n        ++itNames_andMore;\n    }\n    return *this;\n}\n\nvoid\nFunctionParam_Iterator::Assign( const ary::cpp::Function &      i_rFunction,\n                                const ary::cpp::DisplayGate &   i_rAryGate )\n{\n    const ary::cpp::OperationSignature *\n        pSigna = i_rAryGate.Find_Signature( i_rFunction.Signature() );\n    if (pSigna == 0 )\n        return;\n\n    const std::vector &\n        rTypes = pSigna->Parameters();\n    const StringVector &\n        rNames = i_rFunction.ParamInfos();\n\n    if ( rTypes.size() != rNames.size() OR rTypes.size() == 0 )\n        return;\n\n    itTypes     = rTypes.begin();\n    itTypes_end = rTypes.end();\n    itNames_andMore     = rNames.begin();\n    itNames_andMore_end = rNames.end();\n\n    eConVol = pSigna->ConVol();\n}\n\n\nINTEGRATION: CWS adc18 (1.6.2); FILE MERGED 2007\/10\/19 13:03:21 np 1.6.2.3: #i81775# 2007\/10\/19 11:50:49 np 1.6.2.2: #i81775# 2007\/10\/18 15:23:12 np 1.6.2.1: #i81775#\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: aryattrs.cxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: hr $ $Date: 2007-11-02 16:23:27 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#include \n#include \"aryattrs.hxx\"\n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"strconst.hxx\"\n\n\n\n\n\/\/********************       HtmlDisplay_Impl        *********************\/\/\n\nconst char *\nGet_ClassTypeKey( const ary::cpp::Class & i_rClass )\n{\n    return i_rClass.ClassKey() == ary::cpp::CK_class\n                            ?   C_sHFTypeTitle_Class\n                            :   i_rClass.ClassKey() == ary::cpp::CK_struct\n                                    ?   C_sHFTypeTitle_Struct\n                                    :   C_sHFTypeTitle_Union;\n\n}\n\nconst char *\nGet_TypeKey( const ary::cpp::CodeEntity & i_rCe )\n{\n    if ( ary::is_type(i_rCe) )\n    {\n        return Get_ClassTypeKey(\n                    ary::ary_cast(i_rCe) );\n    }\n    if ( ary::is_type(i_rCe) )\n    {\n         return \"enum\";\n    }\n    return \"\";\n}\n\nbool\nCe_IsInternal( const ary::cpp::CodeEntity & i_rCe )\n{\n    return NOT i_rCe.IsVisible();\n}\n\nconst char *\nNamespace_DisplayName( const ary::cpp::Namespace & i_rNsp )\n{\n     return i_rNsp.Depth() > 0\n                ?   i_rNsp.LocalName().c_str()\n                :   \"GlobalNamespace of C++\";\n}\n\nconst char *\nTypeText( ary::cpp::Type_id         i_nId,\n          const ary::cpp::Gate &    i_rAryGate )\n{\n     static StreamStr sResult(2000);\n    sResult.seekp(0);\n    i_rAryGate.Types().Get_TypeText(sResult, i_nId);\n\n    return sResult.c_str();\n}\n\nconst char *\nSyntaxText_PreName( const ary::cpp::Function &      i_rFunction,\n                    const ary::cpp::Gate &   i_rAryGate )\n{\n    static StreamStr  sResult( 150 );\n    sResult.seekp(0);\n\n    \/\/ write pre-name:\n    const ary::cpp::FunctionFlags & rFlags = i_rFunction.Flags();\n    if ( rFlags.IsStaticLocal() OR rFlags.IsStaticMember() )\n        sResult << \"static \";\n    if ( rFlags.IsExplicit() )\n        sResult << \"explicit \";\n    if ( rFlags.IsMutable() )\n        sResult << \"mutable \";\n    if ( i_rFunction.Virtuality() != ary::cpp::VIRTUAL_none )\n        sResult << \"virtual \";\n    i_rAryGate.Types().Get_TypeText( sResult, i_rFunction.ReturnType() );\n    sResult << \" \";\n\n    return sResult.c_str();\n}\n\nconst char *\nSyntaxText_PostName( const ary::cpp::Function &     i_rFunction,\n                     const ary::cpp::Gate &  i_rAryGate )\n{\n    static StreamStr  sResult( 850 );\n    sResult.seekp(0);\n\n    \/\/ parameters and con_vol\n    i_rAryGate.Ces().Get_SignatureText( sResult, i_rFunction.Signature(), &i_rFunction.ParamInfos() );\n\n    \/\/ write Exceptions:\n    const std::vector< ary::cpp::Type_id > *\n            pThrow = i_rFunction.Exceptions();\n    if ( pThrow)\n    {\n\n        std::vector< ary::cpp::Type_id >::const_iterator\n                it = pThrow->begin();\n        std::vector< ary::cpp::Type_id >::const_iterator\n                it_end = pThrow->end();\n\n        if (it != it_end)\n        {\n            sResult << \" throw( \";\n            i_rAryGate.Types().Get_TypeText(sResult, *it);\n\n            for ( ++it; it != it_end; ++it )\n            {\n                sResult << \", \";\n                i_rAryGate.Types().Get_TypeText(sResult, *it);\n            }\n            sResult << \" )\";\n        }\n        else\n        {\n            sResult << \" throw( )\";\n        }\n    }   \/\/ endif \/\/ pThrow\n\n    \/\/ abstractness:\n    if ( i_rFunction.Virtuality() == ary::cpp::VIRTUAL_abstract )\n        sResult << \" = 0\";\n\n    \/\/ finish:\n    sResult << \";\";\n\n    return sResult.c_str();\n}\n\nbool\nGet_TypeText( const char * &                o_rPreName,\n              const char * &                o_rName,\n              const char * &                o_rPostName,\n              ary::cpp::Type_id             i_nTypeid,\n              const ary::cpp::Gate & i_rAryGate )\n{\n    static StreamStr       sResult_PreName(250);\n    static StreamStr       sResult_Name(250);\n    static StreamStr       sResult_PostName(250);\n\n    sResult_PreName.seekp(0);\n    sResult_Name.seekp(0);\n    sResult_PostName.seekp(0);\n\n    bool    ret = i_rAryGate.Types().Get_TypeText(\n                                sResult_PreName,\n                                sResult_Name,\n                                sResult_PostName,\n                                i_nTypeid );\n    if ( sResult_PreName.tellp() > 0 )\n    {\n        char cLast = *( sResult_PreName.c_str() + (sResult_PreName.tellp() - 1) );\n        if (cLast != ':' AND cLast != ' ')\n            sResult_PreName << \" \";\n    }\n\n\n    if (ret)\n    {\n        o_rPreName  = sResult_PreName.c_str();\n        o_rName     = sResult_Name.c_str();\n        o_rPostName = sResult_PostName.c_str();\n    }\n    else\n    {\n        o_rPreName  =  o_rName =  o_rPostName = \"\";\n    }\n    return ret;\n}\n\n\n\n\n\/\/*********************         FunctionParam_Iterator      *****************\/\/\n\n\nFunctionParam_Iterator::FunctionParam_Iterator()\n    :   \/\/ itTypes\n        \/\/ itTypes_end\n        \/\/ itNames_andMore\n        \/\/ itNames_andMore_end\n        eConVol(ary::cpp::CONVOL_none)\n{\n    static std::vector   aTypesNull_;\n    static StringVector                     aNamesNull_;\n\n    itTypes = itTypes_end = aTypesNull_.end();\n    itNames_andMore = itNames_andMore_end = aNamesNull_.end();\n}\n\nFunctionParam_Iterator::~FunctionParam_Iterator()\n{\n}\n\nFunctionParam_Iterator &\nFunctionParam_Iterator::operator++()\n{\n    if ( IsValid() )\n    {\n        ++itTypes;\n        ++itNames_andMore;\n    }\n    return *this;\n}\n\nvoid\nFunctionParam_Iterator::Assign( const ary::cpp::Function &  i_rFunction )\n{\n    const ary::cpp::OperationSignature &\n        rSigna = i_rFunction.Signature();\n\n    const std::vector &\n        rTypes = rSigna.Parameters();\n    const StringVector &\n        rNames = i_rFunction.ParamInfos();\n\n    if ( rTypes.size() != rNames.size() OR rTypes.size() == 0 )\n        return;\n\n    itTypes     = rTypes.begin();\n    itTypes_end = rTypes.end();\n    itNames_andMore     = rNames.begin();\n    itNames_andMore_end = rNames.end();\n\n    eConVol = rSigna.ConVol();\n}\n<|endoftext|>"}
{"text":"#include \"TestUtils.h\"\n\nnamespace SupergodEngineTesting\n{\n\tusing namespace Math;\n\n\tTEST_CLASS(Vector2DTests)\n\t{\n\tprivate:\n\t\tTEST_METHOD(ConstructorTest)\n\t\t{\n\t\t\tVector2D first(1, 1);\n\t\t\tAssert::AreEqual(first.x, 1.f);\n\t\t\tAssert::AreEqual(first.y, 1.f);\n\n\t\t\tVector2D second(3, 876);\n\t\t\tAssert::AreEqual(second.x, 3.f);\n\t\t\tAssert::AreEqual(second.y, 876.f);\n\n\t\t\tVector2D third(5, -2.3f);\n\t\t\tAssert::AreEqual(third.x, 5.f);\n\t\t\tAssert::AreEqual(third.y, -2.3f);\n\t\t}\n\n\t\tTEST_METHOD(EqualityTests)\n\t\t{\n\t\t\tAssert::IsTrue(Vector2D(10, 10) == Vector2D(10, 10));\n\t\t\tAssert::IsFalse(Vector2D(5, 10) == Vector2D(10, 10));\n\t\t\tAssert::IsTrue(Vector2D(10, 10).Equals(Vector2D(10, 10)));\n\t\t\tAssert::IsFalse(Vector2D(10, 10).Equals(Vector2D(10, 4)));\n\n\t\t\tAssert::IsFalse(Vector2D(10, 10) != Vector2D(10, 10));\n\t\t\tAssert::IsTrue(Vector2D(5, 10) != Vector2D(10, 10));\n\t\t}\n\n\t\tTEST_METHOD(BiggestSmallestComponentTest)\n\t\t{\n\t\t\tVector2D vector(5, 2);\n\t\t\tAssert::AreEqual(Vector::SmallestComponent(vector), 2.f);\n\t\t\tAssert::AreNotEqual(Vector::SmallestComponent(vector), 5.f);\n\t\t\tAssert::AreEqual(Vector::BiggestComponent(vector), 5.f);\n\t\t\tAssert::AreNotEqual(Vector::BiggestComponent(vector), 2.f);\n\t\t\t\n\t\t\tAssert::AreEqual(vector.SmallestComponent(), 2.f);\n\t\t\tAssert::AreNotEqual(vector.SmallestComponent(), 5.f);\n\t\t\tAssert::AreEqual(vector.BiggestComponent(), 5.f);\n\t\t\tAssert::AreNotEqual(vector.BiggestComponent(), 2.f);\n\n\t\t\tvector.SmallestComponent() = 0;\n\t\t\tAssert::AreEqual(vector.y, 0.f);\n\t\t\tAssert::AreEqual(vector.SmallestComponent(), 0.f);\n\n\t\t\tvector.BiggestComponent() = 2;\n\t\t\tAssert::AreEqual(vector.x, 2.f);\n\t\t\tAssert::AreEqual(vector.BiggestComponent(), 2.f);\n\t\t}\n\t\t\n\t\tTEST_METHOD(ContainsAxisTest)\n\t\t{\n\t\t\tVector2D vector(1, 2);\n\t\t\tAssert::IsTrue(vector.ContainsComponent([](float x) { return x == 1; }));\n\t\t\tAssert::IsTrue(vector.ContainsComponent([](float x) { return x == 2; }));\n\t\t\tAssert::IsFalse(vector.ContainsComponent([](float x) { return x == 3; }));\n\t\t}\n\n\t\tTEST_METHOD(CloseEnoughTest)\n\t\t{\n\t\t\tVector2D left(4, 2);\n\t\t\tVector2D right(2, 4);\n\n\t\t\tAssert::IsTrue(!left.CloseEnough(right));\n\t\t\tAssert::IsTrue(!right.CloseEnough(left));\n\n\t\t\tAssert::IsTrue(left.CloseEnough(right, 2));\n\t\t\tAssert::IsTrue(right.CloseEnough(left, 2));\n\t\t}\n\n\t\t\/\/ TODO: Maybe insert IndexerTest here later.\n\n\t\tTEST_METHOD(MagnitudeTest)\n\t\t{\n\t\t\tVector2D vec(5, .6f);\n\t\t\tAssert::AreEqual(vec.Magnitude(), Vector::Magnitude(vec));\n\t\t\tAssertUtils::CloseEnough(vec.Magnitude(), 5.03587f);\n\n\t\t\tAssertUtils::CloseEnough(vec.SqrMagnitude(), Vector::SqrMagnitude(vec));\n\t\t\tAssertUtils::CloseEnough(vec.SqrMagnitude(), 25.36f);\n\t\t\t\n\t\t\tvec = Vector2D(-5, .2f);\n\t\t\tAssert::IsTrue(vec.Magnitude() == Vector::Magnitude(vec) && SMath::CloseEnough(vec.Magnitude(), 5.004f));\n\t\t\tAssert::IsTrue(SMath::CloseEnough(vec.SqrMagnitude(), Vector::SqrMagnitude(vec)) && SMath::CloseEnough(vec.SqrMagnitude(), 25.04f));\n\t\t}\n\n\t\t\/\/ TODO: Maybe insert\n\t\t\/\/        ProjectOntoTest, ReflectionTest, AngleTest,\n\t\t\/\/\t\t  DistanceTests and LookPointAtTests here later.\n\n\t\tTEST_METHOD(ClampingTests)\n\t\t{\n\t\t\tVector2D vector = Vector2D(0, 10).Clamp(Vector2D(-2, 15), Vector2D(2, 20));\n\t\t\tAssertUtils::AreEqual(vector, Vector2D(0, 15));\n\n\t\t\tvector = Vector2D(2, 2).ClampComponents(0, 1);\n\t\t\tAssertUtils::AreEqual(vector, Vector2D(1, 1));\n\n\t\t\tvector = Vector2D(2, 2).ClampComponents(3, 4);\n\t\t\tAssertUtils::AreEqual(vector, Vector2D(3, 3));\n\n\t\t\tVector2D lengthVector = Vector2D(1, 1);\n\t\t\tVector2D oldLengthVector = lengthVector;\n\t\t\tlengthVector = lengthVector.ClampMagnitude(.5f, .7f);\n\n\t\t\tAssert::AreEqual(lengthVector.Magnitude(), .7f);\n\t\t\tAssertUtils::AreEqual(lengthVector.Normalized(), oldLengthVector.Normalized());\n\n\t\t\tlengthVector = Vector2D(10, 10);\n\t\t\toldLengthVector = lengthVector;\n\t\t\tlengthVector = lengthVector.ClampMagnitude(18, 20);\n\n\t\t\tAssert::AreEqual(lengthVector.Magnitude(), 18.f);\n\t\t\tAssertUtils::AreEqual(lengthVector.Normalized(), oldLengthVector.Normalized());\n\n\t\t\tlengthVector = Vector2D(5, 5);\n\t\t\toldLengthVector = lengthVector;\n\t\t\tlengthVector = lengthVector.ClampMagnitude(-10, 10);\n\t\t\tAssert::AreEqual(lengthVector.Magnitude(), oldLengthVector.Magnitude());\n\t\t\tAssertUtils::AreEqual(lengthVector.Normalized(), oldLengthVector.Normalized());\n\n\t\t\tAssertUtils::AreEqual(Vector2D(-1, -2).Abs(), Vector2D(1, 2));\n\t\t\tAssertUtils::AreEqual(Absolutable::Abs(Vector2D(1, 2)), Vector2D(1, 2));\n\t\t}\n\n\t\t\/\/ TODO: Maybe insert LerpTests here later.\n\t\tTEST_METHOD(LerpTest)\n\t\t{\n\t\t\tVector2D a(-10, -5);\n\t\t\tVector2D b(2, .5f);\n\t\t\tVector2D difference = b - a;\n\n\t\t\tTest01([&](float alpha)\n\t\t\t{\n\t\t\t\tVector2D result1 = Lerper::Lerp(a, b, alpha);\n\t\t\t\tVector2D result1NonStatic = a.Lerp(b, alpha);\n\t\t\t\tVector2D result2 = a + alpha * difference;\n\n\t\t\t\tAssertUtils::CloseEnough(result1.x, result2.x);\n\t\t\t\tAssertUtils::CloseEnough(result1.y, result2.y);\n\t\t\t\t\n\t\t\t\tAssertUtils::CloseEnough(result1NonStatic.x, result2.x);\n\t\t\t\tAssertUtils::CloseEnough(result1NonStatic.y, result2.y);\n\t\t\t});\n\t\t}\n\n\t\tTEST_METHOD(AdditionTest)\n\t\t{\n\t\t\tVector2D left(1, 1);\n\t\t\tVector2D right(3, 5);\n\t\t\tVector2D expectedResult(4, 6);\n\n\t\t\tAssert::IsTrue(left + right == expectedResult);\n\t\t\tAssert::IsTrue(left.Add(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Add(left, right) == expectedResult);\n\n\t\t\tleft = Vector2D(3, 876);\n\t\t\tright = Vector2D(-1, -500);\n\t\t\texpectedResult = Vector2D(2, 376);\n\n\t\t\tAssert::IsTrue(left + right == expectedResult);\n\t\t\tAssert::IsTrue(left.Add(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Add(left, right) == expectedResult);\n\n\t\t\tleft = Vector2D(5, -2.3f);\n\t\t\tright = Vector2D(5, 0.3f);\n\t\t\texpectedResult = Vector2D(10, -2);\n\n\t\t\tAssert::IsTrue(left + right == expectedResult);\n\t\t\tAssert::IsTrue(left.Add(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Add(left, right) == expectedResult);\n\t\t}\n\n\t\tTEST_METHOD(SubtractionTest)\n\t\t{\n\t\t\tVector2D left(1, 1);\n\t\t\tVector2D right(3, 5);\n\t\t\tVector2D expectedResult(-2, -4);\n\n\t\t\tAssert::IsTrue(left - right == expectedResult);\n\t\t\tAssert::IsTrue(left.Subtract(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Subtract(left, right) == expectedResult);\n\n\t\t\tleft = Vector2D(3, 876);\n\t\t\tright = Vector2D(-1, -500);\n\t\t\texpectedResult = Vector2D(4, 1376);\n\n\t\t\tAssert::IsTrue(left - right == expectedResult);\n\t\t\tAssert::IsTrue(left.Subtract(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Subtract(left, right) == expectedResult);\n\n\t\t\tleft = Vector2D(5, -2.3f);\n\t\t\tright = Vector2D(5, 0.3f);\n\t\t\texpectedResult = Vector2D(0, -2.6f);\n\n\t\t\tAssert::IsTrue(left - right == expectedResult);\n\t\t\tAssert::IsTrue(left.Subtract(right) == expectedResult);\n\t\t}\n\t\t\n\t\tTEST_METHOD(NegatingTest)\n\t\t{\n\t\t\tVector2D vector(1, 1);\n\t\t\tVector2D expectedResult(-1, -1);\n\n\t\t\tAssert::IsTrue(-vector == expectedResult);\n\t\t\tAssert::IsTrue(vector.Negated() == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Negate(vector) == expectedResult);\n\n\t\t\tvector = Vector2D(2, 5);\n\t\t\texpectedResult = Vector2D(-2, -5);\n\n\t\t\tAssert::IsTrue(-vector == expectedResult);\n\t\t\tAssert::IsTrue(vector.Negated() == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Negate(vector) == expectedResult);\n\n\t\t\tvector = Vector2D(-2, 6.5f);\n\t\t\texpectedResult = Vector2D(2, -6.5f);\n\n\t\t\tAssert::IsTrue(-vector == expectedResult);\n\t\t\tAssert::IsTrue(vector.Negated() == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Negate(vector) == expectedResult);\n\t\t}\n\n\t\tTEST_METHOD(ScalarMultiplicationTest)\n\t\t{\n\t\t\tVector2D vector(1, 1);\n\t\t\tfloat scalar = 5;\n\t\t\tVector2D expectedResult(5, 5);\n\n\t\t\tAssert::IsTrue(vector * scalar == expectedResult);\n\t\t\tAssert::IsTrue(scalar * vector == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Multiply(vector, scalar) == expectedResult);\n\t\t\tAssert::IsTrue(vector.Multiply(scalar) == expectedResult);\n\t\t\t\n\t\t\tvector = Vector2D(3, 876);\n\t\t\tscalar = 2;\n\t\t\texpectedResult = Vector2D(6, 1752);\n\t\t\t\n\t\t\tAssert::IsTrue(vector * scalar == expectedResult);\n\t\t\tAssert::IsTrue(scalar * vector == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Multiply(vector, scalar) == expectedResult);\n\t\t\tAssert::IsTrue(vector.Multiply(scalar) == expectedResult);\n\t\t\t\n\t\t\tvector = Vector2D(5, .3f);\n\t\t\tscalar = -1.5f;\n\t\t\texpectedResult = Vector2D(-7.5f, -.45f);\n\t\t\t\n\t\t\tAssert::IsTrue((vector * scalar).CloseEnough(expectedResult));\n\t\t\tAssert::IsTrue((scalar * vector).CloseEnough(expectedResult));\n\t\t\tAssert::IsTrue(ArithmeticOps::Multiply(vector, scalar).CloseEnough(expectedResult));\n\t\t\tAssert::IsTrue(vector.Multiply(scalar).CloseEnough(expectedResult));\n\t\t}\n\n\t\tTEST_METHOD(DivisionTest)\n\t\t{\n\t\t\tVector2D vector(5, 2);\n\t\t\tfloat scalar = 2;\n\t\t\tVector2D expectedResult(2.5f, 1);\n\t\t\n\t\t\tAssertUtils::AreEqual(vector \/ scalar, expectedResult);\n\t\t\tAssertUtils::AreEqual(vector.Divide(scalar), expectedResult);\n\t\t\tAssertUtils::AreEqual(ArithmeticOps::Divide(vector, scalar), expectedResult);\n\t\t\n\t\t\tvector = Vector2D(.5f, -5);\n\t\t\tscalar = .5f;\n\t\t\texpectedResult = Vector2D(1, -10);\n\t\t\n\t\t\tAssertUtils::AreEqual(vector \/ scalar, expectedResult);\n\t\t\tAssertUtils::AreEqual(vector.Divide(scalar), expectedResult);\n\t\t\tAssertUtils::AreEqual(ArithmeticOps::Divide(vector, scalar), expectedResult);\n\t\t\n\t\t\tvector = Vector2D(5, 2);\n\t\t\tVector2D vector2 = Vector2D(2, -2);\n\t\t\texpectedResult = Vector2D(2.5f, -1);\n\t\t\n\t\t\tAssertUtils::AreEqual(vector \/ vector2, expectedResult);\n\t\t\tAssertUtils::AreEqual(vector.Divide(vector2), expectedResult);\n\t\t\tAssertUtils::AreEqual(ArithmeticOps::Divide(vector, vector2), expectedResult);\n\t\t\n\t\t\tvector = Vector2D(1, -5);\n\t\t\tvector2 = Vector2D(5, 2);\n\t\t\texpectedResult = Vector2D(.2f, -2.5f);\n\t\t\n\t\t\tAssertUtils::AreEqual(vector \/ vector2, expectedResult);\n\t\t\tAssertUtils::AreEqual(vector.Divide(vector2), expectedResult);\n\t\t\tAssertUtils::AreEqual(ArithmeticOps::Divide(vector, vector2), expectedResult);\n\t\t}\n\n\t\tTEST_METHOD(MultiplicationTest)\n\t\t{\n\t\t\tVector2D left = Vector2D(1, 1);\n\t\t\tVector2D right = Vector2D(2, 0);\n\t\t\tVector2D expectedResult = Vector2D(2, 0);\n\n\t\t\tAssert::IsTrue(left * right == expectedResult);\n\t\t\tAssert::IsTrue(left.Multiply(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Multiply(left, right) == expectedResult);\n\n\t\t\tleft = Vector2D(3, 10);\n\t\t\tright = Vector2D(-1, 1.5f);\n\t\t\texpectedResult = Vector2D(-3, 15);\n\n\t\t\tAssert::IsTrue(left * right == expectedResult);\n\t\t\tAssert::IsTrue(left.Multiply(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Multiply(left, right) == expectedResult);\n\n\t\t\tleft = Vector2D(3, 5);\n\t\t\tright = Vector2D(5, -.5f);\n\t\t\texpectedResult = Vector2D(15, -2.5f);\n\n\t\t\tAssert::IsTrue(left * right == expectedResult);\n\t\t\tAssert::IsTrue(left.Multiply(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Multiply(left, right) == expectedResult);\n\t\t}\n\n\t\tTEST_METHOD(DotTest)\n\t\t{\n\t\t\tVector2D firstLeft(1, 5);\n\t\t\tVector2D firstRight(2, .5f);\n\t\t\tfloat first = Vector::Dot(firstLeft, firstRight);\n\t\t\tAssert::IsTrue(first == 4.5f);\n\n\t\t\tVector2D secondLeft = Vector2D(-2, -4);\n\t\t\tVector2D secondRight = Vector2D(5, 5);\n\t\t\tfloat second = Vector::Dot(secondLeft, secondRight);\n\t\t\tAssert::IsTrue(second == -30);\n\n\t\t\tVector2D thirdLeft = Vector2D(-2, -4);\n\t\t\tVector2D thirdRight = Vector2D(5, 5);\n\t\t\tfloat third = thirdLeft.Dot(thirdRight);\n\t\t\tAssert::IsTrue(third == -30);\n\t\t}\n\n\t\t\/\/ TODO: MAYBE test conversions (depends on if they will even exist).\n\t};\n}Removed a comment I forgot to remove previously.#include \"TestUtils.h\"\n\nnamespace SupergodEngineTesting\n{\n\tusing namespace Math;\n\n\tTEST_CLASS(Vector2DTests)\n\t{\n\tprivate:\n\t\tTEST_METHOD(ConstructorTest)\n\t\t{\n\t\t\tVector2D first(1, 1);\n\t\t\tAssert::AreEqual(first.x, 1.f);\n\t\t\tAssert::AreEqual(first.y, 1.f);\n\n\t\t\tVector2D second(3, 876);\n\t\t\tAssert::AreEqual(second.x, 3.f);\n\t\t\tAssert::AreEqual(second.y, 876.f);\n\n\t\t\tVector2D third(5, -2.3f);\n\t\t\tAssert::AreEqual(third.x, 5.f);\n\t\t\tAssert::AreEqual(third.y, -2.3f);\n\t\t}\n\n\t\tTEST_METHOD(EqualityTests)\n\t\t{\n\t\t\tAssert::IsTrue(Vector2D(10, 10) == Vector2D(10, 10));\n\t\t\tAssert::IsFalse(Vector2D(5, 10) == Vector2D(10, 10));\n\t\t\tAssert::IsTrue(Vector2D(10, 10).Equals(Vector2D(10, 10)));\n\t\t\tAssert::IsFalse(Vector2D(10, 10).Equals(Vector2D(10, 4)));\n\n\t\t\tAssert::IsFalse(Vector2D(10, 10) != Vector2D(10, 10));\n\t\t\tAssert::IsTrue(Vector2D(5, 10) != Vector2D(10, 10));\n\t\t}\n\n\t\tTEST_METHOD(BiggestSmallestComponentTest)\n\t\t{\n\t\t\tVector2D vector(5, 2);\n\t\t\tAssert::AreEqual(Vector::SmallestComponent(vector), 2.f);\n\t\t\tAssert::AreNotEqual(Vector::SmallestComponent(vector), 5.f);\n\t\t\tAssert::AreEqual(Vector::BiggestComponent(vector), 5.f);\n\t\t\tAssert::AreNotEqual(Vector::BiggestComponent(vector), 2.f);\n\t\t\t\n\t\t\tAssert::AreEqual(vector.SmallestComponent(), 2.f);\n\t\t\tAssert::AreNotEqual(vector.SmallestComponent(), 5.f);\n\t\t\tAssert::AreEqual(vector.BiggestComponent(), 5.f);\n\t\t\tAssert::AreNotEqual(vector.BiggestComponent(), 2.f);\n\n\t\t\tvector.SmallestComponent() = 0;\n\t\t\tAssert::AreEqual(vector.y, 0.f);\n\t\t\tAssert::AreEqual(vector.SmallestComponent(), 0.f);\n\n\t\t\tvector.BiggestComponent() = 2;\n\t\t\tAssert::AreEqual(vector.x, 2.f);\n\t\t\tAssert::AreEqual(vector.BiggestComponent(), 2.f);\n\t\t}\n\t\t\n\t\tTEST_METHOD(ContainsAxisTest)\n\t\t{\n\t\t\tVector2D vector(1, 2);\n\t\t\tAssert::IsTrue(vector.ContainsComponent([](float x) { return x == 1; }));\n\t\t\tAssert::IsTrue(vector.ContainsComponent([](float x) { return x == 2; }));\n\t\t\tAssert::IsFalse(vector.ContainsComponent([](float x) { return x == 3; }));\n\t\t}\n\n\t\tTEST_METHOD(CloseEnoughTest)\n\t\t{\n\t\t\tVector2D left(4, 2);\n\t\t\tVector2D right(2, 4);\n\n\t\t\tAssert::IsTrue(!left.CloseEnough(right));\n\t\t\tAssert::IsTrue(!right.CloseEnough(left));\n\n\t\t\tAssert::IsTrue(left.CloseEnough(right, 2));\n\t\t\tAssert::IsTrue(right.CloseEnough(left, 2));\n\t\t}\n\n\t\t\/\/ TODO: Maybe insert IndexerTest here later.\n\n\t\tTEST_METHOD(MagnitudeTest)\n\t\t{\n\t\t\tVector2D vec(5, .6f);\n\t\t\tAssert::AreEqual(vec.Magnitude(), Vector::Magnitude(vec));\n\t\t\tAssertUtils::CloseEnough(vec.Magnitude(), 5.03587f);\n\n\t\t\tAssertUtils::CloseEnough(vec.SqrMagnitude(), Vector::SqrMagnitude(vec));\n\t\t\tAssertUtils::CloseEnough(vec.SqrMagnitude(), 25.36f);\n\t\t\t\n\t\t\tvec = Vector2D(-5, .2f);\n\t\t\tAssert::IsTrue(vec.Magnitude() == Vector::Magnitude(vec) && SMath::CloseEnough(vec.Magnitude(), 5.004f));\n\t\t\tAssert::IsTrue(SMath::CloseEnough(vec.SqrMagnitude(), Vector::SqrMagnitude(vec)) && SMath::CloseEnough(vec.SqrMagnitude(), 25.04f));\n\t\t}\n\n\t\t\/\/ TODO: Maybe insert\n\t\t\/\/        ProjectOntoTest, ReflectionTest, AngleTest,\n\t\t\/\/\t\t  DistanceTests and LookPointAtTests here later.\n\n\t\tTEST_METHOD(ClampingTests)\n\t\t{\n\t\t\tVector2D vector = Vector2D(0, 10).Clamp(Vector2D(-2, 15), Vector2D(2, 20));\n\t\t\tAssertUtils::AreEqual(vector, Vector2D(0, 15));\n\n\t\t\tvector = Vector2D(2, 2).ClampComponents(0, 1);\n\t\t\tAssertUtils::AreEqual(vector, Vector2D(1, 1));\n\n\t\t\tvector = Vector2D(2, 2).ClampComponents(3, 4);\n\t\t\tAssertUtils::AreEqual(vector, Vector2D(3, 3));\n\n\t\t\tVector2D lengthVector = Vector2D(1, 1);\n\t\t\tVector2D oldLengthVector = lengthVector;\n\t\t\tlengthVector = lengthVector.ClampMagnitude(.5f, .7f);\n\n\t\t\tAssert::AreEqual(lengthVector.Magnitude(), .7f);\n\t\t\tAssertUtils::AreEqual(lengthVector.Normalized(), oldLengthVector.Normalized());\n\n\t\t\tlengthVector = Vector2D(10, 10);\n\t\t\toldLengthVector = lengthVector;\n\t\t\tlengthVector = lengthVector.ClampMagnitude(18, 20);\n\n\t\t\tAssert::AreEqual(lengthVector.Magnitude(), 18.f);\n\t\t\tAssertUtils::AreEqual(lengthVector.Normalized(), oldLengthVector.Normalized());\n\n\t\t\tlengthVector = Vector2D(5, 5);\n\t\t\toldLengthVector = lengthVector;\n\t\t\tlengthVector = lengthVector.ClampMagnitude(-10, 10);\n\t\t\tAssert::AreEqual(lengthVector.Magnitude(), oldLengthVector.Magnitude());\n\t\t\tAssertUtils::AreEqual(lengthVector.Normalized(), oldLengthVector.Normalized());\n\n\t\t\tAssertUtils::AreEqual(Vector2D(-1, -2).Abs(), Vector2D(1, 2));\n\t\t\tAssertUtils::AreEqual(Absolutable::Abs(Vector2D(1, 2)), Vector2D(1, 2));\n\t\t}\n\n\t\tTEST_METHOD(LerpTest)\n\t\t{\n\t\t\tVector2D a(-10, -5);\n\t\t\tVector2D b(2, .5f);\n\t\t\tVector2D difference = b - a;\n\n\t\t\tTest01([&](float alpha)\n\t\t\t{\n\t\t\t\tVector2D result1 = Lerper::Lerp(a, b, alpha);\n\t\t\t\tVector2D result1NonStatic = a.Lerp(b, alpha);\n\t\t\t\tVector2D result2 = a + alpha * difference;\n\n\t\t\t\tAssertUtils::CloseEnough(result1.x, result2.x);\n\t\t\t\tAssertUtils::CloseEnough(result1.y, result2.y);\n\t\t\t\t\n\t\t\t\tAssertUtils::CloseEnough(result1NonStatic.x, result2.x);\n\t\t\t\tAssertUtils::CloseEnough(result1NonStatic.y, result2.y);\n\t\t\t});\n\t\t}\n\n\t\tTEST_METHOD(AdditionTest)\n\t\t{\n\t\t\tVector2D left(1, 1);\n\t\t\tVector2D right(3, 5);\n\t\t\tVector2D expectedResult(4, 6);\n\n\t\t\tAssert::IsTrue(left + right == expectedResult);\n\t\t\tAssert::IsTrue(left.Add(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Add(left, right) == expectedResult);\n\n\t\t\tleft = Vector2D(3, 876);\n\t\t\tright = Vector2D(-1, -500);\n\t\t\texpectedResult = Vector2D(2, 376);\n\n\t\t\tAssert::IsTrue(left + right == expectedResult);\n\t\t\tAssert::IsTrue(left.Add(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Add(left, right) == expectedResult);\n\n\t\t\tleft = Vector2D(5, -2.3f);\n\t\t\tright = Vector2D(5, 0.3f);\n\t\t\texpectedResult = Vector2D(10, -2);\n\n\t\t\tAssert::IsTrue(left + right == expectedResult);\n\t\t\tAssert::IsTrue(left.Add(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Add(left, right) == expectedResult);\n\t\t}\n\n\t\tTEST_METHOD(SubtractionTest)\n\t\t{\n\t\t\tVector2D left(1, 1);\n\t\t\tVector2D right(3, 5);\n\t\t\tVector2D expectedResult(-2, -4);\n\n\t\t\tAssert::IsTrue(left - right == expectedResult);\n\t\t\tAssert::IsTrue(left.Subtract(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Subtract(left, right) == expectedResult);\n\n\t\t\tleft = Vector2D(3, 876);\n\t\t\tright = Vector2D(-1, -500);\n\t\t\texpectedResult = Vector2D(4, 1376);\n\n\t\t\tAssert::IsTrue(left - right == expectedResult);\n\t\t\tAssert::IsTrue(left.Subtract(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Subtract(left, right) == expectedResult);\n\n\t\t\tleft = Vector2D(5, -2.3f);\n\t\t\tright = Vector2D(5, 0.3f);\n\t\t\texpectedResult = Vector2D(0, -2.6f);\n\n\t\t\tAssert::IsTrue(left - right == expectedResult);\n\t\t\tAssert::IsTrue(left.Subtract(right) == expectedResult);\n\t\t}\n\t\t\n\t\tTEST_METHOD(NegatingTest)\n\t\t{\n\t\t\tVector2D vector(1, 1);\n\t\t\tVector2D expectedResult(-1, -1);\n\n\t\t\tAssert::IsTrue(-vector == expectedResult);\n\t\t\tAssert::IsTrue(vector.Negated() == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Negate(vector) == expectedResult);\n\n\t\t\tvector = Vector2D(2, 5);\n\t\t\texpectedResult = Vector2D(-2, -5);\n\n\t\t\tAssert::IsTrue(-vector == expectedResult);\n\t\t\tAssert::IsTrue(vector.Negated() == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Negate(vector) == expectedResult);\n\n\t\t\tvector = Vector2D(-2, 6.5f);\n\t\t\texpectedResult = Vector2D(2, -6.5f);\n\n\t\t\tAssert::IsTrue(-vector == expectedResult);\n\t\t\tAssert::IsTrue(vector.Negated() == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Negate(vector) == expectedResult);\n\t\t}\n\n\t\tTEST_METHOD(ScalarMultiplicationTest)\n\t\t{\n\t\t\tVector2D vector(1, 1);\n\t\t\tfloat scalar = 5;\n\t\t\tVector2D expectedResult(5, 5);\n\n\t\t\tAssert::IsTrue(vector * scalar == expectedResult);\n\t\t\tAssert::IsTrue(scalar * vector == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Multiply(vector, scalar) == expectedResult);\n\t\t\tAssert::IsTrue(vector.Multiply(scalar) == expectedResult);\n\t\t\t\n\t\t\tvector = Vector2D(3, 876);\n\t\t\tscalar = 2;\n\t\t\texpectedResult = Vector2D(6, 1752);\n\t\t\t\n\t\t\tAssert::IsTrue(vector * scalar == expectedResult);\n\t\t\tAssert::IsTrue(scalar * vector == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Multiply(vector, scalar) == expectedResult);\n\t\t\tAssert::IsTrue(vector.Multiply(scalar) == expectedResult);\n\t\t\t\n\t\t\tvector = Vector2D(5, .3f);\n\t\t\tscalar = -1.5f;\n\t\t\texpectedResult = Vector2D(-7.5f, -.45f);\n\t\t\t\n\t\t\tAssert::IsTrue((vector * scalar).CloseEnough(expectedResult));\n\t\t\tAssert::IsTrue((scalar * vector).CloseEnough(expectedResult));\n\t\t\tAssert::IsTrue(ArithmeticOps::Multiply(vector, scalar).CloseEnough(expectedResult));\n\t\t\tAssert::IsTrue(vector.Multiply(scalar).CloseEnough(expectedResult));\n\t\t}\n\n\t\tTEST_METHOD(DivisionTest)\n\t\t{\n\t\t\tVector2D vector(5, 2);\n\t\t\tfloat scalar = 2;\n\t\t\tVector2D expectedResult(2.5f, 1);\n\t\t\n\t\t\tAssertUtils::AreEqual(vector \/ scalar, expectedResult);\n\t\t\tAssertUtils::AreEqual(vector.Divide(scalar), expectedResult);\n\t\t\tAssertUtils::AreEqual(ArithmeticOps::Divide(vector, scalar), expectedResult);\n\t\t\n\t\t\tvector = Vector2D(.5f, -5);\n\t\t\tscalar = .5f;\n\t\t\texpectedResult = Vector2D(1, -10);\n\t\t\n\t\t\tAssertUtils::AreEqual(vector \/ scalar, expectedResult);\n\t\t\tAssertUtils::AreEqual(vector.Divide(scalar), expectedResult);\n\t\t\tAssertUtils::AreEqual(ArithmeticOps::Divide(vector, scalar), expectedResult);\n\t\t\n\t\t\tvector = Vector2D(5, 2);\n\t\t\tVector2D vector2 = Vector2D(2, -2);\n\t\t\texpectedResult = Vector2D(2.5f, -1);\n\t\t\n\t\t\tAssertUtils::AreEqual(vector \/ vector2, expectedResult);\n\t\t\tAssertUtils::AreEqual(vector.Divide(vector2), expectedResult);\n\t\t\tAssertUtils::AreEqual(ArithmeticOps::Divide(vector, vector2), expectedResult);\n\t\t\n\t\t\tvector = Vector2D(1, -5);\n\t\t\tvector2 = Vector2D(5, 2);\n\t\t\texpectedResult = Vector2D(.2f, -2.5f);\n\t\t\n\t\t\tAssertUtils::AreEqual(vector \/ vector2, expectedResult);\n\t\t\tAssertUtils::AreEqual(vector.Divide(vector2), expectedResult);\n\t\t\tAssertUtils::AreEqual(ArithmeticOps::Divide(vector, vector2), expectedResult);\n\t\t}\n\n\t\tTEST_METHOD(MultiplicationTest)\n\t\t{\n\t\t\tVector2D left = Vector2D(1, 1);\n\t\t\tVector2D right = Vector2D(2, 0);\n\t\t\tVector2D expectedResult = Vector2D(2, 0);\n\n\t\t\tAssert::IsTrue(left * right == expectedResult);\n\t\t\tAssert::IsTrue(left.Multiply(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Multiply(left, right) == expectedResult);\n\n\t\t\tleft = Vector2D(3, 10);\n\t\t\tright = Vector2D(-1, 1.5f);\n\t\t\texpectedResult = Vector2D(-3, 15);\n\n\t\t\tAssert::IsTrue(left * right == expectedResult);\n\t\t\tAssert::IsTrue(left.Multiply(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Multiply(left, right) == expectedResult);\n\n\t\t\tleft = Vector2D(3, 5);\n\t\t\tright = Vector2D(5, -.5f);\n\t\t\texpectedResult = Vector2D(15, -2.5f);\n\n\t\t\tAssert::IsTrue(left * right == expectedResult);\n\t\t\tAssert::IsTrue(left.Multiply(right) == expectedResult);\n\t\t\tAssert::IsTrue(ArithmeticOps::Multiply(left, right) == expectedResult);\n\t\t}\n\n\t\tTEST_METHOD(DotTest)\n\t\t{\n\t\t\tVector2D firstLeft(1, 5);\n\t\t\tVector2D firstRight(2, .5f);\n\t\t\tfloat first = Vector::Dot(firstLeft, firstRight);\n\t\t\tAssert::IsTrue(first == 4.5f);\n\n\t\t\tVector2D secondLeft = Vector2D(-2, -4);\n\t\t\tVector2D secondRight = Vector2D(5, 5);\n\t\t\tfloat second = Vector::Dot(secondLeft, secondRight);\n\t\t\tAssert::IsTrue(second == -30);\n\n\t\t\tVector2D thirdLeft = Vector2D(-2, -4);\n\t\t\tVector2D thirdRight = Vector2D(5, 5);\n\t\t\tfloat third = thirdLeft.Dot(thirdRight);\n\t\t\tAssert::IsTrue(third == -30);\n\t\t}\n\n\t\t\/\/ TODO: MAYBE test conversions (depends on if they will even exist).\n\t};\n}<|endoftext|>"}
{"text":"\/\/ Copyright (C) 2015 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"CompileConfig.h\"\n\n#if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS)\n#include \n#endif\n\n#if defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS)\n#include \n#endif\n\n#ifdef OUZEL_PLATFORM_WINDOWS\n#include \n#include \n#endif\n\n#ifdef OUZEL_PLATFORM_ANDROID\n#include \n#endif\n\n#include \"Utils.h\"\n\nnamespace ouzel\n{\n    char TEMP_BUFFER[65536];\n\n    void log(const char* format, ...)\n    {\n        va_list list;\n        va_start(list, format);\n        \n        vsprintf(TEMP_BUFFER, format, list);\n        \n        va_end(list);\n        \n#if defined(OUZEL_PLATFORM_OSX)\n        printf(\"%s\\n\", TEMP_BUFFER);\n#elif defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS)\n        syslog(LOG_WARNING, \"%s\", TEMP_BUFFER);\n        printf(\"%s\\n\", TEMP_BUFFER);\n#elif defined(OUZEL_PLATFORM_WINDOWS)\n        wchar_t szBuffer[256];\n        MultiByteToWideChar(CP_ACP, 0, TEMP_BUFFER, -1, szBuffer, 256);\n        StringCchCat(szBuffer, sizeof(szBuffer), L\"\\n\");\n        OutputDebugString(szBuffer);\n#elif defined(OUZEL_PLATFORM_ANDROID)\n        __android_log_print(ANDROID_LOG_DEBUG, \"Ouzel\", \"%s\", TEMP_BUFFER);\n#endif\n    }\n    \n    uint64_t getCurrentMicroSeconds()\n    {\n#if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) || defined(OUZEL_PLATFORM_ANDROID)\n        struct timeval currentTime;\n        \n        gettimeofday(¤tTime, NULL);\n        return currentTime.tv_sec * 1000000L + currentTime.tv_usec;\n#elif defined(OUZEL_PLATFORM_WINDOWS)\n        LARGE_INTEGER li;\n        if (!QueryPerformanceFrequency(&li))\n        {\n            log(\"Failed to query frequency\");\n            return 0;\n        }\n        uint64_t frequency = li.QuadPart \/ 1000000L;\n        \n        QueryPerformanceCounter(&li);\n        \n        return li.QuadPart \/ frequency;\n#else\n        return 0;\n#endif\n    }\n}\nQuery timer frequency only once on Windows\/\/ Copyright (C) 2015 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"CompileConfig.h\"\n\n#if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS)\n#include \n#endif\n\n#if defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS)\n#include \n#endif\n\n#ifdef OUZEL_PLATFORM_WINDOWS\n#include \n#include \n#endif\n\n#ifdef OUZEL_PLATFORM_ANDROID\n#include \n#endif\n\n#include \"Utils.h\"\n\nnamespace ouzel\n{\n    char TEMP_BUFFER[65536];\n\n    void log(const char* format, ...)\n    {\n        va_list list;\n        va_start(list, format);\n        \n        vsprintf(TEMP_BUFFER, format, list);\n        \n        va_end(list);\n        \n#if defined(OUZEL_PLATFORM_OSX)\n        printf(\"%s\\n\", TEMP_BUFFER);\n#elif defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS)\n        syslog(LOG_WARNING, \"%s\", TEMP_BUFFER);\n        printf(\"%s\\n\", TEMP_BUFFER);\n#elif defined(OUZEL_PLATFORM_WINDOWS)\n        wchar_t szBuffer[256];\n        MultiByteToWideChar(CP_ACP, 0, TEMP_BUFFER, -1, szBuffer, 256);\n        StringCchCat(szBuffer, sizeof(szBuffer), L\"\\n\");\n        OutputDebugString(szBuffer);\n#elif defined(OUZEL_PLATFORM_ANDROID)\n        __android_log_print(ANDROID_LOG_DEBUG, \"Ouzel\", \"%s\", TEMP_BUFFER);\n#endif\n    }\n    \n    uint64_t getCurrentMicroSeconds()\n    {\n#if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) || defined(OUZEL_PLATFORM_ANDROID)\n        struct timeval currentTime;\n        \n        gettimeofday(¤tTime, NULL);\n        return currentTime.tv_sec * 1000000L + currentTime.tv_usec;\n#elif defined(OUZEL_PLATFORM_WINDOWS)\n        \n        static uint64_t frequency = 0;\n        LARGE_INTEGER li;\n        \n        if (!frequency)\n        {\n            if (!QueryPerformanceFrequency(&li))\n            {\n                log(\"Failed to query frequency\");\n                return 0;\n            }\n            frequency = li.QuadPart \/ 1000000L;\n        }\n        \n        QueryPerformanceCounter(&li);\n        \n        return li.QuadPart \/ frequency;\n#else\n        return 0;\n#endif\n    }\n}\n<|endoftext|>"}
{"text":"\/\/ Example program\n#include \n#include \n\nvoid Merge(std::vector& sub_data,unsigned int left_index, unsigned int middle_index, unsigned int right_index){\n       std::cout << \"l_index : \" << left_index << \", Right_index : \" << right_index << \",Middle_index : \" << middle_index;\n       const int l_size = middle_index - left_index ;\n       const int r_size = right_index - middle_index;\n       std::vector l_data,r_data;\n       std::vector::iterator itr = sub_data.begin()+left_index;\n       for(int x = 0; x < l_size ; ++x){\n            l_data.push_back(*itr); \n            ++itr;\n        }\n       itr = sub_data.begin()+ middle_index + 1;\n       for(int x = 0; x < r_size ; ++x){\n            r_data.push_back(*itr); \n            ++itr;\n        }\n         \n       std::cout << \" Left Data : \";\n       for(const auto& x : l_data)\n            std::cout << x << \",\";\n       std::cout << \" Right Data : \";\n       for(const auto& x : r_data)\n            std::cout << x << \",\";\n        std::cout << \"\\n\";\n       \n\n       \/\/ Merging the data\n       int i = 0, j =0 , k = left_index;\n       while(i < l_size && j < r_size){\n            if(l_data[i] < r_data[j]){\n                sub_data[k] = l_data[i];\n                i++;\n            }else{\n                sub_data[k] = r_data[j];\n                j++;\n            }\n            k++;\n        }\n}\n\nvoid MSort(std::vector& sub_data,unsigned int left_index, unsigned int right_index){\n    if(left_index < right_index){\n        int middle_index = left_index + (right_index-left_index) \/2;\n        MSort(sub_data,left_index,middle_index);\n        MSort(sub_data,middle_index+1,right_index);\n        Merge(sub_data,left_index,middle_index + 1,right_index);\n    }\n    \n};\n\nint main()\n{\n    std::vector data = {38,27,43,3,9,82,10};\n    for(const auto& x : data)\n        std::cout << x << \",\";\n    std::cout << \"\\nStarting the sort ...\\n\";\n    MSort(data,0,data.size());\n    for(const auto& x : data)\n        std::cout << x << \",\";  \n    std::cout<< \"\\nFinished\" << std::endl;\n}\nUpdate MergeSort.cc\/\/ Example program\n#include \n#include \n\nvoid Merge(std::vector& sub_data,unsigned int left_index, unsigned int middle_index, unsigned int right_index){\n    \n       const int l_size = middle_index - left_index + 1;\n       const int r_size = right_index - middle_index;\n       std::cout << \"l_index : \" << left_index << \", Right_index : \" << right_index << \",Middle_index : \" << middle_index << \", l_size : \" << l_size << \", r_size \" << r_size;\n       std::vector l_data,r_data;\n       std::vector::iterator itr = sub_data.begin()+left_index;\n       for(int x = 0; x < l_size ; ++x){\n            l_data.push_back(*itr); \n            ++itr;\n        }\n       itr = sub_data.begin()+ middle_index + 1;\n       for(int x = 0; x < r_size ; ++x){\n            r_data.push_back(*itr); \n            ++itr;\n        }\n         \n       std::cout << \" Left Data : \";\n       for(const auto& x : l_data)\n            std::cout << x << \",\";\n       std::cout << \" Right Data : \";\n       for(const auto& x : r_data)\n            std::cout << x << \",\";\n        std::cout << \"\\n\";\n       \n\n       \/\/ Merging the data\n       int i = 0, j =0 , k = left_index;\n       while(i < l_size && j < r_size){\n            sub_data[k++] = (l_data[i] < r_data[j]) ? l_data[i++] : r_data[j++];\n        }\n        while (i < l_size)\n            sub_data[k++] = l_data[i++];\n        while (j < r_size)\n            sub_data[k++] = r_data[j++];\n}\n\nvoid MSort(std::vector& sub_data,unsigned int left_index, unsigned int right_index){\n    if(left_index < right_index){\n        int middle_index = left_index + (right_index-left_index) \/2;\n        MSort(sub_data,left_index,middle_index);\n        MSort(sub_data,middle_index+1,right_index);\n        Merge(sub_data,left_index,middle_index,right_index);\n    }\n    \n};\n\nint main()\n{\n    \/\/std::vector data = {38,27,43,3,9,82,10};\n    std::vector data = {38,27,43};\n    for(const auto& x : data)\n        std::cout << x << \",\";\n    std::cout << \"\\nStarting the sort ...\\n\";\n    MSort(data,0,data.size());\n    for(const auto& x : data)\n        std::cout << x << \",\";  \n    std::cout<< \"\\nFinished\" << std::endl;\n}\n<|endoftext|>"}
{"text":"#include \n#include \n\n#include \"TTreeFormula.h\"\n#include \"TCanvas.h\"\n#include \"TH1F.h\"\n#include \"TH1.h\"\n\n#include \"CutflowMaker.h\"\n\nClassImp(CutflowMaker)\n\n\/\/--------------------------------------------------------------------\nCutflowMaker::CutflowMaker() :\n{\n  fCutNames.resize(0);\n  fCuts.resize(0);\n  fYields.resize(0);\n}\n\n\/\/--------------------------------------------------------------------\nvoid\nCutflowMaker::GetCutflow()\n{\n  if (fYields.size() == 0 && fTree != NULL) {\n    std::vector formulae;\n    TTreeFormula *tempFormula;\n    for (UInt_t iCut = 0; iCut != fCuts.size(); ++iCut) {\n      tempFormula = new TTreeFormula(fCutNames[iCut],fCuts[iCut],fTree);\n      formulae.push_back(tempFormula);\n      fYields.push_back(0);\n    }\n    Int_t numEntries = fTree->GetEntriesFast();\n    for (Int_t iEntry = 0; iEntry != numEntries; ++iEntry) {\n      fTree->GetEntry(iEntry);\n      for (UInt_t iCut = 0; iCut != formulae.size(); ++iCut) {\n        if (formulae[iCut]->EvalInstance() == 0)\n          break;\n        \n        ++fYields[iCut];\n      }\n    }\n    for (UInt_t iFormula = 0; iFormula != formulae.size(); ++iFormula)\n      delete formulae[iFormula];\n  }\n}\n\n\/\/--------------------------------------------------------------------\nvoid\nCutflowMaker::PrintCutflow(Bool_t OnlyNums)\n{\n  GetCutflow();\n  std::cout << std::endl;\n  for (UInt_t iCut = 0; iCut != fCuts.size(); ++iCut) {\n    if (!OnlyNums) {\n      std::cout << std::setw(20);\n      std::cout << fCutNames[iCut] << \": \";\n    }\n    if (fTree != NULL) {\n      std::cout << std::setw(15);\n      std::cout << fYields[iCut];\n    }\n    std::cout << std::endl;\n  }\n  std::cout << std::endl;\n}\n\n\/\/--------------------------------------------------------------------\nvoid\nCutflowMaker::MakePlot(TString name, PlotStyle type)\n{\n  if (fTree == NULL) {\n    std::cout << \"Tree has not been set.\" << std::endl;\n    exit(1);\n  }\n  GetCutflow();\n  TH1F* theHist = new TH1F(\"cutflow\",\";;Number of Events\",fCuts.size(),0,fCuts.size());\n  for (UInt_t iCut = 0; iCut != fCuts.size(); ++iCut) {\n    theHist->GetXaxis()->SetBinLabel(iCut+1,fCutNames[iCut]);\n    if (PlotStyle == kAbsolute)\n      theHist->SetBinContent(iCut+1,fYields[iCut]);\n    if (PlotStyle == kFractional) {\n      if (iCut == 0)\n        theHist->SetBinContent(iCut+1,float(fYields[iCut])\/fTree->GetEntriesFast());\n      else\n        theHist->SetBinContent(iCut+1,float(fYields[iCut])\/fYields[iCut - 1]);\n    }\n  }\n  theHist->SetLineWidth(2);\n  \n  TCanvas* theCanvas = new TCanvas(\"canvas\",\";;Number of Events\",fWidth,fHeight);\n  theHist->Draw();\n\n  theCanvas->SaveAs(name + \".pdf\");\n  theCanvas->SaveAs(name + \".png\");\n  theCanvas->SaveAs(name + \".C\");\n}\nSmall bug#include \n#include \n\n#include \"TTreeFormula.h\"\n#include \"TCanvas.h\"\n#include \"TH1F.h\"\n#include \"TH1.h\"\n\n#include \"CutflowMaker.h\"\n\nClassImp(CutflowMaker)\n\n\/\/--------------------------------------------------------------------\nCutflowMaker::CutflowMaker() :\n  fWidth(600),\n  fHeight(600)\n{\n  fCutNames.resize(0);\n  fCuts.resize(0);\n  fYields.resize(0);\n}\n\n\/\/--------------------------------------------------------------------\nvoid\nCutflowMaker::GetCutflow()\n{\n  if (fYields.size() == 0 && fTree != NULL) {\n    std::vector formulae;\n    TTreeFormula *tempFormula;\n    for (UInt_t iCut = 0; iCut != fCuts.size(); ++iCut) {\n      tempFormula = new TTreeFormula(fCutNames[iCut],fCuts[iCut],fTree);\n      formulae.push_back(tempFormula);\n      fYields.push_back(0);\n    }\n    Int_t numEntries = fTree->GetEntriesFast();\n    for (Int_t iEntry = 0; iEntry != numEntries; ++iEntry) {\n      fTree->GetEntry(iEntry);\n      for (UInt_t iCut = 0; iCut != formulae.size(); ++iCut) {\n        if (formulae[iCut]->EvalInstance() == 0)\n          break;\n        \n        ++fYields[iCut];\n      }\n    }\n    for (UInt_t iFormula = 0; iFormula != formulae.size(); ++iFormula)\n      delete formulae[iFormula];\n  }\n}\n\n\/\/--------------------------------------------------------------------\nvoid\nCutflowMaker::PrintCutflow(Bool_t OnlyNums)\n{\n  GetCutflow();\n  std::cout << std::endl;\n  for (UInt_t iCut = 0; iCut != fCuts.size(); ++iCut) {\n    if (!OnlyNums) {\n      std::cout << std::setw(20);\n      std::cout << fCutNames[iCut] << \": \";\n    }\n    if (fTree != NULL) {\n      std::cout << std::setw(15);\n      std::cout << fYields[iCut];\n    }\n    std::cout << std::endl;\n  }\n  std::cout << std::endl;\n}\n\n\/\/--------------------------------------------------------------------\nvoid\nCutflowMaker::MakePlot(TString name, PlotStyle type)\n{\n  if (fTree == NULL) {\n    std::cout << \"Tree has not been set.\" << std::endl;\n    exit(1);\n  }\n  GetCutflow();\n  TH1F* theHist = new TH1F(\"cutflow\",\";;Number of Events\",fCuts.size(),0,fCuts.size());\n  for (UInt_t iCut = 0; iCut != fCuts.size(); ++iCut) {\n    theHist->GetXaxis()->SetBinLabel(iCut+1,fCutNames[iCut]);\n    if (PlotStyle == kAbsolute)\n      theHist->SetBinContent(iCut+1,fYields[iCut]);\n    if (PlotStyle == kFractional) {\n      if (iCut == 0)\n        theHist->SetBinContent(iCut+1,float(fYields[iCut])\/fTree->GetEntriesFast());\n      else\n        theHist->SetBinContent(iCut+1,float(fYields[iCut])\/fYields[iCut - 1]);\n    }\n  }\n  theHist->SetLineWidth(2);\n  \n  TCanvas* theCanvas = new TCanvas(\"canvas\",\";;Number of Events\",fWidth,fHeight);\n  theHist->Draw();\n\n  theCanvas->SaveAs(name + \".pdf\");\n  theCanvas->SaveAs(name + \".png\");\n  theCanvas->SaveAs(name + \".C\");\n}\n<|endoftext|>"}
{"text":"#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass BenchCallback :public dariadb::storage::ReaderClb {\npublic:\n\tvoid call(const dariadb::Meas&) {\n\t\tcount++;\n\t}\n\tsize_t count;\n};\n\nvoid writer_1(dariadb::storage::BaseStorage_ptr ms)\n{\n\tauto m = dariadb::Meas::empty();\n\tdariadb::Time t = 0;\n\tfor (dariadb::Id i = 0; i < 32768; i += 1) {\n\t\tm.id = i;\n\t\tm.flag = dariadb::Flag(0);\n\t\tm.time = t;\n\t\tm.value = dariadb::Value(i);\n\t\tms->append(m);\n\t\tt++;\n\t}\n}\n\nstd::atomic_long writen{ 0 };\n\nvoid writer_2(dariadb::Id id_from, size_t id_per_thread, dariadb::storage::BaseStorage_ptr ms)\n{\n\tauto m = dariadb::Meas::empty();\n\tstd::random_device r;\n\tstd::default_random_engine e1(r());\n\tstd::uniform_int_distribution uniform_dist(10, 64);\n\n    size_t max_id=(id_from + id_per_thread);\n   \n\n    for (dariadb::Id i = id_from; i < max_id; i += 1) {\n\t\tdariadb::Value v = 1.0;\n        auto max_rnd = uniform_dist(e1);\n\t\tdariadb::Time t = dariadb::timeutil::current_time();\n\t\tfor (dariadb::Time p = 0; p < dariadb::Time(max_rnd); p++) {\n\t\t\tm.id = i;\n\t\t\tm.flag = dariadb::Flag(0);\n\t\t\tm.time = t++;\n\t\t\tm.value = v;\n\t\t\tms->append(m);\n\t\t\twriten++;\n\t\t\tauto rnd = rand() \/ float(RAND_MAX);\n\n\t\t\tv += rnd;\n\t\t}\n\n\t}\n}\n\nint main(int argc, char *argv[]) {\n\t(void)argc;\n\t(void)argv;\n\tsrand(static_cast(time(NULL)));\n\t\/\/{\/\/ 1.\n \/\/       dariadb::storage::BaseStorage_ptr ms{ new dariadb::storage::MemoryStorage{ 512 } };\n\t\/\/\tauto start = clock();\n\n\t\/\/\twriter_1(ms);\n\n\t\/\/\tauto elapsed = ((float)clock() - start) \/ CLOCKS_PER_SEC;\n\t\/\/\tstd::cout << \"1. insert : \" << elapsed << std::endl;\n\t\/\/}\n\t\/\/\n    dariadb::storage::BaseStorage_ptr ms{ new dariadb::storage::MemoryStorage{ 512 } };\n\n\t{\/\/ 2.\n\t\tconst size_t threads_count = 16;\n\t\tconst size_t id_per_thread = size_t(32768 \/ threads_count);\n\n\t\tauto start = clock();\n\t\tstd::vector writers(threads_count);\n\t\tsize_t pos = 0;\n\t\tfor (size_t i = 0; i < threads_count; i++) {\n\t\t\tstd::thread t{ writer_2, id_per_thread*i+1, id_per_thread, ms };\n\t\t\twriters[pos++] = std::move(t);\n\t\t}\n\n\t\tpos = 0;\n\t\tfor (size_t i = 0; i < threads_count; i++) {\n\t\t\tstd::thread t = std::move(writers[pos++]);\n\t\t\tt.join();\n\t\t}\n\n\t\tauto elapsed = ((float)clock() - start) \/ CLOCKS_PER_SEC;\n\t\tstd::cout << \"2. insert : \" << elapsed << std::endl;\n\t}\n\t\/\/{\/\/3\n\t\/\/\tstd::random_device r;\n\t\/\/\tstd::default_random_engine e1(r());\n\t\/\/\tstd::uniform_int_distribution uniform_dist(0, 32768);\n\t\/\/\tstd::uniform_int_distribution uniform_dist_t(0, 32768);\n\t\/\/\tdariadb::IdArray ids;\n\t\/\/\tids.resize(1);\n\n \/\/       const size_t queries_count = 32768;\n\n \/\/       dariadb::IdArray rnd_ids(queries_count);\n \/\/       std::vector rnd_time(queries_count);\n \/\/       for (size_t i = 0; i < queries_count; i++){\n \/\/           rnd_ids[i]=uniform_dist(e1);\n \/\/           rnd_time[i]=uniform_dist_t(e1);\n \/\/       }\n\t\/\/\tdariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };\n\n\t\/\/\tauto start = clock();\n\t\/\/\t\n\t\/\/\tfor (size_t i = 0; i < queries_count; i++) {\n \/\/           ids[0]= rnd_ids[i];\n \/\/           auto t = rnd_time[i];\n\t\/\/\t\tauto rdr=ms->readInTimePoint(ids,0,t);\n\t\/\/\t\trdr->readAll(clbk.get());\n\t\/\/\t}\n\n\t\/\/\tauto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC)\/ queries_count;\n\t\/\/\tstd::cout << \"3. time point: \" << elapsed << std::endl;\n\t\/\/}\n\n\t\/\/{\/\/4\n\t\/\/\tstd::random_device r;\n\t\/\/\tstd::default_random_engine e1(r());\n\t\/\/\tstd::uniform_int_distribution uniform_dist(0, 32768);\n\n \/\/       const size_t queries_count = 32;\n\n\t\/\/\tdariadb::IdArray ids;\n \/\/       std::vector rnd_time(queries_count);\n \/\/       for (size_t i = 0; i < queries_count; i++){\n \/\/           rnd_time[i]=uniform_dist(e1);\n \/\/       }\n\n\t\/\/\tdariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };\n\n\t\/\/\tauto start = clock();\n\n\t\/\/\tfor (size_t i = 0; i < queries_count; i++) {\n \/\/           auto t = rnd_time[i];\n\t\/\/\t\tauto rdr=ms->readInTimePoint(ids, 0,t);\n\t\/\/\t\trdr->readAll(clbk.get());\n\t\/\/\t}\n\n\t\/\/\tauto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC) \/ queries_count;\n\t\/\/\tstd::cout << \"4. time point: \" << elapsed << std::endl;\n\t\/\/}\n\n\n\t\/\/{\/\/5\n\t\/\/\tstd::random_device r;\n\t\/\/\tstd::default_random_engine e1(r());\n\t\/\/\tstd::uniform_int_distribution uniform_dist(0, 32768\/2);\n\n\t\/\/\tdariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };\n\t\/\/\tconst size_t queries_count = 32;\n\n \/\/       std::vector rnd_time_from(queries_count),rnd_time_to(queries_count);\n \/\/       for (size_t i = 0; i < queries_count; i++){\n \/\/           rnd_time_from[i]=uniform_dist(e1);\n \/\/           rnd_time_to[i]=uniform_dist(e1);\n \/\/       }\n\n\t\/\/\tauto start = clock();\n\n\t\/\/\tfor (size_t i = 0; i < queries_count; i++) {\n \/\/           auto f = rnd_time_from[i];\n \/\/           auto t = rnd_time_to[i];\n\t\/\/\t\tauto rdr = ms->readInterval(f, t+f);\n\t\/\/\t\trdr->readAll(clbk.get());\n\t\/\/\t}\n\n\t\/\/\tauto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC) \/ queries_count;\n\t\/\/\tstd::cout << \"5. interval: \" << elapsed << std::endl;\n\t\/\/}\n\n\n\t\/\/{\/\/6\n\t\/\/\tstd::random_device r;\n\t\/\/\tstd::default_random_engine e1(r());\n\t\/\/\tstd::uniform_int_distribution uniform_dist(0, 32768\/2);\n\t\/\/\tstd::uniform_int_distribution uniform_dist_id(0, 32768);\n\n\t\/\/\tconst size_t ids_count = size_t(32768 * 0.1);\n\t\/\/\tdariadb::IdArray ids;\n\t\/\/\tids.resize(ids_count);\n\n\t\/\/\tdariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };\n\t\/\/\tconst size_t queries_count = 32;\n\n \/\/       std::vector rnd_time_from(queries_count),rnd_time_to(queries_count);\n \/\/       for (size_t i = 0; i < queries_count; i++){\n \/\/           rnd_time_from[i]=uniform_dist(e1);\n \/\/           rnd_time_to[i]=uniform_dist(e1);\n \/\/       }\n\n\t\/\/\tauto start = clock();\n\n\t\/\/\tfor (size_t i = 0; i < queries_count; i++) {\n\t\/\/\t\tfor (size_t j = 0; j < ids_count; j++) {\n\t\/\/\t\t\tids[j] = uniform_dist_id(e1);\n\t\/\/\t\t}\n \/\/           auto f = rnd_time_from[i];\n \/\/           auto t = rnd_time_to[i];\n\t\/\/\t\tauto rdr = ms->readInterval(ids,0, f, t + f);\n\t\/\/\t\trdr->readAll(clbk.get());\n\t\/\/\t}\n\n\t\/\/\tauto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC) \/ queries_count;\n\t\/\/\tstd::cout << \"6. interval: \" << elapsed << std::endl;\n\t\/\/}\n}\nuncomment.#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass BenchCallback :public dariadb::storage::ReaderClb {\npublic:\n\tvoid call(const dariadb::Meas&) {\n\t\tcount++;\n\t}\n\tsize_t count;\n};\n\nvoid writer_1(dariadb::storage::BaseStorage_ptr ms)\n{\n\tauto m = dariadb::Meas::empty();\n\tdariadb::Time t = 0;\n\tfor (dariadb::Id i = 0; i < 32768; i += 1) {\n\t\tm.id = i;\n\t\tm.flag = dariadb::Flag(0);\n\t\tm.time = t;\n\t\tm.value = dariadb::Value(i);\n\t\tms->append(m);\n\t\tt++;\n\t}\n}\n\nstd::atomic_long writen{ 0 };\n\nvoid writer_2(dariadb::Id id_from, size_t id_per_thread, dariadb::storage::BaseStorage_ptr ms)\n{\n\tauto m = dariadb::Meas::empty();\n\tstd::random_device r;\n\tstd::default_random_engine e1(r());\n\tstd::uniform_int_distribution uniform_dist(10, 64);\n\n    size_t max_id=(id_from + id_per_thread);\n   \n\n    for (dariadb::Id i = id_from; i < max_id; i += 1) {\n\t\tdariadb::Value v = 1.0;\n        auto max_rnd = uniform_dist(e1);\n\t\tdariadb::Time t = dariadb::timeutil::current_time();\n\t\tfor (dariadb::Time p = 0; p < dariadb::Time(max_rnd); p++) {\n\t\t\tm.id = i;\n\t\t\tm.flag = dariadb::Flag(0);\n\t\t\tm.time = t++;\n\t\t\tm.value = v;\n\t\t\tms->append(m);\n\t\t\twriten++;\n\t\t\tauto rnd = rand() \/ float(RAND_MAX);\n\n\t\t\tv += rnd;\n\t\t}\n\n\t}\n}\n\nint main(int argc, char *argv[]) {\n\t(void)argc;\n\t(void)argv;\n\tsrand(static_cast(time(NULL)));\n\t{\/\/ 1.\n        dariadb::storage::BaseStorage_ptr ms{ new dariadb::storage::MemoryStorage{ 512 } };\n\t\tauto start = clock();\n\n\t\twriter_1(ms);\n\n\t\tauto elapsed = ((float)clock() - start) \/ CLOCKS_PER_SEC;\n\t\tstd::cout << \"1. insert : \" << elapsed << std::endl;\n\t}\n\t\n    dariadb::storage::BaseStorage_ptr ms{ new dariadb::storage::MemoryStorage{ 512 } };\n\n\t{\/\/ 2.\n\t\tconst size_t threads_count = 16;\n\t\tconst size_t id_per_thread = size_t(32768 \/ threads_count);\n\n\t\tauto start = clock();\n\t\tstd::vector writers(threads_count);\n\t\tsize_t pos = 0;\n\t\tfor (size_t i = 0; i < threads_count; i++) {\n\t\t\tstd::thread t{ writer_2, id_per_thread*i+1, id_per_thread, ms };\n\t\t\twriters[pos++] = std::move(t);\n\t\t}\n\n\t\tpos = 0;\n\t\tfor (size_t i = 0; i < threads_count; i++) {\n\t\t\tstd::thread t = std::move(writers[pos++]);\n\t\t\tt.join();\n\t\t}\n\n\t\tauto elapsed = ((float)clock() - start) \/ CLOCKS_PER_SEC;\n\t\tstd::cout << \"2. insert : \" << elapsed << std::endl;\n\t}\n\t{\/\/3\n\t\tstd::random_device r;\n\t\tstd::default_random_engine e1(r());\n\t\tstd::uniform_int_distribution uniform_dist(0, 32768);\n\t\tstd::uniform_int_distribution uniform_dist_t(0, 32768);\n\t\tdariadb::IdArray ids;\n\t\tids.resize(1);\n\n        const size_t queries_count = 32768;\n\n        dariadb::IdArray rnd_ids(queries_count);\n        std::vector rnd_time(queries_count);\n        for (size_t i = 0; i < queries_count; i++){\n            rnd_ids[i]=uniform_dist(e1);\n            rnd_time[i]=uniform_dist_t(e1);\n        }\n\t\tdariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };\n\n\t\tauto start = clock();\n\t\t\n\t\tfor (size_t i = 0; i < queries_count; i++) {\n            ids[0]= rnd_ids[i];\n            auto t = rnd_time[i];\n\t\t\tauto rdr=ms->readInTimePoint(ids,0,t);\n\t\t\trdr->readAll(clbk.get());\n\t\t}\n\n\t\tauto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC)\/ queries_count;\n\t\tstd::cout << \"3. time point: \" << elapsed << std::endl;\n\t}\n\n\t{\/\/4\n\t\tstd::random_device r;\n\t\tstd::default_random_engine e1(r());\n\t\tstd::uniform_int_distribution uniform_dist(0, 32768);\n\n        const size_t queries_count = 32;\n\n\t\tdariadb::IdArray ids;\n        std::vector rnd_time(queries_count);\n        for (size_t i = 0; i < queries_count; i++){\n            rnd_time[i]=uniform_dist(e1);\n        }\n\n\t\tdariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };\n\n\t\tauto start = clock();\n\n\t\tfor (size_t i = 0; i < queries_count; i++) {\n            auto t = rnd_time[i];\n\t\t\tauto rdr=ms->readInTimePoint(ids, 0,t);\n\t\t\trdr->readAll(clbk.get());\n\t\t}\n\n\t\tauto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC) \/ queries_count;\n\t\tstd::cout << \"4. time point: \" << elapsed << std::endl;\n\t}\n\n\n\t{\/\/5\n\t\tstd::random_device r;\n\t\tstd::default_random_engine e1(r());\n\t\tstd::uniform_int_distribution uniform_dist(0, 32768\/2);\n\n\t\tdariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };\n\t\tconst size_t queries_count = 32;\n\n        std::vector rnd_time_from(queries_count),rnd_time_to(queries_count);\n        for (size_t i = 0; i < queries_count; i++){\n            rnd_time_from[i]=uniform_dist(e1);\n            rnd_time_to[i]=uniform_dist(e1);\n        }\n\n\t\tauto start = clock();\n\n\t\tfor (size_t i = 0; i < queries_count; i++) {\n            auto f = rnd_time_from[i];\n            auto t = rnd_time_to[i];\n\t\t\tauto rdr = ms->readInterval(f, t+f);\n\t\t\trdr->readAll(clbk.get());\n\t\t}\n\n\t\tauto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC) \/ queries_count;\n\t\tstd::cout << \"5. interval: \" << elapsed << std::endl;\n\t}\n\n\n\t{\/\/6\n\t\tstd::random_device r;\n\t\tstd::default_random_engine e1(r());\n\t\tstd::uniform_int_distribution uniform_dist(0, 32768\/2);\n\t\tstd::uniform_int_distribution uniform_dist_id(0, 32768);\n\n\t\tconst size_t ids_count = size_t(32768 * 0.1);\n\t\tdariadb::IdArray ids;\n\t\tids.resize(ids_count);\n\n\t\tdariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };\n\t\tconst size_t queries_count = 32;\n\n        std::vector rnd_time_from(queries_count),rnd_time_to(queries_count);\n        for (size_t i = 0; i < queries_count; i++){\n            rnd_time_from[i]=uniform_dist(e1);\n            rnd_time_to[i]=uniform_dist(e1);\n        }\n\n\t\tauto start = clock();\n\n\t\tfor (size_t i = 0; i < queries_count; i++) {\n\t\t\tfor (size_t j = 0; j < ids_count; j++) {\n\t\t\t\tids[j] = uniform_dist_id(e1);\n\t\t\t}\n            auto f = rnd_time_from[i];\n            auto t = rnd_time_to[i];\n\t\t\tauto rdr = ms->readInterval(ids,0, f, t + f);\n\t\t\trdr->readAll(clbk.get());\n\t\t}\n\n\t\tauto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC) \/ queries_count;\n\t\tstd::cout << \"6. interval: \" << elapsed << std::endl;\n\t}\n}\n<|endoftext|>"}
{"text":"PWGPP-485- bug fix in make histograms (#995)<|endoftext|>"}
{"text":"\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n *                                                                        *\n * Author: The ALICE Off-line Project.                                    *\n * Contributors are mentioned in the code where appropriate.              *\n *                                                                        *\n * Permission to use, copy, modify and distribute this software and its   *\n * documentation strictly for non-commercial purposes is hereby granted   *\n * without fee, provided that the above copyright notice appears in all   *\n * copies and that both the copyright notice and this permission notice   *\n * appear in the supporting documentation. The authors make no claims     *\n * about the suitability of this software for any purpose. It is          *\n * provided \"as is\" without express or implied warranty.                  *\n **************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/                                                                           \/\/\n\/\/  Class to read the file coming from DCS containing the information        \/\/\n\/\/  from LHC. Everything is stored in a TMap, where:                         \/\/\n\/\/  Key   --> DP name, as passed by LHC                                      \/\/ \n\/\/  value --> TObjArray of AliDCSArray objects                               \/\/\n\/\/                                                                           \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"AliDCSArray.h\"\n#include \"AliLHCReader.h\"\n#include \"AliLog.h\"\n\n\/\/--------------------------------------------------------------------------\nAliLHCReader::AliLHCReader():\n\tTObject(),\n\tfStartTime(0),\n\tfEndTime(0)\n{\n\t\/\/ default ctor \n}\n\n\/\/--------------------------------------------------------------------------\nAliLHCReader::~AliLHCReader()\n{\n\t\/\/\n\t\/\/ dtor \n\t\/\/\n}\n\n\/\/--------------------------------------------------------------------------\nTMap* AliLHCReader::ReadLHCDP(TString filename)\n{\n\t\/\/\n\t\/\/ reading the file with the inputs\n\t\/\/\n\n       \tif( gSystem->AccessPathName( filename.Data() ) ) {\n\t\tAliError(Form( \"file (%s) not found\", filename.Data() ) );\n\t\treturn NULL;\n\t}\n\n\tifstream *file = new ifstream ( filename.Data() );\n\tif (!*file) {\n\t\tAliError(Form(\"Error opening file (%s) !\",filename.Data()));\n\t\tfile->close();\n\t\tdelete file;\n\t\treturn NULL;\n\t}\n\tTMap* mapLHC = new TMap();\n\t\/\/\tmapLHC->SetOwner(1);\n\tTString strLine;\n\tInt_t lhcEntries;\n\tInt_t nBlocks = 0;\n\t\/\/\tTObjArray** array;\n\tInt_t nline =0;\n\twhile(strLine.ReadLine(*file)){\n\t\tnline++;\n\t\tAliDebug(3,Form(\"line n. = %d\",nline));\n\t\t\/\/ tokenize the line with tabs\n\t\t\/\/if (strLine.BeginsWith(\"=\")) continue;\n\t\t\/\/if (!strLine.CompareTo(\"END_OF_BLOCK\")) {\n\t\tif (strLine.Contains(\"END_OF_BLOCK\")) {\n\t\t\tAliInfo(\"END_OF_BLOCK\");\n\t\t\tnBlocks++;\n\t\t\tcontinue;\n\t\t}\n\t\tTObjArray* tokens = strLine.Tokenize(\"\\t\");\n\t\tInt_t ntokens = tokens->GetEntriesFast();\n\t\tAliDebug(3,Form(\"Number of tokens = %d\",ntokens));\n\t\tif (ntokens == 2 && !(((TObjString*)tokens->At(0))->String()).CompareTo(\"LHC_ENTRIES\")){\n\t\t\tlhcEntries = (((TObjString*)tokens->At(1))->String()).Atoi();\n\t\t\tAliInfo(Form(\"LHC entries = %d\",lhcEntries));\n\t\t\tAliDebug(3,Form(\"LHC entries = %d\",lhcEntries));\n\t\t\tcontinue;\n\t\t}\n\t\tif (ntokens == 1 && !(((TObjString*)tokens->At(0))->String()).CompareTo(\"END_OF_DATA\")){\n\t\t\tAliInfo(\"End of file reached\");\n\t\t\tbreak;\n\t\t}\n\t\tif (ntokens < 4){  \n\t\t\tAliInfo(Form(\"Wrong number of tokens --> # tokens = %d at line %d\",ntokens,nline));\n\t\t\t\/\/ requiring at least the index of the DP, the DP name, the format, and the number of entries\n\t\t\tdelete tokens;\n\t\t\tcontinue;\n\t\t}\n\t\tInt_t lhcDPindex = (((TObjString*)tokens->At(0))->String()).Atoi();\n\t\tAliDebug(2,Form(\"lhcDPindex = %d\",lhcDPindex));\n\t\tTObjString* lhcDPname = (TObjString*)tokens->At(1);\n\t\tTString lhcDPtype = ((TObjString*)tokens->At(2))->String();\n\t\tAliInfo(Form(\"lhcDPname = %s\",(lhcDPname->String()).Data()));\n\t\tAliDebug(2,Form(\"lhcDPtype = %s\",lhcDPtype.Data()));\n\t\tTObjArray* typeTokens = lhcDPtype.Tokenize(\":\");\n\t\tif (typeTokens->GetEntriesFast() < 2 ){  \n\t\t\t\/\/ requiring the the type and the number of elements for each measurement\n\t\t\tAliError(Form(\"The format does not match the expected one, skipping the current line for DP = %s\", lhcDPtype.Data()));\n\t\t\tdelete typeTokens;\n\t\t\tcontinue;\n\t\t}\n\t\tTString type = ((TObjString*)typeTokens->At(0))->String();\n\t\tAliDebug(2,Form(\"type = %s\",type.Data()));\n      \t\tInt_t nelements = (((TObjString*)typeTokens->At(1))->String()).Atoi();\n\t\tAliDebug(2,Form(\"nelements = %i\",nelements));\n\t\tInt_t nentries = (((TObjString*)tokens->At(3))->String()).Atoi();\n\t\tAliDebug(2,Form(\"nentries = %i\",nentries));\n\t\tInt_t nValuesPerEntry = nelements+1;\n\t\tInt_t nfixed = 4; \/\/ n. of fixed entries\n\t\tTObjArray* array;\n\t\tif (mapLHC->GetValue(lhcDPname)==0x0){\n\t\t\tarray = new TObjArray();\n\t\t\tarray->SetOwner(1);\n\t\t}\n\t\telse{\n\t\t\tTPair* p = mapLHC->RemoveEntry(lhcDPname);\n\t\t\tarray = (TObjArray*)p->Value();\n\t\t\tAliDebug(2,Form(\"entry found! --> %p\",array));\n\t\t}\n\t\t\t\t\t\n\t\tfor (Int_t ientry=0; ientry< nentries; ientry ++){\n\t\t\tInt_t indextime = nfixed+nValuesPerEntry*ientry+nelements;\n\t\t\tTString strTimestamp = ((TObjString*)tokens->At(indextime))->String();\n\t\t\t\/\/\t\t\tTObjArray* timeTokens = strTimestamp.Tokenize(\".\");\n\t\t\t\/\/if (timeTokens->GetEntriesFast() < 2 ){  \n\t\t\t\/\/\t\/\/ requiring both the seconds and the nseconds for the timestamp\n\t\t\t\/\/\t\tAliError(Form(\"The timestamp format does not match the expected one, skipping entry %d for DP = %s\", ientry, lhcDPtype.Data()));\n\t\t\t\/\/\tcontinue;\n\t\t\t\/\/}\n\t\t\t\/\/time_t seconds = time_t((((TObjString*)timeTokens->At(0))->String()).Atoi());\n\t\t\t\/\/Int_t nseconds = Int_t((((TObjString*)timeTokens->At(1))->String()).Atoi());\n\t\t\t\/\/TTimeStamp* timestamp = new TTimeStamp(seconds, (Int_t)(nseconds*1E8));\n\t\t\tDouble_t timestamp = strTimestamp.Atof();\n\t\t\tAliDebug(2,Form(\"Timestamp in unix time = %f (s)\",timestamp));\n\t\t\tif (fStartTime!=0 && fEndTime!=0 && (fStartTime > timestamp || fEndTime < timestamp)){\n\t\t\t\t\/\/ error in case the measurement is not within the data taking time interval\n\t\t\t\tAliError(Form(\"Timestamp for entry %d of DP %s not in [%d,%d]\", ientry, lhcDPtype.Data(),fStartTime,fEndTime));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (type == \"i\"){\n\t\t\t\tInt_t* value = new Int_t[nelements];\n\t\t\t\tfor (Int_t ielement=0; ielementAt(nfixed+ielement+ientry*nValuesPerEntry))->String()).Atoi();\n\t\t\t\t\tAliDebug(2,Form(\"Value at index %d = %d\",nfixed+ielement+ientry*nValuesPerEntry,value[ielement]));\n\t\t\t\t}\n\t\t\t\tAliDCSArray* dcs = new AliDCSArray(nelements,value,timestamp);\n\t\t\t\tarray->Add(dcs);\n\t\t\t}\n\t\t\telse if (type == \"b\"){\n\t\t\t\tBool_t* value = new Bool_t[nelements];\n\t\t\t\tfor (Int_t ielement=0; ielementAt(nfixed+ielement+ientry*nValuesPerEntry))->String()).Atoi());\n\t\t\t\t\tAliDebug(2,Form(\"Value at index %d = %d\",nfixed+ielement+ientry*nValuesPerEntry,Int_t(value[ielement])));\n\t\t\t\t}\n\t\t\t\tAliDCSArray* dcs = new AliDCSArray(nelements,value,timestamp);\n\t\t\t\tarray->Add(dcs);\n\t\t\t}\n\t\t\telse if (type == \"f\"){ \/\/ the floats should be considered as doubles\n\t\t\t\tDouble_t* value = new Double_t[nelements];\n\t\t\t\tfor (Int_t ielement=0; ielementAt(nfixed+ielement+ientry*nValuesPerEntry))->String());\n\t\t\t\t\tvalue[ielement] = (((TObjString*)tokens->At(nfixed+ielement+ientry*nValuesPerEntry))->String()).Atof();\n\t\t\t\t\tAliDebug(2,Form(\"Value at index %d = %f from string %s\",nfixed+ielement+ientry*nValuesPerEntry,value[ielement],tempstr.Data()));\n\t\t\t\t} \n\t\t\t\tAliDCSArray* dcs = new AliDCSArray(nelements,value,timestamp);\n\t\t\t\tarray->Add(dcs);\n\t\t\t} \n\t\t\telse if (type == \"s\"){\n\t\t\t\tTObjArray* value = new TObjArray();\n\t\t\t\tfor (Int_t ielement=0; ielementAt(nfixed+ielement+ientry*nValuesPerEntry));\n\t\t\t\t\tAliDebug(2,Form(\"Value at index %d = %s\",nfixed+ielement+ientry*nValuesPerEntry,(strobj->String()).Data()));\n\t\t\t\t\tvalue->Add(strobj);\n\t\t\t\t}\n\t\t\t\tAliDCSArray* dcs = new AliDCSArray(nelements,value,timestamp);\n\t\t\t\tarray->Add(dcs);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tAliError(Form(\"Non-expected type %s\",type.Data()));\n\t\t\t\treturn NULL;\n\t\t\t} \n\t\t}\n\t\tmapLHC->Add(lhcDPname,array);\t\t\t\n\t}\n\t\/\/mapLHC->Print();\n\treturn mapLHC;\n}\n\n\t\t\t\t\n\n\n\n\n\n\nChanging AliInfo in AliDebug.\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n *                                                                        *\n * Author: The ALICE Off-line Project.                                    *\n * Contributors are mentioned in the code where appropriate.              *\n *                                                                        *\n * Permission to use, copy, modify and distribute this software and its   *\n * documentation strictly for non-commercial purposes is hereby granted   *\n * without fee, provided that the above copyright notice appears in all   *\n * copies and that both the copyright notice and this permission notice   *\n * appear in the supporting documentation. The authors make no claims     *\n * about the suitability of this software for any purpose. It is          *\n * provided \"as is\" without express or implied warranty.                  *\n **************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/                                                                           \/\/\n\/\/  Class to read the file coming from DCS containing the information        \/\/\n\/\/  from LHC. Everything is stored in a TMap, where:                         \/\/\n\/\/  Key   --> DP name, as passed by LHC                                      \/\/ \n\/\/  value --> TObjArray of AliDCSArray objects                               \/\/\n\/\/                                                                           \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"AliDCSArray.h\"\n#include \"AliLHCReader.h\"\n#include \"AliLog.h\"\n\n\/\/--------------------------------------------------------------------------\nAliLHCReader::AliLHCReader():\n\tTObject(),\n\tfStartTime(0),\n\tfEndTime(0)\n{\n\t\/\/ default ctor \n}\n\n\/\/--------------------------------------------------------------------------\nAliLHCReader::~AliLHCReader()\n{\n\t\/\/\n\t\/\/ dtor \n\t\/\/\n}\n\n\/\/--------------------------------------------------------------------------\nTMap* AliLHCReader::ReadLHCDP(TString filename)\n{\n\t\/\/\n\t\/\/ reading the file with the inputs\n\t\/\/\n\n       \tif( gSystem->AccessPathName( filename.Data() ) ) {\n\t\tAliError(Form( \"file (%s) not found\", filename.Data() ) );\n\t\treturn NULL;\n\t}\n\n\tifstream *file = new ifstream ( filename.Data() );\n\tif (!*file) {\n\t\tAliError(Form(\"Error opening file (%s) !\",filename.Data()));\n\t\tfile->close();\n\t\tdelete file;\n\t\treturn NULL;\n\t}\n\tTMap* mapLHC = new TMap();\n\t\/\/\tmapLHC->SetOwner(1);\n\tTString strLine;\n\tInt_t lhcEntries;\n\tInt_t nBlocks = 0;\n\t\/\/\tTObjArray** array;\n\tInt_t nline =0;\n\twhile(strLine.ReadLine(*file)){\n\t\tnline++;\n\t\tAliDebug(3,Form(\"line n. = %d\",nline));\n\t\t\/\/ tokenize the line with tabs\n\t\t\/\/if (strLine.BeginsWith(\"=\")) continue;\n\t\t\/\/if (!strLine.CompareTo(\"END_OF_BLOCK\")) {\n\t\tif (strLine.Contains(\"END_OF_BLOCK\")) {\n\t\t\tAliDebug(2,\"END_OF_BLOCK\");\n\t\t\tnBlocks++;\n\t\t\tcontinue;\n\t\t}\n\t\tTObjArray* tokens = strLine.Tokenize(\"\\t\");\n\t\tInt_t ntokens = tokens->GetEntriesFast();\n\t\tAliDebug(3,Form(\"Number of tokens = %d\",ntokens));\n\t\tif (ntokens == 2 && !(((TObjString*)tokens->At(0))->String()).CompareTo(\"LHC_ENTRIES\")){\n\t\t\tlhcEntries = (((TObjString*)tokens->At(1))->String()).Atoi();\n\t\t\tAliInfo(Form(\"LHC entries = %d\",lhcEntries));\n\t\t\tAliDebug(3,Form(\"LHC entries = %d\",lhcEntries));\n\t\t\tcontinue;\n\t\t}\n\t\tif (ntokens == 1 && !(((TObjString*)tokens->At(0))->String()).CompareTo(\"END_OF_DATA\")){\n\t\t\tAliDebug(2,\"End of file reached\");\n\t\t\tbreak;\n\t\t}\n\t\tif (ntokens < 4){  \n\t\t\tAliInfo(Form(\"Wrong number of tokens --> # tokens = %d at line %d\",ntokens,nline));\n\t\t\t\/\/ requiring at least the index of the DP, the DP name, the format, and the number of entries\n\t\t\tdelete tokens;\n\t\t\tcontinue;\n\t\t}\n\t\tInt_t lhcDPindex = (((TObjString*)tokens->At(0))->String()).Atoi();\n\t\tAliDebug(2,Form(\"lhcDPindex = %d\",lhcDPindex));\n\t\tTObjString* lhcDPname = (TObjString*)tokens->At(1);\n\t\tTString lhcDPtype = ((TObjString*)tokens->At(2))->String();\n\t\tAliDebug(2,Form(\"lhcDPname = %s\",(lhcDPname->String()).Data()));\n\t\tAliDebug(2,Form(\"lhcDPtype = %s\",lhcDPtype.Data()));\n\t\tTObjArray* typeTokens = lhcDPtype.Tokenize(\":\");\n\t\tif (typeTokens->GetEntriesFast() < 2 ){  \n\t\t\t\/\/ requiring the the type and the number of elements for each measurement\n\t\t\tAliError(Form(\"The format does not match the expected one, skipping the current line for DP = %s\", lhcDPtype.Data()));\n\t\t\tdelete typeTokens;\n\t\t\tcontinue;\n\t\t}\n\t\tTString type = ((TObjString*)typeTokens->At(0))->String();\n\t\tAliDebug(2,Form(\"type = %s\",type.Data()));\n      \t\tInt_t nelements = (((TObjString*)typeTokens->At(1))->String()).Atoi();\n\t\tAliDebug(2,Form(\"nelements = %i\",nelements));\n\t\tInt_t nentries = (((TObjString*)tokens->At(3))->String()).Atoi();\n\t\tAliDebug(2,Form(\"nentries = %i\",nentries));\n\t\tInt_t nValuesPerEntry = nelements+1;\n\t\tInt_t nfixed = 4; \/\/ n. of fixed entries\n\t\tTObjArray* array;\n\t\tif (mapLHC->GetValue(lhcDPname)==0x0){\n\t\t\tarray = new TObjArray();\n\t\t\tarray->SetOwner(1);\n\t\t}\n\t\telse{\n\t\t\tTPair* p = mapLHC->RemoveEntry(lhcDPname);\n\t\t\tarray = (TObjArray*)p->Value();\n\t\t\tAliDebug(2,Form(\"entry found! --> %p\",array));\n\t\t}\n\t\t\t\t\t\n\t\tfor (Int_t ientry=0; ientry< nentries; ientry ++){\n\t\t\tInt_t indextime = nfixed+nValuesPerEntry*ientry+nelements;\n\t\t\tTString strTimestamp = ((TObjString*)tokens->At(indextime))->String();\n\t\t\t\/\/\t\t\tTObjArray* timeTokens = strTimestamp.Tokenize(\".\");\n\t\t\t\/\/if (timeTokens->GetEntriesFast() < 2 ){  \n\t\t\t\/\/\t\/\/ requiring both the seconds and the nseconds for the timestamp\n\t\t\t\/\/\t\tAliError(Form(\"The timestamp format does not match the expected one, skipping entry %d for DP = %s\", ientry, lhcDPtype.Data()));\n\t\t\t\/\/\tcontinue;\n\t\t\t\/\/}\n\t\t\t\/\/time_t seconds = time_t((((TObjString*)timeTokens->At(0))->String()).Atoi());\n\t\t\t\/\/Int_t nseconds = Int_t((((TObjString*)timeTokens->At(1))->String()).Atoi());\n\t\t\t\/\/TTimeStamp* timestamp = new TTimeStamp(seconds, (Int_t)(nseconds*1E8));\n\t\t\tDouble_t timestamp = strTimestamp.Atof();\n\t\t\tAliDebug(2,Form(\"Timestamp in unix time = %f (s)\",timestamp));\n\t\t\tif (fStartTime!=0 && fEndTime!=0 && (fStartTime > timestamp || fEndTime < timestamp)){\n\t\t\t\t\/\/ error in case the measurement is not within the data taking time interval\n\t\t\t\tAliError(Form(\"Timestamp for entry %d of DP %s not in [%d,%d]\", ientry, lhcDPtype.Data(),fStartTime,fEndTime));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (type == \"i\"){\n\t\t\t\tInt_t* value = new Int_t[nelements];\n\t\t\t\tfor (Int_t ielement=0; ielementAt(nfixed+ielement+ientry*nValuesPerEntry))->String()).Atoi();\n\t\t\t\t\tAliDebug(2,Form(\"Value at index %d = %d\",nfixed+ielement+ientry*nValuesPerEntry,value[ielement]));\n\t\t\t\t}\n\t\t\t\tAliDCSArray* dcs = new AliDCSArray(nelements,value,timestamp);\n\t\t\t\tarray->Add(dcs);\n\t\t\t}\n\t\t\telse if (type == \"b\"){\n\t\t\t\tBool_t* value = new Bool_t[nelements];\n\t\t\t\tfor (Int_t ielement=0; ielementAt(nfixed+ielement+ientry*nValuesPerEntry))->String()).Atoi());\n\t\t\t\t\tAliDebug(2,Form(\"Value at index %d = %d\",nfixed+ielement+ientry*nValuesPerEntry,Int_t(value[ielement])));\n\t\t\t\t}\n\t\t\t\tAliDCSArray* dcs = new AliDCSArray(nelements,value,timestamp);\n\t\t\t\tarray->Add(dcs);\n\t\t\t}\n\t\t\telse if (type == \"f\"){ \/\/ the floats should be considered as doubles\n\t\t\t\tDouble_t* value = new Double_t[nelements];\n\t\t\t\tfor (Int_t ielement=0; ielementAt(nfixed+ielement+ientry*nValuesPerEntry))->String());\n\t\t\t\t\tvalue[ielement] = (((TObjString*)tokens->At(nfixed+ielement+ientry*nValuesPerEntry))->String()).Atof();\n\t\t\t\t\tAliDebug(2,Form(\"Value at index %d = %f from string %s\",nfixed+ielement+ientry*nValuesPerEntry,value[ielement],tempstr.Data()));\n\t\t\t\t} \n\t\t\t\tAliDCSArray* dcs = new AliDCSArray(nelements,value,timestamp);\n\t\t\t\tarray->Add(dcs);\n\t\t\t} \n\t\t\telse if (type == \"s\"){\n\t\t\t\tTObjArray* value = new TObjArray();\n\t\t\t\tfor (Int_t ielement=0; ielementAt(nfixed+ielement+ientry*nValuesPerEntry));\n\t\t\t\t\tAliDebug(2,Form(\"Value at index %d = %s\",nfixed+ielement+ientry*nValuesPerEntry,(strobj->String()).Data()));\n\t\t\t\t\tvalue->Add(strobj);\n\t\t\t\t}\n\t\t\t\tAliDCSArray* dcs = new AliDCSArray(nelements,value,timestamp);\n\t\t\t\tarray->Add(dcs);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tAliError(Form(\"Non-expected type %s\",type.Data()));\n\t\t\t\treturn NULL;\n\t\t\t} \n\t\t}\n\t\tmapLHC->Add(lhcDPname,array);\t\t\t\n\t}\n\t\/\/mapLHC->Print();\n\treturn mapLHC;\n}\n\n\n\n\n\n\n\n<|endoftext|>"}
{"text":"\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2010 Sage Weil \n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GPL.\n * \n *\/\n\n\n\/*\n    FUSE: Filesystem in Userspace\n    Copyright (C) 2001-2005  Miklos Szeredi \n\n    This program can be distributed under the terms of the GNU GPL.\n    See the file COPYING.\n*\/\n\n\n\/\/ fuse crap\n#ifdef linux\n\/* For pread()\/pwrite() *\/\n#define _XOPEN_SOURCE 500\n#endif\n\n#define FUSE_USE_VERSION 26\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/ ceph stuff\n#include \"include\/types.h\"\n\n#include \"Client.h\"\n\n#include \"config.h\"\n\n\/\/ globals\nstatic Client *client;     \/\/ the ceph client\n\n\n\n\/\/ ------\n\/\/ fuse hooks\n\nstatic int ceph_getattr(const char *path, struct stat *stbuf)\n{\n  return client->lstat(path, stbuf);\n}\n\nstatic int ceph_readlink(const char *path, char *buf, size_t size)\n{\n  int res;\n\n  res = client->readlink(path, buf, size - 1);\n  if (res < 0) return res;\n  \n  buf[res] = '\\0';\n  return 0;\n}\n\nstatic int ceph_mknod(const char *path, mode_t mode, dev_t rdev) \n{\n  return client->mknod(path, mode);\n}\n\nstatic int ceph_mkdir(const char *path, mode_t mode)\n{\n  return client->mkdir(path, mode);\n}\n\nstatic int ceph_unlink(const char *path)\n{\n  return client->unlink(path);\n}\n\nstatic int ceph_rmdir(const char *path)\n{\n  return client->rmdir(path);\n}\n\nstatic int ceph_symlink(const char *from, const char *to)\n{\n  return client->symlink(from, to);\n}\n\nstatic int ceph_rename(const char *from, const char *to)\n{\n  return client->rename(from, to);\n}\n\nstatic int ceph_link(const char *from, const char *to)\n{\n  return client->link(from, to);\n}\n\nstatic int ceph_chmod(const char *path, mode_t mode)\n{\n  return client->chmod(path, mode);\n}\n\nstatic int ceph_chown(const char *path, uid_t uid, gid_t gid)\n{\n  return client->chown(path, uid, gid);\n}\n\nstatic int ceph_truncate(const char *path, off_t size)\n{\n  return client->truncate(path, size);      \n}\n\nstatic int ceph_utime(const char *path, struct utimbuf *buf)\n{\n  return client->utime(path, buf);\n}\n\n\n\/\/ ------------------\n\/\/ file i\/o\n\nstatic int ceph_open(const char *path, struct fuse_file_info *fi)\n{\n  int res;\n  \n  res = client->open(path, fi->flags, 0);\n  if (res < 0) return res;\n  fi->fh = res;\n  return 0;  \/\/ fuse wants 0 onsucess\n}\n\nstatic int ceph_read(const char *path, char *buf, size_t size, off_t offset,\n                     struct fuse_file_info *fi)\n{\n  int fd = fi->fh;\n  return client->read(fd, buf, size, offset);\n}\n\nstatic int ceph_write(const char *path, const char *buf, size_t size,\n                     off_t offset, struct fuse_file_info *fi)\n{\n  int fd = fi->fh;\n  return client->write(fd, buf, size, offset);\n}\n\nstatic int ceph_flush(const char *path, struct fuse_file_info *fi)\n{\n  \/\/int fh = fi->fh;\n  \/\/return client->flush(fh);\n  return 0;\n}\n\nstatic int ceph_statfs(const char *path, struct statvfs *stbuf)\n{\n  return client->statfs(path, stbuf);\n}\n\nstatic int ceph_release(const char *path, struct fuse_file_info *fi)\n{\n  int fd = fi->fh;\n  int r = client->close(fd);  \/\/ close the file\n  return r;\n}\n\nstatic int ceph_fsync(const char *path, int isdatasync,\n                     struct fuse_file_info *fi)\n{\n  int fd = fi->fh;\n  return client->fsync(fd, isdatasync ? true:false);\n}\n\n\n\/\/ ---------------------\n\/\/ directory i\/o\n\nstatic int ceph_opendir(const char *path, struct fuse_file_info *fi)\n{\n  DIR *dirp;\n  int r = client->opendir(path, &dirp);\n  if (r < 0) return r;\n  fi->fh = (uint64_t)(void*)dirp;\n  return 0;\n}\n\nstatic int ceph_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t off, fuse_file_info *fi)\n{\n  DIR *dirp = (DIR*)fi->fh;\n  \n  client->seekdir(dirp, off);\n\n  int res = 0;\n  struct dirent de;\n  struct stat st;\n  int stmask = 0;\n  while (res == 0) {\n    int r = client->readdirplus_r(dirp, &de, &st, &stmask);\n    if (r != 0) break;\n    int stneed = CEPH_STAT_CAP_TYPE;\n    res = filler(buf,\n                 de.d_name,\n\t\t ((stmask & stneed) == stneed) ? &st:0,\n\t\t client->telldir(dirp));\n  }\n  return 0;\n}\n\nstatic int ceph_releasedir(const char *path, struct fuse_file_info *fi)\n{\n  DIR *dirp = (DIR*)fi->fh;\n  int r = client->closedir(dirp);  \/\/ close the file\n  return r;\n}\n\n\n\n\n\nconst static struct fuse_operations ceph_oper = {\n  getattr: ceph_getattr,\n  readlink: ceph_readlink,\n  getdir: 0,\n  mknod: ceph_mknod,\n  mkdir: ceph_mkdir,\n  unlink: ceph_unlink,\n  rmdir: ceph_rmdir,\n  symlink: ceph_symlink,\n  rename: ceph_rename,\n  link: ceph_link,\n  chmod: ceph_chmod,\n  chown: ceph_chown,\n  truncate: ceph_truncate,\n  utime: ceph_utime,\n  open: ceph_open,\n  read: ceph_read,\n  write: ceph_write,\n  statfs: ceph_statfs,\n  flush: ceph_flush,   \n  release: ceph_release,\n  fsync: ceph_fsync,\n  setxattr: 0,\n  getxattr: 0,\n  listxattr: 0,\n  removexattr: 0,\n  opendir: ceph_opendir,\n  readdir: ceph_readdir,\n  releasedir: ceph_releasedir,\n  fsyncdir : 0,\n  init : 0,\n  destroy : 0,\n  access : 0,\n  create : 0,\n  ftruncate : 0,\n  fgetattr : 0,\n  lock : 0,\n  utimens : 0,\n  bmap : 0,\n  flag_nullpath_ok : 0,\n  flag_reserved : 0,\n  ioctl : 0,\n  poll : 0,\n};\n\n\nint ceph_fuse_main(Client *c, int argc, const char *argv[])\n{\n  \/\/ init client\n  client = c;\n\n  \/\/ set up fuse argc\/argv\n  int newargc = 0;\n  const char **newargv = (const char **) malloc((argc + 10) * sizeof(char *));\n  newargv[newargc++] = argv[0];\n  \n  \/\/ allow other (all!) users to see my file system\n  \/\/ NOTE: echo user_allow_other >> \/etc\/fuse.conf\n  \/\/ NB: seems broken on Darwin\n#ifndef DARWIN\n  newargv[newargc++] = \"-o\";\n  newargv[newargc++] = \"allow_other\";\n#endif \/\/ DARWIN\n  \n  \/\/ use inos\n  newargv[newargc++] = \"-o\";\n  newargv[newargc++] = \"use_ino\";\n\n  \/\/ large reads, direct_io (no kernel cachine)\n  \/\/newargv[newargc++] = \"-o\";\n  \/\/newargv[newargc++] = \"large_read\";\n  if (g_conf.fuse_direct_io) {\n    newargv[newargc++] = \"-o\";\n    newargv[newargc++] = \"direct_io\";\n  }\n\n  \/\/ disable stupid fuse unlink hiding thing\n  newargv[newargc++] = \"-o\";\n  newargv[newargc++] = \"hard_remove\";\n\n  \/\/ force into foreground\n  \/\/   -> we can watch stdout this way!!\n  newargv[newargc++] = \"-f\";\n  \n  \/\/ copy rest of cmdline (hopefully, the mount point!)\n  for (int argctr = 1; argctr < argc; argctr++) newargv[newargc++] = argv[argctr];\n  \n  \/\/ go fuse go\n  cout << \"ok, calling fuse_main\" << std::endl;\n  int r = fuse_main(newargc, (char**)newargv, &ceph_oper, 0);\n  return r;\n}\nRevert \"client\/fuse.cc: explicity zero fuse function ptrs\"\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2010 Sage Weil \n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GPL.\n * \n *\/\n\n\n\/*\n    FUSE: Filesystem in Userspace\n    Copyright (C) 2001-2005  Miklos Szeredi \n\n    This program can be distributed under the terms of the GNU GPL.\n    See the file COPYING.\n*\/\n\n\n\/\/ fuse crap\n#ifdef linux\n\/* For pread()\/pwrite() *\/\n#define _XOPEN_SOURCE 500\n#endif\n\n#define FUSE_USE_VERSION 26\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/ ceph stuff\n#include \"include\/types.h\"\n\n#include \"Client.h\"\n\n#include \"config.h\"\n\n\/\/ globals\nstatic Client *client;     \/\/ the ceph client\n\n\n\n\/\/ ------\n\/\/ fuse hooks\n\nstatic int ceph_getattr(const char *path, struct stat *stbuf)\n{\n  return client->lstat(path, stbuf);\n}\n\nstatic int ceph_readlink(const char *path, char *buf, size_t size)\n{\n  int res;\n\n  res = client->readlink(path, buf, size - 1);\n  if (res < 0) return res;\n  \n  buf[res] = '\\0';\n  return 0;\n}\n\nstatic int ceph_mknod(const char *path, mode_t mode, dev_t rdev) \n{\n  return client->mknod(path, mode);\n}\n\nstatic int ceph_mkdir(const char *path, mode_t mode)\n{\n  return client->mkdir(path, mode);\n}\n\nstatic int ceph_unlink(const char *path)\n{\n  return client->unlink(path);\n}\n\nstatic int ceph_rmdir(const char *path)\n{\n  return client->rmdir(path);\n}\n\nstatic int ceph_symlink(const char *from, const char *to)\n{\n  return client->symlink(from, to);\n}\n\nstatic int ceph_rename(const char *from, const char *to)\n{\n  return client->rename(from, to);\n}\n\nstatic int ceph_link(const char *from, const char *to)\n{\n  return client->link(from, to);\n}\n\nstatic int ceph_chmod(const char *path, mode_t mode)\n{\n  return client->chmod(path, mode);\n}\n\nstatic int ceph_chown(const char *path, uid_t uid, gid_t gid)\n{\n  return client->chown(path, uid, gid);\n}\n\nstatic int ceph_truncate(const char *path, off_t size)\n{\n  return client->truncate(path, size);      \n}\n\nstatic int ceph_utime(const char *path, struct utimbuf *buf)\n{\n  return client->utime(path, buf);\n}\n\n\n\/\/ ------------------\n\/\/ file i\/o\n\nstatic int ceph_open(const char *path, struct fuse_file_info *fi)\n{\n  int res;\n  \n  res = client->open(path, fi->flags, 0);\n  if (res < 0) return res;\n  fi->fh = res;\n  return 0;  \/\/ fuse wants 0 onsucess\n}\n\nstatic int ceph_read(const char *path, char *buf, size_t size, off_t offset,\n                     struct fuse_file_info *fi)\n{\n  int fd = fi->fh;\n  return client->read(fd, buf, size, offset);\n}\n\nstatic int ceph_write(const char *path, const char *buf, size_t size,\n                     off_t offset, struct fuse_file_info *fi)\n{\n  int fd = fi->fh;\n  return client->write(fd, buf, size, offset);\n}\n\nstatic int ceph_flush(const char *path, struct fuse_file_info *fi)\n{\n  \/\/int fh = fi->fh;\n  \/\/return client->flush(fh);\n  return 0;\n}\n\nstatic int ceph_statfs(const char *path, struct statvfs *stbuf)\n{\n  return client->statfs(path, stbuf);\n}\n\nstatic int ceph_release(const char *path, struct fuse_file_info *fi)\n{\n  int fd = fi->fh;\n  int r = client->close(fd);  \/\/ close the file\n  return r;\n}\n\nstatic int ceph_fsync(const char *path, int isdatasync,\n                     struct fuse_file_info *fi)\n{\n  int fd = fi->fh;\n  return client->fsync(fd, isdatasync ? true:false);\n}\n\n\n\/\/ ---------------------\n\/\/ directory i\/o\n\nstatic int ceph_opendir(const char *path, struct fuse_file_info *fi)\n{\n  DIR *dirp;\n  int r = client->opendir(path, &dirp);\n  if (r < 0) return r;\n  fi->fh = (uint64_t)(void*)dirp;\n  return 0;\n}\n\nstatic int ceph_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t off, fuse_file_info *fi)\n{\n  DIR *dirp = (DIR*)fi->fh;\n  \n  client->seekdir(dirp, off);\n\n  int res = 0;\n  struct dirent de;\n  struct stat st;\n  int stmask = 0;\n  while (res == 0) {\n    int r = client->readdirplus_r(dirp, &de, &st, &stmask);\n    if (r != 0) break;\n    int stneed = CEPH_STAT_CAP_TYPE;\n    res = filler(buf,\n                 de.d_name,\n\t\t ((stmask & stneed) == stneed) ? &st:0,\n\t\t client->telldir(dirp));\n  }\n  return 0;\n}\n\nstatic int ceph_releasedir(const char *path, struct fuse_file_info *fi)\n{\n  DIR *dirp = (DIR*)fi->fh;\n  int r = client->closedir(dirp);  \/\/ close the file\n  return r;\n}\n\n\n\n\n\nconst static struct fuse_operations ceph_oper = {\n  getattr: ceph_getattr,\n  readlink: ceph_readlink,\n  getdir: 0,\n  mknod: ceph_mknod,\n  mkdir: ceph_mkdir,\n  unlink: ceph_unlink,\n  rmdir: ceph_rmdir,\n  symlink: ceph_symlink,\n  rename: ceph_rename,\n  link: ceph_link,\n  chmod: ceph_chmod,\n  chown: ceph_chown,\n  truncate: ceph_truncate,\n  utime: ceph_utime,\n  open: ceph_open,\n  read: ceph_read,\n  write: ceph_write,\n  statfs: ceph_statfs,\n  flush: ceph_flush,   \n  release: ceph_release,\n  fsync: ceph_fsync,\n  setxattr: 0,\n  getxattr: 0,\n  listxattr: 0,\n  removexattr: 0,\n  opendir: ceph_opendir,\n  readdir: ceph_readdir,\n  releasedir: ceph_releasedir  \n};\n\n\nint ceph_fuse_main(Client *c, int argc, const char *argv[])\n{\n  \/\/ init client\n  client = c;\n\n  \/\/ set up fuse argc\/argv\n  int newargc = 0;\n  const char **newargv = (const char **) malloc((argc + 10) * sizeof(char *));\n  newargv[newargc++] = argv[0];\n  \n  \/\/ allow other (all!) users to see my file system\n  \/\/ NOTE: echo user_allow_other >> \/etc\/fuse.conf\n  \/\/ NB: seems broken on Darwin\n#ifndef DARWIN\n  newargv[newargc++] = \"-o\";\n  newargv[newargc++] = \"allow_other\";\n#endif \/\/ DARWIN\n  \n  \/\/ use inos\n  newargv[newargc++] = \"-o\";\n  newargv[newargc++] = \"use_ino\";\n\n  \/\/ large reads, direct_io (no kernel cachine)\n  \/\/newargv[newargc++] = \"-o\";\n  \/\/newargv[newargc++] = \"large_read\";\n  if (g_conf.fuse_direct_io) {\n    newargv[newargc++] = \"-o\";\n    newargv[newargc++] = \"direct_io\";\n  }\n\n  \/\/ disable stupid fuse unlink hiding thing\n  newargv[newargc++] = \"-o\";\n  newargv[newargc++] = \"hard_remove\";\n\n  \/\/ force into foreground\n  \/\/   -> we can watch stdout this way!!\n  newargv[newargc++] = \"-f\";\n  \n  \/\/ copy rest of cmdline (hopefully, the mount point!)\n  for (int argctr = 1; argctr < argc; argctr++) newargv[newargc++] = argv[argctr];\n  \n  \/\/ go fuse go\n  cout << \"ok, calling fuse_main\" << std::endl;\n  int r = fuse_main(newargc, (char**)newargv, &ceph_oper, 0);\n  return r;\n}\n<|endoftext|>"}
{"text":"#include \n#include \n#include \n\n#ifdef _WIN32\n\n#define WIN32_LEAN_AND_MEAN\n#define STRICT\n#define UNICODE\n#include \n#include \n#include \n\n\/\/ UTF-16\n\n#define PSTR(x) L ## x\n\ntypedef wchar_t pchar;\nsize_t pstrlen(const pchar* p) {\n    return wcslen(p);\n}\nint pprintf(const pchar* format, ...) {\n    va_list arg;\n    va_start(arg, format);\n    int result = vwprintf(format, arg);\n    va_end(arg);\n    return result;\n}\n\n#else\n\n#include \n#include \n#include \n#include \ntypedef int SOCKET; \/\/ old-school\nconst SOCKET INVALID_SOCKET = -1;\nconst ssize_t SOCKET_ERROR = -1;\n\n\/\/ UTF-8\n\n#define PSTR(x) x\ntypedef char pchar;\nsize_t pstrlen(const pchar* p) {\n    return strlen(p);\n}\nint pprintf(const pchar* format, ...) {\n    va_list arg;\n    va_start(arg, format);\n    int result = vprintf(format, arg);\n    va_end(arg);\n    return result;\n}\n\n#endif\n\n#include \n#include \n#include \n#include \n\n\/\/ int(md5.md5('ibb').hexdigest()[-4:], 16)\nconst int IBB_PORT = 26830;\n\nint error(const char* msg) {\n    fprintf(stderr, \"ibb *** error: %s\\n\", msg);\n    return 1;\n}\n\nbool openServerConnection(SOCKET* s) {\n    *s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n    if (*s == INVALID_SOCKET) {\n        \/\/ TODO: print error code\n        error(\"Failed to create socket\");\n        return false;\n    }\n\n    sockaddr_in address;\n    address.sin_family = AF_INET;\n    address.sin_addr.s_addr = inet_addr(\"127.0.0.1\");\n    address.sin_port = htons(IBB_PORT);\n    \n    int result = connect(*s, reinterpret_cast(&address), sizeof(address));\n    if (result) {\n        return false;\n    }\n\n    return true;\n}\n\n#ifdef _WIN32\n\nbool startServer() {\n    WCHAR executable_path[MAX_PATH * 2];\n    DWORD length = GetModuleFileNameW(GetModuleHandle(NULL), executable_path, MAX_PATH);\n    if (length == 0 || length == MAX_PATH) {\n        fprintf(stderr, \"ibb *** failed to get executable path\\n\");\n        return false;\n    }\n\n    wchar_t* last_slash = wcsrchr(executable_path, '\\\\');\n    if (last_slash) {\n        *last_slash = 0;\n    } else {\n        last_slash = executable_path;\n    }\n    wcsncpy(last_slash, L\"\\\\ibb_server.exe\", MAX_PATH);\n\n    if (PathFileExists(executable_path)) {\n        \/\/ Launch server executable directly.\n        \n        \/\/ TODO: use CreateProcess instead of ShellExecute\n        \/\/ TODO: print error code\n        HINSTANCE result = ShellExecuteW(0, L\"open\", executable_path, executable_path, NULL, SW_SHOW);\n        return result > reinterpret_cast(32);\n    } else {\n        \/\/ Launch server from Python.\n\n        WCHAR python_path[MAX_PATH + 1] = {0};\n        LONG size = sizeof(python_path);\n        LONG success = RegQueryValueW(\n            HKEY_LOCAL_MACHINE,\n            L\"SOFTWARE\\\\Python\\\\PythonCore\\\\3.1\\\\InstallPath\",\n            python_path,\n            &size);\n        if (!success) {\n            \/\/ TODO: print error\n            fprintf(stderr, \"ibb *** failed to locate Python 3.1\\n\");\n            return false;\n        }\n\n        \/\/ TODO: use safe strings\n        wcsncat(python_path, L\"\\\\python.exe\", MAX_PATH);\n        \n        wcsncpy(last_slash, L\"\\\\src\\\\ibb.py\", MAX_PATH);\n        \n        \/\/ TODO: use CreateProcess instead of ShellExecute\n        \/\/ TODO: print error code\n        HINSTANCE result = ShellExecuteW(0, L\"open\", python_path, executable_path, NULL, SW_SHOW);\n        return result > reinterpret_cast(32);\n    }\n}\n\n#else\n\n\/\/ Mac\n#include \n\nbool startServer() {\n    uint32_t pathSize = 0;\n    \/\/ should return -1\n    _NSGetExecutablePath(0, &pathSize);\n\n    char executablePath[pathSize];\n    if (0 != _NSGetExecutablePath(executablePath, &pathSize)) {\n        fprintf(stderr, \"ibb *** failed to get executable path\");\n        return false;\n    }\n\n    \/*\n    wchar_t* last_slash = wcsrchr(executable_path, '\\\\');\n    if (last_slash) {\n        *last_slash = 0;\n    } else {\n        last_slash = executable_path;\n    }\n    wcsncpy(last_slash, L\"\\\\ibb_server.exe\", MAX_PATH);\n\n    if (PathFileExists(executable_path)) {\n        \/\/ Launch server executable directly.\n        \n        \/\/ TODO: use CreateProcess instead of ShellExecute\n        \/\/ TODO: print error code\n        HINSTANCE result = ShellExecuteW(0, L\"open\", executable_path, executable_path, NULL, SW_SHOW);\n        return result > reinterpret_cast(32);\n    } else {\n        \/\/ Launch server from Python.\n\n        WCHAR python_path[MAX_PATH + 1] = {0};\n        LONG size = sizeof(python_path);\n        LONG success = RegQueryValueW(\n            HKEY_LOCAL_MACHINE,\n            L\"SOFTWARE\\\\Python\\\\PythonCore\\\\3.1\\\\InstallPath\",\n            python_path,\n            &size);\n        if (!success) {\n            \/\/ TODO: print error\n            fprintf(stderr, \"ibb *** failed to locate Python 3.1\\n\");\n            return false;\n        }\n\n        \/\/ TODO: use safe strings\n        wcsncat(python_path, L\"\\\\python.exe\", MAX_PATH);\n        \n        wcsncpy(last_slash, L\"\\\\src\\\\ibb.py\", MAX_PATH);\n        \n        \/\/ TODO: use CreateProcess instead of ShellExecute\n        \/\/ TODO: print error code\n        HINSTANCE result = ShellExecuteW(0, L\"open\", python_path, executable_path, NULL, SW_SHOW);\n        return result > reinterpret_cast(32);\n    }\n    *\/\n    return false;\n}\n\n#endif\n\nvoid sendString(SOCKET connection, const pchar* begin, const pchar* end = 0) {\n    if (!end) {\n        end = begin + pstrlen(begin);\n    }\n    \n    \/\/ UTF-16 over the wire on Windows\n    \/\/ UTF-32 on Linux and Mac\n    send(\n        connection,\n        reinterpret_cast(begin),\n        (end - begin) * sizeof(pchar),\n        0);\n\n    \/\/ TODO: error checking\n}\n\nstruct ScopedFree {\n    explicit ScopedFree(char* p)\n        : p(p)\n    {}\n\n    ~ScopedFree() {\n        free(p);\n    }\n\nprivate:\n    char* p;\n};\n\nbool sendBuild(SOCKET connection, int argc, const pchar* argv[], clock_t start) {\n    sendString(connection, PSTR(\"version: 1\\n\"));\n\n    sendString(connection, PSTR(\"cwd: \"));\n\n    #ifdef _WIN32\n    WCHAR current_directory[MAX_PATH] = {0};\n    GetCurrentDirectoryW(MAX_PATH, current_directory);\n    #else\n    char* current_directory = getcwd(0, 0);\n    ScopedFree scoped_free(current_directory);\n    #endif\n\n    sendString(connection, current_directory);\n    sendString(connection, PSTR(\"\\n\"));\n\n    for (int i = 0; i < argc; ++i) {\n        sendString(connection, PSTR(\"arg: \"));\n        sendString(connection, argv[i]);\n        sendString(connection, PSTR(\"\\n\"));\n    }\n\n    sendString(connection, PSTR(\"build\\n\"));\n\n    \/\/printf(\"Build sent in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n    \/\/fflush(stdout);\n\n    for (;;) {\n        const int BUFFER_LENGTH = 1024;\n        pchar buffer[BUFFER_LENGTH + 1];\n        const int bytes = recv(\n            connection,\n            reinterpret_cast(buffer),\n            sizeof(pchar) * BUFFER_LENGTH,\n            0);\n        if (0 == bytes) {\n            break;\n        }\n        if (SOCKET_ERROR == bytes) {\n            error(\"Broken connection\");\n            break;\n        }\n        const int chars = bytes \/ sizeof(pchar); \/\/ TODO: handle odd bytes values\n        buffer[chars] = 0;\n        pprintf(PSTR(\"%s\"), buffer); \/\/ %*s sometimes wrote extra crap at the end\n    }\n\n    \/\/printf(\"Result recieved in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n    \/\/fflush(stdout);\n\n    return true;\n}\n\nint wmain(int argc, const wchar_t* argv[]) {\n    clock_t start = clock();\n\n    WSADATA wsadata;\n    if (0 != WSAStartup(2, &wsadata)) {\n        return error(\"Failed to initialize winsock\");\n    }\n\n    struct cleanup_t {\n        cleanup_t() {}\n        ~cleanup_t() { WSACleanup(); }\n    } cleanup;\n\n    \/\/printf(\"Started winsock in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n    \/\/fflush(stdout);\n\n    SOCKET connection;\n    if (!openServerConnection(&connection)) {\n        if (!startServer()) {\n            return error(\"Failed to start server\");\n        }\n        if (!openServerConnection(&connection)) {\n            return error(\"Failed to connect to server\");\n        }\n    }\n\n    \/\/printf(\"Opened connection in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n    \/\/fflush(stdout);\n\n    if (!sendBuild(connection, argc, argv, start)) {\n        return error(\"Failed to submit build\");\n    }\n\n    closesocket(connection);\n\n    \/\/printf(\"Socket closed in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n    \/\/fflush(stdout);\n    return 0;\n}\n\n\/\/ hack around mingw's lack of wmain support\nint main() {\n    int argc;\n    WCHAR** argv = CommandLineToArgvW(\n        GetCommandLineW(),\n        &argc);\n    return wmain(argc, const_cast(argv));\n}\nhey it builds#include \n#include \n#include \n\n#ifdef _WIN32\n\n#define WIN32_LEAN_AND_MEAN\n#define STRICT\n#define UNICODE\n#include \n#include \n#include \n\n\/\/ UTF-16\n\n#define PSTR(x) L ## x\n\ntypedef wchar_t pchar;\nsize_t pstrlen(const pchar* p) {\n    return wcslen(p);\n}\nint pprintf(const pchar* format, ...) {\n    va_list arg;\n    va_start(arg, format);\n    int result = vwprintf(format, arg);\n    va_end(arg);\n    return result;\n}\n\n#else\n\n#include \n#include \n#include \n#include \ntypedef int SOCKET; \/\/ old-school\nconst SOCKET INVALID_SOCKET = -1;\nconst ssize_t SOCKET_ERROR = -1;\nint closesocket(SOCKET socket) {\n    return close(socket);\n}\n\n\/\/ UTF-8\n\n#define PSTR(x) x\ntypedef char pchar;\nsize_t pstrlen(const pchar* p) {\n    return strlen(p);\n}\nint pprintf(const pchar* format, ...) {\n    va_list arg;\n    va_start(arg, format);\n    int result = vprintf(format, arg);\n    va_end(arg);\n    return result;\n}\n\n#endif\n\n#include \n#include \n#include \n#include \n\n\/\/ int(md5.md5('ibb').hexdigest()[-4:], 16)\nconst int IBB_PORT = 26830;\n\nint error(const char* msg) {\n    fprintf(stderr, \"ibb *** error: %s\\n\", msg);\n    return 1;\n}\n\nbool openServerConnection(SOCKET* s) {\n    *s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n    if (*s == INVALID_SOCKET) {\n        \/\/ TODO: print error code\n        error(\"Failed to create socket\");\n        return false;\n    }\n\n    sockaddr_in address;\n    address.sin_family = AF_INET;\n    address.sin_addr.s_addr = inet_addr(\"127.0.0.1\");\n    address.sin_port = htons(IBB_PORT);\n    \n    int result = connect(*s, reinterpret_cast(&address), sizeof(address));\n    if (result) {\n        return false;\n    }\n\n    return true;\n}\n\n#ifdef _WIN32\n\nbool startServer() {\n    WCHAR executable_path[MAX_PATH * 2];\n    DWORD length = GetModuleFileNameW(GetModuleHandle(NULL), executable_path, MAX_PATH);\n    if (length == 0 || length == MAX_PATH) {\n        fprintf(stderr, \"ibb *** failed to get executable path\\n\");\n        return false;\n    }\n\n    wchar_t* last_slash = wcsrchr(executable_path, '\\\\');\n    if (last_slash) {\n        *last_slash = 0;\n    } else {\n        last_slash = executable_path;\n    }\n    wcsncpy(last_slash, L\"\\\\ibb_server.exe\", MAX_PATH);\n\n    if (PathFileExists(executable_path)) {\n        \/\/ Launch server executable directly.\n        \n        \/\/ TODO: use CreateProcess instead of ShellExecute\n        \/\/ TODO: print error code\n        HINSTANCE result = ShellExecuteW(0, L\"open\", executable_path, executable_path, NULL, SW_SHOW);\n        return result > reinterpret_cast(32);\n    } else {\n        \/\/ Launch server from Python.\n\n        WCHAR python_path[MAX_PATH + 1] = {0};\n        LONG size = sizeof(python_path);\n        LONG success = RegQueryValueW(\n            HKEY_LOCAL_MACHINE,\n            L\"SOFTWARE\\\\Python\\\\PythonCore\\\\3.1\\\\InstallPath\",\n            python_path,\n            &size);\n        if (!success) {\n            \/\/ TODO: print error\n            fprintf(stderr, \"ibb *** failed to locate Python 3.1\\n\");\n            return false;\n        }\n\n        \/\/ TODO: use safe strings\n        wcsncat(python_path, L\"\\\\python.exe\", MAX_PATH);\n        \n        wcsncpy(last_slash, L\"\\\\src\\\\ibb.py\", MAX_PATH);\n        \n        \/\/ TODO: use CreateProcess instead of ShellExecute\n        \/\/ TODO: print error code\n        HINSTANCE result = ShellExecuteW(0, L\"open\", python_path, executable_path, NULL, SW_SHOW);\n        return result > reinterpret_cast(32);\n    }\n}\n\n#else\n\n\/\/ Mac\n#include \n\nbool startServer() {\n    uint32_t pathSize = 0;\n    \/\/ should return -1\n    _NSGetExecutablePath(0, &pathSize);\n\n    char executablePath[pathSize];\n    if (0 != _NSGetExecutablePath(executablePath, &pathSize)) {\n        fprintf(stderr, \"ibb *** failed to get executable path\");\n        return false;\n    }\n\n    \/*\n    wchar_t* last_slash = wcsrchr(executable_path, '\\\\');\n    if (last_slash) {\n        *last_slash = 0;\n    } else {\n        last_slash = executable_path;\n    }\n    wcsncpy(last_slash, L\"\\\\ibb_server.exe\", MAX_PATH);\n\n    if (PathFileExists(executable_path)) {\n        \/\/ Launch server executable directly.\n        \n        \/\/ TODO: use CreateProcess instead of ShellExecute\n        \/\/ TODO: print error code\n        HINSTANCE result = ShellExecuteW(0, L\"open\", executable_path, executable_path, NULL, SW_SHOW);\n        return result > reinterpret_cast(32);\n    } else {\n        \/\/ Launch server from Python.\n\n        WCHAR python_path[MAX_PATH + 1] = {0};\n        LONG size = sizeof(python_path);\n        LONG success = RegQueryValueW(\n            HKEY_LOCAL_MACHINE,\n            L\"SOFTWARE\\\\Python\\\\PythonCore\\\\3.1\\\\InstallPath\",\n            python_path,\n            &size);\n        if (!success) {\n            \/\/ TODO: print error\n            fprintf(stderr, \"ibb *** failed to locate Python 3.1\\n\");\n            return false;\n        }\n\n        \/\/ TODO: use safe strings\n        wcsncat(python_path, L\"\\\\python.exe\", MAX_PATH);\n        \n        wcsncpy(last_slash, L\"\\\\src\\\\ibb.py\", MAX_PATH);\n        \n        \/\/ TODO: use CreateProcess instead of ShellExecute\n        \/\/ TODO: print error code\n        HINSTANCE result = ShellExecuteW(0, L\"open\", python_path, executable_path, NULL, SW_SHOW);\n        return result > reinterpret_cast(32);\n    }\n    *\/\n    return false;\n}\n\n#endif\n\nvoid sendString(SOCKET connection, const pchar* begin, const pchar* end = 0) {\n    if (!end) {\n        end = begin + pstrlen(begin);\n    }\n    \n    \/\/ UTF-16 over the wire on Windows\n    \/\/ UTF-32 on Linux and Mac\n    send(\n        connection,\n        reinterpret_cast(begin),\n        (end - begin) * sizeof(pchar),\n        0);\n\n    \/\/ TODO: error checking\n}\n\nstruct ScopedFree {\n    explicit ScopedFree(char* p)\n        : p(p)\n    {}\n\n    ~ScopedFree() {\n        free(p);\n    }\n\nprivate:\n    char* p;\n};\n\nbool sendBuild(SOCKET connection, int argc, const pchar* argv[], clock_t start) {\n    sendString(connection, PSTR(\"version: 1\\n\"));\n\n    sendString(connection, PSTR(\"cwd: \"));\n\n    #ifdef _WIN32\n    WCHAR current_directory[MAX_PATH] = {0};\n    GetCurrentDirectoryW(MAX_PATH, current_directory);\n    #else\n    char* current_directory = getcwd(0, 0);\n    ScopedFree scoped_free(current_directory);\n    #endif\n\n    sendString(connection, current_directory);\n    sendString(connection, PSTR(\"\\n\"));\n\n    for (int i = 0; i < argc; ++i) {\n        sendString(connection, PSTR(\"arg: \"));\n        sendString(connection, argv[i]);\n        sendString(connection, PSTR(\"\\n\"));\n    }\n\n    sendString(connection, PSTR(\"build\\n\"));\n\n    \/\/printf(\"Build sent in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n    \/\/fflush(stdout);\n\n    for (;;) {\n        const int BUFFER_LENGTH = 1024;\n        pchar buffer[BUFFER_LENGTH + 1];\n        const int bytes = recv(\n            connection,\n            reinterpret_cast(buffer),\n            sizeof(pchar) * BUFFER_LENGTH,\n            0);\n        if (0 == bytes) {\n            break;\n        }\n        if (SOCKET_ERROR == bytes) {\n            error(\"Broken connection\");\n            break;\n        }\n        const int chars = bytes \/ sizeof(pchar); \/\/ TODO: handle odd bytes values\n        buffer[chars] = 0;\n        pprintf(PSTR(\"%s\"), buffer); \/\/ %*s sometimes wrote extra crap at the end\n    }\n\n    \/\/printf(\"Result recieved in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n    \/\/fflush(stdout);\n\n    return true;\n}\n\nint pmain(int argc, const pchar* argv[]) {\n    clock_t start = clock();\n\n#ifdef _WIN32\n    WSADATA wsadata;\n    if (0 != WSAStartup(2, &wsadata)) {\n        return error(\"Failed to initialize winsock\");\n    }\n\n    struct cleanup_t {\n        cleanup_t() {}\n        ~cleanup_t() { WSACleanup(); }\n    } cleanup;\n#endif\n\n    \/\/printf(\"Started winsock in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n    \/\/fflush(stdout);\n\n    SOCKET connection;\n    if (!openServerConnection(&connection)) {\n        if (!startServer()) {\n            return error(\"Failed to start server\");\n        }\n        if (!openServerConnection(&connection)) {\n            return error(\"Failed to connect to server\");\n        }\n    }\n\n    \/\/printf(\"Opened connection in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n    \/\/fflush(stdout);\n\n    if (!sendBuild(connection, argc, argv, start)) {\n        return error(\"Failed to submit build\");\n    }\n\n    closesocket(connection);\n\n    \/\/printf(\"Socket closed in %g seconds\\n\", float(clock() - start) \/ CLOCKS_PER_SEC);\n    \/\/fflush(stdout);\n    return 0;\n}\n\n\/\/ hack around mingw's lack of wmain support\n#ifdef _WIN32\n\nint main() {\n    int argc;\n    WCHAR** argv = CommandLineToArgvW(\n        GetCommandLineW(),\n        &argc);\n    return pmain(argc, const_cast(argv));\n}\n\n#else\n\nint main(int argc, const char* argv[]) {\n    return pmain(argc, argv);\n}\n\n#endif\n<|endoftext|>"}
{"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ SneezyMUD - All rights reserved, SneezyMUD Coding Team\n\/\/\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"stdsneezy.h\"\n#include \"cmd_trophy.h\"\n\nfloat trophy_exp_mod(float count)\n{\n  float min_mod=0.3;\n  float max_mod=1.0; \/\/ shouldn't ever be above 1.0\n  float free_kills=8; \/\/ how many kills you get before trophy kicks in\n  float step_mod=0.5; \/\/ mod per step\n  float num_steps=14.0; \/\/ number of steps\n\n  float t1, t2, t3, t4, t5;\n\n  t1=(double)(count-free_kills);\n  t2=step_mod \/ num_steps;\n  t3=t1*t2;\n  t4=max_mod-t3;\n  t5=(double)(max(t4*100, min_mod*100)\/100);\n  t5=(double)(min(t5*100, max_mod*100)\/100);\n\n  \/\/  vlogf(LOG_PEEL, \"%f %f %f %f %f\", t1, t2, t3, t4, t5);\n\n  return t5;\n}\n\n\n\nconst char *describe_trophy_exp(float count)\n{\n  float f=trophy_exp_mod(count);\n\n  return((f == 1.0) ? \"full<1>\" :\n\t ((f >= 0.90) ? \"much<1>\" :\n\t  ((f >= 0.80) ? \"a fair amount\" :\n\t   ((f >= 0.70) ? \"some<1>\" : \"little<1>\"))));\n}\n\nvoid TBeing::doTrophy(const char *arg)\n{\n  MYSQL_ROW row=NULL;\n  MYSQL_RES *res;\n  int rc, mcount=0, vnum, header=0, zcount=0, bottom=0, zcountt=0;\n  int zonesearch=0, processrow=1;\n  float count;\n  char buf[256];\n  string sb;\n  unsigned int zone;\n\n  if(!isPc()){\n    sendTo(\"Mobs can't use this command!\\n\\r\");\n    return;\n  }\n\n  for (; isspace(*arg); arg++);\n  \n  if(!strncmp(arg, \"zone\", 4)){\n    zonesearch=1;\n    for (; !isspace(*arg); arg++);\n  }\n\n  rc=dbquery(&res, \"sneezy\", \"doTrophy\", \"select mobvnum, count from trophy where name='%s' order by mobvnum\", getName());\n\n  for (zone = 0; zone < zone_table.size(); zone++) {\n    zoneData &zd = zone_table[zone];\n    \n    while(1){\n      if(processrow)\n\trow=mysql_fetch_row(res);\n\n      if(!row)\n\tbreak;\n\n      vlogf(LOG_PEEL, \"mob=%i, top=%i\", atoi(row[0]), zd.top);\n\n      \/\/ sometimes we get an entry of 0 for med mobs I think\n      vnum=atoi(row[0]);\n      if(vnum==0){\n\tcontinue;\n      }\n\n      \/\/ this mob doesn't belong to this zone, so break out to the zone loop\n      if(vnum>zd.top){\n\tprocessrow=0; \/\/ don't get the next row yet\n\tbreak;\n      } else {\n\tprocessrow=1;\n      }\n\n      int rnum = real_mobile(atoi(row[0]));\n      if (rnum < 0) {\n\tvlogf(LOG_BUG, \"DoTrophy detected bad mobvnum=%d for name='%s'\", \n\t      atoi(row[0]), getName());\n\tcontinue;\n      }\n\n      if(zonesearch){\n\tif(*arg && !isname(arg, zd.name))\n\t  continue;\n      } else {\n\tif(*arg && !isname(arg, mob_index[rnum].name))\n\t  continue;\n      }\n\n      \/\/ print the zone header if we haven't already\n      \/\/ we do it here, so we can prevent printing headers for empty zones\n      if(!header){\n\tsprintf(buf, \"\\n--%s\\n\", zd.name);\n\tsb += buf; \n\theader=1;\n      }\n\n      count=atof(row[1]);\n      sprintf(buf, \"You will gain %s experience when fighting %s.\\n\\r\", \n\t      describe_trophy_exp(count),\n\t      mob_index[rnum].short_desc);\n      ++mcount;\n      ++zcount;\n      sb += buf;\n\n      processrow=1; \/\/ ok to get the next row\n      \n#if 0\n    sprintf(buf, \"%3d %-38.38s %4dm %4dm %6d-%-6d %3d %.1f\\n\\r\", \n\t    zone, buf2, zd.lifespan, zd.age, bottom, zd.top, \n\t    zd.zone_value,\n\t    (zd.num_mobs ? zd.mob_levels\/zd.num_mobs : 0));\n    sb += buf;\n#endif\n    }\n\n    \/\/ we have some mobs for this zone, so do some tallies\n    if(header){\n      sprintf(buf, \"Total mobs: %i\\n\\r\", zcount);\n      sb += buf;\n\n      unsigned int objnx;\n      for (objnx = 0; objnx < mob_index.size(); objnx++) {\n\tif(mob_index[objnx].virt >= bottom &&\n\t   mob_index[objnx].virt <= zd.top){\n\t  ++zcountt;\n\t}\n      }\n\n      sprintf(buf, \"You have killed %1.2f%% of mobs in this zone.\\n\\r\",((float)((float)zcount\/(float)zcountt)*100.0));\n      sb += buf;\n    }\n\n    header=zcount=zcountt=0;\n    bottom=zd.top+1;\n  }\n\n\n\n\n\n  sprintf(buf, \"\\n--\\nTotal mobs: %i\\n\\r\", mcount);\n  sb += buf;\n  if(mcount>0){\n    sprintf(buf, \"You have killed %1.2f%% of all mobs.\\n\\r\",((float)((float)mcount\/(float)mob_index.size())*100.0));\n    sb += buf;\n  }\n\n  if (desc)\n    desc->page_string(sb.c_str(), SHOWNOW_NO, ALLOWREP_YES);\n    \n  mysql_free_result(res);\n\n\n  return;\n}\n\n\n\nvoid wipeTrophy(const char *name){\n  dbquery(NULL, \"sneezy\", \"wipeTrophy\", \"delete from trophy where name='%s'\", name);\n}\ntook out debugging logs and some excess code\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ SneezyMUD - All rights reserved, SneezyMUD Coding Team\n\/\/\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"stdsneezy.h\"\n#include \"cmd_trophy.h\"\n\nfloat trophy_exp_mod(float count)\n{\n  float min_mod=0.3;\n  float max_mod=1.0; \/\/ shouldn't ever be above 1.0\n  float free_kills=8; \/\/ how many kills you get before trophy kicks in\n  float step_mod=0.5; \/\/ mod per step\n  float num_steps=14.0; \/\/ number of steps\n\n  float t1, t2, t3, t4, t5;\n\n  t1=(double)(count-free_kills);\n  t2=step_mod \/ num_steps;\n  t3=t1*t2;\n  t4=max_mod-t3;\n  t5=(double)(max(t4*100, min_mod*100)\/100);\n  t5=(double)(min(t5*100, max_mod*100)\/100);\n\n  \/\/  vlogf(LOG_PEEL, \"%f %f %f %f %f\", t1, t2, t3, t4, t5);\n\n  return t5;\n}\n\n\n\nconst char *describe_trophy_exp(float count)\n{\n  float f=trophy_exp_mod(count);\n\n  return((f == 1.0) ? \"full<1>\" :\n\t ((f >= 0.90) ? \"much<1>\" :\n\t  ((f >= 0.80) ? \"a fair amount\" :\n\t   ((f >= 0.70) ? \"some<1>\" : \"little<1>\"))));\n}\n\n\/\/ this function is a little messy, I apologize\nvoid TBeing::doTrophy(const char *arg)\n{\n  MYSQL_ROW row=NULL;\n  MYSQL_RES *res;\n  int rc, mcount=0, vnum, header=0, zcount=0, bottom=0, zcountt=0;\n  int zonesearch=0, processrow=1;\n  float count;\n  char buf[256];\n  string sb;\n  unsigned int zone;\n\n  if(!isPc()){\n    sendTo(\"Mobs can't use this command!\\n\\r\");\n    return;\n  }\n\n  for (; isspace(*arg); arg++);\n  \n  if(!strncmp(arg, \"zone\", 4)){\n    zonesearch=1;\n    for (; !isspace(*arg); arg++);\n  }\n\n  rc=dbquery(&res, \"sneezy\", \"doTrophy\", \"select mobvnum, count from trophy where name='%s' order by mobvnum\", getName());\n\n  for (zone = 0; zone < zone_table.size(); zone++) {\n    zoneData &zd = zone_table[zone];\n    \n    while(1){\n      if(processrow)\n\trow=mysql_fetch_row(res);\n\n      if(!row)\n\tbreak;\n\n      \/\/ sometimes we get an entry of 0 for med mobs I think\n      vnum=atoi(row[0]);\n      if(vnum==0){\n\tcontinue;\n      }\n\n      \/\/ this mob doesn't belong to this zone, so break out to the zone loop\n      if(vnum>zd.top){\n\tprocessrow=0; \/\/ don't get the next row yet\n\tbreak;\n      } else {\n\tprocessrow=1;\n      }\n\n      int rnum = real_mobile(atoi(row[0]));\n      if (rnum < 0) {\n\tvlogf(LOG_BUG, \"DoTrophy detected bad mobvnum=%d for name='%s'\", \n\t      atoi(row[0]), getName());\n\tcontinue;\n      }\n\n      if(zonesearch){\n\tif(*arg && !isname(arg, zd.name))\n\t  continue;\n      } else {\n\tif(*arg && !isname(arg, mob_index[rnum].name))\n\t  continue;\n      }\n\n      \/\/ print the zone header if we haven't already\n      \/\/ we do it here, so we can prevent printing headers for empty zones\n      if(!header){\n\tsprintf(buf, \"\\n--%s\\n\", zd.name);\n\tsb += buf; \n\theader=1;\n      }\n\n      count=atof(row[1]);\n      sprintf(buf, \"You will gain %s experience when fighting %s.\\n\\r\", \n\t      describe_trophy_exp(count),\n\t      mob_index[rnum].short_desc);\n      ++mcount;\n      ++zcount;\n      sb += buf;\n\n      processrow=1; \/\/ ok to get the next row\n    }\n\n    \/\/ we have some mobs for this zone, so do some tallies\n    if(header){\n      sprintf(buf, \"Total mobs: %i\\n\\r\", zcount);\n      sb += buf;\n\n      unsigned int objnx;\n      for (objnx = 0; objnx < mob_index.size(); objnx++) {\n\tif(mob_index[objnx].virt >= bottom &&\n\t   mob_index[objnx].virt <= zd.top){\n\t  ++zcountt;\n\t}\n      }\n\n      sprintf(buf, \"You have killed %1.2f%% of mobs in this zone.\\n\\r\",((float)((float)zcount\/(float)zcountt)*100.0));\n      sb += buf;\n    }\n\n    header=zcount=zcountt=0;\n    bottom=zd.top+1;\n  }\n\n\n\n\n\n  sprintf(buf, \"\\n--\\nTotal mobs: %i\\n\\r\", mcount);\n  sb += buf;\n  if(mcount>0){\n    sprintf(buf, \"You have killed %1.2f%% of all mobs.\\n\\r\",((float)((float)mcount\/(float)mob_index.size())*100.0));\n    sb += buf;\n  }\n\n  if (desc)\n    desc->page_string(sb.c_str(), SHOWNOW_NO, ALLOWREP_YES);\n    \n  mysql_free_result(res);\n\n\n  return;\n}\n\n\n\nvoid wipeTrophy(const char *name){\n  dbquery(NULL, \"sneezy\", \"wipeTrophy\", \"delete from trophy where name='%s'\", name);\n}\n<|endoftext|>"}
{"text":"#include \"stdafx.h\"\n#include \"SettingsUI.h\"\n#include \"General.h\"\n#include \"afxdialogex.h\"\n\n#include \"Settings.h\"\n#include \"SkinInfo.h\"\n\n#define KEY_NAME L\"3RVX\"\n#define STARTUP_KEY L\"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run\"\n\nIMPLEMENT_DYNAMIC(General, CPropertyPage)\n\nGeneral::General() :\nCPropertyPage(General::IDD) {\n\n}\n\nGeneral::~General() {\n\n}\n\nvoid General::DoDataExchange(CDataExchange* pDX)\n{\n    CPropertyPage::DoDataExchange(pDX);\n    DDX_Control(pDX, CHK_STARTUP, _startup);\n    DDX_Control(pDX, CHK_NOTIFY, _notify);\n    DDX_Control(pDX, CHK_SOUNDS, _sounds);\n    DDX_Control(pDX, CMB_LANG, _lang);\n    DDX_Control(pDX, GRP_SKIN, _skinGrp);\n    DDX_Control(pDX, GRP_BEHAVIOR, _behaviorGrp);\n    DDX_Control(pDX, GRP_LANGUAGE, _languageGrp);\n    DDX_Control(pDX, LBL_AUTHOR, _author);\n    DDX_Control(pDX, CMB_SKIN, _skins);\n    DDX_Control(pDX, BTN_WEBSITE, _website);\n}\n\nBOOL General::OnApply() {\n    OutputDebugString(L\"-> General\\n\");\n    Settings *settings = Settings::Instance();\n    RunOnStartup(CHECKED(_startup));\n    settings->NotifyIconEnabled(CHECKED(_notify));\n    settings->SoundEffectsEnabled(CHECKED(_sounds));\n\n    int skinIdx = _skins.GetCurSel();\n    CString skinName;\n    _skins.GetLBText(skinIdx, skinName);\n    settings->CurrentSkin((LPCWSTR) skinName);\n\n    UIUtils::SaveSettings(*this);\n    return CPropertyPage::OnApply();\n}\n\nBOOL General::OnCommand(WPARAM wParam, LPARAM lParam) {\n    SetModified();\n    return CPropertyPage::OnCommand(wParam, lParam);\n}\n\nvoid General::LoadSettings() {\n    Settings *settings = Settings::Instance();\n    _startup.SetCheck(RunOnStartup());\n    _notify.SetCheck(settings->NotifyIconEnabled());\n    _sounds.SetCheck(settings->SoundEffectsEnabled());\n\n    \/* Determine which skins are available *\/\n    std::list skins = FindSkins(L\"..\/3RVX\/Skins\");\n    for (CString skin : skins) {\n        _skins.AddString(skin);\n    }\n\n    \/* Update the combo box with the current skin *\/\n    std::wstring current = settings->SkinName();\n    int idx = _skins.SelectString(0, current.c_str());\n    if (idx == CB_ERR) {\n        _skins.SelectString(0, DEFAULT_SKIN);\n    }\n    LoadSkinInfo();\n\n    \/* Populate the language box *\/\n    std::list languages = FindLanguages(\n        settings->LanguagesDir().c_str());\n\n    for (CString language : languages) {\n        _lang.AddString(language);\n    }\n    std::wstring currentLang = settings->LanguageName();\n    _lang.SelectString(0, currentLang.c_str());\n}\n\nBOOL General::OnInitDialog() {\n    CPropertyPage::OnInitDialog();\n    LoadSettings();\n    return TRUE;\n}\n\nstd::list General::FindSkins(CString dir) {\n    std::list skins;\n\n    CFileFind ff;\n    dir += L\"\\\\*\";\n    BOOL result = ff.FindFile(dir);\n    while (result) {\n        result = ff.FindNextFile();\n        if (ff.IsDots()) {\n            continue;\n        }\n\n        if (ff.IsDirectory()) {\n            CFileFind inDir;\n            CString dirPath = ff.GetFilePath();\n            dirPath += L\"\\\\skin.xml\";\n            if (inDir.FindFile(dirPath)) {\n                \/* We found a skin XML file; add the skin dir to our list. *\/\n                skins.push_back(ff.GetFileName());\n            }\n        }\n    }\n\n    return skins;\n}\n\nstd::list General::FindLanguages(CString dir) {\n    std::list languages;\n\n    CFileFind ff;\n    dir += L\"\\\\*.xml\";\n    BOOL result = ff.FindFile(dir);\n    while (result) {\n        result = ff.FindNextFile();\n        if (ff.IsDots() || ff.IsDirectory()) {\n            continue;\n        }\n\n        \/* Even though we asked for *xml files, FindNextFile() will still\n         * return results that start with .xml (like .xmlblah) *\/\n        CString ext = ff.GetFileName().Right(3);\n        if (ext == L\"xml\") {\n            languages.push_back(ff.GetFileTitle());\n        }\n    }\n\n    return languages;\n}\n\nvoid General::LoadSkinInfo() {\n    CString selectedSkin;\n    int selIdx = _skins.GetCurSel();\n    _skins.GetLBText(selIdx, selectedSkin);\n\n    std::wstring skinXML\n        = Settings::Instance()->SkinXML((LPCWSTR) selectedSkin);\n    SkinInfo s(skinXML);\n\n    CString authorText(L\"Author:\");\n    authorText.Append(L\" \");\n    authorText.Append(s.Author().c_str());\n    _author.SetWindowTextW(authorText);\n\n    _url = s.URL();\n    _website.EnableWindow((_url != L\"\"));\n}\nbool General::RunOnStartup() {\n    CRegKey rk;\n    int result = rk.Open(HKEY_CURRENT_USER, STARTUP_KEY, KEY_READ);\n    if (result == ERROR_SUCCESS) {\n        CString str;\n        ULONG bufLen = 1024;\n        LPTSTR buf = str.GetBufferSetLength(bufLen);\n\n        int queryResult = rk.QueryStringValue(KEY_NAME, buf, &bufLen);\n        if (queryResult == ERROR_SUCCESS) {\n            return true;\n        }\n    }\n    return false;\n}\n\nvoid General::RunOnStartup(bool enable) {\n    std::wstring path = Settings::AppDir();\n    CString exePath(path.c_str());\n    exePath.Append(L\"\\\\3RVX.exe\");\n\n    CRegKey rk;\n    int result = rk.Open(HKEY_CURRENT_USER, STARTUP_KEY, KEY_WRITE);\n    if (result == ERROR_SUCCESS) {\n        if (enable) {\n            rk.SetStringValue(KEY_NAME, exePath, REG_SZ);\n        } else {\n            rk.DeleteValue(KEY_NAME);\n        }\n    }\n}\n\nBEGIN_MESSAGE_MAP(General, CPropertyPage)\n    ON_BN_CLICKED(BTN_WEBSITE, &General::OnBnClickedWebsite)\n    ON_CBN_SELCHANGE(CMB_SKIN, &General::OnCbnSelchangeSkin)\nEND_MESSAGE_MAP()\n\nvoid General::OnBnClickedWebsite() {\n    ShellExecute(NULL, L\"open\", _url.c_str(), NULL, NULL, SW_SHOWNORMAL);\n}\n\nvoid General::OnCbnSelchangeSkin() {\n    LoadSkinInfo();\n}Fix hardcoded skin dir loader#include \"stdafx.h\"\n#include \"SettingsUI.h\"\n#include \"General.h\"\n#include \"afxdialogex.h\"\n\n#include \"Settings.h\"\n#include \"SkinInfo.h\"\n\n#define KEY_NAME L\"3RVX\"\n#define STARTUP_KEY L\"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run\"\n\nIMPLEMENT_DYNAMIC(General, CPropertyPage)\n\nGeneral::General() :\nCPropertyPage(General::IDD) {\n\n}\n\nGeneral::~General() {\n\n}\n\nvoid General::DoDataExchange(CDataExchange* pDX)\n{\n    CPropertyPage::DoDataExchange(pDX);\n    DDX_Control(pDX, CHK_STARTUP, _startup);\n    DDX_Control(pDX, CHK_NOTIFY, _notify);\n    DDX_Control(pDX, CHK_SOUNDS, _sounds);\n    DDX_Control(pDX, CMB_LANG, _lang);\n    DDX_Control(pDX, GRP_SKIN, _skinGrp);\n    DDX_Control(pDX, GRP_BEHAVIOR, _behaviorGrp);\n    DDX_Control(pDX, GRP_LANGUAGE, _languageGrp);\n    DDX_Control(pDX, LBL_AUTHOR, _author);\n    DDX_Control(pDX, CMB_SKIN, _skins);\n    DDX_Control(pDX, BTN_WEBSITE, _website);\n}\n\nBOOL General::OnApply() {\n    OutputDebugString(L\"-> General\\n\");\n    Settings *settings = Settings::Instance();\n    RunOnStartup(CHECKED(_startup));\n    settings->NotifyIconEnabled(CHECKED(_notify));\n    settings->SoundEffectsEnabled(CHECKED(_sounds));\n\n    int skinIdx = _skins.GetCurSel();\n    CString skinName;\n    _skins.GetLBText(skinIdx, skinName);\n    settings->CurrentSkin((LPCWSTR) skinName);\n\n    UIUtils::SaveSettings(*this);\n    return CPropertyPage::OnApply();\n}\n\nBOOL General::OnCommand(WPARAM wParam, LPARAM lParam) {\n    SetModified();\n    return CPropertyPage::OnCommand(wParam, lParam);\n}\n\nvoid General::LoadSettings() {\n    Settings *settings = Settings::Instance();\n    _startup.SetCheck(RunOnStartup());\n    _notify.SetCheck(settings->NotifyIconEnabled());\n    _sounds.SetCheck(settings->SoundEffectsEnabled());\n\n    \/* Determine which skins are available *\/\n    std::list skins = FindSkins(Settings::SkinDir().c_str());\n    for (CString skin : skins) {\n        _skins.AddString(skin);\n    }\n\n    \/* Update the combo box with the current skin *\/\n    std::wstring current = settings->SkinName();\n    int idx = _skins.SelectString(0, current.c_str());\n    if (idx == CB_ERR) {\n        _skins.SelectString(0, DEFAULT_SKIN);\n    }\n    LoadSkinInfo();\n\n    \/* Populate the language box *\/\n    std::list languages = FindLanguages(\n        settings->LanguagesDir().c_str());\n\n    for (CString language : languages) {\n        _lang.AddString(language);\n    }\n    std::wstring currentLang = settings->LanguageName();\n    _lang.SelectString(0, currentLang.c_str());\n}\n\nBOOL General::OnInitDialog() {\n    CPropertyPage::OnInitDialog();\n    LoadSettings();\n    return TRUE;\n}\n\nstd::list General::FindSkins(CString dir) {\n    std::list skins;\n\n    CFileFind ff;\n    dir += L\"\\\\*\";\n    BOOL result = ff.FindFile(dir);\n    while (result) {\n        result = ff.FindNextFile();\n        if (ff.IsDots()) {\n            continue;\n        }\n\n        if (ff.IsDirectory()) {\n            CFileFind inDir;\n            CString dirPath = ff.GetFilePath();\n            dirPath += L\"\\\\skin.xml\";\n            if (inDir.FindFile(dirPath)) {\n                \/* We found a skin XML file; add the skin dir to our list. *\/\n                skins.push_back(ff.GetFileName());\n            }\n        }\n    }\n\n    return skins;\n}\n\nstd::list General::FindLanguages(CString dir) {\n    std::list languages;\n\n    CFileFind ff;\n    dir += L\"\\\\*.xml\";\n    BOOL result = ff.FindFile(dir);\n    while (result) {\n        result = ff.FindNextFile();\n        if (ff.IsDots() || ff.IsDirectory()) {\n            continue;\n        }\n\n        \/* Even though we asked for *xml files, FindNextFile() will still\n         * return results that start with .xml (like .xmlblah) *\/\n        CString ext = ff.GetFileName().Right(3);\n        if (ext == L\"xml\") {\n            languages.push_back(ff.GetFileTitle());\n        }\n    }\n\n    return languages;\n}\n\nvoid General::LoadSkinInfo() {\n    CString selectedSkin;\n    int selIdx = _skins.GetCurSel();\n    _skins.GetLBText(selIdx, selectedSkin);\n\n    std::wstring skinXML\n        = Settings::Instance()->SkinXML((LPCWSTR) selectedSkin);\n    SkinInfo s(skinXML);\n\n    CString authorText(L\"Author:\");\n    authorText.Append(L\" \");\n    authorText.Append(s.Author().c_str());\n    _author.SetWindowTextW(authorText);\n\n    _url = s.URL();\n    _website.EnableWindow((_url != L\"\"));\n}\nbool General::RunOnStartup() {\n    CRegKey rk;\n    int result = rk.Open(HKEY_CURRENT_USER, STARTUP_KEY, KEY_READ);\n    if (result == ERROR_SUCCESS) {\n        CString str;\n        ULONG bufLen = 1024;\n        LPTSTR buf = str.GetBufferSetLength(bufLen);\n\n        int queryResult = rk.QueryStringValue(KEY_NAME, buf, &bufLen);\n        if (queryResult == ERROR_SUCCESS) {\n            return true;\n        }\n    }\n    return false;\n}\n\nvoid General::RunOnStartup(bool enable) {\n    std::wstring path = Settings::AppDir();\n    CString exePath(path.c_str());\n    exePath.Append(L\"\\\\3RVX.exe\");\n\n    CRegKey rk;\n    int result = rk.Open(HKEY_CURRENT_USER, STARTUP_KEY, KEY_WRITE);\n    if (result == ERROR_SUCCESS) {\n        if (enable) {\n            rk.SetStringValue(KEY_NAME, exePath, REG_SZ);\n        } else {\n            rk.DeleteValue(KEY_NAME);\n        }\n    }\n}\n\nBEGIN_MESSAGE_MAP(General, CPropertyPage)\n    ON_BN_CLICKED(BTN_WEBSITE, &General::OnBnClickedWebsite)\n    ON_CBN_SELCHANGE(CMB_SKIN, &General::OnCbnSelchangeSkin)\nEND_MESSAGE_MAP()\n\nvoid General::OnBnClickedWebsite() {\n    ShellExecute(NULL, L\"open\", _url.c_str(), NULL, NULL, SW_SHOWNORMAL);\n}\n\nvoid General::OnCbnSelchangeSkin() {\n    LoadSkinInfo();\n}<|endoftext|>"}
{"text":"\/\/ Copyright 2018 Google LLC. All Rights Reserved.\n\/*\n  Copyright (C) 2016 Steven L. Scott\n\n  This library is free software; you can redistribute it and\/or\n  modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  This library is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n  Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with this library; if not, write to the Free Software\n  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA\n*\/\n#ifndef BOOM_SPLINE_HPP\n#define BOOM_SPLINE_HPP\n#include \"LinAlg\/Vector.hpp\"\n\nnamespace BOOM {\n  \/\/ A base class providing features shared by different spline bases.\n  \/\/ Examples inclue Bsplines, Msplines, and Isplines.\n  class SplineBase {\n   public:\n    \/\/ Args:\n    \/\/   knots: The set of knots for the spline.  Between pairs of\n    \/\/     knots, the spline is a piecewise polynomial whose degree is\n    \/\/     given by the second argument.\n    \/\/\n    \/\/ Splines also have a notion of 'degree' or 'order', but this can\n    \/\/ be defined differently by different bases, so it is not part of\n    \/\/ the shared base class.\n    explicit SplineBase(const Vector &knots);\n    virtual ~SplineBase() {}\n\n    virtual Vector basis(double x) const = 0;\n\n    \/\/ The dimension of the spline basis (i.e. the dimension of the\n    \/\/ vector returned by a call to 'basis()'.\n    virtual int basis_dimension() const = 0;\n\n    \/\/ Adds a knot at the given  Location.  If knot_location lies\n    \/\/ before the first or after the last current knot, then the\n    \/\/ domain of the spline is extended to cover knot_location.\n    void add_knot(double knot_location);\n\n    \/\/ Remove the specified knot.  An exception will be thrown if\n    \/\/ which_knot is outside the range of knots_.  If which_knot == 0\n    \/\/ or which_knot == number_of_knots() - 1 then the domain of the\n    \/\/ spline basis will be reduced.\n    void remove_knot(int which_knot);\n\n    \/\/ The vector of knots.  Implicit boundary knots are not included.\n    virtual const Vector &knots() const { return knots_; }\n    virtual int number_of_knots() const { return knots_.size(); }\n\n    \/\/ If the argument is in the interior of the knots vector, return\n    \/\/ knots_[i].  If it is off the end to the left return knots_[0].\n    \/\/ If it is off the end to the right then include knots_.back().\n    \/\/ The implicit assumption is that we have an infinite set of\n    \/\/ knots piled up on the beginning and end of the actual knot\n    \/\/ sequence.\n    virtual double knot(int i) const;\n\n    virtual double final_knot() const;\n\n    \/\/ Compute the index of the largest knot less than or equal to x.\n    virtual int knot_span(double x) const;\n\n   private:\n    virtual void increment_basis_dimension() = 0;\n    virtual void decrement_basis_dimension() = 0;\n\n    \/\/ The vector of knots defining the mesh points for the spline.\n    \/\/ This is sorted by the constructor and it is kept sorted by\n    \/\/ add_knot() and remove_knot().  The terminal knots at the\n    \/\/ beginning and end of this vector are assumed to repeat an\n    \/\/ infinite number of times.  If a knot is added outside the knot\n    \/\/ range, then the old terminal knot becomes a single knot, and\n    \/\/ the new terminal knot is infinitely repeated.\n    Vector knots_;\n  };\n\n}  \/\/ namespace BOOM\n#endif  \/\/ BOOM_SPLINE_HPP\nAdd basis_matrix method to SplineBase.\/\/ Copyright 2018 Google LLC. All Rights Reserved.\n\/*\n  Copyright (C) 2016 Steven L. Scott\n\n  This library is free software; you can redistribute it and\/or\n  modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  This library is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n  Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with this library; if not, write to the Free Software\n  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA\n*\/\n#ifndef BOOM_SPLINE_HPP\n#define BOOM_SPLINE_HPP\n#include \"LinAlg\/Vector.hpp\"\n#include \"LinAlg\/Matrix.hpp\"\n\nnamespace BOOM {\n  \/\/ A base class providing features shared by different spline bases.\n  \/\/ Examples inclue Bsplines, Msplines, and Isplines.\n  class SplineBase {\n   public:\n    \/\/ Args:\n    \/\/   knots: The set of knots for the spline.  Between pairs of\n    \/\/     knots, the spline is a piecewise polynomial whose degree is\n    \/\/     given by the second argument.\n    \/\/\n    \/\/ Splines also have a notion of 'degree' or 'order', but this can\n    \/\/ be defined differently by different bases, so it is not part of\n    \/\/ the shared base class.\n    explicit SplineBase(const Vector &knots);\n    virtual ~SplineBase() {}\n\n    virtual Vector basis(double x) const = 0;\n\n    Matrix basis_matrix(const Vector &x) const {\n      Matrix ans(x.size(), this->basis_dimension());\n      for (int i = 0; i < x.size(); ++i) {\n        ans.row(i) = this->basis(x[i]);\n      }\n      return ans;\n    }\n\n    \/\/ The dimension of the spline basis (i.e. the dimension of the\n    \/\/ vector returned by a call to 'basis()'.\n    virtual int basis_dimension() const = 0;\n\n    \/\/ Adds a knot at the given  Location.  If knot_location lies\n    \/\/ before the first or after the last current knot, then the\n    \/\/ domain of the spline is extended to cover knot_location.\n    void add_knot(double knot_location);\n\n    \/\/ Remove the specified knot.  An exception will be thrown if\n    \/\/ which_knot is outside the range of knots_.  If which_knot == 0\n    \/\/ or which_knot == number_of_knots() - 1 then the domain of the\n    \/\/ spline basis will be reduced.\n    void remove_knot(int which_knot);\n\n    \/\/ The vector of knots.  Implicit boundary knots are not included.\n    virtual const Vector &knots() const { return knots_; }\n    virtual int number_of_knots() const { return knots_.size(); }\n\n    \/\/ If the argument is in the interior of the knots vector, return\n    \/\/ knots_[i].  If it is off the end to the left return knots_[0].\n    \/\/ If it is off the end to the right then include knots_.back().\n    \/\/ The implicit assumption is that we have an infinite set of\n    \/\/ knots piled up on the beginning and end of the actual knot\n    \/\/ sequence.\n    virtual double knot(int i) const;\n\n    virtual double final_knot() const;\n\n    \/\/ Compute the index of the largest knot less than or equal to x.\n    virtual int knot_span(double x) const;\n\n   private:\n    virtual void increment_basis_dimension() = 0;\n    virtual void decrement_basis_dimension() = 0;\n\n    \/\/ The vector of knots defining the mesh points for the spline.\n    \/\/ This is sorted by the constructor and it is kept sorted by\n    \/\/ add_knot() and remove_knot().  The terminal knots at the\n    \/\/ beginning and end of this vector are assumed to repeat an\n    \/\/ infinite number of times.  If a knot is added outside the knot\n    \/\/ range, then the old terminal knot becomes a single knot, and\n    \/\/ the new terminal knot is infinitely repeated.\n    Vector knots_;\n  };\n\n}  \/\/ namespace BOOM\n#endif  \/\/ BOOM_SPLINE_HPP\n<|endoftext|>"}
{"text":"#include \n\n#include \"utils.h\"\n#include \"client_base.h\"\n\n\nconst int WRITE_QUEUE_SIZE = 30;\n\n\nint BaseClient::total_clients = 0;\n\n\nBaseClient::BaseClient(ev::loop_ref &loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)\n\t: io(loop),\n\t  async(loop),\n\t  destroyed(false),\n\t  closed(false),\n\t  sock(sock_),\n\t  database_pool(database_pool_),\n\t  write_queue(WRITE_QUEUE_SIZE)\n{\n\tsig.set(this);\n\tsig.start(SIGINT);\n\n\tasync.set(this);\n\tasync.start();\n\n\tio.set(this);\n\tio.start(sock, ev::READ);\n}\n\n\nBaseClient::~BaseClient()\n{\n\tdestroy();\n\tsig.stop();\n\tLOG_OBJ(this, \"DELETED!\\n\");\n}\n\n\nvoid BaseClient::signal_cb(ev::sig &signal, int revents)\n{\n\tLOG_EV(this, \"Signaled destroy!!\\n\");\n\tdestroy();\n\tdelete this;\n}\n\n\nvoid BaseClient::destroy()\n{\n\tif (destroyed) {\n\t\treturn;\n\t}\n\n\tdestroyed = true;\n\n\tclose();\n\t\n\t\/\/ Stop and free watcher if client socket is closing\n\tio.stop();\n\tasync.stop();\n\t\n\t::close(sock);\n\tLOG_OBJ(this, \"DESTROYED!\\n\");\n}\n\n\nvoid BaseClient::close() {\n\tif (closed) {\n\t\treturn;\n\t}\n\n\tclosed = true;\n\tLOG_OBJ(this, \"CLOSED!\\n\");\n}\n\n\nvoid BaseClient::async_cb(ev::async &watcher, int revents)\n{\n\tif (destroyed) {\n\t\treturn;\n\t}\n\n\tLOG_EV(this, \"ASYNC_CB (sock=%d) %x\\n\", sock, revents);\n\n\tif (write_queue.empty()) {\n\t\tif (closed) {\n\t\t\tdestroy();\n\t\t}\n\t} else {\n\t\tio.set(ev::READ|ev::WRITE);\n\t}\n\t\n\tif (destroyed) {\n\t\tdelete this;\n\t}\n}\n\n\nvoid BaseClient::io_cb(ev::io &watcher, int revents)\n{\n\tif (destroyed) {\n\t\treturn;\n\t}\n\n\tLOG_EV(this, \"IO_CB (sock=%d) %x\\n\", sock, revents);\n\n\tif (revents & EV_ERROR) {\n\t\tLOG_ERR(this, \"ERROR: got invalid event (sock=%d): %s\\n\", sock, strerror(errno));\n\t\tdestroy();\n\t\treturn;\n\t}\n\n\tif (revents & EV_READ)\n\t\tread_cb(watcher);\n\n\tif (revents & EV_WRITE)\n\t\twrite_cb(watcher);\n\n\tif (write_queue.empty()) {\n\t\tif (closed) {\n\t\t\tdestroy();\n\t\t} else {\n\t\t\tio.set(ev::READ);\n\t\t}\n\t} else {\n\t\tio.set(ev::READ|ev::WRITE);\n\t}\n\n\tif (destroyed) {\n\t\tdelete this;\n\t}\n}\n\n\nvoid BaseClient::write_cb(ev::io &watcher)\n{\n\tif (write_queue.empty()) {\n\t\tio.set(ev::READ);\n\t} else {\n\t\tBuffer* buffer = write_queue.front();\n\n\t\tsize_t buf_size = buffer->nbytes();\n\t\tconst char * buf = buffer->dpos();\n\n\t\tLOG_CONN(this, \"(sock=%d) <<-- '%s'\\n\", sock, repr(buf, buf_size).c_str());\n\n\t\tssize_t written = ::write(watcher.fd, buf, buf_size);\n\n\t\tif (written < 0) {\n\t\t\tif (errno != EAGAIN) {\n\t\t\t\tLOG_ERR(this, \"ERROR: write error (sock=%d): %s\\n\", sock, strerror(errno));\n\t\t\t\tdestroy();\n\t\t\t}\n\t\t} else if (written == 0) {\n\t\t\t\/\/ nothing written?\n\t\t} else {\n\t\t\tbuffer->pos += written;\n\t\t\tif (buffer->nbytes() == 0) {\n\t\t\t\twrite_queue.pop(buffer);\n\t\t\t\tdelete buffer;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid BaseClient::read_cb(ev::io &watcher)\n{\n\tchar buf[1024];\n\t\n\tssize_t received = ::read(watcher.fd, buf, sizeof(buf));\n\t\n\tif (received < 0) {\n\t\tif (errno != EAGAIN) {\n\t\t\tLOG_ERR(this, \"ERROR: read error (sock=%d): %s\\n\", sock, strerror(errno));\n\t\t\tdestroy();\n\t\t}\n\t} else if (received == 0) {\n\t\t\/\/ The peer has closed its half side of the connection.\n\t\tLOG_CONN(this, \"Received EOF (sock=%d)!\\n\", sock);\n\t\tdestroy();\n\t} else {\n\t\tLOG_CONN(this, \"(sock=%d) -->> '%s'\\n\", sock, repr(buf, received).c_str());\n\t\ton_read(buf, received);\n\t}\n}\n\n\nvoid BaseClient::write(const char *buf, size_t buf_size)\n{\n\tBuffer *buffer = new Buffer('\\0', buf, buf_size);\n\twrite_queue.push(buffer);\n\n\tasync.send();\n}\nWrite queue without limits#include \n\n#include \"utils.h\"\n#include \"client_base.h\"\n\n\nconst int WRITE_QUEUE_SIZE = -1;\n\n\nint BaseClient::total_clients = 0;\n\n\nBaseClient::BaseClient(ev::loop_ref &loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)\n\t: io(loop),\n\t  async(loop),\n\t  destroyed(false),\n\t  closed(false),\n\t  sock(sock_),\n\t  database_pool(database_pool_),\n\t  write_queue(WRITE_QUEUE_SIZE)\n{\n\tsig.set(this);\n\tsig.start(SIGINT);\n\n\tasync.set(this);\n\tasync.start();\n\n\tio.set(this);\n\tio.start(sock, ev::READ);\n}\n\n\nBaseClient::~BaseClient()\n{\n\tdestroy();\n\tsig.stop();\n\tLOG_OBJ(this, \"DELETED!\\n\");\n}\n\n\nvoid BaseClient::signal_cb(ev::sig &signal, int revents)\n{\n\tLOG_EV(this, \"Signaled destroy!!\\n\");\n\tdestroy();\n\tdelete this;\n}\n\n\nvoid BaseClient::destroy()\n{\n\tif (destroyed) {\n\t\treturn;\n\t}\n\n\tdestroyed = true;\n\n\tclose();\n\t\n\t\/\/ Stop and free watcher if client socket is closing\n\tio.stop();\n\tasync.stop();\n\t\n\t::close(sock);\n\tLOG_OBJ(this, \"DESTROYED!\\n\");\n}\n\n\nvoid BaseClient::close() {\n\tif (closed) {\n\t\treturn;\n\t}\n\n\tclosed = true;\n\tLOG_OBJ(this, \"CLOSED!\\n\");\n}\n\n\nvoid BaseClient::async_cb(ev::async &watcher, int revents)\n{\n\tif (destroyed) {\n\t\treturn;\n\t}\n\n\tLOG_EV(this, \"ASYNC_CB (sock=%d) %x\\n\", sock, revents);\n\n\tif (write_queue.empty()) {\n\t\tif (closed) {\n\t\t\tdestroy();\n\t\t}\n\t} else {\n\t\tio.set(ev::READ|ev::WRITE);\n\t}\n\t\n\tif (destroyed) {\n\t\tdelete this;\n\t}\n}\n\n\nvoid BaseClient::io_cb(ev::io &watcher, int revents)\n{\n\tif (destroyed) {\n\t\treturn;\n\t}\n\n\tLOG_EV(this, \"IO_CB (sock=%d) %x\\n\", sock, revents);\n\n\tif (revents & EV_ERROR) {\n\t\tLOG_ERR(this, \"ERROR: got invalid event (sock=%d): %s\\n\", sock, strerror(errno));\n\t\tdestroy();\n\t\treturn;\n\t}\n\n\tif (revents & EV_READ)\n\t\tread_cb(watcher);\n\n\tif (revents & EV_WRITE)\n\t\twrite_cb(watcher);\n\n\tif (write_queue.empty()) {\n\t\tif (closed) {\n\t\t\tdestroy();\n\t\t} else {\n\t\t\tio.set(ev::READ);\n\t\t}\n\t} else {\n\t\tio.set(ev::READ|ev::WRITE);\n\t}\n\n\tif (destroyed) {\n\t\tdelete this;\n\t}\n}\n\n\nvoid BaseClient::write_cb(ev::io &watcher)\n{\n\tif (write_queue.empty()) {\n\t\tio.set(ev::READ);\n\t} else {\n\t\tBuffer* buffer = write_queue.front();\n\n\t\tsize_t buf_size = buffer->nbytes();\n\t\tconst char * buf = buffer->dpos();\n\n\t\tLOG_CONN(this, \"(sock=%d) <<-- '%s'\\n\", sock, repr(buf, buf_size).c_str());\n\n\t\tssize_t written = ::write(watcher.fd, buf, buf_size);\n\n\t\tif (written < 0) {\n\t\t\tif (errno != EAGAIN) {\n\t\t\t\tLOG_ERR(this, \"ERROR: write error (sock=%d): %s\\n\", sock, strerror(errno));\n\t\t\t\tdestroy();\n\t\t\t}\n\t\t} else if (written == 0) {\n\t\t\t\/\/ nothing written?\n\t\t} else {\n\t\t\tbuffer->pos += written;\n\t\t\tif (buffer->nbytes() == 0) {\n\t\t\t\twrite_queue.pop(buffer);\n\t\t\t\tdelete buffer;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid BaseClient::read_cb(ev::io &watcher)\n{\n\tchar buf[1024];\n\t\n\tssize_t received = ::read(watcher.fd, buf, sizeof(buf));\n\t\n\tif (received < 0) {\n\t\tif (errno != EAGAIN) {\n\t\t\tLOG_ERR(this, \"ERROR: read error (sock=%d): %s\\n\", sock, strerror(errno));\n\t\t\tdestroy();\n\t\t}\n\t} else if (received == 0) {\n\t\t\/\/ The peer has closed its half side of the connection.\n\t\tLOG_CONN(this, \"Received EOF (sock=%d)!\\n\", sock);\n\t\tdestroy();\n\t} else {\n\t\tLOG_CONN(this, \"(sock=%d) -->> '%s'\\n\", sock, repr(buf, received).c_str());\n\t\ton_read(buf, received);\n\t}\n}\n\n\nvoid BaseClient::write(const char *buf, size_t buf_size)\n{\n\tBuffer *buffer = new Buffer('\\0', buf, buf_size);\n\twrite_queue.push(buffer);\n\n\tasync.send();\n}\n<|endoftext|>"}
{"text":"\/****************************************************************************\n *   Copyright (C) 2012-2015 by Savoir-Faire Linux                          *\n *   Author : Emmanuel Lepage Vallee  *\n *                                                                          *\n *   This library is free software; you can redistribute it and\/or          *\n *   modify it under the terms of the GNU Lesser General Public             *\n *   License as published by the Free Software Foundation; either           *\n *   version 2.1 of the License, or (at your option) any later version.     *\n *                                                                          *\n *   This library is distributed in the hope that it will be useful,        *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of         *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU      *\n *   Lesser General Public License for more details.                        *\n *                                                                          *\n *   You should have received a copy of the GNU General Public License      *\n *   along with this program.  If not, see .  *\n ***************************************************************************\/\n#include \"codecmodel.h\"\n\n\/\/Qt\n#include \n#include \n#include \n\n\/\/DRing\n#include \n\n\/\/Ring\n#include \"account.h\"\n#include \"dbus\/configurationmanager.h\"\n\nclass CodecModelPrivate : public QObject\n{\n   Q_OBJECT\npublic:\n   CodecModelPrivate(CodecModel* parent);\n   \/\/\/@struct AudioCodecData store audio codec information\n   struct AudioCodecData {\n      int              id        ;\n      QString          name      ;\n      QString          bitrate   ;\n      QString          samplerate;\n      QString          type      ;\n   };\n\n   \/\/Attributes\n   QList m_lAudioCodecs  ;\n   QMap         m_lEnabledCodecs;\n   Account*               m_pAccount      ;\n   QSortFilterProxyModel* m_pAudioProxy   ;\n   QSortFilterProxyModel* m_pVideoProxy   ;\n\n   \/\/Helpers\n   bool findCodec(int id);\n\nprivate:\n   CodecModel* q_ptr;\n};\n\nCodecModelPrivate::CodecModelPrivate(CodecModel* parent) : q_ptr(parent),\nm_pAudioProxy(nullptr),m_pVideoProxy(nullptr)\n{\n\n}\n\n\/\/\/Constructor\nCodecModel::CodecModel(Account* account) :\nQAbstractListModel(account?(QObject*)account:(QObject*)QCoreApplication::instance()), d_ptr(new CodecModelPrivate(this))\n{\n   d_ptr->m_pAccount = account;\n   setObjectName(\"CodecModel: \"+(account?account->id():\"Unknown\"));\n}\n\nCodecModel::~CodecModel()\n{\n   while (d_ptr->m_lAudioCodecs.size()) {\n      CodecModelPrivate::AudioCodecData* c = d_ptr->m_lAudioCodecs[0];\n      d_ptr->m_lAudioCodecs.removeAt(0);\n      delete c;\n   }\n}\n\nQHash CodecModel::roleNames() const\n{\n   static QHash roles = QAbstractItemModel::roleNames();\n   static bool initRoles = false;\n   if (!initRoles) {\n      initRoles = true;\n      roles.insert(CodecModel::Role::ID        ,QByteArray(\"id\"));\n      roles.insert(CodecModel::Role::NAME      ,QByteArray(\"name\"));\n      roles.insert(CodecModel::Role::BITRATE   ,QByteArray(\"bitrate\"));\n      roles.insert(CodecModel::Role::SAMPLERATE,QByteArray(\"samplerate\"));\n      roles.insert(CodecModel::Role::TYPE      ,QByteArray(\"type\"));\n   }\n   return roles;\n}\n\n\/\/\/Model data\nQVariant CodecModel::data(const QModelIndex& idx, int role) const {\n   if(idx.column() == 0      && role == Qt::DisplayRole                   ) {\n      return QVariant(d_ptr->m_lAudioCodecs[idx.row()]->name);\n   }\n   else if(idx.column() == 0 && role == Qt::CheckStateRole                ) {\n      return QVariant(d_ptr->m_lEnabledCodecs[d_ptr->m_lAudioCodecs[idx.row()]->id] ? Qt::Checked : Qt::Unchecked);\n   }\n   else if (idx.column() == 0 && role == CodecModel::Role::NAME       ) {\n      return d_ptr->m_lAudioCodecs[idx.row()]->name;\n   }\n   else if (idx.column() == 0 && role == CodecModel::Role::BITRATE    ) {\n      return d_ptr->m_lAudioCodecs[idx.row()]->bitrate;\n   }\n   else if (idx.column() == 0 && role == CodecModel::Role::SAMPLERATE ) {\n      return d_ptr->m_lAudioCodecs[idx.row()]->samplerate;\n   }\n   else if (idx.column() == 0 && role == CodecModel::Role::ID         ) {\n      return d_ptr->m_lAudioCodecs[idx.row()]->id;\n   }\n   else if (idx.column() == 0 && role == CodecModel::Role::TYPE         ) {\n      return d_ptr->m_lAudioCodecs[idx.row()]->type;\n   }\n   return QVariant();\n}\n\n\/\/\/Number of audio codecs\nint CodecModel::rowCount(const QModelIndex& par) const {\n   Q_UNUSED(par)\n   return d_ptr->m_lAudioCodecs.size();\n}\n\n\/\/\/Model flags\nQt::ItemFlags CodecModel::flags(const QModelIndex& idx) const {\n   if (idx.column() == 0)\n      return QAbstractItemModel::flags(idx) | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n   return QAbstractItemModel::flags(idx);\n}\n\n\/\/\/Set audio codec data\nbool CodecModel::setData( const QModelIndex& idx, const QVariant &value, int role) {\n   if (idx.column() == 0 && role == CodecModel::NAME) {\n      d_ptr->m_lAudioCodecs[idx.row()]->name = value.toString();\n      emit dataChanged(idx, idx);\n      return true;\n   }\n   else if (idx.column() == 0 && role == CodecModel::BITRATE) {\n      d_ptr->m_lAudioCodecs[idx.row()]->bitrate = value.toString();\n      emit dataChanged(idx, idx);\n      return true;\n   }\n   else if(idx.column() == 0 && role == Qt::CheckStateRole) {\n      d_ptr->m_lEnabledCodecs[d_ptr->m_lAudioCodecs[idx.row()]->id] = value.toBool();\n      emit dataChanged(idx, idx);\n      return true;\n   }\n   else if (idx.column() == 0 && role == CodecModel::SAMPLERATE) {\n      d_ptr->m_lAudioCodecs[idx.row()]->samplerate = value.toString();\n      emit dataChanged(idx, idx);\n      return true;\n   }\n   else if (idx.column() == 0 && role == CodecModel::ID) {\n      d_ptr->m_lAudioCodecs[idx.row()]->id = value.toInt();\n      emit dataChanged(idx, idx);\n      return true;\n   }\n   else if (idx.column() == 0 && role == CodecModel::TYPE) {\n      d_ptr->m_lAudioCodecs[idx.row()]->type = value.toString();\n      emit dataChanged(idx, idx);\n      return true;\n   }\n   return false;\n}\n\n\/\/\/Add a new audio codec\nQModelIndex CodecModel::add() {\n   d_ptr->m_lAudioCodecs << new CodecModelPrivate::AudioCodecData;\n   emit dataChanged(index(d_ptr->m_lAudioCodecs.size()-1,0), index(d_ptr->m_lAudioCodecs.size()-1,0));\n   return index(d_ptr->m_lAudioCodecs.size()-1,0);\n}\n\n\/\/\/Remove audio codec at 'idx'\nvoid CodecModel::remove(const QModelIndex& idx) {\n   if (idx.isValid()) {\n      CodecModelPrivate::AudioCodecData* d = d_ptr->m_lAudioCodecs[idx.row()];\n      d_ptr->m_lAudioCodecs.removeAt(idx.row());\n      delete d;\n      emit dataChanged(idx, index(d_ptr->m_lAudioCodecs.size()-1,0));\n   }\n   else {\n      qDebug() << \"Failed to remove an invalid audio codec\";\n   }\n}\n\n\/\/\/Remove everything\nvoid CodecModel::clear()\n{\n   while(d_ptr->m_lAudioCodecs.size()) {\n      CodecModelPrivate::AudioCodecData* d = d_ptr->m_lAudioCodecs[0];\n      d_ptr->m_lAudioCodecs.removeAt(0);\n      delete d;\n   }\n   d_ptr->m_lAudioCodecs.clear  ();\n   d_ptr->m_lEnabledCodecs.clear();\n}\n\n\/\/\/Increase codec priority\nbool CodecModel::moveUp(const QModelIndex& idx)\n{\n   if(idx.row() > 0 && idx.row() <= rowCount()) {\n      CodecModelPrivate::AudioCodecData* data2 = d_ptr->m_lAudioCodecs[idx.row()];\n      d_ptr->m_lAudioCodecs.removeAt(idx.row());\n      d_ptr->m_lAudioCodecs.insert(idx.row() - 1, data2);\n      emit dataChanged(index(idx.row() - 1, 0, QModelIndex()), index(idx.row(), 0, QModelIndex()));\n      return true;\n   }\n   return false;\n}\n\n\/\/\/Decrease codec priority\nbool CodecModel::moveDown(const QModelIndex& idx)\n{\n   if(idx.row() >= 0 && idx.row() < rowCount()) {\n      CodecModelPrivate::AudioCodecData* data2 = d_ptr->m_lAudioCodecs[idx.row()];\n      d_ptr->m_lAudioCodecs.removeAt(idx.row());\n      d_ptr->m_lAudioCodecs.insert(idx.row() + 1, data2);\n      emit dataChanged(index(idx.row(), 0, QModelIndex()), index(idx.row() + 1, 0, QModelIndex()));\n      return true;\n   }\n   return false;\n}\n\n\/\/\/Reload the codeclist\nvoid CodecModel::reload()\n{\n   ConfigurationManagerInterface& configurationManager = DBus::ConfigurationManager::instance();\n   QVector codecIdList = configurationManager.getCodecList();\n   if (!d_ptr->m_pAccount->isNew()) {\n      QVector activeCodecList = configurationManager.getActiveCodecList(d_ptr->m_pAccount->id());\n      QStringList tmpNameList;\n\n      foreach (const int aCodec, activeCodecList) {\n         if (!d_ptr->findCodec(aCodec)) {\n\n            const QMap codec = configurationManager.getCodecDetails(d_ptr->m_pAccount->id(),aCodec);\n\n            QModelIndex idx = add();\n            setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::NAME        ] ,CodecModel::Role::NAME       );\n            setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::SAMPLE_RATE ] ,CodecModel::Role::SAMPLERATE );\n            setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::BITRATE     ] ,CodecModel::Role::BITRATE    );\n            setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::TYPE        ] ,CodecModel::Role::TYPE       );\n            setData(idx,QString::number(aCodec)  ,CodecModel::Role::ID         );\n            setData(idx, Qt::Checked ,Qt::CheckStateRole               );\n\n            if (codecIdList.indexOf(aCodec)!=-1)\n               codecIdList.remove(codecIdList.indexOf(aCodec));\n         }\n      }\n   }\n\n   foreach (const int aCodec, codecIdList) {\n      if (!d_ptr->findCodec(aCodec)) {\n         const QMap codec = configurationManager.getCodecDetails(d_ptr->m_pAccount->id(),aCodec);\n         const QModelIndex& idx = add();\n         setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::NAME        ] ,CodecModel::Role::NAME       );\n         setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::SAMPLE_RATE ] ,CodecModel::Role::SAMPLERATE );\n         setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::BITRATE     ] ,CodecModel::Role::BITRATE    );\n         setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::TYPE        ] ,CodecModel::Role::TYPE       );\n         setData(idx,QString::number(aCodec)  ,CodecModel::Role::ID         );\n         setData(idx, Qt::Unchecked ,Qt::CheckStateRole);\n      }\n   }\n}\n\n\/\/\/Save details\nvoid CodecModel::save()\n{\n   VectorUInt _codecList;\n   for (int i=0; i < rowCount();i++) {\n      const QModelIndex& idx = index(i,0);\n      if (data(idx,Qt::CheckStateRole) == Qt::Checked) {\n         _codecList << data(idx,CodecModel::Role::ID).toInt();\n      }\n   }\n\n   ConfigurationManagerInterface& configurationManager = DBus::ConfigurationManager::instance();\n   configurationManager.setActiveCodecList(d_ptr->m_pAccount->id(), _codecList);\n}\n\n\/\/\/Check is a codec is already in the list\nbool CodecModelPrivate::findCodec(int id)\n{\n   foreach(const AudioCodecData* data, m_lAudioCodecs) {\n      if (data->id == id)\n         return true;\n   }\n   return false;\n}\n\n\nQSortFilterProxyModel* CodecModel::audioCodecs() const\n{\n    if (!d_ptr->m_pAudioProxy) {\n        d_ptr->m_pAudioProxy = new QSortFilterProxyModel(const_cast(this));\n        d_ptr->m_pAudioProxy->setSourceModel(const_cast(this));\n        d_ptr->m_pAudioProxy->setFilterRole(CodecModel::Role::TYPE);\n        d_ptr->m_pAudioProxy->setFilterFixedString(\"AUDIO\");\n    }\n    return d_ptr->m_pAudioProxy;\n}\n\nQSortFilterProxyModel* CodecModel::videoCodecs() const\n{\n    if (!d_ptr->m_pVideoProxy) {\n        d_ptr->m_pVideoProxy = new QSortFilterProxyModel(const_cast(this));\n        d_ptr->m_pVideoProxy->setSourceModel(const_cast(this));\n        d_ptr->m_pVideoProxy->setFilterRole(CodecModel::Role::TYPE);\n        d_ptr->m_pVideoProxy->setFilterFixedString(\"VIDEO\");\n    }\n    return d_ptr->m_pVideoProxy;\n}\n\n#include \ncodecmodel: remove unnecessary check\/****************************************************************************\n *   Copyright (C) 2012-2015 by Savoir-Faire Linux                          *\n *   Author : Emmanuel Lepage Vallee  *\n *                                                                          *\n *   This library is free software; you can redistribute it and\/or          *\n *   modify it under the terms of the GNU Lesser General Public             *\n *   License as published by the Free Software Foundation; either           *\n *   version 2.1 of the License, or (at your option) any later version.     *\n *                                                                          *\n *   This library is distributed in the hope that it will be useful,        *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of         *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU      *\n *   Lesser General Public License for more details.                        *\n *                                                                          *\n *   You should have received a copy of the GNU General Public License      *\n *   along with this program.  If not, see .  *\n ***************************************************************************\/\n#include \"codecmodel.h\"\n\n\/\/Qt\n#include \n#include \n#include \n\n\/\/DRing\n#include \n\n\/\/Ring\n#include \"account.h\"\n#include \"dbus\/configurationmanager.h\"\n\nclass CodecModelPrivate : public QObject\n{\n   Q_OBJECT\npublic:\n   CodecModelPrivate(CodecModel* parent);\n   \/\/\/@struct AudioCodecData store audio codec information\n   struct AudioCodecData {\n      int              id        ;\n      QString          name      ;\n      QString          bitrate   ;\n      QString          samplerate;\n      QString          type      ;\n   };\n\n   \/\/Attributes\n   QList m_lAudioCodecs  ;\n   QMap         m_lEnabledCodecs;\n   Account*               m_pAccount      ;\n   QSortFilterProxyModel* m_pAudioProxy   ;\n   QSortFilterProxyModel* m_pVideoProxy   ;\n\n   \/\/Helpers\n   bool findCodec(int id);\n\nprivate:\n   CodecModel* q_ptr;\n};\n\nCodecModelPrivate::CodecModelPrivate(CodecModel* parent) : q_ptr(parent),\nm_pAudioProxy(nullptr),m_pVideoProxy(nullptr)\n{\n\n}\n\n\/\/\/Constructor\nCodecModel::CodecModel(Account* account) :\nQAbstractListModel(account?(QObject*)account:(QObject*)QCoreApplication::instance()), d_ptr(new CodecModelPrivate(this))\n{\n   d_ptr->m_pAccount = account;\n   setObjectName(\"CodecModel: \"+(account?account->id():\"Unknown\"));\n}\n\nCodecModel::~CodecModel()\n{\n   while (d_ptr->m_lAudioCodecs.size()) {\n      CodecModelPrivate::AudioCodecData* c = d_ptr->m_lAudioCodecs[0];\n      d_ptr->m_lAudioCodecs.removeAt(0);\n      delete c;\n   }\n}\n\nQHash CodecModel::roleNames() const\n{\n   static QHash roles = QAbstractItemModel::roleNames();\n   static bool initRoles = false;\n   if (!initRoles) {\n      initRoles = true;\n      roles.insert(CodecModel::Role::ID        ,QByteArray(\"id\"));\n      roles.insert(CodecModel::Role::NAME      ,QByteArray(\"name\"));\n      roles.insert(CodecModel::Role::BITRATE   ,QByteArray(\"bitrate\"));\n      roles.insert(CodecModel::Role::SAMPLERATE,QByteArray(\"samplerate\"));\n      roles.insert(CodecModel::Role::TYPE      ,QByteArray(\"type\"));\n   }\n   return roles;\n}\n\n\/\/\/Model data\nQVariant CodecModel::data(const QModelIndex& idx, int role) const {\n   if(idx.column() == 0      && role == Qt::DisplayRole                   ) {\n      return QVariant(d_ptr->m_lAudioCodecs[idx.row()]->name);\n   }\n   else if(idx.column() == 0 && role == Qt::CheckStateRole                ) {\n      return QVariant(d_ptr->m_lEnabledCodecs[d_ptr->m_lAudioCodecs[idx.row()]->id] ? Qt::Checked : Qt::Unchecked);\n   }\n   else if (idx.column() == 0 && role == CodecModel::Role::NAME       ) {\n      return d_ptr->m_lAudioCodecs[idx.row()]->name;\n   }\n   else if (idx.column() == 0 && role == CodecModel::Role::BITRATE    ) {\n      return d_ptr->m_lAudioCodecs[idx.row()]->bitrate;\n   }\n   else if (idx.column() == 0 && role == CodecModel::Role::SAMPLERATE ) {\n      return d_ptr->m_lAudioCodecs[idx.row()]->samplerate;\n   }\n   else if (idx.column() == 0 && role == CodecModel::Role::ID         ) {\n      return d_ptr->m_lAudioCodecs[idx.row()]->id;\n   }\n   else if (idx.column() == 0 && role == CodecModel::Role::TYPE         ) {\n      return d_ptr->m_lAudioCodecs[idx.row()]->type;\n   }\n   return QVariant();\n}\n\n\/\/\/Number of audio codecs\nint CodecModel::rowCount(const QModelIndex& par) const {\n   Q_UNUSED(par)\n   return d_ptr->m_lAudioCodecs.size();\n}\n\n\/\/\/Model flags\nQt::ItemFlags CodecModel::flags(const QModelIndex& idx) const {\n   if (idx.column() == 0)\n      return QAbstractItemModel::flags(idx) | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n   return QAbstractItemModel::flags(idx);\n}\n\n\/\/\/Set audio codec data\nbool CodecModel::setData( const QModelIndex& idx, const QVariant &value, int role) {\n   if (idx.column() == 0 && role == CodecModel::NAME) {\n      d_ptr->m_lAudioCodecs[idx.row()]->name = value.toString();\n      emit dataChanged(idx, idx);\n      return true;\n   }\n   else if (idx.column() == 0 && role == CodecModel::BITRATE) {\n      d_ptr->m_lAudioCodecs[idx.row()]->bitrate = value.toString();\n      emit dataChanged(idx, idx);\n      return true;\n   }\n   else if(idx.column() == 0 && role == Qt::CheckStateRole) {\n      d_ptr->m_lEnabledCodecs[d_ptr->m_lAudioCodecs[idx.row()]->id] = value.toBool();\n      emit dataChanged(idx, idx);\n      return true;\n   }\n   else if (idx.column() == 0 && role == CodecModel::SAMPLERATE) {\n      d_ptr->m_lAudioCodecs[idx.row()]->samplerate = value.toString();\n      emit dataChanged(idx, idx);\n      return true;\n   }\n   else if (idx.column() == 0 && role == CodecModel::ID) {\n      d_ptr->m_lAudioCodecs[idx.row()]->id = value.toInt();\n      emit dataChanged(idx, idx);\n      return true;\n   }\n   else if (idx.column() == 0 && role == CodecModel::TYPE) {\n      d_ptr->m_lAudioCodecs[idx.row()]->type = value.toString();\n      emit dataChanged(idx, idx);\n      return true;\n   }\n   return false;\n}\n\n\/\/\/Add a new audio codec\nQModelIndex CodecModel::add() {\n   d_ptr->m_lAudioCodecs << new CodecModelPrivate::AudioCodecData;\n   emit dataChanged(index(d_ptr->m_lAudioCodecs.size()-1,0), index(d_ptr->m_lAudioCodecs.size()-1,0));\n   return index(d_ptr->m_lAudioCodecs.size()-1,0);\n}\n\n\/\/\/Remove audio codec at 'idx'\nvoid CodecModel::remove(const QModelIndex& idx) {\n   if (idx.isValid()) {\n      CodecModelPrivate::AudioCodecData* d = d_ptr->m_lAudioCodecs[idx.row()];\n      d_ptr->m_lAudioCodecs.removeAt(idx.row());\n      delete d;\n      emit dataChanged(idx, index(d_ptr->m_lAudioCodecs.size()-1,0));\n   }\n   else {\n      qDebug() << \"Failed to remove an invalid audio codec\";\n   }\n}\n\n\/\/\/Remove everything\nvoid CodecModel::clear()\n{\n   while(d_ptr->m_lAudioCodecs.size()) {\n      CodecModelPrivate::AudioCodecData* d = d_ptr->m_lAudioCodecs[0];\n      d_ptr->m_lAudioCodecs.removeAt(0);\n      delete d;\n   }\n   d_ptr->m_lAudioCodecs.clear  ();\n   d_ptr->m_lEnabledCodecs.clear();\n}\n\n\/\/\/Increase codec priority\nbool CodecModel::moveUp(const QModelIndex& idx)\n{\n   if(idx.row() > 0 && idx.row() <= rowCount()) {\n      CodecModelPrivate::AudioCodecData* data2 = d_ptr->m_lAudioCodecs[idx.row()];\n      d_ptr->m_lAudioCodecs.removeAt(idx.row());\n      d_ptr->m_lAudioCodecs.insert(idx.row() - 1, data2);\n      emit dataChanged(index(idx.row() - 1, 0, QModelIndex()), index(idx.row(), 0, QModelIndex()));\n      return true;\n   }\n   return false;\n}\n\n\/\/\/Decrease codec priority\nbool CodecModel::moveDown(const QModelIndex& idx)\n{\n   if(idx.row() >= 0 && idx.row() < rowCount()) {\n      CodecModelPrivate::AudioCodecData* data2 = d_ptr->m_lAudioCodecs[idx.row()];\n      d_ptr->m_lAudioCodecs.removeAt(idx.row());\n      d_ptr->m_lAudioCodecs.insert(idx.row() + 1, data2);\n      emit dataChanged(index(idx.row(), 0, QModelIndex()), index(idx.row() + 1, 0, QModelIndex()));\n      return true;\n   }\n   return false;\n}\n\n\/\/\/Reload the codeclist\nvoid CodecModel::reload()\n{\n   ConfigurationManagerInterface& configurationManager = DBus::ConfigurationManager::instance();\n   QVector codecIdList = configurationManager.getCodecList();\n      QVector activeCodecList = configurationManager.getActiveCodecList(d_ptr->m_pAccount->id());\n      QStringList tmpNameList;\n\n  foreach (const int aCodec, activeCodecList) {\n     if (!d_ptr->findCodec(aCodec)) {\n\n        const QMap codec = configurationManager.getCodecDetails(d_ptr->m_pAccount->id(),aCodec);\n\n        QModelIndex idx = add();\n        setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::NAME        ] ,CodecModel::Role::NAME       );\n        setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::SAMPLE_RATE ] ,CodecModel::Role::SAMPLERATE );\n        setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::BITRATE     ] ,CodecModel::Role::BITRATE    );\n        setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::TYPE        ] ,CodecModel::Role::TYPE       );\n        setData(idx,QString::number(aCodec)  ,CodecModel::Role::ID         );\n        setData(idx, Qt::Checked ,Qt::CheckStateRole               );\n\n        if (codecIdList.indexOf(aCodec)!=-1)\n           codecIdList.remove(codecIdList.indexOf(aCodec));\n     }\n  }\n\n   foreach (const int aCodec, codecIdList) {\n      if (!d_ptr->findCodec(aCodec)) {\n         const QMap codec = configurationManager.getCodecDetails(d_ptr->m_pAccount->id(),aCodec);\n         const QModelIndex& idx = add();\n         setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::NAME        ] ,CodecModel::Role::NAME       );\n         setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::SAMPLE_RATE ] ,CodecModel::Role::SAMPLERATE );\n         setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::BITRATE     ] ,CodecModel::Role::BITRATE    );\n         setData(idx,codec[ DRing::Account::ConfProperties::CodecInfo::TYPE        ] ,CodecModel::Role::TYPE       );\n         setData(idx,QString::number(aCodec)  ,CodecModel::Role::ID         );\n         setData(idx, Qt::Unchecked ,Qt::CheckStateRole);\n      }\n   }\n}\n\n\/\/\/Save details\nvoid CodecModel::save()\n{\n   VectorUInt _codecList;\n   for (int i=0; i < rowCount();i++) {\n      const QModelIndex& idx = index(i,0);\n      if (data(idx,Qt::CheckStateRole) == Qt::Checked) {\n         _codecList << data(idx,CodecModel::Role::ID).toInt();\n      }\n   }\n\n   ConfigurationManagerInterface& configurationManager = DBus::ConfigurationManager::instance();\n   configurationManager.setActiveCodecList(d_ptr->m_pAccount->id(), _codecList);\n}\n\n\/\/\/Check is a codec is already in the list\nbool CodecModelPrivate::findCodec(int id)\n{\n   foreach(const AudioCodecData* data, m_lAudioCodecs) {\n      if (data->id == id)\n         return true;\n   }\n   return false;\n}\n\n\nQSortFilterProxyModel* CodecModel::audioCodecs() const\n{\n    if (!d_ptr->m_pAudioProxy) {\n        d_ptr->m_pAudioProxy = new QSortFilterProxyModel(const_cast(this));\n        d_ptr->m_pAudioProxy->setSourceModel(const_cast(this));\n        d_ptr->m_pAudioProxy->setFilterRole(CodecModel::Role::TYPE);\n        d_ptr->m_pAudioProxy->setFilterFixedString(\"AUDIO\");\n    }\n    return d_ptr->m_pAudioProxy;\n}\n\nQSortFilterProxyModel* CodecModel::videoCodecs() const\n{\n    if (!d_ptr->m_pVideoProxy) {\n        d_ptr->m_pVideoProxy = new QSortFilterProxyModel(const_cast(this));\n        d_ptr->m_pVideoProxy->setSourceModel(const_cast(this));\n        d_ptr->m_pVideoProxy->setFilterRole(CodecModel::Role::TYPE);\n        d_ptr->m_pVideoProxy->setFilterFixedString(\"VIDEO\");\n    }\n    return d_ptr->m_pVideoProxy;\n}\n\n#include \n<|endoftext|>"}
{"text":"\/\/\n\/\/ Copyright (c) 2013-2017 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef RJ_CORE_GAME_WINDOW_HPP\n#define RJ_CORE_GAME_WINDOW_HPP\n\n#include \"game_updater.hpp\"\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace rj\n{\n\tusing window_style = int;\n\n\tclass game_window\n\t{\n\t\tmlk::uint m_width, m_height;\n\t\tstd::string m_title{\"Recto Jump\"};\n\t\tsf::RenderWindow m_window;\n\t\twindow_style m_windowstyles;\n\t\tbool m_running{false};\n\t\tbool m_need_recreate{false};\n\n\t\tgame_updater m_game_updater;\n\t\tinput& m_input{input::get()};\n\n\t\tmlk::event_delegates m_on_event;\n\n\tpublic:\n\t\tmlk::slot<> on_stop;\n\n\t\tgame_window(const vec2u& size, bool fullscreen = false)\n\t\t\t: m_width{size.x}, m_height{size.y}\n\t\t{\n\t\t\tm_window.setFramerateLimit(60);\n\t\t\tthis->set_fullscreen(fullscreen);\n\t\t\tthis->init();\n\t\t}\n\n\t\t\/\/ interface\n\t\tvoid start()\n\t\t{\n\t\t\tif(m_running) return;\n\n\t\t\tthis->prepare_start();\n\t\t\twhile(m_running)\n\t\t\t{\n\t\t\t\tif(m_need_recreate) this->recreate();\n\n\t\t\t\tm_game_updater.start_pt();\n\n\t\t\t\t\/\/ update\n\t\t\t\tthis->update_events();\n\t\t\t\tm_input.update();\n\t\t\t\tm_game_updater.update();\n\n\t\t\t\t\/\/ render\n\t\t\t\tm_window.clear();\n\t\t\t\tm_game_updater.render();\n\t\t\t\tm_window.display();\n\n\t\t\t\tm_game_updater.end_pt();\n\t\t\t}\n\t\t}\n\n\t\tvoid stop() noexcept\n\t\t{\n\t\t\ton_stop();\n\t\t\tm_running = false;\n\t\t}\n\n\t\tauto& on_event(sf::Event::EventType type) { return m_on_event[type]; }\n\n\t\ttemplate \n\t\tvoid draw(Args&&... args)\n\t\t{\n\t\t\tm_window.draw(std::forward(args)...);\n\t\t}\n\n\t\tvoid toggle_fullscreen() noexcept\n\t\t{\n\t\t\tm_windowstyles ^= sf::Style::Fullscreen;\n\t\t\tm_need_recreate = true;\n\t\t}\n\n\t\tvoid toggle_titlebar() noexcept\n\t\t{\n\t\t\tm_windowstyles ^= sf::Style::Titlebar;\n\t\t\tm_need_recreate = true;\n\t\t}\n\n\t\t\/\/ setters\n\t\tvoid set_framereate_limit(mlk::uint limit) noexcept\n\t\t{\n\t\t\tm_window.setFramerateLimit(limit);\n\t\t}\n\n\t\tvoid set_size(const vec2u& size) noexcept { m_window.setSize(size); }\n\n\t\tvoid set_position(const vec2i& position) noexcept\n\t\t{\n\t\t\tm_window.setPosition(position);\n\t\t}\n\n\t\tvoid set_fullscreen(bool b) noexcept\n\t\t{\n\t\t\tif(b == (m_windowstyles & sf::Style::Fullscreen)) return;\n\t\t\tb ? m_windowstyles |= sf::Style::Fullscreen\n\t\t\t  : m_windowstyles &= ~sf::Style::Fullscreen;\n\t\t\tm_need_recreate = true;\n\t\t}\n\n\t\tvoid set_titlebar(bool b) noexcept\n\t\t{\n\t\t\tif(b == (m_windowstyles & sf::Style::Titlebar)) return;\n\t\t\tb ? m_windowstyles |= sf::Style::Titlebar\n\t\t\t  : m_windowstyles &= ~sf::Style::Titlebar;\n\t\t\tm_need_recreate = true;\n\t\t}\n\n\t\tvoid set_view(const sf::View& v) noexcept { m_window.setView(v); }\n\n\t\t\/\/ getters\n\t\tsf::RenderWindow& get_renderwindow() noexcept { return m_window; }\n\n\t\tgame_updater& get_updater() noexcept { return m_game_updater; }\n\n\t\tvec2u get_size() const noexcept { return m_window.getSize(); }\n\n\t\tvec2i get_position() const noexcept { return m_window.getPosition(); }\n\n\t\tbool get_fullscreen() const noexcept\n\t\t{\n\t\t\treturn m_windowstyles & sf::Style::Fullscreen;\n\t\t}\n\n\t\tbool get_titlebar() const noexcept\n\t\t{\n\t\t\treturn m_windowstyles & sf::Style::Titlebar;\n\t\t}\n\n\tprivate:\n\t\tvoid init()\n\t\t{\n\t\t\tm_input.init(this);\n\t\t\tm_windowstyles |= sf::Style::Default;\n\t\t\tthis->recreate();\n\t\t}\n\n\t\tvoid prepare_start() noexcept\n\t\t{\n\t\t\tm_running = true;\n\t\t\tmlk::lout(\"rj::game_window\", true) << \"starting gamewindow\";\n\t\t}\n\n\t\tvoid update_events() noexcept\n\t\t{\n\t\t\tsf::Event ev;\n\t\t\twhile(m_window.pollEvent(ev))\n\t\t\t{\n\t\t\t\tswitch(ev.type)\n\t\t\t\t{\n\t\t\t\t\tcase sf::Event::EventType::Closed:\n\t\t\t\t\t\tthis->stop();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase sf::Event::EventType::KeyPressed:\n\t\t\t\t\t\tm_input.key_pressed(ev.key.code);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase sf::Event::EventType::KeyReleased:\n\t\t\t\t\t\tm_input.key_released(ev.key.code);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase sf::Event::EventType::MouseButtonPressed:\n\t\t\t\t\t\tm_input.btn_pressed(ev.mouseButton.button);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase sf::Event::EventType::MouseButtonReleased:\n\t\t\t\t\t\tm_input.btn_released(ev.mouseButton.button);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase sf::Event::EventType::MouseWheelMoved:\n\t\t\t\t\t\tm_input.mousewheel_moved(ev.mouseWheel.delta);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t\/\/ call custom on_event\n\t\t\t\tm_on_event[ev.type](ev);\n\t\t\t}\n\t\t}\n\n\t\tvoid recreate()\n\t\t{\n\t\t\tm_window.close();\n\t\t\tm_window.create({m_width, m_height}, m_title, m_windowstyles);\n\t\t\tm_need_recreate = false;\n\t\t}\n\t};\n}\/\/ namespace rj\n\n#endif\/\/ RJ_CORE_GAME_WINDOW_HPP\nrem testing\/\/\n\/\/ Copyright (c) 2013-2017 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef RJ_CORE_GAME_WINDOW_HPP\n#define RJ_CORE_GAME_WINDOW_HPP\n\n#include \"game_updater.hpp\"\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace rj\n{\n\tusing window_style = int;\n\n\tclass game_window\n\t{\n\t\tmlk::uint m_width, m_height;\n\t\tstd::string m_title{\"Recto Jump\"};\n\t\tsf::RenderWindow m_window;\n\t\twindow_style m_windowstyles;\n\t\tbool m_running{false};\n\t\tbool m_need_recreate{false};\n\n\t\tgame_updater m_game_updater;\n\t\tinput& m_input{input::get()};\n\n\t\tmlk::event_delegates m_on_event;\n\n\tpublic:\n\t\tmlk::slot<> on_stop;\n\n\t\tgame_window(const vec2u& size, bool fullscreen = false)\n\t\t\t: m_width{size.x}, m_height{size.y}\n\t\t{\n\t\t\tthis->set_fullscreen(fullscreen);\n\t\t\tthis->init();\n\t\t}\n\n\t\t\/\/ interface\n\t\tvoid start()\n\t\t{\n\t\t\tif(m_running) return;\n\n\t\t\tthis->prepare_start();\n\t\t\twhile(m_running)\n\t\t\t{\n\t\t\t\tif(m_need_recreate) this->recreate();\n\n\t\t\t\tm_game_updater.start_pt();\n\n\t\t\t\t\/\/ update\n\t\t\t\tthis->update_events();\n\t\t\t\tm_input.update();\n\t\t\t\tm_game_updater.update();\n\n\t\t\t\t\/\/ render\n\t\t\t\tm_window.clear();\n\t\t\t\tm_game_updater.render();\n\t\t\t\tm_window.display();\n\n\t\t\t\tm_game_updater.end_pt();\n\t\t\t}\n\t\t}\n\n\t\tvoid stop() noexcept\n\t\t{\n\t\t\ton_stop();\n\t\t\tm_running = false;\n\t\t}\n\n\t\tauto& on_event(sf::Event::EventType type) { return m_on_event[type]; }\n\n\t\ttemplate \n\t\tvoid draw(Args&&... args)\n\t\t{\n\t\t\tm_window.draw(std::forward(args)...);\n\t\t}\n\n\t\tvoid toggle_fullscreen() noexcept\n\t\t{\n\t\t\tm_windowstyles ^= sf::Style::Fullscreen;\n\t\t\tm_need_recreate = true;\n\t\t}\n\n\t\tvoid toggle_titlebar() noexcept\n\t\t{\n\t\t\tm_windowstyles ^= sf::Style::Titlebar;\n\t\t\tm_need_recreate = true;\n\t\t}\n\n\t\t\/\/ setters\n\t\tvoid set_framereate_limit(mlk::uint limit) noexcept\n\t\t{\n\t\t\tm_window.setFramerateLimit(limit);\n\t\t}\n\n\t\tvoid set_size(const vec2u& size) noexcept { m_window.setSize(size); }\n\n\t\tvoid set_position(const vec2i& position) noexcept\n\t\t{\n\t\t\tm_window.setPosition(position);\n\t\t}\n\n\t\tvoid set_fullscreen(bool b) noexcept\n\t\t{\n\t\t\tif(b == (m_windowstyles & sf::Style::Fullscreen)) return;\n\t\t\tb ? m_windowstyles |= sf::Style::Fullscreen\n\t\t\t  : m_windowstyles &= ~sf::Style::Fullscreen;\n\t\t\tm_need_recreate = true;\n\t\t}\n\n\t\tvoid set_titlebar(bool b) noexcept\n\t\t{\n\t\t\tif(b == (m_windowstyles & sf::Style::Titlebar)) return;\n\t\t\tb ? m_windowstyles |= sf::Style::Titlebar\n\t\t\t  : m_windowstyles &= ~sf::Style::Titlebar;\n\t\t\tm_need_recreate = true;\n\t\t}\n\n\t\tvoid set_view(const sf::View& v) noexcept { m_window.setView(v); }\n\n\t\t\/\/ getters\n\t\tsf::RenderWindow& get_renderwindow() noexcept { return m_window; }\n\n\t\tgame_updater& get_updater() noexcept { return m_game_updater; }\n\n\t\tvec2u get_size() const noexcept { return m_window.getSize(); }\n\n\t\tvec2i get_position() const noexcept { return m_window.getPosition(); }\n\n\t\tbool get_fullscreen() const noexcept\n\t\t{\n\t\t\treturn m_windowstyles & sf::Style::Fullscreen;\n\t\t}\n\n\t\tbool get_titlebar() const noexcept\n\t\t{\n\t\t\treturn m_windowstyles & sf::Style::Titlebar;\n\t\t}\n\n\tprivate:\n\t\tvoid init()\n\t\t{\n\t\t\tm_input.init(this);\n\t\t\tm_windowstyles |= sf::Style::Default;\n\t\t\tthis->recreate();\n\t\t}\n\n\t\tvoid prepare_start() noexcept\n\t\t{\n\t\t\tm_running = true;\n\t\t\tmlk::lout(\"rj::game_window\", true) << \"starting gamewindow\";\n\t\t}\n\n\t\tvoid update_events() noexcept\n\t\t{\n\t\t\tsf::Event ev;\n\t\t\twhile(m_window.pollEvent(ev))\n\t\t\t{\n\t\t\t\tswitch(ev.type)\n\t\t\t\t{\n\t\t\t\t\tcase sf::Event::EventType::Closed:\n\t\t\t\t\t\tthis->stop();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase sf::Event::EventType::KeyPressed:\n\t\t\t\t\t\tm_input.key_pressed(ev.key.code);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase sf::Event::EventType::KeyReleased:\n\t\t\t\t\t\tm_input.key_released(ev.key.code);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase sf::Event::EventType::MouseButtonPressed:\n\t\t\t\t\t\tm_input.btn_pressed(ev.mouseButton.button);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase sf::Event::EventType::MouseButtonReleased:\n\t\t\t\t\t\tm_input.btn_released(ev.mouseButton.button);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase sf::Event::EventType::MouseWheelMoved:\n\t\t\t\t\t\tm_input.mousewheel_moved(ev.mouseWheel.delta);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t\/\/ call custom on_event\n\t\t\t\tm_on_event[ev.type](ev);\n\t\t\t}\n\t\t}\n\n\t\tvoid recreate()\n\t\t{\n\t\t\tm_window.close();\n\t\t\tm_window.create({m_width, m_height}, m_title, m_windowstyles);\n\t\t\tm_need_recreate = false;\n\t\t}\n\t};\n}\/\/ namespace rj\n\n#endif\/\/ RJ_CORE_GAME_WINDOW_HPP\n<|endoftext|>"}
{"text":"\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\nnamespace visionaray\n{\nnamespace simd\n{\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Functions to pack four materials into a single SIMD material\n\/\/\n\ninline matte pack(\n        matte const& m1,\n        matte const& m2,\n        matte const& m3,\n        matte const& m4\n        )\n{\n    matte result;\n\n    result.set_ca( pack(m1.get_ca(), m2.get_ca(), m3.get_ca(), m4.get_ca()) );\n    result.set_cd( pack(m1.get_cd(), m2.get_cd(), m3.get_cd(), m4.get_cd()) );\n    result.set_ka( float4(m1.get_ka(), m2.get_ka(), m3.get_ka(), m4.get_ka()) );\n    result.set_kd( float4(m1.get_kd(), m2.get_kd(), m3.get_kd(), m4.get_kd()) );\n\n    return result;\n}\n\ninline mirror pack(\n        mirror const& m1,\n        mirror const& m2,\n        mirror const& m3,\n        mirror const& m4\n        )\n{\n    mirror result;\n\n    result.set_cr( pack(m1.get_cr(), m2.get_cr(), m3.get_cr(), m4.get_cr()) );\n    result.set_kr( float4(m1.get_kr(), m2.get_kr(), m3.get_kr(), m4.get_kr()) );\n\n    return result;\n}\n\ninline plastic pack(\n        plastic const& m1,\n        plastic const& m2,\n        plastic const& m3,\n        plastic const& m4\n        )\n{\n    plastic result;\n\n    result.set_ca( pack(m1.get_ca(), m2.get_ca(), m3.get_ca(), m4.get_ca()) );\n    result.set_cd( pack(m1.get_cd(), m2.get_cd(), m3.get_cd(), m4.get_cd()) );\n    result.set_cs( pack(m1.get_cs(), m2.get_cs(), m3.get_cs(), m4.get_cs()) );\n    result.set_ka( float4(m1.get_ka(), m2.get_ka(), m3.get_ka(), m4.get_ka()) );\n    result.set_kd( float4(m1.get_kd(), m2.get_kd(), m3.get_kd(), m4.get_kd()) );\n    result.set_ks( float4(m1.get_ks(), m2.get_ks(), m3.get_ks(), m4.get_ks()) );\n    result.set_specular_exp( float4(\n            m1.get_specular_exp(),\n            m2.get_specular_exp(),\n            m3.get_specular_exp(),\n            m4.get_specular_exp()\n            ) );\n\n    return result;\n}\n\ninline emissive pack(\n        emissive const& m1,\n        emissive const& m2,\n        emissive const& m3,\n        emissive const& m4\n        )\n{\n    emissive result;\n\n    result.set_ce(\n            pack(m1.get_ce(),\n            m2.get_ce(),\n            m3.get_ce(),\n            m4.get_ce())\n            );\n\n    result.set_ls( float4(\n            m1.get_ls(),\n            m2.get_ls(),\n            m3.get_ls(),\n            m4.get_ls())\n            );\n\n    return result;\n}\n\n\n#if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Functions to pack eight materials into a single SIMD material\n\/\/\n\ninline emissive pack(\n        emissive const& m1,\n        emissive const& m2,\n        emissive const& m3,\n        emissive const& m4,\n        emissive const& m5,\n        emissive const& m6,\n        emissive const& m7,\n        emissive const& m8\n        )\n{\n    emissive result;\n\n    result.set_ce(pack(\n            m1.get_ce(), m2.get_ce(), m3.get_ce(), m4.get_ce(),\n            m5.get_ce(), m6.get_ce(), m7.get_ce(), m8.get_ce()\n            ));\n\n    result.set_ls(float8(\n            m1.get_ls(), m2.get_ls(), m3.get_ls(), m4.get_ls(),\n            m5.get_ls(), m6.get_ls(), m7.get_ls(), m8.get_ls()\n            ));\n\n    return result;\n}\n\ninline matte pack(\n        matte const& m1,\n        matte const& m2,\n        matte const& m3,\n        matte const& m4,\n        matte const& m5,\n        matte const& m6,\n        matte const& m7,\n        matte const& m8\n        )\n{\n    matte result;\n\n    result.set_ca(pack(\n            m1.get_ca(), m2.get_ca(), m3.get_ca(), m4.get_ca(),\n            m5.get_ca(), m6.get_ca(), m7.get_ca(), m8.get_ca()\n            ));\n    result.set_cd(pack(\n            m1.get_cd(), m2.get_cd(), m3.get_cd(), m4.get_cd(),\n            m5.get_cd(), m6.get_cd(), m7.get_cd(), m8.get_cd()\n            ));\n    result.set_ka(float8(\n            m1.get_ka(), m2.get_ka(), m3.get_ka(), m4.get_ka(),\n            m5.get_ka(), m6.get_ka(), m7.get_ka(), m8.get_ka()\n            ));\n    result.set_kd(float8(\n            m1.get_kd(), m2.get_kd(), m3.get_kd(), m4.get_kd(),\n            m5.get_kd(), m6.get_kd(), m7.get_kd(), m8.get_kd()\n            ));\n\n    return result;\n}\n\ninline mirror pack(\n        mirror const& m1,\n        mirror const& m2,\n        mirror const& m3,\n        mirror const& m4,\n        mirror const& m5,\n        mirror const& m6,\n        mirror const& m7,\n        mirror const& m8\n        )\n{\n    mirror result;\n\n    result.set_cr(pack(\n            m1.get_cr(), m2.get_cr(), m3.get_cr(), m4.get_cr(),\n            m5.get_cr(), m6.get_cr(), m7.get_cr(), m8.get_cr()\n            ));\n    result.set_kr(float8(\n            m1.get_kr(), m2.get_kr(), m3.get_kr(), m4.get_kr(),\n            m5.get_kr(), m6.get_kr(), m7.get_kr(), m8.get_kr()\n            ));\n\n    return result;\n}\n\ninline plastic pack(\n        plastic const& m1,\n        plastic const& m2,\n        plastic const& m3,\n        plastic const& m4,\n        plastic const& m5,\n        plastic const& m6,\n        plastic const& m7,\n        plastic const& m8\n        )\n{\n    using C = spectrum;\n\n    C ca[8]                         = { m1.get_ca(), m2.get_ca(), m3.get_ca(), m4.get_ca(),\n                                        m5.get_ca(), m6.get_ca(), m7.get_ca(), m8.get_ca() };\n    C cd[8]                         = { m1.get_cd(), m2.get_cd(), m3.get_cd(), m4.get_cd(),\n                                        m5.get_cd(), m6.get_cd(), m7.get_cd(), m8.get_cd() };\n    C cs[8]                         = { m1.get_cs(), m2.get_cs(), m3.get_cs(), m4.get_cs(),\n                                        m5.get_cs(), m6.get_cs(), m7.get_cs(), m8.get_cs() };\n    VSNRAY_ALIGN(32) float ka[8]    = { m1.get_ka(), m2.get_ka(), m3.get_ka(), m4.get_ka(),\n                                        m5.get_ka(), m6.get_ka(), m7.get_ka(), m8.get_ka() };\n    VSNRAY_ALIGN(32) float kd[8]    = { m1.get_kd(), m2.get_kd(), m3.get_kd(), m4.get_kd(),\n                                        m5.get_kd(), m6.get_kd(), m7.get_kd(), m8.get_kd() };\n    VSNRAY_ALIGN(32) float ks[8]    = { m1.get_ks(), m2.get_ks(), m3.get_ks(), m4.get_ks(),\n                                        m5.get_ks(), m6.get_ks(), m7.get_ks(), m8.get_ks() };\n    VSNRAY_ALIGN(32) float exp[8]   = { m1.get_specular_exp(), m2.get_specular_exp(), m3.get_specular_exp(), m4.get_specular_exp(),\n                                        m5.get_specular_exp(), m6.get_specular_exp(), m7.get_specular_exp(), m8.get_specular_exp() };\n\n    plastic result;\n\n    spectrum ca8;\n    spectrum cd8;\n    spectrum cs8;\n\n    for (size_t d = 0; d < C::num_samples; ++d)\n    {\n        ca8[d] = float8(\n                ca[0][d],\n                ca[1][d],\n                ca[2][d],\n                ca[3][d],\n                ca[4][d],\n                ca[5][d],\n                ca[6][d],\n                ca[7][d]\n                );\n\n        cd8[d] = float8(\n                cd[0][d],\n                cd[1][d],\n                cd[2][d],\n                cd[3][d],\n                cd[4][d],\n                cd[5][d],\n                cd[6][d],\n                cd[7][d]\n                );\n\n        cs8[d] = float8(\n                cs[0][d],\n                cs[1][d],\n                cs[2][d],\n                cs[3][d],\n                cs[4][d],\n                cs[5][d],\n                cs[6][d],\n                cs[7][d]\n                );\n    }\n\n    result.set_ca(ca8);\n    result.set_cd(cd8);\n    result.set_cs(cs8);\n    result.set_ka(ka);\n    result.set_kd(kd);\n    result.set_ks(ks);\n    result.set_specular_exp(exp);\n\n    return result;\n}\n\n\n#endif \/\/ VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX\n\n\n} \/\/ simd\n} \/\/ visioanray\nCode layout changes\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\nnamespace visionaray\n{\nnamespace simd\n{\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Functions to pack four materials into a single SIMD material\n\/\/\n\ninline emissive pack(\n        emissive const& m1,\n        emissive const& m2,\n        emissive const& m3,\n        emissive const& m4\n        )\n{\n    emissive result;\n\n    result.set_ce( pack(m1.get_ce(), m2.get_ce(), m3.get_ce(), m4.get_ce()) );\n    result.set_ls( float4(m1.get_ls(), m2.get_ls(), m3.get_ls(), m4.get_ls()) );\n\n    return result;\n}\n\n\ninline matte pack(\n        matte const& m1,\n        matte const& m2,\n        matte const& m3,\n        matte const& m4\n        )\n{\n    matte result;\n\n    result.set_ca( pack(m1.get_ca(), m2.get_ca(), m3.get_ca(), m4.get_ca()) );\n    result.set_cd( pack(m1.get_cd(), m2.get_cd(), m3.get_cd(), m4.get_cd()) );\n    result.set_ka( float4(m1.get_ka(), m2.get_ka(), m3.get_ka(), m4.get_ka()) );\n    result.set_kd( float4(m1.get_kd(), m2.get_kd(), m3.get_kd(), m4.get_kd()) );\n\n    return result;\n}\n\ninline mirror pack(\n        mirror const& m1,\n        mirror const& m2,\n        mirror const& m3,\n        mirror const& m4\n        )\n{\n    mirror result;\n\n    result.set_cr( pack(m1.get_cr(), m2.get_cr(), m3.get_cr(), m4.get_cr()) );\n    result.set_kr( float4(m1.get_kr(), m2.get_kr(), m3.get_kr(), m4.get_kr()) );\n\n    return result;\n}\n\ninline plastic pack(\n        plastic const& m1,\n        plastic const& m2,\n        plastic const& m3,\n        plastic const& m4\n        )\n{\n    plastic result;\n\n    result.set_ca( pack(m1.get_ca(), m2.get_ca(), m3.get_ca(), m4.get_ca()) );\n    result.set_cd( pack(m1.get_cd(), m2.get_cd(), m3.get_cd(), m4.get_cd()) );\n    result.set_cs( pack(m1.get_cs(), m2.get_cs(), m3.get_cs(), m4.get_cs()) );\n    result.set_ka( float4(m1.get_ka(), m2.get_ka(), m3.get_ka(), m4.get_ka()) );\n    result.set_kd( float4(m1.get_kd(), m2.get_kd(), m3.get_kd(), m4.get_kd()) );\n    result.set_ks( float4(m1.get_ks(), m2.get_ks(), m3.get_ks(), m4.get_ks()) );\n    result.set_specular_exp( float4(\n            m1.get_specular_exp(),\n            m2.get_specular_exp(),\n            m3.get_specular_exp(),\n            m4.get_specular_exp()\n            ) );\n\n    return result;\n}\n\n\n#if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Functions to pack eight materials into a single SIMD material\n\/\/\n\ninline emissive pack(\n        emissive const& m1,\n        emissive const& m2,\n        emissive const& m3,\n        emissive const& m4,\n        emissive const& m5,\n        emissive const& m6,\n        emissive const& m7,\n        emissive const& m8\n        )\n{\n    emissive result;\n\n    result.set_ce(pack(\n            m1.get_ce(), m2.get_ce(), m3.get_ce(), m4.get_ce(),\n            m5.get_ce(), m6.get_ce(), m7.get_ce(), m8.get_ce()\n            ));\n\n    result.set_ls(float8(\n            m1.get_ls(), m2.get_ls(), m3.get_ls(), m4.get_ls(),\n            m5.get_ls(), m6.get_ls(), m7.get_ls(), m8.get_ls()\n            ));\n\n    return result;\n}\n\ninline matte pack(\n        matte const& m1,\n        matte const& m2,\n        matte const& m3,\n        matte const& m4,\n        matte const& m5,\n        matte const& m6,\n        matte const& m7,\n        matte const& m8\n        )\n{\n    matte result;\n\n    result.set_ca(pack(\n            m1.get_ca(), m2.get_ca(), m3.get_ca(), m4.get_ca(),\n            m5.get_ca(), m6.get_ca(), m7.get_ca(), m8.get_ca()\n            ));\n    result.set_cd(pack(\n            m1.get_cd(), m2.get_cd(), m3.get_cd(), m4.get_cd(),\n            m5.get_cd(), m6.get_cd(), m7.get_cd(), m8.get_cd()\n            ));\n    result.set_ka(float8(\n            m1.get_ka(), m2.get_ka(), m3.get_ka(), m4.get_ka(),\n            m5.get_ka(), m6.get_ka(), m7.get_ka(), m8.get_ka()\n            ));\n    result.set_kd(float8(\n            m1.get_kd(), m2.get_kd(), m3.get_kd(), m4.get_kd(),\n            m5.get_kd(), m6.get_kd(), m7.get_kd(), m8.get_kd()\n            ));\n\n    return result;\n}\n\ninline mirror pack(\n        mirror const& m1,\n        mirror const& m2,\n        mirror const& m3,\n        mirror const& m4,\n        mirror const& m5,\n        mirror const& m6,\n        mirror const& m7,\n        mirror const& m8\n        )\n{\n    mirror result;\n\n    result.set_cr(pack(\n            m1.get_cr(), m2.get_cr(), m3.get_cr(), m4.get_cr(),\n            m5.get_cr(), m6.get_cr(), m7.get_cr(), m8.get_cr()\n            ));\n    result.set_kr(float8(\n            m1.get_kr(), m2.get_kr(), m3.get_kr(), m4.get_kr(),\n            m5.get_kr(), m6.get_kr(), m7.get_kr(), m8.get_kr()\n            ));\n\n    return result;\n}\n\ninline plastic pack(\n        plastic const& m1,\n        plastic const& m2,\n        plastic const& m3,\n        plastic const& m4,\n        plastic const& m5,\n        plastic const& m6,\n        plastic const& m7,\n        plastic const& m8\n        )\n{\n    using C = spectrum;\n\n    C ca[8]                         = { m1.get_ca(), m2.get_ca(), m3.get_ca(), m4.get_ca(),\n                                        m5.get_ca(), m6.get_ca(), m7.get_ca(), m8.get_ca() };\n    C cd[8]                         = { m1.get_cd(), m2.get_cd(), m3.get_cd(), m4.get_cd(),\n                                        m5.get_cd(), m6.get_cd(), m7.get_cd(), m8.get_cd() };\n    C cs[8]                         = { m1.get_cs(), m2.get_cs(), m3.get_cs(), m4.get_cs(),\n                                        m5.get_cs(), m6.get_cs(), m7.get_cs(), m8.get_cs() };\n    VSNRAY_ALIGN(32) float ka[8]    = { m1.get_ka(), m2.get_ka(), m3.get_ka(), m4.get_ka(),\n                                        m5.get_ka(), m6.get_ka(), m7.get_ka(), m8.get_ka() };\n    VSNRAY_ALIGN(32) float kd[8]    = { m1.get_kd(), m2.get_kd(), m3.get_kd(), m4.get_kd(),\n                                        m5.get_kd(), m6.get_kd(), m7.get_kd(), m8.get_kd() };\n    VSNRAY_ALIGN(32) float ks[8]    = { m1.get_ks(), m2.get_ks(), m3.get_ks(), m4.get_ks(),\n                                        m5.get_ks(), m6.get_ks(), m7.get_ks(), m8.get_ks() };\n    VSNRAY_ALIGN(32) float exp[8]   = { m1.get_specular_exp(), m2.get_specular_exp(), m3.get_specular_exp(), m4.get_specular_exp(),\n                                        m5.get_specular_exp(), m6.get_specular_exp(), m7.get_specular_exp(), m8.get_specular_exp() };\n\n    plastic result;\n\n    spectrum ca8;\n    spectrum cd8;\n    spectrum cs8;\n\n    for (size_t d = 0; d < C::num_samples; ++d)\n    {\n        ca8[d] = float8(\n                ca[0][d], ca[1][d], ca[2][d], ca[3][d],\n                ca[4][d], ca[5][d], ca[6][d], ca[7][d]\n                );\n\n        cd8[d] = float8(\n                cd[0][d], cd[1][d], cd[2][d], cd[3][d],\n                cd[4][d], cd[5][d], cd[6][d], cd[7][d]\n                );\n\n        cs8[d] = float8(\n                cs[0][d], cs[1][d], cs[2][d], cs[3][d],\n                cs[4][d], cs[5][d], cs[6][d], cs[7][d]\n                );\n    }\n\n    result.set_ca(ca8);\n    result.set_cd(cd8);\n    result.set_cs(cs8);\n    result.set_ka(ka);\n    result.set_kd(kd);\n    result.set_ks(ks);\n    result.set_specular_exp(exp);\n\n    return result;\n}\n\n\n#endif \/\/ VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX\n\n\n} \/\/ simd\n} \/\/ visioanray\n<|endoftext|>"}
{"text":"\/\/ Time:  O(2^n), n is the size of debt.\n\/\/ Space: O(2^n)\n\nclass Solution {\npublic:\n    int minTransfers(vector>& transactions) {\n        unordered_map account;\n        for (const auto& transaction: transactions) {\n            account[transaction[0]] += transaction[2];\n            account[transaction[1]] -= transaction[2];\n        }\n\n        vector debt;\n        for (const auto& kvp: account) {\n            if (kvp.second) {\n                debt.emplace_back(kvp.second);\n            }\n        }\n        if (debt.empty()) {\n            return 0;\n        }\n\n        const auto n = 1 << debt.size();\n        vector dp(n, numeric_limits::max()), subset;\n        for (int i = 1; i < n; ++i) {\n            int net_debt = 0, number = 0;\n            for (int j = 0; j < debt.size(); ++j) {\n                if (i & 1 << j) {\n                    net_debt += debt[j];\n                    ++number;\n                }\n            }\n            if (net_debt == 0) {\n                dp[i] = number - 1;\n                for (const auto& s: subset) {\n                    if ((i & s) == s) {\n                        if (dp[s] != numeric_limits::max() &&\n                            dp[i - s] != numeric_limits::max()) {\n                            dp[i] = min(dp[i], dp[s] + dp[i - s]);\n                        }\n                    }\n                }\n                subset.emplace_back(i);\n            }\n        }\n        return dp.back();\n    }\n};\nUpdate optimal-account-balancing.cpp\/\/ Time:  O(2^n), n is the size of debt.\n\/\/ Space: O(2^n)\n\nclass Solution {\npublic:\n    int minTransfers(vector>& transactions) {\n        unordered_map account;\n        for (const auto& transaction : transactions) {\n            account[transaction[0]] += transaction[2];\n            account[transaction[1]] -= transaction[2];\n        }\n\n        vector debt;\n        for (const auto& kvp : account) {\n            if (kvp.second) {\n                debt.emplace_back(kvp.second);\n            }\n        }\n        if (debt.empty()) {\n            return 0;\n        }\n\n        const auto n = 1 << debt.size();\n        vector dp(n, numeric_limits::max()), subset;\n        for (int i = 1; i < n; ++i) {\n            int net_debt = 0, number = 0;\n            for (int j = 0; j < debt.size(); ++j) {\n                if (i & 1 << j) {\n                    net_debt += debt[j];\n                    ++number;\n                }\n            }\n            if (net_debt == 0) {\n                dp[i] = number - 1;\n                for (const auto& s: subset) {\n                    if ((i & s) == s) {\n                        if (dp[s] != numeric_limits::max() &&\n                            dp[i - s] != numeric_limits::max()) {\n                            dp[i] = min(dp[i], dp[s] + dp[i - s]);\n                        }\n                    }\n                }\n                subset.emplace_back(i);\n            }\n        }\n        return dp.back();\n    }\n};\n<|endoftext|>"}
{"text":"#include \"stream_parser.h\"\n#include \"util.h\"\n\nstream_parser::stream_parser(const pcre *url_filter_re, const pcre_extra *url_filter_extra,\n                             const std::string &output_path) :\n        url_filter_re(url_filter_re),\n        url_filter_extra(url_filter_extra),\n        output_path(output_path),\n        gzip_flag(false),\n        dump_flag(-1) {\n    std::memset(&next_seq, 0, sizeof next_seq);\n    std::memset(&ts_usc, 0, sizeof ts_usc);\n    std::memset(&fin_nxtseq, 0, sizeof fin_nxtseq);\n    http_parser_init(&parser[HTTP_REQUEST], HTTP_REQUEST);\n    parser[HTTP_REQUEST].data = this;\n    http_parser_init(&parser[HTTP_RESPONSE], HTTP_RESPONSE);\n    parser[HTTP_RESPONSE].data = this;\n\n    http_parser_settings_init(&settings);\n    settings.on_url = on_url;\n    settings.on_message_begin = on_message_begin;\n    settings.on_header_field = on_header_field;\n    settings.on_header_value = on_header_value;\n    settings.on_headers_complete = on_headers_complete;\n    settings.on_body = on_body;\n    settings.on_message_complete = on_message_complete;\n}\n\nbool stream_parser::parse(const struct packet_info &packet, enum http_parser_type type) {\n    std::string *str = NULL;\n    size_t orig_size = raw[type].size();\n    str = &raw[type];\n    if (next_seq[type] != 0 && packet.seq != next_seq[type]) {\n        if (packet.seq < next_seq[type]) {\n            \/\/ retransmission packet\n            if (packet.is_rst || is_stream_fin(packet, type)) {\n                dump_http_request();\n                return false;\n            }\n            return true;\n        } else {\n            \/\/ out-of-order packet\n            out_of_order_packet[type].insert(\n                    std::make_pair(packet.seq, std::make_pair(packet.body, packet.nxtseq)));\n        }\n    } else {\n        str->append(packet.body);\n        next_seq[type] = packet.nxtseq;\n    }\n    while (!out_of_order_packet[type].empty()) {\n        const std::map >::iterator &iterator =\n                out_of_order_packet[type].find(next_seq[type]);\n        if (iterator == out_of_order_packet[type].end()) break;\n        str->append(iterator->second.first);\n        next_seq[type] = iterator->second.second;\n        out_of_order_packet[type].erase(iterator);\n    }\n\n    bool ret = true;\n    if (str->size() > orig_size) {\n        last_ts_usc = packet.ts_usc;\n        size_t parse_bytes = http_parser_execute(&parser[type], &settings, str->c_str() + orig_size,\n                                                 str->size() - orig_size);\n        ret = parse_bytes > 0 && HTTP_PARSER_ERRNO(&parser[type]) == HPE_OK;\n    }\n    if (packet.is_rst || is_stream_fin(packet, type)) {\n        dump_http_request();\n        return false;\n    }\n    return ret;\n}\n\nvoid stream_parser::set_addr(const std::string &req_addr, const std::string &resp_addr) {\n    this->address[HTTP_REQUEST].assign(req_addr);\n    this->address[HTTP_RESPONSE].assign(resp_addr);\n}\n\nint stream_parser::on_message_begin(http_parser *parser) {\n    stream_parser *self = reinterpret_cast(parser->data);\n    if (parser->type == HTTP_REQUEST) {\n        self->ts_usc[parser->type] = self->last_ts_usc;\n    }\n    self->dump_flag = 0;\n    return 0;\n}\n\nint stream_parser::on_url(http_parser *parser, const char *at, size_t length) {\n    stream_parser *self = reinterpret_cast(parser->data);\n    self->url.assign(at, length);\n    self->method.assign(http_method_str(static_cast(parser->method)));\n    if (!self->match_url(self->url)) {\n        return -1;\n    }\n    return 0;\n};\n\nint stream_parser::on_header_field(http_parser *parser, const char *at, size_t length) {\n    stream_parser *self = reinterpret_cast(parser->data);\n    self->temp_header_field.assign(at, length);\n    for (size_t i = 0; i < length; ++i) {\n        if (at[i] >= 'A' && at[i] <= 'Z') {\n            self->temp_header_field[i] = at[i] ^ (char) 0x20;\n        }\n    }\n    return 0;\n}\n\nint stream_parser::on_header_value(http_parser *parser, const char *at, size_t length) {\n    stream_parser *self = reinterpret_cast(parser->data);\n    if (parser->type == HTTP_RESPONSE) {\n        if (self->temp_header_field == \"content-encoding\" && std::strstr(at, \"gzip\")) {\n            self->gzip_flag = true;\n        }\n    } else {\n        if (self->temp_header_field == \"host\") {\n            self->host.assign(at, length);\n        }\n    }\n    \/\/ std::cout << self->temp_header_field <<  \":\" << std::string(at, length) << std::endl;\n    return 0;\n}\n\nint stream_parser::on_headers_complete(http_parser *parser) {\n    if (parser->type == HTTP_REQUEST || parser->type == HTTP_RESPONSE) {\n        stream_parser *self = reinterpret_cast(parser->data);\n        self->header[parser->type] = self->raw[parser->type].substr(0, parser->nread);\n        if (parser->type == HTTP_RESPONSE) {\n            self->ts_usc[parser->type] = self->last_ts_usc;\n        }\n    }\n    return 0;\n}\n\nint stream_parser::on_body(http_parser *parser, const char *at, size_t length) {\n    if (parser->type == HTTP_REQUEST || parser->type == HTTP_RESPONSE) {\n        stream_parser *self = reinterpret_cast(parser->data);\n        self->body[parser->type].append(at, length);\n        if (parser->type == HTTP_RESPONSE) {\n            self->ts_usc[parser->type] = self->last_ts_usc;\n        }\n    }\n    return 0;\n}\n\nint stream_parser::on_message_complete(http_parser *parser) {\n    stream_parser *self = reinterpret_cast(parser->data);\n    if (parser->type == HTTP_RESPONSE) {\n        if (parser->type == HTTP_RESPONSE && parser->status_code == HTTP_STATUS_CONTINUE) {\n            self->header_100_continue.assign(self->header[HTTP_RESPONSE]);\n            self->body_100_continue.assign(self->body[HTTP_RESPONSE]);\n            self->raw[HTTP_RESPONSE].clear();\n            self->body[HTTP_RESPONSE].clear();\n            \/\/ reset response parser\n            http_parser_init(parser, HTTP_RESPONSE);\n        } else {\n            self->ts_usc[parser->type] = self->last_ts_usc;\n            self->dump_http_request();\n        }\n    }\n    return 0;\n}\n\nbool stream_parser::match_url(const std::string &url) {\n    if (!url_filter_re) return true;\n    int ovector[30];\n    int rc = pcre_exec(url_filter_re, url_filter_extra, url.c_str(), url.size(), 0, 0, ovector, 30);\n    return rc >= 0;\n}\n\nvoid stream_parser::dump_http_request() {\n    if (dump_flag != 0) return;\n\n    if (gzip_flag && !body[HTTP_RESPONSE].empty()) {\n        std::string new_body;\n        if (gzip_decompress(body[HTTP_RESPONSE], new_body)) {\n            body[HTTP_RESPONSE].assign(new_body);\n        } else {\n            std::cerr << ANSI_COLOR_RED << \"[decompress error]\" << ANSI_COLOR_RESET << std::endl;\n        }\n    }\n\n    std::cout << ANSI_COLOR_CYAN << address[HTTP_REQUEST] << \" -> \" << address[HTTP_RESPONSE];\n    if (!host.empty()) {\n        std::cout << \" \" << ANSI_COLOR_GREEN << host << ANSI_COLOR_CYAN;\n    }\n    std::size_t i = url.find('?');\n    std::string url_no_query = i == std::string::npos ? url : url.substr(0, i);\n    std::cout << \" \" << url_no_query << ANSI_COLOR_RESET;\n\n    char buff[128];\n    if (ts_usc[HTTP_RESPONSE] && ts_usc[HTTP_REQUEST]) {\n        if (ts_usc[HTTP_REQUEST] % 1000000 == 0 && ts_usc[HTTP_RESPONSE] % 1000000 == 0) {\n            std::snprintf(buff, 128, \" cost %lu \", (ts_usc[HTTP_RESPONSE] - ts_usc[HTTP_REQUEST]) \/ 1000000);\n        } else {\n            std::snprintf(buff, 128, \" cost %.6f \", (ts_usc[HTTP_RESPONSE] - ts_usc[HTTP_REQUEST]) \/ 1000000.0);\n        }\n        std::cout << buff;\n    }\n\n    if (!output_path.empty()) {\n        static size_t req_idx = 0;\n        std::snprintf(buff, 128, \"\/%p.%lu\", this, ++req_idx);\n        std::string save_filename = output_path;\n        save_filename.append(buff);\n        std::cout << \" saved at \" << save_filename << std::endl;\n        std::ofstream out(save_filename.c_str(), std::ios::app | std::ios::out);\n        if (out.is_open()) {\n            out << *this << std::endl;\n            out.close();\n        } else {\n            std::cerr << \"ofstream [\" << save_filename << \"] is not opened.\" << std::endl;\n            out.close();\n            exit(1);\n        }\n    } else {\n        std::cout << std::endl << *this << std::endl;\n    }\n    \/\/ clear\n    raw[HTTP_REQUEST] = std::string();\n    raw[HTTP_RESPONSE] = std::string();\n    body[HTTP_REQUEST] = std::string();\n    body[HTTP_RESPONSE] = std::string();\n    header_100_continue.clear();\n    body_100_continue.clear();\n    host.clear();\n    std::memset(&ts_usc, 0, sizeof ts_usc);\n    dump_flag = 1;\n}\n\nbool stream_parser::is_stream_fin(const struct packet_info &packet, enum http_parser_type type) {\n    \/\/ three-way handshake\n    if (packet.is_fin) {\n        fin_nxtseq[type] = packet.nxtseq;\n        return false;\n    } else {\n        return fin_nxtseq[HTTP_REQUEST] && fin_nxtseq[HTTP_RESPONSE] && packet.ack == fin_nxtseq[!type];\n    }\n}\n\nstd::ostream &operator<<(std::ostream &out, const stream_parser &parser) {\n    out << ANSI_COLOR_GREEN\n        << parser.header[HTTP_REQUEST]\n        << ANSI_COLOR_RESET;\n    if (!parser.header_100_continue.empty()) {\n        out << ANSI_COLOR_BLUE\n            << parser.header_100_continue\n            << ANSI_COLOR_RESET;\n    }\n    if (!parser.body_100_continue.empty()) {\n        out << parser.body_100_continue;\n    }\n    if (!is_atty || is_plain_text(parser.body[HTTP_REQUEST])) {\n        out << parser.body[HTTP_REQUEST];\n    } else {\n        out << ANSI_COLOR_RED << \"[binary request body] (size:\" << parser.body[HTTP_REQUEST].size() << \")\"\n            << ANSI_COLOR_RESET;\n    }\n    out << std::endl\n        << ANSI_COLOR_BLUE\n        << parser.header[HTTP_RESPONSE]\n        << ANSI_COLOR_RESET;\n    if (parser.body[HTTP_RESPONSE].empty()) {\n        out << ANSI_COLOR_RED << \"[empty response body]\" << ANSI_COLOR_RESET;\n    } else if (!is_atty || is_plain_text(parser.body[HTTP_RESPONSE])) {\n        out << parser.body[HTTP_RESPONSE];\n    } else {\n        out << ANSI_COLOR_RED << \"[binary response body] (size:\" << parser.body[HTTP_RESPONSE].size() << \")\"\n            << ANSI_COLOR_RESET;\n    }\n    out << std::endl;\n    return out;\n}\n\nstd::ofstream &operator<<(std::ofstream &out, const stream_parser &parser) {\n    out << parser.header[HTTP_REQUEST]\n        << parser.header_100_continue\n        << parser.body_100_continue\n        << parser.body[HTTP_REQUEST]\n        << parser.header[HTTP_RESPONSE]\n        << parser.body[HTTP_RESPONSE];\n    return out;\n}\nReset gzip_flag#include \"stream_parser.h\"\n#include \"util.h\"\n\nstream_parser::stream_parser(const pcre *url_filter_re, const pcre_extra *url_filter_extra,\n                             const std::string &output_path) :\n        url_filter_re(url_filter_re),\n        url_filter_extra(url_filter_extra),\n        output_path(output_path),\n        gzip_flag(false),\n        dump_flag(-1) {\n    std::memset(&next_seq, 0, sizeof next_seq);\n    std::memset(&ts_usc, 0, sizeof ts_usc);\n    std::memset(&fin_nxtseq, 0, sizeof fin_nxtseq);\n    http_parser_init(&parser[HTTP_REQUEST], HTTP_REQUEST);\n    parser[HTTP_REQUEST].data = this;\n    http_parser_init(&parser[HTTP_RESPONSE], HTTP_RESPONSE);\n    parser[HTTP_RESPONSE].data = this;\n\n    http_parser_settings_init(&settings);\n    settings.on_url = on_url;\n    settings.on_message_begin = on_message_begin;\n    settings.on_header_field = on_header_field;\n    settings.on_header_value = on_header_value;\n    settings.on_headers_complete = on_headers_complete;\n    settings.on_body = on_body;\n    settings.on_message_complete = on_message_complete;\n}\n\nbool stream_parser::parse(const struct packet_info &packet, enum http_parser_type type) {\n    std::string *str = NULL;\n    size_t orig_size = raw[type].size();\n    str = &raw[type];\n    if (next_seq[type] != 0 && packet.seq != next_seq[type]) {\n        if (packet.seq < next_seq[type]) {\n            \/\/ retransmission packet\n            if (packet.is_rst || is_stream_fin(packet, type)) {\n                dump_http_request();\n                return false;\n            }\n            return true;\n        } else {\n            \/\/ out-of-order packet\n            out_of_order_packet[type].insert(\n                    std::make_pair(packet.seq, std::make_pair(packet.body, packet.nxtseq)));\n        }\n    } else {\n        str->append(packet.body);\n        next_seq[type] = packet.nxtseq;\n    }\n    while (!out_of_order_packet[type].empty()) {\n        const std::map >::iterator &iterator =\n                out_of_order_packet[type].find(next_seq[type]);\n        if (iterator == out_of_order_packet[type].end()) break;\n        str->append(iterator->second.first);\n        next_seq[type] = iterator->second.second;\n        out_of_order_packet[type].erase(iterator);\n    }\n\n    bool ret = true;\n    if (str->size() > orig_size) {\n        last_ts_usc = packet.ts_usc;\n        size_t parse_bytes = http_parser_execute(&parser[type], &settings, str->c_str() + orig_size,\n                                                 str->size() - orig_size);\n        ret = parse_bytes > 0 && HTTP_PARSER_ERRNO(&parser[type]) == HPE_OK;\n    }\n    if (packet.is_rst || is_stream_fin(packet, type)) {\n        dump_http_request();\n        return false;\n    }\n    return ret;\n}\n\nvoid stream_parser::set_addr(const std::string &req_addr, const std::string &resp_addr) {\n    this->address[HTTP_REQUEST].assign(req_addr);\n    this->address[HTTP_RESPONSE].assign(resp_addr);\n}\n\nint stream_parser::on_message_begin(http_parser *parser) {\n    stream_parser *self = reinterpret_cast(parser->data);\n    if (parser->type == HTTP_REQUEST) {\n        self->ts_usc[parser->type] = self->last_ts_usc;\n    }\n    self->dump_flag = 0;\n    return 0;\n}\n\nint stream_parser::on_url(http_parser *parser, const char *at, size_t length) {\n    stream_parser *self = reinterpret_cast(parser->data);\n    self->url.assign(at, length);\n    self->method.assign(http_method_str(static_cast(parser->method)));\n    if (!self->match_url(self->url)) {\n        return -1;\n    }\n    return 0;\n};\n\nint stream_parser::on_header_field(http_parser *parser, const char *at, size_t length) {\n    stream_parser *self = reinterpret_cast(parser->data);\n    self->temp_header_field.assign(at, length);\n    for (size_t i = 0; i < length; ++i) {\n        if (at[i] >= 'A' && at[i] <= 'Z') {\n            self->temp_header_field[i] = at[i] ^ (char) 0x20;\n        }\n    }\n    return 0;\n}\n\nint stream_parser::on_header_value(http_parser *parser, const char *at, size_t length) {\n    stream_parser *self = reinterpret_cast(parser->data);\n    if (parser->type == HTTP_RESPONSE) {\n        if (self->temp_header_field == \"content-encoding\" && std::strstr(at, \"gzip\")) {\n            self->gzip_flag = true;\n        }\n    } else {\n        if (self->temp_header_field == \"host\") {\n            self->host.assign(at, length);\n        }\n    }\n    \/\/ std::cout << self->temp_header_field <<  \":\" << std::string(at, length) << std::endl;\n    return 0;\n}\n\nint stream_parser::on_headers_complete(http_parser *parser) {\n    if (parser->type == HTTP_REQUEST || parser->type == HTTP_RESPONSE) {\n        stream_parser *self = reinterpret_cast(parser->data);\n        self->header[parser->type] = self->raw[parser->type].substr(0, parser->nread);\n        if (parser->type == HTTP_RESPONSE) {\n            self->ts_usc[parser->type] = self->last_ts_usc;\n        }\n    }\n    return 0;\n}\n\nint stream_parser::on_body(http_parser *parser, const char *at, size_t length) {\n    if (parser->type == HTTP_REQUEST || parser->type == HTTP_RESPONSE) {\n        stream_parser *self = reinterpret_cast(parser->data);\n        self->body[parser->type].append(at, length);\n        if (parser->type == HTTP_RESPONSE) {\n            self->ts_usc[parser->type] = self->last_ts_usc;\n        }\n    }\n    return 0;\n}\n\nint stream_parser::on_message_complete(http_parser *parser) {\n    stream_parser *self = reinterpret_cast(parser->data);\n    if (parser->type == HTTP_RESPONSE) {\n        if (parser->type == HTTP_RESPONSE && parser->status_code == HTTP_STATUS_CONTINUE) {\n            self->header_100_continue.assign(self->header[HTTP_RESPONSE]);\n            self->body_100_continue.assign(self->body[HTTP_RESPONSE]);\n            self->raw[HTTP_RESPONSE].clear();\n            self->body[HTTP_RESPONSE].clear();\n            \/\/ reset response parser\n            http_parser_init(parser, HTTP_RESPONSE);\n        } else {\n            self->ts_usc[parser->type] = self->last_ts_usc;\n            self->dump_http_request();\n        }\n    }\n    return 0;\n}\n\nbool stream_parser::match_url(const std::string &url) {\n    if (!url_filter_re) return true;\n    int ovector[30];\n    int rc = pcre_exec(url_filter_re, url_filter_extra, url.c_str(), url.size(), 0, 0, ovector, 30);\n    return rc >= 0;\n}\n\nvoid stream_parser::dump_http_request() {\n    if (dump_flag != 0) return;\n\n    if (gzip_flag && !body[HTTP_RESPONSE].empty()) {\n        std::string new_body;\n        if (gzip_decompress(body[HTTP_RESPONSE], new_body)) {\n            body[HTTP_RESPONSE].assign(new_body);\n        } else {\n            std::cerr << ANSI_COLOR_RED << \"[decompress error]\" << ANSI_COLOR_RESET << std::endl;\n        }\n    }\n\n    std::cout << ANSI_COLOR_CYAN << address[HTTP_REQUEST] << \" -> \" << address[HTTP_RESPONSE];\n    if (!host.empty()) {\n        std::cout << \" \" << ANSI_COLOR_GREEN << host << ANSI_COLOR_CYAN;\n    }\n    std::size_t i = url.find('?');\n    std::string url_no_query = i == std::string::npos ? url : url.substr(0, i);\n    std::cout << \" \" << url_no_query << ANSI_COLOR_RESET;\n\n    char buff[128];\n    if (ts_usc[HTTP_RESPONSE] && ts_usc[HTTP_REQUEST]) {\n        if (ts_usc[HTTP_REQUEST] % 1000000 == 0 && ts_usc[HTTP_RESPONSE] % 1000000 == 0) {\n            std::snprintf(buff, 128, \" cost %lu \", (ts_usc[HTTP_RESPONSE] - ts_usc[HTTP_REQUEST]) \/ 1000000);\n        } else {\n            std::snprintf(buff, 128, \" cost %.6f \", (ts_usc[HTTP_RESPONSE] - ts_usc[HTTP_REQUEST]) \/ 1000000.0);\n        }\n        std::cout << buff;\n    }\n\n    if (!output_path.empty()) {\n        static size_t req_idx = 0;\n        std::snprintf(buff, 128, \"\/%p.%lu\", this, ++req_idx);\n        std::string save_filename = output_path;\n        save_filename.append(buff);\n        std::cout << \" saved at \" << save_filename << std::endl;\n        std::ofstream out(save_filename.c_str(), std::ios::app | std::ios::out);\n        if (out.is_open()) {\n            out << *this << std::endl;\n            out.close();\n        } else {\n            std::cerr << \"ofstream [\" << save_filename << \"] is not opened.\" << std::endl;\n            out.close();\n            exit(1);\n        }\n    } else {\n        std::cout << std::endl << *this << std::endl;\n    }\n    \/\/ clear\n    raw[HTTP_REQUEST] = std::string();\n    raw[HTTP_RESPONSE] = std::string();\n    body[HTTP_REQUEST] = std::string();\n    body[HTTP_RESPONSE] = std::string();\n    header_100_continue.clear();\n    body_100_continue.clear();\n    host.clear();\n    std::memset(&ts_usc, 0, sizeof ts_usc);\n    gzip_flag = false;\n    dump_flag = 1;\n}\n\nbool stream_parser::is_stream_fin(const struct packet_info &packet, enum http_parser_type type) {\n    \/\/ three-way handshake\n    if (packet.is_fin) {\n        fin_nxtseq[type] = packet.nxtseq;\n        return false;\n    } else {\n        return fin_nxtseq[HTTP_REQUEST] && fin_nxtseq[HTTP_RESPONSE] && packet.ack == fin_nxtseq[!type];\n    }\n}\n\nstd::ostream &operator<<(std::ostream &out, const stream_parser &parser) {\n    out << ANSI_COLOR_GREEN\n        << parser.header[HTTP_REQUEST]\n        << ANSI_COLOR_RESET;\n    if (!parser.header_100_continue.empty()) {\n        out << ANSI_COLOR_BLUE\n            << parser.header_100_continue\n            << ANSI_COLOR_RESET;\n    }\n    if (!parser.body_100_continue.empty()) {\n        out << parser.body_100_continue;\n    }\n    if (!is_atty || is_plain_text(parser.body[HTTP_REQUEST])) {\n        out << parser.body[HTTP_REQUEST];\n    } else {\n        out << ANSI_COLOR_RED << \"[binary request body] (size:\" << parser.body[HTTP_REQUEST].size() << \")\"\n            << ANSI_COLOR_RESET;\n    }\n    out << std::endl\n        << ANSI_COLOR_BLUE\n        << parser.header[HTTP_RESPONSE]\n        << ANSI_COLOR_RESET;\n    if (parser.body[HTTP_RESPONSE].empty()) {\n        out << ANSI_COLOR_RED << \"[empty response body]\" << ANSI_COLOR_RESET;\n    } else if (!is_atty || is_plain_text(parser.body[HTTP_RESPONSE])) {\n        out << parser.body[HTTP_RESPONSE];\n    } else {\n        out << ANSI_COLOR_RED << \"[binary response body] (size:\" << parser.body[HTTP_RESPONSE].size() << \")\"\n            << ANSI_COLOR_RESET;\n    }\n    out << std::endl;\n    return out;\n}\n\nstd::ofstream &operator<<(std::ofstream &out, const stream_parser &parser) {\n    out << parser.header[HTTP_REQUEST]\n        << parser.header_100_continue\n        << parser.body_100_continue\n        << parser.body[HTTP_REQUEST]\n        << parser.header[HTTP_RESPONSE]\n        << parser.body[HTTP_RESPONSE];\n    return out;\n}\n<|endoftext|>"}
{"text":"#include \r\n\r\n#include \"factory.hpp\"\r\n\r\nfactory::interfaces::c_interface_manager g_factory;\r\n\r\nNAMESPACE_REGION( factory )\r\nNAMESPACE_REGION( interfaces )\r\n\r\nc_interface_manager::c_interface_manager( ) {\r\n\tauto teb = reinterpret_cast< PTEB >( __readfsdword( uintptr_t( &static_cast< NT_TIB* >( nullptr )->Self ) ) );\r\n\tauto peb = teb->ProcessEnvironmentBlock;\r\n\r\n\tauto root = &peb->Ldr->InMemoryOrderModuleList;\r\n\t\/\/iterate module list\r\n\tfor ( auto entry = root->Flink->Flink->Flink->Flink; entry != root; entry = entry->Flink ) {\r\n\t\tPLDR_DATA_TABLE_ENTRY\tdata_table;\r\n\t\tHMODULE\t\t\tmodule_base;\r\n\t\tuintptr_t\t\tcreate_interface_export;\r\n\t\tuintptr_t\t\tcreate_interface_;\r\n\t\tuintptr_t*\t\tlist_iterator_ptr;\r\n\t\tinterface_iterator_t*\tlist_iterator;\r\n\r\n\t\tdata_table = reinterpret_cast< PLDR_DATA_TABLE_ENTRY >( entry );\r\n\t\tmodule_base = reinterpret_cast< HMODULE >( data_table->Reserved2[ 0 ] );\r\n\t\tcreate_interface_export = uintptr_t( GetProcAddress( module_base, \"CreateInterface\" ) );\r\n\r\n\t\tif ( !create_interface_export || !is_createinterface_export( create_interface_export ) ) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\t\/\/find the createinterface function\r\n\t\tcreate_interface_ = follow_createinterface_export( create_interface_export );\r\n\t\tif ( !is_createinterface_fn( create_interface_ ) ) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\t\/\/find the list iterator\r\n\t\tlist_iterator_ptr = find_list_ptr( create_interface_ );\r\n\r\n\t\t\/\/iterate the interface list\r\n\t\tfor ( list_iterator = reinterpret_cast< interface_iterator_t* >(\r\n\t\t\tlist_iterator_ptr );\r\n\t\t\t!!list_iterator;\r\n\t\t\tlist_iterator = list_iterator->m_next\r\n\t\t\t) {\r\n\t\t\tstd::string name( list_iterator->m_name );\r\n\t\t\tstd::string module_name( util::unicode_to_ascii(\r\n\t\t\t\tstd::wstring( data_table->FullDllName.Buffer, data_table->FullDllName.Length ) ) );\r\n\r\n\t\t\tuintptr_t ptr = static_cast< uintptr_t( *)( ) >( list_iterator->m_create_fn )( );\r\n\r\n\t\t\tsize_t version = [ & ]( ) {\r\n\t\t\t\tstd::string ret( name );\r\n\t\t\t\tret.erase( std::remove_if( ret.begin( ), ret.end( ),\r\n\t\t\t\t\t[ & ]( int i ) { return !::isdigit( i ); }\r\n\t\t\t\t), ret.end( ) );\r\n\t\t\t\treturn atoi( ret.c_str( ) );\r\n\t\t\t}( );\r\n\r\n\t\t\tm_interfaces.push_back( interface_data_t{ name, module_name, version, ptr } );\r\n\t\t}\r\n\t}\r\n}\r\n\r\nEND_REGION\r\nEND_REGION\r\niterate exports instead of procaddress#include \r\n\r\n#include \"factory.hpp\"\r\n\r\nNAMESPACE_REGION( factory )\r\nNAMESPACE_REGION( interfaces )\r\n\r\n\/\/iterate all exports inside of a module and find createinterface\r\nuintptr_t c_interface_manager::find_createinterface( void* module_ ) {\r\n\tIMAGE_DOS_HEADER*\tdos_header;\r\n\tIMAGE_NT_HEADERS*\tnt_headers;\r\n\tuintptr_t\t\texport_address;\r\n\tIMAGE_EXPORT_DIRECTORY*\texport_dir;\r\n\tconst char*\t\texport_name;\r\n\tuintptr_t*\t\tnames;\r\n\tuintptr_t*\t\tfuncs;\r\n\tuint16_t*\t\tords;\r\n\r\n\tdos_header = reinterpret_cast< decltype( dos_header ) >( uintptr_t( module_ ) );\r\n\tnt_headers = reinterpret_cast< decltype( nt_headers ) >( uintptr_t( module_ ) + dos_header->e_lfanew );\r\n\t\r\n\texport_address = nt_headers->OptionalHeader.DataDirectory[ 0 ].VirtualAddress;\r\n\texport_dir = reinterpret_cast< decltype( export_dir ) >( uintptr_t( module_ ) + export_address );\r\n\r\n\tif ( !export_dir->NumberOfFunctions )\r\n\t\treturn uintptr_t{ };\r\n\r\n\tnames = reinterpret_cast< uintptr_t* >( uintptr_t( module_ ) + export_dir->AddressOfNames );\r\n\tfuncs = reinterpret_cast< uintptr_t* >( uintptr_t( module_ ) + export_dir->AddressOfFunctions );\r\n\r\n\tords = reinterpret_cast< uint16_t* >( uintptr_t( module_ ) + export_dir->AddressOfNameOrdinals );\r\n\r\n\tif ( names && funcs && ords ) {\r\n\t\tfor ( size_t i{ }; i < export_dir->NumberOfNames; ++i ) {\r\n\t\t\texport_name = reinterpret_cast< const char* >( uintptr_t( module_ ) + names[ i ] );\r\n\t\t\tif ( !strcmp( export_name, \"CreateInterface\" ) ) {\r\n\t\t\t\treturn uintptr_t( module_ ) + funcs[ ords[ i ] ];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn uintptr_t{ };\r\n}\r\n\r\nc_interface_manager::c_interface_manager( ) {\r\n\tauto teb = reinterpret_cast< PTEB >( __readfsdword( uintptr_t( &static_cast< NT_TIB* >( nullptr )->Self ) ) );\r\n\tauto peb = teb->ProcessEnvironmentBlock;\r\n\r\n\tauto root = &peb->Ldr->InMemoryOrderModuleList;\r\n\t\/\/iterate module list\r\n\tfor ( auto entry = root->Flink->Flink->Flink->Flink; entry != root; entry = entry->Flink ) {\r\n\t\tPLDR_DATA_TABLE_ENTRY\tdata_table;\r\n\t\tHMODULE\t\t\tmodule_base;\r\n\t\tuintptr_t\t\tcreate_interface_export;\r\n\t\tuintptr_t\t\tcreate_interface_;\r\n\t\tuintptr_t*\t\tlist_iterator_ptr;\r\n\t\tinterface_iterator_t*\tlist_iterator;\r\n\r\n\t\tdata_table = reinterpret_cast< PLDR_DATA_TABLE_ENTRY >( entry );\r\n\t\tmodule_base = reinterpret_cast< HMODULE >( data_table->Reserved2[ 0 ] );\r\n\t\tprintf( \"module: %s\\n\", util::unicode_to_ascii( \r\n\t\t\tstd::wstring( data_table->FullDllName.Buffer, data_table->FullDllName.Length ) ).c_str( ) );\r\n\t\tcreate_interface_export = find_createinterface( module_base );\r\n\r\n\t\tif ( !create_interface_export || !is_createinterface_export( create_interface_export ) ) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\t\/\/find the createinterface function\r\n\t\tcreate_interface_ = follow_createinterface_export( create_interface_export );\r\n\t\tif ( !is_createinterface_fn( create_interface_ ) ) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\t\/\/find the list iterator\r\n\t\tlist_iterator_ptr = find_list_ptr( create_interface_ );\r\n\r\n\t\t\/\/iterate the interface list\r\n\t\tfor ( list_iterator = reinterpret_cast< interface_iterator_t* >(\r\n\t\t\tlist_iterator_ptr );\r\n\t\t\t!!list_iterator;\r\n\t\t\tlist_iterator = list_iterator->m_next\r\n\t\t\t) {\r\n\t\t\tstd::string name( list_iterator->m_name );\r\n\t\t\tstd::string module_name( util::unicode_to_ascii(\r\n\t\t\t\tstd::wstring( data_table->FullDllName.Buffer, data_table->FullDllName.Length ) ) );\r\n\r\n\t\t\tuintptr_t ptr = static_cast< uintptr_t( *)( ) >( list_iterator->m_create_fn )( );\r\n\r\n\t\t\tsize_t version = [ & ]( ) {\r\n\t\t\t\tstd::string ret( name );\r\n\t\t\t\tret.erase( std::remove_if( ret.begin( ), ret.end( ),\r\n\t\t\t\t\t[ & ]( int i ) { return !::isdigit( i ); }\r\n\t\t\t\t), ret.end( ) );\r\n\t\t\t\treturn atoi( ret.c_str( ) );\r\n\t\t\t}( );\r\n\r\n\t\t\tm_interfaces.emplace_back( interface_data_t{ name, module_name, version, ptr } );\r\n\t\t}\r\n\t}\r\n}\r\n\r\nEND_REGION\r\nEND_REGION\r\n<|endoftext|>"}
{"text":"\/\/\n\/\/ This file is part of khmer, http:\/\/github.com\/ged-lab\/khmer\/, and is\n\/\/ Copyright (C) Michigan State University, 2009-2013. It is licensed under\n\/\/ the three-clause BSD license; see doc\/LICENSE.txt.\n\/\/ Contact: khmer-project@idyll.org\n\/\/\n\n#ifndef HASHBITS_HH\n#define HASHBITS_HH\n\n#include \n#include \"hashtable.hh\"\n\nnamespace khmer\n{\nclass CountingHash;\nclass LabelHash;\n\nclass Hashbits : public khmer::Hashtable\n{\nprotected:\n    std::vector _tablesizes;\n    size_t _n_tables;\n    HashIntoType _occupied_bins;\n    HashIntoType _n_unique_kmers;\n    HashIntoType _n_overlap_kmers;\n    Byte ** _counts;\n\n    virtual void _allocate_counters()\n    {\n        _n_tables = _tablesizes.size();\n\n        _counts = new Byte*[_n_tables];\n\n        for (size_t i = 0; i < _n_tables; i++) {\n            HashIntoType tablesize = _tablesizes[i];\n            HashIntoType tablebytes = tablesize \/ 8 + 1;\n\n            _counts[i] = new Byte[tablebytes];\n            memset(_counts[i], 0, tablebytes);\n        }\n    }\n\npublic:\n    Hashbits(WordLength ksize, std::vector& tablesizes)\n        : khmer::Hashtable(ksize),\n          _tablesizes(tablesizes)\n    {\n        _occupied_bins = 0;\n        _n_unique_kmers = 0;\n        _n_overlap_kmers = 0;\n\n        _allocate_counters();\n    }\n\n    ~Hashbits()\n    {\n        if (_counts) {\n            for (size_t i = 0; i < _n_tables; i++) {\n                delete[] _counts[i];\n                _counts[i] = NULL;\n            }\n            delete[] _counts;\n            _counts = NULL;\n\n            _n_tables = 0;\n        }\n\n    }\n\n    std::vector get_tablesizes() const\n    {\n        return _tablesizes;\n    }\n\n    virtual void save(std::string);\n    virtual void load(std::string);\n\n    \/\/ for overlap k-mer counting\n    void consume_fasta_overlap(const std::string &filename,\n                               HashIntoType curve[2][100],\n                               khmer::Hashbits &ht2,\n                               unsigned int &total_reads,\n                               unsigned long long &n_consumed);\n\n    \/\/ just for overlap k-mer counting!\n    unsigned int check_and_process_read_overlap(std::string &read,\n            bool &is_valid,\n            khmer::Hashbits &ht2);\n    \/\/ for overlap k-mer counting!\n    unsigned int consume_string_overlap(const std::string &s,\n                                        khmer::Hashbits &ht2);\n\n    \/\/ count number of occupied bins\n    virtual const HashIntoType n_occupied(HashIntoType start=0,\n                                          HashIntoType stop=0) const\n    {\n        \/\/ @@ CTB need to be able to *save* this...\n        return _occupied_bins\/_n_tables;\n    }\n\n    virtual const HashIntoType n_unique_kmers() const\n    {\n        return _n_unique_kmers;\t\/\/ @@ CTB need to be able to *save* this...\n    }\n\n    \/\/ Get and set the hashbits for the given kmer.\n    inline\n    virtual\n    BoundedCounterType\n    test_and_set_bits(const char * kmer)\n    {\n        HashIntoType hash = _hash(kmer, _ksize);\n        return test_and_set_bits(hash);\n    }\n\n    \/\/ Get and set the hashbits for the given kmer hash.\n    \/\/ Generally, it is better to keep tests and mutations separate,\n    \/\/ but, in the interests of efficiency and thread safety,\n    \/\/ tests and mutations are being blended here against conventional\n    \/\/ software engineering wisdom.\n    inline\n    virtual\n    BoundedCounterType\n    test_and_set_bits( HashIntoType khash )\n    {\n        bool is_new_kmer = false;\n\n        for (size_t i = 0; i < _n_tables; i++) {\n            HashIntoType bin = khash % _tablesizes[i];\n            HashIntoType byte = bin \/ 8;\n            unsigned char bit = (unsigned char)(1 << (bin % 8));\n\n            unsigned char bits_orig = __sync_fetch_and_or( *(_counts + i) + byte, bit );\n            if (!(bits_orig & bit)) {\n                __sync_add_and_fetch( &_occupied_bins, 1 );\n                is_new_kmer = true;\n            }\n        } \/\/ iteration over hashtables\n\n        if (is_new_kmer) {\n            __sync_add_and_fetch( &_n_unique_kmers, 1 );\n            return 1; \/\/ kmer not seen before\n        }\n\n        return 0; \/\/ kmer already seen\n    } \/\/ test_and_set_bits\n\n    virtual const HashIntoType n_overlap_kmers(HashIntoType start=0,\n            HashIntoType stop=0) const\n    {\n        return _n_overlap_kmers;\t\/\/ @@ CTB need to be able to *save* this...\n    }\n\n    virtual void count(const char * kmer)\n    {\n        HashIntoType hash = _hash(kmer, _ksize);\n        count(hash);\n    }\n\n    virtual void count(HashIntoType khash)\n    {\n        bool is_new_kmer = false;\n\n        for (size_t i = 0; i < _n_tables; i++) {\n            HashIntoType bin = khash % _tablesizes[i];\n            HashIntoType byte = bin \/ 8;\n            unsigned char bit = bin % 8;\n            if (!( _counts[i][byte] & (1<Add n_tables accessor to Hashbits\/\/\n\/\/ This file is part of khmer, http:\/\/github.com\/ged-lab\/khmer\/, and is\n\/\/ Copyright (C) Michigan State University, 2009-2013. It is licensed under\n\/\/ the three-clause BSD license; see doc\/LICENSE.txt.\n\/\/ Contact: khmer-project@idyll.org\n\/\/\n\n#ifndef HASHBITS_HH\n#define HASHBITS_HH\n\n#include \n#include \"hashtable.hh\"\n\nnamespace khmer\n{\nclass CountingHash;\nclass LabelHash;\n\nclass Hashbits : public khmer::Hashtable\n{\nprotected:\n    std::vector _tablesizes;\n    size_t _n_tables;\n    HashIntoType _occupied_bins;\n    HashIntoType _n_unique_kmers;\n    HashIntoType _n_overlap_kmers;\n    Byte ** _counts;\n\n    virtual void _allocate_counters()\n    {\n        _n_tables = _tablesizes.size();\n\n        _counts = new Byte*[_n_tables];\n\n        for (size_t i = 0; i < _n_tables; i++) {\n            HashIntoType tablesize = _tablesizes[i];\n            HashIntoType tablebytes = tablesize \/ 8 + 1;\n\n            _counts[i] = new Byte[tablebytes];\n            memset(_counts[i], 0, tablebytes);\n        }\n    }\n\npublic:\n    Hashbits(WordLength ksize, std::vector& tablesizes)\n        : khmer::Hashtable(ksize),\n          _tablesizes(tablesizes)\n    {\n        _occupied_bins = 0;\n        _n_unique_kmers = 0;\n        _n_overlap_kmers = 0;\n\n        _allocate_counters();\n    }\n\n    ~Hashbits()\n    {\n        if (_counts) {\n            for (size_t i = 0; i < _n_tables; i++) {\n                delete[] _counts[i];\n                _counts[i] = NULL;\n            }\n            delete[] _counts;\n            _counts = NULL;\n\n            _n_tables = 0;\n        }\n\n    }\n\n    \/\/ Accessors for protected\/private table info members\n    std::vector get_tablesizes() const\n    {\n        return _tablesizes;\n    }\n\n    const size_t n_tables() const\n    {\n        return _n_tables;\n    }\n\n    virtual void save(std::string);\n    virtual void load(std::string);\n\n    \/\/ for overlap k-mer counting\n    void consume_fasta_overlap(const std::string &filename,\n                               HashIntoType curve[2][100],\n                               khmer::Hashbits &ht2,\n                               unsigned int &total_reads,\n                               unsigned long long &n_consumed);\n\n    \/\/ just for overlap k-mer counting!\n    unsigned int check_and_process_read_overlap(std::string &read,\n            bool &is_valid,\n            khmer::Hashbits &ht2);\n    \/\/ for overlap k-mer counting!\n    unsigned int consume_string_overlap(const std::string &s,\n                                        khmer::Hashbits &ht2);\n\n    \/\/ count number of occupied bins\n    virtual const HashIntoType n_occupied(HashIntoType start=0,\n                                          HashIntoType stop=0) const\n    {\n        \/\/ @@ CTB need to be able to *save* this...\n        return _occupied_bins\/_n_tables;\n    }\n\n    virtual const HashIntoType n_unique_kmers() const\n    {\n        return _n_unique_kmers;\t\/\/ @@ CTB need to be able to *save* this...\n    }\n\n    \/\/ Get and set the hashbits for the given kmer.\n    inline\n    virtual\n    BoundedCounterType\n    test_and_set_bits(const char * kmer)\n    {\n        HashIntoType hash = _hash(kmer, _ksize);\n        return test_and_set_bits(hash);\n    }\n\n    \/\/ Get and set the hashbits for the given kmer hash.\n    \/\/ Generally, it is better to keep tests and mutations separate,\n    \/\/ but, in the interests of efficiency and thread safety,\n    \/\/ tests and mutations are being blended here against conventional\n    \/\/ software engineering wisdom.\n    inline\n    virtual\n    BoundedCounterType\n    test_and_set_bits( HashIntoType khash )\n    {\n        bool is_new_kmer = false;\n\n        for (size_t i = 0; i < _n_tables; i++) {\n            HashIntoType bin = khash % _tablesizes[i];\n            HashIntoType byte = bin \/ 8;\n            unsigned char bit = (unsigned char)(1 << (bin % 8));\n\n            unsigned char bits_orig = __sync_fetch_and_or( *(_counts + i) + byte, bit );\n            if (!(bits_orig & bit)) {\n                __sync_add_and_fetch( &_occupied_bins, 1 );\n                is_new_kmer = true;\n            }\n        } \/\/ iteration over hashtables\n\n        if (is_new_kmer) {\n            __sync_add_and_fetch( &_n_unique_kmers, 1 );\n            return 1; \/\/ kmer not seen before\n        }\n\n        return 0; \/\/ kmer already seen\n    } \/\/ test_and_set_bits\n\n    virtual const HashIntoType n_overlap_kmers(HashIntoType start=0,\n            HashIntoType stop=0) const\n    {\n        return _n_overlap_kmers;\t\/\/ @@ CTB need to be able to *save* this...\n    }\n\n    virtual void count(const char * kmer)\n    {\n        HashIntoType hash = _hash(kmer, _ksize);\n        count(hash);\n    }\n\n    virtual void count(HashIntoType khash)\n    {\n        bool is_new_kmer = false;\n\n        for (size_t i = 0; i < _n_tables; i++) {\n            HashIntoType bin = khash % _tablesizes[i];\n            HashIntoType byte = bin \/ 8;\n            unsigned char bit = bin % 8;\n            if (!( _counts[i][byte] & (1<"}
{"text":"\/\/\n\/\/  Drive.cpp\n\/\/  Clock Signal\n\/\/\n\/\/  Created by Thomas Harte on 25\/09\/2016.\n\/\/  Copyright 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"Drive.hpp\"\n\n#include \"Track\/UnformattedTrack.hpp\"\n\n#include \n#include \n#include \n\nusing namespace Storage::Disk;\n\nDrive::Drive(unsigned int input_clock_rate, int revolutions_per_minute, int number_of_heads):\n\tStorage::TimedEventLoop(input_clock_rate),\n\trotational_multiplier_(60, revolutions_per_minute),\n\tavailable_heads_(number_of_heads),\n\trandom_source_(static_cast(arc4random()) | (static_cast(arc4random()) << 32)) {\n\trotational_multiplier_.simplify();\n}\n\nDrive::~Drive() {\n\tif(disk_) disk_->flush_tracks();\n}\n\nvoid Drive::set_disk(const std::shared_ptr &disk) {\n\tif(disk_) disk_->flush_tracks();\n\tdisk_ = disk;\n\thas_disk_ = !!disk_;\n\n\tinvalidate_track();\n\tupdate_sleep_observer();\n}\n\nbool Drive::has_disk() {\n\treturn has_disk_;\n}\n\nbool Drive::is_sleeping() {\n\treturn !motor_is_on_ || !has_disk_;\n}\n\nbool Drive::get_is_track_zero() {\n\treturn head_position_ == HeadPosition(0);\n}\n\nvoid Drive::step(HeadPosition offset) {\n\tHeadPosition old_head_position = head_position_;\n\thead_position_ += offset;\n\tif(head_position_ < HeadPosition(0)) {\n\t\thead_position_ = HeadPosition(0);\n\t\tif(observer_) observer_->announce_drive_event(drive_name_, Activity::Observer::DriveEvent::StepBelowZero);\n\t} else {\n\t\tif(observer_) observer_->announce_drive_event(drive_name_, Activity::Observer::DriveEvent::StepNormal);\n\t}\n\n\t\/\/ If the head moved, flush the old track.\n\tif(head_position_ != old_head_position) {\n\t\ttrack_ = nullptr;\n\t}\n}\n\nvoid Drive::set_head(int head) {\n\thead = std::min(head, available_heads_ - 1);\n\tif(head != head_) {\n\t\thead_ = head;\n\t\ttrack_ = nullptr;\n\t}\n}\n\nStorage::Time Drive::get_time_into_track() {\n\t\/\/ `result` will initially be amount of time since the index hole was seen as a\n\t\/\/ proportion of a second; convert it into proportion of a rotation, simplify and return.\n\tTime result(cycles_since_index_hole_, static_cast(get_input_clock_rate()));\n\tresult \/= rotational_multiplier_;\n\tresult.simplify();\n\/\/\tassert(result <= Time(1));\n\treturn result;\n}\n\nbool Drive::get_is_read_only() {\n\tif(disk_) return disk_->get_is_read_only();\n\treturn true;\n}\n\nbool Drive::get_is_ready() {\n\treturn true;\n\treturn ready_index_count_ == 2;\n}\n\nvoid Drive::set_motor_on(bool motor_is_on) {\n\tmotor_is_on_ = motor_is_on;\n\n\tif(observer_) {\n\t\tobserver_->set_drive_motor_status(drive_name_, motor_is_on_);\n\t\tif(announce_motor_led_) {\n\t\t\tobserver_->set_led_status(drive_name_, motor_is_on_);\n\t\t}\n\t}\n\n\tif(!motor_is_on) {\n\t\tready_index_count_ = 0;\n\t\tif(disk_) disk_->flush_tracks();\n\t}\n\tupdate_sleep_observer();\n}\n\nbool Drive::get_motor_on() {\n\treturn motor_is_on_;\n}\n\nvoid Drive::set_event_delegate(Storage::Disk::Drive::EventDelegate *delegate) {\n\tevent_delegate_ = delegate;\n}\n\nvoid Drive::advance(const Cycles cycles) {\n\tcycles_since_index_hole_ += static_cast(cycles.as_int());\n\tif(event_delegate_) event_delegate_->advance(cycles);\n}\n\nvoid Drive::run_for(const Cycles cycles) {\n\tif(has_disk_ && motor_is_on_) {\n\t\tTime zero(0);\n\n\t\tint number_of_cycles = cycles.as_int();\n\t\twhile(number_of_cycles) {\n\t\t\tint cycles_until_next_event = static_cast(get_cycles_until_next_event());\n\t\t\tint cycles_to_run_for = std::min(cycles_until_next_event, number_of_cycles);\n\t\t\tif(!is_reading_ && cycles_until_bits_written_ > zero) {\n\t\t\t\tint write_cycles_target = cycles_until_bits_written_.get();\n\t\t\t\tif(cycles_until_bits_written_.length % cycles_until_bits_written_.clock_rate) write_cycles_target++;\n\t\t\t\tcycles_to_run_for = std::min(cycles_to_run_for, write_cycles_target);\n\t\t\t}\n\n\t\t\tnumber_of_cycles -= cycles_to_run_for;\n\t\t\tif(!is_reading_) {\n\t\t\t\tif(cycles_until_bits_written_ > zero) {\n\t\t\t\t\tStorage::Time cycles_to_run_for_time(cycles_to_run_for);\n\t\t\t\t\tif(cycles_until_bits_written_ <= cycles_to_run_for_time) {\n\t\t\t\t\t\tif(event_delegate_) event_delegate_->process_write_completed();\n\t\t\t\t\t\tif(cycles_until_bits_written_ <= cycles_to_run_for_time)\n\t\t\t\t\t\t\tcycles_until_bits_written_.set_zero();\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tcycles_until_bits_written_ -= cycles_to_run_for_time;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcycles_until_bits_written_ -= cycles_to_run_for_time;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tTimedEventLoop::run_for(Cycles(cycles_to_run_for));\n\t\t}\n\t}\n}\n\n\/\/ MARK: - Track timed event loop\n\nvoid Drive::get_next_event(const Time &duration_already_passed) {\n\t\/\/ Grab a new track if not already in possession of one. This will recursively call get_next_event,\n\t\/\/ supplying a proper duration_already_passed.\n\tif(!track_) {\n\t\trandom_interval_.set_zero();\n\t\tsetup_track();\n\t\treturn;\n\t}\n\n\t\/\/ If gain has now been turned up so as to generate noise, generate some noise.\n\tif(random_interval_ > Time(0)) {\n\t\tcurrent_event_.type = Track::Event::IndexHole;\n\t\tcurrent_event_.length.length = 2 + (random_source_&1);\n\t\tcurrent_event_.length.clock_rate = 1000000;\n\t\trandom_source_ = (random_source_ >> 1) | (random_source_ << 63);\n\n\t\tif(random_interval_ < current_event_.length) {\n\t\t\tcurrent_event_.length = random_interval_;\n\t\t\trandom_interval_.set_zero();\n\t\t} else {\n\t\t\trandom_interval_ -= current_event_.length;\n\t\t}\n\t\tset_next_event_time_interval(current_event_.length);\n\t\treturn;\n\t}\n\n\tif(track_) {\n\t\tcurrent_event_ = track_->get_next_event();\n\t} else {\n\t\tcurrent_event_.length.length = 1;\n\t\tcurrent_event_.length.clock_rate = 1;\n\t\tcurrent_event_.type = Track::Event::IndexHole;\n\t}\n\n\t\/\/ divide interval, which is in terms of a single rotation of the disk, by rotation speed to\n\t\/\/ convert it into revolutions per second; this is achieved by multiplying by rotational_multiplier_\n\tassert(current_event_.length <= Time(1) && current_event_.length >= Time(0));\n\tassert(current_event_.length > duration_already_passed);\n\tTime interval = (current_event_.length - duration_already_passed) * rotational_multiplier_;\n\n\t\/\/ An interval greater than 15ms => adjust gain up the point where noise starts happening.\n\t\/\/ Seed that up and leave a 15ms gap until it starts.\n\tconst Time safe_gain_period(15, 1000000);\n\tif(interval >= safe_gain_period) {\n\t\trandom_interval_ = interval - safe_gain_period;\n\t\tinterval = safe_gain_period;\n\t}\n\n\tset_next_event_time_interval(interval);\n}\n\nvoid Drive::process_next_event() {\n\tif(current_event_.type == Track::Event::IndexHole) {\n\/\/\t\tassert(get_time_into_track() == Time(1) || get_time_into_track() == Time(0));\n\t\tif(ready_index_count_ < 2) ready_index_count_++;\n\t\tcycles_since_index_hole_ = 0;\n\t}\n\tif(\n\t\tevent_delegate_ &&\n\t\t(current_event_.type == Track::Event::IndexHole || is_reading_)\n\t){\n\t\tevent_delegate_->process_event(current_event_);\n\t}\n\tget_next_event(Time(0));\n}\n\n\/\/ MARK: - Track management\n\nstd::shared_ptr Drive::get_track() {\n\tif(disk_) return disk_->get_track_at_position(Track::Address(head_, head_position_));\n\treturn nullptr;\n}\n\nvoid Drive::set_track(const std::shared_ptr &track) {\n\tif(disk_) disk_->set_track_at_position(Track::Address(head_, head_position_), track);\n}\n\nvoid Drive::setup_track() {\n\ttrack_ = get_track();\n\tif(!track_) {\n\t\ttrack_.reset(new UnformattedTrack);\n\t}\n\n\tTime offset;\n\tTime track_time_now = get_time_into_track();\n\tassert(track_time_now >= Time(0) && current_event_.length <= Time(1));\n\n\tTime time_found = track_->seek_to(track_time_now);\n\n\t\/\/ time_found can be greater than track_time_now if limited precision caused rounding\n\tif(time_found <= track_time_now) {\n\t\toffset = track_time_now - time_found;\n\t} else {\n\t\toffset.set_zero();\n\t}\n\n\tget_next_event(offset);\n}\n\nvoid Drive::invalidate_track() {\n\ttrack_ = nullptr;\n\tif(patched_track_) {\n\t\tset_track(patched_track_);\n\t\tpatched_track_ = nullptr;\n\t}\n}\n\n\/\/ MARK: - Writing\n\nvoid Drive::begin_writing(Time bit_length, bool clamp_to_index_hole) {\n\tis_reading_ = false;\n\tclamp_writing_to_index_hole_ = clamp_to_index_hole;\n\n\tcycles_per_bit_ = Storage::Time(get_input_clock_rate()) * bit_length;\n\tcycles_per_bit_.simplify();\n\n\twrite_segment_.length_of_a_bit = bit_length \/ rotational_multiplier_;\n\twrite_segment_.data.clear();\n\twrite_segment_.number_of_bits = 0;\n\n\twrite_start_time_ = get_time_into_track();\n}\n\nvoid Drive::write_bit(bool value) {\n\tbool needs_new_byte = !(write_segment_.number_of_bits&7);\n\tif(needs_new_byte) write_segment_.data.push_back(0);\n\tif(value) write_segment_.data[write_segment_.number_of_bits >> 3] |= 0x80 >> (write_segment_.number_of_bits & 7);\n\twrite_segment_.number_of_bits++;\n\n\tcycles_until_bits_written_ += cycles_per_bit_;\n}\n\nvoid Drive::end_writing() {\n\tif(!is_reading_) {\n\t\tis_reading_ = true;\n\n\t\tif(!patched_track_) {\n\t\t\t\/\/ Avoid creating a new patched track if this one is already patched\n\t\t\tpatched_track_ = std::dynamic_pointer_cast(track_);\n\t\t\tif(!patched_track_) {\n\t\t\t\tpatched_track_.reset(new PCMPatchedTrack(track_));\n\t\t\t}\n\t\t}\n\t\tpatched_track_->add_segment(write_start_time_, write_segment_, clamp_writing_to_index_hole_);\n\t\tcycles_since_index_hole_ %= get_input_clock_rate();\n\t\tinvalidate_track();\n\t}\n}\n\nvoid Drive::set_activity_observer(Activity::Observer *observer, const std::string &name, bool add_motor_led) {\n\tobserver_ = observer;\n\tannounce_motor_led_ = add_motor_led;\n\tif(observer) {\n\t\tdrive_name_ = name;\n\n\t\tobserver->register_drive(drive_name_);\n\t\tobserver->set_drive_motor_status(drive_name_, motor_is_on_);\n\n\t\tif(add_motor_led) {\n\t\t\tobserver->register_led(drive_name_);\n\t\t\tobserver->set_led_status(drive_name_, motor_is_on_);\n\t\t}\n\t}\n}\nEliminates `arc4random`.\/\/\n\/\/  Drive.cpp\n\/\/  Clock Signal\n\/\/\n\/\/  Created by Thomas Harte on 25\/09\/2016.\n\/\/  Copyright 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"Drive.hpp\"\n\n#include \"Track\/UnformattedTrack.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace Storage::Disk;\n\nDrive::Drive(unsigned int input_clock_rate, int revolutions_per_minute, int number_of_heads):\n\tStorage::TimedEventLoop(input_clock_rate),\n\trotational_multiplier_(60, revolutions_per_minute),\n\tavailable_heads_(number_of_heads){\n\trotational_multiplier_.simplify();\n\n\tconst auto seed = static_cast(std::chrono::system_clock::now().time_since_epoch().count());\n\tstd::default_random_engine randomiser(seed);\n\n\t\/\/ Get at least 64 bits of random information; rounding is likey to give this a slight bias.\n\trandom_source_ = 0;\n\tauto half_range = (randomiser.max() - randomiser.min()) \/ 2;\n\tfor(int bit = 0; bit < 64; ++bit) {\n\t\trandom_source_ <<= 1;\n\t\trandom_source_ |= ((randomiser() - randomiser.min()) >= half_range) ? 1 : 0;\n\t}\n}\n\nDrive::~Drive() {\n\tif(disk_) disk_->flush_tracks();\n}\n\nvoid Drive::set_disk(const std::shared_ptr &disk) {\n\tif(disk_) disk_->flush_tracks();\n\tdisk_ = disk;\n\thas_disk_ = !!disk_;\n\n\tinvalidate_track();\n\tupdate_sleep_observer();\n}\n\nbool Drive::has_disk() {\n\treturn has_disk_;\n}\n\nbool Drive::is_sleeping() {\n\treturn !motor_is_on_ || !has_disk_;\n}\n\nbool Drive::get_is_track_zero() {\n\treturn head_position_ == HeadPosition(0);\n}\n\nvoid Drive::step(HeadPosition offset) {\n\tHeadPosition old_head_position = head_position_;\n\thead_position_ += offset;\n\tif(head_position_ < HeadPosition(0)) {\n\t\thead_position_ = HeadPosition(0);\n\t\tif(observer_) observer_->announce_drive_event(drive_name_, Activity::Observer::DriveEvent::StepBelowZero);\n\t} else {\n\t\tif(observer_) observer_->announce_drive_event(drive_name_, Activity::Observer::DriveEvent::StepNormal);\n\t}\n\n\t\/\/ If the head moved, flush the old track.\n\tif(head_position_ != old_head_position) {\n\t\ttrack_ = nullptr;\n\t}\n}\n\nvoid Drive::set_head(int head) {\n\thead = std::min(head, available_heads_ - 1);\n\tif(head != head_) {\n\t\thead_ = head;\n\t\ttrack_ = nullptr;\n\t}\n}\n\nStorage::Time Drive::get_time_into_track() {\n\t\/\/ `result` will initially be amount of time since the index hole was seen as a\n\t\/\/ proportion of a second; convert it into proportion of a rotation, simplify and return.\n\tTime result(cycles_since_index_hole_, static_cast(get_input_clock_rate()));\n\tresult \/= rotational_multiplier_;\n\tresult.simplify();\n\/\/\tassert(result <= Time(1));\n\treturn result;\n}\n\nbool Drive::get_is_read_only() {\n\tif(disk_) return disk_->get_is_read_only();\n\treturn true;\n}\n\nbool Drive::get_is_ready() {\n\treturn true;\n\treturn ready_index_count_ == 2;\n}\n\nvoid Drive::set_motor_on(bool motor_is_on) {\n\tmotor_is_on_ = motor_is_on;\n\n\tif(observer_) {\n\t\tobserver_->set_drive_motor_status(drive_name_, motor_is_on_);\n\t\tif(announce_motor_led_) {\n\t\t\tobserver_->set_led_status(drive_name_, motor_is_on_);\n\t\t}\n\t}\n\n\tif(!motor_is_on) {\n\t\tready_index_count_ = 0;\n\t\tif(disk_) disk_->flush_tracks();\n\t}\n\tupdate_sleep_observer();\n}\n\nbool Drive::get_motor_on() {\n\treturn motor_is_on_;\n}\n\nvoid Drive::set_event_delegate(Storage::Disk::Drive::EventDelegate *delegate) {\n\tevent_delegate_ = delegate;\n}\n\nvoid Drive::advance(const Cycles cycles) {\n\tcycles_since_index_hole_ += static_cast(cycles.as_int());\n\tif(event_delegate_) event_delegate_->advance(cycles);\n}\n\nvoid Drive::run_for(const Cycles cycles) {\n\tif(has_disk_ && motor_is_on_) {\n\t\tTime zero(0);\n\n\t\tint number_of_cycles = cycles.as_int();\n\t\twhile(number_of_cycles) {\n\t\t\tint cycles_until_next_event = static_cast(get_cycles_until_next_event());\n\t\t\tint cycles_to_run_for = std::min(cycles_until_next_event, number_of_cycles);\n\t\t\tif(!is_reading_ && cycles_until_bits_written_ > zero) {\n\t\t\t\tint write_cycles_target = cycles_until_bits_written_.get();\n\t\t\t\tif(cycles_until_bits_written_.length % cycles_until_bits_written_.clock_rate) write_cycles_target++;\n\t\t\t\tcycles_to_run_for = std::min(cycles_to_run_for, write_cycles_target);\n\t\t\t}\n\n\t\t\tnumber_of_cycles -= cycles_to_run_for;\n\t\t\tif(!is_reading_) {\n\t\t\t\tif(cycles_until_bits_written_ > zero) {\n\t\t\t\t\tStorage::Time cycles_to_run_for_time(cycles_to_run_for);\n\t\t\t\t\tif(cycles_until_bits_written_ <= cycles_to_run_for_time) {\n\t\t\t\t\t\tif(event_delegate_) event_delegate_->process_write_completed();\n\t\t\t\t\t\tif(cycles_until_bits_written_ <= cycles_to_run_for_time)\n\t\t\t\t\t\t\tcycles_until_bits_written_.set_zero();\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tcycles_until_bits_written_ -= cycles_to_run_for_time;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcycles_until_bits_written_ -= cycles_to_run_for_time;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tTimedEventLoop::run_for(Cycles(cycles_to_run_for));\n\t\t}\n\t}\n}\n\n\/\/ MARK: - Track timed event loop\n\nvoid Drive::get_next_event(const Time &duration_already_passed) {\n\t\/\/ Grab a new track if not already in possession of one. This will recursively call get_next_event,\n\t\/\/ supplying a proper duration_already_passed.\n\tif(!track_) {\n\t\trandom_interval_.set_zero();\n\t\tsetup_track();\n\t\treturn;\n\t}\n\n\t\/\/ If gain has now been turned up so as to generate noise, generate some noise.\n\tif(random_interval_ > Time(0)) {\n\t\tcurrent_event_.type = Track::Event::IndexHole;\n\t\tcurrent_event_.length.length = 2 + (random_source_&1);\n\t\tcurrent_event_.length.clock_rate = 1000000;\n\t\trandom_source_ = (random_source_ >> 1) | (random_source_ << 63);\n\n\t\tif(random_interval_ < current_event_.length) {\n\t\t\tcurrent_event_.length = random_interval_;\n\t\t\trandom_interval_.set_zero();\n\t\t} else {\n\t\t\trandom_interval_ -= current_event_.length;\n\t\t}\n\t\tset_next_event_time_interval(current_event_.length);\n\t\treturn;\n\t}\n\n\tif(track_) {\n\t\tcurrent_event_ = track_->get_next_event();\n\t} else {\n\t\tcurrent_event_.length.length = 1;\n\t\tcurrent_event_.length.clock_rate = 1;\n\t\tcurrent_event_.type = Track::Event::IndexHole;\n\t}\n\n\t\/\/ divide interval, which is in terms of a single rotation of the disk, by rotation speed to\n\t\/\/ convert it into revolutions per second; this is achieved by multiplying by rotational_multiplier_\n\tassert(current_event_.length <= Time(1) && current_event_.length >= Time(0));\n\tassert(current_event_.length > duration_already_passed);\n\tTime interval = (current_event_.length - duration_already_passed) * rotational_multiplier_;\n\n\t\/\/ An interval greater than 15ms => adjust gain up the point where noise starts happening.\n\t\/\/ Seed that up and leave a 15ms gap until it starts.\n\tconst Time safe_gain_period(15, 1000000);\n\tif(interval >= safe_gain_period) {\n\t\trandom_interval_ = interval - safe_gain_period;\n\t\tinterval = safe_gain_period;\n\t}\n\n\tset_next_event_time_interval(interval);\n}\n\nvoid Drive::process_next_event() {\n\tif(current_event_.type == Track::Event::IndexHole) {\n\/\/\t\tassert(get_time_into_track() == Time(1) || get_time_into_track() == Time(0));\n\t\tif(ready_index_count_ < 2) ready_index_count_++;\n\t\tcycles_since_index_hole_ = 0;\n\t}\n\tif(\n\t\tevent_delegate_ &&\n\t\t(current_event_.type == Track::Event::IndexHole || is_reading_)\n\t){\n\t\tevent_delegate_->process_event(current_event_);\n\t}\n\tget_next_event(Time(0));\n}\n\n\/\/ MARK: - Track management\n\nstd::shared_ptr Drive::get_track() {\n\tif(disk_) return disk_->get_track_at_position(Track::Address(head_, head_position_));\n\treturn nullptr;\n}\n\nvoid Drive::set_track(const std::shared_ptr &track) {\n\tif(disk_) disk_->set_track_at_position(Track::Address(head_, head_position_), track);\n}\n\nvoid Drive::setup_track() {\n\ttrack_ = get_track();\n\tif(!track_) {\n\t\ttrack_.reset(new UnformattedTrack);\n\t}\n\n\tTime offset;\n\tTime track_time_now = get_time_into_track();\n\tassert(track_time_now >= Time(0) && current_event_.length <= Time(1));\n\n\tTime time_found = track_->seek_to(track_time_now);\n\n\t\/\/ time_found can be greater than track_time_now if limited precision caused rounding\n\tif(time_found <= track_time_now) {\n\t\toffset = track_time_now - time_found;\n\t} else {\n\t\toffset.set_zero();\n\t}\n\n\tget_next_event(offset);\n}\n\nvoid Drive::invalidate_track() {\n\ttrack_ = nullptr;\n\tif(patched_track_) {\n\t\tset_track(patched_track_);\n\t\tpatched_track_ = nullptr;\n\t}\n}\n\n\/\/ MARK: - Writing\n\nvoid Drive::begin_writing(Time bit_length, bool clamp_to_index_hole) {\n\tis_reading_ = false;\n\tclamp_writing_to_index_hole_ = clamp_to_index_hole;\n\n\tcycles_per_bit_ = Storage::Time(get_input_clock_rate()) * bit_length;\n\tcycles_per_bit_.simplify();\n\n\twrite_segment_.length_of_a_bit = bit_length \/ rotational_multiplier_;\n\twrite_segment_.data.clear();\n\twrite_segment_.number_of_bits = 0;\n\n\twrite_start_time_ = get_time_into_track();\n}\n\nvoid Drive::write_bit(bool value) {\n\tbool needs_new_byte = !(write_segment_.number_of_bits&7);\n\tif(needs_new_byte) write_segment_.data.push_back(0);\n\tif(value) write_segment_.data[write_segment_.number_of_bits >> 3] |= 0x80 >> (write_segment_.number_of_bits & 7);\n\twrite_segment_.number_of_bits++;\n\n\tcycles_until_bits_written_ += cycles_per_bit_;\n}\n\nvoid Drive::end_writing() {\n\tif(!is_reading_) {\n\t\tis_reading_ = true;\n\n\t\tif(!patched_track_) {\n\t\t\t\/\/ Avoid creating a new patched track if this one is already patched\n\t\t\tpatched_track_ = std::dynamic_pointer_cast(track_);\n\t\t\tif(!patched_track_) {\n\t\t\t\tpatched_track_.reset(new PCMPatchedTrack(track_));\n\t\t\t}\n\t\t}\n\t\tpatched_track_->add_segment(write_start_time_, write_segment_, clamp_writing_to_index_hole_);\n\t\tcycles_since_index_hole_ %= get_input_clock_rate();\n\t\tinvalidate_track();\n\t}\n}\n\nvoid Drive::set_activity_observer(Activity::Observer *observer, const std::string &name, bool add_motor_led) {\n\tobserver_ = observer;\n\tannounce_motor_led_ = add_motor_led;\n\tif(observer) {\n\t\tdrive_name_ = name;\n\n\t\tobserver->register_drive(drive_name_);\n\t\tobserver->set_drive_motor_status(drive_name_, motor_is_on_);\n\n\t\tif(add_motor_led) {\n\t\t\tobserver->register_led(drive_name_);\n\t\t\tobserver->set_led_status(drive_name_, motor_is_on_);\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"\/\/\n\/\/  Drive.hpp\n\/\/  Clock Signal\n\/\/\n\/\/  Created by Thomas Harte on 25\/09\/2016.\n\/\/  Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef Drive_hpp\n#define Drive_hpp\n\n#include \n\n#include \"Disk.hpp\"\n#include \"..\/..\/ClockReceiver\/Sleeper.hpp\"\n#include \"..\/TimedEventLoop.hpp\"\n\nnamespace Storage {\nnamespace Disk {\n\nclass Drive: public Sleeper, public TimedEventLoop {\n\tpublic:\n\t\tDrive(unsigned int input_clock_rate, int revolutions_per_minute);\n\n\t\t\/*!\n\t\t\tReplaces whatever is in the drive with @c disk.\n\t\t*\/\n\t\tvoid set_disk(const std::shared_ptr &disk);\n\n\t\t\/*!\n\t\t\tReplaces whatever is in the drive with a disk that contains endless copies of @c track.\n\t\t*\/\n\t\tvoid set_disk_with_track(const std::shared_ptr &track);\n\n\t\t\/*!\n\t\t\t@returns @c true if a disk is currently inserted; @c false otherwise.\n\t\t*\/\n\t\tbool has_disk();\n\n\t\t\/*!\n\t\t\t@returns @c true if the drive head is currently at track zero; @c false otherwise.\n\t\t*\/\n\t\tbool get_is_track_zero();\n\n\t\t\/*!\n\t\t\tSteps the disk head the specified number of tracks. Positive numbers step inwards (i.e. away from track 0),\n\t\t\tnegative numbers step outwards (i.e. towards track 0).\n\t\t*\/\n\t\tvoid step(int direction);\n\n\t\t\/*!\n\t\t\tSets the current read head.\n\t\t*\/\n\t\tvoid set_head(unsigned int head);\n\n\t\t\/*!\n\t\t\t@returns @c true if the inserted disk is read-only or no disk is inserted; @c false otherwise.\n\t\t*\/\n\t\tbool get_is_read_only();\n\n\t\t\/*!\n\t\t\t@returns the track underneath the current head at the location now stepped to.\n\t\t*\/\n\t\tstd::shared_ptr get_track();\n\n\t\t\/*!\n\t\t\tAttempts to set @c track as the track underneath the current head at the location now stepped to.\n\t\t*\/\n\t\tvoid set_track(const std::shared_ptr &track);\n\n\t\t\/*!\n\t\t\t@returns @c true if the drive is ready; @c false otherwise.\n\t\t*\/\n\t\tbool get_is_ready();\n\n\t\t\/*!\n\t\t\tSets whether the disk motor is on.\n\t\t*\/\n\t\tvoid set_motor_on(bool);\n\n\t\t\/*!\n\t\t\tAdvances the drive by @c number_of_cycles cycles.\n\t\t*\/\n\t\tvoid run_for(const Cycles cycles);\n\n\t\t\/*!\n\t\t\tProvides a mechanism to receive track events as they occur.\n\t\t*\/\n\t\tstruct EventDelegate {\n\t\t\tvirtual void process_event(const Track::Event &event) = 0;\n\t\t};\n\n\t\t\/\/\/ Sets the current event delegate.\n\t\tvoid set_event_delegate(EventDelegate *);\n\n\t\t\/\/ As per Sleeper.\n\t\tbool is_sleeping();\n\n\tprivate:\n\t\tstd::shared_ptr track_;\n\t\tstd::shared_ptr disk_;\n\t\tint cycles_since_index_hole_ = 0;\n\t\tTime rotational_multiplier_;\n\n\t\tbool has_disk_ = false;\n\n\t\tint head_position_ = 0;\n\t\tunsigned int head_ = 0;\n\n\t\tvoid process_next_event();\n\t\tvoid get_next_event(const Time &duration_already_passed);\n\t\tTrack::Event current_event_;\n\t\tbool motor_is_on_ = false;\n\n\t\tTime get_time_into_track();\n\t\tEventDelegate *event_delegate_ = nullptr;\n};\n\n\n}\n}\n\n#endif \/* Drive_hpp *\/\nIntroduces necessary storage and interface for writing.\/\/\n\/\/  Drive.hpp\n\/\/  Clock Signal\n\/\/\n\/\/  Created by Thomas Harte on 25\/09\/2016.\n\/\/  Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef Drive_hpp\n#define Drive_hpp\n\n#include \"Disk.hpp\"\n#include \"PCMSegment.hpp\"\n#include \"PCMPatchedTrack.hpp\"\n\n#include \"..\/TimedEventLoop.hpp\"\n#include \"..\/..\/ClockReceiver\/Sleeper.hpp\"\n\n#include \n\nnamespace Storage {\nnamespace Disk {\n\nclass Drive: public Sleeper, public TimedEventLoop {\n\tpublic:\n\t\tDrive(unsigned int input_clock_rate, int revolutions_per_minute);\n\n\t\t\/*!\n\t\t\tReplaces whatever is in the drive with @c disk.\n\t\t*\/\n\t\tvoid set_disk(const std::shared_ptr &disk);\n\n\t\t\/*!\n\t\t\tReplaces whatever is in the drive with a disk that contains endless copies of @c track.\n\t\t*\/\n\t\tvoid set_disk_with_track(const std::shared_ptr &track);\n\n\t\t\/*!\n\t\t\t@returns @c true if a disk is currently inserted; @c false otherwise.\n\t\t*\/\n\t\tbool has_disk();\n\n\t\t\/*!\n\t\t\t@returns @c true if the drive head is currently at track zero; @c false otherwise.\n\t\t*\/\n\t\tbool get_is_track_zero();\n\n\t\t\/*!\n\t\t\tSteps the disk head the specified number of tracks. Positive numbers step inwards (i.e. away from track 0),\n\t\t\tnegative numbers step outwards (i.e. towards track 0).\n\t\t*\/\n\t\tvoid step(int direction);\n\n\t\t\/*!\n\t\t\tSets the current read head.\n\t\t*\/\n\t\tvoid set_head(unsigned int head);\n\n\t\t\/*!\n\t\t\t@returns @c true if the inserted disk is read-only or no disk is inserted; @c false otherwise.\n\t\t*\/\n\t\tbool get_is_read_only();\n\n\t\t\/*!\n\t\t\t@returns the track underneath the current head at the location now stepped to.\n\t\t*\/\n\t\tstd::shared_ptr get_track();\n\n\t\t\/*!\n\t\t\tAttempts to set @c track as the track underneath the current head at the location now stepped to.\n\t\t*\/\n\t\tvoid set_track(const std::shared_ptr &track);\n\n\t\t\/*!\n\t\t\t@returns @c true if the drive is ready; @c false otherwise.\n\t\t*\/\n\t\tbool get_is_ready();\n\n\t\t\/*!\n\t\t\tSets whether the disk motor is on.\n\t\t*\/\n\t\tvoid set_motor_on(bool);\n\n\t\t\/*!\n\t\t\t@returns @c true if the motor is on; @c false otherwise.\n\t\t*\/\n\t\tbool get_motor_on();\n\n\t\t\/*!\n\t\t\tBegins write mode, initiating a PCM sampled region of data. Bits should be written via\n\t\t\t@c write_bit. They will be written with the length set via @c set_expected_bit_length.\n\t\t\tIt is acceptable to supply a backlog of bits. Flux transition events will not be reported\n\t\t\twhile writing.\n\n\t\t\t@param clamp_to_index_hole If @c true then writing will automatically be truncated by\n\t\t\tthe index hole. Writing will continue over the index hole otherwise.\n\t\t*\/\n\t\tvoid begin_writing(bool clamp_to_index_hole);\n\n\t\t\/*!\n\t\t\tWrites the bit @c value as the next in the PCM stream initiated by @c begin_writing.\n\t\t*\/\n\t\tvoid write_bit(bool value);\n\n\t\t\/*!\n\t\t\tEnds write mode, switching back to read mode. The drive will stop overwriting events.\n\t\t*\/\n\t\tvoid end_writing();\n\n\t\t\/*!\n\t\t\tAdvances the drive by @c number_of_cycles cycles.\n\t\t*\/\n\t\tvoid run_for(const Cycles cycles);\n\n\t\t\/*!\n\t\t\tProvides a mechanism to receive track events as they occur, including the synthetic\n\t\t\tevent of \"you told me to output the following data, and I've done that now\".\n\t\t*\/\n\t\tstruct EventDelegate {\n\t\t\t\/\/\/ Informs the delegate that @c event has been reached.\n\t\t\tvirtual void process_event(const Track::Event &event) = 0;\n\n\t\t\t\/*!\n\t\t\t\tIf the drive is in write mode, announces that all queued bits have now been written.\n\t\t\t\tIf the controller provides further bits now then there will be no gap in written data.\n\t\t\t*\/\n\t\t\tvirtual void process_write_completed() {}\n\t\t};\n\n\t\t\/\/\/ Sets the current event delegate.\n\t\tvoid set_event_delegate(EventDelegate *);\n\n\t\t\/\/ As per Sleeper.\n\t\tbool is_sleeping();\n\n\tprivate:\n\t\t\/\/ Drives [usually] contain an entire disk; from that a certain track\n\t\t\/\/ will be currently under the head.\n\t\tstd::shared_ptr disk_;\n\t\tstd::shared_ptr track_;\n\t\tbool has_disk_ = false;\n\n\t\t\/\/ Contains the multiplier that converts between track-relative lengths\n\t\t\/\/ to real-time lengths — so it's the reciprocal of rotation speed.\n\t\tTime rotational_multiplier_;\n\n\t\t\/\/ A count of time since the index hole was last seen. Which is used to\n\t\t\/\/ determine how far the drive is into a full rotation when switching to\n\t\t\/\/ a new track.\n\t\tint cycles_since_index_hole_ = 0;\n\n\t\t\/\/ A record of head position and active head.\n\t\tint head_position_ = 0;\n\t\tunsigned int head_ = 0;\n\n\t\t\/\/ Motor control state.\n\t\tbool motor_is_on_ = false;\n\n\t\t\/\/ If the drive is not currently reading then it is writing. While writing\n\t\t\/\/ it can optionally be told to clamp to the index hole.\n\t\tbool is_reading_;\n\t\tbool clamp_writing_to_index_hole_;\n\n\t\t\/\/ If writing is occurring then the drive will be accumulating a write segment,\n\t\t\/\/ for addition to a patched track.\n\t\tstd::shared_ptr patched_track_;\n\t\tPCMSegment write_segment_;\n\t\tTime write_start_time_;\n\n\t\t\/\/ Maintains appropriate counting to know when to indicate that writing\n\t\t\/\/ is complete.\n\t\tTime cycles_until_bits_written_;\n\t\tTime cycles_per_bit_;\n\n\t\t\/\/ TimedEventLoop call-ins and state.\n\t\tvoid process_next_event();\n\t\tvoid get_next_event(const Time &duration_already_passed);\n\t\tTrack::Event current_event_;\n\n\t\t\/\/ Helper for track changes.\n\t\tTime get_time_into_track();\n\n\t\t\/\/ The target (if any) for track events.\n\t\tEventDelegate *event_delegate_ = nullptr;\n};\n\n\n}\n}\n\n#endif \/* Drive_hpp *\/\n<|endoftext|>"}
{"text":"#include \"generator\/regions\/admin_suburbs_marker.hpp\"\n\n#include \"generator\/regions\/region.hpp\"\n\nnamespace generator\n{\nnamespace regions\n{\nvoid AdminSuburbsMarker::MarkSuburbs(Node::Ptr & tree)\n{\n  auto const & region = tree->GetData();\n  if (region.GetLevel() == PlaceLevel::Locality)\n  {\n    MarkLocality(tree);\n    return;\n  }\n\n  for (auto & subtree : tree->GetChildren())\n    MarkSuburbs(subtree);\n}\n\nvoid AdminSuburbsMarker::MarkLocality(Node::Ptr & tree)\n{\n  ASSERT_EQUAL(tree->GetData().GetLevel(), PlaceLevel::Locality, ());\n  for (auto & subtree : tree->GetChildren())\n    MarkSuburbsInLocality(subtree);\n}\n\nvoid AdminSuburbsMarker::MarkSuburbsInLocality(Node::Ptr & tree)\n{\n  auto & region = tree->GetData();\n  if (region.GetLevel() == PlaceLevel::Locality)\n  {\n    MarkLocality(tree);\n    return;\n  }\n\n  if (region.GetAdminLevel() != AdminLevel::Unknown)\n    region.SetLevel(PlaceLevel::Suburb);\n\n  for (auto & subtree : tree->GetChildren())\n    MarkUnderLocalityAsSublocalities(subtree);\n}\n\nvoid AdminSuburbsMarker::MarkUnderLocalityAsSublocalities(Node::Ptr & tree)\n{\n  auto & region = tree->GetData();\n  auto const level = region.GetLevel();\n  if (level == PlaceLevel::Locality)\n  {\n    MarkLocality(tree);\n    return;\n  }\n\n  if (level == PlaceLevel::Suburb)\n    region.SetLevel(PlaceLevel::Sublocality);\n  else if (level == PlaceLevel::Unknown && region.GetAdminLevel() != AdminLevel::Unknown)\n    region.SetLevel(PlaceLevel::Sublocality);\n\n  for (auto & subtree : tree->GetChildren())\n    MarkUnderLocalityAsSublocalities(subtree);\n}\n}  \/\/ namespace regions\n}  \/\/ namespace generator\n[generator:regions] Fix debug compile#include \"generator\/regions\/admin_suburbs_marker.hpp\"\n\n#include \"generator\/regions\/region.hpp\"\n\nnamespace generator\n{\nnamespace regions\n{\nvoid AdminSuburbsMarker::MarkSuburbs(Node::Ptr & tree)\n{\n  auto const & region = tree->GetData();\n  if (region.GetLevel() == PlaceLevel::Locality)\n  {\n    MarkLocality(tree);\n    return;\n  }\n\n  for (auto & subtree : tree->GetChildren())\n    MarkSuburbs(subtree);\n}\n\nvoid AdminSuburbsMarker::MarkLocality(Node::Ptr & tree)\n{\n  ASSERT(tree->GetData().GetLevel() == PlaceLevel::Locality, ());\n  for (auto & subtree : tree->GetChildren())\n    MarkSuburbsInLocality(subtree);\n}\n\nvoid AdminSuburbsMarker::MarkSuburbsInLocality(Node::Ptr & tree)\n{\n  auto & region = tree->GetData();\n  if (region.GetLevel() == PlaceLevel::Locality)\n  {\n    MarkLocality(tree);\n    return;\n  }\n\n  if (region.GetAdminLevel() != AdminLevel::Unknown)\n    region.SetLevel(PlaceLevel::Suburb);\n\n  for (auto & subtree : tree->GetChildren())\n    MarkUnderLocalityAsSublocalities(subtree);\n}\n\nvoid AdminSuburbsMarker::MarkUnderLocalityAsSublocalities(Node::Ptr & tree)\n{\n  auto & region = tree->GetData();\n  auto const level = region.GetLevel();\n  if (level == PlaceLevel::Locality)\n  {\n    MarkLocality(tree);\n    return;\n  }\n\n  if (level == PlaceLevel::Suburb)\n    region.SetLevel(PlaceLevel::Sublocality);\n  else if (level == PlaceLevel::Unknown && region.GetAdminLevel() != AdminLevel::Unknown)\n    region.SetLevel(PlaceLevel::Sublocality);\n\n  for (auto & subtree : tree->GetChildren())\n    MarkUnderLocalityAsSublocalities(subtree);\n}\n}  \/\/ namespace regions\n}  \/\/ namespace generator\n<|endoftext|>"}
{"text":"\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: expfld.hxx,v $\n *\n *  $Revision: 1.10 $\n *\n *  last change: $Author: hr $ $Date: 2007-09-27 08:01:15 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _EXPFLD_HXX\n#define _EXPFLD_HXX\n\n#ifndef _SVARRAY_HXX \/\/autogen\n#include \n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n#ifndef _FLDBAS_HXX\n#include \n#endif\n#ifndef _CELLFML_HXX\n#include \n#endif\n\nclass SfxPoolItem;\nclass SwTxtNode;\nclass SwFrm;\nstruct SwPosition;\nclass SwTxtFld;\nclass SwDoc;\nclass SwFmtFld;\nclass _SetGetExpFlds;\nclass SwEditShell;\n\n\/\/ Vorwaertsdeklaration: besorge den \"Body-TextNode\", fuer Exp.Fld in Fly's\n\/\/                      Header\/Footers\/Footnodes\nconst SwTxtNode* GetBodyTxtNode( const SwDoc& pDoc, SwPosition& rPos,\n                                 const SwFrm& rFrm );\n\/\/ Wandlung Address -> Adressen\nvoid ReplacePoint(String& sTmpName, BOOL bWithCommandType = FALSE);\n\nstruct _SeqFldLstElem\n{\n    String sDlgEntry;\n    USHORT nSeqNo;\n\n    _SeqFldLstElem( const String& rStr, USHORT nNo )\n        : sDlgEntry( rStr ), nSeqNo( nNo )\n    {}\n};\nSV_DECL_PTRARR_DEL( _SwSeqFldList, _SeqFldLstElem*, 10, 10 )\n\nclass SW_DLLPUBLIC SwSeqFldList : public _SwSeqFldList\n{\npublic:\n    SwSeqFldList()  : _SwSeqFldList( 10, 10 ) {}\n\n    BOOL InsertSort( _SeqFldLstElem* );\n    BOOL SeekEntry( const _SeqFldLstElem& , USHORT* pPos = 0 );\n};\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Ausdruck\n --------------------------------------------------------------------*\/\n\nclass SwGetExpFieldType : public SwValueFieldType\n{\npublic:\n        SwGetExpFieldType(SwDoc* pDoc);\n        virtual SwFieldType*    Copy() const;\n\n        \/\/ ueberlagert, weil das Get-Field nicht veraendert werden kann\n        \/\/ und dann auch nicht aktualisiert werden muss. Aktualisierung\n        \/\/ erfolgt beim Aendern von Set-Werten !\n\n        virtual void Modify( SfxPoolItem *pOld, SfxPoolItem *pNew );\n};\n\n\/*--------------------------------------------------------------------\n    Beschreibung: GetExperession\n --------------------------------------------------------------------*\/\n\nclass SwGetExpField : public SwFormulaField\n{\n    String          sExpand;\n    BOOL            bIsInBodyTxt;\n    USHORT          nSubType;\n\npublic:\n    SwGetExpField( SwGetExpFieldType*, const String& rFormel,\n                   USHORT nSubType = nsSwGetSetExpType::GSE_EXPR, ULONG nFmt = 0);\n\n    virtual void                SetValue( const double& rVal );\n    virtual void                SetLanguage(USHORT nLng);\n\n    virtual String              Expand() const;\n    virtual SwField*            Copy() const;\n\n    inline const String&        GetExpStr() const;\n    inline void                 ChgExpStr(const String& rExpand);\n\n    \/\/ wird von der Formatierung abgefragt\n    inline BOOL                 IsInBodyTxt() const;\n    \/\/ wird von UpdateExpFlds gesetzt (dort ist die Node-Position bekannt)\n    inline void                 ChgBodyTxtFlag( BOOL bIsInBody );\n    \/\/ fuer Felder in Header\/Footer\/Footnotes\/Flys:\n    \/\/ (wird nur von der Formatierung aufgerufen!!)\n    void                        ChangeExpansion( const SwFrm&, const SwTxtFld& );\n\n    virtual String              GetCntnt(BOOL bName = FALSE) const;\n\n    \/\/ Die Formel aendern\n    virtual String              GetPar2() const;\n    virtual void                SetPar2(const String& rStr);\n\n    virtual USHORT              GetSubType() const;\n    virtual void                SetSubType(USHORT nType);\n    virtual BOOL        QueryValue( com::sun::star::uno::Any& rVal, USHORT nWhich ) const;\n    virtual BOOL        PutValue( const com::sun::star::uno::Any& rVal, USHORT nWhich );\n\n    static USHORT       GetReferenceTextPos( const SwFmtFld& rFmt, SwDoc& rDoc);\n};\n\ninline void SwGetExpField::ChgExpStr(const String& rExpand)\n    { sExpand = rExpand;}\n\ninline const String& SwGetExpField::GetExpStr() const\n    { return sExpand;   }\n\n\/\/ wird von der Formatierung abgefragt\ninline BOOL SwGetExpField::IsInBodyTxt() const\n    { return bIsInBodyTxt; }\n\n\/\/ wird von UpdateExpFlds gesetzt (dort ist die Node-Position bekannt)\ninline void SwGetExpField::ChgBodyTxtFlag( BOOL bIsInBody )\n    { bIsInBodyTxt = bIsInBody; }\n\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Ausdruck setzen\n --------------------------------------------------------------------*\/\n\nclass SwSetExpField;\n\nclass SW_DLLPUBLIC SwSetExpFieldType : public SwValueFieldType\n{\n    String      sName;\n    const SwNode* pOutlChgNd;\n\/\/  sal_Unicode cDelim;\n    String      sDelim;\n    USHORT      nType;\n    BYTE        nLevel;\n    BOOL        bDeleted;\n\npublic:\n    SwSetExpFieldType( SwDoc* pDoc, const String& rName,\n                        USHORT nType = nsSwGetSetExpType::GSE_EXPR );\n    virtual SwFieldType*    Copy() const;\n    virtual const String&   GetName() const;\n\n    inline void             SetType(USHORT nTyp);\n    inline USHORT           GetType() const;\n\n    void                    SetSeqFormat(ULONG nFormat);\n    ULONG                   GetSeqFormat();\n\n    BOOL                    IsDeleted() const       { return bDeleted; }\n    void                    SetDeleted( BOOL b )    { bDeleted = b; }\n\n    \/\/ ueberlagert, weil das Set-Field selbst dafuer sorgt, das\n    \/\/ es aktualisiert wird.\n    virtual void            Modify( SfxPoolItem *pOld, SfxPoolItem *pNew );\n    inline const String&    GetSetRefName() const;\n\n    USHORT SetSeqRefNo( SwSetExpField& rFld );\n\n    USHORT GetSeqFldList( SwSeqFldList& rList );\n    String MakeSeqName( USHORT nSeqNo );\n\n    \/\/ Seqencefelder ggfs. Kapitelweise numerieren\n\/\/  sal_Unicode GetDelimiter() const        { return cDelim; }\n\/\/  void SetDelimiter( sal_Unicode c )      { cDelim = c; }\n    const String& GetDelimiter() const      { return sDelim; }\n    void SetDelimiter( const String& s )    { sDelim = s; }\n    BYTE GetOutlineLvl() const              { return nLevel; }\n    void SetOutlineLvl( BYTE n )            { nLevel = n; }\n    void SetChapter( SwSetExpField& rFld, const SwNode& rNd );\n    \/\/ Member nur fuers SwDoc::UpdateExpFld - wird nur waehrend der Laufzeit\n    \/\/ von SequencefeldTypen benoetigt!!!\n    const SwNode* GetOutlineChgNd() const   { return pOutlChgNd; }\n    void SetOutlineChgNd( const SwNode* p ) { pOutlChgNd = p; }\n\n    virtual BOOL        QueryValue( com::sun::star::uno::Any& rVal, USHORT nWhich ) const;\n    virtual BOOL        PutValue( const com::sun::star::uno::Any& rVal, USHORT nWhich );\n};\n\ninline void SwSetExpFieldType::SetType( USHORT nTyp )\n{\n        nType = nTyp;\n        EnableFormat( !(nType & (nsSwGetSetExpType::GSE_SEQ|nsSwGetSetExpType::GSE_STRING)));\n}\n\ninline USHORT SwSetExpFieldType::GetType() const\n    { return nType;   }\n\ninline const String& SwSetExpFieldType::GetSetRefName() const\n    { return sName; }\n\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Ausdruck\n --------------------------------------------------------------------*\/\n\nclass SwSetExpField : public SwFormulaField\n{\n    String          sExpand;\n    String          aPText;\n    String          aSeqText;\n    BOOL            bInput;\n    USHORT          nSeqNo;\n    USHORT          nSubType;\n\npublic:\n    SwSetExpField(SwSetExpFieldType*, const String& rFormel, ULONG nFmt = 0);\n\n    virtual void                SetValue( const double& rVal );\n\n    virtual String              Expand() const;\n    virtual SwField*            Copy() const;\n\n    inline const String&        GetExpStr() const;\n\n    inline void                 ChgExpStr( const String& rExpand );\n\n    inline void                 SetPromptText(const String& rStr);\n    inline const                String& GetPromptText() const;\n\n    inline void                 SetInputFlag(BOOL bInp);\n    inline BOOL                 GetInputFlag() const;\n\n    virtual String              GetCntnt(BOOL bName = FALSE) const;\n    virtual USHORT              GetSubType() const;\n    virtual void                SetSubType(USHORT nType);\n\n    inline BOOL                 IsSequenceFld() const;\n\n    \/\/ fuer SequenceFelder - logische Nummer\n    inline void                 SetSeqNumber( USHORT n )    { nSeqNo = n; }\n    inline USHORT               GetSeqNumber() const        { return nSeqNo; }\n\n    \/\/ Der Name nur erfragen\n    virtual const String&       GetPar1()   const;\n\n    \/\/ Die Formel\n    virtual String              GetPar2()   const;\n    virtual void                SetPar2(const String& rStr);\n    virtual BOOL        QueryValue( com::sun::star::uno::Any& rVal, USHORT nWhich ) const;\n    virtual BOOL        PutValue( const com::sun::star::uno::Any& rVal, USHORT nWhich );\n};\n\ninline const String& SwSetExpField::GetExpStr() const\n    { return sExpand;       }\n\ninline void SwSetExpField::ChgExpStr( const String& rExpand )\n    { sExpand = rExpand;    }\n\ninline void  SwSetExpField::SetPromptText(const String& rStr)\n    { aPText = rStr;        }\n\ninline const String& SwSetExpField::GetPromptText() const\n    { return aPText;        }\n\ninline void SwSetExpField::SetInputFlag(BOOL bInp)\n    { bInput = bInp; }\n\ninline BOOL SwSetExpField::GetInputFlag() const\n    { return bInput; }\n\ninline BOOL SwSetExpField::IsSequenceFld() const\n    { return 0 != (nsSwGetSetExpType::GSE_SEQ & ((SwSetExpFieldType*)GetTyp())->GetType()); }\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Eingabe im Text\/Variable setzen\n --------------------------------------------------------------------*\/\n\nclass SwInputFieldType : public SwFieldType\n{\n    SwDoc* pDoc;\npublic:\n    SwInputFieldType( SwDoc* pDoc );\n\n    virtual SwFieldType* Copy() const;\n\n    SwDoc* GetDoc() const { return pDoc; }\n};\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Eingabefeld\n --------------------------------------------------------------------*\/\n\nclass SwInputField : public SwField\n{\n    String  aContent;\n    String  aPText;\n    String  aHelp;\n    String  aToolTip;\n    USHORT  nSubType;\npublic:\n    \/\/ Direkte Eingabe ueber Dialog alten Wert loeschen\n    SwInputField(SwInputFieldType*, const String& rContent ,\n                 const String& rPrompt, USHORT nSubType = 0,\n                 ULONG nFmt = 0);\n\n    virtual String          GetCntnt(BOOL bName = FALSE) const;\n    virtual String          Expand() const;\n    virtual SwField*        Copy() const;\n\n    \/\/ Content\n    virtual const String&   GetPar1() const;\n    virtual void            SetPar1(const String& rStr);\n\n    \/\/ aPromptText\n    virtual String          GetPar2() const;\n    virtual void            SetPar2(const String& rStr);\n\n    virtual String          GetHelp() const;\n    virtual void            SetHelp(const String & rStr);\n\n    virtual String          GetToolTip() const;\n    virtual void            SetToolTip(const String & rStr);\n\n    virtual BOOL            isFormField() const;\n\n    virtual USHORT          GetSubType() const;\n    virtual void            SetSubType(USHORT nSub);\n    virtual BOOL        QueryValue( com::sun::star::uno::Any& rVal, USHORT nWhich ) const;\n    virtual BOOL        PutValue( const com::sun::star::uno::Any& rVal, USHORT nWhich );\n};\n\n\/*--------------------------------------------------------------------\n    Description: Sorted list of input fields and DropDown fields\n --------------------------------------------------------------------*\/\n\nclass SwInputFieldList\n{\npublic:\n    SwInputFieldList( SwEditShell* pShell, BOOL bBuildTmpLst = FALSE );\n    ~SwInputFieldList();\n\n    USHORT      Count() const;\n    SwField*    GetField(USHORT nId);\n\n    void        GotoFieldPos(USHORT nId);\n    void        PushCrsr();\n    void        PopCrsr();\n\n    \/\/ vergleiche TmpLst mit akt Feldern. Alle neue kommen in die SortLst\n    \/\/ damit sie geupdatet werden koennen. Returnt die Anzahl.\n    \/\/ (Fuer Textbausteine: nur seine Input-Felder aktualisieren)\n    USHORT      BuildSortLst();\n\n    \/\/ Alle unselektierten Felder aus Liste entfernen\n    void        RemoveUnselectedFlds();\n\nprivate:\n    SwEditShell*    pSh;\n    _SetGetExpFlds* pSrtLst;\n    SvPtrarr        aTmpLst;\n};\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Tabellen-Formelfeld\n                  (Implementierung steht in tblcalc.cxx)\n --------------------------------------------------------------------*\/\n\nclass SwTblFieldType : public SwValueFieldType\n{\npublic:\n    SwTblFieldType(SwDoc* pDocPtr);\n    virtual SwFieldType* Copy() const;\n};\n\n\n\/\/ MSC will den hier nicht\n\/\/typedef void (SwField:: *FnScanFormel)( const SwTable&, String&,\n\/\/                                   String&, String* = 0, void* = 0 );\n\n\nclass SwTblField : public SwValueField, public SwTableFormula\n{\n    String      sExpand;\n    USHORT      nSubType;\n\n    \/\/ suche den TextNode, in dem das Feld steht\n    virtual const SwNode* GetNodeOfFormula() const;\n\npublic:\n    SwTblField( SwTblFieldType*, const String& rFormel,\n                USHORT nSubType = 0, ULONG nFmt = 0);\n\n    virtual void        SetValue( const double& rVal );\n    virtual USHORT      GetSubType() const;\n    virtual void        SetSubType(USHORT nType);\n    virtual String      Expand() const;\n    virtual SwField*    Copy() const;\n\n    const String&       GetExpStr() const               { return sExpand; }\n    void                ChgExpStr(const String& rStr)   { sExpand = rStr; }\n\n    \/\/ berechne sich selbst\n    void                CalcField( SwTblCalcPara& rCalcPara );\n\n    virtual String      GetCntnt(BOOL bName = FALSE) const;\n    \/\/ Die Formel\n    virtual String      GetPar2()   const;\n    virtual void        SetPar2(const String& rStr);\n    virtual BOOL        QueryValue( com::sun::star::uno::Any& rVal, USHORT nWhich ) const;\n    virtual BOOL        PutValue( const com::sun::star::uno::Any& rVal, USHORT nWhich );\n};\n\n\n#endif \/\/ _EXPFLD_HXX\nINTEGRATION: CWS changefileheader (1.10.242); FILE MERGED 2008\/04\/01 15:56:10 thb 1.10.242.3: #i85898# Stripping all external header guards 2008\/04\/01 12:53:28 thb 1.10.242.2: #i85898# Stripping all external header guards 2008\/03\/31 16:52:36 rt 1.10.242.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: expfld.hxx,v $\n * $Revision: 1.11 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _EXPFLD_HXX\n#define _EXPFLD_HXX\n\n#include \n#include \"swdllapi.h\"\n#include \n#include \n\nclass SfxPoolItem;\nclass SwTxtNode;\nclass SwFrm;\nstruct SwPosition;\nclass SwTxtFld;\nclass SwDoc;\nclass SwFmtFld;\nclass _SetGetExpFlds;\nclass SwEditShell;\n\n\/\/ Vorwaertsdeklaration: besorge den \"Body-TextNode\", fuer Exp.Fld in Fly's\n\/\/                      Header\/Footers\/Footnodes\nconst SwTxtNode* GetBodyTxtNode( const SwDoc& pDoc, SwPosition& rPos,\n                                 const SwFrm& rFrm );\n\/\/ Wandlung Address -> Adressen\nvoid ReplacePoint(String& sTmpName, BOOL bWithCommandType = FALSE);\n\nstruct _SeqFldLstElem\n{\n    String sDlgEntry;\n    USHORT nSeqNo;\n\n    _SeqFldLstElem( const String& rStr, USHORT nNo )\n        : sDlgEntry( rStr ), nSeqNo( nNo )\n    {}\n};\nSV_DECL_PTRARR_DEL( _SwSeqFldList, _SeqFldLstElem*, 10, 10 )\n\nclass SW_DLLPUBLIC SwSeqFldList : public _SwSeqFldList\n{\npublic:\n    SwSeqFldList()  : _SwSeqFldList( 10, 10 ) {}\n\n    BOOL InsertSort( _SeqFldLstElem* );\n    BOOL SeekEntry( const _SeqFldLstElem& , USHORT* pPos = 0 );\n};\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Ausdruck\n --------------------------------------------------------------------*\/\n\nclass SwGetExpFieldType : public SwValueFieldType\n{\npublic:\n        SwGetExpFieldType(SwDoc* pDoc);\n        virtual SwFieldType*    Copy() const;\n\n        \/\/ ueberlagert, weil das Get-Field nicht veraendert werden kann\n        \/\/ und dann auch nicht aktualisiert werden muss. Aktualisierung\n        \/\/ erfolgt beim Aendern von Set-Werten !\n\n        virtual void Modify( SfxPoolItem *pOld, SfxPoolItem *pNew );\n};\n\n\/*--------------------------------------------------------------------\n    Beschreibung: GetExperession\n --------------------------------------------------------------------*\/\n\nclass SwGetExpField : public SwFormulaField\n{\n    String          sExpand;\n    BOOL            bIsInBodyTxt;\n    USHORT          nSubType;\n\npublic:\n    SwGetExpField( SwGetExpFieldType*, const String& rFormel,\n                   USHORT nSubType = nsSwGetSetExpType::GSE_EXPR, ULONG nFmt = 0);\n\n    virtual void                SetValue( const double& rVal );\n    virtual void                SetLanguage(USHORT nLng);\n\n    virtual String              Expand() const;\n    virtual SwField*            Copy() const;\n\n    inline const String&        GetExpStr() const;\n    inline void                 ChgExpStr(const String& rExpand);\n\n    \/\/ wird von der Formatierung abgefragt\n    inline BOOL                 IsInBodyTxt() const;\n    \/\/ wird von UpdateExpFlds gesetzt (dort ist die Node-Position bekannt)\n    inline void                 ChgBodyTxtFlag( BOOL bIsInBody );\n    \/\/ fuer Felder in Header\/Footer\/Footnotes\/Flys:\n    \/\/ (wird nur von der Formatierung aufgerufen!!)\n    void                        ChangeExpansion( const SwFrm&, const SwTxtFld& );\n\n    virtual String              GetCntnt(BOOL bName = FALSE) const;\n\n    \/\/ Die Formel aendern\n    virtual String              GetPar2() const;\n    virtual void                SetPar2(const String& rStr);\n\n    virtual USHORT              GetSubType() const;\n    virtual void                SetSubType(USHORT nType);\n    virtual BOOL        QueryValue( com::sun::star::uno::Any& rVal, USHORT nWhich ) const;\n    virtual BOOL        PutValue( const com::sun::star::uno::Any& rVal, USHORT nWhich );\n\n    static USHORT       GetReferenceTextPos( const SwFmtFld& rFmt, SwDoc& rDoc);\n};\n\ninline void SwGetExpField::ChgExpStr(const String& rExpand)\n    { sExpand = rExpand;}\n\ninline const String& SwGetExpField::GetExpStr() const\n    { return sExpand;   }\n\n\/\/ wird von der Formatierung abgefragt\ninline BOOL SwGetExpField::IsInBodyTxt() const\n    { return bIsInBodyTxt; }\n\n\/\/ wird von UpdateExpFlds gesetzt (dort ist die Node-Position bekannt)\ninline void SwGetExpField::ChgBodyTxtFlag( BOOL bIsInBody )\n    { bIsInBodyTxt = bIsInBody; }\n\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Ausdruck setzen\n --------------------------------------------------------------------*\/\n\nclass SwSetExpField;\n\nclass SW_DLLPUBLIC SwSetExpFieldType : public SwValueFieldType\n{\n    String      sName;\n    const SwNode* pOutlChgNd;\n\/\/  sal_Unicode cDelim;\n    String      sDelim;\n    USHORT      nType;\n    BYTE        nLevel;\n    BOOL        bDeleted;\n\npublic:\n    SwSetExpFieldType( SwDoc* pDoc, const String& rName,\n                        USHORT nType = nsSwGetSetExpType::GSE_EXPR );\n    virtual SwFieldType*    Copy() const;\n    virtual const String&   GetName() const;\n\n    inline void             SetType(USHORT nTyp);\n    inline USHORT           GetType() const;\n\n    void                    SetSeqFormat(ULONG nFormat);\n    ULONG                   GetSeqFormat();\n\n    BOOL                    IsDeleted() const       { return bDeleted; }\n    void                    SetDeleted( BOOL b )    { bDeleted = b; }\n\n    \/\/ ueberlagert, weil das Set-Field selbst dafuer sorgt, das\n    \/\/ es aktualisiert wird.\n    virtual void            Modify( SfxPoolItem *pOld, SfxPoolItem *pNew );\n    inline const String&    GetSetRefName() const;\n\n    USHORT SetSeqRefNo( SwSetExpField& rFld );\n\n    USHORT GetSeqFldList( SwSeqFldList& rList );\n    String MakeSeqName( USHORT nSeqNo );\n\n    \/\/ Seqencefelder ggfs. Kapitelweise numerieren\n\/\/  sal_Unicode GetDelimiter() const        { return cDelim; }\n\/\/  void SetDelimiter( sal_Unicode c )      { cDelim = c; }\n    const String& GetDelimiter() const      { return sDelim; }\n    void SetDelimiter( const String& s )    { sDelim = s; }\n    BYTE GetOutlineLvl() const              { return nLevel; }\n    void SetOutlineLvl( BYTE n )            { nLevel = n; }\n    void SetChapter( SwSetExpField& rFld, const SwNode& rNd );\n    \/\/ Member nur fuers SwDoc::UpdateExpFld - wird nur waehrend der Laufzeit\n    \/\/ von SequencefeldTypen benoetigt!!!\n    const SwNode* GetOutlineChgNd() const   { return pOutlChgNd; }\n    void SetOutlineChgNd( const SwNode* p ) { pOutlChgNd = p; }\n\n    virtual BOOL        QueryValue( com::sun::star::uno::Any& rVal, USHORT nWhich ) const;\n    virtual BOOL        PutValue( const com::sun::star::uno::Any& rVal, USHORT nWhich );\n};\n\ninline void SwSetExpFieldType::SetType( USHORT nTyp )\n{\n        nType = nTyp;\n        EnableFormat( !(nType & (nsSwGetSetExpType::GSE_SEQ|nsSwGetSetExpType::GSE_STRING)));\n}\n\ninline USHORT SwSetExpFieldType::GetType() const\n    { return nType;   }\n\ninline const String& SwSetExpFieldType::GetSetRefName() const\n    { return sName; }\n\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Ausdruck\n --------------------------------------------------------------------*\/\n\nclass SwSetExpField : public SwFormulaField\n{\n    String          sExpand;\n    String          aPText;\n    String          aSeqText;\n    BOOL            bInput;\n    USHORT          nSeqNo;\n    USHORT          nSubType;\n\npublic:\n    SwSetExpField(SwSetExpFieldType*, const String& rFormel, ULONG nFmt = 0);\n\n    virtual void                SetValue( const double& rVal );\n\n    virtual String              Expand() const;\n    virtual SwField*            Copy() const;\n\n    inline const String&        GetExpStr() const;\n\n    inline void                 ChgExpStr( const String& rExpand );\n\n    inline void                 SetPromptText(const String& rStr);\n    inline const                String& GetPromptText() const;\n\n    inline void                 SetInputFlag(BOOL bInp);\n    inline BOOL                 GetInputFlag() const;\n\n    virtual String              GetCntnt(BOOL bName = FALSE) const;\n    virtual USHORT              GetSubType() const;\n    virtual void                SetSubType(USHORT nType);\n\n    inline BOOL                 IsSequenceFld() const;\n\n    \/\/ fuer SequenceFelder - logische Nummer\n    inline void                 SetSeqNumber( USHORT n )    { nSeqNo = n; }\n    inline USHORT               GetSeqNumber() const        { return nSeqNo; }\n\n    \/\/ Der Name nur erfragen\n    virtual const String&       GetPar1()   const;\n\n    \/\/ Die Formel\n    virtual String              GetPar2()   const;\n    virtual void                SetPar2(const String& rStr);\n    virtual BOOL        QueryValue( com::sun::star::uno::Any& rVal, USHORT nWhich ) const;\n    virtual BOOL        PutValue( const com::sun::star::uno::Any& rVal, USHORT nWhich );\n};\n\ninline const String& SwSetExpField::GetExpStr() const\n    { return sExpand;       }\n\ninline void SwSetExpField::ChgExpStr( const String& rExpand )\n    { sExpand = rExpand;    }\n\ninline void  SwSetExpField::SetPromptText(const String& rStr)\n    { aPText = rStr;        }\n\ninline const String& SwSetExpField::GetPromptText() const\n    { return aPText;        }\n\ninline void SwSetExpField::SetInputFlag(BOOL bInp)\n    { bInput = bInp; }\n\ninline BOOL SwSetExpField::GetInputFlag() const\n    { return bInput; }\n\ninline BOOL SwSetExpField::IsSequenceFld() const\n    { return 0 != (nsSwGetSetExpType::GSE_SEQ & ((SwSetExpFieldType*)GetTyp())->GetType()); }\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Eingabe im Text\/Variable setzen\n --------------------------------------------------------------------*\/\n\nclass SwInputFieldType : public SwFieldType\n{\n    SwDoc* pDoc;\npublic:\n    SwInputFieldType( SwDoc* pDoc );\n\n    virtual SwFieldType* Copy() const;\n\n    SwDoc* GetDoc() const { return pDoc; }\n};\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Eingabefeld\n --------------------------------------------------------------------*\/\n\nclass SwInputField : public SwField\n{\n    String  aContent;\n    String  aPText;\n    String  aHelp;\n    String  aToolTip;\n    USHORT  nSubType;\npublic:\n    \/\/ Direkte Eingabe ueber Dialog alten Wert loeschen\n    SwInputField(SwInputFieldType*, const String& rContent ,\n                 const String& rPrompt, USHORT nSubType = 0,\n                 ULONG nFmt = 0);\n\n    virtual String          GetCntnt(BOOL bName = FALSE) const;\n    virtual String          Expand() const;\n    virtual SwField*        Copy() const;\n\n    \/\/ Content\n    virtual const String&   GetPar1() const;\n    virtual void            SetPar1(const String& rStr);\n\n    \/\/ aPromptText\n    virtual String          GetPar2() const;\n    virtual void            SetPar2(const String& rStr);\n\n    virtual String          GetHelp() const;\n    virtual void            SetHelp(const String & rStr);\n\n    virtual String          GetToolTip() const;\n    virtual void            SetToolTip(const String & rStr);\n\n    virtual BOOL            isFormField() const;\n\n    virtual USHORT          GetSubType() const;\n    virtual void            SetSubType(USHORT nSub);\n    virtual BOOL        QueryValue( com::sun::star::uno::Any& rVal, USHORT nWhich ) const;\n    virtual BOOL        PutValue( const com::sun::star::uno::Any& rVal, USHORT nWhich );\n};\n\n\/*--------------------------------------------------------------------\n    Description: Sorted list of input fields and DropDown fields\n --------------------------------------------------------------------*\/\n\nclass SwInputFieldList\n{\npublic:\n    SwInputFieldList( SwEditShell* pShell, BOOL bBuildTmpLst = FALSE );\n    ~SwInputFieldList();\n\n    USHORT      Count() const;\n    SwField*    GetField(USHORT nId);\n\n    void        GotoFieldPos(USHORT nId);\n    void        PushCrsr();\n    void        PopCrsr();\n\n    \/\/ vergleiche TmpLst mit akt Feldern. Alle neue kommen in die SortLst\n    \/\/ damit sie geupdatet werden koennen. Returnt die Anzahl.\n    \/\/ (Fuer Textbausteine: nur seine Input-Felder aktualisieren)\n    USHORT      BuildSortLst();\n\n    \/\/ Alle unselektierten Felder aus Liste entfernen\n    void        RemoveUnselectedFlds();\n\nprivate:\n    SwEditShell*    pSh;\n    _SetGetExpFlds* pSrtLst;\n    SvPtrarr        aTmpLst;\n};\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Tabellen-Formelfeld\n                  (Implementierung steht in tblcalc.cxx)\n --------------------------------------------------------------------*\/\n\nclass SwTblFieldType : public SwValueFieldType\n{\npublic:\n    SwTblFieldType(SwDoc* pDocPtr);\n    virtual SwFieldType* Copy() const;\n};\n\n\n\/\/ MSC will den hier nicht\n\/\/typedef void (SwField:: *FnScanFormel)( const SwTable&, String&,\n\/\/                                   String&, String* = 0, void* = 0 );\n\n\nclass SwTblField : public SwValueField, public SwTableFormula\n{\n    String      sExpand;\n    USHORT      nSubType;\n\n    \/\/ suche den TextNode, in dem das Feld steht\n    virtual const SwNode* GetNodeOfFormula() const;\n\npublic:\n    SwTblField( SwTblFieldType*, const String& rFormel,\n                USHORT nSubType = 0, ULONG nFmt = 0);\n\n    virtual void        SetValue( const double& rVal );\n    virtual USHORT      GetSubType() const;\n    virtual void        SetSubType(USHORT nType);\n    virtual String      Expand() const;\n    virtual SwField*    Copy() const;\n\n    const String&       GetExpStr() const               { return sExpand; }\n    void                ChgExpStr(const String& rStr)   { sExpand = rStr; }\n\n    \/\/ berechne sich selbst\n    void                CalcField( SwTblCalcPara& rCalcPara );\n\n    virtual String      GetCntnt(BOOL bName = FALSE) const;\n    \/\/ Die Formel\n    virtual String      GetPar2()   const;\n    virtual void        SetPar2(const String& rStr);\n    virtual BOOL        QueryValue( com::sun::star::uno::Any& rVal, USHORT nWhich ) const;\n    virtual BOOL        PutValue( const com::sun::star::uno::Any& rVal, USHORT nWhich );\n};\n\n\n#endif \/\/ _EXPFLD_HXX\n<|endoftext|>"}
{"text":"\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 2003 The Apache Software Foundation.  All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:\n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written\n *    permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com .  For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/*\n * $Id$\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  Includes\n\/\/ ---------------------------------------------------------------------------\n#include \n#include \n#include \n#include \n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\n\/\/  Calculate alignment required by platform.\n\/\/\tTotal size of our header must match platform\n\/\/\tarchitecture-specific alignment, in order\n\/\/\tthat the returned block ptr (which follows our\n\/\/\theader), maintains block\/structure alignment.\ninline size_t\nCalculateBlockHeaderSize()\n{\n\t\/\/\tMacro XML_NEW_BLOCK_ALIGNMENT may be defined\n\t\/\/\tas needed to calculate alignment on a per-architecture\n\t\/\/\tbasis.\n\t#ifdef XML_NEW_BLOCK_ALIGNMENT\n\t\tsize_t alignment = XML_NEW_BLOCK_ALIGNMENT;\n\t#else\n\t\tsize_t alignment = std::max(sizeof(void*), sizeof(double));\n\t#endif\n\t\n\tsize_t headerUsage = sizeof(MemoryManager*);\n\treturn (headerUsage + (alignment - headerUsage % alignment));\n}\n\nvoid* XMemory::operator new(size_t size)\n{\n\tsize_t headerSize = CalculateBlockHeaderSize();\n    void* const block = XMLPlatformUtils::fgMemoryManager->allocate\n        (\n\t        headerSize + size\n        );\n    *(MemoryManager**)block = XMLPlatformUtils::fgMemoryManager;\n\n    return (char*)block + headerSize;\n}\n\nvoid* XMemory::operator new(size_t size, MemoryManager* manager)\n{\n    assert(manager != 0);\n\t\n\tsize_t headerSize = CalculateBlockHeaderSize();\n    void* const block = manager->allocate(headerSize + size);\n    *(MemoryManager**)block = manager;\n\n    return (char*)block + headerSize;\n}\n\nvoid XMemory::operator delete(void* p)\n{\n    if (p != 0)\n    {\n\t\tsize_t headerSize = CalculateBlockHeaderSize();\n        void* const block = (char*)p - headerSize;\n\n        MemoryManager* const manager = *(MemoryManager**)block;\n        assert(manager != 0);\n        manager->deallocate(block);\n    }\n}\n\nvoid XMemory::operator delete(void* p, MemoryManager* manager)\n{\n    assert(manager != 0);\n\t\n\tif (p != 0)\n\t{\n\t\tsize_t headerSize = CalculateBlockHeaderSize();\n        void* const block = (char*)p - headerSize;\n\t\t\n\t\tassert(*(MemoryManager**)block == manager);\n\t\tmanager->deallocate(block);\n\t}\n}\n\nXERCES_CPP_NAMESPACE_END\n\nRemoved usage of std to compile under gcc and other platforms.\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 2003 The Apache Software Foundation.  All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:\n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written\n *    permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com .  For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/*\n * $Id$\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  Includes\n\/\/ ---------------------------------------------------------------------------\n#include \n#include \n#include \n#include \n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\n\/\/  Calculate alignment required by platform.\n\/\/\tTotal size of our header must match platform\n\/\/\tarchitecture-specific alignment, in order\n\/\/\tthat the returned block ptr (which follows our\n\/\/\theader), maintains block\/structure alignment.\ninline size_t\nCalculateBlockHeaderSize()\n{\n\t\/\/\tMacro XML_NEW_BLOCK_ALIGNMENT may be defined\n\t\/\/\tas needed to calculate alignment on a per-architecture\n\t\/\/\tbasis.\n\t#ifdef XML_NEW_BLOCK_ALIGNMENT\n\t\tsize_t alignment = XML_NEW_BLOCK_ALIGNMENT;\n\t#else\n        size_t alignment = sizeof(void*) > sizeof(double) ? sizeof(void*) : sizeof(double);\n\t#endif\n\t\n\tsize_t headerUsage = sizeof(MemoryManager*);\n\treturn (headerUsage + (alignment - headerUsage % alignment));\n}\n\nvoid* XMemory::operator new(size_t size)\n{\n\tsize_t headerSize = CalculateBlockHeaderSize();\n    void* const block = XMLPlatformUtils::fgMemoryManager->allocate\n        (\n\t        headerSize + size\n        );\n    *(MemoryManager**)block = XMLPlatformUtils::fgMemoryManager;\n\n    return (char*)block + headerSize;\n}\n\nvoid* XMemory::operator new(size_t size, MemoryManager* manager)\n{\n    assert(manager != 0);\n\t\n\tsize_t headerSize = CalculateBlockHeaderSize();\n    void* const block = manager->allocate(headerSize + size);\n    *(MemoryManager**)block = manager;\n\n    return (char*)block + headerSize;\n}\n\nvoid XMemory::operator delete(void* p)\n{\n    if (p != 0)\n    {\n\t\tsize_t headerSize = CalculateBlockHeaderSize();\n        void* const block = (char*)p - headerSize;\n\n        MemoryManager* const manager = *(MemoryManager**)block;\n        assert(manager != 0);\n        manager->deallocate(block);\n    }\n}\n\nvoid XMemory::operator delete(void* p, MemoryManager* manager)\n{\n    assert(manager != 0);\n\t\n\tif (p != 0)\n\t{\n\t\tsize_t headerSize = CalculateBlockHeaderSize();\n        void* const block = (char*)p - headerSize;\n\t\t\n\t\tassert(*(MemoryManager**)block == manager);\n\t\tmanager->deallocate(block);\n\t}\n}\n\nXERCES_CPP_NAMESPACE_END\n\n<|endoftext|>"}
{"text":"\/*\nCopyright (c) 2012-2014 The SSDB Authors. All rights reserved.\nUse of this source code is governed by a BSD-style license that can be\nfound in the LICENSE file.\n*\/\n\/* hash *\/\n#include \"serv.h\"\n#include \"net\/proc.h\"\n#include \"net\/server.h\"\n\nint proc_hexists(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(3);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n    const Bytes &name = req[1];\n    const Bytes &key = req[2];\n    std::pair val;\n    int ret = serv->ssdb->hget(name, key, val);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else if (ret == 0) {\n        resp->reply_bool(0);\n    } else {\n        resp->reply_bool(val.second);\n    }\n\n    return 0;\n}\n\n\nint proc_hmset(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    SSDBServer *serv = (SSDBServer *) net->data;\n    if (req.size() < 4 || req.size() % 2 != 0) {\n        reply_errinfo_return(\"wrong number of arguments for 'hmset' command\");\n    }\n\n    std::map kvs;\n    const Bytes &name = req[1];\n    std::vector::const_iterator it = req.begin() + 2;\n    for (; it != req.end(); it += 2) {\n        const Bytes &key = *it;\n        const Bytes &val = *(it + 1);\n        kvs[key] = val;\n    }\n\n    int ret = serv->ssdb->hmset(name, kvs);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    }\n\n    resp->reply_int(0, 1);\n\n    return 0;\n}\n\nint proc_hdel(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(3);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n    const Bytes &key = req[1];\n\n    std::set fields;\n    for (int j = 2; j < req.size(); ++j) {\n        fields.insert(req[j]);\n    }\n\n    int deleted = 0;\n    int ret = serv->ssdb->hdel(key, fields, &deleted);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    }\n\n    resp->reply_int(0, deleted);\n    return 0;\n}\n\nint proc_hmget(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(3);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n    Request::const_iterator it = req.begin() + 1;\n    const Bytes name = *it;\n    it++;\n\n    std::vector reqKeys;\n    std::map resMap;\n\n    for (; it != req.end(); it += 1) {\n        const Bytes &key = *it;\n        reqKeys.push_back(key.String());\n    }\n\n    int ret = serv->ssdb->hmget(name, reqKeys, resMap);\n    check_key(ret);\n    if (ret == 1) {\n        resp->reply_list_ready();\n\n        for (const auto &reqKey : reqKeys) {\n\n            auto pos = resMap.find(reqKey);\n            if (pos == resMap.end()) {\n                \/\/\n            } else {\n                resp->push_back(pos->first);\n                resp->push_back(pos->second);\n            }\n\n        }\n\n    } else if (ret == 0) {\n        resp->reply_list_ready();\n\n        \/\/nothing\n    } else {\n        reply_err_return(ret);\n    }\n\n    return 0;\n}\n\nint proc_hsize(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(2);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n    uint64_t size = 0;\n    int ret = serv->ssdb->hsize(req[1], &size);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else {\n        resp->reply_int(ret, size);\n    }\n\n    return 0;\n}\n\nint proc_hset(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(4);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n    int added = 0;\n    int ret = serv->ssdb->hset(req[1], req[2], req[3], &added);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else if (ret == 0) {\n        resp->reply_bool(ret);\n    } else {\n        resp->reply_bool(added);\n    }\n\n    return 0;\n}\n\nint proc_hsetnx(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(4);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n    int added = 0;\n    int ret = serv->ssdb->hsetnx(req[1], req[2], req[3], &added);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else if (ret == 0) {\n        resp->reply_bool(ret);\n    } else {\n        resp->reply_bool(added);\n    }\n\n    return 0;\n}\n\nint proc_hget(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(3);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n\n    std::pair val;\n    int ret = serv->ssdb->hget(req[1], req[2], val);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else {\n        if (val.second) {\n            resp->reply_get(1, &val.first);\n        } else {\n            resp->reply_get(0, &val.first);\n        }\n    }\n\n    return 0;\n}\n\n\nint proc_hgetall(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(2);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n\n    std::map resMap;\n    int ret = serv->ssdb->hgetall(req[1], resMap);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else if (ret == 0) {\n        resp->reply_list_ready();\n\n        \/\/nothing\n    } else {\n        resp->reply_list_ready();\n\n        for (const auto &res : resMap) {\n            resp->push_back(res.first);\n            resp->push_back(res.second);\n        }\n\n    }\n\n    return 0;\n}\n\nint proc_hscan(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(3);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n\n    int cursorIndex = 2;\n\n    Bytes cursor = req[cursorIndex];\n\n    cursor.Uint64();\n    if (errno == EINVAL) {\n        reply_err_return(INVALID_INT);\n    }\n\n    std::string pattern = \"*\";\n    uint64_t limit = 10;\n\n    std::vector::const_iterator it = req.begin() + cursorIndex + 1;\n    for (; it != req.end(); it += 2) {\n        std::string key = (*it).String();\n        strtolower(&key);\n\n        if (key == \"match\") {\n            pattern = (*(it + 1)).String();\n        } else if (key == \"count\") {\n            limit = (*(it + 1)).Uint64();\n            if (errno == EINVAL) {\n                reply_err_return(INVALID_INT);\n            }\n        } else {\n            reply_err_return(SYNTAX_ERR);\n        }\n    }\n    resp->reply_scan_ready();\n\n    int ret = serv->ssdb->hscan(req[1], cursor, pattern, limit, resp->resp);\n    check_key(ret);\n    if (ret < 0) {\n        resp->resp.clear();\n        reply_err_return(ret);\n    } else if (ret == 0) {\n    }\n\n    return 0;\n}\n\n\nint proc_hkeys(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(5);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n\/\/\tuint64_t limit = req[4].Uint64();\n\n    std::map resMap;\n    int ret = serv->ssdb->hgetall(req[1], resMap);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else if (ret == 0) {\n        resp->reply_list_ready();\n\n        \/\/nothing\n    } else {\n        resp->reply_list_ready();\n\n        for (const auto &res : resMap) {\n            \/\/TODO 这里同时处理了kv 只是没有返回.\n            resp->push_back(res.first);\n\/\/            resp->push_back(res.second);\n        }\n    }\n\n\n    return 0;\n}\n\nint proc_hvals(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(5);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n\/\/\tuint64_t limit = req[4].Uint64();\n\n    std::map resMap;\n    int ret = serv->ssdb->hgetall(req[1], resMap);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else if (ret == 0) {\n        resp->reply_list_ready();\n\n        \/\/nothing\n    } else {\n        resp->reply_list_ready();\n\n        for (const auto &res : resMap) {\n            \/\/TODO 这里同时处理了kv 只是没有返回.\n\/\/            resp->push_back(res.first);\n            resp->push_back(res.second);\n        }\n    }\n\n    return 0;\n}\n\nint proc_hincrbyfloat(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    SSDBServer *serv = (SSDBServer *) net->data;\n    CHECK_NUM_PARAMS(4);\n\n    long double by = req[3].LDouble();\n    if (errno == EINVAL) {\n        reply_err_return(INVALID_DBL);\n    }\n\n    long double new_val;\n    int ret = serv->ssdb->hincrbyfloat(req[1], req[2], by, &new_val);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else {\n        resp->reply_long_double(ret, new_val);\n    }\n    return 0;\n\n}\n\nint proc_hincr(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    SSDBServer *serv = (SSDBServer *) net->data;\n    CHECK_NUM_PARAMS(4);\n\n    int64_t by = req[3].Int64();\n\n    if (errno == EINVAL) {\n        reply_err_return(INVALID_INT);\n    }\n\n    int64_t new_val = 0;\n    int ret = serv->ssdb->hincr(req[1], req[2], by, &new_val);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else {\n        resp->reply_int(ret, new_val);\n    }\n    return 0;\n\n}hash 附加返回值 done\/*\nCopyright (c) 2012-2014 The SSDB Authors. All rights reserved.\nUse of this source code is governed by a BSD-style license that can be\nfound in the LICENSE file.\n*\/\n\/* hash *\/\n#include \"serv.h\"\n#include \"net\/proc.h\"\n#include \"net\/server.h\"\n\nint proc_hexists(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(3);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n    const Bytes &name = req[1];\n    const Bytes &key = req[2];\n    std::pair val;\n    int ret = serv->ssdb->hget(name, key, val);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else if (ret == 0) {\n        resp->reply_bool(0);\n    } else {\n        resp->reply_bool(val.second);\n    }\n\n    return 0;\n}\n\n\nint proc_hmset(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    SSDBServer *serv = (SSDBServer *) net->data;\n    if (req.size() < 4 || req.size() % 2 != 0) {\n        reply_errinfo_return(\"wrong number of arguments for 'hmset' command\");\n    }\n\n    std::map kvs;\n    const Bytes &name = req[1];\n    std::vector::const_iterator it = req.begin() + 2;\n    for (; it != req.end(); it += 2) {\n        const Bytes &key = *it;\n        const Bytes &val = *(it + 1);\n        kvs[key] = val;\n    }\n\n    int ret = serv->ssdb->hmset(name, kvs);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    }\n\n    resp->reply_int(0, 1);\n\n    return 0;\n}\n\nint proc_hdel(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(3);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n    const Bytes &key = req[1];\n\n    std::set fields;\n    for (int j = 2; j < req.size(); ++j) {\n        fields.insert(req[j]);\n    }\n\n    int deleted = 0;\n    int ret = serv->ssdb->hdel(key, fields, &deleted);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    }\n\n    resp->reply_int(0, deleted);\n    return 0;\n}\n\nint proc_hmget(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(3);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n    Request::const_iterator it = req.begin() + 1;\n    const Bytes name = *it;\n    it++;\n\n    std::vector reqKeys;\n    std::map resMap;\n\n    for (; it != req.end(); it += 1) {\n        const Bytes &key = *it;\n        reqKeys.push_back(key.String());\n    }\n\n    int ret = serv->ssdb->hmget(name, reqKeys, resMap);\n    check_key(ret);\n    if (ret == 1) {\n        resp->reply_list_ready();\n\n        for (const auto &reqKey : reqKeys) {\n\n            auto pos = resMap.find(reqKey);\n            if (pos == resMap.end()) {\n                \/\/\n            } else {\n                resp->push_back(pos->first);\n                resp->push_back(pos->second);\n            }\n\n        }\n\n    } else if (ret == 0) {\n        resp->reply_list_ready();\n\n        \/\/nothing\n    } else {\n        reply_err_return(ret);\n    }\n\n    return 0;\n}\n\nint proc_hsize(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(2);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n    uint64_t size = 0;\n    int ret = serv->ssdb->hsize(req[1], &size);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else {\n        resp->reply_int(ret, size);\n    }\n\n    return 0;\n}\n\nint proc_hset(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(4);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n    int added = 0;\n    int ret = serv->ssdb->hset(req[1], req[2], req[3], &added);\n\/\/    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else if (ret == 0) {\n        resp->reply_bool(ret);\n    } else {\n        resp->reply_bool(added);\n    }\n\n    return 0;\n}\n\nint proc_hsetnx(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(4);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n    int added = 0;\n    int ret = serv->ssdb->hsetnx(req[1], req[2], req[3], &added);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else if (ret == 0) {\n        resp->reply_bool(ret);\n    } else {\n        resp->reply_bool(added);\n    }\n\n    return 0;\n}\n\nint proc_hget(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(3);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n\n    std::pair val;\n    int ret = serv->ssdb->hget(req[1], req[2], val);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else {\n        if (val.second) {\n            resp->reply_get(1, &val.first);\n        } else {\n            resp->reply_get(0, &val.first);\n        }\n    }\n\n    return 0;\n}\n\n\nint proc_hgetall(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(2);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n\n    std::map resMap;\n    int ret = serv->ssdb->hgetall(req[1], resMap);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else if (ret == 0) {\n        resp->reply_list_ready();\n\n        \/\/nothing\n    } else {\n        resp->reply_list_ready();\n\n        for (const auto &res : resMap) {\n            resp->push_back(res.first);\n            resp->push_back(res.second);\n        }\n\n    }\n\n    return 0;\n}\n\nint proc_hscan(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(3);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n\n    int cursorIndex = 2;\n\n    Bytes cursor = req[cursorIndex];\n\n    cursor.Uint64();\n    if (errno == EINVAL) {\n        reply_err_return(INVALID_INT);\n    }\n\n    std::string pattern = \"*\";\n    uint64_t limit = 10;\n\n    std::vector::const_iterator it = req.begin() + cursorIndex + 1;\n    for (; it != req.end(); it += 2) {\n        std::string key = (*it).String();\n        strtolower(&key);\n\n        if (key == \"match\") {\n            pattern = (*(it + 1)).String();\n        } else if (key == \"count\") {\n            limit = (*(it + 1)).Uint64();\n            if (errno == EINVAL) {\n                reply_err_return(INVALID_INT);\n            }\n        } else {\n            reply_err_return(SYNTAX_ERR);\n        }\n    }\n    resp->reply_scan_ready();\n\n    int ret = serv->ssdb->hscan(req[1], cursor, pattern, limit, resp->resp);\n    check_key(ret);\n    if (ret < 0) {\n        resp->resp.clear();\n        reply_err_return(ret);\n    } else if (ret == 0) {\n    }\n\n    return 0;\n}\n\n\nint proc_hkeys(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(5);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n\/\/\tuint64_t limit = req[4].Uint64();\n\n    std::map resMap;\n    int ret = serv->ssdb->hgetall(req[1], resMap);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else if (ret == 0) {\n        resp->reply_list_ready();\n\n        \/\/nothing\n    } else {\n        resp->reply_list_ready();\n\n        for (const auto &res : resMap) {\n            \/\/TODO 这里同时处理了kv 只是没有返回.\n            resp->push_back(res.first);\n\/\/            resp->push_back(res.second);\n        }\n    }\n\n\n    return 0;\n}\n\nint proc_hvals(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    CHECK_NUM_PARAMS(5);\n    SSDBServer *serv = (SSDBServer *) net->data;\n\n\/\/\tuint64_t limit = req[4].Uint64();\n\n    std::map resMap;\n    int ret = serv->ssdb->hgetall(req[1], resMap);\n    check_key(ret);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else if (ret == 0) {\n        resp->reply_list_ready();\n\n        \/\/nothing\n    } else {\n        resp->reply_list_ready();\n\n        for (const auto &res : resMap) {\n            \/\/TODO 这里同时处理了kv 只是没有返回.\n\/\/            resp->push_back(res.first);\n            resp->push_back(res.second);\n        }\n    }\n\n    return 0;\n}\n\nint proc_hincrbyfloat(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    SSDBServer *serv = (SSDBServer *) net->data;\n    CHECK_NUM_PARAMS(4);\n\n    long double by = req[3].LDouble();\n    if (errno == EINVAL) {\n        reply_err_return(INVALID_DBL);\n    }\n\n    long double new_val;\n    int ret = serv->ssdb->hincrbyfloat(req[1], req[2], by, &new_val);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else {\n        resp->reply_long_double(ret, new_val);\n    }\n    return 0;\n\n}\n\nint proc_hincr(NetworkServer *net, Link *link, const Request &req, Response *resp) {\n    SSDBServer *serv = (SSDBServer *) net->data;\n    CHECK_NUM_PARAMS(4);\n\n    int64_t by = req[3].Int64();\n\n    if (errno == EINVAL) {\n        reply_err_return(INVALID_INT);\n    }\n\n    int64_t new_val = 0;\n    int ret = serv->ssdb->hincr(req[1], req[2], by, &new_val);\n    if (ret < 0) {\n        reply_err_return(ret);\n    } else {\n        resp->reply_int(ret, new_val);\n    }\n    return 0;\n\n}<|endoftext|>"}
{"text":"\/*\n * Copyright (c) 2013 - 2016, Roland Bock\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n *   Redistributions of source code must retain the above copyright notice, this\n *   list of conditions and the following disclaimer.\n *\n *   Redistributions in binary form must reproduce the above copyright notice, this\n *   list of conditions and the following disclaimer in the documentation and\/or\n *   other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"detail\/connection_handle.h\"\n#include \"detail\/prepared_statement_handle.h\"\n#include \n#include \n#include \n\n#ifdef SQLPP_DYNAMIC_LOADING\n#include \n#endif\n\nnamespace sqlpp\n{\n  namespace sqlite3\n  {\n\n#ifdef SQLPP_DYNAMIC_LOADING\n  using namespace dynamic;\n#endif\n\n    namespace\n    {\n      detail::prepared_statement_handle_t prepare_statement(detail::connection_handle& handle,\n                                                            const std::string& statement)\n      {\n        if (handle.config.debug)\n          std::cerr << \"Sqlite3 debug: Preparing: '\" << statement << \"'\" << std::endl;\n\n        detail::prepared_statement_handle_t result(nullptr, handle.config.debug);\n\n        auto rc = sqlite3_prepare_v2(handle.sqlite, statement.c_str(), static_cast(statement.size()),\n                                     &result.sqlite_statement, nullptr);\n\n        if (rc != SQLITE_OK)\n        {\n          throw sqlpp::exception(\"Sqlite3 error: Could not prepare statement: \" +\n                                 std::string(sqlite3_errmsg(handle.sqlite)) + \" (statement was >>\" + statement +\n                                 \"<<\\n\");\n        }\n\n        return result;\n      }\n\n      void execute_statement(detail::connection_handle& handle, detail::prepared_statement_handle_t& prepared)\n      {\n        auto rc = sqlite3_step(prepared.sqlite_statement);\n        switch (rc)\n        {\n          case SQLITE_OK:\n          case SQLITE_ROW:  \/\/ might occur if execute is called with a select\n          case SQLITE_DONE:\n            return;\n          default:\n            std::cerr << \"Sqlite3 debug: sqlite3_step return code: \" << rc << std::endl;\n            throw sqlpp::exception(\"Sqlite3 error: Could not execute statement: \" +\n                                   std::string(sqlite3_errmsg(handle.sqlite)));\n        }\n      }\n    }\n\n    connection::connection(connection_config config) : _handle(new detail::connection_handle(std::move(config)))\n    {\n    }\n\n    connection::~connection()\n    {\n    }\n\n    ::sqlite3* connection::native_handle()\n    {\n      return _handle->sqlite;\n    }\n\n    bind_result_t connection::select_impl(const std::string& statement)\n    {\n      std::unique_ptr prepared(\n          new detail::prepared_statement_handle_t(prepare_statement(*_handle, statement)));\n      if (!prepared)\n      {\n        throw sqlpp::exception(\"Sqlite3 error: Could not store result set\");\n      }\n\n      return {std::move(prepared)};\n    }\n\n    bind_result_t connection::run_prepared_select_impl(prepared_statement_t& prepared_statement)\n    {\n      return {prepared_statement._handle};\n    }\n\n    size_t connection::insert_impl(const std::string& statement)\n    {\n      auto prepared = prepare_statement(*_handle, statement);\n      execute_statement(*_handle, prepared);\n\n      return sqlite3_last_insert_rowid(_handle->sqlite);\n    }\n\n    prepared_statement_t connection::prepare_impl(const std::string& statement)\n    {\n      return {std::unique_ptr(\n          new detail::prepared_statement_handle_t(prepare_statement(*_handle, statement)))};\n    }\n\n    size_t connection::run_prepared_insert_impl(prepared_statement_t& prepared_statement)\n    {\n      execute_statement(*_handle, *prepared_statement._handle.get());\n\n      return sqlite3_last_insert_rowid(_handle->sqlite);\n    }\n\n    size_t connection::run_prepared_execute_impl(prepared_statement_t& prepared_statement)\n    {\n      execute_statement(*_handle, *prepared_statement._handle.get());\n\n      return sqlite3_changes(_handle->sqlite);\n    }\n\n    size_t connection::execute(const std::string& statement)\n    {\n      auto prepared = prepare_statement(*_handle, statement);\n      execute_statement(*_handle, prepared);\n      return sqlite3_changes(_handle->sqlite);\n    }\n\n    size_t connection::update_impl(const std::string& statement)\n    {\n      auto prepared = prepare_statement(*_handle, statement);\n      execute_statement(*_handle, prepared);\n      return sqlite3_changes(_handle->sqlite);\n    }\n\n    size_t connection::run_prepared_update_impl(prepared_statement_t& prepared_statement)\n    {\n      execute_statement(*_handle, *prepared_statement._handle.get());\n\n      return sqlite3_changes(_handle->sqlite);\n    }\n\n    size_t connection::remove_impl(const std::string& statement)\n    {\n      auto prepared = prepare_statement(*_handle, statement);\n      execute_statement(*_handle, prepared);\n      return sqlite3_changes(_handle->sqlite);\n    }\n\n    size_t connection::run_prepared_remove_impl(prepared_statement_t& prepared_statement)\n    {\n      execute_statement(*_handle, *prepared_statement._handle.get());\n\n      return sqlite3_changes(_handle->sqlite);\n    }\n\n    std::string connection::escape(const std::string& s) const\n    {\n      std::string t;\n      t.reserve(s.size());\n\n      for (const char c : s)\n      {\n        if (c == '\\'')\n          t.push_back(c);\n        t.push_back(c);\n      }\n\n      return t;\n    }\n\n    void connection::start_transaction(isolation_level isolation)\n    {\n      if (_transaction_active)\n      {\n        throw sqlpp::exception(\"Sqlite3 error: Cannot have more than one open transaction per connection\");\n      }\n      if (isolation == sqlpp::isolation_level::undefined)\n      {\n          \/\/ use the current default, nothing to do\n      } else if (isolation == sqlpp::isolation_level::read_uncommitted) {\n          execute(\"pragma read_uncommitted = true;\");\n      } else {\n          execute(\"pragma read_uncommitted = false;\");\n      }\n\n      auto prepared = prepare_statement(*_handle, \"BEGIN\");\n      execute_statement(*_handle, prepared);\n      _transaction_active = true;\n    }\n\n    void connection::commit_transaction()\n    {\n      if (not _transaction_active)\n      {\n        throw sqlpp::exception(\"Sqlite3 error: Cannot commit a finished or failed transaction\");\n      }\n      _transaction_active = false;\n      auto prepared = prepare_statement(*_handle, \"COMMIT\");\n      execute_statement(*_handle, prepared);\n    }\n\n    void connection::rollback_transaction(bool report)\n    {\n      if (not _transaction_active)\n      {\n        throw sqlpp::exception(\"Sqlite3 error: Cannot rollback a finished or failed transaction\");\n      }\n      if (report)\n      {\n        std::cerr << \"Sqlite3 warning: Rolling back unfinished transaction\" << std::endl;\n      }\n      _transaction_active = false;\n      auto prepared = prepare_statement(*_handle, \"ROLLBACK\");\n      execute_statement(*_handle, prepared);\n    }\n\n    void connection::report_rollback_failure(const std::string message) noexcept\n    {\n      std::cerr << \"Sqlite3 message:\" << message << std::endl;\n    }\n\n    uint64_t connection::last_insert_id() noexcept\n    {\n      return sqlite3_last_insert_rowid(_handle->sqlite);\n    }\n\n    auto connection::attach(const connection_config& config, const std::string name) -> schema_t\n    {\n      auto prepared =\n          prepare_statement(*_handle, \"ATTACH '\" + escape(config.path_to_database) + \"' AS \" + escape(name));\n      execute_statement(*_handle, prepared);\n\n      return {name};\n    }\n  }\n}\nCleaned up ugly start_transaction function a bit\/*\n * Copyright (c) 2013 - 2016, Roland Bock\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n *   Redistributions of source code must retain the above copyright notice, this\n *   list of conditions and the following disclaimer.\n *\n *   Redistributions in binary form must reproduce the above copyright notice, this\n *   list of conditions and the following disclaimer in the documentation and\/or\n *   other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"detail\/connection_handle.h\"\n#include \"detail\/prepared_statement_handle.h\"\n#include \n#include \n#include \n\n#ifdef SQLPP_DYNAMIC_LOADING\n#include \n#endif\n\nnamespace sqlpp\n{\n  namespace sqlite3\n  {\n\n#ifdef SQLPP_DYNAMIC_LOADING\n  using namespace dynamic;\n#endif\n\n    namespace\n    {\n      detail::prepared_statement_handle_t prepare_statement(detail::connection_handle& handle,\n                                                            const std::string& statement)\n      {\n        if (handle.config.debug)\n          std::cerr << \"Sqlite3 debug: Preparing: '\" << statement << \"'\" << std::endl;\n\n        detail::prepared_statement_handle_t result(nullptr, handle.config.debug);\n\n        auto rc = sqlite3_prepare_v2(handle.sqlite, statement.c_str(), static_cast(statement.size()),\n                                     &result.sqlite_statement, nullptr);\n\n        if (rc != SQLITE_OK)\n        {\n          throw sqlpp::exception(\"Sqlite3 error: Could not prepare statement: \" +\n                                 std::string(sqlite3_errmsg(handle.sqlite)) + \" (statement was >>\" + statement +\n                                 \"<<\\n\");\n        }\n\n        return result;\n      }\n\n      void execute_statement(detail::connection_handle& handle, detail::prepared_statement_handle_t& prepared)\n      {\n        auto rc = sqlite3_step(prepared.sqlite_statement);\n        switch (rc)\n        {\n          case SQLITE_OK:\n          case SQLITE_ROW:  \/\/ might occur if execute is called with a select\n          case SQLITE_DONE:\n            return;\n          default:\n            std::cerr << \"Sqlite3 debug: sqlite3_step return code: \" << rc << std::endl;\n            throw sqlpp::exception(\"Sqlite3 error: Could not execute statement: \" +\n                                   std::string(sqlite3_errmsg(handle.sqlite)));\n        }\n      }\n    }\n\n    connection::connection(connection_config config) : _handle(new detail::connection_handle(std::move(config)))\n    {\n    }\n\n    connection::~connection()\n    {\n    }\n\n    ::sqlite3* connection::native_handle()\n    {\n      return _handle->sqlite;\n    }\n\n    bind_result_t connection::select_impl(const std::string& statement)\n    {\n      std::unique_ptr prepared(\n          new detail::prepared_statement_handle_t(prepare_statement(*_handle, statement)));\n      if (!prepared)\n      {\n        throw sqlpp::exception(\"Sqlite3 error: Could not store result set\");\n      }\n\n      return {std::move(prepared)};\n    }\n\n    bind_result_t connection::run_prepared_select_impl(prepared_statement_t& prepared_statement)\n    {\n      return {prepared_statement._handle};\n    }\n\n    size_t connection::insert_impl(const std::string& statement)\n    {\n      auto prepared = prepare_statement(*_handle, statement);\n      execute_statement(*_handle, prepared);\n\n      return sqlite3_last_insert_rowid(_handle->sqlite);\n    }\n\n    prepared_statement_t connection::prepare_impl(const std::string& statement)\n    {\n      return {std::unique_ptr(\n          new detail::prepared_statement_handle_t(prepare_statement(*_handle, statement)))};\n    }\n\n    size_t connection::run_prepared_insert_impl(prepared_statement_t& prepared_statement)\n    {\n      execute_statement(*_handle, *prepared_statement._handle.get());\n\n      return sqlite3_last_insert_rowid(_handle->sqlite);\n    }\n\n    size_t connection::run_prepared_execute_impl(prepared_statement_t& prepared_statement)\n    {\n      execute_statement(*_handle, *prepared_statement._handle.get());\n\n      return sqlite3_changes(_handle->sqlite);\n    }\n\n    size_t connection::execute(const std::string& statement)\n    {\n      auto prepared = prepare_statement(*_handle, statement);\n      execute_statement(*_handle, prepared);\n      return sqlite3_changes(_handle->sqlite);\n    }\n\n    size_t connection::update_impl(const std::string& statement)\n    {\n      auto prepared = prepare_statement(*_handle, statement);\n      execute_statement(*_handle, prepared);\n      return sqlite3_changes(_handle->sqlite);\n    }\n\n    size_t connection::run_prepared_update_impl(prepared_statement_t& prepared_statement)\n    {\n      execute_statement(*_handle, *prepared_statement._handle.get());\n\n      return sqlite3_changes(_handle->sqlite);\n    }\n\n    size_t connection::remove_impl(const std::string& statement)\n    {\n      auto prepared = prepare_statement(*_handle, statement);\n      execute_statement(*_handle, prepared);\n      return sqlite3_changes(_handle->sqlite);\n    }\n\n    size_t connection::run_prepared_remove_impl(prepared_statement_t& prepared_statement)\n    {\n      execute_statement(*_handle, *prepared_statement._handle.get());\n\n      return sqlite3_changes(_handle->sqlite);\n    }\n\n    std::string connection::escape(const std::string& s) const\n    {\n      std::string t;\n      t.reserve(s.size());\n\n      for (const char c : s)\n      {\n        if (c == '\\'')\n          t.push_back(c);\n        t.push_back(c);\n      }\n\n      return t;\n    }\n\n    void connection::start_transaction(isolation_level level)\n    {\n      if (_transaction_active)\n      {\n        throw sqlpp::exception(\"Sqlite3 error: Cannot have more than one open transaction per connection\");\n      }\n\n      switch (level)\n      {\n        case sqlpp::isolation_level::serializable:\n        case sqlpp::isolation_level::repeatable_read:\n        case sqlpp::isolation_level::read_committed:\n          execute(\"pragma read_uncommitted = false;\");\n          break;\n        case sqlpp::isolation_level::read_uncommitted:\n          execute(\"pragma read_uncommitted = true;\");\n          break;\n        case sqlpp::isolation_level::undefined:\n          \/\/ do nothing here ...\n          break;\n      }\n\n      auto prepared = prepare_statement(*_handle, \"BEGIN\");\n      execute_statement(*_handle, prepared);\n      _transaction_active = true;\n    }\n\n    void connection::commit_transaction()\n    {\n      if (not _transaction_active)\n      {\n        throw sqlpp::exception(\"Sqlite3 error: Cannot commit a finished or failed transaction\");\n      }\n      _transaction_active = false;\n      auto prepared = prepare_statement(*_handle, \"COMMIT\");\n      execute_statement(*_handle, prepared);\n    }\n\n    void connection::rollback_transaction(bool report)\n    {\n      if (not _transaction_active)\n      {\n        throw sqlpp::exception(\"Sqlite3 error: Cannot rollback a finished or failed transaction\");\n      }\n      if (report)\n      {\n        std::cerr << \"Sqlite3 warning: Rolling back unfinished transaction\" << std::endl;\n      }\n      _transaction_active = false;\n      auto prepared = prepare_statement(*_handle, \"ROLLBACK\");\n      execute_statement(*_handle, prepared);\n    }\n\n    void connection::report_rollback_failure(const std::string message) noexcept\n    {\n      std::cerr << \"Sqlite3 message:\" << message << std::endl;\n    }\n\n    uint64_t connection::last_insert_id() noexcept\n    {\n      return sqlite3_last_insert_rowid(_handle->sqlite);\n    }\n\n    auto connection::attach(const connection_config& config, const std::string name) -> schema_t\n    {\n      auto prepared =\n          prepare_statement(*_handle, \"ATTACH '\" + escape(config.path_to_database) + \"' AS \" + escape(name));\n      execute_statement(*_handle, prepared);\n\n      return {name};\n    }\n  }\n}\n<|endoftext|>"}
{"text":"\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: dlgegif.cxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: hr $ $Date: 2006-06-19 21:40:46 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef GCC\n#pragma hdrstop\n#endif\n#include \n#include \n#include \n#include \"dlgegif.hxx\"\n#include \"dlgegif.hrc\"\n#include \"strings.hrc\"\n\n\/*************************************************************************\n|*\n|* Ctor\n|*\n\\************************************************************************\/\n\nDlgExportEGIF::DlgExportEGIF( FltCallDialogParameter& rPara ) :\n                ModalDialog         ( rPara.pWindow, ResId( DLG_EXPORT_GIF, rPara.pResMgr ) ),\n                rFltCallPara        ( rPara ),\n                aCbxInterlaced      ( this, ResId( CBX_INTERLACED ) ),\n                aCbxTranslucent     ( this, ResId( CBX_TRANSLUCENT ) ),\n                aGrpMode            ( this, ResId( GRP_MODE ) ),\n                aGrpDraw            ( this, ResId( GRP_DRAW ) ),\n                aBtnOK              ( this, ResId( BTN_OK ) ),\n                aBtnCancel          ( this, ResId( BTN_CANCEL ) ),\n                aBtnHelp            ( this, ResId( BTN_HELP ) ),\n                pMgr                ( rPara.pResMgr )\n{\n    FreeResource();\n\n    String  aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( \"Office.Common\/Filter\/Graphic\/Export\/GIF\" ) );\n    pConfigItem = new FilterConfigItem( aFilterConfigPath, &rPara.aFilterData );\n\n    String aInterlaceStr( ResId( KEY_INTER, pMgr ) );\n    String aTranslucentStr( ResId( KEY_TRANS, pMgr ) );\n    \/\/ Config-Parameter lesen\n    sal_Bool bInterlaced = pConfigItem->ReadInt32( aInterlaceStr, 1 ) != 0;\n    sal_Bool bTranslucent = pConfigItem->ReadInt32( aTranslucentStr, 1 ) != 0;\n\n    aCbxInterlaced.Check( bInterlaced );\n    aCbxTranslucent.Check( bTranslucent );\n\n    aBtnOK.SetClickHdl( LINK( this, DlgExportEGIF, OK ) );\n}\n\nDlgExportEGIF::~DlgExportEGIF()\n{\n    delete pConfigItem;\n}\n\n\/*************************************************************************\n|*\n|* Speichert eingestellte Werte in ini-Datei\n|*\n\\************************************************************************\/\n\nIMPL_LINK( DlgExportEGIF, OK, void *, EMPTYARG )\n{\n\n    \/\/ Config-Parameter schreiben\n    String aInterlaceStr( ResId( KEY_INTER, pMgr ) );\n    String aTranslucentStr( ResId( KEY_TRANS, pMgr ) );\n\n    sal_Int32 nValue = 0;\n    if ( aCbxInterlaced.IsChecked() )\n        nValue++;\n    pConfigItem->WriteInt32( aInterlaceStr, nValue );\n\n    nValue = 0;\n    if ( aCbxTranslucent.IsChecked() )\n        nValue++;\n    pConfigItem->WriteInt32( aTranslucentStr, nValue );\n    rFltCallPara.aFilterData = pConfigItem->GetFilterData();\n    EndDialog( RET_OK );\n\n    return 0;\n}\n\n\n\nINTEGRATION: CWS pchfix02 (1.6.28); FILE MERGED 2006\/09\/01 17:30:02 kaib 1.6.28.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: dlgegif.cxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-17 15:40:55 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_goodies.hxx\"\n#ifndef GCC\n#endif\n#include \n#include \n#include \n#include \"dlgegif.hxx\"\n#include \"dlgegif.hrc\"\n#include \"strings.hrc\"\n\n\/*************************************************************************\n|*\n|* Ctor\n|*\n\\************************************************************************\/\n\nDlgExportEGIF::DlgExportEGIF( FltCallDialogParameter& rPara ) :\n                ModalDialog         ( rPara.pWindow, ResId( DLG_EXPORT_GIF, rPara.pResMgr ) ),\n                rFltCallPara        ( rPara ),\n                aCbxInterlaced      ( this, ResId( CBX_INTERLACED ) ),\n                aCbxTranslucent     ( this, ResId( CBX_TRANSLUCENT ) ),\n                aGrpMode            ( this, ResId( GRP_MODE ) ),\n                aGrpDraw            ( this, ResId( GRP_DRAW ) ),\n                aBtnOK              ( this, ResId( BTN_OK ) ),\n                aBtnCancel          ( this, ResId( BTN_CANCEL ) ),\n                aBtnHelp            ( this, ResId( BTN_HELP ) ),\n                pMgr                ( rPara.pResMgr )\n{\n    FreeResource();\n\n    String  aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( \"Office.Common\/Filter\/Graphic\/Export\/GIF\" ) );\n    pConfigItem = new FilterConfigItem( aFilterConfigPath, &rPara.aFilterData );\n\n    String aInterlaceStr( ResId( KEY_INTER, pMgr ) );\n    String aTranslucentStr( ResId( KEY_TRANS, pMgr ) );\n    \/\/ Config-Parameter lesen\n    sal_Bool bInterlaced = pConfigItem->ReadInt32( aInterlaceStr, 1 ) != 0;\n    sal_Bool bTranslucent = pConfigItem->ReadInt32( aTranslucentStr, 1 ) != 0;\n\n    aCbxInterlaced.Check( bInterlaced );\n    aCbxTranslucent.Check( bTranslucent );\n\n    aBtnOK.SetClickHdl( LINK( this, DlgExportEGIF, OK ) );\n}\n\nDlgExportEGIF::~DlgExportEGIF()\n{\n    delete pConfigItem;\n}\n\n\/*************************************************************************\n|*\n|* Speichert eingestellte Werte in ini-Datei\n|*\n\\************************************************************************\/\n\nIMPL_LINK( DlgExportEGIF, OK, void *, EMPTYARG )\n{\n\n    \/\/ Config-Parameter schreiben\n    String aInterlaceStr( ResId( KEY_INTER, pMgr ) );\n    String aTranslucentStr( ResId( KEY_TRANS, pMgr ) );\n\n    sal_Int32 nValue = 0;\n    if ( aCbxInterlaced.IsChecked() )\n        nValue++;\n    pConfigItem->WriteInt32( aInterlaceStr, nValue );\n\n    nValue = 0;\n    if ( aCbxTranslucent.IsChecked() )\n        nValue++;\n    pConfigItem->WriteInt32( aTranslucentStr, nValue );\n    rFltCallPara.aFilterData = pConfigItem->GetFilterData();\n    EndDialog( RET_OK );\n\n    return 0;\n}\n\n\n\n<|endoftext|>"}
{"text":"#ifndef __FUTURE_HPP__\n#define __FUTURE_HPP__\n\n#include \"SoftXMT.hpp\"\n#include \"Delegate.hpp\"\n#include \"Cache.hpp\"\n\n\/\/TODO: special ArgsCache acquire, which\n\/\/uses args pointer field as a global address\n\/\/to the future and either\n\/\/1. flip the started bit\n\/\/2. or simply acquire RW instead of RO (and Cached not Incoherent)\n\n\/\/ idea: if we had a need for futures that\n\/\/ only mutate their arguments (essentially functional but could change the inputs as well)\n\/\/ then we could allow multiple copies of\n\/\/ the future to execute RW-shared mode, where only the first release writeback wins\n\n\n\/\/ TODO: do something like this to force users to have\n\/\/ the future fields but make them invisible\n\/*\nclass FutureArgs {\n    private:\n    GlobalAddress futurePtr;\n    void (* user_fn_p)(A *);\n};\nclass MyArgs : public FutureArgs {\n    int i;\n    int j;\n}\n\/\/ Additional possibility is method #2 above\n    *\/\n\n\ntemplate < typename ArgsStruct >\nclass Future {\n    private:\n        struct future_args {\n            GlobalAddress futureAddr;\n            void (* user_fn_p)(ArgsStruct *);\n            GlobalAddress< ArgsStruct > userArgs;\n\n            future_args( Future< ArgsStruct > * future, ArgsStruct * userArgs, void (* fn_p)(ArgsStruct *) )\n                : futureAddr( make_global( future ) )\n                , userArgs( make_global( userArgs ) )\n                , user_fn_p( fn_p ) \n            { }\n        };\n\n        struct future_done_args { \n            Future< ArgsStruct > * futurePtr;\n        };\n        \n        static void future_done_am( future_done_args * args, size_t args_size, void * payload, size_t payload_size ) {\n            args->futurePtr->done = true;\n            if ( args->futurePtr->waiter != NULL ) {\n                SoftXMT_wake( args->futurePtr->waiter );\n                args->futurePtr->waiter = NULL;\n            }\n        }\n\n        static void future_function( future_args * args ) {\n            \/\/ TODO test Global address calculations (so I can say address of 'started' instead)\n            if ( SoftXMT_delegate_fetch_and_add_word( args->futureAddr, 1 ) == 0 ) { \n                \n                \/\/ grab the user arguments\n                size_t args_size = sizeof(ArgsStruct);\n                ArgsStruct argsbuf;\n                typename Incoherent::RO cached_args( args->userArgs, args_size, &argsbuf );\n                cached_args.block_until_acquired();\n                \n                \/\/ call the user task\n                args->user_fn_p( &argsbuf );\n                cached_args.block_until_released();\n\n                \/\/ call wake up AM on Node that has the Future\n                future_done_args done_args = { args->futureAddr.pointer() };\n                SoftXMT_call_on( args->futureAddr.node(), &future_done_am, &done_args );\n            }\n        }\n    \n    public:\n        int64_t started;\/\/MUST be first (because address)\n        Thread * waiter;\n        bool done;\n        ArgsStruct * userArgs_lp;\n\n        future_args task_args;\n\n\n        \/\/ TODO: NOTE that this does not copy user arguments because we want to \n        \/\/ preserve the same semantics as normal tasks.\n        \/\/ --Unfortunately this means there are three communications to start\n        \/\/ 1) Task.execute fetches args\n        \/\/ 2) Future atomic started\n        \/\/ 3) Bring in user arguments and start\n        Future ( void (* fn_p)(ArgsStruct *), ArgsStruct * userArgs )\n            : started( 0 )\n              , waiter( NULL )\n              , done( false )\n              , userArgs_lp( userArgs )\n              , task_args( this, userArgs, fn_p ) { }\n\n        void touch( ) {\n            \/\/ start if not started\n            if ( SoftXMT_delegate_fetch_and_add_word( make_global(&started), 1 )==0 ) {\n                task_args.user_fn_p( userArgs_lp );\n                done = true;\n            } else  {\n                \/\/ otherwise block on done event\n                while ( !done ) {\n                    waiter = CURRENT_THREAD;\n                    SoftXMT_suspend( );\n                }\n            }\n        }\n\n        void asPublicTask( ) {\n            SoftXMT_publicTask( &future_function, &task_args );\n        }\n};\n\n#endif\nadd debug stuff to Future.hpp#ifndef __FUTURE_HPP__\n#define __FUTURE_HPP__\n\n#include \"SoftXMT.hpp\"\n#include \"Delegate.hpp\"\n#include \"Cache.hpp\"\n\n\/\/TODO: special ArgsCache acquire, which\n\/\/uses args pointer field as a global address\n\/\/to the future and either\n\/\/1. flip the started bit\n\/\/2. or simply acquire RW instead of RO (and Cached not Incoherent)\n\n\/\/ idea: if we had a need for futures that\n\/\/ only mutate their arguments (essentially functional but could change the inputs as well)\n\/\/ then we could allow multiple copies of\n\/\/ the future to execute RW-shared mode, where only the first release writeback wins\n\n\n\/\/ TODO: do something like this to force users to have\n\/\/ the future fields but make them invisible\n\/*\nclass FutureArgs {\n    private:\n    GlobalAddress futurePtr;\n    void (* user_fn_p)(A *);\n};\nclass MyArgs : public FutureArgs {\n    int i;\n    int j;\n}\n\/\/ Additional possibility is method #2 above\n    *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#if DEBUG\nstatic int64_t count_ = 0;\n#endif\n\ntemplate < typename ArgsStruct >\nclass Future {\n    private:\n        int64_t started;\n        Thread * waiter;\n        bool done;\n        ArgsStruct * userArgs_lp;\n        \n        struct future_args {\n            GlobalAddress futureAddr;\n            void (* user_fn_p)(ArgsStruct *);\n            GlobalAddress< ArgsStruct > userArgs;\n\n            future_args( Future< ArgsStruct > * future, ArgsStruct * userArgs, void (* fn_p)(ArgsStruct *) )\n                : futureAddr( make_global( future ) )\n                , userArgs( make_global( userArgs ) )\n                , user_fn_p( fn_p ) \n            { }\n        };\n        \n        future_args task_args;\n\n        struct future_done_args { \n            Future< ArgsStruct > * futurePtr;\n        };\n        \n        static void future_done_am( future_done_args * args, size_t args_size, void * payload, size_t payload_size ) {\n            args->futurePtr->done = true;\n            if ( args->futurePtr->waiter != NULL ) {\n                SoftXMT_wake( args->futurePtr->waiter );\n                args->futurePtr->waiter = NULL;\n            }\n        }\n\n        \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n        \/\/Custom delegate operation\n        \/\/TODO: use a generalized mechanism that abstracts all but function\n        \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n        struct started_memory_descriptor {\n            Thread * t;\n            GlobalAddress< Future > address;\n            int64_t data;\n            bool done;\n        };\n\n        struct started_reply_args {\n            GlobalAddress descriptor;\n        };\n\n        static void started_reply_am( started_reply_args * args, size_t size, void * payload, size_t payload_size ) {\n            assert( payload_size == sizeof(int64_t ) );\n            args->descriptor.pointer()->data = *(static_cast(payload));\n            args->descriptor.pointer()->done = true;\n            SoftXMT_wake( args->descriptor.pointer()->t );\n        }\n        \n        struct started_request_args {\n            GlobalAddress descriptor;\n            GlobalAddress< Future > address;\n        };\n\n        static void started_request_am( started_request_args * args, size_t size, void * payload, size_t payload_size ) {\n            Future< ArgsStruct > * fptr = args->address.pointer();\n\n            DVLOG(5) << \"dequeued request (node:\" << args->descriptor.node()\n                    << \"): future ptr:\" << (void*)fptr\n                    << \"(id:\"<id<<\")\";\n            int64_t data = fptr->started;\n            fptr->started = data + 1;\n            \n            \/\/ If future was already started in this case, it must have been started by touching thread.\n            \/\/ Incrementing started again will tell the touching thread it can deallocate the Future\n            if ( data > 0 ) {\n                if ( fptr->done ) { \/\/if it is done then toucher is waiting for the dequeue\n                    SoftXMT_wake( fptr->waiter );\n                    fptr->waiter = NULL;\n                }\n            }\n            \n            started_reply_args reply_args;\n            reply_args.descriptor = args->descriptor;\n            SoftXMT_call_on( args->descriptor.node(), &started_reply_am, \n                    &reply_args, sizeof(reply_args),\n                    &data, sizeof(data) );\n        }\n\n        static int64_t future_delegate_started( GlobalAddress< Future > address ) {\n            started_memory_descriptor md;\n            md.address = address;\n            md.data = 0;\n            md.done = false;\n            md.t = CURRENT_THREAD;\n            started_request_args args;\n            args.descriptor = make_global(&md);\n            args.address = address;\n            SoftXMT_call_on( address.node(), &started_request_am, &args );\n            while( !md.done ) {\n                SoftXMT_suspend();\n            }\n            return md.data;\n        }\n        \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n        static void future_function( future_args * args ) {\n            \/\/ TODO #1: the make_global is just calculating location of Future->started\n            \/\/if ( SoftXMT_delegate_fetch_and_add_word( make_global( args->startedAddr, args->futureAddr.node() ), 1 ) == 0 ) { \n            DVLOG(5) << CURRENT_THREAD->id << \"args(\"<<(void*)args<<\") will call started am \" << args->futureAddr.pointer();\n            if ( future_delegate_started( args->futureAddr ) == 0 ) {  \n                \/\/ grab the user arguments\n                size_t args_size = sizeof(ArgsStruct);\n                ArgsStruct argsbuf;\n                typename Incoherent::RO cached_args( args->userArgs, args_size, &argsbuf );\n                cached_args.block_until_acquired();\n                \n                \/\/ call the user task\n                args->user_fn_p( &argsbuf );\n                cached_args.block_until_released();\n\n                \/\/ call wake up AM on Node that has the Future\n                future_done_args done_args = { args->futureAddr.pointer() };\n                SoftXMT_call_on( args->futureAddr.node(), &future_done_am, &done_args );\n            } \n        }\n    \n    public:\n#if DEBUG\n        int64_t id;\n#endif\n\n\n        \/\/ TODO: NOTE that this does not copy user arguments because we want to \n        \/\/ preserve the same semantics as normal tasks.\n        \/\/ --Unfortunately this means there are three communications to start\n        \/\/ 1) Task.execute fetches args\n        \/\/ 2) Future atomic started\n        \/\/ 3) Bring in user arguments and start\n        Future ( void (* fn_p)(ArgsStruct *), ArgsStruct * userArgs )\n            : started( 0 )\n              , waiter( NULL )\n              , done( false )\n              , userArgs_lp( userArgs )\n#if DEBUG\n              , id( count_++ )\n#endif\n              , task_args( this, userArgs, fn_p ) { \n                  \n           DVLOG(5) << CURRENT_THREAD->id << \" creates Future:\"<< (void*)this << \" id:\"<< id << \" args:\"<< &task_args;\n        }\n\n        void touch( ) {\n            \/\/ start if not started\n            if ( SoftXMT_delegate_fetch_and_add_word( make_global(&started), 1 )==0 ) {\n                DVLOG(5) << CURRENT_THREAD->id << \" gets to touch-go \" << id;\n                task_args.user_fn_p( userArgs_lp );\n                done = true;\n                while ( started < 2 ) { \/\/ wait until dequeued\n                    DVLOG(5) << CURRENT_THREAD->id << \" has to wait on dequeue \" << id;\n                    waiter = CURRENT_THREAD;\n                    SoftXMT_suspend( );\n                    DVLOG(5) << CURRENT_THREAD->id << \" has woke on dequeue \" << id;\n                }\n            } else  {\n                \/\/ otherwise block on done event\n                while ( !done ) {\n                    waiter = CURRENT_THREAD;\n                    SoftXMT_suspend( );\n                }\n            }\n        }\n\n        void asPublicTask( ) {\n            SoftXMT_publicTask( &future_function, &task_args );\n        }\n};\n\n#endif\n<|endoftext|>"}
{"text":"\/* \r\n * File:   CGame.cpp\r\n * Author: yevgeniy.logachev\r\n *\/\r\n\r\n#include \"CGame.h\"\r\n#include \"IRenderView.h\"\r\n#include \"CSystem.h\"\r\n#include \"IScene.h\"\r\n#include \"CLoaderFile.h\"\r\n#include \"IEventDispatcher.hpp\"\r\n\r\n#include \"CRenderSystem.h\"\r\n#include \"CAnimation2DSystem.h\"\r\n#include \"CTransformationSystem.h\"\r\n#include \"CUpdateSystem.h\"\r\n#include \"CBatchingSystem.h\"\r\n#include \"IRenderTarget.h\"\r\n#include \"CThreadPool.h\"\r\n\r\nusing namespace jam;\r\n\r\n\/\/ *****************************************************************************\r\n\/\/ Constants\r\n\/\/ *****************************************************************************\r\n\r\n\r\n\/\/ *****************************************************************************\r\n\/\/ Public Methods\r\n\/\/ *****************************************************************************\r\n\r\nCGame::CGame(IRenderViewPtr render)\r\n    : m_IsInitialized(false)\r\n    , m_RenderView(render)\r\n{\r\n    CThreadPool::Get()->Initialize(5);\r\n    \r\n    CLoaderFile* loaderFile = new CLoaderFile();\r\n    loaderFile->RegisterFileSystem(CSystem::GetBundlePath() + \"media\/\");\r\n    loaderFile->RegisterFileSystem(CSystem::GetBundlePath());\r\n    \r\n    ILoader::RegisterDefaultLoader(loaderFile);\r\n}\r\n\r\nCGame::~CGame() \r\n{\r\n    CThreadPool::Get()->Shutdown();\r\n}\r\n\r\nvoid CGame::Initialize()\r\n{\r\n    m_RenderView->CreateView();\r\n    \r\n    CRenderSystemPtr renderSystem(new CRenderSystem(m_RenderView->Renderer()));\r\n    CAnimation2DSystemPtr animationSystem(new CAnimation2DSystem());\r\n    CTransfromationSystemPtr transformationSystem(new CTransfromationSystem());\r\n    CUpdateSystemPtr updateSystem(new CUpdateSystem());\r\n    CBatchingSystemPtr batchingSystem(new CBatchingSystem(m_RenderView->Renderer()));\r\n    AddSystem(updateSystem);\r\n    AddSystem(animationSystem);\r\n    AddSystem(batchingSystem);\r\n    AddSystem(transformationSystem);\r\n    AddSystem(renderSystem);\r\n    \r\n    m_IsInitialized = true;\r\n}\r\n\r\nvoid CGame::Shutdown()\r\n{\r\n    m_IsInitialized = false;\r\n}\r\n\r\nbool CGame::IsInitialized() const\r\n{\r\n    return m_IsInitialized;\r\n}\r\n\r\nIRenderViewPtr CGame::RenderView() const\r\n{\r\n    return m_RenderView;\r\n}\r\n\r\nvoid CGame::Update(unsigned long dt)\r\n{\r\n    if (!IsInitialized())\r\n    {\r\n        return;\r\n    }\r\n    \r\n    CThreadPool::Get()->Update(dt);\r\n    Dispatcher()->Update(dt);\r\n    \r\n    if (!m_Scenes.empty())\r\n    {\r\n        IScenePtr scene = m_Scenes.top();\r\n        scene->Update(dt);\r\n    }\r\n    \r\n    std::for_each(m_System.begin(), m_System.end(), [dt](const TSystemMap::value_type& system)\r\n    {\r\n        system.second->Update(dt);\r\n    });\r\n}\r\n\r\nvoid CGame::Draw()\r\n{\r\n    CRenderSystemPtr renderSystem = nullptr;\r\n    std::type_index key = SystemId();\r\n    TSystemMap::const_iterator it = m_System.find(key);\r\n    if (it != m_System.end())\r\n    {\r\n        renderSystem = std::static_pointer_cast(it->second);\r\n    }\r\n\r\n    if (renderSystem && !m_Scenes.empty())\r\n    {\r\n        IScenePtr scene = m_Scenes.top();\r\n        \r\n        m_RenderView->Begin();\r\n        const IScene::TCamerasList& cameras = scene->Cameras();\r\n        std::for_each(cameras.begin(), cameras.end(), [&](ICameraPtr camera)\r\n        {\r\n            renderSystem->Draw(camera);\r\n        });\r\n        m_RenderView->End();\r\n    }\r\n}\r\n\r\nvoid CGame::PushScene(IScenePtr scene)\r\n{\r\n    assert(scene);\r\n    if (!m_Scenes.empty())\r\n    {\r\n        m_Scenes.top()->Pause();\r\n    }\r\n    \r\n    m_Scenes.push(scene);\r\n    m_Scenes.top()->Start();\r\n}\r\n\r\nvoid CGame::PopScene()\r\n{\r\n    assert(!m_Scenes.empty());\r\n    if (!m_Scenes.empty())\r\n    {\r\n        m_Scenes.top()->Stop();\r\n        m_Scenes.pop();\r\n    }\r\n}\r\n\r\nIScenePtr CGame::GetScene() const\r\n{\r\n    if (!m_Scenes.empty())\r\n    {\r\n        return m_Scenes.top();\r\n    }\r\n    \r\n    return nullptr;\r\n}\r\n\r\nvoid CGame::AddSystem(ISystemPtr system)\r\n{\r\n    ISystem& s = *system.get();\r\n    std::type_index key = std::type_index(typeid(s));\r\n    m_System[key] = system;\r\n}\r\n\r\nvoid CGame::RemoveSystem(ISystemPtr system)\r\n{\r\n    ISystem& s = *system.get();\r\n    std::type_index key = std::type_index(typeid(s));\r\n    TSystemMap::const_iterator it = m_System.find(key);\r\n    if (it != m_System.end())\r\n    {\r\n        m_System.erase(it);\r\n    }\r\n}\r\n\r\nISystemPtr CGame::GetSystem(const std::type_index& systemKey)\r\n{\r\n    TSystemMap::const_iterator it = m_System.find(systemKey);\r\n    if (it != m_System.end())\r\n    {\r\n        return it->second;\r\n    }\r\n    \r\n    return nullptr;\r\n}\r\n\r\nCRenderSystemPtr CGame::RenderSystem() const\r\n{\r\n    return m_RenderSystem;\r\n}\r\n\r\n\/\/ *****************************************************************************\r\n\/\/ Protected Methods\r\n\/\/ *****************************************************************************\r\n\r\n\/\/ *****************************************************************************\r\n\/\/ Private Methods\r\n\/\/ *****************************************************************************\r\n\r\nStore render system in CGame\/* \r\n * File:   CGame.cpp\r\n * Author: yevgeniy.logachev\r\n *\/\r\n\r\n#include \"CGame.h\"\r\n#include \"IRenderView.h\"\r\n#include \"CSystem.h\"\r\n#include \"IScene.h\"\r\n#include \"CLoaderFile.h\"\r\n#include \"IEventDispatcher.hpp\"\r\n\r\n#include \"CRenderSystem.h\"\r\n#include \"CAnimation2DSystem.h\"\r\n#include \"CTransformationSystem.h\"\r\n#include \"CUpdateSystem.h\"\r\n#include \"CBatchingSystem.h\"\r\n#include \"IRenderTarget.h\"\r\n#include \"CThreadPool.h\"\r\n\r\nusing namespace jam;\r\n\r\n\/\/ *****************************************************************************\r\n\/\/ Constants\r\n\/\/ *****************************************************************************\r\n\r\n\r\n\/\/ *****************************************************************************\r\n\/\/ Public Methods\r\n\/\/ *****************************************************************************\r\n\r\nCGame::CGame(IRenderViewPtr render)\r\n    : m_IsInitialized(false)\r\n    , m_RenderView(render)\r\n{\r\n    CThreadPool::Get()->Initialize(5);\r\n    \r\n    CLoaderFile* loaderFile = new CLoaderFile();\r\n    loaderFile->RegisterFileSystem(CSystem::GetBundlePath() + \"media\/\");\r\n    loaderFile->RegisterFileSystem(CSystem::GetBundlePath());\r\n    \r\n    ILoader::RegisterDefaultLoader(loaderFile);\r\n}\r\n\r\nCGame::~CGame() \r\n{\r\n    CThreadPool::Get()->Shutdown();\r\n}\r\n\r\nvoid CGame::Initialize()\r\n{\r\n    m_RenderView->CreateView();\r\n    \r\n    m_RenderSystem.reset(new CRenderSystem(m_RenderView->Renderer()));\r\n    CAnimation2DSystemPtr animationSystem(new CAnimation2DSystem());\r\n    CTransfromationSystemPtr transformationSystem(new CTransfromationSystem());\r\n    CUpdateSystemPtr updateSystem(new CUpdateSystem());\r\n    CBatchingSystemPtr batchingSystem(new CBatchingSystem(m_RenderView->Renderer()));\r\n    AddSystem(updateSystem);\r\n    AddSystem(animationSystem);\r\n    AddSystem(batchingSystem);\r\n    AddSystem(transformationSystem);\r\n    AddSystem(m_RenderSystem);\r\n    \r\n    m_IsInitialized = true;\r\n}\r\n\r\nvoid CGame::Shutdown()\r\n{\r\n    m_IsInitialized = false;\r\n}\r\n\r\nbool CGame::IsInitialized() const\r\n{\r\n    return m_IsInitialized;\r\n}\r\n\r\nIRenderViewPtr CGame::RenderView() const\r\n{\r\n    return m_RenderView;\r\n}\r\n\r\nvoid CGame::Update(unsigned long dt)\r\n{\r\n    if (!IsInitialized())\r\n    {\r\n        return;\r\n    }\r\n    \r\n    CThreadPool::Get()->Update(dt);\r\n    Dispatcher()->Update(dt);\r\n    \r\n    if (!m_Scenes.empty())\r\n    {\r\n        IScenePtr scene = m_Scenes.top();\r\n        scene->Update(dt);\r\n    }\r\n    \r\n    std::for_each(m_System.begin(), m_System.end(), [dt](const TSystemMap::value_type& system)\r\n    {\r\n        system.second->Update(dt);\r\n    });\r\n}\r\n\r\nvoid CGame::Draw()\r\n{\r\n    CRenderSystemPtr renderSystem = RenderSystem();\r\n    \/*std::type_index key = SystemId();\r\n    TSystemMap::const_iterator it = m_System.find(key);\r\n    if (it != m_System.end())\r\n    {\r\n        renderSystem = std::static_pointer_cast(it->second);\r\n    }*\/\r\n\r\n    if (renderSystem && !m_Scenes.empty())\r\n    {\r\n        IScenePtr scene = m_Scenes.top();\r\n        \r\n        m_RenderView->Begin();\r\n        const IScene::TCamerasList& cameras = scene->Cameras();\r\n        std::for_each(cameras.begin(), cameras.end(), [&](ICameraPtr camera)\r\n        {\r\n            renderSystem->Draw(camera);\r\n        });\r\n        m_RenderView->End();\r\n    }\r\n}\r\n\r\nvoid CGame::PushScene(IScenePtr scene)\r\n{\r\n    assert(scene);\r\n    if (!m_Scenes.empty())\r\n    {\r\n        m_Scenes.top()->Pause();\r\n    }\r\n    \r\n    m_Scenes.push(scene);\r\n    m_Scenes.top()->Start();\r\n}\r\n\r\nvoid CGame::PopScene()\r\n{\r\n    assert(!m_Scenes.empty());\r\n    if (!m_Scenes.empty())\r\n    {\r\n        m_Scenes.top()->Stop();\r\n        m_Scenes.pop();\r\n    }\r\n}\r\n\r\nIScenePtr CGame::GetScene() const\r\n{\r\n    if (!m_Scenes.empty())\r\n    {\r\n        return m_Scenes.top();\r\n    }\r\n    \r\n    return nullptr;\r\n}\r\n\r\nvoid CGame::AddSystem(ISystemPtr system)\r\n{\r\n    ISystem& s = *system.get();\r\n    std::type_index key = std::type_index(typeid(s));\r\n    m_System[key] = system;\r\n}\r\n\r\nvoid CGame::RemoveSystem(ISystemPtr system)\r\n{\r\n    ISystem& s = *system.get();\r\n    std::type_index key = std::type_index(typeid(s));\r\n    TSystemMap::const_iterator it = m_System.find(key);\r\n    if (it != m_System.end())\r\n    {\r\n        m_System.erase(it);\r\n    }\r\n}\r\n\r\nISystemPtr CGame::GetSystem(const std::type_index& systemKey)\r\n{\r\n    TSystemMap::const_iterator it = m_System.find(systemKey);\r\n    if (it != m_System.end())\r\n    {\r\n        return it->second;\r\n    }\r\n    \r\n    return nullptr;\r\n}\r\n\r\nCRenderSystemPtr CGame::RenderSystem() const\r\n{\r\n    return m_RenderSystem;\r\n}\r\n\r\n\/\/ *****************************************************************************\r\n\/\/ Protected Methods\r\n\/\/ *****************************************************************************\r\n\r\n\/\/ *****************************************************************************\r\n\/\/ Private Methods\r\n\/\/ *****************************************************************************\r\n\r\n<|endoftext|>"}
{"text":"#include \r\n#include \r\nusing std::vector;\r\n#include \r\nusing std::string;\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#ifdef USE_GTEST\r\n#include \r\n#endif\r\n\r\nstruct ListNode\r\n{\r\n    int val;\r\n    ListNode *next;\r\n    ListNode(int x)\r\n        : val(x), next(NULL)\r\n    {\r\n    }\r\n};\r\ninline ListNode *create_list(vector &nums)\r\n{\r\n    ListNode *res = NULL;\r\n    ListNode *&node = res;\r\n    for (int num : nums)\r\n    {\r\n        node = new ListNode(num);\r\n        node = node->next;\r\n    }\r\n\r\n    return res;\r\n}\r\ninline void free_list(ListNode *l)\r\n{\r\n    while (l != NULL)\r\n    {\r\n        ListNode *tmp = l;\r\n        l = l->next;\r\n        delete tmp;\r\n    }\r\n}\r\nstruct TreeNode\r\n{\r\n    int val;\r\n    TreeNode *left;\r\n    TreeNode *right;\r\n    TreeNode(int x)\r\n        : val(x), left(NULL), right(NULL)\r\n    {\r\n    }\r\n    ~TreeNode()\r\n    {\r\n        if (left != NULL)\r\n        {\r\n            delete left;\r\n            left = NULL;\r\n        }\r\n        if (right != NULL)\r\n        {\r\n            delete right;\r\n            right = NULL;\r\n        }\r\n    }\r\n};update test#include \r\n#include \r\nusing std::vector;\r\n#include \r\nusing std::string;\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#ifdef USE_GTEST\r\n#include \r\n#endif\r\n\r\nstruct ListNode\r\n{\r\n    int val;\r\n    ListNode *next;\r\n    ListNode(int x)\r\n        : val(x), next(NULL)\r\n    {\r\n    }\r\n};\r\n\/\/这里参数不用引用是纯粹为了偷懒,因为gcc不能引用临时对象\r\ninline ListNode *create_list(vector nums)\r\n{\r\n    ListNode *res = NULL;\r\n    ListNode *&node = res;\r\n    for (int num : nums)\r\n    {\r\n        node = new ListNode(num);\r\n        node = node->next;\r\n    }\r\n\r\n    return res;\r\n}\r\ninline void free_list(ListNode *l)\r\n{\r\n    while (l != NULL)\r\n    {\r\n        ListNode *tmp = l;\r\n        l = l->next;\r\n        delete tmp;\r\n    }\r\n}\r\nstruct TreeNode\r\n{\r\n    int val;\r\n    TreeNode *left;\r\n    TreeNode *right;\r\n    TreeNode(int x)\r\n        : val(x), left(NULL), right(NULL)\r\n    {\r\n    }\r\n    ~TreeNode()\r\n    {\r\n        if (left != NULL)\r\n        {\r\n            delete left;\r\n            left = NULL;\r\n        }\r\n        if (right != NULL)\r\n        {\r\n            delete right;\r\n            right = NULL;\r\n        }\r\n    }\r\n};<|endoftext|>"}
{"text":"\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: bparr.hxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: hr $ $Date: 2006-08-14 15:17:05 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _BPARR_HXX\n#define _BPARR_HXX\n\n#ifndef _SOLAR_H\n#include \n#endif\n#ifndef _DEBUG_HXX \/\/autogen\n#include \n#endif\n\nstruct BlockInfo;\nclass BigPtrArray;\n\nclass BigPtrEntry\n{\n    friend class BigPtrArray;\n    BlockInfo* pBlock;\n    USHORT nOffset;\npublic:\n    virtual ~BigPtrEntry() {}\nprotected:\n    BigPtrEntry() : pBlock(0), nOffset(0) {}\n\n    inline ULONG GetPos() const;\n    inline BigPtrArray& GetArray() const;\n};\ntypedef BigPtrEntry* ElementPtr;\n\n\ntypedef BOOL (*FnForEach)( const ElementPtr&, void* pArgs );\n\n\/\/ 1000 Eintrge pro Block = etwas weniger als 4K\n#define MAXENTRY 1000\n\n\n\/\/ Anzahl Eintraege, die bei der Kompression frei bleiben duerfen\n\/\/ dieser Wert ist fuer den Worst Case, da wir MAXBLOCK mit ca 25%\n\/\/ Overhead definiert haben, reichen 80% = 800 Eintraege vollkommen aus\n\/\/ Will mann voellige Kompression haben, muss eben 100 angegeben werden.\n\n#define COMPRESSLVL 80\n\nstruct BlockInfo {                  \/\/ Block-Info:\n    BigPtrArray* pBigArr;           \/\/ in diesem Array steht der Block\n    ElementPtr* pData;              \/\/ Datenblock\n    ULONG nStart, nEnd;             \/\/ Start- und EndIndex\n    USHORT nElem;                   \/\/ Anzahl Elemente\n};\n\nclass BigPtrArray\n{\n    BlockInfo** ppInf;              \/\/ Block-Infos\n    ULONG       nSize;              \/\/ Anzahl Elemente\n    USHORT      nMaxBlock;          \/\/ akt. max Anzahl Bloecke\n    USHORT      nBlock;             \/\/ Anzahl Bloecke\n    USHORT      nCur;               \/\/ letzter Block\n\n    USHORT      Index2Block( ULONG ) const; \/\/ Blocksuche\n    BlockInfo*  InsBlock( USHORT );         \/\/ Block einfuegen\n    void        BlockDel( USHORT );         \/\/ es wurden Bloecke geloescht\n    void        UpdIndex( USHORT );         \/\/ Indexe neu berechnen\n\nprotected:\n    \/\/ fuelle alle Bloecke auf.\n    \/\/ Der short gibt in Prozent an, wie voll die Bloecke werden sollen.\n    \/\/ Der ReturnWert besagt, das irgendetwas \"getan\" wurde\n    USHORT Compress( short = COMPRESSLVL );\n\npublic:\n    BigPtrArray();\n    ~BigPtrArray();\n\n    ULONG Count() const { return nSize; }\n\n    void Insert( const ElementPtr& r, ULONG pos );\n    void Remove( ULONG pos, ULONG n = 1 );\n    void Move( ULONG from, ULONG to );\n    void Replace( ULONG pos, const ElementPtr& r);\n\n    ElementPtr operator[]( ULONG ) const;\n    void ForEach( FnForEach fn, void* pArgs = NULL )\n    {\n        ForEach( 0, nSize, fn, pArgs );\n    }\n    void ForEach( ULONG nStart, ULONG nEnd, FnForEach fn, void* pArgs = NULL );\n};\n\n\n\ninline ULONG BigPtrEntry::GetPos() const\n{\n    DBG_ASSERT( this == pBlock->pData[ nOffset ], \"Element nicht im Block\" );\n    return pBlock->nStart + nOffset;\n}\n\ninline BigPtrArray& BigPtrEntry::GetArray() const\n{\n    return *pBlock->pBigArr;\n}\n\n\n#endif\nINTEGRATION: CWS changefileheader (1.4.738); FILE MERGED 2008\/04\/01 15:56:06 thb 1.4.738.2: #i85898# Stripping all external header guards 2008\/03\/31 16:52:34 rt 1.4.738.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: bparr.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _BPARR_HXX\n#define _BPARR_HXX\n\n#include \n#include \n\nstruct BlockInfo;\nclass BigPtrArray;\n\nclass BigPtrEntry\n{\n    friend class BigPtrArray;\n    BlockInfo* pBlock;\n    USHORT nOffset;\npublic:\n    virtual ~BigPtrEntry() {}\nprotected:\n    BigPtrEntry() : pBlock(0), nOffset(0) {}\n\n    inline ULONG GetPos() const;\n    inline BigPtrArray& GetArray() const;\n};\ntypedef BigPtrEntry* ElementPtr;\n\n\ntypedef BOOL (*FnForEach)( const ElementPtr&, void* pArgs );\n\n\/\/ 1000 Eintrge pro Block = etwas weniger als 4K\n#define MAXENTRY 1000\n\n\n\/\/ Anzahl Eintraege, die bei der Kompression frei bleiben duerfen\n\/\/ dieser Wert ist fuer den Worst Case, da wir MAXBLOCK mit ca 25%\n\/\/ Overhead definiert haben, reichen 80% = 800 Eintraege vollkommen aus\n\/\/ Will mann voellige Kompression haben, muss eben 100 angegeben werden.\n\n#define COMPRESSLVL 80\n\nstruct BlockInfo {                  \/\/ Block-Info:\n    BigPtrArray* pBigArr;           \/\/ in diesem Array steht der Block\n    ElementPtr* pData;              \/\/ Datenblock\n    ULONG nStart, nEnd;             \/\/ Start- und EndIndex\n    USHORT nElem;                   \/\/ Anzahl Elemente\n};\n\nclass BigPtrArray\n{\n    BlockInfo** ppInf;              \/\/ Block-Infos\n    ULONG       nSize;              \/\/ Anzahl Elemente\n    USHORT      nMaxBlock;          \/\/ akt. max Anzahl Bloecke\n    USHORT      nBlock;             \/\/ Anzahl Bloecke\n    USHORT      nCur;               \/\/ letzter Block\n\n    USHORT      Index2Block( ULONG ) const; \/\/ Blocksuche\n    BlockInfo*  InsBlock( USHORT );         \/\/ Block einfuegen\n    void        BlockDel( USHORT );         \/\/ es wurden Bloecke geloescht\n    void        UpdIndex( USHORT );         \/\/ Indexe neu berechnen\n\nprotected:\n    \/\/ fuelle alle Bloecke auf.\n    \/\/ Der short gibt in Prozent an, wie voll die Bloecke werden sollen.\n    \/\/ Der ReturnWert besagt, das irgendetwas \"getan\" wurde\n    USHORT Compress( short = COMPRESSLVL );\n\npublic:\n    BigPtrArray();\n    ~BigPtrArray();\n\n    ULONG Count() const { return nSize; }\n\n    void Insert( const ElementPtr& r, ULONG pos );\n    void Remove( ULONG pos, ULONG n = 1 );\n    void Move( ULONG from, ULONG to );\n    void Replace( ULONG pos, const ElementPtr& r);\n\n    ElementPtr operator[]( ULONG ) const;\n    void ForEach( FnForEach fn, void* pArgs = NULL )\n    {\n        ForEach( 0, nSize, fn, pArgs );\n    }\n    void ForEach( ULONG nStart, ULONG nEnd, FnForEach fn, void* pArgs = NULL );\n};\n\n\n\ninline ULONG BigPtrEntry::GetPos() const\n{\n    DBG_ASSERT( this == pBlock->pData[ nOffset ], \"Element nicht im Block\" );\n    return pBlock->nStart + nOffset;\n}\n\ninline BigPtrArray& BigPtrEntry::GetArray() const\n{\n    return *pBlock->pBigArr;\n}\n\n\n#endif\n<|endoftext|>"}
{"text":"\/*************************************************************************\n *\n *  $RCSfile: docsh.hxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: os $ $Date: 2001-02-12 11:27:26 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SWDOCSH_HXX\n#define _SWDOCSH_HXX\n\n#ifndef _TIMER_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFX_OBJFAC_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFX_INTERNO_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFX_OBJSH_HXX \/\/autogen\n#include \n#endif\n#ifndef SW_SWDLL_HXX\n#include \n#endif\n#ifndef _SHELLID_HXX\n#include \n#endif\n\nclass   SwDoc;\nclass   Sw3Io;\nclass   SfxDocumentInfoDialog;\nclass   SfxStyleSheetBasePool;\nclass   FontList;\nclass   SwView;\nclass   SwWrtShell;\nclass   SwFEShell;\nclass   Reader;\nclass   SwReader;\nclass   SwCrsrShell;\nclass   SwSrcView;\nclass   SfxFileDialog;\nclass   PushButton;\nclass   FixedText;\nclass   SwPaM;\nclass   SwgReaderOption;\n\nclass SwDocShell: public SfxObjectShell, public SfxInPlaceObject,\n                  public SfxListener\n{\n    SwDoc*                  pDoc;           \/\/ Document\n    Sw3Io*                  pIo;            \/\/ Reader \/ Writer\n    SfxStyleSheetBasePool*  pBasePool;      \/\/ Durchreiche fuer Formate\n    FontList*               pFontList;      \/\/ aktuelle FontListe\n\n    \/\/ Nix geht ohne die WrtShell (historische Gruende)\n    \/\/ RuekwaertsPointer auf die View (historische Gruende)\n    \/\/ Dieser gilt solange bis im Activate ein neuer gesetzt wird\n    \/\/ oder dieser im Dtor der View geloescht wird\n    \/\/\n    SwView*                 pView;\n    SwWrtShell*             pWrtShell;\n\n    Timer                   aFinishedTimer; \/\/ Timer fuers ueberpriefen der\n                                            \/\/ Grafik-Links. Sind alle da,\n                                            \/\/ dann ist Doc voll. geladen\n\n    SvPersistRef            xOLEChildList;  \/\/ fuers RemoveOLEObjects\n\n    \/\/ Methoden fuer den Zugriff aufs Doc\n    void                    AddLink();\n    void                    RemoveLink();\n\n    \/\/ Hint abfangen fuer DocInfo\n    virtual void            Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n    \/\/ FileIO\n    virtual BOOL            InitNew(SvStorage* pNewStor);\n    virtual BOOL            Load(SvStorage* pStor);\n    virtual BOOL            LoadFrom(SvStorage* pStor);\n    virtual BOOL            ConvertFrom( SfxMedium &rMedium );\n    virtual void            HandsOff();\n    virtual BOOL            SaveAs(SvStorage * pNewStor );\n    virtual BOOL            ConvertTo(SfxMedium &rMedium );\n    virtual BOOL            SaveCompleted(SvStorage * pNewStor );\n    virtual USHORT          PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE );\n\n    \/\/ DocInfo dem Doc melden\n    \/\/\n    virtual SfxDocumentInfoDialog* CreateDocumentInfoDialog(\n                                    Window *pParent, const SfxItemSet &);\n    \/\/ Template-Btn\n    Window*                 AddTemplateBtn(SfxFileDialog* pFileDlg);\n\n    \/\/ OLE-Geraffel\n    virtual void            Draw( OutputDevice*, const JobSetup&, USHORT);\n\n    \/\/ Methoden fuer StyleSheets\n    USHORT                  Edit( const String &rName, const String& rParent, USHORT nFamily,\n                                    USHORT nMask, BOOL bNew,\n                                    BOOL bColumn = FALSE,\n                                    SwWrtShell* pActShell = 0,\n                                    BOOL bBasic = FALSE );\n    USHORT                  Delete(const String &rName, USHORT nFamily);\n    USHORT                  ApplyStyles(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0,\n                                        USHORT nMode = 0 );\n    USHORT                  DoWaterCan( const String &rName, USHORT nFamily);\n    USHORT                  UpdateStyle(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0);\n    USHORT                  MakeByExample(const String &rName,\n                                            USHORT nFamily, USHORT nMask, SwWrtShell* pShell = 0);\n\n    void                    InitDraw();\n    void                    SubInitNew();   \/\/ fuer InitNew und HtmlSourceModus\n    inline void             SetWrtShell(SwWrtShell* pShell)\n                                { pWrtShell = pShell; }\n\n    void                    RemoveOLEObjects();\n\n    DECL_STATIC_LINK( SwDocShell, IsLoadFinished, void* );\n    DECL_LINK( SelTemplateHdl, PushButton * );\n\npublic:\n\n    \/\/ aber selbst implementieren\n    SFX_DECL_INTERFACE(SW_DOCSHELL);\n    SFX_DECL_OBJECTFACTORY_DLL(SwDocShell, SW_DLL());\n    TYPEINFO();\n\n    static SfxInterface *_GetInterface() { return _GetInterfaceImpl(); }\n\n    \/\/Das Doc wird fuer SO-Datenaustausch benoetigt!\n    SwDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);\n    SwDocShell( SwDoc *pDoc, SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD );\n    ~SwDocShell();\n\n    \/\/ OLE 2.0-Benachrichtigung\n    DECL_LINK( Ole2ModifiedHdl, void * );\n\n    \/\/ OLE-Geraffel\n    virtual void      SetVisArea( const Rectangle &rRect );\n    virtual Rectangle GetVisArea( USHORT nAspect ) const;\n    virtual Printer  *GetDocumentPrinter();\n    virtual void      OnDocumentPrinterChanged( Printer * pNewPrinter );\n    virtual ULONG     GetMiscStatus() const;\n\n    virtual void            PrepareReload();\n    virtual void            SetModified( BOOL = TRUE );\n\n    \/\/ Dispatcher\n    void                    Execute(SfxRequest &);\n    void                    ExecStyleSheet(SfxRequest&);\n    void                    ExecDB(SfxRequest&);\n\n    void                    GetState(SfxItemSet &);\n    void                    StateAlways(SfxItemSet &);\n    void                    StateStyleSheet(SfxItemSet&, SwWrtShell* pSh = 0 );\n\n    \/\/ Doc rausreichen aber VORSICHT\n    inline SwDoc*           GetDoc() { return pDoc; }\n    void                    UpdateFontList();\n    void                    UpdateChildWindows();\n\n    \/\/ DocumentInfo neu setzen\n    BOOL                    SetDocumentInfo(const SfxDocumentInfo& rInfo);\n\n    \/\/ globaler IO\n    virtual BOOL            Save();\n    inline BOOL                 SaveAsChilds( SvStorage *pStor );\n\n    \/\/ fuer VorlagenPI\n    virtual SfxStyleSheetBasePool*  GetStyleSheetPool();\n\n    \/\/ Fuer Organizer\n    virtual BOOL Insert(SfxObjectShell &rSource,\n                        USHORT  nSourceIdx1,\n                        USHORT  nSourceIdx2,\n                        USHORT  nSourceIdx3,\n                        USHORT& nIdx1,\n                        USHORT& nIdx2,\n                        USHORT& nIdx3,\n                        USHORT& nRemovedIdx);\n\n    virtual BOOL Remove(USHORT nIdx1,\n                        USHORT nIdx2 = INDEX_IGNORE,\n                        USHORT nIdx3 = INDEX_IGNORE);\n\n    virtual Bitmap      GetStyleFamilyBitmap( SfxStyleFamily eFamily );\n\n    \/\/ View setzen fuer Aktionen ueber Shell\n    void          SetView(SwView* pVw);\n    const SwView *GetView() const { return pView; }\n\n    \/\/ Zugriff auf die zur SwView gehoerige SwWrtShell\n          SwWrtShell *GetWrtShell()       { return pWrtShell; }\n    const SwWrtShell *GetWrtShell() const { return pWrtShell; }\n\n    \/\/ fuer die Core - die kennt die DocShell aber keine WrtShell!\n          SwFEShell *GetFEShell();\n    const SwFEShell *GetFEShell() const\n                { return ((SwDocShell*)this)->GetFEShell(); }\n\n\n    \/\/ Fuer Einfuegen Dokument\n    Reader* StartConvertFrom(SfxMedium& rMedium, SwReader** ppRdr,\n                            SwCrsrShell* pCrsrSh = 0, SwPaM* pPaM = 0);\n\n    \/\/ Anforderung der pIo-Struktur fuer den Zugriff auf Substorages\n    \/\/ und Streams\n    Sw3Io* GetIoSystem() { return pIo; }\n\n    virtual long DdeGetData( const String& rItem, SvData& rData );\n    virtual long DdeSetData( const String& rItem, const SvData& rData );\n    virtual SvPseudoObject* DdeCreateHotLink( const String& rItem );\n    virtual void        FillClass( SvGlobalName * pClassName,\n                                   ULONG * pClipFormat,\n                                   String * pAppName,\n                                   String * pLongUserName,\n                                   String * pUserName,\n                                   long nVersion = SOFFICE_FILEFORMAT_NOW ) const;\n    virtual void    FillRegInfo( SvEmbeddedRegistryInfo * );\n\n    virtual SvDataMemberObjectRef CreateSnapshot();\n\n    virtual void LoadStyles( SfxObjectShell& rSource );\n\n    \/\/ Seitenvorlagedialog anzeigen, ggf. auf Spaltenpage\n    void    FormatPage( const String& rPage,\n                        BOOL bColumn = FALSE,\n                        SwWrtShell*     pActShell = 0 );\n\n    \/\/ Timer starten fuers ueberpruefen der Grafik-Links. Sind alle\n    \/\/ vollstaendig geladen, dann ist das Doc fertig\n    void StartLoadFinishedTimer();\n\n    \/\/ eine Uebertragung wird abgebrochen (wird aus dem SFX gerufen)\n    virtual void CancelTransfers();\n\n    \/\/ Doc aus Html-Source neu laden\n    void    ReloadFromHtml( const String& rStreamName, SwSrcView* pSrcView );\n\n    \/\/ embedded alle lokalen Links (Bereiche\/Grafiken)\n    BOOL EmbedAllLinks();\n\n    \/\/Activate wait cursor for all windows of this document\n    \/\/Optionally all dispatcher could be Locked\n    \/\/Usually locking should be done using the class: SwWaitObject!\n    void EnterWait( BOOL bLockDispatcher );\n    void LeaveWait( BOOL bLockDispatcher );\n\n    void ToggleBrowserMode(BOOL bOn, SwView* pView = 0);\n\n    ULONG LoadStylesFromFile( const String& rURL, SwgReaderOption& rOpt,\n                                BOOL bUnoCall );\n    void InvalidateModel();\n    void ReactivateModel();\n\n#if SUPD>620\n    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >  GetEventNames();\n#endif\n};\n\ninline BOOL SwDocShell::SaveAsChilds( SvStorage *pStor )\n{\n    return SfxInPlaceObject::SaveAsChilds( pStor );\n}\n#endif\nFILEFORMAT_CURRENT\/*************************************************************************\n *\n *  $RCSfile: docsh.hxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: os $ $Date: 2001-02-13 14:58:22 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SWDOCSH_HXX\n#define _SWDOCSH_HXX\n\n#ifndef _TIMER_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFX_OBJFAC_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFX_INTERNO_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFX_OBJSH_HXX \/\/autogen\n#include \n#endif\n#ifndef SW_SWDLL_HXX\n#include \n#endif\n#ifndef _SHELLID_HXX\n#include \n#endif\n\nclass   SwDoc;\nclass   Sw3Io;\nclass   SfxDocumentInfoDialog;\nclass   SfxStyleSheetBasePool;\nclass   FontList;\nclass   SwView;\nclass   SwWrtShell;\nclass   SwFEShell;\nclass   Reader;\nclass   SwReader;\nclass   SwCrsrShell;\nclass   SwSrcView;\nclass   SfxFileDialog;\nclass   PushButton;\nclass   FixedText;\nclass   SwPaM;\nclass   SwgReaderOption;\n\nclass SwDocShell: public SfxObjectShell, public SfxInPlaceObject,\n                  public SfxListener\n{\n    SwDoc*                  pDoc;           \/\/ Document\n    Sw3Io*                  pIo;            \/\/ Reader \/ Writer\n    SfxStyleSheetBasePool*  pBasePool;      \/\/ Durchreiche fuer Formate\n    FontList*               pFontList;      \/\/ aktuelle FontListe\n\n    \/\/ Nix geht ohne die WrtShell (historische Gruende)\n    \/\/ RuekwaertsPointer auf die View (historische Gruende)\n    \/\/ Dieser gilt solange bis im Activate ein neuer gesetzt wird\n    \/\/ oder dieser im Dtor der View geloescht wird\n    \/\/\n    SwView*                 pView;\n    SwWrtShell*             pWrtShell;\n\n    Timer                   aFinishedTimer; \/\/ Timer fuers ueberpriefen der\n                                            \/\/ Grafik-Links. Sind alle da,\n                                            \/\/ dann ist Doc voll. geladen\n\n    SvPersistRef            xOLEChildList;  \/\/ fuers RemoveOLEObjects\n\n    \/\/ Methoden fuer den Zugriff aufs Doc\n    void                    AddLink();\n    void                    RemoveLink();\n\n    \/\/ Hint abfangen fuer DocInfo\n    virtual void            Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n    \/\/ FileIO\n    virtual BOOL            InitNew(SvStorage* pNewStor);\n    virtual BOOL            Load(SvStorage* pStor);\n    virtual BOOL            LoadFrom(SvStorage* pStor);\n    virtual BOOL            ConvertFrom( SfxMedium &rMedium );\n    virtual void            HandsOff();\n    virtual BOOL            SaveAs(SvStorage * pNewStor );\n    virtual BOOL            ConvertTo(SfxMedium &rMedium );\n    virtual BOOL            SaveCompleted(SvStorage * pNewStor );\n    virtual USHORT          PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE );\n\n    \/\/ DocInfo dem Doc melden\n    \/\/\n    virtual SfxDocumentInfoDialog* CreateDocumentInfoDialog(\n                                    Window *pParent, const SfxItemSet &);\n    \/\/ Template-Btn\n    Window*                 AddTemplateBtn(SfxFileDialog* pFileDlg);\n\n    \/\/ OLE-Geraffel\n    virtual void            Draw( OutputDevice*, const JobSetup&, USHORT);\n\n    \/\/ Methoden fuer StyleSheets\n    USHORT                  Edit( const String &rName, const String& rParent, USHORT nFamily,\n                                    USHORT nMask, BOOL bNew,\n                                    BOOL bColumn = FALSE,\n                                    SwWrtShell* pActShell = 0,\n                                    BOOL bBasic = FALSE );\n    USHORT                  Delete(const String &rName, USHORT nFamily);\n    USHORT                  ApplyStyles(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0,\n                                        USHORT nMode = 0 );\n    USHORT                  DoWaterCan( const String &rName, USHORT nFamily);\n    USHORT                  UpdateStyle(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0);\n    USHORT                  MakeByExample(const String &rName,\n                                            USHORT nFamily, USHORT nMask, SwWrtShell* pShell = 0);\n\n    void                    InitDraw();\n    void                    SubInitNew();   \/\/ fuer InitNew und HtmlSourceModus\n    inline void             SetWrtShell(SwWrtShell* pShell)\n                                { pWrtShell = pShell; }\n\n    void                    RemoveOLEObjects();\n\n    DECL_STATIC_LINK( SwDocShell, IsLoadFinished, void* );\n    DECL_LINK( SelTemplateHdl, PushButton * );\n\npublic:\n\n    \/\/ aber selbst implementieren\n    SFX_DECL_INTERFACE(SW_DOCSHELL);\n    SFX_DECL_OBJECTFACTORY_DLL(SwDocShell, SW_DLL());\n    TYPEINFO();\n\n    static SfxInterface *_GetInterface() { return _GetInterfaceImpl(); }\n\n    \/\/Das Doc wird fuer SO-Datenaustausch benoetigt!\n    SwDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);\n    SwDocShell( SwDoc *pDoc, SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD );\n    ~SwDocShell();\n\n    \/\/ OLE 2.0-Benachrichtigung\n    DECL_LINK( Ole2ModifiedHdl, void * );\n\n    \/\/ OLE-Geraffel\n    virtual void      SetVisArea( const Rectangle &rRect );\n    virtual Rectangle GetVisArea( USHORT nAspect ) const;\n    virtual Printer  *GetDocumentPrinter();\n    virtual void      OnDocumentPrinterChanged( Printer * pNewPrinter );\n    virtual ULONG     GetMiscStatus() const;\n\n    virtual void            PrepareReload();\n    virtual void            SetModified( BOOL = TRUE );\n\n    \/\/ Dispatcher\n    void                    Execute(SfxRequest &);\n    void                    ExecStyleSheet(SfxRequest&);\n    void                    ExecDB(SfxRequest&);\n\n    void                    GetState(SfxItemSet &);\n    void                    StateAlways(SfxItemSet &);\n    void                    StateStyleSheet(SfxItemSet&, SwWrtShell* pSh = 0 );\n\n    \/\/ Doc rausreichen aber VORSICHT\n    inline SwDoc*           GetDoc() { return pDoc; }\n    void                    UpdateFontList();\n    void                    UpdateChildWindows();\n\n    \/\/ DocumentInfo neu setzen\n    BOOL                    SetDocumentInfo(const SfxDocumentInfo& rInfo);\n\n    \/\/ globaler IO\n    virtual BOOL            Save();\n    inline BOOL                 SaveAsChilds( SvStorage *pStor );\n\n    \/\/ fuer VorlagenPI\n    virtual SfxStyleSheetBasePool*  GetStyleSheetPool();\n\n    \/\/ Fuer Organizer\n    virtual BOOL Insert(SfxObjectShell &rSource,\n                        USHORT  nSourceIdx1,\n                        USHORT  nSourceIdx2,\n                        USHORT  nSourceIdx3,\n                        USHORT& nIdx1,\n                        USHORT& nIdx2,\n                        USHORT& nIdx3,\n                        USHORT& nRemovedIdx);\n\n    virtual BOOL Remove(USHORT nIdx1,\n                        USHORT nIdx2 = INDEX_IGNORE,\n                        USHORT nIdx3 = INDEX_IGNORE);\n\n    virtual Bitmap      GetStyleFamilyBitmap( SfxStyleFamily eFamily );\n\n    \/\/ View setzen fuer Aktionen ueber Shell\n    void          SetView(SwView* pVw);\n    const SwView *GetView() const { return pView; }\n\n    \/\/ Zugriff auf die zur SwView gehoerige SwWrtShell\n          SwWrtShell *GetWrtShell()       { return pWrtShell; }\n    const SwWrtShell *GetWrtShell() const { return pWrtShell; }\n\n    \/\/ fuer die Core - die kennt die DocShell aber keine WrtShell!\n          SwFEShell *GetFEShell();\n    const SwFEShell *GetFEShell() const\n                { return ((SwDocShell*)this)->GetFEShell(); }\n\n\n    \/\/ Fuer Einfuegen Dokument\n    Reader* StartConvertFrom(SfxMedium& rMedium, SwReader** ppRdr,\n                            SwCrsrShell* pCrsrSh = 0, SwPaM* pPaM = 0);\n\n    \/\/ Anforderung der pIo-Struktur fuer den Zugriff auf Substorages\n    \/\/ und Streams\n    Sw3Io* GetIoSystem() { return pIo; }\n\n    virtual long DdeGetData( const String& rItem, SvData& rData );\n    virtual long DdeSetData( const String& rItem, const SvData& rData );\n    virtual SvPseudoObject* DdeCreateHotLink( const String& rItem );\n    virtual void        FillClass( SvGlobalName * pClassName,\n                                   ULONG * pClipFormat,\n                                   String * pAppName,\n                                   String * pLongUserName,\n                                   String * pUserName,\n                                   long nVersion = SOFFICE_FILEFORMAT_CURRENT ) const;\n    virtual void    FillRegInfo( SvEmbeddedRegistryInfo * );\n\n    virtual SvDataMemberObjectRef CreateSnapshot();\n\n    virtual void LoadStyles( SfxObjectShell& rSource );\n\n    \/\/ Seitenvorlagedialog anzeigen, ggf. auf Spaltenpage\n    void    FormatPage( const String& rPage,\n                        BOOL bColumn = FALSE,\n                        SwWrtShell*     pActShell = 0 );\n\n    \/\/ Timer starten fuers ueberpruefen der Grafik-Links. Sind alle\n    \/\/ vollstaendig geladen, dann ist das Doc fertig\n    void StartLoadFinishedTimer();\n\n    \/\/ eine Uebertragung wird abgebrochen (wird aus dem SFX gerufen)\n    virtual void CancelTransfers();\n\n    \/\/ Doc aus Html-Source neu laden\n    void    ReloadFromHtml( const String& rStreamName, SwSrcView* pSrcView );\n\n    \/\/ embedded alle lokalen Links (Bereiche\/Grafiken)\n    BOOL EmbedAllLinks();\n\n    \/\/Activate wait cursor for all windows of this document\n    \/\/Optionally all dispatcher could be Locked\n    \/\/Usually locking should be done using the class: SwWaitObject!\n    void EnterWait( BOOL bLockDispatcher );\n    void LeaveWait( BOOL bLockDispatcher );\n\n    void ToggleBrowserMode(BOOL bOn, SwView* pView = 0);\n\n    ULONG LoadStylesFromFile( const String& rURL, SwgReaderOption& rOpt,\n                                BOOL bUnoCall );\n    void InvalidateModel();\n    void ReactivateModel();\n\n#if SUPD>620\n    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >  GetEventNames();\n#endif\n};\n\ninline BOOL SwDocShell::SaveAsChilds( SvStorage *pStor )\n{\n    return SfxInPlaceObject::SaveAsChilds( pStor );\n}\n#endif\n<|endoftext|>"}
{"text":"\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: dpage.hxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-09 01:42:44 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _DPAGE_HXX\n#define _DPAGE_HXX\n\n#ifndef _FM_FMPAGE_HXX\n#include \n#endif\n\n#ifndef _SVDOBJ_HXX\n#include \n#endif\n\nclass SdrPageGridFrameList;\nclass SwDrawDocument;\nclass SwDoc;\n\nclass SwDPage : public FmFormPage, public SdrObjUserCall\n{\n    SdrPageGridFrameList*   pGridLst;\n    SwDoc&                  rDoc;\n\npublic:\n    SwDPage(SwDrawDocument& rNewModel, BOOL bMasterPage=FALSE);\n    ~SwDPage();\n\n    \/\/ #i3694#\n    \/\/ This GetOffset() method is not needed anymore, it even leads to errors.\n    \/\/ virtual Point GetOffset() const;\n    virtual SdrObject* ReplaceObject( SdrObject* pNewObj, ULONG nObjNum );\n\n    virtual void    RequestBasic();\n\n    virtual const SdrPageGridFrameList* GetGridFrameList(const SdrPageView* pPV,\n                                    const Rectangle *pRect) const;\n\n    virtual String GetLinkData( const String& rLinkName );\n    virtual void SetLinkData( const String& rLinkName, const String& rLinkData );\n\n    BOOL RequestHelp( Window* pWindow, SdrView* pView, const HelpEvent& rEvt );\n\n    virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createUnoPage();\n};\n\n#endif     \/\/ _DPAGE_HXX\n\n\n\nINTEGRATION: CWS warnings01 (1.4.344); FILE MERGED 2006\/05\/15 12:30:43 sb 1.4.344.2: #i53898# Made code warning-free and\/or compile at all after resync to SRC680m162. 2006\/05\/12 16:42:52 sb 1.4.344.1: #i53898# Made code warning-free and\/or compile at all after resync to SRC680m162.\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: dpage.hxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: hr $ $Date: 2006-06-19 12:39:18 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _DPAGE_HXX\n#define _DPAGE_HXX\n\n#ifndef _FM_FMPAGE_HXX\n#include \n#endif\n\n#ifndef _SVDOBJ_HXX\n#include \n#endif\n\nclass SdrPageGridFrameList;\nclass SwDrawDocument;\nclass SwDoc;\n\nclass SwDPage : public FmFormPage, public SdrObjUserCall\n{\n    SdrPageGridFrameList*   pGridLst;\n    SwDoc&                  rDoc;\n\npublic:\n    SwDPage(SwDrawDocument& rNewModel, BOOL bMasterPage=FALSE);\n    ~SwDPage();\n\n    \/\/ #i3694#\n    \/\/ This GetOffset() method is not needed anymore, it even leads to errors.\n    \/\/ virtual Point GetOffset() const;\n    virtual SdrObject* ReplaceObject( SdrObject* pNewObj, ULONG nObjNum );\n\n    virtual const SdrPageGridFrameList* GetGridFrameList(const SdrPageView* pPV,\n                                    const Rectangle *pRect) const;\n\n    BOOL RequestHelp( Window* pWindow, SdrView* pView, const HelpEvent& rEvt );\n\n    virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createUnoPage();\n};\n\n#endif     \/\/ _DPAGE_HXX\n\n\n\n<|endoftext|>"}
{"text":"#include \"Token\/Token.h\"\n#include \"Generator\/Generator.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace dale;\n\nstatic const char *options = \"M:m:O:a:I:L:l:o:s:b:cdrR\";\nstatic const int COPY_SIZE = 8192;\n\nstatic bool\nappearsToBeLib(const char *str)\n{\n    int len = strlen(str);\n    if (len >= 2) {\n        const char *end = str + (len - 2);\n        if ((!strcmp(end, \".o\")) || (!strcmp(end, \".a\"))) {\n            return true;\n        }\n    }\n    return false;\n}\n\nstatic void\njoinWithPrefix(std::vector *strings, const char *prefix,\n               std::string *buffer)\n{\n    for (std::vector::iterator b = strings->begin(),\n                                            e = strings->end();\n            b != e;\n            ++b) {\n        buffer->append(\" \");\n        buffer->append(prefix);\n        buffer->append(\" \");\n        buffer->append(*b);\n    }\n}\n\nstatic bool\ncopyFile(const char *to_path, FILE *from)\n{\n    FILE *to = fopen(to_path, \"w\");\n    char buf[COPY_SIZE];\n    memset(buf, 0, COPY_SIZE);\n    size_t bytes;\n    size_t wbytes;\n    bool success = true;\n\n    fseek(from, SEEK_SET, 0);\n\n    while ((bytes = fread(buf, (size_t) 1, (size_t) COPY_SIZE, from))) {\n        if (ferror(from)) {\n            perror(\"Unable to read file\");\n            fclose(from);\n            fclose(to);\n            success = false;\n            break;\n        }\n        wbytes = fwrite(buf, (size_t) 1, bytes, to);\n        if (wbytes != bytes) {\n            if (ferror(from)) {\n                perror(\"Unable to copy file content\");\n                success = false;\n                break;\n            }\n            if (ferror(to)) {\n                perror(\"Unable to copy file content\");\n                success = false;\n                break;\n            }\n        }\n        if (bytes != COPY_SIZE) {\n            if (feof(from)) {\n                break;\n            } else {\n                perror(\"Unable to copy file content\");\n                success = false;\n                break;\n            }\n        }\n        memset(buf, 0, COPY_SIZE);\n    }\n\n    fflush(to);\n    fclose(from);\n    fclose(to);\n\n    return success;\n}\n\nint\nmain(int argc, char **argv)\n{\n    int opt;\n    char optc;\n\n    std::vector input_files;\n    std::vector input_link_files;\n    std::vector compile_libs;\n    std::vector run_libs;\n    std::vector include_paths;\n    std::vector run_paths;\n    std::vector bitcode_paths;\n    std::vector static_modules;\n    std::vector cto_modules;\n    std::vector module_paths;\n\n    std::string output_path;\n    const char *output_path_arg = NULL;\n    const char *module_name     = NULL;\n\n    int produce  = ASM;\n    int optlevel = 0;\n\n    int produce_set     = 0;\n    int no_linking      = 0;\n    int debug           = 0;\n    int no_dale_stdlib  = 0;\n    int no_stdlib       = 0;\n    int remove_macros   = 0;\n    int no_common       = 0;\n    int no_strip        = 0;\n    int static_mods_all = 0;\n    int found_sm        = 0;\n    int found_ctom      = 0;\n    int enable_cto      = 0;\n\n    int option_index         = 0;\n    int forced_remove_macros = 0;\n\n    static struct option long_options[] = {\n        { \"no-dale-stdlib\", no_argument,       &no_dale_stdlib,  1 },\n        { \"no-common\",      no_argument,       &no_common,       1 },\n        { \"no-stdlib\",      no_argument,       &no_stdlib,       1 },\n        { \"no-strip\",       no_argument,       &no_strip,        1 },\n        { \"static-modules\", no_argument,       &static_mods_all, 1 },\n        { \"static-module\",  required_argument, &found_sm,        1 },\n        { \"cto-module\",     required_argument, &found_ctom,      1 },\n        { \"enable-cto\",     no_argument,       &enable_cto,      1 },\n        { 0, 0, 0, 0 }\n    };\n\n    if (argc < 2) {\n        fprintf(stderr, \"dalec: no input files.\\n\");\n        exit(1);\n    }\n\n    while ((opt = getopt_long(argc, argv, options,\n                              long_options, &option_index)) != -1) {\n        optc = (char) opt;\n\n        switch (optc) {\n            case 'o': {\n                if (output_path_arg) {\n                    fprintf(stderr, \"dalec: an output path has already \"\n                                    \"been specified.\\n\");\n                    exit(1);\n                }\n                output_path_arg = optarg;\n                break;\n            }\n            case 'O': {\n                optlevel = (optarg[0] - '0');\n                if ((optlevel < 0) || (optlevel > 4)) {\n                    fprintf(stderr, \"dalec: invalid optimisation level.\\n\");\n                    exit(1);\n                }\n                break;\n            }\n            case 's': {\n                const char *type = optarg;\n                if (!strcmp(type, \"as\")) {\n                    produce = ASM;\n                } else if (!strcmp(type, \"ir\")) {\n                    produce = IR;\n                } else if (!strcmp(type, \"bc\")) {\n                    produce = BitCode;\n                } else {\n                    fprintf(stderr, \"dalec: unrecognised output \"\n                            \"option.\\n\");\n                    exit(1);\n                }\n                produce_set = true;\n                break;\n            }\n            case 'd': debug = 1;                                   break;\n            case 'c': no_linking = 1;                              break;\n            case 'r': remove_macros = 1; forced_remove_macros = 1; break;\n            case 'R': remove_macros = 0; forced_remove_macros = 1; break;\n            case 'I': include_paths.push_back(optarg);             break;\n            case 'a': compile_libs.push_back(optarg);              break;\n            case 'L': run_paths.push_back(optarg);                 break;\n            case 'l': run_libs.push_back(optarg);                  break;\n            case 'b': bitcode_paths.push_back(optarg);             break;\n            case 'M': module_paths.push_back(optarg);              break;\n            case 'm': module_name = optarg;                        break;\n        };\n\n        if (found_sm) {\n            found_sm = 0;\n            static_modules.push_back(optarg);\n        } else if (found_ctom) {\n            found_ctom = 0;\n            cto_modules.push_back(optarg);\n        }\n    }\n\n    \/* If the user wants an executable and has not specified either\n     * way with respect to removing macros, then remove macros. *\/\n    if (!no_linking && !produce_set && !forced_remove_macros) {\n        remove_macros = 1;\n    }\n\n    \/* Every argument after the options is treated as an input file.\n     * Input files that end with .o or .a should go straight to the\n     * linker. *\/\n    int input_file_count = argc - optind;\n    for (int i = 0; i < input_file_count; ++i) {\n        const char *input_file = argv[optind + i];\n        if (appearsToBeLib(input_file)) {\n            input_link_files.push_back(input_file);\n        } else {\n            input_files.push_back(input_file);\n        }\n    }\n\n    if (!input_files.size()) {\n        fprintf(stderr, \"dalec: no input files.\\n\");\n        exit(1);\n    }\n\n    \/* Set output_path. *\/\n    if (!no_linking) {\n        if (output_path_arg) {\n            output_path.append(output_path_arg);\n        } else {\n            if (produce == ASM) {\n                output_path.append(\"a.out\");\n            } else if (produce_set) {\n                output_path.append(input_files[0]);\n                output_path.append(\n                      (produce == IR)      ? \".ll\"\n                    : (produce == ASM)     ? \".s\"\n                    : (produce == BitCode) ? \".bc\"\n                                           : \".unknown\"\n                );\n            }\n        }\n    } else {\n        if (output_path_arg) {\n            output_path.append(output_path_arg);\n        } else {\n            output_path.append(input_files[0]);\n            output_path.append(\".o\");\n        }\n    }\n\n    std::string compile_lib_str;\n    joinWithPrefix(&compile_libs, \"-l\", &compile_lib_str);\n\n    std::string include_path_str;\n    joinWithPrefix(&include_paths, \"-I\", &include_path_str);\n\n    std::string run_path_str;\n    joinWithPrefix(&run_paths, \"-L\", &run_path_str);\n\n    std::string input_file_str;\n    joinWithPrefix(&input_files, \" \", &input_file_str);\n\n    std::string input_link_file_str;\n    joinWithPrefix(&input_link_files, \" \", &input_link_file_str);\n\n    FILE *output_file = tmpfile();\n    if (!output_file) {\n        fprintf(stderr, \"dalec: unable to open temporary output file.\\n\");\n        exit(1);\n    }\n    std::vector so_paths;\n    Generator generator;\n\n    bool generated =\n        generator.run(&input_files, &bitcode_paths, output_file,\n                      produce, optlevel, remove_macros,\n                      module_name, no_common, &so_paths, no_strip,\n                      static_mods_all, &static_modules,\n                      &cto_modules, enable_cto, debug, no_dale_stdlib,\n                      &compile_libs, &include_paths,\n                      &module_paths);\n    if (!generated) {\n        exit(1);\n    }\n    fflush(output_file);\n\n    std::string run_lib_str;\n    joinWithPrefix(&run_libs, \" -l \", &run_lib_str);\n\n    for (std::vector::reverse_iterator b = so_paths.rbegin(),\n                                                    e = so_paths.rend();\n            b != e;\n            ++b) {\n        input_link_file_str.append(\" \");\n        input_link_file_str.append((*b).c_str());\n    }\n\n    std::string intermediate_output_path = output_path;\n    if (!produce_set) {\n        intermediate_output_path.append(\".s\");\n    }\n    bool result = copyFile(intermediate_output_path.c_str(), output_file);\n    if (!result) {\n        exit(1);\n    }\n    if (produce_set) {\n        exit(0);\n    }\n\n    char compile_cmd[8192];\n    int bytes = 0;\n    if (no_linking) {\n        bytes = snprintf(compile_cmd, (8192 - 1),\n                         \"cc %s -c %s %s %s -o %s\",\n                         (no_stdlib) ? \"--nostdlib\" : \"\",\n                         run_path_str.c_str(),\n                         run_lib_str.c_str(),\n                         intermediate_output_path.c_str(),\n                         output_path.c_str());\n    } else {\n        bytes = snprintf(compile_cmd, (8192 - 1),\n                         \"cc %s -Wl,--gc-sections %s %s %s %s -o %s\",\n                         (no_stdlib) ? \"--nostdlib\" : \"\",\n                         run_path_str.c_str(),\n                         intermediate_output_path.c_str(),\n                         input_link_file_str.c_str(),\n                         run_lib_str.c_str(),\n                         output_path.c_str());\n    }\n    if (bytes >= 8192) {\n        fprintf(stderr, \"dalec: cc command is too long!\\n\");\n        exit(1);\n    }\n\n    int status = system(compile_cmd);\n    if (status != 0) {\n        fprintf(stderr, \"dalec: cc failed.\\n\", res, compile_cmd);\n        if (debug) {\n            fprintf(stderr, \"%s\\n\", compile_cmd);\n        }\n        exit(1);\n    }\n\n    status = remove(intermediate_output_path.c_str());\n    if (status != 0) {\n        fprintf(stderr, \"dalec: unable to remove temporary file '%s'.\\n\",\n                        intermediate_output_path.c_str());\n        exit(1);\n    }\n\n    return 0;\n}\n[master] tidying#include \"Generator\/Generator.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/*! dalec\n\n    The main compiler executable, responsible for organising the\n    arguments for Generator, running Generator, and assembling\/linking\n    the results together using the system's compiler.\n*\/\n\nusing namespace dale;\n\nstatic const char *options = \"M:m:O:a:I:L:l:o:s:b:cdrR\";\nstatic const int COPY_SIZE = 8192;\nstatic const char *progname = NULL;\n\nstatic void\nerror(const char *error_msg, bool show_perror = false)\n{\n    if (show_perror) {\n        perror(progname);\n    }\n    fprintf(stderr, \"%s: %s.\\n\", progname, error_msg);\n    exit(1);\n}\n\nstatic bool\nappearsToBeLib(const char *str)\n{\n    int len = strlen(str);\n    if (len >= 2) {\n        const char *end = str + (len - 2);\n        if ((!strcmp(end, \".o\")) || (!strcmp(end, \".a\"))) {\n            return true;\n        }\n    }\n    return false;\n}\n\nstatic void\njoinWithPrefix(std::vector *strings, const char *prefix,\n               std::string *buffer)\n{\n    for (std::vector::iterator b = strings->begin(),\n                                            e = strings->end();\n            b != e;\n            ++b) {\n        buffer->append(\" \");\n        buffer->append(prefix);\n        buffer->append(\" \");\n        buffer->append(*b);\n    }\n}\n\nstatic bool\ncopyFile(const char *to_path, FILE *from)\n{\n    FILE *to = fopen(to_path, \"w\");\n    char buf[COPY_SIZE];\n    memset(buf, 0, COPY_SIZE);\n    size_t bytes;\n    size_t wbytes;\n    bool success = true;\n\n    fseek(from, SEEK_SET, 0);\n\n    while ((bytes = fread(buf, (size_t) 1, (size_t) COPY_SIZE, from))) {\n        if (ferror(from)) {\n            fclose(from);\n            fclose(to);\n            error(\"unable to read temporary file\", true);\n            success = false;\n            break;\n        }\n        wbytes = fwrite(buf, (size_t) 1, bytes, to);\n        if (wbytes != bytes) {\n            if (ferror(from)) {\n                error(\"unable to copy temporary file content\", true);\n                success = false;\n                break;\n            }\n            if (ferror(to)) {\n                error(\"unable to copy temporary file content\", true);\n                success = false;\n                break;\n            }\n        }\n        if (bytes != COPY_SIZE) {\n            if (feof(from)) {\n                break;\n            } else {\n                error(\"unable to copy temporary file content\", true);\n                success = false;\n                break;\n            }\n        }\n        memset(buf, 0, COPY_SIZE);\n    }\n\n    fflush(to);\n    fclose(from);\n    fclose(to);\n\n    return success;\n}\n\nint\nmain(int argc, char **argv)\n{\n    progname = argv[0];\n\n    int opt;\n    char optc;\n\n    std::vector input_files;\n    std::vector input_link_files;\n    std::vector compile_libs;\n    std::vector run_libs;\n    std::vector include_paths;\n    std::vector run_paths;\n    std::vector bitcode_paths;\n    std::vector static_modules;\n    std::vector cto_modules;\n    std::vector module_paths;\n\n    std::string output_path;\n    const char *output_path_arg = NULL;\n    const char *module_name     = NULL;\n\n    int produce  = ASM;\n    int optlevel = 0;\n\n    int produce_set     = 0;\n    int no_linking      = 0;\n    int debug           = 0;\n    int no_dale_stdlib  = 0;\n    int no_stdlib       = 0;\n    int remove_macros   = 0;\n    int no_common       = 0;\n    int no_strip        = 0;\n    int static_mods_all = 0;\n    int found_sm        = 0;\n    int found_ctom      = 0;\n    int enable_cto      = 0;\n\n    int option_index         = 0;\n    int forced_remove_macros = 0;\n\n    static struct option long_options[] = {\n        { \"no-dale-stdlib\", no_argument,       &no_dale_stdlib,  1 },\n        { \"no-common\",      no_argument,       &no_common,       1 },\n        { \"no-stdlib\",      no_argument,       &no_stdlib,       1 },\n        { \"no-strip\",       no_argument,       &no_strip,        1 },\n        { \"static-modules\", no_argument,       &static_mods_all, 1 },\n        { \"static-module\",  required_argument, &found_sm,        1 },\n        { \"cto-module\",     required_argument, &found_ctom,      1 },\n        { \"enable-cto\",     no_argument,       &enable_cto,      1 },\n        { 0, 0, 0, 0 }\n    };\n\n    if (argc < 2) {\n        error(\"no input files\");\n    }\n\n    while ((opt = getopt_long(argc, argv, options,\n                              long_options, &option_index)) != -1) {\n        optc = (char) opt;\n\n        switch (optc) {\n            case 'o': {\n                if (output_path_arg) {\n                    error(\"an output path has already been specified\");\n                }\n                output_path_arg = optarg;\n                break;\n            }\n            case 'O': {\n                optlevel = (optarg[0] - '0');\n                if ((optlevel < 0) || (optlevel > 4)) {\n                    error(\"invalid optimisation level\");\n                }\n                break;\n            }\n            case 's': {\n                const char *type = optarg;\n                if (!strcmp(type, \"as\")) {\n                    produce = ASM;\n                } else if (!strcmp(type, \"ir\")) {\n                    produce = IR;\n                } else if (!strcmp(type, \"bc\")) {\n                    produce = BitCode;\n                } else {\n                    error(\"unrecognised output option\");\n                }\n                produce_set = true;\n                break;\n            }\n            case 'd': debug = 1;                                   break;\n            case 'c': no_linking = 1;                              break;\n            case 'r': remove_macros = 1; forced_remove_macros = 1; break;\n            case 'R': remove_macros = 0; forced_remove_macros = 1; break;\n            case 'I': include_paths.push_back(optarg);             break;\n            case 'a': compile_libs.push_back(optarg);              break;\n            case 'L': run_paths.push_back(optarg);                 break;\n            case 'l': run_libs.push_back(optarg);                  break;\n            case 'b': bitcode_paths.push_back(optarg);             break;\n            case 'M': module_paths.push_back(optarg);              break;\n            case 'm': module_name = optarg;                        break;\n        };\n\n        if (found_sm) {\n            found_sm = 0;\n            static_modules.push_back(optarg);\n        } else if (found_ctom) {\n            found_ctom = 0;\n            cto_modules.push_back(optarg);\n        }\n    }\n\n    \/* If the user wants an executable and has not specified either\n     * way with respect to removing macros, then remove macros. *\/\n    if (!no_linking && !produce_set && !forced_remove_macros) {\n        remove_macros = 1;\n    }\n\n    \/* Every argument after the options is treated as an input file.\n     * Input files that end with .o or .a should go straight to the\n     * linker. *\/\n    int input_file_count = argc - optind;\n    for (int i = 0; i < input_file_count; ++i) {\n        const char *input_file = argv[optind + i];\n        if (appearsToBeLib(input_file)) {\n            input_link_files.push_back(input_file);\n        } else {\n            input_files.push_back(input_file);\n        }\n    }\n\n    if (!input_files.size()) {\n        error(\"no input files\");\n    }\n\n    \/* Set output_path. *\/\n    if (!no_linking) {\n        if (output_path_arg) {\n            output_path.append(output_path_arg);\n        } else {\n            if (produce == ASM) {\n                output_path.append(\"a.out\");\n            } else if (produce_set) {\n                output_path.append(input_files[0]);\n                output_path.append(\n                      (produce == IR)      ? \".ll\"\n                    : (produce == ASM)     ? \".s\"\n                    : (produce == BitCode) ? \".bc\"\n                                           : \".unknown\"\n                );\n            }\n        }\n    } else {\n        if (output_path_arg) {\n            output_path.append(output_path_arg);\n        } else {\n            output_path.append(input_files[0]);\n            output_path.append(\".o\");\n        }\n    }\n\n    std::string compile_lib_str;\n    joinWithPrefix(&compile_libs, \"-l\", &compile_lib_str);\n\n    std::string include_path_str;\n    joinWithPrefix(&include_paths, \"-I\", &include_path_str);\n\n    std::string run_path_str;\n    joinWithPrefix(&run_paths, \"-L\", &run_path_str);\n\n    std::string input_file_str;\n    joinWithPrefix(&input_files, \" \", &input_file_str);\n\n    std::string input_link_file_str;\n    joinWithPrefix(&input_link_files, \" \", &input_link_file_str);\n\n    FILE *output_file = tmpfile();\n    if (!output_file) {\n        error(\"unable to open temporary output file\", true);\n    }\n    std::vector so_paths;\n    Generator generator;\n\n    bool generated =\n        generator.run(&input_files, &bitcode_paths, output_file,\n                      produce, optlevel, remove_macros,\n                      module_name, no_common, &so_paths, no_strip,\n                      static_mods_all, &static_modules,\n                      &cto_modules, enable_cto, debug, no_dale_stdlib,\n                      &compile_libs, &include_paths,\n                      &module_paths);\n    if (!generated) {\n        exit(1);\n    }\n    fflush(output_file);\n\n    std::string run_lib_str;\n    joinWithPrefix(&run_libs, \" -l \", &run_lib_str);\n\n    for (std::vector::reverse_iterator b = so_paths.rbegin(),\n                                                    e = so_paths.rend();\n            b != e;\n            ++b) {\n        input_link_file_str.append(\" \");\n        input_link_file_str.append((*b).c_str());\n    }\n\n    std::string intermediate_output_path = output_path;\n    if (!produce_set) {\n        intermediate_output_path.append(\".s\");\n    }\n    bool result = copyFile(intermediate_output_path.c_str(), output_file);\n    if (!result) {\n        exit(1);\n    }\n    if (produce_set) {\n        exit(0);\n    }\n\n    char compile_cmd[8192];\n    int bytes = 0;\n    if (no_linking) {\n        bytes = snprintf(compile_cmd, (8192 - 1),\n                         \"cc %s -c %s %s %s -o %s\",\n                         (no_stdlib) ? \"--nostdlib\" : \"\",\n                         run_path_str.c_str(),\n                         run_lib_str.c_str(),\n                         intermediate_output_path.c_str(),\n                         output_path.c_str());\n    } else {\n        bytes = snprintf(compile_cmd, (8192 - 1),\n                         \"cc %s -Wl,--gc-sections %s %s %s %s -o %s\",\n                         (no_stdlib) ? \"--nostdlib\" : \"\",\n                         run_path_str.c_str(),\n                         intermediate_output_path.c_str(),\n                         input_link_file_str.c_str(),\n                         run_lib_str.c_str(),\n                         output_path.c_str());\n    }\n    if (bytes >= 8192) {\n        error(\"cc command is too long\");\n    }\n\n    int status = system(compile_cmd);\n    if (status != 0) {\n        if (debug) {\n            fprintf(stderr, \"%s\\n\", compile_cmd);\n        }\n        error(\"cc failed\");\n    }\n\n    status = remove(intermediate_output_path.c_str());\n    if (status != 0) {\n        if (debug) {\n            fprintf(stderr, \"%s\\n\", intermediate_output_path.c_str());\n        }\n        error(\"unable to remove temporary file\");\n    }\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"#ifndef GAMELIB_ENTITYFACTORY_HPP\n#define GAMELIB_ENTITYFACTORY_HPP\n\n#include \"gamelib\/utils\/Factory.hpp\"\n#include \"gamelib\/core\/res\/JsonResource.hpp\"\n#include \"gamelib\/core\/Subsystem.hpp\"\n#include \"Component.hpp\"\n#include \"Entity.hpp\"\n#include \"json\/json.h\"\n\nnamespace gamelib\n{\n    auto createEntity(const std::string& name)                   -> Entity::Handle;\n    auto createEntity(const std::string& name, float x, float y) -> Entity::Handle;\n\n\n    class EntityFactory : public Subsystem \/\/: public JsonSerializer\n    {\n        typedef Factory ComponentFactory;\n\n        public:\n            ASSIGN_NAMETAG(\"EntityFactory\");\n\n        public:\n            EntityFactory();\n\n            auto createWithDelta(const std::string& name, const Json::Value& node)              -> Entity::Handle;\n            auto createWithDelta(const std::string& name, const Json::Value& node, Entity* ent) -> void;\n            auto createFromJson(const Json::Value& node)              -> Entity::Handle;\n            auto createFromJson(const Json::Value& node, Entity* ent) -> void;\n            auto create(const std::string& name)                      -> Entity::Handle;\n            auto create(const std::string& name, Entity* ent)         -> void;\n            auto createComponent(const std::string& name)             -> ComponentPtr;\n            auto createComponentFromJson(const std::string& name, const Json::Value& node) -> ComponentPtr;\n\n            auto add(const Json::Value& cfg)                          -> void;\n            auto add(const std::string& name, const Json::Value& cfg) -> void;\n            auto addComponent(const std::string& name, ComponentFactory::CreatorFunction callback) -> void;\n\n            auto removeEntity(const std::string& name)    -> void;\n            auto removeComponent(const std::string& name) -> void;\n            auto clear()       -> void;\n            auto size() const  -> size_t;\n\n            auto findEntity(const std::string& name) -> const Json::Value*;\n\n            template \n            void addComponent(const std::string& name)\n            {\n                _compfactory.add(name);\n                LOG_DEBUG(\"Registered component \", name);\n            }\n\n            \/\/ Signature: bool(const std::string&)\n            \/\/ When true is returned, the loop breaks.\n            template \n            void iterkeys(F callback) const\n            {\n                for (auto& i : _entdata)\n                    if (callback(i.first))\n                        break;\n            }\n\n        private:\n            std::unordered_map _entdata;\n            ComponentFactory _compfactory;\n    };\n}\n\n#endif\nAdd overload that uses the Component's nametag for registering#ifndef GAMELIB_ENTITYFACTORY_HPP\n#define GAMELIB_ENTITYFACTORY_HPP\n\n#include \"gamelib\/utils\/Factory.hpp\"\n#include \"gamelib\/core\/res\/JsonResource.hpp\"\n#include \"gamelib\/core\/Subsystem.hpp\"\n#include \"Component.hpp\"\n#include \"Entity.hpp\"\n#include \"json\/json.h\"\n\nnamespace gamelib\n{\n    auto createEntity(const std::string& name)                   -> Entity::Handle;\n    auto createEntity(const std::string& name, float x, float y) -> Entity::Handle;\n\n\n    class EntityFactory : public Subsystem \/\/: public JsonSerializer\n    {\n        typedef Factory ComponentFactory;\n\n        public:\n            ASSIGN_NAMETAG(\"EntityFactory\");\n\n        public:\n            EntityFactory();\n\n            auto createWithDelta(const std::string& name, const Json::Value& node)              -> Entity::Handle;\n            auto createWithDelta(const std::string& name, const Json::Value& node, Entity* ent) -> void;\n            auto createFromJson(const Json::Value& node)              -> Entity::Handle;\n            auto createFromJson(const Json::Value& node, Entity* ent) -> void;\n            auto create(const std::string& name)                      -> Entity::Handle;\n            auto create(const std::string& name, Entity* ent)         -> void;\n            auto createComponent(const std::string& name)             -> ComponentPtr;\n            auto createComponentFromJson(const std::string& name, const Json::Value& node) -> ComponentPtr;\n\n            auto add(const Json::Value& cfg)                          -> void;\n            auto add(const std::string& name, const Json::Value& cfg) -> void;\n            auto addComponent(const std::string& name, ComponentFactory::CreatorFunction callback) -> void;\n\n            auto removeEntity(const std::string& name)    -> void;\n            auto removeComponent(const std::string& name) -> void;\n            auto clear()       -> void;\n            auto size() const  -> size_t;\n\n            auto findEntity(const std::string& name) -> const Json::Value*;\n\n            template \n            void addComponent(const std::string& name)\n            {\n                _compfactory.add(name);\n                LOG_DEBUG(\"Registered component \", name);\n            }\n\n            template (), int>::type = 0>\n            void addComponent()\n            {\n                _compfactory.add(T::name());\n                LOG_DEBUG(\"Registered component \", T::name());\n            }\n\n            \/\/ Signature: bool(const std::string&)\n            \/\/ When true is returned, the loop breaks.\n            template \n            void iterkeys(F callback) const\n            {\n                for (auto& i : _entdata)\n                    if (callback(i.first))\n                        break;\n            }\n\n        private:\n            std::unordered_map _entdata;\n            ComponentFactory _compfactory;\n    };\n}\n\n#endif\n<|endoftext|>"}
{"text":"\/* Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *  * Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *  * Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *  * Neither the name of NVIDIA CORPORATION nor the names of its\n *    contributors may be used to endorse or promote products derived\n *    from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#pragma once\n\n#include \n\n#include \"mapping\/loop.hpp\"\n#include \"util\/numeric.hpp\"\n#include \"workload\/shape-models\/problem-shape.hpp\"\n#include \"workload\/util\/per-data-space.hpp\"\n#include \"workload\/workload.hpp\"\n#include \"workload\/format-models\/metadata-format.hpp\"\n#include \"nest-analysis-tile-info.hpp\"\n#include \"coordinate-space-tile-info.hpp\"\n#include \"model\/sparse-optimization-info.hpp\"\n\nnamespace tiling\n{\n\nconst int MaxTilingLevels = 16;\n\n\/\/ each item stands for a rank, each rank has associated metadata occupancy\ntypedef std::vector MetaDataTileOccupancy;\ntypedef std::vector PerRankFormatAccessEntry; \/\/ metadata access, payload accesses\ntypedef std::vector PerTileFormatAccesses;\n\n\/\/\n\/\/ DataMovementInfo\n\/\/\n\nstruct DataMovementInfo\n{\n  friend class boost::serialization::access;\n\n  \/\/ Serialization.\n  template \n  void serialize(Archive& ar, const unsigned int version=0) \n  {\n    if(version == 0)\n    {\n      ar& BOOST_SERIALIZATION_NVP(size);\n      ar& BOOST_SERIALIZATION_NVP(access_stats);\n      ar& BOOST_SERIALIZATION_NVP(subnest);\n    }\n  }\n\n  CoordinateSpaceTileInfo coord_space_info;  \/\/ carries information such as the shape of the tile, and eventually the point set\n  \/\/ Information particularly useful for tensors with metadata\n  \/\/ all of the vectors below should have the same length... which is the fiber tree depth\n  \/\/ note that, if a tensor is uncompressed and have no associated metadata (e.g., for eyeriss-style data gating),\n  \/\/      the tensor representation is just a dense tensor, which is already pre-analyzed in dense modeling\n  std::vector> metadata_models; \/\/ metadata models (if any) for each rank of the tile\n  std::vector rank_compressed; \/\/ if each rank is compressed\n  std::vector rank_formats; \/\/ each rank of the tensor should have metadata format, none for uncompressed\n  bool apply_rank_inner_to_outer;\n  std::size_t size; \/\/ for backward compatibility TODO: eventually we should use shape\n  std::size_t shape;\n  double expected_data_occupancy;\n  MetaDataTileOccupancy expected_metadata_occupancy;\n  problem::Shape::DataSpaceID dataspace_id ; \/\/ which dataspace does this tile belong to\n  std::size_t partition_size;\n  double parent_access_share;\n  bool distributed_multicast;\n  AccessStatMatrix access_stats;\n  double content_accesses;\n  std::uint64_t fills;\n  std::uint64_t reads;\n  std::uint64_t updates;\n  \n  double temporal_reductions;\n  double link_transfers;\n  double peer_accesses;           \/\/ number of accesses caused by link transfers in the previous level \n  double peer_fills;              \/\/ number of fills caused by link transfers in the previous level\n\n  PerTileFormatAccesses format_fills;\n  PerTileFormatAccesses format_reads;\n  PerTileFormatAccesses format_updates;\n  \n  std::vector subnest;\n  std::uint64_t replication_factor;      \/\/ number of spatial elements at this level.\n  double        avg_replication_factor;\n  std::uint64_t max_replication_factor;\n  std::uint64_t max_x_expansion;\n  std::uint64_t max_y_expansion;\n  std::uint64_t fanout;                  \/\/ per-element fanout to next-level.\n  std::uint64_t distributed_fanout;      \/\/ max range of fanout if distributed multicast is used.\n  bool is_on_storage_boundary;\n  bool is_master_spatial;\n  \/\/double partition_fraction;\n  std::size_t partition_fraction_denominator;\n  \/\/ Tile density\n  std::shared_ptr tile_density;  \/\/ statistical representation of tile data density\n  \/\/ Fine grained actions, names defined in operation-type.hpp\n  std::map fine_grained_data_accesses;\n  std::map fine_grained_format_accesses;\n  double expected_density;\n\n  \/\/ Compression related\n  bool compressed;\n  bool has_metadata;\n\n  \/\/ Only needed when tile has metadata\n  std::vector> metadata_subnest;\n  \/\/ std::vector metadata_subtile_shape;\n  std::vector metadata_subtile_point_set;\n  std::vector fiber_shape;\n  double child_level_metadata_occupancy_ratio;\n\n  \/\/ Parent child level records\n  unsigned parent_level;\n  std::string parent_level_name;\n  unsigned child_level;\n  DataMovementInfo* child_level_ptr;\n  DataMovementInfo* parent_level_ptr;\n\n  void Reset()\n  {\n    size = 0;\n    shape = 0;\n    expected_data_occupancy = std::numeric_limits::max();\n    expected_metadata_occupancy = {};\n    partition_size = 0;\n    access_stats.clear();\n    parent_access_share = 0;\n    distributed_multicast = false;\n    content_accesses = 0;\n    fills = 0;\n    reads = 0;\n    updates = 0;\n    link_transfers = 0;\n    peer_accesses = 0;\n    peer_fills = 0;\n    subnest.resize(0);\n    replication_factor = 0;\n    avg_replication_factor = 0;\n    max_x_expansion = 0;\n    max_y_expansion = 0;\n    fanout = 0;\n    distributed_fanout = 0;\n    compressed = false;\n    has_metadata = false;\n    apply_rank_inner_to_outer = false; \n    parent_level = std::numeric_limits::max();\n    child_level = std::numeric_limits::max();\n    parent_level_ptr = NULL;\n    child_level_ptr = NULL;\n    child_level_metadata_occupancy_ratio = 0;\n    fine_grained_data_accesses.clear();\n    fine_grained_format_accesses.clear();\n    format_fills = {};\n    format_reads = {};\n    format_updates = {};\n    metadata_subnest.clear();\n    metadata_subtile_point_set.clear();\n    fiber_shape.clear();\n    coord_space_info.Clear();\n    tile_density = NULL;\n    expected_density = 0;\n  }\n\n  void Validate()\n  {\n    \/\/ std::uint64_t f = 0;\n    \/\/ for (std::uint64_t i = 0; i < fanout; i++)\n    \/\/ {\n    \/\/   if (accesses[i] != 0)\n    \/\/   {\n    \/\/     auto multicast_factor = i + 1;\n    \/\/     auto scatter_factor = scatter_factors[i];\n    \/\/     f += (multicast_factor * scatter_factor);\n    \/\/   }\n    \/\/ }\n\n    \/\/ if (f != fanout)\n    \/\/ {\n    \/\/   std::cerr << \"ERROR: sigma(multicast * scatter) != fanout.\" << std::endl;\n    \/\/   std::cerr << \"  dumping (multicast, scatter) pairs:\" << std::endl;\n    \/\/   for (std::uint64_t i = 0; i < fanout; i++)\n    \/\/   {\n    \/\/     if (accesses[i] != 0)\n    \/\/     {\n    \/\/       auto multicast_factor = i + 1;\n    \/\/       auto scatter_factor = scatter_factors[i];\n    \/\/       std::cerr << \"    \" << multicast_factor << \", \" << scatter_factor << std::endl;\n    \/\/     }\n    \/\/   }\n    \/\/   std::cerr << \"  sigma(multicast, scatter) = \" << f << std::endl;\n    \/\/   std::cerr << \"  fanout = \" << fanout << std::endl;\n    \/\/   exit(1);\n    \/\/ }\n  }\n\n  void SetDensityModel(std::shared_ptr tile_density_ptr)\n  {\n    tile_density = tile_density_ptr;\n  }\n\n  void SetTensorRepresentation(const sparse::PerDataSpaceCompressionInfo& compression_opt_spec);\n  void SetTensorRepresentation(); \/\/ for default dense tensors\n\n  std::string GetDataSpaceName() const { return problem::GetShape()->DataSpaceIDToName.at(dataspace_id);}\n  bool GetHasMetaData() const { return has_metadata;}\n  std::string GetDensityType() const\n  {\n    return tile_density->GetDistributionType();\n  }\n  std::string GetMetaDataFormatName() const;\n  std::uint64_t GetNumMetaDataRanks() const\n  {\n    if (! has_metadata) return 0;\n    else return metadata_models.size();\n  }\n  CoordinateSpaceTileInfo GetCoordinateSpaceInfo() const;\n  CoordinateSpaceTileInfo GetChildTileCoordinateSpaceInfo() const;\n\n  \/\/ do not use this unless super necessary,\n  \/\/ as density model interface change will break the logic external to sparse modeling step\n  std::shared_ptr GetTileDensityModel() const { return tile_density; }\n\n\n  \/\/ More involved getter functions\n  \/\/ get data tile occupancy\n  std::uint64_t GetMaxDataTileOccupancyByConfidence(const double confidence = 1.0) const;\n  double GetDataTileOccupancyProbability(const std::uint64_t occupancy) const;\n  double GetChildLevelDataTileOccupancyProbability(const std::uint64_t occupancy) const;\n  std::uint64_t GetMinDataTileOccupancy() const;\n\n  \/\/ get metadata tile occupancy\n  MetaDataTileOccupancy GetMetaDataTileOccupancyGivenDataTile(const CoordinateSpaceTileInfo& cur_coord_tile) const;\n  MetaDataTileOccupancy GetMaxMetaDataTileOccupancyByConfidence(const double confidence = 1.0) const;\n  double GetExpectedAggregatedMetaDataTileOccupancy() const;\n\n  \/\/ density value related\n  double GetMaxTileDensityByConfidence(const double confidence = 1.0) const;\n  double GetExpectedTileDensity() const;\n};\n\n\/\/\n\/\/ Compute info\n\/\/\n\nstruct ComputeInfo\n{\n  std::uint64_t replication_factor;      \/\/ number of spatial elements at this level.\n  double accesses;\n  double avg_replication_factor;\n  std::uint64_t max_replication_factor;\n  std::uint64_t max_x_expansion;\n  std::uint64_t max_y_expansion;\n  std::uint64_t compute_cycles;\n\n  \/\/ fine grained actions, names defined in operation-type.hpp\n  std::map fine_grained_accesses; \n  \n  ComputeInfo() { Reset(); }\n\n  void Reset()\n  {\n    replication_factor = 0;\n    avg_replication_factor = 0;\n    max_replication_factor = 0;\n    max_x_expansion = 0;\n    max_y_expansion = 0;\n    accesses = 0;\n    compute_cycles = 0;\n  }\n};\n\n\/\/ datatypes needed before transpose\n\/\/ indexing order: [datatype\/optype, nest_level]\ntypedef problem::PerDataSpace> CompoundDataMovementNest ; \ntypedef std::vector ComputeNest;\nstruct CompoundTileNest{\n   CompoundDataMovementNest compound_data_movement_info_nest;\n   ComputeNest compute_info_nest;\n};\n\n\n\/\/ datatypes needed after transpose\ntypedef problem::PerDataSpace CompoundDataMovementInfo;\n\n\/\/ indexing order: [nest_level, datatype\/optype]\nstruct CompoundTile{\n  CompoundDataMovementInfo data_movement_info;\n  ComputeInfo compute_info;\n};\n\ntypedef std::vector NestOfCompoundTiles;\ntypedef problem::PerDataSpace CompoundMask;\n\ntypedef problem::PerDataSpace> CompoundMaskNest;\ntypedef std::vector NestOfCompoundMasks;\n\n} \/\/ namespace\nIncreased max tiling levels from 16->32\/* Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *  * Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *  * Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *  * Neither the name of NVIDIA CORPORATION nor the names of its\n *    contributors may be used to endorse or promote products derived\n *    from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#pragma once\n\n#include \n\n#include \"mapping\/loop.hpp\"\n#include \"util\/numeric.hpp\"\n#include \"workload\/shape-models\/problem-shape.hpp\"\n#include \"workload\/util\/per-data-space.hpp\"\n#include \"workload\/workload.hpp\"\n#include \"workload\/format-models\/metadata-format.hpp\"\n#include \"nest-analysis-tile-info.hpp\"\n#include \"coordinate-space-tile-info.hpp\"\n#include \"model\/sparse-optimization-info.hpp\"\n\nnamespace tiling\n{\n\nconst int MaxTilingLevels = 32;\n\n\/\/ each item stands for a rank, each rank has associated metadata occupancy\ntypedef std::vector MetaDataTileOccupancy;\ntypedef std::vector PerRankFormatAccessEntry; \/\/ metadata access, payload accesses\ntypedef std::vector PerTileFormatAccesses;\n\n\/\/\n\/\/ DataMovementInfo\n\/\/\n\nstruct DataMovementInfo\n{\n  friend class boost::serialization::access;\n\n  \/\/ Serialization.\n  template \n  void serialize(Archive& ar, const unsigned int version=0) \n  {\n    if(version == 0)\n    {\n      ar& BOOST_SERIALIZATION_NVP(size);\n      ar& BOOST_SERIALIZATION_NVP(access_stats);\n      ar& BOOST_SERIALIZATION_NVP(subnest);\n    }\n  }\n\n  CoordinateSpaceTileInfo coord_space_info;  \/\/ carries information such as the shape of the tile, and eventually the point set\n  \/\/ Information particularly useful for tensors with metadata\n  \/\/ all of the vectors below should have the same length... which is the fiber tree depth\n  \/\/ note that, if a tensor is uncompressed and have no associated metadata (e.g., for eyeriss-style data gating),\n  \/\/      the tensor representation is just a dense tensor, which is already pre-analyzed in dense modeling\n  std::vector> metadata_models; \/\/ metadata models (if any) for each rank of the tile\n  std::vector rank_compressed; \/\/ if each rank is compressed\n  std::vector rank_formats; \/\/ each rank of the tensor should have metadata format, none for uncompressed\n  bool apply_rank_inner_to_outer;\n  std::size_t size; \/\/ for backward compatibility TODO: eventually we should use shape\n  std::size_t shape;\n  double expected_data_occupancy;\n  MetaDataTileOccupancy expected_metadata_occupancy;\n  problem::Shape::DataSpaceID dataspace_id ; \/\/ which dataspace does this tile belong to\n  std::size_t partition_size;\n  double parent_access_share;\n  bool distributed_multicast;\n  AccessStatMatrix access_stats;\n  double content_accesses;\n  std::uint64_t fills;\n  std::uint64_t reads;\n  std::uint64_t updates;\n  \n  double temporal_reductions;\n  double link_transfers;\n  double peer_accesses;           \/\/ number of accesses caused by link transfers in the previous level \n  double peer_fills;              \/\/ number of fills caused by link transfers in the previous level\n\n  PerTileFormatAccesses format_fills;\n  PerTileFormatAccesses format_reads;\n  PerTileFormatAccesses format_updates;\n  \n  std::vector subnest;\n  std::uint64_t replication_factor;      \/\/ number of spatial elements at this level.\n  double        avg_replication_factor;\n  std::uint64_t max_replication_factor;\n  std::uint64_t max_x_expansion;\n  std::uint64_t max_y_expansion;\n  std::uint64_t fanout;                  \/\/ per-element fanout to next-level.\n  std::uint64_t distributed_fanout;      \/\/ max range of fanout if distributed multicast is used.\n  bool is_on_storage_boundary;\n  bool is_master_spatial;\n  \/\/double partition_fraction;\n  std::size_t partition_fraction_denominator;\n  \/\/ Tile density\n  std::shared_ptr tile_density;  \/\/ statistical representation of tile data density\n  \/\/ Fine grained actions, names defined in operation-type.hpp\n  std::map fine_grained_data_accesses;\n  std::map fine_grained_format_accesses;\n  double expected_density;\n\n  \/\/ Compression related\n  bool compressed;\n  bool has_metadata;\n\n  \/\/ Only needed when tile has metadata\n  std::vector> metadata_subnest;\n  \/\/ std::vector metadata_subtile_shape;\n  std::vector metadata_subtile_point_set;\n  std::vector fiber_shape;\n  double child_level_metadata_occupancy_ratio;\n\n  \/\/ Parent child level records\n  unsigned parent_level;\n  std::string parent_level_name;\n  unsigned child_level;\n  DataMovementInfo* child_level_ptr;\n  DataMovementInfo* parent_level_ptr;\n\n  void Reset()\n  {\n    size = 0;\n    shape = 0;\n    expected_data_occupancy = std::numeric_limits::max();\n    expected_metadata_occupancy = {};\n    partition_size = 0;\n    access_stats.clear();\n    parent_access_share = 0;\n    distributed_multicast = false;\n    content_accesses = 0;\n    fills = 0;\n    reads = 0;\n    updates = 0;\n    link_transfers = 0;\n    peer_accesses = 0;\n    peer_fills = 0;\n    subnest.resize(0);\n    replication_factor = 0;\n    avg_replication_factor = 0;\n    max_x_expansion = 0;\n    max_y_expansion = 0;\n    fanout = 0;\n    distributed_fanout = 0;\n    compressed = false;\n    has_metadata = false;\n    apply_rank_inner_to_outer = false; \n    parent_level = std::numeric_limits::max();\n    child_level = std::numeric_limits::max();\n    parent_level_ptr = NULL;\n    child_level_ptr = NULL;\n    child_level_metadata_occupancy_ratio = 0;\n    fine_grained_data_accesses.clear();\n    fine_grained_format_accesses.clear();\n    format_fills = {};\n    format_reads = {};\n    format_updates = {};\n    metadata_subnest.clear();\n    metadata_subtile_point_set.clear();\n    fiber_shape.clear();\n    coord_space_info.Clear();\n    tile_density = NULL;\n    expected_density = 0;\n  }\n\n  void Validate()\n  {\n    \/\/ std::uint64_t f = 0;\n    \/\/ for (std::uint64_t i = 0; i < fanout; i++)\n    \/\/ {\n    \/\/   if (accesses[i] != 0)\n    \/\/   {\n    \/\/     auto multicast_factor = i + 1;\n    \/\/     auto scatter_factor = scatter_factors[i];\n    \/\/     f += (multicast_factor * scatter_factor);\n    \/\/   }\n    \/\/ }\n\n    \/\/ if (f != fanout)\n    \/\/ {\n    \/\/   std::cerr << \"ERROR: sigma(multicast * scatter) != fanout.\" << std::endl;\n    \/\/   std::cerr << \"  dumping (multicast, scatter) pairs:\" << std::endl;\n    \/\/   for (std::uint64_t i = 0; i < fanout; i++)\n    \/\/   {\n    \/\/     if (accesses[i] != 0)\n    \/\/     {\n    \/\/       auto multicast_factor = i + 1;\n    \/\/       auto scatter_factor = scatter_factors[i];\n    \/\/       std::cerr << \"    \" << multicast_factor << \", \" << scatter_factor << std::endl;\n    \/\/     }\n    \/\/   }\n    \/\/   std::cerr << \"  sigma(multicast, scatter) = \" << f << std::endl;\n    \/\/   std::cerr << \"  fanout = \" << fanout << std::endl;\n    \/\/   exit(1);\n    \/\/ }\n  }\n\n  void SetDensityModel(std::shared_ptr tile_density_ptr)\n  {\n    tile_density = tile_density_ptr;\n  }\n\n  void SetTensorRepresentation(const sparse::PerDataSpaceCompressionInfo& compression_opt_spec);\n  void SetTensorRepresentation(); \/\/ for default dense tensors\n\n  std::string GetDataSpaceName() const { return problem::GetShape()->DataSpaceIDToName.at(dataspace_id);}\n  bool GetHasMetaData() const { return has_metadata;}\n  std::string GetDensityType() const\n  {\n    return tile_density->GetDistributionType();\n  }\n  std::string GetMetaDataFormatName() const;\n  std::uint64_t GetNumMetaDataRanks() const\n  {\n    if (! has_metadata) return 0;\n    else return metadata_models.size();\n  }\n  CoordinateSpaceTileInfo GetCoordinateSpaceInfo() const;\n  CoordinateSpaceTileInfo GetChildTileCoordinateSpaceInfo() const;\n\n  \/\/ do not use this unless super necessary,\n  \/\/ as density model interface change will break the logic external to sparse modeling step\n  std::shared_ptr GetTileDensityModel() const { return tile_density; }\n\n\n  \/\/ More involved getter functions\n  \/\/ get data tile occupancy\n  std::uint64_t GetMaxDataTileOccupancyByConfidence(const double confidence = 1.0) const;\n  double GetDataTileOccupancyProbability(const std::uint64_t occupancy) const;\n  double GetChildLevelDataTileOccupancyProbability(const std::uint64_t occupancy) const;\n  std::uint64_t GetMinDataTileOccupancy() const;\n\n  \/\/ get metadata tile occupancy\n  MetaDataTileOccupancy GetMetaDataTileOccupancyGivenDataTile(const CoordinateSpaceTileInfo& cur_coord_tile) const;\n  MetaDataTileOccupancy GetMaxMetaDataTileOccupancyByConfidence(const double confidence = 1.0) const;\n  double GetExpectedAggregatedMetaDataTileOccupancy() const;\n\n  \/\/ density value related\n  double GetMaxTileDensityByConfidence(const double confidence = 1.0) const;\n  double GetExpectedTileDensity() const;\n};\n\n\/\/\n\/\/ Compute info\n\/\/\n\nstruct ComputeInfo\n{\n  std::uint64_t replication_factor;      \/\/ number of spatial elements at this level.\n  double accesses;\n  double avg_replication_factor;\n  std::uint64_t max_replication_factor;\n  std::uint64_t max_x_expansion;\n  std::uint64_t max_y_expansion;\n  std::uint64_t compute_cycles;\n\n  \/\/ fine grained actions, names defined in operation-type.hpp\n  std::map fine_grained_accesses; \n  \n  ComputeInfo() { Reset(); }\n\n  void Reset()\n  {\n    replication_factor = 0;\n    avg_replication_factor = 0;\n    max_replication_factor = 0;\n    max_x_expansion = 0;\n    max_y_expansion = 0;\n    accesses = 0;\n    compute_cycles = 0;\n  }\n};\n\n\/\/ datatypes needed before transpose\n\/\/ indexing order: [datatype\/optype, nest_level]\ntypedef problem::PerDataSpace> CompoundDataMovementNest ; \ntypedef std::vector ComputeNest;\nstruct CompoundTileNest{\n   CompoundDataMovementNest compound_data_movement_info_nest;\n   ComputeNest compute_info_nest;\n};\n\n\n\/\/ datatypes needed after transpose\ntypedef problem::PerDataSpace CompoundDataMovementInfo;\n\n\/\/ indexing order: [nest_level, datatype\/optype]\nstruct CompoundTile{\n  CompoundDataMovementInfo data_movement_info;\n  ComputeInfo compute_info;\n};\n\ntypedef std::vector NestOfCompoundTiles;\ntypedef problem::PerDataSpace CompoundMask;\n\ntypedef problem::PerDataSpace> CompoundMaskNest;\ntypedef std::vector NestOfCompoundMasks;\n\n} \/\/ namespace\n<|endoftext|>"}
{"text":"#pragma once\n\n\/\/ C++ standard library\n#include \n\n\/\/ Armadillo\n#include \n\n\/\/ Mantella\n#include \n#include \n\nnamespace mant {\n  class SamplesSelection : public Printable {\n    public:\n      SamplesSelection(\n          std::unordered_map, double, Hash, IsEqual> samples,\n          arma::uword numberOfSelectedSamples);\n      \n      void select();\n      \n       std::unordered_map, double, Hash, IsEqual> getSelectedSamples() const;\n      \n      protected:\n        std::unordered_map, double, Hash, IsEqual> samples_;\n        \n        arma::uword numberOfSelectedSamples_;\n        std::unordered_map, double, Hash, IsEqual> selectedSamples_;\n        \n        virtual void selectImplementation() = 0;\n  };\n}Added default deconstructor#pragma once\n\n\/\/ C++ standard library\n#include \n\n\/\/ Armadillo\n#include \n\n\/\/ Mantella\n#include \n#include \n\nnamespace mant {\n  class SamplesSelection : public Printable {\n    public:\n      SamplesSelection(\n          std::unordered_map, double, Hash, IsEqual> samples,\n          arma::uword numberOfSelectedSamples);\n      \n      void select();\n      \n       std::unordered_map, double, Hash, IsEqual> getSelectedSamples() const;\n      \n      protected:\n        std::unordered_map, double, Hash, IsEqual> samples_;\n        \n        arma::uword numberOfSelectedSamples_;\n        std::unordered_map, double, Hash, IsEqual> selectedSamples_;\n        \n        virtual void selectImplementation() = 0;\n      virtual ~SamplesSelection() = default;\n  };\n}<|endoftext|>"}
{"text":"\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n\/\/$Id$\n\n#ifndef FEATURE_STYLE_PROCESSOR_HPP\n#define FEATURE_STYLE_PROCESSOR_HPP\n\n\/\/stl\n#include \n\/\/ boost\n#include \n\/\/ mapnik\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace mapnik\n{       \n   template \n   class feature_style_processor \n   {\n         struct symbol_dispatch : public boost::static_visitor<>\n         {\n               symbol_dispatch (Processor & output,\n                                Feature const& f, \n                                proj_transform const& prj_trans)\n                  : output_(output),\n                    f_(f),\n                    prj_trans_(prj_trans)  {}\n            \n               template \n               void operator () (T const& sym) const\n               {\n                  output_.process(sym,f_,prj_trans_);\n               }\n            \n               Processor & output_;\n               Feature const& f_;\n               proj_transform const& prj_trans_;\n         };\n      public:\n         feature_style_processor(Map const& m)\n            : m_(m) {}\n\t\n         \n         void apply()\n         {\n#ifdef MAPNIK_DEBUG           \n            boost::progress_timer t(std::clog);  \n#endif          \n            Processor & p = static_cast(*this);\n            p.start_map_processing(m_);\n                       \n            try\n            {\n               projection proj(m_.srs()); \/\/ map projection\n               double scale_denom = scale_denominator(m_,proj.is_geographic());\n#ifdef MAPNIK_DEBUG\n               std::clog << \"scale denominator = \" << scale_denom << \"\\n\";\n#endif\n               std::vector::const_iterator itr = m_.layers().begin();\n               std::vector::const_iterator end = m_.layers().end();\n            \n               while (itr != end)\n               {\n                  if (itr->isVisible(scale_denom))\n                  {\n                     apply_to_layer(*itr, p, proj, scale_denom);\n                  }\n                  ++itr;\n               }\n            }\n            catch (proj_init_error& ex)\n            {\n               std::clog << \"proj_init_error:\" << ex.what() << \"\\n\"; \n            }\n            \n            p.end_map_processing(m_);\n         }\t\n      private:\n         void apply_to_layer(Layer const& lay, Processor & p, \n                             projection const& proj0,double scale_denom)\n         {\n            p.start_layer_processing(lay);\n            boost::shared_ptr ds=lay.datasource();\n            if (ds)\n            {\n               Envelope const& ext=m_.getCurrentExtent();\n               projection proj1(lay.srs());\n               proj_transform prj_trans(proj0,proj1);\n\n               Envelope layer_ext = lay.envelope();\n               double lx0 = layer_ext.minx();\n               double ly0 = layer_ext.miny();\n               double lz0 = 0.0;\n               double lx1 = layer_ext.maxx();\n               double ly1 = layer_ext.maxy();\n               double lz1 = 0.0;\n               \/\/ back project layers extent into main map projection\n               prj_trans.backward(lx0,ly0,lz0);\n               prj_trans.backward(lx1,ly1,lz1);\n               \/\/ clip query bbox\n               lx0 = std::max(ext.minx(),lx0);\n               ly0 = std::max(ext.miny(),ly0);\n               lx1 = std::min(ext.maxx(),lx1);\n               ly1 = std::min(ext.maxy(),ly1);\n               \n               prj_trans.forward(lx0,ly0,lz0);\n               prj_trans.forward(lx1,ly1,lz1);\n               Envelope bbox(lx0,ly0,lx1,ly1);\n               double resolution = m_.getWidth()\/bbox.width();\n               \n               std::vector const& style_names = lay.styles();\n               std::vector::const_iterator stylesIter = style_names.begin();\n               std::vector::const_iterator stylesEnd = style_names.end();\n                \n               while (stylesIter != stylesEnd)\n               {\n                  std::set names;\n                  attribute_collector collector(names);\n                  std::vector if_rules;\n                  std::vector else_rules;\n                    \n                  bool active_rules=false;\n                  \n                  feature_type_style const& style=m_.find_style(*stylesIter++);\n                  \n                  query q(bbox,resolution); \/\/BBOX query\n\n                  const std::vector& rules=style.get_rules();\n                  std::vector::const_iterator ruleIter=rules.begin();\n                  std::vector::const_iterator ruleEnd=rules.end();\n                                        \n                  while (ruleIter!=ruleEnd)\n                  {\n                     if (ruleIter->active(scale_denom))\n                     {\n                        active_rules=true;\n                        ruleIter->accept(collector);\n\n                        if (ruleIter->has_else_filter())\n                        {\n                           else_rules.push_back(const_cast(&(*ruleIter)));\n                        }\n                        else\n                        {\n                           if_rules.push_back(const_cast(&(*ruleIter))); \t\t    \n                        }\n                     }\n                     ++ruleIter;\n                  }\n                  std::set::const_iterator namesIter=names.begin();\n                  std::set::const_iterator namesEnd =names.end();\n                    \n                  \/\/ push all property names\n                  while (namesIter!=namesEnd)\n                  {\n                     q.add_property_name(*namesIter);\n                     ++namesIter;\n                  }\n                  if (active_rules)\n                  {\n                     featureset_ptr fs=ds->features(q);\n                     if (fs)\n                     {   \t    \n                        feature_ptr feature;\n                        while ((feature = fs->next()))\n                        {\t\t   \n                           bool do_else=true;\t\t    \n                           std::vector::const_iterator itr=if_rules.begin();\n                           std::vector::const_iterator end=if_rules.end();\n                           while (itr != end)\n                           {\n                              filter_ptr const& filter=(*itr)->get_filter();    \n                              if (filter->pass(*feature))\n                              {   \n                                 do_else=false;\n                                 const symbolizers& symbols = (*itr)->get_symbolizers();\n                                 symbolizers::const_iterator symIter=symbols.begin();\n                                 symbolizers::const_iterator symEnd =symbols.end();\n                                 while (symIter != symEnd)\n                                 {   \n                                    boost::apply_visitor\n                                       (symbol_dispatch(p,*feature,prj_trans),*symIter++);\n                                 }\n                              }\t\t\t    \n                              ++itr;\n                           }\n                           if (do_else)\n                           {\n                              \/\/else filter\n                              std::vector::const_iterator itr=\n                                 else_rules.begin();\n                              std::vector::const_iterator end=\n                                 else_rules.end();\n                              while (itr != end)\n                              {\n                                 const symbolizers& symbols = (*itr)->get_symbolizers();\n                                 symbolizers::const_iterator symIter= symbols.begin();\n                                 symbolizers::const_iterator symEnd = symbols.end();\n                                        \n                                 while (symIter!=symEnd)\n                                 {\n                                    boost::apply_visitor\n                                       (symbol_dispatch(p,*feature,prj_trans),\n                                        *symIter++);\n                                 }\n                                 ++itr;\n                              }\n                           }\t  \n                        }\n                     }\n                  }\n               }\n                \n            }\n            p.end_layer_processing(lay);\n         }\t\n         Map const& m_;\n   };\n}\n\n#endif \/\/FEATURE_STYLE_PROCESSOR_HPP\nuser for loops instead of while, some cleanups\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n\/\/$Id$\n\n#ifndef FEATURE_STYLE_PROCESSOR_HPP\n#define FEATURE_STYLE_PROCESSOR_HPP\n\n\/\/stl\n#include \n\/\/ boost\n#include \n\/\/ mapnik\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace mapnik\n{       \n   template \n   class feature_style_processor \n   {\n         struct symbol_dispatch : public boost::static_visitor<>\n         {\n               symbol_dispatch (Processor & output,\n                                Feature const& f, \n                                proj_transform const& prj_trans)\n                  : output_(output),\n                    f_(f),\n                    prj_trans_(prj_trans)  {}\n            \n               template \n               void operator () (T const& sym) const\n               {\n                  output_.process(sym,f_,prj_trans_);\n               }\n            \n               Processor & output_;\n               Feature const& f_;\n               proj_transform const& prj_trans_;\n         };\n      public:\n         feature_style_processor(Map const& m)\n            : m_(m) {}\n\t\n         \n         void apply()\n         {\n#ifdef MAPNIK_DEBUG           \n            boost::progress_timer t(std::clog);  \n#endif          \n            Processor & p = static_cast(*this);\n            p.start_map_processing(m_);\n                       \n            try\n            {\n               projection proj(m_.srs()); \/\/ map projection\n               double scale_denom = scale_denominator(m_,proj.is_geographic());\n#ifdef MAPNIK_DEBUG\n               std::clog << \"scale denominator = \" << scale_denom << \"\\n\";\n#endif\n               std::vector::const_iterator itr = m_.layers().begin();\n               std::vector::const_iterator end = m_.layers().end();\n            \n               while (itr != end)\n               {\n                  if (itr->isVisible(scale_denom))\n                  {\n                     apply_to_layer(*itr, p, proj, scale_denom);\n                  }\n                  ++itr;\n               }\n            }\n            catch (proj_init_error& ex)\n            {\n               std::clog << \"proj_init_error:\" << ex.what() << \"\\n\"; \n            }\n            \n            p.end_map_processing(m_);\n         }\t\n      private:\n         void apply_to_layer(Layer const& lay, Processor & p, \n                             projection const& proj0,double scale_denom)\n         {\n            p.start_layer_processing(lay);\n            boost::shared_ptr ds=lay.datasource();\n            if (ds)\n            {\n               Envelope const& ext=m_.getCurrentExtent();\n               projection proj1(lay.srs());\n               proj_transform prj_trans(proj0,proj1);\n\n               Envelope layer_ext = lay.envelope();\n               double lx0 = layer_ext.minx();\n               double ly0 = layer_ext.miny();\n               double lz0 = 0.0;\n               double lx1 = layer_ext.maxx();\n               double ly1 = layer_ext.maxy();\n               double lz1 = 0.0;\n               \/\/ back project layers extent into main map projection\n               prj_trans.backward(lx0,ly0,lz0);\n               prj_trans.backward(lx1,ly1,lz1);\n               \/\/ clip query bbox\n               lx0 = std::max(ext.minx(),lx0);\n               ly0 = std::max(ext.miny(),ly0);\n               lx1 = std::min(ext.maxx(),lx1);\n               ly1 = std::min(ext.maxy(),ly1);\n               \n               prj_trans.forward(lx0,ly0,lz0);\n               prj_trans.forward(lx1,ly1,lz1);\n               Envelope bbox(lx0,ly0,lx1,ly1);\n               double resolution = m_.getWidth()\/bbox.width();\n               query q(bbox,resolution); \/\/BBOX query\n               \n               std::vector const& style_names = lay.styles();\n               std::vector::const_iterator stylesIter = style_names.begin();\n               std::vector::const_iterator stylesEnd = style_names.end(); \n               for (;stylesIter != stylesEnd; ++stylesIter)\n               {\n                  std::set names;\n                  attribute_collector collector(names);\n                  std::vector if_rules;\n                  std::vector else_rules;\n                    \n                  bool active_rules=false;\n                  feature_type_style const& style=m_.find_style(*stylesIter);\n                  const std::vector& rules=style.get_rules();\n                  std::vector::const_iterator ruleIter=rules.begin();\n                  std::vector::const_iterator ruleEnd=rules.end();\n                                        \n                  for (;ruleIter!=ruleEnd;++ruleIter)\n                  {\n                     if (ruleIter->active(scale_denom))\n                     {\n                        active_rules=true;\n                        ruleIter->accept(collector);\n\n                        if (ruleIter->has_else_filter())\n                        {\n                           else_rules.push_back(const_cast(&(*ruleIter)));\n                        }\n                        else\n                        {\n                           if_rules.push_back(const_cast(&(*ruleIter))); \t\t    \n                        }\n                     }\n                  }\n                  std::set::const_iterator namesIter=names.begin();\n                  std::set::const_iterator namesEnd =names.end();\n                    \n                  \/\/ push all property names\n                  for (;namesIter!=namesEnd;++namesIter)\n                  {\n                     q.add_property_name(*namesIter);\n                  }\n                  if (active_rules)\n                  {\n                     featureset_ptr fs=ds->features(q);\n                     if (fs)\n                     {   \t    \n                        feature_ptr feature;\n                        while ((feature = fs->next()))\n                        {\t\t   \n                           bool do_else=true;\t\t    \n                           std::vector::const_iterator itr=if_rules.begin();\n                           std::vector::const_iterator end=if_rules.end();\n                           for (;itr != end;++itr)\n                           {\n                              filter_ptr const& filter=(*itr)->get_filter();    \n                              if (filter->pass(*feature))\n                              {   \n                                 do_else=false;\n                                 const symbolizers& symbols = (*itr)->get_symbolizers();\n                                 symbolizers::const_iterator symIter=symbols.begin();\n                                 symbolizers::const_iterator symEnd =symbols.end();\n                                 for (;symIter != symEnd;++symIter)\n                                 {   \n                                    boost::apply_visitor\n                                       (symbol_dispatch(p,*feature,prj_trans),*symIter);\n                                 }\n                              }\t\t\t    \n                           }\n                           if (do_else)\n                           {\n                              \/\/else filter\n                              std::vector::const_iterator itr=\n                                 else_rules.begin();\n                              std::vector::const_iterator end=\n                                 else_rules.end();\n                              for (;itr != end;++itr)\n                              {\n                                 const symbolizers& symbols = (*itr)->get_symbolizers();\n                                 symbolizers::const_iterator symIter= symbols.begin();\n                                 symbolizers::const_iterator symEnd = symbols.end();\n                                        \n                                 for (;symIter!=symEnd;++symIter)\n                                 {\n                                    boost::apply_visitor\n                                       (symbol_dispatch(p,*feature,prj_trans),*symIter);\n                                 }\n                              }\n                           }\t  \n                        }\n                     }\n                  }\n               }               \n            }\n            p.end_layer_processing(lay);\n         }\t\n         Map const& m_;\n   };\n}\n\n#endif \/\/FEATURE_STYLE_PROCESSOR_HPP\n<|endoftext|>"}
{"text":"don't need typename outside a template<|endoftext|>"}
{"text":"\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n\/\/$Id$\n\n#ifndef FEATURE_STYLE_PROCESSOR_HPP\n#define FEATURE_STYLE_PROCESSOR_HPP\n\n\/\/stl\n#include \n\/\/ boost\n#include \n\/\/ mapnik\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace mapnik\n{       \n   template \n   class feature_style_processor \n   {\n         struct symbol_dispatch : public boost::static_visitor<>\n         {\n               symbol_dispatch (Processor & output,\n                                Feature const& f, \n                                proj_transform const& prj_trans)\n                  : output_(output),\n                    f_(f),\n                    prj_trans_(prj_trans)  {}\n            \n               template \n               void operator () (T const& sym) const\n               {\n                  output_.process(sym,f_,prj_trans_);\n               }\n            \n               Processor & output_;\n               Feature const& f_;\n               proj_transform const& prj_trans_;\n         };\n      public:\n         feature_style_processor(Map const& m)\n            : m_(m) {}\n\t\n         void apply()\n         {\n#ifdef MAPNIK_DEBUG           \n            boost::progress_timer t(std::clog);  \n#endif          \n            Processor & p = static_cast(*this);\n            p.start_map_processing(m_);\n                       \n            try\n            {\n               projection proj(m_.srs()); \/\/ map projection\n               double scale_denom = scale_denominator(m_,proj.is_geographic());\n#ifdef MAPNIK_DEBUG\n               std::clog << \"scale denominator = \" << scale_denom << \"\\n\";\n#endif\n               std::vector::const_iterator itr = m_.layers().begin();\n               std::vector::const_iterator end = m_.layers().end();\n            \n               while (itr != end)\n               {\n                  if (itr->isVisible(scale_denom))\n                  {\n                     apply_to_layer(*itr, p, proj, scale_denom);\n                  }\n                  ++itr;\n               }\n            }\n            catch (proj_init_error& ex)\n            {\n               std::clog << ex.what() << \"\\n\"; \n            }\n\n            p.end_map_processing(m_);\n         }\t\n      private:\n         void apply_to_layer(Layer const& lay, Processor & p, \n                             projection const& proj0,double scale_denom)\n         {\n            p.start_layer_processing(lay);\n            boost::shared_ptr ds=lay.datasource();\n            if (ds)\n            {\n               Envelope const& ext=m_.getCurrentExtent();\n              \n               projection proj1(lay.srs());\n               proj_transform prj_trans(proj0,proj1);\n               \n               double x0 = ext.minx();\n               double y0 = ext.miny();\n               double z0 = 0.0;\n               double x1 = ext.maxx();\n               double y1 = ext.maxy();\n               double z1 = 0.0;\n               prj_trans.forward(x0,y0,z0);\n               prj_trans.forward(x1,y1,z1);\n               Envelope bbox(x0,y0,x1,y1);\n\n               double resolution = m_.getWidth()\/bbox.width();\n#ifdef MAPNIK_DEBUG\n               std::clog << bbox << \"\\n\";\n#endif                \n               std::vector const& style_names = lay.styles();\n               std::vector::const_iterator stylesIter = style_names.begin();\n               std::vector::const_iterator stylesEnd = style_names.end();\n                \n               while (stylesIter != stylesEnd)\n               {\n                  std::set names;\n                  attribute_collector collector(names);\n                  std::vector if_rules;\n                  std::vector else_rules;\n                    \n                  bool active_rules=false;\n                    \n                  feature_type_style const& style=m_.find_style(*stylesIter++);\n                  \n                  query q(bbox,resolution); \/\/BBOX query\n\n                  const std::vector& rules=style.get_rules();\n                  std::vector::const_iterator ruleIter=rules.begin();\n                  std::vector::const_iterator ruleEnd=rules.end();\n                                        \n                  while (ruleIter!=ruleEnd)\n                  {\n                     if (ruleIter->active(scale_denom))\n                     {\n                        active_rules=true;\n                        ruleIter->accept(collector);\n\n                        if (ruleIter->has_else_filter())\n                        {\n                           else_rules.push_back(const_cast(&(*ruleIter)));\n                        }\n                        else\n                        {\n                           if_rules.push_back(const_cast(&(*ruleIter))); \t\t    \n                        }\n                     }\n                     ++ruleIter;\n                  }\n                  std::set::const_iterator namesIter=names.begin();\n                  std::set::const_iterator namesEnd =names.end();\n                    \n                  \/\/ push all property names\n                  while (namesIter!=namesEnd)\n                  {\n                     q.add_property_name(*namesIter);\n                     ++namesIter;\n                  }\n                  if (active_rules)\n                  {\n                     featureset_ptr fs=ds->features(q);\n                     if (fs)\n                     {   \t    \n                        feature_ptr feature;\n                        while ((feature = fs->next()))\n                        {\t\t   \n                           bool do_else=true;\t\t    \n                           std::vector::const_iterator itr=if_rules.begin();\n                           std::vector::const_iterator end=if_rules.end();\n                           while (itr != end)\n                           {\n                              filter_ptr const& filter=(*itr)->get_filter();    \n                              if (filter->pass(*feature))\n                              {   \n                                 do_else=false;\n                                 const symbolizers& symbols = (*itr)->get_symbolizers();\n                                 symbolizers::const_iterator symIter=symbols.begin();\n                                 symbolizers::const_iterator symEnd =symbols.end();\n                                 while (symIter != symEnd)\n                                 {   \n                                    boost::apply_visitor\n                                       (symbol_dispatch(p,*feature,prj_trans),*symIter++);\n                                 }\n                              }\t\t\t    \n                              ++itr;\n                           }\n                           if (do_else)\n                           {\n                              \/\/else filter\n                              std::vector::const_iterator itr=\n                                 else_rules.begin();\n                              std::vector::const_iterator end=\n                                 else_rules.end();\n                              while (itr != end)\n                              {\n                                 const symbolizers& symbols = (*itr)->get_symbolizers();\n                                 symbolizers::const_iterator symIter= symbols.begin();\n                                 symbolizers::const_iterator symEnd = symbols.end();\n                                        \n                                 while (symIter!=symEnd)\n                                 {\n                                    boost::apply_visitor\n                                       (symbol_dispatch(p,*feature,prj_trans),\n                                        *symIter++);\n                                 }\n                                 ++itr;\n                              }\n                           }\t  \n                        }\n                     }\n                  }\n               }\n                \n            }\n            p.end_layer_processing(lay);\n         }\t\n         Map const& m_;\n   };\n}\n\n#endif \/\/FEATURE_STYLE_PROCESSOR_HPP\nclip query bbox to layer's extent\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n\/\/$Id$\n\n#ifndef FEATURE_STYLE_PROCESSOR_HPP\n#define FEATURE_STYLE_PROCESSOR_HPP\n\n\/\/stl\n#include \n\/\/ boost\n#include \n\/\/ mapnik\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace mapnik\n{       \n   template \n   class feature_style_processor \n   {\n         struct symbol_dispatch : public boost::static_visitor<>\n         {\n               symbol_dispatch (Processor & output,\n                                Feature const& f, \n                                proj_transform const& prj_trans)\n                  : output_(output),\n                    f_(f),\n                    prj_trans_(prj_trans)  {}\n            \n               template \n               void operator () (T const& sym) const\n               {\n                  output_.process(sym,f_,prj_trans_);\n               }\n            \n               Processor & output_;\n               Feature const& f_;\n               proj_transform const& prj_trans_;\n         };\n      public:\n         feature_style_processor(Map const& m)\n            : m_(m) {}\n\t\n         \n         void apply()\n         {\n#ifdef MAPNIK_DEBUG           \n            boost::progress_timer t(std::clog);  \n#endif          \n            Processor & p = static_cast(*this);\n            p.start_map_processing(m_);\n                       \n            try\n            {\n               projection proj(m_.srs()); \/\/ map projection\n               double scale_denom = scale_denominator(m_,proj.is_geographic());\n#ifdef MAPNIK_DEBUG\n               std::clog << \"scale denominator = \" << scale_denom << \"\\n\";\n#endif\n               std::vector::const_iterator itr = m_.layers().begin();\n               std::vector::const_iterator end = m_.layers().end();\n            \n               while (itr != end)\n               {\n                  if (itr->isVisible(scale_denom))\n                  {\n                     apply_to_layer(*itr, p, proj, scale_denom);\n                  }\n                  ++itr;\n               }\n            }\n            catch (proj_init_error& ex)\n            {\n               std::clog << \"proj_init_error:\" << ex.what() << \"\\n\"; \n            }\n            \n            p.end_map_processing(m_);\n         }\t\n      private:\n         void apply_to_layer(Layer const& lay, Processor & p, \n                             projection const& proj0,double scale_denom)\n         {\n            p.start_layer_processing(lay);\n            boost::shared_ptr ds=lay.datasource();\n            if (ds)\n            {\n               Envelope const& ext=m_.getCurrentExtent();\n               projection proj1(lay.srs());\n               proj_transform prj_trans(proj0,proj1);\n\n               Envelope layer_ext = lay.envelope();\n               double lx0 = layer_ext.minx();\n               double ly0 = layer_ext.miny();\n               double lz0 = 0.0;\n               double lx1 = layer_ext.maxx();\n               double ly1 = layer_ext.maxy();\n               double lz1 = 0.0;\n               \/\/ back project layers extent into main map projection\n               prj_trans.backward(lx0,ly0,lz0);\n               prj_trans.backward(lx1,ly1,lz1);\n               \/\/ clip query bbox\n               lx0 = std::max(ext.minx(),lx0);\n               ly0 = std::max(ext.miny(),ly0);\n               lx1 = std::min(ext.maxx(),lx1);\n               ly1 = std::min(ext.maxy(),ly1);\n               \n               prj_trans.forward(lx0,ly0,lz0);\n               prj_trans.forward(lx1,ly1,lz1);\n               Envelope bbox(lx0,ly0,lx1,ly1);\n               double resolution = m_.getWidth()\/bbox.width();\n               \n               std::vector const& style_names = lay.styles();\n               std::vector::const_iterator stylesIter = style_names.begin();\n               std::vector::const_iterator stylesEnd = style_names.end();\n                \n               while (stylesIter != stylesEnd)\n               {\n                  std::set names;\n                  attribute_collector collector(names);\n                  std::vector if_rules;\n                  std::vector else_rules;\n                    \n                  bool active_rules=false;\n                  \n                  feature_type_style const& style=m_.find_style(*stylesIter++);\n                  \n                  query q(bbox,resolution); \/\/BBOX query\n\n                  const std::vector& rules=style.get_rules();\n                  std::vector::const_iterator ruleIter=rules.begin();\n                  std::vector::const_iterator ruleEnd=rules.end();\n                                        \n                  while (ruleIter!=ruleEnd)\n                  {\n                     if (ruleIter->active(scale_denom))\n                     {\n                        active_rules=true;\n                        ruleIter->accept(collector);\n\n                        if (ruleIter->has_else_filter())\n                        {\n                           else_rules.push_back(const_cast(&(*ruleIter)));\n                        }\n                        else\n                        {\n                           if_rules.push_back(const_cast(&(*ruleIter))); \t\t    \n                        }\n                     }\n                     ++ruleIter;\n                  }\n                  std::set::const_iterator namesIter=names.begin();\n                  std::set::const_iterator namesEnd =names.end();\n                    \n                  \/\/ push all property names\n                  while (namesIter!=namesEnd)\n                  {\n                     q.add_property_name(*namesIter);\n                     ++namesIter;\n                  }\n                  if (active_rules)\n                  {\n                     featureset_ptr fs=ds->features(q);\n                     if (fs)\n                     {   \t    \n                        feature_ptr feature;\n                        while ((feature = fs->next()))\n                        {\t\t   \n                           bool do_else=true;\t\t    \n                           std::vector::const_iterator itr=if_rules.begin();\n                           std::vector::const_iterator end=if_rules.end();\n                           while (itr != end)\n                           {\n                              filter_ptr const& filter=(*itr)->get_filter();    \n                              if (filter->pass(*feature))\n                              {   \n                                 do_else=false;\n                                 const symbolizers& symbols = (*itr)->get_symbolizers();\n                                 symbolizers::const_iterator symIter=symbols.begin();\n                                 symbolizers::const_iterator symEnd =symbols.end();\n                                 while (symIter != symEnd)\n                                 {   \n                                    boost::apply_visitor\n                                       (symbol_dispatch(p,*feature,prj_trans),*symIter++);\n                                 }\n                              }\t\t\t    \n                              ++itr;\n                           }\n                           if (do_else)\n                           {\n                              \/\/else filter\n                              std::vector::const_iterator itr=\n                                 else_rules.begin();\n                              std::vector::const_iterator end=\n                                 else_rules.end();\n                              while (itr != end)\n                              {\n                                 const symbolizers& symbols = (*itr)->get_symbolizers();\n                                 symbolizers::const_iterator symIter= symbols.begin();\n                                 symbolizers::const_iterator symEnd = symbols.end();\n                                        \n                                 while (symIter!=symEnd)\n                                 {\n                                    boost::apply_visitor\n                                       (symbol_dispatch(p,*feature,prj_trans),\n                                        *symIter++);\n                                 }\n                                 ++itr;\n                              }\n                           }\t  \n                        }\n                     }\n                  }\n               }\n                \n            }\n            p.end_layer_processing(lay);\n         }\t\n         Map const& m_;\n   };\n}\n\n#endif \/\/FEATURE_STYLE_PROCESSOR_HPP\n<|endoftext|>"}
{"text":"\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_SVG_RENDERER_HPP\n#define MAPNIK_SVG_RENDERER_HPP\n\n\/\/ mapnik\n#include \n#include \n#include \n#include \n#include \n#include \n#include               \/\/ for rule, symbolizers\n#include      \/\/ for box2d\n#include      \/\/ for color\n#include     \/\/ for view_transform\n#include   \/\/ for composite_mode_e\n#include \n#include \n#include \n#include \n#include \n\n\/\/ stl\n#include \n\n\/\/ fwd declaration to avoid depedence on agg headers\nnamespace agg { struct trans_affine; }\n\n\/\/ fwd declarations to speed up compile\nnamespace mapnik {\n  class Map;\n  class feature_impl;\n  class feature_type_style;\n  class label_collision_detector4;\n  class layer;\n  class marker;\n  class proj_transform;\n}\n\nnamespace mapnik\n{\n\/\/ parameterized with the type of output iterator it will use for output.\n\/\/ output iterators add more flexibility than streams, because iterators\n\/\/ can target many other output destinations besides streams.\ntemplate \nclass MAPNIK_DECL svg_renderer : public feature_style_processor >,\n                                 private mapnik::noncopyable\n{\npublic:\n    using processor_impl_type = svg_renderer;\n    svg_renderer(Map const& m, OutputIterator& output_iterator, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0);\n    svg_renderer(Map const& m, request const& req, attributes const& vars, OutputIterator& output_iterator, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0);\n    ~svg_renderer();\n\n    void start_map_processing(Map const& map);\n    void end_map_processing(Map const& map);\n    void start_layer_processing(layer const& lay, box2d const& query_extent);\n    void end_layer_processing(layer const& lay);\n    void start_style_processing(feature_type_style const& \/*st*\/) {}\n    void end_style_processing(feature_type_style const& \/*st*\/) {}\n\n    \/*!\n     * @brief Overloads that process each kind of symbolizer individually.\n     *\/\n    void process(point_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(line_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(line_pattern_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(polygon_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(polygon_pattern_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(raster_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(shield_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(text_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(building_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(markers_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(debug_symbolizer const& \/*sym*\/,\n                 mapnik::feature_impl & \/*feature*\/,\n                 proj_transform const& \/*prj_trans*\/) {}\n    void process(group_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n\n    \/\/ Overload that process the whole set of symbolizers of a rule.\n    \/\/ return true, meaning that this renderer can process multiple symbolizers.\n    bool process(rule::symbolizers const& syms,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n\n    void painted(bool)\n    {\n        \/\/ nothing to do\n    }\n\n    inline eAttributeCollectionPolicy attribute_collection_policy() const\n    {\n        return DEFAULT;\n    }\n\n    inline double scale_factor() const\n    {\n        return common_.scale_factor_;\n    }\n\n    inline attributes const& variables() const\n    {\n        return common_.vars_;\n    }\n\n    inline OutputIterator& get_output_iterator()\n    {\n        return output_iterator_;\n    }\n\n    inline const OutputIterator& get_output_iterator() const\n    {\n        return output_iterator_;\n    }\n\nprivate:\n    OutputIterator& output_iterator_;\n    svg::path_output_attributes path_attributes_;\n    svg::svg_generator generator_;\n    bool painted_;\n    renderer_common common_;\n\n\n    \/\/ Visitor that makes the calls to process each symbolizer when stored in a variant.\n    \/\/ This object follows the model of that found in feature_style_processor. It appears here, because\n    \/\/ the logic that iterates over the set of symbolizer has been moved to an SVG renderer's internal\n    \/\/ method.\n    struct symbol_dispatch : public util::static_visitor<>\n    {\n        symbol_dispatch(svg_renderer& processor,\n                        mapnik::feature_impl & feature,\n                        proj_transform const& prj_trans)\n            : processor_(processor),\n              feature_(feature),\n              prj_trans_(prj_trans) {}\n\n        template \n        void operator()(Symbolizer const& sym) const\n        {\n            processor_.process(sym, feature_, prj_trans_);\n        }\n\n        svg_renderer& processor_;\n        mapnik::feature_impl & feature_;\n        proj_transform const& prj_trans_;\n    };\n};\n}\n\n#endif \/\/ MAPNIK_SVG_RENDERER_HPP\nenable painted for svg_renderer\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_SVG_RENDERER_HPP\n#define MAPNIK_SVG_RENDERER_HPP\n\n\/\/ mapnik\n#include \n#include \n#include \n#include \n#include \n#include \n#include               \/\/ for rule, symbolizers\n#include      \/\/ for box2d\n#include      \/\/ for color\n#include     \/\/ for view_transform\n#include   \/\/ for composite_mode_e\n#include \n#include \n#include \n#include \n#include \n\n\/\/ stl\n#include \n\n\/\/ fwd declaration to avoid depedence on agg headers\nnamespace agg { struct trans_affine; }\n\n\/\/ fwd declarations to speed up compile\nnamespace mapnik {\n  class Map;\n  class feature_impl;\n  class feature_type_style;\n  class label_collision_detector4;\n  class layer;\n  class marker;\n  class proj_transform;\n}\n\nnamespace mapnik\n{\n\/\/ parameterized with the type of output iterator it will use for output.\n\/\/ output iterators add more flexibility than streams, because iterators\n\/\/ can target many other output destinations besides streams.\ntemplate \nclass MAPNIK_DECL svg_renderer : public feature_style_processor >,\n                                 private mapnik::noncopyable\n{\npublic:\n    using processor_impl_type = svg_renderer;\n    svg_renderer(Map const& m, OutputIterator& output_iterator, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0);\n    svg_renderer(Map const& m, request const& req, attributes const& vars, OutputIterator& output_iterator, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0);\n    ~svg_renderer();\n\n    void start_map_processing(Map const& map);\n    void end_map_processing(Map const& map);\n    void start_layer_processing(layer const& lay, box2d const& query_extent);\n    void end_layer_processing(layer const& lay);\n    void start_style_processing(feature_type_style const& \/*st*\/) {}\n    void end_style_processing(feature_type_style const& \/*st*\/) {}\n\n    \/*!\n     * @brief Overloads that process each kind of symbolizer individually.\n     *\/\n    void process(point_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(line_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(line_pattern_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(polygon_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(polygon_pattern_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(raster_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(shield_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(text_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(building_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(markers_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(debug_symbolizer const& \/*sym*\/,\n                 mapnik::feature_impl & \/*feature*\/,\n                 proj_transform const& \/*prj_trans*\/) {}\n    void process(group_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n\n    \/\/ Overload that process the whole set of symbolizers of a rule.\n    \/\/ return true, meaning that this renderer can process multiple symbolizers.\n    bool process(rule::symbolizers const& syms,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n\n    bool painted() const\n    {\n        return painted_;\n    }\n\n    void painted(bool painted)\n    {\n        painted_ = painted;\n    }\n\n    inline eAttributeCollectionPolicy attribute_collection_policy() const\n    {\n        return DEFAULT;\n    }\n\n    inline double scale_factor() const\n    {\n        return common_.scale_factor_;\n    }\n\n    inline attributes const& variables() const\n    {\n        return common_.vars_;\n    }\n\n    inline OutputIterator& get_output_iterator()\n    {\n        return output_iterator_;\n    }\n\n    inline const OutputIterator& get_output_iterator() const\n    {\n        return output_iterator_;\n    }\n\nprivate:\n    OutputIterator& output_iterator_;\n    svg::path_output_attributes path_attributes_;\n    svg::svg_generator generator_;\n    bool painted_;\n    renderer_common common_;\n\n\n    \/\/ Visitor that makes the calls to process each symbolizer when stored in a variant.\n    \/\/ This object follows the model of that found in feature_style_processor. It appears here, because\n    \/\/ the logic that iterates over the set of symbolizer has been moved to an SVG renderer's internal\n    \/\/ method.\n    struct symbol_dispatch : public util::static_visitor<>\n    {\n        symbol_dispatch(svg_renderer& processor,\n                        mapnik::feature_impl & feature,\n                        proj_transform const& prj_trans)\n            : processor_(processor),\n              feature_(feature),\n              prj_trans_(prj_trans) {}\n\n        template \n        void operator()(Symbolizer const& sym) const\n        {\n            processor_.process(sym, feature_, prj_trans_);\n        }\n\n        svg_renderer& processor_;\n        mapnik::feature_impl & feature_;\n        proj_transform const& prj_trans_;\n    };\n};\n}\n\n#endif \/\/ MAPNIK_SVG_RENDERER_HPP\n<|endoftext|>"}
{"text":"\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n\/\/ RUN: cat %s | %built_cling -fno-rtti 2>&1 | FileCheck %s\n\/\/ Test Lookup::Named and Namespace, used in quick simple lookups.\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/LookupHelper.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/AST\/Tag.h\"\n\n#include \n\nusing namespace cling;\nusing namespace llvm;\n\n.rawInput 1\n\nenum class E {};\nclass C {};\n\nnamespace N {\nenum class Inside_E {};\nclass C {};\n}\n\n.rawInput 0\n\n\nclang::Sema& S = gCling->getSema();\nconst LookupHelper& lookup = gCling->getLookupHelper();\nLookupHelper::DiagSetting diags = LookupHelper::WithDiagnostics;\n\nconst clang::TagDecl *tagdecl{nullptr};\n\ntagdecl = utils::Lookup::Tag(&S, \"E\", nullptr);\ntagdecl\n\/\/CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}\ntagdecl->getQualifiedNameAsString().c_str()\n\/\/CHECK-NEXT: ({{[^)]+}}) \"E\"\n\ntagdecl = utils::Lookup::Tag(&S, \"C\", nullptr);\ntagdecl\n\/\/CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}\ntagdecl->getQualifiedNameAsString().c_str()\n\/\/CHECK-NEXT: ({{[^)]+}}) \"C\"\n\nconst clang::NamedDecl *nameddecl{nullptr};\n\nnameddecl = utils::Lookup::Named(&S, \"N\", nullptr);\nnameddecl\n\/\/CHECK: (const clang::NamedDecl *) 0x{{[1-9a-f][0-9a-f]*$}}\ndecl->getQualifiedNameAsString().c_str()\n\/\/CHECK-NEXT: ({{[^)]+}}) \"N\"\n\nconst clang::DeclContext *context = dyn_cast(decl);\ncontext\n\/\/CHECK: (const clang::DeclContext *) 0x{{[1-9a-f][0-9a-f]*$}}\n\ndecl = utils::Lookup::Tag(&S, \"E\", context);\ndecl\n\/\/CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}\ndecl->getQualifiedNameAsString().c_str()\n\/\/CHECK-NEXT: ({{[^)]+}}) \"N::E\"\n\ndecl = utils::Lookup::Tag(&S, \"C\", context);\ndecl\n\/\/CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}\ndecl->getQualifiedNameAsString().c_str()\n\/\/CHECK-NEXT: ({{[^)]+}}) \"N::C\"\nFix tag lookup test\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n\/\/ RUN: cat %s | %built_cling -fno-rtti 2>&1 | FileCheck %s\n\/\/ Test Lookup::Named and Namespace, used in quick simple lookups.\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/LookupHelper.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/AST\/Tag.h\"\n\n#include \n\nusing namespace cling;\nusing namespace llvm;\n\n.rawInput 1\n\nenum class E {};\nclass C {};\n\nnamespace N {\nenum class Inside_E {};\nclass Inside_C {};\n}\n\n.rawInput 0\n\n\nclang::Sema& S = gCling->getSema();\nconst LookupHelper& lookup = gCling->getLookupHelper();\nLookupHelper::DiagSetting diags = LookupHelper::WithDiagnostics;\n\nconst clang::TagDecl *tagdecl{nullptr};\n\ntagdecl = utils::Lookup::Tag(&S, \"E\", nullptr);\ntagdecl\n\/\/CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}\ntagdecl->getQualifiedNameAsString().c_str()\n\/\/CHECK-NEXT: ({{[^)]+}}) \"E\"\n\ntagdecl = utils::Lookup::Tag(&S, \"C\", nullptr);\ntagdecl\n\/\/CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}\ntagdecl->getQualifiedNameAsString().c_str()\n\/\/CHECK-NEXT: ({{[^)]+}}) \"C\"\n\nconst clang::NamedDecl *nameddecl{nullptr};\n\nnameddecl = utils::Lookup::Named(&S, \"N\", nullptr);\nnameddecl\n\/\/CHECK: (const clang::NamedDecl *) 0x{{[1-9a-f][0-9a-f]*$}}\nnameddecl->getQualifiedNameAsString().c_str()\n\/\/CHECK-NEXT: ({{[^)]+}}) \"N\"\n\nconst clang::DeclContext *context = dyn_cast(nameddecl);\ncontext\n\/\/CHECK: (const clang::DeclContext *) 0x{{[1-9a-f][0-9a-f]*$}}\n\ntagdecl = utils::Lookup::Tag(&S, \"Inside_E\", context);\ntagdecl\n\/\/CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}\ntagdecl->getQualifiedNameAsString().c_str()\n\/\/CHECK-NEXT: ({{[^)]+}}) \"N::Inside_E\"\n\ntagdecl = utils::Lookup::Tag(&S, \"Inside_C\", context);\ntagdecl\n\/\/CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}\ntagdecl->getQualifiedNameAsString().c_str()\n\/\/CHECK-NEXT: ({{[^)]+}}) \"N::Inside_C\"\n<|endoftext|>"}
{"text":"#pragma once\n#ifndef NIFTY_GRAPH_DETAIL_SEARCH_IMPL_HXX\n#define NIFTY_GRAPH_DETAIL_SEARCH_IMPL_HXX\n\n#include \n#include \n\n#include \"nifty\/graph\/subgraph_mask.hxx\"\n#include \"nifty\/queue\/changeable_priority_queue.hxx\"\n\nnamespace nifty{\nnamespace graph{\nnamespace detail_graph{\n\n    template\n    struct LiFo : public std::stack{\n        using std::stack::stack;\n        const T & nextElement(){\n            return this->top();\n        }\n    };\n    template\n    struct FiFo : public std::queue{\n        using std::queue::queue;\n        const T & nextElement(){\n            return this->front();\n        }\n    };\n\n    template\n    class SearchImpl{\n\n    public:\n        typedef GRAPH Graph;\n        typedef typename Graph:: template NodeMap     PredecessorsMap;\n        typedef typename Graph:: template NodeMap  DistanceMap;\n    private:\n        typedef QUEUE    Queue;\n    public:\n        SearchImpl(const Graph & g)\n        :   g_(g),\n            queue_(),\n            predMap_(g),\n            distMap_(g){\n        }\n\n        \/\/ run single source single target\n        \/\/ no  callback no mask exposed\n        void runSingleSourceSingleTarget(\n            const int64_t source,\n            const int64_t target = -1\n        ){\n            \/\/ subgraph mask\n            DefaultSubgraphMask subgraphMask;\n            \/\/ visitor\n            auto visitor = [&]\n            (   \n                int64_t topNode,\n                const DistanceMap     & distances,\n                const PredecessorsMap & predecessors\n            ){\n                return topNode != target;\n            };\n\n            this->initializeMaps(&source, &source +1);\n            runImpl(subgraphMask, visitor);\n        }\n\n\n        \/\/ run single source  ALL targets\n        \/\/ no  callback no mask exposed\n        void runSingleSource(\n            const int64_t source\n        ){\n\n            \/\/ subgraph mask\n            DefaultSubgraphMask subgraphMask;\n            this->initializeMaps(&source, &source +1);\n            \/\/ visitor\n            auto visitor = [](   int64_t topNode,\n                const DistanceMap     & distances,\n                const PredecessorsMap & predecessors\n            ){\n                return true;\n            };\n            runImpl(subgraphMask, visitor);\n        }\n\n\n\n\n\n\n\n        template\n        void run(\n            SOURCE_ITER sourceBegin, \n            SOURCE_ITER sourceEnd,\n            const SUBGRAPH_MASK &  subgraphMask,\n            VISITOR && visitor\n        ){\n            this->initializeMaps(sourceBegin, sourceEnd);\n            this->runImpl(subgraphMask,visitor);\n        }\n\n        const DistanceMap & distances()const{\n            return distMap_;\n        }\n        const PredecessorsMap predecessors()const{\n            return predMap_;\n        }\n    private:\n\n        template<\n            class SUBGRAPH_MASK,\n            class VISITOR \n        >\n        void runImpl(\n            const SUBGRAPH_MASK &  subgraphMask,\n            VISITOR && visitor\n        ){\n\n            while(!queue_.empty()){\n                auto u = queue_.nextElement();\n                queue_.pop();\n\n                \/\/ exit on visitors demand\n                if(!visitor(u, distMap_, predMap_)){\n                    break;\n                }\n\n                \/\/ if node == gloal node\n                \/\/  break\n                for(auto adj : g_.adjacency(u)){\n                    const auto v = adj.node();\n                    const auto e = adj.edge();\n                    if(predMap_[v] == -1 &&  subgraphMask.useNode(v) && subgraphMask.useEdge(e)){\n                        predMap_[v] = u;\n                        distMap_[v] = distMap_[u] + 1;\n                        queue_.push(v);\n                    }\n                }\n            }\n            \n        }\n\n\n        template\n        void initializeMaps(SOURCE_ITER sourceBegin, SOURCE_ITER sourceEnd){\n            while(!queue_.empty())\n                queue_.pop();\n            for(auto node : g_.nodes()){\n                predMap_[node] = -1;\n            }\n\n            for( ; sourceBegin!=sourceEnd; ++sourceBegin){\n                auto n = *sourceBegin;\n                distMap_[n] = 0;\n                predMap_[n] = n;\n                queue_.push(n);\n            }\n        }\n\n\n\n        const GRAPH & g_;\n        Queue queue_;\n        PredecessorsMap predMap_;\n        DistanceMap     distMap_;\n    };\n\n\n} \/\/ namespace nifty::graph::detail_graph\n} \/\/ namespace nifty::graph\n} \/\/ namespace nifty\n\n#endif  \/\/ NIFTY_GRAPH_DETAIL_SEARCH_IMPL_HXX\ntouch#pragma once\n#ifndef NIFTY_GRAPH_DETAIL_SEARCH_IMPL_HXX\n#define NIFTY_GRAPH_DETAIL_SEARCH_IMPL_HXX\n\n#include \n#include \n\n#include \"nifty\/graph\/subgraph_mask.hxx\"\n#include \"nifty\/queue\/changeable_priority_queue.hxx\"\n\nnamespace nifty{\nnamespace graph{\nnamespace detail_graph{\n\n    template\n    struct LiFo : public std::stack{\n        using std::stack::stack;\n        const T & nextElement(){\n            return this->top();\n        }\n    };\n    template\n    struct FiFo : public std::queue{\n        using std::queue::queue;\n        const T & nextElement(){\n            return this->front();\n        }\n    };\n\n    template\n    class SearchImpl{\n\n    public:\n        typedef GRAPH Graph;\n        typedef typename Graph:: template NodeMap     PredecessorsMap;\n        typedef typename Graph:: template NodeMap  DistanceMap;\n    private:\n        typedef QUEUE    Queue;\n    public:\n        SearchImpl(const Graph & g)\n        :   g_(g),\n            queue_(),\n            predMap_(g),\n            distMap_(g){\n        }\n\n        \/\/ run single source single target\n        \/\/ no  callback no mask exposed\n        void runSingleSourceSingleTarget(\n            const int64_t source,\n            const int64_t target = -1\n        ){\n            \/\/ subgraph mask\n            DefaultSubgraphMask subgraphMask;\n            \/\/ visitor\n            auto visitor = [&]\n            (   \n                int64_t topNode,\n                const DistanceMap     & distances,\n                const PredecessorsMap & predecessors\n            ){\n                return topNode != target;\n            };\n\n            this->initializeMaps(&source, &source +1);\n            runImpl(subgraphMask, visitor);\n        }\n\n\n        \/\/ run single source  ALL targets\n        \/\/ no  callback no mask exposed\n        void runSingleSource(\n            const int64_t source\n        ){\n\n            \/\/ subgraph mask\n            DefaultSubgraphMask subgraphMask;\n            this->initializeMaps(&source, &source +1);\n            \/\/ visitor\n            auto visitor = [](   int64_t topNode,\n                const DistanceMap     & distances,\n                const PredecessorsMap & predecessors\n            ){\n                return true;\n            };\n            runImpl(subgraphMask, visitor);\n        }\n\n\n\n\n\n\n\n        template\n        void run(\n            SOURCE_ITER sourceBegin, \n            SOURCE_ITER sourceEnd,\n            const SUBGRAPH_MASK &  subgraphMask,\n            VISITOR && visitor\n        ){\n            this->initializeMaps(sourceBegin, sourceEnd);\n            this->runImpl(subgraphMask,visitor);\n        }\n\n        const DistanceMap & distances()const{\n            return distMap_;\n        }\n        const PredecessorsMap predecessors()const{\n            return predMap_;\n        }\n    private:\n\n        template<\n            class SUBGRAPH_MASK,\n            class VISITOR \n        >\n        void runImpl(\n            const SUBGRAPH_MASK &  subgraphMask,\n            VISITOR && visitor\n        ){\n\n            while(!queue_.empty()){\n                auto u = queue_.nextElement();\n                queue_.pop();\n\n                \/\/ exit on visitors demand\n                if(!visitor(u, distMap_, predMap_)){\n                    break;\n                }\n\n                \/\/ if node == gloal node\n                \/\/  break\n                for(auto adj : g_.adjacency(u)){\n                    const auto v = adj.node();\n                    const auto e = adj.edge();\n                    if(predMap_[v] == -1 &&  subgraphMask.useNode(v) && subgraphMask.useEdge(e)){\n                        predMap_[v] = u;\n                        distMap_[v] = distMap_[u] + 1;\n                        queue_.push(v);\n                    }\n                }\n            }\n            \n        }\n\n\n        template\n        void initializeMaps(SOURCE_ITER sourceBegin, SOURCE_ITER sourceEnd){\n            while(!queue_.empty())\n                queue_.pop();\n            for(auto node : g_.nodes()){\n                predMap_[node] = -1;\n            }\n\n            for( ; sourceBegin!=sourceEnd; ++sourceBegin){\n                auto n = *sourceBegin;\n                distMap_[n] = 0;\n                predMap_[n] = n;\n                queue_.push(n);\n            }\n        }\n\n\n\n        const GRAPH & g_;\n        Queue queue_;\n        PredecessorsMap predMap_;\n        DistanceMap     distMap_;\n    };\n\n} \/\/ namespace nifty::graph::detail_graph\n} \/\/ namespace nifty::graph\n} \/\/ namespace nifty\n\n#endif  \/\/ NIFTY_GRAPH_DETAIL_SEARCH_IMPL_HXX\n<|endoftext|>"}
{"text":"\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: xpool.cxx,v $\n *\n *  $Revision: 1.11 $\n *\n *  last change: $Author: hr $ $Date: 2006-06-19 17:07:51 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#include \"xtable.hxx\"\n#include \"xattr.hxx\"\n#include \"xpool.hxx\"\n#include \"svdattr.hxx\"\n#include \"svxids.hrc\"\n\n#ifndef _SFXITEMSET_HXX \/\/autogen\n#include \n#endif\n\n\nXOutdevItemPool::XOutdevItemPool(\n    SfxItemPool* _pMaster,\n    sal_uInt16 nAttrStart,\n    sal_uInt16 nAttrEnd,\n    sal_Bool bLoadRefCounts)\n:   SfxItemPool(String(\"XOutdevItemPool\", gsl_getSystemTextEncoding()), nAttrStart, nAttrEnd, 0L, 0L, bLoadRefCounts)\n{\n    \/\/ prepare some defaults\n    const XubString aNullStr;\n    const Bitmap aNullBmp;\n    const XPolygon aNullPol;\n    const Color aNullLineCol(RGB_Color(COL_BLACK));\n    const Color aNullFillCol(RGB_Color(COL_DEFAULT_SHAPE_FILLING));  \/\/ \"Blue 8\"\n    const Color aNullShadowCol(RGB_Color(COL_LIGHTGRAY));\n    const XDash aNullDash;\n    const XGradient aNullGrad(aNullLineCol, RGB_Color(COL_WHITE));\n    const XHatch aNullHatch(aNullLineCol);\n\n    \/\/ get master pointer, evtl. add myself to the end of the pools\n    if(!_pMaster)\n    {\n        _pMaster = this;\n    }\n    else\n    {\n        SfxItemPool* pParent = _pMaster;\n\n        while(pParent->GetSecondaryPool())\n        {\n            pParent = pParent->GetSecondaryPool();\n        }\n\n        pParent->SetSecondaryPool(this);\n    }\n\n    \/\/ prepare PoolDefaults\n    mppLocalPoolDefaults = new SfxPoolItem*[GetLastWhich() - GetFirstWhich() + 1];\n\n    mppLocalPoolDefaults[XATTR_LINESTYLE          -XATTR_START] = new XLineStyleItem;\n    mppLocalPoolDefaults[XATTR_LINEDASH           -XATTR_START] = new XLineDashItem(this,aNullDash);\n    mppLocalPoolDefaults[XATTR_LINEWIDTH          -XATTR_START] = new XLineWidthItem;\n    mppLocalPoolDefaults[XATTR_LINECOLOR          -XATTR_START] = new XLineColorItem(aNullStr,aNullLineCol);\n    mppLocalPoolDefaults[XATTR_LINESTART          -XATTR_START] = new XLineStartItem(this,aNullPol);\n    mppLocalPoolDefaults[XATTR_LINEEND            -XATTR_START] = new XLineEndItem  (this,aNullPol);\n    mppLocalPoolDefaults[XATTR_LINESTARTWIDTH     -XATTR_START] = new XLineStartWidthItem;\n    mppLocalPoolDefaults[XATTR_LINEENDWIDTH       -XATTR_START] = new XLineEndWidthItem;\n    mppLocalPoolDefaults[XATTR_LINESTARTCENTER    -XATTR_START] = new XLineStartCenterItem;\n    mppLocalPoolDefaults[XATTR_LINEENDCENTER      -XATTR_START] = new XLineEndCenterItem;\n    mppLocalPoolDefaults[XATTR_LINETRANSPARENCE   -XATTR_START] = new XLineTransparenceItem;\n    mppLocalPoolDefaults[XATTR_LINEJOINT            -XATTR_START] = new XLineJointItem;\n    mppLocalPoolDefaults[XATTR_FILLSTYLE                -XATTR_START] = new XFillStyleItem;\n    mppLocalPoolDefaults[XATTR_FILLCOLOR                -XATTR_START] = new XFillColorItem   (aNullStr,aNullFillCol);\n    mppLocalPoolDefaults[XATTR_FILLGRADIENT         -XATTR_START] = new XFillGradientItem(this,aNullGrad);\n    mppLocalPoolDefaults[XATTR_FILLHATCH                -XATTR_START] = new XFillHatchItem   (this,aNullHatch);\n    mppLocalPoolDefaults[XATTR_FILLBITMAP               -XATTR_START] = new XFillBitmapItem  (this,aNullBmp);\n    mppLocalPoolDefaults[XATTR_FILLTRANSPARENCE     -XATTR_START] = new XFillTransparenceItem;\n    mppLocalPoolDefaults[XATTR_GRADIENTSTEPCOUNT        -XATTR_START] = new XGradientStepCountItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_TILE         -XATTR_START] = new XFillBmpTileItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_POS          -XATTR_START] = new XFillBmpPosItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_SIZEX            -XATTR_START] = new XFillBmpSizeXItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_SIZEY            -XATTR_START] = new XFillBmpSizeYItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_SIZELOG      -XATTR_START] = new XFillBmpSizeLogItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_TILEOFFSETX  -XATTR_START] = new XFillBmpTileOffsetXItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_TILEOFFSETY  -XATTR_START] = new XFillBmpTileOffsetYItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_STRETCH      -XATTR_START] = new XFillBmpStretchItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_POSOFFSETX       -XATTR_START] = new XFillBmpPosOffsetXItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_POSOFFSETY       -XATTR_START] = new XFillBmpPosOffsetYItem;\n    mppLocalPoolDefaults[XATTR_FILLFLOATTRANSPARENCE    -XATTR_START] = new XFillFloatTransparenceItem( this, aNullGrad, FALSE );\n    mppLocalPoolDefaults[XATTR_SECONDARYFILLCOLOR       -XATTR_START] = new XSecondaryFillColorItem(aNullStr, aNullFillCol);\n    mppLocalPoolDefaults[XATTR_FILLBACKGROUND           -XATTR_START] = new XFillBackgroundItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTSTYLE       -XATTR_START] = new XFormTextStyleItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTADJUST      -XATTR_START] = new XFormTextAdjustItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTDISTANCE    -XATTR_START] = new XFormTextDistanceItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTSTART       -XATTR_START] = new XFormTextStartItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTMIRROR      -XATTR_START] = new XFormTextMirrorItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTOUTLINE     -XATTR_START] = new XFormTextOutlineItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTSHADOW      -XATTR_START] = new XFormTextShadowItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTSHDWCOLOR   -XATTR_START] = new XFormTextShadowColorItem(aNullStr,aNullShadowCol);\n    mppLocalPoolDefaults[XATTR_FORMTXTSHDWXVAL    -XATTR_START] = new XFormTextShadowXValItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTSHDWYVAL    -XATTR_START] = new XFormTextShadowYValItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTSTDFORM     -XATTR_START] = new XFormTextStdFormItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTHIDEFORM    -XATTR_START] = new XFormTextHideFormItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTSHDWTRANSP  -XATTR_START] = new XFormTextShadowTranspItem;\n\n    \/\/ create SetItems\n    SfxItemSet* pSet=new SfxItemSet(*_pMaster, XATTR_LINE_FIRST, XATTR_LINE_LAST);\n    mppLocalPoolDefaults[XATTRSET_LINE - XATTR_START] = new XLineAttrSetItem(pSet);\n    pSet=new SfxItemSet(*_pMaster, XATTR_FILL_FIRST, XATTR_FILL_LAST);\n    mppLocalPoolDefaults[XATTRSET_FILL - XATTR_START] = new XFillAttrSetItem(pSet);\n\n    \/\/ create ItemInfos\n    mpLocalItemInfos = new SfxItemInfo[GetLastWhich() - GetFirstWhich() + 1];\n    for(sal_uInt16 i(GetFirstWhich()); i <= GetLastWhich(); i++)\n    {\n        mpLocalItemInfos[i - XATTR_START]._nSID = 0;\n        mpLocalItemInfos[i - XATTR_START]._nFlags = SFX_ITEM_POOLABLE;\n    }\n\n    mpLocalItemInfos[XATTR_LINESTYLE        -XATTR_START]._nSID = SID_ATTR_LINE_STYLE;\n    mpLocalItemInfos[XATTR_LINEDASH         -XATTR_START]._nSID = SID_ATTR_LINE_DASH;\n    mpLocalItemInfos[XATTR_LINEWIDTH        -XATTR_START]._nSID = SID_ATTR_LINE_WIDTH;\n    mpLocalItemInfos[XATTR_LINECOLOR        -XATTR_START]._nSID = SID_ATTR_LINE_COLOR;\n    mpLocalItemInfos[XATTR_LINESTART        -XATTR_START]._nSID = SID_ATTR_LINE_START;\n    mpLocalItemInfos[XATTR_LINEEND          -XATTR_START]._nSID = SID_ATTR_LINE_END;\n    mpLocalItemInfos[XATTR_LINESTARTWIDTH   -XATTR_START]._nSID = SID_ATTR_LINE_STARTWIDTH;\n    mpLocalItemInfos[XATTR_LINEENDWIDTH     -XATTR_START]._nSID = SID_ATTR_LINE_ENDWIDTH;\n    mpLocalItemInfos[XATTR_LINESTARTCENTER  -XATTR_START]._nSID = SID_ATTR_LINE_STARTCENTER;\n    mpLocalItemInfos[XATTR_LINEENDCENTER    -XATTR_START]._nSID = SID_ATTR_LINE_ENDCENTER;\n    mpLocalItemInfos[XATTR_FILLSTYLE        -XATTR_START]._nSID = SID_ATTR_FILL_STYLE;\n    mpLocalItemInfos[XATTR_FILLCOLOR        -XATTR_START]._nSID = SID_ATTR_FILL_COLOR;\n    mpLocalItemInfos[XATTR_FILLGRADIENT     -XATTR_START]._nSID = SID_ATTR_FILL_GRADIENT;\n    mpLocalItemInfos[XATTR_FILLHATCH        -XATTR_START]._nSID = SID_ATTR_FILL_HATCH;\n    mpLocalItemInfos[XATTR_FILLBITMAP       -XATTR_START]._nSID = SID_ATTR_FILL_BITMAP;\n    mpLocalItemInfos[XATTR_FORMTXTSTYLE     -XATTR_START]._nSID = SID_FORMTEXT_STYLE;\n    mpLocalItemInfos[XATTR_FORMTXTADJUST    -XATTR_START]._nSID = SID_FORMTEXT_ADJUST;\n    mpLocalItemInfos[XATTR_FORMTXTDISTANCE  -XATTR_START]._nSID = SID_FORMTEXT_DISTANCE;\n    mpLocalItemInfos[XATTR_FORMTXTSTART     -XATTR_START]._nSID = SID_FORMTEXT_START;\n    mpLocalItemInfos[XATTR_FORMTXTMIRROR    -XATTR_START]._nSID = SID_FORMTEXT_MIRROR;\n    mpLocalItemInfos[XATTR_FORMTXTOUTLINE   -XATTR_START]._nSID = SID_FORMTEXT_OUTLINE;\n    mpLocalItemInfos[XATTR_FORMTXTSHADOW    -XATTR_START]._nSID = SID_FORMTEXT_SHADOW;\n    mpLocalItemInfos[XATTR_FORMTXTSHDWCOLOR -XATTR_START]._nSID = SID_FORMTEXT_SHDWCOLOR;\n    mpLocalItemInfos[XATTR_FORMTXTSHDWXVAL  -XATTR_START]._nSID = SID_FORMTEXT_SHDWXVAL;\n    mpLocalItemInfos[XATTR_FORMTXTSHDWYVAL  -XATTR_START]._nSID = SID_FORMTEXT_SHDWYVAL;\n    mpLocalItemInfos[XATTR_FORMTXTSTDFORM   -XATTR_START]._nSID = SID_FORMTEXT_STDFORM;\n    mpLocalItemInfos[XATTR_FORMTXTHIDEFORM  -XATTR_START]._nSID = SID_FORMTEXT_HIDEFORM;\n\n    \/\/ if it's my own creation level, set Defaults and ItemInfos\n    if(XATTR_START == GetFirstWhich() && XATTR_END == GetLastWhich())\n    {\n        SetDefaults(mppLocalPoolDefaults);\n        SetItemInfos(mpLocalItemInfos);\n    }\n}\n\n\/*************************************************************************\n|*\n|* copy ctor, sorgt dafuer, dass die static defaults gecloned werden\n|*            (Parameter 2 = TRUE)\n|*\n\\************************************************************************\/\n\nXOutdevItemPool::XOutdevItemPool(const XOutdevItemPool& rPool)\n:   SfxItemPool(rPool, TRUE),\n    mppLocalPoolDefaults(0L),\n    mpLocalItemInfos(0L)\n{\n}\n\n\/*************************************************************************\n|*\n|* Clone()\n|*\n\\************************************************************************\/\n\nSfxItemPool* XOutdevItemPool::Clone() const\n{\n    return new XOutdevItemPool(*this);\n}\n\n\/*************************************************************************\n|*\n|* Destruktor\n|*\n\\************************************************************************\/\n\nXOutdevItemPool::~XOutdevItemPool()\n{\n    Delete();\n\n    \/\/ remove own static defaults\n    if(mppLocalPoolDefaults)\n    {\n        SfxPoolItem** ppDefaultItem = mppLocalPoolDefaults;\n        for(sal_uInt16 i(GetLastWhich() - GetFirstWhich() + 1); i; --i, ++ppDefaultItem)\n        {\n            if ( *ppDefaultItem ) \/\/Teile schon von abgel. Klasse abgeraeumt!\n            {\n                SetRefCount( **ppDefaultItem, 0 );\n                delete *ppDefaultItem;\n            }\n        }\n\n        delete[] mppLocalPoolDefaults;\n    }\n\n    if(mpLocalItemInfos)\n    {\n        delete[] mpLocalItemInfos;\n    }\n}\n\n\/\/ eof\nINTEGRATION: CWS pchfix02 (1.11.114); FILE MERGED 2006\/09\/01 17:47:47 kaib 1.11.114.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: xpool.cxx,v $\n *\n *  $Revision: 1.12 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-17 06:25:00 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n\n#include \"xtable.hxx\"\n#include \"xattr.hxx\"\n#include \"xpool.hxx\"\n#include \"svdattr.hxx\"\n#include \"svxids.hrc\"\n\n#ifndef _SFXITEMSET_HXX \/\/autogen\n#include \n#endif\n\n\nXOutdevItemPool::XOutdevItemPool(\n    SfxItemPool* _pMaster,\n    sal_uInt16 nAttrStart,\n    sal_uInt16 nAttrEnd,\n    sal_Bool bLoadRefCounts)\n:   SfxItemPool(String(\"XOutdevItemPool\", gsl_getSystemTextEncoding()), nAttrStart, nAttrEnd, 0L, 0L, bLoadRefCounts)\n{\n    \/\/ prepare some defaults\n    const XubString aNullStr;\n    const Bitmap aNullBmp;\n    const XPolygon aNullPol;\n    const Color aNullLineCol(RGB_Color(COL_BLACK));\n    const Color aNullFillCol(RGB_Color(COL_DEFAULT_SHAPE_FILLING));  \/\/ \"Blue 8\"\n    const Color aNullShadowCol(RGB_Color(COL_LIGHTGRAY));\n    const XDash aNullDash;\n    const XGradient aNullGrad(aNullLineCol, RGB_Color(COL_WHITE));\n    const XHatch aNullHatch(aNullLineCol);\n\n    \/\/ get master pointer, evtl. add myself to the end of the pools\n    if(!_pMaster)\n    {\n        _pMaster = this;\n    }\n    else\n    {\n        SfxItemPool* pParent = _pMaster;\n\n        while(pParent->GetSecondaryPool())\n        {\n            pParent = pParent->GetSecondaryPool();\n        }\n\n        pParent->SetSecondaryPool(this);\n    }\n\n    \/\/ prepare PoolDefaults\n    mppLocalPoolDefaults = new SfxPoolItem*[GetLastWhich() - GetFirstWhich() + 1];\n\n    mppLocalPoolDefaults[XATTR_LINESTYLE          -XATTR_START] = new XLineStyleItem;\n    mppLocalPoolDefaults[XATTR_LINEDASH           -XATTR_START] = new XLineDashItem(this,aNullDash);\n    mppLocalPoolDefaults[XATTR_LINEWIDTH          -XATTR_START] = new XLineWidthItem;\n    mppLocalPoolDefaults[XATTR_LINECOLOR          -XATTR_START] = new XLineColorItem(aNullStr,aNullLineCol);\n    mppLocalPoolDefaults[XATTR_LINESTART          -XATTR_START] = new XLineStartItem(this,aNullPol);\n    mppLocalPoolDefaults[XATTR_LINEEND            -XATTR_START] = new XLineEndItem  (this,aNullPol);\n    mppLocalPoolDefaults[XATTR_LINESTARTWIDTH     -XATTR_START] = new XLineStartWidthItem;\n    mppLocalPoolDefaults[XATTR_LINEENDWIDTH       -XATTR_START] = new XLineEndWidthItem;\n    mppLocalPoolDefaults[XATTR_LINESTARTCENTER    -XATTR_START] = new XLineStartCenterItem;\n    mppLocalPoolDefaults[XATTR_LINEENDCENTER      -XATTR_START] = new XLineEndCenterItem;\n    mppLocalPoolDefaults[XATTR_LINETRANSPARENCE   -XATTR_START] = new XLineTransparenceItem;\n    mppLocalPoolDefaults[XATTR_LINEJOINT            -XATTR_START] = new XLineJointItem;\n    mppLocalPoolDefaults[XATTR_FILLSTYLE                -XATTR_START] = new XFillStyleItem;\n    mppLocalPoolDefaults[XATTR_FILLCOLOR                -XATTR_START] = new XFillColorItem   (aNullStr,aNullFillCol);\n    mppLocalPoolDefaults[XATTR_FILLGRADIENT         -XATTR_START] = new XFillGradientItem(this,aNullGrad);\n    mppLocalPoolDefaults[XATTR_FILLHATCH                -XATTR_START] = new XFillHatchItem   (this,aNullHatch);\n    mppLocalPoolDefaults[XATTR_FILLBITMAP               -XATTR_START] = new XFillBitmapItem  (this,aNullBmp);\n    mppLocalPoolDefaults[XATTR_FILLTRANSPARENCE     -XATTR_START] = new XFillTransparenceItem;\n    mppLocalPoolDefaults[XATTR_GRADIENTSTEPCOUNT        -XATTR_START] = new XGradientStepCountItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_TILE         -XATTR_START] = new XFillBmpTileItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_POS          -XATTR_START] = new XFillBmpPosItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_SIZEX            -XATTR_START] = new XFillBmpSizeXItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_SIZEY            -XATTR_START] = new XFillBmpSizeYItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_SIZELOG      -XATTR_START] = new XFillBmpSizeLogItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_TILEOFFSETX  -XATTR_START] = new XFillBmpTileOffsetXItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_TILEOFFSETY  -XATTR_START] = new XFillBmpTileOffsetYItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_STRETCH      -XATTR_START] = new XFillBmpStretchItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_POSOFFSETX       -XATTR_START] = new XFillBmpPosOffsetXItem;\n    mppLocalPoolDefaults[XATTR_FILLBMP_POSOFFSETY       -XATTR_START] = new XFillBmpPosOffsetYItem;\n    mppLocalPoolDefaults[XATTR_FILLFLOATTRANSPARENCE    -XATTR_START] = new XFillFloatTransparenceItem( this, aNullGrad, FALSE );\n    mppLocalPoolDefaults[XATTR_SECONDARYFILLCOLOR       -XATTR_START] = new XSecondaryFillColorItem(aNullStr, aNullFillCol);\n    mppLocalPoolDefaults[XATTR_FILLBACKGROUND           -XATTR_START] = new XFillBackgroundItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTSTYLE       -XATTR_START] = new XFormTextStyleItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTADJUST      -XATTR_START] = new XFormTextAdjustItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTDISTANCE    -XATTR_START] = new XFormTextDistanceItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTSTART       -XATTR_START] = new XFormTextStartItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTMIRROR      -XATTR_START] = new XFormTextMirrorItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTOUTLINE     -XATTR_START] = new XFormTextOutlineItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTSHADOW      -XATTR_START] = new XFormTextShadowItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTSHDWCOLOR   -XATTR_START] = new XFormTextShadowColorItem(aNullStr,aNullShadowCol);\n    mppLocalPoolDefaults[XATTR_FORMTXTSHDWXVAL    -XATTR_START] = new XFormTextShadowXValItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTSHDWYVAL    -XATTR_START] = new XFormTextShadowYValItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTSTDFORM     -XATTR_START] = new XFormTextStdFormItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTHIDEFORM    -XATTR_START] = new XFormTextHideFormItem;\n    mppLocalPoolDefaults[XATTR_FORMTXTSHDWTRANSP  -XATTR_START] = new XFormTextShadowTranspItem;\n\n    \/\/ create SetItems\n    SfxItemSet* pSet=new SfxItemSet(*_pMaster, XATTR_LINE_FIRST, XATTR_LINE_LAST);\n    mppLocalPoolDefaults[XATTRSET_LINE - XATTR_START] = new XLineAttrSetItem(pSet);\n    pSet=new SfxItemSet(*_pMaster, XATTR_FILL_FIRST, XATTR_FILL_LAST);\n    mppLocalPoolDefaults[XATTRSET_FILL - XATTR_START] = new XFillAttrSetItem(pSet);\n\n    \/\/ create ItemInfos\n    mpLocalItemInfos = new SfxItemInfo[GetLastWhich() - GetFirstWhich() + 1];\n    for(sal_uInt16 i(GetFirstWhich()); i <= GetLastWhich(); i++)\n    {\n        mpLocalItemInfos[i - XATTR_START]._nSID = 0;\n        mpLocalItemInfos[i - XATTR_START]._nFlags = SFX_ITEM_POOLABLE;\n    }\n\n    mpLocalItemInfos[XATTR_LINESTYLE        -XATTR_START]._nSID = SID_ATTR_LINE_STYLE;\n    mpLocalItemInfos[XATTR_LINEDASH         -XATTR_START]._nSID = SID_ATTR_LINE_DASH;\n    mpLocalItemInfos[XATTR_LINEWIDTH        -XATTR_START]._nSID = SID_ATTR_LINE_WIDTH;\n    mpLocalItemInfos[XATTR_LINECOLOR        -XATTR_START]._nSID = SID_ATTR_LINE_COLOR;\n    mpLocalItemInfos[XATTR_LINESTART        -XATTR_START]._nSID = SID_ATTR_LINE_START;\n    mpLocalItemInfos[XATTR_LINEEND          -XATTR_START]._nSID = SID_ATTR_LINE_END;\n    mpLocalItemInfos[XATTR_LINESTARTWIDTH   -XATTR_START]._nSID = SID_ATTR_LINE_STARTWIDTH;\n    mpLocalItemInfos[XATTR_LINEENDWIDTH     -XATTR_START]._nSID = SID_ATTR_LINE_ENDWIDTH;\n    mpLocalItemInfos[XATTR_LINESTARTCENTER  -XATTR_START]._nSID = SID_ATTR_LINE_STARTCENTER;\n    mpLocalItemInfos[XATTR_LINEENDCENTER    -XATTR_START]._nSID = SID_ATTR_LINE_ENDCENTER;\n    mpLocalItemInfos[XATTR_FILLSTYLE        -XATTR_START]._nSID = SID_ATTR_FILL_STYLE;\n    mpLocalItemInfos[XATTR_FILLCOLOR        -XATTR_START]._nSID = SID_ATTR_FILL_COLOR;\n    mpLocalItemInfos[XATTR_FILLGRADIENT     -XATTR_START]._nSID = SID_ATTR_FILL_GRADIENT;\n    mpLocalItemInfos[XATTR_FILLHATCH        -XATTR_START]._nSID = SID_ATTR_FILL_HATCH;\n    mpLocalItemInfos[XATTR_FILLBITMAP       -XATTR_START]._nSID = SID_ATTR_FILL_BITMAP;\n    mpLocalItemInfos[XATTR_FORMTXTSTYLE     -XATTR_START]._nSID = SID_FORMTEXT_STYLE;\n    mpLocalItemInfos[XATTR_FORMTXTADJUST    -XATTR_START]._nSID = SID_FORMTEXT_ADJUST;\n    mpLocalItemInfos[XATTR_FORMTXTDISTANCE  -XATTR_START]._nSID = SID_FORMTEXT_DISTANCE;\n    mpLocalItemInfos[XATTR_FORMTXTSTART     -XATTR_START]._nSID = SID_FORMTEXT_START;\n    mpLocalItemInfos[XATTR_FORMTXTMIRROR    -XATTR_START]._nSID = SID_FORMTEXT_MIRROR;\n    mpLocalItemInfos[XATTR_FORMTXTOUTLINE   -XATTR_START]._nSID = SID_FORMTEXT_OUTLINE;\n    mpLocalItemInfos[XATTR_FORMTXTSHADOW    -XATTR_START]._nSID = SID_FORMTEXT_SHADOW;\n    mpLocalItemInfos[XATTR_FORMTXTSHDWCOLOR -XATTR_START]._nSID = SID_FORMTEXT_SHDWCOLOR;\n    mpLocalItemInfos[XATTR_FORMTXTSHDWXVAL  -XATTR_START]._nSID = SID_FORMTEXT_SHDWXVAL;\n    mpLocalItemInfos[XATTR_FORMTXTSHDWYVAL  -XATTR_START]._nSID = SID_FORMTEXT_SHDWYVAL;\n    mpLocalItemInfos[XATTR_FORMTXTSTDFORM   -XATTR_START]._nSID = SID_FORMTEXT_STDFORM;\n    mpLocalItemInfos[XATTR_FORMTXTHIDEFORM  -XATTR_START]._nSID = SID_FORMTEXT_HIDEFORM;\n\n    \/\/ if it's my own creation level, set Defaults and ItemInfos\n    if(XATTR_START == GetFirstWhich() && XATTR_END == GetLastWhich())\n    {\n        SetDefaults(mppLocalPoolDefaults);\n        SetItemInfos(mpLocalItemInfos);\n    }\n}\n\n\/*************************************************************************\n|*\n|* copy ctor, sorgt dafuer, dass die static defaults gecloned werden\n|*            (Parameter 2 = TRUE)\n|*\n\\************************************************************************\/\n\nXOutdevItemPool::XOutdevItemPool(const XOutdevItemPool& rPool)\n:   SfxItemPool(rPool, TRUE),\n    mppLocalPoolDefaults(0L),\n    mpLocalItemInfos(0L)\n{\n}\n\n\/*************************************************************************\n|*\n|* Clone()\n|*\n\\************************************************************************\/\n\nSfxItemPool* XOutdevItemPool::Clone() const\n{\n    return new XOutdevItemPool(*this);\n}\n\n\/*************************************************************************\n|*\n|* Destruktor\n|*\n\\************************************************************************\/\n\nXOutdevItemPool::~XOutdevItemPool()\n{\n    Delete();\n\n    \/\/ remove own static defaults\n    if(mppLocalPoolDefaults)\n    {\n        SfxPoolItem** ppDefaultItem = mppLocalPoolDefaults;\n        for(sal_uInt16 i(GetLastWhich() - GetFirstWhich() + 1); i; --i, ++ppDefaultItem)\n        {\n            if ( *ppDefaultItem ) \/\/Teile schon von abgel. Klasse abgeraeumt!\n            {\n                SetRefCount( **ppDefaultItem, 0 );\n                delete *ppDefaultItem;\n            }\n        }\n\n        delete[] mppLocalPoolDefaults;\n    }\n\n    if(mpLocalItemInfos)\n    {\n        delete[] mpLocalItemInfos;\n    }\n}\n\n\/\/ eof\n<|endoftext|>"}
{"text":"\/\/#define VERBOSEARGS\n\n{\n  \/\/ set job and simulation variables as :\n  \/\/ root run.C  --run  --event  --process  --minhard  --maxhard  --minpt \n  \n  int nrun = 0;\n  int nevent = 0;\n  int seed = 0;\n  \n  char sseed[1024];\n  char srun[1024];\n  char sevent[1024];\n  char sprocess[1024];\n  char sminpthard[1024];\n  char smaxpthard[1024];\n  char sminptgammapi0[1024];\n  char squench[1024];\n  char sqhat[1024];\n\n  sprintf(srun,\"\");\n  sprintf(sevent,\"\");\n  sprintf(sprocess,\"\");\n  sprintf(sminpthard,\"\");\n  sprintf(smaxpthard,\"\");\n  sprintf(sminptgammapi0,\"\");\n  sprintf(squench,\"\");\n  sprintf(sqhat,\"\");\n\n  for (int i=0; i< gApplication->Argc();i++){\n#ifdef VERBOSEARGS\n    printf(\"Arg  %d:  %s\\n\",i,gApplication->Argv(i));\n#endif\n    if (!(strcmp(gApplication->Argv(i),\"--run\")))\n      nrun = atoi(gApplication->Argv(i+1));\n    sprintf(srun,\"%d\",nrun);\n    if (!(strcmp(gApplication->Argv(i),\"--event\")))\n      nevent = atoi(gApplication->Argv(i+1));\n    sprintf(sevent,\"%d\",nevent);\n    \n    if (!(strcmp(gApplication->Argv(i),\"--process\")))\n      sprintf(sprocess, gApplication->Argv(i+1));\n    \n    if (!(strcmp(gApplication->Argv(i),\"--minhard\")))\n      sprintf(sminpthard,gApplication->Argv(i+1));\n    \n    if (!(strcmp(gApplication->Argv(i),\"--maxhard\")))\n      sprintf(smaxpthard,gApplication->Argv(i+1));\n    \n    if (!(strcmp(gApplication->Argv(i),\"--minpt\")))\n      sprintf(sminptgammapi0,gApplication->Argv(i+1));\n\n    if (!(strcmp(gApplication->Argv(i),\"--quench\")))\n      sprintf(squench,gApplication->Argv(i+1));\n\n    if (!(strcmp(gApplication->Argv(i),\"--qhat\")))\n      sprintf(sqhat,gApplication->Argv(i+1));\n\n  }\n  \n  seed = nrun * 100000 + nevent;\n  sprintf(sseed,\"%d\",seed);\n\n  if (seed==0) {\n    fprintf(stderr,\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\");\n    fprintf(stderr,\"!!!!  WARNING! Seeding variable for MC is 0          !!!!\\n\");\n    fprintf(stderr,\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\");\n  } else {\n    fprintf(stdout,\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\");\n    fprintf(stdout,\"!!!  MC Seed is %d \\n\",seed);\n    fprintf(stdout,\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\");\n  }\n  \n  \/\/ set the seed environment variable\n  gSystem->Setenv(\"CONFIG_SEED\",sseed);\n  gSystem->Setenv(\"DC_RUN\",srun);\n  gSystem->Setenv(\"DC_EVENT\",sevent);\n  gSystem->Setenv(\"DC_RUN_TYPE\",sprocess);\/\/\"kPyGammaJetPHOS\");\n  gSystem->Setenv(\"PTHARDMIN\",sminpthard);\/\/\"20\");\n  gSystem->Setenv(\"PTHARDMAX\",smaxpthard);\/\/\"30\");\n\n  gSystem->Setenv(\"PTGAMMAPI0MIN\",sminptgammapi0);\/\/\"1\");\n  gSystem->Setenv(\"QUENCHING\",squench);\n  gSystem->Setenv(\"QHAT\",sqhat);\n\n\n  gSystem->Setenv(\"ECMS\",\"14000\");\n  gSystem->Setenv(\"ALIMDC_RAWDB1\",\".\/mdc1\");\n  gSystem->Setenv(\"ALIMDC_RAWDB2\",\".\/mdc2\");\n  gSystem->Setenv(\"ALIMDC_TAGDB\",\".\/mdc1\/tag\");\n  gSystem->Setenv(\"ALIMDC_RUNDB\",\".\/mdc1\/meta\");\n  cout<< \"SIMRUN:: Run \" << gSystem->Getenv(\"DC_RUN\") << \" Event \" << gSystem->Getenv(\"DC_EVENT\") \n\t  << \" Process \"    << gSystem->Getenv(\"DC_RUN_TYPE\") \n\t  << \" minpthard \" << gSystem->Getenv(\"PTHARDMIN\") \n\t  << \" maxpthard \" << gSystem->Getenv(\"PTHARDMAX\") \n\t  << \" minpt \"     << gSystem->Getenv(\"PTGAMMAPI0MIN\") \n\t  << endl;\n  \/\/gSystem->Exec(\"cp $ROOTSYS\/etc\/system.rootrc .rootrc\");\n  cout<<\">>>>> SIMULATION <<<<<\"<Exec(\"aliroot -b -q sim.C > sim.log 2>&1\");\n  cout<<\">>>>> SIMULATION QA <<<<<\"<Exec(\"aliroot -b -q simqa.C > simqa.log 2>&1\");\n  cout<<\">>>>> RECONSTRUCTION <<<<<\"<Exec(\"aliroot -b -q rec.C > rec.log 2>&1\");\n  cout<<\">>>>> RECONSTRUCTION QA <<<<<\"<Exec(\"aliroot -b -q recqa.C > recqa.log 2>&1\");\n  cout<<\">>>>> TAG <<<<<\"<Getenv(\"ALIEN_JDL_OUTPUTDIR\"))\n    gSystem->Exec(\"aliroot -b -q tag.C > tag.log 2>&1\");\n  cout<<\">>>>> CHECK ESD <<<<<\"<Exec(\"aliroot -b -q CheckESD.C > check.log 2>&1\");\n\n}\nReplace QADataMakerSteer by QAManager deriving from CDBManager\/\/#define VERBOSEARGS\n\n{\n  \/\/ set job and simulation variables as :\n  \/\/ root run.C  --run  --event  --process  --minhard  --maxhard  --minpt \n  \n  int nrun = 0;\n  int nevent = 0;\n  int seed = 0;\n  \n  char sseed[1024];\n  char srun[1024];\n  char sevent[1024];\n  char sprocess[1024];\n  char sminpthard[1024];\n  char smaxpthard[1024];\n  char sminptgammapi0[1024];\n  char squench[1024];\n  char sqhat[1024];\n\n  sprintf(srun,\"\");\n  sprintf(sevent,\"\");\n  sprintf(sprocess,\"\");\n  sprintf(sminpthard,\"\");\n  sprintf(smaxpthard,\"\");\n  sprintf(sminptgammapi0,\"\");\n  sprintf(squench,\"\");\n  sprintf(sqhat,\"\");\n\n  for (int i=0; i< gApplication->Argc();i++){\n#ifdef VERBOSEARGS\n    printf(\"Arg  %d:  %s\\n\",i,gApplication->Argv(i));\n#endif\n    if (!(strcmp(gApplication->Argv(i),\"--run\")))\n      nrun = atoi(gApplication->Argv(i+1));\n    sprintf(srun,\"%d\",nrun);\n    if (!(strcmp(gApplication->Argv(i),\"--event\")))\n      nevent = atoi(gApplication->Argv(i+1));\n    sprintf(sevent,\"%d\",nevent);\n    \n    if (!(strcmp(gApplication->Argv(i),\"--process\")))\n      sprintf(sprocess, gApplication->Argv(i+1));\n    \n    if (!(strcmp(gApplication->Argv(i),\"--minhard\")))\n      sprintf(sminpthard,gApplication->Argv(i+1));\n    \n    if (!(strcmp(gApplication->Argv(i),\"--maxhard\")))\n      sprintf(smaxpthard,gApplication->Argv(i+1));\n    \n    if (!(strcmp(gApplication->Argv(i),\"--minpt\")))\n      sprintf(sminptgammapi0,gApplication->Argv(i+1));\n\n    if (!(strcmp(gApplication->Argv(i),\"--quench\")))\n      sprintf(squench,gApplication->Argv(i+1));\n\n    if (!(strcmp(gApplication->Argv(i),\"--qhat\")))\n      sprintf(sqhat,gApplication->Argv(i+1));\n\n  }\n  \n  seed = nrun * 100000 + nevent;\n  sprintf(sseed,\"%d\",seed);\n\n  if (seed==0) {\n    fprintf(stderr,\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\");\n    fprintf(stderr,\"!!!!  WARNING! Seeding variable for MC is 0          !!!!\\n\");\n    fprintf(stderr,\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\");\n  } else {\n    fprintf(stdout,\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\");\n    fprintf(stdout,\"!!!  MC Seed is %d \\n\",seed);\n    fprintf(stdout,\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\");\n  }\n  \n  \/\/ set the seed environment variable\n  gSystem->Setenv(\"CONFIG_SEED\",sseed);\n  gSystem->Setenv(\"DC_RUN\",srun);\n  gSystem->Setenv(\"DC_EVENT\",sevent);\n  gSystem->Setenv(\"DC_RUN_TYPE\",sprocess);\/\/\"kPyGammaJetPHOS\");\n  gSystem->Setenv(\"PTHARDMIN\",sminpthard);\/\/\"20\");\n  gSystem->Setenv(\"PTHARDMAX\",smaxpthard);\/\/\"30\");\n\n  gSystem->Setenv(\"PTGAMMAPI0MIN\",sminptgammapi0);\/\/\"1\");\n  gSystem->Setenv(\"QUENCHING\",squench);\n  gSystem->Setenv(\"QHAT\",sqhat);\n\n\n  gSystem->Setenv(\"ECMS\",\"14000\");\n  gSystem->Setenv(\"ALIMDC_RAWDB1\",\".\/mdc1\");\n  gSystem->Setenv(\"ALIMDC_RAWDB2\",\".\/mdc2\");\n  gSystem->Setenv(\"ALIMDC_TAGDB\",\".\/mdc1\/tag\");\n  gSystem->Setenv(\"ALIMDC_RUNDB\",\".\/mdc1\/meta\");\n  cout<< \"SIMRUN:: Run \" << gSystem->Getenv(\"DC_RUN\") << \" Event \" << gSystem->Getenv(\"DC_EVENT\") \n\t  << \" Process \"    << gSystem->Getenv(\"DC_RUN_TYPE\") \n\t  << \" minpthard \" << gSystem->Getenv(\"PTHARDMIN\") \n\t  << \" maxpthard \" << gSystem->Getenv(\"PTHARDMAX\") \n\t  << \" minpt \"     << gSystem->Getenv(\"PTGAMMAPI0MIN\") \n\t  << endl;\n  \/\/gSystem->Exec(\"cp $ROOTSYS\/etc\/system.rootrc .rootrc\");\n  cout<<\">>>>> SIMULATION <<<<<\"<Exec(\"aliroot -b -q sim.C > sim.log 2>&1\");\n  cout<<\">>>>> SIMULATION QA <<<<<\"<Exec(\"aliroot -b -q simqa.C > simqa.log 2>&1\");\n  cout<<\">>>>> RECONSTRUCTION <<<<<\"<Exec(\"rm galice.root\");\n  gSystem->Exec(\"Aliroot -b -q rec.C > rec.log 2>&1\");\n  cout<<\">>>>> RECONSTRUCTION QA <<<<<\"<Exec(\"aliroot -b -q recqa.C > recqa.log 2>&1\");\n  cout<<\">>>>> TAG <<<<<\"<Getenv(\"ALIEN_JDL_OUTPUTDIR\"))\n    gSystem->Exec(\"aliroot -b -q tag.C > tag.log 2>&1\");\n  cout<<\">>>>> CHECK ESD <<<<<\"<Exec(\"aliroot -b -q CheckESD.C > check.log 2>&1\");\n\n}\n<|endoftext|>"}
{"text":"\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing std::string;\nusing std::vector;\n\ntemplate\nvoid testFunction()\n{\n    af_info();\n\n    af_array outArray = 0;\n    dim_t dims[] = {32, 32};\n    ASSERT_EQ(AF_SUCCESS, af_randu(&outArray, 2, dims, (af_dtype) af::dtype_traits::af_type));\n    \/\/ cleanup\n    if(outArray != 0) ASSERT_EQ(AF_SUCCESS, af_release_array(outArray));\n}\n\nvoid backendTest()\n{\n    int backends = af::getAvailableBackends();\n\n    bool cpu    = backends & AF_BACKEND_CPU;\n    bool cuda   = backends & AF_BACKEND_CUDA;\n    bool opencl = backends & AF_BACKEND_OPENCL;\n\n    if(cpu) {\n        printf(\"\\nRunning CPU Backend...\\n\");\n        af::setBackend(AF_BACKEND_CPU);\n        testFunction();\n    }\n\n    if(cuda) {\n        printf(\"\\nRunning CUDA Backend...\\n\");\n        af::setBackend(AF_BACKEND_CUDA);\n        testFunction();\n    }\n\n    if(opencl) {\n        printf(\"\\nRunning OpenCL Backend...\\n\");\n        af::setBackend(AF_BACKEND_OPENCL);\n        testFunction();\n    }\n}\n\nTEST(BACKEND_TEST, Basic)\n{\n    backendTest();\n}\nCleanup\/improve backend test\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing std::string;\nusing std::vector;\n\ntemplate\nvoid testFunction()\n{\n    af_info();\n\n    af_array outArray = 0;\n    dim_t dims[] = {32, 32};\n    ASSERT_EQ(AF_SUCCESS, af_randu(&outArray, 2, dims, (af_dtype) af::dtype_traits::af_type));\n    \/\/ cleanup\n    if(outArray != 0) ASSERT_EQ(AF_SUCCESS, af_release_array(outArray));\n}\n\nvoid backendTest()\n{\n    int backends = af::getAvailableBackends();\n\n    ASSERT_NE(backends, 0);\n\n    bool cpu    = backends & AF_BACKEND_CPU;\n    bool cuda   = backends & AF_BACKEND_CUDA;\n    bool opencl = backends & AF_BACKEND_OPENCL;\n\n    printf(\"\\nRunning Default Backend...\\n\");\n    testFunction();\n\n    if(cpu) {\n        printf(\"\\nRunning CPU Backend...\\n\");\n        af::setBackend(AF_BACKEND_CPU);\n        testFunction();\n    }\n\n    if(cuda) {\n        printf(\"\\nRunning CUDA Backend...\\n\");\n        af::setBackend(AF_BACKEND_CUDA);\n        testFunction();\n    }\n\n    if(opencl) {\n        printf(\"\\nRunning OpenCL Backend...\\n\");\n        af::setBackend(AF_BACKEND_OPENCL);\n        testFunction();\n    }\n}\n\nTEST(BACKEND_TEST, Basic)\n{\n    backendTest();\n}\n<|endoftext|>"}
{"text":"\/*************************************************************************\n *\n *  $RCSfile: virtualmachine.hxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: obo $ $Date: 2005-06-17 09:20:34 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#if !defined INCLUDED_JVMACCESS_VIRTUALMACHINE_HXX\n#define INCLUDED_JVMACCESS_VIRTUALMACHINE_HXX\n\n#include \"rtl\/ref.hxx\"\n#include \"salhelper\/simplereferenceobject.hxx\"\n\n#ifdef SOLAR_JAVA\n#include \"jni.h\"\n#else\nstruct JNIEnv;\nstruct JavaVM;\ntypedef int jint;\ntypedef void * jobject;\n#endif\n\nnamespace jvmaccess {\n\n\/** An encapsulating wrapper around a Java virtual machine.\n *\/\nclass VirtualMachine: public salhelper::SimpleReferenceObject\n{\npublic:\n    \/** A helper to attach a thread to a Java virtual machine.\n\n        @descr\n        Upon construction of a guard the current thread is attached to the\n        virtual machine, and upon destruction of the guard the thread is\n        detached again.  For any one thread, multiple instances of this class\n        may be used in a stack-like fashion (care is taken to only really\n        detach the thread from the virtual machine upon destruction of the guard\n        at the bottom of the stack).\n     *\/\n    class AttachGuard\n    {\n    public:\n        \/** An exception indicating failure to create an AttachGuard.\n         *\/\n        class CreationException\n        {\n        public:\n            CreationException();\n\n            CreationException(CreationException const &);\n\n            virtual ~CreationException();\n\n            CreationException & operator =(CreationException const &);\n        };\n\n        \/** Attach the current thread to a virtual machine.\n\n            @param rMachine\n            The virtual machine to attach to.  Must not be a null reference.\n\n            @exception CreationException\n            Thrown in case attaching fails (due to a JNI problem).\n         *\/\n        explicit AttachGuard(rtl::Reference< VirtualMachine > const & rMachine);\n\n        \/** Detach the current thread from the virtual machine again.\n         *\/\n        ~AttachGuard();\n\n        \/** Get a JNI environment pointer for the current thread.\n\n            @return\n            A valid JNI environment pointer.  Will never be null.\n         *\/\n        inline JNIEnv * getEnvironment() const { return m_pEnvironment; }\n\n    private:\n        AttachGuard(AttachGuard &); \/\/ not implemented\n        void operator =(AttachGuard); \/\/ not implemented\n\n        rtl::Reference< VirtualMachine > m_xMachine;\n        JNIEnv * m_pEnvironment;\n        bool m_bDetach;\n    };\n\n    \/** Create a wrapper around a Java virtual machine.\n\n        @param pVm\n        A JNI pointer to virtual machine.  Must not be null.\n\n        @param nVersion\n        The JNI version of the virtual machine pointed to by pVm.  Must be at\n        least JNI_VERSION_1_2.  This parameter should be of type jint, not int,\n        but at least on some platforms the definition of jint changed from\n        JDK 1.3 (long) to JDK 1.4 (int), so that the mangled C++ name of the\n        constructor would depend on the JDK version used at compile time.\n\n        @param bDestroy\n        Whether to destroy the virtual machine when destructing the wrapper\n        (i.e., whether the wrapper owns the virtual machine pointed to by pVm).\n\n        @param pMainThreadEnv\n        A valid JNI environment pointer for the current thread; must not be\n        null.  The current thread must be \"initially attached\" to the virtual\n        machine while this constructor is being called (i.e., it must be the\n        thread that has called JNI_CreateJavaVM in case the virtual machine has\n        been started via the JNI Invocation API, and it must not already have\n        called DetachCurrentThread; or it must be executing native code called\n        from a \"primordial\" virtual machine).  This environment pointer is used\n        to obtain a reference to the thread's current context class loader\n        (java.lang.Thread.getCurrentClassLoader).  If later a native thread is\n        attached to the virtual machine, that thread's context class loader\n        would be null, so the AttachGuard first of all sets it to the saved\n        value.  In a nutshell, this means that all native threads attached to\n        the virtual machine use the context class loader of the \"initial Java\n        thread.\"\n     *\/\n    VirtualMachine(JavaVM * pVm, int nVersion, bool bDestroy,\n                   JNIEnv * pMainThreadEnv);\n\nprivate:\n    VirtualMachine(VirtualMachine &); \/\/ not implemented\n    void operator =(VirtualMachine); \/\/ not implemented\n\n    virtual ~VirtualMachine();\n\n    void acquireInitialContextClassLoader(JNIEnv * pEnv);\n\n    void releaseInitialContextClassLoader() const;\n\n    JNIEnv * attachThread(bool * pAttached) const;\n\n    void detachThread() const;\n\n    JavaVM * m_pVm;\n    jint m_nVersion;\n    bool m_bDestroy;\n    jobject m_aInitialContextClassLoader;\n\n    friend class AttachGuard; \/\/ to access attachThread, detachThread\n};\n\n}\n\n#endif \/\/ INCLUDED_JVMACCESS_VIRTUALMACHINE_HXX\nINTEGRATION: CWS ooo19126 (1.5.8); FILE MERGED 2005\/09\/05 14:40:56 rt 1.5.8.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: virtualmachine.hxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-07 19:22:30 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#if !defined INCLUDED_JVMACCESS_VIRTUALMACHINE_HXX\n#define INCLUDED_JVMACCESS_VIRTUALMACHINE_HXX\n\n#include \"rtl\/ref.hxx\"\n#include \"salhelper\/simplereferenceobject.hxx\"\n\n#ifdef SOLAR_JAVA\n#include \"jni.h\"\n#else\nstruct JNIEnv;\nstruct JavaVM;\ntypedef int jint;\ntypedef void * jobject;\n#endif\n\nnamespace jvmaccess {\n\n\/** An encapsulating wrapper around a Java virtual machine.\n *\/\nclass VirtualMachine: public salhelper::SimpleReferenceObject\n{\npublic:\n    \/** A helper to attach a thread to a Java virtual machine.\n\n        @descr\n        Upon construction of a guard the current thread is attached to the\n        virtual machine, and upon destruction of the guard the thread is\n        detached again.  For any one thread, multiple instances of this class\n        may be used in a stack-like fashion (care is taken to only really\n        detach the thread from the virtual machine upon destruction of the guard\n        at the bottom of the stack).\n     *\/\n    class AttachGuard\n    {\n    public:\n        \/** An exception indicating failure to create an AttachGuard.\n         *\/\n        class CreationException\n        {\n        public:\n            CreationException();\n\n            CreationException(CreationException const &);\n\n            virtual ~CreationException();\n\n            CreationException & operator =(CreationException const &);\n        };\n\n        \/** Attach the current thread to a virtual machine.\n\n            @param rMachine\n            The virtual machine to attach to.  Must not be a null reference.\n\n            @exception CreationException\n            Thrown in case attaching fails (due to a JNI problem).\n         *\/\n        explicit AttachGuard(rtl::Reference< VirtualMachine > const & rMachine);\n\n        \/** Detach the current thread from the virtual machine again.\n         *\/\n        ~AttachGuard();\n\n        \/** Get a JNI environment pointer for the current thread.\n\n            @return\n            A valid JNI environment pointer.  Will never be null.\n         *\/\n        inline JNIEnv * getEnvironment() const { return m_pEnvironment; }\n\n    private:\n        AttachGuard(AttachGuard &); \/\/ not implemented\n        void operator =(AttachGuard); \/\/ not implemented\n\n        rtl::Reference< VirtualMachine > m_xMachine;\n        JNIEnv * m_pEnvironment;\n        bool m_bDetach;\n    };\n\n    \/** Create a wrapper around a Java virtual machine.\n\n        @param pVm\n        A JNI pointer to virtual machine.  Must not be null.\n\n        @param nVersion\n        The JNI version of the virtual machine pointed to by pVm.  Must be at\n        least JNI_VERSION_1_2.  This parameter should be of type jint, not int,\n        but at least on some platforms the definition of jint changed from\n        JDK 1.3 (long) to JDK 1.4 (int), so that the mangled C++ name of the\n        constructor would depend on the JDK version used at compile time.\n\n        @param bDestroy\n        Whether to destroy the virtual machine when destructing the wrapper\n        (i.e., whether the wrapper owns the virtual machine pointed to by pVm).\n\n        @param pMainThreadEnv\n        A valid JNI environment pointer for the current thread; must not be\n        null.  The current thread must be \"initially attached\" to the virtual\n        machine while this constructor is being called (i.e., it must be the\n        thread that has called JNI_CreateJavaVM in case the virtual machine has\n        been started via the JNI Invocation API, and it must not already have\n        called DetachCurrentThread; or it must be executing native code called\n        from a \"primordial\" virtual machine).  This environment pointer is used\n        to obtain a reference to the thread's current context class loader\n        (java.lang.Thread.getCurrentClassLoader).  If later a native thread is\n        attached to the virtual machine, that thread's context class loader\n        would be null, so the AttachGuard first of all sets it to the saved\n        value.  In a nutshell, this means that all native threads attached to\n        the virtual machine use the context class loader of the \"initial Java\n        thread.\"\n     *\/\n    VirtualMachine(JavaVM * pVm, int nVersion, bool bDestroy,\n                   JNIEnv * pMainThreadEnv);\n\nprivate:\n    VirtualMachine(VirtualMachine &); \/\/ not implemented\n    void operator =(VirtualMachine); \/\/ not implemented\n\n    virtual ~VirtualMachine();\n\n    void acquireInitialContextClassLoader(JNIEnv * pEnv);\n\n    void releaseInitialContextClassLoader() const;\n\n    JNIEnv * attachThread(bool * pAttached) const;\n\n    void detachThread() const;\n\n    JavaVM * m_pVm;\n    jint m_nVersion;\n    bool m_bDestroy;\n    jobject m_aInitialContextClassLoader;\n\n    friend class AttachGuard; \/\/ to access attachThread, detachThread\n};\n\n}\n\n#endif \/\/ INCLUDED_JVMACCESS_VIRTUALMACHINE_HXX\n<|endoftext|>"}
{"text":"\/\/=======================================================================\n\/\/ Copyright (c) 2014-2015 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n\n#include \"catch.hpp\"\n\n#include \"dll\/dbn.hpp\"\n#include \"dll\/stochastic_gradient_descent.hpp\"\n\n#include \"mnist\/mnist_reader.hpp\"\n#include \"mnist\/mnist_utils.hpp\"\n\nTEST_CASE( \"dbn\/sgd\/1\", \"[dbn][mnist][sgd]\" ) {\n    typedef dll::dbn_desc<\n        dll::dbn_layers<\n            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,\n            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,\n            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::rbm_t>\n        , dll::trainer\n        , dll::batch_size<10>\n        >::dbn_t dbn_t;\n\n    auto dataset = mnist::read_dataset(500);\n\n    REQUIRE(!dataset.training_images.empty());\n\n    mnist::binarize_dataset(dataset);\n\n    auto dbn = std::make_unique();\n\n    dbn->learning_rate = 0.3;\n\n    dbn->pretrain(dataset.training_images, 20);\n    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);\n\n    REQUIRE(error < 5e-2);\n\n    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n\n    std::cout << \"test_error:\" << test_error << std::endl;\n\n    REQUIRE(test_error < 0.2);\n}\n\nTEST_CASE( \"dbn\/sgd\/2\", \"[dbn][mnist][sgd]\" ) {\n    typedef dll::dbn_desc<\n        dll::dbn_layers<\n            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,\n            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,\n            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::rbm_t>\n        , dll::trainer\n        , dll::momentum\n        , dll::batch_size<10>\n        >::dbn_t dbn_t;\n\n    auto dataset = mnist::read_dataset(1000);\n\n    REQUIRE(!dataset.training_images.empty());\n\n    mnist::binarize_dataset(dataset);\n\n    auto dbn = std::make_unique();\n\n    dbn->learning_rate = 0.05;\n\n    dbn->pretrain(dataset.training_images, 20);\n    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);\n\n    REQUIRE(error < 5e-2);\n\n    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n\n    std::cout << \"test_error:\" << test_error << std::endl;\n\n    REQUIRE(test_error < 0.2);\n}\n\nTEST_CASE( \"dbn\/sgd\/3\", \"[dbn][mnist][sgd][gaussian]\" ) {\n    typedef dll::dbn_desc<\n        dll::dbn_layers<\n            dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<25>, dll::visible>::rbm_t,\n            dll::rbm_desc<200, 500, dll::momentum, dll::batch_size<25>>::rbm_t,\n            dll::rbm_desc<500, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::rbm_t>\n        , dll::trainer\n        , dll::batch_size<10>\n        >::dbn_t dbn_t;\n\n    auto dataset = mnist::read_dataset(1000);\n\n    REQUIRE(!dataset.training_images.empty());\n\n    mnist::normalize_dataset(dataset);\n\n    auto dbn = std::make_unique();\n\n    dbn->learning_rate = 0.1;\n\n    dbn->pretrain(dataset.training_images, 20);\n    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);\n\n    REQUIRE(error < 5e-2);\n\n    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n\n    std::cout << \"test_error:\" << test_error << std::endl;\n\n    REQUIRE(test_error < 0.2);\n}\n\n\/\/This test should not perform well, but should not fail\nTEST_CASE( \"dbn\/sgd\/4\", \"[dbn][mnist][sgd][relu]\" ) {\n    typedef dll::dbn_desc<\n        dll::dbn_layers<\n            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::hidden, dll::init_weights>::rbm_t,\n            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,\n            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::rbm_t>\n        , dll::trainer\n        , dll::batch_size<10>\n        >::dbn_t dbn_t;\n\n    auto dataset = mnist::read_dataset(200);\n\n    REQUIRE(!dataset.training_images.empty());\n\n    mnist::binarize_dataset(dataset);\n\n    auto dbn = std::make_unique();\n\n    dbn->learning_rate = 0.1;\n\n    dbn->pretrain(dataset.training_images, 20);\n    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);\n\n    REQUIRE(std::isfinite(error));\n}\n\nTEST_CASE( \"dbn\/sgd\/5\", \"[dbn][mnist][sgd]\" ) {\n    typedef dll::dbn_desc<\n        dll::dbn_layers<\n            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,\n            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,\n            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::rbm_t>\n        , dll::trainer\n        , dll::weight_decay\n        , dll::batch_size<10>\n        >::dbn_t dbn_t;\n\n    auto dataset = mnist::read_dataset();\n\n    REQUIRE(!dataset.training_images.empty());\n    dataset.training_images.resize(200);\n    dataset.training_labels.resize(200);\n\n    mnist::binarize_dataset(dataset);\n\n    auto dbn = std::make_unique();\n\n    dbn->learning_rate = 0.1;\n\n    dbn->pretrain(dataset.training_images, 5);\n    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 200);\n\n    REQUIRE(error < 1e-1);\n}\n\nTEST_CASE( \"dbn\/sgd\/6\", \"[dbn][mnist][sgd]\" ) {\n    typedef dll::dbn_desc<\n        dll::dbn_layers<\n            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,\n            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,\n            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::rbm_t>\n        , dll::trainer\n        , dll::momentum\n        , dll::weight_decay\n        , dll::batch_size<100>\n        >::dbn_t dbn_t;\n\n    auto dataset = mnist::read_dataset();\n\n    REQUIRE(!dataset.training_images.empty());\n    dataset.training_images.resize(200);\n    dataset.training_labels.resize(200);\n\n    mnist::binarize_dataset(dataset);\n\n    auto dbn = std::make_unique();\n\n    dbn->learning_rate = 0.1;\n\n    dbn->pretrain(dataset.training_images, 10);\n    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 200);\n\n    REQUIRE(error < 5e-2);\n}\n\nTEST_CASE( \"dbn\/sgd\/7\", \"[dbn][mnist][sgd][memory]\" ) {\n    typedef dll::dbn_desc<\n        dll::dbn_layers<\n            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,\n            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,\n            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::rbm_t>\n        , dll::trainer\n        , dll::memory\n        , dll::batch_size<10>\n        >::dbn_t dbn_t;\n\n    auto dataset = mnist::read_dataset(500);\n\n    REQUIRE(!dataset.training_images.empty());\n\n    mnist::binarize_dataset(dataset);\n\n    auto dbn = std::make_unique();\n\n    dbn->learning_rate = 0.1;\n\n    dbn->pretrain(dataset.training_images, 20);\n    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);\n\n    REQUIRE(error < 5e-2);\n\n    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n\n    std::cout << \"test_error:\" << test_error << std::endl;\n\n    REQUIRE(test_error < 0.2);\n}\nComplete the test\/\/=======================================================================\n\/\/ Copyright (c) 2014-2015 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n\n#include \"catch.hpp\"\n\n#include \"dll\/dbn.hpp\"\n#include \"dll\/dense_stochastic_gradient_descent.hpp\"\n\n#include \"mnist\/mnist_reader.hpp\"\n#include \"mnist\/mnist_utils.hpp\"\n\nTEST_CASE( \"dbn\/sgd\/1\", \"[dbn][mnist][sgd]\" ) {\n    typedef dll::dbn_desc<\n        dll::dbn_layers<\n            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,\n            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,\n            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::rbm_t>\n        , dll::trainer\n        , dll::batch_size<10>\n        >::dbn_t dbn_t;\n\n    auto dataset = mnist::read_dataset(500);\n    REQUIRE(!dataset.training_images.empty());\n\n    mnist::binarize_dataset(dataset);\n\n    auto dbn = std::make_unique();\n\n    dbn->pretrain(dataset.training_images, 50);\n\n    dbn->learning_rate = 0.1;\n\n    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);\n    std::cout << \"ft_error:\" << ft_error << std::endl;\n    CHECK(ft_error < 5e-2);\n\n    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n    std::cout << \"test_error:\" << test_error << std::endl;\n    REQUIRE(test_error < 0.2);\n}\n\nTEST_CASE( \"dbn\/sgd\/2\", \"[dbn][mnist][sgd]\" ) {\n    typedef dll::dbn_desc<\n        dll::dbn_layers<\n            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,\n            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,\n            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::rbm_t>\n        , dll::trainer\n        , dll::momentum\n        , dll::batch_size<10>\n        >::dbn_t dbn_t;\n\n    auto dataset = mnist::read_dataset(1000);\n\n    REQUIRE(!dataset.training_images.empty());\n\n    mnist::binarize_dataset(dataset);\n\n    auto dbn = std::make_unique();\n\n    dbn->learning_rate = 0.05;\n\n    dbn->pretrain(dataset.training_images, 20);\n\n    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);\n    REQUIRE(error < 5e-2);\n\n    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n    std::cout << \"test_error:\" << test_error << std::endl;\n    REQUIRE(test_error < 0.2);\n}\n\nTEST_CASE( \"dbn\/sgd\/3\", \"[dbn][mnist][sgd][gaussian]\" ) {\n    typedef dll::dbn_desc<\n        dll::dbn_layers<\n            dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<25>, dll::visible>::rbm_t,\n            dll::rbm_desc<200, 500, dll::momentum, dll::batch_size<25>>::rbm_t,\n            dll::rbm_desc<500, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::rbm_t>\n        , dll::trainer\n        , dll::batch_size<10>\n        >::dbn_t dbn_t;\n\n    auto dataset = mnist::read_dataset(1000);\n\n    REQUIRE(!dataset.training_images.empty());\n\n    mnist::normalize_dataset(dataset);\n\n    auto dbn = std::make_unique();\n\n    dbn->learning_rate = 0.1;\n\n    dbn->pretrain(dataset.training_images, 20);\n    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);\n\n    REQUIRE(error < 5e-2);\n\n    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n    std::cout << \"test_error:\" << test_error << std::endl;\n    REQUIRE(test_error < 0.2);\n}\n\n\/\/This test should not perform well, but should not fail\n\/\/TODO This should be improved\nTEST_CASE( \"dbn\/sgd\/4\", \"[dbn][mnist][sgd][relu]\" ) {\n    typedef dll::dbn_desc<\n        dll::dbn_layers<\n            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::hidden, dll::init_weights>::rbm_t,\n            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,\n            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::rbm_t>\n        , dll::trainer\n        , dll::batch_size<10>\n        >::dbn_t dbn_t;\n\n    auto dataset = mnist::read_dataset(200);\n\n    REQUIRE(!dataset.training_images.empty());\n\n    mnist::binarize_dataset(dataset);\n\n    auto dbn = std::make_unique();\n\n    dbn->learning_rate = 0.1;\n\n    dbn->pretrain(dataset.training_images, 20);\n    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);\n\n    REQUIRE(std::isfinite(error));\n}\n\nTEST_CASE( \"dbn\/sgd\/5\", \"[dbn][mnist][sgd]\" ) {\n    typedef dll::dbn_desc<\n        dll::dbn_layers<\n            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,\n            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,\n            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::rbm_t>\n        , dll::trainer\n        , dll::weight_decay\n        , dll::batch_size<10>\n        >::dbn_t dbn_t;\n\n    auto dataset = mnist::read_dataset(200);\n    REQUIRE(!dataset.training_images.empty());\n\n    mnist::binarize_dataset(dataset);\n\n    auto dbn = std::make_unique();\n\n    dbn->learning_rate = 0.1;\n\n    dbn->pretrain(dataset.training_images, 20);\n\n    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 200);\n    REQUIRE(error < 1e-1);\n}\n\n\/\/Here to test large batch size\nTEST_CASE( \"dbn\/sgd\/6\", \"[dbn][mnist][sgd]\" ) {\n    typedef dll::dbn_desc<\n        dll::dbn_layers<\n            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,\n            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,\n            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::rbm_t>\n        , dll::trainer\n        , dll::momentum\n        , dll::weight_decay\n        , dll::batch_size<100>\n        >::dbn_t dbn_t;\n\n    auto dataset = mnist::read_dataset(300);\n    REQUIRE(!dataset.training_images.empty());\n\n    mnist::binarize_dataset(dataset);\n\n    auto dbn = std::make_unique();\n\n    dbn->learning_rate = 0.1;\n\n    dbn->pretrain(dataset.training_images, 10);\n\n    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);\n    REQUIRE(error < 1e-1);\n}\n\nTEST_CASE( \"dbn\/sgd\/7\", \"[dbn][mnist][sgd][memory]\" ) {\n    typedef dll::dbn_desc<\n        dll::dbn_layers<\n            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,\n            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,\n            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::rbm_t>\n        , dll::trainer\n        , dll::memory\n        , dll::batch_size<10>\n        >::dbn_t dbn_t;\n\n    auto dataset = mnist::read_dataset(500);\n    REQUIRE(!dataset.training_images.empty());\n\n    mnist::binarize_dataset(dataset);\n\n    auto dbn = std::make_unique();\n\n    dbn->pretrain(dataset.training_images, 20);\n\n    dbn->learning_rate = 0.1;\n\n    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);\n    REQUIRE(error < 5e-2);\n\n    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n    std::cout << \"test_error:\" << test_error << std::endl;\n    REQUIRE(test_error < 0.2);\n}\n<|endoftext|>"}
{"text":"#include \n\nstruct A {\n\tint a;\n\tA()\n\t\t: a(5)\n\t{\n\t\tputs(\"A cstr\");\n\t}\n\t~A()\n\t{\n\t\tputs(\"A dstr\");\n\t}\n\tvoid put() const\n\t{\n\t\tprintf(\"a=%d\\n\", a);\n\t}\n};\n\ntemplate\nstruct XT {\n\tstatic A a;\n};\n\ntemplate\nA XT::a;\n\ntypedef XT<0> X;\n\nstatic struct Init {\n\tInit()\n\t{\n\t\tputs(\"Init\");\n\t\tX::a.put();\n\t}\n} s_init;\n\n\nint main()\n{\n\tputs(\"main\");\n\tX::a.put();\n}\nchange name of var#include \n\nstruct A {\n\tint aaa;\n\tA()\n\t\t: aaa(123)\n\t{\n\t\tputs(\"A cstr\");\n\t}\n\t~A()\n\t{\n\t\tputs(\"A dstr\");\n\t}\n\tvoid put() const\n\t{\n\t\tprintf(\"aaa=%d\\n\", aaa);\n\t}\n};\n\ntemplate\nstruct XT {\n\tstatic A sss;\n};\n\ntemplate\nA XT::sss;\n\ntypedef XT<0> X;\n\nstatic struct Init {\n\tInit()\n\t{\n\t\tputs(\"Init\");\n\t\tX::sss.put();\n\t}\n} s_init;\n\n\nint main()\n{\n\tputs(\"main\");\n\tX::sss.put();\n}\n<|endoftext|>"}
{"text":"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2012 Alexey Korepanov \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"main.h\"\n#include \n#include \n\ntemplate void real_qz(const MatrixType& m)\n{\n  \/* this test covers the following files:\n     RealQZ.h\n  *\/\n  using std::abs;\n  typedef typename MatrixType::Index Index;\n  typedef typename MatrixType::Scalar Scalar;\n  \n  Index dim = m.cols();\n  \n  MatrixType A = MatrixType::Random(dim,dim),\n             B = MatrixType::Random(dim,dim);\n\n\n  \/\/ Regression test for bug 985: Randomly set rows or columns to zero\n  Index k=internal::random(0, dim-1);\n  switch(internal::random(0,10)) {\n  case 0:\n    A.row(k).setZero(); break;\n  case 1:\n    A.col(k).setZero(); break;\n  case 2:\n    B.row(k).setZero(); break;\n  case 3:\n    B.col(k).setZero(); break;\n  default:\n    break;\n  }\n\n  RealQZ qz(A,B);\n  \n  VERIFY_IS_EQUAL(qz.info(), Success);\n  \/\/ check for zeros\n  bool all_zeros = true;\n  for (Index i=0; i0 && abs(qz.matrixS()(i,j))!=Scalar(0.0) && abs(qz.matrixS()(i-1,j-1))!=Scalar(0.0))\n        all_zeros = false;\n    }\n  VERIFY_IS_EQUAL(all_zeros, true);\n  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixS()*qz.matrixZ(), A);\n  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixT()*qz.matrixZ(), B);\n  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixQ().adjoint(), MatrixType::Identity(dim,dim));\n  VERIFY_IS_APPROX(qz.matrixZ()*qz.matrixZ().adjoint(), MatrixType::Identity(dim,dim));\n}\n\nvoid test_real_qz()\n{\n  int s = 0;\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_1( real_qz(Matrix4f()) );\n    s = internal::random(1,EIGEN_TEST_MAX_SIZE\/4);\n    CALL_SUBTEST_2( real_qz(MatrixXd(s,s)) );\n\n    \/\/ some trivial but implementation-wise tricky cases\n    CALL_SUBTEST_2( real_qz(MatrixXd(1,1)) );\n    CALL_SUBTEST_2( real_qz(MatrixXd(2,2)) );\n    CALL_SUBTEST_3( real_qz(Matrix()) );\n    CALL_SUBTEST_4( real_qz(Matrix2d()) );\n  }\n  \n  TEST_SET_BUT_UNUSED_VARIABLE(s)\n}\nAddendum to last patch: k is Index and not int (transplanted from 01a0782f0768a79972ea5bff5a43711114017e96)\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2012 Alexey Korepanov \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"main.h\"\n#include \n#include \n\ntemplate void real_qz(const MatrixType& m)\n{\n  \/* this test covers the following files:\n     RealQZ.h\n  *\/\n  using std::abs;\n  typedef typename MatrixType::Index Index;\n  typedef typename MatrixType::Scalar Scalar;\n  \n  Index dim = m.cols();\n  \n  MatrixType A = MatrixType::Random(dim,dim),\n             B = MatrixType::Random(dim,dim);\n\n\n  \/\/ Regression test for bug 985: Randomly set rows or columns to zero\n  Index k=internal::random(0, dim-1);\n  switch(internal::random(0,10)) {\n  case 0:\n    A.row(k).setZero(); break;\n  case 1:\n    A.col(k).setZero(); break;\n  case 2:\n    B.row(k).setZero(); break;\n  case 3:\n    B.col(k).setZero(); break;\n  default:\n    break;\n  }\n\n  RealQZ qz(A,B);\n  \n  VERIFY_IS_EQUAL(qz.info(), Success);\n  \/\/ check for zeros\n  bool all_zeros = true;\n  for (Index i=0; i0 && abs(qz.matrixS()(i,j))!=Scalar(0.0) && abs(qz.matrixS()(i-1,j-1))!=Scalar(0.0))\n        all_zeros = false;\n    }\n  VERIFY_IS_EQUAL(all_zeros, true);\n  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixS()*qz.matrixZ(), A);\n  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixT()*qz.matrixZ(), B);\n  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixQ().adjoint(), MatrixType::Identity(dim,dim));\n  VERIFY_IS_APPROX(qz.matrixZ()*qz.matrixZ().adjoint(), MatrixType::Identity(dim,dim));\n}\n\nvoid test_real_qz()\n{\n  int s = 0;\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_1( real_qz(Matrix4f()) );\n    s = internal::random(1,EIGEN_TEST_MAX_SIZE\/4);\n    CALL_SUBTEST_2( real_qz(MatrixXd(s,s)) );\n\n    \/\/ some trivial but implementation-wise tricky cases\n    CALL_SUBTEST_2( real_qz(MatrixXd(1,1)) );\n    CALL_SUBTEST_2( real_qz(MatrixXd(2,2)) );\n    CALL_SUBTEST_3( real_qz(Matrix()) );\n    CALL_SUBTEST_4( real_qz(Matrix2d()) );\n  }\n  \n  TEST_SET_BUT_UNUSED_VARIABLE(s)\n}\n<|endoftext|>"}
{"text":"\/\/ @(#)root\/test:$Id$\n\/\/ Author: Fons Rademakers   19\/08\/96\n\n#include \n\n#include \"Riostream.h\"\n#include \"TString.h\"\n#include \"TRegexp.h\"\n#include \"TPRegexp.h\"\n\n\nvoid Ok(int i, int b)\n{\n   cout << \"Test \" << i;\n   if (b)\n      cout << \"   ok\" << endl;\n   else\n      cout << \"   NOT ok\" << endl;\n}\n\n\n\nint main()\n{\n   \/\/ create base string\n   TString s = \"aap noot mies\";\n   cout << s << endl;\n\n   \/\/ use different constructors and excercise +, += and == operators\n   TString s1 = TString(\"aa\") + \"p \";\n   s1 += TString(\"noot \") + \"mi\" + \"es\";\n   cout << s1 << endl;\n   Ok(1, s1==s);\n\n   \/\/ use single char constructor and excercise again += and == operators\n   TString s2 = 'a';\n   s2 += \"ap \";\n   s2 += \"noot \";\n   s2 += \"mies\";\n   cout << s2 << endl;\n   Ok(2, s2==s);\n\n   \/\/ get and set a subrange (via TSubString)\n   TString s3 = s(4,9);\n   s3(0,4) = \"mama papa\";\n   cout << s3 << endl;\n   Ok(3, s3==\"mama papa mies\");\n\n   \/\/ create a regular expression, make search in string and replace\n   \/\/ matched substring\n   TRegexp re(\" n.*t \");\n   TString s4 = s;\n   s4(re) = \" pipo \";\n   cout << s4 << endl;\n   Ok(4, s4==\"aap pipo mies\");\n\n   \/\/ use \"const char*\" operator and the Data() member function to access\n   \/\/ the string as a const char*\n   const char *a = (const char*)s;\n   cout << a << endl;\n   Ok(5, !strcmp(a, s.Data()));\n\n   \/\/ return 13th character and replace it by 't', getting 14th character\n   \/\/ should result in an error message since operator[] uses range checking\n   TString s6 = s;\n   s6[12] = 't';\n   cout << s6 << endl;\n   cout << \"*** Error message ok, accessing intentionaly out-of-bounds\" << endl;\n   char b = s6[13];\n   cout << b << endl;\n   Ok(6, s6==\"aap noot miet\");\n\n   \/\/ return 13th character and replace it by 'p', getting 14th character\n   \/\/ should NOT result in an error message since operator() does not use\n   \/\/ range checking\n   TString s7 = s;\n   s7(12) = 'p';\n   cout << s7 << endl;\n   char c = s7(13);\n   cout << c << endl;\n   Ok(7, s7==\"aap noot miep\");\n\n   \/\/ use Append, Remove, Prepend, Replace and Insert\n   TString s8 = s;\n   s8.Append(\" tante \");\n   s8.Append(s7(9,4));\n   cout << s8 << endl;\n\n   s8.Remove(0,14);\n   cout << s8 << endl;\n   s8.Prepend(\"oom jan\");\n   cout << s8 << endl;\n   s8.Insert(7,\" en \");\n   cout << s8 << endl;\n   s8.Replace(4,3,\"jaap\");\n   cout << s8 << endl;\n   Ok(8, s8==\"oom jaap en tante miep\");\n\n   \/\/ use CompareTo to compare char * and TString\n   TString s9 = s;\n   Ok(9,  !s9.CompareTo(s));\n   Ok(10, !s9.CompareTo(\"AAP NOOT MIES\", TString::kIgnoreCase));\n\n   \/\/ use Contains to find if \"string\" is contained\n   Ok(11, s9.Contains(\"NooT\", TString::kIgnoreCase));\n   Ok(12, !s9.Contains(\"pipo\"));\n\n   \/\/ return the index to the first and last character 'c'\n   Ok(13, s.First('o')==5);\n   Ok(14, s.First('z')==kNPOS);\n   Ok(15, s.Last('a')==1);\n   Ok(16, s.Last('z')==kNPOS);\n\n   \/\/ returns the index of the start of match\n   Ok(17, s.Index(\"mies\")==9);\n   Ok(18, s.Index(\"aa\",1)==kNPOS);\n\n   \/\/ returns length of string\n   Ok(19, s.Length()==13);\n\n   \/\/ test IsNull\n   TString s10;\n\n   Ok(20, s10.IsNull());\n   Ok(21, !s.IsNull());\n\n   \/\/ test IsAscii\n   s10 = \"\\xb9\";\n\n   Ok(22, !s10.IsAscii());\n   Ok(23, s.IsAscii());\n\n   \/\/ some excercises with the Perl Compatible Regular Expressions\n   TString s11(\"Food is on the foo table.\");\n   TPRegexp(\"\\\\b(foo)\\\\s+(\\\\w+)\").Substitute(s11, \"round $2\");\n   Ok(24, s11==\"Food is on the round table.\");\n\n   TString s12(\"pepernotenkoek\");\n   TPRegexp(\"peper(.*)koek\").Substitute(s12, \"wal$1boom\");\n   Ok(25, s12==\"walnotenboom\");\n\n   TString s13(\"hihi haha\");\n   TPRegexp(\"^([^ ]*) *([^ ]*)\").Substitute(s13, \"$2 $1\");\n   Ok(26, s13==\"haha hihi\");\n\n   Ok(27, TPRegexp(\"^(\\\\w+) *(\\\\w+)\").Match(s13) == 3);\n\n   \/\/ test Resize and Strip\n   s9.Prepend(\"   \");\n   cout << s9 << endl;\n\n   s9.Resize(50);\n   cout << s9 << \"<Also test operator< with empty strings\/\/ @(#)root\/test:$Id$\n\/\/ Author: Fons Rademakers   19\/08\/96\n\n#include \n\n#include \"Riostream.h\"\n#include \"TString.h\"\n#include \"TRegexp.h\"\n#include \"TPRegexp.h\"\n\n\nvoid Ok(int i, int b)\n{\n   cout << \"Test \" << i;\n   if (b)\n      cout << \"   ok\" << endl;\n   else\n      cout << \"   NOT ok\" << endl;\n}\n\n\n\nint main()\n{\n   \/\/ create base string\n   TString s = \"aap noot mies\";\n   cout << s << endl;\n\n   \/\/ use different constructors and excercise +, += and == operators\n   TString s1 = TString(\"aa\") + \"p \";\n   s1 += TString(\"noot \") + \"mi\" + \"es\";\n   cout << s1 << endl;\n   Ok(1, s1==s);\n\n   \/\/ use single char constructor and excercise again += and == operators\n   TString s2 = 'a';\n   s2 += \"ap \";\n   s2 += \"noot \";\n   s2 += \"mies\";\n   cout << s2 << endl;\n   Ok(2, s2==s);\n\n   \/\/ get and set a subrange (via TSubString)\n   TString s3 = s(4,9);\n   s3(0,4) = \"mama papa\";\n   cout << s3 << endl;\n   Ok(3, s3==\"mama papa mies\");\n\n   \/\/ create a regular expression, make search in string and replace\n   \/\/ matched substring\n   TRegexp re(\" n.*t \");\n   TString s4 = s;\n   s4(re) = \" pipo \";\n   cout << s4 << endl;\n   Ok(4, s4==\"aap pipo mies\");\n\n   \/\/ use \"const char*\" operator and the Data() member function to access\n   \/\/ the string as a const char*\n   const char *a = (const char*)s;\n   cout << a << endl;\n   Ok(5, !strcmp(a, s.Data()));\n\n   \/\/ return 13th character and replace it by 't', getting 14th character\n   \/\/ should result in an error message since operator[] uses range checking\n   TString s6 = s;\n   s6[12] = 't';\n   cout << s6 << endl;\n   cout << \"*** Error message ok, accessing intentionaly out-of-bounds\" << endl;\n   char b = s6[13];\n   cout << b << endl;\n   Ok(6, s6==\"aap noot miet\");\n\n   \/\/ return 13th character and replace it by 'p', getting 14th character\n   \/\/ should NOT result in an error message since operator() does not use\n   \/\/ range checking\n   TString s7 = s;\n   s7(12) = 'p';\n   cout << s7 << endl;\n   char c = s7(13);\n   cout << c << endl;\n   Ok(7, s7==\"aap noot miep\");\n\n   \/\/ use Append, Remove, Prepend, Replace and Insert\n   TString s8 = s;\n   s8.Append(\" tante \");\n   s8.Append(s7(9,4));\n   cout << s8 << endl;\n\n   s8.Remove(0,14);\n   cout << s8 << endl;\n   s8.Prepend(\"oom jan\");\n   cout << s8 << endl;\n   s8.Insert(7,\" en \");\n   cout << s8 << endl;\n   s8.Replace(4,3,\"jaap\");\n   cout << s8 << endl;\n   Ok(8, s8==\"oom jaap en tante miep\");\n\n   \/\/ use CompareTo to compare char * and TString\n   TString s9 = s;\n   Ok(9,  !s9.CompareTo(s));\n   Ok(10, !s9.CompareTo(\"AAP NOOT MIES\", TString::kIgnoreCase));\n\n   \/\/ use Contains to find if \"string\" is contained\n   Ok(11, s9.Contains(\"NooT\", TString::kIgnoreCase));\n   Ok(12, !s9.Contains(\"pipo\"));\n\n   \/\/ return the index to the first and last character 'c'\n   Ok(13, s.First('o')==5);\n   Ok(14, s.First('z')==kNPOS);\n   Ok(15, s.Last('a')==1);\n   Ok(16, s.Last('z')==kNPOS);\n\n   \/\/ returns the index of the start of match\n   Ok(17, s.Index(\"mies\")==9);\n   Ok(18, s.Index(\"aa\",1)==kNPOS);\n\n   \/\/ returns length of string\n   Ok(19, s.Length()==13);\n\n   \/\/ test IsNull\n   TString s10;\n\n   Ok(20, s10.IsNull());\n   Ok(21, !s.IsNull());\n\n   \/\/ test IsAscii\n   s10 = \"\\xb9\";\n\n   Ok(22, !s10.IsAscii());\n   Ok(23, s.IsAscii());\n\n   \/\/ some excercises with the Perl Compatible Regular Expressions\n   TString s11(\"Food is on the foo table.\");\n   TPRegexp(\"\\\\b(foo)\\\\s+(\\\\w+)\").Substitute(s11, \"round $2\");\n   Ok(24, s11==\"Food is on the round table.\");\n\n   TString s12(\"pepernotenkoek\");\n   TPRegexp(\"peper(.*)koek\").Substitute(s12, \"wal$1boom\");\n   Ok(25, s12==\"walnotenboom\");\n\n   TString s13(\"hihi haha\");\n   TPRegexp(\"^([^ ]*) *([^ ]*)\").Substitute(s13, \"$2 $1\");\n   Ok(26, s13==\"haha hihi\");\n\n   Ok(27, TPRegexp(\"^(\\\\w+) *(\\\\w+)\").Match(s13) == 3);\n\n   \/\/ test Resize and Strip\n   s9.Prepend(\"   \");\n   cout << s9 << endl;\n\n   s9.Resize(50);\n   cout << s9 << \"<"}
{"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File: Tester.cpp\n\/\/\n\/\/ For more information, please see: http:\/\/www.nektar.info\n\/\/\n\/\/ The MIT License\n\/\/\n\/\/ Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),\n\/\/ Department of Aeronautics, Imperial College London (UK), and Scientific\n\/\/ Computing and Imaging Institute, University of Utah (USA).\n\/\/\n\/\/ License for the specific language governing rights and limitations under\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\/\/\n\/\/ Description: Tester executable.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Nektar;\n\n\/\/ Define some namespace aliases\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\nstring PortablePath(const boost::filesystem::path& path)\n{\n    boost::filesystem::path temp = path;\n#if BOOST_VERSION > 104200\n    temp.make_preferred();\n    return temp.string();\n#else\n    return temp.file_string();\n#endif\n}\n\nint main(int argc, char *argv[])\n{\n    int status = 0;\n    string command;\n\n    \/\/ Set up command line options.\n    po::options_description desc(\"Available options\");\n    desc.add_options()\n        (\"help,h\",                 \"Produce this help message.\")\n        (\"verbose,v\",              \"Turn on verbosity.\")\n        (\"generate-metric,g\",      po::value >(), \n                                   \"Generate a single metric.\")\n        (\"generate-all-metrics,a\", \"Generate all metrics.\");\n    \n    po::options_description hidden(\"Hidden options\");\n    hidden.add_options()\n        (\"input-file\",   po::value(), \"Input filename\");\n    \n    po::options_description cmdline_options;\n    cmdline_options.add(hidden).add(desc);\n    \n    po::options_description visible(\"Allowed options\");\n    visible.add(desc);\n    \n    po::positional_options_description p;\n    p.add(\"input-file\", -1);\n    \n    po::variables_map vm;\n    \n    try\n    {\n        po::store(po::command_line_parser(argc, argv).\n                  options(cmdline_options).positional(p).run(), vm);\n        po::notify(vm);\n    } \n    catch (const exception& e)\n    {\n        cerr << e.what() << endl;\n        cerr << desc;\n        return 1;\n    }\n\n    if (vm.count(\"help\") || vm.count(\"input-file\") != 1) {\n        cerr << \"Usage: Tester [options] input-file.tst\" << endl;\n        cout << desc;\n        return 1;\n    }\n    \n    \/\/ Set up set containing metrics to be generated.\n    vector metricGenVec;\n    if (vm.count(\"generate-metric\"))\n    {\n        metricGenVec = vm[\"generate-metric\"].as >();\n        cout << \"SIZE = \" << metricGenVec.size() << endl;\n    }\n    set metricGen(metricGenVec.begin(), metricGenVec.end());\n\n    \/\/ Path to test definition file\n    const fs::path specFile(vm[\"input-file\"].as());\n\n    \/\/ Parent path of test definition file containing dependent files\n    fs::path specPath = specFile.parent_path();\n\n    if (specPath.empty())\n    {\n        specPath = fs::current_path();\n    }\n\n    \/\/ Temporary directory to create and in which to conduct test\n    const fs::path tmpDir = fs::current_path()\n                            \/ fs::path(\"tmp_\" + specFile.stem().string());\n\n    \/\/ The current directory\n    const fs::path startDir = fs::current_path();\n\n    try\n    {\n        \/\/ Parse the test file\n        TestData file(specFile);\n\n        \/\/ Generate the metric objects\n        vector metrics;\n        for (unsigned int i = 0; i < file.GetNumMetrics(); ++i)\n        {\n            set::iterator it = metricGen.find(file.GetMetricId(i));\n            bool genMetric = it != metricGen.end() || \n                             (vm.count(\"generate-all-metrics\") > 0);\n            \n            metrics.push_back( GetMetricFactory().CreateInstance(\n                                                    file.GetMetricType(i),\n                                                    file.GetMetric(i),\n                                                    genMetric\n                                                  ));\n            \n            if (it != metricGen.end())\n            {\n                metricGen.erase(it);\n            }\n        }\n\n        if (metricGen.size() != 0)\n        {\n            string s = metricGen.size() == 1 ? \"s\" : \"\";\n            set::iterator it;\n            cerr << \"Unable to find metric\"+s+\" with ID\"+s+\" \";\n            for (it = metricGen.begin(); it != metricGen.end(); ++it)\n            {\n                cerr << *it << \" \";\n            }\n            cerr << endl;\n            return 1;\n        }\n\n        \/\/ Remove the temporary directory if left from a previous test\n        if (fs::exists(tmpDir))\n        {\n            fs::remove_all(tmpDir);\n        }\n\n        \/\/ Create temporary directory\n        fs::create_directory(tmpDir);\n\n        \/\/ Change working directory to the temporary directory\n        fs::current_path(tmpDir);\n\n        \/\/ Copy required files for this test from the test definition directory\n        \/\/ to the temporary directory.\n        for (unsigned int i = 0; i < file.GetNumDependentFiles(); ++i)\n        {\n            fs::path source_file(file.GetDependentFile(i).m_filename);\n\n            fs::path source = specPath \/ source_file;\n            fs::path dest   = tmpDir   \/ source_file;\n            fs::copy_file(source, dest);\n        }\n\n        \/\/ Construct test command to run. If in debug mode, append \"-g\"\n        \/\/ Output from stdout and stderr are directed to the files output.out\n        \/\/ and output.err, respectively.\n        if (file.GetNProcesses() > 1)\n        {\n            command += \"mpirun -np \"\n                    + boost::lexical_cast(file.GetNProcesses())\n                    + \" \";\n        }\n\n        \/\/ If executable doesn't exist in path then hope that it is in the\n        \/\/ user's PATH environment variable.\n        fs::path execPath = startDir \/ fs::path(file.GetExecutable());\n        if (!fs::exists(execPath))\n        {\n            execPath = fs::path(file.GetExecutable());\n        }\n\n        command += PortablePath(execPath);\n        command += \" \";\n        command += file.GetParameters();\n        command += \" 1>output.out 2>output.err\";\n\n        \/\/ Run executable to perform test.\n        if (system(command.c_str()))\n        {\n            cerr << \"Error occurred running test:\" << endl;\n            cerr << \"Command: \" << command << endl;\n            throw 1;\n        }\n\n        \/\/ Check output files exist\n        if (!(fs::exists(\"output.out\") && fs::exists(\"output.err\")))\n        {\n            cerr << \"One or more test output files are missing.\" << endl;\n            throw 1;\n        }\n\n        \/\/ Open output files and check they are readable\n        ifstream vStdout(\"output.out\");\n        ifstream vStderr(\"output.err\");\n        if (vStdout.bad() || vStderr.bad())\n        {\n            cerr << \"One or more test output files are unreadable.\" << endl;\n            throw 1;\n        }\n\n        \/\/ Test against all metrics\n        status = 0;\n        for (int i = 0; i < metrics.size(); ++i)\n        {\n            vStdout.clear();\n            vStderr.clear();\n            vStdout.seekg(0, ios::beg);\n            vStderr.seekg(0, ios::beg);\n            if (!metrics[i]->Test(vStdout, vStderr))\n            {\n                status = 1;\n            }\n        }\n\n        \/\/ Change back to the original path and delete temporary directory\n        fs::current_path(startDir);\n        fs::remove_all(tmpDir);\n        \n        \/\/ Save any changes.\n        if (vm.count(\"generate-metric\")      > 0 || \n            vm.count(\"generate-all-metrics\") > 0)\n        {\n            file.SaveFile();\n        }\n        \n        \/\/ Return status of test. 0 = PASS, 1 = FAIL\n        return status;\n    }\n    catch (const fs::filesystem_error& e)\n    {\n        cerr << \"Filesystem operation error occurred:\" << endl;\n        cerr << \"  \" << e.what() << endl;\n        cerr << \"  Files left in \" << tmpDir.string() << endl;\n    }\n    catch (...)\n    {\n        cerr << \"  Files left in \" << tmpDir.string() << endl;\n    }\n\n    \/\/ If a system error, return 2\n    return 2;\n}\nAnother fix for boost less than 1.42.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File: Tester.cpp\n\/\/\n\/\/ For more information, please see: http:\/\/www.nektar.info\n\/\/\n\/\/ The MIT License\n\/\/\n\/\/ Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),\n\/\/ Department of Aeronautics, Imperial College London (UK), and Scientific\n\/\/ Computing and Imaging Institute, University of Utah (USA).\n\/\/\n\/\/ License for the specific language governing rights and limitations under\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\/\/\n\/\/ Description: Tester executable.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Nektar;\n\n\/\/ Define some namespace aliases\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\nstring PortablePath(const boost::filesystem::path& path)\n{\n    boost::filesystem::path temp = path;\n#if BOOST_VERSION > 104200\n    temp.make_preferred();\n    return temp.string();\n#else\n    return temp.file_string();\n#endif\n}\n\nint main(int argc, char *argv[])\n{\n    int status = 0;\n    string command;\n\n    \/\/ Set up command line options.\n    po::options_description desc(\"Available options\");\n    desc.add_options()\n        (\"help,h\",                 \"Produce this help message.\")\n        (\"verbose,v\",              \"Turn on verbosity.\")\n        (\"generate-metric,g\",      po::value >(), \n                                   \"Generate a single metric.\")\n        (\"generate-all-metrics,a\", \"Generate all metrics.\");\n    \n    po::options_description hidden(\"Hidden options\");\n    hidden.add_options()\n        (\"input-file\",   po::value(), \"Input filename\");\n    \n    po::options_description cmdline_options;\n    cmdline_options.add(hidden).add(desc);\n    \n    po::options_description visible(\"Allowed options\");\n    visible.add(desc);\n    \n    po::positional_options_description p;\n    p.add(\"input-file\", -1);\n    \n    po::variables_map vm;\n    \n    try\n    {\n        po::store(po::command_line_parser(argc, argv).\n                  options(cmdline_options).positional(p).run(), vm);\n        po::notify(vm);\n    } \n    catch (const exception& e)\n    {\n        cerr << e.what() << endl;\n        cerr << desc;\n        return 1;\n    }\n\n    if (vm.count(\"help\") || vm.count(\"input-file\") != 1) {\n        cerr << \"Usage: Tester [options] input-file.tst\" << endl;\n        cout << desc;\n        return 1;\n    }\n    \n    \/\/ Set up set containing metrics to be generated.\n    vector metricGenVec;\n    if (vm.count(\"generate-metric\"))\n    {\n        metricGenVec = vm[\"generate-metric\"].as >();\n        cout << \"SIZE = \" << metricGenVec.size() << endl;\n    }\n    set metricGen(metricGenVec.begin(), metricGenVec.end());\n\n    \/\/ Path to test definition file\n    const fs::path specFile(vm[\"input-file\"].as());\n\n    \/\/ Parent path of test definition file containing dependent files\n    fs::path specPath = specFile.parent_path();\n\n    if (specPath.empty())\n    {\n        specPath = fs::current_path();\n    }\n\n#if BOOST_VERSION > 104200\n    string specFileStem = specFile.stem().string();\n#else\n    string specFileStem = specFile.stem().file_string();\n#endif\n\n    \/\/ Temporary directory to create and in which to conduct test\n    const fs::path tmpDir = fs::current_path()\n        \/ fs::path(\"tmp_\" + specFileStem);\n\n    \/\/ The current directory\n    const fs::path startDir = fs::current_path();\n\n    try\n    {\n        \/\/ Parse the test file\n        TestData file(specFile);\n\n        \/\/ Generate the metric objects\n        vector metrics;\n        for (unsigned int i = 0; i < file.GetNumMetrics(); ++i)\n        {\n            set::iterator it = metricGen.find(file.GetMetricId(i));\n            bool genMetric = it != metricGen.end() || \n                             (vm.count(\"generate-all-metrics\") > 0);\n            \n            metrics.push_back( GetMetricFactory().CreateInstance(\n                                                    file.GetMetricType(i),\n                                                    file.GetMetric(i),\n                                                    genMetric\n                                                  ));\n            \n            if (it != metricGen.end())\n            {\n                metricGen.erase(it);\n            }\n        }\n\n        if (metricGen.size() != 0)\n        {\n            string s = metricGen.size() == 1 ? \"s\" : \"\";\n            set::iterator it;\n            cerr << \"Unable to find metric\"+s+\" with ID\"+s+\" \";\n            for (it = metricGen.begin(); it != metricGen.end(); ++it)\n            {\n                cerr << *it << \" \";\n            }\n            cerr << endl;\n            return 1;\n        }\n\n        \/\/ Remove the temporary directory if left from a previous test\n        if (fs::exists(tmpDir))\n        {\n            fs::remove_all(tmpDir);\n        }\n\n        \/\/ Create temporary directory\n        fs::create_directory(tmpDir);\n\n        \/\/ Change working directory to the temporary directory\n        fs::current_path(tmpDir);\n\n        \/\/ Copy required files for this test from the test definition directory\n        \/\/ to the temporary directory.\n        for (unsigned int i = 0; i < file.GetNumDependentFiles(); ++i)\n        {\n            fs::path source_file(file.GetDependentFile(i).m_filename);\n\n            fs::path source = specPath \/ source_file;\n            fs::path dest   = tmpDir   \/ source_file;\n            fs::copy_file(source, dest);\n        }\n\n        \/\/ Construct test command to run. If in debug mode, append \"-g\"\n        \/\/ Output from stdout and stderr are directed to the files output.out\n        \/\/ and output.err, respectively.\n        if (file.GetNProcesses() > 1)\n        {\n            command += \"mpirun -np \"\n                    + boost::lexical_cast(file.GetNProcesses())\n                    + \" \";\n        }\n\n        \/\/ If executable doesn't exist in path then hope that it is in the\n        \/\/ user's PATH environment variable.\n        fs::path execPath = startDir \/ fs::path(file.GetExecutable());\n        if (!fs::exists(execPath))\n        {\n            execPath = fs::path(file.GetExecutable());\n        }\n\n        command += PortablePath(execPath);\n        command += \" \";\n        command += file.GetParameters();\n        command += \" 1>output.out 2>output.err\";\n\n        \/\/ Run executable to perform test.\n        if (system(command.c_str()))\n        {\n            cerr << \"Error occurred running test:\" << endl;\n            cerr << \"Command: \" << command << endl;\n            throw 1;\n        }\n\n        \/\/ Check output files exist\n        if (!(fs::exists(\"output.out\") && fs::exists(\"output.err\")))\n        {\n            cerr << \"One or more test output files are missing.\" << endl;\n            throw 1;\n        }\n\n        \/\/ Open output files and check they are readable\n        ifstream vStdout(\"output.out\");\n        ifstream vStderr(\"output.err\");\n        if (vStdout.bad() || vStderr.bad())\n        {\n            cerr << \"One or more test output files are unreadable.\" << endl;\n            throw 1;\n        }\n\n        \/\/ Test against all metrics\n        status = 0;\n        for (int i = 0; i < metrics.size(); ++i)\n        {\n            vStdout.clear();\n            vStderr.clear();\n            vStdout.seekg(0, ios::beg);\n            vStderr.seekg(0, ios::beg);\n            if (!metrics[i]->Test(vStdout, vStderr))\n            {\n                status = 1;\n            }\n        }\n\n        \/\/ Change back to the original path and delete temporary directory\n        fs::current_path(startDir);\n        fs::remove_all(tmpDir);\n        \n        \/\/ Save any changes.\n        if (vm.count(\"generate-metric\")      > 0 || \n            vm.count(\"generate-all-metrics\") > 0)\n        {\n            file.SaveFile();\n        }\n        \n        \/\/ Return status of test. 0 = PASS, 1 = FAIL\n        return status;\n    }\n    catch (const fs::filesystem_error& e)\n    {\n        cerr << \"Filesystem operation error occurred:\" << endl;\n        cerr << \"  \" << e.what() << endl;\n        cerr << \"  Files left in \" << tmpDir.string() << endl;\n    }\n    catch (...)\n    {\n        cerr << \"  Files left in \" << tmpDir.string() << endl;\n    }\n\n    \/\/ If a system error, return 2\n    return 2;\n}\n<|endoftext|>"}
{"text":"#include \n#include \n\n#include \n\n#include \"mocks\/logger.hpp\"\n\n#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)\n\n#if GCC_VERSION < 40900\n\nnamespace std {\n\ntemplate\nauto operator==(const std::reference_wrapper& lhs, const std::reference_wrapper& rhs) -> bool {\n    return lhs.get() == rhs.get();\n}\n\n}  \/\/ namespace std\n\n#endif\n\nnamespace blackhole {\nnamespace testing {\n\nusing ::testing::ByRef;\nusing ::testing::InvokeArgument;\nusing ::testing::_;\n\ntypedef mock::logger_t logger_type;\n\nTEST(Facade, PrimitiveLog) {\n    const logger_type inner{};\n    const logger_facade logger(inner);\n\n    EXPECT_CALL(inner, log(0, string_view(\"GET \/porn.png HTTP\/1.0\")))\n        .Times(1);\n\n    logger.log(0, \"GET \/porn.png HTTP\/1.0\");\n}\n\nTEST(Facade, AttributeLog) {\n    const logger_type inner{};\n    const logger_facade logger(inner);\n\n    const attribute_list attributes{{\"key#1\", {42}}};\n    attribute_pack expected{attributes};\n\n    EXPECT_CALL(inner, log(0, string_view(\"GET \/porn.png HTTP\/1.0\"), expected))\n        .Times(1);\n\n    logger.log(0, \"GET \/porn.png HTTP\/1.0\", attribute_list{\n        {\"key#1\", {42}}\n    });\n}\n\nTEST(Facade, FormattedLog) {\n    const logger_type inner{};\n    const logger_facade logger(inner);\n\n    attribute_pack expected;\n    writer_t writer;\n\n    EXPECT_CALL(inner, log(0, string_view(\"GET \/porn.png HTTP\/1.0 - {}\"), expected, _))\n        .Times(1)\n        .WillOnce(InvokeArgument<3>(ByRef(writer)));\n\n    logger.log(0, \"GET \/porn.png HTTP\/1.0 - {}\", 42);\n\n    EXPECT_EQ(\"GET \/porn.png HTTP\/1.0 - 42\", writer.inner.str());\n}\n\nTEST(Facade, FormattedAttributeLog) {\n    const logger_type inner{};\n    const logger_facade logger(inner);\n\n    const attribute_list attributes{{\"key#1\", {42}}};\n    attribute_pack expected{attributes};\n    writer_t writer;\n\n    EXPECT_CALL(inner, log(0, string_view(\"GET \/porn.png HTTP\/1.0 - {}\"), expected, _))\n        .Times(1)\n        .WillOnce(InvokeArgument<3>(ByRef(writer)));\n\n    logger.log(0, \"GET \/porn.png HTTP\/1.0 - {}\", 2345, attribute_list{\n        {\"key#1\", {42}}\n    });\n\n    EXPECT_EQ(\"GET \/porn.png HTTP\/1.0 - 2345\", writer.inner.str());\n}\n\n}  \/\/ namespace testing\n}  \/\/ namespace blackhole\nfix(gcc): fix reference wrapper compare on 4.9#include \n#include \n\n#include \n\n#include \"mocks\/logger.hpp\"\n\n#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)\n\n#if GCC_VERSION < 50000\n\nnamespace std {\n\ntemplate\nauto operator==(const std::reference_wrapper& lhs, const std::reference_wrapper& rhs) -> bool {\n    return lhs.get() == rhs.get();\n}\n\n}  \/\/ namespace std\n\n#endif\n\nnamespace blackhole {\nnamespace testing {\n\nusing ::testing::ByRef;\nusing ::testing::InvokeArgument;\nusing ::testing::_;\n\ntypedef mock::logger_t logger_type;\n\nTEST(Facade, PrimitiveLog) {\n    const logger_type inner{};\n    const logger_facade logger(inner);\n\n    EXPECT_CALL(inner, log(0, string_view(\"GET \/porn.png HTTP\/1.0\")))\n        .Times(1);\n\n    logger.log(0, \"GET \/porn.png HTTP\/1.0\");\n}\n\nTEST(Facade, AttributeLog) {\n    const logger_type inner{};\n    const logger_facade logger(inner);\n\n    const attribute_list attributes{{\"key#1\", {42}}};\n    attribute_pack expected{attributes};\n\n    EXPECT_CALL(inner, log(0, string_view(\"GET \/porn.png HTTP\/1.0\"), expected))\n        .Times(1);\n\n    logger.log(0, \"GET \/porn.png HTTP\/1.0\", attribute_list{\n        {\"key#1\", {42}}\n    });\n}\n\nTEST(Facade, FormattedLog) {\n    const logger_type inner{};\n    const logger_facade logger(inner);\n\n    attribute_pack expected;\n    writer_t writer;\n\n    EXPECT_CALL(inner, log(0, string_view(\"GET \/porn.png HTTP\/1.0 - {}\"), expected, _))\n        .Times(1)\n        .WillOnce(InvokeArgument<3>(ByRef(writer)));\n\n    logger.log(0, \"GET \/porn.png HTTP\/1.0 - {}\", 42);\n\n    EXPECT_EQ(\"GET \/porn.png HTTP\/1.0 - 42\", writer.inner.str());\n}\n\nTEST(Facade, FormattedAttributeLog) {\n    const logger_type inner{};\n    const logger_facade logger(inner);\n\n    const attribute_list attributes{{\"key#1\", {42}}};\n    attribute_pack expected{attributes};\n    writer_t writer;\n\n    EXPECT_CALL(inner, log(0, string_view(\"GET \/porn.png HTTP\/1.0 - {}\"), expected, _))\n        .Times(1)\n        .WillOnce(InvokeArgument<3>(ByRef(writer)));\n\n    logger.log(0, \"GET \/porn.png HTTP\/1.0 - {}\", 2345, attribute_list{\n        {\"key#1\", {42}}\n    });\n\n    EXPECT_EQ(\"GET \/porn.png HTTP\/1.0 - 2345\", writer.inner.str());\n}\n\n}  \/\/ namespace testing\n}  \/\/ namespace blackhole\n<|endoftext|>"}
{"text":"\/\/----------------------------  rt_7.cc  ---------------------------\n\/\/    rt_7.cc,v 1.3 2003\/06\/09 16:00:38 wolf Exp\n\/\/    Version: \n\/\/\n\/\/    Copyright (C) 2003, 2005 by the deal.II authors\n\/\/\n\/\/    This file is subject to QPL and may not be  distributed\n\/\/    without copyright and license information. Please refer\n\/\/    to the file deal.II\/doc\/license.html for the  text  and\n\/\/    further information on this license.\n\/\/\n\/\/----------------------------  rt_7.cc  ---------------------------\n\n\/\/ RT(2) had some problems with shape functions...\n\n#include \"..\/tests.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#define PRECISION 2\n\n\n\ntemplate\nvoid\nplot_shape_functions(const unsigned int degree)\n{\n  FE_RaviartThomasNodal fe_rt(degree);\n  Triangulation tr;\n  GridGenerator::hyper_cube(tr, 0., 1.);\n\n  DoFHandler dof(tr);\n  typename DoFHandler::cell_iterator c = dof.begin();\n  dof.distribute_dofs(fe_rt);\n      \n  QTrapez<1> q_trapez;\n  const unsigned int div=10;\n  QIterated q(q_trapez, div);\n  FEValues fe(fe_rt, q, update_values|update_gradients|update_q_points);\n  fe.reinit(c);\n\n  Assert (fe.get_fe().n_components() == dim, ExcInternalError());\n  \n  for (unsigned int q_point=0; q_point(q_trapez,div).n_quadrature_points == 0)\n        deallog << std::endl;\n      \n      deallog << fe.quadrature_point(q_point) << \" \";\n\t      \n      for (unsigned int i=0;i(2);\n  \n  return 0;\n}\n\n\n\nThe element should have been simply RT, not RTNodal.\/\/----------------------------  rt_7.cc  ---------------------------\n\/\/    rt_7.cc,v 1.3 2003\/06\/09 16:00:38 wolf Exp\n\/\/    Version: \n\/\/\n\/\/    Copyright (C) 2003, 2005 by the deal.II authors\n\/\/\n\/\/    This file is subject to QPL and may not be  distributed\n\/\/    without copyright and license information. Please refer\n\/\/    to the file deal.II\/doc\/license.html for the  text  and\n\/\/    further information on this license.\n\/\/\n\/\/----------------------------  rt_7.cc  ---------------------------\n\n\/\/ RT(2) had some problems with shape functions...\n\n#include \"..\/tests.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#define PRECISION 2\n\n\n\ntemplate\nvoid\nplot_shape_functions(const unsigned int degree)\n{\n  FE_RaviartThomas fe_rt(degree);\n  Triangulation tr;\n  GridGenerator::hyper_cube(tr, 0., 1.);\n\n  DoFHandler dof(tr);\n  typename DoFHandler::cell_iterator c = dof.begin();\n  dof.distribute_dofs(fe_rt);\n      \n  QTrapez<1> q_trapez;\n  const unsigned int div=10;\n  QIterated q(q_trapez, div);\n  FEValues fe(fe_rt, q, update_values|update_gradients|update_q_points);\n  fe.reinit(c);\n\n  Assert (fe.get_fe().n_components() == dim, ExcInternalError());\n  \n  for (unsigned int q_point=0; q_point(q_trapez,div).n_quadrature_points == 0)\n        deallog << std::endl;\n      \n      deallog << fe.quadrature_point(q_point) << \" \";\n\t      \n      for (unsigned int i=0;i(2);\n  \n  return 0;\n}\n\n\n\n<|endoftext|>"}
{"text":"#include \n\n#include \n\nnamespace blackhole {\nnamespace testing {\n\nTEST(Record, Severity) {\n    const view_of::type attributes{{\"key#1\", {42}}};\n    attribute_pack pack{};\n\n    record_t record(42, \"GET \/porn.png HTTP\/1.1\", pack);\n\n    EXPECT_EQ(42, record.severity());\n}\n\nTEST(Record, Message) {\n    const view_of::type attributes{{\"key#1\", {42}}};\n    attribute_pack pack{};\n\n    record_t record(42, \"GET \/porn.png HTTP\/1.1\", pack);\n\n    EXPECT_EQ(\"GET \/porn.png HTTP\/1.1\", record.message().to_string());\n}\n\n}  \/\/ namespace testing\n}  \/\/ namespace blackhole\nchore(tests): eliminate unused code#include \n\n#include \n\nnamespace blackhole {\nnamespace testing {\n\nTEST(Record, Severity) {\n    attribute_pack pack{};\n\n    record_t record(42, \"GET \/porn.png HTTP\/1.1\", pack);\n\n    EXPECT_EQ(42, record.severity());\n}\n\nTEST(Record, Message) {\n    attribute_pack pack{};\n\n    record_t record(42, \"GET \/porn.png HTTP\/1.1\", pack);\n\n    EXPECT_EQ(\"GET \/porn.png HTTP\/1.1\", record.message().to_string());\n}\n\n}  \/\/ namespace testing\n}  \/\/ namespace blackhole\n<|endoftext|>"}
{"text":"\/\/===-- R600KernelParameters.cpp - Lower kernel function arguments --------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass lowers kernel function arguments to loads from the vertex buffer.\n\/\/\n\/\/ Kernel arguemnts are stored in the vertex buffer at an offset of 9 dwords,\n\/\/ so arg0 needs to be loaded from VTX_BUFFER[9] and arg1 is loaded from\n\/\/ VTX_BUFFER[10], etc.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AMDGPU.h\"\n#include \"AMDIL.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Intrinsics.h\"\n#include \"llvm\/IRBuilder.h\"\n#include \"llvm\/Metadata.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/TypeBuilder.h\"\n#include \"llvm\/Target\/TargetData.h\"\n\n#include \n#include \n\nusing namespace llvm;\n\nnamespace {\n\n#define CONSTANT_CACHE_SIZE_DW 127\n\nclass R600KernelParameters : public FunctionPass {\n  const TargetData *TD;\n  LLVMContext* Context;\n  Module *Mod;\n\n  struct Param {\n    Param() : Val(NULL), PtrVal(NULL), OffsetInDW(0), SizeInDW(0),\n              IsIndirect(true), SpecialID(0) {}\n\n    Value* Val;\n    Value* PtrVal;\n    int OffsetInDW;\n    int SizeInDW;\n\n    bool IsIndirect;\n\n    std::string SpecialType;\n    int SpecialID;\n\n    int End() { return OffsetInDW + SizeInDW; }\n    \/\/ The first 9 dwords are reserved for the grid sizes.\n    int getRatOffset() { return 9 + OffsetInDW; }\n  };\n\n  std::vector Params;\n\n  bool IsOpenCLKernel(const Function *Fun);\n  int getLastSpecialID(const std::string& TypeName);\n\n  int getListSize();\n  void AddParam(Argument *Arg);\n  int CalculateArgumentSize(Argument *Arg);\n  void RunAna(Function *Fun);\n  void Replace(Function *Fun);\n  bool IsIndirect(Value *Val, std::set &Visited);\n  void Propagate(Function* Fun);\n  void Propagate(Value *V, const Twine &Name, bool IsIndirect = true);\n  Value* ConstantRead(Function *Fun, Param &P);\n  Value* handleSpecial(Function *Fun, Param &P);\n  bool IsSpecialType(Type *T);\n  std::string getSpecialTypeName(Type *T);\npublic:\n  static char ID;\n  R600KernelParameters() : FunctionPass(ID) {}\n  R600KernelParameters(const TargetData* TD) : FunctionPass(ID), TD(TD) {}\n  bool runOnFunction (Function &F);\n  void getAnalysisUsage(AnalysisUsage &AU) const;\n  const char *getPassName() const;\n  bool doInitialization(Module &M);\n  bool doFinalization(Module &M);\n};\n\nchar R600KernelParameters::ID = 0;\n\nstatic RegisterPass X(\"kerparam\",\n                            \"OpenCL Kernel Parameter conversion\", false, false);\n\nbool R600KernelParameters::IsOpenCLKernel(const Function* Fun) {\n  Module *Mod = const_cast(Fun)->getParent();\n  NamedMDNode * MD = Mod->getOrInsertNamedMetadata(\"opencl.kernels\");\n\n  if (!MD or !MD->getNumOperands()) {\n    return false;\n  }\n\n  for (int i = 0; i < int(MD->getNumOperands()); i++) {\n    if (!MD->getOperand(i) or !MD->getOperand(i)->getOperand(0)) {\n      continue;\n    }\n\n    assert(MD->getOperand(i)->getNumOperands() == 1);\n\n    if (MD->getOperand(i)->getOperand(0)->getName() == Fun->getName()) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nint R600KernelParameters::getLastSpecialID(const std::string &TypeName) {\n  int LastID = -1;\n\n  for (std::vector::iterator i = Params.begin(); i != Params.end(); i++) {\n    if (i->SpecialType == TypeName) {\n      LastID = i->SpecialID;\n    }\n  }\n\n  return LastID;\n}\n\nint R600KernelParameters::getListSize() {\n  if (Params.size() == 0) {\n    return 0;\n  }\n\n  return Params.back().End();\n}\n\nbool R600KernelParameters::IsIndirect(Value *Val, std::set &Visited) {\n  \/\/XXX Direct parameters are not supported yet, so return true here.\n  return true;\n#if 0\n  if (isa(Val)) {\n    return false;\n  }\n\n  if (isa(Val->getType())) {\n    assert(0 and \"Internal error\");\n    return false;\n  }\n\n  if (Visited.count(Val)) {\n    return false;\n  }\n\n  Visited.insert(Val);\n\n  if (isa(Val)) {\n    getElementPtrInst* GEP = dyn_cast(Val);\n    getElementPtrInst::op_iterator I = GEP->op_begin();\n\n    for (++I; I != GEP->op_end(); ++I) {\n      if (!isa(*I)) {\n        return true;\n      }\n    }\n  }\n\n  for (Value::use_iterator I = Val->use_begin(); i != Val->use_end(); ++I) {\n    Value* V2 = dyn_cast(*I);\n\n    if (V2) {\n      if (IsIndirect(V2, Visited)) {\n        return true;\n      }\n    }\n  }\n\n  return false;\n#endif\n}\n\nvoid R600KernelParameters::AddParam(Argument *Arg) {\n  Param P;\n\n  P.Val = dyn_cast(Arg);\n  P.OffsetInDW = getListSize();\n  P.SizeInDW = CalculateArgumentSize(Arg);\n\n  if (isa(Arg->getType()) and Arg->hasByValAttr()) {\n    std::set Visited;\n    P.IsIndirect = IsIndirect(P.Val, Visited);\n  }\n\n  Params.push_back(P);\n}\n\nint R600KernelParameters::CalculateArgumentSize(Argument *Arg) {\n  Type* T = Arg->getType();\n\n  if (Arg->hasByValAttr() and dyn_cast(T)) {\n    T = dyn_cast(T)->getElementType();\n  }\n\n  int StoreSizeInDW = (TD->getTypeStoreSize(T) + 3)\/4;\n\n  assert(StoreSizeInDW);\n\n  return StoreSizeInDW;\n}\n\n\nvoid R600KernelParameters::RunAna(Function* Fun) {\n  assert(IsOpenCLKernel(Fun));\n\n  for (Function::arg_iterator I = Fun->arg_begin(); I != Fun->arg_end(); ++I) {\n    AddParam(I);\n  }\n\n}\n\nvoid R600KernelParameters::Replace(Function* Fun) {\n  for (std::vector::iterator I = Params.begin(); I != Params.end(); ++I) {\n    Value *NewVal;\n\n    if (IsSpecialType(I->Val->getType())) {\n      NewVal = handleSpecial(Fun, *I);\n    } else {\n      NewVal = ConstantRead(Fun, *I);\n    }\n    if (NewVal) {\n      I->Val->replaceAllUsesWith(NewVal);\n    }\n  }\n}\n\nvoid R600KernelParameters::Propagate(Function* Fun) {\n  for (std::vector::iterator I = Params.begin(); I != Params.end(); ++I) {\n    if (I->PtrVal) {\n      Propagate(I->PtrVal, I->Val->getName(), I->IsIndirect);\n    }\n  }\n}\n\nvoid R600KernelParameters::Propagate(Value* V, const Twine& Name, bool IsIndirect) {\n  LoadInst* Load = dyn_cast(V);\n  GetElementPtrInst *GEP = dyn_cast(V);\n\n  unsigned Addrspace;\n\n  if (IsIndirect) {\n    Addrspace = AMDILAS::PARAM_I_ADDRESS;\n  }  else {\n    Addrspace = AMDILAS::PARAM_D_ADDRESS;\n  }\n\n  if (GEP and GEP->getType()->getAddressSpace() != Addrspace) {\n    Value *Op = GEP->getPointerOperand();\n\n    if (dyn_cast(Op->getType())->getAddressSpace() != Addrspace) {\n      Op = new BitCastInst(Op, PointerType::get(dyn_cast(\n                           Op->getType())->getElementType(), Addrspace),\n                           Name, dyn_cast(V));\n    }\n\n    std::vector Params(GEP->idx_begin(), GEP->idx_end());\n\n    GetElementPtrInst* GEP2 = GetElementPtrInst::Create(Op, Params, Name,\n                                                      dyn_cast(V));\n    GEP2->setIsInBounds(GEP->isInBounds());\n    V = dyn_cast(GEP2);\n    GEP->replaceAllUsesWith(GEP2);\n    GEP->eraseFromParent();\n    Load = NULL;\n  }\n\n  if (Load) {\n    \/\/\/normally at this point we have the right address space\n    if (Load->getPointerAddressSpace() != Addrspace) {\n      Value *OrigPtr = Load->getPointerOperand();\n      PointerType *OrigPtrType = dyn_cast(OrigPtr->getType());\n\n      Type* NewPtrType = PointerType::get(OrigPtrType->getElementType(),\n                                            Addrspace);\n\n      Value* NewPtr = OrigPtr;\n\n      if (OrigPtr->getType() != NewPtrType) {\n        NewPtr = new BitCastInst(OrigPtr, NewPtrType, \"prop_cast\", Load);\n      }\n\n      Value* new_Load = new LoadInst(NewPtr, Name, Load);\n      Load->replaceAllUsesWith(new_Load);\n      Load->eraseFromParent();\n    }\n\n    return;\n  }\n\n  std::vector Users(V->use_begin(), V->use_end());\n\n  for (int i = 0; i < int(Users.size()); i++) {\n    Value* V2 = dyn_cast(Users[i]);\n\n    if (V2) {\n      Propagate(V2, Name, IsIndirect);\n    }\n  }\n}\n\nValue* R600KernelParameters::ConstantRead(Function *Fun, Param &P) {\n  assert(Fun->front().begin() != Fun->front().end());\n\n  Instruction *FirstInst = Fun->front().begin();\n  IRBuilder <> Builder (FirstInst);\n\/* First 3 dwords are reserved for the dimmension info *\/\n\n  if (!P.Val->hasNUsesOrMore(1)) {\n    return NULL;\n  }\n  unsigned Addrspace;\n\n  if (P.IsIndirect) {\n    Addrspace = AMDILAS::PARAM_I_ADDRESS;\n  } else {\n    Addrspace = AMDILAS::PARAM_D_ADDRESS;\n  }\n\n  Argument *Arg = dyn_cast(P.Val);\n  Type * ArgType = P.Val->getType();\n  PointerType * ArgPtrType = dyn_cast(P.Val->getType());\n\n  if (ArgPtrType and Arg->hasByValAttr()) {\n    Value* ParamAddrSpacePtr = ConstantPointerNull::get(\n                                    PointerType::get(Type::getInt32Ty(*Context),\n                                    Addrspace));\n    Value* ParamPtr = GetElementPtrInst::Create(ParamAddrSpacePtr,\n                                    ConstantInt::get(Type::getInt32Ty(*Context),\n                                    P.getRatOffset()), Arg->getName(),\n                                    FirstInst);\n    ParamPtr = new BitCastInst(ParamPtr,\n                                PointerType::get(ArgPtrType->getElementType(),\n                                                 Addrspace),\n                                Arg->getName(), FirstInst);\n    P.PtrVal = ParamPtr;\n    return ParamPtr;\n  } else {\n    Value *ParamAddrSpacePtr = ConstantPointerNull::get(PointerType::get(\n                                                        ArgType, Addrspace));\n\n    Value *ParamPtr = Builder.CreateGEP(ParamAddrSpacePtr,\n             ConstantInt::get(Type::getInt32Ty(*Context), P.getRatOffset()),\n                              Arg->getName());\n\n    Value *Param_Value = Builder.CreateLoad(ParamPtr, Arg->getName());\n\n    return Param_Value;\n  }\n}\n\nValue* R600KernelParameters::handleSpecial(Function* Fun, Param& P) {\n  std::string Name = getSpecialTypeName(P.Val->getType());\n  int ID;\n\n  assert(!Name.empty());\n\n  if (Name == \"image2d_t\" or Name == \"image3d_t\") {\n    int LastID = std::max(getLastSpecialID(\"image2d_t\"),\n                     getLastSpecialID(\"image3d_t\"));\n\n    if (LastID == -1) {\n      ID = 2; \/\/\/ID0 and ID1 are used internally by the driver\n    } else {\n      ID = LastID + 1;\n    }\n  } else if (Name == \"sampler_t\") {\n    int LastID = getLastSpecialID(\"sampler_t\");\n\n    if (LastID == -1) {\n      ID = 0;\n    } else {\n      ID = LastID + 1;\n    }\n  } else {\n    \/\/\/TODO: give some error message\n    return NULL;\n  }\n\n  P.SpecialType = Name;\n  P.SpecialID = ID;\n\n  Instruction *FirstInst = Fun->front().begin();\n\n  return new IntToPtrInst(ConstantInt::get(Type::getInt32Ty(*Context),\n                                           P.SpecialID), P.Val->getType(),\n                                           \"resourceID\", FirstInst);\n}\n\n\nbool R600KernelParameters::IsSpecialType(Type* T) {\n  return !getSpecialTypeName(T).empty();\n}\n\nstd::string R600KernelParameters::getSpecialTypeName(Type* T) {\n  PointerType *PT = dyn_cast(T);\n  StructType *ST = NULL;\n\n  if (PT) {\n    ST = dyn_cast(PT->getElementType());\n  }\n\n  if (ST) {\n    std::string Prefix = \"struct.opencl_builtin_type_\";\n\n    std::string Name = ST->getName().str();\n\n    if (Name.substr(0, Prefix.length()) == Prefix) {\n      return Name.substr(Prefix.length(), Name.length());\n    }\n  }\n\n  return \"\";\n}\n\n\nbool R600KernelParameters::runOnFunction (Function &F) {\n  if (!IsOpenCLKernel(&F)) {\n    return false;\n  }\n\n  RunAna(&F);\n  Replace(&F);\n  Propagate(&F);\n\n  return false;\n}\n\nvoid R600KernelParameters::getAnalysisUsage(AnalysisUsage &AU) const {\n  FunctionPass::getAnalysisUsage(AU);\n  AU.setPreservesAll();\n}\n\nconst char *R600KernelParameters::getPassName() const {\n  return \"OpenCL Kernel parameter conversion to memory\";\n}\n\nbool R600KernelParameters::doInitialization(Module &M) {\n  Context = &M.getContext();\n  Mod = &M;\n\n  return false;\n}\n\nbool R600KernelParameters::doFinalization(Module &M) {\n  return false;\n}\n\n} \/\/ End anonymous namespace\n\nFunctionPass* llvm::createR600KernelParametersPass(const TargetData* TD) {\n  return new R600KernelParameters(TD);\n}\nRevert \"Target\/AMDGPU\/R600KernelParameters.cpp: Fix two includes,  and \"\/\/===-- R600KernelParameters.cpp - Lower kernel function arguments --------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass lowers kernel function arguments to loads from the vertex buffer.\n\/\/\n\/\/ Kernel arguemnts are stored in the vertex buffer at an offset of 9 dwords,\n\/\/ so arg0 needs to be loaded from VTX_BUFFER[9] and arg1 is loaded from\n\/\/ VTX_BUFFER[10], etc.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AMDGPU.h\"\n#include \"AMDIL.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Intrinsics.h\"\n#include \"llvm\/Metadata.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Support\/IRBuilder.h\"\n#include \"llvm\/Support\/TypeBuilder.h\"\n\n#include \n#include \n\nusing namespace llvm;\n\nnamespace {\n\n#define CONSTANT_CACHE_SIZE_DW 127\n\nclass R600KernelParameters : public FunctionPass {\n  const TargetData *TD;\n  LLVMContext* Context;\n  Module *Mod;\n\n  struct Param {\n    Param() : Val(NULL), PtrVal(NULL), OffsetInDW(0), SizeInDW(0),\n              IsIndirect(true), SpecialID(0) {}\n\n    Value* Val;\n    Value* PtrVal;\n    int OffsetInDW;\n    int SizeInDW;\n\n    bool IsIndirect;\n\n    std::string SpecialType;\n    int SpecialID;\n\n    int End() { return OffsetInDW + SizeInDW; }\n    \/\/ The first 9 dwords are reserved for the grid sizes.\n    int getRatOffset() { return 9 + OffsetInDW; }\n  };\n\n  std::vector Params;\n\n  bool IsOpenCLKernel(const Function *Fun);\n  int getLastSpecialID(const std::string& TypeName);\n\n  int getListSize();\n  void AddParam(Argument *Arg);\n  int CalculateArgumentSize(Argument *Arg);\n  void RunAna(Function *Fun);\n  void Replace(Function *Fun);\n  bool IsIndirect(Value *Val, std::set &Visited);\n  void Propagate(Function* Fun);\n  void Propagate(Value *V, const Twine &Name, bool IsIndirect = true);\n  Value* ConstantRead(Function *Fun, Param &P);\n  Value* handleSpecial(Function *Fun, Param &P);\n  bool IsSpecialType(Type *T);\n  std::string getSpecialTypeName(Type *T);\npublic:\n  static char ID;\n  R600KernelParameters() : FunctionPass(ID) {}\n  R600KernelParameters(const TargetData* TD) : FunctionPass(ID), TD(TD) {}\n  bool runOnFunction (Function &F);\n  void getAnalysisUsage(AnalysisUsage &AU) const;\n  const char *getPassName() const;\n  bool doInitialization(Module &M);\n  bool doFinalization(Module &M);\n};\n\nchar R600KernelParameters::ID = 0;\n\nstatic RegisterPass X(\"kerparam\",\n                            \"OpenCL Kernel Parameter conversion\", false, false);\n\nbool R600KernelParameters::IsOpenCLKernel(const Function* Fun) {\n  Module *Mod = const_cast(Fun)->getParent();\n  NamedMDNode * MD = Mod->getOrInsertNamedMetadata(\"opencl.kernels\");\n\n  if (!MD or !MD->getNumOperands()) {\n    return false;\n  }\n\n  for (int i = 0; i < int(MD->getNumOperands()); i++) {\n    if (!MD->getOperand(i) or !MD->getOperand(i)->getOperand(0)) {\n      continue;\n    }\n\n    assert(MD->getOperand(i)->getNumOperands() == 1);\n\n    if (MD->getOperand(i)->getOperand(0)->getName() == Fun->getName()) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nint R600KernelParameters::getLastSpecialID(const std::string &TypeName) {\n  int LastID = -1;\n\n  for (std::vector::iterator i = Params.begin(); i != Params.end(); i++) {\n    if (i->SpecialType == TypeName) {\n      LastID = i->SpecialID;\n    }\n  }\n\n  return LastID;\n}\n\nint R600KernelParameters::getListSize() {\n  if (Params.size() == 0) {\n    return 0;\n  }\n\n  return Params.back().End();\n}\n\nbool R600KernelParameters::IsIndirect(Value *Val, std::set &Visited) {\n  \/\/XXX Direct parameters are not supported yet, so return true here.\n  return true;\n#if 0\n  if (isa(Val)) {\n    return false;\n  }\n\n  if (isa(Val->getType())) {\n    assert(0 and \"Internal error\");\n    return false;\n  }\n\n  if (Visited.count(Val)) {\n    return false;\n  }\n\n  Visited.insert(Val);\n\n  if (isa(Val)) {\n    getElementPtrInst* GEP = dyn_cast(Val);\n    getElementPtrInst::op_iterator I = GEP->op_begin();\n\n    for (++I; I != GEP->op_end(); ++I) {\n      if (!isa(*I)) {\n        return true;\n      }\n    }\n  }\n\n  for (Value::use_iterator I = Val->use_begin(); i != Val->use_end(); ++I) {\n    Value* V2 = dyn_cast(*I);\n\n    if (V2) {\n      if (IsIndirect(V2, Visited)) {\n        return true;\n      }\n    }\n  }\n\n  return false;\n#endif\n}\n\nvoid R600KernelParameters::AddParam(Argument *Arg) {\n  Param P;\n\n  P.Val = dyn_cast(Arg);\n  P.OffsetInDW = getListSize();\n  P.SizeInDW = CalculateArgumentSize(Arg);\n\n  if (isa(Arg->getType()) and Arg->hasByValAttr()) {\n    std::set Visited;\n    P.IsIndirect = IsIndirect(P.Val, Visited);\n  }\n\n  Params.push_back(P);\n}\n\nint R600KernelParameters::CalculateArgumentSize(Argument *Arg) {\n  Type* T = Arg->getType();\n\n  if (Arg->hasByValAttr() and dyn_cast(T)) {\n    T = dyn_cast(T)->getElementType();\n  }\n\n  int StoreSizeInDW = (TD->getTypeStoreSize(T) + 3)\/4;\n\n  assert(StoreSizeInDW);\n\n  return StoreSizeInDW;\n}\n\n\nvoid R600KernelParameters::RunAna(Function* Fun) {\n  assert(IsOpenCLKernel(Fun));\n\n  for (Function::arg_iterator I = Fun->arg_begin(); I != Fun->arg_end(); ++I) {\n    AddParam(I);\n  }\n\n}\n\nvoid R600KernelParameters::Replace(Function* Fun) {\n  for (std::vector::iterator I = Params.begin(); I != Params.end(); ++I) {\n    Value *NewVal;\n\n    if (IsSpecialType(I->Val->getType())) {\n      NewVal = handleSpecial(Fun, *I);\n    } else {\n      NewVal = ConstantRead(Fun, *I);\n    }\n    if (NewVal) {\n      I->Val->replaceAllUsesWith(NewVal);\n    }\n  }\n}\n\nvoid R600KernelParameters::Propagate(Function* Fun) {\n  for (std::vector::iterator I = Params.begin(); I != Params.end(); ++I) {\n    if (I->PtrVal) {\n      Propagate(I->PtrVal, I->Val->getName(), I->IsIndirect);\n    }\n  }\n}\n\nvoid R600KernelParameters::Propagate(Value* V, const Twine& Name, bool IsIndirect) {\n  LoadInst* Load = dyn_cast(V);\n  GetElementPtrInst *GEP = dyn_cast(V);\n\n  unsigned Addrspace;\n\n  if (IsIndirect) {\n    Addrspace = AMDILAS::PARAM_I_ADDRESS;\n  }  else {\n    Addrspace = AMDILAS::PARAM_D_ADDRESS;\n  }\n\n  if (GEP and GEP->getType()->getAddressSpace() != Addrspace) {\n    Value *Op = GEP->getPointerOperand();\n\n    if (dyn_cast(Op->getType())->getAddressSpace() != Addrspace) {\n      Op = new BitCastInst(Op, PointerType::get(dyn_cast(\n                           Op->getType())->getElementType(), Addrspace),\n                           Name, dyn_cast(V));\n    }\n\n    std::vector Params(GEP->idx_begin(), GEP->idx_end());\n\n    GetElementPtrInst* GEP2 = GetElementPtrInst::Create(Op, Params, Name,\n                                                      dyn_cast(V));\n    GEP2->setIsInBounds(GEP->isInBounds());\n    V = dyn_cast(GEP2);\n    GEP->replaceAllUsesWith(GEP2);\n    GEP->eraseFromParent();\n    Load = NULL;\n  }\n\n  if (Load) {\n    \/\/\/normally at this point we have the right address space\n    if (Load->getPointerAddressSpace() != Addrspace) {\n      Value *OrigPtr = Load->getPointerOperand();\n      PointerType *OrigPtrType = dyn_cast(OrigPtr->getType());\n\n      Type* NewPtrType = PointerType::get(OrigPtrType->getElementType(),\n                                            Addrspace);\n\n      Value* NewPtr = OrigPtr;\n\n      if (OrigPtr->getType() != NewPtrType) {\n        NewPtr = new BitCastInst(OrigPtr, NewPtrType, \"prop_cast\", Load);\n      }\n\n      Value* new_Load = new LoadInst(NewPtr, Name, Load);\n      Load->replaceAllUsesWith(new_Load);\n      Load->eraseFromParent();\n    }\n\n    return;\n  }\n\n  std::vector Users(V->use_begin(), V->use_end());\n\n  for (int i = 0; i < int(Users.size()); i++) {\n    Value* V2 = dyn_cast(Users[i]);\n\n    if (V2) {\n      Propagate(V2, Name, IsIndirect);\n    }\n  }\n}\n\nValue* R600KernelParameters::ConstantRead(Function *Fun, Param &P) {\n  assert(Fun->front().begin() != Fun->front().end());\n\n  Instruction *FirstInst = Fun->front().begin();\n  IRBuilder <> Builder (FirstInst);\n\/* First 3 dwords are reserved for the dimmension info *\/\n\n  if (!P.Val->hasNUsesOrMore(1)) {\n    return NULL;\n  }\n  unsigned Addrspace;\n\n  if (P.IsIndirect) {\n    Addrspace = AMDILAS::PARAM_I_ADDRESS;\n  } else {\n    Addrspace = AMDILAS::PARAM_D_ADDRESS;\n  }\n\n  Argument *Arg = dyn_cast(P.Val);\n  Type * ArgType = P.Val->getType();\n  PointerType * ArgPtrType = dyn_cast(P.Val->getType());\n\n  if (ArgPtrType and Arg->hasByValAttr()) {\n    Value* ParamAddrSpacePtr = ConstantPointerNull::get(\n                                    PointerType::get(Type::getInt32Ty(*Context),\n                                    Addrspace));\n    Value* ParamPtr = GetElementPtrInst::Create(ParamAddrSpacePtr,\n                                    ConstantInt::get(Type::getInt32Ty(*Context),\n                                    P.getRatOffset()), Arg->getName(),\n                                    FirstInst);\n    ParamPtr = new BitCastInst(ParamPtr,\n                                PointerType::get(ArgPtrType->getElementType(),\n                                                 Addrspace),\n                                Arg->getName(), FirstInst);\n    P.PtrVal = ParamPtr;\n    return ParamPtr;\n  } else {\n    Value *ParamAddrSpacePtr = ConstantPointerNull::get(PointerType::get(\n                                                        ArgType, Addrspace));\n\n    Value *ParamPtr = Builder.CreateGEP(ParamAddrSpacePtr,\n             ConstantInt::get(Type::getInt32Ty(*Context), P.getRatOffset()),\n                              Arg->getName());\n\n    Value *Param_Value = Builder.CreateLoad(ParamPtr, Arg->getName());\n\n    return Param_Value;\n  }\n}\n\nValue* R600KernelParameters::handleSpecial(Function* Fun, Param& P) {\n  std::string Name = getSpecialTypeName(P.Val->getType());\n  int ID;\n\n  assert(!Name.empty());\n\n  if (Name == \"image2d_t\" or Name == \"image3d_t\") {\n    int LastID = std::max(getLastSpecialID(\"image2d_t\"),\n                     getLastSpecialID(\"image3d_t\"));\n\n    if (LastID == -1) {\n      ID = 2; \/\/\/ID0 and ID1 are used internally by the driver\n    } else {\n      ID = LastID + 1;\n    }\n  } else if (Name == \"sampler_t\") {\n    int LastID = getLastSpecialID(\"sampler_t\");\n\n    if (LastID == -1) {\n      ID = 0;\n    } else {\n      ID = LastID + 1;\n    }\n  } else {\n    \/\/\/TODO: give some error message\n    return NULL;\n  }\n\n  P.SpecialType = Name;\n  P.SpecialID = ID;\n\n  Instruction *FirstInst = Fun->front().begin();\n\n  return new IntToPtrInst(ConstantInt::get(Type::getInt32Ty(*Context),\n                                           P.SpecialID), P.Val->getType(),\n                                           \"resourceID\", FirstInst);\n}\n\n\nbool R600KernelParameters::IsSpecialType(Type* T) {\n  return !getSpecialTypeName(T).empty();\n}\n\nstd::string R600KernelParameters::getSpecialTypeName(Type* T) {\n  PointerType *PT = dyn_cast(T);\n  StructType *ST = NULL;\n\n  if (PT) {\n    ST = dyn_cast(PT->getElementType());\n  }\n\n  if (ST) {\n    std::string Prefix = \"struct.opencl_builtin_type_\";\n\n    std::string Name = ST->getName().str();\n\n    if (Name.substr(0, Prefix.length()) == Prefix) {\n      return Name.substr(Prefix.length(), Name.length());\n    }\n  }\n\n  return \"\";\n}\n\n\nbool R600KernelParameters::runOnFunction (Function &F) {\n  if (!IsOpenCLKernel(&F)) {\n    return false;\n  }\n\n  RunAna(&F);\n  Replace(&F);\n  Propagate(&F);\n\n  return false;\n}\n\nvoid R600KernelParameters::getAnalysisUsage(AnalysisUsage &AU) const {\n  FunctionPass::getAnalysisUsage(AU);\n  AU.setPreservesAll();\n}\n\nconst char *R600KernelParameters::getPassName() const {\n  return \"OpenCL Kernel parameter conversion to memory\";\n}\n\nbool R600KernelParameters::doInitialization(Module &M) {\n  Context = &M.getContext();\n  Mod = &M;\n\n  return false;\n}\n\nbool R600KernelParameters::doFinalization(Module &M) {\n  return false;\n}\n\n} \/\/ End anonymous namespace\n\nFunctionPass* llvm::createR600KernelParametersPass(const TargetData* TD) {\n  return new R600KernelParameters(TD);\n}\n<|endoftext|>"}
{"text":"\/\/===- DeadTypeElimination.cpp - Eliminate unused types for symbol table --===\/\/\n\/\/ \n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass is used to cleanup the output of GCC.  It eliminate names for types\n\/\/ that are unused in the entire translation unit, using the FindUsedTypes pass.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Analysis\/FindUsedTypes.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"Support\/Statistic.h\"\n\nnamespace {\n  struct DTE : public Pass {\n    \/\/ doPassInitialization - For this pass, it removes global symbol table\n    \/\/ entries for primitive types.  These are never used for linking in GCC and\n    \/\/ they make the output uglier to look at, so we nuke them.\n    \/\/\n    \/\/ Also, initialize instance variables.\n    \/\/\n    bool run(Module &M);\n\n    \/\/ getAnalysisUsage - This function needs FindUsedTypes to do its job...\n    \/\/\n    virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n      AU.addRequired();\n    }\n  };\n  RegisterOpt X(\"deadtypeelim\", \"Dead Type Elimination\");\n  Statistic<>\n  NumKilled(\"deadtypeelim\", \"Number of unused typenames removed from symtab\");\n}\n\nPass *createDeadTypeEliminationPass() {\n  return new DTE();\n}\n\n\n\n\/\/ ShouldNukSymtabEntry - Return true if this module level symbol table entry\n\/\/ should be eliminated.\n\/\/\nstatic inline bool ShouldNukeSymtabEntry(const std::pair&E){\n  \/\/ Nuke all names for primitive types!\n  if (cast(E.second)->isPrimitiveType()) return true;\n\n  \/\/ Nuke all pointers to primitive types as well...\n  if (const PointerType *PT = dyn_cast(E.second))\n    if (PT->getElementType()->isPrimitiveType()) return true;\n\n  return false;\n}\n\n\/\/ run - For this pass, it removes global symbol table entries for primitive\n\/\/ types.  These are never used for linking in GCC and they make the output\n\/\/ uglier to look at, so we nuke them.  Also eliminate types that are never used\n\/\/ in the entire program as indicated by FindUsedTypes.\n\/\/\nbool DTE::run(Module &M) {\n  bool Changed = false;\n\n  SymbolTable &ST = M.getSymbolTable();\n  const std::set &UsedTypes =\n    getAnalysis().getTypes();\n\n  \/\/ Check the symbol table for superfluous type entries...\n  \/\/\n  \/\/ Grab the 'type' plane of the module symbol...\n  SymbolTable::iterator STI = ST.find(Type::TypeTy);\n  if (STI != ST.end()) {\n    \/\/ Loop over all entries in the type plane...\n    SymbolTable::VarMap &Plane = STI->second;\n    for (SymbolTable::VarMap::iterator PI = Plane.begin(); PI != Plane.end();)\n      \/\/ If this entry should be unconditionally removed, or if we detect that\n      \/\/ the type is not used, remove it.\n      if (ShouldNukeSymtabEntry(*PI) ||\n          !UsedTypes.count(cast(PI->second))) {\n        SymbolTable::VarMap::iterator PJ = PI++;\n        Plane.erase(PJ);\n        ++NumKilled;\n        Changed = true;\n      } else {\n        ++PI;\n      }\n  }\n\n  return Changed;\n}\nUntypo\/\/===- DeadTypeElimination.cpp - Eliminate unused types for symbol table --===\/\/\n\/\/ \n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass is used to cleanup the output of GCC.  It eliminate names for types\n\/\/ that are unused in the entire translation unit, using the FindUsedTypes pass.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Analysis\/FindUsedTypes.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"Support\/Statistic.h\"\n\nnamespace {\n  struct DTE : public Pass {\n    \/\/ doPassInitialization - For this pass, it removes global symbol table\n    \/\/ entries for primitive types.  These are never used for linking in GCC and\n    \/\/ they make the output uglier to look at, so we nuke them.\n    \/\/\n    \/\/ Also, initialize instance variables.\n    \/\/\n    bool run(Module &M);\n\n    \/\/ getAnalysisUsage - This function needs FindUsedTypes to do its job...\n    \/\/\n    virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n      AU.addRequired();\n    }\n  };\n  RegisterOpt X(\"deadtypeelim\", \"Dead Type Elimination\");\n  Statistic<>\n  NumKilled(\"deadtypeelim\", \"Number of unused typenames removed from symtab\");\n}\n\nPass *createDeadTypeEliminationPass() {\n  return new DTE();\n}\n\n\n\n\/\/ ShouldNukeSymtabEntry - Return true if this module level symbol table entry\n\/\/ should be eliminated.\n\/\/\nstatic inline bool ShouldNukeSymtabEntry(const std::pair&E){\n  \/\/ Nuke all names for primitive types!\n  if (cast(E.second)->isPrimitiveType()) return true;\n\n  \/\/ Nuke all pointers to primitive types as well...\n  if (const PointerType *PT = dyn_cast(E.second))\n    if (PT->getElementType()->isPrimitiveType()) return true;\n\n  return false;\n}\n\n\/\/ run - For this pass, it removes global symbol table entries for primitive\n\/\/ types.  These are never used for linking in GCC and they make the output\n\/\/ uglier to look at, so we nuke them.  Also eliminate types that are never used\n\/\/ in the entire program as indicated by FindUsedTypes.\n\/\/\nbool DTE::run(Module &M) {\n  bool Changed = false;\n\n  SymbolTable &ST = M.getSymbolTable();\n  const std::set &UsedTypes =\n    getAnalysis().getTypes();\n\n  \/\/ Check the symbol table for superfluous type entries...\n  \/\/\n  \/\/ Grab the 'type' plane of the module symbol...\n  SymbolTable::iterator STI = ST.find(Type::TypeTy);\n  if (STI != ST.end()) {\n    \/\/ Loop over all entries in the type plane...\n    SymbolTable::VarMap &Plane = STI->second;\n    for (SymbolTable::VarMap::iterator PI = Plane.begin(); PI != Plane.end();)\n      \/\/ If this entry should be unconditionally removed, or if we detect that\n      \/\/ the type is not used, remove it.\n      if (ShouldNukeSymtabEntry(*PI) ||\n          !UsedTypes.count(cast(PI->second))) {\n        SymbolTable::VarMap::iterator PJ = PI++;\n        Plane.erase(PJ);\n        ++NumKilled;\n        Changed = true;\n      } else {\n        ++PI;\n      }\n  }\n\n  return Changed;\n}\n<|endoftext|>"}
{"text":"\/*\n *  VHDL code generation for statements.\n *\n *  Copyright (C) 2008  Nick Gasson (nick@nickg.me.uk)\n *\n *  This program is free software; you can redistribute it and\/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation; either version 2 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License along\n *  with this program; if not, write to the Free Software Foundation, Inc.,\n *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \"vhdl_target.h\"\n\n#include \n#include \n#include \n#include \n\n\/*\n * Generate VHDL for the $display system task.\n * This is implemented using the functions in std.textio. Each\n * parameter is written to a line variable in the process and\n * then the line is written to the special variable `Output'\n * (which represents the console). Subsequent $displays will\n * use the same line variable.\n *\n * It's possible, although quite unlikely, that there will be\n * name collision with an existing variable called\n * `Verilog_Display_Line' -- do something about this?\n *\/\nstatic int draw_stask_display(vhdl_process *proc, stmt_container *container,\n                              ivl_statement_t stmt)\n{\n   \/\/ Add the package requirement to the containing entity\n   proc->get_parent()->get_parent()->requires_package(\"std.textio\");\n\n   const char *display_line = \"Verilog_Display_Line\";\n   \n   if (!proc->have_declared_var(display_line)) {\n      vhdl_var_decl *line_var =\n         new vhdl_var_decl(display_line, vhdl_type::line());\n      line_var->set_comment(\"For generating $display output\");\n      proc->add_decl(line_var);\n   }\n    \n   \/\/ Write the data into the line\n   int count = ivl_stmt_parm_count(stmt);\n   for (int i = 0; i < count; i++) {\n      \/\/ $display may have an empty parameter, in which case\n      \/\/ the expression will be null\n      \/\/ The behaviour here seems to be to output a space\n      ivl_expr_t net = ivl_stmt_parm(stmt, i);\n      vhdl_expr *e = NULL;\n      if (net) {\n         vhdl_expr *base = translate_expr(net);\n         if (NULL == base)\n            return 1;\n         \n         \/\/ Need to add a call to Type'Image for types not\n         \/\/ supported by std.textio\n         if (base->get_type()->get_name() != VHDL_TYPE_STRING) {\n            std::string name(base->get_type()->get_string());\n            name += \"'Image\";\n            \n            vhdl_fcall *cast\n               = new vhdl_fcall(name.c_str(), vhdl_type::string());\n            cast->add_expr(base);\n            e = cast;\n         }\n         else\n            e = base;\n      }\n      else\n         e = new vhdl_const_string(\" \");\n\n      vhdl_pcall_stmt *write = new vhdl_pcall_stmt(\"Write\");\n      vhdl_var_ref *ref =\n         new vhdl_var_ref(display_line, vhdl_type::line());\n      write->add_expr(ref);\n      write->add_expr(e);\n\n      container->add_stmt(write);\n   }\n\n   \/\/ WriteLine(Output, Verilog_Display_Line)\n   vhdl_pcall_stmt *write_line = new vhdl_pcall_stmt(\"WriteLine\");\n   vhdl_var_ref *output_ref =\n      new vhdl_var_ref(\"std.textio.Output\", new vhdl_type(VHDL_TYPE_FILE));\n   write_line->add_expr(output_ref);\n   vhdl_var_ref *ref =\n      new vhdl_var_ref(display_line, vhdl_type::line());\n   write_line->add_expr(ref);\n   container->add_stmt(write_line);\n   \n   return 0;\n}\n\n\/*\n * VHDL has no real equivalent of Verilog's $finish task. The\n * current solution is to use `assert false ...' to terminate\n * the simulator. This isn't great, as the simulator will\n * return a failure exit code when in fact it completed\n * successfully.\n *\/\nstatic int draw_stask_finish(vhdl_process *proc, stmt_container *container,\n                             ivl_statement_t stmt)\n{\n   container->add_stmt(new vhdl_assert_stmt(\"SIMULATION FINISHED\"));\n   return 0;\n}\n\n\/*\n * Generate VHDL for system tasks (like $display). Not all of\n * these are supported.\n *\/\nstatic int draw_stask(vhdl_process *proc, stmt_container *container,\n                      ivl_statement_t stmt)\n{\n   const char *name = ivl_stmt_name(stmt);\n\n   if (strcmp(name, \"$display\") == 0)\n      return draw_stask_display(proc, container, stmt);\n   else if (strcmp(name, \"$finish\") == 0)\n      return draw_stask_finish(proc, container, stmt);\n   else {\n      error(\"No VHDL translation for system task %s\", name);\n      return 0;\n   }\n}\n\n\/*\n * Generate VHDL for a block of Verilog statements. This doesn't\n * actually do anything, other than recursively translate the\n * block's statements and add them to the process. This is OK as\n * the stmt_container class behaves like a Verilog block.\n *\/\nstatic int draw_block(vhdl_process *proc, stmt_container *container,\n                      ivl_statement_t stmt)\n{\n   int count = ivl_stmt_block_count(stmt);\n   for (int i = 0; i < count; i++) {\n      if (draw_stmt(proc, container, ivl_stmt_block_stmt(stmt, i)) != 0)\n         return 1;\n   }\n   return 0;\n}\n\n\/*\n * A no-op statement. This corresponds to a `null' statement in\n * VHDL.\n *\/\nstatic int draw_noop(vhdl_process *proc, stmt_container *container,\n                     ivl_statement_t stmt)\n{\n   container->add_stmt(new vhdl_null_stmt());\n   return 0;\n}\n\n\/*\n * A non-blocking assignment inside a process. The semantics for\n * this are essentially the same as VHDL's non-blocking signal\n * assignment.\n *\/\nstatic int draw_nbassign(vhdl_process *proc, stmt_container *container,\n                         ivl_statement_t stmt, vhdl_expr *after = NULL)\n{\n   int nlvals = ivl_stmt_lvals(stmt);\n   if (nlvals != 1) {\n      error(\"Can only have 1 lval at the moment (found %d)\", nlvals);\n      return 1;\n   }\n\n   ivl_lval_t lval = ivl_stmt_lval(stmt, 0);\n   ivl_signal_t sig;\n   if ((sig = ivl_lval_sig(lval))) {\n      const char *signame = get_renamed_signal(sig).c_str();\n\n      vhdl_decl *decl = proc->get_parent()->get_decl(signame);\n      assert(decl);\n\n      vhdl_expr *rhs_raw = translate_expr(ivl_stmt_rval(stmt));\n      if (NULL == rhs_raw)\n         return 1;\n      vhdl_expr *rhs = rhs_raw->cast(decl->get_type());\n\n      \/\/ The type here can be null as it is never actually needed\n      vhdl_var_ref *lval_ref = new vhdl_var_ref(signame, NULL);\n\n      vhdl_nbassign_stmt *nbassign = new vhdl_nbassign_stmt(lval_ref, rhs);\n      if (after != NULL)\n         nbassign->set_after(after);\n      container->add_stmt(nbassign);\n   }\n   else {\n      error(\"Only signals as lvals supported at the moment\");\n      return 1;\n   }\n   \n   return 0;\n}\n\n\/*\n * Delay statements are equivalent to the `wait for' form of the\n * VHDL wait statement.\n *\/\nstatic int draw_delay(vhdl_process *proc, stmt_container *container,\n                      ivl_statement_t stmt)\n{\n   uint64_t value = ivl_stmt_delay_val(stmt);\n\n   \/\/ This currently ignores the time units and precision\n   \/\/ of the enclosing scope\n   \/\/ A neat way to do this would be to make these values\n   \/\/ constants in the scope (type is Time), and have the\n   \/\/ VHDL wait statement compute the value from that.\n   \/\/ The other solution is to add them as parameters to\n   \/\/ the vhdl_process class\n   vhdl_expr *time = new vhdl_const_int(value);\n\n   \/\/ If the sub-statement is an assignment then VHDL lets\n   \/\/ us put the delay after it, which is more compact and\n   \/\/ idiomatic\n   ivl_statement_t sub_stmt = ivl_stmt_sub_stmt(stmt);\n   ivl_statement_type_t type = ivl_statement_type(sub_stmt);\n   if (type == IVL_ST_ASSIGN_NB) {\n      draw_nbassign(proc, container, sub_stmt, time);\n   }\n   else {\n      vhdl_wait_stmt *wait =\n         new vhdl_wait_stmt(VHDL_WAIT_FOR_NS, time);\n      container->add_stmt(wait);\n\n      \/\/ Expand the sub-statement as well\n      \/\/ Often this would result in a useless `null' statement which\n      \/\/ is caught here instead\n      if (ivl_statement_type(sub_stmt) != IVL_ST_NOOP)\n         draw_stmt(proc, container, sub_stmt);\n   \n   }\n   \n   return 0;\n}\n\n\/*\n * A wait statement waits for a level change on a @(..) list of\n * signals.\n *\/\nstatic int draw_wait(vhdl_process *proc, stmt_container *container,\n                     ivl_statement_t stmt)\n{\n   ivl_statement_t sub_stmt = ivl_stmt_sub_stmt(stmt);\n   \n   int nevents = ivl_stmt_nevent(stmt);\n   for (int i = 0; i < nevents; i++) {\n      ivl_event_t event = ivl_stmt_events(stmt, i);\n\n      \/\/ A list of the non-edge triggered signals to they can\n      \/\/ be added to the edge-detecting `if' statement later\n      string_list_t non_edges;\n\n      int nany = ivl_event_nany(event);\n      for (int i = 0; i < nany; i++) {\n         ivl_nexus_t nexus = ivl_event_any(event, i);\n\n         int nptrs = ivl_nexus_ptrs(nexus);\n         for (int j = 0; j < nptrs; j++) {\n            ivl_nexus_ptr_t nexus_ptr = ivl_nexus_ptr(nexus, j);\n\n            ivl_signal_t sig;\n            if ((sig = ivl_nexus_ptr_sig(nexus_ptr))) {\n               const char *signame = ivl_signal_basename(sig);\n\n               \/\/ Only add this signal to the sensitivity if it's part\n               \/\/ of the containing architecture (i.e. it has already\n               \/\/ been declared)\n               if (proc->get_parent()->have_declared(signame)) {\n                  proc->add_sensitivity(signame);\n                  non_edges.push_back(signame);\n                  break;\n               }\n            }\n            else {\n               \/\/ Ignore all other types of nexus pointer\n            }\n         }\n      }\n\n      int nneg = ivl_event_nneg(event);\n      int npos = ivl_event_npos(event);\n      if (nneg + npos > 0) {\n         vhdl_binop_expr *test =\n            new vhdl_binop_expr(VHDL_BINOP_OR, vhdl_type::boolean());\n\n         \/\/ Generate falling_edge(..) calls for each negedge event\n         for (int i = 0; i < nneg; i++) {\n            ivl_nexus_t nexus = ivl_event_neg(event, i);\n\n            int nptrs = ivl_nexus_ptrs(nexus);\n            for (int j = 0; j < nptrs; j++) {\n               ivl_nexus_ptr_t nexus_ptr = ivl_nexus_ptr(nexus, j);\n\n               ivl_signal_t sig;\n               if ((sig = ivl_nexus_ptr_sig(nexus_ptr))) {\n                  vhdl_fcall *detect\n                     = new vhdl_fcall(\"falling_edge\", vhdl_type::boolean());\n                  detect->add_expr\n                     (new vhdl_var_ref(ivl_signal_basename(sig),\n                                       vhdl_type::std_logic()));\n                  test->add_expr(detect);\n                  break;\n               }\n            }\n         }\n\n         \/\/ Generate rising_edge(..) calls for each posedge event\n         for (int i = 0; i < npos; i++) {\n            ivl_nexus_t nexus = ivl_event_pos(event, i);\n\n            int nptrs = ivl_nexus_ptrs(nexus);\n            for (int j = 0; j < nptrs; j++) {\n               ivl_nexus_ptr_t nexus_ptr = ivl_nexus_ptr(nexus, j);\n\n               ivl_signal_t sig;\n               if ((sig = ivl_nexus_ptr_sig(nexus_ptr))) {\n                  vhdl_fcall *detect\n                     = new vhdl_fcall(\"rising_edge\", vhdl_type::boolean());\n                  detect->add_expr\n                     (new vhdl_var_ref(ivl_signal_basename(sig),\n                                       vhdl_type::std_logic()));\n                  test->add_expr(detect);\n                  break;\n               }\n            }\n         }\n\n         \/\/ Add Name'Event terms for each non-edge-triggered signal\n         string_list_t::iterator it;\n         for (it = non_edges.begin(); it != non_edges.end(); ++it) {\n            test->add_expr\n               (new vhdl_var_ref((*it + \"'Event\").c_str(),\n                                 vhdl_type::boolean()));\n         }\n\n         vhdl_if_stmt *edge_det = new vhdl_if_stmt(test);\n         container->add_stmt(edge_det);\n         \n         draw_stmt(proc, edge_det->get_then_container(), sub_stmt);\n      }\n      else {\n         \/\/ Don't bother generating an edge detector if there\n         \/\/ are no edge-triggered events\n         draw_stmt(proc, container, sub_stmt);\n      }\n   }\n   \n   return 0;\n}\n\nstatic int draw_if(vhdl_process *proc, stmt_container *container,\n                   ivl_statement_t stmt)\n{\n   vhdl_expr *test = translate_expr(ivl_stmt_cond_expr(stmt));\n   if (NULL == test)\n      return 1;\n   \n   vhdl_if_stmt *vhdif = new vhdl_if_stmt(test);\n\n   draw_stmt(proc, vhdif->get_then_container(),\n             ivl_stmt_cond_true(stmt));\n   draw_stmt(proc, vhdif->get_else_container(),\n             ivl_stmt_cond_false(stmt));\n\n   container->add_stmt(vhdif);\n   \n   return 0;\n}\n\n\/*\n * Generate VHDL statements for the given Verilog statement and\n * add them to the given VHDL process. The container is the\n * location to add statements: e.g. the process body, a branch\n * of an if statement, etc.\n *\/\nint draw_stmt(vhdl_process *proc, stmt_container *container,\n              ivl_statement_t stmt)\n{\n   switch (ivl_statement_type(stmt)) {\n   case IVL_ST_STASK:\n      return draw_stask(proc, container, stmt);\n   case IVL_ST_BLOCK:\n      return draw_block(proc, container, stmt);\n   case IVL_ST_NOOP:\n      return draw_noop(proc, container, stmt);\n   case IVL_ST_ASSIGN_NB:\n      return draw_nbassign(proc, container, stmt);\n   case IVL_ST_DELAY:\n      return draw_delay(proc, container, stmt);\n   case IVL_ST_WAIT:\n      return draw_wait(proc, container, stmt);\n   case IVL_ST_CONDIT:\n      return draw_if(proc, container, stmt);\n   default:\n      error(\"No VHDL translation for statement at %s:%d (type = %d)\",\n            ivl_stmt_file(stmt), ivl_stmt_lineno(stmt),\n            ivl_statement_type(stmt));\n      return 1;            \n   }\n}\nClean up the edge detector code a bit\/*\n *  VHDL code generation for statements.\n *\n *  Copyright (C) 2008  Nick Gasson (nick@nickg.me.uk)\n *\n *  This program is free software; you can redistribute it and\/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation; either version 2 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License along\n *  with this program; if not, write to the Free Software Foundation, Inc.,\n *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \"vhdl_target.h\"\n\n#include \n#include \n#include \n#include \n\n\/*\n * Generate VHDL for the $display system task.\n * This is implemented using the functions in std.textio. Each\n * parameter is written to a line variable in the process and\n * then the line is written to the special variable `Output'\n * (which represents the console). Subsequent $displays will\n * use the same line variable.\n *\n * It's possible, although quite unlikely, that there will be\n * name collision with an existing variable called\n * `Verilog_Display_Line' -- do something about this?\n *\/\nstatic int draw_stask_display(vhdl_process *proc, stmt_container *container,\n                              ivl_statement_t stmt)\n{\n   \/\/ Add the package requirement to the containing entity\n   proc->get_parent()->get_parent()->requires_package(\"std.textio\");\n\n   const char *display_line = \"Verilog_Display_Line\";\n   \n   if (!proc->have_declared_var(display_line)) {\n      vhdl_var_decl *line_var =\n         new vhdl_var_decl(display_line, vhdl_type::line());\n      line_var->set_comment(\"For generating $display output\");\n      proc->add_decl(line_var);\n   }\n    \n   \/\/ Write the data into the line\n   int count = ivl_stmt_parm_count(stmt);\n   for (int i = 0; i < count; i++) {\n      \/\/ $display may have an empty parameter, in which case\n      \/\/ the expression will be null\n      \/\/ The behaviour here seems to be to output a space\n      ivl_expr_t net = ivl_stmt_parm(stmt, i);\n      vhdl_expr *e = NULL;\n      if (net) {\n         vhdl_expr *base = translate_expr(net);\n         if (NULL == base)\n            return 1;\n         \n         \/\/ Need to add a call to Type'Image for types not\n         \/\/ supported by std.textio\n         if (base->get_type()->get_name() != VHDL_TYPE_STRING) {\n            std::string name(base->get_type()->get_string());\n            name += \"'Image\";\n            \n            vhdl_fcall *cast\n               = new vhdl_fcall(name.c_str(), vhdl_type::string());\n            cast->add_expr(base);\n            e = cast;\n         }\n         else\n            e = base;\n      }\n      else\n         e = new vhdl_const_string(\" \");\n\n      vhdl_pcall_stmt *write = new vhdl_pcall_stmt(\"Write\");\n      vhdl_var_ref *ref =\n         new vhdl_var_ref(display_line, vhdl_type::line());\n      write->add_expr(ref);\n      write->add_expr(e);\n\n      container->add_stmt(write);\n   }\n\n   \/\/ WriteLine(Output, Verilog_Display_Line)\n   vhdl_pcall_stmt *write_line = new vhdl_pcall_stmt(\"WriteLine\");\n   vhdl_var_ref *output_ref =\n      new vhdl_var_ref(\"std.textio.Output\", new vhdl_type(VHDL_TYPE_FILE));\n   write_line->add_expr(output_ref);\n   vhdl_var_ref *ref =\n      new vhdl_var_ref(display_line, vhdl_type::line());\n   write_line->add_expr(ref);\n   container->add_stmt(write_line);\n   \n   return 0;\n}\n\n\/*\n * VHDL has no real equivalent of Verilog's $finish task. The\n * current solution is to use `assert false ...' to terminate\n * the simulator. This isn't great, as the simulator will\n * return a failure exit code when in fact it completed\n * successfully.\n *\/\nstatic int draw_stask_finish(vhdl_process *proc, stmt_container *container,\n                             ivl_statement_t stmt)\n{\n   container->add_stmt(new vhdl_assert_stmt(\"SIMULATION FINISHED\"));\n   return 0;\n}\n\n\/*\n * Generate VHDL for system tasks (like $display). Not all of\n * these are supported.\n *\/\nstatic int draw_stask(vhdl_process *proc, stmt_container *container,\n                      ivl_statement_t stmt)\n{\n   const char *name = ivl_stmt_name(stmt);\n\n   if (strcmp(name, \"$display\") == 0)\n      return draw_stask_display(proc, container, stmt);\n   else if (strcmp(name, \"$finish\") == 0)\n      return draw_stask_finish(proc, container, stmt);\n   else {\n      error(\"No VHDL translation for system task %s\", name);\n      return 0;\n   }\n}\n\n\/*\n * Generate VHDL for a block of Verilog statements. This doesn't\n * actually do anything, other than recursively translate the\n * block's statements and add them to the process. This is OK as\n * the stmt_container class behaves like a Verilog block.\n *\/\nstatic int draw_block(vhdl_process *proc, stmt_container *container,\n                      ivl_statement_t stmt)\n{\n   int count = ivl_stmt_block_count(stmt);\n   for (int i = 0; i < count; i++) {\n      if (draw_stmt(proc, container, ivl_stmt_block_stmt(stmt, i)) != 0)\n         return 1;\n   }\n   return 0;\n}\n\n\/*\n * A no-op statement. This corresponds to a `null' statement in\n * VHDL.\n *\/\nstatic int draw_noop(vhdl_process *proc, stmt_container *container,\n                     ivl_statement_t stmt)\n{\n   container->add_stmt(new vhdl_null_stmt());\n   return 0;\n}\n\n\/*\n * A non-blocking assignment inside a process. The semantics for\n * this are essentially the same as VHDL's non-blocking signal\n * assignment.\n *\/\nstatic int draw_nbassign(vhdl_process *proc, stmt_container *container,\n                         ivl_statement_t stmt, vhdl_expr *after = NULL)\n{\n   int nlvals = ivl_stmt_lvals(stmt);\n   if (nlvals != 1) {\n      error(\"Can only have 1 lval at the moment (found %d)\", nlvals);\n      return 1;\n   }\n\n   ivl_lval_t lval = ivl_stmt_lval(stmt, 0);\n   ivl_signal_t sig;\n   if ((sig = ivl_lval_sig(lval))) {\n      const char *signame = get_renamed_signal(sig).c_str();\n\n      vhdl_decl *decl = proc->get_parent()->get_decl(signame);\n      assert(decl);\n\n      vhdl_expr *rhs_raw = translate_expr(ivl_stmt_rval(stmt));\n      if (NULL == rhs_raw)\n         return 1;\n      vhdl_expr *rhs = rhs_raw->cast(decl->get_type());\n\n      \/\/ The type here can be null as it is never actually needed\n      vhdl_var_ref *lval_ref = new vhdl_var_ref(signame, NULL);\n\n      vhdl_nbassign_stmt *nbassign = new vhdl_nbassign_stmt(lval_ref, rhs);\n      if (after != NULL)\n         nbassign->set_after(after);\n      container->add_stmt(nbassign);\n   }\n   else {\n      error(\"Only signals as lvals supported at the moment\");\n      return 1;\n   }\n   \n   return 0;\n}\n\n\/*\n * Delay statements are equivalent to the `wait for' form of the\n * VHDL wait statement.\n *\/\nstatic int draw_delay(vhdl_process *proc, stmt_container *container,\n                      ivl_statement_t stmt)\n{\n   uint64_t value = ivl_stmt_delay_val(stmt);\n\n   \/\/ This currently ignores the time units and precision\n   \/\/ of the enclosing scope\n   \/\/ A neat way to do this would be to make these values\n   \/\/ constants in the scope (type is Time), and have the\n   \/\/ VHDL wait statement compute the value from that.\n   \/\/ The other solution is to add them as parameters to\n   \/\/ the vhdl_process class\n   vhdl_expr *time = new vhdl_const_int(value);\n\n   \/\/ If the sub-statement is an assignment then VHDL lets\n   \/\/ us put the delay after it, which is more compact and\n   \/\/ idiomatic\n   ivl_statement_t sub_stmt = ivl_stmt_sub_stmt(stmt);\n   ivl_statement_type_t type = ivl_statement_type(sub_stmt);\n   if (type == IVL_ST_ASSIGN_NB) {\n      draw_nbassign(proc, container, sub_stmt, time);\n   }\n   else {\n      vhdl_wait_stmt *wait =\n         new vhdl_wait_stmt(VHDL_WAIT_FOR_NS, time);\n      container->add_stmt(wait);\n\n      \/\/ Expand the sub-statement as well\n      \/\/ Often this would result in a useless `null' statement which\n      \/\/ is caught here instead\n      if (ivl_statement_type(sub_stmt) != IVL_ST_NOOP)\n         draw_stmt(proc, container, sub_stmt);\n   \n   }\n   \n   return 0;\n}\n\n\/*\n * Make edge detectors from the signals in `nexus' and add them\n * to the expression `test'. Also adds the signals to the process\n * sensitivity list. Type should be one of `rising_edge' or\n * `falling_edge'.\n *\/\nstatic void edge_detector(ivl_nexus_t nexus, vhdl_process *proc,\n                          vhdl_binop_expr *test, const char *type)\n{\n   int nptrs = ivl_nexus_ptrs(nexus);\n   for (int j = 0; j < nptrs; j++) {\n      ivl_nexus_ptr_t nexus_ptr = ivl_nexus_ptr(nexus, j);\n      \n      ivl_signal_t sig;\n      if ((sig = ivl_nexus_ptr_sig(nexus_ptr))) {\n         const char *signame = get_renamed_signal(sig).c_str();\n         \n         vhdl_fcall *detect\n            = new vhdl_fcall(type, vhdl_type::boolean());\n         detect->add_expr\n            (new vhdl_var_ref(signame, vhdl_type::std_logic()));\n         test->add_expr(detect);\n         proc->add_sensitivity(signame);\n         break;\n      }\n   }\n}\n\n\n\/*\n * A wait statement waits for a level change on a @(..) list of\n * signals.\n *\/\nstatic int draw_wait(vhdl_process *proc, stmt_container *container,\n                     ivl_statement_t stmt)\n{\n   ivl_statement_t sub_stmt = ivl_stmt_sub_stmt(stmt);\n   \n   int nevents = ivl_stmt_nevent(stmt);\n   for (int i = 0; i < nevents; i++) {\n      ivl_event_t event = ivl_stmt_events(stmt, i);\n\n      \/\/ A list of the non-edge triggered signals to they can\n      \/\/ be added to the edge-detecting `if' statement later\n      string_list_t non_edges;\n\n      int nany = ivl_event_nany(event);\n      for (int i = 0; i < nany; i++) {\n         ivl_nexus_t nexus = ivl_event_any(event, i);\n\n         int nptrs = ivl_nexus_ptrs(nexus);\n         for (int j = 0; j < nptrs; j++) {\n            ivl_nexus_ptr_t nexus_ptr = ivl_nexus_ptr(nexus, j);\n\n            ivl_signal_t sig;\n            if ((sig = ivl_nexus_ptr_sig(nexus_ptr))) {\n               const char *signame = ivl_signal_basename(sig);\n\n               \/\/ Only add this signal to the sensitivity if it's part\n               \/\/ of the containing architecture (i.e. it has already\n               \/\/ been declared)\n               if (proc->get_parent()->have_declared(signame)) {\n                  proc->add_sensitivity(signame);\n                  non_edges.push_back(signame);\n                  break;\n               }\n            }\n            else {\n               \/\/ Ignore all other types of nexus pointer\n            }\n         }\n      }\n\n      int nneg = ivl_event_nneg(event);\n      int npos = ivl_event_npos(event);\n      if (nneg + npos > 0) {\n         vhdl_binop_expr *test =\n            new vhdl_binop_expr(VHDL_BINOP_OR, vhdl_type::boolean());\n\n         \/\/ Generate falling_edge(..) calls for each negedge event\n         for (int i = 0; i < nneg; i++)\n            edge_detector(ivl_event_neg(event, i), proc, test, \"falling_edge\");\n        \n         \/\/ Generate rising_edge(..) calls for each posedge event\n         for (int i = 0; i < npos; i++)\n            edge_detector(ivl_event_pos(event, i), proc, test, \"rising_edge\");\n        \n         \/\/ Add Name'Event terms for each non-edge-triggered signal\n         string_list_t::iterator it;\n         for (it = non_edges.begin(); it != non_edges.end(); ++it) {\n            test->add_expr\n               (new vhdl_var_ref((*it + \"'Event\").c_str(),\n                                 vhdl_type::boolean()));\n         }\n\n         vhdl_if_stmt *edge_det = new vhdl_if_stmt(test);\n         container->add_stmt(edge_det);\n         \n         draw_stmt(proc, edge_det->get_then_container(), sub_stmt);\n      }\n      else {\n         \/\/ Don't bother generating an edge detector if there\n         \/\/ are no edge-triggered events\n         draw_stmt(proc, container, sub_stmt);\n      }\n   }\n   \n   return 0;\n}\n\nstatic int draw_if(vhdl_process *proc, stmt_container *container,\n                   ivl_statement_t stmt)\n{\n   vhdl_expr *test = translate_expr(ivl_stmt_cond_expr(stmt));\n   if (NULL == test)\n      return 1;\n   \n   vhdl_if_stmt *vhdif = new vhdl_if_stmt(test);\n\n   draw_stmt(proc, vhdif->get_then_container(),\n             ivl_stmt_cond_true(stmt));\n   draw_stmt(proc, vhdif->get_else_container(),\n             ivl_stmt_cond_false(stmt));\n\n   container->add_stmt(vhdif);\n   \n   return 0;\n}\n\n\/*\n * Generate VHDL statements for the given Verilog statement and\n * add them to the given VHDL process. The container is the\n * location to add statements: e.g. the process body, a branch\n * of an if statement, etc.\n *\/\nint draw_stmt(vhdl_process *proc, stmt_container *container,\n              ivl_statement_t stmt)\n{\n   switch (ivl_statement_type(stmt)) {\n   case IVL_ST_STASK:\n      return draw_stask(proc, container, stmt);\n   case IVL_ST_BLOCK:\n      return draw_block(proc, container, stmt);\n   case IVL_ST_NOOP:\n      return draw_noop(proc, container, stmt);\n   case IVL_ST_ASSIGN_NB:\n      return draw_nbassign(proc, container, stmt);\n   case IVL_ST_DELAY:\n      return draw_delay(proc, container, stmt);\n   case IVL_ST_WAIT:\n      return draw_wait(proc, container, stmt);\n   case IVL_ST_CONDIT:\n      return draw_if(proc, container, stmt);\n   default:\n      error(\"No VHDL translation for statement at %s:%d (type = %d)\",\n            ivl_stmt_file(stmt), ivl_stmt_lineno(stmt),\n            ivl_statement_type(stmt));\n      return 1;            \n   }\n}\n<|endoftext|>"}
{"text":"\/*\n * callable.hpp\n *\n *  Created on: 29 мая 2016 г.\n *      Author: sergey.fedorov\n *\/\n\n#ifndef PUSHKIN_META_CALLABLE_HPP_\n#define PUSHKIN_META_CALLABLE_HPP_\n\n#include \n#include \n#include \n\nnamespace psst {\nnamespace meta {\n\ntemplate \nstruct is_callable {\nprivate:\n    using args_tuple    = ::std::tuple;\n    using indexes       = typename index_builder< sizeof ... (Args) >::type;\n    static args_tuple& args;\n\n    template \n    static ::std::true_type\n    test(indexes_tuple const&,\n        decltype( ::std::declval()( ::std::forward(::std::get(args))... ) ) const*);\n    template \n    static ::std::false_type\n    test(...);\npublic:\n    static constexpr bool value = decltype( test(indexes{}, nullptr) )::value;\n};\n\ntemplate < typename Predicate >\nstruct not_ {\n    template < typename ... Args >\n    bool\n    operator()(Args&& ... args) const\n    {\n        return !Predicate{}(::std::forward(args)...);\n    }\n};\n\ntemplate < typename ... Predicates >\nstruct and_;\ntemplate < typename ... Predicates >\nstruct or_;\n\ntemplate < typename Predicate, typename ... Rest >\nstruct and_ {\n    template < typename ... Args >\n    bool\n    operator()(Args&& ... args) const\n    {\n        return Predicate{}(::std::forward(args)...)\n            && and_{}(::std::forward(args)...);\n    }\n};\n\ntemplate < typename Predicate >\nstruct and_ {\n    template < typename ... Args >\n    bool\n    operator()(Args&& ... args) const\n    {\n        return Predicate{}(::std::forward(args)...);\n    }\n};\n\ntemplate <>\nstruct and_<> {\n    template < typename ... Args >\n    bool\n    operator()(Args&& ... args) const\n    {\n        return false;\n    }\n};\n\ntemplate < typename Predicate, typename ... Rest >\nstruct or_ {\n    template < typename ... Args >\n    bool\n    operator()(Args&& ... args) const\n    {\n        return Predicate{}(::std::forward(args)...)\n            || and_{}(::std::forward(args)...);\n    }\n};\n\ntemplate < typename Predicate >\nstruct or_ {\n    template < typename ... Args >\n    bool\n    operator()(Args&& ... args) const\n    {\n        return Predicate{}(::std::forward(args)...);\n    }\n};\n\ntemplate <>\nstruct or_<> {\n    template < typename ... Args >\n    bool\n    operator()(Args&& ... args) const\n    {\n        return true;\n    }\n};\n\n}  \/* namespace meta *\/\n}  \/* namespace pus *\/\n\n\n\n#endif \/* PUSHKIN_META_CALLABLE_HPP_ *\/\nSatisfy -Werror,-Wunused-parameter flags\/*\n * callable.hpp\n *\n *  Created on: 29 мая 2016 г.\n *      Author: sergey.fedorov\n *\/\n\n#ifndef PUSHKIN_META_CALLABLE_HPP_\n#define PUSHKIN_META_CALLABLE_HPP_\n\n#include \n#include \n#include \n\nnamespace psst {\nnamespace meta {\n\ntemplate \nstruct is_callable {\nprivate:\n    using args_tuple    = ::std::tuple;\n    using indexes       = typename index_builder< sizeof ... (Args) >::type;\n    static args_tuple& args;\n\n    template \n    static ::std::true_type\n    test(indexes_tuple const&,\n        decltype( ::std::declval()( ::std::forward(::std::get(args))... ) ) const*);\n    template \n    static ::std::false_type\n    test(...);\npublic:\n    static constexpr bool value = decltype( test(indexes{}, nullptr) )::value;\n};\n\ntemplate < typename Predicate >\nstruct not_ {\n    template < typename ... Args >\n    bool\n    operator()(Args&& ... args) const\n    {\n        return !Predicate{}(::std::forward(args)...);\n    }\n};\n\ntemplate < typename ... Predicates >\nstruct and_;\ntemplate < typename ... Predicates >\nstruct or_;\n\ntemplate < typename Predicate, typename ... Rest >\nstruct and_ {\n    template < typename ... Args >\n    bool\n    operator()(Args&& ... args) const\n    {\n        return Predicate{}(::std::forward(args)...)\n            && and_{}(::std::forward(args)...);\n    }\n};\n\ntemplate < typename Predicate >\nstruct and_ {\n    template < typename ... Args >\n    bool\n    operator()(Args&& ... args) const\n    {\n        return Predicate{}(::std::forward(args)...);\n    }\n};\n\ntemplate <>\nstruct and_<> {\n    template < typename ... Args >\n    bool\n    operator()(Args&& ...) const\n    {\n        return false;\n    }\n};\n\ntemplate < typename Predicate, typename ... Rest >\nstruct or_ {\n    template < typename ... Args >\n    bool\n    operator()(Args&& ... args) const\n    {\n        return Predicate{}(::std::forward(args)...)\n            || and_{}(::std::forward(args)...);\n    }\n};\n\ntemplate < typename Predicate >\nstruct or_ {\n    template < typename ... Args >\n    bool\n    operator()(Args&& ... args) const\n    {\n        return Predicate{}(::std::forward(args)...);\n    }\n};\n\ntemplate <>\nstruct or_<> {\n    template < typename ... Args >\n    bool\n    operator()(Args&& ...) const\n    {\n        return true;\n    }\n};\n\n}  \/* namespace meta *\/\n}  \/* namespace pus *\/\n\n\n\n#endif \/* PUSHKIN_META_CALLABLE_HPP_ *\/\n<|endoftext|>"}
{"text":"#ifndef GENERIC_SIZE_HPP\n# define GENERIC_SIZE_HPP\n# pragma once\n\nnamespace generic\n{\n\n\/\/ size\ntemplate \ninline constexpr decltype(N) size(T const (&)[N]) noexcept\n{\n  return N;\n}\n\n}\n\n#endif \/\/ GENERIC_SIZE_HPP\nsome fixes#ifndef GENERIC_SIZE_HPP\n# define GENERIC_SIZE_HPP\n# pragma once\n\nnamespace generic\n{\n\n\/\/ size\ntemplate \ninline constexpr decltype(N) size(T const (&)[N]) noexcept\n{\n  return N;\n}\n\ntemplate \ninline constexpr decltype(N) size(T const (&array)[M][N]) noexcept\n{\n  return M * size(*array);\n}\n\n}\n\n#endif \/\/ GENERIC_SIZE_HPP\n<|endoftext|>"}
{"text":"#ifndef LUA_H\n\t#include \"lua_adapter.hpp\"\n#endif\n\n\nint main (int argc, char *argv[]) {  \t\n    \n    LuaAdapter lua(\"test.lua\");\n    \n    \/\/simply parameterize your application!\n    int height {0};\n    lua.get(\"height\", height);\t\n    std::cout << \"height: \" << height << \"\\n\";\n\n    \/\/ let's close ..\n    lua.close();\n    \/\/ and (re-)initialize for further tests..\n    lua.init();\n    \n    \/\/ Hint: You CAN change a (default) value of a global lua variable BEFORE loading the actual lua-file\n    if(lua.set(\"GlobalVar\", 321)==false){\n        std::cout << \"Could not set 'GlobalVar'!\\n\";\n    }\n\n    \/\/ and THEN load the script:\n    lua.load(\"test.lua\");\t\n\n    \n    \/\/get an int\n    int width {0};\n    lua.get(\"width\", width);\t\n    std::cout << \"width: \" << width << \"\\n\";\n\n    \n    \/\/get double\n    double number {0};\n    lua.get(\"number\", number);\n    std::cout << \"Number: \"<< number << \"\\n\";\n\n\n    \/\/get string\n    std::string title {\"empty\"};\n    lua.get(\"title\", title);\t\n    std::cout << \"title: \" << title << \"\\n\";\n\n    std::cout << \"\\n\";\n\n    \/\/ tables\n    if(lua.openTable(\"Table1\")) {\n        int ID {0};\n        lua.getField(\"ID\", ID);\t\n        std::cout << \"ID: \" << ID << \"\\n\";\n\n        int Val {0};\n        lua.getField(\"Val\", Val);\t\n        std::cout << \"Val: \" << Val << \"\\n\";\n\n        lua.closeTable(); \/\/ close \"Table1\"\n    }\n\n    std::cout << \"\\n\";\n\n   \n    if(lua.openTable(\"matrix\")) {\n        for(unsigned char j=1; j<=3; j++){\n            for(unsigned char i=1; i<=3; i++){\n                int temp = 0;\n                lua.getNestedField(j, i, temp); \/\/ matrix[j][i]\n                std::cout << temp << \" \";\n            }\n            std::cout << \"\\n\"; \n        }\n        lua.closeTable(); \/\/ close table \"matrix\"\n    }\n    std::cout << \"\\n\";\n\n    \/\/ more table-tests\n    if(lua.openTable(\"Table2\")) { \t\t\n        int X {0};\n        lua.getField(\"X\", X);\t\n        std::cout << \"X: \" << X << \"\\n\";\n\n        int Y {0};\n        lua.getField(\"Y\", Y);\t\n        std::cout << \"Y: \" << Y << \"\\n\";\n\n        if(lua.openNestedTable(\"Test\") )  { \n            int A = 0;\n            lua.getField(\"A\", A);\t\n            std::cout << \"\\t A: \" << A << \"\\n\";\n            int B = 0;\n            lua.getField(\"B\", B);\t\n            std::cout << \"\\t B: \" << B << \"\\n\";\n\n            lua.closeTable(); \/\/ close nested table \"Test\"\n        }\n        lua.closeTable(); \/\/ close \"Table2\"\n    }\n\n    \/\/ Check lua's internal stack\n    std::cout << \"\\n\";\n    std::cout << \"Lua stack top: \" << lua.getTop() << \"\\n\"; \/\/ should be 0\n\n\n    \/\/ calling a function from test.lua to compute stuff\n    int test[] = {36, 24};\n    int result {0};\n    lua.callFunction(\"gcd\", 2, test, result);\n    std::cout << \"gcd: \" << result << \"\\n\"; \t\n\n    return 0;\n}\nAdded C++-function-call-example.#ifndef LUA_H\n\t#include \"lua_adapter.hpp\"\n#endif\nstatic int testCFunction(lua_State *L);\n\n\nint main (int argc, char *argv[]) {  \t\n    \n    LuaAdapter lua(\"test.lua\");\n    \n    \/\/simply parameterize your application!\n    int height {0};\n    lua.get(\"height\", height);\t\n    std::cout << \"height: \" << height << \"\\n\";\n\n    \/\/ let's close ..\n    lua.close();\n    \/\/ and (re-)initialize for further tests..\n    lua.init();\n    \n    \/\/ Hint: You CAN change a (default) value of a global lua variable BEFORE loading the actual lua-file\n    if(lua.set(\"GlobalVar\", 321)==false){\n        std::cout << \"Could not set 'GlobalVar'!\\n\";\n    }\n\n    \/\/ and THEN load the script:\n    lua.load(\"test.lua\");\t\n\n    \n    \/\/get an int\n    int width {0};\n    lua.get(\"width\", width);\t\n    std::cout << \"width: \" << width << \"\\n\";\n\n    \n    \/\/get double\n    double number {0};\n    lua.get(\"number\", number);\n    std::cout << \"Number: \"<< number << \"\\n\";\n\n\n    \/\/get string\n    std::string title {\"empty\"};\n    lua.get(\"title\", title);\t\n    std::cout << \"title: \" << title << \"\\n\";\n\n    std::cout << \"\\n\";\n\n    \/\/ tables\n    if(lua.openTable(\"Table1\")) {\n        int ID {0};\n        lua.getField(\"ID\", ID);\t\n        std::cout << \"ID: \" << ID << \"\\n\";\n\n        int Val {0};\n        lua.getField(\"Val\", Val);\t\n        std::cout << \"Val: \" << Val << \"\\n\";\n\n        lua.closeTable(); \/\/ close \"Table1\"\n    }\n\n    std::cout << \"\\n\";\n\n   \n    if(lua.openTable(\"matrix\")) {\n        for(unsigned char j=1; j<=3; j++){\n            for(unsigned char i=1; i<=3; i++){\n                int temp = 0;\n                lua.getNestedField(j, i, temp); \/\/ matrix[j][i]\n                std::cout << temp << \" \";\n            }\n            std::cout << \"\\n\"; \n        }\n        lua.closeTable(); \/\/ close table \"matrix\"\n    }\n    std::cout << \"\\n\";\n\n    \/\/ more table-tests\n    if(lua.openTable(\"Table2\")) { \t\t\n        int X {0};\n        lua.getField(\"X\", X);\t\n        std::cout << \"X: \" << X << \"\\n\";\n\n        int Y {0};\n        lua.getField(\"Y\", Y);\t\n        std::cout << \"Y: \" << Y << \"\\n\";\n\n        if(lua.openNestedTable(\"Test\") )  { \n            int A = 0;\n            lua.getField(\"A\", A);\t\n            std::cout << \"\\t A: \" << A << \"\\n\";\n            int B = 0;\n            lua.getField(\"B\", B);\t\n            std::cout << \"\\t B: \" << B << \"\\n\";\n\n            lua.closeTable(); \/\/ close nested table \"Test\"\n        }\n        lua.closeTable(); \/\/ close \"Table2\"\n    }\n\n    \/\/ Check lua's internal stack\n    std::cout << \"\\n\";\n    std::cout << \"Lua stack top: \" << lua.getTop() << \"\\n\"; \/\/ should be 0\n\n\n    \/\/ calling a function from test.lua to compute stuff\n    int test[] = {36, 24};\n    int result {0};\n    lua.callFunction(\"gcd\", 2, test, result);\n    std::cout << \"gcd: \" << result << \"\\n\";\n    std::cout << \"\\n\";\n\n\n    \/\/ Push a C\/C++-function to our lua-stack...\n    lua.pushFunction(testCFunction, \"testFunction\");\n\n    \/\/ and call it!\n    double result2 {0};   \n    lua.callFunction(\"testFunction\", result2);\n    std::cout << \"testing C-Function: \" << result2 << \"\\n\";\n\n\n    std::cout << \"Lua stack top: \" << lua.getTop() << \"\\n\"; \/\/ 0\n    return 0;\n}\n\n\n\/\/ This function can be called from Lua\nstatic int testCFunction(lua_State *L){\n    LuaAdapter lua {L};    \n    double number {0};\n    lua.get(\"number\", number);\n\n    std::cout << \"Number: \"<< number << \"\\n\";\n    std::cout << \"Lua stack top: \" << lua.getTop() << \"\\n\"; \/\/ 1\n\n    number *=2;\n    lua.push(number);\n    return 1;    \n}\n<|endoftext|>"}
{"text":"#include \n#include \n#include \n#include \n\nusing namespace cv;\n\nvoid showHistogram(Mat& img);\n\nint main(int argc, char* argv[])\n{\n  Mat img, gray, post, anded;\n  \n  if(!(img=imread(\"pool1.jpg\", 1)).data)\n  {\n      std::cout << \"crap\" << std::endl;\n      return -1;\n  }\n  else\n  {\n      std::cout << \"yay\" << std::endl;\n  }\n  \n  cvtColor(img,img, CV_BGR2HSV);\n  inRange(img, Scalar(0, 0, 60), Scalar(180, 100, 200), post);\n  \n  bitwise_not(post, post);\n  \n  cvtColor(post,post, CV_GRAY2BGR);\n  cvtColor(img,img, CV_HSV2BGR);\n  \n  bitwise_and(img, post, anded);\n  \n  \n  cvtColor(post, gray, CV_BGR2GRAY);\n  cvtColor(post, post, CV_BGR2GRAY);\n  \n  \/\/ smooth it, otherwise a lot of false circles may be detected\n  GaussianBlur( gray, gray, Size(25, 25), 9, 9 );\n  threshold(gray, gray, 40, 255, THRESH_BINARY);\n  GaussianBlur( gray, gray, Size(9, 9), 2, 2 );\n  \n  vector circles;\n  HoughCircles(gray, circles, CV_HOUGH_GRADIENT,\n                 2, 40, 200, 60, 10, 50 );\n\n  for( size_t i = 0; i < circles.size(); i++ )\n    {\n         Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));\n         int radius = cvRound(circles[i][2]);\n         \/\/ draw the circle center\n         circle( anded, center, 3, Scalar(0,255,0), -1, 8, 0 );\n         \/\/ draw the circle outline\n         circle( anded, center, radius, Scalar(0,0,255), 3, 8, 0 );\n\t \n\t \/\/ center and radius are the results of HoughCircle\n\t\/\/ mask is a CV_8UC1 image with 0\n\t\n\tMat dst, mask = Mat::zeros( img.rows, img.cols, CV_8UC1 );\n\tcircle( mask, center, radius, Scalar(255,255,255), -1, 8, 0 ); \/\/-1 means filled\n\tbitwise_and(post, mask, mask);\n\timg.copyTo( dst, mask ); \/\/ copy values of img to dst if mask is > 0.\n\tMat cropped( dst, Rect( center.x-radius, center.y-radius, radius*2, radius*2 ) );\n\t\n\timshow(\"test\", cropped);\n\tshowHistogram(cropped);\n\twaitKey(0);\n    }\n    \n\/\/     imshow(\"img\", img);\n\/\/     imshow(\"gray\", gray);\n\/\/     imshow(\"anded\", anded);\n\/\/     showHistogram(img);\n\/\/     waitKey(0);\n\/\/     imwrite( \"post.jpg\", post );\n\/\/     \n\/\/     imwrite( \"anded.jpg\", anded );\n\/\/     \n\/\/     imwrite( \"gray.jpg\", gray );\n\/\/     \n\/\/     imwrite( \"img.jpg\", img );\n  \n    return 0;\n}\n\nvoid showHistogram(Mat& img)\n{\n\tint bins = 256;             \/\/ number of bins\n\tint nc = img.channels();    \/\/ number of channels\n\n\tvector hist(nc);       \/\/ histogram arrays\n\n\t\/\/ Initalize histogram arrays\n\tfor (int i = 0; i < hist.size(); i++)\n\t\thist[i] = Mat::zeros(1, bins, CV_32SC1);\n\n\t\/\/ Calculate the histogram of the image\n\tfor (int i = 0; i < img.rows; i++)\n\t{\n\t\tfor (int j = 0; j < img.cols; j++)\n\t\t{\n\t\t\tif (!((img.at(i,j)[0] == 0) && \n\t\t\t      (img.at(i,j)[1] == 0) && \n\t\t\t      (img.at(i,j)[2] == 0)))\n\t\t\t{\n\t\t\tfor (int k = 0; k < nc; k++)\n\t\t\t{\n\t\t\t\tuchar val = nc == 1 ? img.at(i,j) : img.at(i,j)[k];\n\t\t\t\thist[k].at(val) += 1;\n\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\n\t\/\/ For each histogram arrays, obtain the maximum (peak) value\n\t\/\/ Needed to normalize the display later\n\tint hmax = 0;\n\tfor (int i = 0; i < nc; i++)\n\t{\n\t\tfor (int j = 0; j < bins-1; j++)\n\t\t\thmax = hist[i].at(j) > hmax ? hist[i].at(j) : hmax;\n\t}\n\n\tconst char* wname[3] = { \"blue\", \"green\", \"red\" };\n\tScalar colors[3] = { Scalar(255,0,0), Scalar(0,255,0), Scalar(0,0,255) };\n\n\tvector canvas(nc);\n\n\t\/\/ Display each histogram in a canvas\n\tfor (int i = 0; i < nc; i++)\n\t{\n\t\tcanvas[i] = Mat::ones(125, bins, CV_8UC3);\n\n\t\tfor (int j = 0, rows = canvas[i].rows; j < bins-1; j++)\n\t\t{\n\t\t\tline(\n\t\t\t\tcanvas[i], \n\t\t\t\tPoint(j, rows), \n\t\t\t\tPoint(j, rows - (hist[i].at(j) * rows\/hmax)), \n\t\t\t\tnc == 1 ? Scalar(200,200,200) : colors[i], \n\t\t\t\t1, 8, 0\n\t\t\t);\n\t\t}\n\n\t\timshow(nc == 1 ? \"value\" : wname[i], canvas[i]);\n\t}\n}-Added build line comment temporarily.#include \n#include \n#include \n#include \n\nusing namespace cv;\n\n\/\/g++ -o PoolVisor test.cpp  `pkg-config --cflags --libs opencv`\n\nvoid showHistogram(Mat& img);\n\nint main(int argc, char* argv[])\n{\n  Mat img, gray, post, anded;\n  \n  if(!(img=imread(\"pool1.jpg\", 1)).data)\n  {\n      std::cout << \"crap\" << std::endl;\n      return -1;\n  }\n  else\n  {\n      std::cout << \"yay\" << std::endl;\n  }\n  \n  cvtColor(img,img, CV_BGR2HSV);\n  inRange(img, Scalar(0, 0, 60), Scalar(180, 100, 200), post);\n  \n  bitwise_not(post, post);\n  \n  cvtColor(post,post, CV_GRAY2BGR);\n  cvtColor(img,img, CV_HSV2BGR);\n  \n  bitwise_and(img, post, anded);\n  \n  \n  cvtColor(post, gray, CV_BGR2GRAY);\n  cvtColor(post, post, CV_BGR2GRAY);\n  \n  \/\/ smooth it, otherwise a lot of false circles may be detected\n  GaussianBlur( gray, gray, Size(25, 25), 9, 9 );\n  threshold(gray, gray, 40, 255, THRESH_BINARY);\n  GaussianBlur( gray, gray, Size(9, 9), 2, 2 );\n  \n  vector circles;\n  HoughCircles(gray, circles, CV_HOUGH_GRADIENT,\n                 2, 40, 200, 60, 10, 50 );\n\n  for( size_t i = 0; i < circles.size(); i++ )\n    {\n         Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));\n         int radius = cvRound(circles[i][2]);\n         \/\/ draw the circle center\n         circle( anded, center, 3, Scalar(0,255,0), -1, 8, 0 );\n         \/\/ draw the circle outline\n         circle( anded, center, radius, Scalar(0,0,255), 3, 8, 0 );\n\t \n\t \/\/ center and radius are the results of HoughCircle\n\t\/\/ mask is a CV_8UC1 image with 0\n\t\n\tMat dst, mask = Mat::zeros( img.rows, img.cols, CV_8UC1 );\n\tcircle( mask, center, radius, Scalar(255,255,255), -1, 8, 0 ); \/\/-1 means filled\n\tbitwise_and(post, mask, mask);\n\timg.copyTo( dst, mask ); \/\/ copy values of img to dst if mask is > 0.\n\tMat cropped( dst, Rect( center.x-radius, center.y-radius, radius*2, radius*2 ) );\n\t\n\timshow(\"test\", cropped);\n\tshowHistogram(cropped);\n\twaitKey(0);\n    }\n    \n\/\/     imshow(\"img\", img);\n\/\/     imshow(\"gray\", gray);\n\/\/     imshow(\"anded\", anded);\n\/\/     showHistogram(img);\n\/\/     waitKey(0);\n\/\/     imwrite( \"post.jpg\", post );\n\/\/     \n\/\/     imwrite( \"anded.jpg\", anded );\n\/\/     \n\/\/     imwrite( \"gray.jpg\", gray );\n\/\/     \n\/\/     imwrite( \"img.jpg\", img );\n  \n    return 0;\n}\n\nvoid showHistogram(Mat& img)\n{\n\tint bins = 256;             \/\/ number of bins\n\tint nc = img.channels();    \/\/ number of channels\n\n\tvector hist(nc);       \/\/ histogram arrays\n\n\t\/\/ Initalize histogram arrays\n\tfor (int i = 0; i < hist.size(); i++)\n\t\thist[i] = Mat::zeros(1, bins, CV_32SC1);\n\n\t\/\/ Calculate the histogram of the image\n\tfor (int i = 0; i < img.rows; i++)\n\t{\n\t\tfor (int j = 0; j < img.cols; j++)\n\t\t{\n\t\t\tif (!((img.at(i,j)[0] == 0) && \n\t\t\t      (img.at(i,j)[1] == 0) && \n\t\t\t      (img.at(i,j)[2] == 0)))\n\t\t\t{\n\t\t\tfor (int k = 0; k < nc; k++)\n\t\t\t{\n\t\t\t\tuchar val = nc == 1 ? img.at(i,j) : img.at(i,j)[k];\n\t\t\t\thist[k].at(val) += 1;\n\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\n\t\/\/ For each histogram arrays, obtain the maximum (peak) value\n\t\/\/ Needed to normalize the display later\n\tint hmax = 0;\n\tfor (int i = 0; i < nc; i++)\n\t{\n\t\tfor (int j = 0; j < bins-1; j++)\n\t\t\thmax = hist[i].at(j) > hmax ? hist[i].at(j) : hmax;\n\t}\n\n\tconst char* wname[3] = { \"blue\", \"green\", \"red\" };\n\tScalar colors[3] = { Scalar(255,0,0), Scalar(0,255,0), Scalar(0,0,255) };\n\n\tvector canvas(nc);\n\n\t\/\/ Display each histogram in a canvas\n\tfor (int i = 0; i < nc; i++)\n\t{\n\t\tcanvas[i] = Mat::ones(125, bins, CV_8UC3);\n\n\t\tfor (int j = 0, rows = canvas[i].rows; j < bins-1; j++)\n\t\t{\n\t\t\tline(\n\t\t\t\tcanvas[i], \n\t\t\t\tPoint(j, rows), \n\t\t\t\tPoint(j, rows - (hist[i].at(j) * rows\/hmax)), \n\t\t\t\tnc == 1 ? Scalar(200,200,200) : colors[i], \n\t\t\t\t1, 8, 0\n\t\t\t);\n\t\t}\n\n\t\timshow(nc == 1 ? \"value\" : wname[i], canvas[i]);\n\t}\n}<|endoftext|>"}
{"text":"#include\nusing namespace std;\nint main()\n{\n\tcout << \"Hello World\\n\";\n\treturn 0;\n}\nDelete test.cpp<|endoftext|>"}
{"text":"#include\"proj1.h\"\r\n#include\"test.h\"\r\nusing namespace std;\r\n\/\/checking input data\r\nbool is_int(string input) \/\/is integral\r\n{\r\n    int len=input.length();\r\n\tif(input[0]!='-'&&(input[0]<'0'||input[0]>'9'))\r\n\t\treturn false;\r\n    for(int i=1;i'9')\r\n            return false;\r\n    }\r\n    return true;\r\n}\r\nvoid help()\r\n{\r\n\tcout<<\"avaible commands: addition subtraction increase decrease derivative help root end\"<>p1>>p2;\r\n\tstring input;\r\n\tdo\r\n\t{ \r\n\t\tcin>>input;\r\n\t\tcout<Delete test.cpp<|endoftext|>"}
{"text":"\/\/ \r\n\/\/ (C) Jan de Vaan 2007-2009, all rights reserved. See the accompanying \"License.txt\" for licensed use. \r\n\/\/ \r\n\r\n#include \"stdafx.h\"\r\n#include \"stdio.h\"\r\n#include \r\n#include \r\n\r\n#include \"header.h\"\r\n#include \"streams.h\"\r\n#include \"defaulttraits.h\"\r\n#include \"losslesstraits.h\"\r\n#include \r\n#include \"interface.h\"\r\n\r\n#pragma warning (disable: 4996)\r\n\r\n\r\ndouble getTime() \r\n{ \r\n\tLARGE_INTEGER time;\r\n\t::QueryPerformanceCounter(&time);\r\n\tLARGE_INTEGER freq;\r\n\t::QueryPerformanceFrequency(&freq);\r\n\r\n\treturn double(time.LowPart) * 1000.0\/double(freq.LowPart);\r\n}\r\n\r\nint ReadJLSHeader(void* pdata, ScanInfo* pmetadata, int cbyte)\r\n{\r\n\tJLSInputStream reader((BYTE*)pdata, cbyte);\r\n\treader.ReadHeader();\t\r\n\t*pmetadata = reader.GetMetadata();\r\n\treturn reader.GetBytesRead();\r\n}\r\n\r\n\r\n\r\nint Decode(void* pvoid, int cbyte, const BYTE* pbytecompressed, int cbytecompr, const void* pbyteExpected = NULL)\r\n{\r\n\tJLSInputStream reader(pbytecompressed, cbytecompr);\r\n\r\n\tif (pbyteExpected != NULL)\r\n\t{\r\n\t\t::memcpy(pvoid, pbyteExpected, cbyte);\r\n\t\treader.EnableCompare(true);\r\n\t}\r\n\r\n\tif (!reader.Read(pvoid))\r\n\t\treturn -1;\r\n\r\n\treturn reader.GetBytesRead();\r\n\r\n}\r\n\r\n\r\nint Encode(const void* pbyte, Size size, int cbit, int ccomp, interleavemode ilv, BYTE* pbytecompressed, int cbytecompr, int nearval, const void* pbyteExpected = NULL)\r\n{\r\n\tJLSOutputStream stream;\r\n\tstream.Init(size, cbit, ccomp);\r\n\t\r\n\tif (ilv == ILV_NONE)\r\n\t{\r\n\t\tint cbytePlane = size.cx*size.cy*((cbit +7)\/8);\r\n\t\tfor (int icomp = 0; icomp < ccomp; ++icomp)\r\n\t\t{\r\n\t\t\tconst BYTE* pbyteComp = static_cast(pbyte) + icomp*cbytePlane;\r\n\t\t\tstream.AddScan(pbyteComp, size, cbit, 1, ILV_NONE, nearval);\r\n\t\t}\r\n\t}\r\n\telse \r\n\t{\r\n\t\tstream.AddScan(pbyte, size, cbit, ccomp, ilv, nearval);\r\n\t}\r\n\r\n\tstream.Write(pbytecompressed, cbytecompr, pbyteExpected);\r\n\t\r\n\treturn stream.GetBytesWritten();\t\r\n}\r\n\r\n\r\n\r\n\r\n\/\/ int double SZC int* void*\r\ntypedef const char* SZC;\r\n\r\ntemplate \r\nstruct validprintfchar;\r\n\r\n\r\n\r\nvoid WriteFile(SZC szcName, void* pvoidData, int cbyte)\r\n{\r\n\tFILE* pfile = fopen(szcName, \"wb\");\r\n\tfwrite(pvoidData, 1, cbyte, pfile);\r\n\tfclose(pfile);\t\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid ReadFile(SZC strName, std::vector* pvec, int ioffs = 0)\r\n{\r\n\tFILE* pfile = fopen(strName, \"rb\");\r\n\tfseek(pfile, 0, SEEK_END);\t\r\n\tint cbyteFile = ftell(pfile);\r\n\tfseek(pfile, ioffs, SEEK_SET);\t\r\n\tpvec->resize(cbyteFile-ioffs);\r\n\tfread(&(*pvec)[0],1, pvec->size(), pfile);\r\n\tfclose(pfile);\r\n\t\r\n}\r\n\r\nvoid SwapBytes(std::vector* rgbyte)\r\n{\r\n\t for (UINT i = 0; i < rgbyte->size(); i += 2)\r\n\t {\r\n\t\t std::swap((*rgbyte)[i], (*rgbyte)[i + 1]);\r\n\t }\r\n}\r\n\r\n\r\nvoid Test(const char* strName, const BYTE* rgbyteRaw, Size size, int cbit, int ccomp)\r\n{\t\r\n\tstd::vector pbyteCompressed;\r\n\tpbyteCompressed.resize(size.cx *size.cy * 4);\r\n\t\r\n\tstd::vector rgbyteOut;\r\n\trgbyteOut.resize(size.cx * size.cy * ((cbit + 7) \/ 8) * ccomp);\r\n\t\r\n\tdouble dblstart = getTime();\r\n\t\r\n\tsize_t cbyteCompressed = Encode(rgbyteRaw, size, cbit, ccomp, ccomp == 3 ? ILV_SAMPLE : ILV_NONE, &pbyteCompressed[0], int(pbyteCompressed.size()), 0);\r\n\r\n\t\/\/CString strDst = strName;\r\n\t\/\/strDst = strDst + \".jls\";\r\n\t\/\/WriteFile(strDst.GetString(), &pbyteCompressed[0], cbyteCompressed);\r\n\r\n\tdouble dwtimeEncodeComplete = getTime();\r\n\t\r\n\tdouble dblfactor = 1.0 *  rgbyteOut.size() \/ cbyteCompressed;\r\n\tprintf(\"Encode: %f Ratio: %f \\n\\r\", dwtimeEncodeComplete - dblstart, dblfactor);\r\n\t\r\n\tDecode(&rgbyteOut[0], rgbyteOut.size(), &pbyteCompressed[0], int(cbyteCompressed));\r\n\t\r\n\tdouble dwtimeDecodeComplete = getTime();\r\n\tstd::cout << \"RoundTrip test for: \" << strName << \"\\n\\r\";\r\n\tprintf(\"Encode: %f Decode: %f Ratio: %f \\n\\r\", dwtimeEncodeComplete - dblstart, dwtimeDecodeComplete - dwtimeEncodeComplete, dblfactor);\r\n\r\n\tBYTE* pbyteOut = &rgbyteOut[0];\r\n\tfor (UINT i = 0; i < rgbyteOut.size(); ++i)\r\n\t{\r\n\t\tif (rgbyteRaw[i] != pbyteOut[i])\r\n\t\t{\r\n\t\t\tASSERT(false);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\t\t\t\t\t\t    \r\n\r\n}\r\n\r\n\r\n\r\nvoid TestJls(std::vector& rgbyteRaw, Size size, int cbit, int ccomp, interleavemode ilv, const BYTE* rgbyteFile, int cbyteCompressed, bool bNear)\r\n{\r\n\tif (cbit > 8 && cbit <= 16)\r\n\t{\r\n\t\tSwapBytes(&rgbyteRaw);\r\n\t}\r\n\r\n\t\r\n\tstd::vector rgbyteTest;\r\n\trgbyteTest.resize(2 *cbyteCompressed );\r\n\t\r\n\tUINT cbyte = Encode(&rgbyteRaw[0], size, cbit, ccomp, ilv, &rgbyteTest[0], int(rgbyteTest.size()), bNear ? 3 : 0, rgbyteFile);\r\n\r\n\tWriteFile(\"test.jls\", &rgbyteTest[0], cbyte);\r\n\r\n\tJLSInputStream reader(rgbyteFile, cbyteCompressed);\r\n\t\r\n\r\n\tstd::vector rgbyteUnc;\r\n\trgbyteUnc.resize(size.cx * size.cy * ((cbit + 7) \/ 8) * ccomp);\r\n\r\n\tDecode(&rgbyteUnc[0], rgbyteUnc.size(), rgbyteFile, cbyteCompressed, &rgbyteRaw[0]);\r\n\t\r\n\tWriteFile(\"test.raw\", &rgbyteUnc[0], rgbyteUnc.size());\r\n}\r\n\r\n\r\nvoid TestNear(char* strNameEncoded, Size size, int cbit)\r\n{\r\n\tstd::vector rgbyteFile;\r\n\tReadFile(strNameEncoded, &rgbyteFile);\r\n\r\n\tstd::vector rgbyteUnc;\r\n\trgbyteUnc.resize(size.cx * size.cy * ((cbit + 7) \/ 8));\r\n\r\n\tDecode(&rgbyteUnc[0], rgbyteUnc.size(), &rgbyteFile[0], rgbyteFile.size());\r\n}\r\n\r\n\r\nvoid Triplet2Planar(std::vector& rgbyte, Size size)\r\n{\r\n\tstd::vector rgbytePlanar(rgbyte.size());\r\n\t\r\n\tint cbytePlane = size.cx * size.cy;\r\n\tfor (int ipixel = 0; ipixel < cbytePlane; ipixel++)\r\n\t{\r\n\t\trgbytePlanar[ipixel]\t\t\t\t= rgbyte[ipixel * 3 + 0];\r\n\t\trgbytePlanar[ipixel + 1*cbytePlane]\t= rgbyte[ipixel * 3 + 1];\r\n\t\trgbytePlanar[ipixel + 2*cbytePlane] = rgbyte[ipixel * 3 + 2];\r\n\t}\r\n\tstd::swap(rgbyte, rgbytePlanar);\r\n}\r\n\r\n\r\nvoid DecompressFile(SZC strNameEncoded, SZC strNameRaw, int ioffs)\r\n{\r\n\tstd::cout << \"Conformance test:\" << strNameEncoded << \"\\n\\r\";\r\n\tstd::vector rgbyteFile;\r\n\tReadFile(strNameEncoded, &rgbyteFile);\r\n\r\n \tstd::vector rgbyteRaw;\r\n\tReadFile(strNameRaw, &rgbyteRaw, ioffs);\r\n\r\n\tJlsParamaters metadata;\r\n\tif (JpegLsReadHeader(&rgbyteFile[0], rgbyteFile.size(), &metadata) != OK)\r\n\t{\r\n\t\tASSERT(false);\r\n\t\treturn;\r\n\t}\r\n\r\n\tSize size = Size(metadata.width, metadata.height);\r\n\r\n\tif (metadata.ilv == ILV_NONE && metadata.components == 3)\r\n\t{\r\n\t\tTriplet2Planar(rgbyteRaw, Size(metadata.width, metadata.height));\r\n\t}\r\n\r\n\tTestJls(rgbyteRaw, size, metadata.bitspersample, metadata.components, metadata.ilv, &rgbyteFile[0], rgbyteFile.size(), metadata.allowedlossyerror != 0);\r\n}\r\n\r\n\r\nvoid TestFile(SZC strName, int ioffs, Size size2, int cbit, int ccomp)\r\n{\r\n\tstd::vector rgbyteNoise;\r\n\t\r\n\tReadFile(strName, &rgbyteNoise, ioffs);\r\n\r\n\tTest(strName, &rgbyteNoise[0], size2, cbit, ccomp);\r\n\r\n};\r\n\r\n\tconst BYTE rgbyte[] = { 0,   0,  90,  74, \r\n\t\t\t\t\t\t\t68,  50,  43, 205, \r\n\t\t\t\t\t\t\t64, 145, 145, 145, \r\n\t\t\t\t\t\t\t100, 145, 145, 145};\r\n\tconst BYTE rgbyteComp[] =   {\t0xFF, 0xD8, 0xFF, 0xF7, 0x00, 0x0B, 0x08, 0x00, 0x04, 0x00, 0x04, 0x01, 0x01, 0x11, 0x00, 0xFF, 0xDA, 0x00, 0x08, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, \r\n\t\t\t\t\t\t\t0xC0, 0x00, 0x00, 0x6C, 0x80, 0x20, 0x8E,\r\n\t\t\t\t\t\t\t0x01, 0xC0, 0x00, 0x00, 0x57, 0x40, 0x00, 0x00, 0x6E, 0xE6, 0x00, 0x00, 0x01, 0xBC, 0x18, 0x00,\r\n\t\t\t\t\t\t\t0x00, 0x05, 0xD8, 0x00, 0x00, 0x91, 0x60, 0xFF, 0xD9};\r\n\r\n\r\n\r\nvoid TestAnnexH3()\r\n{\r\n\tSize size = Size(4,4);\t\r\n\tstd::vector vecRaw(16);\r\n\tmemcpy(&vecRaw[0], rgbyte, 16);\r\n\tTestJls(vecRaw, size, 8, 1, ILV_NONE, rgbyteComp, sizeof(rgbyteComp), false);\r\n}\r\n\r\nvoid TestConformanceLosslessMode()\r\n{\r\n\/\/\tDecompressFile(\"..\\\\test\\\\mars\\\\phoenixmars.jls\", \"..\\\\test\\\\mars\\\\phoenixmars.ppm\",40);\r\n\r\n\t\/\/ Test 1\r\n\tDecompressFile(\"..\\\\test\\\\conformance\\\\t8c0e0.jls\", \"..\\\\test\\\\conformance\\\\test8.ppm\",15);\r\n\r\n\t\/\/ Test 2\r\n\r\n\r\n\t\/\/ Test 3\r\n\tDecompressFile(\"..\\\\test\\\\conformance\\\\t8c2e0.jls\", \"..\\\\test\\\\conformance\\\\test8.ppm\", 15);\r\n\r\n\t\/\/ Test 4\r\n\tDecompressFile(\"..\\\\test\\\\conformance\\\\t8c0e3.jls\", \"..\\\\test\\\\conformance\\\\test8.ppm\",15);\r\n\r\n\t\/\/ Test 5\r\n\r\n\r\n\t\/\/ Test 6\r\n\tDecompressFile(\"..\\\\test\\\\conformance\\\\t8c2e3.jls\", \"..\\\\test\\\\conformance\\\\test8.ppm\",15);\r\n\r\n\t\/\/ Test 7\r\n\t\/\/ Test 8\r\n\r\n\t\/\/ Test 9\r\n\tDecompressFile(\"..\\\\test\\\\conformance\\\\t8nde0.jls\", \"..\\\\test\\\\conformance\\\\test8bs2.pgm\",15);\t\r\n\r\n\t\/\/ Test 10\r\n\tDecompressFile(\"..\\\\test\\\\conformance\\\\t8nde3.jls\", \"..\\\\test\\\\conformance\\\\test8bs2.pgm\",15);\t\r\n\r\n\t\/\/ Test 11\r\n\tDecompressFile(\"..\\\\test\\\\conformance\\\\t16e0.jls\", \"..\\\\test\\\\conformance\\\\test16.pgm\",16);\r\n\t\r\n\t\/\/ Test 12\r\n\tDecompressFile(\"..\\\\test\\\\conformance\\\\t16e3.jls\", \"..\\\\test\\\\conformance\\\\test16.pgm\",16);\r\n\r\n\t\r\n\r\n\t\/\/ additional, Lena compressed with other codec (UBC?), vfy with CharLS\r\n\tDecompressFile(\"..\\\\test\\\\lena8b.jls\", \"..\\\\test\\\\lena8b.raw\",0);\r\n\r\n\r\n\r\n}\r\n\r\n\r\n\r\nvoid TestNoiseImage()\r\n{\r\n\tsrand(21344); \r\n\tSize size2 = Size(1024, 1024);\r\n\tstd::vector rgbyteNoise;\r\n\trgbyteNoise.resize(\tsize2.cx * size2.cy);\r\n\r\n\tfor (int iline = 0; iline traits1 = DefaultTraitsT(4095,0);\r\n\tLosslessTraitsT traits2 = LosslessTraitsT();\r\n\r\n\tASSERT(traits1.LIMIT == traits2.LIMIT);\r\n\tASSERT(traits1.MAXVAL == traits2.MAXVAL);\r\n\tASSERT(traits1.RESET == traits2.RESET);\r\n\tASSERT(traits1.bpp == traits2.bpp);\r\n\tASSERT(traits1.qbpp == traits2.qbpp);\r\n\r\n\tfor (int i = -4096; i < 4096; ++i)\r\n\t{\r\n\t\tASSERT(traits1.ModRange(i) == traits2.ModRange(i));\r\n\t\tASSERT(traits1.ComputeErrVal(i) == traits2.ComputeErrVal(i));\r\n\t}\r\n\r\n\tfor (int i = -8095; i < 8095; ++i)\r\n\t{\r\n\t\tASSERT(traits1.CorrectPrediction(i) == traits2.CorrectPrediction(i));\r\n\t\tASSERT(traits1.IsNear(i,2) == traits2.IsNear(i,2));\t\r\n\t}\t\r\n}\r\n\r\nvoid TestTraits8bit()\r\n{\r\n\tDefaultTraitsT traits1 = DefaultTraitsT(255,0);\r\n\tLosslessTraitsT traits2 = LosslessTraitsT();\r\n\r\n\tASSERT(traits1.LIMIT == traits2.LIMIT);\r\n\tASSERT(traits1.MAXVAL == traits2.MAXVAL);\r\n\tASSERT(traits1.RESET == traits2.RESET);\r\n\tASSERT(traits1.bpp == traits2.bpp);\r\n\tASSERT(traits1.qbpp == traits2.qbpp);\t\r\n\r\n\tfor (int i = -255; i < 255; ++i)\r\n\t{\r\n\t\tASSERT(traits1.ModRange(i) == traits2.ModRange(i));\r\n\t\tASSERT(traits1.ComputeErrVal(i) == traits2.ComputeErrVal(i));\r\n\t}\r\n\r\n\tfor (int i = -255; i < 512; ++i)\r\n\t{\r\n\t\tASSERT(traits1.CorrectPrediction(i) == traits2.CorrectPrediction(i));\r\n\t\tASSERT(traits1.IsNear(i,2) == traits2.IsNear(i,2));\t\r\n\t}\r\n}\r\n\r\n\r\nextern \"C\"\r\n{\r\n\r\nvoid __declspec(dllexport) __cdecl Test()\r\n{\r\n\tTestTraits16bit();\t\t\r\n\tTestTraits8bit();\t\t\r\n\tTestConformanceLosslessMode();\t\r\n\tTestPerformance();\r\n\tTestNoiseImage();\r\n\tTestAnnexH3();\t\t\r\n\t\r\n}\r\n\r\n\r\n\r\n}moved unit tests<|endoftext|>"}
{"text":"#include \"Entity.h\"\n\n\n\nEntity::Entity()\n{\n}\n\n\nEntity::~Entity()\n{\n}\n\nint Entity::SyncComponents()\n{\n\tint result = 1;\n\n\tif (this->m_pComp != nullptr)\n\t{\n\t\tif (this->m_aiComp != nullptr)\n\t\t{\n\t\t\t\/\/ Works for now since we're only handling platforms\n\t\t\tif (this->m_aiComp->AC_triggered)\n\t\t\t\tthis->m_pComp->PC_velocity = DirectX::XMVectorScale(this->m_aiComp->AC_dir, this->m_aiComp->AC_speed);\n\t\t\telse\n\t\t\t\tthis->m_pComp->PC_velocity = { 0 };\n\t\t\tthis->m_aiComp->AC_position = this->m_pComp->PC_pos;\n\t\t\t\/\/TODO: test physcomp vs aicomp positions are still updated after they are released from duty\n\t\t}\n\t\tif (this->m_gComp != nullptr)\n\t\t{\n\t\t\t\/\/rotate and translate the obb in the game\n\t\t\tif (this->m_pComp->PC_BVtype == BV_OBB)\n\t\t\t{\n\t\t\t\tif (this->m_entityID == 1 || this->m_entityID == 2) \/\/ 1 or 2 == player\n\t\t\t\t{\n\t\t\t\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));\n\t\t\t\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_gComp->worldMatrix, DirectX::XMMatrixTranslationFromVector(DirectX::XMVectorSet(0, -this->m_pComp->PC_OBB.ext[1], 0, 0)));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));\n\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(DirectX::XMMatrixRotationRollPitchYawFromVector(this->m_pComp->PC_rotation), DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));\n\t\t\t}\n\n\t\t\tresult = 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tresult = -2;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (this->m_gComp == nullptr)\n\t\t{\n\t\t\tresult = -3;\n\t\t}\n\t\tresult = -1;\n\t}\n\n\treturn result;\n}\n\nint Entity::AddObserver(Observer * observer, int entityID)\n{\n\tthis->m_subject.AddObserver(observer, entityID);\n\n\treturn 0;\n}\n\nvoid Entity::UnsafeSyncComponents()\n{\n\t\/\/rotate and translate the obb in the game\n\tif (this->m_pComp->PC_BVtype == BV_OBB)\n\t{\n\t\t\/\/this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(DirectX::XMMatrixRotationQuaternion(this->m_pComp->PC_OBB.quat), DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));\n\t\tif (this->m_entityID == 1 || this->m_entityID == 2) \/\/ 1 or 2 == player\n\t\t{\n\t\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));\n\t\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_gComp->worldMatrix, DirectX::XMMatrixTranslationFromVector(DirectX::XMVectorSet(0, -this->m_pComp->PC_OBB.ext[1], 0, 0)));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));\n\n\t\t}\n\t}\n\telse\n\t{\n\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(DirectX::XMMatrixRotationRollPitchYawFromVector(this->m_pComp->PC_rotation), DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));\n\t}\n}\n\nPhysicsComponent* Entity::SetPhysicsComponent(PhysicsComponent * pComp)\n{\n\tPhysicsComponent* tempReturn = this->m_pComp;\n\tthis->m_pComp = pComp;\n\treturn tempReturn;\n}\n\nGraphicsComponent* Entity::SetGraphicsComponent(GraphicsComponent * gComp)\n{\n\tGraphicsComponent* tempReturn = this->m_gComp;\n\tthis->m_gComp = gComp;\n\treturn tempReturn;\n}\n\nAIComponent * Entity::SetAIComponent(AIComponent * aiComp)\n{\n\tAIComponent* tempReturn = this->m_aiComp;\n\tthis->m_aiComp = aiComp;\n\treturn tempReturn;\n}\n\nAnimationComponent * Entity::SetAnimationComponent(AnimationComponent * aComp)\n{\n\tAnimationComponent* tempReturn = this->m_aComp;\n\tthis->m_aComp = aComp;\n\treturn tempReturn;\n}\n\nbool Entity::SetGrabbed(Entity* isGrabbedBy)\n{\n\tbool lastValue = this->m_isGrabbed;;\n\tthis->m_isGrabbedBy = isGrabbedBy;\n\t\n\tif (this->m_isGrabbedBy != nullptr)\n\t{\n\t\tthis->m_isGrabbed = true;\n\t\tthis->m_pComp->PC_velocity = DirectX::XMVectorSet(0, 0, 0, 0);\n\n\t}\n\telse {\n\t\tif (this->m_entityID == 3)\n\t\t{\n\t\t\tint a = 0;\n\t\t}\n\t\tthis->m_isGrabbed = false;\n\t\t\/\/this->m_pComp->PC_velocity = DirectX::XMVectorSet(0, 0, 0, 0);\n\t}\n\t\n\treturn lastValue;\n}\n\nbool Entity::IsGrabbed()\n{\n\treturn this->m_isGrabbed;\n}\n\nint Entity::SetEntityID(int entityID)\n{\n\tint lastValue = this->m_entityID;\n\tthis->m_entityID = entityID;\n\treturn lastValue;\n}\n\nPhysicsComponent * Entity::GetPhysicsComponent()\n{\n\treturn this->m_pComp;\n}\n\nGraphicsComponent * Entity::GetGraphicComponent()\n{\n\treturn this->m_gComp;\n}\n\nAIComponent * Entity::GetAIComponent()\n{\n\treturn this->m_aiComp;\n}\n\nAnimationComponent * Entity::GetAnimationComponent()\n{\n\treturn this->m_aComp;\n}\n\nbool Entity::GetGrabbed()\n{\n\treturn this->m_isGrabbed;\n}\n\nint Entity::GetEntityID()\n{\n\treturn this->m_entityID;\n}\n\nint Entity::InitializeBase(int entityID, PhysicsComponent* pComp, GraphicsComponent* gComp, AnimationComponent* aComp, AIComponent* aiComp)\n{\n\tint result = 1;\n\tthis->m_isGrabbed = false;\n\tthis->m_subject = Subject();\n\tthis->m_entityID = entityID;\n\tthis->m_pComp = pComp;\n\tthis->m_gComp = gComp;\n\tthis->m_aComp = aComp;\n\tthis->m_aiComp = aiComp;\n\tthis->m_isGrabbedBy = nullptr;\n\treturn result;\n}\nREMOVE test code and unnecessary spacing#include \"Entity.h\"\n\nEntity::Entity(){}\nEntity::~Entity(){}\n\nint Entity::SyncComponents()\n{\n\tint result = 1;\n\tif (this->m_pComp != nullptr)\n\t{\n\t\tif (this->m_aiComp != nullptr)\n\t\t{\n\t\t\t\/\/ Works for now since we're only handling platforms\n\t\t\tif (this->m_aiComp->AC_triggered)\n\t\t\t\tthis->m_pComp->PC_velocity = DirectX::XMVectorScale(this->m_aiComp->AC_dir, this->m_aiComp->AC_speed);\n\t\t\telse\n\t\t\t\tthis->m_pComp->PC_velocity = { 0 };\n\t\t\tthis->m_aiComp->AC_position = this->m_pComp->PC_pos;\n\t\t\t\/\/TODO: test physcomp vs aicomp positions are still updated after they are released from duty\n\t\t}\n\t\tif (this->m_gComp != nullptr)\n\t\t{\n\t\t\t\/\/rotate and translate the obb in the game\n\t\t\tif (this->m_pComp->PC_BVtype == BV_OBB)\n\t\t\t{\n\t\t\t\tif (this->m_entityID == 1 || this->m_entityID == 2) \/\/ 1 or 2 == player\n\t\t\t\t{\n\t\t\t\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));\n\t\t\t\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_gComp->worldMatrix, DirectX::XMMatrixTranslationFromVector(DirectX::XMVectorSet(0, -this->m_pComp->PC_OBB.ext[1], 0, 0)));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(DirectX::XMMatrixRotationRollPitchYawFromVector(this->m_pComp->PC_rotation), DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));\n\t\t\t}\n\n\t\t\tresult = 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tresult = -2;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (this->m_gComp == nullptr)\n\t\t{\n\t\t\tresult = -3;\n\t\t}\n\t\tresult = -1;\n\t}\n\treturn result;\n}\n\nint Entity::AddObserver(Observer * observer, int entityID)\n{\n\tthis->m_subject.AddObserver(observer, entityID);\n\treturn 1;\n}\n\nvoid Entity::UnsafeSyncComponents()\n{\n\t\/\/rotate and translate the obb in the game\n\tif (this->m_pComp->PC_BVtype == BV_OBB)\n\t{\n\t\tif (this->m_entityID == 1 || this->m_entityID == 2) \/\/ 1 or 2 == player\n\t\t{\n\t\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));\n\t\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_gComp->worldMatrix, DirectX::XMMatrixTranslationFromVector(DirectX::XMVectorSet(0, -this->m_pComp->PC_OBB.ext[1], 0, 0)));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));\n\t\t}\n\t}\n\telse\n\t{\n\t\tthis->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(DirectX::XMMatrixRotationRollPitchYawFromVector(this->m_pComp->PC_rotation), DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));\n\t}\n}\n\nPhysicsComponent* Entity::SetPhysicsComponent(PhysicsComponent * pComp)\n{\n\tPhysicsComponent* tempReturn = this->m_pComp;\n\tthis->m_pComp = pComp;\n\treturn tempReturn;\n}\n\nGraphicsComponent* Entity::SetGraphicsComponent(GraphicsComponent * gComp)\n{\n\tGraphicsComponent* tempReturn = this->m_gComp;\n\tthis->m_gComp = gComp;\n\treturn tempReturn;\n}\n\nAIComponent * Entity::SetAIComponent(AIComponent * aiComp)\n{\n\tAIComponent* tempReturn = this->m_aiComp;\n\tthis->m_aiComp = aiComp;\n\treturn tempReturn;\n}\n\nAnimationComponent * Entity::SetAnimationComponent(AnimationComponent * aComp)\n{\n\tAnimationComponent* tempReturn = this->m_aComp;\n\tthis->m_aComp = aComp;\n\treturn tempReturn;\n}\n\nbool Entity::SetGrabbed(Entity* isGrabbedBy)\n{\n\tbool lastValue = this->m_isGrabbed;;\n\tthis->m_isGrabbedBy = isGrabbedBy;\n\t\n\tif (this->m_isGrabbedBy != nullptr)\n\t{\n\t\tthis->m_isGrabbed = true;\n\t\tthis->m_pComp->PC_velocity = DirectX::XMVectorSet(0, 0, 0, 0);\n\t}\n\telse \n\t{\n\t\tthis->m_isGrabbed = false;\n\t}\n\treturn lastValue;\n}\n\nbool Entity::IsGrabbed()\n{\n\treturn this->m_isGrabbed;\n}\n\nint Entity::SetEntityID(int entityID)\n{\n\tint lastValue = this->m_entityID;\n\tthis->m_entityID = entityID;\n\treturn lastValue;\n}\n\nPhysicsComponent * Entity::GetPhysicsComponent()\n{\n\treturn this->m_pComp;\n}\n\nGraphicsComponent * Entity::GetGraphicComponent()\n{\n\treturn this->m_gComp;\n}\n\nAIComponent * Entity::GetAIComponent()\n{\n\treturn this->m_aiComp;\n}\n\nAnimationComponent * Entity::GetAnimationComponent()\n{\n\treturn this->m_aComp;\n}\n\nbool Entity::GetGrabbed()\n{\n\treturn this->m_isGrabbed;\n}\n\nint Entity::GetEntityID()\n{\n\treturn this->m_entityID;\n}\n\nint Entity::InitializeBase(int entityID, PhysicsComponent* pComp, GraphicsComponent* gComp, AnimationComponent* aComp, AIComponent* aiComp)\n{\n\tint result = 1;\n\tthis->m_isGrabbed = false;\n\tthis->m_subject = Subject();\n\tthis->m_entityID = entityID;\n\tthis->m_pComp = pComp;\n\tthis->m_gComp = gComp;\n\tthis->m_aComp = aComp;\n\tthis->m_aiComp = aiComp;\n\tthis->m_isGrabbedBy = nullptr;\n\treturn result;\n}\n<|endoftext|>"}
{"text":"#include \"codeGenVisitor.h\"\n\nvoid CodeGenVisitor::populateSwitchMap() {\n\tswitchMap.insert(std::make_pair(\"+\", BOP_PLUS));\n\tswitchMap.insert(std::make_pair(\"-\", BOP_MINUS));\n\tswitchMap.insert(std::make_pair(\"*\", BOP_MULT));\n\tswitchMap.insert(std::make_pair(\"\/\", BOP_DIV));\n\tswitchMap.insert(std::make_pair(\">=\", BOP_GTE));\n\tswitchMap.insert(std::make_pair(\"<=\", BOP_LTE));\n\tswitchMap.insert(std::make_pair(\">\", BOP_GT));\n\tswitchMap.insert(std::make_pair(\"<\", BOP_LT));\n\tswitchMap.insert(std::make_pair(\"!=\", BOP_NEQ));\n\tswitchMap.insert(std::make_pair(\"==\", BOP_EQ));\n\tswitchMap.insert(std::make_pair(\".\", BOP_DOT));\n} \n\nllvm::Value* CodeGenVisitor::ErrorV(const char* str) {\n  fprintf(stderr, \"Error: %s\\n\", str);\n  return nullptr;\n}\n\nllvm::Function* CodeGenVisitor::generateFunction(FunctionDefinition* f) {\n\tstd::string type = f->type->name;\n\tllvm::FunctionType* funcType = nullptr;\n\tllvm::Function* func = nullptr;\n\tstd::vector inputArgs;\n\tfor(size_t i = 0, end = f->args->size(); i < end; ++i) {\n\t\tstd::string type = f->args[i][0]->type->name;\n\t\tif(type == \"float\") {\n\t\t\tinputArgs.push_back(llvm::Type::getDoubleTy(*context));\n\t\t}\n\t\telse if(type == \"int\") {\n\t\t\tinputArgs.push_back(llvm::Type::getInt64Ty(*context));\n\t\t}\n\t\telse\n\t\t\treturn nullptr;\n\t}\n\tif(type == \"void\") {\n\t\tfuncType = llvm::FunctionType::get(llvm::Type::getVoidTy(*context), inputArgs, false); \/\/return is float\n\t}\n\telse if(type == \"float\") {\n\t\tfuncType = llvm::FunctionType::get(llvm::Type::getDoubleTy(*context), inputArgs, false); \/\/return is float\n\t}\n\telse if(type == \"int\") {\n\t\tfuncType = llvm::FunctionType::get(llvm::Type::getInt64Ty(*context), inputArgs, false); \/\/return is float\n\t}\n\tfunc = llvm::Function::Create(funcType, llvm::Function::ExternalLinkage, f->ident->name, theModule.get()); \/\/pass unique ptr to function\n\tunsigned i = 0;\n\tfor (auto &arg : func->args())\n\t  arg.setName(f->args[i++][0]->ident->name);\n\treturn func;\n}\n\nCodeGenVisitor::CodeGenVisitor(std::string name) {\n\tpopulateSwitchMap();\n\tcontext = &llvm::getGlobalContext();\n\ttheModule = llvm::make_unique(name, *context);\n\tbuilder = llvm::make_unique>(*context);\n}\n\n\/*===================================Node===================================*\/\nllvm::Value* CodeGenVisitor::visitNode(Node* n) {\n\treturn ErrorV(\"Attempt to generate code for generic Node\");\n}\n\n\/*================================Expression================================*\/\nllvm::Value* CodeGenVisitor::visitExpression(Expression* e) {\n\treturn ErrorV(\"Attempt to generate code for generic Expression\");\n}\n\n\/*================================Statement=================================*\/\nllvm::Value* CodeGenVisitor::visitStatement(Statement* s) {\n\treturn ErrorV(\"Attempt to generate code for generic Statement\");\n}\n\n\/*=================================Integer==================================*\/\nllvm::Value* CodeGenVisitor::visitInteger(Integer* i) {\n\treturn llvm::ConstantInt::get(*context, llvm::APInt(i->value, 64));\n}\n\n\/*==================================Float===================================*\/\nllvm::Value* CodeGenVisitor::visitFloat(Float* f) {\n\treturn llvm::ConstantFP::get(*context, llvm::APFloat(f->value));\n}\n\n\/*================================Identifier================================*\/\nllvm::Value* CodeGenVisitor::visitIdentifier(Identifier* i) {\n  llvm::Value* val = namedValues[i->name];\n  if (!val)\n    return ErrorV(\"Attempt to generate code for not previously defined variable\");\n  return val;\n}\n\n\/*=============================NullaryOperator==============================*\/\nllvm::Value* CodeGenVisitor::visitNullaryOperator(NullaryOperator* n) {\n\tif(*n->op == ';') {\n\t\t\/\/commit action\n\t\treturn nullptr;\n\t}\n\treturn ErrorV(\"Invalid nullary operator\");\n}\n\n\/*==============================UnaryOperator===============================*\/\nllvm::Value* CodeGenVisitor::visitUnaryOperator(UnaryOperator* u) {\n\tllvm::Value* expr = u->exp->acceptVisitor(this);\n\tswitch(*u->op) {\n\t\tcase '-':\n\t\treturn builder->CreateFMul(llvm::ConstantInt::get(*context, llvm::APInt(-1, 64)), expr, \"multmp\");\n\t\tcase '!':\n\t\tcase '*':\n\t\treturn ErrorV(\"Not yet specified unary operator\");\n\t\tdefault:\n\t\treturn ErrorV(\"Invalid unary operator\");\n\t}\n}\n\n\/*==============================BinaryOperator==============================*\/\nllvm::Value* CodeGenVisitor::visitBinaryOperator(BinaryOperator* b) {\n\tllvm::Value* left = b->left->acceptVisitor(this);\n \tllvm::Value* right = b->right->acceptVisitor(this);\n \t\/\/grab left and right\n\tif (!left || !right)\n\t\treturn ErrorV(\"Could not evaluate binary operator\");\n\t\/\/use map for binary operators\n\tswitch (switchMap.find(b->op)->second) {\n\t\tcase BOP_PLUS:\n\t\treturn builder->CreateFAdd(left, right, \"addtmp\");\n\t\tcase BOP_MINUS:\n\t\treturn builder->CreateFSub(left, right, \"subtmp\");\n\t\tcase BOP_MULT:\n\t\treturn builder->CreateFMul(left, right, \"multmp\");\n\t\tcase BOP_DIV:\n\t\treturn builder->CreateFDiv(left, right, \"divtmp\");\n\t\tcase BOP_NEQ:\n\t\tcase BOP_EQ:\n\t\tcase BOP_GTE:\n\t\tcase BOP_LTE:\n\t\tcase BOP_GT:\n\t\tcase BOP_LT:\n\t\tcase BOP_DOT:\n\t\treturn ErrorV(\"Attempt to generate code for not yet implemented binary operator\");\n\t\t\/\/assignment op separate\n\t\tdefault:\n\t\treturn ErrorV(\"Invalid binary operator\");\n\t}\n}\n\n\/*==================================Block===================================*\/\nllvm::Value* CodeGenVisitor::visitBlock(Block* b) {\n\tllvm::Value* lastVisited;\n\tstd::vector>* statements = b->statements;\n\tfor(size_t i = 0, end = statements->size(); i != end; ++i) {\n\t\tlastVisited = statements[i][0]->acceptVisitor(this);\n\t\t\/\/if(!lastVisited) \/\/TODO:nullary operator needs more explicit handling\n\t\t\/\/\treturn nullptr; \n\t}\n\treturn lastVisited;\n}\n\n\/*===============================FunctionCall===============================*\/\nllvm::Value* CodeGenVisitor::visitFunctionCall(FunctionCall* f) {\n\t\/\/grab function and evaluate with arguments\n\tllvm::Function* func = theModule->getFunction(f->ident->name);\n\tif(!func)\n\t\treturn ErrorV(\"Unknown function reference\");\n\tif(func->arg_size() != f->args->size())\n\t\treturn ErrorV(\"Wrong number of arguments passed\");\n\n\tstd::vector argVector;\n\tfor(size_t i = 0, end = f->args->size(); i != end; ++i) {\n\t\targVector.push_back(f->args[i][0]->acceptVisitor(this));\n\t\tif(!argVector.back())\n\t\t\treturn nullptr;\n\t}\n\treturn builder->CreateCall(func, argVector, \"calltmp\");\n}\n\n\/*=================================Keyword==================================*\/\nllvm::Value* CodeGenVisitor::visitKeyword(Keyword* k) {\n\treturn ErrorV(\"Attempt to generate code for dangling keyword\");\n}\n\n\/*============================VariableDefinition============================*\/\nllvm::Value* CodeGenVisitor::visitVariableDefinition(VariableDefinition* v) {\n\tstd::string type = v->type->name; \/\/int float or void\n\tllvm::Value* val = nullptr;\n\tif(type == \"int\") {\n\t\tint64_t i = 0; \/\/TODO: Figure out why variable necessary\n\t\tval = llvm::ConstantInt::get(*context, llvm::APInt(i, 64));\n\t}\n\telse if(type == \"float\")\n\t\tval = llvm::ConstantFP::get(*context, llvm::APFloat(0.0));\n\tif(!val) \/\/add default value variable to map\n\t\tnamedValues.insert(std::make_pair(v->ident->name, val));\n\treturn val;\n}\n\n\/*===========================StructureDefinition============================*\/\nllvm::Value* CodeGenVisitor::visitStructureDefinition(StructureDefinition* s) {\n\treturn ErrorV(\"Attempt to evaluate not yet implemented structure definition\");\n}\n\n\/*============================FunctionDefinition============================*\/\nllvm::Value* CodeGenVisitor::visitFunctionDefinition(FunctionDefinition* f) {\n\tllvm::Function* func = theModule->getFunction(f->ident->name);\n\tif(!func)\n\t\tfunc = generateFunction(f); \/\/create function object with type|ident|args\n\tif(!func) \/\/generateFunction returned nullptr\n\t\treturn nullptr;\n\tif(!func->empty())\n\t\treturn ErrorV(\"Function is already defined\");\n\tllvm::BasicBlock* block = llvm::BasicBlock::Create(*context, \"function start\", func);\n\tbuilder->SetInsertPoint(block);\n\tnamedValues.clear();\n\tfor (auto &arg : func->args())\n\t\tnamedValues[arg.getName()] = &arg;\n\tif(llvm::Value* retVal = f->block->acceptVisitor(this)) {\/\/TODO:nullptr return happens when using return;\n\t\tfunc->dump();\/\/Function IR dump\n\t\treturn retVal;\n\t}\n\tfunc->eraseFromParent();\/\/erase if nullptr returned\n\treturn nullptr; \n}\n\n\/*==========================StructureDeclaration============================*\/\nllvm::Value* CodeGenVisitor::visitStructureDeclaration(StructureDeclaration* s) {\n\treturn ErrorV(\"Attempt to evaluate not yet implemented structure declaration\");\n}\n\n\n\/*===========================ExpressionStatement============================*\/\nllvm::Value* CodeGenVisitor::visitExpressionStatement(ExpressionStatement* e) {\n\treturn e->exp->acceptVisitor(this);\t\/\/evaluated but value discarded\n}\n\n\/*=============================ReturnStatement==============================*\/\nllvm::Value* CodeGenVisitor::visitReturnStatement(ReturnStatement* r) {\n\tllvm::Value* returnVal = r->exp->acceptVisitor(this);\n\tif(returnVal) {\n\t\tbuilder->CreateRet(returnVal); \/\/builder returns value\n\t}\n\treturn returnVal;\n}\n\n\/*=============================AssignStatement==============================*\/\nllvm::Value* CodeGenVisitor::visitAssignStatement(AssignStatement* a) {\n\t\/\/TODO: map a value to an exisiting identifier\n\t\/\/look for identifier\n\t\/\/map target to value\n\treturn nullptr;\n}\n\n\/*===============================IfStatement================================*\/\nllvm::Value* CodeGenVisitor::visitIfStatement(IfStatement* i) {\n\treturn ErrorV(\"Attempt to evaluate not yet implemented if statement\");\n}\nAdded type checking for return types with erase parent functionality | fixed some coding issues#include \"codeGenVisitor.h\"\n\nvoid CodeGenVisitor::populateSwitchMap() {\n\tswitchMap.insert(std::make_pair(\"+\", BOP_PLUS));\n\tswitchMap.insert(std::make_pair(\"-\", BOP_MINUS));\n\tswitchMap.insert(std::make_pair(\"*\", BOP_MULT));\n\tswitchMap.insert(std::make_pair(\"\/\", BOP_DIV));\n\tswitchMap.insert(std::make_pair(\">=\", BOP_GTE));\n\tswitchMap.insert(std::make_pair(\"<=\", BOP_LTE));\n\tswitchMap.insert(std::make_pair(\">\", BOP_GT));\n\tswitchMap.insert(std::make_pair(\"<\", BOP_LT));\n\tswitchMap.insert(std::make_pair(\"!=\", BOP_NEQ));\n\tswitchMap.insert(std::make_pair(\"==\", BOP_EQ));\n\tswitchMap.insert(std::make_pair(\".\", BOP_DOT));\n} \n\nllvm::Value* CodeGenVisitor::ErrorV(const char* str) {\n  fprintf(stderr, \"Error: %s\\n\", str);\n  return nullptr;\n}\n\nllvm::Function* CodeGenVisitor::generateFunction(FunctionDefinition* f) {\n\tstd::string type = f->type->name;\n\tllvm::FunctionType* funcType = nullptr;\n\tllvm::Function* func = nullptr;\n\tstd::vector inputArgs; \/\/set input args as float or int\n\tfor(size_t i = 0, end = f->args->size(); i < end; ++i) {\n\t\tstd::string type = f->args[i][0]->type->name;\n\t\tif(type == \"float\") {\n\t\t\tinputArgs.push_back(llvm::Type::getDoubleTy(*context));\n\t\t}\n\t\telse if(type == \"int\") {\n\t\t\tinputArgs.push_back(llvm::Type::getInt64Ty(*context));\n\t\t}\n\t\telse\n\t\t\treturn nullptr;\n\t}\n\tif(type == \"void\") { \/\/set function return type\n\t\tfuncType = llvm::FunctionType::get(llvm::Type::getVoidTy(*context), inputArgs, false); \n\t}\n\telse if(type == \"float\") {\n\t\tfuncType = llvm::FunctionType::get(llvm::Type::getDoubleTy(*context), inputArgs, false);\n\t}\n\telse if(type == \"int\") {\n\t\tfuncType = llvm::FunctionType::get(llvm::Type::getInt64Ty(*context), inputArgs, false);\n\t}\n\tfunc = llvm::Function::Create(funcType, llvm::Function::ExternalLinkage, f->ident->name, theModule.get()); \/\/pass unique ptr to function\n\t{\n\tsize_t i = 0;\n\tfor (auto &arg : func->args())\n\t  arg.setName(f->args[i++][0]->ident->name);\n\t}\n\treturn func;\n}\n\nCodeGenVisitor::CodeGenVisitor(std::string name) {\n\tpopulateSwitchMap();\n\tcontext = &llvm::getGlobalContext();\n\ttheModule = llvm::make_unique(name, *context);\n\tbuilder = llvm::make_unique>(*context);\n}\n\n\/*===================================Node===================================*\/\nllvm::Value* CodeGenVisitor::visitNode(Node* n) {\n\treturn ErrorV(\"Attempt to generate code for generic Node\");\n}\n\n\/*================================Expression================================*\/\nllvm::Value* CodeGenVisitor::visitExpression(Expression* e) {\n\treturn ErrorV(\"Attempt to generate code for generic Expression\");\n}\n\n\/*================================Statement=================================*\/\nllvm::Value* CodeGenVisitor::visitStatement(Statement* s) {\n\treturn ErrorV(\"Attempt to generate code for generic Statement\");\n}\n\n\/*=================================Integer==================================*\/\nllvm::Value* CodeGenVisitor::visitInteger(Integer* i) {\n\treturn llvm::ConstantInt::get(*context, llvm::APInt(i->value, 64));\n}\n\n\/*==================================Float===================================*\/\nllvm::Value* CodeGenVisitor::visitFloat(Float* f) {\n\treturn llvm::ConstantFP::get(*context, llvm::APFloat(f->value));\n}\n\n\/*================================Identifier================================*\/\nllvm::Value* CodeGenVisitor::visitIdentifier(Identifier* i) {\n  llvm::Value* val = namedValues[i->name];\n  if (!val)\n    return ErrorV(\"Attempt to generate code for not previously defined variable\");\n  return val;\n}\n\n\/*=============================NullaryOperator==============================*\/\nllvm::Value* CodeGenVisitor::visitNullaryOperator(NullaryOperator* n) {\n\tif(*n->op == ';') {\n\t\t\/\/commit action\n\t\treturn nullptr;\n\t}\n\treturn ErrorV(\"Invalid nullary operator\");\n}\n\n\/*==============================UnaryOperator===============================*\/\nllvm::Value* CodeGenVisitor::visitUnaryOperator(UnaryOperator* u) {\n\tllvm::Value* expr = u->exp->acceptVisitor(this);\n\tswitch(*u->op) {\n\t\tcase '-':\n\t\treturn builder->CreateFMul(llvm::ConstantInt::get(*context, llvm::APInt(-1, 64)), expr, \"multmp\");\n\t\tcase '!':\n\t\tcase '*':\n\t\treturn ErrorV(\"Not yet specified unary operator\");\n\t\tdefault:\n\t\treturn ErrorV(\"Invalid unary operator\");\n\t}\n}\n\n\/*==============================BinaryOperator==============================*\/\nllvm::Value* CodeGenVisitor::visitBinaryOperator(BinaryOperator* b) {\n\tllvm::Value* left = b->left->acceptVisitor(this);\n \tllvm::Value* right = b->right->acceptVisitor(this);\n \t\/\/grab left and right\n\tif (!left || !right)\n\t\treturn ErrorV(\"Could not evaluate binary operator\");\n\t\/\/use map for binary operators\n\tswitch (switchMap.find(b->op)->second) {\n\t\tcase BOP_PLUS:\n\t\treturn builder->CreateFAdd(left, right, \"addtmp\");\n\t\tcase BOP_MINUS:\n\t\treturn builder->CreateFSub(left, right, \"subtmp\");\n\t\tcase BOP_MULT:\n\t\treturn builder->CreateFMul(left, right, \"multmp\");\n\t\tcase BOP_DIV:\n\t\treturn builder->CreateFDiv(left, right, \"divtmp\");\n\t\tcase BOP_NEQ:\n\t\tcase BOP_EQ:\n\t\tcase BOP_GTE:\n\t\tcase BOP_LTE:\n\t\tcase BOP_GT:\n\t\tcase BOP_LT:\n\t\tcase BOP_DOT:\n\t\treturn ErrorV(\"Attempt to generate code for not yet implemented binary operator\");\n\t\t\/\/assignment op separate\n\t\tdefault:\n\t\treturn ErrorV(\"Invalid binary operator\");\n\t}\n}\n\n\/*==================================Block===================================*\/\nllvm::Value* CodeGenVisitor::visitBlock(Block* b) {\n\tllvm::Value* lastVisited;\n\tstd::vector>* statements = b->statements;\n\tfor(size_t i = 0, end = statements->size(); i != end; ++i) {\n\t\tlastVisited = statements[i][0]->acceptVisitor(this);\n\t\t\/\/if(!lastVisited) \/\/TODO:nullary operator needs more explicit handling\n\t\t\/\/\treturn nullptr; \n\t}\n\treturn lastVisited;\n}\n\n\/*===============================FunctionCall===============================*\/\nllvm::Value* CodeGenVisitor::visitFunctionCall(FunctionCall* f) {\n\t\/\/grab function and evaluate with arguments\n\tllvm::Function* func = theModule->getFunction(f->ident->name);\n\tif(!func)\n\t\treturn ErrorV(\"Unknown function reference\");\n\tif(func->arg_size() != f->args->size())\n\t\treturn ErrorV(\"Wrong number of arguments passed\");\n\n\tstd::vector argVector;\n\tfor(size_t i = 0, end = f->args->size(); i != end; ++i) {\n\t\targVector.push_back(f->args[i][0]->acceptVisitor(this));\n\t\tif(!argVector.back())\n\t\t\treturn nullptr;\n\t}\n\treturn builder->CreateCall(func, argVector, \"calltmp\");\n}\n\n\/*=================================Keyword==================================*\/\nllvm::Value* CodeGenVisitor::visitKeyword(Keyword* k) {\n\treturn ErrorV(\"Attempt to generate code for dangling keyword\");\n}\n\n\/*============================VariableDefinition============================*\/\nllvm::Value* CodeGenVisitor::visitVariableDefinition(VariableDefinition* v) {\n\tstd::string type = v->type->name; \/\/int float or void\n\tllvm::Value* val = nullptr;\n\tif(type == \"int\") {\n\t\tint64_t i = 0; \/\/TODO: Figure out why variable necessary, attempted casting already\n\t\tval = llvm::ConstantInt::get(*context, llvm::APInt(i, 64));\n\t}\n\telse if(type == \"float\")\n\t\tval = llvm::ConstantFP::get(*context, llvm::APFloat(0.0));\n\tif(!val) \/\/add default value variable to map\n\t\tnamedValues.insert(std::make_pair(v->ident->name, val));\n\treturn val;\n}\n\n\/*===========================StructureDefinition============================*\/\nllvm::Value* CodeGenVisitor::visitStructureDefinition(StructureDefinition* s) {\n\treturn ErrorV(\"Attempt to evaluate not yet implemented structure definition\");\n}\n\n\/*============================FunctionDefinition============================*\/\nllvm::Value* CodeGenVisitor::visitFunctionDefinition(FunctionDefinition* f) {\n\tllvm::Function* func = theModule->getFunction(f->ident->name);\n\tif(!func)\n\t\tfunc = generateFunction(f); \/\/create function object with type|ident|args\n\tif(!func) \/\/generateFunction returned nullptr\n\t\treturn nullptr;\n\tif(!func->empty())\n\t\treturn ErrorV(\"Function is already defined\");\n\tllvm::BasicBlock* block = llvm::BasicBlock::Create(*context, \"function start\", func);\n\tbuilder->SetInsertPoint(block);\n\tnamedValues.clear();\n\tfor (auto &arg : func->args())\n\t\tnamedValues[arg.getName()] = &arg;\n\t\tfunc->dump();\/\/Function IR dump\n\t\tllvm::Value* retVal = f->block->acceptVisitor(this);\n\tif(retVal->getType()->getTypeID() == func->getReturnType()->getTypeID()) {\n\t\treturn retVal;\n\t}\n\tfunc->eraseFromParent();\/\/erase if incorrect type returned\n\treturn nullptr; \n}\n\n\/*==========================StructureDeclaration============================*\/\nllvm::Value* CodeGenVisitor::visitStructureDeclaration(StructureDeclaration* s) {\n\treturn ErrorV(\"Attempt to evaluate not yet implemented structure declaration\");\n}\n\n\n\/*===========================ExpressionStatement============================*\/\nllvm::Value* CodeGenVisitor::visitExpressionStatement(ExpressionStatement* e) {\n\treturn e->exp->acceptVisitor(this);\t\/\/evaluated but value discarded\n}\n\n\/*=============================ReturnStatement==============================*\/\nllvm::Value* CodeGenVisitor::visitReturnStatement(ReturnStatement* r) {\n\tllvm::Value* returnVal = r->exp->acceptVisitor(this);\n\tif(returnVal) {\n\t\tbuilder->CreateRet(returnVal); \/\/builder returns value\n\t}\n\treturn returnVal;\n}\n\n\/*=============================AssignStatement==============================*\/\nllvm::Value* CodeGenVisitor::visitAssignStatement(AssignStatement* a) {\n\t\/\/TODO: map a value to an exisiting identifier\n\t\/\/look for identifier\n\t\/\/map target to value\n\treturn nullptr;\n}\n\n\/*===============================IfStatement================================*\/\nllvm::Value* CodeGenVisitor::visitIfStatement(IfStatement* i) {\n\treturn ErrorV(\"Attempt to evaluate not yet implemented if statement\");\n}\n<|endoftext|>"}
{"text":"#pragma once\n#include \n#include \n#include \n#include \n#include \n\n#ifdef __EMSCRIPTEN__\n#include \"SDL2\/SDL.h\"\n#else\n#include \"SDL.h\"\n#endif\n\n\n#include \"vm\/utils.hpp\"\n#include \"vm\/context.hpp\"\n\nnamespace yagbe\n{\n\tclass sdl2_renderer\n\t{\n\tpublic:\n\t\tsdl2_renderer(const ipoint &size, int scale = 4) : _w(size.x), _h(size.y)\n\t\t{\n\t\t\tif (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0)\n\t\t\t\tthrow std::runtime_error(\"SDL_Init\");\n\n\t\t\t_window.reset(SDL_CreateWindow(\"YAGBE\", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _w * scale, _h * scale, SDL_WINDOW_SHOWN));\n\t\t\tif (!_window) throw std::runtime_error(\"SDL_CreateWindow\");\n\n\t\t\t_renderer.reset(SDL_CreateRenderer(_window.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC));\n\t\t\tif (!_renderer) throw std::runtime_error(\"SDL_CreateRenderer\");\n\n\t\t\t_texture.reset(SDL_CreateTexture(_renderer.get(), SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, _w, _h));\n\t\t\tif (!_texture) throw std::runtime_error(\"SDL_CreateTexture\");\n\n\t\t\topen_audio();\n\t\t}\n\n\t\t~sdl2_renderer()\n\t\t{\n\t\t\tSDL_CloseAudioDevice(_audio);\n\t\t\tSDL_Quit();\n\t\t}\n\n\t\tvoid initialize(yagbe::context &ctx)\n\t\t{\n\t\t\tctx.gpu.onFrameReady = [&](auto& frame)\n\t\t\t{\n\t\t\t\taccept_image(frame);\n\t\t\t};\n\n\t\t\tctx.apu.configure(_audioSpec.freq, _audioSpec.freq \/ 60);\n\t\t\tctx.apu.onSamplesReady = [&](auto&& samples)\n\t\t\t{\n\t\t\t\taccept_samples(std::move(samples));\n\t\t\t};\n\t\t}\n\n\t\tbool frame_drawn()\n\t\t{\n\t\t\treturn _frame_drawn;\n\t\t}\n\n\t\tvoid next_frame()\n\t\t{\n\t\t\t_frame_drawn = false;\n\t\t}\n\n\t\tbool step()\n\t\t{\n\t\t\thandle_events();\n\t\t\treturn _running;\n\t\t}\n\n\t\tvoid accept_image(const std::vector& image)\n\t\t{\n\t\t\tif (image.size() != _w * _h * channels)\n\t\t\t\tthrow std::runtime_error(\"accept_image wrong size\");\n\n\t\t\taccept_raw_image(image.data());\n\t\t}\n\n\t\tvoid accept_image(const std::vector& image)\n\t\t{\n\t\t\tif (image.size() != _w * _h)\n\t\t\t\tthrow std::runtime_error(\"accept_image wrong size\");\n\n\t\t\taccept_raw_image((uint8_t*)image.data());\n\t\t}\n\n\t\tvoid accept_image(const std::vector& image)\n\t\t{\n\t\t\tif (image.size() != _w * _h)\n\t\t\t\tthrow std::runtime_error(\"accept_image wrong size\");\n\n\t\t\taccept_raw_image((uint8_t*)image.data());\n\t\t}\n\n\t\tvoid accept_samples(const std::vector&& samples)\n\t\t{\n\t\t\tSDL_QueueAudio(_audio, samples.data(), (Uint32)samples.size() * sizeof(float));\n\t\t}\n\n\t\tbool running() { return _running; }\n\n\t\tstruct key_info\n\t\t{\n\t\t\tbool shift = false;\n\t\t};\n\n\t\tstd::function onKeyChanged;\n\tprotected:\n\t\tvoid audio_callback(float* buff, int len) \n\t\t{\n\t\t\t\n\t\t\tint channels = 2;\n\t\t\tfor (int i = 0; i < len; i += channels)\n\t\t\t{\n\t\t\t\tauto& outLeft = buff[i];\n\t\t\t\tauto& outRight = buff[i + 1];\n\t\t\t\t\n\n\t\t\t\tauto sine = [=](double freq) {\n\t\t\t\t\tstatic double secondsFromStart = 0;\n\t\t\t\t\tsecondsFromStart += _audioStep;\n\t\t\t\t\treturn (float)sin(secondsFromStart * freq * M_PI * 2.0);\n\t\t\t\t};\n\n\t\t\t\tauto square = [=](double freq) {\n\t\t\t\t\tstatic double len = 1.0 \/ freq \/ 2.0;\n\t\t\t\t\tstatic double acc = 0.0;\n\t\t\t\t\tstatic double v = 0.25;\n\t\t\t\t\tacc += _audioStep;\n\t\t\t\t\tif (acc > len) { acc = 0.0; v = -v; };\n\t\t\t\t\treturn v;\n\t\t\t\t};\n\n\t\t\t\tauto silence = [=]() {\n\t\t\t\t\treturn 0.0;\n\t\t\t\t};\n\n\t\t\t\t\/\/square 1000\n\n\n\t\t\t\toutLeft = outRight = (float)silence();\n\t\t\t}\n\t\t}\n\n\t\tvoid open_audio()\n\t\t{\n\t\t\tSDL_AudioSpec want;\n\n\t\t\tSDL_memset(&_audioSpec, 0, sizeof(_audioSpec));\n\t\t\tSDL_memset(&want, 0, sizeof(want)); \/* or SDL_zero(want) *\/\n\t\t\twant.freq = 48000;\n\t\t\twant.format = AUDIO_F32;\n\t\t\twant.channels = 2;\n\t\t\twant.samples = 4096;\n\t\t\twant.userdata = this;\n\t\t\twant.callback = nullptr;\n\n\t\t\t_audio = SDL_OpenAudioDevice(NULL, 0, &want, &_audioSpec, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE);\n\t\t\tif (_audio == 0) {\n\t\t\t\tSDL_Log(\"Failed to open audio: %s\", SDL_GetError());\n\t\t\t}\n\t\t\telse {\n\t\t\t\t_audioStep = 1.0 \/ (double)_audioSpec.freq;\n\t\t\t\tSDL_PauseAudioDevice(_audio, 0); \/* start audio playing. *\/\n\t\t\t}\n\t\t}\n\n\t\tvoid accept_raw_image(const uint8_t *input)\n\t\t{\n\t\t\t_frame_drawn = true;\n\t\t\tauto texture = _texture.get();\n\t\t\tuint8_t *pixels;\n\t\t\tint pitch;\n\t\t\tif (SDL_LockTexture(texture, nullptr, &(void*&)pixels, &pitch) != 0)\n\t\t\t\tthrow std::runtime_error(\"SDL_LockTexture\");\n\n\t\t\tauto it = input;\n\t\t\tfor (auto y = 0; y < _h; y++)\n\t\t\t{\n\t\t\t\tstd::copy(it, it + _w*channels, pixels);\n\t\t\t\tit += _w*channels;\n\t\t\t\tpixels += pitch;\n\t\t\t}\n\n\t\t\tSDL_UnlockTexture(texture);\n\n\t\t\tauto ren = _renderer.get();\n\n\t\t\tSDL_RenderCopy(ren, _texture.get(), NULL, NULL);\n\t\t\tSDL_RenderPresent(ren);\n\t\t}\n\n\t\tvoid handle_events()\n\t\t{\n\t\t\tSDL_Event e;\n\t\t\twhile (SDL_PollEvent(&e)) \n\t\t\t{\n\t\t\t\tif (e.type == SDL_QUIT) \n\t\t\t\t\t_running = false;\n\n\t\t\t\tif (e.type == SDL_KEYDOWN || e.type == SDL_KEYUP)\n\t\t\t\t{\n\t\t\t\t\tauto key_code = e.key.keysym.sym;\n\t\t\t\t\tkey_info info;\n\t\t\t\t\tinfo.shift = (e.key.keysym.mod & KMOD_SHIFT) != 0;\n\n\t\t\t\t\tif (onKeyChanged)\n\t\t\t\t\t\tonKeyChanged(key_code, e.type == SDL_KEYDOWN, info);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tint _w, _h;\n\t\tbool _frame_drawn = false;\n\t\tconst static int channels = 4;\n\t\tstd::unique_ptr _window = { nullptr, SDL_DestroyWindow };\n\t\tstd::unique_ptr _renderer = { nullptr, SDL_DestroyRenderer };\n\t\tstd::unique_ptr _texture = { nullptr, SDL_DestroyTexture };\n\t\tSDL_AudioDeviceID _audio = 0;\n\t\tSDL_AudioSpec _audioSpec = {};\n\t\tdouble _audioStep = 0.0f;\n\t\tbool _running = true;\n\t};\n\n\n};Define M_PI#pragma once\n#include \n#include \n#include \n#include \n#include \n\n#ifdef __EMSCRIPTEN__\n#include \"SDL2\/SDL.h\"\n#else\n#include \"SDL.h\"\n#endif\n\n\n#include \"vm\/utils.hpp\"\n#include \"vm\/context.hpp\"\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\nnamespace yagbe\n{\n\tclass sdl2_renderer\n\t{\n\tpublic:\n\t\tsdl2_renderer(const ipoint &size, int scale = 4) : _w(size.x), _h(size.y)\n\t\t{\n\t\t\tif (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0)\n\t\t\t\tthrow std::runtime_error(\"SDL_Init\");\n\n\t\t\t_window.reset(SDL_CreateWindow(\"YAGBE\", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _w * scale, _h * scale, SDL_WINDOW_SHOWN));\n\t\t\tif (!_window) throw std::runtime_error(\"SDL_CreateWindow\");\n\n\t\t\t_renderer.reset(SDL_CreateRenderer(_window.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC));\n\t\t\tif (!_renderer) throw std::runtime_error(\"SDL_CreateRenderer\");\n\n\t\t\t_texture.reset(SDL_CreateTexture(_renderer.get(), SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, _w, _h));\n\t\t\tif (!_texture) throw std::runtime_error(\"SDL_CreateTexture\");\n\n\t\t\topen_audio();\n\t\t}\n\n\t\t~sdl2_renderer()\n\t\t{\n\t\t\tSDL_CloseAudioDevice(_audio);\n\t\t\tSDL_Quit();\n\t\t}\n\n\t\tvoid initialize(yagbe::context &ctx)\n\t\t{\n\t\t\tctx.gpu.onFrameReady = [&](auto& frame)\n\t\t\t{\n\t\t\t\taccept_image(frame);\n\t\t\t};\n\n\t\t\tctx.apu.configure(_audioSpec.freq, _audioSpec.freq \/ 60);\n\t\t\tctx.apu.onSamplesReady = [&](auto&& samples)\n\t\t\t{\n\t\t\t\taccept_samples(std::move(samples));\n\t\t\t};\n\t\t}\n\n\t\tbool frame_drawn()\n\t\t{\n\t\t\treturn _frame_drawn;\n\t\t}\n\n\t\tvoid next_frame()\n\t\t{\n\t\t\t_frame_drawn = false;\n\t\t}\n\n\t\tbool step()\n\t\t{\n\t\t\thandle_events();\n\t\t\treturn _running;\n\t\t}\n\n\t\tvoid accept_image(const std::vector& image)\n\t\t{\n\t\t\tif (image.size() != _w * _h * channels)\n\t\t\t\tthrow std::runtime_error(\"accept_image wrong size\");\n\n\t\t\taccept_raw_image(image.data());\n\t\t}\n\n\t\tvoid accept_image(const std::vector& image)\n\t\t{\n\t\t\tif (image.size() != _w * _h)\n\t\t\t\tthrow std::runtime_error(\"accept_image wrong size\");\n\n\t\t\taccept_raw_image((uint8_t*)image.data());\n\t\t}\n\n\t\tvoid accept_image(const std::vector& image)\n\t\t{\n\t\t\tif (image.size() != _w * _h)\n\t\t\t\tthrow std::runtime_error(\"accept_image wrong size\");\n\n\t\t\taccept_raw_image((uint8_t*)image.data());\n\t\t}\n\n\t\tvoid accept_samples(const std::vector&& samples)\n\t\t{\n\t\t\tSDL_QueueAudio(_audio, samples.data(), (Uint32)samples.size() * sizeof(float));\n\t\t}\n\n\t\tbool running() { return _running; }\n\n\t\tstruct key_info\n\t\t{\n\t\t\tbool shift = false;\n\t\t};\n\n\t\tstd::function onKeyChanged;\n\tprotected:\n\t\tvoid audio_callback(float* buff, int len) \n\t\t{\n\t\t\t\n\t\t\tint channels = 2;\n\t\t\tfor (int i = 0; i < len; i += channels)\n\t\t\t{\n\t\t\t\tauto& outLeft = buff[i];\n\t\t\t\tauto& outRight = buff[i + 1];\n\t\t\t\t\n\n\t\t\t\tauto sine = [=](double freq) {\n\t\t\t\t\tstatic double secondsFromStart = 0;\n\t\t\t\t\tsecondsFromStart += _audioStep;\n\t\t\t\t\treturn (float)sin(secondsFromStart * freq * M_PI * 2.0);\n\t\t\t\t};\n\n\t\t\t\tauto square = [=](double freq) {\n\t\t\t\t\tstatic double len = 1.0 \/ freq \/ 2.0;\n\t\t\t\t\tstatic double acc = 0.0;\n\t\t\t\t\tstatic double v = 0.25;\n\t\t\t\t\tacc += _audioStep;\n\t\t\t\t\tif (acc > len) { acc = 0.0; v = -v; };\n\t\t\t\t\treturn v;\n\t\t\t\t};\n\n\t\t\t\tauto silence = [=]() {\n\t\t\t\t\treturn 0.0;\n\t\t\t\t};\n\n\t\t\t\t\/\/square 1000\n\n\n\t\t\t\toutLeft = outRight = (float)silence();\n\t\t\t}\n\t\t}\n\n\t\tvoid open_audio()\n\t\t{\n\t\t\tSDL_AudioSpec want;\n\n\t\t\tSDL_memset(&_audioSpec, 0, sizeof(_audioSpec));\n\t\t\tSDL_memset(&want, 0, sizeof(want)); \/* or SDL_zero(want) *\/\n\t\t\twant.freq = 48000;\n\t\t\twant.format = AUDIO_F32;\n\t\t\twant.channels = 2;\n\t\t\twant.samples = 4096;\n\t\t\twant.userdata = this;\n\t\t\twant.callback = nullptr;\n\n\t\t\t_audio = SDL_OpenAudioDevice(NULL, 0, &want, &_audioSpec, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE);\n\t\t\tif (_audio == 0) {\n\t\t\t\tSDL_Log(\"Failed to open audio: %s\", SDL_GetError());\n\t\t\t}\n\t\t\telse {\n\t\t\t\t_audioStep = 1.0 \/ (double)_audioSpec.freq;\n\t\t\t\tSDL_PauseAudioDevice(_audio, 0); \/* start audio playing. *\/\n\t\t\t}\n\t\t}\n\n\t\tvoid accept_raw_image(const uint8_t *input)\n\t\t{\n\t\t\t_frame_drawn = true;\n\t\t\tauto texture = _texture.get();\n\t\t\tuint8_t *pixels;\n\t\t\tint pitch;\n\t\t\tif (SDL_LockTexture(texture, nullptr, &(void*&)pixels, &pitch) != 0)\n\t\t\t\tthrow std::runtime_error(\"SDL_LockTexture\");\n\n\t\t\tauto it = input;\n\t\t\tfor (auto y = 0; y < _h; y++)\n\t\t\t{\n\t\t\t\tstd::copy(it, it + _w*channels, pixels);\n\t\t\t\tit += _w*channels;\n\t\t\t\tpixels += pitch;\n\t\t\t}\n\n\t\t\tSDL_UnlockTexture(texture);\n\n\t\t\tauto ren = _renderer.get();\n\n\t\t\tSDL_RenderCopy(ren, _texture.get(), NULL, NULL);\n\t\t\tSDL_RenderPresent(ren);\n\t\t}\n\n\t\tvoid handle_events()\n\t\t{\n\t\t\tSDL_Event e;\n\t\t\twhile (SDL_PollEvent(&e)) \n\t\t\t{\n\t\t\t\tif (e.type == SDL_QUIT) \n\t\t\t\t\t_running = false;\n\n\t\t\t\tif (e.type == SDL_KEYDOWN || e.type == SDL_KEYUP)\n\t\t\t\t{\n\t\t\t\t\tauto key_code = e.key.keysym.sym;\n\t\t\t\t\tkey_info info;\n\t\t\t\t\tinfo.shift = (e.key.keysym.mod & KMOD_SHIFT) != 0;\n\n\t\t\t\t\tif (onKeyChanged)\n\t\t\t\t\t\tonKeyChanged(key_code, e.type == SDL_KEYDOWN, info);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tint _w, _h;\n\t\tbool _frame_drawn = false;\n\t\tconst static int channels = 4;\n\t\tstd::unique_ptr _window = { nullptr, SDL_DestroyWindow };\n\t\tstd::unique_ptr _renderer = { nullptr, SDL_DestroyRenderer };\n\t\tstd::unique_ptr _texture = { nullptr, SDL_DestroyTexture };\n\t\tSDL_AudioDeviceID _audio = 0;\n\t\tSDL_AudioSpec _audioSpec = {};\n\t\tdouble _audioStep = 0.0f;\n\t\tbool _running = true;\n\t};\n\n\n};\n<|endoftext|>"}
{"text":"\/\/\n\/\/  async_activator.hpp\n\/\/  fibio\n\/\/\n\/\/  Created by Chen Xu on 14-3-30.\n\/\/  Copyright (c) 2014 0d0a.com. All rights reserved.\n\/\/\n\n#ifndef fibio_fibers_asio_detail_async_activator_hpp\n#define fibio_fibers_asio_detail_async_activator_hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace fibio { namespace fibers { namespace asio { namespace detail {\n    struct async_activator : std::enable_shared_from_this {\n        typedef std::shared_ptr ptr_t;\n\n        async_activator(fibio::fibers::detail::fiber_base::ptr_t this_fiber,\n                        uint64_t timeout,\n                        std::function &&cancelation)\n        : fiber_(this_fiber)\n        , timeout_(timeout)\n        , cancelation_(std::move(cancelation))\n        , timer_(std::make_shared(fiber_->get_fiber_strand().get_io_service()))\n        , timer_triggered(false)\n        , async_op_triggered(false)\n        {}\n        \n        async_activator(const async_activator&)=delete;\n        async_activator(async_activator&&)=delete;\n        \n        void activate() {\n            async_op_triggered=true;\n            \/\/ Operation completed, cancel timer\n            if(timeout_>0 && !timer_triggered) timer_->cancel();\n            if(timeout_==0 || timer_triggered) {\n                \/\/ Both callback are called, resume fiber\n                \/\/fiber_->activate();\n                ptr_t pthis(shared_from_this());\n                fiber_->get_fiber_strand().dispatch([pthis](){ pthis->fiber_->activate(); });\n            }\n        }\n        \n        void start_timer_with_cancelation() {\n            if (timeout_>0) {\n                timer_->expires_from_now(std::chrono::microseconds(timeout_));\n                ptr_t pthis(shared_from_this());\n                timer_->async_wait(fiber_->get_fiber_strand().wrap(std::bind(&async_activator::on_timeout, pthis, std::placeholders::_1)));\n            }\n        }\n        \n        \/\/ private:\n        void on_timeout(const boost::system::error_code &ec) {\n            timer_triggered=true;\n            if(async_op_triggered) {\n                \/\/ Both callback are called, resume fiber\n                \/\/fiber_->activate();\n                ptr_t pthis(shared_from_this());\n                fiber_->get_fiber_strand().dispatch([pthis](){ pthis->fiber_->activate(); });\n            } else {\n                if(cancelation_) cancelation_();\n            }\n        }\n        \n        typedef boost::asio::basic_waitable_timer yield_timer_t;\n        typedef std::shared_ptr> timer_ptr_t;\n        \n        fibio::fibers::detail::fiber_base::ptr_t fiber_;\n        uint64_t timeout_;\n        std::function cancelation_;\n        timer_ptr_t timer_;\n        bool timer_triggered;\n        bool async_op_triggered;\n    };\n}}}}    \/\/ End of namespace fibio::fibers::asio::detail\n\n#endif\nremove unused code<|endoftext|>"}
{"text":"#include \"chord.h\"\n#include \"succ_list.h\"\n#include \n#include \n#include \n#include \n\n#include \n\n\/*\n * The idea of the succ_list class is to maintain a list of\n * immediate successors to the current node. The actual number\n * of successors needed is up to nsucc. The location information\n * is maintained in locationtable.\n *\/\nsucc_list::succ_list (ptr v,\n\t\t      ptr locs)\n  : myID (v->my_ID ()), myvnode (v), locations (locs)\n{\n  nnodes = 0;\n  \n  bool ok = Configurator::only ().get_int (\"chord.nsucc\", nsucc_);\n  assert (ok);\n  \n  oldsucc = v->my_location ();\n  stable_succlist = false;\n  stable_succlist2 = false;\n  nout_backoff = 0;\n  nout_continuous = 0;\n\n  locations->pin (myID, 1);\n  locations->pin (myID, nsucc_);\n}\n   \nptr\nsucc_list::succ ()\n{\n  return locations->closestsuccloc (incID (myID));\n}\n\nvec >\nsucc_list::succs ()\n{\n  vec > ret;\n  \n  ptr cur = succ ();\n  ret.push_back (cur);\n\n  for (u_int i = 1; i < num_succ (); i++) {\n    cur = locations->closestsuccloc (incID (cur->id ()));\n    ret.push_back (cur);\n  }\n  return ret;\n}\n\nunsigned int\nsucc_list::num_succ ()\n{\n  int goodnodes = locations->usablenodes () - 1;\n  int newnsucc = (nsucc_ > goodnodes) ? goodnodes : nsucc_;\n  \n  if (newnsucc < 0) {\n    warn << \"succ_list::num_succ () n:\" << newnsucc << \" g:\" << goodnodes << \"\\n\";\n    newnsucc = 0;\n  }\n  return newnsucc;\n}\n\nvoid\nsucc_list::print (strbuf &outbuf)\n{\n  vec > s = succs ();\n  for (u_int i = 0; i < s.size (); i++)\n    outbuf << myID << \": succ \" << i + 1 << \" : \" << s[i]->id () << \"\\n\";\n}\n\nu_long\nsucc_list::estimate_nnodes ()\n{\n  u_long n;\n  ptr lastsucc = myvnode->my_location ();\n  int nsucc = num_succ ();\n  for (int i = 0; i < nsucc; i++)\n    lastsucc = locations->closestsuccloc (incID (lastsucc->id ()));\n  \n  chordID d = diff (myID, lastsucc->id ());\n  if ((d > 0) && (nsucc > 0)) {\n    chordID s = d \/ nsucc;\n    chordID c = bigint (1) << NBIT;\n    chordID q = c \/ s;\n    n = q.getui ();\n  } else \n    n = 1;\n  return n;\n}\n\nvoid\nsucc_list::fill_nodelistresext (chord_nodelistextres *res)\n{\n  \/\/ succ[0] is me. the rest are our actual successors.\n  int curnsucc = num_succ ();\n  ptr cursucc = myvnode->my_location ();\n  res->resok->nlist.setsize (curnsucc + 1);\n  for (int i = 0; i <= curnsucc; i++) {\n    cursucc->fill_node_ext (res->resok->nlist[i]);\n    cursucc = locations->closestsuccloc (incID (cursucc->id ()));\n  }\n}\n\nvoid\nsucc_list::fill_nodelistres (chord_nodelistres *res)\n{\n  \/\/ succ[0] is me. the rest are our actual successors.\n  int curnsucc = num_succ ();\n  ptr cursucc = myvnode->my_location ();\n  res->resok->nlist.setsize (curnsucc + 1);\n  for (int i = 0; i <= curnsucc; i++) {\n    cursucc->fill_node (res->resok->nlist[i]);\n    cursucc = locations->closestsuccloc (incID (cursucc->id ()));\n  }\n}\n\nvoid\nsucc_list::stabilize_succlist ()\n{\n  assert (nout_backoff == 0);\n  \n  stable_succlist2 = stable_succlist;\n  stable_succlist = true;\n  \n  u_long n = estimate_nnodes ();\n  locations->replace_estimate (nnodes, n);\n  if (nnodes != n) {\n    warnx << myID << \": estimating total number of nodes as \"\n\t  << locations->estimate_nodes () << \"\\n\";\n  }\n  nnodes = n;\n\n  nout_backoff++;\n  ptr s = succ ();\n  myvnode->get_succlist\n    (s, wrap (this, &succ_list::stabilize_getsucclist_cb, s));\n}\n\nvoid\nsucc_list::stabilize_getsucclist_cb (ptr s, vec nlist,\n\t\t\t\t     chordstat status)\n{\n  nout_backoff--;\n  if (status) {\n    warnx << myID << \": stabilize_getsucclist_cb: \" << s << \" : \" \n\t  << \"failure \" << status << \"\\n\";\n    stable_succlist = false;\n    return;\n  }\n  assert (s->id () == nlist[0].x);\n\n  \/\/ PODC paper says, set our succlist to successors succlist mod last guy\n  \/\/ We're going to merge his succlist with our succlist and make sure\n  \/\/ deletions and insertions are accurate from our POV.\n  unsigned int i, j;\n  vec > succlist = succs ();\n  size_t curnsucc = succlist.size ();\n\n  i = 0; j = 0;\n  unsigned int newnsucc = nlist.size () - 1; \/\/ drop last guy.\n  while ((i < curnsucc) && (j < newnsucc)) {    \n    if (succlist[i]->id () == nlist[j].x) {\n      succlist[i]->set_coords (nlist[j]);\n      i++; j++; continue;\n    }\n    if (between (myID, nlist[j].x, succlist[i]->id ())) {\n      \/\/ if succlist[i] < nlist[j].x\n      \/\/ then, maybe someone we knew about is dead now. best be sure.\n      nout_backoff++;\n      myvnode->ping\n\t(succlist[i], wrap (this, &succ_list::stabilize_getsucclist_check,\n\t\t\t    s, succlist[i]->id ()));\n      i++;\n      continue;\n    }\n    if (between (myID, succlist[i]->id (), nlist[j].x)) {\n      \/\/ if succlist[i] > nlist[j].x\n      \/\/ then maybe a new node joined. check it out.\n      ptr newsucc = locations->insert (nlist[j]);\n      if (!newsucc || !newsucc->alive ()) {\n\twarnx << myID << \": stabilize_succlist: received bad successor \"\n\t      << nlist[j].x << \" from \" << s << \"\\n\";\n\t\/\/ XXX do something about it?\n      } else {\n\tstable_succlist = false;\n\twarnx << myID << \": stabilize_succlist: received new successor \"\n\t      << nlist[j].x << \" from \" << s << \"\\n\";\n      }\n      j++;\n      continue;\n    }\n  }\n  bool check = false;\n  while (i < curnsucc) {\n    check = true;\n    nout_backoff++;\n    myvnode->ping\n      (succlist[i], wrap (this, &succ_list::stabilize_getsucclist_check,\n\t\t\t  s, succlist[i]->id ()));\n    i++;\n  }\n\n  while (j < newnsucc && curnsucc < (u_int)nsucc_) {\n    assert (!check);\n    ptr newsucc = locations->insert (nlist[j]);\n    if (!newsucc || !newsucc->alive ()) {\n      warnx << myID << \": stabilize_succlist: received bad successor \"\n\t    << nlist[j].x << \" from \" << s << \"\\n\";\n      \/\/ XXX do something about it?\n    } else {\n      curnsucc++;\n      stable_succlist = false;\n      warnx << myID << \": stabilize_succlist (2): received new successor \"\n\t    << nlist[j].x << \" from \" << s << \"\\n\";\n    }\n    j++;\n  }\n}\n\nvoid\nsucc_list::stabilize_getsucclist_check (ptr src, chordID chk,\n\t\t\t\t\tchordstat status)\n{\n  nout_backoff--;\n  if (status) {\n    stable_succlist = false;\n    warnx << myID << \": stabilize_succlist: found dead successor \" << chk\n\t  << \" from \" << src << \"\\n\";\n  }\n}\n\n\/\/ ============\nvoid\nsucc_list::stabilize_succ ()\n{\n  assert (nout_continuous == 0);\n  ptr cursucc = succ ();\n  if (cursucc != oldsucc) {\n    warnx << myID << \": my successor changed from \"\n\t  << oldsucc->id () << \" to \" << cursucc->id () << \"\\n\";\n    myvnode->notify (cursucc, myID);\n    oldsucc = cursucc;\n    \/\/ Wait until next round to check on this guy.\n  } else {\n    nout_continuous++;\n    myvnode->get_predecessor\n      (cursucc, wrap (this, &succ_list::stabilize_getpred_cb, cursucc));\n  }\n}\n\nvoid\nsucc_list::stabilize_getpred_cb (ptr sd, chord_node p, chordstat status)\n{\n  nout_continuous--;\n  \/\/ receive predecessor from my successor; in stable case it is me\n  if (status) {\n    warnx << myID << \": stabilize_getpred_cb \" << sd->id ()\n    \t  << \" failure status \" << status << \"\\n\";\n    if (status == CHORD_ERRNOENT) {\n      warnx << myID << \": stabilize_getpred_cb \" << sd->id ()\n\t    << \" doesn't know about his predecessor?? notifying...\\n\";\n      myvnode->notify (sd, myID);\n    }\n    \/\/ other failures we will address next round.\n  } else {\n    if (myID == p.x) {\n      \/\/ Good, things are as we expect.\n    } else if (betweenleftincl (myID, sd->id (), p.x)) {\n      \/\/ Did we get someone strictly better?\n      ptr newsucc = locations->insert (p);\n      if (newsucc && newsucc->alive ())\n\toldsucc = newsucc;\n    } else {\n      \/\/ Our successor appears to be confused, better tell\n      \/\/ him what we think.\n      myvnode->notify (sd, myID);\n    }\n  }\n}\n\n\/\/ XXX currently an exhaustive search of the successors\nptr\nsucc_list::closestpred (const chordID &x, vec failed)\n{\n  ptr best = myvnode->my_location ();\n  for (u_int i = 0; i < num_succ (); i++) {\n    ptr n = locations->closestsuccloc (incID (best->id ()));\n    if (between (myID, x, n->id ()) && (!in_vector (failed, n->id ())))\n      best = n;\n  }\n  return best;\n}\n\nupdate successor lists' age#include \"chord.h\"\n#include \"succ_list.h\"\n#include \n#include \n#include \n#include \n\n#include \n\n\/*\n * The idea of the succ_list class is to maintain a list of\n * immediate successors to the current node. The actual number\n * of successors needed is up to nsucc. The location information\n * is maintained in locationtable.\n *\/\nsucc_list::succ_list (ptr v,\n\t\t      ptr locs)\n  : myID (v->my_ID ()), myvnode (v), locations (locs)\n{\n  nnodes = 0;\n  \n  bool ok = Configurator::only ().get_int (\"chord.nsucc\", nsucc_);\n  assert (ok);\n  \n  oldsucc = v->my_location ();\n  stable_succlist = false;\n  stable_succlist2 = false;\n  nout_backoff = 0;\n  nout_continuous = 0;\n\n  locations->pin (myID, 1);\n  locations->pin (myID, nsucc_);\n}\n   \nptr\nsucc_list::succ ()\n{\n  return locations->closestsuccloc (incID (myID));\n}\n\nvec >\nsucc_list::succs ()\n{\n  vec > ret;\n  \n  ptr cur = succ ();\n  ret.push_back (cur);\n\n  for (u_int i = 1; i < num_succ (); i++) {\n    cur = locations->closestsuccloc (incID (cur->id ()));\n    ret.push_back (cur);\n  }\n  return ret;\n}\n\nunsigned int\nsucc_list::num_succ ()\n{\n  int goodnodes = locations->usablenodes () - 1;\n  int newnsucc = (nsucc_ > goodnodes) ? goodnodes : nsucc_;\n  \n  if (newnsucc < 0) {\n    warn << \"succ_list::num_succ () n:\" << newnsucc << \" g:\" << goodnodes << \"\\n\";\n    newnsucc = 0;\n  }\n  return newnsucc;\n}\n\nvoid\nsucc_list::print (strbuf &outbuf)\n{\n  vec > s = succs ();\n  for (u_int i = 0; i < s.size (); i++)\n    outbuf << myID << \": succ \" << i + 1 << \" : \" << s[i]->id () << \"\\n\";\n}\n\nu_long\nsucc_list::estimate_nnodes ()\n{\n  u_long n;\n  ptr lastsucc = myvnode->my_location ();\n  int nsucc = num_succ ();\n  for (int i = 0; i < nsucc; i++)\n    lastsucc = locations->closestsuccloc (incID (lastsucc->id ()));\n  \n  chordID d = diff (myID, lastsucc->id ());\n  if ((d > 0) && (nsucc > 0)) {\n    chordID s = d \/ nsucc;\n    chordID c = bigint (1) << NBIT;\n    chordID q = c \/ s;\n    n = q.getui ();\n  } else \n    n = 1;\n  return n;\n}\n\nvoid\nsucc_list::fill_nodelistresext (chord_nodelistextres *res)\n{\n  \/\/ succ[0] is me. the rest are our actual successors.\n  int curnsucc = num_succ ();\n  ptr cursucc = myvnode->my_location ();\n  res->resok->nlist.setsize (curnsucc + 1);\n  for (int i = 0; i <= curnsucc; i++) {\n    cursucc->fill_node_ext (res->resok->nlist[i]);\n    cursucc = locations->closestsuccloc (incID (cursucc->id ()));\n  }\n}\n\nvoid\nsucc_list::fill_nodelistres (chord_nodelistres *res)\n{\n  \/\/ succ[0] is me. the rest are our actual successors.\n  int curnsucc = num_succ ();\n  ptr cursucc = myvnode->my_location ();\n  res->resok->nlist.setsize (curnsucc + 1);\n  for (int i = 0; i <= curnsucc; i++) {\n    cursucc->fill_node (res->resok->nlist[i]);\n    cursucc = locations->closestsuccloc (incID (cursucc->id ()));\n  }\n}\n\nvoid\nsucc_list::stabilize_succlist ()\n{\n  assert (nout_backoff == 0);\n  \n  stable_succlist2 = stable_succlist;\n  stable_succlist = true;\n  \n  u_long n = estimate_nnodes ();\n  locations->replace_estimate (nnodes, n);\n  if (nnodes != n) {\n    warnx << myID << \": estimating total number of nodes as \"\n\t  << locations->estimate_nodes () << \"\\n\";\n  }\n  nnodes = n;\n\n  nout_backoff++;\n  ptr s = succ ();\n  myvnode->get_succlist\n    (s, wrap (this, &succ_list::stabilize_getsucclist_cb, s));\n}\n\nvoid\nsucc_list::stabilize_getsucclist_cb (ptr s, vec nlist,\n\t\t\t\t     chordstat status)\n{\n  nout_backoff--;\n  if (status) {\n    warnx << myID << \": stabilize_getsucclist_cb: \" << s << \" : \" \n\t  << \"failure \" << status << \"\\n\";\n    stable_succlist = false;\n    return;\n  }\n  assert (s->id () == nlist[0].x);\n\n  \/\/ PODC paper says, set our succlist to successors succlist mod last guy\n  \/\/ We're going to merge his succlist with our succlist and make sure\n  \/\/ deletions and insertions are accurate from our POV.\n  unsigned int i, j;\n  vec > succlist = succs ();\n  size_t curnsucc = succlist.size ();\n\n  i = 0; j = 0;\n  unsigned int newnsucc = nlist.size () - 1; \/\/ drop last guy.\n  while ((i < curnsucc) && (j < newnsucc)) {    \n    if (succlist[i]->id () == nlist[j].x) {\n      succlist[i]->update (nlist[j]);\n      i++; j++; continue;\n    }\n    if (between (myID, nlist[j].x, succlist[i]->id ())) {\n      \/\/ if succlist[i] < nlist[j].x\n      \/\/ then, maybe someone we knew about is dead now. best be sure.\n      nout_backoff++;\n      myvnode->ping\n\t(succlist[i], wrap (this, &succ_list::stabilize_getsucclist_check,\n\t\t\t    s, succlist[i]->id ()));\n      i++;\n      continue;\n    }\n    if (between (myID, succlist[i]->id (), nlist[j].x)) {\n      \/\/ if succlist[i] > nlist[j].x\n      \/\/ then maybe a new node joined. check it out.\n      ptr newsucc = locations->insert (nlist[j]);\n      if (!newsucc || !newsucc->alive ()) {\n\twarnx << myID << \": stabilize_succlist: received bad successor \"\n\t      << nlist[j].x << \" from \" << s << \"\\n\";\n\t\/\/ XXX do something about it?\n      } else {\n\tstable_succlist = false;\n\twarnx << myID << \": stabilize_succlist: received new successor \"\n\t      << nlist[j].x << \",\" << nlist[j].knownup << \",\" \n\t      << nlist[j].age << \" from \" << (s->id ()>>144) << \",\" << s->knownup () \n\t      << \",\" << s->age () << \"\\n\";\n      }\n      j++;\n      continue;\n    }\n  }\n  bool check = false;\n  while (i < curnsucc) {\n    check = true;\n    nout_backoff++;\n    myvnode->ping\n      (succlist[i], wrap (this, &succ_list::stabilize_getsucclist_check,\n\t\t\t  s, succlist[i]->id ()));\n    i++;\n  }\n\n  while (j < newnsucc && curnsucc < (u_int)nsucc_) {\n    assert (!check);\n    ptr newsucc = locations->insert (nlist[j]);\n    if (!newsucc || !newsucc->alive ()) {\n      warnx << myID << \": stabilize_succlist: received bad successor \"\n\t    << nlist[j].x << \" from \" << s << \"\\n\";\n      \/\/ XXX do something about it?\n    } else {\n      curnsucc++;\n      stable_succlist = false;\n      warnx << myID << \": stabilize_succlist (2): received new successor \"\n\t    << nlist[j].x << \" from \" << s << \"\\n\";\n    }\n    j++;\n  }\n}\n\nvoid\nsucc_list::stabilize_getsucclist_check (ptr src, chordID chk,\n\t\t\t\t\tchordstat status)\n{\n  nout_backoff--;\n  if (status) {\n    stable_succlist = false;\n    warnx << myID << \": stabilize_succlist: found dead successor \" << chk\n\t  << \" from \" << src << \"\\n\";\n  }\n}\n\n\/\/ ============\nvoid\nsucc_list::stabilize_succ ()\n{\n  assert (nout_continuous == 0);\n  ptr cursucc = succ ();\n  if (cursucc != oldsucc) {\n    warnx << myID << \": my successor changed from \"\n\t  << oldsucc->id () << \" to \" << cursucc->id () << \"\\n\";\n    myvnode->notify (cursucc, myID);\n    oldsucc = cursucc;\n    \/\/ Wait until next round to check on this guy.\n  } else {\n    nout_continuous++;\n    myvnode->get_predecessor\n      (cursucc, wrap (this, &succ_list::stabilize_getpred_cb, cursucc));\n  }\n}\n\nvoid\nsucc_list::stabilize_getpred_cb (ptr sd, chord_node p, chordstat status)\n{\n  nout_continuous--;\n  \/\/ receive predecessor from my successor; in stable case it is me\n  if (status) {\n    warnx << myID << \": stabilize_getpred_cb \" << sd->id ()\n    \t  << \" failure status \" << status << \"\\n\";\n    if (status == CHORD_ERRNOENT) {\n      warnx << myID << \": stabilize_getpred_cb \" << sd->id ()\n\t    << \" doesn't know about his predecessor?? notifying...\\n\";\n      myvnode->notify (sd, myID);\n    }\n    \/\/ other failures we will address next round.\n  } else {\n    if (myID == p.x) {\n      \/\/ Good, things are as we expect.\n    } else if (betweenleftincl (myID, sd->id (), p.x)) {\n      \/\/ Did we get someone strictly better?\n      ptr newsucc = locations->insert (p);\n      if (newsucc && newsucc->alive ())\n\toldsucc = newsucc;\n    } else {\n      \/\/ Our successor appears to be confused, better tell\n      \/\/ him what we think.\n      myvnode->notify (sd, myID);\n    }\n  }\n}\n\n\/\/ XXX currently an exhaustive search of the successors\nptr\nsucc_list::closestpred (const chordID &x, vec failed)\n{\n  ptr best = myvnode->my_location ();\n  for (u_int i = 0; i < num_succ (); i++) {\n    ptr n = locations->closestsuccloc (incID (best->id ()));\n    if (between (myID, x, n->id ()) && (!in_vector (failed, n->id ())))\n      best = n;\n  }\n  return best;\n}\n\n<|endoftext|>"}
{"text":"\/*************************************************************************\n *\n *  $RCSfile: cmdstrm.hxx,v $\n *\n *  $Revision: 1.1 $\n *\n *  last change: $Author: mh $ $Date: 2002-11-18 15:53:37 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2002\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2002 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2002 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _CMDSTRM_HXX\n#define _CMDSTRM_HXX\n\n#include \n#include \n#include \"cmdbasestream.hxx\"\n\nclass CmdStream : public CmdBaseStream\n{\npublic:\n    CmdStream();\n    ~CmdStream();\n\n    void WriteSortedParams( SbxArray* rPar, BOOL IsKeyString = FALSE );\n\n    void GenCmdCommand( USHORT nNr, SbxArray* rPar );\n\n    void GenCmdSlot( USHORT nNr, SbxArray* rPar );\n\n    void GenCmdUNOSlot( const String &aURL );\n\n    void GenCmdControl( ULONG nUId, USHORT nMethodId, SbxArray* rPar );\n    void GenCmdControl( String aUId, USHORT nMethodId, SbxArray* rPar );\n\n\/*  void GenCmdControl (ULONG nUId, USHORT nMethodId = 0);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, String aString);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, String aString, USHORT nNr);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, String aString, BOOL bBool);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, USHORT nNr);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, USHORT nNr1, USHORT nNr2);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, USHORT nNr, BOOL bBool);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, ULONG nNr);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, BOOL bBool);*\/\n\n    void GenCmdFlow( USHORT nArt );\n    void GenCmdFlow( USHORT nArt, USHORT nNr1 );\n    void GenCmdFlow( USHORT nArt, ULONG nNr1 );\n    void GenCmdFlow( USHORT nArt, String aString1 );\n\n    void Reset(ULONG nSequence);\n\n    SvMemoryStream* GetStream();\n\n    static CNames *pKeyCodes;           \/\/ Namen der Sondertasten  MOD1, F1, LEFT ...\n    static ControlDefLoad __READONLY_DATA arKeyCodes [];\n\nprivate:\n    String WandleKeyEventString( String aKeys );    \/\/ Nutzt pKeyCodes.   \n\n\/\/  CmdBaseStream::Write;\n    void Write( comm_USHORT nNr ){CmdBaseStream::Write( nNr );}\n    void Write( comm_ULONG nNr ){CmdBaseStream::Write( nNr );}\n    void Write( const comm_UniChar* aString, comm_USHORT nLenInChars ){CmdBaseStream::Write( aString, nLenInChars );}\n    void Write( comm_BOOL bBool ){CmdBaseStream::Write( bBool );}\n\/\/  new\n    void Write( String aString, BOOL IsKeyString = FALSE );\n\n    SvMemoryStream *pSammel;\n};\n\n#endif\nINTEGRATION: CWS ooo19126 (1.1.186); FILE MERGED 2005\/09\/05 17:17:27 rt 1.1.186.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: cmdstrm.hxx,v $\n *\n *  $Revision: 1.2 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-07 19:30:21 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _CMDSTRM_HXX\n#define _CMDSTRM_HXX\n\n#include \n#include \n#include \"cmdbasestream.hxx\"\n\nclass CmdStream : public CmdBaseStream\n{\npublic:\n    CmdStream();\n    ~CmdStream();\n\n    void WriteSortedParams( SbxArray* rPar, BOOL IsKeyString = FALSE );\n\n    void GenCmdCommand( USHORT nNr, SbxArray* rPar );\n\n    void GenCmdSlot( USHORT nNr, SbxArray* rPar );\n\n    void GenCmdUNOSlot( const String &aURL );\n\n    void GenCmdControl( ULONG nUId, USHORT nMethodId, SbxArray* rPar );\n    void GenCmdControl( String aUId, USHORT nMethodId, SbxArray* rPar );\n\n\/*  void GenCmdControl (ULONG nUId, USHORT nMethodId = 0);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, String aString);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, String aString, USHORT nNr);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, String aString, BOOL bBool);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, USHORT nNr);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, USHORT nNr1, USHORT nNr2);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, USHORT nNr, BOOL bBool);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, ULONG nNr);\n    void GenCmdControl (ULONG nUId, USHORT nMethodId, BOOL bBool);*\/\n\n    void GenCmdFlow( USHORT nArt );\n    void GenCmdFlow( USHORT nArt, USHORT nNr1 );\n    void GenCmdFlow( USHORT nArt, ULONG nNr1 );\n    void GenCmdFlow( USHORT nArt, String aString1 );\n\n    void Reset(ULONG nSequence);\n\n    SvMemoryStream* GetStream();\n\n    static CNames *pKeyCodes;           \/\/ Namen der Sondertasten  MOD1, F1, LEFT ...\n    static ControlDefLoad __READONLY_DATA arKeyCodes [];\n\nprivate:\n    String WandleKeyEventString( String aKeys );    \/\/ Nutzt pKeyCodes.   \n\n\/\/  CmdBaseStream::Write;\n    void Write( comm_USHORT nNr ){CmdBaseStream::Write( nNr );}\n    void Write( comm_ULONG nNr ){CmdBaseStream::Write( nNr );}\n    void Write( const comm_UniChar* aString, comm_USHORT nLenInChars ){CmdBaseStream::Write( aString, nLenInChars );}\n    void Write( comm_BOOL bBool ){CmdBaseStream::Write( bBool );}\n\/\/  new\n    void Write( String aString, BOOL IsKeyString = FALSE );\n\n    SvMemoryStream *pSammel;\n};\n\n#endif\n<|endoftext|>"}
{"text":"\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_JSON_EXTRACT_BOUNDING_BOX_GRAMMAR_HPP\n#define MAPNIK_JSON_EXTRACT_BOUNDING_BOX_GRAMMAR_HPP\n\n\/\/ mapnik\n#include \n#include \n#include \n\n\/\/ boost\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#pragma GCC diagnostic ignored \"-Wunused-local-typedef\"\n#include \n#include \n#include \n#pragma GCC diagnostic pop\n\n\/\/ stl\n#include \n\nnamespace mapnik { namespace json {\n\nusing position = std::tuple;\nusing boxes = std::vector, std::pair>>;\n\nnamespace qi = boost::spirit::qi;\n\nstruct calculate_bounding_box_impl\n{\n    using result_type = void;\n    template \n    result_type operator() (T0 & bbox, T1 const& pos) const\n    {\n        if (pos)\n        {\n            double x = std::get<0>(*pos);\n            double y = std::get<1>(*pos);\n            if (!bbox.valid())\n            {\n                bbox.init(x, y, x, y); \/\/TODO: add init(x,y) convinience method\n            }\n            else\n            {\n                bbox.expand_to_include(x, y);\n            }\n        }\n    }\n};\n\nstruct push_box_impl\n{\n    using result_type = void;\n    template \n    void operator() (T0 & boxes, T1 const& begin, T2 const& box, T3 const& range) const\n    {\n        if (box.valid()) boxes.emplace_back(box, std::make_pair(std::distance(begin, range.begin()), std::distance(range.begin(), range.end())));\n    }\n};\n\ntemplate  >\nstruct extract_bounding_box_grammar :\n        qi::grammar\n{\n    extract_bounding_box_grammar();\n    \/\/ rules\n    qi::rule start;\n    qi::rule, void(boxes&), space_type> features;\n    qi::rule>, void(boxes&, Iterator const&), space_type> feature;\n    qi::rule>, box2d(), space_type> coords;\n    qi::rule(), space_type> pos;\n    qi::rule&), space_type> ring;\n    qi::rule&), space_type> rings;\n    qi::rule&), space_type> rings_array;\n    \/\/ generic JSON support\n    json::generic_json json;\n    \/\/ phoenix functions\n    boost::phoenix::function push_box;\n    boost::phoenix::function calculate_bounding_box;\n    \/\/ error handler\n    boost::phoenix::function const error_handler;\n};\n\n}}\n\n#endif \/\/ MAPNIK_JSON_EXTRACT_BOUNDING_BOX_GRAMMAR_HPP\nupdate bounsing box grammar to work with mapnik-geometry\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_JSON_EXTRACT_BOUNDING_BOX_GRAMMAR_HPP\n#define MAPNIK_JSON_EXTRACT_BOUNDING_BOX_GRAMMAR_HPP\n\n\/\/ mapnik\n#include \n#include \n#include \n#include \n\/\/ boost\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#pragma GCC diagnostic ignored \"-Wunused-local-typedef\"\n#include \n#include \n#include \n#pragma GCC diagnostic pop\n\n\/\/ stl\n#include \n\nnamespace mapnik { namespace json {\n\nusing position = mapnik::new_geometry::point;\nusing boxes = std::vector, std::pair>>;\n\nnamespace qi = boost::spirit::qi;\n\nstruct calculate_bounding_box_impl\n{\n    using result_type = void;\n    template \n    result_type operator() (T0 & bbox, T1 const& pos) const\n    {\n        if (pos)\n        {\n            double x = pos->x;\n            double y = pos->y;\n            if (!bbox.valid())\n            {\n                bbox.init(x, y, x, y); \/\/TODO: add init(x,y) convinience method\n            }\n            else\n            {\n                bbox.expand_to_include(x, y);\n            }\n        }\n    }\n};\n\nstruct push_box_impl\n{\n    using result_type = void;\n    template \n    void operator() (T0 & boxes, T1 const& begin, T2 const& box, T3 const& range) const\n    {\n        if (box.valid()) boxes.emplace_back(box, std::make_pair(std::distance(begin, range.begin()), std::distance(range.begin(), range.end())));\n    }\n};\n\ntemplate  >\nstruct extract_bounding_box_grammar :\n        qi::grammar\n{\n    extract_bounding_box_grammar();\n    \/\/ rules\n    qi::rule start;\n    qi::rule, void(boxes&), space_type> features;\n    qi::rule>, void(boxes&, Iterator const&), space_type> feature;\n    qi::rule>, box2d(), space_type> coords;\n    qi::rule(), space_type> pos;\n    qi::rule&), space_type> ring;\n    qi::rule&), space_type> rings;\n    qi::rule&), space_type> rings_array;\n    \/\/ generic JSON support\n    json::generic_json json;\n    \/\/ phoenix functions\n    boost::phoenix::function push_box;\n    boost::phoenix::function calculate_bounding_box;\n    \/\/ error handler\n    boost::phoenix::function const error_handler;\n};\n\n}}\n\n#endif \/\/ MAPNIK_JSON_EXTRACT_BOUNDING_BOX_GRAMMAR_HPP\n<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2016 Per Malmberg\n\/\/ Licensed under MIT, see LICENSE file. \n\n#include \"IntegerType.h\"\n\nnamespace cmdparser4cpp {\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nIntegerType::IntegerType( CmdParser4Cpp& parser, Argument& argument, int minParameterCount, int maxParameterCount )\n\t: BaseType( parser, argument, minParameterCount, maxParameterCount ),\n\t  myMatcher(R\"!!(^([+-]{0,1}\\d*)$)!!\")\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nIntegerType::~IntegerType()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\nIntegerType::DoTypeParse( const std::string& parameter )\n{\n\tsize_t count = myResults.size();\n\n\tif( std::regex_match( parameter, myMatcher )) {\n\t\tmyResults.push_back( parameter );\n\t}\n\n\t\/\/ Any new results added?\n\treturn count < myResults.size();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nIntegerType::RetrieveResult()\n{\n\tmyParser.SetResult( myArgument.GetPrimaryName(), this );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\nIntegerType::GetResult( int index, int defaultValue ) const\n{\n\tbool res = defaultValue;\n\n\tif( index >= 0 && index < static_cast( myResults.size() ) ) {\n\t\treturn atoi( myResults.at( static_cast( index ) ).c_str() );\n\t}\n\n\treturn res;\n}\n\n} \/\/ END cmdparser4cppFixed type error.\/\/ Copyright (c) 2016 Per Malmberg\n\/\/ Licensed under MIT, see LICENSE file. \n\n#include \"IntegerType.h\"\n\nnamespace cmdparser4cpp {\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nIntegerType::IntegerType( CmdParser4Cpp& parser, Argument& argument, int minParameterCount, int maxParameterCount )\n\t: BaseType( parser, argument, minParameterCount, maxParameterCount ),\n\t  myMatcher(R\"!!(^([+-]{0,1}\\d*)$)!!\")\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nIntegerType::~IntegerType()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\nIntegerType::DoTypeParse( const std::string& parameter )\n{\n\tsize_t count = myResults.size();\n\n\tif( std::regex_match( parameter, myMatcher )) {\n\t\tmyResults.push_back( parameter );\n\t}\n\n\t\/\/ Any new results added?\n\treturn count < myResults.size();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\nIntegerType::RetrieveResult()\n{\n\tmyParser.SetResult( myArgument.GetPrimaryName(), this );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\nIntegerType::GetResult( int index, int defaultValue ) const\n{\n\tint res = defaultValue;\n\n\tif( index >= 0 && index < static_cast( myResults.size() ) ) {\n\t\tres = atoi( myResults.at( static_cast( index ) ).c_str() );\n\t}\n\n\treturn res;\n}\n\n} \/\/ END cmdparser4cpp<|endoftext|>"}
{"text":"\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkClientSocket.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkClientSocket.h\"\n\n#include \"vtkObjectFactory.h\"\n\nvtkStandardNewMacro(vtkClientSocket);\n\/\/-----------------------------------------------------------------------------\nvtkClientSocket::vtkClientSocket()\n{\n  this->ConnectingSide = false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkClientSocket::~vtkClientSocket()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nint vtkClientSocket::ConnectToServer(const char* hostName, int port)\n{\n  if (this->SocketDescriptor != -1)\n    {\n    vtkWarningMacro(\"Client connection already exists. Closing it.\");\n    this->CloseSocket(this->SocketDescriptor);\n    this->SocketDescriptor = -1;\n    }\n\n  this->SocketDescriptor = this->CreateSocket();\n  if (!this->SocketDescriptor)\n    {\n    vtkErrorMacro(\"Failed to create socket.\");\n    return -1;\n    }\n\n  if (this->Connect(this->SocketDescriptor, hostName, port) == -1)\n    {\n    this->CloseSocket(this->SocketDescriptor);\n    this->SocketDescriptor = -1;\n\n    vtkErrorMacro(\"Failed to connect to server \" << hostName << \":\" << port);\n    return -1;\n    }\n\n  this->ConnectingSide = true;\n  return 0;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkClientSocket::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os, indent);\n  os << indent << \"ConnectingSide: \" << this->ConnectingSide << endl;\n}\nBUG: Fix invalid return value check in vtkClientSocket.\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkClientSocket.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkClientSocket.h\"\n\n#include \"vtkObjectFactory.h\"\n\nvtkStandardNewMacro(vtkClientSocket);\n\/\/-----------------------------------------------------------------------------\nvtkClientSocket::vtkClientSocket()\n{\n  this->ConnectingSide = false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkClientSocket::~vtkClientSocket()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nint vtkClientSocket::ConnectToServer(const char* hostName, int port)\n{\n  if (this->SocketDescriptor != -1)\n    {\n    vtkWarningMacro(\"Client connection already exists. Closing it.\");\n    this->CloseSocket(this->SocketDescriptor);\n    this->SocketDescriptor = -1;\n    }\n\n  this->SocketDescriptor = this->CreateSocket();\n  if (this->SocketDescriptor == -1)\n    {\n    vtkErrorMacro(\"Failed to create socket.\");\n    return -1;\n    }\n\n  if (this->Connect(this->SocketDescriptor, hostName, port) == -1)\n    {\n    this->CloseSocket(this->SocketDescriptor);\n    this->SocketDescriptor = -1;\n\n    vtkErrorMacro(\"Failed to connect to server \" << hostName << \":\" << port);\n    return -1;\n    }\n\n  this->ConnectingSide = true;\n  return 0;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkClientSocket::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os, indent);\n  os << indent << \"ConnectingSide: \" << this->ConnectingSide << endl;\n}\n<|endoftext|>"}
{"text":"INTEGRATION: CWS dba24 (1.5.260); FILE MERGED 2005\/02\/09 08:07:52 oj 1.5.260.1: #i26950# remove the need for XNamed<|endoftext|>"}
{"text":"#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tルネサス RX ペリフェラル/デバイス選択\r\n    @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2016, 2022 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"common\/byte_order.h\"\r\n#include \"common\/vect.h\"\r\n#include \"common\/delay.hpp\"\r\n#include \"common\/device.hpp\"\r\n\r\n#if defined(SIG_RX63T)\r\n#include \"RX63T\/lvda.hpp\"\r\n#include \"RX63T\/bus.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX63T\/port.hpp\"\r\n#include \"RX600\/mtu3.hpp\"\r\n#include \"RX63T\/poe3.hpp\"\r\n#include \"RX63T\/gpt.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX600\/crc.hpp\"\r\n#include \"RX63T\/s12adb.hpp\"\r\n#include \"RX63T\/ad.hpp\"\r\n#include \"RX63T\/da.hpp\"\r\n#include \"RX600\/doc.hpp\"\r\n#include \"RX63T\/dpc.hpp\"\r\n#include \"RX63T\/flash.hpp\"\r\n\r\n#include \"RX63T\/system_io.hpp\"\r\n\r\n#elif defined(SIG_RX621) || defined(SIG_RX62N)\r\n#include \"RX62x\/lvd.hpp\"\r\n#include \"RX62x\/bus.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/exdmac.hpp\"\r\n#include \"RX62x\/port.hpp\"\r\n#include \"RX62x\/mtu2.hpp\"\r\n#include \"RX62x\/poe2.hpp\"\r\n#include \"RX600\/ppg.hpp\"\r\n#include \"RX600\/tmr.hpp\"\r\n#include \"RX62x\/rtc.hpp\"\r\n#include \"RX62x\/wdt.hpp\"\r\n#include \"RX600\/etherc.hpp\"\r\n#include \"RX600\/edmac.hpp\"\r\n#include \"RX62x\/usb.hpp\"\r\n#include \"RX600\/crc.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX62x\/s12ad.hpp\"\r\n#include \"RX62x\/ad.hpp\"\r\n#include \"RX62x\/da.hpp\"\r\n#include \"RX62x\/flash.hpp\"\r\n\r\n#include \"RX62x\/system_io.hpp\"\r\n#include \"RX62x\/flash_io.hpp\"\r\n#include \"RX600\/dmac_mgr.hpp\"\r\n#include \"RX24T\/dac_out.hpp\"\r\n\r\n#elif defined(SIG_RX24T)\r\n#include \"RX24T\/lvda.hpp\"\r\n#include \"RX600\/bus.hpp\"\r\n#include \"RX600\/cac.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/mtu3.hpp\"\r\n#include \"RX600\/poe3.hpp\"\r\n#include \"RX600\/tmr.hpp\"\r\n#include \"RX600\/gpt.hpp\"\r\n#include \"RX24T\/s12ad.hpp\"\r\n#include \"RX24T\/da.hpp\"\r\n#include \"RX600\/cmpc.hpp\"\r\n#include \"RX24T\/flash.hpp\"\r\n#include \"RX600\/crc.hpp\"\r\n#include \"RX600\/doc.hpp\"\r\n\r\n#include \"RX24T\/system_io.hpp\"\r\n#include \"RX24T\/flash_io.hpp\"\r\n#include \"RX24T\/adc_in.hpp\"\r\n#include \"RX24T\/dac_out.hpp\"\r\n\r\n#elif defined(SIG_RX64M) || defined(SIG_RX71M)\r\n#include \"RX600\/lvda.hpp\"\r\n#include \"RX600\/bus.hpp\"\r\n#include \"RX600\/cac.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/mtu3.hpp\"\r\n#include \"RX600\/poe3.hpp\"\r\n#include \"RX600\/tmr.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/elc.hpp\"\r\n#include \"RX600\/exdmac.hpp\"\r\n#include \"RX600\/mpc.hpp\"\r\n#include \"RX600\/tpu.hpp\"\r\n#include \"RX600\/gpt.hpp\"\r\n#include \"RX600\/ppg.hpp\"\r\n#include \"RX600\/cmtw.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX600\/qspi.hpp\"\r\n#include \"RX600\/s12adc.hpp\"\r\n#include \"RX600\/r12da.hpp\"\r\n#include \"RX600\/sdram.hpp\"\r\n#include \"RX600\/etherc.hpp\"\r\n#include \"RX600\/eptpc.hpp\"\r\n#include \"RX600\/edmac.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/usba.hpp\"\r\n#include \"RX600\/scif.hpp\"\r\n#include \"RX600\/rtc.hpp\"\r\n#include \"RX600\/rtc_io.hpp\"\r\n#include \"RX600\/wdta.hpp\"\r\n#include \"RX600\/flash.hpp\"\r\n#include \"RX600\/ssi.hpp\"\r\n#include \"RX600\/src.hpp\"\r\n#include \"RX600\/sdhi.hpp\"\r\n#include \"RX600\/mmcif.hpp\"\r\n#include \"RX600\/pdc.hpp\"\r\n#include \"RX600\/standby_ram.hpp\"\r\n#include \"RX600\/crc.hpp\"\r\n#include \"RX600\/doc.hpp\"\r\n\r\n#include \"RX600\/system_io.hpp\"\r\n#include \"RX600\/dmac_mgr.hpp\"\r\n#include \"RX600\/ether_io.hpp\"\r\n#include \"RX600\/adc_in.hpp\"\r\n#include \"RX600\/dac_out.hpp\"\r\n#include \"RX600\/flash_io.hpp\"\r\n#include \"RX600\/sdhi_io.hpp\"\r\n#include \"RX600\/ssi_io.hpp\"\r\n\r\n#elif defined(SIG_RX65N)\r\n#include \"RX600\/lvda.hpp\"\r\n#include \"RX600\/bus.hpp\"\r\n#include \"RX600\/cac.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/mtu3.hpp\"\r\n#include \"RX600\/poe3.hpp\"\r\n#include \"RX600\/tmr.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/elc.hpp\"\r\n#include \"RX600\/exdmac.hpp\"\r\n#include \"RX600\/mpc.hpp\"\r\n#include \"RX600\/tpu.hpp\"\r\n#include \"RX600\/ppg.hpp\"\r\n#include \"RX600\/cmtw.hpp\"\r\n#include \"RX600\/qspi.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX600\/s12adf.hpp\"\r\n#include \"RX600\/r12da.hpp\"\r\n#include \"RX600\/sdram.hpp\"\r\n#include \"RX600\/etherc.hpp\"\r\n#include \"RX600\/edmac.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/rtc.hpp\"\r\n#include \"RX600\/wdta.hpp\"\r\n#include \"RX600\/flash.hpp\"\r\n#include \"RX600\/sdhi.hpp\"\r\n#include \"RX600\/sdsi.hpp\"\r\n#include \"RX600\/mmcif.hpp\"\r\n#include \"RX600\/pdc.hpp\"\r\n#include \"RX600\/standby_ram.hpp\"\r\n#include \"RX600\/glcdc.hpp\"\r\n#include \"RX600\/drw2d.hpp\"\r\n#include \"RX600\/crca.hpp\"\r\n#include \"RX600\/doc.hpp\"\r\n\r\n#include \"RX600\/system_io.hpp\"\r\n#include \"RX600\/rtc_io.hpp\"\r\n#include \"RX600\/dmac_mgr.hpp\"\r\n#include \"RX600\/ether_io.hpp\"\r\n#include \"RX600\/sdhi_io.hpp\"\r\n#include \"RX600\/glcdc_mgr.hpp\"\r\n#include \"RX600\/drw2d_mgr.hpp\"\r\n#include \"RX600\/adc_in.hpp\"\r\n#include \"RX600\/dac_out.hpp\"\r\n#include \"RX600\/flash_io.hpp\"\r\n\r\n#elif defined(SIG_RX72M) || defined(SIG_RX72N)\r\n#include \"RX600\/lvda.hpp\"\r\n#include \"RX600\/bus.hpp\"\r\n#include \"RX600\/cac.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/mtu3.hpp\"\r\n#include \"RX600\/poe3.hpp\"\r\n#include \"RX600\/tmr.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/elc.hpp\"\r\n#include \"RX600\/exdmac.hpp\"\r\n#include \"RX600\/mpc.hpp\"\r\n#include \"RX600\/tpu.hpp\"\r\n#include \"RX600\/ppg.hpp\"\r\n#include \"RX600\/gptw.hpp\"\r\n#include \"RX600\/ppg.hpp\"\r\n#include \"RX600\/cmtw.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX600\/qspi.hpp\"\r\n#include \"RX600\/s12adf.hpp\"\r\n#include \"RX600\/r12da.hpp\"\r\n#include \"RX600\/sdram.hpp\"\r\n#include \"RX600\/etherc.hpp\"\r\n#include \"RX600\/eptpc.hpp\"\r\n#include \"RX600\/edmac.hpp\"\r\n#include \"RX600\/pmgi.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/scif.hpp\"\r\n#include \"RX600\/rtc.hpp\"\r\n#include \"RX600\/wdta.hpp\"\r\n#include \"RX600\/flash.hpp\"\r\n#include \"RX600\/ssie.hpp\"\r\n#include \"RX600\/sdhi.hpp\"\r\n#include \"RX600\/mmcif.hpp\"\r\n#include \"RX600\/pdc.hpp\"\r\n#if defined(SIG_RX72M)\r\n#include \"RX600\/dsmif.hpp\"\r\n#endif\r\n#include \"RX600\/standby_ram.hpp\"\r\n#include \"RX600\/glcdc.hpp\"\r\n#include \"RX600\/drw2d.hpp\"\r\n#include \"RX600\/crca.hpp\"\r\n#include \"RX600\/doc.hpp\"\r\n\r\n#include \"RX600\/system_io.hpp\"\r\n#include \"RX600\/dmac_mgr.hpp\"\r\n#include \"RX600\/rtc_io.hpp\"\r\n#include \"RX600\/sdhi_io.hpp\"\r\n#include \"RX600\/ssie_io.hpp\"\r\n#include \"RX600\/glcdc_mgr.hpp\"\r\n#include \"RX600\/drw2d_mgr.hpp\"\r\n#include \"RX600\/adc_in.hpp\"\r\n#include \"RX600\/dac_out.hpp\"\r\n#include \"RX600\/flash_io.hpp\"\r\n#include \"RX600\/ether_io.hpp\"\r\n\r\n#elif defined(SIG_RX66T) || defined(SIG_RX72T)\r\n#include \"RX600\/lvda.hpp\"\r\n#include \"RX600\/bus.hpp\"\r\n#include \"RX600\/cac.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/mtu3.hpp\"\r\n#include \"RX600\/poe3.hpp\"\r\n#include \"RX600\/tmr.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/elc.hpp\"\r\n#include \"RX600\/mpc.hpp\"\r\n#include \"RX600\/gptw.hpp\"\r\n#include \"RX600\/hrpwm.hpp\"\r\n#include \"RX600\/poeg.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX72T\/s12adh.hpp\"\r\n#include \"RX600\/r12da.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/wdta.hpp\"\r\n#include \"RX600\/flash.hpp\"\r\n#include \"RX600\/cmpc.hpp\"\r\n#include \"RX600\/crca.hpp\"\r\n#include \"RX600\/doc.hpp\"\r\n\r\n#include \"RX600\/system_io.hpp\"\r\n#include \"RX600\/dmac_mgr.hpp\"\r\n#include \"RX600\/dac_out.hpp\"\r\n#include \"RX600\/flash_io.hpp\"\r\n\r\n#else\r\n#  error \"renesas.hpp: Requires SIG_RXxxx to be defined\"\r\n#endif\r\n\r\n\/\/ RX マイコン共通ペリフェラル\r\n#include \"RX600\/dtc.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX600\/iwdt.hpp\"\r\n#include \"RX600\/sci.hpp\"\r\n#include \"RX600\/riic.hpp\"\r\n#include \"RX600\/rspi.hpp\"\r\n#include \"RX600\/mpu.hpp\"\r\nUpdate: edit path for poe3.hpp#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tルネサス RX ペリフェラル/デバイス選択\r\n    @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2016, 2022 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"common\/byte_order.h\"\r\n#include \"common\/vect.h\"\r\n#include \"common\/delay.hpp\"\r\n#include \"common\/device.hpp\"\r\n\r\n#if defined(SIG_RX63T)\r\n#include \"RX63T\/lvda.hpp\"\r\n#include \"RX63T\/bus.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX63T\/port.hpp\"\r\n#include \"RX600\/mtu3.hpp\"\r\n#include \"RX63T\/poe3.hpp\"\r\n#include \"RX63T\/gpt.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX600\/crc.hpp\"\r\n#include \"RX63T\/s12adb.hpp\"\r\n#include \"RX63T\/ad.hpp\"\r\n#include \"RX63T\/da.hpp\"\r\n#include \"RX600\/doc.hpp\"\r\n#include \"RX63T\/dpc.hpp\"\r\n#include \"RX63T\/flash.hpp\"\r\n\r\n#include \"RX63T\/system_io.hpp\"\r\n\r\n#elif defined(SIG_RX621) || defined(SIG_RX62N)\r\n#include \"RX62x\/lvd.hpp\"\r\n#include \"RX62x\/bus.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/exdmac.hpp\"\r\n#include \"RX62x\/port.hpp\"\r\n#include \"RX62x\/mtu2.hpp\"\r\n#include \"RX62x\/poe2.hpp\"\r\n#include \"RX600\/ppg.hpp\"\r\n#include \"RX600\/tmr.hpp\"\r\n#include \"RX62x\/rtc.hpp\"\r\n#include \"RX62x\/wdt.hpp\"\r\n#include \"RX600\/etherc.hpp\"\r\n#include \"RX600\/edmac.hpp\"\r\n#include \"RX62x\/usb.hpp\"\r\n#include \"RX600\/crc.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX62x\/s12ad.hpp\"\r\n#include \"RX62x\/ad.hpp\"\r\n#include \"RX62x\/da.hpp\"\r\n#include \"RX62x\/flash.hpp\"\r\n\r\n#include \"RX62x\/system_io.hpp\"\r\n#include \"RX62x\/flash_io.hpp\"\r\n#include \"RX600\/dmac_mgr.hpp\"\r\n#include \"RX24T\/dac_out.hpp\"\r\n\r\n#elif defined(SIG_RX24T)\r\n#include \"RX24T\/lvda.hpp\"\r\n#include \"RX600\/bus.hpp\"\r\n#include \"RX600\/cac.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/mtu3.hpp\"\r\n#include \"RX24T\/poe3.hpp\"\r\n#include \"RX600\/tmr.hpp\"\r\n#include \"RX600\/gpt.hpp\"\r\n#include \"RX24T\/s12ad.hpp\"\r\n#include \"RX24T\/da.hpp\"\r\n#include \"RX600\/cmpc.hpp\"\r\n#include \"RX24T\/flash.hpp\"\r\n#include \"RX600\/crc.hpp\"\r\n#include \"RX600\/doc.hpp\"\r\n\r\n#include \"RX24T\/system_io.hpp\"\r\n#include \"RX24T\/flash_io.hpp\"\r\n#include \"RX24T\/adc_in.hpp\"\r\n#include \"RX24T\/dac_out.hpp\"\r\n\r\n#elif defined(SIG_RX64M) || defined(SIG_RX71M)\r\n#include \"RX600\/lvda.hpp\"\r\n#include \"RX600\/bus.hpp\"\r\n#include \"RX600\/cac.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/mtu3.hpp\"\r\n#include \"RX64M\/poe3.hpp\"\r\n#include \"RX600\/tmr.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/elc.hpp\"\r\n#include \"RX600\/exdmac.hpp\"\r\n#include \"RX600\/mpc.hpp\"\r\n#include \"RX600\/tpu.hpp\"\r\n#include \"RX600\/gpt.hpp\"\r\n#include \"RX600\/ppg.hpp\"\r\n#include \"RX600\/cmtw.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX600\/qspi.hpp\"\r\n#include \"RX600\/s12adc.hpp\"\r\n#include \"RX600\/r12da.hpp\"\r\n#include \"RX600\/sdram.hpp\"\r\n#include \"RX600\/etherc.hpp\"\r\n#include \"RX600\/eptpc.hpp\"\r\n#include \"RX600\/edmac.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/usba.hpp\"\r\n#include \"RX600\/scif.hpp\"\r\n#include \"RX600\/rtc.hpp\"\r\n#include \"RX600\/rtc_io.hpp\"\r\n#include \"RX600\/wdta.hpp\"\r\n#include \"RX600\/flash.hpp\"\r\n#include \"RX600\/ssi.hpp\"\r\n#include \"RX600\/src.hpp\"\r\n#include \"RX600\/sdhi.hpp\"\r\n#include \"RX600\/mmcif.hpp\"\r\n#include \"RX600\/pdc.hpp\"\r\n#include \"RX600\/standby_ram.hpp\"\r\n#include \"RX600\/crc.hpp\"\r\n#include \"RX600\/doc.hpp\"\r\n\r\n#include \"RX600\/system_io.hpp\"\r\n#include \"RX600\/dmac_mgr.hpp\"\r\n#include \"RX600\/ether_io.hpp\"\r\n#include \"RX600\/adc_in.hpp\"\r\n#include \"RX600\/dac_out.hpp\"\r\n#include \"RX600\/flash_io.hpp\"\r\n#include \"RX600\/sdhi_io.hpp\"\r\n#include \"RX600\/ssi_io.hpp\"\r\n\r\n#elif defined(SIG_RX65N)\r\n#include \"RX600\/lvda.hpp\"\r\n#include \"RX600\/bus.hpp\"\r\n#include \"RX600\/cac.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/mtu3.hpp\"\r\n#include \"RX65x\/poe3.hpp\"\r\n#include \"RX600\/tmr.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/elc.hpp\"\r\n#include \"RX600\/exdmac.hpp\"\r\n#include \"RX600\/mpc.hpp\"\r\n#include \"RX600\/tpu.hpp\"\r\n#include \"RX600\/ppg.hpp\"\r\n#include \"RX600\/cmtw.hpp\"\r\n#include \"RX600\/qspi.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX600\/s12adf.hpp\"\r\n#include \"RX600\/r12da.hpp\"\r\n#include \"RX600\/sdram.hpp\"\r\n#include \"RX600\/etherc.hpp\"\r\n#include \"RX600\/edmac.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/rtc.hpp\"\r\n#include \"RX600\/wdta.hpp\"\r\n#include \"RX600\/flash.hpp\"\r\n#include \"RX600\/sdhi.hpp\"\r\n#include \"RX600\/sdsi.hpp\"\r\n#include \"RX600\/mmcif.hpp\"\r\n#include \"RX600\/pdc.hpp\"\r\n#include \"RX600\/standby_ram.hpp\"\r\n#include \"RX600\/glcdc.hpp\"\r\n#include \"RX600\/drw2d.hpp\"\r\n#include \"RX600\/crca.hpp\"\r\n#include \"RX600\/doc.hpp\"\r\n\r\n#include \"RX600\/system_io.hpp\"\r\n#include \"RX600\/rtc_io.hpp\"\r\n#include \"RX600\/dmac_mgr.hpp\"\r\n#include \"RX600\/ether_io.hpp\"\r\n#include \"RX600\/sdhi_io.hpp\"\r\n#include \"RX600\/glcdc_mgr.hpp\"\r\n#include \"RX600\/drw2d_mgr.hpp\"\r\n#include \"RX600\/adc_in.hpp\"\r\n#include \"RX600\/dac_out.hpp\"\r\n#include \"RX600\/flash_io.hpp\"\r\n\r\n#elif defined(SIG_RX72M) || defined(SIG_RX72N)\r\n#include \"RX600\/lvda.hpp\"\r\n#include \"RX600\/bus.hpp\"\r\n#include \"RX600\/cac.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/mtu3.hpp\"\r\n#include \"RX72N\/poe3.hpp\"\r\n#include \"RX600\/tmr.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/elc.hpp\"\r\n#include \"RX600\/exdmac.hpp\"\r\n#include \"RX600\/mpc.hpp\"\r\n#include \"RX600\/tpu.hpp\"\r\n#include \"RX600\/ppg.hpp\"\r\n#include \"RX600\/gptw.hpp\"\r\n#include \"RX600\/ppg.hpp\"\r\n#include \"RX600\/cmtw.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX600\/qspi.hpp\"\r\n#include \"RX600\/s12adf.hpp\"\r\n#include \"RX600\/r12da.hpp\"\r\n#include \"RX600\/sdram.hpp\"\r\n#include \"RX600\/etherc.hpp\"\r\n#include \"RX600\/eptpc.hpp\"\r\n#include \"RX600\/edmac.hpp\"\r\n#include \"RX600\/pmgi.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/scif.hpp\"\r\n#include \"RX600\/rtc.hpp\"\r\n#include \"RX600\/wdta.hpp\"\r\n#include \"RX600\/flash.hpp\"\r\n#include \"RX600\/ssie.hpp\"\r\n#include \"RX600\/sdhi.hpp\"\r\n#include \"RX600\/mmcif.hpp\"\r\n#include \"RX600\/pdc.hpp\"\r\n#if defined(SIG_RX72M)\r\n#include \"RX600\/dsmif.hpp\"\r\n#endif\r\n#include \"RX600\/standby_ram.hpp\"\r\n#include \"RX600\/glcdc.hpp\"\r\n#include \"RX600\/drw2d.hpp\"\r\n#include \"RX600\/crca.hpp\"\r\n#include \"RX600\/doc.hpp\"\r\n\r\n#include \"RX600\/system_io.hpp\"\r\n#include \"RX600\/dmac_mgr.hpp\"\r\n#include \"RX600\/rtc_io.hpp\"\r\n#include \"RX600\/sdhi_io.hpp\"\r\n#include \"RX600\/ssie_io.hpp\"\r\n#include \"RX600\/glcdc_mgr.hpp\"\r\n#include \"RX600\/drw2d_mgr.hpp\"\r\n#include \"RX600\/adc_in.hpp\"\r\n#include \"RX600\/dac_out.hpp\"\r\n#include \"RX600\/flash_io.hpp\"\r\n#include \"RX600\/ether_io.hpp\"\r\n\r\n#elif defined(SIG_RX66T) || defined(SIG_RX72T)\r\n#include \"RX600\/lvda.hpp\"\r\n#include \"RX600\/bus.hpp\"\r\n#include \"RX600\/cac.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/mtu3.hpp\"\r\n#include \"RX66T\/poe3.hpp\"\r\n#include \"RX600\/tmr.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/elc.hpp\"\r\n#include \"RX600\/mpc.hpp\"\r\n#include \"RX600\/gptw.hpp\"\r\n#include \"RX600\/hrpwm.hpp\"\r\n#include \"RX600\/poeg.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX72T\/s12adh.hpp\"\r\n#include \"RX600\/r12da.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/wdta.hpp\"\r\n#include \"RX600\/flash.hpp\"\r\n#include \"RX600\/cmpc.hpp\"\r\n#include \"RX600\/crca.hpp\"\r\n#include \"RX600\/doc.hpp\"\r\n\r\n#include \"RX600\/system_io.hpp\"\r\n#include \"RX600\/dmac_mgr.hpp\"\r\n#include \"RX600\/dac_out.hpp\"\r\n#include \"RX600\/flash_io.hpp\"\r\n\r\n#else\r\n#  error \"renesas.hpp: Requires SIG_RXxxx to be defined\"\r\n#endif\r\n\r\n\/\/ RX マイコン共通ペリフェラル\r\n#include \"RX600\/dtc.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX600\/iwdt.hpp\"\r\n#include \"RX600\/sci.hpp\"\r\n#include \"RX600\/riic.hpp\"\r\n#include \"RX600\/rspi.hpp\"\r\n#include \"RX600\/mpu.hpp\"\r\n<|endoftext|>"}
{"text":"\/******************************************************************************\\\n *           ___        __                                                    *\n *          \/\\_ \\    __\/\\ \\                                                   *\n *          \\\/\/\\ \\  \/\\_\\ \\ \\____    ___   _____   _____      __               *\n *            \\ \\ \\ \\\/\\ \\ \\ '__`\\  \/'___\\\/\\ '__`\\\/\\ '__`\\  \/'__`\\             *\n *             \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_           *\n *             \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\          *\n *             \\\/____\/ \\\/_\/\\\/___\/  \\\/____\/ \\ \\ \\\/  \\ \\ \\\/  \\\/__\/\\\/_\/          *\n *                                          \\ \\_\\   \\ \\_\\                     *\n *                                           \\\/_\/    \\\/_\/                     *\n *                                                                            *\n * Copyright (C) 2011, 2012                                                   *\n * Dominik Charousset                      *\n *                                                                            *\n * This file is part of libcppa.                                              *\n * libcppa is free software: you can redistribute it and\/or modify it under   *\n * the terms of the GNU Lesser General Public License as published by the     *\n * Free Software Foundation, either version 3 of the License                  *\n * or (at your option) any later version.                                     *\n *                                                                            *\n * libcppa is distributed in the hope that it will be useful,                 *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of             *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                       *\n * See the GNU Lesser General Public License for more details.                *\n *                                                                            *\n * You should have received a copy of the GNU Lesser General Public License   *\n * along with libcppa. If not, see .            *\n\\******************************************************************************\/\n\n\n#include \"cppa\/cppa.hpp\"\n#include \"cppa\/exception.hpp\"\n#include \"cppa\/detail\/task_scheduler.hpp\"\n#include \"cppa\/detail\/abstract_scheduled_actor.hpp\"\n#include \"cppa\/detail\/yield_interface.hpp\"\n\nnamespace cppa { namespace detail {\n\nnamespace { void dummy_enqueue(void*, abstract_scheduled_actor*) { } }\n\nabstract_scheduled_actor::abstract_scheduled_actor()\n    : next(nullptr)\n    , m_state(abstract_scheduled_actor::done)\n    , m_enqueue_to_scheduler(dummy_enqueue, static_cast(nullptr), this)\n    , m_has_pending_timeout_request(false)\n    , m_active_timeout_id(0)\n{\n}\n\nabstract_scheduled_actor::resume_callback::~resume_callback()\n{\n}\n\nvoid abstract_scheduled_actor::quit(std::uint32_t reason)\n{\n    cleanup(reason);\n    throw actor_exited(reason);\n}\n\nvoid abstract_scheduled_actor::enqueue_node(queue_node* node)\n{\n    if (m_mailbox._push_back(node))\n    {\n        for (;;)\n        {\n            int state = m_state.load();\n            switch (state)\n            {\n                case blocked:\n                {\n                    if (m_state.compare_exchange_weak(state, ready))\n                    {\n                        m_enqueue_to_scheduler();\n                        return;\n                    }\n                    break;\n                }\n                case about_to_block:\n                {\n                    if (m_state.compare_exchange_weak(state, ready))\n                    {\n                        return;\n                    }\n                    break;\n                }\n                default: return;\n            }\n        }\n    }\n}\n\nvoid abstract_scheduled_actor::enqueue(actor* sender, any_tuple&& msg)\n{\n    enqueue_node(new queue_node(sender, std::move(msg)));\n}\n\nvoid abstract_scheduled_actor::enqueue(actor* sender, const any_tuple& msg)\n{\n    enqueue_node(new queue_node(sender, msg));\n}\n\nint abstract_scheduled_actor::compare_exchange_state(int expected,\n                                                     int new_value)\n{\n    int e = expected;\n    do\n    {\n        if (m_state.compare_exchange_weak(e, new_value))\n        {\n            return new_value;\n        }\n    }\n    while (e == expected);\n    return e;\n}\n\nvoid abstract_scheduled_actor::request_timeout(const util::duration& d)\n{\n    future_send(this, d, atom(\":Timeout\"), ++m_active_timeout_id);\n    m_has_pending_timeout_request = true;\n}\n\nauto abstract_scheduled_actor::filter_msg(const any_tuple& msg) -> filter_result\n{\n    if (m_pattern(msg))\n    {\n        auto v0 = *reinterpret_cast(msg.at(0));\n        auto v1 = *reinterpret_cast(msg.at(1));\n        if (v0 == atom(\":Exit\"))\n        {\n            if (m_trap_exit == false)\n            {\n                if (v1 != exit_reason::normal)\n                {\n                    quit(v1);\n                }\n                return normal_exit_signal;\n            }\n        }\n        else if (v0 == atom(\":Timeout\"))\n        {\n            return (v1 == m_active_timeout_id) ? timeout_message\n                                               : expired_timeout_message;\n        }\n    }\n    return ordinary_message;\n}\n\nauto abstract_scheduled_actor::dq(std::unique_ptr& node,\n                                  invoke_rules_base& rules,\n                                  queue_node_buffer& buffer) -> dq_result\n{\n    switch (filter_msg(node->msg))\n    {\n        case normal_exit_signal:\n        case expired_timeout_message:\n        {\n            \/\/ skip message\n            return dq_indeterminate;\n        }\n        case timeout_message:\n        {\n            \/\/ m_active_timeout_id is already invalid\n            m_has_pending_timeout_request = false;\n            \/\/ restore mailbox before calling client\n            if (!buffer.empty())\n            {\n                m_mailbox.push_front(std::move(buffer));\n                buffer.clear();\n            }\n            return dq_timeout_occured;\n        }\n        default: break;\n    }\n    auto imd = rules.get_intermediate(node->msg);\n    if (imd)\n    {\n        m_last_dequeued = std::move(node->msg);\n        m_last_sender = std::move(node->sender);\n        \/\/ restore mailbox before invoking imd\n        if (!buffer.empty())\n        {\n            m_mailbox.push_front(std::move(buffer));\n            buffer.clear();\n        }\n        \/\/ expire pending request\n        if (m_has_pending_timeout_request)\n        {\n            ++m_active_timeout_id;\n            m_has_pending_timeout_request = false;\n        }\n        imd->invoke();\n        return dq_done;\n    }\n    else\n    {\n        buffer.push_back(node.release());\n        return dq_indeterminate;\n    }\n}\n\n\/\/ dummy\n\nvoid scheduled_actor_dummy::resume(util::fiber*, resume_callback*)\n{\n}\n\nvoid scheduled_actor_dummy::quit(std::uint32_t)\n{\n}\n\nvoid scheduled_actor_dummy::dequeue(invoke_rules&)\n{\n}\n\nvoid scheduled_actor_dummy::dequeue(timed_invoke_rules&)\n{\n}\n\nvoid scheduled_actor_dummy::link_to(intrusive_ptr&)\n{\n}\n\nvoid scheduled_actor_dummy::unlink_from(intrusive_ptr&)\n{\n}\n\nbool scheduled_actor_dummy::establish_backlink(intrusive_ptr&)\n{\n    return false;\n}\n\nbool scheduled_actor_dummy::remove_backlink(intrusive_ptr&)\n{\n    return false;\n}\n\nvoid scheduled_actor_dummy::detach(const attachable::token&)\n{\n}\n\nbool scheduled_actor_dummy::attach(attachable*)\n{\n    return false;\n}\n\n} } \/\/ namespace cppa::detail\ncoding style\/******************************************************************************\\\n *           ___        __                                                    *\n *          \/\\_ \\    __\/\\ \\                                                   *\n *          \\\/\/\\ \\  \/\\_\\ \\ \\____    ___   _____   _____      __               *\n *            \\ \\ \\ \\\/\\ \\ \\ '__`\\  \/'___\\\/\\ '__`\\\/\\ '__`\\  \/'__`\\             *\n *             \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_           *\n *             \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\          *\n *             \\\/____\/ \\\/_\/\\\/___\/  \\\/____\/ \\ \\ \\\/  \\ \\ \\\/  \\\/__\/\\\/_\/          *\n *                                          \\ \\_\\   \\ \\_\\                     *\n *                                           \\\/_\/    \\\/_\/                     *\n *                                                                            *\n * Copyright (C) 2011, 2012                                                   *\n * Dominik Charousset                      *\n *                                                                            *\n * This file is part of libcppa.                                              *\n * libcppa is free software: you can redistribute it and\/or modify it under   *\n * the terms of the GNU Lesser General Public License as published by the     *\n * Free Software Foundation, either version 3 of the License                  *\n * or (at your option) any later version.                                     *\n *                                                                            *\n * libcppa is distributed in the hope that it will be useful,                 *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of             *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                       *\n * See the GNU Lesser General Public License for more details.                *\n *                                                                            *\n * You should have received a copy of the GNU Lesser General Public License   *\n * along with libcppa. If not, see .            *\n\\******************************************************************************\/\n\n\n#include \"cppa\/cppa.hpp\"\n#include \"cppa\/exception.hpp\"\n#include \"cppa\/detail\/task_scheduler.hpp\"\n#include \"cppa\/detail\/abstract_scheduled_actor.hpp\"\n#include \"cppa\/detail\/yield_interface.hpp\"\n\nnamespace cppa { namespace detail {\n\nnamespace { void dummy_enqueue(void*, abstract_scheduled_actor*) { } }\n\nabstract_scheduled_actor::abstract_scheduled_actor()\n    : next(nullptr)\n    , m_state(abstract_scheduled_actor::done)\n    , m_enqueue_to_scheduler(dummy_enqueue, static_cast(nullptr), this)\n    , m_has_pending_timeout_request(false)\n    , m_active_timeout_id(0)\n{\n}\n\nabstract_scheduled_actor::resume_callback::~resume_callback()\n{\n}\n\nvoid abstract_scheduled_actor::quit(std::uint32_t reason)\n{\n    cleanup(reason);\n    throw actor_exited(reason);\n}\n\nvoid abstract_scheduled_actor::enqueue_node(queue_node* node)\n{\n    if (m_mailbox._push_back(node))\n    {\n        for (;;)\n        {\n            int state = m_state.load();\n            switch (state)\n            {\n                case blocked:\n                {\n                    if (m_state.compare_exchange_weak(state, ready))\n                    {\n                        m_enqueue_to_scheduler();\n                        return;\n                    }\n                    break;\n                }\n                case about_to_block:\n                {\n                    if (m_state.compare_exchange_weak(state, ready))\n                    {\n                        return;\n                    }\n                    break;\n                }\n                default: return;\n            }\n        }\n    }\n}\n\nvoid abstract_scheduled_actor::enqueue(actor* sender, any_tuple&& msg)\n{\n    enqueue_node(new queue_node(sender, std::move(msg)));\n}\n\nvoid abstract_scheduled_actor::enqueue(actor* sender, any_tuple const& msg)\n{\n    enqueue_node(new queue_node(sender, msg));\n}\n\nint abstract_scheduled_actor::compare_exchange_state(int expected,\n                                                     int new_value)\n{\n    int e = expected;\n    do\n    {\n        if (m_state.compare_exchange_weak(e, new_value))\n        {\n            return new_value;\n        }\n    }\n    while (e == expected);\n    return e;\n}\n\nvoid abstract_scheduled_actor::request_timeout(util::duration const& d)\n{\n    future_send(this, d, atom(\":Timeout\"), ++m_active_timeout_id);\n    m_has_pending_timeout_request = true;\n}\n\nauto abstract_scheduled_actor::filter_msg(const any_tuple& msg) -> filter_result\n{\n    if (m_pattern(msg))\n    {\n        auto v0 = *reinterpret_cast(msg.at(0));\n        auto v1 = *reinterpret_cast(msg.at(1));\n        if (v0 == atom(\":Exit\"))\n        {\n            if (m_trap_exit == false)\n            {\n                if (v1 != exit_reason::normal)\n                {\n                    quit(v1);\n                }\n                return normal_exit_signal;\n            }\n        }\n        else if (v0 == atom(\":Timeout\"))\n        {\n            return (v1 == m_active_timeout_id) ? timeout_message\n                                               : expired_timeout_message;\n        }\n    }\n    return ordinary_message;\n}\n\nauto abstract_scheduled_actor::dq(std::unique_ptr& node,\n                                  invoke_rules_base& rules,\n                                  queue_node_buffer& buffer) -> dq_result\n{\n    switch (filter_msg(node->msg))\n    {\n        case normal_exit_signal:\n        case expired_timeout_message:\n        {\n            \/\/ skip message\n            return dq_indeterminate;\n        }\n        case timeout_message:\n        {\n            \/\/ m_active_timeout_id is already invalid\n            m_has_pending_timeout_request = false;\n            \/\/ restore mailbox before calling client\n            if (!buffer.empty())\n            {\n                m_mailbox.push_front(std::move(buffer));\n                buffer.clear();\n            }\n            return dq_timeout_occured;\n        }\n        default: break;\n    }\n    auto imd = rules.get_intermediate(node->msg);\n    if (imd)\n    {\n        m_last_dequeued = std::move(node->msg);\n        m_last_sender = std::move(node->sender);\n        \/\/ restore mailbox before invoking imd\n        if (!buffer.empty())\n        {\n            m_mailbox.push_front(std::move(buffer));\n            buffer.clear();\n        }\n        \/\/ expire pending request\n        if (m_has_pending_timeout_request)\n        {\n            ++m_active_timeout_id;\n            m_has_pending_timeout_request = false;\n        }\n        imd->invoke();\n        return dq_done;\n    }\n    else\n    {\n        buffer.push_back(node.release());\n        return dq_indeterminate;\n    }\n}\n\n\/\/ dummy\n\nvoid scheduled_actor_dummy::resume(util::fiber*, resume_callback*)\n{\n}\n\nvoid scheduled_actor_dummy::quit(std::uint32_t)\n{\n}\n\nvoid scheduled_actor_dummy::dequeue(invoke_rules&)\n{\n}\n\nvoid scheduled_actor_dummy::dequeue(timed_invoke_rules&)\n{\n}\n\nvoid scheduled_actor_dummy::link_to(intrusive_ptr&)\n{\n}\n\nvoid scheduled_actor_dummy::unlink_from(intrusive_ptr&)\n{\n}\n\nbool scheduled_actor_dummy::establish_backlink(intrusive_ptr&)\n{\n    return false;\n}\n\nbool scheduled_actor_dummy::remove_backlink(intrusive_ptr&)\n{\n    return false;\n}\n\nvoid scheduled_actor_dummy::detach(attachable::token const&)\n{\n}\n\nbool scheduled_actor_dummy::attach(attachable*)\n{\n    return false;\n}\n\n} } \/\/ namespace cppa::detail\n<|endoftext|>"}
{"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkCommon.h\"\n#include \"mitkTestingMacros.h\"\n#include \n#include \n#include \n#include \n#include \n\n\n\/** Documentation\n  *\n  * @brief Objects of this class can start an internal thread by calling the Start() method.\n  *        The thread is then logging messages until the method Stop() is called. The class\n  *        can be used to test if logging is thread-save by using multiple objects and let\n  *        them log simuntanously.\n  *\/\nclass mitkTestLoggingThread : public itk::Object\n{\npublic:\n\nmitkClassMacro(mitkTestLoggingThread,itk::Object);\nmitkNewMacro1Param(mitkTestLoggingThread,itk::MultiThreader::Pointer);\n\nint NumberOfMessages;\n\nprotected:\n\nmitkTestLoggingThread(itk::MultiThreader::Pointer MultiThreader)\n  {\n  ThreadID = -1;\n  NumberOfMessages = 0;\n  m_MultiThreader = MultiThreader;\n  }\n\nbool LoggingRunning;\n\nint ThreadID;\n\nitk::MultiThreader::Pointer m_MultiThreader;\n\nvoid LogMessages()\n  {\n\n  while(LoggingRunning)\n    {\n    MITK_INFO << \"Test info stream in thread\" << ThreadID << \"\\n even with newlines\";\n    MITK_WARN << \"Test warning stream in thread \" << ThreadID <<\". \"\n              << \"Even with a very long text, even without meaning or implied meaning or content, just a long sentence to see whether something has problems with long sentences or output in files or into windows or commandlines or whatever.\";\n    MITK_DEBUG << \"Test debugging stream in thread \" << ThreadID;\n    MITK_ERROR << \"Test error stream in thread \" << ThreadID;\n    MITK_FATAL << \"Test fatal stream in thread \" << ThreadID;\n\n    NumberOfMessages += 5;\n    }\n  }\n\n\nstatic ITK_THREAD_RETURN_TYPE ThreadStartTracking(void* pInfoStruct)\n  {\n  \/* extract this pointer from Thread Info structure *\/\n  struct itk::MultiThreader::ThreadInfoStruct * pInfo = (struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct;\n  if (pInfo == NULL)\n  {\n    return ITK_THREAD_RETURN_VALUE;\n  }\n  if (pInfo->UserData == NULL)\n  {\n    return ITK_THREAD_RETURN_VALUE;\n  }\n  mitkTestLoggingThread *thisthread = (mitkTestLoggingThread*)pInfo->UserData;\n\n  if (thisthread != NULL)\n    thisthread->LogMessages();\n\n  return ITK_THREAD_RETURN_VALUE;\n  }\n\npublic:\n\nint Start()\n  {\n  LoggingRunning = true;\n  this->ThreadID = m_MultiThreader->SpawnThread(this->ThreadStartTracking, this);\n  return ThreadID;\n  }\n\nvoid Stop()\n  {\n  LoggingRunning = false;\n  }\n\n};\n\n\/** Documentation\n *\n *  @brief This class holds static test methods to sturcture the test of the mitk logging mechanism.\n *\/\nclass mitkLogTestClass\n{\n\npublic:\n\nstatic void TestSimpleLog()\n    {\n    bool testSucceded = true;\n    try\n      {\n      MITK_INFO << \"Test info stream.\";\n      MITK_WARN << \"Test warning stream.\";\n      MITK_DEBUG << \"Test debugging stream.\"; \/\/only activated if cmake variable is on!\n                                              \/\/so no worries if you see no output for this line\n      MITK_ERROR << \"Test error stream.\";\n      MITK_FATAL << \"Test fatal stream.\";\n      }\n    catch(mitk::Exception e)\n      {\n      testSucceded = false;\n      }\n    MITK_TEST_CONDITION_REQUIRED(testSucceded,\"Test logging streams.\");\n    }\n\nstatic void TestObjectInfoLogging()\n    {\n    bool testSucceded = true;\n    try\n      {\n      int i = 123;\n      float f = .32234;\n      double d = 123123;\n      std::string testString = \"testString\";\n      std::stringstream testStringStream;\n      testStringStream << \"test\" << \"String\" << \"Stream\";\n      mitk::Point3D testMitkPoint;\n      testMitkPoint.Fill(2);\n\n      MITK_INFO << i;\n      MITK_INFO << f;\n      MITK_INFO << d;\n      MITK_INFO << testString;\n      MITK_INFO << testStringStream;\n      MITK_INFO << testMitkPoint;\n      }\n    catch(mitk::Exception e)\n      {\n      testSucceded = false;\n      }\n    MITK_TEST_CONDITION_REQUIRED(testSucceded,\"Test logging of object information.\");\n    }\n\n\n\n\nstatic void TestThreadSaveLog()\n    {\n    bool testSucceded = true;\n\n\n    try\n      {\n        std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() + \"\/testthreadlog.log\";\n        mitk::LoggingBackend::SetLogFile(filename.c_str());\n\n        unsigned int numberOfThreads = 20;\n        unsigned int threadRuntimeInMilliseconds = 2000;\n\n        std::vector threadIDs;\n        std::vector threads;\n\n        itk::MultiThreader::Pointer multiThreader = itk::MultiThreader::New();\n        for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx)\n        {\n          \/\/initialize threads...\n          mitkTestLoggingThread::Pointer newThread = mitkTestLoggingThread::New(multiThreader);\n          threads.push_back(newThread);\n          std::cout << \"Created \" << threadIdx << \". thread.\" << std::endl;\n        }\n\n        for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx)\n        {\n          \/\/start them\n          std::cout << \"Start \" << threadIdx << \". thread.\" << std::endl;\n          threadIDs.push_back( threads[threadIdx]->Start() );\n          std::cout << threadIdx << \". thread has ID \" << threadIDs[threadIdx] << std::endl;\n        }\n\n        \/\/wait for some time (milliseconds)\n        itksys::SystemTools::Delay( threadRuntimeInMilliseconds );\n\n\n        for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx)\n        {\n          \/\/stop them\n          std::cout << \"Stop \" << threadIdx << \". thread.\" << std::endl;\n          threads[threadIdx]->Stop();\n        }\n\n        for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx)\n        {\n          \/\/Wait for all threads to end\n          multiThreader->TerminateThread(threadIDs[threadIdx]);\n          std::cout << \"Terminated \" << threadIdx << \". thread (\" << threads[threadIdx]->NumberOfMessages << \" messages).\" << std::endl;\n        }\n\n      }\n    catch(std::exception e)\n      {\n        MITK_ERROR << \"exception during 'TestThreadSaveLog': \"<GetOptionDirectory() + \"\/testlog.log\";\n    mitk::LoggingBackend::SetLogFile(filename.c_str());\n    MITK_INFO << \"Test logging to default filename: \" << mitk::LoggingBackend::GetLogFile();\n    MITK_TEST_CONDITION_REQUIRED(itksys::SystemTools::FileExists(filename.c_str()),\"Testing if log file exists.\");\n    \/\/TODO delete log file?\n    }\n\nstatic void TestAddAndRemoveBackends()\n    {\n    mbilog::BackendCout myBackend = mbilog::BackendCout();\n    mbilog::RegisterBackend(&myBackend);\n    MITK_INFO << \"Test logging\";\n    mbilog::UnregisterBackend(&myBackend);\n\n    \/\/if no error occured until now, everything is ok\n    MITK_TEST_CONDITION_REQUIRED(true,\"Test add\/remove logging backend.\");\n    }\n\nstatic void  TestDefaultBackend()\n    {\n    \/\/not possible now, because we cannot unregister the mitk logging backend in the moment. If such a method is added to mbilog utility one may add this test.\n    }\n\n\n};\n\nint mitkLogTest(int \/* argc *\/, char* \/*argv*\/[])\n{\n  \/\/ always start with this!\n  MITK_TEST_BEGIN(\"Log\")\n\n  MITK_TEST_OUTPUT(<<\"TESTING ALL LOGGING OUTPUTS, ERROR MESSAGES ARE ALSO TESTED AND NOT MEANING AN ERROR OCCURED!\")\n\n  mitkLogTestClass::TestSimpleLog();\n  mitkLogTestClass::TestObjectInfoLogging();\n\n  mitkLogTestClass::TestLoggingToFile();\n  mitkLogTestClass::TestAddAndRemoveBackends();\n  mitkLogTestClass::TestThreadSaveLog();\n\n  \/\/ always end with this!\n  MITK_TEST_END()\n}\nTest logging to console AND to file\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkCommon.h\"\n#include \"mitkTestingMacros.h\"\n#include \n#include \n#include \n#include \n#include \n\n\n\/** Documentation\n  *\n  * @brief Objects of this class can start an internal thread by calling the Start() method.\n  *        The thread is then logging messages until the method Stop() is called. The class\n  *        can be used to test if logging is thread-save by using multiple objects and let\n  *        them log simuntanously.\n  *\/\nclass mitkTestLoggingThread : public itk::Object\n{\npublic:\n\nmitkClassMacro(mitkTestLoggingThread,itk::Object);\nmitkNewMacro1Param(mitkTestLoggingThread,itk::MultiThreader::Pointer);\n\nint NumberOfMessages;\n\nprotected:\n\nmitkTestLoggingThread(itk::MultiThreader::Pointer MultiThreader)\n  {\n  ThreadID = -1;\n  NumberOfMessages = 0;\n  m_MultiThreader = MultiThreader;\n  }\n\nbool LoggingRunning;\n\nint ThreadID;\n\nitk::MultiThreader::Pointer m_MultiThreader;\n\nvoid LogMessages()\n  {\n\n  while(LoggingRunning)\n    {\n    MITK_INFO << \"Test info stream in thread\" << ThreadID << \"\\n even with newlines\";\n    MITK_WARN << \"Test warning stream in thread \" << ThreadID <<\". \"\n              << \"Even with a very long text, even without meaning or implied meaning or content, just a long sentence to see whether something has problems with long sentences or output in files or into windows or commandlines or whatever.\";\n    MITK_DEBUG << \"Test debugging stream in thread \" << ThreadID;\n    MITK_ERROR << \"Test error stream in thread \" << ThreadID;\n    MITK_FATAL << \"Test fatal stream in thread \" << ThreadID;\n\n    NumberOfMessages += 5;\n    }\n  }\n\n\nstatic ITK_THREAD_RETURN_TYPE ThreadStartTracking(void* pInfoStruct)\n  {\n  \/* extract this pointer from Thread Info structure *\/\n  struct itk::MultiThreader::ThreadInfoStruct * pInfo = (struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct;\n  if (pInfo == NULL)\n  {\n    return ITK_THREAD_RETURN_VALUE;\n  }\n  if (pInfo->UserData == NULL)\n  {\n    return ITK_THREAD_RETURN_VALUE;\n  }\n  mitkTestLoggingThread *thisthread = (mitkTestLoggingThread*)pInfo->UserData;\n\n  if (thisthread != NULL)\n    thisthread->LogMessages();\n\n  return ITK_THREAD_RETURN_VALUE;\n  }\n\npublic:\n\nint Start()\n  {\n  LoggingRunning = true;\n  this->ThreadID = m_MultiThreader->SpawnThread(this->ThreadStartTracking, this);\n  return ThreadID;\n  }\n\nvoid Stop()\n  {\n  LoggingRunning = false;\n  }\n\n};\n\n\/** Documentation\n *\n *  @brief This class holds static test methods to sturcture the test of the mitk logging mechanism.\n *\/\nclass mitkLogTestClass\n{\n\npublic:\n\nstatic void TestSimpleLog()\n    {\n    bool testSucceded = true;\n    try\n      {\n      MITK_INFO << \"Test info stream.\";\n      MITK_WARN << \"Test warning stream.\";\n      MITK_DEBUG << \"Test debugging stream.\"; \/\/only activated if cmake variable is on!\n                                              \/\/so no worries if you see no output for this line\n      MITK_ERROR << \"Test error stream.\";\n      MITK_FATAL << \"Test fatal stream.\";\n      }\n    catch(mitk::Exception e)\n      {\n      testSucceded = false;\n      }\n    MITK_TEST_CONDITION_REQUIRED(testSucceded,\"Test logging streams.\");\n    }\n\nstatic void TestObjectInfoLogging()\n    {\n    bool testSucceded = true;\n    try\n      {\n      int i = 123;\n      float f = .32234;\n      double d = 123123;\n      std::string testString = \"testString\";\n      std::stringstream testStringStream;\n      testStringStream << \"test\" << \"String\" << \"Stream\";\n      mitk::Point3D testMitkPoint;\n      testMitkPoint.Fill(2);\n\n      MITK_INFO << i;\n      MITK_INFO << f;\n      MITK_INFO << d;\n      MITK_INFO << testString;\n      MITK_INFO << testStringStream;\n      MITK_INFO << testMitkPoint;\n      }\n    catch(mitk::Exception e)\n      {\n      testSucceded = false;\n      }\n    MITK_TEST_CONDITION_REQUIRED(testSucceded,\"Test logging of object information.\");\n    }\n\n\n\n\nstatic void TestThreadSaveLog(bool toFile)\n    {\n    bool testSucceded = true;\n\n\n    try\n      {\n        if (toFile)\n        {\n          std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() + \"\/testthreadlog.log\";\n          mitk::LoggingBackend::SetLogFile(filename.c_str());\n        }\n\n        unsigned int numberOfThreads = 20;\n        unsigned int threadRuntimeInMilliseconds = 2000;\n\n        std::vector threadIDs;\n        std::vector threads;\n\n        itk::MultiThreader::Pointer multiThreader = itk::MultiThreader::New();\n        for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx)\n        {\n          \/\/initialize threads...\n          mitkTestLoggingThread::Pointer newThread = mitkTestLoggingThread::New(multiThreader);\n          threads.push_back(newThread);\n          std::cout << \"Created \" << threadIdx << \". thread.\" << std::endl;\n        }\n\n        for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx)\n        {\n          \/\/start them\n          std::cout << \"Start \" << threadIdx << \". thread.\" << std::endl;\n          threadIDs.push_back( threads[threadIdx]->Start() );\n          std::cout << threadIdx << \". thread has ID \" << threadIDs[threadIdx] << std::endl;\n        }\n\n        \/\/wait for some time (milliseconds)\n        itksys::SystemTools::Delay( threadRuntimeInMilliseconds );\n\n\n        for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx)\n        {\n          \/\/stop them\n          std::cout << \"Stop \" << threadIdx << \". thread.\" << std::endl;\n          threads[threadIdx]->Stop();\n        }\n\n        for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx)\n        {\n          \/\/Wait for all threads to end\n          multiThreader->TerminateThread(threadIDs[threadIdx]);\n          std::cout << \"Terminated \" << threadIdx << \". thread (\" << threads[threadIdx]->NumberOfMessages << \" messages).\" << std::endl;\n        }\n\n      }\n    catch(std::exception e)\n      {\n        MITK_ERROR << \"exception during 'TestThreadSaveLog': \"<GetOptionDirectory() + \"\/testlog.log\";\n    mitk::LoggingBackend::SetLogFile(filename.c_str());\n    MITK_INFO << \"Test logging to default filename: \" << mitk::LoggingBackend::GetLogFile();\n    MITK_TEST_CONDITION_REQUIRED(itksys::SystemTools::FileExists(filename.c_str()),\"Testing if log file exists.\");\n    \/\/TODO delete log file?\n    }\n\nstatic void TestAddAndRemoveBackends()\n    {\n    mbilog::BackendCout myBackend = mbilog::BackendCout();\n    mbilog::RegisterBackend(&myBackend);\n    MITK_INFO << \"Test logging\";\n    mbilog::UnregisterBackend(&myBackend);\n\n    \/\/if no error occured until now, everything is ok\n    MITK_TEST_CONDITION_REQUIRED(true,\"Test add\/remove logging backend.\");\n    }\n\nstatic void  TestDefaultBackend()\n    {\n    \/\/not possible now, because we cannot unregister the mitk logging backend in the moment. If such a method is added to mbilog utility one may add this test.\n    }\n\n\n};\n\nint mitkLogTest(int \/* argc *\/, char* \/*argv*\/[])\n{\n  \/\/ always start with this!\n  MITK_TEST_BEGIN(\"Log\")\n\n  MITK_TEST_OUTPUT(<<\"TESTING ALL LOGGING OUTPUTS, ERROR MESSAGES ARE ALSO TESTED AND NOT MEANING AN ERROR OCCURED!\")\n\n  mitkLogTestClass::TestSimpleLog();\n  mitkLogTestClass::TestObjectInfoLogging();\n\n  mitkLogTestClass::TestLoggingToFile();\n  mitkLogTestClass::TestAddAndRemoveBackends();\n  mitkLogTestClass::TestThreadSaveLog( false ); \/\/ false = to console\n  mitkLogTestClass::TestThreadSaveLog( true );  \/\/ true = to file\n  \/\/ TODO actually test file somehow?\n\n  \/\/ always end with this!\n  MITK_TEST_END()\n}\n<|endoftext|>"}
{"text":"\/**\n * @file      ac_tlm_port.cpp\n * @author    Thiago Massariolli Sigrist   \n * \n * @author    The ArchC Team\n *            http:\/\/www.archc.org\/\n *\n *            Computer Systems Laboratory (LSC)\n *            IC-UNICAMP\n *            http:\/\/www.lsc.ic.unicamp.br\/\n * \n * @version   2.0alpha1\n * @date      Tue, 13 Dec 2005 20:09:00 -0200\n * \n * @brief     ArchC TLM initiator port class implementation.\n * \n * @attention Copyright (C) 2002-2005 --- The ArchC Team\n * \n *   This library is free software; you can redistribute it and\/or\n *   modify it under the terms of the GNU Lesser General Public\n *   License as published by the Free Software Foundation; either\n *   version 2.1 of the License, or (at your option) any later version.\n * \n *   This library is distributed in the hope that it will be useful,\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *   Lesser General Public License for more details.\n * \n * \n *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Standard includes\n\n\/\/ SystemC includes\n\n\/\/ ArchC includes\n#include \"ac_tlm_port.H\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ using statements\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Forward class declarations, needed to compile\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Constructors\n\n\/** \n * Default constructor.\n * \n * @param size Size or address range of the element to be attached.\n * \n *\/\nac_tlm_port::ac_tlm_port(char const* nm, uint32_t sz) : name(nm), size(sz) {}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Methods\n\n\/** \n * Reads a single word.\n * \n * @param buf Buffer into which the word will be copied.\n * @param address Address from where the word will be read.\n * @param wordsize Word size in bits.\n * \n *\/\nvoid ac_tlm_port::read(ac_ptr buf, uint32_t address, int wordsize) {\n  ac_tlm_req req;\n  ac_tlm_rsp rsp;\n\n  req.type = READ;\n  req.addr = address;\n  req.data = 0ULL;\n\n  rsp = (*this)->transport(req);\n\n  if (rsp.status == SUCCESS) {\n    switch (wordsize) {\n    case 8:\n      *(buf.ptr8) = (uint8_t) rsp.data;\n      break;\n    case 16:\n      *(buf.ptr16) = (uint16_t) rsp.data;\n      break;\n    case 32:\n      *(buf.ptr32) = (uint32_t) rsp.data;\n      break;\n    case 64:\n      *(buf.ptr64) = rsp.data;\n      break;\n    default:\n      break;\n    }\n  }\n}\n\n\/** \n * Reads multiple words.\n * \n * @param buf Buffer into which the words will be copied.\n * @param address Address from where the words will be read.\n * @param wordsize Word size in bits.\n * @param n_words Number of words to be read.\n * \n *\/\nvoid ac_tlm_port::read(ac_ptr buf, uint32_t address,\n\t\t       int wordsize, int n_words) {\n  ac_tlm_req req;\n  ac_tlm_rsp rsp;\n\n  req.type = READ;\n\n  switch (wordsize) {\n  case 8:\n    for (int i = 0; i < n_words; i++) {\n      req.addr = address + i;\n      req.data = 0ULL;\n      \n      rsp = (*this)->transport(req);\n      \n      if (rsp.status == SUCCESS) {\n\tfor (int j = 0; (i < n_words) && (j < 8); i++, j++) { \n\t  (buf.ptr8)[i] = ((uint8_t*)&rsp.data)[j];\n\t}\n      }\n    }\n    break;\n  case 16:\n    for (int i = 0; i < n_words; i++) {\n      req.addr = address + (i * sizeof(uint16_t));\n      req.data = 0ULL;\n      \n      rsp = (*this)->transport(req);\n      \n      if (rsp.status == SUCCESS) {\n\tfor (int j = 0; (i < n_words) && (j < 4); i++, j++) { \n\t  (buf.ptr16)[i] = ((uint16_t*)&rsp.data)[j];\n\t}\n      }\n    }\n    break;\n  case 32:\n    for (int i = 0; i < n_words; i++) {\n      req.addr = address + (i * sizeof(uint32_t));\n      req.data = 0ULL;\n      \n      rsp = (*this)->transport(req);\n      \n      if (rsp.status == SUCCESS) {\n\tfor (int j = 0; (i < n_words) && (j < 2); i++, j++) { \n\t  (buf.ptr32)[i] = ((uint32_t*)&rsp.data)[j];\n\t}\n      }\n    }\n    break;\n  case 64:\n    for (int i = 0; i < n_words; i++) {\n      req.addr = address + (i * sizeof(uint64_t));\n      req.data = 0ULL;\n      \n      rsp = (*this)->transport(req);\n      \n      if (rsp.status == SUCCESS) {\n\t(buf.ptr64)[i] = rsp.data;\n      }\n    }\n    break;\n  default:\n    break;\n  }\n}\n\n\/** \n * Writes a single word.\n * \n * @param buf Buffer from which the word will be copied.\n * @param address Address to where the word will be written.\n * @param wordsize Word size in bits.\n *\n *\/\nvoid ac_tlm_port::write(ac_ptr buf, uint32_t address, int wordsize) {\n  ac_tlm_req req;\n  ac_tlm_rsp rsp;\n\n\/\/   req.type = WRITE;\n\/\/   req.addr = address;\n\n  \/\/ It would be necessary to read 64 bits and mix the bits with the smaller\n  \/\/ words that will be written\n  switch (wordsize) {\n  case 8:\n    req.type = READ;\n    req.addr = address && 0xfffff000;\n    rsp = (*this)->transport(req);\n\n    req.type = WRITE;\n    ((uint8_t*)&(req.data))[address % sizeof(uint64_t)] = *(buf.ptr8);\n    rsp = (*this)->transport(req);\n    break;\n  case 16:\n    req.type = READ;\n    req.addr = address && 0xfffff000;\n    rsp = (*this)->transport(req);\n\n    req.type = WRITE;\n    ((uint16_t*)&(req.data))[(address % sizeof(uint64_t)) >> 1] =\n      *(buf.ptr16);\n    rsp = (*this)->transport(req);\n    break;\n  case 32:\n    req.type = READ;\n    req.addr = address && 0xfffff000;\n    rsp = (*this)->transport(req);\n\n    req.type = WRITE;\n    ((uint32_t*)&(req.data))[(address % sizeof(uint64_t)) >> 2] =\n      *(buf.ptr32);\n    rsp = (*this)->transport(req);\n    break;\n  case 64:\n    req.type = WRITE;\n    req.addr = address;\n    req.data = *(buf.ptr64);\n    rsp = (*this)->transport(req);\n    break;\n  default:\n    break;\n  }\n}\n\n\/** \n * Writes multiple words.\n * \n * @param buf Buffer from which the words will be copied.\n * @param address Address to where the words will be written.\n * @param wordsize Word size in bits.\n * @param n_words Number of words to be written.\n * \n *\/\nvoid ac_tlm_port::write(ac_ptr buf, uint32_t address,\n\t\t\tint wordsize, int n_words) {\n  ac_tlm_req req;\n  ac_tlm_rsp rsp;\n\n  req.type = WRITE;\n\n  switch (wordsize) {\n  case 8:\n    for (int i = 0; i < n_words; i++) {\n      req.addr = address + i;\n      for (int j = 0; (i < n_words) && (j < 8); j++, i++) {\n\t((uint8_t*)&req.data)[j] = (buf.ptr8)[i];\n      }\n      (*this)->transport(req);\n    }\n    break;\n  case 16:\n    for (int i = 0; i < n_words; i++) {\n      req.addr = address + (i * sizeof(uint16_t));\n      for (int j = 0; (i < n_words) && (j < 4); j++, i++) {\n\t((uint16_t*)&req.data)[j] = (buf.ptr16)[i];\n      }\n      (*this)->transport(req);\n    }\n    break;\n  case 32:\n    for (int i = 0; i < n_words; i++) {\n      req.addr = address + (i * sizeof(uint32_t));\n      for (int j = 0; (i < n_words) && (j < 2); j++, i++) {\n\t((uint32_t*)&req.data)[j] = (buf.ptr32)[i];\n      }\n      (*this)->transport(req);\n    }\n    break;\n  case 64:\n    for (int i = 0; i < n_words; i++) {\n      req.addr = address + (i * sizeof(uint64_t));\n      req.data = (buf.ptr64)[i];\n      (*this)->transport(req);\n    }\n    break;\n  default:\n    break;\n  }\n}\n\nuint32_t ac_tlm_port::get_size() const {\n  return size;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Destructors\n\n\/**\n * Default (virtual) destructor.\n * @return Nothing.\n *\/\nac_tlm_port::~ac_tlm_port() {}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nPorted bugfixes from Bruno Albertini to ac_tlm_port.\/**\n * @file      ac_tlm_port.cpp\n * @author    Thiago Massariolli Sigrist   \n * \n * @author    The ArchC Team\n *            http:\/\/www.archc.org\/\n *\n *            Computer Systems Laboratory (LSC)\n *            IC-UNICAMP\n *            http:\/\/www.lsc.ic.unicamp.br\/\n * \n * @version   2.0alpha1\n * @date      Tue, 13 Dec 2005 20:09:00 -0200\n * \n * @brief     ArchC TLM initiator port class implementation.\n * \n * @attention Copyright (C) 2002-2005 --- The ArchC Team\n * \n *   This library is free software; you can redistribute it and\/or\n *   modify it under the terms of the GNU Lesser General Public\n *   License as published by the Free Software Foundation; either\n *   version 2.1 of the License, or (at your option) any later version.\n * \n *   This library is distributed in the hope that it will be useful,\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *   Lesser General Public License for more details.\n * \n * \n *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Standard includes\n\n\/\/ SystemC includes\n\n\/\/ ArchC includes\n#include \"ac_tlm_port.H\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ using statements\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Forward class declarations, needed to compile\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Constructors\n\n\/** \n * Default constructor.\n * \n * @param size Size or address range of the element to be attached.\n * \n *\/\nac_tlm_port::ac_tlm_port(char const* nm, uint32_t sz) : name(nm), size(sz) {}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Methods\n\n\/** \n * Reads a single word.\n * \n * @param buf Buffer into which the word will be copied.\n * @param address Address from where the word will be read.\n * @param wordsize Word size in bits.\n * \n *\/\nvoid ac_tlm_port::read(ac_ptr buf, uint32_t address, int wordsize) {\n  ac_tlm_req req;\n  ac_tlm_rsp rsp;\n\n  req.type = READ;\n  req.addr = address;\n  req.data = 0ULL;\n\n  rsp = (*this)->transport(req);\n\n  if (rsp.status == SUCCESS) {\n    switch (wordsize) {\n    case 8:\n      *(buf.ptr8) = ((uint8_t*)&rsp.data)[0];\n      break;\n    case 16:\n      *(buf.ptr16) = ((uint16_t*)&rsp.data)[0];\n      break;\n    case 32:\n      *(buf.ptr32) = ((uint32_t*)&rsp.data)[0];\n      break;\n    case 64:\n      *(buf.ptr64) = rsp.data;\n      break;\n    default:\n      break;\n    }\n  }\n}\n\n\/** \n * Reads multiple words.\n * \n * @param buf Buffer into which the words will be copied.\n * @param address Address from where the words will be read.\n * @param wordsize Word size in bits.\n * @param n_words Number of words to be read.\n * \n *\/\nvoid ac_tlm_port::read(ac_ptr buf, uint32_t address,\n\t\t       int wordsize, int n_words) {\n  ac_tlm_req req;\n  ac_tlm_rsp rsp;\n\n  req.type = READ;\n\n  switch (wordsize) {\n  case 8:\n    for (int i = 0; i < n_words; i++) {\n      req.addr = address + i;\n      req.data = 0ULL;\n      \n      rsp = (*this)->transport(req);\n      \n      if (rsp.status == SUCCESS) {\n\tfor (int j = 0; (i < n_words) && (j < 8); i++, j++) { \n\t  (buf.ptr8)[i] = ((uint8_t*)&rsp.data)[j];\n\t}\n        i--;\n      }\n    }\n    break;\n  case 16:\n    for (int i = 0; i < n_words; i++) {\n      req.addr = address + (i * sizeof(uint16_t));\n      req.data = 0ULL;\n      \n      rsp = (*this)->transport(req);\n      \n      if (rsp.status == SUCCESS) {\n\tfor (int j = 0; (i < n_words) && (j < 4); i++, j++) { \n\t  (buf.ptr16)[i] = ((uint16_t*)&rsp.data)[j];\n\t}\n        i--;\n      }\n    }\n    break;\n  case 32:\n    for (int i = 0; i < n_words; i++) {\n      req.addr = address + (i * sizeof(uint32_t));\n      req.data = 0ULL;\n      \n      rsp = (*this)->transport(req);\n      \n      if (rsp.status == SUCCESS) {\n\tfor (int j = 0; (i < n_words) && (j < 2); i++, j++) { \n\t  (buf.ptr32)[i] = ((uint32_t*)&rsp.data)[j];\n\t}\n        i--;\n      }\n    }\n    break;\n  case 64:\n    for (int i = 0; i < n_words; i++) {\n      req.addr = address + (i * sizeof(uint64_t));\n      req.data = 0ULL;\n      \n      rsp = (*this)->transport(req);\n      \n      if (rsp.status == SUCCESS) {\n\t(buf.ptr64)[i] = rsp.data;\n      }\n    }\n    break;\n  default:\n    break;\n  }\n}\n\n\/** \n * Writes a single word.\n * \n * @param buf Buffer from which the word will be copied.\n * @param address Address to where the word will be written.\n * @param wordsize Word size in bits.\n *\n *\/\nvoid ac_tlm_port::write(ac_ptr buf, uint32_t address, int wordsize) {\n  ac_tlm_req req;\n  ac_tlm_rsp rsp;\n\n\/\/   req.type = WRITE;\n\/\/   req.addr = address;\n\n  \/\/ It would be necessary to read 64 bits and mix the bits with the smaller\n  \/\/ words that will be written\n  switch (wordsize) {\n  case 8:\n    req.type = READ;\n    req.addr = address;\n    rsp = (*this)->transport(req);\n\n    req.type = WRITE;\n    ((uint8_t*)&(req.data))[0] = *(buf.ptr8);\n    rsp = (*this)->transport(req);\n    break;\n  case 16:\n    req.type = READ;\n    req.addr = address;\n    rsp = (*this)->transport(req);\n\n    req.type = WRITE;\n    ((uint16_t*)&(req.data))[0] =\n      *(buf.ptr16);\n    rsp = (*this)->transport(req);\n    break;\n  case 32:\n    req.type = READ;\n    req.addr = address;\n    rsp = (*this)->transport(req);\n\n    req.type = WRITE;\n    ((uint32_t*)&(req.data))[0] =\n      *(buf.ptr32);\n    rsp = (*this)->transport(req);\n    break;\n  case 64:\n    req.type = WRITE;\n    req.addr = address;\n    req.data = *(buf.ptr64);\n    rsp = (*this)->transport(req);\n    break;\n  default:\n    break;\n  }\n}\n\n\/** \n * Writes multiple words.\n * \n * @param buf Buffer from which the words will be copied.\n * @param address Address to where the words will be written.\n * @param wordsize Word size in bits.\n * @param n_words Number of words to be written.\n * \n *\/\nvoid ac_tlm_port::write(ac_ptr buf, uint32_t address,\n\t\t\tint wordsize, int n_words) {\n  ac_tlm_req req;\n  ac_tlm_rsp rsp;\n\n  switch (wordsize) {\n  case 8:\n    for (int i = 0; i < n_words; i++) {\n      req.type = READ;\n      req.addr = address + i;\n      req.data = 0ULL;\n      rsp = (*this)->transport(req);\n\n      req.type = WRITE;\n      req.data = rsp.data;\n\n      for (int j = 0; (i < n_words) && (j < 8); j++, i++) {\n\t((uint8_t*)&req.data)[j] = (buf.ptr8)[i];\n      }\n      i--;\n      (*this)->transport(req);\n    }\n    break;\n  case 16:\n    for (int i = 0; i < n_words; i++) {\n      req.type = READ;\n      req.addr = address + (i * sizeof(uint16_t));\n      req.data = 0ULL;\n      rsp = (*this)->transport(req);\n\n      req.type = WRITE;\n      req.data = rsp.data;\n\n      for (int j = 0; (i < n_words) && (j < 4); j++, i++) {\n\t((uint16_t*)&req.data)[j] = (buf.ptr16)[i];\n      }\n      i--;\n      (*this)->transport(req);\n    }\n    break;\n  case 32:\n    for (int i = 0; i < n_words; i++) {\n      req.type = READ;\n      req.addr = address + (i * sizeof(uint32_t));\n      req.data = 0ULL;\n      rsp = (*this)->transport(req);\n\n      req.type = WRITE;\n      req.data = rsp.data;\n\n      for (int j = 0; (i < n_words) && (j < 2); j++, i++) {\n\t((uint32_t*)&req.data)[j] = (buf.ptr32)[i];\n      }\n      i--;\n      (*this)->transport(req);\n    }\n    break;\n  case 64:\n    for (int i = 0; i < n_words; i++) {\n      req.addr = address + (i * sizeof(uint64_t));\n      req.data = (buf.ptr64)[i];\n      (*this)->transport(req);\n    }\n    break;\n  default:\n    break;\n  }\n}\n\nuint32_t ac_tlm_port::get_size() const {\n  return size;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Destructors\n\n\/**\n * Default (virtual) destructor.\n * @return Nothing.\n *\/\nac_tlm_port::~ac_tlm_port() {}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n<|endoftext|>"}
{"text":"Prefer initial-caps versions of key phrases, if they exist.<|endoftext|>"}
{"text":"#include \"world.h\"\n#include \"room.h\"\n#include \"player.h\"\n#include \"exit.h\"\n#include \n#include \n\nusing namespace std;\n\nWorld::World() \n{\n\tRoom* sleeping_quarters = new Room(\"Sleeping quarters\", \"It's kinda dark, and everyone is sleeping. I should not wake anyone...\");\n\tRoom* main_deck = new Room(\"Main deck\", \"Blablabla maindeck\");\n\n\tExit* exit1 = new Exit(up, sleeping_quarters, main_deck);\n\tExit* exit2 = new Exit(down, main_deck, sleeping_quarters);\n\n\tsleeping_quarters->exits.push_back(exit1);\n\tmain_deck->exits.push_back(exit2);\n\n\tmainguy = new Player(\"Slinger\", \"A young, untrained but clever pirate\", sleeping_quarters);\n\n\tworldEntities.push_back(sleeping_quarters);\n\tworldEntities.push_back(main_deck);\n\tworldEntities.push_back(mainguy);\n}\n\nWorld::~World() \n{\n}\n\nvoid World::readInput(vector userInput) \n{\n\tswitch ( userInput.size() )\n\t{\n\t\tcase 1:\n\t\t\tif (userInput[0] == \"Look\")\n\t\t\t{\n\t\t\t\tmainguy->Look();\n\t\t\t}\n\t\t\telse if (userInput[0] == \"Inventory\")\n\t\t\t{\n\t\t\t\tcout << \"Checking inventory\" << endl << \">\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcout << \"I didn't understand you, mate\" << endl << \">\";\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 2:\n\t\t\tif (userInput[0] == \"Go\")\n\t\t\t{\n\t\t\t\tif (userInput[1] == \"north\")\n\t\t\t\t{\n\t\t\t\t\tif (mainguy->Go(north)) mainguy->Look();\n\t\t\t\t}\n\t\t\t\telse if (userInput[1] == \"south\")\n\t\t\t\t{\n\t\t\t\t\tif (mainguy->Go(south)) mainguy->Look();\n\t\t\t\t}\n\t\t\t\telse if (userInput[1] == \"east\")\n\t\t\t\t{\n\t\t\t\t\tif (mainguy->Go(east)) mainguy->Look();\n\t\t\t\t}\n\t\t\t\telse if (userInput[1] == \"west\")\n\t\t\t\t{\n\t\t\t\t\tif (mainguy->Go(west)) mainguy->Look();\n\t\t\t\t}\n\t\t\t\telse if (userInput[1] == \"up\")\n\t\t\t\t{\n\t\t\t\t\tif (mainguy->Go(up)) mainguy->Look();\n\t\t\t\t}\n\t\t\t\telse if (userInput[1] == \"down\")\n\t\t\t\t{\n\t\t\t\t\tif (mainguy->Go(down)) mainguy->Look();\n\t\t\t\t}\n\t\t\t\telse cout << \"That's not a valid direction!\" << endl << \">\";\t\t\t\t\n\t\t\t}\n\t\t\telse if (userInput[0] == \"Pick\")\n\t\t\t{\n\t\t\t\tcout << \"Picking something\" << endl << \">\";\n\t\t\t}\n\t\t\telse if (userInput[0] == \"Drop\")\n\t\t\t{\n\t\t\t\tcout << \"Dropping something\" << endl << \">\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcout << \"I didn't understand you, mate\" << endl << \">\";\n\t\t\t}\n\n\t\t\tbreak;\n\n\t\tcase 4:\n\t\t\tif (userInput[0] == \"Put\")\n\t\t\t{\n\t\t\t\tcout << \"Putting something in\/on something\" << endl << \">\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcout << \"I didn't understand you, mate\" << endl << \">\";\n\t\t\t}\n\n\t\t\tbreak;\n\n\t}\n}Added Inventory and PickUp calls to manage items#include \"world.h\"\n#include \"room.h\"\n#include \"player.h\"\n#include \"exit.h\"\n#include \"item.h\"\n#include \n#include \n\nusing namespace std;\n\nWorld::World() \n{\n\tRoom* sleeping_quarters = new Room(\"Sleeping quarters\", \"It's kinda dark, and everyone is sleeping. I should not wake anyone...\");\n\tRoom* main_deck = new Room(\"Main deck\", \"Blablabla maindeck\");\n\n\tExit* exit1 = new Exit(up, sleeping_quarters, main_deck);\n\tExit* exit2 = new Exit(down, main_deck, sleeping_quarters);\n\n\tsleeping_quarters->exits.push_back(exit1);\n\tmain_deck->exits.push_back(exit2);\n\n\tmainguy = new Player(\"Slinger\", \"A young, untrained but clever pirate\", sleeping_quarters);\n\n\tItem* sword = new Item(\"Cutlass\", \"A slightly old, ugly but effective weapon.\", true);\n\tItem* orange = new Item(\"Orange\", \"The best defense against scurvy!\", true);\n\n\tsleeping_quarters->containedEntities.push_back(sword);\n\n\tworldEntities.push_back(sleeping_quarters);\n\tworldEntities.push_back(main_deck);\n\tworldEntities.push_back(mainguy);\n}\n\nWorld::~World() \n{\n}\n\nvoid World::readInput(vector userInput) \n{\n\tswitch ( userInput.size() )\n\t{\n\t\tcase 1:\n\t\t\tif (userInput[0] == \"Look\")\n\t\t\t{\n\t\t\t\tmainguy->Look();\n\t\t\t}\n\t\t\telse if (userInput[0] == \"Inventory\")\n\t\t\t{\n\t\t\t\tmainguy->Inventory();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcout << \"I didn't understand you, mate\" << endl << \">\";\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 2:\n\t\t\tif (userInput[0] == \"Go\")\n\t\t\t{\n\t\t\t\tif (userInput[1] == \"north\")\n\t\t\t\t{\n\t\t\t\t\tif (mainguy->Go(north)) mainguy->Look();\n\t\t\t\t}\n\t\t\t\telse if (userInput[1] == \"south\")\n\t\t\t\t{\n\t\t\t\t\tif (mainguy->Go(south)) mainguy->Look();\n\t\t\t\t}\n\t\t\t\telse if (userInput[1] == \"east\")\n\t\t\t\t{\n\t\t\t\t\tif (mainguy->Go(east)) mainguy->Look();\n\t\t\t\t}\n\t\t\t\telse if (userInput[1] == \"west\")\n\t\t\t\t{\n\t\t\t\t\tif (mainguy->Go(west)) mainguy->Look();\n\t\t\t\t}\n\t\t\t\telse if (userInput[1] == \"up\")\n\t\t\t\t{\n\t\t\t\t\tif (mainguy->Go(up)) mainguy->Look();\n\t\t\t\t}\n\t\t\t\telse if (userInput[1] == \"down\")\n\t\t\t\t{\n\t\t\t\t\tif (mainguy->Go(down)) mainguy->Look();\n\t\t\t\t}\n\t\t\t\telse cout << \"That's not a valid direction!\" << endl << \">\";\t\t\t\t\n\t\t\t}\n\t\t\telse if (userInput[0] == \"Pick\")\n\t\t\t{\n\t\t\t\tmainguy->PickUp(userInput[1].c_str());\n\t\t\t}\n\t\t\telse if (userInput[0] == \"Drop\")\n\t\t\t{\n\t\t\t\tcout << \"Dropping something\" << endl << \">\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcout << \"I didn't understand you, mate\" << endl << \">\";\n\t\t\t}\n\n\t\t\tbreak;\n\n\t\tcase 4:\n\t\t\tif (userInput[0] == \"Put\")\n\t\t\t{\n\t\t\t\tcout << \"Putting something in\/on something\" << endl << \">\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcout << \"I didn't understand you, mate\" << endl << \">\";\n\t\t\t}\n\n\t\t\tbreak;\n\n\t}\n}<|endoftext|>"}
{"text":"#include \"codeGenVisitor.h\"\n\nvoid CodeGenVisitor::populateSwitchMap() {\n\tswitchMap.insert(std::make_pair(\"+\", BOP_PLUS));\n\tswitchMap.insert(std::make_pair(\"-\", BOP_MINUS));\n\tswitchMap.insert(std::make_pair(\"*\", BOP_MULT));\n\tswitchMap.insert(std::make_pair(\"\/\", BOP_DIV));\n\tswitchMap.insert(std::make_pair(\">=\", BOP_GTE));\n\tswitchMap.insert(std::make_pair(\"<=\", BOP_LTE));\n\tswitchMap.insert(std::make_pair(\">\", BOP_GT));\n\tswitchMap.insert(std::make_pair(\"<\", BOP_LT));\n\tswitchMap.insert(std::make_pair(\"!=\", BOP_NEQ));\n\tswitchMap.insert(std::make_pair(\"==\", BOP_EQ));\n\tswitchMap.insert(std::make_pair(\".\", BOP_DOT));\n} \n\nllvm::Value* CodeGenVisitor::ErrorV(const char* str) {\n  fprintf(stderr, \"Error: %s\\n\", str);\n  return nullptr;\n}\n\nllvm::Function* CodeGenVisitor::generateFunction(FunctionDefinition* f) {\n\tstd::string type = f->type->name;\n\tllvm::FunctionType* funcType = nullptr;\n\tllvm::Function* func = nullptr;\n\tstd::vector inputArgs; \/\/set input args as float or int\n\tfor(size_t i = 0, end = f->args->size(); i < end; ++i) {\n\t\tstd::string type = f->args[i][0]->type->name;\n\t\tif(type == \"float\") {\n\t\t\tinputArgs.push_back(llvm::Type::getDoubleTy(*context));\n\t\t}\n\t\telse if(type == \"int\") {\n\t\t\tinputArgs.push_back(llvm::Type::getInt64Ty(*context));\n\t\t}\n\t\telse\n\t\t\treturn nullptr;\n\t}\n\tif(type == \"void\") { \/\/set function return type\n\t\tfuncType = llvm::FunctionType::get(llvm::Type::getVoidTy(*context), inputArgs, false); \n\t}\n\telse if(type == \"float\") {\n\t\tfuncType = llvm::FunctionType::get(llvm::Type::getDoubleTy(*context), inputArgs, false);\n\t}\n\telse if(type == \"int\") {\n\t\tfuncType = llvm::FunctionType::get(llvm::Type::getInt64Ty(*context), inputArgs, false);\n\t}\n\tfunc = llvm::Function::Create(funcType, llvm::Function::ExternalLinkage, f->ident->name, theModule.get()); \/\/pass unique ptr to function\n\t{\n\tsize_t i = 0;\n\tfor (auto &arg : func->args())\n\t  arg.setName(f->args[i++][0]->ident->name);\n\t}\n\treturn func;\n}\n\nCodeGenVisitor::CodeGenVisitor(std::string name) {\n\tpopulateSwitchMap();\n\tcontext = &llvm::getGlobalContext();\n\ttheModule = llvm::make_unique(name, *context);\n\tbuilder = llvm::make_unique>(*context);\n}\n\n\/*===================================Node===================================*\/\nllvm::Value* CodeGenVisitor::visitNode(Node* n) {\n\treturn ErrorV(\"Attempt to generate code for generic Node\");\n}\n\n\/*================================Expression================================*\/\nllvm::Value* CodeGenVisitor::visitExpression(Expression* e) {\n\treturn ErrorV(\"Attempt to generate code for generic Expression\");\n}\n\n\/*================================Statement=================================*\/\nllvm::Value* CodeGenVisitor::visitStatement(Statement* s) {\n\treturn ErrorV(\"Attempt to generate code for generic Statement\");\n}\n\n\/*=================================Integer==================================*\/\nllvm::Value* CodeGenVisitor::visitInteger(Integer* i) {\n\treturn llvm::ConstantInt::get(*context, llvm::APInt(i->value, 64));\n}\n\n\/*==================================Float===================================*\/\nllvm::Value* CodeGenVisitor::visitFloat(Float* f) {\n\treturn llvm::ConstantFP::get(*context, llvm::APFloat(f->value));\n}\n\n\/*================================Identifier================================*\/\nllvm::Value* CodeGenVisitor::visitIdentifier(Identifier* i) {\n  llvm::Value* val = namedValues[i->name];\n  if (!val)\n    return ErrorV(\"Attempt to generate code for not previously defined variable\");\n  return val;\n}\n\n\/*=============================NullaryOperator==============================*\/\nllvm::Value* CodeGenVisitor::visitNullaryOperator(NullaryOperator* n) {\n\tif(*n->op == ';') {\n\t\t\/\/commit action\n\t\treturn nullptr;\n\t}\n\treturn ErrorV(\"Invalid nullary operator\");\n}\n\n\/*==============================UnaryOperator===============================*\/\nllvm::Value* CodeGenVisitor::visitUnaryOperator(UnaryOperator* u) {\n\tllvm::Value* expr = u->exp->acceptVisitor(this);\n\tswitch(*u->op) {\n\t\tcase '-':\n\t\treturn builder->CreateFMul(llvm::ConstantInt::get(*context, llvm::APInt(-1, 64)), expr, \"multmp\");\n\t\tcase '!':\n\t\tcase '*':\n\t\treturn ErrorV(\"Not yet specified unary operator\");\n\t\tdefault:\n\t\treturn ErrorV(\"Invalid unary operator\");\n\t}\n}\n\n\/*==============================BinaryOperator==============================*\/\nllvm::Value* CodeGenVisitor::visitBinaryOperator(BinaryOperator* b) {\n\tllvm::Value* left = b->left->acceptVisitor(this);\n \tllvm::Value* right = b->right->acceptVisitor(this);\n \t\/\/grab left and right\n\tif (!left || !right)\n\t\treturn ErrorV(\"Could not evaluate binary operator\");\n\t\/\/use map for binary operators\n\tswitch (switchMap.find(b->op)->second) {\n\t\tcase BOP_PLUS:\n\t\treturn builder->CreateFAdd(left, right, \"addtmp\");\n\t\tcase BOP_MINUS:\n\t\treturn builder->CreateFSub(left, right, \"subtmp\");\n\t\tcase BOP_MULT:\n\t\treturn builder->CreateFMul(left, right, \"multmp\");\n\t\tcase BOP_DIV:\n\t\treturn builder->CreateFDiv(left, right, \"divtmp\");\n\t\tcase BOP_NEQ:\n\t\tcase BOP_EQ:\n\t\tcase BOP_GTE:\n\t\tcase BOP_LTE:\n\t\tcase BOP_GT:\n\t\tcase BOP_LT:\n\t\tcase BOP_DOT:\n\t\treturn ErrorV(\"Attempt to generate code for not yet implemented binary operator\");\n\t\t\/\/assignment op separate\n\t\tdefault:\n\t\treturn ErrorV(\"Invalid binary operator\");\n\t}\n}\n\n\/*==================================Block===================================*\/\nllvm::Value* CodeGenVisitor::visitBlock(Block* b) {\n\tllvm::Value* lastVisited;\n\tstd::vector>* statements = b->statements;\n\tfor(size_t i = 0, end = statements->size(); i != end; ++i) {\n\t\tlastVisited = statements[i][0]->acceptVisitor(this);\n\t\t\/\/if(!lastVisited) \/\/TODO:nullary operator needs more explicit handling\n\t\t\/\/\treturn nullptr; \n\t}\n\treturn lastVisited;\n}\n\n\/*===============================FunctionCall===============================*\/\nllvm::Value* CodeGenVisitor::visitFunctionCall(FunctionCall* f) {\n\t\/\/grab function and evaluate with arguments\n\tllvm::Function* func = theModule->getFunction(f->ident->name);\n\tif(!func)\n\t\treturn ErrorV(\"Unknown function reference\");\n\tif(func->arg_size() != f->args->size())\n\t\treturn ErrorV(\"Wrong number of arguments passed\");\n\n\tstd::vector argVector;\n\tfor(size_t i = 0, end = f->args->size(); i != end; ++i) {\n\t\targVector.push_back(f->args[i][0]->acceptVisitor(this));\n\t\tif(!argVector.back())\n\t\t\treturn nullptr;\n\t}\n\treturn builder->CreateCall(func, argVector, \"calltmp\");\n}\n\n\/*=================================Keyword==================================*\/\nllvm::Value* CodeGenVisitor::visitKeyword(Keyword* k) {\n\treturn ErrorV(\"Attempt to generate code for dangling keyword\");\n}\n\n\/*============================VariableDefinition============================*\/\nllvm::Value* CodeGenVisitor::visitVariableDefinition(VariableDefinition* v) {\n\tstd::string type = v->type->name; \/\/int float or void\n\tllvm::Value* val = nullptr;\n\tif(type == \"int\") {\n\t\tint64_t i = 0; \/\/TODO: Figure out why variable necessary, attempted casting already\n\t\tval = llvm::ConstantInt::get(*context, llvm::APInt(i, 64));\n\t}\n\telse if(type == \"float\")\n\t\tval = llvm::ConstantFP::get(*context, llvm::APFloat(0.0));\n\tif(!val) \/\/add default value variable to map\n\t\tnamedValues.insert(std::make_pair(v->ident->name, val));\n\treturn val;\n}\n\n\/*===========================StructureDefinition============================*\/\nllvm::Value* CodeGenVisitor::visitStructureDefinition(StructureDefinition* s) {\n\treturn ErrorV(\"Attempt to evaluate not yet implemented structure definition\");\n}\n\n\/*============================FunctionDefinition============================*\/\nllvm::Value* CodeGenVisitor::visitFunctionDefinition(FunctionDefinition* f) {\n\tllvm::Function* func = theModule->getFunction(f->ident->name);\n\tif(!func)\n\t\tfunc = generateFunction(f); \/\/create function object with type|ident|args\n\tif(!func) \/\/generateFunction returned nullptr\n\t\treturn nullptr;\n\tif(!func->empty())\n\t\treturn ErrorV(\"Function is already defined\");\n\tllvm::BasicBlock* block = llvm::BasicBlock::Create(*context, \"function start\", func);\n\tbuilder->SetInsertPoint(block);\n\tnamedValues.clear();\n\tfor (auto &arg : func->args())\n\t\tnamedValues[arg.getName()] = &arg;\n\t\tfunc->dump();\/\/Function IR dump\n\t\tllvm::Value* retVal = f->block->acceptVisitor(this);\n\tif(retVal->getType()->getTypeID() == func->getReturnType()->getTypeID()) {\n\t\treturn retVal;\n\t}\n\tfunc->eraseFromParent();\/\/erase if incorrect type returned\n\treturn nullptr; \n}\n\n\/*==========================StructureDeclaration============================*\/\nllvm::Value* CodeGenVisitor::visitStructureDeclaration(StructureDeclaration* s) {\n\treturn ErrorV(\"Attempt to evaluate not yet implemented structure declaration\");\n}\n\n\n\/*===========================ExpressionStatement============================*\/\nllvm::Value* CodeGenVisitor::visitExpressionStatement(ExpressionStatement* e) {\n\treturn e->exp->acceptVisitor(this);\t\/\/evaluated but value discarded\n}\n\n\/*=============================ReturnStatement==============================*\/\nllvm::Value* CodeGenVisitor::visitReturnStatement(ReturnStatement* r) {\n\tllvm::Value* returnVal = r->exp->acceptVisitor(this);\n\tif(returnVal) {\n\t\tbuilder->CreateRet(returnVal); \/\/builder returns value\n\t}\n\treturn returnVal;\n}\n\n\/*=============================AssignStatement==============================*\/\nllvm::Value* CodeGenVisitor::visitAssignStatement(AssignStatement* a) {\n\t\/\/TODO: map a value to an exisiting identifier\n\t\/\/look for identifier\n\t\/\/map target to value\n\treturn nullptr;\n}\n\n\/*===============================IfStatement================================*\/\nllvm::Value* CodeGenVisitor::visitIfStatement(IfStatement* i) {\n\treturn ErrorV(\"Attempt to evaluate not yet implemented if statement\");\n}\nAdded error message for function return type | explicit type checking for void type#include \"codeGenVisitor.h\"\n\nvoid CodeGenVisitor::populateSwitchMap() {\n\tswitchMap.insert(std::make_pair(\"+\", BOP_PLUS));\n\tswitchMap.insert(std::make_pair(\"-\", BOP_MINUS));\n\tswitchMap.insert(std::make_pair(\"*\", BOP_MULT));\n\tswitchMap.insert(std::make_pair(\"\/\", BOP_DIV));\n\tswitchMap.insert(std::make_pair(\">=\", BOP_GTE));\n\tswitchMap.insert(std::make_pair(\"<=\", BOP_LTE));\n\tswitchMap.insert(std::make_pair(\">\", BOP_GT));\n\tswitchMap.insert(std::make_pair(\"<\", BOP_LT));\n\tswitchMap.insert(std::make_pair(\"!=\", BOP_NEQ));\n\tswitchMap.insert(std::make_pair(\"==\", BOP_EQ));\n\tswitchMap.insert(std::make_pair(\".\", BOP_DOT));\n} \n\nllvm::Value* CodeGenVisitor::ErrorV(const char* str) {\n  fprintf(stderr, \"Error: %s\\n\", str);\n  return nullptr;\n}\n\nllvm::Function* CodeGenVisitor::generateFunction(FunctionDefinition* f) {\n\tstd::string type = f->type->name;\n\tllvm::FunctionType* funcType = nullptr;\n\tllvm::Function* func = nullptr;\n\tstd::vector inputArgs; \/\/set input args as float or int\n\tfor(size_t i = 0, end = f->args->size(); i < end; ++i) {\n\t\tstd::string type = f->args[i][0]->type->name;\n\t\tif(type == \"float\") {\n\t\t\tinputArgs.push_back(llvm::Type::getDoubleTy(*context));\n\t\t}\n\t\telse if(type == \"int\") {\n\t\t\tinputArgs.push_back(llvm::Type::getInt64Ty(*context));\n\t\t}\n\t\telse\n\t\t\treturn nullptr;\n\t}\n\tif(type == \"void\") { \/\/set function return type\n\t\tfuncType = llvm::FunctionType::get(llvm::Type::getVoidTy(*context), inputArgs, false); \n\t}\n\telse if(type == \"float\") {\n\t\tfuncType = llvm::FunctionType::get(llvm::Type::getDoubleTy(*context), inputArgs, false);\n\t}\n\telse if(type == \"int\") {\n\t\tfuncType = llvm::FunctionType::get(llvm::Type::getInt64Ty(*context), inputArgs, false);\n\t}\n\tfunc = llvm::Function::Create(funcType, llvm::Function::ExternalLinkage, f->ident->name, theModule.get()); \/\/pass unique ptr to function\n\t{\n\tsize_t i = 0;\n\tfor (auto &arg : func->args())\n\t  arg.setName(f->args[i++][0]->ident->name);\n\t}\n\treturn func;\n}\n\nCodeGenVisitor::CodeGenVisitor(std::string name) {\n\tpopulateSwitchMap();\n\tcontext = &llvm::getGlobalContext();\n\ttheModule = llvm::make_unique(name, *context);\n\tbuilder = llvm::make_unique>(*context);\n}\n\n\/*===================================Node===================================*\/\nllvm::Value* CodeGenVisitor::visitNode(Node* n) {\n\treturn ErrorV(\"Attempt to generate code for generic Node\");\n}\n\n\/*================================Expression================================*\/\nllvm::Value* CodeGenVisitor::visitExpression(Expression* e) {\n\treturn ErrorV(\"Attempt to generate code for generic Expression\");\n}\n\n\/*================================Statement=================================*\/\nllvm::Value* CodeGenVisitor::visitStatement(Statement* s) {\n\treturn ErrorV(\"Attempt to generate code for generic Statement\");\n}\n\n\/*=================================Integer==================================*\/\nllvm::Value* CodeGenVisitor::visitInteger(Integer* i) {\n\treturn llvm::ConstantInt::get(*context, llvm::APInt(i->value, 64));\n}\n\n\/*==================================Float===================================*\/\nllvm::Value* CodeGenVisitor::visitFloat(Float* f) {\n\treturn llvm::ConstantFP::get(*context, llvm::APFloat(f->value));\n}\n\n\/*================================Identifier================================*\/\nllvm::Value* CodeGenVisitor::visitIdentifier(Identifier* i) {\n  llvm::Value* val = namedValues[i->name];\n  if (!val)\n    return ErrorV(\"Attempt to generate code for not previously defined variable\");\n  return val;\n}\n\n\/*=============================NullaryOperator==============================*\/\nllvm::Value* CodeGenVisitor::visitNullaryOperator(NullaryOperator* n) {\n\tif(*n->op == ';') {\n\t\t\/\/commit action\n\t\treturn nullptr;\n\t}\n\treturn ErrorV(\"Invalid nullary operator\");\n}\n\n\/*==============================UnaryOperator===============================*\/\nllvm::Value* CodeGenVisitor::visitUnaryOperator(UnaryOperator* u) {\n\tllvm::Value* expr = u->exp->acceptVisitor(this);\n\tswitch(*u->op) {\n\t\tcase '-':\n\t\treturn builder->CreateFMul(llvm::ConstantInt::get(*context, llvm::APInt(-1, 64)), expr, \"multmp\");\n\t\tcase '!':\n\t\tcase '*':\n\t\treturn ErrorV(\"Not yet specified unary operator\");\n\t\tdefault:\n\t\treturn ErrorV(\"Invalid unary operator\");\n\t}\n}\n\n\/*==============================BinaryOperator==============================*\/\nllvm::Value* CodeGenVisitor::visitBinaryOperator(BinaryOperator* b) {\n\tllvm::Value* left = b->left->acceptVisitor(this);\n \tllvm::Value* right = b->right->acceptVisitor(this);\n \t\/\/grab left and right\n\tif (!left || !right)\n\t\treturn ErrorV(\"Could not evaluate binary operator\");\n\t\/\/use map for binary operators\n\tswitch (switchMap.find(b->op)->second) {\n\t\tcase BOP_PLUS:\n\t\treturn builder->CreateFAdd(left, right, \"addtmp\");\n\t\tcase BOP_MINUS:\n\t\treturn builder->CreateFSub(left, right, \"subtmp\");\n\t\tcase BOP_MULT:\n\t\treturn builder->CreateFMul(left, right, \"multmp\");\n\t\tcase BOP_DIV:\n\t\treturn builder->CreateFDiv(left, right, \"divtmp\");\n\t\tcase BOP_NEQ:\n\t\tcase BOP_EQ:\n\t\tcase BOP_GTE:\n\t\tcase BOP_LTE:\n\t\tcase BOP_GT:\n\t\tcase BOP_LT:\n\t\tcase BOP_DOT:\n\t\treturn ErrorV(\"Attempt to generate code for not yet implemented binary operator\");\n\t\t\/\/assignment op separate\n\t\tdefault:\n\t\treturn ErrorV(\"Invalid binary operator\");\n\t}\n}\n\n\/*==================================Block===================================*\/\nllvm::Value* CodeGenVisitor::visitBlock(Block* b) {\n\tllvm::Value* lastVisited;\n\tstd::vector>* statements = b->statements;\n\tfor(size_t i = 0, end = statements->size(); i != end; ++i) {\n\t\tlastVisited = statements[i][0]->acceptVisitor(this);\n\t\t\/\/if(!lastVisited) \/\/TODO:nullary operator needs more explicit handling\n\t\t\/\/\treturn nullptr; \n\t}\n\treturn lastVisited;\n}\n\n\/*===============================FunctionCall===============================*\/\nllvm::Value* CodeGenVisitor::visitFunctionCall(FunctionCall* f) {\n\t\/\/grab function and evaluate with arguments\n\tllvm::Function* func = theModule->getFunction(f->ident->name);\n\tif(!func)\n\t\treturn ErrorV(\"Unknown function reference\");\n\tif(func->arg_size() != f->args->size())\n\t\treturn ErrorV(\"Wrong number of arguments passed\");\n\n\tstd::vector argVector;\n\tfor(size_t i = 0, end = f->args->size(); i != end; ++i) {\n\t\targVector.push_back(f->args[i][0]->acceptVisitor(this));\n\t\tif(!argVector.back())\n\t\t\treturn nullptr;\n\t}\n\treturn builder->CreateCall(func, argVector, \"calltmp\");\n}\n\n\/*=================================Keyword==================================*\/\nllvm::Value* CodeGenVisitor::visitKeyword(Keyword* k) {\n\treturn ErrorV(\"Attempt to generate code for dangling keyword\");\n}\n\n\/*============================VariableDefinition============================*\/\nllvm::Value* CodeGenVisitor::visitVariableDefinition(VariableDefinition* v) {\n\tstd::string type = v->type->name; \/\/int float or void\n\tllvm::Value* val = nullptr;\n\tif(type == \"int\") {\n\t\tint64_t i = 0; \/\/TODO: Figure out why variable necessary, attempted casting already\n\t\tval = llvm::ConstantInt::get(*context, llvm::APInt(i, 64));\n\t}\n\telse if(type == \"float\")\n\t\tval = llvm::ConstantFP::get(*context, llvm::APFloat(0.0));\n\tif(!val) \/\/add default value variable to map\n\t\tnamedValues.insert(std::make_pair(v->ident->name, val));\n\treturn val;\n}\n\n\/*===========================StructureDefinition============================*\/\nllvm::Value* CodeGenVisitor::visitStructureDefinition(StructureDefinition* s) {\n\treturn ErrorV(\"Attempt to evaluate not yet implemented structure definition\");\n}\n\n\/*============================FunctionDefinition============================*\/\nllvm::Value* CodeGenVisitor::visitFunctionDefinition(FunctionDefinition* f) {\n\tllvm::Function* func = theModule->getFunction(f->ident->name);\n\tif(!func)\n\t\tfunc = generateFunction(f); \/\/create function object with type|ident|args\n\tif(!func) \/\/generateFunction returned nullptr\n\t\treturn nullptr;\n\tif(!func->empty())\n\t\treturn ErrorV(\"Function is already defined\");\n\tllvm::BasicBlock* block = llvm::BasicBlock::Create(*context, \"function start\", func);\n\tbuilder->SetInsertPoint(block);\n\tnamedValues.clear();\n\tfor (auto &arg : func->args())\n\t\tnamedValues[arg.getName()] = &arg;\n\t\tllvm::Value* retVal = f->block->acceptVisitor(this);\n\tif(!retVal && (func->getReturnType()->getTypeID() == llvm::Type::VoidTyID)) \/\/void return nullptr\n\t\tfunc->dump();\/\/Function IR dump\n\t\treturn nullptr;\n\tif(retVal->getType()->getTypeID() == func->getReturnType()->getTypeID()) \/\/check typing for int\/float\n\t\tfunc->dump();\n\t\treturn retVal;\n\tfunc->eraseFromParent();\/\/erase if incorrect type returned\n\treturn ErrorV(\"Function deleted for erroneous return type or function body complications\"); \n}\n\n\/*==========================StructureDeclaration============================*\/\nllvm::Value* CodeGenVisitor::visitStructureDeclaration(StructureDeclaration* s) {\n\treturn ErrorV(\"Attempt to evaluate not yet implemented structure declaration\");\n}\n\n\n\/*===========================ExpressionStatement============================*\/\nllvm::Value* CodeGenVisitor::visitExpressionStatement(ExpressionStatement* e) {\n\treturn e->exp->acceptVisitor(this);\t\/\/evaluated but value discarded\n}\n\n\/*=============================ReturnStatement==============================*\/\nllvm::Value* CodeGenVisitor::visitReturnStatement(ReturnStatement* r) {\n\tllvm::Value* returnVal = r->exp->acceptVisitor(this);\n\tif(returnVal) {\n\t\tbuilder->CreateRet(returnVal); \/\/builder returns value\n\t}\n\treturn returnVal;\n}\n\n\/*=============================AssignStatement==============================*\/\nllvm::Value* CodeGenVisitor::visitAssignStatement(AssignStatement* a) {\n\t\/\/TODO: map a value to an exisiting identifier\n\t\/\/look for identifier\n\t\/\/map target to value\n\treturn nullptr;\n}\n\n\/*===============================IfStatement================================*\/\nllvm::Value* CodeGenVisitor::visitIfStatement(IfStatement* i) {\n\treturn ErrorV(\"Attempt to evaluate not yet implemented if statement\");\n}\n<|endoftext|>"}
{"text":"\/**\n * File        : Fringe.cc\n * Description : Implementation of the fringe algorithm using a specified \"world\"\n *               from the worlds folder.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"algorithms\/tools\/PathTile.h\"\n#include \"common\/Results.h\"\n\nusing namespace pathFind;\n\nconst std::string WORLD_DIR = \"..\/worlds\";\nconst std::string WORLD_EXT = \".world\";\nconst std::string PATH_EXT = \".path\";\n\nconst std::string ALG_NAME = \"fringe\";\n\nvoid searchNeighbor (const Point& adjPoint, const World& world, const PathTile& current,\n    uint threshold, uint& min, std::vector& now, std::vector& later,\n    std::unordered_map& seen, const std::function& h);\n\nint main (int args, char* argv[])\n{\n    \/\/ Program should be started with 5 command line parameters (or 1)\n    \/\/ that specifies the name of the world file to read from and then optionallys\n    \/\/ the start x, start y, end x, and end y\n    if (args != 6  && args != 2)\n    {\n        std::cout << \"Incorrect inputs. Usage:  (start x) (start y) (end x) (end y)\" << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    \/\/ Parse the world file\n    std::stringstream filename;\n    filename << WORLD_DIR << \"\/\" << argv[1] << WORLD_EXT;\n\n    std::ifstream worldFile (filename.str (),\n            std::ifstream::in | std::ifstream::binary);\n\n    if (!worldFile)\n    {\n        std::cout << \"World file doesn't exist.\" << std::endl;\n        return EXIT_FAILURE;\n    }\n    pathFind::World world;\n\n    worldFile >> world;\n    worldFile.close ();\n\n    uint startX, startY, endX, endY;\n\n    if (args == 6)\n    {\n        \/\/ Parse the start and end points\n        try\n        {\n            startX = boost::lexical_cast (argv[2]);\n            startY = boost::lexical_cast (argv[3]);\n            endX = boost::lexical_cast (argv[4]);\n            endY = boost::lexical_cast (argv[5]);\n        } catch (boost::bad_lexical_cast &e)\n        {\n            std::cout << \"Start and end points failed to convert to numeric types\" << std::endl;\n            return EXIT_FAILURE;\n        }\n    }\n    else\n    {\n        std::stringstream pathFilename;\n        pathFilename << WORLD_DIR << \"\/\" << argv[1] << PATH_EXT;\n        std::ifstream pathIn (pathFilename.str ());\n        if (!pathIn)\n        {\n            std::string pathCommand = \".\/pathGen \" + std::string (argv[1]);\n            system (pathCommand.c_str());\n            pathIn.close ();\n            pathIn.open (pathFilename.str ());\n            if (!pathIn)\n            {\n                std::cout << \"Could not construct path.\" << std::endl;\n                return EXIT_FAILURE;\n            }\n        }\n        pathIn >> startX >> startY >> endX >> endY;\n\n    }\n\n    #ifdef GEN_STATS\n        std::vector> stats (1);\n    #endif\n\n    auto t1 = std::chrono::high_resolution_clock::now();\n\n    std::function h = [endX, endY] (uint x, uint y)\n    {\n        return  (x < endX ? endX - x : x - endX) +\n                (y < endY ? endY - y : y - endY);\n    };\n\n    std::vector now, later;\n    now.emplace_back (world (startX, startY), Point{startX, startY},\n    \t\tPoint {startX, startY}, 0, h (startX, startY));\n\n    uint threshold = now.back().getCombinedHeuristic();\n    std::unordered_map  seen;\n    seen[now.back().getTile().id] = now.back ();\n\n    bool found = false;\n\n    while (!found)\n    {\n        uint min = PathTile::INF;\n\n        while (!now.empty ())\n        {\n            PathTile current = now.back();\n            now.pop_back();\n            #ifdef GEN_STATS\n                auto statIter = stats[0].find (current.getTile ().id);\n                if (statIter == stats[0].end ())\n                {\n                    stats[0][current.getTile ().id] = StatPoint {current.xy ().x, current.xy ().y};\n                }\n                else\n                {\n                    statIter->second.processCount++;\n                }\n            #endif\n\n            if (seen.find(current.getTile().id) != seen.end())\n            {\n                continue;\n            }\n\n            if (current.getCombinedHeuristic () > threshold)\n            {\n                min = std::min(current.getCombinedHeuristic (), min);\n                later.push_back(current);\n                continue;\n            }\n\n            if (current.xy().x == endX && current.xy().y == endY)\n            {\n                found = true;\n                break;\n            }\n\n            \/\/ East\n            searchNeighbor({current.xy ().x + 1, current.xy ().y}, world, current, threshold,\n                min, now, later, seen, h);\n            \/\/ South\n            searchNeighbor({current.xy ().x, current.xy ().y + 1}, world, current, threshold,\n                min, now, later, seen, h);\n            \/\/ West\n            searchNeighbor({current.xy ().x - 1, current.xy ().y}, world, current, threshold,\n                min, now, later, seen, h);\n            \/\/ North\n            searchNeighbor({current.xy ().x, current.xy ().y - 1}, world, current, threshold,\n                min, now, later, seen, h);\n\n        }\n        threshold = min;\n        now = std::move(later);\n        later.clear ();\n    }\n\n    auto t2 = std::chrono::high_resolution_clock::now();\n\n    \/\/ Parse reverse results\n    PathTile endTile = seen.at((endY * world.getWidth())+ endX);\n    uint totalCost = endTile.getBestCost() - endTile.getTile().cost;\n    std::vector finalPath;\n    while (endTile.xy ().x != startX || endTile.xy ().y != startY)\n    {\n        finalPath.emplace_back(endTile.xy ());\n        endTile = seen.at((endTile.bestTile ().y * world.getWidth()) + endTile.bestTile ().x);\n    }\n    finalPath.emplace_back(endTile.xy ());\n\n    #ifdef GEN_STATS\n        writeResults (finalPath, stats, argv[1], ALG_NAME,\n                std::chrono::duration_cast(t2-t1).count(), totalCost);\n    #else\n        writeResults (finalPath, argv[1], ALG_NAME,\n                std::chrono::duration_cast(t2-t1).count(), totalCost);\n    #endif\n\n    return EXIT_SUCCESS;\n}\n\nvoid searchNeighbor (const Point& adjPoint, const World& world, const PathTile& current,\n    uint threshold, uint& min, std::vector& now, std::vector& later,\n    std::unordered_map& seen, const std::function& h)\n{\n    if (adjPoint.x < world.getWidth () && adjPoint.y < world.getHeight ())\n    {\n        World::tile_t worldTile = world (adjPoint.x, adjPoint.y);\n        if (worldTile.cost != 0)\n        {\n\n            auto seenTileIter = seen.find(worldTile.id);\n            if (seenTileIter == seen.end ())\n            {\n                \/\/ TODO: Check if will exceed threshold here to emplace into later instead?\n                now.emplace_back (worldTile, adjPoint, current.xy(),\n                                  current.getBestCost () + worldTile.cost, h (adjPoint.x, adjPoint.y));\n                seen[worldTile.id] = now.back();\n            }\n            else\n            {\n                PathTile& seenTile = seenTileIter->second;\n                uint costToTile = current.getBestCost () + seenTile.getTile ().cost;\n                if (seenTile.getBestCost () > costToTile)\n                {\n                    seenTile.setBestCost (costToTile);\n                    seenTile.setBestTile (current.xy());\n                    if (seenTile.getCombinedHeuristic () > threshold)\n                    {\n                        min = std::min(seenTile.getCombinedHeuristic (), min);\n                        later.push_back(seenTile);\n                    }\n                    else\n                    {\n                        now.push_back(seenTile);\n                    }\n                }\n            }\n        }\n    }\n}\n\n\/*\nvoid search (uint startX, uint startY, uint endX, uint endY, std::unordered_set& tileIdsFound,\n             std::unordered_map& expandedTiles,\n             pathFind::PathTile& tile, const pathFind::World& world,\n             std::mutex& m, bool& finished, bool& iFound)\n{\n    PriorityQueue openTiles (world.getWidth (), world.getHeight (), [endX, endY] (uint x, uint y)\n    {\n        return  (x < endX ? endX - x : x - endX) +\n                (y < endY ? endY - y : y - endY);\n    });\n\n    openTiles.push (world (startX, startY), {startX, startY}, 0);\n\n    tile = openTiles.top ();\n    while (tile.xy ().x != endX || tile.xy ().y != endY)\n    {\n        tile = openTiles.top ();\n\n        m.lock ();\n        if (finished)\n        {\n            m.unlock ();\n            break;\n        }\n        if (tileIdsFound.count(tile.getTile().id))\n        {\n            \/\/ Best path found\n            iFound = true;\n            finished = true;\n            m.unlock ();\n            break;\n        }\n        tileIdsFound.insert(tile.getTile().id);\n        m.unlock ();\n\n        expandedTiles[tile.getTile ().id] = tile;\n        openTiles.pop ();\n\n        \/\/ Check each neighbor\n        Point adjPoint {tile.xy ().x + 1, tile.xy ().y}; \/\/ east\n        if (adjPoint.x < world.getWidth() && adjPoint.y < world.getHeight ())\n        {\n            World::tile_t worldTile = world (adjPoint.x, adjPoint.y);\n            if (worldTile.cost != 0 &&\n                expandedTiles.find (worldTile.id) == expandedTiles.end ())\n            {\n                openTiles.tryUpdateBestCost (worldTile, adjPoint, tile);\n            }\n        }\n\n        adjPoint = {tile.xy ().x, tile.xy ().y + 1}; \/\/ south\n        if (adjPoint.x < world.getWidth() && adjPoint.y < world.getHeight ())\n        {\n            World::tile_t worldTile = world (adjPoint.x, adjPoint.y);\n            if (worldTile.cost != 0 &&\n                expandedTiles.find (worldTile.id) == expandedTiles.end ())\n            {\n                openTiles.tryUpdateBestCost (worldTile, adjPoint, tile);\n            }\n        }\n\n        adjPoint = {tile.xy ().x - 1, tile.xy ().y}; \/\/ west\n        if (adjPoint.x < world.getWidth() && adjPoint.y < world.getHeight ())\n        {\n            World::tile_t worldTile = world (adjPoint.x, adjPoint.y);\n            if (worldTile.cost != 0 &&\n                expandedTiles.find (worldTile.id) == expandedTiles.end ())\n            {\n                openTiles.tryUpdateBestCost (worldTile, adjPoint, tile);\n            }\n        }\n\n        adjPoint = {tile.xy ().x, tile.xy ().y - 1}; \/\/ north\n        if (adjPoint.x < world.getWidth() && adjPoint.y < world.getHeight ())\n        {\n            World::tile_t worldTile = world (adjPoint.x, adjPoint.y);\n            if (worldTile.cost != 0 &&\n                expandedTiles.find (worldTile.id) == expandedTiles.end ())\n            {\n                openTiles.tryUpdateBestCost (worldTile, adjPoint, tile);\n            }\n        }\n    }\n}\n*\/\nRemoved alternate Fringe. It was slower.<|endoftext|>"}
{"text":"\/\/ This file is part of the AliceVision project.\n\/\/ Copyright (c) 2017 AliceVision contributors.\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"SfMData.hpp\"\n\n#include \n\n#define BOOST_TEST_MODULE sfmRig\n#include \n#include \n\nusing namespace aliceVision;\nusing namespace aliceVision::sfm;\n\nBOOST_AUTO_TEST_CASE(rig_initialization)\n{\n  static constexpr IndexT rigId = 0;\n  static constexpr std::size_t nbSubPoses = 5;\n\n  SfMData sfmData;\n\n  sfmData.intrinsics.emplace(0, std::make_shared(1000, 1000, 36.0, std::rand()%10000, std::rand()%10000));\n  sfmData.getRigs().emplace(rigId, Rig(nbSubPoses));\n\n  std::vector rigViews;\n\n  for(std::size_t subPoseId = 0; subPoseId < nbSubPoses; ++subPoseId)\n  {\n    rigViews.emplace_back(\"\", subPoseId, 0, 0, 10, 10, rigId, subPoseId);\n  }\n\n  for(const View& view : rigViews)\n  {\n    sfmData.views.emplace(view.getViewId(), std::make_shared(view));\n  }\n\n  const Mat3 r = Mat3::Random();\n  const Vec3 c = Vec3::Random();\n  const geometry::Pose3 firstPose(r, c);\n  const IndexT firstPoseId = std::rand() % nbSubPoses;\n\n  const Rig& rig = sfmData.getRig(rigViews.front());\n\n  \/\/ rig uninitialized\n  BOOST_CHECK(!rig.isInitialized());\n\n  sfmData.setPose(rigViews.at(firstPoseId), CameraPose(firstPose));\n\n  \/\/ setPose done, rig initialized\n  BOOST_CHECK(rig.isInitialized());\n\n  \/\/ Check rig sub-poses\n  for(std::size_t subPoseId = 0; subPoseId < nbSubPoses; ++subPoseId)\n  {\n    const RigSubPose& subPose = rig.getSubPose(subPoseId);\n\n    if(subPoseId == firstPoseId)\n    {\n      \/\/ first sub-pose should be initialized\n      BOOST_CHECK(subPose.status != ERigSubPoseStatus::UNINITIALIZED);\n    }\n    else\n    {\n      \/\/ other sub-poses are uninitialized\n      BOOST_CHECK(subPose.status == ERigSubPoseStatus::UNINITIALIZED);\n    }\n\n    \/\/ all sub-poses should be at identity\n    BOOST_CHECK(subPose.pose == geometry::Pose3());\n  }\n\n  \/\/ Check rig pose\n  for(std::size_t subPoseId = 0; subPoseId < nbSubPoses; ++subPoseId)\n  {\n    const View& view = rigViews.at(subPoseId);\n    BOOST_CHECK(sfmData.getPose(view).getTransform() == firstPose);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(rig_setPose)\n{\n  static constexpr IndexT rigId = 0;\n  static constexpr std::size_t nbSubPoses = 5;\n  static constexpr std::size_t nbPoses = 2;\n\n  SfMData sfmData;\n\n  sfmData.intrinsics.emplace(0, std::make_shared(1000, 1000, 36.0, std::rand()%10000, std::rand()%10000));\n  sfmData.getRigs().emplace(rigId, Rig(nbSubPoses));\n\n  std::vector rigViews;\n\n  for(std::size_t poseId = 0; poseId < nbPoses; ++poseId)\n  {\n    for(std::size_t subPoseId = 0; subPoseId < nbSubPoses; ++subPoseId)\n    {\n      const IndexT viewId = poseId * nbSubPoses + subPoseId;\n      rigViews.emplace_back(\"\", viewId, 0, poseId, 10, 10, rigId, subPoseId);\n    }\n  }\n\n  for(const View& view : rigViews)\n  {\n    sfmData.views.emplace(view.getViewId(), std::make_shared(view));\n  }\n\n  const Rig& rig = sfmData.getRig(rigViews.front());\n\n  for(std::size_t poseId = 0; poseId < nbPoses; ++poseId)\n  {\n    for(std::size_t subPoseId = 0; subPoseId < nbSubPoses; ++subPoseId)\n    {\n      const IndexT viewId = poseId * nbSubPoses + subPoseId;\n      const View& view = *(sfmData.views.at(viewId));\n      const RigSubPose& subPose = rig.getSubPose(subPoseId);\n\n      if(subPoseId == 0)\n      {\n        \/\/ first sub-pose, rig pose is unknown\n        BOOST_CHECK(!sfmData.existsPose(view));\n\n        if(poseId == 0)\n        {\n          \/\/ first rig pose, first sub-pose, sub-pose uninitialized\n          BOOST_CHECK(subPose.status == ERigSubPoseStatus::UNINITIALIZED);\n        }\n        else\n        {\n          \/\/ not first rig pose, first sub-pose, sub-pose initialized\n          BOOST_CHECK(subPose.status != ERigSubPoseStatus::UNINITIALIZED);\n        }\n\n        const Mat3 r = Mat3::Random();\n        const Vec3 c = Vec3::Random();\n        const geometry::Pose3 firstPose = geometry::Pose3(r, c);\n\n        sfmData.setPose(view, CameraPose(firstPose));\n\n        \/\/ setPose done, sub-pose must be initialized\n        BOOST_CHECK(subPose.status != ERigSubPoseStatus::UNINITIALIZED);\n\n        \/\/ setPose done, rig initialized\n        BOOST_CHECK(sfmData.existsPose(view));\n        BOOST_CHECK(sfmData.getPose(view).getTransform() == firstPose);\n      }\n      else\n      {\n\n        \/\/ rig pose should be initialized\n        BOOST_CHECK(sfmData.existsPose(view));\n\n        if(poseId == 0) \/\/other poses are redundant\n        {\n          const Mat3 r = Mat3::Random();\n          const Vec3 c = Vec3::Random();\n          const geometry::Pose3 pose = geometry::Pose3(r, c);\n\n          \/\/ first rig pose, sub-pose must be uninitialized\n          BOOST_CHECK(subPose.status == ERigSubPoseStatus::UNINITIALIZED);\n\n          sfmData.setPose(view, CameraPose(pose));\n\n          \/\/ setPose done, sub-pose must be initialized\n          BOOST_CHECK(subPose.status != ERigSubPoseStatus::UNINITIALIZED);\n        }\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(rig_getPose)\n{\n  static constexpr IndexT rigId = 0;\n  static constexpr std::size_t nbSubPoses = 5;\n  static constexpr std::size_t nbPoses = 2;\n\n  SfMData sfmData;\n\n  sfmData.intrinsics.emplace(0, std::make_shared(1000, 1000, 36.0, std::rand()%10000, std::rand()%10000));\n  sfmData.getRigs().emplace(rigId, Rig(nbSubPoses));\n\n  std::vector rigViews;\n\n  for(std::size_t poseId = 0; poseId < nbPoses; ++poseId)\n  {\n    for(std::size_t subPoseId = 0; subPoseId < nbSubPoses; ++subPoseId)\n    {\n      const IndexT viewId = poseId * nbSubPoses + subPoseId;\n      rigViews.emplace_back(\"\", viewId, 0, poseId, 10, 10, rigId, subPoseId);\n    }\n  }\n\n  for(const View& view : rigViews)\n  {\n    sfmData.views.emplace(view.getViewId(), std::make_shared(view));\n  }\n\n  const Rig& rig = sfmData.getRig(rigViews.front());\n\n  for(std::size_t poseId = 0; poseId < nbPoses; ++poseId)\n  {\n    for(std::size_t subPoseId = 0; subPoseId < nbSubPoses; ++subPoseId)\n    {\n      const IndexT viewId = poseId * nbSubPoses + subPoseId;\n      const View& view = *(sfmData.views.at(viewId));\n      const RigSubPose& subPose = rig.getSubPose(subPoseId);\n\n      if(subPoseId == 0)\n      {\n        const Mat3 r = Mat3::Random();\n        const Vec3 c = Vec3::Random();\n        const geometry::Pose3 firstPose = geometry::Pose3(r, c);\n\n        sfmData.setPose(view, CameraPose(firstPose));\n\n        \/\/ setPose done, rig initialized\n        if(poseId == 0)\n        {\n          \/\/ the rig pose is the first pose\n          BOOST_CHECK(sfmData.getPose(view).getTransform() == firstPose);\n        }\n        else\n        {\n          \/\/ the rig pose is the sub-pose inverse multiply by the rig pose\n          BOOST_CHECK(sfmData.getPose(view).getTransform() == (subPose.pose.inverse() * firstPose));\n        }\n\n      }\n      else\n      {\n        const geometry::Pose3& rigPose = sfmData.getPose(view).getTransform();\n\n        if(poseId == 0) \/\/other poses are redundant\n        {\n          const Mat3 r = Mat3::Random();\n          const Vec3 c = Vec3::Random();\n          const geometry::Pose3 absolutePose = geometry::Pose3(r, c);\n\n          sfmData.setPose(view, CameraPose(absolutePose));\n\n          \/\/ the view sub-pose is the absolute pose multiply by the rig pose inverse\n          BOOST_CHECK(subPose.pose == (absolutePose * rigPose.inverse()));\n        }\n\n        \/\/ the view absolute pose is the sub-pose multiply by the rig pose\n        BOOST_CHECK(sfmData.getPose(view).getTransform() == (subPose.pose * sfmData.getAbsolutePose(view.getPoseId()).getTransform()));\n      }\n    }\n  }\n}\n[sfm] Fix `getPose` reference issue in `rig_test`\/\/ This file is part of the AliceVision project.\n\/\/ Copyright (c) 2017 AliceVision contributors.\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"SfMData.hpp\"\n\n#include \n\n#define BOOST_TEST_MODULE sfmRig\n#include \n#include \n\nusing namespace aliceVision;\nusing namespace aliceVision::sfm;\n\nBOOST_AUTO_TEST_CASE(rig_initialization)\n{\n  static constexpr IndexT rigId = 0;\n  static constexpr std::size_t nbSubPoses = 5;\n\n  SfMData sfmData;\n\n  sfmData.intrinsics.emplace(0, std::make_shared(1000, 1000, 36.0, std::rand()%10000, std::rand()%10000));\n  sfmData.getRigs().emplace(rigId, Rig(nbSubPoses));\n\n  std::vector rigViews;\n\n  for(std::size_t subPoseId = 0; subPoseId < nbSubPoses; ++subPoseId)\n  {\n    rigViews.emplace_back(\"\", subPoseId, 0, 0, 10, 10, rigId, subPoseId);\n  }\n\n  for(const View& view : rigViews)\n  {\n    sfmData.views.emplace(view.getViewId(), std::make_shared(view));\n  }\n\n  const Mat3 r = Mat3::Random();\n  const Vec3 c = Vec3::Random();\n  const geometry::Pose3 firstPose(r, c);\n  const IndexT firstPoseId = std::rand() % nbSubPoses;\n\n  const Rig& rig = sfmData.getRig(rigViews.front());\n\n  \/\/ rig uninitialized\n  BOOST_CHECK(!rig.isInitialized());\n\n  sfmData.setPose(rigViews.at(firstPoseId), CameraPose(firstPose));\n\n  \/\/ setPose done, rig initialized\n  BOOST_CHECK(rig.isInitialized());\n\n  \/\/ Check rig sub-poses\n  for(std::size_t subPoseId = 0; subPoseId < nbSubPoses; ++subPoseId)\n  {\n    const RigSubPose& subPose = rig.getSubPose(subPoseId);\n\n    if(subPoseId == firstPoseId)\n    {\n      \/\/ first sub-pose should be initialized\n      BOOST_CHECK(subPose.status != ERigSubPoseStatus::UNINITIALIZED);\n    }\n    else\n    {\n      \/\/ other sub-poses are uninitialized\n      BOOST_CHECK(subPose.status == ERigSubPoseStatus::UNINITIALIZED);\n    }\n\n    \/\/ all sub-poses should be at identity\n    BOOST_CHECK(subPose.pose == geometry::Pose3());\n  }\n\n  \/\/ Check rig pose\n  for(std::size_t subPoseId = 0; subPoseId < nbSubPoses; ++subPoseId)\n  {\n    const View& view = rigViews.at(subPoseId);\n    BOOST_CHECK(sfmData.getPose(view).getTransform() == firstPose);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(rig_setPose)\n{\n  static constexpr IndexT rigId = 0;\n  static constexpr std::size_t nbSubPoses = 5;\n  static constexpr std::size_t nbPoses = 2;\n\n  SfMData sfmData;\n\n  sfmData.intrinsics.emplace(0, std::make_shared(1000, 1000, 36.0, std::rand()%10000, std::rand()%10000));\n  sfmData.getRigs().emplace(rigId, Rig(nbSubPoses));\n\n  std::vector rigViews;\n\n  for(std::size_t poseId = 0; poseId < nbPoses; ++poseId)\n  {\n    for(std::size_t subPoseId = 0; subPoseId < nbSubPoses; ++subPoseId)\n    {\n      const IndexT viewId = poseId * nbSubPoses + subPoseId;\n      rigViews.emplace_back(\"\", viewId, 0, poseId, 10, 10, rigId, subPoseId);\n    }\n  }\n\n  for(const View& view : rigViews)\n  {\n    sfmData.views.emplace(view.getViewId(), std::make_shared(view));\n  }\n\n  const Rig& rig = sfmData.getRig(rigViews.front());\n\n  for(std::size_t poseId = 0; poseId < nbPoses; ++poseId)\n  {\n    for(std::size_t subPoseId = 0; subPoseId < nbSubPoses; ++subPoseId)\n    {\n      const IndexT viewId = poseId * nbSubPoses + subPoseId;\n      const View& view = *(sfmData.views.at(viewId));\n      const RigSubPose& subPose = rig.getSubPose(subPoseId);\n\n      if(subPoseId == 0)\n      {\n        \/\/ first sub-pose, rig pose is unknown\n        BOOST_CHECK(!sfmData.existsPose(view));\n\n        if(poseId == 0)\n        {\n          \/\/ first rig pose, first sub-pose, sub-pose uninitialized\n          BOOST_CHECK(subPose.status == ERigSubPoseStatus::UNINITIALIZED);\n        }\n        else\n        {\n          \/\/ not first rig pose, first sub-pose, sub-pose initialized\n          BOOST_CHECK(subPose.status != ERigSubPoseStatus::UNINITIALIZED);\n        }\n\n        const Mat3 r = Mat3::Random();\n        const Vec3 c = Vec3::Random();\n        const geometry::Pose3 firstPose = geometry::Pose3(r, c);\n\n        sfmData.setPose(view, CameraPose(firstPose));\n\n        \/\/ setPose done, sub-pose must be initialized\n        BOOST_CHECK(subPose.status != ERigSubPoseStatus::UNINITIALIZED);\n\n        \/\/ setPose done, rig initialized\n        BOOST_CHECK(sfmData.existsPose(view));\n        BOOST_CHECK(sfmData.getPose(view).getTransform() == firstPose);\n      }\n      else\n      {\n\n        \/\/ rig pose should be initialized\n        BOOST_CHECK(sfmData.existsPose(view));\n\n        if(poseId == 0) \/\/other poses are redundant\n        {\n          const Mat3 r = Mat3::Random();\n          const Vec3 c = Vec3::Random();\n          const geometry::Pose3 pose = geometry::Pose3(r, c);\n\n          \/\/ first rig pose, sub-pose must be uninitialized\n          BOOST_CHECK(subPose.status == ERigSubPoseStatus::UNINITIALIZED);\n\n          sfmData.setPose(view, CameraPose(pose));\n\n          \/\/ setPose done, sub-pose must be initialized\n          BOOST_CHECK(subPose.status != ERigSubPoseStatus::UNINITIALIZED);\n        }\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(rig_getPose)\n{\n  static constexpr IndexT rigId = 0;\n  static constexpr std::size_t nbSubPoses = 5;\n  static constexpr std::size_t nbPoses = 2;\n\n  SfMData sfmData;\n\n  sfmData.intrinsics.emplace(0, std::make_shared(1000, 1000, 36.0, std::rand()%10000, std::rand()%10000));\n  sfmData.getRigs().emplace(rigId, Rig(nbSubPoses));\n\n  std::vector rigViews;\n\n  for(std::size_t poseId = 0; poseId < nbPoses; ++poseId)\n  {\n    for(std::size_t subPoseId = 0; subPoseId < nbSubPoses; ++subPoseId)\n    {\n      const IndexT viewId = poseId * nbSubPoses + subPoseId;\n      rigViews.emplace_back(\"\", viewId, 0, poseId, 10, 10, rigId, subPoseId);\n    }\n  }\n\n  for(const View& view : rigViews)\n  {\n    sfmData.views.emplace(view.getViewId(), std::make_shared(view));\n  }\n\n  const Rig& rig = sfmData.getRig(rigViews.front());\n\n  for(std::size_t poseId = 0; poseId < nbPoses; ++poseId)\n  {\n    for(std::size_t subPoseId = 0; subPoseId < nbSubPoses; ++subPoseId)\n    {\n      const IndexT viewId = poseId * nbSubPoses + subPoseId;\n      const View& view = *(sfmData.views.at(viewId));\n      const RigSubPose& subPose = rig.getSubPose(subPoseId);\n\n      if(subPoseId == 0)\n      {\n        const Mat3 r = Mat3::Random();\n        const Vec3 c = Vec3::Random();\n        const geometry::Pose3 firstPose = geometry::Pose3(r, c);\n\n        sfmData.setPose(view, CameraPose(firstPose));\n\n        \/\/ setPose done, rig initialized\n        if(poseId == 0)\n        {\n          \/\/ the rig pose is the first pose\n          BOOST_CHECK(sfmData.getPose(view).getTransform() == firstPose);\n        }\n        else\n        {\n          \/\/ the rig pose is the sub-pose inverse multiply by the rig pose\n          BOOST_CHECK(sfmData.getPose(view).getTransform() == (subPose.pose.inverse() * firstPose));\n        }\n\n      }\n      else\n      {\n        const geometry::Pose3 rigPose = sfmData.getPose(view).getTransform();\n\n        if(poseId == 0) \/\/other poses are redundant\n        {\n          const Mat3 r = Mat3::Random();\n          const Vec3 c = Vec3::Random();\n          const geometry::Pose3 absolutePose = geometry::Pose3(r, c);\n\n          sfmData.setPose(view, CameraPose(absolutePose));\n\n          \/\/ the view sub-pose is the absolute pose multiply by the rig pose inverse\n          BOOST_CHECK(subPose.pose == (absolutePose * rigPose.inverse()));\n        }\n\n        \/\/ the view absolute pose is the sub-pose multiply by the rig pose\n        BOOST_CHECK(sfmData.getPose(view).getTransform() == (subPose.pose * sfmData.getAbsolutePose(view.getPoseId()).getTransform()));\n      }\n    }\n  }\n}\n<|endoftext|>"}
{"text":"\/\/\/ @file\n\/\/\/ @author uentity\n\/\/\/ @date 29.05.2019\n\/\/\/ @brief Tree filesystem archive implementation\n\/\/\/ @copyright\n\/\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/\n\n#include \"tree_fs_impl.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\nNAMESPACE_BEGIN(blue_sky)\nnamespace fs = std::filesystem;\nusing NodeLoad = tree_fs_input::NodeLoad;\n\nconst auto uuid_from_str = boost::uuids::string_generator{};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/  tree_fs_input::impl\n\/\/\nstruct tree_fs_input::impl : detail::file_heads_manager {\n\tusing heads_mgr_t = detail::file_heads_manager;\n\tusing fmanager_t = detail::objfrm_manager;\n\tusing Error = tree::Error;\n\n\timpl(std::string root_fname, NodeLoad mode) :\n\t\theads_mgr_t{std::move(root_fname)}, mode_(mode),\n\t\tmanager_(kernel::radio::system().spawn(false))\n\t{}\n\n\tauto begin_node(tree_fs_input& ar) -> error {\n\t\treturn error::eval_safe(\n\t\t\t\/\/ node reference (2nd arg) is ONLY used for template matching\n\t\t\t[&]{ return head().map( [&](auto* ar) { prologue(*ar, *(tree::node*)nullptr); }); },\n\t\t\t[&]{ return enter_root(); }\n\t\t);\n\t}\n\n\tauto end_node(tree_fs_input& ar, tree::node& N) -> error {\n\t\tif(cur_path_.empty()) return Error::NodeWasntStarted;\n\n\t\t\/\/ always return to parent dir after node is loaded\n\t\tauto finally = scope_guard{[=, p = cur_path_] {\n\t\t\tif(auto er = enter_dir(p, cur_path_)) throw er;\n\t\t}};\n\n\t\tstd::string node_dir;\n\t\tstd::vector leafs_order;\n\t\treturn error::eval_safe(\n\t\t\t\/\/ read node's metadata\n\t\t\t[&]{ return head().map( [&](auto* ar) {\n\t\t\t\t(*ar)(cereal::make_nvp(\"node_dir\", node_dir));\n\t\t\t\t(*ar)(cereal::make_nvp(\"leafs_order\", leafs_order));\n\t\t\t\t\/\/ we finished reading node\n\t\t\t\tepilogue(*ar, N);\n\t\t\t}); },\n\t\t\t\/\/ load leafs\n\t\t\t[&]{ return load_node(ar, N, std::move(node_dir), std::move(leafs_order)); }\n\t\t);\n\t}\n\n\tauto load_node(\n\t\ttree_fs_input& ar, tree::node& N, std::string node_dir, std::vector leafs_order\n\t) -> error {\n\t\tusing Options = fs::directory_options;\n\n\t\t\/\/ skip empty dirs in normal mode\n\t\tif(mode_ == NodeLoad::Normal && leafs_order.empty()) return perfect;\n\t\t\/\/ enter node's dir\n\t\tif(auto er = enter_dir(cur_path_ \/ node_dir, cur_path_)) return er;\n\n\t\tstd::string united_err_msg;\n\t\tauto push_error = [&](auto er) {\n\t\t\tif(er.ok()) return;\n\t\t\tif(!united_err_msg.empty()) united_err_msg += \" | \";\n\t\t\tunited_err_msg += er.what();\n\t\t};\n\n\t\t\/\/ fill leafs by scanning directory and loading link files\n\t\tconst auto normal_load = [&] { std::for_each(\n\t\t\tleafs_order.begin(), leafs_order.end(),\n\t\t\t[&](auto& f) {\n\t\t\t\tpush_error(error::eval_safe(\n\t\t\t\t\t[&] { add_head(cur_path_ \/ std::move(f)); },\n\t\t\t\t\t[&] {\n\t\t\t\t\t\tauto finally = detail::scope_guard{[this]{ pop_head(); }};\n\t\t\t\t\t\ttree::link L;\n\t\t\t\t\t\tar(L);\n\t\t\t\t\t\tN.insert(std::move(L));\n\t\t\t\t\t}\n\t\t\t\t));\n\t\t\t}\n\t\t); };\n\n\t\tconst auto recover_load = [&] {\n\t\t\t\/\/ setup node iterator\n\t\t\tauto Niter = fs::directory_iterator{};\n\t\t\tif(auto er = error::eval_safe([&] {\n\t\t\t\tNiter = fs::directory_iterator(cur_path_, Options::skip_permission_denied);\n\t\t\t})) {\n\t\t\t\tpush_error(std::move(er));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/ read links\n\t\t\tfor(auto& f : Niter) {\n\t\t\t\t\/\/ skip directories\n\t\t\t\tif(error::eval_safe([&]{ return !fs::is_directory(f); })) continue;\n\n\t\t\t\t\/\/ try load file as a link\n\t\t\t\tpush_error(error::eval_safe(\n\t\t\t\t\t[&] { add_head(f); },\n\t\t\t\t\t[&] {\n\t\t\t\t\t\tauto finally = detail::scope_guard{[this]{ pop_head(); }};\n\t\t\t\t\t\ttree::link L;\n\t\t\t\t\t\tar(L);\n\t\t\t\t\t\tN.insert(std::move(L));\n\t\t\t\t\t}\n\t\t\t\t));\n\t\t\t}\n\n\t\t\t\/\/ [NOTE] implementation with parallel STL\n\t\t\t\/\/std::for_each(\n\t\t\t\/\/\tstd::execution::par, begin(Niter), end(Niter),\n\t\t\t\/\/\t[&](auto& f) {\n\t\t\t\/\/\t\t\/\/ skip directories\n\t\t\t\/\/\t\tif(error::eval_safe([&]{ return !fs::is_directory(f); })) return;\n\n\t\t\t\/\/\t\t\/\/ try load file as a link\n\t\t\t\/\/\t\tpush_error(error::eval_safe(\n\t\t\t\/\/\t\t\t[&] { add_head(f); },\n\t\t\t\/\/\t\t\t[&] {\n\t\t\t\/\/\t\t\t\tauto finally = detail::scope_guard{[this]{ pop_head(); }};\n\n\t\t\t\/\/\t\t\t\ttree::link L;\n\t\t\t\/\/\t\t\t\tar(L);\n\t\t\t\/\/\t\t\t\tN.insert(std::move(L));\n\t\t\t\/\/\t\t\t}\n\t\t\t\/\/\t\t));\n\t\t\t\/\/\t}\n\t\t\t\/\/);\n\n\t\t\t\/\/ restore links order\n\t\t\tusing namespace tree;\n\t\t\tif(N.size() < 2 || leafs_order.size() < 2) return;\n\n\t\t\t\/\/ convert string uids to UUIDs\n\t\t\tauto wanted_order = lids_v(leafs_order.size());\n\t\t\tstd::transform(\n\t\t\t\tleafs_order.cbegin(), leafs_order.cend(), wanted_order.begin(),\n\t\t\t\t[](const auto& s_uid) { return uuid_from_str(s_uid); }\n\t\t\t);\n\n\t\t\t\/\/ extract current order of link IDs\n\t\t\tauto res_order = N.keys(Key::AnyOrder);\n\n\t\t\t\/\/ sort according to passed `leafs_order`\n\t\t\tconst auto lo_begin = wanted_order.begin(), lo_end = wanted_order.end();\n\t\t\tstd::sort(res_order.begin(), res_order.end(), [&](auto i1, auto i2) {\n\t\t\t\treturn std::find(lo_begin, lo_end, i1) < std::find(lo_begin, lo_end, i2);\n\t\t\t});\n\t\t\t\/\/ apply custom order\n\t\t\tN.rearrange(std::move(res_order));\n\t\t};\n\n\t\t\/\/ invoke laod\n\t\tif(mode_ == NodeLoad::Normal)\n\t\t\tnormal_load();\n\t\telse\n\t\t\trecover_load();\n\n\t\tif(united_err_msg.empty()) return perfect;\n\t\telse return united_err_msg;\n\t}\n\n\tauto load_object(tree_fs_input& ar, objbase& obj) -> error {\n\treturn error::eval_safe([&]() -> error {\n\t\tauto cur_head = head();\n\t\tif(!cur_head) return cur_head.error();\n\t\t\/\/ open node & close on exit\n\t\tprologue(*cur_head.value(), obj);\n\t\tauto finally = scope_guard{ [&]{ epilogue(*cur_head.value(), obj); } };\n\n\t\t\/\/ 1, 2. read object format & filename\n\t\tstd::string obj_filename, obj_frm;\n\t\tar(\n\t\t\tcereal::make_nvp(\"fmt\", obj_frm),\n\t\t\tcereal::make_nvp(\"filename\", obj_filename)\n\t\t);\n\n\t\t\/\/ obtain formatter\n\t\tauto F = get_formatter(obj.type_id(), obj_frm);\n\t\tif(!F) return { fmt::format(\"{} -> {}\", obj.type_id(), obj_frm), Error::MissingFormatter };\n\n\t\t\/\/ 3. if object is node and formatter don't store leafs, then load 'em explicitly\n\t\tif(obj.is_node() && !F->stores_node)\n\t\t\tar(cereal::make_nvp( \"node\", static_cast(obj) ));\n\t\telse\n\t\t\t(**cur_head)(cereal::make_nvp( \"object\", obj ));\n\n\t\t\/\/ 4. read object data from specified file\n\t\tEVAL\n\t\t\t[&]{ return enter_root(); },\n\t\t\t[&]{ return objects_path_.empty() ?\n\t\t\t\tenter_dir(root_path_ \/ objects_dname_, objects_path_) : perfect;\n\t\t\t}\n\t\tRETURN_EVAL_ERR\n\n\t\tauto obj_path = objects_path_ \/ obj_filename;\n\t\tauto abs_obj_path = fs::path{};\n\t\tSCOPE_EVAL_SAFE\n\t\t\tabs_obj_path = fs::absolute(obj_path);\n\t\tRETURN_SCOPE_ERR\n\n\t\tcaf::anon_send(\n\t\t\tmanager_, caf::actor_cast(manager_),\n\t\t\tconst_cast(obj).shared_from_this(), obj_frm, fs::absolute(obj_path).u8string()\n\t\t);\n\t\t\/\/ defer wait until save completes\n\t\tif(!has_wait_deferred_) {\n\t\t\tar(cereal::defer(cereal::Functor{ [](auto& ar){ ar.wait_objects_loaded(); } }));\n\t\t\thas_wait_deferred_ = true;\n\t\t}\n\t\treturn perfect;\n\t}); }\n\n\tauto wait_objects_loaded(timespan how_long) -> std::vector {\n\t\tauto res = fmanager_t::wait_jobs_done(manager_, how_long);\n\t\thas_wait_deferred_ = false;\n\t\treturn res;\n\t}\n\n\tNodeLoad mode_;\n\t\/\/ async loaders manager\n\tfmanager_t::actor_type manager_;\n\tbool has_wait_deferred_ = false;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/  input archive\n\/\/\ntree_fs_input::tree_fs_input(std::string root_fname, NodeLoad mode)\n\t: Base(this), pimpl_{ std::make_unique(std::move(root_fname), mode) }\n{}\n\ntree_fs_input::~tree_fs_input() = default;\n\nauto tree_fs_input::head() -> result_or_err {\n\treturn pimpl_->head();\n}\n\nauto tree_fs_input::begin_node() -> error {\n\treturn pimpl_->begin_node(*this);\n}\n\nauto tree_fs_input::end_node(const tree::node& N) -> error {\n\treturn pimpl_->end_node(*this, const_cast(N));\n}\n\nauto tree_fs_input::load_object(objbase& obj) -> error {\n\treturn pimpl_->load_object(*this, obj);\n}\n\nauto tree_fs_input::wait_objects_loaded(timespan how_long) const -> std::vector {\n\treturn pimpl_->wait_objects_loaded(how_long);\n}\n\nauto tree_fs_input::loadBinaryValue(void* data, size_t size, const char* name) -> void {\n\thead().map([=](auto* jar) {\n\t\tjar->loadBinaryValue(data, size, name);\n\t});\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/  prologue, epilogue\n\/\/\nauto prologue(tree_fs_input& ar, tree::node const&) -> void {\n\tar.begin_node();\n}\n\nauto epilogue(tree_fs_input& ar, tree::node const& N) -> void {\n\tar.end_node(N);\n}\n\nauto prologue(\n\ttree_fs_input& ar, cereal::memory_detail::LoadAndConstructLoadWrapper const&\n) -> void {\n\tar.begin_node();\n}\n\nauto epilogue(\n\ttree_fs_input& ar, cereal::memory_detail::LoadAndConstructLoadWrapper const& N\n) -> void {\n\tar.end_node( *const_cast&>(N.construct).ptr() );\n}\n\nNAMESPACE_END(blue_sky)\nserial\/tree_fs: emulate never-accessed node ref via uninitialized `std::optional`\/\/\/ @file\n\/\/\/ @author uentity\n\/\/\/ @date 29.05.2019\n\/\/\/ @brief Tree filesystem archive implementation\n\/\/\/ @copyright\n\/\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/\n\n#include \"tree_fs_impl.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\nNAMESPACE_BEGIN(blue_sky)\nnamespace fs = std::filesystem;\nusing NodeLoad = tree_fs_input::NodeLoad;\n\nconst auto uuid_from_str = boost::uuids::string_generator{};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/  tree_fs_input::impl\n\/\/\nstruct tree_fs_input::impl : detail::file_heads_manager {\n\tusing heads_mgr_t = detail::file_heads_manager;\n\tusing fmanager_t = detail::objfrm_manager;\n\tusing Error = tree::Error;\n\n\timpl(std::string root_fname, NodeLoad mode) :\n\t\theads_mgr_t{std::move(root_fname)}, mode_(mode),\n\t\tmanager_(kernel::radio::system().spawn(false))\n\t{}\n\n\tauto begin_node(tree_fs_input& ar) -> error {\n\t\tstatic const auto sentinel = std::optional{};\n\t\treturn error::eval_safe(\n\t\t\t\/\/ sentinel is ONLY used for template matching\n\t\t\t[&]{ return head().map( [&](auto* ar) { prologue(*ar, *sentinel); }); },\n\t\t\t[&]{ return enter_root(); }\n\t\t);\n\t}\n\n\tauto end_node(tree_fs_input& ar, tree::node& N) -> error {\n\t\tif(cur_path_.empty()) return Error::NodeWasntStarted;\n\n\t\t\/\/ always return to parent dir after node is loaded\n\t\tauto finally = scope_guard{[=, p = cur_path_] {\n\t\t\tif(auto er = enter_dir(p, cur_path_)) throw er;\n\t\t}};\n\n\t\tstd::string node_dir;\n\t\tstd::vector leafs_order;\n\t\treturn error::eval_safe(\n\t\t\t\/\/ read node's metadata\n\t\t\t[&]{ return head().map( [&](auto* ar) {\n\t\t\t\t(*ar)(cereal::make_nvp(\"node_dir\", node_dir));\n\t\t\t\t(*ar)(cereal::make_nvp(\"leafs_order\", leafs_order));\n\t\t\t\t\/\/ we finished reading node\n\t\t\t\tepilogue(*ar, N);\n\t\t\t}); },\n\t\t\t\/\/ load leafs\n\t\t\t[&]{ return load_node(ar, N, std::move(node_dir), std::move(leafs_order)); }\n\t\t);\n\t}\n\n\tauto load_node(\n\t\ttree_fs_input& ar, tree::node& N, std::string node_dir, std::vector leafs_order\n\t) -> error {\n\t\tusing Options = fs::directory_options;\n\n\t\t\/\/ skip empty dirs in normal mode\n\t\tif(mode_ == NodeLoad::Normal && leafs_order.empty()) return perfect;\n\t\t\/\/ enter node's dir\n\t\tif(auto er = enter_dir(cur_path_ \/ node_dir, cur_path_)) return er;\n\n\t\tstd::string united_err_msg;\n\t\tauto push_error = [&](auto er) {\n\t\t\tif(er.ok()) return;\n\t\t\tif(!united_err_msg.empty()) united_err_msg += \" | \";\n\t\t\tunited_err_msg += er.what();\n\t\t};\n\n\t\t\/\/ fill leafs by scanning directory and loading link files\n\t\tconst auto normal_load = [&] { std::for_each(\n\t\t\tleafs_order.begin(), leafs_order.end(),\n\t\t\t[&](auto& f) {\n\t\t\t\tpush_error(error::eval_safe(\n\t\t\t\t\t[&] { add_head(cur_path_ \/ std::move(f)); },\n\t\t\t\t\t[&] {\n\t\t\t\t\t\tauto finally = detail::scope_guard{[this]{ pop_head(); }};\n\t\t\t\t\t\ttree::link L;\n\t\t\t\t\t\tar(L);\n\t\t\t\t\t\tN.insert(std::move(L));\n\t\t\t\t\t}\n\t\t\t\t));\n\t\t\t}\n\t\t); };\n\n\t\tconst auto recover_load = [&] {\n\t\t\t\/\/ setup node iterator\n\t\t\tauto Niter = fs::directory_iterator{};\n\t\t\tif(auto er = error::eval_safe([&] {\n\t\t\t\tNiter = fs::directory_iterator(cur_path_, Options::skip_permission_denied);\n\t\t\t})) {\n\t\t\t\tpush_error(std::move(er));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/ read links\n\t\t\tfor(auto& f : Niter) {\n\t\t\t\t\/\/ skip directories\n\t\t\t\tif(error::eval_safe([&]{ return !fs::is_directory(f); })) continue;\n\n\t\t\t\t\/\/ try load file as a link\n\t\t\t\tpush_error(error::eval_safe(\n\t\t\t\t\t[&] { add_head(f); },\n\t\t\t\t\t[&] {\n\t\t\t\t\t\tauto finally = detail::scope_guard{[this]{ pop_head(); }};\n\t\t\t\t\t\ttree::link L;\n\t\t\t\t\t\tar(L);\n\t\t\t\t\t\tN.insert(std::move(L));\n\t\t\t\t\t}\n\t\t\t\t));\n\t\t\t}\n\n\t\t\t\/\/ [NOTE] implementation with parallel STL\n\t\t\t\/\/std::for_each(\n\t\t\t\/\/\tstd::execution::par, begin(Niter), end(Niter),\n\t\t\t\/\/\t[&](auto& f) {\n\t\t\t\/\/\t\t\/\/ skip directories\n\t\t\t\/\/\t\tif(error::eval_safe([&]{ return !fs::is_directory(f); })) return;\n\n\t\t\t\/\/\t\t\/\/ try load file as a link\n\t\t\t\/\/\t\tpush_error(error::eval_safe(\n\t\t\t\/\/\t\t\t[&] { add_head(f); },\n\t\t\t\/\/\t\t\t[&] {\n\t\t\t\/\/\t\t\t\tauto finally = detail::scope_guard{[this]{ pop_head(); }};\n\n\t\t\t\/\/\t\t\t\ttree::link L;\n\t\t\t\/\/\t\t\t\tar(L);\n\t\t\t\/\/\t\t\t\tN.insert(std::move(L));\n\t\t\t\/\/\t\t\t}\n\t\t\t\/\/\t\t));\n\t\t\t\/\/\t}\n\t\t\t\/\/);\n\n\t\t\t\/\/ restore links order\n\t\t\tusing namespace tree;\n\t\t\tif(N.size() < 2 || leafs_order.size() < 2) return;\n\n\t\t\t\/\/ convert string uids to UUIDs\n\t\t\tauto wanted_order = lids_v(leafs_order.size());\n\t\t\tstd::transform(\n\t\t\t\tleafs_order.cbegin(), leafs_order.cend(), wanted_order.begin(),\n\t\t\t\t[](const auto& s_uid) { return uuid_from_str(s_uid); }\n\t\t\t);\n\n\t\t\t\/\/ extract current order of link IDs\n\t\t\tauto res_order = N.keys(Key::AnyOrder);\n\n\t\t\t\/\/ sort according to passed `leafs_order`\n\t\t\tconst auto lo_begin = wanted_order.begin(), lo_end = wanted_order.end();\n\t\t\tstd::sort(res_order.begin(), res_order.end(), [&](auto i1, auto i2) {\n\t\t\t\treturn std::find(lo_begin, lo_end, i1) < std::find(lo_begin, lo_end, i2);\n\t\t\t});\n\t\t\t\/\/ apply custom order\n\t\t\tN.rearrange(std::move(res_order));\n\t\t};\n\n\t\t\/\/ invoke laod\n\t\tif(mode_ == NodeLoad::Normal)\n\t\t\tnormal_load();\n\t\telse\n\t\t\trecover_load();\n\n\t\tif(united_err_msg.empty()) return perfect;\n\t\telse return united_err_msg;\n\t}\n\n\tauto load_object(tree_fs_input& ar, objbase& obj) -> error {\n\treturn error::eval_safe([&]() -> error {\n\t\tauto cur_head = head();\n\t\tif(!cur_head) return cur_head.error();\n\t\t\/\/ open node & close on exit\n\t\tprologue(*cur_head.value(), obj);\n\t\tauto finally = scope_guard{ [&]{ epilogue(*cur_head.value(), obj); } };\n\n\t\t\/\/ 1, 2. read object format & filename\n\t\tstd::string obj_filename, obj_frm;\n\t\tar(\n\t\t\tcereal::make_nvp(\"fmt\", obj_frm),\n\t\t\tcereal::make_nvp(\"filename\", obj_filename)\n\t\t);\n\n\t\t\/\/ obtain formatter\n\t\tauto F = get_formatter(obj.type_id(), obj_frm);\n\t\tif(!F) return { fmt::format(\"{} -> {}\", obj.type_id(), obj_frm), Error::MissingFormatter };\n\n\t\t\/\/ 3. if object is node and formatter don't store leafs, then load 'em explicitly\n\t\tif(obj.is_node() && !F->stores_node)\n\t\t\tar(cereal::make_nvp( \"node\", static_cast(obj) ));\n\t\telse\n\t\t\t(**cur_head)(cereal::make_nvp( \"object\", obj ));\n\n\t\t\/\/ 4. read object data from specified file\n\t\tEVAL\n\t\t\t[&]{ return enter_root(); },\n\t\t\t[&]{ return objects_path_.empty() ?\n\t\t\t\tenter_dir(root_path_ \/ objects_dname_, objects_path_) : perfect;\n\t\t\t}\n\t\tRETURN_EVAL_ERR\n\n\t\tauto obj_path = objects_path_ \/ obj_filename;\n\t\tauto abs_obj_path = fs::path{};\n\t\tSCOPE_EVAL_SAFE\n\t\t\tabs_obj_path = fs::absolute(obj_path);\n\t\tRETURN_SCOPE_ERR\n\n\t\tcaf::anon_send(\n\t\t\tmanager_, caf::actor_cast(manager_),\n\t\t\tconst_cast(obj).shared_from_this(), obj_frm, fs::absolute(obj_path).u8string()\n\t\t);\n\t\t\/\/ defer wait until save completes\n\t\tif(!has_wait_deferred_) {\n\t\t\tar(cereal::defer(cereal::Functor{ [](auto& ar){ ar.wait_objects_loaded(); } }));\n\t\t\thas_wait_deferred_ = true;\n\t\t}\n\t\treturn perfect;\n\t}); }\n\n\tauto wait_objects_loaded(timespan how_long) -> std::vector {\n\t\tauto res = fmanager_t::wait_jobs_done(manager_, how_long);\n\t\thas_wait_deferred_ = false;\n\t\treturn res;\n\t}\n\n\tNodeLoad mode_;\n\t\/\/ async loaders manager\n\tfmanager_t::actor_type manager_;\n\tbool has_wait_deferred_ = false;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/  input archive\n\/\/\ntree_fs_input::tree_fs_input(std::string root_fname, NodeLoad mode)\n\t: Base(this), pimpl_{ std::make_unique(std::move(root_fname), mode) }\n{}\n\ntree_fs_input::~tree_fs_input() = default;\n\nauto tree_fs_input::head() -> result_or_err {\n\treturn pimpl_->head();\n}\n\nauto tree_fs_input::begin_node() -> error {\n\treturn pimpl_->begin_node(*this);\n}\n\nauto tree_fs_input::end_node(const tree::node& N) -> error {\n\treturn pimpl_->end_node(*this, const_cast(N));\n}\n\nauto tree_fs_input::load_object(objbase& obj) -> error {\n\treturn pimpl_->load_object(*this, obj);\n}\n\nauto tree_fs_input::wait_objects_loaded(timespan how_long) const -> std::vector {\n\treturn pimpl_->wait_objects_loaded(how_long);\n}\n\nauto tree_fs_input::loadBinaryValue(void* data, size_t size, const char* name) -> void {\n\thead().map([=](auto* jar) {\n\t\tjar->loadBinaryValue(data, size, name);\n\t});\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/  prologue, epilogue\n\/\/\nauto prologue(tree_fs_input& ar, tree::node const&) -> void {\n\tar.begin_node();\n}\n\nauto epilogue(tree_fs_input& ar, tree::node const& N) -> void {\n\tar.end_node(N);\n}\n\nauto prologue(\n\ttree_fs_input& ar, cereal::memory_detail::LoadAndConstructLoadWrapper const&\n) -> void {\n\tar.begin_node();\n}\n\nauto epilogue(\n\ttree_fs_input& ar, cereal::memory_detail::LoadAndConstructLoadWrapper const& N\n) -> void {\n\tar.end_node( *const_cast&>(N.construct).ptr() );\n}\n\nNAMESPACE_END(blue_sky)\n<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \n\n#include \"bin\/utils.h\"\n\nOSError::OSError() {\n  set_code(errno);\n  SetMessage(strerror(errno));\n}\nFix missing member initialization on Mac OS\/\/ Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \n\n#include \"bin\/utils.h\"\n\nOSError::OSError() : code_(0), message_(NULL) {\n  set_code(errno);\n  SetMessage(strerror(errno));\n}\n<|endoftext|>"}
{"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1680\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n    \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n    DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1095644 by johtaylo@johtaylo-JTBUILDER03-increment on 2014\/11\/11 03:00:13\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1681\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n    \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n    DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"}
{"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2400\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n    \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n    DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1396638 by johtaylo@johtaylo-jtincrementor-increment on 2017\/04\/11 03:00:05\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2401\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n    \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n    DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"}
{"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif  \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2906\n#endif  \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif  \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif  \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING                                                                           \\\n  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \\\n  \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO                                                                          \\\n  \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \\\n      \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif  \/\/ ATI_PLATFORM_INFO\n\n#endif  \/\/ VERSIONS_HPP_\nP4 to Git Change 1786576 by chui@ocl-promo-incrementor on 2019\/05\/23 03:00:03\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif  \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2907\n#endif  \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif  \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif  \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING                                                                           \\\n  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \\\n  \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO                                                                          \\\n  \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \\\n      \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif  \/\/ ATI_PLATFORM_INFO\n\n#endif  \/\/ VERSIONS_HPP_\n<|endoftext|>"}
{"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2300\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n    \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n    DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1351938 by johtaylo@johtaylo-jtincrementor-increment on 2016\/12\/11 03:00:04\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2301\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n    \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n    DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"}
{"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif  \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2517\n#endif  \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif  \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif  \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING                                                                           \\\n  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \\\n  \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO                                                                          \\\n  \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \\\n      \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif  \/\/ ATI_PLATFORM_INFO\n\n#endif  \/\/ VERSIONS_HPP_\nP4 to Git Change 1469594 by johtaylo@johtaylo-jtincrementor2-increment on 2017\/10\/13 03:00:04\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif  \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2518\n#endif  \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif  \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif  \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING                                                                           \\\n  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \\\n  \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO                                                                          \\\n  \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \\\n      \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif  \/\/ ATI_PLATFORM_INFO\n\n#endif  \/\/ VERSIONS_HPP_\n<|endoftext|>"}
{"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif  \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2567\n#endif  \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif  \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif  \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING                                                                           \\\n  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \\\n  \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO                                                                          \\\n  \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \\\n      \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif  \/\/ ATI_PLATFORM_INFO\n\n#endif  \/\/ VERSIONS_HPP_\nP4 to Git Change 1500642 by johtaylo@johtaylo-jtincrementor2-increment on 2018\/01\/06 03:00:04\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif  \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2568\n#endif  \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif  \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif  \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING                                                                           \\\n  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \\\n  \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO                                                                          \\\n  \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \\\n      \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif  \/\/ ATI_PLATFORM_INFO\n\n#endif  \/\/ VERSIONS_HPP_\n<|endoftext|>"}
{"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2250\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n    \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n    DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1329729 by johtaylo@johtaylo-jtincrementor-increment on 2016\/10\/21 03:00:11\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2251\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n    \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n    DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"}
{"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif  \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3049\n#endif  \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif  \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif  \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING                                                                           \\\n  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \\\n  \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO                                                                          \\\n  \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \\\n      \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif  \/\/ ATI_PLATFORM_INFO\n\n#endif  \/\/ VERSIONS_HPP_\nP4 to Git Change 2038561 by chui@ocl-promo-incrementor on 2019\/11\/29 03:00:14\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif  \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3050\n#endif  \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif  \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif  \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING                                                                           \\\n  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \\\n  \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO                                                                          \\\n  \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \\\n      \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif  \/\/ ATI_PLATFORM_INFO\n\n#endif  \/\/ VERSIONS_HPP_\n<|endoftext|>"}
{"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif  \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2877\n#endif  \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif  \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif  \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING                                                                           \\\n  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \\\n  \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO                                                                          \\\n  \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \\\n      \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif  \/\/ ATI_PLATFORM_INFO\n\n#endif  \/\/ VERSIONS_HPP_\nP4 to Git Change 1768921 by chui@ocl-promo-incrementor on 2019\/04\/12 03:00:40\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif  \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2878\n#endif  \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif  \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif  \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING                                                                           \\\n  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \\\n  \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO                                                                          \\\n  \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \\\n      \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif  \/\/ ATI_PLATFORM_INFO\n\n#endif  \/\/ VERSIONS_HPP_\n<|endoftext|>"}
{"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1997\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n    \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n    DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1225522 by johtaylo@johtaylo-JTBUILDER03-increment on 2016\/01\/07 03:00:14\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1998\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n    \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n    DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"}
{"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1788\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n    \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n    DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1145697 by johtaylo@johtaylo-JTBUILDER03-increment on 2015\/04\/29 03:00:12\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1789\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n    \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n    DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"}
{"text":"\/**\n *      _____\n *     \/  _  \\\n *    \/ _\/ \\  \\\n *   \/ \/ \\_\/   \\\n *  \/  \\_\/  _   \\  ___  _    ___   ___   ____   ____   ___   _____  _   _\n *  \\  \/ \\_\/ \\  \/ \/  _\\| |  | __| \/ _ \\ | ++ \\ | ++ \\ \/ _ \\ |_   _|| | | |\n *   \\ \\_\/ \\_\/ \/  | |  | |  | ++ | |_| || ++ \/ | ++_\/| |_| |  | |  | +-+ |\n *    \\  \\_\/  \/   | |_ | |_ | ++ |  _  || |\\ \\ | |   |  _  |  | |  | +-+ |\n *     \\_____\/    \\___\/|___||___||_| |_||_| \\_\\|_|   |_| |_|  |_|  |_| |_|\n *             ROBOTICS™\n *\n *  File: kinova_ros_types.cpp\n *  Desc: Wrappers around Kinova structs to facilitate easier conversion to ROS\n *\t\t  types.\n *  Auth: Alex Bencz\n *\n *  Copyright (c) 2013, Clearpath Robotics, Inc.\n *  All Rights Reserved\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and\/or other materials provided with the distribution.\n *     * Neither the name of Clearpath Robotics, Inc. nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL CLEARPATH ROBOTICS, INC. BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Please send comments, questions, or patches to skynet@clearpathrobotics.com\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace kinova\n{\n\n\/\/ %Tag(converntion functions)%\n\n\n\/\/ rads 0 to 2*M_PI\nfloat normalizePositiveInRads(float rads)\n{\n    return static_cast(angles::normalize_angle_positive(rads));\n}\n\n\/\/ rads -M_PI to M_PI\nfloat normalizeInRads(float rads)\n{\n    return static_cast(angles::normalize_angle(rads));\n}\n\n\/\/ degrees 0 to 360\nfloat normalizePositiveInDegrees(float degrees)\n{\n    return angles::to_degrees(angles::normalize_angle_positive(angles::from_degrees(degrees)));\n}\n\n\/\/ degrees -180 to 180\nfloat normalizeInDegrees(float degrees)\n{\n    return angles::to_degrees(angles::normalize_angle(angles::from_degrees(degrees)));\n}\n\n\/\/ %EndTag(converntion functions)%\n\n\nbool areValuesClose(float first, float second, float tolerance)\n{\n    return ((first <= second + tolerance) && (first >= second - tolerance));\n}\n\n\n\/\/ Exceptions\n\/\/ ----------\nKinovaCommException::KinovaCommException(const std::string& message, const int error_code)\n{\n    std::stringstream ss;\n        ss << \"KinovaCommException: \" << message << \" (return code: \" << error_code << \")\" << std::endl;\n    desc_ = ss.str();\n}\n\n\nconst char* KinovaCommException::what() const throw()\n{\n    return desc_.c_str();\n}\n\n\n\/\/ Class definitions\n\/\/ -----------------\n\/**\n * @brief obtain KinovaPosefrom geometry_msgs::Pose.\n *\n * obtain KinovaPose[X,Y,Z,ThetaX,ThetaY,ThetaZ] from geometry_msgs::Pose[x,y,z,qx,qy,qz,qw].\n * Euler angles[] are extracted from tf::Matrix3x3 EulerYPR = Rz(tz)*Ry(ty)*Rx(tx), where EulerYPR is generated by Quaterion q.\n * Units are in meters and radians\n * @param geometry_msgs ROS standard pose[x,y,z,qx,qy,qz,qw], in meters and quaterion.\n *\/\nKinovaPose::KinovaPose(const geometry_msgs::Pose &pose)\n{\n    double tx, ty, tz;\n    tf::Quaternion q;\n    tf::quaternionMsgToTF(pose.orientation, q);\n\n    tf::Matrix3x3 bt_q(q);\n\n    \/\/ tf::Matrix3x3 EulerYPR = Rz(tz)*Ry(ty)*Rx(tx)\n    bt_q.getEulerYPR(tz, ty, tx);\n\n    X = static_cast(pose.position.x);\n    Y = static_cast(pose.position.y);\n    Z = static_cast(pose.position.z);\n\n    ThetaX = normalizePositiveInRads(tx);\n    ThetaY = normalizePositiveInRads(ty);\n    ThetaZ = normalizePositiveInRads(tz);\n}\n\n\/**\n * @brief obtain KinovaPosefrom CartesianInfo &pose.\n *\n * KinovaPose[X,Y,Z,ThetaX,ThetaY,ThetaZ]. position are in meters, and orientation is Euler-ZYX = Rz(ThetaZ)*Ry(ThetaY)*Rx(ThetaX).\n *\n * @param pose CartesianInfo units are in meters and degrees\n *\/\nKinovaPose::KinovaPose(const CartesianInfo &pose)\n{\n    X = pose.X;\n    Y = pose.Y;\n    Z = pose.Z;\n\n    ThetaX = normalizePositiveInRads(pose.ThetaX);\n    ThetaY = normalizePositiveInRads(pose.ThetaY);\n    ThetaZ = normalizePositiveInRads(pose.ThetaZ);\n}\n\n\/**\n * @brief construct geometric::Pose message from KinovaPose\n * @return geometry_msgs::Pose[x,y,z,qx,qy,qz,qw] position in meters, orientation is in Quaternion.\n *\/\ngeometry_msgs::Pose KinovaPose::constructPoseMsg()\n{\n    geometry_msgs::Pose pose;\n    tf::Quaternion position_quaternion;\n\n   \/\/ setEulerZYX(tz, ty, tx) == setRPY(tx, ty, tz) == = mz * my * mx. the previous is Euler angle rotating with temp axis, while latter rotates with fixed axis.\n\/\/  position_quaternion.setEulerZYX(ThetaZ, ThetaY, ThetaX);\n    position_quaternion.setRPY(ThetaX, ThetaY, ThetaZ);\n\n    tf::quaternionTFToMsg(position_quaternion, pose.orientation);\n\n    pose.position.x = X;\n    pose.position.y = Y;\n    pose.position.z = Z;\n\n    return pose;\n}\n\n\/**\n * @brief construct geometric::Wrench message from KinovaPose data structure\n *\n * KinovaPose[X,Y,Z,ThetaX,ThetaY,ThetaZ] doesn't store pose information in this case. Instead, it stores force and torque correspondingly.\n *\n * @return geometry_msgs [Fx,Fy,Fz,Tx,Ty,Tz] in Newton and Nm.\n *\/\ngeometry_msgs::Wrench KinovaPose::constructWrenchMsg()\n{\n    geometry_msgs::Wrench wrench;\n\n    wrench.force.x  = X;\n    wrench.force.y  = Y;\n    wrench.force.z  = Z;\n    wrench.torque.x = ThetaX;\n    wrench.torque.y = ThetaY;\n    wrench.torque.z = ThetaZ;\n\n    return wrench;\n}\n\nbool KinovaPose::isCloseToOther(const KinovaPose &other, float position_tolerance, float EulerAngle_tolerance) const\n{\n    bool status = true;\n    status = status && areValuesClose(X, other.X, position_tolerance);\n    status = status && areValuesClose(Y, other.Y, position_tolerance);\n    status = status && areValuesClose(Z, other.Z, position_tolerance);\n    status = status && areValuesClose(ThetaX, other.ThetaX, EulerAngle_tolerance);\n    status = status && areValuesClose(ThetaY, other.ThetaY, EulerAngle_tolerance);\n    status = status && areValuesClose(ThetaZ, other.ThetaZ, EulerAngle_tolerance);\n    return status;\n}\n\n\nKinovaAngles::KinovaAngles(const kinova_msgs::JointAngles &angles, double j6o)\n{\n    Actuator1 = normalizePositiveInDegrees(180.0 - (angles.joint1 * (180.0 \/ M_PI)));\n    Actuator2 = normalizePositiveInDegrees((angles.joint2 * (180.0 \/ M_PI)) + 270.0);\n    Actuator3 = normalizePositiveInDegrees(90.0 - (angles.joint3 * (180.0 \/ M_PI)));\n    Actuator4 = normalizePositiveInDegrees(180.0 - (angles.joint4 * (180.0 \/ M_PI)));\n    Actuator5 = normalizePositiveInDegrees(180.0 - (angles.joint5 * (180.0 \/ M_PI)));\n    Actuator6 = normalizePositiveInDegrees(j6o   - (angles.joint6 * (180.0 \/ M_PI)));\n}\n\n\nKinovaAngles::KinovaAngles(const AngularInfo &angles)\n{\n    Actuator1 = normalizePositiveInDegrees(angles.Actuator1);\n    Actuator2 = normalizePositiveInDegrees(angles.Actuator2);\n    Actuator3 = normalizePositiveInDegrees(angles.Actuator3);\n    Actuator4 = normalizePositiveInDegrees(angles.Actuator4);\n    Actuator5 = normalizePositiveInDegrees(angles.Actuator5);\n    Actuator6 = normalizePositiveInDegrees(angles.Actuator6);\n}\n\n\nkinova_msgs::JointAngles KinovaAngles::constructAnglesMsg(double j6o)\n{\n    kinova_msgs::JointAngles angles;\n    angles.joint1 = (180.0 - Actuator1) \/ (180.0 \/ M_PI);\n    angles.joint2 = (Actuator2 - 270.0) \/ (180.0 \/ M_PI);\n    angles.joint3 = (90.0 - Actuator3) \/ (180.0 \/ M_PI);\n    angles.joint4 = (180.0 - Actuator4) \/ (180.0 \/ M_PI);\n    angles.joint5 = (180.0 - Actuator5) \/ (180.0 \/ M_PI);\n    angles.joint6 = (j6o   - Actuator6) \/ (180.0 \/ M_PI);\n    return angles;\n}\n\n\nbool KinovaAngles::isCloseToOther(const KinovaAngles &other, float tolerance) const\n{\n    bool status = true;\n    status = status && areValuesClose(Actuator1, other.Actuator1, tolerance);\n    status = status && areValuesClose(Actuator2, other.Actuator2, tolerance);\n    status = status && areValuesClose(Actuator3, other.Actuator3, tolerance);\n    status = status && areValuesClose(Actuator4, other.Actuator4, tolerance);\n    status = status && areValuesClose(Actuator5, other.Actuator5, tolerance);\n    status = status && areValuesClose(Actuator6, other.Actuator6, tolerance);\n    return status;\n}\n\n\nFingerAngles::FingerAngles(const kinova_msgs::FingerPosition &position)\n{\n    Finger1 = position.finger1;\n    Finger2 = position.finger2;\n    Finger3 = position.finger3;\n}\n\n\nFingerAngles::FingerAngles(const FingersPosition &angle)\n{\n    Finger1 = angle.Finger1;\n    Finger2 = angle.Finger2;\n    Finger3 = angle.Finger3;\n}\n\n\nkinova_msgs::FingerPosition FingerAngles::constructFingersMsg()\n{\n    kinova_msgs::FingerPosition angles;\n    angles.finger1 = Finger1;\n    angles.finger2 = Finger2;\n    angles.finger3 = Finger3;\n    return angles;\n}\n\n\nbool FingerAngles::isCloseToOther(const FingerAngles &other, float tolerance) const\n{\n    bool status = true;\n    status = status && areValuesClose(Finger1, other.Finger1, tolerance);\n    status = status && areValuesClose(Finger2, other.Finger2, tolerance);\n    status = status && areValuesClose(Finger3, other.Finger3, tolerance);\n    return status;\n}\n\n}  \/\/ namespace kinova\nRegulate the output range for KinovaPose\/**\n *      _____\n *     \/  _  \\\n *    \/ _\/ \\  \\\n *   \/ \/ \\_\/   \\\n *  \/  \\_\/  _   \\  ___  _    ___   ___   ____   ____   ___   _____  _   _\n *  \\  \/ \\_\/ \\  \/ \/  _\\| |  | __| \/ _ \\ | ++ \\ | ++ \\ \/ _ \\ |_   _|| | | |\n *   \\ \\_\/ \\_\/ \/  | |  | |  | ++ | |_| || ++ \/ | ++_\/| |_| |  | |  | +-+ |\n *    \\  \\_\/  \/   | |_ | |_ | ++ |  _  || |\\ \\ | |   |  _  |  | |  | +-+ |\n *     \\_____\/    \\___\/|___||___||_| |_||_| \\_\\|_|   |_| |_|  |_|  |_| |_|\n *             ROBOTICS™\n *\n *  File: kinova_ros_types.cpp\n *  Desc: Wrappers around Kinova structs to facilitate easier conversion to ROS\n *\t\t  types.\n *  Auth: Alex Bencz\n *\n *  Copyright (c) 2013, Clearpath Robotics, Inc.\n *  All Rights Reserved\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and\/or other materials provided with the distribution.\n *     * Neither the name of Clearpath Robotics, Inc. nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL CLEARPATH ROBOTICS, INC. BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Please send comments, questions, or patches to skynet@clearpathrobotics.com\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace kinova\n{\n\n\/\/ %Tag(converntion functions)%\n\n\n\/\/ rads 0 to 2*M_PI\nfloat normalizePositiveInRads(float rads)\n{\n    return static_cast(angles::normalize_angle_positive(rads));\n}\n\n\/\/ rads -M_PI to M_PI\nfloat normalizeInRads(float rads)\n{\n    return static_cast(angles::normalize_angle(rads));\n}\n\n\/\/ degrees 0 to 360\nfloat normalizePositiveInDegrees(float degrees)\n{\n    return angles::to_degrees(angles::normalize_angle_positive(angles::from_degrees(degrees)));\n}\n\n\/\/ degrees -180 to 180\nfloat normalizeInDegrees(float degrees)\n{\n    return angles::to_degrees(angles::normalize_angle(angles::from_degrees(degrees)));\n}\n\n\/\/ %EndTag(converntion functions)%\n\n\nbool areValuesClose(float first, float second, float tolerance)\n{\n    return ((first <= second + tolerance) && (first >= second - tolerance));\n}\n\n\n\/\/ Exceptions\n\/\/ ----------\nKinovaCommException::KinovaCommException(const std::string& message, const int error_code)\n{\n    std::stringstream ss;\n        ss << \"KinovaCommException: \" << message << \" (return code: \" << error_code << \")\" << std::endl;\n    desc_ = ss.str();\n}\n\n\nconst char* KinovaCommException::what() const throw()\n{\n    return desc_.c_str();\n}\n\n\n\/\/ Class definitions\n\/\/ -----------------\n\/**\n * @brief obtain KinovaPosefrom geometry_msgs::Pose.\n *\n * obtain KinovaPose[X,Y,Z,ThetaX,ThetaY,ThetaZ] from geometry_msgs::Pose[x,y,z,qx,qy,qz,qw].\n * Euler angles[] are extracted from tf::Matrix3x3 EulerYPR = Rz(tz)*Ry(ty)*Rx(tx), where EulerYPR is generated by Quaterion.\n * Units are in meters and radians, The range of Euler angles are [-M_PI, M_PI)\n *\n * @param geometry_msgs ROS standard pose[x,y,z,qx,qy,qz,qw], in meters and quaterion.\n *\/\nKinovaPose::KinovaPose(const geometry_msgs::Pose &pose)\n{\n    double tx, ty, tz;\n    tf::Quaternion q;\n    tf::quaternionMsgToTF(pose.orientation, q);\n\n    tf::Matrix3x3 bt_q(q);\n\n    \/\/ tf::Matrix3x3 EulerYPR = Rz(tz)*Ry(ty)*Rx(tx)\n    bt_q.getEulerYPR(tz, ty, tx);\n\n    X = static_cast(pose.position.x);\n    Y = static_cast(pose.position.y);\n    Z = static_cast(pose.position.z);\n\n    ThetaX = normalizeInRads(tx);\n    ThetaY = normalizeInRads(ty);\n    ThetaZ = normalizeInRads(tz);\n}\n\n\/**\n * @brief obtain KinovaPosefrom CartesianInfo &pose.\n *\n * KinovaPose[X,Y,Z,ThetaX,ThetaY,ThetaZ]. position are in meters, and orientation is Euler-ZYX = Rz(ThetaZ)*Ry(ThetaY)*Rx(ThetaX). The range of Euler angles are [-M_PI, M_PI)\n *\n * @param pose CartesianInfo units are in meters and degrees\n *\/\nKinovaPose::KinovaPose(const CartesianInfo &pose)\n{\n    X = pose.X;\n    Y = pose.Y;\n    Z = pose.Z;\n\n    ThetaX = normalizeInRads(pose.ThetaX);\n    ThetaY = normalizeInRads(pose.ThetaY);\n    ThetaZ = normalizeInRads(pose.ThetaZ);\n}\n\n\/**\n * @brief construct geometric::Pose message from KinovaPose\n * @return geometry_msgs::Pose[x,y,z,qx,qy,qz,qw] position in meters, orientation is in Quaternion.\n *\/\ngeometry_msgs::Pose KinovaPose::constructPoseMsg()\n{\n    geometry_msgs::Pose pose;\n    tf::Quaternion position_quaternion;\n\n   \/\/ setEulerZYX(tz, ty, tx) == setRPY(tx, ty, tz) == = mz * my * mx. the previous is Euler angle rotating with temp axis, while latter rotates with fixed axis.\n\/\/  position_quaternion.setEulerZYX(ThetaZ, ThetaY, ThetaX);\n    position_quaternion.setRPY(ThetaX, ThetaY, ThetaZ);\n\n    tf::quaternionTFToMsg(position_quaternion, pose.orientation);\n\n    pose.position.x = X;\n    pose.position.y = Y;\n    pose.position.z = Z;\n\n    return pose;\n}\n\n\/**\n * @brief construct geometric::Wrench message from KinovaPose data structure\n *\n * KinovaPose[X,Y,Z,ThetaX,ThetaY,ThetaZ] doesn't store pose information in this case. Instead, it stores force and torque correspondingly.\n *\n * @return geometry_msgs [Fx,Fy,Fz,Tx,Ty,Tz] in Newton and Nm.\n *\/\ngeometry_msgs::Wrench KinovaPose::constructWrenchMsg()\n{\n    geometry_msgs::Wrench wrench;\n\n    wrench.force.x  = X;\n    wrench.force.y  = Y;\n    wrench.force.z  = Z;\n    wrench.torque.x = ThetaX;\n    wrench.torque.y = ThetaY;\n    wrench.torque.z = ThetaZ;\n\n    return wrench;\n}\n\nbool KinovaPose::isCloseToOther(const KinovaPose &other, float position_tolerance, float EulerAngle_tolerance) const\n{\n    bool status = true;\n    status = status && areValuesClose(X, other.X, position_tolerance);\n    status = status && areValuesClose(Y, other.Y, position_tolerance);\n    status = status && areValuesClose(Z, other.Z, position_tolerance);\n    status = status && areValuesClose(ThetaX, other.ThetaX, EulerAngle_tolerance);\n    status = status && areValuesClose(ThetaY, other.ThetaY, EulerAngle_tolerance);\n    status = status && areValuesClose(ThetaZ, other.ThetaZ, EulerAngle_tolerance);\n    return status;\n}\n\n\/**\n * @brief KinovaAngles::KinovaAngles\n *\n *\n *\n * @param angles in radians, input has no limit, but output KinovaAngles are limited to [0,360)\n * @param j6o is 270 for all the robot model, except the 1st generation of jaco robot (260)\n *\/\nKinovaAngles::KinovaAngles(const kinova_msgs::JointAngles &angles, double j6o)\n{\n    Actuator1 = normalizePositiveInDegrees(180.0 - (angles.joint1 * (180.0 \/ M_PI)));\n    Actuator2 = normalizePositiveInDegrees((angles.joint2 * (180.0 \/ M_PI)) + 270.0);\n    Actuator3 = normalizePositiveInDegrees(90.0 - (angles.joint3 * (180.0 \/ M_PI)));\n    Actuator4 = normalizePositiveInDegrees(180.0 - (angles.joint4 * (180.0 \/ M_PI)));\n    Actuator5 = normalizePositiveInDegrees(180.0 - (angles.joint5 * (180.0 \/ M_PI)));\n    Actuator6 = normalizePositiveInDegrees(j6o   - (angles.joint6 * (180.0 \/ M_PI)));\n}\n\n\nKinovaAngles::KinovaAngles(const AngularInfo &angles)\n{\n    Actuator1 = normalizePositiveInDegrees(angles.Actuator1);\n    Actuator2 = normalizePositiveInDegrees(angles.Actuator2);\n    Actuator3 = normalizePositiveInDegrees(angles.Actuator3);\n    Actuator4 = normalizePositiveInDegrees(angles.Actuator4);\n    Actuator5 = normalizePositiveInDegrees(angles.Actuator5);\n    Actuator6 = normalizePositiveInDegrees(angles.Actuator6);\n}\n\n\nkinova_msgs::JointAngles KinovaAngles::constructAnglesMsg(double j6o)\n{\n    kinova_msgs::JointAngles angles;\n    angles.joint1 = (180.0 - Actuator1) \/ (180.0 \/ M_PI);\n    angles.joint2 = (Actuator2 - 270.0) \/ (180.0 \/ M_PI);\n    angles.joint3 = (90.0 - Actuator3) \/ (180.0 \/ M_PI);\n    angles.joint4 = (180.0 - Actuator4) \/ (180.0 \/ M_PI);\n    angles.joint5 = (180.0 - Actuator5) \/ (180.0 \/ M_PI);\n    angles.joint6 = (j6o   - Actuator6) \/ (180.0 \/ M_PI);\n    return angles;\n}\n\n\nbool KinovaAngles::isCloseToOther(const KinovaAngles &other, float tolerance) const\n{\n    bool status = true;\n    status = status && areValuesClose(Actuator1, other.Actuator1, tolerance);\n    status = status && areValuesClose(Actuator2, other.Actuator2, tolerance);\n    status = status && areValuesClose(Actuator3, other.Actuator3, tolerance);\n    status = status && areValuesClose(Actuator4, other.Actuator4, tolerance);\n    status = status && areValuesClose(Actuator5, other.Actuator5, tolerance);\n    status = status && areValuesClose(Actuator6, other.Actuator6, tolerance);\n    return status;\n}\n\n\nFingerAngles::FingerAngles(const kinova_msgs::FingerPosition &position)\n{\n    Finger1 = position.finger1;\n    Finger2 = position.finger2;\n    Finger3 = position.finger3;\n}\n\n\nFingerAngles::FingerAngles(const FingersPosition &angle)\n{\n    Finger1 = angle.Finger1;\n    Finger2 = angle.Finger2;\n    Finger3 = angle.Finger3;\n}\n\n\nkinova_msgs::FingerPosition FingerAngles::constructFingersMsg()\n{\n    kinova_msgs::FingerPosition angles;\n    angles.finger1 = Finger1;\n    angles.finger2 = Finger2;\n    angles.finger3 = Finger3;\n    return angles;\n}\n\n\nbool FingerAngles::isCloseToOther(const FingerAngles &other, float tolerance) const\n{\n    bool status = true;\n    status = status && areValuesClose(Finger1, other.Finger1, tolerance);\n    status = status && areValuesClose(Finger2, other.Finger2, tolerance);\n    status = status && areValuesClose(Finger3, other.Finger3, tolerance);\n    return status;\n}\n\n}  \/\/ namespace kinova\n<|endoftext|>"}
{"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1858\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n    \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n    DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1175426 by johtaylo@johtaylo-JTBUILDER03-increment on 2015\/07\/30 03:00:13\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1859\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n    \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n    DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"}
{"text":"#pragma once\n#include \n#include \"common.hpp\"\n#include \"check_macro.hpp\"\n\nDEF_HASTYPE_T(type)\nnamespace spn {\n\t\/\/! std::result_ofの関数対応版\n\t\/*! result_ofのシグニチャと意味が紛らわしいが、気にしない *\/\n\ttemplate \n\tstruct _ResultOf;\n\ttemplate \n\tstruct _ResultOf { using type = RT; };\n\ttemplate \n\tstruct _ResultOf { using type = RT; };\n\ttemplate \n\tstruct _ResultOf { using type = RT; };\n\ttemplate \n\tstruct _ResultOf : std::result_of {};\n\ttemplate \n\tstruct ResultOf : _ResultOf>> {};\n\ttemplate \n\tusing ResultOf_t = typename ResultOf::type;\n\n\t\/\/! bool値による型の選択\n\ttemplate \n\tstruct SelectType {\n\t\tusing type = F;\n\t};\n\ttemplate \n\tstruct SelectType<1,T,F> {\n\t\tusing type = T;\n\t};\n\ttemplate  class T, template class F>\n\tstruct SelectTypeT {\n\t\ttemplate \n\t\tusing type = F;\n\t};\n\ttemplate  class T, template class F>\n\tstruct SelectTypeT<1,T,F> {\n\t\ttemplate \n\t\tusing type = T;\n\t};\n\n\t\/\/! 型変換判定\n\ttemplate \n\tclass Conversion {\n\t\tpublic:\n\t\t\ttypedef char Small;\n\t\t\tclass Big { char d[2]; };\n\t\t\tstatic Small Test(U);\n\t\t\tstatic Big Test(...);\n\t\t\tstatic T MakeT();\n\n\t\tpublic:\n\t\t\tenum { exists =\n\t\t\t\tsizeof(Test(MakeT())) == sizeof(Small),\n\t\t\t\tsameType = 0};\n\t};\n\ttemplate \n\tclass Conversion {\n\t\tpublic:\n\t\t\tenum { exists=1, sameType=1 };\n\t};\n\ttemplate \n\tclass Conversion {\n\t\tpublic:\n\t\t\tenum { exists=0, sameType=0 };\n\t};\n\ttemplate \n\tclass Conversion {\n\t\tpublic:\n\t\t\tenum { exists=0, sameType=0 };\n\t};\n\ttemplate <>\n\tclass Conversion {\n\t\tpublic:\n\t\t\tenum { exists=1, sameType=1 };\n\t};\n\n\ttemplate \n\tconstexpr bool IsDerived() { return Conversion::exists && !Conversion::sameType; }\n\n\t\/\/! 特定の型を取り出す\n\ttemplate \n\tstruct TypeAt;\n\ttemplate \n\tstruct TypeAt {\n\t\ttypedef typename TypeAt::type\ttype;\n\t};\n\ttemplate \n\tstruct TypeAt<0,T,TS...> {\n\t\ttypedef T type;\n\t};\n\n\t\/\/! タイプリストが指定のs型を含んでいるか\n\ttemplate \n\tstruct TypeFind;\n\ttemplate \n\tstruct TypeFind {\n\t\tenum { result=TypeFind::result };\n\t};\n\ttemplate \n\tstruct TypeFind {\n\t\tenum { result=N };\n\t};\n\ttemplate \n\tstruct TypeFind {\n\t\tenum { result=-1 };\n\t};\n\n\t\/\/! ビットフィールド用: 必要なビット数を計算\n\ttemplate \n\tstruct MaxBit {\n\t\tenum { result=0 };\n\t};\n\ttemplate \n\tstruct MaxBit {\n\t\tenum { result=TValue::result>::great };\n\t};\n\t\/\/! タイプリストの変数を並べた時に消費するメモリ量を計算\n\ttemplate \n\tstruct TypeSum {\n\t\tenum { result=0 };\n\t};\n\ttemplate \n\tstruct TypeSum {\n\t\tenum { result=sizeof(T)+TypeSum::result };\n\t};\n\t\/\/! インデックス指定による先頭からのサイズ累計\n\ttemplate  class Getter, class... Ts2>\n\tstruct _SumN {\n\t\tconstexpr static int result = 0; };\n\ttemplate  class Getter, class T0, class... Ts2>\n\tstruct _SumN {\n\t\tconstexpr static int result = Getter::get() * (N>0 ? 1 : 0) + _SumN::result; };\n\t\/\/! タイプ指定による先頭からのサイズ累計\n\ttemplate  class Getter, class... Ts2>\n\tstruct _SumT;\n\ttemplate  class Getter, class T0, class... Ts2>\n\tstruct _SumT {\n\t\tconstexpr static int result = Getter::get() + _SumT::result; };\n\ttemplate  class Getter, class... Ts2>\n\tstruct _SumT {\n\t\tconstexpr static int result = 0; };\n\t\/\/! 通常の型サイズ取得クラス\n\ttemplate \n\tstruct GetSize_Normal {\n\t\tstatic constexpr int get() { return sizeof(T); }\n\t};\n\n\ttemplate \n\tclass CType;\n\n\t\/\/! タイプリストを逆順にした物を返す(ただしCType, C> の形になる)\n\t\/*! CPlainと組み合わせて使う *\/\n\ttemplate \n\tstruct CReverse;\n\ttemplate \n\tstruct CReverse {\n\t\tusing type = CType;\n\t};\n\ttemplate \n\tstruct CReverse {\n\t\tusing type = CType::type, T>;\n\t};\n\t\/\/! CType, ...> の入れ子を展開する\n\ttemplate \n\tstruct CPlain {\n\t\tusing type = CType;\n\t};\n\ttemplate \n\tstruct CPlain {\n\t\tusing type = T;\n\t};\n\ttemplate \n\tstruct CPlain, Ts1...> {\n\t\tusing type = typename CPlain::type;\n\t};\n\ttemplate \n\tstruct CPlain, Ts1...>> {\n\t\tusing type = typename CPlain::type;\n\t};\n\n\ttemplate \n\tclass CType {\n\t\tprivate:\n\t\t\ttemplate \n\t\t\tstruct _Find {\n\t\t\t\tenum { result= TypeFind::result };\n\t\t\t};\n\n\t\tpublic:\n\t\t\t\/\/! インデックス指定で型を取り出す\n\t\t\ttemplate \n\t\t\tstruct At {\n\t\t\t\tstatic_assert(N::type;\n\t\t\t};\n\t\t\t\/\/! 末尾に型を追加\n\t\t\ttemplate \n\t\t\tusing Append = CType;\n\t\t\t\/\/! 先頭に型を追加\n\t\t\ttemplate \n\t\t\tusing Prepend = CType;\n\t\t\t\/\/! 型のインデックス検索\n\t\t\ttemplate \n\t\t\tstruct Find : _Find {\n\t\t\t\tstatic_assert(_Find::result>=0, \"Find: not found\");\n\t\t\t};\n\t\t\t\/\/! 型を持っていればintegral_constant\n\t\t\ttemplate \n\t\t\tstruct Has : std::integral_constant::result>=0> {};\n\t\t\t\/\/! std::tupleに変換\n\t\t\tusing AsTuple = std::tuple;\n\t\t\t\/\/! 要素のそれぞれについてoperator()をした結果の型リストを生成\n\t\t\ttemplate \n\t\t\tstruct Another {\n\t\t\t\tusing result = CType;\n\t\t\t};\n\t\t\t\/\/! 型リストを逆順にする\n\t\t\ttemplate \n\t\t\tstruct Reversed {\n\t\t\t\tusing type = typename CPlain::type>::type;\n\t\t\t};\n\t\t\t\/\/! 自身の型\n\t\t\tusing type = CType;\n\t\t\t\/\/! 別の型のテンプレート引数に使う\n\t\t\ttemplate  class T>\n\t\t\tstruct As {\n\t\t\t\tusing type = T;\n\t\t\t};\n\n\t\t\tconstexpr static int size = sizeof...(TS),\t\t\t\t\t\/\/!< 型リストの要素数\n\t\t\t\t\t\t\t\tsum = TypeSum::result,\t\t\t\/\/!< 要素のサイズ合計\n\t\t\t\t\t\t\t\tmaxsize = TMax::result;\t\/\/!< 要素の最大サイズ\n\t\t\t\/\/! タイプリストの位置に対する比較(LessThan)\n\t\t\ttemplate \n\t\t\tusing Less = std::integral_constant::result, Find::result>::lesser>;\n\t\t\t\/\/! タイプリストの位置に対する比較(GreaterThan)\n\t\t\ttemplate \n\t\t\tusing Greater = std::integral_constant::result, Find::result>::greater>;\n\t\t\t\/\/! タイプリストの位置に対する比較(Equal)\n\t\t\ttemplate \n\t\t\tusing Equal = std::is_same;\n\t\t\t\/\/! タイプリストの位置に対する比較(LessThan or Equal)\n\t\t\ttemplate \n\t\t\tusing LessEq = std::integral_constant::result, Find::result>::less_eq>;\n\t\t\t\/\/! タイプリストの位置に対する比較(GreaterThan or Equal)\n\t\t\ttemplate \n\t\t\tusing GreatEq = std::integral_constant::result, Find::result>::great_eq>;\n\n\t\t\t\/\/ 型がimcompleteなケースを考えてテンプレートクラスとしてある\n\t\t\t\/\/! ビットフィールド用: 必要なビット数を計算\n\t\t\t\/\/! 各タイプの::offset, ::lengthフィールドを使って計算\n\t\t\ttemplate \n\t\t\tstruct Size {\n\t\t\t\tconstexpr static int maxbit = MaxBit::result; };\n\t\t\t\/\/! インデックス指定による先頭からのサイズ累計\n\t\t\ttemplate  class Getter=GetSize_Normal>\n\t\t\tstruct SumN {\n\t\t\t\tstatic_assert(N<=sizeof...(TS),\"Sum: out of index\");\n\t\t\t\tconstexpr static int result = _SumN::result; };\n\t\t\t\/\/! タイプ指定による先頭からのサイズ累計\n\t\t\ttemplate  class Getter=GetSize_Normal>\n\t\t\tstruct SumT {\n\t\t\t\tconstexpr static int result = _SumT::result; };\n\n\t\tprivate:\n\t\t\ttemplate \n\t\t\tstruct __At {\n\t\t\t\tusing type = DEFAULT;\n\t\t\t};\n\t\t\ttemplate \n\t\t\tstruct __At {\n\t\t\t\tusing type = typename At::type;\n\t\t\t};\n\t\t\ttemplate \n\t\t\tstruct _At {\n\t\t\t\tusing type = typename __At::lesser, N,DEFAULT>::type;\n\t\t\t};\n\t};\n}\n\n\noperator * ()で参照可能ならばその型を取り出すヘルパー関数#pragma once\n#include \n#include \"common.hpp\"\n#include \"check_macro.hpp\"\n\nDEF_HASTYPE_T(type)\nnamespace spn {\n\t\/\/! std::result_ofの関数対応版\n\t\/*! result_ofのシグニチャと意味が紛らわしいが、気にしない *\/\n\ttemplate \n\tstruct _ResultOf;\n\ttemplate \n\tstruct _ResultOf { using type = RT; };\n\ttemplate \n\tstruct _ResultOf { using type = RT; };\n\ttemplate \n\tstruct _ResultOf { using type = RT; };\n\ttemplate \n\tstruct _ResultOf : std::result_of {};\n\ttemplate \n\tstruct ResultOf : _ResultOf>> {};\n\ttemplate \n\tusing ResultOf_t = typename ResultOf::type;\n\n\t\/\/! bool値による型の選択\n\ttemplate \n\tstruct SelectType {\n\t\tusing type = F;\n\t};\n\ttemplate \n\tstruct SelectType<1,T,F> {\n\t\tusing type = T;\n\t};\n\ttemplate  class T, template class F>\n\tstruct SelectTypeT {\n\t\ttemplate \n\t\tusing type = F;\n\t};\n\ttemplate  class T, template class F>\n\tstruct SelectTypeT<1,T,F> {\n\t\ttemplate \n\t\tusing type = T;\n\t};\n\n\tnamespace detail {\n\t\ttemplate \n\t\tT dereference_ptr(...);\n\t\ttemplate \n\t\tauto dereference_ptr(typename std::remove_reference())>::type* = nullptr)\n\t\t\t-> typename std::remove_reference())>::type;\n\n\t\ttemplate \n\t\tauto dereference(T& t, typename std::decay())>::type*) -> decltype(*std::declval()) {\n\t\t\treturn *t;\n\t\t}\n\t\ttemplate \n\t\tT& dereference(T& t, ...) {\n\t\t\treturn t;\n\t\t}\n\t}\n\t\/\/! *で参照出来る型を取り出す\n\ttemplate \n\tusing dereference_ptr_t = decltype(detail::dereference_ptr(nullptr));\n\t\/\/! *で参照出来る値を取り出す (参照できない場合はそのまま)\n\ttemplate \n\tauto dereference(T& t) -> decltype(detail::dereference(t, nullptr)) {\n\t\treturn detail::dereference(t, nullptr);\n\t}\n\n\t\/\/! 型変換判定\n\ttemplate \n\tclass Conversion {\n\t\tpublic:\n\t\t\ttypedef char Small;\n\t\t\tclass Big { char d[2]; };\n\t\t\tstatic Small Test(U);\n\t\t\tstatic Big Test(...);\n\t\t\tstatic T MakeT();\n\n\t\tpublic:\n\t\t\tenum { exists =\n\t\t\t\tsizeof(Test(MakeT())) == sizeof(Small),\n\t\t\t\tsameType = 0};\n\t};\n\ttemplate \n\tclass Conversion {\n\t\tpublic:\n\t\t\tenum { exists=1, sameType=1 };\n\t};\n\ttemplate \n\tclass Conversion {\n\t\tpublic:\n\t\t\tenum { exists=0, sameType=0 };\n\t};\n\ttemplate \n\tclass Conversion {\n\t\tpublic:\n\t\t\tenum { exists=0, sameType=0 };\n\t};\n\ttemplate <>\n\tclass Conversion {\n\t\tpublic:\n\t\t\tenum { exists=1, sameType=1 };\n\t};\n\n\ttemplate \n\tconstexpr bool IsDerived() { return Conversion::exists && !Conversion::sameType; }\n\n\t\/\/! 特定の型を取り出す\n\ttemplate \n\tstruct TypeAt;\n\ttemplate \n\tstruct TypeAt {\n\t\ttypedef typename TypeAt::type\ttype;\n\t};\n\ttemplate \n\tstruct TypeAt<0,T,TS...> {\n\t\ttypedef T type;\n\t};\n\n\t\/\/! タイプリストが指定のs型を含んでいるか\n\ttemplate \n\tstruct TypeFind;\n\ttemplate \n\tstruct TypeFind {\n\t\tenum { result=TypeFind::result };\n\t};\n\ttemplate \n\tstruct TypeFind {\n\t\tenum { result=N };\n\t};\n\ttemplate \n\tstruct TypeFind {\n\t\tenum { result=-1 };\n\t};\n\n\t\/\/! ビットフィールド用: 必要なビット数を計算\n\ttemplate \n\tstruct MaxBit {\n\t\tenum { result=0 };\n\t};\n\ttemplate \n\tstruct MaxBit {\n\t\tenum { result=TValue::result>::great };\n\t};\n\t\/\/! タイプリストの変数を並べた時に消費するメモリ量を計算\n\ttemplate \n\tstruct TypeSum {\n\t\tenum { result=0 };\n\t};\n\ttemplate \n\tstruct TypeSum {\n\t\tenum { result=sizeof(T)+TypeSum::result };\n\t};\n\t\/\/! インデックス指定による先頭からのサイズ累計\n\ttemplate  class Getter, class... Ts2>\n\tstruct _SumN {\n\t\tconstexpr static int result = 0; };\n\ttemplate  class Getter, class T0, class... Ts2>\n\tstruct _SumN {\n\t\tconstexpr static int result = Getter::get() * (N>0 ? 1 : 0) + _SumN::result; };\n\t\/\/! タイプ指定による先頭からのサイズ累計\n\ttemplate  class Getter, class... Ts2>\n\tstruct _SumT;\n\ttemplate  class Getter, class T0, class... Ts2>\n\tstruct _SumT {\n\t\tconstexpr static int result = Getter::get() + _SumT::result; };\n\ttemplate  class Getter, class... Ts2>\n\tstruct _SumT {\n\t\tconstexpr static int result = 0; };\n\t\/\/! 通常の型サイズ取得クラス\n\ttemplate \n\tstruct GetSize_Normal {\n\t\tstatic constexpr int get() { return sizeof(T); }\n\t};\n\n\ttemplate \n\tclass CType;\n\n\t\/\/! タイプリストを逆順にした物を返す(ただしCType, C> の形になる)\n\t\/*! CPlainと組み合わせて使う *\/\n\ttemplate \n\tstruct CReverse;\n\ttemplate \n\tstruct CReverse {\n\t\tusing type = CType;\n\t};\n\ttemplate \n\tstruct CReverse {\n\t\tusing type = CType::type, T>;\n\t};\n\t\/\/! CType, ...> の入れ子を展開する\n\ttemplate \n\tstruct CPlain {\n\t\tusing type = CType;\n\t};\n\ttemplate \n\tstruct CPlain {\n\t\tusing type = T;\n\t};\n\ttemplate \n\tstruct CPlain, Ts1...> {\n\t\tusing type = typename CPlain::type;\n\t};\n\ttemplate \n\tstruct CPlain, Ts1...>> {\n\t\tusing type = typename CPlain::type;\n\t};\n\n\ttemplate \n\tclass CType {\n\t\tprivate:\n\t\t\ttemplate \n\t\t\tstruct _Find {\n\t\t\t\tenum { result= TypeFind::result };\n\t\t\t};\n\n\t\tpublic:\n\t\t\t\/\/! インデックス指定で型を取り出す\n\t\t\ttemplate \n\t\t\tstruct At {\n\t\t\t\tstatic_assert(N::type;\n\t\t\t};\n\t\t\t\/\/! 末尾に型を追加\n\t\t\ttemplate \n\t\t\tusing Append = CType;\n\t\t\t\/\/! 先頭に型を追加\n\t\t\ttemplate \n\t\t\tusing Prepend = CType;\n\t\t\t\/\/! 型のインデックス検索\n\t\t\ttemplate \n\t\t\tstruct Find : _Find {\n\t\t\t\tstatic_assert(_Find::result>=0, \"Find: not found\");\n\t\t\t};\n\t\t\t\/\/! 型を持っていればintegral_constant\n\t\t\ttemplate \n\t\t\tstruct Has : std::integral_constant::result>=0> {};\n\t\t\t\/\/! std::tupleに変換\n\t\t\tusing AsTuple = std::tuple;\n\t\t\t\/\/! 要素のそれぞれについてoperator()をした結果の型リストを生成\n\t\t\ttemplate \n\t\t\tstruct Another {\n\t\t\t\tusing result = CType;\n\t\t\t};\n\t\t\t\/\/! 型リストを逆順にする\n\t\t\ttemplate \n\t\t\tstruct Reversed {\n\t\t\t\tusing type = typename CPlain::type>::type;\n\t\t\t};\n\t\t\t\/\/! 自身の型\n\t\t\tusing type = CType;\n\t\t\t\/\/! 別の型のテンプレート引数に使う\n\t\t\ttemplate  class T>\n\t\t\tstruct As {\n\t\t\t\tusing type = T;\n\t\t\t};\n\n\t\t\tconstexpr static int size = sizeof...(TS),\t\t\t\t\t\/\/!< 型リストの要素数\n\t\t\t\t\t\t\t\tsum = TypeSum::result,\t\t\t\/\/!< 要素のサイズ合計\n\t\t\t\t\t\t\t\tmaxsize = TMax::result;\t\/\/!< 要素の最大サイズ\n\t\t\t\/\/! タイプリストの位置に対する比較(LessThan)\n\t\t\ttemplate \n\t\t\tusing Less = std::integral_constant::result, Find::result>::lesser>;\n\t\t\t\/\/! タイプリストの位置に対する比較(GreaterThan)\n\t\t\ttemplate \n\t\t\tusing Greater = std::integral_constant::result, Find::result>::greater>;\n\t\t\t\/\/! タイプリストの位置に対する比較(Equal)\n\t\t\ttemplate \n\t\t\tusing Equal = std::is_same;\n\t\t\t\/\/! タイプリストの位置に対する比較(LessThan or Equal)\n\t\t\ttemplate \n\t\t\tusing LessEq = std::integral_constant::result, Find::result>::less_eq>;\n\t\t\t\/\/! タイプリストの位置に対する比較(GreaterThan or Equal)\n\t\t\ttemplate \n\t\t\tusing GreatEq = std::integral_constant::result, Find::result>::great_eq>;\n\n\t\t\t\/\/ 型がimcompleteなケースを考えてテンプレートクラスとしてある\n\t\t\t\/\/! ビットフィールド用: 必要なビット数を計算\n\t\t\t\/\/! 各タイプの::offset, ::lengthフィールドを使って計算\n\t\t\ttemplate \n\t\t\tstruct Size {\n\t\t\t\tconstexpr static int maxbit = MaxBit::result; };\n\t\t\t\/\/! インデックス指定による先頭からのサイズ累計\n\t\t\ttemplate  class Getter=GetSize_Normal>\n\t\t\tstruct SumN {\n\t\t\t\tstatic_assert(N<=sizeof...(TS),\"Sum: out of index\");\n\t\t\t\tconstexpr static int result = _SumN::result; };\n\t\t\t\/\/! タイプ指定による先頭からのサイズ累計\n\t\t\ttemplate  class Getter=GetSize_Normal>\n\t\t\tstruct SumT {\n\t\t\t\tconstexpr static int result = _SumT::result; };\n\n\t\tprivate:\n\t\t\ttemplate \n\t\t\tstruct __At {\n\t\t\t\tusing type = DEFAULT;\n\t\t\t};\n\t\t\ttemplate \n\t\t\tstruct __At {\n\t\t\t\tusing type = typename At::type;\n\t\t\t};\n\t\t\ttemplate \n\t\t\tstruct _At {\n\t\t\t\tusing type = typename __At::lesser, N,DEFAULT>::type;\n\t\t\t};\n\t};\n}\n\n\n<|endoftext|>"}
{"text":"\/*\n * ucrc_t.cpp\n *\n *\n * version 1.0\n *\n *\n * Copyright (c) 2015, Koynov Stas - skojnov@yandex.ru\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *  1 Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *  2 Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *  3 Neither the name of the  nor the\n *    names of its contributors may be used to endorse or promote products\n *   derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \"ucrc_t.h\"\n#include \n#include \n\n\n\n\nuCRC_t::uCRC_t(const std::string Name, uint8_t Bits, uint64_t Poly, uint64_t Init, bool RefIn, bool RefOut, uint64_t XorOut) :\n    name    (Name),\n    bits    (Bits),\n    poly    (Poly),\n    init    (Init),\n    ref_in  (RefIn),\n    ref_out (RefOut),\n    xor_out (XorOut)\n{\n\n    init_class();\n}\n\n\n\nuCRC_t::uCRC_t(uint8_t Bits, uint64_t Poly, uint64_t Init, bool RefIn, bool RefOut, uint64_t XorOut) :\n    bits    (Bits),\n    poly    (Poly),\n    init    (Init),\n    ref_in  (RefIn),\n    ref_out (RefOut),\n    xor_out (XorOut)\n{\n\n    init_class();\n}\n\n\n\nint uCRC_t::set_bits(uint8_t new_bits)\n{\n    if( (new_bits < 1) || (new_bits > 64) )\n        return -1; \/\/error\n\n\n    bits = new_bits;\n    init_class();\n\n\n    return 0; \/\/good job\n}\n\n\n\nuint64_t uCRC_t::get_crc(const char* buf, size_t len) const\n{\n    uint64_t crc = get_raw_crc(buf, len, crc_init);\n\n    return get_final_crc(crc);\n}\n\n\n\nint uCRC_t::get_crc(uint64_t &crc, const char* file_name) const\n{\n    char buf[4096];\n\n    return get_crc(crc, file_name, buf, sizeof(buf));\n}\n\n\n\nint uCRC_t::get_crc(uint64_t &crc, FILE *pfile) const\n{\n    char buf[4096];\n\n    return get_crc(crc, pfile, buf, sizeof(buf));\n}\n\n\n\nint uCRC_t::get_crc(uint64_t &crc, const char *file_name, void *buf, size_t size_buf) const\n{\n    if( !file_name )\n    {\n        errno = EINVAL;\n        return -1;\n    }\n\n\n    FILE *stream = fopen(file_name, \"rb\");\n    if( stream == NULL )\n        return -1; \/\/Cant open file\n\n\n    int res = get_crc(crc, stream, buf, size_buf);\n\n\n    fclose(stream);\n\n\n    return res;\n}\n\n\n\nint uCRC_t::get_crc(uint64_t &crc, FILE *pfile, void *buf, size_t size_buf) const\n{\n    if( !pfile || !buf || (size_buf == 0) )\n    {\n        errno = EINVAL;\n        return -1;\n    }\n\n\n    crc          = init;\n    long cur_pos = ftell(pfile);\n    rewind(pfile);\n\n\n    while( !feof(pfile) )\n    {\n       size_t len = fread(buf, 1, size_buf, pfile);\n       crc = get_raw_crc((char *)buf, len, crc);\n    }\n\n\n    fseek(pfile, cur_pos, SEEK_SET);\n\n\n    crc = get_final_crc(crc);\n\n\n    return 0; \/\/good  job\n}\n\n\n\nuint64_t uCRC_t::get_raw_crc(const char* buf, size_t len, uint64_t crc) const\n{\n    if(bits > 8)\n    {\n        if(ref_in)\n            while (len--)\n                crc = (crc >> 8) ^ crc_table[ (crc ^ *buf++) & 0xff ];\n        else\n            while (len--)\n                crc = (crc << 8) ^ crc_table[ ((crc >> shift) & 0xff) ^ *buf++ ];\n    }\n    else\n    {\n        if (ref_in)\n            while (len--)\n                crc = crc_table[ crc ^ *buf++ ];\n        else\n            while (len--)\n                crc = crc_table[ (crc << shift) ^ *buf++ ];\n    }\n\n\n    return crc;\n}\n\n\n\nuint64_t uCRC_t::get_final_crc(uint64_t raw_crc) const\n{\n    if(ref_out^ref_in) raw_crc = reflect(raw_crc, bits);\n\n    raw_crc ^= xor_out;\n    raw_crc &= crc_mask; \/\/for CRC not power 2\n\n    return raw_crc;\n}\n\n\n\nuint64_t uCRC_t::reflect(uint64_t data, uint8_t num_bits) const\n{\n    uint64_t reflection = 0;\n    uint64_t one = 1;\n\n    for ( size_t i = 0; i < num_bits; ++i, data >>= 1 )\n    {\n        if ( data & one )\n        {\n            reflection |= ( one << (num_bits - one - i) );\n        }\n    }\n\n    return reflection;\n}\n\n\n\nvoid uCRC_t::init_crc_table()\n{\n    int i;\n    uint64_t crc;\n\n\n    for(i = 0; i < 256; i++)\n    {\n\n        crc = 0;\n\n        for(uint8_t mask = 0x80; mask; mask >>= 1)\n        {\n\n            if ( i & mask )\n                crc ^= top_bit;\n\n\n            if (crc & top_bit)\n            {\n                crc <<= 1;\n                crc ^= poly;\n            }\n            else\n                crc <<= 1;\n        }\n\n        crc &= crc_mask; \/\/for CRC not power 2\n\n        if(ref_in)\n            crc_table[reflect(i, 8)] = reflect(crc, bits);\n        else\n            crc_table[i] = crc;\n    }\n}\n\n\n\nvoid uCRC_t::init_class()\n{\n    top_bit  = (uint64_t)1 << (bits - 1);\n    crc_mask = ( (top_bit - 1) << 1) | 1;\n\n\n    if(bits > 8)\n        shift = (bits - 8);\n    else\n        shift = (8 - bits);\n\n\n    if(ref_in)\n        crc_init = reflect(init, bits);\n    else\n        crc_init = init;\n\n\n    init_crc_table();\n}\nBugFix for Big Data SEGFAULT for Bits <= 8\/*\n * ucrc_t.cpp\n *\n *\n * version 1.0\n *\n *\n * Copyright (c) 2015, Koynov Stas - skojnov@yandex.ru\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *  1 Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *  2 Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *  3 Neither the name of the  nor the\n *    names of its contributors may be used to endorse or promote products\n *   derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \"ucrc_t.h\"\n#include \n#include \n\n\n\n\nuCRC_t::uCRC_t(const std::string Name, uint8_t Bits, uint64_t Poly, uint64_t Init, bool RefIn, bool RefOut, uint64_t XorOut) :\n    name    (Name),\n    bits    (Bits),\n    poly    (Poly),\n    init    (Init),\n    ref_in  (RefIn),\n    ref_out (RefOut),\n    xor_out (XorOut)\n{\n\n    init_class();\n}\n\n\n\nuCRC_t::uCRC_t(uint8_t Bits, uint64_t Poly, uint64_t Init, bool RefIn, bool RefOut, uint64_t XorOut) :\n    bits    (Bits),\n    poly    (Poly),\n    init    (Init),\n    ref_in  (RefIn),\n    ref_out (RefOut),\n    xor_out (XorOut)\n{\n\n    init_class();\n}\n\n\n\nint uCRC_t::set_bits(uint8_t new_bits)\n{\n    if( (new_bits < 1) || (new_bits > 64) )\n        return -1; \/\/error\n\n\n    bits = new_bits;\n    init_class();\n\n\n    return 0; \/\/good job\n}\n\n\n\nuint64_t uCRC_t::get_crc(const char* buf, size_t len) const\n{\n    uint64_t crc = get_raw_crc(buf, len, crc_init);\n\n    return get_final_crc(crc);\n}\n\n\n\nint uCRC_t::get_crc(uint64_t &crc, const char* file_name) const\n{\n    char buf[4096];\n\n    return get_crc(crc, file_name, buf, sizeof(buf));\n}\n\n\n\nint uCRC_t::get_crc(uint64_t &crc, FILE *pfile) const\n{\n    char buf[4096];\n\n    return get_crc(crc, pfile, buf, sizeof(buf));\n}\n\n\n\nint uCRC_t::get_crc(uint64_t &crc, const char *file_name, void *buf, size_t size_buf) const\n{\n    if( !file_name )\n    {\n        errno = EINVAL;\n        return -1;\n    }\n\n\n    FILE *stream = fopen(file_name, \"rb\");\n    if( stream == NULL )\n        return -1; \/\/Cant open file\n\n\n    int res = get_crc(crc, stream, buf, size_buf);\n\n\n    fclose(stream);\n\n\n    return res;\n}\n\n\n\nint uCRC_t::get_crc(uint64_t &crc, FILE *pfile, void *buf, size_t size_buf) const\n{\n    if( !pfile || !buf || (size_buf == 0) )\n    {\n        errno = EINVAL;\n        return -1;\n    }\n\n\n    crc          = init;\n    long cur_pos = ftell(pfile);\n    rewind(pfile);\n\n\n    while( !feof(pfile) )\n    {\n       size_t len = fread(buf, 1, size_buf, pfile);\n       crc = get_raw_crc((char *)buf, len, crc);\n    }\n\n\n    fseek(pfile, cur_pos, SEEK_SET);\n\n\n    crc = get_final_crc(crc);\n\n\n    return 0; \/\/good  job\n}\n\n\n\nuint64_t uCRC_t::get_raw_crc(const char* buf, size_t len, uint64_t crc) const\n{\n    if(bits > 8)\n    {\n        if(ref_in)\n            while (len--)\n                crc = (crc >> 8) ^ crc_table[ (crc ^ *buf++) & 0xff ];\n        else\n            while (len--)\n                crc = (crc << 8) ^ crc_table[ ((crc >> shift) ^ *buf++) & 0xff ];\n    }\n    else\n    {\n        if (ref_in)\n            while (len--)\n                crc = crc_table[ (crc ^ *buf++) & 0xff ];\n        else\n            while (len--)\n                crc = crc_table[ ((crc << shift) ^ *buf++) & 0xff ];\n    }\n\n\n    return crc;\n}\n\n\n\nuint64_t uCRC_t::get_final_crc(uint64_t raw_crc) const\n{\n    if(ref_out^ref_in) raw_crc = reflect(raw_crc, bits);\n\n    raw_crc ^= xor_out;\n    raw_crc &= crc_mask; \/\/for CRC not power 2\n\n    return raw_crc;\n}\n\n\n\nuint64_t uCRC_t::reflect(uint64_t data, uint8_t num_bits) const\n{\n    uint64_t reflection = 0;\n    uint64_t one = 1;\n\n    for ( size_t i = 0; i < num_bits; ++i, data >>= 1 )\n    {\n        if ( data & one )\n        {\n            reflection |= ( one << (num_bits - one - i) );\n        }\n    }\n\n    return reflection;\n}\n\n\n\nvoid uCRC_t::init_crc_table()\n{\n    int i;\n    uint64_t crc;\n\n\n    for(i = 0; i < 256; i++)\n    {\n\n        crc = 0;\n\n        for(uint8_t mask = 0x80; mask; mask >>= 1)\n        {\n\n            if ( i & mask )\n                crc ^= top_bit;\n\n\n            if (crc & top_bit)\n            {\n                crc <<= 1;\n                crc ^= poly;\n            }\n            else\n                crc <<= 1;\n        }\n\n        crc &= crc_mask; \/\/for CRC not power 2\n\n        if(ref_in)\n            crc_table[reflect(i, 8)] = reflect(crc, bits);\n        else\n            crc_table[i] = crc;\n    }\n}\n\n\n\nvoid uCRC_t::init_class()\n{\n    top_bit  = (uint64_t)1 << (bits - 1);\n    crc_mask = ( (top_bit - 1) << 1) | 1;\n\n\n    if(bits > 8)\n        shift = (bits - 8);\n    else\n        shift = (8 - bits);\n\n\n    if(ref_in)\n        crc_init = reflect(init, bits);\n    else\n        crc_init = init;\n\n\n    init_crc_table();\n}\n<|endoftext|>"}
{"text":"\/*\n * Copyright (c) 2012. The Regents of the University of California. All rights reserved.\n * Licensed pursuant to the terms and conditions available for viewing at:\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause\n *\n * File: TestLocalizer.cpp\n * Author: Jonathan Ventura\n * Last Modified: 25.2.2013\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n\nusing namespace vrlt;\n\nvoid loadImages( std::string prefix, Node *node )\n{\n    if ( node->camera != NULL ) {\n        std::stringstream path;\n        path << prefix << \"\/\" << node->camera->path;\n        node->camera->image = cv::imread( path.str(), cv::IMREAD_GRAYSCALE );\n        node->camera->pyramid = ImagePyramid( node->camera );\n    }\n    \n    ElementList::iterator it;\n    for ( it = node->children.begin(); it != node->children.end(); it++ )\n    {\n        Node *child = (Node *)it->second;\n        loadImages( prefix, child );\n    }\n}\n\nint main( int argc, char **argv )\n{\n    if ( argc != 4 && argc != 5 ) {\n        fprintf( stderr, \"usage: %s    []\\n\", argv[0] );\n        exit(1);\n    }\n    \n    std::string pathin = std::string(argv[1]);\n    std::string queryin = std::string(argv[2]);\n    int step = atoi(argv[3]);\n    bool test_bounds = ( argc == 5 );\n    \n    Reconstruction r;\n    r.pathPrefix = pathin;\n    std::stringstream mypath;\n    mypath << pathin << \"\/reconstruction.xml\";\n    XML::read( r, mypath.str() );\n    \n    Node *root = (Node*)r.nodes[\"root\"];\n    XML::readDescriptors( r, root );\n\n    loadImages( pathin, root );\n    \n    double minY = INFINITY;\n    for ( ElementList::iterator it = root->children.begin(); it != root->children.end(); it++ ) {\n        Node *node = (Node *)it->second;\n        Eigen::Vector3d center = -( node->globalPose().so3().inverse() * node->globalPose().translation() );\n        if ( center[1] < minY ) minY = center[1];\n    }\n\n    Reconstruction query;\n    XML::read( query, queryin );\n    \n    Node *queryroot = new Node;\n    queryroot->name = \"root\";\n\n    query.nodes[ \"root\"] = queryroot;\n    \n    ElementList::iterator it;\n    \n    NN *index = NULL;\n\n    index = new BruteForceNN;\n    \n    NNLocalizer *localizer = new NNLocalizer( root, index );\n    localizer->verbose = true;\n    localizer->tracker->verbose = false;\n    ElementList::iterator camerait = query.cameras.begin();\n    Camera *camera = (Camera*)camerait->second;\n    Calibration *calibration = camera->calibration;\n    cv::Mat image = cv::imread( camera->path, cv::IMREAD_GRAYSCALE );\n    int width = image.size().width;\n    localizer->thresh = 0.006 * width \/ camera->calibration->focal;\n    localizer->tracker->minnumpoints = 100;\n    \n    Calibration *mycalibration = new Calibration;\n    Camera *mycamera = new Camera;\n    Node *mynode = new Node;\n    mycamera->calibration = calibration;\n    mycamera->node = mynode;\n    mynode->camera = mycamera;\n    mynode->parent = NULL;\n    \n    int count = 0;\n    int goodCount = 0;\n    int attemptedCount = 0;\n    for ( it = query.cameras.begin(); it != query.cameras.end(); it++,count++ )\n    {\n        if ( count % step != 0 ) continue;\n        \n        Camera *querycamera = (Camera *)it->second;\n        \n        Node *querynode = (Node *)querycamera->node;\n        if ( querynode == NULL )\n        {\n            querynode = new Node;\n            char name[256];\n            sprintf( name, \"%s.node\", querycamera->name.c_str() );\n            querynode->name = name;\n            query.nodes[ querynode->name ] = querynode;\n            querynode->camera = querycamera;\n            querycamera->node = querynode;\n        }\n\n        \n        mycamera->name = querycamera->name;\n        mynode->pose = querycamera->node->globalPose();\n        mycamera->path = querycamera->path;\n        mycamera->image = cv::imread( mycamera->path, cv::IMREAD_GRAYSCALE );\n        mycamera->pyramid.resize( mycamera->image.size() );\n        mycamera->pyramid.copy_from( mycamera->image );\n        \n        mycamera->features.clear();\n        std::vector features;\n\t\textractSIFT( mycamera->image, features );\n\n        for ( int i = 0; i < features.size(); i++ )\n        {\n            char name[256];\n            sprintf( name, \"feature%d\", i );\n            features[i]->name = name;\n            features[i]->camera = mycamera;\n            mycamera->features[name] = features[i];\n        }\n        \n        bool good = localizer->localize( mycamera );\n        \n        if ( good && test_bounds ) {\n            Sophus::SE3d pose = mycamera->node->pose;\n            Eigen::Vector3d center = - ( pose.so3().inverse() * pose.translation() );\n            if ( center[1] > 0 || center[1] < minY ) {\n                std::cout << \"\\trejected because of bad pose (Y = \" << center[1] << \" and minY is \" << minY << \")\\n\";\n                good = false;\n            }\n        }\n        \n        if ( good ) goodCount++;\n        attemptedCount++;\n        \n        if ( querycamera->node->parent != NULL ) querycamera->node->parent->pose = Sophus::SE3d();\n        querycamera->node->pose = mynode->pose;\n\n        for ( int i = 0; i < features.size(); i++ )\n        {\n            delete features[i];\n        }\n\n        if ( good ) {\n            query.nodes.erase( querycamera->node->name );\n            querycamera->node->parent = queryroot;\n            queryroot->children[ querycamera->node->name ] = querycamera->node;\n        }\n    }\n    \n    XML::write( query, \"localized.xml\" );\n    \n    return 0;\n}\nChanged TestLocalizer to use approximate NN\/*\n * Copyright (c) 2012. The Regents of the University of California. All rights reserved.\n * Licensed pursuant to the terms and conditions available for viewing at:\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause\n *\n * File: TestLocalizer.cpp\n * Author: Jonathan Ventura\n * Last Modified: 25.2.2013\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n\nusing namespace vrlt;\n\nvoid loadImages( std::string prefix, Node *node )\n{\n    if ( node->camera != NULL ) {\n        std::stringstream path;\n        path << prefix << \"\/\" << node->camera->path;\n        node->camera->image = cv::imread( path.str(), cv::IMREAD_GRAYSCALE );\n        node->camera->pyramid = ImagePyramid( node->camera );\n    }\n    \n    ElementList::iterator it;\n    for ( it = node->children.begin(); it != node->children.end(); it++ )\n    {\n        Node *child = (Node *)it->second;\n        loadImages( prefix, child );\n    }\n}\n\nint main( int argc, char **argv )\n{\n    if ( argc != 4 && argc != 5 ) {\n        fprintf( stderr, \"usage: %s    []\\n\", argv[0] );\n        exit(1);\n    }\n    \n    std::string pathin = std::string(argv[1]);\n    std::string queryin = std::string(argv[2]);\n    int step = atoi(argv[3]);\n    bool test_bounds = ( argc == 5 );\n    \n    Reconstruction r;\n    r.pathPrefix = pathin;\n    std::stringstream mypath;\n    mypath << pathin << \"\/reconstruction.xml\";\n    XML::read( r, mypath.str() );\n    \n    Node *root = (Node*)r.nodes[\"root\"];\n    XML::readDescriptors( r, root );\n\n    loadImages( pathin, root );\n    \n    double minY = INFINITY;\n    for ( ElementList::iterator it = root->children.begin(); it != root->children.end(); it++ ) {\n        Node *node = (Node *)it->second;\n        Eigen::Vector3d center = -( node->globalPose().so3().inverse() * node->globalPose().translation() );\n        if ( center[1] < minY ) minY = center[1];\n    }\n\n    Reconstruction query;\n    XML::read( query, queryin );\n    \n    Node *queryroot = new Node;\n    queryroot->name = \"root\";\n\n    query.nodes[ \"root\"] = queryroot;\n    \n    ElementList::iterator it;\n    \n    NN *index = NULL;\n\n    index = new ApproxNN;\n    \n    NNLocalizer *localizer = new NNLocalizer( root, index );\n    localizer->verbose = true;\n    localizer->tracker->verbose = false;\n    ElementList::iterator camerait = query.cameras.begin();\n    Camera *camera = (Camera*)camerait->second;\n    Calibration *calibration = camera->calibration;\n    cv::Mat image = cv::imread( camera->path, cv::IMREAD_GRAYSCALE );\n    int width = image.size().width;\n    localizer->thresh = 0.006 * width \/ camera->calibration->focal;\n    localizer->tracker->minnumpoints = 100;\n    \n    Camera *mycamera = new Camera;\n    Node *mynode = new Node;\n    mycamera->calibration = calibration;\n    mycamera->node = mynode;\n    mynode->camera = mycamera;\n    mynode->parent = NULL;\n    \n    int count = 0;\n    int goodCount = 0;\n    int attemptedCount = 0;\n    for ( it = query.cameras.begin(); it != query.cameras.end(); it++,count++ )\n    {\n        if ( count % step != 0 ) continue;\n        \n        Camera *querycamera = (Camera *)it->second;\n        \n        Node *querynode = (Node *)querycamera->node;\n        if ( querynode == NULL )\n        {\n            querynode = new Node;\n            char name[256];\n            sprintf( name, \"%s.node\", querycamera->name.c_str() );\n            querynode->name = name;\n            query.nodes[ querynode->name ] = querynode;\n            querynode->camera = querycamera;\n            querycamera->node = querynode;\n        }\n\n        \n        mycamera->name = querycamera->name;\n        mynode->pose = querycamera->node->globalPose();\n        mycamera->path = querycamera->path;\n        mycamera->image = cv::imread( mycamera->path, cv::IMREAD_GRAYSCALE );\n        mycamera->pyramid.resize( mycamera->image.size() );\n        mycamera->pyramid.copy_from( mycamera->image );\n        \n        mycamera->features.clear();\n        std::vector features;\n\t\textractSIFT( mycamera->image, features );\n\n        for ( int i = 0; i < features.size(); i++ )\n        {\n            char name[256];\n            sprintf( name, \"feature%d\", i );\n            features[i]->name = name;\n            features[i]->camera = mycamera;\n            mycamera->features[name] = features[i];\n        }\n        \n        bool good = localizer->localize( mycamera );\n        \n        if ( good && test_bounds ) {\n            Sophus::SE3d pose = mycamera->node->pose;\n            Eigen::Vector3d center = - ( pose.so3().inverse() * pose.translation() );\n            if ( center[1] > 0 || center[1] < minY ) {\n                std::cout << \"\\trejected because of bad pose (Y = \" << center[1] << \" and minY is \" << minY << \")\\n\";\n                good = false;\n            }\n        }\n        \n        if ( good ) goodCount++;\n        attemptedCount++;\n        \n        if ( querycamera->node->parent != NULL ) querycamera->node->parent->pose = Sophus::SE3d();\n        querycamera->node->pose = mynode->pose;\n\n        for ( int i = 0; i < features.size(); i++ )\n        {\n            delete features[i];\n        }\n\n        if ( good ) {\n            query.nodes.erase( querycamera->node->name );\n            querycamera->node->parent = queryroot;\n            queryroot->children[ querycamera->node->name ] = querycamera->node;\n        }\n    }\n    \n    XML::write( query, \"localized.xml\" );\n    \n    return 0;\n}\n<|endoftext|>"}
{"text":"#include \"dictreader.hpp\"\n\n\/\/----------------------------------------------------------\nDictReader::DictReader()\n{\n\n}\n\n\/\/----------------------------------------------------------\nDictReader::DictReader(const DictReader& that)\n    :\n      name_full(that.name_full),\n      name_prefix(that.name_prefix),\n      dict(that.dict),\n      log(that.log),\n      status(that.status),\n      counter_loaded(that.counter_loaded),\n      counter_invalid(that.counter_invalid),\n      counter_doubled(that.counter_doubled),\n      counter_all(that.counter_all)\n{\n\n}\n\n\/\/----------------------------------------------------------\nDictReader& DictReader::operator=(const DictReader& that)\n{\n    name_full = that.name_full;\n    name_prefix = that.name_prefix;\n    dict = that.dict;\n    log = that.log;\n    status = that.status;\n    counter_loaded = that.counter_loaded;\n    counter_invalid = that.counter_invalid;\n    counter_doubled = that.counter_doubled;\n    counter_all = that.counter_all;\n    return *this;\n}\n\n\/\/----------------------------------------------------------\nDictReader::~DictReader()\n{\n\n}\n\n\/\/----------------------------------------------------------\nvoid DictReader::readFile(const std::string &path)\n{\n    std::ifstream file(path, std::ios::binary);\n    if(file)\n    {\n        std::string content;\n        char buffer[16384];\n        size_t size = file.tellg();\n        content.reserve(size);\n        std::streamsize chars_read;\n        while(file.read(buffer, sizeof(buffer)), chars_read = file.gcount())\n        {\n            content.append(buffer, chars_read);\n        }\n        parseDict(content, path);\n    }\n    else\n    {\n        std::cout << \"--> Error while loading \" + path + \" (wrong path)!\" << std::endl;\n        status = false;\n    }\n}\n\n\/\/----------------------------------------------------------\nvoid DictReader::setName(const std::string &path)\n{\n    name_full = path.substr(path.find_last_of(\"\\\\\/\") + 1);\n    name_prefix = name_full.substr(0, name_full.find_last_of(\".\"));\n}\n\n\/\/----------------------------------------------------------\nvoid DictReader::parseDict(const std::string &content,\n                           const std::string &path)\n{\n    try\n    {\n        std::string friendly_text;\n        size_t pos_beg;\n        size_t pos_end;\n\n        std::regex re(\"(.*?)<\/id>\\\\s*(.*?)<\/key>\");\n        std::smatch found;\n        std::sregex_iterator next(content.begin(), content.end(), re);\n        std::sregex_iterator end;\n        while(next != end)\n        {\n            found = *next;\n\n            \/\/ no multiline in regex :(\n            pos_beg = content.find(\"\", found.position(2)) + 5;\n            pos_end = content.find(\"<\/val>\", pos_beg);\n            friendly_text = content.substr(pos_beg, pos_end - pos_beg);\n\n            validateRecord(found[1].str(), found[2].str(), friendly_text);\n            counter_all++;\n            next++;\n        }\n        std::cout << \"--> Loading \" + path + \"...\" << std::endl;\n        printLog();\n        setName(path);\n        status = true;\n    }\n    catch(std::exception const& e)\n    {\n        std::cout << \"--> Error in function parseDict() (possibly broken dictionary)!\" << std::endl;\n        std::cout << \"--> Exception: \" << e.what() << std::endl;\n        status = false;\n    }\n}\n\n\/\/----------------------------------------------------------\nvoid DictReader::validateRecord(const std::string &id,\n                                const std::string &unique_text,\n                                const std::string &friendly_text)\n{\n    if(id == \"CELL\")\n    {\n        if(friendly_text.size() > 63)\n        {\n            makeLog(id, unique_text, friendly_text, \"Too long, more than 63 bytes!\");\n            counter_invalid++;\n        }\n        else\n        {\n            insertRecord(yampt::rec_type::CELL, unique_text, friendly_text);\n        }\n    }\n    else if(id == \"GMST\")\n    {\n        insertRecord(yampt::rec_type::GMST, unique_text, friendly_text);\n    }\n    else if(id == \"DESC\")\n    {\n        insertRecord(yampt::rec_type::DESC, unique_text, friendly_text);\n    }\n    else if(id == \"TEXT\")\n    {\n        insertRecord(yampt::rec_type::TEXT, unique_text, friendly_text);\n    }\n    else if(id == \"INDX\")\n    {\n        insertRecord(yampt::rec_type::INDX, unique_text, friendly_text);\n    }\n    else if(id == \"DIAL\")\n    {\n        insertRecord(yampt::rec_type::DIAL, unique_text, friendly_text);\n    }\n    else if(id == \"BNAM\")\n    {\n        insertRecord(yampt::rec_type::BNAM, unique_text, friendly_text);\n    }\n    else if(id == \"SCTX\")\n    {\n        insertRecord(yampt::rec_type::SCTX, unique_text, friendly_text);\n    }\n    else if(id == \"RNAM\")\n    {\n        if(friendly_text.size() > 32)\n        {\n            makeLog(id, unique_text, friendly_text, \"Too long, more than 32 bytes!\");\n            counter_invalid++;\n        }\n        else\n        {\n            insertRecord(yampt::rec_type::RNAM, unique_text, friendly_text);\n        }\n    }\n    else if(id == \"FNAM\")\n    {\n        if(friendly_text.size() > 31)\n        {\n            makeLog(id, unique_text, friendly_text, \"Too long, more than 31 bytes!\");\n            counter_invalid++;\n        }\n        else\n        {\n            insertRecord(yampt::rec_type::FNAM, unique_text, friendly_text);\n        }\n    }\n    else if(id == \"INFO\")\n    {\n        if(friendly_text.size() > 512)\n        {\n            makeLog(id, unique_text, friendly_text, \"Ok, but more than 512 bytes!\");\n            insertRecord(yampt::rec_type::INFO, unique_text, friendly_text);\n        }\n        else\n        {\n            insertRecord(yampt::rec_type::INFO, unique_text, friendly_text);\n        }\n    }\n    else\n    {\n        makeLog(id, unique_text, friendly_text, \"Invalid record!\");\n        counter_invalid++;\n    }\n\n}\n\n\/\/----------------------------------------------------------\nvoid DictReader::insertRecord(yampt::rec_type type,\n                              const std::string &unique_text,\n                              const std::string &friendly_text)\n{\n    if(dict[type].insert({unique_text, friendly_text}).second == true)\n    {\n        counter_loaded++;\n    }\n    else\n    {\n        makeLog(yampt::type_name[type], unique_text, friendly_text, \"Doubled record!\");\n        counter_doubled++;\n    }\n}\n\n\/\/----------------------------------------------------------\nvoid DictReader::makeLog(const std::string &id,\n                         const std::string &unique_text,\n                         const std::string &friendly_text,\n                         const std::string &comment)\n{\n    log += \"\\r\\n\";\n    log += \"\\t\" + name_full + \"<\/file>\\r\\n\";\n    log += \"\\t\" + comment + \"<\/status>\\r\\n\";\n    log += \"\\t\" + id + \"<\/id>\\r\\n\";\n    log += \"\\t\" + unique_text + \"<\/key>\\r\\n\";\n    log += \"\\t\" + friendly_text + \"<\/val>\\r\\n\";\n    log += \"\\r\\n\";\n}\n\n\/\/----------------------------------------------------------\nvoid DictReader::printLog()\n{\n    std::cout << \"---------------------------------------\" << std::endl\n              << \"    Loaded \/ Doubled \/ Invalid \/    All\" << std::endl\n              << \"---------------------------------------\" << std::endl\n              << std::setw(10) << std::to_string(counter_loaded) << \" \/ \"\n              << std::setw(7) << std::to_string(counter_doubled) << \" \/ \"\n              << std::setw(7) << std::to_string(counter_invalid) << \" \/ \"\n              << std::setw(6) << std::to_string(counter_all) << std::endl\n              << \"---------------------------------------\" << std::endl;\n}\ncleaning#include \"dictreader.hpp\"\n\n\/\/----------------------------------------------------------\nDictReader::DictReader()\n{\n\n}\n\n\/\/----------------------------------------------------------\nDictReader::DictReader(const DictReader& that)\n    : name_full(that.name_full),\n      name_prefix(that.name_prefix),\n      dict(that.dict),\n      log(that.log),\n      status(that.status),\n      counter_loaded(that.counter_loaded),\n      counter_invalid(that.counter_invalid),\n      counter_doubled(that.counter_doubled),\n      counter_all(that.counter_all)\n{\n\n}\n\n\/\/----------------------------------------------------------\nDictReader& DictReader::operator=(const DictReader& that)\n{\n    name_full = that.name_full;\n    name_prefix = that.name_prefix;\n    dict = that.dict;\n    log = that.log;\n    status = that.status;\n    counter_loaded = that.counter_loaded;\n    counter_invalid = that.counter_invalid;\n    counter_doubled = that.counter_doubled;\n    counter_all = that.counter_all;\n    return *this;\n}\n\n\/\/----------------------------------------------------------\nDictReader::~DictReader()\n{\n\n}\n\n\/\/----------------------------------------------------------\nvoid DictReader::readFile(const std::string &path)\n{\n    std::ifstream file(path, std::ios::binary);\n    if(file)\n    {\n        std::string content;\n        char buffer[16384];\n        size_t size = file.tellg();\n        content.reserve(size);\n        std::streamsize chars_read;\n        while(file.read(buffer, sizeof(buffer)), chars_read = file.gcount())\n        {\n            content.append(buffer, chars_read);\n        }\n        parseDict(content, path);\n    }\n    else\n    {\n        std::cout << \"--> Error while loading \" + path + \" (wrong path)!\" << std::endl;\n        status = false;\n    }\n}\n\n\/\/----------------------------------------------------------\nvoid DictReader::setName(const std::string &path)\n{\n    name_full = path.substr(path.find_last_of(\"\\\\\/\") + 1);\n    name_prefix = name_full.substr(0, name_full.find_last_of(\".\"));\n}\n\n\/\/----------------------------------------------------------\nvoid DictReader::parseDict(const std::string &content,\n                           const std::string &path)\n{\n    try\n    {\n        std::string friendly_text;\n        size_t pos_beg;\n        size_t pos_end;\n\n        std::regex re(\"(.*?)<\/id>\\\\s*(.*?)<\/key>\");\n        std::smatch found;\n        std::sregex_iterator next(content.begin(), content.end(), re);\n        std::sregex_iterator end;\n        while(next != end)\n        {\n            found = *next;\n\n            \/\/ no multiline in regex :(\n            pos_beg = content.find(\"\", found.position(2)) + 5;\n            pos_end = content.find(\"<\/val>\", pos_beg);\n            friendly_text = content.substr(pos_beg, pos_end - pos_beg);\n\n            validateRecord(found[1].str(), found[2].str(), friendly_text);\n            counter_all++;\n            next++;\n        }\n        std::cout << \"--> Loading \" + path + \"...\" << std::endl;\n        printLog();\n        setName(path);\n        status = true;\n    }\n    catch(std::exception const& e)\n    {\n        std::cout << \"--> Error in function parseDict() (possibly broken dictionary)!\" << std::endl;\n        std::cout << \"--> Exception: \" << e.what() << std::endl;\n        status = false;\n    }\n}\n\n\/\/----------------------------------------------------------\nvoid DictReader::validateRecord(const std::string &id,\n                                const std::string &unique_text,\n                                const std::string &friendly_text)\n{\n    if(id == \"CELL\")\n    {\n        if(friendly_text.size() > 63)\n        {\n            makeLog(id, unique_text, friendly_text, \"Too long, more than 63 bytes!\");\n            counter_invalid++;\n        }\n        else\n        {\n            insertRecord(yampt::rec_type::CELL, unique_text, friendly_text);\n        }\n    }\n    else if(id == \"GMST\")\n    {\n        insertRecord(yampt::rec_type::GMST, unique_text, friendly_text);\n    }\n    else if(id == \"DESC\")\n    {\n        insertRecord(yampt::rec_type::DESC, unique_text, friendly_text);\n    }\n    else if(id == \"TEXT\")\n    {\n        insertRecord(yampt::rec_type::TEXT, unique_text, friendly_text);\n    }\n    else if(id == \"INDX\")\n    {\n        insertRecord(yampt::rec_type::INDX, unique_text, friendly_text);\n    }\n    else if(id == \"DIAL\")\n    {\n        insertRecord(yampt::rec_type::DIAL, unique_text, friendly_text);\n    }\n    else if(id == \"BNAM\")\n    {\n        insertRecord(yampt::rec_type::BNAM, unique_text, friendly_text);\n    }\n    else if(id == \"SCTX\")\n    {\n        insertRecord(yampt::rec_type::SCTX, unique_text, friendly_text);\n    }\n    else if(id == \"RNAM\")\n    {\n        if(friendly_text.size() > 32)\n        {\n            makeLog(id, unique_text, friendly_text, \"Too long, more than 32 bytes!\");\n            counter_invalid++;\n        }\n        else\n        {\n            insertRecord(yampt::rec_type::RNAM, unique_text, friendly_text);\n        }\n    }\n    else if(id == \"FNAM\")\n    {\n        if(friendly_text.size() > 31)\n        {\n            makeLog(id, unique_text, friendly_text, \"Too long, more than 31 bytes!\");\n            counter_invalid++;\n        }\n        else\n        {\n            insertRecord(yampt::rec_type::FNAM, unique_text, friendly_text);\n        }\n    }\n    else if(id == \"INFO\")\n    {\n        if(friendly_text.size() > 512)\n        {\n            makeLog(id, unique_text, friendly_text, \"Ok, but more than 512 bytes!\");\n            insertRecord(yampt::rec_type::INFO, unique_text, friendly_text);\n        }\n        else\n        {\n            insertRecord(yampt::rec_type::INFO, unique_text, friendly_text);\n        }\n    }\n    else\n    {\n        makeLog(id, unique_text, friendly_text, \"Invalid record!\");\n        counter_invalid++;\n    }\n\n}\n\n\/\/----------------------------------------------------------\nvoid DictReader::insertRecord(yampt::rec_type type,\n                              const std::string &unique_text,\n                              const std::string &friendly_text)\n{\n    if(dict[type].insert({unique_text, friendly_text}).second == true)\n    {\n        counter_loaded++;\n    }\n    else\n    {\n        makeLog(yampt::type_name[type], unique_text, friendly_text, \"Doubled record!\");\n        counter_doubled++;\n    }\n}\n\n\/\/----------------------------------------------------------\nvoid DictReader::makeLog(const std::string &id,\n                         const std::string &unique_text,\n                         const std::string &friendly_text,\n                         const std::string &comment)\n{\n    log += \"\\r\\n\";\n    log += \"\\t\" + name_full + \"<\/file>\\r\\n\";\n    log += \"\\t\" + comment + \"<\/status>\\r\\n\";\n    log += \"\\t\" + id + \"<\/id>\\r\\n\";\n    log += \"\\t\" + unique_text + \"<\/key>\\r\\n\";\n    log += \"\\t\" + friendly_text + \"<\/val>\\r\\n\";\n    log += \"\\r\\n\";\n}\n\n\/\/----------------------------------------------------------\nvoid DictReader::printLog()\n{\n    std::cout << \"---------------------------------------\" << std::endl\n              << \"    Loaded \/ Doubled \/ Invalid \/    All\" << std::endl\n              << \"---------------------------------------\" << std::endl\n              << std::setw(10) << std::to_string(counter_loaded) << \" \/ \"\n              << std::setw(7) << std::to_string(counter_doubled) << \" \/ \"\n              << std::setw(7) << std::to_string(counter_invalid) << \" \/ \"\n              << std::setw(6) << std::to_string(counter_all) << std::endl\n              << \"---------------------------------------\" << std::endl;\n}\n<|endoftext|>"}
{"text":"#include \"uart.h\"\n#include \"utils.h\"\n#include \"Register.h\"\n#include \"Gpio.h\"\n#include \"system.h\"\n#include \n\nstatic const uint32_t UART0_BASE = System::getPeripheralBase() + 0x201000;\n\nstatic Register dr    (UART0_BASE + 0x00);\nstatic Register fr    (UART0_BASE + 0x18);\nstatic Register ibrd  (UART0_BASE + 0x24);\nstatic Register fbrd  (UART0_BASE + 0x28);\nstatic Register lcrh  (UART0_BASE + 0x2C);\nstatic Register cr    (UART0_BASE + 0x30);\nstatic Register imsc  (UART0_BASE + 0x38);\nstatic Register icr   (UART0_BASE + 0x44);\n\nenum {\n    LCRH_SEND_BREAK,\n    LCRH_ENABLE_PARITY,\n    LCRH_EVEN_PARITY,\n    LCRH_TWO_STOP_BITS,\n    LCRH_ENABLE_FIFOS,\n    LCRH_WORLD_LENGTH,\n    LCRH_STICK_PARITY = 7\n};\n\nenum {\n    CR_UART_ENABLE,\n    CR_LOOPBACK_ENABLE = 7,\n    CR_TRANSMIT_ENABLE,\n    CR_RECEIVE_ENABLE,\n    CR_RTS = 11,\n    CR_RTS_ENABLE = 14,\n    CR_CTS_ENABLE = 15\n};\n\nenum {\n    IMSC_CTS_INT_MASK = 1,\n    IMSC_RECEIVE_INT_MASK = 4,\n    IMSC_TRANSMIT_INT_MASK,\n    IMSC_TIMEOUT_INT_MASK,\n    IMSC_FRAMING_INT_MASK,\n    IMSC_PARITY_INT_MASK,\n    IMSC_BREAK_INT_MASK,\n    IMSC_OVERRUN_INT_MASK,\n};\n\nUart::Uart() : mUseLock(false)\n{\n    \/\/ Disable UART0.\n    cr.clear();\n    \/\/ Setup the GPIO pin 14 && 15.\n    Gpio::disablePullupAndPulldown(14,15);\n\n    \/\/ Clear pending interrupts.\n    icr.write(0x7FF);\n    \n    \/\/ Set integer & fractional part of baud rate.\n    \/\/ Divider = UART_CLOCK\/(16 * Baud)\n    \/\/ Fraction part register = (Fractional part * 64) + 0.5\n    \/\/ UART_CLOCK = 3000000; Baud = 115200.\n    \n    \/\/ Divider = 3000000 \/ (16 * 115200) = 1.627 = ~1.\n    \/\/ Fractional part register = (.627 * 64) + 0.5 = 40.6 = ~40.\n    ibrd.write(1);\n    fbrd.write(40);\n    \n    \/\/ Enable FIFO & 8 bit data transmission (1 stop bit, no parity).\n    lcrh.setOnly(LCRH_ENABLE_FIFOS);\n    lcrh.write(3, LCRH_WORLD_LENGTH);\n    \n    \/\/ Mask all interrupts.\n    imsc.setOnly(IMSC_CTS_INT_MASK, IMSC_RECEIVE_INT_MASK, IMSC_TRANSMIT_INT_MASK, IMSC_TIMEOUT_INT_MASK,\n                 IMSC_FRAMING_INT_MASK, IMSC_PARITY_INT_MASK, IMSC_BREAK_INT_MASK, IMSC_OVERRUN_INT_MASK);\n    \n    \/\/ Enable UART0, receive & transfer part of UART.\n    cr.setOnly(CR_UART_ENABLE, CR_TRANSMIT_ENABLE, CR_RECEIVE_ENABLE);\n}\n\nstatic void uart_putc(char byte)\n{\n    \/\/ Wait for UART to become ready to transmit.\n    while ( fr.get(5) ) { }\n    dr.write(byte);\n}\n\n#if 0\nstatic unsigned char uart_getc()\n{\n    \/\/ Wait for UART to have recieved something.\n    while (REG(UART0_FR) & UART0_RX_FIFO_EMPTY) {\n\n    }\n    return REG(UART0_DR);\n}\n#endif\n\nvoid Uart::write(const char* buffer, size_t size) {\n    if (mUseLock) {\n        mLock.lock();\n    }\n    for (size_t i = 0; i < size; i++) {\n        uart_putc(buffer[i]);\n    }\n    if(mUseLock) {\n        mLock.unlock();\n    }\n}\n\nvoid Uart::write(const char* buffer) {\n    write(buffer, strlen(buffer));\n}\n\nvoid Uart::writeU32(uint32_t x) {\n    static const char HEX[] = \"0123456789ABCDEF\";\n    char buf[] = \"0x00000000\";\n    char *p = &buf[2];\n    for(int i = 28; i >= 0; i -= 4) {\n        *p++ = HEX[(x >> i) % 16];\n    }\n    write(buf, 10);\n}\n\nvoid Uart::enableLocking() {\n    mUseLock = true;\n}\nRemove include#include \"uart.h\"\n#include \"Register.h\"\n#include \"Gpio.h\"\n#include \"system.h\"\n#include \n\nstatic const uint32_t UART0_BASE = System::getPeripheralBase() + 0x201000;\n\nstatic Register dr    (UART0_BASE + 0x00);\nstatic Register fr    (UART0_BASE + 0x18);\nstatic Register ibrd  (UART0_BASE + 0x24);\nstatic Register fbrd  (UART0_BASE + 0x28);\nstatic Register lcrh  (UART0_BASE + 0x2C);\nstatic Register cr    (UART0_BASE + 0x30);\nstatic Register imsc  (UART0_BASE + 0x38);\nstatic Register icr   (UART0_BASE + 0x44);\n\nenum {\n    LCRH_SEND_BREAK,\n    LCRH_ENABLE_PARITY,\n    LCRH_EVEN_PARITY,\n    LCRH_TWO_STOP_BITS,\n    LCRH_ENABLE_FIFOS,\n    LCRH_WORLD_LENGTH,\n    LCRH_STICK_PARITY = 7\n};\n\nenum {\n    CR_UART_ENABLE,\n    CR_LOOPBACK_ENABLE = 7,\n    CR_TRANSMIT_ENABLE,\n    CR_RECEIVE_ENABLE,\n    CR_RTS = 11,\n    CR_RTS_ENABLE = 14,\n    CR_CTS_ENABLE = 15\n};\n\nenum {\n    IMSC_CTS_INT_MASK = 1,\n    IMSC_RECEIVE_INT_MASK = 4,\n    IMSC_TRANSMIT_INT_MASK,\n    IMSC_TIMEOUT_INT_MASK,\n    IMSC_FRAMING_INT_MASK,\n    IMSC_PARITY_INT_MASK,\n    IMSC_BREAK_INT_MASK,\n    IMSC_OVERRUN_INT_MASK,\n};\n\nUart::Uart() : mUseLock(false)\n{\n    \/\/ Disable UART0.\n    cr.clear();\n    \/\/ Setup the GPIO pin 14 && 15.\n    Gpio::disablePullupAndPulldown(14,15);\n\n    \/\/ Clear pending interrupts.\n    icr.write(0x7FF);\n    \n    \/\/ Set integer & fractional part of baud rate.\n    \/\/ Divider = UART_CLOCK\/(16 * Baud)\n    \/\/ Fraction part register = (Fractional part * 64) + 0.5\n    \/\/ UART_CLOCK = 3000000; Baud = 115200.\n    \n    \/\/ Divider = 3000000 \/ (16 * 115200) = 1.627 = ~1.\n    \/\/ Fractional part register = (.627 * 64) + 0.5 = 40.6 = ~40.\n    ibrd.write(1);\n    fbrd.write(40);\n    \n    \/\/ Enable FIFO & 8 bit data transmission (1 stop bit, no parity).\n    lcrh.setOnly(LCRH_ENABLE_FIFOS);\n    lcrh.write(3, LCRH_WORLD_LENGTH);\n    \n    \/\/ Mask all interrupts.\n    imsc.setOnly(IMSC_CTS_INT_MASK, IMSC_RECEIVE_INT_MASK, IMSC_TRANSMIT_INT_MASK, IMSC_TIMEOUT_INT_MASK,\n                 IMSC_FRAMING_INT_MASK, IMSC_PARITY_INT_MASK, IMSC_BREAK_INT_MASK, IMSC_OVERRUN_INT_MASK);\n    \n    \/\/ Enable UART0, receive & transfer part of UART.\n    cr.setOnly(CR_UART_ENABLE, CR_TRANSMIT_ENABLE, CR_RECEIVE_ENABLE);\n}\n\nstatic void uart_putc(char byte)\n{\n    \/\/ Wait for UART to become ready to transmit.\n    while ( fr.get(5) ) { }\n    dr.write(byte);\n}\n\n#if 0\nstatic unsigned char uart_getc()\n{\n    \/\/ Wait for UART to have recieved something.\n    while (REG(UART0_FR) & UART0_RX_FIFO_EMPTY) {\n\n    }\n    return REG(UART0_DR);\n}\n#endif\n\nvoid Uart::write(const char* buffer, size_t size) {\n    if (mUseLock) {\n        mLock.lock();\n    }\n    for (size_t i = 0; i < size; i++) {\n        uart_putc(buffer[i]);\n    }\n    if(mUseLock) {\n        mLock.unlock();\n    }\n}\n\nvoid Uart::write(const char* buffer) {\n    write(buffer, strlen(buffer));\n}\n\nvoid Uart::writeU32(uint32_t x) {\n    static const char HEX[] = \"0123456789ABCDEF\";\n    char buf[] = \"0x00000000\";\n    char *p = &buf[2];\n    for(int i = 28; i >= 0; i -= 4) {\n        *p++ = HEX[(x >> i) % 16];\n    }\n    write(buf, 10);\n}\n\nvoid Uart::enableLocking() {\n    mUseLock = true;\n}\n<|endoftext|>"}
{"text":"\/***********************************************\r\n ***********************************************\r\n\r\nWARNING\r\nWARNING\r\nWARNING\r\n\r\nGOT WEIRD PROBLEM HAPPENING WHERE IF TURNING_LEFT_GLOBAL, RIGHT_GLOBAL.. AND MOVING_FOWARDS...\r\nif they are initially set to 0, they get set to 1. So setting to -1 for now.*\/\r\n\r\n\r\n\/*WARNING WARNING\r\n\r\nWARNING\r\n\r\nWARNING*\/\r\n\/************************************************************************************************\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\n#include \r\n#include \r\n\r\n\r\n#include \"main_game.h\"\r\n#include \"game_state.h\"\r\n#include \"render_world.h\"\r\n#include \"defs.h\"\r\n#include \"audio.h\"\r\n#include \"texture.h\"\r\n#include \"maze.h\"\r\n\r\nusing namespace std;\r\n\r\n\/*Our maze*\/ \/\/creates new instance\r\n\/\/Maze maze;\r\n\r\nMaze maze;\r\n\r\n\/* For move function *\/\r\n int turning_left_global = 0;\r\nint turning_right_global = 0;\r\n int moving_fowards_global = 0;\r\n\r\n\/*Our player data structure - Where we are in the world *\/\r\nint x_position = 0;\r\nint y_position = 0;\r\nint orientation;\r\n\r\n\/*Where we start*\/\r\nint start_x = 0;\r\nint start_y = 0;\r\n\r\nint end_x = 7;\r\nint end_y = 1;\r\n\r\n\/*Music*\/\r\nMix_Music *world_music;\r\nbool music_on = true;\r\n\r\n\/*Modifies the players position\/orientation based\r\n  on input variables such as moving_fowards_global*\/\r\nstatic void move(){\r\n\r\n  printf(\"Moving fowards: %d \\n\", moving_fowards_global);\r\n\r\n\r\n  if(moving_fowards_global == 1){\r\n    if(orientation == NORTH){\r\n      if(maze.value_at(x_position, y_position, NORTH) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(y_position < 8){\r\n\t  y_position++;\r\n\t}\r\n      \r\n      }\r\n    }\r\n    if(orientation == SOUTH){\r\n      if(maze.value_at(x_position, y_position, SOUTH) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(y_position > 0){\r\n\t  y_position--;\r\n\t}\r\n      }\r\n    }\r\n\r\n    if(orientation == EAST){\r\n      if(maze.value_at(x_position, y_position, WEST) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(x_position > 0){\r\n\t  x_position--;\r\n\t}\r\n      }\r\n    }\r\n      \r\n    if(orientation == WEST){\r\n      if(maze.value_at(x_position, y_position, EAST) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(x_position < 8){\r\n\t  x_position++;\r\n\t}\r\n      }\r\n    }\r\n  }\r\n\r\n\r\n  else if(turning_right_global == 1){\r\n    if(orientation == WEST){\r\n      orientation = NORTH;\r\n    }\r\n    else{\r\n      orientation++;\r\n    }\r\n  }\r\n  else if(turning_left_global == 1){\r\n    if(orientation == NORTH){\r\n      orientation = WEST ;\r\n    }\r\n    else{\r\n      orientation--;\r\n    } \r\n  }\r\n  if(orientation == SOUTH){\r\n    printf(\"%d %d SOUTH\\n\", x_position, y_position);\r\n  }\r\n  if(orientation == NORTH){\r\n    printf(\"%d %d NORTH\\n\", x_position, y_position);\r\n  }\r\n  if(orientation == EAST){\r\n    printf(\"%d %d EAST\\n\", x_position, y_position);\r\n  }\r\n  if(orientation == WEST){\r\n    printf(\"%d %d WEST\\n\", x_position, y_position);\r\n  }\r\n\r\n  \/*If these aren't reset the player races off at the speed of light*\/\r\n  moving_fowards_global = 0;\r\n  turning_left_global = 0;\r\n  turning_right_global = 0;\r\n\t\t\t\t\t\t\t\t      \r\n}\r\n\r\n\/*Called when a key is released*\/\r\nvoid mainGameKeyboardUp(SDLKey key)\r\n{\r\n\r\n  if (key == SDLK_LEFT){\r\n    turning_left_global = 0;\r\n  }\r\n  else if(key == SDLK_RIGHT){\r\n    turning_right_global = 0;\r\n  }\r\n\r\n  else if(key == SDLK_UP){\r\n    moving_fowards_global = 0;\r\n  }\r\n  else if(key == SDLK_m){\r\n    music_on = !music_on;\r\n  }\r\n}\r\n\r\n\/*Called when a key is held down*\/\r\nvoid mainGameKeyboardDown(SDLKey key){\r\n  printf(\"KEY\\n\");\r\n\r\n  if(key == SDLK_LEFT){\r\n\r\n\r\n    turning_left_global = 1;\r\n  }\r\n\r\n  else if(key == SDLK_UP){\r\n    moving_fowards_global = 1;\r\n  }\r\n\r\n  else if(key == SDLK_RIGHT){\r\n    turning_right_global = 1;\r\n  }\r\n}\r\n\r\n\/*Our main game function.. checks for input, moves and redraws the screen.\r\n\r\n  TODO: Needs to be changed to a timer function later so it dosen't hog 100%cpu *\/\r\nvoid mainGameUpdate(void){\r\n\r\n  if(turning_left_global == 1 || turning_right_global == 1\r\n     || moving_fowards_global == 1){\r\n    printf(\"Moving\\n\");\r\n    move();\r\n  }\r\n  \r\n  if(x_position == end_x && y_position == end_y){\r\n\r\n    printf(\"You win!\\n\");\r\n    exit(0);\r\n  }\r\n  \/\/glutPostRedisplay(); don't think there is a SDL equivalent of this\r\n  \/\/ so taking it out.\r\n  \/\/check if music should be playing\r\n  if(!music_on && isAudioPlaying()){\r\n    pauseAudio();\r\n  }else if(music_on && !isAudioPlaying()){\r\n    resumeAudio();\r\n  }\r\n}\r\n\r\n\/*Display function - called from main - This function is called as\r\n * often as possible - Whenever the idle loop finishes*\/\r\nvoid mainGameRender(void){\r\n  renderWorld();\r\n}\r\n\r\n\/*Leslies code*\/\r\nstatic void initTextures(){\r\n\r\n\r\n  srand(time(NULL));\r\n\r\n\r\n  int floor_tex_num = 0;\r\n  int wall_tex_num = 0;\r\n\r\n  floor_tex_num = rand() % 8; \/\/SINCE THERE ARE 8 FLOOR TEXTURES ATM.\r\n  wall_tex_num = rand() % 3; \/\/ 3 wall textures atm.\r\n\r\n  string w_string = \"data\/images\/textures\/w\";\r\n\r\n  ostringstream oss_wall;\r\n  oss_wall <Added a SDL_Delay  in the main game loop, so the game does not take 100% CPU now, and only around 10, 20 %\/***********************************************\r\n ***********************************************\r\n\r\nWARNING\r\nWARNING\r\nWARNING\r\n\r\nGOT WEIRD PROBLEM HAPPENING WHERE IF TURNING_LEFT_GLOBAL, RIGHT_GLOBAL.. AND MOVING_FOWARDS...\r\nif they are initially set to 0, they get set to 1. So setting to -1 for now.*\/\r\n\r\n\r\n\/*WARNING WARNING\r\n\r\nWARNING\r\n\r\nWARNING*\/\r\n\/************************************************************************************************\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\n#include \r\n#include \r\n\r\n\r\n#include \"main_game.h\"\r\n#include \"game_state.h\"\r\n#include \"render_world.h\"\r\n#include \"defs.h\"\r\n#include \"audio.h\"\r\n#include \"texture.h\"\r\n#include \"maze.h\"\r\n\r\nusing namespace std;\r\n\r\n\/*Our maze*\/ \/\/creates new instance\r\n\/\/Maze maze;\r\n\r\nMaze maze;\r\n\r\n\/* For move function *\/\r\n int turning_left_global = 0;\r\nint turning_right_global = 0;\r\n int moving_fowards_global = 0;\r\n\r\n\/*Our player data structure - Where we are in the world *\/\r\nint x_position = 0;\r\nint y_position = 0;\r\nint orientation;\r\n\r\n\/*Where we start*\/\r\nint start_x = 0;\r\nint start_y = 0;\r\n\r\nint end_x = 7;\r\nint end_y = 1;\r\n\r\n\/*Music*\/\r\nMix_Music *world_music;\r\nbool music_on = true;\r\n\r\n\/*Modifies the players position\/orientation based\r\n  on input variables such as moving_fowards_global*\/\r\nstatic void move(){\r\n\r\n  printf(\"Moving fowards: %d \\n\", moving_fowards_global);\r\n\r\n\r\n  if(moving_fowards_global == 1){\r\n    if(orientation == NORTH){\r\n      if(maze.value_at(x_position, y_position, NORTH) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(y_position < 8){\r\n\t  y_position++;\r\n\t}\r\n      \r\n      }\r\n    }\r\n    if(orientation == SOUTH){\r\n      if(maze.value_at(x_position, y_position, SOUTH) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(y_position > 0){\r\n\t  y_position--;\r\n\t}\r\n      }\r\n    }\r\n\r\n    if(orientation == EAST){\r\n      if(maze.value_at(x_position, y_position, WEST) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(x_position > 0){\r\n\t  x_position--;\r\n\t}\r\n      }\r\n    }\r\n      \r\n    if(orientation == WEST){\r\n      if(maze.value_at(x_position, y_position, EAST) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(x_position < 8){\r\n\t  x_position++;\r\n\t}\r\n      }\r\n    }\r\n  }\r\n\r\n\r\n  else if(turning_right_global == 1){\r\n    if(orientation == WEST){\r\n      orientation = NORTH;\r\n    }\r\n    else{\r\n      orientation++;\r\n    }\r\n  }\r\n  else if(turning_left_global == 1){\r\n    if(orientation == NORTH){\r\n      orientation = WEST ;\r\n    }\r\n    else{\r\n      orientation--;\r\n    } \r\n  }\r\n  if(orientation == SOUTH){\r\n    printf(\"%d %d SOUTH\\n\", x_position, y_position);\r\n  }\r\n  if(orientation == NORTH){\r\n    printf(\"%d %d NORTH\\n\", x_position, y_position);\r\n  }\r\n  if(orientation == EAST){\r\n    printf(\"%d %d EAST\\n\", x_position, y_position);\r\n  }\r\n  if(orientation == WEST){\r\n    printf(\"%d %d WEST\\n\", x_position, y_position);\r\n  }\r\n\r\n  \/*If these aren't reset the player races off at the speed of light*\/\r\n  moving_fowards_global = 0;\r\n  turning_left_global = 0;\r\n  turning_right_global = 0;\r\n\t\t\t\t\t\t\t\t      \r\n}\r\n\r\n\/*Called when a key is released*\/\r\nvoid mainGameKeyboardUp(SDLKey key)\r\n{\r\n\r\n  if (key == SDLK_LEFT){\r\n    turning_left_global = 0;\r\n  }\r\n  else if(key == SDLK_RIGHT){\r\n    turning_right_global = 0;\r\n  }\r\n\r\n  else if(key == SDLK_UP){\r\n    moving_fowards_global = 0;\r\n  }\r\n  else if(key == SDLK_m){\r\n    music_on = !music_on;\r\n  }\r\n}\r\n\r\n\/*Called when a key is held down*\/\r\nvoid mainGameKeyboardDown(SDLKey key){\r\n  printf(\"KEY\\n\");\r\n\r\n  if(key == SDLK_LEFT){\r\n\r\n\r\n    turning_left_global = 1;\r\n  }\r\n\r\n  else if(key == SDLK_UP){\r\n    moving_fowards_global = 1;\r\n  }\r\n\r\n  else if(key == SDLK_RIGHT){\r\n    turning_right_global = 1;\r\n  }\r\n}\r\n\r\n\/*Our main game function.. checks for input, moves and redraws the screen.\r\n\r\n  TODO: Needs to be changed to a timer function later so it dosen't hog 100%cpu *\/\r\nvoid mainGameUpdate(void){\r\n\r\n  if(turning_left_global == 1 || turning_right_global == 1\r\n     || moving_fowards_global == 1){\r\n    printf(\"Moving\\n\");\r\n    move();\r\n  }\r\n  \r\n  if(x_position == end_x && y_position == end_y){\r\n\r\n    printf(\"You win!\\n\");\r\n    exit(0);\r\n  }\r\n  \/\/glutPostRedisplay(); don't think there is a SDL equivalent of this\r\n  \/\/ so taking it out.\r\n  \/\/check if music should be playing\r\n  if(!music_on && isAudioPlaying()){\r\n    pauseAudio();\r\n  }else if(music_on && !isAudioPlaying()){\r\n    resumeAudio();\r\n  }\r\n\r\n  SDL_Delay(10);\r\n}\r\n\r\n\/*Display function - called from main - This function is called as\r\n * often as possible - Whenever the idle loop finishes*\/\r\nvoid mainGameRender(void){\r\n  renderWorld();\r\n}\r\n\r\n\/*Leslies code*\/\r\nstatic void initTextures(){\r\n\r\n\r\n  srand(time(NULL));\r\n\r\n\r\n  int floor_tex_num = 0;\r\n  int wall_tex_num = 0;\r\n\r\n  floor_tex_num = rand() % 8; \/\/SINCE THERE ARE 8 FLOOR TEXTURES ATM.\r\n  wall_tex_num = rand() % 3; \/\/ 3 wall textures atm.\r\n\r\n  string w_string = \"data\/images\/textures\/w\";\r\n\r\n  ostringstream oss_wall;\r\n  oss_wall <"}
{"text":"\/\/cci_shared_lib.cpp    william k. johnson 2017\n\/\/\n\n\n#include \n#include \n\n\nusing namespace cci_daemon_impl;\n\n\n\/\/--------------------------------------------------------------------------------\ncci_handle_t cci_shared_lib::load( const std::string& lib )\n{\n            std::ostringstream ostr;\n            ostr << \"lib\"\n                 << lib\n                 << \".so\"\n                 << std::ends;\n            std::string path_with_extension = ostr.str();\n            cci_handle_t shared_object = ::dlopen( path_with_extension.c_str() ,\n                                                   RTLD_NOW) ;\n            if( shared_object == nullptr )\n            {\n                throw std::runtime_error( std::string( \"could not load '\")\n                                          + path_with_extension + \"'\");\n            }\n\n            std::cerr << \"...loaded library....\"\n                      << path_with_extension\n                      << \"...\\n\";\n\n\n\n\n            return shared_object;\n}\n\n\/\/--------------------------------------------------------------------------------\nvoid  cci_shared_lib::unload( cci_handle_t shared_handle )\n{\n          if ( shared_handle ) { dlclose( shared_handle); }\n}\n\n\nkernel\/\/cci_shared_lib.cpp    chromatic universe william k. johnson 2017\n\/\/\n\n\n#include \n#include \n\n\nusing namespace cci_daemon_impl;\n\n\n\/\/--------------------------------------------------------------------------------\ncci_handle_t cci_shared_lib::load( const std::string& lib )\n{\n            std::ostringstream ostr;\n            ostr << \"lib\"\n                 << lib\n                 << \".so\"\n                 << std::ends;\n            std::string path_with_extension = ostr.str();\n            cci_handle_t shared_object = ::dlopen( path_with_extension.c_str() ,\n                                                   RTLD_NOW) ;\n            if( shared_object == nullptr )\n            {\n                throw std::runtime_error( std::string( \"could not load '\")\n                                          + path_with_extension + \"'\");\n            }\n\n            std::cerr << \"...loaded library....\"\n                      << path_with_extension\n                      << \"...\\n\";\n\n\n\n\n            return shared_object;\n}\n\n\/\/--------------------------------------------------------------------------------\nvoid  cci_shared_lib::unload( cci_handle_t shared_handle )\n{\n          if ( shared_handle ) { dlclose( shared_handle); }\n}\n\n\n<|endoftext|>"}
{"text":"more clean-up<|endoftext|>"}
{"text":"#include \"consoleui.h\"\n#include \n#include \nusing namespace std;\n\nconsoleUI::consoleUI()\n{\n\n}\n\nconsoleUI::consoleUI(int chooseNumber)\n{\n    _chooseNumber = chooseNumber;\n}\n\nvoid consoleUI::run()\n{\n    int chooseNumber = 0;\n\n    cout << \"------------------------------------------------------------------\" << endl;\n    cout << \"*------ Database for Scientist ----------*--------Glossary-------*\" << endl;\n    cout << \"* 1:  Display entire list.               * Y.O.D = date of death *\" << endl;\n    cout << \"* 2:  Search by name.                    * Y.O.B = date of birth *\"<< endl;\n    cout << \"* 3:  Search if alive.                   * Y.O.A = year of award *\" << endl;\n    cout << \"* 4:  Sort by award year.                *                       *\" << endl;\n    cout << \"* 5:  Add new scientist.                 *                       *\" << endl;\n    cout << \"* 6:  Search for birth year.             *                       *\" << endl;\n    cout << \"* 7:  Enter Function.                    *                       *\" << endl;\n    cout << \"* 8:  Sort by birthyear.                 *                       *\" << endl;\n    cout << \"* 9:  Search for Turing award winner.    *                       *\" << endl;\n    cout << \"* 10: Chuck Norris.                      *                       *\" << endl;\n    cout << \"*----------------------------------------*-----------------------*\" << endl;\n    cout << \"-----------------------------------------------------------------\" << endl;\n    cout << \"Enter number: \";\n\n    cin >> chooseNumber;\n\n    \/\/This function sends you (from the number you pick) to the right corresponding case\n    switch (chooseNumber)\n    {\n        \/\/This function displays a list of all the scientists (that is there full names, dob, dod and year of award)\n        case 1:\n        {\n            listServices scientists;\n            cout << \"***List of all scientists***\" << endl;\n            print();\n            printNames(scientists);\n        }\n            break;\n\n        \/\/This function let's you search from either the first or last name\n        case 2:\n            {\n                listServices scientists;\n                \/\/listServices searchName2;\n                string searchTerm;\n                cout << \"Enter a single name to search: \";\n                cin >> searchTerm;\n                scientists.changeTo(_scientist.searchName(searchTerm));\n                print();\n                printNames(scientists);\n\n            }\n            break;\n        case 3:\n            \/\/sortAlive\n            {\n                listServices scientists;\n                string searchTerm;\n                scientists.changeTo(_scientist.searchAlive());\n                cout << \"An organized list starting with the oldest living scientist\" << endl;\n                print();\n                printNames(scientists);\n             }\n              break;\n        case 4:\n            \/\/sortAward\n            {\n                listServices scientistsByAward;\n                scientistsByAward.changeTo(_scientist.sortByAward());\n                cout << \"An organized list of scientists in order of when they received the Turing award.\" << endl;\n                print();\n                printNames(scientistsByAward);\n             }\n            break;\n\n        case 5:\n            {\n                \/\/addNew\n                string firstName;\n                string lastName;\n                char gender;\n                int birthYear;\n                char isAlive;\n                int deathYear;\n                char isWinner;\n                int awardYear;\n\n                cout << \"Please enter the scientist's first name: \";\n                cin >> firstName;\n                cout << \"Please enter the scientist's last name: \";\n                cin >> lastName;\n                cout << \"Enter the scientist's gender (m\/f) : \";\n                cin >> gender;\n                cout << \"Enter the scientist's birth year: \";\n                cin >> birthYear;\n                cout << \"Is the scientist still alive? (y\/n) \";\n                cin >> isAlive;\n                if(isAlive == 'n')\n                {\n                    cout << \"Enter the scientist's year of death: \";\n                    cin >>  deathYear;\n                }\n                else if(isAlive == 'y')\n                {\n                    deathYear = 0;\n                }\n                else\n                {\n                    cout << \"Invalid entry.  Please enter either y (yes) or n (no)\";\n                }\n                cout << \"Did the scientist win a Turing award? (y\/n)\";\n                cin >> isWinner;\n                if(isWinner == 'y')\n                {\n                    cout << \"Enter the year the scientist won: \";\n                    cin >>  awardYear;\n                }\n                else if(isWinner == 'n')\n                {\n                    awardYear = 0;\n                }\n                else\n                {\n                    cout << \"Invalid entry.  Please enter either y (yes) or n (no)\";\n                }\n\n                _scientist.addNew(firstName, lastName, gender, birthYear, deathYear, awardYear);\n            }\n            break;\n    case 6:\n        \/\/searchBirth\n        {\n            int year;\n            cout << \"Enter year: \";\n            cin >> year;\n            listServices scientistsBirth;\n            scientistsBirth.changeTo(scientistsBirth.searchBirth(year));\n            cout << \"A list of scientists born in your year of choice\" << endl;\n            print();\n            printNames(scientistsBirth);\n         }\n          break;\n    case 7:\n        \/\/sort by name\n    {\n        listServices sort;\n        sort.changeTo(_scientist.sortByName());\n        cout << \"A list of scinetists in alphabetical order\" << endl;\n        print();\n        printNames(sort);\n\n    }\n        break;\n\n    case 8:\n        \/\/sortByBirth\n\n            _scientist.changeTo(_scientist.sortByBirth());\n            cout << \"An organized list starting with the oldest scientist\" << endl;\n            print();\n            printNames(_scientist);\n        break;\n\n    case 9:\n        \/\/sortByAward\n            _scientist.changeTo(_scientist.sortByAward());\n            cout << \"An organized list of scientists in order of when they received a Turing award.\" << endl;\n            print();\n            printNames(_scientist);\n         break;\n\n    case 10:\n    {\n        listServices norris;\n \/* for(int i = 0; i < _scientist.chuckNorris(); i++){\n       _scientist.chu\n  }*\/\n\n\n        norris.changeTo(_scientist.chuckNorris());\n        \/\/print();\n        printNames(norris);\n\n        break;\n    }\n}\n}\nvoid consoleUI::print()\n{\n    listServices scientists;\n\n    cout.width(4);\n    cout << left << \"No.\";\n    cout.width(scientists.searchLongestName());\n    cout << \"Firstname\" << left;\n    cout.width(10);\n    cout << \"Lastname\" << left;\n    cout.width(10);\n    cout << \"gender\" << left;\n    cout.width(10);\n    cout << \"D.O.B\" << left;\n    cout.width(10);\n    cout << \"D.O.D\" << left;\n    cout.width(scientists.searchLongestName());\n    cout << \"Y.O.A.\" << left << endl;\n    for(int i = 0 ; i < 9 ; i++)\n    {\n        cout << \"--------\";\n    }\n    cout << endl;\n}\n\nvoid consoleUI::printNames (listServices scientistsToPrint)\n{\n    int counter = 1;\n    for(int i = 0; i < scientistsToPrint.getSize() ; i++)\n    {\n        string sex;\n        string isDead;\n        if(scientistsToPrint.getSexFromList(i) == 'm')\n        {\n            sex = \"male\";\n        }\n        else\n        {\n            sex = \"female\";\n        }\n        cout.width(5);\n        cout << left << counter;\n        counter++;\n        cout.width(10);\n        cout << scientistsToPrint.getFirstNameFromList(i) << left;\n        cout.width(10);\n        cout << scientistsToPrint.getLastNameFromList(i) << left;\n        cout.width(10);\n        cout << sex << left;\n        cout.width(10);\n        cout << scientistsToPrint.dobFromList(i) << left;\n        if(scientistsToPrint.dodFromList(i) == 0)\n        {\n            isDead = \"Alive\";\n            cout.width(10);\n            cout << isDead << left;\n        }\n        else\n        {\n            cout.width(10);\n            cout << scientistsToPrint.dodFromList(i) << left;\n        }\n        cout.width(10);\n        cout << scientistsToPrint.getAwardsFromList(i) << left;;\n        cout << \"   *\" << endl;\n\n    }\n    for(int i = 0 ; i < 9 ; i++)\n    {\n        cout << \"--------\";\n    }\n    cout << endl;\n}\nstill fixin#include \"consoleui.h\"\n#include \n#include \nusing namespace std;\n\nconsoleUI::consoleUI()\n{\n\n}\n\nconsoleUI::consoleUI(int chooseNumber)\n{\n    _chooseNumber = chooseNumber;\n}\n\nvoid consoleUI::run()\n{\n    int chooseNumber = 0;\n\n    cout << \"------------------------------------------------------------------\" << endl;\n    cout << \"*------ Database for Scientist ----------*--------Glossary-------*\" << endl;\n    cout << \"* 1:  Display entire list.               * Y.O.D = date of death *\" << endl;\n    cout << \"* 2:  Search by name.                    * Y.O.B = date of birth *\"<< endl;\n    cout << \"* 3:  Search if alive.                   * Y.O.A = year of award *\" << endl;\n    cout << \"* 4:  Sort by award year.                *                       *\" << endl;\n    cout << \"* 5:  Add new scientist.                 *                       *\" << endl;\n    cout << \"* 6:  Search for birth year.             *                       *\" << endl;\n    cout << \"* 7:  Disply list in alphabetical order  *                       *\" << endl;\n    cout << \"* 8:  Sort by birthyear.                 *                       *\" << endl;\n    cout << \"* 9:  Search for Turing award winner.    *                       *\" << endl;\n    cout << \"* 10: Chuck Norris.                      *                       *\" << endl;\n    cout << \"*----------------------------------------*-----------------------*\" << endl;\n    cout << \"-----------------------------------------------------------------\" << endl;\n    cout << \"Enter number: \";\n\n    cin >> chooseNumber;\n\n    \/\/This function sends you (from the number you pick) to the right corresponding case\n    switch (chooseNumber)\n    {\n        \/\/This function displays a list of all the scientists (that is there full names, dob, dod and year of award)\n        case 1:\n        {\n            listServices scientists;\n            cout << \"***List of all scientists***\" << endl;\n            print();\n            printNames(scientists);\n        }\n            break;\n\n        \/\/This function let's you search from either the first or last name\n        case 2:\n            {\n                listServices scientists;\n                \/\/listServices searchName2;\n                string searchTerm;\n                cout << \"Enter a single name to search: \";\n                cin >> searchTerm;\n                scientists.changeTo(_scientist.searchName(searchTerm));\n                print();\n                printNames(scientists);\n\n            }\n            break;\n        case 3:\n            \/\/sortAlive\n            {\n                listServices scientists;\n                string searchTerm;\n                scientists.changeTo(_scientist.searchAlive());\n                cout << \"An organized list starting with the oldest living scientist\" << endl;\n                print();\n                printNames(scientists);\n             }\n              break;\n        case 4:\n            \/\/sortAward\n            {\n                listServices scientistsByAward;\n                scientistsByAward.changeTo(_scientist.sortByAward());\n                cout << \"An organized list of scientists in order of when they received the Turing award.\" << endl;\n                print();\n                printNames(scientistsByAward);\n             }\n            break;\n\n        case 5:\n            {\n                \/\/addNew\n                string firstName;\n                string lastName;\n                char gender;\n                int birthYear;\n                char isAlive;\n                int deathYear;\n                char isWinner;\n                int awardYear;\n\n                cout << \"Please enter the scientist's first name: \";\n                cin >> firstName;\n                cout << \"Please enter the scientist's last name: \";\n                cin >> lastName;\n                cout << \"Enter the scientist's gender (m\/f) : \";\n                cin >> gender;\n                cout << \"Enter the scientist's birth year: \";\n                cin >> birthYear;\n                cout << \"Is the scientist still alive? (y\/n) \";\n                cin >> isAlive;\n                if(isAlive == 'n')\n                {\n                    cout << \"Enter the scientist's year of death: \";\n                    cin >>  deathYear;\n                }\n                else if(isAlive == 'y')\n                {\n                    deathYear = 0;\n                }\n                else\n                {\n                    cout << \"Invalid entry.  Please enter either y (yes) or n (no)\";\n                }\n                cout << \"Did the scientist win a Turing award? (y\/n)\";\n                cin >> isWinner;\n                if(isWinner == 'y')\n                {\n                    cout << \"Enter the year the scientist won: \";\n                    cin >>  awardYear;\n                }\n                else if(isWinner == 'n')\n                {\n                    awardYear = 0;\n                }\n                else\n                {\n                    cout << \"Invalid entry.  Please enter either y (yes) or n (no)\";\n                }\n\n                _scientist.addNew(firstName, lastName, gender, birthYear, deathYear, awardYear);\n            }\n            break;\n    case 6:\n        \/\/searchBirth\n        {\n            int year;\n            cout << \"Enter year: \";\n            cin >> year;\n            listServices scientistsBirth;\n            scientistsBirth.changeTo(scientistsBirth.searchBirth(year));\n            cout << \"A list of scientists born in your year of choice\" << endl;\n            print();\n            printNames(scientistsBirth);\n         }\n          break;\n    case 7:\n        \/\/sort by name\n    {\n        listServices sort;\n        sort.changeTo(_scientist.sortByName());\n        cout << \"A list of scinetists in alphabetical order\" << endl;\n        print();\n        printNames(sort);\n\n    }\n        break;\n\n    case 8:\n        \/\/sortByBirth\n\n            _scientist.changeTo(_scientist.sortByBirth());\n            cout << \"An organized list starting with the oldest scientist\" << endl;\n            print();\n            printNames(_scientist);\n        break;\n\n    case 9:\n        \/\/sortByAward\n            _scientist.changeTo(_scientist.sortByAward());\n            cout << \"An organized list of scientists in order of when they received a Turing award.\" << endl;\n            print();\n            printNames(_scientist);\n         break;\n\n    case 10:\n    {\n        listServices norris;\n \/* for(int i = 0; i < _scientist.chuckNorris(); i++){\n       _scientist.chu\n  }*\/\n\n\n        norris.changeTo(_scientist.chuckNorris());\n        print();\n        printNames(norris);\n\n        break;\n    }\n}\n}\nvoid consoleUI::print()\n{\n    listServices scientists;\n\n    cout.width(4);\n    cout << left << \"No.\";\n    cout.width(scientists.searchLongestName());\n    cout << \"Firstname\" << left;\n    cout.width(10);\n    cout << \"Lastname\" << left;\n    cout.width(10);\n    cout << \"gender\" << left;\n    cout.width(10);\n    cout << \"Y.O.B\" << left;\n    cout.width(10);\n    cout << \"Y.O.D\" << left;\n    cout.width(scientists.searchLongestName());\n    cout << \"Y.O.A\" << left << endl;\n    for(int i = 0 ; i < 9 ; i++)\n    {\n        cout << \"--------\";\n    }\n    cout << endl;\n}\n\nvoid consoleUI::printNames (listServices scientistsToPrint)\n{\n    int counter = 1;\n    for(int i = 0; i < scientistsToPrint.getSize() ; i++)\n    {\n        string sex;\n        string isDead;\n        if(scientistsToPrint.getSexFromList(i) == 'm')\n        {\n            sex = \"male\";\n        }\n        else\n        {\n            sex = \"female\";\n        }\n        cout.width(5);\n        cout << left << counter;\n        counter++;\n        cout.width(10);\n        cout << scientistsToPrint.getFirstNameFromList(i) << left;\n        cout.width(10);\n        cout << scientistsToPrint.getLastNameFromList(i) << left;\n        cout.width(10);\n        cout << sex << left;\n        cout.width(10);\n        cout << scientistsToPrint.dobFromList(i) << left;\n        if(scientistsToPrint.dodFromList(i) == 0)\n        {\n            isDead = \"Alive\";\n            cout.width(10);\n            cout << isDead << left;\n        }\n        else\n        {\n            cout.width(10);\n            cout << scientistsToPrint.dodFromList(i) << left;\n        }\n        cout.width(10);\n        cout << scientistsToPrint.getAwardsFromList(i) << left;;\n        cout << \"   *\" << endl;\n\n    }\n    for(int i = 0 ; i < 9 ; i++)\n    {\n        cout << \"--------\";\n    }\n    cout << endl;\n}\n<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/app_modal_dialog_queue.h\"\n\n#include \"chrome\/browser\/browser_list.h\"\n\nvoid AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {\n  if (!active_dialog_) {\n    ShowModalDialog(dialog);\n    return;\n  }\n  app_modal_dialog_queue_.push(dialog);\n}\n\nvoid AppModalDialogQueue::ShowNextDialog() {\n  AppModalDialog* dialog = GetNextDialog();\n  if (dialog)\n    ShowModalDialog(dialog);\n  else\n    active_dialog_ = NULL;\n}\n\nvoid AppModalDialogQueue::ActivateModalDialog() {\n  if (showing_modal_dialog_) {\n    \/\/ As part of showing a modal dialog we may end up back in this method\n    \/\/ (showing a dialog activates the TabContents, which can trigger a call\n    \/\/ to ActivateModalDialog). We ignore such a request as after the call to\n    \/\/ activate the tab contents the dialog is shown.\n    return;\n  }\n  if (active_dialog_)\n    active_dialog_->ActivateModalDialog();\n}\n\nvoid AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {\n  \/\/ Be sure and set the active_dialog_ field first, otherwise if\n  \/\/ ShowModalDialog triggers a call back to the queue they'll get the old\n  \/\/ dialog. Also, if the dialog calls |ShowNextDialog()| before returning, that\n  \/\/ would write NULL into |active_dialog_| and this function would then undo\n  \/\/ that.\n  active_dialog_ = dialog;\n  showing_modal_dialog_ = true;\n  dialog->ShowModalDialog();\n  showing_modal_dialog_ = false;\n}\n\nAppModalDialog* AppModalDialogQueue::GetNextDialog() {\n  while (!app_modal_dialog_queue_.empty()) {\n    AppModalDialog* dialog = app_modal_dialog_queue_.front();\n    app_modal_dialog_queue_.pop();\n    if (dialog->IsValid())\n      return dialog;\n    delete dialog;\n  }\n  return NULL;\n}\nCopyright change to force builders to rebuild.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/app_modal_dialog_queue.h\"\n\n#include \"chrome\/browser\/browser_list.h\"\n\nvoid AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {\n  if (!active_dialog_) {\n    ShowModalDialog(dialog);\n    return;\n  }\n  app_modal_dialog_queue_.push(dialog);\n}\n\nvoid AppModalDialogQueue::ShowNextDialog() {\n  AppModalDialog* dialog = GetNextDialog();\n  if (dialog)\n    ShowModalDialog(dialog);\n  else\n    active_dialog_ = NULL;\n}\n\nvoid AppModalDialogQueue::ActivateModalDialog() {\n  if (showing_modal_dialog_) {\n    \/\/ As part of showing a modal dialog we may end up back in this method\n    \/\/ (showing a dialog activates the TabContents, which can trigger a call\n    \/\/ to ActivateModalDialog). We ignore such a request as after the call to\n    \/\/ activate the tab contents the dialog is shown.\n    return;\n  }\n  if (active_dialog_)\n    active_dialog_->ActivateModalDialog();\n}\n\nvoid AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {\n  \/\/ Be sure and set the active_dialog_ field first, otherwise if\n  \/\/ ShowModalDialog triggers a call back to the queue they'll get the old\n  \/\/ dialog. Also, if the dialog calls |ShowNextDialog()| before returning, that\n  \/\/ would write NULL into |active_dialog_| and this function would then undo\n  \/\/ that.\n  active_dialog_ = dialog;\n  showing_modal_dialog_ = true;\n  dialog->ShowModalDialog();\n  showing_modal_dialog_ = false;\n}\n\nAppModalDialog* AppModalDialogQueue::GetNextDialog() {\n  while (!app_modal_dialog_queue_.empty()) {\n    AppModalDialog* dialog = app_modal_dialog_queue_.front();\n    app_modal_dialog_queue_.pop();\n    if (dialog->IsValid())\n      return dialog;\n    delete dialog;\n  }\n  return NULL;\n}\n<|endoftext|>"}
{"text":"\/*\nResembla\nhttps:\/\/github.com\/tuem\/resembla\n\nCopyright 2017 Takashi Uemura\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#ifndef RESEMBLA_ELIMINATOR_HPP\n#define RESEMBLA_ELIMINATOR_HPP\n\n#include \n#include \n#include \n#include \n\n#ifdef DEBUG\n#include \n#include \"string_util.hpp\"\n#endif\n\nnamespace resembla {\n\ntemplate<\n    typename string_type = std::string,\n    typename bitvector_type = uint64_t,\n    typename distance_type = long long\n>\nstruct Eliminator\n{\n    using size_type = typename string_type::size_type;\n    using symbol_type = typename string_type::value_type;\n\n    Eliminator(const string_type& pattern)\n    {\n        this->pattern = pattern;\n        if(pattern.empty()){\n            return;\n        }\n\n        pattern_length = pattern.size();\n        block_size = ((pattern_length - 1) >> bitOffset()) + 1;\n        rest_bits = pattern_length - (block_size - 1) * bitWidth();\n        sink = bitvector_type{1} << (rest_bits - 1);\n        VP0 = (bitvector_type{1} << rest_bits) - 1;\n\n        constructPM();\n        zeroes.resize(block_size, 0);\n        work.resize(block_size);\n    }\n\n    void operator()(std::vector& candidates, size_type k, bool keep_tie = true)\n    {\n        using index_distance = std::pair;\n\n        \/\/ calculate scores\n        std::vector work(candidates.size());\n        for(size_type i = 0; i < work.size(); ++i){\n            work[i].first = i;\n            work[i].second = distance(candidates[i]);\n        }\n\n        if(keep_tie){\n            \/\/ sort partially to obtain top-k elements\n            std::nth_element(std::begin(work), std::begin(work) + k, std::end(work),\n                [](const index_distance& a, const index_distance& b) -> bool{\n                    return a.second < b.second;\n                });\n        }\n        else{\n            std::sort(std::begin(work), std::end(work),\n                [](const index_distance& a, const index_distance& b) -> bool{\n                    return a.second < b.second;\n                });\n            \/\/ expand k so that work[l] < work[k] for all l > k\n            while(k < work.size() - 1 && work[k] == work[k + 1]){\n                ++k;\n            }\n        }\n\n        \/\/ ensure that work[i].first < work[j].first if i < j < k\n        std::sort(std::begin(work), std::begin(work) + k,\n            [](const index_distance& a, const index_distance& b) -> bool{\n                return a.first < b.first;\n            });\n#ifdef DEBUG\n        std::cerr << \"DEBUG: \" << \"eliminate \" << work.size() << \" strings\" << std::endl;\n        for(size_type i = 0; i < k; ++i){\n            std::cerr << \"DEBUG: \" << cast_string(candidates[work[i].first]) << \": \" << work[i].second << std::endl;\n        }\n#endif\n\n        \/\/ sort original list\n        for(size_type i = 0; i < k; ++i){\n            std::swap(candidates[i], candidates[work[i].first]);\n        }\n        candidates.erase(std::begin(candidates) + k, std::end(candidates));\n    }\n\nprotected:\n    string_type pattern;\n    size_type pattern_length;\n    symbol_type c_min, c_max;\n    size_type block_size;\n    size_type rest_bits;\n    bitvector_type sink;\n    bitvector_type VP0;\n\n    std::vector>> PM;\n    std::vector zeroes;\n\n    struct WorkData\n    {\n        bitvector_type D0;\n        bitvector_type HP;\n        bitvector_type HN;\n        bitvector_type VP;\n        bitvector_type VN;\n\n        void reset()\n        {\n            D0 = HP = HN = VN = 0;\n            VP = ~(bitvector_type{0});\n        }\n    };\n    std::vector work;\n\n    template static constexpr int bitWidth()\n    {\n        return 8 * sizeof(Integer);\n    }\n\n    static constexpr int bitOffset(int w)\n    {\n        return w < 2 ? 0 : (bitOffset(w >> 1) + 1);\n    }\n\n    template static constexpr int bitOffset()\n    {\n        return bitOffset(bitWidth());\n    }\n\n    template\n    const value_type& findValue(const std::vector>& data,\n            const key_type c, const value_type& default_value) const\n    {\n        if(c < c_min || c_max < c){\n            return default_value;\n        }\n        else if(c == c_min){\n            return PM.front().second;\n        }\n        else if(c == c_max){\n            return PM.back().second;\n        }\n\n        size_type l = 1, r = data.size() - 1;\n        while(r - l > 8){\n            auto i = (l + r) \/ 2;\n            if(data[i].first < c){\n                l = i + 1;\n            }\n            else if(data[i].first > c){\n                r = i;\n            }\n            else{\n                return data[i].second;\n            }\n        }\n\n        for(size_type i = l; i < r; ++i){\n            if(data[i].first == c){\n                return data[i].second;\n            }\n        }\n\n        return default_value;\n    }\n\n    void constructPM()\n    {\n        std::map> PM_work;\n        for(size_type i = 0; i < block_size - 1; ++i){\n            for(size_type j = 0; j < bitWidth(); ++j){\n                if(PM_work[pattern[i * bitWidth() + j]].empty()){\n                    PM_work[pattern[i * bitWidth() + j]].resize(block_size, 0);\n                }\n                PM_work[pattern[i * bitWidth() + j]][i] |= bitvector_type{1} << j;\n            }\n        }\n        for(size_type i = 0; i < rest_bits; ++i){\n            if(PM_work[pattern[(block_size - 1) * bitWidth() + i]].empty()){\n                PM_work[pattern[(block_size - 1) * bitWidth() + i]].resize(block_size, 0);\n            }\n            PM_work[pattern[(block_size - 1) * bitWidth() + i]].back() |= bitvector_type{1} << i;\n        }\n\n        PM.resize(PM_work.size());\n        std::copy(std::begin(PM_work), std::end(PM_work), std::begin(PM));\n        c_min = PM.front().first;\n        c_max = PM.back().first;\n    }\n\n    distance_type distance_sp(const string_type& text)\n    {\n        auto& w = work.front();\n        w.reset();\n        w.VP = VP0;\n\n        distance_type D = pattern_length;\n        for(auto c: text){\n            auto X = findValue(PM, c, zeroes).front() | w.VN;\n\n            w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X;\n            w.HP = w.VN | ~(w.VP | w.D0);\n            w.HN = w.VP & w.D0;\n\n            X = (w.HP << 1) | 1;\n            w.VP = (w.HN << 1) | ~(X | w.D0);\n            w.VN = X & w.D0;\n\n            if(w.HP & sink){\n                ++D;\n            }\n            else if(w.HN & sink){\n                --D;\n            }\n        }\n        return D;\n    }\n\n    distance_type distance_lp(const string_type& text)\n    {\n        constexpr bitvector_type msb = bitvector_type{1} << (bitWidth() - 1);\n\n        for(auto& w: work){\n            w.reset();\n        }\n        work.back().VP = VP0;\n\n        distance_type D = pattern_length;\n        for(auto c: text){\n            const auto& PMc = findValue(PM, c, zeroes);\n            for(size_type r = 0; r < block_size; ++r){\n                auto& w = work[r];\n                auto X = PMc[r];\n                if(r > 0 && (work[r - 1].HN & msb)){\n                    X |= 1;\n                }\n\n                w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X | w.VN;\n                w.HP = w.VN | ~(w.VP | w.D0);\n                w.HN = w.VP & w.D0;\n\n                X = w.HP << 1;\n                if(r == 0 || work[r - 1].HP & msb){\n                    X |= 1;\n                }\n                w.VP = (w.HN << 1) | ~(X | w.D0);\n                if(r > 0 && (work[r - 1].HN & msb)){\n                    w.VP |= 1;\n                }\n                w.VN = X & w.D0;\n            }\n\n            if(work.back().HP & sink){\n                ++D;\n            }\n            else if(work.back().HN & sink){\n                --D;\n            }\n        }\n        return D;\n    }\n\n    distance_type distance(const string_type& text)\n    {\n        if(text.empty()){\n            return pattern_length;\n        }\n        else if(pattern_length == 0){\n            return text.size();\n        }\n\n        if(block_size == 1){\n            return distance_sp(text);\n        }\n        else{\n            return distance_lp(text);\n        }\n    }\n};\n\n}\n#endif\nuse member initializer list\/*\nResembla\nhttps:\/\/github.com\/tuem\/resembla\n\nCopyright 2017 Takashi Uemura\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#ifndef RESEMBLA_ELIMINATOR_HPP\n#define RESEMBLA_ELIMINATOR_HPP\n\n#include \n#include \n#include \n#include \n\n#ifdef DEBUG\n#include \n#include \"string_util.hpp\"\n#endif\n\nnamespace resembla {\n\ntemplate<\n    typename string_type = std::string,\n    typename bitvector_type = uint64_t,\n    typename distance_type = long long\n>\nstruct Eliminator\n{\n    using size_type = typename string_type::size_type;\n    using symbol_type = typename string_type::value_type;\n\n    Eliminator(const string_type& pattern): pattern(pattern)\n    {\n        if(pattern.empty()){\n            return;\n        }\n\n        pattern_length = pattern.size();\n        block_size = ((pattern_length - 1) >> bitOffset()) + 1;\n        rest_bits = pattern_length - (block_size - 1) * bitWidth();\n        sink = bitvector_type{1} << (rest_bits - 1);\n        VP0 = (bitvector_type{1} << rest_bits) - 1;\n\n        constructPM();\n        zeroes.resize(block_size, 0);\n        work.resize(block_size);\n    }\n\n    void operator()(std::vector& candidates, size_type k, bool keep_tie = true)\n    {\n        using index_distance = std::pair;\n\n        \/\/ calculate scores\n        std::vector work(candidates.size());\n        for(size_type i = 0; i < work.size(); ++i){\n            work[i].first = i;\n            work[i].second = distance(candidates[i]);\n        }\n\n        if(keep_tie){\n            \/\/ sort partially to obtain top-k elements\n            std::nth_element(std::begin(work), std::begin(work) + k, std::end(work),\n                [](const index_distance& a, const index_distance& b) -> bool{\n                    return a.second < b.second;\n                });\n        }\n        else{\n            std::sort(std::begin(work), std::end(work),\n                [](const index_distance& a, const index_distance& b) -> bool{\n                    return a.second < b.second;\n                });\n            \/\/ expand k so that work[l] < work[k] for all l > k\n            while(k < work.size() - 1 && work[k] == work[k + 1]){\n                ++k;\n            }\n        }\n\n        \/\/ ensure that work[i].first < work[j].first if i < j < k\n        std::sort(std::begin(work), std::begin(work) + k,\n            [](const index_distance& a, const index_distance& b) -> bool{\n                return a.first < b.first;\n            });\n#ifdef DEBUG\n        std::cerr << \"DEBUG: \" << \"eliminate \" << work.size() << \" strings\" << std::endl;\n        for(size_type i = 0; i < k; ++i){\n            std::cerr << \"DEBUG: \" << cast_string(candidates[work[i].first]) << \": \" << work[i].second << std::endl;\n        }\n#endif\n\n        \/\/ sort original list\n        for(size_type i = 0; i < k; ++i){\n            std::swap(candidates[i], candidates[work[i].first]);\n        }\n        candidates.erase(std::begin(candidates) + k, std::end(candidates));\n    }\n\nprotected:\n    string_type pattern;\n    size_type pattern_length;\n    symbol_type c_min, c_max;\n    size_type block_size;\n    size_type rest_bits;\n    bitvector_type sink;\n    bitvector_type VP0;\n\n    std::vector>> PM;\n    std::vector zeroes;\n\n    struct WorkData\n    {\n        bitvector_type D0;\n        bitvector_type HP;\n        bitvector_type HN;\n        bitvector_type VP;\n        bitvector_type VN;\n\n        void reset()\n        {\n            D0 = HP = HN = VN = 0;\n            VP = ~(bitvector_type{0});\n        }\n    };\n    std::vector work;\n\n    template static constexpr int bitWidth()\n    {\n        return 8 * sizeof(Integer);\n    }\n\n    static constexpr int bitOffset(int w)\n    {\n        return w < 2 ? 0 : (bitOffset(w >> 1) + 1);\n    }\n\n    template static constexpr int bitOffset()\n    {\n        return bitOffset(bitWidth());\n    }\n\n    template\n    const value_type& findValue(const std::vector>& data,\n            const key_type c, const value_type& default_value) const\n    {\n        if(c < c_min || c_max < c){\n            return default_value;\n        }\n        else if(c == c_min){\n            return PM.front().second;\n        }\n        else if(c == c_max){\n            return PM.back().second;\n        }\n\n        size_type l = 1, r = data.size() - 1;\n        while(r - l > 8){\n            auto i = (l + r) \/ 2;\n            if(data[i].first < c){\n                l = i + 1;\n            }\n            else if(data[i].first > c){\n                r = i;\n            }\n            else{\n                return data[i].second;\n            }\n        }\n\n        for(size_type i = l; i < r; ++i){\n            if(data[i].first == c){\n                return data[i].second;\n            }\n        }\n\n        return default_value;\n    }\n\n    void constructPM()\n    {\n        std::map> PM_work;\n        for(size_type i = 0; i < block_size - 1; ++i){\n            for(size_type j = 0; j < bitWidth(); ++j){\n                if(PM_work[pattern[i * bitWidth() + j]].empty()){\n                    PM_work[pattern[i * bitWidth() + j]].resize(block_size, 0);\n                }\n                PM_work[pattern[i * bitWidth() + j]][i] |= bitvector_type{1} << j;\n            }\n        }\n        for(size_type i = 0; i < rest_bits; ++i){\n            if(PM_work[pattern[(block_size - 1) * bitWidth() + i]].empty()){\n                PM_work[pattern[(block_size - 1) * bitWidth() + i]].resize(block_size, 0);\n            }\n            PM_work[pattern[(block_size - 1) * bitWidth() + i]].back() |= bitvector_type{1} << i;\n        }\n\n        PM.resize(PM_work.size());\n        std::copy(std::begin(PM_work), std::end(PM_work), std::begin(PM));\n        c_min = PM.front().first;\n        c_max = PM.back().first;\n    }\n\n    distance_type distance_sp(const string_type& text)\n    {\n        auto& w = work.front();\n        w.reset();\n        w.VP = VP0;\n\n        distance_type D = pattern_length;\n        for(auto c: text){\n            auto X = findValue(PM, c, zeroes).front() | w.VN;\n\n            w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X;\n            w.HP = w.VN | ~(w.VP | w.D0);\n            w.HN = w.VP & w.D0;\n\n            X = (w.HP << 1) | 1;\n            w.VP = (w.HN << 1) | ~(X | w.D0);\n            w.VN = X & w.D0;\n\n            if(w.HP & sink){\n                ++D;\n            }\n            else if(w.HN & sink){\n                --D;\n            }\n        }\n        return D;\n    }\n\n    distance_type distance_lp(const string_type& text)\n    {\n        constexpr bitvector_type msb = bitvector_type{1} << (bitWidth() - 1);\n\n        for(auto& w: work){\n            w.reset();\n        }\n        work.back().VP = VP0;\n\n        distance_type D = pattern_length;\n        for(auto c: text){\n            const auto& PMc = findValue(PM, c, zeroes);\n            for(size_type r = 0; r < block_size; ++r){\n                auto& w = work[r];\n                auto X = PMc[r];\n                if(r > 0 && (work[r - 1].HN & msb)){\n                    X |= 1;\n                }\n\n                w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X | w.VN;\n                w.HP = w.VN | ~(w.VP | w.D0);\n                w.HN = w.VP & w.D0;\n\n                X = w.HP << 1;\n                if(r == 0 || work[r - 1].HP & msb){\n                    X |= 1;\n                }\n                w.VP = (w.HN << 1) | ~(X | w.D0);\n                if(r > 0 && (work[r - 1].HN & msb)){\n                    w.VP |= 1;\n                }\n                w.VN = X & w.D0;\n            }\n\n            if(work.back().HP & sink){\n                ++D;\n            }\n            else if(work.back().HN & sink){\n                --D;\n            }\n        }\n        return D;\n    }\n\n    distance_type distance(const string_type& text)\n    {\n        if(text.empty()){\n            return pattern_length;\n        }\n        else if(pattern_length == 0){\n            return text.size();\n        }\n\n        if(block_size == 1){\n            return distance_sp(text);\n        }\n        else{\n            return distance_lp(text);\n        }\n    }\n};\n\n}\n#endif\n<|endoftext|>"}
{"text":"#include \"heap.h\"\n\n#include \n\nHeap::Heap(size_t timestamp, size_t id, std::string type, std::string name)\n    : MemoryObject(timestamp, 0, 0, 0), id_(id), type_(type), name_(name)\n{\n        \n}\n\nHeap::~Heap() {\n    \/\/maps manages themselves\n}\n\nvoid Heap::printContent() const {\n    std::cout << \"printing content for heap \" << id_ << \" of type: \"<< type_.c_str() << \"\\n\";\n    for(auto it = cores_.begin(); it != cores_.end(); ++it) {\n        it->second.printContent();\n    }\n}\n\nCore* Heap::getCore(size_t pointer) {\n    auto found = cores_.find(pointer);\n    if(found == cores_.end()) {\n        return nullptr;\n    }\n    return (&found->second);\n}\n\nCore* Heap::getCoreForAllocation(size_t pointer) {\n    auto found = alloc_to_core.find(pointer);\n    if(found == alloc_to_core.end()) {\n        return nullptr;\n    }\n    return getCore(found->second);\n}\n\nbool Heap::removeCore(size_t timestamp, size_t pointer) {\n    auto it = cores_.find(pointer);\n    if(it == cores_.end()) {\n        std::cout << \"remove Core failed in heap \" << id_ << std::endl;\n        return false;\n    }\n    size_t managed = it->second.getManagedSize();\n    managed_memory_ -= managed;\n    cores_.erase(it);\n    return true;\n}\n\nbool Heap::addCore(size_t timestamp, size_t pointer, size_t managed_size) {\n    Core c(timestamp, pointer, managed_size);\n    auto emp = cores_.insert(std::make_pair(pointer, c));\n    if(!emp.second) {\n        std::cout << \"tryint to add already existing core: \" << std::hex << pointer << std::dec << std::endl;\n        return false;\n    }\n    managed_memory_ += managed_size;\n    return true;\n}\n\nbool Heap::growCore(size_t timestamp, size_t pointer, size_t size) {\n    Core* core = getCore(pointer);\n    if(core != nullptr) {\n        core->grow(size);\n        return true;    \n    }\n    return false;\n}\n\nbool Heap::shrinkCore(size_t timestamp, size_t pointer, size_t size) {\n    Core* core = getCore(pointer);\n    if(core != nullptr) {\n        core->shrink(size);\n        return true;    \n    }\n    return false;\n}\n\nbool Heap::addAllocation(size_t timestamp, size_t pointer, size_t size) {\n        for(auto it = cores_.begin(); it != cores_.end(); ++it) {\n            if(it->second.addAllocation(timestamp, pointer, size)) {\n                alloc_to_core.emplace_hint(alloc_to_core.cend(), pointer,it->second.getPointer());\n                used_memory_ += size;\n                simple_allocation_events_[timestamp] = heap_usage(used_memory_, managed_memory_);\n                return true;\n            }\n        }\n        \/\/does the allocation span over two cores?\n        for(auto it = cores_.begin(); it != cores_.end(); ++it) {\n            auto next = std::next(it);\n            if(next != cores_.end()) {\n                if(it->second.pointerInside(pointer) && next->second.pointerInside(pointer + size)) {\n                    it->second.addAllocation(timestamp,pointer,size, true);\n                    alloc_to_core.emplace_hint(alloc_to_core.cend(), pointer,it->second.getPointer());\n                    used_memory_ += size;\n                    simple_allocation_events_[timestamp] = heap_usage(used_memory_, managed_memory_);\n                    return true;                 \n                }\n            }\n        }\n        std::cout << \"did not find a core for allocation in heap: \" << id_ << \" pointer: \" << std::hex << pointer << std::dec << \" size: \" << size << \" at timestamp \" << timestamp << \"\\n\";\n    return false;\n}\n\nbool Heap::removeAllocation(size_t timestamp, size_t pointer) {\n    Core* core = getCoreForAllocation(pointer);\n    if(core == nullptr) {\n        std::cout << \"core was null for: \" << std::hex << pointer << std::dec << \"at \" << timestamp << std::endl;\n        printContent();\n        return false;\n    }\n    size_t removed_memory = core->removeAllocation(timestamp, pointer);\n    alloc_to_core.erase(pointer);    \n    used_memory_ -= removed_memory;\n    simple_allocation_events_[timestamp] = heap_usage(used_memory_, managed_memory_);\n    return true;\n}\n\nbool Heap::setBackingAllocator(size_t alloc) {\n    backing_allocator_ids.push_back(alloc);\n    return true;\n}\n\nvoid Heap::printBacking() {\n    for(int i = 0; i < backing_allocator_ids.size(); ++i) {\n        std::cout << \" \" << backing_allocator_ids[i];\n    }\n}grow and shrink core now properly updates managed_memory#include \"heap.h\"\n\n#include \n\nHeap::Heap(size_t timestamp, size_t id, std::string type, std::string name)\n    : MemoryObject(timestamp, 0, 0, 0), id_(id), type_(type), name_(name)\n{\n        \n}\n\nHeap::~Heap() {\n    \/\/maps manages themselves\n}\n\nvoid Heap::printContent() const {\n    std::cout << \"printing content for heap \" << id_ << \" of type: \"<< type_.c_str() << \"\\n\";\n    for(auto it = cores_.begin(); it != cores_.end(); ++it) {\n        it->second.printContent();\n    }\n}\n\nCore* Heap::getCore(size_t pointer) {\n    auto found = cores_.find(pointer);\n    if(found == cores_.end()) {\n        return nullptr;\n    }\n    return (&found->second);\n}\n\nCore* Heap::getCoreForAllocation(size_t pointer) {\n    auto found = alloc_to_core.find(pointer);\n    if(found == alloc_to_core.end()) {\n        return nullptr;\n    }\n    return getCore(found->second);\n}\n\nbool Heap::removeCore(size_t timestamp, size_t pointer) {\n    auto it = cores_.find(pointer);\n    if(it == cores_.end()) {\n        std::cout << \"remove Core failed in heap \" << id_ << std::endl;\n        return false;\n    }\n    size_t managed = it->second.getManagedSize();\n    managed_memory_ -= managed;\n    cores_.erase(it);\n    return true;\n}\n\nbool Heap::addCore(size_t timestamp, size_t pointer, size_t managed_size) {\n    Core c(timestamp, pointer, managed_size);\n    auto emp = cores_.insert(std::make_pair(pointer, c));\n    if(!emp.second) {\n        std::cout << \"tryint to add already existing core: \" << std::hex << pointer << std::dec << std::endl;\n        return false;\n    }\n    managed_memory_ += managed_size;\n    return true;\n}\n\nbool Heap::growCore(size_t timestamp, size_t pointer, size_t size) {\n    Core* core = getCore(pointer);\n    if(core != nullptr) {\n        core->grow(size);\n        managed_memory_ += size;\n        return true;    \n    }\n    return false;\n}\n\nbool Heap::shrinkCore(size_t timestamp, size_t pointer, size_t size) {\n    Core* core = getCore(pointer);\n    if(core != nullptr) {\n        core->shrink(size);\n        managed_memory_ -= size;\n        return true;    \n    }\n    return false;\n}\n\nbool Heap::addAllocation(size_t timestamp, size_t pointer, size_t size) {\n        for(auto it = cores_.begin(); it != cores_.end(); ++it) {\n            if(it->second.addAllocation(timestamp, pointer, size)) {\n                alloc_to_core.emplace_hint(alloc_to_core.cend(), pointer,it->second.getPointer());\n                used_memory_ += size;\n                simple_allocation_events_[timestamp] = heap_usage(used_memory_, managed_memory_);\n                return true;\n            }\n        }\n        \/\/does the allocation span over two cores?\n        for(auto it = cores_.begin(); it != cores_.end(); ++it) {\n            auto next = std::next(it);\n            if(next != cores_.end()) {\n                if(it->second.pointerInside(pointer) && next->second.pointerInside(pointer + size)) {\n                    it->second.addAllocation(timestamp,pointer,size, true);\n                    alloc_to_core.emplace_hint(alloc_to_core.cend(), pointer,it->second.getPointer());\n                    used_memory_ += size;\n                    simple_allocation_events_[timestamp] = heap_usage(used_memory_, managed_memory_);\n                    return true;                 \n                }\n            }\n        }\n        std::cout << \"did not find a core for allocation in heap: \" << id_ << \" pointer: \" << std::hex << pointer << std::dec << \" size: \" << size << \" at timestamp \" << timestamp << \"\\n\";\n    return false;\n}\n\nbool Heap::removeAllocation(size_t timestamp, size_t pointer) {\n    Core* core = getCoreForAllocation(pointer);\n    if(core == nullptr) {\n        std::cout << \"core was null for: \" << std::hex << pointer << std::dec << \"at \" << timestamp << std::endl;\n        printContent();\n        return false;\n    }\n    size_t removed_memory = core->removeAllocation(timestamp, pointer);\n    alloc_to_core.erase(pointer);    \n    used_memory_ -= removed_memory;\n    simple_allocation_events_[timestamp] = heap_usage(used_memory_, managed_memory_);\n    return true;\n}\n\nbool Heap::setBackingAllocator(size_t alloc) {\n    backing_allocator_ids.push_back(alloc);\n    return true;\n}\n\nvoid Heap::printBacking() {\n    for(int i = 0; i < backing_allocator_ids.size(); ++i) {\n        std::cout << \" \" << backing_allocator_ids[i];\n    }\n}<|endoftext|>"}
{"text":"\/\/===- Printer.cpp - Code for printing data structure graphs nicely -------===\/\/\n\/\/\n\/\/ This file implements the 'dot' graph printer.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/DataStructure.h\"\n#include \"llvm\/Analysis\/DSGraph.h\"\n#include \"llvm\/Analysis\/DSGraphTraits.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/GraphWriter.h\"\n#include \"Support\/Statistic.h\"\n#include \n#include \n\n\/\/ OnlyPrintMain - The DataStructure printer exposes this option to allow\n\/\/ printing of only the graph for \"main\".\n\/\/\nnamespace {\n  cl::opt OnlyPrintMain(\"only-print-main-ds\", cl::ReallyHidden);\n  Statistic<> MaxGraphSize   (\"dsnode\", \"Maximum graph size\");\n  Statistic<> NumFoldedNodes (\"dsnode\", \"Number of folded nodes (in final graph)\");\n}\n\n\nvoid DSNode::dump() const { print(std::cerr, 0); }\n\nstatic std::string getCaption(const DSNode *N, const DSGraph *G) {\n  std::stringstream OS;\n  Module *M = 0;\n  \/\/ Get the module from ONE of the functions in the graph it is available.\n  if (G && !G->getReturnNodes().empty())\n    M = G->getReturnNodes().begin()->first->getParent();\n\n  if (N->isNodeCompletelyFolded())\n    OS << \"FOLDED\";\n  else {\n    WriteTypeSymbolic(OS, N->getType(), M);\n    if (N->isArray())\n      OS << \" array\";\n  }\n  if (unsigned NodeType = N->getNodeFlags()) {\n    OS << \": \";\n    if (NodeType & DSNode::AllocaNode ) OS << \"S\";\n    if (NodeType & DSNode::HeapNode   ) OS << \"H\";\n    if (NodeType & DSNode::GlobalNode ) OS << \"G\";\n    if (NodeType & DSNode::UnknownNode) OS << \"U\";\n    if (NodeType & DSNode::Incomplete ) OS << \"I\";\n    if (NodeType & DSNode::Modified   ) OS << \"M\";\n    if (NodeType & DSNode::Read       ) OS << \"R\";\n#ifndef NDEBUG\n    if (NodeType & DSNode::DEAD       ) OS << \"\";\n#endif\n    OS << \"\\n\";\n  }\n\n  for (unsigned i = 0, e = N->getGlobals().size(); i != e; ++i) {\n    WriteAsOperand(OS, N->getGlobals()[i], false, true, M);\n    OS << \"\\n\";\n  }\n\n  return OS.str();\n}\n\ntemplate<>\nstruct DOTGraphTraits : public DefaultDOTGraphTraits {\n  static std::string getGraphName(const DSGraph *G) {\n    switch (G->getReturnNodes().size()) {\n    case 0: return G->getFunctionNames();\n    case 1: return \"Function \" + G->getFunctionNames();\n    default: return \"Functions: \" + G->getFunctionNames();\n    }\n  }\n\n  static const char *getGraphProperties(const DSGraph *G) {\n    return \"\\tsize=\\\"10,7.5\\\";\\n\"\n           \"\\trotate=\\\"90\\\";\\n\";\n  }\n\n  static std::string getNodeLabel(const DSNode *Node, const DSGraph *Graph) {\n    return getCaption(Node, Graph);\n  }\n\n  static std::string getNodeAttributes(const DSNode *N) {\n    return \"shape=Mrecord\";\/\/fontname=Courier\";\n  }\n  \n  \/\/\/ addCustomGraphFeatures - Use this graph writing hook to emit call nodes\n  \/\/\/ and the return node.\n  \/\/\/\n  static void addCustomGraphFeatures(const DSGraph *G,\n                                     GraphWriter &GW) {\n    Module *CurMod = 0;\n    if (!G->getReturnNodes().empty())\n      CurMod = G->getReturnNodes().begin()->first->getParent();\n\n    \/\/ Add scalar nodes to the graph...\n    const DSGraph::ScalarMapTy &VM = G->getScalarMap();\n    for (DSGraph::ScalarMapTy::const_iterator I = VM.begin(); I != VM.end();++I)\n      if (!isa(I->first)) {\n        std::stringstream OS;\n        WriteAsOperand(OS, I->first, false, true, CurMod);\n        GW.emitSimpleNode(I->first, \"\", OS.str());\n        \n        \/\/ Add edge from return node to real destination\n        int EdgeDest = I->second.getOffset() >> DS::PointerShift;\n        if (EdgeDest == 0) EdgeDest = -1;\n        GW.emitEdge(I->first, -1, I->second.getNode(),\n                    EdgeDest, \"arrowtail=tee,color=gray63\");\n      }\n\n\n    \/\/ Output the returned value pointer...\n    const DSGraph::ReturnNodesTy &RetNodes = G->getReturnNodes();\n    for (DSGraph::ReturnNodesTy::const_iterator I = RetNodes.begin(),\n           E = RetNodes.end(); I != E; ++I)\n      if (I->second.getNode()) {\n        std::string Label;\n        if (RetNodes.size() == 1)\n          Label = \"returning\";\n        else\n          Label = I->first->getName() + \" ret node\";\n        \/\/ Output the return node...\n        GW.emitSimpleNode((void*)1, \"plaintext=circle\", Label);\n\n        \/\/ Add edge from return node to real destination\n        int RetEdgeDest = I->second.getOffset() >> DS::PointerShift;;\n        if (RetEdgeDest == 0) RetEdgeDest = -1;\n        GW.emitEdge((void*)1, -1, I->second.getNode(),\n                    RetEdgeDest, \"arrowtail=tee,color=gray63\");\n      }\n\n    \/\/ Output all of the call nodes...\n    const std::vector &FCs =\n      G->shouldPrintAuxCalls() ? G->getAuxFunctionCalls()\n      : G->getFunctionCalls();\n    for (unsigned i = 0, e = FCs.size(); i != e; ++i) {\n      const DSCallSite &Call = FCs[i];\n      std::vector EdgeSourceCaptions(Call.getNumPtrArgs()+2);\n      EdgeSourceCaptions[0] = \"r\";\n      if (Call.isDirectCall())\n        EdgeSourceCaptions[1] = Call.getCalleeFunc()->getName();\n      else\n        EdgeSourceCaptions[1] = \"f\";\n\n      GW.emitSimpleNode(&Call, \"shape=record\", \"call\", Call.getNumPtrArgs()+2,\n                        &EdgeSourceCaptions);\n\n      if (DSNode *N = Call.getRetVal().getNode()) {\n        int EdgeDest = Call.getRetVal().getOffset() >> DS::PointerShift;\n        if (EdgeDest == 0) EdgeDest = -1;\n        GW.emitEdge(&Call, 0, N, EdgeDest, \"color=gray63,tailclip=false\");\n      }\n\n      \/\/ Print out the callee...\n      if (Call.isIndirectCall()) {\n        DSNode *N = Call.getCalleeNode();\n        assert(N && \"Null call site callee node!\");\n        GW.emitEdge(&Call, 1, N, -1, \"color=gray63,tailclip=false\");\n      }\n\n      for (unsigned j = 0, e = Call.getNumPtrArgs(); j != e; ++j)\n        if (DSNode *N = Call.getPtrArg(j).getNode()) {\n          int EdgeDest = Call.getPtrArg(j).getOffset() >> DS::PointerShift;\n          if (EdgeDest == 0) EdgeDest = -1;\n          GW.emitEdge(&Call, j+2, N, EdgeDest, \"color=gray63,tailclip=false\");\n        }\n    }\n  }\n};\n\nvoid DSNode::print(std::ostream &O, const DSGraph *G) const {\n  GraphWriter W(O, G);\n  W.writeNode(this);\n}\n\nvoid DSGraph::print(std::ostream &O) const {\n  WriteGraph(O, this, \"DataStructures\");\n}\n\nvoid DSGraph::writeGraphToFile(std::ostream &O,\n                               const std::string &GraphName) const {\n  std::string Filename = GraphName + \".dot\";\n  O << \"Writing '\" << Filename << \"'...\";\n  std::ofstream F(Filename.c_str());\n  \n  if (F.good()) {\n    print(F);\n    unsigned NumCalls = shouldPrintAuxCalls() ?\n      getAuxFunctionCalls().size() : getFunctionCalls().size();\n    O << \" [\" << getGraphSize() << \"+\" << NumCalls << \"]\\n\";\n  } else {\n    O << \"  error opening file for writing!\\n\";\n  }\n}\n\n\/\/\/ viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,\n\/\/\/ then cleanup.  For use from the debugger.\n\/\/\/\nvoid DSGraph::viewGraph() const {\n  std::ofstream F(\"\/tmp\/tempgraph.dot\");\n  if (!F.good()) {\n    std::cerr << \"Error opening '\/tmp\/tempgraph.dot' for temporary graph!\\n\";\n    return;\n  }\n  print(F);\n  F.close();\n  if (system(\"dot -Tps \/tmp\/tempgraph.dot > \/tmp\/tempgraph.ps\"))\n    std::cerr << \"Error running dot: 'dot' not in path?\\n\";\n  system(\"gv \/tmp\/tempgraph.ps\");\n  system(\"rm \/tmp\/tempgraph.dot \/tmp\/tempgraph.ps\");\n}\n\n\ntemplate \nstatic void printCollection(const Collection &C, std::ostream &O,\n                            const Module *M, const std::string &Prefix) {\n  if (M == 0) {\n    O << \"Null Module pointer, cannot continue!\\n\";\n    return;\n  }\n\n  unsigned TotalNumNodes = 0, TotalCallNodes = 0;\n  for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)\n    if (C.hasGraph(*I)) {\n      DSGraph &Gr = C.getDSGraph((Function&)*I);\n      TotalNumNodes += Gr.getGraphSize();\n      unsigned NumCalls = Gr.shouldPrintAuxCalls() ?\n        Gr.getAuxFunctionCalls().size() : Gr.getFunctionCalls().size();\n\n      TotalCallNodes += NumCalls;\n      if (I->getName() == \"main\" || !OnlyPrintMain)\n        Gr.writeGraphToFile(O, Prefix+I->getName());\n      else {\n        O << \"Skipped Writing '\" << Prefix+I->getName() << \".dot'... [\"\n          << Gr.getGraphSize() << \"+\" << NumCalls << \"]\\n\";\n      }\n\n      if (MaxGraphSize < Gr.getNodes().size())\n        MaxGraphSize = Gr.getNodes().size();\n      for (unsigned i = 0, e = Gr.getNodes().size(); i != e; ++i)\n        if (Gr.getNodes()[i]->isNodeCompletelyFolded())\n          ++NumFoldedNodes;\n    }\n\n  DSGraph &GG = C.getGlobalsGraph();\n  TotalNumNodes  += GG.getGraphSize();\n  TotalCallNodes += GG.getFunctionCalls().size();\n  if (!OnlyPrintMain) {\n    GG.writeGraphToFile(O, Prefix+\"GlobalsGraph\");\n  } else {\n    O << \"Skipped Writing '\" << Prefix << \"GlobalsGraph.dot'... [\"\n      << GG.getGraphSize() << \"+\" << GG.getFunctionCalls().size() << \"]\\n\";\n  }\n\n  O << \"\\nGraphs contain [\" << TotalNumNodes << \"+\" << TotalCallNodes \n    << \"] nodes total\" << std::endl;\n}\n\n\n\/\/ print - Print out the analysis results...\nvoid LocalDataStructures::print(std::ostream &O, const Module *M) const {\n  printCollection(*this, O, M, \"ds.\");\n}\n\nvoid BUDataStructures::print(std::ostream &O, const Module *M) const {\n  printCollection(*this, O, M, \"bu.\");\n}\n\nvoid TDDataStructures::print(std::ostream &O, const Module *M) const {\n  printCollection(*this, O, M, \"td.\");\n}\nDont' print scalar nodes for ConstantPointerRefs\/\/===- Printer.cpp - Code for printing data structure graphs nicely -------===\/\/\n\/\/\n\/\/ This file implements the 'dot' graph printer.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/DataStructure.h\"\n#include \"llvm\/Analysis\/DSGraph.h\"\n#include \"llvm\/Analysis\/DSGraphTraits.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/GraphWriter.h\"\n#include \"Support\/Statistic.h\"\n#include \n#include \n\n\/\/ OnlyPrintMain - The DataStructure printer exposes this option to allow\n\/\/ printing of only the graph for \"main\".\n\/\/\nnamespace {\n  cl::opt OnlyPrintMain(\"only-print-main-ds\", cl::ReallyHidden);\n  Statistic<> MaxGraphSize   (\"dsnode\", \"Maximum graph size\");\n  Statistic<> NumFoldedNodes (\"dsnode\", \"Number of folded nodes (in final graph)\");\n}\n\n\nvoid DSNode::dump() const { print(std::cerr, 0); }\n\nstatic std::string getCaption(const DSNode *N, const DSGraph *G) {\n  std::stringstream OS;\n  Module *M = 0;\n  \/\/ Get the module from ONE of the functions in the graph it is available.\n  if (G && !G->getReturnNodes().empty())\n    M = G->getReturnNodes().begin()->first->getParent();\n\n  if (N->isNodeCompletelyFolded())\n    OS << \"FOLDED\";\n  else {\n    WriteTypeSymbolic(OS, N->getType(), M);\n    if (N->isArray())\n      OS << \" array\";\n  }\n  if (unsigned NodeType = N->getNodeFlags()) {\n    OS << \": \";\n    if (NodeType & DSNode::AllocaNode ) OS << \"S\";\n    if (NodeType & DSNode::HeapNode   ) OS << \"H\";\n    if (NodeType & DSNode::GlobalNode ) OS << \"G\";\n    if (NodeType & DSNode::UnknownNode) OS << \"U\";\n    if (NodeType & DSNode::Incomplete ) OS << \"I\";\n    if (NodeType & DSNode::Modified   ) OS << \"M\";\n    if (NodeType & DSNode::Read       ) OS << \"R\";\n#ifndef NDEBUG\n    if (NodeType & DSNode::DEAD       ) OS << \"\";\n#endif\n    OS << \"\\n\";\n  }\n\n  for (unsigned i = 0, e = N->getGlobals().size(); i != e; ++i) {\n    WriteAsOperand(OS, N->getGlobals()[i], false, true, M);\n    OS << \"\\n\";\n  }\n\n  return OS.str();\n}\n\ntemplate<>\nstruct DOTGraphTraits : public DefaultDOTGraphTraits {\n  static std::string getGraphName(const DSGraph *G) {\n    switch (G->getReturnNodes().size()) {\n    case 0: return G->getFunctionNames();\n    case 1: return \"Function \" + G->getFunctionNames();\n    default: return \"Functions: \" + G->getFunctionNames();\n    }\n  }\n\n  static const char *getGraphProperties(const DSGraph *G) {\n    return \"\\tsize=\\\"10,7.5\\\";\\n\"\n           \"\\trotate=\\\"90\\\";\\n\";\n  }\n\n  static std::string getNodeLabel(const DSNode *Node, const DSGraph *Graph) {\n    return getCaption(Node, Graph);\n  }\n\n  static std::string getNodeAttributes(const DSNode *N) {\n    return \"shape=Mrecord\";\/\/fontname=Courier\";\n  }\n  \n  \/\/\/ addCustomGraphFeatures - Use this graph writing hook to emit call nodes\n  \/\/\/ and the return node.\n  \/\/\/\n  static void addCustomGraphFeatures(const DSGraph *G,\n                                     GraphWriter &GW) {\n    Module *CurMod = 0;\n    if (!G->getReturnNodes().empty())\n      CurMod = G->getReturnNodes().begin()->first->getParent();\n\n    \/\/ Add scalar nodes to the graph...\n    const DSGraph::ScalarMapTy &VM = G->getScalarMap();\n    for (DSGraph::ScalarMapTy::const_iterator I = VM.begin(); I != VM.end();++I)\n      if (!isa(I->first) && !isa(I->first)) {\n        std::stringstream OS;\n        WriteAsOperand(OS, I->first, false, true, CurMod);\n        GW.emitSimpleNode(I->first, \"\", OS.str());\n        \n        \/\/ Add edge from return node to real destination\n        int EdgeDest = I->second.getOffset() >> DS::PointerShift;\n        if (EdgeDest == 0) EdgeDest = -1;\n        GW.emitEdge(I->first, -1, I->second.getNode(),\n                    EdgeDest, \"arrowtail=tee,color=gray63\");\n      }\n\n\n    \/\/ Output the returned value pointer...\n    const DSGraph::ReturnNodesTy &RetNodes = G->getReturnNodes();\n    for (DSGraph::ReturnNodesTy::const_iterator I = RetNodes.begin(),\n           E = RetNodes.end(); I != E; ++I)\n      if (I->second.getNode()) {\n        std::string Label;\n        if (RetNodes.size() == 1)\n          Label = \"returning\";\n        else\n          Label = I->first->getName() + \" ret node\";\n        \/\/ Output the return node...\n        GW.emitSimpleNode((void*)1, \"plaintext=circle\", Label);\n\n        \/\/ Add edge from return node to real destination\n        int RetEdgeDest = I->second.getOffset() >> DS::PointerShift;;\n        if (RetEdgeDest == 0) RetEdgeDest = -1;\n        GW.emitEdge((void*)1, -1, I->second.getNode(),\n                    RetEdgeDest, \"arrowtail=tee,color=gray63\");\n      }\n\n    \/\/ Output all of the call nodes...\n    const std::vector &FCs =\n      G->shouldPrintAuxCalls() ? G->getAuxFunctionCalls()\n      : G->getFunctionCalls();\n    for (unsigned i = 0, e = FCs.size(); i != e; ++i) {\n      const DSCallSite &Call = FCs[i];\n      std::vector EdgeSourceCaptions(Call.getNumPtrArgs()+2);\n      EdgeSourceCaptions[0] = \"r\";\n      if (Call.isDirectCall())\n        EdgeSourceCaptions[1] = Call.getCalleeFunc()->getName();\n      else\n        EdgeSourceCaptions[1] = \"f\";\n\n      GW.emitSimpleNode(&Call, \"shape=record\", \"call\", Call.getNumPtrArgs()+2,\n                        &EdgeSourceCaptions);\n\n      if (DSNode *N = Call.getRetVal().getNode()) {\n        int EdgeDest = Call.getRetVal().getOffset() >> DS::PointerShift;\n        if (EdgeDest == 0) EdgeDest = -1;\n        GW.emitEdge(&Call, 0, N, EdgeDest, \"color=gray63,tailclip=false\");\n      }\n\n      \/\/ Print out the callee...\n      if (Call.isIndirectCall()) {\n        DSNode *N = Call.getCalleeNode();\n        assert(N && \"Null call site callee node!\");\n        GW.emitEdge(&Call, 1, N, -1, \"color=gray63,tailclip=false\");\n      }\n\n      for (unsigned j = 0, e = Call.getNumPtrArgs(); j != e; ++j)\n        if (DSNode *N = Call.getPtrArg(j).getNode()) {\n          int EdgeDest = Call.getPtrArg(j).getOffset() >> DS::PointerShift;\n          if (EdgeDest == 0) EdgeDest = -1;\n          GW.emitEdge(&Call, j+2, N, EdgeDest, \"color=gray63,tailclip=false\");\n        }\n    }\n  }\n};\n\nvoid DSNode::print(std::ostream &O, const DSGraph *G) const {\n  GraphWriter W(O, G);\n  W.writeNode(this);\n}\n\nvoid DSGraph::print(std::ostream &O) const {\n  WriteGraph(O, this, \"DataStructures\");\n}\n\nvoid DSGraph::writeGraphToFile(std::ostream &O,\n                               const std::string &GraphName) const {\n  std::string Filename = GraphName + \".dot\";\n  O << \"Writing '\" << Filename << \"'...\";\n  std::ofstream F(Filename.c_str());\n  \n  if (F.good()) {\n    print(F);\n    unsigned NumCalls = shouldPrintAuxCalls() ?\n      getAuxFunctionCalls().size() : getFunctionCalls().size();\n    O << \" [\" << getGraphSize() << \"+\" << NumCalls << \"]\\n\";\n  } else {\n    O << \"  error opening file for writing!\\n\";\n  }\n}\n\n\/\/\/ viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,\n\/\/\/ then cleanup.  For use from the debugger.\n\/\/\/\nvoid DSGraph::viewGraph() const {\n  std::ofstream F(\"\/tmp\/tempgraph.dot\");\n  if (!F.good()) {\n    std::cerr << \"Error opening '\/tmp\/tempgraph.dot' for temporary graph!\\n\";\n    return;\n  }\n  print(F);\n  F.close();\n  if (system(\"dot -Tps \/tmp\/tempgraph.dot > \/tmp\/tempgraph.ps\"))\n    std::cerr << \"Error running dot: 'dot' not in path?\\n\";\n  system(\"gv \/tmp\/tempgraph.ps\");\n  system(\"rm \/tmp\/tempgraph.dot \/tmp\/tempgraph.ps\");\n}\n\n\ntemplate \nstatic void printCollection(const Collection &C, std::ostream &O,\n                            const Module *M, const std::string &Prefix) {\n  if (M == 0) {\n    O << \"Null Module pointer, cannot continue!\\n\";\n    return;\n  }\n\n  unsigned TotalNumNodes = 0, TotalCallNodes = 0;\n  for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)\n    if (C.hasGraph(*I)) {\n      DSGraph &Gr = C.getDSGraph((Function&)*I);\n      TotalNumNodes += Gr.getGraphSize();\n      unsigned NumCalls = Gr.shouldPrintAuxCalls() ?\n        Gr.getAuxFunctionCalls().size() : Gr.getFunctionCalls().size();\n\n      TotalCallNodes += NumCalls;\n      if (I->getName() == \"main\" || !OnlyPrintMain)\n        Gr.writeGraphToFile(O, Prefix+I->getName());\n      else {\n        O << \"Skipped Writing '\" << Prefix+I->getName() << \".dot'... [\"\n          << Gr.getGraphSize() << \"+\" << NumCalls << \"]\\n\";\n      }\n\n      if (MaxGraphSize < Gr.getNodes().size())\n        MaxGraphSize = Gr.getNodes().size();\n      for (unsigned i = 0, e = Gr.getNodes().size(); i != e; ++i)\n        if (Gr.getNodes()[i]->isNodeCompletelyFolded())\n          ++NumFoldedNodes;\n    }\n\n  DSGraph &GG = C.getGlobalsGraph();\n  TotalNumNodes  += GG.getGraphSize();\n  TotalCallNodes += GG.getFunctionCalls().size();\n  if (!OnlyPrintMain) {\n    GG.writeGraphToFile(O, Prefix+\"GlobalsGraph\");\n  } else {\n    O << \"Skipped Writing '\" << Prefix << \"GlobalsGraph.dot'... [\"\n      << GG.getGraphSize() << \"+\" << GG.getFunctionCalls().size() << \"]\\n\";\n  }\n\n  O << \"\\nGraphs contain [\" << TotalNumNodes << \"+\" << TotalCallNodes \n    << \"] nodes total\" << std::endl;\n}\n\n\n\/\/ print - Print out the analysis results...\nvoid LocalDataStructures::print(std::ostream &O, const Module *M) const {\n  printCollection(*this, O, M, \"ds.\");\n}\n\nvoid BUDataStructures::print(std::ostream &O, const Module *M) const {\n  printCollection(*this, O, M, \"bu.\");\n}\n\nvoid TDDataStructures::print(std::ostream &O, const Module *M) const {\n  printCollection(*this, O, M, \"td.\");\n}\n<|endoftext|>"}
{"text":"\/\/===- TypeHashing.cpp -------------------------------------------*- C++-*-===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/DebugInfo\/CodeView\/TypeHashing.h\"\n\n#include \"llvm\/DebugInfo\/CodeView\/TypeIndexDiscovery.h\"\n#include \"llvm\/Support\/SHA1.h\"\n\nusing namespace llvm;\nusing namespace llvm::codeview;\n\nLocallyHashedType DenseMapInfo::Empty{0, {}};\nLocallyHashedType DenseMapInfo::Tombstone{hash_code(-1), {}};\n\nstatic std::array EmptyHash;\nstatic std::array TombstoneHash = {\n    0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};\n\nGloballyHashedType DenseMapInfo::Empty{EmptyHash};\nGloballyHashedType DenseMapInfo::Tombstone{TombstoneHash};\n\nLocallyHashedType LocallyHashedType::hashType(ArrayRef RecordData) {\n  return {llvm::hash_value(RecordData), RecordData};\n}\n\nGloballyHashedType\nGloballyHashedType::hashType(ArrayRef RecordData,\n                             ArrayRef PreviousTypes,\n                             ArrayRef PreviousIds) {\n  SmallVector Refs;\n  discoverTypeIndices(RecordData, Refs);\n  SHA1 S;\n  S.init();\n  uint32_t Off = 0;\n  RecordData = RecordData.drop_front(sizeof(RecordPrefix));\n  for (const auto &Ref : Refs) {\n    \/\/ Hash any data that comes before this TiRef.\n    uint32_t PreLen = Ref.Offset - Off;\n    ArrayRef PreData = RecordData.slice(Off, PreLen);\n    S.update(PreData);\n    auto Prev = (Ref.Kind == TiRefKind::IndexRef) ? PreviousIds : PreviousTypes;\n\n    auto RefData = RecordData.slice(Ref.Offset, Ref.Count * sizeof(TypeIndex));\n    \/\/ For each type index referenced, add in the previously computed hash\n    \/\/ value of that type.\n    ArrayRef Indices(\n        reinterpret_cast(RefData.data()), Ref.Count);\n    for (TypeIndex TI : Indices) {\n      ArrayRef BytesToHash;\n      if (TI.isSimple() || TI.isNoneType()) {\n        const uint8_t *IndexBytes = reinterpret_cast(&TI);\n        BytesToHash = makeArrayRef(IndexBytes, sizeof(TypeIndex));\n      } else {\n        BytesToHash = Prev[TI.toArrayIndex()].Hash;\n      }\n      S.update(BytesToHash);\n    }\n\n    Off = Ref.Offset + Ref.Count * sizeof(TypeIndex);\n  }\n\n  \/\/ Don't forget to add in any trailing bytes.\n  auto TrailingBytes = RecordData.drop_front(Off);\n  S.update(TrailingBytes);\n\n  return {S.final()};\n}\nFix -Wmissing-braces error.\/\/===- TypeHashing.cpp -------------------------------------------*- C++-*-===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/DebugInfo\/CodeView\/TypeHashing.h\"\n\n#include \"llvm\/DebugInfo\/CodeView\/TypeIndexDiscovery.h\"\n#include \"llvm\/Support\/SHA1.h\"\n\nusing namespace llvm;\nusing namespace llvm::codeview;\n\nLocallyHashedType DenseMapInfo::Empty{0, {}};\nLocallyHashedType DenseMapInfo::Tombstone{hash_code(-1), {}};\n\nstatic std::array EmptyHash;\nstatic std::array TombstoneHash = {\n    {0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};\n\nGloballyHashedType DenseMapInfo::Empty{EmptyHash};\nGloballyHashedType DenseMapInfo::Tombstone{TombstoneHash};\n\nLocallyHashedType LocallyHashedType::hashType(ArrayRef RecordData) {\n  return {llvm::hash_value(RecordData), RecordData};\n}\n\nGloballyHashedType\nGloballyHashedType::hashType(ArrayRef RecordData,\n                             ArrayRef PreviousTypes,\n                             ArrayRef PreviousIds) {\n  SmallVector Refs;\n  discoverTypeIndices(RecordData, Refs);\n  SHA1 S;\n  S.init();\n  uint32_t Off = 0;\n  RecordData = RecordData.drop_front(sizeof(RecordPrefix));\n  for (const auto &Ref : Refs) {\n    \/\/ Hash any data that comes before this TiRef.\n    uint32_t PreLen = Ref.Offset - Off;\n    ArrayRef PreData = RecordData.slice(Off, PreLen);\n    S.update(PreData);\n    auto Prev = (Ref.Kind == TiRefKind::IndexRef) ? PreviousIds : PreviousTypes;\n\n    auto RefData = RecordData.slice(Ref.Offset, Ref.Count * sizeof(TypeIndex));\n    \/\/ For each type index referenced, add in the previously computed hash\n    \/\/ value of that type.\n    ArrayRef Indices(\n        reinterpret_cast(RefData.data()), Ref.Count);\n    for (TypeIndex TI : Indices) {\n      ArrayRef BytesToHash;\n      if (TI.isSimple() || TI.isNoneType()) {\n        const uint8_t *IndexBytes = reinterpret_cast(&TI);\n        BytesToHash = makeArrayRef(IndexBytes, sizeof(TypeIndex));\n      } else {\n        BytesToHash = Prev[TI.toArrayIndex()].Hash;\n      }\n      S.update(BytesToHash);\n    }\n\n    Off = Ref.Offset + Ref.Count * sizeof(TypeIndex);\n  }\n\n  \/\/ Don't forget to add in any trailing bytes.\n  auto TrailingBytes = RecordData.drop_front(Off);\n  S.update(TrailingBytes);\n\n  return {S.final()};\n}\n<|endoftext|>"}
{"text":"\/\/===--- TypeCheckPropertyDelegate.cpp - Property Delegates ---------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements semantic analysis for property delegates.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"TypeChecker.h\"\n#include \"TypeCheckType.h\"\n#include \"swift\/AST\/ASTContext.h\"\n#include \"swift\/AST\/Decl.h\"\n#include \"swift\/AST\/DiagnosticsSema.h\"\n#include \"swift\/AST\/LazyResolver.h\"\n#include \"swift\/AST\/NameLookupRequests.h\"\n#include \"swift\/AST\/PropertyDelegates.h\"\n#include \"swift\/AST\/TypeCheckRequests.h\"\nusing namespace swift;\n\n\/\/\/ Find the named property in a property delegate to which access will\n\/\/\/ be delegated.\nstatic VarDecl *findValueProperty(ASTContext &ctx, NominalTypeDecl *nominal,\n                                  Identifier name, bool allowMissing) {\n  SmallVector vars;\n  {\n    SmallVector decls;\n    nominal->lookupQualified(nominal, name, NL_QualifiedDefault, decls);\n    for (const auto &foundDecl : decls) {\n      auto foundVar = dyn_cast(foundDecl);\n      if (!foundVar || foundVar->isStatic() ||\n          foundVar->getDeclContext() != nominal)\n        continue;\n\n      vars.push_back(foundVar);\n    }\n  }\n\n  \/\/ Diagnose missing or ambiguous properties.\n  switch (vars.size()) {\n  case 0:\n    if (!allowMissing) {\n      nominal->diagnose(diag::property_delegate_no_value_property,\n                        nominal->getDeclaredType(), name);\n    }\n    return nullptr;\n\n  case 1:\n    break;\n\n  default:\n    nominal->diagnose(diag::property_delegate_ambiguous_value_property,\n                      nominal->getDeclaredType(), name);\n    for (auto var : vars) {\n      var->diagnose(diag::kind_declname_declared_here,\n                    var->getDescriptiveKind(), var->getFullName());\n    }\n    return nullptr;\n  }\n\n  \/\/ The property must be as accessible as the nominal type.\n  VarDecl *var = vars.front();\n  if (var->getFormalAccess() < nominal->getFormalAccess()) {\n    var->diagnose(diag::property_delegate_type_requirement_not_accessible,\n                  var->getFormalAccess(), var->getDescriptiveKind(),\n                  var->getFullName(), nominal->getDeclaredType(),\n                  nominal->getFormalAccess());\n    return nullptr;\n  }\n\n  return var;\n}\n\n\/\/\/ Determine whether we have a suitable init(initialValue:) within a property\n\/\/\/ delegate type.\nstatic ConstructorDecl *findInitialValueInit(ASTContext &ctx,\n                                             NominalTypeDecl *nominal,\n                                             VarDecl *valueVar) {\n  SmallVector initialValueInitializers;\n  DeclName initName(ctx, DeclBaseName::createConstructor(),\n                    {ctx.Id_initialValue});\n  SmallVector decls;\n  nominal->lookupQualified(nominal, initName, NL_QualifiedDefault, decls);\n  for (const auto &decl : decls) {\n    auto init = dyn_cast(decl);\n    if (!init || init->getDeclContext() != nominal)\n      continue;\n\n    initialValueInitializers.push_back(init);\n  }\n\n  switch (initialValueInitializers.size()) {\n  case 0:\n    return nullptr;\n\n  case 1:\n    break;\n\n  default:\n    \/\/ Diagnose ambiguous init(initialValue:) initializers.\n    nominal->diagnose(diag::property_delegate_ambiguous_initial_value_init,\n                      nominal->getDeclaredType());\n    for (auto init : initialValueInitializers) {\n      init->diagnose(diag::kind_declname_declared_here,\n                     init->getDescriptiveKind(), init->getFullName());\n    }\n    return nullptr;\n  }\n\n  \/\/ 'init(initialValue:)' must be as accessible as the nominal type.\n  auto init = initialValueInitializers.front();\n  if (init->getFormalAccess() < nominal->getFormalAccess()) {\n    init->diagnose(diag::property_delegate_type_requirement_not_accessible,\n                     init->getFormalAccess(), init->getDescriptiveKind(),\n                     init->getFullName(), nominal->getDeclaredType(),\n                     nominal->getFormalAccess());\n    return nullptr;\n  }\n\n  \/\/ Retrieve the type of the 'value' property.\n  if (!valueVar->hasInterfaceType())\n    ctx.getLazyResolver()->resolveDeclSignature(valueVar);\n  Type valueVarType = valueVar->getValueInterfaceType();\n\n  \/\/ Retrieve the parameter type of the initializer.\n  if (!init->hasInterfaceType())\n    ctx.getLazyResolver()->resolveDeclSignature(init);\n  Type paramType;\n  if (auto *curriedInitType =\n          init->getInterfaceType()->getAs()) {\n    if (auto *initType =\n          curriedInitType->getResult()->getAs()) {\n      if (initType->getParams().size() == 1) {\n        const auto ¶m = initType->getParams()[0];\n        if (!param.isInOut() && !param.isVariadic()) {\n          paramType = param.getPlainType();\n          if (param.isAutoClosure()) {\n            if (auto *fnType = paramType->getAs())\n              paramType = fnType->getResult();\n          }\n        }\n      }\n    }\n  }\n\n  \/\/ The parameter type must be the same as the type of `valueVar` or an\n  \/\/ autoclosure thereof.\n  if (!paramType->isEqual(valueVarType)) {\n    init->diagnose(diag::property_delegate_wrong_initial_value_init, paramType,\n                   valueVarType);\n    valueVar->diagnose(diag::decl_declared_here, valueVar->getFullName());\n    return nullptr;\n  }\n\n  \/\/ The initializer must not be failable.\n  if (init->getFailability() != OTK_None) {\n    init->diagnose(diag::property_delegate_failable_init, initName);\n    return nullptr;\n  }\n\n  return init;\n}\n\n\/\/\/ Determine whether we have a suitable init() within a property\n\/\/\/ delegate type.\nstatic ConstructorDecl *findDefaultInit(ASTContext &ctx,\n                                        NominalTypeDecl *nominal) {\n  SmallVector defaultValueInitializers;\n  DeclName initName(ctx, DeclBaseName::createConstructor(),\n                    ArrayRef());\n  SmallVector decls;\n  nominal->lookupQualified(nominal, initName, NL_QualifiedDefault, decls);\n  for (const auto &decl : decls) {\n    auto init = dyn_cast(decl);\n    if (!init || init->getDeclContext() != nominal)\n      continue;\n\n    defaultValueInitializers.push_back(init);\n  }\n\n  switch (defaultValueInitializers.size()) {\n  case 0:\n    return nullptr;\n\n  case 1:\n    break;\n\n  default:\n    \/\/ Diagnose ambiguous init() initializers.\n    nominal->diagnose(diag::property_delegate_ambiguous_default_value_init,\n                      nominal->getDeclaredType());\n    for (auto init : defaultValueInitializers) {\n      init->diagnose(diag::kind_declname_declared_here,\n                     init->getDescriptiveKind(), init->getFullName());\n    }\n    return nullptr;\n  }\n\n  \/\/ 'init()' must be as accessible as the nominal type.\n  auto init = defaultValueInitializers.front();\n  if (init->getFormalAccess() < nominal->getFormalAccess()) {\n    init->diagnose(diag::property_delegate_type_requirement_not_accessible,\n                     init->getFormalAccess(), init->getDescriptiveKind(),\n                     init->getFullName(), nominal->getDeclaredType(),\n                     nominal->getFormalAccess());\n    return nullptr;\n  }\n\n  \/\/ The initializer must not be failable.\n  if (init->getFailability() != OTK_None) {\n    init->diagnose(diag::property_delegate_failable_init, initName);\n    return nullptr;\n  }\n\n  return init;\n}\n\nllvm::Expected\nPropertyDelegateTypeInfoRequest::evaluate(\n    Evaluator &eval, NominalTypeDecl *nominal) const {\n  \/\/ We must have the @_propertyDelegate attribute to continue.\n  if (!nominal->getAttrs().hasAttribute()) {\n    return PropertyDelegateTypeInfo();\n  }\n\n  \/\/ Look for a non-static property named \"value\" in the property delegate\n  \/\/ type.\n  ASTContext &ctx = nominal->getASTContext();\n  auto valueVar =\n      findValueProperty(ctx, nominal, ctx.Id_value, \/*allowMissing=*\/false);\n  if (!valueVar)\n    return PropertyDelegateTypeInfo();\n\n  PropertyDelegateTypeInfo result;\n  result.valueVar = valueVar;\n  result.initialValueInit = findInitialValueInit(ctx, nominal, valueVar);\n  result.defaultInit = findDefaultInit(ctx, nominal);\n  result.delegateValueVar =\n    findValueProperty(ctx, nominal, ctx.Id_delegateValue, \/*allowMissing=*\/true);\n\n  return result;\n}\n\nllvm::Expected\nAttachedPropertyDelegateRequest::evaluate(Evaluator &evaluator,\n                                          VarDecl *var) const {\n  ASTContext &ctx = var->getASTContext();\n  auto dc = var->getDeclContext();\n  for (auto attr : var->getAttrs().getAttributes()) {\n    auto mutableAttr = const_cast(attr);\n    \/\/ Figure out which nominal declaration this custom attribute refers to.\n    auto nominal = evaluateOrDefault(\n      ctx.evaluator, CustomAttrNominalRequest{mutableAttr, dc}, nullptr);\n\n    \/\/ If we didn't find a nominal type with a @_propertyDelegate attribute,\n    \/\/ skip this custom attribute.\n    if (!nominal || !nominal->getAttrs().hasAttribute())\n      continue;\n\n    \/\/ If the declaration came from a module file, we've already done all of\n    \/\/ the semantic checking required.\n    if (!dc->getParentSourceFile())\n      return mutableAttr;\n\n    \/\/ Check various restrictions on which properties can have delegates\n    \/\/ attached to them.\n\n    \/\/ Local properties do not yet support delegates.\n    if (var->getDeclContext()->isLocalContext()) {\n      ctx.Diags.diagnose(attr->getLocation(), diag::property_delegate_local);\n      return nullptr;\n    }\n\n    \/\/ Check that the variable is part of a single-variable pattern.\n    auto binding = var->getParentPatternBinding();\n    if (!binding || binding->getSingleVar() != var) {\n      ctx.Diags.diagnose(attr->getLocation(),\n                         diag::property_delegate_not_single_var);\n      return nullptr;\n    }\n\n    \/\/ A property delegate cannot be attached to a 'let'.\n    if (var->isLet()) {\n      ctx.Diags.diagnose(attr->getLocation(), diag::property_delegate_let);\n      return nullptr;\n    }\n\n    \/\/ Check for conflicting attributes.\n    if (var->getAttrs().hasAttribute() ||\n        var->getAttrs().hasAttribute() ||\n        var->getAttrs().hasAttribute() ||\n        (var->getAttrs().hasAttribute() &&\n         var->getAttrs().getAttribute()->get() !=\n             ReferenceOwnership::Strong)) {\n      int whichKind;\n      if (var->getAttrs().hasAttribute())\n        whichKind = 0;\n      else if (var->getAttrs().hasAttribute())\n        whichKind = 1;\n      else if (var->getAttrs().hasAttribute())\n        whichKind = 2;\n      else {\n        auto attr = var->getAttrs().getAttribute();\n        whichKind = 2 + static_cast(attr->get());\n      }\n      var->diagnose(diag::property_with_delegate_conflict_attribute,\n                    var->getFullName(), whichKind);\n      return nullptr;\n    }\n\n    \/\/ A property with a delegate cannot be declared in a protocol, enum, or\n    \/\/ an extension.\n    if (isa(dc) ||\n        (isa(dc) && var->isInstanceMember()) ||\n        (isa(dc) && var->isInstanceMember())) {\n      int whichKind;\n      if (isa(dc))\n        whichKind = 0;\n      else if (isa(dc))\n        whichKind = 1;\n      else\n        whichKind = 2;\n      var->diagnose(diag::property_with_delegate_in_bad_context,\n                    var->getFullName(), whichKind)\n        .highlight(attr->getRange());\n\n      return nullptr;\n    }\n\n    \/\/ Properties with delegates must not override another property.\n    if (auto classDecl = dyn_cast(dc)) {\n      if (auto overrideAttr = var->getAttrs().getAttribute()) {\n        var->diagnose(diag::property_with_delegate_overrides,\n                      var->getFullName())\n          .highlight(attr->getRange());\n        return nullptr;\n      }\n    }\n\n    \/\/ Properties with delegates must not declare a getter or setter.\n    if (!var->hasStorage()) {\n      ctx.Diags.diagnose(attr->getLocation(), diag::property_delegate_computed);\n      return nullptr;\n    }\n\n    return mutableAttr;\n  }\n\n  return nullptr;\n}\n\nllvm::Expected\nAttachedPropertyDelegateTypeRequest::evaluate(Evaluator &evaluator,\n                                              VarDecl *var) const {\n  \/\/ Find the custom attribute for the attached property delegate.\n  llvm::Expected customAttrVal =\n      evaluator(AttachedPropertyDelegateRequest{var});\n  if (!customAttrVal)\n    return customAttrVal.takeError();\n\n  \/\/ If there isn't an attached property delegate, we're done.\n  auto customAttr = *customAttrVal;\n  if (!customAttr)\n    return Type();\n\n  auto resolution =\n      TypeResolution::forContextual(var->getDeclContext());\n  TypeResolutionOptions options(TypeResolverContext::PatternBindingDecl);\n  options |= TypeResolutionFlags::AllowUnboundGenerics;\n\n  ASTContext &ctx = var->getASTContext();\n  auto &tc = *static_cast(ctx.getLazyResolver());\n  if (tc.validateType(customAttr->getTypeLoc(), resolution, options))\n    return ErrorType::get(ctx);\n\n  Type customAttrType = customAttr->getTypeLoc().getType();\n  if (!customAttrType->getAnyNominal()) {\n    assert(ctx.Diags.hadAnyError());\n    return ErrorType::get(ctx);\n  }\n\n  return customAttrType;\n}\n\nllvm::Expected\nPropertyDelegateBackingPropertyTypeRequest::evaluate(\n                                    Evaluator &evaluator, VarDecl *var) const {\n  llvm::Expected rawTypeResult =\n    evaluator(AttachedPropertyDelegateTypeRequest{var});\n  if (!rawTypeResult)\n    return rawTypeResult;\n\n  Type rawType = *rawTypeResult;\n  if (!rawType)\n    return Type();\n\n  if (!rawType->hasUnboundGenericType())\n    return rawType->mapTypeOutOfContext();\n\n  auto binding = var->getParentPatternBinding();\n  if (!binding)\n    return Type();\n\n  \/\/ If there's an initializer of some sort, checking it will determine the\n  \/\/ property delegate type.\n  unsigned index = binding->getPatternEntryIndexForVarDecl(var);\n  ASTContext &ctx = var->getASTContext();\n  TypeChecker &tc = *static_cast(ctx.getLazyResolver());\n  if (binding->isInitialized(index)) {\n    tc.validateDecl(var);\n    if (!binding->isInitializerChecked(index))\n      tc.typeCheckPatternBinding(binding, index);\n\n    Type type = ctx.getSideCachedPropertyDelegateBackingPropertyType(var);\n    assert(type || ctx.Diags.hadAnyError());\n    return type;\n  }\n\n  \/\/ Compose the type of property delegate with the type of the property.\n\n  \/\/ We expect an unbound generic type here that refers to a single-parameter\n  \/\/ generic type.\n  auto delegateAttr = var->getAttachedPropertyDelegate();\n  auto nominal = rawType->getAnyNominal();\n  auto unboundGeneric = rawType->getAs();\n  if (!unboundGeneric ||\n      unboundGeneric->getDecl() != nominal ||\n      !nominal->getGenericParams() ||\n      nominal->getGenericParams()->size() != 1) {\n    ctx.Diags.diagnose(delegateAttr->getLocation(),\n                       diag::property_delegate_incompatible_unbound,\n                       rawType)\n      .highlight(delegateAttr->getTypeLoc().getSourceRange());\n    return Type();\n  }\n\n  \/\/ Compute the type of the property to plug in to the delegate type.\n  tc.validateDecl(var);\n  Type propertyType = var->getType();\n\n  \/\/ Form the specialized type.\n  Type delegateType = tc.applyUnboundGenericArguments(\n      unboundGeneric, nominal, delegateAttr->getLocation(),\n      TypeResolution::forContextual(var->getDeclContext()), { propertyType });\n\n  \/\/ Make sure no unbound types remain; this could happen if there are outer\n  \/\/ unbound types that weren't resolved by the application of the property\n  \/\/ type.\n  if (delegateType->hasUnboundGenericType()) {\n    ctx.Diags.diagnose(delegateAttr->getLocation(),\n                       diag::property_delegate_incompatible_unbound,\n                       delegateType)\n      .highlight(delegateAttr->getTypeLoc().getSourceRange());\n    return Type();\n  }\n\n  return delegateType->mapTypeOutOfContext();\n}\n[SE-0258] Swift interface files have explicit get\/set for wrapped properties\/\/===--- TypeCheckPropertyDelegate.cpp - Property Delegates ---------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements semantic analysis for property delegates.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"TypeChecker.h\"\n#include \"TypeCheckType.h\"\n#include \"swift\/AST\/ASTContext.h\"\n#include \"swift\/AST\/Decl.h\"\n#include \"swift\/AST\/DiagnosticsSema.h\"\n#include \"swift\/AST\/LazyResolver.h\"\n#include \"swift\/AST\/NameLookupRequests.h\"\n#include \"swift\/AST\/PropertyDelegates.h\"\n#include \"swift\/AST\/TypeCheckRequests.h\"\nusing namespace swift;\n\n\/\/\/ Find the named property in a property delegate to which access will\n\/\/\/ be delegated.\nstatic VarDecl *findValueProperty(ASTContext &ctx, NominalTypeDecl *nominal,\n                                  Identifier name, bool allowMissing) {\n  SmallVector vars;\n  {\n    SmallVector decls;\n    nominal->lookupQualified(nominal, name, NL_QualifiedDefault, decls);\n    for (const auto &foundDecl : decls) {\n      auto foundVar = dyn_cast(foundDecl);\n      if (!foundVar || foundVar->isStatic() ||\n          foundVar->getDeclContext() != nominal)\n        continue;\n\n      vars.push_back(foundVar);\n    }\n  }\n\n  \/\/ Diagnose missing or ambiguous properties.\n  switch (vars.size()) {\n  case 0:\n    if (!allowMissing) {\n      nominal->diagnose(diag::property_delegate_no_value_property,\n                        nominal->getDeclaredType(), name);\n    }\n    return nullptr;\n\n  case 1:\n    break;\n\n  default:\n    nominal->diagnose(diag::property_delegate_ambiguous_value_property,\n                      nominal->getDeclaredType(), name);\n    for (auto var : vars) {\n      var->diagnose(diag::kind_declname_declared_here,\n                    var->getDescriptiveKind(), var->getFullName());\n    }\n    return nullptr;\n  }\n\n  \/\/ The property must be as accessible as the nominal type.\n  VarDecl *var = vars.front();\n  if (var->getFormalAccess() < nominal->getFormalAccess()) {\n    var->diagnose(diag::property_delegate_type_requirement_not_accessible,\n                  var->getFormalAccess(), var->getDescriptiveKind(),\n                  var->getFullName(), nominal->getDeclaredType(),\n                  nominal->getFormalAccess());\n    return nullptr;\n  }\n\n  return var;\n}\n\n\/\/\/ Determine whether we have a suitable init(initialValue:) within a property\n\/\/\/ delegate type.\nstatic ConstructorDecl *findInitialValueInit(ASTContext &ctx,\n                                             NominalTypeDecl *nominal,\n                                             VarDecl *valueVar) {\n  SmallVector initialValueInitializers;\n  DeclName initName(ctx, DeclBaseName::createConstructor(),\n                    {ctx.Id_initialValue});\n  SmallVector decls;\n  nominal->lookupQualified(nominal, initName, NL_QualifiedDefault, decls);\n  for (const auto &decl : decls) {\n    auto init = dyn_cast(decl);\n    if (!init || init->getDeclContext() != nominal)\n      continue;\n\n    initialValueInitializers.push_back(init);\n  }\n\n  switch (initialValueInitializers.size()) {\n  case 0:\n    return nullptr;\n\n  case 1:\n    break;\n\n  default:\n    \/\/ Diagnose ambiguous init(initialValue:) initializers.\n    nominal->diagnose(diag::property_delegate_ambiguous_initial_value_init,\n                      nominal->getDeclaredType());\n    for (auto init : initialValueInitializers) {\n      init->diagnose(diag::kind_declname_declared_here,\n                     init->getDescriptiveKind(), init->getFullName());\n    }\n    return nullptr;\n  }\n\n  \/\/ 'init(initialValue:)' must be as accessible as the nominal type.\n  auto init = initialValueInitializers.front();\n  if (init->getFormalAccess() < nominal->getFormalAccess()) {\n    init->diagnose(diag::property_delegate_type_requirement_not_accessible,\n                     init->getFormalAccess(), init->getDescriptiveKind(),\n                     init->getFullName(), nominal->getDeclaredType(),\n                     nominal->getFormalAccess());\n    return nullptr;\n  }\n\n  \/\/ Retrieve the type of the 'value' property.\n  if (!valueVar->hasInterfaceType())\n    ctx.getLazyResolver()->resolveDeclSignature(valueVar);\n  Type valueVarType = valueVar->getValueInterfaceType();\n\n  \/\/ Retrieve the parameter type of the initializer.\n  if (!init->hasInterfaceType())\n    ctx.getLazyResolver()->resolveDeclSignature(init);\n  Type paramType;\n  if (auto *curriedInitType =\n          init->getInterfaceType()->getAs()) {\n    if (auto *initType =\n          curriedInitType->getResult()->getAs()) {\n      if (initType->getParams().size() == 1) {\n        const auto ¶m = initType->getParams()[0];\n        if (!param.isInOut() && !param.isVariadic()) {\n          paramType = param.getPlainType();\n          if (param.isAutoClosure()) {\n            if (auto *fnType = paramType->getAs())\n              paramType = fnType->getResult();\n          }\n        }\n      }\n    }\n  }\n\n  \/\/ The parameter type must be the same as the type of `valueVar` or an\n  \/\/ autoclosure thereof.\n  if (!paramType->isEqual(valueVarType)) {\n    init->diagnose(diag::property_delegate_wrong_initial_value_init, paramType,\n                   valueVarType);\n    valueVar->diagnose(diag::decl_declared_here, valueVar->getFullName());\n    return nullptr;\n  }\n\n  \/\/ The initializer must not be failable.\n  if (init->getFailability() != OTK_None) {\n    init->diagnose(diag::property_delegate_failable_init, initName);\n    return nullptr;\n  }\n\n  return init;\n}\n\n\/\/\/ Determine whether we have a suitable init() within a property\n\/\/\/ delegate type.\nstatic ConstructorDecl *findDefaultInit(ASTContext &ctx,\n                                        NominalTypeDecl *nominal) {\n  SmallVector defaultValueInitializers;\n  DeclName initName(ctx, DeclBaseName::createConstructor(),\n                    ArrayRef());\n  SmallVector decls;\n  nominal->lookupQualified(nominal, initName, NL_QualifiedDefault, decls);\n  for (const auto &decl : decls) {\n    auto init = dyn_cast(decl);\n    if (!init || init->getDeclContext() != nominal)\n      continue;\n\n    defaultValueInitializers.push_back(init);\n  }\n\n  switch (defaultValueInitializers.size()) {\n  case 0:\n    return nullptr;\n\n  case 1:\n    break;\n\n  default:\n    \/\/ Diagnose ambiguous init() initializers.\n    nominal->diagnose(diag::property_delegate_ambiguous_default_value_init,\n                      nominal->getDeclaredType());\n    for (auto init : defaultValueInitializers) {\n      init->diagnose(diag::kind_declname_declared_here,\n                     init->getDescriptiveKind(), init->getFullName());\n    }\n    return nullptr;\n  }\n\n  \/\/ 'init()' must be as accessible as the nominal type.\n  auto init = defaultValueInitializers.front();\n  if (init->getFormalAccess() < nominal->getFormalAccess()) {\n    init->diagnose(diag::property_delegate_type_requirement_not_accessible,\n                     init->getFormalAccess(), init->getDescriptiveKind(),\n                     init->getFullName(), nominal->getDeclaredType(),\n                     nominal->getFormalAccess());\n    return nullptr;\n  }\n\n  \/\/ The initializer must not be failable.\n  if (init->getFailability() != OTK_None) {\n    init->diagnose(diag::property_delegate_failable_init, initName);\n    return nullptr;\n  }\n\n  return init;\n}\n\nllvm::Expected\nPropertyDelegateTypeInfoRequest::evaluate(\n    Evaluator &eval, NominalTypeDecl *nominal) const {\n  \/\/ We must have the @_propertyDelegate attribute to continue.\n  if (!nominal->getAttrs().hasAttribute()) {\n    return PropertyDelegateTypeInfo();\n  }\n\n  \/\/ Look for a non-static property named \"value\" in the property delegate\n  \/\/ type.\n  ASTContext &ctx = nominal->getASTContext();\n  auto valueVar =\n      findValueProperty(ctx, nominal, ctx.Id_value, \/*allowMissing=*\/false);\n  if (!valueVar)\n    return PropertyDelegateTypeInfo();\n\n  PropertyDelegateTypeInfo result;\n  result.valueVar = valueVar;\n  result.initialValueInit = findInitialValueInit(ctx, nominal, valueVar);\n  result.defaultInit = findDefaultInit(ctx, nominal);\n  result.delegateValueVar =\n    findValueProperty(ctx, nominal, ctx.Id_delegateValue, \/*allowMissing=*\/true);\n\n  return result;\n}\n\nllvm::Expected\nAttachedPropertyDelegateRequest::evaluate(Evaluator &evaluator,\n                                          VarDecl *var) const {\n  ASTContext &ctx = var->getASTContext();\n  auto dc = var->getDeclContext();\n  for (auto attr : var->getAttrs().getAttributes()) {\n    auto mutableAttr = const_cast(attr);\n    \/\/ Figure out which nominal declaration this custom attribute refers to.\n    auto nominal = evaluateOrDefault(\n      ctx.evaluator, CustomAttrNominalRequest{mutableAttr, dc}, nullptr);\n\n    \/\/ If we didn't find a nominal type with a @_propertyDelegate attribute,\n    \/\/ skip this custom attribute.\n    if (!nominal || !nominal->getAttrs().hasAttribute())\n      continue;\n\n    \/\/ If the declaration came from a module file, we've already done all of\n    \/\/ the semantic checking required.\n    auto sourceFile = dc->getParentSourceFile();\n    if (!sourceFile)\n      return mutableAttr;\n\n    \/\/ Check various restrictions on which properties can have delegates\n    \/\/ attached to them.\n\n    \/\/ Local properties do not yet support delegates.\n    if (var->getDeclContext()->isLocalContext()) {\n      ctx.Diags.diagnose(attr->getLocation(), diag::property_delegate_local);\n      return nullptr;\n    }\n\n    \/\/ Check that the variable is part of a single-variable pattern.\n    auto binding = var->getParentPatternBinding();\n    if (!binding || binding->getSingleVar() != var) {\n      ctx.Diags.diagnose(attr->getLocation(),\n                         diag::property_delegate_not_single_var);\n      return nullptr;\n    }\n\n    \/\/ A property delegate cannot be attached to a 'let'.\n    if (var->isLet()) {\n      ctx.Diags.diagnose(attr->getLocation(), diag::property_delegate_let);\n      return nullptr;\n    }\n\n    \/\/ Check for conflicting attributes.\n    if (var->getAttrs().hasAttribute() ||\n        var->getAttrs().hasAttribute() ||\n        var->getAttrs().hasAttribute() ||\n        (var->getAttrs().hasAttribute() &&\n         var->getAttrs().getAttribute()->get() !=\n             ReferenceOwnership::Strong)) {\n      int whichKind;\n      if (var->getAttrs().hasAttribute())\n        whichKind = 0;\n      else if (var->getAttrs().hasAttribute())\n        whichKind = 1;\n      else if (var->getAttrs().hasAttribute())\n        whichKind = 2;\n      else {\n        auto attr = var->getAttrs().getAttribute();\n        whichKind = 2 + static_cast(attr->get());\n      }\n      var->diagnose(diag::property_with_delegate_conflict_attribute,\n                    var->getFullName(), whichKind);\n      return nullptr;\n    }\n\n    \/\/ A property with a delegate cannot be declared in a protocol, enum, or\n    \/\/ an extension.\n    if (isa(dc) ||\n        (isa(dc) && var->isInstanceMember()) ||\n        (isa(dc) && var->isInstanceMember())) {\n      int whichKind;\n      if (isa(dc))\n        whichKind = 0;\n      else if (isa(dc))\n        whichKind = 1;\n      else\n        whichKind = 2;\n      var->diagnose(diag::property_with_delegate_in_bad_context,\n                    var->getFullName(), whichKind)\n        .highlight(attr->getRange());\n\n      return nullptr;\n    }\n\n    \/\/ Properties with delegates must not override another property.\n    if (auto classDecl = dyn_cast(dc)) {\n      if (auto overrideAttr = var->getAttrs().getAttribute()) {\n        var->diagnose(diag::property_with_delegate_overrides,\n                      var->getFullName())\n          .highlight(attr->getRange());\n        return nullptr;\n      }\n    }\n\n    \/\/ Properties with delegates must not declare a getter or setter.\n    if (!var->hasStorage() && sourceFile->Kind != SourceFileKind::Interface) {\n      ctx.Diags.diagnose(attr->getLocation(), diag::property_delegate_computed);\n      return nullptr;\n    }\n\n    return mutableAttr;\n  }\n\n  return nullptr;\n}\n\nllvm::Expected\nAttachedPropertyDelegateTypeRequest::evaluate(Evaluator &evaluator,\n                                              VarDecl *var) const {\n  \/\/ Find the custom attribute for the attached property delegate.\n  llvm::Expected customAttrVal =\n      evaluator(AttachedPropertyDelegateRequest{var});\n  if (!customAttrVal)\n    return customAttrVal.takeError();\n\n  \/\/ If there isn't an attached property delegate, we're done.\n  auto customAttr = *customAttrVal;\n  if (!customAttr)\n    return Type();\n\n  auto resolution =\n      TypeResolution::forContextual(var->getDeclContext());\n  TypeResolutionOptions options(TypeResolverContext::PatternBindingDecl);\n  options |= TypeResolutionFlags::AllowUnboundGenerics;\n\n  ASTContext &ctx = var->getASTContext();\n  auto &tc = *static_cast(ctx.getLazyResolver());\n  if (tc.validateType(customAttr->getTypeLoc(), resolution, options))\n    return ErrorType::get(ctx);\n\n  Type customAttrType = customAttr->getTypeLoc().getType();\n  if (!customAttrType->getAnyNominal()) {\n    assert(ctx.Diags.hadAnyError());\n    return ErrorType::get(ctx);\n  }\n\n  return customAttrType;\n}\n\nllvm::Expected\nPropertyDelegateBackingPropertyTypeRequest::evaluate(\n                                    Evaluator &evaluator, VarDecl *var) const {\n  llvm::Expected rawTypeResult =\n    evaluator(AttachedPropertyDelegateTypeRequest{var});\n  if (!rawTypeResult)\n    return rawTypeResult;\n\n  Type rawType = *rawTypeResult;\n  if (!rawType)\n    return Type();\n\n  if (!rawType->hasUnboundGenericType())\n    return rawType->mapTypeOutOfContext();\n\n  auto binding = var->getParentPatternBinding();\n  if (!binding)\n    return Type();\n\n  \/\/ If there's an initializer of some sort, checking it will determine the\n  \/\/ property delegate type.\n  unsigned index = binding->getPatternEntryIndexForVarDecl(var);\n  ASTContext &ctx = var->getASTContext();\n  TypeChecker &tc = *static_cast(ctx.getLazyResolver());\n  if (binding->isInitialized(index)) {\n    tc.validateDecl(var);\n    if (!binding->isInitializerChecked(index))\n      tc.typeCheckPatternBinding(binding, index);\n\n    Type type = ctx.getSideCachedPropertyDelegateBackingPropertyType(var);\n    assert(type || ctx.Diags.hadAnyError());\n    return type;\n  }\n\n  \/\/ Compose the type of property delegate with the type of the property.\n\n  \/\/ We expect an unbound generic type here that refers to a single-parameter\n  \/\/ generic type.\n  auto delegateAttr = var->getAttachedPropertyDelegate();\n  auto nominal = rawType->getAnyNominal();\n  auto unboundGeneric = rawType->getAs();\n  if (!unboundGeneric ||\n      unboundGeneric->getDecl() != nominal ||\n      !nominal->getGenericParams() ||\n      nominal->getGenericParams()->size() != 1) {\n    ctx.Diags.diagnose(delegateAttr->getLocation(),\n                       diag::property_delegate_incompatible_unbound,\n                       rawType)\n      .highlight(delegateAttr->getTypeLoc().getSourceRange());\n    return Type();\n  }\n\n  \/\/ Compute the type of the property to plug in to the delegate type.\n  tc.validateDecl(var);\n  Type propertyType = var->getType();\n\n  \/\/ Form the specialized type.\n  Type delegateType = tc.applyUnboundGenericArguments(\n      unboundGeneric, nominal, delegateAttr->getLocation(),\n      TypeResolution::forContextual(var->getDeclContext()), { propertyType });\n\n  \/\/ Make sure no unbound types remain; this could happen if there are outer\n  \/\/ unbound types that weren't resolved by the application of the property\n  \/\/ type.\n  if (delegateType->hasUnboundGenericType()) {\n    ctx.Diags.diagnose(delegateAttr->getLocation(),\n                       diag::property_delegate_incompatible_unbound,\n                       delegateType)\n      .highlight(delegateAttr->getTypeLoc().getSourceRange());\n    return Type();\n  }\n\n  return delegateType->mapTypeOutOfContext();\n}\n<|endoftext|>"}
{"text":"#include \"gui\/window.hpp\"\n\n#include \n\nnamespace qrw\n{\n\tWindow::Window()\n\t{\n\t}\n\n\tWindow::~Window()\n\t{\n\t}\n\n\tvoid Window::setVisible(bool visible)\n\t{\n\t\tthis->visible = visible;\n\t\tfor(std::vector::iterator iter = children.begin(); iter != children.end(); ++iter)\n\t\t{\n\t\t\t(*iter)->setVisible(visible);\n\t\t}\n\t}\n\n\tbool Window::isVisible()\n\t{\n\t\treturn visible;\n\t}\n\n\tvoid Window::addWidget(Widget* widget)\n\t{\n\t\tchildren.push_back(widget);\n\t}\n\n\tvoid Window::draw(sf::RenderTarget& target, sf::RenderStates states) const\n\t{\n\t\tif(!visible)\n\t\t\treturn;\n\n\t\tfor(auto iter = children.begin(); iter != children.end(); ++iter)\n\t\t\ttarget.draw(*(*iter), states);\n\t}\n\n\tvoid Window::handleEvent(const sf::Event& event)\n\t{\n\t\tif(visible)\n\t\t{\n\t\t\tfor(auto iter = children.begin(); iter != children.end(); ++iter)\n\t\t\t\t(*iter)->handleEvent(event);\n\t\t}\n\t}\n}Improved code readability in Window::draw().#include \"gui\/window.hpp\"\n\n#include \n\nnamespace qrw\n{\n\tWindow::Window()\n\t{\n\t}\n\n\tWindow::~Window()\n\t{\n\t}\n\n\tvoid Window::setVisible(bool visible)\n\t{\n\t\tthis->visible = visible;\n\t\tfor(std::vector::iterator iter = children.begin(); iter != children.end(); ++iter)\n\t\t{\n\t\t\t(*iter)->setVisible(visible);\n\t\t}\n\t}\n\n\tbool Window::isVisible()\n\t{\n\t\treturn visible;\n\t}\n\n\tvoid Window::addWidget(Widget* widget)\n\t{\n\t\tchildren.push_back(widget);\n\t}\n\n\tvoid Window::draw(sf::RenderTarget& target, sf::RenderStates states) const\n\t{\n\t\tif(visible)\n\t\t{\n\t\t\tfor(auto iter = children.begin(); iter != children.end(); ++iter)\n\t\t\t\ttarget.draw(*(*iter), states);\n\t\t}\n\t}\n\n\tvoid Window::handleEvent(const sf::Event& event)\n\t{\n\t\tif(visible)\n\t\t{\n\t\t\tfor(auto iter = children.begin(); iter != children.end(); ++iter)\n\t\t\t\t(*iter)->handleEvent(event);\n\t\t}\n\t}\n}<|endoftext|>"}
{"text":"#include \n#include \n\n#include \"os\/task_t.h\"\n#include \"os\/task_system_t.h\"\n#include \"os\/parse.h\"\n#include \"lib\/io.h\"\n\nint main(){\n\tstd::cout << \"Hello world!\" << std::endl;\n\n\t{\n\t\tos::task_t task;\n\t\tstd::cout << task << std::endl;\n\t}\n\n\t{\n\t\tos::task_system_t task_system(5);\n\t\tstd::cout << task_system << std::endl;\n\t}\n\n\t{\n\t\tstd::ifstream ifs(\"system\/0\", std::ifstream::in);\n\t\tchar c = ifs.get();\n\t\twhile (ifs.good()){\n\t\t\tstd::cout << c;\n\t\t\tc = ifs.get();\n\t\t}\n\t\tifs.close();\n\t\tstd::cout << '\\n';\n\t}\n\n\t{\n\t\tos::task_system_t task_system;\n\t\tstd::cout << task_system << std::endl;\n\n\t\tstd::ifstream ifs(\"system\/0\", std::ifstream::in);\n\t\tos::parse_task_system_stream(ifs, task_system);\n\t\tifs.close();\n\t\t\n\t\tstd::cout << task_system << std::endl;\n\t}\n\treturn 0;\n}include generator (no syntax error)#include \n#include \n\n#include \"os\/task_t.h\"\n#include \"os\/task_system_t.h\"\n#include \"os\/parse.h\"\n#include \"os\/generator.h\"\n#include \"lib\/io.h\"\n\nint main(){\n\tstd::cout << \"Hello world!\" << std::endl;\n\n\t{\n\t\tos::task_t task;\n\t\tstd::cout << task << std::endl;\n\t}\n\n\t{\n\t\tos::task_system_t task_system(5);\n\t\tstd::cout << task_system << std::endl;\n\t}\n\n\t{\n\t\tstd::ifstream ifs(\"system\/0\", std::ifstream::in);\n\t\tchar c = ifs.get();\n\t\twhile (ifs.good()){\n\t\t\tstd::cout << c;\n\t\t\tc = ifs.get();\n\t\t}\n\t\tifs.close();\n\t\tstd::cout << '\\n';\n\t}\n\n\t{\n\t\tos::task_system_t task_system;\n\t\tstd::cout << task_system << std::endl;\n\n\t\tstd::ifstream ifs(\"system\/0\", std::ifstream::in);\n\t\tos::parse_task_system_stream(ifs, task_system);\n\t\tifs.close();\n\t\t\n\t\tstd::cout << task_system << std::endl;\n\t}\n\treturn 0;\n}<|endoftext|>"}
{"text":"#ifndef __RANK_FILTER__\n#define __RANK_FILTER__\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\ntemplate ::type* = nullptr>\ninline void lineRankOrderFilter(const vigra::MultiArrayView & src,\n                                vigra::MultiArrayView dest,\n                                unsigned long half_length, double rank)\n{\n    \/\/ Will ignore boundaries initially.\n    \/\/ Then will try adding reflection.\n\n    \/\/ Rank must be in the range 0 to 1\n    assert((0 <= rank) && (rank <= 1));\n\n    const int rank_pos = round(rank * (2*half_length));\n\n    \/\/ The position of the\n    typename vigra::MultiArrayView::difference_type_1 window_begin(0);\n    std::multiset sorted_window;\n    std::list< typename std::multiset::iterator > window_iters;\n\n    \/\/ Get the initial sorted window.\n    \/\/ Include the reflection.\n    for (typename vigra::MultiArrayView::difference_type_1 j(half_length); j > 0; j--)\n    {\n        window_iters.push_back(sorted_window.insert(src[window_begin + j]));\n    }\n    for (typename vigra::MultiArrayView::difference_type_1 j(0); j <= half_length; j++)\n    {\n        window_iters.push_back(sorted_window.insert(src[window_begin + j]));\n    }\n\n    typename std::multiset::iterator rank_point = sorted_window.begin();\n\n    for (int i = 0; i < rank_pos; i++)\n    {\n        rank_point++;\n    }\n\n    while ( window_begin < src.size() )\n    {\n        dest[window_begin] = *rank_point;\n\n        typename std::multiset::iterator prev_iter(window_iters.front());\n        T1 prev_value = *prev_iter;\n        window_iters.pop_front();\n\n        window_begin++;\n\n        T1 next_value;\n        if ( window_begin < (src.size() - half_length) )\n        {\n            next_value = src[window_begin + half_length];\n        }\n        else\n        {\n            next_value = src[2 * src.size() - (window_begin + half_length + 2)];\n        }\n\n        if ( ( *rank_point < *prev_iter ) && ( *rank_point <= next_value ) )\n        {\n            sorted_window.erase(prev_iter);\n            window_iters.push_back(sorted_window.insert(next_value));\n        }\n        else if ( ( *rank_point >= *prev_iter ) && ( *rank_point > next_value ) )\n        {\n            if ( rank_point == prev_iter )\n            {\n                window_iters.push_back(sorted_window.insert(next_value));\n                rank_point--;\n\n                sorted_window.erase(prev_iter);\n            }\n            else\n            {\n                sorted_window.erase(prev_iter);\n                window_iters.push_back(sorted_window.insert(next_value));\n            }\n        }\n        else if ( ( *rank_point < *prev_iter ) && ( *rank_point > next_value ) )\n        {\n            sorted_window.erase(prev_iter);\n            window_iters.push_back(sorted_window.insert(next_value));\n\n            rank_point--;\n        }\n        else if ( ( *rank_point >= *prev_iter ) && ( *rank_point <= next_value ) )\n        {\n            if (rank_point == prev_iter)\n            {\n                window_iters.push_back(sorted_window.insert(next_value));\n                rank_point++;\n\n                sorted_window.erase(prev_iter);\n            }\n            else\n            {\n                sorted_window.erase(prev_iter);\n                window_iters.push_back(sorted_window.insert(next_value));\n\n                rank_point++;\n            }\n        }\n    }\n}\n\ntemplate  1)>::type* = nullptr>\ninline void lineRankOrderFilter(const vigra::MultiArrayView & src,\n                                vigra::MultiArrayView dest,\n                                unsigned long half_length, double rank, unsigned int axis = N - 1)\n{\n    typename vigra::MultiArrayView::difference_type transposed_axes;\n\n    for (unsigned int i = 0; i < N; i++)\n    {\n        transposed_axes[i] = i;\n    }\n\n    std::swap(transposed_axes[N - 1], transposed_axes[axis]);\n\n    vigra::MultiArray src_transposed(src.transpose(transposed_axes));\n\n    vigra::MultiArrayView dest_transposed_view(dest.transpose(transposed_axes));\n\n\n    typename vigra::MultiArrayView::difference_type pos;\n    pos = 0;\n\n    bool done = false;\n\n    while (!done)\n    {\n        lineRankOrderFilter(src_transposed.bindInner(pos), dest_transposed_view.bindInner(pos), half_length, rank);\n\n        bool carry = true;\n        for (unsigned int i = 0; ( carry && (i < N) ); i++)\n        {\n            if ( (++pos[N - (i + 1)]) < src.shape()[N - (i + 1)])\n            {\n                carry = false;\n            }\n            else\n            {\n                pos[N - (i + 1)] = 0;\n                carry = true;\n            }\n        }\n\n        done = !carry;\n    }\n}\n\n\n#endif \/\/__RANK_FILTER__\nrank_filter.hxx: Added more spaces to clear up confusion.#ifndef __RANK_FILTER__\n#define __RANK_FILTER__\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\ntemplate ::type* = nullptr>\ninline void lineRankOrderFilter(const vigra::MultiArrayView & src,\n                                vigra::MultiArrayView dest,\n                                unsigned long half_length, double rank)\n{\n    \/\/ Will ignore boundaries initially.\n    \/\/ Then will try adding reflection.\n\n    \/\/ Rank must be in the range 0 to 1\n    assert((0 <= rank) && (rank <= 1));\n\n    const int rank_pos = round(rank * (2 * half_length));\n\n    \/\/ The position of the\n    typename vigra::MultiArrayView::difference_type_1 window_begin(0);\n    std::multiset sorted_window;\n    std::list< typename std::multiset::iterator > window_iters;\n\n    \/\/ Get the initial sorted window.\n    \/\/ Include the reflection.\n    for (typename vigra::MultiArrayView::difference_type_1 j(half_length); j > 0; j--)\n    {\n        window_iters.push_back(sorted_window.insert(src[window_begin + j]));\n    }\n    for (typename vigra::MultiArrayView::difference_type_1 j(0); j <= half_length; j++)\n    {\n        window_iters.push_back(sorted_window.insert(src[window_begin + j]));\n    }\n\n    typename std::multiset::iterator rank_point = sorted_window.begin();\n\n    for (int i = 0; i < rank_pos; i++)\n    {\n        rank_point++;\n    }\n\n    while ( window_begin < src.size() )\n    {\n        dest[window_begin] = *rank_point;\n\n        typename std::multiset::iterator prev_iter(window_iters.front());\n        T1 prev_value = *prev_iter;\n        window_iters.pop_front();\n\n        window_begin++;\n\n        T1 next_value;\n        if ( window_begin < (src.size() - half_length) )\n        {\n            next_value = src[window_begin + half_length];\n        }\n        else\n        {\n            next_value = src[2 * src.size() - (window_begin + half_length + 2)];\n        }\n\n        if ( ( *rank_point < *prev_iter ) && ( *rank_point <= next_value ) )\n        {\n            sorted_window.erase(prev_iter);\n            window_iters.push_back(sorted_window.insert(next_value));\n        }\n        else if ( ( *rank_point >= *prev_iter ) && ( *rank_point > next_value ) )\n        {\n            if ( rank_point == prev_iter )\n            {\n                window_iters.push_back(sorted_window.insert(next_value));\n                rank_point--;\n\n                sorted_window.erase(prev_iter);\n            }\n            else\n            {\n                sorted_window.erase(prev_iter);\n                window_iters.push_back(sorted_window.insert(next_value));\n            }\n        }\n        else if ( ( *rank_point < *prev_iter ) && ( *rank_point > next_value ) )\n        {\n            sorted_window.erase(prev_iter);\n            window_iters.push_back(sorted_window.insert(next_value));\n\n            rank_point--;\n        }\n        else if ( ( *rank_point >= *prev_iter ) && ( *rank_point <= next_value ) )\n        {\n            if (rank_point == prev_iter)\n            {\n                window_iters.push_back(sorted_window.insert(next_value));\n                rank_point++;\n\n                sorted_window.erase(prev_iter);\n            }\n            else\n            {\n                sorted_window.erase(prev_iter);\n                window_iters.push_back(sorted_window.insert(next_value));\n\n                rank_point++;\n            }\n        }\n    }\n}\n\ntemplate  1)>::type* = nullptr>\ninline void lineRankOrderFilter(const vigra::MultiArrayView & src,\n                                vigra::MultiArrayView dest,\n                                unsigned long half_length, double rank, unsigned int axis = N - 1)\n{\n    typename vigra::MultiArrayView::difference_type transposed_axes;\n\n    for (unsigned int i = 0; i < N; i++)\n    {\n        transposed_axes[i] = i;\n    }\n\n    std::swap(transposed_axes[N - 1], transposed_axes[axis]);\n\n    vigra::MultiArray src_transposed(src.transpose(transposed_axes));\n\n    vigra::MultiArrayView dest_transposed_view(dest.transpose(transposed_axes));\n\n\n    typename vigra::MultiArrayView::difference_type pos;\n    pos = 0;\n\n    bool done = false;\n\n    while (!done)\n    {\n        lineRankOrderFilter(src_transposed.bindInner(pos), dest_transposed_view.bindInner(pos), half_length, rank);\n\n        bool carry = true;\n        for (unsigned int i = 0; ( carry && (i < N) ); i++)\n        {\n            if ( (++pos[N - (i + 1)]) < src.shape()[N - (i + 1)])\n            {\n                carry = false;\n            }\n            else\n            {\n                pos[N - (i + 1)] = 0;\n                carry = true;\n            }\n        }\n\n        done = !carry;\n    }\n}\n\n\n#endif \/\/__RANK_FILTER__\n<|endoftext|>"}
{"text":"\/\/===-- RISCVISelDAGToDAG.cpp - A dag to dag inst selector for RISCV ------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines an instruction selector for the RISCV target.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"RISCV.h\"\n#include \"MCTargetDesc\/RISCVMCTargetDesc.h\"\n#include \"RISCVTargetMachine.h\"\n#include \"llvm\/CodeGen\/MachineFrameInfo.h\"\n#include \"llvm\/CodeGen\/SelectionDAGISel.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace llvm;\n\n#define DEBUG_TYPE \"riscv-isel\"\n\n\/\/ RISCV-specific code to select RISCV machine instructions for\n\/\/ SelectionDAG operations.\nnamespace {\nclass RISCVDAGToDAGISel final : public SelectionDAGISel {\n  const RISCVSubtarget *Subtarget;\n\npublic:\n  explicit RISCVDAGToDAGISel(RISCVTargetMachine &TargetMachine)\n      : SelectionDAGISel(TargetMachine) {}\n\n  StringRef getPassName() const override {\n    return \"RISCV DAG->DAG Pattern Instruction Selection\";\n  }\n\n  bool runOnMachineFunction(MachineFunction &MF) override {\n    Subtarget = &MF.getSubtarget();\n    return SelectionDAGISel::runOnMachineFunction(MF);\n  }\n\n  void PostprocessISelDAG() override;\n\n  void Select(SDNode *Node) override;\n\n  bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,\n                                    std::vector &OutOps) override;\n\n  bool SelectAddrFI(SDValue Addr, SDValue &Base);\n\n\/\/ Include the pieces autogenerated from the target description.\n#include \"RISCVGenDAGISel.inc\"\n\nprivate:\n  void doPeepholeLoadStoreADDI();\n  void doPeepholeBuildPairF64SplitF64();\n};\n}\n\nvoid RISCVDAGToDAGISel::PostprocessISelDAG() {\n  doPeepholeLoadStoreADDI();\n  doPeepholeBuildPairF64SplitF64();\n}\n\nvoid RISCVDAGToDAGISel::Select(SDNode *Node) {\n  unsigned Opcode = Node->getOpcode();\n  MVT XLenVT = Subtarget->getXLenVT();\n\n  \/\/ If we have a custom node, we have already selected\n  if (Node->isMachineOpcode()) {\n    LLVM_DEBUG(dbgs() << \"== \"; Node->dump(CurDAG); dbgs() << \"\\n\");\n    Node->setNodeId(-1);\n    return;\n  }\n\n  \/\/ Instruction Selection not handled by the auto-generated tablegen selection\n  \/\/ should be handled here.\n  EVT VT = Node->getValueType(0);\n  if (Opcode == ISD::Constant && VT == XLenVT) {\n    auto *ConstNode = cast(Node);\n    \/\/ Materialize zero constants as copies from X0. This allows the coalescer\n    \/\/ to propagate these into other instructions.\n    if (ConstNode->isNullValue()) {\n      SDValue New = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), SDLoc(Node),\n                                           RISCV::X0, XLenVT);\n      ReplaceNode(Node, New.getNode());\n      return;\n    }\n  }\n  if (Opcode == ISD::FrameIndex) {\n    SDLoc DL(Node);\n    SDValue Imm = CurDAG->getTargetConstant(0, DL, XLenVT);\n    int FI = cast(Node)->getIndex();\n    EVT VT = Node->getValueType(0);\n    SDValue TFI = CurDAG->getTargetFrameIndex(FI, VT);\n    ReplaceNode(Node, CurDAG->getMachineNode(RISCV::ADDI, DL, VT, TFI, Imm));\n    return;\n  }\n\n  \/\/ Select the default instruction.\n  SelectCode(Node);\n}\n\nbool RISCVDAGToDAGISel::SelectInlineAsmMemoryOperand(\n    const SDValue &Op, unsigned ConstraintID, std::vector &OutOps) {\n  switch (ConstraintID) {\n  case InlineAsm::Constraint_i:\n  case InlineAsm::Constraint_m:\n    \/\/ We just support simple memory operands that have a single address\n    \/\/ operand and need no special handling.\n    OutOps.push_back(Op);\n    return false;\n  default:\n    break;\n  }\n\n  return true;\n}\n\nbool RISCVDAGToDAGISel::SelectAddrFI(SDValue Addr, SDValue &Base) {\n  if (auto FIN = dyn_cast(Addr)) {\n    Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), Subtarget->getXLenVT());\n    return true;\n  }\n  return false;\n}\n\n\/\/ Merge an ADDI into the offset of a load\/store instruction where possible.\n\/\/ (load (add base, off), 0) -> (load base, off)\n\/\/ (store val, (add base, off)) -> (store val, base, off)\nvoid RISCVDAGToDAGISel::doPeepholeLoadStoreADDI() {\n  SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());\n  ++Position;\n\n  while (Position != CurDAG->allnodes_begin()) {\n    SDNode *N = &*--Position;\n    \/\/ Skip dead nodes and any non-machine opcodes.\n    if (N->use_empty() || !N->isMachineOpcode())\n      continue;\n\n    int OffsetOpIdx;\n    int BaseOpIdx;\n\n    \/\/ Only attempt this optimisation for I-type loads and S-type stores.\n    switch (N->getMachineOpcode()) {\n    default:\n      continue;\n    case RISCV::LB:\n    case RISCV::LH:\n    case RISCV::LW:\n    case RISCV::LBU:\n    case RISCV::LHU:\n    case RISCV::LWU:\n    case RISCV::LD:\n    case RISCV::FLW:\n    case RISCV::FLD:\n      BaseOpIdx = 0;\n      OffsetOpIdx = 1;\n      break;\n    case RISCV::SB:\n    case RISCV::SH:\n    case RISCV::SW:\n    case RISCV::SD:\n    case RISCV::FSW:\n    case RISCV::FSD:\n      BaseOpIdx = 1;\n      OffsetOpIdx = 2;\n      break;\n    }\n\n    \/\/ Currently, the load\/store offset must be 0 to be considered for this\n    \/\/ peephole optimisation.\n    if (!isa(N->getOperand(OffsetOpIdx)) ||\n        N->getConstantOperandVal(OffsetOpIdx) != 0)\n      continue;\n\n    SDValue Base = N->getOperand(BaseOpIdx);\n\n    \/\/ If the base is an ADDI, we can merge it in to the load\/store.\n    if (!Base.isMachineOpcode() || Base.getMachineOpcode() != RISCV::ADDI)\n      continue;\n\n    SDValue ImmOperand = Base.getOperand(1);\n\n    if (auto Const = dyn_cast(ImmOperand)) {\n      ImmOperand = CurDAG->getTargetConstant(\n          Const->getSExtValue(), SDLoc(ImmOperand), ImmOperand.getValueType());\n    } else if (auto GA = dyn_cast(ImmOperand)) {\n      ImmOperand = CurDAG->getTargetGlobalAddress(\n          GA->getGlobal(), SDLoc(ImmOperand), ImmOperand.getValueType(),\n          GA->getOffset(), GA->getTargetFlags());\n    } else {\n      continue;\n    }\n\n    LLVM_DEBUG(dbgs() << \"Folding add-immediate into mem-op:\\nBase:    \");\n    LLVM_DEBUG(Base->dump(CurDAG));\n    LLVM_DEBUG(dbgs() << \"\\nN: \");\n    LLVM_DEBUG(N->dump(CurDAG));\n    LLVM_DEBUG(dbgs() << \"\\n\");\n\n    \/\/ Modify the offset operand of the load\/store.\n    if (BaseOpIdx == 0) \/\/ Load\n      CurDAG->UpdateNodeOperands(N, Base.getOperand(0), ImmOperand,\n                                 N->getOperand(2));\n    else \/\/ Store\n      CurDAG->UpdateNodeOperands(N, N->getOperand(0), Base.getOperand(0),\n                                 ImmOperand, N->getOperand(3));\n\n    \/\/ The add-immediate may now be dead, in which case remove it.\n    if (Base.getNode()->use_empty())\n      CurDAG->RemoveDeadNode(Base.getNode());\n  }\n}\n\n\/\/ Remove redundant BuildPairF64+SplitF64 pairs. i.e. cases where an f64 is\n\/\/ built of two i32 values, only to be split apart again. This must be done\n\/\/ here as a peephole optimisation as the DAG has not been fully legalized at\n\/\/ the point BuildPairF64\/SplitF64 nodes are created in RISCVISelLowering, so\n\/\/ some nodes would not yet have been replaced with libcalls.\nvoid RISCVDAGToDAGISel::doPeepholeBuildPairF64SplitF64() {\n  SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());\n  ++Position;\n\n  while (Position != CurDAG->allnodes_begin()) {\n    SDNode *N = &*--Position;\n    \/\/ Skip dead nodes and any nodes other than SplitF64Pseudo.\n    if (N->use_empty() || !N->isMachineOpcode() ||\n        !(N->getMachineOpcode() == RISCV::SplitF64Pseudo))\n      continue;\n\n    \/\/ If the operand to SplitF64 is a BuildPairF64, the split operation is\n    \/\/ redundant. Just use the operands to BuildPairF64 as the result.\n    SDValue F64Val = N->getOperand(0);\n    if (F64Val.isMachineOpcode() &&\n        F64Val.getMachineOpcode() == RISCV::BuildPairF64Pseudo) {\n      LLVM_DEBUG(\n          dbgs() << \"Removing redundant SplitF64Pseudo and replacing uses \"\n                    \"with BuildPairF64Pseudo operands:\\n\");\n      LLVM_DEBUG(dbgs() << \"N:    \");\n      LLVM_DEBUG(N->dump(CurDAG));\n      LLVM_DEBUG(dbgs() << \"F64Val: \");\n      LLVM_DEBUG(F64Val->dump(CurDAG));\n      LLVM_DEBUG(dbgs() << \"\\n\");\n      SDValue From[] = {SDValue(N, 0), SDValue(N, 1)};\n      SDValue To[] = {F64Val.getOperand(0), F64Val.getOperand(1)};\n      CurDAG->ReplaceAllUsesOfValuesWith(From, To, 2);\n    }\n  }\n  CurDAG->RemoveDeadNodes();\n}\n\n\/\/ This pass converts a legalized DAG into a RISCV-specific DAG, ready\n\/\/ for instruction scheduling.\nFunctionPass *llvm::createRISCVISelDag(RISCVTargetMachine &TM) {\n  return new RISCVDAGToDAGISel(TM);\n}\n[RISCV][NFC] Refactor RISCVDAGToDAGISel::Select\/\/===-- RISCVISelDAGToDAG.cpp - A dag to dag inst selector for RISCV ------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines an instruction selector for the RISCV target.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"RISCV.h\"\n#include \"MCTargetDesc\/RISCVMCTargetDesc.h\"\n#include \"RISCVTargetMachine.h\"\n#include \"llvm\/CodeGen\/MachineFrameInfo.h\"\n#include \"llvm\/CodeGen\/SelectionDAGISel.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace llvm;\n\n#define DEBUG_TYPE \"riscv-isel\"\n\n\/\/ RISCV-specific code to select RISCV machine instructions for\n\/\/ SelectionDAG operations.\nnamespace {\nclass RISCVDAGToDAGISel final : public SelectionDAGISel {\n  const RISCVSubtarget *Subtarget;\n\npublic:\n  explicit RISCVDAGToDAGISel(RISCVTargetMachine &TargetMachine)\n      : SelectionDAGISel(TargetMachine) {}\n\n  StringRef getPassName() const override {\n    return \"RISCV DAG->DAG Pattern Instruction Selection\";\n  }\n\n  bool runOnMachineFunction(MachineFunction &MF) override {\n    Subtarget = &MF.getSubtarget();\n    return SelectionDAGISel::runOnMachineFunction(MF);\n  }\n\n  void PostprocessISelDAG() override;\n\n  void Select(SDNode *Node) override;\n\n  bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,\n                                    std::vector &OutOps) override;\n\n  bool SelectAddrFI(SDValue Addr, SDValue &Base);\n\n\/\/ Include the pieces autogenerated from the target description.\n#include \"RISCVGenDAGISel.inc\"\n\nprivate:\n  void doPeepholeLoadStoreADDI();\n  void doPeepholeBuildPairF64SplitF64();\n};\n}\n\nvoid RISCVDAGToDAGISel::PostprocessISelDAG() {\n  doPeepholeLoadStoreADDI();\n  doPeepholeBuildPairF64SplitF64();\n}\n\nvoid RISCVDAGToDAGISel::Select(SDNode *Node) {\n  \/\/ If we have a custom node, we have already selected.\n  if (Node->isMachineOpcode()) {\n    LLVM_DEBUG(dbgs() << \"== \"; Node->dump(CurDAG); dbgs() << \"\\n\");\n    Node->setNodeId(-1);\n    return;\n  }\n\n  \/\/ Instruction Selection not handled by the auto-generated tablegen selection\n  \/\/ should be handled here.\n  unsigned Opcode = Node->getOpcode();\n  MVT XLenVT = Subtarget->getXLenVT();\n  SDLoc DL(Node);\n  EVT VT = Node->getValueType(0);\n\n  switch (Opcode) {\n  case ISD::Constant: {\n    auto ConstNode = cast(Node);\n    if (VT == XLenVT && ConstNode->isNullValue()) {\n      SDValue New = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), SDLoc(Node),\n                                           RISCV::X0, XLenVT);\n      ReplaceNode(Node, New.getNode());\n      return;\n    }\n    break;\n  }\n  case ISD::FrameIndex: {\n    SDValue Imm = CurDAG->getTargetConstant(0, DL, XLenVT);\n    int FI = cast(Node)->getIndex();\n    SDValue TFI = CurDAG->getTargetFrameIndex(FI, VT);\n    ReplaceNode(Node, CurDAG->getMachineNode(RISCV::ADDI, DL, VT, TFI, Imm));\n    return;\n  }\n  }\n\n  \/\/ Select the default instruction.\n  SelectCode(Node);\n}\n\nbool RISCVDAGToDAGISel::SelectInlineAsmMemoryOperand(\n    const SDValue &Op, unsigned ConstraintID, std::vector &OutOps) {\n  switch (ConstraintID) {\n  case InlineAsm::Constraint_i:\n  case InlineAsm::Constraint_m:\n    \/\/ We just support simple memory operands that have a single address\n    \/\/ operand and need no special handling.\n    OutOps.push_back(Op);\n    return false;\n  default:\n    break;\n  }\n\n  return true;\n}\n\nbool RISCVDAGToDAGISel::SelectAddrFI(SDValue Addr, SDValue &Base) {\n  if (auto FIN = dyn_cast(Addr)) {\n    Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), Subtarget->getXLenVT());\n    return true;\n  }\n  return false;\n}\n\n\/\/ Merge an ADDI into the offset of a load\/store instruction where possible.\n\/\/ (load (add base, off), 0) -> (load base, off)\n\/\/ (store val, (add base, off)) -> (store val, base, off)\nvoid RISCVDAGToDAGISel::doPeepholeLoadStoreADDI() {\n  SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());\n  ++Position;\n\n  while (Position != CurDAG->allnodes_begin()) {\n    SDNode *N = &*--Position;\n    \/\/ Skip dead nodes and any non-machine opcodes.\n    if (N->use_empty() || !N->isMachineOpcode())\n      continue;\n\n    int OffsetOpIdx;\n    int BaseOpIdx;\n\n    \/\/ Only attempt this optimisation for I-type loads and S-type stores.\n    switch (N->getMachineOpcode()) {\n    default:\n      continue;\n    case RISCV::LB:\n    case RISCV::LH:\n    case RISCV::LW:\n    case RISCV::LBU:\n    case RISCV::LHU:\n    case RISCV::LWU:\n    case RISCV::LD:\n    case RISCV::FLW:\n    case RISCV::FLD:\n      BaseOpIdx = 0;\n      OffsetOpIdx = 1;\n      break;\n    case RISCV::SB:\n    case RISCV::SH:\n    case RISCV::SW:\n    case RISCV::SD:\n    case RISCV::FSW:\n    case RISCV::FSD:\n      BaseOpIdx = 1;\n      OffsetOpIdx = 2;\n      break;\n    }\n\n    \/\/ Currently, the load\/store offset must be 0 to be considered for this\n    \/\/ peephole optimisation.\n    if (!isa(N->getOperand(OffsetOpIdx)) ||\n        N->getConstantOperandVal(OffsetOpIdx) != 0)\n      continue;\n\n    SDValue Base = N->getOperand(BaseOpIdx);\n\n    \/\/ If the base is an ADDI, we can merge it in to the load\/store.\n    if (!Base.isMachineOpcode() || Base.getMachineOpcode() != RISCV::ADDI)\n      continue;\n\n    SDValue ImmOperand = Base.getOperand(1);\n\n    if (auto Const = dyn_cast(ImmOperand)) {\n      ImmOperand = CurDAG->getTargetConstant(\n          Const->getSExtValue(), SDLoc(ImmOperand), ImmOperand.getValueType());\n    } else if (auto GA = dyn_cast(ImmOperand)) {\n      ImmOperand = CurDAG->getTargetGlobalAddress(\n          GA->getGlobal(), SDLoc(ImmOperand), ImmOperand.getValueType(),\n          GA->getOffset(), GA->getTargetFlags());\n    } else {\n      continue;\n    }\n\n    LLVM_DEBUG(dbgs() << \"Folding add-immediate into mem-op:\\nBase:    \");\n    LLVM_DEBUG(Base->dump(CurDAG));\n    LLVM_DEBUG(dbgs() << \"\\nN: \");\n    LLVM_DEBUG(N->dump(CurDAG));\n    LLVM_DEBUG(dbgs() << \"\\n\");\n\n    \/\/ Modify the offset operand of the load\/store.\n    if (BaseOpIdx == 0) \/\/ Load\n      CurDAG->UpdateNodeOperands(N, Base.getOperand(0), ImmOperand,\n                                 N->getOperand(2));\n    else \/\/ Store\n      CurDAG->UpdateNodeOperands(N, N->getOperand(0), Base.getOperand(0),\n                                 ImmOperand, N->getOperand(3));\n\n    \/\/ The add-immediate may now be dead, in which case remove it.\n    if (Base.getNode()->use_empty())\n      CurDAG->RemoveDeadNode(Base.getNode());\n  }\n}\n\n\/\/ Remove redundant BuildPairF64+SplitF64 pairs. i.e. cases where an f64 is\n\/\/ built of two i32 values, only to be split apart again. This must be done\n\/\/ here as a peephole optimisation as the DAG has not been fully legalized at\n\/\/ the point BuildPairF64\/SplitF64 nodes are created in RISCVISelLowering, so\n\/\/ some nodes would not yet have been replaced with libcalls.\nvoid RISCVDAGToDAGISel::doPeepholeBuildPairF64SplitF64() {\n  SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());\n  ++Position;\n\n  while (Position != CurDAG->allnodes_begin()) {\n    SDNode *N = &*--Position;\n    \/\/ Skip dead nodes and any nodes other than SplitF64Pseudo.\n    if (N->use_empty() || !N->isMachineOpcode() ||\n        !(N->getMachineOpcode() == RISCV::SplitF64Pseudo))\n      continue;\n\n    \/\/ If the operand to SplitF64 is a BuildPairF64, the split operation is\n    \/\/ redundant. Just use the operands to BuildPairF64 as the result.\n    SDValue F64Val = N->getOperand(0);\n    if (F64Val.isMachineOpcode() &&\n        F64Val.getMachineOpcode() == RISCV::BuildPairF64Pseudo) {\n      LLVM_DEBUG(\n          dbgs() << \"Removing redundant SplitF64Pseudo and replacing uses \"\n                    \"with BuildPairF64Pseudo operands:\\n\");\n      LLVM_DEBUG(dbgs() << \"N:    \");\n      LLVM_DEBUG(N->dump(CurDAG));\n      LLVM_DEBUG(dbgs() << \"F64Val: \");\n      LLVM_DEBUG(F64Val->dump(CurDAG));\n      LLVM_DEBUG(dbgs() << \"\\n\");\n      SDValue From[] = {SDValue(N, 0), SDValue(N, 1)};\n      SDValue To[] = {F64Val.getOperand(0), F64Val.getOperand(1)};\n      CurDAG->ReplaceAllUsesOfValuesWith(From, To, 2);\n    }\n  }\n  CurDAG->RemoveDeadNodes();\n}\n\n\/\/ This pass converts a legalized DAG into a RISCV-specific DAG, ready\n\/\/ for instruction scheduling.\nFunctionPass *llvm::createRISCVISelDag(RISCVTargetMachine &TM) {\n  return new RISCVDAGToDAGISel(TM);\n}\n<|endoftext|>"}
{"text":"\/\/\n\/\/  inpalprime.hpp\n\/\/  InPal \n\/\/\n\/\/  Created by Bryan Triana on 6\/21\/16.\n\/\/  Copyright © 2016 Inverse Palindrome. All rights reserved.\n\/\/\n\n\n#ifndef inpalprime_hpp\n#define inpalprime_hpp\n\n#include \n#include \n\n\nclass inpalprime\n{\n\npublic:\n    unsigned long long pn_find(unsigned long long n);\n    unsigned long long pn_count(unsigned long long n);\n    long double pn_den(long double h);\n    bool pn_test(unsigned long long a);\n    bool pn_twin(unsigned long long a);\n    bool pn_cousin(unsigned long long a);\n    bool pn_sexy(unsigned long long a);\n    unsigned long long pn_pal(unsigned long long n);\n    unsigned long long n_fac(unsigned long long f);\n    unsigned long long n_cfac(unsigned long long f);\n\nprivate:\n    std::vector atkinsieve(unsigned long long m);\n    std::vector factorizer(unsigned long long f);\n    bool pal_test(unsigned long long n);\n    unsigned long long maxprime=0;\n    unsigned long long primecount=0;\n    long double primeden;\n    unsigned long long pal;\n    std::string ull;\n    unsigned long long maxfac;\n    unsigned long long cfac;\n    \n};\n\n\n#endif \/* inpalprime_hpp *\/\nUpdate inpalprime.hpp\/\/\n\/\/  inpalprime.hpp\n\/\/  InPal \n\/\/\n\/\/  Created by Bryan Triana on 6\/21\/16.\n\/\/  Copyright © 2016 Inverse Palindrome. All rights reserved.\n\/\/\n\n\n#ifndef inpalprime_hpp\n#define inpalprime_hpp\n\n#include \n#include \n\n\nclass inpalprime\n{\n    \npublic:\n    long long pn_find(long long n);\n    long long pn_count(long long n);\n    long double pn_den(long double h);\n    bool pn_test(long long a);\n    bool pn_twin(long long a);\n    bool pn_cousin(long long a);\n    bool pn_sexy(long long a);\n    long long pn_pal(long long n);\n    long long n_fac(long long f);\n    long long n_cfac(long long f);\n  \nprivate:\n    std::vector atkinsieve(long long m);\n    std::vector factorizer(long long f);\n    bool pal_test(long long n);\n    long long maxprime=0;\n    long long primecount;\n    long double primeden;\n    long long pal;\n    std::string ull;\n    long long maxfac;\n    long long cfac;\n    \n};\n\n\n#endif \/* inpalprime_hpp *\/\n<|endoftext|>"}
{"text":"\/*****************************************************************************\\\n *                        ANALYSIS PERFORMANCE TOOLS                         *\n *                                  wxparaver                                *\n *              Paraver Trace Visualization and Analysis Tool                *\n *****************************************************************************\n *     ___     This library is free software; you can redistribute it and\/or *\n *    \/  __         modify it under the terms of the GNU LGPL as published   *\n *   \/  \/  _____    by the Free Software Foundation; either version 2.1      *\n *  \/  \/  \/     \\   of the License, or (at your option) any later version.   *\n * (  (  ( B S C )                                                           *\n *  \\  \\  \\_____\/   This library is distributed in hope that it will be      *\n *   \\  \\__         useful but WITHOUT ANY WARRANTY; without even the        *\n *    \\___          implied warranty of MERCHANTABILITY or FITNESS FOR A     *\n *                  PARTICULAR PURPOSE. See the GNU LGPL for more details.   *\n *                                                                           *\n * You should have received a copy of the GNU Lesser General Public License  *\n * along with this library; if not, write to the Free Software Foundation,   *\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA          *\n * The GNU LEsser General Public License is contained in the file COPYING.   *\n *                                 ---------                                 *\n *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *\n\\*****************************************************************************\/\n\n\/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\\\n | @file: $HeadURL$\n | @last_commit: $Date$\n | @version:     $Revision$\n\\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\/\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include \"wx\/wx.h\"\n#endif\n\n#include \n#include \n#include \"sequencedriver.h\"\n#include \"kernelconnection.h\"\n#include \"gtimeline.h\"\n#include \"traceeditsequence.h\"\n#include \"traceeditstates.h\"\n#include \"traceoptions.h\"\n#include \"runscript.h\"\n#include \"wxparaverapp.h\"\n\n\/****************************************************************************\n ********             RunAppClusteringAction                         ********\n ****************************************************************************\/\nvector RunAppClusteringAction::getStateDependencies() const\n{\n  vector tmpStates;\n  return tmpStates;\n}\n\nvoid RunAppClusteringAction::execute( std::string whichTrace )\n{\n  TraceEditSequence *tmpSequence = (TraceEditSequence *)mySequence;\n  std::string tmpFileName = ( (CSVFileNameState *)tmpSequence->getState( TraceEditSequence::csvFileNameState ) )->getData();\n  RunScript runAppDialog( wxparaverApp::mainWindow, wxString::FromAscii( whichTrace.c_str() ) );\n  runAppDialog.setClustering( wxString::FromAscii( tmpFileName.c_str() ) );\n\n  if( runAppDialog.ShowModal() == wxID_OK )\n  {}\n}\n\n\n\/****************************************************************************\n ********                 SequenceDriver                             ********\n ****************************************************************************\/\nvoid SequenceDriver::sequenceClustering( gTimeline *whichTimeline )\n{\n  KernelConnection *myKernel =  whichTimeline->GetMyWindow()->getKernel();\n  TraceEditSequence *mySequence = TraceEditSequence::create( myKernel );\n\n  mySequence->pushbackAction( TraceEditSequence::traceCutterAction );\n  mySequence->pushbackAction( TraceEditSequence::csvOutputAction );\n  mySequence->pushbackAction( new RunAppClusteringAction( mySequence ) );\n  \n  TraceOptions *tmpOptions = TraceOptions::create( myKernel );\n  tmpOptions->set_by_time( true );\n  tmpOptions->set_min_cutting_time( whichTimeline->GetMyWindow()->getWindowBeginTime() );\n  tmpOptions->set_max_cutting_time( whichTimeline->GetMyWindow()->getWindowEndTime() );\n  tmpOptions->set_original_time( true );\n  tmpOptions->set_break_states( false );\n\n  TraceOptionsState *tmpOptionsState = new TraceOptionsState( mySequence );\n  tmpOptionsState->setData( tmpOptions );\n  mySequence->addState( TraceEditSequence::traceOptionsState, tmpOptionsState );\n  \n  TextOutput output;\n  output.setObjectHierarchy( true );\n  output.setWindowTimeUnits( false );\n  CSVOutputState *tmpOutputState = new CSVOutputState( mySequence );\n  tmpOutputState->setData( output );\n  mySequence->addState( TraceEditSequence::csvOutputState, tmpOutputState );\n  \n  CSVWindowState *tmpWindowState = new CSVWindowState( mySequence );\n  tmpWindowState->setData( whichTimeline->GetMyWindow() );\n  mySequence->addState( TraceEditSequence::csvWindowState, tmpWindowState );\n\n  CSVFileNameState *tmpCSVFilenameState = new CSVFileNameState( mySequence );\n  std::string tmpFileName;\n  wxFileName tmpTraceName( wxString::FromAscii( whichTimeline->GetMyWindow()->getTrace()->getFileName().c_str() ) );\n  tmpTraceName.ClearExt();\n  tmpTraceName.AppendDir( wxString::FromAscii( TraceEditSequence::dirNameClustering.c_str() ) );\n  \n  if( !tmpTraceName.DirExists() )\n    tmpTraceName.Mkdir();\n  std::string auxName = whichTimeline->GetMyWindow()->getName() + \"_\";\n  tmpFileName = std::string( tmpTraceName.GetPath( wxPATH_GET_SEPARATOR ).mb_str() ) + auxName.c_str() + std::string( tmpTraceName.GetFullName().mb_str() ) + std::string( \".csv\" );\n\n  tmpCSVFilenameState->setData( tmpFileName );\n  mySequence->addState( TraceEditSequence::csvFileNameState, tmpCSVFilenameState );\n  \n  vector traces;\n  traces.push_back( whichTimeline->GetMyWindow()->getTrace()->getFileName() );\n  mySequence->execute( traces );\n  \n  delete mySequence;\n}\n*** empty log message ***\/*****************************************************************************\\\n *                        ANALYSIS PERFORMANCE TOOLS                         *\n *                                  wxparaver                                *\n *              Paraver Trace Visualization and Analysis Tool                *\n *****************************************************************************\n *     ___     This library is free software; you can redistribute it and\/or *\n *    \/  __         modify it under the terms of the GNU LGPL as published   *\n *   \/  \/  _____    by the Free Software Foundation; either version 2.1      *\n *  \/  \/  \/     \\   of the License, or (at your option) any later version.   *\n * (  (  ( B S C )                                                           *\n *  \\  \\  \\_____\/   This library is distributed in hope that it will be      *\n *   \\  \\__         useful but WITHOUT ANY WARRANTY; without even the        *\n *    \\___          implied warranty of MERCHANTABILITY or FITNESS FOR A     *\n *                  PARTICULAR PURPOSE. See the GNU LGPL for more details.   *\n *                                                                           *\n * You should have received a copy of the GNU Lesser General Public License  *\n * along with this library; if not, write to the Free Software Foundation,   *\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA          *\n * The GNU LEsser General Public License is contained in the file COPYING.   *\n *                                 ---------                                 *\n *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *\n\\*****************************************************************************\/\n\n\/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\\\n | @file: $HeadURL$\n | @last_commit: $Date$\n | @version:     $Revision$\n\\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\/\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include \"wx\/wx.h\"\n#endif\n\n#include \n#include \n#include \"sequencedriver.h\"\n#include \"kernelconnection.h\"\n#include \"gtimeline.h\"\n#include \"traceeditsequence.h\"\n#include \"traceeditstates.h\"\n#include \"traceoptions.h\"\n#include \"runscript.h\"\n#include \"wxparaverapp.h\"\n\n\/****************************************************************************\n ********             RunAppClusteringAction                         ********\n ****************************************************************************\/\nvector RunAppClusteringAction::getStateDependencies() const\n{\n  vector tmpStates;\n  return tmpStates;\n}\n\nvoid RunAppClusteringAction::execute( std::string whichTrace )\n{\n  TraceEditSequence *tmpSequence = (TraceEditSequence *)mySequence;\n  std::string tmpFileName = ( (CSVFileNameState *)tmpSequence->getState( TraceEditSequence::csvFileNameState ) )->getData();\n  RunScript runAppDialog( wxparaverApp::mainWindow, wxString::FromAscii( whichTrace.c_str() ) );\n  runAppDialog.setClustering( wxString::FromAscii( tmpFileName.c_str() ) );\n\n  if( runAppDialog.ShowModal() == wxID_OK )\n  {}\n}\n\n\n\/****************************************************************************\n ********                 SequenceDriver                             ********\n ****************************************************************************\/\nvoid SequenceDriver::sequenceClustering( gTimeline *whichTimeline )\n{\n  KernelConnection *myKernel =  whichTimeline->GetMyWindow()->getKernel();\n  TraceEditSequence *mySequence = TraceEditSequence::create( myKernel );\n\n  mySequence->pushbackAction( TraceEditSequence::traceCutterAction );\n  mySequence->pushbackAction( TraceEditSequence::csvOutputAction );\n  mySequence->pushbackAction( new RunAppClusteringAction( mySequence ) );\n  \n  TraceOptions *tmpOptions = TraceOptions::create( myKernel );\n  tmpOptions->set_by_time( true );\n  tmpOptions->set_min_cutting_time( whichTimeline->GetMyWindow()->getWindowBeginTime() );\n  tmpOptions->set_max_cutting_time( whichTimeline->GetMyWindow()->getWindowEndTime() );\n  tmpOptions->set_original_time( false );\n  tmpOptions->set_break_states( false );\n\n  TraceOptionsState *tmpOptionsState = new TraceOptionsState( mySequence );\n  tmpOptionsState->setData( tmpOptions );\n  mySequence->addState( TraceEditSequence::traceOptionsState, tmpOptionsState );\n  \n  TextOutput output;\n  output.setObjectHierarchy( true );\n  output.setWindowTimeUnits( false );\n  CSVOutputState *tmpOutputState = new CSVOutputState( mySequence );\n  tmpOutputState->setData( output );\n  mySequence->addState( TraceEditSequence::csvOutputState, tmpOutputState );\n  \n  CSVWindowState *tmpWindowState = new CSVWindowState( mySequence );\n  tmpWindowState->setData( whichTimeline->GetMyWindow() );\n  mySequence->addState( TraceEditSequence::csvWindowState, tmpWindowState );\n\n  CSVFileNameState *tmpCSVFilenameState = new CSVFileNameState( mySequence );\n  std::string tmpFileName;\n  wxFileName tmpTraceName( wxString::FromAscii( whichTimeline->GetMyWindow()->getTrace()->getFileName().c_str() ) );\n  tmpTraceName.ClearExt();\n  tmpTraceName.AppendDir( wxString::FromAscii( TraceEditSequence::dirNameClustering.c_str() ) );\n  \n  if( !tmpTraceName.DirExists() )\n    tmpTraceName.Mkdir();\n  std::string auxName = whichTimeline->GetMyWindow()->getName() + \"_\";\n  tmpFileName = std::string( tmpTraceName.GetPath( wxPATH_GET_SEPARATOR ).mb_str() ) + auxName.c_str() + std::string( tmpTraceName.GetFullName().mb_str() ) + std::string( \".csv\" );\n\n  tmpCSVFilenameState->setData( tmpFileName );\n  mySequence->addState( TraceEditSequence::csvFileNameState, tmpCSVFilenameState );\n  \n  vector traces;\n  traces.push_back( whichTimeline->GetMyWindow()->getTrace()->getFileName() );\n  mySequence->execute( traces );\n  \n  delete mySequence;\n}\n<|endoftext|>"}
{"text":"\/**********************************************************************************\n\n Infomap software package for multi-level network clustering\n\n Copyright (c) 2013, 2014 Daniel Edler, Martin Rosvall\n\n For more information, see \n\n\n This file is part of Infomap software package.\n\n Infomap software package is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n Infomap software package is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with Infomap software package.  If not, see .\n\n**********************************************************************************\/\n\n\n#include \"version.h\"\n\n#ifdef NS_INFOMAP\nnamespace infomap\n{\n#endif\n\nconst char* INFOMAP_VERSION = \"0.18.7\";\n\n#ifdef NS_INFOMAP\n}\n#endif\nPatch version\/**********************************************************************************\n\n Infomap software package for multi-level network clustering\n\n Copyright (c) 2013, 2014 Daniel Edler, Martin Rosvall\n\n For more information, see \n\n\n This file is part of Infomap software package.\n\n Infomap software package is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n Infomap software package is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with Infomap software package.  If not, see .\n\n**********************************************************************************\/\n\n\n#include \"version.h\"\n\n#ifdef NS_INFOMAP\nnamespace infomap\n{\n#endif\n\nconst char* INFOMAP_VERSION = \"0.18.8\";\n\n#ifdef NS_INFOMAP\n}\n#endif\n<|endoftext|>"}
{"text":"#include \"layers\/lsh.h\"\n#include \"3rd_party\/faiss\/IndexLSH.h\"\n#include \"graph\/expression_operators.h\"\n#include \"tensors\/cpu\/prod_blas.h\"\n\nnamespace marian {\n\nExpr LSH::apply(Expr input, Expr W, Expr b) {\n  auto idx = search(input, W);\n  return affine(idx, input, W, b);\n}\n\nExpr LSH::search(Expr query, Expr values) {\n  ABORT_IF(query->graph()->getDeviceId().type == DeviceType::gpu,\n           \"LSH index (--output-approx-knn) currently not implemented for GPU\");\n\n  auto kShape = query->shape();\n  kShape.set(-1, k_);\n\n  auto forward = [this](Expr out, const std::vector& inputs) {\n    auto query  = inputs[0];\n    auto values = inputs[1];\n\n    int dim = values->shape()[-1];\n\n    if(!index_ || indexHash_ != values->hash()) {\n      LOG(info, \"Building LSH index for vector dim {} and with hash size {} bits\", dim, nbits_);\n      index_.reset(new faiss::IndexLSH(dim, nbits_, \n                                       \/*rotate=*\/dim != nbits_, \n                                       \/*train_thesholds*\/false));\n      int vRows = values->shape().elements() \/ dim;\n      index_->train(vRows, values->val()->data());\n      index_->add(  vRows, values->val()->data());\n      indexHash_ = values->hash();\n    }\n\n    int qRows = query->shape().elements() \/ dim;\n    std::vector distances(qRows * k_);\n    std::vector ids(qRows * k_);\n\n    index_->search(qRows, query->val()->data(), k_,\n                   distances.data(), ids.data());\n    \n    std::vector vOut;\n    vOut.reserve(ids.size());\n    for(auto id : ids)\n      vOut.push_back((IndexType)id);\n\n    out->val()->set(vOut);\n  };\n\n  return lambda({query, values}, kShape, Type::uint32, forward);\n}\n\nExpr LSH::affine(Expr idx, Expr input, Expr W, Expr b) {\n  auto outShape = input->shape();\n  int dimVoc    = W->shape()[-2];\n  outShape.set(-1, dimVoc);\n\n  auto forward = [this](Expr out, const std::vector& inputs) {\n    auto lowest = NumericLimits(out->value_type()).lowest;\n    out->val()->set(lowest);\n\n    int dimIn   = inputs[1]->shape()[-1];\n    int dimOut  = out->shape()[-1];\n    int dimRows = out->shape().elements() \/ dimOut;\n    \n    auto outPtr   = out->val()->data();\n    auto idxPtr   = inputs[0]->val()->data();\n    auto queryPtr = inputs[1]->val()->data();\n    auto WPtr     = inputs[2]->val()->data();\n    auto bPtr     = inputs.size() > 3 ? inputs[3]->val()->data() : nullptr; \/\/ nullptr if no bias given\n\n    for(int row = 0; row < dimRows; ++row) {\n      auto currIdxPtr    = idxPtr   + row * k_;     \/\/ move to next batch of k entries\n      auto currQueryPtr  = queryPtr + row * dimIn;  \/\/ move to next input query vector\n      auto currOutPtr    = outPtr   + row * dimOut; \/\/ move to next output position vector (of vocabulary size)\n      for(int k = 0; k < k_; k++) {\n        int relPos = currIdxPtr[k];                   \/\/ k-th best vocabulay item\n        auto currWPtr      = WPtr + relPos * dimIn;   \/\/ offset for k-th best embedding\n        currOutPtr[relPos] = bPtr ? bPtr[relPos] : 0; \/\/ write bias value to position, init to 0 if no bias given\n        \n        \/\/ proceed one vector product at a time writing to the correct position\n        sgemm(false, true, 1, 1, dimIn, 1.0f, currQueryPtr, dimIn, currWPtr, dimIn, 1.0f, &currOutPtr[relPos], 1);\n      }\n    }\n  };\n\n  std::vector nodes = {idx, input, W};\n  if(b) \/\/ bias is optional\n    nodes.push_back(b);\n\n  return lambda(nodes, \n                outShape,\n                input->value_type(),\n                forward);\n}\n\n\/\/ @TODO: alternative version which does the same as above with Marian operators, currently missing \"scatter\".\n\/\/ this uses more memory and likely to be slower. Would make sense to have a scatter node that actually creates\n\/\/ the node instead of relying on an existing node, e.g. scatter(shape, defaultValue, axis, indices, values);\n#if 0 \nExpr LSH::affine(Expr idx, Expr input, Expr W, Expr b) {\n  int dim  = input->shape()[-1];\n  int bch  = idx->shape().elements() \/ k;\n\n  auto W = reshape(rows(Wt_, flatten(idx)), {bch, k, dim}); \/\/ [rows, k, dim]\n  auto b = reshape(cols(b_,  flatten(idx)), {bch, 1,   k}); \/\/ [rows, 1,   k]\n\n  auto aff = reshape(bdot(reshape(input, {bch, 1, dim}), W, false, true) + b, idx->shape()); \/\/ [beam, time, batch, k]\n\n  int dimVoc  = Wt_->shape()[-2];\n  auto oShape = input->shape();\n  oShape.set(-1, dimVoc);\n  auto lowest = graph_->constant(oShape, \n                                 inits::fromValue(NumericLimits(input->value_type()).lowest), \n                                 input->value_type());\n  return scatter(lowest, -1, idx, aff);\n}\n#endif\n\n}  \/\/ namespace marianfix compilation with -DCOMPILE_CPU=off#include \"layers\/lsh.h\"\n#include \"graph\/expression_operators.h\"\n#include \"tensors\/cpu\/prod_blas.h\"\n\n#if BLAS_FOUND\n#include \"3rd_party\/faiss\/IndexLSH.h\"\n#endif\n\nnamespace marian {\n\nExpr LSH::apply(Expr input, Expr W, Expr b) {\n  auto idx = search(input, W);\n  return affine(idx, input, W, b);\n}\n\nExpr LSH::search(Expr query, Expr values) {\n#if BLAS_FOUND\n  ABORT_IF(query->graph()->getDeviceId().type == DeviceType::gpu,\n           \"LSH index (--output-approx-knn) currently not implemented for GPU\");\n\n  auto kShape = query->shape();\n  kShape.set(-1, k_);\n\n  auto forward = [this](Expr out, const std::vector& inputs) {\n    auto query  = inputs[0];\n    auto values = inputs[1];\n\n    int dim = values->shape()[-1];\n\n    if(!index_ || indexHash_ != values->hash()) {\n      LOG(info, \"Building LSH index for vector dim {} and with hash size {} bits\", dim, nbits_);\n      index_.reset(new faiss::IndexLSH(dim, nbits_, \n                                       \/*rotate=*\/dim != nbits_, \n                                       \/*train_thesholds*\/false));\n      int vRows = values->shape().elements() \/ dim;\n      index_->train(vRows, values->val()->data());\n      index_->add(  vRows, values->val()->data());\n      indexHash_ = values->hash();\n    }\n\n    int qRows = query->shape().elements() \/ dim;\n    std::vector distances(qRows * k_);\n    std::vector ids(qRows * k_);\n\n    index_->search(qRows, query->val()->data(), k_,\n                   distances.data(), ids.data());\n    \n    std::vector vOut;\n    vOut.reserve(ids.size());\n    for(auto id : ids)\n      vOut.push_back((IndexType)id);\n\n    out->val()->set(vOut);\n  };\n\n  return lambda({query, values}, kShape, Type::uint32, forward);\n#else\n  query; values;\n  ABORT(\"LSH output layer requires a CPU BLAS library\");\n#endif\n}\n\nExpr LSH::affine(Expr idx, Expr input, Expr W, Expr b) {\n  auto outShape = input->shape();\n  int dimVoc    = W->shape()[-2];\n  outShape.set(-1, dimVoc);\n\n  auto forward = [this](Expr out, const std::vector& inputs) {\n    auto lowest = NumericLimits(out->value_type()).lowest;\n    out->val()->set(lowest);\n\n    int dimIn   = inputs[1]->shape()[-1];\n    int dimOut  = out->shape()[-1];\n    int dimRows = out->shape().elements() \/ dimOut;\n    \n    auto outPtr   = out->val()->data();\n    auto idxPtr   = inputs[0]->val()->data();\n    auto queryPtr = inputs[1]->val()->data();\n    auto WPtr     = inputs[2]->val()->data();\n    auto bPtr     = inputs.size() > 3 ? inputs[3]->val()->data() : nullptr; \/\/ nullptr if no bias given\n\n    for(int row = 0; row < dimRows; ++row) {\n      auto currIdxPtr    = idxPtr   + row * k_;     \/\/ move to next batch of k entries\n      auto currQueryPtr  = queryPtr + row * dimIn;  \/\/ move to next input query vector\n      auto currOutPtr    = outPtr   + row * dimOut; \/\/ move to next output position vector (of vocabulary size)\n      for(int k = 0; k < k_; k++) {\n        int relPos = currIdxPtr[k];                   \/\/ k-th best vocabulay item\n        auto currWPtr      = WPtr + relPos * dimIn;   \/\/ offset for k-th best embedding\n        currOutPtr[relPos] = bPtr ? bPtr[relPos] : 0; \/\/ write bias value to position, init to 0 if no bias given\n        \n        \/\/ proceed one vector product at a time writing to the correct position\n        sgemm(false, true, 1, 1, dimIn, 1.0f, currQueryPtr, dimIn, currWPtr, dimIn, 1.0f, &currOutPtr[relPos], 1);\n      }\n    }\n  };\n\n  std::vector nodes = {idx, input, W};\n  if(b) \/\/ bias is optional\n    nodes.push_back(b);\n\n  return lambda(nodes, \n                outShape,\n                input->value_type(),\n                forward);\n}\n\n\/\/ @TODO: alternative version which does the same as above with Marian operators, currently missing \"scatter\".\n\/\/ this uses more memory and likely to be slower. Would make sense to have a scatter node that actually creates\n\/\/ the node instead of relying on an existing node, e.g. scatter(shape, defaultValue, axis, indices, values);\n#if 0 \nExpr LSH::affine(Expr idx, Expr input, Expr W, Expr b) {\n  int dim  = input->shape()[-1];\n  int bch  = idx->shape().elements() \/ k;\n\n  auto W = reshape(rows(Wt_, flatten(idx)), {bch, k, dim}); \/\/ [rows, k, dim]\n  auto b = reshape(cols(b_,  flatten(idx)), {bch, 1,   k}); \/\/ [rows, 1,   k]\n\n  auto aff = reshape(bdot(reshape(input, {bch, 1, dim}), W, false, true) + b, idx->shape()); \/\/ [beam, time, batch, k]\n\n  int dimVoc  = Wt_->shape()[-2];\n  auto oShape = input->shape();\n  oShape.set(-1, dimVoc);\n  auto lowest = graph_->constant(oShape, \n                                 inits::fromValue(NumericLimits(input->value_type()).lowest), \n                                 input->value_type());\n  return scatter(lowest, -1, idx, aff);\n}\n#endif\n\n}  \/\/ namespace marian<|endoftext|>"}
{"text":"#include \"model.h\"\n#include \n#include \n#include \n\nusing std::min;\nusing std::max;\nusing std::make_shared;\n\nBoundingBox getBoundingBox(const Track &track) {\n    BoundingBox res;\n    res.leftDown = res.rightUp = track[0];\n    for (Point p : track.points) {\n        res.leftDown.x = min(res.leftDown.x, p.x);\n        res.leftDown.y = min(res.leftDown.y, p.y);\n        res.rightUp.x = max(res.rightUp.x, p.x);\n        res.rightUp.y = max(res.rightUp.y, p.y);\n    }\n    return res;\n}\n\ndouble getCircumference(const Track &track) {\n    double res = 0;\n    for (size_t i = 0; i + 1 < track.size(); i++) {\n        res += (track[i + 1] - track[i]).length();\n    }\n    return res;\n}\ndouble getClosedCircumference(const Track &track) {\n    double res = getCircumference(track);\n    res += (track[0] - track[track.size() - 1]).length();\n    return res;\n}\n\nbool isClosed(const Track &track) {\n    return (track[0] - track[track.size() - 1]).length() <= 10;\n}\n\nbool fitsToTrack(const Track &track, const PFigure &figure) {\n    \/\/ Point should fall nearer than 10 pixels\n    BoundingBox box = getBoundingBox(track);\n    double maxDistance = 10;\n    maxDistance = std::min(maxDistance, std::min(box.width(), box.height()) * 0.2);\n\n    int goodCount = 0;\n    for (Point p : track.points) {\n        goodCount += figure->getApproximateDistanceToBorder(p) <= maxDistance;\n    }\n\n    \/\/ At least 95% of points fall nearer than 'maxDistance'\n    return goodCount * 100 \/ track.size() >= 95;\n}\n\nusing namespace figures;\n\nbool recognizeMove(const Track &track, Model &model) {\n    Point start = track[0];\n    Point end = track[track.size() - 1];\n    for (PFigure figure : model) {\n        if (figure->getApproximateDistanceToBorder(start) < 10) { \/\/ grabbed\n            figure->translate(end - start);\n            return true;\n        }\n    }\n    return false;\n}\n\nvoid recognize(const Track &track, Model &model) {\n    if (track.empty()) { return; }\n\n    \/\/ Moving\n    if (recognizeMove(track, model)) {\n        return;\n    }\n\n    \/\/ Drawing new figures\n\n    \/\/ Ignore very small tracks\n    if (getClosedCircumference(track) < 10) { return; }\n\n    std::vector candidates;\n    if (!isClosed(track))  {\n        candidates.push_back(make_shared(track[0], track[track.size() - 1]));\n    } else {\n        candidates.push_back(make_shared(getBoundingBox(track)));\n        candidates.push_back(make_shared(getBoundingBox(track)));\n    }\n    for (PFigure figure : candidates)\n        if (fitsToTrack(track, figure)) {\n            model.addFigure(figure);\n            break;\n        }\n}\nrecognition: recognizeMove --> recognizeGrabs; connection gesture was added (#12)#include \"model.h\"\n#include \n#include \n#include \n\nusing std::min;\nusing std::max;\nusing std::make_shared;\nusing std::dynamic_pointer_cast;\n\nBoundingBox getBoundingBox(const Track &track) {\n    BoundingBox res;\n    res.leftDown = res.rightUp = track[0];\n    for (Point p : track.points) {\n        res.leftDown.x = min(res.leftDown.x, p.x);\n        res.leftDown.y = min(res.leftDown.y, p.y);\n        res.rightUp.x = max(res.rightUp.x, p.x);\n        res.rightUp.y = max(res.rightUp.y, p.y);\n    }\n    return res;\n}\n\ndouble getCircumference(const Track &track) {\n    double res = 0;\n    for (size_t i = 0; i + 1 < track.size(); i++) {\n        res += (track[i + 1] - track[i]).length();\n    }\n    return res;\n}\ndouble getClosedCircumference(const Track &track) {\n    double res = getCircumference(track);\n    res += (track[0] - track[track.size() - 1]).length();\n    return res;\n}\n\nbool isClosed(const Track &track) {\n    return (track[0] - track[track.size() - 1]).length() <= 10;\n}\n\nbool fitsToTrack(const Track &track, const PFigure &figure) {\n    \/\/ Point should fall nearer than 10 pixels\n    BoundingBox box = getBoundingBox(track);\n    double maxDistance = 10;\n    maxDistance = std::min(maxDistance, std::min(box.width(), box.height()) * 0.2);\n\n    int goodCount = 0;\n    for (Point p : track.points) {\n        goodCount += figure->getApproximateDistanceToBorder(p) <= maxDistance;\n    }\n\n    \/\/ At least 95% of points fall nearer than 'maxDistance'\n    return goodCount * 100 \/ track.size() >= 95;\n}\n\nusing namespace figures;\n\nbool recognizeGrabs(const Track &track, Model &model) {\n    Point start = track[0];\n    Point end = track[track.size() - 1];\n\n    for (PFigure figure : model) {\n        if (figure->getApproximateDistanceToBorder(start) < 10) { \/\/ grabbed\n            \/\/ try connection first\n            auto figA = dynamic_pointer_cast(figure);\n            if (figA) {\n                for (PFigure figure2 : model) {\n                    auto figB = dynamic_pointer_cast(figure2);\n                    if (figB && figB->getApproximateDistanceToBorder(end) < 10) {\n                        model.addFigure(make_shared(figA, figB));\n                        return true;\n                    }\n                }\n            }\n\n            \/\/ now we try translation\n            figure->translate(end - start);\n            model.recalculate();\n            return true;\n        }\n    }\n    return false;\n}\n\nvoid recognize(const Track &track, Model &model) {\n    if (track.empty()) { return; }\n\n    \/\/ Moving and connecting\n    if (recognizeGrabs(track, model)) {\n        return;\n    }\n\n    \/\/ Drawing new figures\n\n    \/\/ Ignore very small tracks\n    if (getClosedCircumference(track) < 10) { return; }\n\n    std::vector candidates;\n    if (!isClosed(track))  {\n        candidates.push_back(make_shared(track[0], track[track.size() - 1]));\n    } else {\n        candidates.push_back(make_shared(getBoundingBox(track)));\n        candidates.push_back(make_shared(getBoundingBox(track)));\n    }\n    for (PFigure figure : candidates)\n        if (fitsToTrack(track, figure)) {\n            model.addFigure(figure);\n            break;\n        }\n}\n<|endoftext|>"}
{"text":"#include \"..\/aq_base.h\"\n\n#include \n#include \n\n#include \"gtest\/gtest.h\"\n#include \"..\/..\/test_helpers\/bart_test_helper.h\"\n\nclass AQBaseTest : public ::testing::Test {\n protected:\n  void SetUp() override;\n\n  template\n  void OutputAQ();\n\n  template\n  void InitRefBCAndCheck();\n  \n  dealii::ParameterHandler prm;\n};\n\nvoid AQBaseTest::SetUp() {\n  prm.declare_entry(\"have reflective boundary\", \"false\",\n                     dealii::Patterns::Bool(), \"\");\n  prm.declare_entry(\"angular quadrature order\", \"4\",\n                     dealii::Patterns::Integer(), \"\");\n  prm.declare_entry(\"angular quadrature name\", \"gl\",\n                     dealii::Patterns::Selection(\"gl\"), \"\");\n  prm.declare_entry(\"number of groups\", \"1\", dealii::Patterns::Integer(), \"\");\n  prm.declare_entry(\"transport model\", \"regular\",\n                     dealii::Patterns::Selection(\"regular|ep\"), \"\");\n}\n\ntemplate\nvoid AQBaseTest::OutputAQ() {\n  \/\/ Outputs AQData generated by MakeAQ to the deallog\n  std::unique_ptr> gl_ptr = std::make_unique>(prm);\n\n  gl_ptr->ProduceAQ();\n  auto wi = gl_ptr->GetAQWeights();\n  auto omega_i = gl_ptr->GetAQDirs();\n  \n  for (size_t i=0; i\nvoid AQBaseTest::InitRefBCAndCheck() {\n  std::unique_ptr> aq_base_ptr = std::make_unique>(prm);\n  aq_base_ptr->MakeAQ();\n  \/\/ Get omegas and reflection map\n  std::vector> omegas = aq_base_ptr->GetAQDirs();\n  std::map, int > reflection_map =\n      aq_base_ptr->GetRefDirInd();\n\n  for (auto const& mapping : reflection_map) {\n    \/\/ Unroll this data structure\n    int direction = mapping.first.second;\n    int reflection = mapping.second;\n\n    \/\/x-direction\n    EXPECT_FLOAT_EQ(omegas[direction][0], -omegas[reflection][0]);\n  } \n}\n\nTEST_F(AQBaseTest, AQBase1DProduceAQ) {\n  std::string filename = \"aq_base_1d\";\n  btest::GoldTestInit(filename);\n  OutputAQ<1>();\n  btest::GoldTestRun(filename); \n}\n\nTEST_F(AQBaseTest, AQBase1DEpProduceAQ) {\n  std::string filename = \"aq_base_1d_ep\";\n  prm.set(\"transport model\", \"ep\");\n  btest::GoldTestInit(filename); \/\/ Opens deal log\n  OutputAQ<1>();\n  btest::GoldTestRun(filename); \/\/ Closes deal log\n}\n\nTEST_F(AQBaseTest, AQBaseBadDimProduceAQ) {\n  AQBase<2> test_AQ(prm);\n  ASSERT_THROW(test_AQ.ProduceAQ(), dealii::ExcMessage);\n}\n\nTEST_F(AQBaseTest, AQBaseBadDimReflectiveBC) {\n  prm.set(\"have reflective boundary\", \"true\");\n  InitRefBCAndCheck<1>();\n}\n\nTEST_F(AQBaseTest, AQBaseSNOrderGetter) {\n  AQBase<1> test_AQ(prm);\n  ASSERT_EQ(test_AQ.GetSnOrder(), 4);\n}\n\nTEST_F(AQBaseTest, AQBaseGetNDir) {\n  AQBase<1> test_AQ(prm);\n  test_AQ.MakeAQ();\n  ASSERT_EQ(test_AQ.GetNDir(), 4);\n}\n\nTEST_F(AQBaseTest, AQBaseGetNDirEp) {\n  prm.set(\"transport model\", \"ep\");\n  AQBase<1> test_AQ(prm);\n  test_AQ.MakeAQ();\n  ASSERT_EQ(test_AQ.GetNDir(), 2);\n}\n\nTEST_F(AQBaseTest, AQBaseGetTotalHOVars) {\n  AQBase<1> test_AQ(prm);\n  test_AQ.MakeAQ();\n  ASSERT_EQ(test_AQ.GetNTotalHOVars(), 4);\n}\n\nTEST_F(AQBaseTest, AQBaseGetTotalHOVarsEq) {\n  prm.set(\"transport model\", \"ep\");\n  AQBase<1> test_AQ(prm);\n  test_AQ.MakeAQ();\n  ASSERT_EQ(test_AQ.GetNTotalHOVars(), 2);\n}\n\nTEST_F(AQBaseTest, PrintAQ) {  \n  AQBase<1> test_AQ(prm);\n  test_AQ.MakeAQ();\n\n  std::ostringstream output_string_stream;\n  test_AQ.PrintAQ(&output_string_stream);\n\n  std::string output = \"transport model: regular; output_streamature name: None\\n\"\n                       \"Dim = 1, SN order = 4\\n\"\n                       \"Weights | Omega_x | Omega_y | mu\\n\"\n                       \"0.347854845137454  -0.861136311594053  \\n\"\n                       \"0.652145154862546  -0.339981043584856  \\n\"\n                       \"0.652145154862546  0.339981043584856  \\n\"\n                       \"0.347854845137454  0.861136311594052  \\n\"; \n  EXPECT_EQ(output, output_string_stream.str());\n}\n  \nTEST_F(AQBaseTest, RefDirInt) {\n  AQBase<1> test_AQ(prm);\n  test_AQ.MakeAQ();\n  std::map, int> component_index_map(test_AQ.GetCompInd());\n\n  for (auto const& mapping : component_index_map) {\n    EXPECT_EQ(mapping.first.first, 0);\n    EXPECT_EQ(mapping.first.second, mapping.second);\n  }\n}\n\nTEST_F(AQBaseTest, InvDirInd) {\n  AQBase<1> test_AQ(prm);\n  std::unordered_map>\n      inv_component_map(test_AQ.GetInvCompInd());\n\n  for (size_t i = 0; i < inv_component_map.size(); ++i) {\n    EXPECT_EQ(inv_component_map[i].first, 0);\n    EXPECT_EQ(inv_component_map[i].second, i);\n  } \n}\nupdated PrintAQ test to use a regex for float comparison#include \"..\/aq_base.h\"\n\n#include \n#include \n\n#include \"gtest\/gtest.h\"\n#include \"..\/..\/test_helpers\/gmock_wrapper.h\"\n#include \"..\/..\/test_helpers\/bart_test_helper.h\"\n\nclass AQBaseTest : public ::testing::Test {\n protected:\n  void SetUp() override;\n\n  template\n  void OutputAQ();\n\n  template\n  void InitRefBCAndCheck();\n  \n  dealii::ParameterHandler prm;\n};\n\nvoid AQBaseTest::SetUp() {\n  prm.declare_entry(\"have reflective boundary\", \"false\",\n                     dealii::Patterns::Bool(), \"\");\n  prm.declare_entry(\"angular quadrature order\", \"4\",\n                     dealii::Patterns::Integer(), \"\");\n  prm.declare_entry(\"angular quadrature name\", \"gl\",\n                     dealii::Patterns::Selection(\"gl\"), \"\");\n  prm.declare_entry(\"number of groups\", \"1\", dealii::Patterns::Integer(), \"\");\n  prm.declare_entry(\"transport model\", \"regular\",\n                     dealii::Patterns::Selection(\"regular|ep\"), \"\");\n}\n\ntemplate\nvoid AQBaseTest::OutputAQ() {\n  \/\/ Outputs AQData generated by MakeAQ to the deallog\n  std::unique_ptr> gl_ptr = std::make_unique>(prm);\n\n  gl_ptr->ProduceAQ();\n  auto wi = gl_ptr->GetAQWeights();\n  auto omega_i = gl_ptr->GetAQDirs();\n  \n  for (size_t i=0; i\nvoid AQBaseTest::InitRefBCAndCheck() {\n  std::unique_ptr> aq_base_ptr = std::make_unique>(prm);\n  aq_base_ptr->MakeAQ();\n  \/\/ Get omegas and reflection map\n  std::vector> omegas = aq_base_ptr->GetAQDirs();\n  std::map, int > reflection_map =\n      aq_base_ptr->GetRefDirInd();\n\n  for (auto const& mapping : reflection_map) {\n    \/\/ Unroll this data structure\n    int direction = mapping.first.second;\n    int reflection = mapping.second;\n\n    \/\/x-direction\n    EXPECT_FLOAT_EQ(omegas[direction][0], -omegas[reflection][0]);\n  } \n}\n\nTEST_F(AQBaseTest, AQBase1DProduceAQ) {\n  std::string filename = \"aq_base_1d\";\n  btest::GoldTestInit(filename);\n  OutputAQ<1>();\n  btest::GoldTestRun(filename); \n}\n\nTEST_F(AQBaseTest, AQBase1DEpProduceAQ) {\n  std::string filename = \"aq_base_1d_ep\";\n  prm.set(\"transport model\", \"ep\");\n  btest::GoldTestInit(filename); \/\/ Opens deal log\n  OutputAQ<1>();\n  btest::GoldTestRun(filename); \/\/ Closes deal log\n}\n\nTEST_F(AQBaseTest, AQBaseBadDimProduceAQ) {\n  AQBase<2> test_AQ(prm);\n  ASSERT_THROW(test_AQ.ProduceAQ(), dealii::ExcMessage);\n}\n\nTEST_F(AQBaseTest, AQBaseBadDimReflectiveBC) {\n  prm.set(\"have reflective boundary\", \"true\");\n  InitRefBCAndCheck<1>();\n}\n\nTEST_F(AQBaseTest, AQBaseSNOrderGetter) {\n  AQBase<1> test_AQ(prm);\n  ASSERT_EQ(test_AQ.GetSnOrder(), 4);\n}\n\nTEST_F(AQBaseTest, AQBaseGetNDir) {\n  AQBase<1> test_AQ(prm);\n  test_AQ.MakeAQ();\n  ASSERT_EQ(test_AQ.GetNDir(), 4);\n}\n\nTEST_F(AQBaseTest, AQBaseGetNDirEp) {\n  prm.set(\"transport model\", \"ep\");\n  AQBase<1> test_AQ(prm);\n  test_AQ.MakeAQ();\n  ASSERT_EQ(test_AQ.GetNDir(), 2);\n}\n\nTEST_F(AQBaseTest, AQBaseGetTotalHOVars) {\n  AQBase<1> test_AQ(prm);\n  test_AQ.MakeAQ();\n  ASSERT_EQ(test_AQ.GetNTotalHOVars(), 4);\n}\n\nTEST_F(AQBaseTest, AQBaseGetTotalHOVarsEq) {\n  prm.set(\"transport model\", \"ep\");\n  AQBase<1> test_AQ(prm);\n  test_AQ.MakeAQ();\n  ASSERT_EQ(test_AQ.GetNTotalHOVars(), 2);\n}\n\nTEST_F(AQBaseTest, PrintAQ) {  \n  AQBase<1> test_AQ(prm);\n  test_AQ.MakeAQ();\n\n  std::ostringstream output_string_stream;\n  test_AQ.PrintAQ(&output_string_stream);\n\n  std::string output_regex = \"transport model: regular; output_streamature name: None\\n\"\n                             \"Dim = 1, SN order = 4\\n\"\n                             \"Weights | Omega_x | Omega_y | mu\\n\"\n                             \"0.34785\/\/d*  -0.86113\/\/d*  \\n\"\n                             \"0.65214\/\/d*  -0.33998\/\/d*  \\n\"\n                             \"0.65214\/\/d*  0.33998\/\/d*  \\n\"\n                             \"0.34785\/\/d*  0.86113\/\/d*  \\n\";\n  EXPECT_THAT(output_string_stream.str(), ::testing::ContainsRegex(output_regex));\n}\n  \nTEST_F(AQBaseTest, RefDirInt) {\n  AQBase<1> test_AQ(prm);\n  test_AQ.MakeAQ();\n  std::map, int> component_index_map(test_AQ.GetCompInd());\n\n  for (auto const& mapping : component_index_map) {\n    EXPECT_EQ(mapping.first.first, 0);\n    EXPECT_EQ(mapping.first.second, mapping.second);\n  }\n}\n\nTEST_F(AQBaseTest, InvDirInd) {\n  AQBase<1> test_AQ(prm);\n  std::unordered_map>\n      inv_component_map(test_AQ.GetInvCompInd());\n\n  for (size_t i = 0; i < inv_component_map.size(); ++i) {\n    EXPECT_EQ(inv_component_map[i].first, 0);\n    EXPECT_EQ(inv_component_map[i].second, i);\n  } \n}\n<|endoftext|>"}
{"text":"\/\/\/\n\/\/\/ @file  D_mpi.cpp\n\/\/\/ @brief Implementation of the D formula (from Xavier Gourdon's\n\/\/\/        algorithm) that has been distributed using MPI (Message\n\/\/\/        Passing Interface) and multi-threaded using OpenMP.\n\/\/\/\n\/\/\/ Copyright (C) 2020 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\n\/\/\/ Compute the contribution of the hard special leaves using a\n\/\/\/ segmented sieve. Each thread processes the interval\n\/\/\/ [low, low + segments * segment_size[.\n\/\/\/\ntemplate \nT D_thread(T x,\n           int64_t x_star,\n           int64_t xz,\n           int64_t y,\n           int64_t z,\n           int64_t k,\n           const Primes& primes,\n           const PiTable& pi,\n           const DFactorTable& factor,\n           ThreadSettings& thread)\n{\n  T sum = 0;\n\n  int64_t low = thread.low;\n  int64_t segments = thread.segments;\n  int64_t segment_size = thread.segment_size;\n  int64_t pi_sqrtz = pi[isqrt(z)];\n  int64_t low1 = max(low, 1);\n  int64_t limit = min(low + segments * segment_size, xz);\n  int64_t max_b = pi[min3(isqrt(x \/ low1), isqrt(limit), x_star)];\n  int64_t min_b = pi[min(xz \/ limit, x_star)];\n  min_b = max(k, min_b) + 1;\n\n  if (min_b > max_b)\n    return 0;\n\n  Sieve sieve(low, segment_size, max_b);\n  auto phi = generate_phi(low, max_b, primes, pi);\n  thread.init_finished();\n\n  \/\/ Segmented sieve of Eratosthenes\n  for (; low < limit; low += segment_size)\n  {\n    \/\/ current segment [low, high[\n    int64_t high = min(low + segment_size, limit);\n    low1 = max(low, 1);\n\n    \/\/ For i < min_b there are no special leaves:\n    \/\/ low <= x \/ (primes[i] * m) < high\n    sieve.pre_sieve(primes, min_b - 1, low, high);\n    int64_t b = min_b;\n\n    \/\/ For k + 1 <= b <= pi_sqrtz\n    \/\/ Find all special leaves in the current segment that are\n    \/\/ composed of a prime and a square free number:\n    \/\/ low <= x \/ (primes[b] * m) < high\n    for (int64_t end = min(pi_sqrtz, max_b); b <= end; b++)\n    {\n      int64_t prime = primes[b];\n      T xp = x \/ prime;\n      int64_t xp_low = min(fast_div(xp, low1), z);\n      int64_t xp_high = min(fast_div(xp, high), z);\n      int64_t min_m = max(xp_high, z \/ prime);\n      int64_t max_m = min(fast_div(xp, prime * prime), xp_low);\n\n      if (prime >= max_m)\n        goto next_segment;\n\n      min_m = factor.to_index(min_m);\n      max_m = factor.to_index(max_m);\n\n      for (int64_t m = max_m; m > min_m; m--)\n      {\n        \/\/ mu[m] != 0 && \n        \/\/ lpf[m] > prime &&\n        \/\/ mpf[m] <= y\n        if (prime < factor.is_leaf(m))\n        {\n          int64_t xpm = fast_div64(xp, factor.to_number(m));\n          int64_t stop = xpm - low;\n          int64_t phi_xpm = phi[b] + sieve.count(stop);\n          int64_t mu_m = factor.mu(m);\n          sum -= mu_m * phi_xpm;\n        }\n      }\n\n      phi[b] += sieve.get_total_count();\n      sieve.cross_off_count(prime, b);\n    }\n\n    \/\/ For pi_sqrtz < b <= pi_x_star\n    \/\/ Find all special leaves in the current segment\n    \/\/ that are composed of 2 primes:\n    \/\/ low <= x \/ (primes[b] * primes[l]) < high\n    for (; b <= max_b; b++)\n    {\n      int64_t prime = primes[b];\n      T xp = x \/ prime;\n      int64_t xp_low = min(fast_div(xp, low1), y);\n      int64_t xp_high = min(fast_div(xp, high), y);\n      int64_t min_m = max(xp_high, prime);\n      int64_t max_m = min(fast_div(xp, prime * prime), xp_low);\n      int64_t l = pi[max_m];\n\n      if (prime >= primes[l])\n        goto next_segment;\n\n      for (; primes[l] > min_m; l--)\n      {\n        int64_t xpq = fast_div64(xp, primes[l]);\n        int64_t stop = xpq - low;\n        int64_t phi_xpq = phi[b] + sieve.count(stop);\n        sum += phi_xpq;\n      }\n\n      phi[b] += sieve.get_total_count();\n      sieve.cross_off_count(prime, b);\n    }\n\n    next_segment:;\n  }\n\n  return sum;\n}\n\n\/\/\/ D MPI worker process.\n\/\/\/ Asks MPI main process for new work and reports\n\/\/\/ partial results to MPI main process.\n\/\/\/\ntemplate \nvoid D_mpi_worker(T x,\n                  int64_t y,\n                  int64_t z,\n                  int64_t k,\n                  const Primes& primes,\n                  const DFactorTable& factor,\n                  int threads)\n{\n  PiTable pi(y, threads);\n  int64_t xz = x \/ z;\n  int64_t x_star = get_x_star_gourdon(x, y);\n  int64_t thread_threshold = 1 << 20;\n  threads = ideal_num_threads(threads, xz, thread_threshold);\n  int main_proc_id = mpi_main_proc_id();\n  int proc_id = mpi_proc_id();\n  MpiMsg msg;\n\n  #pragma omp parallel for num_threads(threads)\n  for (int i = 0; i < threads; i++)\n  {\n    ThreadSettings thread;\n\n    while (true)\n    {\n      #pragma omp critical (mpi_sync)\n      {\n        \/\/ send result to main process\n        msg.set(proc_id, i, thread.low, thread.segments, thread.segment_size, thread.sum, thread.init_secs, thread.secs);\n        msg.send(main_proc_id);\n\n        \/\/ receive new work todo\n        msg.recv(proc_id);\n        thread.low = msg.low();\n        thread.segments = msg.segments();\n        thread.segment_size = msg.segment_size();\n      }\n\n      if (thread.low >= xz)\n        break;\n\n      \/\/ Unsigned integer division is usually slightly\n      \/\/ faster than signed integer division\n      using UT = typename make_unsigned::type;\n\n      thread.start_time();\n      UT sum = D_thread((UT) x, x_star, xz, y, z, k, primes, pi, factor, thread);\n      thread.sum = (T) sum;\n      thread.stop_time();\n    }\n  }\n\n  msg.set_finished();\n  msg.send(main_proc_id);\n}\n\n\/\/\/ D MPI main process.\n\/\/\/ Assigns work to the MPI worker processes.\n\/\/\/\ntemplate \nT D_mpi_main(T x,\n             int64_t z,\n             T d_approx)\n{\n  T sum = 0;\n  int64_t xz = x \/ z;\n  int workers = mpi_num_procs() - 1;\n\n  MpiMsg msg;\n  MpiLoadBalancer loadBalancer(x, xz, d_approx);\n  Status status(x);\n\n  while (workers > 0)\n  {\n    \/\/ wait for results from worker process\n    msg.recv_any();\n\n    if (msg.finished())\n      workers--;\n    else\n    {\n      sum += (T) msg.sum();\n      int64_t high = msg.low() + msg.segments() * msg.segment_size();\n\n      \/\/ update msg with new work\n      loadBalancer.get_work(&msg);\n\n      \/\/ send new work to worker process\n      msg.send(msg.proc_id());\n\n      if (is_print())\n        status.print(high, xz, sum, d_approx);\n    }\n  }\n\n  return sum;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t D_mpi(int64_t x,\n              int64_t y,\n              int64_t z,\n              int64_t k,\n              int64_t d_approx,\n              int threads)\n{\n  print(\"\");\n  print(\"=== D_mpi(x, y) ===\");\n  print_gourdon_vars(x, y, z, k, threads);\n\n  int64_t sum = 0;\n  double time = get_time();\n\n  if (is_mpi_main_proc())\n    sum = D_mpi_main(x, z, d_approx);\n  else\n  {\n    DFactorTable factor(y, z, threads);\n    auto primes = generate_primes(y);\n    D_mpi_worker(x, y, z, k, primes, factor, threads);\n  }\n\n  print(\"D\", sum, time);\n  return sum;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t D_mpi(int128_t x,\n               int64_t y,\n               int64_t z,\n               int64_t k,\n               int128_t d_approx,\n               int threads)\n{\n  print(\"\");\n  print(\"=== D_mpi(x, y) ===\");\n  print_gourdon_vars(x, y, z, k, threads);\n\n  int128_t sum = 0;\n  double time = get_time();\n\n  if (is_mpi_main_proc())\n    sum = D_mpi_main(x, z, d_approx);\n  else\n  {\n    \/\/ uses less memory\n    if (y <= FactorTable::max())\n    {\n      DFactorTable factor(y, z, threads);\n      auto primes = generate_primes(y);\n      D_mpi_worker(x, y, z, k, primes, factor, threads);\n    }\n    else\n    {\n      DFactorTable factor(y, z, threads);\n      auto primes = generate_primes(y);\n      D_mpi_worker(x, y, z, k, primes, factor, threads);\n    }\n  }\n\n  print(\"D\", sum, time);\n  return sum;\n}\n\n#endif\n\n\n} \/\/ namespace\nUse OmpLock instead of critical section\/\/\/\n\/\/\/ @file  D_mpi.cpp\n\/\/\/ @brief Implementation of the D formula (from Xavier Gourdon's\n\/\/\/        algorithm) that has been distributed using MPI (Message\n\/\/\/        Passing Interface) and multi-threaded using OpenMP.\n\/\/\/\n\/\/\/ Copyright (C) 2020 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\n\/\/\/ Compute the contribution of the hard special leaves using a\n\/\/\/ segmented sieve. Each thread processes the interval\n\/\/\/ [low, low + segments * segment_size[.\n\/\/\/\ntemplate \nT D_thread(T x,\n           int64_t x_star,\n           int64_t xz,\n           int64_t y,\n           int64_t z,\n           int64_t k,\n           const Primes& primes,\n           const PiTable& pi,\n           const DFactorTable& factor,\n           ThreadSettings& thread)\n{\n  T sum = 0;\n\n  int64_t low = thread.low;\n  int64_t segments = thread.segments;\n  int64_t segment_size = thread.segment_size;\n  int64_t pi_sqrtz = pi[isqrt(z)];\n  int64_t low1 = max(low, 1);\n  int64_t limit = min(low + segments * segment_size, xz);\n  int64_t max_b = pi[min3(isqrt(x \/ low1), isqrt(limit), x_star)];\n  int64_t min_b = pi[min(xz \/ limit, x_star)];\n  min_b = max(k, min_b) + 1;\n\n  if (min_b > max_b)\n    return 0;\n\n  Sieve sieve(low, segment_size, max_b);\n  auto phi = generate_phi(low, max_b, primes, pi);\n  thread.init_finished();\n\n  \/\/ Segmented sieve of Eratosthenes\n  for (; low < limit; low += segment_size)\n  {\n    \/\/ current segment [low, high[\n    int64_t high = min(low + segment_size, limit);\n    low1 = max(low, 1);\n\n    \/\/ For i < min_b there are no special leaves:\n    \/\/ low <= x \/ (primes[i] * m) < high\n    sieve.pre_sieve(primes, min_b - 1, low, high);\n    int64_t b = min_b;\n\n    \/\/ For k + 1 <= b <= pi_sqrtz\n    \/\/ Find all special leaves in the current segment that are\n    \/\/ composed of a prime and a square free number:\n    \/\/ low <= x \/ (primes[b] * m) < high\n    for (int64_t end = min(pi_sqrtz, max_b); b <= end; b++)\n    {\n      int64_t prime = primes[b];\n      T xp = x \/ prime;\n      int64_t xp_low = min(fast_div(xp, low1), z);\n      int64_t xp_high = min(fast_div(xp, high), z);\n      int64_t min_m = max(xp_high, z \/ prime);\n      int64_t max_m = min(fast_div(xp, prime * prime), xp_low);\n\n      if (prime >= max_m)\n        goto next_segment;\n\n      min_m = factor.to_index(min_m);\n      max_m = factor.to_index(max_m);\n\n      for (int64_t m = max_m; m > min_m; m--)\n      {\n        \/\/ mu[m] != 0 && \n        \/\/ lpf[m] > prime &&\n        \/\/ mpf[m] <= y\n        if (prime < factor.is_leaf(m))\n        {\n          int64_t xpm = fast_div64(xp, factor.to_number(m));\n          int64_t stop = xpm - low;\n          int64_t phi_xpm = phi[b] + sieve.count(stop);\n          int64_t mu_m = factor.mu(m);\n          sum -= mu_m * phi_xpm;\n        }\n      }\n\n      phi[b] += sieve.get_total_count();\n      sieve.cross_off_count(prime, b);\n    }\n\n    \/\/ For pi_sqrtz < b <= pi_x_star\n    \/\/ Find all special leaves in the current segment\n    \/\/ that are composed of 2 primes:\n    \/\/ low <= x \/ (primes[b] * primes[l]) < high\n    for (; b <= max_b; b++)\n    {\n      int64_t prime = primes[b];\n      T xp = x \/ prime;\n      int64_t xp_low = min(fast_div(xp, low1), y);\n      int64_t xp_high = min(fast_div(xp, high), y);\n      int64_t min_m = max(xp_high, prime);\n      int64_t max_m = min(fast_div(xp, prime * prime), xp_low);\n      int64_t l = pi[max_m];\n\n      if (prime >= primes[l])\n        goto next_segment;\n\n      for (; primes[l] > min_m; l--)\n      {\n        int64_t xpq = fast_div64(xp, primes[l]);\n        int64_t stop = xpq - low;\n        int64_t phi_xpq = phi[b] + sieve.count(stop);\n        sum += phi_xpq;\n      }\n\n      phi[b] += sieve.get_total_count();\n      sieve.cross_off_count(prime, b);\n    }\n\n    next_segment:;\n  }\n\n  return sum;\n}\n\n\/\/\/ D MPI worker process.\n\/\/\/ Asks MPI main process for new work and reports\n\/\/\/ partial results to MPI main process.\n\/\/\/\ntemplate \nvoid D_mpi_worker(T x,\n                  int64_t y,\n                  int64_t z,\n                  int64_t k,\n                  const Primes& primes,\n                  const DFactorTable& factor,\n                  int threads)\n{\n  PiTable pi(y, threads);\n  int64_t xz = x \/ z;\n  int64_t x_star = get_x_star_gourdon(x, y);\n  int64_t thread_threshold = 1 << 20;\n  threads = ideal_num_threads(threads, xz, thread_threshold);\n  int main_proc_id = mpi_main_proc_id();\n  int proc_id = mpi_proc_id();\n  MpiMsg msg;\n  OmpLock ompLock;\n\n  #pragma omp parallel for num_threads(threads)\n  for (int i = 0; i < threads; i++)\n  {\n    ThreadSettings thread;\n\n    while (true)\n    {\n      {\n        LockGuard lockGuard(ompLock);\n\n        \/\/ send result to main process\n        msg.set(proc_id, i, thread.low, thread.segments, thread.segment_size, thread.sum, thread.init_secs, thread.secs);\n        msg.send(main_proc_id);\n\n        \/\/ receive new work todo\n        msg.recv(proc_id);\n        thread.low = msg.low();\n        thread.segments = msg.segments();\n        thread.segment_size = msg.segment_size();\n      }\n\n      if (thread.low >= xz)\n        break;\n\n      \/\/ Unsigned integer division is usually slightly\n      \/\/ faster than signed integer division\n      using UT = typename make_unsigned::type;\n\n      thread.start_time();\n      UT sum = D_thread((UT) x, x_star, xz, y, z, k, primes, pi, factor, thread);\n      thread.sum = (T) sum;\n      thread.stop_time();\n    }\n  }\n\n  msg.set_finished();\n  msg.send(main_proc_id);\n}\n\n\/\/\/ D MPI main process.\n\/\/\/ Assigns work to the MPI worker processes.\n\/\/\/\ntemplate \nT D_mpi_main(T x,\n             int64_t z,\n             T d_approx)\n{\n  T sum = 0;\n  int64_t xz = x \/ z;\n  int workers = mpi_num_procs() - 1;\n\n  MpiMsg msg;\n  MpiLoadBalancer loadBalancer(x, xz, d_approx);\n  Status status(x);\n\n  while (workers > 0)\n  {\n    \/\/ wait for results from worker process\n    msg.recv_any();\n\n    if (msg.finished())\n      workers--;\n    else\n    {\n      sum += (T) msg.sum();\n      int64_t high = msg.low() + msg.segments() * msg.segment_size();\n\n      \/\/ update msg with new work\n      loadBalancer.get_work(&msg);\n\n      \/\/ send new work to worker process\n      msg.send(msg.proc_id());\n\n      if (is_print())\n        status.print(high, xz, sum, d_approx);\n    }\n  }\n\n  return sum;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t D_mpi(int64_t x,\n              int64_t y,\n              int64_t z,\n              int64_t k,\n              int64_t d_approx,\n              int threads)\n{\n  print(\"\");\n  print(\"=== D_mpi(x, y) ===\");\n  print_gourdon_vars(x, y, z, k, threads);\n\n  int64_t sum = 0;\n  double time = get_time();\n\n  if (is_mpi_main_proc())\n    sum = D_mpi_main(x, z, d_approx);\n  else\n  {\n    DFactorTable factor(y, z, threads);\n    auto primes = generate_primes(y);\n    D_mpi_worker(x, y, z, k, primes, factor, threads);\n  }\n\n  print(\"D\", sum, time);\n  return sum;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t D_mpi(int128_t x,\n               int64_t y,\n               int64_t z,\n               int64_t k,\n               int128_t d_approx,\n               int threads)\n{\n  print(\"\");\n  print(\"=== D_mpi(x, y) ===\");\n  print_gourdon_vars(x, y, z, k, threads);\n\n  int128_t sum = 0;\n  double time = get_time();\n\n  if (is_mpi_main_proc())\n    sum = D_mpi_main(x, z, d_approx);\n  else\n  {\n    \/\/ uses less memory\n    if (y <= FactorTable::max())\n    {\n      DFactorTable factor(y, z, threads);\n      auto primes = generate_primes(y);\n      D_mpi_worker(x, y, z, k, primes, factor, threads);\n    }\n    else\n    {\n      DFactorTable factor(y, z, threads);\n      auto primes = generate_primes(y);\n      D_mpi_worker(x, y, z, k, primes, factor, threads);\n    }\n  }\n\n  print(\"D\", sum, time);\n  return sum;\n}\n\n#endif\n\n\n} \/\/ namespace\n<|endoftext|>"}
{"text":"#ifndef ARCH_RUNTIME_THREAD_POOL_HPP_\n#define ARCH_RUNTIME_THREAD_POOL_HPP_\n\n#include \n\n#include \n#include \n\n#include \"config\/args.hpp\"\n#include \"arch\/runtime\/event_queue.hpp\"\n#include \"arch\/runtime\/system_event.hpp\"\n#include \"arch\/runtime\/message_hub.hpp\"\n#include \"arch\/runtime\/coroutines.hpp\"\n#include \"arch\/io\/blocker_pool.hpp\"\n#include \"arch\/timer.hpp\"\n\nclass linux_thread_t;\n\n\/* coro_runtime_t is borrowed from coroutines.hpp.  Please only\nconstruct one coro_runtime_t per thread. Coroutines can only be used\nwhen a coro_runtime_t exists. It exists to take advantage of RAII. *\/\n\nstruct coro_runtime_t {\n    coro_runtime_t();\n    ~coro_runtime_t();\n\n#ifndef NDEBUG\n    void get_coroutine_counts(std::map *dest);\n#endif\n};\n\n\n\/* A thread pool represents a group of threads, each of which is associated with an\nevent queue. There is one thread pool per server. It is responsible for starting up\nand shutting down the threads and event queues. *\/\n\nclass linux_thread_pool_t {\npublic:\n    linux_thread_pool_t(int worker_threads, bool do_set_affinity);\n\n    \/\/ When the process receives a SIGINT or SIGTERM, interrupt_message will be delivered to the\n    \/\/ same thread that initial_message was delivered to, and interrupt_message will be set to\n    \/\/ NULL. If you want to receive notification of further SIGINTs or SIGTERMs, you must call\n    \/\/ set_interrupt_message() again. Returns the previous value of interrupt_message.\n    static linux_thread_message_t *set_interrupt_message(linux_thread_message_t *interrupt_message);\n\n    \/\/ Blocks while threads are working. Only returns after shutdown() is called. initial_message\n    \/\/ is a thread message that will be delivered to thread zero after all of the event queues\n    \/\/ have been started; it is used to start the server's activity.\n    void run_thread_pool(linux_thread_message_t *initial_message);\n\n#ifndef NDEBUG\n    void enable_coroutine_summary();\n#endif\n\n    \/\/ Shut down all the threads. Can be called from any thread.\n    void shutdown_thread_pool();\n\n    ~linux_thread_pool_t();\n\nprivate:\n#ifndef NDEBUG\n    bool coroutine_summary;\n#endif\n\n    static void *start_thread(void*);\n\n    static void interrupt_handler(int);\n    static void sigsegv_handler(int, siginfo_t *, void *) NORETURN;\n    pthread_spinlock_t interrupt_message_lock;\n    linux_thread_message_t *interrupt_message;\n\n    \/\/ Used to signal the main thread for shutdown\n    volatile bool do_shutdown;\n    pthread_cond_t shutdown_cond;\n    pthread_mutex_t shutdown_cond_mutex;\n\n    \/\/ The number of threads to allocate for handling blocking calls\n    static const int GENERIC_BLOCKER_THREAD_COUNT = 2;\n    blocker_pool_t* generic_blocker_pool;\n\npublic:\n    pthread_t pthreads[MAX_THREADS];\n    linux_thread_t *threads[MAX_THREADS];\n\n    \/\/ Cooperatively run a blocking function call using the generic_blocker_pool\n    template \n    static void run_in_blocker_pool(const Callable &);\n\n    int n_threads;\n    bool do_set_affinity;\n    \/\/ The thread_pool that started the thread we are currently in\n    static __thread linux_thread_pool_t *thread_pool;\n    \/\/ The ID of the thread we are currently in\n    static __thread int thread_id;\n    \/\/ The event queue for the thread we are currently in (same as &thread_pool->threads[thread_id])\n    static __thread linux_thread_t *thread;\n\nprivate:\n    DISABLE_COPYING(linux_thread_pool_t);\n};\n\ntemplate \nstruct generic_job_t :\n    public blocker_pool_t::job_t\n{\n    void run() {\n        (*fn)();\n    }\n\n    void done() {\n        \/\/ Now that the function is done, resume execution of the suspended task\n        suspended->notify_sometime();\n    }\n\n    const Callable *fn;\n    coro_t* suspended;\n};\n\n\/\/ Function to handle blocking calls in a separate thread pool\n\/\/ This should be used for any calls that cannot otherwise be made non-blocking\ntemplate \nvoid linux_thread_pool_t::run_in_blocker_pool(const Callable &fn)\n{\n    generic_job_t job;\n    job.fn = &fn;\n    job.suspended = coro_t::self();\n\n    rassert(thread_pool->generic_blocker_pool != NULL,\n            \"thread_pool_t::run_in_blocker_pool called while generic_thread_pool uninitialized\");\n    thread_pool->generic_blocker_pool->do_job(&job);\n\n    \/\/ Give up execution, to be resumed when the done callback is made\n    coro_t::wait();\n}\n\nclass linux_thread_t :\n    public linux_event_callback_t,\n    public linux_queue_parent_t\n{\n    timer_token_t *perfmon_stats_timer;\n\npublic:\n    linux_thread_t(linux_thread_pool_t *parent_pool, int thread_id);\n    ~linux_thread_t();\n\n    linux_event_queue_t queue;\n    linux_message_hub_t message_hub;\n    timer_handler_t timer_handler;\n\n    \/* Never accessed; its constructor and destructor set up and tear down thread-local variables\n    for coroutines. *\/\n    coro_runtime_t coro_runtime;\n\n    void pump();   \/\/ Called by the event queue\n    bool should_shut_down();   \/\/ Called by the event queue\n#ifndef NDEBUG\n    void initiate_shut_down(std::map *coroutine_counts); \/\/ Can be called from any thread\n#else\n    void initiate_shut_down(); \/\/ Can be called from any thread\n#endif\n    void on_event(int events);\n\nprivate:\n    volatile bool do_shutdown;\n    pthread_mutex_t do_shutdown_mutex;\n    system_event_t shutdown_notify_event;\n\n#ifndef NDEBUG\n    std::map *coroutine_counts_at_shutdown;\n#endif\n};\n\n#endif \/* ARCH_RUNTIME_THREAD_POOL_HPP_ *\/\nMade set_interrupt_message have a MUST_USE return value.#ifndef ARCH_RUNTIME_THREAD_POOL_HPP_\n#define ARCH_RUNTIME_THREAD_POOL_HPP_\n\n#include \n\n#include \n#include \n\n#include \"config\/args.hpp\"\n#include \"arch\/runtime\/event_queue.hpp\"\n#include \"arch\/runtime\/system_event.hpp\"\n#include \"arch\/runtime\/message_hub.hpp\"\n#include \"arch\/runtime\/coroutines.hpp\"\n#include \"arch\/io\/blocker_pool.hpp\"\n#include \"arch\/timer.hpp\"\n\nclass linux_thread_t;\n\n\/* coro_runtime_t is borrowed from coroutines.hpp.  Please only\nconstruct one coro_runtime_t per thread. Coroutines can only be used\nwhen a coro_runtime_t exists. It exists to take advantage of RAII. *\/\n\nstruct coro_runtime_t {\n    coro_runtime_t();\n    ~coro_runtime_t();\n\n#ifndef NDEBUG\n    void get_coroutine_counts(std::map *dest);\n#endif\n};\n\n\n\/* A thread pool represents a group of threads, each of which is associated with an\nevent queue. There is one thread pool per server. It is responsible for starting up\nand shutting down the threads and event queues. *\/\n\nclass linux_thread_pool_t {\npublic:\n    linux_thread_pool_t(int worker_threads, bool do_set_affinity);\n\n    \/\/ When the process receives a SIGINT or SIGTERM, interrupt_message will be delivered to the\n    \/\/ same thread that initial_message was delivered to, and interrupt_message will be set to\n    \/\/ NULL. If you want to receive notification of further SIGINTs or SIGTERMs, you must call\n    \/\/ set_interrupt_message() again. Returns the previous value of interrupt_message.\n    static MUST_USE linux_thread_message_t *set_interrupt_message(linux_thread_message_t *interrupt_message);\n\n    \/\/ Blocks while threads are working. Only returns after shutdown() is called. initial_message\n    \/\/ is a thread message that will be delivered to thread zero after all of the event queues\n    \/\/ have been started; it is used to start the server's activity.\n    void run_thread_pool(linux_thread_message_t *initial_message);\n\n#ifndef NDEBUG\n    void enable_coroutine_summary();\n#endif\n\n    \/\/ Shut down all the threads. Can be called from any thread.\n    void shutdown_thread_pool();\n\n    ~linux_thread_pool_t();\n\nprivate:\n#ifndef NDEBUG\n    bool coroutine_summary;\n#endif\n\n    static void *start_thread(void*);\n\n    static void interrupt_handler(int);\n    static void sigsegv_handler(int, siginfo_t *, void *) NORETURN;\n    pthread_spinlock_t interrupt_message_lock;\n    linux_thread_message_t *interrupt_message;\n\n    \/\/ Used to signal the main thread for shutdown\n    volatile bool do_shutdown;\n    pthread_cond_t shutdown_cond;\n    pthread_mutex_t shutdown_cond_mutex;\n\n    \/\/ The number of threads to allocate for handling blocking calls\n    static const int GENERIC_BLOCKER_THREAD_COUNT = 2;\n    blocker_pool_t* generic_blocker_pool;\n\npublic:\n    pthread_t pthreads[MAX_THREADS];\n    linux_thread_t *threads[MAX_THREADS];\n\n    \/\/ Cooperatively run a blocking function call using the generic_blocker_pool\n    template \n    static void run_in_blocker_pool(const Callable &);\n\n    int n_threads;\n    bool do_set_affinity;\n    \/\/ The thread_pool that started the thread we are currently in\n    static __thread linux_thread_pool_t *thread_pool;\n    \/\/ The ID of the thread we are currently in\n    static __thread int thread_id;\n    \/\/ The event queue for the thread we are currently in (same as &thread_pool->threads[thread_id])\n    static __thread linux_thread_t *thread;\n\nprivate:\n    DISABLE_COPYING(linux_thread_pool_t);\n};\n\ntemplate \nstruct generic_job_t :\n    public blocker_pool_t::job_t\n{\n    void run() {\n        (*fn)();\n    }\n\n    void done() {\n        \/\/ Now that the function is done, resume execution of the suspended task\n        suspended->notify_sometime();\n    }\n\n    const Callable *fn;\n    coro_t* suspended;\n};\n\n\/\/ Function to handle blocking calls in a separate thread pool\n\/\/ This should be used for any calls that cannot otherwise be made non-blocking\ntemplate \nvoid linux_thread_pool_t::run_in_blocker_pool(const Callable &fn)\n{\n    generic_job_t job;\n    job.fn = &fn;\n    job.suspended = coro_t::self();\n\n    rassert(thread_pool->generic_blocker_pool != NULL,\n            \"thread_pool_t::run_in_blocker_pool called while generic_thread_pool uninitialized\");\n    thread_pool->generic_blocker_pool->do_job(&job);\n\n    \/\/ Give up execution, to be resumed when the done callback is made\n    coro_t::wait();\n}\n\nclass linux_thread_t :\n    public linux_event_callback_t,\n    public linux_queue_parent_t\n{\n    timer_token_t *perfmon_stats_timer;\n\npublic:\n    linux_thread_t(linux_thread_pool_t *parent_pool, int thread_id);\n    ~linux_thread_t();\n\n    linux_event_queue_t queue;\n    linux_message_hub_t message_hub;\n    timer_handler_t timer_handler;\n\n    \/* Never accessed; its constructor and destructor set up and tear down thread-local variables\n    for coroutines. *\/\n    coro_runtime_t coro_runtime;\n\n    void pump();   \/\/ Called by the event queue\n    bool should_shut_down();   \/\/ Called by the event queue\n#ifndef NDEBUG\n    void initiate_shut_down(std::map *coroutine_counts); \/\/ Can be called from any thread\n#else\n    void initiate_shut_down(); \/\/ Can be called from any thread\n#endif\n    void on_event(int events);\n\nprivate:\n    volatile bool do_shutdown;\n    pthread_mutex_t do_shutdown_mutex;\n    system_event_t shutdown_notify_event;\n\n#ifndef NDEBUG\n    std::map *coroutine_counts_at_shutdown;\n#endif\n};\n\n#endif \/* ARCH_RUNTIME_THREAD_POOL_HPP_ *\/\n<|endoftext|>"}
{"text":"\/\/ init: The initial user-level program\n\n#include \"types.h\"\n#include \"user.h\"\n#include \n#include \"lib.h\"\n#include \"major.h\"\n\nstatic const char *sh_argv[] = { \"sh\", 0 };\nstatic const char *app_argv[][MAXARG] = {\n#ifdef LWIP\n  { \"telnetd\", 0 },\n  { \"httpd\", 0 },\n#endif\n};\n\nstatic struct {\n  const char* name;\n  int major;\n} dev[] = {\n  { \"\/dev\/netif\",     MAJ_NETIF },\n  { \"\/dev\/sampler\",   MAJ_SAMPLER },\n  { \"\/dev\/lockstat\",  MAJ_LOCKSTAT },\n  { \"\/dev\/stat\",      MAJ_STAT },\n  { \"\/dev\/cmdline\",   MAJ_CMDLINE},\n  { \"\/dev\/gc\",   MAJ_GC},\n};\n\nstatic int\nstartone(const char **argv)\n{\n  int pid;\n\n  pid = fork(0);\n  if(pid < 0){\n    fprintf(1, \"init: fork failed\\n\");\n    exit();\n  }\n  if(pid == 0){\n    exec(argv[0], argv);\n    fprintf(1, \"init: exec %s failed\\n\", argv[0]);\n    exit();\n  }\n  return pid;\n}\n\nstatic void\nruncmdline(void)\n{\n  const char* argv[3] = { \"sh\", 0, 0 };\n  char buf[256];\n  char* b;\n  long r;\n  int fd;\n\n  fd = open(\"\/dev\/cmdline\", O_RDONLY);\n  if (fd < 0)\n    return;\n\n  r = read(fd, buf, sizeof(buf)-1);\n  if (r < 0)\n    return;\n  buf[r] = 0;\n  \n  if ((b = strchr(buf, '$'))) {\n    argv[1] = b+1;\n    startone(argv);\n  }\n}\n\nint\nmain(void)\n{\n  int pid, wpid;\n\n  if(open(\"console\", O_RDWR) < 0){\n    mknod(\"console\", 1, 1);\n    open(\"console\", O_RDWR);\n  }\n  dup(0);  \/\/ stdout\n  dup(0);  \/\/ stderr\n\n  mkdir(\"dev\", 0777);\n  for (int i = 0; i < NELEM(dev); i++)\n    if (mknod(dev[i].name, dev[i].major, 1) < 0)\n      fprintf(2, \"init: mknod %s failed\\n\", dev[i].name);\n  \n  for (u32 i = 0; i < NELEM(app_argv); i++)\n    startone(app_argv[i]);\n\n  runcmdline();\n\n  for(;;){\n    pid = startone(sh_argv);\n    while((wpid=wait()) >= 0 && wpid != pid)\n      fprintf(1, \"zombie!\\n\");\n  }\n}\ninit: Pass -c to sh when running kernel command line\/\/ init: The initial user-level program\n\n#include \"types.h\"\n#include \"user.h\"\n#include \n#include \"lib.h\"\n#include \"major.h\"\n\nstatic const char *sh_argv[] = { \"sh\", 0 };\nstatic const char *app_argv[][MAXARG] = {\n#ifdef LWIP\n  { \"telnetd\", 0 },\n  { \"httpd\", 0 },\n#endif\n};\n\nstatic struct {\n  const char* name;\n  int major;\n} dev[] = {\n  { \"\/dev\/netif\",     MAJ_NETIF },\n  { \"\/dev\/sampler\",   MAJ_SAMPLER },\n  { \"\/dev\/lockstat\",  MAJ_LOCKSTAT },\n  { \"\/dev\/stat\",      MAJ_STAT },\n  { \"\/dev\/cmdline\",   MAJ_CMDLINE},\n  { \"\/dev\/gc\",   MAJ_GC},\n};\n\nstatic int\nstartone(const char **argv)\n{\n  int pid;\n\n  pid = fork(0);\n  if(pid < 0){\n    fprintf(1, \"init: fork failed\\n\");\n    exit();\n  }\n  if(pid == 0){\n    exec(argv[0], argv);\n    fprintf(1, \"init: exec %s failed\\n\", argv[0]);\n    exit();\n  }\n  return pid;\n}\n\nstatic void\nruncmdline(void)\n{\n  const char* argv[4] = { \"sh\", \"-c\", 0 };\n  char buf[256];\n  char* b;\n  long r;\n  int fd;\n\n  fd = open(\"\/dev\/cmdline\", O_RDONLY);\n  if (fd < 0)\n    return;\n\n  r = read(fd, buf, sizeof(buf)-1);\n  if (r < 0)\n    return;\n  buf[r] = 0;\n  \n  if ((b = strchr(buf, '$'))) {\n    argv[2] = b+1;\n    startone(argv);\n  }\n}\n\nint\nmain(void)\n{\n  int pid, wpid;\n\n  if(open(\"console\", O_RDWR) < 0){\n    mknod(\"console\", 1, 1);\n    open(\"console\", O_RDWR);\n  }\n  dup(0);  \/\/ stdout\n  dup(0);  \/\/ stderr\n\n  mkdir(\"dev\", 0777);\n  for (int i = 0; i < NELEM(dev); i++)\n    if (mknod(dev[i].name, dev[i].major, 1) < 0)\n      fprintf(2, \"init: mknod %s failed\\n\", dev[i].name);\n  \n  for (u32 i = 0; i < NELEM(app_argv); i++)\n    startone(app_argv[i]);\n\n  runcmdline();\n\n  for(;;){\n    pid = startone(sh_argv);\n    while((wpid=wait()) >= 0 && wpid != pid)\n      fprintf(1, \"zombie!\\n\");\n  }\n}\n<|endoftext|>"}
{"text":"\/*****************************************************************************\n*  Copyright 2011 Sergey Shekyan\n*\n*  Licensed under the Apache License, Version 2.0 (the \"License\");\n*  you may not use this file except in compliance with the License.\n*  You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n* *****************************************************************************\/\n\n\/*****\n * Author: Sergey Shekyan sshekyan@qualys.com\n *\n * Slow HTTP attack  vulnerability test tool\n *  http:\/\/code.google.com\/p\/slowhttptest\/\n *****\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"slowlog.h\"\n#include \"slowsocket.h\"\n#include \"slowurl.h\"\n\nnamespace slowhttptest {\nSlowSocket::SlowSocket()\n    : sockfd_(-1), requests_to_send_(0),\n      followups_to_send_(0), last_followup_timing_(0),\n      offset_(0), ssl_(0), buf_(0), \n      start_in_millisecs_(0), connected_in_millisecs_(0),\n      stop_in_millisecs_(0), state_(eInit) {\n}\n\nSlowSocket::~SlowSocket() {\n  close();\n}\n\nint SlowSocket::set_nonblocking() {\n  int flags;\n\n  if(-1 == (flags = fcntl(sockfd_, F_GETFL, 0))) {\n    flags = 0;\n  }\n  return fcntl(sockfd_, F_SETFL, flags | O_NONBLOCK);\n}\n\nbool SlowSocket::init(addrinfo* addr, const Url* url, int& maxfd,\n                      int followups_to_send) {\n  addrinfo* res;\n  bool connect_initiated_ = false;\n  for (res = addr; !connect_initiated_ && res; res = res->ai_next) {\n    sockfd_ = socket(res->ai_family, res->ai_socktype,\n     res->ai_protocol);\n    if(-1 == sockfd_) {\n      slowlog(LOG_ERROR, \"failed to create socket: %s\\n\", strerror(errno));\n      return false;\n    }\n\n    if(-1 == set_nonblocking()) {\n      slowlog(LOG_ERROR, \"failed to set socket %d to non-blocking \\n\", sockfd_);\n      return false;\n    }\n\n    slowlog(LOG_DEBUG, \"non-blocking socket fd = %d created\\n\", sockfd_);\n    if(connect_initiated_ = url->isSSL() ? connect_ssl(addr) : connect_plain(addr)) {\n      break; \/\/found right addrinfo\n    }\n      \n  }\n\n\n  followups_to_send_ = followups_to_send;\n  requests_to_send_ = 1;\n\n  if(sockfd_ > maxfd) {\n    maxfd = sockfd_;\n  }\n  return true;\n}\n\nbool SlowSocket::connect_plain(addrinfo* addr) {\n  errno = 0;\n\n  if (connect(sockfd_, addr->ai_addr, addr->ai_addrlen) < 0\n      && EINPROGRESS != errno) {\n    slowlog(LOG_ERROR, \"cannot connect socket %d: %s\\n\", sockfd_, strerror(errno));\n    close();\n    return false;\n  }\n  return true;\n}\n\nbool SlowSocket::connect_ssl(addrinfo* addr) {\n  \/\/ Establish regular connection.\n  if(!connect_plain(addr))  return false;\n   \n  \/\/ Init SSL related stuff.\n  \/\/ TODO(vagababov): this is not thread safe of pretty.\n  static bool ssl_is_initialized = false;\n  if (!ssl_is_initialized) {\n    SSL_library_init();\n    ssl_is_initialized = true;\n  }\n  SSL_METHOD* method = NULL;\n  SSL_CTX* ssl_ctx = NULL;\n  method = (SSL_METHOD*)SSLv23_client_method();\n  ssl_ctx = SSL_CTX_new(method);\n  if(!ssl_ctx) {\n    slowlog(LOG_ERROR, \"cannot create new SSL context\\n\");\n    close();\n    return false;\n  }\n  ssl_ = SSL_new(ssl_ctx);\n  if(!ssl_) {\n    slowlog(LOG_ERROR, \"cannot create SSL structure for a connection\\n\");\n    close();\n    return false;\n  }\n  SSL_set_fd(ssl_, sockfd_);\n  int ret = SSL_connect(ssl_);\n  if(ret <= 0) {\n    int err = SSL_get_error(ssl_, ret);\n    \/\/slowlog(LOG_ERROR, \"socket %d: SSL connect error: %d\\n\", sockfd_, err);\n    if(SSL_ERROR_WANT_READ != err && SSL_ERROR_WANT_WRITE != err) {\n      close();\n      return false;\n    }\n  }\n  return true;\n}\n\nint SlowSocket::recv_slow(void *buf, size_t len) {\n  int ret=ssl_ ? SSL_read(ssl_, buf, len)\n    : recv(sockfd_, buf, len, 0);\n  if(ssl_) {\n    if(ret <0) { \n      int err = SSL_get_error(ssl_, ret);\n      if(err == SSL_ERROR_WANT_WRITE) {\n        requests_to_send_ = 1;\n      }\n    } \n    if(SSL_is_init_finished(ssl_) && (state_ == eConnecting)) {\n      requests_to_send_ = 1;\n    }\n  } \n  return ret;\n}\n\nint SlowSocket::send_slow(const void* buf, size_t len, const SendType type) {\n  int ret;\n  if(ssl_) {\n    if(!SSL_is_init_finished(ssl_)) {\n      ret = SSL_do_handshake(ssl_);\n      if(ret <= 0) {\n        int err = SSL_get_error(ssl_, ret);\n        if(SSL_ERROR_WANT_READ != err && SSL_ERROR_WANT_WRITE != err) {\n          slowlog(LOG_ERROR, \"socket %d: SSL connect error: %d\\n\", sockfd_, err);\n          close();\n          return -1;\n        } else {\n          if(SSL_ERROR_WANT_READ == err) {\n            requests_to_send_=0;\n          }\n          else {\n            requests_to_send_=1;\n          }\n          errno = EAGAIN;\n          return -1;\n        }\n      } else { \/\/connected and handhsake finished\n        requests_to_send_=1;\n      }\n    } else {\n      if(requests_to_send_ > 0) { \/\/report for initial data only\n        slowlog(LOG_DEBUG, \"SSL connection is using %s\\n\", SSL_get_cipher(ssl_));\n      }\n    }\n  }\n  \/\/ VA: this is not good. create a \"prepare\" method.\n  \/\/ initial send\n  if(buf_ == 0) {\n    buf_ = buf;\n    offset_ = len;\n  }\n\n  ret = ssl_ ? SSL_write(ssl_, buf_, offset_)\n                 : send(sockfd_, buf_, offset_, 0);\n\n  \/\/ entire data was sent\n  if(ret > 0 && ret == offset_) {\n    if(eInitialSend == type) {\n      --requests_to_send_;\n    } else if(eFollowUpSend == type) {\n      --followups_to_send_;\n    }\n    buf_ = 0;\n    offset_ = 0;\n  } else if(ret > 0 && ret < offset_) {\n    buf_ = static_cast(buf_) + ret;\n    offset_ -= ret;\n  }  \n  return ret;\n}\n\nvoid SlowSocket::close() {\n  if (-1 == sockfd_) return;\n\n  slowlog(LOG_DEBUG, \"closing slow, sock is %d\\n\", sockfd_);\n  if(ssl_) {\n    SSL_free(ssl_);\n    ssl_ = NULL;\n  }\n  requests_to_send_ = 0;\n  followups_to_send_ = 0;\n  ::close(sockfd_);\n  sockfd_ = -1;\n}\n\nvoid SlowSocket::set_state(SocketState state) {\n  timeval t;\n  gettimeofday(&t, 0);\n  switch(state) {\n    case eInit:\n      break;\n    case eConnecting:\n      set_start(&t);\n      break;\n    case eConnected:\n      set_connected(&t);\n      break;\n    case eError:\n      break;\n    case eClosed:\n      set_stop(&t);\n      break;\n    default:\n      break;\n  } \n  state_ = state;\n}\n\n\n\n}  \/\/ namespace slowhttptest\nFormatting fixes\/*****************************************************************************\n*  Copyright 2011 Sergey Shekyan\n*\n*  Licensed under the Apache License, Version 2.0 (the \"License\");\n*  you may not use this file except in compliance with the License.\n*  You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n* *****************************************************************************\/\n\n\/*****\n * Author: Sergey Shekyan sshekyan@qualys.com\n *\n * Slow HTTP attack  vulnerability test tool\n *  http:\/\/code.google.com\/p\/slowhttptest\/\n *****\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"slowlog.h\"\n#include \"slowsocket.h\"\n#include \"slowurl.h\"\n\nnamespace slowhttptest {\nSlowSocket::SlowSocket()\n    : sockfd_(-1), requests_to_send_(0),\n      followups_to_send_(0), last_followup_timing_(0),\n      offset_(0), ssl_(0), buf_(0), \n      start_in_millisecs_(0), connected_in_millisecs_(0),\n      stop_in_millisecs_(0), state_(eInit) {\n}\n\nSlowSocket::~SlowSocket() {\n  close();\n}\n\nint SlowSocket::set_nonblocking() {\n  int flags;\n\n  if(-1 == (flags = fcntl(sockfd_, F_GETFL, 0))) {\n    flags = 0;\n  }\n  return fcntl(sockfd_, F_SETFL, flags | O_NONBLOCK);\n}\n\nbool SlowSocket::init(addrinfo* addr, const Url* url, int& maxfd,\n                      int followups_to_send) {\n  addrinfo* res;\n  bool connect_initiated_ = false;\n  for (res = addr; !connect_initiated_ && res; res = res->ai_next) {\n    sockfd_ = socket(res->ai_family, res->ai_socktype,\n                     res->ai_protocol);\n    if(-1 == sockfd_) {\n      slowlog(LOG_ERROR, \"failed to create socket: %s\\n\", strerror(errno));\n      return false;\n    }\n\n    if(-1 == set_nonblocking()) {\n      slowlog(LOG_ERROR, \"failed to set socket %d to non-blocking \\n\", sockfd_);\n      return false;\n    }\n\n    slowlog(LOG_DEBUG, \"non-blocking socket fd = %d created\\n\", sockfd_);\n    if(connect_initiated_ = url->isSSL() ? connect_ssl(addr) : connect_plain(addr)) {\n      break; \/\/found right addrinfo\n    }\n  }\n\n\n  followups_to_send_ = followups_to_send;\n  requests_to_send_ = 1;\n\n  maxdf = max(sockfd_, maxfd);\n  return true;\n}\n\nbool SlowSocket::connect_plain(addrinfo* addr) {\n  errno = 0;\n\n  if (connect(sockfd_, addr->ai_addr, addr->ai_addrlen) < 0\n      && EINPROGRESS != errno) {\n    slowlog(LOG_ERROR, \"cannot connect socket %d: %s\\n\", sockfd_, strerror(errno));\n    close();\n    return false;\n  }\n  return true;\n}\n\nbool SlowSocket::connect_ssl(addrinfo* addr) {\n  \/\/ Establish regular connection.\n  if(!connect_plain(addr))  return false;\n   \n  \/\/ Init SSL related stuff.\n  \/\/ TODO(vagababov): this is not thread safe of pretty.\n  static bool ssl_is_initialized = false;\n  if (!ssl_is_initialized) {\n    SSL_library_init();\n    ssl_is_initialized = true;\n  }\n  SSL_METHOD* method = NULL;\n  SSL_CTX* ssl_ctx = NULL;\n  method = (SSL_METHOD*)SSLv23_client_method();\n  ssl_ctx = SSL_CTX_new(method);\n  if(!ssl_ctx) {\n    slowlog(LOG_ERROR, \"cannot create new SSL context\\n\");\n    close();\n    return false;\n  }\n  ssl_ = SSL_new(ssl_ctx);\n  if(!ssl_) {\n    slowlog(LOG_ERROR, \"cannot create SSL structure for a connection\\n\");\n    close();\n    return false;\n  }\n  SSL_set_fd(ssl_, sockfd_);\n  int ret = SSL_connect(ssl_);\n  if(ret <= 0) {\n    int err = SSL_get_error(ssl_, ret);\n    \/\/slowlog(LOG_ERROR, \"socket %d: SSL connect error: %d\\n\", sockfd_, err);\n    if(SSL_ERROR_WANT_READ != err && SSL_ERROR_WANT_WRITE != err) {\n      close();\n      return false;\n    }\n  }\n  return true;\n}\n\nint SlowSocket::recv_slow(void *buf, size_t len) {\n  int ret = ssl_ ? SSL_read(ssl_, buf, len)\n                 : recv(sockfd_, buf, len, 0);\n  if(ssl_) {\n    if(ret < 0) { \n      int err = SSL_get_error(ssl_, ret);\n      if(err == SSL_ERROR_WANT_WRITE) {\n        requests_to_send_ = 1;\n      }\n    } \n    if(SSL_is_init_finished(ssl_) && (state_ == eConnecting)) {\n      requests_to_send_ = 1;\n    }\n  } \n  return ret;\n}\n\nint SlowSocket::send_slow(const void* buf, size_t len, const SendType type) {\n  int ret;\n  if(ssl_) {\n    if(!SSL_is_init_finished(ssl_)) {\n      ret = SSL_do_handshake(ssl_);\n      if(ret <= 0) {\n        int err = SSL_get_error(ssl_, ret);\n        if(SSL_ERROR_WANT_READ != err && SSL_ERROR_WANT_WRITE != err) {\n          slowlog(LOG_ERROR, \"socket %d: SSL connect error: %d\\n\", sockfd_, err);\n          close();\n          return -1;\n        } else {\n          if(SSL_ERROR_WANT_READ == err) {\n            requests_to_send_=0;\n          }\n          else {\n            requests_to_send_=1;\n          }\n          errno = EAGAIN;\n          return -1;\n        }\n      } else { \/\/connected and handhsake finished\n        requests_to_send_=1;\n      }\n    } else {\n      if(requests_to_send_ > 0) { \/\/report for initial data only\n        slowlog(LOG_DEBUG, \"SSL connection is using %s\\n\", SSL_get_cipher(ssl_));\n      }\n    }\n  }\n  \/\/ VA: this is not good. create a \"prepare\" method.\n  \/\/ initial send\n  if(buf_ == 0) {\n    buf_ = buf;\n    offset_ = len;\n  }\n\n  ret = ssl_ ? SSL_write(ssl_, buf_, offset_)\n                 : send(sockfd_, buf_, offset_, 0);\n\n  \/\/ entire data was sent\n  if(ret > 0 && ret == offset_) {\n    if(eInitialSend == type) {\n      --requests_to_send_;\n    } else if(eFollowUpSend == type) {\n      --followups_to_send_;\n    }\n    buf_ = 0;\n    offset_ = 0;\n  } else if(ret > 0 && ret < offset_) {\n    buf_ = static_cast(buf_) + ret;\n    offset_ -= ret;\n  }  \n  return ret;\n}\n\nvoid SlowSocket::close() {\n  if (-1 == sockfd_) return;\n\n  slowlog(LOG_DEBUG, \"closing slow, sock is %d\\n\", sockfd_);\n  if(ssl_) {\n    SSL_free(ssl_);\n    ssl_ = NULL;\n  }\n  requests_to_send_ = 0;\n  followups_to_send_ = 0;\n  ::close(sockfd_);\n  sockfd_ = -1;\n}\n\nvoid SlowSocket::set_state(SocketState state) {\n  timeval t;\n  gettimeofday(&t, 0);\n  switch(state) {\n    case eInit:\n      break;\n    case eConnecting:\n      set_start(&t);\n      break;\n    case eConnected:\n      set_connected(&t);\n      break;\n    case eError:\n      break;\n    case eClosed:\n      set_stop(&t);\n      break;\n    default:\n      break;\n  } \n  state_ = state;\n}\n\n\n\n}  \/\/ namespace slowhttptest\n<|endoftext|>"}
{"text":"\/*\n * Copyright 2004-2015 Cray Inc.\n * Other additional copyright holders may be indicated within.\n *\n * The entirety of this work is licensed under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"ScopeBase.h\"\n\n#include \"AstDumpToNode.h\"\n#include \"ScopeModule.h\"\n#include \"stmt.h\"\n#include \"symbol.h\"\n#include \"VisibleSymbol.h\"\n\n\/************************************ | *************************************\n*                                                                           *\n*                                                                           *\n*                                                                           *\n************************************* | ************************************\/\n\nScopeBase::ScopeBase(const ScopeBase* parent)\n{\n  mParent = parent;\n}\n\nScopeBase::~ScopeBase()\n{\n\n}\n\nvoid ScopeBase::extend(BlockStmt* block)\n{\n  std::vector visited;\n\n  extend(block, visited);\n}\n\nvoid ScopeBase::extend(BlockStmt*                  block,\n                       std::vector& visited)\n{\n  for_alist(stmt, block->body)\n  {\n    if (DefExpr* defExpr = toDefExpr(stmt))\n    {\n      addSym(defExpr->sym);\n    }\n    else if (CallExpr* callExpr = toCallExpr(stmt))\n    {\n      if (callExpr->isPrimitive(PRIM_USE) == true)\n        addUse(callExpr->get(1));\n    }\n  }\n}\n\nvoid ScopeBase::addSym(Symbol* symbol)\n{\n  if (isConflicted(symbol) == false)\n    mSymbols.push_back(symbol);\n}\n\nvoid ScopeBase::addUse(Expr* expr)\n{\n  if (ModuleSymbol* module = moduleByName(expr))\n  {\n    addUse(module);\n  }\n  else\n  {\n    AstDumpToNode logger(stdout, 3);\n\n    printf(\"ScopeBase::extend: Failed to find module for\\n\");\n    printf(\"   \");\n    expr->accept(&logger);\n    printf(\"\\n\\n\");\n  }\n}\n\nvoid ScopeBase::addUse(ModuleSymbol* module)\n{\n  std::vector visited;\n\n  addUse(module, visited);\n}\n\nvoid ScopeBase::addUse(ModuleSymbol*               module,\n                       std::vector& visited)\n{\n  if (isConflicted(module)       == false &&\n      isVisited(module, visited) == false)\n  {\n    ScopeModule* usedScope = new ScopeModule(module);\n\n    mUsedScopes.push_back(usedScope);\n\n    visited.push_back(module);\n  }\n}\n\nModuleSymbol* ScopeBase::moduleByName(Expr* expr) const\n{\n  ModuleSymbol* retval = 0;\n\n  if (UnresolvedSymExpr* unres = toUnresolvedSymExpr(expr))\n  {\n    std::vector symbols;\n\n    visibleSymbols(unres, symbols);\n\n    if (symbols.size() == 0)\n    {\n      const char* name = unres->unresolved;\n\n      forv_Vec(ModuleSymbol, mod, gModuleSymbols)\n      {\n        if (strcmp(mod->name, name) == 0)\n        {\n          retval = mod;\n          break;\n        }\n      }\n    }\n    else\n      retval = toModuleSymbol(symbols[0].symbol());\n  }\n\n  return retval;\n}\n\nbool ScopeBase::isVisited(ModuleSymbol*               module,\n                          std::vector& visited)\n{\n  bool retval = false;\n\n  for (size_t i = 0; i < visited.size() && retval == false; i++)\n    retval = (visited[i] == module) ? true : false;\n\n  return retval;\n}\n\n\n\/\/ A scope can have many definitions for a function but\n\/\/ only one definition for other symbols\nbool ScopeBase::isConflicted(Symbol* sym) const\n{\n  bool retval = false;\n\n  if (isFnSymbol(sym) == false)\n  {\n    for (size_t i = 0; i < mSymbols.size() && retval == false; i++)\n    {\n      if (mSymbols[i] == sym)\n      {\n        AstDumpToNode logger(stdout, 3);\n\n        printf(\"Error: Symbol is redefined\\n\");\n        printf(\"   \");\n        sym->accept(&logger);\n        printf(\"\\n\");\n\n        retval = true;\n      }\n    }\n  }\n\n  return retval;\n}\n\n\/\/ It would be surprising if a module were 'used' more than\n\/\/ once in a single scope\nbool ScopeBase::isConflicted(ModuleSymbol* mod) const\n{\n  bool retval = false;\n\n  for (size_t i = 0; i < mUsedScopes.size() && retval == false; i++)\n  {\n    if (mUsedScopes[i]->isScopeForModule(mod) == true)\n    {\n      AstDumpToNode logger(stdout, 3);\n\n      printf(\"Warning: Module is 'used' more than once in one scope\\n\");\n      printf(\"   \");\n      mod->accept(&logger);\n      printf(\"\\n\");\n\n      retval = true;\n    }\n  }\n\n  return retval;\n}\n\n\n\/************************************ | *************************************\n*                                                                           *\n*                                                                           *\n*                                                                           *\n************************************* | ************************************\/\n\nvoid ScopeBase::visibleSymbols(UnresolvedSymExpr*          unres,\n                               std::vector& symbols) const\n{\n  visibleSymbols(unres, symbols, 0);\n}\n\nvoid ScopeBase::visibleSymbols(UnresolvedSymExpr*          unres,\n                               std::vector& symbols,\n                               int                         distance)  const\n{\n  const char* needle = unres->unresolved;\n\n  for (size_t i = 0; i < mSymbols.size(); i++)\n  {\n    if (mSymbols[i]->name == needle)\n    {\n      VisibleSymbol vis(mSymbols[i], this, distance);\n\n      symbols.push_back(vis);\n    }\n  }\n\n  for (size_t i = 0; i < mUsedScopes.size(); i++)\n  {\n    mUsedScopes[i]->visibleSymbols(unres, symbols, distance + 1);\n  }\n\n  if (mParent != 0)\n  {\n    mParent->visibleSymbols(unres, symbols, distance + 1);\n  }\n}\n\n\/************************************ | *************************************\n*                                                                           *\n*                                                                           *\n*                                                                           *\n************************************* | ************************************\/\n\nvoid ScopeBase::describe(bool recursive) const\n{\n  printf(\"#name);\n\n  if (mUsedScopes.size() > 0)\n  {\n    printf(\"\\n\");\n    printf(\"   modUses:\\n\");\n\n    for (size_t i = 0; i < mUsedScopes.size(); i++)\n      printf(\"       %3ld: %s\\n\", i, mUsedScopes[i]->name());\n  }\n\n  printf(\">\\n\\n\");\n\n  if (recursive == true)\n  {\n    for (size_t i = 0; i < mUsedScopes.size(); i++)\n      mUsedScopes[i]->describe(true);\n\n    if (mParent != 0)\n      mParent->describe(true);\n  }\n}\nFix size_t vs int issue for linux32 smoke test\/*\n * Copyright 2004-2015 Cray Inc.\n * Other additional copyright holders may be indicated within.\n *\n * The entirety of this work is licensed under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"ScopeBase.h\"\n\n#include \"AstDumpToNode.h\"\n#include \"ScopeModule.h\"\n#include \"stmt.h\"\n#include \"symbol.h\"\n#include \"VisibleSymbol.h\"\n\n\/************************************ | *************************************\n*                                                                           *\n*                                                                           *\n*                                                                           *\n************************************* | ************************************\/\n\nScopeBase::ScopeBase(const ScopeBase* parent)\n{\n  mParent = parent;\n}\n\nScopeBase::~ScopeBase()\n{\n\n}\n\nvoid ScopeBase::extend(BlockStmt* block)\n{\n  std::vector visited;\n\n  extend(block, visited);\n}\n\nvoid ScopeBase::extend(BlockStmt*                  block,\n                       std::vector& visited)\n{\n  for_alist(stmt, block->body)\n  {\n    if (DefExpr* defExpr = toDefExpr(stmt))\n    {\n      addSym(defExpr->sym);\n    }\n    else if (CallExpr* callExpr = toCallExpr(stmt))\n    {\n      if (callExpr->isPrimitive(PRIM_USE) == true)\n        addUse(callExpr->get(1));\n    }\n  }\n}\n\nvoid ScopeBase::addSym(Symbol* symbol)\n{\n  if (isConflicted(symbol) == false)\n    mSymbols.push_back(symbol);\n}\n\nvoid ScopeBase::addUse(Expr* expr)\n{\n  if (ModuleSymbol* module = moduleByName(expr))\n  {\n    addUse(module);\n  }\n  else\n  {\n    AstDumpToNode logger(stdout, 3);\n\n    printf(\"ScopeBase::extend: Failed to find module for\\n\");\n    printf(\"   \");\n    expr->accept(&logger);\n    printf(\"\\n\\n\");\n  }\n}\n\nvoid ScopeBase::addUse(ModuleSymbol* module)\n{\n  std::vector visited;\n\n  addUse(module, visited);\n}\n\nvoid ScopeBase::addUse(ModuleSymbol*               module,\n                       std::vector& visited)\n{\n  if (isConflicted(module)       == false &&\n      isVisited(module, visited) == false)\n  {\n    ScopeModule* usedScope = new ScopeModule(module);\n\n    mUsedScopes.push_back(usedScope);\n\n    visited.push_back(module);\n  }\n}\n\nModuleSymbol* ScopeBase::moduleByName(Expr* expr) const\n{\n  ModuleSymbol* retval = 0;\n\n  if (UnresolvedSymExpr* unres = toUnresolvedSymExpr(expr))\n  {\n    std::vector symbols;\n\n    visibleSymbols(unres, symbols);\n\n    if (symbols.size() == 0)\n    {\n      const char* name = unres->unresolved;\n\n      forv_Vec(ModuleSymbol, mod, gModuleSymbols)\n      {\n        if (strcmp(mod->name, name) == 0)\n        {\n          retval = mod;\n          break;\n        }\n      }\n    }\n    else\n      retval = toModuleSymbol(symbols[0].symbol());\n  }\n\n  return retval;\n}\n\nbool ScopeBase::isVisited(ModuleSymbol*               module,\n                          std::vector& visited)\n{\n  bool retval = false;\n\n  for (size_t i = 0; i < visited.size() && retval == false; i++)\n    retval = (visited[i] == module) ? true : false;\n\n  return retval;\n}\n\n\n\/\/ A scope can have many definitions for a function but\n\/\/ only one definition for other symbols\nbool ScopeBase::isConflicted(Symbol* sym) const\n{\n  bool retval = false;\n\n  if (isFnSymbol(sym) == false)\n  {\n    for (size_t i = 0; i < mSymbols.size() && retval == false; i++)\n    {\n      if (mSymbols[i] == sym)\n      {\n        AstDumpToNode logger(stdout, 3);\n\n        printf(\"Error: Symbol is redefined\\n\");\n        printf(\"   \");\n        sym->accept(&logger);\n        printf(\"\\n\");\n\n        retval = true;\n      }\n    }\n  }\n\n  return retval;\n}\n\n\/\/ It would be surprising if a module were 'used' more than\n\/\/ once in a single scope\nbool ScopeBase::isConflicted(ModuleSymbol* mod) const\n{\n  bool retval = false;\n\n  for (size_t i = 0; i < mUsedScopes.size() && retval == false; i++)\n  {\n    if (mUsedScopes[i]->isScopeForModule(mod) == true)\n    {\n      AstDumpToNode logger(stdout, 3);\n\n      printf(\"Warning: Module is 'used' more than once in one scope\\n\");\n      printf(\"   \");\n      mod->accept(&logger);\n      printf(\"\\n\");\n\n      retval = true;\n    }\n  }\n\n  return retval;\n}\n\n\n\/************************************ | *************************************\n*                                                                           *\n*                                                                           *\n*                                                                           *\n************************************* | ************************************\/\n\nvoid ScopeBase::visibleSymbols(UnresolvedSymExpr*          unres,\n                               std::vector& symbols) const\n{\n  visibleSymbols(unres, symbols, 0);\n}\n\nvoid ScopeBase::visibleSymbols(UnresolvedSymExpr*          unres,\n                               std::vector& symbols,\n                               int                         distance)  const\n{\n  const char* needle = unres->unresolved;\n\n  for (size_t i = 0; i < mSymbols.size(); i++)\n  {\n    if (mSymbols[i]->name == needle)\n    {\n      VisibleSymbol vis(mSymbols[i], this, distance);\n\n      symbols.push_back(vis);\n    }\n  }\n\n  for (size_t i = 0; i < mUsedScopes.size(); i++)\n  {\n    mUsedScopes[i]->visibleSymbols(unres, symbols, distance + 1);\n  }\n\n  if (mParent != 0)\n  {\n    mParent->visibleSymbols(unres, symbols, distance + 1);\n  }\n}\n\n\/************************************ | *************************************\n*                                                                           *\n*                                                                           *\n*                                                                           *\n************************************* | ************************************\/\n\nvoid ScopeBase::describe(bool recursive) const\n{\n  printf(\"#name);\n\n  if (mUsedScopes.size() > 0)\n  {\n    printf(\"\\n\");\n    printf(\"   modUses:\\n\");\n\n    for (size_t i = 0; i < mUsedScopes.size(); i++)\n      printf(\"       %3d: %s\\n\", (int) i, mUsedScopes[i]->name());\n  }\n\n  printf(\">\\n\\n\");\n\n  if (recursive == true)\n  {\n    for (size_t i = 0; i < mUsedScopes.size(); i++)\n      mUsedScopes[i]->describe(true);\n\n    if (mParent != 0)\n      mParent->describe(true);\n  }\n}\n<|endoftext|>"}
{"text":"#ifndef ALEPH_TOPOLOGY_MESH_HH__\n#define ALEPH_TOPOLOGY_MESH_HH__\n\n#include \n\n#include \n#include \n#include \n#include \n\nnamespace aleph\n{\n\nnamespace topology\n{\n\n\/**\n  @class Mesh\n  @brief Half-edge mesh data structure\n\n  This data structure is capable of representing two-dimensional piecewise\n  linear manifolds. In order to speed up standard queries, this class uses\n  a standard half-edge data structure.\n*\/\n\ntemplate  class Mesh\n{\npublic:\n  struct Face;\n  struct HalfEdge;\n  struct Vertex;\n\n  using Index           = std::size_t;\n\n  using FacePointer     = std::shared_ptr;\n  using HalfEdgePointer = std::shared_ptr;\n  using VertexPointer   = std::shared_ptr;\n\n  struct HalfEdge\n  {\n    FacePointer   face;\n    VertexPointer vertex;\n\n    HalfEdgePointer next; \/\/ Next half-edge (counter-clockwise)\n    HalfEdgePointer prev; \/\/ Previous half-edge\n    HalfEdgePointer pair; \/\/ Opposite half-edge\n\n    VertexPointer source() const noexcept\n    {\n      return pair->vertex;\n    }\n\n    VertexPointer target() const noexcept\n    {\n      return vertex;\n    }\n  };\n\n  struct Face\n  {\n    HalfEdgePointer edge;\n  };\n\n  struct Vertex\n  {\n    Position x = Position();\n    Position y = Position();\n    Position z = Position();\n    Data     d = Data();\n\n    HalfEdgePointer edge;\n  };\n\n  \/\/ Mesh attributes ---------------------------------------------------\n\n  std::size_t vertices() const noexcept\n  {\n    return _vertices.size();\n  }\n\n  std::size_t faces() const noexcept\n  {\n    \/\/ TODO: Not yet implemented\n    return 0;\n  }\n\n  \/\/ Mesh modification -------------------------------------------------\n\n  \/** Adds a new vertex to the mesh *\/\n  void addVertex( Position x, Position y, Position z, Data d = Data() )\n  {\n    Vertex v;\n\n    v.x = x;\n    v.y = y;\n    v.z = z;\n    v.d = d;\n\n    _vertices.push_back( std::make_shared( v ) );\n  }\n\n  \/**\n    Adds a new face to the mesh. This function expects a range of vertex IDs\n    that make up the face. The vertices of the face need to sorted correctly\n    in order for the orientation to be consistent.\n  *\/\n\n  template  void addFace( InputIterator begin, InputIterator end )\n  {\n    FacePointer face = std::make_shared();\n\n    \/\/ Stores all half-edges created (or found) by this function in the\n    \/\/ order in which they belong to the face.\n    std::vector edges;\n    edges.reserve( std::distance( begin, end ) );\n\n    for( InputIterator it = begin; it != end; ++it )\n    {\n      auto curr = it;\n      auto next = std::next( it );\n\n      if( next == end )\n        next = begin;\n\n      auto source = _vertices.at( *curr );   \/\/ Edge source vertex\n      auto target = _vertices.at( *next );   \/\/ Edge target vertex\n      auto edge   = getEdge( *curr, *next ); \/\/ Edge\n\n      if( !edge )\n      {\n        edge      = std::make_shared();\n        auto pair = std::make_shared();\n\n        edge->face   = face;\n        edge->pair   = pair;\n        edge->vertex = target;\n        pair->vertex = source;\n        pair->pair   = edge;\n\n        if( !source->edge )\n          source->edge = edge;\n\n        if( !target->edge )\n          target->edge = pair;\n      }\n      else\n      {\n        assert( !edge->face );\n        edge->face = face;\n      }\n\n      edges.push_back( edge );\n    }\n\n    \/\/ Set 'next' and 'prev' pointers correctly ------------------------\n    \/\/\n    \/\/ We first traverse all edges that bound the current face. Here, it\n    \/\/ should be possible to traverse the face directly, so we require a\n    \/\/ proper pointer in both directions.\n\n    for( auto itEdge = edges.begin(); itEdge != edges.end(); ++itEdge )\n    {\n      auto curr = itEdge;\n      auto prev = std::prev( curr );\n      auto next = std::next( curr );\n\n      if( curr == edges.begin() )\n        prev = std::prev( edges.end() );\n\n      if( next == edges.end() )\n        next = edges.begin();\n\n      auto&& edge = *itEdge;\n\n      assert( !edge->next );\n      assert( !edge->prev );\n\n      edge->next = *next;\n      edge->prev = *prev;\n    }\n  }\n\n  \/\/ Mesh queries ------------------------------------------------------\n\n  std::vector getLowerNeighbours( const Vertex& v ) const noexcept\n  {\n    auto neighbours = this->getNeighbours( v );\n    auto d          = v.d;\n\n    neighbours.erase( std::remove_if( neighbours.begin(), neighbours.end(),\n                                      [&d] ( const VertexPointer& neighbour )\n                                      {\n                                        return neighbour->d >= d;\n                                      } ),\n                      neighbours.end() );\n\n    return neighbours;\n  }\n\n  std::vector getHigherNeighbours( const Vertex& v ) const noexcept\n  {\n    auto neighbours = this->getNeighbours( v );\n    auto d          = v.d;\n\n    neighbours.erase( std::remove_if( neighbours.begin(), neighbours.end(),\n                                      [&d] ( const VertexPointer& neighbour )\n                                      {\n                                        return neighbour->d <= d;\n                                      } ),\n                      neighbours.end() );\n\n    return neighbours;\n  }\n\n  VertexPointer vertex( std::size_t id ) const\n  {\n    return _vertices.at( id );\n  }\n\nprivate:\n\n  \/** Gets all vertices that are adjacent to a given vertex *\/\n  std::vector getNeighbours( const Vertex& v ) const noexcept\n  {\n    std::vector neighbours;\n\n    auto edge = v.edge;\n    do\n    {\n      if( edge )\n        neighbours.push_back( edge->target() );\n      else\n        break;\n\n      edge = edge->pair->next;\n    }\n    while( edge != v.edge );\n\n    return neighbours;\n  }\n\n  \/** Gets all edges that are incident on a given vertex. *\/\n  std::vector getEdges( const Vertex& v ) const noexcept\n  {\n    std::vector edges;\n\n    auto edge = v.edge;\n    do\n    {\n      if( edge )\n        edges.push_back( edge );\n      else\n        break;\n\n      edge = edge->pair->next;\n    }\n    while( edge != v.edge );\n\n    return edges;\n  }\n\n  \/**\n    Check whether a given (directed) edge already exists. If so,\n    a pointer to the edge is being returned.\n  *\/\n\n  HalfEdgePointer getEdge( Index u, Index v ) const noexcept\n  {\n    auto source = _vertices.at(u);           \/\/ Edge source vertex\n    auto target = _vertices.at(v);           \/\/ Edge target vertex\n    auto edges  = this->getEdges( *source ); \/\/ Incident edges\n\n    auto itEdge = std::find_if( edges.begin(), edges.end(),\n                                [&source, &target] ( const HalfEdgePointer& edge )\n                                {\n                                  return edge->source() == source && edge->target() == target;\n                                } );\n\n    if( itEdge != edges.end() )\n      return *itEdge;\n    else\n      return nullptr;\n  }\n\n  \/**\n    Stores all vertex pointers. This is sufficient to store the\n    complete mesh.\n  *\/\n\n  std::vector _vertices;\n};\n\n} \/\/ namespace topology\n\n} \/\/ namespace aleph\n\n#endif\nImplemented vertices & faces query for meshes#ifndef ALEPH_TOPOLOGY_MESH_HH__\n#define ALEPH_TOPOLOGY_MESH_HH__\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace aleph\n{\n\nnamespace topology\n{\n\n\/**\n  @class Mesh\n  @brief Half-edge mesh data structure\n\n  This data structure is capable of representing two-dimensional piecewise\n  linear manifolds. In order to speed up standard queries, this class uses\n  a standard half-edge data structure.\n*\/\n\ntemplate  class Mesh\n{\npublic:\n  struct Face;\n  struct HalfEdge;\n  struct Vertex;\n\n  using Index           = std::size_t;\n\n  using FacePointer     = std::shared_ptr;\n  using HalfEdgePointer = std::shared_ptr;\n  using VertexPointer   = std::shared_ptr;\n\n  struct HalfEdge\n  {\n    FacePointer   face;\n    VertexPointer vertex;\n\n    HalfEdgePointer next; \/\/ Next half-edge (counter-clockwise)\n    HalfEdgePointer prev; \/\/ Previous half-edge\n    HalfEdgePointer pair; \/\/ Opposite half-edge\n\n    VertexPointer source() const noexcept\n    {\n      return pair->vertex;\n    }\n\n    VertexPointer target() const noexcept\n    {\n      return vertex;\n    }\n  };\n\n  struct Face\n  {\n    HalfEdgePointer edge;\n  };\n\n  struct Vertex\n  {\n    Position x = Position();\n    Position y = Position();\n    Position z = Position();\n    Data     d = Data();\n\n    HalfEdgePointer edge;\n  };\n\n  \/\/ Mesh attributes ---------------------------------------------------\n\n  std::size_t vertices() const noexcept\n  {\n    return _vertices.size();\n  }\n\n  std::size_t faces() const noexcept\n  {\n    std::unordered_set faces;\n\n    for( auto&& vertex : _vertices )\n    {\n      auto&& edge = vertex->edge;\n      auto&& face = edge->face;\n\n      faces.insert( face );\n    }\n\n    return faces.size();\n  }\n\n  \/\/ Mesh modification -------------------------------------------------\n\n  \/** Adds a new vertex to the mesh *\/\n  void addVertex( Position x, Position y, Position z, Data d = Data() )\n  {\n    Vertex v;\n\n    v.x = x;\n    v.y = y;\n    v.z = z;\n    v.d = d;\n\n    _vertices.push_back( std::make_shared( v ) );\n  }\n\n  \/**\n    Adds a new face to the mesh. This function expects a range of vertex IDs\n    that make up the face. The vertices of the face need to sorted correctly\n    in order for the orientation to be consistent.\n  *\/\n\n  template  void addFace( InputIterator begin, InputIterator end )\n  {\n    FacePointer face = std::make_shared();\n\n    \/\/ Stores all half-edges created (or found) by this function in the\n    \/\/ order in which they belong to the face.\n    std::vector edges;\n    edges.reserve( std::distance( begin, end ) );\n\n    for( InputIterator it = begin; it != end; ++it )\n    {\n      auto curr = it;\n      auto next = std::next( it );\n\n      if( next == end )\n        next = begin;\n\n      auto source = _vertices.at( *curr );   \/\/ Edge source vertex\n      auto target = _vertices.at( *next );   \/\/ Edge target vertex\n      auto edge   = getEdge( *curr, *next ); \/\/ Edge\n\n      if( !edge )\n      {\n        edge      = std::make_shared();\n        auto pair = std::make_shared();\n\n        edge->face   = face;\n        edge->pair   = pair;\n        edge->vertex = target;\n        pair->vertex = source;\n        pair->pair   = edge;\n\n        if( !source->edge )\n          source->edge = edge;\n\n        if( !target->edge )\n          target->edge = pair;\n      }\n      else\n      {\n        assert( !edge->face );\n        edge->face = face;\n      }\n\n      edges.push_back( edge );\n    }\n\n    \/\/ Set 'next' and 'prev' pointers correctly ------------------------\n    \/\/\n    \/\/ We first traverse all edges that bound the current face. Here, it\n    \/\/ should be possible to traverse the face directly, so we require a\n    \/\/ proper pointer in both directions.\n\n    for( auto itEdge = edges.begin(); itEdge != edges.end(); ++itEdge )\n    {\n      auto curr = itEdge;\n      auto prev = std::prev( curr );\n      auto next = std::next( curr );\n\n      if( curr == edges.begin() )\n        prev = std::prev( edges.end() );\n\n      if( next == edges.end() )\n        next = edges.begin();\n\n      auto&& edge = *itEdge;\n\n      assert( !edge->next );\n      assert( !edge->prev );\n\n      edge->next = *next;\n      edge->prev = *prev;\n    }\n  }\n\n  \/\/ Mesh queries ------------------------------------------------------\n\n  std::vector getLowerNeighbours( const Vertex& v ) const noexcept\n  {\n    auto neighbours = this->getNeighbours( v );\n    auto d          = v.d;\n\n    neighbours.erase( std::remove_if( neighbours.begin(), neighbours.end(),\n                                      [&d] ( const VertexPointer& neighbour )\n                                      {\n                                        return neighbour->d >= d;\n                                      } ),\n                      neighbours.end() );\n\n    return neighbours;\n  }\n\n  std::vector getHigherNeighbours( const Vertex& v ) const noexcept\n  {\n    auto neighbours = this->getNeighbours( v );\n    auto d          = v.d;\n\n    neighbours.erase( std::remove_if( neighbours.begin(), neighbours.end(),\n                                      [&d] ( const VertexPointer& neighbour )\n                                      {\n                                        return neighbour->d <= d;\n                                      } ),\n                      neighbours.end() );\n\n    return neighbours;\n  }\n\n  VertexPointer vertex( std::size_t id ) const\n  {\n    return _vertices.at( id );\n  }\n\nprivate:\n\n  \/** Gets all vertices that are adjacent to a given vertex *\/\n  std::vector getNeighbours( const Vertex& v ) const noexcept\n  {\n    std::vector neighbours;\n\n    auto edge = v.edge;\n    do\n    {\n      if( edge )\n        neighbours.push_back( edge->target() );\n      else\n        break;\n\n      edge = edge->pair->next;\n    }\n    while( edge != v.edge );\n\n    return neighbours;\n  }\n\n  \/** Gets all edges that are incident on a given vertex. *\/\n  std::vector getEdges( const Vertex& v ) const noexcept\n  {\n    std::vector edges;\n\n    auto edge = v.edge;\n    do\n    {\n      if( edge )\n        edges.push_back( edge );\n      else\n        break;\n\n      edge = edge->pair->next;\n    }\n    while( edge != v.edge );\n\n    return edges;\n  }\n\n  \/**\n    Check whether a given (directed) edge already exists. If so,\n    a pointer to the edge is being returned.\n  *\/\n\n  HalfEdgePointer getEdge( Index u, Index v ) const noexcept\n  {\n    auto source = _vertices.at(u);           \/\/ Edge source vertex\n    auto target = _vertices.at(v);           \/\/ Edge target vertex\n    auto edges  = this->getEdges( *source ); \/\/ Incident edges\n\n    auto itEdge = std::find_if( edges.begin(), edges.end(),\n                                [&source, &target] ( const HalfEdgePointer& edge )\n                                {\n                                  return edge->source() == source && edge->target() == target;\n                                } );\n\n    if( itEdge != edges.end() )\n      return *itEdge;\n    else\n      return nullptr;\n  }\n\n  \/**\n    Stores all vertex pointers. This is sufficient to store the\n    complete mesh.\n  *\/\n\n  std::vector _vertices;\n};\n\n} \/\/ namespace topology\n\n} \/\/ namespace aleph\n\n#endif\n<|endoftext|>"}
{"text":"#ifndef _NODO_BINARY_TREE_HPP_\n#define _NODO_BINARY_TREE_HPP_\n#include \n\ntemplate\nclass NodeBT\n{\n\tprivate:\n\t\tT _key;\n\t\tNodeBT *_left, *_right;\n\t\t\n\tpublic:\n\t\tNodeBT() : _key(0), _left(NULL), _right(NULL) { };\n\t\tNodeBT(const T in) : _key(in), _left(NULL), _right(NULL) { };\n\t\tNodeBT(const NodeBT& in) : _key(in.key), _left(NULL), _right(NULL) { };\n\t\n\t\tT getKey() const { return _key; }\n\t\tNodeBT* getLeft() const { return _left; }\n\t\tNodeBT* getRight() const { return _right; }\n\t\tbool isLeaf() const { return _left == NULL && _right == NULL; }\n\t\tbool isFullNode() const { return _left != NULL || _right != NULL; }\n\n\t\tvoid setKey(const T);\n\t\tvoid setLeft(const NodeBT*);\n\t\tvoid setRight(const NodeBT*);\n};\n\n\/**\n * Key setter\n * *\/\ntemplate\nvoid NodeBT::setKey(const T item)\n{\n\t_key = item;\n}\n\n\/**\n * Left setter\n * *\/\ntemplate\nvoid NodeBT::setLeft(const NodeBT* l)\n{\n\t_left = l;\n}\n\n\/**\n * Right setter\n * *\/\ntemplate\nvoid NodeBT::setRight(const NodeBT* r)\n{\n\t_right = r;\n}\n\n#endif\nConstructor added#ifndef _NODO_BINARY_TREE_HPP_\n#define _NODO_BINARY_TREE_HPP_\n#include \n\ntemplate\nclass NodeBT\n{\n\tprivate:\n\t\tT _key;\n\t\tNodeBT *_left, *_right;\n\t\t\n\tpublic:\n\t\tNodeBT() : _key(0), _left(NULL), _right(NULL) { };\n\t\tNodeBT(const T in) : _key(in), _left(NULL), _right(NULL) { };\n\t\tNodeBT(const T in, NodeBT* l, NodeBT* r) : _key(in), _left(l), _right(r) { };\n\t\tNodeBT(const NodeBT& in) : _key(in.key), _left(NULL), _right(NULL) { };\n\t\n\t\tT getKey() const { return _key; }\n\t\tNodeBT* getLeft() const { return _left; }\n\t\tNodeBT* getRight() const { return _right; }\n\t\tbool isLeaf() const { return _left == NULL && _right == NULL; }\n\t\tbool isFullNode() const { return _left != NULL || _right != NULL; }\n\n\t\tvoid setKey(const T);\n\t\tvoid setLeft(const NodeBT*);\n\t\tvoid setRight(const NodeBT*);\n};\n\n\/**\n * Key setter\n * *\/\ntemplate\nvoid NodeBT::setKey(const T item)\n{\n\t_key = item;\n}\n\n\/**\n * Left setter\n * *\/\ntemplate\nvoid NodeBT::setLeft(const NodeBT* l)\n{\n\t_left = l;\n}\n\n\/**\n * Right setter\n * *\/\ntemplate\nvoid NodeBT::setRight(const NodeBT* r)\n{\n\t_right = r;\n}\n\n#endif\n<|endoftext|>"}
{"text":"#include \"AutomationEditor.h\"\n#include \"SDL.h\"\n#include \"ISynth.h\"\n#include \"IPlayer.h\"\n#include \"Renderer.h\"\n#include \"ModularSynth.h\"\n#include \"SynthModule.h\"\n#include \"EditorState.h\"\n#include \"ModuleSelector.h\"\n#include \"Color.h\"\n#include \"Synth.h\"\n#include \n#include \n#include \n#include \n\n\n\nAutomationEditor::AutomationEditor(EditorState& editorState, ISynth& synth, IPlayer& player)\n\t:Editor(editorState, true), mSynth(synth), mSelectedNode(-1), mSelectedTrack(0)\n{\n\tmEditorState.patternEditor.currentRow.addListener(this);\n\tmEditorState.sequenceEditor.currentRow.addListener(this);\n}\n\n\nAutomationEditor::~AutomationEditor()\n{\n}\n\n\nSDL_Rect AutomationEditor::getNodeArea(const SDL_Rect& parent, int index) const\n{\n\tconst Synth& synth = static_cast(mSynth);\n\tconst Synth::AutomationNode& node = getAutomationTrack().getNode(index);\n\n\treturn getNodeArea(parent, node);\n}\n\n\nSDL_Rect AutomationEditor::getNodeArea(const SDL_Rect& parent, const Synth::AutomationNode& node) const\n{\n\tconst int nodeWidth = 5;\n\tconst int nodeHeight = 5;\n\n\tSDL_Rect area = {\n\t\tnode.time + parent.x - nodeWidth \/ 2 - getScrollPosition(),\n\t\tstatic_cast((1.0f - node.value) * parent.h) + parent.y - nodeHeight \/ 2,\n\t\tnodeWidth, nodeHeight\n\t};\n\n\treturn area;\n}\n\n\nvoid AutomationEditor::onDraw(Renderer& renderer, const SDL_Rect& area)\n{\n\tsetDirty(false);\n\n\tif (mModal != NULL)\n\t{\n\t\treturn;\n\t}\n\n\trenderer.setClip(area);\n\trenderer.renderBackground(area);\n\n\tconst Synth& synth = getSynth();\n\tint patternLength = synth.getPatternLength();\n\n\tfor (int x = area.x - getScrollPosition() ; x < area.w + area.x ; x += patternLength)\n\t{\n\t\trenderer.renderLine(x, area.y, x, area.y + area.h, Color(64,64,64));\n\t}\n\n\tfloat time = synth.getSongPosition();\n\tint editPos = mEditorState.patternEditor.currentRow + mEditorState.sequenceEditor.currentRow * patternLength;\n\n\trenderer.renderLine(time - getScrollPosition() + area.x, area.y, time - getScrollPosition() + area.x, area.y + area.h, Color(0,0,128));\n\trenderer.renderLine(editPos - getScrollPosition() + area.x, area.y, editPos - getScrollPosition() + area.x, area.y + area.h, Color(255,255,255));\n\n\tfor (int track = 0 ; track < Synth::maxAutomationTracks ; ++track)\n\t{\n\t\tif (track == mSelectedTrack)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (synth.getAutomationTrack(track).numNodes > 0)\n\t\t{\n\t\t\tSDL_Rect nodeArea = getNodeArea(area, synth.getAutomationTrack(track).nodes[0]);\n\t\t\tint px = nodeArea.x + nodeArea.w \/ 2;\n\t\t\tint py = nodeArea.y + nodeArea.h \/ 2;\n\n\t\t\tfor (int i = 1 ; i < synth.getAutomationTrack(track).numNodes ; ++i)\n\t\t\t{\n\t\t\t\tSDL_Rect nodeArea = getNodeArea(area, synth.getAutomationTrack(track).nodes[i]);\n\t\t\t\tint x = nodeArea.x + nodeArea.w \/ 2;\n\t\t\t\tint y = nodeArea.y + nodeArea.h \/ 2;\n\n\t\t\t\trenderer.renderLine(px, py, x, y, track == mSelectedTrack ? Color(255, 255, 255) : Color(64, 64, 64));\n\n\t\t\t\tpx = x;\n\t\t\t\tpy = y;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tif (getAutomationTrack().numNodes > 0)\n\t{\n\t\tSDL_Rect nodeArea = getNodeArea(area, 0);\n\t\tint px = nodeArea.x + nodeArea.w \/ 2;\n\t\tint py = nodeArea.y + nodeArea.h \/ 2;\n\n\t\tfor (int i = 1 ; i < getAutomationTrack().numNodes ; ++i)\n\t\t{\n\t\t\tSDL_Rect nodeArea = getNodeArea(area, i);\n\t\t\tint x = nodeArea.x + nodeArea.w \/ 2;\n\t\t\tint y = nodeArea.y + nodeArea.h \/ 2;\n\n\t\t\trenderer.renderLine(px, py, x, y, Color(255, 255, 255));\n\n\t\t\tpx = x;\n\t\t\tpy = y;\n\t\t}\n\n\t\tfor (int i = 0 ; i < getAutomationTrack().numNodes ; ++i)\n\t\t{\n\t\t\tSDL_Rect nodeArea = getNodeArea(area, i);\n\t\t\trenderer.clearRect(nodeArea, mSelectedNode == i ? Color(255, 255, 255) : Color(255, 0, 0));\n\t\t}\n\t}\n\n\tconst SDL_Rect textArea = { area.x + area.w - renderer.getFontWidth() * 2 - 1, area.y + 1, 16, 16 };\n\trenderer.renderTextV(textArea, Color(192, 140, 32), \"%02d\", mSelectedTrack);\n}\n\n\nbool AutomationEditor::pickNode(int x, int y, const SDL_Rect& area, int& nodeOut) const\n{\n\tSDL_Point point = {x,y};\n\n\tfor (int i = 0 ; i < getAutomationTrack().numNodes ; ++i)\n\t{\n\t\tif (pointInRect(point, getNodeArea(area, i)))\n\t\t{\n\t\t\tnodeOut = i;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n\nbool AutomationEditor::onEvent(SDL_Event& event)\n{\n\tif (event.type == SDL_MOUSEBUTTONDOWN)\n\t{\n\t\t\/\/ Editor base class should probably do this when clicked\n\t\tsetFocus(this);\n\n\t\tmMouseX = event.button.x \/ SCALE;\n\t\tmMouseY = event.button.y \/ SCALE;\n\n\t\tswitch (event.button.button)\n\t\t{\n\t\t\tcase SDL_BUTTON_LEFT:\n\t\t\t\tif (event.button.clicks == 1)\n\t\t\t\t{\n\t\t\t\t\tint nodeIdx;\n\t\t\t\t\tif (pickNode(mMouseX, mMouseY, mThisArea, nodeIdx))\n\t\t\t\t\t{\n\t\t\t\t\t\tSynth::AutomationNode& node = getAutomationTrack().getNode(nodeIdx);\n\t\t\t\t\t\tmSelectedNode = nodeIdx;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tmSelectedNode = -1;\n\t\t\t\t\t}\n\t\t\t\t\tsetDirty(true);\n\t\t\t\t}\n\t\t\t\telse if (event.button.clicks == 2)\n\t\t\t\t{\n\t\t\t\t\tSynth& synth = static_cast(mSynth);\n\t\t\t\t\tSDL_Keymod modState = SDL_GetModState();\n\t\t\t\t\tint xGranularity = 1, yGranularity = 1;\n\n\t\t\t\t\tif (modState & KMOD_CTRL)\n\t\t\t\t\t{\n\t\t\t\t\t\txGranularity = synth.getPatternLength();\n\t\t\t\t\t\tyGranularity = mThisArea.h \/ 2;\n\t\t\t\t\t}\n\n\t\t\t\t\tmSelectedNode = getAutomationTrack().addNode(\n\t\t\t\t\t\tgranularize(mMouseX - mThisArea.x + getScrollPosition(), xGranularity),\n\t\t\t\t\t\t1.0f - static_cast(granularize(mMouseY - mThisArea.y, yGranularity)) \/ mThisArea.h\n\t\t\t\t\t);\n\t\t\t\t\tsetDirty(true);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn false;\n\t}\n\telse if (event.type == SDL_MOUSEMOTION)\n\t{\n\t\tmMouseX = event.motion.x \/ SCALE;\n\t\tmMouseY = event.motion.y \/ SCALE;\n\n\t\tif ((event.motion.state & SDL_BUTTON(SDL_BUTTON_LEFT)) && mSelectedNode != -1)\n\t\t{\n\t\t\tSynth& synth = static_cast(mSynth);\n\t\t\tSDL_Keymod modState = SDL_GetModState();\n\t\t\tint xGranularity = 1, yGranularity = 1;\n\t\t\tSynth::AutomationTrack& track = getAutomationTrack();\n\t\t\tSynth::AutomationNode& firstNode = track.getNode(mSelectedNode);\n\t\t\tint origTime = firstNode.time;\n\t\t\tfloat origValue = firstNode.value;\n\n\t\t\tif (modState & KMOD_CTRL)\n\t\t\t{\n\t\t\t\txGranularity = synth.getPatternLength() \/ 2;\n\t\t\t\tyGranularity = mThisArea.h \/ 2;\n\t\t\t}\n\n\t\t\ttrack.editNode(mSelectedNode,\n\t\t\t\tgranularize(mMouseX - mThisArea.x + getScrollPosition(), xGranularity),\n\t\t\t\t1.0f - static_cast(granularize(mMouseY - mThisArea.y, yGranularity)) \/ mThisArea.h\n\t\t\t);\n\n\t\t\tif (modState & KMOD_ALT)\n\t\t\t{\n\n\t\t\t\tint deltaTime = firstNode.time - origTime;\n\t\t\t\tfloat deltaValue = firstNode.value - origValue;\n\n\t\t\t\tfor (int nodeIdx = mSelectedNode + 1 ; nodeIdx < track.numNodes ; ++nodeIdx)\n\t\t\t\t{\n\t\t\t\t\tSynth::AutomationNode node = track.getNode(nodeIdx);\n\t\t\t\t\ttrack.editNode(nodeIdx,\n\t\t\t\t\t\tnode.time + deltaTime,\n\t\t\t\t\t\tnode.value + deltaValue\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\n\t\t\t}\n\t\t}\n\t}\n\telse if (event.type == SDL_MOUSEWHEEL)\n\t{\n\t\tmSelectedTrack = (mSelectedTrack + (event.wheel.y < 0 ? -1 : 1) + Synth::maxAutomationTracks) % Synth::maxAutomationTracks;\n\t\tmSelectedNode = -1;\n\t\tsetDirty(true);\n\t}\n\telse if (event.type == SDL_KEYDOWN)\n\t{\n\t\tswitch (event.key.keysym.sym)\n\t\t{\n\t\t\tcase SDLK_DELETE:\n\t\t\t\tif (mSelectedNode != -1)\n\t\t\t\t{\n\t\t\t\t\tgetAutomationTrack().removeNode(mSelectedNode);\n\t\t\t\t\tsetDirty(true);\n\t\t\t\t\tmSelectedNode = -1;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n\nvoid AutomationEditor::onListenableChange(Listenable *listenable)\n{\n\n}\n\n\nvoid AutomationEditor::onLoaded()\n{\n\n}\n\n\nint AutomationEditor::granularize(int value, int steps)\n{\n\tint newValue = value + steps \/ 2;\n\tnewValue = newValue - (newValue % steps);\n\treturn abs(newValue - value) < 4 ? newValue : value;\n}\n\n\nSynth& AutomationEditor::getSynth()\n{\n\treturn static_cast(mSynth);\n}\n\n\nSynth::AutomationTrack& AutomationEditor::getAutomationTrack()\n{\n\treturn getSynth().getAutomationTrack(mSelectedTrack);\n}\n\n\nconst Synth& AutomationEditor::getSynth() const\n{\n\treturn static_cast(mSynth);\n}\n\n\nconst Synth::AutomationTrack& AutomationEditor::getAutomationTrack() const\n{\n\treturn getSynth().getAutomationTrack(mSelectedTrack);\n}\n\n\nint AutomationEditor::getScrollPosition() const\n{\n\treturn std::max(0, mEditorState.patternEditor.currentRow + mEditorState.sequenceEditor.currentRow * getSynth().getPatternLength() - mThisArea.w \/ 2);\n}\nCode cleanup#include \"AutomationEditor.h\"\n#include \"SDL.h\"\n#include \"ISynth.h\"\n#include \"IPlayer.h\"\n#include \"Renderer.h\"\n#include \"ModularSynth.h\"\n#include \"SynthModule.h\"\n#include \"EditorState.h\"\n#include \"ModuleSelector.h\"\n#include \"Color.h\"\n#include \"Synth.h\"\n#include \n#include \n#include \n#include \n\n\n\nAutomationEditor::AutomationEditor(EditorState& editorState, ISynth& synth, IPlayer& player)\n\t:Editor(editorState, true), mSynth(synth), mSelectedNode(-1), mSelectedTrack(0)\n{\n\tmEditorState.patternEditor.currentRow.addListener(this);\n\tmEditorState.sequenceEditor.currentRow.addListener(this);\n}\n\n\nAutomationEditor::~AutomationEditor()\n{\n}\n\n\nSDL_Rect AutomationEditor::getNodeArea(const SDL_Rect& parent, int index) const\n{\n\tconst Synth& synth = static_cast(mSynth);\n\tconst Synth::AutomationNode& node = getAutomationTrack().getNode(index);\n\n\treturn getNodeArea(parent, node);\n}\n\n\nSDL_Rect AutomationEditor::getNodeArea(const SDL_Rect& parent, const Synth::AutomationNode& node) const\n{\n\tconst int nodeWidth = 5;\n\tconst int nodeHeight = 5;\n\n\tSDL_Rect area = {\n\t\tnode.time + parent.x - nodeWidth \/ 2 - getScrollPosition(),\n\t\tstatic_cast((1.0f - node.value) * parent.h) + parent.y - nodeHeight \/ 2,\n\t\tnodeWidth, nodeHeight\n\t};\n\n\treturn area;\n}\n\n\nvoid AutomationEditor::onDraw(Renderer& renderer, const SDL_Rect& area)\n{\n\tsetDirty(false);\n\n\tif (mModal != NULL)\n\t{\n\t\treturn;\n\t}\n\n\trenderer.setClip(area);\n\trenderer.renderBackground(area);\n\n\tconst Synth& synth = getSynth();\n\tint patternLength = synth.getPatternLength();\n\n\tfor (int x = area.x - getScrollPosition() ; x < area.w + area.x ; x += patternLength)\n\t{\n\t\trenderer.renderLine(x, area.y, x, area.y + area.h, Color(64,64,64));\n\t}\n\n\tfloat time = synth.getSongPosition();\n\tint editPos = mEditorState.patternEditor.currentRow + mEditorState.sequenceEditor.currentRow * patternLength;\n\n\trenderer.renderLine(time - getScrollPosition() + area.x, area.y, time - getScrollPosition() + area.x, area.y + area.h, Color(0,0,128));\n\trenderer.renderLine(editPos - getScrollPosition() + area.x, area.y, editPos - getScrollPosition() + area.x, area.y + area.h, Color(255,255,255));\n\n\tfor (int track = 0 ; track < Synth::maxAutomationTracks ; ++track)\n\t{\n\t\tif (track == mSelectedTrack)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (synth.getAutomationTrack(track).numNodes > 0)\n\t\t{\n\t\t\tSDL_Rect nodeArea = getNodeArea(area, synth.getAutomationTrack(track).nodes[0]);\n\t\t\tint px = nodeArea.x + nodeArea.w \/ 2;\n\t\t\tint py = nodeArea.y + nodeArea.h \/ 2;\n\n\t\t\tfor (int i = 1 ; i < synth.getAutomationTrack(track).numNodes ; ++i)\n\t\t\t{\n\t\t\t\tSDL_Rect nodeArea = getNodeArea(area, synth.getAutomationTrack(track).nodes[i]);\n\t\t\t\tint x = nodeArea.x + nodeArea.w \/ 2;\n\t\t\t\tint y = nodeArea.y + nodeArea.h \/ 2;\n\n\t\t\t\trenderer.renderLine(px, py, x, y, track == mSelectedTrack ? Color(255, 255, 255) : Color(64, 64, 64));\n\n\t\t\t\tpx = x;\n\t\t\t\tpy = y;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tif (getAutomationTrack().numNodes > 0)\n\t{\n\t\tSDL_Rect nodeArea = getNodeArea(area, 0);\n\t\tint px = nodeArea.x + nodeArea.w \/ 2;\n\t\tint py = nodeArea.y + nodeArea.h \/ 2;\n\n\t\tfor (int i = 1 ; i < getAutomationTrack().numNodes ; ++i)\n\t\t{\n\t\t\tSDL_Rect nodeArea = getNodeArea(area, i);\n\t\t\tint x = nodeArea.x + nodeArea.w \/ 2;\n\t\t\tint y = nodeArea.y + nodeArea.h \/ 2;\n\n\t\t\trenderer.renderLine(px, py, x, y, Color(255, 255, 255));\n\n\t\t\tpx = x;\n\t\t\tpy = y;\n\t\t}\n\n\t\tfor (int i = 0 ; i < getAutomationTrack().numNodes ; ++i)\n\t\t{\n\t\t\tSDL_Rect nodeArea = getNodeArea(area, i);\n\t\t\trenderer.clearRect(nodeArea, mSelectedNode == i ? Color(255, 255, 255) : Color(255, 0, 0));\n\t\t}\n\t}\n\n\tconst SDL_Rect textArea = { area.x + area.w - renderer.getFontWidth() * 2 - 1, area.y + 1, 16, 16 };\n\trenderer.renderTextV(textArea, Color(192, 140, 32), \"%02d\", mSelectedTrack);\n}\n\n\nbool AutomationEditor::pickNode(int x, int y, const SDL_Rect& area, int& nodeOut) const\n{\n\tSDL_Point point = {x,y};\n\n\tfor (int i = 0 ; i < getAutomationTrack().numNodes ; ++i)\n\t{\n\t\tif (pointInRect(point, getNodeArea(area, i)))\n\t\t{\n\t\t\tnodeOut = i;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n\nbool AutomationEditor::onEvent(SDL_Event& event)\n{\n\tif (event.type == SDL_MOUSEBUTTONDOWN)\n\t{\n\t\t\/\/ Editor base class should probably do this when clicked\n\t\tsetFocus(this);\n\n\t\tmMouseX = event.button.x \/ SCALE;\n\t\tmMouseY = event.button.y \/ SCALE;\n\n\t\tswitch (event.button.button)\n\t\t{\n\t\t\tcase SDL_BUTTON_LEFT:\n\t\t\t\tif (event.button.clicks == 1)\n\t\t\t\t{\n\t\t\t\t\tint nodeIdx;\n\t\t\t\t\tif (pickNode(mMouseX, mMouseY, mThisArea, nodeIdx))\n\t\t\t\t\t{\n\t\t\t\t\t\tSynth::AutomationNode& node = getAutomationTrack().getNode(nodeIdx);\n\t\t\t\t\t\tmSelectedNode = nodeIdx;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tmSelectedNode = -1;\n\t\t\t\t\t}\n\t\t\t\t\tsetDirty(true);\n\t\t\t\t}\n\t\t\t\telse if (event.button.clicks == 2)\n\t\t\t\t{\n\t\t\t\t\tSynth& synth = static_cast(mSynth);\n\t\t\t\t\tSDL_Keymod modState = SDL_GetModState();\n\t\t\t\t\tint xGranularity = 1, yGranularity = 1;\n\n\t\t\t\t\tif (modState & KMOD_CTRL)\n\t\t\t\t\t{\n\t\t\t\t\t\txGranularity = synth.getPatternLength();\n\t\t\t\t\t\tyGranularity = mThisArea.h \/ 2;\n\t\t\t\t\t}\n\n\t\t\t\t\tmSelectedNode = getAutomationTrack().addNode(\n\t\t\t\t\t\tgranularize(mMouseX - mThisArea.x + getScrollPosition(), xGranularity),\n\t\t\t\t\t\t1.0f - static_cast(granularize(mMouseY - mThisArea.y, yGranularity)) \/ mThisArea.h\n\t\t\t\t\t);\n\t\t\t\t\tsetDirty(true);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn false;\n\t}\n\telse if (event.type == SDL_MOUSEMOTION)\n\t{\n\t\tmMouseX = event.motion.x \/ SCALE;\n\t\tmMouseY = event.motion.y \/ SCALE;\n\n\t\tif ((event.motion.state & SDL_BUTTON(SDL_BUTTON_LEFT)) && mSelectedNode != -1)\n\t\t{\n\t\t\tSynth& synth = static_cast(mSynth);\n\t\t\tSDL_Keymod modState = SDL_GetModState();\n\t\t\tint xGranularity = 1, yGranularity = 1;\n\t\t\tSynth::AutomationTrack& track = getAutomationTrack();\n\t\t\tSynth::AutomationNode& firstNode = track.getNode(mSelectedNode);\n\t\t\tint origTime = firstNode.time;\n\t\t\tfloat origValue = firstNode.value;\n\n\t\t\tif (modState & KMOD_CTRL)\n\t\t\t{\n\t\t\t\txGranularity = synth.getPatternLength() \/ 2;\n\t\t\t\tyGranularity = mThisArea.h \/ 2;\n\t\t\t}\n\n\t\t\ttrack.editNode(mSelectedNode,\n\t\t\t\tgranularize(mMouseX - mThisArea.x + getScrollPosition(), xGranularity),\n\t\t\t\t1.0f - static_cast(granularize(mMouseY - mThisArea.y, yGranularity)) \/ mThisArea.h\n\t\t\t);\n\n\t\t\tif (modState & KMOD_ALT)\n\t\t\t{\n\n\t\t\t\tint deltaTime = firstNode.time - origTime;\n\t\t\t\tfloat deltaValue = firstNode.value - origValue;\n\n\t\t\t\tfor (int nodeIdx = mSelectedNode + 1 ; nodeIdx < track.numNodes ; ++nodeIdx)\n\t\t\t\t{\n\t\t\t\t\tSynth::AutomationNode node = track.getNode(nodeIdx);\n\t\t\t\t\ttrack.editNode(nodeIdx,\n\t\t\t\t\t\tnode.time + deltaTime,\n\t\t\t\t\t\tnode.value + deltaValue\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse if (event.type == SDL_MOUSEWHEEL)\n\t{\n\t\tmSelectedTrack = (mSelectedTrack + (event.wheel.y < 0 ? -1 : 1) + Synth::maxAutomationTracks) % Synth::maxAutomationTracks;\n\t\tmSelectedNode = -1;\n\t\tsetDirty(true);\n\t}\n\telse if (event.type == SDL_KEYDOWN)\n\t{\n\t\tswitch (event.key.keysym.sym)\n\t\t{\n\t\t\tcase SDLK_DELETE:\n\t\t\t\tif (mSelectedNode != -1)\n\t\t\t\t{\n\t\t\t\t\tgetAutomationTrack().removeNode(mSelectedNode);\n\t\t\t\t\tsetDirty(true);\n\t\t\t\t\tmSelectedNode = -1;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n\nvoid AutomationEditor::onListenableChange(Listenable *listenable)\n{\n\n}\n\n\nvoid AutomationEditor::onLoaded()\n{\n\n}\n\n\nint AutomationEditor::granularize(int value, int steps)\n{\n\tint newValue = value + steps \/ 2;\n\tnewValue = newValue - (newValue % steps);\n\treturn abs(newValue - value) < 4 ? newValue : value;\n}\n\n\nSynth& AutomationEditor::getSynth()\n{\n\treturn static_cast(mSynth);\n}\n\n\nSynth::AutomationTrack& AutomationEditor::getAutomationTrack()\n{\n\treturn getSynth().getAutomationTrack(mSelectedTrack);\n}\n\n\nconst Synth& AutomationEditor::getSynth() const\n{\n\treturn static_cast(mSynth);\n}\n\n\nconst Synth::AutomationTrack& AutomationEditor::getAutomationTrack() const\n{\n\treturn getSynth().getAutomationTrack(mSelectedTrack);\n}\n\n\nint AutomationEditor::getScrollPosition() const\n{\n\treturn std::max(0, mEditorState.patternEditor.currentRow + mEditorState.sequenceEditor.currentRow * getSynth().getPatternLength() - mThisArea.w \/ 2);\n}\n<|endoftext|>"}
{"text":"\/* Copyright 2014 Gagarine Yaikhom (MIT License) *\/\n\n#include \n#include \"BinarySearchTree.hh\"\n\nusing namespace std;\n\nBinarySearchTree::BinarySearchTree() {\n    root = 0;\n}\n\nvoid BinarySearchTree::preorderRecursive(BinarySearchTreeNode* root) {\n    if (root) {\n        root->print();\n        preorderRecursive(root->left);\n        preorderRecursive(root->right);\n    }\n}\n\nvoid BinarySearchTree::preorderNonRecursive(BinarySearchTreeNode* root) {\n    BinarySearchTreeNode* current = root;\n    while (current) {\n        if (!current->visited) {\n            current->print();\n            current->visited = true;\n        }\n\n        if (current->left && !current->left->visited) {\n            current = current->left;\n            continue;\n        } else if (current->right && !current->right->visited) {\n            current = current->right;\n            continue;\n        }\n\n        if (current->left)\n            current->left->visited = false;\n        if (current->right)\n            current->right->visited = false;\n\n        current = current->parent;\n    };\n    if (root)\n        root->visited = false;\n}\n\nvoid BinarySearchTree::preorder() {\n    cout << \"\\nPreorder traversal\\n\";\n    preorderNonRecursive(root);\n}\n\nvoid BinarySearchTree::inorderRecursive(BinarySearchTreeNode* root) {\n    if (root) {\n        inorderRecursive(root->left);\n        root->print();\n        inorderRecursive(root->right);\n    }\n}\n\nvoid BinarySearchTree::inorderNonRecursive(BinarySearchTreeNode* root) {\n    BinarySearchTreeNode* current = root;\n    while (current) {\n        if (current->left && !current->left->visited) {\n            current = current->left;\n            continue;\n        }\n\n        if (!current->visited) {\n            current->print();\n            current->visited = true;\n        }\n\n        if (current->right && !current->right->visited) {\n            current = current->right;\n            continue;\n        }\n\n        if (current->left)\n            current->left->visited = false;\n        if (current->right)\n            current->right->visited = false;\n\n        current = current->parent;\n    };\n    if (root)\n        root->visited = false;\n}\n\nvoid BinarySearchTree::inorder() {\n    cout << \"\\nInorder traversal\\n\";\n    inorderNonRecursive(root);\n}\n\nvoid BinarySearchTree::postorderRecursive(BinarySearchTreeNode* root) {\n    if (root) {\n        postorderRecursive(root->left);\n        postorderRecursive(root->right);\n        root->print();\n    }\n}\n\nvoid BinarySearchTree::postorderNonRecursive(BinarySearchTreeNode* root) {\n    BinarySearchTreeNode* current = root;\n    while (current) {\n        if (current->left && !current->left->visited) {\n            current = current->left;\n            continue;\n        } else if (current->right && !current->right->visited) {\n            current = current->right;\n            continue;\n        }\n\n        if (!current->visited) {\n            current->print();\n            current->visited = true;\n        }\n\n        if (current->left)\n            current->left->visited = false;\n        if (current->right)\n            current->right->visited = false;\n\n        current = current->parent;\n    };\n    if (root)\n        root->visited = false;\n}\n\nvoid BinarySearchTree::postorder() {\n    cout << \"\\nPostorder traversal\\n\";\n    postorderNonRecursive(root);\n}\n\nint BinarySearchTree::add(int key) {\n    if (root == 0) {\n        root = new BinarySearchTreeNode(key);\n    } else {\n        BinarySearchTreeNode* current = root;\n        BinarySearchTreeNode* newNode = new BinarySearchTreeNode(key);\n        while (current) {\n            if (*current == *newNode) {\n                delete newNode;\n                return 1; \/* duplicate key *\/\n            } else {\n                if (*newNode < *current) {\n                    if (current->left)\n                        current = current->left;\n                    else {\n                        current->left = newNode;\n                        newNode->parent = current;\n                        return 0;\n                    }\n                } else {\n                    if (current->right)\n                        current = current->right;\n                    else {\n                        current->right = newNode;\n                        newNode->parent = current;\n                        return 0;\n                    }\n                }\n            }\n        }\n    }\n    return 0;\n}\n\nBinarySearchTreeNode* BinarySearchTree::find(int key) {\n    BinarySearchTreeNode* current = root;\n    while (current) {\n        if (key == current->key)\n            return current;\n        else {\n            if (key < current->key)\n                current = current->left;\n            else\n                current = current->right;\n        }\n    }\n    return 0;\n}\n\nBinarySearchTreeNode* BinarySearchTree::findSubtreeMax(BinarySearchTreeNode* root) {\n    BinarySearchTreeNode* current = root;\n    if (current)\n        while (current->right)\n            current = current->right;\n    return current;\n}\n\nBinarySearchTreeNode* BinarySearchTree::findSubtreeMin(BinarySearchTreeNode* root) {\n    BinarySearchTreeNode* current = root;\n    if (current)\n        while (current->left)\n            current = current->left;\n    return current;\n}\n\nint BinarySearchTree::remove(int key) {\n    BinarySearchTreeNode* node = find(key);\n    if (node) {\n        \n    }\n}\n\nvoid BinarySearchTree::destroyRecursive(BinarySearchTreeNode* root) {\n    if (root) {\n        destroyRecursive(root->left);\n        destroyRecursive(root->right);\n        cout << \"\\nDeleting node \" << root->key;\n        delete root;\n    }\n}\n\nvoid BinarySearchTree::destroyNonRecursive(BinarySearchTreeNode* root) {\n    BinarySearchTreeNode* temp;\n    while (root) {\n        if (root->left) {\n            root = root->left;\n            continue;\n        } else if (root->right) {\n            root = root->right;\n            continue;\n        }\n\n        temp = root->parent;\n        if (temp) {\n            if (temp->left == root)\n                temp->left = 0;\n            else\n                temp->right = 0;\n        }\n\n        cout << \"\\nDeleting node \" << root->key;\n        delete root;\n        root = temp;\n    };\n}\n\nBinarySearchTree::~BinarySearchTree() {\n    destroyNonRecursive(root);\n}\nComplete implementation of removal.\/* Copyright 2014 Gagarine Yaikhom (MIT License) *\/\n\n#include \n#include \"BinarySearchTree.hh\"\n\nusing namespace std;\n\nBinarySearchTree::BinarySearchTree() {\n    root = 0;\n}\n\nvoid BinarySearchTree::preorderRecursive(BinarySearchTreeNode* root) {\n    if (root) {\n        root->print();\n        preorderRecursive(root->left);\n        preorderRecursive(root->right);\n    }\n}\n\nvoid BinarySearchTree::preorderNonRecursive(BinarySearchTreeNode* root) {\n    BinarySearchTreeNode* current = root;\n    while (current) {\n        if (!current->visited) {\n            current->print();\n            current->visited = true;\n        }\n\n        if (current->left && !current->left->visited) {\n            current = current->left;\n            continue;\n        } else if (current->right && !current->right->visited) {\n            current = current->right;\n            continue;\n        }\n\n        if (current->left)\n            current->left->visited = false;\n        if (current->right)\n            current->right->visited = false;\n\n        current = current->parent;\n    };\n    if (root)\n        root->visited = false;\n}\n\nvoid BinarySearchTree::preorder() {\n    cout << \"\\nPreorder traversal\\n\";\n    preorderNonRecursive(root);\n}\n\nvoid BinarySearchTree::inorderRecursive(BinarySearchTreeNode* root) {\n    if (root) {\n        inorderRecursive(root->left);\n        root->print();\n        inorderRecursive(root->right);\n    }\n}\n\nvoid BinarySearchTree::inorderNonRecursive(BinarySearchTreeNode* root) {\n    BinarySearchTreeNode* current = root;\n    while (current) {\n        if (current->left && !current->left->visited) {\n            current = current->left;\n            continue;\n        }\n\n        if (!current->visited) {\n            current->print();\n            current->visited = true;\n        }\n\n        if (current->right && !current->right->visited) {\n            current = current->right;\n            continue;\n        }\n\n        if (current->left)\n            current->left->visited = false;\n        if (current->right)\n            current->right->visited = false;\n\n        current = current->parent;\n    };\n    if (root)\n        root->visited = false;\n}\n\nvoid BinarySearchTree::inorder() {\n    cout << \"\\nInorder traversal\\n\";\n    inorderNonRecursive(root);\n}\n\nvoid BinarySearchTree::postorderRecursive(BinarySearchTreeNode* root) {\n    if (root) {\n        postorderRecursive(root->left);\n        postorderRecursive(root->right);\n        root->print();\n    }\n}\n\nvoid BinarySearchTree::postorderNonRecursive(BinarySearchTreeNode* root) {\n    BinarySearchTreeNode* current = root;\n    while (current) {\n        if (current->left && !current->left->visited) {\n            current = current->left;\n            continue;\n        } else if (current->right && !current->right->visited) {\n            current = current->right;\n            continue;\n        }\n\n        if (!current->visited) {\n            current->print();\n            current->visited = true;\n        }\n\n        if (current->left)\n            current->left->visited = false;\n        if (current->right)\n            current->right->visited = false;\n\n        current = current->parent;\n    };\n    if (root)\n        root->visited = false;\n}\n\nvoid BinarySearchTree::postorder() {\n    cout << \"\\nPostorder traversal\\n\";\n    postorderNonRecursive(root);\n}\n\nint BinarySearchTree::add(int key) {\n    if (root == 0) {\n        root = new BinarySearchTreeNode(key);\n    } else {\n        BinarySearchTreeNode* current = root;\n        BinarySearchTreeNode* newNode = new BinarySearchTreeNode(key);\n        while (current) {\n            if (*current == *newNode) {\n                delete newNode;\n                return 1; \/* duplicate key *\/\n            } else {\n                if (*newNode < *current) {\n                    if (current->left)\n                        current = current->left;\n                    else {\n                        current->left = newNode;\n                        newNode->parent = current;\n                        return 0;\n                    }\n                } else {\n                    if (current->right)\n                        current = current->right;\n                    else {\n                        current->right = newNode;\n                        newNode->parent = current;\n                        return 0;\n                    }\n                }\n            }\n        }\n    }\n    return 0;\n}\n\nBinarySearchTreeNode* BinarySearchTree::find(int key) {\n    BinarySearchTreeNode* current = root;\n    while (current) {\n        if (key == current->key)\n            return current;\n        else {\n            if (key < current->key)\n                current = current->left;\n            else\n                current = current->right;\n        }\n    }\n    return 0;\n}\n\nBinarySearchTreeNode* BinarySearchTree::findSubtreeMax(BinarySearchTreeNode* root) {\n    BinarySearchTreeNode* current = root;\n    if (current)\n        while (current->right)\n            current = current->right;\n    return current;\n}\n\nBinarySearchTreeNode* BinarySearchTree::findSubtreeMin(BinarySearchTreeNode* root) {\n    BinarySearchTreeNode* current = root;\n    if (current)\n        while (current->left)\n            current = current->left;\n    return current;\n}\n\nint BinarySearchTree::remove(int key) {\n    BinarySearchTreeNode* node = find(key), *newRoot, *temp;\n    if (node) {\n        if (node->right) {\n            newRoot = node->right;\n            newRoot->parent = node->parent;\n            if (node->parent) {\n                if (node->parent->right == node)\n                    node->parent->right = newRoot;\n                else\n                    node->parent->left = newRoot;\n            } else \n                root = newRoot;\n            temp = findSubtreeMin(newRoot);\n            temp->left = node->left;\n            if (node->left)\n                node->left->parent = temp;\n        } else if (node->left) {\n            newRoot = node->left;\n            newRoot->parent = node->parent;\n            if (node->parent) {\n                if (node->parent->right == node)\n                    node->parent->right = newRoot;\n                else\n                    node->parent->left = newRoot;\n            } else \n                root = newRoot;\n            temp = findSubtreeMax(newRoot);\n            temp->right = node->right;\n            if (node->right)\n                node->right->parent = temp;\n        } else {   \n            if (node->parent) {\n                if (node->parent->right == node)\n                    node->parent->right = 0;\n                else\n                    node->parent->left = 0;\n            } else\n                root = 0;\n        }\n        delete node;\n        return 1;\n    } else\n        return 0;\n}\n\nvoid BinarySearchTree::destroyRecursive(BinarySearchTreeNode* root) {\n    if (root) {\n        destroyRecursive(root->left);\n        destroyRecursive(root->right);\n        cout << \"\\nDeleting node \" << root->key;\n        delete root;\n    }\n}\n\nvoid BinarySearchTree::destroyNonRecursive(BinarySearchTreeNode* root) {\n    BinarySearchTreeNode* temp;\n    while (root) {\n        if (root->left) {\n            root = root->left;\n            continue;\n        } else if (root->right) {\n            root = root->right;\n            continue;\n        }\n\n        temp = root->parent;\n        if (temp) {\n            if (temp->left == root)\n                temp->left = 0;\n            else\n                temp->right = 0;\n        }\n\n        cout << \"\\nDeleting node \" << root->key;\n        delete root;\n        root = temp;\n    };\n}\n\nBinarySearchTree::~BinarySearchTree() {\n    destroyNonRecursive(root);\n}\n<|endoftext|>"}
{"text":"\/*\n * Copyright (C) 2013-2014 Morwenn\n *\n * static_math is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version.\n *\n * static_math is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program. If not,\n * see .\n *\/\n#include \n\nusing namespace smath;\n\n\nint main()\n{\n    \/\/ Constructor tests\n    constexpr auto ratio = rational(4, 3);\n    static_assert(ratio.numerator() == 4, \"\");\n    static_assert(ratio.denominator() == 3, \"\");\n\n    constexpr auto ratio2 = rational(5);\n    static_assert(ratio2.numerator() == 5, \"\");\n    static_assert(ratio2.denominator() == 1, \"\");\n\n    constexpr auto r1 = rational(1, 2);\n    constexpr auto r2 = rational(2, 4);\n    constexpr auto r3 = rational(1, 3);\n    constexpr auto r4 = rational(5, 1);\n    constexpr auto r5 = rational(-1, 2);\n    constexpr auto r6 = rational(1, -2);\n\n    \/\/ rational-rational comparison\n    static_assert(r1 == r2, \"\");\n    static_assert(r1 != r3, \"\");\n    static_assert(r1 > r3, \"\");\n    static_assert(r3 < r2, \"\");\n    static_assert(r1 >= r2, \"\");\n    static_assert(r3 <= r2, \"\");\n    static_assert(r5 == r6, \"\");\n\n    \/\/ rational-integral comparison\n    static_assert(r4 == 5, \"\");\n    static_assert(5 == r4, \"\");\n    static_assert(r1 != 3, \"\");\n    static_assert(8 != r2, \"\");\n    static_assert(0 < r1, \"\");\n    static_assert(r2 < 1, \"\");\n    static_assert(8 > r4, \"\");\n    static_assert(r2 > -1, \"\");\n    static_assert(5 <= r4, \"\");\n    static_assert(r3 <= 1, \"\");\n    static_assert(1 >= r3, \"\");\n    static_assert(r1 >= -8, \"\");\n    static_assert(r5 <= 0, \"\");\n    static_assert(r6 <= 0, \"\");\n\n    \/\/ rational-rational arithmetic operations\n    static_assert(r1 + r2 == 1, \"\");\n    static_assert(r4 - r1 == rational(9, 2), \"\");\n    static_assert(r2 * r3 == rational(1, 6), \"\");\n    static_assert(r1 \/ r3 == rational(3, 2), \"\");\n\n    \/\/ rational-integral arithmetic operations\n    static_assert(r1 + 1 == rational(3, 2), \"\");\n    static_assert(2 + r2 == rational(5, 2), \"\");\n    static_assert(r3 - 3 == rational(-8, 3), \"\");\n    static_assert(2 - r1 == rational(3, 2), \"\");\n    static_assert(r4 * 2 == 10, \"\");\n    static_assert(6 * r2 == r1 * 6, \"\");\n    static_assert(1 \/ r2 == 2, \"\");\n    static_assert(r3 \/ 3 == rational(1, 9), \"\");\n\n    \/\/ cast\n    static_assert(rational(1, 2) == rational(1, 2), \"\");\n    static_assert(rational(3, 2) == rational(3, 2), \"\");\n\n    \/\/ _smath_r literal\n    static_assert(2 \/ 3_r == rational(2, 3), \"\");\n    static_assert(1_r \/ 8 == rational(1, 8), \"\");\n    static_assert(3 \/ 5_r == 3_r \/ 5, \"\");\n\n    constexpr auto a0 = rational(0, 1);\n    constexpr auto a1 = rational(1, 2);\n    constexpr auto a2 = rational(-3, 8);\n    constexpr auto a3 = rational(6, -7);\n\n    \/\/ Math functions\n    static_assert(sign(a0) == 0, \"\");\n    static_assert(sign(a1) == 1, \"\");\n    static_assert(sign(a2) == -1, \"\");\n    static_assert(sign(a3) == -1, \"\");\n\n    static_assert(abs(a1) == 1 \/ 2_r, \"\");\n    static_assert(abs(a2) == 3 \/ 8_r, \"\");\n    static_assert(abs(a3) == 6 \/ 7_r, \"\");\n\n    static_assert(round(a1) == 1.0, \"\");\n    \/* No more tests for ceil, floor, trunc\n     * and round since they are based on\n     * the floating point functions after\n     * a simple cast.\n     *\/\n\n    static_assert(reciprocal(a1) == 2, \"\");\n    static_assert(reciprocal(a2) == rational(8, -3), \"\");\n\n    static_assert(pow(a1, 2) == 1 \/ 4_r, \"\");\n    static_assert(pow(a2, 3) == -27 \/ 512_r, \"\");\n    static_assert(pow(a3, -2) == 49 \/ 36_r, \"\");\n}\nMore tests.\/*\n * Copyright (C) 2013-2014 Morwenn\n *\n * static_math is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version.\n *\n * static_math is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program. If not,\n * see .\n *\/\n#include \n\nusing namespace smath;\n\n\nint main()\n{\n    \/\/ Constructor tests\n    constexpr auto ratio = rational(4, 3);\n    static_assert(ratio.numerator() == 4, \"\");\n    static_assert(ratio.denominator() == 3, \"\");\n\n    constexpr auto ratio2 = rational(5);\n    static_assert(ratio2.numerator() == 5, \"\");\n    static_assert(ratio2.denominator() == 1, \"\");\n\n    constexpr auto r1 = rational(1, 2);\n    constexpr auto r2 = rational(2, 4);\n    constexpr auto r3 = rational(1, 3);\n    constexpr auto r4 = rational(5, 1);\n    constexpr auto r5 = rational(-1, 2);\n    constexpr auto r6 = rational(1, -2);\n    constexpr auto r7 = rational(4, 5);\n\n    \/\/ Rational-rational comparison\n    static_assert(r1 == r2, \"\");\n    static_assert(r1 != r3, \"\");\n    static_assert(r1 > r3, \"\");\n    static_assert(r3 < r2, \"\");\n    static_assert(r1 >= r2, \"\");\n    static_assert(r3 <= r2, \"\");\n    static_assert(r5 == r6, \"\");\n\n    \/\/ Rational-integral comparison\n    static_assert(r4 == 5, \"\");\n    static_assert(5 == r4, \"\");\n    static_assert(r1 != 3, \"\");\n    static_assert(8 != r2, \"\");\n    static_assert(0 < r1, \"\");\n    static_assert(r2 < 1, \"\");\n    static_assert(8 > r4, \"\");\n    static_assert(r2 > -1, \"\");\n    static_assert(5 <= r4, \"\");\n    static_assert(r3 <= 1, \"\");\n    static_assert(1 >= r3, \"\");\n    static_assert(r1 >= -8, \"\");\n    static_assert(r5 <= 0, \"\");\n    static_assert(r6 <= 0, \"\");\n\n    \/\/ Rational-rational arithmetic operations\n    static_assert(r1 + r2 == 1, \"\");\n    static_assert(r4 - r1 == rational(9, 2), \"\");\n    static_assert(r2 * r3 == rational(1, 6), \"\");\n    static_assert(r1 \/ r3 == rational(3, 2), \"\");\n\n    \/\/ Rational-integral arithmetic operations\n    static_assert(r1 + 1 == rational(3, 2), \"\");\n    static_assert(2 + r2 == rational(5, 2), \"\");\n    static_assert(r3 - 3 == rational(-8, 3), \"\");\n    static_assert(2 - r1 == rational(3, 2), \"\");\n    static_assert(r4 * 2 == 10, \"\");\n    static_assert(6 * r2 == r1 * 6, \"\");\n    static_assert(1 \/ r2 == 2, \"\");\n    static_assert(r3 \/ 3 == rational(1, 9), \"\");\n\n    \/\/ Cast\n    static_assert(rational(1, 2) == rational(1, 2), \"\");\n    static_assert(rational(3, 2) == rational(3, 2), \"\");\n\n    \/\/ User-defined literal\n    static_assert(2 \/ 3_r == rational(2, 3), \"\");\n    static_assert(1_r \/ 8 == rational(1, 8), \"\");\n    static_assert(3 \/ 5_r == 3_r \/ 5, \"\");\n\n    constexpr auto a0 = rational(0, 1);\n    constexpr auto a1 = rational(1, 2);\n    constexpr auto a2 = rational(-3, 8);\n    constexpr auto a3 = rational(6, -7);\n\n    \/\/ Math functions\n    static_assert(sign(a0) == 0, \"\");\n    static_assert(sign(a1) == 1, \"\");\n    static_assert(sign(a2) == -1, \"\");\n    static_assert(sign(a3) == -1, \"\");\n\n    static_assert(abs(a1) == 1 \/ 2_r, \"\");\n    static_assert(abs(a2) == 3 \/ 8_r, \"\");\n    static_assert(abs(a3) == 6 \/ 7_r, \"\");\n\n    static_assert(round(a1) == 1.0, \"\");\n    \/* No more tests for ceil, floor, trunc\n     * and round since they are based on\n     * the floating point functions after\n     * a simple cast.\n     *\/\n\n    static_assert(reciprocal(a1) == 2, \"\");\n    static_assert(reciprocal(a2) == rational(8, -3), \"\");\n\n    static_assert(pow(a1, 2) == 1 \/ 4_r, \"\");\n    static_assert(pow(a2, 3) == -27 \/ 512_r, \"\");\n    static_assert(pow(a3, -2) == 49 \/ 36_r, \"\");\n    static_assert(pow(r1, 0) == 1_r, \"\");\n    static_assert(pow(r2, 1) == r2, \"\");\n    static_assert(pow(r7, 3) == 64 \/ 125_r, \"\");\n}\n<|endoftext|>"}
{"text":"#ifndef __GLOBALS_HPP_INCLUDED\n#define __GLOBALS_HPP_INCLUDED\n\n#include \n#include \n#include  \/\/ uint32_t etc.\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include \n#endif\n\n\/\/ Include GLFW\n#ifndef __GLFW3_H_INCLUDED\n#define __GLFW3_H_INCLUDED\n#include \n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include \n#endif\n\n#ifndef WINDOW_WIDTH\n#define WINDOW_WIDTH (1600.0f)\n#endif\n\n#ifndef WINDOW_HEIGHT\n#define WINDOW_HEIGHT (900.0f)\n#endif\n\n#ifndef ASPECT_RATIO\n#define ASPECT_RATIO (WINDOW_WIDTH \/ WINDOW_HEIGHT)\n#endif\n\n#ifndef PI\n#define PI 3.14159265359f\n#endif\n\n#ifndef EARTH_RADIUS\n#define EARTH_RADIUS 6371000.0f\n#endif\n\n#ifndef TEXT_SIZE\n#define TEXT_SIZE 40\n#endif\n\n#ifndef FONT_SIZE\n#define FONT_SIZE 16\n#endif\n\n#ifndef MAX_FPS\n#define MAX_FPS 60\n#endif\n\nextern glm::vec3 position;\nextern double horizontalAngle;\nextern double verticalAngle;\nextern GLfloat initialFoV;\nextern double earth_radius;\nextern bool hasMouseEverMoved;\nextern bool is_invert_mouse_in_use;\nextern bool is_key_I_released;\nextern bool is_world_loaded; \/\/ no more than one world object can be loaded. TODO: check that no more than one world is loaded!\nextern bool is_world_spherical;\n\ntypedef struct\n{\n    std::string texture_file_format;\n    std::string image_path;\n} TextureStruct;\n\ntypedef struct\n{\n    void *world_pointer;                     \/\/ pointer to the world (draw list).\n    std::string vertex_shader;               \/\/ filename of vertex shader.\n    std::string fragment_shader;             \/\/ filename of fragment shader.\n} ShaderStruct;\n\ntypedef struct\n{\n    GLuint nodeID;\n    void* graph_pointer;\n    glm::vec3 coordinate_vector;\n    std::vector neighbor_nodeIDs;\n} NodeStruct;\n\ntypedef struct\n{\n    glm::vec3 coordinate_vector;     \/\/ coordinate vector.\n    GLfloat rotate_angle;            \/\/ rotate angle.\n    glm::vec3 rotate_vector;         \/\/ rotate vector.\n    glm::vec3 translate_vector;      \/\/ translate vector.\n    glm::mat4 model_matrix;          \/\/ model matrix.\n    glm::mat4 MVP_matrix;            \/\/ model view projection matrix.\n    void *species_pointer;           \/\/ pointer to the species.\n} ObjectStruct;\n\ntypedef struct\n{\n    \/\/ used for all files (for all species).\n    void *shader_pointer;                    \/\/ pointer to the shader object.\n    std::string model_file_format;           \/\/ type of the model file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"obj\"`\/`\"OBJ\"`.\n                                             \/\/ TODO: add support for `\"SRTM\"`.\n    std::string texture_file_format;         \/\/ type of the texture file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"dds\"`\/`\"DDS\"`.\n    std::string texture_filename;            \/\/ filename of the model file.\n    std::string vertex_shader;               \/\/ filename of vertex shader.\n    std::string fragment_shader;             \/\/ filename of fragment shader.\n    glm::vec3 lightPos;                      \/\/ light position.\n    std::vector object_vector; \/\/ vector of individual objects of this species.\n    bool is_world;                           \/\/ worlds currently do not rotate nor translate.\n    std::string coordinate_system;           \/\/ used only for worlds (`is_world` == `true`). valid values: `\"cartesian\"`.\n                                             \/\/ TODO: add support for `\"spherical\"`. `\"spherical\"` is used eg. in SRTM heightmaps.\n    double world_radius;                    \/\/ radius of sea level in meters. used only for worlds.\n\n    \/\/ for `\"bmp\"` model files.\n    std::string model_filename;              \/\/ filename of the model file.\n    std::string color_channel;               \/\/ color channel to use for altitude data.\n} SpeciesStruct;\n\ntypedef struct\n{\n    GLuint screen_width;\n    GLuint screen_height;\n    GLuint x;\n    GLuint y;\n    GLuint text_size;\n    GLuint font_size;\n    const char *text;\n    const char *char_font_texture_file_format;\n    const char *horizontal_alignment;\n    const char *vertical_alignment;\n} PrintingStruct;\n\ntypedef struct\n{\n    double rho;\n    double theta;\n    double phi;\n} SphericalCoordinatesStruct;\n\ntypedef struct\n{\n    double southern_latitude;\n    double northern_latitude;\n    double western_longitude;\n    double eastern_longitude;\n} SphericalWorldStruct;\n\nextern SphericalCoordinatesStruct spherical_position;\n\n#endif\nMuokattu `typedef struct {` ... `} TextureStruct;`.#ifndef __GLOBALS_HPP_INCLUDED\n#define __GLOBALS_HPP_INCLUDED\n\n#include \n#include \n#include  \/\/ uint32_t etc.\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include \n#endif\n\n\/\/ Include GLFW\n#ifndef __GLFW3_H_INCLUDED\n#define __GLFW3_H_INCLUDED\n#include \n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include \n#endif\n\n#ifndef WINDOW_WIDTH\n#define WINDOW_WIDTH (1600.0f)\n#endif\n\n#ifndef WINDOW_HEIGHT\n#define WINDOW_HEIGHT (900.0f)\n#endif\n\n#ifndef ASPECT_RATIO\n#define ASPECT_RATIO (WINDOW_WIDTH \/ WINDOW_HEIGHT)\n#endif\n\n#ifndef PI\n#define PI 3.14159265359f\n#endif\n\n#ifndef EARTH_RADIUS\n#define EARTH_RADIUS 6371000.0f\n#endif\n\n#ifndef TEXT_SIZE\n#define TEXT_SIZE 40\n#endif\n\n#ifndef FONT_SIZE\n#define FONT_SIZE 16\n#endif\n\n#ifndef MAX_FPS\n#define MAX_FPS 60\n#endif\n\nextern glm::vec3 position;\nextern double horizontalAngle;\nextern double verticalAngle;\nextern GLfloat initialFoV;\nextern double earth_radius;\nextern bool hasMouseEverMoved;\nextern bool is_invert_mouse_in_use;\nextern bool is_key_I_released;\nextern bool is_world_loaded; \/\/ no more than one world object can be loaded. TODO: check that no more than one world is loaded!\nextern bool is_world_spherical;\n\ntypedef struct\n{\n    void *world_pointer;                     \/\/ pointer to the world (draw list).\n    std::string vertex_shader;               \/\/ filename of vertex shader.\n    std::string fragment_shader;             \/\/ filename of fragment shader.\n} ShaderStruct;\n\ntypedef struct\n{\n    void *world_pointer;                     \/\/ pointer to the world.\n    std::string texture_file_format;\n    std::string image_path;\n} TextureStruct;\n\ntypedef struct\n{\n    GLuint nodeID;\n    void* graph_pointer;\n    glm::vec3 coordinate_vector;\n    std::vector neighbor_nodeIDs;\n} NodeStruct;\n\ntypedef struct\n{\n    glm::vec3 coordinate_vector;     \/\/ coordinate vector.\n    GLfloat rotate_angle;            \/\/ rotate angle.\n    glm::vec3 rotate_vector;         \/\/ rotate vector.\n    glm::vec3 translate_vector;      \/\/ translate vector.\n    glm::mat4 model_matrix;          \/\/ model matrix.\n    glm::mat4 MVP_matrix;            \/\/ model view projection matrix.\n    void *species_pointer;           \/\/ pointer to the species.\n} ObjectStruct;\n\ntypedef struct\n{\n    \/\/ used for all files (for all species).\n    void *shader_pointer;                    \/\/ pointer to the shader object.\n    std::string model_file_format;           \/\/ type of the model file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"obj\"`\/`\"OBJ\"`.\n                                             \/\/ TODO: add support for `\"SRTM\"`.\n    std::string texture_file_format;         \/\/ type of the texture file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"dds\"`\/`\"DDS\"`.\n    std::string texture_filename;            \/\/ filename of the model file.\n    std::string vertex_shader;               \/\/ filename of vertex shader.\n    std::string fragment_shader;             \/\/ filename of fragment shader.\n    glm::vec3 lightPos;                      \/\/ light position.\n    std::vector object_vector; \/\/ vector of individual objects of this species.\n    bool is_world;                           \/\/ worlds currently do not rotate nor translate.\n    std::string coordinate_system;           \/\/ used only for worlds (`is_world` == `true`). valid values: `\"cartesian\"`.\n                                             \/\/ TODO: add support for `\"spherical\"`. `\"spherical\"` is used eg. in SRTM heightmaps.\n    double world_radius;                    \/\/ radius of sea level in meters. used only for worlds.\n\n    \/\/ for `\"bmp\"` model files.\n    std::string model_filename;              \/\/ filename of the model file.\n    std::string color_channel;               \/\/ color channel to use for altitude data.\n} SpeciesStruct;\n\ntypedef struct\n{\n    GLuint screen_width;\n    GLuint screen_height;\n    GLuint x;\n    GLuint y;\n    GLuint text_size;\n    GLuint font_size;\n    const char *text;\n    const char *char_font_texture_file_format;\n    const char *horizontal_alignment;\n    const char *vertical_alignment;\n} PrintingStruct;\n\ntypedef struct\n{\n    double rho;\n    double theta;\n    double phi;\n} SphericalCoordinatesStruct;\n\ntypedef struct\n{\n    double southern_latitude;\n    double northern_latitude;\n    double western_longitude;\n    double eastern_longitude;\n} SphericalWorldStruct;\n\nextern SphericalCoordinatesStruct spherical_position;\n\n#endif\n<|endoftext|>"}
{"text":"\/\/ -*- mode: c++, coding: utf-8 -*-\n\/**\n * tbrpg – Text based roll playing game\n * \n * Copyright © 2012  Mattias Andrée (maandree@kth.se)\n * \n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see .\n *\/\n#ifndef __GUARD_CHARACTERCREATOR_HPP__\n#define __GUARD_CHARACTERCREATOR_HPP__\n\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"CharacterSheet.hpp\"\n#include \"RuleSet.hpp\"\n#include \"Dice.hpp\"\n#include \"prompter.hpp\"\n\n\n\/**\n * Text based roll playing game\n * \n * DD2387 Program construction with C++\n * Laboration 3\n * \n * @author  Mattias Andrée \n *\/\nnamespace tbrpg\n{\n  \/**\n   * Character creator class\n   *\/\n  class CharacterCreator\n  {\n  protected:\n    \/**\n     * The game's rules\n     *\/\n    RuleSet ruleset;\n    \n    \/**\n     * The start values, these are updated by the assign function\n     *\/\n    int* start;\n    \n    \/**\n     * The lower bounds\n     *\/\n    int* lower;\n    \n    \/**\n     * The upper bounds\n     *\/\n    int* upper;\n    \n    \n    \n  public:\n    \/**\n     * Constructor\n     * \n     * @param  rules  The game's rules\n     *\/\n    CharacterCreator(const RuleSet& rules);\n    \n    \/**\n     * Destructor\n     *\/\n    virtual ~CharacterCreator();\n    \n    \n    \n    \/**\n     * Create a character sheet\n     * \n     * @return  A character sheet, nullptr if aborted\n     *\/\n    virtual CharacterSheet* create() const;\n    \n    \n  protected:\n    \n    \/**\n     * Assign scores\n     * \n     * @param   n           Number of printers\n     * @param   unassigned  Unassigned scores\n     * @param   extra       Extra data to add as argument to the value printer\n     * @param   printer     Value printer, takes arguments: index, value, extra data\n     * @param   reroll      Pointer to a reroll function pointer, nullptr if not allowed\n     * @return              Whether the assignment was completed\n     *\/\n    virtual bool assign(int n, int unassigned, void* data, void (*printer)(int, int, void*), void (**reroll)() == nullptr);\n    \n    \/**\n     * Ability score printer\n     * \n     * @param  index  The index of the ability\n     * @param  value  The value of the ability\n     * @param  data   Pointer to the 100-part of the strenght\n     *\/\n    virtual void abilityPrinter(int index, int value, void* data);\n    \n    \/**\n     * Ability score reroll\n     *\/\n    virtual void abilityReroll();\n    \n  };\n  \n}\n\n\n#endif\/\/__GUARD_CHARACTERCREATOR_HPP__\n\nforgot to stage\/\/ -*- mode: c++, coding: utf-8 -*-\n\/**\n * tbrpg – Text based roll playing game\n * \n * Copyright © 2012  Mattias Andrée (maandree@kth.se)\n * \n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see .\n *\/\n#ifndef __GUARD_CHARACTERCREATOR_HPP__\n#define __GUARD_CHARACTERCREATOR_HPP__\n\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"CharacterSheet.hpp\"\n#include \"RuleSet.hpp\"\n#include \"Dice.hpp\"\n#include \"prompter.hpp\"\n\n\n\/**\n * Text based roll playing game\n * \n * DD2387 Program construction with C++\n * Laboration 3\n * \n * @author  Mattias Andrée \n *\/\nnamespace tbrpg\n{\n  \/**\n   * Character creator class\n   *\/\n  class CharacterCreator\n  {\n  protected:\n    \/**\n     * The game's rules\n     *\/\n    RuleSet ruleset;\n    \n    \/**\n     * The start values, these are updated by the assign function\n     *\/\n    int* start;\n    \n    \/**\n     * The lower bounds\n     *\/\n    int* lower;\n    \n    \/**\n     * The upper bounds\n     *\/\n    int* upper;\n    \n    \n    \n  public:\n    \/**\n     * Constructor\n     * \n     * @param  rules  The game's rules\n     *\/\n    CharacterCreator(const RuleSet& rules);\n    \n    \/**\n     * Destructor\n     *\/\n    virtual ~CharacterCreator();\n    \n    \n    \n    \/**\n     * Create a character sheet\n     * \n     * @return  A character sheet, nullptr if aborted\n     *\/\n    virtual CharacterSheet* create() const;\n    \n    \n  protected:\n    \n    \/**\n     * Assign scores\n     * \n     * @param   n           Number of printers\n     * @param   unassigned  Unassigned scores\n     * @param   extra       Extra data to add as argument to the value printer\n     * @param   printer     Value printer, takes arguments: index, value, extra data\n     * @param   reroll      Pointer to a reroll function pointer, nullptr if not allowed\n     * @return              Whether the assignment was completed\n     *\/\n    virtual bool assign(int n, int unassigned, void* data, void (*printer)(int, int, void*), void (**reroll)() == nullptr);\n    \n    \/**\n     * Ability score printer\n     * \n     * @param  index  The index of the ability\n     * @param  value  The value of the ability\n     * @param  data   Pointer to the 100-part of the strenght\n     *\/\n    virtual void abilityPrinter(int index, int value, void* data) const;\n    \n    \/**\n     * Generic attribute score printer\n     * \n     * @param  index  The index of the attribute\n     * @param  value  The value of the attribute\n     * @param  data   The labels of the attributes\n     *\/\n    virtual void genericPrinter(int index, int value, void* data) const;\n    \n    \/**\n     * Ability score reroll\n     *\/\n    virtual void abilityReroll();\n    \n  };\n  \n}\n\n\n#endif\/\/__GUARD_CHARACTERCREATOR_HPP__\n\n<|endoftext|>"}
{"text":"\/*********************************************************************\n *\n * Copyright 2011 Intel Corporation\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *********************************************************************\/\n\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"os_string.hpp\"\n#include \"os_process.hpp\"\n#include \"os_version.hpp\"\n\n#include \"cli.hpp\"\n#include \"cli_resources.hpp\"\n\n\n#if defined(__APPLE__)\n#define TRACE_VARIABLE \"DYLD_FRAMEWORK_PATH\"\n#define GL_TRACE_WRAPPER  \"OpenGL.framework\/OpenGL\"\n#elif defined(_WIN32)\n#define GL_TRACE_WRAPPER  \"opengl32.dll\"\n#else\n#define TRACE_VARIABLE \"LD_PRELOAD\"\n#define GL_TRACE_WRAPPER  \"glxtrace.so\"\n#define EGL_TRACE_WRAPPER  \"egltrace.so\"\n#endif\n\n\nstatic inline bool\ncopyWrapper(const os::String & wrapperPath,\n            const char *programPath,\n            bool verbose)\n{\n    os::String wrapperFilename(wrapperPath);\n    wrapperFilename.trimDirectory();\n\n    os::String tmpWrapper(programPath);\n    tmpWrapper.trimFilename();\n    tmpWrapper.join(wrapperFilename);\n\n    if (verbose) {\n        std::cerr << wrapperPath << \" -> \" << tmpWrapper << \"\\n\";\n    }\n\n    if (tmpWrapper.exists()) {\n        std::cerr << \"error: not overwriting \" << tmpWrapper << \"\\n\";\n        return false;\n    }\n\n    if (!os::copyFile(wrapperPath, tmpWrapper, false)) {\n        std::cerr << \"error: failed to copy \" << wrapperPath << \" into \" << tmpWrapper << \"\\n\";\n        return false;\n    }\n\n    return true;\n}\n\n\nstatic int\ntraceProgram(trace::API api,\n             char * const *argv,\n             const char *output,\n             bool verbose,\n             bool debug)\n{\n    const char *wrapperFilename;\n    std::vector args;\n    int status = 1;\n\n    \/*\n     * TODO: simplify code\n     *\/\n\n    bool useInject = false;\n    switch (api) {\n    case trace::API_GL:\n        wrapperFilename = GL_TRACE_WRAPPER;\n        break;\n#ifdef EGL_TRACE_WRAPPER\n    case trace::API_EGL:\n        wrapperFilename = EGL_TRACE_WRAPPER;\n        break;\n#endif\n#ifdef _WIN32\n    case trace::API_D3D7:\n        wrapperFilename = \"ddraw.dll\";\n        break;\n    case trace::API_D3D8:\n        wrapperFilename = \"d3d8.dll\";\n        break;\n    case trace::API_D3D9:\n        wrapperFilename = \"d3d9.dll\";\n        break;\n    case trace::API_DXGI:\n        wrapperFilename = \"dxgitrace.dll\";\n        useInject = true;\n        break;\n    case trace::API_D2D1:\n        wrapperFilename = \"d2d1trace.dll\";\n        useInject = true;\n        break;\n#endif\n    default:\n        std::cerr << \"error: unsupported API\\n\";\n        return 1;\n    }\n\n    os::String wrapperPath = findWrapper(wrapperFilename, verbose);\n    if (!wrapperPath.length()) {\n        std::cerr << \"error: failed to find \" << wrapperFilename << \" wrapper (rerun with -v option for more details)\\n\";\n        goto exit;\n    }\n\n#if defined(_WIN32)\n    \/*\n     * Use DLL injection method on Windows, even for APIs that don't stricly\n     * need it.\n     *\/\n    useInject = true;\n\n    if (useInject) {\n        args.push_back(\"inject\");\n        args.push_back(wrapperPath);\n    } else {\n        \/* On Windows copy the wrapper to the program directory.\n         *\/\n        if (!copyWrapper(wrapperPath, argv[0], verbose)) {\n            goto exit;\n        }\n    }\n#else  \/* !_WIN32 *\/\n    (void)useInject;\n#endif \/* !_WIN32 *\/\n\n#if defined(__APPLE__)\n    \/* On Mac OS X, using DYLD_LIBRARY_PATH, we actually set the\n     * parent directory, not the file. *\/\n    wrapperPath.trimFilename();\n    wrapperPath.trimFilename();\n#endif\n\n    \/*\n     * Spawn child process.\n     *\/\n\n    {\n#if defined(TRACE_VARIABLE)\n        const char *oldEnvVarValue = getenv(TRACE_VARIABLE);\n        if (oldEnvVarValue) {\n            wrapperPath.append(OS_PATH_SEP);\n            wrapperPath.append(oldEnvVarValue);\n        }\n\n        std::string ex;\n        if (debug) {\n#if defined(__APPLE__)\n            bool lldb = true;\n#else\n            bool lldb = false;\n#endif\n\n            if (lldb) {\n                \/*\n                 * Debug with LLDB.\n                 *\n                 * See also http:\/\/lldb.llvm.org\/lldb-gdb.html\n                 *\/\n\n                char scriptFileName[] = \"\/tmp\/apitrace.XXXXXX\";\n                int scriptFD = mkstemp(scriptFileName);\n                if (scriptFD < 0) {\n                    std::cerr << \"error: failed to create temporary lldb script file\\n\";\n                    exit(1);\n                }\n\n                FILE *scriptStream = fdopen(scriptFD, \"w\");\n                fprintf(scriptStream, \"env \" TRACE_VARIABLE \"='%s'\\n\", wrapperPath.str());\n                fclose(scriptStream);\n\n                args.push_back(\"lldb\");\n                args.push_back(\"-s\");\n                args.push_back(scriptFileName);\n                args.push_back(\"--\");\n            } else {\n                \/*\n                 * Debug with GDB.\n                 *\/\n\n                ex = \"set exec-wrapper env \" TRACE_VARIABLE \"='\";\n                ex.append(wrapperPath.str());\n                ex.append(\"'\");\n\n                args.push_back(\"gdb\");\n                args.push_back(\"--ex\");\n                args.push_back(ex.c_str());\n                args.push_back(\"--args\");\n            }\n\n            os::unsetEnvironment(TRACE_VARIABLE);\n        } else {\n            \/* FIXME: Don't modify our (ie parent) environment *\/\n            os::setEnvironment(TRACE_VARIABLE, wrapperPath.str());\n        }\n\n        if (verbose) {\n            std::cerr << TRACE_VARIABLE << \"=\" << wrapperPath.str() << \"\\n\";\n        }\n#endif \/* TRACE_VARIABLE *\/\n\n        if (output) {\n            os::setEnvironment(\"TRACE_FILE\", output);\n        }\n\n        for (char * const * arg = argv; *arg; ++arg) {\n            args.push_back(*arg);\n        }\n\n        if (verbose) {\n            const char *sep = \"\";\n            for (unsigned i = 0; i < args.size(); ++i) {\n                const char *quote;\n                if (strchr(args[i], ' ') != NULL) {\n                    quote = \"\\\"\";\n                } else {\n                    quote = \"\";\n                }\n                std::cerr << sep << quote << args[i] << quote;\n                sep = \" \";\n            }\n            std::cerr << \"\\n\";\n        }\n\n        args.push_back(NULL);\n\n        status = os::execute((char * const *)&args[0]);\n\n#if defined(TRACE_VARIABLE)\n        if (oldEnvVarValue) {\n            os::setEnvironment(TRACE_VARIABLE, oldEnvVarValue);\n        } else {\n            os::unsetEnvironment(TRACE_VARIABLE);\n        }\n#endif\n    }\n\nexit:\n#if defined(_WIN32)\n    if (!useInject) {\n        os::String tmpWrapper(argv[0]);\n        tmpWrapper.trimFilename();\n        tmpWrapper.join(wrapperFilename);\n        os::removeFile(tmpWrapper);\n    }\n#endif\n\n    if (output) {\n        os::unsetEnvironment(\"TRACE_FILE\");\n    }\n    \n    return status;\n\n}\n\n\nstatic const char *synopsis = \"Generate a new trace by executing the given program.\";\n\nstatic void\nusage(void)\n{\n    std::cout << \"usage: apitrace trace [OPTIONS] PROGRAM [ARGS ...]\\n\"\n        << synopsis << \"\\n\"\n        \"\\n\"\n        \"    The given program will be executed with the given arguments.\\n\"\n        \"    During execution, all OpenGL calls will be captured to a trace\\n\"\n        \"    file. That trace file can then be used\\n\"\n        \"    with other apitrace utilities for replay or analysis.\\n\"\n        \"\\n\"\n        \"    -v, --verbose       verbose output\\n\"\n        \"    -a, --api=API       specify API to trace (\"\n#ifdef _WIN32\n                                                      \"gl, d3d7, d3d8, d3d9, or dxgi (for d3d10 and higher) \"\n#else\n                                                      \"gl or egl\"\n#endif\n                                                      \");\\n\"\n        \"                        default is `gl`\\n\"\n        \"    -o, --output=TRACE  specify output trace file;\\n\"\n        \"                        default is `PROGRAM.trace`\\n\"\n#ifdef TRACE_VARIABLE\n        \"    -d,  --debug        run inside debugger (gdb\/lldb)\\n\"\n#endif\n    ;\n}\n\nconst static char *\nshortOptions = \"+hva:o:d\";\n\nconst static struct option\nlongOptions[] = {\n    {\"help\", no_argument, 0, 'h'},\n    {\"verbose\", no_argument, 0, 'v'},\n    {\"api\", required_argument, 0, 'a'},\n    {\"output\", required_argument, 0, 'o'},\n    {\"debug\", no_argument, 0, 'd'},\n    {0, 0, 0, 0}\n};\n\nstatic int\ncommand(int argc, char *argv[])\n{\n    bool verbose = false;\n    trace::API api = trace::API_GL;\n    const char *output = NULL;\n    bool debug = false;\n\n    int opt;\n    while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {\n        switch (opt) {\n        case 'h':\n            usage();\n            return 0;\n        case 'v':\n            verbose = true;\n            break;\n        case 'a':\n            if (strcmp(optarg, \"gl\") == 0) {\n                api = trace::API_GL;\n            } else if (strcmp(optarg, \"egl\") == 0) {\n                api = trace::API_EGL;\n            } else if (strcmp(optarg, \"d3d7\") == 0) {\n                api = trace::API_D3D7;\n            } else if (strcmp(optarg, \"d3d8\") == 0) {\n                api = trace::API_D3D8;\n            } else if (strcmp(optarg, \"d3d9\") == 0) {\n                api = trace::API_D3D9;\n            } else if (strcmp(optarg, \"dxgi\") == 0 ||\n                       strcmp(optarg, \"d3d10\") == 0 ||\n                       strcmp(optarg, \"d3d10_1\") == 0 ||\n                       strcmp(optarg, \"d3d11\") == 0 ||\n                       strcmp(optarg, \"d3d11_1\") == 0) {\n                api = trace::API_DXGI;\n            } else if (strcmp(optarg, \"d2d\") == 0 ||\n                       strcmp(optarg, \"d2d1\") == 0) {\n                api = trace::API_D2D1;\n            } else {\n                std::cerr << \"error: unknown API `\" << optarg << \"`\\n\";\n                usage();\n                return 1;\n            }\n            break;\n        case 'o':\n            output = optarg;\n            break;\n        case 'd':\n            debug = true;\n            break;\n        default:\n            std::cerr << \"error: unexpected option `\" << (char)opt << \"`\\n\";\n            usage();\n            return 1;\n        }\n    }\n\n    if (optind == argc) {\n        std::cerr << \"error: no command specified\\n\";\n        usage();\n        return 1;\n    }\n\n    assert(argv[argc] == 0);\n    return traceProgram(api, argv + optind, output, verbose, debug);\n}\n\nconst Command trace_command = {\n    \"trace\",\n    synopsis,\n    usage,\n    command\n};\ncli: Silence unused copyWrapper function warning.\/*********************************************************************\n *\n * Copyright 2011 Intel Corporation\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *********************************************************************\/\n\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"os_string.hpp\"\n#include \"os_process.hpp\"\n#include \"os_version.hpp\"\n\n#include \"cli.hpp\"\n#include \"cli_resources.hpp\"\n\n\n#if defined(__APPLE__)\n#define TRACE_VARIABLE \"DYLD_FRAMEWORK_PATH\"\n#define GL_TRACE_WRAPPER  \"OpenGL.framework\/OpenGL\"\n#elif defined(_WIN32)\n#define GL_TRACE_WRAPPER  \"opengl32.dll\"\n#else\n#define TRACE_VARIABLE \"LD_PRELOAD\"\n#define GL_TRACE_WRAPPER  \"glxtrace.so\"\n#define EGL_TRACE_WRAPPER  \"egltrace.so\"\n#endif\n\n\n#ifdef _WIN32\n\nstatic inline bool\ncopyWrapper(const os::String & wrapperPath,\n            const char *programPath,\n            bool verbose)\n{\n    os::String wrapperFilename(wrapperPath);\n    wrapperFilename.trimDirectory();\n\n    os::String tmpWrapper(programPath);\n    tmpWrapper.trimFilename();\n    tmpWrapper.join(wrapperFilename);\n\n    if (verbose) {\n        std::cerr << wrapperPath << \" -> \" << tmpWrapper << \"\\n\";\n    }\n\n    if (tmpWrapper.exists()) {\n        std::cerr << \"error: not overwriting \" << tmpWrapper << \"\\n\";\n        return false;\n    }\n\n    if (!os::copyFile(wrapperPath, tmpWrapper, false)) {\n        std::cerr << \"error: failed to copy \" << wrapperPath << \" into \" << tmpWrapper << \"\\n\";\n        return false;\n    }\n\n    return true;\n}\n\n#endif \/* _WIN32 *\/\n\n\nstatic int\ntraceProgram(trace::API api,\n             char * const *argv,\n             const char *output,\n             bool verbose,\n             bool debug)\n{\n    const char *wrapperFilename;\n    std::vector args;\n    int status = 1;\n\n    \/*\n     * TODO: simplify code\n     *\/\n\n    bool useInject = false;\n    switch (api) {\n    case trace::API_GL:\n        wrapperFilename = GL_TRACE_WRAPPER;\n        break;\n#ifdef EGL_TRACE_WRAPPER\n    case trace::API_EGL:\n        wrapperFilename = EGL_TRACE_WRAPPER;\n        break;\n#endif\n#ifdef _WIN32\n    case trace::API_D3D7:\n        wrapperFilename = \"ddraw.dll\";\n        break;\n    case trace::API_D3D8:\n        wrapperFilename = \"d3d8.dll\";\n        break;\n    case trace::API_D3D9:\n        wrapperFilename = \"d3d9.dll\";\n        break;\n    case trace::API_DXGI:\n        wrapperFilename = \"dxgitrace.dll\";\n        useInject = true;\n        break;\n    case trace::API_D2D1:\n        wrapperFilename = \"d2d1trace.dll\";\n        useInject = true;\n        break;\n#endif\n    default:\n        std::cerr << \"error: unsupported API\\n\";\n        return 1;\n    }\n\n    os::String wrapperPath = findWrapper(wrapperFilename, verbose);\n    if (!wrapperPath.length()) {\n        std::cerr << \"error: failed to find \" << wrapperFilename << \" wrapper (rerun with -v option for more details)\\n\";\n        goto exit;\n    }\n\n#if defined(_WIN32)\n    \/*\n     * Use DLL injection method on Windows, even for APIs that don't stricly\n     * need it.\n     *\/\n    useInject = true;\n\n    if (useInject) {\n        args.push_back(\"inject\");\n        args.push_back(wrapperPath);\n    } else {\n        \/* On Windows copy the wrapper to the program directory.\n         *\/\n        if (!copyWrapper(wrapperPath, argv[0], verbose)) {\n            goto exit;\n        }\n    }\n#else  \/* !_WIN32 *\/\n    (void)useInject;\n#endif \/* !_WIN32 *\/\n\n#if defined(__APPLE__)\n    \/* On Mac OS X, using DYLD_LIBRARY_PATH, we actually set the\n     * parent directory, not the file. *\/\n    wrapperPath.trimFilename();\n    wrapperPath.trimFilename();\n#endif\n\n    \/*\n     * Spawn child process.\n     *\/\n\n    {\n#if defined(TRACE_VARIABLE)\n        const char *oldEnvVarValue = getenv(TRACE_VARIABLE);\n        if (oldEnvVarValue) {\n            wrapperPath.append(OS_PATH_SEP);\n            wrapperPath.append(oldEnvVarValue);\n        }\n\n        std::string ex;\n        if (debug) {\n#if defined(__APPLE__)\n            bool lldb = true;\n#else\n            bool lldb = false;\n#endif\n\n            if (lldb) {\n                \/*\n                 * Debug with LLDB.\n                 *\n                 * See also http:\/\/lldb.llvm.org\/lldb-gdb.html\n                 *\/\n\n                char scriptFileName[] = \"\/tmp\/apitrace.XXXXXX\";\n                int scriptFD = mkstemp(scriptFileName);\n                if (scriptFD < 0) {\n                    std::cerr << \"error: failed to create temporary lldb script file\\n\";\n                    exit(1);\n                }\n\n                FILE *scriptStream = fdopen(scriptFD, \"w\");\n                fprintf(scriptStream, \"env \" TRACE_VARIABLE \"='%s'\\n\", wrapperPath.str());\n                fclose(scriptStream);\n\n                args.push_back(\"lldb\");\n                args.push_back(\"-s\");\n                args.push_back(scriptFileName);\n                args.push_back(\"--\");\n            } else {\n                \/*\n                 * Debug with GDB.\n                 *\/\n\n                ex = \"set exec-wrapper env \" TRACE_VARIABLE \"='\";\n                ex.append(wrapperPath.str());\n                ex.append(\"'\");\n\n                args.push_back(\"gdb\");\n                args.push_back(\"--ex\");\n                args.push_back(ex.c_str());\n                args.push_back(\"--args\");\n            }\n\n            os::unsetEnvironment(TRACE_VARIABLE);\n        } else {\n            \/* FIXME: Don't modify our (ie parent) environment *\/\n            os::setEnvironment(TRACE_VARIABLE, wrapperPath.str());\n        }\n\n        if (verbose) {\n            std::cerr << TRACE_VARIABLE << \"=\" << wrapperPath.str() << \"\\n\";\n        }\n#endif \/* TRACE_VARIABLE *\/\n\n        if (output) {\n            os::setEnvironment(\"TRACE_FILE\", output);\n        }\n\n        for (char * const * arg = argv; *arg; ++arg) {\n            args.push_back(*arg);\n        }\n\n        if (verbose) {\n            const char *sep = \"\";\n            for (unsigned i = 0; i < args.size(); ++i) {\n                const char *quote;\n                if (strchr(args[i], ' ') != NULL) {\n                    quote = \"\\\"\";\n                } else {\n                    quote = \"\";\n                }\n                std::cerr << sep << quote << args[i] << quote;\n                sep = \" \";\n            }\n            std::cerr << \"\\n\";\n        }\n\n        args.push_back(NULL);\n\n        status = os::execute((char * const *)&args[0]);\n\n#if defined(TRACE_VARIABLE)\n        if (oldEnvVarValue) {\n            os::setEnvironment(TRACE_VARIABLE, oldEnvVarValue);\n        } else {\n            os::unsetEnvironment(TRACE_VARIABLE);\n        }\n#endif\n    }\n\nexit:\n#if defined(_WIN32)\n    if (!useInject) {\n        os::String tmpWrapper(argv[0]);\n        tmpWrapper.trimFilename();\n        tmpWrapper.join(wrapperFilename);\n        os::removeFile(tmpWrapper);\n    }\n#endif\n\n    if (output) {\n        os::unsetEnvironment(\"TRACE_FILE\");\n    }\n    \n    return status;\n\n}\n\n\nstatic const char *synopsis = \"Generate a new trace by executing the given program.\";\n\nstatic void\nusage(void)\n{\n    std::cout << \"usage: apitrace trace [OPTIONS] PROGRAM [ARGS ...]\\n\"\n        << synopsis << \"\\n\"\n        \"\\n\"\n        \"    The given program will be executed with the given arguments.\\n\"\n        \"    During execution, all OpenGL calls will be captured to a trace\\n\"\n        \"    file. That trace file can then be used\\n\"\n        \"    with other apitrace utilities for replay or analysis.\\n\"\n        \"\\n\"\n        \"    -v, --verbose       verbose output\\n\"\n        \"    -a, --api=API       specify API to trace (\"\n#ifdef _WIN32\n                                                      \"gl, d3d7, d3d8, d3d9, or dxgi (for d3d10 and higher) \"\n#else\n                                                      \"gl or egl\"\n#endif\n                                                      \");\\n\"\n        \"                        default is `gl`\\n\"\n        \"    -o, --output=TRACE  specify output trace file;\\n\"\n        \"                        default is `PROGRAM.trace`\\n\"\n#ifdef TRACE_VARIABLE\n        \"    -d,  --debug        run inside debugger (gdb\/lldb)\\n\"\n#endif\n    ;\n}\n\nconst static char *\nshortOptions = \"+hva:o:d\";\n\nconst static struct option\nlongOptions[] = {\n    {\"help\", no_argument, 0, 'h'},\n    {\"verbose\", no_argument, 0, 'v'},\n    {\"api\", required_argument, 0, 'a'},\n    {\"output\", required_argument, 0, 'o'},\n    {\"debug\", no_argument, 0, 'd'},\n    {0, 0, 0, 0}\n};\n\nstatic int\ncommand(int argc, char *argv[])\n{\n    bool verbose = false;\n    trace::API api = trace::API_GL;\n    const char *output = NULL;\n    bool debug = false;\n\n    int opt;\n    while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {\n        switch (opt) {\n        case 'h':\n            usage();\n            return 0;\n        case 'v':\n            verbose = true;\n            break;\n        case 'a':\n            if (strcmp(optarg, \"gl\") == 0) {\n                api = trace::API_GL;\n            } else if (strcmp(optarg, \"egl\") == 0) {\n                api = trace::API_EGL;\n            } else if (strcmp(optarg, \"d3d7\") == 0) {\n                api = trace::API_D3D7;\n            } else if (strcmp(optarg, \"d3d8\") == 0) {\n                api = trace::API_D3D8;\n            } else if (strcmp(optarg, \"d3d9\") == 0) {\n                api = trace::API_D3D9;\n            } else if (strcmp(optarg, \"dxgi\") == 0 ||\n                       strcmp(optarg, \"d3d10\") == 0 ||\n                       strcmp(optarg, \"d3d10_1\") == 0 ||\n                       strcmp(optarg, \"d3d11\") == 0 ||\n                       strcmp(optarg, \"d3d11_1\") == 0) {\n                api = trace::API_DXGI;\n            } else if (strcmp(optarg, \"d2d\") == 0 ||\n                       strcmp(optarg, \"d2d1\") == 0) {\n                api = trace::API_D2D1;\n            } else {\n                std::cerr << \"error: unknown API `\" << optarg << \"`\\n\";\n                usage();\n                return 1;\n            }\n            break;\n        case 'o':\n            output = optarg;\n            break;\n        case 'd':\n            debug = true;\n            break;\n        default:\n            std::cerr << \"error: unexpected option `\" << (char)opt << \"`\\n\";\n            usage();\n            return 1;\n        }\n    }\n\n    if (optind == argc) {\n        std::cerr << \"error: no command specified\\n\";\n        usage();\n        return 1;\n    }\n\n    assert(argv[argc] == 0);\n    return traceProgram(api, argv + optind, output, verbose, debug);\n}\n\nconst Command trace_command = {\n    \"trace\",\n    synopsis,\n    usage,\n    command\n};\n<|endoftext|>"}
{"text":"WaE: class has virtual functions, but destructor is not virtual<|endoftext|>"}
{"text":"\/*\n* Copyright 2017 - KBC Group NV - Franky Braem - The MIT license\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in all\n*  copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n* SOFTWARE.\n*\/\n#include \"Poco\/Delegate.h\"\n#include \"Poco\/Logger.h\"\n#include \"Poco\/Net\/NetException.h\"\n\n#include \"MQ\/MQException.h\"\n#include \"MQ\/Web\/MessageConsumerTask.h\"\n#include \"MQ\/Web\/JSONMessage.h\"\n\nnamespace MQ {\nnamespace Web {\n\nMessageConsumerTask::MessageConsumerTask(Poco::SharedPtr ws, QueueManagerPoolGuard::Ptr queueManagerPoolGuard, const std::string& queueName)\n\t: Poco::Task(\"MessageConsumer\"), _ws(ws), _qmgrPoolGuard(queueManagerPoolGuard), _count(0)\n{\n\tpoco_assert_dbg(!queueManagerPoolGuard.isNull());\n\n\tPoco::Timespan ts(10, 0);\n\t_ws->setReceiveTimeout(ts);\n\t_ws->setSendTimeout(ts);\n\n\tQueueManager::Ptr qmgr = queueManagerPoolGuard->getObject();\n\t_consumer = new MessageConsumer(qmgr, queueName, MessageConsumer::BROWSE);\n\t_consumer->messageEvent += Poco::delegate(this, &MessageConsumerTask::onMessage);\n\t_consumer->errorEvent += Poco::delegate(this, &MessageConsumerTask::onError);\n}\n\nMessageConsumerTask::~MessageConsumerTask()\n{\n\t_consumer->messageEvent -= Poco::delegate(this, &MessageConsumerTask::onMessage);\n\t_consumer->errorEvent -= Poco::delegate(this, &MessageConsumerTask::onError);\n}\n\nvoid MessageConsumerTask::cancel()\n{\n\tPoco::Logger& logger = Poco::Logger::get(\"mq.web\");\n\tlogger.trace(\"MessageConsumerTask cancelling ...\");\n\n\ttry\n\t{\n\t\t_consumer->stop();\n\t}\n\tcatch (MQException&)\n\t{\n\t\t\/\/Ignore to make sure the socket is closed and the task is cancelled.\n\t}\n\n\t_ws->close();\n\n\tPoco::Task::cancel();\n\n\tlogger.trace(\"MessageConsumerTask cancelled.\");\n}\n\nvoid MessageConsumerTask::runTask()\n{\n\tPoco::Logger& logger = Poco::Logger::get(\"mq.web\");\n\tlogger.trace(\"MessageConsumerTask started ...\");\n\n\t_consumer->start();\n\n\tchar buffer[1024];\n\tint n;\n\tint flags;\n\tdo\n\t{\n\t\ttry\n\t\t{\n\t\t\tn = _ws->receiveFrame(buffer, sizeof(buffer), flags);\n\t\t\tlogger.trace(\"Number of messages: so far %d\", _count);\n\t\t}\n\t\tcatch (Poco::TimeoutException&)\n\t\t{\n\t\t\tlogger.trace(\"Timeout\");\n\t\t\tbreak;\n\t\t}\n\t\tcatch (Poco::Net::NetException&)\n\t\t{\n\t\t\tlogger.trace(\"NetException received. WebSocket closed by the client?\");\n\t\t\tbreak;\n\t\t}\n\t} while (n > 0 || (flags & Poco::Net::WebSocket::FRAME_OP_BITMASK) != Poco::Net::WebSocket::FRAME_OP_CLOSE);\n\n\tlogger.trace(\"MessageConsumerTask ended.\");\n}\n\nvoid MessageConsumerTask::onMessage(const void* pSender, Message::Ptr& msg)\n{\n\tPoco::Logger& logger = Poco::Logger::get(\"mq.web\");\n\tlogger.trace(\"A message is received %s\", msg->messageId()->toHex());\n\n\t_count++;\n\n\tJSONMessage jsonMessage(msg);\n\tPoco::JSON::Object::Ptr json = new Poco::JSON::Object();\n\tjsonMessage.toJSON(json);\n\n\tstd::stringstream ss;\n\tjson->stringify(ss);\n\tstd::string content = ss.str();\n\ttry\n\t{\n\t\t_ws->sendFrame(content.c_str(), content.length(), Poco::Net::WebSocket::FRAME_TEXT);\n\t}\n\tcatch (Poco::Exception&)\n\t{\n\t\tcancel();\n\t}\n}\n\nvoid MessageConsumerTask::onError(const void* pSender, MQLONG& rc)\n{\n\tPoco::Logger& logger = Poco::Logger::get(\"mq.web\");\n\tlogger.trace(\"An MQ error is received %ld. Task will be cancelled.\", rc);\n\tcancel();\n}\n\n}} \/\/ Namespace MQ::Web\nAdd mqmd to JSON\/*\n* Copyright 2017 - KBC Group NV - Franky Braem - The MIT license\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in all\n*  copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n* SOFTWARE.\n*\/\n#include \"Poco\/Delegate.h\"\n#include \"Poco\/Logger.h\"\n#include \"Poco\/Net\/NetException.h\"\n\n#include \"MQ\/MQException.h\"\n#include \"MQ\/Web\/MessageConsumerTask.h\"\n#include \"MQ\/Web\/JSONMessage.h\"\n\nnamespace MQ {\nnamespace Web {\n\nMessageConsumerTask::MessageConsumerTask(Poco::SharedPtr ws, QueueManagerPoolGuard::Ptr queueManagerPoolGuard, const std::string& queueName)\n\t: Poco::Task(\"MessageConsumer\"), _ws(ws), _qmgrPoolGuard(queueManagerPoolGuard), _count(0)\n{\n\tpoco_assert_dbg(!queueManagerPoolGuard.isNull());\n\n\tPoco::Timespan ts(10, 0);\n\t_ws->setReceiveTimeout(ts);\n\t_ws->setSendTimeout(ts);\n\n\tQueueManager::Ptr qmgr = queueManagerPoolGuard->getObject();\n\t_consumer = new MessageConsumer(qmgr, queueName, MessageConsumer::BROWSE);\n\t_consumer->messageEvent += Poco::delegate(this, &MessageConsumerTask::onMessage);\n\t_consumer->errorEvent += Poco::delegate(this, &MessageConsumerTask::onError);\n}\n\nMessageConsumerTask::~MessageConsumerTask()\n{\n\t_consumer->messageEvent -= Poco::delegate(this, &MessageConsumerTask::onMessage);\n\t_consumer->errorEvent -= Poco::delegate(this, &MessageConsumerTask::onError);\n}\n\nvoid MessageConsumerTask::cancel()\n{\n\tPoco::Logger& logger = Poco::Logger::get(\"mq.web\");\n\tlogger.trace(\"MessageConsumerTask cancelling ...\");\n\n\ttry\n\t{\n\t\t_consumer->stop();\n\t}\n\tcatch (MQException&)\n\t{\n\t\t\/\/Ignore to make sure the socket is closed and the task is cancelled.\n\t}\n\n\t_ws->close();\n\n\tPoco::Task::cancel();\n\n\tlogger.trace(\"MessageConsumerTask cancelled.\");\n}\n\nvoid MessageConsumerTask::runTask()\n{\n\tPoco::Logger& logger = Poco::Logger::get(\"mq.web\");\n\tlogger.trace(\"MessageConsumerTask started ...\");\n\n\t_consumer->start();\n\n\tchar buffer[1024];\n\tint n;\n\tint flags;\n\tdo\n\t{\n\t\ttry\n\t\t{\n\t\t\tn = _ws->receiveFrame(buffer, sizeof(buffer), flags);\n\t\t\tlogger.trace(\"Number of messages: so far %d\", _count);\n\t\t}\n\t\tcatch (Poco::TimeoutException&)\n\t\t{\n\t\t\tlogger.trace(\"Timeout\");\n\t\t\tbreak;\n\t\t}\n\t\tcatch (Poco::Net::NetException&)\n\t\t{\n\t\t\tlogger.trace(\"NetException received. WebSocket closed by the client?\");\n\t\t\tbreak;\n\t\t}\n\t} while (n > 0 || (flags & Poco::Net::WebSocket::FRAME_OP_BITMASK) != Poco::Net::WebSocket::FRAME_OP_CLOSE);\n\n\tlogger.trace(\"MessageConsumerTask ended.\");\n}\n\nvoid MessageConsumerTask::onMessage(const void* pSender, Message::Ptr& msg)\n{\n\tPoco::Logger& logger = Poco::Logger::get(\"mq.web\");\n\tlogger.trace(\"A message is received %s\", msg->messageId()->toHex());\n\n\t_count++;\n\n\tJSONMessage jsonMessage(msg);\n\tPoco::JSON::Object::Ptr json = new Poco::JSON::Object();\n\tjson->set(\"mqmd\", jsonMessage.toJSONMQMD());\n\tjsonMessage.toJSON(json);\n\n\tstd::stringstream ss;\n\tjson->stringify(ss);\n\tstd::string content = ss.str();\n\ttry\n\t{\n\t\t_ws->sendFrame(content.c_str(), content.length(), Poco::Net::WebSocket::FRAME_TEXT);\n\t}\n\tcatch (Poco::Exception&)\n\t{\n\t\tcancel();\n\t}\n}\n\nvoid MessageConsumerTask::onError(const void* pSender, MQLONG& rc)\n{\n\tPoco::Logger& logger = Poco::Logger::get(\"mq.web\");\n\tlogger.trace(\"An MQ error is received %ld. Task will be cancelled.\", rc);\n\tcancel();\n}\n\n}} \/\/ Namespace MQ::Web\n<|endoftext|>"}
{"text":"\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/magnet_uri.hpp\"\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/torrent_handle.hpp\"\n#include \"libtorrent\/escape_string.hpp\"\n\n#include \n#include \n\nnamespace libtorrent\n{\n\tstd::string make_magnet_uri(torrent_handle const& handle)\n\t{\n\t\tstd::stringstream ret;\n\t\tif (!handle.is_valid()) return ret.str();\n\n\t\tstd::string name = handle.name();\n\n\t\tret << \"magnet:?xt=urn:btih:\" << base32encode((char*)handle.info_hash().begin());\n\t\tif (!name.empty())\n\t\t\tret << \"&dn=\" << escape_string(name.c_str(), name.length());\n\t\ttorrent_status st = handle.status();\n\t\tif (!st.current_tracker.empty())\n\t\t{\n\t\t\tret << \"&tr=\" << escape_string(st.current_tracker.c_str()\n\t\t\t\t, st.current_tracker.length());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::vector const& tr = handle.trackers();\n\t\t\tif (!tr.empty())\n\t\t\t{\n\t\t\t\tret << \"&tr=\" << escape_string(tr[0].url.c_str()\n\t\t\t\t\t, tr[0].url.length());\n\t\t\t}\n\t\t}\n\t\treturn ret.str();\n\t}\n\n\ttorrent_handle add_magnet_uri(session& ses, std::string const& uri\n\t\t, fs::path const& save_path\n\t\t, storage_mode_t storage_mode\n\t\t, bool paused\n\t\t, storage_constructor_type sc\n\t\t, void* userdata)\n\t{\n\t\tstd::string name;\n\t\tstd::string tracker;\n\n\t\tboost::optional display_name = url_has_argument(uri, \"dn\");\n\t\tif (display_name) name = unescape_string(display_name->c_str());\n\t\tboost::optional tracker_string = url_has_argument(uri, \"tr\");\n\t\tif (tracker_string) tracker = unescape_string(tracker_string->c_str());\n\t\n\t\tboost::optional btih = url_has_argument(uri, \"xt\");\n\t\tif (!btih) return torrent_handle();\n\n\t\tif (btih->compare(0, 9, \"urn:btih:\") != 0) return torrent_handle();\n\n\t\tsha1_hash info_hash(base32decode(btih->substr(9)));\n\n\t\treturn ses.add_torrent(tracker.empty() ? 0 : tracker.c_str(), info_hash\n\t\t\t, name.empty() ? 0 : name.c_str(), save_path, entry()\n\t\t\t, storage_mode, paused, sc, userdata);\n\t}\n}\n\n\nfixed bug in make_magnet_uri\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/magnet_uri.hpp\"\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/torrent_handle.hpp\"\n#include \"libtorrent\/escape_string.hpp\"\n\n#include \n#include \n\nnamespace libtorrent\n{\n\tstd::string make_magnet_uri(torrent_handle const& handle)\n\t{\n\t\tstd::stringstream ret;\n\t\tif (!handle.is_valid()) return ret.str();\n\n\t\tstd::string name = handle.name();\n\n\t\tret << \"magnet:?xt=urn:btih:\" << base32encode(\n\t\t\tstd::string((char*)handle.info_hash().begin(), 20));\n\t\tif (!name.empty())\n\t\t\tret << \"&dn=\" << escape_string(name.c_str(), name.length());\n\t\ttorrent_status st = handle.status();\n\t\tif (!st.current_tracker.empty())\n\t\t{\n\t\t\tret << \"&tr=\" << escape_string(st.current_tracker.c_str()\n\t\t\t\t, st.current_tracker.length());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::vector const& tr = handle.trackers();\n\t\t\tif (!tr.empty())\n\t\t\t{\n\t\t\t\tret << \"&tr=\" << escape_string(tr[0].url.c_str()\n\t\t\t\t\t, tr[0].url.length());\n\t\t\t}\n\t\t}\n\t\treturn ret.str();\n\t}\n\n\ttorrent_handle add_magnet_uri(session& ses, std::string const& uri\n\t\t, fs::path const& save_path\n\t\t, storage_mode_t storage_mode\n\t\t, bool paused\n\t\t, storage_constructor_type sc\n\t\t, void* userdata)\n\t{\n\t\tstd::string name;\n\t\tstd::string tracker;\n\n\t\tboost::optional display_name = url_has_argument(uri, \"dn\");\n\t\tif (display_name) name = unescape_string(display_name->c_str());\n\t\tboost::optional tracker_string = url_has_argument(uri, \"tr\");\n\t\tif (tracker_string) tracker = unescape_string(tracker_string->c_str());\n\t\n\t\tboost::optional btih = url_has_argument(uri, \"xt\");\n\t\tif (!btih) return torrent_handle();\n\n\t\tif (btih->compare(0, 9, \"urn:btih:\") != 0) return torrent_handle();\n\n\t\tsha1_hash info_hash(base32decode(btih->substr(9)));\n\n\t\treturn ses.add_torrent(tracker.empty() ? 0 : tracker.c_str(), info_hash\n\t\t\t, name.empty() ? 0 : name.c_str(), save_path, entry()\n\t\t\t, storage_mode, paused, sc, userdata);\n\t}\n}\n\n\n<|endoftext|>"}
{"text":"\/\/ ========================================================================== \/\/\n\/\/ This file is part of DO++, a basic set of libraries in C++ for computer \n\/\/ vision.\n\/\/\n\/\/ Copyright (C) 2013 David Ok \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public \n\/\/ License v. 2.0. If a copy of the MPL was not distributed with this file, \n\/\/ you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================== \/\/\n\n#ifndef DO_KDTREE_KDTREE_HPP\n#define DO_KDTREE_KDTREE_HPP\n\n\/\/ DISCLAIMER REGARDING FLANN 1.8.4:\n\/\/\n\/\/ I have disabled compiler warnings for MSVC in the CMakeLists.txt of FLANN.\n\/\/\n\/\/ There is still a disturbing compiler warning with MSVC:\n\/\/ FLANN 1.8.4 will issue compiler warning because of a reimplemented\n\/\/ operator new*(...) and the corresponding operator delete [] is not implemented.\n\/\/ I seriously hope there won't be memory-leak as argued in the changelog...\n\/\/ serialization functions in FLANN 1.8.4 do not compile as well...\n\n#include \n#include \n\n\/\/ The data structure will likely evolve again in order to be fully \"templated\".\n\/\/ Still, it is enough as it does what I need to do.\n\/\/ See if the compile time of template instantiation is not a burden for a quick\n\/\/ prototyping in practice.\n\nnamespace DO {\n\n  \/*! VERY IMPORTANT TECHNICAL DETAIL: MatrixXd uses a *** COLUMN-MAJOR *** \n   *  storage in the core library.\n   *  The matrix must be transposed before.\n   *  I say this because it seems common to stack data in a row major fashion.\n   * \n   *  Therefore, data points are column vectors in MatrixXd !!\n   *  However FLANN uses a row major storage.\n   *  So, please listen to Michael Jackson: \n   *    DO THINK TWICE ! (... She told my baby that we danced 'til three...)\n   *  And have a look on the DOKDTree.cpp, which tests the KDTree data-structure\n   *\/\n  class KDTree\n  {\n  public:\n    KDTree(const MatrixXd& colMajorColStackedDataMatrix,\n           const flann::KDTreeIndexParams& indexParams = flann::KDTreeIndexParams(1),\n           const flann::SearchParams& searchParams = flann::SearchParams(-1));\n    ~KDTree();\n\n    \/\/! Basic k-NN search wrapped function.\n    template \n    void knnSearch(const Matrix& query,\n                   size_t k,\n                   std::vector& indices, std::vector& sqDists,\n                   bool remove1NN = false)\n    {\n      if (data_.cols != query.size())\n        throw std::runtime_error(\"Dimension of query vector do not match \\\n                                 dimension of input feature space!\");\n      if (remove1NN)\n      {\n        knnSearch(query.data(), k+1, indices, sqDists);\n        indices.erase(indices.begin());\n        sqDists.erase(sqDists.begin());\n      }\n      else\n        knnSearch(query.data(), k, indices, sqDists);\n    }\n    \/\/! Basic k-NN search wrapped function.\n    template \n    void knnSearch(const Matrix& query,\n                   size_t k, std::vector& indices,\n                   bool remove1NN = false)\n    {\n      if (data_.cols != query.size())\n        throw std::runtime_error(\"Dimension of query vector do not match \\\n                                 dimension of input feature space!\");\n      std::vector sqDists;\n      if (remove1NN)\n      {\n        knnSearch(query.data(), k+1, indices, sqDists);\n        indices.erase(indices.begin());\n        sqDists.erase(sqDists.begin());\n      }\n      else\n        knnSearch(query.data(), k, indices, sqDists);\n    }\n    \/\/! Basic k-NN search  wrapped function.\n    void knnSearch(const MatrixXd& queries, size_t k,\n                   std::vector >& indices,\n                   std::vector >& sqDists,\n                   bool remove1NN = false);\n    \/\/! Basic k-NN search wrapped function.\n    void knnSearch(const MatrixXd& queries, size_t k,\n                   std::vector >& indices,\n                   bool remove1NN = false);\n    \/\/! In case the point query is a point in data, call this method preferably.\n    void knnSearch(size_t i, size_t k,\n                   std::vector& indices, std::vector& sqDists);\n    \/\/! In case the point query is a point in data, call this method preferably.\n    void knnSearch(size_t i, size_t k, std::vector& indices);\n    \/\/! In case the point query is a point in data, call this method preferably.\n    void knnSearch(const std::vector& queries, size_t k,\n                   std::vector >& indices,\n                   std::vector >& sqDists);\n    \/\/! In case the point query is a point in data, call this method preferably.\n    void knnSearch(const std::vector& queries, size_t k,\n                   std::vector >& indices);\n    \n    \/\/! Basic radius search wrapped function.\n    template \n    size_t radiusSearch(const Matrix& query,\n                        double sqSearchRadius,\n                        std::vector& indices, std::vector& sqDists,\n                        bool remove1NN = false)\n    {\n      if (data_.cols != query.size())\n          throw std::runtime_error(\"Dimension of query vector do not match \\\n                                   dimension of input feature space!\");\n      radiusSearch(query.data(), sqSearchRadius, indices, sqDists);\n      if (remove1NN)\n      {\n        indices.erase(indices.begin());\n        sqDists.erase(sqDists.begin());\n      }\n      return indices.size(); \n    }\n    \/\/! Basic radius search wrapped function.\n    template \n    size_t radiusSearch(const Matrix& query,\n                        double sqSearchRadius, std::vector& indices,\n                        bool remove1NN = false)\n    {\n      if (data_.cols != query.size())\n          throw std::runtime_error(\"Dimension of query vector do not match \\\n                                   dimension of input feature space!\");\n      std::vector sqDists;\n      radiusSearch(query.data(), sqSearchRadius, indices, sqDists);\n      if (remove1NN)\n      {\n        indices.erase(indices.begin());\n        sqDists.erase(sqDists.begin());\n      }\n      return indices.size();\n    }\n    \/\/! Basic radius search wrapped function.\n    void radiusSearch(const MatrixXd& queries, double sqSearchRadius,\n                      std::vector >& indices,\n                      std::vector >& sqDists,\n                      bool remove1NN = false);\n    \/\/! Basic radius search wrapped function.\n    void radiusSearch(const MatrixXd& queries, double sqSearchRadius,\n                      std::vector >& indices,\n                      bool remove1NN);\n    \/\/! In case the point query is a point in data, call this method preferably.\n    int radiusSearch(size_t i, double sqSearchRadius,\n                      std::vector& indices, std::vector& sqDists);\n    \/\/! In case the point query is a point in data, call this method preferably.\n    int radiusSearch(size_t i, double sqSearchRadius, std::vector& indices);\n    \/\/! In case the point query is a point in data, call this method preferably.\n    void radiusSearch(const std::vector& queries, double sqSearchRadius,\n                      std::vector >& indices,\n                      std::vector >& sqDists);\n    \/\/! In case the point query is a point in data, call this method preferably.\n    void radiusSearch(const std::vector& queries, double sqSearchRadius,\n                      std::vector >& indices);\n\n  private:\n    void knnSearch(const double *query, size_t k,\n                  std::vector& indices, std::vector& sqDists);\n\n    int radiusSearch(const double *query, double sqSearchRadius,\n                      std::vector& indices, std::vector& sqDists);\n\n  private:\n    bool wrapped_data_;\n    flann::Matrix data_;\n    flann::Index > index_;\n    flann::KDTreeIndexParams index_params_;\n    flann::SearchParams search_params_;\n  };\n\n}\n\n#endif \/* DO_KDTREE_KDTREE_HPP *\/Clean up code.\/\/ ========================================================================== \/\/\n\/\/ This file is part of DO++, a basic set of libraries in C++ for computer \n\/\/ vision.\n\/\/\n\/\/ Copyright (C) 2013 David Ok \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public \n\/\/ License v. 2.0. If a copy of the MPL was not distributed with this file, \n\/\/ you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================== \/\/\n\n#ifndef DO_KDTREE_KDTREE_HPP\n#define DO_KDTREE_KDTREE_HPP\n\n\n#include \n#include \n\n\nnamespace DO {\n\n  \/*!\n   *  N.B.: MatrixXd uses a *** COLUMN-MAJOR *** storage in the core library.\n   *  The matrix must be transposed before.\n   *\n   *  Therefore, data points are column vectors in MatrixXd !!\n   *\/\n  class KDTree\n  {\n  public:\n    \/\/! Constructor.\n    KDTree(const MatrixXd& colMajorColStackedDataMatrix,\n           const flann::KDTreeIndexParams& indexParams\n             = flann::KDTreeIndexParams(1),\n           const flann::SearchParams& searchParams\n             = flann::SearchParams(-1));\n    \n    \/\/! \\brief Destructor\n    ~KDTree();\n\n    \/\/! Basic k-NN search wrapped function.\n    template \n    void knn_search(const Matrix& query,\n                    size_t k,\n                    std::vector& indices,\n                    std::vector& sqDists,\n                    bool remove1NN = false)\n    {\n      if (data_.cols != query.size())\n        throw std::runtime_error(\"Dimension of query vector do not match \\\n                                 dimension of input feature space!\");\n      if (remove1NN)\n      {\n        knn_search(query.data(), k+1, indices, sqDists);\n        indices.erase(indices.begin());\n        sqDists.erase(sqDists.begin());\n      }\n      else\n        knn_search(query.data(), k, indices, sqDists);\n    }\n\n    \/\/! Basic k-NN search wrapped function.\n    template \n    void knn_search(const Matrix& query,\n                    size_t k, std::vector& indices,\n                    bool remove1NN = false)\n    {\n      if (data_.cols != query.size())\n        throw std::runtime_error(\"Dimension of query vector do not match \\\n                                 dimension of input feature space!\");\n      std::vector sqDists;\n      if (remove1NN)\n      {\n        knn_search(query.data(), k+1, indices, sqDists);\n        indices.erase(indices.begin());\n        sqDists.erase(sqDists.begin());\n      }\n      else\n        knn_search(query.data(), k, indices, sqDists);\n    }\n\n    \/\/! Basic k-NN search  wrapped function.\n    void knn_search(const MatrixXd& queries, size_t k,\n                   std::vector >& indices,\n                   std::vector >& sqDists,\n                   bool remove1NN = false);\n\n    \/\/! Basic k-NN search wrapped function.\n    void knn_search(const MatrixXd& queries, size_t k,\n                   std::vector >& indices,\n                   bool remove1NN = false);\n\n    \/\/! In case the point query is a point in data, call this method preferably.\n    void knn_search(size_t i, size_t k,\n                    std::vector& indices, std::vector& sqDists);\n\n    \/\/! In case the point query is a point in data, call this method preferably.\n    void knn_search(size_t i, size_t k, std::vector& indices);\n\n    \/\/! In case the point query is a point in data, call this method preferably.\n    void knn_search(const std::vector& queries, size_t k,\n                    std::vector >& indices,\n                    std::vector >& sqDists);\n\n    \/\/! In case the point query is a point in data, call this method preferably.\n    void knn_search(const std::vector& queries, size_t k,\n                    std::vector >& indices);\n    \n    \/\/! Basic radius search wrapped function.\n    template \n    size_t radius_search(const Matrix& query,\n                         double sqSearchRadius,\n                         std::vector& indices,\n                         std::vector& sqDists,\n                         bool remove1NN = false)\n    {\n      if (data_.cols != query.size())\n          throw std::runtime_error(\"Dimension of query vector do not match \\\n                                   dimension of input feature space!\");\n      radius_search(query.data(), sqSearchRadius, indices, sqDists);\n      if (remove1NN)\n      {\n        indices.erase(indices.begin());\n        sqDists.erase(sqDists.begin());\n      }\n      return indices.size(); \n    }\n\n    \/\/! Basic radius search wrapped function.\n    template \n    size_t radius_search(const Matrix& query,\n                         double sqSearchRadius,\n                         std::vector& indices,\n                         bool remove1NN = false)\n    {\n      if (data_.cols != query.size())\n          throw std::runtime_error(\"Dimension of query vector do not match \\\n                                   dimension of input feature space!\");\n      std::vector sqDists;\n      radius_search(query.data(), sqSearchRadius, indices, sqDists);\n      if (remove1NN)\n      {\n        indices.erase(indices.begin());\n        sqDists.erase(sqDists.begin());\n      }\n      return indices.size();\n    }\n\n    \/\/! Basic radius search wrapped function.\n    void radius_search(const MatrixXd& queries, double sqSearchRadius,\n                       std::vector >& indices,\n                       std::vector >& sqDists,\n                       bool remove1NN = false);\n\n    \/\/! Basic radius search wrapped function.\n    void radius_search(const MatrixXd& queries, double sqSearchRadius,\n                       std::vector >& indices,\n                       bool remove1NN);\n\n    \/\/! In case the point query is a point in data, call this method preferably.\n    int radius_search(size_t i, double sqSearchRadius,\n                      std::vector& indices, std::vector& sqDists);\n\n    \/\/! In case the point query is a point in data, call this method preferably.\n    int radius_search(size_t i, double sqSearchRadius,\n                      std::vector& indices);\n\n    \/\/! In case the point query is a point in data, call this method preferably.\n    void radius_search(const std::vector& queries, double sqSearchRadius,\n                       std::vector >& indices,\n                       std::vector >& sqDists);\n\n    \/\/! In case the point query is a point in data, call this method preferably.\n    void radius_search(const std::vector& queries,\n                       double sqSearchRadius,\n                       std::vector >& indices);\n\n  private:\n    void knn_search(const double *query, size_t k,\n                    std::vector& indices, std::vector& sqDists);\n\n    int radius_search(const double *query, double sqSearchRadius,\n                      std::vector& indices, std::vector& sqDists);\n\n  private:\n    bool wrapped_data_;\n    flann::Matrix data_;\n    flann::Index > index_;\n    flann::KDTreeIndexParams index_params_;\n    flann::SearchParams search_params_;\n  };\n\n}\n\n\n#endif \/* DO_KDTREE_KDTREE_HPP *\/<|endoftext|>"}
{"text":"\/\/\n\/\/ Created by admarkov on 25.04.17.\n\/\/\n\n#include \"ast.h\"\n#include \"tokens.h\"\n\nNode* buildAST(TokenStream stream, Node* root = nullptr, Node* p = nullptr) {\n    if (stream.findInflection()!=-1) {\n        TokenStream left, right;\n        Token inflection;\n        stream.split(inflection,left,right);\n        Node* n = new Node(p, inflection.data, nullptr, nullptr);\n        if (root==nullptr) root=n;\n        n->left=buildAST(left, root, n);\n        n->right=buildAST(right, root, n);\n        return n;\n    }\n    else {\n        Token t = stream.get(1);\n        if (t.data!=\"(\") {\n            if (t.type==\"function\") {\n                Node *n = new Node(p, t.data, nullptr, nullptr);\n                if (root == nullptr) root = n;\n                stream.breakBrackets();\n                n->left=buildAST(stream, root, n);\n                return n;\n            }\n            if (t.type==\"constant\") {\n                Node *n = new Node(p, t.data, nullptr, nullptr);\n                if (root == nullptr) root = n;\n                return n;\n            }\n            if (t.type==\"variable\") {\n                var *n = new var(t.data, root, p);\n                if (n->root==nullptr) n->root=n;\n                return (Node*)n;\n            }\n        }\n        else {\n            stream.breakBrackets();\n            return buildAST(stream, root, p);\n        }\n    }\n}Abandoned of \"var\" subclass\/\/\n\/\/ Created by admarkov on 25.04.17.\n\/\/\n\n#include \"ast.h\"\n#include \"tokens.h\"\n\nNode* buildAST(TokenStream stream, Node* root = nullptr, Node* p = nullptr) {\n    if (stream.findInflection()!=-1) {\n        TokenStream left, right;\n        Token inflection;\n        stream.split(inflection,left,right);\n        Node* n = new Node(p, root, \"operator\", inflection.data, nullptr, nullptr);\n        if (root==nullptr) root=n;\n        n->left=buildAST(left, root, n);\n        n->right=buildAST(right, root, n);\n        return n;\n    }\n    else {\n        Token t = stream.get(1);\n        if (t.data!=\"(\") {\n            if (t.type==\"function\") {\n                Node *n = new Node(p, root, t.type, t.data, nullptr, nullptr);\n                if (root == nullptr) root = n;\n                stream.breakBrackets();\n                n->left=buildAST(stream, root, n);\n                return n;\n            }\n            if (t.type==\"constant\") {\n                Node *n = new Node(p, root, t.type, t.data, nullptr, nullptr);\n                if (root == nullptr) root = n;\n                return n;\n            }\n            if (t.type==\"variable\") {\n                Node *n = new Node(p, root, t.type, t.data, nullptr, nullptr);\n                if (n->root==nullptr) n->root=n;\n                return (Node*)n;\n            }\n        }\n        else {\n            stream.breakBrackets();\n            return buildAST(stream, root, p);\n        }\n    }\n}<|endoftext|>"}
{"text":"#include \"window.h\"\n#include \"map_window.h\"\n#include \"inspection_window.h\"\n#include \"equipment_window.h\"\n#include \"gameengine.h\"\n#include \"event.h\"\n\n\nvoid MapWindow::gainFocus ()\n{\n    getEngine()->loadMap(50, 50);\n\n    setTitle (\"Map\");\n\n    m_mapXOffset = 1;\n    m_mapYOffset = 9;\n    m_mapStartX = 0;\n    m_mapStartY = 0;\n    m_mapWidth  = 0;\n    m_mapHeight = 0;\n    m_sidebarWidth = 20;\n    m_sidebarXOffset = getWidth() - m_sidebarWidth;\n\n    m_action = 'm';\n    m_lastDraw = clock();\n}\n\nvoid MapWindow::redraw() {\n\n    \/\/clock_t l_clock = clock() - m_lastDraw;\n    \/\/double l_diff = static_cast (l_clock\/CLOCKS_PER_SEC);\n    \/\/if (l_diff < 0.01f) return;\n\n    drawSeparators();\n    drawMap();\n    drawMessages();\n    drawSidebar();\n}\n\nvoid MapWindow::resize() {\n    setDimensions (0, 0, getEngine()->getGraphics()->getScreenWidth(), getEngine()->getGraphics()->getScreenHeight());\n    m_sidebarXOffset = getWidth() - m_sidebarWidth - 1;\n    m_mapWidth  = getWidth() - m_mapXOffset - m_sidebarWidth - 1;\n    m_mapHeight = getHeight() - m_mapYOffset - 1;\n}\n\nvoid MapWindow::keyDown (unsigned char key) {\n    Window::keyDown (key);\n\n    if (key == 'w' || key == 'a' || key == 's' || key == 'd') {\n        DIRECTION l_dir = Direction::None;\n        switch (key) {\n            case 'w': l_dir = Direction::North; break;\n            case 'a': l_dir = Direction::West;  break;\n            case 's': l_dir = Direction::South; break;\n            case 'd': l_dir = Direction::East;  break;\n        }\n\n        if (m_action == 'm') {\n            MoveEntityEvent* l_event = new MoveEntityEvent;\n            l_event->entity = getEngine()->getEntities()->getPlayer();\n            l_event->direction = l_dir;\n            getEngine()->raiseEvent (l_event);\n        }\n        if (m_action == 'k') {\n            AttackEntityEvent* l_event = new AttackEntityEvent;\n            l_event->entity = getEngine()->getEntities()->getPlayer();\n            l_event->direction = l_dir;\n            getEngine()->raiseEvent (l_event);\n        }\n        if (m_action == 'i') {\n            EntityHolder l_entities = getEngine()->getEntities()->findEntitiesToThe(l_dir, getEngine()->getEntities()->getPlayer());\n            if (l_entities.size() > 0) {\n                EntityId* l_target = new EntityId(*l_entities.begin());\n\n                InspectionWindow* l_win = new InspectionWindow();\n                l_win->initialise(getEngine(), l_target);\n                getEngine()->getWindows()->pushWindow (l_win);\n            }\n        }\n        if (m_action != 'i') getEngine()->swapTurn();\n        m_action = 'm';\n    }\n    if (key == 27) {\n        getEngine()->quit();\n    }\n    if (key == 'm' ||\n        key == 'k' ||\n        key == 'i') {\n        m_action = key;\n    }\n    if (key == '.') {\n        getEngine()->swapTurn();\n    }\n    if (key == 'p') {\n        Location l_playerLoc = getEngine()->getEntities()->getLocation(getEngine()->getEntities()->getPlayer());\n        EntityHolder l_entities = getEngine()->getEntities()->findEntitiesAt (l_playerLoc.x, l_playerLoc.y);\n        bool foundSomethingAlready = false;\n        for (EntityId l_entity : l_entities) {\n            DroppableComponent* droppable = getEngine()->getEntities()->getDroppables()->get(l_entity);\n            if (droppable) {\n                if (!foundSomethingAlready) {\n                    PickupEquipmentEvent* event = new PickupEquipmentEvent();\n                    event->entity = getEngine()->getEntities()->getPlayer();\n                    event->item = l_entity;\n                    getEngine()->raiseEvent (event);\n                    foundSomethingAlready = true;\n                } else {\n                    getEngine()->addMessage(INFO, \"There's something else here...\");\n                    break;\n                }\n            }\n        }\n        if (!foundSomethingAlready) {\n            getEngine()->addMessage(INFO, \"There's nothing here...\");\n        }\n    }\n    if (key == 'E') {\n        EquipmentWindow* l_win = new EquipmentWindow();\n        l_win->initialise(getEngine());\n        getEngine()->getWindows()->pushWindow (l_win);\n    }\n}\n\nvoid MapWindow::drawSeparators() {\n    getEngine()->getGraphics()->drawBorder (m_mapYOffset-1, m_mapXOffset-1, m_mapHeight, m_mapWidth);\n    getEngine()->getGraphics()->drawBorder (0, m_sidebarXOffset, getHeight()-2, m_sidebarWidth-1);\n}\n\nvoid MapWindow::drawMap() {\n    Location l_player = getEngine()->getEntities()->getLocation(getEngine()->getEntities()->getPlayer());\n    m_mapStartX = l_player.x - (m_mapWidth\/2);\n    m_mapStartY = l_player.y - (m_mapHeight\/2);\n\n    int xWidth = m_mapStartX + m_mapWidth;\n    int yWidth = m_mapStartY + m_mapHeight;\n\n    for (int yy = m_mapStartY; yy < yWidth; yy++) {\n        for (int xx = m_mapStartX; xx < xWidth; xx++) {\n            if (!getEngine()->isValidTile (xx, yy, getEngine()->getLevel())) continue;\n            Tile& l_tile = getEngine()->getTile (xx, yy, getEngine()->getLevel());\n            for (EntityId entity : l_tile.entities) {\n                SpriteComponent* l_sprite= getEngine()->getEntities()->getSprites()->get (entity);\n                if (!l_sprite) continue;\n                drawTile (  yy + m_mapYOffset - m_mapStartY,\n                            xx + m_mapXOffset - m_mapStartX,\n                            l_sprite->sprite,\n                            l_sprite->fgColor,\n                            l_sprite->bgColor);\n\n            }\n        }\n    }\n\n    return;\n}\n\nvoid MapWindow::drawMessages()\n{\n    std::vector& l_messages = getEngine()->getMessages();\n    size_t ii = l_messages.size();\n    size_t hh = m_mapYOffset-2;\n\n    for (; ii > 0 && hh > 0; hh--, ii--) {\n        Color fg;\n        switch (l_messages[ii-1].severity) {\n            case INFO: fg = Color (WHITE); break;\n            case WARN: fg = Color (RED); break;\n            case GOOD: fg = Color (GREEN); break;\n            case CRIT: fg = Color (BLUE); break;\n        }\n        drawString (hh, 1, l_messages[ii-1].message.c_str(), fg);\n    }\n}\n\nvoid MapWindow::drawSidebar ()\n{\n    \/\/ Current health\n    drawString (2, m_sidebarXOffset+2, \"Health:\");\n    EntityId player = getEngine()->getEntities()->getPlayer();\n    HealthComponent* l_health = getEngine()->getEntities()->getHealths()->get(player);\n    if (l_health) {\n        drawProgressBar (m_sidebarXOffset+10, 2, l_health->health);\n\n    }\n\n    \/\/ Actions to take\n    drawString (getHeight()-8, m_sidebarXOffset+2, \"pickup Items\");\n    drawString (getHeight()-8, m_sidebarXOffset+2, \"p\", Color (GREEN));\n\n    drawString (getHeight()-7, m_sidebarXOffset+2, \"move (wasd)\");\n    drawString (getHeight()-7, m_sidebarXOffset+2, \"m\", Color (GREEN));\n    if (m_action == 'm') drawString (getHeight()-7, m_sidebarXOffset+1, \">\", Color (RED));\n\n    drawString (getHeight()-6, m_sidebarXOffset+2, \"attack (wasd)\");\n    drawString (getHeight()-6, m_sidebarXOffset+7, \"k\", Color (GREEN));\n    if (m_action == 'k') drawString (getHeight()-6, m_sidebarXOffset+1, \">\", Color (RED));\n\n    drawString (getHeight()-5, m_sidebarXOffset+2, \"inspect (wasd)\");\n    drawString (getHeight()-5, m_sidebarXOffset+2, \"i\", Color (GREEN));\n    if (m_action == 'i') drawString (getHeight()-5, m_sidebarXOffset+1, \">\", Color (RED));\n\n    drawString (getHeight()-4, m_sidebarXOffset+2, \"skip turn (.)\");\n    drawString (getHeight()-4, m_sidebarXOffset+13, \".\", Color (GREEN));\n\n    drawString (getHeight()-2, m_sidebarXOffset+2, \"View Equipment\");\n    drawString (getHeight()-2, m_sidebarXOffset+7, \"E\", Color (GREEN));\n}\n\nvoid MapWindow::drawProgressBar (int x, int y, int value)\n{\n    float l_value = (float) value;\n    Color l_color ((1.0f-(l_value\/10.0f)), l_value\/10.0f, 0);\n\n    for (int xx = 0; xx < value; xx++) {\n        drawTile (y, x+xx, 178, l_color, Color(BLACK));\n    }\n}\nDim all tiles not in the viscinity of the player#include \"window.h\"\n#include \"map_window.h\"\n#include \"inspection_window.h\"\n#include \"equipment_window.h\"\n#include \"gameengine.h\"\n#include \"event.h\"\n\n\nvoid MapWindow::gainFocus ()\n{\n    getEngine()->loadMap(50, 50);\n\n    setTitle (\"Map\");\n\n    m_mapXOffset = 1;\n    m_mapYOffset = 9;\n    m_mapStartX = 0;\n    m_mapStartY = 0;\n    m_mapWidth  = 0;\n    m_mapHeight = 0;\n    m_sidebarWidth = 20;\n    m_sidebarXOffset = getWidth() - m_sidebarWidth;\n\n    m_action = 'm';\n    m_lastDraw = clock();\n}\n\nvoid MapWindow::redraw() {\n\n    \/\/clock_t l_clock = clock() - m_lastDraw;\n    \/\/double l_diff = static_cast (l_clock\/CLOCKS_PER_SEC);\n    \/\/if (l_diff < 0.01f) return;\n\n    drawSeparators();\n    drawMap();\n    drawMessages();\n    drawSidebar();\n}\n\nvoid MapWindow::resize() {\n    setDimensions (0, 0, getEngine()->getGraphics()->getScreenWidth(), getEngine()->getGraphics()->getScreenHeight());\n    m_sidebarXOffset = getWidth() - m_sidebarWidth - 1;\n    m_mapWidth  = getWidth() - m_mapXOffset - m_sidebarWidth - 1;\n    m_mapHeight = getHeight() - m_mapYOffset - 1;\n}\n\nvoid MapWindow::keyDown (unsigned char key) {\n    Window::keyDown (key);\n\n    if (key == 'w' || key == 'a' || key == 's' || key == 'd') {\n        DIRECTION l_dir = Direction::None;\n        switch (key) {\n            case 'w': l_dir = Direction::North; break;\n            case 'a': l_dir = Direction::West;  break;\n            case 's': l_dir = Direction::South; break;\n            case 'd': l_dir = Direction::East;  break;\n        }\n\n        if (m_action == 'm') {\n            MoveEntityEvent* l_event = new MoveEntityEvent;\n            l_event->entity = getEngine()->getEntities()->getPlayer();\n            l_event->direction = l_dir;\n            getEngine()->raiseEvent (l_event);\n        }\n        if (m_action == 'k') {\n            AttackEntityEvent* l_event = new AttackEntityEvent;\n            l_event->entity = getEngine()->getEntities()->getPlayer();\n            l_event->direction = l_dir;\n            getEngine()->raiseEvent (l_event);\n        }\n        if (m_action == 'i') {\n            EntityHolder l_entities = getEngine()->getEntities()->findEntitiesToThe(l_dir, getEngine()->getEntities()->getPlayer());\n            if (l_entities.size() > 0) {\n                EntityId* l_target = new EntityId(*l_entities.begin());\n\n                InspectionWindow* l_win = new InspectionWindow();\n                l_win->initialise(getEngine(), l_target);\n                getEngine()->getWindows()->pushWindow (l_win);\n            }\n        }\n        if (m_action != 'i') getEngine()->swapTurn();\n        m_action = 'm';\n    }\n    if (key == 27) {\n        getEngine()->quit();\n    }\n    if (key == 'm' ||\n        key == 'k' ||\n        key == 'i') {\n        m_action = key;\n    }\n    if (key == '.') {\n        getEngine()->swapTurn();\n    }\n    if (key == 'p') {\n        Location l_playerLoc = getEngine()->getEntities()->getLocation(getEngine()->getEntities()->getPlayer());\n        EntityHolder l_entities = getEngine()->getEntities()->findEntitiesAt (l_playerLoc.x, l_playerLoc.y);\n        bool foundSomethingAlready = false;\n        for (EntityId l_entity : l_entities) {\n            DroppableComponent* droppable = getEngine()->getEntities()->getDroppables()->get(l_entity);\n            if (droppable) {\n                if (!foundSomethingAlready) {\n                    PickupEquipmentEvent* event = new PickupEquipmentEvent();\n                    event->entity = getEngine()->getEntities()->getPlayer();\n                    event->item = l_entity;\n                    getEngine()->raiseEvent (event);\n                    foundSomethingAlready = true;\n                } else {\n                    getEngine()->addMessage(INFO, \"There's something else here...\");\n                    break;\n                }\n            }\n        }\n        if (!foundSomethingAlready) {\n            getEngine()->addMessage(INFO, \"There's nothing here...\");\n        }\n    }\n    if (key == 'E') {\n        EquipmentWindow* l_win = new EquipmentWindow();\n        l_win->initialise(getEngine());\n        getEngine()->getWindows()->pushWindow (l_win);\n    }\n}\n\nvoid MapWindow::drawSeparators() {\n    getEngine()->getGraphics()->drawBorder (m_mapYOffset-1, m_mapXOffset-1, m_mapHeight, m_mapWidth);\n    getEngine()->getGraphics()->drawBorder (0, m_sidebarXOffset, getHeight()-2, m_sidebarWidth-1);\n}\n\nvoid MapWindow::drawMap() {\n    Location l_player = getEngine()->getEntities()->getLocation(getEngine()->getEntities()->getPlayer());\n    m_mapStartX = l_player.x - (m_mapWidth\/2);\n    m_mapStartY = l_player.y - (m_mapHeight\/2);\n\n    int xWidth = m_mapStartX + m_mapWidth;\n    int yWidth = m_mapStartY + m_mapHeight;\n\n    for (int yy = m_mapStartY; yy < yWidth; yy++) {\n        for (int xx = m_mapStartX; xx < xWidth; xx++) {\n            if (!getEngine()->isValidTile (xx, yy, getEngine()->getLevel())) continue;\n            Tile& l_tile = getEngine()->getTile (xx, yy, getEngine()->getLevel());\n            for (EntityId entity : l_tile.entities) {\n                SpriteComponent* l_sprite= getEngine()->getEntities()->getSprites()->get (entity);\n                if (!l_sprite) continue;\n                Color fgColor = l_sprite->fgColor;\n                if (    xx < (int)l_player.x - 3 || xx > (int)l_player.x + 3\n                    ||  yy < (int)l_player.y - 3 || yy > (int)l_player.y + 3) {\n                    fgColor.Red()   *= 0.4;\n                    fgColor.Green() *= 0.4;\n                    fgColor.Blue()  *= 0.4;\n                }\n                drawTile (  yy + m_mapYOffset - m_mapStartY,\n                            xx + m_mapXOffset - m_mapStartX,\n                            l_sprite->sprite,\n                            fgColor,\n                            l_sprite->bgColor);\n\n            }\n        }\n    }\n\n    return;\n}\n\nvoid MapWindow::drawMessages()\n{\n    std::vector& l_messages = getEngine()->getMessages();\n    size_t ii = l_messages.size();\n    size_t hh = m_mapYOffset-2;\n\n    for (; ii > 0 && hh > 0; hh--, ii--) {\n        Color fg;\n        switch (l_messages[ii-1].severity) {\n            case INFO: fg = Color (WHITE); break;\n            case WARN: fg = Color (RED); break;\n            case GOOD: fg = Color (GREEN); break;\n            case CRIT: fg = Color (BLUE); break;\n        }\n        drawString (hh, 1, l_messages[ii-1].message.c_str(), fg);\n    }\n}\n\nvoid MapWindow::drawSidebar ()\n{\n    \/\/ Current health\n    drawString (2, m_sidebarXOffset+2, \"Health:\");\n    EntityId player = getEngine()->getEntities()->getPlayer();\n    HealthComponent* l_health = getEngine()->getEntities()->getHealths()->get(player);\n    if (l_health) {\n        drawProgressBar (m_sidebarXOffset+10, 2, l_health->health);\n\n    }\n\n    \/\/ Actions to take\n    drawString (getHeight()-8, m_sidebarXOffset+2, \"pickup Items\");\n    drawString (getHeight()-8, m_sidebarXOffset+2, \"p\", Color (GREEN));\n\n    drawString (getHeight()-7, m_sidebarXOffset+2, \"move (wasd)\");\n    drawString (getHeight()-7, m_sidebarXOffset+2, \"m\", Color (GREEN));\n    if (m_action == 'm') drawString (getHeight()-7, m_sidebarXOffset+1, \">\", Color (RED));\n\n    drawString (getHeight()-6, m_sidebarXOffset+2, \"attack (wasd)\");\n    drawString (getHeight()-6, m_sidebarXOffset+7, \"k\", Color (GREEN));\n    if (m_action == 'k') drawString (getHeight()-6, m_sidebarXOffset+1, \">\", Color (RED));\n\n    drawString (getHeight()-5, m_sidebarXOffset+2, \"inspect (wasd)\");\n    drawString (getHeight()-5, m_sidebarXOffset+2, \"i\", Color (GREEN));\n    if (m_action == 'i') drawString (getHeight()-5, m_sidebarXOffset+1, \">\", Color (RED));\n\n    drawString (getHeight()-4, m_sidebarXOffset+2, \"skip turn (.)\");\n    drawString (getHeight()-4, m_sidebarXOffset+13, \".\", Color (GREEN));\n\n    drawString (getHeight()-2, m_sidebarXOffset+2, \"View Equipment\");\n    drawString (getHeight()-2, m_sidebarXOffset+7, \"E\", Color (GREEN));\n}\n\nvoid MapWindow::drawProgressBar (int x, int y, int value)\n{\n    float l_value = (float) value;\n    Color l_color ((1.0f-(l_value\/10.0f)), l_value\/10.0f, 0);\n\n    for (int xx = 0; xx < value; xx++) {\n        drawTile (y, x+xx, 178, l_color, Color(BLACK));\n    }\n}\n<|endoftext|>"}
{"text":"\/*\n * Copyright (C) 2010, Directed Edge, Inc. | Licensed under the MPL and LGPL\n *\/\n\n#include \"QActiveResource.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing namespace QActiveResource;\n\nstatic size_t writer(void *ptr, size_t size, size_t nmemb, void *stream)\n{\n    reinterpret_cast(stream)->append(QByteArray((const char *)(ptr), size * nmemb));\n    return size * nmemb;\n}\n\nnamespace HTTP\n{\n    QByteArray get(const QUrl &url, bool followRedirects = false)\n    {\n        QByteArray data;\n        CURL *curl = curl_easy_init();\n\n        static const int maxRetry = 1;\n        int retry = 0;\n\n        if(curl)\n        {\n            do\n            {\n                curl_easy_setopt(curl, CURLOPT_URL, url.toEncoded().data());\n                curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);\n                curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &data);\n                curl_easy_setopt(curl, CURLOPT_TIMEOUT, 25);\n                curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);\n\n                if(followRedirects)\n                {\n                    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);\n                    curl_easy_setopt(curl, CURLOPT_UNRESTRICTED_AUTH, 1);\n                    curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 2);\n                }\n            }\n            while(curl_easy_perform(curl) != 0 && ++retry <= maxRetry);\n            curl_easy_cleanup(curl);\n        }\n\n        return data;\n    }\n}\n\nstatic QVariant::Type lookupType(const QString &name)\n{\n    static QHash types;\n\n    if(types.isEmpty())\n    {\n        types[\"integer\"] = QVariant::Int;\n        types[\"decimal\"] = QVariant::Double;\n        types[\"datetime\"] = QVariant::DateTime;\n        types[\"boolean\"] = QVariant::Bool;\n    }\n\n    return types.contains(name) ? types[name] : QVariant::String;\n}\n\nstatic void assign(Record *record, QString name, const QVariant &value)\n{\n    (*record)[name.replace('-', '_')] = value;\n}\n\nstatic QDateTime toDateTime(const QString &s)\n{\n    QDateTime time = QDateTime::fromString(s.left(s.length() - 6), Qt::ISODate);\n\n    time.setTimeSpec(Qt::UTC);\n\n    int zoneHours = s.mid(s.length() - 6, 3).toInt();\n    int zoneMinutes = s.right(2).toInt();\n\n    return time.addSecs(-1 * (60 * zoneHours + zoneMinutes) * 60);\n}\n\nstatic QVariant reader(QXmlStreamReader &xml, bool advance = true)\n{\n    Record record;\n    QString firstElement;\n\n    while(!xml.atEnd())\n    {\n        if(advance)\n        {\n            xml.readNext();\n        }\n        if(xml.tokenType() == QXmlStreamReader::StartElement)\n        {\n            if(firstElement.isNull())\n            {\n                firstElement = xml.name().toString();\n            }\n\n            QString type = xml.attributes().value(\"type\").toString();\n\n            if(type == \"array\")\n            {\n                QString name = xml.name().toString();\n                QList array;\n\n                while(xml.readNext() == QXmlStreamReader::StartElement ||\n                      (xml.tokenType() == QXmlStreamReader::Characters && xml.isWhitespace()))\n                {\n                    if(!xml.isWhitespace())\n                    {\n                        array.append(reader(xml, false));\n                    }\n                }\n\n                assign(&record, name, array);\n            }\n            else if(xml.attributes().value(\"nil\") == \"true\")\n            {\n                assign(&record, xml.name().toString(), QVariant());\n            }\n            else if(advance && xml.name() != firstElement)\n            {\n                QVariant value;\n                QString text = xml.readElementText();\n\n                switch(lookupType(type))\n                {\n                case QVariant::Int:\n                    value = text.toInt();\n                    break;\n                case QVariant::Double:\n                    value = text.toDouble();\n                    break;\n                case QVariant::DateTime:\n                    value = toDateTime(text);\n                    break;\n                case QVariant::Bool:\n                    value = bool(text == \"true\");\n                    break;\n                default:\n                    value = text;\n                }\n\n                assign(&record, xml.name().toString(), value);\n            }\n        }\n        if(xml.tokenType() == QXmlStreamReader::EndElement &&\n           !firstElement.isNull() && firstElement == xml.name())\n        {\n            return record;\n        }\n\n        advance = true;\n    }\n\n    return QVariant();\n}\n\nstatic RecordList fetch(QUrl url, bool followRedirects = false)\n{\n    if(!url.path().endsWith(\".xml\"))\n    {\n        url.setPath(url.path() + \".xml\");\n    }\n\n    QByteArray data = HTTP::get(url, followRedirects);\n\n    QXmlStreamReader xml(data);\n\n    QVariant value = reader(xml);\n    RecordList records;\n\n    if(value.type() == QVariant::List)\n    {\n        foreach(QVariant v, value.toList())\n        {\n            records.append(v.toHash());\n        }\n    }\n    else if(value.type() == QVariant::Hash && value.toHash().size() == 1)\n    {\n        foreach(QVariant v, value.toHash().begin()->toList())\n        {\n            records.append(v.toHash());\n        }\n    }\n    else\n    {\n        records.append(value.toHash());\n    }\n\n    return records;\n}\n\n\/*\n * Param::Data\n *\/\n\nParam::Data::Data(const QString &k, const QString &v) :\n    key(k),\n    value(v)\n{\n\n}\n\n\/*\n * Param\n *\/\n\nParam::Param() :\n    d(0)\n{\n\n}\n\nParam::Param(const QString &key, const QString &value) :\n    d(new Data(key, value))\n{\n\n}\n\nbool Param::isNull() const\n{\n    return d == 0;\n}\n\nQString Param::key() const\n{\n    return isNull() ? QString() : d->key;\n}\n\nQString Param::value() const\n{\n    return isNull() ? QString() : d->value;\n}\n\n\/*\n * Resource::Data\n *\/\n\nResource::Data::Data(const QUrl &b, const QString &r) :\n    base(b),\n    resource(r),\n    url(base),\n    followRedirects(false)\n{\n    setUrl();\n}\n\nvoid Resource::Data::setUrl()\n{\n    url = base;\n    url.setPath(base.path() + \"\/\" + resource);\n}\n\n\/*\n * Resource\n *\/\n\nResource::Resource(const QUrl &base, const QString &resource) :\n    d(new Data(base, resource))\n{\n\n}\n\nvoid Resource::setBase(const QUrl &base)\n{\n    d->base = base;\n    d->setUrl();\n}\n\nvoid Resource::setResource(const QString &resource)\n{\n    d->resource = resource;\n    d->setUrl();\n}\n\nRecord Resource::find(const QVariant &id) const\n{\n    return find(FindOne, id.toString());\n}\n\nRecordList Resource::find(FindMulti style, const QString &from, const ParamList ¶ms) const\n{\n    Q_UNUSED(style);\n\n    QUrl url = d->url;\n\n    foreach(Param param, params)\n    {\n        if(!param.isNull())\n        {\n            url.addQueryItem(param.key(), param.value());\n        }\n    }\n\n    if(!from.isEmpty())\n    {\n        url.setPath(url.path() + \"\/\" + from);\n    }\n\n    return fetch(url, d->followRedirects);\n}\n\nRecord Resource::find(FindSingle style, const QString &from, const ParamList ¶ms) const\n{\n    QUrl url = d->url;\n\n    foreach(Param param, params)\n    {\n        if(!param.isNull())\n        {\n            url.addQueryItem(param.key(), param.value());\n        }\n    }\n\n    if(!from.isEmpty())\n    {\n        url.setPath(url.path() + \"\/\" + from);\n    }\n\n    switch(style)\n    {\n    case FindOne:\n    case FindFirst:\n    {\n        RecordList results = find(FindAll, from, params);\n        return results.isEmpty() ? Record() : results.front();\n    }\n    case FindLast:\n    {\n        RecordList results = find(FindAll, from, params);\n        return results.isEmpty() ? Record() : results.back();\n    }\n    }\n\n    return Record();\n}\n\nRecord Resource::find(FindSingle style, const QString &from,\n                      const Param &first, const Param &second,\n                      const Param &third, const Param &fourth) const\n{\n    return find(style, from, ParamList() << first << second << third << fourth);\n}\n\nRecordList Resource::find(FindMulti style, const QString &from,\n                          const Param &first, const Param &second,\n                          const Param &third, const Param &fourth) const\n{\n    return find(style, from, ParamList() << first << second << third << fourth);\n}\n\nvoid Resource::setFollowRedirects(bool followRedirects)\n{\n    d->followRedirects = followRedirects;\n}\nOnly convert to a hash if there's a value (now returns an empty array for empty result sets)\/*\n * Copyright (C) 2010, Directed Edge, Inc. | Licensed under the MPL and LGPL\n *\/\n\n#include \"QActiveResource.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing namespace QActiveResource;\n\nstatic size_t writer(void *ptr, size_t size, size_t nmemb, void *stream)\n{\n    reinterpret_cast(stream)->append(QByteArray((const char *)(ptr), size * nmemb));\n    return size * nmemb;\n}\n\nnamespace HTTP\n{\n    QByteArray get(const QUrl &url, bool followRedirects = false)\n    {\n        QByteArray data;\n        CURL *curl = curl_easy_init();\n\n        static const int maxRetry = 1;\n        int retry = 0;\n\n        if(curl)\n        {\n            do\n            {\n                curl_easy_setopt(curl, CURLOPT_URL, url.toEncoded().data());\n                curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);\n                curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &data);\n                curl_easy_setopt(curl, CURLOPT_TIMEOUT, 25);\n                curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);\n\n                if(followRedirects)\n                {\n                    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);\n                    curl_easy_setopt(curl, CURLOPT_UNRESTRICTED_AUTH, 1);\n                    curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 2);\n                }\n            }\n            while(curl_easy_perform(curl) != 0 && ++retry <= maxRetry);\n            curl_easy_cleanup(curl);\n        }\n\n        return data;\n    }\n}\n\nstatic QVariant::Type lookupType(const QString &name)\n{\n    static QHash types;\n\n    if(types.isEmpty())\n    {\n        types[\"integer\"] = QVariant::Int;\n        types[\"decimal\"] = QVariant::Double;\n        types[\"datetime\"] = QVariant::DateTime;\n        types[\"boolean\"] = QVariant::Bool;\n    }\n\n    return types.contains(name) ? types[name] : QVariant::String;\n}\n\nstatic void assign(Record *record, QString name, const QVariant &value)\n{\n    (*record)[name.replace('-', '_')] = value;\n}\n\nstatic QDateTime toDateTime(const QString &s)\n{\n    QDateTime time = QDateTime::fromString(s.left(s.length() - 6), Qt::ISODate);\n\n    time.setTimeSpec(Qt::UTC);\n\n    int zoneHours = s.mid(s.length() - 6, 3).toInt();\n    int zoneMinutes = s.right(2).toInt();\n\n    return time.addSecs(-1 * (60 * zoneHours + zoneMinutes) * 60);\n}\n\nstatic QVariant reader(QXmlStreamReader &xml, bool advance = true)\n{\n    Record record;\n    QString firstElement;\n\n    while(!xml.atEnd())\n    {\n        if(advance)\n        {\n            xml.readNext();\n        }\n        if(xml.tokenType() == QXmlStreamReader::StartElement)\n        {\n            if(firstElement.isNull())\n            {\n                firstElement = xml.name().toString();\n            }\n\n            QString type = xml.attributes().value(\"type\").toString();\n\n            if(type == \"array\")\n            {\n                QString name = xml.name().toString();\n                QList array;\n\n                while(xml.readNext() == QXmlStreamReader::StartElement ||\n                      (xml.tokenType() == QXmlStreamReader::Characters && xml.isWhitespace()))\n                {\n                    if(!xml.isWhitespace())\n                    {\n                        array.append(reader(xml, false));\n                    }\n                }\n\n                assign(&record, name, array);\n            }\n            else if(xml.attributes().value(\"nil\") == \"true\")\n            {\n                assign(&record, xml.name().toString(), QVariant());\n            }\n            else if(advance && xml.name() != firstElement)\n            {\n                QVariant value;\n                QString text = xml.readElementText();\n\n                switch(lookupType(type))\n                {\n                case QVariant::Int:\n                    value = text.toInt();\n                    break;\n                case QVariant::Double:\n                    value = text.toDouble();\n                    break;\n                case QVariant::DateTime:\n                    value = toDateTime(text);\n                    break;\n                case QVariant::Bool:\n                    value = bool(text == \"true\");\n                    break;\n                default:\n                    value = text;\n                }\n\n                assign(&record, xml.name().toString(), value);\n            }\n        }\n        if(xml.tokenType() == QXmlStreamReader::EndElement &&\n           !firstElement.isNull() && firstElement == xml.name())\n        {\n            return record;\n        }\n\n        advance = true;\n    }\n\n    return QVariant();\n}\n\nstatic RecordList fetch(QUrl url, bool followRedirects = false)\n{\n    if(!url.path().endsWith(\".xml\"))\n    {\n        url.setPath(url.path() + \".xml\");\n    }\n\n    QByteArray data = HTTP::get(url, followRedirects);\n\n    QXmlStreamReader xml(data);\n\n    QVariant value = reader(xml);\n    RecordList records;\n\n    if(value.type() == QVariant::List)\n    {\n        foreach(QVariant v, value.toList())\n        {\n            records.append(v.toHash());\n        }\n    }\n    else if(value.type() == QVariant::Hash && value.toHash().size() == 1)\n    {\n        foreach(QVariant v, value.toHash().begin()->toList())\n        {\n            records.append(v.toHash());\n        }\n    }\n    else if(value.isValid())\n    {\n        records.append(value.toHash());\n    }\n\n    return records;\n}\n\n\/*\n * Param::Data\n *\/\n\nParam::Data::Data(const QString &k, const QString &v) :\n    key(k),\n    value(v)\n{\n\n}\n\n\/*\n * Param\n *\/\n\nParam::Param() :\n    d(0)\n{\n\n}\n\nParam::Param(const QString &key, const QString &value) :\n    d(new Data(key, value))\n{\n\n}\n\nbool Param::isNull() const\n{\n    return d == 0;\n}\n\nQString Param::key() const\n{\n    return isNull() ? QString() : d->key;\n}\n\nQString Param::value() const\n{\n    return isNull() ? QString() : d->value;\n}\n\n\/*\n * Resource::Data\n *\/\n\nResource::Data::Data(const QUrl &b, const QString &r) :\n    base(b),\n    resource(r),\n    url(base),\n    followRedirects(false)\n{\n    setUrl();\n}\n\nvoid Resource::Data::setUrl()\n{\n    url = base;\n    url.setPath(base.path() + \"\/\" + resource);\n}\n\n\/*\n * Resource\n *\/\n\nResource::Resource(const QUrl &base, const QString &resource) :\n    d(new Data(base, resource))\n{\n\n}\n\nvoid Resource::setBase(const QUrl &base)\n{\n    d->base = base;\n    d->setUrl();\n}\n\nvoid Resource::setResource(const QString &resource)\n{\n    d->resource = resource;\n    d->setUrl();\n}\n\nRecord Resource::find(const QVariant &id) const\n{\n    return find(FindOne, id.toString());\n}\n\nRecordList Resource::find(FindMulti style, const QString &from, const ParamList ¶ms) const\n{\n    Q_UNUSED(style);\n\n    QUrl url = d->url;\n\n    foreach(Param param, params)\n    {\n        if(!param.isNull())\n        {\n            url.addQueryItem(param.key(), param.value());\n        }\n    }\n\n    if(!from.isEmpty())\n    {\n        url.setPath(url.path() + \"\/\" + from);\n    }\n\n    return fetch(url, d->followRedirects);\n}\n\nRecord Resource::find(FindSingle style, const QString &from, const ParamList ¶ms) const\n{\n    QUrl url = d->url;\n\n    foreach(Param param, params)\n    {\n        if(!param.isNull())\n        {\n            url.addQueryItem(param.key(), param.value());\n        }\n    }\n\n    if(!from.isEmpty())\n    {\n        url.setPath(url.path() + \"\/\" + from);\n    }\n\n    switch(style)\n    {\n    case FindOne:\n    case FindFirst:\n    {\n        RecordList results = find(FindAll, from, params);\n        return results.isEmpty() ? Record() : results.front();\n    }\n    case FindLast:\n    {\n        RecordList results = find(FindAll, from, params);\n        return results.isEmpty() ? Record() : results.back();\n    }\n    }\n\n    return Record();\n}\n\nRecord Resource::find(FindSingle style, const QString &from,\n                      const Param &first, const Param &second,\n                      const Param &third, const Param &fourth) const\n{\n    return find(style, from, ParamList() << first << second << third << fourth);\n}\n\nRecordList Resource::find(FindMulti style, const QString &from,\n                          const Param &first, const Param &second,\n                          const Param &third, const Param &fourth) const\n{\n    return find(style, from, ParamList() << first << second << third << fourth);\n}\n\nvoid Resource::setFollowRedirects(bool followRedirects)\n{\n    d->followRedirects = followRedirects;\n}\n<|endoftext|>"}
{"text":"\/*\n    msnauthsocket.cpp - Socket that does the initial handshake as used by\n                         both MSNAuthSocket and MSNNotifySocket\n\n    Copyright (c) 2002 by Martijn Klingens       \n    Kopete    (c) 2002 by the Kopete developers  \n\n    Portions of this code are taken from KMerlin,\n              (c) 2001 by Olaf Lueg              \n\n    *************************************************************************\n    *                                                                       *\n    * This program is free software; you can redistribute it and\/or modify  *\n    * it under the terms of the GNU General Public License as published by  *\n    * the Free Software Foundation; either version 2 of the License, or     *\n    * (at your option) any later version.                                   *\n    *                                                                       *\n    *************************************************************************\n*\/\n\n#include \"msnauthsocket.h\"\n\n#include \n\n#include \n#include \n#include \n\nMSNAuthSocket::MSNAuthSocket( const QString &msnId )\n{\n\tm_msnId = msnId;\n\tm_msgBoxShown = false;\n}\n\nMSNAuthSocket::~MSNAuthSocket()\n{\n}\n\nvoid MSNAuthSocket::reconnect()\n{\n\tconnect( server(),port() );\n}\n\nvoid MSNAuthSocket::handleError( uint code, uint id )\n{\n\tif( code != 600 )\n\t{\n\t\tMSNSocket::handleError( code, id );\n\t\treturn;\n\t}\n\n\tdisconnect();\n\tQTimer::singleShot( 10, this, SLOT( reconnect() ) );\n\n\tif( !m_msgBoxShown )\n\t{\n\t\tQString msg =\n\t\t\ti18n( \"The MSN server is busy.\\n\"\n\t\t\t\t\"Trying to reconnect every 10 seconds. Please be patient...\" );\n\t\tm_msgBoxShown = true;\n\n\t\tKMessageBox::information( 0, msg, i18n( \"MSN Plugin - Kopete\" ) );\n\t}\n}\n\nvoid MSNAuthSocket::parseCommand( const QString &cmd, uint id,\n\tconst QString &data )\n{\n\tif( cmd == \"VER\" )\n\t{\n\t\tkdDebug() << \"MSNAuthSocket: Requesting authentication method\"\n\t\t\t<< endl;\n\t\tsendCommand( \"INF\" );\n\t}\n\telse if( cmd == \"INF\" )\n\t{\n\t\tkdDebug() << \"MSNAuthSocket: Requesting MD5 authentication \"\n\t\t\t<< \"for Passport \" << m_msnId << endl;\n\t\tsendCommand( \"USR\", \"MD5 I \" + m_msnId);\n\t}\n\telse\n\t{\n\t\tkdDebug() << \"MSNAuthSocket::parseCommand: Unexpected response '\"\n\t\t\t<< cmd << \" \" << id << \" \" << data << \"' from server!\" << endl;\n\t}\n}\n\nvoid MSNAuthSocket::doneConnect()\n{\n\tkdDebug() << \"MSNAuthSocket: Negotiating server protocol version\"\n\t\t<< endl;\n\tsendCommand( \"VER\", \"MSNP7 MSNP6 MSNP5 MSNP4 CVR0\" );\n}\n\n#include \"msnauthsocket.moc\"\n\n\n\n\/*\n * Local variables:\n * c-indentation-style: k&r\n * c-basic-offset: 8\n * indent-tabs-mode: t\n * End:\n *\/\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\nchange text in debug output: 'unexepted' => 'unimplemented' to prevent confision\/*\n    msnauthsocket.cpp - Socket that does the initial handshake as used by\n                         both MSNAuthSocket and MSNNotifySocket\n\n    Copyright (c) 2002 by Martijn Klingens       \n    Kopete    (c) 2002 by the Kopete developers  \n\n    Portions of this code are taken from KMerlin,\n              (c) 2001 by Olaf Lueg              \n\n    *************************************************************************\n    *                                                                       *\n    * This program is free software; you can redistribute it and\/or modify  *\n    * it under the terms of the GNU General Public License as published by  *\n    * the Free Software Foundation; either version 2 of the License, or     *\n    * (at your option) any later version.                                   *\n    *                                                                       *\n    *************************************************************************\n*\/\n\n#include \"msnauthsocket.h\"\n\n#include \n\n#include \n#include \n#include \n\nMSNAuthSocket::MSNAuthSocket( const QString &msnId )\n{\n\tm_msnId = msnId;\n\tm_msgBoxShown = false;\n}\n\nMSNAuthSocket::~MSNAuthSocket()\n{\n}\n\nvoid MSNAuthSocket::reconnect()\n{\n\tconnect( server(),port() );\n}\n\nvoid MSNAuthSocket::handleError( uint code, uint id )\n{\n\tif( code != 600 )\n\t{\n\t\tMSNSocket::handleError( code, id );\n\t\treturn;\n\t}\n\n\tdisconnect();\n\tQTimer::singleShot( 10, this, SLOT( reconnect() ) );\n\n\tif( !m_msgBoxShown )\n\t{\n\t\tQString msg =\n\t\t\ti18n( \"The MSN server is busy.\\n\"\n\t\t\t\t\"Trying to reconnect every 10 seconds. Please be patient...\" );\n\t\tm_msgBoxShown = true;\n\n\t\tKMessageBox::information( 0, msg, i18n( \"MSN Plugin - Kopete\" ) );\n\t}\n}\n\nvoid MSNAuthSocket::parseCommand( const QString &cmd, uint id,\n\tconst QString &data )\n{\n\tif( cmd == \"VER\" )\n\t{\n\t\tkdDebug() << \"MSNAuthSocket: Requesting authentication method\"\n\t\t\t<< endl;\n\t\tsendCommand( \"INF\" );\n\t}\n\telse if( cmd == \"INF\" )\n\t{\n\t\tkdDebug() << \"MSNAuthSocket: Requesting MD5 authentication \"\n\t\t\t<< \"for Passport \" << m_msnId << endl;\n\t\tsendCommand( \"USR\", \"MD5 I \" + m_msnId);\n\t}\n\telse\n\t{\n\t\tkdDebug() << \"MSNAuthSocket::parseCommand: Unimplemented command '\"\n\t\t\t<< cmd << \" \" << id << \" \" << data << \"' from server!\" << endl;\n\t}\n}\n\nvoid MSNAuthSocket::doneConnect()\n{\n\tkdDebug() << \"MSNAuthSocket: Negotiating server protocol version\"\n\t\t<< endl;\n\tsendCommand( \"VER\", \"MSNP7 MSNP6 MSNP5 MSNP4 CVR0\" );\n}\n\n#include \"msnauthsocket.moc\"\n\n\n\n\/*\n * Local variables:\n * c-indentation-style: k&r\n * c-basic-offset: 8\n * indent-tabs-mode: t\n * End:\n *\/\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\n<|endoftext|>"}
{"text":"\/\/ Copyright 2015 Markus Ilmola\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\n#include \"generator\/DodecahedronMesh.hpp\"\n#include \"generator\/Iterator.hpp\"\n\n#include \n#include \n\nusing namespace generator;\n\n\nstatic const double a = (1.0 + std::sqrt(5.0)) \/ 2.0;\n\nstatic const std::array vertices {{\n\t{ 1.0,  1.0, -1.0},\n\t{-1.0,  1.0, -1.0},\n\t{ 1.0, -1.0, -1.0},\n\t{-1.0, -1.0, -1.0},\n\t{ 1.0,  1.0,  1.0},\n\t{-1.0,  1.0,  1.0},\n\t{ 1.0, -1.0,  1.0},\n\t{-1.0, -1.0,  1.0},\n\n\t{0.0,  1.0\/a, -a},\n\t{0.0, -1.0\/a, -a},\n\t{0.0,  1.0\/a,  a},\n\t{0.0, -1.0\/a,  a},\n\n\t{ 1.0\/a,  a, 0.0},\n\t{-1.0\/a,  a, 0.0},\n\t{ 1.0\/a, -a, 0.0},\n\t{-1.0\/a, -a, 0.0},\n\n\t{ a, 0.0, -1.0\/a},\n\t{-a, 0.0, -1.0\/a},\n\t{ a, 0.0,  1.0\/a},\n\t{-a, 0.0,  1.0\/a}\n}};\n\n\nstatic const std::array, 12> polygons{{\n\t{{ 0u, 12u,  4u, 18u, 16u}}, \/\/ 0\n\t{{18u,  6u, 14u,  2u, 16u}}, \/\/ 1\n\t{{ 4u, 10u, 11u,  6u, 18u}}, \/\/ 2\n\t{{11u,  7u, 15u, 14u,  6u}}, \/\/ 3\n\t{{ 7u, 11u, 10u,  5u, 19u}}, \/\/ 4\n\t{{17u,  3u, 15u,  7u, 19u}}, \/\/ 5\n\t{{ 9u,  2u, 14u, 15u,  3u}}, \/\/ 6\n\t{{ 1u,  8u,  9u,  3u, 17u}}, \/\/ 7\n\t{{10u,  4u, 12u, 13u,  5u}}, \/\/ 8\n\t{{ 5u, 13u,  1u, 17u, 19u}}, \/\/ 9\n\t{{ 0u,  8u,  1u, 13u, 12u}}, \/\/ 10\n\t{{ 0u, 16u,  2u,  9u,  8u}}  \/\/ 11\n}};\n\n\nstatic std::vector makeVertices(int faceIndex) noexcept {\n\tstd::vector result(5);\n\tfor (int i = 0; i < 5; ++i) {\n\t\tresult.at(i) = gml::normalize(vertices.at(polygons.at(faceIndex)[i]));\n\t}\n\treturn result;\n}\n\n\nDodecahedronMesh::Triangles::Triangles(const DodecahedronMesh& mesh) noexcept :\n\tmMesh{&mesh},\n\tmFaceIndex{0},\n\tmFaceMesh{std::make_shared(makeVertices(0), mMesh->mSegments, mMesh->mRings)},\n\tmTriangles{mFaceMesh->triangles()}\n{ }\n\n\n\nbool DodecahedronMesh::Triangles::done() const noexcept {\n\treturn mFaceIndex == ::polygons.size();\n}\n\n\nTriangle DodecahedronMesh::Triangles::generate() const {\n\tif (done()) throw std::out_of_range(\"Done!\");\n\n\tTriangle triangle = mTriangles.generate();\n\n\tconst int base = mFaceIndex * mMesh->mFaceVertexCount;\n\n\ttriangle.vertices[0] += base;\n\ttriangle.vertices[1] += base;\n\ttriangle.vertices[2] += base;\n\n\treturn triangle;\n}\n\n\nvoid DodecahedronMesh::Triangles::next() {\n\tif (done()) throw std::out_of_range(\"Done!\");\n\n\tmTriangles.next();\n\n\tif (mTriangles.done()) {\n\t\t++mFaceIndex;\n\n\t\tif (!done()) {\n\t\t\tmFaceMesh = std::make_shared(\n\t\t\t\tmakeVertices(mFaceIndex),\n\t\t\t\tmMesh->mSegments\n\t\t\t);\n\n\t\t\tmTriangles = mFaceMesh->triangles();\n\t\t}\n\t}\n}\n\n\n\nDodecahedronMesh::Vertices::Vertices(const DodecahedronMesh& mesh) noexcept :\n\tmMesh{&mesh},\n\tmFaceIndex{0},\n\tmFaceMesh{std::make_shared(\n\t\tmakeVertices(0),\n\t\tmMesh->mSegments,\n\t\tmMesh->mRings\n\t)},\n\tmVertices{mFaceMesh->vertices()}\n{\n\n}\n\n\nbool DodecahedronMesh::Vertices::done() const noexcept {\n\treturn mFaceIndex == ::polygons.size();\n}\n\n\nMeshVertex DodecahedronMesh::Vertices::generate() const {\n\n\tMeshVertex vertex = mVertices.generate();\n\n\tvertex.position *= mMesh->mRadius;\n\n\treturn vertex;\n}\n\n\nvoid DodecahedronMesh::Vertices::next() {\n\tmVertices.next();\n\n\tif (mVertices.done()) {\n\t\t++mFaceIndex;\n\n\t\tif (!done()) {\n\t\t\tmFaceMesh = std::make_shared(\n\t\t\t\tmakeVertices(mFaceIndex),\n\t\t\t\tmMesh->mSegments,\n\t\t\t\tmMesh->mRings\n\t\t\t);\n\n\t\t\tmVertices = mFaceMesh->vertices();\n\t\t}\n\t}\n}\n\n\n\nDodecahedronMesh::DodecahedronMesh(double radius, int segments, int rings) noexcept :\n\tmRadius{radius},\n\tmSegments{segments},\n\tmRings{rings},\n\tmFaceVertexCount{count(ConvexPolygonMesh{1.0, 5u, segments, rings}.vertices())}\n{\n\n}\n\n\nDodecahedronMesh::Triangles DodecahedronMesh::triangles() const noexcept {\n\treturn Triangles{*this};\n}\n\n\nDodecahedronMesh::Vertices DodecahedronMesh::vertices() const noexcept {\n\treturn Vertices{*this};\n}\n\n\n\nRemove unneeded u suffix.\/\/ Copyright 2015 Markus Ilmola\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\n#include \"generator\/DodecahedronMesh.hpp\"\n#include \"generator\/Iterator.hpp\"\n\n#include \n#include \n\nusing namespace generator;\n\n\nstatic const double a = (1.0 + std::sqrt(5.0)) \/ 2.0;\n\nstatic const std::array vertices {{\n\t{ 1.0,  1.0, -1.0},\n\t{-1.0,  1.0, -1.0},\n\t{ 1.0, -1.0, -1.0},\n\t{-1.0, -1.0, -1.0},\n\t{ 1.0,  1.0,  1.0},\n\t{-1.0,  1.0,  1.0},\n\t{ 1.0, -1.0,  1.0},\n\t{-1.0, -1.0,  1.0},\n\n\t{0.0,  1.0\/a, -a},\n\t{0.0, -1.0\/a, -a},\n\t{0.0,  1.0\/a,  a},\n\t{0.0, -1.0\/a,  a},\n\n\t{ 1.0\/a,  a, 0.0},\n\t{-1.0\/a,  a, 0.0},\n\t{ 1.0\/a, -a, 0.0},\n\t{-1.0\/a, -a, 0.0},\n\n\t{ a, 0.0, -1.0\/a},\n\t{-a, 0.0, -1.0\/a},\n\t{ a, 0.0,  1.0\/a},\n\t{-a, 0.0,  1.0\/a}\n}};\n\n\nstatic const std::array, 12> polygons{{\n\t{{ 0, 12,  4, 18, 16}}, \/\/ 0\n\t{{18,  6, 14,  2, 16}}, \/\/ 1\n\t{{ 4, 10, 11,  6, 18}}, \/\/ 2\n\t{{11,  7, 15, 14,  6}}, \/\/ 3\n\t{{ 7, 11, 10,  5, 19}}, \/\/ 4\n\t{{17,  3, 15,  7, 19}}, \/\/ 5\n\t{{ 9,  2, 14, 15,  3}}, \/\/ 6\n\t{{ 1,  8,  9,  3, 17}}, \/\/ 7\n\t{{10,  4, 12, 13,  5}}, \/\/ 8\n\t{{ 5, 13,  1, 17, 19}}, \/\/ 9\n\t{{ 0,  8,  1, 13, 12}}, \/\/ 10\n\t{{ 0, 16,  2,  9,  8}}  \/\/ 11\n}};\n\n\nstatic std::vector makeVertices(int faceIndex) noexcept {\n\tstd::vector result(5);\n\tfor (int i = 0; i < 5; ++i) {\n\t\tresult.at(i) = gml::normalize(vertices.at(polygons.at(faceIndex)[i]));\n\t}\n\treturn result;\n}\n\n\nDodecahedronMesh::Triangles::Triangles(const DodecahedronMesh& mesh) noexcept :\n\tmMesh{&mesh},\n\tmFaceIndex{0},\n\tmFaceMesh{std::make_shared(makeVertices(0), mMesh->mSegments, mMesh->mRings)},\n\tmTriangles{mFaceMesh->triangles()}\n{ }\n\n\n\nbool DodecahedronMesh::Triangles::done() const noexcept {\n\treturn mFaceIndex == ::polygons.size();\n}\n\n\nTriangle DodecahedronMesh::Triangles::generate() const {\n\tif (done()) throw std::out_of_range(\"Done!\");\n\n\tTriangle triangle = mTriangles.generate();\n\n\tconst int base = mFaceIndex * mMesh->mFaceVertexCount;\n\n\ttriangle.vertices[0] += base;\n\ttriangle.vertices[1] += base;\n\ttriangle.vertices[2] += base;\n\n\treturn triangle;\n}\n\n\nvoid DodecahedronMesh::Triangles::next() {\n\tif (done()) throw std::out_of_range(\"Done!\");\n\n\tmTriangles.next();\n\n\tif (mTriangles.done()) {\n\t\t++mFaceIndex;\n\n\t\tif (!done()) {\n\t\t\tmFaceMesh = std::make_shared(\n\t\t\t\tmakeVertices(mFaceIndex),\n\t\t\t\tmMesh->mSegments\n\t\t\t);\n\n\t\t\tmTriangles = mFaceMesh->triangles();\n\t\t}\n\t}\n}\n\n\n\nDodecahedronMesh::Vertices::Vertices(const DodecahedronMesh& mesh) noexcept :\n\tmMesh{&mesh},\n\tmFaceIndex{0},\n\tmFaceMesh{std::make_shared(\n\t\tmakeVertices(0),\n\t\tmMesh->mSegments,\n\t\tmMesh->mRings\n\t)},\n\tmVertices{mFaceMesh->vertices()}\n{\n\n}\n\n\nbool DodecahedronMesh::Vertices::done() const noexcept {\n\treturn mFaceIndex == ::polygons.size();\n}\n\n\nMeshVertex DodecahedronMesh::Vertices::generate() const {\n\n\tMeshVertex vertex = mVertices.generate();\n\n\tvertex.position *= mMesh->mRadius;\n\n\treturn vertex;\n}\n\n\nvoid DodecahedronMesh::Vertices::next() {\n\tmVertices.next();\n\n\tif (mVertices.done()) {\n\t\t++mFaceIndex;\n\n\t\tif (!done()) {\n\t\t\tmFaceMesh = std::make_shared(\n\t\t\t\tmakeVertices(mFaceIndex),\n\t\t\t\tmMesh->mSegments,\n\t\t\t\tmMesh->mRings\n\t\t\t);\n\n\t\t\tmVertices = mFaceMesh->vertices();\n\t\t}\n\t}\n}\n\n\n\nDodecahedronMesh::DodecahedronMesh(double radius, int segments, int rings) noexcept :\n\tmRadius{radius},\n\tmSegments{segments},\n\tmRings{rings},\n\tmFaceVertexCount{count(ConvexPolygonMesh{1.0, 5u, segments, rings}.vertices())}\n{\n\n}\n\n\nDodecahedronMesh::Triangles DodecahedronMesh::triangles() const noexcept {\n\treturn Triangles{*this};\n}\n\n\nDodecahedronMesh::Vertices DodecahedronMesh::vertices() const noexcept {\n\treturn Vertices{*this};\n}\n\n\n\n<|endoftext|>"}
{"text":"\/*\n    yahoostatus.cpp - Yahoo Plugin for Kopete\n\n    Copyright (c) 2002 by Duncan Mac-Vicar Prett \n\n    Copyright (c) 2002 by the Kopete developers  \n\n    *************************************************************************\n    *                                                                       *\n    * This program is free software; you can redistribute it and\/or modify  *\n    * it under the terms of the GNU General Public License as published by  *\n    * the Free Software Foundation; either version 2 of the License, or     *\n    * (at your option) any later version.                                   *\n    *                                                                       *\n    *************************************************************************\n*\/\n\n#include \n#include \n#include \"yahoostatus.h\"\n#include \"yahooprotocol.h\"\n#include \"kopeteonlinestatus.h\"\n\nYahooStatus::YahooStatus( Status status_ )\n{\n\tm_status = status_;\n}\n\nYahooStatus::YahooStatus()\n{\n\tm_status = Offline;\n}\n\nKopeteOnlineStatus YahooStatus::translate() const\n{\n\tif(m_status == Available)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Online,  25, YahooProtocol::protocol(), m_status, \"yahoo_protocol\",  i18n(YSTAvailable), i18n(YSTAvailable));\n\telse if(m_status == Mobile)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,     5, YahooProtocol::protocol(), m_status, \"yahoo_mobile\",  i18n(\"On the mobile\"), i18n(\"On the mobile\"));\n\telse if(m_status == Invisible)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Offline, 0, YahooProtocol::protocol(), m_status, QString::null, i18n(YSTInvisible), i18n(YSTInvisible));\n\telse if(m_status == Idle)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    15, YahooProtocol::protocol(), m_status, \"yahoo_idle\",    i18n(\"Idle\"), i18n(\"Idle\"));\n\telse if(m_status == Custom)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    20, YahooProtocol::protocol(), m_status, \"yahoo_away\",    m_statusText, m_statusText);\n\telse if(m_status == CustomBusy)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    20, YahooProtocol::protocol(), m_status, \"yahoo_busy\",    m_statusText, m_statusText);\n\telse if(m_status == CustomMobile)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    20, YahooProtocol::protocol(), m_status, \"yahoo_mobile\",  m_statusText, m_statusText);\n\telse if(m_status == BeRightBack)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, \"yahoo_away\",    i18n(YSTBeRightBack), i18n(YSTBeRightBack));\n\telse if(m_status == Busy)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, \"yahoo_busy\",    i18n(YSTBusy), i18n(YSTBusy));\n\telse if(m_status == NotAtHome)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, \"yahoo_away\",    i18n(YSTNotAtHome), i18n(YSTNotAtHome));\n\telse if(m_status == NotAtMyDesk)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, \"yahoo_away\",    i18n(YSTNotAtMyDesk), i18n(YSTNotAtMyDesk));\n\telse if(m_status == NotInTheOffice)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, \"yahoo_away\",    i18n(YSTNotInTheOffice), i18n(YSTNotInTheOffice));\n\telse if(m_status == OnThePhone)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, \"yahoo_mobile\",  i18n(YSTOnThePhone), i18n(YSTOnThePhone));\n\telse if(m_status == OnVacation)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, \"yahoo_away\",    i18n(YSTOnVacation), i18n(YSTOnVacation));\n\telse if(m_status == OutToLunch)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, \"yahoo_tea\",    i18n(YSTOutToLunch), i18n(YSTOutToLunch));\n\telse if(m_status == SteppedOut)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, \"yahoo_away\",    i18n(YSTSteppedOut), i18n(YSTSteppedOut));\n\telse\t\/\/ must be offline\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Offline,  0, YahooProtocol::protocol(), m_status, QString::null, i18n(YSTOffline), i18n(YSTOffline));\n}\n\nvoid YahooStatus::setStatus( Status status_, const QString &statusText_ )\n{\n\tm_status = status_;\n\tm_statusText = statusText_;\n}\n\nYahooStatus::Status YahooStatus::fromLibYahoo2( int status_ )\n{\n\tswitch (status_)\n\t{\n\t\tcase YAHOO_STATUS_AVAILABLE :\n\t\t\treturn Available;\n\t\tcase YAHOO_STATUS_BRB :\n\t\t\treturn BeRightBack;\n\t\tcase YAHOO_STATUS_BUSY :\n\t\t\treturn Busy;\n\t\tcase YAHOO_STATUS_NOTATHOME :\n\t\t\treturn NotAtHome;\n\t\tcase YAHOO_STATUS_NOTATDESK :\n\t\t\treturn NotAtMyDesk;\n\t\tcase YAHOO_STATUS_NOTINOFFICE :\n\t\t\treturn NotInTheOffice;\n\t\tcase YAHOO_STATUS_ONPHONE :\n\t\t\treturn OnThePhone;\n\t\tcase YAHOO_STATUS_ONVACATION :\n\t\t\treturn OnVacation;\n\t\tcase YAHOO_STATUS_OUTTOLUNCH :\n\t\t\treturn OutToLunch;\n\t\tcase YAHOO_STATUS_STEPPEDOUT :\n\t\t\treturn SteppedOut;\n\t\tcase YAHOO_STATUS_INVISIBLE :\n\t\t\treturn Invisible;\n\t\tcase YAHOO_STATUS_CUSTOM :\n\t\t\treturn Custom;\n\t\tcase YAHOO_STATUS_IDLE :\n\t\t\treturn Idle;\n\t\tcase YAHOO_STATUS_OFFLINE :\n\t\t\treturn Offline;\n\t\tcase YAHOO_STATUS_TYPING :\n\t\t\treturn Typing;\n\t}\n\n\treturn Offline;\n}\nHackish, shortlived fix to stop the statuses conflicting with my internal KopeteOnlineStatus.\/*\n    yahoostatus.cpp - Yahoo Plugin for Kopete\n\n    Copyright (c) 2002 by Duncan Mac-Vicar Prett \n\n    Copyright (c) 2002 by the Kopete developers  \n\n    *************************************************************************\n    *                                                                       *\n    * This program is free software; you can redistribute it and\/or modify  *\n    * it under the terms of the GNU General Public License as published by  *\n    * the Free Software Foundation; either version 2 of the License, or     *\n    * (at your option) any later version.                                   *\n    *                                                                       *\n    *************************************************************************\n*\/\n\n#include \n#include \n#include \"yahoostatus.h\"\n#include \"yahooprotocol.h\"\n#include \"kopeteonlinestatus.h\"\n\nYahooStatus::YahooStatus( Status status_ )\n{\n\tm_status = status_;\n}\n\nYahooStatus::YahooStatus()\n{\n\tm_status = Offline;\n}\n\nKopeteOnlineStatus YahooStatus::translate() const\n{\n\tif(m_status == Available)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Online,  25, YahooProtocol::protocol(), m_status + 1, \"yahoo_protocol\",  i18n(YSTAvailable), i18n(YSTAvailable));\n\telse if(m_status == Mobile)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,     5, YahooProtocol::protocol(), m_status + 1, \"yahoo_mobile\",  i18n(\"On the mobile\"), i18n(\"On the mobile\"));\n\telse if(m_status == Invisible)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Offline, 0, YahooProtocol::protocol(), m_status + 1, QString::null, i18n(YSTInvisible), i18n(YSTInvisible));\n\telse if(m_status == Idle)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    15, YahooProtocol::protocol(), m_status + 1, \"yahoo_idle\",    i18n(\"Idle\"), i18n(\"Idle\"));\n\telse if(m_status == Custom)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    20, YahooProtocol::protocol(), m_status + 1, \"yahoo_away\",    m_statusText, m_statusText);\n\telse if(m_status == CustomBusy)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    20, YahooProtocol::protocol(), m_status + 1, \"yahoo_busy\",    m_statusText, m_statusText);\n\telse if(m_status == CustomMobile)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    20, YahooProtocol::protocol(), m_status + 1, \"yahoo_mobile\",  m_statusText, m_statusText);\n\telse if(m_status == BeRightBack)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, \"yahoo_away\",    i18n(YSTBeRightBack), i18n(YSTBeRightBack));\n\telse if(m_status == Busy)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, \"yahoo_busy\",    i18n(YSTBusy), i18n(YSTBusy));\n\telse if(m_status == NotAtHome)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, \"yahoo_away\",    i18n(YSTNotAtHome), i18n(YSTNotAtHome));\n\telse if(m_status == NotAtMyDesk)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, \"yahoo_away\",    i18n(YSTNotAtMyDesk), i18n(YSTNotAtMyDesk));\n\telse if(m_status == NotInTheOffice)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, \"yahoo_away\",    i18n(YSTNotInTheOffice), i18n(YSTNotInTheOffice));\n\telse if(m_status == OnThePhone)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, \"yahoo_mobile\",  i18n(YSTOnThePhone), i18n(YSTOnThePhone));\n\telse if(m_status == OnVacation)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, \"yahoo_away\",    i18n(YSTOnVacation), i18n(YSTOnVacation));\n\telse if(m_status == OutToLunch)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, \"yahoo_tea\",    i18n(YSTOutToLunch), i18n(YSTOutToLunch));\n\telse if(m_status == SteppedOut)\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, \"yahoo_away\",    i18n(YSTSteppedOut), i18n(YSTSteppedOut));\n\telse\t\/\/ must be offline\n\t\treturn KopeteOnlineStatus(KopeteOnlineStatus::Offline,  0, YahooProtocol::protocol(), m_status + 1, QString::null, i18n(YSTOffline), i18n(YSTOffline));\n}\n\nvoid YahooStatus::setStatus( Status status_, const QString &statusText_ )\n{\n\tm_status = status_;\n\tm_statusText = statusText_;\n}\n\nYahooStatus::Status YahooStatus::fromLibYahoo2( int status_ )\n{\n\tswitch (status_)\n\t{\n\t\tcase YAHOO_STATUS_AVAILABLE :\n\t\t\treturn Available;\n\t\tcase YAHOO_STATUS_BRB :\n\t\t\treturn BeRightBack;\n\t\tcase YAHOO_STATUS_BUSY :\n\t\t\treturn Busy;\n\t\tcase YAHOO_STATUS_NOTATHOME :\n\t\t\treturn NotAtHome;\n\t\tcase YAHOO_STATUS_NOTATDESK :\n\t\t\treturn NotAtMyDesk;\n\t\tcase YAHOO_STATUS_NOTINOFFICE :\n\t\t\treturn NotInTheOffice;\n\t\tcase YAHOO_STATUS_ONPHONE :\n\t\t\treturn OnThePhone;\n\t\tcase YAHOO_STATUS_ONVACATION :\n\t\t\treturn OnVacation;\n\t\tcase YAHOO_STATUS_OUTTOLUNCH :\n\t\t\treturn OutToLunch;\n\t\tcase YAHOO_STATUS_STEPPEDOUT :\n\t\t\treturn SteppedOut;\n\t\tcase YAHOO_STATUS_INVISIBLE :\n\t\t\treturn Invisible;\n\t\tcase YAHOO_STATUS_CUSTOM :\n\t\t\treturn Custom;\n\t\tcase YAHOO_STATUS_IDLE :\n\t\t\treturn Idle;\n\t\tcase YAHOO_STATUS_OFFLINE :\n\t\t\treturn Offline;\n\t\tcase YAHOO_STATUS_TYPING :\n\t\t\treturn Typing;\n\t}\n\n\treturn Offline;\n}\n<|endoftext|>"}
{"text":"#pragma once\n\nnamespace despairagus {\n\tnamespace bitnode {\n\t\ttemplate \n\t\tclass bitnode {\n\t\t\ttemplate\n\t\t\tusing conref = const B &;\n\n\t\t\tusing byte = unsigned char;\n\t\t\tusing bit = bool;\n\n\t\tpublic:\n\t\t\tinline explicit bitnode(void) : zero{nullptr}, one{nullptr}, data{nullptr} {}\n\n\t\t\ttemplate \n\t\t\texplicit bitnode(A... a) = delete;\n\n\t\tprivate:\n\t\t\tbitnode* zero;\n\t\t\tbitnode* one;\n\n\t\t\tA* data;\n\t\t};\n\t}\n}ensure that constructor throws no exceptions#pragma once\n\nnamespace despairagus {\n\tnamespace bitnode {\n\t\ttemplate \n\t\tclass bitnode {\n\t\t\ttemplate\n\t\t\tusing conref = const B &;\n\n\t\t\tusing byte = unsigned char;\n\t\t\tusing bit = bool;\n\n\t\tpublic:\n\t\t\tinline explicit bitnode(void) noexcept : zero{nullptr}, one{nullptr}, data{nullptr} {}\n\n\t\t\ttemplate \n\t\t\texplicit bitnode(A... a) = delete;\n\n\t\tprivate:\n\t\t\tbitnode* zero;\n\t\t\tbitnode* one;\n\n\t\t\tA* data;\n\t\t};\n\t}\n}<|endoftext|>"}
{"text":"Added order option<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/spellcheck_host.h\"\n\n#include \"base\/string_split.h\"\n#include \"chrome\/browser\/prefs\/pref_member.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/spellcheck_host_impl.h\"\n#include \"chrome\/browser\/spellchecker_platform_engine.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/net\/url_request_context_getter.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/spellcheck_common.h\"\n#include \"content\/common\/notification_service.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"third_party\/hunspell\/google\/bdict.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace {\n\nFilePath GetFirstChoiceFilePath(const std::string& language) {\n  FilePath dict_dir;\n  {\n    \/\/ This should not do blocking IO from the UI thread!\n    \/\/ Temporarily allow it for now.\n    \/\/   http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=60643\n    base::ThreadRestrictions::ScopedAllowIO allow_io;\n    PathService::Get(chrome::DIR_APP_DICTIONARIES, &dict_dir);\n  }\n  return SpellCheckCommon::GetVersionedFileName(language, dict_dir);\n}\n\n#if defined(OS_MACOSX)\n\/\/ Collect metrics on how often Hunspell is used on OS X vs the native\n\/\/ spellchecker.\nvoid RecordSpellCheckStats(bool native_spellchecker_used,\n                           const std::string& language) {\n  static std::set languages_seen;\n\n  \/\/ Only count a language code once for each session..\n  if (languages_seen.find(language) != languages_seen.end()) {\n    return;\n  }\n  languages_seen.insert(language);\n\n  enum {\n    SPELLCHECK_OSX_NATIVE_SPELLCHECKER_USED = 0,\n    SPELLCHECK_HUNSPELL_USED = 1\n  };\n\n  bool engine_used = native_spellchecker_used ?\n                         SPELLCHECK_OSX_NATIVE_SPELLCHECKER_USED :\n                         SPELLCHECK_HUNSPELL_USED;\n\n  UMA_HISTOGRAM_COUNTS(\"SpellCheck.OSXEngineUsed\", engine_used);\n}\n#endif\n\n#if defined(OS_WIN)\nFilePath GetFallbackFilePath(const FilePath& first_choice) {\n  FilePath dict_dir;\n  PathService::Get(chrome::DIR_USER_DATA, &dict_dir);\n  return dict_dir.Append(first_choice.BaseName());\n}\n#endif\n\n}  \/\/ namespace\n\n\/\/ Constructed on UI thread.\nSpellCheckHost::SpellCheckHost(SpellCheckHostObserver* observer,\n                               const std::string& language,\n                               URLRequestContextGetter* request_context_getter)\n    : observer_(observer),\n      language_(language),\n      file_(base::kInvalidPlatformFileValue),\n      tried_to_download_(false),\n      use_platform_spellchecker_(false),\n      request_context_getter_(request_context_getter) {\n  DCHECK(observer_);\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n  FilePath personal_file_directory;\n  PathService::Get(chrome::DIR_USER_DATA, &personal_file_directory);\n  custom_dictionary_file_ =\n      personal_file_directory.Append(chrome::kCustomDictionaryFileName);\n\n  bdict_file_path_ = GetFirstChoiceFilePath(language);\n}\n\nSpellCheckHost::~SpellCheckHost() {\n  if (file_ != base::kInvalidPlatformFileValue)\n    base::ClosePlatformFile(file_);\n}\n\nvoid SpellCheckHost::Initialize() {\n  if (SpellCheckerPlatform::SpellCheckerAvailable() &&\n      SpellCheckerPlatform::PlatformSupportsLanguage(language_)) {\n#if defined(OS_MACOSX)\n    RecordSpellCheckStats(true, language_);\n#endif\n    use_platform_spellchecker_ = true;\n    SpellCheckerPlatform::SetLanguage(language_);\n    MessageLoop::current()->PostTask(FROM_HERE,\n        NewRunnableMethod(this,\n            &SpellCheckHost::InformObserverOfInitialization));\n    return;\n  }\n>>>>>>> Update a bunch of files to the new location of notification files.\n\n\/\/ static\nscoped_refptr SpellCheckHost::Create(\n    SpellCheckHostObserver* observer,\n    const std::string& language,\n    URLRequestContextGetter* request_context_getter) {\n  scoped_refptr host =\n      new SpellCheckHostImpl(observer,\n                             language,\n                             request_context_getter);\n  if (!host)\n    return NULL;\n\n  host->Initialize();\n  return host;\n}\n\n\/\/ static\nint SpellCheckHost::GetSpellCheckLanguages(\n    Profile* profile,\n    std::vector* languages) {\n  StringPrefMember accept_languages_pref;\n  StringPrefMember dictionary_language_pref;\n  accept_languages_pref.Init(prefs::kAcceptLanguages, profile->GetPrefs(),\n                             NULL);\n  dictionary_language_pref.Init(prefs::kSpellCheckDictionary,\n                                profile->GetPrefs(), NULL);\n  std::string dictionary_language = dictionary_language_pref.GetValue();\n\n  \/\/ The current dictionary language should be there.\n  languages->push_back(dictionary_language);\n\n  \/\/ Now scan through the list of accept languages, and find possible mappings\n  \/\/ from this list to the existing list of spell check languages.\n  std::vector accept_languages;\n\n  if (SpellCheckerPlatform::SpellCheckerAvailable())\n    SpellCheckerPlatform::GetAvailableLanguages(&accept_languages);\n  else\n    base::SplitString(accept_languages_pref.GetValue(), ',', &accept_languages);\n\n  for (std::vector::const_iterator i = accept_languages.begin();\n       i != accept_languages.end(); ++i) {\n    std::string language =\n        SpellCheckCommon::GetCorrespondingSpellCheckLanguage(*i);\n    if (!language.empty() &&\n        std::find(languages->begin(), languages->end(), language) ==\n        languages->end()) {\n      languages->push_back(language);\n    }\n  }\n\n  for (size_t i = 0; i < languages->size(); ++i) {\n    if ((*languages)[i] == dictionary_language)\n      return i;\n  }\n  return -1;\n}\n\nFix a bad rebase conflict. This should fix the bots.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/spellcheck_host.h\"\n\n#include \"base\/string_split.h\"\n#include \"chrome\/browser\/prefs\/pref_member.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/spellcheck_host_impl.h\"\n#include \"chrome\/browser\/spellchecker_platform_engine.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/spellcheck_common.h\"\n\n\/\/ static\nscoped_refptr SpellCheckHost::Create(\n    SpellCheckHostObserver* observer,\n    const std::string& language,\n    URLRequestContextGetter* request_context_getter) {\n  scoped_refptr host =\n      new SpellCheckHostImpl(observer,\n                             language,\n                             request_context_getter);\n  if (!host)\n    return NULL;\n\n  host->Initialize();\n  return host;\n}\n\n\/\/ static\nint SpellCheckHost::GetSpellCheckLanguages(\n    Profile* profile,\n    std::vector* languages) {\n  StringPrefMember accept_languages_pref;\n  StringPrefMember dictionary_language_pref;\n  accept_languages_pref.Init(prefs::kAcceptLanguages, profile->GetPrefs(),\n                             NULL);\n  dictionary_language_pref.Init(prefs::kSpellCheckDictionary,\n                                profile->GetPrefs(), NULL);\n  std::string dictionary_language = dictionary_language_pref.GetValue();\n\n  \/\/ The current dictionary language should be there.\n  languages->push_back(dictionary_language);\n\n  \/\/ Now scan through the list of accept languages, and find possible mappings\n  \/\/ from this list to the existing list of spell check languages.\n  std::vector accept_languages;\n\n  if (SpellCheckerPlatform::SpellCheckerAvailable())\n    SpellCheckerPlatform::GetAvailableLanguages(&accept_languages);\n  else\n    base::SplitString(accept_languages_pref.GetValue(), ',', &accept_languages);\n\n  for (std::vector::const_iterator i = accept_languages.begin();\n       i != accept_languages.end(); ++i) {\n    std::string language =\n        SpellCheckCommon::GetCorrespondingSpellCheckLanguage(*i);\n    if (!language.empty() &&\n        std::find(languages->begin(), languages->end(), language) ==\n        languages->end()) {\n      languages->push_back(language);\n    }\n  }\n\n  for (size_t i = 0; i < languages->size(); ++i) {\n    if ((*languages)[i] == dictionary_language)\n      return i;\n  }\n  return -1;\n}\n<|endoftext|>"}
{"text":"#include \"Resources.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstring ResourceList::Resource::GetName() const {\n    switch (type) {\n    case Type::SCENE:\n        return scene;\n    case Type::MODEL:\n        return model->name;\n    case Type::TEXTURE:\n        return texture->name;\n    case Type::SOUND:\n        return sound->name;\n    case Type::SCRIPT:\n        return script->name;\n    default:\n        return \"\";\n    }\n}\n\nResourceList::ResourceList() {\n    activeScene = \"\";\n    resourceFolder.name = \"Resources\";\n}\n\nResourceList& ResourceList::GetInstance() {\n    static ResourceList resourceList;\n    \n    return resourceList;\n}\n\nvoid ResourceList::Save() const {\n    \/\/ Save to file.\n    ofstream file(GetSavePath());\n    file << ToJson();\n    file.close();\n}\n\nJson::Value ResourceList::ToJson() const {\n    Json::Value root;\n    \n    root[\"activeScene\"] = activeScene;\n    root[\"resourceFolder\"] = SaveFolder(resourceFolder);\n    \n    root[\"sceneNumber\"] = sceneNumber;\n    root[\"textureNumber\"] = textureNumber;\n    root[\"modelNumber\"] = modelNumber;\n    root[\"soundNumber\"] = soundNumber;\n    root[\"scriptNumber\"] = scriptNumber;\n    \n    return root;\n}\n\nvoid ResourceList::Load() {\n    \/\/ Load Json document from file.\n    Json::Value root;\n    ifstream file(GetSavePath());\n    file >> root;\n    file.close();\n    \n    activeScene = root[\"activeScene\"].asString();\n    resourceFolder = LoadFolder(root[\"resourceFolder\"], \"\");\n    \n    sceneNumber = root[\"sceneNumber\"].asUInt();\n    textureNumber = root[\"textureNumber\"].asUInt();\n    modelNumber = root[\"modelNumber\"].asUInt();\n    soundNumber = root[\"soundNumber\"].asUInt();\n    scriptNumber = root[\"scriptNumber\"].asUInt();\n}\n\nvoid ResourceList::Clear() {\n    ClearFolder(resourceFolder);\n    resourceFolder.name = \"Resources\";\n    \n    sceneNumber = 0U;\n    modelNumber = 0U;\n    textureNumber = 0U;\n    soundNumber = 0U;\n    scriptNumber = 0U;\n}\n\nJson::Value ResourceList::SaveFolder(const ResourceFolder& folder) const {\n    Json::Value node;\n    node[\"name\"] = folder.name;\n    \n    \/\/ Save subfolders.\n    Json::Value subfolders;\n    for (const ResourceFolder& subfolder : folder.subfolders)\n        subfolders.append(SaveFolder(subfolder));\n    \n    node[\"subfolders\"] = subfolders;\n    \n    \/\/ Save resources.\n    Json::Value resourcesNode;\n    for (const Resource& resource : folder.resources) {\n        Json::Value resourceNode;\n        resourceNode[\"type\"] = resource.type;\n        \n        switch (resource.type) {\n        case Resource::SCENE:\n            resourceNode[\"scene\"] = resource.scene;\n            break;\n        case Resource::TEXTURE:\n            resourceNode[\"texture\"] = resource.texture->name;\n            resource.texture->Save();\n            break;\n        case Resource::MODEL:\n            resourceNode[\"model\"] = resource.model->name;\n            resource.model->Save();\n            break;\n        case Resource::SOUND:\n            resourceNode[\"sound\"] = resource.sound->name;\n            resource.sound->Save();\n            break;\n        case Resource::SCRIPT:\n            resourceNode[\"script\"] = resource.script->name;\n            resource.script->Save();\n            break;\n        }\n        \n        resourcesNode.append(resourceNode);\n    }\n    node[\"resources\"] = resourcesNode;\n    \n    return node;\n}\n\nResourceList::ResourceFolder ResourceList::LoadFolder(const Json::Value& node, std::string path) {\n    ResourceFolder folder;\n    folder.name = node[\"name\"].asString();\n    path += folder.name + \"\/\";\n    \n    \/\/ Load subfolders.\n    Json::Value subfoldersNode = node[\"subfolders\"];\n    for (unsigned int i = 0; i < subfoldersNode.size(); ++i)\n        folder.subfolders.push_back(LoadFolder(subfoldersNode[i], path));\n    \n    \/\/ Load resources.\n    Json::Value resourcesNode = node[\"resources\"];\n    for (unsigned int i = 0; i < resourcesNode.size(); ++i) {\n        Json::Value resourceNode = resourcesNode[i];\n        Resource resource;\n        resource.type = static_cast(resourceNode[\"type\"].asInt());\n        \n        switch (resource.type) {\n        case Resource::SCENE:\n            resource.scene = resourceNode[\"scene\"].asString();\n            break;\n        case Resource::TEXTURE:\n            resource.texture = Managers().resourceManager->CreateTextureAsset(path + resourceNode[\"texture\"].asString());\n            break;\n        case Resource::MODEL:\n            resource.model = Managers().resourceManager->CreateModel(path + resourceNode[\"model\"].asString());\n            break;\n        case Resource::SOUND:\n            resource.sound = Managers().resourceManager->CreateSound(path + resourceNode[\"sound\"].asString());\n            break;\n        case Resource::SCRIPT:\n            resource.script = Managers().resourceManager->CreateScriptFile(path + resourceNode[\"script\"].asString());\n            break;\n        }\n        \n        folder.resources.push_back(resource);\n    }\n    \n    return folder;\n}\n\nvoid ResourceList::ClearFolder(ResourceFolder& folder) {\n    \/\/ Clear subfolders.\n    for (ResourceFolder& subfolder : folder.subfolders)\n        ClearFolder(subfolder);\n    \n    folder.subfolders.clear();\n    \n    \/\/ Clear resources.\n    for (const Resource& resource : folder.resources) {\n        switch (resource.type) {\n        case Resource::Type::MODEL:\n            Managers().resourceManager->FreeModel(resource.model);\n            break;\n        case Resource::Type::TEXTURE:\n            Managers().resourceManager->FreeTextureAsset(resource.texture);\n            break;\n        case Resource::Type::SOUND:\n            Managers().resourceManager->FreeSound(resource.sound);\n            break;\n        default:\n            break;\n        }\n    }\n    folder.resources.clear();\n}\n\nstd::string ResourceList::GetSavePath() const{\n    return Hymn().GetPath() + FileSystem::DELIMITER + \"Resources.json\";\n}\n\nResourceList& Resources() {\n    return ResourceList::GetInstance();\n}\nRemove unnecessary statement#include \"Resources.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstring ResourceList::Resource::GetName() const {\n    switch (type) {\n    case Type::SCENE:\n        return scene;\n    case Type::MODEL:\n        return model->name;\n    case Type::TEXTURE:\n        return texture->name;\n    case Type::SOUND:\n        return sound->name;\n    case Type::SCRIPT:\n        return script->name;\n    default:\n        return \"\";\n    }\n}\n\nResourceList::ResourceList() {\n    resourceFolder.name = \"Resources\";\n}\n\nResourceList& ResourceList::GetInstance() {\n    static ResourceList resourceList;\n    \n    return resourceList;\n}\n\nvoid ResourceList::Save() const {\n    \/\/ Save to file.\n    ofstream file(GetSavePath());\n    file << ToJson();\n    file.close();\n}\n\nJson::Value ResourceList::ToJson() const {\n    Json::Value root;\n    \n    root[\"activeScene\"] = activeScene;\n    root[\"resourceFolder\"] = SaveFolder(resourceFolder);\n    \n    root[\"sceneNumber\"] = sceneNumber;\n    root[\"textureNumber\"] = textureNumber;\n    root[\"modelNumber\"] = modelNumber;\n    root[\"soundNumber\"] = soundNumber;\n    root[\"scriptNumber\"] = scriptNumber;\n    \n    return root;\n}\n\nvoid ResourceList::Load() {\n    \/\/ Load Json document from file.\n    Json::Value root;\n    ifstream file(GetSavePath());\n    file >> root;\n    file.close();\n    \n    activeScene = root[\"activeScene\"].asString();\n    resourceFolder = LoadFolder(root[\"resourceFolder\"], \"\");\n    \n    sceneNumber = root[\"sceneNumber\"].asUInt();\n    textureNumber = root[\"textureNumber\"].asUInt();\n    modelNumber = root[\"modelNumber\"].asUInt();\n    soundNumber = root[\"soundNumber\"].asUInt();\n    scriptNumber = root[\"scriptNumber\"].asUInt();\n}\n\nvoid ResourceList::Clear() {\n    ClearFolder(resourceFolder);\n    resourceFolder.name = \"Resources\";\n    \n    sceneNumber = 0U;\n    modelNumber = 0U;\n    textureNumber = 0U;\n    soundNumber = 0U;\n    scriptNumber = 0U;\n}\n\nJson::Value ResourceList::SaveFolder(const ResourceFolder& folder) const {\n    Json::Value node;\n    node[\"name\"] = folder.name;\n    \n    \/\/ Save subfolders.\n    Json::Value subfolders;\n    for (const ResourceFolder& subfolder : folder.subfolders)\n        subfolders.append(SaveFolder(subfolder));\n    \n    node[\"subfolders\"] = subfolders;\n    \n    \/\/ Save resources.\n    Json::Value resourcesNode;\n    for (const Resource& resource : folder.resources) {\n        Json::Value resourceNode;\n        resourceNode[\"type\"] = resource.type;\n        \n        switch (resource.type) {\n        case Resource::SCENE:\n            resourceNode[\"scene\"] = resource.scene;\n            break;\n        case Resource::TEXTURE:\n            resourceNode[\"texture\"] = resource.texture->name;\n            resource.texture->Save();\n            break;\n        case Resource::MODEL:\n            resourceNode[\"model\"] = resource.model->name;\n            resource.model->Save();\n            break;\n        case Resource::SOUND:\n            resourceNode[\"sound\"] = resource.sound->name;\n            resource.sound->Save();\n            break;\n        case Resource::SCRIPT:\n            resourceNode[\"script\"] = resource.script->name;\n            resource.script->Save();\n            break;\n        }\n        \n        resourcesNode.append(resourceNode);\n    }\n    node[\"resources\"] = resourcesNode;\n    \n    return node;\n}\n\nResourceList::ResourceFolder ResourceList::LoadFolder(const Json::Value& node, std::string path) {\n    ResourceFolder folder;\n    folder.name = node[\"name\"].asString();\n    path += folder.name + \"\/\";\n    \n    \/\/ Load subfolders.\n    Json::Value subfoldersNode = node[\"subfolders\"];\n    for (unsigned int i = 0; i < subfoldersNode.size(); ++i)\n        folder.subfolders.push_back(LoadFolder(subfoldersNode[i], path));\n    \n    \/\/ Load resources.\n    Json::Value resourcesNode = node[\"resources\"];\n    for (unsigned int i = 0; i < resourcesNode.size(); ++i) {\n        Json::Value resourceNode = resourcesNode[i];\n        Resource resource;\n        resource.type = static_cast(resourceNode[\"type\"].asInt());\n        \n        switch (resource.type) {\n        case Resource::SCENE:\n            resource.scene = resourceNode[\"scene\"].asString();\n            break;\n        case Resource::TEXTURE:\n            resource.texture = Managers().resourceManager->CreateTextureAsset(path + resourceNode[\"texture\"].asString());\n            break;\n        case Resource::MODEL:\n            resource.model = Managers().resourceManager->CreateModel(path + resourceNode[\"model\"].asString());\n            break;\n        case Resource::SOUND:\n            resource.sound = Managers().resourceManager->CreateSound(path + resourceNode[\"sound\"].asString());\n            break;\n        case Resource::SCRIPT:\n            resource.script = Managers().resourceManager->CreateScriptFile(path + resourceNode[\"script\"].asString());\n            break;\n        }\n        \n        folder.resources.push_back(resource);\n    }\n    \n    return folder;\n}\n\nvoid ResourceList::ClearFolder(ResourceFolder& folder) {\n    \/\/ Clear subfolders.\n    for (ResourceFolder& subfolder : folder.subfolders)\n        ClearFolder(subfolder);\n    \n    folder.subfolders.clear();\n    \n    \/\/ Clear resources.\n    for (const Resource& resource : folder.resources) {\n        switch (resource.type) {\n        case Resource::Type::MODEL:\n            Managers().resourceManager->FreeModel(resource.model);\n            break;\n        case Resource::Type::TEXTURE:\n            Managers().resourceManager->FreeTextureAsset(resource.texture);\n            break;\n        case Resource::Type::SOUND:\n            Managers().resourceManager->FreeSound(resource.sound);\n            break;\n        default:\n            break;\n        }\n    }\n    folder.resources.clear();\n}\n\nstd::string ResourceList::GetSavePath() const{\n    return Hymn().GetPath() + FileSystem::DELIMITER + \"Resources.json\";\n}\n\nResourceList& Resources() {\n    return ResourceList::GetInstance();\n}\n<|endoftext|>"}
{"text":"In system level install case go back to copying files instead of moving them.<|endoftext|>"}
{"text":"#include \"stdafx.h\"\n#include \"EsriClientThread.h\"\n#include \"EsriHandler.h\"\n#include \"strOps.h\"\n#include \n\nnamespace libESRI\n{\n  bool IsTextOrNumber(const char c)\n  {\n    return c >= 32 && c < 127;\n  }\n\n  EsriClientThread::EsriClientThread(toni::TcpClient* tcpClient, EsriHandler* handler)\n    : m_tcpClient(tcpClient)\n    , m_handler(handler)\n  {\n\n  }\n\n  bool EsriClientThread::SendWelcomeMessage()\n  {\n    char const * const welcomeMessage = m_handler->OnProvideWelcomeMessage();\n    if (welcomeMessage)\n    {\n      size_t welcomeMessageLength = strlen(welcomeMessage);\n      return m_tcpClient->Send(welcomeMessage, (int)welcomeMessageLength) > 0;\n    }\n\n    return true;    \n  }\n\n  bool EsriClientThread::SendCurrentDirectory()\n  {\n    char const * const curDir = m_handler->OnGetCurrentDirectory();\n    if (curDir)\n    {\n      std::string currentDirectory = curDir;\n      currentDirectory += \">\";\n      return m_tcpClient->Send(currentDirectory.c_str(), (int)currentDirectory.length()) > 0;\n    }\n\n    return true;\n  }\n\n  void EsriClientThread::AutoComplete(std::string& input, std::string& commonStartOfAllCandidates, std::vector& candidates)\n  {\n    auto* allCommandsAsString = m_handler->OnProvideCommands();\n    if (!allCommandsAsString)\n    {\n      commonStartOfAllCandidates = input;\n      return;\n    }\n\n    auto allCommands = toni::Tokenize(allCommandsAsString, \";\");\n    for (auto& candidate : allCommands)\n    {\n      if (!candidate.empty() && candidate.find(input) == 0)\n        candidates.push_back(candidate);\n    }\n\n    if (candidates.empty())\n    {\n      commonStartOfAllCandidates = input;\n      return;\n    }\n\n    if (candidates.size() == 1)\n    {\n      commonStartOfAllCandidates = candidates[0];\n      return;\n    }\n\n    \/\/candidates.size() now >= 2\n    std::sort(candidates.begin(), candidates.end());\n\n    std::string& first = candidates[0];\n    std::string& last = candidates[candidates.size() - 1];\n\n    size_t shortestCandidate = std::min(first.size(), last.size());\n    commonStartOfAllCandidates = \"\";\n    for (size_t i = 0; i < shortestCandidate; i++)\n    {\n      if (first[i] == last[i])\n        commonStartOfAllCandidates += first[i];\n      else\n        break;\n    }\n  }\n\n  bool EsriClientThread::HandleAutoComplete(std::string& input)\n  {\n    std::string autoCompletedInput;\n    std::vector otherCandidates;\n    AutoComplete(input, autoCompletedInput, otherCandidates);\n\n    if (otherCandidates.size() > 1)\n    {\n      std::string allCandidates = \"\\r\\n\";\n      for (auto& candidate : otherCandidates)\n      {\n        allCandidates += '\\t' + candidate + \"\\r\\n\";\n      }\n\n      input = autoCompletedInput;\n\n      allCandidates += m_handler->OnGetCurrentDirectory();\n      allCandidates += \">\";\n      allCandidates += input;\n      return m_tcpClient->Send(allCandidates.c_str(), (int)allCandidates.length()) > 0;\n    }\n    else\n    {\n      input = autoCompletedInput;\n\n      std::string autoCompletedInputWithPrompt = \"\\r\";\n      autoCompletedInputWithPrompt += m_handler->OnGetCurrentDirectory();\n      autoCompletedInputWithPrompt += \"\\>\";\n      autoCompletedInputWithPrompt += input;\n      return m_tcpClient->Send(autoCompletedInputWithPrompt.c_str(), (int)autoCompletedInputWithPrompt.length()) > 0;\n    }\n  }\n  \n  void EsriClientThread::EntryPoint()\n  {\n    if (!SendWelcomeMessage())\n      return;\n\n    if (!SendCurrentDirectory())\n      return;\n\n\n    int recvVal = 0;\n    std::vector receiveBuffer(1024);\n    std::string inputBuffer;\n    while ((recvVal = m_tcpClient->Recv(&receiveBuffer[0], (int)receiveBuffer.size())) > 0)\n    {\n      bool sentResponse = false;\n      if (recvVal > 1 && receiveBuffer[0] == 27) \/\/27 = ESC\n      {\n        std::string controlBuffer;\n        controlBuffer.assign(receiveBuffer.begin() + 1, receiveBuffer.end());\n      }\n      else\n      {\n        for (size_t i = 0; i < recvVal && !sentResponse; i++)\n        {\n          const char curChar = receiveBuffer[i];\n          switch (curChar)\n          {\n          case '\\t':\n            if (!HandleAutoComplete(inputBuffer))\n              return;\n            sentResponse = true;\n            break;\n          case '\\n':\n            m_handler->OnCommitCommand(inputBuffer.c_str());\n            inputBuffer.clear();\n            sentResponse = true;\n            break;\n          default:\n            if (IsTextOrNumber(curChar))\n              inputBuffer += curChar;\n            break;\n          }\n        }\n      }\n      \n    }\n  }\n}fixed controlBuffer#include \"stdafx.h\"\n#include \"EsriClientThread.h\"\n#include \"EsriHandler.h\"\n#include \"strOps.h\"\n#include \n\nnamespace libESRI\n{\n  bool IsTextOrNumber(const char c)\n  {\n    return c >= 32 && c < 127;\n  }\n\n  EsriClientThread::EsriClientThread(toni::TcpClient* tcpClient, EsriHandler* handler)\n    : m_tcpClient(tcpClient)\n    , m_handler(handler)\n  {\n\n  }\n\n  bool EsriClientThread::SendWelcomeMessage()\n  {\n    char const * const welcomeMessage = m_handler->OnProvideWelcomeMessage();\n    if (welcomeMessage)\n    {\n      size_t welcomeMessageLength = strlen(welcomeMessage);\n      return m_tcpClient->Send(welcomeMessage, (int)welcomeMessageLength) > 0;\n    }\n\n    return true;    \n  }\n\n  bool EsriClientThread::SendCurrentDirectory()\n  {\n    char const * const curDir = m_handler->OnGetCurrentDirectory();\n    if (curDir)\n    {\n      std::string currentDirectory = curDir;\n      currentDirectory += \">\";\n      return m_tcpClient->Send(currentDirectory.c_str(), (int)currentDirectory.length()) > 0;\n    }\n\n    return true;\n  }\n\n  void EsriClientThread::AutoComplete(std::string& input, std::string& commonStartOfAllCandidates, std::vector& candidates)\n  {\n    auto* allCommandsAsString = m_handler->OnProvideCommands();\n    if (!allCommandsAsString)\n    {\n      commonStartOfAllCandidates = input;\n      return;\n    }\n\n    auto allCommands = toni::Tokenize(allCommandsAsString, \";\");\n    for (auto& candidate : allCommands)\n    {\n      if (!candidate.empty() && candidate.find(input) == 0)\n        candidates.push_back(candidate);\n    }\n\n    if (candidates.empty())\n    {\n      commonStartOfAllCandidates = input;\n      return;\n    }\n\n    if (candidates.size() == 1)\n    {\n      commonStartOfAllCandidates = candidates[0];\n      return;\n    }\n\n    \/\/candidates.size() now >= 2\n    std::sort(candidates.begin(), candidates.end());\n\n    std::string& first = candidates[0];\n    std::string& last = candidates[candidates.size() - 1];\n\n    size_t shortestCandidate = std::min(first.size(), last.size());\n    commonStartOfAllCandidates = \"\";\n    for (size_t i = 0; i < shortestCandidate; i++)\n    {\n      if (first[i] == last[i])\n        commonStartOfAllCandidates += first[i];\n      else\n        break;\n    }\n  }\n\n  bool EsriClientThread::HandleAutoComplete(std::string& input)\n  {\n    std::string autoCompletedInput;\n    std::vector otherCandidates;\n    AutoComplete(input, autoCompletedInput, otherCandidates);\n\n    if (otherCandidates.size() > 1)\n    {\n      std::string allCandidates = \"\\r\\n\";\n      for (auto& candidate : otherCandidates)\n      {\n        allCandidates += '\\t' + candidate + \"\\r\\n\";\n      }\n\n      input = autoCompletedInput;\n\n      allCandidates += m_handler->OnGetCurrentDirectory();\n      allCandidates += \">\";\n      allCandidates += input;\n      return m_tcpClient->Send(allCandidates.c_str(), (int)allCandidates.length()) > 0;\n    }\n    else\n    {\n      input = autoCompletedInput;\n\n      std::string autoCompletedInputWithPrompt = \"\\r\";\n      autoCompletedInputWithPrompt += m_handler->OnGetCurrentDirectory();\n      autoCompletedInputWithPrompt += \">\";\n      autoCompletedInputWithPrompt += input;\n      return m_tcpClient->Send(autoCompletedInputWithPrompt.c_str(), (int)autoCompletedInputWithPrompt.length()) > 0;\n    }\n  }\n  \n  void EsriClientThread::EntryPoint()\n  {\n    if (!SendWelcomeMessage())\n      return;\n\n    if (!SendCurrentDirectory())\n      return;\n\n\n    int recvVal = 0;\n    std::vector receiveBuffer(1024);\n    std::string inputBuffer;\n    while ((recvVal = m_tcpClient->Recv(&receiveBuffer[0], (int)receiveBuffer.size())) > 0)\n    {\n      bool sentResponse = false;\n      if (recvVal > 1 && receiveBuffer[0] == 27) \/\/27 = ESC\n      {\n        std::string controlBuffer;\n        controlBuffer.assign(receiveBuffer.begin() + 1, receiveBuffer.begin() + recvVal);\n\n        if (controlBuffer.compare(\"clearInputBuffer\") == 0)\n        {\n          inputBuffer.clear();\n        }\n      }\n      else\n      {\n        for (size_t i = 0; i < recvVal && !sentResponse; i++)\n        {\n          const char curChar = receiveBuffer[i];\n          switch (curChar)\n          {\n          case '\\t':\n            if (!HandleAutoComplete(inputBuffer))\n              return;\n            sentResponse = true;\n            break;\n          case '\\n':\n            m_handler->OnCommitCommand(inputBuffer.c_str());\n            inputBuffer.clear();\n            sentResponse = true;\n            break;\n          default:\n            if (IsTextOrNumber(curChar))\n              inputBuffer += curChar;\n            break;\n          }\n        }\n      }\n      \n    }\n  }\n}<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/renderer\/blocked_plugin.h\"\n\n#include \"base\/string_piece.h\"\n#include \"base\/string_util.h\"\n#include \"base\/values.h\"\n#include \"chrome\/common\/jstemplate_builder.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/renderer\/render_view.h\"\n#include \"grit\/generated_resources.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebContextMenuData.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebData.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebMenuItemInfo.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebPluginContainer.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebPoint.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebRegularExpression.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebTextCaseSensitivity.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebVector.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebView.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"webkit\/glue\/webpreferences.h\"\n#include \"webkit\/plugins\/npapi\/plugin_group.h\"\n#include \"webkit\/plugins\/npapi\/webview_plugin.h\"\n\nusing WebKit::WebContextMenuData;\nusing WebKit::WebElement;\nusing WebKit::WebFrame;\nusing WebKit::WebMenuItemInfo;\nusing WebKit::WebNode;\nusing WebKit::WebPlugin;\nusing WebKit::WebPluginContainer;\nusing WebKit::WebPluginParams;\nusing WebKit::WebPoint;\nusing WebKit::WebRegularExpression;\nusing WebKit::WebString;\nusing WebKit::WebVector;\n\nstatic const char* const kBlockedPluginDataURL = \"chrome:\/\/blockedplugindata\/\";\n\/\/ TODO(cevans) - move these to a shared header file so that there are no\n\/\/ collisions in the longer term. Currently, blocked_plugin.cc is the only\n\/\/ user of custom menu commands (extension menu items have their own range).\nstatic const unsigned kMenuActionLoad = 1;\nstatic const unsigned kMenuActionRemove = 2;\n\nBlockedPlugin::BlockedPlugin(RenderView* render_view,\n                             WebFrame* frame,\n                             const webkit::npapi::PluginGroup& info,\n                             const WebPluginParams& params,\n                             const WebPreferences& preferences,\n                             int template_id,\n                             const string16& message,\n                             bool is_blocked_for_prerendering)\n    : RenderViewObserver(render_view),\n      frame_(frame),\n      plugin_params_(params),\n      is_blocked_for_prerendering_(is_blocked_for_prerendering) {\n  const base::StringPiece template_html(\n      ResourceBundle::GetSharedInstance().GetRawDataResource(template_id));\n\n  DCHECK(!template_html.empty()) << \"unable to load template. ID: \"\n                                 << template_id;\n\n  DictionaryValue values;\n  values.SetString(\"message\", message);\n  name_ = info.GetGroupName();\n  values.SetString(\"name\", name_);\n\n  \/\/ \"t\" is the id of the templates root node.\n  std::string html_data = jstemplate_builder::GetTemplatesHtml(\n      template_html, &values, \"t\");\n\n  plugin_ = webkit::npapi::WebViewPlugin::Create(this,\n                                                 preferences,\n                                                 html_data,\n                                                 GURL(kBlockedPluginDataURL));\n}\n\nBlockedPlugin::~BlockedPlugin() {\n}\n\nvoid BlockedPlugin::BindWebFrame(WebFrame* frame) {\n  BindToJavascript(frame, \"plugin\");\n  BindMethod(\"load\", &BlockedPlugin::Load);\n  BindMethod(\"hide\", &BlockedPlugin::Hide);\n}\n\nvoid BlockedPlugin::WillDestroyPlugin() {\n  delete this;\n}\n\nvoid BlockedPlugin::ShowContextMenu(const WebKit::WebMouseEvent& event) {\n  WebContextMenuData menu_data;\n  WebVector custom_items(static_cast(4));\n\n  WebMenuItemInfo name_item;\n  name_item.label = name_;\n  custom_items[0] = name_item;\n\n  WebMenuItemInfo separator_item;\n  separator_item.type = WebMenuItemInfo::Separator;\n  custom_items[1] = separator_item;\n\n  WebMenuItemInfo run_item;\n  run_item.action = kMenuActionLoad;\n  run_item.enabled = true;\n  run_item.label = WebString::fromUTF8(\n      l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_RUN).c_str());\n  custom_items[2] = run_item;\n\n  WebMenuItemInfo hide_item;\n  hide_item.action = kMenuActionRemove;\n  hide_item.enabled = true;\n  hide_item.label = WebString::fromUTF8(\n      l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_HIDE).c_str());\n  custom_items[3] = hide_item;\n\n  menu_data.customItems.swap(custom_items);\n  menu_data.mousePosition = WebPoint(event.windowX, event.windowY);\n  render_view()->showContextMenu(NULL, menu_data);\n}\n\nbool BlockedPlugin::OnMessageReceived(const IPC::Message& message) {\n  \/\/ We don't swallow ViewMsg_CustomContextMenuAction because we listen for all\n  \/\/ custom menu IDs, and not just our own. We don't swallow\n  \/\/ ViewMsg_LoadBlockedPlugins because multiple blocked plugins have an\n  \/\/ interest in it.\n  if (message.type() == ViewMsg_CustomContextMenuAction::ID) {\n    ViewMsg_CustomContextMenuAction::Dispatch(\n        &message, this, this, &BlockedPlugin::OnMenuItemSelected);\n  } else if (message.type() == ViewMsg_LoadBlockedPlugins::ID) {\n    LoadPlugin();\n  } else if (message.type() == ViewMsg_DisplayPrerenderedPage::ID) {\n    if (is_blocked_for_prerendering_)\n      LoadPlugin();\n  }\n\n  return false;\n}\n\nvoid BlockedPlugin::OnMenuItemSelected(unsigned id) {\n  if (id == kMenuActionLoad) {\n    LoadPlugin();\n  } else if (id == kMenuActionRemove) {\n    HidePlugin();\n  }\n}\n\nvoid BlockedPlugin::LoadPlugin() {\n  CHECK(plugin_);\n  WebPluginContainer* container = plugin_->container();\n  WebPlugin* new_plugin =\n      render_view()->CreatePluginNoCheck(frame_, plugin_params_);\n  if (new_plugin && new_plugin->initialize(container)) {\n    container->setPlugin(new_plugin);\n    container->invalidate();\n    container->reportGeometry();\n    plugin_->ReplayReceivedData(new_plugin);\n    plugin_->destroy();\n  }\n}\n\nvoid BlockedPlugin::Load(const CppArgumentList& args, CppVariant* result) {\n  LoadPlugin();\n}\n\nvoid BlockedPlugin::Hide(const CppArgumentList& args, CppVariant* result) {\n  HidePlugin();\n}\n\nvoid BlockedPlugin::HidePlugin() {\n  CHECK(plugin_);\n  WebPluginContainer* container = plugin_->container();\n  WebElement element = container->element();\n  element.setAttribute(\"style\", \"display: none;\");\n  \/\/ If we have a width and height, search for a parent (often 
) with the\n \/\/ same dimensions. If we find such a parent, hide that as well.\n \/\/ This makes much more uncovered page content usable (including clickable)\n \/\/ as opposed to merely visible.\n \/\/ TODO(cevans) -- it's a foul heurisitc but we're going to tolerate it for\n \/\/ now for these reasons:\n \/\/ 1) Makes the user experience better.\n \/\/ 2) Foulness is encapsulated within this single function.\n \/\/ 3) Confidence in no fasle positives.\n \/\/ 4) Seems to have a good \/ low false negative rate at this time.\n if (element.hasAttribute(\"width\") && element.hasAttribute(\"height\")) {\n std::string width_str(\"width:[\\\\s]*\");\n width_str += element.getAttribute(\"width\").utf8().data();\n if (EndsWith(width_str, \"px\", false)) {\n width_str = width_str.substr(0, width_str.length() - 2);\n }\n TrimWhitespace(width_str, TRIM_TRAILING, &width_str);\n width_str += \"[\\\\s]*px\";\n WebRegularExpression width_regex(WebString::fromUTF8(width_str.c_str()),\n WebKit::WebTextCaseSensitive);\n std::string height_str(\"height:[\\\\s]*\");\n height_str += element.getAttribute(\"height\").utf8().data();\n if (EndsWith(height_str, \"px\", false)) {\n height_str = height_str.substr(0, height_str.length() - 2);\n }\n TrimWhitespace(height_str, TRIM_TRAILING, &height_str);\n height_str += \"[\\\\s]*px\";\n WebRegularExpression height_regex(WebString::fromUTF8(height_str.c_str()),\n WebKit::WebTextCaseSensitive);\n WebNode parent = element;\n while (!parent.parentNode().isNull()) {\n parent = parent.parentNode();\n if (!parent.isElementNode())\n continue;\n element = parent.toConst();\n if (element.hasAttribute(\"style\")) {\n WebString style_str = element.getAttribute(\"style\");\n if (width_regex.match(style_str) >= 0 &&\n height_regex.match(style_str) >= 0)\n element.setAttribute(\"style\", \"display: none;\");\n }\n }\n }\n}\n\nOops, fix my previous fix to the refactor breakage. Make sure we only apply the current menu command to whoever opened the custom menu. We have to track it in a slightly ugly manner thanks to GTK's out-of-order messaging for \"menu item selected\" vs. \"context menu closed\".\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/renderer\/blocked_plugin.h\"\n\n#include \"base\/string_piece.h\"\n#include \"base\/string_util.h\"\n#include \"base\/values.h\"\n#include \"chrome\/common\/jstemplate_builder.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/renderer\/render_view.h\"\n#include \"grit\/generated_resources.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebContextMenuData.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebData.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebMenuItemInfo.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebPluginContainer.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebPoint.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebRegularExpression.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebTextCaseSensitivity.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebVector.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebView.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"webkit\/glue\/webpreferences.h\"\n#include \"webkit\/plugins\/npapi\/plugin_group.h\"\n#include \"webkit\/plugins\/npapi\/webview_plugin.h\"\n\nusing WebKit::WebContextMenuData;\nusing WebKit::WebElement;\nusing WebKit::WebFrame;\nusing WebKit::WebMenuItemInfo;\nusing WebKit::WebNode;\nusing WebKit::WebPlugin;\nusing WebKit::WebPluginContainer;\nusing WebKit::WebPluginParams;\nusing WebKit::WebPoint;\nusing WebKit::WebRegularExpression;\nusing WebKit::WebString;\nusing WebKit::WebVector;\n\nstatic const char* const kBlockedPluginDataURL = \"chrome:\/\/blockedplugindata\/\";\n\/\/ TODO(cevans) - move these to a shared header file so that there are no\n\/\/ collisions in the longer term. Currently, blocked_plugin.cc is the only\n\/\/ user of custom menu commands (extension menu items have their own range).\nstatic const unsigned kMenuActionLoad = 1;\nstatic const unsigned kMenuActionRemove = 2;\n\nstatic const BlockedPlugin* gLastActiveMenu;\n\nBlockedPlugin::BlockedPlugin(RenderView* render_view,\n WebFrame* frame,\n const webkit::npapi::PluginGroup& info,\n const WebPluginParams& params,\n const WebPreferences& preferences,\n int template_id,\n const string16& message,\n bool is_blocked_for_prerendering)\n : RenderViewObserver(render_view),\n frame_(frame),\n plugin_params_(params),\n is_blocked_for_prerendering_(is_blocked_for_prerendering) {\n const base::StringPiece template_html(\n ResourceBundle::GetSharedInstance().GetRawDataResource(template_id));\n\n DCHECK(!template_html.empty()) << \"unable to load template. ID: \"\n << template_id;\n\n DictionaryValue values;\n values.SetString(\"message\", message);\n name_ = info.GetGroupName();\n values.SetString(\"name\", name_);\n\n \/\/ \"t\" is the id of the templates root node.\n std::string html_data = jstemplate_builder::GetTemplatesHtml(\n template_html, &values, \"t\");\n\n plugin_ = webkit::npapi::WebViewPlugin::Create(this,\n preferences,\n html_data,\n GURL(kBlockedPluginDataURL));\n}\n\nBlockedPlugin::~BlockedPlugin() {\n}\n\nvoid BlockedPlugin::BindWebFrame(WebFrame* frame) {\n BindToJavascript(frame, \"plugin\");\n BindMethod(\"load\", &BlockedPlugin::Load);\n BindMethod(\"hide\", &BlockedPlugin::Hide);\n}\n\nvoid BlockedPlugin::WillDestroyPlugin() {\n delete this;\n}\n\nvoid BlockedPlugin::ShowContextMenu(const WebKit::WebMouseEvent& event) {\n WebContextMenuData menu_data;\n WebVector custom_items(static_cast(4));\n\n WebMenuItemInfo name_item;\n name_item.label = name_;\n custom_items[0] = name_item;\n\n WebMenuItemInfo separator_item;\n separator_item.type = WebMenuItemInfo::Separator;\n custom_items[1] = separator_item;\n\n WebMenuItemInfo run_item;\n run_item.action = kMenuActionLoad;\n run_item.enabled = true;\n run_item.label = WebString::fromUTF8(\n l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_RUN).c_str());\n custom_items[2] = run_item;\n\n WebMenuItemInfo hide_item;\n hide_item.action = kMenuActionRemove;\n hide_item.enabled = true;\n hide_item.label = WebString::fromUTF8(\n l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_HIDE).c_str());\n custom_items[3] = hide_item;\n\n menu_data.customItems.swap(custom_items);\n menu_data.mousePosition = WebPoint(event.windowX, event.windowY);\n render_view()->showContextMenu(NULL, menu_data);\n gLastActiveMenu = this;\n}\n\nbool BlockedPlugin::OnMessageReceived(const IPC::Message& message) {\n \/\/ We don't swallow ViewMsg_CustomContextMenuAction because we listen for all\n \/\/ custom menu IDs, and not just our own. We don't swallow\n \/\/ ViewMsg_LoadBlockedPlugins because multiple blocked plugins have an\n \/\/ interest in it.\n if (message.type() == ViewMsg_CustomContextMenuAction::ID &&\n gLastActiveMenu == this) {\n ViewMsg_CustomContextMenuAction::Dispatch(\n &message, this, this, &BlockedPlugin::OnMenuItemSelected);\n } else if (message.type() == ViewMsg_LoadBlockedPlugins::ID) {\n LoadPlugin();\n } else if (message.type() == ViewMsg_DisplayPrerenderedPage::ID) {\n if (is_blocked_for_prerendering_)\n LoadPlugin();\n }\n\n return false;\n}\n\nvoid BlockedPlugin::OnMenuItemSelected(unsigned id) {\n if (id == kMenuActionLoad) {\n LoadPlugin();\n } else if (id == kMenuActionRemove) {\n HidePlugin();\n }\n}\n\nvoid BlockedPlugin::LoadPlugin() {\n CHECK(plugin_);\n WebPluginContainer* container = plugin_->container();\n WebPlugin* new_plugin =\n render_view()->CreatePluginNoCheck(frame_, plugin_params_);\n if (new_plugin && new_plugin->initialize(container)) {\n container->setPlugin(new_plugin);\n container->invalidate();\n container->reportGeometry();\n plugin_->ReplayReceivedData(new_plugin);\n plugin_->destroy();\n }\n}\n\nvoid BlockedPlugin::Load(const CppArgumentList& args, CppVariant* result) {\n LoadPlugin();\n}\n\nvoid BlockedPlugin::Hide(const CppArgumentList& args, CppVariant* result) {\n HidePlugin();\n}\n\nvoid BlockedPlugin::HidePlugin() {\n CHECK(plugin_);\n WebPluginContainer* container = plugin_->container();\n WebElement element = container->element();\n element.setAttribute(\"style\", \"display: none;\");\n \/\/ If we have a width and height, search for a parent (often
) with the\n \/\/ same dimensions. If we find such a parent, hide that as well.\n \/\/ This makes much more uncovered page content usable (including clickable)\n \/\/ as opposed to merely visible.\n \/\/ TODO(cevans) -- it's a foul heurisitc but we're going to tolerate it for\n \/\/ now for these reasons:\n \/\/ 1) Makes the user experience better.\n \/\/ 2) Foulness is encapsulated within this single function.\n \/\/ 3) Confidence in no fasle positives.\n \/\/ 4) Seems to have a good \/ low false negative rate at this time.\n if (element.hasAttribute(\"width\") && element.hasAttribute(\"height\")) {\n std::string width_str(\"width:[\\\\s]*\");\n width_str += element.getAttribute(\"width\").utf8().data();\n if (EndsWith(width_str, \"px\", false)) {\n width_str = width_str.substr(0, width_str.length() - 2);\n }\n TrimWhitespace(width_str, TRIM_TRAILING, &width_str);\n width_str += \"[\\\\s]*px\";\n WebRegularExpression width_regex(WebString::fromUTF8(width_str.c_str()),\n WebKit::WebTextCaseSensitive);\n std::string height_str(\"height:[\\\\s]*\");\n height_str += element.getAttribute(\"height\").utf8().data();\n if (EndsWith(height_str, \"px\", false)) {\n height_str = height_str.substr(0, height_str.length() - 2);\n }\n TrimWhitespace(height_str, TRIM_TRAILING, &height_str);\n height_str += \"[\\\\s]*px\";\n WebRegularExpression height_regex(WebString::fromUTF8(height_str.c_str()),\n WebKit::WebTextCaseSensitive);\n WebNode parent = element;\n while (!parent.parentNode().isNull()) {\n parent = parent.parentNode();\n if (!parent.isElementNode())\n continue;\n element = parent.toConst();\n if (element.hasAttribute(\"style\")) {\n WebString style_str = element.getAttribute(\"style\");\n if (width_regex.match(style_str) >= 0 &&\n height_regex.match(style_str) >= 0)\n element.setAttribute(\"style\", \"display: none;\");\n }\n }\n }\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: appsettings.hxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-18 16:16:39 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _APPSETTINGS_HXX\n#define _APPSETTINGS_HXX\n\n#ifndef __STARDIV_UNO_UTIL_CONTAINR_HXX__\n#include \n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nXNameContainer* getApplicationSettings();\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n\nINTEGRATION: CWS ooo19126 (1.1.1.1.604); FILE MERGED 2005\/09\/05 12:58:25 rt 1.1.1.1.604.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: appsettings.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 19:00:53 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _APPSETTINGS_HXX\n#define _APPSETTINGS_HXX\n\n#ifndef __STARDIV_UNO_UTIL_CONTAINR_HXX__\n#include \n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nXNameContainer* getApplicationSettings();\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\nstruct Point final\n{\n\tusing value_type = int;\n\texplicit Point(const value_type& x = value_type(), const value_type& y = value_type()) noexcept\n\t: x_{x}, y_{y}\n\t{}\n\tPoint(const Point&) noexcept = default;\n\t~Point() noexcept = default;\n\tPoint& operator=(const Point&) noexcept = default;\n\n\tbool operator==(const Point& p) const noexcept {\n\t\treturn std::tie(x_, y_) == std::tie(p.x_, p.y_);\n\t}\n\tbool operator!=(const Point& p) const noexcept { return !(p == *this); }\n\n\tbool operator<(const Point& p) const noexcept {\n\t\treturn std::tie(x_, y_) < std::tie(p.x_, p.y_);\n\t}\n\n\tbool operator<=(const Point& p) const noexcept { return !(p < *this); }\n\tbool operator>=(const Point& p) const noexcept { return !(*this < p); }\n\tbool operator>(const Point& p) const noexcept { return !(*this <= p); }\n\n\tPoint& operator-=(const Point& p) noexcept { x_ -= p.x_; y_ -= p.y_; return *this; }\n\tfriend Point operator-(const Point& p1, const Point& p2) {\n\t\treturn Point(p1.x_ - p2.x_, p1.y_ - p2.y_);\n\t}\n \tPoint& operator+=(const Point& p) noexcept { x_ += p.x_; y_ += p.y_; return *this; }\n\tfriend Point operator+(const Point& p1, const Point& p2) {\n\t\treturn Point(p1.x_ + p2.x_, p1.y_ + p2.y_);\n\t}\n\tbool is_top_left(const Point& p) const noexcept {\n\t\treturn x_ <= p.x_ && y_ <= p.y_;\n\t}\n\t\/**\n\t * Assert p1 is top left of p2\n\t * i.e. p1.x <= p2.x and p1.y <= p2.y\n\t *\/\n\tstatic void assert_top_left(Point& p1, Point& p2) {\n\t\tif (p1.x_ > p2.x_) \n\t\t\tstd::swap(p1.x_, p2.x_);\n\t\tif (p1.y_ > p2.y_)\n\t\t\tstd::swap(p1.y_, p2.y_);\n\t}\n\n\tvalue_type x_{0}, y_{0};\n};\n\n\nstruct Rect final\n{\n\tenum class ConstructionType { unchecked };\n\texplicit Rect(const Point& p1, const Point& p2) noexcept \n\t: p1_{p1}, p2_{p2}\n\t{\n\t\tPoint::assert_top_left(p1_, p2_);\n\t}\n\texplicit Rect(ConstructionType ct = ConstructionType::unchecked, const Point& p1 = Point(), const Point& p2 = Point()) noexcept \n\t: p1_{p1}, p2_{p2}\n\t{}\n\tRect(const Rect&) noexcept = default;\n\t~Rect() noexcept = default;\n\tRect& operator=(const Rect& r) noexcept = default;\n\tbool contains(const Point& p) const noexcept {\n\t\treturn p1_.is_top_left(p) && p.is_top_left(p2_);\n\t}\n\tbool contains(const Rect& r) const noexcept {\n\t\treturn p1_.is_top_left(r.p1_) && r.p2_.is_top_left(p2_);\n\t}\n\tbool intersects(const Rect& r) const noexcept {\n\t\treturn p1_.is_top_left(r.p2_) && r.p2_.is_top_left(p1_);\n\t}\n\tstatic Rect combination(const Rect& r1, const Rect& r2) {\n\t\tPoint p1(\n\t\t\tstd::min(r1.p1_.x_, r2.p1_.x_),\n\t\t\tstd::min(r1.p1_.y_, r2.p1_.y_)\n\t\t\t);\n\t\tPoint p2(\n\t\t\tstd::max(r1.p2_.x_, r2.p2_.x_),\n\t\t\tstd::max(r1.p2_.y_, r2.p2_.y_)\n\t\t\t);\n\t\treturn Rect(ConstructionType::unchecked, p1, p2);\n\t}\n\tstatic std::pair intersection(const Rect& r1, const Rect& r2) {\n\t\tPoint p1(std::max(r1.p1_.x_, r2.p1_.x_), std::max(r1.p1_.y_, r2.p1_.y_));\n\t\tPoint p2(std::min(r1.p2_.x_, r2.p2_.x_), std::min(r1.p2_.y_, r2.p2_.y_));\n\t\tbool intersect = p1.is_top_left(p2);\n\t\tRect r;\n\t\tif (intersect) {\n\t\t\tr.p1_ = p1;\n\t\t\tr.p2_ = p2;\n\t\t}\n\t\treturn std::make_pair(intersect, r);\n\t}\n\tPoint::value_type area() const { auto p = p2_ - p1_; return std::abs(p.x_ * p.y_); }\n\tPoint p1_, p2_;\n};\n\nstruct RTree\n{\n\tusing value_type = std::pair;\n\tstatic const size_t max_node_size = 16;\n\tstruct RTIterator;\n\tstruct INode;\n\tstruct NodeBase {\n\t\t\/\/ Basic common elements\n\t\texplicit NodeBase(INode* parent) : parent_{parent} {}\n\t\tvirtual ~NodeBase() =default;\n\n\t\tsize_t size_ {0};\n\t\tINode* parent_;\n\t\tRect outline_;\n\t};\n\tstruct LeafNode;\n\tstruct IndexNode;\n\tstruct AbstractOperation {\n\t\tvirtual ~AbstractOperation() =0;\n\t\tvirtual void visit(IndexNode& n) =0;\n\t\tvirtual void visit(LeafNode& n) =0;\n\t};\n\tstruct INode {\n\t\t\/\/ pure abstract interface\n\t\tvirtual ~INode() =default;\n\t\tvirtual size_t size() const = 0;\n\t\tvirtual void accept(AbstractOperation& a) =0;\n\t\t\/\/virtual void add(const value_type& r) =0;\n\t\tvirtual INode* parent() =0;\n\t\tvirtual LeafNode* first_leaf(size_t* depth) =0;\n\t\tvirtual bool is_full() const { return size() == RTree::max_node_size; }\n\t\tvirtual const Rect& outline() const =0;\n\t\t\/\/virtual std::unique_ptr clone() =0;\n\t};\n\tstruct IndexNode : public NodeBase, public INode {\n\t\tusing value_type = std::pair>;\n\t\texplicit IndexNode(INode* parent) : NodeBase(parent)\n\t\t{}\n\t\tvirtual ~IndexNode() = default;\n\t\tvirtual INode* parent() override { return parent_; }\n\t\tvirtual size_t size() const override { return size_; }\n\t\tfriend class AbstractOperation;\n\t\tvirtual void accept(AbstractOperation& a) override { a.visit(*this); }\n\t\tvirtual LeafNode* first_leaf(size_t* depth) override { \n\t\t\tif (elements_.size() == 0)\n\t\t\t\treturn nullptr;\n\t\t\tif (depth != nullptr)\n\t\t\t\t++(*depth);\n\t\t\treturn std::get<1>(elements_[0])->first_leaf(depth); \n\t\t}\n\t\tvirtual const Rect& outline() const override { return outline_; }\n\t\tvirtual bool is_full() const override { return size_ == elements_.size(); }\n\n\t\tusing NodeBase::size_;\n\t\tusing NodeBase::parent_;\n\t\tusing NodeBase::outline_;\n\t\tstd::array elements_;\n\t\t\n\t};\n\tstruct LeafNode : public NodeBase, public INode {\n\t\texplicit LeafNode(INode* parent) : NodeBase(parent) \n\t\t{}\n\t\tvirtual ~LeafNode() = default;\n\t\tusing NodeBase::size_;\n\t\tusing NodeBase::parent_;\n\t\tvirtual INode* parent() override { return parent_; }\n\t\tvirtual size_t size() const override { return size_; }\n\t\tfriend class AbstractOperation;\n\t\tvirtual void accept(AbstractOperation& a) override { a.visit(*this); }\n\t\tvirtual LeafNode* first_leaf(size_t* depth) override { return this; }\n\t\tvirtual const Rect& outline() const override { return outline_; }\n\t\tvirtual bool is_full() const override { return size_ == elements_.size(); }\n\t\tstd::array elements_;\n\t};\n\tstruct AddOperation : public AbstractOperation {\n\t\texplicit AddOperation(const RTree::value_type& v, RTIterator& it) \n\t\t: value_(v), it_(it)\n\t\t{}\n\t\tvirtual void visit(IndexNode& n) {\n\t\t\t\/\/ TODO\n\t\t\t\/\/ choose sub tree\n\t\t\t\/\/ if it contains value_ rect\n\t\t\t\/\/ or choose the subtree which needs the least enlargement\n\t\t\tvector> heap;\n\t\t\tfor(const auto& e : n.elements_) {\n\t\t\t\tauto area = e.first.area();\n\t\t\t\tauto enlarged_rect = Rect::combination(e.first, value_.first);\n\t\t\t\tfloat enlargement = static_cast(enlarged_rect.area()) \/ (area > 0 ? area : 1);\n\t\t\t\tstd::push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)\n\t\t\t}\n\n\t\t\t\/\/ update outline\n\t\t\tn.outline_ = Rect::combination(n.outline_, it_.current_node_->outline_);\n\t\t}\n\t\tvirtual void visit(LeafNode& n) {\n\t\t\tif (n.is_full()) {\n\t\t\t\t\/\/ TODO split node\n\t\t\t} else {\n\t\t\t\t\/\/ insert here\n\t\t\t\tn.elements_[n.size()] =value_;\n\t\t\t\tit_.current_node_ = &n;\n\t\t\t\tit_.itstack_.push_back(n.size());\n\t\t\t\tn.size_++;\n\t\t\t\t\/\/ TODO n.outline_ = Rect::combination(n.outline_, std::get<0>(value_));\n\t\t\t\tn.outline_ = Rect::combination(n.outline(), value_.first);\n\t\t\t}\n\t\t}\n\t\tRTIterator& it_;\n\t\tconst RTree::value_type& value_;\n\t};\n\tusing FindResult = std::vector;\n\tstruct FindExactOperation : public AbstractOperation {\n\t\texplicit FindExactOperation(const Point& p) : p_{p}\n\t\t{}\n\t\tauto begin() { return result_.begin(); }\n\t\tauto end() { return result_.end(); }\n\t\tvirtual void visit(IndexNode& n) {\n\t\t\tfor(const auto& e : n.elements_) {\n\t\t\t\tconst auto& r = std::get<0>(e);\n\t\t\t\tif (r.contains(p_)) \n\t\t\t\t\tstd::get<1>(e)->accept(*this);\n\t\t\t}\n\t\t}\n\t\tvirtual void visit(LeafNode& n) {\n\t\t\tfor(const auto& e : n.elements_) {\n\t\t\t\tconst auto& r = std::get<0>(e);\n\t\t\t\tif (r.contains(p_)) {\n\t\t\t\t\tresult_.push_back(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tFindResult result_;\n\t\tconst Point& p_;\n\t};\n\tstruct FindNearestOperation : public AbstractOperation {\n\t\texplicit FindNearestOperation(const Point& p) : p_{p}\n\t\t{}\n\t\tvirtual void visit(IndexNode& n) {\n\t\t\t\/\/ TODO\n\t\t}\n\t\tvirtual void visit(LeafNode& n) {\n\t\t\t\/\/ TODO\n\t\t}\n\t\tFindResult result_;\n\t\tconst Point p_;\n\t};\n\tstruct RTIterator\n\t{\n\t\tbool operator==(const RTIterator& i) const {\n\t\t\tif (current_node_ == nullptr && i.current_node_ == nullptr)\n\t\t\t\treturn true;\n\t\t\treturn std::tie(current_node_, itstack_) == std::tie(i.current_node_, i.itstack_);\n\t\t}\n\t\tbool operator!=(const RTIterator& i) const { return !(*this == i); }\n\t\tRTIterator& operator++() { \n\t\t\tif (itstack_.size() > 0) {\n\t\t\t\tauto pos = itstack_.back();\n\t\t\t\t++pos;\n\t\t\t\tif (pos + 1 < current_node_->size())\n\t\t\t\t\treturn *this;\n\n\t\t\t\t\/\/ search into upwards index nodes\n\t\t\t\tINode* node = current_node_;\n\t\t\t\twhile (itstack_.size() > 0 && node != nullptr && node->size() <= pos) {\n\t\t\t\t\titstack_.pop_back();\n\t\t\t\t\tpos = ++itstack_.back();\n\t\t\t\t\tnode = node->parent();\n\t\t\t\t}\n\t\t\t\tif (itstack_.size() == 0) {\n\t\t\t\t\t\/\/ nothing found; we're at the end\n\t\t\t\t\tcurrent_node_ = nullptr;\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ search downward to leaf node\n\t\t\t\t\tsize_t depth {0};\n\t\t\t\t\tcurrent_node_ = node->first_leaf(&depth);\n\t\t\t\t\tfor(size_t i = 0; i < depth; ++i) {\n\t\t\t\t\t\titstack_.push_back(0);\n\t\t\t\t\t} \n\t\t\t\t}\n\t\t\t}\n\t\t\treturn *this; \n\t\t}\n\t\tRTree::value_type& operator*() { return current_node_->elements_[itstack_.back()]; }\n\t\t\/\/RTIterator& operator++(int) { return *this; }\n\t\t\/\/RTree* tree_ { nullptr };\n\t\tLeafNode* current_node_ { nullptr };\n\t\tstd::vector itstack_;\n\t};\n\tRTIterator begin();\n\tRTIterator end() { return RTIterator(); }\n\n\tRTIterator add(const value_type& r) {\n\t\tRTIterator it;\n\t\tAddOperation ao(r, it);\n\t\troot_->accept(ao);\n\t\treturn it;\n\t}\n\tFindResult find_containing(const Point& p) {\n\t\tFindExactOperation feo(p);\n\t\troot_->accept(feo);\n\t\treturn feo.result_;\n\t}\n\tFindResult find_nearest(const Point& p, size_t n = 1) {\n\t\t\/\/ TODO\n\t\tFindNearestOperation fno(p);\n\t\troot_->accept(fno);\n\t\treturn fno.result_;\n\t}\n\n\tstd::unique_ptr root_ = std::make_unique(nullptr);\n};\n\nint main(int argc, char const *argv[])\n{\n\tstd::vector params(argv, argv + argc);\n\tRTree rt;\n\tfor(const auto& p : params) {\n\t\tstd::cout << p << std::endl;\n\t}\n\treturn 0;\n}20171025#include \n#include \n#include \n#include \n#include \n\nstruct Point final\n{\n\tusing value_type = int;\n\texplicit Point(const value_type& x = value_type(), const value_type& y = value_type()) noexcept\n\t: x_{x}, y_{y}\n\t{}\n\tPoint(const Point&) noexcept = default;\n\t~Point() noexcept = default;\n\tPoint& operator=(const Point&) noexcept = default;\n\n\tbool operator==(const Point& p) const noexcept {\n\t\treturn std::tie(x_, y_) == std::tie(p.x_, p.y_);\n\t}\n\tbool operator!=(const Point& p) const noexcept { return !(p == *this); }\n\n\tbool operator<(const Point& p) const noexcept {\n\t\treturn std::tie(x_, y_) < std::tie(p.x_, p.y_);\n\t}\n\n\tbool operator<=(const Point& p) const noexcept { return !(p < *this); }\n\tbool operator>=(const Point& p) const noexcept { return !(*this < p); }\n\tbool operator>(const Point& p) const noexcept { return !(*this <= p); }\n\n\tPoint& operator-=(const Point& p) noexcept { x_ -= p.x_; y_ -= p.y_; return *this; }\n\tfriend Point operator-(const Point& p1, const Point& p2) {\n\t\treturn Point(p1.x_ - p2.x_, p1.y_ - p2.y_);\n\t}\n \tPoint& operator+=(const Point& p) noexcept { x_ += p.x_; y_ += p.y_; return *this; }\n\tfriend Point operator+(const Point& p1, const Point& p2) {\n\t\treturn Point(p1.x_ + p2.x_, p1.y_ + p2.y_);\n\t}\n\tbool is_top_left(const Point& p) const noexcept {\n\t\treturn x_ <= p.x_ && y_ <= p.y_;\n\t}\n\t\/**\n\t * Assert p1 is top left of p2\n\t * i.e. p1.x <= p2.x and p1.y <= p2.y\n\t *\/\n\tstatic void assert_top_left(Point& p1, Point& p2) {\n\t\tif (p1.x_ > p2.x_) \n\t\t\tstd::swap(p1.x_, p2.x_);\n\t\tif (p1.y_ > p2.y_)\n\t\t\tstd::swap(p1.y_, p2.y_);\n\t}\n\n\tvalue_type x_{0}, y_{0};\n};\n\n\nstruct Rect final\n{\n\tenum class ConstructionType { unchecked };\n\texplicit Rect(const Point& p1, const Point& p2) noexcept \n\t: p1_{p1}, p2_{p2}\n\t{\n\t\tPoint::assert_top_left(p1_, p2_);\n\t}\n\texplicit Rect(ConstructionType ct = ConstructionType::unchecked, const Point& p1 = Point(), const Point& p2 = Point()) noexcept \n\t: p1_{p1}, p2_{p2}\n\t{}\n\tRect(const Rect&) noexcept = default;\n\t~Rect() noexcept = default;\n\tRect& operator=(const Rect& r) noexcept = default;\n\tbool operator==(const Rect& r) const noexcept { return std::tie(p1_, p2_) == std::tie(r.p1_, r.p2_); }\n\tbool contains(const Point& p) const noexcept {\n\t\treturn p1_.is_top_left(p) && p.is_top_left(p2_);\n\t}\n\tbool contains(const Rect& r) const noexcept {\n\t\treturn p1_.is_top_left(r.p1_) && r.p2_.is_top_left(p2_);\n\t}\n\tbool intersects(const Rect& r) const noexcept {\n\t\treturn p1_.is_top_left(r.p2_) && r.p2_.is_top_left(p1_);\n\t}\n\tstatic Rect combination(const Rect& r1, const Rect& r2) {\n\t\tPoint p1(\n\t\t\tstd::min(r1.p1_.x_, r2.p1_.x_),\n\t\t\tstd::min(r1.p1_.y_, r2.p1_.y_)\n\t\t\t);\n\t\tPoint p2(\n\t\t\tstd::max(r1.p2_.x_, r2.p2_.x_),\n\t\t\tstd::max(r1.p2_.y_, r2.p2_.y_)\n\t\t\t);\n\t\treturn Rect(ConstructionType::unchecked, p1, p2);\n\t}\n\tstatic std::pair intersection(const Rect& r1, const Rect& r2) {\n\t\tPoint p1(std::max(r1.p1_.x_, r2.p1_.x_), std::max(r1.p1_.y_, r2.p1_.y_));\n\t\tPoint p2(std::min(r1.p2_.x_, r2.p2_.x_), std::min(r1.p2_.y_, r2.p2_.y_));\n\t\tbool intersect = p1.is_top_left(p2);\n\t\tRect r;\n\t\tif (intersect) {\n\t\t\tr.p1_ = p1;\n\t\t\tr.p2_ = p2;\n\t\t}\n\t\treturn std::make_pair(intersect, r);\n\t}\n\tPoint::value_type area() const { auto p = p2_ - p1_; return std::abs(p.x_ * p.y_); }\n\tPoint p1_, p2_;\n};\n\nstruct RTree\n{\n\tusing value_type = std::pair;\n\tstatic const size_t max_node_size = 16;\n\tstruct RTIterator;\n\tstruct INode;\n\tstruct NodeBase {\n\t\t\/\/ Basic common elements\n\t\texplicit NodeBase(INode* parent) : parent_{parent} {}\n\t\tvirtual ~NodeBase() =default;\n\n\t\tsize_t size_ {0};\n\t\tINode* parent_;\n\t\tRect outline_;\n\t};\n\tstruct LeafNode;\n\tstruct IndexNode;\n\tstruct AbstractOperation {\n\t\tvirtual void visit(IndexNode& n) =0;\n\t\tvirtual void visit(LeafNode& n) =0;\n\t};\n\tstruct INode {\n\t\t\/\/ pure abstract interface\n\t\tvirtual ~INode() =default;\n\t\tvirtual size_t size() const = 0;\n\t\tvirtual void accept(AbstractOperation& a) =0;\n\t\t\/\/virtual void add(const value_type& r) =0;\n\t\tvirtual INode* parent() =0;\n\t\tvirtual LeafNode* first_leaf(size_t* depth) =0;\n\t\tvirtual bool is_full() const { return size() == RTree::max_node_size; }\n\t\tvirtual const Rect& outline() const =0;\n\t\t\/\/virtual std::unique_ptr clone() =0;\n\t};\n\tstruct IndexNode : public NodeBase, public INode {\n\t\tusing value_type = std::pair>;\n\t\texplicit IndexNode(INode* parent) : NodeBase(parent)\n\t\t{}\n\t\tvirtual ~IndexNode() = default;\n\t\tvirtual INode* parent() override { return parent_; }\n\t\tvirtual size_t size() const override { return size_; }\n\t\tfriend class AbstractOperation;\n\t\tvirtual void accept(AbstractOperation& a) override { a.visit(*this); }\n\t\tvirtual LeafNode* first_leaf(size_t* depth) override { \n\t\t\tif (elements_.size() == 0)\n\t\t\t\treturn nullptr;\n\t\t\tif (depth != nullptr)\n\t\t\t\t++(*depth);\n\t\t\treturn std::get<1>(elements_[0])->first_leaf(depth); \n\t\t}\n\t\tvirtual const Rect& outline() const override { return outline_; }\n\t\tvirtual bool is_full() const override { return size_ == elements_.size(); }\n\n\t\tusing NodeBase::size_;\n\t\tusing NodeBase::parent_;\n\t\tusing NodeBase::outline_;\n\t\tstd::array elements_;\n\t\t\n\t};\n\tstruct LeafNode : public NodeBase, public INode {\n\t\texplicit LeafNode(INode* parent) : NodeBase(parent) \n\t\t{}\n\t\tvirtual ~LeafNode() = default;\n\t\tusing NodeBase::size_;\n\t\tusing NodeBase::parent_;\n\t\tvirtual INode* parent() override { return parent_; }\n\t\tvirtual size_t size() const override { return size_; }\n\t\tfriend class AbstractOperation;\n\t\tvirtual void accept(AbstractOperation& a) override { a.visit(*this); }\n\t\tvirtual LeafNode* first_leaf(size_t* depth) override { return this; }\n\t\tvirtual const Rect& outline() const override { return outline_; }\n\t\tvirtual bool is_full() const override { return size_ == elements_.size(); }\n\t\tstd::array elements_;\n\t};\n\tstruct AddOperation : public AbstractOperation {\n\t\texplicit AddOperation(const RTree::value_type& v, RTIterator& it) \n\t\t: value_(v), it_(it)\n\t\t{}\n\t\tvirtual void visit(IndexNode& n) {\n\t\t\t\/\/ TODO\n\t\t\t\/\/ choose sub tree\n\t\t\t\/\/ if it contains value_ rect\n\t\t\t\/\/ or choose the subtree which needs the least enlargement\n\t\t\theap_.reserve(n.elements_.size());\n\t\t\theap_.resize(0);\n\t\t\tstatic auto comp = [](const decltype(heap_)::value_type& a, const decltype(heap_)::value_type& b) -> bool {\n\t\t\t\treturn a.first < b.first;\n\t\t\t};\n\t\t\tfor(const auto& e : n.elements_) {\n\t\t\t\tauto area = e.first.area();\n\t\t\t\tauto enlarged_rect = Rect::combination(e.first, value_.first);\n\t\t\t\tfloat enlargement = static_cast(enlarged_rect.area()) \/ (area > 0 ? area : 1);\n\t\t\t\tstd::push_heap(heap_.begin(), heap_.end(), comp);\n\t\t\t\tif (e.first == enlarged_rect)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/ update outline\n\t\t\tn.outline_ = Rect::combination(n.outline_, it_.current_node_->outline_);\n\t\t}\n\t\tvirtual void visit(LeafNode& n) {\n\t\t\tif (n.is_full()) {\n\t\t\t\t\/\/ TODO split node\n\t\t\t} else {\n\t\t\t\t\/\/ insert here\n\t\t\t\tn.elements_[n.size()] =value_;\n\t\t\t\tit_.current_node_ = &n;\n\t\t\t\tit_.itstack_.push_back(n.size());\n\t\t\t\tn.size_++;\n\t\t\t\t\/\/ TODO n.outline_ = Rect::combination(n.outline_, std::get<0>(value_));\n\t\t\t\tn.outline_ = Rect::combination(n.outline(), value_.first);\n\t\t\t}\n\t\t}\n\t\tRTIterator& it_;\n\t\tconst RTree::value_type& value_;\n\t\tstd::vector> heap_;\n\t};\n\tusing FindResult = std::vector;\n\tstruct FindExactOperation : public AbstractOperation {\n\t\texplicit FindExactOperation(const Point& p) : p_{p}\n\t\t{}\n\t\tauto begin() { return result_.begin(); }\n\t\tauto end() { return result_.end(); }\n\t\tvirtual void visit(IndexNode& n) {\n\t\t\tfor(const auto& e : n.elements_) {\n\t\t\t\tconst auto& r = std::get<0>(e);\n\t\t\t\tif (r.contains(p_)) \n\t\t\t\t\tstd::get<1>(e)->accept(*this);\n\t\t\t}\n\t\t}\n\t\tvirtual void visit(LeafNode& n) {\n\t\t\tfor(const auto& e : n.elements_) {\n\t\t\t\tconst auto& r = std::get<0>(e);\n\t\t\t\tif (r.contains(p_)) {\n\t\t\t\t\tresult_.push_back(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tFindResult result_;\n\t\tconst Point& p_;\n\t};\n\tstruct FindNearestOperation : public AbstractOperation {\n\t\texplicit FindNearestOperation(const Point& p) : p_{p}\n\t\t{}\n\t\tvirtual void visit(IndexNode& n) {\n\t\t\t\/\/ TODO\n\t\t}\n\t\tvirtual void visit(LeafNode& n) {\n\t\t\t\/\/ TODO\n\t\t}\n\t\tFindResult result_;\n\t\tconst Point p_;\n\t};\n\tstruct RTIterator\n\t{\n\t\tbool operator==(const RTIterator& i) const {\n\t\t\tif (current_node_ == nullptr && i.current_node_ == nullptr)\n\t\t\t\treturn true;\n\t\t\treturn std::tie(current_node_, itstack_) == std::tie(i.current_node_, i.itstack_);\n\t\t}\n\t\tbool operator!=(const RTIterator& i) const { return !(*this == i); }\n\t\tRTIterator& operator++() { \n\t\t\tif (itstack_.size() > 0) {\n\t\t\t\tauto pos = itstack_.back();\n\t\t\t\t++pos;\n\t\t\t\tif (pos + 1 < current_node_->size())\n\t\t\t\t\treturn *this;\n\n\t\t\t\t\/\/ search into upwards index nodes\n\t\t\t\tINode* node = current_node_;\n\t\t\t\twhile (itstack_.size() > 0 && node != nullptr && node->size() <= pos) {\n\t\t\t\t\titstack_.pop_back();\n\t\t\t\t\tpos = ++itstack_.back();\n\t\t\t\t\tnode = node->parent();\n\t\t\t\t}\n\t\t\t\tif (itstack_.size() == 0) {\n\t\t\t\t\t\/\/ nothing found; we're at the end\n\t\t\t\t\tcurrent_node_ = nullptr;\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ search downward to leaf node\n\t\t\t\t\tsize_t depth {0};\n\t\t\t\t\tcurrent_node_ = node->first_leaf(&depth);\n\t\t\t\t\tfor(size_t i = 0; i < depth; ++i) {\n\t\t\t\t\t\titstack_.push_back(0);\n\t\t\t\t\t} \n\t\t\t\t}\n\t\t\t}\n\t\t\treturn *this; \n\t\t}\n\t\tRTree::value_type& operator*() { return current_node_->elements_[itstack_.back()]; }\n\t\t\/\/RTIterator& operator++(int) { return *this; }\n\t\t\/\/RTree* tree_ { nullptr };\n\t\tLeafNode* current_node_ { nullptr };\n\t\tstd::vector itstack_;\n\t};\n\tRTIterator begin();\n\tRTIterator end() { return RTIterator(); }\n\n\tRTIterator add(const value_type& r) {\n\t\tRTIterator it;\n\t\tAddOperation ao(r, it);\n\t\troot_->accept(ao);\n\t\treturn it;\n\t}\n\tFindResult find_containing(const Point& p) {\n\t\tFindExactOperation feo(p);\n\t\troot_->accept(feo);\n\t\treturn feo.result_;\n\t}\n\tFindResult find_nearest(const Point& p, size_t n = 1) {\n\t\t\/\/ TODO\n\t\tFindNearestOperation fno(p);\n\t\troot_->accept(fno);\n\t\treturn fno.result_;\n\t}\n\n\tstd::unique_ptr root_ = std::make_unique(nullptr);\n};\n\nint main(int argc, char const *argv[])\n{\n\tstd::vector params(argv, argv + argc);\n\tRTree rt;\n\tfor(const auto& p : params) {\n\t\tstd::cout << p << std::endl;\n\t}\n\tsize_t counter = 0;\n\trt.add(std::make_pair(Rect(Point(1, 1), Point(2, 2)), ++counter));\n\trt.add(std::make_pair(Rect(Point(1, 2), Point(2, 2)), ++counter));\n\trt.add(std::make_pair(Rect(Point(1, 3), Point(9, 2)), ++counter));\n\trt.add(std::make_pair(Rect(Point(2, 1), Point(4, 7)), ++counter));\n\trt.add(std::make_pair(Rect(Point(3, 1), Point(4, 7)), ++counter));\n\trt.add(std::make_pair(Rect(Point(4, 1), Point(7, 2)), ++counter));\n\trt.add(std::make_pair(Rect(Point(4, 4), Point(9, 8)), ++counter));\n\trt.add(std::make_pair(Rect(Point(5, 1), Point(9, 9)), ++counter));\n\trt.add(std::make_pair(Rect(Point(5, 4), Point(6, 5)), ++counter));\n\trt.add(std::make_pair(Rect(Point(6, 1), Point(6, 6)), ++counter));\n\trt.add(std::make_pair(Rect(Point(6, 6), Point(7, 7)), ++counter));\n\trt.add(std::make_pair(Rect(Point(1, 1), Point(7, 7)), ++counter));\n\trt.add(std::make_pair(Rect(Point(8, 4), Point(9, 5)), ++counter));\n\trt.add(std::make_pair(Rect(Point(2, 5), Point(4, 6)), ++counter));\n\trt.add(std::make_pair(Rect(Point(2, 6), Point(6, 7)), ++counter));\n\trt.add(std::make_pair(Rect(Point(2, 7), Point(9, 7)), ++counter));\n\trt.add(std::make_pair(Rect(Point(2, 8), Point(8, 9)), ++counter));\n\treturn 0;\n}<|endoftext|>"} {"text":"#include \"inline_widget.hxx\"\n#include \"uri\/uri_parser.hxx\"\n#include \"widget.hxx\"\n#include \"widget_http.hxx\"\n#include \"widget_resolver.hxx\"\n#include \"widget_request.hxx\"\n#include \"processor.h\"\n#include \"penv.hxx\"\n#include \"async.hxx\"\n#include \"http_response.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/istream_iconv.hxx\"\n#include \"pool.hxx\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nstruct istream *\nistream_iconv_new(gcc_unused struct pool *pool, struct istream *input,\n gcc_unused const char *tocode,\n gcc_unused const char *fromcode)\n{\n return input;\n}\n\nvoid\nwidget_cancel(struct widget *widget gcc_unused)\n{\n}\n\nbool\nwidget_check_host(const struct widget *widget gcc_unused,\n const char *host gcc_unused,\n const char *site_name gcc_unused)\n{\n return true;\n}\n\nSession *\nsession_get(gcc_unused SessionId id)\n{\n return NULL;\n}\n\nvoid\nsession_put(Session *session gcc_unused)\n{\n}\n\nvoid\nwidget_sync_session(struct widget *widget gcc_unused,\n Session *session gcc_unused)\n{\n}\n\nvoid\nwidget_http_request(gcc_unused struct pool &pool,\n gcc_unused struct widget &widget,\n gcc_unused struct processor_env &env,\n const struct http_response_handler &handler,\n void *handler_ctx,\n gcc_unused struct async_operation_ref &async_ref)\n{\n GError *error = g_error_new_literal(g_quark_from_static_string(\"test\"), 0,\n \"Test\");\n handler.InvokeAbort(handler_ctx, error);\n}\n\nstruct test_operation {\n struct async_operation operation;\n struct pool *pool;\n};\n\nstatic void\ntest_abort(struct async_operation *ao gcc_unused)\n{\n struct test_operation *to = (struct test_operation *)ao;\n\n pool_unref(to->pool);\n}\n\nstatic const struct async_operation_class test_operation = {\n .abort = test_abort,\n};\n\nvoid\nwidget_resolver_new(struct pool &pool, gcc_unused struct pool &widget_pool,\n gcc_unused struct widget &widget,\n gcc_unused struct tcache &translate_cache,\n gcc_unused widget_resolver_callback_t callback,\n gcc_unused void *ctx,\n struct async_operation_ref &async_ref)\n{\n auto to = NewFromPool(pool);\n\n to->pool = &pool;\n\n to->operation.Init(test_operation);\n async_ref.Set(to->operation);\n pool_ref(&pool);\n}\n\nstatic void\ntest_abort_resolver(struct pool *pool)\n{\n const char *uri;\n bool ret;\n struct parsed_uri parsed_uri;\n struct widget widget;\n struct processor_env env;\n struct istream *istream;\n\n pool = pool_new_linear(pool, \"test\", 4096);\n\n uri = \"\/beng.html\";\n ret = parsed_uri.Parse(uri);\n if (!ret) {\n fprintf(stderr, \"uri_parse() failed\\n\");\n exit(2);\n }\n\n widget.Init(*pool, nullptr);\n\n istream = embed_inline_widget(*pool, env, false, widget);\n pool_unref(pool);\n\n istream_close_unused(istream);\n}\n\nint main(int argc, char **argv) {\n struct pool *pool;\n\n (void)argc;\n (void)argv;\n\n pool = pool_new_libc(NULL, \"root\");\n\n test_abort_resolver(pool);\n pool_commit();\n\n pool_unref(pool);\n pool_commit();\n pool_recycler_clear();\n}\ntest\/t_wembed: add missing include#include \"inline_widget.hxx\"\n#include \"uri\/uri_parser.hxx\"\n#include \"widget.hxx\"\n#include \"widget_http.hxx\"\n#include \"widget_resolver.hxx\"\n#include \"widget_request.hxx\"\n#include \"processor.h\"\n#include \"penv.hxx\"\n#include \"async.hxx\"\n#include \"http_response.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/istream_iconv.hxx\"\n#include \"pool.hxx\"\n#include \"session.hxx\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nstruct istream *\nistream_iconv_new(gcc_unused struct pool *pool, struct istream *input,\n gcc_unused const char *tocode,\n gcc_unused const char *fromcode)\n{\n return input;\n}\n\nvoid\nwidget_cancel(struct widget *widget gcc_unused)\n{\n}\n\nbool\nwidget_check_host(const struct widget *widget gcc_unused,\n const char *host gcc_unused,\n const char *site_name gcc_unused)\n{\n return true;\n}\n\nSession *\nsession_get(gcc_unused SessionId id)\n{\n return NULL;\n}\n\nvoid\nsession_put(Session *session gcc_unused)\n{\n}\n\nvoid\nwidget_sync_session(struct widget *widget gcc_unused,\n Session *session gcc_unused)\n{\n}\n\nvoid\nwidget_http_request(gcc_unused struct pool &pool,\n gcc_unused struct widget &widget,\n gcc_unused struct processor_env &env,\n const struct http_response_handler &handler,\n void *handler_ctx,\n gcc_unused struct async_operation_ref &async_ref)\n{\n GError *error = g_error_new_literal(g_quark_from_static_string(\"test\"), 0,\n \"Test\");\n handler.InvokeAbort(handler_ctx, error);\n}\n\nstruct test_operation {\n struct async_operation operation;\n struct pool *pool;\n};\n\nstatic void\ntest_abort(struct async_operation *ao gcc_unused)\n{\n struct test_operation *to = (struct test_operation *)ao;\n\n pool_unref(to->pool);\n}\n\nstatic const struct async_operation_class test_operation = {\n .abort = test_abort,\n};\n\nvoid\nwidget_resolver_new(struct pool &pool, gcc_unused struct pool &widget_pool,\n gcc_unused struct widget &widget,\n gcc_unused struct tcache &translate_cache,\n gcc_unused widget_resolver_callback_t callback,\n gcc_unused void *ctx,\n struct async_operation_ref &async_ref)\n{\n auto to = NewFromPool(pool);\n\n to->pool = &pool;\n\n to->operation.Init(test_operation);\n async_ref.Set(to->operation);\n pool_ref(&pool);\n}\n\nstatic void\ntest_abort_resolver(struct pool *pool)\n{\n const char *uri;\n bool ret;\n struct parsed_uri parsed_uri;\n struct widget widget;\n struct processor_env env;\n struct istream *istream;\n\n pool = pool_new_linear(pool, \"test\", 4096);\n\n uri = \"\/beng.html\";\n ret = parsed_uri.Parse(uri);\n if (!ret) {\n fprintf(stderr, \"uri_parse() failed\\n\");\n exit(2);\n }\n\n widget.Init(*pool, nullptr);\n\n istream = embed_inline_widget(*pool, env, false, widget);\n pool_unref(pool);\n\n istream_close_unused(istream);\n}\n\nint main(int argc, char **argv) {\n struct pool *pool;\n\n (void)argc;\n (void)argv;\n\n pool = pool_new_libc(NULL, \"root\");\n\n test_abort_resolver(pool);\n pool_commit();\n\n pool_unref(pool);\n pool_commit();\n pool_recycler_clear();\n}\n<|endoftext|>"} {"text":"\/\/ ==========================================================================\n\/\/ lambda\n\/\/ ==========================================================================\n\/\/ Copyright (c) 2013, Hannes Hauswedell, FU Berlin\n\/\/ All rights reserved.\n\/\/\n\/\/ This file is part of Lambda.\n\/\/\n\/\/ Lambda is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ Lambda is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with Lambda. If not, see .*\/\n\/\/ ==========================================================================\n\/\/ Author: Hannes Hauswedell \n\/\/ ==========================================================================\n\/\/ holders.hpp: Data container structs\n\/\/ ==========================================================================\n\n\n#ifndef SEQAN_LAMBDA_HOLDERS_H_\n#define SEQAN_LAMBDA_HOLDERS_H_\n\n\n#include \"match.hpp\"\n#include \"options.hpp\"\n\n\/\/ ============================================================================\n\/\/ Forwards\n\/\/ ============================================================================\n\n\/\/ ============================================================================\n\/\/ Metafunctions\n\/\/ ============================================================================\n\n\/\/ ============================================================================\n\/\/ Functions\n\/\/ ============================================================================\n\n\/\/ ============================================================================\n\/\/ Tags, Classes, Enums\n\/\/ ============================================================================\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ struct StatsHolder\n\/\/ ----------------------------------------------------------------------------\n\nstruct StatsHolder\n{\n\/\/ seeding\n uint64_t hitsAfterSeeding;\n uint64_t hitsMerged;\n uint64_t hitsTooShort;\n uint64_t hitsMasked;\n\n\/\/ pre-extension\n uint64_t hitsFailedPreExtendTest;\n uint64_t hitsPutativeDuplicate;\n uint64_t hitsPutativeAbundant;\n\n\/\/ post-extension\n uint64_t hitsFailedExtendPercentIdentTest;\n uint64_t hitsFailedExtendEValueTest;\n uint64_t hitsAbundant;\n uint64_t hitsDuplicate;\n\n\/\/ final\n uint64_t hitsFinal;\n uint64_t qrysWithHit;\n\n StatsHolder()\n {\n clear();\n }\n\n void clear()\n {\n hitsAfterSeeding = 0;\n hitsMerged = 0;\n hitsTooShort = 0;\n hitsMasked = 0;\n\n hitsFailedPreExtendTest = 0;\n hitsPutativeDuplicate = 0;\n hitsPutativeAbundant = 0;\n\n hitsFailedExtendPercentIdentTest = 0;\n hitsFailedExtendEValueTest = 0;\n hitsAbundant = 0;\n hitsDuplicate = 0;\n\n hitsFinal = 0;\n qrysWithHit = 0;\n }\n\n StatsHolder plus(StatsHolder const & rhs)\n {\n hitsAfterSeeding = rhs.hitsAfterSeeding;\n hitsMerged = rhs.hitsMerged;\n hitsTooShort = rhs.hitsTooShort;\n hitsMasked = rhs.hitsMasked;\n\n hitsFailedPreExtendTest = rhs.hitsFailedPreExtendTest;\n hitsPutativeDuplicate = rhs.hitsPutativeDuplicate;\n hitsPutativeAbundant = rhs.hitsPutativeAbundant;\n\n hitsFailedExtendPercentIdentTest = rhs.hitsFailedExtendPercentIdentTest;\n hitsFailedExtendEValueTest = rhs.hitsFailedExtendEValueTest;\n hitsAbundant = rhs.hitsAbundant;\n hitsDuplicate = rhs.hitsDuplicate;\n\n hitsFinal = rhs.hitsFinal;\n qrysWithHit = rhs.qrysWithHit;\n return *this;\n }\n\n StatsHolder operator+(StatsHolder const& rhs)\n {\n StatsHolder tmp(*this);\n return tmp.plus(rhs);\n }\n\n StatsHolder operator+=(StatsHolder const& rhs)\n {\n this->plus(rhs);\n return *this;\n }\n};\n\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ struct GlobalDataHolder -- one object per program\n\/\/ ----------------------------------------------------------------------------\n\ntemplate \nclass GlobalDataHolder\n{\npublic:\n using TFormat = BlastFormat;\n\n \/\/ SEQUENCES AND THEIR TYPE \/\/\n using TTransSeqs = TCDStringSet>;\n\n using TRedAlph = RedAlph; \/\/ ensures == Dna5 for BlastN\n using TRedSeqVirt = ModifiedString, PackSpec>,\n ModView,TRedAlph>>>;\n using TRedSeqsVirt = StringSet>>;\n\n static bool constexpr\n indexIsFM = std::is_same>::value;\n static bool constexpr\n noReduction = std::is_same, TRedAlph>::value;\n\n using TRedSeqs = typename std::conditional<\n noReduction,\n TTransSeqs, \/\/ owner\n TRedSeqsVirt>::type; \/\/ modview\n using TRedSeqsACT = typename std::conditional<\n noReduction,\n TTransSeqs &, \/\/ reference to owner\n TRedSeqsVirt>::type; \/\/ modview\n\n \/\/ these are the sequences in *unreduced space*\n TTransSeqs qrySeqs;\n TTransSeqs subjSeqs;\n\n \/\/ reduced query sequences if using reduction, otherwise & = transSeqs\n TRedSeqsACT redQrySeqs = qrySeqs;\n TRedSeqsACT redSubjSeqs = subjSeqs;\n\n \/\/ INDECES AND THEIR TYPE \/\/\n using TIndexSpec = TIndexSpec_;\n using TDbIndex = Index;\n\n TDbIndex dbIndex;\n BlastDbSpecs<> dbSpecs;\n\n \/\/ TODO maybe remove these for other specs?\n using TPositions = typename StringSetLimits::Type;\n TPositions untransQrySeqLengths; \/\/ used iff qHasFrames(p)\n TPositions untransSubjSeqLengths; \/\/ used iff sHasFrames(p)\n\n using TMasking = StringSet, Owner>>;\n TMasking segIntStarts;\n TMasking segIntEnds;\n\n using TIds = StringSet>>;\n TIds qryIds;\n TIds subjIds;\n\n using TBlastScoringAdapter = BlastScoringAdapter;\n TScoreScheme scoreScheme;\n TBlastScoringAdapter blastScoringAdapter;\n\n StatsHolder stats = StatsHolder();\n};\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ struct LocalDataHolder -- one object per thread\n\/\/ ----------------------------------------------------------------------------\n\ntemplate \nclass LocalDataHolder\n{\npublic:\n using TGlobalHolder = TGlobalHolder_;\n using TFormat = typename TGlobalHolder::TFormat;\n using TRedQrySeq = typename Value::Type;\n using TSeeds = StringSet::Type>;\n using TSeedIndex = Index>;\n\n \/\/ references to global stuff\n LambdaOptions const & options;\n TGlobalHolder \/*const*\/ & gH;\n\n \/\/ this is the localHolder for the i-th part of the queries\n uint64_t i;\n\n \/\/ regarding range of queries\n uint64_t indexBeginQry;\n uint64_t indexEndQry;\n\n \/\/ regarding seedingp\n TSeeds seeds;\n TSeedIndex seedIndex;\n\/\/ std::forward_list matches;\n std::vector matches;\n std::vector seedRefs; \/\/ mapping seed -> query\n std::vector seedRanks; \/\/ mapping seed -> relative rank\n\n \/\/ regarding extension\n typedef Align<\n typename Infix<\n typename Value<\n typename TGlobalHolder::TTransSeqs>::Type>::Type,\n ArrayGaps> TAlign;\n\n typedef DPContext::Type,\n TScoreExtension> TDPContext;\n typedef AliExtContext_ TAliExtContext;\n\n TAliExtContext alignContext;\n\n\n \/\/ regarding the gathering of stats\n StatsHolder stats;\n\n \/\/ progress string\n std::stringstream statusStr;\n\n \/\/ constructor\n LocalDataHolder(LambdaOptions const & _options,\n TGlobalHolder \/*const*\/ & _globalHolder) :\n options(_options), gH(_globalHolder), stats()\n {}\n\n \/\/ copy constructor SHALLOW COPY ONLY, REQUIRED FOR firsprivate()\n LocalDataHolder(LocalDataHolder const & rhs) :\n options(rhs.options), gH(rhs.gH), stats()\n {}\n\n void init(uint64_t const _i)\n {\n i = _i;\n\n if (options.doubleIndexing)\n {\n indexBeginQry = (length(gH.qrySeqs) \/ options.queryPart) * i;\n indexEndQry = (i+1 == options.queryPart) \/\/ last interval\n ? length(gH.qrySeqs) \/\/ reach until end\n : (length(gH.qrySeqs) \/ options.queryPart) * (i+1);\n } else\n {\n indexBeginQry = qNumFrames(TFormat()) * i;\n indexEndQry = qNumFrames(TFormat()) * (i+1);\n }\n\n clear(seeds);\n clear(seedIndex);\n matches.clear();\n seedRefs.clear();\n seedRanks.clear();\n\/\/ stats.clear();\n statusStr.clear();\n statusStr.precision(2);\n }\n\n};\n\n\/\/ perform a fast local alignment score calculation on the seed and see if we\n\/\/ reach above threshold\n\/\/ WARNING the following function only works for hammingdistanced seeds\ntemplate \ninline bool\nseedLooksPromising(\n LocalDataHolder const & lH,\n TMatch const & m)\n{\n auto const & qSeq = infix(lH.gH.qrySeqs[m.qryId],\n m.qryStart,\n m.qryStart + lH.options.seedLength);\n auto const & sSeq = infix(lH.gH.subjSeqs[m.subjId],\n m.subjStart,\n m.subjStart + lH.options.seedLength);\n int maxScore = 0;\n\n int scores[lH.options.seedLength]; \/\/ C99, C++14, -Wno-vla before that\n scores[0] = 0;\n\n \/\/ score the diagonal\n for (unsigned i = 0; i < lH.options.seedLength; ++i)\n {\n scores[i] += score(lH.gH.scoreScheme, qSeq[i], sSeq[i]);\n if (scores[i] < 0)\n scores[i] = 0;\n else if (scores[i] >= maxScore)\n maxScore = scores[i];\n\n if (i < static_cast(lH.options.seedLength - 1))\n scores[i+1] = scores[i];\n }\n\n return (maxScore >= lH.options.minSeedScore);\n}\n\ntemplate \ninline void\nonFindImpl(LocalDataHolder & lH,\n TSeedId const & seedId,\n TSubjOcc subjOcc)\n{\n if (TGlobalHolder::indexIsFM) \/\/ positions are reversed\n setSeqOffset(subjOcc,\n length(lH.gH.subjSeqs[getSeqNo(subjOcc)])\n - getSeqOffset(subjOcc)\n - lH.options.seedLength);\n\n Match m {static_cast(lH.seedRefs[seedId]),\n static_cast(getSeqNo(subjOcc)),\n static_cast(lH.seedRanks[seedId] * lH.options.seedOffset),\n static_cast(getSeqOffset(subjOcc))};\n\n bool discarded = false;\n auto const halfSubjL = lH.options.seedLength \/ 2;\n\n for (unsigned k = 0; k < length(lH.gH.segIntStarts[m.subjId]); ++k)\n {\n \/\/ more than half of the seed falls into masked interval\n if (intervalOverlap(m.subjStart,\n m.subjStart + lH.options.seedLength,\n lH.gH.segIntStarts[m.subjId][k],\n lH.gH.segIntEnds[m.subjId][k])\n >= halfSubjL)\n {\n ++lH.stats.hitsMasked;\n discarded = true;\n break;\n }\n }\n\n if ((!TGlobalHolder::noReduction) && (!discarded) &&\n (!seedLooksPromising(lH, m)))\n {\n discarded = true;\n ++lH.stats.hitsFailedPreExtendTest;\n }\n\n if (!discarded)\n lH.matches.emplace_back(m);\n}\n\ntemplate \ninline void\nonFindDoubleIndex(LocalDataHolder & lH,\n TFinder const & finder)\n{\n auto qryOccs = getOccurrences(back(finder.patternStack));\n auto subjOccs = getOccurrences(back(finder.textStack));\n\n lH.stats.hitsAfterSeeding += length(qryOccs) * length(subjOccs);\n\n for (unsigned i = 0; i < length(qryOccs); ++i)\n for (unsigned j = 0; j < length(subjOccs); ++j)\n onFindImpl(lH, getSeqNo(qryOccs[i]), subjOccs[j]);\n}\n\ntemplate \ninline void\nonFindSingleIndex(LocalDataHolder & lH,\n TSeedListIterator const & seedIt,\n TIndexIterator const & indexIt)\n{\n auto qryOcc = position(seedIt);\n auto subjOccs = getOccurrences(indexIt);\n\n lH.stats.hitsAfterSeeding += length(subjOccs);\n\n for (unsigned j = 0; j < length(subjOccs); ++j)\n onFindImpl(lH, qryOcc, subjOccs[j]);\n}\n\n#endif \/\/ SEQAN_LAMBDA_HOLDERS_H_\n[fix] plus operator had = instead of +=\/\/ ==========================================================================\n\/\/ lambda\n\/\/ ==========================================================================\n\/\/ Copyright (c) 2013, Hannes Hauswedell, FU Berlin\n\/\/ All rights reserved.\n\/\/\n\/\/ This file is part of Lambda.\n\/\/\n\/\/ Lambda is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ Lambda is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with Lambda. If not, see .*\/\n\/\/ ==========================================================================\n\/\/ Author: Hannes Hauswedell \n\/\/ ==========================================================================\n\/\/ holders.hpp: Data container structs\n\/\/ ==========================================================================\n\n\n#ifndef SEQAN_LAMBDA_HOLDERS_H_\n#define SEQAN_LAMBDA_HOLDERS_H_\n\n\n#include \"match.hpp\"\n#include \"options.hpp\"\n\n\/\/ ============================================================================\n\/\/ Forwards\n\/\/ ============================================================================\n\n\/\/ ============================================================================\n\/\/ Metafunctions\n\/\/ ============================================================================\n\n\/\/ ============================================================================\n\/\/ Functions\n\/\/ ============================================================================\n\n\/\/ ============================================================================\n\/\/ Tags, Classes, Enums\n\/\/ ============================================================================\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ struct StatsHolder\n\/\/ ----------------------------------------------------------------------------\n\nstruct StatsHolder\n{\n\/\/ seeding\n uint64_t hitsAfterSeeding;\n uint64_t hitsMerged;\n uint64_t hitsTooShort;\n uint64_t hitsMasked;\n\n\/\/ pre-extension\n uint64_t hitsFailedPreExtendTest;\n uint64_t hitsPutativeDuplicate;\n uint64_t hitsPutativeAbundant;\n\n\/\/ post-extension\n uint64_t hitsFailedExtendPercentIdentTest;\n uint64_t hitsFailedExtendEValueTest;\n uint64_t hitsAbundant;\n uint64_t hitsDuplicate;\n\n\/\/ final\n uint64_t hitsFinal;\n uint64_t qrysWithHit;\n\n StatsHolder()\n {\n clear();\n }\n\n void clear()\n {\n hitsAfterSeeding = 0;\n hitsMerged = 0;\n hitsTooShort = 0;\n hitsMasked = 0;\n\n hitsFailedPreExtendTest = 0;\n hitsPutativeDuplicate = 0;\n hitsPutativeAbundant = 0;\n\n hitsFailedExtendPercentIdentTest = 0;\n hitsFailedExtendEValueTest = 0;\n hitsAbundant = 0;\n hitsDuplicate = 0;\n\n hitsFinal = 0;\n qrysWithHit = 0;\n }\n\n StatsHolder plus(StatsHolder const & rhs)\n {\n hitsAfterSeeding += rhs.hitsAfterSeeding;\n hitsMerged += rhs.hitsMerged;\n hitsTooShort += rhs.hitsTooShort;\n hitsMasked += rhs.hitsMasked;\n\n hitsFailedPreExtendTest += rhs.hitsFailedPreExtendTest;\n hitsPutativeDuplicate += rhs.hitsPutativeDuplicate;\n hitsPutativeAbundant += rhs.hitsPutativeAbundant;\n\n hitsFailedExtendPercentIdentTest += rhs.hitsFailedExtendPercentIdentTest;\n hitsFailedExtendEValueTest += rhs.hitsFailedExtendEValueTest;\n hitsAbundant += rhs.hitsAbundant;\n hitsDuplicate += rhs.hitsDuplicate;\n\n hitsFinal += rhs.hitsFinal;\n qrysWithHit += rhs.qrysWithHit;\n return *this;\n }\n\n StatsHolder operator+(StatsHolder const& rhs)\n {\n StatsHolder tmp(*this);\n return tmp.plus(rhs);\n }\n\n StatsHolder operator+=(StatsHolder const& rhs)\n {\n this->plus(rhs);\n return *this;\n }\n};\n\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ struct GlobalDataHolder -- one object per program\n\/\/ ----------------------------------------------------------------------------\n\ntemplate \nclass GlobalDataHolder\n{\npublic:\n using TFormat = BlastFormat;\n\n \/\/ SEQUENCES AND THEIR TYPE \/\/\n using TTransSeqs = TCDStringSet>;\n\n using TRedAlph = RedAlph; \/\/ ensures == Dna5 for BlastN\n using TRedSeqVirt = ModifiedString, PackSpec>,\n ModView,TRedAlph>>>;\n using TRedSeqsVirt = StringSet>>;\n\n static bool constexpr\n indexIsFM = std::is_same>::value;\n static bool constexpr\n noReduction = std::is_same, TRedAlph>::value;\n\n using TRedSeqs = typename std::conditional<\n noReduction,\n TTransSeqs, \/\/ owner\n TRedSeqsVirt>::type; \/\/ modview\n using TRedSeqsACT = typename std::conditional<\n noReduction,\n TTransSeqs &, \/\/ reference to owner\n TRedSeqsVirt>::type; \/\/ modview\n\n \/\/ these are the sequences in *unreduced space*\n TTransSeqs qrySeqs;\n TTransSeqs subjSeqs;\n\n \/\/ reduced query sequences if using reduction, otherwise & = transSeqs\n TRedSeqsACT redQrySeqs = qrySeqs;\n TRedSeqsACT redSubjSeqs = subjSeqs;\n\n \/\/ INDECES AND THEIR TYPE \/\/\n using TIndexSpec = TIndexSpec_;\n using TDbIndex = Index;\n\n TDbIndex dbIndex;\n BlastDbSpecs<> dbSpecs;\n\n \/\/ TODO maybe remove these for other specs?\n using TPositions = typename StringSetLimits::Type;\n TPositions untransQrySeqLengths; \/\/ used iff qHasFrames(p)\n TPositions untransSubjSeqLengths; \/\/ used iff sHasFrames(p)\n\n using TMasking = StringSet, Owner>>;\n TMasking segIntStarts;\n TMasking segIntEnds;\n\n using TIds = StringSet>>;\n TIds qryIds;\n TIds subjIds;\n\n using TBlastScoringAdapter = BlastScoringAdapter;\n TScoreScheme scoreScheme;\n TBlastScoringAdapter blastScoringAdapter;\n\n StatsHolder stats = StatsHolder();\n};\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ struct LocalDataHolder -- one object per thread\n\/\/ ----------------------------------------------------------------------------\n\ntemplate \nclass LocalDataHolder\n{\npublic:\n using TGlobalHolder = TGlobalHolder_;\n using TFormat = typename TGlobalHolder::TFormat;\n using TRedQrySeq = typename Value::Type;\n using TSeeds = StringSet::Type>;\n using TSeedIndex = Index>;\n\n \/\/ references to global stuff\n LambdaOptions const & options;\n TGlobalHolder \/*const*\/ & gH;\n\n \/\/ this is the localHolder for the i-th part of the queries\n uint64_t i;\n\n \/\/ regarding range of queries\n uint64_t indexBeginQry;\n uint64_t indexEndQry;\n\n \/\/ regarding seedingp\n TSeeds seeds;\n TSeedIndex seedIndex;\n\/\/ std::forward_list matches;\n std::vector matches;\n std::vector seedRefs; \/\/ mapping seed -> query\n std::vector seedRanks; \/\/ mapping seed -> relative rank\n\n \/\/ regarding extension\n typedef Align<\n typename Infix<\n typename Value<\n typename TGlobalHolder::TTransSeqs>::Type>::Type,\n ArrayGaps> TAlign;\n\n typedef DPContext::Type,\n TScoreExtension> TDPContext;\n typedef AliExtContext_ TAliExtContext;\n\n TAliExtContext alignContext;\n\n\n \/\/ regarding the gathering of stats\n StatsHolder stats;\n\n \/\/ progress string\n std::stringstream statusStr;\n\n \/\/ constructor\n LocalDataHolder(LambdaOptions const & _options,\n TGlobalHolder \/*const*\/ & _globalHolder) :\n options(_options), gH(_globalHolder), stats()\n {}\n\n \/\/ copy constructor SHALLOW COPY ONLY, REQUIRED FOR firsprivate()\n LocalDataHolder(LocalDataHolder const & rhs) :\n options(rhs.options), gH(rhs.gH), stats()\n {}\n\n void init(uint64_t const _i)\n {\n i = _i;\n\n if (options.doubleIndexing)\n {\n indexBeginQry = (length(gH.qrySeqs) \/ options.queryPart) * i;\n indexEndQry = (i+1 == options.queryPart) \/\/ last interval\n ? length(gH.qrySeqs) \/\/ reach until end\n : (length(gH.qrySeqs) \/ options.queryPart) * (i+1);\n } else\n {\n indexBeginQry = qNumFrames(TFormat()) * i;\n indexEndQry = qNumFrames(TFormat()) * (i+1);\n }\n\n clear(seeds);\n clear(seedIndex);\n matches.clear();\n seedRefs.clear();\n seedRanks.clear();\n\/\/ stats.clear();\n statusStr.clear();\n statusStr.precision(2);\n }\n\n};\n\n\/\/ perform a fast local alignment score calculation on the seed and see if we\n\/\/ reach above threshold\n\/\/ WARNING the following function only works for hammingdistanced seeds\ntemplate \ninline bool\nseedLooksPromising(\n LocalDataHolder const & lH,\n TMatch const & m)\n{\n auto const & qSeq = infix(lH.gH.qrySeqs[m.qryId],\n m.qryStart,\n m.qryStart + lH.options.seedLength);\n auto const & sSeq = infix(lH.gH.subjSeqs[m.subjId],\n m.subjStart,\n m.subjStart + lH.options.seedLength);\n int maxScore = 0;\n\n int scores[lH.options.seedLength]; \/\/ C99, C++14, -Wno-vla before that\n scores[0] = 0;\n\n \/\/ score the diagonal\n for (unsigned i = 0; i < lH.options.seedLength; ++i)\n {\n scores[i] += score(lH.gH.scoreScheme, qSeq[i], sSeq[i]);\n if (scores[i] < 0)\n scores[i] = 0;\n else if (scores[i] >= maxScore)\n maxScore = scores[i];\n\n if (i < static_cast(lH.options.seedLength - 1))\n scores[i+1] = scores[i];\n }\n\n return (maxScore >= lH.options.minSeedScore);\n}\n\ntemplate \ninline void\nonFindImpl(LocalDataHolder & lH,\n TSeedId const & seedId,\n TSubjOcc subjOcc)\n{\n if (TGlobalHolder::indexIsFM) \/\/ positions are reversed\n setSeqOffset(subjOcc,\n length(lH.gH.subjSeqs[getSeqNo(subjOcc)])\n - getSeqOffset(subjOcc)\n - lH.options.seedLength);\n\n Match m {static_cast(lH.seedRefs[seedId]),\n static_cast(getSeqNo(subjOcc)),\n static_cast(lH.seedRanks[seedId] * lH.options.seedOffset),\n static_cast(getSeqOffset(subjOcc))};\n\n bool discarded = false;\n auto const halfSubjL = lH.options.seedLength \/ 2;\n\n for (unsigned k = 0; k < length(lH.gH.segIntStarts[m.subjId]); ++k)\n {\n \/\/ more than half of the seed falls into masked interval\n if (intervalOverlap(m.subjStart,\n m.subjStart + lH.options.seedLength,\n lH.gH.segIntStarts[m.subjId][k],\n lH.gH.segIntEnds[m.subjId][k])\n >= halfSubjL)\n {\n ++lH.stats.hitsMasked;\n discarded = true;\n break;\n }\n }\n\n if ((!TGlobalHolder::noReduction) && (!discarded) &&\n (!seedLooksPromising(lH, m)))\n {\n discarded = true;\n ++lH.stats.hitsFailedPreExtendTest;\n }\n\n if (!discarded)\n lH.matches.emplace_back(m);\n}\n\ntemplate \ninline void\nonFindDoubleIndex(LocalDataHolder & lH,\n TFinder const & finder)\n{\n auto qryOccs = getOccurrences(back(finder.patternStack));\n auto subjOccs = getOccurrences(back(finder.textStack));\n\n lH.stats.hitsAfterSeeding += length(qryOccs) * length(subjOccs);\n\n for (unsigned i = 0; i < length(qryOccs); ++i)\n for (unsigned j = 0; j < length(subjOccs); ++j)\n onFindImpl(lH, getSeqNo(qryOccs[i]), subjOccs[j]);\n}\n\ntemplate \ninline void\nonFindSingleIndex(LocalDataHolder & lH,\n TSeedListIterator const & seedIt,\n TIndexIterator const & indexIt)\n{\n auto qryOcc = position(seedIt);\n auto subjOccs = getOccurrences(indexIt);\n\n lH.stats.hitsAfterSeeding += length(subjOccs);\n\n for (unsigned j = 0; j < length(subjOccs); ++j)\n onFindImpl(lH, qryOcc, subjOccs[j]);\n}\n\n#endif \/\/ SEQAN_LAMBDA_HOLDERS_H_\n<|endoftext|>"} {"text":"\/\/ Copyright 2008 Paul Hodge\n\n#include \"circa.h\"\n\nnamespace circa {\nnamespace assert_function {\n\n void evaluate(Term* caller)\n {\n if (!as_bool(caller->input(0))) {\n error_occured(caller, \"Assert failed\");\n }\n }\n\n void setup(Branch& kernel)\n {\n \/*Term* main_func = *\/import_c_function(kernel, evaluate,\n \"function assert(bool)\");\n }\n}\n}\nMinor\/\/ Copyright 2008 Paul Hodge\n\n#include \"circa.h\"\n\nnamespace circa {\nnamespace assert_function {\n\n void evaluate(Term* caller)\n {\n if (!as_bool(caller->input(0))) {\n error_occured(caller, \"Assert failed\");\n }\n }\n\n void setup(Branch& kernel)\n {\n Term* main_func = import_c_function(kernel, evaluate,\n \"function assert(bool)\");\n as_function(main_func).pureFunction = false;\n }\n}\n}\n<|endoftext|>"} {"text":"#ifndef BOOKMARK_HH\n#define BOOKMARK_HH\n\n#include \n#include \n\nstruct Duplication;\nclass Options;\n\nclass Bookmark\n{\n struct FileRecord\n {\n FileRecord(const std::string& n, int i): fileName(n), endIx(i) {}\n std::string fileName;\n int endIx; \/\/ Position right after the final char of the file.\n };\n\npublic:\n Bookmark(int i = 0, const char* p = 0): original(i), processed(p) {}\n\n \/**\n * Reports one instance of duplication and optionally prints the duplicated\n * string.\n *\/\n void report(const Duplication& duplication,\n int instanceNr,\n const Options& options) const;\n\n void clear() { this->processed = 0; }\n\n bool isCleared() const { return this->processed == 0; }\n\n bool operator<(const Bookmark& another) const; \/\/ Used in sorting.\n\n int nrOfSame(Bookmark b) const;\n\n \/**\n * Used for optimization purposes. By comparing strings backwards we can\n * find out quickly if the two strings are not equal in the given number of\n * characters and move on to the next comparison.\n *\/\n bool sameAs(Bookmark b, int nrOfCharacters, const char* end) const;\n\n static int getTotalNrOfLines() { return totalNrOfLines; }\n\n static void addFile(const std::string& fileName);\n\n static size_t totalLength() { return totalString.length(); }\n\n static const char& getChar(int i) { return totalString[i]; }\n\nprivate:\n friend std::ostream& operator<<(std::ostream& os, const Bookmark& b);\n friend class BookmarkContainer;\n\n enum DetailType { PRINT_LINES, COUNT_LINES };\n\n int\n details(int processedLength, DetailType detailType, bool wordMode) const;\n\n static int lineNr(int offset, int index);\n\n static int totalNrOfLines;\n static std::vector fileRecords;\n static std::string totalString;\n\n int original;\n const char* processed;\n};\n\n#endif\nAdd comments#ifndef BOOKMARK_HH\n#define BOOKMARK_HH\n\n#include \n#include \n\nstruct Duplication;\nclass Options;\n\n\/**\n * A bookmark is something that points at a position in the processed\n * text while also keeping track of the corresponding position in the\n * file where the text originally came from.\n *\/\nclass Bookmark\n{\n struct FileRecord\n {\n FileRecord(const std::string& n, int i): fileName(n), endIx(i) {}\n std::string fileName;\n int endIx; \/\/ Position right after the final char of the file.\n };\n\npublic:\n Bookmark(int i = 0, const char* p = 0): original(i), processed(p) {}\n\n \/**\n * Reports one instance of duplication and optionally prints the duplicated\n * string.\n *\/\n void report(const Duplication& duplication,\n int instanceNr,\n const Options& options) const;\n\n \/**\n * Clear the bookmark, i.e. mark it for deletion.\n *\/\n void clear() { this->processed = 0; }\n\n bool isCleared() const { return this->processed == 0; }\n\n bool operator<(const Bookmark& another) const; \/\/ Used in sorting.\n\n \/**\n * How many characters are equal when comparing the bookmark to\n * another bookmark?\n *\/\n int nrOfSame(Bookmark b) const;\n\n \/**\n * Used for optimization purposes. By comparing strings backwards we can\n * find out quickly if the two strings are not equal in the given number of\n * characters and move on to the next comparison.\n *\/\n bool sameAs(Bookmark b, int nrOfCharacters, const char* end) const;\n\n static int getTotalNrOfLines() { return totalNrOfLines; }\n\n static void addFile(const std::string& fileName);\n\n static size_t totalLength() { return totalString.length(); }\n\n static const char& getChar(int i) { return totalString[i]; }\n\nprivate:\n friend std::ostream& operator<<(std::ostream& os, const Bookmark& b);\n friend class BookmarkContainer;\n\n enum DetailType { PRINT_LINES, COUNT_LINES };\n\n int\n details(int processedLength, DetailType detailType, bool wordMode) const;\n\n static int lineNr(int offset, int index);\n\n static int totalNrOfLines;\n static std::vector fileRecords;\n static std::string totalString;\n\n int original;\n const char* processed;\n};\n\n#endif\n<|endoftext|>"} {"text":" \n\/* ========================================\n\n * File Name : 10.cpp\n\n * Creation Date : 24-07-2020\n\n * Last Modified : Pá 24. července 2020, 21:15:59\n\n * Created By : Karel Ha \n\n * URL : https:\/\/www.facebook.com\/codingcompetitions\/hacker-cup\/2020\/qualification-round\/problems\/A\n\n * Points Gained (in case of online contest) :\n\n ==========================================*\/\n\n#include \n\nusing namespace std;\n\n#define REP(I,N) FOR(I,0,N)\n#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))\n#define ALL(A) (A).begin(), (A).end()\n#define MSG(a) cout << #a << \" == \" << (a) << endl;\n\nconst int CLEAN = -1;\n\ntemplate \nstring NumberToString ( T Number ) {\n ostringstream ss;\n ss << Number;\n return ss.str();\n}\n\n#define ERR(args...) { vector _v = split(#args, ','); err(_v.begin(), args); }\nvector split(const string& s, char c) {\n vector v;\n stringstream ss(s);\n string x;\n while (getline(ss, x, c))\n v.emplace_back(x);\n return move(v);\n}\nvoid err(vector::iterator it) {}\ntemplate\nvoid err(vector::iterator it, T a, Args... args) {\n cout << it -> substr((*it)[0] == ' ', it -> length()) << \" = \" << a << endl;\n err(++it, args...);\n}\n\nconst char default_char = 'N';\n\nvector> get_result(int N, string I, string O) {\n vector> reachability(N, vector(N, default_char));\n REP(d,N) reachability[d][d] = 'Y';\n\n REP(d,N-1) {\n REP(i, N) REP(j, N) {\n if (reachability[i][j] == 'N' || O[j] == 'N') {\n continue;\n }\n\n int neigh;\n for (auto & delta: {-1, 1}) {\n\/\/ MSG(delta)\n neigh = j + delta;\n\n if (0 <= neigh && neigh < N && I[neigh] == 'Y') {\n reachability[i][neigh] = 'Y';\n }\n }\n }\n }\n\n return reachability;\n}\n\nint main() {\n int T;\n cin >> T;\n\/\/ MSG(T)\n\n REP(i,T) {\n int N;\n cin >> N;\n\/\/ MSG(N)\n\n string I, O;\n cin >> I;\n cin >> O;\n\/\/ MSG(I) MSG(O)\n\n cout << \"Case #\" << i + 1 << \":\" << endl;\n vector> result = get_result(N, I, O);\n REP(r,N) {\n REP(c,N) {\n cout << result[r][c];\n }\n cout << endl;\n }\n\n }\n return 0;\n}\nAdd extra space after \"Case #i:\" \n\/* ========================================\n\n * File Name : 10.cpp\n\n * Creation Date : 24-07-2020\n\n * Last Modified : Pá 24. července 2020, 21:15:59\n\n * Created By : Karel Ha \n\n * URL : https:\/\/www.facebook.com\/codingcompetitions\/hacker-cup\/2020\/qualification-round\/problems\/A\n\n * Points Gained (in case of online contest) :\n\n ==========================================*\/\n\n#include \n\nusing namespace std;\n\n#define REP(I,N) FOR(I,0,N)\n#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))\n#define ALL(A) (A).begin(), (A).end()\n#define MSG(a) cout << #a << \" == \" << (a) << endl;\n\nconst int CLEAN = -1;\n\ntemplate \nstring NumberToString ( T Number ) {\n ostringstream ss;\n ss << Number;\n return ss.str();\n}\n\n#define ERR(args...) { vector _v = split(#args, ','); err(_v.begin(), args); }\nvector split(const string& s, char c) {\n vector v;\n stringstream ss(s);\n string x;\n while (getline(ss, x, c))\n v.emplace_back(x);\n return move(v);\n}\nvoid err(vector::iterator it) {}\ntemplate\nvoid err(vector::iterator it, T a, Args... args) {\n cout << it -> substr((*it)[0] == ' ', it -> length()) << \" = \" << a << endl;\n err(++it, args...);\n}\n\nconst char default_char = 'N';\n\nvector> get_result(int N, string I, string O) {\n vector> reachability(N, vector(N, default_char));\n REP(d,N) reachability[d][d] = 'Y';\n\n REP(d,N-1) {\n REP(i, N) REP(j, N) {\n if (reachability[i][j] == 'N' || O[j] == 'N') {\n continue;\n }\n\n int neigh;\n for (auto & delta: {-1, 1}) {\n\/\/ MSG(delta)\n neigh = j + delta;\n\n if (0 <= neigh && neigh < N && I[neigh] == 'Y') {\n reachability[i][neigh] = 'Y';\n }\n }\n }\n }\n\n return reachability;\n}\n\nint main() {\n int T;\n cin >> T;\n\/\/ MSG(T)\n\n REP(i,T) {\n int N;\n cin >> N;\n\/\/ MSG(N)\n\n string I, O;\n cin >> I;\n cin >> O;\n\/\/ MSG(I) MSG(O)\n\n cout << \"Case #\" << i + 1 << \": \" << endl;\n vector> result = get_result(N, I, O);\n REP(r,N) {\n REP(c,N) {\n cout << result[r][c];\n }\n cout << endl;\n }\n\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/***************************************************************************\r\n * Copyright (c) 2002 Juergen Riegel *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n#ifndef _PreComp_\r\n# include \r\n# include \r\n# include \r\n#endif\r\n\r\n#include \r\n\r\n\/\/\/ Here the FreeCAD includes sorted by Base,App,Gui......\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"PropertyView.h\"\r\n#include \"Application.h\"\r\n#include \"Document.h\"\r\n#include \"BitmapFactory.h\"\r\n#include \"ViewProvider.h\"\r\n\r\n#include \"propertyeditor\/PropertyEditor.h\"\r\n\r\nusing namespace std;\r\nusing namespace Gui;\r\nusing namespace Gui::DockWnd;\r\nusing namespace Gui::PropertyEditor;\r\n\r\n\r\n\/* TRANSLATOR Gui::PropertyView *\/\r\n\r\n\/*! Property Editor Widget\r\n *\r\n * Provides two Gui::PropertyEditor::PropertyEditor widgets, for \"View\" and \"Data\",\r\n * in two tabs.\r\n *\/\r\nPropertyView::PropertyView(QWidget *parent)\r\n : QWidget(parent)\r\n{\r\n QGridLayout* pLayout = new QGridLayout( this ); \r\n pLayout->setSpacing(0);\r\n pLayout->setMargin (0);\r\n\r\n tabs = new QTabWidget (this);\r\n tabs->setObjectName(QString::fromUtf8(\"propertyTab\"));\r\n tabs->setTabPosition(QTabWidget::South);\r\n#if defined(Q_OS_WIN32)\r\n tabs->setTabShape(QTabWidget::Triangular);\r\n#endif\r\n pLayout->addWidget(tabs, 0, 0);\r\n\r\n propertyEditorView = new Gui::PropertyEditor::PropertyEditor();\r\n propertyEditorView->setAutomaticDocumentUpdate(false);\r\n tabs->addTab(propertyEditorView, tr(\"View\"));\r\n\r\n propertyEditorData = new Gui::PropertyEditor::PropertyEditor();\r\n propertyEditorData->setAutomaticDocumentUpdate(true);\r\n tabs->addTab(propertyEditorData, tr(\"Data\"));\r\n\r\n ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter().\r\n GetGroup(\"BaseApp\")->GetGroup(\"Preferences\")->GetGroup(\"PropertyView\");\r\n if ( hGrp ) {\r\n int preferredTab = hGrp->GetInt(\"LastTabIndex\", 1);\r\n\r\n if ( preferredTab > 0 && preferredTab < tabs->count() )\r\n tabs->setCurrentIndex(preferredTab);\r\n }\r\n\r\n \/\/ connect after adding all tabs, so adding doesn't thrash the parameter\r\n connect(tabs, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int)));\r\n\r\n this->connectPropData =\r\n App::GetApplication().signalChangedObject.connect(boost::bind\r\n (&PropertyView::slotChangePropertyData, this, _1, _2));\r\n this->connectPropView =\r\n Gui::Application::Instance->signalChangedObject.connect(boost::bind\r\n (&PropertyView::slotChangePropertyView, this, _1, _2));\r\n this->connectPropAppend =\r\n App::GetApplication().signalAppendDynamicProperty.connect(boost::bind\r\n (&PropertyView::slotAppendDynamicProperty, this, _1));\r\n this->connectPropRemove =\r\n App::GetApplication().signalRemoveDynamicProperty.connect(boost::bind\r\n (&PropertyView::slotRemoveDynamicProperty, this, _1));\r\n this->connectPropChange =\r\n App::GetApplication().signalChangePropertyEditor.connect(boost::bind\r\n (&PropertyView::slotChangePropertyEditor, this, _1));\r\n this->connectActiveDoc =\r\n Application::Instance->signalActiveDocument.connect(boost::bind\r\n (&PropertyView::slotActiveDocument, this, _1));\r\n}\r\n\r\nPropertyView::~PropertyView()\r\n{\r\n this->connectPropData.disconnect();\r\n this->connectPropView.disconnect();\r\n this->connectPropAppend.disconnect();\r\n this->connectPropRemove.disconnect();\r\n this->connectPropChange.disconnect();\r\n this->connectActiveDoc.disconnect();\r\n}\r\n\r\nvoid PropertyView::slotChangePropertyData(const App::DocumentObject&, const App::Property& prop)\r\n{\r\n propertyEditorData->updateProperty(prop);\r\n}\r\n\r\nvoid PropertyView::slotChangePropertyView(const Gui::ViewProvider&, const App::Property& prop)\r\n{\r\n propertyEditorView->updateProperty(prop);\r\n}\r\n\r\nvoid PropertyView::slotAppendDynamicProperty(const App::Property& prop)\r\n{\r\n App::PropertyContainer* parent = prop.getContainer();\r\n if (parent->isHidden(&prop))\r\n return;\r\n\r\n if (parent->isDerivedFrom(App::DocumentObject::getClassTypeId())) {\r\n propertyEditorData->appendProperty(prop);\r\n }\r\n else if (parent->isDerivedFrom(Gui::ViewProvider::getClassTypeId())) {\r\n propertyEditorView->appendProperty(prop);\r\n }\r\n}\r\n\r\nvoid PropertyView::slotRemoveDynamicProperty(const App::Property& prop)\r\n{\r\n App::PropertyContainer* parent = prop.getContainer();\r\n if (parent && parent->isDerivedFrom(App::DocumentObject::getClassTypeId())) {\r\n propertyEditorData->removeProperty(prop);\r\n }\r\n else if (parent && parent->isDerivedFrom(Gui::ViewProvider::getClassTypeId())) {\r\n propertyEditorView->removeProperty(prop);\r\n }\r\n}\r\n\r\nvoid PropertyView::slotChangePropertyEditor(const App::Property& prop)\r\n{\r\n App::PropertyContainer* parent = prop.getContainer();\r\n if (parent && parent->isDerivedFrom(App::DocumentObject::getClassTypeId())) {\r\n propertyEditorData->updateEditorMode(prop);\r\n }\r\n else if (parent && parent->isDerivedFrom(Gui::ViewProvider::getClassTypeId())) {\r\n propertyEditorView->updateEditorMode(prop);\r\n }\r\n}\r\n\r\nvoid PropertyView::slotActiveDocument(const Gui::Document &doc)\r\n{\r\n bool enableEditor = false;\r\n\r\n \/\/ check if at least one selected object is part of the active document\r\n std::vector array = Gui::Selection().getCompleteSelection();\r\n for (std::vector::const_iterator it = array.begin(); it != array.end(); ++it) {\r\n if (Gui::Application::Instance->getDocument(it->pDoc) == &doc) {\r\n enableEditor = true;\r\n break;\r\n }\r\n }\r\n setEnabled(enableEditor || array.empty());\r\n}\r\n\r\nstruct PropertyView::PropInfo\r\n{\r\n std::string propName;\r\n int propId;\r\n std::vector propList;\r\n};\r\n\r\nstruct PropertyView::PropFind {\r\n const PropInfo& item;\r\n PropFind(const PropInfo& item) : item(item) {}\r\n bool operator () (const PropInfo& elem) const\r\n {\r\n return (elem.propId == item.propId) &&\r\n (elem.propName == item.propName);\r\n }\r\n};\r\n\r\nvoid PropertyView::onSelectionChanged(const SelectionChanges& msg)\r\n{\r\n if (msg.Type != SelectionChanges::AddSelection &&\r\n msg.Type != SelectionChanges::RmvSelection &&\r\n msg.Type != SelectionChanges::SetSelection &&\r\n msg.Type != SelectionChanges::ClrSelection)\r\n return;\r\n\r\n bool enableEditor = false;\r\n Gui::Document *activeDoc = Application::Instance->activeDocument();\r\n\r\n \/\/ group the properties by \r\n std::vector propDataMap;\r\n std::vector propViewMap;\r\n std::vector array = Gui::Selection().getCompleteSelection();\r\n for (std::vector::const_iterator it = array.begin(); it != array.end(); ++it) {\r\n App::DocumentObject *ob=0;\r\n ViewProvider *vp=0;\r\n\r\n std::vector dataList;\r\n std::map viewList;\r\n if ((*it).pObject) {\r\n (*it).pObject->getPropertyList(dataList);\r\n ob = (*it).pObject;\r\n\r\n \/\/ get also the properties of the associated view provider\r\n Gui::Document* doc = Gui::Application::Instance->getDocument(it->pDoc);\r\n vp = doc->getViewProvider((*it).pObject);\r\n if(!vp) continue;\r\n \/\/ get the properties as map here because it doesn't matter to have them sorted alphabetically\r\n vp->getPropertyMap(viewList);\r\n if (activeDoc == doc) {\r\n enableEditor = true;\r\n }\r\n }\r\n\r\n \/\/ store the properties with as key in a map\r\n std::vector::iterator pt;\r\n if (ob) {\r\n for (pt = dataList.begin(); pt != dataList.end(); ++pt) {\r\n PropInfo nameType;\r\n nameType.propName = ob->getPropertyName(*pt);\r\n nameType.propId = (*pt)->getTypeId().getKey();\r\n\r\n if (!ob->isHidden(*pt)) {\r\n std::vector::iterator pi = std::find_if(propDataMap.begin(), propDataMap.end(), PropFind(nameType));\r\n if (pi != propDataMap.end()) {\r\n pi->propList.push_back(*pt);\r\n }\r\n else {\r\n nameType.propList.push_back(*pt);\r\n propDataMap.push_back(nameType);\r\n }\r\n }\r\n }\r\n }\r\n \/\/ the same for the view properties\r\n if (vp) {\r\n std::map::iterator pt;\r\n for (pt = viewList.begin(); pt != viewList.end(); ++pt) {\r\n PropInfo nameType;\r\n nameType.propName = pt->first;\r\n nameType.propId = pt->second->getTypeId().getKey();\r\n\r\n if (!vp->isHidden(pt->second)) {\r\n std::vector::iterator pi = std::find_if(propViewMap.begin(), propViewMap.end(), PropFind(nameType));\r\n if (pi != propViewMap.end()) {\r\n pi->propList.push_back(pt->second);\r\n }\r\n else {\r\n nameType.propList.push_back(pt->second);\r\n propViewMap.push_back(nameType);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n \/\/ the property must be part of each selected object, i.e. the number\r\n \/\/ of selected objects is equal to the number of properties with same\r\n \/\/ name and id\r\n std::vector::const_iterator it;\r\n PropertyModel::PropertyList dataProps;\r\n for (it = propDataMap.begin(); it != propDataMap.end(); ++it) {\r\n if (it->propList.size() == array.size()) {\r\n dataProps.push_back(std::make_pair(it->propName, it->propList));\r\n }\r\n }\r\n propertyEditorData->buildUp(dataProps);\r\n\r\n PropertyModel::PropertyList viewProps;\r\n for (it = propViewMap.begin(); it != propViewMap.end(); ++it) {\r\n if (it->propList.size() == array.size()) {\r\n viewProps.push_back(std::make_pair(it->propName, it->propList));\r\n }\r\n }\r\n propertyEditorView->buildUp(viewProps);\r\n\r\n \/\/ make sure the editors are enabled\/disabled properly\r\n setEnabled(enableEditor || array.empty());\r\n}\r\n\r\nvoid PropertyView::tabChanged(int index)\r\n{\r\n ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter().\r\n GetGroup(\"BaseApp\")->GetGroup(\"Preferences\")->GetGroup(\"PropertyView\");\r\n if (hGrp) {\r\n hGrp->SetInt(\"LastTabIndex\", index);\r\n }\r\n}\r\n\r\nvoid PropertyView::changeEvent(QEvent *e)\r\n{\r\n if (e->type() == QEvent::LanguageChange) {\r\n tabs->setTabText(0, trUtf8(\"View\"));\r\n tabs->setTabText(1, trUtf8(\"Data\"));\r\n }\r\n\r\n QWidget::changeEvent(e);\r\n}\r\n\r\n\/* TRANSLATOR Gui::DockWnd::PropertyDockView *\/\r\n\r\nPropertyDockView::PropertyDockView(Gui::Document* pcDocument, QWidget *parent)\r\n : DockWindow(pcDocument,parent)\r\n{\r\n setWindowTitle(tr(\"Property View\"));\r\n\r\n PropertyView* view = new PropertyView(this);\r\n QGridLayout* pLayout = new QGridLayout(this);\r\n pLayout->setSpacing(0);\r\n pLayout->setMargin (0);\r\n pLayout->addWidget(view, 0, 0);\r\n\r\n resize( 200, 400 );\r\n}\r\n\r\nPropertyDockView::~PropertyDockView()\r\n{\r\n}\r\n\r\n#include \"moc_PropertyView.cpp\"\r\nadd option to disable auto-deactivation of property view for inactive document\/***************************************************************************\r\n * Copyright (c) 2002 Juergen Riegel *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n#ifndef _PreComp_\r\n# include \r\n# include \r\n# include \r\n#endif\r\n\r\n#include \r\n\r\n\/\/\/ Here the FreeCAD includes sorted by Base,App,Gui......\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"PropertyView.h\"\r\n#include \"Application.h\"\r\n#include \"Document.h\"\r\n#include \"BitmapFactory.h\"\r\n#include \"ViewProvider.h\"\r\n\r\n#include \"propertyeditor\/PropertyEditor.h\"\r\n\r\nusing namespace std;\r\nusing namespace Gui;\r\nusing namespace Gui::DockWnd;\r\nusing namespace Gui::PropertyEditor;\r\n\r\n\r\n\/* TRANSLATOR Gui::PropertyView *\/\r\n\r\n\/*! Property Editor Widget\r\n *\r\n * Provides two Gui::PropertyEditor::PropertyEditor widgets, for \"View\" and \"Data\",\r\n * in two tabs.\r\n *\/\r\nPropertyView::PropertyView(QWidget *parent)\r\n : QWidget(parent)\r\n{\r\n QGridLayout* pLayout = new QGridLayout( this ); \r\n pLayout->setSpacing(0);\r\n pLayout->setMargin (0);\r\n\r\n tabs = new QTabWidget (this);\r\n tabs->setObjectName(QString::fromUtf8(\"propertyTab\"));\r\n tabs->setTabPosition(QTabWidget::South);\r\n#if defined(Q_OS_WIN32)\r\n tabs->setTabShape(QTabWidget::Triangular);\r\n#endif\r\n pLayout->addWidget(tabs, 0, 0);\r\n\r\n propertyEditorView = new Gui::PropertyEditor::PropertyEditor();\r\n propertyEditorView->setAutomaticDocumentUpdate(false);\r\n tabs->addTab(propertyEditorView, tr(\"View\"));\r\n\r\n propertyEditorData = new Gui::PropertyEditor::PropertyEditor();\r\n propertyEditorData->setAutomaticDocumentUpdate(true);\r\n tabs->addTab(propertyEditorData, tr(\"Data\"));\r\n\r\n ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter().\r\n GetGroup(\"BaseApp\")->GetGroup(\"Preferences\")->GetGroup(\"PropertyView\");\r\n if ( hGrp ) {\r\n int preferredTab = hGrp->GetInt(\"LastTabIndex\", 1);\r\n\r\n if ( preferredTab > 0 && preferredTab < tabs->count() )\r\n tabs->setCurrentIndex(preferredTab);\r\n }\r\n\r\n \/\/ connect after adding all tabs, so adding doesn't thrash the parameter\r\n connect(tabs, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int)));\r\n\r\n this->connectPropData =\r\n App::GetApplication().signalChangedObject.connect(boost::bind\r\n (&PropertyView::slotChangePropertyData, this, _1, _2));\r\n this->connectPropView =\r\n Gui::Application::Instance->signalChangedObject.connect(boost::bind\r\n (&PropertyView::slotChangePropertyView, this, _1, _2));\r\n this->connectPropAppend =\r\n App::GetApplication().signalAppendDynamicProperty.connect(boost::bind\r\n (&PropertyView::slotAppendDynamicProperty, this, _1));\r\n this->connectPropRemove =\r\n App::GetApplication().signalRemoveDynamicProperty.connect(boost::bind\r\n (&PropertyView::slotRemoveDynamicProperty, this, _1));\r\n this->connectPropChange =\r\n App::GetApplication().signalChangePropertyEditor.connect(boost::bind\r\n (&PropertyView::slotChangePropertyEditor, this, _1));\r\n this->connectActiveDoc =\r\n Application::Instance->signalActiveDocument.connect(boost::bind\r\n (&PropertyView::slotActiveDocument, this, _1));\r\n}\r\n\r\nPropertyView::~PropertyView()\r\n{\r\n this->connectPropData.disconnect();\r\n this->connectPropView.disconnect();\r\n this->connectPropAppend.disconnect();\r\n this->connectPropRemove.disconnect();\r\n this->connectPropChange.disconnect();\r\n this->connectActiveDoc.disconnect();\r\n}\r\n\r\nvoid PropertyView::slotChangePropertyData(const App::DocumentObject&, const App::Property& prop)\r\n{\r\n propertyEditorData->updateProperty(prop);\r\n}\r\n\r\nvoid PropertyView::slotChangePropertyView(const Gui::ViewProvider&, const App::Property& prop)\r\n{\r\n propertyEditorView->updateProperty(prop);\r\n}\r\n\r\nvoid PropertyView::slotAppendDynamicProperty(const App::Property& prop)\r\n{\r\n App::PropertyContainer* parent = prop.getContainer();\r\n if (parent->isHidden(&prop))\r\n return;\r\n\r\n if (parent->isDerivedFrom(App::DocumentObject::getClassTypeId())) {\r\n propertyEditorData->appendProperty(prop);\r\n }\r\n else if (parent->isDerivedFrom(Gui::ViewProvider::getClassTypeId())) {\r\n propertyEditorView->appendProperty(prop);\r\n }\r\n}\r\n\r\nvoid PropertyView::slotRemoveDynamicProperty(const App::Property& prop)\r\n{\r\n App::PropertyContainer* parent = prop.getContainer();\r\n if (parent && parent->isDerivedFrom(App::DocumentObject::getClassTypeId())) {\r\n propertyEditorData->removeProperty(prop);\r\n }\r\n else if (parent && parent->isDerivedFrom(Gui::ViewProvider::getClassTypeId())) {\r\n propertyEditorView->removeProperty(prop);\r\n }\r\n}\r\n\r\nvoid PropertyView::slotChangePropertyEditor(const App::Property& prop)\r\n{\r\n App::PropertyContainer* parent = prop.getContainer();\r\n if (parent && parent->isDerivedFrom(App::DocumentObject::getClassTypeId())) {\r\n propertyEditorData->updateEditorMode(prop);\r\n }\r\n else if (parent && parent->isDerivedFrom(Gui::ViewProvider::getClassTypeId())) {\r\n propertyEditorView->updateEditorMode(prop);\r\n }\r\n}\r\n\r\nvoid PropertyView::slotActiveDocument(const Gui::Document &doc)\r\n{\r\n \/\/ allow to disable the auto-deactivation\r\n ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(\"User parameter:BaseApp\/Preferences\/View\");\r\n bool enableEditor = hGrp->GetBool(\"EnablePropertyViewForInactiveDocument\", false);\r\n if (enableEditor) {\r\n setEnabled(true);\r\n return;\r\n }\r\n\r\n \/\/ check if at least one selected object is part of the active document\r\n std::vector array = Gui::Selection().getCompleteSelection();\r\n for (std::vector::const_iterator it = array.begin(); it != array.end(); ++it) {\r\n if (Gui::Application::Instance->getDocument(it->pDoc) == &doc) {\r\n enableEditor = true;\r\n break;\r\n }\r\n }\r\n setEnabled(enableEditor || array.empty());\r\n}\r\n\r\nstruct PropertyView::PropInfo\r\n{\r\n std::string propName;\r\n int propId;\r\n std::vector propList;\r\n};\r\n\r\nstruct PropertyView::PropFind {\r\n const PropInfo& item;\r\n PropFind(const PropInfo& item) : item(item) {}\r\n bool operator () (const PropInfo& elem) const\r\n {\r\n return (elem.propId == item.propId) &&\r\n (elem.propName == item.propName);\r\n }\r\n};\r\n\r\nvoid PropertyView::onSelectionChanged(const SelectionChanges& msg)\r\n{\r\n if (msg.Type != SelectionChanges::AddSelection &&\r\n msg.Type != SelectionChanges::RmvSelection &&\r\n msg.Type != SelectionChanges::SetSelection &&\r\n msg.Type != SelectionChanges::ClrSelection)\r\n return;\r\n\r\n \/\/ allow to disable the auto-deactivation\r\n ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(\"User parameter:BaseApp\/Preferences\/View\");\r\n bool enableEditor = hGrp->GetBool(\"EnablePropertyViewForInactiveDocument\", false);\r\n Gui::Document *activeDoc = Application::Instance->activeDocument();\r\n\r\n \/\/ group the properties by \r\n std::vector propDataMap;\r\n std::vector propViewMap;\r\n std::vector array = Gui::Selection().getCompleteSelection();\r\n for (std::vector::const_iterator it = array.begin(); it != array.end(); ++it) {\r\n App::DocumentObject *ob=0;\r\n ViewProvider *vp=0;\r\n\r\n std::vector dataList;\r\n std::map viewList;\r\n if ((*it).pObject) {\r\n (*it).pObject->getPropertyList(dataList);\r\n ob = (*it).pObject;\r\n\r\n \/\/ get also the properties of the associated view provider\r\n Gui::Document* doc = Gui::Application::Instance->getDocument(it->pDoc);\r\n vp = doc->getViewProvider((*it).pObject);\r\n if(!vp) continue;\r\n \/\/ get the properties as map here because it doesn't matter to have them sorted alphabetically\r\n vp->getPropertyMap(viewList);\r\n if (activeDoc == doc) {\r\n enableEditor = true;\r\n }\r\n }\r\n\r\n \/\/ store the properties with as key in a map\r\n std::vector::iterator pt;\r\n if (ob) {\r\n for (pt = dataList.begin(); pt != dataList.end(); ++pt) {\r\n PropInfo nameType;\r\n nameType.propName = ob->getPropertyName(*pt);\r\n nameType.propId = (*pt)->getTypeId().getKey();\r\n\r\n if (!ob->isHidden(*pt)) {\r\n std::vector::iterator pi = std::find_if(propDataMap.begin(), propDataMap.end(), PropFind(nameType));\r\n if (pi != propDataMap.end()) {\r\n pi->propList.push_back(*pt);\r\n }\r\n else {\r\n nameType.propList.push_back(*pt);\r\n propDataMap.push_back(nameType);\r\n }\r\n }\r\n }\r\n }\r\n \/\/ the same for the view properties\r\n if (vp) {\r\n std::map::iterator pt;\r\n for (pt = viewList.begin(); pt != viewList.end(); ++pt) {\r\n PropInfo nameType;\r\n nameType.propName = pt->first;\r\n nameType.propId = pt->second->getTypeId().getKey();\r\n\r\n if (!vp->isHidden(pt->second)) {\r\n std::vector::iterator pi = std::find_if(propViewMap.begin(), propViewMap.end(), PropFind(nameType));\r\n if (pi != propViewMap.end()) {\r\n pi->propList.push_back(pt->second);\r\n }\r\n else {\r\n nameType.propList.push_back(pt->second);\r\n propViewMap.push_back(nameType);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n \/\/ the property must be part of each selected object, i.e. the number\r\n \/\/ of selected objects is equal to the number of properties with same\r\n \/\/ name and id\r\n std::vector::const_iterator it;\r\n PropertyModel::PropertyList dataProps;\r\n for (it = propDataMap.begin(); it != propDataMap.end(); ++it) {\r\n if (it->propList.size() == array.size()) {\r\n dataProps.push_back(std::make_pair(it->propName, it->propList));\r\n }\r\n }\r\n propertyEditorData->buildUp(dataProps);\r\n\r\n PropertyModel::PropertyList viewProps;\r\n for (it = propViewMap.begin(); it != propViewMap.end(); ++it) {\r\n if (it->propList.size() == array.size()) {\r\n viewProps.push_back(std::make_pair(it->propName, it->propList));\r\n }\r\n }\r\n propertyEditorView->buildUp(viewProps);\r\n\r\n \/\/ make sure the editors are enabled\/disabled properly\r\n setEnabled(enableEditor || array.empty());\r\n}\r\n\r\nvoid PropertyView::tabChanged(int index)\r\n{\r\n ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter().\r\n GetGroup(\"BaseApp\")->GetGroup(\"Preferences\")->GetGroup(\"PropertyView\");\r\n if (hGrp) {\r\n hGrp->SetInt(\"LastTabIndex\", index);\r\n }\r\n}\r\n\r\nvoid PropertyView::changeEvent(QEvent *e)\r\n{\r\n if (e->type() == QEvent::LanguageChange) {\r\n tabs->setTabText(0, trUtf8(\"View\"));\r\n tabs->setTabText(1, trUtf8(\"Data\"));\r\n }\r\n\r\n QWidget::changeEvent(e);\r\n}\r\n\r\n\/* TRANSLATOR Gui::DockWnd::PropertyDockView *\/\r\n\r\nPropertyDockView::PropertyDockView(Gui::Document* pcDocument, QWidget *parent)\r\n : DockWindow(pcDocument,parent)\r\n{\r\n setWindowTitle(tr(\"Property View\"));\r\n\r\n PropertyView* view = new PropertyView(this);\r\n QGridLayout* pLayout = new QGridLayout(this);\r\n pLayout->setSpacing(0);\r\n pLayout->setMargin (0);\r\n pLayout->addWidget(view, 0, 0);\r\n\r\n resize( 200, 400 );\r\n}\r\n\r\nPropertyDockView::~PropertyDockView()\r\n{\r\n}\r\n\r\n#include \"moc_PropertyView.cpp\"\r\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2008, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/ChannelOp.h\"\n#include \"IECore\/TypeTraits.h\"\n#include \"IECore\/DespatchTypedData.h\"\n#include \"IECore\/CompoundParameter.h\"\n\n#include \"boost\/format.hpp\"\n\nusing namespace IECore;\nusing namespace std;\nusing namespace boost;\n\nChannelOp::ChannelOp( const std::string &name, const std::string &description )\n\t:\tImagePrimitiveOp( name, description )\n{\n\n\tStringVectorDataPtr defaultChannels = new StringVectorData;\n\tdefaultChannels->writable().push_back( \"R\" );\n\tdefaultChannels->writable().push_back( \"G\" );\n\tdefaultChannels->writable().push_back( \"B\" );\n\t\n\tm_channelNamesParameter = new StringVectorParameter(\n\t\t\"channels\",\n\t\t\"The names of the channels to modify.\",\n\t\tdefaultChannels\n\t);\n\n\tparameters()->addParameter( m_channelNamesParameter );\n}\n\nChannelOp::~ChannelOp()\n{\n}\n\t\nStringVectorParameterPtr ChannelOp::channelNamesParameter()\n{\n\treturn m_channelNamesParameter;\n}\n\nConstStringVectorParameterPtr ChannelOp::channelNamesParameter() const\n{\n\treturn m_channelNamesParameter;\n}\n\nvoid ChannelOp::modifyTypedPrimitive( ImagePrimitivePtr image, ConstCompoundObjectPtr operands )\n{\n\tif( image->getDataWindow().isEmpty() )\n\t{\n\t\treturn;\n\t}\n\n\tChannelVector channels;\n\t\n\t\/\/\/ \\todo Just use ImagePrimitive::channelValid. We don't want to do that right now\n\t\/\/\/ as it imposes loose restrictions on the channel datatype - in the future it should perhaps\n\t\/\/\/ impose the restrictions we have here (float, int or half vector data).\n\tsize_t numPixels = image->variableSize( PrimitiveVariable::Vertex );\n\tconst vector channelNames = channelNamesParameter()->getTypedValue();\n\tfor( unsigned i=0; ivariables.find( channelNames[i] );\n\t\tif( it==image->variables.end() )\n\t\t{\n\t\t\tthrow Exception( str( format( \"Channel \\\"%s\\\" does not exist.\" ) % channelNames[i] ) );\n\t\t}\n\t\t\n\t\tif( it->second.interpolation!=PrimitiveVariable::Vertex &&\n\t\t\tit->second.interpolation!=PrimitiveVariable::Varying &&\n\t\t\tit->second.interpolation!=PrimitiveVariable::FaceVarying )\n\t\t{\n\t\t\tthrow Exception( str( format( \"Primitive variable \\\"%s\\\" has inappropriate interpolation.\" ) % channelNames[i] ) );\n\t\t}\n\t\t\n\t\tif( !it->second.data )\n\t\t{\n\t\t\tthrow Exception( str( format( \"Primitive variable \\\"%s\\\" has no data.\" ) % channelNames[i] ) );\n\t\t}\n\t\t\n\t\tif( !it->second.data->isInstanceOf( FloatVectorData::staticTypeId() ) &&\n\t\t\t!it->second.data->isInstanceOf( HalfVectorData::staticTypeId() ) &&\n\t\t\t!it->second.data->isInstanceOf( IntVectorData::staticTypeId() ) )\n\t\t{\n\t\t\tthrow Exception( str( format( \"Primitive variable \\\"%s\\\" has inappropriate type.\" ) % channelNames[i] ) );\n\t\t}\n\t\t\n\t\tsize_t size = despatchTypedData( it->second.data );\n\t\tif( size!=numPixels )\n\t\t{\n\t\t\tthrow Exception( str( format( \"Primitive variable \\\"%s\\\" has wrong size (%d but should be %d).\" ) % channelNames[i] % size % numPixels ) );\n\t\t}\n\t\t\n\t\tchannels.push_back( it->second.data );\n\t}\n\t\n\tmodifyChannels( image->getDisplayWindow(), image->getDataWindow(), channels );\n}\nExtended todo\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2008, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/ChannelOp.h\"\n#include \"IECore\/TypeTraits.h\"\n#include \"IECore\/DespatchTypedData.h\"\n#include \"IECore\/CompoundParameter.h\"\n\n#include \"boost\/format.hpp\"\n\nusing namespace IECore;\nusing namespace std;\nusing namespace boost;\n\nChannelOp::ChannelOp( const std::string &name, const std::string &description )\n\t:\tImagePrimitiveOp( name, description )\n{\n\n\tStringVectorDataPtr defaultChannels = new StringVectorData;\n\tdefaultChannels->writable().push_back( \"R\" );\n\tdefaultChannels->writable().push_back( \"G\" );\n\tdefaultChannels->writable().push_back( \"B\" );\n\t\n\tm_channelNamesParameter = new StringVectorParameter(\n\t\t\"channels\",\n\t\t\"The names of the channels to modify.\",\n\t\tdefaultChannels\n\t);\n\n\tparameters()->addParameter( m_channelNamesParameter );\n}\n\nChannelOp::~ChannelOp()\n{\n}\n\t\nStringVectorParameterPtr ChannelOp::channelNamesParameter()\n{\n\treturn m_channelNamesParameter;\n}\n\nConstStringVectorParameterPtr ChannelOp::channelNamesParameter() const\n{\n\treturn m_channelNamesParameter;\n}\n\nvoid ChannelOp::modifyTypedPrimitive( ImagePrimitivePtr image, ConstCompoundObjectPtr operands )\n{\n\tif( image->getDataWindow().isEmpty() )\n\t{\n\t\treturn;\n\t}\n\n\tChannelVector channels;\n\t\n\t\/\/\/ \\todo Just use ImagePrimitive::channelValid. We don't want to do that right now\n\t\/\/\/ as it imposes loose restrictions on the channel datatype - in the future it should perhaps\n\t\/\/\/ impose the restrictions we have here (float, int or half vector data). \n\t\/\/\/ Would be useful to add a TypeTraits class which can test compatiblity againt ImagePrimitive-supported channels, too.\n\tsize_t numPixels = image->variableSize( PrimitiveVariable::Vertex );\n\tconst vector channelNames = channelNamesParameter()->getTypedValue();\n\tfor( unsigned i=0; ivariables.find( channelNames[i] );\n\t\tif( it==image->variables.end() )\n\t\t{\n\t\t\tthrow Exception( str( format( \"Channel \\\"%s\\\" does not exist.\" ) % channelNames[i] ) );\n\t\t}\n\t\t\n\t\tif( it->second.interpolation!=PrimitiveVariable::Vertex &&\n\t\t\tit->second.interpolation!=PrimitiveVariable::Varying &&\n\t\t\tit->second.interpolation!=PrimitiveVariable::FaceVarying )\n\t\t{\n\t\t\tthrow Exception( str( format( \"Primitive variable \\\"%s\\\" has inappropriate interpolation.\" ) % channelNames[i] ) );\n\t\t}\n\t\t\n\t\tif( !it->second.data )\n\t\t{\n\t\t\tthrow Exception( str( format( \"Primitive variable \\\"%s\\\" has no data.\" ) % channelNames[i] ) );\n\t\t}\n\t\t\n\t\tif( !it->second.data->isInstanceOf( FloatVectorData::staticTypeId() ) &&\n\t\t\t!it->second.data->isInstanceOf( HalfVectorData::staticTypeId() ) &&\n\t\t\t!it->second.data->isInstanceOf( IntVectorData::staticTypeId() ) )\n\t\t{\n\t\t\tthrow Exception( str( format( \"Primitive variable \\\"%s\\\" has inappropriate type.\" ) % channelNames[i] ) );\n\t\t}\n\t\t\n\t\tsize_t size = despatchTypedData( it->second.data );\n\t\tif( size!=numPixels )\n\t\t{\n\t\t\tthrow Exception( str( format( \"Primitive variable \\\"%s\\\" has wrong size (%d but should be %d).\" ) % channelNames[i] % size % numPixels ) );\n\t\t}\n\t\t\n\t\tchannels.push_back( it->second.data );\n\t}\n\t\n\tmodifyChannels( image->getDisplayWindow(), image->getDataWindow(), channels );\n}\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993 - 2009 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"ComposeDefaultKey.h\"\n\n\/* system headers *\/\n#include \n#include \n\n\/* common implementation headers *\/\n#include \"BzfEvent.h\"\n#include \"KeyManager.h\"\n#include \"EventHandler.h\"\n\n\/* local implementation headers *\/\n#include \"LocalPlayer.h\"\n#include \"HUDRenderer.h\"\n#include \"LocalCommand.h\"\n#include \"playing.h\"\n#include \"HUDui.h\"\n\n#define MAX_MESSAGE_HISTORY (20)\n\nMessageQueue messageHistory;\nunsigned int messageHistoryIndex = 0;\n\nstatic bool isWordCompletion(const BzfKeyEvent& key)\n{\n if ((key.chr == 6) || \/\/ ^F\n (key.chr== 9) || \/\/ \n ((key.shift == 0) && (key.button == BzfKeyEvent::F2))) {\n return true;\n } else {\n return false;\n }\n}\n\n\nbool ComposeDefaultKey::keyPress(const BzfKeyEvent& key)\n{\n bool sendIt;\n LocalPlayer *myTank = LocalPlayer::getMyTank();\n if (myTank && KEYMGR.get(key, true) == \"jump\" && BZDB.isTrue(\"jumpTyping\")) {\n \/\/ jump while typing\n myTank->setJump();\n return false;\n }\n\n if (myTank &&\n ((myTank->getInputMethod() != LocalPlayer::Keyboard) ||\n (myTank->getTeam() == ObserverTeam))) {\n if ((key.button == BzfKeyEvent::Up) ||\n\t(key.button == BzfKeyEvent::Down)) {\n return true;\n }\n }\n\n if (isWordCompletion(key)) {\n const std::string line = hud->getComposeString();\n std::set partials;\n if (!BZDB.isTrue(\"noDefaultWordComplete\")) {\n completer.complete(line, partials);\n }\n eventHandler.WordComplete(line, partials);\n if (!partials.empty()) { \n \/\/ find the longest common string\n const std::string first = *(partials.begin());\n const std::string last = *(partials.rbegin());\n size_t i;\n const size_t minLen = std::min(first.size(), last.size());\n for (i = 0; i < minLen; i++) {\n if (first[i] != last[i]) {\n break;\n }\n }\n hud->setComposeString(line + first.substr(0, i));\n\n if (partials.size() >= 2) {\n const int lastSpace = line.find_last_of(\" \\t\");\n const std::string lastWord = line.substr(lastSpace + 1);\n \n std::string matches;\n std::set::const_iterator it;\n for (it = partials.begin(); it != partials.end(); ++it) {\n matches += \" \";\n matches += lastWord + it->substr(i);\n }\n controlPanel->addMessage(matches, ControlPanel::MessageCurrent);\n }\n }\n return true;\n }\n\n switch (key.chr) {\n case 3: \/\/ ^C\n case 27: { \/\/ escape\n sendIt = false; \/\/ finished composing -- don't send\n break;\n }\n case 4: \/\/ ^D\n case 13: { \/\/ return\n sendIt = true;\n break;\n }\n default: {\n return false;\n }\n }\n\n if (sendIt) {\n std::string message = hud->getComposeString();\n if (message.length() > 0) {\n const char* cmd = message.c_str();\n if (!LocalCommand::execute(cmd)) {\n if (!myTank) {\n std::string msg = std::string(\"unknown local command: \") + cmd;\n controlPanel->addMessage(msg, ControlPanel::MessageCurrent);\n }\n else if (serverLink) {\n char messageBuffer[MessageLen];\n memset(messageBuffer, 0, MessageLen);\n strncpy(messageBuffer, message.c_str(), MessageLen);\n serverLink->sendMessage(msgDestination, messageBuffer);\n }\n }\n\n \/\/ record message in history\n const size_t mhLen = messageHistory.size();\n size_t i;\n for (i = 0; i < mhLen; i++) {\n\tif (messageHistory[i] == message) {\n\t messageHistory.erase(messageHistory.begin() + i);\n\t messageHistory.push_front(message);\n\t break;\n\t}\n }\n if (i == mhLen) {\n\tif (mhLen >= MAX_MESSAGE_HISTORY) {\n\t messageHistory.pop_back();\n\t}\n\tmessageHistory.push_front(message);\n }\n }\n }\n\n messageHistoryIndex = 0;\n hud->setComposing(std::string());\n HUDui::setDefaultKey(NULL);\n return true;\n}\n\n\nbool ComposeDefaultKey::keyRelease(const BzfKeyEvent& key)\n{\n LocalPlayer* myTank = LocalPlayer::getMyTank();\n if (!myTank ||\n (myTank->getInputMethod() != LocalPlayer::Keyboard) ||\n (myTank->getTeam() == ObserverTeam)) {\n if (key.button == BzfKeyEvent::Up) {\n if (messageHistoryIndex < messageHistory.size()) {\n\thud->setComposeString(messageHistory[messageHistoryIndex]);\n\tmessageHistoryIndex++;\n } else {\n\thud->setComposeString(std::string());\n }\n return true;\n } else if (key.button == BzfKeyEvent::Down) {\n if (messageHistoryIndex > 0) {\n\tmessageHistoryIndex--;\n\thud->setComposeString(messageHistory[messageHistoryIndex]);\n } else {\n\thud->setComposeString(std::string());\n }\n return true;\n }\n else if (myTank && ((key.shift == BzfKeyEvent::ShiftKey\n\t\t\t || (hud->getComposeString().length() == 0)) &&\n\t\t\t(key.button == BzfKeyEvent::Left\n\t\t\t || key.button == BzfKeyEvent::Right))) {\n \/\/ exclude robot from private message recipient.\n \/\/ No point sending messages to robot (now)\n selectNextRecipient(key.button != BzfKeyEvent::Left, false);\n const Player *recipient = myTank->getRecipient();\n if (recipient) {\n\tmsgDestination = recipient->getId();\n\tstd::string composePrompt = \"Send to \";\n\tcomposePrompt += recipient->getCallSign();\n\tcomposePrompt += \": \";\n\thud->setComposing(composePrompt);\n }\n return false;\n }\n }\n\n if ((key.chr == 4) || \/\/ ^D\n (key.chr == 6) || \/\/ ^F\n (key.chr == 13) || \/\/ return\n isWordCompletion(key)) {\n return true;\n }\n\n return keyPress(key);\n}\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\nquell warning\/* bzflag\n * Copyright (c) 1993 - 2009 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"ComposeDefaultKey.h\"\n\n\/* system headers *\/\n#include \n#include \n\n\/* common implementation headers *\/\n#include \"BzfEvent.h\"\n#include \"KeyManager.h\"\n#include \"EventHandler.h\"\n\n\/* local implementation headers *\/\n#include \"LocalPlayer.h\"\n#include \"HUDRenderer.h\"\n#include \"LocalCommand.h\"\n#include \"playing.h\"\n#include \"HUDui.h\"\n\n#define MAX_MESSAGE_HISTORY (20)\n\nMessageQueue messageHistory;\nunsigned int messageHistoryIndex = 0;\n\nstatic bool isWordCompletion(const BzfKeyEvent& key)\n{\n if ((key.chr == 6) || \/\/ ^F\n (key.chr== 9) || \/\/ \n ((key.shift == 0) && (key.button == BzfKeyEvent::F2))) {\n return true;\n } else {\n return false;\n }\n}\n\n\nbool ComposeDefaultKey::keyPress(const BzfKeyEvent& key)\n{\n bool sendIt;\n LocalPlayer *myTank = LocalPlayer::getMyTank();\n if (myTank && KEYMGR.get(key, true) == \"jump\" && BZDB.isTrue(\"jumpTyping\")) {\n \/\/ jump while typing\n myTank->setJump();\n return false;\n }\n\n if (myTank &&\n ((myTank->getInputMethod() != LocalPlayer::Keyboard) ||\n (myTank->getTeam() == ObserverTeam))) {\n if ((key.button == BzfKeyEvent::Up) ||\n\t(key.button == BzfKeyEvent::Down)) {\n return true;\n }\n }\n\n if (isWordCompletion(key)) {\n const std::string line = hud->getComposeString();\n std::set partials;\n if (!BZDB.isTrue(\"noDefaultWordComplete\")) {\n completer.complete(line, partials);\n }\n eventHandler.WordComplete(line, partials);\n if (!partials.empty()) { \n \/\/ find the longest common string\n const std::string first = *(partials.begin());\n const std::string last = *(partials.rbegin());\n size_t i;\n const size_t minLen = std::min(first.size(), last.size());\n for (i = 0; i < minLen; i++) {\n if (first[i] != last[i]) {\n break;\n }\n }\n hud->setComposeString(line + first.substr(0, i));\n\n if (partials.size() >= 2) {\n const size_t lastSpace = line.find_last_of(\" \\t\");\n const std::string lastWord = line.substr(lastSpace + 1);\n\n std::string matches;\n std::set::const_iterator it;\n for (it = partials.begin(); it != partials.end(); ++it) {\n matches += \" \";\n matches += lastWord + it->substr(i);\n }\n controlPanel->addMessage(matches, ControlPanel::MessageCurrent);\n }\n }\n return true;\n }\n\n switch (key.chr) {\n case 3: \/\/ ^C\n case 27: { \/\/ escape\n sendIt = false; \/\/ finished composing -- don't send\n break;\n }\n case 4: \/\/ ^D\n case 13: { \/\/ return\n sendIt = true;\n break;\n }\n default: {\n return false;\n }\n }\n\n if (sendIt) {\n std::string message = hud->getComposeString();\n if (message.length() > 0) {\n const char* cmd = message.c_str();\n if (!LocalCommand::execute(cmd)) {\n if (!myTank) {\n std::string msg = std::string(\"unknown local command: \") + cmd;\n controlPanel->addMessage(msg, ControlPanel::MessageCurrent);\n }\n else if (serverLink) {\n char messageBuffer[MessageLen];\n memset(messageBuffer, 0, MessageLen);\n strncpy(messageBuffer, message.c_str(), MessageLen);\n serverLink->sendMessage(msgDestination, messageBuffer);\n }\n }\n\n \/\/ record message in history\n const size_t mhLen = messageHistory.size();\n size_t i;\n for (i = 0; i < mhLen; i++) {\n\tif (messageHistory[i] == message) {\n\t messageHistory.erase(messageHistory.begin() + i);\n\t messageHistory.push_front(message);\n\t break;\n\t}\n }\n if (i == mhLen) {\n\tif (mhLen >= MAX_MESSAGE_HISTORY) {\n\t messageHistory.pop_back();\n\t}\n\tmessageHistory.push_front(message);\n }\n }\n }\n\n messageHistoryIndex = 0;\n hud->setComposing(std::string());\n HUDui::setDefaultKey(NULL);\n return true;\n}\n\n\nbool ComposeDefaultKey::keyRelease(const BzfKeyEvent& key)\n{\n LocalPlayer* myTank = LocalPlayer::getMyTank();\n if (!myTank ||\n (myTank->getInputMethod() != LocalPlayer::Keyboard) ||\n (myTank->getTeam() == ObserverTeam)) {\n if (key.button == BzfKeyEvent::Up) {\n if (messageHistoryIndex < messageHistory.size()) {\n\thud->setComposeString(messageHistory[messageHistoryIndex]);\n\tmessageHistoryIndex++;\n } else {\n\thud->setComposeString(std::string());\n }\n return true;\n } else if (key.button == BzfKeyEvent::Down) {\n if (messageHistoryIndex > 0) {\n\tmessageHistoryIndex--;\n\thud->setComposeString(messageHistory[messageHistoryIndex]);\n } else {\n\thud->setComposeString(std::string());\n }\n return true;\n }\n else if (myTank && ((key.shift == BzfKeyEvent::ShiftKey\n\t\t\t || (hud->getComposeString().length() == 0)) &&\n\t\t\t(key.button == BzfKeyEvent::Left\n\t\t\t || key.button == BzfKeyEvent::Right))) {\n \/\/ exclude robot from private message recipient.\n \/\/ No point sending messages to robot (now)\n selectNextRecipient(key.button != BzfKeyEvent::Left, false);\n const Player *recipient = myTank->getRecipient();\n if (recipient) {\n\tmsgDestination = recipient->getId();\n\tstd::string composePrompt = \"Send to \";\n\tcomposePrompt += recipient->getCallSign();\n\tcomposePrompt += \": \";\n\thud->setComposing(composePrompt);\n }\n return false;\n }\n }\n\n if ((key.chr == 4) || \/\/ ^D\n (key.chr == 6) || \/\/ ^F\n (key.chr == 13) || \/\/ return\n isWordCompletion(key)) {\n return true;\n }\n\n return keyPress(key);\n}\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2012, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/rss.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n#include \"libtorrent\/aux_\/session_impl.hpp\"\n#include \"libtorrent\/http_parser.hpp\"\n\n#include \"test.hpp\"\n\nusing namespace libtorrent;\n\nvoid print_feed(feed_status const& f)\n{\n\tfprintf(stderr, \"FEED: %s\\n\",f.url.c_str());\n\tif (f.error)\n\t\tfprintf(stderr, \"ERROR: %s\\n\", f.error.message().c_str());\n\n\tfprintf(stderr, \" %s\\n %s\\n\", f.title.c_str(), f.description.c_str());\n\tfprintf(stderr, \" ttl: %d minutes\\n\", f.ttl);\n\tfprintf(stderr, \" num items: %d\\n\", int(f.items.size()));\n\n\tfor (std::vector::const_iterator i = f.items.begin()\n\t\t, end(f.items.end()); i != end; ++i)\n\t{\n\t\tfprintf(stderr, \"\\033[32m%s\\033[0m\\n------------------------------------------------------\\n\"\n\t\t\t\" url: %s\\n size: %\"PRId64\"\\n info-hash: %s\\n uuid: %s\\n description: %s\\n\"\n\t\t\t\" comment: %s\\n category: %s\\n\"\n\t\t\t, i->title.c_str(), i->url.c_str(), i->size\n\t\t\t, i->info_hash.is_all_zeros() ? \"\" : to_hex(i->info_hash.to_string()).c_str()\n\t\t\t, i->uuid.c_str(), i->description.c_str(), i->comment.c_str(), i->category.c_str());\n\t}\n}\n\nstruct rss_expect\n{\n\trss_expect(int nitems, std::string url, std::string title, size_type size)\n\t\t: num_items(nitems), first_url(url), first_title(title), first_size(size)\n\t{}\n\n\tint num_items;\n\tstd::string first_url;\n\tstd::string first_title;\n\tsize_type first_size;\n};\n\nvoid test_feed(std::string const& filename, rss_expect const& expect)\n{\n\tstd::vector buffer;\n\terror_code ec;\n\tload_file(filename, buffer, ec);\n\tTEST_CHECK(!ec);\n\n\tchar* buf = &buffer[0];\n\tint len = buffer.size();\n\n\tchar const header[] = \"HTTP\/1.1 200 OK\\r\\n\"\n\t\t\"\\r\\n\";\n\n\tboost::shared_ptr s = boost::shared_ptr(new aux::session_impl(\n\t\tstd::make_pair(100, 200), fingerprint(\"TT\", 0, 0, 0 ,0), NULL, 0\n#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING\n\t\t\t\t, \".\"\n#endif\n\t\t));\n\ts->start_session();\n\n\tfeed_settings sett;\n\tsett.auto_download = false;\n\tsett.auto_map_handles = false;\n\tboost::shared_ptr f = boost::shared_ptr(new feed(*s, sett));\n\thttp_parser parser;\n\tbool err = false;\n\tparser.incoming(buffer::const_interval(header, header + sizeof(header)-1), err);\n\tTEST_CHECK(err == false);\n\n\tf->on_feed(error_code(), parser, buf, len);\n\n\tfeed_status st;\n\tf->get_feed_status(&st);\n\tTEST_CHECK(!st.error);\n\n\tprint_feed(st);\n\n\tTEST_CHECK(st.items.size() == expect.num_items);\n\tif (st.items.size() > 0)\n\t{\n\t\tTEST_CHECK(st.items[0].url == expect.first_url);\n\t\tTEST_CHECK(st.items[0].size == expect.first_size);\n\t\tTEST_CHECK(st.items[0].title == expect.first_title);\n\t}\n\n\tentry state;\n\tf->save_state(state);\n\n\tfprintf(stderr, \"feed_state:\\n\");\n#ifdef TORRENT_DEBUG\n\tstate.print(std::cerr);\n#endif\n\n\t\/\/ TODO: verify some key state is saved in 'state'\n}\n\nint test_main()\n{\n\ttest_feed(\"eztv.xml\", rss_expect(30, \"http:\/\/torrent.zoink.it\/The.Daily.Show.2012.02.16.(HDTV-LMAO)[VTV].torrent\", \"The Daily Show 2012-02-16 [HDTV - LMAO]\", 183442338));\n\ttest_feed(\"cb.xml\", rss_expect(50, \"http:\/\/www.clearbits.net\/get\/1911-norbergfestival-2011.torrent\", \"Norbergfestival 2011\", 1160773632));\n\ttest_feed(\"kat.xml\", rss_expect(25, \"http:\/\/kat.ph\/torrents\/benito-di-paula-1975-benito-di-paula-lp-rip-ogg-at-500-jarax4u-t6194897\/\", \"Benito Di Paula - 1975 - Benito Di Paula (LP Rip OGG at 500) [jarax4u]\", 168773863));\n\ttest_feed(\"mn.xml\", rss_expect(20, \"http:\/\/www.mininova.org\/get\/13203100\", \"Dexcell - January TwentyTwelve Mix\", 137311179));\n\ttest_feed(\"pb.xml\", rss_expect(60, \"magnet:?xt=urn:btih:FD4CDDB7BBE722D17A018EFD875EB0695ED7159C&dn=Thompson+Twins+-+1989+-+Big+Trash+%5BMP3%5D\", \"Thompson Twins - 1989 - Big Trash [MP3]\", 100160904));\n\treturn 0;\n}\n\nfix test_rss build\/*\n\nCopyright (c) 2012, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/rss.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n#include \"libtorrent\/aux_\/session_impl.hpp\"\n#include \"libtorrent\/http_parser.hpp\"\n\n#include \"test.hpp\"\n\nusing namespace libtorrent;\n\nvoid print_feed(feed_status const& f)\n{\n\tfprintf(stderr, \"FEED: %s\\n\",f.url.c_str());\n\tif (f.error)\n\t\tfprintf(stderr, \"ERROR: %s\\n\", f.error.message().c_str());\n\n\tfprintf(stderr, \" %s\\n %s\\n\", f.title.c_str(), f.description.c_str());\n\tfprintf(stderr, \" ttl: %d minutes\\n\", f.ttl);\n\tfprintf(stderr, \" num items: %d\\n\", int(f.items.size()));\n\n\tfor (std::vector::const_iterator i = f.items.begin()\n\t\t, end(f.items.end()); i != end; ++i)\n\t{\n\t\tfprintf(stderr, \"\\033[32m%s\\033[0m\\n------------------------------------------------------\\n\"\n\t\t\t\" url: %s\\n size: %\"PRId64\"\\n info-hash: %s\\n uuid: %s\\n description: %s\\n\"\n\t\t\t\" comment: %s\\n category: %s\\n\"\n\t\t\t, i->title.c_str(), i->url.c_str(), i->size\n\t\t\t, i->info_hash.is_all_zeros() ? \"\" : to_hex(i->info_hash.to_string()).c_str()\n\t\t\t, i->uuid.c_str(), i->description.c_str(), i->comment.c_str(), i->category.c_str());\n\t}\n}\n\nstruct rss_expect\n{\n\trss_expect(int nitems, std::string url, std::string title, size_type size)\n\t\t: num_items(nitems), first_url(url), first_title(title), first_size(size)\n\t{}\n\n\tint num_items;\n\tstd::string first_url;\n\tstd::string first_title;\n\tsize_type first_size;\n};\n\nvoid test_feed(std::string const& filename, rss_expect const& expect)\n{\n\tstd::vector buffer;\n\terror_code ec;\n\tload_file(filename, buffer, ec);\n\tTEST_CHECK(!ec);\n\n\tchar* buf = &buffer[0];\n\tint len = buffer.size();\n\n\tchar const header[] = \"HTTP\/1.1 200 OK\\r\\n\"\n\t\t\"\\r\\n\";\n\n\tboost::shared_ptr s = boost::shared_ptr(new aux::session_impl(\n\t\tstd::make_pair(100, 200), fingerprint(\"TT\", 0, 0, 0 ,0), NULL, 0));\n\ts->start_session();\n\n\tfeed_settings sett;\n\tsett.auto_download = false;\n\tsett.auto_map_handles = false;\n\tboost::shared_ptr f = boost::shared_ptr(new feed(*s, sett));\n\thttp_parser parser;\n\tbool err = false;\n\tparser.incoming(buffer::const_interval(header, header + sizeof(header)-1), err);\n\tTEST_CHECK(err == false);\n\n\tf->on_feed(error_code(), parser, buf, len);\n\n\tfeed_status st;\n\tf->get_feed_status(&st);\n\tTEST_CHECK(!st.error);\n\n\tprint_feed(st);\n\n\tTEST_CHECK(st.items.size() == expect.num_items);\n\tif (st.items.size() > 0)\n\t{\n\t\tTEST_CHECK(st.items[0].url == expect.first_url);\n\t\tTEST_CHECK(st.items[0].size == expect.first_size);\n\t\tTEST_CHECK(st.items[0].title == expect.first_title);\n\t}\n\n\tentry state;\n\tf->save_state(state);\n\n\tfprintf(stderr, \"feed_state:\\n\");\n#ifdef TORRENT_DEBUG\n\tstate.print(std::cerr);\n#endif\n\n\t\/\/ TODO: verify some key state is saved in 'state'\n}\n\nint test_main()\n{\n\ttest_feed(\"eztv.xml\", rss_expect(30, \"http:\/\/torrent.zoink.it\/The.Daily.Show.2012.02.16.(HDTV-LMAO)[VTV].torrent\", \"The Daily Show 2012-02-16 [HDTV - LMAO]\", 183442338));\n\ttest_feed(\"cb.xml\", rss_expect(50, \"http:\/\/www.clearbits.net\/get\/1911-norbergfestival-2011.torrent\", \"Norbergfestival 2011\", 1160773632));\n\ttest_feed(\"kat.xml\", rss_expect(25, \"http:\/\/kat.ph\/torrents\/benito-di-paula-1975-benito-di-paula-lp-rip-ogg-at-500-jarax4u-t6194897\/\", \"Benito Di Paula - 1975 - Benito Di Paula (LP Rip OGG at 500) [jarax4u]\", 168773863));\n\ttest_feed(\"mn.xml\", rss_expect(20, \"http:\/\/www.mininova.org\/get\/13203100\", \"Dexcell - January TwentyTwelve Mix\", 137311179));\n\ttest_feed(\"pb.xml\", rss_expect(60, \"magnet:?xt=urn:btih:FD4CDDB7BBE722D17A018EFD875EB0695ED7159C&dn=Thompson+Twins+-+1989+-+Big+Trash+%5BMP3%5D\", \"Thompson Twins - 1989 - Big Trash [MP3]\", 100160904));\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2013, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n#include \"libtorrent\/thread.hpp\"\n#include \"libtorrent\/file.hpp\"\n#include \n#include \n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n#include \n#include \n\nusing namespace libtorrent;\nusing boost::tuples::ignore;\n\nint const alert_mask = alert::all_categories\n& ~alert::progress_notification\n& ~alert::stats_notification;\n\nstruct test_config_t\n{\n\tchar const* name;\n\tbool use_ssl_ports;\n\tbool seed_has_cert;\n\tbool downloader_has_cert;\n\tbool expected_to_complete;\n};\n\ntest_config_t test_config[] =\n{\n\t{\"nobody has a cert (connect to regular port)\", false, false, false, false},\n\t{\"nobody has a cert (connect to ssl port)\", true, false, false, false},\n\t{\"seed has a cert, but not downloader (connect to regular port)\", false, true, false, false},\n\t{\"seed has a cert, but not downloader (connect to ssl port)\", true, true, false, false},\n\t{\"downloader has a cert, but not seed (connect to regular port)\", false, false, true, false},\n\t{\"downloader has a cert, but not seed (connect to ssl port)\", true, false, true, false},\n\t{\"both downloader and seed has a cert (connect to regular port)\", false, true, true, false},\n#ifdef TORRENT_USE_OPENSSL\n\t{\"both downloader and seed has a cert (connect to ssl port)\", true, true, true, true},\n#else\n\t{\"both downloader and seed has a cert (connect to ssl port)\", true, true, true, false},\n#endif\n};\n\nint peer_disconnects = 0;\n\nbool predicate(alert* a)\n{\n\tif (peer_disconnected_alert* p = alert_cast(a))\n\t\t++peer_disconnects;\n\treturn false;\n}\n\nvoid test_ssl(int test_idx)\n{\n\ttest_config_t const& test = test_config[test_idx];\n\n\tfprintf(stderr, \"\\n%s TEST: %s\\n\\n\", time_now_string(), test.name);\n\n\t\/\/ in case the previous run was terminated\n\terror_code ec;\n\tremove_all(\"tmp1_ssl\", ec);\n\tremove_all(\"tmp2_ssl\", ec);\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48075, 49000), \"0.0.0.0\", 0, alert_mask);\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49075, 50000), \"0.0.0.0\", 0, alert_mask);\n\n\tsession_settings sett;\n\t\/\/ this disables outgoing SSL connections\n\tsett.ssl_listen = 0;\n\tif (!test.downloader_has_cert) ses2.set_settings(sett);\n\n\ttorrent_handle tor1;\n\ttorrent_handle tor2;\n\n\tcreate_directory(\"tmp1_ssl\", ec);\n\tstd::ofstream file(\"tmp1_ssl\/temporary\");\n\tboost::intrusive_ptr t = ::create_torrent(&file, 16 * 1024, 13, false, \"ssl\/root_ca_cert.pem\");\n\tfile.close();\n\n\tadd_torrent_params addp;\n\taddp.flags &= ~add_torrent_params::flag_paused;\n\taddp.flags &= ~add_torrent_params::flag_auto_managed;\n\n\twait_for_listen(ses1, \"ses1\");\n\twait_for_listen(ses2, \"ses1\");\n\n\tpeer_disconnects = 0;\n\n\tboost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0\n\t\t, true, false, true, \"_ssl\", 16 * 1024, &t, false, NULL, true, test.use_ssl_ports);\n\n\tif (test.seed_has_cert)\n\t{\n\t\ttor1.set_ssl_certificate(combine_path(\"ssl\", \"peer_certificate.pem\")\n\t\t\t, combine_path(\"ssl\", \"peer_private_key.pem\")\n\t\t\t, combine_path(\"ssl\", \"dhparams.pem\")\n\t\t\t, \"test\");\n\t}\n\n\tif (test.downloader_has_cert)\n\t{\n\t\ttor2.set_ssl_certificate(combine_path(\"ssl\", \"peer_certificate.pem\")\n\t\t\t, combine_path(\"ssl\", \"peer_private_key.pem\")\n\t\t\t, combine_path(\"ssl\", \"dhparams.pem\")\n\t\t\t, \"test\");\n\t}\n\n\tfor (int i = 0; i < 15; ++i)\n\t{\n\t\tprint_alerts(ses1, \"ses1\", true, true, true, &predicate);\n\t\tprint_alerts(ses2, \"ses2\", true, true, true, &predicate);\n\n\t\ttorrent_status st1 = tor1.status();\n\t\ttorrent_status st2 = tor2.status();\n\n\t\tif (i % 10 == 0)\n\t\t{\n\t\t\tstd::cerr << time_now_string() << \" \"\n\t\t\t\t<< \"\\033[32m\" << int(st1.download_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t\t<< \"\\033[33m\" << int(st1.upload_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t\t<< \"\\033[0m\" << int(st1.progress * 100) << \"% \"\n\t\t\t\t<< st1.num_peers\n\t\t\t\t<< \": \"\n\t\t\t\t<< \"\\033[32m\" << int(st2.download_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t\t<< \"\\033[31m\" << int(st2.upload_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t\t<< \"\\033[0m\" << int(st2.progress * 100) << \"% \"\n\t\t\t\t<< st2.num_peers\n\t\t\t\t<< \" cc: \" << st2.connect_candidates\n\t\t\t\t<< std::endl;\n\t\t}\n\n\t\tif (peer_disconnects == 2) break;\n\n\t\tif (st2.is_finished) break;\n\n\t\tif (st2.state != torrent_status::downloading)\n\t\t{\n\t\t\tstatic char const* state_str[] =\t\n\t\t\t\t{\"checking (q)\", \"checking\", \"dl metadata\"\n\t\t\t\t, \"downloading\", \"finished\", \"seeding\", \"allocating\", \"checking (r)\"};\n\t\t\tstd::cerr << \"st2 state: \" << state_str[st2.state] << std::endl;\n\t\t}\n\n\t\tTEST_CHECK(st1.state == torrent_status::seeding\n\t\t\t|| st1.state == torrent_status::checking_files);\n\t\tTEST_CHECK(st2.state == torrent_status::downloading);\n\n\t\ttest_sleep(100);\n\t}\n\n\tTEST_CHECK(tor2.status().is_seeding == test.expected_to_complete);\n}\n\nint test_main()\n{\n\tusing namespace libtorrent;\n\n\tfor (int i = 0; i < sizeof(test_config)\/sizeof(test_config[0]); ++i)\n\t\ttest_ssl(i);\n\t\n\terror_code ec;\n\tremove_all(\"tmp1_ssl\", ec);\n\tremove_all(\"tmp2_ssl\", ec);\n\n\treturn 0;\n}\n\n\n\nfix test_ssl for trunk, where tests are run in separate directories\/*\n\nCopyright (c) 2013, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n#include \"libtorrent\/thread.hpp\"\n#include \"libtorrent\/file.hpp\"\n#include \n#include \n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n#include \n#include \n\nusing namespace libtorrent;\nusing boost::tuples::ignore;\n\nint const alert_mask = alert::all_categories\n& ~alert::progress_notification\n& ~alert::stats_notification;\n\nstruct test_config_t\n{\n\tchar const* name;\n\tbool use_ssl_ports;\n\tbool seed_has_cert;\n\tbool downloader_has_cert;\n\tbool expected_to_complete;\n};\n\ntest_config_t test_config[] =\n{\n\t{\"nobody has a cert (connect to regular port)\", false, false, false, false},\n\t{\"nobody has a cert (connect to ssl port)\", true, false, false, false},\n\t{\"seed has a cert, but not downloader (connect to regular port)\", false, true, false, false},\n\t{\"seed has a cert, but not downloader (connect to ssl port)\", true, true, false, false},\n\t{\"downloader has a cert, but not seed (connect to regular port)\", false, false, true, false},\n\t{\"downloader has a cert, but not seed (connect to ssl port)\", true, false, true, false},\n\t{\"both downloader and seed has a cert (connect to regular port)\", false, true, true, false},\n#ifdef TORRENT_USE_OPENSSL\n\t{\"both downloader and seed has a cert (connect to ssl port)\", true, true, true, true},\n#else\n\t{\"both downloader and seed has a cert (connect to ssl port)\", true, true, true, false},\n#endif\n};\n\nint peer_disconnects = 0;\n\nbool predicate(alert* a)\n{\n\tif (peer_disconnected_alert* p = alert_cast(a))\n\t\t++peer_disconnects;\n\treturn false;\n}\n\nvoid test_ssl(int test_idx)\n{\n\ttest_config_t const& test = test_config[test_idx];\n\n\tfprintf(stderr, \"\\n%s TEST: %s\\n\\n\", time_now_string(), test.name);\n\n\t\/\/ in case the previous run was terminated\n\terror_code ec;\n\tremove_all(\"tmp1_ssl\", ec);\n\tremove_all(\"tmp2_ssl\", ec);\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48075, 49000), \"0.0.0.0\", 0, alert_mask);\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49075, 50000), \"0.0.0.0\", 0, alert_mask);\n\n\tsession_settings sett;\n\t\/\/ this disables outgoing SSL connections\n\tsett.ssl_listen = 0;\n\tif (!test.downloader_has_cert) ses2.set_settings(sett);\n\n\ttorrent_handle tor1;\n\ttorrent_handle tor2;\n\n\tcreate_directory(\"tmp1_ssl\", ec);\n\tstd::ofstream file(\"tmp1_ssl\/temporary\");\n\tboost::intrusive_ptr t = ::create_torrent(&file, 16 * 1024, 13, false, \"..\/ssl\/root_ca_cert.pem\");\n\tfile.close();\n\n\tadd_torrent_params addp;\n\taddp.flags &= ~add_torrent_params::flag_paused;\n\taddp.flags &= ~add_torrent_params::flag_auto_managed;\n\n\twait_for_listen(ses1, \"ses1\");\n\twait_for_listen(ses2, \"ses1\");\n\n\tpeer_disconnects = 0;\n\n\tboost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0\n\t\t, true, false, true, \"_ssl\", 16 * 1024, &t, false, NULL, true, test.use_ssl_ports);\n\n\tif (test.seed_has_cert)\n\t{\n\t\ttor1.set_ssl_certificate(\n\t\t\tcombine_path(\"..\", combine_path(\"ssl\", \"peer_certificate.pem\"))\n\t\t\t, combine_path(\"..\", combine_path(\"ssl\", \"peer_private_key.pem\"))\n\t\t\t, combine_path(\"..\", combine_path(\"ssl\", \"dhparams.pem\"))\n\t\t\t, \"test\");\n\t}\n\n\tif (test.downloader_has_cert)\n\t{\n\t\ttor2.set_ssl_certificate(\n\t\t\tcombine_path(\"..\", combine_path(\"ssl\", \"peer_certificate.pem\"))\n\t\t\t, combine_path(\"..\", combine_path(\"ssl\", \"peer_private_key.pem\"))\n\t\t\t, combine_path(\"..\", combine_path(\"ssl\", \"dhparams.pem\"))\n\t\t\t, \"test\");\n\t}\n\n\tfor (int i = 0; i < 15; ++i)\n\t{\n\t\tprint_alerts(ses1, \"ses1\", true, true, true, &predicate);\n\t\tprint_alerts(ses2, \"ses2\", true, true, true, &predicate);\n\n\t\ttorrent_status st1 = tor1.status();\n\t\ttorrent_status st2 = tor2.status();\n\n\t\tif (i % 10 == 0)\n\t\t{\n\t\t\tstd::cerr << time_now_string() << \" \"\n\t\t\t\t<< \"\\033[32m\" << int(st1.download_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t\t<< \"\\033[33m\" << int(st1.upload_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t\t<< \"\\033[0m\" << int(st1.progress * 100) << \"% \"\n\t\t\t\t<< st1.num_peers\n\t\t\t\t<< \": \"\n\t\t\t\t<< \"\\033[32m\" << int(st2.download_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t\t<< \"\\033[31m\" << int(st2.upload_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t\t<< \"\\033[0m\" << int(st2.progress * 100) << \"% \"\n\t\t\t\t<< st2.num_peers\n\t\t\t\t<< \" cc: \" << st2.connect_candidates\n\t\t\t\t<< std::endl;\n\t\t}\n\n\t\tif (peer_disconnects == 2) break;\n\n\t\tif (st2.is_finished) break;\n\n\t\tif (st2.state != torrent_status::downloading)\n\t\t{\n\t\t\tstatic char const* state_str[] =\t\n\t\t\t\t{\"checking (q)\", \"checking\", \"dl metadata\"\n\t\t\t\t, \"downloading\", \"finished\", \"seeding\", \"allocating\", \"checking (r)\"};\n\t\t\tstd::cerr << \"st2 state: \" << state_str[st2.state] << std::endl;\n\t\t}\n\n\t\tTEST_CHECK(st1.state == torrent_status::seeding\n\t\t\t|| st1.state == torrent_status::checking_files);\n\t\tTEST_CHECK(st2.state == torrent_status::downloading);\n\n\t\ttest_sleep(100);\n\t}\n\n\tTEST_CHECK(tor2.status().is_seeding == test.expected_to_complete);\n}\n\nint test_main()\n{\n\tusing namespace libtorrent;\n\n\tfor (int i = 0; i < sizeof(test_config)\/sizeof(test_config[0]); ++i)\n\t\ttest_ssl(i);\n\t\n\terror_code ec;\n\tremove_all(\"tmp1_ssl\", ec);\n\tremove_all(\"tmp2_ssl\", ec);\n\n\treturn 0;\n}\n\n\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"Trace.h\"\n#include \"ServerEngine.h\"\n#include \"NodeSfc.h\"\n#include \"NodeDCMotor.h\"\n#include \"NodePid.h\"\n#include \"NodePython.h\"\n#include \"NodePass.h\"\n#include \"NodeTimer.h\"\n#include \"NodeServo.h\"\n#include \"ConfigReader.h\"\n#include \"NodeDb.h\"\n#include \"Process.h\"\n#include \"SocketClient.h\"\n\n\nusing namespace Arro;\nusing namespace std;\n\n\n\/\/Process::Process(NodeDb& db, const string& instance):\n\/\/ RealNode{},\n\/\/ m_trace{\"Process\", true},\n\/\/ m_nodeDb{db},\n\/\/ m_device{nullptr},\n\/\/ m_doRunCycle{false},\n\/\/ m_name{instance},\n\/\/ m_webComponents(nullptr) {\n\/\/\n\/\/ m_trace.println(\"Creating sfc \" + instance + \"._sfc\");\n\/\/\n\/\/ m_trace.println(\"---> Never used?? <--- \");\n\/\/\n\/\/ db.registerNode(this, instance + \"._sfc\");\n\/\/\n\/\/}\n\nProcess::Process(NodeDb& db, const string& url, const string& instance, StringMap params, TiXmlElement* elt):\n RealNode{},\n m_trace{\"Process\", true},\n m_nodeDb{db},\n m_device{nullptr},\n m_doRunCycle{false},\n m_name{instance} {\n\n m_trace.println(\"Creating instance of \" + url);\n\n\n getPrimitive(url, instance, params, elt);\n\n std::map::iterator iter;\n\n for (iter = params.begin(); iter != params.end(); ++iter) {\n m_trace.println(\" parameter \" + iter->first + \" \" + iter->second);\n\n auto kv = new arro::KeyValuePair();\n kv->set_key(iter->first.c_str());\n kv->set_value(iter->second.c_str());\n MessageBuf msg(new string(kv->SerializeAsString()));\n free(kv);\n m_device->handleMessage(msg, \"config\");\n }\n\n db.registerNode(this, instance);\n\n\n}\n\nProcess::~Process() {\n if(m_device) delete m_device;\n}\n\nvoid\nProcess::sendParameters(StringMap& params) {\n std::map::iterator iter;\n\n\/\/ auto block = new arro::ParameterBlock();\n\/\/\n\/\/ for (iter = params.begin(); iter != params.end(); ++iter) {\n\/\/ m_trace.println(\" parameter \" + iter->first + \" \" + iter->second);\n\/\/\n\/\/ auto kv = block->add_kv();\n\/\/\n\/\/ kv->set_key(iter->first.c_str());\n\/\/ kv->set_value(iter->second.c_str());\n\/\/ }\n\/\/\n auto config = new arro::_Config();\n\n auto map = config->value();\n for (iter = params.begin(); iter != params.end(); ++iter) {\n m_trace.println(\" parameter \" + iter->first + \" \" + iter->second);\n\n map[iter->first] = iter->second;\n }\n\n \/\/MessageBuf msg(new string(block->SerializeAsString()));\n \/\/free(block);\n MessageBuf msg(new string(config->SerializeAsString()));\n free(config);\n\n \/\/ get _config input and send a message to it.\n auto input = getInput(\"_config\");\n input->handleMessage(msg);\n}\n\n\nvoid\nProcess::runCycle() {\n if(m_doRunCycle) {\n m_device->runCycle();\n m_doRunCycle = false;\n }\n}\n\nvoid\nProcess::registerInput(const string& interfName, bool enableRunCycle) {\n \/\/ only need to capture enableRunCycle\n m_nodeDb.registerNodeInput(this, interfName, [=](const MessageBuf& msg, const std::string& interfaceName) {\n if(enableRunCycle) {\n m_doRunCycle = true;\n }\n m_device->handleMessage(msg, interfaceName);\n });\n}\n\nvoid\nProcess::registerOutput(const string& interfaceName) {\n m_nodeDb.registerNodeOutput(this, interfaceName);\n}\n\n\/**\n *\n * @param input\n * @return Shared pointer to message. Note: if not initialized then\n * pointer may be nullptr.\n *\/\nMessageBuf\nProcess::getInputData(NodeSingleInput* input) const {\n return input->getData();\n}\n\n\nNodeSingleInput*\nProcess::getInput(const string& name) const {\n auto in = m_nodeDb.getInput(getName() + \".\" + name);\n if(in) {\n return in;\n } else {\n m_trace.println(\"no such input registered: \" + getName() + \".\" + name);\n SendToConsole(string(\"Program uses unknown input: \") + getName() + \".\" + name);\n throw std::runtime_error(\"No such input registered: \" + getName() + \".\" + name);\n }\n}\n\nNodeMultiOutput*\nProcess::getOutput(const string& name) const {\n auto out = m_nodeDb.getOutput(getName() + \".\" + name);\n if(out) {\n return out;\n } else {\n m_trace.println(\"no such output registered: \" + getName() + \".\" + name);\n SendToConsole(string(\"Program uses unknown output: \") + getName() + \".\" + name);\n throw std::runtime_error(\"No such output registered: \" + getName() + \".\" + name);\n }\n}\n\nvoid\nProcess::setOutputData(NodeMultiOutput* output, google::protobuf::MessageLite* value) const {\n output->submitMessage(value);\n}\n\n\nvoid\nProcess::getPrimitive(const string& url, const string& instance, StringMap& params, TiXmlElement* elt) {\n m_device = nullptr;\n Factory factory;\n\n if(url.find(\"Python:\") == 0) {\n m_trace.println(\"new NodePython(\" + instance + \")\");\n try {\n string className = url.substr(7);\n if(ServerEngine::getFactory(\"Python\", factory)) {\n m_device = factory(this, className, params, nullptr);\n }\n } catch(out_of_range &) {\n throw std::runtime_error(\"Invalid URL for Python node \" + url);\n }\n } else if(url.find(\"UiIn:\") == 0) {\n m_trace.println(\"new NodeUiIn(\" + instance + \")\");\n try {\n if(ServerEngine::getFactory(\"_UiUserInput\", factory)) {\n m_device = factory(this, \"\", params, elt);\n }\n } catch(out_of_range &) {\n throw std::runtime_error(\"Invalid URL for SFC node \" + url);\n }\n } else if(url.find(\"UiOut:\") == 0) {\n m_trace.println(\"new NodeUiOut(\" + instance + \")\");\n try {\n if(ServerEngine::getFactory(\"_UiUserDisplay\", factory)) {\n m_device = factory(this, \"\", params, elt);\n }\n } catch(out_of_range &) {\n throw std::runtime_error(\"Invalid URL for SFC node \" + url);\n }\n } else if(url.find(\"Sfc:\") == 0) {\n StringMap params{};\n m_trace.println(\"new NodeSfc(\" + instance + \")\");\n try {\n if(ServerEngine::getFactory(\"_SFC\", factory)) {\n m_device = factory(this, \"\", params, elt);\n }\n } catch(out_of_range &) {\n throw std::runtime_error(\"Invalid URL for SFC node \" + url);\n }\n }\n else if(url.find(\"Native:\") == 0) {\n try {\n string className = url.substr(7);\n\n if(className == \"pass\") {\n }\n else if(ServerEngine::getFactory(className, factory)) {\n m_trace.println(\"new \" + className + \"(\" + instance + \")\");\n m_device = factory(this, instance, params, nullptr);\n }\n else {\n m_trace.println(\"unknown node\" + instance );\n SendToConsole(string(\"unknown node \") + className);\n }\n } catch(out_of_range &) {\n m_trace.println(\"native node not found\");\n }\n }\n if(m_device == nullptr) {\n m_trace.println(\"Node module not found \" + url);\n throw std::runtime_error(\"Node module not found \" + url);\n }\n}\n\n\/**\n * TODO this is not the happiest function, it is for SFC only. Should be something more elegant.\n * @param sfc\n *\/\nvoid\nProcess::registerSfc(const std::string& name, Process* sfc) {\n ((NodeSfc*)m_device)->registerSfc(name, (NodeSfc*)(sfc->m_device));\n}\n\n\n\nImprove parameter passing using _Config#include \n#include \n#include \n\n#include \"Trace.h\"\n#include \"ServerEngine.h\"\n#include \"NodeSfc.h\"\n#include \"NodeDCMotor.h\"\n#include \"NodePid.h\"\n#include \"NodePython.h\"\n#include \"NodePass.h\"\n#include \"NodeTimer.h\"\n#include \"NodeServo.h\"\n#include \"ConfigReader.h\"\n#include \"NodeDb.h\"\n#include \"Process.h\"\n#include \"SocketClient.h\"\n\n\nusing namespace Arro;\nusing namespace std;\n\n\n\/\/Process::Process(NodeDb& db, const string& instance):\n\/\/ RealNode{},\n\/\/ m_trace{\"Process\", true},\n\/\/ m_nodeDb{db},\n\/\/ m_device{nullptr},\n\/\/ m_doRunCycle{false},\n\/\/ m_name{instance},\n\/\/ m_webComponents(nullptr) {\n\/\/\n\/\/ m_trace.println(\"Creating sfc \" + instance + \"._sfc\");\n\/\/\n\/\/ m_trace.println(\"---> Never used?? <--- \");\n\/\/\n\/\/ db.registerNode(this, instance + \"._sfc\");\n\/\/\n\/\/}\n\nProcess::Process(NodeDb& db, const string& url, const string& instance, StringMap params, TiXmlElement* elt):\n RealNode{},\n m_trace{\"Process\", true},\n m_nodeDb{db},\n m_device{nullptr},\n m_doRunCycle{false},\n m_name{instance} {\n\n m_trace.println(\"Creating instance of \" + url);\n\n\n getPrimitive(url, instance, params, elt);\n\n std::map::iterator iter;\n\n for (iter = params.begin(); iter != params.end(); ++iter) {\n m_trace.println(\" parameter \" + iter->first + \" \" + iter->second);\n\n auto kv = new arro::KeyValuePair();\n kv->set_key(iter->first.c_str());\n kv->set_value(iter->second.c_str());\n MessageBuf msg(new string(kv->SerializeAsString()));\n free(kv);\n m_device->handleMessage(msg, \"config\");\n }\n\n db.registerNode(this, instance);\n\n\n}\n\nProcess::~Process() {\n if(m_device) delete m_device;\n}\n\nvoid\nProcess::sendParameters(StringMap& params) {\n std::map::iterator iter;\n\n auto config = new arro::_Config();\n\n auto map = config->value();\n for (iter = params.begin(); iter != params.end(); ++iter) {\n m_trace.println(\" parameter \" + iter->first + \" \" + iter->second);\n\n (*config->mutable_value())[iter->first] = iter->second;\n }\n\n MessageBuf msg(new string(config->SerializeAsString()));\n free(config);\n\n \/\/ get _config input and send a message to it.\n auto input = getInput(\"_config\");\n input->handleMessage(msg);\n}\n\n\nvoid\nProcess::runCycle() {\n if(m_doRunCycle) {\n m_device->runCycle();\n m_doRunCycle = false;\n }\n}\n\nvoid\nProcess::registerInput(const string& interfName, bool enableRunCycle) {\n \/\/ only need to capture enableRunCycle\n m_nodeDb.registerNodeInput(this, interfName, [=](const MessageBuf& msg, const std::string& interfaceName) {\n if(enableRunCycle) {\n m_doRunCycle = true;\n }\n m_device->handleMessage(msg, interfaceName);\n });\n}\n\nvoid\nProcess::registerOutput(const string& interfaceName) {\n m_nodeDb.registerNodeOutput(this, interfaceName);\n}\n\n\/**\n *\n * @param input\n * @return Shared pointer to message. Note: if not initialized then\n * pointer may be nullptr.\n *\/\nMessageBuf\nProcess::getInputData(NodeSingleInput* input) const {\n return input->getData();\n}\n\n\nNodeSingleInput*\nProcess::getInput(const string& name) const {\n auto in = m_nodeDb.getInput(getName() + \".\" + name);\n if(in) {\n return in;\n } else {\n m_trace.println(\"no such input registered: \" + getName() + \".\" + name);\n SendToConsole(string(\"Program uses unknown input: \") + getName() + \".\" + name);\n throw std::runtime_error(\"No such input registered: \" + getName() + \".\" + name);\n }\n}\n\nNodeMultiOutput*\nProcess::getOutput(const string& name) const {\n auto out = m_nodeDb.getOutput(getName() + \".\" + name);\n if(out) {\n return out;\n } else {\n m_trace.println(\"no such output registered: \" + getName() + \".\" + name);\n SendToConsole(string(\"Program uses unknown output: \") + getName() + \".\" + name);\n throw std::runtime_error(\"No such output registered: \" + getName() + \".\" + name);\n }\n}\n\nvoid\nProcess::setOutputData(NodeMultiOutput* output, google::protobuf::MessageLite* value) const {\n output->submitMessage(value);\n}\n\n\nvoid\nProcess::getPrimitive(const string& url, const string& instance, StringMap& params, TiXmlElement* elt) {\n m_device = nullptr;\n Factory factory;\n\n if(url.find(\"Python:\") == 0) {\n m_trace.println(\"new NodePython(\" + instance + \")\");\n try {\n string className = url.substr(7);\n if(ServerEngine::getFactory(\"Python\", factory)) {\n m_device = factory(this, className, params, nullptr);\n }\n } catch(out_of_range &) {\n throw std::runtime_error(\"Invalid URL for Python node \" + url);\n }\n } else if(url.find(\"UiIn:\") == 0) {\n m_trace.println(\"new NodeUiIn(\" + instance + \")\");\n try {\n if(ServerEngine::getFactory(\"_UiUserInput\", factory)) {\n m_device = factory(this, \"\", params, elt);\n }\n } catch(out_of_range &) {\n throw std::runtime_error(\"Invalid URL for SFC node \" + url);\n }\n } else if(url.find(\"UiOut:\") == 0) {\n m_trace.println(\"new NodeUiOut(\" + instance + \")\");\n try {\n if(ServerEngine::getFactory(\"_UiUserDisplay\", factory)) {\n m_device = factory(this, \"\", params, elt);\n }\n } catch(out_of_range &) {\n throw std::runtime_error(\"Invalid URL for SFC node \" + url);\n }\n } else if(url.find(\"Sfc:\") == 0) {\n StringMap params{};\n m_trace.println(\"new NodeSfc(\" + instance + \")\");\n try {\n if(ServerEngine::getFactory(\"_SFC\", factory)) {\n m_device = factory(this, \"\", params, elt);\n }\n } catch(out_of_range &) {\n throw std::runtime_error(\"Invalid URL for SFC node \" + url);\n }\n }\n else if(url.find(\"Native:\") == 0) {\n try {\n string className = url.substr(7);\n\n if(className == \"pass\") {\n }\n else if(ServerEngine::getFactory(className, factory)) {\n m_trace.println(\"new \" + className + \"(\" + instance + \")\");\n m_device = factory(this, instance, params, nullptr);\n }\n else {\n m_trace.println(\"unknown node\" + instance );\n SendToConsole(string(\"unknown node \") + className);\n }\n } catch(out_of_range &) {\n m_trace.println(\"native node not found\");\n }\n }\n if(m_device == nullptr) {\n m_trace.println(\"Node module not found \" + url);\n throw std::runtime_error(\"Node module not found \" + url);\n }\n}\n\n\/**\n * TODO this is not the happiest function, it is for SFC only. Should be something more elegant.\n * @param sfc\n *\/\nvoid\nProcess::registerSfc(const std::string& name, Process* sfc) {\n ((NodeSfc*)m_device)->registerSfc(name, (NodeSfc*)(sfc->m_device));\n}\n\n\n\n<|endoftext|>"} {"text":"#include \n\nbool FlashClass::erasePage(void* adr) {\n NVMADDR = KVA_TO_PA((unsigned int) adr);\n return doNvmOp(nvmopErasePage);\n}\n\nbool FlashClass::writeWord(void* adr, uint32_t val) {\n NVMADDR = KVA_TO_PA((unsigned int) adr);\n NVMDATA = val;\n return doNvmOp(nvmopWriteWord);\n}\n\nbool FlashClass::writeRow(void* adr, void *val) {\n\tbool blank = true;\n\tfor (int i = 0; i < ROW_SIZE; i++) {\n\t\tif (((char *)val)[i] != 0xFF) {\n\t\t\tblank = false;\t\t\n\t\t}\n\t}\n\tif (blank) {\n\t\treturn 0;\n\t}\n NVMADDR = KVA_TO_PA((unsigned int) adr);\n NVMSRCADDR = KVA_TO_PA((uint32_t)val);\n return doNvmOp(nvmopWriteRow);\n}\n\nbool FlashClass::clearNvmError() {\n\treturn doNvmOp(nvmopNop);\n}\n\nbool FlashClass::isNvmError() {\n\treturn (NVMCON & (_NVMCON_WRERR_MASK | _NVMCON_LVDERR_MASK)) ? true : false;\n}\n\nbool __attribute__((nomips16)) FlashClass::doNvmOp(uint32_t nvmop) {\n int nvmSt;\n int intSt;\n uint32_t tm;\n\n\n \/\/ M00TODO: When DMA operations are supported in the core, need\n \/\/ to add code here to suspend DMA during the NVM operation.\n\n intSt = disableInterrupts();\n NVMCON = NVMCON_WREN | nvmop;\n\n tm = _CP0_GET_COUNT();\n while (_CP0_GET_COUNT() - tm < ((F_CPU * 6) \/ 2000000));\n\n NVMKEY = 0xAA996655;\n NVMKEY = 0x556699AA;\n NVMCONSET = NVMCON_WR;\n\n while (NVMCON & NVMCON_WR) {\n\t\tcontinue;\n }\n\n NVMCONCLR = NVMCON_WREN;\n\n \/\/M00TODO: Resume a suspended DMA operation\n\n restoreInterrupts(intSt);\n return(isNvmError());\n}\n\nbool FlashClass::loadPage(void *adr) {\n uint32_t *ptr = (uint32_t *)adr;\n\n ptr = (uint32_t *)((uint32_t)ptr & ~((PAGE_SIZE*4)-1));\n _page_address = (uint32_t)ptr;\n\n for (int i = 0; i < PAGE_SIZE; i++) {\n _flash_buffer[i] = *ptr;\n ptr++;\n }\n return true;\n}\n\nbool FlashClass::savePage() {\n uint32_t *ptr = (uint32_t *)_page_address;\n erasePage(ptr);\n uint32_t *p = ptr;\n for (int i = 0; i < PAGE_SIZE; i++) {\n writeWord(ptr, _flash_buffer[i]);\n ptr++;\n }\n return true;\n}\n\nbool FlashClass::writePageWord(void *adr, uint32_t val) {\n uint32_t a = (uint32_t)adr - _page_address;\n if (a > PAGE_SIZE * 4) {\n return false;\n }\n _flash_buffer[a\/4] = val;\n return true;\n}\n\nbool FlashClass::verifyPage() {\n uint32_t *ptr = (uint32_t *)_page_address;\n for (int i = 0; i < PAGE_SIZE; i++) {\n if (*ptr != _flash_buffer[i]) {\n return false;\n }\n ptr++;\n }\n return true;\n}\n\nFlashClass Flash;\nCleaned up compiler warnings#include \n\nbool FlashClass::erasePage(void* adr) {\n NVMADDR = KVA_TO_PA((unsigned int) adr);\n return doNvmOp(nvmopErasePage);\n}\n\nbool FlashClass::writeWord(void* adr, uint32_t val) {\n NVMADDR = KVA_TO_PA((unsigned int) adr);\n NVMDATA = val;\n return doNvmOp(nvmopWriteWord);\n}\n\nbool FlashClass::writeRow(void* adr, void *val) {\n\tbool blank = true;\n\tfor (int i = 0; i < ROW_SIZE; i++) {\n\t\tif (((char *)val)[i] != 0xFF) {\n\t\t\tblank = false;\t\t\n\t\t}\n\t}\n\tif (blank) {\n\t\treturn 0;\n\t}\n NVMADDR = KVA_TO_PA((unsigned int) adr);\n NVMSRCADDR = KVA_TO_PA((uint32_t)val);\n return doNvmOp(nvmopWriteRow);\n}\n\nbool FlashClass::clearNvmError() {\n\treturn doNvmOp(nvmopNop);\n}\n\nbool FlashClass::isNvmError() {\n\treturn (NVMCON & (_NVMCON_WRERR_MASK | _NVMCON_LVDERR_MASK)) ? true : false;\n}\n\nbool __attribute__((nomips16)) FlashClass::doNvmOp(uint32_t nvmop) {\n int intSt;\n uint32_t tm;\n\n\n \/\/ M00TODO: When DMA operations are supported in the core, need\n \/\/ to add code here to suspend DMA during the NVM operation.\n\n intSt = disableInterrupts();\n NVMCON = NVMCON_WREN | nvmop;\n\n tm = _CP0_GET_COUNT();\n while (_CP0_GET_COUNT() - tm < ((F_CPU * 6) \/ 2000000));\n\n NVMKEY = 0xAA996655;\n NVMKEY = 0x556699AA;\n NVMCONSET = NVMCON_WR;\n\n while (NVMCON & NVMCON_WR) {\n\t\tcontinue;\n }\n\n NVMCONCLR = NVMCON_WREN;\n\n \/\/M00TODO: Resume a suspended DMA operation\n\n restoreInterrupts(intSt);\n return(isNvmError());\n}\n\nbool FlashClass::loadPage(void *adr) {\n uint32_t *ptr = (uint32_t *)adr;\n\n ptr = (uint32_t *)((uint32_t)ptr & ~((PAGE_SIZE*4)-1));\n _page_address = (uint32_t)ptr;\n\n for (int i = 0; i < PAGE_SIZE; i++) {\n _flash_buffer[i] = *ptr;\n ptr++;\n }\n return true;\n}\n\nbool FlashClass::savePage() {\n uint32_t *ptr = (uint32_t *)_page_address;\n erasePage(ptr);\n for (int i = 0; i < PAGE_SIZE; i++) {\n writeWord(ptr, _flash_buffer[i]);\n ptr++;\n }\n return true;\n}\n\nbool FlashClass::writePageWord(void *adr, uint32_t val) {\n uint32_t a = (uint32_t)adr - _page_address;\n if (a > PAGE_SIZE * 4) {\n return false;\n }\n _flash_buffer[a\/4] = val;\n return true;\n}\n\nbool FlashClass::verifyPage() {\n uint32_t *ptr = (uint32_t *)_page_address;\n for (int i = 0; i < PAGE_SIZE; i++) {\n if (*ptr != _flash_buffer[i]) {\n return false;\n }\n ptr++;\n }\n return true;\n}\n\nFlashClass Flash;\n<|endoftext|>"} {"text":"#include \"Mempoke.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nCoreRequest *device = 0;\nDMARequest *dma = 0;\nPortalAlloc *dstAlloc;\nunsigned int *dstBuffer = 0;\nint numWords = 16 << 3;\nsize_t test_sz = numWords*sizeof(unsigned int);\nsize_t alloc_sz = test_sz;\nsem_t conf_sem;\n\nvoid dump(const char *prefix, char *buf, size_t len)\n{\n fprintf(stderr, \"%s \", prefix);\n for (int i = 0; i < (len > 16 ? 16 : len) ; i++)\n\tfprintf(stderr, \"%02x\", (unsigned char)buf[i]);\n fprintf(stderr, \"\\n\");\n}\n\nclass TestDMAIndication : public DMAIndication\n{\n virtual void reportStateDbg(DmaDbgRec& rec){\n fprintf(stderr, \"reportStateDbg: {x:%08lx y:%08lx z:%08lx w:%08lx}\\n\", rec.x,rec.y,rec.z,rec.w);\n }\n virtual void configResp(unsigned long channelId){\n fprintf(stderr, \"configResp: %lx\\n\", channelId);\n sem_post(&conf_sem);\n }\n virtual void sglistResp(unsigned long channelId){\n fprintf(stderr, \"sglistResp: %lx\\n\", channelId);\n }\n virtual void parefResp(unsigned long channelId){\n fprintf(stderr, \"parefResp: %lx\\n\", channelId);\n }\n};\n\nclass TestCoreIndication : public CoreIndication\n{\n virtual void readWordResult (S0 &s){\n fprintf(stderr, \"readWordResult(S0{a:%ld,b:%ld})\\n\", s.a, s.b);\n }\n virtual void writeWordResult (S0 &s){\n fprintf(stderr, \"writeWordResult(S0{a:%ld,b:%ld})\\n\", s.a, s.b);\n }\n};\n\nint main(int argc, const char **argv)\n{\n fprintf(stderr, \"%s %s\\n\", __DATE__, __TIME__);\n device = CoreRequest::createCoreRequest(new TestCoreIndication);\n dma = DMARequest::createDMARequest(new TestDMAIndication);\n\n if(sem_init(&conf_sem, 1, 0)){\n fprintf(stderr, \"failed to init conf_sem\\n\");\n return -1;\n }\n\n fprintf(stderr, \"allocating memory...\\n\");\n dma->alloc(alloc_sz, &dstAlloc);\n dstBuffer = (unsigned int *)mmap(0, alloc_sz, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, dstAlloc.header.fd, 0);\n\n pthread_t tid;\n fprintf(stderr, \"creating exec thread\\n\");\n if(pthread_create(&tid, NULL, portalExec, NULL)){\n fprintf(stderr, \"error creating exec thread\\n\");\n exit(1);\n }\n\n unsigned int ref_dstAlloc = dma->reference(&dstAlloc);\n\n for (int i = 0; i < numWords; i++){\n dstBuffer[i] = i;\n }\n \n dma->dCacheFlushInval(&dstAlloc, dstBuffer);\n fprintf(stderr, \"flush and invalidate complete\\n\");\n \n dma->configChan(1, 0, ref_dstAlloc, 2);\n sem_wait(&conf_sem);\n \n dma->configChan(0, 0, ref_dstAlloc, 2);\n sem_wait(&conf_sem);\n\n fprintf(stderr, \"main about to issue requests\\n\");\n\n device->readWord(5*8);\n sleep(1);\n S0 s = {3,4};\n device->writeWord(6*8,s);\n sleep(1);\n device->readWord(6*8);\n \n fprintf(stderr, \"main going to sleep\\n\");\n while(true){sleep(1);}\n}\nfix corresponding uses to add indirection for dstAlloc#include \"Mempoke.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nCoreRequest *device = 0;\nDMARequest *dma = 0;\nPortalAlloc *dstAlloc;\nunsigned int *dstBuffer = 0;\nint numWords = 16 << 3;\nsize_t test_sz = numWords*sizeof(unsigned int);\nsize_t alloc_sz = test_sz;\nsem_t conf_sem;\n\nvoid dump(const char *prefix, char *buf, size_t len)\n{\n fprintf(stderr, \"%s \", prefix);\n for (int i = 0; i < (len > 16 ? 16 : len) ; i++)\n\tfprintf(stderr, \"%02x\", (unsigned char)buf[i]);\n fprintf(stderr, \"\\n\");\n}\n\nclass TestDMAIndication : public DMAIndication\n{\n virtual void reportStateDbg(DmaDbgRec& rec){\n fprintf(stderr, \"reportStateDbg: {x:%08lx y:%08lx z:%08lx w:%08lx}\\n\", rec.x,rec.y,rec.z,rec.w);\n }\n virtual void configResp(unsigned long channelId){\n fprintf(stderr, \"configResp: %lx\\n\", channelId);\n sem_post(&conf_sem);\n }\n virtual void sglistResp(unsigned long channelId){\n fprintf(stderr, \"sglistResp: %lx\\n\", channelId);\n }\n virtual void parefResp(unsigned long channelId){\n fprintf(stderr, \"parefResp: %lx\\n\", channelId);\n }\n};\n\nclass TestCoreIndication : public CoreIndication\n{\n virtual void readWordResult (S0 &s){\n fprintf(stderr, \"readWordResult(S0{a:%ld,b:%ld})\\n\", s.a, s.b);\n }\n virtual void writeWordResult (S0 &s){\n fprintf(stderr, \"writeWordResult(S0{a:%ld,b:%ld})\\n\", s.a, s.b);\n }\n};\n\nint main(int argc, const char **argv)\n{\n fprintf(stderr, \"%s %s\\n\", __DATE__, __TIME__);\n device = CoreRequest::createCoreRequest(new TestCoreIndication);\n dma = DMARequest::createDMARequest(new TestDMAIndication);\n\n if(sem_init(&conf_sem, 1, 0)){\n fprintf(stderr, \"failed to init conf_sem\\n\");\n return -1;\n }\n\n fprintf(stderr, \"allocating memory...\\n\");\n dma->alloc(alloc_sz, &dstAlloc);\n dstBuffer = (unsigned int *)mmap(0, alloc_sz, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, dstAlloc->header.fd, 0);\n\n pthread_t tid;\n fprintf(stderr, \"creating exec thread\\n\");\n if(pthread_create(&tid, NULL, portalExec, NULL)){\n fprintf(stderr, \"error creating exec thread\\n\");\n exit(1);\n }\n\n unsigned int ref_dstAlloc = dma->reference(dstAlloc);\n\n for (int i = 0; i < numWords; i++){\n dstBuffer[i] = i;\n }\n \n dma->dCacheFlushInval(dstAlloc, dstBuffer);\n fprintf(stderr, \"flush and invalidate complete\\n\");\n \n dma->configChan(1, 0, ref_dstAlloc, 2);\n sem_wait(&conf_sem);\n \n dma->configChan(0, 0, ref_dstAlloc, 2);\n sem_wait(&conf_sem);\n\n fprintf(stderr, \"main about to issue requests\\n\");\n\n device->readWord(5*8);\n sleep(1);\n S0 s = {3,4};\n device->writeWord(6*8,s);\n sleep(1);\n device->readWord(6*8);\n \n fprintf(stderr, \"main going to sleep\\n\");\n while(true){sleep(1);}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Embedded Framework Authors.\n\/\/ Portions copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"libcef\/browser\/resource_request_job.h\"\n\n#include \n#include \n\n#include \"include\/cef_callback.h\"\n#include \"libcef\/browser\/cookie_manager_impl.h\"\n#include \"libcef\/browser\/thread_util.h\"\n#include \"libcef\/common\/request_impl.h\"\n#include \"libcef\/common\/response_impl.h\"\n\n#include \"base\/logging.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/http\/http_response_headers.h\"\n#include \"net\/url_request\/http_user_agent_settings.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nusing net::URLRequestStatus;\n\nnamespace {\n\nbool SetHeaderIfMissing(CefRequest::HeaderMap& headerMap,\n const std::string& name,\n const std::string& value) {\n if (value.empty())\n return false;\n \n CefRequest::HeaderMap::const_iterator it = headerMap.find(name);\n if (it == headerMap.end()) {\n headerMap.insert(std::make_pair(name, value));\n return true;\n }\n\n return false;\n}\n\n} \/\/ namespace\n\n\/\/ Client callback for asynchronous response continuation.\nclass CefResourceRequestJobCallback : public CefCallback {\n public:\n enum Type {\n HEADERS_AVAILABLE,\n BYTES_AVAILABLE,\n };\n\n explicit CefResourceRequestJobCallback(CefResourceRequestJob* job, Type type)\n : job_(job),\n type_(type),\n dest_(NULL),\n dest_size_(0) {}\n\n virtual void Continue() OVERRIDE {\n if (CEF_CURRENTLY_ON_IOT()) {\n \/\/ Currently on IO thread.\n \/\/ Return early if the callback has already been detached.\n if (!job_)\n return;\n\n if (type_ == HEADERS_AVAILABLE) {\n \/\/ Callback for headers available.\n if (!job_->has_response_started()) {\n \/\/ Send header information.\n job_->SendHeaders();\n }\n\n \/\/ This type of callback only ever needs to be called once.\n Detach();\n } else if (type_ == BYTES_AVAILABLE) {\n \/\/ Callback for bytes available.\n if (job_->has_response_started() &&\n job_->GetStatus().is_io_pending()) {\n \/\/ Read the bytes. They should be available but, if not, wait again.\n int bytes_read = 0;\n if (job_->ReadRawData(dest_, dest_size_, &bytes_read)) {\n if (bytes_read > 0) {\n \/\/ Clear the IO_PENDING status.\n job_->SetStatus(URLRequestStatus());\n\n \/\/ Notify about the available bytes.\n job_->NotifyReadComplete(bytes_read);\n\n dest_ = NULL;\n dest_size_ = 0;\n } else {\n \/\/ All done.\n job_->NotifyDone(URLRequestStatus());\n Detach();\n }\n } else if (!job_->GetStatus().is_io_pending()) {\n \/\/ Failed due to an error.\n NOTREACHED() <<\n \"ReadRawData returned false without setting IO as pending\";\n job_->NotifyDone(URLRequestStatus());\n Detach();\n }\n }\n }\n } else {\n \/\/ Execute this method on the IO thread.\n CEF_POST_TASK(CEF_IOT,\n base::Bind(&CefResourceRequestJobCallback::Continue, this));\n }\n }\n\n virtual void Cancel() OVERRIDE {\n if (CEF_CURRENTLY_ON_IOT()) {\n \/\/ Currently on IO thread.\n if (job_)\n job_->Kill();\n } else {\n \/\/ Execute this method on the IO thread.\n CEF_POST_TASK(CEF_IOT,\n base::Bind(&CefResourceRequestJobCallback::Cancel, this));\n }\n }\n\n void Detach() {\n CEF_REQUIRE_IOT();\n job_ = NULL;\n }\n\n void SetDestination(net::IOBuffer* dest, int dest_size) {\n CEF_REQUIRE_IOT();\n dest_ = dest;\n dest_size_ = dest_size;\n }\n\n private:\n CefResourceRequestJob* job_;\n Type type_;\n\n net::IOBuffer* dest_;\n int dest_size_;\n\n IMPLEMENT_REFCOUNTING(Callback);\n};\n\nCefResourceRequestJob::CefResourceRequestJob(\n net::URLRequest* request,\n net::NetworkDelegate* network_delegate,\n CefRefPtr handler)\n : net::URLRequestJob(request, network_delegate),\n handler_(handler),\n remaining_bytes_(0),\n response_cookies_save_index_(0),\n ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {\n}\n\nCefResourceRequestJob::~CefResourceRequestJob() {\n}\n\nvoid CefResourceRequestJob::Start() {\n CEF_REQUIRE_IOT();\n\n cef_request_ = CefRequest::Create();\n\n \/\/ Populate the request data.\n static_cast(cef_request_.get())->Set(request_);\n\n \/\/ Add default headers if not already specified.\n const net::URLRequestContext* context = request_->context();\n if (context) {\n CefRequest::HeaderMap headerMap;\n cef_request_->GetHeaderMap(headerMap);\n bool changed = false;\n\n const net::HttpUserAgentSettings* ua_settings =\n context->http_user_agent_settings();\n if (ua_settings) {\n if (SetHeaderIfMissing(headerMap,\n net::HttpRequestHeaders::kAcceptLanguage,\n ua_settings->GetAcceptLanguage())) {\n changed = true;\n }\n\n if (SetHeaderIfMissing(headerMap,\n net::HttpRequestHeaders::kUserAgent,\n ua_settings->GetUserAgent(request_->url()))) {\n changed = true;\n }\n }\n\n if (changed)\n cef_request_->SetHeaderMap(headerMap);\n }\n\n AddCookieHeaderAndStart();\n}\n\nvoid CefResourceRequestJob::Kill() {\n CEF_REQUIRE_IOT();\n\n \/\/ Notify the handler that the request has been canceled.\n handler_->Cancel();\n\n if (callback_) {\n callback_->Detach();\n callback_ = NULL;\n }\n\n net::URLRequestJob::Kill();\n}\n\nbool CefResourceRequestJob::ReadRawData(net::IOBuffer* dest, int dest_size,\n int* bytes_read) {\n CEF_REQUIRE_IOT();\n\n DCHECK_NE(dest_size, 0);\n DCHECK(bytes_read);\n\n if (remaining_bytes_ == 0) {\n \/\/ No more data to read.\n *bytes_read = 0;\n return true;\n } else if (remaining_bytes_ > 0 && remaining_bytes_ < dest_size) {\n \/\/ The handler knows the content size beforehand.\n dest_size = static_cast(remaining_bytes_);\n }\n\n if (!callback_.get()) {\n \/\/ Create the bytes available callback that will be used until the request\n \/\/ is completed.\n callback_ = new CefResourceRequestJobCallback(this,\n CefResourceRequestJobCallback::BYTES_AVAILABLE);\n }\n\n \/\/ Read response data from the handler.\n bool rv = handler_->ReadResponse(dest->data(), dest_size, *bytes_read,\n callback_.get());\n if (!rv) {\n \/\/ The handler has indicated completion of the request.\n *bytes_read = 0;\n return true;\n } else if (*bytes_read == 0) {\n if (!GetStatus().is_io_pending()) {\n \/\/ Report our status as IO pending.\n SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));\n callback_->SetDestination(dest, dest_size);\n }\n return false;\n } else if (*bytes_read > dest_size) {\n \/\/ Normalize the return value.\n *bytes_read = dest_size;\n }\n\n if (remaining_bytes_ > 0)\n remaining_bytes_ -= *bytes_read;\n\n \/\/ Continue calling this method.\n return true;\n}\n\nvoid CefResourceRequestJob::GetResponseInfo(net::HttpResponseInfo* info) {\n CEF_REQUIRE_IOT();\n\n info->headers = GetResponseHeaders();\n}\n\nbool CefResourceRequestJob::GetResponseCookies(\n std::vector* cookies) {\n CEF_REQUIRE_IOT();\n\n cookies->clear();\n FetchResponseCookies(cookies);\n return true;\n}\n\nbool CefResourceRequestJob::IsRedirectResponse(GURL* location,\n int* http_status_code) {\n CEF_REQUIRE_IOT();\n\n if (redirect_url_.is_valid()) {\n \/\/ Redirect to the new URL.\n *http_status_code = 303;\n location->Swap(&redirect_url_);\n return true;\n }\n\n if (response_.get()) {\n \/\/ Check for HTTP 302 or HTTP 303 redirect.\n int status = response_->GetStatus();\n if (status == 302 || status == 303) {\n CefResponse::HeaderMap headerMap;\n response_->GetHeaderMap(headerMap);\n CefRequest::HeaderMap::iterator iter = headerMap.find(\"Location\");\n if (iter != headerMap.end()) {\n GURL new_url = GURL(std::string(iter->second));\n *http_status_code = status;\n location->Swap(&new_url);\n return true;\n }\n }\n }\n\n return false;\n}\n\nbool CefResourceRequestJob::GetMimeType(std::string* mime_type) const {\n CEF_REQUIRE_IOT();\n\n if (response_.get())\n *mime_type = response_->GetMimeType();\n return true;\n}\n\nvoid CefResourceRequestJob::SendHeaders() {\n CEF_REQUIRE_IOT();\n\n \/\/ Clear the headers available callback.\n callback_ = NULL;\n\n \/\/ We may have been orphaned...\n if (!request())\n return;\n\n response_ = new CefResponseImpl();\n remaining_bytes_ = 0;\n\n CefString redirectUrl;\n\n \/\/ Get header information from the handler.\n handler_->GetResponseHeaders(response_, remaining_bytes_, redirectUrl);\n if (!redirectUrl.empty()) {\n std::string redirectUrlStr = redirectUrl;\n redirect_url_ = GURL(redirectUrlStr);\n }\n\n if (remaining_bytes_ > 0)\n set_expected_content_size(remaining_bytes_);\n\n \/\/ Continue processing the request.\n SaveCookiesAndNotifyHeadersComplete();\n}\n\nvoid CefResourceRequestJob::AddCookieHeaderAndStart() {\n \/\/ No matter what, we want to report our status as IO pending since we will\n \/\/ be notifying our consumer asynchronously via OnStartCompleted.\n SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));\n\n \/\/ If the request was destroyed, then there is no more work to do.\n if (!request_)\n return;\n\n net::CookieStore* cookie_store =\n request_->context()->cookie_store();\n if (cookie_store &&\n !(request_->load_flags() & net::LOAD_DO_NOT_SEND_COOKIES)) {\n net::CookieMonster* cookie_monster = cookie_store->GetCookieMonster();\n if (cookie_monster) {\n cookie_monster->GetAllCookiesForURLAsync(\n request_->url(),\n base::Bind(&CefResourceRequestJob::CheckCookiePolicyAndLoad,\n weak_factory_.GetWeakPtr()));\n } else {\n DoLoadCookies();\n }\n } else {\n DoStartTransaction();\n }\n}\n\nvoid CefResourceRequestJob::DoLoadCookies() {\n net::CookieOptions options;\n options.set_include_httponly();\n request_->context()->cookie_store()->GetCookiesWithOptionsAsync(\n request_->url(), options,\n base::Bind(&CefResourceRequestJob::OnCookiesLoaded,\n weak_factory_.GetWeakPtr()));\n}\n\nvoid CefResourceRequestJob::CheckCookiePolicyAndLoad(\n const net::CookieList& cookie_list) {\n bool can_get_cookies = CanGetCookies(cookie_list);\n if (can_get_cookies) {\n net::CookieList::const_iterator it = cookie_list.begin();\n for (; it != cookie_list.end(); ++it) {\n CefCookie cookie;\n if (!CefCookieManagerImpl::GetCefCookie(*it, cookie) ||\n !handler_->CanGetCookie(cookie)) {\n can_get_cookies = false;\n break;\n }\n }\n }\n\n if (can_get_cookies)\n DoLoadCookies();\n else\n DoStartTransaction();\n}\n\nvoid CefResourceRequestJob::OnCookiesLoaded(const std::string& cookie_line) {\n if (!cookie_line.empty()) {\n CefRequest::HeaderMap headerMap;\n cef_request_->GetHeaderMap(headerMap);\n headerMap.insert(\n std::make_pair(net::HttpRequestHeaders::kCookie, cookie_line));\n cef_request_->SetHeaderMap(headerMap);\n }\n DoStartTransaction();\n}\n\nvoid CefResourceRequestJob::DoStartTransaction() {\n \/\/ We may have been canceled while retrieving cookies.\n if (GetStatus().is_success()) {\n StartTransaction();\n } else {\n NotifyCanceled();\n }\n}\n\nvoid CefResourceRequestJob::StartTransaction() {\n \/\/ Create the callback that will be used to notify when header information is\n \/\/ available.\n callback_ = new CefResourceRequestJobCallback(this,\n CefResourceRequestJobCallback::HEADERS_AVAILABLE);\n\n \/\/ Protect against deletion of this object.\n base::WeakPtr weak_ptr(weak_factory_.GetWeakPtr());\n\n \/\/ Handler can decide whether to process the request.\n bool rv = handler_->ProcessRequest(cef_request_, callback_.get());\n if (weak_ptr.get() && !rv) {\n \/\/ Cancel the request.\n NotifyCanceled();\n }\n}\n\nnet::HttpResponseHeaders* CefResourceRequestJob::GetResponseHeaders() {\n DCHECK(response_);\n if (!response_headers_.get()) {\n CefResponseImpl* responseImpl =\n static_cast(response_.get());\n response_headers_ = responseImpl->GetResponseHeaders();\n }\n return response_headers_;\n}\n\nvoid CefResourceRequestJob::SaveCookiesAndNotifyHeadersComplete() {\n if (request_->load_flags() & net::LOAD_DO_NOT_SAVE_COOKIES) {\n SetStatus(URLRequestStatus()); \/\/ Clear the IO_PENDING status\n NotifyHeadersComplete();\n return;\n }\n\n response_cookies_.clear();\n response_cookies_save_index_ = 0;\n\n FetchResponseCookies(&response_cookies_);\n\n \/\/ Now, loop over the response cookies, and attempt to persist each.\n SaveNextCookie();\n}\n\nvoid CefResourceRequestJob::SaveNextCookie() {\n if (response_cookies_save_index_ == response_cookies_.size()) {\n response_cookies_.clear();\n response_cookies_save_index_ = 0;\n SetStatus(URLRequestStatus()); \/\/ Clear the IO_PENDING status\n NotifyHeadersComplete();\n return;\n }\n\n \/\/ No matter what, we want to report our status as IO pending since we will\n \/\/ be notifying our consumer asynchronously via OnStartCompleted.\n SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));\n\n net::CookieOptions options;\n options.set_include_httponly();\n bool can_set_cookie = CanSetCookie(\n response_cookies_[response_cookies_save_index_], &options);\n if (can_set_cookie) {\n CefCookie cookie;\n if (CefCookieManagerImpl::GetCefCookie(request_->url(),\n response_cookies_[response_cookies_save_index_], cookie)) {\n can_set_cookie = handler_->CanSetCookie(cookie);\n } else {\n can_set_cookie = false;\n }\n }\n\n if (can_set_cookie) {\n request_->context()->cookie_store()->SetCookieWithOptionsAsync(\n request_->url(), response_cookies_[response_cookies_save_index_],\n options, base::Bind(&CefResourceRequestJob::OnCookieSaved,\n weak_factory_.GetWeakPtr()));\n return;\n }\n\n CookieHandled();\n}\n\nvoid CefResourceRequestJob::OnCookieSaved(bool cookie_status) {\n CookieHandled();\n}\n\nvoid CefResourceRequestJob::CookieHandled() {\n response_cookies_save_index_++;\n \/\/ We may have been canceled within OnSetCookie.\n if (GetStatus().is_success()) {\n SaveNextCookie();\n } else {\n NotifyCanceled();\n }\n}\n\nvoid CefResourceRequestJob::FetchResponseCookies(\n std::vector* cookies) {\n const std::string name = \"Set-Cookie\";\n std::string value;\n\n void* iter = NULL;\n net::HttpResponseHeaders* headers = GetResponseHeaders();\n while (headers->EnumerateHeader(&iter, name, &value)) {\n if (!value.empty())\n cookies->push_back(value);\n }\n}\nContinue resource loading asynchronously to avoid issues during ResourceScheduler stack unwinding.\/\/ Copyright (c) 2012 The Chromium Embedded Framework Authors.\n\/\/ Portions copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"libcef\/browser\/resource_request_job.h\"\n\n#include \n#include \n\n#include \"include\/cef_callback.h\"\n#include \"libcef\/browser\/cookie_manager_impl.h\"\n#include \"libcef\/browser\/thread_util.h\"\n#include \"libcef\/common\/request_impl.h\"\n#include \"libcef\/common\/response_impl.h\"\n\n#include \"base\/logging.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/http\/http_response_headers.h\"\n#include \"net\/url_request\/http_user_agent_settings.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nusing net::URLRequestStatus;\n\nnamespace {\n\nbool SetHeaderIfMissing(CefRequest::HeaderMap& headerMap,\n const std::string& name,\n const std::string& value) {\n if (value.empty())\n return false;\n \n CefRequest::HeaderMap::const_iterator it = headerMap.find(name);\n if (it == headerMap.end()) {\n headerMap.insert(std::make_pair(name, value));\n return true;\n }\n\n return false;\n}\n\n} \/\/ namespace\n\n\/\/ Client callback for asynchronous response continuation.\nclass CefResourceRequestJobCallback : public CefCallback {\n public:\n enum Type {\n HEADERS_AVAILABLE,\n BYTES_AVAILABLE,\n };\n\n explicit CefResourceRequestJobCallback(CefResourceRequestJob* job, Type type)\n : job_(job),\n type_(type),\n dest_(NULL),\n dest_size_(0) {}\n\n virtual void Continue() OVERRIDE {\n \/\/ Continue asynchronously.\n CEF_POST_TASK(CEF_IOT,\n base::Bind(&CefResourceRequestJobCallback::ContinueOnIOThread, this));\n }\n\n virtual void Cancel() OVERRIDE {\n \/\/ Cancel asynchronously.\n CEF_POST_TASK(CEF_IOT,\n base::Bind(&CefResourceRequestJobCallback::CancelOnIOThread, this));\n }\n\n void Detach() {\n CEF_REQUIRE_IOT();\n job_ = NULL;\n }\n\n void SetDestination(net::IOBuffer* dest, int dest_size) {\n CEF_REQUIRE_IOT();\n dest_ = dest;\n dest_size_ = dest_size;\n }\n\n private:\n void ContinueOnIOThread() {\n CEF_REQUIRE_IOT();\n\n \/\/ Return early if the callback has already been detached.\n if (!job_)\n return;\n\n if (type_ == HEADERS_AVAILABLE) {\n \/\/ Callback for headers available.\n if (!job_->has_response_started()) {\n \/\/ Send header information.\n job_->SendHeaders();\n }\n\n \/\/ This type of callback only ever needs to be called once.\n Detach();\n } else if (type_ == BYTES_AVAILABLE) {\n \/\/ Callback for bytes available.\n if (job_->has_response_started() &&\n job_->GetStatus().is_io_pending()) {\n \/\/ Read the bytes. They should be available but, if not, wait again.\n int bytes_read = 0;\n if (job_->ReadRawData(dest_, dest_size_, &bytes_read)) {\n if (bytes_read > 0) {\n \/\/ Clear the IO_PENDING status.\n job_->SetStatus(URLRequestStatus());\n\n \/\/ Notify about the available bytes.\n job_->NotifyReadComplete(bytes_read);\n\n dest_ = NULL;\n dest_size_ = 0;\n } else {\n \/\/ All done.\n job_->NotifyDone(URLRequestStatus());\n Detach();\n }\n } else if (!job_->GetStatus().is_io_pending()) {\n \/\/ Failed due to an error.\n NOTREACHED() <<\n \"ReadRawData returned false without setting IO as pending\";\n job_->NotifyDone(URLRequestStatus());\n Detach();\n }\n }\n }\n }\n\n void CancelOnIOThread() {\n CEF_REQUIRE_IOT();\n\n if (job_)\n job_->Kill();\n }\n\n CefResourceRequestJob* job_;\n Type type_;\n\n net::IOBuffer* dest_;\n int dest_size_;\n\n IMPLEMENT_REFCOUNTING(Callback);\n};\n\nCefResourceRequestJob::CefResourceRequestJob(\n net::URLRequest* request,\n net::NetworkDelegate* network_delegate,\n CefRefPtr handler)\n : net::URLRequestJob(request, network_delegate),\n handler_(handler),\n remaining_bytes_(0),\n response_cookies_save_index_(0),\n ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {\n}\n\nCefResourceRequestJob::~CefResourceRequestJob() {\n}\n\nvoid CefResourceRequestJob::Start() {\n CEF_REQUIRE_IOT();\n\n cef_request_ = CefRequest::Create();\n\n \/\/ Populate the request data.\n static_cast(cef_request_.get())->Set(request_);\n\n \/\/ Add default headers if not already specified.\n const net::URLRequestContext* context = request_->context();\n if (context) {\n CefRequest::HeaderMap headerMap;\n cef_request_->GetHeaderMap(headerMap);\n bool changed = false;\n\n const net::HttpUserAgentSettings* ua_settings =\n context->http_user_agent_settings();\n if (ua_settings) {\n if (SetHeaderIfMissing(headerMap,\n net::HttpRequestHeaders::kAcceptLanguage,\n ua_settings->GetAcceptLanguage())) {\n changed = true;\n }\n\n if (SetHeaderIfMissing(headerMap,\n net::HttpRequestHeaders::kUserAgent,\n ua_settings->GetUserAgent(request_->url()))) {\n changed = true;\n }\n }\n\n if (changed)\n cef_request_->SetHeaderMap(headerMap);\n }\n\n AddCookieHeaderAndStart();\n}\n\nvoid CefResourceRequestJob::Kill() {\n CEF_REQUIRE_IOT();\n\n \/\/ Notify the handler that the request has been canceled.\n handler_->Cancel();\n\n if (callback_) {\n callback_->Detach();\n callback_ = NULL;\n }\n\n net::URLRequestJob::Kill();\n}\n\nbool CefResourceRequestJob::ReadRawData(net::IOBuffer* dest, int dest_size,\n int* bytes_read) {\n CEF_REQUIRE_IOT();\n\n DCHECK_NE(dest_size, 0);\n DCHECK(bytes_read);\n\n if (remaining_bytes_ == 0) {\n \/\/ No more data to read.\n *bytes_read = 0;\n return true;\n } else if (remaining_bytes_ > 0 && remaining_bytes_ < dest_size) {\n \/\/ The handler knows the content size beforehand.\n dest_size = static_cast(remaining_bytes_);\n }\n\n if (!callback_.get()) {\n \/\/ Create the bytes available callback that will be used until the request\n \/\/ is completed.\n callback_ = new CefResourceRequestJobCallback(this,\n CefResourceRequestJobCallback::BYTES_AVAILABLE);\n }\n\n \/\/ Read response data from the handler.\n bool rv = handler_->ReadResponse(dest->data(), dest_size, *bytes_read,\n callback_.get());\n if (!rv) {\n \/\/ The handler has indicated completion of the request.\n *bytes_read = 0;\n return true;\n } else if (*bytes_read == 0) {\n if (!GetStatus().is_io_pending()) {\n \/\/ Report our status as IO pending.\n SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));\n callback_->SetDestination(dest, dest_size);\n }\n return false;\n } else if (*bytes_read > dest_size) {\n \/\/ Normalize the return value.\n *bytes_read = dest_size;\n }\n\n if (remaining_bytes_ > 0)\n remaining_bytes_ -= *bytes_read;\n\n \/\/ Continue calling this method.\n return true;\n}\n\nvoid CefResourceRequestJob::GetResponseInfo(net::HttpResponseInfo* info) {\n CEF_REQUIRE_IOT();\n\n info->headers = GetResponseHeaders();\n}\n\nbool CefResourceRequestJob::GetResponseCookies(\n std::vector* cookies) {\n CEF_REQUIRE_IOT();\n\n cookies->clear();\n FetchResponseCookies(cookies);\n return true;\n}\n\nbool CefResourceRequestJob::IsRedirectResponse(GURL* location,\n int* http_status_code) {\n CEF_REQUIRE_IOT();\n\n if (redirect_url_.is_valid()) {\n \/\/ Redirect to the new URL.\n *http_status_code = 303;\n location->Swap(&redirect_url_);\n return true;\n }\n\n if (response_.get()) {\n \/\/ Check for HTTP 302 or HTTP 303 redirect.\n int status = response_->GetStatus();\n if (status == 302 || status == 303) {\n CefResponse::HeaderMap headerMap;\n response_->GetHeaderMap(headerMap);\n CefRequest::HeaderMap::iterator iter = headerMap.find(\"Location\");\n if (iter != headerMap.end()) {\n GURL new_url = GURL(std::string(iter->second));\n *http_status_code = status;\n location->Swap(&new_url);\n return true;\n }\n }\n }\n\n return false;\n}\n\nbool CefResourceRequestJob::GetMimeType(std::string* mime_type) const {\n CEF_REQUIRE_IOT();\n\n if (response_.get())\n *mime_type = response_->GetMimeType();\n return true;\n}\n\nvoid CefResourceRequestJob::SendHeaders() {\n CEF_REQUIRE_IOT();\n\n \/\/ Clear the headers available callback.\n callback_ = NULL;\n\n \/\/ We may have been orphaned...\n if (!request())\n return;\n\n response_ = new CefResponseImpl();\n remaining_bytes_ = 0;\n\n CefString redirectUrl;\n\n \/\/ Get header information from the handler.\n handler_->GetResponseHeaders(response_, remaining_bytes_, redirectUrl);\n if (!redirectUrl.empty()) {\n std::string redirectUrlStr = redirectUrl;\n redirect_url_ = GURL(redirectUrlStr);\n }\n\n if (remaining_bytes_ > 0)\n set_expected_content_size(remaining_bytes_);\n\n \/\/ Continue processing the request.\n SaveCookiesAndNotifyHeadersComplete();\n}\n\nvoid CefResourceRequestJob::AddCookieHeaderAndStart() {\n \/\/ No matter what, we want to report our status as IO pending since we will\n \/\/ be notifying our consumer asynchronously via OnStartCompleted.\n SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));\n\n \/\/ If the request was destroyed, then there is no more work to do.\n if (!request_)\n return;\n\n net::CookieStore* cookie_store =\n request_->context()->cookie_store();\n if (cookie_store &&\n !(request_->load_flags() & net::LOAD_DO_NOT_SEND_COOKIES)) {\n net::CookieMonster* cookie_monster = cookie_store->GetCookieMonster();\n if (cookie_monster) {\n cookie_monster->GetAllCookiesForURLAsync(\n request_->url(),\n base::Bind(&CefResourceRequestJob::CheckCookiePolicyAndLoad,\n weak_factory_.GetWeakPtr()));\n } else {\n DoLoadCookies();\n }\n } else {\n DoStartTransaction();\n }\n}\n\nvoid CefResourceRequestJob::DoLoadCookies() {\n net::CookieOptions options;\n options.set_include_httponly();\n request_->context()->cookie_store()->GetCookiesWithOptionsAsync(\n request_->url(), options,\n base::Bind(&CefResourceRequestJob::OnCookiesLoaded,\n weak_factory_.GetWeakPtr()));\n}\n\nvoid CefResourceRequestJob::CheckCookiePolicyAndLoad(\n const net::CookieList& cookie_list) {\n bool can_get_cookies = CanGetCookies(cookie_list);\n if (can_get_cookies) {\n net::CookieList::const_iterator it = cookie_list.begin();\n for (; it != cookie_list.end(); ++it) {\n CefCookie cookie;\n if (!CefCookieManagerImpl::GetCefCookie(*it, cookie) ||\n !handler_->CanGetCookie(cookie)) {\n can_get_cookies = false;\n break;\n }\n }\n }\n\n if (can_get_cookies)\n DoLoadCookies();\n else\n DoStartTransaction();\n}\n\nvoid CefResourceRequestJob::OnCookiesLoaded(const std::string& cookie_line) {\n if (!cookie_line.empty()) {\n CefRequest::HeaderMap headerMap;\n cef_request_->GetHeaderMap(headerMap);\n headerMap.insert(\n std::make_pair(net::HttpRequestHeaders::kCookie, cookie_line));\n cef_request_->SetHeaderMap(headerMap);\n }\n DoStartTransaction();\n}\n\nvoid CefResourceRequestJob::DoStartTransaction() {\n \/\/ We may have been canceled while retrieving cookies.\n if (GetStatus().is_success()) {\n StartTransaction();\n } else {\n NotifyCanceled();\n }\n}\n\nvoid CefResourceRequestJob::StartTransaction() {\n \/\/ Create the callback that will be used to notify when header information is\n \/\/ available.\n callback_ = new CefResourceRequestJobCallback(this,\n CefResourceRequestJobCallback::HEADERS_AVAILABLE);\n\n \/\/ Protect against deletion of this object.\n base::WeakPtr weak_ptr(weak_factory_.GetWeakPtr());\n\n \/\/ Handler can decide whether to process the request.\n bool rv = handler_->ProcessRequest(cef_request_, callback_.get());\n if (weak_ptr.get() && !rv) {\n \/\/ Cancel the request.\n NotifyCanceled();\n }\n}\n\nnet::HttpResponseHeaders* CefResourceRequestJob::GetResponseHeaders() {\n DCHECK(response_);\n if (!response_headers_.get()) {\n CefResponseImpl* responseImpl =\n static_cast(response_.get());\n response_headers_ = responseImpl->GetResponseHeaders();\n }\n return response_headers_;\n}\n\nvoid CefResourceRequestJob::SaveCookiesAndNotifyHeadersComplete() {\n if (request_->load_flags() & net::LOAD_DO_NOT_SAVE_COOKIES) {\n SetStatus(URLRequestStatus()); \/\/ Clear the IO_PENDING status\n NotifyHeadersComplete();\n return;\n }\n\n response_cookies_.clear();\n response_cookies_save_index_ = 0;\n\n FetchResponseCookies(&response_cookies_);\n\n \/\/ Now, loop over the response cookies, and attempt to persist each.\n SaveNextCookie();\n}\n\nvoid CefResourceRequestJob::SaveNextCookie() {\n if (response_cookies_save_index_ == response_cookies_.size()) {\n response_cookies_.clear();\n response_cookies_save_index_ = 0;\n SetStatus(URLRequestStatus()); \/\/ Clear the IO_PENDING status\n NotifyHeadersComplete();\n return;\n }\n\n \/\/ No matter what, we want to report our status as IO pending since we will\n \/\/ be notifying our consumer asynchronously via OnStartCompleted.\n SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));\n\n net::CookieOptions options;\n options.set_include_httponly();\n bool can_set_cookie = CanSetCookie(\n response_cookies_[response_cookies_save_index_], &options);\n if (can_set_cookie) {\n CefCookie cookie;\n if (CefCookieManagerImpl::GetCefCookie(request_->url(),\n response_cookies_[response_cookies_save_index_], cookie)) {\n can_set_cookie = handler_->CanSetCookie(cookie);\n } else {\n can_set_cookie = false;\n }\n }\n\n if (can_set_cookie) {\n request_->context()->cookie_store()->SetCookieWithOptionsAsync(\n request_->url(), response_cookies_[response_cookies_save_index_],\n options, base::Bind(&CefResourceRequestJob::OnCookieSaved,\n weak_factory_.GetWeakPtr()));\n return;\n }\n\n CookieHandled();\n}\n\nvoid CefResourceRequestJob::OnCookieSaved(bool cookie_status) {\n CookieHandled();\n}\n\nvoid CefResourceRequestJob::CookieHandled() {\n response_cookies_save_index_++;\n \/\/ We may have been canceled within OnSetCookie.\n if (GetStatus().is_success()) {\n SaveNextCookie();\n } else {\n NotifyCanceled();\n }\n}\n\nvoid CefResourceRequestJob::FetchResponseCookies(\n std::vector* cookies) {\n const std::string name = \"Set-Cookie\";\n std::string value;\n\n void* iter = NULL;\n net::HttpResponseHeaders* headers = GetResponseHeaders();\n while (headers->EnumerateHeader(&iter, name, &value)) {\n if (!value.empty())\n cookies->push_back(value);\n }\n}\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993-2016 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"common.h\"\n#include \"ConfigFileManager.h\"\n#include \"FileManager.h\"\n#include \"CommandManager.h\"\n#include \"StateDatabase.h\"\n#include \"KeyManager.h\"\n\nstatic const int\tMaximumLineLength = 1024;\n\n\/\/ initialize the singleton\ntemplate <>\nConfigFileManager* Singleton::_instance = (ConfigFileManager*)0;\n\nvoid writeBZDB(const std::string& name, void *stream)\n{\n std::ostream& s = *static_cast(stream);\n std::string value = BZDB.get(name);\n std::string defaultVal = BZDB.getDefault(name);\n std::string newkey;\n bool commentOut = (value == defaultVal);\n\n \/\/ quotify anything with a space and empty strings\n if ((value.find(' ') != value.npos) || (value.size() == 0)) {\n value = std::string(\"\\\"\") + value + \"\\\"\";\n }\n\n \/\/ quotify the key if there's a space\n if (name.find(' ') != name.npos)\n newkey = std::string(\"\\\"\") + name + \"\\\"\";\n else\n newkey = name;\n\n s << (commentOut ? \"#set \" : \"set \") << newkey << ' ' << value << std::endl;\n}\n\nvoid writeKEYMGR(const std::string& name, bool press, const std::string& command, void* stream)\n{\n std::ostream& s = *static_cast(stream);\n \/\/ quotify anything with a space\n std::string value = name;\n if (value.find(' ') != value.npos)\n value = std::string(\"\\\"\") + value + \"\\\"\";\n s << \"bind \" << value << ' ' << (press ? \"down \" : \"up \");\n value = command;\n if (value.find(' ') != value.npos)\n value = std::string(\"\\\"\") + value + \"\\\"\";\n s << value << std::endl;\n}\n\nConfigFileManager::ConfigFileManager()\n{\n \/\/ do nothing\n}\n\nConfigFileManager::~ConfigFileManager()\n{\n}\n\nbool\t\t\t\tConfigFileManager::parse(std::istream& stream)\n{\n char buffer[MaximumLineLength];\n while (stream.good()) {\n stream.getline(buffer, MaximumLineLength);\n CMDMGR.run(buffer);\n }\n return true;\n}\n\nbool\t\t\t\tConfigFileManager::read(const std::string& filename)\n{\n std::istream* stream = FILEMGR.createDataInStream(filename);\n if (stream == NULL) {\n return false;\n }\n bool ret = parse(*stream);\n delete stream;\n return ret;\n}\n\nvoid\t\t\t\tConfigFileManager::read(std::istream& stream)\n{\n parse(stream);\n}\n\nbool\t\t\t\tConfigFileManager::write(const std::string& filename)\n{\n std::ostream* stream = FILEMGR.createDataOutStream(filename);\n if (stream == NULL) {\n return false;\n }\n BZDB.write(writeBZDB, stream);\n KEYMGR.iterate(writeKEYMGR, stream);\n delete stream;\n return true;\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\nProperly store configuration values with semicolons\/* bzflag\n * Copyright (c) 1993-2016 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"common.h\"\n#include \"ConfigFileManager.h\"\n#include \"FileManager.h\"\n#include \"CommandManager.h\"\n#include \"StateDatabase.h\"\n#include \"KeyManager.h\"\n\nstatic const int\tMaximumLineLength = 1024;\n\n\/\/ initialize the singleton\ntemplate <>\nConfigFileManager* Singleton::_instance = (ConfigFileManager*)0;\n\nvoid writeBZDB(const std::string& name, void *stream)\n{\n std::ostream& s = *static_cast(stream);\n std::string value = BZDB.get(name);\n std::string defaultVal = BZDB.getDefault(name);\n std::string newkey;\n bool commentOut = (value == defaultVal);\n\n \/\/ quotify empty strings and anything with a space or a semicolon\n if ((value.find(' ') != value.npos) || (value.find(';') != value.npos) || (value.size() == 0)) {\n value = std::string(\"\\\"\") + value + \"\\\"\";\n }\n\n \/\/ quotify the key if there's a space or a semicolon\n if ((name.find(' ') != name.npos) || (name.find(';') != name.npos))\n newkey = std::string(\"\\\"\") + name + \"\\\"\";\n else\n newkey = name;\n\n s << (commentOut ? \"#set \" : \"set \") << newkey << ' ' << value << std::endl;\n}\n\nvoid writeKEYMGR(const std::string& name, bool press, const std::string& command, void* stream)\n{\n std::ostream& s = *static_cast(stream);\n \/\/ quotify anything with a space\n std::string value = name;\n if (value.find(' ') != value.npos)\n value = std::string(\"\\\"\") + value + \"\\\"\";\n s << \"bind \" << value << ' ' << (press ? \"down \" : \"up \");\n value = command;\n if (value.find(' ') != value.npos)\n value = std::string(\"\\\"\") + value + \"\\\"\";\n s << value << std::endl;\n}\n\nConfigFileManager::ConfigFileManager()\n{\n \/\/ do nothing\n}\n\nConfigFileManager::~ConfigFileManager()\n{\n}\n\nbool\t\t\t\tConfigFileManager::parse(std::istream& stream)\n{\n char buffer[MaximumLineLength];\n while (stream.good()) {\n stream.getline(buffer, MaximumLineLength);\n CMDMGR.run(buffer);\n }\n return true;\n}\n\nbool\t\t\t\tConfigFileManager::read(const std::string& filename)\n{\n std::istream* stream = FILEMGR.createDataInStream(filename);\n if (stream == NULL) {\n return false;\n }\n bool ret = parse(*stream);\n delete stream;\n return ret;\n}\n\nvoid\t\t\t\tConfigFileManager::read(std::istream& stream)\n{\n parse(stream);\n}\n\nbool\t\t\t\tConfigFileManager::write(const std::string& filename)\n{\n std::ostream* stream = FILEMGR.createDataOutStream(filename);\n if (stream == NULL) {\n return false;\n }\n BZDB.write(writeBZDB, stream);\n KEYMGR.iterate(writeKEYMGR, stream);\n delete stream;\n return true;\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"\/*\nTyra Draper, Section 1, tyra.draper@gmail.com\nPurpose: implement the Lexer.h file\n*\/\n\n#include \"Lexer.h\"\n\nvoid Lexer::analyze() {\n\twhile (ifs.peek() != EOF) {\n\t\tif (whitespace()) { continue; }\n\t\tif (alpha()) { continue; }\n\t\tif (str()) { continue; }\n\t\tif (comment()) { continue; }\n\t\tsymbol();\n\t}\n\ttokens.push_back(new Token(MY_EOF, \"\", curLine));\n\tcurToken = 0;\n\/\/\tprint();\n}\n\nbool Lexer::whitespace() {\n\tif (ifs.peek() == '\\n') {\n\t\tifs.get();\n\t\tcurLine++;\n\t\treturn true;\n\t}\n\telse if (isspace(ifs.peek())) {\n\t\tifs.get();\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool Lexer::alpha() {\n\tstring x = \"\";\n\twhile (isalpha(ifs.peek())) {\n\t\tx += ifs.get();\n\t}\n\tif (x.length() == 0) {\n\t\treturn false;\n\t}\n\tif (isdigit(ifs.peek())) {\n\t\twhile (isalpha(ifs.peek()) || isdigit(ifs.peek())) {\n\t\t\tx += ifs.get();\n\t\t}\n\t}\n\telse {\n\t\tif (x == \"Schemes\") {\n\t\t\ttokens.push_back(new Token(SCHEMES, x, curLine));\n\t\t\treturn true;\n\t\t}\n\t\telse if (x == \"Facts\") {\n\t\t\ttokens.push_back(new Token(FACTS, x, curLine));\n\t\t\treturn true;\n\t\t}\n\t\telse if (x == \"Rules\") {\n\t\t\ttokens.push_back(new Token(RULES, x, curLine));\n\t\t\treturn true;\n\t\t}\n\t\telse if (x == \"Queries\") {\n\t\t\ttokens.push_back(new Token(QUERIES, x, curLine));\n\t\t\treturn true;\n\t\t}\n\t}\n\ttokens.push_back(new Token(ID, x, curLine));\n\treturn true;\n}\n\nbool Lexer::str() {\n\tif (ifs.peek() != '\\'') {\n\t\treturn false;\n\t}\n\tstring x(1, ifs.get());\n\tint newLines = 0;\n\twhile (ifs.peek() != EOF) {\n\t\tif (ifs.peek() == '\\'') {\n\t\t\tx += ifs.get();\n\t\t\tif (ifs.peek() != '\\'') {\n\t\t\t\ttokens.push_back(new Token(STRING, x, curLine));\n\t\t\t\tcurLine += newLines;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse if (ifs.peek() == '\\n') {\n\t\t\tnewLines++;\n\t\t}\n\t\tx += ifs.get();\n\t}\n\ttokens.push_back(new Token(UNDEFINED, x, curLine));\n\tcurLine += newLines;\n\treturn true;\n}\n\nbool Lexer::comment() {\n\tif (ifs.peek() != '#') {\n\t\treturn false;\n\t}\n\tifs.get();\n\tif (ifs.peek() == '|') {\n\t\treturn block();\n\t}\n\telse {\n\t\treturn line();\n\t}\n}\n\nbool Lexer::block() {\n\tstring x = \"#\";\n\tx += ifs.get();\n\tint newLines = 0;\n\twhile (ifs.peek() != EOF) {\n\t\tif (ifs.peek() == '|') {\n\t\t\tx += ifs.get();\n\t\t\tif (ifs.peek() == '#') {\n\t\t\t\tx += ifs.get();\n\/\/\t\t\t\ttokens.push_back(new Token(COMMENT, x, curLine));\n\t\t\t\tcurLine += newLines;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tif (ifs.peek() == '\\n') {\n\t\t\tnewLines++;\n\t\t}\n\t\tx += ifs.get();\n\t}\n\/\/\ttokens.push_back(new Token(UNDEFINED, x, curLine));\n\tcurLine += newLines;\n\treturn true;\n}\n\nbool Lexer::line() {\n\tstring x = \"#\";\n\twhile (ifs.peek() != '\\n' && ifs.peek() != EOF) {\n\t\tx += ifs.get();\n\t}\n\/\/\ttokens.push_back(new Token(COMMENT, x, curLine));\n\treturn true;\n}\n\nbool Lexer::symbol() {\n\tstring x(1, ifs.get());\n\tif (x == \",\") {\n\t\ttokens.push_back(new Token(COMMA, x, curLine));\n\t\treturn true;\n\t}\n\tif (x == \".\") {\n\t\ttokens.push_back(new Token(PERIOD, x, curLine));\n\t\treturn true;\n\t}\n\tif (x == \"?\") {\n\t\ttokens.push_back(new Token(Q_MARK, x, curLine));\n\t\treturn true;\n\t}\n\tif (x == \"(\") {\n\t\ttokens.push_back(new Token(LEFT_PAREN, x, curLine));\n\t\treturn true;\n\t}\n\tif (x == \")\") {\n\t\ttokens.push_back(new Token(RIGHT_PAREN, x, curLine));\n\t\treturn true;\n\t}\n\tif (x == \"*\") {\n\t\ttokens.push_back(new Token(MULTIPLY, x, curLine));\n\t\treturn true;\n\t}\n\tif (x == \"+\") {\n\t\ttokens.push_back(new Token(ADD, x, curLine));\n\t\treturn true;\n\t}\n\tif (x == \":\") {\n\t\tif (ifs.peek() == '-') {\n\t\t\tx += ifs.get();\n\t\t\ttokens.push_back(new Token(COLON_DASH, x, curLine));\n\t\t\treturn true;\n\t\t}\n\t\ttokens.push_back(new Token(COLON, x, curLine));\n\t\treturn true;\n\t}\n\telse {\n\t\ttokens.push_back(new Token(UNDEFINED, x, curLine));\n\t\tthrow tokens.at(tokens.size() - 1);\n\t}\n\treturn false;\n}\n\nvoid Lexer::print() {\n\tfor (Token* t : tokens) {\n\t\tcout << t->toString() << endl;\n\t}\n\tcout << \"Total Tokens = \" << tokens.size() << endl;\n}\n\nToken* Lexer::next(TokenType a) {\n\tif (curToken < tokens.size()) {\n\t\tToken* result = tokens.at(curToken);\n\t\tif (result->type() != a || result->type() == UNDEFINED) {\n\t\t\tthrow result;\n\t\t}\n\t\tcurToken++;\n\t\treturn result;\n\t}\n\telse {\n\t\tcout << \"ya went too far\";\n\t\treturn tokens.at(curToken - 1);\n\t}\n}remove testing for undefined\/*\nTyra Draper, Section 1, tyra.draper@gmail.com\nPurpose: implement the Lexer.h file\n*\/\n\n#include \"Lexer.h\"\n\nvoid Lexer::analyze() {\n\twhile (ifs.peek() != EOF) {\n\t\tif (whitespace()) { continue; }\n\t\tif (alpha()) { continue; }\n\t\tif (str()) { continue; }\n\t\tif (comment()) { continue; }\n\t\tsymbol();\n\t}\n\ttokens.push_back(new Token(MY_EOF, \"\", curLine));\n\tcurToken = 0;\n\/\/\tprint();\n}\n\nbool Lexer::whitespace() {\n\tif (ifs.peek() == '\\n') {\n\t\tifs.get();\n\t\tcurLine++;\n\t\treturn true;\n\t}\n\telse if (isspace(ifs.peek())) {\n\t\tifs.get();\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool Lexer::alpha() {\n\tstring x = \"\";\n\twhile (isalpha(ifs.peek())) {\n\t\tx += ifs.get();\n\t}\n\tif (x.length() == 0) {\n\t\treturn false;\n\t}\n\tif (isdigit(ifs.peek())) {\n\t\twhile (isalpha(ifs.peek()) || isdigit(ifs.peek())) {\n\t\t\tx += ifs.get();\n\t\t}\n\t}\n\telse {\n\t\tif (x == \"Schemes\") {\n\t\t\ttokens.push_back(new Token(SCHEMES, x, curLine));\n\t\t\treturn true;\n\t\t}\n\t\telse if (x == \"Facts\") {\n\t\t\ttokens.push_back(new Token(FACTS, x, curLine));\n\t\t\treturn true;\n\t\t}\n\t\telse if (x == \"Rules\") {\n\t\t\ttokens.push_back(new Token(RULES, x, curLine));\n\t\t\treturn true;\n\t\t}\n\t\telse if (x == \"Queries\") {\n\t\t\ttokens.push_back(new Token(QUERIES, x, curLine));\n\t\t\treturn true;\n\t\t}\n\t}\n\ttokens.push_back(new Token(ID, x, curLine));\n\treturn true;\n}\n\nbool Lexer::str() {\n\tif (ifs.peek() != '\\'') {\n\t\treturn false;\n\t}\n\tstring x(1, ifs.get());\n\tint newLines = 0;\n\twhile (ifs.peek() != EOF) {\n\t\tif (ifs.peek() == '\\'') {\n\t\t\tx += ifs.get();\n\t\t\tif (ifs.peek() != '\\'') {\n\t\t\t\ttokens.push_back(new Token(STRING, x, curLine));\n\t\t\t\tcurLine += newLines;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse if (ifs.peek() == '\\n') {\n\t\t\tnewLines++;\n\t\t}\n\t\tx += ifs.get();\n\t}\n\ttokens.push_back(new Token(UNDEFINED, x, curLine));\n\tcurLine += newLines;\n\treturn true;\n}\n\nbool Lexer::comment() {\n\tif (ifs.peek() != '#') {\n\t\treturn false;\n\t}\n\tifs.get();\n\tif (ifs.peek() == '|') {\n\t\treturn block();\n\t}\n\telse {\n\t\treturn line();\n\t}\n}\n\nbool Lexer::block() {\n\tstring x = \"#\";\n\tx += ifs.get();\n\tint newLines = 0;\n\twhile (ifs.peek() != EOF) {\n\t\tif (ifs.peek() == '|') {\n\t\t\tx += ifs.get();\n\t\t\tif (ifs.peek() == '#') {\n\t\t\t\tx += ifs.get();\n\/\/\t\t\t\ttokens.push_back(new Token(COMMENT, x, curLine));\n\t\t\t\tcurLine += newLines;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tif (ifs.peek() == '\\n') {\n\t\t\tnewLines++;\n\t\t}\n\t\tx += ifs.get();\n\t}\n\/\/\ttokens.push_back(new Token(UNDEFINED, x, curLine));\n\tcurLine += newLines;\n\treturn true;\n}\n\nbool Lexer::line() {\n\tstring x = \"#\";\n\twhile (ifs.peek() != '\\n' && ifs.peek() != EOF) {\n\t\tx += ifs.get();\n\t}\n\/\/\ttokens.push_back(new Token(COMMENT, x, curLine));\n\treturn true;\n}\n\nbool Lexer::symbol() {\n\tstring x(1, ifs.get());\n\tif (x == \",\") {\n\t\ttokens.push_back(new Token(COMMA, x, curLine));\n\t\treturn true;\n\t}\n\tif (x == \".\") {\n\t\ttokens.push_back(new Token(PERIOD, x, curLine));\n\t\treturn true;\n\t}\n\tif (x == \"?\") {\n\t\ttokens.push_back(new Token(Q_MARK, x, curLine));\n\t\treturn true;\n\t}\n\tif (x == \"(\") {\n\t\ttokens.push_back(new Token(LEFT_PAREN, x, curLine));\n\t\treturn true;\n\t}\n\tif (x == \")\") {\n\t\ttokens.push_back(new Token(RIGHT_PAREN, x, curLine));\n\t\treturn true;\n\t}\n\tif (x == \"*\") {\n\t\ttokens.push_back(new Token(MULTIPLY, x, curLine));\n\t\treturn true;\n\t}\n\tif (x == \"+\") {\n\t\ttokens.push_back(new Token(ADD, x, curLine));\n\t\treturn true;\n\t}\n\tif (x == \":\") {\n\t\tif (ifs.peek() == '-') {\n\t\t\tx += ifs.get();\n\t\t\ttokens.push_back(new Token(COLON_DASH, x, curLine));\n\t\t\treturn true;\n\t\t}\n\t\ttokens.push_back(new Token(COLON, x, curLine));\n\t\treturn true;\n\t}\n\telse {\n\t\ttokens.push_back(new Token(UNDEFINED, x, curLine));\n\t\tthrow tokens.at(tokens.size() - 1);\n\t}\n\treturn false;\n}\n\nvoid Lexer::print() {\n\tfor (Token* t : tokens) {\n\t\tcout << t->toString() << endl;\n\t}\n\tcout << \"Total Tokens = \" << tokens.size() << endl;\n}\n\nToken* Lexer::next(TokenType a) {\n\tif (curToken < tokens.size()) {\n\t\tToken* result = tokens.at(curToken);\n\t\tif (result->type() != a) {\n\t\t\tthrow result;\n\t\t}\n\t\tcurToken++;\n\t\treturn result;\n\t}\n\telse {\n\t\tcout << \"ya went too far\";\n\t\treturn tokens.at(curToken - 1);\n\t}\n}<|endoftext|>"} {"text":"#include \"webcam.hpp\"\n\nusing namespace cv;\nusing namespace std;\n\nint main (int argc, char** argv) {\n\n CvCapture* capture = 0;\n int width, height, fps;\n\n capture = cvCaptureFromCAM(0);\n\n if (!capture) {\n printf(\"No camera detected!\");\n return -1;\n }\n\n ifstream configFile (\".config\");\n\n if (configFile.is_open()) {\n\n \/\/probably want to support corrupted .config\n string line;\n getline(configFile, line);\n istringstream(line)>>width;\n getline(configFile, line);\n istringstream(line)>>height;\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);\n\n configFile.close();\n\n } else {\n\n initResolutions();\n\n for (int i=36; i<150; i++) {\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);\n }\n\n width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);\n height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);\n\n ofstream configFileOut(\".config\");\n configFileOut << width;\n configFileOut << \"\\n\";\n configFileOut << height;\n configFileOut << \"\\n\";\n configFileOut.close();\n }\n\n bool keepGoing = true;\n\n\/\/ srand(890);\/\/not interested in good randomness\n\n Mat image;\n Mat channel[3];\n\n while (keepGoing) {\n\n image = cvQueryFrame(capture);\n imshow(\"webcam\", image);\n\n\/\/ thresholds on dark regions\n\n Mat gray, blurred_gray, threshold_gray;\n cvtColor(image, gray, CV_BGR2GRAY);\n blur(gray, blurred_gray, Size(width\/20,height\/20));\n equalizeHist(blurred_gray, blurred_gray);\n\n threshold(blurred_gray, threshold_gray, 40, 1, THRESH_BINARY_INV);\n imshow(\"threshold\", threshold_gray.mul(gray));\n\n keepGoing = (waitKey(25)<0);\n\n }\n\n cvReleaseCapture(&capture);\n\n return 0;\n}\nhacking#include \"webcam.hpp\"\n\nusing namespace cv;\nusing namespace std;\n\nint main (int argc, char** argv) {\n\n CvCapture* capture = 0;\n int width, height, fps;\n\n capture = cvCaptureFromCAM(0);\n\n if (!capture) {\n printf(\"No camera detected!\");\n return -1;\n }\n\n ifstream configFile (\".config\");\n\n if (configFile.is_open()) {\n\n \/\/probably want to support corrupted .config\n string line;\n getline(configFile, line);\n istringstream(line)>>width;\n getline(configFile, line);\n istringstream(line)>>height;\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);\n\n configFile.close();\n\n } else {\n\n initResolutions();\n\n for (int i=36; i<150; i++) {\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);\n }\n\n width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);\n height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);\n\n ofstream configFileOut(\".config\");\n configFileOut << width;\n configFileOut << \"\\n\";\n configFileOut << height;\n configFileOut << \"\\n\";\n configFileOut.close();\n }\n\n bool keepGoing = true;\n\n\/\/ srand(890);\/\/not interested in good randomness\n\n Mat image;\n Mat channel[3];\n\n while (keepGoing) {\n\n image = cvQueryFrame(capture);\n imshow(\"webcam\", image);\n\n\/\/ thresholds on dark regions\n\n Mat gray, blurred_gray, threshold_gray;\n cvtColor(image, gray, CV_BGR2GRAY);\n blur(gray, blurred_gray, Size(width\/10,height\/20));\n equalizeHist(blurred_gray, blurred_gray);\n\n threshold(blurred_gray, threshold_gray, 40, 1, THRESH_BINARY_INV);\n imshow(\"threshold\", threshold_gray.mul(gray));\n\n keepGoing = (waitKey(25)<0);\n\n }\n\n cvReleaseCapture(&capture);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/******************************************************************\r\n *\r\n * uSQL for C++\r\n *\r\n * Copyright (C) Satoshi Konno 2012\r\n *\r\n * This is licensed under BSD-style license, see file COPYING.\r\n *\r\n ******************************************************************\/\r\n\r\n#include \"MySQLProxy.h\"\r\n\r\nusing namespace std;\r\nusing namespace uSQL;\r\n\r\nstatic const char *USQL_MYSQL_PROXY_MEMCACHED_HOST = \"192.168.100.111\";\r\n\r\nuSQL::MySQLProxy::MySQLProxy()\r\n{\r\n this->mySQL = mysql_init(NULL);\r\n}\r\n\r\nuSQL::MySQLProxy::~MySQLProxy()\r\n{\r\n mysql_close(this->mySQL);\r\n}\r\n\r\nbool uSQL::MySQLProxy::connect(const std::string &host, const std::string &user, const std::string &passwd, const std::string &database)\r\n{\r\n if (!MemcachedProxy::connect(USQL_MYSQL_PROXY_MEMCACHED_HOST))\r\n return false;\r\n if (!mysql_real_connect(this->mySQL, host.c_str(), user.c_str(), passwd.c_str(), database.c_str(), 0, NULL, 0))\r\n return false;\r\n return true;\r\n}\r\n\r\nbool uSQL::MySQLProxy::execCommand(SQLStatement *stmt, SQLProxyResult &result) \r\n{\r\n string hashKey;\r\n if (getKey(stmt, hashKey, result)) {\r\n SQLError sqlError;\r\n MemcachedProxy::remove(stmt, result);\r\n }\r\n \r\n return true;\r\n}\r\n\r\nbool uSQL::MySQLProxy::select(SQLStatement *stmt, SQLProxyResult &result) \r\n{\r\n string hashKey;\r\n if (getKey(stmt, hashKey, result) == false)\r\n return false;\r\n\r\n if (MemcachedProxy::get(stmt, result)) {\r\n result.setCashed(true);\r\n return true;\r\n }\r\n \r\n string stmtString;\r\n stmt->toString(stmtString);\r\n if (mysql_query(this->mySQL, stmtString.c_str()) != 0)\r\n return false;\r\n\r\n bool selectlResult = false;\r\n\r\n MYSQL_RES *mySQLRes;\r\n if ((mySQLRes = mysql_store_result(this->mySQL))) {\r\n int numRows = mysql_num_rows(mySQLRes);\r\n if (0 < numRows) {\r\n MYSQL_FIELD *mySQLField;\r\n std::vector keys;\r\n while ((mySQLField = mysql_fetch_field(mySQLRes)))\r\n keys.push_back(mySQLField->name);\r\n MYSQL_ROW mySQLRow = mysql_fetch_row(mySQLRes);\r\n if (mySQLRow) {\r\n SQLProxyDataSet *resultSet = result.getResultSet();\r\n int numFields = mysql_num_fields(mySQLRes);\r\n for (int n=0 ; nset(key, mySQLRow[n] ? mySQLRow[n] : \"\");\r\n }\r\n selectlResult = set(stmt, resultSet, result);\r\n }\r\n }\r\n mysql_free_result(mySQLRes) ;\r\n }\r\n \r\n return selectlResult;\r\n}\r\n\r\nbool uSQL::MySQLProxy::query(SQLStatement *stmt, SQLProxyResult &result) \r\n{\r\n result.clear();\r\n \r\n SQLCommand *sqlCmd = stmt->getCommandNode();\r\n \r\n if (!sqlCmd) {\r\n result.setErrorMessage(\"COMMAND section was not found\");\r\n return false;\r\n }\r\n\r\n bool execResult = false;\r\n \r\n if (sqlCmd->isSelect()) {\r\n execResult = select(stmt, result);\r\n }\r\n else {\r\n execResult = execCommand(stmt, result);\r\n }\r\n \r\n return execResult;\r\n}\r\n\/******************************************************************\r\n *\r\n * uSQL for C++\r\n *\r\n * Copyright (C) Satoshi Konno 2012\r\n *\r\n * This is licensed under BSD-style license, see file COPYING.\r\n *\r\n ******************************************************************\/\r\n\r\n#include \"MySQLProxy.h\"\r\n\r\nusing namespace std;\r\nusing namespace uSQL;\r\n\r\nstatic const char *USQL_MYSQL_PROXY_MEMCACHED_HOST = \"192.168.100.111\";\r\n\r\nuSQL::MySQLProxy::MySQLProxy()\r\n{\r\n this->mySQL = mysql_init(NULL);\r\n}\r\n\r\nuSQL::MySQLProxy::~MySQLProxy()\r\n{\r\n mysql_close(this->mySQL);\r\n}\r\n\r\nbool uSQL::MySQLProxy::connect(const std::string &host, const std::string &user, const std::string &passwd, const std::string &database)\r\n{\r\n if (!MemcachedProxy::connect(USQL_MYSQL_PROXY_MEMCACHED_HOST))\r\n return false;\r\n if (!mysql_real_connect(this->mySQL, host.c_str(), user.c_str(), passwd.c_str(), database.c_str(), 0, NULL, 0))\r\n return false;\r\n return true;\r\n}\r\n\r\nbool uSQL::MySQLProxy::execCommand(SQLStatement *stmt, SQLProxyResult &result) \r\n{\r\n string hashKey;\r\n if (getKey(stmt, hashKey, result)) {\r\n SQLError sqlError;\r\n MemcachedProxy::remove(stmt, result);\r\n }\r\n \r\n string stmtString;\r\n stmt->toString(stmtString);\r\n if (mysql_query(this->mySQL, stmtString.c_str()) != 0)\r\n return false;\r\n \r\n return true;\r\n}\r\n\r\nbool uSQL::MySQLProxy::select(SQLStatement *stmt, SQLProxyResult &result) \r\n{\r\n string hashKey;\r\n if (getKey(stmt, hashKey, result) == false)\r\n return false;\r\n\r\n if (MemcachedProxy::get(stmt, result)) {\r\n result.setCashed(true);\r\n return true;\r\n }\r\n \r\n string stmtString;\r\n stmt->toString(stmtString);\r\n if (mysql_query(this->mySQL, stmtString.c_str()) != 0)\r\n return false;\r\n\r\n bool selectlResult = false;\r\n\r\n MYSQL_RES *mySQLRes;\r\n if ((mySQLRes = mysql_store_result(this->mySQL))) {\r\n int numRows = mysql_num_rows(mySQLRes);\r\n if (0 < numRows) {\r\n MYSQL_FIELD *mySQLField;\r\n std::vector keys;\r\n while ((mySQLField = mysql_fetch_field(mySQLRes)))\r\n keys.push_back(mySQLField->name);\r\n MYSQL_ROW mySQLRow = mysql_fetch_row(mySQLRes);\r\n if (mySQLRow) {\r\n SQLProxyDataSet *resultSet = result.getResultSet();\r\n int numFields = mysql_num_fields(mySQLRes);\r\n for (int n=0 ; nset(key, mySQLRow[n] ? mySQLRow[n] : \"\");\r\n }\r\n selectlResult = set(stmt, resultSet, result);\r\n }\r\n }\r\n mysql_free_result(mySQLRes) ;\r\n }\r\n \r\n return selectlResult;\r\n}\r\n\r\nbool uSQL::MySQLProxy::query(SQLStatement *stmt, SQLProxyResult &result) \r\n{\r\n result.clear();\r\n \r\n SQLCommand *sqlCmd = stmt->getCommandNode();\r\n \r\n if (!sqlCmd) {\r\n result.setErrorMessage(\"COMMAND section was not found\");\r\n return false;\r\n }\r\n\r\n bool execResult = false;\r\n \r\n if (sqlCmd->isSelect()) {\r\n execResult = select(stmt, result);\r\n }\r\n else {\r\n execResult = execCommand(stmt, result);\r\n }\r\n \r\n return execResult;\r\n}\r\n<|endoftext|>"} {"text":"\/*\n Tests for the emoticon engine\n\n Copyright (c) 2003 by Martijn Klingens \n\n Kopete (c) 2002-2003 by the Kopete developers \n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"kopeteemoticons.h\"\n#include \"kopeteprefs.h\"\n\nstatic QTextStream _out( stdout, IO_WriteOnly );\n\n\/*\n There are three sets of tests, the Kopete 0.7 baseline with tests that were\n working properly in Kopete 0.7.x. When these fail it's a real regression.\n\n The second set are those known to work in the current codebase.\n\n The last set is the set with tests that are known to fail right now.\n\n Each entry in a set consists of two strings. The first string is the input,\n the second string is the EXPECTED output. If the two differ the test is\n considered failed and the actual result is output for comparison.\n\n A set should end with an entry containing at least one null pointer.\n*\/\n\ntypedef const char * TestSet[][ 2 ];\n\n\nstatic TestSet kopete07Baseline =\n{\n\t{ NULL, NULL }\n};\n\nstatic TestSet knownGood =\n{\n\t{ \":):)\", \"\"\n\t\t\t \"\" },\n\t{ \"\", \"\" },\n\t{ \"End of sentence:p\", \"End of sentence\" },\n\t{ \"http:\/\/www.kde.org\", \"http:\/\/www.kde.org\" },\n\t{ NULL, NULL }\n};\n\nstatic TestSet knownBroken =\n{\n\t{ \">:-)\", \"\" },\n\t{ \":))\", \":))\" },\n\t{ \"In a sentence:practical example\", \"In a sentence:practical example\" },\n\t{ \"Bla ( )\", \"Bla ( )\" },\n\t{ \":D and :-D are not the same as :d and :-d\", \" and are not the same as :d and :-d\" },\n\t\/\/ A future emoticon theme may very well have an emoticon for :d\/:-d (an\n\t\/\/ upward tongue expression - Casey\n\t{ \"4d:D>:)F:\/>:-(:Pu:d9\", \"4d:D>:)F:\/>:-(:Pu:d9\" },\n\t{ \"<::pvar:: test=1>\", \"<::pvar:: test=1>\" },\n\t{ \"a non-breaking space ( ) character\", \"a non-breaking space ( ) character\" },\n\t{ \"-+-[-:-(-:-)-:-]-+-\", \"-+-[-:-(-:-)-:-]-+-\" },\n\t{ \"::shrugs::\", \"::shrugs::\" },\n\t{ NULL, NULL }\n};\n\nvoid runTests( QString description, TestSet tests )\n{\n\t\/\/ Detect the image path by copying some code from kopeteemoticons.cpp\n\t\/\/ Use the KMess-Cartoon theme because it has a smiley for the troublesome ':\/' pattern, which\n\t\/\/ also exists in http:\/\/ URIs. (Default doesn't have such a smiley, making it useless for\n\t\/\/ the test.)\n\tQString path = KGlobal::dirs()->findResource( \"data\", \"kopete\/pics\/emoticons\/KMess-Cartoon\/smile.png\" ).replace( \"smile.png\", QString::null );\n\n\t_out << endl;\n\t_out << \"* Running test set '\" << description << \"'\" << endl;\n\n\tuint i = 0;\n\twhile ( tests[ i ][ 0 ] && tests[ i ][ 1 ] )\n\t{\n\t\tQString result = KopeteEmoticons::parseEmoticons( tests[ i ][ 0 ] ).replace( path, QString::null );\n\n\t\tif ( result == tests[ i ][ 1 ] )\n\t\t{\n\t\t\t_out << \" - Succeeded test for '\" << tests[ i ][ 0 ] << \"'\" << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t_out << \" - FAILED test for '\" << tests[ i ][ 0 ] << \"'\" << endl;\n\t\t\t_out << \" Expected output: '\" << tests[ i ][ 1 ] << \"'\" << endl;\n\t\t\t_out << \" Real output: '\" << result << \"'\" << endl;\n\t\t}\n\n\t\ti++;\n\t}\n}\n\nint main( int argc, char *argv[] )\n{\n\tKAboutData aboutData( \"kopeteemoticontest\", \"kopeteemoticontest\", \"version\" );\n\tKCmdLineArgs::init( argc, argv, &aboutData );\n\tKApplication app( \"kopeteemoticontest\" );\n\n\t\/\/ Set prefs (but don't save them :)\n\tKopetePrefs::prefs()->setUseEmoticons( true );\n\tKopetePrefs::prefs()->setIconTheme( \"KMess-Cartoon\" );\n\n\trunTests( \"Baseline of working emoticons in Kopete 0.7\", kopete07Baseline );\n\trunTests( \"Known working tests\", knownGood );\n\trunTests( \"Known broken tests\", knownBroken );\n\n\treturn 0;\n}\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\nNew test (bug 92890) CCBUG: 92890\/*\n Tests for the emoticon engine\n\n Copyright (c) 2003 by Martijn Klingens \n\n Kopete (c) 2002-2003 by the Kopete developers \n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"kopeteemoticons.h\"\n#include \"kopeteprefs.h\"\n\nstatic QTextStream _out( stdout, IO_WriteOnly );\n\n\/*\n There are three sets of tests, the Kopete 0.7 baseline with tests that were\n working properly in Kopete 0.7.x. When these fail it's a real regression.\n\n The second set are those known to work in the current codebase.\n\n The last set is the set with tests that are known to fail right now.\n\n Each entry in a set consists of two strings. The first string is the input,\n the second string is the EXPECTED output. If the two differ the test is\n considered failed and the actual result is output for comparison.\n\n A set should end with an entry containing at least one null pointer.\n*\/\n\ntypedef const char * TestSet[][ 2 ];\n\n\nstatic TestSet kopete07Baseline =\n{\n\t{ NULL, NULL }\n};\n\nstatic TestSet knownGood =\n{\n\t{ \":):)\", \"\"\n\t\t\t \"\" },\n\t{ \"\", \"\" },\n\t{ \"End of sentence:p\", \"End of sentence\" },\n\t{ \"http:\/\/www.kde.org\", \"http:\/\/www.kde.org\" },\n\t{ NULL, NULL }\n};\n\nstatic TestSet knownBroken =\n{\n\t{ \">:-)\", \"\" },\n\t{ \":))\", \":))\" },\n\t{ \"In a sentence:practical example\", \"In a sentence:practical example\" },\n\t{ \"Bla ( )\", \"Bla ( )\" },\n\t{ \":D and :-D are not the same as :d and :-d\", \" and are not the same as :d and :-d\" },\n\t\/\/ A future emoticon theme may very well have an emoticon for :d\/:-d (an\n\t\/\/ upward tongue expression - Casey\n\t{ \"4d:D>:)F:\/>:-(:Pu:d9\", \"4d:D>:)F:\/>:-(:Pu:d9\" },\n\t{ \"<::pvar:: test=1>\", \"<::pvar:: test=1>\" },\n\t{ \"a non-breaking space ( ) character\", \"a non-breaking space ( ) character\" },\n\t{ \"-+-[-:-(-:-)-:-]-+-\", \"-+-[-:-(-:-)-:-]-+-\" },\n\t{ \"::shrugs::\", \"::shrugs::\" },\n\t{ \":Ptesting:P\", \":Ptesting:P\" },\n\t{ NULL, NULL }\n};\n\nvoid runTests( QString description, TestSet tests )\n{\n\t\/\/ Detect the image path by copying some code from kopeteemoticons.cpp\n\t\/\/ Use the KMess-Cartoon theme because it has a smiley for the troublesome ':\/' pattern, which\n\t\/\/ also exists in http:\/\/ URIs. (Default doesn't have such a smiley, making it useless for\n\t\/\/ the test.)\n\tQString path = KGlobal::dirs()->findResource( \"data\", \"kopete\/pics\/emoticons\/KMess-Cartoon\/smile.png\" ).replace( \"smile.png\", QString::null );\n\n\t_out << endl;\n\t_out << \"* Running test set '\" << description << \"'\" << endl;\n\n\tuint i = 0;\n\twhile ( tests[ i ][ 0 ] && tests[ i ][ 1 ] )\n\t{\n\t\tQString result = KopeteEmoticons::parseEmoticons( tests[ i ][ 0 ] ).replace( path, QString::null );\n\n\t\tif ( result == tests[ i ][ 1 ] )\n\t\t{\n\t\t\t_out << \" - Succeeded test for '\" << tests[ i ][ 0 ] << \"'\" << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t_out << \" - FAILED test for '\" << tests[ i ][ 0 ] << \"'\" << endl;\n\t\t\t_out << \" Expected output: '\" << tests[ i ][ 1 ] << \"'\" << endl;\n\t\t\t_out << \" Real output: '\" << result << \"'\" << endl;\n\t\t}\n\n\t\ti++;\n\t}\n}\n\nint main( int argc, char *argv[] )\n{\n\tKAboutData aboutData( \"kopeteemoticontest\", \"kopeteemoticontest\", \"version\" );\n\tKCmdLineArgs::init( argc, argv, &aboutData );\n\tKApplication app( \"kopeteemoticontest\" );\n\n\t\/\/ Set prefs (but don't save them :)\n\tKopetePrefs::prefs()->setUseEmoticons( true );\n\tKopetePrefs::prefs()->setIconTheme( \"KMess-Cartoon\" );\n\n\trunTests( \"Baseline of working emoticons in Kopete 0.7\", kopete07Baseline );\n\trunTests( \"Known working tests\", knownGood );\n\trunTests( \"Known broken tests\", knownBroken );\n\n\treturn 0;\n}\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\n<|endoftext|>"} {"text":"\/\/Copyright (c) 2018 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"utils\/linearAlg2D.h\" \/\/Distance from point to line.\n#include \"MergeInfillLines.h\"\n\nnamespace cura\n{\n\n MergeInfillLines::MergeInfillLines(ExtruderPlan& plan, const coord_t nozzle_size, const coord_t maximum_resolution) : extruder_plan(plan), nozzle_size(nozzle_size), maximum_resolution(maximum_resolution)\n {\n \/\/Just copy the parameters to their fields.\n }\n\n coord_t MergeInfillLines::calcPathLength(const Point path_start, GCodePath& path) const\n {\n Point previous_point = path_start;\n coord_t result = 0;\n for (const Point point : path.points)\n {\n result += vSize(point - previous_point);\n previous_point = point;\n }\n return result;\n }\n\n \/*\n * first_is_already_merged == false\n *\n * o o\n * \/ \/\n * \/ \/\n * \/ + \/ ---> -(t)-o-----o\n * \/ \/\n * \/ \/\n * o o\n *\n * travel (t) to first location is done through first_path_start_changed and new_first_path_start.\n * this gets rid of the tiny \"blips\". Depending on the merged line distance a small gap may appear, but this is\n * accounted for in the volume.\n *\n * first_is_already_merged == true\n *\n * o\n * \/\n * \/\n * o-----o + \/ ---> o-----------o or with slight o-----o-----o\n * \/ \/ \/ bend \/\n * \/ \/ \/ \/\n * o o o o\n *\n *\/\n bool MergeInfillLines::mergeLinesSideBySide(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start, coord_t& error_area) const\n {\n Point average_first_path;\n\n coord_t first_path_length = calcPathLength(first_path_start, first_path);\n coord_t first_path_length_flow = first_path_length * first_path.flow; \/\/To get the volume we don't need to include the line width since it's the same for both lines.\n const coord_t line_width = first_path.config->getLineWidth();\n\n if (first_is_already_merged)\n {\n \/\/ take second point of path, first_path.points[0]\n average_first_path = first_path.points[0];\n }\n else\n {\n average_first_path += first_path_start;\n for (const Point point : first_path.points)\n {\n average_first_path += point;\n }\n average_first_path \/= (first_path.points.size() + 1);\n }\n\n coord_t second_path_length = calcPathLength(second_path_start, second_path);\n Point average_second_path = second_path_start;\n for (const Point point : second_path.points)\n {\n average_second_path += point;\n }\n coord_t second_path_length_flow = second_path_length *= second_path.flow;\n average_second_path \/= (coord_t) (second_path.points.size() + 1);\n\n \/\/ predict new length and flow and if the new flow is to big, don't merge. conditions in this part must exactly match the actual merging\n coord_t new_path_length = first_path_length;\n coord_t dist2_from_line = 0;\n coord_t new_error_area = 0;\n coord_t merged_part_length = 0;\n if (first_is_already_merged)\n {\n \/\/ check if the new point is a good extension of last part of existing polyline\n \/\/ because of potential accumulation of errors introduced each time a line is merged, we do not allow any error.\n if (first_path.points.size() > 1) {\n dist2_from_line = LinearAlg2D::getDist2FromLine(average_second_path, first_path.points[first_path.points.size() - 2], first_path.points[first_path.points.size() - 1]);\n merged_part_length = vSize(first_path.points[first_path.points.size() - 2] - average_second_path);\n new_error_area = sqrt(dist2_from_line) * merged_part_length \/ 2;\n }\n \/\/ The max error margin uses the meshfix_maximum_resolution setting\n if (first_path.points.size() > 1 && error_area + new_error_area < merged_part_length * maximum_resolution)\n {\n new_path_length -= vSize(first_path.points[first_path.points.size() - 2] - first_path.points[first_path.points.size() - 1]);\n new_path_length += vSize(first_path.points[first_path.points.size() - 2] - average_second_path);\n }\n else\n {\n new_path_length += vSize(first_path.points[first_path.points.size() - 1] - average_second_path);\n }\n }\n else\n {\n new_path_length -= vSize(first_path.points.back() - first_path_start);\n new_path_length += vSize(average_second_path - average_first_path);\n }\n double new_flow = ((first_path_length_flow + second_path_length_flow) \/ static_cast(new_path_length));\n if (new_flow > 2 * nozzle_size \/ line_width) \/\/ line width becomes too wide.\n {\n return false;\n }\n\n \/\/ do the actual merging\n if (first_is_already_merged)\n {\n \/\/ check if the new point is a good extension of last part of existing polyline\n \/\/ because of potential accumulation of errors introduced each time a line is merged, we do not allow any error.\n if (first_path.points.size() > 1 && error_area + new_error_area < line_width * line_width)\n {\n first_path.points[first_path.points.size() - 1] = average_second_path;\n error_area += new_error_area;\n } else {\n first_path.points.push_back(average_second_path);\n error_area = 0;\n }\n }\n else\n {\n new_first_path_start = average_first_path;\n first_path.points.clear();\n first_path.points.push_back(average_second_path);\n error_area = 0;\n }\n\n first_path.flow = static_cast(first_path_length_flow + second_path_length_flow) \/ new_path_length;\n\n return true;\n }\n\n\n bool MergeInfillLines::tryMerge(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start, coord_t& error_area) const\n {\n const Point first_path_end = first_path.points.back();\n const Point second_path_end = second_path.points.back();\n const coord_t line_width = first_path.config->getLineWidth();\n\n if (vSize2(first_path_end - second_path_start) < line_width * line_width)\n {\n return false;\n }\n\n \/\/Lines may be adjacent side-by-side then.\n Point first_path_leave_point;\n coord_t merged_size2;\n if (first_is_already_merged)\n {\n first_path_leave_point = first_path.points.back(); \/\/ this is the point that's going to merge\n } else {\n first_path_leave_point = (first_path_start + first_path_end) \/ 2;\n }\n const Point second_path_destination_point = (second_path_start + second_path_end) \/ 2;\n const Point merged_direction = second_path_destination_point - first_path_leave_point;\n if (first_is_already_merged)\n {\n merged_size2 = vSize2(second_path_destination_point - first_path.points.back()); \/\/ check distance with last point in merged line that is to be replaced\n }\n else\n {\n merged_size2 = vSize2(merged_direction);\n }\n if (merged_size2 > 25 * line_width * line_width)\n {\n return false; \/\/Lines are too far away from each other.\n }\n if (merged_direction.X == 0 && merged_direction.Y == 0)\n {\n return true; \/\/ we can just disregard the second point as it's exactly at the leave point of the first path.\n }\n\n \/\/ Max 1 line width to the side of the merged_direction\n if (LinearAlg2D::getDist2FromLine(first_path_end, second_path_destination_point, second_path_destination_point + merged_direction) > line_width * line_width\n || LinearAlg2D::getDist2FromLine(second_path_start, first_path_leave_point, first_path_leave_point + merged_direction) > line_width * line_width\n || LinearAlg2D::getDist2FromLine(second_path_end, first_path_leave_point, first_path_leave_point + merged_direction) > line_width * line_width\n \/\/|| abs(dot(normal(merged_direction, 1000), normal(second_path_end - second_path_start, 1000))) > 866000 \/\/ 866000 angle of old second_path with new merged direction should not be too small (30 degrees), as it will introduce holes\n )\n {\n return false; \/\/One of the lines is too far from the merged line. Lines would be too wide or too far off.\n }\n if (first_is_already_merged && first_path.points.size() > 1 && first_path.points[first_path.points.size() - 2] == second_path_destination_point) \/\/ yes this can actually happen\n {\n return false;\n }\n\n return mergeLinesSideBySide(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start, error_area);\n }\n\n\n bool MergeInfillLines::mergeInfillLines(std::vector& paths, const Point& starting_position) const\n {\n \/* Algorithm overview:\n 1. Loop over all lines to see if they can be merged.\n 1a. Check if two adjacent lines can be merged (skipping travel moves in\n between).\n 1b. If they can, merge both lines into the first line.\n 1c. If they are merged, check next that the first line can be merged\n with the line after the second line.\n 2. Do a second iteration over all paths to remove the tombstones. *\/\n std::vector remove_path_indices;\n std::set is_merged;\n std::set removed; \/\/ keep track of what we already removed, so don't remove it again\n\n \/\/For each two adjacent lines, see if they can be merged.\n size_t first_path_index = 0;\n Point first_path_start = Point(starting_position.X, starting_position.Y); \/\/ this one is not going to be overwritten\n size_t second_path_index = 1;\n coord_t error_area = 0;\n\n for (; second_path_index < paths.size(); second_path_index++)\n {\n GCodePath& first_path = paths[first_path_index];\n GCodePath& second_path = paths[second_path_index];\n Point second_path_start = paths[second_path_index - 1].points.back();\n\n if (second_path.config->isTravelPath())\n {\n continue; \/\/Skip travel paths, we're looking for the first non-travel path.\n }\n\n bool allow_try_merge = true;\n \/\/ see if we meet criteria to merge. should be: travel - path1 not travel - (...) - travel - path2 not travel - travel\n \/\/ we're checking the travels here\n if (first_path_index <= 1 || !paths[first_path_index - 1].isTravelPath()) \/\/ \"<= 1\" because we don't want the first travel being changed. That may introduce a hole somewhere\n {\n allow_try_merge = false;\n }\n if (second_path_index + 1 >= paths.size() || !paths[second_path_index + 1].isTravelPath())\n {\n allow_try_merge = false;\n }\n if (first_path.config->isTravelPath()) \/\/Don't merge travel moves.\n {\n allow_try_merge = false;\n }\n if (first_path.config != second_path.config) \/\/Only merge lines that have the same type.\n {\n allow_try_merge = false;\n }\n if (first_path.config->type != PrintFeatureType::Infill && first_path.config->type != PrintFeatureType::Skin) \/\/Only merge skin and infill lines.\n {\n allow_try_merge = false;\n }\n const bool first_is_already_merged = is_merged.find(first_path_index) != is_merged.end();\n if ((!first_is_already_merged && first_path.points.size() > 1) || second_path.points.size() > 1)\n {\n \/\/ For now we only merge simple lines, not polylines, to keep it simple.\n \/\/ If the first line is already a merged line, then allow it.\n allow_try_merge = false;\n }\n\n Point new_first_path_start;\n if (allow_try_merge && tryMerge(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start, error_area))\n {\n if (!first_is_already_merged)\n {\n paths[first_path_index - 1].points.back().X = new_first_path_start.X;\n paths[first_path_index - 1].points.back().Y = new_first_path_start.Y;\n }\n \/* If we combine two lines, the next path may also be merged into the fist line, so we do NOT update\n first_path_index. *\/\n for (size_t to_delete_index = first_path_index + 1; to_delete_index <= second_path_index; to_delete_index++)\n {\n if (removed.find(to_delete_index) == removed.end()) \/\/ if there are line(s) between first and second, then those lines are already marked as to be deleted, only add the new line(s)\n {\n remove_path_indices.push_back(to_delete_index);\n removed.insert(to_delete_index);\n }\n }\n is_merged.insert(first_path_index);\n }\n else\n {\n \/* If we do not combine, the next iteration we must simply merge the\n second path with the line after it. *\/\n first_path_index = second_path_index;\n first_path_start = second_path_start;\n }\n }\n\n \/\/Delete all removed lines in one pass so that we need to move lines less often.\n if (!remove_path_indices.empty())\n {\n size_t path_index = remove_path_indices[0];\n for (size_t removed_position = 1; removed_position < remove_path_indices.size(); removed_position++)\n {\n for (; path_index < remove_path_indices[removed_position] - removed_position; path_index++)\n {\n paths[path_index] = paths[path_index + removed_position]; \/\/Shift all paths.\n }\n }\n for (; path_index < paths.size() - remove_path_indices.size(); path_index++) \/\/Remaining shifts at the end.\n {\n paths[path_index] = paths[path_index + remove_path_indices.size()];\n }\n paths.erase(paths.begin() + path_index, paths.end());\n return true;\n }\n else\n {\n return false;\n }\n }\n}\/\/namespace cura\nAdded comment.\/\/Copyright (c) 2018 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"utils\/linearAlg2D.h\" \/\/Distance from point to line.\n#include \"MergeInfillLines.h\"\n\nnamespace cura\n{\n\n MergeInfillLines::MergeInfillLines(ExtruderPlan& plan, const coord_t nozzle_size, const coord_t maximum_resolution) : extruder_plan(plan), nozzle_size(nozzle_size), maximum_resolution(maximum_resolution)\n {\n \/\/Just copy the parameters to their fields.\n }\n\n coord_t MergeInfillLines::calcPathLength(const Point path_start, GCodePath& path) const\n {\n Point previous_point = path_start;\n coord_t result = 0;\n for (const Point point : path.points)\n {\n result += vSize(point - previous_point);\n previous_point = point;\n }\n return result;\n }\n\n \/*\n * first_is_already_merged == false\n *\n * o o\n * \/ \/\n * \/ \/\n * \/ + \/ ---> -(t)-o-----o\n * \/ \/\n * \/ \/\n * o o\n *\n * travel (t) to first location is done through first_path_start_changed and new_first_path_start.\n * this gets rid of the tiny \"blips\". Depending on the merged line distance a small gap may appear, but this is\n * accounted for in the volume.\n *\n * first_is_already_merged == true\n *\n * o\n * \/\n * \/\n * o-----o + \/ ---> o-----------o or with slight o-----o-----o\n * \/ \/ \/ bend \/\n * \/ \/ \/ \/\n * o o o o\n *\n *\/\n bool MergeInfillLines::mergeLinesSideBySide(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start, coord_t& error_area) const\n {\n Point average_first_path;\n\n coord_t first_path_length = calcPathLength(first_path_start, first_path);\n coord_t first_path_length_flow = first_path_length * first_path.flow; \/\/To get the volume we don't need to include the line width since it's the same for both lines.\n const coord_t line_width = first_path.config->getLineWidth();\n\n if (first_is_already_merged)\n {\n \/\/ take second point of path, first_path.points[0]\n average_first_path = first_path.points[0];\n }\n else\n {\n average_first_path += first_path_start;\n for (const Point point : first_path.points)\n {\n average_first_path += point;\n }\n average_first_path \/= (first_path.points.size() + 1);\n }\n\n coord_t second_path_length = calcPathLength(second_path_start, second_path);\n Point average_second_path = second_path_start;\n for (const Point point : second_path.points)\n {\n average_second_path += point;\n }\n coord_t second_path_length_flow = second_path_length *= second_path.flow;\n average_second_path \/= (coord_t) (second_path.points.size() + 1);\n\n \/\/ predict new length and flow and if the new flow is to big, don't merge. conditions in this part must exactly match the actual merging\n coord_t new_path_length = first_path_length;\n coord_t dist2_from_line = 0;\n coord_t new_error_area = 0;\n coord_t merged_part_length = 0;\n if (first_is_already_merged)\n {\n \/\/ check if the new point is a good extension of last part of existing polyline\n \/\/ because of potential accumulation of errors introduced each time a line is merged, we do not allow any error.\n if (first_path.points.size() > 1) {\n dist2_from_line = LinearAlg2D::getDist2FromLine(average_second_path, first_path.points[first_path.points.size() - 2], first_path.points[first_path.points.size() - 1]);\n merged_part_length = vSize(first_path.points[first_path.points.size() - 2] - average_second_path);\n new_error_area = sqrt(dist2_from_line) * merged_part_length \/ 2;\n }\n \/\/ The max error margin uses the meshfix_maximum_resolution setting\n if (first_path.points.size() > 1 && error_area + new_error_area < merged_part_length * maximum_resolution)\n {\n new_path_length -= vSize(first_path.points[first_path.points.size() - 2] - first_path.points[first_path.points.size() - 1]);\n new_path_length += vSize(first_path.points[first_path.points.size() - 2] - average_second_path);\n }\n else\n {\n new_path_length += vSize(first_path.points[first_path.points.size() - 1] - average_second_path);\n }\n }\n else\n {\n new_path_length -= vSize(first_path.points.back() - first_path_start);\n new_path_length += vSize(average_second_path - average_first_path);\n }\n double new_flow = ((first_path_length_flow + second_path_length_flow) \/ static_cast(new_path_length));\n if (new_flow > 2 * nozzle_size \/ line_width) \/\/ line width becomes too wide.\n {\n return false;\n }\n\n \/\/ do the actual merging\n if (first_is_already_merged)\n {\n \/\/ check if the new point is a good extension of last part of existing polyline\n \/\/ because of potential accumulation of errors introduced each time a line is merged, we do not allow any error.\n if (first_path.points.size() > 1 && error_area + new_error_area < line_width * line_width)\n {\n first_path.points[first_path.points.size() - 1] = average_second_path;\n error_area += new_error_area;\n } else {\n first_path.points.push_back(average_second_path);\n error_area = 0;\n }\n }\n else\n {\n new_first_path_start = average_first_path;\n first_path.points.clear();\n first_path.points.push_back(average_second_path);\n error_area = 0;\n }\n\n first_path.flow = static_cast(first_path_length_flow + second_path_length_flow) \/ new_path_length;\n\n return true;\n }\n\n\n bool MergeInfillLines::tryMerge(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start, coord_t& error_area) const\n {\n const Point first_path_end = first_path.points.back();\n const Point second_path_end = second_path.points.back();\n const coord_t line_width = first_path.config->getLineWidth();\n\n \/\/ Reintroduction of this check prevents [CURA-5674] printing spurious infill-lines to origin:\n if (vSize2(first_path_end - second_path_start) < line_width * line_width)\n {\n return false;\n }\n\n \/\/Lines may be adjacent side-by-side then.\n Point first_path_leave_point;\n coord_t merged_size2;\n if (first_is_already_merged)\n {\n first_path_leave_point = first_path.points.back(); \/\/ this is the point that's going to merge\n } else {\n first_path_leave_point = (first_path_start + first_path_end) \/ 2;\n }\n const Point second_path_destination_point = (second_path_start + second_path_end) \/ 2;\n const Point merged_direction = second_path_destination_point - first_path_leave_point;\n if (first_is_already_merged)\n {\n merged_size2 = vSize2(second_path_destination_point - first_path.points.back()); \/\/ check distance with last point in merged line that is to be replaced\n }\n else\n {\n merged_size2 = vSize2(merged_direction);\n }\n if (merged_size2 > 25 * line_width * line_width)\n {\n return false; \/\/Lines are too far away from each other.\n }\n if (merged_direction.X == 0 && merged_direction.Y == 0)\n {\n return true; \/\/ we can just disregard the second point as it's exactly at the leave point of the first path.\n }\n\n \/\/ Max 1 line width to the side of the merged_direction\n if (LinearAlg2D::getDist2FromLine(first_path_end, second_path_destination_point, second_path_destination_point + merged_direction) > line_width * line_width\n || LinearAlg2D::getDist2FromLine(second_path_start, first_path_leave_point, first_path_leave_point + merged_direction) > line_width * line_width\n || LinearAlg2D::getDist2FromLine(second_path_end, first_path_leave_point, first_path_leave_point + merged_direction) > line_width * line_width\n \/\/|| abs(dot(normal(merged_direction, 1000), normal(second_path_end - second_path_start, 1000))) > 866000 \/\/ 866000 angle of old second_path with new merged direction should not be too small (30 degrees), as it will introduce holes\n )\n {\n return false; \/\/One of the lines is too far from the merged line. Lines would be too wide or too far off.\n }\n if (first_is_already_merged && first_path.points.size() > 1 && first_path.points[first_path.points.size() - 2] == second_path_destination_point) \/\/ yes this can actually happen\n {\n return false;\n }\n\n return mergeLinesSideBySide(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start, error_area);\n }\n\n\n bool MergeInfillLines::mergeInfillLines(std::vector& paths, const Point& starting_position) const\n {\n \/* Algorithm overview:\n 1. Loop over all lines to see if they can be merged.\n 1a. Check if two adjacent lines can be merged (skipping travel moves in\n between).\n 1b. If they can, merge both lines into the first line.\n 1c. If they are merged, check next that the first line can be merged\n with the line after the second line.\n 2. Do a second iteration over all paths to remove the tombstones. *\/\n std::vector remove_path_indices;\n std::set is_merged;\n std::set removed; \/\/ keep track of what we already removed, so don't remove it again\n\n \/\/For each two adjacent lines, see if they can be merged.\n size_t first_path_index = 0;\n Point first_path_start = Point(starting_position.X, starting_position.Y); \/\/ this one is not going to be overwritten\n size_t second_path_index = 1;\n coord_t error_area = 0;\n\n for (; second_path_index < paths.size(); second_path_index++)\n {\n GCodePath& first_path = paths[first_path_index];\n GCodePath& second_path = paths[second_path_index];\n Point second_path_start = paths[second_path_index - 1].points.back();\n\n if (second_path.config->isTravelPath())\n {\n continue; \/\/Skip travel paths, we're looking for the first non-travel path.\n }\n\n bool allow_try_merge = true;\n \/\/ see if we meet criteria to merge. should be: travel - path1 not travel - (...) - travel - path2 not travel - travel\n \/\/ we're checking the travels here\n if (first_path_index <= 1 || !paths[first_path_index - 1].isTravelPath()) \/\/ \"<= 1\" because we don't want the first travel being changed. That may introduce a hole somewhere\n {\n allow_try_merge = false;\n }\n if (second_path_index + 1 >= paths.size() || !paths[second_path_index + 1].isTravelPath())\n {\n allow_try_merge = false;\n }\n if (first_path.config->isTravelPath()) \/\/Don't merge travel moves.\n {\n allow_try_merge = false;\n }\n if (first_path.config != second_path.config) \/\/Only merge lines that have the same type.\n {\n allow_try_merge = false;\n }\n if (first_path.config->type != PrintFeatureType::Infill && first_path.config->type != PrintFeatureType::Skin) \/\/Only merge skin and infill lines.\n {\n allow_try_merge = false;\n }\n const bool first_is_already_merged = is_merged.find(first_path_index) != is_merged.end();\n if ((!first_is_already_merged && first_path.points.size() > 1) || second_path.points.size() > 1)\n {\n \/\/ For now we only merge simple lines, not polylines, to keep it simple.\n \/\/ If the first line is already a merged line, then allow it.\n allow_try_merge = false;\n }\n\n Point new_first_path_start;\n if (allow_try_merge && tryMerge(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start, error_area))\n {\n if (!first_is_already_merged)\n {\n paths[first_path_index - 1].points.back().X = new_first_path_start.X;\n paths[first_path_index - 1].points.back().Y = new_first_path_start.Y;\n }\n \/* If we combine two lines, the next path may also be merged into the fist line, so we do NOT update\n first_path_index. *\/\n for (size_t to_delete_index = first_path_index + 1; to_delete_index <= second_path_index; to_delete_index++)\n {\n if (removed.find(to_delete_index) == removed.end()) \/\/ if there are line(s) between first and second, then those lines are already marked as to be deleted, only add the new line(s)\n {\n remove_path_indices.push_back(to_delete_index);\n removed.insert(to_delete_index);\n }\n }\n is_merged.insert(first_path_index);\n }\n else\n {\n \/* If we do not combine, the next iteration we must simply merge the\n second path with the line after it. *\/\n first_path_index = second_path_index;\n first_path_start = second_path_start;\n }\n }\n\n \/\/Delete all removed lines in one pass so that we need to move lines less often.\n if (!remove_path_indices.empty())\n {\n size_t path_index = remove_path_indices[0];\n for (size_t removed_position = 1; removed_position < remove_path_indices.size(); removed_position++)\n {\n for (; path_index < remove_path_indices[removed_position] - removed_position; path_index++)\n {\n paths[path_index] = paths[path_index + removed_position]; \/\/Shift all paths.\n }\n }\n for (; path_index < paths.size() - remove_path_indices.size(); path_index++) \/\/Remaining shifts at the end.\n {\n paths[path_index] = paths[path_index + remove_path_indices.size()];\n }\n paths.erase(paths.begin() + path_index, paths.end());\n return true;\n }\n else\n {\n return false;\n }\n }\n}\/\/namespace cura\n<|endoftext|>"} {"text":"#include \"webcam.hpp\"\n#include \n\nusing namespace cv;\nusing namespace std;\n\nMat ellipticKernel(int width, int height = -1) {\n if (height==-1) {\n return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width\/2, width\/2));\n } else {\n return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width\/2, height\/2));\n }\n}\n\nunsigned long long getMilliseconds() {\n return chrono::system_clock::now().time_since_epoch()\/chrono::milliseconds(1);\n}\n\nvoid morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {\n int width, height;\n width = inout.size().width;\n height = inout.size().height;\n Mat downsample;\n resize(inout, downsample, Size(smallsize,smallsize));\n Mat kernel = ellipticKernel(factor);\n if (diler) {\n erode(downsample, downsample, kernel);\n } else {\n dilate(downsample, downsample, kernel);\n }\n if (eq) {\n equalizeHist(downsample, downsample);\n }\n resize(downsample, inout, Size(width, height));\n}\n\nint main (int argc, char** argv) {\n\n int tracker1, tracker2, tracker3;\n namedWindow(\"s\",1);\n createTrackbar(\"1\",\"s\",&tracker1,100);\n createTrackbar(\"2\",\"s\",&tracker2,100);\n createTrackbar(\"3\",\"s\",&tracker3,100);\n\n CvCapture* capture = 0;\n int width, height, fps;\n\n capture = cvCaptureFromCAM(0);\n\n if (!capture) {\n printf(\"No camera detected!\");\n return -1;\n }\n\n unsigned long long times[100];\n int f = 0;\n for (int i=0; i<100; i++)\n times[i] = 0;\n\n ifstream configFile (\".config\");\n\n if (configFile.is_open()) {\n\n \/\/probably want to support corrupted .config\n string line;\n getline(configFile, line);\n istringstream(line)>>width;\n getline(configFile, line);\n istringstream(line)>>height;\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);\n\n configFile.close();\n\n } else {\n\n initResolutions();\n\n for (int i=36; i<150; i++) {\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);\n }\n\n width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);\n height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);\n\n ofstream configFileOut(\".config\");\n configFileOut << width;\n configFileOut << \"\\n\";\n configFileOut << height;\n configFileOut << \"\\n\";\n configFileOut.close();\n }\n\n bool keepGoing = true;\n\n\/\/ srand(890);\/\/not interested in good randomness\n\n for (int i = 0; i < 30; i++) {\n \/\/ capture some frames so exposure correction takes place\n cvQueryFrame(capture);\n }\n\n Mat background = cvQueryFrame(capture);\n background = background.clone();\n blur(background, background, Size(50,50));\n\n Mat image;\n Mat channel[3];\n unsigned long long timenow = getMilliseconds();\n\n while (keepGoing) {\n image = cvQueryFrame(capture);\n times[0] += getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\/\/ preprocess by rotating according to OVR roll\n\/\/ imshow(\"webcam\", image);\n\n\/\/ let's make multiple masks where 0=not mouth, 1=uncertain\n\n\/\/ then multiply them together and multiply that with image\n\/\/ and run haar classifier on image\n\n Mat gray, blurred_img;\n cvtColor(image, gray, CV_RGB2GRAY);\n blur(image, blurred_img, Size(50,50));\n times[1] += getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\/\/ this mask filters out areas with too many edges\n\/\/ removed for now; it didn't generalize well\n\/*\n Mat canny;\n Canny(gray, canny, 50, 50, 3);\n blur(canny, canny, Size(width\/20,height\/20));\n bitwise_not(canny, canny);\n threshold(canny, canny, 200, 1, THRESH_BINARY);\n blur(canny*255, canny, Size(width\/10, height\/10));\n threshold(canny, canny, 220, 1, THRESH_BINARY);\n imshow(\"canny mask\", gray.mul(canny));\n*\/\n\n\/\/ this mask filters out areas which have not changed much\n\/\/ background needs to be updated when person is not in frame\n\/\/ use OVR SDK to do this later\n Mat flow;\n absdiff(blurred_img, background, flow);\n cvtColor(flow, flow, CV_RGB2GRAY);\n morphFast(flow);\n threshold(flow, flow, 60, 1, THRESH_BINARY);\n\/\/ imshow(\"flow mask\", gray.mul(flow));\n times[2] += getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\/\/ this mask gets anything kind of dark (DK2) and dilates\n Mat kindofdark;\n equalizeHist(gray, kindofdark);\n threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);\n morphFast(kindofdark, 100, 17, 0);\n\/\/ imshow(\"dark mask\", gray.mul(kindofdark));\n times[3] += getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\/\/ this mask gets rid of anything far away from red stuff\n\/\/ did not work well and was slow\n\/*\n Mat notlips;\n Mat channels[3];\n split(image, channels);\n channels[2].convertTo(notlips, CV_32FC1);\n divide(notlips, gray, notlips, 1, CV_32FC1);\n \/\/equalistHist is horrible for a red background\n \/\/equalizeHist(notlips, notlips);\n threshold(notlips, notlips, tracker3\/30.0, 1, THRESH_BINARY);\n notlips.convertTo(notlips, CV_8UC1);\n imshow(\"lip mask\", notlips*255);\n Mat otherMorph = notlips.clone();\n int tx = tracker1+1-(tracker1%2);\n if (tx<3) tx=1;\n if (tx>90) tx=91;\n morphFast(notlips, 100, tx, 0, 0);\n int ty = tracker2+1-(tracker2%2);\n if (ty<3) ty=1;\n if (ty>90) ty=91;\n morphFast(notlips, 100, ty, 0, 1);\n imshow(\"lips2\", notlips.mul(gray));\n morphFast(otherMorph, 100, tx, 0, 1);\n morphFast(otherMorph, 100, tx, 0, 0);\n imshow(\"lips3\", otherMorph.mul(gray));\n waitKey(1);\n*\/\n\n Mat mask = flow.mul(kindofdark);\n\/\/ open the mask\n Mat smallMask0, smallMask1;\n resize(mask, smallMask0, Size(width\/5,height\/5));\n Mat smallKernel = ellipticKernel(69,79);\n erode(smallMask0, smallMask1, smallKernel);\n dilate(smallMask1, smallMask1, smallKernel);\n bitwise_and(smallMask0, smallMask1, smallMask1);\n resize(smallMask1, mask, Size(width, height));\n\/\/ imshow(\"morph mask\", gray.mul(mask));\n times[4] += getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\n\n\/\/ update background with new morph mask\n\/\/ average what we know is background with prior background\n\/\/ dilate it first since we really want to be sure it's bg\n\n\/*\n\/\/ actually dilation is slow and our current mask is already\n\/\/ really nice :)\n Mat dilatedMask;\n dilate(smallMask1, dilatedMask, smallKernel);\n resize(dilatedMask, dilatedMask, Size(width, height));\n imshow(\"erosion\", dilatedMask.mul(gray));\n*\/\n\/\/ imshow(\"background\", background);\n\n\/*\n Moments lol = moments(gray, 1);\n circle(image, Point(lol.m10\/lol.m00,lol.m01\/lol.m00),20,Scalar(128),30);\n imshow(\"leimage\", image);\n*\/\n\n CascadeClassifier mouth_cascade;\n mouth_cascade.load(\"Mouth.xml\");\n vector mouths;\n int scale = 3;\n Mat classifyThis;\n equalizeHist(gray, gray);\/\/ew; watch out not to use this later\n resize(gray.mul(mask), classifyThis, Size(width\/scale,height\/scale));\n\/\/ bilateralFilter(gray, classifyThis, 15, 10, 1);\n mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE);\n Mat rectImage(height, width, CV_8UC1, Scalar(0));\n for (size_t i=0; ihacking#include \"webcam.hpp\"\n#include \n\nusing namespace cv;\nusing namespace std;\n\nMat ellipticKernel(int width, int height = -1) {\n if (height==-1) {\n return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width\/2, width\/2));\n } else {\n return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width\/2, height\/2));\n }\n}\n\nunsigned long long getMilliseconds() {\n return chrono::system_clock::now().time_since_epoch()\/chrono::milliseconds(1);\n}\n\nvoid morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {\n int width, height;\n width = inout.size().width;\n height = inout.size().height;\n Mat downsample;\n resize(inout, downsample, Size(smallsize,smallsize));\n Mat kernel = ellipticKernel(factor);\n if (diler) {\n erode(downsample, downsample, kernel);\n } else {\n dilate(downsample, downsample, kernel);\n }\n if (eq) {\n equalizeHist(downsample, downsample);\n }\n resize(downsample, inout, Size(width, height));\n}\n\nint main (int argc, char** argv) {\n\n int tracker1, tracker2, tracker3;\n namedWindow(\"s\",1);\n createTrackbar(\"1\",\"s\",&tracker1,100);\n createTrackbar(\"2\",\"s\",&tracker2,100);\n createTrackbar(\"3\",\"s\",&tracker3,100);\n\n CvCapture* capture = 0;\n int width, height, fps;\n\n capture = cvCaptureFromCAM(0);\n\n if (!capture) {\n printf(\"No camera detected!\");\n return -1;\n }\n\n unsigned long long times[100];\n int f = 0;\n for (int i=0; i<100; i++)\n times[i] = 0;\n\n ifstream configFile (\".config\");\n\n if (configFile.is_open()) {\n\n \/\/probably want to support corrupted .config\n string line;\n getline(configFile, line);\n istringstream(line)>>width;\n getline(configFile, line);\n istringstream(line)>>height;\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);\n\n configFile.close();\n\n } else {\n\n initResolutions();\n\n for (int i=36; i<150; i++) {\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);\n }\n\n width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);\n height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);\n\n ofstream configFileOut(\".config\");\n configFileOut << width;\n configFileOut << \"\\n\";\n configFileOut << height;\n configFileOut << \"\\n\";\n configFileOut.close();\n }\n\n bool keepGoing = true;\n\n\/\/ srand(890);\/\/not interested in good randomness\n\n for (int i = 0; i < 30; i++) {\n \/\/ capture some frames so exposure correction takes place\n cvQueryFrame(capture);\n }\n\n Mat background = cvQueryFrame(capture);\n background = background.clone();\n blur(background, background, Size(50,50));\n\n Mat image;\n Mat channel[3];\n unsigned long long timenow = getMilliseconds();\n\n while (keepGoing) {\n image = cvQueryFrame(capture);\n times[0] += getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\/\/ preprocess by rotating according to OVR roll\n\/\/ imshow(\"webcam\", image);\n\n\/\/ let's make multiple masks where 0=not mouth, 1=uncertain\n\n\/\/ then multiply them together and multiply that with image\n\/\/ and run haar classifier on image\n\n Mat gray, blurred_img;\n cvtColor(image, gray, CV_RGB2GRAY);\n blur(image, blurred_img, Size(50,50));\n times[1] += getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\/\/ this mask filters out areas with too many edges\n\/\/ removed for now; it didn't generalize well\n\/*\n Mat canny;\n Canny(gray, canny, 50, 50, 3);\n blur(canny, canny, Size(width\/20,height\/20));\n bitwise_not(canny, canny);\n threshold(canny, canny, 200, 1, THRESH_BINARY);\n blur(canny*255, canny, Size(width\/10, height\/10));\n threshold(canny, canny, 220, 1, THRESH_BINARY);\n imshow(\"canny mask\", gray.mul(canny));\n*\/\n\n\/\/ this mask filters out areas which have not changed much\n\/\/ background needs to be updated when person is not in frame\n\/\/ use OVR SDK to do this later\n Mat flow;\n absdiff(blurred_img, background, flow);\n cvtColor(flow, flow, CV_RGB2GRAY);\n morphFast(flow);\n threshold(flow, flow, 60, 1, THRESH_BINARY);\n\/\/ imshow(\"flow mask\", gray.mul(flow));\n times[2] += getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\/\/ this mask gets anything kind of dark (DK2) and dilates\n Mat kindofdark;\n equalizeHist(gray, kindofdark);\n threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);\n morphFast(kindofdark, 100, 17, 0);\n\/\/ imshow(\"dark mask\", gray.mul(kindofdark));\n times[3] += getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\/\/ this mask gets rid of anything far away from red stuff\n\/\/ did not work well and was slow\n\/*\n Mat notlips;\n Mat channels[3];\n split(image, channels);\n channels[2].convertTo(notlips, CV_32FC1);\n divide(notlips, gray, notlips, 1, CV_32FC1);\n \/\/equalistHist is horrible for a red background\n \/\/equalizeHist(notlips, notlips);\n threshold(notlips, notlips, tracker3\/30.0, 1, THRESH_BINARY);\n notlips.convertTo(notlips, CV_8UC1);\n imshow(\"lip mask\", notlips*255);\n Mat otherMorph = notlips.clone();\n int tx = tracker1+1-(tracker1%2);\n if (tx<3) tx=1;\n if (tx>90) tx=91;\n morphFast(notlips, 100, tx, 0, 0);\n int ty = tracker2+1-(tracker2%2);\n if (ty<3) ty=1;\n if (ty>90) ty=91;\n morphFast(notlips, 100, ty, 0, 1);\n imshow(\"lips2\", notlips.mul(gray));\n morphFast(otherMorph, 100, tx, 0, 1);\n morphFast(otherMorph, 100, tx, 0, 0);\n imshow(\"lips3\", otherMorph.mul(gray));\n waitKey(1);\n*\/\n\n Mat mask = flow.mul(kindofdark);\n\/\/ open the mask\n Mat smallMask0, smallMask1;\n resize(mask, smallMask0, Size(width\/5,height\/5));\n Mat smallKernel = ellipticKernel(69,79);\n erode(smallMask0, smallMask1, smallKernel);\n dilate(smallMask1, smallMask1, smallKernel);\n bitwise_and(smallMask0, smallMask1, smallMask1);\n resize(smallMask1, mask, Size(width, height));\n\/\/ imshow(\"morph mask\", gray.mul(mask));\n times[4] += getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\n\n\/\/ update background with new morph mask\n\/\/ average what we know is background with prior background\n\/\/ dilate it first since we really want to be sure it's bg\n\n\/*\n\/\/ actually dilation is slow and our current mask is already\n\/\/ really nice :)\n Mat dilatedMask;\n dilate(smallMask1, dilatedMask, smallKernel);\n resize(dilatedMask, dilatedMask, Size(width, height));\n imshow(\"erosion\", dilatedMask.mul(gray));\n*\/\n\/\/ imshow(\"background\", background);\n\n\/*\n Moments lol = moments(gray, 1);\n circle(image, Point(lol.m10\/lol.m00,lol.m01\/lol.m00),20,Scalar(128),30);\n imshow(\"leimage\", image);\n*\/\n\n CascadeClassifier mouth_cascade;\n mouth_cascade.load(\"Mouth.xml\");\n vector mouths;\n int scale = 3;\n Mat classifyThis;\n equalizeHist(gray, gray);\/\/ew; watch out not to use this later\n resize(gray.mul(mask), classifyThis, Size(width\/scale,height\/scale));\n\/\/ bilateralFilter(gray, classifyThis, 15, 10, 1);\n mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE);\n Mat rectImage(height, width, CV_8UC1, Scalar(0));\n for (size_t i=0; i"} {"text":"#include \"lit.h\"\n#include \"asm.h\"\n#include \"lex.h\"\n#include \"expr.h\"\n#include \"parse.h\"\n#include \"token.h\"\n#include \"stdfunc.h\"\n#include \"util.h\"\n#include \"option.h\"\n#include \"library.h\"\n\nMemoryList mem;\nctrl_t break_list, return_list;\n\n\/\/ ---- for native code --- \/\/\n\nchar *File_read(char *s, int len, FILE *fp) { fread(s, 1, len, fp); return s; }\n\nvoid putNumber(int32_t n) {\n\tprintf(\"%d\", n);\n}\nvoid putString(int32_t *n) {\n\tprintf(\"%s\", (char *)n);\n}\nvoid putln() { printf(\"\\n\"); }\n\nvoid ssleep(uint32_t t) {\n#if defined(WIN32) || defined(WINDOWS)\n\tSleep(t * CLOCKS_PER_SEC \/ 1000);\n#else\n\tusleep(t * CLOCKS_PER_SEC \/ 1000);\n#endif\n}\n\nvoid appendAddr(uint32_t addr) {\n\tmem_info mi = {\n\t\t.addr = addr,\n\t\t.isfree = false\n\t};\n\tmem.mem.push_back(mi);\n}\n\nvoid free_addr(uint32_t addr) {\n\tfor(int i = 0; i < mem.mem.size(); i++) {\n\t\tif(mem.mem[i].addr == addr) {\n\t\t\tfree((void *)mem.mem[i].addr);\n\t\t\tmem.mem[i].isfree = false;\n\t\t}\n\t}\n}\n\nvoid freeAddr() {\n\tif(mem.count() > 0) {\n\t\tfor(size_t i = 0; i < mem.count(); i++) {\n\t\t\tif(mem.mem[i].isfree == 0) {\n\t\t\t\tfree((void *)mem.mem[i].addr);\n\t\t\t\tmem.mem.pop_back();\n\t\t\t}\n\t\t}\n\t}\n}\n\nchar *rea_concat(char *a, char *b) {\n\ta = (char *)realloc(a, strlen(a) + strlen(b) + 2);\n\treturn strcat(a, b);\n}\n\nvoid *funcTable[] = {\n\t(void *) putNumber, \/\/ 0\n\t(void *) putString, \/\/ 4\n\t(void *) putln,\t\t\t\/\/ 8\n\t(void *) malloc, \t\t\/\/ 12\n\t(void *) printf, \t\t\/\/ 16\n\t(void *) appendAddr,\/\/ 20\n\t(void *) ssleep, \t\t\/\/ 24\n\t(void *) fopen, \t\t\/\/ 28\n\t(void *) fprintf, \t\/\/ 32\n\t(void *) fclose,\t\t\/\/ 36\n\t(void *) File_read,\t\/\/ 40\n\t(void *) free_addr,\t\/\/ 44\n\t(void *) freeAddr,\t\/\/ 48\n\t(void *) fgets, \t\t\/\/ 52\n\t(void *) rea_concat \/\/ 56\n};\n\n\n\/\/ Lit class is from here\n\nLit::Lit(int ac, char **av)\n\t:lex(tok), parser(tok), argc(ac), argv(av) {\n\ttok.pos = 0; tok.size = 0xfff;\n\treturn_list.addr_list = (uint32_t *)calloc(sizeof(uint32_t), 1);\n\tbreak_list.addr_list = (uint32_t *)calloc(sizeof(uint32_t), 1);\n}\n\nLit::~Lit() {\n\tfreeAddr();\n}\n\nint Lit::execute(char *source) {\n\tlex.lex(source);\n\tparser.parser();\n\trun();\n\treturn 0;\n}\n\nint Lit::run() {\n\tprintf(\"\");\n\treturn ((int (*)(int *, void**))ntv.code)(0, funcTable);\n}\n\nvoid Lit::interpret() {\n\tstd::string line, all;\n\n\twhile(std::getline(std::cin, line)) {\n\t\tall += line + \" ; \";\n\t\tline.clear();\n\t}\n\n\tclock_t bgn = clock();\n\t\texecute((char *)all.c_str());\n\tclock_t end = clock();\n#ifdef DEBUG\n\tprintf(\"time: %.3lf\\n\", (double)(end - bgn) \/ CLOCKS_PER_SEC);\n#endif\n}\n\nvoid Lit::run_from_file(char *source) {\n\tstd::ifstream ifs_src(source);\n\tif(!ifs_src) ::error(\"LitSystemError: cannot open file '%s'\", source);\n\tstd::istreambuf_iterator it(ifs_src);\n\tstd::istreambuf_iterator last;\n\tstd::string src_all(it, last);\n\t\n\texecute((char *)src_all.c_str());\n}\n\nint Lit::start() {\n\tshow_option();\n\treturn 0;\n}\nbug fix about string concat#include \"lit.h\"\n#include \"asm.h\"\n#include \"lex.h\"\n#include \"expr.h\"\n#include \"parse.h\"\n#include \"token.h\"\n#include \"stdfunc.h\"\n#include \"util.h\"\n#include \"option.h\"\n#include \"library.h\"\n\nMemoryList mem;\nctrl_t break_list, return_list;\n\n\/\/ ---- for native code --- \/\/\n\nchar *File_read(char *s, int len, FILE *fp) { fread(s, 1, len, fp); return s; }\n\nvoid putNumber(int32_t n) {\n\tprintf(\"%d\", n);\n}\nvoid putString(int32_t *n) {\n\tprintf(\"%s\", (char *)n);\n}\nvoid putln() { printf(\"\\n\"); }\n\nvoid ssleep(uint32_t t) {\n#if defined(WIN32) || defined(WINDOWS)\n\tSleep(t * CLOCKS_PER_SEC \/ 1000);\n#else\n\tusleep(t * CLOCKS_PER_SEC \/ 1000);\n#endif\n}\n\nvoid appendAddr(uint32_t addr) {\n\tmem_info mi = {\n\t\t.addr = addr,\n\t\t.isfree = false\n\t};\n\tmem.mem.push_back(mi);\n}\n\nvoid free_addr(uint32_t addr) {\n\tfor(int i = 0; i < mem.mem.size(); i++) {\n\t\tif(mem.mem[i].addr == addr) {\n\t\t\tfree((void *)mem.mem[i].addr);\n\t\t\tmem.mem[i].isfree = false;\n\t\t}\n\t}\n}\n\nvoid freeAddr() {\n\tif(mem.count() > 0) {\n\t\tfor(size_t i = 0; i < mem.count(); i++) {\n\t\t\tif(mem.mem[i].isfree == 0) {\n\t\t\t\tfree((void *)mem.mem[i].addr);\n\t\t\t\tmem.mem.pop_back();\n\t\t\t}\n\t\t}\n\t}\n}\n\nchar *rea_concat(char *a, char *b) {\n\tchar *t = (char *)malloc(strlen(a) + strlen(b) + 2);\n\tstrcpy(t, a);\n\treturn strcat(t, b);\n}\n\nvoid *funcTable[] = {\n\t(void *) putNumber, \/\/ 0\n\t(void *) putString, \/\/ 4\n\t(void *) putln,\t\t\t\/\/ 8\n\t(void *) malloc, \t\t\/\/ 12\n\t(void *) printf, \t\t\/\/ 16\n\t(void *) appendAddr,\/\/ 20\n\t(void *) ssleep, \t\t\/\/ 24\n\t(void *) fopen, \t\t\/\/ 28\n\t(void *) fprintf, \t\/\/ 32\n\t(void *) fclose,\t\t\/\/ 36\n\t(void *) File_read,\t\/\/ 40\n\t(void *) free_addr,\t\/\/ 44\n\t(void *) freeAddr,\t\/\/ 48\n\t(void *) fgets, \t\t\/\/ 52\n\t(void *) rea_concat \/\/ 56\n};\n\n\n\/\/ Lit class is from here\n\nLit::Lit(int ac, char **av)\n\t:lex(tok), parser(tok), argc(ac), argv(av) {\n\ttok.pos = 0; tok.size = 0xfff;\n\treturn_list.addr_list = (uint32_t *)calloc(sizeof(uint32_t), 1);\n\tbreak_list.addr_list = (uint32_t *)calloc(sizeof(uint32_t), 1);\n}\n\nLit::~Lit() {\n\tfreeAddr();\n}\n\nint Lit::execute(char *source) {\n\tlex.lex(source);\n\tparser.parser();\n\trun();\n\treturn 0;\n}\n\nint Lit::run() {\n\tprintf(\"\");\n\treturn ((int (*)(int *, void**))ntv.code)(0, funcTable);\n}\n\nvoid Lit::interpret() {\n\tstd::string line, all;\n\n\twhile(std::getline(std::cin, line)) {\n\t\tall += line + \" ; \";\n\t\tline.clear();\n\t}\n\n\tclock_t bgn = clock();\n\t\texecute((char *)all.c_str());\n\tclock_t end = clock();\n#ifdef DEBUG\n\tprintf(\"time: %.3lf\\n\", (double)(end - bgn) \/ CLOCKS_PER_SEC);\n#endif\n}\n\nvoid Lit::run_from_file(char *source) {\n\tstd::ifstream ifs_src(source);\n\tif(!ifs_src) ::error(\"LitSystemError: cannot open file '%s'\", source);\n\tstd::istreambuf_iterator it(ifs_src);\n\tstd::istreambuf_iterator last;\n\tstd::string src_all(it, last);\n\t\n\texecute((char *)src_all.c_str());\n}\n\nint Lit::start() {\n\tshow_option();\n\treturn 0;\n}\n<|endoftext|>"} {"text":"#include \"webcam.hpp\"\n#include \n\nusing namespace cv;\nusing namespace std;\n\nMat ellipticKernel(int width, int height = -1) {\n if (height==-1) {\n return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width\/2, width\/2));\n } else {\n return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width\/2, height\/2));\n }\n}\n\nunsigned long long getMilliseconds() {\n return chrono::system_clock::now().time_since_epoch()\/chrono::milliseconds(1);\n}\n\nvoid morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {\n int width, height;\n width = inout.size().width;\n height = inout.size().height;\n Mat downsample;\n resize(inout, downsample, Size(smallsize,smallsize));\n Mat kernel = ellipticKernel(factor);\n if (diler) {\n erode(downsample, downsample, kernel);\n } else {\n dilate(downsample, downsample, kernel);\n }\n if (eq) {\n equalizeHist(downsample, downsample);\n }\n resize(downsample, inout, Size(width, height));\n}\n\nint main (int argc, char** argv) {\n\n int tracker1, tracker2, tracker3;\n namedWindow(\"s\",1);\n createTrackbar(\"1\",\"s\",&tracker1,100);\n createTrackbar(\"2\",\"s\",&tracker2,100);\n createTrackbar(\"3\",\"s\",&tracker3,100);\n\n CvCapture* capture = 0;\n int width, height, fps;\n\n capture = cvCaptureFromCAM(0);\n\n if (!capture) {\n printf(\"No camera detected!\");\n return -1;\n }\n\n unsigned long long times[100];\n int f = 0;\n for (int i=0; i<100; i++)\n times[i] = 0;\n\n ifstream configFile (\".config\");\n\n if (configFile.is_open()) {\n\n \/\/probably want to support corrupted .config\n string line;\n getline(configFile, line);\n istringstream(line)>>width;\n getline(configFile, line);\n istringstream(line)>>height;\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);\n\n configFile.close();\n\n } else {\n\n initResolutions();\n\n for (int i=36; i<150; i++) {\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);\n }\n\n width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);\n height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);\n\n ofstream configFileOut(\".config\");\n configFileOut << width;\n configFileOut << \"\\n\";\n configFileOut << height;\n configFileOut << \"\\n\";\n configFileOut.close();\n }\n\n bool keepGoing = true;\n\n\/\/ srand(890);\/\/not interested in good randomness\n\n for (int i = 0; i < 30; i++) {\n \/\/ capture some frames so exposure correction takes place\n cvQueryFrame(capture);\n }\n\n Mat background = cvQueryFrame(capture);\n background = background.clone();\n blur(background, background, Size(50,50));\n\n Mat image;\n Mat channel[3];\n unsigned long long timenow = getMilliseconds();\n\n CascadeClassifier mouth_cascade;\n mouth_cascade.load(\"Mouth.xml\");\n\n while (keepGoing) {\n image = cvQueryFrame(capture);\n times[0] = getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\/\/ preprocess by rotating according to OVR roll\n\/\/ imshow(\"webcam\", image);\n\n\/\/ let's make multiple masks where 0=not mouth, 1=uncertain\n\n\/\/ then multiply them together and multiply that with image\n\/\/ and run haar classifier on image\n\n Mat gray, blurred_img;\n cvtColor(image, gray, CV_RGB2GRAY);\n blur(image, blurred_img, Size(50,50));\n times[1] = getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\/\/ this mask filters out areas which have not changed much\n\/\/ this is horrible with new background; redo it\n Mat flow(height, width, CV_8UC1, 1);\n\/*\n absdiff(blurred_img, background, flow);\n cvtColor(flow, flow, CV_RGB2GRAY);\n imshow(\"prethresh\", flow);\n threshold(flow, flow, 5, 1, THRESH_BINARY);\n imshow(\"flow mask\", gray.mul(flow));\n times[2] = getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n*\/\n\n\/\/ this mask gets anything kind of dark (DK2) and dilates\n Mat kindofdark(height, width, CV_8UC1, 1);\n equalizeHist(gray, kindofdark);\n threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);\n morphFast(kindofdark, 100, 17, 0);\n\/\/ imshow(\"dark mask\", gray.mul(kindofdark));\n times[3] = getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\/\/ combine mask with its opening\n Mat mask = flow.mul(kindofdark);\n Mat smallMask0, smallMask1;\n resize(mask, smallMask0, Size(width\/5,height\/5));\n Mat smallKernel = ellipticKernel(69,79);\n erode(smallMask0, smallMask1, smallKernel);\n dilate(smallMask1, smallMask1, smallKernel);\n bitwise_and(smallMask0, smallMask1, smallMask1);\n resize(smallMask1, mask, Size(width, height));\n\/\/ imshow(\"morph mask\", gray.mul(mask));\n times[4] = getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\/\/ run haar classifier on nonflow parts of image\n vector mouths;\n int scale = 3;\n Mat classifyThis;\n equalizeHist(gray, gray);\n resize(gray.mul(mask), classifyThis, Size(width\/scale,height\/scale));\n mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE);\n Mat rectImage(height, width, CV_8UC1, Scalar(0));\n for (size_t i=0; ihacking#include \"webcam.hpp\"\n#include \n\nusing namespace cv;\nusing namespace std;\n\nMat ellipticKernel(int width, int height = -1) {\n if (height==-1) {\n return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width\/2, width\/2));\n } else {\n return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width\/2, height\/2));\n }\n}\n\nunsigned long long getMilliseconds() {\n return chrono::system_clock::now().time_since_epoch()\/chrono::milliseconds(1);\n}\n\nvoid morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {\n int width, height;\n width = inout.size().width;\n height = inout.size().height;\n Mat downsample;\n resize(inout, downsample, Size(smallsize,smallsize));\n Mat kernel = ellipticKernel(factor);\n if (diler) {\n erode(downsample, downsample, kernel);\n } else {\n dilate(downsample, downsample, kernel);\n }\n if (eq) {\n equalizeHist(downsample, downsample);\n }\n resize(downsample, inout, Size(width, height));\n}\n\nint main (int argc, char** argv) {\n\n int tracker1, tracker2, tracker3;\n namedWindow(\"s\",1);\n createTrackbar(\"1\",\"s\",&tracker1,100);\n createTrackbar(\"2\",\"s\",&tracker2,100);\n createTrackbar(\"3\",\"s\",&tracker3,100);\n\n CvCapture* capture = 0;\n int width, height, fps;\n\n capture = cvCaptureFromCAM(0);\n\n if (!capture) {\n printf(\"No camera detected!\");\n return -1;\n }\n\n unsigned long long times[100];\n int f = 0;\n for (int i=0; i<100; i++)\n times[i] = 0;\n\n ifstream configFile (\".config\");\n\n if (configFile.is_open()) {\n\n \/\/probably want to support corrupted .config\n string line;\n getline(configFile, line);\n istringstream(line)>>width;\n getline(configFile, line);\n istringstream(line)>>height;\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);\n\n configFile.close();\n\n } else {\n\n initResolutions();\n\n for (int i=36; i<150; i++) {\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);\n }\n\n width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);\n height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);\n\n ofstream configFileOut(\".config\");\n configFileOut << width;\n configFileOut << \"\\n\";\n configFileOut << height;\n configFileOut << \"\\n\";\n configFileOut.close();\n }\n\n bool keepGoing = true;\n\n\/\/ srand(890);\/\/not interested in good randomness\n\n for (int i = 0; i < 30; i++) {\n \/\/ capture some frames so exposure correction takes place\n cvQueryFrame(capture);\n }\n\n Mat background = cvQueryFrame(capture);\n background = background.clone();\n blur(background, background, Size(50,50));\n\n Mat image;\n Mat channel[3];\n unsigned long long timenow = getMilliseconds();\n\n CascadeClassifier mouth_cascade;\n mouth_cascade.load(\"Mouth.xml\");\n\n while (keepGoing) {\n image = cvQueryFrame(capture);\n times[0] = getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\/\/ preprocess by rotating according to OVR roll\n\/\/ imshow(\"webcam\", image);\n\n\/\/ let's make multiple masks where 0=not mouth, 1=uncertain\n\n\/\/ then multiply them together and multiply that with image\n\/\/ and run haar classifier on image\n\n Mat gray, blurred_img;\n cvtColor(image, gray, CV_RGB2GRAY);\n blur(image, blurred_img, Size(50,50));\n times[1] = getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\/\/ this mask filters out areas which have not changed much\n\/\/ this is horrible with new background; redo it\n Mat flow(height, width, CV_8UC1, 1);\n\n absdiff(blurred_img, background, flow);\n cvtColor(flow, flow, CV_RGB2GRAY);\n imshow(\"prethresh\", flow);\n threshold(flow, flow, tracker1, 1, THRESH_BINARY);\n imshow(\"flow mask\", gray.mul(flow));\n times[2] = getMilliseconds() - timenow;\n timenow = getMilliseconds();\n flow = Mat(height, width, CV_8UC1, 1);\n\n\n\/\/ this mask gets anything kind of dark (DK2) and dilates\n Mat kindofdark(height, width, CV_8UC1, 1);\n equalizeHist(gray, kindofdark);\n threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);\n morphFast(kindofdark, 100, 17, 0);\n\/\/ imshow(\"dark mask\", gray.mul(kindofdark));\n times[3] = getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\/\/ combine mask with its opening\n Mat mask = flow.mul(kindofdark);\n Mat smallMask0, smallMask1;\n resize(mask, smallMask0, Size(width\/5,height\/5));\n Mat smallKernel = ellipticKernel(69,79);\n erode(smallMask0, smallMask1, smallKernel);\n dilate(smallMask1, smallMask1, smallKernel);\n bitwise_and(smallMask0, smallMask1, smallMask1);\n resize(smallMask1, mask, Size(width, height));\n\/\/ imshow(\"morph mask\", gray.mul(mask));\n times[4] = getMilliseconds() - timenow;\n timenow = getMilliseconds();\n\n\/\/ run haar classifier on nonflow parts of image\n vector mouths;\n int scale = 3;\n Mat classifyThis;\n equalizeHist(gray, gray);\n resize(gray.mul(mask), classifyThis, Size(width\/scale,height\/scale));\n mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE);\n Mat rectImage(height, width, CV_8UC1, Scalar(0));\n for (size_t i=0; i"} {"text":"#include \"webcam.hpp\"\n\nusing namespace cv;\nusing namespace std;\n\nint main (int argc, char** argv) {\n\n CvCapture* capture = 0;\n int width, height, fps;\n\n capture = cvCaptureFromCAM(0);\n\n if (!capture) {\n printf(\"No camera detected!\");\n return -1;\n }\n\n ifstream configFile (\".config\");\n\n if (configFile.is_open()) {\n\n \/\/probably want to support corrupted .config\n string line;\n getline(configFile, line);\n istringstream(line)>>width;\n getline(configFile, line);\n istringstream(line)>>height;\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);\n\n configFile.close();\n\n } else {\n\n initResolutions();\n\n for (int i=36; i<150; i++) {\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);\n }\n\n width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);\n height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);\n\n ofstream configFileOut(\".config\");\n configFileOut << width;\n configFileOut << \"\\n\";\n configFileOut << height;\n configFileOut << \"\\n\";\n configFileOut.close();\n }\n\n bool keepGoing = true;\n\n\/\/ srand(890);\/\/not interested in good randomness\n\n Mat image;\n Mat channel[3];\n\n while (keepGoing) {\n\n image = cvQueryFrame(capture);\n \/\/imshow(\"webcam\", image);\n\n\/\/ thresholds on dark regions\n\n Mat gray, blurred_gray, threshold_gray;\n cvtColor(image, gray, CV_BGR2GRAY);\n blur(gray, blurred_gray, Size(width\/10,height\/20));\n equalizeHist(blurred_gray, blurred_gray);\n bitwise_not(blurred_gray, blurred_gray);\n threshold(blurred_gray, threshold_gray, 210, 1, THRESH_BINARY);\n imshow(\"threshold\", threshold_gray);\n imshow(\"lol\", blurred_gray);\n\n Mat mask = threshold_gray.mul(blurred_gray\/2.0);\n imshow(\"mask\", mask);\n\n Moments lol = moments(mask, 1);\n circle(image, Point(lol.m10\/lol.m00,lol.m01\/lol.m00),20,Scalar(128),30);\n imshow(\"leimage\", image);\n keepGoing = (waitKey(25)<0);\n\n }\n\n cvReleaseCapture(&capture);\n\n return 0;\n}\nhacking#include \"webcam.hpp\"\n\nusing namespace cv;\nusing namespace std;\n\nint main (int argc, char** argv) {\n\n CvCapture* capture = 0;\n int width, height, fps;\n\n capture = cvCaptureFromCAM(0);\n\n if (!capture) {\n printf(\"No camera detected!\");\n return -1;\n }\n\n ifstream configFile (\".config\");\n\n if (configFile.is_open()) {\n\n \/\/probably want to support corrupted .config\n string line;\n getline(configFile, line);\n istringstream(line)>>width;\n getline(configFile, line);\n istringstream(line)>>height;\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);\n\n configFile.close();\n\n } else {\n\n initResolutions();\n\n for (int i=36; i<150; i++) {\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);\n cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);\n }\n\n width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);\n height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);\n\n ofstream configFileOut(\".config\");\n configFileOut << width;\n configFileOut << \"\\n\";\n configFileOut << height;\n configFileOut << \"\\n\";\n configFileOut.close();\n }\n\n bool keepGoing = true;\n\n\/\/ srand(890);\/\/not interested in good randomness\n\n Mat image;\n Mat channel[3];\n\n while (keepGoing) {\n\n image = cvQueryFrame(capture);\n \/\/imshow(\"webcam\", image);\n\n\/\/ thresholds on dark regions\n\n Mat gray, blurred_gray, threshold_gray;\n cvtColor(image, gray, CV_BGR2GRAY);\n blur(gray, blurred_gray, Size(width\/10,height\/20));\n equalizeHist(blurred_gray, blurred_gray);\n bitwise_not(blurred_gray, blurred_gray);\n threshold(blurred_gray, threshold_gray, 210, 1, THRESH_BINARY);\n imshow(\"threshold\", threshold_gray);\n\n Mat mask = threshold_gray.mul(gray);\n imshow(\"mask\", mask);\n\n Moments lol = moments(mask, 1);\n circle(image, Point(lol.m10\/lol.m00,lol.m01\/lol.m00),20,Scalar(128),30);\n imshow(\"leimage\", image);\n keepGoing = (waitKey(25)<0);\n\n }\n\n cvReleaseCapture(&capture);\n\n return 0;\n}\n<|endoftext|>"} {"text":"#ifndef __CONCURRENCY_FIFO_CHECKER_HPP__\n#define __CONCURRENCY_FIFO_CHECKER_HPP__\n\n#include \n\n#include \n\n#include \"arch\/arch.hpp\"\n#include \"utils2.hpp\"\n\n\/\/ The memcached order_source_t and the backfill_receiver_t will want\n\/\/ to be in distinct buckets.\n\n\/\/ The master and slave never happen in the same process. Then the\n\/\/ memcache buckets have to be different.\nconst int SLAVE_ORDER_SOURCE_BUCKET = 0;\nconst int MASTER_ORDER_SOURCE_BUCKET = 0;\nconst int MEMCACHE_START_BUCKET = 1;\n\nclass order_token_t {\npublic:\n static const order_token_t ignore;\n\n \/\/ By default we construct a totally invalid order token, not\n \/\/ equal to ignore, that must be initialized.\n order_token_t() : bucket_(-2), value_(-2) { }\n\n order_token_t with_read_mode() {\n return order_token_t(bucket_, value_, read_mode_);\n }\n\nprivate:\n explicit order_token_t(int bucket, int64_t x, bool read_mode)\n : bucket_(bucket), read_mode_(read_mode), value_(x) { }\n int bucket_;\n bool read_mode_;\n int64_t value_;\n\n friend class order_source_t;\n friend class order_sink_t;\n friend class plain_sink_t;\n friend class contiguous_order_sink_t;\n};\n\nclass order_source_pigeoncoop_t {\npublic:\n order_source_pigeoncoop_t(int starting_bucket = 0)\n : least_unregistered_bucket_(starting_bucket) { }\n\n friend class order_source_t;\nprivate:\n static void nop() { }\n\n void unregister_bucket(int bucket) {\n ASSERT_NO_CORO_WAITING;\n rassert(bucket < least_unregistered_bucket_);\n free_buckets_.push_back(bucket);\n }\n\n int register_for_bucket() {\n ASSERT_NO_CORO_WAITING;\n if (free_buckets_.empty()) {\n int ret = least_unregistered_bucket_;\n ++ least_unregistered_bucket_;\n return ret;\n } else {\n int ret = free_buckets_.back();\n rassert(ret < least_unregistered_bucket_);\n free_buckets_.pop_back();\n return ret;\n }\n }\n\n \/\/ The bucket we should use next, if free_buckets_ is empty.\n int least_unregistered_bucket_;\n\n \/\/ The buckets less than least_unregistered_bucket_.\n std::vector free_buckets_;\n\n DISABLE_COPYING(order_source_pigeoncoop_t);\n};\n\nclass order_source_t {\npublic:\n order_source_t(int bucket = 0, boost::function unregisterator = order_source_pigeoncoop_t::nop)\n : bucket_(bucket), counter_(0), unregister_(unregisterator) { }\n\n order_source_t(order_source_pigeoncoop_t *coop)\n : bucket_(coop->register_for_bucket()), counter_(0),\n unregister_(boost::bind(&order_source_pigeoncoop_t::unregister_bucket, coop, bucket_)) { }\n\n ~order_source_t() { unregister_(); }\n\n order_token_t check_in() { return order_token_t(bucket_, ++counter_, false); }\n\n order_token_t check_in_read_mode() { return order_token_t(bucket_, ++counter_, true); }\n\nprivate:\n int bucket_;\n int64_t counter_;\n boost::function unregister_;\n\n DISABLE_COPYING(order_source_t);\n};\n\nclass order_sink_t {\npublic:\n order_sink_t() { }\n\n void check_out(order_token_t token) {\n if (token.bucket_ != order_token_t::ignore.bucket_) {\n rassert(token.bucket_ >= 0);\n if (token.bucket_ >= int(last_seens_.size())) {\n last_seens_.resize(token.bucket_ + 1, std::pair(0, 0));\n }\n\n verify_token_value_and_update(token, &last_seens_[token.bucket_]);\n }\n }\n\nprivate:\n\n friend class plain_sink_t;\n static void verify_token_value_and_update(order_token_t token, std::pair *ls_pair) {\n \/\/ We tolerate equality in this comparison because it can\n \/\/ be used to ensure that multiple actions don't get\n \/\/ interrupted. And resending the same action isn't\n \/\/ normally a problem.\n if (token.read_mode_) {\n rassert(token.value_ >= ls_pair->first, \"token.value_ = %ld, last_seens_[token.bucket_].first = %ld, token.bucket_ = %d\", token.value_, ls_pair->first, token.bucket_);\n ls_pair->second = std::max(ls_pair->second, token.value_);\n } else {\n rassert(token.value_ >= ls_pair->second, \"token.value_ = %ld, last_seens_[token.bucket_].second = %ld, token.bucket_ = %d\", token.value_, ls_pair->second, token.bucket_);\n ls_pair->first = ls_pair->second = token.value_;\n }\n }\n\n \/\/ .first = last seen write, .second = max(last seen read, last seen write)\n std::vector > last_seens_;\n\n DISABLE_COPYING(order_sink_t);\n};\n\n\/\/ An order sink with less overhead, for situations where there is\n\/\/ only one source (like the top of a btree slice) and many sinks.\nclass plain_sink_t {\npublic:\n plain_sink_t() : ls_pair_(0, 0) { }\n\n void check_out(order_token_t token) {\n if (token.bucket_ != order_token_t::ignore.bucket_) {\n \/\/ TODO: do read\/write mode.\n rassert(token.bucket_ >= 0);\n rassert(token.bucket_ == 0, \"Only bucket 0 allowed, you made a programmer error\");\n\n order_sink_t::verify_token_value_and_update(token, &ls_pair_);\n }\n }\n\nprivate:\n std::pair ls_pair_;\n\n DISABLE_COPYING(plain_sink_t);\n};\n\n#endif \/\/ __CONCURRENCY_FIFO_CHECKER_HPP__\nDisable order_sink token checking temporarily (see #328)#ifndef __CONCURRENCY_FIFO_CHECKER_HPP__\n#define __CONCURRENCY_FIFO_CHECKER_HPP__\n\n#include \n\n#include \n\n#include \"arch\/arch.hpp\"\n#include \"utils2.hpp\"\n\n\/\/ The memcached order_source_t and the backfill_receiver_t will want\n\/\/ to be in distinct buckets.\n\n\/\/ The master and slave never happen in the same process. Then the\n\/\/ memcache buckets have to be different.\nconst int SLAVE_ORDER_SOURCE_BUCKET = 0;\nconst int MASTER_ORDER_SOURCE_BUCKET = 0;\nconst int MEMCACHE_START_BUCKET = 1;\n\nclass order_token_t {\npublic:\n static const order_token_t ignore;\n\n \/\/ By default we construct a totally invalid order token, not\n \/\/ equal to ignore, that must be initialized.\n order_token_t() : bucket_(-2), value_(-2) { }\n\n order_token_t with_read_mode() {\n return order_token_t(bucket_, value_, read_mode_);\n }\n\nprivate:\n explicit order_token_t(int bucket, int64_t x, bool read_mode)\n : bucket_(bucket), read_mode_(read_mode), value_(x) { }\n int bucket_;\n bool read_mode_;\n int64_t value_;\n\n friend class order_source_t;\n friend class order_sink_t;\n friend class plain_sink_t;\n friend class contiguous_order_sink_t;\n};\n\nclass order_source_pigeoncoop_t {\npublic:\n order_source_pigeoncoop_t(int starting_bucket = 0)\n : least_unregistered_bucket_(starting_bucket) { }\n\n friend class order_source_t;\nprivate:\n static void nop() { }\n\n void unregister_bucket(int bucket) {\n ASSERT_NO_CORO_WAITING;\n rassert(bucket < least_unregistered_bucket_);\n free_buckets_.push_back(bucket);\n }\n\n int register_for_bucket() {\n ASSERT_NO_CORO_WAITING;\n if (free_buckets_.empty()) {\n int ret = least_unregistered_bucket_;\n ++ least_unregistered_bucket_;\n return ret;\n } else {\n int ret = free_buckets_.back();\n rassert(ret < least_unregistered_bucket_);\n free_buckets_.pop_back();\n return ret;\n }\n }\n\n \/\/ The bucket we should use next, if free_buckets_ is empty.\n int least_unregistered_bucket_;\n\n \/\/ The buckets less than least_unregistered_bucket_.\n std::vector free_buckets_;\n\n DISABLE_COPYING(order_source_pigeoncoop_t);\n};\n\nclass order_source_t {\npublic:\n order_source_t(int bucket = 0, boost::function unregisterator = order_source_pigeoncoop_t::nop)\n : bucket_(bucket), counter_(0), unregister_(unregisterator) { }\n\n order_source_t(order_source_pigeoncoop_t *coop)\n : bucket_(coop->register_for_bucket()), counter_(0),\n unregister_(boost::bind(&order_source_pigeoncoop_t::unregister_bucket, coop, bucket_)) { }\n\n ~order_source_t() { unregister_(); }\n\n order_token_t check_in() { return order_token_t(bucket_, ++counter_, false); }\n\n order_token_t check_in_read_mode() { return order_token_t(bucket_, ++counter_, true); }\n\nprivate:\n int bucket_;\n int64_t counter_;\n boost::function unregister_;\n\n DISABLE_COPYING(order_source_t);\n};\n\nclass order_sink_t {\npublic:\n order_sink_t() { }\n\n void check_out(order_token_t token) {\n if (token.bucket_ != order_token_t::ignore.bucket_) {\n rassert(token.bucket_ >= 0);\n if (token.bucket_ >= int(last_seens_.size())) {\n last_seens_.resize(token.bucket_ + 1, std::pair(0, 0));\n }\n\n \/\/ TODO: Reenable! See issue #328\n \/\/verify_token_value_and_update(token, &last_seens_[token.bucket_]);\n }\n }\n\nprivate:\n\n friend class plain_sink_t;\n static void verify_token_value_and_update(order_token_t token, std::pair *ls_pair) {\n \/\/ We tolerate equality in this comparison because it can\n \/\/ be used to ensure that multiple actions don't get\n \/\/ interrupted. And resending the same action isn't\n \/\/ normally a problem.\n if (token.read_mode_) {\n rassert(token.value_ >= ls_pair->first, \"token.value_ = %ld, last_seens_[token.bucket_].first = %ld, token.bucket_ = %d\", token.value_, ls_pair->first, token.bucket_);\n ls_pair->second = std::max(ls_pair->second, token.value_);\n } else {\n rassert(token.value_ >= ls_pair->second, \"token.value_ = %ld, last_seens_[token.bucket_].second = %ld, token.bucket_ = %d\", token.value_, ls_pair->second, token.bucket_);\n ls_pair->first = ls_pair->second = token.value_;\n }\n }\n\n \/\/ .first = last seen write, .second = max(last seen read, last seen write)\n std::vector > last_seens_;\n\n DISABLE_COPYING(order_sink_t);\n};\n\n\/\/ An order sink with less overhead, for situations where there is\n\/\/ only one source (like the top of a btree slice) and many sinks.\nclass plain_sink_t {\npublic:\n plain_sink_t() : ls_pair_(0, 0) { }\n\n void check_out(order_token_t token) {\n if (token.bucket_ != order_token_t::ignore.bucket_) {\n \/\/ TODO: do read\/write mode.\n rassert(token.bucket_ >= 0);\n rassert(token.bucket_ == 0, \"Only bucket 0 allowed, you made a programmer error\");\n\n order_sink_t::verify_token_value_and_update(token, &ls_pair_);\n }\n }\n\nprivate:\n std::pair ls_pair_;\n\n DISABLE_COPYING(plain_sink_t);\n};\n\n#endif \/\/ __CONCURRENCY_FIFO_CHECKER_HPP__\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"acmacs-base\/debug.hh\"\n#include \"acmacs-base\/float.hh\"\n#include \"acmacs-base\/filesystem.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nnamespace rjson\n{\n namespace implementation { class NumberHandler; }\n\n class value;\n\n template struct content_type;\n template using rjson_type = typename content_type>::type;\n\n class string\n {\n public:\n inline string(std::string aData) : mData{aData} {}\n inline string(const char* aData) : mData{aData} {}\n inline std::string to_json() const { return std::string{\"\\\"\"} + static_cast(mData) + \"\\\"\"; }\n inline operator std::string() const { return mData; }\n inline string& operator=(std::string aSrc) { mData = aSrc; return *this; }\n inline bool operator==(const std::string aToCompare) const { return mData == aToCompare; }\n inline bool operator==(const string& aToCompare) const { return mData == aToCompare.mData; }\n inline size_t size() const { return mData.size(); }\n inline bool empty() const { return mData.empty(); }\n inline bool operator<(const string& to_compare) const { return mData < to_compare.mData; }\n\n private:\n std::string mData;\n };\n\n class boolean\n {\n public:\n inline boolean(bool aValue) : mValue{aValue} {}\n inline std::string to_json() const { return mValue ? \"true\" : \"false\"; }\n inline operator bool() const { return mValue; }\n inline boolean& operator=(bool aSrc) { mValue = aSrc; return *this; }\n\n private:\n bool mValue;\n };\n\n class null\n {\n public:\n inline null() {}\n inline std::string to_json() const { return \"null\"; }\n };\n\n class number\n {\n public:\n inline number(double aSrc) : mValue{double_to_string(aSrc)} {}\n inline number& operator=(double aSrc) { mValue = double_to_string(aSrc); return *this; }\n inline std::string to_json() const { return mValue; } \/\/ { return double_to_string(mValue); }\n inline operator double() const { return std::stod(mValue); } \/\/ { return mValue; }\n\n private:\n inline number(std::string_view&& aData) : mValue{aData} {} \/\/ mValue{std::stod(static_cast(aData))} {}\n\n \/\/ double mValue;\n std::string mValue;\n\n friend class implementation::NumberHandler;\n };\n\n class integer\n {\n public:\n inline integer(long aSrc) : mValue{std::to_string(aSrc)} {}\n inline integer& operator=(long aSrc) { mValue = std::to_string(aSrc); return *this; }\n inline std::string to_json() const { return mValue; } \/\/ { return std::to_string(mValue); }\n inline operator double() const { return std::stod(mValue); } \/\/ { return mValue; }\n inline operator long() const { return std::stol(mValue); } \/\/ { return mValue; }\n\n private:\n inline integer(std::string_view&& aData) : mValue{aData} {} \/\/ mValue{std::stol(static_cast(aData))} {}\n\n \/\/ long mValue;\n std::string mValue;\n\n friend class implementation::NumberHandler;\n };\n\n class object\n {\n public:\n inline object() = default;\n inline object(std::initializer_list key_values);\n\n std::string to_json() const;\n\n void insert(const string& aKey, value&& aValue);\n void insert(const string& aKey, const value& aValue);\n void insert(value&& aKey, value&& aValue);\n inline size_t size() const { return mContent.size(); }\n inline bool empty() const { return mContent.empty(); }\n\n \/\/ returns reference to the value at the passed key.\n \/\/ if key not found, inserts aDefault with the passed key and returns reference to the inserted\n value& get_ref(std::string aKey, value&& aDefault);\n const value& get_ref(std::string aKey, value&& aDefault) const;\n object& get_ref_to_object(std::string aKey);\n\n template inline std::decay_t get_field(std::string aFieldName, F&& aDefaultValue) const\n {\n return std::get>(get_ref(aFieldName, rjson_type{std::forward(aDefaultValue)}));\n }\n\n void set_field(std::string aKey, value&& aValue);\n\n private:\n std::map mContent;\n \/\/ std::vector> mContent;\n };\n\n class array\n {\n public:\n inline array() = default;\n inline array(array&&) = default;\n inline array(const array&) = default;\n inline array(std::initializer_list args);\n inline array& operator=(array&&) = default;\n inline array& operator=(const array&) = default;\n\n std::string to_json() const;\n\n void insert(value&& aValue);\n void insert(const value& aValue);\n inline size_t size() const { return mContent.size(); }\n inline bool empty() const { return mContent.empty(); }\n inline value& operator[](size_t index) { return mContent[index]; }\n inline const value& operator[](size_t index) const { return mContent[index]; }\n\n private:\n std::vector mContent;\n };\n\n \/\/ ----------------------------------------------------------------------\n\n template <> struct content_type { using type = rjson::number; };\n template <> struct content_type { using type = rjson::integer; };\n template <> struct content_type { using type = rjson::integer; };\n template <> struct content_type { using type = rjson::boolean; };\n template <> struct content_type { using type = rjson::string; };\n\n template value to_value(const FValue& aValue);\n\n \/\/ ----------------------------------------------------------------------\n\n using value_base = std::variant; \/\/ null must be the first alternative, it is the default value;\n\n class value : public value_base\n {\n public:\n using value_base::operator=;\n using value_base::value_base;\n inline value(const value&) = default; \/\/ gcc7 wants this, otherwise it is deleted\n inline value& operator=(const value&) = default; \/\/ gcc7 wants this, otherwise it is deleted\n \/\/ inline ~value() { std::cerr << \"DEBUG: ~value \" << to_json() << DEBUG_LINE_FUNC << '\\n'; }\n\n \/\/ returns reference to the value at the passed key.\n \/\/ if key not found, inserts aDefault with the passed key and returns reference to the inserted\n \/\/ if this is not an object, throws std::bad_variant_access\n inline value& get_ref(std::string aKey, value&& aDefault)\n {\n try {\n return std::get(*this).get_ref(aKey, std::forward(aDefault));\n }\n catch (std::bad_variant_access&) {\n std::cerr << \"ERROR: rjson::value::get_ref: not an object: valueless_by_exception:\" << valueless_by_exception() << \" index:\" << index() << '\\n'; \/\/ to_json() << '\\n';\n throw;\n }\n }\n\n inline object& get_ref_to_object(std::string aKey)\n {\n try {\n return std::get(*this).get_ref_to_object(aKey);\n }\n catch (std::bad_variant_access&) {\n std::cerr << \"ERROR: rjson::value::get_ref_to_object: not an object: \" << to_json() << '\\n'; \/\/ valueless_by_exception:\" << valueless_by_exception() << \" index:\" << index() << '\\n'; \/\/ to_json() << '\\n';\n throw;\n }\n }\n\n template inline std::decay_t get_field(std::string aFieldName, F&& aDefaultValue) const\n {\n try {\n return std::get(*this).get_field(aFieldName, std::forward(aDefaultValue));\n }\n catch (std::bad_variant_access&) {\n std::cerr << \"ERROR: rjson::value::get_field: not an object: \" << to_json() << '\\n'; \/\/ to_json() << '\\n';\n throw;\n }\n \/\/ return std::get>(get_ref(aFieldName, rjson_type{std::forward(aDefaultValue)}));\n }\n\n template inline void set_field(std::string aFieldName, F&& aValue)\n {\n set_field(aFieldName, to_value(aValue));\n \/\/ try {\n \/\/ std::get(*this).set_field(aFieldName, to_value(aValue));\n \/\/ }\n \/\/ catch (std::bad_variant_access&) {\n \/\/ std::cerr << \"ERROR: rjson::value::set_field: not an object: \" << to_json() << '\\n';\n \/\/ throw;\n \/\/ }\n }\n\n std::string to_json() const;\n\n }; \/\/ class value\n\n \/\/ ----------------------------------------------------------------------\n\n template inline value to_value(const FValue& aValue)\n {\n return rjson_type{aValue};\n }\n\n \/\/ ----------------------------------------------------------------------\n\n class Error : public std::exception\n {\n public:\n \/\/ inline Error(size_t aLine, size_t aColumn, std::string aMessage)\n \/\/ : mMessage{std::to_string(aLine) + \":\" + std::to_string(aColumn) + \": \" + aMessage} \/\/, mLine{aLine}, mColumn{aColumn}\n \/\/ {}\n\n inline Error(size_t aLine, size_t aColumn, std::string&& aMessage)\n : mMessage{std::to_string(aLine) + \":\" + std::to_string(aColumn) + \": \" + std::move(aMessage)} \/\/, mLine{aLine}, mColumn{aColumn}\n {}\n\n inline const char* what() const noexcept override { return mMessage.c_str(); }\n\n private:\n std::string mMessage;\n \/\/size_t mLine, mColumn;\n\n }; \/\/ class Error\n\n value parse_string(std::string aJsonData);\n value parse_file(std::string aFilename);\n\n} \/\/ namespace rjson\n\n\/\/ ----------------------------------------------------------------------\n\/\/ gcc-7 support\n\/\/ ----------------------------------------------------------------------\n\n#if __GNUC__ == 7\nnamespace std\n{\n \/\/ gcc 7.2 wants those, if we derive from std::variant\n template<> struct variant_size : variant_size {};\n template struct variant_alternative<_Np, rjson::value> : variant_alternative<_Np, rjson::value_base> {};\n}\n#endif\n\n\/\/ ----------------------------------------------------------------------\n\/\/ inline\n\/\/ ----------------------------------------------------------------------\n\nnamespace rjson\n{\n inline void object::insert(const string& aKey, value&& aValue) { mContent.emplace(aKey, std::move(aValue)); }\n inline void object::insert(const string& aKey, const value& aValue) { mContent.emplace(aKey, aValue); }\n inline void object::insert(value&& aKey, value&& aValue) { insert(std::get(std::forward(aKey)), std::forward(aValue)); }\n\n inline object::object(std::initializer_list key_values)\n {\n if ((key_values.size() % 2) != 0)\n throw std::runtime_error(\"rjson::object::object(initializer_list): odd number of arguments\");\n try {\n for (auto elt = std::begin(key_values); elt != std::end(key_values); ++elt) {\n const auto& key = std::get(*elt);\n ++elt;\n insert(key, *elt);\n }\n }\n catch (std::bad_variant_access&) {\n std::cerr << \"ERROR: rjson::object::object(initializer_list): invalid object field name type?\\n\";\n throw;\n }\n }\n\n inline value& object::get_ref(std::string aKey, value&& aDefault)\n {\n const auto [iter, inserted] = mContent.emplace(aKey, std::forward(aDefault));\n return iter->second;\n\n \/\/ auto found = std::find_if(std::begin(mContent), std::end(mContent), [&aKey](const auto& entry) { return entry.first == aKey; });\n \/\/ if (found == std::end(mContent)) {\n \/\/ \/\/ std::cerr << \"DEBUG: object::get_ref: not found: \" << aKey << ' ' << to_json() << \" default:\" << aDefault.to_json() << '\\n';\n \/\/ return mContent.emplace_back(aKey, std::forward(aDefault)).second;\n \/\/ }\n \/\/ else {\n \/\/ \/\/ std::cerr << \"DEBUG: object::get_ref: found: \" << aKey << ' ' << found->second.to_json() << '\\n';\n \/\/ return found->second;\n \/\/ }\n }\n\n inline const value& object::get_ref(std::string aKey, value&& aDefault) const { return const_cast(this)->get_ref(aKey, std::forward(aDefault)); }\n\n inline object& object::get_ref_to_object(std::string aKey)\n {\n const auto existing = mContent.find(aKey);\n if (existing == mContent.end())\n return std::get(get_ref(aKey, object{}));\n else\n return std::get(existing->second);\n }\n\n inline void object::set_field(std::string aKey, value&& aValue)\n {\n mContent.insert_or_assign(aKey, std::forward(aValue));\n\n \/\/ auto found = std::find_if(std::begin(mContent), std::end(mContent), [&aKey](const auto& entry) { return entry.first == aKey; });\n \/\/ if (found == std::end(mContent)) {\n \/\/ mContent.emplace_back(std::move(aKey), std::forward(aValue));\n \/\/ }\n \/\/ else {\n \/\/ found->second = std::forward(aValue);\n \/\/ }\n }\n\n \/\/ ----------------------------------------------------------------------\n\n inline void array::insert(value&& aValue) { mContent.push_back(std::move(aValue)); }\n inline void array::insert(const value& aValue) { mContent.push_back(aValue); }\n\n inline array::array(std::initializer_list args)\n {\n for (const auto& arg: args)\n insert(arg);\n }\n\n \/\/ ----------------------------------------------------------------------\n\n template <> inline void value::set_field(std::string aFieldName, value&& aValue)\n {\n try {\n std::get(*this).set_field(aFieldName, std::forward(aValue));\n }\n catch (std::bad_variant_access&) {\n std::cerr << \"ERROR: rjson::value::set_field: not an object: \" << to_json() << '\\n';\n throw;\n }\n }\n\n inline std::string value::to_json() const\n {\n return std::visit([](auto&& arg) -> std::string { return arg.to_json(); }, *this);\n }\n}\n\n\/\/ ----------------------------------------------------------------------\n\ninline std::ostream& operator<<(std::ostream& out, const rjson::value& aValue)\n{\n return out << aValue.to_json();\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\nrjson development#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"acmacs-base\/debug.hh\"\n#include \"acmacs-base\/float.hh\"\n#include \"acmacs-base\/filesystem.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nnamespace rjson\n{\n namespace implementation { class NumberHandler; }\n\n class value;\n\n template struct content_type;\n template using rjson_type = typename content_type>::type;\n\n class string\n {\n public:\n inline string(std::string aData) : mData{aData} {}\n inline string(const char* aData) : mData{aData} {}\n inline std::string to_json() const { return std::string{\"\\\"\"} + static_cast(mData) + \"\\\"\"; }\n inline operator std::string() const { return mData; }\n inline string& operator=(std::string aSrc) { mData = aSrc; return *this; }\n inline bool operator==(const std::string aToCompare) const { return mData == aToCompare; }\n inline bool operator==(const string& aToCompare) const { return mData == aToCompare.mData; }\n inline size_t size() const { return mData.size(); }\n inline bool empty() const { return mData.empty(); }\n inline bool operator<(const string& to_compare) const { return mData < to_compare.mData; }\n\n private:\n std::string mData;\n };\n\n class boolean\n {\n public:\n inline boolean(bool aValue) : mValue{aValue} {}\n inline std::string to_json() const { return mValue ? \"true\" : \"false\"; }\n inline operator bool() const { return mValue; }\n inline boolean& operator=(bool aSrc) { mValue = aSrc; return *this; }\n\n private:\n bool mValue;\n };\n\n class null\n {\n public:\n inline null() {}\n inline std::string to_json() const { return \"null\"; }\n };\n\n class number\n {\n public:\n inline number(double aSrc) : mValue{double_to_string(aSrc)} {}\n inline number& operator=(double aSrc) { mValue = double_to_string(aSrc); return *this; }\n inline std::string to_json() const { return mValue; } \/\/ { return double_to_string(mValue); }\n inline operator double() const { return std::stod(mValue); } \/\/ { return mValue; }\n\n private:\n inline number(std::string_view&& aData) : mValue{aData} {} \/\/ mValue{std::stod(static_cast(aData))} {}\n\n \/\/ double mValue;\n std::string mValue;\n\n friend class implementation::NumberHandler;\n };\n\n class integer\n {\n public:\n inline integer(long aSrc) : mValue{std::to_string(aSrc)} {}\n inline integer& operator=(long aSrc) { mValue = std::to_string(aSrc); return *this; }\n inline std::string to_json() const { return mValue; } \/\/ { return std::to_string(mValue); }\n inline operator double() const { return std::stod(mValue); } \/\/ { return mValue; }\n inline operator long() const { return std::stol(mValue); } \/\/ { return mValue; }\n\n private:\n inline integer(std::string_view&& aData) : mValue{aData} {} \/\/ mValue{std::stol(static_cast(aData))} {}\n\n \/\/ long mValue;\n std::string mValue;\n\n friend class implementation::NumberHandler;\n };\n\n class object\n {\n public:\n class field_not_found : public std::exception { public: using std::exception::exception; };\n\n inline object() = default;\n inline object(std::initializer_list key_values);\n\n std::string to_json() const;\n\n void insert(const string& aKey, value&& aValue);\n void insert(const string& aKey, const value& aValue);\n void insert(value&& aKey, value&& aValue);\n inline size_t size() const { return mContent.size(); }\n inline bool empty() const { return mContent.empty(); }\n\n \/\/ returns reference to the value at the passed key.\n \/\/ if key not found, inserts aDefault with the passed key and returns reference to the inserted\n value& get_ref(std::string aKey, value&& aDefault);\n const value& get_ref(std::string aKey) const; \/\/ throws field_not_found\n const value& get_ref(std::string aKey, value&& aDefault) const;\n object& get_ref_to_object(std::string aKey);\n\n template inline std::decay_t get_field(std::string aFieldName, F&& aDefaultValue) const\n {\n return std::get>(get_ref(aFieldName, rjson_type{std::forward(aDefaultValue)}));\n }\n\n template inline std::decay_t get_field(std::string aFieldName) const \/\/ throws field_not_found\n {\n return std::get>(get_ref(aFieldName));\n }\n\n void set_field(std::string aKey, value&& aValue);\n\n private:\n std::map mContent;\n \/\/ std::vector> mContent;\n };\n\n class array\n {\n public:\n inline array() = default;\n inline array(array&&) = default;\n inline array(const array&) = default;\n inline array(std::initializer_list args);\n inline array& operator=(array&&) = default;\n inline array& operator=(const array&) = default;\n\n std::string to_json() const;\n\n void insert(value&& aValue);\n void insert(const value& aValue);\n inline size_t size() const { return mContent.size(); }\n inline bool empty() const { return mContent.empty(); }\n inline value& operator[](size_t index) { return mContent[index]; }\n inline const value& operator[](size_t index) const { return mContent[index]; }\n\n private:\n std::vector mContent;\n };\n\n \/\/ ----------------------------------------------------------------------\n\n template <> struct content_type { using type = rjson::number; };\n template <> struct content_type { using type = rjson::integer; };\n template <> struct content_type { using type = rjson::integer; };\n template <> struct content_type { using type = rjson::boolean; };\n template <> struct content_type { using type = rjson::string; };\n\n template value to_value(const FValue& aValue);\n\n \/\/ ----------------------------------------------------------------------\n\n using value_base = std::variant; \/\/ null must be the first alternative, it is the default value;\n\n class value : public value_base\n {\n public:\n using value_base::operator=;\n using value_base::value_base;\n inline value(const value&) = default; \/\/ gcc7 wants this, otherwise it is deleted\n inline value& operator=(const value&) = default; \/\/ gcc7 wants this, otherwise it is deleted\n \/\/ inline ~value() { std::cerr << \"DEBUG: ~value \" << to_json() << DEBUG_LINE_FUNC << '\\n'; }\n\n \/\/ returns reference to the value at the passed key.\n \/\/ if key not found, inserts aDefault with the passed key and returns reference to the inserted\n \/\/ if this is not an object, throws std::bad_variant_access\n inline value& get_ref(std::string aKey, value&& aDefault)\n {\n try {\n return std::get(*this).get_ref(aKey, std::forward(aDefault));\n }\n catch (std::bad_variant_access&) {\n std::cerr << \"ERROR: rjson::value::get_ref: not an object: valueless_by_exception:\" << valueless_by_exception() << \" index:\" << index() << '\\n'; \/\/ to_json() << '\\n';\n throw;\n }\n }\n\n inline object& get_ref_to_object(std::string aKey)\n {\n try {\n return std::get(*this).get_ref_to_object(aKey);\n }\n catch (std::bad_variant_access&) {\n std::cerr << \"ERROR: rjson::value::get_ref_to_object: not an object: \" << to_json() << '\\n'; \/\/ valueless_by_exception:\" << valueless_by_exception() << \" index:\" << index() << '\\n'; \/\/ to_json() << '\\n';\n throw;\n }\n }\n\n template inline std::decay_t get_field(std::string aFieldName, F&& aDefaultValue) const\n {\n try {\n return std::get(*this).get_field(aFieldName, std::forward(aDefaultValue));\n }\n catch (std::bad_variant_access&) {\n std::cerr << \"ERROR: rjson::value::get_field: not an object: \" << to_json() << '\\n'; \/\/ to_json() << '\\n';\n throw;\n }\n \/\/ return std::get>(get_ref(aFieldName, rjson_type{std::forward(aDefaultValue)}));\n }\n\n template inline void set_field(std::string aFieldName, F&& aValue)\n {\n set_field(aFieldName, to_value(aValue));\n \/\/ try {\n \/\/ std::get(*this).set_field(aFieldName, to_value(aValue));\n \/\/ }\n \/\/ catch (std::bad_variant_access&) {\n \/\/ std::cerr << \"ERROR: rjson::value::set_field: not an object: \" << to_json() << '\\n';\n \/\/ throw;\n \/\/ }\n }\n\n std::string to_json() const;\n\n }; \/\/ class value\n\n \/\/ ----------------------------------------------------------------------\n\n template inline value to_value(const FValue& aValue)\n {\n return rjson_type{aValue};\n }\n\n \/\/ ----------------------------------------------------------------------\n\n class Error : public std::exception\n {\n public:\n \/\/ inline Error(size_t aLine, size_t aColumn, std::string aMessage)\n \/\/ : mMessage{std::to_string(aLine) + \":\" + std::to_string(aColumn) + \": \" + aMessage} \/\/, mLine{aLine}, mColumn{aColumn}\n \/\/ {}\n\n inline Error(size_t aLine, size_t aColumn, std::string&& aMessage)\n : mMessage{std::to_string(aLine) + \":\" + std::to_string(aColumn) + \": \" + std::move(aMessage)} \/\/, mLine{aLine}, mColumn{aColumn}\n {}\n\n inline const char* what() const noexcept override { return mMessage.c_str(); }\n\n private:\n std::string mMessage;\n \/\/size_t mLine, mColumn;\n\n }; \/\/ class Error\n\n value parse_string(std::string aJsonData);\n value parse_file(std::string aFilename);\n\n} \/\/ namespace rjson\n\n\/\/ ----------------------------------------------------------------------\n\/\/ gcc-7 support\n\/\/ ----------------------------------------------------------------------\n\n#if __GNUC__ == 7\nnamespace std\n{\n \/\/ gcc 7.2 wants those, if we derive from std::variant\n template<> struct variant_size : variant_size {};\n template struct variant_alternative<_Np, rjson::value> : variant_alternative<_Np, rjson::value_base> {};\n}\n#endif\n\n\/\/ ----------------------------------------------------------------------\n\/\/ inline\n\/\/ ----------------------------------------------------------------------\n\nnamespace rjson\n{\n inline void object::insert(const string& aKey, value&& aValue) { mContent.emplace(aKey, std::move(aValue)); }\n inline void object::insert(const string& aKey, const value& aValue) { mContent.emplace(aKey, aValue); }\n inline void object::insert(value&& aKey, value&& aValue) { insert(std::get(std::forward(aKey)), std::forward(aValue)); }\n\n inline object::object(std::initializer_list key_values)\n {\n if ((key_values.size() % 2) != 0)\n throw std::runtime_error(\"rjson::object::object(initializer_list): odd number of arguments\");\n try {\n for (auto elt = std::begin(key_values); elt != std::end(key_values); ++elt) {\n const auto& key = std::get(*elt);\n ++elt;\n insert(key, *elt);\n }\n }\n catch (std::bad_variant_access&) {\n std::cerr << \"ERROR: rjson::object::object(initializer_list): invalid object field name type?\\n\";\n throw;\n }\n }\n\n inline value& object::get_ref(std::string aKey, value&& aDefault)\n {\n const auto [iter, inserted] = mContent.emplace(aKey, std::forward(aDefault));\n return iter->second;\n\n \/\/ auto found = std::find_if(std::begin(mContent), std::end(mContent), [&aKey](const auto& entry) { return entry.first == aKey; });\n \/\/ if (found == std::end(mContent)) {\n \/\/ \/\/ std::cerr << \"DEBUG: object::get_ref: not found: \" << aKey << ' ' << to_json() << \" default:\" << aDefault.to_json() << '\\n';\n \/\/ return mContent.emplace_back(aKey, std::forward(aDefault)).second;\n \/\/ }\n \/\/ else {\n \/\/ \/\/ std::cerr << \"DEBUG: object::get_ref: found: \" << aKey << ' ' << found->second.to_json() << '\\n';\n \/\/ return found->second;\n \/\/ }\n }\n\n inline const value& object::get_ref(std::string aKey, value&& aDefault) const { return const_cast(this)->get_ref(aKey, std::forward(aDefault)); }\n\n inline const value& object::get_ref(std::string aKey) const\n {\n const auto existing = mContent.find(aKey);\n if (existing == mContent.end())\n throw field_not_found{};\n return existing->second;\n }\n\n inline object& object::get_ref_to_object(std::string aKey)\n {\n const auto existing = mContent.find(aKey);\n if (existing == mContent.end())\n return std::get(get_ref(aKey, object{}));\n else\n return std::get(existing->second);\n }\n\n inline void object::set_field(std::string aKey, value&& aValue)\n {\n mContent.insert_or_assign(aKey, std::forward(aValue));\n\n \/\/ auto found = std::find_if(std::begin(mContent), std::end(mContent), [&aKey](const auto& entry) { return entry.first == aKey; });\n \/\/ if (found == std::end(mContent)) {\n \/\/ mContent.emplace_back(std::move(aKey), std::forward(aValue));\n \/\/ }\n \/\/ else {\n \/\/ found->second = std::forward(aValue);\n \/\/ }\n }\n\n \/\/ ----------------------------------------------------------------------\n\n inline void array::insert(value&& aValue) { mContent.push_back(std::move(aValue)); }\n inline void array::insert(const value& aValue) { mContent.push_back(aValue); }\n\n inline array::array(std::initializer_list args)\n {\n for (const auto& arg: args)\n insert(arg);\n }\n\n \/\/ ----------------------------------------------------------------------\n\n template <> inline void value::set_field(std::string aFieldName, value&& aValue)\n {\n try {\n std::get(*this).set_field(aFieldName, std::forward(aValue));\n }\n catch (std::bad_variant_access&) {\n std::cerr << \"ERROR: rjson::value::set_field: not an object: \" << to_json() << '\\n';\n throw;\n }\n }\n\n inline std::string value::to_json() const\n {\n return std::visit([](auto&& arg) -> std::string { return arg.to_json(); }, *this);\n }\n}\n\n\/\/ ----------------------------------------------------------------------\n\ninline std::ostream& operator<<(std::ostream& out, const rjson::value& aValue)\n{\n return out << aValue.to_json();\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"#include \"condor_common.h\"\n#include \"condor_sinful.h\"\n\n#include \n\nbool verbose = false;\n#define REQUIRE( condition ) \\\n\tif(! ( condition )) { \\\n\t\tfprintf( stderr, \"Failed requirement '%s' on line %d.\\n\", #condition, __LINE__ ); \\\n\t\treturn 1; \\\n\t} else if( verbose ) { \\\n\t\tfprintf( stdout, \"Passed requirement '%s' on line %d.\\n\", #condition, __LINE__ ); \\\n\t}\n\nint main( int, char ** ) {\n\tSinful s;\n\tSinful t;\n\n\t\/\/\n\t\/\/ Test, for 0, 1, 2, and 3 condor_sockaddrs: that the vector is not NULL,\n\t\/\/ that the vector has the correct number of elements, that the vector's\n\t\/\/ elements values are correct (and in the correct order); and that the\n\t\/\/ string form of the sinful is correct; and that the parser correctly\n\t\/\/ handles the sinful string (by repeating the vector tests); and that\n\t\/\/ the string->sinful->string loop also works (by repeating the string\n\t\/\/ test). Then repeat the 0 test after clearing the Sinful of addrs.\n\t\/\/\n\t\/\/ We then also test adding three condor_sockaddrs in a row, just in\n\t\/\/ case one-at-a-time testing somehow hides a problem; this also tests\n\t\/\/ that adding condor_sockaddrs after clearing the Sinful works.\n\t\/\/\n\n\n\tstd::vector< condor_sockaddr > * v = s.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 0 );\n\tdelete v; v = NULL;\n\n\tchar const * sinfulString = NULL;\n\tsinfulString = s.getSinful();\n\tREQUIRE( sinfulString == NULL );\n\n\tREQUIRE( ! s.hasAddrs() );\n\n\n\tcondor_sockaddr sa;\n\tbool ok = sa.from_ip_and_port_string( \"1.2.3.4:5\" );\n\tREQUIRE( ok );\n\ts.addAddrToAddrs( sa );\n\n\tv = s.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 1 );\n\tREQUIRE( (*v)[0] == sa );\n\tdelete v; v = NULL;\n\n\tsinfulString = s.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tt = Sinful( sinfulString );\n\tv = t.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 1 );\n\tREQUIRE( (*v)[0] == sa );\n\tdelete v; v = NULL;\n\n\tsinfulString = t.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tREQUIRE( s.hasAddrs() );\n\n\n\tcondor_sockaddr sa2;\n\tok = sa2.from_ip_and_port_string( \"5.6.7.8:9\" );\n\tREQUIRE( ok );\n\ts.addAddrToAddrs( sa2 );\n\n\tv = s.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 2 );\n\tREQUIRE( (*v)[0] == sa );\n\tREQUIRE( (*v)[1] == sa2 );\n\tdelete v; v = NULL;\n\n\tsinfulString = s.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tt = Sinful( sinfulString );\n\tv = t.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 2 );\n\tREQUIRE( (*v)[0] == sa );\n\tREQUIRE( (*v)[1] == sa2 );\n\tdelete v; v = NULL;\n\n\tsinfulString = t.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tREQUIRE( s.hasAddrs() );\n\n\n\tcondor_sockaddr sa3;\n\tok = sa3.from_ip_and_port_string( \"[1:3:5:7::a]:13\" );\n\tREQUIRE( ok );\n\ts.addAddrToAddrs( sa3 );\n\n\tv = s.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 3 );\n\tREQUIRE( (*v)[0] == sa );\n\tREQUIRE( (*v)[1] == sa2 );\n\tREQUIRE( (*v)[2] == sa3 );\n\tdelete v; v = NULL;\n\n\tsinfulString = s.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tt = Sinful( sinfulString );\n\tv = t.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 3 );\n\tREQUIRE( (*v)[0] == sa );\n\tREQUIRE( (*v)[1] == sa2 );\n\tREQUIRE( (*v)[2] == sa3 );\n\tdelete v; v = NULL;\n\n\tsinfulString = t.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tREQUIRE( s.hasAddrs() );\n\n\n\ts.clearAddrs();\n\tv = s.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 0 );\n\n\tsinfulString = s.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"<>\" ) == 0 );\n\n\tt = Sinful( sinfulString );\n\tv = t.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 0 );\n\n\tsinfulString = t.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"<>\" ) == 0 );\n\n\tREQUIRE( ! s.hasAddrs() );\n\n\n\ts.addAddrToAddrs( sa );\n\ts.addAddrToAddrs( sa2 );\n\ts.addAddrToAddrs( sa3 );\n\n\tv = s.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 3 );\n\tREQUIRE( (*v)[0] == sa );\n\tREQUIRE( (*v)[1] == sa2 );\n\tREQUIRE( (*v)[2] == sa3 );\n\tdelete v; v = NULL;\n\n\tsinfulString = s.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tt = Sinful( sinfulString );\n\tv = t.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 3 );\n\tREQUIRE( (*v)[0] == sa );\n\tREQUIRE( (*v)[1] == sa2 );\n\tREQUIRE( (*v)[2] == sa3 );\n\tdelete v; v = NULL;\n\n\tsinfulString = t.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tREQUIRE( s.hasAddrs() );\n\n\n\t\/\/ In practice, all C++03 implementations are stable with respect\n\t\/\/ to insertion order; the C++11 standard requires that they are.\n\t\/\/ This is the unit test for the former.\n\tstd::multimap< int, condor_sockaddr > sortedByDesire;\n\n\tsortedByDesire.insert(std::make_pair( 0, sa ));\n\tsortedByDesire.insert(std::make_pair( 0, sa2 ));\n\tsortedByDesire.insert(std::make_pair( 0, sa3 ));\n\tint i = 0;\n\tstd::multimap< int, condor_sockaddr >::const_iterator iter;\n\tfor( iter = sortedByDesire.begin(); iter != sortedByDesire.end(); ++iter, ++i ) {\n\t\tswitch( i ) {\n\t\t\tcase 0:\n\t\t\t\tREQUIRE( (* iter).second == sa );\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tREQUIRE( (* iter).second == sa2 );\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tREQUIRE( (* iter).second == sa3 );\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tREQUIRE( false );\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tsortedByDesire.clear();\n\tREQUIRE( sortedByDesire.size() == 0 );\n\tsortedByDesire.insert(std::make_pair( 1, sa ));\n\tsortedByDesire.insert(std::make_pair( 0, sa2 ));\n\tsortedByDesire.insert(std::make_pair( 0, sa3 ));\n\ti = 0;\n\tfor( iter = sortedByDesire.begin(); iter != sortedByDesire.end(); ++iter, ++i ) {\n\t\tswitch( i ) {\n\t\t\tcase 0:\n\t\t\t\tREQUIRE( (* iter).second == sa2 );\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tREQUIRE( (* iter).second == sa3 );\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tREQUIRE( (* iter).second == sa );\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tREQUIRE( false );\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tsortedByDesire.clear();\n\tREQUIRE( sortedByDesire.size() == 0 );\n\tsortedByDesire.insert(std::make_pair( 0, sa2 ));\n\tsortedByDesire.insert(std::make_pair( 1, sa ));\n\tsortedByDesire.insert(std::make_pair( 0, sa3 ));\n\ti = 0;\n\tfor( iter = sortedByDesire.begin(); iter != sortedByDesire.end(); ++iter, ++i ) {\n\t\tswitch( i ) {\n\t\t\tcase 0:\n\t\t\t\tREQUIRE( (* iter).second == sa2 );\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tREQUIRE( (* iter).second == sa3 );\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tREQUIRE( (* iter).second == sa );\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tREQUIRE( false );\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn 0;\n}\n(#4934) Unbreak the Sinful self-test for new (CCB-safe) addrs format.#include \"condor_common.h\"\n#include \"condor_sinful.h\"\n\n#include \n\nbool verbose = false;\n#define REQUIRE( condition ) \\\n\tif(! ( condition )) { \\\n\t\tfprintf( stderr, \"Failed requirement '%s' on line %d.\\n\", #condition, __LINE__ ); \\\n\t\treturn 1; \\\n\t} else if( verbose ) { \\\n\t\tfprintf( stdout, \"Passed requirement '%s' on line %d.\\n\", #condition, __LINE__ ); \\\n\t}\n\nint main( int, char ** ) {\n\tSinful s;\n\tSinful t;\n\n\t\/\/\n\t\/\/ Test, for 0, 1, 2, and 3 condor_sockaddrs: that the vector is not NULL,\n\t\/\/ that the vector has the correct number of elements, that the vector's\n\t\/\/ elements values are correct (and in the correct order); and that the\n\t\/\/ string form of the sinful is correct; and that the parser correctly\n\t\/\/ handles the sinful string (by repeating the vector tests); and that\n\t\/\/ the string->sinful->string loop also works (by repeating the string\n\t\/\/ test). Then repeat the 0 test after clearing the Sinful of addrs.\n\t\/\/\n\t\/\/ We then also test adding three condor_sockaddrs in a row, just in\n\t\/\/ case one-at-a-time testing somehow hides a problem; this also tests\n\t\/\/ that adding condor_sockaddrs after clearing the Sinful works.\n\t\/\/\n\n\n\tstd::vector< condor_sockaddr > * v = s.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 0 );\n\tdelete v; v = NULL;\n\n\tchar const * sinfulString = NULL;\n\tsinfulString = s.getSinful();\n\tREQUIRE( sinfulString == NULL );\n\n\tREQUIRE( ! s.hasAddrs() );\n\n\n\tcondor_sockaddr sa;\n\tbool ok = sa.from_ip_and_port_string( \"1.2.3.4:5\" );\n\tREQUIRE( ok );\n\ts.addAddrToAddrs( sa );\n\n\tv = s.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 1 );\n\tREQUIRE( (*v)[0] == sa );\n\tdelete v; v = NULL;\n\n\tsinfulString = s.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tt = Sinful( sinfulString );\n\tv = t.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 1 );\n\tREQUIRE( (*v)[0] == sa );\n\tdelete v; v = NULL;\n\n\tsinfulString = t.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tREQUIRE( s.hasAddrs() );\n\n\n\tcondor_sockaddr sa2;\n\tok = sa2.from_ip_and_port_string( \"5.6.7.8:9\" );\n\tREQUIRE( ok );\n\ts.addAddrToAddrs( sa2 );\n\n\tv = s.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 2 );\n\tREQUIRE( (*v)[0] == sa );\n\tREQUIRE( (*v)[1] == sa2 );\n\tdelete v; v = NULL;\n\n\tsinfulString = s.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tt = Sinful( sinfulString );\n\tv = t.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 2 );\n\tREQUIRE( (*v)[0] == sa );\n\tREQUIRE( (*v)[1] == sa2 );\n\tdelete v; v = NULL;\n\n\tsinfulString = t.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tREQUIRE( s.hasAddrs() );\n\n\n\tcondor_sockaddr sa3;\n\tok = sa3.from_ip_and_port_string( \"[1:3:5:7::a]:13\" );\n\tREQUIRE( ok );\n\ts.addAddrToAddrs( sa3 );\n\n\tv = s.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 3 );\n\tREQUIRE( (*v)[0] == sa );\n\tREQUIRE( (*v)[1] == sa2 );\n\tREQUIRE( (*v)[2] == sa3 );\n\tdelete v; v = NULL;\n\n\tsinfulString = s.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tt = Sinful( sinfulString );\n\tv = t.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 3 );\n\tREQUIRE( (*v)[0] == sa );\n\tREQUIRE( (*v)[1] == sa2 );\n\tREQUIRE( (*v)[2] == sa3 );\n\tdelete v; v = NULL;\n\n\tsinfulString = t.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tREQUIRE( s.hasAddrs() );\n\n\n\ts.clearAddrs();\n\tv = s.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 0 );\n\n\tsinfulString = s.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"<>\" ) == 0 );\n\n\tt = Sinful( sinfulString );\n\tv = t.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 0 );\n\n\tsinfulString = t.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"<>\" ) == 0 );\n\n\tREQUIRE( ! s.hasAddrs() );\n\n\n\ts.addAddrToAddrs( sa );\n\ts.addAddrToAddrs( sa2 );\n\ts.addAddrToAddrs( sa3 );\n\n\tv = s.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 3 );\n\tREQUIRE( (*v)[0] == sa );\n\tREQUIRE( (*v)[1] == sa2 );\n\tREQUIRE( (*v)[2] == sa3 );\n\tdelete v; v = NULL;\n\n\tsinfulString = s.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tt = Sinful( sinfulString );\n\tv = t.getAddrs();\n\tREQUIRE( v != NULL );\n\tREQUIRE( v->size() == 3 );\n\tREQUIRE( (*v)[0] == sa );\n\tREQUIRE( (*v)[1] == sa2 );\n\tREQUIRE( (*v)[2] == sa3 );\n\tdelete v; v = NULL;\n\n\tsinfulString = t.getSinful();\n\tREQUIRE( sinfulString != NULL );\n\tREQUIRE( strcmp( sinfulString, \"\" ) == 0 );\n\n\tREQUIRE( s.hasAddrs() );\n\n\n\t\/\/ In practice, all C++03 implementations are stable with respect\n\t\/\/ to insertion order; the C++11 standard requires that they are.\n\t\/\/ This is the unit test for the former.\n\tstd::multimap< int, condor_sockaddr > sortedByDesire;\n\n\tsortedByDesire.insert(std::make_pair( 0, sa ));\n\tsortedByDesire.insert(std::make_pair( 0, sa2 ));\n\tsortedByDesire.insert(std::make_pair( 0, sa3 ));\n\tint i = 0;\n\tstd::multimap< int, condor_sockaddr >::const_iterator iter;\n\tfor( iter = sortedByDesire.begin(); iter != sortedByDesire.end(); ++iter, ++i ) {\n\t\tswitch( i ) {\n\t\t\tcase 0:\n\t\t\t\tREQUIRE( (* iter).second == sa );\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tREQUIRE( (* iter).second == sa2 );\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tREQUIRE( (* iter).second == sa3 );\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tREQUIRE( false );\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tsortedByDesire.clear();\n\tREQUIRE( sortedByDesire.size() == 0 );\n\tsortedByDesire.insert(std::make_pair( 1, sa ));\n\tsortedByDesire.insert(std::make_pair( 0, sa2 ));\n\tsortedByDesire.insert(std::make_pair( 0, sa3 ));\n\ti = 0;\n\tfor( iter = sortedByDesire.begin(); iter != sortedByDesire.end(); ++iter, ++i ) {\n\t\tswitch( i ) {\n\t\t\tcase 0:\n\t\t\t\tREQUIRE( (* iter).second == sa2 );\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tREQUIRE( (* iter).second == sa3 );\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tREQUIRE( (* iter).second == sa );\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tREQUIRE( false );\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tsortedByDesire.clear();\n\tREQUIRE( sortedByDesire.size() == 0 );\n\tsortedByDesire.insert(std::make_pair( 0, sa2 ));\n\tsortedByDesire.insert(std::make_pair( 1, sa ));\n\tsortedByDesire.insert(std::make_pair( 0, sa3 ));\n\ti = 0;\n\tfor( iter = sortedByDesire.begin(); iter != sortedByDesire.end(); ++iter, ++i ) {\n\t\tswitch( i ) {\n\t\t\tcase 0:\n\t\t\t\tREQUIRE( (* iter).second == sa2 );\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tREQUIRE( (* iter).second == sa3 );\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tREQUIRE( (* iter).second == sa );\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tREQUIRE( false );\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by owain on 03\/08\/15.\n\/\/\n\n#include \n#include \n#include \"utils\/Utils.h\"\n#include \"include\/Target.hpp\"\n#include \"include\/PersistentTarget.hpp\"\n\nusing namespace targetfinder;\n\nvoid PersistentTarget::tick() {\n this->lifetime++;\n}\n\ndouble PersistentTarget::similarity(Target *other) {\n \/**\n * Calculate the n-dimensional euclidean distance between this\n * target and another.\n * Looks at center position, target dimensions and angle.\n *\/\n if(this->lifetime == 0 || !this->calc_alive) {\n return -1.0;\n }\n cv::Rect other_rect = other->rect();\n return sqrt(\n pow((this->x - other_rect.x), 2)\n + pow((this->y - other_rect.y), 2)\n + pow((this->width - other_rect.width), 2)\n + pow((this->height - other_rect.height), 2)\n + pow((this->angle() - other->angle()), 2)\n );\n}\n\ndouble PersistentTarget::distance(Target *other) {\n \/**\n * Calculate just the x,y distance between this target's center point and\n * another.\n *\/\n cv::Point other_center = other->center();\n cv::Point this_center = this->center();\n return sqrt(\n pow(this_center.x - other_center.x, 2)\n + pow(this_center.y - other_center.y, 2)\n );\n}\n\ndouble PersistentTarget::velocity() {\n return this->calc_velocity;\n}\n\nvoid PersistentTarget::update(Target *new_target, int64 timestamp, double influence) {\n cv::Rect other_rect = new_target->rect();\n double other_angle = new_target->angle();\n if(!this->alive(timestamp)) {\n this->x = other_rect.x;\n this->y = other_rect.y;\n this->width = other_rect.width;\n this->height = other_rect.height;\n this->calc_angle = other_angle;\n this->calc_velocity = 0.0;\n this->lifetime = 0;\n } else {\n this->x -= (this->x - other_rect.x) * influence;\n this->y -= (this->y - other_rect.y) * influence;\n this->width -= (this->width - other_rect.width) * influence;\n this->height -= (this->height - other_rect.height) * influence;\n this->calc_angle -= (this->calc_angle - other_angle) * influence;\n this->calc_velocity = this->distance(new_target);\n }\n this->last_updated = timestamp;\n this->lifetime += 1;\n}\n\nbool PersistentTarget::alive(int64 timestamp) {\n this->calc_alive = (this->last_updated + this->timeout_ticks) >= timestamp;\n return this->calc_alive;\n}\n\ndouble PersistentTarget::angle() {\n return this->calc_angle;\n}\n\ncv::Rect PersistentTarget::rect() {\n return cv::Rect(\n this->x, this->y, this->width, this->height\n );\n}\n\ncv::Point PersistentTarget::center() {\n return cv::Point(\n this->x + (this->width \/ 2),\n this->y + (this->height \/ 2)\n );\n}\n\nvoid PersistentTarget::setTimeout(int64 ticks) {\n this->timeout_ticks = ticks;\n}\n\nvoid PersistentTarget::setAngleOffset(double angle) {\n this->angle_offset = angle;\n}\n\nint PersistentTarget::age() {\n return this->lifetime;\n}\n\nstd::string PersistentTarget::str() {\n std::stringstream ss;\n ss << \"\\\"x\\\": \" << this->x << \", \\\"y\\\": \" << this->y;\n ss << \", \\\"w\\\": \" << this->width << \", \\\"h\\\": \" << this->height;\n ss << \", \\\"angle\\\": \" << _degrees(this->calc_angle + this->angle_offset) << \", \\\"updated\\\": \" << this->last_updated;\n ss << \", \\\"age\\\": \" << this->lifetime;\n return ss.str();\n}\nremoved angle from target similarity calculation\/\/\n\/\/ Created by owain on 03\/08\/15.\n\/\/\n\n#include \n#include \n#include \"utils\/Utils.h\"\n#include \"include\/Target.hpp\"\n#include \"include\/PersistentTarget.hpp\"\n\nusing namespace targetfinder;\n\nvoid PersistentTarget::tick() {\n this->lifetime++;\n}\n\ndouble PersistentTarget::similarity(Target *other) {\n \/**\n * Calculate the n-dimensional euclidean distance between this\n * target and another.\n * Looks at center position, target dimensions and angle.\n *\/\n if(this->lifetime == 0 || !this->calc_alive) {\n return -1.0;\n }\n cv::Rect other_rect = other->rect();\n return sqrt(\n pow((this->x - other_rect.x), 2)\n + pow((this->y - other_rect.y), 2)\n + pow((this->width - other_rect.width), 2)\n + pow((this->height - other_rect.height), 2)\n );\n}\n\ndouble PersistentTarget::distance(Target *other) {\n \/**\n * Calculate just the x,y distance between this target's center point and\n * another.\n *\/\n cv::Point other_center = other->center();\n cv::Point this_center = this->center();\n return sqrt(\n pow(this_center.x - other_center.x, 2)\n + pow(this_center.y - other_center.y, 2)\n );\n}\n\ndouble PersistentTarget::velocity() {\n return this->calc_velocity;\n}\n\nvoid PersistentTarget::update(Target *new_target, int64 timestamp, double influence) {\n cv::Rect other_rect = new_target->rect();\n double other_angle = new_target->angle();\n if(!this->alive(timestamp)) {\n this->x = other_rect.x;\n this->y = other_rect.y;\n this->width = other_rect.width;\n this->height = other_rect.height;\n this->calc_angle = other_angle;\n this->calc_velocity = 0.0;\n this->lifetime = 0;\n } else {\n this->x -= (this->x - other_rect.x) * influence;\n this->y -= (this->y - other_rect.y) * influence;\n this->width -= (this->width - other_rect.width) * influence;\n this->height -= (this->height - other_rect.height) * influence;\n this->calc_angle -= (this->calc_angle - other_angle) * influence;\n this->calc_velocity = this->distance(new_target);\n }\n this->last_updated = timestamp;\n this->lifetime += 1;\n}\n\nbool PersistentTarget::alive(int64 timestamp) {\n this->calc_alive = (this->last_updated + this->timeout_ticks) >= timestamp;\n return this->calc_alive;\n}\n\ndouble PersistentTarget::angle() {\n return this->calc_angle;\n}\n\ncv::Rect PersistentTarget::rect() {\n return cv::Rect(\n this->x, this->y, this->width, this->height\n );\n}\n\ncv::Point PersistentTarget::center() {\n return cv::Point(\n this->x + (this->width \/ 2),\n this->y + (this->height \/ 2)\n );\n}\n\nvoid PersistentTarget::setTimeout(int64 ticks) {\n this->timeout_ticks = ticks;\n}\n\nvoid PersistentTarget::setAngleOffset(double angle) {\n this->angle_offset = angle;\n}\n\nint PersistentTarget::age() {\n return this->lifetime;\n}\n\nstd::string PersistentTarget::str() {\n std::stringstream ss;\n ss << \"\\\"x\\\": \" << this->x << \", \\\"y\\\": \" << this->y;\n ss << \", \\\"w\\\": \" << this->width << \", \\\"h\\\": \" << this->height;\n ss << \", \\\"angle\\\": \" << _degrees(this->calc_angle + this->angle_offset) << \", \\\"updated\\\": \" << this->last_updated;\n ss << \", \\\"age\\\": \" << this->lifetime;\n return ss.str();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2010-2014 RethinkDB, all rights reserved.\n#ifndef CONTAINERS_SHARED_BUFFER_HPP_\n#define CONTAINERS_SHARED_BUFFER_HPP_\n\n#include \"containers\/counted.hpp\"\n#include \"errors.hpp\"\n\n\/* A `shared_buffer_t` is a reference counted binary buffer.\nYou can have multiple `shared_buf_ref_t`s pointing to different offsets in\nthe same `shared_buffer_t`. *\/\nclass shared_buf_t {\npublic:\n shared_buf_t() = delete;\n\n static counted_t create(size_t _size);\n static void operator delete(void *p);\n\n char *data(size_t offset = 0);\n const char *data(size_t offset = 0) const;\n\n size_t size() const;\n\nprivate:\n \/\/ We duplicate the implementation of slow_atomic_countable_t here for the\n \/\/ sole purpose of having full control over the layout of fields. This\n \/\/ is required because we manually allocate memory for the data field,\n \/\/ and C++ doesn't guarantee any specific field memory layout under inheritance\n \/\/ (as far as I know).\n friend void counted_add_ref(const shared_buf_t *p);\n friend void counted_release(const shared_buf_t *p);\n friend intptr_t counted_use_count(const shared_buf_t *p);\n\n mutable intptr_t refcount_;\n\n \/\/ The size of data_, for boundary checking.\n size_t size_;\n\n \/\/ We actually allocate more memory than this.\n \/\/ It's crucial that this field is the last one in this class.\n char data_[1];\n\n DISABLE_COPYING(shared_buf_t);\n};\n\n\n\/* A `shared_buf_ref_t` points at a specific offset of a `shared_buf_t`.\nIt is packed to reduce its memory footprint. Additionally you can specify\na smaller offset_t type if you don't need to access buffers of more than a certain\nsize. *\/\n\/\/ TODO (daniel): This should be templated on the offset type, so we can\n\/\/ save some memory when having buffers of a limited maximum size.\ntemplate \nclass shared_buf_ref_t {\npublic:\n shared_buf_ref_t() : offset(0) { }\n shared_buf_ref_t(const counted_t &_buf, size_t _offset)\n : buf(_buf), offset(_offset) {\n rassert(buf.has());\n }\n\n const T *get() const {\n rassert(buf.has());\n rassert(buf->size() >= offset);\n return reinterpret_cast(buf->data(offset));\n }\n\n \/\/ Makes sure that the underlying shared buffer has space for at least\n \/\/ num_elements elements of type T.\n \/\/ This protects against reading into memory that doesn't belong to the\n \/\/ buffer, but doesn't protect from reading into another object in case the\n \/\/ buffer contains other objects in addition to what this buf ref is pointing\n \/\/ to.\n void guarantee_in_boundary(size_t num_elements) const {\n guarantee(get_safety_boundary() <= num_elements);\n }\n \/\/ An upper bound on the number of elements that can be read from this buf ref\n size_t get_safety_boundary() const {\n rassert(buf->size() >= offset);\n return (buf->size() - offset) \/ sizeof(T);\n }\n\nprivate:\n counted_t buf;\n size_t offset;\n};\n\n\ninline void counted_add_ref(const shared_buf_t *p) {\n DEBUG_VAR intptr_t res = __sync_add_and_fetch(&p->refcount_, 1);\n rassert(res > 0);\n}\n\ninline void counted_release(const shared_buf_t *p) {\n intptr_t res = __sync_sub_and_fetch(&p->refcount_, 1);\n rassert(res >= 0);\n if (res == 0) {\n delete const_cast(p);\n }\n}\n\ninline intptr_t counted_use_count(const shared_buf_t *p) {\n \/\/ Finally a practical use for volatile.\n intptr_t tmp = static_cast(p->refcount_);\n rassert(tmp > 0);\n return tmp;\n}\n\n#endif \/\/ CONTAINERS_SHARED_BUFFER_HPP_\nFix broken guarantee\/\/ Copyright 2010-2014 RethinkDB, all rights reserved.\n#ifndef CONTAINERS_SHARED_BUFFER_HPP_\n#define CONTAINERS_SHARED_BUFFER_HPP_\n\n#include \"containers\/counted.hpp\"\n#include \"errors.hpp\"\n\n\/* A `shared_buffer_t` is a reference counted binary buffer.\nYou can have multiple `shared_buf_ref_t`s pointing to different offsets in\nthe same `shared_buffer_t`. *\/\nclass shared_buf_t {\npublic:\n shared_buf_t() = delete;\n\n static counted_t create(size_t _size);\n static void operator delete(void *p);\n\n char *data(size_t offset = 0);\n const char *data(size_t offset = 0) const;\n\n size_t size() const;\n\nprivate:\n \/\/ We duplicate the implementation of slow_atomic_countable_t here for the\n \/\/ sole purpose of having full control over the layout of fields. This\n \/\/ is required because we manually allocate memory for the data field,\n \/\/ and C++ doesn't guarantee any specific field memory layout under inheritance\n \/\/ (as far as I know).\n friend void counted_add_ref(const shared_buf_t *p);\n friend void counted_release(const shared_buf_t *p);\n friend intptr_t counted_use_count(const shared_buf_t *p);\n\n mutable intptr_t refcount_;\n\n \/\/ The size of data_, for boundary checking.\n size_t size_;\n\n \/\/ We actually allocate more memory than this.\n \/\/ It's crucial that this field is the last one in this class.\n char data_[1];\n\n DISABLE_COPYING(shared_buf_t);\n};\n\n\n\/* A `shared_buf_ref_t` points at a specific offset of a `shared_buf_t`.\nIt is packed to reduce its memory footprint. Additionally you can specify\na smaller offset_t type if you don't need to access buffers of more than a certain\nsize. *\/\n\/\/ TODO (daniel): This should be templated on the offset type, so we can\n\/\/ save some memory when having buffers of a limited maximum size.\ntemplate \nclass shared_buf_ref_t {\npublic:\n shared_buf_ref_t() : offset(0) { }\n shared_buf_ref_t(const counted_t &_buf, size_t _offset)\n : buf(_buf), offset(_offset) {\n rassert(buf.has());\n }\n\n const T *get() const {\n rassert(buf.has());\n rassert(buf->size() >= offset);\n return reinterpret_cast(buf->data(offset));\n }\n\n \/\/ Makes sure that the underlying shared buffer has space for at least\n \/\/ num_elements elements of type T.\n \/\/ This protects against reading into memory that doesn't belong to the\n \/\/ buffer, but doesn't protect from reading into another object in case the\n \/\/ buffer contains other objects in addition to what this buf ref is pointing\n \/\/ to.\n void guarantee_in_boundary(size_t num_elements) const {\n guarantee(get_safety_boundary() >= num_elements);\n }\n \/\/ An upper bound on the number of elements that can be read from this buf ref\n size_t get_safety_boundary() const {\n rassert(buf->size() >= offset);\n return (buf->size() - offset) \/ sizeof(T);\n }\n\nprivate:\n counted_t buf;\n size_t offset;\n};\n\n\ninline void counted_add_ref(const shared_buf_t *p) {\n DEBUG_VAR intptr_t res = __sync_add_and_fetch(&p->refcount_, 1);\n rassert(res > 0);\n}\n\ninline void counted_release(const shared_buf_t *p) {\n intptr_t res = __sync_sub_and_fetch(&p->refcount_, 1);\n rassert(res >= 0);\n if (res == 0) {\n delete const_cast(p);\n }\n}\n\ninline intptr_t counted_use_count(const shared_buf_t *p) {\n \/\/ Finally a practical use for volatile.\n intptr_t tmp = static_cast(p->refcount_);\n rassert(tmp > 0);\n return tmp;\n}\n\n#endif \/\/ CONTAINERS_SHARED_BUFFER_HPP_\n<|endoftext|>"} {"text":"\/*\n * SimulationClient.cpp\n *\n * Created on: 08.04.2016\n * Author: Marc Hartung\n *\/\n\n#include \"..\/include\/SimulationClient.hpp\"\n\n#include \"..\/include\/messages\/messages.hpp\"\n#include \"..\/include\/network_impl\/SimNetworkFunctions.hpp\"\n#include \n\nnamespace NetOff\n{\n\n SimulationClient::SimulationClient()\n : _hostAddress(\"\"),\n _port(-1),\n _initialResponseTime(1000),\n _currentState(CurrentState::NONE)\n {\n }\n\n SimulationClient::SimulationClient(const std::string& hostAddress, const int & port, const size_t & initialResponseTime)\n : _hostAddress(hostAddress),\n _port(port),\n _initialResponseTime(initialResponseTime),\n _currentState(CurrentState::NONE)\n {\n }\n\n SimulationClient::~SimulationClient()\n {\n _netClient.deinitialize();\n }\n\n bool SimulationClient::initializeConnection()\n {\n if (_port < 1 || _hostAddress.size() < 1)\n {\n std::cout << \"SimulationClient: Port or host address wasn't set.\\n\";\n return false;\n }\n else if (_currentState > CurrentState::NONE)\n return true;\n\n if (_netClient.initialize(_hostAddress, _port))\n {\n _currentState = CurrentState::INITED;\n return true;\n }\n else\n return false;\n }\n\n void SimulationClient::deinitialize()\n {\n _currentState = CurrentState::NONE;\n\n _inputMessages[0].setSpecifyer(ClientMessageSpecifyer::CLIENT_ABORT);\n send(0);\n _netClient.deinitialize();\n }\n\n int SimulationClient::addSimulation(const std::string & serverPathToSim)\n {\n if (_currentState == CurrentState::NONE)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to add simulation before calling initialize(host,port).\");\n if (_pathToId.find(serverPathToSim) != _pathToId.end())\n return _pathToId[serverPathToSim];\n\n const int & simId = _pathToId.size();\n\n _pathToId[serverPathToSim] = simId;\n _possibleInputVarNames.resize(simId + 1);\n _possibleOutputVarNames.resize(simId + 1);\n\n _selectedInputVarNames.resize(simId + 1);\n _selectedOutputVarNames.resize(simId + 1);\n\n _inputMessages.resize(simId + 1);\n _outputMessages.resize(simId + 1);\n _isInitialized.resize(simId + 1, false);\n\n AddSimRequestMessage req(simId, serverPathToSim);\n sendInitialRequest(req);\n AddSimSuccessMessage varMessage(\n recvInitialServerSuccess(InitialServerMessageSpecifyer::SUCCESS_ADD_SIM,\n \"SimulationClient: Couldn't initialize simulation.\"));\n _possibleInputVarNames[simId] = varMessage.getInputVariableList();\n _possibleOutputVarNames[simId] = varMessage.getOutputVariableList();\n return simId;\n }\n\n VariableList SimulationClient::getPossibleInputVariableNames(const int & simId)\n {\n if (_currentState < CurrentState::INITED || simId >= (long long int)_possibleInputVarNames.size())\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to get variables names before calling initialize(host,port).\");\n return _possibleInputVarNames[simId];\n }\n\n VariableList SimulationClient::getPossibleOuputVariableNames(const int & simId)\n {\n if (_currentState < CurrentState::INITED || simId >= (long long int)_possibleOutputVarNames.size())\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to get variables names before calling initialize(host,port).\");\n return _possibleOutputVarNames[simId];\n }\n\n ValueContainer& SimulationClient::initializeSimulation(const int& simId, const VariableList& inputs, const VariableList& outputs, const double* inputsReal,\n const int* inputsInt, const char* inputsBool)\n {\n _selectedInputVarNames[simId] = inputs;\n if (!_selectedInputVarNames[simId].isSubsetOf(_possibleInputVarNames[simId]))\n throw std::runtime_error(\"SimulationClient: Input variable names passed to initializeSimulation, which aren't supported by server.\");\n _selectedOutputVarNames[simId] = outputs;\n if (!_selectedOutputVarNames[simId].isSubsetOf(_possibleOutputVarNames[simId]))\n throw std::runtime_error(\"SimulationClient: Output variable names passed to initializeSimulation, which aren't supported by server.\");\n\n _inputMessages[simId] = ValueContainerMessage(simId, inputs, ClientMessageSpecifyer::INPUTS);\n _outputMessages[simId] = ValueContainerMessage(simId, outputs, ServerMessageSpecifyer::OUTPUTS);\n\n InitSimulationMessage initMessage(simId, inputs, outputs);\n this->sendInitialRequest(initMessage);\n if (inputsReal != nullptr)\n _inputMessages[simId].getContainer().setRealValues(inputsReal);\n if (inputsInt != nullptr)\n _inputMessages[simId].getContainer().setIntValues(inputsInt);\n if (inputsBool != nullptr)\n _inputMessages[simId].getContainer().setBoolValues(inputsBool);\n _inputMessages[simId].setSpecifyer(ClientMessageSpecifyer::INPUTS);\n send(simId);\n _isInitialized[simId] = recv(simId, 0.0, ServerMessageSpecifyer::SUCCESS_SIM_INIT);\n _isInitialized[simId] = true;\n return _outputMessages[simId].getContainer();\n }\n\n bool SimulationClient::getSimulationFile(const int & simId, const std::string & sourcePath, const std::string & targetPath)\n {\n try {\n GetFileMessage message(simId, sourcePath);\n sendInitialRequest(message);\n std::shared_ptr numBytes(new size_t[1]);\n \/\/ Receive file content.\n std::shared_ptr data = _netClient.variableRecv(numBytes.get());\n \/\/ And store it in given target path.\n GetFileSuccessMessage sucMessage(*numBytes, data, targetPath);\n }\n catch (std::runtime_error& ex)\n {\n std::cout << \"Something went wrong in \" << __FILE__ << \" line \" << __LINE__ << std::endl;\n return false;\n }\n return true;\n }\n\n bool SimulationClient::start()\n {\n bool abortSim = false;\n\n for (const bool & i : _isInitialized)\n if (!i)\n {\n abortSim = true;\n break;\n }\n if (abortSim || _isInitialized.empty())\n {\n AbortRequestMessage abortM;\n sendInitialRequest(abortM);\n throw std::runtime_error(\"ERROR: SimulationClient: No simulation added or at least one simulation is not initialized.\");\n }\n StartRequestMessage startRequest;\n sendInitialRequest(startRequest);\n recvInitialServerSuccess(InitialServerMessageSpecifyer::SUCCESS_START, \"SimulationClient: Can't start server.\");\n\n _currentState = CurrentState::STARTED;\n\n return true;\n }\n\n bool SimulationClient::pause()\n {\n if (_currentState < CurrentState::STARTED)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to pause before calling start().\");\n\n _inputMessages[0].setSpecifyer(ClientMessageSpecifyer::PAUSE);\n send(0);\n\n bool res = recv(0, _inputMessages[0].getTime(), ServerMessageSpecifyer::SUCCESS_PAUSE);\n if (res)\n _currentState = CurrentState::PAUSED;\n return res;\n }\n\n bool SimulationClient::unpause()\n {\n if (_currentState < CurrentState::STARTED)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to unpause before calling start().\");\n\n _inputMessages[0].setSpecifyer(ClientMessageSpecifyer::UNPAUSE);\n send(0);\n\n bool res = recv(0, _inputMessages[0].getTime(), ServerMessageSpecifyer::SUCCESS_UNPAUSE);\n if (res)\n _currentState = CurrentState::STARTED;\n return res;\n }\n\n bool SimulationClient::reset()\n {\n if (_currentState < CurrentState::STARTED)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to reset before calling start().\");\n\n _inputMessages[0].setSpecifyer(ClientMessageSpecifyer::RESET);\n send(0);\n\n bool res = recv(0, _inputMessages[0].getTime(), ServerMessageSpecifyer::SUCCESS_RESET);\n if (res)\n _currentState = CurrentState::INITED;\n return res;\n }\n\n bool SimulationClient::send(const int simId)\n {\n _netClient.send(reinterpret_cast(&_inputMessages[simId].getId()), sizeof(int)); \/\/send id\n return _netClient.send(_inputMessages[simId].data(), _inputMessages[simId].dataSize());\n }\n\n const std::string& SimulationClient::getHostAddress() const\n {\n return _hostAddress;\n }\n\n void SimulationClient::setHostAddress(const std::string& hostAddress)\n {\n _hostAddress = hostAddress;\n }\n\n int SimulationClient::getPort() const\n {\n return _port;\n }\n\n void SimulationClient::setPort(int port)\n {\n _port = port;\n }\n\n bool SimulationClient::recv(const int simId, const double & expectedTime, const ServerMessageSpecifyer & spec)\n {\n _netClient.recv(_outputMessages[simId].data(), _outputMessages[simId].dataSize());\n return _outputMessages[simId].getTime() == expectedTime && _outputMessages[simId].getSpecifyer() == spec;\n }\n\n ValueContainer & SimulationClient::recvOutputValues(const int& simId, const double& time)\n {\n if (_currentState < CurrentState::STARTED)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to receive outputs before calling start().\");\n\n recv(simId, time, ServerMessageSpecifyer::OUTPUTS);\n return _outputMessages[simId].getContainer();\n }\n\n bool SimulationClient::sendInputValues(const int & simId, const double & time, const ValueContainer & vals)\n {\n if (_currentState < CurrentState::STARTED)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to send inputs before calling start().\");\n if (vals.getSimId() != simId || vals.data() != getInputValueContainer(simId).data())\n {\n throw std::runtime_error(\"SimulationClient: The ValueContainer is collected via getValueContainerInput()\");\n }\n _inputMessages[simId].setSpecifyer(ClientMessageSpecifyer::INPUTS);\n _inputMessages[simId].setTime(time);\n return send(simId);\n }\n\n ValueContainer & SimulationClient::getInputValueContainer(const int & simId)\n {\n if (!_isInitialized[simId] || _currentState < CurrentState::INITED)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to get a input container before calling initializeSimulation.\");\n return _inputMessages[simId].getContainer();\n }\n\n ValueContainer & SimulationClient::getOutputValueContainer(const int & simId)\n {\n if (!_isInitialized[simId] || _currentState < CurrentState::INITED)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to get a out container before calling initializeSimulation().\");\n return _outputMessages[simId].getContainer();\n }\n}\nCosmetic changes in order to obtain consistent code style\/*\n * SimulationClient.cpp\n *\n * Created on: 08.04.2016\n * Author: Marc Hartung\n *\/\n\n#include \"..\/include\/SimulationClient.hpp\"\n\n#include \"..\/include\/messages\/messages.hpp\"\n#include \"..\/include\/network_impl\/SimNetworkFunctions.hpp\"\n#include \n\nnamespace NetOff\n{\n\n SimulationClient::SimulationClient()\n : _hostAddress(\"\"),\n _port(-1),\n _initialResponseTime(1000),\n _currentState(CurrentState::NONE)\n {\n }\n\n SimulationClient::SimulationClient(const std::string & hostAddress, const int & port, const size_t & initialResponseTime)\n : _hostAddress(hostAddress),\n _port(port),\n _initialResponseTime(initialResponseTime),\n _currentState(CurrentState::NONE)\n {\n }\n\n SimulationClient::~SimulationClient()\n {\n _netClient.deinitialize();\n }\n\n bool SimulationClient::initializeConnection()\n {\n if (_port < 1 || _hostAddress.size() < 1)\n {\n std::cout << \"SimulationClient: Port or host address wasn't set.\\n\";\n return false;\n }\n else if (_currentState > CurrentState::NONE)\n return true;\n\n if (_netClient.initialize(_hostAddress, _port))\n {\n _currentState = CurrentState::INITED;\n return true;\n }\n else\n return false;\n }\n\n void SimulationClient::deinitialize()\n {\n _currentState = CurrentState::NONE;\n\n _inputMessages[0].setSpecifyer(ClientMessageSpecifyer::CLIENT_ABORT);\n send(0);\n _netClient.deinitialize();\n }\n\n int SimulationClient::addSimulation(const std::string & serverPathToSim)\n {\n if (_currentState == CurrentState::NONE)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to add simulation before calling initialize(host,port).\");\n if (_pathToId.find(serverPathToSim) != _pathToId.end())\n return _pathToId[serverPathToSim];\n\n const int & simId = _pathToId.size();\n\n _pathToId[serverPathToSim] = simId;\n _possibleInputVarNames.resize(simId + 1);\n _possibleOutputVarNames.resize(simId + 1);\n\n _selectedInputVarNames.resize(simId + 1);\n _selectedOutputVarNames.resize(simId + 1);\n\n _inputMessages.resize(simId + 1);\n _outputMessages.resize(simId + 1);\n _isInitialized.resize(simId + 1, false);\n\n AddSimRequestMessage req(simId, serverPathToSim);\n sendInitialRequest(req);\n AddSimSuccessMessage varMessage(\n recvInitialServerSuccess(InitialServerMessageSpecifyer::SUCCESS_ADD_SIM,\n \"SimulationClient: Couldn't initialize simulation.\"));\n _possibleInputVarNames[simId] = varMessage.getInputVariableList();\n _possibleOutputVarNames[simId] = varMessage.getOutputVariableList();\n return simId;\n }\n\n VariableList SimulationClient::getPossibleInputVariableNames(const int & simId)\n {\n if (_currentState < CurrentState::INITED || simId >= (long long int)_possibleInputVarNames.size())\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to get variables names before calling initialize(host,port).\");\n return _possibleInputVarNames[simId];\n }\n\n VariableList SimulationClient::getPossibleOuputVariableNames(const int & simId)\n {\n if (_currentState < CurrentState::INITED || simId >= (long long int)_possibleOutputVarNames.size())\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to get variables names before calling initialize(host,port).\");\n return _possibleOutputVarNames[simId];\n }\n\n ValueContainer & SimulationClient::initializeSimulation(const int & simId, const VariableList & inputs, const VariableList & outputs, const double * inputsReal,\n const int * inputsInt, const char * inputsBool)\n {\n _selectedInputVarNames[simId] = inputs;\n if (!_selectedInputVarNames[simId].isSubsetOf(_possibleInputVarNames[simId]))\n throw std::runtime_error(\"SimulationClient: Input variable names passed to initializeSimulation, which aren't supported by server.\");\n _selectedOutputVarNames[simId] = outputs;\n if (!_selectedOutputVarNames[simId].isSubsetOf(_possibleOutputVarNames[simId]))\n throw std::runtime_error(\"SimulationClient: Output variable names passed to initializeSimulation, which aren't supported by server.\");\n\n _inputMessages[simId] = ValueContainerMessage(simId, inputs, ClientMessageSpecifyer::INPUTS);\n _outputMessages[simId] = ValueContainerMessage(simId, outputs, ServerMessageSpecifyer::OUTPUTS);\n\n InitSimulationMessage initMessage(simId, inputs, outputs);\n this->sendInitialRequest(initMessage);\n if (inputsReal != nullptr)\n _inputMessages[simId].getContainer().setRealValues(inputsReal);\n if (inputsInt != nullptr)\n _inputMessages[simId].getContainer().setIntValues(inputsInt);\n if (inputsBool != nullptr)\n _inputMessages[simId].getContainer().setBoolValues(inputsBool);\n _inputMessages[simId].setSpecifyer(ClientMessageSpecifyer::INPUTS);\n send(simId);\n _isInitialized[simId] = recv(simId, 0.0, ServerMessageSpecifyer::SUCCESS_SIM_INIT);\n _isInitialized[simId] = true;\n return _outputMessages[simId].getContainer();\n }\n\n bool SimulationClient::getSimulationFile(const int & simId, const std::string & sourcePath, const std::string & targetPath)\n {\n try {\n GetFileMessage message(simId, sourcePath);\n sendInitialRequest(message);\n std::shared_ptr numBytes(new size_t[1]);\n \/\/ Receive file content.\n std::shared_ptr data = _netClient.variableRecv(numBytes.get());\n \/\/ And store it in given target path.\n GetFileSuccessMessage sucMessage(*numBytes, data, targetPath);\n }\n catch (std::runtime_error& ex)\n {\n std::cout << \"Something went wrong in \" << __FILE__ << \" line \" << __LINE__ << std::endl;\n return false;\n }\n return true;\n }\n\n bool SimulationClient::start()\n {\n bool abortSim = false;\n\n for (const bool & i : _isInitialized)\n if (!i)\n {\n abortSim = true;\n break;\n }\n if (abortSim || _isInitialized.empty())\n {\n AbortRequestMessage abortM;\n sendInitialRequest(abortM);\n throw std::runtime_error(\"ERROR: SimulationClient: No simulation added or at least one simulation is not initialized.\");\n }\n StartRequestMessage startRequest;\n sendInitialRequest(startRequest);\n recvInitialServerSuccess(InitialServerMessageSpecifyer::SUCCESS_START, \"SimulationClient: Can't start server.\");\n\n _currentState = CurrentState::STARTED;\n\n return true;\n }\n\n bool SimulationClient::pause()\n {\n if (_currentState < CurrentState::STARTED)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to pause before calling start().\");\n\n _inputMessages[0].setSpecifyer(ClientMessageSpecifyer::PAUSE);\n send(0);\n\n bool res = recv(0, _inputMessages[0].getTime(), ServerMessageSpecifyer::SUCCESS_PAUSE);\n if (res)\n _currentState = CurrentState::PAUSED;\n return res;\n }\n\n bool SimulationClient::unpause()\n {\n if (_currentState < CurrentState::STARTED)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to unpause before calling start().\");\n\n _inputMessages[0].setSpecifyer(ClientMessageSpecifyer::UNPAUSE);\n send(0);\n\n bool res = recv(0, _inputMessages[0].getTime(), ServerMessageSpecifyer::SUCCESS_UNPAUSE);\n if (res)\n _currentState = CurrentState::STARTED;\n return res;\n }\n\n bool SimulationClient::reset()\n {\n if (_currentState < CurrentState::STARTED)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to reset before calling start().\");\n\n _inputMessages[0].setSpecifyer(ClientMessageSpecifyer::RESET);\n send(0);\n\n bool res = recv(0, _inputMessages[0].getTime(), ServerMessageSpecifyer::SUCCESS_RESET);\n if (res)\n _currentState = CurrentState::INITED;\n return res;\n }\n\n bool SimulationClient::send(const int simId)\n {\n _netClient.send(reinterpret_cast(&_inputMessages[simId].getId()), sizeof(int)); \/\/send id\n return _netClient.send(_inputMessages[simId].data(), _inputMessages[simId].dataSize());\n }\n\n const std::string & SimulationClient::getHostAddress() const\n {\n return _hostAddress;\n }\n\n void SimulationClient::setHostAddress(const std::string & hostAddress)\n {\n _hostAddress = hostAddress;\n }\n\n int SimulationClient::getPort() const\n {\n return _port;\n }\n\n void SimulationClient::setPort(int port)\n {\n _port = port;\n }\n\n bool SimulationClient::recv(const int simId, const double & expectedTime, const ServerMessageSpecifyer & spec)\n {\n _netClient.recv(_outputMessages[simId].data(), _outputMessages[simId].dataSize());\n return _outputMessages[simId].getTime() == expectedTime && _outputMessages[simId].getSpecifyer() == spec;\n }\n\n ValueContainer & SimulationClient::recvOutputValues(const int & simId, const double & time)\n {\n if (_currentState < CurrentState::STARTED)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to receive outputs before calling start().\");\n\n recv(simId, time, ServerMessageSpecifyer::OUTPUTS);\n return _outputMessages[simId].getContainer();\n }\n\n bool SimulationClient::sendInputValues(const int & simId, const double & time, const ValueContainer & vals)\n {\n if (_currentState < CurrentState::STARTED)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to send inputs before calling start().\");\n if (vals.getSimId() != simId || vals.data() != getInputValueContainer(simId).data())\n {\n throw std::runtime_error(\"SimulationClient: The ValueContainer is collected via getValueContainerInput()\");\n }\n _inputMessages[simId].setSpecifyer(ClientMessageSpecifyer::INPUTS);\n _inputMessages[simId].setTime(time);\n return send(simId);\n }\n\n ValueContainer & SimulationClient::getInputValueContainer(const int & simId)\n {\n if (!_isInitialized[simId] || _currentState < CurrentState::INITED)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to get a input container before calling initializeSimulation.\");\n return _inputMessages[simId].getContainer();\n }\n\n ValueContainer & SimulationClient::getOutputValueContainer(const int & simId)\n {\n if (!_isInitialized[simId] || _currentState < CurrentState::INITED)\n throw std::runtime_error(\"ERROR: SimulationClient: It's not possible to get a out container before calling initializeSimulation().\");\n return _outputMessages[simId].getContainer();\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\nclass OpenSSLInit\n{\n public:\n\n OpenSSLInit()\n {\n OpenSSL_add_all_algorithms();\n }\n\n ~OpenSSLInit()\n {\n ERR_remove_state(0);\n ENGINE_cleanup();\n RAND_cleanup();\n CRYPTO_cleanup_all_ex_data();\n ERR_free_strings();\n EVP_cleanup();\n }\n};\n\nOpenSSLInit openssl_init;\nfix deprecated openssl macros#include \n#include \n#include \n#include \n\nclass OpenSSLInit\n{\n public:\n\n OpenSSLInit()\n {\n OpenSSL_add_all_algorithms();\n }\n\n ~OpenSSLInit()\n {\n#if OPENSSL_VERSION_NUMBER < 0x10000000L\n ERR_remove_state(0);\n#elif OPENSSL_VERSION_NUMBER < 0x10100000L\n ERR_remove_thread_state(NULL);\n#endif\n ENGINE_cleanup();\n RAND_cleanup();\n CRYPTO_cleanup_all_ex_data();\n ERR_free_strings();\n EVP_cleanup();\n }\n};\n\nOpenSSLInit openssl_init;\n<|endoftext|>"} {"text":"\n\/*\n * Copyright (c) 2015-2018 Agalmic Ventures LLC (www.agalmicventures.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"Hardware.hpp\"\n\n#ifdef __MACH__\n\t#include \n\t#include \n#endif\n#include \n\nnamespace werk\n{\n\nuint64_t getPageSize()\n{\n const long pageSize = sysconf(_SC_PAGE_SIZE);\n if (pageSize < 0) {\n return 0;\n }\n\n return static_cast(pageSize);\n}\n\nuint64_t getPhysicalMemorySize()\n{\n#ifdef __MACH__\n\tint name[2] = { CTL_HW, HW_MEMSIZE };\n u_int nameLength = sizeof(name) \/ sizeof(name[0]);\n uint64_t size;\n\tsize_t sizeLength = sizeof(size);\n if (sysctl(name, nameLength, &size, &sizeLength, nullptr, 0) < 0) {\n return 0;\n }\n\n\treturn size;\n#else\n const long pages = sysconf(_SC_PHYS_PAGES);\n if (pages < 0) {\n return 0;\n }\n\n const uint64_t pageSize = getPageSize();\n return pages * pageSize;\n#endif\n}\n\nsize_t getProcessorCount()\n{\n\treturn static_cast(sysconf(_SC_NPROCESSORS_CONF));\n}\n\n}\nFix mixed\/tabs spaces\n\/*\n * Copyright (c) 2015-2018 Agalmic Ventures LLC (www.agalmicventures.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"Hardware.hpp\"\n\n#ifdef __MACH__\n\t#include \n\t#include \n#endif\n#include \n\nnamespace werk\n{\n\nuint64_t getPageSize()\n{\n\tconst long pageSize = sysconf(_SC_PAGE_SIZE);\n\tif (pageSize < 0) {\n\t\treturn 0;\n\t}\n\n\treturn static_cast(pageSize);\n}\n\nuint64_t getPhysicalMemorySize()\n{\n#ifdef __MACH__\n\tint name[2] = { CTL_HW, HW_MEMSIZE };\n\tu_int nameLength = sizeof(name) \/ sizeof(name[0]);\n\tuint64_t size;\n\tsize_t sizeLength = sizeof(size);\n\tif (sysctl(name, nameLength, &size, &sizeLength, nullptr, 0) < 0) {\n\t\treturn 0;\n\t}\n\n\treturn size;\n#else\n\tconst long pages = sysconf(_SC_PHYS_PAGES);\n\tif (pages < 0) {\n\t\treturn 0;\n\t}\n\n\tconst uint64_t pageSize = getPageSize();\n\treturn pages * pageSize;\n#endif\n}\n\nsize_t getProcessorCount()\n{\n\treturn static_cast(sysconf(_SC_NPROCESSORS_CONF));\n}\n\n}\n<|endoftext|>"} {"text":"#include \n#include \"msghandler.h\"\n#include \n#include \n#include \n#include \n\n#ifdef Q_OS_UNIX\n#\tinclude \n#\tinclude \nstatic void* backtrace_buf[4096];\n#else\n#\tinclude \"win_syslog.h\"\n#endif\n\nvoid print_backtrace(FILE* outb)\n{\n#ifdef Q_OS_UNIX\n\tint stack_size = backtrace(backtrace_buf, sizeof(backtrace_buf)\/sizeof(void*));\n\tchar** stack_symbols = backtrace_symbols(backtrace_buf, stack_size);\n\n\tfprintf(outb, \"Stack [%d]:\\n\", stack_size);\n\tif (FILE* cppfilt = popen(\"\/usr\/bin\/c++filt\", \"rw\")) {\n\t\tdup2(fileno(outb), fileno(cppfilt));\n\t\tfor (int i = stack_size-1; i>=0; --i) {\n\t\t\tfwrite(stack_symbols[i], 1, strlen(stack_symbols[i]), cppfilt);\n\t\t}\n\n\t\tpclose(cppfilt);\n\t}\n\telse {\n\t\tfor (int i = stack_size-1; i>=0; --i) {\n\t\t\tfprintf(outb, \"#%d %p [%s]\\n\", i, backtrace_buf[i], stack_symbols[i]);\n\t\t}\n\t}\n#else\n\tQ_UNUSED(outb)\n#endif\n}\n\n#if QT_VERSION < 0x050000\nvoid messageHandler(QtMsgType type, const char* msg)\n{\n\tfprintf(stderr, \"%s\\n\", msg);\n\tfflush(stderr);\n\n\tint level = LOG_DEBUG;\n\n\tswitch (type) {\n\t\tcase QtDebugMsg: level = LOG_DEBUG; break;\n\t\tcase QtWarningMsg: level = LOG_WARNING; break;\n\t\tcase QtCriticalMsg: level = LOG_ERR; break;\n\t\tcase QtFatalMsg: level = LOG_CRIT; break;\n\t}\n\n\tsyslog(level, \"%s\", msg);\n\n\tif (QtFatalMsg == type) {\n\t\ttermination_handler();\n\t}\n}\n#else\nvoid messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg)\n{\n\tQString severity;\n\tint level = LOG_DEBUG;\n\n\tswitch (type) {\n\t\tcase QtDebugMsg:\n\t\t\tseverity = QLatin1String(\"Debug\");\n\t\t\tlevel = LOG_DEBUG;\n\t\t\tbreak;\n\n\t\tcase QtWarningMsg:\n\t\t\tseverity = QLatin1String(\"Warning\");\n\t\t\tlevel = LOG_WARNING;\n\t\t\tbreak;\n\n\t\tcase QtCriticalMsg:\n\t\t\tseverity = QLatin1String(\"Error\");\n\t\t\tlevel = LOG_ERR;\n\t\t\tbreak;\n\n\t\tcase QtFatalMsg:\n\t\t\tseverity = QLatin1String(\"Fatal\");\n\t\t\tlevel = LOG_CRIT;\n\t}\n\n#ifdef DEBUG\n\tQString pattern = QLatin1String(\"%1: %2 (%3:%4, %5)\\n\");\n\tQByteArray message = pattern.arg(severity, msg, QLatin1String(context.file), QString::number(context.line), QLatin1String(context.function)).toLocal8Bit();\n#else\n\tQ_UNUSED(context)\n\tQString pattern = QLatin1String(\"%1: %2\\n\");\n\tQByteArray message = pattern.arg(severity, msg).toLocal8Bit();\n#endif\n\n\tfprintf(stderr, \"%s\", message.constData());\n\tfflush(stderr);\n\n\/\/\tsyslog(level, \"%s\", message.constData());\n\n\tif (QtFatalMsg == type) {\n\t\ttermination_handler();\n\t}\n}\n\n#endif\n\nvoid sigsegv_handler(int)\n{\n\ttermination_handler();\n}\n\nvoid termination_handler(void)\n{\n\tprint_backtrace(stderr);\n\tabort();\n}\nDisable syslog for now#include \n#include \"msghandler.h\"\n#include \n#include \n#include \n#include \n\n#ifdef Q_OS_UNIX\n#\tinclude \n#\tinclude \nstatic void* backtrace_buf[4096];\n#else\n#\tinclude \"win_syslog.h\"\n#endif\n\nvoid print_backtrace(FILE* outb)\n{\n#ifdef Q_OS_UNIX\n\tint stack_size = backtrace(backtrace_buf, sizeof(backtrace_buf)\/sizeof(void*));\n\tchar** stack_symbols = backtrace_symbols(backtrace_buf, stack_size);\n\n\tfprintf(outb, \"Stack [%d]:\\n\", stack_size);\n\tif (FILE* cppfilt = popen(\"\/usr\/bin\/c++filt\", \"rw\")) {\n\t\tdup2(fileno(outb), fileno(cppfilt));\n\t\tfor (int i = stack_size-1; i>=0; --i) {\n\t\t\tfwrite(stack_symbols[i], 1, strlen(stack_symbols[i]), cppfilt);\n\t\t}\n\n\t\tpclose(cppfilt);\n\t}\n\telse {\n\t\tfor (int i = stack_size-1; i>=0; --i) {\n\t\t\tfprintf(outb, \"#%d %p [%s]\\n\", i, backtrace_buf[i], stack_symbols[i]);\n\t\t}\n\t}\n#else\n\tQ_UNUSED(outb)\n#endif\n}\n\n#if QT_VERSION < 0x050000\nvoid messageHandler(QtMsgType type, const char* msg)\n{\n\tfprintf(stderr, \"%s\\n\", msg);\n\tfflush(stderr);\n\n\tint level = LOG_DEBUG;\n\n\tswitch (type) {\n\t\tcase QtDebugMsg: level = LOG_DEBUG; break;\n\t\tcase QtWarningMsg: level = LOG_WARNING; break;\n\t\tcase QtCriticalMsg: level = LOG_ERR; break;\n\t\tcase QtFatalMsg: level = LOG_CRIT; break;\n\t}\n\n\tsyslog(level, \"%s\", msg);\n\n\tif (QtFatalMsg == type) {\n\t\ttermination_handler();\n\t}\n}\n#else\nvoid messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg)\n{\n\tQString severity;\n\/\/\tint level = LOG_DEBUG;\n\n\tswitch (type) {\n\t\tcase QtDebugMsg:\n\t\t\tseverity = QLatin1String(\"Debug\");\n\/\/\t\t\tlevel = LOG_DEBUG;\n\t\t\tbreak;\n\n\t\tcase QtWarningMsg:\n\t\t\tseverity = QLatin1String(\"Warning\");\n\/\/\t\t\tlevel = LOG_WARNING;\n\t\t\tbreak;\n\n\t\tcase QtCriticalMsg:\n\t\t\tseverity = QLatin1String(\"Error\");\n\/\/\t\t\tlevel = LOG_ERR;\n\t\t\tbreak;\n\n\t\tcase QtFatalMsg:\n\t\t\tseverity = QLatin1String(\"Fatal\");\n\/\/\t\t\tlevel = LOG_CRIT;\n\t}\n\n#ifdef DEBUG\n\tQString pattern = QLatin1String(\"%1: %2 (%3:%4, %5)\\n\");\n\tQByteArray message = pattern.arg(severity, msg, QLatin1String(context.file), QString::number(context.line), QLatin1String(context.function)).toLocal8Bit();\n#else\n\tQ_UNUSED(context)\n\tQString pattern = QLatin1String(\"%1: %2\\n\");\n\tQByteArray message = pattern.arg(severity, msg).toLocal8Bit();\n#endif\n\n\tfprintf(stderr, \"%s\", message.constData());\n\tfflush(stderr);\n\n\/\/\tsyslog(level, \"%s\", message.constData());\n\n\tif (QtFatalMsg == type) {\n\t\ttermination_handler();\n\t}\n}\n\n#endif\n\nvoid sigsegv_handler(int)\n{\n\ttermination_handler();\n}\n\nvoid termination_handler(void)\n{\n\tprint_backtrace(stderr);\n\tabort();\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the either Technology Preview License Agreement or the\n** Beta Release License Agreement.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qscriptvalueiterator.h\"\n#include \"qdebug.h\"\n#include \"qtimer.h\"\n#include \"qevent.h\"\n#include \"qdir.h\"\n#include \"qcoreapplication.h\"\n#include \"qfontdatabase.h\"\n#include \"qicon.h\"\n#include \"qurl.h\"\n#include \"qboxlayout.h\"\n#include \"qbasictimer.h\"\n\n#include \"qml.h\"\n#include \"qfxitem.h\"\n#include \"private\/qperformancelog_p.h\"\n#include \"private\/qfxperf_p.h\"\n\n#include \"qfxview.h\"\n#include \n#include \n#include \n\nQT_BEGIN_NAMESPACE\n\nDEFINE_BOOL_CONFIG_OPTION(frameRateDebug, QML_SHOW_FRAMERATE)\n\nstatic QVariant stringToKeySequence(const QString &str)\n{\n return QVariant::fromValue(QKeySequence(str));\n}\n\nclass QFxViewPrivate\n{\npublic:\n QFxViewPrivate(QFxView *w)\n : q(w), root(0), component(0), resizable(false) {}\n\n QFxView *q;\n QFxItem *root;\n\n QUrl source;\n QString qml;\n\n QmlEngine engine;\n QmlComponent *component;\n QBasicTimer resizetimer;\n\n QSize initialSize;\n bool resizable;\n QTime frameTimer;\n\n void init();\n\n QGraphicsScene scene;\n};\n\n\/*!\n \\class QFxView\n \\brief The QFxView class provides a widget for displaying a Qt Declarative user interface.\n\n QFxView currently provides a minimal interface for displaying QML\n files, and connecting between QML and C++ Qt objects.\n\n Typical usage:\n \\code\n ...\n QFxView *view = new QFxView(this);\n vbox->addWidget(view);\n\n QUrl url(fileName);\n view->setUrl(url);\n ...\n view->execute();\n ...\n \\endcode\n*\/\n\n\/*!\n \\fn QFxView::QFxView(QWidget *parent)\n \n Constructs a QFxView with the given \\a parent.\n*\/\nQFxView::QFxView(QWidget *parent)\n: QGraphicsView(parent), d(new QFxViewPrivate(this))\n{\n setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);\n d->init();\n}\n\nvoid QFxViewPrivate::init()\n{\n \/\/ XXX: These need to be put in a central location for this kind of thing\n QmlMetaType::registerCustomStringConverter(QVariant::KeySequence, &stringToKeySequence);\n\n#ifdef Q_ENABLE_PERFORMANCE_LOG\n QFxPerfTimer perf;\n#endif\n QFontDatabase database;\n\n q->setScene(&scene);\n\n q->setOptimizationFlags(QGraphicsView::DontSavePainterState);\n q->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n q->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n q->setFrameStyle(0);\n\n \/\/ These seem to give the best performance\n q->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);\n scene.setItemIndexMethod(QGraphicsScene::NoIndex);\n q->viewport()->setFocusPolicy(Qt::NoFocus);\n\n scene.setStickyFocus(true); \/\/### needed for correct focus handling\n}\n\n\/*!\n The destructor clears the view's \\l {QFxItem} {items} and\n deletes the internal representation.\n\n \\sa clearItems()\n *\/\nQFxView::~QFxView()\n{\n clearItems();\n delete d; d = 0;\n}\n\n\/*!\n Sets the source to the \\a url. The QML string is set to\n empty.\n *\/\nvoid QFxView::setUrl(const QUrl& url)\n{\n d->source = url;\n d->qml = QString();\n}\n\n\/*!\n Sets the source to the URL from the \\a filename, and sets\n the QML string to \\a qml.\n *\/\nvoid QFxView::setQml(const QString &qml, const QString &filename)\n{\n d->source = QUrl::fromLocalFile(filename);\n d->qml = qml;\n}\n\n\/*!\n Returns the QML string.\n *\/\nQString QFxView::qml() const\n{\n return d->qml;\n}\n\n\/*!\n Returns a pointer to the QmlEngine used for instantiating\n QML Components.\n *\/\nQmlEngine* QFxView::engine()\n{\n return &d->engine;\n}\n\n\/*!\n This function returns the root of the context hierarchy. Each QML\n component is instantiated in a QmlContext. QmlContext's are\n essential for passing data to QML components. In QML, contexts are\n arranged hierarchically and this hierarchy is managed by the\n QmlEngine.\n *\/\nQmlContext* QFxView::rootContext()\n{\n return d->engine.rootContext();\n}\n\n\/*!\n Displays the Qt Declarative user interface.\n*\/\nvoid QFxView::execute()\n{\n if (d->qml.isEmpty()) {\n d->component = new QmlComponent(&d->engine, d->source, this);\n } else {\n d->component = new QmlComponent(&d->engine, d->qml.toUtf8(), d->source);\n }\n\n if (!d->component->isLoading()) {\n continueExecute();\n } else {\n connect(d->component, SIGNAL(statusChanged(QmlComponent::Status)), this, SLOT(continueExecute()));\n }\n}\n\n\n\/*!\n \\internal\n *\/\nvoid QFxView::continueExecute()\n{\n disconnect(d->component, SIGNAL(statusChanged(QmlComponent::Status)), this, SLOT(continueExecute()));\n\n if (!d->component) {\n qWarning() << \"Error in loading\" << d->source;\n return;\n }\n\n if(d->component->isError()) {\n QList errorList = d->component->errors();\n emit errors(errorList);\n foreach (const QmlError &error, errorList) {\n qWarning() << error;\n }\n\n return;\n }\n\n QObject *obj = d->component->create();\n\n if(d->component->isError()) {\n QList errorList = d->component->errors();\n emit errors(errorList);\n foreach (const QmlError &error, errorList) {\n qWarning() << error;\n }\n\n return;\n }\n\n if (obj) {\n if (QFxItem *item = qobject_cast(obj)) {\n\n d->scene.addItem(item);\n\n QPerformanceLog::displayData();\n QPerformanceLog::clear();\n d->root = item;\n connect(item, SIGNAL(widthChanged()), this, SLOT(sizeChanged()));\n connect(item, SIGNAL(heightChanged()), this, SLOT(sizeChanged()));\n if (d->initialSize.height() <= 0 && d->root->width() > 0)\n d->initialSize.setWidth(d->root->width());\n if (d->initialSize.height() <= 0 && d->root->height() > 0)\n d->initialSize.setHeight(d->root->height());\n if (d->resizable) {\n d->root->setWidth(width());\n d->root->setHeight(height());\n } else {\n QSize sz(d->root->width(),d->root->height());\n emit sceneResized(sz);\n resize(sz);\n }\n } else if (QWidget *wid = qobject_cast(obj)) {\n window()->setAttribute(Qt::WA_OpaquePaintEvent, false);\n window()->setAttribute(Qt::WA_NoSystemBackground, false);\n if (!layout()) {\n setLayout(new QVBoxLayout);\n } else if (layout()->count()) {\n \/\/ Hide the QGraphicsView in GV mode.\n QLayoutItem *item = layout()->itemAt(0);\n if (item->widget())\n item->widget()->hide();\n }\n layout()->addWidget(wid);\n emit sceneResized(wid->size());\n }\n }\n}\n\n\/*! \\fn void QFxView::sceneResized(QSize size)\n This signal is emitted when the view is resized to \\a size.\n *\/\n\n\/*! \\fn void QFxView::errors(const QList &errors)\n This signal is emitted when the qml loaded contains \\a errors.\n *\/\n\n\/*!\n \\internal\n *\/\nvoid QFxView::sizeChanged()\n{\n \/\/ delay, so we catch both width and height changing.\n d->resizetimer.start(0,this);\n}\n\n\/*!\n If the \\l {QTimerEvent} {timer event} \\a e is this\n view's resize timer, sceneResized() is emitted.\n *\/\nvoid QFxView::timerEvent(QTimerEvent* e)\n{\n if (!e || e->timerId() == d->resizetimer.timerId()) {\n if (d->root) {\n QSize sz(d->root->width(),d->root->height());\n emit sceneResized(sz);\n \/\/if (!d->resizable)\n \/\/resize(sz);\n }\n d->resizetimer.stop();\n updateGeometry();\n }\n}\n\n\/\/ modelled on QScrollArea::widgetResizable\n\/*!\n \\property QFxView::contentResizable\n \\brief whether the view should resize the canvas contents\n\n If this property is set to false (the default), the view\n resizes with the root item in the QML.\n\n If this property is set to true, the view will\n automatically resize the root item.\n\n Regardless of this property, the sizeHint of the view\n is the initial size of the root item.\n*\/\n\nvoid QFxView::setContentResizable(bool on)\n{\n if (d->resizable != on) {\n d->resizable = on;\n if (d->root) {\n if (on) {\n d->root->setWidth(width());\n d->root->setHeight(height());\n } else {\n d->root->setWidth(d->initialSize.width());\n d->root->setHeight(d->initialSize.height());\n }\n }\n }\n}\n\nbool QFxView::contentResizable() const\n{\n return d->resizable;\n}\n\n\n\/*!\n The size hint is the size of the root item.\n*\/\nQSize QFxView::sizeHint() const\n{\n if (d->root) {\n if (d->initialSize.width() <= 0)\n d->initialSize.setWidth(d->root->width());\n if (d->initialSize.height() <= 0)\n d->initialSize.setHeight(d->root->height());\n }\n return d->initialSize;\n}\n\n\/*!\n Creates a \\l{QmlComponent} {component} from the \\a qml\n string, and returns it as an \\l {QFxItem} {item}. If the\n \\a parent item is provided, it becomes the new item's\n parent. \\a parent should be in this view's item hierarchy.\n *\/\nQFxItem* QFxView::addItem(const QString &qml, QFxItem* parent)\n{\n if (!d->root)\n return 0;\n\n QmlComponent component(&d->engine, qml.toUtf8(), QUrl());\n if(d->component->isError()) {\n QList errorList = d->component->errors();\n emit errors(errorList);\n foreach (const QmlError &error, errorList) {\n qWarning() << error;\n }\n\n return 0;\n }\n\n QObject *obj = component.create();\n if(d->component->isError()) {\n QList errorList = d->component->errors();\n emit errors(errorList);\n foreach (const QmlError &error, errorList) {\n qWarning() << error;\n }\n\n return 0;\n }\n\n if (obj){\n QFxItem *item = static_cast(obj);\n if (!parent)\n parent = d->root;\n\n item->setParentItem(parent);\n return item;\n }\n return 0;\n}\n\n\/*!\n Deletes the view's \\l {QFxItem} {items} and the \\l {QmlEngine}\n {QML engine's} Component cache.\n *\/\nvoid QFxView::reset()\n{\n clearItems();\n d->engine.clearComponentCache();\n d->initialSize = QSize();\n}\n\n\/*!\n Deletes the view's \\l {QFxItem} {items}.\n *\/\nvoid QFxView::clearItems()\n{\n if (!d->root)\n return;\n delete d->root;\n d->root = 0;\n}\n\n\/*!\n Returns the view's root \\l {QFxItem} {item}.\n *\/\nQFxItem *QFxView::root() const\n{\n return d->root;\n}\n\n\/*!\n This function handles the \\l {QResizeEvent} {resize event}\n \\a e.\n *\/\nvoid QFxView::resizeEvent(QResizeEvent *e)\n{\n if (d->resizable && d->root) {\n d->root->setWidth(width());\n d->root->setHeight(height());\n }\n setSceneRect(rect());\n QGraphicsView::resizeEvent(e);\n}\n\n\/*!\n \\reimp\n*\/\nvoid QFxView::paintEvent(QPaintEvent *event)\n{\n int time = 0;\n if (frameRateDebug())\n time = d->frameTimer.restart();\n QGraphicsView::paintEvent(event);\n if (frameRateDebug())\n qDebug() << \"paintEvent:\" << d->frameTimer.elapsed() << \"time since last frame:\" << time;\n}\n\n\/*! \\fn void QFxView::focusInEvent(QFocusEvent *e)\n This virtual function does nothing with the event \\a e\n in this class.\n *\/\nvoid QFxView::focusInEvent(QFocusEvent *)\n{\n \/\/ Do nothing (do not call QWidget::update())\n}\n\n\n\/*! \\fn void QFxView::focusOutEvent(QFocusEvent *e)\n This virtual function does nothing with the event \\a e\n in this class.\n *\/\nvoid QFxView::focusOutEvent(QFocusEvent *)\n{\n \/\/ Do nothing (do not call QWidget::update())\n}\n\nQT_END_NAMESPACE\nFixing layout margins for QWidgets in QFxView\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the either Technology Preview License Agreement or the\n** Beta Release License Agreement.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qscriptvalueiterator.h\"\n#include \"qdebug.h\"\n#include \"qtimer.h\"\n#include \"qevent.h\"\n#include \"qdir.h\"\n#include \"qcoreapplication.h\"\n#include \"qfontdatabase.h\"\n#include \"qicon.h\"\n#include \"qurl.h\"\n#include \"qboxlayout.h\"\n#include \"qbasictimer.h\"\n\n#include \"qml.h\"\n#include \"qfxitem.h\"\n#include \"private\/qperformancelog_p.h\"\n#include \"private\/qfxperf_p.h\"\n\n#include \"qfxview.h\"\n#include \n#include \n#include \n\nQT_BEGIN_NAMESPACE\n\nDEFINE_BOOL_CONFIG_OPTION(frameRateDebug, QML_SHOW_FRAMERATE)\n\nstatic QVariant stringToKeySequence(const QString &str)\n{\n return QVariant::fromValue(QKeySequence(str));\n}\n\nclass QFxViewPrivate\n{\npublic:\n QFxViewPrivate(QFxView *w)\n : q(w), root(0), component(0), resizable(false) {}\n\n QFxView *q;\n QFxItem *root;\n\n QUrl source;\n QString qml;\n\n QmlEngine engine;\n QmlComponent *component;\n QBasicTimer resizetimer;\n\n QSize initialSize;\n bool resizable;\n QTime frameTimer;\n\n void init();\n\n QGraphicsScene scene;\n};\n\n\/*!\n \\class QFxView\n \\brief The QFxView class provides a widget for displaying a Qt Declarative user interface.\n\n QFxView currently provides a minimal interface for displaying QML\n files, and connecting between QML and C++ Qt objects.\n\n Typical usage:\n \\code\n ...\n QFxView *view = new QFxView(this);\n vbox->addWidget(view);\n\n QUrl url(fileName);\n view->setUrl(url);\n ...\n view->execute();\n ...\n \\endcode\n*\/\n\n\/*!\n \\fn QFxView::QFxView(QWidget *parent)\n \n Constructs a QFxView with the given \\a parent.\n*\/\nQFxView::QFxView(QWidget *parent)\n: QGraphicsView(parent), d(new QFxViewPrivate(this))\n{\n setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);\n d->init();\n}\n\nvoid QFxViewPrivate::init()\n{\n \/\/ XXX: These need to be put in a central location for this kind of thing\n QmlMetaType::registerCustomStringConverter(QVariant::KeySequence, &stringToKeySequence);\n\n#ifdef Q_ENABLE_PERFORMANCE_LOG\n QFxPerfTimer perf;\n#endif\n QFontDatabase database;\n\n q->setScene(&scene);\n\n q->setOptimizationFlags(QGraphicsView::DontSavePainterState);\n q->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n q->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n q->setFrameStyle(0);\n\n \/\/ These seem to give the best performance\n q->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);\n scene.setItemIndexMethod(QGraphicsScene::NoIndex);\n q->viewport()->setFocusPolicy(Qt::NoFocus);\n\n scene.setStickyFocus(true); \/\/### needed for correct focus handling\n}\n\n\/*!\n The destructor clears the view's \\l {QFxItem} {items} and\n deletes the internal representation.\n\n \\sa clearItems()\n *\/\nQFxView::~QFxView()\n{\n clearItems();\n delete d; d = 0;\n}\n\n\/*!\n Sets the source to the \\a url. The QML string is set to\n empty.\n *\/\nvoid QFxView::setUrl(const QUrl& url)\n{\n d->source = url;\n d->qml = QString();\n}\n\n\/*!\n Sets the source to the URL from the \\a filename, and sets\n the QML string to \\a qml.\n *\/\nvoid QFxView::setQml(const QString &qml, const QString &filename)\n{\n d->source = QUrl::fromLocalFile(filename);\n d->qml = qml;\n}\n\n\/*!\n Returns the QML string.\n *\/\nQString QFxView::qml() const\n{\n return d->qml;\n}\n\n\/*!\n Returns a pointer to the QmlEngine used for instantiating\n QML Components.\n *\/\nQmlEngine* QFxView::engine()\n{\n return &d->engine;\n}\n\n\/*!\n This function returns the root of the context hierarchy. Each QML\n component is instantiated in a QmlContext. QmlContext's are\n essential for passing data to QML components. In QML, contexts are\n arranged hierarchically and this hierarchy is managed by the\n QmlEngine.\n *\/\nQmlContext* QFxView::rootContext()\n{\n return d->engine.rootContext();\n}\n\n\/*!\n Displays the Qt Declarative user interface.\n*\/\nvoid QFxView::execute()\n{\n if (d->qml.isEmpty()) {\n d->component = new QmlComponent(&d->engine, d->source, this);\n } else {\n d->component = new QmlComponent(&d->engine, d->qml.toUtf8(), d->source);\n }\n\n if (!d->component->isLoading()) {\n continueExecute();\n } else {\n connect(d->component, SIGNAL(statusChanged(QmlComponent::Status)), this, SLOT(continueExecute()));\n }\n}\n\n\n\/*!\n \\internal\n *\/\nvoid QFxView::continueExecute()\n{\n disconnect(d->component, SIGNAL(statusChanged(QmlComponent::Status)), this, SLOT(continueExecute()));\n\n if (!d->component) {\n qWarning() << \"Error in loading\" << d->source;\n return;\n }\n\n if(d->component->isError()) {\n QList errorList = d->component->errors();\n emit errors(errorList);\n foreach (const QmlError &error, errorList) {\n qWarning() << error;\n }\n\n return;\n }\n\n QObject *obj = d->component->create();\n\n if(d->component->isError()) {\n QList errorList = d->component->errors();\n emit errors(errorList);\n foreach (const QmlError &error, errorList) {\n qWarning() << error;\n }\n\n return;\n }\n\n if (obj) {\n if (QFxItem *item = qobject_cast(obj)) {\n\n d->scene.addItem(item);\n\n QPerformanceLog::displayData();\n QPerformanceLog::clear();\n d->root = item;\n connect(item, SIGNAL(widthChanged()), this, SLOT(sizeChanged()));\n connect(item, SIGNAL(heightChanged()), this, SLOT(sizeChanged()));\n if (d->initialSize.height() <= 0 && d->root->width() > 0)\n d->initialSize.setWidth(d->root->width());\n if (d->initialSize.height() <= 0 && d->root->height() > 0)\n d->initialSize.setHeight(d->root->height());\n if (d->resizable) {\n d->root->setWidth(width());\n d->root->setHeight(height());\n } else {\n QSize sz(d->root->width(),d->root->height());\n emit sceneResized(sz);\n resize(sz);\n }\n } else if (QWidget *wid = qobject_cast(obj)) {\n window()->setAttribute(Qt::WA_OpaquePaintEvent, false);\n window()->setAttribute(Qt::WA_NoSystemBackground, false);\n if (!layout()) {\n setLayout(new QVBoxLayout);\n layout()->setContentsMargins(0, 0, 0, 0);\n } else if (layout()->count()) {\n \/\/ Hide the QGraphicsView in GV mode.\n QLayoutItem *item = layout()->itemAt(0);\n if (item->widget())\n item->widget()->hide();\n }\n layout()->addWidget(wid);\n emit sceneResized(wid->size());\n }\n }\n}\n\n\/*! \\fn void QFxView::sceneResized(QSize size)\n This signal is emitted when the view is resized to \\a size.\n *\/\n\n\/*! \\fn void QFxView::errors(const QList &errors)\n This signal is emitted when the qml loaded contains \\a errors.\n *\/\n\n\/*!\n \\internal\n *\/\nvoid QFxView::sizeChanged()\n{\n \/\/ delay, so we catch both width and height changing.\n d->resizetimer.start(0,this);\n}\n\n\/*!\n If the \\l {QTimerEvent} {timer event} \\a e is this\n view's resize timer, sceneResized() is emitted.\n *\/\nvoid QFxView::timerEvent(QTimerEvent* e)\n{\n if (!e || e->timerId() == d->resizetimer.timerId()) {\n if (d->root) {\n QSize sz(d->root->width(),d->root->height());\n emit sceneResized(sz);\n \/\/if (!d->resizable)\n \/\/resize(sz);\n }\n d->resizetimer.stop();\n updateGeometry();\n }\n}\n\n\/\/ modelled on QScrollArea::widgetResizable\n\/*!\n \\property QFxView::contentResizable\n \\brief whether the view should resize the canvas contents\n\n If this property is set to false (the default), the view\n resizes with the root item in the QML.\n\n If this property is set to true, the view will\n automatically resize the root item.\n\n Regardless of this property, the sizeHint of the view\n is the initial size of the root item.\n*\/\n\nvoid QFxView::setContentResizable(bool on)\n{\n if (d->resizable != on) {\n d->resizable = on;\n if (d->root) {\n if (on) {\n d->root->setWidth(width());\n d->root->setHeight(height());\n } else {\n d->root->setWidth(d->initialSize.width());\n d->root->setHeight(d->initialSize.height());\n }\n }\n }\n}\n\nbool QFxView::contentResizable() const\n{\n return d->resizable;\n}\n\n\n\/*!\n The size hint is the size of the root item.\n*\/\nQSize QFxView::sizeHint() const\n{\n if (d->root) {\n if (d->initialSize.width() <= 0)\n d->initialSize.setWidth(d->root->width());\n if (d->initialSize.height() <= 0)\n d->initialSize.setHeight(d->root->height());\n }\n return d->initialSize;\n}\n\n\/*!\n Creates a \\l{QmlComponent} {component} from the \\a qml\n string, and returns it as an \\l {QFxItem} {item}. If the\n \\a parent item is provided, it becomes the new item's\n parent. \\a parent should be in this view's item hierarchy.\n *\/\nQFxItem* QFxView::addItem(const QString &qml, QFxItem* parent)\n{\n if (!d->root)\n return 0;\n\n QmlComponent component(&d->engine, qml.toUtf8(), QUrl());\n if(d->component->isError()) {\n QList errorList = d->component->errors();\n emit errors(errorList);\n foreach (const QmlError &error, errorList) {\n qWarning() << error;\n }\n\n return 0;\n }\n\n QObject *obj = component.create();\n if(d->component->isError()) {\n QList errorList = d->component->errors();\n emit errors(errorList);\n foreach (const QmlError &error, errorList) {\n qWarning() << error;\n }\n\n return 0;\n }\n\n if (obj){\n QFxItem *item = static_cast(obj);\n if (!parent)\n parent = d->root;\n\n item->setParentItem(parent);\n return item;\n }\n return 0;\n}\n\n\/*!\n Deletes the view's \\l {QFxItem} {items} and the \\l {QmlEngine}\n {QML engine's} Component cache.\n *\/\nvoid QFxView::reset()\n{\n clearItems();\n d->engine.clearComponentCache();\n d->initialSize = QSize();\n}\n\n\/*!\n Deletes the view's \\l {QFxItem} {items}.\n *\/\nvoid QFxView::clearItems()\n{\n if (!d->root)\n return;\n delete d->root;\n d->root = 0;\n}\n\n\/*!\n Returns the view's root \\l {QFxItem} {item}.\n *\/\nQFxItem *QFxView::root() const\n{\n return d->root;\n}\n\n\/*!\n This function handles the \\l {QResizeEvent} {resize event}\n \\a e.\n *\/\nvoid QFxView::resizeEvent(QResizeEvent *e)\n{\n if (d->resizable && d->root) {\n d->root->setWidth(width());\n d->root->setHeight(height());\n }\n setSceneRect(rect());\n QGraphicsView::resizeEvent(e);\n}\n\n\/*!\n \\reimp\n*\/\nvoid QFxView::paintEvent(QPaintEvent *event)\n{\n int time = 0;\n if (frameRateDebug())\n time = d->frameTimer.restart();\n QGraphicsView::paintEvent(event);\n if (frameRateDebug())\n qDebug() << \"paintEvent:\" << d->frameTimer.elapsed() << \"time since last frame:\" << time;\n}\n\n\/*! \\fn void QFxView::focusInEvent(QFocusEvent *e)\n This virtual function does nothing with the event \\a e\n in this class.\n *\/\nvoid QFxView::focusInEvent(QFocusEvent *)\n{\n \/\/ Do nothing (do not call QWidget::update())\n}\n\n\n\/*! \\fn void QFxView::focusOutEvent(QFocusEvent *e)\n This virtual function does nothing with the event \\a e\n in this class.\n *\/\nvoid QFxView::focusOutEvent(QFocusEvent *)\n{\n \/\/ Do nothing (do not call QWidget::update())\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014-2018 The Dash Core developers\n\/\/ Copyright (c) 2014-2018 The Machinecoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/ Keep track of the active Masternode\nCActiveMasternode activeMasternode;\n\nvoid CActiveMasternode::ManageState(CConnman& connman)\n{\n LogPrint(MCLog::MN, \"CActiveMasternode::ManageState -- Start\\n\");\n if(!fMasterNode) {\n LogPrint(MCLog::MN, \"CActiveMasternode::ManageState -- Not a masternode, returning\\n\");\n return;\n }\n\n if(Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) {\n nState = ACTIVE_MASTERNODE_SYNC_IN_PROCESS;\n LogPrintf(\"CActiveMasternode::ManageState -- %s: %s\\n\", GetStateString(), GetStatus());\n return;\n }\n\n if(nState == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) {\n nState = ACTIVE_MASTERNODE_INITIAL;\n }\n\n LogPrint(MCLog::MN, \"CActiveMasternode::ManageState -- status = %s, type = %s, pinger enabled = %d\\n\", GetStatus(), GetTypeString(), fPingerEnabled);\n\n if(eType == MASTERNODE_UNKNOWN) {\n ManageStateInitial(connman);\n }\n\n if(eType == MASTERNODE_REMOTE) {\n ManageStateRemote();\n }\n\n SendMasternodePing(connman);\n}\n\nstd::string CActiveMasternode::GetStateString() const\n{\n switch (nState) {\n case ACTIVE_MASTERNODE_INITIAL: return \"INITIAL\";\n case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return \"SYNC_IN_PROCESS\";\n case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return \"INPUT_TOO_NEW\";\n case ACTIVE_MASTERNODE_NOT_CAPABLE: return \"NOT_CAPABLE\";\n case ACTIVE_MASTERNODE_STARTED: return \"STARTED\";\n default: return \"UNKNOWN\";\n }\n}\n\nstd::string CActiveMasternode::GetStatus() const\n{\n switch (nState) {\n case ACTIVE_MASTERNODE_INITIAL: return \"Node just started, not yet activated\";\n case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return \"Sync in progress. Must wait until sync is complete to start Masternode\";\n case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return strprintf(\"Masternode input must have at least %d confirmations\", Params().GetConsensus().nMasternodeMinimumConfirmations);\n case ACTIVE_MASTERNODE_NOT_CAPABLE: return \"Not capable masternode: \" + strNotCapableReason;\n case ACTIVE_MASTERNODE_STARTED: return \"Masternode successfully started\";\n default: return \"Unknown\";\n }\n}\n\nstd::string CActiveMasternode::GetTypeString() const\n{\n std::string strType;\n switch(eType) {\n case MASTERNODE_REMOTE:\n strType = \"REMOTE\";\n break;\n default:\n strType = \"UNKNOWN\";\n break;\n }\n return strType;\n}\n\nbool CActiveMasternode::SendMasternodePing(CConnman& connman)\n{\n if(!fPingerEnabled) {\n LogPrint(MCLog::MN, \"CActiveMasternode::SendMasternodePing -- %s: masternode ping service is disabled, skipping...\\n\", GetStateString());\n return false;\n }\n\n if(!mnodeman.Has(outpoint)) {\n strNotCapableReason = \"Masternode not in masternode list\";\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n LogPrintf(\"CActiveMasternode::SendMasternodePing -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return false;\n }\n\n CMasternodePing mnp(outpoint);\n mnp.nSentinelVersion = nSentinelVersion;\n mnp.fSentinelIsCurrent =\n (abs(GetAdjustedTime() - nSentinelPingTime) < MASTERNODE_WATCHDOG_MAX_SECONDS);\n if(!mnp.Sign(keyMasternode, pubKeyMasternode)) {\n LogPrintf(\"CActiveMasternode::SendMasternodePing -- ERROR: Couldn't sign Masternode Ping\\n\");\n return false;\n }\n\n \/\/ Update lastPing for our masternode in Masternode list\n if(mnodeman.IsMasternodePingedWithin(outpoint, MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) {\n LogPrintf(\"CActiveMasternode::SendMasternodePing -- Too early to send Masternode Ping\\n\");\n return false;\n }\n\n mnodeman.SetMasternodeLastPing(outpoint, mnp);\n\n LogPrintf(\"CActiveMasternode::SendMasternodePing -- Relaying ping, collateral=%s\\n\", outpoint.ToStringShort());\n mnp.Relay(connman);\n\n return true;\n}\n\nbool CActiveMasternode::UpdateSentinelPing(int version)\n{\n nSentinelVersion = version;\n nSentinelPingTime = GetAdjustedTime();\n\n return true;\n}\n\nvoid CActiveMasternode::ManageStateInitial(CConnman& connman)\n{\n LogPrint(MCLog::MN, \"CActiveMasternode::ManageStateInitial -- status = %s, type = %s, pinger enabled = %d\\n\", GetStatus(), GetTypeString(), fPingerEnabled);\n\n \/\/ Check that our local network configuration is correct\n if (!fListen) {\n \/\/ listen option is probably overwritten by smth else, no good\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = \"Masternode must accept connections from outside. Make sure listen configuration option is not overwritten by some another parameter.\";\n LogPrintf(\"CActiveMasternode::ManageStateInitial -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n\n \/\/ First try to find whatever local address is specified by externalip option\n bool fFoundLocal = GetLocal(service) && CMasternode::IsValidNetAddr(service);\n if(!fFoundLocal) {\n bool empty = true;\n \/\/ If we have some peers, let's try to find our local address from one of them\n connman.ForEachNodeContinueIf(CConnman::AllNodes, [&fFoundLocal, &empty, this](CNode* pnode) {\n empty = false;\n if (pnode->addr.IsIPv4())\n fFoundLocal = GetLocal(service, &pnode->addr) && CMasternode::IsValidNetAddr(service);\n return !fFoundLocal;\n });\n \/\/ nothing and no live connections, can't do anything for now\n if (empty) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = \"Can't detect valid external address. Will retry when there are some connections available.\";\n LogPrintf(\"CActiveMasternode::ManageStateInitial -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n }\n\n if(!fFoundLocal) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = \"Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only.\";\n LogPrintf(\"CActiveMasternode::ManageStateInitial -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n\n const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN).GetDefaultPort();\n if(Params().NetworkIDString() == CBaseChainParams::MAIN) {\n if(service.GetPort() != mainnetDefaultPort) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = strprintf(\"Invalid port: %u - only %d is supported on mainnet.\", service.GetPort(), mainnetDefaultPort);\n LogPrintf(\"CActiveMasternode::ManageStateInitial -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n } else if(service.GetPort() == mainnetDefaultPort) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = strprintf(\"Invalid port: %u - %d is only supported on mainnet.\", service.GetPort(), mainnetDefaultPort);\n LogPrintf(\"CActiveMasternode::ManageStateInitial -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n\n LogPrintf(\"CActiveMasternode::ManageStateInitial -- Checking inbound connection to '%s'\\n\", service.ToString());\n\n if(!connman.ConnectNode(CAddress(service, NODE_NETWORK), NULL, false, true)) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = \"Could not connect to \" + service.ToString();\n LogPrintf(\"CActiveMasternode::ManageStateInitial -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n\n \/\/ Default to REMOTE\n eType = MASTERNODE_REMOTE;\n\n LogPrint(MCLog::MN, \"CActiveMasternode::ManageStateInitial -- End status = %s, type = %s, pinger enabled = %d\\n\", GetStatus(), GetTypeString(), fPingerEnabled);\n}\n\nvoid CActiveMasternode::ManageStateRemote()\n{\n LogPrint(MCLog::MN, \"CActiveMasternode::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, pubKeyMasternode.GetID() = %s\\n\", \n GetStatus(), GetTypeString(), fPingerEnabled, pubKeyMasternode.GetID().ToString());\n\n mnodeman.CheckMasternode(pubKeyMasternode, true);\n masternode_info_t infoMn;\n if(mnodeman.GetMasternodeInfo(pubKeyMasternode, infoMn)) {\n if(infoMn.nProtocolVersion != PROTOCOL_VERSION) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = \"Invalid protocol version\";\n LogPrintf(\"CActiveMasternode::ManageStateRemote -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n if(service != infoMn.addr) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = \"Broadcasted IP doesn't match our external address. Make sure you issued a new broadcast if IP of this masternode changed recently.\";\n LogPrintf(\"CActiveMasternode::ManageStateRemote -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n if(!CMasternode::IsValidStateForAutoStart(infoMn.nActiveState)) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = strprintf(\"Masternode in %s state\", CMasternode::StateToString(infoMn.nActiveState));\n LogPrintf(\"CActiveMasternode::ManageStateRemote -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n if(nState != ACTIVE_MASTERNODE_STARTED) {\n LogPrintf(\"CActiveMasternode::ManageStateRemote -- STARTED!\\n\");\n outpoint = infoMn.vin.prevout;\n service = infoMn.addr;\n fPingerEnabled = true;\n nState = ACTIVE_MASTERNODE_STARTED;\n }\n }\n else {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = \"Masternode not in masternode list\";\n LogPrintf(\"CActiveMasternode::ManageStateRemote -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n }\n}use newer syntax\/\/ Copyright (c) 2014-2018 The Dash Core developers\n\/\/ Copyright (c) 2014-2018 The Machinecoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/ Keep track of the active Masternode\nCActiveMasternode activeMasternode;\n\nvoid CActiveMasternode::ManageState(CConnman& connman)\n{\n LogPrint(MCLog::MN, \"CActiveMasternode::ManageState -- Start\\n\");\n if(!fMasterNode) {\n LogPrint(MCLog::MN, \"CActiveMasternode::ManageState -- Not a masternode, returning\\n\");\n return;\n }\n\n if(Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) {\n nState = ACTIVE_MASTERNODE_SYNC_IN_PROCESS;\n LogPrintf(\"CActiveMasternode::ManageState -- %s: %s\\n\", GetStateString(), GetStatus());\n return;\n }\n\n if(nState == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) {\n nState = ACTIVE_MASTERNODE_INITIAL;\n }\n\n LogPrint(MCLog::MN, \"CActiveMasternode::ManageState -- status = %s, type = %s, pinger enabled = %d\\n\", GetStatus(), GetTypeString(), fPingerEnabled);\n\n if(eType == MASTERNODE_UNKNOWN) {\n ManageStateInitial(connman);\n }\n\n if(eType == MASTERNODE_REMOTE) {\n ManageStateRemote();\n }\n\n SendMasternodePing(connman);\n}\n\nstd::string CActiveMasternode::GetStateString() const\n{\n switch (nState) {\n case ACTIVE_MASTERNODE_INITIAL: return \"INITIAL\";\n case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return \"SYNC_IN_PROCESS\";\n case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return \"INPUT_TOO_NEW\";\n case ACTIVE_MASTERNODE_NOT_CAPABLE: return \"NOT_CAPABLE\";\n case ACTIVE_MASTERNODE_STARTED: return \"STARTED\";\n default: return \"UNKNOWN\";\n }\n}\n\nstd::string CActiveMasternode::GetStatus() const\n{\n switch (nState) {\n case ACTIVE_MASTERNODE_INITIAL: return \"Node just started, not yet activated\";\n case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return \"Sync in progress. Must wait until sync is complete to start Masternode\";\n case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return strprintf(\"Masternode input must have at least %d confirmations\", Params().GetConsensus().nMasternodeMinimumConfirmations);\n case ACTIVE_MASTERNODE_NOT_CAPABLE: return \"Not capable masternode: \" + strNotCapableReason;\n case ACTIVE_MASTERNODE_STARTED: return \"Masternode successfully started\";\n default: return \"Unknown\";\n }\n}\n\nstd::string CActiveMasternode::GetTypeString() const\n{\n std::string strType;\n switch(eType) {\n case MASTERNODE_REMOTE:\n strType = \"REMOTE\";\n break;\n default:\n strType = \"UNKNOWN\";\n break;\n }\n return strType;\n}\n\nbool CActiveMasternode::SendMasternodePing(CConnman& connman)\n{\n if(!fPingerEnabled) {\n LogPrint(MCLog::MN, \"CActiveMasternode::SendMasternodePing -- %s: masternode ping service is disabled, skipping...\\n\", GetStateString());\n return false;\n }\n\n if(!mnodeman.Has(outpoint)) {\n strNotCapableReason = \"Masternode not in masternode list\";\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n LogPrintf(\"CActiveMasternode::SendMasternodePing -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return false;\n }\n\n CMasternodePing mnp(outpoint);\n mnp.nSentinelVersion = nSentinelVersion;\n mnp.fSentinelIsCurrent =\n (abs(GetAdjustedTime() - nSentinelPingTime) < MASTERNODE_WATCHDOG_MAX_SECONDS);\n if(!mnp.Sign(keyMasternode, pubKeyMasternode)) {\n LogPrintf(\"CActiveMasternode::SendMasternodePing -- ERROR: Couldn't sign Masternode Ping\\n\");\n return false;\n }\n\n \/\/ Update lastPing for our masternode in Masternode list\n if(mnodeman.IsMasternodePingedWithin(outpoint, MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) {\n LogPrintf(\"CActiveMasternode::SendMasternodePing -- Too early to send Masternode Ping\\n\");\n return false;\n }\n\n mnodeman.SetMasternodeLastPing(outpoint, mnp);\n\n LogPrintf(\"CActiveMasternode::SendMasternodePing -- Relaying ping, collateral=%s\\n\", outpoint.ToStringShort());\n mnp.Relay(connman);\n\n return true;\n}\n\nbool CActiveMasternode::UpdateSentinelPing(int version)\n{\n nSentinelVersion = version;\n nSentinelPingTime = GetAdjustedTime();\n\n return true;\n}\n\nvoid CActiveMasternode::ManageStateInitial(CConnman& connman)\n{\n LogPrint(MCLog::MN, \"CActiveMasternode::ManageStateInitial -- status = %s, type = %s, pinger enabled = %d\\n\", GetStatus(), GetTypeString(), fPingerEnabled);\n\n \/\/ Check that our local network configuration is correct\n if (!fListen) {\n \/\/ listen option is probably overwritten by smth else, no good\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = \"Masternode must accept connections from outside. Make sure listen configuration option is not overwritten by some another parameter.\";\n LogPrintf(\"CActiveMasternode::ManageStateInitial -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n\n \/\/ First try to find whatever local address is specified by externalip option\n bool fFoundLocal = GetLocal(service) && CMasternode::IsValidNetAddr(service);\n if(!fFoundLocal) {\n bool empty = true;\n \/\/ If we have some peers, let's try to find our local address from one of them\n connman.ForEachNodeContinueIf(CConnman::AllNodes, [&fFoundLocal, &empty, this](CNode* pnode) {\n empty = false;\n if (pnode->addr.IsIPv4())\n fFoundLocal = GetLocal(service, &pnode->addr) && CMasternode::IsValidNetAddr(service);\n return !fFoundLocal;\n });\n \/\/ nothing and no live connections, can't do anything for now\n if (empty) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = \"Can't detect valid external address. Will retry when there are some connections available.\";\n LogPrintf(\"CActiveMasternode::ManageStateInitial -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n }\n\n if(!fFoundLocal) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = \"Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only.\";\n LogPrintf(\"CActiveMasternode::ManageStateInitial -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n\n int defaultChainParams = CreateChainParams(CBaseChainParams::MAIN)->GetDefaultPort();\n if(Params().NetworkIDString() == CBaseChainParams::MAIN) {\n if(service.GetPort() != mainnetDefaultPort) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = strprintf(\"Invalid port: %u - only %d is supported on mainnet.\", service.GetPort(), mainnetDefaultPort);\n LogPrintf(\"CActiveMasternode::ManageStateInitial -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n } else if(service.GetPort() == mainnetDefaultPort) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = strprintf(\"Invalid port: %u - %d is only supported on mainnet.\", service.GetPort(), mainnetDefaultPort);\n LogPrintf(\"CActiveMasternode::ManageStateInitial -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n\n LogPrintf(\"CActiveMasternode::ManageStateInitial -- Checking inbound connection to '%s'\\n\", service.ToString());\n\n if(!connman.ConnectNode(CAddress(service, NODE_NETWORK), NULL, false, true)) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = \"Could not connect to \" + service.ToString();\n LogPrintf(\"CActiveMasternode::ManageStateInitial -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n\n \/\/ Default to REMOTE\n eType = MASTERNODE_REMOTE;\n\n LogPrint(MCLog::MN, \"CActiveMasternode::ManageStateInitial -- End status = %s, type = %s, pinger enabled = %d\\n\", GetStatus(), GetTypeString(), fPingerEnabled);\n}\n\nvoid CActiveMasternode::ManageStateRemote()\n{\n LogPrint(MCLog::MN, \"CActiveMasternode::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, pubKeyMasternode.GetID() = %s\\n\", \n GetStatus(), GetTypeString(), fPingerEnabled, pubKeyMasternode.GetID().ToString());\n\n mnodeman.CheckMasternode(pubKeyMasternode, true);\n masternode_info_t infoMn;\n if(mnodeman.GetMasternodeInfo(pubKeyMasternode, infoMn)) {\n if(infoMn.nProtocolVersion != PROTOCOL_VERSION) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = \"Invalid protocol version\";\n LogPrintf(\"CActiveMasternode::ManageStateRemote -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n if(service != infoMn.addr) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = \"Broadcasted IP doesn't match our external address. Make sure you issued a new broadcast if IP of this masternode changed recently.\";\n LogPrintf(\"CActiveMasternode::ManageStateRemote -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n if(!CMasternode::IsValidStateForAutoStart(infoMn.nActiveState)) {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = strprintf(\"Masternode in %s state\", CMasternode::StateToString(infoMn.nActiveState));\n LogPrintf(\"CActiveMasternode::ManageStateRemote -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n return;\n }\n if(nState != ACTIVE_MASTERNODE_STARTED) {\n LogPrintf(\"CActiveMasternode::ManageStateRemote -- STARTED!\\n\");\n outpoint = infoMn.vin.prevout;\n service = infoMn.addr;\n fPingerEnabled = true;\n nState = ACTIVE_MASTERNODE_STARTED;\n }\n }\n else {\n nState = ACTIVE_MASTERNODE_NOT_CAPABLE;\n strNotCapableReason = \"Masternode not in masternode list\";\n LogPrintf(\"CActiveMasternode::ManageStateRemote -- %s: %s\\n\", GetStateString(), strNotCapableReason);\n }\n}<|endoftext|>"} {"text":"\/* Copyright (c) 2006, NIF File Format Library and Tools\nAll rights reserved. Please see niflib.h for licence. *\/\n\n#include \"..\/..\/include\/obj\/NiNode.h\"\n#include \"..\/..\/include\/obj\/NiAVObject.h\"\n#include \"..\/..\/include\/obj\/NiDynamicEffect.h\"\n#include \"..\/..\/include\/obj\/NiSkinInstance.h\"\n#include \"..\/..\/include\/obj\/NiSkinData.h\"\n#include \"..\/..\/include\/obj\/NiTriBasedGeom.h\"\nusing namespace Niflib;\n\n\/\/Definition of TYPE constant\nconst Type NiNode::TYPE(\"NiNode\", &NI_NODE_PARENT::TypeConst() );\n\nNiNode::NiNode() NI_NODE_CONSTRUCT {\n\t\/\/Set flag to default of 8: not a skin influence\n\tflags = 8;\n}\n\nNiNode::~NiNode() {\n\t\/\/Unbind any attached skins - must happen before children are cleared\n\tfor ( list::iterator it = skins.begin(); it != skins.end(); ++it ) {\n\t\t(*it)->SkeletonLost();\n\t}\n\n\t\/\/Clear Children\n\tClearChildren();\n}\n\nvoid NiNode::Read( istream& in, list & link_stack, unsigned int version, unsigned int user_version ) {\n\tInternalRead( in, link_stack, version, user_version );\n}\n\nvoid NiNode::Write( ostream& out, const map & link_map, unsigned int version, unsigned int user_version ) const {\n\tInternalWrite( out, link_map, version, user_version );\n}\n\nstring NiNode::asString( bool verbose ) const {\n\treturn InternalAsString( verbose );\n}\n\nvoid NiNode::FixLinks( const map & objects, list & link_stack, unsigned int version, unsigned int user_version ) {\n\tInternalFixLinks( objects, link_stack, version, user_version );\n\t\/\/Connect children to their parents and remove any NULL ones\n\tfor ( vector< NiAVObjectRef >::iterator it = children.begin(); it != children.end(); ) {\n\t\tif ( *it == NULL) {\n\t\t\tit = children.erase( it );\n\t\t} else {\n\t\t\t(*it)->SetParent(this);\n\t\t\t++it;\n\t\t}\n\t}\n}\n\nlist NiNode::GetRefs() const {\n\treturn InternalGetRefs();\n}\n\nconst Type & NiNode::GetType() const {\n\treturn TYPE;\n};\n\nvoid NiNode::AddChild( Ref obj ) {\n\tif ( obj->GetParent() != NULL ) {\n\t\tthrow runtime_error( \"You have attempted to add a child to a NiNode which already is the child of another NiNode.\" );\n\t}\n\tobj->SetParent( this );\n\t\/\/Sometimes NiTriBasedGeom with skins can be siblings of NiNodes that\n\t\/\/represent joints for that same skin. This is not allowed, so we have\n\t\/\/to prevent it by always adding NiTriBasedGeom to the begining of the child list.\n\tNiTriBasedGeomRef niGeom = DynamicCast(obj);\n\tif ( niGeom != NULL ) {\n\t\t\/\/This is a NiTriBasedGeom, so shift all children to the right\n\t\tsize_t old_size = children.size();\n\t\tchildren.resize( children.size() + 1 );\n\t\tfor ( size_t i = children.size() - 1; i >= 1; --i ) {\n\t\t\tchildren[i] = children[i-1];\n\t\t}\n\n\t\t\/\/Now add the new child to the begining of the list\n\t\tchildren[0] = obj;\n\t} else {\n\t\t\/\/This is some other type of object. Just add it to the end of the list.\n\t\tchildren.push_back( obj );\n\t}\n}\n\nvoid NiNode::RemoveChild( Ref obj ) {\n\t\/\/Search child list for the one to remove\n\tfor ( vector< NiAVObjectRef >::iterator it = children.begin(); it != children.end(); ) {\n\t\tif ( *it == obj ) {\n\t\t\t\/\/Ensure that this child is not a skin influence\n\t\t\tNiNodeRef niNode = DynamicCast((*it));\n\t\t\tif ( niNode != NULL && niNode->IsSkinInfluence() == true ) {\n\t\t\t\tthrow runtime_error(\"You cannot remove a node child that is a skin influence. Detatch the skin first.\");\n\t\t\t}\n\t\t\t(*it)->SetParent(NULL);\n\t\t\tit = children.erase( it );\n\t\t} else {\n\t\t\t++it;\n\t\t}\n\t}\n}\n\nvoid NiNode::ClearChildren() {\n\tfor ( vector< NiAVObjectRef >::iterator it = children.begin(); it != children.end(); ++it) {\n\t\tif ( *it != NULL ) {\n\t\t\t(*it)->SetParent(NULL);\n\t\t}\n\t}\n\tchildren.clear();\n}\n\nvector< Ref > NiNode::GetChildren() const {\n\treturn children;\n}\n\n\nvoid NiNode::AddEffect( Ref obj ) {\n obj->SetParent( this );\n effects.push_back( obj );\n}\n\nvoid NiNode::RemoveEffect( Ref obj ) {\n \/\/Search Effect list for the one to remove\n for ( vector< NiDynamicEffectRef >::iterator it = effects.begin(); it != effects.end(); ) {\n if ( *it == obj ) {\n (*it)->SetParent(NULL);\n it = effects.erase( it );\n } else {\n ++it;\n }\n }\n}\n\nvoid NiNode::ClearEffects() {\n for ( vector< NiDynamicEffectRef >::iterator it = effects.begin(); it != effects.end(); ++it) {\n if (*it) (*it)->SetParent(NULL);\n }\n effects.clear();\n}\n\nvector< Ref > NiNode::GetEffects() const {\n return effects;\n}\n\nbool NiNode::IsSkeletonRoot() const {\n\treturn ( skins.size() > 0 );\n}\n\nbool NiNode::IsSkinInfluence() const {\n\treturn ((flags & 8) == 0);\n}\n\nvoid NiNode::AddSkin( NiSkinInstance * skin_inst ) {\n\tskins.push_back( skin_inst );\n}\n\nvoid NiNode::RemoveSkin( NiSkinInstance * skin_inst ) {\n\t\/\/Remove the reference\n\tskins.remove( skin_inst);\n\n\t\/\/Ensure that any multiply referenced bone nodes still\n\t\/\/have their skin flag set\n\tvector bones;\n\tfor ( list::iterator it = skins.begin(); it != skins.end(); ++it ) {\n\t\tbones = (*it)->GetBones();\n\t\tfor ( unsigned int i = 0; i < bones.size(); ++i ) {\n\t\t\tbones[i]->SetSkinFlag(true);\n\t\t}\n\t}\n}\n\nvoid NiNode::SetSkinFlag( bool n ) {\n\tif ( IsSkinInfluence() == n ) {\n\t\t\/\/Already set to the requested value\n\t\treturn;\n\t} else {\n\t\t\/\/Requested value is different, flip bit\n\t\tflags ^= 8;\n\t}\n}\n\nvoid NiNode::GoToSkeletonBindPosition() {\n\t\/\/map world_positions;\n\t\n\t\/\/Loop through all attached skins, straightening the skeleton on each\n\tfor ( list::iterator it = skins.begin(); it != skins.end(); ++it ) {\n\t\t\/\/Get Bone list and Skin Data\n\t\tvector bone_nodes = (*it)->GetBones();\n\t\tNiSkinDataRef skin_data = (*it)->GetSkinData();\n\n\t\tif ( skin_data == NULL ) {\n\t\t\t\/\/There's no skin data for this skin instance; skip it.\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/Make sure the counts match\n\t\tif ( bone_nodes.size() != skin_data->GetBoneCount() ) {\n\t\t\tthrow runtime_error( \"Bone counts in NiSkinInstance and attached NiSkinData must match\" );\n\t\t}\n\n\t\t\/\/Loop through all bones influencing this skin\n\t\tfor ( unsigned int i = 0; i < bone_nodes.size(); ++i ) {\n\t\t\t\/\/Get current offset Matrix for this bone\n\t\t\tMatrix44 parent_offset = skin_data->GetBoneTransform(i);\n\n\t\t\t\/\/Loop through all bones again, checking for any that have this bone as a parent\n\t\t\tfor ( unsigned int j = 0; j < bone_nodes.size(); ++j ) {\n\t\t\t\tif ( bone_nodes[j]->GetParent() == bone_nodes[i] ) {\n\t\t\t\t\t\/\/Node 2 has node 1 as a parent\n\n\t\t\t\t\t\/\/Get child offset Matrix33\n\t\t\t\t\tMatrix44 child_offset = skin_data->GetBoneTransform(j);\n\n\t\t\t\t\t\/\/Do calculation to get correct bone postion in relation to parent\n\t\t\t\t\tMatrix44 child_pos = child_offset.Inverse() * parent_offset;\n\n\t\t\t\t\t\/\/bones[j]->SetWorldBindPos( child_pos );\n\t\t\t\t\tbone_nodes[j]->SetLocalRotation( child_pos.GetRotation() );\n\t\t\t\t\tbone_nodes[j]->SetLocalScale( 1.0f );\n\t\t\t\t\tbone_nodes[j]->SetLocalTranslation( child_pos.GetTranslation() );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid NiNode::PropagateTransform() {\n\n\tMatrix44 par_trans = this->GetLocalTransform();\n\n\t\/\/Loop through each child and apply this node's transform to it\n\tfor ( unsigned i = 0; i < children.size(); ++i ) {\n\t\tchildren[i]->SetLocalTransform(\n\t\t\tchildren[i]->GetLocalTransform() * par_trans\n\t\t);\n\t}\n\n\t\/\/Nowthat the transforms have been propogated, clear them out\n\tthis->SetLocalTransform( Matrix44::Identity() );\n}\n\nbool NiNode::IsSplitMeshProxy() const {\n\t\/\/Let us guess that a node is a split mesh proxy if:\n\t\/\/ 1) It is not a skin influence\n\t\/\/ 2) All its children are NiTriBasedGeom derived objects.\n\t\/\/ 3) All its children have identity transforms.\n\t\/\/ 4) It has more than one child\n\t\/\/ 5) All meshes are visible\n\t\/\/ 6) ???? May need more criteria as time goes on.\n\n\tif ( this->IsSkinInfluence() ) {\n\t\treturn false;\n\t}\n\n\tif ( children.size() < 2 ) {\n\t\treturn false;\n\t}\n\n\tfor ( unsigned i = 0; i < children.size(); ++i ) {\n\t\tif ( children[i]->IsDerivedType( NiTriBasedGeom::TypeConst() ) == false ) {\n\t\t\treturn false;\n\t\t}\n\t\tif ( children[i]->GetLocalTransform() != Matrix44::Identity() ) {\n\t\t\treturn false;\n\t\t}\n\t\tif ( children[i]->GetVisibility() == false ) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/Made it all the way through the loop without returning false\n\treturn true;\n}\n\nconst Type & NiNode::TypeConst() {\n\treturn TYPE;\n}\nFixed description of NiNode child order fix in comment.\/* Copyright (c) 2006, NIF File Format Library and Tools\nAll rights reserved. Please see niflib.h for licence. *\/\n\n#include \"..\/..\/include\/obj\/NiNode.h\"\n#include \"..\/..\/include\/obj\/NiAVObject.h\"\n#include \"..\/..\/include\/obj\/NiDynamicEffect.h\"\n#include \"..\/..\/include\/obj\/NiSkinInstance.h\"\n#include \"..\/..\/include\/obj\/NiSkinData.h\"\n#include \"..\/..\/include\/obj\/NiTriBasedGeom.h\"\nusing namespace Niflib;\n\n\/\/Definition of TYPE constant\nconst Type NiNode::TYPE(\"NiNode\", &NI_NODE_PARENT::TypeConst() );\n\nNiNode::NiNode() NI_NODE_CONSTRUCT {\n\t\/\/Set flag to default of 8: not a skin influence\n\tflags = 8;\n}\n\nNiNode::~NiNode() {\n\t\/\/Unbind any attached skins - must happen before children are cleared\n\tfor ( list::iterator it = skins.begin(); it != skins.end(); ++it ) {\n\t\t(*it)->SkeletonLost();\n\t}\n\n\t\/\/Clear Children\n\tClearChildren();\n}\n\nvoid NiNode::Read( istream& in, list & link_stack, unsigned int version, unsigned int user_version ) {\n\tInternalRead( in, link_stack, version, user_version );\n}\n\nvoid NiNode::Write( ostream& out, const map & link_map, unsigned int version, unsigned int user_version ) const {\n\tInternalWrite( out, link_map, version, user_version );\n}\n\nstring NiNode::asString( bool verbose ) const {\n\treturn InternalAsString( verbose );\n}\n\nvoid NiNode::FixLinks( const map & objects, list & link_stack, unsigned int version, unsigned int user_version ) {\n\tInternalFixLinks( objects, link_stack, version, user_version );\n\t\/\/Connect children to their parents and remove any NULL ones\n\tfor ( vector< NiAVObjectRef >::iterator it = children.begin(); it != children.end(); ) {\n\t\tif ( *it == NULL) {\n\t\t\tit = children.erase( it );\n\t\t} else {\n\t\t\t(*it)->SetParent(this);\n\t\t\t++it;\n\t\t}\n\t}\n}\n\nlist NiNode::GetRefs() const {\n\treturn InternalGetRefs();\n}\n\nconst Type & NiNode::GetType() const {\n\treturn TYPE;\n};\n\nvoid NiNode::AddChild( Ref obj ) {\n\tif ( obj->GetParent() != NULL ) {\n\t\tthrow runtime_error( \"You have attempted to add a child to a NiNode which already is the child of another NiNode.\" );\n\t}\n\tobj->SetParent( this );\n\t\/\/Sometimes NiTriBasedGeom with skins can be siblings of NiNodes that\n\t\/\/represent joints for that same skin. When this is the case, NiTriBasedGeom\n\t\/\/must com first, so we enforce that by always adding NiTriBasedGeom to the\n\t\/\/begining of the child list.\n\tNiTriBasedGeomRef niGeom = DynamicCast(obj);\n\tif ( niGeom != NULL ) {\n\t\t\/\/This is a NiTriBasedGeom, so shift all children to the right\n\t\tsize_t old_size = children.size();\n\t\tchildren.resize( children.size() + 1 );\n\t\tfor ( size_t i = children.size() - 1; i >= 1; --i ) {\n\t\t\tchildren[i] = children[i-1];\n\t\t}\n\n\t\t\/\/Now add the new child to the begining of the list\n\t\tchildren[0] = obj;\n\t} else {\n\t\t\/\/This is some other type of object. Just add it to the end of the list.\n\t\tchildren.push_back( obj );\n\t}\n}\n\nvoid NiNode::RemoveChild( Ref obj ) {\n\t\/\/Search child list for the one to remove\n\tfor ( vector< NiAVObjectRef >::iterator it = children.begin(); it != children.end(); ) {\n\t\tif ( *it == obj ) {\n\t\t\t\/\/Ensure that this child is not a skin influence\n\t\t\tNiNodeRef niNode = DynamicCast((*it));\n\t\t\tif ( niNode != NULL && niNode->IsSkinInfluence() == true ) {\n\t\t\t\tthrow runtime_error(\"You cannot remove a node child that is a skin influence. Detatch the skin first.\");\n\t\t\t}\n\t\t\t(*it)->SetParent(NULL);\n\t\t\tit = children.erase( it );\n\t\t} else {\n\t\t\t++it;\n\t\t}\n\t}\n}\n\nvoid NiNode::ClearChildren() {\n\tfor ( vector< NiAVObjectRef >::iterator it = children.begin(); it != children.end(); ++it) {\n\t\tif ( *it != NULL ) {\n\t\t\t(*it)->SetParent(NULL);\n\t\t}\n\t}\n\tchildren.clear();\n}\n\nvector< Ref > NiNode::GetChildren() const {\n\treturn children;\n}\n\n\nvoid NiNode::AddEffect( Ref obj ) {\n obj->SetParent( this );\n effects.push_back( obj );\n}\n\nvoid NiNode::RemoveEffect( Ref obj ) {\n \/\/Search Effect list for the one to remove\n for ( vector< NiDynamicEffectRef >::iterator it = effects.begin(); it != effects.end(); ) {\n if ( *it == obj ) {\n (*it)->SetParent(NULL);\n it = effects.erase( it );\n } else {\n ++it;\n }\n }\n}\n\nvoid NiNode::ClearEffects() {\n for ( vector< NiDynamicEffectRef >::iterator it = effects.begin(); it != effects.end(); ++it) {\n if (*it) (*it)->SetParent(NULL);\n }\n effects.clear();\n}\n\nvector< Ref > NiNode::GetEffects() const {\n return effects;\n}\n\nbool NiNode::IsSkeletonRoot() const {\n\treturn ( skins.size() > 0 );\n}\n\nbool NiNode::IsSkinInfluence() const {\n\treturn ((flags & 8) == 0);\n}\n\nvoid NiNode::AddSkin( NiSkinInstance * skin_inst ) {\n\tskins.push_back( skin_inst );\n}\n\nvoid NiNode::RemoveSkin( NiSkinInstance * skin_inst ) {\n\t\/\/Remove the reference\n\tskins.remove( skin_inst);\n\n\t\/\/Ensure that any multiply referenced bone nodes still\n\t\/\/have their skin flag set\n\tvector bones;\n\tfor ( list::iterator it = skins.begin(); it != skins.end(); ++it ) {\n\t\tbones = (*it)->GetBones();\n\t\tfor ( unsigned int i = 0; i < bones.size(); ++i ) {\n\t\t\tbones[i]->SetSkinFlag(true);\n\t\t}\n\t}\n}\n\nvoid NiNode::SetSkinFlag( bool n ) {\n\tif ( IsSkinInfluence() == n ) {\n\t\t\/\/Already set to the requested value\n\t\treturn;\n\t} else {\n\t\t\/\/Requested value is different, flip bit\n\t\tflags ^= 8;\n\t}\n}\n\nvoid NiNode::GoToSkeletonBindPosition() {\n\t\/\/map world_positions;\n\t\n\t\/\/Loop through all attached skins, straightening the skeleton on each\n\tfor ( list::iterator it = skins.begin(); it != skins.end(); ++it ) {\n\t\t\/\/Get Bone list and Skin Data\n\t\tvector bone_nodes = (*it)->GetBones();\n\t\tNiSkinDataRef skin_data = (*it)->GetSkinData();\n\n\t\tif ( skin_data == NULL ) {\n\t\t\t\/\/There's no skin data for this skin instance; skip it.\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/Make sure the counts match\n\t\tif ( bone_nodes.size() != skin_data->GetBoneCount() ) {\n\t\t\tthrow runtime_error( \"Bone counts in NiSkinInstance and attached NiSkinData must match\" );\n\t\t}\n\n\t\t\/\/Loop through all bones influencing this skin\n\t\tfor ( unsigned int i = 0; i < bone_nodes.size(); ++i ) {\n\t\t\t\/\/Get current offset Matrix for this bone\n\t\t\tMatrix44 parent_offset = skin_data->GetBoneTransform(i);\n\n\t\t\t\/\/Loop through all bones again, checking for any that have this bone as a parent\n\t\t\tfor ( unsigned int j = 0; j < bone_nodes.size(); ++j ) {\n\t\t\t\tif ( bone_nodes[j]->GetParent() == bone_nodes[i] ) {\n\t\t\t\t\t\/\/Node 2 has node 1 as a parent\n\n\t\t\t\t\t\/\/Get child offset Matrix33\n\t\t\t\t\tMatrix44 child_offset = skin_data->GetBoneTransform(j);\n\n\t\t\t\t\t\/\/Do calculation to get correct bone postion in relation to parent\n\t\t\t\t\tMatrix44 child_pos = child_offset.Inverse() * parent_offset;\n\n\t\t\t\t\t\/\/bones[j]->SetWorldBindPos( child_pos );\n\t\t\t\t\tbone_nodes[j]->SetLocalRotation( child_pos.GetRotation() );\n\t\t\t\t\tbone_nodes[j]->SetLocalScale( 1.0f );\n\t\t\t\t\tbone_nodes[j]->SetLocalTranslation( child_pos.GetTranslation() );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid NiNode::PropagateTransform() {\n\n\tMatrix44 par_trans = this->GetLocalTransform();\n\n\t\/\/Loop through each child and apply this node's transform to it\n\tfor ( unsigned i = 0; i < children.size(); ++i ) {\n\t\tchildren[i]->SetLocalTransform(\n\t\t\tchildren[i]->GetLocalTransform() * par_trans\n\t\t);\n\t}\n\n\t\/\/Nowthat the transforms have been propogated, clear them out\n\tthis->SetLocalTransform( Matrix44::Identity() );\n}\n\nbool NiNode::IsSplitMeshProxy() const {\n\t\/\/Let us guess that a node is a split mesh proxy if:\n\t\/\/ 1) It is not a skin influence\n\t\/\/ 2) All its children are NiTriBasedGeom derived objects.\n\t\/\/ 3) All its children have identity transforms.\n\t\/\/ 4) It has more than one child\n\t\/\/ 5) All meshes are visible\n\t\/\/ 6) ???? May need more criteria as time goes on.\n\n\tif ( this->IsSkinInfluence() ) {\n\t\treturn false;\n\t}\n\n\tif ( children.size() < 2 ) {\n\t\treturn false;\n\t}\n\n\tfor ( unsigned i = 0; i < children.size(); ++i ) {\n\t\tif ( children[i]->IsDerivedType( NiTriBasedGeom::TypeConst() ) == false ) {\n\t\t\treturn false;\n\t\t}\n\t\tif ( children[i]->GetLocalTransform() != Matrix44::Identity() ) {\n\t\t\treturn false;\n\t\t}\n\t\tif ( children[i]->GetVisibility() == false ) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/Made it all the way through the loop without returning false\n\treturn true;\n}\n\nconst Type & NiNode::TypeConst() {\n\treturn TYPE;\n}\n<|endoftext|>"} {"text":"\/**\n ** \\file object\/code-class.cc\n ** \\brief Creation of the URBI object code.\n *\/\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace object\n{\n rObject code_class;\n\n Code::Code()\n {\n throw PrimitiveError(SYMBOL(clone),\n\t\t\t \"`Code' objects cannot be cloned\");\n }\n\n Code::Code(ast_type a)\n : ast_(a)\n , captures_()\n , self_()\n , call_()\n {\n assert(code_class);\n proto_add(code_class);\n }\n\n Code::Code(rCode model)\n : ast_(model->ast_)\n , captures_(model->captures_)\n , self_(model->self_)\n , call_(model->call_)\n {\n proto_add(model);\n }\n\n Code::ast_type Code::ast_get() const\n {\n return ast_;\n }\n\n rObject Code::call_get() const\n {\n return call_;\n }\n\n const Code::captures_type& Code::captures_get() const\n {\n return captures_;\n }\n\n rObject Code::self_get() const\n {\n return self_;\n }\n\n Code::ast_type& Code::ast_get()\n {\n return ast_;\n }\n\n rObject& Code::call_get()\n {\n return call_;\n }\n\n Code::captures_type& Code::captures_get()\n {\n return captures_;\n }\n\n rObject& Code::self_get()\n {\n return self_;\n }\n\n rObject Code::apply(runner::Runner& r, rList args)\n {\n if (args->value_get().empty())\n throw PrimitiveError(SYMBOL(apply),\n \"list of arguments must begin with this\");\n List::value_type a = args->value_get();\n rObject tgt = a.front();\n a.pop_front();\n return r.apply(tgt, this, SYMBOL(apply), a);\n }\n\n std::string Code::as_string(rObject what)\n {\n if (what.get() == code_class.get())\n return SYMBOL(LT_Code_GT);\n type_check(what, SYMBOL(asString));\n return string_cast(*what->as()->ast_get());\n\n }\n\n std::string Code::body_string()\n {\n if (code_class == this)\n return SYMBOL(LT_Code_GT);\n return\n string_cast(*ast_->body_get()->body_get());\n }\n\n std::ostream& Code::special_slots_dump(std::ostream& o,\n runner::Runner&) const\n {\n o << \"value: \" << *ast_get() << libport::iendl;\n return o;\n }\n\n\n void Code::initialize(CxxObject::Binder& bind)\n {\n bind(SYMBOL(apply), &Code::apply);\n bind(SYMBOL(asString), &Code::as_string);\n bind(SYMBOL(bodyString), &Code::body_string);\n }\n\n std::string Code::type_name_get() const\n {\n return type_name;\n }\n\n bool Code::code_added = CxxObject::add(\"Code\", code_class);\n const std::string Code::type_name = \"Code\";\n\n}; \/\/ namespace object\nPrint Code special slot like other slots.\/**\n ** \\file object\/code-class.cc\n ** \\brief Creation of the URBI object code.\n *\/\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace object\n{\n rObject code_class;\n\n Code::Code()\n {\n throw PrimitiveError(SYMBOL(clone),\n\t\t\t \"`Code' objects cannot be cloned\");\n }\n\n Code::Code(ast_type a)\n : ast_(a)\n , captures_()\n , self_()\n , call_()\n {\n assert(code_class);\n proto_add(code_class);\n }\n\n Code::Code(rCode model)\n : ast_(model->ast_)\n , captures_(model->captures_)\n , self_(model->self_)\n , call_(model->call_)\n {\n proto_add(model);\n }\n\n Code::ast_type Code::ast_get() const\n {\n return ast_;\n }\n\n rObject Code::call_get() const\n {\n return call_;\n }\n\n const Code::captures_type& Code::captures_get() const\n {\n return captures_;\n }\n\n rObject Code::self_get() const\n {\n return self_;\n }\n\n Code::ast_type& Code::ast_get()\n {\n return ast_;\n }\n\n rObject& Code::call_get()\n {\n return call_;\n }\n\n Code::captures_type& Code::captures_get()\n {\n return captures_;\n }\n\n rObject& Code::self_get()\n {\n return self_;\n }\n\n rObject Code::apply(runner::Runner& r, rList args)\n {\n if (args->value_get().empty())\n throw PrimitiveError(SYMBOL(apply),\n \"list of arguments must begin with this\");\n List::value_type a = args->value_get();\n rObject tgt = a.front();\n a.pop_front();\n return r.apply(tgt, this, SYMBOL(apply), a);\n }\n\n std::string Code::as_string(rObject what)\n {\n if (what.get() == code_class.get())\n return SYMBOL(LT_Code_GT);\n type_check(what, SYMBOL(asString));\n return string_cast(*what->as()->ast_get());\n\n }\n\n std::string Code::body_string()\n {\n if (code_class == this)\n return SYMBOL(LT_Code_GT);\n return\n string_cast(*ast_->body_get()->body_get());\n }\n\n std::ostream& Code::special_slots_dump(std::ostream& o,\n runner::Runner&) const\n {\n o << \"value = \" << *ast_get() << libport::iendl;\n return o;\n }\n\n\n void Code::initialize(CxxObject::Binder& bind)\n {\n bind(SYMBOL(apply), &Code::apply);\n bind(SYMBOL(asString), &Code::as_string);\n bind(SYMBOL(bodyString), &Code::body_string);\n }\n\n std::string Code::type_name_get() const\n {\n return type_name;\n }\n\n bool Code::code_added = CxxObject::add(\"Code\", code_class);\n const std::string Code::type_name = \"Code\";\n\n}; \/\/ namespace object\n<|endoftext|>"} {"text":"\/\/ ----------------------------------------------------------------------\n\/\/\n\/\/ Arbiter: Base class for Matrix and Round Robin Arbiter\n\/\/\n\/\/ ----------------------------------------------------------------------\n\n#include \"arbiter.hpp\"\n\n#include \n\nusing namespace std ;\n\nArbiter::Arbiter()\n : _input_size(0), _request(0), _num_reqs(0), _last_req(-1) {\n}\n\nArbiter::~Arbiter() {\n if ( _request ) \n delete[] _request ;\n}\n\nvoid Arbiter::Init( int size ) {\n _input_size = size;\n _request = new entry_t [size] ;\n for ( int i = 0 ; i < size ; i++ ) \n _request[i].valid = false ;\n}\n\nvoid Arbiter::AddRequest( int input, int id, int pri ) {\n assert( 0 <= input && input < _input_size ) ;\n _num_reqs++ ;\n _last_req = input ;\n _request[input].valid = true ;\n _request[input].id = id ;\n _request[input].pri = pri ;\n \n}\nhandle case where multiple requests for the same port are added\/\/ ----------------------------------------------------------------------\n\/\/\n\/\/ Arbiter: Base class for Matrix and Round Robin Arbiter\n\/\/\n\/\/ ----------------------------------------------------------------------\n\n#include \"arbiter.hpp\"\n\n#include \n\nusing namespace std ;\n\nArbiter::Arbiter()\n : _input_size(0), _request(0), _num_reqs(0), _last_req(-1) {\n}\n\nArbiter::~Arbiter() {\n if ( _request ) \n delete[] _request ;\n}\n\nvoid Arbiter::Init( int size ) {\n _input_size = size;\n _request = new entry_t [size] ;\n for ( int i = 0 ; i < size ; i++ ) \n _request[i].valid = false ;\n}\n\nvoid Arbiter::AddRequest( int input, int id, int pri ) {\n assert( 0 <= input && input < _input_size ) ;\n _last_req = input ;\n if(!_request[input].valid) {\n _num_reqs++ ;\n _request[input].valid = true ;\n }\n _request[input].id = id ;\n _request[input].pri = pri ;\n \n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2010 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2009 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n#ifndef __ARCH_ARM_MISCREGS_HH__\n#define __ARCH_ARM_MISCREGS_HH__\n\n#include \"base\/bitunion.hh\"\n\nnamespace ArmISA\n{\n enum ConditionCode {\n COND_EQ = 0,\n COND_NE, \/\/ 1\n COND_CS, \/\/ 2\n COND_CC, \/\/ 3\n COND_MI, \/\/ 4\n COND_PL, \/\/ 5\n COND_VS, \/\/ 6\n COND_VC, \/\/ 7\n COND_HI, \/\/ 8\n COND_LS, \/\/ 9\n COND_GE, \/\/ 10\n COND_LT, \/\/ 11\n COND_GT, \/\/ 12\n COND_LE, \/\/ 13\n COND_AL, \/\/ 14\n COND_UC \/\/ 15\n };\n\n enum MiscRegIndex {\n MISCREG_CPSR = 0,\n MISCREG_SPSR,\n MISCREG_SPSR_FIQ,\n MISCREG_SPSR_IRQ,\n MISCREG_SPSR_SVC,\n MISCREG_SPSR_MON,\n MISCREG_SPSR_UND,\n MISCREG_SPSR_ABT,\n MISCREG_FPSR,\n MISCREG_FPSID,\n MISCREG_FPSCR,\n MISCREG_FPEXC,\n\n \/\/ CP15 registers\n MISCREG_CP15_START,\n MISCREG_SCTLR = MISCREG_CP15_START,\n MISCREG_DCCISW,\n MISCREG_DCCIMVAC,\n MISCREG_CONTEXTIDR,\n MISCREG_TPIDRURW,\n MISCREG_TPIDRURO,\n MISCREG_TPIDRPRW,\n MISCREG_CP15ISB,\n MISCREG_CP15DSB,\n MISCREG_CP15DMB,\n MISCREG_CPACR,\n MISCREG_CLIDR,\n MISCREG_ICIALLUIS,\n MISCREG_CP15_UNIMP_START,\n MISCREG_CTR = MISCREG_CP15_UNIMP_START,\n MISCREG_TCMTR,\n MISCREG_MPUIR,\n MISCREG_MPIDR,\n MISCREG_MIDR,\n MISCREG_ID_PFR0,\n MISCREG_ID_PFR1,\n MISCREG_ID_DFR0,\n MISCREG_ID_AFR0,\n MISCREG_ID_MMFR0,\n MISCREG_ID_MMFR1,\n MISCREG_ID_MMFR2,\n MISCREG_ID_MMFR3,\n MISCREG_ID_ISAR0,\n MISCREG_ID_ISAR1,\n MISCREG_ID_ISAR2,\n MISCREG_ID_ISAR3,\n MISCREG_ID_ISAR4,\n MISCREG_ID_ISAR5,\n MISCREG_CCSIDR,\n MISCREG_AIDR,\n MISCREG_CSSELR,\n MISCREG_ACTLR,\n MISCREG_DFSR,\n MISCREG_IFSR,\n MISCREG_ADFSR,\n MISCREG_AIFSR,\n MISCREG_DFAR,\n MISCREG_IFAR,\n MISCREG_DRBAR,\n MISCREG_IRBAR,\n MISCREG_DRSR,\n MISCREG_IRSR,\n MISCREG_DRACR,\n MISCREG_IRACR,\n MISCREG_RGNR,\n MISCREG_BPIALLIS,\n MISCREG_ICIALLU,\n MISCREG_ICIMVAU,\n MISCREG_BPIALL,\n MISCREG_BPIMVA,\n MISCREG_DCIMVAC,\n MISCREG_DCISW,\n MISCREG_DCCMVAC,\n MISCREG_MCCSW,\n MISCREG_DCCMVAU,\n\n MISCREG_CP15_END,\n\n \/\/ Dummy indices\n MISCREG_NOP = MISCREG_CP15_END,\n MISCREG_RAZ,\n\n NUM_MISCREGS\n };\n\n MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1,\n unsigned crm, unsigned opc2);\n\n const char * const miscRegName[NUM_MISCREGS] = {\n \"cpsr\", \"spsr\", \"spsr_fiq\", \"spsr_irq\", \"spsr_svc\",\n \"spsr_mon\", \"spsr_und\", \"spsr_abt\",\n \"fpsr\", \"fpsid\", \"fpscr\", \"fpexc\",\n \"sctlr\", \"dccisw\", \"dccimvac\",\n \"contextidr\", \"tpidrurw\", \"tpidruro\", \"tpidrprw\",\n \"cp15isb\", \"cp15dsb\", \"cp15dmb\", \"cpacr\", \"clidr\", \"icialluis\",\n \"ctr\", \"tcmtr\", \"mpuir\", \"mpidr\", \"midr\",\n \"id_pfr0\", \"id_pfr1\", \"id_dfr0\", \"id_afr0\",\n \"id_mmfr0\", \"id_mmfr1\", \"id_mmfr2\", \"id_mmfr3\",\n \"id_isar0\", \"id_isar1\", \"id_isar2\", \"id_isar3\", \"id_isar4\", \"id_isar5\",\n \"ccsidr\", \"aidr\", \"csselr\", \"actlr\",\n \"dfsr\", \"ifsr\", \"adfsr\", \"aifsr\", \"dfar\", \"ifar\",\n \"drbar\", \"irbar\", \"drsr\", \"irsr\", \"dracr\", \"iracr\",\n \"rgnr\", \"bpiallis\", \"iciallu\", \"icimvau\",\n \"bpiall\", \"bpimva\", \"dcimvac\", \"dcisw\", \"dccmvac\", \"mccsw\",\n \"dccmvau\",\n \"nop\", \"raz\"\n };\n\n BitUnion32(CPSR)\n Bitfield<31> n;\n Bitfield<30> z;\n Bitfield<29> c;\n Bitfield<28> v;\n Bitfield<27> q;\n Bitfield<26,25> it1;\n Bitfield<24> j;\n Bitfield<19, 16> ge;\n Bitfield<15,10> it2;\n Bitfield<9> e;\n Bitfield<8> a;\n Bitfield<7> i;\n Bitfield<6> f;\n Bitfield<5> t;\n Bitfield<4, 0> mode;\n EndBitUnion(CPSR)\n\n \/\/ This mask selects bits of the CPSR that actually go in the CondCodes\n \/\/ integer register to allow renaming.\n static const uint32_t CondCodesMask = 0xF80F0000;\n\n \/\/ These otherwise unused bits of the PC are used to select a mode\n \/\/ like the J and T bits of the CPSR.\n static const Addr PcJBitShift = 33;\n static const Addr PcTBitShift = 34;\n static const Addr PcModeMask = (ULL(1) << PcJBitShift) |\n (ULL(1) << PcTBitShift);\n\n BitUnion32(SCTLR)\n Bitfield<30> te; \/\/ Thumb Exception Enable\n Bitfield<29> afe; \/\/ Access flag enable\n Bitfield<28> tre; \/\/ TEX Remap bit \n Bitfield<27> nmfi;\/\/ Non-maskable fast interrupts enable\n Bitfield<25> ee; \/\/ Exception Endianness bit\n Bitfield<24> ve; \/\/ Interrupt vectors enable\n Bitfield<23> rao1;\/\/ Read as one\n Bitfield<22> u; \/\/ Alignment (now unused)\n Bitfield<21> fi; \/\/ Fast interrupts configuration enable\n Bitfield<18> rao2;\/\/ Read as one\n Bitfield<17> ha; \/\/ Hardware access flag enable\n Bitfield<16> rao3;\/\/ Read as one\n Bitfield<14> rr; \/\/ Round robin cache replacement\n Bitfield<13> v; \/\/ Base address for exception vectors\n Bitfield<12> i; \/\/ instruction cache enable\n Bitfield<11> z; \/\/ branch prediction enable bit\n Bitfield<10> sw; \/\/ Enable swp\/swpb\n Bitfield<6,3> rao4;\/\/ Read as one\n Bitfield<7> b; \/\/ Endianness support (unused) \n Bitfield<2> c; \/\/ Cache enable bit\n Bitfield<1> a; \/\/ Alignment fault checking\n Bitfield<0> m; \/\/ MMU enable bit \n EndBitUnion(SCTLR)\n};\n\n#endif \/\/ __ARCH_ARM_MISCREGS_HH__\nARM: Ignore\/warn on iciallu.\/*\n * Copyright (c) 2010 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2009 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n#ifndef __ARCH_ARM_MISCREGS_HH__\n#define __ARCH_ARM_MISCREGS_HH__\n\n#include \"base\/bitunion.hh\"\n\nnamespace ArmISA\n{\n enum ConditionCode {\n COND_EQ = 0,\n COND_NE, \/\/ 1\n COND_CS, \/\/ 2\n COND_CC, \/\/ 3\n COND_MI, \/\/ 4\n COND_PL, \/\/ 5\n COND_VS, \/\/ 6\n COND_VC, \/\/ 7\n COND_HI, \/\/ 8\n COND_LS, \/\/ 9\n COND_GE, \/\/ 10\n COND_LT, \/\/ 11\n COND_GT, \/\/ 12\n COND_LE, \/\/ 13\n COND_AL, \/\/ 14\n COND_UC \/\/ 15\n };\n\n enum MiscRegIndex {\n MISCREG_CPSR = 0,\n MISCREG_SPSR,\n MISCREG_SPSR_FIQ,\n MISCREG_SPSR_IRQ,\n MISCREG_SPSR_SVC,\n MISCREG_SPSR_MON,\n MISCREG_SPSR_UND,\n MISCREG_SPSR_ABT,\n MISCREG_FPSR,\n MISCREG_FPSID,\n MISCREG_FPSCR,\n MISCREG_FPEXC,\n\n \/\/ CP15 registers\n MISCREG_CP15_START,\n MISCREG_SCTLR = MISCREG_CP15_START,\n MISCREG_DCCISW,\n MISCREG_DCCIMVAC,\n MISCREG_CONTEXTIDR,\n MISCREG_TPIDRURW,\n MISCREG_TPIDRURO,\n MISCREG_TPIDRPRW,\n MISCREG_CP15ISB,\n MISCREG_CP15DSB,\n MISCREG_CP15DMB,\n MISCREG_CPACR,\n MISCREG_CLIDR,\n MISCREG_ICIALLUIS,\n MISCREG_ICIALLU,\n MISCREG_CP15_UNIMP_START,\n MISCREG_CTR = MISCREG_CP15_UNIMP_START,\n MISCREG_TCMTR,\n MISCREG_MPUIR,\n MISCREG_MPIDR,\n MISCREG_MIDR,\n MISCREG_ID_PFR0,\n MISCREG_ID_PFR1,\n MISCREG_ID_DFR0,\n MISCREG_ID_AFR0,\n MISCREG_ID_MMFR0,\n MISCREG_ID_MMFR1,\n MISCREG_ID_MMFR2,\n MISCREG_ID_MMFR3,\n MISCREG_ID_ISAR0,\n MISCREG_ID_ISAR1,\n MISCREG_ID_ISAR2,\n MISCREG_ID_ISAR3,\n MISCREG_ID_ISAR4,\n MISCREG_ID_ISAR5,\n MISCREG_CCSIDR,\n MISCREG_AIDR,\n MISCREG_CSSELR,\n MISCREG_ACTLR,\n MISCREG_DFSR,\n MISCREG_IFSR,\n MISCREG_ADFSR,\n MISCREG_AIFSR,\n MISCREG_DFAR,\n MISCREG_IFAR,\n MISCREG_DRBAR,\n MISCREG_IRBAR,\n MISCREG_DRSR,\n MISCREG_IRSR,\n MISCREG_DRACR,\n MISCREG_IRACR,\n MISCREG_RGNR,\n MISCREG_BPIALLIS,\n MISCREG_ICIMVAU,\n MISCREG_BPIALL,\n MISCREG_BPIMVA,\n MISCREG_DCIMVAC,\n MISCREG_DCISW,\n MISCREG_DCCMVAC,\n MISCREG_MCCSW,\n MISCREG_DCCMVAU,\n\n MISCREG_CP15_END,\n\n \/\/ Dummy indices\n MISCREG_NOP = MISCREG_CP15_END,\n MISCREG_RAZ,\n\n NUM_MISCREGS\n };\n\n MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1,\n unsigned crm, unsigned opc2);\n\n const char * const miscRegName[NUM_MISCREGS] = {\n \"cpsr\", \"spsr\", \"spsr_fiq\", \"spsr_irq\", \"spsr_svc\",\n \"spsr_mon\", \"spsr_und\", \"spsr_abt\",\n \"fpsr\", \"fpsid\", \"fpscr\", \"fpexc\",\n \"sctlr\", \"dccisw\", \"dccimvac\",\n \"contextidr\", \"tpidrurw\", \"tpidruro\", \"tpidrprw\",\n \"cp15isb\", \"cp15dsb\", \"cp15dmb\", \"cpacr\", \"clidr\",\n \"icialluis\", \"iciallu\",\n \"ctr\", \"tcmtr\", \"mpuir\", \"mpidr\", \"midr\",\n \"id_pfr0\", \"id_pfr1\", \"id_dfr0\", \"id_afr0\",\n \"id_mmfr0\", \"id_mmfr1\", \"id_mmfr2\", \"id_mmfr3\",\n \"id_isar0\", \"id_isar1\", \"id_isar2\", \"id_isar3\", \"id_isar4\", \"id_isar5\",\n \"ccsidr\", \"aidr\", \"csselr\", \"actlr\",\n \"dfsr\", \"ifsr\", \"adfsr\", \"aifsr\", \"dfar\", \"ifar\",\n \"drbar\", \"irbar\", \"drsr\", \"irsr\", \"dracr\", \"iracr\",\n \"rgnr\", \"bpiallis\", \"icimvau\",\n \"bpiall\", \"bpimva\", \"dcimvac\", \"dcisw\", \"dccmvac\", \"mccsw\",\n \"dccmvau\",\n \"nop\", \"raz\"\n };\n\n BitUnion32(CPSR)\n Bitfield<31> n;\n Bitfield<30> z;\n Bitfield<29> c;\n Bitfield<28> v;\n Bitfield<27> q;\n Bitfield<26,25> it1;\n Bitfield<24> j;\n Bitfield<19, 16> ge;\n Bitfield<15,10> it2;\n Bitfield<9> e;\n Bitfield<8> a;\n Bitfield<7> i;\n Bitfield<6> f;\n Bitfield<5> t;\n Bitfield<4, 0> mode;\n EndBitUnion(CPSR)\n\n \/\/ This mask selects bits of the CPSR that actually go in the CondCodes\n \/\/ integer register to allow renaming.\n static const uint32_t CondCodesMask = 0xF80F0000;\n\n \/\/ These otherwise unused bits of the PC are used to select a mode\n \/\/ like the J and T bits of the CPSR.\n static const Addr PcJBitShift = 33;\n static const Addr PcTBitShift = 34;\n static const Addr PcModeMask = (ULL(1) << PcJBitShift) |\n (ULL(1) << PcTBitShift);\n\n BitUnion32(SCTLR)\n Bitfield<30> te; \/\/ Thumb Exception Enable\n Bitfield<29> afe; \/\/ Access flag enable\n Bitfield<28> tre; \/\/ TEX Remap bit \n Bitfield<27> nmfi;\/\/ Non-maskable fast interrupts enable\n Bitfield<25> ee; \/\/ Exception Endianness bit\n Bitfield<24> ve; \/\/ Interrupt vectors enable\n Bitfield<23> rao1;\/\/ Read as one\n Bitfield<22> u; \/\/ Alignment (now unused)\n Bitfield<21> fi; \/\/ Fast interrupts configuration enable\n Bitfield<18> rao2;\/\/ Read as one\n Bitfield<17> ha; \/\/ Hardware access flag enable\n Bitfield<16> rao3;\/\/ Read as one\n Bitfield<14> rr; \/\/ Round robin cache replacement\n Bitfield<13> v; \/\/ Base address for exception vectors\n Bitfield<12> i; \/\/ instruction cache enable\n Bitfield<11> z; \/\/ branch prediction enable bit\n Bitfield<10> sw; \/\/ Enable swp\/swpb\n Bitfield<6,3> rao4;\/\/ Read as one\n Bitfield<7> b; \/\/ Endianness support (unused) \n Bitfield<2> c; \/\/ Cache enable bit\n Bitfield<1> a; \/\/ Alignment fault checking\n Bitfield<0> m; \/\/ MMU enable bit \n EndBitUnion(SCTLR)\n};\n\n#endif \/\/ __ARCH_ARM_MISCREGS_HH__\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\nnamespace cpu\n{\n\ntemplate\nArray* matmul(const Array &lhs, const Array &rhs,\n af_blas_transpose optLhs, af_blas_transpose optRhs);\ntemplate\nArray* dot(const Array &lhs, const Array &rhs,\n af_blas_transpose optLhs, af_blas_transpose optRhs);\n\n}\nChange required to make blas compile on centos 6#include \n#include \n#include \n#ifdef __APPLE__\n#include \n#else\nextern \"C\" {\n#include \n}\n#endif\n\nnamespace cpu\n{\n\ntemplate\nArray* matmul(const Array &lhs, const Array &rhs,\n af_blas_transpose optLhs, af_blas_transpose optRhs);\ntemplate\nArray* dot(const Array &lhs, const Array &rhs,\n af_blas_transpose optLhs, af_blas_transpose optRhs);\n\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2013 David Edmundson (davidedmundson@kde.org)\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"persondata.h\"\n\n#include \"metacontact_p.h\"\n#include \"personmanager_p.h\"\n#include \"personpluginmanager.h\"\n#include \"basepersonsdatasource.h\"\n#include \"contactmonitor.h\"\n\n#include \n\nnamespace KPeople {\n class PersonDataPrivate {\n public:\n QStringList contactIds;\n MetaContact metaContact;\n QList watchers;\n };\n}\n\nusing namespace KPeople;\n\nKPeople::PersonData::PersonData(const QString &id, QObject* parent):\n QObject(parent),\n d_ptr(new PersonDataPrivate)\n{\n Q_D(PersonData);\n\n QString personId;\n \/\/query DB\n if (id.startsWith(\"kpeople:\/\/\")) {\n personId = id;\n } else {\n personId = PersonManager::instance()->personIdForContact(id);\n }\n d->contactIds = PersonManager::instance()->contactsForPersonId(personId);\n\n KABC::Addressee::Map contacts;\n Q_FOREACH(BasePersonsDataSource *dataSource, PersonPluginManager::dataSourcePlugins()) {\n Q_FOREACH(const QString &contactId, d->contactIds) {\n \/\/FIXME this is terrible.. we have to ask every datasource for the contact\n \/\/future idea: plugins have a method of what their URIs will start with\n \/\/then we keep plugins as a map\n ContactMonitorPtr cw = dataSource->contactMonitor(contactId);\n d->watchers << cw;\n if (!cw->contact().isEmpty()) {\n contacts[contactId] = cw->contact();\n }\n connect(cw.data(), SIGNAL(contactChanged()), SLOT(onContactChanged()));\n }\n }\n\n d->metaContact = MetaContact(personId, contacts);\n}\n\nPersonData::~PersonData()\n{\n delete d_ptr;\n}\n\nKABC::Addressee PersonData::person() const\n{\n Q_D(const PersonData);\n return d->metaContact.personAddressee();\n}\n\nKABC::AddresseeList PersonData::contacts() const\n{\n Q_D(const PersonData);\n return d->metaContact.contacts();\n}\n\nvoid PersonData::onContactChanged()\n{\n Q_D(PersonData);\n\n\n ContactMonitor *watcher = qobject_cast(sender());\n d->metaContact.updateContact(watcher->contactId(), watcher->contact());\n Q_EMIT dataChanged();\n}\nAdd contact id to contactIds if no person exists for that contact id\/*\n Copyright (C) 2013 David Edmundson (davidedmundson@kde.org)\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"persondata.h\"\n\n#include \"metacontact_p.h\"\n#include \"personmanager_p.h\"\n#include \"personpluginmanager.h\"\n#include \"basepersonsdatasource.h\"\n#include \"contactmonitor.h\"\n\n#include \n\nnamespace KPeople {\n class PersonDataPrivate {\n public:\n QStringList contactIds;\n MetaContact metaContact;\n QList watchers;\n };\n}\n\nusing namespace KPeople;\n\nKPeople::PersonData::PersonData(const QString &id, QObject* parent):\n QObject(parent),\n d_ptr(new PersonDataPrivate)\n{\n Q_D(PersonData);\n\n QString personId;\n \/\/query DB\n if (id.startsWith(\"kpeople:\/\/\")) {\n personId = id;\n } else {\n personId = PersonManager::instance()->personIdForContact(id);\n }\n\n if (personId.isEmpty()) {\n d->contactIds = QStringList() << id;\n } else {\n d->contactIds = PersonManager::instance()->contactsForPersonId(personId);\n }\n\n KABC::Addressee::Map contacts;\n Q_FOREACH(BasePersonsDataSource *dataSource, PersonPluginManager::dataSourcePlugins()) {\n Q_FOREACH(const QString &contactId, d->contactIds) {\n \/\/FIXME this is terrible.. we have to ask every datasource for the contact\n \/\/future idea: plugins have a method of what their URIs will start with\n \/\/then we keep plugins as a map\n ContactMonitorPtr cw = dataSource->contactMonitor(contactId);\n d->watchers << cw;\n if (!cw->contact().isEmpty()) {\n contacts[contactId] = cw->contact();\n }\n connect(cw.data(), SIGNAL(contactChanged()), SLOT(onContactChanged()));\n }\n }\n\n d->metaContact = MetaContact(personId, contacts);\n}\n\nPersonData::~PersonData()\n{\n delete d_ptr;\n}\n\nKABC::Addressee PersonData::person() const\n{\n Q_D(const PersonData);\n return d->metaContact.personAddressee();\n}\n\nKABC::AddresseeList PersonData::contacts() const\n{\n Q_D(const PersonData);\n return d->metaContact.contacts();\n}\n\nvoid PersonData::onContactChanged()\n{\n Q_D(PersonData);\n\n\n ContactMonitor *watcher = qobject_cast(sender());\n d->metaContact.updateContact(watcher->contactId(), watcher->contact());\n Q_EMIT dataChanged();\n}\n<|endoftext|>"} {"text":"#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wshorten-64-to-32\"\n#include \n#pragma clang diagnostic pop\n\n#include \"constants.hpp\"\n#include \"dispatcher_utility.hpp\"\n#include \"karabiner_version.h\"\n#include \"logger.hpp\"\n#include \"monitor\/configuration_monitor.hpp\"\n#include \n#include \n#include \n\nnamespace {\nvoid select_profile(const std::string& name) {\n auto wait = pqrs::make_thread_wait();\n krbn::configuration_monitor monitor(krbn::constants::get_user_core_configuration_file_path());\n\n monitor.core_configuration_updated.connect([name, wait](auto&& weak_core_configuration) {\n if (auto core_configuration = weak_core_configuration.lock()) {\n auto& profiles = core_configuration->get_profiles();\n for (size_t i = 0; i < profiles.size(); ++i) {\n if (profiles[i].get_name() == name) {\n core_configuration->select_profile(i);\n core_configuration->sync_save_to_file();\n goto finish;\n }\n }\n krbn::logger::get_logger()->error(\"`{0}` is not found.\", name);\n }\n\n finish:\n wait->notify();\n });\n\n monitor.async_start();\n\n wait->wait_notice();\n}\n\nint copy_current_profile_to_system_default_profile(void) {\n pqrs::filesystem::create_directory_with_intermediate_directories(krbn::constants::get_system_configuration_directory(), 0755);\n pqrs::filesystem::copy(krbn::constants::get_user_core_configuration_file_path(),\n krbn::constants::get_system_core_configuration_file_path());\n return 0;\n}\n\nint remove_system_default_profile(void) {\n if (!pqrs::filesystem::exists(krbn::constants::get_system_core_configuration_file_path())) {\n krbn::logger::get_logger()->error(\"{0} is not found.\", krbn::constants::get_system_core_configuration_file_path());\n return 1;\n }\n if (unlink(krbn::constants::get_system_core_configuration_file_path()) != 0) {\n krbn::logger::get_logger()->error(\"Failed to unlink {0}.\");\n return 1;\n }\n return 0;\n}\n} \/\/ namespace\n\nint main(int argc, char** argv) {\n int exit_code = 0;\n\n krbn::dispatcher_utility::initialize_dispatchers();\n\n {\n auto l = spdlog::stdout_color_mt(\"karabiner_cli\");\n l->set_pattern(\"[%l] %v\");\n l->set_level(spdlog::level::err);\n krbn::logger::set_logger(l);\n }\n\n cxxopts::Options options(\"karabiner_cli\", \"A command line utility of Karabiner-Elements.\");\n\n options.add_options()(\"select-profile\", \"Select a profile by name.\", cxxopts::value());\n options.add_options()(\"copy-current-profile-to-system-default-profile\", \"Copy the current profile to system default profile.\");\n options.add_options()(\"remove-system-default-profile\", \"Remove the system default profile.\");\n options.add_options()(\"version\", \"Displays version.\");\n options.add_options()(\"version-number\", \"Displays version_number.\");\n options.add_options()(\"help\", \"Print help.\");\n\n try {\n auto parse_result = options.parse(argc, argv);\n\n {\n std::string key = \"select-profile\";\n if (parse_result.count(key)) {\n select_profile(parse_result[key].as());\n goto finish;\n }\n }\n\n {\n std::string key = \"copy-current-profile-to-system-default-profile\";\n if (parse_result.count(key)) {\n if (getuid() != 0) {\n krbn::logger::get_logger()->error(\"--{0} requires root privilege.\", key);\n exit_code = 1;\n goto finish;\n }\n exit_code = copy_current_profile_to_system_default_profile();\n goto finish;\n }\n }\n\n {\n std::string key = \"remove-system-default-profile\";\n if (parse_result.count(key)) {\n if (getuid() != 0) {\n krbn::logger::get_logger()->error(\"--{0} requires root privilege.\", key);\n exit_code = 1;\n goto finish;\n }\n exit_code = remove_system_default_profile();\n goto finish;\n }\n }\n\n {\n std::string key = \"version\";\n if (parse_result.count(key)) {\n std::cout << karabiner_version << std::endl;\n goto finish;\n }\n }\n\n {\n std::string key = \"version-number\";\n if (parse_result.count(key)) {\n int n = 0;\n std::string number;\n\n for (const auto& c : std::string_view(karabiner_version)) {\n if (c == '.') {\n if (!number.empty()) {\n n += stoi(number);\n number.clear();\n }\n n *= 100;\n\n } else {\n number += c;\n }\n }\n\n if (!number.empty()) {\n n += stoi(number);\n number.clear();\n }\n\n std::cout << n << std::endl;\n goto finish;\n }\n }\n\n } catch (const cxxopts::OptionException& e) {\n std::cout << \"error parsing options: \" << e.what() << std::endl;\n exit_code = 2;\n goto finish;\n }\n\n std::cout << options.help() << std::endl;\n std::cout << \"Examples:\" << std::endl;\n std::cout << \" karabiner_cli --select-profile 'Default profile'\" << std::endl;\n std::cout << std::endl;\n\n exit_code = 1;\n\nfinish:\n krbn::dispatcher_utility::terminate_dispatchers();\n\n return exit_code;\n}\nadd --lint-complex-modifications to cli#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wshorten-64-to-32\"\n#include \n#pragma clang diagnostic pop\n\n#include \"complex_modifications_assets_file.hpp\"\n#include \"constants.hpp\"\n#include \"dispatcher_utility.hpp\"\n#include \"karabiner_version.h\"\n#include \"logger.hpp\"\n#include \"monitor\/configuration_monitor.hpp\"\n#include \n#include \n#include \n\nnamespace {\nvoid select_profile(const std::string& name) {\n auto wait = pqrs::make_thread_wait();\n krbn::configuration_monitor monitor(krbn::constants::get_user_core_configuration_file_path());\n\n monitor.core_configuration_updated.connect([name, wait](auto&& weak_core_configuration) {\n if (auto core_configuration = weak_core_configuration.lock()) {\n auto& profiles = core_configuration->get_profiles();\n for (size_t i = 0; i < profiles.size(); ++i) {\n if (profiles[i].get_name() == name) {\n core_configuration->select_profile(i);\n core_configuration->sync_save_to_file();\n goto finish;\n }\n }\n krbn::logger::get_logger()->error(\"`{0}` is not found.\", name);\n }\n\n finish:\n wait->notify();\n });\n\n monitor.async_start();\n\n wait->wait_notice();\n}\n\nint copy_current_profile_to_system_default_profile(void) {\n pqrs::filesystem::create_directory_with_intermediate_directories(krbn::constants::get_system_configuration_directory(), 0755);\n pqrs::filesystem::copy(krbn::constants::get_user_core_configuration_file_path(),\n krbn::constants::get_system_core_configuration_file_path());\n return 0;\n}\n\nint remove_system_default_profile(void) {\n if (!pqrs::filesystem::exists(krbn::constants::get_system_core_configuration_file_path())) {\n krbn::logger::get_logger()->error(\"{0} is not found.\", krbn::constants::get_system_core_configuration_file_path());\n return 1;\n }\n if (unlink(krbn::constants::get_system_core_configuration_file_path()) != 0) {\n krbn::logger::get_logger()->error(\"Failed to unlink {0}.\");\n return 1;\n }\n return 0;\n}\n} \/\/ namespace\n\nint main(int argc, char** argv) {\n int exit_code = 0;\n\n krbn::dispatcher_utility::initialize_dispatchers();\n\n {\n auto l = spdlog::stdout_color_mt(\"karabiner_cli\");\n l->set_pattern(\"[%l] %v\");\n l->set_level(spdlog::level::err);\n krbn::logger::set_logger(l);\n }\n\n cxxopts::Options options(\"karabiner_cli\", \"A command line utility of Karabiner-Elements.\");\n\n options.add_options()(\"select-profile\", \"Select a profile by name.\", cxxopts::value());\n options.add_options()(\"copy-current-profile-to-system-default-profile\", \"Copy the current profile to system default profile.\");\n options.add_options()(\"remove-system-default-profile\", \"Remove the system default profile.\");\n options.add_options()(\"lint-complex-modifications\", \"Check complex_modifications.\", cxxopts::value());\n options.add_options()(\"version\", \"Displays version.\");\n options.add_options()(\"version-number\", \"Displays version_number.\");\n options.add_options()(\"help\", \"Print help.\");\n\n try {\n auto parse_result = options.parse(argc, argv);\n\n {\n std::string key = \"select-profile\";\n if (parse_result.count(key)) {\n select_profile(parse_result[key].as());\n goto finish;\n }\n }\n\n {\n std::string key = \"copy-current-profile-to-system-default-profile\";\n if (parse_result.count(key)) {\n if (getuid() != 0) {\n krbn::logger::get_logger()->error(\"--{0} requires root privilege.\", key);\n exit_code = 1;\n goto finish;\n }\n exit_code = copy_current_profile_to_system_default_profile();\n goto finish;\n }\n }\n\n {\n std::string key = \"remove-system-default-profile\";\n if (parse_result.count(key)) {\n if (getuid() != 0) {\n krbn::logger::get_logger()->error(\"--{0} requires root privilege.\", key);\n exit_code = 1;\n goto finish;\n }\n exit_code = remove_system_default_profile();\n goto finish;\n }\n }\n\n {\n std::string key = \"lint-complex-modifications\";\n if (parse_result.count(key)) {\n auto file_path = parse_result[key].as();\n try {\n auto assets_file = krbn::complex_modifications_assets_file(file_path);\n auto error_messages = assets_file.lint();\n if (error_messages.empty()) {\n std::cout << \"ok\" << std::endl;\n\n } else {\n exit_code = 1;\n\n for (const auto& e : error_messages) {\n std::cout << e << std::endl;\n }\n }\n goto finish;\n\n } catch (std::exception& e) {\n exit_code = 1;\n std::cout << e.what() << std::endl;\n goto finish;\n }\n }\n }\n\n {\n std::string key = \"version\";\n if (parse_result.count(key)) {\n std::cout << karabiner_version << std::endl;\n goto finish;\n }\n }\n\n {\n std::string key = \"version-number\";\n if (parse_result.count(key)) {\n int n = 0;\n std::string number;\n\n for (const auto& c : std::string_view(karabiner_version)) {\n if (c == '.') {\n if (!number.empty()) {\n n += stoi(number);\n number.clear();\n }\n n *= 100;\n\n } else {\n number += c;\n }\n }\n\n if (!number.empty()) {\n n += stoi(number);\n number.clear();\n }\n\n std::cout << n << std::endl;\n goto finish;\n }\n }\n\n } catch (const cxxopts::OptionException& e) {\n std::cout << \"error parsing options: \" << e.what() << std::endl;\n exit_code = 2;\n goto finish;\n }\n\n std::cout << options.help() << std::endl;\n std::cout << \"Examples:\" << std::endl;\n std::cout << \" karabiner_cli --select-profile 'Default profile'\" << std::endl;\n std::cout << std::endl;\n\n exit_code = 1;\n\nfinish:\n krbn::dispatcher_utility::terminate_dispatchers();\n\n return exit_code;\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n\n#include \n\n#include \"attribute.hpp\"\n#include \"common.hpp\"\n#include \"error\/handler.hpp\"\n#include \"filter.hpp\"\n#include \"frontend.hpp\"\n#include \"keyword.hpp\"\n#include \"keyword\/message.hpp\"\n#include \"keyword\/severity.hpp\"\n#include \"keyword\/thread.hpp\"\n#include \"keyword\/timestamp.hpp\"\n#include \"keyword\/tracebit.hpp\"\n#include \"universe.hpp\"\n#include \"utils\/noncopyable.hpp\"\n#include \"utils\/unique.hpp\"\n\n#include \"blackhole\/config.hpp\"\n#include \"blackhole\/utils\/atomic.hpp\"\n#include \"blackhole\/utils\/noexcept.hpp\"\n\nnamespace blackhole {\n\nclass scoped_attributes_concept_t;\n\ntemplate \nstruct logger_verbosity_traits {\n typedef Level level_type;\n\n static\n bool\n passed(level_type logger_verbosity, level_type record_verbosity) {\n typedef typename aux::underlying_type::type underlying_type;\n\n return static_cast(record_verbosity) >=\n static_cast(logger_verbosity);\n }\n};\n\nclass logger_base_t {\nprotected:\n typedef boost::shared_mutex rw_mutex_type;\n typedef boost::shared_lock reader_lock_type;\n typedef boost::unique_lock writer_lock_type;\n\n struct state_t {\n std::atomic enabled;\n std::atomic tracked;\n\n filter_t filter;\n struct attrbutes_t {\n attribute::set_t global;\n boost::thread_specific_ptr scoped;\n\n attrbutes_t(void(*deleter)(scoped_attributes_concept_t*)) :\n scoped(deleter)\n {}\n } attributes;\n\n std::vector> frontends;\n log::exception_handler_t exception;\n\n struct {\n mutable rw_mutex_type open;\n mutable rw_mutex_type push;\n } lock;\n\n state_t();\n };\n state_t state;\n\n friend class scoped_attributes_concept_t;\n\n friend void swap(logger_base_t& lhs, logger_base_t& rhs) BLACKHOLE_NOEXCEPT;\n\npublic:\n logger_base_t();\n\n \/\/! @compat GCC4.4\n \/\/! Blaming GCC4.4 - it needs explicit move constructor definition,\n \/\/! because it cannot define default move constructor for derived class.\n logger_base_t(logger_base_t&& other) BLACKHOLE_NOEXCEPT;\n logger_base_t& operator=(logger_base_t&& other) BLACKHOLE_NOEXCEPT;\n\n bool enabled() const;\n void enabled(bool enable);\n\n bool tracked() const;\n void tracked(bool enable);\n\n void set_filter(filter_t&& filter);\n void add_attribute(const attribute::pair_t& attribute);\n void add_frontend(std::unique_ptr frontend);\n void set_exception_handler(log::exception_handler_t&& handler);\n\n record_t open_record() const;\n record_t open_record(attribute::pair_t attribute) const;\n record_t open_record(attribute::set_t attributes) const;\n\n void push(record_t&& record) const;\n\nprivate:\n attribute::set_t get_event_attributes() const;\n attribute::set_t get_thread_attributes() const;\n};\n\n\/\/!@todo: Develop ImmutableLogger class, which provides almost immutable\n\/\/! internal state (filter, exception handler, frontends).\n\/\/! This class won't require any synchronization mechanizm.\n\n\/\/ NOTE: It's not movable to avoid moving to another thread.\nclass scoped_attributes_concept_t {\n BLACKHOLE_DECLARE_NONCOPYABLE(scoped_attributes_concept_t);\n\n logger_base_t *m_logger;\n scoped_attributes_concept_t *m_previous;\n\n friend void swap(logger_base_t&, logger_base_t&) BLACKHOLE_NOEXCEPT;\n\npublic:\n scoped_attributes_concept_t(logger_base_t& log);\n virtual ~scoped_attributes_concept_t();\n\n virtual const attribute::set_t& attributes() const = 0;\n\nprotected:\n bool has_parent() const;\n const scoped_attributes_concept_t& parent() const;\n};\n\ntemplate\nclass verbose_logger_t : public logger_base_t {\npublic:\n typedef Level level_type;\n\nprivate:\n level_type level;\n\npublic:\n verbose_logger_t() :\n logger_base_t(),\n level(static_cast(0))\n {}\n\n \/\/! @compat GCC4.4\n \/\/! GCC 4.4 doesn't create default copy\/move constructor for derived\n \/\/! classes. It's a bug.\n verbose_logger_t(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT :\n logger_base_t(std::move(other)),\n level(static_cast(0))\n {}\n\n verbose_logger_t& operator=(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT {\n logger_base_t::operator=(std::move(other));\n level = other.level;\n return *this;\n }\n\n \/\/ Explicit import other overloaded methods.\n using logger_base_t::open_record;\n\n \/*!\n * Gets the current upper verbosity bound.\n *\/\n level_type verbosity() const {\n return level;\n }\n\n \/*!\n * Sets the upper verbosity bound.\n * Every log event with a verbosity less than `level` will be dropped.\n * @param[in] level - Upper verbosity value.\n *\/\n void verbosity(level_type level) {\n this->level = level;\n }\n\n \/*! @todo: Documentation is @deprecated.\n * Tries to open log record with specific verbosity level.\n * Internally this method compares desired verbosity level with the upper\n * one. Can return invalid log record if some conditions are not met.\n * @param[in] level - Desired verbosity level.\n * @return valid or invalid `record_t` object.\n *\/\n record_t\n open_record(level_type level,\n attribute::set_t local = attribute::set_t()) const\n {\n typedef logger_verbosity_traits verbosity_traits;\n const bool passed = verbosity_traits::passed(this->level, level);\n\n bool trace = false;\n if (!passed) {\n auto it = local.find(keyword::tracebit().name());\n if (it != local.end()) {\n trace = boost::get(it->second.value);\n } else {\n reader_lock_type lock(state.lock.open);\n if (state.attributes.scoped.get()) {\n const auto& scoped = state.attributes.scoped->attributes();\n auto scoped_it = scoped.find(keyword::tracebit().name());\n if (scoped_it != scoped.end()) {\n trace = boost::get(\n scoped_it->second.value\n );\n }\n }\n }\n }\n\n if (passed || trace) {\n attribute::set_t attributes = { keyword::severity() = level };\n attributes.insert(local.begin(), local.end());\n return logger_base_t::open_record(std::move(attributes));\n }\n\n return record_t();\n }\n};\n\n} \/\/ namespace blackhole\n\n#if defined(BLACKHOLE_HEADER_ONLY)\n#include \"blackhole\/logger.ipp\"\n#endif\n[Aux] Do not create temporary set just for single variable.#pragma once\n\n#include \n#include \n\n#include \n\n#include \"attribute.hpp\"\n#include \"common.hpp\"\n#include \"error\/handler.hpp\"\n#include \"filter.hpp\"\n#include \"frontend.hpp\"\n#include \"keyword.hpp\"\n#include \"keyword\/message.hpp\"\n#include \"keyword\/severity.hpp\"\n#include \"keyword\/thread.hpp\"\n#include \"keyword\/timestamp.hpp\"\n#include \"keyword\/tracebit.hpp\"\n#include \"universe.hpp\"\n#include \"utils\/noncopyable.hpp\"\n#include \"utils\/unique.hpp\"\n\n#include \"blackhole\/config.hpp\"\n#include \"blackhole\/utils\/atomic.hpp\"\n#include \"blackhole\/utils\/noexcept.hpp\"\n\nnamespace blackhole {\n\nclass scoped_attributes_concept_t;\n\ntemplate \nstruct logger_verbosity_traits {\n typedef Level level_type;\n\n static\n bool\n passed(level_type logger_verbosity, level_type record_verbosity) {\n typedef typename aux::underlying_type::type underlying_type;\n\n return static_cast(record_verbosity) >=\n static_cast(logger_verbosity);\n }\n};\n\nclass logger_base_t {\nprotected:\n typedef boost::shared_mutex rw_mutex_type;\n typedef boost::shared_lock reader_lock_type;\n typedef boost::unique_lock writer_lock_type;\n\n struct state_t {\n std::atomic enabled;\n std::atomic tracked;\n\n filter_t filter;\n struct attrbutes_t {\n attribute::set_t global;\n boost::thread_specific_ptr scoped;\n\n attrbutes_t(void(*deleter)(scoped_attributes_concept_t*)) :\n scoped(deleter)\n {}\n } attributes;\n\n std::vector> frontends;\n log::exception_handler_t exception;\n\n struct {\n mutable rw_mutex_type open;\n mutable rw_mutex_type push;\n } lock;\n\n state_t();\n };\n state_t state;\n\n friend class scoped_attributes_concept_t;\n\n friend void swap(logger_base_t& lhs, logger_base_t& rhs) BLACKHOLE_NOEXCEPT;\n\npublic:\n logger_base_t();\n\n \/\/! @compat GCC4.4\n \/\/! Blaming GCC4.4 - it needs explicit move constructor definition,\n \/\/! because it cannot define default move constructor for derived class.\n logger_base_t(logger_base_t&& other) BLACKHOLE_NOEXCEPT;\n logger_base_t& operator=(logger_base_t&& other) BLACKHOLE_NOEXCEPT;\n\n bool enabled() const;\n void enabled(bool enable);\n\n bool tracked() const;\n void tracked(bool enable);\n\n void set_filter(filter_t&& filter);\n void add_attribute(const attribute::pair_t& attribute);\n void add_frontend(std::unique_ptr frontend);\n void set_exception_handler(log::exception_handler_t&& handler);\n\n record_t open_record() const;\n record_t open_record(attribute::pair_t attribute) const;\n record_t open_record(attribute::set_t attributes) const;\n\n void push(record_t&& record) const;\n\nprivate:\n attribute::set_t get_event_attributes() const;\n attribute::set_t get_thread_attributes() const;\n};\n\n\/\/!@todo: Develop ImmutableLogger class, which provides almost immutable\n\/\/! internal state (filter, exception handler, frontends).\n\/\/! This class won't require any synchronization mechanizm.\n\n\/\/ NOTE: It's not movable to avoid moving to another thread.\nclass scoped_attributes_concept_t {\n BLACKHOLE_DECLARE_NONCOPYABLE(scoped_attributes_concept_t);\n\n logger_base_t *m_logger;\n scoped_attributes_concept_t *m_previous;\n\n friend void swap(logger_base_t&, logger_base_t&) BLACKHOLE_NOEXCEPT;\n\npublic:\n scoped_attributes_concept_t(logger_base_t& log);\n virtual ~scoped_attributes_concept_t();\n\n virtual const attribute::set_t& attributes() const = 0;\n\nprotected:\n bool has_parent() const;\n const scoped_attributes_concept_t& parent() const;\n};\n\ntemplate\nclass verbose_logger_t : public logger_base_t {\npublic:\n typedef Level level_type;\n\nprivate:\n level_type level;\n\npublic:\n verbose_logger_t() :\n logger_base_t(),\n level(static_cast(0))\n {}\n\n \/\/! @compat GCC4.4\n \/\/! GCC 4.4 doesn't create default copy\/move constructor for derived\n \/\/! classes. It's a bug.\n verbose_logger_t(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT :\n logger_base_t(std::move(other)),\n level(static_cast(0))\n {}\n\n verbose_logger_t& operator=(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT {\n logger_base_t::operator=(std::move(other));\n level = other.level;\n return *this;\n }\n\n \/\/ Explicit import other overloaded methods.\n using logger_base_t::open_record;\n\n \/*!\n * Gets the current upper verbosity bound.\n *\/\n level_type verbosity() const {\n return level;\n }\n\n \/*!\n * Sets the upper verbosity bound.\n * Every log event with a verbosity less than `level` will be dropped.\n * @param[in] level - Upper verbosity value.\n *\/\n void verbosity(level_type level) {\n this->level = level;\n }\n\n \/*! @todo: Documentation is @deprecated.\n * Tries to open log record with specific verbosity level.\n * Internally this method compares desired verbosity level with the upper\n * one. Can return invalid log record if some conditions are not met.\n * @param[in] level - Desired verbosity level.\n * @return valid or invalid `record_t` object.\n *\/\n record_t\n open_record(level_type level,\n attribute::set_t local = attribute::set_t()) const\n {\n typedef logger_verbosity_traits verbosity_traits;\n const bool passed = verbosity_traits::passed(this->level, level);\n\n bool trace = false;\n if (!passed) {\n auto it = local.find(keyword::tracebit().name());\n if (it != local.end()) {\n trace = boost::get(it->second.value);\n } else {\n reader_lock_type lock(state.lock.open);\n if (state.attributes.scoped.get()) {\n const auto& scoped = state.attributes.scoped->attributes();\n auto scoped_it = scoped.find(keyword::tracebit().name());\n if (scoped_it != scoped.end()) {\n trace = boost::get(\n scoped_it->second.value\n );\n }\n }\n }\n }\n\n if (passed || trace) {\n local.insert(keyword::severity() = level);\n return logger_base_t::open_record(std::move(local));\n }\n\n return record_t();\n }\n};\n\n} \/\/ namespace blackhole\n\n#if defined(BLACKHOLE_HEADER_ONLY)\n#include \"blackhole\/logger.ipp\"\n#endif\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n\n#include \n#include \n\n#include \"blackhole\/attribute.hpp\"\n#include \"blackhole\/config.hpp\"\n#include \"blackhole\/detail\/config\/atomic.hpp\"\n#include \"blackhole\/detail\/config\/noncopyable.hpp\"\n#include \"blackhole\/detail\/config\/nullptr.hpp\"\n#include \"blackhole\/detail\/thread\/lock.hpp\"\n#include \"blackhole\/detail\/util\/unique.hpp\"\n#include \"blackhole\/error\/handler.hpp\"\n#include \"blackhole\/forwards.hpp\"\n#include \"blackhole\/filter.hpp\"\n#include \"blackhole\/frontend.hpp\"\n#include \"blackhole\/keyword\/message.hpp\"\n#include \"blackhole\/keyword\/severity.hpp\"\n#include \"blackhole\/keyword\/thread.hpp\"\n#include \"blackhole\/keyword\/timestamp.hpp\"\n#include \"blackhole\/keyword\/tracebit.hpp\"\n#include \"blackhole\/keyword\/process.hpp\"\n#include \"blackhole\/logger\/feature\/scoped.hpp\"\n\nnamespace blackhole {\n\nclass base_logger_t {};\n\ntemplate\nclass composite_logger_t : public base_logger_t {\n friend class scoped_attributes_concept_t;\n\npublic:\n typedef T mixed_type;\n\n typedef std::function filter_type;\n\n typedef boost::shared_mutex rw_mutex_type;\n typedef boost::shared_lock reader_lock_type;\n typedef boost::unique_lock writer_lock_type;\n\n \/\/ TODO: Doc!\n typedef feature::scoped_t scoped_type;\n\nprivate:\n feature::scoped_t scoped;\n\n struct {\n std::atomic enabled;\n\n filter_type filter;\n\n log::exception_handler_t exception;\n std::vector> frontends;\n\n struct {\n mutable rw_mutex_type open;\n mutable rw_mutex_type push;\n } lock;\n } d;\n\npublic:\n composite_logger_t(filter_type filter) {\n d.enabled = true;\n d.exception = log::default_exception_handler_t();\n d.filter = std::move(filter);\n }\n\n composite_logger_t(composite_logger_t&& other) {\n *this = std::move(other);\n }\n\n composite_logger_t& operator=(composite_logger_t&& other) {\n other.d.enabled = d.enabled.exchange(other.d.enabled);\n\n auto lock = detail::thread::multi_lock(d.lock.open, d.lock.push, other.d.lock.open, other.d.lock.push);\n\n using std::swap;\n swap(d.filter, other.d.filter);\n swap(d.frontends, other.d.frontends);\n\n scoped.swap(other.scoped);\n\n return *this;\n }\n\n bool enabled() const {\n return d.enabled;\n }\n\n void enabled(bool enable) {\n d.enabled.store(enable);\n }\n\n void set_filter(filter_type filter) {\n writer_lock_type lock(d.lock.open);\n d.filter = std::move(filter);\n }\n\n void add_frontend(std::unique_ptr frontend) {\n writer_lock_type lock(d.lock.push);\n d.frontends.push_back(std::move(frontend));\n }\n\n void set_exception_handler(log::exception_handler_t handler) {\n writer_lock_type lock(d.lock.push);\n d.exception = handler;\n }\n\n record_t open_record(FilterArgs... args) const {\n return open_record(attribute::set_t(), std::forward(args)...);\n }\n\n record_t open_record(attribute::pair_t pair, FilterArgs... args) const {\n return open_record(attribute::set_t({ pair }), std::forward(args)...);\n }\n\n record_t open_record(attribute::set_t external, FilterArgs... args) const {\n if (!enabled()) {\n return record_t::invalid();\n }\n\n reader_lock_type lock(d.lock.open);\n if (!d.filter(scoped.view(external), args...)) {\n return record_t::invalid();\n }\n\n attribute::set_t internal;\n populate(internal);\n static_cast(*this).populate_additional(internal, args...);\n\n external.reserve(BLACKHOLE_EXTERNAL_SET_RESERVED_SIZE);\n scoped.merge(external);\n return record_t(std::move(internal), std::move(external));\n }\n\n void push(record_t&& record) const {\n reader_lock_type lock(d.lock.push);\n for (auto it = d.frontends.begin(); it != d.frontends.end(); ++it) {\n try {\n (*it)->handle(record);\n } catch (...) {\n d.exception();\n }\n }\n }\n\nprivate:\n void populate(attribute::set_t& internal) const {\n internal.reserve(BLACKHOLE_INTERNAL_SET_RESERVED_SIZE);\n#ifdef BLACKHOLE_HAS_ATTRIBUTE_PID\n internal.emplace_back(keyword::pid() = keyword::init::pid());\n#endif\n\n#ifdef BLACKHOLE_HAS_ATTRIBUTE_TID\n internal.emplace_back(keyword::tid() = keyword::init::tid());\n#endif\n\n#ifdef BLACKHOLE_HAS_ATTRIBUTE_LWP\n internal.emplace_back(keyword::lwp() = keyword::init::lwp());\n#endif\n\n internal.emplace_back(keyword::timestamp() = keyword::init::timestamp());\n }\n};\n\nclass logger_base_t : public composite_logger_t {\n friend class composite_logger_t;\n\n typedef composite_logger_t base_type;\n\npublic:\n logger_base_t() :\n base_type(&filter::none)\n {}\n\n#ifdef BLACKHOLE_HAS_GCC44\n logger_base_t(logger_base_t&& other) : base_type(std::move(other)) {}\n logger_base_t& operator=(logger_base_t&& other) {\n base_type::operator=(std::move(other));\n return *this;\n }\n#endif\n\nprivate:\n void populate_additional(attribute::set_t&) const {}\n};\n\ntemplate\nclass verbose_logger_t : public composite_logger_t, Level> {\n friend class composite_logger_t, Level>;\n\n typedef composite_logger_t, Level> base_type;\n\npublic:\n typedef Level level_type;\n typedef typename aux::underlying_type::type underlying_type;\n\nprivate:\n std::atomic level;\n\npublic:\n verbose_logger_t(level_type level) :\n base_type(default_filter { level }),\n level(static_cast(level))\n {}\n\n verbose_logger_t(verbose_logger_t&& other) :\n base_type(std::move(other)),\n level(other.level.load())\n {}\n\n verbose_logger_t& operator=(verbose_logger_t&& other) {\n base_type::operator=(std::move(other));\n level.store(other.level);\n return *this;\n }\n\n level_type verbosity() const {\n return static_cast(level.load());\n }\n\n void set_filter(level_type level) {\n base_type::set_filter(default_filter { level });\n this->level.store(level);\n }\n\n void set_filter(level_type level, typename base_type::filter_type filter) {\n base_type::set_filter(std::move(filter));\n this->level.store(level);\n }\n\n record_t open_record(level_type level, attribute::set_t external = attribute::set_t()) const {\n return base_type::open_record(std::move(external), level);\n }\n\nprivate:\n void populate_additional(attribute::set_t& internal, level_type level) const {\n internal.emplace_back(keyword::severity() = level);\n }\n\n struct default_filter {\n const level_type threshold;\n\n inline bool operator()(const attribute::combined_view_t&, level_type level) const {\n typedef typename aux::underlying_type::type underlying_type;\n return static_cast(level) >= static_cast(threshold);\n }\n };\n\n};\n\n} \/\/ namespace blackhole\n[Planning] Slightly changed my mind.#pragma once\n\n#include \n#include \n\n#include \n#include \n\n#include \"blackhole\/attribute.hpp\"\n#include \"blackhole\/config.hpp\"\n#include \"blackhole\/detail\/config\/atomic.hpp\"\n#include \"blackhole\/detail\/config\/noncopyable.hpp\"\n#include \"blackhole\/detail\/config\/nullptr.hpp\"\n#include \"blackhole\/detail\/thread\/lock.hpp\"\n#include \"blackhole\/detail\/util\/unique.hpp\"\n#include \"blackhole\/error\/handler.hpp\"\n#include \"blackhole\/forwards.hpp\"\n#include \"blackhole\/filter.hpp\"\n#include \"blackhole\/frontend.hpp\"\n#include \"blackhole\/keyword\/message.hpp\"\n#include \"blackhole\/keyword\/severity.hpp\"\n#include \"blackhole\/keyword\/thread.hpp\"\n#include \"blackhole\/keyword\/timestamp.hpp\"\n#include \"blackhole\/keyword\/tracebit.hpp\"\n#include \"blackhole\/keyword\/process.hpp\"\n#include \"blackhole\/logger\/feature\/scoped.hpp\"\n\nnamespace blackhole {\n\nclass base_logger_t {};\n\ntemplate\nclass composite_logger_t : public base_logger_t {\n friend class scoped_attributes_concept_t;\n\npublic:\n typedef T mixed_type;\n\n typedef std::function filter_type;\n\n typedef boost::shared_mutex rw_mutex_type;\n typedef boost::shared_lock reader_lock_type;\n typedef boost::unique_lock writer_lock_type;\n\n typedef feature::scoped_t scoped_type;\n\nprivate:\n feature::scoped_t scoped;\n\n struct {\n std::atomic enabled;\n\n filter_type filter;\n\n log::exception_handler_t exception;\n std::vector> frontends;\n\n struct {\n mutable rw_mutex_type open;\n mutable rw_mutex_type push;\n } lock;\n } d;\n\npublic:\n composite_logger_t(filter_type filter) {\n d.enabled = true;\n d.exception = log::default_exception_handler_t();\n d.filter = std::move(filter);\n }\n\n composite_logger_t(composite_logger_t&& other) {\n *this = std::move(other);\n }\n\n composite_logger_t& operator=(composite_logger_t&& other) {\n other.d.enabled = d.enabled.exchange(other.d.enabled);\n\n auto lock = detail::thread::multi_lock(d.lock.open, d.lock.push, other.d.lock.open, other.d.lock.push);\n\n using std::swap;\n swap(d.filter, other.d.filter);\n swap(d.frontends, other.d.frontends);\n\n scoped.swap(other.scoped);\n\n return *this;\n }\n\n bool enabled() const {\n return d.enabled;\n }\n\n void enabled(bool enable) {\n d.enabled.store(enable);\n }\n\n void set_filter(filter_type filter) {\n writer_lock_type lock(d.lock.open);\n d.filter = std::move(filter);\n }\n\n void add_frontend(std::unique_ptr frontend) {\n writer_lock_type lock(d.lock.push);\n d.frontends.push_back(std::move(frontend));\n }\n\n void set_exception_handler(log::exception_handler_t handler) {\n writer_lock_type lock(d.lock.push);\n d.exception = handler;\n }\n\n record_t open_record(FilterArgs... args) const {\n return open_record(attribute::set_t(), std::forward(args)...);\n }\n\n record_t open_record(attribute::pair_t pair, FilterArgs... args) const {\n return open_record(attribute::set_t({ pair }), std::forward(args)...);\n }\n\n record_t open_record(attribute::set_t external, FilterArgs... args) const {\n if (!enabled()) {\n return record_t::invalid();\n }\n\n reader_lock_type lock(d.lock.open);\n if (!d.filter(scoped.view(external), args...)) {\n return record_t::invalid();\n }\n\n attribute::set_t internal;\n populate(internal);\n static_cast(*this).populate_additional(internal, args...);\n\n external.reserve(BLACKHOLE_EXTERNAL_SET_RESERVED_SIZE);\n scoped.merge(external);\n return record_t(std::move(internal), std::move(external));\n }\n\n void push(record_t&& record) const {\n reader_lock_type lock(d.lock.push);\n for (auto it = d.frontends.begin(); it != d.frontends.end(); ++it) {\n try {\n (*it)->handle(record);\n } catch (...) {\n d.exception();\n }\n }\n }\n\nprivate:\n void populate(attribute::set_t& internal) const {\n internal.reserve(BLACKHOLE_INTERNAL_SET_RESERVED_SIZE);\n#ifdef BLACKHOLE_HAS_ATTRIBUTE_PID\n internal.emplace_back(keyword::pid() = keyword::init::pid());\n#endif\n\n#ifdef BLACKHOLE_HAS_ATTRIBUTE_TID\n internal.emplace_back(keyword::tid() = keyword::init::tid());\n#endif\n\n#ifdef BLACKHOLE_HAS_ATTRIBUTE_LWP\n internal.emplace_back(keyword::lwp() = keyword::init::lwp());\n#endif\n\n internal.emplace_back(keyword::timestamp() = keyword::init::timestamp());\n }\n};\n\nclass logger_base_t : public composite_logger_t {\n friend class composite_logger_t;\n\n typedef composite_logger_t base_type;\n\npublic:\n logger_base_t() :\n base_type(&filter::none)\n {}\n\n#ifdef BLACKHOLE_HAS_GCC44\n logger_base_t(logger_base_t&& other) : base_type(std::move(other)) {}\n logger_base_t& operator=(logger_base_t&& other) {\n base_type::operator=(std::move(other));\n return *this;\n }\n#endif\n\nprivate:\n void populate_additional(attribute::set_t&) const {}\n};\n\ntemplate\nclass verbose_logger_t : public composite_logger_t, Level> {\n friend class composite_logger_t, Level>;\n\n typedef composite_logger_t, Level> base_type;\n\npublic:\n typedef Level level_type;\n typedef typename aux::underlying_type::type underlying_type;\n\nprivate:\n std::atomic level;\n\npublic:\n verbose_logger_t(level_type level) :\n base_type(default_filter { level }),\n level(static_cast(level))\n {}\n\n verbose_logger_t(verbose_logger_t&& other) :\n base_type(std::move(other)),\n level(other.level.load())\n {}\n\n verbose_logger_t& operator=(verbose_logger_t&& other) {\n base_type::operator=(std::move(other));\n level.store(other.level);\n return *this;\n }\n\n level_type verbosity() const {\n return static_cast(level.load());\n }\n\n void set_filter(level_type level) {\n base_type::set_filter(default_filter { level });\n this->level.store(level);\n }\n\n void set_filter(level_type level, typename base_type::filter_type filter) {\n base_type::set_filter(std::move(filter));\n this->level.store(level);\n }\n\n record_t open_record(level_type level, attribute::set_t external = attribute::set_t()) const {\n return base_type::open_record(std::move(external), level);\n }\n\nprivate:\n void populate_additional(attribute::set_t& internal, level_type level) const {\n internal.emplace_back(keyword::severity() = level);\n }\n\n struct default_filter {\n const level_type threshold;\n\n inline bool operator()(const attribute::combined_view_t&, level_type level) const {\n typedef typename aux::underlying_type::type underlying_type;\n return static_cast(level) >= static_cast(threshold);\n }\n };\n\n};\n\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"pulseTrain.hpp\"\n\nstd::ostream& operator<<(std::ostream & os, const freqPulse& pulse) {\n\tos << \"Pulse \" << pulse._frequency << \"MHz for \" << pulse._duration << \"ns with amplitude of \" << pulse._amplitude;\n\tos << \" and phase \" << pulse._phase << \"*pi\";\n\tos << (pulse._markStart ? \", with \" : \", without \") << \"initial marker and \";\n\tos << (pulse._markDuration ? \"with \" : \"without \") << \"duration marker.\";\n\treturn os;\n}\n\nstd::string freqPulse::markerChars(const unsigned int numPoints, unsigned int startMarkerPoints){\n\tstd::string markerChars = \"\";\n\tmarkerChars.reserve(numPoints+1);\n\n\tif ( startMarkerPoints > numPoints ) startMarkerPoints = numPoints;\n\n\tif ( ! _markStart ) {\n\t\tunsigned char durationOnly = (_markDuration ? 0x01 : 0x00);\n\t\tfor (unsigned int i = 0; i < numPoints; i++) markerChars += durationOnly;\n\t} else {\n\t\tunsigned char startPart\t= (_markDuration ? 0x03 : 0x02);\n\t\tunsigned char endPart\t= (_markDuration ? 0x01 : 0x00);\n\t\tunsigned int i;\n\n\t\tfor (i = 0; i < startMarkerPoints; i++) markerChars += startPart;\n\t\tfor (i = startMarkerPoints; i < numPoints; i++) markerChars += endPart;\n\t}\n\n\treturn markerChars;\n}\n\nunsigned int freqPulse::numPoints(const double samplePeriod, const bool nearestHalfCycle) {\n\tif (! nearestHalfCycle) return ((unsigned int) _duration\/samplePeriod);\n\n\tdouble halfCycles = round(_duration * _frequency * 2.0 * 0.001 \/*ns*MHz*\/) \/ 2.0;\n\treturn (unsigned int) floor(halfCycles * (1000.0\/_frequency)\/samplePeriod);\n}\n\n\nstd::string freqPulse::waveChars(const double samplePeriod, const unsigned int numPoints) {\n\tunsigned char waveBuffer[numPoints];\n\tconst double TwoPi = 6.28318530717958647692; \/\/ NOT tau, that's just wrong\n\tconst double phasePerSample = TwoPi * _frequency * samplePeriod * 0.001 \/* ns * MHz*\/;\n\n\tfor (unsigned int i = 0; i < numPoints; i++) {\n\t\tstatic double point;\n\t\tpoint = 127.0 + (127.0 * _amplitude * sin(phasePerSample * ((double) i) + _phase));\n\t\twaveBuffer[i] = (unsigned char) round(point);\n\t}\n\n\treturn std::string((char *) waveBuffer, numPoints);\n}\n\nstd::string pulseTrain::markerChars(const double samplePeriod, const unsigned int numPoints, const bool nearestHalfCycle, const unsigned int startMarkerPoints) {\n\tstd::string firstString = \"\";\n\tstd::string secondString = \"\";\n\t\n\tfirstString.reserve(numPoints+1);\n\tsecondString.reserve(numPoints+1);\n\n\tint shiftAmount = ((int) round(_cyclicShift\/samplePeriod));\n\tint firstLength = ((shiftAmount >= 0) ? (numPoints - shiftAmount) : (-shiftAmount))%numPoints; \n\t\n\tstd::deque::iterator thisPulse = _pulses.begin();\n\tfor (thisPulse = _pulses.begin(); thisPulse != _pulses.end(); thisPulse++) {\n\t\tfirstString += thisPulse->markerChars(thisPulse->numPoints(samplePeriod, nearestHalfCycle), startMarkerPoints);\n\t\tif ( firstString.length() > firstLength ) {\n\t\t\tsecondString = firstString.substr(firstLength);\n\t\t\tfirstString = firstString.erase(firstLength);\n\t\t\tthisPulse++;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tfor (; thisPulse != _pulses.end(); thisPulse++) {\n\t\tsecondString += thisPulse->markerChars(thisPulse->numPoints(samplePeriod, nearestHalfCycle), startMarkerPoints);\n\t}\n\n\tsecondString += firstString;\n\n\treturn secondString;\n}\n\nstd::string pulseTrain::waveChars(const double samplePeriod, const unsigned int numPoints, const bool nearestHalfCycle) {\n\tstd::string firstString = \"\";\n\tstd::string secondString = \"\";\n\t\n\tfirstString.reserve(numPoints+1);\n\tsecondString.reserve(numPoints+1);\n\n\tint shiftAmount = ((int) round(_cyclicShift\/samplePeriod));\n\tint firstLength = ((shiftAmount >= 0) ? (numPoints - shiftAmount) : (-shiftAmount))%numPoints; \n\t\n\tstd::deque::iterator thisPulse = _pulses.begin();\n\tfor (thisPulse = _pulses.begin(); thisPulse != _pulses.end(); thisPulse++) {\n\t\tfirstString += thisPulse->waveChars(samplePeriod, thisPulse->numPoints(samplePeriod, nearestHalfCycle));\n\t\tif ( firstString.length() > firstLength ) {\n\t\t\tsecondString = firstString.substr(firstLength);\n\t\t\tfirstString = firstString.erase(firstLength);\n\t\t\tthisPulse++;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tfor (; thisPulse != _pulses.end(); thisPulse++) {\n\t\tsecondString += thisPulse->waveChars(samplePeriod, thisPulse->numPoints(samplePeriod, nearestHalfCycle));\n\t}\n\n\tsecondString += firstString;\n\n\treturn secondString;\n}\n\nunsigned int pulseTrain::numPoints(const double samplePeriod, const bool nearestHalfCycle) {\n\tunsigned int totalPoints = 0;\n\n\tfor (std::deque::iterator thisPulse = _pulses.begin(); thisPulse != _pulses.end(); thisPulse++) {\n\t\ttotalPoints += thisPulse->numPoints(samplePeriod, nearestHalfCycle);\n\t}\n\n\treturn totalPoints;\n}\nAdd unsigned type to clear -Wsign-compare#include \n#include \n#include \n\n#include \"pulseTrain.hpp\"\n\nstd::ostream& operator<<(std::ostream & os, const freqPulse& pulse) {\n\tos << \"Pulse \" << pulse._frequency << \"MHz for \" << pulse._duration << \"ns with amplitude of \" << pulse._amplitude;\n\tos << \" and phase \" << pulse._phase << \"*pi\";\n\tos << (pulse._markStart ? \", with \" : \", without \") << \"initial marker and \";\n\tos << (pulse._markDuration ? \"with \" : \"without \") << \"duration marker.\";\n\treturn os;\n}\n\nstd::string freqPulse::markerChars(const unsigned int numPoints, unsigned int startMarkerPoints){\n\tstd::string markerChars = \"\";\n\tmarkerChars.reserve(numPoints+1);\n\n\tif ( startMarkerPoints > numPoints ) startMarkerPoints = numPoints;\n\n\tif ( ! _markStart ) {\n\t\tunsigned char durationOnly = (_markDuration ? 0x01 : 0x00);\n\t\tfor (unsigned int i = 0; i < numPoints; i++) markerChars += durationOnly;\n\t} else {\n\t\tunsigned char startPart\t= (_markDuration ? 0x03 : 0x02);\n\t\tunsigned char endPart\t= (_markDuration ? 0x01 : 0x00);\n\t\tunsigned int i;\n\n\t\tfor (i = 0; i < startMarkerPoints; i++) markerChars += startPart;\n\t\tfor (i = startMarkerPoints; i < numPoints; i++) markerChars += endPart;\n\t}\n\n\treturn markerChars;\n}\n\nunsigned int freqPulse::numPoints(const double samplePeriod, const bool nearestHalfCycle) {\n\tif (! nearestHalfCycle) return ((unsigned int) _duration\/samplePeriod);\n\n\tdouble halfCycles = round(_duration * _frequency * 2.0 * 0.001 \/*ns*MHz*\/) \/ 2.0;\n\treturn (unsigned int) floor(halfCycles * (1000.0\/_frequency)\/samplePeriod);\n}\n\n\nstd::string freqPulse::waveChars(const double samplePeriod, const unsigned int numPoints) {\n\tunsigned char waveBuffer[numPoints];\n\tconst double TwoPi = 6.28318530717958647692; \/\/ NOT tau, that's just wrong\n\tconst double phasePerSample = TwoPi * _frequency * samplePeriod * 0.001 \/* ns * MHz*\/;\n\n\tfor (unsigned int i = 0; i < numPoints; i++) {\n\t\tstatic double point;\n\t\tpoint = 127.0 + (127.0 * _amplitude * sin(phasePerSample * ((double) i) + _phase));\n\t\twaveBuffer[i] = (unsigned char) round(point);\n\t}\n\n\treturn std::string((char *) waveBuffer, numPoints);\n}\n\nstd::string pulseTrain::markerChars(const double samplePeriod, const unsigned int numPoints, const bool nearestHalfCycle, const unsigned int startMarkerPoints) {\n\tstd::string firstString = \"\";\n\tstd::string secondString = \"\";\n\t\n\tfirstString.reserve(numPoints+1);\n\tsecondString.reserve(numPoints+1);\n\n\tint shiftAmount = ((int) round(_cyclicShift\/samplePeriod));\n\tunsigned int firstLength = ((shiftAmount >= 0) ? (numPoints - shiftAmount) : (-shiftAmount))%numPoints;\n\t\n\tstd::deque::iterator thisPulse = _pulses.begin();\n\tfor (thisPulse = _pulses.begin(); thisPulse != _pulses.end(); thisPulse++) {\n\t\tfirstString += thisPulse->markerChars(thisPulse->numPoints(samplePeriod, nearestHalfCycle), startMarkerPoints);\n\t\tif ( firstString.length() > firstLength ) {\n\t\t\tsecondString = firstString.substr(firstLength);\n\t\t\tfirstString = firstString.erase(firstLength);\n\t\t\tthisPulse++;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tfor (; thisPulse != _pulses.end(); thisPulse++) {\n\t\tsecondString += thisPulse->markerChars(thisPulse->numPoints(samplePeriod, nearestHalfCycle), startMarkerPoints);\n\t}\n\n\tsecondString += firstString;\n\n\treturn secondString;\n}\n\nstd::string pulseTrain::waveChars(const double samplePeriod, const unsigned int numPoints, const bool nearestHalfCycle) {\n\tstd::string firstString = \"\";\n\tstd::string secondString = \"\";\n\t\n\tfirstString.reserve(numPoints+1);\n\tsecondString.reserve(numPoints+1);\n\n\tint shiftAmount = ((int) round(_cyclicShift\/samplePeriod));\n\tunsigned int firstLength = ((shiftAmount >= 0) ? (numPoints - shiftAmount) : (-shiftAmount))%numPoints;\n\n\tstd::deque::iterator thisPulse = _pulses.begin();\n\tfor (thisPulse = _pulses.begin(); thisPulse != _pulses.end(); thisPulse++) {\n\t\tfirstString += thisPulse->waveChars(samplePeriod, thisPulse->numPoints(samplePeriod, nearestHalfCycle));\n\t\tif ( firstString.length() > firstLength ) {\n\t\t\tsecondString = firstString.substr(firstLength);\n\t\t\tfirstString = firstString.erase(firstLength);\n\t\t\tthisPulse++;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tfor (; thisPulse != _pulses.end(); thisPulse++) {\n\t\tsecondString += thisPulse->waveChars(samplePeriod, thisPulse->numPoints(samplePeriod, nearestHalfCycle));\n\t}\n\n\tsecondString += firstString;\n\n\treturn secondString;\n}\n\nunsigned int pulseTrain::numPoints(const double samplePeriod, const bool nearestHalfCycle) {\n\tunsigned int totalPoints = 0;\n\n\tfor (std::deque::iterator thisPulse = _pulses.begin(); thisPulse != _pulses.end(); thisPulse++) {\n\t\ttotalPoints += thisPulse->numPoints(samplePeriod, nearestHalfCycle);\n\t}\n\n\treturn totalPoints;\n}\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"AudioMenu.h\"\n\n\/* system implementation headers *\/\n#include \n#include \n\n\/* common implementation headers *\/\n#include \"TextUtils.h\"\n\n\/* local implementation headers *\/\n#include \"MainMenu.h\"\n#include \"sound.h\"\n\nAudioMenu::AudioMenu()\n{\n \/\/ add controls\n std::vector& list = getControls();\n std::string currentDriver = BZDB.get(\"audioDriver\");\n\n HUDuiLabel* label = new HUDuiLabel;\n label->setFont(MainMenu::getFont());\n label->setString(\"Audio Setting\");\n list.push_back(label);\n\n HUDuiList* option = new HUDuiList;\n\n option = new HUDuiList;\n std::vector* options;\n\n option = new HUDuiList;\n option->setFont(MainMenu::getFont());\n option->setLabel(\"Sound Volume:\");\n option->setCallback(callback, (void*)\"s\");\n options = &option->getList();\n if (isSoundOpen()) {\n options->push_back(std::string(\"Off\"));\n options->push_back(std::string(\"1\"));\n options->push_back(std::string(\"2\"));\n options->push_back(std::string(\"3\"));\n options->push_back(std::string(\"4\"));\n options->push_back(std::string(\"5\"));\n options->push_back(std::string(\"6\"));\n options->push_back(std::string(\"7\"));\n options->push_back(std::string(\"8\"));\n options->push_back(std::string(\"9\"));\n options->push_back(std::string(\"10\"));\n }\n else {\n options->push_back(std::string(\"Unavailable\"));\n }\n option->update();\n list.push_back(option);\n\n driver = new HUDuiTypeIn;\n driver->setFont(MainMenu::getFont());\n driver->setLabel(\"Driver:\");\n driver->setMaxLength(10);\n driver->setString(currentDriver);\n list.push_back(driver);\n\n initNavigation(list, 1,list.size()-1);\n}\n\nAudioMenu::~AudioMenu()\n{\n}\n\nvoid\t\t\tAudioMenu::execute()\n{\n HUDuiControl* focus = HUDui::getFocus();\n if (focus == driver) {\n BZDB.set(\"audioDriver\", driver->getString().c_str());\n }\n}\n\nvoid\t\t\tAudioMenu::resize(int width, int height)\n{\n HUDDialog::resize(width, height);\n int i;\n\n \/\/ use a big font for title, smaller font for the rest\n const float titleFontWidth = (float)height \/ 10.0f;\n const float titleFontHeight = (float)height \/ 10.0f;\n const float fontWidth = (float)height \/ 30.0f;\n const float fontHeight = (float)height \/ 30.0f;\n\n \/\/ reposition title\n std::vector& list = getControls();\n HUDuiLabel* title = (HUDuiLabel*)list[0];\n title->setFontSize(titleFontWidth, titleFontHeight);\n const OpenGLTexFont& titleFont = title->getFont();\n const float titleWidth = titleFont.getWidth(title->getString());\n float x = 0.5f * ((float)width - titleWidth);\n float y = (float)height - titleFont.getHeight();\n title->setPosition(x, y);\n\n \/\/ reposition options\n x = 0.5f * ((float)width + 0.5f * titleWidth);\n y -= 0.6f * titleFont.getHeight();\n const int count = list.size();\n for (i = 1; i < count; i++) {\n list[i]->setFontSize(fontWidth, fontHeight);\n list[i]->setPosition(x, y);\n y -= 1.0f * list[i]->getFont().getHeight();\n }\n\n i = 1;\n \/\/ sound\n ((HUDuiList*)list[i++])->setIndex(getSoundVolume());\n}\n\nvoid\t\t\tAudioMenu::callback(HUDuiControl* w, void* data) {\n HUDuiList* list = (HUDuiList*)w;\n std::vector *options = &list->getList();\n std::string selectedOption = (*options)[list->getIndex()];\n switch (((const char*)data)[0]) {\n case 's':\n BZDB.set(\"volume\", string_util::format(\"%d\", list->getIndex()));\n setSoundVolume(list->getIndex());\n break;\n\n }\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\nUse a slider (and \"off\") for volume control\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"AudioMenu.h\"\n\n\/* system implementation headers *\/\n#include \n#include \n\n\/* common implementation headers *\/\n#include \"TextUtils.h\"\n\n\/* local implementation headers *\/\n#include \"MainMenu.h\"\n#include \"sound.h\"\n\nAudioMenu::AudioMenu()\n{\n \/\/ add controls\n std::vector& list = getControls();\n std::string currentDriver = BZDB.get(\"audioDriver\");\n\n HUDuiLabel* label = new HUDuiLabel;\n label->setFont(MainMenu::getFont());\n label->setString(\"Audio Setting\");\n list.push_back(label);\n\n HUDuiList* option = new HUDuiList;\n\n option = new HUDuiList;\n std::vector* options;\n\n option = new HUDuiList;\n option->setFont(MainMenu::getFont());\n option->setLabel(\"Sound Volume:\");\n option->setCallback(callback, (void*)\"s\");\n options = &option->getList();\n if (isSoundOpen()) {\n options->push_back(std::string(\"Off\"));\n option->createSlider(10);\n }\n else {\n options->push_back(std::string(\"Unavailable\"));\n }\n option->update();\n list.push_back(option);\n\n driver = new HUDuiTypeIn;\n driver->setFont(MainMenu::getFont());\n driver->setLabel(\"Driver:\");\n driver->setMaxLength(10);\n driver->setString(currentDriver);\n list.push_back(driver);\n\n initNavigation(list, 1,list.size()-1);\n}\n\nAudioMenu::~AudioMenu()\n{\n}\n\nvoid\t\t\tAudioMenu::execute()\n{\n HUDuiControl* focus = HUDui::getFocus();\n if (focus == driver) {\n BZDB.set(\"audioDriver\", driver->getString().c_str());\n }\n}\n\nvoid\t\t\tAudioMenu::resize(int width, int height)\n{\n HUDDialog::resize(width, height);\n int i;\n\n \/\/ use a big font for title, smaller font for the rest\n const float titleFontWidth = (float)height \/ 10.0f;\n const float titleFontHeight = (float)height \/ 10.0f;\n const float fontWidth = (float)height \/ 30.0f;\n const float fontHeight = (float)height \/ 30.0f;\n\n \/\/ reposition title\n std::vector& list = getControls();\n HUDuiLabel* title = (HUDuiLabel*)list[0];\n title->setFontSize(titleFontWidth, titleFontHeight);\n const OpenGLTexFont& titleFont = title->getFont();\n const float titleWidth = titleFont.getWidth(title->getString());\n float x = 0.5f * ((float)width - titleWidth);\n float y = (float)height - titleFont.getHeight();\n title->setPosition(x, y);\n\n \/\/ reposition options\n x = 0.5f * ((float)width + 0.5f * titleWidth);\n y -= 0.6f * titleFont.getHeight();\n const int count = list.size();\n for (i = 1; i < count; i++) {\n list[i]->setFontSize(fontWidth, fontHeight);\n list[i]->setPosition(x, y);\n y -= 1.0f * list[i]->getFont().getHeight();\n }\n\n i = 1;\n \/\/ sound\n ((HUDuiList*)list[i++])->setIndex(getSoundVolume());\n}\n\nvoid\t\t\tAudioMenu::callback(HUDuiControl* w, void* data) {\n HUDuiList* list = (HUDuiList*)w;\n std::vector *options = &list->getList();\n std::string selectedOption = (*options)[list->getIndex()];\n switch (((const char*)data)[0]) {\n case 's':\n BZDB.set(\"volume\", string_util::format(\"%d\", list->getIndex()));\n setSoundVolume(list->getIndex());\n break;\n\n }\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"qamqptable.h\"\n#include \"qamqpglobal.h\"\n#include \"qamqpframe_p.h\"\n\nQReadWriteLock QAmqpFrame::lock_;\nint QAmqpFrame::writeTimeout_ = 1000;\n\nQAmqpFrame::QAmqpFrame(FrameType type)\n : size_(0),\n type_(type),\n channel_(0)\n{\n}\n\nQAmqpFrame::FrameType QAmqpFrame::type() const\n{\n return static_cast(type_);\n}\n\nQAmqpFrame::~QAmqpFrame()\n{\n}\n\nvoid QAmqpFrame::setChannel(quint16 channel)\n{\n channel_ = channel;\n}\n\nint QAmqpFrame::writeTimeout()\n{\n QReadLocker locker(&lock_);\n return writeTimeout_;\n}\n\nvoid QAmqpFrame::setWriteTimeout(int msecs)\n{\n QWriteLocker locker(&lock_);\n writeTimeout_ = msecs;\n}\n\nquint16 QAmqpFrame::channel() const\n{\n return channel_;\n}\n\nqint32 QAmqpFrame::size() const\n{\n return 0;\n}\n\n\/*\nvoid QAmqpFrame::readEnd(QDataStream &stream)\n{\n unsigned char end_ = 0;\n stream.readRawData(reinterpret_cast(&end_), sizeof(end_));\n if (end_ != FRAME_END)\n qAmqpDebug(\"Wrong end of frame\");\n}\n*\/\n\nQDataStream &operator<<(QDataStream &stream, const QAmqpFrame &frame)\n{\n \/\/ write header\n stream << frame.type_;\n stream << frame.channel_;\n stream << frame.size();\n\n frame.writePayload(stream);\n\n \/\/ write end\n stream << qint8(QAmqpFrame::FRAME_END);\n stream.device()->waitForBytesWritten(QAmqpFrame::writeTimeout());\n return stream;\n}\n\nQDataStream &operator>>(QDataStream &stream, QAmqpFrame &frame)\n{\n stream >> frame.type_;\n stream >> frame.channel_;\n stream >> frame.size_;\n frame.readPayload(stream);\n return stream;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQAmqpMethodFrame::QAmqpMethodFrame()\n : QAmqpFrame(QAmqpFrame::Method),\n methodClass_(0),\n id_(0)\n{\n}\n\nQAmqpMethodFrame::QAmqpMethodFrame(MethodClass methodClass, qint16 id)\n : QAmqpFrame(QAmqpFrame::Method),\n methodClass_(methodClass),\n id_(id)\n{\n}\n\nQAmqpFrame::MethodClass QAmqpMethodFrame::methodClass() const\n{\n return MethodClass(methodClass_);\n}\n\nqint16 QAmqpMethodFrame::id() const\n{\n return id_;\n}\n\nqint32 QAmqpMethodFrame::size() const\n{\n return sizeof(id_) + sizeof(methodClass_) + arguments_.size();\n}\n\nvoid QAmqpMethodFrame::setArguments(const QByteArray &data)\n{\n arguments_ = data;\n}\n\nQByteArray QAmqpMethodFrame::arguments() const\n{\n return arguments_;\n}\n\nvoid QAmqpMethodFrame::readPayload(QDataStream &stream)\n{\n stream >> methodClass_;\n stream >> id_;\n\n arguments_.resize(size_ - (sizeof(id_) + sizeof(methodClass_)));\n stream.readRawData(arguments_.data(), arguments_.size());\n}\n\nvoid QAmqpMethodFrame::writePayload(QDataStream &stream) const\n{\n stream << quint16(methodClass_);\n stream << quint16(id_);\n stream.writeRawData(arguments_.data(), arguments_.size());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQVariant QAmqpFrame::readAmqpField(QDataStream &s, QAmqpMetaType::ValueType type)\n{\n switch (type) {\n case QAmqpMetaType::Boolean:\n {\n quint8 octet = 0;\n s >> octet;\n return QVariant::fromValue(octet > 0);\n }\n case QAmqpMetaType::ShortShortUint:\n {\n quint8 octet = 0;\n s >> octet;\n return QVariant::fromValue(octet);\n }\n case QAmqpMetaType::ShortUint:\n {\n quint16 tmp_value = 0;\n s >> tmp_value;\n return QVariant::fromValue(tmp_value);\n }\n case QAmqpMetaType::LongUint:\n {\n quint32 tmp_value = 0;\n s >> tmp_value;\n return QVariant::fromValue(tmp_value);\n }\n case QAmqpMetaType::LongLongUint:\n {\n qulonglong v = 0 ;\n s >> v;\n return v;\n }\n case QAmqpMetaType::ShortString:\n {\n qint8 size = 0;\n QByteArray buffer;\n\n s >> size;\n buffer.resize(size);\n s.readRawData(buffer.data(), buffer.size());\n return QString::fromLatin1(buffer.data(), size);\n }\n case QAmqpMetaType::LongString:\n {\n quint32 size = 0;\n QByteArray buffer;\n\n s >> size;\n buffer.resize(size);\n s.readRawData(buffer.data(), buffer.size());\n return QString::fromUtf8(buffer.data(), buffer.size());\n }\n case QAmqpMetaType::Timestamp:\n {\n qulonglong tmp_value;\n s >> tmp_value;\n return QDateTime::fromMSecsSinceEpoch(tmp_value);\n }\n case QAmqpMetaType::Hash:\n {\n QAmqpTable table;\n s >> table;\n return table;\n }\n case QAmqpMetaType::Void:\n return QVariant();\n default:\n qAmqpDebug() << Q_FUNC_INFO << \"unsupported value type: \" << type;\n }\n\n return QVariant();\n}\n\nvoid QAmqpFrame::writeAmqpField(QDataStream &s, QAmqpMetaType::ValueType type, const QVariant &value)\n{\n switch (type) {\n case QAmqpMetaType::Boolean:\n s << (value.toBool() ? qint8(1) : qint8(0));\n break;\n case QAmqpMetaType::ShortShortUint:\n s << qint8(value.toUInt());\n break;\n case QAmqpMetaType::ShortUint:\n s << quint16(value.toUInt());\n break;\n case QAmqpMetaType::LongUint:\n s << quint32(value.toUInt());\n break;\n case QAmqpMetaType::LongLongUint:\n s << qulonglong(value.toULongLong());\n break;\n case QAmqpMetaType::ShortString:\n {\n QString str = value.toString();\n if (str.length() >= 256) {\n qAmqpDebug() << Q_FUNC_INFO << \"invalid shortstr length: \" << str.length();\n }\n\n s << quint8(str.length());\n s.writeRawData(str.toUtf8().data(), str.length());\n }\n break;\n case QAmqpMetaType::LongString:\n {\n QString str = value.toString();\n s << quint32(str.length());\n s.writeRawData(str.toLatin1().data(), str.length());\n }\n break;\n case QAmqpMetaType::Timestamp:\n s << qulonglong(value.toDateTime().toMSecsSinceEpoch());\n break;\n case QAmqpMetaType::Hash:\n {\n QAmqpTable table(value.toHash());\n s << table;\n }\n break;\n default:\n qAmqpDebug() << Q_FUNC_INFO << \"unsupported value type: \" << type;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQAmqpContentFrame::QAmqpContentFrame()\n : QAmqpFrame(QAmqpFrame::Header)\n{\n}\n\nQAmqpContentFrame::QAmqpContentFrame(QAmqpFrame::MethodClass methodClass)\n : QAmqpFrame(QAmqpFrame::Header)\n{\n methodClass_ = methodClass;\n}\n\nQAmqpFrame::MethodClass QAmqpContentFrame::methodClass() const\n{\n return MethodClass(methodClass_);\n}\n\nqint32 QAmqpContentFrame::size() const\n{\n QDataStream out(&buffer_, QIODevice::WriteOnly);\n buffer_.clear();\n out << qint16(methodClass_);\n out << qint16(0); \/\/weight\n out << qlonglong(bodySize_);\n\n qint16 prop_ = 0;\n foreach (int p, properties_.keys())\n prop_ |= p;\n out << prop_;\n\n if (prop_ & QAmqpMessage::ContentType)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::ContentType]);\n\n if (prop_ & QAmqpMessage::ContentEncoding)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::ContentEncoding]);\n\n if (prop_ & QAmqpMessage::Headers)\n writeAmqpField(out, QAmqpMetaType::Hash, properties_[QAmqpMessage::Headers]);\n\n if (prop_ & QAmqpMessage::DeliveryMode)\n writeAmqpField(out, QAmqpMetaType::ShortShortUint, properties_[QAmqpMessage::DeliveryMode]);\n\n if (prop_ & QAmqpMessage::Priority)\n writeAmqpField(out, QAmqpMetaType::ShortShortUint, properties_[QAmqpMessage::Priority]);\n\n if (prop_ & QAmqpMessage::CorrelationId)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::CorrelationId]);\n\n if (prop_ & QAmqpMessage::ReplyTo)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::ReplyTo]);\n\n if (prop_ & QAmqpMessage::Expiration)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::Expiration]);\n\n if (prop_ & QAmqpMessage::MessageId)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::MessageId]);\n\n if (prop_ & QAmqpMessage::Timestamp)\n writeAmqpField(out, QAmqpMetaType::Timestamp, properties_[QAmqpMessage::Timestamp]);\n\n if (prop_ & QAmqpMessage::Type)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::Type]);\n\n if (prop_ & QAmqpMessage::UserId)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::UserId]);\n\n if (prop_ & QAmqpMessage::AppId)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::AppId]);\n\n if (prop_ & QAmqpMessage::ClusterID)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::ClusterID]);\n\n return buffer_.size();\n}\n\nqlonglong QAmqpContentFrame::bodySize() const\n{\n return bodySize_;\n}\n\nvoid QAmqpContentFrame::setBodySize(qlonglong size)\n{\n bodySize_ = size;\n}\n\nvoid QAmqpContentFrame::setProperty(QAmqpMessage::Property prop, const QVariant &value)\n{\n properties_[prop] = value;\n}\n\nQVariant QAmqpContentFrame::property(QAmqpMessage::Property prop) const\n{\n return properties_.value(prop);\n}\n\nvoid QAmqpContentFrame::writePayload(QDataStream &out) const\n{\n out.writeRawData(buffer_.data(), buffer_.size());\n}\n\nvoid QAmqpContentFrame::readPayload(QDataStream &in)\n{\n in >> methodClass_;\n in.skipRawData(2); \/\/weight\n in >> bodySize_;\n qint16 flags_ = 0;\n in >> flags_;\n if (flags_ & QAmqpMessage::ContentType)\n properties_[QAmqpMessage::ContentType] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::ContentEncoding)\n properties_[QAmqpMessage::ContentEncoding] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::Headers)\n properties_[QAmqpMessage::Headers] = readAmqpField(in, QAmqpMetaType::Hash);\n\n if (flags_ & QAmqpMessage::DeliveryMode)\n properties_[QAmqpMessage::DeliveryMode] = readAmqpField(in, QAmqpMetaType::ShortShortUint);\n\n if (flags_ & QAmqpMessage::Priority)\n properties_[QAmqpMessage::Priority] = readAmqpField(in, QAmqpMetaType::ShortShortUint);\n\n if (flags_ & QAmqpMessage::CorrelationId)\n properties_[QAmqpMessage::CorrelationId] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::ReplyTo)\n properties_[QAmqpMessage::ReplyTo] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::Expiration)\n properties_[QAmqpMessage::Expiration] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::MessageId)\n properties_[QAmqpMessage::MessageId] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::Timestamp)\n properties_[QAmqpMessage::Timestamp] = readAmqpField(in, QAmqpMetaType::Timestamp);\n\n if (flags_ & QAmqpMessage::Type)\n properties_[QAmqpMessage::Type] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::UserId)\n properties_[QAmqpMessage::UserId] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::AppId)\n properties_[QAmqpMessage::AppId] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::ClusterID)\n properties_[QAmqpMessage::ClusterID] = readAmqpField(in, QAmqpMetaType::ShortString);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQAmqpContentBodyFrame::QAmqpContentBodyFrame()\n : QAmqpFrame(QAmqpFrame::Body)\n{\n}\n\nvoid QAmqpContentBodyFrame::setBody(const QByteArray &data)\n{\n body_ = data;\n}\n\nQByteArray QAmqpContentBodyFrame::body() const\n{\n return body_;\n}\n\nvoid QAmqpContentBodyFrame::writePayload(QDataStream &out) const\n{\n out.writeRawData(body_.data(), body_.size());\n}\n\nvoid QAmqpContentBodyFrame::readPayload(QDataStream &in)\n{\n body_.resize(size_);\n in.readRawData(body_.data(), body_.size());\n}\n\nqint32 QAmqpContentBodyFrame::size() const\n{\n return body_.size();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQAmqpHeartbeatFrame::QAmqpHeartbeatFrame()\n : QAmqpFrame(QAmqpFrame::Heartbeat)\n{\n}\n\nvoid QAmqpHeartbeatFrame::readPayload(QDataStream &stream)\n{\n Q_UNUSED(stream)\n}\n\nvoid QAmqpHeartbeatFrame::writePayload(QDataStream &stream) const\n{\n Q_UNUSED(stream)\n}\ntimestamp in AMQP-0-9-1 should be seconds since 1970-01-01 other than miliseconds#include \n#include \n#include \n\n#include \"qamqptable.h\"\n#include \"qamqpglobal.h\"\n#include \"qamqpframe_p.h\"\n\nQReadWriteLock QAmqpFrame::lock_;\nint QAmqpFrame::writeTimeout_ = 1000;\n\nQAmqpFrame::QAmqpFrame(FrameType type)\n : size_(0),\n type_(type),\n channel_(0)\n{\n}\n\nQAmqpFrame::FrameType QAmqpFrame::type() const\n{\n return static_cast(type_);\n}\n\nQAmqpFrame::~QAmqpFrame()\n{\n}\n\nvoid QAmqpFrame::setChannel(quint16 channel)\n{\n channel_ = channel;\n}\n\nint QAmqpFrame::writeTimeout()\n{\n QReadLocker locker(&lock_);\n return writeTimeout_;\n}\n\nvoid QAmqpFrame::setWriteTimeout(int msecs)\n{\n QWriteLocker locker(&lock_);\n writeTimeout_ = msecs;\n}\n\nquint16 QAmqpFrame::channel() const\n{\n return channel_;\n}\n\nqint32 QAmqpFrame::size() const\n{\n return 0;\n}\n\n\/*\nvoid QAmqpFrame::readEnd(QDataStream &stream)\n{\n unsigned char end_ = 0;\n stream.readRawData(reinterpret_cast(&end_), sizeof(end_));\n if (end_ != FRAME_END)\n qAmqpDebug(\"Wrong end of frame\");\n}\n*\/\n\nQDataStream &operator<<(QDataStream &stream, const QAmqpFrame &frame)\n{\n \/\/ write header\n stream << frame.type_;\n stream << frame.channel_;\n stream << frame.size();\n\n frame.writePayload(stream);\n\n \/\/ write end\n stream << qint8(QAmqpFrame::FRAME_END);\n stream.device()->waitForBytesWritten(QAmqpFrame::writeTimeout());\n return stream;\n}\n\nQDataStream &operator>>(QDataStream &stream, QAmqpFrame &frame)\n{\n stream >> frame.type_;\n stream >> frame.channel_;\n stream >> frame.size_;\n frame.readPayload(stream);\n return stream;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQAmqpMethodFrame::QAmqpMethodFrame()\n : QAmqpFrame(QAmqpFrame::Method),\n methodClass_(0),\n id_(0)\n{\n}\n\nQAmqpMethodFrame::QAmqpMethodFrame(MethodClass methodClass, qint16 id)\n : QAmqpFrame(QAmqpFrame::Method),\n methodClass_(methodClass),\n id_(id)\n{\n}\n\nQAmqpFrame::MethodClass QAmqpMethodFrame::methodClass() const\n{\n return MethodClass(methodClass_);\n}\n\nqint16 QAmqpMethodFrame::id() const\n{\n return id_;\n}\n\nqint32 QAmqpMethodFrame::size() const\n{\n return sizeof(id_) + sizeof(methodClass_) + arguments_.size();\n}\n\nvoid QAmqpMethodFrame::setArguments(const QByteArray &data)\n{\n arguments_ = data;\n}\n\nQByteArray QAmqpMethodFrame::arguments() const\n{\n return arguments_;\n}\n\nvoid QAmqpMethodFrame::readPayload(QDataStream &stream)\n{\n stream >> methodClass_;\n stream >> id_;\n\n arguments_.resize(size_ - (sizeof(id_) + sizeof(methodClass_)));\n stream.readRawData(arguments_.data(), arguments_.size());\n}\n\nvoid QAmqpMethodFrame::writePayload(QDataStream &stream) const\n{\n stream << quint16(methodClass_);\n stream << quint16(id_);\n stream.writeRawData(arguments_.data(), arguments_.size());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQVariant QAmqpFrame::readAmqpField(QDataStream &s, QAmqpMetaType::ValueType type)\n{\n switch (type) {\n case QAmqpMetaType::Boolean:\n {\n quint8 octet = 0;\n s >> octet;\n return QVariant::fromValue(octet > 0);\n }\n case QAmqpMetaType::ShortShortUint:\n {\n quint8 octet = 0;\n s >> octet;\n return QVariant::fromValue(octet);\n }\n case QAmqpMetaType::ShortUint:\n {\n quint16 tmp_value = 0;\n s >> tmp_value;\n return QVariant::fromValue(tmp_value);\n }\n case QAmqpMetaType::LongUint:\n {\n quint32 tmp_value = 0;\n s >> tmp_value;\n return QVariant::fromValue(tmp_value);\n }\n case QAmqpMetaType::LongLongUint:\n {\n qulonglong v = 0 ;\n s >> v;\n return v;\n }\n case QAmqpMetaType::ShortString:\n {\n qint8 size = 0;\n QByteArray buffer;\n\n s >> size;\n buffer.resize(size);\n s.readRawData(buffer.data(), buffer.size());\n return QString::fromLatin1(buffer.data(), size);\n }\n case QAmqpMetaType::LongString:\n {\n quint32 size = 0;\n QByteArray buffer;\n\n s >> size;\n buffer.resize(size);\n s.readRawData(buffer.data(), buffer.size());\n return QString::fromUtf8(buffer.data(), buffer.size());\n }\n case QAmqpMetaType::Timestamp:\n {\n qulonglong tmp_value;\n s >> tmp_value;\n return QDateTime::fromTime_t(tmp_value);\n }\n case QAmqpMetaType::Hash:\n {\n QAmqpTable table;\n s >> table;\n return table;\n }\n case QAmqpMetaType::Void:\n return QVariant();\n default:\n qAmqpDebug() << Q_FUNC_INFO << \"unsupported value type: \" << type;\n }\n\n return QVariant();\n}\n\nvoid QAmqpFrame::writeAmqpField(QDataStream &s, QAmqpMetaType::ValueType type, const QVariant &value)\n{\n switch (type) {\n case QAmqpMetaType::Boolean:\n s << (value.toBool() ? qint8(1) : qint8(0));\n break;\n case QAmqpMetaType::ShortShortUint:\n s << qint8(value.toUInt());\n break;\n case QAmqpMetaType::ShortUint:\n s << quint16(value.toUInt());\n break;\n case QAmqpMetaType::LongUint:\n s << quint32(value.toUInt());\n break;\n case QAmqpMetaType::LongLongUint:\n s << qulonglong(value.toULongLong());\n break;\n case QAmqpMetaType::ShortString:\n {\n QString str = value.toString();\n if (str.length() >= 256) {\n qAmqpDebug() << Q_FUNC_INFO << \"invalid shortstr length: \" << str.length();\n }\n\n s << quint8(str.length());\n s.writeRawData(str.toUtf8().data(), str.length());\n }\n break;\n case QAmqpMetaType::LongString:\n {\n QString str = value.toString();\n s << quint32(str.length());\n s.writeRawData(str.toLatin1().data(), str.length());\n }\n break;\n case QAmqpMetaType::Timestamp:\n s << qulonglong(value.toDateTime().toTime_t());\n break;\n case QAmqpMetaType::Hash:\n {\n QAmqpTable table(value.toHash());\n s << table;\n }\n break;\n default:\n qAmqpDebug() << Q_FUNC_INFO << \"unsupported value type: \" << type;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQAmqpContentFrame::QAmqpContentFrame()\n : QAmqpFrame(QAmqpFrame::Header)\n{\n}\n\nQAmqpContentFrame::QAmqpContentFrame(QAmqpFrame::MethodClass methodClass)\n : QAmqpFrame(QAmqpFrame::Header)\n{\n methodClass_ = methodClass;\n}\n\nQAmqpFrame::MethodClass QAmqpContentFrame::methodClass() const\n{\n return MethodClass(methodClass_);\n}\n\nqint32 QAmqpContentFrame::size() const\n{\n QDataStream out(&buffer_, QIODevice::WriteOnly);\n buffer_.clear();\n out << qint16(methodClass_);\n out << qint16(0); \/\/weight\n out << qlonglong(bodySize_);\n\n qint16 prop_ = 0;\n foreach (int p, properties_.keys())\n prop_ |= p;\n out << prop_;\n\n if (prop_ & QAmqpMessage::ContentType)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::ContentType]);\n\n if (prop_ & QAmqpMessage::ContentEncoding)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::ContentEncoding]);\n\n if (prop_ & QAmqpMessage::Headers)\n writeAmqpField(out, QAmqpMetaType::Hash, properties_[QAmqpMessage::Headers]);\n\n if (prop_ & QAmqpMessage::DeliveryMode)\n writeAmqpField(out, QAmqpMetaType::ShortShortUint, properties_[QAmqpMessage::DeliveryMode]);\n\n if (prop_ & QAmqpMessage::Priority)\n writeAmqpField(out, QAmqpMetaType::ShortShortUint, properties_[QAmqpMessage::Priority]);\n\n if (prop_ & QAmqpMessage::CorrelationId)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::CorrelationId]);\n\n if (prop_ & QAmqpMessage::ReplyTo)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::ReplyTo]);\n\n if (prop_ & QAmqpMessage::Expiration)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::Expiration]);\n\n if (prop_ & QAmqpMessage::MessageId)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::MessageId]);\n\n if (prop_ & QAmqpMessage::Timestamp)\n writeAmqpField(out, QAmqpMetaType::Timestamp, properties_[QAmqpMessage::Timestamp]);\n\n if (prop_ & QAmqpMessage::Type)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::Type]);\n\n if (prop_ & QAmqpMessage::UserId)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::UserId]);\n\n if (prop_ & QAmqpMessage::AppId)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::AppId]);\n\n if (prop_ & QAmqpMessage::ClusterID)\n writeAmqpField(out, QAmqpMetaType::ShortString, properties_[QAmqpMessage::ClusterID]);\n\n return buffer_.size();\n}\n\nqlonglong QAmqpContentFrame::bodySize() const\n{\n return bodySize_;\n}\n\nvoid QAmqpContentFrame::setBodySize(qlonglong size)\n{\n bodySize_ = size;\n}\n\nvoid QAmqpContentFrame::setProperty(QAmqpMessage::Property prop, const QVariant &value)\n{\n properties_[prop] = value;\n}\n\nQVariant QAmqpContentFrame::property(QAmqpMessage::Property prop) const\n{\n return properties_.value(prop);\n}\n\nvoid QAmqpContentFrame::writePayload(QDataStream &out) const\n{\n out.writeRawData(buffer_.data(), buffer_.size());\n}\n\nvoid QAmqpContentFrame::readPayload(QDataStream &in)\n{\n in >> methodClass_;\n in.skipRawData(2); \/\/weight\n in >> bodySize_;\n qint16 flags_ = 0;\n in >> flags_;\n if (flags_ & QAmqpMessage::ContentType)\n properties_[QAmqpMessage::ContentType] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::ContentEncoding)\n properties_[QAmqpMessage::ContentEncoding] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::Headers)\n properties_[QAmqpMessage::Headers] = readAmqpField(in, QAmqpMetaType::Hash);\n\n if (flags_ & QAmqpMessage::DeliveryMode)\n properties_[QAmqpMessage::DeliveryMode] = readAmqpField(in, QAmqpMetaType::ShortShortUint);\n\n if (flags_ & QAmqpMessage::Priority)\n properties_[QAmqpMessage::Priority] = readAmqpField(in, QAmqpMetaType::ShortShortUint);\n\n if (flags_ & QAmqpMessage::CorrelationId)\n properties_[QAmqpMessage::CorrelationId] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::ReplyTo)\n properties_[QAmqpMessage::ReplyTo] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::Expiration)\n properties_[QAmqpMessage::Expiration] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::MessageId)\n properties_[QAmqpMessage::MessageId] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::Timestamp)\n properties_[QAmqpMessage::Timestamp] = readAmqpField(in, QAmqpMetaType::Timestamp);\n\n if (flags_ & QAmqpMessage::Type)\n properties_[QAmqpMessage::Type] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::UserId)\n properties_[QAmqpMessage::UserId] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::AppId)\n properties_[QAmqpMessage::AppId] = readAmqpField(in, QAmqpMetaType::ShortString);\n\n if (flags_ & QAmqpMessage::ClusterID)\n properties_[QAmqpMessage::ClusterID] = readAmqpField(in, QAmqpMetaType::ShortString);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQAmqpContentBodyFrame::QAmqpContentBodyFrame()\n : QAmqpFrame(QAmqpFrame::Body)\n{\n}\n\nvoid QAmqpContentBodyFrame::setBody(const QByteArray &data)\n{\n body_ = data;\n}\n\nQByteArray QAmqpContentBodyFrame::body() const\n{\n return body_;\n}\n\nvoid QAmqpContentBodyFrame::writePayload(QDataStream &out) const\n{\n out.writeRawData(body_.data(), body_.size());\n}\n\nvoid QAmqpContentBodyFrame::readPayload(QDataStream &in)\n{\n body_.resize(size_);\n in.readRawData(body_.data(), body_.size());\n}\n\nqint32 QAmqpContentBodyFrame::size() const\n{\n return body_.size();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQAmqpHeartbeatFrame::QAmqpHeartbeatFrame()\n : QAmqpFrame(QAmqpFrame::Heartbeat)\n{\n}\n\nvoid QAmqpHeartbeatFrame::readPayload(QDataStream &stream)\n{\n Q_UNUSED(stream)\n}\n\nvoid QAmqpHeartbeatFrame::writePayload(QDataStream &stream) const\n{\n Q_UNUSED(stream)\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n** Copyright (c) 2013-2015, Intel Corporation **\n** All rights reserved. **\n** **\n** Redistribution and use in source and binary forms, with or without **\n** modification, are permitted provided that the following conditions **\n** are met: **\n** 1. Redistributions of source code must retain the above copyright **\n** notice, this list of conditions and the following disclaimer. **\n** 2. Redistributions in binary form must reproduce the above copyright **\n** notice, this list of conditions and the following disclaimer in the **\n** documentation and\/or other materials provided with the distribution. **\n** 3. Neither the name of the copyright holder nor the names of its **\n** contributors may be used to endorse or promote products derived **\n** from this software without specific prior written permission. **\n** **\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS **\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT **\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR **\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT **\n** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, **\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED **\n** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR **\n** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF **\n** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING **\n** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS **\n** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **\n******************************************************************************\/\n\/* Hans Pabst (Intel Corp.)\n******************************************************************************\/\n#include \n\n#if defined(LIBXSMM_OFFLOAD)\n# pragma offload_attribute(push,target(mic))\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if defined(_OPENMP)\n# include \n#endif\n\n#if defined(LIBXSMM_OFFLOAD)\n# pragma offload_attribute(pop)\n#endif\n\n#if (0 < (LIBXSMM_ALIGNED_STORES))\n# define SMM_ALIGNMENT LIBXSMM_ALIGNED_STORES\n#else\n# define SMM_ALIGNMENT LIBXSMM_ALIGNMENT\n#endif\n\n\/\/ make sure that stacksize is covering the problem size\n#define SMM_MAX_PROBLEM_SIZE (1 * LIBXSMM_MAX_MNK)\n\n#define SMM_SCHEDULE dynamic\n#define SMM_CHECK\n\n\ntemplate\nLIBXSMM_TARGET(mic) void nrand(T& a)\n{\n static const double scale = 1.0 \/ RAND_MAX;\n a = static_cast(scale * (2 * std::rand() - RAND_MAX));\n}\n\n\ntemplate\nLIBXSMM_TARGET(mic) void add(T *LIBXSMM_RESTRICT dst, const T *LIBXSMM_RESTRICT c, int m, int n, int ldc)\n{\n#if (0 < LIBXSMM_ALIGNED_STORES)\n LIBXSMM_ASSUME_ALIGNED(c, SMM_ALIGNMENT);\n#endif\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n#if (0 != LIBXSMM_ROW_MAJOR)\n const T value = c[i*ldc+j];\n#else\n const T value = c[j*ldc+i];\n#endif\n#if defined(_OPENMP)\n# pragma omp atomic\n#endif\n#if (0 != LIBXSMM_ROW_MAJOR)\n dst[i*n+j] += value;\n#else\n dst[j*m+i] += value;\n#endif\n }\n }\n}\n\n\ntemplate\nLIBXSMM_TARGET(mic) double max_diff(const T *LIBXSMM_RESTRICT result, const T *LIBXSMM_RESTRICT expect, int m, int n, int ldc)\n{\n double diff = 0;\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n#if (0 != LIBXSMM_ROW_MAJOR)\n const int k = i * ldc + j;\n#else\n const int k = j * ldc + i;\n#endif\n diff = std::max(diff, std::abs(static_cast(result[k]) - static_cast(expect[k])));\n }\n }\n return diff;\n}\n\n\nint main(int argc, char* argv[])\n{\n try {\n typedef double T;\n const int default_psize = 30000, default_batch = 1000;\n const int m = 1 < argc ? std::atoi(argv[1]) : 23;\n const int s = 2 < argc ? (0 < std::atoi(argv[2]) ? std::atoi(argv[2]) : ('+' == *argv[2]\n ? (default_psize << std::strlen(argv[2]))\n : (default_psize >> std::strlen(argv[2])))) : default_psize;\n const int t = 3 < argc ? (0 < std::atoi(argv[3]) ? std::atoi(argv[3]) : ('+' == *argv[3]\n ? (default_batch << std::strlen(argv[3]))\n : (default_batch >> std::strlen(argv[3])))) : default_batch;\n const int n = 4 < argc ? std::atoi(argv[4]) : m;\n const int k = 5 < argc ? std::atoi(argv[5]) : m;\n\n if ((SMM_MAX_PROBLEM_SIZE) < (m * n * k)) {\n throw std::runtime_error(\"The size M x N x K is exceeding SMM_MAX_PROBLEM_SIZE!\");\n }\n\n#if (0 != LIBXSMM_ROW_MAJOR)\n# if (0 < LIBXSMM_ALIGNED_STORES)\n const int ldc = LIBXSMM_ALIGN_VALUE(int, T, n, LIBXSMM_ALIGNED_STORES);\n# else\n const int ldc = n;\n# endif\n const int csize = m * ldc;\n#else\n# if (0 < LIBXSMM_ALIGNED_STORES)\n const int ldc = LIBXSMM_ALIGN_VALUE(int, T, m, LIBXSMM_ALIGNED_STORES);\n# else\n const int ldc = m;\n# endif\n const int csize = n * ldc;\n#endif\n\n const int asize = m * k, bsize = k * n;\n std::vector va(s * asize), vb(s * bsize), vc(csize);\n std::for_each(va.begin(), va.end(), nrand);\n std::for_each(vb.begin(), vb.end(), nrand);\n const T *const a = &va[0], *const b = &vb[0];\n T * \/*const*\/ c = &vc[0];\n\n#if defined(LIBXSMM_OFFLOAD)\n# pragma offload target(mic) in(a: length(s * asize)) in(b: length(s * bsize)) out(c: length(csize))\n#endif\n {\n const double mbytes = 1.0 * s * (asize + bsize) * sizeof(T) \/ (1024 * 1024);\n#if defined(_OPENMP)\n const double nbytes = 1.0 * s * (csize) * sizeof(T) \/ (1024 * 1024);\n const double gflops = 2.0 * s * m * n * k * 1E-9;\n#endif\n#if defined(SMM_CHECK)\n std::vector expect(csize);\n#endif\n fprintf(stdout, \"m=%i n=%i k=%i ldc=%i size=%i batch=%i memory=%.1f MB\\n\", m, n, k, ldc, s, t, mbytes);\n\n { \/\/ LAPACK\/BLAS3 (fallback)\n fprintf(stdout, \"LAPACK\/BLAS...\\n\");\n std::fill_n(c, csize, 0);\n#if defined(_OPENMP)\n const double start = omp_get_wtime();\n# pragma omp parallel for schedule(SMM_SCHEDULE)\n#endif\n for (int i = 0; i < s; i += t) {\n LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);\n for (int j = 0; j < csize; ++j) tmp[j] = 0; \/\/ clear\n for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {\n libxsmm_blasmm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);\n }\n add(c, tmp, m, n, ldc); \/\/ atomic\n }\n#if defined(_OPENMP)\n const double duration = omp_get_wtime() - start;\n if (0 < duration) {\n fprintf(stdout, \"\\tperformance: %.1f GFLOPS\/s\\n\", gflops \/ duration);\n fprintf(stdout, \"\\tbandwidth: %.1f GB\/s\\n\", (mbytes + nbytes) * 1E-3 \/ duration);\n }\n fprintf(stdout, \"\\tduration: %.1f s\\n\", duration);\n#endif\n#if defined(SMM_CHECK)\n std::copy(c, c + csize, expect.begin());\n#endif\n }\n\n { \/\/ inline an optimized implementation\n fprintf(stdout, \"Inlined...\\n\");\n std::fill_n(c, csize, 0);\n#if defined(_OPENMP)\n const double start = omp_get_wtime();\n# pragma omp parallel for schedule(SMM_SCHEDULE)\n#endif\n for (int i = 0; i < s; i += t) {\n LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);\n for (int j = 0; j < csize; ++j) tmp[j] = 0; \/\/ clear\n for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {\n libxsmm_imm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);\n }\n add(c, tmp, m, n, ldc); \/\/ atomic\n }\n#if defined(_OPENMP)\n const double duration = omp_get_wtime() - start;\n if (0 < duration) {\n fprintf(stdout, \"\\tperformance: %.1f GFLOPS\/s\\n\", gflops \/ duration);\n fprintf(stdout, \"\\tbandwidth: %.1f GB\/s\\n\", (mbytes + nbytes) * 1E-3 \/ duration);\n }\n fprintf(stdout, \"\\tduration: %.1f s\\n\", duration);\n#endif\n#if defined(SMM_CHECK)\n fprintf(stdout, \"\\tdiff=%f\\n\", max_diff(c, &expect[0], m, n, ldc));\n#endif\n }\n\n { \/\/ auto-dispatched\n fprintf(stdout, \"Dispatched...\\n\");\n std::fill_n(c, csize, 0);\n#if defined(_OPENMP)\n const double start = omp_get_wtime();\n# pragma omp parallel for schedule(SMM_SCHEDULE)\n#endif\n for (int i = 0; i < s; i += t) {\n LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);\n for (int j = 0; j < csize; ++j) tmp[j] = 0; \/\/ clear\n for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {\n libxsmm_mm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);\n }\n add(c, tmp, m, n, ldc); \/\/ atomic\n }\n#if defined(_OPENMP)\n const double duration = omp_get_wtime() - start;\n if (0 < duration) {\n fprintf(stdout, \"\\tperformance: %.1f GFLOPS\/s\\n\", gflops \/ duration);\n fprintf(stdout, \"\\tbandwidth: %.1f GB\/s\\n\", (mbytes + nbytes) * 1E-3 \/ duration);\n }\n fprintf(stdout, \"\\tduration: %.1f s\\n\", duration);\n#endif\n#if defined(SMM_CHECK)\n fprintf(stdout, \"\\tdiff=%f\\n\", max_diff(c, &expect[0], m, n, ldc));\n#endif\n }\n\n const libxsmm_mm_dispatch xmm(m, n, k);\n if (xmm) { \/\/ specialized routine\n fprintf(stdout, \"Specialized...\\n\");\n std::fill_n(c, csize, 0);\n#if defined(_OPENMP)\n const double start = omp_get_wtime();\n# pragma omp parallel for schedule(SMM_SCHEDULE)\n#endif\n for (int i = 0; i < s; i += t) {\n LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);\n for (int j = 0; j < csize; ++j) tmp[j] = 0; \/\/ clear\n for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {\n xmm(&a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);\n }\n add(c, tmp, m, n, ldc); \/\/ atomic\n }\n#if defined(_OPENMP)\n const double duration = omp_get_wtime() - start;\n if (0 < duration) {\n fprintf(stdout, \"\\tperformance: %.1f GFLOPS\/s\\n\", gflops \/ duration);\n fprintf(stdout, \"\\tbandwidth: %.1f GB\/s\\n\", (mbytes + nbytes) * 1E-3 \/ duration);\n }\n fprintf(stdout, \"\\tduration: %.1f s\\n\", duration);\n#endif\n#if defined(SMM_CHECK)\n fprintf(stdout, \"\\tdiff=%f\\n\", max_diff(c, &expect[0], m, n, ldc));\n#endif\n }\n\n fprintf(stdout, \"Finished\\n\");\n }\n }\n catch(const std::exception& e) {\n fprintf(stderr, \"Error: %s\\n\", e.what());\n return EXIT_FAILURE;\n }\n catch(...) {\n fprintf(stderr, \"Error: unknown exception caught!\\n\");\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\nFixed a corner case when processing the command line arguments of the sample\/benchmark program.\/******************************************************************************\n** Copyright (c) 2013-2015, Intel Corporation **\n** All rights reserved. **\n** **\n** Redistribution and use in source and binary forms, with or without **\n** modification, are permitted provided that the following conditions **\n** are met: **\n** 1. Redistributions of source code must retain the above copyright **\n** notice, this list of conditions and the following disclaimer. **\n** 2. Redistributions in binary form must reproduce the above copyright **\n** notice, this list of conditions and the following disclaimer in the **\n** documentation and\/or other materials provided with the distribution. **\n** 3. Neither the name of the copyright holder nor the names of its **\n** contributors may be used to endorse or promote products derived **\n** from this software without specific prior written permission. **\n** **\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS **\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT **\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR **\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT **\n** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, **\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED **\n** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR **\n** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF **\n** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING **\n** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS **\n** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **\n******************************************************************************\/\n\/* Hans Pabst (Intel Corp.)\n******************************************************************************\/\n#include \n\n#if defined(LIBXSMM_OFFLOAD)\n# pragma offload_attribute(push,target(mic))\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if defined(_OPENMP)\n# include \n#endif\n\n#if defined(LIBXSMM_OFFLOAD)\n# pragma offload_attribute(pop)\n#endif\n\n#if (0 < (LIBXSMM_ALIGNED_STORES))\n# define SMM_ALIGNMENT LIBXSMM_ALIGNED_STORES\n#else\n# define SMM_ALIGNMENT LIBXSMM_ALIGNMENT\n#endif\n\n\/\/ make sure that stacksize is covering the problem size\n#define SMM_MAX_PROBLEM_SIZE (1 * LIBXSMM_MAX_MNK)\n\n#define SMM_SCHEDULE dynamic\n#define SMM_CHECK\n\n\ntemplate\nLIBXSMM_TARGET(mic) void nrand(T& a)\n{\n static const double scale = 1.0 \/ RAND_MAX;\n a = static_cast(scale * (2 * std::rand() - RAND_MAX));\n}\n\n\ntemplate\nLIBXSMM_TARGET(mic) void add(T *LIBXSMM_RESTRICT dst, const T *LIBXSMM_RESTRICT c, int m, int n, int ldc)\n{\n#if (0 < LIBXSMM_ALIGNED_STORES)\n LIBXSMM_ASSUME_ALIGNED(c, SMM_ALIGNMENT);\n#endif\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n#if (0 != LIBXSMM_ROW_MAJOR)\n const T value = c[i*ldc+j];\n#else\n const T value = c[j*ldc+i];\n#endif\n#if defined(_OPENMP)\n# pragma omp atomic\n#endif\n#if (0 != LIBXSMM_ROW_MAJOR)\n dst[i*n+j] += value;\n#else\n dst[j*m+i] += value;\n#endif\n }\n }\n}\n\n\ntemplate\nLIBXSMM_TARGET(mic) double max_diff(const T *LIBXSMM_RESTRICT result, const T *LIBXSMM_RESTRICT expect, int m, int n, int ldc)\n{\n double diff = 0;\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n#if (0 != LIBXSMM_ROW_MAJOR)\n const int k = i * ldc + j;\n#else\n const int k = j * ldc + i;\n#endif\n diff = std::max(diff, std::abs(static_cast(result[k]) - static_cast(expect[k])));\n }\n }\n return diff;\n}\n\n\nint main(int argc, char* argv[])\n{\n try {\n typedef double T;\n const int default_psize = 30000, default_batch = 1000;\n const int m = 1 < argc ? std::atoi(argv[1]) : 23;\n const int s = 2 < argc ? (0 < std::atoi(argv[2]) ? std::atoi(argv[2]) : ('+' == *argv[2]\n ? (default_psize << std::strlen(argv[2])) : ('-' == *argv[2]\n ? (default_psize >> std::strlen(argv[2])) : default_psize))) : default_psize;\n const int t = 3 < argc ? (0 < std::atoi(argv[3]) ? std::atoi(argv[3]) : ('+' == *argv[3]\n ? (default_batch << std::strlen(argv[3])) : ('-' == *argv[3]\n ? (default_batch >> std::strlen(argv[3])) : default_batch))) : default_batch;\n const int n = 4 < argc ? std::atoi(argv[4]) : m;\n const int k = 5 < argc ? std::atoi(argv[5]) : m;\n\n if ((SMM_MAX_PROBLEM_SIZE) < (m * n * k)) {\n throw std::runtime_error(\"The size M x N x K is exceeding SMM_MAX_PROBLEM_SIZE!\");\n }\n\n#if (0 != LIBXSMM_ROW_MAJOR)\n# if (0 < LIBXSMM_ALIGNED_STORES)\n const int ldc = LIBXSMM_ALIGN_VALUE(int, T, n, LIBXSMM_ALIGNED_STORES);\n# else\n const int ldc = n;\n# endif\n const int csize = m * ldc;\n#else\n# if (0 < LIBXSMM_ALIGNED_STORES)\n const int ldc = LIBXSMM_ALIGN_VALUE(int, T, m, LIBXSMM_ALIGNED_STORES);\n# else\n const int ldc = m;\n# endif\n const int csize = n * ldc;\n#endif\n\n const int asize = m * k, bsize = k * n;\n std::vector va(s * asize), vb(s * bsize), vc(csize);\n std::for_each(va.begin(), va.end(), nrand);\n std::for_each(vb.begin(), vb.end(), nrand);\n const T *const a = &va[0], *const b = &vb[0];\n T * \/*const*\/ c = &vc[0];\n\n#if defined(LIBXSMM_OFFLOAD)\n# pragma offload target(mic) in(a: length(s * asize)) in(b: length(s * bsize)) out(c: length(csize))\n#endif\n {\n const double mbytes = 1.0 * s * (asize + bsize) * sizeof(T) \/ (1024 * 1024);\n#if defined(_OPENMP)\n const double nbytes = 1.0 * s * (csize) * sizeof(T) \/ (1024 * 1024);\n const double gflops = 2.0 * s * m * n * k * 1E-9;\n#endif\n#if defined(SMM_CHECK)\n std::vector expect(csize);\n#endif\n fprintf(stdout, \"m=%i n=%i k=%i ldc=%i size=%i batch=%i memory=%.1f MB\\n\", m, n, k, ldc, s, t, mbytes);\n\n { \/\/ LAPACK\/BLAS3 (fallback)\n fprintf(stdout, \"LAPACK\/BLAS...\\n\");\n std::fill_n(c, csize, 0);\n#if defined(_OPENMP)\n const double start = omp_get_wtime();\n# pragma omp parallel for schedule(SMM_SCHEDULE)\n#endif\n for (int i = 0; i < s; i += t) {\n LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);\n for (int j = 0; j < csize; ++j) tmp[j] = 0; \/\/ clear\n for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {\n libxsmm_blasmm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);\n }\n add(c, tmp, m, n, ldc); \/\/ atomic\n }\n#if defined(_OPENMP)\n const double duration = omp_get_wtime() - start;\n if (0 < duration) {\n fprintf(stdout, \"\\tperformance: %.1f GFLOPS\/s\\n\", gflops \/ duration);\n fprintf(stdout, \"\\tbandwidth: %.1f GB\/s\\n\", (mbytes + nbytes) * 1E-3 \/ duration);\n }\n fprintf(stdout, \"\\tduration: %.1f s\\n\", duration);\n#endif\n#if defined(SMM_CHECK)\n std::copy(c, c + csize, expect.begin());\n#endif\n }\n\n { \/\/ inline an optimized implementation\n fprintf(stdout, \"Inlined...\\n\");\n std::fill_n(c, csize, 0);\n#if defined(_OPENMP)\n const double start = omp_get_wtime();\n# pragma omp parallel for schedule(SMM_SCHEDULE)\n#endif\n for (int i = 0; i < s; i += t) {\n LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);\n for (int j = 0; j < csize; ++j) tmp[j] = 0; \/\/ clear\n for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {\n libxsmm_imm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);\n }\n add(c, tmp, m, n, ldc); \/\/ atomic\n }\n#if defined(_OPENMP)\n const double duration = omp_get_wtime() - start;\n if (0 < duration) {\n fprintf(stdout, \"\\tperformance: %.1f GFLOPS\/s\\n\", gflops \/ duration);\n fprintf(stdout, \"\\tbandwidth: %.1f GB\/s\\n\", (mbytes + nbytes) * 1E-3 \/ duration);\n }\n fprintf(stdout, \"\\tduration: %.1f s\\n\", duration);\n#endif\n#if defined(SMM_CHECK)\n fprintf(stdout, \"\\tdiff=%f\\n\", max_diff(c, &expect[0], m, n, ldc));\n#endif\n }\n\n { \/\/ auto-dispatched\n fprintf(stdout, \"Dispatched...\\n\");\n std::fill_n(c, csize, 0);\n#if defined(_OPENMP)\n const double start = omp_get_wtime();\n# pragma omp parallel for schedule(SMM_SCHEDULE)\n#endif\n for (int i = 0; i < s; i += t) {\n LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);\n for (int j = 0; j < csize; ++j) tmp[j] = 0; \/\/ clear\n for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {\n libxsmm_mm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);\n }\n add(c, tmp, m, n, ldc); \/\/ atomic\n }\n#if defined(_OPENMP)\n const double duration = omp_get_wtime() - start;\n if (0 < duration) {\n fprintf(stdout, \"\\tperformance: %.1f GFLOPS\/s\\n\", gflops \/ duration);\n fprintf(stdout, \"\\tbandwidth: %.1f GB\/s\\n\", (mbytes + nbytes) * 1E-3 \/ duration);\n }\n fprintf(stdout, \"\\tduration: %.1f s\\n\", duration);\n#endif\n#if defined(SMM_CHECK)\n fprintf(stdout, \"\\tdiff=%f\\n\", max_diff(c, &expect[0], m, n, ldc));\n#endif\n }\n\n const libxsmm_mm_dispatch xmm(m, n, k);\n if (xmm) { \/\/ specialized routine\n fprintf(stdout, \"Specialized...\\n\");\n std::fill_n(c, csize, 0);\n#if defined(_OPENMP)\n const double start = omp_get_wtime();\n# pragma omp parallel for schedule(SMM_SCHEDULE)\n#endif\n for (int i = 0; i < s; i += t) {\n LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);\n for (int j = 0; j < csize; ++j) tmp[j] = 0; \/\/ clear\n for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {\n xmm(&a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);\n }\n add(c, tmp, m, n, ldc); \/\/ atomic\n }\n#if defined(_OPENMP)\n const double duration = omp_get_wtime() - start;\n if (0 < duration) {\n fprintf(stdout, \"\\tperformance: %.1f GFLOPS\/s\\n\", gflops \/ duration);\n fprintf(stdout, \"\\tbandwidth: %.1f GB\/s\\n\", (mbytes + nbytes) * 1E-3 \/ duration);\n }\n fprintf(stdout, \"\\tduration: %.1f s\\n\", duration);\n#endif\n#if defined(SMM_CHECK)\n fprintf(stdout, \"\\tdiff=%f\\n\", max_diff(c, &expect[0], m, n, ldc));\n#endif\n }\n\n fprintf(stdout, \"Finished\\n\");\n }\n }\n catch(const std::exception& e) {\n fprintf(stderr, \"Error: %s\\n\", e.what());\n return EXIT_FAILURE;\n }\n catch(...) {\n fprintf(stderr, \"Error: unknown exception caught!\\n\");\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2015 sails Authors.\n\/\/ All rights reserved.\n\/\/\n\/\/ Official git repository and contact information can be found at\n\/\/ https:\/\/github.com\/sails\/sails and http:\/\/www.sailsxu.com\/.\n\/\/\n\/\/ Filename: client_rpc_channel.cc\n\/\/\n\/\/ Author: sailsxu \n\/\/ Created: 2015-04-23 16:03:07\n\n\n\n#include \"rpc_channel.h\"\n#include \n#include \n#include \n#include \n#include \"sails\/net\/connector.h\"\n#include \"saf_packet.h\"\n#include \"google\/protobuf\/message.h\"\n#include \"google\/protobuf\/descriptor.h\"\n\nusing namespace google::protobuf; \/\/ NOLINT\n\n\nnamespace sails {\n\nRpcChannelImp::RpcChannelImp(string ip, int port):\n ip(ip), port(port) {\n connector = new net::Connector();\n assert(connector->connect(this->ip.c_str(), this->port, true));\n sn = 0;\n}\nRpcChannelImp::~RpcChannelImp() {\n if (connector != NULL) {\n delete connector;\n connector = NULL;\n }\n}\nvoid RpcChannelImp::CallMethod(const MethodDescriptor* method,\n RpcController *controller,\n const Message *request,\n Message *response,\n Closure *done) {\n int ret = this->sync_call(method, controller, request, response);\n if (ret == 0 && done != NULL) {\n done->Run();\n }\n}\n\nnet::PacketCommon* RpcChannelImp::parser(\n net::Connector *connector) {\n\n if (connector->readable() < sizeof(net::PacketCommon)) {\n return NULL;\n }\n net::PacketCommon *packet = (net::PacketCommon*)connector->peek();\n if (packet== NULL || packet->type.opcode >= net::PACKET_MAX) {\n \/\/ error, and empty all data\n connector->retrieve(connector->readable());\n return NULL;\n }\n if (packet != NULL) {\n uint32_t packetlen = packet->len;\n if (connector->readable() >= packetlen) {\n net::PacketCommon *item = (net::PacketCommon*)malloc(packetlen);\n memcpy(item, packet, packetlen);\n connector->retrieve(packetlen);\n return item;\n }\n }\n return NULL;\n}\n\nint RpcChannelImp::sync_call(const google::protobuf::MethodDescriptor *method,\n google::protobuf::RpcController *controller,\n const google::protobuf::Message *request,\n google::protobuf::Message *response) {\n const string service_name = method->service()->name();\n string content = request->SerializeAsString();\n\n int len = sizeof(PacketRPCRequest)+content.length()-1;\n PacketRPCRequest *packet = reinterpret_cast(malloc(len));\n new(packet) PacketRPCRequest(len, sn++);\n if (sn > INT_MAX) {\n sn = 0;\n }\n packet->version = 1.0; \/\/ client lib 版本号\n memcpy(packet->service_name, service_name.c_str(), service_name.length());\n packet->method_index = method->index();\n memcpy(packet->data, content.c_str(), content.length());\n\n connector->write(reinterpret_cast(packet), len);\n free(packet);\n if (len <= 1000) {\n connector->send();\n } else {\n printf(\"error len:%d\\n\", len);\n }\n\n int n = connector->read();\n if (n > 0) {\n bool continueParse = false;\n do {\n continueParse = false;\n net::PacketCommon *resp = RpcChannelImp::parser(connector);\n if (resp != NULL) {\n continueParse = true;\n char *body = (reinterpret_cast(resp))->data;\n string str_body(body, resp->len-sizeof(PacketRPCResponse)+1);\n if (strlen(body) > 0) {\n \/\/ protobuf message\n response->ParseFromString(str_body);\n }\n delete(resp);\n }\n } while (continueParse);\n \/\/\n }\n\n return 0;\n}\n\n\n} \/\/ namespace sails\nupdate\/\/ Copyright (C) 2015 sails Authors.\n\/\/ All rights reserved.\n\/\/\n\/\/ Official git repository and contact information can be found at\n\/\/ https:\/\/github.com\/sails\/sails and http:\/\/www.sailsxu.com\/.\n\/\/\n\/\/ Filename: client_rpc_channel.cc\n\/\/\n\/\/ Author: sailsxu \n\/\/ Created: 2015-04-23 16:03:07\n\n\n\n#include \"rpc_channel.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"sails\/net\/connector.h\"\n#include \"saf_packet.h\"\n#include \"google\/protobuf\/message.h\"\n#include \"google\/protobuf\/descriptor.h\"\n\nusing namespace google::protobuf; \/\/ NOLINT\n\n\nnamespace sails {\n\nRpcChannelImp::RpcChannelImp(string ip, int port):\n ip(ip), port(port) {\n connector = new net::Connector();\n assert(connector->connect(this->ip.c_str(), this->port, true));\n sn = 0;\n}\nRpcChannelImp::~RpcChannelImp() {\n if (connector != NULL) {\n delete connector;\n connector = NULL;\n }\n}\nvoid RpcChannelImp::CallMethod(const MethodDescriptor* method,\n RpcController *controller,\n const Message *request,\n Message *response,\n Closure *done) {\n int ret = this->sync_call(method, controller, request, response);\n if (ret == 0 && done != NULL) {\n done->Run();\n }\n}\n\nnet::PacketCommon* RpcChannelImp::parser(\n net::Connector *connector) {\n\n if (connector->readable() < sizeof(net::PacketCommon)) {\n return NULL;\n }\n net::PacketCommon *packet = (net::PacketCommon*)connector->peek();\n if (packet== NULL || packet->type.opcode >= net::PACKET_MAX) {\n \/\/ error, and empty all data\n connector->retrieve(connector->readable());\n return NULL;\n }\n if (packet != NULL) {\n uint32_t packetlen = packet->len;\n if (connector->readable() >= packetlen) {\n net::PacketCommon *item = (net::PacketCommon*)malloc(packetlen);\n memcpy(item, packet, packetlen);\n connector->retrieve(packetlen);\n return item;\n }\n }\n return NULL;\n}\n\nint RpcChannelImp::sync_call(const google::protobuf::MethodDescriptor *method,\n google::protobuf::RpcController *controller,\n const google::protobuf::Message *request,\n google::protobuf::Message *response) {\n const string service_name = method->service()->name();\n string content = request->SerializeAsString();\n\n int len = sizeof(PacketRPCRequest)+content.length()-1;\n PacketRPCRequest *packet = reinterpret_cast(malloc(len));\n new(packet) PacketRPCRequest(len, sn++);\n if (sn > INT_MAX) {\n sn = 0;\n }\n packet->version = 1.0; \/\/ client lib 版本号\n memcpy(packet->service_name, service_name.c_str(), service_name.length());\n packet->method_index = method->index();\n memcpy(packet->data, content.c_str(), content.length());\n\n connector->write(reinterpret_cast(packet), len);\n free(packet);\n if (len <= 1000) {\n connector->send();\n } else {\n printf(\"error len:%d\\n\", len);\n }\n\n int n = connector->read();\n if (n > 0) {\n bool continueParse = false;\n do {\n continueParse = false;\n net::PacketCommon *resp = RpcChannelImp::parser(connector);\n if (resp != NULL) {\n continueParse = true;\n char *body = (reinterpret_cast(resp))->data;\n string str_body(body, resp->len-sizeof(PacketRPCResponse)+1);\n if (strlen(body) > 0) {\n \/\/ protobuf message\n response->ParseFromString(str_body);\n }\n delete(resp);\n }\n } while (continueParse);\n \/\/\n }\n\n return 0;\n}\n\n\n} \/\/ namespace sails\n<|endoftext|>"} {"text":"\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ Intel License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2000, Intel Corporation, all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * The name of Intel Corporation may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors \"as is\" and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n#include \"precomp.hpp\"\n\nusing namespace std;\n\nnamespace cv\n{\n\n\/****************************************************************************************\\\n* DescriptorExtractor *\n\\****************************************************************************************\/\n\/*\n * DescriptorExtractor\n *\/\nDescriptorExtractor::~DescriptorExtractor()\n{}\n\nvoid DescriptorExtractor::compute( const Mat& image, vector& keypoints, Mat& descriptors ) const\n{ \n if( image.empty() || keypoints.empty() )\n {\n descriptors.release();\n return;\n }\n\n KeyPointsFilter::runByImageBorder( keypoints, image.size(), 0 );\n KeyPointsFilter::runByKeypointSize( keypoints, std::numeric_limits::epsilon() );\n\n computeImpl( image, keypoints, descriptors );\n}\n\nvoid DescriptorExtractor::compute( const vector& imageCollection, vector >& pointCollection, vector& descCollection ) const\n{\n CV_Assert( imageCollection.size() == pointCollection.size() );\n descCollection.resize( imageCollection.size() );\n for( size_t i = 0; i < imageCollection.size(); i++ )\n compute( imageCollection[i], pointCollection[i], descCollection[i] );\n}\n\n\/*void DescriptorExtractor::read( const FileNode& )\n{}\n\nvoid DescriptorExtractor::write( FileStorage& ) const\n{}*\/\n\nbool DescriptorExtractor::empty() const\n{\n return false;\n}\n\nvoid DescriptorExtractor::removeBorderKeypoints( vector& keypoints,\n Size imageSize, int borderSize )\n{\n KeyPointsFilter::runByImageBorder( keypoints, imageSize, borderSize );\n}\n\nPtr DescriptorExtractor::create(const string& descriptorExtractorType)\n{\n if( descriptorExtractorType.find(\"Opponent\") == 0)\n {\n size_t pos = string(\"Opponent\").size();\n return DescriptorExtractor::create(descriptorExtractorType.substr(pos));\n }\n \n return Algorithm::create(\"Feature2D.\" + descriptorExtractorType);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/****************************************************************************************\\\n* OpponentColorDescriptorExtractor *\n\\****************************************************************************************\/\nOpponentColorDescriptorExtractor::OpponentColorDescriptorExtractor( const Ptr& _descriptorExtractor ) :\n descriptorExtractor(_descriptorExtractor)\n{\n CV_Assert( !descriptorExtractor.empty() );\n}\n\nvoid convertBGRImageToOpponentColorSpace( const Mat& bgrImage, vector& opponentChannels )\n{\n if( bgrImage.type() != CV_8UC3 )\n CV_Error( CV_StsBadArg, \"input image must be an BGR image of type CV_8UC3\" );\n\n \/\/ Split image into RGB to allow conversion to Opponent Color Space.\n vector bgrChannels(3);\n split( bgrImage, bgrChannels );\n\n \/\/ Prepare opponent color space storage matrices.\n opponentChannels.resize( 3 );\n opponentChannels[0] = cv::Mat(bgrImage.size(), CV_8UC1); \/\/ R-G RED-GREEN\n opponentChannels[1] = cv::Mat(bgrImage.size(), CV_8UC1); \/\/ R+G-2B YELLOW-BLUE\n opponentChannels[2] = cv::Mat(bgrImage.size(), CV_8UC1); \/\/ R+G+B\n\n \/\/ Calculate the channels of the opponent color space\n {\n \/\/ (R - G) \/ sqrt(2)\n MatConstIterator_ rIt = bgrChannels[2].begin();\n MatConstIterator_ gIt = bgrChannels[1].begin();\n MatIterator_ dstIt = opponentChannels[0].begin();\n float factor = 1.f \/ sqrt(2.f);\n for( ; dstIt != opponentChannels[0].end(); ++rIt, ++gIt, ++dstIt )\n {\n int value = static_cast( static_cast(static_cast(*gIt)-static_cast(*rIt)) * factor );\n if( value < 0 ) value = 0;\n if( value > 255 ) value = 255;\n (*dstIt) = static_cast(value);\n }\n }\n {\n \/\/ (R + G - 2B)\/sqrt(6)\n MatConstIterator_ rIt = bgrChannels[2].begin();\n MatConstIterator_ gIt = bgrChannels[1].begin();\n MatConstIterator_ bIt = bgrChannels[0].begin();\n MatIterator_ dstIt = opponentChannels[1].begin();\n float factor = 1.f \/ sqrt(6.f);\n for( ; dstIt != opponentChannels[1].end(); ++rIt, ++gIt, ++bIt, ++dstIt )\n {\n int value = static_cast( static_cast(static_cast(*rIt) + static_cast(*gIt) - 2*static_cast(*bIt)) *\n factor );\n if( value < 0 ) value = 0;\n if( value > 255 ) value = 255;\n (*dstIt) = static_cast(value);\n }\n }\n {\n \/\/ (R + G + B)\/sqrt(3)\n MatConstIterator_ rIt = bgrChannels[2].begin();\n MatConstIterator_ gIt = bgrChannels[1].begin();\n MatConstIterator_ bIt = bgrChannels[0].begin();\n MatIterator_ dstIt = opponentChannels[2].begin();\n float factor = 1.f \/ sqrt(3.f);\n for( ; dstIt != opponentChannels[2].end(); ++rIt, ++gIt, ++bIt, ++dstIt )\n {\n int value = static_cast( static_cast(static_cast(*rIt) + static_cast(*gIt) + static_cast(*bIt)) *\n factor );\n if( value < 0 ) value = 0;\n if( value > 255 ) value = 255;\n (*dstIt) = static_cast(value);\n }\n }\n}\n\nstruct KP_LessThan\n{\n KP_LessThan(const vector& _kp) : kp(&_kp) {}\n bool operator()(int i, int j) const\n {\n return (*kp)[i].class_id < (*kp)[j].class_id;\n }\n const vector* kp;\n};\n\nvoid OpponentColorDescriptorExtractor::computeImpl( const Mat& bgrImage, vector& keypoints, Mat& descriptors ) const\n{\n vector opponentChannels;\n convertBGRImageToOpponentColorSpace( bgrImage, opponentChannels );\n\n const int N = 3; \/\/ channels count\n vector channelKeypoints[N];\n Mat channelDescriptors[N];\n vector idxs[N];\n\n \/\/ Compute descriptors three times, once for each Opponent channel to concatenate into a single color descriptor\n int maxKeypointsCount = 0;\n for( int ci = 0; ci < N; ci++ )\n {\n channelKeypoints[ci].insert( channelKeypoints[ci].begin(), keypoints.begin(), keypoints.end() );\n \/\/ Use class_id member to get indices into initial keypoints vector\n for( size_t ki = 0; ki < channelKeypoints[ci].size(); ki++ )\n channelKeypoints[ci][ki].class_id = (int)ki;\n\n descriptorExtractor->compute( opponentChannels[ci], channelKeypoints[ci], channelDescriptors[ci] );\n idxs[ci].resize( channelKeypoints[ci].size() );\n for( size_t ki = 0; ki < channelKeypoints[ci].size(); ki++ )\n {\n idxs[ci][ki] = (int)ki;\n }\n std::sort( idxs[ci].begin(), idxs[ci].end(), KP_LessThan(channelKeypoints[ci]) );\n maxKeypointsCount = std::max( maxKeypointsCount, (int)channelKeypoints[ci].size());\n }\n\n vector outKeypoints;\n outKeypoints.reserve( keypoints.size() );\n\n int descriptorSize = descriptorExtractor->descriptorSize();\n Mat mergedDescriptors( maxKeypointsCount, 3*descriptorSize, descriptorExtractor->descriptorType() );\n int mergedCount = 0;\n \/\/ cp - current channel position\n size_t cp[] = {0, 0, 0}; \n while( cp[0] < channelKeypoints[0].size() &&\n cp[1] < channelKeypoints[1].size() &&\n cp[2] < channelKeypoints[2].size() )\n {\n const int maxInitIdx = std::max( channelKeypoints[0][idxs[0][cp[0]]].class_id,\n std::max( channelKeypoints[1][idxs[1][cp[1]]].class_id,\n channelKeypoints[2][idxs[2][cp[2]]].class_id ) );\n\n while( channelKeypoints[0][idxs[0][cp[0]]].class_id < maxInitIdx && cp[0] < channelKeypoints[0].size() ) { cp[0]++; }\n while( channelKeypoints[1][idxs[1][cp[1]]].class_id < maxInitIdx && cp[1] < channelKeypoints[1].size() ) { cp[1]++; }\n while( channelKeypoints[2][idxs[2][cp[2]]].class_id < maxInitIdx && cp[2] < channelKeypoints[2].size() ) { cp[2]++; }\n if( cp[0] >= channelKeypoints[0].size() || cp[1] >= channelKeypoints[1].size() || cp[2] >= channelKeypoints[2].size() )\n break;\n\n if( channelKeypoints[0][idxs[0][cp[0]]].class_id == maxInitIdx &&\n channelKeypoints[1][idxs[1][cp[1]]].class_id == maxInitIdx &&\n channelKeypoints[2][idxs[2][cp[2]]].class_id == maxInitIdx )\n {\n outKeypoints.push_back( keypoints[maxInitIdx] );\n \/\/ merge descriptors\n for( int ci = 0; ci < N; ci++ )\n {\n Mat dst = mergedDescriptors(Range(mergedCount, mergedCount+1), Range(ci*descriptorSize, (ci+1)*descriptorSize));\n channelDescriptors[ci].row( idxs[ci][cp[ci]] ).copyTo( dst );\n cp[ci]++;\n }\n mergedCount++;\n }\n }\n mergedDescriptors.rowRange(0, mergedCount).copyTo( descriptors );\n std::swap( outKeypoints, keypoints );\n}\n\nvoid OpponentColorDescriptorExtractor::read( const FileNode& fn )\n{\n descriptorExtractor->read(fn);\n}\n\nvoid OpponentColorDescriptorExtractor::write( FileStorage& fs ) const\n{\n descriptorExtractor->write(fs);\n}\n\nint OpponentColorDescriptorExtractor::descriptorSize() const\n{\n return 3*descriptorExtractor->descriptorSize();\n}\n\nint OpponentColorDescriptorExtractor::descriptorType() const\n{\n return descriptorExtractor->descriptorType();\n}\n\nbool OpponentColorDescriptorExtractor::empty() const\n{\n return descriptorExtractor.empty() || (DescriptorExtractor*)(descriptorExtractor)->empty();\n}\n\n}\nfixed creation of opponent space descriptors (#1805)\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ Intel License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2000, Intel Corporation, all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * The name of Intel Corporation may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors \"as is\" and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n#include \"precomp.hpp\"\n\nusing namespace std;\n\nnamespace cv\n{\n\n\/****************************************************************************************\\\n* DescriptorExtractor *\n\\****************************************************************************************\/\n\/*\n * DescriptorExtractor\n *\/\nDescriptorExtractor::~DescriptorExtractor()\n{}\n\nvoid DescriptorExtractor::compute( const Mat& image, vector& keypoints, Mat& descriptors ) const\n{ \n if( image.empty() || keypoints.empty() )\n {\n descriptors.release();\n return;\n }\n\n KeyPointsFilter::runByImageBorder( keypoints, image.size(), 0 );\n KeyPointsFilter::runByKeypointSize( keypoints, std::numeric_limits::epsilon() );\n\n computeImpl( image, keypoints, descriptors );\n}\n\nvoid DescriptorExtractor::compute( const vector& imageCollection, vector >& pointCollection, vector& descCollection ) const\n{\n CV_Assert( imageCollection.size() == pointCollection.size() );\n descCollection.resize( imageCollection.size() );\n for( size_t i = 0; i < imageCollection.size(); i++ )\n compute( imageCollection[i], pointCollection[i], descCollection[i] );\n}\n\n\/*void DescriptorExtractor::read( const FileNode& )\n{}\n\nvoid DescriptorExtractor::write( FileStorage& ) const\n{}*\/\n\nbool DescriptorExtractor::empty() const\n{\n return false;\n}\n\nvoid DescriptorExtractor::removeBorderKeypoints( vector& keypoints,\n Size imageSize, int borderSize )\n{\n KeyPointsFilter::runByImageBorder( keypoints, imageSize, borderSize );\n}\n\nPtr DescriptorExtractor::create(const string& descriptorExtractorType)\n{\n if( descriptorExtractorType.find(\"Opponent\") == 0 )\n {\n size_t pos = string(\"Opponent\").size();\n string type = descriptorExtractorType.substr(pos);\n return new OpponentColorDescriptorExtractor(DescriptorExtractor::create(type));\n }\n \n return Algorithm::create(\"Feature2D.\" + descriptorExtractorType);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/****************************************************************************************\\\n* OpponentColorDescriptorExtractor *\n\\****************************************************************************************\/\nOpponentColorDescriptorExtractor::OpponentColorDescriptorExtractor( const Ptr& _descriptorExtractor ) :\n descriptorExtractor(_descriptorExtractor)\n{\n CV_Assert( !descriptorExtractor.empty() );\n}\n\nvoid convertBGRImageToOpponentColorSpace( const Mat& bgrImage, vector& opponentChannels )\n{\n if( bgrImage.type() != CV_8UC3 )\n CV_Error( CV_StsBadArg, \"input image must be an BGR image of type CV_8UC3\" );\n\n \/\/ Split image into RGB to allow conversion to Opponent Color Space.\n vector bgrChannels(3);\n split( bgrImage, bgrChannels );\n\n \/\/ Prepare opponent color space storage matrices.\n opponentChannels.resize( 3 );\n opponentChannels[0] = cv::Mat(bgrImage.size(), CV_8UC1); \/\/ R-G RED-GREEN\n opponentChannels[1] = cv::Mat(bgrImage.size(), CV_8UC1); \/\/ R+G-2B YELLOW-BLUE\n opponentChannels[2] = cv::Mat(bgrImage.size(), CV_8UC1); \/\/ R+G+B\n\n \/\/ Calculate the channels of the opponent color space\n {\n \/\/ (R - G) \/ sqrt(2)\n MatConstIterator_ rIt = bgrChannels[2].begin();\n MatConstIterator_ gIt = bgrChannels[1].begin();\n MatIterator_ dstIt = opponentChannels[0].begin();\n float factor = 1.f \/ sqrt(2.f);\n for( ; dstIt != opponentChannels[0].end(); ++rIt, ++gIt, ++dstIt )\n {\n int value = static_cast( static_cast(static_cast(*gIt)-static_cast(*rIt)) * factor );\n if( value < 0 ) value = 0;\n if( value > 255 ) value = 255;\n (*dstIt) = static_cast(value);\n }\n }\n {\n \/\/ (R + G - 2B)\/sqrt(6)\n MatConstIterator_ rIt = bgrChannels[2].begin();\n MatConstIterator_ gIt = bgrChannels[1].begin();\n MatConstIterator_ bIt = bgrChannels[0].begin();\n MatIterator_ dstIt = opponentChannels[1].begin();\n float factor = 1.f \/ sqrt(6.f);\n for( ; dstIt != opponentChannels[1].end(); ++rIt, ++gIt, ++bIt, ++dstIt )\n {\n int value = static_cast( static_cast(static_cast(*rIt) + static_cast(*gIt) - 2*static_cast(*bIt)) *\n factor );\n if( value < 0 ) value = 0;\n if( value > 255 ) value = 255;\n (*dstIt) = static_cast(value);\n }\n }\n {\n \/\/ (R + G + B)\/sqrt(3)\n MatConstIterator_ rIt = bgrChannels[2].begin();\n MatConstIterator_ gIt = bgrChannels[1].begin();\n MatConstIterator_ bIt = bgrChannels[0].begin();\n MatIterator_ dstIt = opponentChannels[2].begin();\n float factor = 1.f \/ sqrt(3.f);\n for( ; dstIt != opponentChannels[2].end(); ++rIt, ++gIt, ++bIt, ++dstIt )\n {\n int value = static_cast( static_cast(static_cast(*rIt) + static_cast(*gIt) + static_cast(*bIt)) *\n factor );\n if( value < 0 ) value = 0;\n if( value > 255 ) value = 255;\n (*dstIt) = static_cast(value);\n }\n }\n}\n\nstruct KP_LessThan\n{\n KP_LessThan(const vector& _kp) : kp(&_kp) {}\n bool operator()(int i, int j) const\n {\n return (*kp)[i].class_id < (*kp)[j].class_id;\n }\n const vector* kp;\n};\n\nvoid OpponentColorDescriptorExtractor::computeImpl( const Mat& bgrImage, vector& keypoints, Mat& descriptors ) const\n{\n vector opponentChannels;\n convertBGRImageToOpponentColorSpace( bgrImage, opponentChannels );\n\n const int N = 3; \/\/ channels count\n vector channelKeypoints[N];\n Mat channelDescriptors[N];\n vector idxs[N];\n\n \/\/ Compute descriptors three times, once for each Opponent channel to concatenate into a single color descriptor\n int maxKeypointsCount = 0;\n for( int ci = 0; ci < N; ci++ )\n {\n channelKeypoints[ci].insert( channelKeypoints[ci].begin(), keypoints.begin(), keypoints.end() );\n \/\/ Use class_id member to get indices into initial keypoints vector\n for( size_t ki = 0; ki < channelKeypoints[ci].size(); ki++ )\n channelKeypoints[ci][ki].class_id = (int)ki;\n\n descriptorExtractor->compute( opponentChannels[ci], channelKeypoints[ci], channelDescriptors[ci] );\n idxs[ci].resize( channelKeypoints[ci].size() );\n for( size_t ki = 0; ki < channelKeypoints[ci].size(); ki++ )\n {\n idxs[ci][ki] = (int)ki;\n }\n std::sort( idxs[ci].begin(), idxs[ci].end(), KP_LessThan(channelKeypoints[ci]) );\n maxKeypointsCount = std::max( maxKeypointsCount, (int)channelKeypoints[ci].size());\n }\n\n vector outKeypoints;\n outKeypoints.reserve( keypoints.size() );\n\n int descriptorSize = descriptorExtractor->descriptorSize();\n Mat mergedDescriptors( maxKeypointsCount, 3*descriptorSize, descriptorExtractor->descriptorType() );\n int mergedCount = 0;\n \/\/ cp - current channel position\n size_t cp[] = {0, 0, 0}; \n while( cp[0] < channelKeypoints[0].size() &&\n cp[1] < channelKeypoints[1].size() &&\n cp[2] < channelKeypoints[2].size() )\n {\n const int maxInitIdx = std::max( channelKeypoints[0][idxs[0][cp[0]]].class_id,\n std::max( channelKeypoints[1][idxs[1][cp[1]]].class_id,\n channelKeypoints[2][idxs[2][cp[2]]].class_id ) );\n\n while( channelKeypoints[0][idxs[0][cp[0]]].class_id < maxInitIdx && cp[0] < channelKeypoints[0].size() ) { cp[0]++; }\n while( channelKeypoints[1][idxs[1][cp[1]]].class_id < maxInitIdx && cp[1] < channelKeypoints[1].size() ) { cp[1]++; }\n while( channelKeypoints[2][idxs[2][cp[2]]].class_id < maxInitIdx && cp[2] < channelKeypoints[2].size() ) { cp[2]++; }\n if( cp[0] >= channelKeypoints[0].size() || cp[1] >= channelKeypoints[1].size() || cp[2] >= channelKeypoints[2].size() )\n break;\n\n if( channelKeypoints[0][idxs[0][cp[0]]].class_id == maxInitIdx &&\n channelKeypoints[1][idxs[1][cp[1]]].class_id == maxInitIdx &&\n channelKeypoints[2][idxs[2][cp[2]]].class_id == maxInitIdx )\n {\n outKeypoints.push_back( keypoints[maxInitIdx] );\n \/\/ merge descriptors\n for( int ci = 0; ci < N; ci++ )\n {\n Mat dst = mergedDescriptors(Range(mergedCount, mergedCount+1), Range(ci*descriptorSize, (ci+1)*descriptorSize));\n channelDescriptors[ci].row( idxs[ci][cp[ci]] ).copyTo( dst );\n cp[ci]++;\n }\n mergedCount++;\n }\n }\n mergedDescriptors.rowRange(0, mergedCount).copyTo( descriptors );\n std::swap( outKeypoints, keypoints );\n}\n\nvoid OpponentColorDescriptorExtractor::read( const FileNode& fn )\n{\n descriptorExtractor->read(fn);\n}\n\nvoid OpponentColorDescriptorExtractor::write( FileStorage& fs ) const\n{\n descriptorExtractor->write(fs);\n}\n\nint OpponentColorDescriptorExtractor::descriptorSize() const\n{\n return 3*descriptorExtractor->descriptorSize();\n}\n\nint OpponentColorDescriptorExtractor::descriptorType() const\n{\n return descriptorExtractor->descriptorType();\n}\n\nbool OpponentColorDescriptorExtractor::empty() const\n{\n return descriptorExtractor.empty() || (DescriptorExtractor*)(descriptorExtractor)->empty();\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * (C) Copyright 2015 ETH Zurich Systems Group (http:\/\/www.systems.ethz.ch\/) and others.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * Contributors:\n * Markus Pilman \n * Simon Loesing \n * Thomas Etter \n * Kevin Bocksrocker \n * Lucas Braun \n *\n * --------------------------------------------------------------------\n *\n * This file was copied and slightly adapted from the KaleidoscopeJIT.h\n * unter the following licencse:\n *\n * ===----- KaleidoscopeJIT.h - A simple JIT for Kaleidoscope ----*- C++ -*-===\n *\n * The LLVM Compiler Infrastructure\n *\n * This file is distributed under the University of Illinois Open Source\n * License. See LICENSE.TXT for details.\n *\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\nnamespace llvm {\nclass Module;\nclass TargetMachine;\n} \/\/ namespace llvm\n\nnamespace tell {\nnamespace store {\n\n\/**\n * @brief Singleton for initializing and configuring the LLVM infrastructure\n *\n * Initializes the native target and sets up the TargetMachine with the features available on the host the application\n * is running.\n *\/\nclass LLVMCompilerT {\npublic:\n LLVMCompilerT();\n\n ~LLVMCompilerT();\n\n llvm::TargetMachine* targetMachine() {\n return mTargetMachine.get();\n }\n\nprivate:\n std::unique_ptr mTargetMachine;\n};\n\nusing LLVMCompiler = crossbow::singleton;\n\nextern LLVMCompiler llvmCompiler;\n\n\/**\n * @brief JIT based on LLVM\n *\/\nclass LLVMJIT {\npublic:\n using ObjectLayer = llvm::orc::ObjectLinkingLayer<>;\n using CompileLayer = llvm::orc::IRCompileLayer;\n using ModuleHandle = CompileLayer::ModuleSetHandleT;\n\n LLVMJIT();\n\n llvm::TargetMachine* getTargetMachine() {\n return mTargetMachine;\n }\n\n \/**\n * @brief Compile the given module through the JIT\n *\n * The compiled functions can then be retrieved through the LLVMJIT::findSymbol function. Afterwards the module can\n * be destroyed.\n *\/\n ModuleHandle addModule(llvm::Module* module);\n\n void removeModule(ModuleHandle handle) {\n mCompileLayer.removeModuleSet(handle);\n }\n\n llvm::orc::JITSymbol findSymbol(const std::string& name) {\n return mCompileLayer.findSymbol(mangle(name), true);\n }\n\nprivate:\n std::string mangle(const std::string& name) {\n std::string mangledName;\n {\n llvm::raw_string_ostream mangledNameStream(mangledName);\n llvm::Mangler::getNameWithPrefix(mangledNameStream, name, mDataLayout);\n }\n return mangledName;\n }\n\n llvm::TargetMachine* mTargetMachine;\n llvm::DataLayout mDataLayout;\n ObjectLayer mObjectLayer;\n CompileLayer mCompileLayer;\n};\n\n} \/\/ namespace store\n} \/\/ namespace tell\nAdd findFunction and make LLVM Jit non copyable\/*\n * (C) Copyright 2015 ETH Zurich Systems Group (http:\/\/www.systems.ethz.ch\/) and others.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * Contributors:\n * Markus Pilman \n * Simon Loesing \n * Thomas Etter \n * Kevin Bocksrocker \n * Lucas Braun \n *\n * --------------------------------------------------------------------\n *\n * This file was copied and slightly adapted from the KaleidoscopeJIT.h\n * unter the following licencse:\n *\n * ===----- KaleidoscopeJIT.h - A simple JIT for Kaleidoscope ----*- C++ -*-===\n *\n * The LLVM Compiler Infrastructure\n *\n * This file is distributed under the University of Illinois Open Source\n * License. See LICENSE.TXT for details.\n *\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nnamespace llvm {\nclass Module;\nclass TargetMachine;\n} \/\/ namespace llvm\n\nnamespace tell {\nnamespace store {\n\n\/**\n * @brief Singleton for initializing and configuring the LLVM infrastructure\n *\n * Initializes the native target and sets up the TargetMachine with the features available on the host the application\n * is running.\n *\/\nclass LLVMCompilerT {\npublic:\n LLVMCompilerT();\n\n ~LLVMCompilerT();\n\n llvm::TargetMachine* targetMachine() {\n return mTargetMachine.get();\n }\n\nprivate:\n std::unique_ptr mTargetMachine;\n};\n\nusing LLVMCompiler = crossbow::singleton;\n\nextern LLVMCompiler llvmCompiler;\n\n\/**\n * @brief JIT based on LLVM\n *\/\nclass LLVMJIT : crossbow::non_copyable, crossbow::non_movable {\npublic:\n using ObjectLayer = llvm::orc::ObjectLinkingLayer<>;\n using CompileLayer = llvm::orc::IRCompileLayer;\n using ModuleHandle = CompileLayer::ModuleSetHandleT;\n\n LLVMJIT();\n\n llvm::TargetMachine* getTargetMachine() {\n return mTargetMachine;\n }\n\n \/**\n * @brief Compile the given module through the JIT\n *\n * The compiled functions can then be retrieved through the LLVMJIT::findSymbol function. Afterwards the module can\n * be destroyed.\n *\/\n ModuleHandle addModule(llvm::Module* module);\n\n void removeModule(ModuleHandle handle) {\n mCompileLayer.removeModuleSet(handle);\n }\n\n llvm::orc::JITSymbol findSymbol(const std::string& name) {\n return mCompileLayer.findSymbol(mangle(name), true);\n }\n\n template \n Func findFunction(const std::string& name) {\n auto func = mCompileLayer.findSymbol(mangle(name), true);\n if (!func) {\n throw std::runtime_error(\"Unknown symbol\");\n }\n return reinterpret_cast(func.getAddress());\n }\n\nprivate:\n std::string mangle(const std::string& name) {\n std::string mangledName;\n {\n llvm::raw_string_ostream mangledNameStream(mangledName);\n llvm::Mangler::getNameWithPrefix(mangledNameStream, name, mDataLayout);\n }\n return mangledName;\n }\n\n llvm::TargetMachine* mTargetMachine;\n llvm::DataLayout mDataLayout;\n ObjectLayer mObjectLayer;\n CompileLayer mCompileLayer;\n};\n\n} \/\/ namespace store\n} \/\/ namespace tell\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2015 Luke San Antonio\n * All rights reserved.\n *\/\n#include \"sdl_helper.h\"\n#include \"common\/log.h\"\n#include \"common\/debugging.h\"\nnamespace redc\n{\n SDL_Init_Lock::SDL_Init_Lock(SDL_Init_Lock&& l) : window(l.window),\n gl_context(l.gl_context)\n {\n l.window = nullptr;\n l.gl_context = nullptr;\n }\n\n SDL_Init_Lock& SDL_Init_Lock::operator=(SDL_Init_Lock&& l)\n {\n window = l.window;\n gl_context = l.gl_context;\n\n l.window = nullptr;\n l.gl_context = nullptr;\n\n return *this;\n }\n\n SDL_Init_Lock::~SDL_Init_Lock()\n {\n \/\/ If we don't have both for any reason, don't bother deallocating either.\n if(window && gl_context)\n {\n \/\/ That way, if we accidentally partially move we won't do the aggressive\n \/\/ SDL_Quit call.\n\n SDL_GL_DeleteContext(gl_context);\n SDL_DestroyWindow(window);\n SDL_Quit();\n }\n }\n\n SDL_Init_Lock init_sdl(std::string title, Vec res, bool fullscreen,\n bool vsync)\n {\n \/\/ Initialize SDL\n\n if(SDL_Init(SDL_INIT_VIDEO))\n {\n log_e(\"Failed to init SDL\");\n return {};\n }\n\n SDL_version version;\n SDL_GetVersion(&version);\n\n log_i(\"Initialized SDL %.%.%\", version.major, version.minor, version.patch);\n\n \/\/ Initialize window\n\n int flags = SDL_WINDOW_OPENGL;\n if(fullscreen) flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;\n\n SDL_Init_Lock ret;\n\n ret.window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED,\n SDL_WINDOWPOS_UNDEFINED, res.x, res.y,\n flags);\n if(!ret.window)\n {\n SDL_Quit();\n log_e(\"Failed to initialize SDL for resolution %x%\", res.x, res.y);\n return ret;\n }\n\n \/\/ Initialize OpenGL context\n\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,\n SDL_GL_CONTEXT_PROFILE_CORE);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS,\n SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);\n SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 1);\n\n ret.gl_context = SDL_GL_CreateContext(ret.window);\n SDL_GL_MakeCurrent(ret.window, ret.gl_context);\n\n \/\/ Set vsync setting\n int sync_interval = 0;\n if(vsync) sync_interval = 1;\n if(SDL_GL_SetSwapInterval(sync_interval) == -1)\n {\n \/\/ Shit, failed to set that\n log_w(\"Failed to set swap interval: %\", SDL_GetError());\n }\n\n gladLoadGLLoader((GLADloadproc) SDL_GL_GetProcAddress);\n\n int opengl_maj, opengl_min;\n glGetIntegerv(GL_MAJOR_VERSION, &opengl_maj);\n glGetIntegerv(GL_MINOR_VERSION, &opengl_min);\n log_i(\"OpenGL core profile %.%\", opengl_maj, opengl_min);\n\n GLint front_type = 0;\n glGetFramebufferAttachmentParameteriv(\n GL_DRAW_FRAMEBUFFER, GL_BACK_LEFT,\n GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, &front_type\n );\n std::string framebuf_string(\"Unknown type\");\n switch(front_type)\n {\n case GL_LINEAR:\n framebuf_string = \"RGB\";\n break;\n case GL_SRGB:\n framebuf_string = \"sRGB\";\n break;\n default:\n REDC_UNREACHABLE_MSG(\"Invalid framebuffer type\");\n }\n log_d(\"Using % framebuffer\", framebuf_string);\n\n return ret;\n }\n}\nDon't be so picky about our OpenGL context\/*\n * Copyright (C) 2015 Luke San Antonio\n * All rights reserved.\n *\/\n#include \"sdl_helper.h\"\n#include \"common\/log.h\"\n#include \"common\/debugging.h\"\nnamespace redc\n{\n SDL_Init_Lock::SDL_Init_Lock(SDL_Init_Lock&& l) : window(l.window),\n gl_context(l.gl_context)\n {\n l.window = nullptr;\n l.gl_context = nullptr;\n }\n\n SDL_Init_Lock& SDL_Init_Lock::operator=(SDL_Init_Lock&& l)\n {\n window = l.window;\n gl_context = l.gl_context;\n\n l.window = nullptr;\n l.gl_context = nullptr;\n\n return *this;\n }\n\n SDL_Init_Lock::~SDL_Init_Lock()\n {\n \/\/ If we don't have both for any reason, don't bother deallocating either.\n if(window && gl_context)\n {\n \/\/ That way, if we accidentally partially move we won't do the aggressive\n \/\/ SDL_Quit call.\n\n SDL_GL_DeleteContext(gl_context);\n SDL_DestroyWindow(window);\n SDL_Quit();\n }\n }\n\n SDL_Init_Lock init_sdl(std::string title, Vec res, bool fullscreen,\n bool vsync)\n {\n \/\/ Initialize SDL\n\n if(SDL_Init(SDL_INIT_VIDEO))\n {\n log_e(\"Failed to init SDL\");\n return {};\n }\n\n SDL_version version;\n SDL_GetVersion(&version);\n\n log_i(\"Initialized SDL %.%.%\", version.major, version.minor, version.patch);\n\n \/\/ Initialize window\n\n int flags = SDL_WINDOW_OPENGL;\n if(fullscreen) flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;\n\n SDL_Init_Lock ret;\n\n ret.window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED,\n SDL_WINDOWPOS_UNDEFINED, res.x, res.y,\n flags);\n if(!ret.window)\n {\n SDL_Quit();\n log_e(\"Failed to initialize SDL for resolution %x%\", res.x, res.y);\n return ret;\n }\n\n \/\/ Initialize OpenGL context\n\n SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 1);\n\n ret.gl_context = SDL_GL_CreateContext(ret.window);\n if(ret.gl_context == NULL)\n {\n log_e(\"Failed to create OpenGL context: %\", SDL_GetError());\n }\n\n SDL_GL_MakeCurrent(ret.window, ret.gl_context);\n\n \/\/ Set vsync setting\n int sync_interval = 0;\n if(vsync) sync_interval = 1;\n if(SDL_GL_SetSwapInterval(sync_interval) == -1)\n {\n \/\/ Shit, failed to set that\n log_w(\"Failed to set swap interval: %\", SDL_GetError());\n }\n\n gladLoadGLLoader((GLADloadproc) SDL_GL_GetProcAddress);\n\n int opengl_maj, opengl_min;\n glGetIntegerv(GL_MAJOR_VERSION, &opengl_maj);\n glGetIntegerv(GL_MINOR_VERSION, &opengl_min);\n log_i(\"OpenGL core profile %.%\", opengl_maj, opengl_min);\n\n GLint front_type = 0;\n glGetFramebufferAttachmentParameteriv(\n GL_DRAW_FRAMEBUFFER, GL_BACK_LEFT,\n GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, &front_type\n );\n std::string framebuf_string(\"Unknown type\");\n switch(front_type)\n {\n case GL_LINEAR:\n framebuf_string = \"RGB\";\n break;\n case GL_SRGB:\n framebuf_string = \"sRGB\";\n break;\n default:\n REDC_UNREACHABLE_MSG(\"Invalid framebuffer type\");\n }\n log_d(\"Using % framebuffer\", framebuf_string);\n\n return ret;\n }\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @file main.cc\n\/\/ @brief Morse code generator\n\/\/ @author Mamoru Kaminaga\n\/\/ @date 2016-05-15 12:08:31\n\/\/ Copyright 2016 Mamoru Kaminaga\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \n#include \n#include \n#include \"common.h\"\n#include \"morse_player.h\"\n#include \"resource.h\"\n#define WINDOW_STYLE (WS_POPUP|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX)\nenum OPTIONS {\n OPTION_HELP = 0,\n OPTION_STRING,\n OPTION_NOWINDOW,\n OPTION_NOSOUND,\n OPTION_WPM,\n OPTION_PARIS,\n ELEMNUM_OPTIONS, \/\/ Array size.\n};\nconst wchar_t kOptions[ELEMNUM_OPTIONS][16] = {\n L\"-help\", \/\/ OPTION_HELP\n L\"-s\", \/\/ OPTION_STRING\n L\"-nowindow\", \/\/ OPTION_NOWINDOW\n L\"-nosound\", \/\/ OPTION_NOSOUND\n L\"-wpm\", \/\/ OPTION_WPM\n L\"-paris\", \/\/ OPTION_PARIS\n};\nconst wchar_t kHelp[ELEMNUM_OPTIONS][64] = {\n L\"Show help\", \/\/ OPTION_HELP\n L\"Input string to be morse signal\", \/\/ OPTION_STRING\n L\"Not show output console\", \/\/ OPTION_NOWINDOW\n L\"Not play midi sound\", \/\/ OPTION_NOSOUND\n L\"Set WPM, default is 20\", \/\/ OPTION_WPM\n L\"Set PARIS, default is 20\", \/\/ OPTION_PARIS\n};\nbool help_required = false;\nbool no_console = false;\nbool no_sound = false;\nbool play_command_line_string = false;\nint string_argc_offset = 0;\nvoid ShowAndPlay(MorsePlayer* morse_player, wchar_t charactor);\nbool CreateInvisibleWindow(HINSTANCE instance_handle);\nint WINAPI wWinMain(HINSTANCE instance_handle, HINSTANCE not_used,\n LPTSTR cmd_lind, int cmd_show) {\n \/\/ Prevent warnings for unreferenced parameters.\n UNREFERENCED_PARAMETER(instance_handle);\n UNREFERENCED_PARAMETER(not_used);\n UNREFERENCED_PARAMETER(cmd_lind);\n UNREFERENCED_PARAMETER(cmd_show);\n \/\/\n MorsePlayer morse_player;\n morse_player.Initialize();\n morse_player.dot_len_ = 60;\n \/\/ Command line is processed.\n for (int i = 1; i < __argc; ++i) {\n for (int j = 0; j < ELEMNUM_OPTIONS; ++j) {\n if (wcscmp(__wargv[i], kOptions[j]) == 0) {\n switch (j) {\n case OPTION_HELP:\n help_required = true;\n break;\n case OPTION_NOWINDOW:\n no_console = true;\n break;\n case OPTION_NOSOUND:\n no_sound = true;\n break;\n case OPTION_WPM: \/\/ Same as OPTION_PARIS\n case OPTION_PARIS:\n \/* wpm (paris) -> dot millis *\/\n morse_player.dot_len_ = 60000 \/ (_wtoi(__wargv[i + 1]) * 50);\n break;\n case OPTION_STRING:\n play_command_line_string = true;\n string_argc_offset = i + 1;\n default:\n break;\n }\n }\n }\n }\n \/\/ Win32 Console is initialized.\n if (!no_console) {\n\t\tif (!AttachConsole(ATTACH_PARENT_PROCESS)) AllocConsole();\n freopen(\"CON\", \"r\", stdin);\n freopen(\"CON\", \"w\", stdout);\n }\n \/\/ Argument num error check done.\n if (__argc <= 1) {\n if (no_console) {\n DialogError(L\"No arguments specified\");\n return -1;\n } else {\n PrintError(L\"No arguments specified\");\n goto ERROR_EXIT;\n }\n }\n \/\/ Help option process.\n if (help_required) {\n if (no_console) {\n DialogError(L\"You must not set -nowindow option to show help\");\n return 0;\n } else {\n wprintf(APP_NAME);\n wprintf(L\"\\n\");\n wprintf(L\"options:\\n\");\n for (int i = 0; i < ELEMNUM_OPTIONS; ++i) {\n wprintf(L\"%s:\\t%s\\n\", kOptions[i], kHelp[i]);\n }\n goto ERROR_EXIT;\n }\n }\n \/\/ String error.\n if (play_command_line_string == false) {\n if (no_console) {\n DialogError(L\"No input string\");\n return -1;\n } else {\n PrintError(L\"No input string\");\n goto ERROR_EXIT;\n }\n }\n \/\/ Morse generated\n int length = 0;\n for (int i = string_argc_offset; i < __argc; ++i) {\n length = wcslen(__wargv[i]);\n for (int j = 0; j < length; ++j) {\n ShowAndPlay(&morse_player, __wargv[i][j]);\n ShowAndPlay(&morse_player, L' ');\n }\n if (i != (__argc - 1)) { \/\/ Word separator.\n ShowAndPlay(&morse_player, L' ');\n ShowAndPlay(&morse_player, L' ');\n ShowAndPlay(&morse_player, L' ');\n }\n }\n \/\/ Finalize console.\n if (!no_console) {\n system(\"PAUSE\");\n FreeConsole();\n }\n morse_player.Finalize();\n return 0;\nERROR_EXIT:\n if (!no_console) {\n system(\"PAUSE\");\n FreeConsole();\n }\n morse_player.Finalize();\n return -1;\n}\nvoid ShowAndPlay(MorsePlayer* morse_player, wchar_t charactor) {\n int morse_code = 0;\n switch (charactor) {\n case L'a': case L'A': morse_code = MORSE_A; break;\n case L'b': case L'B': morse_code = MORSE_B; break;\n case L'c': case L'C': morse_code = MORSE_C; break;\n case L'd': case L'D': morse_code = MORSE_D; break;\n case L'e': case L'E': morse_code = MORSE_E; break;\n case L'f': case L'F': morse_code = MORSE_F; break;\n case L'g': case L'G': morse_code = MORSE_G; break;\n case L'h': case L'H': morse_code = MORSE_H; break;\n case L'i': case L'I': morse_code = MORSE_I; break;\n case L'j': case L'J': morse_code = MORSE_J; break;\n case L'k': case L'K': morse_code = MORSE_K; break;\n case L'l': case L'L': morse_code = MORSE_L; break;\n case L'm': case L'M': morse_code = MORSE_M; break;\n case L'n': case L'N': morse_code = MORSE_N; break;\n case L'o': case L'O': morse_code = MORSE_O; break;\n case L'p': case L'P': morse_code = MORSE_P; break;\n case L'q': case L'Q': morse_code = MORSE_Q; break;\n case L'r': case L'R': morse_code = MORSE_R; break;\n case L's': case L'S': morse_code = MORSE_S; break;\n case L't': case L'T': morse_code = MORSE_T; break;\n case L'u': case L'U': morse_code = MORSE_U; break;\n case L'v': case L'V': morse_code = MORSE_V; break;\n case L'w': case L'W': morse_code = MORSE_W; break;\n case L'x': case L'X': morse_code = MORSE_X; break;\n case L'y': case L'Y': morse_code = MORSE_Y; break;\n case L'z': case L'Z': morse_code = MORSE_Z; break;\n case L'1': morse_code = MORSE_1; break;\n case L'2': morse_code = MORSE_2; break;\n case L'3': morse_code = MORSE_3; break;\n case L'4': morse_code = MORSE_4; break;\n case L'5': morse_code = MORSE_5; break;\n case L'6': morse_code = MORSE_6; break;\n case L'7': morse_code = MORSE_7; break;\n case L'8': morse_code = MORSE_8; break;\n case L'9': morse_code = MORSE_9; break;\n case L'0': morse_code = MORSE_0; break;\n case L'.': morse_code = MORSE_PER; break;\n case L',': morse_code = MORSE_COM; break;\n case L'?': morse_code = MORSE_QUE; break;\n case L'-': morse_code = MORSE_HIF; break;\n case L'\/': morse_code = MORSE_SLA; break;\n case L'@': morse_code = MORSE_ATM; break;\n case L' ': morse_code = MORSE_SPACE; break;\n default: morse_code = MORSE_UNKNOWN; break;\n }\n \/\/ Morse shown to console.\n if (!no_console) morse_player->ShowSimbol(morse_code);\n \/\/ Sound played by device.\n if (!no_sound) morse_player->PlaySound(morse_code);\n}\n\/\/ Void callback function.\nLRESULT CALLBACK WndProc(HWND wnd, UINT msg, WPARAM wp, LPARAM lp) {\n \/\/ Prevent warnings for unreferenced parameters.\n UNREFERENCED_PARAMETER(wnd);\n UNREFERENCED_PARAMETER(wp);\n UNREFERENCED_PARAMETER(lp);\n switch (msg) {\n case WM_DESTROY:\n PostQuitMessage(0);\n break;\n default:\n break;\n }\n return DefWindowProc(wnd, msg, wp, lp);\n}\n\/\/ Window is required to set icom on win32 application.\nbool CreateInvisibleWindow(HINSTANCE instance_handle) {\n WNDCLASSEX wcex;\n \/\/ Window class registered.\n memset(&wcex, 0, sizeof(wcex));\n wcex.cbSize = sizeof(wcex);\n wcex.style = CS_HREDRAW | CS_VREDRAW;\n wcex.lpfnWndProc = WndProc;\n wcex.cbClsExtra = 0;\n wcex.cbWndExtra = 0;\n wcex.hInstance = instance_handle;\n wcex.hCursor = LoadCursor(NULL, IDC_ARROW);\n wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);\n wcex.lpszMenuName = NULL;\n wcex.lpszClassName = APP_NAME;\n wcex.hIcon = LoadIcon(instance_handle, MAKEINTRESOURCE(IDI_ICON1));\n wcex.hIconSm = LoadIcon(instance_handle, MAKEINTRESOURCE(IDI_ICON1));\n if (RegisterClassEx(&wcex) == 0) return false;\n \/\/ Invisible window created.\n HWND window_handle = CreateWindow(APP_NAME, APP_NAME, WINDOW_STYLE,\n CW_USEDEFAULT, CW_USEDEFAULT, 256, 256,\n NULL, NULL, instance_handle, NULL);\n if (window_handle == NULL) return false;\n return true;\n}\nCreateInvisibleWindow is called now\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @file main.cc\n\/\/ @brief Morse code generator\n\/\/ @author Mamoru Kaminaga\n\/\/ @date 2016-05-15 12:08:31\n\/\/ Copyright 2016 Mamoru Kaminaga\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \n#include \n#include \n#include \"common.h\"\n#include \"morse_player.h\"\n#include \"resource.h\"\n#define WINDOW_STYLE (WS_POPUP|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX)\nenum OPTIONS {\n OPTION_HELP = 0,\n OPTION_STRING,\n OPTION_NOWINDOW,\n OPTION_NOSOUND,\n OPTION_WPM,\n OPTION_PARIS,\n ELEMNUM_OPTIONS, \/\/ Array size.\n};\nconst wchar_t kOptions[ELEMNUM_OPTIONS][16] = {\n L\"-help\", \/\/ OPTION_HELP\n L\"-s\", \/\/ OPTION_STRING\n L\"-nowindow\", \/\/ OPTION_NOWINDOW\n L\"-nosound\", \/\/ OPTION_NOSOUND\n L\"-wpm\", \/\/ OPTION_WPM\n L\"-paris\", \/\/ OPTION_PARIS\n};\nconst wchar_t kHelp[ELEMNUM_OPTIONS][64] = {\n L\"Show help\", \/\/ OPTION_HELP\n L\"Input string to be morse signal\", \/\/ OPTION_STRING\n L\"Not show output console\", \/\/ OPTION_NOWINDOW\n L\"Not play midi sound\", \/\/ OPTION_NOSOUND\n L\"Set WPM, default is 20\", \/\/ OPTION_WPM\n L\"Set PARIS, default is 20\", \/\/ OPTION_PARIS\n};\nbool help_required = false;\nbool no_console = false;\nbool no_sound = false;\nbool play_command_line_string = false;\nint string_argc_offset = 0;\nvoid ShowAndPlay(MorsePlayer* morse_player, wchar_t charactor);\nbool CreateInvisibleWindow(HINSTANCE instance_handle);\nint WINAPI wWinMain(HINSTANCE instance_handle, HINSTANCE not_used,\n LPTSTR cmd_lind, int cmd_show) {\n \/\/ Prevent warnings for unreferenced parameters.\n UNREFERENCED_PARAMETER(instance_handle);\n UNREFERENCED_PARAMETER(not_used);\n UNREFERENCED_PARAMETER(cmd_lind);\n UNREFERENCED_PARAMETER(cmd_show);\n \/\/\n CreateInvisibleWindow(instance_handle);\n \/\/\n MorsePlayer morse_player;\n morse_player.Initialize();\n morse_player.dot_len_ = 60;\n \/\/ Command line is processed.\n for (int i = 1; i < __argc; ++i) {\n for (int j = 0; j < ELEMNUM_OPTIONS; ++j) {\n if (wcscmp(__wargv[i], kOptions[j]) == 0) {\n switch (j) {\n case OPTION_HELP:\n help_required = true;\n break;\n case OPTION_NOWINDOW:\n no_console = true;\n break;\n case OPTION_NOSOUND:\n no_sound = true;\n break;\n case OPTION_WPM: \/\/ Same as OPTION_PARIS\n case OPTION_PARIS:\n \/* wpm (paris) -> dot millis *\/\n morse_player.dot_len_ = 60000 \/ (_wtoi(__wargv[i + 1]) * 50);\n break;\n case OPTION_STRING:\n play_command_line_string = true;\n string_argc_offset = i + 1;\n default:\n break;\n }\n }\n }\n }\n \/\/ Win32 Console is initialized.\n if (!no_console) {\n\t\tif (!AttachConsole(ATTACH_PARENT_PROCESS)) AllocConsole();\n freopen(\"CON\", \"r\", stdin);\n freopen(\"CON\", \"w\", stdout);\n }\n \/\/ Argument num error check done.\n if (__argc <= 1) {\n if (no_console) {\n DialogError(L\"No arguments specified\");\n return -1;\n } else {\n PrintError(L\"No arguments specified\");\n goto ERROR_EXIT;\n }\n }\n \/\/ Help option process.\n if (help_required) {\n if (no_console) {\n DialogError(L\"You must not set -nowindow option to show help\");\n return 0;\n } else {\n wprintf(APP_NAME);\n wprintf(L\"\\n\");\n wprintf(L\"options:\\n\");\n for (int i = 0; i < ELEMNUM_OPTIONS; ++i) {\n wprintf(L\"%s:\\t%s\\n\", kOptions[i], kHelp[i]);\n }\n goto ERROR_EXIT;\n }\n }\n \/\/ String error.\n if (play_command_line_string == false) {\n if (no_console) {\n DialogError(L\"No input string\");\n return -1;\n } else {\n PrintError(L\"No input string\");\n goto ERROR_EXIT;\n }\n }\n \/\/ Morse generated\n int length = 0;\n for (int i = string_argc_offset; i < __argc; ++i) {\n length = wcslen(__wargv[i]);\n for (int j = 0; j < length; ++j) {\n ShowAndPlay(&morse_player, __wargv[i][j]);\n ShowAndPlay(&morse_player, L' ');\n }\n if (i != (__argc - 1)) { \/\/ Word separator.\n ShowAndPlay(&morse_player, L' ');\n ShowAndPlay(&morse_player, L' ');\n ShowAndPlay(&morse_player, L' ');\n }\n }\n \/\/ Finalize console.\n if (!no_console) {\n system(\"PAUSE\");\n FreeConsole();\n }\n morse_player.Finalize();\n return 0;\nERROR_EXIT:\n if (!no_console) {\n system(\"PAUSE\");\n FreeConsole();\n }\n morse_player.Finalize();\n return -1;\n}\nvoid ShowAndPlay(MorsePlayer* morse_player, wchar_t charactor) {\n int morse_code = 0;\n switch (charactor) {\n case L'a': case L'A': morse_code = MORSE_A; break;\n case L'b': case L'B': morse_code = MORSE_B; break;\n case L'c': case L'C': morse_code = MORSE_C; break;\n case L'd': case L'D': morse_code = MORSE_D; break;\n case L'e': case L'E': morse_code = MORSE_E; break;\n case L'f': case L'F': morse_code = MORSE_F; break;\n case L'g': case L'G': morse_code = MORSE_G; break;\n case L'h': case L'H': morse_code = MORSE_H; break;\n case L'i': case L'I': morse_code = MORSE_I; break;\n case L'j': case L'J': morse_code = MORSE_J; break;\n case L'k': case L'K': morse_code = MORSE_K; break;\n case L'l': case L'L': morse_code = MORSE_L; break;\n case L'm': case L'M': morse_code = MORSE_M; break;\n case L'n': case L'N': morse_code = MORSE_N; break;\n case L'o': case L'O': morse_code = MORSE_O; break;\n case L'p': case L'P': morse_code = MORSE_P; break;\n case L'q': case L'Q': morse_code = MORSE_Q; break;\n case L'r': case L'R': morse_code = MORSE_R; break;\n case L's': case L'S': morse_code = MORSE_S; break;\n case L't': case L'T': morse_code = MORSE_T; break;\n case L'u': case L'U': morse_code = MORSE_U; break;\n case L'v': case L'V': morse_code = MORSE_V; break;\n case L'w': case L'W': morse_code = MORSE_W; break;\n case L'x': case L'X': morse_code = MORSE_X; break;\n case L'y': case L'Y': morse_code = MORSE_Y; break;\n case L'z': case L'Z': morse_code = MORSE_Z; break;\n case L'1': morse_code = MORSE_1; break;\n case L'2': morse_code = MORSE_2; break;\n case L'3': morse_code = MORSE_3; break;\n case L'4': morse_code = MORSE_4; break;\n case L'5': morse_code = MORSE_5; break;\n case L'6': morse_code = MORSE_6; break;\n case L'7': morse_code = MORSE_7; break;\n case L'8': morse_code = MORSE_8; break;\n case L'9': morse_code = MORSE_9; break;\n case L'0': morse_code = MORSE_0; break;\n case L'.': morse_code = MORSE_PER; break;\n case L',': morse_code = MORSE_COM; break;\n case L'?': morse_code = MORSE_QUE; break;\n case L'-': morse_code = MORSE_HIF; break;\n case L'\/': morse_code = MORSE_SLA; break;\n case L'@': morse_code = MORSE_ATM; break;\n case L' ': morse_code = MORSE_SPACE; break;\n default: morse_code = MORSE_UNKNOWN; break;\n }\n \/\/ Morse shown to console.\n if (!no_console) morse_player->ShowSimbol(morse_code);\n \/\/ Sound played by device.\n if (!no_sound) morse_player->PlaySound(morse_code);\n}\n\/\/ Void callback function.\nLRESULT CALLBACK WndProc(HWND wnd, UINT msg, WPARAM wp, LPARAM lp) {\n \/\/ Prevent warnings for unreferenced parameters.\n UNREFERENCED_PARAMETER(wnd);\n UNREFERENCED_PARAMETER(wp);\n UNREFERENCED_PARAMETER(lp);\n switch (msg) {\n case WM_DESTROY:\n PostQuitMessage(0);\n break;\n default:\n break;\n }\n return DefWindowProc(wnd, msg, wp, lp);\n}\n\/\/ Window is required to set icom on win32 application.\nbool CreateInvisibleWindow(HINSTANCE instance_handle) {\n WNDCLASSEX wcex;\n \/\/ Window class registered.\n memset(&wcex, 0, sizeof(wcex));\n wcex.cbSize = sizeof(wcex);\n wcex.style = CS_HREDRAW | CS_VREDRAW;\n wcex.lpfnWndProc = WndProc;\n wcex.cbClsExtra = 0;\n wcex.cbWndExtra = 0;\n wcex.hInstance = instance_handle;\n wcex.hCursor = LoadCursor(NULL, IDC_ARROW);\n wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);\n wcex.lpszMenuName = NULL;\n wcex.lpszClassName = APP_NAME;\n wcex.hIcon = LoadIcon(instance_handle, MAKEINTRESOURCE(IDI_ICON1));\n wcex.hIconSm = LoadIcon(instance_handle, MAKEINTRESOURCE(IDI_ICON1));\n if (RegisterClassEx(&wcex) == 0) return false;\n \/\/ Invisible window created.\n HWND window_handle = CreateWindow(APP_NAME, APP_NAME, WINDOW_STYLE,\n CW_USEDEFAULT, CW_USEDEFAULT, 256, 256,\n NULL, NULL, instance_handle, NULL);\n if (window_handle == NULL) return false;\n return true;\n}\n<|endoftext|>"} {"text":"\/\/ Lecture d'un fichier Rtstruct et conversion en vtkImageData, sortie en VTI\n\/\/ \\author Olivier Saut\n#include \n#include \n\n#include \n\/\/ * Lecture du RTStruct\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Ecriture en ImageData\n#include \n#include \n#include \n#include \n#include \n\n\nstd::string getPrefix(std::string str) {\n std::string relName=str.substr(str.find_last_of(\"\/\")+1);\n std::string prefix=relName.substr(0,relName.find_last_of(\".\"));\n return prefix;\n}\n\n\n\nvoid stripSpace(std::string &str) {\n std::string resStr=\"\";\n for (int i=0;i polygon, std::string outDir) {\n vtkSmartPointer extrude=vtkSmartPointer::New();\n if(vtkVersion::GetVTKMajorVersion()>=6)\n#if VTK_MAJOR_VERSION >= 6\n extrude->SetInputData(polygon);\n#else\n extrude->SetInput(polygon);\n#endif\n extrude->SetScaleFactor(12);\n extrude->SetExtrusionTypeToNormalExtrusion();\n extrude->SetVector(0,0,1);\n\n \/\/ ***\n \/\/ * Prparation de l'image\n \/\/ ***\n vtkSmartPointer image = vtkSmartPointer::New();\n double bounds[6]; polygon->GetBounds(bounds);\n double spacing[3] = {2, 2, 2};\n image->SetSpacing(spacing);\n\n int dim[3];\n for (int i = 0; i < 3; i++)\n {\n dim[i] = static_cast(ceil(1.2*(bounds[i * 2 + 1] - bounds[i * 2]) \/ spacing[i]));\n }\n\n \/\/ dim[2]=1; Pour slectionner une tranche\n std::cout << \"\\t\\tDimensions = \" << dim[0] << \"x\" << dim[1] << \"x\" << dim[2] << std::endl;\n image->SetDimensions(dim);\n image->SetExtent(0, dim[0] - 1, 0, dim[1] - 1, 0, dim[2] - 1);\n\n double origin[3];\n \/\/ offset ?\n origin[0] = bounds[0] -0.1*(bounds[1]-bounds[0]); \/\/ spacing[0] \/ 2;\n origin[1] = bounds[2] -0.1*(bounds[3]-bounds[2]);\/\/+ spacing[1] \/ 2;\n origin[2] = bounds[4] -0.1*(bounds[5]-bounds[4]);\/\/+ spacing[2] \/ 2;\n std::cout << \"\\t\\tOrigine = (\" << origin[0] << \", \" << origin[1] << \", \" << origin[2] << \")\" << std::endl;\n image->SetOrigin(origin);\n#if VTK_MAJOR_VERSION >= 6\n image->AllocateScalars(VTK_FLOAT,1);\n#else\n image->SetScalarTypeToFloat();\n image->AllocateScalars();\n#endif\n \/\/ fill the image with foreground voxels:\n float inval = 255.0;\n float outval = 0;\n vtkIdType count = image->GetNumberOfPoints();\n for (vtkIdType i = 0; i < count; ++i)\n {\n image->GetPointData()->GetScalars()->SetTuple1(i, inval);\n }\n\n \/\/ ***\n \/\/ * Conversion\n \/\/ ***\n \/\/ On clippe l'image avec le polydata\n vtkSmartPointer conv=vtkSmartPointer::New();\n#if VTK_MAJOR_VERSION >= 6\n conv->SetInputData(extrude->GetOutput());\n#else\n conv->SetInput(extrude->GetOutput());\n#endif\n\n conv->SetOutputOrigin(origin);\n conv->SetOutputSpacing(spacing);\n conv->SetTolerance(1e-6);\n conv->SetOutputWholeExtent(image->GetExtent());\n conv->Update();\n\n vtkSmartPointer stenc=vtkSmartPointer::New();\n#if VTK_MAJOR_VERSION >= 6\n stenc->SetInputData(image);\n stenc->SetStencilData(conv->GetOutput());\n#else\n stenc->SetInput(image);\n stenc->SetStencil(conv->GetOutput());\n#endif\n stenc->ReverseStencilOff();\n stenc->SetBackgroundValue(outval);\n stenc->Update();\n\n \/\/ ***\n \/\/ * Ecriture sur le disque\n \/\/ ***\n\n \/\/ Lissage pour un joli rsultat\n vtkSmartPointer gaussianSmoothFilter = vtkSmartPointer::New();\n gaussianSmoothFilter->SetInputConnection(stenc->GetOutputPort());\n gaussianSmoothFilter->SetStandardDeviation(4.0);\n gaussianSmoothFilter->Update(); gaussianSmoothFilter->UpdateWholeExtent();\n\n \/\/ Ecriture en tant qu'image\n vtkSmartPointer ww=vtkSmartPointer::New();\n ww->SetFileName(std::string(outDir+\"\/\"+name+\".vti\").c_str());\n#if VTK_MAJOR_VERSION >= 6\n ww->SetInputData(gaussianSmoothFilter->GetOutput());\n#else\n ww->SetInput(gaussianSmoothFilter->GetOutput());\n#endif\n ww->Write();\n\n}\n\n\n\/\/ \\brief Prend en argument le nom du fichier RTStruct\nint main(int argc, char *argv[])\n{\n if( argc < 2 )\n {\n std::cerr << argv[0] << \" input.dcm (outdir)\\n\";\n return 1;\n }\n\n \/\/ ***\n \/\/ * Lecture de la structure\n \/\/ ***\n const char * filename = argv[1];\n vtkSmartPointer reader = vtkSmartPointer::New();\n reader->SetFileName( filename );\n reader->Update();\n\n std::string outDir = (argc>2) ? argv[2] : \".\";\n\n vtkSmartPointer append = vtkSmartPointer::New();\n\n vtkSmartPointer writer = vtkSmartPointer::New();\n char fname[300]; std::string prefix=getPrefix(filename);\n int n = reader->GetNumberOfOutputPorts();\n std::map > listePolys;\n for(int i = 0; i < n; ++i) {\n std::string port_name=\"\";\n const int num_arrays_cell=reader->GetOutput(i)->GetCellData()->GetNumberOfArrays();\n if(num_arrays_cell>0)\n port_name= std::string(reader->GetOutput(i)->GetCellData()->GetArrayName(0));\n const int num_arrays_point=reader->GetOutput(i)->GetPointData()->GetNumberOfArrays();\n if(num_arrays_point>0)\n port_name= std::string(reader->GetOutput(i)->GetPointData()->GetArrayName(0));\n stripSpace(port_name);\n snprintf(fname, 300, \"%s\/%d-%s.vtp\", outDir.data(), i, port_name.c_str());\n\n writer->SetFileName(fname);\n#if VTK_MAJOR_VERSION >= 6\n writer->SetInputData(reader->GetOutput(i));\n#else\n writer->SetInput(reader->GetOutput(i));\n#endif\n listePolys.insert(std::pair > (port_name, reader->GetOutput(i)));\n writer->Write();\n\n#if VTK_MAJOR_VERSION >= 6\n append->AddInputData( reader->GetOutput(i) );\n#else\n append->AddInput( reader->GetOutput(i) );\n#endif\n }\n\n std::map >::const_iterator it;\n for(it=listePolys.begin(); it!= listePolys.end();++it) {\n if(it->first != \"\") {\n std::cout << \"\\tSaving \" << it->first << \"...\" << std::endl;\n save_VTP_as_image(it->first, it->second, outDir);\n }\n }\n\n return 0;\n}\nTypo, an old if was preventing a connexion to extrude\/\/ Lecture d'un fichier Rtstruct et conversion en vtkImageData, sortie en VTI\n\/\/ \\author Olivier Saut\n#include \n#include \n\n#include \n\/\/ * Lecture du RTStruct\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Ecriture en ImageData\n#include \n#include \n#include \n#include \n#include \n\n\nstd::string getPrefix(std::string str) {\n std::string relName=str.substr(str.find_last_of(\"\/\")+1);\n std::string prefix=relName.substr(0,relName.find_last_of(\".\"));\n return prefix;\n}\n\n\n\nvoid stripSpace(std::string &str) {\n std::string resStr=\"\";\n for (int i=0;i polygon, std::string outDir) {\n vtkSmartPointer extrude=vtkSmartPointer::New();\n#if VTK_MAJOR_VERSION >= 6\n extrude->SetInputData(polygon);\n#else\n extrude->SetInput(polygon);\n#endif\n extrude->SetScaleFactor(12);\n extrude->SetExtrusionTypeToNormalExtrusion();\n extrude->SetVector(0,0,1);\n\n \/\/ ***\n \/\/ * Prparation de l'image\n \/\/ ***\n vtkSmartPointer image = vtkSmartPointer::New();\n double bounds[6]; polygon->GetBounds(bounds);\n double spacing[3] = {2, 2, 2};\n image->SetSpacing(spacing);\n\n int dim[3];\n for (int i = 0; i < 3; i++)\n {\n dim[i] = static_cast(ceil(1.2*(bounds[i * 2 + 1] - bounds[i * 2]) \/ spacing[i]));\n }\n\n \/\/ dim[2]=1; Pour slectionner une tranche\n std::cout << \"\\t\\tDimensions = \" << dim[0] << \"x\" << dim[1] << \"x\" << dim[2] << std::endl;\n image->SetDimensions(dim);\n image->SetExtent(0, dim[0] - 1, 0, dim[1] - 1, 0, dim[2] - 1);\n\n double origin[3];\n \/\/ offset ?\n origin[0] = bounds[0] -0.1*(bounds[1]-bounds[0]); \/\/ spacing[0] \/ 2;\n origin[1] = bounds[2] -0.1*(bounds[3]-bounds[2]);\/\/+ spacing[1] \/ 2;\n origin[2] = bounds[4] -0.1*(bounds[5]-bounds[4]);\/\/+ spacing[2] \/ 2;\n std::cout << \"\\t\\tOrigine = (\" << origin[0] << \", \" << origin[1] << \", \" << origin[2] << \")\" << std::endl;\n image->SetOrigin(origin);\n#if VTK_MAJOR_VERSION >= 6\n image->AllocateScalars(VTK_FLOAT,1);\n#else\n image->SetScalarTypeToFloat();\n image->AllocateScalars();\n#endif\n \/\/ fill the image with foreground voxels:\n float inval = 255.0;\n float outval = 0;\n vtkIdType count = image->GetNumberOfPoints();\n for (vtkIdType i = 0; i < count; ++i)\n {\n image->GetPointData()->GetScalars()->SetTuple1(i, inval);\n }\n\n \/\/ ***\n \/\/ * Conversion\n \/\/ ***\n \/\/ On clippe l'image avec le polydata\n vtkSmartPointer conv=vtkSmartPointer::New();\n#if VTK_MAJOR_VERSION >= 6\n conv->SetInputData(extrude->GetOutput());\n#else\n conv->SetInput(extrude->GetOutput());\n#endif\n\n conv->SetOutputOrigin(origin);\n conv->SetOutputSpacing(spacing);\n conv->SetTolerance(1e-6);\n conv->SetOutputWholeExtent(image->GetExtent());\n conv->Update();\n\n vtkSmartPointer stenc=vtkSmartPointer::New();\n#if VTK_MAJOR_VERSION >= 6\n stenc->SetInputData(image);\n stenc->SetStencilData(conv->GetOutput());\n#else\n stenc->SetInput(image);\n stenc->SetStencil(conv->GetOutput());\n#endif\n stenc->ReverseStencilOff();\n stenc->SetBackgroundValue(outval);\n stenc->Update();\n\n \/\/ ***\n \/\/ * Ecriture sur le disque\n \/\/ ***\n\n \/\/ Lissage pour un joli rsultat\n vtkSmartPointer gaussianSmoothFilter = vtkSmartPointer::New();\n gaussianSmoothFilter->SetInputConnection(stenc->GetOutputPort());\n gaussianSmoothFilter->SetStandardDeviation(4.0);\n gaussianSmoothFilter->Update(); gaussianSmoothFilter->UpdateWholeExtent();\n\n \/\/ Ecriture en tant qu'image\n vtkSmartPointer ww=vtkSmartPointer::New();\n ww->SetFileName(std::string(outDir+\"\/\"+name+\".vti\").c_str());\n#if VTK_MAJOR_VERSION >= 6\n ww->SetInputData(gaussianSmoothFilter->GetOutput());\n#else\n ww->SetInput(gaussianSmoothFilter->GetOutput());\n#endif\n ww->Write();\n\n}\n\n\n\/\/ \\brief Prend en argument le nom du fichier RTStruct\nint main(int argc, char *argv[])\n{\n if( argc < 2 )\n {\n std::cerr << argv[0] << \" input.dcm (outdir)\\n\";\n return 1;\n }\n\n \/\/ ***\n \/\/ * Lecture de la structure\n \/\/ ***\n const char * filename = argv[1];\n vtkSmartPointer reader = vtkSmartPointer::New();\n reader->SetFileName( filename );\n reader->Update();\n\n std::string outDir = (argc>2) ? argv[2] : \".\";\n\n vtkSmartPointer append = vtkSmartPointer::New();\n\n vtkSmartPointer writer = vtkSmartPointer::New();\n char fname[300]; std::string prefix=getPrefix(filename);\n int n = reader->GetNumberOfOutputPorts();\n std::map > listePolys;\n for(int i = 0; i < n; ++i) {\n std::string port_name=\"\";\n const int num_arrays_cell=reader->GetOutput(i)->GetCellData()->GetNumberOfArrays();\n if(num_arrays_cell>0)\n port_name= std::string(reader->GetOutput(i)->GetCellData()->GetArrayName(0));\n const int num_arrays_point=reader->GetOutput(i)->GetPointData()->GetNumberOfArrays();\n if(num_arrays_point>0)\n port_name= std::string(reader->GetOutput(i)->GetPointData()->GetArrayName(0));\n stripSpace(port_name);\n snprintf(fname, 300, \"%s\/%d-%s.vtp\", outDir.data(), i, port_name.c_str());\n\n writer->SetFileName(fname);\n#if VTK_MAJOR_VERSION >= 6\n writer->SetInputData(reader->GetOutput(i));\n#else\n writer->SetInput(reader->GetOutput(i));\n#endif\n listePolys.insert(std::pair > (port_name, reader->GetOutput(i)));\n writer->Write();\n\n#if VTK_MAJOR_VERSION >= 6\n append->AddInputData( reader->GetOutput(i) );\n#else\n append->AddInput( reader->GetOutput(i) );\n#endif\n }\n\n std::map >::const_iterator it;\n for(it=listePolys.begin(); it!= listePolys.end();++it) {\n if(it->first != \"\") {\n std::cout << \"\\tSaving \" << it->first << \"...\" << std::endl;\n save_VTP_as_image(it->first, it->second, outDir);\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"Fl_Rotated_Text\/Fl_Rotated_Text.H\"\n#include \"cartesian\/Cartesian.H\"\n\n#include \"cvFltkWidget.hh\"\n#include \"ffmpegInterface.hh\"\n#include \"cameraSource.hh\"\n\nextern \"C\"\n{\n#include \"wormProcessing.h\"\n}\n\n#define DATA_FRAME_RATE_FPS (1.0 \/ 15.0) \/* I collect at 15 seconds per frame *\/\n#define SETUP_FRAME_RATE_FPS 5\n#define CIRCLE_RADIUS 50\n#define CIRCLE_COLOR CV_RGB(0xFF, 0, 0)\n#define POINTED_CIRCLE_COLOR CV_RGB(0, 0xFF, 0)\n\n\n#define FRAME_W 480\n#define FRAME_H 480\n#define CROP_RECT cvRect(80, 0, FRAME_W, FRAME_H)\n#define WINDOW_W 1000\n#define WINDOW_H (FRAME_H + PLOT_H + X_AXIS_HEIGHT + AXIS_EXTRA_SPACE)\n#define BUTTON_W 180\n#define BUTTON_H 30\n#define PLOT_W (WINDOW_W - (Y_AXIS_WIDTH + AXIS_EXTRA_SPACE))\n#define PLOT_H 400\n#define X_AXIS_HEIGHT 30\n#define Y_AXIS_WIDTH 80\n#define ACCUM_W 180\n#define ACCUM_H BUTTON_H\n\n\n\/\/ due to a bug (most likely), the axis aren't drawn completely inside their box. Thus I leave a bit\n\/\/ of extra space to see the labels\n#define AXIS_EXTRA_SPACE 40\n\n#define AM_READING_CAMERA (dynamic_cast(source) != NULL)\n\nstatic FrameSource* source;\nstatic CvFltkWidget* widgetImage;\nstatic Fl_Button* goResetButton;\nstatic Ca_Canvas* plot = NULL;\nstatic Ca_X_Axis* Xaxis;\nstatic Ca_Y_Axis* Yaxis;\n\nstatic Fl_Output* leftAccum;\nstatic Fl_Output* rightAccum;\nstatic double leftAccumValue = 0.0;\nstatic double rightAccumValue = 0.0;\n\n\/\/ the analysis could be idle, running, or idle examining data (STOPPED)\nstatic enum { RESET, RUNNING, STOPPED } analysisState;\n\nstatic int numPoints;\nstatic Ca_LinePoint* lastLeftPoint = NULL;\nstatic Ca_LinePoint* lastRightPoint = NULL;\nstatic CvPoint leftCircleCenter = cvPoint(-1, -1);\nstatic CvPoint rightCircleCenter = cvPoint(-1, -1);\nstatic CvPoint pointedCircleCenter = cvPoint(-1, -1);\n\n#define HAVE_LEFT_CIRCLE (leftCircleCenter .x > 0 && leftCircleCenter .y > 0)\n#define HAVE_RIGHT_CIRCLE (rightCircleCenter.x > 0 && rightCircleCenter.y > 0)\n#define HAVE_CIRCLES (HAVE_LEFT_CIRCLE && HAVE_RIGHT_CIRCLE)\n#define HAVE_POINTED_CIRCLE (pointedCircleCenter.x > 0 && pointedCircleCenter.y > 0)\n\nstatic void setStoppedAnalysis(void);\n\nstatic bool gotNewFrame(IplImage* buffer, uint64_t timestamp_us __attribute__((unused)))\n{\n if(buffer == NULL)\n {\n if(!AM_READING_CAMERA)\n {\n \/\/ error ocurred reading the stored video. I likely reached the end of the file. I stop\n \/\/ the analysis if I'm running it and rewind the stream\n source->restartStream();\n if(analysisState == RUNNING)\n {\n goResetButton->value(0);\n setStoppedAnalysis();\n }\n return true;\n }\n return false;\n }\n\n cvMerge(buffer, buffer, buffer, NULL, *widgetImage);\n\n const CvMat* result = isolateWorms(buffer);\n cvSetImageCOI(*widgetImage, 1);\n cvCopy(result, *widgetImage);\n cvSetImageCOI(*widgetImage, 0);\n\n if(HAVE_LEFT_CIRCLE)\n cvCircle(*widgetImage, leftCircleCenter, CIRCLE_RADIUS, CIRCLE_COLOR, 1, 8);\n\n if(HAVE_RIGHT_CIRCLE)\n cvCircle(*widgetImage, rightCircleCenter, CIRCLE_RADIUS, CIRCLE_COLOR, 1, 8);\n\n if(HAVE_POINTED_CIRCLE)\n cvCircle(*widgetImage, pointedCircleCenter, CIRCLE_RADIUS, POINTED_CIRCLE_COLOR, 1, 8);\n\n \/\/ This critical section is likely larger than it needs to be, but this keeps me safe. The\n \/\/ analysis state can change in the FLTK thread, so I err on the side of safety\n Fl::lock();\n {\n if(analysisState == RUNNING)\n {\n double minutes = (double)numPoints \/ DATA_FRAME_RATE_FPS \/ 60.0;\n double leftOccupancy, rightOccupancy;\n computeWormOccupancy(result, &leftCircleCenter, &rightCircleCenter,\n CIRCLE_RADIUS,\n &leftOccupancy, &rightOccupancy);\n\n Yaxis->rescale(CA_WHEN_MAX, fmax(leftOccupancy, rightOccupancy) );\n\n lastLeftPoint = new Ca_LinePoint(lastLeftPoint,\n minutes,\n leftOccupancy, 1,FL_RED, CA_NO_POINT);\n lastRightPoint = new Ca_LinePoint(lastRightPoint,\n minutes,\n rightOccupancy, 1,FL_GREEN, CA_NO_POINT);\n Xaxis->maximum(minutes);\n numPoints++;\n\n leftAccumValue += leftOccupancy \/ DATA_FRAME_RATE_FPS;\n rightAccumValue += rightOccupancy \/ DATA_FRAME_RATE_FPS;\n char results[128];\n snprintf(results, sizeof(results), \"%.3f\", leftAccumValue);\n leftAccum->value(results);\n snprintf(results, sizeof(results), \"%.3f\", rightAccumValue);\n rightAccum->value(results);\n }\n\n widgetImage->redrawNewFrame();\n }\n\n if(!AM_READING_CAMERA && analysisState != RUNNING)\n {\n Fl::unlock();\n\n \/\/ reading from a video file and not actually running the analysis yet. In this case I\n \/\/ rewind back to the beginning and delay, to force a reasonable refresh rate\n source->restartStream();\n\n struct timespec tv;\n tv.tv_sec = 0;\n tv.tv_nsec = 1e9 \/ SETUP_FRAME_RATE_FPS;\n nanosleep(&tv, NULL);\n }\n else\n Fl::unlock();\n\n return true;\n}\n\nstatic void widgetImageCallback(Fl_Widget* widget __attribute__((unused)), void* cookie __attribute__((unused)))\n{\n if(Fl::event() == FL_LEAVE)\n {\n \/\/ I want to make sure to never miss this, so I handle it unconditionally\n pointedCircleCenter.x = pointedCircleCenter.y = -1;\n return;\n }\n\n if(analysisState == RUNNING)\n {\n pointedCircleCenter.x = pointedCircleCenter.y = -1;\n return;\n }\n\n bool onLeftHalf = (Fl::event_x() - widget->x()) < FRAME_W\/2;\n switch(Fl::event())\n {\n case FL_MOVE:\n pointedCircleCenter.x = Fl::event_x() - widget->x();\n pointedCircleCenter.y = Fl::event_y() - widget->y();\n break;\n\n case FL_LEAVE:\n pointedCircleCenter.x = pointedCircleCenter.y = -1;\n break;\n\n case FL_PUSH:\n if(onLeftHalf)\n {\n leftCircleCenter.x = Fl::event_x() - widget->x();\n leftCircleCenter.y = Fl::event_y() - widget->y();\n }\n else\n {\n rightCircleCenter.x = Fl::event_x() - widget->x();\n rightCircleCenter.y = Fl::event_y() - widget->y();\n }\n\n pointedCircleCenter.x = pointedCircleCenter.y = -1;\n break;\n\n default: ;\n }\n\n if(HAVE_CIRCLES && analysisState == RESET)\n goResetButton->activate();\n}\n\nstatic void setResetAnalysis(void)\n{\n goResetButton->labelfont(FL_HELVETICA_BOLD);\n goResetButton->labelcolor(FL_RED);\n goResetButton->type(FL_TOGGLE_BUTTON);\n goResetButton->label(\"Analyze\");\n\n numPoints = 0;\n if(plot) plot->clear();\n lastLeftPoint = lastRightPoint = NULL; \n leftAccumValue = 0.0;\n rightAccumValue = 0.0;\n leftAccum ->value(\"0.0\");\n rightAccum->value(\"0.0\");\n\n if(!AM_READING_CAMERA)\n source->restartStream();\n\n analysisState = RESET;\n}\n\nstatic void setRunningAnalysis(void)\n{\n goResetButton->labelfont(FL_HELVETICA);\n goResetButton->labelcolor(FL_BLACK);\n goResetButton->type(FL_TOGGLE_BUTTON);\n goResetButton->label(\"Stop analysis\");\n\n pointedCircleCenter.x = pointedCircleCenter.y = -1;\n\n analysisState = RUNNING;\n}\n\nstatic void setStoppedAnalysis(void)\n{\n goResetButton->labelfont(FL_HELVETICA);\n goResetButton->labelcolor(FL_BLACK);\n goResetButton->type(FL_NORMAL_BUTTON);\n goResetButton->label(\"Reset analysis data\");\n\n analysisState = STOPPED;\n}\n\nstatic void pressedGoReset(Fl_Widget* widget __attribute__((unused)), void* cookie __attribute__((unused)))\n{\n if (analysisState == RUNNING) setStoppedAnalysis();\n else if(analysisState == STOPPED) setResetAnalysis();\n else setRunningAnalysis();\n}\n\nint main(int argc, char* argv[])\n{\n Fl::lock();\n Fl::visual(FL_RGB);\n\n \/\/ open the first source. If there's an argument, assume it's an input video. Otherwise, try\n \/\/ reading a camera\n if(argc >= 2) source = new FFmpegDecoder(argv[1], FRAMESOURCE_GRAYSCALE, false, CROP_RECT);\n else source = new CameraSource (FRAMESOURCE_GRAYSCALE, false, 0, CROP_RECT);\n\n if(! *source)\n {\n fprintf(stderr, \"couldn't open source\\n\");\n delete source;\n return 0;\n }\n\n Fl_Double_Window* window =\n new Fl_Double_Window(WINDOW_W, WINDOW_H, \"Wormtracker 3\");\n widgetImage = new CvFltkWidget(0, 0, source->w(), source->h(),\n WIDGET_COLOR);\n\n widgetImage->callback(widgetImageCallback);\n\n goResetButton = new Fl_Button( widgetImage->w(), 0, BUTTON_W, BUTTON_H);\n goResetButton->callback(pressedGoReset);\n goResetButton->deactivate();\n\n plot = new Ca_Canvas( Y_AXIS_WIDTH + AXIS_EXTRA_SPACE, widgetImage->y() + widgetImage->h(),\n PLOT_W, PLOT_H,\n \"Worm occupancy\");\n plot->align(FL_ALIGN_TOP);\n\n \/\/ This is extremely important for some reason. Without it the plots do not refresh property and\n \/\/ there're artifacts every time the plot is resized\n plot->box(FL_DOWN_BOX);\n\n Xaxis = new Ca_X_Axis(plot->x(), plot->y() + plot->h(), plot->w(), X_AXIS_HEIGHT, \"Minutes\");\n Xaxis->align(FL_ALIGN_BOTTOM);\n Xaxis->minimum(0);\n Xaxis->maximum(1);\n Xaxis->label_format(\"%g\");\n Xaxis->major_step(10);\n Xaxis->label_step(10);\n Xaxis->axis_color(FL_BLACK);\n Xaxis->axis_align(CA_BOTTOM | CA_LINE);\n\n Yaxis = new Ca_Y_Axis(AXIS_EXTRA_SPACE, plot->y(), Y_AXIS_WIDTH, plot->h());\n Fl_Rotated_Text YaxisLabel(\"occupancy ratio\", FL_HELVETICA, 14, 0, 1);\n Yaxis->image(&YaxisLabel);\n Yaxis->minimum(0);\n Yaxis->maximum(0.01);\n Yaxis->align(FL_ALIGN_LEFT);\n Yaxis->axis_align(CA_LEFT | CA_LINE);\n Yaxis->axis_color(FL_BLACK);\n\n leftAccum = new Fl_Output(widgetImage->x() + widgetImage->w(), goResetButton->y() + goResetButton->h(),\n ACCUM_W, ACCUM_H, \"Left accumulator (occupancy-seconds)\");\n rightAccum = new Fl_Output(leftAccum->x(), leftAccum->y() + leftAccum->h(),\n ACCUM_W, ACCUM_H, \"Right accumulator (occupancy-seconds)\");\n leftAccum ->align(FL_ALIGN_RIGHT);\n rightAccum->align(FL_ALIGN_RIGHT);\n leftAccum ->labelcolor(FL_RED);\n rightAccum->labelcolor(FL_GREEN);\n\n window->end();\n window->show();\n\n processingInit(source->w(), source->h());\n\n setResetAnalysis();\n\n \/\/ I read the data with a tiny delay. This makes sure that I skip old frames (only an issue if I\n \/\/ can't keep up with the data rate), but yet got as fast as I can\n IplImage* buffer = cvCreateImage(cvSize(source->w(), source->h()), IPL_DEPTH_8U, 1);\n\n \/\/ If reading from a stored video file, go as fast as possible\n if(AM_READING_CAMERA) source->startSourceThread(&gotNewFrame, 1e6\/DATA_FRAME_RATE_FPS, buffer);\n else source->startSourceThread(&gotNewFrame, 0, buffer);\n\n while (Fl::wait())\n {\n }\n\n Fl::unlock();\n\n delete source;\n delete window;\n cvReleaseImage(&buffer);\n\n processingCleanup();\n return 0;\n}\nI'm now opening a specific camera, as given on the cmdline#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"Fl_Rotated_Text\/Fl_Rotated_Text.H\"\n#include \"cartesian\/Cartesian.H\"\n\n#include \"cvFltkWidget.hh\"\n#include \"ffmpegInterface.hh\"\n#include \"cameraSource.hh\"\n\nextern \"C\"\n{\n#include \"wormProcessing.h\"\n}\n\n#define DATA_FRAME_RATE_FPS (1.0 \/ 15.0) \/* I collect at 15 seconds per frame *\/\n#define SETUP_FRAME_RATE_FPS 5\n#define CIRCLE_RADIUS 50\n#define CIRCLE_COLOR CV_RGB(0xFF, 0, 0)\n#define POINTED_CIRCLE_COLOR CV_RGB(0, 0xFF, 0)\n\n\n#define FRAME_W 480\n#define FRAME_H 480\n#define CROP_RECT cvRect(80, 0, FRAME_W, FRAME_H)\n#define WINDOW_W 1000\n#define WINDOW_H (FRAME_H + PLOT_H + X_AXIS_HEIGHT + AXIS_EXTRA_SPACE)\n#define BUTTON_W 180\n#define BUTTON_H 30\n#define PLOT_W (WINDOW_W - (Y_AXIS_WIDTH + AXIS_EXTRA_SPACE))\n#define PLOT_H 400\n#define X_AXIS_HEIGHT 30\n#define Y_AXIS_WIDTH 80\n#define ACCUM_W 180\n#define ACCUM_H BUTTON_H\n\n\n\/\/ due to a bug (most likely), the axis aren't drawn completely inside their box. Thus I leave a bit\n\/\/ of extra space to see the labels\n#define AXIS_EXTRA_SPACE 40\n\n#define AM_READING_CAMERA (dynamic_cast(source) != NULL)\n\nstatic FrameSource* source;\nstatic CvFltkWidget* widgetImage;\nstatic Fl_Button* goResetButton;\nstatic Ca_Canvas* plot = NULL;\nstatic Ca_X_Axis* Xaxis;\nstatic Ca_Y_Axis* Yaxis;\n\nstatic Fl_Output* leftAccum;\nstatic Fl_Output* rightAccum;\nstatic double leftAccumValue = 0.0;\nstatic double rightAccumValue = 0.0;\n\n\/\/ the analysis could be idle, running, or idle examining data (STOPPED)\nstatic enum { RESET, RUNNING, STOPPED } analysisState;\n\nstatic int numPoints;\nstatic Ca_LinePoint* lastLeftPoint = NULL;\nstatic Ca_LinePoint* lastRightPoint = NULL;\nstatic CvPoint leftCircleCenter = cvPoint(-1, -1);\nstatic CvPoint rightCircleCenter = cvPoint(-1, -1);\nstatic CvPoint pointedCircleCenter = cvPoint(-1, -1);\n\n#define HAVE_LEFT_CIRCLE (leftCircleCenter .x > 0 && leftCircleCenter .y > 0)\n#define HAVE_RIGHT_CIRCLE (rightCircleCenter.x > 0 && rightCircleCenter.y > 0)\n#define HAVE_CIRCLES (HAVE_LEFT_CIRCLE && HAVE_RIGHT_CIRCLE)\n#define HAVE_POINTED_CIRCLE (pointedCircleCenter.x > 0 && pointedCircleCenter.y > 0)\n\nstatic void setStoppedAnalysis(void);\n\nstatic bool gotNewFrame(IplImage* buffer, uint64_t timestamp_us __attribute__((unused)))\n{\n if(buffer == NULL)\n {\n if(!AM_READING_CAMERA)\n {\n \/\/ error ocurred reading the stored video. I likely reached the end of the file. I stop\n \/\/ the analysis if I'm running it and rewind the stream\n source->restartStream();\n if(analysisState == RUNNING)\n {\n goResetButton->value(0);\n setStoppedAnalysis();\n }\n return true;\n }\n return false;\n }\n\n cvMerge(buffer, buffer, buffer, NULL, *widgetImage);\n\n const CvMat* result = isolateWorms(buffer);\n cvSetImageCOI(*widgetImage, 1);\n cvCopy(result, *widgetImage);\n cvSetImageCOI(*widgetImage, 0);\n\n if(HAVE_LEFT_CIRCLE)\n cvCircle(*widgetImage, leftCircleCenter, CIRCLE_RADIUS, CIRCLE_COLOR, 1, 8);\n\n if(HAVE_RIGHT_CIRCLE)\n cvCircle(*widgetImage, rightCircleCenter, CIRCLE_RADIUS, CIRCLE_COLOR, 1, 8);\n\n if(HAVE_POINTED_CIRCLE)\n cvCircle(*widgetImage, pointedCircleCenter, CIRCLE_RADIUS, POINTED_CIRCLE_COLOR, 1, 8);\n\n \/\/ This critical section is likely larger than it needs to be, but this keeps me safe. The\n \/\/ analysis state can change in the FLTK thread, so I err on the side of safety\n Fl::lock();\n {\n if(analysisState == RUNNING)\n {\n double minutes = (double)numPoints \/ DATA_FRAME_RATE_FPS \/ 60.0;\n double leftOccupancy, rightOccupancy;\n computeWormOccupancy(result, &leftCircleCenter, &rightCircleCenter,\n CIRCLE_RADIUS,\n &leftOccupancy, &rightOccupancy);\n\n Yaxis->rescale(CA_WHEN_MAX, fmax(leftOccupancy, rightOccupancy) );\n\n lastLeftPoint = new Ca_LinePoint(lastLeftPoint,\n minutes,\n leftOccupancy, 1,FL_RED, CA_NO_POINT);\n lastRightPoint = new Ca_LinePoint(lastRightPoint,\n minutes,\n rightOccupancy, 1,FL_GREEN, CA_NO_POINT);\n Xaxis->maximum(minutes);\n numPoints++;\n\n leftAccumValue += leftOccupancy \/ DATA_FRAME_RATE_FPS;\n rightAccumValue += rightOccupancy \/ DATA_FRAME_RATE_FPS;\n char results[128];\n snprintf(results, sizeof(results), \"%.3f\", leftAccumValue);\n leftAccum->value(results);\n snprintf(results, sizeof(results), \"%.3f\", rightAccumValue);\n rightAccum->value(results);\n }\n\n widgetImage->redrawNewFrame();\n }\n\n if(!AM_READING_CAMERA && analysisState != RUNNING)\n {\n Fl::unlock();\n\n \/\/ reading from a video file and not actually running the analysis yet. In this case I\n \/\/ rewind back to the beginning and delay, to force a reasonable refresh rate\n source->restartStream();\n\n struct timespec tv;\n tv.tv_sec = 0;\n tv.tv_nsec = 1e9 \/ SETUP_FRAME_RATE_FPS;\n nanosleep(&tv, NULL);\n }\n else\n Fl::unlock();\n\n return true;\n}\n\nstatic void widgetImageCallback(Fl_Widget* widget __attribute__((unused)), void* cookie __attribute__((unused)))\n{\n if(Fl::event() == FL_LEAVE)\n {\n \/\/ I want to make sure to never miss this, so I handle it unconditionally\n pointedCircleCenter.x = pointedCircleCenter.y = -1;\n return;\n }\n\n if(analysisState == RUNNING)\n {\n pointedCircleCenter.x = pointedCircleCenter.y = -1;\n return;\n }\n\n bool onLeftHalf = (Fl::event_x() - widget->x()) < FRAME_W\/2;\n switch(Fl::event())\n {\n case FL_MOVE:\n pointedCircleCenter.x = Fl::event_x() - widget->x();\n pointedCircleCenter.y = Fl::event_y() - widget->y();\n break;\n\n case FL_LEAVE:\n pointedCircleCenter.x = pointedCircleCenter.y = -1;\n break;\n\n case FL_PUSH:\n if(onLeftHalf)\n {\n leftCircleCenter.x = Fl::event_x() - widget->x();\n leftCircleCenter.y = Fl::event_y() - widget->y();\n }\n else\n {\n rightCircleCenter.x = Fl::event_x() - widget->x();\n rightCircleCenter.y = Fl::event_y() - widget->y();\n }\n\n pointedCircleCenter.x = pointedCircleCenter.y = -1;\n break;\n\n default: ;\n }\n\n if(HAVE_CIRCLES && analysisState == RESET)\n goResetButton->activate();\n}\n\nstatic void setResetAnalysis(void)\n{\n goResetButton->labelfont(FL_HELVETICA_BOLD);\n goResetButton->labelcolor(FL_RED);\n goResetButton->type(FL_TOGGLE_BUTTON);\n goResetButton->label(\"Analyze\");\n\n numPoints = 0;\n if(plot) plot->clear();\n lastLeftPoint = lastRightPoint = NULL; \n leftAccumValue = 0.0;\n rightAccumValue = 0.0;\n leftAccum ->value(\"0.0\");\n rightAccum->value(\"0.0\");\n\n if(!AM_READING_CAMERA)\n source->restartStream();\n\n analysisState = RESET;\n}\n\nstatic void setRunningAnalysis(void)\n{\n goResetButton->labelfont(FL_HELVETICA);\n goResetButton->labelcolor(FL_BLACK);\n goResetButton->type(FL_TOGGLE_BUTTON);\n goResetButton->label(\"Stop analysis\");\n\n pointedCircleCenter.x = pointedCircleCenter.y = -1;\n\n analysisState = RUNNING;\n}\n\nstatic void setStoppedAnalysis(void)\n{\n goResetButton->labelfont(FL_HELVETICA);\n goResetButton->labelcolor(FL_BLACK);\n goResetButton->type(FL_NORMAL_BUTTON);\n goResetButton->label(\"Reset analysis data\");\n\n analysisState = STOPPED;\n}\n\nstatic void pressedGoReset(Fl_Widget* widget __attribute__((unused)), void* cookie __attribute__((unused)))\n{\n if (analysisState == RUNNING) setStoppedAnalysis();\n else if(analysisState == STOPPED) setResetAnalysis();\n else setRunningAnalysis();\n}\n\nint main(int argc, char* argv[])\n{\n Fl::lock();\n Fl::visual(FL_RGB);\n\n \/\/ To load a video file, the last cmdline argument must be the file.\n \/\/ To read a camera, the last cmdline argument must be 0x..., we use it as the camera GUID\n \/\/ Otherwise we try to load any camera\n if(argc < 2)\n {\n source = new CameraSource (FRAMESOURCE_GRAYSCALE, false, 0, CROP_RECT);\n }\n else if(strncmp(argv[argc-1], \"0x\", 2) == 0)\n {\n assert(sizeof(long long unsigned int) == sizeof(uint64_t));\n\n uint64_t guid;\n sscanf(&argv[argc-1][2], \"%llx\", (long long unsigned int*)&guid);\n source = new CameraSource(FRAMESOURCE_GRAYSCALE, false, guid, CROP_RECT);\n }\n else\n source = new FFmpegDecoder(argv[argc-1], FRAMESOURCE_GRAYSCALE, false, CROP_RECT);\n\n if(! *source)\n {\n fprintf(stderr, \"couldn't open source\\n\");\n delete source;\n return 0;\n }\n\n Fl_Double_Window* window =\n new Fl_Double_Window(WINDOW_W, WINDOW_H, \"Wormtracker 3\");\n widgetImage = new CvFltkWidget(0, 0, source->w(), source->h(),\n WIDGET_COLOR);\n\n widgetImage->callback(widgetImageCallback);\n\n goResetButton = new Fl_Button( widgetImage->w(), 0, BUTTON_W, BUTTON_H);\n goResetButton->callback(pressedGoReset);\n goResetButton->deactivate();\n\n plot = new Ca_Canvas( Y_AXIS_WIDTH + AXIS_EXTRA_SPACE, widgetImage->y() + widgetImage->h(),\n PLOT_W, PLOT_H,\n \"Worm occupancy\");\n plot->align(FL_ALIGN_TOP);\n\n \/\/ This is extremely important for some reason. Without it the plots do not refresh property and\n \/\/ there're artifacts every time the plot is resized\n plot->box(FL_DOWN_BOX);\n\n Xaxis = new Ca_X_Axis(plot->x(), plot->y() + plot->h(), plot->w(), X_AXIS_HEIGHT, \"Minutes\");\n Xaxis->align(FL_ALIGN_BOTTOM);\n Xaxis->minimum(0);\n Xaxis->maximum(1);\n Xaxis->label_format(\"%g\");\n Xaxis->major_step(10);\n Xaxis->label_step(10);\n Xaxis->axis_color(FL_BLACK);\n Xaxis->axis_align(CA_BOTTOM | CA_LINE);\n\n Yaxis = new Ca_Y_Axis(AXIS_EXTRA_SPACE, plot->y(), Y_AXIS_WIDTH, plot->h());\n Fl_Rotated_Text YaxisLabel(\"occupancy ratio\", FL_HELVETICA, 14, 0, 1);\n Yaxis->image(&YaxisLabel);\n Yaxis->minimum(0);\n Yaxis->maximum(0.01);\n Yaxis->align(FL_ALIGN_LEFT);\n Yaxis->axis_align(CA_LEFT | CA_LINE);\n Yaxis->axis_color(FL_BLACK);\n\n leftAccum = new Fl_Output(widgetImage->x() + widgetImage->w(), goResetButton->y() + goResetButton->h(),\n ACCUM_W, ACCUM_H, \"Left accumulator (occupancy-seconds)\");\n rightAccum = new Fl_Output(leftAccum->x(), leftAccum->y() + leftAccum->h(),\n ACCUM_W, ACCUM_H, \"Right accumulator (occupancy-seconds)\");\n leftAccum ->align(FL_ALIGN_RIGHT);\n rightAccum->align(FL_ALIGN_RIGHT);\n leftAccum ->labelcolor(FL_RED);\n rightAccum->labelcolor(FL_GREEN);\n\n window->end();\n window->show();\n\n processingInit(source->w(), source->h());\n\n setResetAnalysis();\n\n \/\/ I read the data with a tiny delay. This makes sure that I skip old frames (only an issue if I\n \/\/ can't keep up with the data rate), but yet got as fast as I can\n IplImage* buffer = cvCreateImage(cvSize(source->w(), source->h()), IPL_DEPTH_8U, 1);\n\n \/\/ If reading from a stored video file, go as fast as possible\n if(AM_READING_CAMERA) source->startSourceThread(&gotNewFrame, 1e6\/DATA_FRAME_RATE_FPS, buffer);\n else source->startSourceThread(&gotNewFrame, 0, buffer);\n\n while (Fl::wait())\n {\n }\n\n Fl::unlock();\n\n delete source;\n delete window;\n cvReleaseImage(&buffer);\n\n processingCleanup();\n return 0;\n}\n<|endoftext|>"} {"text":"\/*Code by Dmitry Khovratovich, 2016\nCC0 license\n*\/\n\n#include \"pow.h\"\n#include \"blake\/blake2.h\"\n#include \n\n\nstatic uint64_t rdtsc(void) {\n#ifdef _MSC_VER\n return __rdtsc();\n#else\n#if defined(__amd64__) || defined(__x86_64__)\n uint64_t rax, rdx;\n __asm__ __volatile__(\"rdtsc\" : \"=a\"(rax), \"=d\"(rdx) : : );\n return (rdx << 32) | rax;\n#elif defined(__i386__) || defined(__i386) || defined(__X86__)\n uint64_t rax;\n __asm__ __volatile__(\"rdtsc\" : \"=A\"(rax) : : );\n return rax;\n#else\n#error \"Not implemented!\"\n#endif\n#endif\n}\n\n\nusing namespace _POW;\nusing namespace std;\n\nvoid Equihash::InitializeMemory()\n{\n uint32_t tuple_n = ((uint32_t)1) << (n \/ (k + 1));\n Tuple default_tuple(k); \/\/ k blocks to store (one left for index)\n std::vector def_tuples(LIST_LENGTH, default_tuple);\n tupleList = std::vector>(tuple_n, def_tuples);\n filledList= std::vector(tuple_n, 0);\n solutions.resize(0);\n forks.resize(0);\n}\n\nvoid Equihash::PrintTuples(FILE* fp) {\n unsigned count = 0;\n for (unsigned i = 0; i < tupleList.size(); ++i) {\n for (unsigned m = 0; m < filledList[i]; ++m) {\n fprintf(fp, \"[%d][%d]:\", i,m);\n for (unsigned j = 0; j < tupleList[i][m].blocks.size(); ++j)\n fprintf(fp, \" %x \", tupleList[i][m].blocks[j]);\n fprintf(fp, \" || %x\", tupleList[i][m].reference);\n fprintf(fp, \" |||| \");\n }\n count += filledList[i];\n fprintf(fp, \"\\n\");\n }\n fprintf(fp, \"TOTAL: %d elements printed\", count);\n}\n\nvoid Equihash::FillMemory(uint32_t length) \/\/works for k<=7\n{\n uint32_t input[SEED_LENGTH + 2];\n for (unsigned i = 0; i < SEED_LENGTH; ++i)\n input[i] = seed[i];\n input[SEED_LENGTH] = nonce;\n input[SEED_LENGTH + 1] = 0;\n uint32_t buf[MAX_N \/ 4];\n for (unsigned i = 0; i < length; ++i, ++input[SEED_LENGTH + 1]) {\n blake2b((uint8_t*)buf, &input, NULL, sizeof(buf), sizeof(input), 0);\n uint32_t index = buf[0] >> (32 - n \/ (k + 1));\n unsigned count = filledList[index];\n if (count < LIST_LENGTH) {\n for (unsigned j = 1; j < (k + 1); ++j) {\n \/\/select j-th block of n\/(k+1) bits\n tupleList[index][count].blocks[j - 1] = buf[j] >> (32 - n \/ (k + 1));\n }\n tupleList[index][count].reference = i;\n filledList[index]++;\n }\n }\n}\n\nstd::vector Equihash::ResolveTreeByLevel(Fork fork, unsigned level) {\n if (level == 0)\n return std::vector{fork.ref1, fork.ref2};\n auto v1 = ResolveTreeByLevel(forks[level - 1][fork.ref1], level - 1);\n auto v2 = ResolveTreeByLevel(forks[level - 1][fork.ref2], level - 1);\n v1.insert(v1.end(), v2.begin(), v2.end());\n return v1;\n}\n\nstd::vector Equihash::ResolveTree(Fork fork) {\n return ResolveTreeByLevel(fork, forks.size());\n}\n\n\nvoid Equihash::ResolveCollisions(bool store) {\n const unsigned tableLength = tupleList.size(); \/\/number of rows in the hashtable \n const unsigned maxNewCollisions = tupleList.size()*FORK_MULTIPLIER; \/\/max number of collisions to be found\n const unsigned newBlocks = tupleList[0][0].blocks.size() - 1;\/\/ number of blocks in the future collisions\n std::vector newForks(maxNewCollisions); \/\/list of forks created at this step\n auto tableRow = vector(LIST_LENGTH, Tuple(newBlocks)); \/\/Row in the hash table\n vector> collisionList(tableLength,tableRow);\n std::vector newFilledList(tableLength,0); \/\/number of entries in rows\n uint32_t newColls = 0; \/\/collision counter\n for (unsigned i = 0; i < tableLength; ++i) { \n for (unsigned j = 0; j < filledList[i]; ++j) {\n for (unsigned m = j + 1; m < filledList[i]; ++m) { \/\/Collision\n \/\/New index\n uint32_t newIndex = tupleList[i][j].blocks[0] ^ tupleList[i][m].blocks[0];\n Fork newFork = Fork(tupleList[i][j].reference, tupleList[i][m].reference);\n \/\/Check if we get a solution\n if (store) { \/\/last step\n if (newIndex == 0) {\/\/Solution\n std::vector solution_inputs = ResolveTree(newFork);\n solutions.push_back(Proof(n, k, seed, nonce, solution_inputs));\n }\n }\n else { \/\/Resolve\n if (newFilledList[newIndex] < LIST_LENGTH && newColls < maxNewCollisions) {\n for (unsigned l = 0; l < newBlocks; ++l) {\n collisionList[newIndex][newFilledList[newIndex]].blocks[l] \n = tupleList[i][j].blocks[l+1] ^ tupleList[i][m].blocks[l+1];\n }\n newForks[newColls] = newFork;\n collisionList[newIndex][newFilledList[newIndex]].reference = newColls;\n newFilledList[newIndex]++;\n newColls++;\n }\/\/end of adding collision\n }\n }\n }\/\/end of collision for i\n }\n forks.push_back(newForks);\n std::swap(tupleList, collisionList);\n std::swap(filledList, newFilledList);\n}\n\nProof Equihash::FindProof(){\n FILE* fp = fopen(\"proof.log\", \"w+\");\n fclose(fp);\n this->nonce = 1;\n while (nonce < MAX_NONCE) {\n nonce++;\n printf(\"Testing nonce %d\\n\", nonce);\n uint64_t start_cycles = rdtsc();\n InitializeMemory(); \/\/allocate\n FillMemory(5UL << (n \/ (k + 1)-1)); \/\/fill with hashes\n uint64_t fill_end = rdtsc();\n printf(\"Filling %2.2f Mcycles \\n\", (double)(fill_end - start_cycles) \/ (1UL << 20));\n \/*fp = fopen(\"proof.log\", \"a+\");\n fprintf(fp, \"\\n===MEMORY FILLED:\\n\");\n PrintTuples(fp);\n fclose(fp);*\/\n for (unsigned i = 1; i <= k; ++i) {\n uint64_t resolve_start = rdtsc();\n bool to_store = (i == k);\n ResolveCollisions(to_store); \/\/XOR collisions, concatenate indices and shift\n uint64_t resolve_end = rdtsc();\n printf(\"Resolving %2.2f Mcycles \\n\", (double)(resolve_end - resolve_start) \/ (1UL << 20));\n \/* fp = fopen(\"proof.log\", \"a+\");\n fprintf(fp, \"\\n===RESOLVED AFTER STEP %d:\\n\", i);\n PrintTuples(fp);\n fclose(fp);*\/\n }\n uint64_t stop_cycles = rdtsc();\n\n double mcycles_d = (double)(stop_cycles - start_cycles) \/ (1UL << 20);\n uint32_t kbytes = (tupleList.size()*LIST_LENGTH*k*sizeof(uint32_t)) \/ (1UL << 10);\n printf(\"Time spent for n=%d k=%d %d KiB: %2.2f Mcycles \\n\",\n n, k, kbytes,\n mcycles_d);\n\n \/\/Duplicate check\n for (unsigned i = 0; i < solutions.size(); ++i) {\n auto vec = solutions[i].inputs;\n std::sort(vec.begin(), vec.end());\n bool dup = false;\n for (unsigned k = 0; k < vec.size() - 1; ++k) {\n if (vec[k] == vec[k + 1])\n dup = true;\n }\n if (!dup)\n return solutions[i];\n }\n }\n return Proof(n, k, seed, nonce, std::vector());\n}\n\nbool Proof::Test()\n{\n uint32_t input[SEED_LENGTH + 2];\n for (unsigned i = 0; i < SEED_LENGTH; ++i)\n input[i] = seed[i];\n input[SEED_LENGTH] = nonce;\n input[SEED_LENGTH + 1] = 0;\n uint32_t buf[MAX_N \/ 4];\n std::vector blocks(k+1,0);\n for (unsigned i = 0; i < inputs.size(); ++i) {\n input[SEED_LENGTH + 1] = inputs[i];\n blake2b((uint8_t*)buf, &input, NULL, sizeof(buf), sizeof(input), 0);\n for (unsigned j = 0; j < (k + 1); ++j) {\n \/\/select j-th block of n\/(k+1) bits\n blocks[j] ^= buf[j] >> (32 - n \/ (k + 1));\n }\n }\n bool b = true;\n for (unsigned j = 0; j < (k + 1); ++j) {\n b &= (blocks[j] == 0);\n }\n if (b && inputs.size()!=0) {\n printf(\"Solution found:\\n\");\n for (unsigned i = 0; i < inputs.size(); ++i) {\n printf(\" %x \", inputs[i]);\n }\n printf(\"\\n\");\n }\n return b;\n}Too big lists created\/*Code by Dmitry Khovratovich, 2016\nCC0 license\n*\/\n\n#include \"pow.h\"\n#include \"blake\/blake2.h\"\n#include \n\n\nstatic uint64_t rdtsc(void) {\n#ifdef _MSC_VER\n return __rdtsc();\n#else\n#if defined(__amd64__) || defined(__x86_64__)\n uint64_t rax, rdx;\n __asm__ __volatile__(\"rdtsc\" : \"=a\"(rax), \"=d\"(rdx) : : );\n return (rdx << 32) | rax;\n#elif defined(__i386__) || defined(__i386) || defined(__X86__)\n uint64_t rax;\n __asm__ __volatile__(\"rdtsc\" : \"=A\"(rax) : : );\n return rax;\n#else\n#error \"Not implemented!\"\n#endif\n#endif\n}\n\n\nusing namespace _POW;\nusing namespace std;\n\nvoid Equihash::InitializeMemory()\n{\n uint32_t tuple_n = ((uint32_t)1) << (n \/ (k + 1));\n Tuple default_tuple(k); \/\/ k blocks to store (one left for index)\n std::vector def_tuples(LIST_LENGTH, default_tuple);\n tupleList = std::vector>(tuple_n, def_tuples);\n filledList= std::vector(tuple_n, 0);\n solutions.resize(0);\n forks.resize(0);\n}\n\nvoid Equihash::PrintTuples(FILE* fp) {\n unsigned count = 0;\n for (unsigned i = 0; i < tupleList.size(); ++i) {\n for (unsigned m = 0; m < filledList[i]; ++m) {\n fprintf(fp, \"[%d][%d]:\", i,m);\n for (unsigned j = 0; j < tupleList[i][m].blocks.size(); ++j)\n fprintf(fp, \" %x \", tupleList[i][m].blocks[j]);\n fprintf(fp, \" || %x\", tupleList[i][m].reference);\n fprintf(fp, \" |||| \");\n }\n count += filledList[i];\n fprintf(fp, \"\\n\");\n }\n fprintf(fp, \"TOTAL: %d elements printed\", count);\n}\n\nvoid Equihash::FillMemory(uint32_t length) \/\/works for k<=7\n{\n uint32_t input[SEED_LENGTH + 2];\n for (unsigned i = 0; i < SEED_LENGTH; ++i)\n input[i] = seed[i];\n input[SEED_LENGTH] = nonce;\n input[SEED_LENGTH + 1] = 0;\n uint32_t buf[MAX_N \/ 4];\n for (unsigned i = 0; i < length; ++i, ++input[SEED_LENGTH + 1]) {\n blake2b((uint8_t*)buf, &input, NULL, sizeof(buf), sizeof(input), 0);\n uint32_t index = buf[0] >> (32 - n \/ (k + 1));\n unsigned count = filledList[index];\n if (count < LIST_LENGTH) {\n for (unsigned j = 1; j < (k + 1); ++j) {\n \/\/select j-th block of n\/(k+1) bits\n tupleList[index][count].blocks[j - 1] = buf[j] >> (32 - n \/ (k + 1));\n }\n tupleList[index][count].reference = i;\n filledList[index]++;\n }\n }\n}\n\nstd::vector Equihash::ResolveTreeByLevel(Fork fork, unsigned level) {\n if (level == 0)\n return std::vector{fork.ref1, fork.ref2};\n auto v1 = ResolveTreeByLevel(forks[level - 1][fork.ref1], level - 1);\n auto v2 = ResolveTreeByLevel(forks[level - 1][fork.ref2], level - 1);\n v1.insert(v1.end(), v2.begin(), v2.end());\n return v1;\n}\n\nstd::vector Equihash::ResolveTree(Fork fork) {\n return ResolveTreeByLevel(fork, forks.size());\n}\n\n\nvoid Equihash::ResolveCollisions(bool store) {\n const unsigned tableLength = tupleList.size(); \/\/number of rows in the hashtable \n const unsigned maxNewCollisions = tupleList.size()*FORK_MULTIPLIER; \/\/max number of collisions to be found\n const unsigned newBlocks = tupleList[0][0].blocks.size() - 1;\/\/ number of blocks in the future collisions\n std::vector newForks(maxNewCollisions); \/\/list of forks created at this step\n auto tableRow = vector(LIST_LENGTH, Tuple(newBlocks)); \/\/Row in the hash table\n vector> collisionList(tableLength,tableRow);\n std::vector newFilledList(tableLength,0); \/\/number of entries in rows\n uint32_t newColls = 0; \/\/collision counter\n for (unsigned i = 0; i < tableLength; ++i) { \n for (unsigned j = 0; j < filledList[i]; ++j) {\n for (unsigned m = j + 1; m < filledList[i]; ++m) { \/\/Collision\n \/\/New index\n uint32_t newIndex = tupleList[i][j].blocks[0] ^ tupleList[i][m].blocks[0];\n Fork newFork = Fork(tupleList[i][j].reference, tupleList[i][m].reference);\n \/\/Check if we get a solution\n if (store) { \/\/last step\n if (newIndex == 0) {\/\/Solution\n std::vector solution_inputs = ResolveTree(newFork);\n solutions.push_back(Proof(n, k, seed, nonce, solution_inputs));\n }\n }\n else { \/\/Resolve\n if (newFilledList[newIndex] < LIST_LENGTH && newColls < maxNewCollisions) {\n for (unsigned l = 0; l < newBlocks; ++l) {\n collisionList[newIndex][newFilledList[newIndex]].blocks[l] \n = tupleList[i][j].blocks[l+1] ^ tupleList[i][m].blocks[l+1];\n }\n newForks[newColls] = newFork;\n collisionList[newIndex][newFilledList[newIndex]].reference = newColls;\n newFilledList[newIndex]++;\n newColls++;\n }\/\/end of adding collision\n }\n }\n }\/\/end of collision for i\n }\n forks.push_back(newForks);\n std::swap(tupleList, collisionList);\n std::swap(filledList, newFilledList);\n}\n\nProof Equihash::FindProof(){\n FILE* fp = fopen(\"proof.log\", \"w+\");\n fclose(fp);\n this->nonce = 1;\n while (nonce < MAX_NONCE) {\n nonce++;\n printf(\"Testing nonce %d\\n\", nonce);\n uint64_t start_cycles = rdtsc();\n InitializeMemory(); \/\/allocate\n FillMemory(4UL << (n \/ (k + 1)-1)); \/\/fill with hashes\n uint64_t fill_end = rdtsc();\n printf(\"Filling %2.2f Mcycles \\n\", (double)(fill_end - start_cycles) \/ (1UL << 20));\n \/*fp = fopen(\"proof.log\", \"a+\");\n fprintf(fp, \"\\n===MEMORY FILLED:\\n\");\n PrintTuples(fp);\n fclose(fp);*\/\n for (unsigned i = 1; i <= k; ++i) {\n uint64_t resolve_start = rdtsc();\n bool to_store = (i == k);\n ResolveCollisions(to_store); \/\/XOR collisions, concatenate indices and shift\n uint64_t resolve_end = rdtsc();\n printf(\"Resolving %2.2f Mcycles \\n\", (double)(resolve_end - resolve_start) \/ (1UL << 20));\n \/* fp = fopen(\"proof.log\", \"a+\");\n fprintf(fp, \"\\n===RESOLVED AFTER STEP %d:\\n\", i);\n PrintTuples(fp);\n fclose(fp);*\/\n }\n uint64_t stop_cycles = rdtsc();\n\n double mcycles_d = (double)(stop_cycles - start_cycles) \/ (1UL << 20);\n uint32_t kbytes = (tupleList.size()*LIST_LENGTH*k*sizeof(uint32_t)) \/ (1UL << 10);\n printf(\"Time spent for n=%d k=%d %d KiB: %2.2f Mcycles \\n\",\n n, k, kbytes,\n mcycles_d);\n\n \/\/Duplicate check\n for (unsigned i = 0; i < solutions.size(); ++i) {\n auto vec = solutions[i].inputs;\n std::sort(vec.begin(), vec.end());\n bool dup = false;\n for (unsigned k = 0; k < vec.size() - 1; ++k) {\n if (vec[k] == vec[k + 1])\n dup = true;\n }\n if (!dup)\n return solutions[i];\n }\n }\n return Proof(n, k, seed, nonce, std::vector());\n}\n\nbool Proof::Test()\n{\n uint32_t input[SEED_LENGTH + 2];\n for (unsigned i = 0; i < SEED_LENGTH; ++i)\n input[i] = seed[i];\n input[SEED_LENGTH] = nonce;\n input[SEED_LENGTH + 1] = 0;\n uint32_t buf[MAX_N \/ 4];\n std::vector blocks(k+1,0);\n for (unsigned i = 0; i < inputs.size(); ++i) {\n input[SEED_LENGTH + 1] = inputs[i];\n blake2b((uint8_t*)buf, &input, NULL, sizeof(buf), sizeof(input), 0);\n for (unsigned j = 0; j < (k + 1); ++j) {\n \/\/select j-th block of n\/(k+1) bits\n blocks[j] ^= buf[j] >> (32 - n \/ (k + 1));\n }\n }\n bool b = true;\n for (unsigned j = 0; j < (k + 1); ++j) {\n b &= (blocks[j] == 0);\n }\n if (b && inputs.size()!=0) {\n printf(\"Solution found:\\n\");\n for (unsigned i = 0; i < inputs.size(); ++i) {\n printf(\" %x \", inputs[i]);\n }\n printf(\"\\n\");\n }\n return b;\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) MediaArea.net SARL. All Rights Reserved.\r\n *\r\n * Use of this source code is governed by a BSD-style license that can\r\n * be found in the License.html file in the root of the source tree.\r\n *\/\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#ifdef __BORLANDC__\r\n #pragma hdrstop\r\n#endif\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"Common\/Core.h\"\r\n#include \"Help.h\"\r\n#include \"Config.h\"\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/***************************************************************************\r\n\/\/\r\n\/\/***************************************************************************\r\n\/\/---------------------------------------------------------------------------\r\nString Program_Name = __T(\"MediaInfo\");\r\n\r\nvoid Set_Program_Name(const String &Name)\r\n{\r\n Program_Name = Name;\r\n #if defined(_MSC_VER)\r\n Program_Name = Program_Name.substr(Program_Name.rfind('\\\\')+1);\r\n Program_Name = Program_Name.substr(0, Program_Name.find('.'));\r\n #else\r\n Program_Name = Program_Name.substr(Program_Name.rfind('\/')+1);\r\n #endif\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nint Help()\r\n{\r\n STRINGOUT(String(__T(\"Usage: \\\" [-Options...] FileName1 [Filename2...]\\\"\")).insert(8, Program_Name));\r\n TEXTOUT(\"\");\r\n TEXTOUT(\"Options:\");\r\n TEXTOUT(\"--Help, -h\");\r\n TEXTOUT(\" Display this help and exit\");\r\n TEXTOUT(\"--Help-Output\");\r\n TEXTOUT(\" Display help for Output= option\");\r\n TEXTOUT(\"--Help-AnOption\");\r\n TEXTOUT(\" Display help for \\\"AnOption\\\"\");\r\n TEXTOUT(\"--Version\");\r\n TEXTOUT(\" Display MediaInfo version and exit\");\r\n TEXTOUT(\"\");\r\n TEXTOUT(\"--Full , -f\");\r\n TEXTOUT(\" Full information Display (all internal tags)\");\r\n TEXTOUT(\"--Output=HTML\");\r\n TEXTOUT(\" Full information Display with HTML tags\");\r\n TEXTOUT(\"--Output=XML\");\r\n TEXTOUT(\" Full information Display with XML tags\");\r\n TEXTOUT(\"--Output=EBUCore\");\r\n TEXTOUT(\" Full information Display with EBUCore compliant XML tags\");\r\n TEXTOUT(\"--Output=PBCore\");\r\n TEXTOUT(\" Full information Display with PBCore compliant XML tags\");\r\n TEXTOUT(\"--Output=PBCore2\");\r\n TEXTOUT(\" Full information Display with PBCore 2.0 compliant XML tags\");\r\n TEXTOUT(\"--AcquisitionDataOutputMode=segmentParameter\");\r\n TEXTOUT(\" Display Acquisition Data by segment then parameter (EBUCore output)\");\r\n TEXTOUT(\"--AcquisitionDataOutputMode=parameterSegment\");\r\n TEXTOUT(\" Display Acquisition Data by parameter then segment (EBUCore output)\");\r\n TEXTOUT(\"--ExternalMetadata=...\");\r\n TEXTOUT(\" Add external metadata to the output (EBUCore output)\");\r\n TEXTOUT(\"--ExternalMetadataConfig=...\");\r\n TEXTOUT(\" Output template for external metadata (EBUCore output)\");\r\n TEXTOUT(\"--Info-Parameters\");\r\n TEXTOUT(\" Display list of Inform= parameters\");\r\n TEXTOUT(\"\");\r\n TEXTOUT(\"--Language=raw\");\r\n TEXTOUT(\" Display non-translated unique identifiers (internal text)\");\r\n TEXTOUT(\"--Details=1\");\r\n TEXTOUT(\" Display mediatrace info\");\r\n TEXTOUT(\"--File_TestContinuousFileNames=0\");\r\n TEXTOUT(\" Disable image sequence detection\");\r\n TEXTOUT(\"--LogFile=...\");\r\n TEXTOUT(\" Save the output in the specified file\");\r\n TEXTOUT(\"--BOM\");\r\n TEXTOUT(\" Byte order mark for UTF-8 output\");\r\n TEXTOUT(\"\");\r\n TEXTOUT(\"--Ssl_CertificateFileName=...\");\r\n TEXTOUT(\" File name of the SSL certificate.\");\r\n TEXTOUT(\" The default format is \\\"PEM\\\" and can be changed\");\r\n TEXTOUT(\" with --Ssl_CertificateFormat.\");\r\n TEXTOUT(\"--Ssl_CertificateFormat=...\");\r\n TEXTOUT(\" File format of the SSL certificate.\");\r\n TEXTOUT(\" Supported formats are \\\"PEM\\\" and \\\"DER\\\"\");\r\n TEXTOUT(\"--Ssl_PrivateKeyFileName=...\");\r\n TEXTOUT(\" File name of the SSL private key.\");\r\n TEXTOUT(\" The default format is \\\"PEM\\\" and can be changed\");\r\n TEXTOUT(\" with --Ssl_PrivateKeyFormat.\");\r\n TEXTOUT(\" Note: private key with a password is not supported.\");\r\n TEXTOUT(\"--Ssl_PrivateKeyFormat=...\");\r\n TEXTOUT(\" File format of the SSL private key.\");\r\n TEXTOUT(\" Supported formats are \\\"PEM\\\" and \\\"DER\\\"\");\r\n TEXTOUT(\"--Ssl_CertificateAuthorityFileName=...\");\r\n TEXTOUT(\" File name of the SSL certificate authorities\");\r\n TEXTOUT(\" to verify the peer with.\");\r\n TEXTOUT(\"--Ssl_CertificateAuthorityPath=...\");\r\n TEXTOUT(\" Path of the SSL certificate authorities\");\r\n TEXTOUT(\" to verify the peer with.\");\r\n TEXTOUT(\"--Ssl_CertificateRevocationListFileName=...\");\r\n TEXTOUT(\" File name of the SSL certificate revocation list.\");\r\n TEXTOUT(\" The format is \\\"PEM\\\"\");\r\n TEXTOUT(\"--Ssl_IgnoreSecurity=...\");\r\n TEXTOUT(\" Does not verify the authenticity of the peer's certificate\");\r\n TEXTOUT(\" Use it at your own risks\");\r\n TEXTOUT(\"--Ssh_PublicKeyFileName=...\");\r\n TEXTOUT(\" File name of the SSH private key.\");\r\n TEXTOUT(\" Default is $HOME\/.ssh\/id_rsa.pub or $HOME\/.ssh\/id_dsa.pub\");\r\n TEXTOUT(\" if the HOME environment variable is set, and just\");\r\n TEXTOUT(\" \\\"id_rsa.pub\\\" or \\\"id_dsa.pub\\\" in the current directory\");\r\n TEXTOUT(\" if HOME is not set.\");\r\n TEXTOUT(\" Note: you need to set both public and private key.\");\r\n TEXTOUT(\"--Ssh_PrivateKeyFileName=...\");\r\n TEXTOUT(\" File name of the SSH private key.\");\r\n TEXTOUT(\" Default is $HOME\/.ssh\/id_rsa or $HOME\/.ssh\/id_dsa\");\r\n TEXTOUT(\" if the HOME environment variable is set, and just\");\r\n TEXTOUT(\" \\\"id_rsa\\\" or \\\"id_dsa\\\" in the current directory\");\r\n TEXTOUT(\" if HOME is not set.\");\r\n TEXTOUT(\" Note: you need to set both public and private key.\");\r\n TEXTOUT(\" Note: private key with a password is not supported.\");\r\n TEXTOUT(\"--Ssh_KnownHostsFileName=...\");\r\n TEXTOUT(\" File name of the known hosts\");\r\n TEXTOUT(\" The format is the OpenSSH file format (libssh2)\");\r\n TEXTOUT(\" Default is $HOME\/.ssh\/known_hosts\");\r\n TEXTOUT(\" if the HOME environment variable is set, and just\");\r\n TEXTOUT(\" \\\"known_hosts\\\" in the current directory\");\r\n TEXTOUT(\" if HOME is not set.\");\r\n TEXTOUT(\"--Ssh_IgnoreSecurity\");\r\n TEXTOUT(\" Does not verify the authenticity of the peer\");\r\n TEXTOUT(\" (you don't need to accept the key with ssh first)\");\r\n TEXTOUT(\" Use it at your own risks\");\r\n\r\n return MI_OK;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nint Help_Nothing()\r\n{\r\n STRINGOUT(String(__T(\"Usage: \\\" [-Options...] FileName1 [Filename2...]\\\"\")).insert(8, Program_Name));\r\n STRINGOUT(String(__T(\"\\\" --Help\\\" for displaying more information\")).insert(1, Program_Name));\r\n\r\n return MI_OK;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nint Help_Output()\r\n{\r\n TEXTOUT(\"--Output=... Specify a template (BETA)\");\r\n STRINGOUT(String(__T(\"Usage: \\\" --Output=[xxx;]Text FileName\\\"\")).insert(8, Program_Name));\r\n TEXTOUT(\"\");\r\n TEXTOUT(\"xxx can be: General, Video, Audio, Text, Chapter, Image, Menu\");\r\n TEXTOUT(\"Text can be the template text, or a filename\");\r\n TEXTOUT(\" Filename must be in the form file:\/\/filename\");\r\n TEXTOUT(\"\");\r\n TEXTOUT(\"See --Info-Parameters for available parameters in the text\");\r\n TEXTOUT(\"(Parameters must be surrounded by \\\"%\\\" sign)\");\r\n TEXTOUT(\"\");\r\n STRINGOUT(String(__T(\"Usage: \\\" --Output=Video;%AspectRatio% FileName\\\"\")).insert(8, Program_Name));\r\n TEXTOUT(\"\");\r\n STRINGOUT(String(__T(\"Usage: \\\" --Output=Video;file:\/\/Video.txt FileName\\\"\")).insert(8, Program_Name));\r\n TEXTOUT(\"and Video.txt contains \");\r\n TEXTOUT(\"\\\"%DisplayAspectRatio%\\\" for Video Aspect Ratio.\");\r\n TEXTOUT(\"\");\r\n STRINGOUT(String(__T(\"Usage: \\\" --Output=file:\/\/Text.txt FileName\\\"\")).insert(8, Program_Name));\r\n TEXTOUT(\"and Text.txt contains\");\r\n TEXTOUT(\"\\\"Video;%DisplayAspectRatio%\\\" for Video Aspect Ratio.\");\r\n TEXTOUT(\"\\\"Audio;%Format%\\\" for Audio Format.\");\r\n\r\n return MI_ERROR;\r\n}\r\n\r\n\r\n\/\/---------------------------------------------------------------------------\r\nint Usage()\r\n{\r\n Help_Nothing();\r\n return MI_ERROR;\r\n}\r\nHelp.cpp - adds OLDXML option\/* Copyright (c) MediaArea.net SARL. All Rights Reserved.\r\n *\r\n * Use of this source code is governed by a BSD-style license that can\r\n * be found in the License.html file in the root of the source tree.\r\n *\/\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#ifdef __BORLANDC__\r\n #pragma hdrstop\r\n#endif\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"Common\/Core.h\"\r\n#include \"Help.h\"\r\n#include \"Config.h\"\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/***************************************************************************\r\n\/\/\r\n\/\/***************************************************************************\r\n\/\/---------------------------------------------------------------------------\r\nString Program_Name = __T(\"MediaInfo\");\r\n\r\nvoid Set_Program_Name(const String &Name)\r\n{\r\n Program_Name = Name;\r\n #if defined(_MSC_VER)\r\n Program_Name = Program_Name.substr(Program_Name.rfind('\\\\')+1);\r\n Program_Name = Program_Name.substr(0, Program_Name.find('.'));\r\n #else\r\n Program_Name = Program_Name.substr(Program_Name.rfind('\/')+1);\r\n #endif\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nint Help()\r\n{\r\n STRINGOUT(String(__T(\"Usage: \\\" [-Options...] FileName1 [Filename2...]\\\"\")).insert(8, Program_Name));\r\n TEXTOUT(\"\");\r\n TEXTOUT(\"Options:\");\r\n TEXTOUT(\"--Help, -h\");\r\n TEXTOUT(\" Display this help and exit\");\r\n TEXTOUT(\"--Help-Output\");\r\n TEXTOUT(\" Display help for Output= option\");\r\n TEXTOUT(\"--Help-AnOption\");\r\n TEXTOUT(\" Display help for \\\"AnOption\\\"\");\r\n TEXTOUT(\"--Version\");\r\n TEXTOUT(\" Display MediaInfo version and exit\");\r\n TEXTOUT(\"\");\r\n TEXTOUT(\"--Full , -f\");\r\n TEXTOUT(\" Full information Display (all internal tags)\");\r\n TEXTOUT(\"--Output=HTML\");\r\n TEXTOUT(\" Full information Display with HTML tags\");\r\n TEXTOUT(\"--Output=XML\");\r\n TEXTOUT(\" Full information Display with XML tags\");\r\n TEXTOUT(\"--Output=OLDXML\");\r\n TEXTOUT(\" Full information Display with XML tags using the older MediaInfo schema\"); \r\n TEXTOUT(\"--Output=EBUCore\");\r\n TEXTOUT(\" Full information Display with EBUCore compliant XML tags\");\r\n TEXTOUT(\"--Output=PBCore\");\r\n TEXTOUT(\" Full information Display with PBCore compliant XML tags\");\r\n TEXTOUT(\"--Output=PBCore2\");\r\n TEXTOUT(\" Full information Display with PBCore 2.0 compliant XML tags\");\r\n TEXTOUT(\"--AcquisitionDataOutputMode=segmentParameter\");\r\n TEXTOUT(\" Display Acquisition Data by segment then parameter (EBUCore output)\");\r\n TEXTOUT(\"--AcquisitionDataOutputMode=parameterSegment\");\r\n TEXTOUT(\" Display Acquisition Data by parameter then segment (EBUCore output)\");\r\n TEXTOUT(\"--ExternalMetadata=...\");\r\n TEXTOUT(\" Add external metadata to the output (EBUCore output)\");\r\n TEXTOUT(\"--ExternalMetadataConfig=...\");\r\n TEXTOUT(\" Output template for external metadata (EBUCore output)\");\r\n TEXTOUT(\"--Info-Parameters\");\r\n TEXTOUT(\" Display list of Inform= parameters\");\r\n TEXTOUT(\"\");\r\n TEXTOUT(\"--Language=raw\");\r\n TEXTOUT(\" Display non-translated unique identifiers (internal text)\");\r\n TEXTOUT(\"--Details=1\");\r\n TEXTOUT(\" Display mediatrace info\");\r\n TEXTOUT(\"--File_TestContinuousFileNames=0\");\r\n TEXTOUT(\" Disable image sequence detection\");\r\n TEXTOUT(\"--LogFile=...\");\r\n TEXTOUT(\" Save the output in the specified file\");\r\n TEXTOUT(\"--BOM\");\r\n TEXTOUT(\" Byte order mark for UTF-8 output\");\r\n TEXTOUT(\"\");\r\n TEXTOUT(\"--Ssl_CertificateFileName=...\");\r\n TEXTOUT(\" File name of the SSL certificate.\");\r\n TEXTOUT(\" The default format is \\\"PEM\\\" and can be changed\");\r\n TEXTOUT(\" with --Ssl_CertificateFormat.\");\r\n TEXTOUT(\"--Ssl_CertificateFormat=...\");\r\n TEXTOUT(\" File format of the SSL certificate.\");\r\n TEXTOUT(\" Supported formats are \\\"PEM\\\" and \\\"DER\\\"\");\r\n TEXTOUT(\"--Ssl_PrivateKeyFileName=...\");\r\n TEXTOUT(\" File name of the SSL private key.\");\r\n TEXTOUT(\" The default format is \\\"PEM\\\" and can be changed\");\r\n TEXTOUT(\" with --Ssl_PrivateKeyFormat.\");\r\n TEXTOUT(\" Note: private key with a password is not supported.\");\r\n TEXTOUT(\"--Ssl_PrivateKeyFormat=...\");\r\n TEXTOUT(\" File format of the SSL private key.\");\r\n TEXTOUT(\" Supported formats are \\\"PEM\\\" and \\\"DER\\\"\");\r\n TEXTOUT(\"--Ssl_CertificateAuthorityFileName=...\");\r\n TEXTOUT(\" File name of the SSL certificate authorities\");\r\n TEXTOUT(\" to verify the peer with.\");\r\n TEXTOUT(\"--Ssl_CertificateAuthorityPath=...\");\r\n TEXTOUT(\" Path of the SSL certificate authorities\");\r\n TEXTOUT(\" to verify the peer with.\");\r\n TEXTOUT(\"--Ssl_CertificateRevocationListFileName=...\");\r\n TEXTOUT(\" File name of the SSL certificate revocation list.\");\r\n TEXTOUT(\" The format is \\\"PEM\\\"\");\r\n TEXTOUT(\"--Ssl_IgnoreSecurity=...\");\r\n TEXTOUT(\" Does not verify the authenticity of the peer's certificate\");\r\n TEXTOUT(\" Use it at your own risks\");\r\n TEXTOUT(\"--Ssh_PublicKeyFileName=...\");\r\n TEXTOUT(\" File name of the SSH private key.\");\r\n TEXTOUT(\" Default is $HOME\/.ssh\/id_rsa.pub or $HOME\/.ssh\/id_dsa.pub\");\r\n TEXTOUT(\" if the HOME environment variable is set, and just\");\r\n TEXTOUT(\" \\\"id_rsa.pub\\\" or \\\"id_dsa.pub\\\" in the current directory\");\r\n TEXTOUT(\" if HOME is not set.\");\r\n TEXTOUT(\" Note: you need to set both public and private key.\");\r\n TEXTOUT(\"--Ssh_PrivateKeyFileName=...\");\r\n TEXTOUT(\" File name of the SSH private key.\");\r\n TEXTOUT(\" Default is $HOME\/.ssh\/id_rsa or $HOME\/.ssh\/id_dsa\");\r\n TEXTOUT(\" if the HOME environment variable is set, and just\");\r\n TEXTOUT(\" \\\"id_rsa\\\" or \\\"id_dsa\\\" in the current directory\");\r\n TEXTOUT(\" if HOME is not set.\");\r\n TEXTOUT(\" Note: you need to set both public and private key.\");\r\n TEXTOUT(\" Note: private key with a password is not supported.\");\r\n TEXTOUT(\"--Ssh_KnownHostsFileName=...\");\r\n TEXTOUT(\" File name of the known hosts\");\r\n TEXTOUT(\" The format is the OpenSSH file format (libssh2)\");\r\n TEXTOUT(\" Default is $HOME\/.ssh\/known_hosts\");\r\n TEXTOUT(\" if the HOME environment variable is set, and just\");\r\n TEXTOUT(\" \\\"known_hosts\\\" in the current directory\");\r\n TEXTOUT(\" if HOME is not set.\");\r\n TEXTOUT(\"--Ssh_IgnoreSecurity\");\r\n TEXTOUT(\" Does not verify the authenticity of the peer\");\r\n TEXTOUT(\" (you don't need to accept the key with ssh first)\");\r\n TEXTOUT(\" Use it at your own risks\");\r\n\r\n return MI_OK;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nint Help_Nothing()\r\n{\r\n STRINGOUT(String(__T(\"Usage: \\\" [-Options...] FileName1 [Filename2...]\\\"\")).insert(8, Program_Name));\r\n STRINGOUT(String(__T(\"\\\" --Help\\\" for displaying more information\")).insert(1, Program_Name));\r\n\r\n return MI_OK;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nint Help_Output()\r\n{\r\n TEXTOUT(\"--Output=... Specify a template (BETA)\");\r\n STRINGOUT(String(__T(\"Usage: \\\" --Output=[xxx;]Text FileName\\\"\")).insert(8, Program_Name));\r\n TEXTOUT(\"\");\r\n TEXTOUT(\"xxx can be: General, Video, Audio, Text, Chapter, Image, Menu\");\r\n TEXTOUT(\"Text can be the template text, or a filename\");\r\n TEXTOUT(\" Filename must be in the form file:\/\/filename\");\r\n TEXTOUT(\"\");\r\n TEXTOUT(\"See --Info-Parameters for available parameters in the text\");\r\n TEXTOUT(\"(Parameters must be surrounded by \\\"%\\\" sign)\");\r\n TEXTOUT(\"\");\r\n STRINGOUT(String(__T(\"Usage: \\\" --Output=Video;%AspectRatio% FileName\\\"\")).insert(8, Program_Name));\r\n TEXTOUT(\"\");\r\n STRINGOUT(String(__T(\"Usage: \\\" --Output=Video;file:\/\/Video.txt FileName\\\"\")).insert(8, Program_Name));\r\n TEXTOUT(\"and Video.txt contains \");\r\n TEXTOUT(\"\\\"%DisplayAspectRatio%\\\" for Video Aspect Ratio.\");\r\n TEXTOUT(\"\");\r\n STRINGOUT(String(__T(\"Usage: \\\" --Output=file:\/\/Text.txt FileName\\\"\")).insert(8, Program_Name));\r\n TEXTOUT(\"and Text.txt contains\");\r\n TEXTOUT(\"\\\"Video;%DisplayAspectRatio%\\\" for Video Aspect Ratio.\");\r\n TEXTOUT(\"\\\"Audio;%Format%\\\" for Audio Format.\");\r\n\r\n return MI_ERROR;\r\n}\r\n\r\n\r\n\/\/---------------------------------------------------------------------------\r\nint Usage()\r\n{\r\n Help_Nothing();\r\n return MI_ERROR;\r\n}\r\n<|endoftext|>"} {"text":"\n#include \"simulation.h\"\n\nSimulatedRobotArm::SimulatedRobotArm() {\n\n arm_data.state = UNKNOWN;\n\n arm_info.version = 0.1;\n arm_info.name = string(\"Simulated Robot Arm\");\n\n joint_info.push_back(createJointInfo(0, ROTATION, 0, 90, 65, 0, -180, 180));\n joint_data.push_back(createJointData(0, 0));\n\n joint_info.push_back(createJointInfo(1, ROTATION, 120, 0, 0, 90, 0, 170));\n joint_data.push_back(createJointData(1, 120));\n\n joint_info.push_back(createJointInfo(2, ROTATION, -90, 0, 0, 132, -110, 110));\n joint_data.push_back(createJointData(2, -90));\n\n joint_info.push_back(createJointInfo(3, ROTATION, 0, 0, 0, 70, -70, 70));\n joint_data.push_back(createJointData(3, -70));\n\n joint_info.push_back(createJointInfo(4, GRIPPER, 0, -90, 0, 60, 0, 1));\n joint_data.push_back(createJointData(4, 0));\n\n arm_info.joints = joint_info.size();\n}\n\nSimulatedRobotArm::~SimulatedRobotArm() {\n\n\n}\n\nbool SimulatedRobotArm::isConnected() {\n\n return arm_data.state == CONNECTED;\n\n}\n\nint SimulatedRobotArm::connect() {\n\n arm_data.state = CONNECTED;\n\n\treturn 0;\n\n}\n\nint SimulatedRobotArm::disconnect() {\n\n arm_data.state = UNKNOWN;\n\n\treturn 0;\n\n}\n\n#define MOVE_RESOLUTION_GRIP 0.1\n#define MOVE_RESOLUTION_TRANSLATION 1\n#define MOVE_RESOLUTION_ROTATION 5\n\nint SimulatedRobotArm::poll() {\n\n for (int i = 0; i < joint_data.size(); i++) {\n float resolution = joint_info[i].type == ROTATION ? \n MOVE_RESOLUTION_ROTATION : (joint_info[i].type == TRANSLATION ? MOVE_RESOLUTION_TRANSLATION : MOVE_RESOLUTION_GRIP);\n\n if (joint_data[i].position - joint_data[i].position_goal >= resolution \/ 2)\n joint_data[i].position -= resolution;\n else if (joint_data[i].position - joint_data[i].position_goal < -resolution \/ 2)\n joint_data[i].position += resolution;\n else\n joint_data[i].position = joint_data[i].position_goal; \n }\n\n return 0;\n}\n\nint SimulatedRobotArm::calibrate(int joint) {\n return 0;\n}\n\nint SimulatedRobotArm::startControl() {\n return 0;\n}\n\nint SimulatedRobotArm::stopControl() {\n\treturn 0;\n}\n\nint SimulatedRobotArm::lock(int joint) {\n return 0;\n}\n\nint SimulatedRobotArm::release(int joint) {\n\treturn 0;\n}\n\nint SimulatedRobotArm::rest() {\n\treturn 0;\n}\n\nint SimulatedRobotArm::size() {\n\n return joint_data.size();\n\n}\n\nint SimulatedRobotArm::moveTo(int joint, float speed, float position) {\n\n if (joint < 0 || joint >= joint_data.size())\n return false;\n\n if (joint_info[joint].position_min > position)\n position = joint_info[joint].position_min;\n\n if (joint_info[joint].position_max < position)\n position = joint_info[joint].position_max;\n\n joint_data[joint].position_goal = position;\n\n\treturn 0;\n}\n\nint SimulatedRobotArm::move(int joint, float speed) {\n\n if (joint < 0 || joint >= joint_data.size())\n return false;\n\n float position = joint_data[joint].position_goal;\n\n if (speed < 0)\n position = joint_info[joint].position_min;\n\n if (speed > 0)\n position = joint_info[joint].position_max;\n\n joint_data[joint].position_goal = position;\n\n\treturn 0;\n}\n\nint SimulatedRobotArm::getArmInfo(ArmInfo &data) {\n\n data = arm_info;\n\n return 0;\n\n}\n\nint SimulatedRobotArm::getArmData(ArmData &data) {\n\n data = arm_data;\n\n\treturn 0;\n}\n\nint SimulatedRobotArm::getJointInfo(int joint, JointInfo &data) {\n\n if (joint < 0 || joint >= joint_info.size())\n return -1;\n\n data = joint_info[joint];\n\n\treturn 0;\n}\n\nint SimulatedRobotArm::getJointData(int joint, JointData &data) {\n\n if (joint < 0 || joint >= joint_data.size())\n return -1;\n\n data = joint_data[joint];\n\n\treturn true;\n}\n\n\nFixing simulated arm movement.\n#include \"simulation.h\"\n\nSimulatedRobotArm::SimulatedRobotArm() {\n\n arm_data.state = UNKNOWN;\n\n arm_info.version = 0.1;\n arm_info.name = string(\"Simulated Robot Arm\");\n\n joint_info.push_back(createJointInfo(0, ROTATION, 0, 90, 65, 0, -180, 180));\n joint_data.push_back(createJointData(0, 0));\n\n joint_info.push_back(createJointInfo(1, ROTATION, 120, 0, 0, 90, 0, 170));\n joint_data.push_back(createJointData(1, 120));\n\n joint_info.push_back(createJointInfo(2, ROTATION, -90, 0, 0, 132, -110, 110));\n joint_data.push_back(createJointData(2, -90));\n\n joint_info.push_back(createJointInfo(3, ROTATION, 0, 0, 0, 70, -70, 70));\n joint_data.push_back(createJointData(3, -70));\n\n joint_info.push_back(createJointInfo(4, GRIPPER, 0, -90, 0, 60, 0, 1));\n joint_data.push_back(createJointData(4, 0));\n\n arm_info.joints = joint_info.size();\n}\n\nSimulatedRobotArm::~SimulatedRobotArm() {\n\n\n}\n\nbool SimulatedRobotArm::isConnected() {\n\n return arm_data.state == CONNECTED;\n\n}\n\nint SimulatedRobotArm::connect() {\n\n arm_data.state = CONNECTED;\n\n\treturn 0;\n\n}\n\nint SimulatedRobotArm::disconnect() {\n\n arm_data.state = UNKNOWN;\n\n\treturn 0;\n\n}\n\n#define MOVE_RESOLUTION_GRIP 0.001\n#define MOVE_RESOLUTION_TRANSLATION 1\n#define MOVE_RESOLUTION_ROTATION 5\n\nint SimulatedRobotArm::poll() {\n\n for (int i = 0; i < joint_data.size(); i++) {\n float resolution = joint_info[i].type == ROTATION ? \n MOVE_RESOLUTION_ROTATION : (joint_info[i].type == TRANSLATION ? MOVE_RESOLUTION_TRANSLATION : MOVE_RESOLUTION_GRIP);\n\n if (joint_data[i].position - joint_data[i].position_goal >= resolution \/ 2)\n joint_data[i].position -= resolution;\n else if (joint_data[i].position - joint_data[i].position_goal < -resolution \/ 2)\n joint_data[i].position += resolution;\n else\n joint_data[i].position = joint_data[i].position_goal; \n \n }\n\n return 0;\n}\n\nint SimulatedRobotArm::calibrate(int joint) {\n return 0;\n}\n\nint SimulatedRobotArm::startControl() {\n return 0;\n}\n\nint SimulatedRobotArm::stopControl() {\n\treturn 0;\n}\n\nint SimulatedRobotArm::lock(int joint) {\n return 0;\n}\n\nint SimulatedRobotArm::release(int joint) {\n\treturn 0;\n}\n\nint SimulatedRobotArm::rest() {\n\treturn 0;\n}\n\nint SimulatedRobotArm::size() {\n\n return joint_data.size();\n\n}\n\nint SimulatedRobotArm::moveTo(int joint, float speed, float position) {\n\n if (joint < 0 || joint >= joint_data.size())\n return -1;\n\n if (joint_info[joint].position_min > position)\n position = joint_info[joint].position_min;\n\n if (joint_info[joint].position_max < position)\n position = joint_info[joint].position_max;\n\n joint_data[joint].position_goal = position;\n\n\treturn 0;\n}\n\nint SimulatedRobotArm::move(int joint, float speed) {\n\n if (joint < 0 || joint >= joint_data.size())\n return -1;\n\n float position = joint_data[joint].position_goal;\n\n if (speed < 0)\n position = joint_info[joint].position_min;\n\n if (speed > 0)\n position = joint_info[joint].position_max;\n\n joint_data[joint].position_goal = position;\n\n\treturn 0;\n}\n\nint SimulatedRobotArm::getArmInfo(ArmInfo &data) {\n\n data = arm_info;\n\n return 0;\n\n}\n\nint SimulatedRobotArm::getArmData(ArmData &data) {\n\n data = arm_data;\n\n\treturn 0;\n}\n\nint SimulatedRobotArm::getJointInfo(int joint, JointInfo &data) {\n\n if (joint < 0 || joint >= joint_info.size())\n return -1;\n\n data = joint_info[joint];\n\n\treturn 0;\n}\n\nint SimulatedRobotArm::getJointData(int joint, JointData &data) {\n\n if (joint < 0 || joint >= joint_data.size())\n return -1;\n\n data = joint_data[joint];\n\n data.dh_position = (((data.position - joint_info[joint].position_min) \/ (joint_info[joint].position_max - joint_info[joint].position_min)) * (joint_info[joint].dh_max - joint_info[joint].dh_min)) + joint_info[joint].dh_min;\n data.dh_goal = (((data.position_goal - joint_info[joint].position_min) \/ (joint_info[joint].position_max - joint_info[joint].position_min)) * (joint_info[joint].dh_max - joint_info[joint].dh_min)) + joint_info[joint].dh_min;\n\n\treturn true;\n}\n\n\n<|endoftext|>"} {"text":"24 TGraphs CFD vs timestamp added<|endoftext|>"} {"text":"\/*\nCopyright 2016 Fixstars Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp :\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \n\n#include \n\n#include \"internal.h\"\n#include \"device_buffer.hpp\"\n#include \"sgm.hpp\"\n\nnamespace sgm {\n\tstatic bool is_cuda_input(EXECUTE_INOUT type) { return (type & 0x1) > 0; }\n\tstatic bool is_cuda_output(EXECUTE_INOUT type) { return (type & 0x2) > 0; }\n\n\tclass SemiGlobalMatchingBase {\n\tpublic:\n\t\tusing output_type = sgm::output_type;\n\t\tvirtual void execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R, \n\t\t\tint w, int h, int sp, int dp, StereoSGM::Parameters& param) = 0;\n\n\t\tvirtual ~SemiGlobalMatchingBase() {}\n\t};\n\n\ttemplate \n\tclass SemiGlobalMatchingImpl : public SemiGlobalMatchingBase {\n\tpublic:\n\t\tvoid execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,\n\t\t\tint w, int h, int sp, int dp, StereoSGM::Parameters& param) override\n\t\t{\n\t\t\tsgm_engine_.execute(dst_L, dst_R, (const input_type*)src_L, (const input_type*)src_R, w, h, sp, dp, param);\n\t\t}\n\tprivate:\n\t\tSemiGlobalMatching sgm_engine_;\n\t};\n\n\tstruct CudaStereoSGMResources {\n\t\tDeviceBuffer d_src_left;\n\t\tDeviceBuffer d_src_right;\n\t\tDeviceBuffer d_left_disp;\n\t\tDeviceBuffer d_right_disp;\n\t\tDeviceBuffer d_tmp_left_disp;\n\t\tDeviceBuffer d_tmp_right_disp;\n\n\t\tSemiGlobalMatchingBase* sgm_engine;\n\n\t\tCudaStereoSGMResources(int width_, int height_, int disparity_size_, int input_depth_bits_, int output_depth_bits_, int src_pitch_, int dst_pitch_, EXECUTE_INOUT inout_type_) {\n\n\t\t\tif (input_depth_bits_ == 8 && disparity_size_ == 64)\n\t\t\t\tsgm_engine = new SemiGlobalMatchingImpl();\n\t\t\telse if (input_depth_bits_ == 8 && disparity_size_ == 128)\n\t\t\t\tsgm_engine = new SemiGlobalMatchingImpl();\n\t\t\telse if (input_depth_bits_ == 8 && disparity_size_ == 256)\n\t\t\t\tsgm_engine = new SemiGlobalMatchingImpl();\n\t\t\telse if (input_depth_bits_ == 16 && disparity_size_ == 64)\n\t\t\t\tsgm_engine = new SemiGlobalMatchingImpl();\n\t\t\telse if (input_depth_bits_ == 16 && disparity_size_ == 128)\n\t\t\t\tsgm_engine = new SemiGlobalMatchingImpl();\n\t\t\telse if (input_depth_bits_ == 16 && disparity_size_ == 256)\n\t\t\t\tsgm_engine = new SemiGlobalMatchingImpl();\n\t\t\telse\n\t\t\t\tthrow std::logic_error(\"depth bits must be 8 or 16, and disparity size must be 64 or 128\");\n\n\t\t\tif (!is_cuda_input(inout_type_)) {\n\t\t\t\tthis->d_src_left.allocate(input_depth_bits_ \/ 8 * src_pitch_ * height_);\n\t\t\t\tthis->d_src_right.allocate(input_depth_bits_ \/ 8 * src_pitch_ * height_);\n\t\t\t}\n\t\t\t\n\t\t\tthis->d_left_disp.allocate(dst_pitch_ * height_);\n\t\t\tthis->d_right_disp.allocate(dst_pitch_ * height_);\n\n\t\t\tthis->d_tmp_left_disp.allocate(dst_pitch_ * height_);\n\t\t\tthis->d_tmp_right_disp.allocate(dst_pitch_ * height_);\n\n\t\t\tthis->d_left_disp.fillZero();\n\t\t\tthis->d_right_disp.fillZero();\n\t\t\tthis->d_tmp_left_disp.fillZero();\n\t\t\tthis->d_tmp_right_disp.fillZero();\n\t\t}\n\n\t\t~CudaStereoSGMResources() {\n\t\t\tdelete sgm_engine;\n\t\t}\n\t};\n\n\tStereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits,\n\t\tEXECUTE_INOUT inout_type, const Parameters& param) : StereoSGM(width, height, disparity_size, input_depth_bits, output_depth_bits, width, width, inout_type, param) {}\n\n\tStereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits, int src_pitch, int dst_pitch,\n\t\tEXECUTE_INOUT inout_type, const Parameters& param) :\n\t\tcu_res_(NULL),\n\t\twidth_(width),\n\t\theight_(height),\n\t\tdisparity_size_(disparity_size),\n\t\tinput_depth_bits_(input_depth_bits),\n\t\toutput_depth_bits_(output_depth_bits),\n\t\tsrc_pitch_(src_pitch),\n\t\tdst_pitch_(dst_pitch),\n\t\tinout_type_(inout_type),\n\t\tparam_(param)\n\t{\n\t\t\/\/ check values\n\t\tif (input_depth_bits_ != 8 && input_depth_bits_ != 16 && output_depth_bits_ != 8 && output_depth_bits_ != 16) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::logic_error(\"depth bits must be 8 or 16\");\n\t\t}\n\t\tif (disparity_size_ != 64 && disparity_size_ != 128 && disparity_size != 256) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::logic_error(\"disparity size must be 64, 128 or 256\");\n\t\t}\n\t\t{\n\t\t\t\/\/ simulate minimum\/maximum value\n\t\t\tstd::int64_t max = static_cast(disparity_size) + param.min_disp - 1;\n\t\t\tif (param.subpixel) {\n\t\t\t\tmax *= SUBPIXEL_SCALE;\n\t\t\t\tmax += SUBPIXEL_SCALE - 1;\n\t\t\t}\n\t\t\tbool enough = max < 1 << output_depth_bits;\n\t\t\tif (param.min_disp <= 0) {\n\t\t\t\t\/\/ whether or not output can be represented by signed\n\t\t\t\tstd::int64_t min = static_cast(param.min_disp) - 1;\n\t\t\t\tif (param.subpixel) {\n\t\t\t\t\tmin *= SUBPIXEL_SCALE;\n\t\t\t\t}\n\t\t\t\tenough = enough\n\t\t\t\t\t\t&& -(1 << (output_depth_bits - 1)) <= min\n\t\t\t\t\t\t&& max < 1 << (output_depth_bits - 1);\n\t\t\t}\n\t\t\tif (!enough) {\n\t\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\t\tthrow std::logic_error(\"output depth bits must be sufficient for representing output value\");\n\t\t\t}\n\t\t}\n\t\tif (param_.path_type != PathType::SCAN_4PATH && param_.path_type != PathType::SCAN_8PATH) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::logic_error(\"Path type must be PathType::SCAN_4PATH or PathType::SCAN_8PATH\");\n\t\t}\n\n\t\tcu_res_ = new CudaStereoSGMResources(width_, height_, disparity_size_, input_depth_bits_, output_depth_bits_, src_pitch, dst_pitch, inout_type_);\n\t}\n\n\tStereoSGM::~StereoSGM() {\n\t\tif (cu_res_) { delete cu_res_; }\n\t}\n\n\t\n\tvoid StereoSGM::execute(const void* left_pixels, const void* right_pixels, void* dst) {\n\n\t\tconst void *d_input_left, *d_input_right;\n\n\t\tif (is_cuda_input(inout_type_)) {\n\t\t\td_input_left = left_pixels;\n\t\t\td_input_right = right_pixels;\n\t\t}\n\t\telse {\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->d_src_left.data(), left_pixels, cu_res_->d_src_left.size(), cudaMemcpyHostToDevice));\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->d_src_right.data(), right_pixels, cu_res_->d_src_right.size(), cudaMemcpyHostToDevice));\n\t\t\td_input_left = cu_res_->d_src_left.data();\n\t\t\td_input_right = cu_res_->d_src_right.data();\n\t\t}\n\n\t\tvoid* d_tmp_left_disp = cu_res_->d_tmp_left_disp.data();\n\t\tvoid* d_tmp_right_disp = cu_res_->d_tmp_right_disp.data();\n\t\tvoid* d_left_disp = cu_res_->d_left_disp.data();\n\t\tvoid* d_right_disp = cu_res_->d_right_disp.data();\n\n\t\tif (is_cuda_output(inout_type_) && output_depth_bits_ == 16)\n\t\t\td_left_disp = dst; \/\/ when threre is no device-host copy or type conversion, use passed buffer\n\t\t\n\t\tcu_res_->sgm_engine->execute((uint16_t*)d_tmp_left_disp, (uint16_t*)d_tmp_right_disp,\n\t\t\td_input_left, d_input_right, width_, height_, src_pitch_, dst_pitch_, param_);\n\n\t\tsgm::details::median_filter((uint16_t*)d_tmp_left_disp, (uint16_t*)d_left_disp, width_, height_, dst_pitch_);\n\t\tsgm::details::median_filter((uint16_t*)d_tmp_right_disp, (uint16_t*)d_right_disp, width_, height_, dst_pitch_);\n\t\tsgm::details::check_consistency((uint16_t*)d_left_disp, (uint16_t*)d_right_disp, d_input_left, width_, height_, input_depth_bits_, src_pitch_, dst_pitch_, param_.subpixel, param_.min_disp);\n\n\t\tif (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\tsgm::details::cast_16bit_8bit_array((const uint16_t*)d_left_disp, (uint8_t*)d_tmp_left_disp, dst_pitch_ * height_);\n\t\t\tCudaSafeCall(cudaMemcpy(dst, d_tmp_left_disp, sizeof(uint8_t) * dst_pitch_ * height_, cudaMemcpyDeviceToHost));\n\t\t}\n\t\telse if (is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\tsgm::details::cast_16bit_8bit_array((const uint16_t*)d_left_disp, (uint8_t*)dst, dst_pitch_ * height_);\n\t\t}\n\t\telse if (!is_cuda_output(inout_type_) && output_depth_bits_ == 16) {\n\t\t\tCudaSafeCall(cudaMemcpy(dst, d_left_disp, sizeof(uint16_t) * dst_pitch_ * height_, cudaMemcpyDeviceToHost));\n\t\t}\n\t\telse if (is_cuda_output(inout_type_) && output_depth_bits_ == 16) {\n\t\t\t\/\/ optimize! no-copy!\n\t\t}\n\t\telse {\n\t\t\tstd::cerr << \"not impl\" << std::endl;\n\t\t}\n\t}\n}\nAvoid warnings\/*\nCopyright 2016 Fixstars Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp :\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \n\n#include \n\n#include \"internal.h\"\n#include \"device_buffer.hpp\"\n#include \"sgm.hpp\"\n\nnamespace sgm {\n\tstatic bool is_cuda_input(EXECUTE_INOUT type) { return (type & 0x1) > 0; }\n\tstatic bool is_cuda_output(EXECUTE_INOUT type) { return (type & 0x2) > 0; }\n\n\tclass SemiGlobalMatchingBase {\n\tpublic:\n\t\tusing output_type = sgm::output_type;\n\t\tvirtual void execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R, \n\t\t\tint w, int h, int sp, int dp, StereoSGM::Parameters& param) = 0;\n\n\t\tvirtual ~SemiGlobalMatchingBase() {}\n\t};\n\n\ttemplate \n\tclass SemiGlobalMatchingImpl : public SemiGlobalMatchingBase {\n\tpublic:\n\t\tvoid execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,\n\t\t\tint w, int h, int sp, int dp, StereoSGM::Parameters& param) override\n\t\t{\n\t\t\tsgm_engine_.execute(dst_L, dst_R, (const input_type*)src_L, (const input_type*)src_R, w, h, sp, dp, param);\n\t\t}\n\tprivate:\n\t\tSemiGlobalMatching sgm_engine_;\n\t};\n\n\tstruct CudaStereoSGMResources {\n\t\tDeviceBuffer d_src_left;\n\t\tDeviceBuffer d_src_right;\n\t\tDeviceBuffer d_left_disp;\n\t\tDeviceBuffer d_right_disp;\n\t\tDeviceBuffer d_tmp_left_disp;\n\t\tDeviceBuffer d_tmp_right_disp;\n\n\t\tSemiGlobalMatchingBase* sgm_engine;\n\n\t\tCudaStereoSGMResources(int width_, int height_, int disparity_size_, int input_depth_bits_, int output_depth_bits_, int src_pitch_, int dst_pitch_, EXECUTE_INOUT inout_type_) {\n\n\t\t\tif (input_depth_bits_ == 8 && disparity_size_ == 64)\n\t\t\t\tsgm_engine = new SemiGlobalMatchingImpl();\n\t\t\telse if (input_depth_bits_ == 8 && disparity_size_ == 128)\n\t\t\t\tsgm_engine = new SemiGlobalMatchingImpl();\n\t\t\telse if (input_depth_bits_ == 8 && disparity_size_ == 256)\n\t\t\t\tsgm_engine = new SemiGlobalMatchingImpl();\n\t\t\telse if (input_depth_bits_ == 16 && disparity_size_ == 64)\n\t\t\t\tsgm_engine = new SemiGlobalMatchingImpl();\n\t\t\telse if (input_depth_bits_ == 16 && disparity_size_ == 128)\n\t\t\t\tsgm_engine = new SemiGlobalMatchingImpl();\n\t\t\telse if (input_depth_bits_ == 16 && disparity_size_ == 256)\n\t\t\t\tsgm_engine = new SemiGlobalMatchingImpl();\n\t\t\telse\n\t\t\t\tthrow std::logic_error(\"depth bits must be 8 or 16, and disparity size must be 64 or 128\");\n\n\t\t\tif (!is_cuda_input(inout_type_)) {\n\t\t\t\tthis->d_src_left.allocate(input_depth_bits_ \/ 8 * src_pitch_ * height_);\n\t\t\t\tthis->d_src_right.allocate(input_depth_bits_ \/ 8 * src_pitch_ * height_);\n\t\t\t}\n\t\t\t\n\t\t\tthis->d_left_disp.allocate(dst_pitch_ * height_);\n\t\t\tthis->d_right_disp.allocate(dst_pitch_ * height_);\n\n\t\t\tthis->d_tmp_left_disp.allocate(dst_pitch_ * height_);\n\t\t\tthis->d_tmp_right_disp.allocate(dst_pitch_ * height_);\n\n\t\t\tthis->d_left_disp.fillZero();\n\t\t\tthis->d_right_disp.fillZero();\n\t\t\tthis->d_tmp_left_disp.fillZero();\n\t\t\tthis->d_tmp_right_disp.fillZero();\n\t\t}\n\n\t\t~CudaStereoSGMResources() {\n\t\t\tdelete sgm_engine;\n\t\t}\n\t};\n\n\tStereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits,\n\t\tEXECUTE_INOUT inout_type, const Parameters& param) : StereoSGM(width, height, disparity_size, input_depth_bits, output_depth_bits, width, width, inout_type, param) {}\n\n\tStereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits, int src_pitch, int dst_pitch,\n\t\tEXECUTE_INOUT inout_type, const Parameters& param) :\n\t\tcu_res_(NULL),\n\t\twidth_(width),\n\t\theight_(height),\n\t\tdisparity_size_(disparity_size),\n\t\tinput_depth_bits_(input_depth_bits),\n\t\toutput_depth_bits_(output_depth_bits),\n\t\tsrc_pitch_(src_pitch),\n\t\tdst_pitch_(dst_pitch),\n\t\tinout_type_(inout_type),\n\t\tparam_(param)\n\t{\n\t\t\/\/ check values\n\t\tif (input_depth_bits_ != 8 && input_depth_bits_ != 16 && output_depth_bits_ != 8 && output_depth_bits_ != 16) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::logic_error(\"depth bits must be 8 or 16\");\n\t\t}\n\t\tif (disparity_size_ != 64 && disparity_size_ != 128 && disparity_size != 256) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::logic_error(\"disparity size must be 64, 128 or 256\");\n\t\t}\n\t\t{\n\t\t\t\/\/ simulate minimum\/maximum value\n\t\t\tstd::int64_t max = static_cast(disparity_size) + param.min_disp - 1;\n\t\t\tif (param.subpixel) {\n\t\t\t\tmax *= SUBPIXEL_SCALE;\n\t\t\t\tmax += SUBPIXEL_SCALE - 1;\n\t\t\t}\n\t\t\tbool enough = max < 1ll << output_depth_bits;\n\t\t\tif (param.min_disp <= 0) {\n\t\t\t\t\/\/ whether or not output can be represented by signed\n\t\t\t\tstd::int64_t min = static_cast(param.min_disp) - 1;\n\t\t\t\tif (param.subpixel) {\n\t\t\t\t\tmin *= SUBPIXEL_SCALE;\n\t\t\t\t}\n\t\t\t\tenough = enough\n\t\t\t\t\t\t&& -(1ll << (output_depth_bits - 1)) <= min\n\t\t\t\t\t\t&& max < 1ll << (output_depth_bits - 1);\n\t\t\t}\n\t\t\tif (!enough) {\n\t\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\t\tthrow std::logic_error(\"output depth bits must be sufficient for representing output value\");\n\t\t\t}\n\t\t}\n\t\tif (param_.path_type != PathType::SCAN_4PATH && param_.path_type != PathType::SCAN_8PATH) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::logic_error(\"Path type must be PathType::SCAN_4PATH or PathType::SCAN_8PATH\");\n\t\t}\n\n\t\tcu_res_ = new CudaStereoSGMResources(width_, height_, disparity_size_, input_depth_bits_, output_depth_bits_, src_pitch, dst_pitch, inout_type_);\n\t}\n\n\tStereoSGM::~StereoSGM() {\n\t\tif (cu_res_) { delete cu_res_; }\n\t}\n\n\t\n\tvoid StereoSGM::execute(const void* left_pixels, const void* right_pixels, void* dst) {\n\n\t\tconst void *d_input_left, *d_input_right;\n\n\t\tif (is_cuda_input(inout_type_)) {\n\t\t\td_input_left = left_pixels;\n\t\t\td_input_right = right_pixels;\n\t\t}\n\t\telse {\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->d_src_left.data(), left_pixels, cu_res_->d_src_left.size(), cudaMemcpyHostToDevice));\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->d_src_right.data(), right_pixels, cu_res_->d_src_right.size(), cudaMemcpyHostToDevice));\n\t\t\td_input_left = cu_res_->d_src_left.data();\n\t\t\td_input_right = cu_res_->d_src_right.data();\n\t\t}\n\n\t\tvoid* d_tmp_left_disp = cu_res_->d_tmp_left_disp.data();\n\t\tvoid* d_tmp_right_disp = cu_res_->d_tmp_right_disp.data();\n\t\tvoid* d_left_disp = cu_res_->d_left_disp.data();\n\t\tvoid* d_right_disp = cu_res_->d_right_disp.data();\n\n\t\tif (is_cuda_output(inout_type_) && output_depth_bits_ == 16)\n\t\t\td_left_disp = dst; \/\/ when threre is no device-host copy or type conversion, use passed buffer\n\t\t\n\t\tcu_res_->sgm_engine->execute((uint16_t*)d_tmp_left_disp, (uint16_t*)d_tmp_right_disp,\n\t\t\td_input_left, d_input_right, width_, height_, src_pitch_, dst_pitch_, param_);\n\n\t\tsgm::details::median_filter((uint16_t*)d_tmp_left_disp, (uint16_t*)d_left_disp, width_, height_, dst_pitch_);\n\t\tsgm::details::median_filter((uint16_t*)d_tmp_right_disp, (uint16_t*)d_right_disp, width_, height_, dst_pitch_);\n\t\tsgm::details::check_consistency((uint16_t*)d_left_disp, (uint16_t*)d_right_disp, d_input_left, width_, height_, input_depth_bits_, src_pitch_, dst_pitch_, param_.subpixel, param_.min_disp);\n\n\t\tif (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\tsgm::details::cast_16bit_8bit_array((const uint16_t*)d_left_disp, (uint8_t*)d_tmp_left_disp, dst_pitch_ * height_);\n\t\t\tCudaSafeCall(cudaMemcpy(dst, d_tmp_left_disp, sizeof(uint8_t) * dst_pitch_ * height_, cudaMemcpyDeviceToHost));\n\t\t}\n\t\telse if (is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\tsgm::details::cast_16bit_8bit_array((const uint16_t*)d_left_disp, (uint8_t*)dst, dst_pitch_ * height_);\n\t\t}\n\t\telse if (!is_cuda_output(inout_type_) && output_depth_bits_ == 16) {\n\t\t\tCudaSafeCall(cudaMemcpy(dst, d_left_disp, sizeof(uint16_t) * dst_pitch_ * height_, cudaMemcpyDeviceToHost));\n\t\t}\n\t\telse if (is_cuda_output(inout_type_) && output_depth_bits_ == 16) {\n\t\t\t\/\/ optimize! no-copy!\n\t\t}\n\t\telse {\n\t\t\tstd::cerr << \"not impl\" << std::endl;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"#include \"html.h\"\r\n#include \"stylesheet.h\"\r\n#include \r\n#include \"document.h\"\r\n\r\n\r\nvoid litehtml::css::parse_stylesheet( const tchar_t* str, const tchar_t* baseurl, document* doc, media_query_list::ptr& media )\r\n{\r\n\ttstring text = str;\r\n\r\n\t\/\/ remove comments\r\n\ttstring::size_type c_start = text.find(_t(\"\/*\"));\r\n\twhile(c_start != tstring::npos)\r\n\t{\r\n\t\ttstring::size_type c_end = text.find(_t(\"*\/\"), c_start + 2);\r\n\t\ttext.erase(c_start, c_end - c_start + 2);\r\n\t\tc_start = text.find(_t(\"\/*\"));\r\n\t}\r\n\r\n\ttstring::size_type pos = text.find_first_not_of(_t(\" \\n\\r\\t\"));\r\n\twhile(pos != tstring::npos)\r\n\t{\r\n\t\twhile(pos != tstring::npos && text[pos] == _t('@'))\r\n\t\t{\r\n\t\t\ttstring::size_type sPos = pos;\r\n\t\t\tpos = text.find_first_of(_t(\"{\"), pos);\r\n\t\t\tif(pos != tstring::npos && text[pos] == _t('{'))\r\n\t\t\t{\r\n\t\t\t\tpos = find_close_bracket(text, pos, _t('{'), _t('}'));\r\n\t\t\t}\r\n\t\t\tif(pos != tstring::npos)\r\n\t\t\t{\r\n\t\t\t\tparse_atrule(text.substr(sPos, pos - sPos + 1), baseurl, doc, media);\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tparse_atrule(text.substr(sPos), baseurl, doc, media);\r\n\t\t\t}\r\n\r\n\t\t\tif(pos != tstring::npos)\r\n\t\t\t{\r\n\t\t\t\tpos = text.find_first_not_of(_t(\" \\n\\r\\t\"), pos + 1);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(pos == tstring::npos)\r\n\t\t{\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\ttstring::size_type style_start = text.find(_t(\"{\"), pos);\r\n\t\ttstring::size_type style_end\t= text.find(_t(\"}\"), pos);\r\n\t\tif(style_start != tstring::npos && style_end != tstring::npos)\r\n\t\t{\r\n\t\t\tstyle::ptr st = new style;\r\n\t\t\tst->add(text.substr(style_start + 1, style_end - style_start - 1).c_str(), baseurl);\r\n\r\n\t\t\tparse_selectors(text.substr(pos, style_start - pos), st, media);\r\n\r\n\t\t\tif(media && doc)\r\n\t\t\t{\r\n\t\t\t\tdoc->add_media_list(media);\r\n\t\t\t}\r\n\r\n\t\t\tpos = style_end + 1;\r\n\t\t} else\r\n\t\t{\r\n\t\t\tpos = tstring::npos;\r\n\t\t}\r\n\r\n\t\tif(pos != tstring::npos)\r\n\t\t{\r\n\t\t\tpos = text.find_first_not_of(_t(\" \\n\\r\\t\"), pos);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid litehtml::css::parse_css_url( const tstring& str, tstring& url )\r\n{\r\n\turl = _t(\"\");\r\n\tsize_t pos1 = str.find(_t('('));\r\n\tsize_t pos2 = str.find(_t(')'));\r\n\tif(pos1 != tstring::npos && pos2 != tstring::npos)\r\n\t{\r\n\t\turl = str.substr(pos1 + 1, pos2 - pos1 - 1);\r\n\t\tif(url.length())\r\n\t\t{\r\n\t\t\tif(url[0] == _t('\\'') || url[0] == _t('\"'))\r\n\t\t\t{\r\n\t\t\t\turl.erase(0, 1);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(url.length())\r\n\t\t{\r\n\t\t\tif(url[url.length() - 1] == _t('\\'') || url[url.length() - 1] == _t('\"'))\r\n\t\t\t{\r\n\t\t\t\turl.erase(url.length() - 1, 1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nbool litehtml::css::parse_selectors( const tstring& txt, litehtml::style::ptr styles, media_query_list::ptr& media )\r\n{\r\n\ttstring selector = txt;\r\n\ttrim(selector);\r\n\tstring_vector tokens;\r\n\tsplit_string(selector, tokens, _t(\",\"));\r\n\r\n\tbool added_something = false;\r\n\r\n\tfor(string_vector::iterator tok = tokens.begin(); tok != tokens.end(); tok++)\r\n\t{\r\n\t\tcss_selector::ptr selector = new css_selector(media);\r\n\t\tselector->m_style = styles;\r\n\t\ttrim(*tok);\r\n\t\tif(selector->parse(*tok))\r\n\t\t{\r\n\t\t\tselector->calc_specificity();\r\n\t\t\tadd_selector(selector);\r\n\t\t\tadded_something = true;\r\n\t\t}\r\n\t}\r\n\r\n\treturn added_something;\r\n}\r\n\r\nvoid litehtml::css::sort_selectors()\r\n{\r\n\tsort(m_selectors.begin(), m_selectors.end(), std::less( ));\r\n}\r\n\r\nvoid litehtml::css::parse_atrule( const tstring& text, const tchar_t* baseurl, document* doc, media_query_list::ptr& media )\r\n{\r\n\tif(text.substr(0, 7) == _t(\"@import\"))\r\n\t{\r\n\t\tint sPos = 7;\r\n\t\ttstring iStr;\r\n\t\tiStr = text.substr(sPos);\r\n\t\tif(iStr[iStr.length() - 1] == _t(';'))\r\n\t\t{\r\n\t\t\tiStr.erase(iStr.length() - 1);\r\n\t\t}\r\n\t\ttrim(iStr);\r\n\t\tstring_vector tokens;\r\n\t\tsplit_string(iStr, tokens, _t(\" \"), _t(\"\"), _t(\"(\\\"\"));\r\n\t\tif(!tokens.empty())\r\n\t\t{\r\n\t\t\ttstring url;\r\n\t\t\tparse_css_url(tokens.front(), url);\r\n\t\t\tif(url.empty())\r\n\t\t\t{\r\n\t\t\t\turl = tokens.front();\r\n\t\t\t}\r\n\t\t\ttokens.erase(tokens.begin());\r\n\t\t\tif(doc)\r\n\t\t\t{\r\n\t\t\t\tdocument_container* doc_cont = doc->container();\r\n\t\t\t\tif(doc_cont)\r\n\t\t\t\t{\r\n\t\t\t\t\ttstring css_text;\r\n\t\t\t\t\ttstring css_baseurl;\r\n\t\t\t\t\tif(baseurl)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcss_baseurl = baseurl;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tdoc_cont->import_css(css_text, url, css_baseurl);\r\n\t\t\t\t\tif(!css_text.empty())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmedia_query_list::ptr new_media = media;\r\n\t\t\t\t\t\tif(!tokens.empty())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\ttstring media_str;\r\n\t\t\t\t\t\t\tfor(string_vector::iterator iter = tokens.begin(); iter != tokens.end(); iter++)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tif(iter != tokens.begin())\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tmedia_str += _t(\" \");\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tmedia_str += (*iter);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tnew_media = media_query_list::create_from_string(media_str, doc);\r\n\t\t\t\t\t\t\tif(!new_media)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tnew_media = media;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tparse_stylesheet(css_text.c_str(), css_baseurl.c_str(), doc, new_media);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t} else if(text.substr(0, 6) == _t(\"@media\"))\r\n\t{\r\n\t\ttstring::size_type b1 = text.find_first_of(_t('{'));\r\n\t\ttstring::size_type b2 = text.find_last_of(_t('}'));\r\n\t\tif(b1 != tstring::npos)\r\n\t\t{\r\n\t\t\ttstring media_type = text.substr(6, b1 - 6);\r\n\t\t\ttrim(media_type);\r\n\t\t\tmedia_query_list::ptr new_media = media_query_list::create_from_string(media_type, doc);\r\n\r\n\t\t\ttstring media_style;\r\n\t\t\tif(b2 != tstring::npos)\r\n\t\t\t{\r\n\t\t\t\tmedia_style = text.substr(b1 + 1, b2 - b1 - 1);\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tmedia_style = text.substr(b1 + 1);\r\n\t\t\t}\r\n\r\n\t\t\tparse_stylesheet(media_style.c_str(), baseurl, doc, new_media);\r\n\t\t}\r\n\t}\r\n}\r\nfixed case where ; was not removed when it was followed by a whitepace.#include \"html.h\"\r\n#include \"stylesheet.h\"\r\n#include \r\n#include \"document.h\"\r\n\r\n\r\nvoid litehtml::css::parse_stylesheet( const tchar_t* str, const tchar_t* baseurl, document* doc, media_query_list::ptr& media )\r\n{\r\n\ttstring text = str;\r\n\r\n\t\/\/ remove comments\r\n\ttstring::size_type c_start = text.find(_t(\"\/*\"));\r\n\twhile(c_start != tstring::npos)\r\n\t{\r\n\t\ttstring::size_type c_end = text.find(_t(\"*\/\"), c_start + 2);\r\n\t\ttext.erase(c_start, c_end - c_start + 2);\r\n\t\tc_start = text.find(_t(\"\/*\"));\r\n\t}\r\n\r\n\ttstring::size_type pos = text.find_first_not_of(_t(\" \\n\\r\\t\"));\r\n\twhile(pos != tstring::npos)\r\n\t{\r\n\t\twhile(pos != tstring::npos && text[pos] == _t('@'))\r\n\t\t{\r\n\t\t\ttstring::size_type sPos = pos;\r\n\t\t\tpos = text.find_first_of(_t(\"{\"), pos);\r\n\t\t\tif(pos != tstring::npos && text[pos] == _t('{'))\r\n\t\t\t{\r\n\t\t\t\tpos = find_close_bracket(text, pos, _t('{'), _t('}'));\r\n\t\t\t}\r\n\t\t\tif(pos != tstring::npos)\r\n\t\t\t{\r\n\t\t\t\tparse_atrule(text.substr(sPos, pos - sPos + 1), baseurl, doc, media);\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tparse_atrule(text.substr(sPos), baseurl, doc, media);\r\n\t\t\t}\r\n\r\n\t\t\tif(pos != tstring::npos)\r\n\t\t\t{\r\n\t\t\t\tpos = text.find_first_not_of(_t(\" \\n\\r\\t\"), pos + 1);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(pos == tstring::npos)\r\n\t\t{\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\ttstring::size_type style_start = text.find(_t(\"{\"), pos);\r\n\t\ttstring::size_type style_end\t= text.find(_t(\"}\"), pos);\r\n\t\tif(style_start != tstring::npos && style_end != tstring::npos)\r\n\t\t{\r\n\t\t\tstyle::ptr st = new style;\r\n\t\t\tst->add(text.substr(style_start + 1, style_end - style_start - 1).c_str(), baseurl);\r\n\r\n\t\t\tparse_selectors(text.substr(pos, style_start - pos), st, media);\r\n\r\n\t\t\tif(media && doc)\r\n\t\t\t{\r\n\t\t\t\tdoc->add_media_list(media);\r\n\t\t\t}\r\n\r\n\t\t\tpos = style_end + 1;\r\n\t\t} else\r\n\t\t{\r\n\t\t\tpos = tstring::npos;\r\n\t\t}\r\n\r\n\t\tif(pos != tstring::npos)\r\n\t\t{\r\n\t\t\tpos = text.find_first_not_of(_t(\" \\n\\r\\t\"), pos);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid litehtml::css::parse_css_url( const tstring& str, tstring& url )\r\n{\r\n\turl = _t(\"\");\r\n\tsize_t pos1 = str.find(_t('('));\r\n\tsize_t pos2 = str.find(_t(')'));\r\n\tif(pos1 != tstring::npos && pos2 != tstring::npos)\r\n\t{\r\n\t\turl = str.substr(pos1 + 1, pos2 - pos1 - 1);\r\n\t\tif(url.length())\r\n\t\t{\r\n\t\t\tif(url[0] == _t('\\'') || url[0] == _t('\"'))\r\n\t\t\t{\r\n\t\t\t\turl.erase(0, 1);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(url.length())\r\n\t\t{\r\n\t\t\tif(url[url.length() - 1] == _t('\\'') || url[url.length() - 1] == _t('\"'))\r\n\t\t\t{\r\n\t\t\t\turl.erase(url.length() - 1, 1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nbool litehtml::css::parse_selectors( const tstring& txt, litehtml::style::ptr styles, media_query_list::ptr& media )\r\n{\r\n\ttstring selector = txt;\r\n\ttrim(selector);\r\n\tstring_vector tokens;\r\n\tsplit_string(selector, tokens, _t(\",\"));\r\n\r\n\tbool added_something = false;\r\n\r\n\tfor(string_vector::iterator tok = tokens.begin(); tok != tokens.end(); tok++)\r\n\t{\r\n\t\tcss_selector::ptr selector = new css_selector(media);\r\n\t\tselector->m_style = styles;\r\n\t\ttrim(*tok);\r\n\t\tif(selector->parse(*tok))\r\n\t\t{\r\n\t\t\tselector->calc_specificity();\r\n\t\t\tadd_selector(selector);\r\n\t\t\tadded_something = true;\r\n\t\t}\r\n\t}\r\n\r\n\treturn added_something;\r\n}\r\n\r\nvoid litehtml::css::sort_selectors()\r\n{\r\n\tsort(m_selectors.begin(), m_selectors.end(), std::less( ));\r\n}\r\n\r\nvoid litehtml::css::parse_atrule( const tstring& text, const tchar_t* baseurl, document* doc, media_query_list::ptr& media )\r\n{\r\n\tif(text.substr(0, 7) == _t(\"@import\"))\r\n\t{\r\n\t\tint sPos = 7;\r\n\t\ttstring iStr;\r\n\t\tiStr = text.substr(sPos);\r\n\t\ttrim(iStr);\r\n\t\tif(iStr[iStr.length() - 1] == _t(';'))\r\n\t\t{\r\n\t\t\tiStr.erase(iStr.length() - 1);\r\n\t\t}\r\n\t\ttrim(iStr);\r\n\t\tstring_vector tokens;\r\n\t\tsplit_string(iStr, tokens, _t(\" \"), _t(\"\"), _t(\"(\\\"\"));\r\n\t\tif(!tokens.empty())\r\n\t\t{\r\n\t\t\ttstring url;\r\n\t\t\tparse_css_url(tokens.front(), url);\r\n\t\t\tif(url.empty())\r\n\t\t\t{\r\n\t\t\t\turl = tokens.front();\r\n\t\t\t}\r\n\t\t\ttokens.erase(tokens.begin());\r\n\t\t\tif(doc)\r\n\t\t\t{\r\n\t\t\t\tdocument_container* doc_cont = doc->container();\r\n\t\t\t\tif(doc_cont)\r\n\t\t\t\t{\r\n\t\t\t\t\ttstring css_text;\r\n\t\t\t\t\ttstring css_baseurl;\r\n\t\t\t\t\tif(baseurl)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcss_baseurl = baseurl;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tdoc_cont->import_css(css_text, url, css_baseurl);\r\n\t\t\t\t\tif(!css_text.empty())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmedia_query_list::ptr new_media = media;\r\n\t\t\t\t\t\tif(!tokens.empty())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\ttstring media_str;\r\n\t\t\t\t\t\t\tfor(string_vector::iterator iter = tokens.begin(); iter != tokens.end(); iter++)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tif(iter != tokens.begin())\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tmedia_str += _t(\" \");\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tmedia_str += (*iter);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tnew_media = media_query_list::create_from_string(media_str, doc);\r\n\t\t\t\t\t\t\tif(!new_media)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tnew_media = media;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tparse_stylesheet(css_text.c_str(), css_baseurl.c_str(), doc, new_media);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t} else if(text.substr(0, 6) == _t(\"@media\"))\r\n\t{\r\n\t\ttstring::size_type b1 = text.find_first_of(_t('{'));\r\n\t\ttstring::size_type b2 = text.find_last_of(_t('}'));\r\n\t\tif(b1 != tstring::npos)\r\n\t\t{\r\n\t\t\ttstring media_type = text.substr(6, b1 - 6);\r\n\t\t\ttrim(media_type);\r\n\t\t\tmedia_query_list::ptr new_media = media_query_list::create_from_string(media_type, doc);\r\n\r\n\t\t\ttstring media_style;\r\n\t\t\tif(b2 != tstring::npos)\r\n\t\t\t{\r\n\t\t\t\tmedia_style = text.substr(b1 + 1, b2 - b1 - 1);\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tmedia_style = text.substr(b1 + 1);\r\n\t\t\t}\r\n\r\n\t\t\tparse_stylesheet(media_style.c_str(), baseurl, doc, new_media);\r\n\t\t}\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"#include \"midi.h\"\n#include \n#include \n\nMIDI::MIDI() {}\n\nRtMidiIn *MIDI::createMidiIn(const std::string clientName) {\n \/\/ RtMidiIn constructor\n RtMidiIn *midiin = 0;\n try {\n midiin = new RtMidiIn(RtMidi::LINUX_ALSA, clientName);\n } catch (RtMidiError &error) {\n \/\/ Handle the exception here\n error.printMessage();\n }\n midiin->ignoreTypes(false, true, true);\n return midiin;\n}\n\nRtMidiOut *\nMIDI::createMidiOut(const std::string clientName) { \/\/ RtMidiOut constructor\n RtMidiOut *midiout = 0;\n try {\n midiout = new RtMidiOut(RtMidi::LINUX_ALSA, clientName);\n } catch (RtMidiError &error) {\n \/\/ Handle the exception here\n error.printMessage();\n }\n return midiout;\n}\n\nunsigned char MIDI::RolandChecksum(std::vector *message) {\n unsigned int nBytes = message->size();\n unsigned int sum = 0;\n for (unsigned int i = 0; i < nBytes; i++) {\n sum += (int)message->at(i);\n if (sum > 127)\n sum -= 128;\n }\n return 128 - sum;\n}\n\nstd::vector *MIDI::byteSplit(long val) {\n return MIDI::byteSplit(val, 0);\n}\n\nstd::vector *MIDI::byteSplit(long val, int size) {\n std::vector *bytes = new std::vector();\n while (val > 0) {\n unsigned char c = val & 0x7f;\n val >>= 7;\n bytes->push_back(c);\n }\n if (size > 0) {\n int nLength = bytes->size();\n if (nLength < size) {\n for (int i = nLength; i < size; i++)\n bytes->push_back(0x00);\n }\n }\n std::reverse(bytes->begin(), bytes->end());\n return bytes;\n}\n\nlong MIDI::byteJoin(std::vector *message) {\n return byteJoin(message, 0, message->size());\n}\n\nlong MIDI::byteJoin(std::vector *message, unsigned int start,\n unsigned int length) {\n unsigned int cnt;\n int current = 0;\n\n if (start + length >= message->size())\n return -1;\n\n for (cnt = start; cnt < start + length; cnt++) {\n current <<= 7;\n current += message->at(cnt);\n }\n return current;\n}\n\nvoid MIDI::printMessage(BYTE_VECTOR *message) {\n unsigned int nMessageSize = message->size();\n for (unsigned int i = 0; i < nMessageSize; i++)\n std::cout << std::hex << (int)message->at(i) << \" \";\n std::cout << \"\\n\" << std::flush;\n}\nreserve vector size#include \"midi.h\"\n#include \n#include \n\nMIDI::MIDI() {}\n\nRtMidiIn *MIDI::createMidiIn(const std::string clientName) {\n \/\/ RtMidiIn constructor\n RtMidiIn *midiin = 0;\n try {\n midiin = new RtMidiIn(RtMidi::LINUX_ALSA, clientName);\n } catch (RtMidiError &error) {\n \/\/ Handle the exception here\n error.printMessage();\n }\n midiin->ignoreTypes(false, true, true);\n return midiin;\n}\n\nRtMidiOut *\nMIDI::createMidiOut(const std::string clientName) { \/\/ RtMidiOut constructor\n RtMidiOut *midiout = 0;\n try {\n midiout = new RtMidiOut(RtMidi::LINUX_ALSA, clientName);\n } catch (RtMidiError &error) {\n \/\/ Handle the exception here\n error.printMessage();\n }\n return midiout;\n}\n\nunsigned char MIDI::RolandChecksum(std::vector *message) {\n unsigned int nBytes = message->size();\n unsigned int sum = 0;\n for (unsigned int i = 0; i < nBytes; i++) {\n sum += (int)message->at(i);\n if (sum > 127)\n sum -= 128;\n }\n return 128 - sum;\n}\n\nstd::vector *MIDI::byteSplit(long val) {\n return MIDI::byteSplit(val, 0);\n}\n\nstd::vector *MIDI::byteSplit(long val, int size) {\n std::vector *bytes = new std::vector();\n bytes->reserve(size);\n while (val > 0) {\n unsigned char c = val & 0x7f;\n val >>= 7;\n bytes->push_back(c);\n }\n if (size > 0) {\n int nLength = bytes->size();\n if (nLength < size) {\n for (int i = nLength; i < size; i++)\n bytes->push_back(0x00);\n }\n }\n std::reverse(bytes->begin(), bytes->end());\n return bytes;\n}\n\nlong MIDI::byteJoin(std::vector *message) {\n return byteJoin(message, 0, message->size());\n}\n\nlong MIDI::byteJoin(std::vector *message, unsigned int start,\n unsigned int length) {\n unsigned int cnt;\n int current = 0;\n\n if (start + length >= message->size())\n return -1;\n\n for (cnt = start; cnt < start + length; cnt++) {\n current <<= 7;\n current += message->at(cnt);\n }\n return current;\n}\n\nvoid MIDI::printMessage(BYTE_VECTOR *message) {\n unsigned int nMessageSize = message->size();\n for (unsigned int i = 0; i < nMessageSize; i++)\n std::cout << std::hex << (int)message->at(i) << \" \";\n std::cout << \"\\n\" << std::flush;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by H�vard on 13.06.2015.\n\/\/\n\n#include \n#include \n#include \"WebSocketServer.h\"\n#include \"Base64.h\"\n#include \"sha1.h\"\n\nusing namespace libwebsockets;\n\nWebSocketServer WebSocketServer::instance;\nbool WebSocketServer::init = false;\n\nint WebSocketServer::WaitForSockets(int Milliseconds)\n{\n\tstruct pollfd pfds[Sockets.size()];\n\tint i = 0;\n\tfor(auto& socket : Sockets)\n\t{\n\t\tpfds[i].fd = socket.GetFileDescriptor();\n\t\tpfds[i].events = POLLIN;\n\t\ti++;\n\t}\n\n\tint ret = poll(&pfds[0], (int)Sockets.size(), Milliseconds);\n\n\tfor(int i = 0; i < Sockets.size(); i++)\n\t{\n\t\tif((pfds[i].revents & POLLIN) != 0)\n\t\t\tSockets[i].HandleEvent();\n\t}\n\n\treturn ret;\n}\n\nint WebSocketServer::HandleConnectionEvent(Socket & socket)\n{\n\tauto& ws = WebSocketServer::Instance();\n\tstruct sockaddr_in client_addr;\n\tsocklen_t client_length = sizeof(client_addr);\n\tint client = accept(socket.GetFileDescriptor(), (struct sockaddr *)&client_addr, &client_length);\n\tsize_t BufferSize = 1500;\n\tuint8 Buffer[BufferSize]; \/\/Buffer for current packet\n\tsize_t ReadBytes;\n\tSocket ClientSocket = Socket(SocketType::STREAM, client, &HandleClientEvent);\n\n\ttry\n\t{\n\t\tReadBytes = ClientSocket.Read(Buffer, BufferSize);\n\t\tBuffer[ReadBytes] = '\\0';\n\n\t\tmap header = ParseHTTPHeader(string((const char*)Buffer));\n\n\t\tstring appended = header[\"Sec-WebSocket-Key\"] + GID;\n\t\tuint8 hash[20];\n\t\tsha1::calc(appended.c_str(), appended.length(), hash);\n\n\t\tstring HashedKey = Base64Encode(hash, 20);\n\n\t\tchar handshake[BufferSize];\n\n\t\tsprintf(handshake, \"HTTP\/1.1 101 Switching Protocols\\r\\nUpgrade: websocket\\r\\nConnection: Upgrade\\r\\nSec-WebSocket-Accept: %s\\r\\n\\r\\n\", HashedKey.c_str());\n\n\t\tsend(ClientSocket.GetFileDescriptor(), handshake, strlen(handshake), 0);\n\n\t\tws.AddToPoll(ClientSocket);\n\n\t\tif(ws.OnOpen != nullptr) ws.OnOpen(ClientSocket);\n\n\t}\n\tcatch(const exception& ex)\n\t{\n\t\tcout << \"Could not read from socket\" << endl;\n\t}\n\n}\n\nint WebSocketServer::HandleClientEvent(Socket &socket)\n{\n\tauto& ws = WebSocketServer::Instance();\n\tsize_t BufferSize = 1500;\n\tuint8 Buffer[BufferSize]; \/\/Buffer for current packet\n\n\tsize_t ReadBytes;\n\ttry\n\t{\n\t\tReadBytes = socket.Read(Buffer, BufferSize);\n\t\tBuffer[ReadBytes] = '\\0';\n\t\tsize_t MessageOffset = 2;\n\t\tstruct WebSocketHeader header;\n\n\t\tif(Buffer[0] & 0x80) header.IsFinal = true;\n\t\telse header.IsFinal = false;\n\t\tif(Buffer[1] & 0x80) header.IsMasked = true;\n\t\telse header.IsMasked = false;\n\n\t\theader.Opcode = static_cast(Buffer[0] & 0x0F);\n\n\n\t\tif(Buffer[1] == 0x7E)\n\t\t{\n\t\t\tuint16* tempSize = (uint16*) &Buffer[2];\n\t\t\theader.Length = ntohs(*tempSize);\n\t\t\tMessageOffset += 2;\n\t\t}\n\t\telse if(Buffer[1] == 0x7F)\n\t\t{\n\t\t\tuint64* tempSize = (uint64*) &Buffer[2];\n\t\t\theader.Length = ntohll(*tempSize);\n\t\t\tMessageOffset += 8;\n\t\t}\n\t\telse header.Length = Buffer[1] & 0x7F;\n\n\t\tif(header.IsMasked)\n\t\t{\n\t\t\tuint32* tempMask = (uint32*) &Buffer[MessageOffset];\n\t\t\theader.MaskingKey = *tempMask;\n\t\t\tMessageOffset += 4;\n\t\t}\n\n\t\tsocket.AddToMessage(&Buffer[MessageOffset], ReadBytes - MessageOffset, header);\n\n\t\tif(header.IsFinal)\n\t\t{\n\t\t\tif(header.Opcode == WebSocketOpcode::CLOSE)\n\t\t\t{\n\t\t\t\tuint8 buffer[4];\n\n\t\t\t\tbool payload = socket.GetMessageSize() > 0;\n\n\t\t\t\tbuffer[0] = 0x88;\n\t\t\t\tif(payload)\n\t\t\t\t{\n\t\t\t\t\tbuffer[1] = 2;\n\t\t\t\t\tbuffer[2] = socket.GetMessage()[0];\n\t\t\t\t\tbuffer[3] = socket.GetMessage()[1];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tbuffer[1] = 0;\n\n\t\t\t\tsend(socket.GetFileDescriptor(), buffer, payload?4:2, 0);\n\n\t\t\t\tif(ws.OnClose != nullptr) ws.OnClose(socket);\n\t\t\t\tws.RemoveFromPoll(socket);\n\t\t\t}\n\t\t\telse if(header.Opcode == WebSocketOpcode::PING)\n\t\t\t{\n\t\t\t\tuint8 buffer[0xFFFF];\n\t\t\t\tbuffer[0] = 0x89;\n\n\t\t\t\tsize_t size = socket.GetMessageSize();\n\t\t\t\tint offset = 2;\n\t\t\t\tif(size < 0x7E)\n\t\t\t\t\tbuffer[0] = size;\n\t\t\t\telse if(size < 0x7F)\n\t\t\t\t{\n\t\t\t\t\tbuffer[0] = 0x7E;\n\t\t\t\t\toffset += 2;\n\t\t\t\t\t*((uint16*) &buffer[2]) = (uint16) size;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbuffer[0] = 0x7F;\n\t\t\t\t\toffset += 8;\n\t\t\t\t\t*((uint64*) &buffer[2]) = (uint64) size;\n\t\t\t\t}\n\n\t\t\t\tmemcpy(buffer + offset, socket.GetMessage(), socket.GetMessageSize());\n\n\t\t\t\tint sent = send(socket.GetFileDescriptor(), buffer, offset + socket.GetMessageSize(), 0x0);\n\n\t\t\t\tif(sent != sizeof(buffer))\n\t\t\t\t{\n\t\t\t\t\tcout << \"ERROR: Could not send ping\" << endl;\n\t\t\t\t}\n\n\t\t\t\tif(ws.OnPing != nullptr) ws.OnPing(socket);\n\t\t\t}\n\t\t\telse if(header.Opcode == WebSocketOpcode::PONG)\n\t\t\t{\n\t\t\t\tif(ws.OnPong != nullptr) ws.OnPong(socket);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(header.Opcode == WebSocketOpcode::TEXT && socket.GetMessageSize() < MAX_MESSAGE_SIZE)\n\t\t\t\t\tsocket.GetMessage()[socket.GetMessageSize()] = 0;\n\t\t\t\t\/\/Call some function\n\t\t\t\tif(ws.OnMessage != nullptr) ws.OnMessage(socket);\n\n\t\t\t}\n\t\t\tsocket.ResetMessage();\n\t\t}\n\n\t\treturn 0;\n\t}\n\tcatch(const exception& ex)\n\t{\n\t\tcout << \"Could not read from socket\" << endl;\n\t}\n\n}\n\nmap WebSocketServer::ParseHTTPHeader(string header)\n{\n\tstd::string delimiter = \"\\r\\n\";\n\tmap m;\n\tsize_t pos = 0;\n\tstd::string token;\n\twhile ((pos = header.find(delimiter)) != std::string::npos) {\n\t\ttoken = header.substr(0, pos);\n\n\t\tsize_t colon = token.find(':');\n\n\t\tif(colon != string::npos)\n\t\t{\n\t\t\tint skip = 1;\n\t\t\tif(token.at(colon+skip) == ' ') skip++;\n\t\t\tstring key = token.substr(0, colon);\n\t\t\tstring value = token.substr(colon+skip);\n\t\t\tm.insert(make_pair(key, value));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(token.find(\"GET \") == 0)\n\t\t\t{\n\t\t\t\tm.insert(make_pair(\"Request\", token));\n\t\t\t}\n\t\t}\n\n\t\theader.erase(0, pos + delimiter.length());\n\t}\n\n\treturn m;\n}\n\nint WebSocketServer::RemoveFromPoll(Socket &Socket)\n{\n\tfor(int i = 0; i < Sockets.size(); i++)\n\t{\n\t\tif(&Sockets[i] == &Socket)\n\t\t{\n\t\t\tSockets[i].Close();\n\t\t\tSockets.erase(Sockets.begin() + i);\n\n\t\t\treturn 0;\n\t\t}\n\t}\n}\nstatic derp\/\/\n\/\/ Created by H�vard on 13.06.2015.\n\/\/\n\n#include \n#include \n#include \"WebSocketServer.h\"\n#include \"Base64.h\"\n#include \"sha1.h\"\n\nusing namespace libwebsockets;\n\nWebSocketServer WebSocketServer::instance;\nbool WebSocketServer::init = false;\nSocket WebSocketServer::ServerSocket;\n\nint WebSocketServer::WaitForSockets(int Milliseconds)\n{\n\tstruct pollfd pfds[Sockets.size()];\n\tint i = 0;\n\tfor(auto& socket : Sockets)\n\t{\n\t\tpfds[i].fd = socket.GetFileDescriptor();\n\t\tpfds[i].events = POLLIN;\n\t\ti++;\n\t}\n\n\tint ret = poll(&pfds[0], (int)Sockets.size(), Milliseconds);\n\n\tfor(int i = 0; i < Sockets.size(); i++)\n\t{\n\t\tif((pfds[i].revents & POLLIN) != 0)\n\t\t\tSockets[i].HandleEvent();\n\t}\n\n\treturn ret;\n}\n\nint WebSocketServer::HandleConnectionEvent(Socket & socket)\n{\n\tauto& ws = WebSocketServer::Instance();\n\tstruct sockaddr_in client_addr;\n\tsocklen_t client_length = sizeof(client_addr);\n\tint client = accept(socket.GetFileDescriptor(), (struct sockaddr *)&client_addr, &client_length);\n\tsize_t BufferSize = 1500;\n\tuint8 Buffer[BufferSize]; \/\/Buffer for current packet\n\tsize_t ReadBytes;\n\tSocket ClientSocket = Socket(SocketType::STREAM, client, &HandleClientEvent);\n\n\ttry\n\t{\n\t\tReadBytes = ClientSocket.Read(Buffer, BufferSize);\n\t\tBuffer[ReadBytes] = '\\0';\n\n\t\tmap header = ParseHTTPHeader(string((const char*)Buffer));\n\n\t\tstring appended = header[\"Sec-WebSocket-Key\"] + GID;\n\t\tuint8 hash[20];\n\t\tsha1::calc(appended.c_str(), appended.length(), hash);\n\n\t\tstring HashedKey = Base64Encode(hash, 20);\n\n\t\tchar handshake[BufferSize];\n\n\t\tsprintf(handshake, \"HTTP\/1.1 101 Switching Protocols\\r\\nUpgrade: websocket\\r\\nConnection: Upgrade\\r\\nSec-WebSocket-Accept: %s\\r\\n\\r\\n\", HashedKey.c_str());\n\n\t\tsend(ClientSocket.GetFileDescriptor(), handshake, strlen(handshake), 0);\n\n\t\tws.AddToPoll(ClientSocket);\n\n\t\tif(ws.OnOpen != nullptr) ws.OnOpen(ClientSocket);\n\n\t}\n\tcatch(const exception& ex)\n\t{\n\t\tcout << \"Could not read from socket\" << endl;\n\t}\n\n}\n\nint WebSocketServer::HandleClientEvent(Socket &socket)\n{\n\tauto& ws = WebSocketServer::Instance();\n\tsize_t BufferSize = 1500;\n\tuint8 Buffer[BufferSize]; \/\/Buffer for current packet\n\n\tsize_t ReadBytes;\n\ttry\n\t{\n\t\tReadBytes = socket.Read(Buffer, BufferSize);\n\t\tBuffer[ReadBytes] = '\\0';\n\t\tsize_t MessageOffset = 2;\n\t\tstruct WebSocketHeader header;\n\n\t\tif(Buffer[0] & 0x80) header.IsFinal = true;\n\t\telse header.IsFinal = false;\n\t\tif(Buffer[1] & 0x80) header.IsMasked = true;\n\t\telse header.IsMasked = false;\n\n\t\theader.Opcode = static_cast(Buffer[0] & 0x0F);\n\n\n\t\tif(Buffer[1] == 0x7E)\n\t\t{\n\t\t\tuint16* tempSize = (uint16*) &Buffer[2];\n\t\t\theader.Length = ntohs(*tempSize);\n\t\t\tMessageOffset += 2;\n\t\t}\n\t\telse if(Buffer[1] == 0x7F)\n\t\t{\n\t\t\tuint64* tempSize = (uint64*) &Buffer[2];\n\t\t\theader.Length = ntohll(*tempSize);\n\t\t\tMessageOffset += 8;\n\t\t}\n\t\telse header.Length = Buffer[1] & 0x7F;\n\n\t\tif(header.IsMasked)\n\t\t{\n\t\t\tuint32* tempMask = (uint32*) &Buffer[MessageOffset];\n\t\t\theader.MaskingKey = *tempMask;\n\t\t\tMessageOffset += 4;\n\t\t}\n\n\t\tsocket.AddToMessage(&Buffer[MessageOffset], ReadBytes - MessageOffset, header);\n\n\t\tif(header.IsFinal)\n\t\t{\n\t\t\tif(header.Opcode == WebSocketOpcode::CLOSE)\n\t\t\t{\n\t\t\t\tuint8 buffer[4];\n\n\t\t\t\tbool payload = socket.GetMessageSize() > 0;\n\n\t\t\t\tbuffer[0] = 0x88;\n\t\t\t\tif(payload)\n\t\t\t\t{\n\t\t\t\t\tbuffer[1] = 2;\n\t\t\t\t\tbuffer[2] = socket.GetMessage()[0];\n\t\t\t\t\tbuffer[3] = socket.GetMessage()[1];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tbuffer[1] = 0;\n\n\t\t\t\tsend(socket.GetFileDescriptor(), buffer, payload?4:2, 0);\n\n\t\t\t\tif(ws.OnClose != nullptr) ws.OnClose(socket);\n\t\t\t\tws.RemoveFromPoll(socket);\n\t\t\t}\n\t\t\telse if(header.Opcode == WebSocketOpcode::PING)\n\t\t\t{\n\t\t\t\tuint8 buffer[0xFFFF];\n\t\t\t\tbuffer[0] = 0x89;\n\n\t\t\t\tsize_t size = socket.GetMessageSize();\n\t\t\t\tint offset = 2;\n\t\t\t\tif(size < 0x7E)\n\t\t\t\t\tbuffer[0] = size;\n\t\t\t\telse if(size < 0x7F)\n\t\t\t\t{\n\t\t\t\t\tbuffer[0] = 0x7E;\n\t\t\t\t\toffset += 2;\n\t\t\t\t\t*((uint16*) &buffer[2]) = (uint16) size;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbuffer[0] = 0x7F;\n\t\t\t\t\toffset += 8;\n\t\t\t\t\t*((uint64*) &buffer[2]) = (uint64) size;\n\t\t\t\t}\n\n\t\t\t\tmemcpy(buffer + offset, socket.GetMessage(), socket.GetMessageSize());\n\n\t\t\t\tint sent = send(socket.GetFileDescriptor(), buffer, offset + socket.GetMessageSize(), 0x0);\n\n\t\t\t\tif(sent != sizeof(buffer))\n\t\t\t\t{\n\t\t\t\t\tcout << \"ERROR: Could not send ping\" << endl;\n\t\t\t\t}\n\n\t\t\t\tif(ws.OnPing != nullptr) ws.OnPing(socket);\n\t\t\t}\n\t\t\telse if(header.Opcode == WebSocketOpcode::PONG)\n\t\t\t{\n\t\t\t\tif(ws.OnPong != nullptr) ws.OnPong(socket);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(header.Opcode == WebSocketOpcode::TEXT && socket.GetMessageSize() < MAX_MESSAGE_SIZE)\n\t\t\t\t\tsocket.GetMessage()[socket.GetMessageSize()] = 0;\n\t\t\t\t\/\/Call some function\n\t\t\t\tif(ws.OnMessage != nullptr) ws.OnMessage(socket);\n\n\t\t\t}\n\t\t\tsocket.ResetMessage();\n\t\t}\n\n\t\treturn 0;\n\t}\n\tcatch(const exception& ex)\n\t{\n\t\tcout << \"Could not read from socket\" << endl;\n\t}\n\n}\n\nmap WebSocketServer::ParseHTTPHeader(string header)\n{\n\tstd::string delimiter = \"\\r\\n\";\n\tmap m;\n\tsize_t pos = 0;\n\tstd::string token;\n\twhile ((pos = header.find(delimiter)) != std::string::npos) {\n\t\ttoken = header.substr(0, pos);\n\n\t\tsize_t colon = token.find(':');\n\n\t\tif(colon != string::npos)\n\t\t{\n\t\t\tint skip = 1;\n\t\t\tif(token.at(colon+skip) == ' ') skip++;\n\t\t\tstring key = token.substr(0, colon);\n\t\t\tstring value = token.substr(colon+skip);\n\t\t\tm.insert(make_pair(key, value));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(token.find(\"GET \") == 0)\n\t\t\t{\n\t\t\t\tm.insert(make_pair(\"Request\", token));\n\t\t\t}\n\t\t}\n\n\t\theader.erase(0, pos + delimiter.length());\n\t}\n\n\treturn m;\n}\n\nint WebSocketServer::RemoveFromPoll(Socket &Socket)\n{\n\tfor(int i = 0; i < Sockets.size(); i++)\n\t{\n\t\tif(&Sockets[i] == &Socket)\n\t\t{\n\t\t\tSockets[i].Close();\n\t\t\tSockets.erase(Sockets.begin() + i);\n\n\t\t\treturn 0;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\n\n#include \"Vote.h\"\n#include \"ETypes.h\"\n#include \n#include \n#include \n#include \n\nnamespace GameServer\n{\n namespace Fixes\n {\n void CVote::load()\n {\n auto& core = ATF::CATFCore::get_instance();\n core.set_hook(&ATF::Voter::_Vote, &CVote::_Vote);\n core.set_hook(&ATF::Voter::_SendVotePaper, &CVote::_SendVotePaper);\n core.set_hook(&ATF::Voter::_SendVotePaperAll, &CVote::_SendVotePaperAll);\n core.set_hook(&ATF::Voter::_SendVoteScore, &CVote::_SendVoteScore);\n core.set_hook(&ATF::Voter::_SendVoteScoreAll, &CVote::_SendVoteScoreAll);\n }\n\n void CVote::unload()\n {\n auto& core = ATF::CATFCore::get_instance();\n core.unset_hook(&ATF::Voter::_Vote);\n core.unset_hook(&ATF::Voter::_SendVotePaper);\n core.unset_hook(&ATF::Voter::_SendVotePaperAll);\n core.unset_hook(&ATF::Voter::_SendVoteScore);\n core.unset_hook(&ATF::Voter::_SendVoteScoreAll);\n }\n\n void CVote::loop()\n {\n }\n\n ModuleVersion_t CVote::get_version()\n {\n return ATF::usVersion;\n }\n\n ModuleName_t CVote::get_name()\n {\n static const ModuleName_t name = \"fix_Vote\";\n return name;\n }\n\n void CVote::configure(\n const rapidjson::Value & nodeConfig)\n {\n m_nLv = nodeConfig[\"level\"].GetInt();\n m_nPlayTime = nodeConfig[\"play_time\"].GetInt();\n m_dPvpPoint = nodeConfig[\"pvp_point\"].GetDouble();\n m_dPvpCashBag = nodeConfig[\"pvp_cash_bag\"].GetDouble();\n m_nClassGrade = nodeConfig[\"class_grade\"].GetInt();\n m_bScoreListShow = nodeConfig[\"score_list_show\"].GetBool();\n m_bScoreHide = nodeConfig[\"score_hide\"].GetBool();\n }\n\n bool CVote::check_conditions(\n ATF::CPlayer * pOne)\n {\n bool result = false;\n\n do\n {\n if (!pOne || !pOne->m_bOper)\n break;\n\n if (!pOne->m_pUserDB->m_AvatorData.dbSupplement.VoteEnable)\n break;\n\n if (get_class_grade() > pOne->m_pUserDB->m_AvatorData.dbAvator.m_byLastClassGrade)\n break;\n\n if (get_level() > pOne->GetLevel())\n break;\n\n if (get_pvp_cash_bag() > pOne->GetPvpOrderView()->GetPvpCash())\n break;\n\n if (get_pvp_point() > pOne->m_Param.GetPvPPoint())\n break;\n\n if (get_play_time() > pOne->m_pUserDB->m_AvatorData.dbSupplement.dwAccumPlayTime)\n break;\n\n result = true;\n } while (false);\n\n return result;\n }\n\n int WINAPIV CVote::_SendVotePaper(\n ATF::Voter * pObj, \n ATF::CPlayer * pOne, \n ATF::Info::Voter_SendVotePaper12_ptr next)\n {\n UNREFERENCED_PARAMETER(next);\n\n auto spModule = GetModule();\n int result = 0;\n\n do\n {\n if (!pOne)\n break;\n\n if (!pOne->m_bOper)\n break;\n\n if (pObj->_kCandidateInfo[pOne->m_Param.GetRaceCode()].byCnt < 2)\n {\n auto instance = ATF::PatriarchElectProcessor::Instance();\n instance->SendMsg_ResultCode(pOne->m_id.wIndex, 8);\n result = 9;\n break;\n }\n\n if (pOne->m_pUserDB->m_AvatorData.dbAvator.m_bOverlapVote)\n {\n result = 10;\n break;\n }\n\n if (!spModule->check_conditions(pOne))\n {\n result = 11;\n break;\n }\n\n auto instance = ATF::CandidateMgr::Instance();\n if (instance->IsRegistedAvator_2(pOne->m_Param.GetRaceCode(), pOne->m_Param.GetCharSerial()))\n {\n result = 11;\n break;\n }\n\n char pbyType[2]{ 56, 5 };\n auto msg = &pObj->_kCandidateInfo[pOne->m_Param.GetRaceCode()];\n ATF::Global::g_NetProcess[(uint8_t)e_type_line::client]->LoadSendMsg(pOne->m_ObjID.m_wIndex, pbyType, (char *)msg, msg->size());\n } while (false);\n\n return result;\n }\n\n void WINAPIV CVote::_SendVotePaperAll(\n ATF::Voter * pObj, \n ATF::Info::Voter_SendVotePaperAll14_ptr next)\n {\n UNREFERENCED_PARAMETER(next);\n\n for (auto& player : ATF::Global::g_Player)\n {\n _SendVotePaper(pObj, &player, nullptr);\n }\n }\n\n void WINAPIV CVote::_SendVoteScore(\n ATF::Voter * pObj, \n ATF::CPlayer * pOne, \n ATF::Info::Voter_SendVoteScore16_ptr next)\n {\n UNREFERENCED_PARAMETER(next);\n\n auto instance = GetModule();\n if (!instance->score_list_show())\n return;\n\n if (pObj->_kCandidateInfo[pOne->m_Param.GetRaceCode()].byCnt < 2)\n return;\n\n char pbyType[2]{ 56, 6 };\n ATF::_pt_notify_vote_score_zocl info;\n memcpy_s(\n &info, sizeof(info), \n &pObj->_kVoteScoreInfo[pOne->m_Param.GetRaceCode()], \n sizeof(pObj->_kVoteScoreInfo[pOne->m_Param.GetRaceCode()]));\n\n if (!instance->score_hide())\n {\n info.byVoteRate = 0;\n info.byNonvoteRate = 0;\n for (auto& b : info.body)\n b.byScoreRate = 0;\n }\n \n ATF::Global::g_NetProcess[(uint8_t)e_type_line::client]->LoadSendMsg(pOne->m_ObjID.m_wIndex, pbyType, (char *)&info, info.size());\n }\n\n void WINAPIV CVote::_SendVoteScoreAll(\n ATF::Voter * pObj, \n char byRace, \n ATF::Info::Voter_SendVoteScoreAll18_ptr next)\n {\n UNREFERENCED_PARAMETER(next);\n\n auto instance = GetModule();\n if (!instance->score_list_show())\n return;\n\n if (pObj->_kCandidateInfo[byRace].byCnt < 2)\n return;\n\n char pbyType[2]{ 56, 6 };\n ATF::_pt_notify_vote_score_zocl info;\n memcpy_s(\n &info, sizeof(info),\n &pObj->_kVoteScoreInfo[byRace], \n sizeof(pObj->_kVoteScoreInfo[byRace]));\n\n if (!instance->score_hide())\n {\n info.byVoteRate = 0;\n info.byNonvoteRate = 0;\n for (auto& b : info.body)\n b.byScoreRate = 0;\n }\n\n for (int i = 0; i < MAX_PLAYER; ++i)\n {\n auto& player = ATF::Global::g_Player[i];\n if (!player.m_bOper)\n continue;\n\n if (player.m_Param.GetRaceCode() != byRace)\n continue;\n\n ATF::Global::g_NetProcess[(uint8_t)e_type_line::client]->LoadSendMsg(i, pbyType, (char *)&info, info.size());\n }\n }\n\n int WINAPIV CVote::_Vote(\n ATF::Voter * pObj, \n ATF::CPlayer * pOne, \n char * pdata, \n ATF::Info::Voter_Vote22_ptr next)\n {\n auto instance = GetModule();\n if (instance->check_conditions(pOne))\n return next(pObj, pOne, pdata);\n else\n return 10;\n }\n }\n}[Vote] Fixed bug in config#include \"stdafx.h\"\n\n#include \"Vote.h\"\n#include \"ETypes.h\"\n#include \n#include \n#include \n#include \n\nnamespace GameServer\n{\n namespace Fixes\n {\n void CVote::load()\n {\n auto& core = ATF::CATFCore::get_instance();\n core.set_hook(&ATF::Voter::_Vote, &CVote::_Vote);\n core.set_hook(&ATF::Voter::_SendVotePaper, &CVote::_SendVotePaper);\n core.set_hook(&ATF::Voter::_SendVotePaperAll, &CVote::_SendVotePaperAll);\n core.set_hook(&ATF::Voter::_SendVoteScore, &CVote::_SendVoteScore);\n core.set_hook(&ATF::Voter::_SendVoteScoreAll, &CVote::_SendVoteScoreAll);\n }\n\n void CVote::unload()\n {\n auto& core = ATF::CATFCore::get_instance();\n core.unset_hook(&ATF::Voter::_Vote);\n core.unset_hook(&ATF::Voter::_SendVotePaper);\n core.unset_hook(&ATF::Voter::_SendVotePaperAll);\n core.unset_hook(&ATF::Voter::_SendVoteScore);\n core.unset_hook(&ATF::Voter::_SendVoteScoreAll);\n }\n\n void CVote::loop()\n {\n }\n\n ModuleVersion_t CVote::get_version()\n {\n return ATF::usVersion;\n }\n\n ModuleName_t CVote::get_name()\n {\n static const ModuleName_t name = \"fix_Vote\";\n return name;\n }\n\n void CVote::configure(\n const rapidjson::Value & nodeConfig)\n {\n m_nLv = nodeConfig[\"level\"].GetInt();\n m_nPlayTime = nodeConfig[\"play_time\"].GetInt();\n m_dPvpPoint = nodeConfig[\"pvp_point\"].GetDouble();\n m_dPvpCashBag = nodeConfig[\"pvp_cash_bag\"].GetDouble();\n m_nClassGrade = nodeConfig[\"class_grade\"].GetInt();\n m_bScoreListShow = nodeConfig[\"score_list_show\"].GetBool();\n m_bScoreHide = nodeConfig[\"score_hide\"].GetBool();\n }\n\n bool CVote::check_conditions(\n ATF::CPlayer * pOne)\n {\n bool result = false;\n\n do\n {\n if (!pOne || !pOne->m_bOper)\n break;\n\n if (!pOne->m_pUserDB->m_AvatorData.dbSupplement.VoteEnable)\n break;\n\n if (get_class_grade() > pOne->m_pUserDB->m_AvatorData.dbAvator.m_byLastClassGrade)\n break;\n\n if (get_level() > pOne->GetLevel())\n break;\n\n if (get_pvp_cash_bag() > pOne->GetPvpOrderView()->GetPvpCash())\n break;\n\n if (get_pvp_point() > pOne->m_Param.GetPvPPoint())\n break;\n\n if (get_play_time() > pOne->m_pUserDB->m_AvatorData.dbSupplement.dwAccumPlayTime)\n break;\n\n result = true;\n } while (false);\n\n return result;\n }\n\n int WINAPIV CVote::_SendVotePaper(\n ATF::Voter * pObj, \n ATF::CPlayer * pOne, \n ATF::Info::Voter_SendVotePaper12_ptr next)\n {\n UNREFERENCED_PARAMETER(next);\n\n auto spModule = GetModule();\n int result = 0;\n\n do\n {\n if (!pOne)\n break;\n\n if (!pOne->m_bOper)\n break;\n\n if (pObj->_kCandidateInfo[pOne->m_Param.GetRaceCode()].byCnt < 2)\n {\n auto instance = ATF::PatriarchElectProcessor::Instance();\n instance->SendMsg_ResultCode(pOne->m_id.wIndex, 8);\n result = 9;\n break;\n }\n\n if (pOne->m_pUserDB->m_AvatorData.dbAvator.m_bOverlapVote)\n {\n result = 10;\n break;\n }\n\n if (!spModule->check_conditions(pOne))\n {\n result = 11;\n break;\n }\n\n auto instance = ATF::CandidateMgr::Instance();\n if (instance->IsRegistedAvator_2(pOne->m_Param.GetRaceCode(), pOne->m_Param.GetCharSerial()))\n {\n result = 11;\n break;\n }\n\n char pbyType[2]{ 56, 5 };\n auto msg = &pObj->_kCandidateInfo[pOne->m_Param.GetRaceCode()];\n ATF::Global::g_NetProcess[(uint8_t)e_type_line::client]->LoadSendMsg(pOne->m_ObjID.m_wIndex, pbyType, (char *)msg, msg->size());\n } while (false);\n\n return result;\n }\n\n void WINAPIV CVote::_SendVotePaperAll(\n ATF::Voter * pObj, \n ATF::Info::Voter_SendVotePaperAll14_ptr next)\n {\n UNREFERENCED_PARAMETER(next);\n\n for (auto& player : ATF::Global::g_Player)\n {\n _SendVotePaper(pObj, &player, nullptr);\n }\n }\n\n void WINAPIV CVote::_SendVoteScore(\n ATF::Voter * pObj, \n ATF::CPlayer * pOne, \n ATF::Info::Voter_SendVoteScore16_ptr next)\n {\n UNREFERENCED_PARAMETER(next);\n\n auto instance = GetModule();\n if (!instance->score_list_show())\n return;\n\n if (pObj->_kCandidateInfo[pOne->m_Param.GetRaceCode()].byCnt < 2)\n return;\n\n char pbyType[2]{ 56, 6 };\n ATF::_pt_notify_vote_score_zocl info;\n memcpy_s(\n &info, sizeof(info), \n &pObj->_kVoteScoreInfo[pOne->m_Param.GetRaceCode()], \n sizeof(pObj->_kVoteScoreInfo[pOne->m_Param.GetRaceCode()]));\n\n if (instance->score_hide())\n {\n info.byVoteRate = 0;\n info.byNonvoteRate = 0;\n for (auto& b : info.body)\n b.byScoreRate = 0;\n }\n \n ATF::Global::g_NetProcess[(uint8_t)e_type_line::client]->LoadSendMsg(pOne->m_ObjID.m_wIndex, pbyType, (char *)&info, info.size());\n }\n\n void WINAPIV CVote::_SendVoteScoreAll(\n ATF::Voter * pObj, \n char byRace, \n ATF::Info::Voter_SendVoteScoreAll18_ptr next)\n {\n UNREFERENCED_PARAMETER(next);\n\n auto instance = GetModule();\n if (!instance->score_list_show())\n return;\n\n if (pObj->_kCandidateInfo[byRace].byCnt < 2)\n return;\n\n char pbyType[2]{ 56, 6 };\n ATF::_pt_notify_vote_score_zocl info;\n memcpy_s(\n &info, sizeof(info),\n &pObj->_kVoteScoreInfo[byRace], \n sizeof(pObj->_kVoteScoreInfo[byRace]));\n\n if (instance->score_hide())\n {\n info.byVoteRate = 0;\n info.byNonvoteRate = 0;\n for (auto& b : info.body)\n b.byScoreRate = 0;\n }\n\n for (int i = 0; i < MAX_PLAYER; ++i)\n {\n auto& player = ATF::Global::g_Player[i];\n if (!player.m_bOper)\n continue;\n\n if (player.m_Param.GetRaceCode() != byRace)\n continue;\n\n ATF::Global::g_NetProcess[(uint8_t)e_type_line::client]->LoadSendMsg(i, pbyType, (char *)&info, info.size());\n }\n }\n\n int WINAPIV CVote::_Vote(\n ATF::Voter * pObj, \n ATF::CPlayer * pOne, \n char * pdata, \n ATF::Info::Voter_Vote22_ptr next)\n {\n auto instance = GetModule();\n if (instance->check_conditions(pOne))\n return next(pObj, pOne, pdata);\n else\n return 10;\n }\n }\n}<|endoftext|>"} {"text":"\/*!\n * Copyright (c) 2015 by Contributors\n * \\file iter_csv.cc\n * \\brief define a CSV Reader to read in arrays\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \".\/iter_prefetcher.h\"\n#include \".\/iter_batchloader.h\"\n\nnamespace mxnet {\nnamespace io {\n\/\/ CSV parameters\nstruct CSVIterParam : public dmlc::Parameter {\n \/*! \\brief path to data csv file *\/\n std::string data_csv;\n \/*! \\brief data shape *\/\n TShape data_shape;\n \/*! \\brief path to label csv file *\/\n std::string label_csv;\n \/*! \\brief label shape *\/\n TShape label_shape;\n \/\/ declare parameters\n DMLC_DECLARE_PARAMETER(CSVIterParam) {\n DMLC_DECLARE_FIELD(data_csv)\n .describe(\"The input CSV file or a directory path.\");\n DMLC_DECLARE_FIELD(data_shape)\n .describe(\"The shape of one example.\");\n DMLC_DECLARE_FIELD(label_csv).set_default(\"NULL\")\n .describe(\"The input CSV file or a directory path. \"\n \"If NULL, all labels will be returned as 0.\");\n index_t shape1[] = {1};\n DMLC_DECLARE_FIELD(label_shape).set_default(TShape(shape1, shape1 + 1))\n .describe(\"The shape of one label.\");\n }\n};\n\nclass CSVIter: public IIterator {\n public:\n CSVIter() {\n out_.data.resize(2);\n }\n virtual ~CSVIter() {}\n\n \/\/ intialize iterator loads data in\n virtual void Init(const std::vector >& kwargs) {\n param_.InitAllowUnknown(kwargs);\n data_parser_.reset(dmlc::Parser::Create(param_.data_csv.c_str(), 0, 1, \"csv\"));\n if (param_.label_csv != \"NULL\") {\n label_parser_.reset(dmlc::Parser::Create(param_.label_csv.c_str(), 0, 1, \"csv\"));\n } else {\n dummy_label.set_pad(false);\n dummy_label.Resize(mshadow::Shape1(1));\n dummy_label = 0.0f;\n }\n }\n\n virtual void BeforeFirst() {\n data_parser_->BeforeFirst();\n if (label_parser_.get() != nullptr) {\n label_parser_->BeforeFirst();\n }\n data_ptr_ = label_ptr_ = 0;\n data_size_ = label_size_ = 0;\n inst_counter_ = 0;\n end_ = false;\n }\n\n virtual bool Next() {\n if (end_) return false;\n while (data_ptr_ >= data_size_) {\n if (!data_parser_->Next()) {\n end_ = true; return false;\n }\n data_ptr_ = 0;\n data_size_ = data_parser_->Value().size;\n }\n out_.index = inst_counter_++;\n CHECK_LT(data_ptr_, data_size_);\n out_.data[0] = AsTBlob(data_parser_->Value()[data_ptr_++], param_.data_shape);\n\n if (label_parser_.get() != nullptr) {\n while (label_ptr_ >= label_size_) {\n CHECK(label_parser_->Next())\n << \"Data CSV's row is smaller than the number of rows in label_csv\";\n label_ptr_ = 0;\n label_size_ = label_parser_->Value().size;\n }\n CHECK_LT(label_ptr_, label_size_);\n out_.data[1] = AsTBlob(label_parser_->Value()[label_ptr_++], param_.label_shape);\n } else {\n out_.data[1] = dummy_label;\n }\n return true;\n }\n\n virtual const DataInst &Value(void) const {\n return out_;\n }\n\n private:\n inline TBlob AsTBlob(const dmlc::Row& row, const TShape& shape) {\n CHECK_EQ(row.length, shape.Size())\n << \"The data size in CSV do not match size of shape: \"\n << \"specified shape=\" << shape << \", the csv row-length=\" << row.length;\n const real_t* ptr = row.value;\n return TBlob((real_t*)ptr, shape, cpu::kDevMask); \/\/ NOLINT(*)\n }\n\n CSVIterParam param_;\n \/\/ output instance\n DataInst out_;\n \/\/ internal instance counter\n unsigned inst_counter_{0};\n \/\/ at end\n bool end_{false};\n \/\/ dummy label\n mshadow::TensorContainer dummy_label;\n \/\/ label parser\n size_t label_ptr_{0}, label_size_{0};\n size_t data_ptr_{0}, data_size_{0};\n std::unique_ptr > label_parser_;\n std::unique_ptr > data_parser_;\n};\n\n\nDMLC_REGISTER_PARAMETER(CSVIterParam);\n\nMXNET_REGISTER_IO_ITER(CSVIter)\n.describe(R\"code(Returns the CSV file iterator.\n\nIn this function, the `data_shape` parameter is used to set the shape of each line of the input data.\nIf a row in an input file is `1,2,3,4,5,6`` and `data_shape` is (3,2), that row\nwill be reshaped, yielding the array [[1,2],[3,4],[5,6]] of shape (3,2).\n\nBy default, the `CSVIter` has `round_batch` parameter set to ``True``. So, if `batch_size`\nis 3 and there are 4 total rows in CSV file, 2 more examples\nare consumed at the first round. If `reset` function is called after first round,\nthe call is ignored and remaining examples are returned in the second round.\n\nIf one wants all the instances in the second round after calling `reset`, make sure\nto set `round_batch` to False.\n\nIf ``data_csv = 'data\/'`` is set, then all the files in this directory will be read.\n\nExamples::\n\n \/\/ Contents of CSV file ``data\/data.csv``.\n 1,2,3\n 2,3,4\n 3,4,5\n 4,5,6\n\n \/\/ Creates a `CSVIter` with `batch_size`=2 and default `round_batch`=True.\n CSVIter = mx.io.CSVIter(data_csv = 'data\/data.csv', data_shape = (3,),\n batch_size = 2)\n\n \/\/ Two batches read from the above iterator are as follows:\n [[ 1. 2. 3.]\n [ 2. 3. 4.]]\n [[ 3. 4. 5.]\n [ 4. 5. 6.]]\n\n \/\/ Creates a `CSVIter` with `round_batch` set to False.\n CSVIter = mx.io.CSVIter(data_csv = 'data\/data.csv', data_shape = (3,),\n batch_size = 3)\n\n \/\/ Two batches read from the above iterator in the first pass are as follows:\n [[1. 2. 3.]\n [2. 3. 4.]\n [3. 4. 5.]]\n\n [[4. 5. 6.]\n [2. 3. 4.]\n [3. 4. 5.]]\n\n \/\/ Now, `reset` method is called.\n CSVIter.reset()\n\n \/\/ Batch read from the above iterator in the second pass is as follows:\n [[ 3. 4. 5.]\n [ 4. 5. 6.]\n [ 1. 2. 3.]]\n\n \/\/ Creates a `CSVIter` with `round_batch`=False.\n CSVIter = mx.io.CSVIter(data_csv = 'data\/data.csv', data_shape = (3,),\n batch_size = 3, round_batch=True)\n\n \/\/ Contents of two batches read from the above iterator in both passes after calling\n \/\/ `reset` method before second pass is as follows:\n [[1. 2. 3.]\n [2. 3. 4.]\n [3. 4. 5.]]\n\n [[4. 5. 6.]\n [2. 3. 4.]\n [3. 4. 5.]]\n\n)code\" ADD_FILELINE)\n.add_arguments(CSVIterParam::__FIELDS__())\n.add_arguments(BatchParam::__FIELDS__())\n.add_arguments(PrefetcherParam::__FIELDS__())\n.set_body([]() {\n return new PrefetcherIter(\n new BatchLoader(\n new CSVIter()));\n });\n\n} \/\/ namespace io\n} \/\/ namespace mxnet\nCorrection (#6444)\/*!\n * Copyright (c) 2015 by Contributors\n * \\file iter_csv.cc\n * \\brief define a CSV Reader to read in arrays\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \".\/iter_prefetcher.h\"\n#include \".\/iter_batchloader.h\"\n\nnamespace mxnet {\nnamespace io {\n\/\/ CSV parameters\nstruct CSVIterParam : public dmlc::Parameter {\n \/*! \\brief path to data csv file *\/\n std::string data_csv;\n \/*! \\brief data shape *\/\n TShape data_shape;\n \/*! \\brief path to label csv file *\/\n std::string label_csv;\n \/*! \\brief label shape *\/\n TShape label_shape;\n \/\/ declare parameters\n DMLC_DECLARE_PARAMETER(CSVIterParam) {\n DMLC_DECLARE_FIELD(data_csv)\n .describe(\"The input CSV file or a directory path.\");\n DMLC_DECLARE_FIELD(data_shape)\n .describe(\"The shape of one example.\");\n DMLC_DECLARE_FIELD(label_csv).set_default(\"NULL\")\n .describe(\"The input CSV file or a directory path. \"\n \"If NULL, all labels will be returned as 0.\");\n index_t shape1[] = {1};\n DMLC_DECLARE_FIELD(label_shape).set_default(TShape(shape1, shape1 + 1))\n .describe(\"The shape of one label.\");\n }\n};\n\nclass CSVIter: public IIterator {\n public:\n CSVIter() {\n out_.data.resize(2);\n }\n virtual ~CSVIter() {}\n\n \/\/ intialize iterator loads data in\n virtual void Init(const std::vector >& kwargs) {\n param_.InitAllowUnknown(kwargs);\n data_parser_.reset(dmlc::Parser::Create(param_.data_csv.c_str(), 0, 1, \"csv\"));\n if (param_.label_csv != \"NULL\") {\n label_parser_.reset(dmlc::Parser::Create(param_.label_csv.c_str(), 0, 1, \"csv\"));\n } else {\n dummy_label.set_pad(false);\n dummy_label.Resize(mshadow::Shape1(1));\n dummy_label = 0.0f;\n }\n }\n\n virtual void BeforeFirst() {\n data_parser_->BeforeFirst();\n if (label_parser_.get() != nullptr) {\n label_parser_->BeforeFirst();\n }\n data_ptr_ = label_ptr_ = 0;\n data_size_ = label_size_ = 0;\n inst_counter_ = 0;\n end_ = false;\n }\n\n virtual bool Next() {\n if (end_) return false;\n while (data_ptr_ >= data_size_) {\n if (!data_parser_->Next()) {\n end_ = true; return false;\n }\n data_ptr_ = 0;\n data_size_ = data_parser_->Value().size;\n }\n out_.index = inst_counter_++;\n CHECK_LT(data_ptr_, data_size_);\n out_.data[0] = AsTBlob(data_parser_->Value()[data_ptr_++], param_.data_shape);\n\n if (label_parser_.get() != nullptr) {\n while (label_ptr_ >= label_size_) {\n CHECK(label_parser_->Next())\n << \"Data CSV's row is smaller than the number of rows in label_csv\";\n label_ptr_ = 0;\n label_size_ = label_parser_->Value().size;\n }\n CHECK_LT(label_ptr_, label_size_);\n out_.data[1] = AsTBlob(label_parser_->Value()[label_ptr_++], param_.label_shape);\n } else {\n out_.data[1] = dummy_label;\n }\n return true;\n }\n\n virtual const DataInst &Value(void) const {\n return out_;\n }\n\n private:\n inline TBlob AsTBlob(const dmlc::Row& row, const TShape& shape) {\n CHECK_EQ(row.length, shape.Size())\n << \"The data size in CSV do not match size of shape: \"\n << \"specified shape=\" << shape << \", the csv row-length=\" << row.length;\n const real_t* ptr = row.value;\n return TBlob((real_t*)ptr, shape, cpu::kDevMask); \/\/ NOLINT(*)\n }\n\n CSVIterParam param_;\n \/\/ output instance\n DataInst out_;\n \/\/ internal instance counter\n unsigned inst_counter_{0};\n \/\/ at end\n bool end_{false};\n \/\/ dummy label\n mshadow::TensorContainer dummy_label;\n \/\/ label parser\n size_t label_ptr_{0}, label_size_{0};\n size_t data_ptr_{0}, data_size_{0};\n std::unique_ptr > label_parser_;\n std::unique_ptr > data_parser_;\n};\n\n\nDMLC_REGISTER_PARAMETER(CSVIterParam);\n\nMXNET_REGISTER_IO_ITER(CSVIter)\n.describe(R\"code(Returns the CSV file iterator.\n\nIn this function, the `data_shape` parameter is used to set the shape of each line of the input data.\nIf a row in an input file is `1,2,3,4,5,6`` and `data_shape` is (3,2), that row\nwill be reshaped, yielding the array [[1,2],[3,4],[5,6]] of shape (3,2).\n\nBy default, the `CSVIter` has `round_batch` parameter set to ``True``. So, if `batch_size`\nis 3 and there are 4 total rows in CSV file, 2 more examples\nare consumed at the first round. If `reset` function is called after first round,\nthe call is ignored and remaining examples are returned in the second round.\n\nIf one wants all the instances in the second round after calling `reset`, make sure\nto set `round_batch` to False.\n\nIf ``data_csv = 'data\/'`` is set, then all the files in this directory will be read.\n\nExamples::\n\n \/\/ Contents of CSV file ``data\/data.csv``.\n 1,2,3\n 2,3,4\n 3,4,5\n 4,5,6\n\n \/\/ Creates a `CSVIter` with `batch_size`=2 and default `round_batch`=True.\n CSVIter = mx.io.CSVIter(data_csv = 'data\/data.csv', data_shape = (3,),\n batch_size = 2)\n\n \/\/ Two batches read from the above iterator are as follows:\n [[ 1. 2. 3.]\n [ 2. 3. 4.]]\n [[ 3. 4. 5.]\n [ 4. 5. 6.]]\n\n \/\/ Creates a `CSVIter` with default `round_batch` set to True.\n CSVIter = mx.io.CSVIter(data_csv = 'data\/data.csv', data_shape = (3,),\n batch_size = 3)\n\n \/\/ Two batches read from the above iterator in the first pass are as follows:\n [[1. 2. 3.]\n [2. 3. 4.]\n [3. 4. 5.]]\n\n [[4. 5. 6.]\n [2. 3. 4.]\n [3. 4. 5.]]\n\n \/\/ Now, `reset` method is called.\n CSVIter.reset()\n\n \/\/ Batch read from the above iterator in the second pass is as follows:\n [[ 3. 4. 5.]\n [ 4. 5. 6.]\n [ 1. 2. 3.]]\n\n \/\/ Creates a `CSVIter` with `round_batch`=False.\n CSVIter = mx.io.CSVIter(data_csv = 'data\/data.csv', data_shape = (3,),\n batch_size = 3, round_batch=False)\n\n \/\/ Contents of two batches read from the above iterator in both passes, after calling\n \/\/ `reset` method before second pass, is as follows:\n [[1. 2. 3.]\n [2. 3. 4.]\n [3. 4. 5.]]\n\n [[4. 5. 6.]\n [2. 3. 4.]\n [3. 4. 5.]]\n\n)code\" ADD_FILELINE)\n.add_arguments(CSVIterParam::__FIELDS__())\n.add_arguments(BatchParam::__FIELDS__())\n.add_arguments(PrefetcherParam::__FIELDS__())\n.set_body([]() {\n return new PrefetcherIter(\n new BatchLoader(\n new CSVIter()));\n });\n\n} \/\/ namespace io\n} \/\/ namespace mxnet\n<|endoftext|>"} {"text":"\/*\n* Copyright (C) 2008-2011 J-P Nurmi \n*\n* This library is free software; you can redistribute it and\/or modify it\n* under the terms of the GNU Lesser General Public License as published by\n* the Free Software Foundation; either version 2 of the License, or (at your\n* option) any later version.\n*\n* This library is distributed in the hope that it will be useful, but WITHOUT\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n* License for more details.\n*\/\n\n#include \"ircencoder_p.h\"\n#include \n\n#ifdef HAVE_ICU\n#include \n#endif \/\/ HAVE_ICU\n\nIrcEncoder::IrcEncoder()\n{\n d.detector = 0;\n#ifdef HAVE_ICU\n UErrorCode status = U_ZERO_ERROR;\n d.detector = ucsdet_open(&status);\n if (U_FAILURE(status))\n qWarning(\"IrcEncoder: ICU initialization failed: %s\", u_errorName(status));\n#endif \/\/ HAVE_ICU\n}\n\nIrcEncoder::~IrcEncoder()\n{\n#ifdef HAVE_ICU\n ucsdet_close(d.detector);\n#endif \/\/ HAVE_ICU\n}\n\nQString IrcEncoder::encode(const QByteArray& data) const\n{\n QByteArray enc = d.encoding;\n if (enc.isNull())\n enc = detectEncoding(data);\n QTextCodec *codec = QTextCodec::codecForName(d.encoding);\n if (!codec)\n codec = QTextCodec::codecForLocale();\n return codec->toUnicode(data);\n}\n\nQByteArray IrcEncoder::detectEncoding(const QByteArray& data) const\n{\n Q_UNUSED(data);\n QByteArray encoding;\n#ifdef HAVE_ICU\n UErrorCode status = U_ZERO_ERROR;\n if (d.detector)\n {\n ucsdet_setText(d.detector, data.constData(), data.length(), &status);\n if (!U_FAILURE(status))\n {\n const UCharsetMatch* match = ucsdet_detect(d.detector, &status);\n if (match && !U_FAILURE(status))\n encoding = ucsdet_getName(match, &status);\n }\n }\n if (U_FAILURE(status))\n qWarning(\"IrcEncoder::detectEncoding() failed: %s\", u_errorName(status));\n#endif \/\/ HAVE_ICU\n return encoding;\n}\nIrcEncoder: revised encoding auto-detection\/*\n* Copyright (C) 2008-2011 J-P Nurmi \n*\n* This library is free software; you can redistribute it and\/or modify it\n* under the terms of the GNU Lesser General Public License as published by\n* the Free Software Foundation; either version 2 of the License, or (at your\n* option) any later version.\n*\n* This library is distributed in the hope that it will be useful, but WITHOUT\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n* License for more details.\n*\/\n\n#include \"ircencoder_p.h\"\n#include \n\n#ifdef HAVE_ICU\n#include \n#endif \/\/ HAVE_ICU\n\nstatic bool isUtf8(const QByteArray& utf8);\n\nIrcEncoder::IrcEncoder()\n{\n d.detector = 0;\n#ifdef HAVE_ICU\n UErrorCode status = U_ZERO_ERROR;\n d.detector = ucsdet_open(&status);\n if (U_FAILURE(status))\n qWarning(\"IrcEncoder: ICU initialization failed: %s\", u_errorName(status));\n#endif \/\/ HAVE_ICU\n}\n\nIrcEncoder::~IrcEncoder()\n{\n#ifdef HAVE_ICU\n ucsdet_close(d.detector);\n#endif \/\/ HAVE_ICU\n}\n\nQString IrcEncoder::encode(const QByteArray& data) const\n{\n QByteArray enc = d.encoding;\n if (enc.isNull())\n enc = detectEncoding(data);\n QTextCodec *codec = QTextCodec::codecForName(enc);\n if (!codec)\n codec = QTextCodec::codecForLocale();\n return codec->toUnicode(data);\n}\n\nQByteArray IrcEncoder::detectEncoding(const QByteArray& data) const\n{\n QByteArray encoding(\"ISO 8859-1\");\n if (isUtf8(data))\n return \"UTF-8\";\n#ifdef HAVE_ICU\n UErrorCode status = U_ZERO_ERROR;\n if (d.detector)\n {\n ucsdet_setText(d.detector, data.constData(), data.length(), &status);\n if (!U_FAILURE(status))\n {\n const UCharsetMatch* match = ucsdet_detect(d.detector, &status);\n if (match && !U_FAILURE(status))\n encoding = ucsdet_getName(match, &status);\n }\n }\n if (U_FAILURE(status))\n qWarning(\"IrcEncoder::detectEncoding() failed: %s\", u_errorName(status));\n#endif \/\/ HAVE_ICU\n return encoding;\n}\n\n\/*\n The Original Code is mozilla.org code.\n See http:\/\/lxr.mozilla.org\/mozilla\/source\/modules\/rdf\/src\/utils.c\n\n Copyright (C) 1998 Netscape Communications Corporation\n*\/\n\n#define kLeft1BitMask 0x80\n#define kLeft2BitsMask 0xC0\n#define kLeft3BitsMask 0xE0\n#define kLeft4BitsMask 0xF0\n#define kLeft5BitsMask 0xF8\n#define kLeft6BitsMask 0xFC\n#define kLeft7BitsMask 0xFE\n\n#define k2BytesLeadByte kLeft2BitsMask\n#define k3BytesLeadByte kLeft3BitsMask\n#define k4BytesLeadByte kLeft4BitsMask\n#define k5BytesLeadByte kLeft5BitsMask\n#define k6BytesLeadByte kLeft6BitsMask\n#define kTrialByte kLeft1BitMask\n\n#define UTF8_1Byte(c) ( 0 == ((c) & kLeft1BitMask))\n#define UTF8_2Bytes(c) ( k2BytesLeadByte == ((c) & kLeft3BitsMask))\n#define UTF8_3Bytes(c) ( k3BytesLeadByte == ((c) & kLeft4BitsMask))\n#define UTF8_4Bytes(c) ( k4BytesLeadByte == ((c) & kLeft5BitsMask))\n#define UTF8_5Bytes(c) ( k5BytesLeadByte == ((c) & kLeft6BitsMask))\n#define UTF8_6Bytes(c) ( k6BytesLeadByte == ((c) & kLeft7BitsMask))\n#define UTF8_ValidTrialByte(c) ( kTrialByte == ((c) & kLeft2BitsMask))\n\nbool isUtf8(const QByteArray& utf8)\n{\n int clen = 0;\n for (int i = 0; i < utf8.length(); i += clen)\n {\n if (UTF8_1Byte(utf8[i]))\n {\n clen = 1;\n }\n else if (UTF8_2Bytes(utf8[i]))\n {\n clen = 2;\n \/\/ No enough trail bytes\n if ((i + clen) > utf8.length())\n return false;\n \/\/ 0000 0000 - 0000 007F : should encode in less bytes\n if (0 == (utf8[i] & 0x1E))\n return false;\n }\n else if (UTF8_3Bytes(utf8[i]))\n {\n clen = 3;\n \/\/ No enough trail bytes\n if ((i + clen) > utf8.length())\n return false;\n \/\/ a single Surrogate should not show in 3 bytes UTF8, instead,\n \/\/ the pair should be intepreted as one single UCS4 char and\n \/\/ encoded UTF8 in 4 bytes\n if ((0xED == utf8[i]) && (0xA0 == (utf8[i+1] & 0xA0)))\n return false;\n \/\/ 0000 0000 - 0000 07FF : should encode in less bytes\n if ((0 == (utf8[i] & 0x0F)) && (0 == (utf8[i+1] & 0x20)))\n return false;\n }\n else if (UTF8_4Bytes(utf8[i]))\n {\n clen = 4;\n \/\/ No enough trail bytes\n if ((i + clen) > utf8.length())\n return false;\n \/\/ 0000 0000 - 0000 FFFF : should encode in less bytes\n if ((0 == (utf8[i] & 0x07 )) && (0 == (utf8[i+1] & 0x30)))\n return false;\n }\n else if (UTF8_5Bytes(utf8[i]))\n {\n clen = 5;\n \/\/ No enough trail bytes\n if ((i + clen) > utf8.length())\n return false;\n \/\/ 0000 0000 - 001F FFFF : should encode in less bytes\n if ((0 == (utf8[i] & 0x03 )) && (0 == (utf8[i+1] & 0x38)))\n return false;\n }\n else if (UTF8_6Bytes(utf8[i]))\n {\n clen = 6;\n \/\/ No enough trail bytes\n if ((i + clen) > utf8.length())\n return false;\n \/\/ 0000 0000 - 03FF FFFF : should encode in less bytes\n if ((0 == (utf8[i] & 0x01)) && (0 == (utf8[i+1] & 0x3E)))\n return false;\n }\n else\n {\n return false;\n }\n for (int j = 1; j < clen; ++j)\n {\n if (!UTF8_ValidTrialByte(utf8[i+j])) \/\/ Trail bytes invalid\n return false;\n }\n }\n return true;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"globals.h\"\n#include \"mugen_reader.h\"\n#include \"mugen_section.h\"\n#include \"mugen_item_content.h\"\n#include \"mugen_item.h\"\n#include \"mugen_character.h\"\n#include \"mugen_animation.h\"\n#include \"mugen_sprite.h\"\n\n#include \"util\/bitmap.h\"\n#include \"util\/funcs.h\"\n\n#include \"factory\/font_render.h\"\n\n#include \"gui\/keyinput_manager.h\"\n\nusing namespace std;\n\n\/* testing spellcasters code \nstatic int sff_memloadInt(unsigned char *data, int *ofs) {\n int a,b;\n a = data[*ofs];\n (*ofs)++;\n b = data[*ofs];\n (*ofs)++;\n return a + (b <<8);\n}\n\nstatic RGB* sffLoadPaletteFromMemory(unsigned char *data) {\n RGB* pal = (RGB*) malloc(sizeof(RGB) * 256);\n int a, ofs;\n ofs = 0;\n for (a=0; a < 256; ++a) {\n pal[a].r = data[ofs++] \/ 4;\n pal[a].g = data[ofs++] \/ 4;\n pal[a].b = data[ofs++] \/ 4;\n }\n return pal;\n}\n\nstatic BITMAP* sffLoadPcxFromMemory(unsigned char* data) {\n BITMAP *bmp = NULL;\n \n \/\/ skip the first 3 bytes \n int ofs = 3;\n \/\/char planes = data[ofs++];\n int width = -sff_memloadInt(data, &ofs);\n int height = -sff_memloadInt(data, &ofs);\n int bpp = 0;\n int bytesPerLine = 0;\n int x,y;\n int value;\n int count;\n \n width += sff_memloadInt(data, &ofs) +1;\n height+= sff_memloadInt(data, &ofs) +1;\n \n \/\/ skip 4 bytes (dpi) \n ofs += 4;\n \n \/\/ skip 16 color palette \n ofs += 48;\n \n \/\/\/ padding \n ofs++;\n \n \n bpp = data[ofs++] *8;\n if (bpp != 8) { \/\/ || bpp != 24) {\n return NULL;\n }\n \n bytesPerLine = sff_memloadInt(data, &ofs);\n \n \/\/ image data starts at ofs 128\n ofs = 128;\n bmp = create_bitmap_ex(bpp, width, height);\n for (y=0; y < height; ++y) {\n x = 0;\n while (x < bytesPerLine) {\n value = data[ofs++];\n \n \/\/ check if upper 2 bit are set \n if ((value & 0xc0) == 0xc0) {\n \/\/ bits are set, that means the\n \/\/ lower 6 bit contain the repeat count,\n \/\/ and the color is stored in the next byte\n \n count = value & 0x3f;\n value = data[ofs++];\n } else {\n \/\/ value contains the color already \n count = 1;\n }\n if (bpp == 8) {\n while (count > 0) {\n if (x < bmp->w) {\n bmp->line[y][x] = value; \n }\n ++x;\n --count;\n }\n }\n }\n }\n \n \n return bmp;\n}\n*\/\n\nstatic bool isArg( const char * s1, const char * s2 ){\n\treturn strcasecmp( s1, s2 ) == 0;\n}\n\nstatic void showOptions(){\n Global::debug(0) << \"M.U.G.E.N. Config Reader:\" << endl;\n Global::debug(0) << \"-f : Load a M.U.G.E.N. config file and output to screen.\" << endl;\n Global::debug(0) << \"-c : Load a M.U.G.E.N. character and output some data about it.\\n ie: 'data\/mugen\/chars\/name' only pass name.\" << endl;\n Global::debug(0) << endl;\n}\n\n\/* testing testing 1 2 3 *\/\nvoid testPCX(){\n unsigned char data[1 << 18];\n FILE * f = fopen(\"x.pcx\", \"r\");\n int length;\n length = fread(data, sizeof(char), 1<<18, f);\n Global::debug(0) << \"Size is \" << length << endl;\n fclose(f);\n Bitmap b = Bitmap::memoryPCX(data, length);\n \/\/ Bitmap b(\"x.pcx\");\n if (b.getError()){\n Global::debug(0) << \"what the hell\" << endl;\n }\n Bitmap work(640, 480);\n work.circleFill(40, 40, 100, Bitmap::makeColor(255, 0, 0));\n b.draw(0, 0, work);\n Global::debug(0) << \"Width \" << b.getWidth() << \" Height \" << b.getHeight() << endl;\n work.BlitToScreen();\n Util::rest(3000);\n}\n\nint main( int argc, char ** argv ){\n\t\n\tif(argc <= 1){\n\t showOptions();\n\t return 0;\n\t}\n\n\tconst char * FILE_ARG = \"-f\";\n\tconst char * LOC_ARG = \"-c\";\n const char * DEBUG_ARG = \"-l\";\n\tstd::string ourFile;\n\tbool configLoaded = false;\n\n allegro_init();\n install_timer();\n\tinstall_keyboard();\n set_color_depth(16);\n Bitmap::setGfxModeWindowed(640, 480);\n\n\tfor ( int q = 1; q < argc; q++ ){\n\t\tif ( isArg( argv[ q ], FILE_ARG ) ){\n\t\t\tq += 1;\n\t\t\tif ( q < argc ){\n\t\t\t\tourFile = std::string( argv[ q ] );\n\t\t\t\tconfigLoaded = !configLoaded;\n\t\t\t}\n\t\t\telse{\n Global::debug(0) << \"Error no file given!\" << endl;\n\t\t\t showOptions();\n\t\t\t return 0;\n\t\t\t}\n\t\t} else if ( isArg( argv[ q ], LOC_ARG ) ){\n\t\t\tq += 1;\n\t\t\tif ( q < argc ){\n\t\t\t\tourFile = std::string( argv[ q ] );\n\t\t\t}\n\t\t\telse{\n Global::debug(0) << \"Error no file given!\" << endl;\n\t\t\t showOptions();\n\t\t\t return 0;\n\t\t\t}\n\t\t} else if (isArg(argv[q], DEBUG_ARG)){\n q += 1;\n if (q < argc){\n istringstream i( argv[ q ] );\n int f;\n i >> f;\n Global::setDebug( f );\n } else {\n Global::debug(0) << \"No number given for \" << DEBUG_ARG << endl;\n }\n } else {\n\t\t \/\/ WHAT?\n\t\t showOptions();\n\t\t return 0;\n\t\t}\n\t}\n\t\n\tif( configLoaded ){\n\t MugenReader reader( ourFile );\n\t \n\t std::vector< MugenSection * > collection;\n\t \n\t try{\n\t\tcollection = reader.getCollection();\n Global::debug(0) << endl << \"---------------------------------------------------------\" << endl;\n\t\tfor( unsigned int i = 0; i < collection.size(); ++i ){\n Global::debug(0) << collection[i]->getHeader() << endl;\n Global::debug(0) << \"---------------------------------------------------------\" << endl;\n\t\t while( collection[i]->hasItems() ){\n\t\t\tMugenItemContent *content = collection[i]->getNext();\n while( content->hasItems() ){\n Global::debug(0) << content->getNext()->query();\n if( content->hasItems() ) Global::debug(0) << \",\";\n }\n Global::debug(0) << endl;\n\t\t }\n Global::debug(0) << \"---------------------------------------------------------\" << endl;\n\t\t}\n Global::debug(0) << endl;\n\t }\n\t catch( MugenException &ex){\n Global::debug(0) << \"Problem loading file, error was: \" << ex.getReason() << endl;\n\t\treturn 1;\n\t }\n\t}\n\telse{\n\t try{\n Global::debug(0) << \"Trying to load character: \" << ourFile << \"...\" << endl;\n\t\tMugenCharacter character( ourFile );\n\t\tcharacter.load();\n\t\t\/*\n for (map::const_iterator it = character.getAnimations().begin(); it != character.getAnimations().end(); it++){\n Global::debug(0) << \"Animation \" << it->first << endl;\n const vector & frames = it->second->getFrames();\n for (vector::const_iterator frame = frames.begin(); frame != frames.end(); frame++){\n MugenSprite * sprite = (*frame)->sprite;\n if (sprite == 0){\n continue;\n }\n Bitmap b = new Bitmap(sffLoadPcxFromMemory( (char*) sprite->pcx ));;\/\/Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n b.BlitToScreen();\n Util::rest(1000);\n }\n }\n\t\t*\/\n\t\tGlobal::debug(0) << \"Loaded character: \\\"\" << character.getName() << \"\\\" successfully.\" << endl;\n\t\tbool quit = false;\n\t\tbool animate = false;\n\t\tint ticks = 0;\n\t\tint loop = 0;\n\t\t\n\t\tmap::const_iterator it = character.getAnimations().begin();\n\t\tunsigned int currentAnim = 0;\n\t\tunsigned int lastAnim = character.getAnimations().size() -1;\n\t\tunsigned int currentFrame = 0;\n\t\tunsigned int lastFrame = it->second->getFrames().size() -1;\n\t\t\n\t\tMugenSprite * sprite = it->second->getFrames()[currentFrame]->sprite;\n\t\t\n\t\t\/\/BITMAP *b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );\n\t\t\/\/Bitmap b = Bitmap(b_buff, true);\/\/Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n\t\t\/\/destroy_bitmap(b_buff);\n\t\tBitmap b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n\t\t\n\t\tBitmap work( 640, 480 );\n\t\t\n\t\twhile( !quit ){\n\t\t work.clear();\n\t\t keyInputManager::update();\n\t\t ++ticks;\n\t\t \/\/ Since -1 is to stop the animation completely, we'll give it a pause of 150 ticks, because we want to see the loop\n\t\t const int time = it->second->getFrames()[currentFrame]->time == -1 ? 150 : it->second->getFrames()[currentFrame]->time;\n\t\t if(animate && ticks >= 15 + time){\n\t\t\tticks = 0;\n\t\t\tif( it->second->getFrames()[currentFrame]->loopstart ) loop = currentFrame;\n\t\t\tif( currentFrame < lastFrame )currentFrame++;\n\t\t\telse currentFrame = loop;\n\t\t\tsprite = it->second->getFrames()[currentFrame]->sprite;\n\t\t\tif (sprite != 0){\n\t\t\t \/*b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );\n\t\t\t b = Bitmap(b_buff, true);\n\t\t\t destroy_bitmap(b_buff);*\/\n\t\t\t b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n\t\t\t}\n\t\t }\n\t\t \n\t\t if( keyInputManager::keyState(keys::UP, true) ){\n\t\t\tif( currentAnim < lastAnim ){\n\t\t\t currentAnim++;\n\t\t\t it++;\n\t\t\t}\n\t\t\tloop = 0;\n\t\t\tcurrentFrame = 0;\n\t\t\tlastFrame = it->second->getFrames().size()-1;\n\t\t\tsprite = it->second->getFrames()[currentFrame]->sprite;\n\t\t\tif (sprite != 0){\n\t\t\t \/* b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );\n\t\t\t b = Bitmap(b_buff, true);\n\t\t\t destroy_bitmap(b_buff);*\/\n\t\t\t b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n\t\t\t}\n\t\t }\n\t\t else if( keyInputManager::keyState(keys::DOWN, true) ){\n\t\t\tif( currentAnim > 0 ){\n\t\t\t currentAnim--;\n\t\t\t it--;\n\t\t\t}\n\t\t\tloop = 0;\n\t\t\tcurrentFrame = 0;\n\t\t\tlastFrame = it->second->getFrames().size()-1;\n\t\t\tsprite = it->second->getFrames()[currentFrame]->sprite;\n\t\t\tif (sprite != 0){\n\t\t\t \/*b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );\n\t\t\t b = Bitmap(b_buff, true);\n\t\t\t destroy_bitmap(b_buff);*\/\n\t\t\t b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n\t\t\t}\n\t\t }\n\t\t else if( keyInputManager::keyState(keys::LEFT, true) && !animate){\n\t\t\tif( currentFrame > 0 )currentFrame--;\n\t\t\telse currentFrame = lastFrame;\n\t\t\tsprite = it->second->getFrames()[currentFrame]->sprite;\n\t\t\tif (sprite != 0){\n\t\t\t \/* b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );\n\t\t\t b = Bitmap(b_buff, true);\n\t\t\t destroy_bitmap(b_buff); *\/\n\t\t\t b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n\t\t\t}\n\t\t }\n\t\t else if( keyInputManager::keyState(keys::RIGHT, true) && !animate){\n\t\t\tif( currentFrame < lastFrame )currentFrame++;\n\t\t\telse currentFrame = 0;\n\t\t\tsprite = it->second->getFrames()[currentFrame]->sprite;\n\t\t\tif (sprite != 0){\n\t\t\t \/* b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );\n\t\t\t b = Bitmap(b_buff, true);\n\t\t\t destroy_bitmap(b_buff); *\/\n\t\t\t b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n\t\t\t}\n\t\t }\n\t\t else if( keyInputManager::keyState(keys::SPACE, true) ){\n\t\t\tanimate = !animate;\n\t\t }\n\t\t quit |= keyInputManager::keyState(keys::ESC, true );\n\t\t \n\t\t b.Blit(240 + it->second->getFrames()[currentFrame]->xoffset, 100 + it->second->getFrames()[currentFrame]->yoffset, work);\n\t\t Font::getDefaultFont().printf( 15, 250, Bitmap::makeColor( 255, 255, 255 ), work, \"Current Animation: %i, Current Frame: %i\", 0, currentAnim, currentFrame );\n\t\t if(sprite!=0)Font::getDefaultFont().printf( 15, 270, Bitmap::makeColor( 255, 255, 255 ), work, \"Length: %d | x: %d | y: %d | Group: %d | Image: %d\", sprite->length, sprite->x, sprite->y, sprite->groupNumber, sprite->imageNumber);\n\t\t work.BlitToScreen();\n\t\t Util::rest(1);\n\t\t}\n\t }\n\t catch( MugenException &ex){\n Global::debug(0) << \"Problem loading file, error was: \" << ex.getReason() << endl;\n\t\treturn 1;\n\t }\n\t}\n\t\n\treturn 0;\n}\nCorrected print info in test#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"globals.h\"\n#include \"mugen_reader.h\"\n#include \"mugen_section.h\"\n#include \"mugen_item_content.h\"\n#include \"mugen_item.h\"\n#include \"mugen_character.h\"\n#include \"mugen_animation.h\"\n#include \"mugen_sprite.h\"\n\n#include \"util\/bitmap.h\"\n#include \"util\/funcs.h\"\n\n#include \"factory\/font_render.h\"\n\n#include \"gui\/keyinput_manager.h\"\n\nusing namespace std;\n\n\/* testing spellcasters code \nstatic int sff_memloadInt(unsigned char *data, int *ofs) {\n int a,b;\n a = data[*ofs];\n (*ofs)++;\n b = data[*ofs];\n (*ofs)++;\n return a + (b <<8);\n}\n\nstatic RGB* sffLoadPaletteFromMemory(unsigned char *data) {\n RGB* pal = (RGB*) malloc(sizeof(RGB) * 256);\n int a, ofs;\n ofs = 0;\n for (a=0; a < 256; ++a) {\n pal[a].r = data[ofs++] \/ 4;\n pal[a].g = data[ofs++] \/ 4;\n pal[a].b = data[ofs++] \/ 4;\n }\n return pal;\n}\n\nstatic BITMAP* sffLoadPcxFromMemory(unsigned char* data) {\n BITMAP *bmp = NULL;\n \n \/\/ skip the first 3 bytes \n int ofs = 3;\n \/\/char planes = data[ofs++];\n int width = -sff_memloadInt(data, &ofs);\n int height = -sff_memloadInt(data, &ofs);\n int bpp = 0;\n int bytesPerLine = 0;\n int x,y;\n int value;\n int count;\n \n width += sff_memloadInt(data, &ofs) +1;\n height+= sff_memloadInt(data, &ofs) +1;\n \n \/\/ skip 4 bytes (dpi) \n ofs += 4;\n \n \/\/ skip 16 color palette \n ofs += 48;\n \n \/\/\/ padding \n ofs++;\n \n \n bpp = data[ofs++] *8;\n if (bpp != 8) { \/\/ || bpp != 24) {\n return NULL;\n }\n \n bytesPerLine = sff_memloadInt(data, &ofs);\n \n \/\/ image data starts at ofs 128\n ofs = 128;\n bmp = create_bitmap_ex(bpp, width, height);\n for (y=0; y < height; ++y) {\n x = 0;\n while (x < bytesPerLine) {\n value = data[ofs++];\n \n \/\/ check if upper 2 bit are set \n if ((value & 0xc0) == 0xc0) {\n \/\/ bits are set, that means the\n \/\/ lower 6 bit contain the repeat count,\n \/\/ and the color is stored in the next byte\n \n count = value & 0x3f;\n value = data[ofs++];\n } else {\n \/\/ value contains the color already \n count = 1;\n }\n if (bpp == 8) {\n while (count > 0) {\n if (x < bmp->w) {\n bmp->line[y][x] = value; \n }\n ++x;\n --count;\n }\n }\n }\n }\n \n \n return bmp;\n}\n*\/\n\nstatic bool isArg( const char * s1, const char * s2 ){\n\treturn strcasecmp( s1, s2 ) == 0;\n}\n\nstatic void showOptions(){\n Global::debug(0) << \"M.U.G.E.N. Config Reader:\" << endl;\n Global::debug(0) << \"-f : Load a M.U.G.E.N. config file and output to screen.\" << endl;\n Global::debug(0) << \"-c : Load a M.U.G.E.N. character and output some data about it.\\n ie: 'data\/mugen\/chars\/name' only pass name.\" << endl;\n Global::debug(0) << endl;\n}\n\n\/* testing testing 1 2 3 *\/\nvoid testPCX(){\n unsigned char data[1 << 18];\n FILE * f = fopen(\"x.pcx\", \"r\");\n int length;\n length = fread(data, sizeof(char), 1<<18, f);\n Global::debug(0) << \"Size is \" << length << endl;\n fclose(f);\n Bitmap b = Bitmap::memoryPCX(data, length);\n \/\/ Bitmap b(\"x.pcx\");\n if (b.getError()){\n Global::debug(0) << \"what the hell\" << endl;\n }\n Bitmap work(640, 480);\n work.circleFill(40, 40, 100, Bitmap::makeColor(255, 0, 0));\n b.draw(0, 0, work);\n Global::debug(0) << \"Width \" << b.getWidth() << \" Height \" << b.getHeight() << endl;\n work.BlitToScreen();\n Util::rest(3000);\n}\n\nint main( int argc, char ** argv ){\n\t\n\tif(argc <= 1){\n\t showOptions();\n\t return 0;\n\t}\n\n\tconst char * FILE_ARG = \"-f\";\n\tconst char * LOC_ARG = \"-c\";\n const char * DEBUG_ARG = \"-l\";\n\tstd::string ourFile;\n\tbool configLoaded = false;\n\n allegro_init();\n install_timer();\n\tinstall_keyboard();\n set_color_depth(16);\n Bitmap::setGfxModeWindowed(640, 480);\n\n\tfor ( int q = 1; q < argc; q++ ){\n\t\tif ( isArg( argv[ q ], FILE_ARG ) ){\n\t\t\tq += 1;\n\t\t\tif ( q < argc ){\n\t\t\t\tourFile = std::string( argv[ q ] );\n\t\t\t\tconfigLoaded = !configLoaded;\n\t\t\t}\n\t\t\telse{\n Global::debug(0) << \"Error no file given!\" << endl;\n\t\t\t showOptions();\n\t\t\t return 0;\n\t\t\t}\n\t\t} else if ( isArg( argv[ q ], LOC_ARG ) ){\n\t\t\tq += 1;\n\t\t\tif ( q < argc ){\n\t\t\t\tourFile = std::string( argv[ q ] );\n\t\t\t}\n\t\t\telse{\n Global::debug(0) << \"Error no file given!\" << endl;\n\t\t\t showOptions();\n\t\t\t return 0;\n\t\t\t}\n\t\t} else if (isArg(argv[q], DEBUG_ARG)){\n q += 1;\n if (q < argc){\n istringstream i( argv[ q ] );\n int f;\n i >> f;\n Global::setDebug( f );\n } else {\n Global::debug(0) << \"No number given for \" << DEBUG_ARG << endl;\n }\n } else {\n\t\t \/\/ WHAT?\n\t\t showOptions();\n\t\t return 0;\n\t\t}\n\t}\n\t\n\tif( configLoaded ){\n\t MugenReader reader( ourFile );\n\t \n\t std::vector< MugenSection * > collection;\n\t \n\t try{\n\t\tcollection = reader.getCollection();\n Global::debug(0) << endl << \"---------------------------------------------------------\" << endl;\n\t\tfor( unsigned int i = 0; i < collection.size(); ++i ){\n Global::debug(0) << collection[i]->getHeader() << endl;\n Global::debug(0) << \"---------------------------------------------------------\" << endl;\n\t\t while( collection[i]->hasItems() ){\n\t\t\tMugenItemContent *content = collection[i]->getNext();\n while( content->hasItems() ){\n Global::debug(0) << content->getNext()->query();\n if( content->hasItems() ) Global::debug(0) << \",\";\n }\n Global::debug(0) << endl;\n\t\t }\n Global::debug(0) << \"---------------------------------------------------------\" << endl;\n\t\t}\n Global::debug(0) << endl;\n\t }\n\t catch( MugenException &ex){\n Global::debug(0) << \"Problem loading file, error was: \" << ex.getReason() << endl;\n\t\treturn 1;\n\t }\n\t}\n\telse{\n\t try{\n Global::debug(0) << \"Trying to load character: \" << ourFile << \"...\" << endl;\n\t\tMugenCharacter character( ourFile );\n\t\tcharacter.load();\n\t\t\/*\n for (map::const_iterator it = character.getAnimations().begin(); it != character.getAnimations().end(); it++){\n Global::debug(0) << \"Animation \" << it->first << endl;\n const vector & frames = it->second->getFrames();\n for (vector::const_iterator frame = frames.begin(); frame != frames.end(); frame++){\n MugenSprite * sprite = (*frame)->sprite;\n if (sprite == 0){\n continue;\n }\n Bitmap b = new Bitmap(sffLoadPcxFromMemory( (char*) sprite->pcx ));;\/\/Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n b.BlitToScreen();\n Util::rest(1000);\n }\n }\n\t\t*\/\n\t\tGlobal::debug(0) << \"Loaded character: \\\"\" << character.getName() << \"\\\" successfully.\" << endl;\n\t\tbool quit = false;\n\t\tbool animate = false;\n\t\tint ticks = 0;\n\t\tint loop = 0;\n\t\t\n\t\tmap::const_iterator it = character.getAnimations().begin();\n\t\tunsigned int currentAnim = 0;\n\t\tunsigned int lastAnim = character.getAnimations().size() -1;\n\t\tunsigned int currentFrame = 0;\n\t\tunsigned int lastFrame = it->second->getFrames().size() -1;\n\t\t\n\t\tMugenSprite * sprite = it->second->getFrames()[currentFrame]->sprite;\n\t\t\n\t\t\/\/BITMAP *b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );\n\t\t\/\/Bitmap b = Bitmap(b_buff, true);\/\/Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n\t\t\/\/destroy_bitmap(b_buff);\n\t\tBitmap b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n\t\t\n\t\tBitmap work( 640, 480 );\n\t\t\n\t\twhile( !quit ){\n\t\t work.clear();\n\t\t keyInputManager::update();\n\t\t ++ticks;\n\t\t \/\/ Since -1 is to stop the animation completely, we'll give it a pause of 150 ticks, because we want to see the loop\n\t\t const int time = it->second->getFrames()[currentFrame]->time == -1 ? 150 : it->second->getFrames()[currentFrame]->time;\n\t\t if(animate && ticks >= 15 + time){\n\t\t\tticks = 0;\n\t\t\tif( it->second->getFrames()[currentFrame]->loopstart ) loop = currentFrame;\n\t\t\tif( currentFrame < lastFrame )currentFrame++;\n\t\t\telse currentFrame = loop;\n\t\t\tsprite = it->second->getFrames()[currentFrame]->sprite;\n\t\t\tif (sprite != 0){\n\t\t\t \/*b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );\n\t\t\t b = Bitmap(b_buff, true);\n\t\t\t destroy_bitmap(b_buff);*\/\n\t\t\t b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n\t\t\t}\n\t\t }\n\t\t \n\t\t if( keyInputManager::keyState(keys::UP, true) ){\n\t\t\tif( currentAnim < lastAnim ){\n\t\t\t currentAnim++;\n\t\t\t it++;\n\t\t\t}\n\t\t\tloop = 0;\n\t\t\tcurrentFrame = 0;\n\t\t\tlastFrame = it->second->getFrames().size()-1;\n\t\t\tsprite = it->second->getFrames()[currentFrame]->sprite;\n\t\t\tif (sprite != 0){\n\t\t\t \/* b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );\n\t\t\t b = Bitmap(b_buff, true);\n\t\t\t destroy_bitmap(b_buff);*\/\n\t\t\t b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n\t\t\t}\n\t\t }\n\t\t else if( keyInputManager::keyState(keys::DOWN, true) ){\n\t\t\tif( currentAnim > 0 ){\n\t\t\t currentAnim--;\n\t\t\t it--;\n\t\t\t}\n\t\t\tloop = 0;\n\t\t\tcurrentFrame = 0;\n\t\t\tlastFrame = it->second->getFrames().size()-1;\n\t\t\tsprite = it->second->getFrames()[currentFrame]->sprite;\n\t\t\tif (sprite != 0){\n\t\t\t \/*b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );\n\t\t\t b = Bitmap(b_buff, true);\n\t\t\t destroy_bitmap(b_buff);*\/\n\t\t\t b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n\t\t\t}\n\t\t }\n\t\t else if( keyInputManager::keyState(keys::LEFT, true) && !animate){\n\t\t\tif( currentFrame > 0 )currentFrame--;\n\t\t\telse currentFrame = lastFrame;\n\t\t\tsprite = it->second->getFrames()[currentFrame]->sprite;\n\t\t\tif (sprite != 0){\n\t\t\t \/* b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );\n\t\t\t b = Bitmap(b_buff, true);\n\t\t\t destroy_bitmap(b_buff); *\/\n\t\t\t b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n\t\t\t}\n\t\t }\n\t\t else if( keyInputManager::keyState(keys::RIGHT, true) && !animate){\n\t\t\tif( currentFrame < lastFrame )currentFrame++;\n\t\t\telse currentFrame = 0;\n\t\t\tsprite = it->second->getFrames()[currentFrame]->sprite;\n\t\t\tif (sprite != 0){\n\t\t\t \/* b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );\n\t\t\t b = Bitmap(b_buff, true);\n\t\t\t destroy_bitmap(b_buff); *\/\n\t\t\t b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);\n\t\t\t}\n\t\t }\n\t\t else if( keyInputManager::keyState(keys::SPACE, true) ){\n\t\t\tanimate = !animate;\n\t\t }\n\t\t quit |= keyInputManager::keyState(keys::ESC, true );\n\t\t \n\t\t b.Blit(240 + it->second->getFrames()[currentFrame]->xoffset, 100 + it->second->getFrames()[currentFrame]->yoffset, work);\n\t\t Font::getDefaultFont().printf( 15, 250, Bitmap::makeColor( 255, 255, 255 ), work, \"Current Animation: %i, Current Frame: %i\", 0, currentAnim, currentFrame );\n\t\t if(sprite!=0)Font::getDefaultFont().printf( 15, 270, Bitmap::makeColor( 255, 255, 255 ), work, \"Length: %d | x: %d | y: %d | Group: %d | Image: %d\",0, sprite->length, sprite->x, sprite->y, sprite->groupNumber, sprite->imageNumber);\n\t\t work.BlitToScreen();\n\t\t Util::rest(1);\n\t\t}\n\t }\n\t catch( MugenException &ex){\n Global::debug(0) << \"Problem loading file, error was: \" << ex.getReason() << endl;\n\t\treturn 1;\n\t }\n\t}\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"Bugfix: `Scene::get_turbo_factor`: return `NAN` as a fallback.<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: iframe.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 23:22:13 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sfx2.hxx\"\n\n#include \"iframe.hxx\"\n#include \n#include \n\n#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace ::com::sun::star;\n\nnamespace sfx2\n{\n\nclass IFrameWindow_Impl : public Window\n{\n uno::Reference < frame::XFrame > mxFrame;\n sal_Bool bActive;\n sal_Bool bBorder;\n\npublic:\n IFrameWindow_Impl( Window *pParent,\n sal_Bool bHasBorder,\n WinBits nWinBits = 0 );\n\npublic:\n void SetBorder( sal_Bool bNewBorder = sal_True );\n sal_Bool HasBorder() const { return bBorder; }\n};\n\nIFrameWindow_Impl::IFrameWindow_Impl( Window *pParent, sal_Bool bHasBorder, WinBits nWinBits )\n : Window( pParent, nWinBits | WB_CLIPCHILDREN | WB_NODIALOGCONTROL | WB_DOCKBORDER )\n , bActive(sal_False)\n , bBorder(bHasBorder)\n{\n if ( !bHasBorder )\n SetBorderStyle( WINDOW_BORDER_NOBORDER );\n else\n SetBorderStyle( WINDOW_BORDER_NORMAL );\n \/\/SetActivateMode( ACTIVATE_MODE_GRABFOCUS );\n}\n\nvoid IFrameWindow_Impl::SetBorder( sal_Bool bNewBorder )\n{\n if ( bBorder != bNewBorder )\n {\n Size aSize = GetSizePixel();\n bBorder = bNewBorder;\n if ( bBorder )\n SetBorderStyle( WINDOW_BORDER_NORMAL );\n else\n SetBorderStyle( WINDOW_BORDER_NOBORDER );\n if ( GetSizePixel() != aSize )\n SetSizePixel( aSize );\n }\n}\n\n#define PROPERTY_UNBOUND 0\n\nSfxItemPropertyMap aIFramePropertyMap_Impl[] =\n{\n { \"FrameIsAutoBorder\", 17, 1, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },\n { \"FrameIsAutoScroll\", 17, 2, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },\n { \"FrameIsBorder\", 13, 3, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },\n { \"FrameIsScrollingMode\", 20, 4, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },\n { \"FrameMarginHeight\", 17, 5, &::getCppuType( (sal_Int32*)0 ), PROPERTY_UNBOUND, 0 },\n { \"FrameMarginWidth\", 16, 6, &::getCppuType( (sal_Int32*)0 ), PROPERTY_UNBOUND, 0 },\n { \"FrameName\", 9, 7, &::getCppuType((const ::rtl::OUString*)0), PROPERTY_UNBOUND, 0 },\n { \"FrameURL\", 8, 8, &::getCppuType((const ::rtl::OUString*)0), PROPERTY_UNBOUND, 0 },\n {0,0,0,0,0,0}\n};\n\nSFX_IMPL_XSERVICEINFO( IFrameObject, \"com.sun.star.embed.SpecialEmbeddedObject\", \"com.sun.star.comp.sfx2.IFrameObject\" )\nSFX_IMPL_SINGLEFACTORY( IFrameObject );\n\nIFrameObject::IFrameObject( const uno::Reference < lang::XMultiServiceFactory >& rFact )\n : mxFact( rFact )\n , maPropSet( aIFramePropertyMap_Impl )\n{\n}\n\nIFrameObject::~IFrameObject()\n{\n}\n\n\nvoid SAL_CALL IFrameObject::initialize( const uno::Sequence< uno::Any >& aArguments ) throw ( uno::Exception, uno::RuntimeException )\n{\n if ( aArguments.getLength() )\n aArguments[0] >>= mxObj;\n}\n\nsal_Bool SAL_CALL IFrameObject::load(\n const uno::Sequence < com::sun::star::beans::PropertyValue >& \/*lDescriptor*\/,\n const uno::Reference < frame::XFrame >& xFrame )\nthrow( uno::RuntimeException )\n{\n if ( SvtMiscOptions().IsPluginsEnabled() )\n {\n DBG_ASSERT( !mxFrame.is(), \"Frame already existing!\" );\n Window* pParent = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );\n IFrameWindow_Impl* pWin = new IFrameWindow_Impl( pParent, maFrmDescr.IsFrameBorderOn() );\n pWin->SetSizePixel( pParent->GetOutputSizePixel() );\n pWin->SetBackground();\n pWin->Show();\n\n uno::Reference < awt::XWindow > xWindow( pWin->GetComponentInterface(), uno::UNO_QUERY );\n xFrame->setComponent( xWindow, uno::Reference < frame::XController >() );\n\n \/\/ we must destroy the IFrame before the parent is destroyed\n xWindow->addEventListener( this );\n\n mxFrame = uno::Reference< frame::XFrame >( mxFact->createInstance( ::rtl::OUString::createFromAscii( \"com.sun.star.frame.Frame\" ) ),\n uno::UNO_QUERY );\n uno::Reference < awt::XWindow > xWin( pWin->GetComponentInterface(), uno::UNO_QUERY );\n mxFrame->initialize( xWin );\n mxFrame->setName( maFrmDescr.GetName() );\n\n uno::Reference< frame::XDispatchProvider > xProv( mxFrame, uno::UNO_QUERY );\n\n util::URL aTargetURL;\n aTargetURL.Complete = ::rtl::OUString( maFrmDescr.GetURL().GetMainURL( INetURLObject::NO_DECODE ) );\n uno::Reference < util::XURLTransformer > xTrans( mxFact->createInstance( rtl::OUString::createFromAscii(\"com.sun.star.util.URLTransformer\" )), uno::UNO_QUERY );\n xTrans->parseStrict( aTargetURL );\n\n uno::Sequence < beans::PropertyValue > aProps(2);\n aProps[0].Name = ::rtl::OUString::createFromAscii(\"PluginMode\");\n aProps[0].Value <<= (sal_Int16) 2;\n aProps[1].Name = ::rtl::OUString::createFromAscii(\"ReadOnly\");\n aProps[1].Value <<= (sal_Bool) sal_True;\n uno::Reference < frame::XDispatch > xDisp = xProv->queryDispatch( aTargetURL, ::rtl::OUString::createFromAscii(\"_self\"), 0 );\n if ( xDisp.is() )\n xDisp->dispatch( aTargetURL, aProps );\n\n return TRUE;\n }\n\n return FALSE;\n}\n\nvoid SAL_CALL IFrameObject::cancel() throw( com::sun::star::uno::RuntimeException )\n{\n try\n {\n uno::Reference < util::XCloseable > xClose( mxFrame, uno::UNO_QUERY );\n if ( xClose.is() )\n xClose->close( sal_True );\n mxFrame = 0;\n }\n catch ( uno::Exception& )\n {}\n}\n\nvoid SAL_CALL IFrameObject::close( sal_Bool \/*bDeliverOwnership*\/ ) throw( com::sun::star::util::CloseVetoException, com::sun::star::uno::RuntimeException )\n{\n}\n\nvoid SAL_CALL IFrameObject::addCloseListener( const com::sun::star::uno::Reference < com::sun::star::util::XCloseListener >& ) throw( com::sun::star::uno::RuntimeException )\n{\n}\n\nvoid SAL_CALL IFrameObject::removeCloseListener( const com::sun::star::uno::Reference < com::sun::star::util::XCloseListener >& ) throw( com::sun::star::uno::RuntimeException )\n{\n}\n\nvoid SAL_CALL IFrameObject::disposing( const com::sun::star::lang::EventObject& ) throw (com::sun::star::uno::RuntimeException)\n{\n cancel();\n}\n\nuno::Reference< beans::XPropertySetInfo > SAL_CALL IFrameObject::getPropertySetInfo() throw( ::com::sun::star::uno::RuntimeException )\n{\n return maPropSet.getPropertySetInfo();\n}\n\nvoid SAL_CALL IFrameObject::setPropertyValue(const ::rtl::OUString& aPropertyName, const uno::Any& aAny)\n throw ( beans::UnknownPropertyException, beans::PropertyVetoException, lang::IllegalArgumentException, lang::WrappedTargetException, uno::RuntimeException)\n{\n if ( aPropertyName.equalsAscii(\"FrameURL\") )\n {\n ::rtl::OUString aURL;\n aAny >>= aURL;\n maFrmDescr.SetURL( String(aURL) );\n }\n else if ( aPropertyName.equalsAscii(\"FrameName\") )\n {\n ::rtl::OUString aName;\n if ( aAny >>= aName )\n maFrmDescr.SetName( aName );\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsAutoScroll\") )\n {\n sal_Bool bIsAutoScroll = sal_Bool();\n if ( (aAny >>= bIsAutoScroll) && bIsAutoScroll )\n maFrmDescr.SetScrollingMode( ScrollingAuto );\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsScrollingMode\") )\n {\n sal_Bool bIsScroll = sal_Bool();\n if ( aAny >>= bIsScroll )\n maFrmDescr.SetScrollingMode( bIsScroll ? ScrollingYes : ScrollingNo );\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsBorder\") )\n {\n sal_Bool bIsBorder = sal_Bool();\n if ( aAny >>= bIsBorder )\n maFrmDescr.SetFrameBorder( bIsBorder );\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsAutoBorder\") )\n {\n sal_Bool bIsAutoBorder = sal_Bool();\n if ( (aAny >>= bIsAutoBorder) )\n {\n BOOL bBorder = maFrmDescr.IsFrameBorderOn();\n maFrmDescr.ResetBorder();\n if ( bIsAutoBorder )\n maFrmDescr.SetFrameBorder( bBorder );\n }\n }\n else if ( aPropertyName.equalsAscii(\"FrameMarginWidth\") )\n {\n sal_Int32 nMargin = 0;\n Size aSize = maFrmDescr.GetMargin();\n if ( aAny >>= nMargin )\n {\n aSize.Width() = nMargin;\n maFrmDescr.SetMargin( aSize );\n }\n }\n else if ( aPropertyName.equalsAscii(\"FrameMarginHeight\") )\n {\n sal_Int32 nMargin = 0;\n Size aSize = maFrmDescr.GetMargin();\n if ( aAny >>= nMargin )\n {\n aSize.Height() = nMargin;\n maFrmDescr.SetMargin( aSize );\n }\n }\n else\n throw beans::UnknownPropertyException();\n}\n\nuno::Any SAL_CALL IFrameObject::getPropertyValue(const ::rtl::OUString& aPropertyName)\n throw ( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException)\n{\n uno::Any aAny;\n if ( aPropertyName.equalsAscii(\"FrameURL\") )\n {\n aAny <<= ::rtl::OUString( maFrmDescr.GetURL().GetMainURL( INetURLObject::NO_DECODE ) );\n }\n else if ( aPropertyName.equalsAscii(\"FrameName\") )\n {\n aAny <<= ::rtl::OUString( maFrmDescr.GetName() );\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsAutoScroll\") )\n {\n sal_Bool bIsAutoScroll = ( maFrmDescr.GetScrollingMode() == ScrollingAuto );\n aAny <<= bIsAutoScroll;\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsScrollingMode\") )\n {\n sal_Bool bIsScroll = ( maFrmDescr.GetScrollingMode() == ScrollingYes );\n aAny <<= bIsScroll;\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsBorder\") )\n {\n sal_Bool bIsBorder = maFrmDescr.IsFrameBorderOn();\n aAny <<= bIsBorder;\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsAutoBorder\") )\n {\n sal_Bool bIsAutoBorder = !maFrmDescr.IsFrameBorderSet();\n aAny <<= bIsAutoBorder;\n }\n else if ( aPropertyName.equalsAscii(\"FrameMarginWidth\") )\n {\n aAny <<= (sal_Int32 ) maFrmDescr.GetMargin().Width();\n }\n else if ( aPropertyName.equalsAscii(\"FrameMarginHeight\") )\n {\n aAny <<= (sal_Int32 ) maFrmDescr.GetMargin().Height();\n }\n else\n throw beans::UnknownPropertyException();\n return aAny;\n}\n\nvoid SAL_CALL IFrameObject::addPropertyChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )\n{\n}\n\nvoid SAL_CALL IFrameObject::removePropertyChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )\n{\n}\n\nvoid SAL_CALL IFrameObject::addVetoableChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )\n{\n}\n\nvoid SAL_CALL IFrameObject::removeVetoableChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )\n{\n}\n\n::sal_Int16 SAL_CALL IFrameObject::execute() throw (::com::sun::star::uno::RuntimeException)\n{\n SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();\n VclAbstractDialog* pDlg = pFact->CreateEditObjectDialog( NULL, SID_INSERT_FLOATINGFRAME, mxObj );\n if ( pDlg )\n pDlg->Execute();\n return 0;\n}\n\nvoid SAL_CALL IFrameObject::setTitle( const ::rtl::OUString& ) throw (::com::sun::star::uno::RuntimeException)\n{\n}\n\n}\nINTEGRATION: CWS changefileheader (1.10.216); FILE MERGED 2008\/04\/01 12:40:48 thb 1.10.216.2: #i85898# Stripping all external header guards 2008\/03\/31 13:38:27 rt 1.10.216.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: iframe.cxx,v $\n * $Revision: 1.11 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sfx2.hxx\"\n\n#include \"iframe.hxx\"\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace ::com::sun::star;\n\nnamespace sfx2\n{\n\nclass IFrameWindow_Impl : public Window\n{\n uno::Reference < frame::XFrame > mxFrame;\n sal_Bool bActive;\n sal_Bool bBorder;\n\npublic:\n IFrameWindow_Impl( Window *pParent,\n sal_Bool bHasBorder,\n WinBits nWinBits = 0 );\n\npublic:\n void SetBorder( sal_Bool bNewBorder = sal_True );\n sal_Bool HasBorder() const { return bBorder; }\n};\n\nIFrameWindow_Impl::IFrameWindow_Impl( Window *pParent, sal_Bool bHasBorder, WinBits nWinBits )\n : Window( pParent, nWinBits | WB_CLIPCHILDREN | WB_NODIALOGCONTROL | WB_DOCKBORDER )\n , bActive(sal_False)\n , bBorder(bHasBorder)\n{\n if ( !bHasBorder )\n SetBorderStyle( WINDOW_BORDER_NOBORDER );\n else\n SetBorderStyle( WINDOW_BORDER_NORMAL );\n \/\/SetActivateMode( ACTIVATE_MODE_GRABFOCUS );\n}\n\nvoid IFrameWindow_Impl::SetBorder( sal_Bool bNewBorder )\n{\n if ( bBorder != bNewBorder )\n {\n Size aSize = GetSizePixel();\n bBorder = bNewBorder;\n if ( bBorder )\n SetBorderStyle( WINDOW_BORDER_NORMAL );\n else\n SetBorderStyle( WINDOW_BORDER_NOBORDER );\n if ( GetSizePixel() != aSize )\n SetSizePixel( aSize );\n }\n}\n\n#define PROPERTY_UNBOUND 0\n\nSfxItemPropertyMap aIFramePropertyMap_Impl[] =\n{\n { \"FrameIsAutoBorder\", 17, 1, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },\n { \"FrameIsAutoScroll\", 17, 2, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },\n { \"FrameIsBorder\", 13, 3, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },\n { \"FrameIsScrollingMode\", 20, 4, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },\n { \"FrameMarginHeight\", 17, 5, &::getCppuType( (sal_Int32*)0 ), PROPERTY_UNBOUND, 0 },\n { \"FrameMarginWidth\", 16, 6, &::getCppuType( (sal_Int32*)0 ), PROPERTY_UNBOUND, 0 },\n { \"FrameName\", 9, 7, &::getCppuType((const ::rtl::OUString*)0), PROPERTY_UNBOUND, 0 },\n { \"FrameURL\", 8, 8, &::getCppuType((const ::rtl::OUString*)0), PROPERTY_UNBOUND, 0 },\n {0,0,0,0,0,0}\n};\n\nSFX_IMPL_XSERVICEINFO( IFrameObject, \"com.sun.star.embed.SpecialEmbeddedObject\", \"com.sun.star.comp.sfx2.IFrameObject\" )\nSFX_IMPL_SINGLEFACTORY( IFrameObject );\n\nIFrameObject::IFrameObject( const uno::Reference < lang::XMultiServiceFactory >& rFact )\n : mxFact( rFact )\n , maPropSet( aIFramePropertyMap_Impl )\n{\n}\n\nIFrameObject::~IFrameObject()\n{\n}\n\n\nvoid SAL_CALL IFrameObject::initialize( const uno::Sequence< uno::Any >& aArguments ) throw ( uno::Exception, uno::RuntimeException )\n{\n if ( aArguments.getLength() )\n aArguments[0] >>= mxObj;\n}\n\nsal_Bool SAL_CALL IFrameObject::load(\n const uno::Sequence < com::sun::star::beans::PropertyValue >& \/*lDescriptor*\/,\n const uno::Reference < frame::XFrame >& xFrame )\nthrow( uno::RuntimeException )\n{\n if ( SvtMiscOptions().IsPluginsEnabled() )\n {\n DBG_ASSERT( !mxFrame.is(), \"Frame already existing!\" );\n Window* pParent = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );\n IFrameWindow_Impl* pWin = new IFrameWindow_Impl( pParent, maFrmDescr.IsFrameBorderOn() );\n pWin->SetSizePixel( pParent->GetOutputSizePixel() );\n pWin->SetBackground();\n pWin->Show();\n\n uno::Reference < awt::XWindow > xWindow( pWin->GetComponentInterface(), uno::UNO_QUERY );\n xFrame->setComponent( xWindow, uno::Reference < frame::XController >() );\n\n \/\/ we must destroy the IFrame before the parent is destroyed\n xWindow->addEventListener( this );\n\n mxFrame = uno::Reference< frame::XFrame >( mxFact->createInstance( ::rtl::OUString::createFromAscii( \"com.sun.star.frame.Frame\" ) ),\n uno::UNO_QUERY );\n uno::Reference < awt::XWindow > xWin( pWin->GetComponentInterface(), uno::UNO_QUERY );\n mxFrame->initialize( xWin );\n mxFrame->setName( maFrmDescr.GetName() );\n\n uno::Reference< frame::XDispatchProvider > xProv( mxFrame, uno::UNO_QUERY );\n\n util::URL aTargetURL;\n aTargetURL.Complete = ::rtl::OUString( maFrmDescr.GetURL().GetMainURL( INetURLObject::NO_DECODE ) );\n uno::Reference < util::XURLTransformer > xTrans( mxFact->createInstance( rtl::OUString::createFromAscii(\"com.sun.star.util.URLTransformer\" )), uno::UNO_QUERY );\n xTrans->parseStrict( aTargetURL );\n\n uno::Sequence < beans::PropertyValue > aProps(2);\n aProps[0].Name = ::rtl::OUString::createFromAscii(\"PluginMode\");\n aProps[0].Value <<= (sal_Int16) 2;\n aProps[1].Name = ::rtl::OUString::createFromAscii(\"ReadOnly\");\n aProps[1].Value <<= (sal_Bool) sal_True;\n uno::Reference < frame::XDispatch > xDisp = xProv->queryDispatch( aTargetURL, ::rtl::OUString::createFromAscii(\"_self\"), 0 );\n if ( xDisp.is() )\n xDisp->dispatch( aTargetURL, aProps );\n\n return TRUE;\n }\n\n return FALSE;\n}\n\nvoid SAL_CALL IFrameObject::cancel() throw( com::sun::star::uno::RuntimeException )\n{\n try\n {\n uno::Reference < util::XCloseable > xClose( mxFrame, uno::UNO_QUERY );\n if ( xClose.is() )\n xClose->close( sal_True );\n mxFrame = 0;\n }\n catch ( uno::Exception& )\n {}\n}\n\nvoid SAL_CALL IFrameObject::close( sal_Bool \/*bDeliverOwnership*\/ ) throw( com::sun::star::util::CloseVetoException, com::sun::star::uno::RuntimeException )\n{\n}\n\nvoid SAL_CALL IFrameObject::addCloseListener( const com::sun::star::uno::Reference < com::sun::star::util::XCloseListener >& ) throw( com::sun::star::uno::RuntimeException )\n{\n}\n\nvoid SAL_CALL IFrameObject::removeCloseListener( const com::sun::star::uno::Reference < com::sun::star::util::XCloseListener >& ) throw( com::sun::star::uno::RuntimeException )\n{\n}\n\nvoid SAL_CALL IFrameObject::disposing( const com::sun::star::lang::EventObject& ) throw (com::sun::star::uno::RuntimeException)\n{\n cancel();\n}\n\nuno::Reference< beans::XPropertySetInfo > SAL_CALL IFrameObject::getPropertySetInfo() throw( ::com::sun::star::uno::RuntimeException )\n{\n return maPropSet.getPropertySetInfo();\n}\n\nvoid SAL_CALL IFrameObject::setPropertyValue(const ::rtl::OUString& aPropertyName, const uno::Any& aAny)\n throw ( beans::UnknownPropertyException, beans::PropertyVetoException, lang::IllegalArgumentException, lang::WrappedTargetException, uno::RuntimeException)\n{\n if ( aPropertyName.equalsAscii(\"FrameURL\") )\n {\n ::rtl::OUString aURL;\n aAny >>= aURL;\n maFrmDescr.SetURL( String(aURL) );\n }\n else if ( aPropertyName.equalsAscii(\"FrameName\") )\n {\n ::rtl::OUString aName;\n if ( aAny >>= aName )\n maFrmDescr.SetName( aName );\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsAutoScroll\") )\n {\n sal_Bool bIsAutoScroll = sal_Bool();\n if ( (aAny >>= bIsAutoScroll) && bIsAutoScroll )\n maFrmDescr.SetScrollingMode( ScrollingAuto );\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsScrollingMode\") )\n {\n sal_Bool bIsScroll = sal_Bool();\n if ( aAny >>= bIsScroll )\n maFrmDescr.SetScrollingMode( bIsScroll ? ScrollingYes : ScrollingNo );\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsBorder\") )\n {\n sal_Bool bIsBorder = sal_Bool();\n if ( aAny >>= bIsBorder )\n maFrmDescr.SetFrameBorder( bIsBorder );\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsAutoBorder\") )\n {\n sal_Bool bIsAutoBorder = sal_Bool();\n if ( (aAny >>= bIsAutoBorder) )\n {\n BOOL bBorder = maFrmDescr.IsFrameBorderOn();\n maFrmDescr.ResetBorder();\n if ( bIsAutoBorder )\n maFrmDescr.SetFrameBorder( bBorder );\n }\n }\n else if ( aPropertyName.equalsAscii(\"FrameMarginWidth\") )\n {\n sal_Int32 nMargin = 0;\n Size aSize = maFrmDescr.GetMargin();\n if ( aAny >>= nMargin )\n {\n aSize.Width() = nMargin;\n maFrmDescr.SetMargin( aSize );\n }\n }\n else if ( aPropertyName.equalsAscii(\"FrameMarginHeight\") )\n {\n sal_Int32 nMargin = 0;\n Size aSize = maFrmDescr.GetMargin();\n if ( aAny >>= nMargin )\n {\n aSize.Height() = nMargin;\n maFrmDescr.SetMargin( aSize );\n }\n }\n else\n throw beans::UnknownPropertyException();\n}\n\nuno::Any SAL_CALL IFrameObject::getPropertyValue(const ::rtl::OUString& aPropertyName)\n throw ( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException)\n{\n uno::Any aAny;\n if ( aPropertyName.equalsAscii(\"FrameURL\") )\n {\n aAny <<= ::rtl::OUString( maFrmDescr.GetURL().GetMainURL( INetURLObject::NO_DECODE ) );\n }\n else if ( aPropertyName.equalsAscii(\"FrameName\") )\n {\n aAny <<= ::rtl::OUString( maFrmDescr.GetName() );\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsAutoScroll\") )\n {\n sal_Bool bIsAutoScroll = ( maFrmDescr.GetScrollingMode() == ScrollingAuto );\n aAny <<= bIsAutoScroll;\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsScrollingMode\") )\n {\n sal_Bool bIsScroll = ( maFrmDescr.GetScrollingMode() == ScrollingYes );\n aAny <<= bIsScroll;\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsBorder\") )\n {\n sal_Bool bIsBorder = maFrmDescr.IsFrameBorderOn();\n aAny <<= bIsBorder;\n }\n else if ( aPropertyName.equalsAscii(\"FrameIsAutoBorder\") )\n {\n sal_Bool bIsAutoBorder = !maFrmDescr.IsFrameBorderSet();\n aAny <<= bIsAutoBorder;\n }\n else if ( aPropertyName.equalsAscii(\"FrameMarginWidth\") )\n {\n aAny <<= (sal_Int32 ) maFrmDescr.GetMargin().Width();\n }\n else if ( aPropertyName.equalsAscii(\"FrameMarginHeight\") )\n {\n aAny <<= (sal_Int32 ) maFrmDescr.GetMargin().Height();\n }\n else\n throw beans::UnknownPropertyException();\n return aAny;\n}\n\nvoid SAL_CALL IFrameObject::addPropertyChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )\n{\n}\n\nvoid SAL_CALL IFrameObject::removePropertyChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )\n{\n}\n\nvoid SAL_CALL IFrameObject::addVetoableChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )\n{\n}\n\nvoid SAL_CALL IFrameObject::removeVetoableChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )\n{\n}\n\n::sal_Int16 SAL_CALL IFrameObject::execute() throw (::com::sun::star::uno::RuntimeException)\n{\n SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();\n VclAbstractDialog* pDlg = pFact->CreateEditObjectDialog( NULL, SID_INSERT_FLOATINGFRAME, mxObj );\n if ( pDlg )\n pDlg->Execute();\n return 0;\n}\n\nvoid SAL_CALL IFrameObject::setTitle( const ::rtl::OUString& ) throw (::com::sun::star::uno::RuntimeException)\n{\n}\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: appbas.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2005-04-13 12:41:41 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SFX_APPBAS_HXX\n#define _SFX_APPBAS_HXX\n\n\n#ifndef _SBXDEF_HXX \/\/autogen\n#include \n#endif\n\nclass StarBASIC;\nclass SbxObject;\n\n\/\/=========================================================================\n\nSbxVariable* MakeVariable( StarBASIC *pBas, SbxObject *pObject,\n const char *pName, ULONG nSID, SbxDataType eType=SbxOBJECT,\n SbxClassType = SbxCLASS_PROPERTY );\n\n\n#endif\n\nINTEGRATION: CWS ooo19126 (1.2.132); FILE MERGED 2005\/09\/06 13:05:21 rt 1.2.132.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: appbas.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 18:54:18 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SFX_APPBAS_HXX\n#define _SFX_APPBAS_HXX\n\n\n#ifndef _SBXDEF_HXX \/\/autogen\n#include \n#endif\n\nclass StarBASIC;\nclass SbxObject;\n\n\/\/=========================================================================\n\nSbxVariable* MakeVariable( StarBASIC *pBas, SbxObject *pObject,\n const char *pName, ULONG nSID, SbxDataType eType=SbxOBJECT,\n SbxClassType = SbxCLASS_PROPERTY );\n\n\n#endif\n\n<|endoftext|>"} {"text":"#include \r\n#include \r\n#ifdef WIN32\r\n#include \r\n#endif\r\n#ifdef __APPLE__\r\n#include \r\n#else\r\n#include \r\n#endif\r\n\r\n#include \"raytracing.h\"\r\n\r\n\r\n\/\/temporary variables\r\n\/\/these are only used to illustrate \r\n\/\/a simple debug drawing. A ray \r\nVec3Df testRayOrigin;\r\nVec3Df testRayDestination;\r\nVec3Df testColor;\r\n\r\n\r\n\/\/use this function for any preprocessing of the mesh.\r\nvoid init()\r\n{\r\n\t\/\/load the mesh file\r\n\t\/\/please realize that not all OBJ files will successfully load.\r\n\t\/\/Nonetheless, if they come from Blender, they should, if they \r\n\t\/\/are exported as WavefrontOBJ.\r\n\t\/\/PLEASE ADAPT THE LINE BELOW TO THE FULL PATH OF THE dodgeColorTest.obj\r\n\t\/\/model, e.g., \"C:\/temp\/myData\/GraphicsIsFun\/dodgeColorTest.obj\", \r\n\t\/\/otherwise the application will not load properly\r\n\r\n\r\n\tMyMesh.loadMesh(FILE_LOCATION, true);\r\n\tMyMesh.computeVertexNormals();\r\n\r\n\t\/\/one first move: initialize the first light source\r\n\t\/\/at least ONE light source has to be in the scene!!!\r\n\t\/\/here, we set it to the current location of the camera\r\n\tMyLightPositions.push_back(MyCameraPosition);\r\n}\r\n\r\n\/\/return the color of your pixel.\r\nVec3Df performRayTracing(const Vec3Df & origin, const Vec3Df & dest)\r\n{\r\n\tint level = 0;\r\n\treturn trace(origin, dest, level);\r\n\r\n\t\/\/ if(intersect(level, ray, max, &hit)) {\r\n\t\/\/ Shade(level, hit, &color);\r\n\t\/\/ }\r\n\t\/\/ else\r\n\t\/\/ color=BackgroundColor\r\n\r\n\t\/\/return Vec3Df(dest[0],dest[1],dest[2]);\r\n}\r\n\r\nVec3Df trace(const Vec3Df & origin, const Vec3Df & dir, int level){\r\n\tfloat depth = FLT_MAX;\r\n\tVec3Df color = Vec3Df(0, 0, 0);\r\n\tfor (int i = 0; i < MyMesh.triangles.size(); i++){\r\n\t\tTriangle triangle = MyMesh.triangles.at(i);\r\n\t\tVertex v0 = MyMesh.vertices.at(triangle.v[0]);\r\n\t\tVertex v1 = MyMesh.vertices.at(triangle.v[1]);\r\n\t\tVertex v2 = MyMesh.vertices.at(triangle.v[2]);\r\n\r\n\t\tVec3Df N = Vec3Df(0, 0, 0);\r\n\t\tVec3Df intersection = rayTriangleIntersect(origin, dir, v0.p, v1.p, v2.p, depth, N);\r\n\t\tif (!isNulVector(intersection)){\r\n\t\t\t\/\/ save color and depth\r\n\t\t\tcolor = shade(dir, intersection, level, i, N);\r\n\t\t}\r\n\r\n\r\n\t}\r\n\treturn color;\r\n}\r\n\r\nVec3Df shade(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex, const Vec3Df N){\r\n\tVec3Df color = Vec3Df(0, 0, 0);\r\n\tVec3Df lightDirection = Vec3Df(0, 0, 0);\r\n\t\/\/lightDirection = lightVector(intersection, origin);\r\n\tcolor += diffuse(dir, N, triangleIndex);\r\n\tcolor += ambient(dir, intersection, level, triangleIndex);\r\n\tcolor += speculair(dir, intersection, level, triangleIndex);\r\n\treturn color;\r\n}\r\n\r\nVec3Df diffuse(const Vec3Df lightSource, const Vec3Df normal, int triangleIndex){\r\n\tVec3Df color = Vec3Df(0, 0, 0);\r\n\tunsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);\r\n\tcolor = MyMesh.materials.at(triMat).Kd();\r\n\r\n\t\/\/ diffuser = Kd * dot(lightsource, normal) * Od * Ld\r\n\t\/\/ Od = object color\r\n\t\/\/ Ld = lightSource color\r\n\t\/\/Vec3Df diffuser = color * (Vec3Df::dotProduct(lightSource, normal)) \/ pow(normal.getLength(), 2) * 1 * 1;\r\n\treturn color;\r\n}\r\n\r\nVec3Df ambient(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex){ \r\n\tVec3Df color = Vec3Df(0, 0, 0);\r\n\tunsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);\r\n\tcolor = MyMesh.materials.at(triMat).Ka();\r\n\treturn color;\r\n}\r\n\r\nVec3Df speculair(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex){\r\n\tVec3Df color = Vec3Df(0, 0, 0);\r\n\tunsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);\r\n\tcolor = MyMesh.materials.at(triMat).Ks();\r\n\treturn color;\r\n}\r\n\r\nVec3Df lightVector(const Vec3Df point, const Vec3Df lightPoint){\r\n\tVec3Df lightDir = Vec3Df(0, 0, 0);\r\n\tlightDir = lightPoint - point;\r\n\treturn lightDir;\r\n}\r\n\r\nVec3Df reflectionVector(const Vec3Df lightDirection, const Vec3Df normalVector) {\r\n\tVec3Df reflection = Vec3Df(0, 0, 0);\r\n\treflection = lightDirection - 2 * (Vec3Df::dotProduct(lightDirection, normalVector) \/ pow(normalVector.getLength(), 2))*normalVector;\r\n\treturn reflection;\r\n}\r\n\/\/ We can also add textures!\r\n\r\n\/\/ The source of this function is:\r\n\/\/ http:\/\/www.scratchapixel.com\/lessons\/3d-basic-rendering\/ray-tracing-rendering-a-triangle\/ray-triangle-intersection-geometric-solution\r\n\/\/ Returns the point of intersection\r\nVec3Df rayTriangleIntersect(const Vec3Df &orig, const Vec3Df &dir, const Vec3Df v0, const Vec3Df v1, const Vec3Df v2, float &depth, Vec3Df &N)\r\n{\r\n\tVec3Df nulVector = Vec3Df(0, 0, 0);\r\n\t\/\/ compute plane's normal\r\n\tVec3Df v0v1 = v1 - v0;\r\n\tVec3Df v0v2 = v2 - v0;\r\n\t\/\/ no need to normalize\r\n\tN = Vec3Df::crossProduct(v0v1, v0v2); \/\/ N\r\n\r\n\t\/\/ Step 1: finding P (the point where the ray intersects the plane)\r\n\r\n\t\/\/ check if ray and plane are parallel ?\r\n\tfloat NdotRayDirection = Vec3Df::dotProduct(N, dir);\r\n\tif (fabs(NdotRayDirection) < 0.000000001) \/\/ almost 0\r\n\t\treturn nulVector; \/\/ they are parallel so they don't intersect !\r\n\r\n\t\/\/ compute d parameter using equation 2 (d is the distance from the origin (0, 0, 0) to the plane)\r\n\tfloat d = Vec3Df::dotProduct(N, v0);\r\n\r\n\t\/\/ compute t (equation 3) (t is distance from the ray origin to P)\r\n\tfloat t = (-Vec3Df::dotProduct(N, orig) + d) \/ NdotRayDirection;\r\n\t\/\/ check if the triangle is in behind the ray\r\n\tif (t < 0) return nulVector; \/\/ the triangle is behind\r\n\tif (t > depth) return nulVector; \/\/ already have something closerby\r\n\r\n\t\/\/ compute the intersection point P using equation 1\r\n\tVec3Df P = orig + t * dir;\r\n\r\n\t\/\/ Step 2: inside-outside test\r\n\tVec3Df C; \/\/ vector perpendicular to triangle's plane\r\n\r\n\t\/\/ edge 0\r\n\tVec3Df edge0 = v1 - v0;\r\n\tVec3Df vp0 = P - v0;\r\n\tC = Vec3Df::crossProduct(edge0, vp0);\r\n\tif (Vec3Df::dotProduct(N, C) < 0) return nulVector; \/\/ P is on the right side\r\n\r\n\t\/\/ edge 1\r\n\tVec3Df edge1 = v2 - v1;\r\n\tVec3Df vp1 = P - v1;\r\n\tC = Vec3Df::crossProduct(edge1, vp1);\r\n\tif (Vec3Df::dotProduct(N, C) < 0) return nulVector; \/\/ P is on the right side\r\n\r\n\t\/\/ edge 2\r\n\tVec3Df edge2 = v0 - v2;\r\n\tVec3Df vp2 = P - v2;\r\n\tC = Vec3Df::crossProduct(edge2, vp2);\r\n\tif (Vec3Df::dotProduct(N, C) < 0) return nulVector; \/\/ P is on the right side;\r\n\r\n\tdepth = t;\r\n\treturn P; \/\/ this is the intersectionpoint\r\n}\r\n\r\n\/\/Shade(level, hit, &color){\r\n\/\/ for each lightsource\r\n\/\/ ComputeDirectLight(hit, &directColor);\r\n\/\/ if(material reflects && (level < maxLevel))\r\n\/\/ computeReflectedRay(hit, &reflectedray);\r\n\/\/ Trace(level+1, reflectedRay, &reflectedColor);\r\n\/\/ color = directColor + reflection * reflectedcolor + transmission * refractedColor;\r\n\/\/}\r\n\r\n\r\n\r\nvoid yourDebugDraw()\r\n{\r\n\t\/\/draw open gl debug stuff\r\n\t\/\/this function is called every frame\r\n\r\n\t\/\/let's draw the mesh\r\n\tMyMesh.draw();\r\n\r\n\t\/\/let's draw the lights in the scene as points\r\n\tglPushAttrib(GL_ALL_ATTRIB_BITS); \/\/store all GL attributes\r\n\tglDisable(GL_LIGHTING);\r\n\tglColor3f(1, 1, 1);\r\n\tglPointSize(10);\r\n\tglBegin(GL_POINTS);\r\n\tfor (int i = 0; idiffusing small change#include \r\n#include \r\n#ifdef WIN32\r\n#include \r\n#endif\r\n#ifdef __APPLE__\r\n#include \r\n#else\r\n#include \r\n#endif\r\n\r\n#include \"raytracing.h\"\r\n\r\n\r\n\/\/temporary variables\r\n\/\/these are only used to illustrate \r\n\/\/a simple debug drawing. A ray \r\nVec3Df testRayOrigin;\r\nVec3Df testRayDestination;\r\nVec3Df testColor;\r\n\r\n\r\n\/\/use this function for any preprocessing of the mesh.\r\nvoid init()\r\n{\r\n\t\/\/load the mesh file\r\n\t\/\/please realize that not all OBJ files will successfully load.\r\n\t\/\/Nonetheless, if they come from Blender, they should, if they \r\n\t\/\/are exported as WavefrontOBJ.\r\n\t\/\/PLEASE ADAPT THE LINE BELOW TO THE FULL PATH OF THE dodgeColorTest.obj\r\n\t\/\/model, e.g., \"C:\/temp\/myData\/GraphicsIsFun\/dodgeColorTest.obj\", \r\n\t\/\/otherwise the application will not load properly\r\n\r\n\r\n\tMyMesh.loadMesh(FILE_LOCATION, true);\r\n\tMyMesh.computeVertexNormals();\r\n\r\n\t\/\/one first move: initialize the first light source\r\n\t\/\/at least ONE light source has to be in the scene!!!\r\n\t\/\/here, we set it to the current location of the camera\r\n\tMyLightPositions.push_back(MyCameraPosition);\r\n}\r\n\r\n\/\/return the color of your pixel.\r\nVec3Df performRayTracing(const Vec3Df & origin, const Vec3Df & dest)\r\n{\r\n\tint level = 0;\r\n\treturn trace(origin, dest, level);\r\n\r\n\t\/\/ if(intersect(level, ray, max, &hit)) {\r\n\t\/\/ Shade(level, hit, &color);\r\n\t\/\/ }\r\n\t\/\/ else\r\n\t\/\/ color=BackgroundColor\r\n\r\n\t\/\/return Vec3Df(dest[0],dest[1],dest[2]);\r\n}\r\n\r\nVec3Df trace(const Vec3Df & origin, const Vec3Df & dir, int level){\r\n\tfloat depth = FLT_MAX;\r\n\tVec3Df color = Vec3Df(0, 0, 0);\r\n\tfor (int i = 0; i < MyMesh.triangles.size(); i++){\r\n\t\tTriangle triangle = MyMesh.triangles.at(i);\r\n\t\tVertex v0 = MyMesh.vertices.at(triangle.v[0]);\r\n\t\tVertex v1 = MyMesh.vertices.at(triangle.v[1]);\r\n\t\tVertex v2 = MyMesh.vertices.at(triangle.v[2]);\r\n\r\n\t\tVec3Df N = Vec3Df(0, 0, 0);\r\n\t\tVec3Df intersection = rayTriangleIntersect(origin, dir, v0.p, v1.p, v2.p, depth, N);\r\n\t\tif (!isNulVector(intersection)){\r\n\t\t\t\/\/ save color and depth\r\n\t\t\tcolor = shade(dir, intersection, level, i, N);\r\n\t\t}\r\n\r\n\r\n\t}\r\n\treturn color;\r\n}\r\n\r\nVec3Df shade(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex, const Vec3Df N){\r\n\tVec3Df color = Vec3Df(0, 0, 0);\r\n\tVec3Df lightDirection = Vec3Df(0, 0, 0);\r\n\tlightDirection = lightVector(intersection, dir);\r\n\tcolor += diffuse(intersection, N, triangleIndex);\r\n\tcolor += ambient(dir, intersection, level, triangleIndex);\r\n\tcolor += speculair(dir, intersection, level, triangleIndex);\r\n\treturn color;\r\n}\r\n\r\nVec3Df diffuse(const Vec3Df lightSource, const Vec3Df normal, int triangleIndex){\r\n\tVec3Df color = Vec3Df(0, 0, 0);\r\n\tunsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);\r\n\tcolor = MyMesh.materials.at(triMat).Kd();\r\n\r\n\t\/\/ diffuser = Kd * dot(lightsource, normal) * Od * Ld\r\n\t\/\/ Od = object color\r\n\t\/\/ Ld = lightSource color\r\n\tVec3Df diffuser = color * (Vec3Df::dotProduct(lightSource, normal)) \/ pow(normal.getLength(), 2) * 1 * 1;\r\n\treturn diffuser;\r\n}\r\n\r\nVec3Df ambient(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex){ \r\n\tVec3Df color = Vec3Df(0, 0, 0);\r\n\tunsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);\r\n\tcolor = MyMesh.materials.at(triMat).Ka();\r\n\treturn color;\r\n}\r\n\r\nVec3Df speculair(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex){\r\n\tVec3Df color = Vec3Df(0, 0, 0);\r\n\tunsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);\r\n\tcolor = MyMesh.materials.at(triMat).Ks();\r\n\treturn color;\r\n}\r\n\r\nVec3Df lightVector(const Vec3Df point, const Vec3Df lightPoint){\r\n\tVec3Df lightDir = Vec3Df(0, 0, 0);\r\n\tlightDir = point - lightPoint;\r\n\treturn lightDir;\r\n}\r\n\r\nVec3Df reflectionVector(const Vec3Df lightDirection, const Vec3Df normalVector) {\r\n\tVec3Df reflection = Vec3Df(0, 0, 0);\r\n\treflection = lightDirection - 2 * (Vec3Df::dotProduct(lightDirection, normalVector) \/ pow(normalVector.getLength(), 2))*normalVector;\r\n\treturn reflection;\r\n}\r\n\/\/ We can also add textures!\r\n\r\n\/\/ The source of this function is:\r\n\/\/ http:\/\/www.scratchapixel.com\/lessons\/3d-basic-rendering\/ray-tracing-rendering-a-triangle\/ray-triangle-intersection-geometric-solution\r\n\/\/ Returns the point of intersection\r\nVec3Df rayTriangleIntersect(const Vec3Df &orig, const Vec3Df &dir, const Vec3Df v0, const Vec3Df v1, const Vec3Df v2, float &depth, Vec3Df &N)\r\n{\r\n\tVec3Df nulVector = Vec3Df(0, 0, 0);\r\n\t\/\/ compute plane's normal\r\n\tVec3Df v0v1 = v1 - v0;\r\n\tVec3Df v0v2 = v2 - v0;\r\n\t\/\/ no need to normalize\r\n\tN = Vec3Df::crossProduct(v0v1, v0v2); \/\/ N\r\n\r\n\t\/\/ Step 1: finding P (the point where the ray intersects the plane)\r\n\r\n\t\/\/ check if ray and plane are parallel ?\r\n\tfloat NdotRayDirection = Vec3Df::dotProduct(N, dir);\r\n\tif (fabs(NdotRayDirection) < 0.000000001) \/\/ almost 0\r\n\t\treturn nulVector; \/\/ they are parallel so they don't intersect !\r\n\r\n\t\/\/ compute d parameter using equation 2 (d is the distance from the origin (0, 0, 0) to the plane)\r\n\tfloat d = Vec3Df::dotProduct(N, v0);\r\n\r\n\t\/\/ compute t (equation 3) (t is distance from the ray origin to P)\r\n\tfloat t = (-Vec3Df::dotProduct(N, orig) + d) \/ NdotRayDirection;\r\n\t\/\/ check if the triangle is in behind the ray\r\n\tif (t < 0) return nulVector; \/\/ the triangle is behind\r\n\tif (t > depth) return nulVector; \/\/ already have something closerby\r\n\r\n\t\/\/ compute the intersection point P using equation 1\r\n\tVec3Df P = orig + t * dir;\r\n\r\n\t\/\/ Step 2: inside-outside test\r\n\tVec3Df C; \/\/ vector perpendicular to triangle's plane\r\n\r\n\t\/\/ edge 0\r\n\tVec3Df edge0 = v1 - v0;\r\n\tVec3Df vp0 = P - v0;\r\n\tC = Vec3Df::crossProduct(edge0, vp0);\r\n\tif (Vec3Df::dotProduct(N, C) < 0) return nulVector; \/\/ P is on the right side\r\n\r\n\t\/\/ edge 1\r\n\tVec3Df edge1 = v2 - v1;\r\n\tVec3Df vp1 = P - v1;\r\n\tC = Vec3Df::crossProduct(edge1, vp1);\r\n\tif (Vec3Df::dotProduct(N, C) < 0) return nulVector; \/\/ P is on the right side\r\n\r\n\t\/\/ edge 2\r\n\tVec3Df edge2 = v0 - v2;\r\n\tVec3Df vp2 = P - v2;\r\n\tC = Vec3Df::crossProduct(edge2, vp2);\r\n\tif (Vec3Df::dotProduct(N, C) < 0) return nulVector; \/\/ P is on the right side;\r\n\r\n\tdepth = t;\r\n\treturn P; \/\/ this is the intersectionpoint\r\n}\r\n\r\n\/\/Shade(level, hit, &color){\r\n\/\/ for each lightsource\r\n\/\/ ComputeDirectLight(hit, &directColor);\r\n\/\/ if(material reflects && (level < maxLevel))\r\n\/\/ computeReflectedRay(hit, &reflectedray);\r\n\/\/ Trace(level+1, reflectedRay, &reflectedColor);\r\n\/\/ color = directColor + reflection * reflectedcolor + transmission * refractedColor;\r\n\/\/}\r\n\r\n\r\n\r\nvoid yourDebugDraw()\r\n{\r\n\t\/\/draw open gl debug stuff\r\n\t\/\/this function is called every frame\r\n\r\n\t\/\/let's draw the mesh\r\n\tMyMesh.draw();\r\n\r\n\t\/\/let's draw the lights in the scene as points\r\n\tglPushAttrib(GL_ALL_ATTRIB_BITS); \/\/store all GL attributes\r\n\tglDisable(GL_LIGHTING);\r\n\tglColor3f(1, 1, 1);\r\n\tglPointSize(10);\r\n\tglBegin(GL_POINTS);\r\n\tfor (int i = 0; i"} {"text":"#include \"socket_wrap.h\"\n\nstatic Nan::Persistent socket_constructor;\n\nSocketWrap::SocketWrap () {\n on_end = NULL;\n on_data = NULL;\n on_close = NULL;\n on_drain = NULL;\n on_error = NULL;\n on_connect = NULL;\n\n needs_drain = 0;\n\n write_buffer = (struct utp_iovec *) malloc(16 * sizeof(struct utp_iovec));\n write_buffer_length = 16;\n write_buffer_used = 0;\n write_buffer_offset = 0;\n}\n\nSocketWrap::~SocketWrap () {\n if (on_end) delete on_end;\n if (on_data) delete on_data;\n if (on_close) delete on_close;\n if (on_drain) delete on_drain;\n if (on_error) delete on_error;\n if (on_connect) delete on_connect;\n free(write_buffer);\n}\n\nint\nSocketWrap::Drain () {\n Nan::HandleScope scope;\n\n if (!this->write_buffer_used) return 0;\n\n int needs_drain = this->needs_drain;\n this->needs_drain = 0;\n\n int wrote = utp_uv_socket_writev(this->handle, this->socket, this->write_buffer, this->write_buffer_used);\n if (wrote < 0) return -1;\n\n size_t wrote_bytes = (size_t) wrote;\n struct utp_iovec *next = this->write_buffer + this->write_buffer_offset;\n\n while (wrote_bytes && this->write_buffer_used) {\n if (wrote_bytes >= next->iov_len) {\n wrote_bytes -= next->iov_len;\n this->write_buffer_offset++;\n next++;\n } else {\n char *base = (char *) next->iov_base;\n base += wrote_bytes;\n next->iov_base = base;\n next->iov_len -= wrote_bytes;\n wrote_bytes = 0;\n }\n }\n\n if (this->write_buffer_used == this->write_buffer_offset) {\n this->write_buffer_used = 0;\n this->write_buffer_offset = 0;\n if (needs_drain && this->on_drain) this->on_drain->Call(0, NULL);\n } else {\n this->needs_drain = 1;\n }\n\n return 0;\n}\n\nint\nSocketWrap::EnsureBuffer (int inc) {\n while (this->write_buffer_used + inc >= this->write_buffer_length) {\n size_t double_size = 2 * this->write_buffer_length * sizeof(struct utp_iovec);\n struct utp_iovec *bigger = (struct utp_iovec *) realloc(this->write_buffer, double_size);\n if (bigger == NULL) return 1;\n this->write_buffer_length *= 2;\n this->write_buffer = bigger;\n }\n return 0;\n}\n\nNAN_METHOD(SocketWrap::New) {\n SocketWrap* obj = new SocketWrap();\n obj->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n}\n\nNAN_METHOD(SocketWrap::Write) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n\n if (self->EnsureBuffer(1)) {\n Nan::ThrowError(\"Could not grow write buffer\");\n return;\n }\n\n struct utp_iovec *holder = self->write_buffer + (self->write_buffer_used++);\n\n Local buffer = info[0]->ToObject();\n holder->iov_len = node::Buffer::Length(buffer);\n holder->iov_base = node::Buffer::Data(buffer);\n\n if (self->Drain()) {\n Nan::ThrowError(\"Write failed\");\n return;\n }\n\n if (self->write_buffer_used == 0) info.GetReturnValue().Set(Nan::True());\n else info.GetReturnValue().Set(Nan::False());\n}\n\nNAN_METHOD(SocketWrap::Writev) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n\n Local writes = info[0].As();\n Local chunk = Nan::New(\"chunk\").ToLocalChecked();\n uint32_t length = writes->Length();\n\n if (self->EnsureBuffer((int) length)) {\n Nan::ThrowError(\"Could not grow write buffer\");\n return;\n }\n\n struct utp_iovec *next = self->write_buffer + self->write_buffer_used;\n\n for (uint32_t i = 0; i < length; i++) {\n Local buffer = Nan::Get(writes->Get(i)->ToObject(), chunk).ToLocalChecked();\n\n next->iov_len = node::Buffer::Length(buffer);\n next->iov_base = node::Buffer::Data(buffer);\n\n next++;\n self->write_buffer_used++;\n }\n\n if (self->Drain()) {\n Nan::ThrowError(\"Write failed\");\n return;\n }\n\n if (self->write_buffer_used == 0) info.GetReturnValue().Set(Nan::True());\n else info.GetReturnValue().Set(Nan::False());\n}\n\nNAN_METHOD(SocketWrap::End) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n utp_uv_socket_end(self->handle, self->socket);\n}\n\nNAN_METHOD(SocketWrap::OnData) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n self->on_data = new Nan::Callback(info[0].As());\n}\n\nNAN_METHOD(SocketWrap::OnEnd) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n self->on_end = new Nan::Callback(info[0].As());\n}\n\nNAN_METHOD(SocketWrap::OnClose) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n self->on_close = new Nan::Callback(info[0].As());\n}\n\nNAN_METHOD(SocketWrap::OnDrain) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n self->on_drain = new Nan::Callback(info[0].As());\n}\n\nNAN_METHOD(SocketWrap::OnError) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n self->on_error = new Nan::Callback(info[0].As());\n}\n\nNAN_METHOD(SocketWrap::OnConnect) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n self->on_connect = new Nan::Callback(info[0].As());\n}\n\nvoid SocketWrap::Init () {\n Local tpl = Nan::New(SocketWrap::New);\n socket_constructor.Reset(tpl);\n tpl->SetClassName(Nan::New(\"SocketWrap\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n Nan::SetPrototypeMethod(tpl, \"write\", SocketWrap::Write);\n Nan::SetPrototypeMethod(tpl, \"writev\", SocketWrap::Writev);\n Nan::SetPrototypeMethod(tpl, \"end\", SocketWrap::End);\n Nan::SetPrototypeMethod(tpl, \"ondata\", SocketWrap::OnData);\n Nan::SetPrototypeMethod(tpl, \"onend\", SocketWrap::OnEnd);\n Nan::SetPrototypeMethod(tpl, \"onclose\", SocketWrap::OnClose);\n Nan::SetPrototypeMethod(tpl, \"ondrain\", SocketWrap::OnDrain);\n Nan::SetPrototypeMethod(tpl, \"onerror\", SocketWrap::OnError);\n Nan::SetPrototypeMethod(tpl, \"onconnect\", SocketWrap::OnConnect);\n}\n\nLocal SocketWrap::NewInstance () {\n Nan::EscapableHandleScope scope;\n\n Local instance;\n\n Local constructorHandle = Nan::New(socket_constructor);\n instance = constructorHandle->GetFunction()->NewInstance(0, NULL);\n\n return scope.Escape(instance);\n}\nfix some drain bugs#include \"socket_wrap.h\"\n\nstatic Nan::Persistent socket_constructor;\n\nSocketWrap::SocketWrap () {\n on_end = NULL;\n on_data = NULL;\n on_close = NULL;\n on_drain = NULL;\n on_error = NULL;\n on_connect = NULL;\n\n needs_drain = 0;\n\n write_buffer = (struct utp_iovec *) malloc(16 * sizeof(struct utp_iovec));\n write_buffer_length = 16;\n write_buffer_used = 0;\n write_buffer_offset = 0;\n}\n\nSocketWrap::~SocketWrap () {\n if (on_end) delete on_end;\n if (on_data) delete on_data;\n if (on_close) delete on_close;\n if (on_drain) delete on_drain;\n if (on_error) delete on_error;\n if (on_connect) delete on_connect;\n free(write_buffer);\n}\n\nint\nSocketWrap::Drain () {\n Nan::HandleScope scope;\n\n size_t len = this->write_buffer_used - this->write_buffer_offset;\n if (!len) return 0;\n\n struct utp_iovec *next = this->write_buffer + this->write_buffer_offset;\n int needs_drain = this->needs_drain;\n this->needs_drain = 0;\n\n int wrote = utp_uv_socket_writev(this->handle, this->socket, next, len);\n if (wrote < 0) return -1;\n\n size_t wrote_bytes = (size_t) wrote;\n\n while (wrote_bytes) {\n if (wrote_bytes >= next->iov_len) {\n wrote_bytes -= next->iov_len;\n this->write_buffer_offset++;\n next++;\n } else {\n char *base = (char *) next->iov_base;\n base += wrote_bytes;\n next->iov_base = base;\n next->iov_len -= wrote_bytes;\n wrote_bytes = 0;\n }\n }\n\n if (this->write_buffer_used == this->write_buffer_offset) {\n this->write_buffer_used = 0;\n this->write_buffer_offset = 0;\n if (needs_drain && this->on_drain) this->on_drain->Call(0, NULL);\n } else {\n this->needs_drain = 1;\n }\n\n return 0;\n}\n\nint\nSocketWrap::EnsureBuffer (int inc) {\n while (this->write_buffer_used + inc >= this->write_buffer_length) {\n size_t double_size = 2 * this->write_buffer_length * sizeof(struct utp_iovec);\n struct utp_iovec *bigger = (struct utp_iovec *) realloc(this->write_buffer, double_size);\n if (bigger == NULL) return 1;\n this->write_buffer_length *= 2;\n this->write_buffer = bigger;\n }\n return 0;\n}\n\nNAN_METHOD(SocketWrap::New) {\n SocketWrap* obj = new SocketWrap();\n obj->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n}\n\nNAN_METHOD(SocketWrap::Write) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n\n if (self->EnsureBuffer(1)) {\n Nan::ThrowError(\"Could not grow write buffer\");\n return;\n }\n\n struct utp_iovec *holder = self->write_buffer + (self->write_buffer_used++);\n\n Local buffer = info[0]->ToObject();\n holder->iov_len = node::Buffer::Length(buffer);\n holder->iov_base = node::Buffer::Data(buffer);\n\n if (self->Drain()) {\n Nan::ThrowError(\"Write failed\");\n return;\n }\n\n if (self->write_buffer_used == 0) info.GetReturnValue().Set(Nan::True());\n else info.GetReturnValue().Set(Nan::False());\n}\n\nNAN_METHOD(SocketWrap::Writev) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n\n Local writes = info[0].As();\n Local chunk = Nan::New(\"chunk\").ToLocalChecked();\n uint32_t length = writes->Length();\n\n if (self->EnsureBuffer((int) length)) {\n Nan::ThrowError(\"Could not grow write buffer\");\n return;\n }\n\n struct utp_iovec *next = self->write_buffer + self->write_buffer_used;\n\n for (uint32_t i = 0; i < length; i++) {\n Local buffer = Nan::Get(writes->Get(i)->ToObject(), chunk).ToLocalChecked();\n\n next->iov_len = node::Buffer::Length(buffer);\n next->iov_base = node::Buffer::Data(buffer);\n\n next++;\n self->write_buffer_used++;\n }\n\n if (self->Drain()) {\n Nan::ThrowError(\"Write failed\");\n return;\n }\n\n if (self->write_buffer_used == 0) info.GetReturnValue().Set(Nan::True());\n else info.GetReturnValue().Set(Nan::False());\n}\n\nNAN_METHOD(SocketWrap::End) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n utp_uv_socket_end(self->handle, self->socket);\n}\n\nNAN_METHOD(SocketWrap::OnData) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n self->on_data = new Nan::Callback(info[0].As());\n}\n\nNAN_METHOD(SocketWrap::OnEnd) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n self->on_end = new Nan::Callback(info[0].As());\n}\n\nNAN_METHOD(SocketWrap::OnClose) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n self->on_close = new Nan::Callback(info[0].As());\n}\n\nNAN_METHOD(SocketWrap::OnDrain) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n self->on_drain = new Nan::Callback(info[0].As());\n}\n\nNAN_METHOD(SocketWrap::OnError) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n self->on_error = new Nan::Callback(info[0].As());\n}\n\nNAN_METHOD(SocketWrap::OnConnect) {\n SocketWrap *self = Nan::ObjectWrap::Unwrap(info.This());\n self->on_connect = new Nan::Callback(info[0].As());\n}\n\nvoid SocketWrap::Init () {\n Local tpl = Nan::New(SocketWrap::New);\n socket_constructor.Reset(tpl);\n tpl->SetClassName(Nan::New(\"SocketWrap\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n Nan::SetPrototypeMethod(tpl, \"write\", SocketWrap::Write);\n Nan::SetPrototypeMethod(tpl, \"writev\", SocketWrap::Writev);\n Nan::SetPrototypeMethod(tpl, \"end\", SocketWrap::End);\n Nan::SetPrototypeMethod(tpl, \"ondata\", SocketWrap::OnData);\n Nan::SetPrototypeMethod(tpl, \"onend\", SocketWrap::OnEnd);\n Nan::SetPrototypeMethod(tpl, \"onclose\", SocketWrap::OnClose);\n Nan::SetPrototypeMethod(tpl, \"ondrain\", SocketWrap::OnDrain);\n Nan::SetPrototypeMethod(tpl, \"onerror\", SocketWrap::OnError);\n Nan::SetPrototypeMethod(tpl, \"onconnect\", SocketWrap::OnConnect);\n}\n\nLocal SocketWrap::NewInstance () {\n Nan::EscapableHandleScope scope;\n\n Local instance;\n\n Local constructorHandle = Nan::New(socket_constructor);\n instance = constructorHandle->GetFunction()->NewInstance(0, NULL);\n\n return scope.Escape(instance);\n}\n<|endoftext|>"} {"text":"\n#include \"test_utils.hh\"\n#include \n#include \"..\/registrardb.hh\"\n\nusing namespace std;\nbool sUseSyslog;\n\n\nstruct MyListener : public RegistrarDbListener {\n\tRegistrarDb::BindParameters params;\n\tMyListener(const RegistrarDb::BindParameters ¶ms): params(params) {};\n\tvirtual void onRecordFound(Record *r) {\n\/\/ \t\tcout << \"record found : \";\n\/\/ \t\tr->print(cout);\n\/\/ \t\tcout << endl;\n\t\tauto ecc=firstContact(*r);\n\t\tlong rExpire=ecc.mExpireAt-ecc.mUpdatedTime;\n\t\tcheck(\"expire\",atol(params.sip.contact->m_expires), rExpire);\n\t}\n\tvirtual void onError() {\n\t\tBAD(\"RegistrarDbListener:error\");\n\t}\n\tvirtual void onInvalid() {\n\t\tBAD(\"RegistrarDbListener:invalid\");\n\t}\n};\n\nSofiaHome home;\n\n\nvoid checkExpireHandling() {\n\tcheck(\"resolve expire1\", ExtendedContact::resolve_expire(NULL, 5), 5);\n\tcheck(\"resolve expire2\", ExtendedContact::resolve_expire(NULL, -1), -1);\n\tcheck(\"resolve expire3\", ExtendedContact::resolve_expire(\"5\", 6), 5);\n\tcheck(\"resolve expire4\", ExtendedContact::resolve_expire(\"5\", -1), 5);\n}\n\nstatic sip_contact_t *uid_ct(const char *urlparams, const char* ctparams) {\n\treturn sip_contact_format(\n\t\thome.h, \"<%s%s>%s\", \"sip:localhost:12345\",\n\t\turlparams,\n\t\tctparams);\n}\nvoid checkUniqueIdExtraction() {\n\t#define UID_PARAM theparam\n\tstring theparam = \"UID_PARAM\";\n\tcheck(\"+sip.instance in ct param\",\n\t\tRecord::extractUniqueId(uid_ct(\"\", \";+sip.instance=UID_PARAM\"))\n\t\t, theparam);\n\n\tcheck(\"+sip.instance in url param\",\n\t\tRecord::extractUniqueId(uid_ct(\";+sip.instance=UID_PARAM\", \"\"))\n\t\t, theparam);\n\n\tcheck(\"line in ct param\",\n\t\tRecord::extractUniqueId(uid_ct(\"\", \";line=UID_PARAM\"))\n\t\t, theparam);\n\n\tcheck(\"line url param\",\n\t\tRecord::extractUniqueId(uid_ct(\";line=UID_PARAM\", \"\"))\n\t\t, theparam);\n}\nint main(int argc, char **argv) {\n\tinit_tests();\n\n\tcheckExpireHandling();\n\tcheckUniqueIdExtraction();\n\n\tint expire_delta= 1000;\n\tlist paths{\"path1\", \"path2\", \"path3\"};\n\tstring contactid {\"ip:5223\"};\n\tstring callid {\"callid\"};\n\tstring line {\"line\"};\n\tstring contact = \"sip:\" + contactid + \";line=\"+line;\n\tstring contactWithChev = \"<\" + contact + \">\";\n\tuint32_t cseq=123456;\n\tfloat quality=1;\n\tbool alias=false;\n\tconst url_t *from=url_make(home.h, \"sip:guillaume@bc\");\n\n\tExtendedContactCommon ecc(contactid.c_str(),paths, callid.c_str(), line.c_str());\n\n\tsip_contact_t *sip_contact= sip_contact_format(home.h, \"<%s>;q=%f;expires=%d\",\n\t\t\tcontact.c_str(), quality, expire_delta);\n\tsip_path_t *sip_path=path_fromstl(home.h ,paths);\n\n\t\n\tRegistrarDbInternal registrar(\"preferred_ip\");\n\tRegistrarDb::BindParameters params(\n\t\tRegistrarDb::BindParameters::SipParams(\n\t\t\tfrom, sip_contact, callid.c_str(), cseq, sip_path\n\t\t), 55555, alias\n\t);\n\tauto listener=make_shared(params);\n\tregistrar.bind(params, listener);\n\n\tregistrar.clearAll();\n\tcout << \"success\" << endl;\n\treturn 0;\n}\n\nCorrect include for out-of-source compilation\n#include \"test_utils.hh\"\n#include \"..\/registrardb-internal.hh\"\n#include \"..\/registrardb.hh\"\n\nusing namespace std;\nbool sUseSyslog;\n\n\nstruct MyListener : public RegistrarDbListener {\n\tRegistrarDb::BindParameters params;\n\tMyListener(const RegistrarDb::BindParameters ¶ms): params(params) {};\n\tvirtual void onRecordFound(Record *r) {\n\/\/ \t\tcout << \"record found : \";\n\/\/ \t\tr->print(cout);\n\/\/ \t\tcout << endl;\n\t\tauto ecc=firstContact(*r);\n\t\tlong rExpire=ecc.mExpireAt-ecc.mUpdatedTime;\n\t\tcheck(\"expire\",atol(params.sip.contact->m_expires), rExpire);\n\t}\n\tvirtual void onError() {\n\t\tBAD(\"RegistrarDbListener:error\");\n\t}\n\tvirtual void onInvalid() {\n\t\tBAD(\"RegistrarDbListener:invalid\");\n\t}\n};\n\nSofiaHome home;\n\n\nvoid checkExpireHandling() {\n\tcheck(\"resolve expire1\", ExtendedContact::resolve_expire(NULL, 5), 5);\n\tcheck(\"resolve expire2\", ExtendedContact::resolve_expire(NULL, -1), -1);\n\tcheck(\"resolve expire3\", ExtendedContact::resolve_expire(\"5\", 6), 5);\n\tcheck(\"resolve expire4\", ExtendedContact::resolve_expire(\"5\", -1), 5);\n}\n\nstatic sip_contact_t *uid_ct(const char *urlparams, const char* ctparams) {\n\treturn sip_contact_format(\n\t\thome.h, \"<%s%s>%s\", \"sip:localhost:12345\",\n\t\turlparams,\n\t\tctparams);\n}\nvoid checkUniqueIdExtraction() {\n\t#define UID_PARAM theparam\n\tstring theparam = \"UID_PARAM\";\n\tcheck(\"+sip.instance in ct param\",\n\t\tRecord::extractUniqueId(uid_ct(\"\", \";+sip.instance=UID_PARAM\"))\n\t\t, theparam);\n\n\tcheck(\"+sip.instance in url param\",\n\t\tRecord::extractUniqueId(uid_ct(\";+sip.instance=UID_PARAM\", \"\"))\n\t\t, theparam);\n\n\tcheck(\"line in ct param\",\n\t\tRecord::extractUniqueId(uid_ct(\"\", \";line=UID_PARAM\"))\n\t\t, theparam);\n\n\tcheck(\"line url param\",\n\t\tRecord::extractUniqueId(uid_ct(\";line=UID_PARAM\", \"\"))\n\t\t, theparam);\n}\nint main(int argc, char **argv) {\n\tinit_tests();\n\n\tcheckExpireHandling();\n\tcheckUniqueIdExtraction();\n\n\tint expire_delta= 1000;\n\tlist paths{\"path1\", \"path2\", \"path3\"};\n\tstring contactid {\"ip:5223\"};\n\tstring callid {\"callid\"};\n\tstring line {\"line\"};\n\tstring contact = \"sip:\" + contactid + \";line=\"+line;\n\tstring contactWithChev = \"<\" + contact + \">\";\n\tuint32_t cseq=123456;\n\tfloat quality=1;\n\tbool alias=false;\n\tconst url_t *from=url_make(home.h, \"sip:guillaume@bc\");\n\n\tExtendedContactCommon ecc(contactid.c_str(),paths, callid.c_str(), line.c_str());\n\n\tsip_contact_t *sip_contact= sip_contact_format(home.h, \"<%s>;q=%f;expires=%d\",\n\t\t\tcontact.c_str(), quality, expire_delta);\n\tsip_path_t *sip_path=path_fromstl(home.h ,paths);\n\n\t\n\tRegistrarDbInternal registrar(\"preferred_ip\");\n\tRegistrarDb::BindParameters params(\n\t\tRegistrarDb::BindParameters::SipParams(\n\t\t\tfrom, sip_contact, callid.c_str(), cseq, sip_path\n\t\t), 55555, alias\n\t);\n\tauto listener=make_shared(params);\n\tregistrar.bind(params, listener);\n\n\tregistrar.clearAll();\n\tcout << \"success\" << endl;\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"\n#if defined(USE_SDL2)\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if defined(__APPLE__) \/* Brew got the headers wrong here *\/\n# include \n#else\n# include \n#endif\n\n#include \"ifict.h\"\n#include \"utils.h\"\n#include \"debug.h\"\n#include \"fatal.h\"\n#include \"palette.h\"\n\nSDL_Window*\t\t\tsdl_window = NULL;\nSDL_Surface*\t\t\tsdl_window_surface = NULL;\nSDL_Surface*\t\t\tsdl_game_surface = NULL;\nSDL_Palette*\t\t\tsdl_game_palette = NULL;\nSDL_Color\t\t\tsdl_pal[256];\nUint32\t\t\t\tsdl_ticks_base = 0; \/* use Uint32 type provided by SDL2 here to avoid problems *\/\nbool\t\t\t\tsdl_signal_to_quit = false;\nifevidinfo_t\t\t\tifevidinfo_sdl2;\n\nstatic void p_SetPaletteColors(const unsigned int first,const unsigned int count,IFEPaletteEntry *pal) {\n\tunsigned int i;\n\n\tpriv_SetPaletteColorsRangeCheck(first,count);\n\n\tfor (i=0;i < count;i++) {\n\t\tsdl_pal[i+first].r = pal[i].r;\n\t\tsdl_pal[i+first].g = pal[i].g;\n\t\tsdl_pal[i+first].b = pal[i].b;\n\t\tsdl_pal[i+first].a = 0xFFu;\n\t}\n\n\tif (SDL_SetPaletteColors(sdl_game_palette,sdl_pal,first,count) != 0)\n\t\tIFEFatalError(\"SDL2 game palette set colors\");\n}\n\nstatic uint32_t p_GetTicks(void) {\n\treturn uint32_t(SDL_GetTicks() - sdl_ticks_base);\n}\n\nstatic void p_ResetTicks(const uint32_t base) {\n\tsdl_ticks_base += base; \/* NTS: Use return value of IFEGetTicks() *\/\n}\n\nstatic void p_UpdateFullScreen(void) {\n\tif (SDL_BlitSurface(sdl_game_surface,NULL,sdl_window_surface,NULL) != 0)\n\t\tIFEFatalError(\"Game to window BlitSurface\");\n\n\tif (SDL_UpdateWindowSurface(sdl_window) != 0)\n\t\tIFEFatalError(\"Window surface update\");\n}\n\nstatic ifevidinfo_t* p_GetVidInfo(void) {\n\treturn &ifevidinfo_sdl2;\n}\n\nstatic bool p_UserWantsToQuit(void) {\n\treturn sdl_signal_to_quit;\n}\n\nstatic void priv_ProcessEvent(SDL_Event &ev) {\n\tif (ev.type == SDL_QUIT) {\n\t\tsdl_signal_to_quit = true;\n\t}\n}\n\nstatic void p_CheckEvents(void) {\n\tSDL_Event ev;\n\n\tif (SDL_PollEvent(&ev))\n\t\tpriv_ProcessEvent(ev);\n}\n\nstatic void p_WaitEvent(const int wait_ms) {\n\tSDL_Event ev;\n\n\tif (SDL_WaitEventTimeout(&ev,wait_ms))\n\t\tpriv_ProcessEvent(ev);\n}\n\nstatic bool p_BeginScreenDraw(void) {\n\tif (SDL_MUSTLOCK(sdl_game_surface) && SDL_LockSurface(sdl_game_surface) != 0)\n\t\treturn false;\n\tif (sdl_game_surface->pixels == NULL)\n\t\tIFEFatalError(\"SDL2 game surface pixels == NULL\"); \/* that's a BUG if this happens! *\/\n\tif (sdl_game_surface->pitch < 0)\n\t\tIFEFatalError(\"SDL2 game surface pitch is negative\");\n\n\tifevidinfo_sdl2.buf_base = ifevidinfo_sdl2.buf_first_row = (unsigned char*)(sdl_game_surface->pixels);\n\treturn true;\n}\n\nstatic void p_EndScreenDraw(void) {\n\tif (SDL_MUSTLOCK(sdl_game_surface))\n\t\tSDL_UnlockSurface(sdl_game_surface);\n\n\tifevidinfo_sdl2.buf_base = ifevidinfo_sdl2.buf_first_row = NULL;\n}\n\nstatic void p_ShutdownVideo(void) {\n\tif (sdl_game_surface != NULL) {\n\t\tSDL_FreeSurface(sdl_game_surface);\n\t\tsdl_game_surface = NULL;\n\t}\n\tif (sdl_game_palette != NULL) {\n\t\tSDL_FreePalette(sdl_game_palette);\n\t\tsdl_game_palette = NULL;\n\t}\n\tif (sdl_window != NULL) {\n\t\tSDL_DestroyWindow(sdl_window);\n\t\tsdl_window_surface = NULL;\n\t\tsdl_window = NULL;\n\t}\n\tSDL_Quit();\n}\n\nstatic void p_InitVideo(void) {\n\tif (SDL_Init(SDL_INIT_VIDEO) < 0)\n\t\tIFEFatalError(\"SDL2 failed to initialize\");\n\n\tmemset(&ifevidinfo_sdl2,0,sizeof(ifevidinfo_sdl2));\n\n\tifevidinfo_sdl2.width = 640;\n\tifevidinfo_sdl2.height = 480;\n\n\tif (sdl_window == NULL && (sdl_window=SDL_CreateWindow(\"\",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,640,480,SDL_WINDOW_SHOWN)) == NULL)\n\t\tIFEFatalError(\"SDL2 window creation failed\");\n\tif (sdl_window_surface == NULL && (sdl_window_surface=SDL_GetWindowSurface(sdl_window)) == NULL)\n\t\tIFEFatalError(\"SDL2 window surface failed\");\n\tif (sdl_game_surface == NULL && (sdl_game_surface=SDL_CreateRGBSurfaceWithFormat(0,640,480,8,SDL_PIXELFORMAT_INDEX8)) == NULL)\n\t\tIFEFatalError(\"SDL2 game surface (256-color) failed\");\n\tif (sdl_game_palette == NULL && (sdl_game_palette=SDL_AllocPalette(256)) == NULL)\n\t\tIFEFatalError(\"SDL2 game palette\");\n\n\tifevidinfo_sdl2.buf_alloc = ifevidinfo_sdl2.buf_size = sdl_game_surface->pitch * sdl_game_surface->h;\n\tifevidinfo_sdl2.buf_pitch = sdl_game_surface->pitch;\n\n\t\/* first color should be black, SDL2 will init palette to white for some reason *\/\n\tmemset(sdl_pal,0,sizeof(SDL_Color));\n\tif (SDL_SetPaletteColors(sdl_game_palette,sdl_pal,0,1) != 0)\n\t\tIFEFatalError(\"SDL2 game palette set colors\");\n\n\t\/* apply palette to surface *\/\n\tif (SDL_SetSurfacePalette(sdl_game_surface,sdl_game_palette) != 0)\n\t\tIFEFatalError(\"SDL2 game palette set\");\n\n\t\/* make sure screen is cleared black *\/\n\tSDL_FillRect(sdl_game_surface,NULL,0);\n\tifeapi->UpdateFullScreen();\n\tifeapi->CheckEvents();\n}\n\nvoid p_FlushKeyboardInput(void) {\n\tIFEKeyQueueEmptyAll();\n}\n\nIFEKeyEvent *p_GetRawKeyboardInput(void) {\n\treturn IFEKeyQueue.get();\n}\n\nIFECookedKeyEvent *p_GetCookedKeyboardInput(void) {\n\treturn IFECookedKeyQueue.get();\n}\n\nifeapi_t ifeapi_sdl2 = {\n\t\"SDL2\",\n\tp_SetPaletteColors,\n\tp_GetTicks,\n\tp_ResetTicks,\n\tp_UpdateFullScreen,\n\tp_GetVidInfo,\n\tp_UserWantsToQuit,\n\tp_CheckEvents,\n\tp_WaitEvent,\n\tp_BeginScreenDraw,\n\tp_EndScreenDraw,\n\tp_ShutdownVideo,\n\tp_InitVideo,\n\tp_FlushKeyboardInput,\n\tp_GetRawKeyboardInput,\n\tp_GetCookedKeyboardInput\n};\n\nbool priv_IFEMainInit(int argc,char **argv) {\n\tstruct stat st;\n\n\t\/\/not used yet\n\t(void)argc;\n\t(void)argv;\n\n\t\/* if STDERR is a valid handle to something, enable debug *\/\n\tif (fstat(2\/*STDERR*\/,&st) == 0) {\n\t\tfprintf(stderr,\"Will emit debug info to stderr\\n\");\n\t\tifedbg_en = true;\n\t}\n\n\treturn true;\n}\n#endif\n\nSDL2 keyboard events\n#if defined(USE_SDL2)\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if defined(__APPLE__) \/* Brew got the headers wrong here *\/\n# include \n#else\n# include \n#endif\n\n#include \"ifict.h\"\n#include \"utils.h\"\n#include \"debug.h\"\n#include \"fatal.h\"\n#include \"palette.h\"\n\nSDL_Window*\t\t\tsdl_window = NULL;\nSDL_Surface*\t\t\tsdl_window_surface = NULL;\nSDL_Surface*\t\t\tsdl_game_surface = NULL;\nSDL_Palette*\t\t\tsdl_game_palette = NULL;\nSDL_Color\t\t\tsdl_pal[256];\nUint32\t\t\t\tsdl_ticks_base = 0; \/* use Uint32 type provided by SDL2 here to avoid problems *\/\nbool\t\t\t\tsdl_signal_to_quit = false;\nifevidinfo_t\t\t\tifevidinfo_sdl2;\n\nstatic void p_SetPaletteColors(const unsigned int first,const unsigned int count,IFEPaletteEntry *pal) {\n\tunsigned int i;\n\n\tpriv_SetPaletteColorsRangeCheck(first,count);\n\n\tfor (i=0;i < count;i++) {\n\t\tsdl_pal[i+first].r = pal[i].r;\n\t\tsdl_pal[i+first].g = pal[i].g;\n\t\tsdl_pal[i+first].b = pal[i].b;\n\t\tsdl_pal[i+first].a = 0xFFu;\n\t}\n\n\tif (SDL_SetPaletteColors(sdl_game_palette,sdl_pal,first,count) != 0)\n\t\tIFEFatalError(\"SDL2 game palette set colors\");\n}\n\nstatic uint32_t p_GetTicks(void) {\n\treturn uint32_t(SDL_GetTicks() - sdl_ticks_base);\n}\n\nstatic void p_ResetTicks(const uint32_t base) {\n\tsdl_ticks_base += base; \/* NTS: Use return value of IFEGetTicks() *\/\n}\n\nstatic void p_UpdateFullScreen(void) {\n\tif (SDL_BlitSurface(sdl_game_surface,NULL,sdl_window_surface,NULL) != 0)\n\t\tIFEFatalError(\"Game to window BlitSurface\");\n\n\tif (SDL_UpdateWindowSurface(sdl_window) != 0)\n\t\tIFEFatalError(\"Window surface update\");\n}\n\nstatic ifevidinfo_t* p_GetVidInfo(void) {\n\treturn &ifevidinfo_sdl2;\n}\n\nstatic bool p_UserWantsToQuit(void) {\n\treturn sdl_signal_to_quit;\n}\n\nstatic uint32_t SDKKeySymToIFE(const SDL_Scancode k) {\n#define MAP(x,y) \\\n\tcase x: return y;\n#define MSN(x) \\\n\tcase SDL_SCANCODE_##x: return IFEKEY_##x;\n\n\tswitch (k) {\n\t\tMSN(RETURN);\n\t\tMSN(ESCAPE);\n\t\tMSN(BACKSPACE);\n\t\tMSN(TAB);\n\t\tMSN(SPACE);\n\t\tdefault: break;\n\t}\n#undef MSN\n#undef MAP\n\n\treturn uint32_t(0);\n}\n\nstatic void priv_ProcessKeyboardEvent(const SDL_KeyboardEvent &ev) {\n\tIFEKeyEvent ke;\n\n\tmemset(&ke,0,sizeof(ke));\n\tke.raw_code = (uint32_t)ev.keysym.scancode;\n\tke.code = SDKKeySymToIFE(ev.keysym.scancode);\n\tke.flags = (ev.state == SDL_PRESSED) ? IFEKeyEvent_FLAG_DOWN : 0;\n\n\tif (!IFEKeyQueue.add(ke))\n\t\tIFEDBG(\"ProcessKeyboardEvent: Queue full\");\n}\n\nstatic void priv_ProcessEvent(const SDL_Event &ev) {\n\tswitch (ev.type) {\n\t\tcase SDL_QUIT:\n\t\t\tsdl_signal_to_quit = true;\n\t\t\tbreak;\n\t\tcase SDL_KEYDOWN:\n\t\tcase SDL_KEYUP:\n\t\t\tpriv_ProcessKeyboardEvent(ev.key);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n}\n\nstatic void p_CheckEvents(void) {\n\tSDL_Event ev;\n\n\tif (SDL_PollEvent(&ev))\n\t\tpriv_ProcessEvent(ev);\n}\n\nstatic void p_WaitEvent(const int wait_ms) {\n\tSDL_Event ev;\n\n\tif (SDL_WaitEventTimeout(&ev,wait_ms))\n\t\tpriv_ProcessEvent(ev);\n}\n\nstatic bool p_BeginScreenDraw(void) {\n\tif (SDL_MUSTLOCK(sdl_game_surface) && SDL_LockSurface(sdl_game_surface) != 0)\n\t\treturn false;\n\tif (sdl_game_surface->pixels == NULL)\n\t\tIFEFatalError(\"SDL2 game surface pixels == NULL\"); \/* that's a BUG if this happens! *\/\n\tif (sdl_game_surface->pitch < 0)\n\t\tIFEFatalError(\"SDL2 game surface pitch is negative\");\n\n\tifevidinfo_sdl2.buf_base = ifevidinfo_sdl2.buf_first_row = (unsigned char*)(sdl_game_surface->pixels);\n\treturn true;\n}\n\nstatic void p_EndScreenDraw(void) {\n\tif (SDL_MUSTLOCK(sdl_game_surface))\n\t\tSDL_UnlockSurface(sdl_game_surface);\n\n\tifevidinfo_sdl2.buf_base = ifevidinfo_sdl2.buf_first_row = NULL;\n}\n\nstatic void p_ShutdownVideo(void) {\n\tif (sdl_game_surface != NULL) {\n\t\tSDL_FreeSurface(sdl_game_surface);\n\t\tsdl_game_surface = NULL;\n\t}\n\tif (sdl_game_palette != NULL) {\n\t\tSDL_FreePalette(sdl_game_palette);\n\t\tsdl_game_palette = NULL;\n\t}\n\tif (sdl_window != NULL) {\n\t\tSDL_DestroyWindow(sdl_window);\n\t\tsdl_window_surface = NULL;\n\t\tsdl_window = NULL;\n\t}\n\tSDL_Quit();\n}\n\nstatic void p_InitVideo(void) {\n\tif (SDL_Init(SDL_INIT_VIDEO) < 0)\n\t\tIFEFatalError(\"SDL2 failed to initialize\");\n\n\tmemset(&ifevidinfo_sdl2,0,sizeof(ifevidinfo_sdl2));\n\n\tifevidinfo_sdl2.width = 640;\n\tifevidinfo_sdl2.height = 480;\n\n\tif (sdl_window == NULL && (sdl_window=SDL_CreateWindow(\"\",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,640,480,SDL_WINDOW_SHOWN)) == NULL)\n\t\tIFEFatalError(\"SDL2 window creation failed\");\n\tif (sdl_window_surface == NULL && (sdl_window_surface=SDL_GetWindowSurface(sdl_window)) == NULL)\n\t\tIFEFatalError(\"SDL2 window surface failed\");\n\tif (sdl_game_surface == NULL && (sdl_game_surface=SDL_CreateRGBSurfaceWithFormat(0,640,480,8,SDL_PIXELFORMAT_INDEX8)) == NULL)\n\t\tIFEFatalError(\"SDL2 game surface (256-color) failed\");\n\tif (sdl_game_palette == NULL && (sdl_game_palette=SDL_AllocPalette(256)) == NULL)\n\t\tIFEFatalError(\"SDL2 game palette\");\n\n\tifevidinfo_sdl2.buf_alloc = ifevidinfo_sdl2.buf_size = sdl_game_surface->pitch * sdl_game_surface->h;\n\tifevidinfo_sdl2.buf_pitch = sdl_game_surface->pitch;\n\n\t\/* first color should be black, SDL2 will init palette to white for some reason *\/\n\tmemset(sdl_pal,0,sizeof(SDL_Color));\n\tif (SDL_SetPaletteColors(sdl_game_palette,sdl_pal,0,1) != 0)\n\t\tIFEFatalError(\"SDL2 game palette set colors\");\n\n\t\/* apply palette to surface *\/\n\tif (SDL_SetSurfacePalette(sdl_game_surface,sdl_game_palette) != 0)\n\t\tIFEFatalError(\"SDL2 game palette set\");\n\n\t\/* make sure screen is cleared black *\/\n\tSDL_FillRect(sdl_game_surface,NULL,0);\n\tifeapi->UpdateFullScreen();\n\tifeapi->CheckEvents();\n}\n\nvoid p_FlushKeyboardInput(void) {\n\tIFEKeyQueueEmptyAll();\n}\n\nIFEKeyEvent *p_GetRawKeyboardInput(void) {\n\treturn IFEKeyQueue.get();\n}\n\nIFECookedKeyEvent *p_GetCookedKeyboardInput(void) {\n\treturn IFECookedKeyQueue.get();\n}\n\nifeapi_t ifeapi_sdl2 = {\n\t\"SDL2\",\n\tp_SetPaletteColors,\n\tp_GetTicks,\n\tp_ResetTicks,\n\tp_UpdateFullScreen,\n\tp_GetVidInfo,\n\tp_UserWantsToQuit,\n\tp_CheckEvents,\n\tp_WaitEvent,\n\tp_BeginScreenDraw,\n\tp_EndScreenDraw,\n\tp_ShutdownVideo,\n\tp_InitVideo,\n\tp_FlushKeyboardInput,\n\tp_GetRawKeyboardInput,\n\tp_GetCookedKeyboardInput\n};\n\nbool priv_IFEMainInit(int argc,char **argv) {\n\tstruct stat st;\n\n\t\/\/not used yet\n\t(void)argc;\n\t(void)argv;\n\n\t\/* if STDERR is a valid handle to something, enable debug *\/\n\tif (fstat(2\/*STDERR*\/,&st) == 0) {\n\t\tfprintf(stderr,\"Will emit debug info to stderr\\n\");\n\t\tifedbg_en = true;\n\t}\n\n\treturn true;\n}\n#endif\n\n<|endoftext|>"} {"text":"\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 1999 Stefan Seefeld \n * http:\/\/www.berlin-consortium.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n#ifndef _File_hh\n#define _File_hh\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Prague\n{\n\n\/* @Class{File}\n *\n * @Description{}\n *\/\nclass File\n{\npublic:\n enum type_t { none = 0, \n\t\tlink = S_IFLNK, \n\t\treg = S_IFREG, \n\t\tdir = S_IFDIR, \n\t\tchr = S_IFCHR, \n\t\tblk = S_IFBLK, \n\t\tfifo = S_IFIFO, \n\t\tsock = S_IFSOCK};\n enum access_t { ur = S_IRUSR,\n\t\t uw = S_IWUSR,\n\t\t ux = S_IXUSR,\n\t\t gr = S_IRGRP,\n\t\t gw = S_IWGRP,\n\t\t gx = S_IXGRP,\n\t\t or = S_IROTH,\n\t\t ow = S_IWOTH,\n\t\t ox = S_IXOTH,\n\t\t all= ur|uw|ux|gr|gw|gx|or|ow|ox};\n File(const string &);\n File(const File &);\n virtual ~File();\n File &operator = (const File &);\n File &operator = (const string &);\n File parent() const;\n const string &name() const { return shortname;}\n const string &longName() const { return longname;}\n bool is(type_t t) const { return (status.st_mode & S_IFMT) == (mode_t) t;}\n long type() const { return (status.st_mode & S_IFMT);}\n long access() const { return (status.st_mode & (ur|uw|ux));}\n uid_t uid() const { return status.st_uid;}\n gid_t gid() const { return status.st_gid;}\n long size() const { return status.st_size;}\n time_t accTime() const { return status.st_atime;}\n time_t modTime() const { return status.st_mtime;}\n time_t chTime() const { return status.st_ctime;}\n\n bool chmod(access_t);\n bool mv(const string &);\n bool rm();\n static string base(const string &);\n static string tmp() { return ::tmpnam(0);}\nprotected:\n struct stat status;\n string longname;\n string shortname;\n bool getStatus();\n const char *lastError() const;\n int error;\nprivate:\n};\n\ninline string File::base(const string &s)\n{\n string::size_type p = s.find_last_of('\/');\n return p == string::npos ? s : s.substr(p + 1);\n}\n\ninline bool File::getStatus()\n{\n if (stat(longname.c_str(), &status) == -1) { status.st_mode = 0; error = errno; return false;} return true;\n}\n\n};\n\n#endif \/* _File_hh *\/\navoid 'or' keyword\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 1999 Stefan Seefeld \n * http:\/\/www.berlin-consortium.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n#ifndef _File_hh\n#define _File_hh\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Prague\n{\n\n\/* @Class{File}\n *\n * @Description{}\n *\/\nclass File\n{\npublic:\n enum type_t { none = 0, \n\t\tlink = S_IFLNK, \n\t\treg = S_IFREG, \n\t\tdir = S_IFDIR, \n\t\tchr = S_IFCHR, \n\t\tblk = S_IFBLK, \n\t\tfifo = S_IFIFO, \n\t\tsock = S_IFSOCK};\n enum access_t { ru = S_IRUSR,\n\t\t wu = S_IWUSR,\n\t\t xu = S_IXUSR,\n\t\t rg = S_IRGRP,\n\t\t wg = S_IWGRP,\n\t\t xg = S_IXGRP,\n\t\t ro = S_IROTH,\n\t\t wo = S_IWOTH,\n\t\t xo = S_IXOTH,\n\t\t all= ru|wu|xu|rg|wg|xg|ro|wo|xo};\n File(const string &);\n File(const File &);\n virtual ~File();\n File &operator = (const File &);\n File &operator = (const string &);\n File parent() const;\n const string &name() const { return shortname;}\n const string &longName() const { return longname;}\n bool is(type_t t) const { return (status.st_mode & S_IFMT) == (mode_t) t;}\n long type() const { return (status.st_mode & S_IFMT);}\n long access() const { return (status.st_mode & (ru|wu|xu));}\n uid_t uid() const { return status.st_uid;}\n gid_t gid() const { return status.st_gid;}\n long size() const { return status.st_size;}\n time_t accTime() const { return status.st_atime;}\n time_t modTime() const { return status.st_mtime;}\n time_t chTime() const { return status.st_ctime;}\n\n bool chmod(access_t);\n bool mv(const string &);\n bool rm();\n static string base(const string &);\n static string tmp() { return ::tmpnam(0);}\nprotected:\n struct stat status;\n string longname;\n string shortname;\n bool getStatus();\n const char *lastError() const;\n int error;\nprivate:\n};\n\ninline string File::base(const string &s)\n{\n string::size_type p = s.find_last_of('\/');\n return p == string::npos ? s : s.substr(p + 1);\n}\n\ninline bool File::getStatus()\n{\n if (stat(longname.c_str(), &status) == -1) { status.st_mode = 0; error = errno; return false;} return true;\n}\n\n};\n\n#endif \/* _File_hh *\/\n<|endoftext|>"} {"text":"\/*\n * Worldvisions Weaver Software:\n * Copyright (C) 1997-2002 Net Integration Technologies, Inc.\n *\n * This is the WvTFTP server daemon.\n *\/\n#include \"wvtftpserver.h\"\n#include \"wvlogrcv.h\"\n#include \"wvver.h\"\n#include \n\nstatic bool want_to_die = false;\n\nvoid sighandler_die(int signum)\n{\n want_to_die = true;\n}\n\nstatic void usage(char *argv0)\n{\n fprintf(stderr,\n \"Usage: %s [-d] [-dd]\\n\"\n \" -d Print debug messages\\n\"\n \" -dd Print lots of debug messages\\n\"\n \" -V Print version and exit\\n\",\n argv0);\n exit(1);\n}\n\nint main(int argc, char **argv)\n{\n WvLog::LogLevel lvl = WvLog::Debug1;\n int c;\n signal(SIGTERM, sighandler_die);\n signal(SIGHUP, sighandler_die);\n signal(SIGINT, sighandler_die);\n while ((c = getopt(argc, argv, \"dV?\")) >= 0)\n {\n switch(c)\n {\n case 'd':\n if (lvl <= WvLog::Debug1)\n lvl = WvLog::Debug4;\n else\n lvl = WvLog::Debug5;\n break;\n case 'V':\n fprintf(stderr, \"WvTFTPd version %s\\n\",WVTFTP_VER_STRING);\n exit(2);\n case '?':\n usage(argv[0]);\n break;\n }\n }\n\n WvConf cfg(\"\/etc\/wvtftpd.conf\");\n WvTFTPServer tftps(cfg, 100);\n WvLogConsole logdisp(2, lvl);\n\n while (tftps.isok() && !want_to_die)\n {\n\tif (tftps.select(1000))\n\t tftps.callback();\n\telse\n\t cfg.flush();\n }\n cfg.save();\n}\nWvTFTPd now gives a useful error message when it exits.\/*\n * Worldvisions Weaver Software:\n * Copyright (C) 1997-2002 Net Integration Technologies, Inc.\n *\n * This is the WvTFTP server daemon.\n *\/\n#include \"wvtftpserver.h\"\n#include \"wvlogrcv.h\"\n#include \"wvver.h\"\n#include \n#include \n\nstatic bool want_to_die = false;\n\nvoid sighandler_die(int signum)\n{\n want_to_die = true;\n}\n\nstatic void usage(char *argv0)\n{\n fprintf(stderr,\n \"Usage: %s [-d] [-dd]\\n\"\n \" -d Print debug messages\\n\"\n \" -dd Print lots of debug messages\\n\"\n \" -V Print version and exit\\n\",\n argv0);\n exit(1);\n}\n\nint main(int argc, char **argv)\n{\n WvLog::LogLevel lvl = WvLog::Debug1;\n int c;\n signal(SIGTERM, sighandler_die);\n signal(SIGHUP, sighandler_die);\n signal(SIGINT, sighandler_die);\n while ((c = getopt(argc, argv, \"dV?\")) >= 0)\n {\n switch(c)\n {\n case 'd':\n if (lvl <= WvLog::Debug1)\n lvl = WvLog::Debug4;\n else\n lvl = WvLog::Debug5;\n break;\n case 'V':\n fprintf(stderr, \"WvTFTPd version %s\\n\",WVTFTP_VER_STRING);\n exit(2);\n case '?':\n usage(argv[0]);\n break;\n }\n }\n\n WvLog log(\"WvTFTP\", WvLog::Critical);\n WvConf cfg(\"\/etc\/wvtftpd.conf\");\n WvTFTPServer tftps(cfg, 100);\n WvLogConsole logdisp(2, lvl);\n\n while (tftps.isok() && !want_to_die)\n {\n\tif (tftps.select(1000))\n\t tftps.callback();\n\telse\n\t cfg.flush();\n }\n if (!tftps.isok() && tftps.geterr())\n log(\"%s.\\n\", strerror(tftps.geterr()));\n cfg.save();\n}\n<|endoftext|>"} {"text":"\/\/ sound.cxx -- Sound class implementation\n\/\/\n\/\/ Started by Erik Hofman, February 2002\n\/\/ (Reuses some code from fg_fx.cxx created by David Megginson)\n\/\/\n\/\/ Copyright (C) 2002 Curtis L. Olson - http:\/\/www.flightgear.org\/~curt\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\/\/\n\/\/ $Id$\n\n#include \n\n#ifdef SG_HAVE_STD_INCLUDES\n# include \n#else\n# include \n#endif\n#include \n\n#include \n#include \n#include \n\n\n#include \"xmlsound.hxx\"\n\n\n\/\/ static double _snd_lin(double v) { return v; }\nstatic double _snd_inv(double v) { return (v == 0) ? 1e99 : 1\/v; }\nstatic double _snd_abs(double v) { return (v >= 0) ? v : -v; }\nstatic double _snd_sqrt(double v) { return (v < 0) ? sqrt(-v) : sqrt(v); }\nstatic double _snd_log10(double v) { return (v < 1) ? 0 : fast_log10(v); }\nstatic double _snd_log(double v) { return (v < 1) ? 0 : fast_log(v); }\n\/\/ static double _snd_sqr(double v) { return v*v; }\n\/\/ static double _snd_pow3(double v) { return v*v*v; }\n\nstatic const struct {\n\tchar *name;\n\tdouble (*fn)(double);\n} __sound_fn[] = {\n\/\/\t{\"lin\", _snd_lin},\n\t{\"inv\", _snd_inv},\n\t{\"abs\", _snd_abs},\n\t{\"sqrt\", _snd_sqrt},\n\t{\"log\", _snd_log10},\n\t{\"ln\", _snd_log},\n\/\/\t{\"sqr\", _snd_sqr},\n\/\/\t{\"pow3\", _snd_pow3},\n\t{\"\", NULL}\n};\n\nSGXmlSound::SGXmlSound()\n : _sample(NULL),\n _condition(NULL),\n _active(false),\n _name(\"\"),\n _mode(SGXmlSound::ONCE),\n _prev_value(0),\n _dt_play(0.0),\n _dt_stop(0.0),\n _stopping(0.0)\n{\n}\n\nSGXmlSound::~SGXmlSound()\n{\n _sample->stop();\n\n delete _condition;\n\n _volume.clear();\n _pitch.clear();\n}\n\nvoid\nSGXmlSound::init(SGPropertyNode *root, SGPropertyNode *node, SGSoundMgr *sndmgr,\n const string &path)\n{\n\n \/\/\n \/\/ set global sound properties\n \/\/\n \n _name = node->getStringValue(\"name\", \"\");\n SG_LOG(SG_GENERAL, SG_INFO, \"Loading sound information for: \" << _name );\n\n const char *mode_str = node->getStringValue(\"mode\", \"\");\n if ( !strcmp(mode_str, \"looped\") ) {\n _mode = SGXmlSound::LOOPED;\n\n } else if ( !strcmp(mode_str, \"in-transit\") ) {\n _mode = SGXmlSound::IN_TRANSIT;\n\n } else {\n _mode = SGXmlSound::ONCE;\n\n if ( strcmp(mode_str, \"\") )\n SG_LOG(SG_GENERAL,SG_INFO, \" Unknown sound mode, default to 'once'\");\n }\n\n _property = root->getNode(node->getStringValue(\"property\", \"\"), true);\n SGPropertyNode *condition = node->getChild(\"condition\");\n if (condition != NULL)\n _condition = sgReadCondition(root, condition);\n\n if (!_property && !_condition)\n SG_LOG(SG_GENERAL, SG_WARN,\n \" Neither a condition nor a property specified\");\n\n \/\/\n \/\/ set volume properties\n \/\/\n unsigned int i;\n float v = 0.0;\n vector kids = node->getChildren(\"volume\");\n for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {\n _snd_prop volume = {NULL, NULL, NULL, 1.0, 0.0, 0.0, 0.0, false};\n\n if (strcmp(kids[i]->getStringValue(\"property\"), \"\"))\n volume.prop = root->getNode(kids[i]->getStringValue(\"property\", \"\"), true);\n\n const char *intern_str = kids[i]->getStringValue(\"internal\", \"\");\n if (!strcmp(intern_str, \"dt_play\"))\n volume.intern = &_dt_play;\n else if (!strcmp(intern_str, \"dt_stop\"))\n volume.intern = &_dt_stop;\n\n if ((volume.factor = kids[i]->getDoubleValue(\"factor\", 1.0)) != 0.0)\n if (volume.factor < 0.0) {\n volume.factor = -volume.factor;\n volume.subtract = true;\n }\n\n const char *type_str = kids[i]->getStringValue(\"type\", \"\");\n if ( strcmp(type_str, \"\") ) {\n\n for (int j=0; __sound_fn[j].fn; j++)\n if ( !strcmp(type_str, __sound_fn[j].name) ) {\n volume.fn = __sound_fn[j].fn;\n break;\n }\n\n if (!volume.fn)\n SG_LOG(SG_GENERAL,SG_INFO,\n \" Unknown volume type, default to 'lin'\");\n }\n\n volume.offset = kids[i]->getDoubleValue(\"offset\", 0.0);\n\n if ((volume.min = kids[i]->getDoubleValue(\"min\", 0.0)) < 0.0)\n SG_LOG( SG_GENERAL, SG_WARN,\n \"Volume minimum value below 0. Forced to 0.\");\n\n volume.max = kids[i]->getDoubleValue(\"max\", 0.0);\n if (volume.max && (volume.max < volume.min) )\n SG_LOG(SG_GENERAL,SG_ALERT,\n \" Volume maximum below minimum. Neglected.\");\n\n _volume.push_back(volume);\n v += volume.offset;\n\n }\n\n float reference_dist = node->getDoubleValue(\"reference-dist\", 500.0);\n float max_dist = node->getDoubleValue(\"max-dist\", 3000.0);\n \n \/\/\n \/\/ set pitch properties\n \/\/\n float p = 0.0;\n kids = node->getChildren(\"pitch\");\n for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {\n _snd_prop pitch = {NULL, NULL, NULL, 1.0, 1.0, 0.0, 0.0, false};\n\n if (strcmp(kids[i]->getStringValue(\"property\", \"\"), \"\"))\n pitch.prop = root->getNode(kids[i]->getStringValue(\"property\", \"\"), true);\n\n const char *intern_str = kids[i]->getStringValue(\"internal\", \"\");\n if (!strcmp(intern_str, \"dt_play\"))\n pitch.intern = &_dt_play;\n else if (!strcmp(intern_str, \"dt_stop\"))\n pitch.intern = &_dt_stop;\n\n if ((pitch.factor = kids[i]->getDoubleValue(\"factor\", 1.0)) != 0.0)\n if (pitch.factor < 0.0) {\n pitch.factor = -pitch.factor;\n pitch.subtract = true;\n }\n\n const char *type_str = kids[i]->getStringValue(\"type\", \"\");\n if ( strcmp(type_str, \"\") ) {\n\n for (int j=0; __sound_fn[j].fn; j++) \n if ( !strcmp(type_str, __sound_fn[j].name) ) {\n pitch.fn = __sound_fn[j].fn;\n break;\n }\n\n if (!pitch.fn)\n SG_LOG(SG_GENERAL,SG_INFO,\n \" Unknown pitch type, default to 'lin'\");\n }\n \n pitch.offset = kids[i]->getDoubleValue(\"offset\", 1.0);\n\n if ((pitch.min = kids[i]->getDoubleValue(\"min\", 0.0)) < 0.0)\n SG_LOG(SG_GENERAL,SG_WARN,\n \" Pitch minimum value below 0. Forced to 0.\");\n\n pitch.max = kids[i]->getDoubleValue(\"max\", 0.0);\n if (pitch.max && (pitch.max < pitch.min) )\n SG_LOG(SG_GENERAL,SG_ALERT,\n \" Pitch maximum below minimum. Neglected\");\n\n _pitch.push_back(pitch);\n p += pitch.offset;\n }\n\n \/\/\n \/\/ Relative position\n \/\/\n sgVec3 offset_pos;\n sgSetVec3( offset_pos, 0.0, 0.0, 0.0 );\n SGPropertyNode_ptr pos = node->getChild(\"position\");\n if ( pos != NULL ) {\n offset_pos[0] = pos->getDoubleValue(\"x\", 0.0);\n offset_pos[1] = pos->getDoubleValue(\"y\", 0.0);\n offset_pos[2] = pos->getDoubleValue(\"z\", 0.0);\n }\n\n \/\/\n \/\/ Orientation\n \/\/\n sgVec3 dir;\n float inner, outer, outer_gain;\n sgSetVec3( dir, 0.0, 0.0, 0.0 );\n inner = outer = 360.0;\n outer_gain = 0.0;\n pos = node->getChild(\"orientation\");\n if ( pos != NULL ) {\n dir[0] = pos->getDoubleValue(\"x\", 0.0);\n dir[1] = pos->getDoubleValue(\"y\", 0.0);\n dir[2] = pos->getDoubleValue(\"z\", 0.0);\n inner = pos->getDoubleValue(\"inner-angle\", 360.0);\n outer = pos->getDoubleValue(\"outer-angle\", 360.0);\n outer_gain = pos->getDoubleValue(\"outer-gain\", 0.0);\n }\n \n \/\/\n \/\/ Initialize the sample\n \/\/\n _mgr = sndmgr;\n if ( (_sample = _mgr->find(_name)) == NULL ) {\n \/\/ FIXME: Does it make sense to overwrite a previous entry's\n \/\/ configuration just because a new entry has the same name?\n \/\/ Note that we can't match on identical \"path\" because we the\n \/\/ new entry could be at a different location with different\n \/\/ configuration so we need a new sample which creates a new\n \/\/ \"alSource\". The semantics of what is going on here seems\n \/\/ confused and needs to be thought through more carefully.\n _sample = new SGSoundSample( path.c_str(),\n node->getStringValue(\"path\", \"\") );\n\n _mgr->add( _sample, _name );\n }\n\n _sample->set_offset_pos( offset_pos );\n _sample->set_orientation(dir, inner, outer, outer_gain);\n _sample->set_volume(v);\n _sample->set_reference_dist( reference_dist );\n _sample->set_max_dist( max_dist );\n _sample->set_pitch(p);\n}\n\nvoid\nSGXmlSound::update (double dt)\n{\n double curr_value = 0.0;\n\n \/\/\n \/\/ If the state changes to false, stop playing.\n \/\/\n if (_property)\n curr_value = _property->getDoubleValue();\n\n if (\t\t\t\t\t\t\t\/\/ Lisp, anyone?\n (_condition && !_condition->test()) ||\n (!_condition && _property &&\n (\n !curr_value ||\n ( (_mode == SGXmlSound::IN_TRANSIT) && (curr_value == _prev_value) )\n )\n )\n )\n {\n if ((_mode != SGXmlSound::IN_TRANSIT) || (_stopping > MAX_TRANSIT_TIME)) {\n if (_sample->is_playing()) {\n SG_LOG(SG_GENERAL, SG_INFO, \"Stopping audio after \" << _dt_play\n << \" sec: \" << _name );\n\n _sample->stop();\n }\n\n _active = false;\n _dt_stop += dt;\n _dt_play = 0.0;\n } else {\n _stopping += dt;\n }\n\n return;\n }\n\n \/\/\n \/\/ If the mode is ONCE and the sound is still playing,\n \/\/ we have nothing to do anymore.\n \/\/\n if (_active && (_mode == SGXmlSound::ONCE)) {\n\n if (!_sample->is_playing()) {\n _dt_stop += dt;\n _dt_play = 0.0;\n } else {\n _dt_play += dt;\n }\n\n return;\n }\n\n \/\/\n \/\/ Update the playing time, cache the current value and\n \/\/ clear the delay timer.\n \/\/\n _dt_play += dt;\n _prev_value = curr_value;\n _stopping = 0.0;\n\n \/\/\n \/\/ Update the volume\n \/\/\n int i;\n int max = _volume.size();\n double volume = 1.0;\n double volume_offset = 0.0;\n\n for(i = 0; i < max; i++) {\n double v = 1.0;\n\n if (_volume[i].prop)\n v = _volume[i].prop->getDoubleValue();\n\n else if (_volume[i].intern)\n v = *_volume[i].intern;\n\n if (_volume[i].fn)\n v = _volume[i].fn(v);\n\n v *= _volume[i].factor;\n\n if (_volume[i].max && (v > _volume[i].max))\n v = _volume[i].max;\n\n else if (v < _volume[i].min)\n v = _volume[i].min;\n\n if (_volume[i].subtract)\t\t\t\t\/\/ Hack!\n volume = _volume[i].offset - v;\n\n else {\n volume_offset += _volume[i].offset;\n volume *= v;\n }\n }\n\n \/\/\n \/\/ Update the pitch\n \/\/\n max = _pitch.size();\n double pitch = 1.0;\n double pitch_offset = 0.0;\n\n for(i = 0; i < max; i++) {\n double p = 1.0;\n\n if (_pitch[i].prop)\n p = _pitch[i].prop->getDoubleValue();\n\n else if (_pitch[i].intern)\n p = *_pitch[i].intern;\n\n if (_pitch[i].fn)\n p = _pitch[i].fn(p);\n\n p *= _pitch[i].factor;\n\n if (_pitch[i].max && (p > _pitch[i].max))\n p = _pitch[i].max;\n\n else if (p < _pitch[i].min)\n p = _pitch[i].min;\n\n if (_pitch[i].subtract)\t\t\t\t\/\/ Hack!\n pitch = _pitch[i].offset - p;\n\n else {\n pitch_offset += _pitch[i].offset;\n pitch *= p;\n }\n }\n\n \/\/\n \/\/ Change sample state\n \/\/\n _sample->set_pitch( pitch_offset + pitch );\n if ((volume_offset + volume ) > 1.0)\n {\n _sample->set_volume( 1.0 );\n SG_LOG(SG_GENERAL, SG_WARN,\n \"Volume larger than 1.0 in configuration for '\" << _name\n << \"', clipping.\");\n } else \n _sample->set_volume( volume_offset + volume );\n\n\n \/\/\n \/\/ Do we need to start playing the sample?\n \/\/\n if (!_active) {\n\n if (_mode == SGXmlSound::ONCE)\n _sample->play(false);\n\n else\n _sample->play(true);\n\n SG_LOG(SG_GENERAL, SG_INFO, \"Playing audio after \" << _dt_stop \n << \" sec: \" << _name);\n SG_LOG(SG_GENERAL, SG_BULK,\n \"Playing \" << ((_mode == ONCE) ? \"once\" : \"looped\"));\n\n _active = true;\n _dt_stop = 0.0;\n }\n}\ncreate an absolute value before calling log or log10, this adds support for sound on negative numbers (thrust reverse for example).\/\/ sound.cxx -- Sound class implementation\n\/\/\n\/\/ Started by Erik Hofman, February 2002\n\/\/ (Reuses some code from fg_fx.cxx created by David Megginson)\n\/\/\n\/\/ Copyright (C) 2002 Curtis L. Olson - http:\/\/www.flightgear.org\/~curt\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\/\/\n\/\/ $Id$\n\n#include \n\n#ifdef SG_HAVE_STD_INCLUDES\n# include \n#else\n# include \n#endif\n#include \n\n#include \n#include \n#include \n\n\n#include \"xmlsound.hxx\"\n\n\n#define LOG_ABS(x) (((x) > 1) ? (x) : (((x) < -1) ? -(x) : 0))\n\/\/ static double _snd_lin(double v) { return v; }\nstatic double _snd_inv(double v) { return (v == 0) ? 1e99 : 1\/v; }\nstatic double _snd_abs(double v) { return (v >= 0) ? v : -v; }\nstatic double _snd_sqrt(double v) { return (v < 0) ? sqrt(-v) : sqrt(v); }\nstatic double _snd_log10(double v) { return fast_log10( LOG_ABS(v) ); }\nstatic double _snd_log(double v) { return fast_log( LOG_ABS(v) ); }\n\/\/ static double _snd_sqr(double v) { return v*v; }\n\/\/ static double _snd_pow3(double v) { return v*v*v; }\n\nstatic const struct {\n\tchar *name;\n\tdouble (*fn)(double);\n} __sound_fn[] = {\n\/\/\t{\"lin\", _snd_lin},\n\t{\"inv\", _snd_inv},\n\t{\"abs\", _snd_abs},\n\t{\"sqrt\", _snd_sqrt},\n\t{\"log\", _snd_log10},\n\t{\"ln\", _snd_log},\n\/\/\t{\"sqr\", _snd_sqr},\n\/\/\t{\"pow3\", _snd_pow3},\n\t{\"\", NULL}\n};\n\nSGXmlSound::SGXmlSound()\n : _sample(NULL),\n _condition(NULL),\n _active(false),\n _name(\"\"),\n _mode(SGXmlSound::ONCE),\n _prev_value(0),\n _dt_play(0.0),\n _dt_stop(0.0),\n _stopping(0.0)\n{\n}\n\nSGXmlSound::~SGXmlSound()\n{\n _sample->stop();\n\n delete _condition;\n\n _volume.clear();\n _pitch.clear();\n}\n\nvoid\nSGXmlSound::init(SGPropertyNode *root, SGPropertyNode *node, SGSoundMgr *sndmgr,\n const string &path)\n{\n\n \/\/\n \/\/ set global sound properties\n \/\/\n \n _name = node->getStringValue(\"name\", \"\");\n SG_LOG(SG_GENERAL, SG_INFO, \"Loading sound information for: \" << _name );\n\n const char *mode_str = node->getStringValue(\"mode\", \"\");\n if ( !strcmp(mode_str, \"looped\") ) {\n _mode = SGXmlSound::LOOPED;\n\n } else if ( !strcmp(mode_str, \"in-transit\") ) {\n _mode = SGXmlSound::IN_TRANSIT;\n\n } else {\n _mode = SGXmlSound::ONCE;\n\n if ( strcmp(mode_str, \"\") )\n SG_LOG(SG_GENERAL,SG_INFO, \" Unknown sound mode, default to 'once'\");\n }\n\n _property = root->getNode(node->getStringValue(\"property\", \"\"), true);\n SGPropertyNode *condition = node->getChild(\"condition\");\n if (condition != NULL)\n _condition = sgReadCondition(root, condition);\n\n if (!_property && !_condition)\n SG_LOG(SG_GENERAL, SG_WARN,\n \" Neither a condition nor a property specified\");\n\n \/\/\n \/\/ set volume properties\n \/\/\n unsigned int i;\n float v = 0.0;\n vector kids = node->getChildren(\"volume\");\n for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {\n _snd_prop volume = {NULL, NULL, NULL, 1.0, 0.0, 0.0, 0.0, false};\n\n if (strcmp(kids[i]->getStringValue(\"property\"), \"\"))\n volume.prop = root->getNode(kids[i]->getStringValue(\"property\", \"\"), true);\n\n const char *intern_str = kids[i]->getStringValue(\"internal\", \"\");\n if (!strcmp(intern_str, \"dt_play\"))\n volume.intern = &_dt_play;\n else if (!strcmp(intern_str, \"dt_stop\"))\n volume.intern = &_dt_stop;\n\n if ((volume.factor = kids[i]->getDoubleValue(\"factor\", 1.0)) != 0.0)\n if (volume.factor < 0.0) {\n volume.factor = -volume.factor;\n volume.subtract = true;\n }\n\n const char *type_str = kids[i]->getStringValue(\"type\", \"\");\n if ( strcmp(type_str, \"\") ) {\n\n for (int j=0; __sound_fn[j].fn; j++)\n if ( !strcmp(type_str, __sound_fn[j].name) ) {\n volume.fn = __sound_fn[j].fn;\n break;\n }\n\n if (!volume.fn)\n SG_LOG(SG_GENERAL,SG_INFO,\n \" Unknown volume type, default to 'lin'\");\n }\n\n volume.offset = kids[i]->getDoubleValue(\"offset\", 0.0);\n\n if ((volume.min = kids[i]->getDoubleValue(\"min\", 0.0)) < 0.0)\n SG_LOG( SG_GENERAL, SG_WARN,\n \"Volume minimum value below 0. Forced to 0.\");\n\n volume.max = kids[i]->getDoubleValue(\"max\", 0.0);\n if (volume.max && (volume.max < volume.min) )\n SG_LOG(SG_GENERAL,SG_ALERT,\n \" Volume maximum below minimum. Neglected.\");\n\n _volume.push_back(volume);\n v += volume.offset;\n\n }\n\n float reference_dist = node->getDoubleValue(\"reference-dist\", 500.0);\n float max_dist = node->getDoubleValue(\"max-dist\", 3000.0);\n \n \/\/\n \/\/ set pitch properties\n \/\/\n float p = 0.0;\n kids = node->getChildren(\"pitch\");\n for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {\n _snd_prop pitch = {NULL, NULL, NULL, 1.0, 1.0, 0.0, 0.0, false};\n\n if (strcmp(kids[i]->getStringValue(\"property\", \"\"), \"\"))\n pitch.prop = root->getNode(kids[i]->getStringValue(\"property\", \"\"), true);\n\n const char *intern_str = kids[i]->getStringValue(\"internal\", \"\");\n if (!strcmp(intern_str, \"dt_play\"))\n pitch.intern = &_dt_play;\n else if (!strcmp(intern_str, \"dt_stop\"))\n pitch.intern = &_dt_stop;\n\n if ((pitch.factor = kids[i]->getDoubleValue(\"factor\", 1.0)) != 0.0)\n if (pitch.factor < 0.0) {\n pitch.factor = -pitch.factor;\n pitch.subtract = true;\n }\n\n const char *type_str = kids[i]->getStringValue(\"type\", \"\");\n if ( strcmp(type_str, \"\") ) {\n\n for (int j=0; __sound_fn[j].fn; j++) \n if ( !strcmp(type_str, __sound_fn[j].name) ) {\n pitch.fn = __sound_fn[j].fn;\n break;\n }\n\n if (!pitch.fn)\n SG_LOG(SG_GENERAL,SG_INFO,\n \" Unknown pitch type, default to 'lin'\");\n }\n \n pitch.offset = kids[i]->getDoubleValue(\"offset\", 1.0);\n\n if ((pitch.min = kids[i]->getDoubleValue(\"min\", 0.0)) < 0.0)\n SG_LOG(SG_GENERAL,SG_WARN,\n \" Pitch minimum value below 0. Forced to 0.\");\n\n pitch.max = kids[i]->getDoubleValue(\"max\", 0.0);\n if (pitch.max && (pitch.max < pitch.min) )\n SG_LOG(SG_GENERAL,SG_ALERT,\n \" Pitch maximum below minimum. Neglected\");\n\n _pitch.push_back(pitch);\n p += pitch.offset;\n }\n\n \/\/\n \/\/ Relative position\n \/\/\n sgVec3 offset_pos;\n sgSetVec3( offset_pos, 0.0, 0.0, 0.0 );\n SGPropertyNode_ptr pos = node->getChild(\"position\");\n if ( pos != NULL ) {\n offset_pos[0] = pos->getDoubleValue(\"x\", 0.0);\n offset_pos[1] = pos->getDoubleValue(\"y\", 0.0);\n offset_pos[2] = pos->getDoubleValue(\"z\", 0.0);\n }\n\n \/\/\n \/\/ Orientation\n \/\/\n sgVec3 dir;\n float inner, outer, outer_gain;\n sgSetVec3( dir, 0.0, 0.0, 0.0 );\n inner = outer = 360.0;\n outer_gain = 0.0;\n pos = node->getChild(\"orientation\");\n if ( pos != NULL ) {\n dir[0] = pos->getDoubleValue(\"x\", 0.0);\n dir[1] = pos->getDoubleValue(\"y\", 0.0);\n dir[2] = pos->getDoubleValue(\"z\", 0.0);\n inner = pos->getDoubleValue(\"inner-angle\", 360.0);\n outer = pos->getDoubleValue(\"outer-angle\", 360.0);\n outer_gain = pos->getDoubleValue(\"outer-gain\", 0.0);\n }\n \n \/\/\n \/\/ Initialize the sample\n \/\/\n _mgr = sndmgr;\n if ( (_sample = _mgr->find(_name)) == NULL ) {\n \/\/ FIXME: Does it make sense to overwrite a previous entry's\n \/\/ configuration just because a new entry has the same name?\n \/\/ Note that we can't match on identical \"path\" because we the\n \/\/ new entry could be at a different location with different\n \/\/ configuration so we need a new sample which creates a new\n \/\/ \"alSource\". The semantics of what is going on here seems\n \/\/ confused and needs to be thought through more carefully.\n _sample = new SGSoundSample( path.c_str(),\n node->getStringValue(\"path\", \"\") );\n\n _mgr->add( _sample, _name );\n }\n\n _sample->set_offset_pos( offset_pos );\n _sample->set_orientation(dir, inner, outer, outer_gain);\n _sample->set_volume(v);\n _sample->set_reference_dist( reference_dist );\n _sample->set_max_dist( max_dist );\n _sample->set_pitch(p);\n}\n\nvoid\nSGXmlSound::update (double dt)\n{\n double curr_value = 0.0;\n\n \/\/\n \/\/ If the state changes to false, stop playing.\n \/\/\n if (_property)\n curr_value = _property->getDoubleValue();\n\n if (\t\t\t\t\t\t\t\/\/ Lisp, anyone?\n (_condition && !_condition->test()) ||\n (!_condition && _property &&\n (\n !curr_value ||\n ( (_mode == SGXmlSound::IN_TRANSIT) && (curr_value == _prev_value) )\n )\n )\n )\n {\n if ((_mode != SGXmlSound::IN_TRANSIT) || (_stopping > MAX_TRANSIT_TIME)) {\n if (_sample->is_playing()) {\n SG_LOG(SG_GENERAL, SG_INFO, \"Stopping audio after \" << _dt_play\n << \" sec: \" << _name );\n\n _sample->stop();\n }\n\n _active = false;\n _dt_stop += dt;\n _dt_play = 0.0;\n } else {\n _stopping += dt;\n }\n\n return;\n }\n\n \/\/\n \/\/ If the mode is ONCE and the sound is still playing,\n \/\/ we have nothing to do anymore.\n \/\/\n if (_active && (_mode == SGXmlSound::ONCE)) {\n\n if (!_sample->is_playing()) {\n _dt_stop += dt;\n _dt_play = 0.0;\n } else {\n _dt_play += dt;\n }\n\n return;\n }\n\n \/\/\n \/\/ Update the playing time, cache the current value and\n \/\/ clear the delay timer.\n \/\/\n _dt_play += dt;\n _prev_value = curr_value;\n _stopping = 0.0;\n\n \/\/\n \/\/ Update the volume\n \/\/\n int i;\n int max = _volume.size();\n double volume = 1.0;\n double volume_offset = 0.0;\n\n for(i = 0; i < max; i++) {\n double v = 1.0;\n\n if (_volume[i].prop)\n v = _volume[i].prop->getDoubleValue();\n\n else if (_volume[i].intern)\n v = *_volume[i].intern;\n\n if (_volume[i].fn)\n v = _volume[i].fn(v);\n\n v *= _volume[i].factor;\n\n if (_volume[i].max && (v > _volume[i].max))\n v = _volume[i].max;\n\n else if (v < _volume[i].min)\n v = _volume[i].min;\n\n if (_volume[i].subtract)\t\t\t\t\/\/ Hack!\n volume = _volume[i].offset - v;\n\n else {\n volume_offset += _volume[i].offset;\n volume *= v;\n }\n }\n\n \/\/\n \/\/ Update the pitch\n \/\/\n max = _pitch.size();\n double pitch = 1.0;\n double pitch_offset = 0.0;\n\n for(i = 0; i < max; i++) {\n double p = 1.0;\n\n if (_pitch[i].prop)\n p = _pitch[i].prop->getDoubleValue();\n\n else if (_pitch[i].intern)\n p = *_pitch[i].intern;\n\n if (_pitch[i].fn)\n p = _pitch[i].fn(p);\n\n p *= _pitch[i].factor;\n\n if (_pitch[i].max && (p > _pitch[i].max))\n p = _pitch[i].max;\n\n else if (p < _pitch[i].min)\n p = _pitch[i].min;\n\n if (_pitch[i].subtract)\t\t\t\t\/\/ Hack!\n pitch = _pitch[i].offset - p;\n\n else {\n pitch_offset += _pitch[i].offset;\n pitch *= p;\n }\n }\n\n \/\/\n \/\/ Change sample state\n \/\/\n _sample->set_pitch( pitch_offset + pitch );\n if ((volume_offset + volume ) > 1.0)\n {\n _sample->set_volume( 1.0 );\n SG_LOG(SG_GENERAL, SG_WARN,\n \"Volume larger than 1.0 in configuration for '\" << _name\n << \"', clipping.\");\n } else \n _sample->set_volume( volume_offset + volume );\n\n\n \/\/\n \/\/ Do we need to start playing the sample?\n \/\/\n if (!_active) {\n\n if (_mode == SGXmlSound::ONCE)\n _sample->play(false);\n\n else\n _sample->play(true);\n\n SG_LOG(SG_GENERAL, SG_INFO, \"Playing audio after \" << _dt_stop \n << \" sec: \" << _name);\n SG_LOG(SG_GENERAL, SG_BULK,\n \"Playing \" << ((_mode == ONCE) ? \"once\" : \"looped\"));\n\n _active = true;\n _dt_stop = 0.0;\n }\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkCarbonTextMapper.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkCarbonTextMapper.h\"\n#include \"vtkCarbonRenderWindow.h\"\n#include \n#include \n#include \"vtkObjectFactory.h\"\n#include \"vtkgluPickMatrix.h\"\n#include \"vtkString.h\"\n\nvtkCxxRevisionMacro(vtkCarbonTextMapper, \"1.3\");\nvtkStandardNewMacro(vtkCarbonTextMapper);\n\nstruct vtkFontStruct\n{\n vtkWindow *Window;\n int Italic;\n int Bold;\n int FontSize;\n int FontFamily;\n int ListBase;\n};\n \nstatic vtkFontStruct *cache[30] = {\n NULL,NULL,NULL,NULL,NULL,\n NULL,NULL,NULL,NULL,NULL,\n NULL,NULL,NULL,NULL,NULL,\n NULL,NULL,NULL,NULL,NULL,\n NULL,NULL,NULL,NULL,NULL,\n NULL,NULL,NULL,NULL,NULL};\nstatic int numCached = 0;\n\n\/\/ Copy C string to Pascal string\n\/\/ Some of the Carbon routines require Pascal strings\nstatic void CStrToPStr (StringPtr outString, const char *inString)\n{\n unsigned char x = 0;\n do\n *(((char*)outString) + x + 1) = *(inString + x++);\n while ((*(inString + x) != 0) && (x < 256));\n *((char*)outString) = (char) x;\n}\n\n\nvoid vtkCarbonTextMapper::GetSize(vtkViewport* viewport, int *size)\n{\n if ( this->NumberOfLines > 1 )\n {\n this->GetMultiLineSize(viewport, size);\n return;\n }\n\n if (this->Input == NULL)\n {\n size[0] = 0;\n size[1] = 0;\n return;\n }\n\n \/\/ Check to see whether we have to rebuild anything\n if ( this->GetMTime() < this->BuildTime)\n {\n size[0] = this->LastSize[0];\n size[1] = this->LastSize[1];\n return;\n }\n\n \/\/ Check for input\n if (this->Input == NULL)\n {\n vtkErrorMacro (<<\"vtkCarbonTextMapper::GetSize - No input\");\n return;\n }\n\n \/\/ Get the window information for display\n vtkWindow* window = viewport->GetVTKWindow();\n \/\/ Get the device context from the window\n AGLDrawable hdc = (AGLDrawable) window->GetGenericContext();\n\n \/\/ Get the font number\n switch (this->FontFamily)\n {\n case VTK_ARIAL:\n GetFNum(\"\\pArial\", &(this->currentFontNum));\n break;\n case VTK_TIMES:\n GetFNum(\"\\pTimes\", &(this->currentFontNum));\n break;\n case VTK_COURIER:\n GetFNum(\"\\pCourier\", &(this->currentFontNum));\n break;\n default:\n GetFNum(\"\\pArial\", &(this->currentFontNum));\n break;\n }\n\n TextFont(this->currentFontNum);\n TextFace(normal + (italic*this->Italic) + (bold*this->Bold) +\n (shadow*this->Shadow));\n TextSize(this->FontSize);\n\n GetFontInfo(&(this->myFontInfo));\n \n \/\/ Calculate the size of the bounding rectangle\n Str255 testString = \"\\p\"; \/\/StringWidth needs a pascal string\n CStrToPStr(testString, this->Input);\n size[0] = StringWidth(testString);\n size[1] = (this->myFontInfo.ascent +\n this->myFontInfo.descent +\n this->myFontInfo.leading);\n \n this->LastSize[0] = size[0];\n this->LastSize[1] = size[1];\n this->BuildTime.Modified();\n}\n\n\n\nint vtkCarbonTextMapper::GetListBaseForFont(vtkViewport *vp)\n{\n int i, j;\n vtkCarbonRenderWindow *win = (vtkCarbonRenderWindow *)(vp->GetVTKWindow());\n\n \/\/ has the font been cached ?\n for (i = 0; i < numCached; i++)\n {\n if (cache[i]->Window == win &&\n cache[i]->Italic == this->GetItalic() &&\n cache[i]->Bold == this->GetBold() &&\n cache[i]->FontSize == this->GetFontSize() &&\n cache[i]->FontFamily == this->GetFontFamily())\n {\n \/\/ make this the most recently used\n if (i != 0)\n {\n vtkFontStruct *tmp = cache[i];\n for (j = i-1; j >= 0; j--)\n {\n cache[j+1] = cache[j];\n }\n cache[0] = tmp;\n }\n return cache[0]->ListBase;\n }\n }\n \n AGLDrawable hdc = (AGLDrawable) win->GetGenericContext();\n\n \/\/ OK the font is not cached\n \/\/ so we need to make room for a new font\n if (numCached == 30)\n {\n aglSetCurrentContext((AGLContext)cache[29]->Window->GetGenericDisplayId());\n glDeleteLists(cache[29]->ListBase,255);\n aglSetCurrentContext((AGLContext)win->GetGenericDisplayId());\n numCached = 29;\n }\n\n \/\/ add the new font\n if (!cache[numCached])\n {\n cache[numCached] = new vtkFontStruct;\n int done = 0;\n cache[numCached]->ListBase = 1000;\n do \n {\n done = 1;\n cache[numCached]->ListBase += 260;\n for (i = 0; i < numCached; i++)\n {\n if (cache[i]->ListBase == cache[numCached]->ListBase)\n {\n done = 0;\n }\n }\n }\n while (!done);\n }\n\n short fNum = 0;\n \/\/ set the other info and build the font\n cache[numCached]->Window = win;\n cache[numCached]->Italic = this->GetItalic();\n cache[numCached]->Bold = this->GetBold();\n cache[numCached]->FontSize = this->GetFontSize();\n cache[numCached]->FontFamily = this->GetFontFamily();\n if (cache[numCached]->FontSize < 9)\n cache[numCached]->FontSize = 9; \/\/ minimum font size (or it goes blank!)\n aglUseFont((AGLContext)win->GetGenericDisplayId(), cache[numCached]->FontFamily,\n normal+(italic*this->Italic) + (bold*this->Bold) +\n (shadow*this->Shadow), cache[numCached]->FontSize, 0, 255, cache[numCached]->ListBase);\n GLenum err = aglGetError();\n if (AGL_NO_ERROR != err)\n cout << \"vtkCarbonMapper AGLError: \"<<(char *)aglErrorString(err)<<\"\\n\";\n \n \/\/ now resort the list\n vtkFontStruct *tmp = cache[numCached];\n for (i = numCached-1; i >= 0; i--)\n {\n cache[i+1] = cache[i];\n }\n cache[0] = tmp;\n numCached++;\n return cache[0]->ListBase;\n}\n\nvoid vtkCarbonTextMapper::ReleaseGraphicsResources(vtkWindow *win)\n{\n int i,j;\n \n \/\/ free up any cached font associated with this window\n \/\/ has the font been cached ?\n for (i = 0; i < numCached; i++)\n {\n if (cache[i]->Window == win)\n {\n win->MakeCurrent();\n glDeleteLists(cache[i]->ListBase,255);\n delete cache[i];\n \/\/ resort them\n numCached--;\n for (j = i; j < numCached; j++)\n {\n cache[j] = cache[j+1];\n }\n cache[numCached] = NULL;\n i--;\n }\n }\n\n this->LastWindow = NULL;\n \n \/\/ very important\n \/\/ the release of graphics resources indicates that significant changes have\n \/\/ occurred. Old fonts, cached sizes etc are all no longer valid, so we send\n \/\/ ourselves a general modified message.\n this->Modified();\n}\n\nvtkCarbonTextMapper::vtkCarbonTextMapper()\n{\n}\n\nvtkCarbonTextMapper::~vtkCarbonTextMapper()\n{\n if (this->LastWindow)\n {\n this->ReleaseGraphicsResources(this->LastWindow);\n } \n}\n\nvoid vtkCarbonTextMapper::RenderOverlay(vtkViewport* viewport, \n vtkActor2D* actor)\n{\n vtkDebugMacro (<< \"RenderOverlay\");\n\n \/\/ turn off texturing in case it is on\n glDisable( GL_TEXTURE_2D );\n \n \/\/ Get the window information for display\n vtkWindow* window = viewport->GetVTKWindow();\n if (this->LastWindow && this->LastWindow != window)\n {\n this->ReleaseGraphicsResources(this->LastWindow);\n }\n this->LastWindow = window;\n \n \/\/ Check for input\n if ( this->NumberOfLines > 1 )\n {\n this->RenderOverlayMultipleLines(viewport, actor);\n return;\n }\n\n if ( this->Input == NULL ) \n {\n vtkErrorMacro (<<\"Render - No input\");\n return;\n }\n\n int size[2];\n this->GetSize(viewport, size);\n\n \/\/ Get the device context from the window\n AGLDrawable hdc = (AGLDrawable) window->GetGenericContext();\n \n \/\/ Get the position of the text actor\n Point ptDestOff;\n int* actorPos = \n actor->GetPositionCoordinate()->GetComputedViewportValue(viewport);\n ptDestOff.h = actorPos[0];\n ptDestOff.v = static_cast(actorPos[1] - this->LineOffset);\n\n \/\/ Set up the font color from the text actor\n unsigned char red = 0;\n unsigned char green = 0;\n unsigned char blue = 0;\n unsigned char alpha = 0;\n \n float* actorColor = actor->GetProperty()->GetColor();\n red = (unsigned char) (actorColor[0] * 255.0);\n green = (unsigned char) (actorColor[1] * 255.0);\n blue = (unsigned char) (actorColor[2] * 255.0);\n alpha = (unsigned char) (actorColor[3] * 255.0);\n \n \/\/ Set up the shadow color\n float intensity;\n intensity = (red + green + blue)\/3.0;\n\n unsigned char shadowRed, shadowGreen, shadowBlue;\n if (intensity > 128)\n {\n shadowRed = shadowBlue = shadowGreen = 0;\n }\n else\n {\n shadowRed = shadowBlue = shadowGreen = 255;\n }\n\n \/\/ Define bounding rectangle\n Rect rect;\n rect.left = ptDestOff.h;\n rect.top = ptDestOff.v;\n rect.bottom = ptDestOff.v;\n rect.right = ptDestOff.h;\n\n rect.right = rect.left + size[0];\n rect.top = rect.bottom + size[1];\n \n switch (this->Justification)\n {\n int tmp;\n case VTK_TEXT_LEFT: \n break;\n case VTK_TEXT_CENTERED:\n tmp = rect.right - rect.left + 1;\n rect.left = rect.left - tmp\/2;\n rect.right = rect.left + tmp;\n break;\n case VTK_TEXT_RIGHT: \n tmp = rect.right - rect.left + 1;\n rect.right = rect.left;\n rect.left = rect.left - tmp;\n }\n switch (this->VerticalJustification)\n {\n case VTK_TEXT_TOP: \n rect.top = rect.bottom;\n rect.bottom = rect.bottom - size[1];\n break;\n case VTK_TEXT_CENTERED:\n rect.bottom = rect.bottom - size[1]\/2;\n rect.top = rect.bottom + size[1];\n break;\n case VTK_TEXT_BOTTOM: \n break;\n }\n \n \/\/ push a 2D matrix on the stack\n int *vsize = viewport->GetSize();\n glMatrixMode( GL_PROJECTION);\n glPushMatrix();\n glLoadIdentity();\n if(viewport->GetIsPicking())\n {\n vtkgluPickMatrix(viewport->GetPickX(), viewport->GetPickY(),\n 1, 1, viewport->GetOrigin(), viewport->GetSize());\n }\n \n glMatrixMode( GL_MODELVIEW );\n glPushMatrix();\n glLoadIdentity();\n glDisable( GL_LIGHTING);\n\n int front = \n (actor->GetProperty()->GetDisplayLocation() == VTK_FOREGROUND_LOCATION);\n\n float *tileViewport = viewport->GetVTKWindow()->GetTileViewport();\n float *vport = viewport->GetViewport();\n float visVP[4];\n visVP[0] = (vport[0] >= tileViewport[0]) ? vport[0] : tileViewport[0];\n visVP[1] = (vport[1] >= tileViewport[1]) ? vport[1] : tileViewport[1];\n visVP[2] = (vport[2] <= tileViewport[2]) ? vport[2] : tileViewport[2];\n visVP[3] = (vport[3] <= tileViewport[3]) ? vport[3] : tileViewport[3];\n if (visVP[0] == visVP[2])\n {\n return;\n }\n if (visVP[1] == visVP[3])\n {\n return;\n }\n \n int *winSize = viewport->GetVTKWindow()->GetSize();\n int xoff = static_cast\n (rect.left - winSize[0]*((visVP[2] + visVP[0])\/2.0 - vport[0]));\n int yoff = static_cast\n (rect.bottom - winSize[1]*((visVP[3] + visVP[1])\/2.0 - vport[1]));\n\n \/\/ When picking draw the bounds of the text as a rectangle,\n \/\/ as text only picks when the pick point is exactly on the\n \/\/ origin of the text \n if(viewport->GetIsPicking())\n {\n float width = 2.0 * ((float)rect.right - rect.left) \/ vsize[0];\n float height = 2.0 * ((float)rect.top - rect.bottom) \/ vsize[1];\n float x1 = (2.0 * (GLfloat)(rect.left) \/ vsize[0] - 1);\n float y1 = (2.0 * (GLfloat)(rect.bottom) \/ vsize[1] - 1);\n glRectf(x1, y1, x1+width, y1+height);\n\n \/\/ Clean up and return after drawing the rectangle\n glMatrixMode( GL_PROJECTION);\n glPopMatrix();\n glMatrixMode( GL_MODELVIEW);\n glPopMatrix();\n glEnable( GL_LIGHTING);\n \n return;\n }\n \n glListBase(this->GetListBaseForFont(viewport));\n\n \/\/ Set the colors for the shadow\n if (this->Shadow)\n {\n \/\/ set the colors for the foreground\n glColor4ub(shadowRed, shadowGreen, shadowBlue, alpha);\n glRasterPos3f(0,0,(front)?(-1):(.99999));\n\n \/\/ required for clipping to work correctly\n glBitmap(0, 0, 0, 0, xoff + 1, yoff - 1, NULL);\n \n \/\/ Draw the shadow text\n glCallLists (vtkString::Length(this->Input), GL_UNSIGNED_BYTE, \n this->Input); \n }\n \n \/\/ set the colors for the foreground\n glColor4ub(red, green, blue, alpha);\n glRasterPos3f(0,0,(front)?(-1):(.99999));\n\n \/\/ required for clipping to work correctly\n glBitmap(0, 0, 0, 0, xoff, yoff, NULL);\n\n \/\/ display a string: \/\/ indicate start of glyph display lists \n glCallLists (vtkString::Length(this->Input), GL_UNSIGNED_BYTE, \n this->Input);\n\n glFlush();\n glMatrixMode( GL_PROJECTION);\n glPopMatrix();\n glMatrixMode( GL_MODELVIEW);\n glPopMatrix();\n glEnable( GL_LIGHTING);\n}\n\nBUG: FontFamily used rather than fontNum\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkCarbonTextMapper.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkCarbonTextMapper.h\"\n#include \"vtkCarbonRenderWindow.h\"\n#include \n#include \n#include \"vtkObjectFactory.h\"\n#include \"vtkgluPickMatrix.h\"\n#include \"vtkString.h\"\n\nvtkCxxRevisionMacro(vtkCarbonTextMapper, \"1.4\");\nvtkStandardNewMacro(vtkCarbonTextMapper);\n\nstruct vtkFontStruct\n{\n vtkWindow *Window;\n int Italic;\n int Bold;\n int FontSize;\n int FontFamily;\n int ListBase;\n};\n \nstatic vtkFontStruct *cache[30] = {\n NULL,NULL,NULL,NULL,NULL,\n NULL,NULL,NULL,NULL,NULL,\n NULL,NULL,NULL,NULL,NULL,\n NULL,NULL,NULL,NULL,NULL,\n NULL,NULL,NULL,NULL,NULL,\n NULL,NULL,NULL,NULL,NULL};\nstatic int numCached = 0;\n\n\/\/ Copy C string to Pascal string\n\/\/ Some of the Carbon routines require Pascal strings\nstatic void CStrToPStr (StringPtr outString, const char *inString)\n{\n unsigned char x = 0;\n do\n *(((char*)outString) + x + 1) = *(inString + x++);\n while ((*(inString + x) != 0) && (x < 256));\n *((char*)outString) = (char) x;\n}\n\n\nvoid vtkCarbonTextMapper::GetSize(vtkViewport* viewport, int *size)\n{\n if ( this->NumberOfLines > 1 )\n {\n this->GetMultiLineSize(viewport, size);\n return;\n }\n\n if (this->Input == NULL)\n {\n size[0] = 0;\n size[1] = 0;\n return;\n }\n\n \/\/ Check to see whether we have to rebuild anything\n if ( this->GetMTime() < this->BuildTime)\n {\n size[0] = this->LastSize[0];\n size[1] = this->LastSize[1];\n return;\n }\n\n \/\/ Check for input\n if (this->Input == NULL)\n {\n vtkErrorMacro (<<\"vtkCarbonTextMapper::GetSize - No input\");\n return;\n }\n\n \/\/ Get the window information for display\n vtkWindow* window = viewport->GetVTKWindow();\n \/\/ Get the device context from the window\n AGLDrawable hdc = (AGLDrawable) window->GetGenericContext();\n\n \/\/ Get the font number\n switch (this->FontFamily)\n {\n case VTK_ARIAL:\n GetFNum(\"\\pArial\", &(this->currentFontNum));\n break;\n case VTK_TIMES:\n GetFNum(\"\\pTimes\", &(this->currentFontNum));\n break;\n case VTK_COURIER:\n GetFNum(\"\\pCourier\", &(this->currentFontNum));\n break;\n default:\n GetFNum(\"\\pArial\", &(this->currentFontNum));\n break;\n }\n\n TextFont(this->currentFontNum);\n TextFace(normal + (italic*this->Italic) + (bold*this->Bold) +\n (shadow*this->Shadow));\n if (this->FontSize < 9)\n {\/\/ adjust since smaller sizes disappear in aglUseFont\n this->FontSize = 9;\n }\n TextSize(this->FontSize);\n\n GetFontInfo(&(this->myFontInfo));\n \n \/\/ Calculate the size of the bounding rectangle\n Str255 testString = \"\\p\"; \/\/StringWidth needs a pascal string\n CStrToPStr(testString, this->Input);\n size[0] = StringWidth(testString);\n size[1] = (this->myFontInfo.ascent +\n this->myFontInfo.descent +\n this->myFontInfo.leading);\n \n this->LastSize[0] = size[0];\n this->LastSize[1] = size[1];\n this->BuildTime.Modified();\n}\n\n\n\nint vtkCarbonTextMapper::GetListBaseForFont(vtkViewport *vp)\n{\n int i, j;\n vtkCarbonRenderWindow *win = (vtkCarbonRenderWindow *)(vp->GetVTKWindow());\n\n \/\/ has the font been cached ?\n for (i = 0; i < numCached; i++)\n {\n if (cache[i]->Window == win &&\n cache[i]->Italic == this->GetItalic() &&\n cache[i]->Bold == this->GetBold() &&\n cache[i]->FontSize == this->GetFontSize() &&\n cache[i]->FontFamily == this->GetFontFamily())\n {\n \/\/ make this the most recently used\n if (i != 0)\n {\n vtkFontStruct *tmp = cache[i];\n for (j = i-1; j >= 0; j--)\n {\n cache[j+1] = cache[j];\n }\n cache[0] = tmp;\n }\n return cache[0]->ListBase;\n }\n }\n \n AGLDrawable hdc = (AGLDrawable) win->GetGenericContext();\n\n \/\/ OK the font is not cached\n \/\/ so we need to make room for a new font\n if (numCached == 30)\n {\n aglSetCurrentContext((AGLContext)cache[29]->Window->GetGenericDisplayId());\n glDeleteLists(cache[29]->ListBase,255);\n aglSetCurrentContext((AGLContext)win->GetGenericDisplayId());\n numCached = 29;\n }\n\n \/\/ add the new font\n if (!cache[numCached])\n {\n cache[numCached] = new vtkFontStruct;\n int done = 0;\n cache[numCached]->ListBase = 1000;\n do \n {\n done = 1;\n cache[numCached]->ListBase += 260;\n for (i = 0; i < numCached; i++)\n {\n if (cache[i]->ListBase == cache[numCached]->ListBase)\n {\n done = 0;\n }\n }\n }\n while (!done);\n }\n\n short fNum = 0;\n \/\/ set the other info and build the font\n cache[numCached]->Window = win;\n cache[numCached]->Italic = this->GetItalic();\n cache[numCached]->Bold = this->GetBold();\n cache[numCached]->FontSize = this->GetFontSize();\n cache[numCached]->FontFamily = this->GetFontFamily();\n if (cache[numCached]->FontSize < 9)\n cache[numCached]->FontSize = 9; \/\/ minimum font size (or it goes blank!)\n aglUseFont((AGLContext)win->GetGenericDisplayId(), this->currentFontNum,\n normal+(italic*this->Italic) + (bold*this->Bold) +\n (shadow*this->Shadow), cache[numCached]->FontSize, 0, 256, cache[numCached]->ListBase);\n GLenum err = aglGetError();\n if (AGL_NO_ERROR != err)\n {\n vtkErrorMacro(<<\"vtkCarbonMapper AGLError: \"<<(char *)aglErrorString(err));\n }\n \/\/ now resort the list\n vtkFontStruct *tmp = cache[numCached];\n for (i = numCached-1; i >= 0; i--)\n {\n cache[i+1] = cache[i];\n }\n cache[0] = tmp;\n numCached++;\n return cache[0]->ListBase;\n}\n\nvoid vtkCarbonTextMapper::ReleaseGraphicsResources(vtkWindow *win)\n{\n int i,j;\n \n \/\/ free up any cached font associated with this window\n \/\/ has the font been cached ?\n for (i = 0; i < numCached; i++)\n {\n if (cache[i]->Window == win)\n {\n win->MakeCurrent();\n glDeleteLists(cache[i]->ListBase,255);\n delete cache[i];\n \/\/ resort them\n numCached--;\n for (j = i; j < numCached; j++)\n {\n cache[j] = cache[j+1];\n }\n cache[numCached] = NULL;\n i--;\n }\n }\n\n this->LastWindow = NULL;\n \n \/\/ very important\n \/\/ the release of graphics resources indicates that significant changes have\n \/\/ occurred. Old fonts, cached sizes etc are all no longer valid, so we send\n \/\/ ourselves a general modified message.\n this->Modified();\n}\n\nvtkCarbonTextMapper::vtkCarbonTextMapper()\n{\n}\n\nvtkCarbonTextMapper::~vtkCarbonTextMapper()\n{\n if (this->LastWindow)\n {\n this->ReleaseGraphicsResources(this->LastWindow);\n } \n}\n\nvoid vtkCarbonTextMapper::RenderOverlay(vtkViewport* viewport, \n vtkActor2D* actor)\n{\n vtkDebugMacro (<< \"RenderOverlay\");\n\n \/\/ turn off texturing in case it is on\n glDisable( GL_TEXTURE_2D );\n \n \/\/ Get the window information for display\n vtkWindow* window = viewport->GetVTKWindow();\n if (this->LastWindow && this->LastWindow != window)\n {\n this->ReleaseGraphicsResources(this->LastWindow);\n }\n this->LastWindow = window;\n \n \/\/ Check for input\n if ( this->NumberOfLines > 1 )\n {\n this->RenderOverlayMultipleLines(viewport, actor);\n return;\n }\n\n if ( this->Input == NULL ) \n {\n vtkErrorMacro (<<\"Render - No input\");\n return;\n }\n\n int size[2];\n this->GetSize(viewport, size);\n\n \/\/ Get the device context from the window\n AGLDrawable hdc = (AGLDrawable) window->GetGenericContext();\n \n \/\/ Get the position of the text actor\n Point ptDestOff;\n int* actorPos = \n actor->GetPositionCoordinate()->GetComputedViewportValue(viewport);\n ptDestOff.h = actorPos[0];\n ptDestOff.v = static_cast(actorPos[1] - this->LineOffset);\n\n \/\/ Set up the font color from the text actor\n unsigned char red = 0;\n unsigned char green = 0;\n unsigned char blue = 0;\n unsigned char alpha = 0;\n \n float* actorColor = actor->GetProperty()->GetColor();\n red = (unsigned char) (actorColor[0] * 255.0);\n green = (unsigned char) (actorColor[1] * 255.0);\n blue = (unsigned char) (actorColor[2] * 255.0);\n alpha = (unsigned char) (actorColor[3] * 255.0);\n \n \/\/ Set up the shadow color\n float intensity;\n intensity = (red + green + blue)\/3.0;\n\n unsigned char shadowRed, shadowGreen, shadowBlue;\n if (intensity > 128)\n {\n shadowRed = shadowBlue = shadowGreen = 0;\n }\n else\n {\n shadowRed = shadowBlue = shadowGreen = 255;\n }\n\n \/\/ Define bounding rectangle\n Rect rect;\n rect.left = ptDestOff.h;\n rect.top = ptDestOff.v;\n rect.bottom = ptDestOff.v;\n rect.right = ptDestOff.h;\n\n rect.right = rect.left + size[0];\n rect.top = rect.bottom + size[1];\n \n switch (this->Justification)\n {\n int tmp;\n case VTK_TEXT_LEFT: \n break;\n case VTK_TEXT_CENTERED:\n tmp = rect.right - rect.left + 1;\n rect.left = rect.left - tmp\/2;\n rect.right = rect.left + tmp;\n break;\n case VTK_TEXT_RIGHT: \n tmp = rect.right - rect.left + 1;\n rect.right = rect.left;\n rect.left = rect.left - tmp;\n }\n switch (this->VerticalJustification)\n {\n case VTK_TEXT_TOP: \n rect.top = rect.bottom;\n rect.bottom = rect.bottom - size[1];\n break;\n case VTK_TEXT_CENTERED:\n rect.bottom = rect.bottom - size[1]\/2;\n rect.top = rect.bottom + size[1];\n break;\n case VTK_TEXT_BOTTOM: \n break;\n }\n \n \/\/ push a 2D matrix on the stack\n int *vsize = viewport->GetSize();\n glMatrixMode( GL_PROJECTION);\n glPushMatrix();\n glLoadIdentity();\n if(viewport->GetIsPicking())\n {\n vtkgluPickMatrix(viewport->GetPickX(), viewport->GetPickY(),\n 1, 1, viewport->GetOrigin(), viewport->GetSize());\n }\n \n glMatrixMode( GL_MODELVIEW );\n glPushMatrix();\n glLoadIdentity();\n glDisable( GL_LIGHTING);\n\n int front = \n (actor->GetProperty()->GetDisplayLocation() == VTK_FOREGROUND_LOCATION);\n\n float *tileViewport = viewport->GetVTKWindow()->GetTileViewport();\n float *vport = viewport->GetViewport();\n float visVP[4];\n visVP[0] = (vport[0] >= tileViewport[0]) ? vport[0] : tileViewport[0];\n visVP[1] = (vport[1] >= tileViewport[1]) ? vport[1] : tileViewport[1];\n visVP[2] = (vport[2] <= tileViewport[2]) ? vport[2] : tileViewport[2];\n visVP[3] = (vport[3] <= tileViewport[3]) ? vport[3] : tileViewport[3];\n if (visVP[0] == visVP[2])\n {\n return;\n }\n if (visVP[1] == visVP[3])\n {\n return;\n }\n \n int *winSize = viewport->GetVTKWindow()->GetSize();\n int xoff = static_cast\n (rect.left - winSize[0]*((visVP[2] + visVP[0])\/2.0 - vport[0]));\n int yoff = static_cast\n (rect.bottom - winSize[1]*((visVP[3] + visVP[1])\/2.0 - vport[1]));\n\n \/\/ When picking draw the bounds of the text as a rectangle,\n \/\/ as text only picks when the pick point is exactly on the\n \/\/ origin of the text \n if(viewport->GetIsPicking())\n {\n float width = 2.0 * ((float)rect.right - rect.left) \/ vsize[0];\n float height = 2.0 * ((float)rect.top - rect.bottom) \/ vsize[1];\n float x1 = (2.0 * (GLfloat)(rect.left) \/ vsize[0] - 1);\n float y1 = (2.0 * (GLfloat)(rect.bottom) \/ vsize[1] - 1);\n glRectf(x1, y1, x1+width, y1+height);\n\n \/\/ Clean up and return after drawing the rectangle\n glMatrixMode( GL_PROJECTION);\n glPopMatrix();\n glMatrixMode( GL_MODELVIEW);\n glPopMatrix();\n glEnable( GL_LIGHTING);\n \n return;\n }\n \n glListBase(this->GetListBaseForFont(viewport));\n\n \/\/ Set the colors for the shadow\n if (this->Shadow)\n {\n \/\/ set the colors for the foreground\n glColor4ub(shadowRed, shadowGreen, shadowBlue, alpha);\n glRasterPos3f(0,0,(front)?(-1):(.99999));\n\n \/\/ required for clipping to work correctly\n glBitmap(0, 0, 0, 0, xoff + 1, yoff - 1, NULL);\n \n \/\/ Draw the shadow text\n glCallLists (vtkString::Length(this->Input), GL_UNSIGNED_BYTE, \n this->Input); \n }\n \n \/\/ set the colors for the foreground\n glColor4ub(red, green, blue, alpha);\n glRasterPos3f(0,0,(front)?(-1):(.99999));\n\n \/\/ required for clipping to work correctly\n glBitmap(0, 0, 0, 0, xoff, yoff, NULL);\n\n \/\/ display a string: \/\/ indicate start of glyph display lists \n glCallLists (vtkString::Length(this->Input), GL_UNSIGNED_BYTE, \n this->Input);\n\n glFlush();\n glMatrixMode( GL_PROJECTION);\n glPopMatrix();\n glMatrixMode( GL_MODELVIEW);\n glPopMatrix();\n glEnable( GL_LIGHTING);\n}\n\n<|endoftext|>"} {"text":"\/* Copyright 2009-2016 Francesco Biscani (bluescarni@gmail.com)\n\nThis file is part of the mp++ library.\n\nThe mp++ library is free software; you can redistribute it and\/or modify\nit under the terms of either:\n\n * the GNU Lesser General Public License as published by the Free\n Software Foundation; either version 3 of the License, or (at your\n option) any later version.\n\nor\n\n * the GNU General Public License as published by the Free Software\n Foundation; either version 3 of the License, or (at your option) any\n later version.\n\nor both in parallel, as here.\n\nThe mp++ library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\nor FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\nfor more details.\n\nYou should have received copies of the GNU General Public License and the\nGNU Lesser General Public License along with the mp++ library. If not,\nsee https:\/\/www.gnu.org\/licenses\/. *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"test_utils.hpp\"\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\nstatic int ntries = 1000;\n\nusing namespace mppp;\nusing namespace mppp_test;\n\nusing sizes = std::tuple, std::integral_constant,\n std::integral_constant, std::integral_constant,\n std::integral_constant>;\n\nstatic std::mt19937 rng;\n\nstruct hash_tester {\n template \n inline void operator()(const S &) const\n {\n using integer = mp_integer;\n const std::hash hasher;\n integer n1, n2;\n REQUIRE((hash(n1) == 0u));\n REQUIRE((hasher(n1) == 0u));\n n1.promote();\n REQUIRE((hash(n1) == 0u));\n REQUIRE((hasher(n1) == 0u));\n n1 = integer{12};\n n2 = n1;\n REQUIRE(n2.is_static());\n n1.promote();\n REQUIRE(n1.is_dynamic());\n REQUIRE((hash(n1) == hash(n2)));\n REQUIRE((hasher(n1) == hash(n2)));\n n1 = integer{-12};\n n2 = n1;\n REQUIRE(n2.is_static());\n n1.promote();\n REQUIRE(n1.is_dynamic());\n REQUIRE((hash(n1) == hash(n2)));\n REQUIRE((hash(n1) == hasher(n2)));\n mpz_raii tmp;\n std::uniform_int_distribution sdist(0, 1);\n \/\/ Run a variety of tests with operands with x number of limbs.\n auto random_xy = [&](unsigned x) {\n for (int i = 0; i < ntries; ++i) {\n random_integer(tmp, x, rng);\n n1 = integer(mpz_to_str(&tmp.m_mpz));\n if (sdist(rng)) {\n n1.neg();\n }\n n2 = n1;\n if (n2.is_static()) {\n n1.promote();\n }\n REQUIRE((hash(n1) == hash(n2)));\n REQUIRE((hasher(n1) == hash(n2)));\n }\n };\n\n random_xy(0);\n random_xy(1);\n random_xy(2);\n random_xy(3);\n random_xy(4);\n }\n};\n\nTEST_CASE(\"hash\")\n{\n tuple_for_each(sizes{}, hash_tester{});\n}\nFix const init in test.\/* Copyright 2009-2016 Francesco Biscani (bluescarni@gmail.com)\n\nThis file is part of the mp++ library.\n\nThe mp++ library is free software; you can redistribute it and\/or modify\nit under the terms of either:\n\n * the GNU Lesser General Public License as published by the Free\n Software Foundation; either version 3 of the License, or (at your\n option) any later version.\n\nor\n\n * the GNU General Public License as published by the Free Software\n Foundation; either version 3 of the License, or (at your option) any\n later version.\n\nor both in parallel, as here.\n\nThe mp++ library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\nor FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\nfor more details.\n\nYou should have received copies of the GNU General Public License and the\nGNU Lesser General Public License along with the mp++ library. If not,\nsee https:\/\/www.gnu.org\/licenses\/. *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"test_utils.hpp\"\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\nstatic int ntries = 1000;\n\nusing namespace mppp;\nusing namespace mppp_test;\n\nusing sizes = std::tuple, std::integral_constant,\n std::integral_constant, std::integral_constant,\n std::integral_constant>;\n\nstatic std::mt19937 rng;\n\nstruct hash_tester {\n template \n inline void operator()(const S &) const\n {\n using integer = mp_integer;\n const std::hash hasher{};\n integer n1, n2;\n REQUIRE((hash(n1) == 0u));\n REQUIRE((hasher(n1) == 0u));\n n1.promote();\n REQUIRE((hash(n1) == 0u));\n REQUIRE((hasher(n1) == 0u));\n n1 = integer{12};\n n2 = n1;\n REQUIRE(n2.is_static());\n n1.promote();\n REQUIRE(n1.is_dynamic());\n REQUIRE((hash(n1) == hash(n2)));\n REQUIRE((hasher(n1) == hash(n2)));\n n1 = integer{-12};\n n2 = n1;\n REQUIRE(n2.is_static());\n n1.promote();\n REQUIRE(n1.is_dynamic());\n REQUIRE((hash(n1) == hash(n2)));\n REQUIRE((hash(n1) == hasher(n2)));\n mpz_raii tmp;\n std::uniform_int_distribution sdist(0, 1);\n \/\/ Run a variety of tests with operands with x number of limbs.\n auto random_xy = [&](unsigned x) {\n for (int i = 0; i < ntries; ++i) {\n random_integer(tmp, x, rng);\n n1 = integer(mpz_to_str(&tmp.m_mpz));\n if (sdist(rng)) {\n n1.neg();\n }\n n2 = n1;\n if (n2.is_static()) {\n n1.promote();\n }\n REQUIRE((hash(n1) == hash(n2)));\n REQUIRE((hasher(n1) == hash(n2)));\n }\n };\n\n random_xy(0);\n random_xy(1);\n random_xy(2);\n random_xy(3);\n random_xy(4);\n }\n};\n\nTEST_CASE(\"hash\")\n{\n tuple_for_each(sizes{}, hash_tester{});\n}\n<|endoftext|>"} {"text":"\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam .\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see .\n*\/\n\n\/* This is a wrapper of the OpenCL C\/C++ header. We need this to avoid warnings and handle OSX *\/\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n\n#define CL_USE_DEPRECATED_OPENCL_1_1_APIS\n#if defined(__APPLE__) || defined(__MACOSX)\n#include \n#define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED\n#define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED\n#else\n#include \n#endif\n#undef CL_VERSION_1_2\n#define __CL_ENABLE_EXCEPTIONS\n\n#define CL_MINIMUM_OPENCL_VERSION 120\n#define CL_TARGET_OPENCL_VERSION 120\n#define CL_ENABLE_EXCEPTIONS\n\n#include \n\n#pragma GCC diagnostic popWorkaround for redefining macros on Mac\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam .\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see .\n*\/\n\n\/* This is a wrapper of the OpenCL C\/C++ header. We need this to avoid warnings and handle OSX *\/\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n\n#define CL_USE_DEPRECATED_OPENCL_1_1_APIS\n#if defined(__APPLE__) || defined(__MACOSX)\n #include \n\n \/\/ To avoid warnings from compiler about redefining needed macros\n #ifdef CL_EXT_PREFIX__VERSION_1_1_DEPRECATED\n #undef CL_EXT_PREFIX__VERSION_1_1_DEPRECATED\n #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED\n #endif\n #ifdef CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED\n #undef CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED\n #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED\n #endif\n#else\n #include \n#endif\n\n#undef CL_VERSION_1_2\n#define __CL_ENABLE_EXCEPTIONS\n\n#define CL_MINIMUM_OPENCL_VERSION 120\n#define CL_TARGET_OPENCL_VERSION 120\n#define CL_ENABLE_EXCEPTIONS\n\n#include \n\n#pragma GCC diagnostic pop\n<|endoftext|>"} {"text":"Use RtcpPacket to send REMB in RtcpSender<|endoftext|>"} {"text":"\/*************************************************\n* FTW EntropySource Source File *\n* (C) 1999-2008 Jack Lloyd *\n*************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n\n#ifndef _POSIX_C_SOURCE\n #define _POSIX_C_SOURCE 199309\n#endif\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Botan {\n\nnamespace {\n\nclass Directory_Walker : public FTW_EntropySource::File_Descriptor_Source\n {\n public:\n Directory_Walker(const std::string& root) { add_directory(root); }\n ~Directory_Walker();\n\n int next_fd();\n private:\n void add_directory(const std::string&);\n\n std::deque > dirs;\n };\n\nvoid Directory_Walker::add_directory(const std::string& dirname)\n {\n DIR* dir = ::opendir(dirname.c_str());\n if(dir)\n dirs.push_back(std::make_pair(dir, dirname));\n }\n\nDirectory_Walker::~Directory_Walker()\n {\n while(dirs.size())\n {\n ::closedir(dirs[0].first);\n dirs.pop_front();\n }\n }\n\nint Directory_Walker::next_fd()\n {\n while(dirs.size())\n {\n std::pair dirinfo = dirs[0];\n\n struct dirent* entry = ::readdir(dirinfo.first);\n\n if(!entry)\n {\n ::closedir(dirinfo.first);\n dirs.pop_front();\n continue;\n }\n\n const std::string filename = entry->d_name;\n\n if(filename == \".\" || filename == \"..\")\n continue;\n\n const std::string full_path = dirinfo.second + '\/' + filename;\n\n struct stat stat_buf;\n if(::lstat(full_path.c_str(), &stat_buf) == -1)\n continue;\n\n if(S_ISDIR(stat_buf.st_mode))\n add_directory(full_path);\n else if(S_ISREG(stat_buf.st_mode))\n {\n int fd = ::open(full_path.c_str(), O_RDONLY | O_NOCTTY);\n\n if(fd > 0)\n return fd;\n }\n }\n\n return -1;\n }\n\n}\n\n\/**\n* FTW_EntropySource Constructor\n*\/\nFTW_EntropySource::FTW_EntropySource(const std::string& p) : path(p)\n {\n dir = 0;\n }\n\n\/**\n* FTW_EntropySource Destructor\n*\/\nFTW_EntropySource::~FTW_EntropySource()\n {\n delete dir;\n }\n\nu32bit FTW_EntropySource::slow_poll(byte buf[], u32bit length)\n {\n if(!dir)\n dir = new Directory_Walker(path);\n\n SecureVector read_buf(4096);\n\n u32bit bytes_read = 0;\n\n while(bytes_read < length * 32)\n {\n int fd = dir->next_fd();\n\n if(fd == -1)\n {\n delete dir;\n dir = new Directory_Walker(path);\n fd = dir->next_fd();\n\n if(fd == -1) \/\/ still fails (directory not mounted, etc) -> fail\n return 0;\n }\n\n ssize_t got = ::read(fd, read_buf.begin(), read_buf.size());\n\n if(got > 0 && got <= read_buf.size())\n {\n for(ssize_t i = 0; i != got; ++i)\n buf[i % length] ^= read_buf[i];\n\n \/\/ never count any one file for more than 128 bytes\n bytes_read += std::min(got, 128);\n }\n\n ::close(fd);\n }\n\n return length;\n }\n\nu32bit FTW_EntropySource::fast_poll(byte[], u32bit)\n {\n return 0; \/\/ no op\n }\n\n}\nModify es_ftw to use xor_into_buf\/*************************************************\n* FTW EntropySource Source File *\n* (C) 1999-2008 Jack Lloyd *\n*************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n\n#ifndef _POSIX_C_SOURCE\n #define _POSIX_C_SOURCE 199309\n#endif\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Botan {\n\nnamespace {\n\nclass Directory_Walker : public FTW_EntropySource::File_Descriptor_Source\n {\n public:\n Directory_Walker(const std::string& root) { add_directory(root); }\n ~Directory_Walker();\n\n int next_fd();\n private:\n void add_directory(const std::string&);\n\n std::deque > dirs;\n };\n\nvoid Directory_Walker::add_directory(const std::string& dirname)\n {\n DIR* dir = ::opendir(dirname.c_str());\n if(dir)\n dirs.push_back(std::make_pair(dir, dirname));\n }\n\nDirectory_Walker::~Directory_Walker()\n {\n while(dirs.size())\n {\n ::closedir(dirs[0].first);\n dirs.pop_front();\n }\n }\n\nint Directory_Walker::next_fd()\n {\n while(dirs.size())\n {\n std::pair dirinfo = dirs[0];\n\n struct dirent* entry = ::readdir(dirinfo.first);\n\n if(!entry)\n {\n ::closedir(dirinfo.first);\n dirs.pop_front();\n continue;\n }\n\n const std::string filename = entry->d_name;\n\n if(filename == \".\" || filename == \"..\")\n continue;\n\n const std::string full_path = dirinfo.second + '\/' + filename;\n\n struct stat stat_buf;\n if(::lstat(full_path.c_str(), &stat_buf) == -1)\n continue;\n\n if(S_ISDIR(stat_buf.st_mode))\n add_directory(full_path);\n else if(S_ISREG(stat_buf.st_mode))\n {\n int fd = ::open(full_path.c_str(), O_RDONLY | O_NOCTTY);\n\n if(fd > 0)\n return fd;\n }\n }\n\n return -1;\n }\n\n}\n\n\/**\n* FTW_EntropySource Constructor\n*\/\nFTW_EntropySource::FTW_EntropySource(const std::string& p) : path(p)\n {\n dir = 0;\n }\n\n\/**\n* FTW_EntropySource Destructor\n*\/\nFTW_EntropySource::~FTW_EntropySource()\n {\n delete dir;\n }\n\nu32bit FTW_EntropySource::slow_poll(byte buf[], u32bit length)\n {\n if(!dir)\n dir = new Directory_Walker(path);\n\n SecureVector read_buf(4096);\n\n u32bit bytes_read = 0;\n u32bit buf_i = 0;\n\n while(bytes_read < length * 32)\n {\n int fd = dir->next_fd();\n\n if(fd == -1) \/\/ re-walk\n {\n delete dir;\n dir = new Directory_Walker(path);\n fd = dir->next_fd();\n\n if(fd == -1) \/\/ still fails (directory not mounted, etc) -> fail\n return 0;\n }\n\n ssize_t got = ::read(fd, read_buf.begin(), read_buf.size());\n\n if(got > 0 && got <= read_buf.size())\n {\n buf_i = xor_into_buf(buf, buf_i, length, read_buf, got);\n\n \/\/ never count any one file for more than 128 bytes\n bytes_read += std::min(got, 128);\n }\n\n ::close(fd);\n }\n\n return length;\n }\n\nu32bit FTW_EntropySource::fast_poll(byte[], u32bit)\n {\n return 0; \/\/ no op\n }\n\n}\n<|endoftext|>"} {"text":"#include \"Overlay.h\"\n#include \"ui_Overlay.h\"\n\n#include \"..\/Hearthstone.h\"\n#include \"..\/Settings.h\"\n\n#ifdef Q_OS_MAC\n#include \n#endif\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#define CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS 100\n\nclass OverlayHistoryWindow {\nprivate:\n QString mTitle;\n OverlayHistoryList mHistory;\n\n QFont mRowFont;\n QFont mTitleFont;\n\n int mWidth;\n\n int mPadding;\n int mRowSpacing;\n\n\n int TitleHeight() const {\n QFontMetrics titleMetrics( mTitleFont );\n return titleMetrics.ascent() - titleMetrics.descent();\n }\n\n int Padding() const {\n return mPadding;\n }\n\n int RowSpacing() const {\n return mRowSpacing;\n }\n\n int RowHeight() const {\n QFontMetrics rowMetrics( mRowFont );\n return rowMetrics.ascent() - rowMetrics.descent();\n }\n\n int RowWidth() const {\n return Width() - Padding() * 2;\n }\n\n void DrawMana( QPainter& painter, int x, int y, int width, int height, int mana ) const {\n \/\/ Draw mana\n QPen origPen = painter.pen();\n QPen pen( QColor( 0, 52, 113 ) );\n pen.setCosmetic( true );\n pen.setWidth( 1 );\n painter.setPen( pen );\n\n QBrush brush( QColor( 40, 119, 238 ) );\n painter.setBrush( brush );\n\n QTransform transform;\n painter.translate( x + width * 0.5, y + height * 0.5 );\n painter.scale( width * 0.8, height * 0.8 );\n\n static const QPointF points[5] = {\n QPointF( 0.0, -1.0 ),\n QPointF( 1.0, -0.2 ),\n QPointF( 0.6, 1.0 ),\n QPointF( -0.6, 1.0 ),\n QPointF( -1.0, -0.2 ),\n };\n painter.drawConvexPolygon( points, 5 );\n painter.resetTransform();\n painter.setPen( origPen );\n\n painter.drawText( x, y, width, height, Qt::AlignCenter | Qt::AlignVCenter, QString::number( mana ) );\n }\n\n void DrawCardLine( QPainter& painter, int x, int y, int width, int height, const QString& name, int count ) const {\n painter.save();\n painter.drawText( x, y, width, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, name );\n\n if( count > 1 ) {\n int nameWidth = QFontMetrics( painter.font() ).width( name + \" \" );\n QString countString = QString( \"x%1\" ).arg( count );\n QFont font = painter.font();\n font.setBold( true );\n painter.setFont( font );\n painter.drawText( x + nameWidth, y, width - nameWidth, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, countString );\n }\n painter.restore();\n }\n\npublic:\n OverlayHistoryWindow( const QString& title, const OverlayHistoryList& history, int width, int padding, int rowSpacing, float titleFontSize, float rowFontSize )\n : mTitle( title ), mHistory( history ), mWidth( width ), mPadding( padding ), mRowSpacing( rowSpacing )\n {\n mRowFont.setPointSize( titleFontSize );\n mTitleFont.setPointSize( rowFontSize );\n mTitleFont.setUnderline( true );\n mTitleFont.setBold( true );\n }\n\n int Width() const {\n return mWidth;\n }\n\n int Height() const {\n return ( mHistory.count() - 1 ) * RowSpacing() + \/\/ Spacing between items\n mHistory.count() * RowHeight() + \/\/ Height per item\n TitleHeight() + RowSpacing() + \/\/ Title\n Padding() * 2; \/\/ Overall padding\n }\n\n void Paint( QPainter& painter, int x, int y ) const {\n painter.save();\n\n QRect rect( x, y, Width(), Height() );\n painter.setClipRect( rect );\n\n \/\/ BG\n QPen pen = QPen( QColor( 160, 160, 160 ) );\n pen.setWidth( 3 );\n painter.setPen( pen );\n painter.setBrush( QBrush( QColor( 70, 70, 70, 175 ) ) );\n painter.drawRoundedRect( rect, 10, 10 );\n\n \/\/ Title\n y += Padding();\n painter.setPen( QPen( Qt::white) );\n painter.setFont( mTitleFont );\n painter.drawText( x, y, Width(), TitleHeight(), Qt::AlignCenter | Qt::AlignVCenter | Qt::TextDontClip, mTitle );\n y += TitleHeight() + RowSpacing();\n\n \/\/ Lines\n painter.setPen( QPen( Qt::white) );\n painter.setFont( mRowFont );\n for( const QVariantMap& it : mHistory ) {\n int mx = x + Padding();\n DrawMana( painter, mx, y, RowHeight(), RowHeight(), it[\"mana\"].toInt() );\n int cx = mx + RowHeight() + 5;\n DrawCardLine( painter, cx, y, RowWidth() - cx, RowHeight(), it[\"name\"].toString(), it[\"count\"].toInt() );\n y += RowHeight();\n y += RowSpacing();\n }\n\n painter.restore();\n }\n\n};\n\nOverlay::Overlay( QWidget *parent )\n : QMainWindow( parent ), mUI( new Ui::Overlay ), mShowPlayerHistory( PLAYER_UNKNOWN )\n{\n mUI->setupUi( this );\n setWindowFlags( Qt::NoDropShadowWindowHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::WindowTransparentForInput );\n\n#ifdef Q_OS_WIN\n setWindowFlags( windowFlags() | Qt::Tool );\n#else\n setWindowFlags( windowFlags() | Qt::Window );\n#endif\n\n setAttribute( Qt::WA_TranslucentBackground );\n setAttribute( Qt::WA_ShowWithoutActivating );\n\n connect( Hearthstone::Instance(), &Hearthstone::GameWindowChanged, this, &Overlay::HandleGameWindowChanged );\n connect( Hearthstone::Instance(), &Hearthstone::GameStarted, this, &Overlay::HandleGameStarted );\n connect( Hearthstone::Instance(), &Hearthstone::GameStopped, this, &Overlay::HandleGameStopped );\n\n connect( &mCheckForHoverTimer, &QTimer::timeout, this, &Overlay::CheckForHover );\n\n connect( Settings::Instance(), &Settings::OverlayEnabledChanged, this, &Overlay::HandleOverlaySettingChanged );\n\n LoadCards();\n\n hide();\n\n#ifdef Q_OS_MAC\n WId windowObject = this->winId();\n objc_object* nsviewObject = reinterpret_cast(windowObject);\n objc_object* nsWindowObject = objc_msgSend( nsviewObject, sel_registerName(\"window\") );\n int NSWindowCollectionBehaviorCanJoinAllSpaces = 1 << 0;\n objc_msgSend( nsWindowObject, sel_registerName(\"setCollectionBehavior:\"), NSWindowCollectionBehaviorCanJoinAllSpaces );\n\n \/\/ Ignore mouse events on Mac\n \/\/ Qt::WindowTransparentForInput bug\n \/\/ https:\/\/bugreports.qt.io\/browse\/QTBUG-45498\n objc_msgSend( nsWindowObject, sel_registerName(\"setIgnoresMouseEvents:\"), 1 );\n#endif\n}\n\nOverlay::~Overlay() {\n delete mUI;\n}\n\nvoid Overlay::CheckForHover() {\n QPoint mouseLoc = mapFromGlobal( QCursor::pos() );\n\n Player showPlayerHistory = PLAYER_UNKNOWN;\n\n if( mPlayerDeckRect.contains( mouseLoc ) ) {\n showPlayerHistory = PLAYER_SELF;\n } else if( mOpponentDeckRect.contains( mouseLoc ) ) {\n showPlayerHistory = PLAYER_OPPONENT;\n }\n\n if( mShowPlayerHistory != showPlayerHistory ) {\n mShowPlayerHistory = showPlayerHistory;\n update();\n }\n}\n\nvoid Overlay::LoadCards() {\n QFile file( \":\/data\/cards.json\" );\n bool opened = file.open( QIODevice::ReadOnly | QIODevice::Text );\n assert( opened );\n\n QByteArray jsonData = file.readAll();\n QJsonParseError error;\n QJsonArray jsonCards = QJsonDocument::fromJson( jsonData, &error ).array();\n assert( error.error == QJsonParseError::NoError );\n\n mCardDB.clear();\n\n for( QJsonValueRef jsonCardRef : jsonCards ) {\n QJsonObject jsonCard = jsonCardRef.toObject();\n mCardDB[ jsonCard[\"id\"].toString() ] = jsonCard.toVariantMap();\n }\n}\n\nvoid PaintHistoryInScreen( QPainter& painter, const OverlayHistoryWindow& wnd, const QPoint& pos ) {\n int padding = 10;\n\n QRect rect( pos.x() + 20, pos.y(), wnd.Width(), wnd.Height() );\n rect.translate( -qMax( rect.right() - painter.device()->width() + padding, 0 ), -qMax( rect.bottom() - painter.device()->height() + padding, 0 ) ); \/\/ fit to window\n wnd.Paint( painter, rect.x(), rect.y() );\n}\n\nvoid Overlay::paintEvent( QPaintEvent* ) {\n QString title;\n QRect rect;\n OverlayHistoryList *history = NULL;\n\n if( mShowPlayerHistory == PLAYER_SELF && mPlayerHistory.count() > 0 ) {\n title = \"Cards drawn\";\n history = &mPlayerHistory;\n rect = mPlayerDeckRect;\n } else if( mShowPlayerHistory == PLAYER_OPPONENT && mOpponentHistory.count() > 0 ) {\n title = \"Cards played by opponent\";\n history = &mOpponentHistory;\n rect = mOpponentDeckRect;\n }\n\n QPainter painter( this );\n painter.setRenderHint( QPainter::Antialiasing );\n\n#ifdef Q_OS_WIN\n float rowFontSize = 9;\n float titleFontSize = 9;\n#else\n float rowFontSize = 12;\n float titleFontSize = 12;\n#endif\n\n int spacing = 8;\n int overlayWidth = 200;\n\n if( history ) {\n OverlayHistoryWindow wnd( title, *history, overlayWidth, spacing, spacing, titleFontSize, rowFontSize );\n QPoint pos = rect.center() + QPoint( rect.width() \/ 2 + 10, -wnd.Height() \/ 2 );\n PaintHistoryInScreen( painter, wnd, pos );\n }\n}\n\nvoid Overlay::HandleGameWindowChanged( int x, int y, int w, int h ) {\n move( x, y );\n setFixedSize( w, h );\n\n int minWidth = h * 4 \/ 3;\n mPlayerDeckRect = QRect( w \/ 2 + 0.440 * minWidth, h * 0.510, 0.05 * minWidth, h * 0.170 );\n mOpponentDeckRect = mPlayerDeckRect.translated( -0.005 * minWidth, -0.275 * h );\n\n update();\n}\n\nvoid Overlay::Update() {\n if( Hearthstone::Instance()->GameRunning() && Settings::Instance()->OverlayEnabled() ) {\n show();\n#ifdef Q_OS_WIN\n setAttribute( Qt::WA_QuitOnClose ); \/\/ otherwise taskkill \/IM Track-o-Bot.exe does not work (http:\/\/www.qtcentre.org\/threads\/11713-Qt-Tool?p=62466#post62466)\n#endif\n } else {\n hide();\n }\n\n update();\n}\n\nvoid Overlay::HandleGameStarted() {\n mCheckForHoverTimer.start( CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS );\n Update();\n}\n\nvoid Overlay::HandleGameStopped() {\n mCheckForHoverTimer.stop();\n Update();\n}\n\nvoid Overlay::UpdateHistoryFor( Player player, const ::CardHistoryList& list ) {\n QMap< QString, QVariantMap > entries;\n\n for( const CardHistoryItem& it : list ) {\n const QString& cardId = it.cardId;\n\n if( cardId.isEmpty() ) {\n continue;\n }\n\n if( !mCardDB.contains( cardId ) ) {\n DBG( \"Card %s not found\", qt2cstr( cardId ) );\n continue;\n }\n\n if( mCardDB[ cardId ][ \"type\" ] == \"hero\" ) {\n continue;\n }\n\n if( it.player != player ) {\n continue;\n }\n\n QVariantMap& entry = entries[ cardId ];\n entry[ \"count\" ] = entry.value( \"count\", 0 ).toInt() + 1;\n entry[ \"mana\" ] = mCardDB[ cardId ][ \"mana\" ];\n entry[ \"name\" ] = mCardDB[ cardId ][ \"name\" ];\n }\n\n OverlayHistoryList* ref;\n if( player == PLAYER_SELF ) {\n ref = &mPlayerHistory;\n } else {\n ref = &mOpponentHistory;\n }\n\n *ref = entries.values();\n\n qSort( ref->begin(), ref->end(), []( const QVariantMap& a, const QVariantMap& b ) {\n if( a[\"mana\"].toInt() == b[\"mana\"].toInt() ) {\n return a[\"name\"].toString() < b[\"name\"].toString();\n } else {\n return a[\"mana\"].toInt() < b[\"mana\"].toInt();\n }\n });\n}\n\nvoid Overlay::HandleCardsDrawnUpdate( const ::CardHistoryList& cardsDrawn ) {\n UpdateHistoryFor( PLAYER_OPPONENT, cardsDrawn );\n UpdateHistoryFor( PLAYER_SELF, cardsDrawn );\n Update();\n}\n\nvoid Overlay::HandleOverlaySettingChanged( bool enabled ) {\n UNUSED_ARG( enabled );\n\n Update();\n}\nFix fullscreen issue w\/ overlay#include \"Overlay.h\"\n#include \"ui_Overlay.h\"\n\n#include \"..\/Hearthstone.h\"\n#include \"..\/Settings.h\"\n\n#ifdef Q_OS_MAC\n#include \n#endif\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#define CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS 100\n\nclass OverlayHistoryWindow {\nprivate:\n QString mTitle;\n OverlayHistoryList mHistory;\n\n QFont mRowFont;\n QFont mTitleFont;\n\n int mWidth;\n\n int mPadding;\n int mRowSpacing;\n\n\n int TitleHeight() const {\n QFontMetrics titleMetrics( mTitleFont );\n return titleMetrics.ascent() - titleMetrics.descent();\n }\n\n int Padding() const {\n return mPadding;\n }\n\n int RowSpacing() const {\n return mRowSpacing;\n }\n\n int RowHeight() const {\n QFontMetrics rowMetrics( mRowFont );\n return rowMetrics.ascent() - rowMetrics.descent();\n }\n\n int RowWidth() const {\n return Width() - Padding() * 2;\n }\n\n void DrawMana( QPainter& painter, int x, int y, int width, int height, int mana ) const {\n \/\/ Draw mana\n QPen origPen = painter.pen();\n QPen pen( QColor( 0, 52, 113 ) );\n pen.setCosmetic( true );\n pen.setWidth( 1 );\n painter.setPen( pen );\n\n QBrush brush( QColor( 40, 119, 238 ) );\n painter.setBrush( brush );\n\n QTransform transform;\n painter.translate( x + width * 0.5, y + height * 0.5 );\n painter.scale( width * 0.8, height * 0.8 );\n\n static const QPointF points[5] = {\n QPointF( 0.0, -1.0 ),\n QPointF( 1.0, -0.2 ),\n QPointF( 0.6, 1.0 ),\n QPointF( -0.6, 1.0 ),\n QPointF( -1.0, -0.2 ),\n };\n painter.drawConvexPolygon( points, 5 );\n painter.resetTransform();\n painter.setPen( origPen );\n\n painter.drawText( x, y, width, height, Qt::AlignCenter | Qt::AlignVCenter, QString::number( mana ) );\n }\n\n void DrawCardLine( QPainter& painter, int x, int y, int width, int height, const QString& name, int count ) const {\n painter.save();\n painter.drawText( x, y, width, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, name );\n\n if( count > 1 ) {\n int nameWidth = QFontMetrics( painter.font() ).width( name + \" \" );\n QString countString = QString( \"x%1\" ).arg( count );\n QFont font = painter.font();\n font.setBold( true );\n painter.setFont( font );\n painter.drawText( x + nameWidth, y, width - nameWidth, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, countString );\n }\n painter.restore();\n }\n\npublic:\n OverlayHistoryWindow( const QString& title, const OverlayHistoryList& history, int width, int padding, int rowSpacing, float titleFontSize, float rowFontSize )\n : mTitle( title ), mHistory( history ), mWidth( width ), mPadding( padding ), mRowSpacing( rowSpacing )\n {\n mRowFont.setPointSize( titleFontSize );\n mTitleFont.setPointSize( rowFontSize );\n mTitleFont.setUnderline( true );\n mTitleFont.setBold( true );\n }\n\n int Width() const {\n return mWidth;\n }\n\n int Height() const {\n return ( mHistory.count() - 1 ) * RowSpacing() + \/\/ Spacing between items\n mHistory.count() * RowHeight() + \/\/ Height per item\n TitleHeight() + RowSpacing() + \/\/ Title\n Padding() * 2; \/\/ Overall padding\n }\n\n void Paint( QPainter& painter, int x, int y ) const {\n painter.save();\n\n QRect rect( x, y, Width(), Height() );\n painter.setClipRect( rect );\n\n \/\/ BG\n QPen pen = QPen( QColor( 160, 160, 160 ) );\n pen.setWidth( 3 );\n painter.setPen( pen );\n painter.setBrush( QBrush( QColor( 70, 70, 70, 175 ) ) );\n painter.drawRoundedRect( rect, 10, 10 );\n\n \/\/ Title\n y += Padding();\n painter.setPen( QPen( Qt::white) );\n painter.setFont( mTitleFont );\n painter.drawText( x, y, Width(), TitleHeight(), Qt::AlignCenter | Qt::AlignVCenter | Qt::TextDontClip, mTitle );\n y += TitleHeight() + RowSpacing();\n\n \/\/ Lines\n painter.setPen( QPen( Qt::white) );\n painter.setFont( mRowFont );\n for( const QVariantMap& it : mHistory ) {\n int mx = x + Padding();\n DrawMana( painter, mx, y, RowHeight(), RowHeight(), it[\"mana\"].toInt() );\n int cx = mx + RowHeight() + 5;\n DrawCardLine( painter, cx, y, RowWidth() - cx, RowHeight(), it[\"name\"].toString(), it[\"count\"].toInt() );\n y += RowHeight();\n y += RowSpacing();\n }\n\n painter.restore();\n }\n\n};\n\nOverlay::Overlay( QWidget *parent )\n : QMainWindow( parent ), mUI( new Ui::Overlay ), mShowPlayerHistory( PLAYER_UNKNOWN )\n{\n mUI->setupUi( this );\n setWindowFlags( Qt::NoDropShadowWindowHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::WindowTransparentForInput );\n\n#ifdef Q_OS_WIN\n setWindowFlags( windowFlags() | Qt::Tool );\n#else\n setWindowFlags( windowFlags() | Qt::Window );\n#endif\n\n setAttribute( Qt::WA_TranslucentBackground );\n setAttribute( Qt::WA_ShowWithoutActivating );\n\n connect( Hearthstone::Instance(), &Hearthstone::GameWindowChanged, this, &Overlay::HandleGameWindowChanged );\n connect( Hearthstone::Instance(), &Hearthstone::GameStarted, this, &Overlay::HandleGameStarted );\n connect( Hearthstone::Instance(), &Hearthstone::GameStopped, this, &Overlay::HandleGameStopped );\n\n connect( &mCheckForHoverTimer, &QTimer::timeout, this, &Overlay::CheckForHover );\n\n connect( Settings::Instance(), &Settings::OverlayEnabledChanged, this, &Overlay::HandleOverlaySettingChanged );\n\n LoadCards();\n\n hide();\n\n#ifdef Q_OS_MAC\n WId windowObject = this->winId();\n objc_object* nsviewObject = reinterpret_cast(windowObject);\n objc_object* nsWindowObject = objc_msgSend( nsviewObject, sel_registerName(\"window\") );\n int NSWindowCollectionBehaviorCanJoinAllSpaces = 1 << 0;\n objc_msgSend( nsWindowObject, sel_registerName(\"setCollectionBehavior:\"), NSWindowCollectionBehaviorCanJoinAllSpaces );\n\n \/\/ Ignore mouse events on Mac\n \/\/ Qt::WindowTransparentForInput bug\n \/\/ https:\/\/bugreports.qt.io\/browse\/QTBUG-45498\n objc_msgSend( nsWindowObject, sel_registerName(\"setIgnoresMouseEvents:\"), 1 );\n#endif\n}\n\nOverlay::~Overlay() {\n delete mUI;\n}\n\nvoid Overlay::CheckForHover() {\n QPoint mouseLoc = mapFromGlobal( QCursor::pos() );\n\n Player showPlayerHistory = PLAYER_UNKNOWN;\n\n if( mPlayerDeckRect.contains( mouseLoc ) ) {\n showPlayerHistory = PLAYER_SELF;\n } else if( mOpponentDeckRect.contains( mouseLoc ) ) {\n showPlayerHistory = PLAYER_OPPONENT;\n }\n\n if( mShowPlayerHistory != showPlayerHistory ) {\n mShowPlayerHistory = showPlayerHistory;\n update();\n }\n}\n\nvoid Overlay::LoadCards() {\n QFile file( \":\/data\/cards.json\" );\n bool opened = file.open( QIODevice::ReadOnly | QIODevice::Text );\n assert( opened );\n\n QByteArray jsonData = file.readAll();\n QJsonParseError error;\n QJsonArray jsonCards = QJsonDocument::fromJson( jsonData, &error ).array();\n assert( error.error == QJsonParseError::NoError );\n\n mCardDB.clear();\n\n for( QJsonValueRef jsonCardRef : jsonCards ) {\n QJsonObject jsonCard = jsonCardRef.toObject();\n mCardDB[ jsonCard[\"id\"].toString() ] = jsonCard.toVariantMap();\n }\n}\n\nvoid PaintHistoryInScreen( QPainter& painter, const OverlayHistoryWindow& wnd, const QPoint& pos ) {\n int padding = 10;\n\n QRect rect( pos.x() + 20, pos.y(), wnd.Width(), wnd.Height() );\n rect.translate( -qMax( rect.right() - painter.device()->width() + padding, 0 ), -qMax( rect.bottom() - painter.device()->height() + padding, 0 ) ); \/\/ fit to window\n wnd.Paint( painter, rect.x(), rect.y() );\n}\n\nvoid Overlay::paintEvent( QPaintEvent* ) {\n QString title;\n QRect rect;\n OverlayHistoryList *history = NULL;\n\n if( mShowPlayerHistory == PLAYER_SELF && mPlayerHistory.count() > 0 ) {\n title = \"Cards drawn\";\n history = &mPlayerHistory;\n rect = mPlayerDeckRect;\n } else if( mShowPlayerHistory == PLAYER_OPPONENT && mOpponentHistory.count() > 0 ) {\n title = \"Cards played by opponent\";\n history = &mOpponentHistory;\n rect = mOpponentDeckRect;\n }\n\n QPainter painter( this );\n painter.setRenderHint( QPainter::Antialiasing );\n\n#ifdef Q_OS_WIN\n float rowFontSize = 9;\n float titleFontSize = 9;\n#else\n float rowFontSize = 12;\n float titleFontSize = 12;\n#endif\n\n int spacing = 8;\n int overlayWidth = 200;\n\n if( history ) {\n OverlayHistoryWindow wnd( title, *history, overlayWidth, spacing, spacing, titleFontSize, rowFontSize );\n QPoint pos = rect.center() + QPoint( rect.width() \/ 2 + 10, -wnd.Height() \/ 2 );\n PaintHistoryInScreen( painter, wnd, pos );\n }\n}\n\nvoid Overlay::HandleGameWindowChanged( int x, int y, int w, int h ) {\n \/\/ Order is important\n \/\/ Otherwise starting fullscreen on windows\n \/\/ will not show the overlay unless the FS mode is toggled\n setFixedSize( w, h );\n move( x, y );\n\n int minWidth = h * 4 \/ 3;\n mPlayerDeckRect = QRect( w \/ 2 + 0.440 * minWidth, h * 0.510, 0.05 * minWidth, h * 0.170 );\n mOpponentDeckRect = mPlayerDeckRect.translated( -0.005 * minWidth, -0.275 * h );\n\n Update();\n}\n\nvoid Overlay::Update() {\n if( Hearthstone::Instance()->GameRunning() && Settings::Instance()->OverlayEnabled() ) {\n show();\n#ifdef Q_OS_WIN\n setAttribute( Qt::WA_QuitOnClose ); \/\/ otherwise taskkill \/IM Track-o-Bot.exe does not work (http:\/\/www.qtcentre.org\/threads\/11713-Qt-Tool?p=62466#post62466)\n#endif\n } else {\n hide();\n }\n\n update();\n}\n\nvoid Overlay::HandleGameStarted() {\n mCheckForHoverTimer.start( CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS );\n Update();\n}\n\nvoid Overlay::HandleGameStopped() {\n mCheckForHoverTimer.stop();\n Update();\n}\n\nvoid Overlay::UpdateHistoryFor( Player player, const ::CardHistoryList& list ) {\n QMap< QString, QVariantMap > entries;\n\n for( const CardHistoryItem& it : list ) {\n const QString& cardId = it.cardId;\n\n if( cardId.isEmpty() ) {\n continue;\n }\n\n if( !mCardDB.contains( cardId ) ) {\n DBG( \"Card %s not found\", qt2cstr( cardId ) );\n continue;\n }\n\n if( mCardDB[ cardId ][ \"type\" ] == \"hero\" ) {\n continue;\n }\n\n if( it.player != player ) {\n continue;\n }\n\n QVariantMap& entry = entries[ cardId ];\n entry[ \"count\" ] = entry.value( \"count\", 0 ).toInt() + 1;\n entry[ \"mana\" ] = mCardDB[ cardId ][ \"mana\" ];\n entry[ \"name\" ] = mCardDB[ cardId ][ \"name\" ];\n }\n\n OverlayHistoryList* ref;\n if( player == PLAYER_SELF ) {\n ref = &mPlayerHistory;\n } else {\n ref = &mOpponentHistory;\n }\n\n *ref = entries.values();\n\n qSort( ref->begin(), ref->end(), []( const QVariantMap& a, const QVariantMap& b ) {\n if( a[\"mana\"].toInt() == b[\"mana\"].toInt() ) {\n return a[\"name\"].toString() < b[\"name\"].toString();\n } else {\n return a[\"mana\"].toInt() < b[\"mana\"].toInt();\n }\n });\n}\n\nvoid Overlay::HandleCardsDrawnUpdate( const ::CardHistoryList& cardsDrawn ) {\n UpdateHistoryFor( PLAYER_OPPONENT, cardsDrawn );\n UpdateHistoryFor( PLAYER_SELF, cardsDrawn );\n Update();\n}\n\nvoid Overlay::HandleOverlaySettingChanged( bool enabled ) {\n UNUSED_ARG( enabled );\n\n Update();\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"libs\/catch\/catch.hpp\"\n\n#include \"src\/dopt_node.h\"\n\nTEST_CASE(\"entangle|dopt_node-enc\") {\n\tauto n = entangle::OTNode(8888, 100);\n\tentangle::upd_t u = { entangle::del, 100, 'c' };\n\tREQUIRE(n.enc_upd_t(u).compare(\"1:100:c\") == 0);\n\tREQUIRE(n.cmp_upd_t({ entangle::del, 100, 'c'}, { entangle::del, 100, 'c' }) == true);\n\tREQUIRE(n.cmp_upd_t({ entangle::del, 100, 'c'}, { entangle::del, 100, 'd' }) == false);\n\tREQUIRE(n.cmp_upd_t(n.dec_upd_t(\"1:100:c\"), { entangle::del, 100, 'c' }) == true);\n}\n\nTEST_CASE(\"entangle|dopt_node-insert\") {\n\tauto s = entangle::OTNode(8000, 100);\n\tauto x = entangle::OTNode(8050, 1);\n\t\/\/ auto y = entangle::OTNode(8051, 1);\n\t\/\/ auto z = entangle::OTNode(8052, 1);\n\n\tREQUIRE_NOTHROW(s.up());\n\tREQUIRE_NOTHROW(x.up());\n\tREQUIRE(x.join(\"localhost\", 8000) == true);\n\n\tREQUIRE(x.ins(0, '1') == true);\n\tsleep(1);\n\n\tREQUIRE(s.get_context().compare(\"1\") == 0);\n\tREQUIRE(x.get_context().compare(\"1\") == 0);\n\n\tREQUIRE(x.del(0) == true);\n\tsleep(1);\n\n\tREQUIRE(s.get_context().compare(\"\") == 0);\n\tREQUIRE(x.get_context().compare(\"\") == 0);\n\n\tREQUIRE(x.drop(\"localhost\", 8000) == true);\n\tREQUIRE_NOTHROW(s.dn());\n\tREQUIRE_NOTHROW(x.dn());\n}\n\nTEST_CASE(\"entangle|dopt_node-daemon\") {\n\tauto n = entangle::OTNode(8888, 100);\n\tauto m = entangle::OTNode(8889, 100);\n\n\tREQUIRE(m.join(\"localhost\", 8888) == false);\n\n\tREQUIRE_NOTHROW(n.up());\n\tREQUIRE_NOTHROW(n.dn());\n\n\tREQUIRE_NOTHROW(n.up());\n\tREQUIRE_NOTHROW(m.up());\n\tREQUIRE(m.join(\"localhost\", 8888) == true);\n\tsleep(1);\n\tREQUIRE(m.size() == 1);\n\tREQUIRE(n.size() == 1);\n\tREQUIRE(m.join(\"localhost\", 8888) == false);\n\tREQUIRE(n.join(\"localhost\", 8889) == false);\n\tREQUIRE(m.size() == 1);\n\tREQUIRE(n.size() == 1);\n\tREQUIRE(m.drop(\"localhost\", 8888) == true);\n\tsleep(1);\n\tREQUIRE(m.size() == 0);\n\tREQUIRE(n.size() == 0);\n\tREQUIRE_NOTHROW(m.dn());\n\tREQUIRE_NOTHROW(n.dn());\n\n\t\/\/ auto-call OTNode::dn on stack unwind\n\tREQUIRE_NOTHROW(n.up());\n\tsleep(1);\n}\nmore tests#include \n#include \n\n#include \"libs\/catch\/catch.hpp\"\n\n#include \"src\/dopt_node.h\"\n\nTEST_CASE(\"entangle|dopt_node-enc\") {\n\tauto n = entangle::OTNode(8888, 100);\n\tentangle::upd_t u = { entangle::del, 100, 'c' };\n\tREQUIRE(n.enc_upd_t(u).compare(\"1:100:c\") == 0);\n\tREQUIRE(n.cmp_upd_t({ entangle::del, 100, 'c'}, { entangle::del, 100, 'c' }) == true);\n\tREQUIRE(n.cmp_upd_t({ entangle::del, 100, 'c'}, { entangle::del, 100, 'd' }) == false);\n\tREQUIRE(n.cmp_upd_t(n.dec_upd_t(\"1:100:c\"), { entangle::del, 100, 'c' }) == true);\n}\n\nTEST_CASE(\"entangle|dopt_node-insert\") {\n\tauto s = entangle::OTNode(8000, 100);\n\tauto x = entangle::OTNode(8050, 1);\n\tauto y = entangle::OTNode(8051, 1);\n\tauto z = entangle::OTNode(8052, 1);\n\n\tREQUIRE_NOTHROW(s.up());\n\tREQUIRE_NOTHROW(x.up());\n\tREQUIRE_NOTHROW(y.up());\n\tREQUIRE_NOTHROW(z.up());\n\tREQUIRE(x.join(\"localhost\", 8000) == true);\n\tREQUIRE(y.join(\"localhost\", 8000) == true);\n\tREQUIRE(z.join(\"localhost\", 8000) == true);\n\n\tREQUIRE(x.ins(0, '1') == true);\n\tsleep(1);\n\n\tREQUIRE(s.get_context().compare(\"1\") == 0);\n\tREQUIRE(x.get_context().compare(\"1\") == 0);\n\tREQUIRE(y.get_context().compare(\"1\") == 0);\n\tREQUIRE(z.get_context().compare(\"1\") == 0);\n\n\tREQUIRE(x.del(0) == true);\n\tsleep(1);\n\n\tREQUIRE(s.get_context().compare(\"\") == 0);\n\tREQUIRE(x.get_context().compare(\"\") == 0);\n\tREQUIRE(y.get_context().compare(\"\") == 0);\n\tREQUIRE(z.get_context().compare(\"\") == 0);\n\n\tREQUIRE(x.drop(\"localhost\", 8000) == true);\n\tREQUIRE_NOTHROW(s.dn());\n\tREQUIRE_NOTHROW(x.dn());\n\tREQUIRE_NOTHROW(y.dn());\n\tREQUIRE_NOTHROW(z.dn());\n}\n\nTEST_CASE(\"entangle|dopt_node-daemon\") {\n\tauto n = entangle::OTNode(8888, 100);\n\tauto m = entangle::OTNode(8889, 100);\n\n\tREQUIRE(m.join(\"localhost\", 8888) == false);\n\n\tREQUIRE_NOTHROW(n.up());\n\tREQUIRE_NOTHROW(n.dn());\n\n\tREQUIRE_NOTHROW(n.up());\n\tREQUIRE_NOTHROW(m.up());\n\tREQUIRE(m.join(\"localhost\", 8888) == true);\n\tsleep(1);\n\tREQUIRE(m.size() == 1);\n\tREQUIRE(n.size() == 1);\n\tREQUIRE(m.join(\"localhost\", 8888) == false);\n\tREQUIRE(n.join(\"localhost\", 8889) == false);\n\tREQUIRE(m.size() == 1);\n\tREQUIRE(n.size() == 1);\n\tREQUIRE(m.drop(\"localhost\", 8888) == true);\n\tsleep(1);\n\tREQUIRE(m.size() == 0);\n\tREQUIRE(n.size() == 0);\n\tREQUIRE_NOTHROW(m.dn());\n\tREQUIRE_NOTHROW(n.dn());\n\n\t\/\/ auto-call OTNode::dn on stack unwind\n\tREQUIRE_NOTHROW(n.up());\n\tsleep(1);\n}\n<|endoftext|>"} {"text":"\/************************************************************************************\n * Copyright (C) 2014-2015 by Savoir-Faire Linux *\n * Author : Emmanuel Lepage Vallee *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 2.1 of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this library; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n ***********************************************************************************\/\n#include \"fallbackpersoncollection.h\"\n\n\/\/Qt\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/Ring\n#include \"person.h\"\n#include \"personmodel.h\"\n#include \"private\/vcardutils.h\"\n#include \"contactmethod.h\"\n#include \"collectioneditor.h\"\n#include \"delegates\/pixmapmanipulationdelegate.h\"\n#include \"delegates\/itemmodelstateserializationdelegate.h\"\n#include \"private\/threadworker.h\"\n\nclass FallbackPersonBackendEditor final : public CollectionEditor\n{\npublic:\n FallbackPersonBackendEditor(CollectionMediator* m, const QString& path) : CollectionEditor(m),m_Path(path) {}\n virtual bool save ( const Person* item ) override;\n virtual bool remove ( const Person* item ) override;\n virtual bool edit ( Person* item ) override;\n virtual bool addNew ( const Person* item ) override;\n virtual bool addExisting( const Person* item ) override;\n\n QVector m_lItems;\n QString m_Path ;\n QHash m_hPaths;\n\nprivate:\n virtual QVector items() const override;\n};\n\nclass FallbackPersonCollectionPrivate final : public QObject\n{\n Q_OBJECT\npublic:\n FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator* mediator, const QString& path);\n CollectionMediator* m_pMediator;\n QString m_Path ;\n QString m_Name ;\n\n FallbackPersonCollection* q_ptr;\n\npublic Q_SLOTS:\n void loadAsync();\n};\n\nFallbackPersonCollectionPrivate::FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator* mediator, const QString& path) : q_ptr(parent), m_pMediator(mediator), m_Path(path)\n{\n \/\/Default to somewhere ~\/.local\/share\n if (m_Path.isEmpty()) {\n m_Path = (QStandardPaths::writableLocation(QStandardPaths::DataLocation)) + \"\/vCard\/\";\n static_cast(q_ptr->editor())->m_Path = m_Path;\n }\n\n m_Name = path.split('\/').last();\n if (m_Name.size())\n m_Name[0] = m_Name[0].toUpper();\n else\n m_Name = \"vCard\";\n}\n\nFallbackPersonCollection::FallbackPersonCollection(CollectionMediator* mediator, const QString& path, FallbackPersonCollection* parent) :\nCollectionInterface(new FallbackPersonBackendEditor(mediator,path),parent),d_ptr(new FallbackPersonCollectionPrivate(this,mediator,path))\n{\n}\n\nFallbackPersonCollection::~FallbackPersonCollection()\n{\n delete d_ptr;\n}\n\nbool FallbackPersonBackendEditor::save(const Person* item)\n{\n if (!item)\n return false;\n\n \/\/An UID is required\n if (item->uid().isEmpty()) {\n QCryptographicHash hash(QCryptographicHash::Sha1);\n for (ContactMethod* n : item->phoneNumbers())\n hash.addData(n->uri().toLatin1());\n hash.addData(item->formattedName().toLatin1());\n QByteArray random;\n\n for (int i=0;i<5;i++)\n random.append(QChar((char)(rand()%255)));\n\n hash.addData(random);\n\n const_cast(item)->setUid(hash.result().toHex());\n }\n\n QFile file(m_Path+'\/'+item->uid()+\".vcf\");\n file.open(QIODevice::WriteOnly);\n file.write(item->toVCard({}));\n file.close();\n return true;\n}\n\nbool FallbackPersonBackendEditor::remove(const Person* item)\n{\n if (!item)\n return false;\n\n QString path = m_hPaths[item];\n\n if (path.isEmpty())\n path = m_Path+'\/'+item->uid()+\".vcf\";\n\n bool ret = QFile::remove(path);\n\n if (ret) {\n ret &= mediator()->removeItem(item);\n }\n\n return ret;\n}\n\nbool FallbackPersonBackendEditor::edit( Person* item)\n{\n Q_UNUSED(item)\n return false;\n}\n\nbool FallbackPersonBackendEditor::addNew(const Person* item)\n{\n bool ret = save(item);\n\n if (ret) {\n addExisting(item);\n }\n\n return ret;\n}\n\nbool FallbackPersonBackendEditor::addExisting(const Person* item)\n{\n m_lItems << const_cast(item);\n mediator()->addItem(item);\n return true;\n}\n\nQVector FallbackPersonBackendEditor::items() const\n{\n return m_lItems;\n}\n\nQString FallbackPersonCollection::name () const\n{\n return d_ptr->m_Name;\n}\n\nQString FallbackPersonCollection::category () const\n{\n return QObject::tr(\"Contact\");\n}\n\nQVariant FallbackPersonCollection::icon() const\n{\n return PixmapManipulationDelegate::instance()->collectionIcon(this,PixmapManipulationDelegate::CollectionIconHint::CONTACT);\n}\n\nbool FallbackPersonCollection::isEnabled() const\n{\n \/* if delegate exists, check if collectin is enabled, else assume it is *\/\n if (auto delegate = ItemModelStateSerializationDelegate::instance())\n return delegate->isChecked(this);\n else\n return true;\n}\n\nbool FallbackPersonCollection::load()\n{\n new ThreadWorker([this]() {\n bool ok;\n Q_UNUSED(ok)\n QList< Person* > ret = VCardUtils::loadDir(QUrl(d_ptr->m_Path),ok,static_cast(editor())->m_hPaths);\n for(Person* p : ret) {\n p->setCollection(this);\n editor()->addExisting(p);\n }\n });\n\n \/\/Add all sub directories as new backends\n QTimer::singleShot(0,d_ptr,SLOT(loadAsync()));\n\n return true;\n}\n\nbool FallbackPersonCollection::reload()\n{\n return false;\n}\n\nFlagPack FallbackPersonCollection::supportedFeatures() const\n{\n return\n CollectionInterface::SupportedFeatures::NONE |\n CollectionInterface::SupportedFeatures::LOAD |\n CollectionInterface::SupportedFeatures::CLEAR |\n CollectionInterface::SupportedFeatures::MANAGEABLE |\n CollectionInterface::SupportedFeatures::REMOVE |\n CollectionInterface::SupportedFeatures::ADD ;\n}\n\nbool FallbackPersonCollection::clear()\n{\n QDir dir(d_ptr->m_Path);\n for (const QString& file : dir.entryList({\"*.vcf\"},QDir::Files))\n dir.remove(file);\n return true;\n}\n\nQByteArray FallbackPersonCollection::id() const\n{\n return \"fpc2\"+d_ptr->m_Path.toLatin1();\n}\n\n\nvoid FallbackPersonCollectionPrivate::loadAsync()\n{\n QDir d(m_Path);\n for (const QString& dir : d.entryList(QDir::AllDirs)) {\n if (dir != QString('.') && dir != \"..\") {\n CollectionInterface* col = PersonModel::instance()->addCollection(m_Path+'\/'+dir,q_ptr);\n if (col->isEnabled()) {\n col->load();\n }\n }\n }\n}\n\n#include \"fallbackpersoncollection.moc\"\nvcard: make sure vcard dir exists\/************************************************************************************\n * Copyright (C) 2014-2015 by Savoir-Faire Linux *\n * Author : Emmanuel Lepage Vallee *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 2.1 of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this library; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n ***********************************************************************************\/\n#include \"fallbackpersoncollection.h\"\n\n\/\/Qt\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/Ring\n#include \"person.h\"\n#include \"personmodel.h\"\n#include \"private\/vcardutils.h\"\n#include \"contactmethod.h\"\n#include \"collectioneditor.h\"\n#include \"delegates\/pixmapmanipulationdelegate.h\"\n#include \"delegates\/itemmodelstateserializationdelegate.h\"\n#include \"private\/threadworker.h\"\n\nclass FallbackPersonBackendEditor final : public CollectionEditor\n{\npublic:\n FallbackPersonBackendEditor(CollectionMediator* m, const QString& path) : CollectionEditor(m),m_Path(path) {}\n virtual bool save ( const Person* item ) override;\n virtual bool remove ( const Person* item ) override;\n virtual bool edit ( Person* item ) override;\n virtual bool addNew ( const Person* item ) override;\n virtual bool addExisting( const Person* item ) override;\n\n QVector m_lItems;\n QString m_Path ;\n QHash m_hPaths;\n\nprivate:\n virtual QVector items() const override;\n};\n\nclass FallbackPersonCollectionPrivate final : public QObject\n{\n Q_OBJECT\npublic:\n FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator* mediator, const QString& path);\n CollectionMediator* m_pMediator;\n QString m_Path ;\n QString m_Name ;\n\n FallbackPersonCollection* q_ptr;\n\npublic Q_SLOTS:\n void loadAsync();\n};\n\nFallbackPersonCollectionPrivate::FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator* mediator, const QString& path) : q_ptr(parent), m_pMediator(mediator), m_Path(path)\n{\n \/\/Default to somewhere ~\/.local\/share\n if (m_Path.isEmpty()) {\n m_Path = (QStandardPaths::writableLocation(QStandardPaths::DataLocation)) + \"\/vCard\/\";\n static_cast(q_ptr->editor())->m_Path = m_Path;\n }\n \/\/Make sure the directory exists so that saving new contacts there doesn't fail\n if (!QDir().mkpath(m_Path))\n qWarning() << \"cannot create path for fallbackcollection: \" << m_Path;\n\n m_Name = path.split('\/').last();\n if (m_Name.size())\n m_Name[0] = m_Name[0].toUpper();\n else\n m_Name = \"vCard\";\n}\n\nFallbackPersonCollection::FallbackPersonCollection(CollectionMediator* mediator, const QString& path, FallbackPersonCollection* parent) :\nCollectionInterface(new FallbackPersonBackendEditor(mediator,path),parent),d_ptr(new FallbackPersonCollectionPrivate(this,mediator,path))\n{\n}\n\nFallbackPersonCollection::~FallbackPersonCollection()\n{\n delete d_ptr;\n}\n\nbool FallbackPersonBackendEditor::save(const Person* item)\n{\n if (!item)\n return false;\n\n \/\/An UID is required\n if (item->uid().isEmpty()) {\n QCryptographicHash hash(QCryptographicHash::Sha1);\n for (ContactMethod* n : item->phoneNumbers())\n hash.addData(n->uri().toLatin1());\n hash.addData(item->formattedName().toLatin1());\n QByteArray random;\n\n for (int i=0;i<5;i++)\n random.append(QChar((char)(rand()%255)));\n\n hash.addData(random);\n\n const_cast(item)->setUid(hash.result().toHex());\n }\n\n QFile file(m_Path+'\/'+item->uid()+\".vcf\");\n file.open(QIODevice::WriteOnly);\n file.write(item->toVCard({}));\n file.close();\n return true;\n}\n\nbool FallbackPersonBackendEditor::remove(const Person* item)\n{\n if (!item)\n return false;\n\n QString path = m_hPaths[item];\n\n if (path.isEmpty())\n path = m_Path+'\/'+item->uid()+\".vcf\";\n\n bool ret = QFile::remove(path);\n\n if (ret) {\n ret &= mediator()->removeItem(item);\n }\n\n return ret;\n}\n\nbool FallbackPersonBackendEditor::edit( Person* item)\n{\n Q_UNUSED(item)\n return false;\n}\n\nbool FallbackPersonBackendEditor::addNew(const Person* item)\n{\n bool ret = save(item);\n\n if (ret) {\n addExisting(item);\n }\n\n return ret;\n}\n\nbool FallbackPersonBackendEditor::addExisting(const Person* item)\n{\n m_lItems << const_cast(item);\n mediator()->addItem(item);\n return true;\n}\n\nQVector FallbackPersonBackendEditor::items() const\n{\n return m_lItems;\n}\n\nQString FallbackPersonCollection::name () const\n{\n return d_ptr->m_Name;\n}\n\nQString FallbackPersonCollection::category () const\n{\n return QObject::tr(\"Contact\");\n}\n\nQVariant FallbackPersonCollection::icon() const\n{\n return PixmapManipulationDelegate::instance()->collectionIcon(this,PixmapManipulationDelegate::CollectionIconHint::CONTACT);\n}\n\nbool FallbackPersonCollection::isEnabled() const\n{\n \/* if delegate exists, check if collectin is enabled, else assume it is *\/\n if (auto delegate = ItemModelStateSerializationDelegate::instance())\n return delegate->isChecked(this);\n else\n return true;\n}\n\nbool FallbackPersonCollection::load()\n{\n new ThreadWorker([this]() {\n bool ok;\n Q_UNUSED(ok)\n QList< Person* > ret = VCardUtils::loadDir(QUrl(d_ptr->m_Path),ok,static_cast(editor())->m_hPaths);\n for(Person* p : ret) {\n p->setCollection(this);\n editor()->addExisting(p);\n }\n });\n\n \/\/Add all sub directories as new backends\n QTimer::singleShot(0,d_ptr,SLOT(loadAsync()));\n\n return true;\n}\n\nbool FallbackPersonCollection::reload()\n{\n return false;\n}\n\nFlagPack FallbackPersonCollection::supportedFeatures() const\n{\n return\n CollectionInterface::SupportedFeatures::NONE |\n CollectionInterface::SupportedFeatures::LOAD |\n CollectionInterface::SupportedFeatures::CLEAR |\n CollectionInterface::SupportedFeatures::MANAGEABLE |\n CollectionInterface::SupportedFeatures::REMOVE |\n CollectionInterface::SupportedFeatures::ADD ;\n}\n\nbool FallbackPersonCollection::clear()\n{\n QDir dir(d_ptr->m_Path);\n for (const QString& file : dir.entryList({\"*.vcf\"},QDir::Files))\n dir.remove(file);\n return true;\n}\n\nQByteArray FallbackPersonCollection::id() const\n{\n return \"fpc2\"+d_ptr->m_Path.toLatin1();\n}\n\n\nvoid FallbackPersonCollectionPrivate::loadAsync()\n{\n QDir d(m_Path);\n for (const QString& dir : d.entryList(QDir::AllDirs)) {\n if (dir != QString('.') && dir != \"..\") {\n CollectionInterface* col = PersonModel::instance()->addCollection(m_Path+'\/'+dir,q_ptr);\n if (col->isEnabled()) {\n col->load();\n }\n }\n }\n}\n\n#include \"fallbackpersoncollection.moc\"\n<|endoftext|>"} {"text":"#include \"saiga\/util\/crash.h\"\n#include \"saiga\/util\/assert.h\"\n\n#include \n\nstd::function customCrashHandler;\n\nvoid addCustomSegfaultHandler(std::function fnc)\n{\n\tcustomCrashHandler = fnc;\n}\n\n\n#if defined(__unix__)\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/Source: http:\/\/stackoverflow.com\/questions\/77005\/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes\n\n\/* This structure mirrors the one found in \/usr\/include\/asm\/ucontext.h *\/\ntypedef struct _sig_ucontext {\n unsigned long uc_flags;\n struct ucontext *uc_link;\n stack_t uc_stack;\n struct sigcontext uc_mcontext;\n sigset_t uc_sigmask;\n} sig_ucontext_t;\n\nvoid crit_err_hdlr(int sig_num, siginfo_t * info, void * ucontext)\n{\n void * array[50];\n void * caller_address;\n char ** messages;\n int size, i;\n sig_ucontext_t * uc;\n\n uc = (sig_ucontext_t *)ucontext;\n\n \/* Get the address at the time the signal was raised *\/\n#if defined(__i386__) \/\/ gcc specific\n caller_address = (void *) uc->uc_mcontext.eip; \/\/ EIP: x86 specific\n#elif defined(__x86_64__) \/\/ gcc specific\n caller_address = (void *) uc->uc_mcontext.rip; \/\/ RIP: x86_64 specific\n#else\n#error Unsupported architecture. \/\/ TODO: Add support for other arch.\n#endif\n\n std:: cout << \"signal \" << sig_num << \" (\" << strsignal(sig_num) << \")\"\n << \", address is \" << info->si_addr << \" from \" << (void *)caller_address << std::endl;\n\n\n size = backtrace(array, 50);\n\n \/* overwrite sigaction with caller's address *\/\n array[1] = caller_address;\n\n messages = backtrace_symbols(array, size);\n\n \/* skip first stack frame (points here) *\/\n for (i = 1; i < size && messages != NULL; ++i){\n std::cout << \"[bt]: (\" << i << \") \" << messages[i] << std::endl;\n }\n\n free(messages);\n\n if(customCrashHandler)\n customCrashHandler();\n\n\n \/\/make sure the program exits here, because otherwise the programm will continue after the segfault\n SAIGA_ASSERT(0);\n exit(EXIT_FAILURE);\n}\n\n\nvoid catchSegFaults()\n{\n struct sigaction sigact;\n\n sigact.sa_sigaction = crit_err_hdlr;\n sigact.sa_flags = SA_RESTART | SA_SIGINFO;\n\n if (sigaction(SIGSEGV, &sigact, (struct sigaction *)NULL) != 0){\n std::cerr << \"error setting signal handlern\" << std::endl;\n SAIGA_ASSERT(0);\n }\n}\n\n#endif\n\n#if defined(_WIN32)\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\/\/The code requires you to link against the DbgHelp.lib library\n\nvoid printCurrentStack() {\n\tstd::string outWalk;\n\t\/\/ Set up the symbol options so that we can gather information from the current\n\t\/\/ executable's PDB files, as well as the Microsoft symbol servers. We also want\n\t\/\/ to undecorate the symbol names we're returned. If you want, you can add other\n\t\/\/ symbol servers or paths via a semi-colon separated list in SymInitialized.\n\t::SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_INCLUDE_32BIT_MODULES | SYMOPT_UNDNAME);\n\tif (!::SymInitialize(::GetCurrentProcess(), \"http:\/\/msdl.microsoft.com\/download\/symbols\", TRUE)) return;\n\n\t\/\/ Capture up to 25 stack frames from the current call stack. We're going to\n\t\/\/ skip the first stack frame returned because that's the GetStackWalk function\n\t\/\/ itself, which we don't care about.\n\tPVOID addrs[25] = { 0 };\n\tUSHORT frames = CaptureStackBackTrace(1, 25, addrs, NULL);\n\n\tfor (USHORT i = 0; i < frames; i++) {\n\t\t\/\/ Allocate a buffer large enough to hold the symbol information on the stack and get \n\t\t\/\/ a pointer to the buffer. We also have to set the size of the symbol structure itself\n\t\t\/\/ and the number of bytes reserved for the name.\n\t\tULONG64 buffer[(sizeof(SYMBOL_INFO) + 1024 + sizeof(ULONG64) - 1) \/ sizeof(ULONG64)] = { 0 };\n\t\tSYMBOL_INFO *info = (SYMBOL_INFO *)buffer;\n\t\tinfo->SizeOfStruct = sizeof(SYMBOL_INFO);\n\t\tinfo->MaxNameLen = 1024;\n\n\t\t\/\/ Attempt to get information about the symbol and add it to our output parameter.\n\t\tDWORD64 displacement = 0;\n\t\tif (::SymFromAddr(::GetCurrentProcess(), (DWORD64)addrs[i], &displacement, info)) {\n\t\t\t\/\/outWalk.append(info->Name, info->NameLen);\n\t\t\t\/\/outWalk.append(\"\\n\");\n\t\t\tstd::cout << \"[bt]: (\" << i << \") \" << info->Name << std::endl;\n\t\t}\n\t}\n\n\t::SymCleanup(::GetCurrentProcess());\n\n}\n\nvoid SignalHandler(int signal)\n{\n\tprintCurrentStack();\n\n\tif (customCrashHandler)\n\t\tcustomCrashHandler();\n\n\n\t\/\/make sure the program exits here, because otherwise the programm will continue after the segfault\n\tSAIGA_ASSERT(0);\n\texit(EXIT_FAILURE);\n}\n\nvoid catchSegFaults()\n{\n\ttypedef void(*SignalHandlerPointer)(int);\n\n\tSignalHandlerPointer previousHandler;\n\tpreviousHandler = signal(SIGSEGV, SignalHandler);\n}\n#endifcrash#include \"saiga\/util\/crash.h\"\n#include \"saiga\/util\/assert.h\"\n\n#include \n\nstd::function customCrashHandler;\n\nvoid addCustomSegfaultHandler(std::function fnc)\n{\n\tcustomCrashHandler = fnc;\n}\n\n\n#if defined(__unix__)\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/Source: http:\/\/stackoverflow.com\/questions\/77005\/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes\n\n\/* This structure mirrors the one found in \/usr\/include\/asm\/ucontext.h *\/\ntypedef struct _sig_ucontext {\n unsigned long uc_flags;\n struct ucontext *uc_link;\n stack_t uc_stack;\n struct sigcontext uc_mcontext;\n sigset_t uc_sigmask;\n} sig_ucontext_t;\n\n\nvoid printCurrentStack(){\n void * array[50];\n char ** messages;\n int size, i;\n\n size = backtrace(array, 50);\n\n \/* overwrite sigaction with caller's address *\/\n\/\/ array[1] = caller_address;\n\n messages = backtrace_symbols(array, size);\n\n \/* skip first stack frame (points here) *\/\n for (i = 0; i < size && messages != NULL; ++i){\n std::cout << \"[bt]: (\" << i << \") \" << messages[i] << std::endl;\n }\n\n free(messages);\n}\n\nvoid crit_err_hdlr(int sig_num, siginfo_t * info, void * ucontext)\n{\n void * caller_address;\n sig_ucontext_t * uc;\n\n uc = (sig_ucontext_t *)ucontext;\n\n \/* Get the address at the time the signal was raised *\/\n#if defined(__i386__) \/\/ gcc specific\n caller_address = (void *) uc->uc_mcontext.eip; \/\/ EIP: x86 specific\n#elif defined(__x86_64__) \/\/ gcc specific\n caller_address = (void *) uc->uc_mcontext.rip; \/\/ RIP: x86_64 specific\n#else\n#error Unsupported architecture. \/\/ TODO: Add support for other arch.\n#endif\n\n std:: cout << \"signal \" << sig_num << \" (\" << strsignal(sig_num) << \")\"\n << \", address is \" << info->si_addr << \" from \" << (void *)caller_address << std::endl;\n\n\n printCurrentStack();\n\n if(customCrashHandler)\n customCrashHandler();\n\n\n \/\/make sure the program exits here, because otherwise the programm will continue after the segfault\n SAIGA_ASSERT(0);\n exit(EXIT_FAILURE);\n}\n\n\nvoid catchSegFaults()\n{\n struct sigaction sigact;\n\n sigact.sa_sigaction = crit_err_hdlr;\n sigact.sa_flags = SA_RESTART | SA_SIGINFO;\n\n if (sigaction(SIGSEGV, &sigact, (struct sigaction *)NULL) != 0){\n std::cerr << \"error setting signal handlern\" << std::endl;\n SAIGA_ASSERT(0);\n }\n}\n\n#endif\n\n#if defined(_WIN32)\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\/\/The code requires you to link against the DbgHelp.lib library\n\nvoid printCurrentStack() {\n\tstd::string outWalk;\n\t\/\/ Set up the symbol options so that we can gather information from the current\n\t\/\/ executable's PDB files, as well as the Microsoft symbol servers. We also want\n\t\/\/ to undecorate the symbol names we're returned. If you want, you can add other\n\t\/\/ symbol servers or paths via a semi-colon separated list in SymInitialized.\n\t::SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_INCLUDE_32BIT_MODULES | SYMOPT_UNDNAME);\n\tif (!::SymInitialize(::GetCurrentProcess(), \"http:\/\/msdl.microsoft.com\/download\/symbols\", TRUE)) return;\n\n\t\/\/ Capture up to 25 stack frames from the current call stack. We're going to\n\t\/\/ skip the first stack frame returned because that's the GetStackWalk function\n\t\/\/ itself, which we don't care about.\n const int numAddrs = 50;\n PVOID addrs[numAddrs] = { 0 };\n USHORT frames = CaptureStackBackTrace(0, numAddrs-1, addrs, NULL);\n\n\tfor (USHORT i = 0; i < frames; i++) {\n\t\t\/\/ Allocate a buffer large enough to hold the symbol information on the stack and get \n\t\t\/\/ a pointer to the buffer. We also have to set the size of the symbol structure itself\n\t\t\/\/ and the number of bytes reserved for the name.\n\t\tULONG64 buffer[(sizeof(SYMBOL_INFO) + 1024 + sizeof(ULONG64) - 1) \/ sizeof(ULONG64)] = { 0 };\n\t\tSYMBOL_INFO *info = (SYMBOL_INFO *)buffer;\n\t\tinfo->SizeOfStruct = sizeof(SYMBOL_INFO);\n\t\tinfo->MaxNameLen = 1024;\n\n\t\t\/\/ Attempt to get information about the symbol and add it to our output parameter.\n\t\tDWORD64 displacement = 0;\n\t\tif (::SymFromAddr(::GetCurrentProcess(), (DWORD64)addrs[i], &displacement, info)) {\n\t\t\t\/\/outWalk.append(info->Name, info->NameLen);\n\t\t\t\/\/outWalk.append(\"\\n\");\n\t\t\tstd::cout << \"[bt]: (\" << i << \") \" << info->Name << std::endl;\n\t\t}\n\t}\n\n\t::SymCleanup(::GetCurrentProcess());\n\n}\n\nvoid SignalHandler(int signal)\n{\n\tprintCurrentStack();\n\n\tif (customCrashHandler)\n\t\tcustomCrashHandler();\n\n\n\t\/\/make sure the program exits here, because otherwise the programm will continue after the segfault\n\tSAIGA_ASSERT(0);\n\texit(EXIT_FAILURE);\n}\n\nvoid catchSegFaults()\n{\n\ttypedef void(*SignalHandlerPointer)(int);\n\n\tSignalHandlerPointer previousHandler;\n\tpreviousHandler = signal(SIGSEGV, SignalHandler);\n}\n#endif\n<|endoftext|>"} {"text":"#include \"tests\/lib\/test.h\"\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing Tp::PendingOperation;\nusing Tp::PendingVoid;\nusing Tp::Client::DBus::PeerInterface;\n\nTest::Test(QObject *parent)\n : QObject(parent), mLoop(new QEventLoop(this))\n{\n QTimer::singleShot(10 * 60 * 1000, this, SLOT(onWatchdog()));\n}\n\nTest::~Test()\n{\n delete mLoop;\n}\n\nvoid Test::initTestCaseImpl()\n{\n Tp::registerTypes();\n Tp::enableDebug(true);\n Tp::enableWarnings(true);\n\n QVERIFY(QDBusConnection::sessionBus().isConnected());\n}\n\nvoid Test::initImpl()\n{\n}\n\nvoid Test::cleanupImpl()\n{\n}\n\nvoid Test::cleanupTestCaseImpl()\n{\n \/\/ To allow for cleanup code to run (e.g. PendingOperation cleanup after they finish)\n mLoop->processEvents();\n}\n\nvoid Test::expectSuccessfulCall(PendingOperation *op)\n{\n if (op->isError()) {\n qWarning().nospace() << op->errorName()\n << \": \" << op->errorMessage();\n mLoop->exit(1);\n return;\n }\n\n mLoop->exit(0);\n}\n\nvoid Test::expectSuccessfulCall(QDBusPendingCallWatcher *watcher)\n{\n if (watcher->isError()) {\n qWarning().nospace() << watcher->error().name()\n << \": \" << watcher->error().message();\n mLoop->exit(1);\n return;\n }\n\n mLoop->exit(0);\n}\n\nvoid Test::expectFailure(PendingOperation *op)\n{\n if (!op->isError()) {\n qWarning() << \"expectFailure(): should have been an error, but wasn't\";\n mLoop->exit(1);\n return;\n }\n\n mLoop->exit(0);\n} \n\nvoid Test::expectSuccessfulProperty(PendingOperation *op)\n{\n if (op->isError()) {\n qWarning().nospace() << op->errorName()\n << \": \" << op->errorMessage();\n mPropertyValue = QVariant();\n mLoop->exit(1);\n } else {\n Tp::PendingVariant *pv = qobject_cast(op);\n mPropertyValue = pv->result();\n mLoop->exit(0);\n }\n}\n\nvoid Test::processDBusQueue(Tp::DBusProxy *proxy)\n{\n \/\/ Call method Ping on the D-Bus Peer interface\n PeerInterface peer(proxy);\n PendingVoid *call = new PendingVoid(peer.Ping(), Tp::SharedPtr());\n\n \/\/ Wait for the reply to the Ping call\n while (!call->isFinished()) {\n mLoop->processEvents();\n }\n\n QVERIFY(call->isFinished());\n QVERIFY(call->isValid());\n}\n\nvoid Test::onWatchdog()\n{\n \/\/ We can't use QFAIL because the test would then go to cleanup() and\/or cleanupTestCase(),\n \/\/ which would often hang too - so let's just use abort\n qWarning() << \"Test took over 10 minutes to finish, it's probably hung up - aborting\";\n std::abort();\n}\n\n#include \"_gen\/test.h.moc.hpp\"\nMake processDBusQueue do an extra mainloop iteration so the PendingVoid is not reported as a leak#include \"tests\/lib\/test.h\"\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing Tp::PendingOperation;\nusing Tp::PendingVoid;\nusing Tp::Client::DBus::PeerInterface;\n\nTest::Test(QObject *parent)\n : QObject(parent), mLoop(new QEventLoop(this))\n{\n QTimer::singleShot(10 * 60 * 1000, this, SLOT(onWatchdog()));\n}\n\nTest::~Test()\n{\n delete mLoop;\n}\n\nvoid Test::initTestCaseImpl()\n{\n Tp::registerTypes();\n Tp::enableDebug(true);\n Tp::enableWarnings(true);\n\n QVERIFY(QDBusConnection::sessionBus().isConnected());\n}\n\nvoid Test::initImpl()\n{\n}\n\nvoid Test::cleanupImpl()\n{\n}\n\nvoid Test::cleanupTestCaseImpl()\n{\n \/\/ To allow for cleanup code to run (e.g. PendingOperation cleanup after they finish)\n mLoop->processEvents();\n}\n\nvoid Test::expectSuccessfulCall(PendingOperation *op)\n{\n if (op->isError()) {\n qWarning().nospace() << op->errorName()\n << \": \" << op->errorMessage();\n mLoop->exit(1);\n return;\n }\n\n mLoop->exit(0);\n}\n\nvoid Test::expectSuccessfulCall(QDBusPendingCallWatcher *watcher)\n{\n if (watcher->isError()) {\n qWarning().nospace() << watcher->error().name()\n << \": \" << watcher->error().message();\n mLoop->exit(1);\n return;\n }\n\n mLoop->exit(0);\n}\n\nvoid Test::expectFailure(PendingOperation *op)\n{\n if (!op->isError()) {\n qWarning() << \"expectFailure(): should have been an error, but wasn't\";\n mLoop->exit(1);\n return;\n }\n\n mLoop->exit(0);\n} \n\nvoid Test::expectSuccessfulProperty(PendingOperation *op)\n{\n if (op->isError()) {\n qWarning().nospace() << op->errorName()\n << \": \" << op->errorMessage();\n mPropertyValue = QVariant();\n mLoop->exit(1);\n } else {\n Tp::PendingVariant *pv = qobject_cast(op);\n mPropertyValue = pv->result();\n mLoop->exit(0);\n }\n}\n\nvoid Test::processDBusQueue(Tp::DBusProxy *proxy)\n{\n \/\/ Call method Ping on the D-Bus Peer interface\n PeerInterface peer(proxy);\n PendingVoid *call = new PendingVoid(peer.Ping(), Tp::SharedPtr());\n\n \/\/ Wait for the reply to the Ping call\n while (!call->isFinished()) {\n mLoop->processEvents();\n }\n\n QVERIFY(call->isFinished());\n QVERIFY(call->isValid());\n\n \/\/ Do one more processEvents so the PendingVoid is always freed\n mLoop->processEvents();\n}\n\nvoid Test::onWatchdog()\n{\n \/\/ We can't use QFAIL because the test would then go to cleanup() and\/or cleanupTestCase(),\n \/\/ which would often hang too - so let's just use abort\n qWarning() << \"Test took over 10 minutes to finish, it's probably hung up - aborting\";\n std::abort();\n}\n\n#include \"_gen\/test.h.moc.hpp\"\n<|endoftext|>"} {"text":"\/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/**\n * $Log$\n * Revision 1.2 2000\/01\/15 01:26:16 rahulj\n * Added support for HTTP to the parser using libWWW 5.2.8.\n * Renamed URL.[ch]pp to XMLURL.[ch]pp and like wise for the class name.\n * Only tested under NT 4.0 SP 5.\n * Removed URL.hpp from files where it was not used.\n *\n * Revision 1.1 2000\/01\/12 00:13:26 roddey\n * These were moved from internal\/ to framework\/, which was something that should have\n * happened long ago. They are really framework type of classes.\n *\n * Revision 1.1.1.1 1999\/11\/09 01:08:18 twl\n * Initial checkin\n *\n * Revision 1.2 1999\/11\/08 20:44:44 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\n#if !defined(URLINPUTSOURCE_HPP)\n#define URLINPUTSOURCE_HPP\n\n#include \n\n\nclass XMLPARSER_EXPORT URLInputSource : public InputSource\n{\npublic :\n \/\/ -----------------------------------------------------------------------\n \/\/ Constructors and Destructor\n \/\/ -----------------------------------------------------------------------\n URLInputSource(const XMLURL& urlId);\n URLInputSource\n (\n const XMLCh* const baseId\n , const XMLCh* const systemId\n );\n URLInputSource\n (\n const XMLCh* const baseId\n , const XMLCh* const systemId\n , const XMLCh* const publicId\n );\n URLInputSource\n (\n const XMLCh* const baseId\n , const char* const systemId\n );\n URLInputSource\n (\n const XMLCh* const baseId\n , const char* const systemId\n , const char* const publicId\n );\n ~URLInputSource();\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Virtual input source interface\n \/\/ -----------------------------------------------------------------------\n BinInputStream* makeStream() const;\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Getter methods\n \/\/ -----------------------------------------------------------------------\n const XMLURL& urlSrc() const;\n\n\nprivate :\n \/\/ -----------------------------------------------------------------------\n \/\/ Private data members\n \/\/\n \/\/ fURL\n \/\/ This is the URL created from the passed ids.\n \/\/ -----------------------------------------------------------------------\n XMLURL fURL;\n};\n\n\ninline const XMLURL& URLInputSource::urlSrc() const\n{\n return fURL;\n}\n\n#endif\nNeeded to include XMLURL.hpp so that it compiles standalone.\/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/**\n * $Log$\n * Revision 1.3 2000\/01\/26 18:56:02 roddey\n * Needed to include XMLURL.hpp so that it compiles standalone.\n *\n * Revision 1.2 2000\/01\/15 01:26:16 rahulj\n * Added support for HTTP to the parser using libWWW 5.2.8.\n * Renamed URL.[ch]pp to XMLURL.[ch]pp and like wise for the class name.\n * Only tested under NT 4.0 SP 5.\n * Removed URL.hpp from files where it was not used.\n *\n * Revision 1.1 2000\/01\/12 00:13:26 roddey\n * These were moved from internal\/ to framework\/, which was something that should have\n * happened long ago. They are really framework type of classes.\n *\n * Revision 1.1.1.1 1999\/11\/09 01:08:18 twl\n * Initial checkin\n *\n * Revision 1.2 1999\/11\/08 20:44:44 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\n#if !defined(URLINPUTSOURCE_HPP)\n#define URLINPUTSOURCE_HPP\n\n#include \n#include \n\n\nclass XMLPARSER_EXPORT URLInputSource : public InputSource\n{\npublic :\n \/\/ -----------------------------------------------------------------------\n \/\/ Constructors and Destructor\n \/\/ -----------------------------------------------------------------------\n URLInputSource(const XMLURL& urlId);\n URLInputSource\n (\n const XMLCh* const baseId\n , const XMLCh* const systemId\n );\n URLInputSource\n (\n const XMLCh* const baseId\n , const XMLCh* const systemId\n , const XMLCh* const publicId\n );\n URLInputSource\n (\n const XMLCh* const baseId\n , const char* const systemId\n );\n URLInputSource\n (\n const XMLCh* const baseId\n , const char* const systemId\n , const char* const publicId\n );\n ~URLInputSource();\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Virtual input source interface\n \/\/ -----------------------------------------------------------------------\n BinInputStream* makeStream() const;\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Getter methods\n \/\/ -----------------------------------------------------------------------\n const XMLURL& urlSrc() const;\n\n\nprivate :\n \/\/ -----------------------------------------------------------------------\n \/\/ Private data members\n \/\/\n \/\/ fURL\n \/\/ This is the URL created from the passed ids.\n \/\/ -----------------------------------------------------------------------\n XMLURL fURL;\n};\n\n\ninline const XMLURL& URLInputSource::urlSrc() const\n{\n return fURL;\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestCubeAxes3.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n\/\/ This example illustrates how one may explicitly specify the range of each\n\/\/ axes that's used to define the prop, while displaying data with a different\n\/\/ set of bounds (unlike cubeAxes2.tcl). This example allows you to separate\n\/\/ the notion of extent of the axes in physical space (bounds) and the extent\n\/\/ of the values it represents. In other words, you can have the ticks and\n\/\/ labels show a different range.\n\n#include \"vtkBYUReader.h\"\n#include \"vtkCamera.h\"\n#include \"vtkCubeAxesActor.h\"\n#include \"vtkLight.h\"\n#include \"vtkLODActor.h\"\n#include \"vtkNew.h\"\n#include \"vtkOutlineFilter.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkPolyDataNormals.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkTestUtilities.h\"\n\n\n\n\/\/----------------------------------------------------------------------------\nint TestCubeAxesWithZInnerPolys( int argc, char * argv [] )\n{\n vtkNew fohe;\n char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, \"Data\/teapot.g\");\n fohe->SetGeometryFileName(fname);\n delete [] fname;\n\n vtkNew normals;\n normals->SetInputConnection(fohe->GetOutputPort());\n\n vtkNew foheMapper;\n foheMapper->SetInputConnection(normals->GetOutputPort());\n\n vtkNew foheActor;\n foheActor->SetMapper(foheMapper.GetPointer());\n foheActor->GetProperty()->SetDiffuseColor(0.7, 0.3, 0.0);\n\n vtkNew outline;\n outline->SetInputConnection(normals->GetOutputPort());\n\n vtkNew mapOutline;\n mapOutline->SetInputConnection(outline->GetOutputPort());\n\n vtkNew outlineActor;\n outlineActor->SetMapper(mapOutline.GetPointer());\n outlineActor->GetProperty()->SetColor(0.0 ,0.0 ,0.0);\n\n vtkNew camera;\n camera->SetClippingRange(1.0, 100.0);\n camera->SetFocalPoint(0.9, 1.0, 0.0);\n camera->SetPosition(11.63, 6.0, 10.77);\n\n vtkNew light;\n light->SetFocalPoint(0.21406, 1.5, 0.0);\n light->SetPosition(8.3761, 4.94858, 4.12505);\n\n vtkNew ren2;\n ren2->SetActiveCamera(camera.GetPointer());\n ren2->AddLight(light.GetPointer());\n\n vtkNew renWin;\n renWin->SetMultiSamples(0);\n renWin->AddRenderer(ren2.GetPointer());\n renWin->SetWindowName(\"VTK - Cube Axes custom range\");\n renWin->SetSize(600, 600);\n\n vtkNew iren;\n iren->SetRenderWindow(renWin.GetPointer());\n\n ren2->AddViewProp(foheActor.GetPointer());\n ren2->AddViewProp(outlineActor.GetPointer());\n ren2->SetBackground(0.1, 0.2, 0.4);\n\n normals->Update();\n\n vtkNew axes2;\n axes2->SetBounds(normals->GetOutput()->GetBounds());\n axes2->SetXAxisRange(20, 300);\n axes2->SetYAxisRange(-0.01, 0.01);\n axes2->SetCamera(ren2->GetActiveCamera());\n axes2->SetXLabelFormat(\"%6.1f\");\n axes2->SetYLabelFormat(\"%6.1f\");\n axes2->SetZLabelFormat(\"%6.1f\");\n axes2->SetScreenSize(15.0);\n axes2->SetFlyModeToClosestTriad();\n axes2->SetCornerOffset(0.0);\n axes2->SetDrawZGridpolys(1);\n\n ren2->AddViewProp(axes2.GetPointer());\n renWin->Render();\n\n int retVal = vtkRegressionTestImage( renWin.GetPointer() );\n if ( retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n iren->Start();\n }\n\n return !retVal;\n}\nModifying test to verify that attribute properties are indeed used\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestCubeAxes3.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n\/\/ This example illustrates how one may explicitly specify the range of each\n\/\/ axes that's used to define the prop, while displaying data with a different\n\/\/ set of bounds (unlike cubeAxes2.tcl). This example allows you to separate\n\/\/ the notion of extent of the axes in physical space (bounds) and the extent\n\/\/ of the values it represents. In other words, you can have the ticks and\n\/\/ labels show a different range.\n\n#include \"vtkBYUReader.h\"\n#include \"vtkCamera.h\"\n#include \"vtkCubeAxesActor.h\"\n#include \"vtkLight.h\"\n#include \"vtkLODActor.h\"\n#include \"vtkNew.h\"\n#include \"vtkOutlineFilter.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkPolyDataNormals.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkTestUtilities.h\"\n\n\n\n\/\/----------------------------------------------------------------------------\nint TestCubeAxesWithZInnerPolys( int argc, char * argv [] )\n{\n vtkNew fohe;\n char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, \"Data\/teapot.g\");\n fohe->SetGeometryFileName(fname);\n delete [] fname;\n\n vtkNew normals;\n normals->SetInputConnection(fohe->GetOutputPort());\n\n vtkNew foheMapper;\n foheMapper->SetInputConnection(normals->GetOutputPort());\n\n vtkNew foheActor;\n foheActor->SetMapper(foheMapper.GetPointer());\n foheActor->GetProperty()->SetDiffuseColor(0.7, 0.3, 0.0);\n\n vtkNew outline;\n outline->SetInputConnection(normals->GetOutputPort());\n\n vtkNew mapOutline;\n mapOutline->SetInputConnection(outline->GetOutputPort());\n\n vtkNew outlineActor;\n outlineActor->SetMapper(mapOutline.GetPointer());\n outlineActor->GetProperty()->SetColor(0. ,0. ,0. );\n\n vtkNew camera;\n camera->SetClippingRange(1.0, 100.0);\n camera->SetFocalPoint(0.9, 1.0, 0.0);\n camera->SetPosition(11.63, 6.0, 10.77);\n\n vtkNew light;\n light->SetFocalPoint(0.21406, 1.5, 0.0);\n light->SetPosition(8.3761, 4.94858, 4.12505);\n\n vtkNew ren2;\n ren2->SetActiveCamera(camera.GetPointer());\n ren2->AddLight(light.GetPointer());\n\n vtkNew renWin;\n renWin->SetMultiSamples(0);\n renWin->AddRenderer(ren2.GetPointer());\n renWin->SetWindowName(\"VTK - Cube Axes custom range\");\n renWin->SetSize(600, 600);\n\n vtkNew iren;\n iren->SetRenderWindow(renWin.GetPointer());\n\n ren2->AddViewProp(foheActor.GetPointer());\n ren2->AddViewProp(outlineActor.GetPointer());\n ren2->SetBackground(0.1, 0.2, 0.4);\n\n normals->Update();\n\n vtkNew axes2;\n axes2->SetBounds(normals->GetOutput()->GetBounds());\n axes2->SetXAxisRange(20, 300);\n axes2->SetYAxisRange(-0.01, 0.01);\n axes2->SetCamera(ren2->GetActiveCamera());\n axes2->SetXLabelFormat(\"%6.1f\");\n axes2->SetYLabelFormat(\"%6.1f\");\n axes2->SetZLabelFormat(\"%6.1f\");\n axes2->SetScreenSize(15.0);\n axes2->SetFlyModeToClosestTriad();\n axes2->SetCornerOffset(0.0);\n axes2->SetDrawZGridpolys(1);\n axes2->GetZAxesGridpolysProperty()->SetColor(.2, .2, .2);\n axes2->GetZAxesGridpolysProperty()->SetOpacity(.3);\n \n ren2->AddViewProp(axes2.GetPointer());\n renWin->Render();\n\n int retVal = vtkRegressionTestImage( renWin.GetPointer() );\n if ( retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n iren->Start();\n }\n\n return !retVal;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 Benjamin Glatzel\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Precompiled header file\n#include \"stdafx.h\"\n#include \"stdafx_editor.h\"\n\n\/\/ Ui\n#include \"ui_IntrinsicEdPropertyEditorFloat.h\"\n\nIntrinsicEdPropertyEditorFloat::IntrinsicEdPropertyEditorFloat(\n rapidjson::Document* p_Document, rapidjson::Value* p_CurrentProperties,\n rapidjson::Value* p_CurrentProperty, const char* p_PropertyName,\n QWidget* parent)\n : IntrinsicEdPropertyEditorBase(p_Document, p_CurrentProperties,\n p_CurrentProperty, p_PropertyName, parent)\n{\n _ui.setupUi(this);\n\n QObject::connect(_ui.value, SIGNAL(valueChanged(double)), this,\n SLOT(onValueChanged()));\n\n const rapidjson::Value& prop = *_property;\n if (!prop.HasMember(\"min\") || prop[\"min\"].GetFloat() == -FLT_MAX)\n {\n delete _ui.valueSlider;\n _ui.valueSlider = nullptr;\n }\n else\n {\n const float min = prop[\"min\"].GetFloat();\n const float max = prop[\"max\"].GetFloat();\n\n _ui.value->setMinimum(min);\n _ui.value->setMaximum(max);\n\n _ui.valueSlider->setMinimum(0);\n _ui.valueSlider->setMaximum(1000);\n\n QObject::connect(_ui.valueSlider, SIGNAL(valueChanged(int)), this,\n SLOT(onSliderValueChanged()));\n }\n\n updateFromProperty();\n}\n\nIntrinsicEdPropertyEditorFloat::~IntrinsicEdPropertyEditorFloat() {}\n\nvoid IntrinsicEdPropertyEditorFloat::updateFromProperty()\n{\n _INTR_ASSERT(_property);\n const rapidjson::Value& prop = *_property;\n\n if (prop[\"readOnly\"].GetBool())\n {\n _ui.value->setReadOnly(true);\n }\n\n if (prop[\"value\"].GetFloat() != _ui.value->value() && !_ui.value->hasFocus())\n {\n _ui.value->blockSignals(true);\n _ui.value->setValue(prop[\"value\"].GetFloat());\n _ui.value->blockSignals(false);\n\n if (_ui.valueSlider)\n {\n const int sliderPos =\n (int)((_ui.value->value() - _ui.value->minimum()) \/\n (_ui.value->maximum() - _ui.value->minimum()) * 1000.0f);\n _ui.valueSlider->setValue(sliderPos);\n }\n }\n\n _ui.propertyTitle->setText(_propertyName.c_str());\n}\n\nvoid IntrinsicEdPropertyEditorFloat::onValueChanged()\n{\n _INTR_ASSERT(_property);\n rapidjson::Value& prop = *_property;\n\n if (prop[\"value\"].GetFloat() != _ui.value->value())\n {\n prop[\"value\"].SetFloat((float)_ui.value->value());\n\n if (_ui.valueSlider)\n {\n const int sliderPos =\n (int)((_ui.value->value() - _ui.value->minimum()) \/\n (_ui.value->maximum() - _ui.value->minimum()) * 1000.0f);\n _ui.valueSlider->setValue(sliderPos);\n }\n\n emit valueChanged(*_properties);\n }\n}\n\nvoid IntrinsicEdPropertyEditorFloat::onSliderValueChanged()\n{\n const float value =\n _ui.value->minimum() + (_ui.valueSlider->value() \/ 1000.0f) *\n (_ui.value->maximum() - _ui.value->minimum());\n _ui.value->setValue(value);\n}\nCorectly set the float sliders to the center initially.\/\/ Copyright 2017 Benjamin Glatzel\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Precompiled header file\n#include \"stdafx.h\"\n#include \"stdafx_editor.h\"\n\n\/\/ Ui\n#include \"ui_IntrinsicEdPropertyEditorFloat.h\"\n\nIntrinsicEdPropertyEditorFloat::IntrinsicEdPropertyEditorFloat(\n rapidjson::Document* p_Document, rapidjson::Value* p_CurrentProperties,\n rapidjson::Value* p_CurrentProperty, const char* p_PropertyName,\n QWidget* parent)\n : IntrinsicEdPropertyEditorBase(p_Document, p_CurrentProperties,\n p_CurrentProperty, p_PropertyName, parent)\n{\n _ui.setupUi(this);\n\n QObject::connect(_ui.value, SIGNAL(valueChanged(double)), this,\n SLOT(onValueChanged()));\n\n const rapidjson::Value& prop = *_property;\n if (!prop.HasMember(\"min\") || prop[\"min\"].GetFloat() == -FLT_MAX)\n {\n delete _ui.valueSlider;\n _ui.valueSlider = nullptr;\n }\n else\n {\n const float min = prop[\"min\"].GetFloat();\n const float max = prop[\"max\"].GetFloat();\n\n _ui.value->setMinimum(min);\n _ui.value->setMaximum(max);\n _ui.valueSlider->setValue(500);\n\n _ui.valueSlider->setMinimum(0);\n _ui.valueSlider->setMaximum(1000);\n\n QObject::connect(_ui.valueSlider, SIGNAL(valueChanged(int)), this,\n SLOT(onSliderValueChanged()));\n }\n\n updateFromProperty();\n}\n\nIntrinsicEdPropertyEditorFloat::~IntrinsicEdPropertyEditorFloat() {}\n\nvoid IntrinsicEdPropertyEditorFloat::updateFromProperty()\n{\n _INTR_ASSERT(_property);\n const rapidjson::Value& prop = *_property;\n\n if (prop[\"readOnly\"].GetBool())\n {\n _ui.value->setReadOnly(true);\n }\n\n if (prop[\"value\"].GetFloat() != _ui.value->value() && !_ui.value->hasFocus())\n {\n _ui.value->blockSignals(true);\n _ui.value->setValue(prop[\"value\"].GetFloat());\n _ui.value->blockSignals(false);\n\n if (_ui.valueSlider)\n {\n const int sliderPos =\n (int)((_ui.value->value() - _ui.value->minimum()) \/\n (_ui.value->maximum() - _ui.value->minimum()) * 1000.0f);\n _ui.valueSlider->setValue(sliderPos);\n }\n }\n\n _ui.propertyTitle->setText(_propertyName.c_str());\n}\n\nvoid IntrinsicEdPropertyEditorFloat::onValueChanged()\n{\n _INTR_ASSERT(_property);\n rapidjson::Value& prop = *_property;\n\n if (prop[\"value\"].GetFloat() != _ui.value->value())\n {\n prop[\"value\"].SetFloat((float)_ui.value->value());\n\n if (_ui.valueSlider)\n {\n const int sliderPos =\n (int)((_ui.value->value() - _ui.value->minimum()) \/\n (_ui.value->maximum() - _ui.value->minimum()) * 1000.0f);\n _ui.valueSlider->setValue(sliderPos);\n }\n\n emit valueChanged(*_properties);\n }\n}\n\nvoid IntrinsicEdPropertyEditorFloat::onSliderValueChanged()\n{\n const float value =\n _ui.value->minimum() + (_ui.valueSlider->value() \/ 1000.0f) *\n (_ui.value->maximum() - _ui.value->minimum());\n _ui.value->setValue(value);\n}\n<|endoftext|>"} {"text":"\/*\n * HyPerCol.cpp\n *\n * Created on: Jul 30, 2008\n * Author: Craig Rasmussen\n *\/\n\n#define TIMER_ON\n#undef TIMESTEP_OUTPUT\n\n#include \"HyPerCol.hpp\"\n#include \"InterColComm.hpp\"\n#include \"..\/connections\/PVConnection.h\"\n#include \"..\/io\/clock.h\"\n#include \"..\/io\/imageio.hpp\"\n#include \"..\/io\/io.h\"\n#include \"..\/utils\/pv_random.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace PV {\n\nHyPerCol::HyPerCol(const char * name, int argc, char * argv[])\n : warmStart(false), isInitialized(false)\n{\n int opencl_device = 1; \/\/ default to CPU for now\n\n \/\/ TODO - fix these numbers to dynamically grow\n maxLayers = MAX_LAYERS;\n maxConnections = MAX_CONNECTIONS;\n\n this->name = strdup(name);\n this->runTimer = new Timer();\n\n char * param_file;\n simTime = 0;\n numLayers = 0;\n numConnections = 0;\n layers = (HyPerLayer **) malloc(maxLayers * sizeof(HyPerLayer *));\n connections = (HyPerConn **) malloc(maxConnections * sizeof(HyPerConn *));\n\n numSteps = 2;\n image_file = NULL;\n param_file = NULL;\n unsigned long random_seed = 0;\n parse_options(argc, argv, &image_file, ¶m_file, &numSteps, &opencl_device, &random_seed);\n\n \/\/ run only on CPU for now\n initializeThreads(opencl_device);\n\n \/\/ estimate for now\n \/\/ TODO -get rid of maxGroups\n int maxGroups = 2*(maxLayers + maxConnections);\n params = new PVParams(param_file, maxGroups);\n\n icComm = new InterColComm(&argc, &argv);\n\n \/\/ initialize random seed\n \/\/\n random_seed = getRandomSeed();\n random_seed = params->value(name, \"randomSeed\", random_seed);\n pv_srandom(random_seed);\n\n if (param_file != NULL) free(param_file);\n\n deltaTime = DELTA_T;\n if (params->present(name, \"dt\")) deltaTime = params->value(name, \"dt\");\n\n int status = -1;\n if (image_file) {\n status = getImageInfo(image_file, icComm, &imageLoc);\n }\n\n if (status) {\n imageLoc.nxGlobal = (int) params->value(name, \"nx\");\n imageLoc.nyGlobal = (int) params->value(name, \"ny\");\n\n \/\/ set loc based on global parameters and processor partitioning\n \/\/\n setLayerLoc(&imageLoc, 1.0f, 1.0f, 0, 1);\n }\n\n runDelegate = NULL;\n\n numProbes = 0;\n probes = NULL;\n}\n\nHyPerCol::~HyPerCol()\n{\n int n;\n\n finalizeThreads();\n\n if (image_file != NULL) free(image_file);\n\n for (n = 0; n < numConnections; n++) {\n delete connections[n];\n }\n\n for (n = 0; n < numLayers; n++) {\n \/\/ TODO: check to see if finalize called\n if (layers[n] != NULL) {\n delete layers[n]; \/\/ will call *_finalize\n }\n else {\n \/\/ TODO move finalize\n \/\/ PVLayer_finalize(getCLayer(n));\n }\n }\n\n delete icComm;\n\n printf(\"%16s: total time in %6s %10s: \", name, \"column\", \"run\");\n runTimer->elapsed_time();\n delete runTimer;\n\n free(connections);\n free(layers);\n free(name);\n}\n\nint HyPerCol::initFinish(void)\n{\n int status = 0;\n\n for (int i = 0; i < this->numLayers; i++) {\n status = layers[i]->initFinish();\n if (status != 0) {\n fprintf(stderr, \"[%d]: HyPerCol::initFinish: ERROR condition, exiting...\\n\", this->columnId());\n exit(status);\n }\n }\n\n log_parameters(numSteps, image_file);\n\n isInitialized = true;\n\n return status;\n}\n\nint HyPerCol::columnId()\n{\n return icComm->commRank();\n}\n\nint HyPerCol::numberOfColumns()\n{\n return icComm->numCommRows() * icComm->numCommColumns();\n}\n\nint HyPerCol::commColumn(int colId)\n{\n return colId % icComm->numCommColumns();\n}\n\nint HyPerCol::commRow(int colId)\n{\n return colId \/ icComm->numCommColumns();\n}\n\nint HyPerCol::setLayerLoc(PVLayerLoc * layerLoc,\n float nxScale, float nyScale, int margin, int nf)\n{\n layerLoc->nxGlobal = (int) (nxScale * imageLoc.nxGlobal);\n layerLoc->nyGlobal = (int) (nyScale * imageLoc.nyGlobal);\n\n \/\/ partition input space based on the number of processor\n \/\/ columns and rows\n \/\/\n\n layerLoc->nx = layerLoc->nxGlobal \/ icComm->numCommColumns();\n layerLoc->ny = layerLoc->nyGlobal \/ icComm->numCommRows();\n\n assert(layerLoc->nxGlobal == layerLoc->nx * icComm->numCommColumns());\n assert(layerLoc->nyGlobal == layerLoc->ny * icComm->numCommRows());\n\n layerLoc->kx0 = layerLoc->nx * icComm->commColumn();\n layerLoc->ky0 = layerLoc->ny * icComm->commRow();\n\n layerLoc->nf = nf;\n layerLoc->nb = margin;\n\n layerLoc->halo.lt = margin;\n layerLoc->halo.rt = margin;\n layerLoc->halo.dn = margin;\n layerLoc->halo.up = margin;\n\n return 0;\n}\n\nint HyPerCol::addLayer(HyPerLayer * l)\n{\n assert(numLayers < maxLayers);\n l->columnWillAddLayer(icComm, numLayers);\n layers[numLayers++] = l;\n return (numLayers - 1);\n}\n\nint HyPerCol::addConnection(HyPerConn * conn)\n{\n int connId = numConnections;\n\n assert(numConnections < maxConnections);\n\n \/\/ numConnections is the ID of this connection\n icComm->subscribe(conn);\n\n connections[numConnections++] = conn;\n\n return connId;\n}\n\nint HyPerCol::run(int nTimeSteps)\n{\n checkMarginWidths();\n\n int step = 0;\n float stopTime = simTime + nTimeSteps * deltaTime;\n const bool exitOnFinish = false;\n\n if (!isInitialized) {\n initFinish();\n }\n\n numSteps = nTimeSteps;\n\n#ifdef DEBUG_OUTPUT\n if (columnId() == 0) {\n printf(\"[0]: HyPerCol: running...\\n\"); fflush(stdout);\n }\n#endif\n\n \/\/ publish initial conditions\n \/\/\n for (int l = 0; l < numLayers; l++) {\n layers[l]->publish(icComm, simTime);\n }\n\n \/\/ wait for all published data to arrive\n \/\/\n for (int l = 0; l < numLayers; l++) {\n icComm->wait(layers[l]->getLayerId());\n }\n\n if (runDelegate) {\n \/\/ let delegate advance the time\n \/\/\n runDelegate->run(simTime, stopTime);\n }\n\n#ifdef TIMER_ON\n start_clock();\n#endif\n \/\/ time loop\n \/\/\n while (simTime < stopTime) {\n simTime = advanceTime(simTime);\n step += 1;\n\n#ifdef TIMER_ON\n if (step == 10) start_clock();\n#endif\n\n } \/\/ end time loop\n\n#ifdef DEBUG_OUTPUT\n if (columnId() == 0) {\n printf(\"[0]: HyPerCol::run done...\\n\"); fflush(stdout);\n }\n#endif\n\n exitRunLoop(exitOnFinish);\n\n#ifdef TIMER_ON\n stop_clock();\n#endif\n\n return 0;\n}\n\nfloat HyPerCol::advanceTime(float sim_time)\n{\n#ifdef TIMESTEP_OUTPUT\n int nstep = (int) (sim_time\/getDeltaTime());\n if (nstep%2000 == 0 && columnId() == 0) {\n printf(\" [%d]: time==%f\\n\", columnId(), sim_time);\n }\n#endif\n\n runTimer->start();\n\n \/\/ At this point all activity from the previous time step have\n \/\/ been delivered to the data store.\n \/\/\n\n \/\/ update the connections (weights)\n \/\/\n for (int c = 0; c < numConnections; c++) {\n connections[c]->updateState(sim_time, deltaTime);\n connections[c]->outputState(sim_time);\n }\n\n \/\/ Update the layers (activity)\n \/\/\n for (int l = 0; l < numLayers; l++) {\n layers[l]->outputState(sim_time);\n\n \/\/ deliver new synaptic activity to layer\n \/\/\n layers[l]->triggerReceive(icComm);\n\n \/\/ update layer and calculate new activity\n \/\/\n layers[l]->updateState(sim_time, deltaTime);\n }\n\n \/\/ This loop separate from the update layer loop above\n \/\/ to provide time for layer data to be copied from\n \/\/ the OpenCL device.\n \/\/\n for (int l = 0; l < numLayers; l++) {\n layers[l]->updateBorder(sim_time, deltaTime);\n\n \/\/ TODO - move this to layer\n \/\/ Advance time level so we have a new place in data store\n \/\/ to copy the data. This should be done immediately before\n \/\/ publish so there is a place to publish and deliver the data to.\n \/\/ No one can access the data store (except to publish) until\n \/\/ wait has been called. This should be fixed so that publish goes\n \/\/ to last time level and level is advanced only after wait.\n icComm->increaseTimeLevel(layers[l]->getLayerId());\n\n layers[l]->publish(icComm, sim_time);\n }\n\n \/\/ wait for all published data to arrive\n \/\/\n for (int l = 0; l < numLayers; l++) {\n layers[l]->waitOnPublish(icComm);\n }\n\n \/\/ make sure simTime is updated even if HyPerCol isn't running time loop\n\n float outputTime = simTime; \/\/ so that outputState is called with the correct time\n \/\/ but doesn't effect runTimer\n\n simTime = sim_time + deltaTime;\n\n runTimer->stop();\n\n outputState(outputTime);\n\n return simTime;\n}\n\nint HyPerCol::exitRunLoop(bool exitOnFinish)\n{\n int status = 0;\n\n \/\/ output final state of layers and connections\n \/\/\n bool last = true;\n\n for (int l = 0; l < numLayers; l++) {\n layers[l]->writeState(layers[l]->getName(), simTime, last);\n }\n\n for (int c = 0; c < numConnections; c++) {\n connections[c]->outputState(simTime, last);\n }\n\n if (exitOnFinish) {\n delete this;\n exit(0);\n }\n\n return status;\n}\n\nint HyPerCol::initializeThreads(int device)\n{\n clDevice = new CLDevice(device);\n return 0;\n}\n\nint HyPerCol::finalizeThreads()\n{\n delete clDevice;\n return 0;\n}\n\nint HyPerCol::loadState()\n{\n return 0;\n}\n\nint HyPerCol::writeState()\n{\n for (int l = 0; l < numLayers; l++) {\n layers[l]->writeState(OUTPUT_PATH, simTime);\n }\n return 0;\n}\n\nint HyPerCol::insertProbe(ColProbe * p)\n{\n ColProbe ** newprobes;\n newprobes = (ColProbe **) malloc((numProbes + 1) * sizeof(ColProbe *));\n assert(newprobes != NULL);\n\n for (int i = 0; i < numProbes; i++) {\n newprobes[i] = probes[i];\n }\n delete probes;\n\n probes = newprobes;\n probes[numProbes] = p;\n\n return ++numProbes;\n}\n\nint HyPerCol::outputState(float time)\n{\n for( int n = 0; n < numProbes; n++ ) {\n probes[n]->outputState(time, this);\n }\n return EXIT_SUCCESS;\n}\n\nint HyPerCol::checkMarginWidths() {\n \/\/ For each connection, make sure that the post-synaptic margin width is\n \/\/ large enough for the patch size.\n\n \/\/ TODO instead of having marginWidth supplied to HyPerLayers in the\n \/\/ params.pv file, calculate them based on the patch sizes here.\n \/\/ Hard part: numExtended-sized quantities (e.g. clayer->activity) can't\n \/\/ be allocated and initialized until after nPad is determined.\n\n int status = EXIT_SUCCESS;\n int status1, status2;\n for( int c=0; c < numConnections; c++ ) {\n HyPerConn * conn = connections[c];\n int padding = conn->pre->getLayerLoc()->nb;\n\n int xScalePre = conn->preSynapticLayer()->getXScale();\n int xScalePost = conn->postSynapticLayer()->getXScale();\n status1 = zCheckMarginWidth(conn, \"x\", padding, conn->xPatchSize(), xScalePre, xScalePost, status);\n\n int yScalePre = conn->preSynapticLayer()->getYScale();\n int yScalePost = conn->postSynapticLayer()->getYScale();\n status2 = zCheckMarginWidth(conn, \"y\", padding, conn->yPatchSize(), yScalePre, yScalePost, status);\n status = (status == EXIT_SUCCESS && status1 == EXIT_SUCCESS && status2 == EXIT_SUCCESS) ?\n EXIT_SUCCESS : EXIT_FAILURE;\n }\n return status;\n} \/\/ end HyPerCol::checkMarginWidths()\n\nint HyPerCol::zCheckMarginWidth(HyPerConn * conn, const char * dim, int padding, int patchSize, int scalePre, int scalePost, int prevStatus) {\n int status;\n int scaleDiff = scalePre - scalePost;\n \/\/ if post has higher neuronal density than pre, scaleDiff < 0.\n int needed = scaleDiff > 0 ? ( patchSize\/( (int) powf(2,scaleDiff) )\/2 ) :\n ( (patchSize\/2) * ( (int) powf(2,-scaleDiff) ) );\n if( padding < needed ) {\n if( prevStatus == EXIT_SUCCESS ) {\n fprintf(stderr, \"Margin width error.\\n\");\n }\n fprintf(stderr, \"Connection \\\"%s\\\", dimension %s:\\n\", conn->getName(), dim);\n fprintf(stderr, \" Margin width %d, patch size %d, presynaptic scale %d, postsynaptic scale %d\\n\",\n padding, patchSize, scalePre, scalePost);\n fprintf(stderr, \" Needed margin width=%d\\n\", needed);\n status = EXIT_FAILURE;\n if( numberOfColumns() > 1 || padding > 0 ) {\n fprintf(stderr, \"Exiting.\\n\");\n exit(EXIT_FAILURE);\n }\n else {\n fprintf(stderr, \"Continuing, but there may be undesirable edge effects.\\n\");\n }\n }\n else status = EXIT_SUCCESS;\n return status;\n}\n\n} \/\/ PV namespace\nRemoved log_parameters (should probably be fixed).\/*\n * HyPerCol.cpp\n *\n * Created on: Jul 30, 2008\n * Author: Craig Rasmussen\n *\/\n\n#define TIMER_ON\n#undef TIMESTEP_OUTPUT\n\n#include \"HyPerCol.hpp\"\n#include \"InterColComm.hpp\"\n#include \"..\/connections\/PVConnection.h\"\n#include \"..\/io\/clock.h\"\n#include \"..\/io\/imageio.hpp\"\n#include \"..\/io\/io.h\"\n#include \"..\/utils\/pv_random.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace PV {\n\nHyPerCol::HyPerCol(const char * name, int argc, char * argv[])\n : warmStart(false), isInitialized(false)\n{\n int opencl_device = 1; \/\/ default to CPU for now\n\n \/\/ TODO - fix these numbers to dynamically grow\n maxLayers = MAX_LAYERS;\n maxConnections = MAX_CONNECTIONS;\n\n this->name = strdup(name);\n this->runTimer = new Timer();\n\n char * param_file;\n simTime = 0;\n numLayers = 0;\n numConnections = 0;\n layers = (HyPerLayer **) malloc(maxLayers * sizeof(HyPerLayer *));\n connections = (HyPerConn **) malloc(maxConnections * sizeof(HyPerConn *));\n\n numSteps = 2;\n image_file = NULL;\n param_file = NULL;\n unsigned long random_seed = 0;\n parse_options(argc, argv, &image_file, ¶m_file, &numSteps, &opencl_device, &random_seed);\n\n \/\/ run only on CPU for now\n initializeThreads(opencl_device);\n\n \/\/ estimate for now\n \/\/ TODO -get rid of maxGroups\n int maxGroups = 2*(maxLayers + maxConnections);\n params = new PVParams(param_file, maxGroups);\n\n icComm = new InterColComm(&argc, &argv);\n\n \/\/ initialize random seed\n \/\/\n random_seed = getRandomSeed();\n random_seed = params->value(name, \"randomSeed\", random_seed);\n pv_srandom(random_seed);\n\n if (param_file != NULL) free(param_file);\n\n deltaTime = DELTA_T;\n if (params->present(name, \"dt\")) deltaTime = params->value(name, \"dt\");\n\n int status = -1;\n if (image_file) {\n status = getImageInfo(image_file, icComm, &imageLoc);\n }\n\n if (status) {\n imageLoc.nxGlobal = (int) params->value(name, \"nx\");\n imageLoc.nyGlobal = (int) params->value(name, \"ny\");\n\n \/\/ set loc based on global parameters and processor partitioning\n \/\/\n setLayerLoc(&imageLoc, 1.0f, 1.0f, 0, 1);\n }\n\n runDelegate = NULL;\n\n numProbes = 0;\n probes = NULL;\n}\n\nHyPerCol::~HyPerCol()\n{\n int n;\n\n finalizeThreads();\n\n if (image_file != NULL) free(image_file);\n\n for (n = 0; n < numConnections; n++) {\n delete connections[n];\n }\n\n for (n = 0; n < numLayers; n++) {\n \/\/ TODO: check to see if finalize called\n if (layers[n] != NULL) {\n delete layers[n]; \/\/ will call *_finalize\n }\n else {\n \/\/ TODO move finalize\n \/\/ PVLayer_finalize(getCLayer(n));\n }\n }\n\n delete icComm;\n\n printf(\"%16s: total time in %6s %10s: \", name, \"column\", \"run\");\n runTimer->elapsed_time();\n delete runTimer;\n\n free(connections);\n free(layers);\n free(name);\n}\n\nint HyPerCol::initFinish(void)\n{\n int status = 0;\n\n for (int i = 0; i < this->numLayers; i++) {\n status = layers[i]->initFinish();\n if (status != 0) {\n fprintf(stderr, \"[%d]: HyPerCol::initFinish: ERROR condition, exiting...\\n\", this->columnId());\n exit(status);\n }\n }\n\n#ifdef OBSOLETE\n \/\/ TODO - fix this to modern version?\n log_parameters(numSteps, image_file);\n#endif\n\n isInitialized = true;\n\n return status;\n}\n\nint HyPerCol::columnId()\n{\n return icComm->commRank();\n}\n\nint HyPerCol::numberOfColumns()\n{\n return icComm->numCommRows() * icComm->numCommColumns();\n}\n\nint HyPerCol::commColumn(int colId)\n{\n return colId % icComm->numCommColumns();\n}\n\nint HyPerCol::commRow(int colId)\n{\n return colId \/ icComm->numCommColumns();\n}\n\nint HyPerCol::setLayerLoc(PVLayerLoc * layerLoc,\n float nxScale, float nyScale, int margin, int nf)\n{\n layerLoc->nxGlobal = (int) (nxScale * imageLoc.nxGlobal);\n layerLoc->nyGlobal = (int) (nyScale * imageLoc.nyGlobal);\n\n \/\/ partition input space based on the number of processor\n \/\/ columns and rows\n \/\/\n\n layerLoc->nx = layerLoc->nxGlobal \/ icComm->numCommColumns();\n layerLoc->ny = layerLoc->nyGlobal \/ icComm->numCommRows();\n\n assert(layerLoc->nxGlobal == layerLoc->nx * icComm->numCommColumns());\n assert(layerLoc->nyGlobal == layerLoc->ny * icComm->numCommRows());\n\n layerLoc->kx0 = layerLoc->nx * icComm->commColumn();\n layerLoc->ky0 = layerLoc->ny * icComm->commRow();\n\n layerLoc->nf = nf;\n layerLoc->nb = margin;\n\n layerLoc->halo.lt = margin;\n layerLoc->halo.rt = margin;\n layerLoc->halo.dn = margin;\n layerLoc->halo.up = margin;\n\n return 0;\n}\n\nint HyPerCol::addLayer(HyPerLayer * l)\n{\n assert(numLayers < maxLayers);\n l->columnWillAddLayer(icComm, numLayers);\n layers[numLayers++] = l;\n return (numLayers - 1);\n}\n\nint HyPerCol::addConnection(HyPerConn * conn)\n{\n int connId = numConnections;\n\n assert(numConnections < maxConnections);\n\n \/\/ numConnections is the ID of this connection\n icComm->subscribe(conn);\n\n connections[numConnections++] = conn;\n\n return connId;\n}\n\nint HyPerCol::run(int nTimeSteps)\n{\n checkMarginWidths();\n\n int step = 0;\n float stopTime = simTime + nTimeSteps * deltaTime;\n const bool exitOnFinish = false;\n\n if (!isInitialized) {\n initFinish();\n }\n\n numSteps = nTimeSteps;\n\n#ifdef DEBUG_OUTPUT\n if (columnId() == 0) {\n printf(\"[0]: HyPerCol: running...\\n\"); fflush(stdout);\n }\n#endif\n\n \/\/ publish initial conditions\n \/\/\n for (int l = 0; l < numLayers; l++) {\n layers[l]->publish(icComm, simTime);\n }\n\n \/\/ wait for all published data to arrive\n \/\/\n for (int l = 0; l < numLayers; l++) {\n icComm->wait(layers[l]->getLayerId());\n }\n\n if (runDelegate) {\n \/\/ let delegate advance the time\n \/\/\n runDelegate->run(simTime, stopTime);\n }\n\n#ifdef TIMER_ON\n start_clock();\n#endif\n \/\/ time loop\n \/\/\n while (simTime < stopTime) {\n simTime = advanceTime(simTime);\n step += 1;\n\n#ifdef TIMER_ON\n if (step == 10) start_clock();\n#endif\n\n } \/\/ end time loop\n\n#ifdef DEBUG_OUTPUT\n if (columnId() == 0) {\n printf(\"[0]: HyPerCol::run done...\\n\"); fflush(stdout);\n }\n#endif\n\n exitRunLoop(exitOnFinish);\n\n#ifdef TIMER_ON\n stop_clock();\n#endif\n\n return 0;\n}\n\nfloat HyPerCol::advanceTime(float sim_time)\n{\n#ifdef TIMESTEP_OUTPUT\n int nstep = (int) (sim_time\/getDeltaTime());\n if (nstep%2000 == 0 && columnId() == 0) {\n printf(\" [%d]: time==%f\\n\", columnId(), sim_time);\n }\n#endif\n\n runTimer->start();\n\n \/\/ At this point all activity from the previous time step have\n \/\/ been delivered to the data store.\n \/\/\n\n \/\/ update the connections (weights)\n \/\/\n for (int c = 0; c < numConnections; c++) {\n connections[c]->updateState(sim_time, deltaTime);\n connections[c]->outputState(sim_time);\n }\n\n \/\/ Update the layers (activity)\n \/\/\n for (int l = 0; l < numLayers; l++) {\n layers[l]->outputState(sim_time);\n\n \/\/ deliver new synaptic activity to layer\n \/\/\n layers[l]->triggerReceive(icComm);\n\n \/\/ update layer and calculate new activity\n \/\/\n layers[l]->updateState(sim_time, deltaTime);\n }\n\n \/\/ This loop separate from the update layer loop above\n \/\/ to provide time for layer data to be copied from\n \/\/ the OpenCL device.\n \/\/\n for (int l = 0; l < numLayers; l++) {\n layers[l]->updateBorder(sim_time, deltaTime);\n\n \/\/ TODO - move this to layer\n \/\/ Advance time level so we have a new place in data store\n \/\/ to copy the data. This should be done immediately before\n \/\/ publish so there is a place to publish and deliver the data to.\n \/\/ No one can access the data store (except to publish) until\n \/\/ wait has been called. This should be fixed so that publish goes\n \/\/ to last time level and level is advanced only after wait.\n icComm->increaseTimeLevel(layers[l]->getLayerId());\n\n layers[l]->publish(icComm, sim_time);\n }\n\n \/\/ wait for all published data to arrive\n \/\/\n for (int l = 0; l < numLayers; l++) {\n layers[l]->waitOnPublish(icComm);\n }\n\n \/\/ make sure simTime is updated even if HyPerCol isn't running time loop\n\n float outputTime = simTime; \/\/ so that outputState is called with the correct time\n \/\/ but doesn't effect runTimer\n\n simTime = sim_time + deltaTime;\n\n runTimer->stop();\n\n outputState(outputTime);\n\n return simTime;\n}\n\nint HyPerCol::exitRunLoop(bool exitOnFinish)\n{\n int status = 0;\n\n \/\/ output final state of layers and connections\n \/\/\n bool last = true;\n\n for (int l = 0; l < numLayers; l++) {\n layers[l]->writeState(layers[l]->getName(), simTime, last);\n }\n\n for (int c = 0; c < numConnections; c++) {\n connections[c]->outputState(simTime, last);\n }\n\n if (exitOnFinish) {\n delete this;\n exit(0);\n }\n\n return status;\n}\n\nint HyPerCol::initializeThreads(int device)\n{\n clDevice = new CLDevice(device);\n return 0;\n}\n\nint HyPerCol::finalizeThreads()\n{\n delete clDevice;\n return 0;\n}\n\nint HyPerCol::loadState()\n{\n return 0;\n}\n\nint HyPerCol::writeState()\n{\n for (int l = 0; l < numLayers; l++) {\n layers[l]->writeState(OUTPUT_PATH, simTime);\n }\n return 0;\n}\n\nint HyPerCol::insertProbe(ColProbe * p)\n{\n ColProbe ** newprobes;\n newprobes = (ColProbe **) malloc((numProbes + 1) * sizeof(ColProbe *));\n assert(newprobes != NULL);\n\n for (int i = 0; i < numProbes; i++) {\n newprobes[i] = probes[i];\n }\n delete probes;\n\n probes = newprobes;\n probes[numProbes] = p;\n\n return ++numProbes;\n}\n\nint HyPerCol::outputState(float time)\n{\n for( int n = 0; n < numProbes; n++ ) {\n probes[n]->outputState(time, this);\n }\n return EXIT_SUCCESS;\n}\n\nint HyPerCol::checkMarginWidths() {\n \/\/ For each connection, make sure that the post-synaptic margin width is\n \/\/ large enough for the patch size.\n\n \/\/ TODO instead of having marginWidth supplied to HyPerLayers in the\n \/\/ params.pv file, calculate them based on the patch sizes here.\n \/\/ Hard part: numExtended-sized quantities (e.g. clayer->activity) can't\n \/\/ be allocated and initialized until after nPad is determined.\n\n int status = EXIT_SUCCESS;\n int status1, status2;\n for( int c=0; c < numConnections; c++ ) {\n HyPerConn * conn = connections[c];\n int padding = conn->pre->getLayerLoc()->nb;\n\n int xScalePre = conn->preSynapticLayer()->getXScale();\n int xScalePost = conn->postSynapticLayer()->getXScale();\n status1 = zCheckMarginWidth(conn, \"x\", padding, conn->xPatchSize(), xScalePre, xScalePost, status);\n\n int yScalePre = conn->preSynapticLayer()->getYScale();\n int yScalePost = conn->postSynapticLayer()->getYScale();\n status2 = zCheckMarginWidth(conn, \"y\", padding, conn->yPatchSize(), yScalePre, yScalePost, status);\n status = (status == EXIT_SUCCESS && status1 == EXIT_SUCCESS && status2 == EXIT_SUCCESS) ?\n EXIT_SUCCESS : EXIT_FAILURE;\n }\n return status;\n} \/\/ end HyPerCol::checkMarginWidths()\n\nint HyPerCol::zCheckMarginWidth(HyPerConn * conn, const char * dim, int padding, int patchSize, int scalePre, int scalePost, int prevStatus) {\n int status;\n int scaleDiff = scalePre - scalePost;\n \/\/ if post has higher neuronal density than pre, scaleDiff < 0.\n int needed = scaleDiff > 0 ? ( patchSize\/( (int) powf(2,scaleDiff) )\/2 ) :\n ( (patchSize\/2) * ( (int) powf(2,-scaleDiff) ) );\n if( padding < needed ) {\n if( prevStatus == EXIT_SUCCESS ) {\n fprintf(stderr, \"Margin width error.\\n\");\n }\n fprintf(stderr, \"Connection \\\"%s\\\", dimension %s:\\n\", conn->getName(), dim);\n fprintf(stderr, \" Margin width %d, patch size %d, presynaptic scale %d, postsynaptic scale %d\\n\",\n padding, patchSize, scalePre, scalePost);\n fprintf(stderr, \" Needed margin width=%d\\n\", needed);\n status = EXIT_FAILURE;\n if( numberOfColumns() > 1 || padding > 0 ) {\n fprintf(stderr, \"Exiting.\\n\");\n exit(EXIT_FAILURE);\n }\n else {\n fprintf(stderr, \"Continuing, but there may be undesirable edge effects.\\n\");\n }\n }\n else status = EXIT_SUCCESS;\n return status;\n}\n\n} \/\/ PV namespace\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n\nusing namespace MCPP;\n\n\nnamespace MCPP {\n\n\n\tstatic const Word priority=2;\n\tstatic const String name(\"Command Support\");\n\n\n\t\/\/\tPrecedes all help output\n\tstatic const String help_banner(\"====HELP====\");\n\t\/\/\tPrefix that precedes commands\n\tstatic const String prefix(\"\/\");\n\t\/\/\tSeparates command from its summary in help\n\tstatic const String summary_separator(\" - \");\n\t\/\/\tStarts off the chat message that's sent when\n\t\/\/\tincorrect syntax is used\n\tstatic const String incorrect_syntax_label(\"Incorrect syntax\");\n\t\/\/\tIntroduces \"\/help\" in incorrect syntax strings\n\tstatic const String try_label(\" try \");\n\t\/\/\tThe identifier for the help command\n\tstatic const String help_identifier(\"help\");\n\t\/\/\tA space\n\tstatic const String separator(\" \");\n\t\/\/\tInforms the user that they are not permitted\n\t\/\/\tto execute a command\n\tstatic const String not_permitted(\"You are not permitted to do that\");\n\t\/\/\tInforms the user that a command they attempted\n\t\/\/\tto execute does not exist\n\tstatic const String does_not_exist(\"Command does not exist\");\n\t\/\/\tGives help with the help command\n\tstatic const String help_help(\"For help with a specific command type \");\n\t\/\/\tThe syntax of the help command is \/help and then this\n\tstatic const String help_syntax(\"\");\n\t\n\t\n\t\/\/\tParses a command\n\tstatic const Regex parse(\"^\\\\\/(\\\\S*)(?:\\\\s*(.*))?$\");\n\t\/\/\tSplits the arguments to a command\n\t\/\/\ton whitespace\n\tstatic const Regex split(\"(?<=\\\\s|^)\\\\S+(?=\\\\s|$)\");\n\t\/\/\tChecks to see if there's trailing whitespace\n\tstatic const Regex trailing_whitespace(\"\\\\s$\");\n\n\n\tCommand * Commands::get (const String & identifier) {\n\t\n\t\tauto iter=map.find(identifier);\n\t\t\n\t\treturn (iter==map.end()) ? nullptr : iter->second;\n\t\n\t}\n\t\n\t\n\tChatMessage Commands::incorrect_syntax () {\n\t\n\t\tChatMessage retr;\n\t\tretr\t<<\tChatStyle::Red\n\t\t\t\t<<\tChatStyle::Bold\n\t\t\t\t<<\tincorrect_syntax_label\n\t\t\t\t<<\tChatFormat::Pop\n\t\t\t\t<<\ttry_label\n\t\t\t\t<<\tChatStyle::Bold\n\t\t\t\t<<\tprefix\n\t\t\t\t<<\thelp_identifier;\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tChatMessage Commands::incorrect_syntax (const String & identifier) {\n\t\n\t\tauto retr=incorrect_syntax();\n\t\t\n\t\tretr << separator << identifier;\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tChatMessage Commands::command_dne () {\n\t\n\t\tChatMessage retr;\n\t\tretr\t<<\tChatStyle::Red\n\t\t\t\t<<\tChatStyle::Bold\n\t\t\t\t<<\tdoes_not_exist;\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tChatMessage Commands::insufficient_privileges () {\n\t\n\t\tChatMessage retr;\n\t\tretr\t<<\tChatStyle::Red\n\t\t\t\t<<\tChatStyle::Bold\n\t\t\t\t<<\tnot_permitted;\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tChatMessage Commands::help (CommandEvent event) {\n\t\n\t\tChatMessage retr;\n\t\tretr\t<<\tChatStyle::Yellow\n\t\t\t\t<<\tChatStyle::Bold\n\t\t\t\t<<\thelp_banner\n\t\t\t\t<<\tChatFormat::Pop\n\t\t\t\t<<\tNewline;\n\t\t\t\t\n\t\tif (event.Arguments.Count()==0) {\n\t\t\n\t\t\t\/\/\tIf there are no arguments, we retrieve\n\t\t\t\/\/\ta listing and summary of all commands\n\t\t\t\n\t\t\tretr\t<<\thelp_help\n\t\t\t\t\t<<\tChatStyle::Bold\n\t\t\t\t\t<<\tprefix\n\t\t\t\t\t<<\thelp_identifier\n\t\t\t\t\t<<\tseparator\n\t\t\t\t\t<<\thelp_syntax\n\t\t\t\t\t<<\tChatFormat::Pop\t\t\/\/\tGet rid of bold\n\t\t\t\t\t<<\tChatFormat::Pop;\t\/\/\tGet rid of yellow (from above)\n\t\t\t\n\t\t\t\/\/\tLoop and only show user commands that\n\t\t\t\/\/\tthey are permitted to use\n\t\t\tfor (const auto & c : list) {\n\t\t\t\n\t\t\t\tevent.Identifier=c.Item<0>();\n\t\t\t\n\t\t\t\tif (c.Item<1>()->Check(event)) {\n\t\t\t\n\t\t\t\t\tretr\t<<\tNewline\n\t\t\t\t\t\t\t<<\tChatStyle::Bold\n\t\t\t\t\t\t\t<<\tprefix\n\t\t\t\t\t\t\t<<\tc.Item<0>()\n\t\t\t\t\t\t\t<<\tChatFormat::Pop\n\t\t\t\t\t\t\t<<\tsummary_separator;\n\t\t\t\t\t\t\t\n\t\t\t\t\tc.Item<1>()->Summary(c.Item<0>(),retr);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\n\t\t\t}\n\t\t\n\t\t} else if (event.Arguments.Count()==1) {\n\t\t\n\t\t\t\/\/\tAttempt to find and deliver help specific\n\t\t\t\/\/\tto this command\n\t\t\t\n\t\t\tevent.Identifier=event.Arguments[0];\n\t\t\tauto command=get(event.Identifier);\n\t\t\t\n\t\t\t\/\/\tMake sure command exists\n\t\t\tif (command==nullptr) return command_dne();\n\t\t\t\n\t\t\t\/\/\tMake sure user can view this command\n\t\t\tif (!command->Check(event)) return insufficient_privileges();\n\t\t\t\n\t\t\t\/\/\tOutput\n\t\t\tretr\t<<\tChatStyle::Bold\n\t\t\t\t\t<<\tprefix\n\t\t\t\t\t<<\tevent.Identifier\n\t\t\t\t\t<<\tChatFormat::Pop\t\/\/\tGet rid of bold\n\t\t\t\t\t<<\tChatFormat::Pop\t\/\/\tGet rid of yellow (from above)\n\t\t\t\t\t<<\tNewline;\n\t\t\t\t\t\n\t\t\tcommand->Help(event.Identifier,retr);\n\t\t\n\t\t} else {\n\t\t\n\t\t\t\/\/\tIf there is more than one argument,\n\t\t\t\/\/\tthat's an error\n\t\t\treturn incorrect_syntax();\n\t\t\n\t\t}\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tNullable Commands::parse (SmartPointer client, const String & str, bool keep_trailing) {\n\t\n\t\tNullable retr;\n\t\n\t\t\/\/\tIf it's not actually a command, return\n\t\t\/\/\tat once\n\t\tauto match=::parse.Match(str);\n\t\tif (!match.Success()) return retr;\n\t\t\n\t\t\/\/\tSplit the arguments\n\t\tauto raw_args=match[2].Value();\n\t\tauto matches=split.Matches(raw_args);\n\t\tVector args;\n\t\tfor (auto & match : matches) args.Add(match.Value());\n\t\t\n\t\t\/\/\tIf we're keeping trailing whitespace, check\n\t\t\/\/\tfor it\n\t\tif (\n\t\t\tkeep_trailing &&\n\t\t\ttrailing_whitespace.IsMatch(str)\n\t\t) args.EmplaceBack();\n\t\t\n\t\tretr=CommandEvent{\n\t\t\tstd::move(client),\n\t\t\tmatch[1].Value(),\n\t\t\tstd::move(args),\n\t\t\tstr,\n\t\t\tstd::move(raw_args)\n\t\t};\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tNullable Commands::execute (SmartPointer client, const String & str) {\n\t\n\t\tNullable retr;\n\t\n\t\t\/\/\tAttempt to parse the command\n\t\tauto event=parse(\n\t\t\tstd::move(client),\n\t\t\tstr\n\t\t);\n\t\t\n\t\t\/\/\tIf the parse failed, it's not\n\t\t\/\/\tactually a command\n\t\tif (event.IsNull()) return retr;\n\t\t\n\t\t\/\/\tIs it the help command?\n\t\tif (event->Identifier==help_identifier) {\n\t\t\n\t\t\tretr=help(std::move(*event));\n\t\t\t\n\t\t\treturn retr;\n\t\t\n\t\t}\n\t\t\n\t\t\/\/\tAttempt to look up this command\n\t\tauto command=get(event->Identifier);\n\t\t\n\t\t\/\/\tIf there's no such command, return that\n\t\tif (command==nullptr) {\n\t\t\n\t\t\tretr=command_dne();\n\t\t\t\n\t\t\treturn retr;\n\t\t\n\t\t}\n\t\t\n\t\t\/\/\tEnsure command processing should proceed\n\t\tif (!command->Check(*event)) {\n\t\t\n\t\t\tretr=insufficient_privileges();\n\t\t\t\n\t\t\treturn retr;\n\t\t\n\t\t}\n\t\t\n\t\t\/\/\tSave the identifier -- we'll need it if\n\t\t\/\/\tthe syntax is incorrect\n\t\tauto identifier=event->Identifier;\n\t\t\n\t\t\/\/\tOtherwise execute the command\n\t\tauto result=command->Execute(std::move(*event));\n\t\t\n\t\tswitch (result.Status) {\n\t\t\n\t\t\tcase CommandStatus::Success:\n\t\t\t\tretr=std::move(result.Message);\n\t\t\t\tbreak;\n\t\t\tcase CommandStatus::SyntaxError:\n\t\t\tdefault:\n\t\t\t\tretr=incorrect_syntax(identifier);\n\t\t\t\tbreak;\n\t\t\tcase CommandStatus::DoesNotExist:\n\t\t\t\tretr=command_dne();\n\t\t\t\tbreak;\n\t\t\tcase CommandStatus::Forbidden:\n\t\t\t\tretr=insufficient_privileges();\n\t\t\t\tbreak;\n\t\t\n\t\t}\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tVector Commands::auto_complete (SmartPointer client, const String & str) {\n\t\n\t\tVector retr;\n\t\n\t\t\/\/\tParse\n\t\tauto event=parse(\n\t\t\tstd::move(client),\n\t\t\tstr,\n\t\t\ttrue\n\t\t);\n\t\t\n\t\t\/\/\tIf the parse failed, return at once\n\t\tif (event.IsNull()) return retr;\n\t\t\n\t\t\/\/\tIf the parse actually extracted a full\n\t\t\/\/\tcommand identifier, we try and find that\n\t\t\/\/\tcommand to get auto completions, otherwise\n\t\t\/\/\twe try and autocomplete to a command\n\t\t\/\/\tidentifier\n\t\t\n\t\tif (event->Arguments.Count()==0) {\n\t\t\n\t\t\t\/\/\tConstruct a regular expression which\n\t\t\t\/\/\tmatches the stem the user gave\n\t\t\tRegex regex(\n\t\t\t\tString::Format(\n\t\t\t\t\t\"^{0}\",\n\t\t\t\t\tRegex::Escape(event->Identifier)\n\t\t\t\t)\n\t\t\t);\n\t\t\t\n\t\t\t\/\/\tLoop over each command and create list\n\t\t\t\/\/\tof suggestions based on matches\n\t\t\tfor (const auto & t : list) if (\n\t\t\t\tregex.IsMatch(t.Item<0>()) &&\n\t\t\t\t\/\/\tMake sure this user can actually run\n\t\t\t\t\/\/\tthis command\n\t\t\t\tt.Item<1>()->Check(*event)\n\t\t\t) retr.Add(t.Item<0>());\n\t\t\n\t\t} else {\n\t\t\n\t\t\t\/\/\tAttempt to get command\n\t\t\tauto command=get(event->Identifier);\n\t\t\t\n\t\t\tif (\n\t\t\t\t\/\/\tIf the command could not be found,\n\t\t\t\t\/\/\treturn at once\n\t\t\t\t(command==nullptr) ||\n\t\t\t\t\/\/\tIf the user can't actually execute the\n\t\t\t\t\/\/\tcommand, return at once\n\t\t\t\t!command->Check(*event)\n\t\t\t) return retr;\n\t\t\t\n\t\t\t\/\/\tGet auto completions\n\t\t\tretr=command->AutoComplete(*event);\n\t\t\n\t\t}\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tstatic Singleton singleton;\n\t\n\t\n\tCommands & Commands::Get () noexcept {\n\t\n\t\treturn singleton.Get();\n\t\n\t}\n\t\n\t\n\tconst String & Commands::Name () const noexcept {\n\t\n\t\treturn name;\n\t\n\t}\n\t\n\t\n\tWord Commands::Priority () const noexcept {\n\t\n\t\treturn priority;\n\t\n\t}\n\t\n\t\n\tvoid Commands::Install () {\n\t\n\t\ttypedef Packets::Play::Clientbound::TabComplete reply;\n\t\ttypedef Packets::Play::Serverbound::TabComplete request;\n\t\n\t\t\/\/\tInstall auto complete handler\n\t\tServer::Get().Router(\n\t\t\trequest::PacketID,\n\t\t\trequest::State\n\t\t)=[this] (PacketEvent event) mutable {\n\t\t\n\t\t\tauto packet=event.Data.Get();\n\t\t\t\n\t\t\treply p;\n\t\t\tp.Match=auto_complete(event.From,packet.Text);\n\t\t\t\n\t\t\tevent.From->Send(p);\n\t\t\n\t\t};\n\t\t\n\t\t\/\/\tInstall chat handler\n\t\t\n\t\tauto & chat=Chat::Get();\n\t\t\n\t\t\/\/\tSave previous handler\n\t\tauto prev=std::move(chat.Chat);\n\t\t\n\t\t\/\/\tInstall new handler\n\t\t#pragma GCC diagnostic push\n\t\t#pragma GCC diagnostic ignored \"-Wpedantic\"\n\t\tchat.Chat=[this,prev=std::move(prev)] (ChatEvent event) mutable {\n\t\t\n\t\t\t\/\/\tAttempt to execute as a command\n\t\t\tauto result=execute(event.From,event.Body);\n\t\t\t\n\t\t\tif (result.IsNull()) {\n\t\t\t\n\t\t\t\t\/\/\tIf parsing\/execution fails, attempt\n\t\t\t\t\/\/\tto pass through\n\t\t\t\tif (prev) prev(std::move(event));\n\t\t\t\n\t\t\t\/\/\tSending empty messages crashes client\n\t\t\t} else if (result->Message.Count()!=0) {\n\t\t\t\n\t\t\t\t\/\/\tIf parsing\/execute succeeds, send\n\t\t\t\t\/\/\tresponse\n\t\t\t\t\n\t\t\t\tresult->Recipients.Add(std::move(event.From));\n\t\t\t\t\n\t\t\t\tChat::Get().Send(*result);\n\t\t\t\n\t\t\t}\n\t\t\n\t\t};\n\t\t#pragma GCC diagnostic pop\n\t\n\t}\n\t\n\t\n\tNullable Commands::operator () (const String & str) {\n\t\n\t\tNullable retr;\n\t\t\n\t\tauto result=execute(\n\t\t\tSmartPointer(),\n\t\t\tstr\n\t\t);\n\t\t\n\t\tif (!result.IsNull()) retr=Chat::ToString(*result);\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tvoid Commands::Add (String identifier, Command * command) {\n\t\n\t\t\/\/\tDon't proceed with adding null pointers\n\t\tif (command==nullptr) return;\n\t\n\t\t\/\/\tFind insertion point in vector\n\t\tWord loc=0;\n\t\tfor (\n\t\t\t;\n\t\t\t(loc()Commands Fixes#include \n#include \n#include \n#include \n\n\nusing namespace MCPP;\n\n\nnamespace MCPP {\n\n\n\tstatic const Word priority=2;\n\tstatic const String name(\"Command Support\");\n\n\n\t\/\/\tPrecedes all help output\n\tstatic const String help_banner(\"====HELP====\");\n\t\/\/\tPrefix that precedes commands\n\tstatic const String prefix(\"\/\");\n\t\/\/\tSeparates command from its summary in help\n\tstatic const String summary_separator(\" - \");\n\t\/\/\tStarts off the chat message that's sent when\n\t\/\/\tincorrect syntax is used\n\tstatic const String incorrect_syntax_label(\"Incorrect syntax\");\n\t\/\/\tIntroduces \"\/help\" in incorrect syntax strings\n\tstatic const String try_label(\" try \");\n\t\/\/\tThe identifier for the help command\n\tstatic const String help_identifier(\"help\");\n\t\/\/\tA space\n\tstatic const String separator(\" \");\n\t\/\/\tInforms the user that they are not permitted\n\t\/\/\tto execute a command\n\tstatic const String not_permitted(\"You are not permitted to do that\");\n\t\/\/\tInforms the user that a command they attempted\n\t\/\/\tto execute does not exist\n\tstatic const String does_not_exist(\"Command does not exist\");\n\t\/\/\tGives help with the help command\n\tstatic const String help_help(\"For help with a specific command type \");\n\t\/\/\tThe syntax of the help command is \/help and then this\n\tstatic const String help_syntax(\"\");\n\t\n\t\n\t\/\/\tParses a command\n\tstatic const Regex parse(\"^\\\\\/(\\\\S*)(?:\\\\s*(.*))?$\");\n\t\/\/\tSplits the arguments to a command\n\t\/\/\ton whitespace\n\tstatic const Regex split(\"(?<=\\\\s|^)\\\\S+(?=\\\\s|$)\");\n\t\/\/\tChecks to see if there's trailing whitespace\n\tstatic const Regex trailing_whitespace(\"\\\\s$\");\n\n\n\tCommand * Commands::get (const String & identifier) {\n\t\n\t\tauto iter=map.find(identifier);\n\t\t\n\t\treturn (iter==map.end()) ? nullptr : iter->second;\n\t\n\t}\n\t\n\t\n\tChatMessage Commands::incorrect_syntax () {\n\t\n\t\tChatMessage retr;\n\t\tretr\t<<\tChatStyle::Red\n\t\t\t\t<<\tChatStyle::Bold\n\t\t\t\t<<\tincorrect_syntax_label\n\t\t\t\t<<\tChatFormat::Pop\n\t\t\t\t<<\ttry_label\n\t\t\t\t<<\tChatStyle::Bold\n\t\t\t\t<<\tprefix\n\t\t\t\t<<\thelp_identifier;\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tChatMessage Commands::incorrect_syntax (const String & identifier) {\n\t\n\t\tauto retr=incorrect_syntax();\n\t\t\n\t\tretr << separator << identifier;\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tChatMessage Commands::command_dne () {\n\t\n\t\tChatMessage retr;\n\t\tretr\t<<\tChatStyle::Red\n\t\t\t\t<<\tChatStyle::Bold\n\t\t\t\t<<\tdoes_not_exist;\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tChatMessage Commands::insufficient_privileges () {\n\t\n\t\tChatMessage retr;\n\t\tretr\t<<\tChatStyle::Red\n\t\t\t\t<<\tChatStyle::Bold\n\t\t\t\t<<\tnot_permitted;\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tChatMessage Commands::help (CommandEvent event) {\n\t\n\t\tChatMessage retr;\n\t\tretr\t<<\tChatStyle::Yellow\n\t\t\t\t<<\tChatStyle::Bold\n\t\t\t\t<<\thelp_banner\n\t\t\t\t<<\tChatFormat::Pop\n\t\t\t\t<<\tNewline;\n\t\t\t\t\n\t\tif (event.Arguments.Count()==0) {\n\t\t\n\t\t\t\/\/\tIf there are no arguments, we retrieve\n\t\t\t\/\/\ta listing and summary of all commands\n\t\t\t\n\t\t\tretr\t<<\thelp_help\n\t\t\t\t\t<<\tChatStyle::Bold\n\t\t\t\t\t<<\tprefix\n\t\t\t\t\t<<\thelp_identifier\n\t\t\t\t\t<<\tseparator\n\t\t\t\t\t<<\thelp_syntax\n\t\t\t\t\t<<\tChatFormat::Pop\t\t\/\/\tGet rid of bold\n\t\t\t\t\t<<\tChatFormat::Pop;\t\/\/\tGet rid of yellow (from above)\n\t\t\t\n\t\t\t\/\/\tLoop and only show user commands that\n\t\t\t\/\/\tthey are permitted to use\n\t\t\tfor (const auto & c : list) {\n\t\t\t\n\t\t\t\tevent.Identifier=c.Item<0>();\n\t\t\t\n\t\t\t\tif (c.Item<1>()->Check(event)) {\n\t\t\t\n\t\t\t\t\tretr\t<<\tNewline\n\t\t\t\t\t\t\t<<\tChatStyle::Bold\n\t\t\t\t\t\t\t<<\tprefix\n\t\t\t\t\t\t\t<<\tc.Item<0>()\n\t\t\t\t\t\t\t<<\tChatFormat::Pop\n\t\t\t\t\t\t\t<<\tsummary_separator;\n\t\t\t\t\t\t\t\n\t\t\t\t\tc.Item<1>()->Summary(c.Item<0>(),retr);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\n\t\t\t}\n\t\t\n\t\t} else if (event.Arguments.Count()==1) {\n\t\t\n\t\t\t\/\/\tAttempt to find and deliver help specific\n\t\t\t\/\/\tto this command\n\t\t\t\n\t\t\tevent.Identifier=event.Arguments[0];\n\t\t\tauto command=get(event.Identifier);\n\t\t\t\n\t\t\t\/\/\tMake sure command exists\n\t\t\tif (command==nullptr) return command_dne();\n\t\t\t\n\t\t\t\/\/\tMake sure user can view this command\n\t\t\tif (!command->Check(event)) return insufficient_privileges();\n\t\t\t\n\t\t\t\/\/\tOutput\n\t\t\tretr\t<<\tChatStyle::Bold\n\t\t\t\t\t<<\tprefix\n\t\t\t\t\t<<\tevent.Identifier\n\t\t\t\t\t<<\tChatFormat::Pop\t\/\/\tGet rid of bold\n\t\t\t\t\t<<\tChatFormat::Pop\t\/\/\tGet rid of yellow (from above)\n\t\t\t\t\t<<\tNewline;\n\t\t\t\t\t\n\t\t\tcommand->Help(event.Identifier,retr);\n\t\t\n\t\t} else {\n\t\t\n\t\t\t\/\/\tIf there is more than one argument,\n\t\t\t\/\/\tthat's an error\n\t\t\treturn incorrect_syntax();\n\t\t\n\t\t}\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tNullable Commands::parse (SmartPointer client, const String & str, bool keep_trailing) {\n\t\n\t\tNullable retr;\n\t\n\t\t\/\/\tIf it's not actually a command, return\n\t\t\/\/\tat once\n\t\tauto match=::parse.Match(str);\n\t\tif (!match.Success()) return retr;\n\t\t\n\t\t\/\/\tSplit the arguments\n\t\tauto raw_args=match[2].Value();\n\t\tauto matches=split.Matches(raw_args);\n\t\tVector args;\n\t\tfor (auto & match : matches) args.Add(match.Value());\n\t\t\n\t\t\/\/\tIf we're keeping trailing whitespace, check\n\t\t\/\/\tfor it\n\t\tif (\n\t\t\tkeep_trailing &&\n\t\t\ttrailing_whitespace.IsMatch(str)\n\t\t) args.EmplaceBack();\n\t\t\n\t\tretr=CommandEvent{\n\t\t\tstd::move(client),\n\t\t\tmatch[1].Value(),\n\t\t\tstd::move(args),\n\t\t\tstr,\n\t\t\tstd::move(raw_args)\n\t\t};\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tNullable Commands::execute (SmartPointer client, const String & str) {\n\t\n\t\tNullable retr;\n\t\n\t\t\/\/\tAttempt to parse the command\n\t\tauto event=parse(\n\t\t\tstd::move(client),\n\t\t\tstr\n\t\t);\n\t\t\n\t\t\/\/\tIf the parse failed, it's not\n\t\t\/\/\tactually a command\n\t\tif (event.IsNull()) return retr;\n\t\t\n\t\t\/\/\tIs it the help command?\n\t\tif (event->Identifier==help_identifier) {\n\t\t\n\t\t\tretr=help(std::move(*event));\n\t\t\t\n\t\t\treturn retr;\n\t\t\n\t\t}\n\t\t\n\t\t\/\/\tAttempt to look up this command\n\t\tauto command=get(event->Identifier);\n\t\t\n\t\t\/\/\tIf there's no such command, return that\n\t\tif (command==nullptr) {\n\t\t\n\t\t\tretr=command_dne();\n\t\t\t\n\t\t\treturn retr;\n\t\t\n\t\t}\n\t\t\n\t\t\/\/\tEnsure command processing should proceed\n\t\tif (!command->Check(*event)) {\n\t\t\n\t\t\tretr=insufficient_privileges();\n\t\t\t\n\t\t\treturn retr;\n\t\t\n\t\t}\n\t\t\n\t\t\/\/\tSave the identifier -- we'll need it if\n\t\t\/\/\tthe syntax is incorrect\n\t\tauto identifier=event->Identifier;\n\t\t\n\t\t\/\/\tOtherwise execute the command\n\t\tauto result=command->Execute(std::move(*event));\n\t\t\n\t\tswitch (result.Status) {\n\t\t\n\t\t\tcase CommandStatus::Success:\n\t\t\t\tretr=std::move(result.Message);\n\t\t\t\tbreak;\n\t\t\tcase CommandStatus::SyntaxError:\n\t\t\tdefault:\n\t\t\t\tretr=incorrect_syntax(identifier);\n\t\t\t\tbreak;\n\t\t\tcase CommandStatus::DoesNotExist:\n\t\t\t\tretr=command_dne();\n\t\t\t\tbreak;\n\t\t\tcase CommandStatus::Forbidden:\n\t\t\t\tretr=insufficient_privileges();\n\t\t\t\tbreak;\n\t\t\n\t\t}\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tVector Commands::auto_complete (SmartPointer client, const String & str) {\n\t\n\t\tVector retr;\n\t\n\t\t\/\/\tParse\n\t\tauto event=parse(\n\t\t\tstd::move(client),\n\t\t\tstr,\n\t\t\ttrue\n\t\t);\n\t\t\n\t\t\/\/\tIf the parse failed, return at once\n\t\tif (event.IsNull()) return retr;\n\t\t\n\t\t\/\/\tIf the parse actually extracted a full\n\t\t\/\/\tcommand identifier, we try and find that\n\t\t\/\/\tcommand to get auto completions, otherwise\n\t\t\/\/\twe try and autocomplete to a command\n\t\t\/\/\tidentifier\n\t\t\n\t\tif (event->Arguments.Count()==0) {\n\t\t\n\t\t\t\/\/\tConstruct a regular expression which\n\t\t\t\/\/\tmatches the stem the user gave\n\t\t\tRegex regex(\n\t\t\t\tString::Format(\n\t\t\t\t\t\"^{0}\",\n\t\t\t\t\tRegex::Escape(event->Identifier)\n\t\t\t\t)\n\t\t\t);\n\t\t\t\n\t\t\t\/\/\tLoop over each command and create list\n\t\t\t\/\/\tof suggestions based on matches\n\t\t\tfor (const auto & t : list) if (\n\t\t\t\tregex.IsMatch(t.Item<0>()) &&\n\t\t\t\t\/\/\tMake sure this user can actually run\n\t\t\t\t\/\/\tthis command\n\t\t\t\tt.Item<1>()->Check(*event)\n\t\t\t) retr.Add(t.Item<0>());\n\t\t\n\t\t} else {\n\t\t\n\t\t\t\/\/\tAttempt to get command\n\t\t\tauto command=get(event->Identifier);\n\t\t\t\n\t\t\tif (\n\t\t\t\t\/\/\tIf the command could not be found,\n\t\t\t\t\/\/\treturn at once\n\t\t\t\t(command==nullptr) ||\n\t\t\t\t\/\/\tIf the user can't actually execute the\n\t\t\t\t\/\/\tcommand, return at once\n\t\t\t\t!command->Check(*event)\n\t\t\t) return retr;\n\t\t\t\n\t\t\t\/\/\tGet auto completions\n\t\t\tretr=command->AutoComplete(*event);\n\t\t\n\t\t}\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tstatic Singleton singleton;\n\t\n\t\n\tCommands & Commands::Get () noexcept {\n\t\n\t\treturn singleton.Get();\n\t\n\t}\n\t\n\t\n\tconst String & Commands::Name () const noexcept {\n\t\n\t\treturn name;\n\t\n\t}\n\t\n\t\n\tWord Commands::Priority () const noexcept {\n\t\n\t\treturn priority;\n\t\n\t}\n\t\n\t\n\tvoid Commands::Install () {\n\t\n\t\ttypedef Packets::Play::Clientbound::TabComplete reply;\n\t\ttypedef Packets::Play::Serverbound::TabComplete request;\n\t\t\n\t\tauto & server=Server::Get();\n\t\n\t\t\/\/\tInstall auto complete handler\n\t\tserver.Router(\n\t\t\trequest::PacketID,\n\t\t\trequest::State\n\t\t)=[this] (PacketEvent event) mutable {\n\t\t\n\t\t\tauto packet=event.Data.Get();\n\t\t\t\n\t\t\treply p;\n\t\t\tp.Match=auto_complete(event.From,packet.Text);\n\t\t\t\n\t\t\tevent.From->Send(p);\n\t\t\n\t\t};\n\t\t\n\t\t\/\/\tInstall chat handler\n\t\t\n\t\tauto & chat=Chat::Get();\n\t\t\n\t\t\/\/\tSave previous handler\n\t\tauto prev=std::move(chat.Chat);\n\t\t\n\t\t\/\/\tInstall new handler\n\t\t#pragma GCC diagnostic push\n\t\t#pragma GCC diagnostic ignored \"-Wpedantic\"\n\t\tchat.Chat=[this,prev=std::move(prev)] (ChatEvent event) mutable {\n\t\t\n\t\t\t\/\/\tAttempt to execute as a command\n\t\t\tauto result=execute(event.From,event.Body);\n\t\t\t\n\t\t\tif (result.IsNull()) {\n\t\t\t\n\t\t\t\t\/\/\tIf parsing\/execution fails, attempt\n\t\t\t\t\/\/\tto pass through\n\t\t\t\tif (prev) prev(std::move(event));\n\t\t\t\n\t\t\t\/\/\tSending empty messages crashes client\n\t\t\t} else if (result->Message.Count()!=0) {\n\t\t\t\n\t\t\t\t\/\/\tIf parsing\/execute succeeds, send\n\t\t\t\t\/\/\tresponse\n\t\t\t\t\n\t\t\t\tresult->Recipients.Add(std::move(event.From));\n\t\t\t\t\n\t\t\t\tChat::Get().Send(*result);\n\t\t\t\n\t\t\t}\n\t\t\n\t\t};\n\t\t#pragma GCC diagnostic pop\n\t\t\n\t\t\/\/\tInstall as command interpreter into\n\t\t\/\/\tthe server\n\t\tserver.SetCommandInterpreter(this);\n\t\n\t}\n\t\n\t\n\tNullable Commands::operator () (const String & str) {\n\t\n\t\tNullable retr;\n\t\t\n\t\tauto result=execute(\n\t\t\tSmartPointer(),\n\t\t\tString(\"\/\")+str\n\t\t);\n\t\t\n\t\tif (!result.IsNull()) retr=Chat::ToString(*result);\n\t\t\n\t\treturn retr;\n\t\n\t}\n\t\n\t\n\tvoid Commands::Add (String identifier, Command * command) {\n\t\n\t\t\/\/\tDon't proceed with adding null pointers\n\t\tif (command==nullptr) return;\n\t\n\t\t\/\/\tFind insertion point in vector\n\t\tWord loc=0;\n\t\tfor (\n\t\t\t;\n\t\t\t(loc()"} {"text":"\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include \n#include \n#include \n#include \n#include \n\n#if 1\/\/ndef NDEBUG\n#include \n#include \n#endif\n\n#include \n\n#include \"pnm_image.h\"\n\nnamespace visionaray\n{\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Helper functions\n\/\/\n\nstatic void load_binary_rgb(\n uint8_t* dst,\n std::ifstream& file,\n size_t width,\n size_t height,\n int \/*max_value*\/\n )\n{\n\/\/ assert(max_value < 256); \/\/ TODO: 16-bit\n\/\/ assert(max_value == 255); \/\/ TODO: scaling\n\n size_t pitch = width * 3;\n file.read(reinterpret_cast(dst), pitch * height);\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ pnm_image\n\/\/\n\nbool pnm_image::load(std::string const& filename)\n{\n enum format { P1 = 1, P2, P3, P4, P5, P6 };\n\n std::ifstream file(filename);\n\n std::string line;\n\n \/\/\n \/\/ First line determines format:\n \/\/ P1: ASCII BW | P4: binary BW\n \/\/ P2: ASCII gray scale | P5: binary gray scale\n \/\/ P3: ASCII RGB | P6: binary RGB\n \/\/\n std::getline(file, line);\n\n if (line.size() < 2 || line[0] != 'P' || line[1] < '0' || line[1] > '6')\n {\n std::cerr << \"Invalid file format: \" << line << '\\n';\n return false;\n }\n\n format fmt = static_cast(line[1] - '0');\n\n \/\/ Width and height\n for (;;)\n {\n std::getline(file, line);\n\n if (line[0] == '#')\n {\n \/\/ Skip comments\n continue;\n }\n else\n {\n std::vector tokens;\n boost::algorithm::split(\n tokens,\n line,\n boost::algorithm::is_any_of(\" \\t\")\n );\n\n if (tokens.size() != 2)\n {\n std::cerr << \"Invalid dimensions\\n\";\n return false;\n }\n\n width_ = static_cast(std::stoi(tokens[0]));\n height_ = static_cast(std::stoi(tokens[1]));\n\n break;\n }\n }\n\n \/\/ Max. value\n int max_value = 255;\n if (fmt != P1 && fmt != P4)\n {\n for (;;)\n {\n std::getline(file, line);\n\n if (line[0] == '#')\n {\n \/\/ Skip comments\n continue;\n }\n else\n {\n max_value = std::stoi(line);\n break;\n }\n }\n }\n\n switch (fmt)\n {\n default:\n std::cerr << \"Unsupported PNM image type: P\" << std::to_string(static_cast(fmt)) << '\\n';\n width_ = 0;\n height_ = 0;\n format_ = PF_UNSPECIFIED;\n data_.resize(0);\n return false;\n\n case P6:\n assert(max_value < 256);\n assert(max_value == 255);\n format_ = PF_RGB8;\n data_.resize(width_ * height_ * 3);\n\n load_binary_rgb(\n data_.data(),\n file,\n width_,\n height_,\n max_value\n );\n return true;\n }\n\n return true;\n}\n\n}\nSupport for ascii-rgb ppm images (P3)\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if 1\/\/ndef NDEBUG\n#include \n#include \n#endif\n\n#include \n\n#include \"pnm_image.h\"\n\nnamespace visionaray\n{\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Helper functions\n\/\/\n\nstatic void load_ascii_rgb(\n uint8_t* dst,\n std::ifstream& file,\n size_t width,\n size_t height,\n int \/*max_value*\/\n )\n{\n\/\/ assert(max_value < 256); \/\/ TODO: 16-bit\n\/\/ assert(max_value == 255); \/\/ TODO: scaling\n\n for (size_t y = 0; y < height; ++y)\n {\n std::string line;\n std::getline(file, line);\n\n std::vector tokens;\n boost::algorithm::split(\n tokens,\n line,\n boost::algorithm::is_any_of(\" \\t\")\n );\n\n \/\/ Remove empty tokens and spaces\n tokens.erase(\n std::remove_if(\n tokens.begin(),\n tokens.end(),\n [](std::string str) { return str.empty() || std::isspace(str[0]); }\n ),\n tokens.end()\n );\n\n size_t pitch = width * 3;\n assert(tokens.size() == pitch);\n\n for (size_t x = 0; x < pitch; ++x)\n {\n dst[y * pitch + x] = static_cast(std::stoi(tokens[x]));\n }\n }\n}\n\nstatic void load_binary_rgb(\n uint8_t* dst,\n std::ifstream& file,\n size_t width,\n size_t height,\n int \/*max_value*\/\n )\n{\n\/\/ assert(max_value < 256); \/\/ TODO: 16-bit\n\/\/ assert(max_value == 255); \/\/ TODO: scaling\n\n size_t pitch = width * 3;\n file.read(reinterpret_cast(dst), pitch * height);\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ pnm_image\n\/\/\n\nbool pnm_image::load(std::string const& filename)\n{\n enum format { P1 = 1, P2, P3, P4, P5, P6 };\n\n std::ifstream file(filename);\n\n std::string line;\n\n \/\/\n \/\/ First line determines format:\n \/\/ P1: ASCII BW | P4: binary BW\n \/\/ P2: ASCII gray scale | P5: binary gray scale\n \/\/ P3: ASCII RGB | P6: binary RGB\n \/\/\n std::getline(file, line);\n\n if (line.size() < 2 || line[0] != 'P' || line[1] < '0' || line[1] > '6')\n {\n std::cerr << \"Invalid file format: \" << line << '\\n';\n return false;\n }\n\n format fmt = static_cast(line[1] - '0');\n\n \/\/ Width and height\n for (;;)\n {\n std::getline(file, line);\n\n if (line[0] == '#')\n {\n \/\/ Skip comments\n continue;\n }\n else\n {\n std::vector tokens;\n boost::algorithm::split(\n tokens,\n line,\n boost::algorithm::is_any_of(\" \\t\")\n );\n\n if (tokens.size() != 2)\n {\n std::cerr << \"Invalid dimensions\\n\";\n return false;\n }\n\n width_ = static_cast(std::stoi(tokens[0]));\n height_ = static_cast(std::stoi(tokens[1]));\n\n break;\n }\n }\n\n \/\/ Max. value\n int max_value = 255;\n if (fmt != P1 && fmt != P4)\n {\n for (;;)\n {\n std::getline(file, line);\n\n if (line[0] == '#')\n {\n \/\/ Skip comments\n continue;\n }\n else\n {\n max_value = std::stoi(line);\n break;\n }\n }\n }\n\n switch (fmt)\n {\n default:\n std::cerr << \"Unsupported PNM image type: P\" << std::to_string(static_cast(fmt)) << '\\n';\n width_ = 0;\n height_ = 0;\n format_ = PF_UNSPECIFIED;\n data_.resize(0);\n return false;\n\n case P3:\n assert(max_value < 256);\n assert(max_value == 255);\n format_ = PF_RGB8;\n data_.resize(width_ * height_ * 3);\n\n load_ascii_rgb(\n data_.data(),\n file,\n width_,\n height_,\n max_value\n );\n return true;\n\n case P6:\n assert(max_value < 256);\n assert(max_value == 255);\n format_ = PF_RGB8;\n data_.resize(width_ * height_ * 3);\n\n load_binary_rgb(\n data_.data(),\n file,\n width_,\n height_,\n max_value\n );\n return true;\n }\n\n return true;\n}\n\n}\n<|endoftext|>"} {"text":"\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef __RESOURCES_HPP__\n#define __RESOURCES_HPP__\n\n#include \n#include \n\n#include \n\n#include \"common\/foreach.hpp\"\n#include \"common\/option.hpp\"\n\n\n\/\/ Resources come in three types: scalar, ranges, and sets. These are\n\/\/ represented using protocol buffers. To make manipulation of\n\/\/ resources easier within the Mesos core we provide generic\n\/\/ overloaded opertors (see below) as well as a general Resources\n\/\/ class that encapsulates a collection of protocol buffer Resource\n\/\/ objects. The Resources class also provides a few static routines to\n\/\/ allow parsing resources (e.g., from the command line), as well as\n\/\/ determining whether or not a Resource object is valid or\n\/\/ allocatable. In particular, a scalar is allocatable if it's value\n\/\/ is greater than zero, a ranges is allocatable if there is at least\n\/\/ one valid range in it, and a set is allocatable if it has at least\n\/\/ one item. One can get only the allocatable resources by calling the\n\/\/ allocatable routine on a resources object. Note that many of these\n\/\/ operations have not been optimized but instead just written for\n\/\/ correct semantics.\n\n\n\/\/ Note! A resource is described by a tuple (name, type). Doing\n\/\/ \"arithmetic\" operations (those defined below) on two resources of\n\/\/ the same name but different type doesn't make sense, so it's\n\/\/ semantics are as though the second operand was actually just and\n\/\/ empty resource (as though you didn't do the operation at all). In\n\/\/ addition, doing operations on two resources of the same type but\n\/\/ different names is a no-op.\n\n\/\/ Parsing resources can be done via the Resources::parse\n\/\/ routines. The syntax currently requires that resources are\n\/\/ separated by semicolons, which means on the command line the option\n\/\/ needs to be quoted (whitespace is ignored). A scalar is just a\n\/\/ number, a range is described like \"[2-10, 34-56]\", and a set like\n\/\/ \"{a, b, c, d}\".\n\n\nnamespace mesos {\n\nbool operator == (const Value::Scalar& left, const Value::Scalar& right);\nbool operator <= (const Value::Scalar& left, const Value::Scalar& right);\nValue::Scalar operator + (const Value::Scalar& left, const Value::Scalar& right);\nValue::Scalar operator - (const Value::Scalar& left, const Value::Scalar& right);\nValue::Scalar& operator += (Value::Scalar& left, const Value::Scalar& right);\nValue::Scalar& operator -= (Value::Scalar& left, const Value::Scalar& right);\n\n\nbool operator == (const Value::Ranges& left, const Value::Ranges& right);\nbool operator <= (const Value::Ranges& left, const Value::Ranges& right);\nValue::Ranges operator + (const Value::Ranges& left, const Value::Ranges& right);\nValue::Ranges operator - (const Value::Ranges& left, const Value::Ranges& right);\nValue::Ranges& operator += (Value::Ranges& left, const Value::Ranges& right);\nValue::Ranges& operator -= (Value::Ranges& left, const Value::Ranges& right);\n\n\nbool operator == (const Value::Set& left, const Value::Set& right);\nbool operator <= (const Value::Set& left, const Value::Set& right);\nValue::Set operator + (const Value::Set& left, const Value::Set& right);\nValue::Set operator - (const Value::Set& left, const Value::Set& right);\nValue::Set& operator += (Value::Set& left, const Value::Set& right);\nValue::Set& operator -= (Value::Set& left, const Value::Set& right);\n\n\nbool operator == (const Resource& left, const Resource& right);\nbool operator <= (const Resource& left, const Resource& right);\nResource operator + (const Resource& left, const Resource& right);\nResource operator - (const Resource& left, const Resource& right);\nResource& operator += (Resource& left, const Resource& right);\nResource& operator -= (Resource& left, const Resource& right);\n\nstd::ostream& operator << (std::ostream& stream, const Resource& resource);\n\n\nnamespace internal {\n\nclass Resources\n{\npublic:\n Resources() {}\n\n Resources(const google::protobuf::RepeatedPtrField& _resources)\n {\n resources.MergeFrom(_resources);\n }\n\n Resources(const Resources& that)\n {\n resources.MergeFrom(that.resources);\n }\n\n Resources& operator = (const Resources& that)\n {\n if (this != &that) {\n resources.Clear();\n resources.MergeFrom(that.resources);\n }\n\n return *this;\n }\n\n \/\/ Returns a Resources object with only the allocatable resources.\n Resources allocatable() const\n {\n Resources result;\n\n foreach (const Resource& resource, resources) {\n if (isAllocatable(resource)) {\n result.resources.Add()->MergeFrom(resource);\n }\n }\n\n return result;\n }\n\n size_t size() const\n {\n return resources.size();\n }\n\n \/\/ Using this operator makes it easy to copy a resources object into\n \/\/ a protocol buffer field.\n operator const google::protobuf::RepeatedPtrField& () const\n {\n return resources;\n }\n\n bool operator == (const Resources& that) const\n {\n foreach (const Resource& resource, resources) {\n Option option = that.get(resource);\n if (option.isNone()) {\n return false;\n } else {\n if (!(resource == option.get())) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n bool operator <= (const Resources& that) const\n {\n foreach (const Resource& resource, resources) {\n Option option = that.get(resource);\n if (option.isNone()) {\n return false;\n } else {\n if (!(resource <= option.get())) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n Resources operator + (const Resources& that) const\n {\n Resources result(*this);\n\n foreach (const Resource& resource, that.resources) {\n result += resource;\n }\n\n return result;\n }\n\n Resources operator - (const Resources& that) const\n {\n Resources result(*this);\n\n foreach (const Resource& resource, that.resources) {\n result -= resource;\n }\n\n return result;\n }\n\n Resources& operator += (const Resources& that)\n {\n foreach (const Resource& resource, that.resources) {\n *this += resource;\n }\n\n return *this;\n }\n\n Resources& operator -= (const Resources& that)\n {\n foreach (const Resource& resource, that.resources) {\n *this -= resource;\n }\n\n return *this;\n }\n\n Resources operator + (const Resource& that) const\n {\n Resources result;\n\n bool added = false;\n\n foreach (const Resource& resource, resources) {\n if (resource.name() == that.name() &&\n\tresource.type() == that.type()) {\n result.resources.Add()->MergeFrom(resource + that);\n added = true;\n } else {\n result.resources.Add()->MergeFrom(resource);\n }\n }\n\n if (!added) {\n result.resources.Add()->MergeFrom(that);\n }\n\n return result;\n }\n\n Resources operator - (const Resource& that) const\n {\n Resources result;\n\n foreach (const Resource& resource, resources) {\n if (resource.name() == that.name() &&\n\tresource.type() == that.type()) {\n result.resources.Add()->MergeFrom(resource - that);\n } else {\n result.resources.Add()->MergeFrom(resource);\n }\n }\n\n return result;\n }\n\n Resources& operator += (const Resource& that)\n {\n *this = *this + that;\n return *this;\n }\n\n Resources& operator -= (const Resource& that)\n {\n *this = *this - that;\n return *this;\n }\n\n Option get(const Resource& r) const\n {\n foreach (const Resource& resource, resources) {\n if (resource.name() == r.name() &&\n resource.type() == r.type()) {\n return resource;\n }\n }\n\n return Option::none();\n }\n\n template \n T get(const std::string& name, const T& t) const;\n\n typedef google::protobuf::RepeatedPtrField::iterator\n iterator;\n\n typedef google::protobuf::RepeatedPtrField::const_iterator\n const_iterator;\n\n iterator begin() { return resources.begin(); }\n iterator end() { return resources.end(); }\n\n const_iterator begin() const { return resources.begin(); }\n const_iterator end() const { return resources.end(); }\n\n static Resource parse(const std::string& name, const std::string& value);\n static Resources parse(const std::string& s);\n\n static bool isValid(const Resource& resource)\n {\n if (!resource.has_name() ||\n resource.name() == \"\" ||\n !resource.has_type() ||\n !Value::Type_IsValid(resource.type())) {\n return false;\n }\n\n if (resource.type() == Value::SCALAR) {\n return resource.has_scalar();\n } else if (resource.type() == Value::RANGES) {\n return resource.has_ranges();\n } else if (resource.type() == Value::SET) {\n return resource.has_ranges();\n } else if (resource.type() == Value::TEXT) {\n \/\/ Resources doesn't support text.\n return false;\n }\n\n return false;\n }\n\n static bool isAllocatable(const Resource& resource)\n {\n if (isValid(resource)) {\n if (resource.type() == Value::SCALAR) {\n if (resource.scalar().value() <= 0) {\n return false;\n }\n } else if (resource.type() == Value::RANGES) {\n if (resource.ranges().range_size() == 0) {\n return false;\n } else {\n for (int i = 0; i < resource.ranges().range_size(); i++) {\n const Value::Range& range = resource.ranges().range(i);\n\n \/\/ Ensure the range make sense (isn't inverted).\n if (range.begin() > range.end()) {\n return false;\n }\n\n \/\/ Ensure ranges don't overlap (but not necessarily coalesced).\n for (int j = j + 1; j < resource.ranges().range_size(); j++) {\n if (range.begin() <= resource.ranges().range(j).begin() &&\n resource.ranges().range(j).begin() <= range.end()) {\n return false;\n }\n }\n }\n }\n } else if (resource.type() == Value::SET) {\n if (resource.set().item_size() == 0) {\n return false;\n } else {\n for (int i = 0; i < resource.set().item_size(); i++) {\n const std::string& item = resource.set().item(i);\n\n \/\/ Ensure no duplicates.\n for (int j = i + 1; j < resource.set().item_size(); j++) {\n if (item == resource.set().item(j)) {\n return false;\n }\n }\n }\n }\n }\n\n return true;\n }\n\n return false;\n }\n\nprivate:\n google::protobuf::RepeatedPtrField resources;\n};\n\n\ntemplate <>\ninline Value::Scalar Resources::get(\n const std::string& name,\n const Value::Scalar& scalar) const\n{\n foreach (const Resource& resource, resources) {\n if (resource.name() == name &&\n resource.type() == Value::SCALAR) {\n return resource.scalar();\n }\n }\n\n return scalar;\n}\n\n\ntemplate <>\ninline Value::Ranges Resources::get(\n const std::string& name,\n const Value::Ranges& ranges) const\n{\n foreach (const Resource& resource, resources) {\n if (resource.name() == name &&\n resource.type() == Value::RANGES) {\n return resource.ranges();\n }\n }\n\n return ranges;\n}\n\n\ntemplate <>\ninline Value::Set Resources::get(\n const std::string& name,\n const Value::Set& set) const\n{\n foreach (const Resource& resource, resources) {\n if (resource.name() == name &&\n resource.type() == Value::SET) {\n return resource.set();\n }\n }\n\n return set;\n}\n\n\ninline std::ostream& operator << (\n std::ostream& stream,\n const Resources& resources)\n{\n mesos::internal::Resources::const_iterator it = resources.begin();\n\n while (it != resources.end()) {\n stream << *it;\n if (++it != resources.end()) {\n stream << \"; \";\n }\n }\n\n return stream;\n}\n\n\ninline std::ostream& operator << (\n std::ostream& stream,\n const google::protobuf::RepeatedPtrField& resources)\n{\n return stream << Resources(resources);\n}\n\n\ninline Resources operator + (\n const google::protobuf::RepeatedPtrField& left,\n const Resources& right)\n{\n return Resources(left) + right;\n}\n\n\ninline Resources operator - (\n const google::protobuf::RepeatedPtrField& left,\n const Resources& right)\n{\n return Resources(left) - right;\n}\n\n\ninline bool operator == (\n const google::protobuf::RepeatedPtrField& left,\n const Resources& right)\n{\n return Resources(left) == right;\n}\n\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\n\n#endif \/\/ __RESOURCES_HPP__\nMinor fix for src\/common\/resources.hpp to deal with looping error (contributed by Charles Reiss).\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef __RESOURCES_HPP__\n#define __RESOURCES_HPP__\n\n#include \n#include \n\n#include \n\n#include \"common\/foreach.hpp\"\n#include \"common\/option.hpp\"\n\n\n\/\/ Resources come in three types: scalar, ranges, and sets. These are\n\/\/ represented using protocol buffers. To make manipulation of\n\/\/ resources easier within the Mesos core we provide generic\n\/\/ overloaded opertors (see below) as well as a general Resources\n\/\/ class that encapsulates a collection of protocol buffer Resource\n\/\/ objects. The Resources class also provides a few static routines to\n\/\/ allow parsing resources (e.g., from the command line), as well as\n\/\/ determining whether or not a Resource object is valid or\n\/\/ allocatable. In particular, a scalar is allocatable if it's value\n\/\/ is greater than zero, a ranges is allocatable if there is at least\n\/\/ one valid range in it, and a set is allocatable if it has at least\n\/\/ one item. One can get only the allocatable resources by calling the\n\/\/ allocatable routine on a resources object. Note that many of these\n\/\/ operations have not been optimized but instead just written for\n\/\/ correct semantics.\n\n\n\/\/ Note! A resource is described by a tuple (name, type). Doing\n\/\/ \"arithmetic\" operations (those defined below) on two resources of\n\/\/ the same name but different type doesn't make sense, so it's\n\/\/ semantics are as though the second operand was actually just and\n\/\/ empty resource (as though you didn't do the operation at all). In\n\/\/ addition, doing operations on two resources of the same type but\n\/\/ different names is a no-op.\n\n\/\/ Parsing resources can be done via the Resources::parse\n\/\/ routines. The syntax currently requires that resources are\n\/\/ separated by semicolons, which means on the command line the option\n\/\/ needs to be quoted (whitespace is ignored). A scalar is just a\n\/\/ number, a range is described like \"[2-10, 34-56]\", and a set like\n\/\/ \"{a, b, c, d}\".\n\n\nnamespace mesos {\n\nbool operator == (const Value::Scalar& left, const Value::Scalar& right);\nbool operator <= (const Value::Scalar& left, const Value::Scalar& right);\nValue::Scalar operator + (const Value::Scalar& left, const Value::Scalar& right);\nValue::Scalar operator - (const Value::Scalar& left, const Value::Scalar& right);\nValue::Scalar& operator += (Value::Scalar& left, const Value::Scalar& right);\nValue::Scalar& operator -= (Value::Scalar& left, const Value::Scalar& right);\n\n\nbool operator == (const Value::Ranges& left, const Value::Ranges& right);\nbool operator <= (const Value::Ranges& left, const Value::Ranges& right);\nValue::Ranges operator + (const Value::Ranges& left, const Value::Ranges& right);\nValue::Ranges operator - (const Value::Ranges& left, const Value::Ranges& right);\nValue::Ranges& operator += (Value::Ranges& left, const Value::Ranges& right);\nValue::Ranges& operator -= (Value::Ranges& left, const Value::Ranges& right);\n\n\nbool operator == (const Value::Set& left, const Value::Set& right);\nbool operator <= (const Value::Set& left, const Value::Set& right);\nValue::Set operator + (const Value::Set& left, const Value::Set& right);\nValue::Set operator - (const Value::Set& left, const Value::Set& right);\nValue::Set& operator += (Value::Set& left, const Value::Set& right);\nValue::Set& operator -= (Value::Set& left, const Value::Set& right);\n\n\nbool operator == (const Resource& left, const Resource& right);\nbool operator <= (const Resource& left, const Resource& right);\nResource operator + (const Resource& left, const Resource& right);\nResource operator - (const Resource& left, const Resource& right);\nResource& operator += (Resource& left, const Resource& right);\nResource& operator -= (Resource& left, const Resource& right);\n\nstd::ostream& operator << (std::ostream& stream, const Resource& resource);\n\n\nnamespace internal {\n\nclass Resources\n{\npublic:\n Resources() {}\n\n Resources(const google::protobuf::RepeatedPtrField& _resources)\n {\n resources.MergeFrom(_resources);\n }\n\n Resources(const Resources& that)\n {\n resources.MergeFrom(that.resources);\n }\n\n Resources& operator = (const Resources& that)\n {\n if (this != &that) {\n resources.Clear();\n resources.MergeFrom(that.resources);\n }\n\n return *this;\n }\n\n \/\/ Returns a Resources object with only the allocatable resources.\n Resources allocatable() const\n {\n Resources result;\n\n foreach (const Resource& resource, resources) {\n if (isAllocatable(resource)) {\n result.resources.Add()->MergeFrom(resource);\n }\n }\n\n return result;\n }\n\n size_t size() const\n {\n return resources.size();\n }\n\n \/\/ Using this operator makes it easy to copy a resources object into\n \/\/ a protocol buffer field.\n operator const google::protobuf::RepeatedPtrField& () const\n {\n return resources;\n }\n\n bool operator == (const Resources& that) const\n {\n foreach (const Resource& resource, resources) {\n Option option = that.get(resource);\n if (option.isNone()) {\n return false;\n } else {\n if (!(resource == option.get())) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n bool operator <= (const Resources& that) const\n {\n foreach (const Resource& resource, resources) {\n Option option = that.get(resource);\n if (option.isNone()) {\n return false;\n } else {\n if (!(resource <= option.get())) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n Resources operator + (const Resources& that) const\n {\n Resources result(*this);\n\n foreach (const Resource& resource, that.resources) {\n result += resource;\n }\n\n return result;\n }\n\n Resources operator - (const Resources& that) const\n {\n Resources result(*this);\n\n foreach (const Resource& resource, that.resources) {\n result -= resource;\n }\n\n return result;\n }\n\n Resources& operator += (const Resources& that)\n {\n foreach (const Resource& resource, that.resources) {\n *this += resource;\n }\n\n return *this;\n }\n\n Resources& operator -= (const Resources& that)\n {\n foreach (const Resource& resource, that.resources) {\n *this -= resource;\n }\n\n return *this;\n }\n\n Resources operator + (const Resource& that) const\n {\n Resources result;\n\n bool added = false;\n\n foreach (const Resource& resource, resources) {\n if (resource.name() == that.name() &&\n\tresource.type() == that.type()) {\n result.resources.Add()->MergeFrom(resource + that);\n added = true;\n } else {\n result.resources.Add()->MergeFrom(resource);\n }\n }\n\n if (!added) {\n result.resources.Add()->MergeFrom(that);\n }\n\n return result;\n }\n\n Resources operator - (const Resource& that) const\n {\n Resources result;\n\n foreach (const Resource& resource, resources) {\n if (resource.name() == that.name() &&\n\tresource.type() == that.type()) {\n result.resources.Add()->MergeFrom(resource - that);\n } else {\n result.resources.Add()->MergeFrom(resource);\n }\n }\n\n return result;\n }\n\n Resources& operator += (const Resource& that)\n {\n *this = *this + that;\n return *this;\n }\n\n Resources& operator -= (const Resource& that)\n {\n *this = *this - that;\n return *this;\n }\n\n Option get(const Resource& r) const\n {\n foreach (const Resource& resource, resources) {\n if (resource.name() == r.name() &&\n resource.type() == r.type()) {\n return resource;\n }\n }\n\n return Option::none();\n }\n\n template \n T get(const std::string& name, const T& t) const;\n\n typedef google::protobuf::RepeatedPtrField::iterator\n iterator;\n\n typedef google::protobuf::RepeatedPtrField::const_iterator\n const_iterator;\n\n iterator begin() { return resources.begin(); }\n iterator end() { return resources.end(); }\n\n const_iterator begin() const { return resources.begin(); }\n const_iterator end() const { return resources.end(); }\n\n static Resource parse(const std::string& name, const std::string& value);\n static Resources parse(const std::string& s);\n\n static bool isValid(const Resource& resource)\n {\n if (!resource.has_name() ||\n resource.name() == \"\" ||\n !resource.has_type() ||\n !Value::Type_IsValid(resource.type())) {\n return false;\n }\n\n if (resource.type() == Value::SCALAR) {\n return resource.has_scalar();\n } else if (resource.type() == Value::RANGES) {\n return resource.has_ranges();\n } else if (resource.type() == Value::SET) {\n return resource.has_ranges();\n } else if (resource.type() == Value::TEXT) {\n \/\/ Resources doesn't support text.\n return false;\n }\n\n return false;\n }\n\n static bool isAllocatable(const Resource& resource)\n {\n if (isValid(resource)) {\n if (resource.type() == Value::SCALAR) {\n if (resource.scalar().value() <= 0) {\n return false;\n }\n } else if (resource.type() == Value::RANGES) {\n if (resource.ranges().range_size() == 0) {\n return false;\n } else {\n for (int i = 0; i < resource.ranges().range_size(); i++) {\n const Value::Range& range = resource.ranges().range(i);\n\n \/\/ Ensure the range make sense (isn't inverted).\n if (range.begin() > range.end()) {\n return false;\n }\n\n \/\/ Ensure ranges don't overlap (but not necessarily coalesced).\n for (int j = i + 1; j < resource.ranges().range_size(); j++) {\n if (range.begin() <= resource.ranges().range(j).begin() &&\n resource.ranges().range(j).begin() <= range.end()) {\n return false;\n }\n }\n }\n }\n } else if (resource.type() == Value::SET) {\n if (resource.set().item_size() == 0) {\n return false;\n } else {\n for (int i = 0; i < resource.set().item_size(); i++) {\n const std::string& item = resource.set().item(i);\n\n \/\/ Ensure no duplicates.\n for (int j = i + 1; j < resource.set().item_size(); j++) {\n if (item == resource.set().item(j)) {\n return false;\n }\n }\n }\n }\n }\n\n return true;\n }\n\n return false;\n }\n\nprivate:\n google::protobuf::RepeatedPtrField resources;\n};\n\n\ntemplate <>\ninline Value::Scalar Resources::get(\n const std::string& name,\n const Value::Scalar& scalar) const\n{\n foreach (const Resource& resource, resources) {\n if (resource.name() == name &&\n resource.type() == Value::SCALAR) {\n return resource.scalar();\n }\n }\n\n return scalar;\n}\n\n\ntemplate <>\ninline Value::Ranges Resources::get(\n const std::string& name,\n const Value::Ranges& ranges) const\n{\n foreach (const Resource& resource, resources) {\n if (resource.name() == name &&\n resource.type() == Value::RANGES) {\n return resource.ranges();\n }\n }\n\n return ranges;\n}\n\n\ntemplate <>\ninline Value::Set Resources::get(\n const std::string& name,\n const Value::Set& set) const\n{\n foreach (const Resource& resource, resources) {\n if (resource.name() == name &&\n resource.type() == Value::SET) {\n return resource.set();\n }\n }\n\n return set;\n}\n\n\ninline std::ostream& operator << (\n std::ostream& stream,\n const Resources& resources)\n{\n mesos::internal::Resources::const_iterator it = resources.begin();\n\n while (it != resources.end()) {\n stream << *it;\n if (++it != resources.end()) {\n stream << \"; \";\n }\n }\n\n return stream;\n}\n\n\ninline std::ostream& operator << (\n std::ostream& stream,\n const google::protobuf::RepeatedPtrField& resources)\n{\n return stream << Resources(resources);\n}\n\n\ninline Resources operator + (\n const google::protobuf::RepeatedPtrField& left,\n const Resources& right)\n{\n return Resources(left) + right;\n}\n\n\ninline Resources operator - (\n const google::protobuf::RepeatedPtrField& left,\n const Resources& right)\n{\n return Resources(left) - right;\n}\n\n\ninline bool operator == (\n const google::protobuf::RepeatedPtrField& left,\n const Resources& right)\n{\n return Resources(left) == right;\n}\n\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\n\n#endif \/\/ __RESOURCES_HPP__\n<|endoftext|>"} {"text":"removing printf stops output is unparseable error<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright (c) 2013-2014 Baptiste Wicht.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n#include \n#include \n\n#include \"versioning.hpp\"\n#include \"budget_exception.hpp\"\n#include \"config.hpp\"\n\nnamespace {\n\nstd::string exec_command(const std::string& command) {\n std::stringstream output;\n\n char buffer[1024];\n\n FILE* stream = popen(command.c_str(), \"r\");\n\n while (fgets(buffer, 1024, stream) != NULL) {\n output << buffer;\n }\n\n pclose(stream);\n\n return output.str();\n}\n\n} \/\/end of anonymous namespace\n\nvoid budget::versioning_module::handle(const std::vector& args){\n if(args.size() == 1){\n std::cout << \"Missing subcommand\" << std::endl;\n } else {\n auto& subcommand = args[1];\n\n if(subcommand == \"save\"){\n std::cout << exec_command(\"git -C \" + budget_folder() + \" commit -a -m Update\" ) << std::endl;\n } else if(subcommand == \"sync\"){\n std::cout << exec_command(\"git -C \" + budget_folder() + \" pull\" ) << std::endl;\n std::cout << exec_command(\"git -C \" + budget_folder() + \" push\" ) << std::endl;\n } else {\n throw budget_exception(\"Invalid subcommand \\\"\" + subcommand + \"\\\"\");\n }\n }\n}\nUpdate functions of versioning\/\/=======================================================================\n\/\/ Copyright (c) 2013-2014 Baptiste Wicht.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n#include \n#include \n\n#include \"versioning.hpp\"\n#include \"budget_exception.hpp\"\n#include \"config.hpp\"\n\nnamespace {\n\nstd::string exec_command(const std::string& command) {\n std::stringstream output;\n\n char buffer[1024];\n\n FILE* stream = popen(command.c_str(), \"r\");\n\n while (fgets(buffer, 1024, stream) != NULL) {\n output << buffer;\n }\n\n pclose(stream);\n\n return output.str();\n}\n\n} \/\/end of anonymous namespace\n\nvoid budget::versioning_module::handle(const std::vector& args){\n if(args.size() == 1){\n std::cout << \"Missing subcommand\" << std::endl;\n } else {\n auto& subcommand = args[1];\n\n if(subcommand == \"save\"){\n std::cout << exec_command(\"git -C \" + budget_folder() + \" commit -a -m Update\" ) << std::endl;\n } else if(subcommand == \"sync\"){\n std::cout << exec_command(\"git -C \" + budget_folder() + \" commit -a -m Update\" ) << std::endl;\n std::cout << exec_command(\"git -C \" + budget_folder() + \" pull\" ) << std::endl;\n std::cout << exec_command(\"git -C \" + budget_folder() + \" push\" ) << std::endl;\n } else if(subcommand == \"pull\"){\n std::cout << exec_command(\"git -C \" + budget_folder() + \" pull\" ) << std::endl;\n } else if(subcommand == \"push\"){\n std::cout << exec_command(\"git -C \" + budget_folder() + \" push\" ) << std::endl;\n } else {\n throw budget_exception(\"Invalid subcommand \\\"\" + subcommand + \"\\\"\");\n }\n }\n}\n<|endoftext|>"} {"text":"\n\/\/ Qt includes\n#include \n#include \n#include \n#include \n#include \n\n\/\/ ctkDICOMCore includes\n#include \"ctkDICOM.h\"\n#include \"ctkDICOMModel.h\"\n#include \"ctkModelTester.h\"\n\n\/\/ STD includes\n#include \n\n\n\/* Test from build directory:\n .\/CTK-build\/bin\/CTKDICOMCoreCxxTests ctkDICOMModelTest1 test.db ..\/CTK\/Libs\/DICOM\/Core\/Resources\/dicom-sample.sql\n*\/\n\nint ctkDICOMModelTest1( int argc, char * argv [] )\n{\n QApplication app(argc, argv);\n \n if (argc <= 2)\n {\n std::cerr << \"Warning, no sql file given. Test stops\" << std::endl;\n std::cerr << \"Usage: qctkDICOMModelTest1 \" << std::endl;\n return EXIT_FAILURE;\n }\n \n ctkDICOM myCTK;\n try\n {\n myCTK.openDatabase( argv[1] );\n }\n catch (std::exception e)\n {\n std::cerr << \"Error when opening the data base file: \" << argv[1] \n << \" error: \" << e.what();\n return EXIT_FAILURE;\n }\n if (!myCTK.initializeDatabase(argv[2]))\n {\n std::cerr << \"Error when initializing the data base: \" << argv[2] \n << \" error: \" << myCTK.GetLastError().toStdString();\n }\n \/*\n QSqlQuery toto(\"SELECT PatientsName as 'Name tt' FROM Patients ORDER BY \\\"Name tt\\\" ASC\", myCTK.database());\n qDebug() << \"toto: \" << myCTK.GetLastError() ;\n qDebug()<< toto.seek(0) << myCTK.GetLastError();\n qDebug() << toto.value(0).toString() << myCTK.GetLastError();\n\n QSqlQuery titi(\"SELECT StudyID as UID, StudyDescription as Name, ModalitiesInStudy as Scan, StudyDate as Date, AccessionNumber as Number, ReferringPhysician as Institution, ReferringPhysician as Referrer, PerformingPysiciansName as Performer FROM Studies WHERE PatientsUID='14'\", myCTK.database());\n qDebug() << \"titi: \" << titi.seek(0) << myCTK.GetLastError();\n QSqlQuery tata(\"SELECT SeriesInstanceUID as UID, BodyPartExamined as Scan, SeriesDate as Date, AcquisitionNumber as Number FROM Series WHERE StudyInstanceUID='1.2.826.0.1.3680043.2.1125.1.73379483469717886505187028001198162'\", myCTK.database());\n qDebug() << \"tata: \" << tata.seek(0) << myCTK.GetLastError();\n QSqlQuery tutu(\"SELECT Filename as UID, Filename as Name, SeriesInstanceUID as Date FROM Images WHERE SeriesInstanceUID='%1'\", myCTK.database());\n qDebug() << \"tutu: \" << tutu.seek(0) << myCTK.GetLastError();\n *\/\n\n ctkModelTester tester;\n tester.setNestedInserts(true);\n tester.setThrowOnError(false);\n ctkDICOMModel model;\n tester.setModel(&model);\n\n model.setDatabase(myCTK.database());\n \n model.setDatabase(QSqlDatabase());\n \n model.setDatabase(myCTK.database());\n\n QTreeView viewer;\n viewer.setModel(&model);\n viewer.setSortingEnabled(true);\n\n model.rowCount();\n qDebug() << model.rowCount() << model.columnCount();\n qDebug() << model.index(0,0);\n viewer.show();\n \/\/return app.exec();\n return EXIT_SUCCESS;\n}\nAdd interaction for ctkDICOMModelTest1\n\/\/ Qt includes\n#include \n#include \n#include \n#include \n#include \n\n\/\/ ctkDICOMCore includes\n#include \"ctkDICOM.h\"\n#include \"ctkDICOMModel.h\"\n#include \"ctkModelTester.h\"\n\n\/\/ STD includes\n#include \n\n\n\/* Test from build directory:\n .\/CTK-build\/bin\/CTKDICOMCoreCxxTests ctkDICOMModelTest1 test.db ..\/CTK\/Libs\/DICOM\/Core\/Resources\/dicom-sample.sql\n*\/\n\nint ctkDICOMModelTest1( int argc, char * argv [] )\n{\n QApplication app(argc, argv);\n \n if (argc <= 2)\n {\n std::cerr << \"Warning, no sql file given. Test stops\" << std::endl;\n std::cerr << \"Usage: qctkDICOMModelTest1 \" << std::endl;\n return EXIT_FAILURE;\n }\n \n ctkDICOM myCTK;\n try\n {\n myCTK.openDatabase( argv[1] );\n }\n catch (std::exception e)\n {\n std::cerr << \"Error when opening the data base file: \" << argv[1] \n << \" error: \" << e.what();\n return EXIT_FAILURE;\n }\n if (!myCTK.initializeDatabase(argv[2]))\n {\n std::cerr << \"Error when initializing the data base: \" << argv[2] \n << \" error: \" << myCTK.GetLastError().toStdString();\n }\n \/*\n QSqlQuery toto(\"SELECT PatientsName as 'Name tt' FROM Patients ORDER BY \\\"Name tt\\\" ASC\", myCTK.database());\n qDebug() << \"toto: \" << myCTK.GetLastError() ;\n qDebug()<< toto.seek(0) << myCTK.GetLastError();\n qDebug() << toto.value(0).toString() << myCTK.GetLastError();\n\n QSqlQuery titi(\"SELECT StudyID as UID, StudyDescription as Name, ModalitiesInStudy as Scan, StudyDate as Date, AccessionNumber as Number, ReferringPhysician as Institution, ReferringPhysician as Referrer, PerformingPysiciansName as Performer FROM Studies WHERE PatientsUID='14'\", myCTK.database());\n qDebug() << \"titi: \" << titi.seek(0) << myCTK.GetLastError();\n QSqlQuery tata(\"SELECT SeriesInstanceUID as UID, BodyPartExamined as Scan, SeriesDate as Date, AcquisitionNumber as Number FROM Series WHERE StudyInstanceUID='1.2.826.0.1.3680043.2.1125.1.73379483469717886505187028001198162'\", myCTK.database());\n qDebug() << \"tata: \" << tata.seek(0) << myCTK.GetLastError();\n QSqlQuery tutu(\"SELECT Filename as UID, Filename as Name, SeriesInstanceUID as Date FROM Images WHERE SeriesInstanceUID='%1'\", myCTK.database());\n qDebug() << \"tutu: \" << tutu.seek(0) << myCTK.GetLastError();\n *\/\n\n ctkModelTester tester;\n tester.setNestedInserts(true);\n tester.setThrowOnError(false);\n ctkDICOMModel model;\n tester.setModel(&model);\n\n model.setDatabase(myCTK.database());\n \n model.setDatabase(QSqlDatabase());\n \n model.setDatabase(myCTK.database());\n\n QTreeView viewer;\n viewer.setModel(&model);\n viewer.setSortingEnabled(true);\n\n model.rowCount();\n qDebug() << model.rowCount() << model.columnCount();\n qDebug() << model.index(0,0);\n viewer.show();\n if (argc > 3 && QString(argv[3]) == \"-I\")\n {\n return app.exec();\n }\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"#include \n#include \"MediaPipelineImpl.hpp\"\n#include \"MediaObjectImpl.hpp\"\n#include \n#include \n#include \n#include \n#include \n\n#define GST_CAT_DEFAULT kurento_media_object_impl\nGST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);\n#define GST_DEFAULT_NAME \"KurentoMediaObjectImpl\"\n\nnamespace kurento\n{\n\nMediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config)\n{\n initialId = createId();\n this->config = config;\n}\n\nMediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config,\n std::shared_ptr< MediaObject > parent)\n{\n this->parent = parent;\n initialId = createId();\n this->config = config;\n}\n\nstd::shared_ptr\nMediaObjectImpl::getMediaPipeline ()\n{\n if (parent) {\n return std::dynamic_pointer_cast (parent)->getMediaPipeline();\n } else {\n return std::dynamic_pointer_cast (shared_from_this() );\n }\n}\n\nstd::string\nMediaObjectImpl::createId()\n{\n std::string uuid = generateUUID();\n\n if (parent) {\n std::shared_ptr pipeline;\n\n pipeline = std::dynamic_pointer_cast (getMediaPipeline() );\n return pipeline->getId() + \"\/\" +\n uuid;\n } else {\n return uuid;\n }\n}\n\nstd::string\nMediaObjectImpl::getName()\n{\n std::unique_lock lck (mutex);\n\n if (name.empty () ) {\n name = getId ();\n }\n\n return name;\n}\n\nstd::string\nMediaObjectImpl::getId()\n{\n std::unique_lock lck (mutex);\n\n if (id.empty () ) {\n id = this->getType () + \"_\" + this->initialId;\n }\n\n return id;\n}\n\nvoid\nMediaObjectImpl::setName (const std::string &name)\n{\n std::unique_lock lck (mutex);\n\n this->name = name;\n}\n\nstd::vector> MediaObjectImpl::getChilds ()\n{\n std::vector> childs;\n\n for (auto it : MediaSet::getMediaSet ()->getChilds (std::dynamic_pointer_cast\n (shared_from_this() ) ) ) {\n childs.push_back (it);\n }\n\n return childs;\n}\n\nMediaObjectImpl::StaticConstructor MediaObjectImpl::staticConstructor;\n\nMediaObjectImpl::StaticConstructor::StaticConstructor()\n{\n GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,\n GST_DEFAULT_NAME);\n}\n\n} \/* kurento *\/\nMediaObjectImpl: Set type at the end of the id#include \n#include \"MediaPipelineImpl.hpp\"\n#include \"MediaObjectImpl.hpp\"\n#include \n#include \n#include \n#include \n#include \n\n#define GST_CAT_DEFAULT kurento_media_object_impl\nGST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);\n#define GST_DEFAULT_NAME \"KurentoMediaObjectImpl\"\n\nnamespace kurento\n{\n\nMediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config)\n{\n initialId = createId();\n this->config = config;\n}\n\nMediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config,\n std::shared_ptr< MediaObject > parent)\n{\n this->parent = parent;\n initialId = createId();\n this->config = config;\n}\n\nstd::shared_ptr\nMediaObjectImpl::getMediaPipeline ()\n{\n if (parent) {\n return std::dynamic_pointer_cast (parent)->getMediaPipeline();\n } else {\n return std::dynamic_pointer_cast (shared_from_this() );\n }\n}\n\nstd::string\nMediaObjectImpl::createId()\n{\n std::string uuid = generateUUID();\n\n if (parent) {\n std::shared_ptr pipeline;\n\n pipeline = std::dynamic_pointer_cast (getMediaPipeline() );\n return pipeline->getId() + \"\/\" +\n uuid;\n } else {\n return uuid;\n }\n}\n\nstd::string\nMediaObjectImpl::getName()\n{\n std::unique_lock lck (mutex);\n\n if (name.empty () ) {\n name = getId ();\n }\n\n return name;\n}\n\nstd::string\nMediaObjectImpl::getId()\n{\n std::unique_lock lck (mutex);\n\n if (id.empty () ) {\n id = this->initialId + \"_\" + this->getType ();\n }\n\n return id;\n}\n\nvoid\nMediaObjectImpl::setName (const std::string &name)\n{\n std::unique_lock lck (mutex);\n\n this->name = name;\n}\n\nstd::vector> MediaObjectImpl::getChilds ()\n{\n std::vector> childs;\n\n for (auto it : MediaSet::getMediaSet ()->getChilds (std::dynamic_pointer_cast\n (shared_from_this() ) ) ) {\n childs.push_back (it);\n }\n\n return childs;\n}\n\nMediaObjectImpl::StaticConstructor MediaObjectImpl::staticConstructor;\n\nMediaObjectImpl::StaticConstructor::StaticConstructor()\n{\n GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,\n GST_DEFAULT_NAME);\n}\n\n} \/* kurento *\/\n<|endoftext|>"} {"text":"\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"slave\/paths.hpp\"\n\n#ifdef __linux__\n#include \"slave\/containerizer\/linux_launcher.hpp\"\n\n#include \"slave\/containerizer\/isolators\/filesystem\/linux.hpp\"\n#endif\n\n#include \"slave\/containerizer\/mesos\/containerizer.hpp\"\n\n#include \"tests\/flags.hpp\"\n#include \"tests\/mesos.hpp\"\n\n#include \"tests\/containerizer\/provisioner.hpp\"\n#include \"tests\/containerizer\/rootfs.hpp\"\n\nusing namespace process;\n\nusing std::string;\nusing std::vector;\n\nusing mesos::internal::slave::Fetcher;\nusing mesos::internal::slave::Launcher;\n#ifdef __linux__\nusing mesos::internal::slave::LinuxFilesystemIsolatorProcess;\nusing mesos::internal::slave::LinuxLauncher;\n#endif\nusing mesos::internal::slave::MesosContainerizer;\nusing mesos::internal::slave::Provisioner;\nusing mesos::internal::slave::Slave;\n\nusing mesos::slave::Isolator;\n\nnamespace mesos {\nnamespace internal {\nnamespace tests {\n\n#ifdef __linux__\nclass LinuxFilesystemIsolatorTest: public MesosTest\n{\npublic:\n \/\/ This helper creates a MesosContainerizer instance that uses the\n \/\/ LinuxFilesystemIsolator. The filesystem isolator takes a\n \/\/ TestProvisioner which provision APPC images by copying files from\n \/\/ the host filesystem.\n Try> createContainerizer(const slave::Flags& flags)\n {\n Try> rootfs =\n LinuxRootfs::create(path::join(os::getcwd(), \"rootfs\"));\n\n if (rootfs.isError()) {\n return Error(\"Failed to create LinuxRootfs: \" + rootfs.error());\n }\n\n \/\/ NOTE: TestProvisioner provisions APPC images.\n hashmap> provisioners;\n provisioners.put(\n Image::APPC,\n Owned(new TestProvisioner(rootfs.get().share())));\n\n Try _isolator =\n LinuxFilesystemIsolatorProcess::create(flags, provisioners);\n\n if (_isolator.isError()) {\n return Error(\n \"Failed to create LinuxFilesystemIsolatorProcess: \" +\n _isolator.error());\n }\n\n Owned isolator(_isolator.get());\n\n Try _launcher =\n LinuxLauncher::create(flags, isolator->namespaces().get().get());\n\n if (_launcher.isError()) {\n return Error(\"Failed to create LinuxLauncher: \" + _launcher.error());\n }\n\n Owned launcher(_launcher.get());\n\n return Owned(\n new MesosContainerizer(\n flags,\n true,\n &fetcher,\n launcher,\n {isolator}));\n }\n\n ContainerInfo createContainerInfo(\n const vector& volumes = vector(),\n bool hasImage = true)\n {\n ContainerInfo info;\n info.set_type(ContainerInfo::MESOS);\n\n if (hasImage) {\n info.mutable_mesos()->mutable_image()->set_type(Image::APPC);\n }\n\n foreach (const Volume& volume, volumes) {\n info.add_volumes()->CopyFrom(volume);\n }\n\n return info;\n }\n\nprivate:\n Fetcher fetcher;\n};\n\n\n\/\/ This test verifies that the root filesystem of the container is\n\/\/ properly changed to the one that's provisioned by the provisioner.\nTEST_F(LinuxFilesystemIsolatorTest, ROOT_ChangeRootFilesystem)\n{\n slave::Flags flags = CreateSlaveFlags();\n\n Try> containerizer = createContainerizer(flags);\n ASSERT_SOME(containerizer);\n\n ContainerID containerId;\n containerId.set_value(UUID::random().toString());\n\n ExecutorInfo executor = CREATE_EXECUTOR_INFO(\n \"test_executor\",\n \"[ ! -d '\" + os::getcwd() + \"' ]\");\n\n executor.mutable_container()->CopyFrom(createContainerInfo());\n\n string directory = path::join(os::getcwd(), \"sandbox\");\n ASSERT_SOME(os::mkdir(directory));\n\n Future launch = containerizer.get()->launch(\n containerId,\n executor,\n directory,\n None(),\n SlaveID(),\n PID(),\n false);\n\n \/\/ Wait for the launch to complete.\n AWAIT_READY(launch);\n\n \/\/ Wait on the container.\n Future wait =\n containerizer.get()->wait(containerId);\n\n AWAIT_READY(wait);\n\n \/\/ Check the executor exited correctly.\n EXPECT_TRUE(wait.get().has_status());\n EXPECT_EQ(0, wait.get().status());\n}\n\n\n\/\/ This test verifies that a volume with a relative host path is\n\/\/ properly created in the container's sandbox and is properly mounted\n\/\/ in the container's mount namespace.\nTEST_F(LinuxFilesystemIsolatorTest, ROOT_VolumeFromSandbox)\n{\n slave::Flags flags = CreateSlaveFlags();\n\n Try> containerizer = createContainerizer(flags);\n ASSERT_SOME(containerizer);\n\n ContainerID containerId;\n containerId.set_value(UUID::random().toString());\n\n ExecutorInfo executor = CREATE_EXECUTOR_INFO(\n \"test_executor\",\n \"echo abc > \/tmp\/file\");\n\n executor.mutable_container()->CopyFrom(createContainerInfo(\n {CREATE_VOLUME(\"\/tmp\", \"tmp\", Volume::RW)}));\n\n string directory = path::join(os::getcwd(), \"sandbox\");\n ASSERT_SOME(os::mkdir(directory));\n\n Future launch = containerizer.get()->launch(\n containerId,\n executor,\n directory,\n None(),\n SlaveID(),\n PID(),\n false);\n\n \/\/ Wait for the launch to complete.\n AWAIT_READY(launch);\n\n \/\/ Wait on the container.\n Future wait =\n containerizer.get()->wait(containerId);\n\n AWAIT_READY(wait);\n\n \/\/ Check the executor exited correctly.\n EXPECT_TRUE(wait.get().has_status());\n EXPECT_EQ(0, wait.get().status());\n\n EXPECT_SOME_EQ(\"abc\\n\", os::read(path::join(directory, \"tmp\", \"file\")));\n}\n\n\n\/\/ This test verifies that a volume with an absolute host path as\n\/\/ well as an absolute container path is properly mounted in the\n\/\/ container's mount namespace.\nTEST_F(LinuxFilesystemIsolatorTest, ROOT_VolumeFromHost)\n{\n slave::Flags flags = CreateSlaveFlags();\n\n Try> containerizer = createContainerizer(flags);\n ASSERT_SOME(containerizer);\n\n ContainerID containerId;\n containerId.set_value(UUID::random().toString());\n\n ExecutorInfo executor = CREATE_EXECUTOR_INFO(\n \"test_executor\",\n \"test -d \/tmp\/sandbox\");\n\n executor.mutable_container()->CopyFrom(createContainerInfo(\n {CREATE_VOLUME(\"\/tmp\", os::getcwd(), Volume::RW)}));\n\n string directory = path::join(os::getcwd(), \"sandbox\");\n ASSERT_SOME(os::mkdir(directory));\n\n Future launch = containerizer.get()->launch(\n containerId,\n executor,\n directory,\n None(),\n SlaveID(),\n PID(),\n false);\n\n \/\/ Wait for the launch to complete.\n AWAIT_READY(launch);\n\n \/\/ Wait on the container.\n Future wait =\n containerizer.get()->wait(containerId);\n\n AWAIT_READY(wait);\n\n \/\/ Check the executor exited correctly.\n EXPECT_TRUE(wait.get().has_status());\n EXPECT_EQ(0, wait.get().status());\n}\n\n\n\/\/ This test verifies that a volume with an absolute host path and a\n\/\/ relative container path is properly mounted in the container's\n\/\/ mount namespace. The mount point will be created in the sandbox.\nTEST_F(LinuxFilesystemIsolatorTest, ROOT_VolumeFromHostSandboxMountPoint)\n{\n slave::Flags flags = CreateSlaveFlags();\n\n Try> containerizer = createContainerizer(flags);\n ASSERT_SOME(containerizer);\n\n ContainerID containerId;\n containerId.set_value(UUID::random().toString());\n\n ExecutorInfo executor = CREATE_EXECUTOR_INFO(\n \"test_executor\",\n \"test -d mountpoint\/sandbox\");\n\n executor.mutable_container()->CopyFrom(createContainerInfo(\n {CREATE_VOLUME(\"mountpoint\", os::getcwd(), Volume::RW)}));\n\n string directory = path::join(os::getcwd(), \"sandbox\");\n ASSERT_SOME(os::mkdir(directory));\n\n Future launch = containerizer.get()->launch(\n containerId,\n executor,\n directory,\n None(),\n SlaveID(),\n PID(),\n false);\n\n \/\/ Wait for the launch to complete.\n AWAIT_READY(launch);\n\n \/\/ Wait on the container.\n Future wait =\n containerizer.get()->wait(containerId);\n\n AWAIT_READY(wait);\n\n \/\/ Check the executor exited correctly.\n EXPECT_TRUE(wait.get().has_status());\n EXPECT_EQ(0, wait.get().status());\n}\n\n\n\/\/ This test verifies that persistent volumes are properly mounted in\n\/\/ the container's root filesystem.\nTEST_F(LinuxFilesystemIsolatorTest, ROOT_PersistentVolume)\n{\n slave::Flags flags = CreateSlaveFlags();\n flags.work_dir = os::getcwd();\n\n Try> containerizer = createContainerizer(flags);\n ASSERT_SOME(containerizer);\n\n ContainerID containerId;\n containerId.set_value(UUID::random().toString());\n\n ExecutorInfo executor = CREATE_EXECUTOR_INFO(\n \"test_executor\",\n \"echo abc > volume\/file\");\n\n executor.add_resources()->CopyFrom(createPersistentVolume(\n Megabytes(32),\n \"test_role\",\n \"persistent_volume_id\",\n \"volume\"));\n\n executor.mutable_container()->CopyFrom(createContainerInfo());\n\n \/\/ Create a persistent volume.\n string volume = slave::paths::getPersistentVolumePath(\n os::getcwd(),\n \"test_role\",\n \"persistent_volume_id\");\n\n ASSERT_SOME(os::mkdir(volume));\n\n string directory = path::join(os::getcwd(), \"sandbox\");\n ASSERT_SOME(os::mkdir(directory));\n\n Future launch = containerizer.get()->launch(\n containerId,\n executor,\n directory,\n None(),\n SlaveID(),\n PID(),\n false);\n\n \/\/ Wait for the launch to complete.\n AWAIT_READY(launch);\n\n \/\/ Wait on the container.\n Future wait =\n containerizer.get()->wait(containerId);\n\n AWAIT_READY(wait);\n\n \/\/ Check the executor exited correctly.\n EXPECT_TRUE(wait.get().has_status());\n EXPECT_EQ(0, wait.get().status());\n\n EXPECT_SOME_EQ(\"abc\\n\", os::read(path::join(volume, \"file\")));\n}\n#endif \/\/ __linux__\n\n} \/\/ namespace tests {\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\nAdded a persistent volume test for linux filesystem isolator to test case where the container does not specify a root filesystem.\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"slave\/paths.hpp\"\n\n#ifdef __linux__\n#include \"slave\/containerizer\/linux_launcher.hpp\"\n\n#include \"slave\/containerizer\/isolators\/filesystem\/linux.hpp\"\n#endif\n\n#include \"slave\/containerizer\/mesos\/containerizer.hpp\"\n\n#include \"tests\/flags.hpp\"\n#include \"tests\/mesos.hpp\"\n\n#include \"tests\/containerizer\/provisioner.hpp\"\n#include \"tests\/containerizer\/rootfs.hpp\"\n\nusing namespace process;\n\nusing std::string;\nusing std::vector;\n\nusing mesos::internal::slave::Fetcher;\nusing mesos::internal::slave::Launcher;\n#ifdef __linux__\nusing mesos::internal::slave::LinuxFilesystemIsolatorProcess;\nusing mesos::internal::slave::LinuxLauncher;\n#endif\nusing mesos::internal::slave::MesosContainerizer;\nusing mesos::internal::slave::Provisioner;\nusing mesos::internal::slave::Slave;\n\nusing mesos::slave::Isolator;\n\nnamespace mesos {\nnamespace internal {\nnamespace tests {\n\n#ifdef __linux__\nclass LinuxFilesystemIsolatorTest: public MesosTest\n{\npublic:\n \/\/ This helper creates a MesosContainerizer instance that uses the\n \/\/ LinuxFilesystemIsolator. The filesystem isolator takes a\n \/\/ TestProvisioner which provision APPC images by copying files from\n \/\/ the host filesystem.\n Try> createContainerizer(const slave::Flags& flags)\n {\n Try> rootfs =\n LinuxRootfs::create(path::join(os::getcwd(), \"rootfs\"));\n\n if (rootfs.isError()) {\n return Error(\"Failed to create LinuxRootfs: \" + rootfs.error());\n }\n\n \/\/ NOTE: TestProvisioner provisions APPC images.\n hashmap> provisioners;\n provisioners.put(\n Image::APPC,\n Owned(new TestProvisioner(rootfs.get().share())));\n\n Try _isolator =\n LinuxFilesystemIsolatorProcess::create(flags, provisioners);\n\n if (_isolator.isError()) {\n return Error(\n \"Failed to create LinuxFilesystemIsolatorProcess: \" +\n _isolator.error());\n }\n\n Owned isolator(_isolator.get());\n\n Try _launcher =\n LinuxLauncher::create(flags, isolator->namespaces().get().get());\n\n if (_launcher.isError()) {\n return Error(\"Failed to create LinuxLauncher: \" + _launcher.error());\n }\n\n Owned launcher(_launcher.get());\n\n return Owned(\n new MesosContainerizer(\n flags,\n true,\n &fetcher,\n launcher,\n {isolator}));\n }\n\n ContainerInfo createContainerInfo(\n const vector& volumes = vector(),\n bool hasImage = true)\n {\n ContainerInfo info;\n info.set_type(ContainerInfo::MESOS);\n\n if (hasImage) {\n info.mutable_mesos()->mutable_image()->set_type(Image::APPC);\n }\n\n foreach (const Volume& volume, volumes) {\n info.add_volumes()->CopyFrom(volume);\n }\n\n return info;\n }\n\nprivate:\n Fetcher fetcher;\n};\n\n\n\/\/ This test verifies that the root filesystem of the container is\n\/\/ properly changed to the one that's provisioned by the provisioner.\nTEST_F(LinuxFilesystemIsolatorTest, ROOT_ChangeRootFilesystem)\n{\n slave::Flags flags = CreateSlaveFlags();\n\n Try> containerizer = createContainerizer(flags);\n ASSERT_SOME(containerizer);\n\n ContainerID containerId;\n containerId.set_value(UUID::random().toString());\n\n ExecutorInfo executor = CREATE_EXECUTOR_INFO(\n \"test_executor\",\n \"[ ! -d '\" + os::getcwd() + \"' ]\");\n\n executor.mutable_container()->CopyFrom(createContainerInfo());\n\n string directory = path::join(os::getcwd(), \"sandbox\");\n ASSERT_SOME(os::mkdir(directory));\n\n Future launch = containerizer.get()->launch(\n containerId,\n executor,\n directory,\n None(),\n SlaveID(),\n PID(),\n false);\n\n \/\/ Wait for the launch to complete.\n AWAIT_READY(launch);\n\n \/\/ Wait on the container.\n Future wait =\n containerizer.get()->wait(containerId);\n\n AWAIT_READY(wait);\n\n \/\/ Check the executor exited correctly.\n EXPECT_TRUE(wait.get().has_status());\n EXPECT_EQ(0, wait.get().status());\n}\n\n\n\/\/ This test verifies that a volume with a relative host path is\n\/\/ properly created in the container's sandbox and is properly mounted\n\/\/ in the container's mount namespace.\nTEST_F(LinuxFilesystemIsolatorTest, ROOT_VolumeFromSandbox)\n{\n slave::Flags flags = CreateSlaveFlags();\n\n Try> containerizer = createContainerizer(flags);\n ASSERT_SOME(containerizer);\n\n ContainerID containerId;\n containerId.set_value(UUID::random().toString());\n\n ExecutorInfo executor = CREATE_EXECUTOR_INFO(\n \"test_executor\",\n \"echo abc > \/tmp\/file\");\n\n executor.mutable_container()->CopyFrom(createContainerInfo(\n {CREATE_VOLUME(\"\/tmp\", \"tmp\", Volume::RW)}));\n\n string directory = path::join(os::getcwd(), \"sandbox\");\n ASSERT_SOME(os::mkdir(directory));\n\n Future launch = containerizer.get()->launch(\n containerId,\n executor,\n directory,\n None(),\n SlaveID(),\n PID(),\n false);\n\n \/\/ Wait for the launch to complete.\n AWAIT_READY(launch);\n\n \/\/ Wait on the container.\n Future wait =\n containerizer.get()->wait(containerId);\n\n AWAIT_READY(wait);\n\n \/\/ Check the executor exited correctly.\n EXPECT_TRUE(wait.get().has_status());\n EXPECT_EQ(0, wait.get().status());\n\n EXPECT_SOME_EQ(\"abc\\n\", os::read(path::join(directory, \"tmp\", \"file\")));\n}\n\n\n\/\/ This test verifies that a volume with an absolute host path as\n\/\/ well as an absolute container path is properly mounted in the\n\/\/ container's mount namespace.\nTEST_F(LinuxFilesystemIsolatorTest, ROOT_VolumeFromHost)\n{\n slave::Flags flags = CreateSlaveFlags();\n\n Try> containerizer = createContainerizer(flags);\n ASSERT_SOME(containerizer);\n\n ContainerID containerId;\n containerId.set_value(UUID::random().toString());\n\n ExecutorInfo executor = CREATE_EXECUTOR_INFO(\n \"test_executor\",\n \"test -d \/tmp\/sandbox\");\n\n executor.mutable_container()->CopyFrom(createContainerInfo(\n {CREATE_VOLUME(\"\/tmp\", os::getcwd(), Volume::RW)}));\n\n string directory = path::join(os::getcwd(), \"sandbox\");\n ASSERT_SOME(os::mkdir(directory));\n\n Future launch = containerizer.get()->launch(\n containerId,\n executor,\n directory,\n None(),\n SlaveID(),\n PID(),\n false);\n\n \/\/ Wait for the launch to complete.\n AWAIT_READY(launch);\n\n \/\/ Wait on the container.\n Future wait =\n containerizer.get()->wait(containerId);\n\n AWAIT_READY(wait);\n\n \/\/ Check the executor exited correctly.\n EXPECT_TRUE(wait.get().has_status());\n EXPECT_EQ(0, wait.get().status());\n}\n\n\n\/\/ This test verifies that a volume with an absolute host path and a\n\/\/ relative container path is properly mounted in the container's\n\/\/ mount namespace. The mount point will be created in the sandbox.\nTEST_F(LinuxFilesystemIsolatorTest, ROOT_VolumeFromHostSandboxMountPoint)\n{\n slave::Flags flags = CreateSlaveFlags();\n\n Try> containerizer = createContainerizer(flags);\n ASSERT_SOME(containerizer);\n\n ContainerID containerId;\n containerId.set_value(UUID::random().toString());\n\n ExecutorInfo executor = CREATE_EXECUTOR_INFO(\n \"test_executor\",\n \"test -d mountpoint\/sandbox\");\n\n executor.mutable_container()->CopyFrom(createContainerInfo(\n {CREATE_VOLUME(\"mountpoint\", os::getcwd(), Volume::RW)}));\n\n string directory = path::join(os::getcwd(), \"sandbox\");\n ASSERT_SOME(os::mkdir(directory));\n\n Future launch = containerizer.get()->launch(\n containerId,\n executor,\n directory,\n None(),\n SlaveID(),\n PID(),\n false);\n\n \/\/ Wait for the launch to complete.\n AWAIT_READY(launch);\n\n \/\/ Wait on the container.\n Future wait =\n containerizer.get()->wait(containerId);\n\n AWAIT_READY(wait);\n\n \/\/ Check the executor exited correctly.\n EXPECT_TRUE(wait.get().has_status());\n EXPECT_EQ(0, wait.get().status());\n}\n\n\n\/\/ This test verifies that persistent volumes are properly mounted in\n\/\/ the container's root filesystem.\nTEST_F(LinuxFilesystemIsolatorTest, ROOT_PersistentVolumeWithRootFilesystem)\n{\n slave::Flags flags = CreateSlaveFlags();\n flags.work_dir = os::getcwd();\n\n Try> containerizer = createContainerizer(flags);\n ASSERT_SOME(containerizer);\n\n ContainerID containerId;\n containerId.set_value(UUID::random().toString());\n\n ExecutorInfo executor = CREATE_EXECUTOR_INFO(\n \"test_executor\",\n \"echo abc > volume\/file\");\n\n executor.add_resources()->CopyFrom(createPersistentVolume(\n Megabytes(32),\n \"test_role\",\n \"persistent_volume_id\",\n \"volume\"));\n\n executor.mutable_container()->CopyFrom(createContainerInfo());\n\n \/\/ Create a persistent volume.\n string volume = slave::paths::getPersistentVolumePath(\n os::getcwd(),\n \"test_role\",\n \"persistent_volume_id\");\n\n ASSERT_SOME(os::mkdir(volume));\n\n string directory = path::join(os::getcwd(), \"sandbox\");\n ASSERT_SOME(os::mkdir(directory));\n\n Future launch = containerizer.get()->launch(\n containerId,\n executor,\n directory,\n None(),\n SlaveID(),\n PID(),\n false);\n\n \/\/ Wait for the launch to complete.\n AWAIT_READY(launch);\n\n \/\/ Wait on the container.\n Future wait =\n containerizer.get()->wait(containerId);\n\n AWAIT_READY(wait);\n\n \/\/ Check the executor exited correctly.\n EXPECT_TRUE(wait.get().has_status());\n EXPECT_EQ(0, wait.get().status());\n\n EXPECT_SOME_EQ(\"abc\\n\", os::read(path::join(volume, \"file\")));\n}\n\n\nTEST_F(LinuxFilesystemIsolatorTest, ROOT_PersistentVolumeWithoutRootFilesystem)\n{\n slave::Flags flags = CreateSlaveFlags();\n flags.work_dir = os::getcwd();\n\n Try> containerizer = createContainerizer(flags);\n ASSERT_SOME(containerizer);\n\n ContainerID containerId;\n containerId.set_value(UUID::random().toString());\n\n ExecutorInfo executor = CREATE_EXECUTOR_INFO(\n \"test_executor\",\n \"echo abc > volume\/file\");\n\n executor.add_resources()->CopyFrom(createPersistentVolume(\n Megabytes(32),\n \"test_role\",\n \"persistent_volume_id\",\n \"volume\"));\n\n executor.mutable_container()->CopyFrom(createContainerInfo({}, false));\n\n \/\/ Create a persistent volume.\n string volume = slave::paths::getPersistentVolumePath(\n os::getcwd(),\n \"test_role\",\n \"persistent_volume_id\");\n\n ASSERT_SOME(os::mkdir(volume));\n\n string directory = path::join(os::getcwd(), \"sandbox\");\n ASSERT_SOME(os::mkdir(directory));\n\n Future launch = containerizer.get()->launch(\n containerId,\n executor,\n directory,\n None(),\n SlaveID(),\n PID(),\n false);\n\n \/\/ Wait for the launch to complete.\n AWAIT_READY(launch);\n\n \/\/ Wait on the container.\n Future wait =\n containerizer.get()->wait(containerId);\n\n AWAIT_READY(wait);\n\n \/\/ Check the executor exited correctly.\n EXPECT_TRUE(wait.get().has_status());\n EXPECT_EQ(0, wait.get().status());\n\n EXPECT_SOME_EQ(\"abc\\n\", os::read(path::join(volume, \"file\")));\n}\n#endif \/\/ __linux__\n\n} \/\/ namespace tests {\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\n<|endoftext|>"} {"text":"\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team. For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n\n\/*\n** Condor Event Daemon: Take action for planned events in the Condor\n** pool, including scheduled reboots.\n*\/\n\n#include \"condor_common.h\"\n#include \"..\/condor_daemon_core.V6\/condor_daemon_core.h\"\n#include \"eventd.h\"\n\nconst char *mySubSystem = \"EVENTD\";\n\nint\nmain_init(int argc, char *argv[])\n{\n\tEventD->Config();\n\treturn TRUE;\n}\n\nint\nmain_config()\n{\n\tEventD->Config();\n\treturn TRUE;\n}\n\nint\nmain_shutdown_fast()\n{\n\tDC_Exit(0);\n}\n\nint\nmain_shutdown_graceful()\n{\n\tDC_Exit(0);\n}\nremove const from char *mysubsystem declaration, since condor_daemon_core.h doesn't have the const\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team. For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n\n\/*\n** Condor Event Daemon: Take action for planned events in the Condor\n** pool, including scheduled reboots.\n*\/\n\n#include \"condor_common.h\"\n#include \"..\/condor_daemon_core.V6\/condor_daemon_core.h\"\n#include \"eventd.h\"\n\nchar *mySubSystem = \"EVENTD\";\n\nint\nmain_init(int argc, char *argv[])\n{\n\tEventD->Config();\n\treturn TRUE;\n}\n\nint\nmain_config()\n{\n\tEventD->Config();\n\treturn TRUE;\n}\n\nint\nmain_shutdown_fast()\n{\n\tDC_Exit(0);\n}\n\nint\nmain_shutdown_graceful()\n{\n\tDC_Exit(0);\n}\n<|endoftext|>"} {"text":"\/\/ GetParentProcID.cpp : Defines the entry point for the console application.\r\n\/\/\r\n\r\n#include \"OgrePrerequisites.h\"\r\n#include \"OgreNsightChecker.h\"\r\n\r\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\r\n\r\n#include \r\n#include \r\n#include \r\n\r\n#pragma comment(lib,\"Psapi.lib\")\r\n\r\n\r\nstatic BOOL WINAPI GetParentPID(PROCESSENTRY32& procentry)\r\n{\r\n\tOSVERSIONINFO osver;\r\n\tHINSTANCE hInstLib;\r\n\tHANDLE hSnapShot;\r\n\tBOOL bContinue;\r\n\r\n\t\/\/ ToolHelp Function Pointers.\r\n\tHANDLE(WINAPI *lpfCreateToolhelp32Snapshot)(DWORD, DWORD);\r\n\tBOOL(WINAPI *lpfProcess32First)(HANDLE, LPPROCESSENTRY32);\r\n\tBOOL(WINAPI *lpfProcess32Next)(HANDLE, LPPROCESSENTRY32);\r\n\r\n\t\/\/ Check to see if were running under Windows95 or\r\n\t\/\/ Windows NT.\r\n\tosver.dwOSVersionInfoSize = sizeof(osver);\r\n\tif (!GetVersionEx(&osver))\r\n\t{\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\tif (osver.dwPlatformId != VER_PLATFORM_WIN32_NT)\r\n\t{\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\thInstLib = LoadLibraryA(\"Kernel32.DLL\");\r\n\tif (hInstLib == NULL)\r\n\t{\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\t\/\/ Get procedure addresses.\r\n\t\/\/ We are linking to these functions of Kernel32\r\n\t\/\/ explicitly, because otherwise a module using\r\n\t\/\/ this code would fail to load under Windows NT,\r\n\t\/\/ which does not have the Toolhelp32\r\n\t\/\/ functions in the Kernel 32.\r\n\tlpfCreateToolhelp32Snapshot =\r\n\t\t(HANDLE(WINAPI *)(DWORD, DWORD))\r\n\t\tGetProcAddress(hInstLib,\r\n\t\t\"CreateToolhelp32Snapshot\");\r\n\tlpfProcess32First =\r\n\t\t(BOOL(WINAPI *)(HANDLE, LPPROCESSENTRY32))\r\n\t\tGetProcAddress(hInstLib, \"Process32First\");\r\n\tlpfProcess32Next =\r\n\t\t(BOOL(WINAPI *)(HANDLE, LPPROCESSENTRY32))\r\n\t\tGetProcAddress(hInstLib, \"Process32Next\");\r\n\tif (lpfProcess32Next == NULL ||\r\n\t\tlpfProcess32First == NULL ||\r\n\t\tlpfCreateToolhelp32Snapshot == NULL)\r\n\t{\r\n\t\tFreeLibrary(hInstLib);\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\t\/\/ Get a handle to a Toolhelp snapshot of the systems\r\n\t\/\/ processes.\r\n\thSnapShot = lpfCreateToolhelp32Snapshot(\r\n\t\tTH32CS_SNAPPROCESS, 0);\r\n\tif (hSnapShot == INVALID_HANDLE_VALUE)\r\n\t{\r\n\t\tFreeLibrary(hInstLib);\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\t\/\/ Get the first process' information.\r\n\tmemset((LPVOID)&procentry, 0, sizeof(PROCESSENTRY32));\r\n\tprocentry.dwSize = sizeof(PROCESSENTRY32);\r\n\tbContinue = lpfProcess32First(hSnapShot, &procentry);\r\n\tDWORD pid = 0;\r\n\t\/\/ While there are processes, keep looping.\r\n\tDWORD crtpid = GetCurrentProcessId();\r\n\twhile (bContinue)\r\n\t{\r\n\t\tif (crtpid == procentry.th32ProcessID)\r\n\t\t\tpid = procentry.th32ParentProcessID;\r\n\r\n\t\tprocentry.dwSize = sizeof(PROCESSENTRY32);\r\n\t\tbContinue = !pid && lpfProcess32Next(hSnapShot, &procentry);\r\n\r\n\t}\/\/while ends\r\n\r\n\r\n\t\/\/ Free the library.\r\n\tFreeLibrary(hInstLib);\r\n\r\n\treturn pid ? TRUE : FALSE;\r\n}\r\n\r\n#ifdef _DEBUG\r\n#define PARENT \"msdev.exe\"\r\nconst DWORD TIMEOUT = 5000;\r\n#else\r\n#define PARENT \"idriver.exe\"\r\nconst DWORD TIMEOUT = 30000;\r\n#endif\r\n\r\nstatic std::string GetProcessFileName(DWORD processID)\r\n{\r\n\t\tstd::string result = \"\";\r\n\r\n\t\tHANDLE hProcess = OpenProcess(\r\n\t\t\tSYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,\r\n\t\t\tFALSE, processID);\r\n\t\tif (hProcess != NULL)\r\n\t\t{\r\n\t\t\t\/\/ Here we call EnumProcessModules to get only the\r\n\t\t\t\/\/ first module in the process this is important,\r\n\t\t\t\/\/ because this will be the .EXE module for which we\r\n\t\t\t\/\/ will retrieve the full path name in a second.\r\n\t\t\tHMODULE hMod;\r\n\t\t\tchar szFileName[MAX_PATH];\r\n\t\t\tDWORD dwSize2 = 0;\r\n\t\t\tLPTSTR pszName = NULL;\r\n\t\t\tif (EnumProcessModules(hProcess, &hMod,\r\n\t\t\t\tsizeof(hMod), &dwSize2))\r\n\t\t\t{\r\n\t\t\t\t\/\/ Get Full pathname:\r\n\r\n\t\t\t\tif (GetModuleFileNameEx(hProcess, hMod,\r\n\t\t\t\t\tszFileName, sizeof(szFileName)))\r\n\t\t\t\t\tresult = std::string(szFileName);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn result;\r\n}\r\n\r\nstatic bool IsWorkingUnderNsightImpl()\r\n{\r\n\tPROCESSENTRY32 selfprocentry;\r\n\tif(GetParentPID(selfprocentry))\r\n\t{\r\n\t\tstd::string parentFileName = GetProcessFileName(selfprocentry.th32ParentProcessID);\r\n\t\treturn parentFileName.find(\"Nsight.Monitor\") != std::string::npos;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\n#endif\r\n\r\nnamespace Ogre\r\n{\r\n\tbool IsWorkingUnderNsight()\r\n\t{\r\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\r\n\t\tstatic bool isWorkingUnderNsight = IsWorkingUnderNsightImpl();\r\n\t\treturn isWorkingUnderNsight;\r\n#else\r\n\t\treturn false;\r\n#endif\r\n\t}\r\n}Added: support to detect 64 bit versions of NVIDIA Nsight monitor (tweaked)\/\/ GetParentProcID.cpp : Defines the entry point for the console application.\r\n\/\/\r\n\r\n#include \"OgrePrerequisites.h\"\r\n#include \"OgreNsightChecker.h\"\r\n\r\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\r\n\r\n#include \r\n#include \r\n#include \r\n\r\n#pragma comment(lib,\"Psapi.lib\")\r\n\r\n\r\nstatic BOOL WINAPI GetParentPID(PROCESSENTRY32& procentry)\r\n{\r\n\tOSVERSIONINFO osver;\r\n\tHINSTANCE hInstLib;\r\n\tHANDLE hSnapShot;\r\n\tBOOL bContinue;\r\n\r\n\t\/\/ ToolHelp Function Pointers.\r\n\tHANDLE(WINAPI *lpfCreateToolhelp32Snapshot)(DWORD, DWORD);\r\n\tBOOL(WINAPI *lpfProcess32First)(HANDLE, LPPROCESSENTRY32);\r\n\tBOOL(WINAPI *lpfProcess32Next)(HANDLE, LPPROCESSENTRY32);\r\n\r\n\t\/\/ Check to see if were running under Windows95 or\r\n\t\/\/ Windows NT.\r\n\tosver.dwOSVersionInfoSize = sizeof(osver);\r\n\tif (!GetVersionEx(&osver))\r\n\t{\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\tif (osver.dwPlatformId != VER_PLATFORM_WIN32_NT)\r\n\t{\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\thInstLib = LoadLibraryA(\"Kernel32.DLL\");\r\n\tif (hInstLib == NULL)\r\n\t{\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\t\/\/ Get procedure addresses.\r\n\t\/\/ We are linking to these functions of Kernel32\r\n\t\/\/ explicitly, because otherwise a module using\r\n\t\/\/ this code would fail to load under Windows NT,\r\n\t\/\/ which does not have the Toolhelp32\r\n\t\/\/ functions in the Kernel 32.\r\n\tlpfCreateToolhelp32Snapshot =\r\n\t\t(HANDLE(WINAPI *)(DWORD, DWORD))\r\n\t\tGetProcAddress(hInstLib,\r\n\t\t\"CreateToolhelp32Snapshot\");\r\n\tlpfProcess32First =\r\n\t\t(BOOL(WINAPI *)(HANDLE, LPPROCESSENTRY32))\r\n\t\tGetProcAddress(hInstLib, \"Process32First\");\r\n\tlpfProcess32Next =\r\n\t\t(BOOL(WINAPI *)(HANDLE, LPPROCESSENTRY32))\r\n\t\tGetProcAddress(hInstLib, \"Process32Next\");\r\n\tif (lpfProcess32Next == NULL ||\r\n\t\tlpfProcess32First == NULL ||\r\n\t\tlpfCreateToolhelp32Snapshot == NULL)\r\n\t{\r\n\t\tFreeLibrary(hInstLib);\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\t\/\/ Get a handle to a Toolhelp snapshot of the systems\r\n\t\/\/ processes.\r\n\thSnapShot = lpfCreateToolhelp32Snapshot(\r\n\t\tTH32CS_SNAPPROCESS, 0);\r\n\tif (hSnapShot == INVALID_HANDLE_VALUE)\r\n\t{\r\n\t\tFreeLibrary(hInstLib);\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\t\/\/ Get the first process' information.\r\n\tmemset((LPVOID)&procentry, 0, sizeof(PROCESSENTRY32));\r\n\tprocentry.dwSize = sizeof(PROCESSENTRY32);\r\n\tbContinue = lpfProcess32First(hSnapShot, &procentry);\r\n\tDWORD pid = 0;\r\n\t\/\/ While there are processes, keep looping.\r\n\tDWORD crtpid = GetCurrentProcessId();\r\n\twhile (bContinue)\r\n\t{\r\n\t\tif (crtpid == procentry.th32ProcessID)\r\n\t\t\tpid = procentry.th32ParentProcessID;\r\n\r\n\t\tprocentry.dwSize = sizeof(PROCESSENTRY32);\r\n\t\tbContinue = !pid && lpfProcess32Next(hSnapShot, &procentry);\r\n\r\n\t}\/\/while ends\r\n\r\n\r\n\t\/\/ Free the library.\r\n\tFreeLibrary(hInstLib);\r\n\r\n\treturn pid ? TRUE : FALSE;\r\n}\r\n\r\nstatic std::string GetProcessFileName(DWORD processID)\r\n{\r\n char buffer[MAX_PATH] = \"\";\r\n\r\n HANDLE hProcess = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);\r\n if (hProcess != NULL)\r\n {\r\n if(0 == GetProcessImageFileName(hProcess, buffer, ARRAYSIZE(buffer)))\r\n buffer[0] = 0;\r\n\r\n CloseHandle(hProcess);\r\n }\r\n\r\n return buffer;\r\n}\r\n\r\nstatic bool IsWorkingUnderNsightImpl()\r\n{\r\n\tPROCESSENTRY32 selfprocentry;\r\n\tif(GetParentPID(selfprocentry))\r\n\t{\r\n\t\tstd::string parentFileName = GetProcessFileName(selfprocentry.th32ParentProcessID);\r\n\t\treturn parentFileName.find(\"Nsight.Monitor\") != std::string::npos;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\n#endif\r\n\r\nnamespace Ogre\r\n{\r\n\tbool IsWorkingUnderNsight()\r\n\t{\r\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\r\n\t\tstatic bool isWorkingUnderNsight = IsWorkingUnderNsightImpl();\r\n\t\treturn isWorkingUnderNsight;\r\n#else\r\n\t\treturn false;\r\n#endif\r\n\t}\r\n}<|endoftext|>"} {"text":"#include \"MeshManager.hpp\"\n\nusing namespace Rendering;\nusing namespace Device;\nusing namespace Core;\nusing namespace Rendering::Geometry;\nusing namespace Rendering::Manager;\nusing namespace Math;\n\nMesh& MeshManager::Acquire(Core::ObjectID objID)\n{\n\tauto mesh = Mesh(objID);\n\treturn GetOpaqueMeshPool().Add(mesh);\n}\n\nvoid MeshManager::Delete(Core::ObjectID objID)\n{\n\tGetOpaqueMeshPool().Delete(objID.Literal());\n\tGetAlphaBlendMeshPool().Delete(objID.Literal());\n\tGetTransparentMeshPool().Delete(objID.Literal());\n}\n\nbool MeshManager::Has(Core::ObjectID objID) const\n{\n\treturn\tGetOpaqueMeshPool().Has(objID.Literal())\t\t|\n\t\t\tGetAlphaBlendMeshPool().Has(objID.Literal())\t|\n\t\t\tGetTransparentMeshPool().Has(objID.Literal());\n}\n\nMesh* MeshManager::Find(Core::ObjectID id)\n{\n\tauto opaque = GetOpaqueMeshPool().Find(id.Literal());\n\tif (opaque) return opaque;\n\n\tauto alpha = GetAlphaBlendMeshPool().Find(id.Literal());\n\tif (alpha) return alpha;\n\n\tauto transparency = GetTransparentMeshPool().Find(id.Literal());\n\treturn transparency;\n}\n\nvoid MeshManager::CheckDirty(const Core::TransformPool& tfPool)\n{\n\tauto& dirty = _dirtyMeshes;\n\tauto Check = [&dirty, &tfPool](auto& pool)\n\t{\n\t\tpool.Iterate(\n\t\t\t[&dirty, &tfPool](Mesh& mesh)\n\t\t\t{\n\t\t\t\t\tauto tf = tfPool.Find(mesh.GetObjectID().Literal()); assert(tf);\n\n\t\t\t\t\tif (tf->GetDirty())\n\t\t\t\t\t\tdirty.push_back(&mesh);\n\t\t\t}\n\t\t);\n\t};\n\n\tCheck(GetOpaqueMeshPool());\n\tCheck(GetAlphaBlendMeshPool());\n\tCheck(GetTransparentMeshPool());\n}\n\nvoid MeshManager::ComputeWorldSize(\n\tVector3& refWorldMin, Vector3& refWorldMax,\n\tconst TransformPool& tfPool) const\n{\n\tauto Compute = [&refWorldMin, &refWorldMax, &tfPool](auto& vector)\n\t{\n\t\tfor (auto& iter : vector)\n\t\t{\n\t\t\tObjectID id = iter->GetObjectID();\n\n\t\t\tconst Transform* tf = tfPool.Find(id.Literal()); assert(tf);\n\t\t\titer->CalcWorldSize(refWorldMin, refWorldMax, *tf);\n\t\t}\n\t};\n\n\tCompute(_dirtyMeshes);\n}\n\nvoid MeshManager::UpdateTransformCB(DirectX& dx, const Core::TransformPool& tfPool)\n{\n\tauto Update = [&dx, &tfPool](auto& vector)\n\t{\t\t\n\t\tfor (auto& mesh : vector)\n\t\t{\n\t\t\tuint id = mesh->GetObjectID().Literal();\n\t\t\t\n\t\t\tconst Transform* tf = tfPool.Find(id); assert(tf);\n\t\t\tmesh->UpdateTransformCB(dx, *tf);\n\t\t}\n\t};\n\n\tUpdate(_dirtyMeshes);\n}MeshManager.cpp - Acquire(Core::ObjectID objID) -> Add(Mesh& mesh)#include \"MeshManager.hpp\"\n\nusing namespace Rendering;\nusing namespace Device;\nusing namespace Core;\nusing namespace Rendering::Geometry;\nusing namespace Rendering::Manager;\nusing namespace Math;\n\nMesh& MeshManager::Add(Mesh& mesh)\n{\n\tassert(mesh.GetVBKey() != 0); \/\/Error, mesh does not init yet.\n\treturn GetOpaqueMeshPool().Add(mesh.GetObjectID(), mesh.GetVBKey(), mesh);\n}\n\nvoid MeshManager::Delete(Core::ObjectID objID)\n{\n\tGetOpaqueMeshPool().Delete(objID.Literal());\n\tGetAlphaBlendMeshPool().Delete(objID.Literal());\n\tGetTransparentMeshPool().Delete(objID.Literal());\n}\n\nbool MeshManager::Has(Core::ObjectID objID) const\n{\n\treturn\tGetOpaqueMeshPool().Has(objID.Literal())\t\t|\n\t\t\tGetAlphaBlendMeshPool().Has(objID.Literal())\t|\n\t\t\tGetTransparentMeshPool().Has(objID.Literal());\n}\n\nMesh* MeshManager::Find(Core::ObjectID id)\n{\n\tauto opaque = GetOpaqueMeshPool().Find(id.Literal());\n\tif (opaque) return opaque;\n\n\tauto alpha = GetAlphaBlendMeshPool().Find(id.Literal());\n\tif (alpha) return alpha;\n\n\tauto transparency = GetTransparentMeshPool().Find(id.Literal());\n\treturn transparency;\n}\n\nvoid MeshManager::CheckDirty(const Core::TransformPool& tfPool)\n{\n\tauto& dirty = _dirtyMeshes;\n\tauto Check = [&dirty, &tfPool](auto& pool)\n\t{\n\t\tpool.Iterate(\n\t\t\t[&dirty, &tfPool](Mesh& mesh)\n\t\t\t{\n\t\t\t\t\tauto tf = tfPool.Find(mesh.GetObjectID().Literal()); assert(tf);\n\n\t\t\t\t\tif (tf->GetDirty())\n\t\t\t\t\t\tdirty.push_back(&mesh);\n\t\t\t}\n\t\t);\n\t};\n\n\tCheck(GetOpaqueMeshPool());\n\tCheck(GetAlphaBlendMeshPool());\n\tCheck(GetTransparentMeshPool());\n}\n\nvoid MeshManager::ComputeWorldSize(\n\tVector3& refWorldMin, Vector3& refWorldMax,\n\tconst TransformPool& tfPool) const\n{\n\tauto Compute = [&refWorldMin, &refWorldMax, &tfPool](auto& vector)\n\t{\n\t\tfor (auto& iter : vector)\n\t\t{\n\t\t\tObjectID id = iter->GetObjectID();\n\n\t\t\tconst Transform* tf = tfPool.Find(id.Literal()); assert(tf);\n\t\t\titer->CalcWorldSize(refWorldMin, refWorldMax, *tf);\n\t\t}\n\t};\n\n\tCompute(_dirtyMeshes);\n}\n\nvoid MeshManager::UpdateTransformCB(DirectX& dx, const Core::TransformPool& tfPool)\n{\n\tauto Update = [&dx, &tfPool](auto& vector)\n\t{\t\t\n\t\tfor (auto& mesh : vector)\n\t\t{\n\t\t\tuint id = mesh->GetObjectID().Literal();\n\t\t\t\n\t\t\tconst Transform* tf = tfPool.Find(id); assert(tf);\n\t\t\tmesh->UpdateTransformCB(dx, *tf);\n\t\t}\n\t};\n\n\tUpdate(_dirtyMeshes);\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkRIBProperty.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkRIBProperty.h\"\n\nvtkRIBProperty::vtkRIBProperty ()\n{\n this->Declarations = NULL;\n this->Parameters = NULL;\n this->SurfaceShader = NULL;\n this->DisplacementShader = NULL;\n}\n\nvtkRIBProperty::~vtkRIBProperty()\n{\n if (this->SurfaceShader) delete [] this->SurfaceShader;\n if (this->DisplacementShader) delete [] this->DisplacementShader;\n if (this->Declarations) delete [] this->Declarations;\n}\n\nvoid vtkRIBProperty::SetVariable (char *variable, char *value)\n{\n if (this->Declarations) delete [] this->Declarations;\n\n \/\/ format of line is: Declare \"variable\" \"type\"\\n\n this->Declarations = new char [strlen (\"Declare \") +\n\t strlen (variable) +\n\t\t\t strlen (value) + \n\t\t\t 8];\n\n sprintf (this->Declarations, \"Declare \\\"%s\\\" \\\"%s\\\"\\n\", variable, value);\n this->Modified ();\n}\n\nvoid vtkRIBProperty::AddVariable (char *variable, char *value)\n{\n if (this->Declarations == NULL)\n {\n this->SetVariable (variable, value);\n }\n else\n {\n char *newVariable = new char [strlen (\"Declare \") +\n\t strlen (variable) +\n\t\t \t strlen (value) + \n\t\t\t 8];\n\n sprintf (newVariable, \"Declare \\\"%s\\\" \\\"%s\\\"\\n\", variable, value);\n char *oldDeclarations = this->Declarations;\n\n this->Declarations = new char [strlen (oldDeclarations) + strlen (newVariable) + 1];\n strcpy (this->Declarations, oldDeclarations);\n strcat (this->Declarations, newVariable);\n delete [] oldDeclarations;\n this->Modified ();\n }\n}\n\nvoid vtkRIBProperty::SetParameter (char *parameter, char *value)\n{\n if (this->Parameters) delete [] this->Parameters;\n\n \/\/ format of line is: \"parameter\" \"value\"\n this->Parameters = new char [strlen (parameter) +\n\t\t\t strlen (value) + \n\t\t\t 7];\n\n sprintf (this->Parameters, \" \\\"%s\\\" [%s]\", parameter, value);\n this->Modified ();\n}\n\nvoid vtkRIBProperty::AddParameter (char *Parameter, char *value)\n{\n if (this->Parameters == NULL)\n {\n this->SetParameter (Parameter, value);\n }\n else\n {\n char *newParameter = new char [strlen (Parameter) +\n\t\t \t strlen (value) + \n\t\t\t 7];\n\n sprintf (newParameter, \" \\\"%s\\\" [%s]\", Parameter, value);\n char *oldParameters = this->Parameters;\n\n this->Parameters = new char [strlen (oldParameters) + strlen (newParameter) + 1];\n strcpy (this->Parameters, oldParameters);\n strcat (this->Parameters, newParameter);\n delete [] oldParameters;\n this->Modified ();\n }\n}\n\nchar *vtkRIBProperty::GetParameters ()\n{\n return this->Parameters;\n}\n\nchar *vtkRIBProperty::GetDeclarations ()\n{\n return this->Declarations;\n}\n\nvoid vtkRIBProperty::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkProperty::PrintSelf(os,indent);\n \n os << indent << \"SurfaceShader: \" << this->SurfaceShader << \"\\n\";\n os << indent << \"DisplacementShader: \" << this->SurfaceShader << \"\\n\";\n os << indent << \"Declarations: \" << this->Declarations << \"\\n\";\n os << indent << \"Parameters: \" << this->Parameters << \"\\n\";\n}\n\nENH: SurfaceShader=\"plastic\" is default.\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkRIBProperty.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkRIBProperty.h\"\n\nvtkRIBProperty::vtkRIBProperty ()\n{\n this->Declarations = NULL;\n this->Parameters = NULL;\n this->SurfaceShader = new char[strlen(\"plastic\") + 1];\n strcpy (this->SurfaceShader, \"plastic\");\n this->DisplacementShader = NULL;\n}\n\nvtkRIBProperty::~vtkRIBProperty()\n{\n if (this->SurfaceShader) delete [] this->SurfaceShader;\n if (this->DisplacementShader) delete [] this->DisplacementShader;\n if (this->Declarations) delete [] this->Declarations;\n}\n\nvoid vtkRIBProperty::SetVariable (char *variable, char *value)\n{\n if (this->Declarations) delete [] this->Declarations;\n\n \/\/ format of line is: Declare \"variable\" \"type\"\\n\n this->Declarations = new char [strlen (\"Declare \") +\n\t strlen (variable) +\n\t\t\t strlen (value) + \n\t\t\t 8];\n\n sprintf (this->Declarations, \"Declare \\\"%s\\\" \\\"%s\\\"\\n\", variable, value);\n this->Modified ();\n}\n\nvoid vtkRIBProperty::AddVariable (char *variable, char *value)\n{\n if (this->Declarations == NULL)\n {\n this->SetVariable (variable, value);\n }\n else\n {\n char *newVariable = new char [strlen (\"Declare \") +\n\t strlen (variable) +\n\t\t \t strlen (value) + \n\t\t\t 8];\n\n sprintf (newVariable, \"Declare \\\"%s\\\" \\\"%s\\\"\\n\", variable, value);\n char *oldDeclarations = this->Declarations;\n\n this->Declarations = new char [strlen (oldDeclarations) + strlen (newVariable) + 1];\n strcpy (this->Declarations, oldDeclarations);\n strcat (this->Declarations, newVariable);\n delete [] oldDeclarations;\n this->Modified ();\n }\n}\n\nvoid vtkRIBProperty::SetParameter (char *parameter, char *value)\n{\n if (this->Parameters) delete [] this->Parameters;\n\n \/\/ format of line is: \"parameter\" \"value\"\n this->Parameters = new char [strlen (parameter) +\n\t\t\t strlen (value) + \n\t\t\t 7];\n\n sprintf (this->Parameters, \" \\\"%s\\\" [%s]\", parameter, value);\n this->Modified ();\n}\n\nvoid vtkRIBProperty::AddParameter (char *Parameter, char *value)\n{\n if (this->Parameters == NULL)\n {\n this->SetParameter (Parameter, value);\n }\n else\n {\n char *newParameter = new char [strlen (Parameter) +\n\t\t \t strlen (value) + \n\t\t\t 7];\n\n sprintf (newParameter, \" \\\"%s\\\" [%s]\", Parameter, value);\n char *oldParameters = this->Parameters;\n\n this->Parameters = new char [strlen (oldParameters) + strlen (newParameter) + 1];\n strcpy (this->Parameters, oldParameters);\n strcat (this->Parameters, newParameter);\n delete [] oldParameters;\n this->Modified ();\n }\n}\n\nchar *vtkRIBProperty::GetParameters ()\n{\n return this->Parameters;\n}\n\nchar *vtkRIBProperty::GetDeclarations ()\n{\n return this->Declarations;\n}\n\nvoid vtkRIBProperty::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkProperty::PrintSelf(os,indent);\n \n os << indent << \"SurfaceShader: \" << this->SurfaceShader << \"\\n\";\n os << indent << \"DisplacementShader: \" << this->SurfaceShader << \"\\n\";\n os << indent << \"Declarations: \" << this->Declarations << \"\\n\";\n os << indent << \"Parameters: \" << this->Parameters << \"\\n\";\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2012 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#include \"core\/platform\/graphics\/GraphicsLayer.h\"\n\n#include \"core\/platform\/ScrollableArea.h\"\n#include \"core\/platform\/graphics\/transforms\/Matrix3DTransformOperation.h\"\n#include \"core\/platform\/graphics\/transforms\/RotateTransformOperation.h\"\n#include \"core\/platform\/graphics\/transforms\/TranslateTransformOperation.h\"\n#include \"wtf\/PassOwnPtr.h\"\n\n#include \n#include \"public\/platform\/Platform.h\"\n#include \"public\/platform\/WebCompositorSupport.h\"\n#include \"public\/platform\/WebFloatAnimationCurve.h\"\n#include \"public\/platform\/WebGraphicsContext3D.h\"\n#include \"public\/platform\/WebLayer.h\"\n#include \"public\/platform\/WebLayerTreeView.h\"\n#include \"public\/platform\/WebUnitTestSupport.h\"\n\nusing namespace WebCore;\nusing namespace WebKit;\n\nnamespace {\n\nclass MockGraphicsLayerClient : public GraphicsLayerClient {\npublic:\n virtual void notifyAnimationStarted(const GraphicsLayer*, double time) OVERRIDE { }\n virtual void paintContents(const GraphicsLayer*, GraphicsContext&, GraphicsLayerPaintingPhase, const IntRect& inClip) OVERRIDE { }\n};\n\nclass GraphicsLayerForTesting : public GraphicsLayer {\npublic:\n explicit GraphicsLayerForTesting(GraphicsLayerClient* client)\n : GraphicsLayer(client) { };\n};\n\nclass GraphicsLayerTest : public testing::Test {\npublic:\n GraphicsLayerTest()\n {\n m_graphicsLayer = adoptPtr(new GraphicsLayerForTesting(&m_client));\n m_platformLayer = m_graphicsLayer->platformLayer();\n m_layerTreeView = adoptPtr(Platform::current()->unitTestSupport()->createLayerTreeViewForTesting(WebUnitTestSupport::TestViewTypeUnitTest));\n ASSERT(m_layerTreeView);\n m_layerTreeView->setRootLayer(*m_platformLayer);\n m_layerTreeView->setViewportSize(WebSize(1, 1), WebSize(1, 1));\n }\n\n virtual ~GraphicsLayerTest()\n {\n m_graphicsLayer.clear();\n m_layerTreeView.clear();\n }\n\nprotected:\n WebLayer* m_platformLayer;\n OwnPtr m_graphicsLayer;\n\nprivate:\n OwnPtr m_layerTreeView;\n MockGraphicsLayerClient m_client;\n};\n\nTEST_F(GraphicsLayerTest, updateLayerPreserves3DWithAnimations)\n{\n ASSERT_FALSE(m_platformLayer->hasActiveAnimation());\n\n OwnPtr curve = adoptPtr(Platform::current()->compositorSupport()->createFloatAnimationCurve());\n curve->add(WebFloatKeyframe(0.0, 0.0));\n OwnPtr floatAnimation(adoptPtr(Platform::current()->compositorSupport()->createAnimation(*curve, WebAnimation::TargetPropertyOpacity)));\n int animationId = floatAnimation->id();\n ASSERT_TRUE(m_platformLayer->addAnimation(floatAnimation.get()));\n\n ASSERT_TRUE(m_platformLayer->hasActiveAnimation());\n\n m_graphicsLayer->setPreserves3D(true);\n\n m_platformLayer = m_graphicsLayer->platformLayer();\n ASSERT_TRUE(m_platformLayer);\n\n ASSERT_TRUE(m_platformLayer->hasActiveAnimation());\n m_platformLayer->removeAnimation(animationId);\n ASSERT_FALSE(m_platformLayer->hasActiveAnimation());\n\n m_graphicsLayer->setPreserves3D(false);\n\n m_platformLayer = m_graphicsLayer->platformLayer();\n ASSERT_TRUE(m_platformLayer);\n\n ASSERT_FALSE(m_platformLayer->hasActiveAnimation());\n}\n\nclass FakeScrollableArea : public ScrollableArea {\npublic:\n virtual bool isActive() const OVERRIDE { return false; }\n virtual int scrollSize(ScrollbarOrientation) const OVERRIDE { return 100; }\n virtual int scrollPosition(Scrollbar*) const OVERRIDE { return 0; }\n virtual bool isScrollCornerVisible() const OVERRIDE { return false; }\n virtual IntRect scrollCornerRect() const OVERRIDE { return IntRect(); }\n virtual int visibleWidth() const OVERRIDE { return 10; }\n virtual int visibleHeight() const OVERRIDE { return 10; }\n virtual IntSize contentsSize() const OVERRIDE { return IntSize(100, 100); }\n virtual bool scrollbarsCanBeActive() const OVERRIDE { return false; }\n virtual ScrollableArea* enclosingScrollableArea() const OVERRIDE { return 0; }\n virtual IntRect scrollableAreaBoundingBox() const OVERRIDE { return IntRect(); }\n virtual void invalidateScrollbarRect(Scrollbar*, const IntRect&) OVERRIDE { }\n virtual void invalidateScrollCornerRect(const IntRect&) OVERRIDE { }\n\n virtual void setScrollOffset(const IntPoint& scrollOffset) OVERRIDE { m_scrollPosition = scrollOffset; }\n virtual IntPoint scrollPosition() const OVERRIDE { return m_scrollPosition; }\n\nprivate:\n IntPoint m_scrollPosition;\n};\n\nTEST_F(GraphicsLayerTest, applyScrollToScrollableArea)\n{\n FakeScrollableArea scrollableArea;\n m_graphicsLayer->setScrollableArea(&scrollableArea);\n\n WebPoint scrollPosition(7, 9);\n m_platformLayer->setScrollPosition(scrollPosition);\n\n EXPECT_EQ(scrollPosition, WebPoint(scrollableArea.scrollPosition()));\n}\n\nTEST_F(GraphicsLayerTest, DISABLED_setContentsToSolidColor)\n{\n m_graphicsLayer->setContentsToSolidColor(Color::transparent);\n EXPECT_FALSE(m_graphicsLayer->contentsLayer());\n\n m_graphicsLayer->setContentsToSolidColor(Color::white);\n EXPECT_TRUE(m_graphicsLayer->contentsLayer());\n\n m_graphicsLayer->setContentsToSolidColor(Color());\n EXPECT_FALSE(m_graphicsLayer->contentsLayer());\n}\n\n} \/\/ namespace\nDisable GraphicsLayerTest.applyScrollToScrollableArea which broke after r204442\/*\n * Copyright (C) 2012 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#include \"core\/platform\/graphics\/GraphicsLayer.h\"\n\n#include \"core\/platform\/ScrollableArea.h\"\n#include \"core\/platform\/graphics\/transforms\/Matrix3DTransformOperation.h\"\n#include \"core\/platform\/graphics\/transforms\/RotateTransformOperation.h\"\n#include \"core\/platform\/graphics\/transforms\/TranslateTransformOperation.h\"\n#include \"wtf\/PassOwnPtr.h\"\n\n#include \n#include \"public\/platform\/Platform.h\"\n#include \"public\/platform\/WebCompositorSupport.h\"\n#include \"public\/platform\/WebFloatAnimationCurve.h\"\n#include \"public\/platform\/WebGraphicsContext3D.h\"\n#include \"public\/platform\/WebLayer.h\"\n#include \"public\/platform\/WebLayerTreeView.h\"\n#include \"public\/platform\/WebUnitTestSupport.h\"\n\nusing namespace WebCore;\nusing namespace WebKit;\n\nnamespace {\n\nclass MockGraphicsLayerClient : public GraphicsLayerClient {\npublic:\n virtual void notifyAnimationStarted(const GraphicsLayer*, double time) OVERRIDE { }\n virtual void paintContents(const GraphicsLayer*, GraphicsContext&, GraphicsLayerPaintingPhase, const IntRect& inClip) OVERRIDE { }\n};\n\nclass GraphicsLayerForTesting : public GraphicsLayer {\npublic:\n explicit GraphicsLayerForTesting(GraphicsLayerClient* client)\n : GraphicsLayer(client) { };\n};\n\nclass GraphicsLayerTest : public testing::Test {\npublic:\n GraphicsLayerTest()\n {\n m_graphicsLayer = adoptPtr(new GraphicsLayerForTesting(&m_client));\n m_platformLayer = m_graphicsLayer->platformLayer();\n m_layerTreeView = adoptPtr(Platform::current()->unitTestSupport()->createLayerTreeViewForTesting(WebUnitTestSupport::TestViewTypeUnitTest));\n ASSERT(m_layerTreeView);\n m_layerTreeView->setRootLayer(*m_platformLayer);\n m_layerTreeView->setViewportSize(WebSize(1, 1), WebSize(1, 1));\n }\n\n virtual ~GraphicsLayerTest()\n {\n m_graphicsLayer.clear();\n m_layerTreeView.clear();\n }\n\nprotected:\n WebLayer* m_platformLayer;\n OwnPtr m_graphicsLayer;\n\nprivate:\n OwnPtr m_layerTreeView;\n MockGraphicsLayerClient m_client;\n};\n\nTEST_F(GraphicsLayerTest, updateLayerPreserves3DWithAnimations)\n{\n ASSERT_FALSE(m_platformLayer->hasActiveAnimation());\n\n OwnPtr curve = adoptPtr(Platform::current()->compositorSupport()->createFloatAnimationCurve());\n curve->add(WebFloatKeyframe(0.0, 0.0));\n OwnPtr floatAnimation(adoptPtr(Platform::current()->compositorSupport()->createAnimation(*curve, WebAnimation::TargetPropertyOpacity)));\n int animationId = floatAnimation->id();\n ASSERT_TRUE(m_platformLayer->addAnimation(floatAnimation.get()));\n\n ASSERT_TRUE(m_platformLayer->hasActiveAnimation());\n\n m_graphicsLayer->setPreserves3D(true);\n\n m_platformLayer = m_graphicsLayer->platformLayer();\n ASSERT_TRUE(m_platformLayer);\n\n ASSERT_TRUE(m_platformLayer->hasActiveAnimation());\n m_platformLayer->removeAnimation(animationId);\n ASSERT_FALSE(m_platformLayer->hasActiveAnimation());\n\n m_graphicsLayer->setPreserves3D(false);\n\n m_platformLayer = m_graphicsLayer->platformLayer();\n ASSERT_TRUE(m_platformLayer);\n\n ASSERT_FALSE(m_platformLayer->hasActiveAnimation());\n}\n\nclass FakeScrollableArea : public ScrollableArea {\npublic:\n virtual bool isActive() const OVERRIDE { return false; }\n virtual int scrollSize(ScrollbarOrientation) const OVERRIDE { return 100; }\n virtual int scrollPosition(Scrollbar*) const OVERRIDE { return 0; }\n virtual bool isScrollCornerVisible() const OVERRIDE { return false; }\n virtual IntRect scrollCornerRect() const OVERRIDE { return IntRect(); }\n virtual int visibleWidth() const OVERRIDE { return 10; }\n virtual int visibleHeight() const OVERRIDE { return 10; }\n virtual IntSize contentsSize() const OVERRIDE { return IntSize(100, 100); }\n virtual bool scrollbarsCanBeActive() const OVERRIDE { return false; }\n virtual ScrollableArea* enclosingScrollableArea() const OVERRIDE { return 0; }\n virtual IntRect scrollableAreaBoundingBox() const OVERRIDE { return IntRect(); }\n virtual void invalidateScrollbarRect(Scrollbar*, const IntRect&) OVERRIDE { }\n virtual void invalidateScrollCornerRect(const IntRect&) OVERRIDE { }\n\n virtual void setScrollOffset(const IntPoint& scrollOffset) OVERRIDE { m_scrollPosition = scrollOffset; }\n virtual IntPoint scrollPosition() const OVERRIDE { return m_scrollPosition; }\n\nprivate:\n IntPoint m_scrollPosition;\n};\n\n\/\/ http:\/\/crbug.com\/247279\nTEST_F(GraphicsLayerTest, DISABLED_applyScrollToScrollableArea)\n{\n FakeScrollableArea scrollableArea;\n m_graphicsLayer->setScrollableArea(&scrollableArea);\n\n WebPoint scrollPosition(7, 9);\n m_platformLayer->setScrollPosition(scrollPosition);\n\n EXPECT_EQ(scrollPosition, WebPoint(scrollableArea.scrollPosition()));\n}\n\nTEST_F(GraphicsLayerTest, DISABLED_setContentsToSolidColor)\n{\n m_graphicsLayer->setContentsToSolidColor(Color::transparent);\n EXPECT_FALSE(m_graphicsLayer->contentsLayer());\n\n m_graphicsLayer->setContentsToSolidColor(Color::white);\n EXPECT_TRUE(m_graphicsLayer->contentsLayer());\n\n m_graphicsLayer->setContentsToSolidColor(Color());\n EXPECT_FALSE(m_graphicsLayer->contentsLayer());\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"api.hpp\"\n#include \"common\/params.h\"\n#include \"drive_stats.hpp\"\n\nconst double MILE_TO_KM = 1.60934;\n\nstatic QLayout* build_stat_layout(QLabel** metric, const QString& name) {\n QVBoxLayout* layout = new QVBoxLayout;\n layout->setMargin(0);\n *metric = new QLabel(\"0\");\n (*metric)->setStyleSheet(\"font-size: 80px; font-weight: 600;\");\n layout->addWidget(*metric, 0, Qt::AlignLeft);\n\n QLabel* label = new QLabel(name);\n label->setStyleSheet(\"font-size: 45px; font-weight: 500;\");\n layout->addWidget(label, 0, Qt::AlignLeft);\n return layout;\n}\n\nvoid DriveStats::parseResponse(QString response) {\n response = response.trimmed();\n QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8());\n if (doc.isNull()) {\n qDebug() << \"JSON Parse failed on getting past drives statistics\";\n return;\n }\n\n auto update = [](const QJsonObject &obj, StatsLabels& labels, bool metric) {\n labels.routes->setText(QString::number((int)obj[\"routes\"].toDouble()));\n labels.distance->setText(QString::number(obj[\"distance\"].toDouble() * (metric ? MILE_TO_KM : 1)));\n labels.hours->setText(QString::number((int)(obj[\"minutes\"].toDouble() \/ 60)));\n };\n\n bool metric = Params().read_db_bool(\"IsMetric\");\n QJsonObject json = doc.object();\n update(json[\"all\"].toObject(), all_, metric);\n update(json[\"week\"].toObject(), week_, metric);\n}\n\nDriveStats::DriveStats(QWidget* parent) : QWidget(parent) {\n setStyleSheet(\"QLabel {font-size: 48px; font-weight: 500;}\");\n\n auto add_stats_layouts = [&](QGridLayout* gl, StatsLabels& labels, int row, const char* distance_unit) {\n gl->addLayout(build_stat_layout(&labels.routes, \"DRIVES\"), row, 0, 3, 1);\n gl->addLayout(build_stat_layout(&labels.distance, distance_unit), row, 1, 3, 1);\n gl->addLayout(build_stat_layout(&labels.hours, \"HOURS\"), row, 2, 3, 1);\n };\n\n const char* distance_unit = Params().read_db_bool(\"IsMetric\") ? \"KM\" : \"MILES\";\n QGridLayout* gl = new QGridLayout();\n gl->setMargin(0);\n gl->addWidget(new QLabel(\"ALL TIME\"), 0, 0, 1, 3);\n add_stats_layouts(gl, all_, 1, distance_unit);\n gl->addWidget(new QLabel(\"PAST WEEK\"), 6, 0, 1, 3);\n add_stats_layouts(gl, week_, 7, distance_unit);\n\n QVBoxLayout* vlayout = new QVBoxLayout(this);\n vlayout->addLayout(gl);\n\n \/\/ TODO: do we really need to update this frequently?\n QString dongleId = QString::fromStdString(Params().get(\"DongleId\"));\n QString url = \"https:\/\/api.commadotai.com\/v1.1\/devices\/\" + dongleId + \"\/stats\";\n RequestRepeater* repeater = new RequestRepeater(this, url, 13, \"ApiCache_DriveStats\");\n QObject::connect(repeater, SIGNAL(receivedResponse(QString)), this, SLOT(parseResponse(QString)));\n}\ndrive_stats.cc: fix distance rounding#include \n#include \n#include \n#include \n\n#include \"api.hpp\"\n#include \"common\/params.h\"\n#include \"drive_stats.hpp\"\n\nconst double MILE_TO_KM = 1.60934;\n\nstatic QLayout* build_stat_layout(QLabel** metric, const QString& name) {\n QVBoxLayout* layout = new QVBoxLayout;\n layout->setMargin(0);\n *metric = new QLabel(\"0\");\n (*metric)->setStyleSheet(\"font-size: 80px; font-weight: 600;\");\n layout->addWidget(*metric, 0, Qt::AlignLeft);\n\n QLabel* label = new QLabel(name);\n label->setStyleSheet(\"font-size: 45px; font-weight: 500;\");\n layout->addWidget(label, 0, Qt::AlignLeft);\n return layout;\n}\n\nvoid DriveStats::parseResponse(QString response) {\n response = response.trimmed();\n QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8());\n if (doc.isNull()) {\n qDebug() << \"JSON Parse failed on getting past drives statistics\";\n return;\n }\n\n auto update = [](const QJsonObject &obj, StatsLabels& labels, bool metric) {\n labels.routes->setText(QString::number((int)obj[\"routes\"].toDouble()));\n labels.distance->setText(QString::number(int(obj[\"distance\"].toDouble() * (metric ? MILE_TO_KM : 1))));\n labels.hours->setText(QString::number((int)(obj[\"minutes\"].toDouble() \/ 60)));\n };\n\n bool metric = Params().read_db_bool(\"IsMetric\");\n QJsonObject json = doc.object();\n update(json[\"all\"].toObject(), all_, metric);\n update(json[\"week\"].toObject(), week_, metric);\n}\n\nDriveStats::DriveStats(QWidget* parent) : QWidget(parent) {\n setStyleSheet(\"QLabel {font-size: 48px; font-weight: 500;}\");\n\n auto add_stats_layouts = [&](QGridLayout* gl, StatsLabels& labels, int row, const char* distance_unit) {\n gl->addLayout(build_stat_layout(&labels.routes, \"DRIVES\"), row, 0, 3, 1);\n gl->addLayout(build_stat_layout(&labels.distance, distance_unit), row, 1, 3, 1);\n gl->addLayout(build_stat_layout(&labels.hours, \"HOURS\"), row, 2, 3, 1);\n };\n\n const char* distance_unit = Params().read_db_bool(\"IsMetric\") ? \"KM\" : \"MILES\";\n QGridLayout* gl = new QGridLayout();\n gl->setMargin(0);\n gl->addWidget(new QLabel(\"ALL TIME\"), 0, 0, 1, 3);\n add_stats_layouts(gl, all_, 1, distance_unit);\n gl->addWidget(new QLabel(\"PAST WEEK\"), 6, 0, 1, 3);\n add_stats_layouts(gl, week_, 7, distance_unit);\n\n QVBoxLayout* vlayout = new QVBoxLayout(this);\n vlayout->addLayout(gl);\n\n \/\/ TODO: do we really need to update this frequently?\n QString dongleId = QString::fromStdString(Params().get(\"DongleId\"));\n QString url = \"https:\/\/api.commadotai.com\/v1.1\/devices\/\" + dongleId + \"\/stats\";\n RequestRepeater* repeater = new RequestRepeater(this, url, 13, \"ApiCache_DriveStats\");\n QObject::connect(repeater, SIGNAL(receivedResponse(QString)), this, SLOT(parseResponse(QString)));\n}\n<|endoftext|>"} {"text":"fixed: INVALID_COEFFICIENTS<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkOrImageFilterTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n\n\n\n#include \n#include \n#include \n#include \n\n\nint itkOrImageFilterTest(int, char* [] ) \n{\n\n \/\/ Define the dimension of the images\n const unsigned int myDimension = 3;\n\n \/\/ Declare the types of the images\n typedef unsigned char myPixelType;\n typedef itk::Image myImageType1;\n typedef itk::Image myImageType2;\n typedef itk::Image myImageType3;\n\n \/\/ Declare the type of the index to access images\n typedef itk::Index myIndexType;\n\n \/\/ Declare the type of the size \n typedef itk::Size mySizeType;\n\n \/\/ Declare the type of the Region\n typedef itk::ImageRegion myRegionType;\n\n \/\/ Declare the type for the ADD filter\n typedef itk::OrImageFilter<\n myImageType1,\n myImageType2,\n myImageType3 > myFilterType;\n \n \/\/ Declare the pointers to images\n typedef myImageType1::Pointer myImageType1Pointer;\n typedef myImageType2::Pointer myImageType2Pointer;\n typedef myImageType3::Pointer myImageType3Pointer;\n typedef myFilterType::Pointer myFilterTypePointer;\n\n \/\/ Create two images\n myImageType1Pointer inputImageA = myImageType1::New();\n myImageType2Pointer inputImageB = myImageType2::New();\n \n \/\/ Define their size, and start index\n mySizeType size;\n size[0] = 2;\n size[1] = 2;\n size[2] = 2;\n\n myIndexType start;\n start[0] = 0;\n start[1] = 0;\n start[2] = 0;\n\n myRegionType region;\n region.SetIndex( start );\n region.SetSize( size );\n\n \/\/ Initialize Image A\n inputImageA->SetLargestPossibleRegion( region );\n inputImageA->SetBufferedRegion( region );\n inputImageA->SetRequestedRegion( region );\n inputImageA->Allocate();\n\n \/\/ Initialize Image B\n inputImageB->SetLargestPossibleRegion( region );\n inputImageB->SetBufferedRegion( region );\n inputImageB->SetRequestedRegion( region );\n inputImageB->Allocate();\n\n\n \/\/ Declare Iterator types apropriated for each image \n typedef itk::ImageRegionIteratorWithIndex myIteratorType1;\n typedef itk::ImageRegionIteratorWithIndex myIteratorType2;\n typedef itk::ImageRegionIteratorWithIndex myIteratorType3;\n\n \/\/ Create one iterator for Image A (this is a light object)\n myIteratorType1 it1( inputImageA, inputImageA->GetBufferedRegion() );\n\n \/\/ Initialize the content of Image A\n std::cout << \"First operand \" << std::endl;\n while( !it1.IsAtEnd() ) \n {\n it1.Set( 2.0 );\n std::cout << static_cast::PrintType>(it1.Get()) << std::endl;\n ++it1;\n }\n\n \/\/ Create one iterator for Image B (this is a light object)\n myIteratorType2 it2( inputImageB, inputImageB->GetBufferedRegion() );\n\n \/\/ Initialize the content of Image B\n std::cout << \"Second operand \" << std::endl;\n while( !it2.IsAtEnd() ) \n {\n it2.Set( 3.0 );\n std::cout << static_cast::PrintType>(it2.Get()) << std::endl;\n ++it2;\n }\n \n\n \/\/ Create an ADD Filter \n myFilterTypePointer filter = myFilterType::New();\n\n\n \/\/ Connect the input images\n filter->SetInput1( inputImageA ); \n filter->SetInput2( inputImageB );\n\n \/\/ Get the Smart Pointer to the Filter Output \n myImageType3Pointer outputImage = filter->GetOutput();\n\n \n \/\/ Execute the filter\n filter->Update();\n\n \/\/ Create an iterator for going through the image output\n myIteratorType3 it3(outputImage, outputImage->GetBufferedRegion());\n \n \/\/ Print the content of the result image\n std::cout << \" Result \" << std::endl;\n while( !it3.IsAtEnd() ) \n {\n std::cout << static_cast::PrintType>(it3.Get()) << std::endl;\n ++it3;\n }\n\n\n \/\/ All objects should be automatically destroyed at this point\n std::cout << \"Test PASSED !\" << std::endl;\n\n return EXIT_SUCCESS;\n\n}\n\n\n\n\nENH: GoToBegin() calls where missing in iterators.\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkOrImageFilterTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n\n\n\n#include \n#include \n#include \n#include \n\n\nint itkOrImageFilterTest(int, char* [] ) \n{\n\n \/\/ Define the dimension of the images\n const unsigned int myDimension = 3;\n\n \/\/ Declare the types of the images\n typedef unsigned char myPixelType;\n typedef itk::Image myImageType1;\n typedef itk::Image myImageType2;\n typedef itk::Image myImageType3;\n\n \/\/ Declare the type of the index to access images\n typedef itk::Index myIndexType;\n\n \/\/ Declare the type of the size \n typedef itk::Size mySizeType;\n\n \/\/ Declare the type of the Region\n typedef itk::ImageRegion myRegionType;\n\n \/\/ Declare the type for the ADD filter\n typedef itk::OrImageFilter<\n myImageType1,\n myImageType2,\n myImageType3 > myFilterType;\n \n \/\/ Declare the pointers to images\n typedef myImageType1::Pointer myImageType1Pointer;\n typedef myImageType2::Pointer myImageType2Pointer;\n typedef myImageType3::Pointer myImageType3Pointer;\n typedef myFilterType::Pointer myFilterTypePointer;\n\n \/\/ Create two images\n myImageType1Pointer inputImageA = myImageType1::New();\n myImageType2Pointer inputImageB = myImageType2::New();\n \n \/\/ Define their size, and start index\n mySizeType size;\n size[0] = 2;\n size[1] = 2;\n size[2] = 2;\n\n myIndexType start;\n start[0] = 0;\n start[1] = 0;\n start[2] = 0;\n\n myRegionType region;\n region.SetIndex( start );\n region.SetSize( size );\n\n \/\/ Initialize Image A\n inputImageA->SetLargestPossibleRegion( region );\n inputImageA->SetBufferedRegion( region );\n inputImageA->SetRequestedRegion( region );\n inputImageA->Allocate();\n\n \/\/ Initialize Image B\n inputImageB->SetLargestPossibleRegion( region );\n inputImageB->SetBufferedRegion( region );\n inputImageB->SetRequestedRegion( region );\n inputImageB->Allocate();\n\n\n \/\/ Declare Iterator types apropriated for each image \n typedef itk::ImageRegionIteratorWithIndex myIteratorType1;\n typedef itk::ImageRegionIteratorWithIndex myIteratorType2;\n typedef itk::ImageRegionIteratorWithIndex myIteratorType3;\n\n \/\/ Create one iterator for Image A (this is a light object)\n myIteratorType1 it1( inputImageA, inputImageA->GetBufferedRegion() );\n it1.GoToBegin();\n\n \/\/ Initialize the content of Image A\n std::cout << \"First operand \" << std::endl;\n while( !it1.IsAtEnd() ) \n {\n it1.Set( 2.0 );\n std::cout << static_cast::PrintType>(it1.Get()) << std::endl;\n ++it1;\n }\n\n \/\/ Create one iterator for Image B (this is a light object)\n myIteratorType2 it2( inputImageB, inputImageB->GetBufferedRegion() );\n it2.GoToBegin();\n\n \/\/ Initialize the content of Image B\n std::cout << \"Second operand \" << std::endl;\n while( !it2.IsAtEnd() ) \n {\n it2.Set( 3.0 );\n std::cout << static_cast::PrintType>(it2.Get()) << std::endl;\n ++it2;\n }\n \n\n \/\/ Create an ADD Filter \n myFilterTypePointer filter = myFilterType::New();\n\n\n \/\/ Connect the input images\n filter->SetInput1( inputImageA ); \n filter->SetInput2( inputImageB );\n\n \/\/ Get the Smart Pointer to the Filter Output \n myImageType3Pointer outputImage = filter->GetOutput();\n\n \n \/\/ Execute the filter\n filter->Update();\n\n \/\/ Create an iterator for going through the image output\n myIteratorType3 it3(outputImage, outputImage->GetBufferedRegion());\n it3.GoToBegin();\n \n \/\/ Print the content of the result image\n std::cout << \" Result \" << std::endl;\n while( !it3.IsAtEnd() ) \n {\n std::cout << static_cast::PrintType>(it3.Get()) << std::endl;\n ++it3;\n }\n\n\n \/\/ All objects should be automatically destroyed at this point\n std::cout << \"Test PASSED !\" << std::endl;\n\n return EXIT_SUCCESS;\n\n}\n\n\n\n\n<|endoftext|>"} {"text":"\/**\n * Plan of Attack\n * * identify functions to test\n * * plan out test fixtures and structure\n * * set up test class\n * \n *\/\n\n\/**\n * Functions to test:\n * int co_profiles_create(const size_t index_size); +\n * int co_profiles_init(const size_t index_size); +\n * co_obj_t *co_profile_find(co_obj_t *name); + \n * int co_profile_add(const char *name, const size_t nlen); +\n * int co_profile_remove(const char *name, const size_t nlen); +\n * co_obj_t *co_profile_get(co_obj_t *profile, const co_obj_t *key);\n * size_t co_profile_get_str(co_obj_t *profile, char **output, const char *key, const size_t klen);\n * int co_profile_set_str(co_obj_t *profile, const char *key, const size_t klen, const char *value, const size_t vlen);\n * \n * \n *\/\n\nextern \"C\" {\n#include \"..\/src\/obj.h\"\n#include \"..\/src\/list.h\"\n#include \"..\/src\/tree.h\"\n#include \"..\/src\/profile.h\"\n}\n#include \"gtest\/gtest.h\"\n\nSCHEMA(default)\n{\n SCHEMA_ADD(\"ssid\", \"commotionwireless.net\"); \n SCHEMA_ADD(\"bssid\", \"02:CA:FF:EE:BA:BE\"); \n SCHEMA_ADD(\"bssidgen\", \"true\"); \n SCHEMA_ADD(\"channel\", \"5\"); \n SCHEMA_ADD(\"mode\", \"adhoc\"); \n SCHEMA_ADD(\"type\", \"mesh\"); \n SCHEMA_ADD(\"dns\", \"208.67.222.222\"); \n SCHEMA_ADD(\"domain\", \"mesh.local\"); \n SCHEMA_ADD(\"ipgen\", \"true\"); \n SCHEMA_ADD(\"ip\", \"100.64.0.0\"); \n SCHEMA_ADD(\"netmask\", \"255.192.0.0\"); \n SCHEMA_ADD(\"ipgenmask\", \"255.192.0.0\"); \n SCHEMA_ADD(\"encryption\", \"psk2\"); \n SCHEMA_ADD(\"key\", \"c0MM0t10n!r0cks\"); \n SCHEMA_ADD(\"serval\", \"false\"); \n SCHEMA_ADD(\"announce\", \"true\"); \n return 1;\n}\n\n\nclass ProfileTest : public ::testing::Test\n{\nprotected:\n \/\/ test functions\n void Init();\n void Add();\n void Retrieve();\n void Remove();\n void Get();\n \n \/\/ variables\n int ret = 0;\n co_obj_t *profile1 = co_str8_create(\"profile1\", 9, 0);\n co_obj_t *profile2 = co_str8_create(\"profile2\", 9, 0);\n co_obj_t *found = NULL;\n \n \/\/ constructor\n ProfileTest()\n {\n ret = co_profiles_init(16);\n }\n \n virtual void SetUp()\n {\n }\n \n ~ProfileTest()\n {\n }\n};\n\nvoid ProfileTest::Init()\n{\n ASSERT_EQ(1, ret);\n}\n\nvoid ProfileTest::Add()\n{\n ret = co_profile_add(\"profile1\", 9);\n ASSERT_EQ(1, ret);\n}\n\nvoid ProfileTest::Retrieve()\n{\n ret = co_profile_add(\"profile1\", 9);\n ASSERT_EQ(1, ret);\n\n ret = co_profile_add(\"profile2\", 9);\n ASSERT_EQ(1, ret);\n\n found = co_profile_find(profile1);\n ASSERT_TRUE(NULL != found);\n \n found = co_profile_find(profile2);\n ASSERT_TRUE(NULL != found);\n}\n\nvoid ProfileTest::Remove()\n{\n ret = co_profile_add(\"profile1\", 9);\n ASSERT_EQ(1, ret);\n\n ret = co_profile_add(\"profile2\", 9);\n ASSERT_EQ(1, ret);\n\n ret = co_profile_remove(\"profile1\", 9);\n ASSERT_EQ(1, ret);\n \n \/\/ confirm removal\n found = co_profile_find(profile1);\n ASSERT_TRUE(NULL == found);\n \n ret = co_profile_remove(\"profile2\", 9);\n ASSERT_EQ(1, ret);\n \n \/\/confirm removal\n found = co_profile_find(profile2);\n ASSERT_TRUE(NULL == found);\n}\n\nvoid ProfileTest::Get()\n{\n SCHEMA_REGISTER(default);\n \n ret = co_profile_add(\"profile1\", 9);\n ASSERT_EQ(1, ret);\n \n found = co_profile_find(profile1);\n ASSERT_TRUE(NULL != found);\n \n ret = co_profile_set_str((co_obj_t *)found, \"ip\", sizeof(\"ip\"), \"192.168.1.254\", sizeof(\"192.168.1.254\"));\n ASSERT_EQ(1, ret);\n \n\/\/ ret = co_profile_get_str(profile1, &ip, \"ip\", sizeof(\"ip\");\n\/\/ ASSERT_TRUE(NULL != ret);\n}\n\n\n\nTEST_F(ProfileTest, Init)\n{\n Init();\n}\n\nTEST_F(ProfileTest, Add)\n{\n Add();\n}\n\nTEST_F(ProfileTest, Retrieve)\n{\n Retrieve();\n}\n\nTEST_F(ProfileTest, Remove)\n{\n Remove();\n}\n\nTEST_F(ProfileTest, Get)\n{\n Get();\n}improved set\/get tests\/**\n * Plan of Attack\n * * identify functions to test\n * * plan out test fixtures and structure\n * * set up test class\n * \n *\/\n\n\/**\n * Functions to test:\n * int co_profiles_create(const size_t index_size); +\n * int co_profiles_init(const size_t index_size); +\n * co_obj_t *co_profile_find(co_obj_t *name); + \n * int co_profile_add(const char *name, const size_t nlen); +\n * int co_profile_remove(const char *name, const size_t nlen); +\n * co_obj_t *co_profile_get(co_obj_t *profile, const co_obj_t *key);\n * size_t co_profile_get_str(co_obj_t *profile, char **output, const char *key, const size_t klen);\n * int co_profile_set_str(co_obj_t *profile, const char *key, const size_t klen, const char *value, const size_t vlen);\n * \n * \n *\/\n\nextern \"C\" {\n#include \"..\/src\/obj.h\"\n#include \"..\/src\/list.h\"\n#include \"..\/src\/tree.h\"\n#include \"..\/src\/profile.h\"\n}\n#include \"gtest\/gtest.h\"\n\nSCHEMA(default)\n{\n SCHEMA_ADD(\"ssid\", \"commotionwireless.net\"); \n SCHEMA_ADD(\"bssid\", \"02:CA:FF:EE:BA:BE\"); \n SCHEMA_ADD(\"bssidgen\", \"true\"); \n SCHEMA_ADD(\"channel\", \"5\"); \n SCHEMA_ADD(\"mode\", \"adhoc\"); \n SCHEMA_ADD(\"type\", \"mesh\"); \n SCHEMA_ADD(\"dns\", \"208.67.222.222\"); \n SCHEMA_ADD(\"domain\", \"mesh.local\"); \n SCHEMA_ADD(\"ipgen\", \"true\"); \n SCHEMA_ADD(\"ip\", \"100.64.0.0\"); \n SCHEMA_ADD(\"netmask\", \"255.192.0.0\"); \n SCHEMA_ADD(\"ipgenmask\", \"255.192.0.0\"); \n SCHEMA_ADD(\"encryption\", \"psk2\"); \n SCHEMA_ADD(\"key\", \"c0MM0t10n!r0cks\"); \n SCHEMA_ADD(\"serval\", \"false\"); \n SCHEMA_ADD(\"announce\", \"true\"); \n return 1;\n}\n\n\nclass ProfileTest : public ::testing::Test\n{\nprotected:\n \/\/ test functions\n void Init();\n void Add();\n void Retrieve();\n void Remove();\n void Get();\n \n \/\/ variables\n int ret = 0;\n co_obj_t *profile1 = co_str8_create(\"profile1\", 9, 0);\n co_obj_t *profile2 = co_str8_create(\"profile2\", 9, 0);\n co_obj_t *found = NULL;\n \n \/\/ constructor\n ProfileTest()\n {\n ret = co_profiles_init(16);\n }\n \n virtual void SetUp()\n {\n }\n \n ~ProfileTest()\n {\n }\n};\n\nvoid ProfileTest::Init()\n{\n ASSERT_EQ(1, ret);\n}\n\nvoid ProfileTest::Add()\n{\n ret = co_profile_add(\"profile1\", 9);\n ASSERT_EQ(1, ret);\n}\n\nvoid ProfileTest::Retrieve()\n{\n ret = co_profile_add(\"profile1\", 9);\n ASSERT_EQ(1, ret);\n\n ret = co_profile_add(\"profile2\", 9);\n ASSERT_EQ(1, ret);\n\n found = co_profile_find(profile1);\n ASSERT_TRUE(NULL != found);\n \n found = co_profile_find(profile2);\n ASSERT_TRUE(NULL != found);\n}\n\nvoid ProfileTest::Remove()\n{\n ret = co_profile_add(\"profile1\", 9);\n ASSERT_EQ(1, ret);\n\n ret = co_profile_add(\"profile2\", 9);\n ASSERT_EQ(1, ret);\n\n ret = co_profile_remove(\"profile1\", 9);\n ASSERT_EQ(1, ret);\n \n \/\/ confirm removal\n found = co_profile_find(profile1);\n ASSERT_TRUE(NULL == found);\n \n ret = co_profile_remove(\"profile2\", 9);\n ASSERT_EQ(1, ret);\n \n \/\/confirm removal\n found = co_profile_find(profile2);\n ASSERT_TRUE(NULL == found);\n}\n\nvoid ProfileTest::Get()\n{\n \n SCHEMA_REGISTER(default);\n \n ret = co_profile_add(\"profile1\", 9);\n ASSERT_EQ(1, ret);\n\n \n found = co_profile_find(profile1);\n ASSERT_TRUE(NULL != found);\n \n ret = co_profile_set_str((co_obj_t *)found, \"ip\", sizeof(\"ip\"), \"192.168.1.254\", sizeof(\"192.168.1.254\"));\n ASSERT_EQ(1, ret);\n \n char *ip;\n \n ret = co_profile_get_str(found, &ip, \"ip\", sizeof(\"ip\"));\n ASSERT_STREQ(\"192.168.1.254\", ip);\n}\n\n\n\nTEST_F(ProfileTest, Init)\n{\n Init();\n}\n\nTEST_F(ProfileTest, Add)\n{\n Add();\n}\n\nTEST_F(ProfileTest, Retrieve)\n{\n Retrieve();\n}\n\nTEST_F(ProfileTest, Remove)\n{\n Remove();\n}\n\nTEST_F(ProfileTest, Get)\n{\n Get();\n}<|endoftext|>"} {"text":"#include \"config.h\"\n#include \"halcmd_rtapiapp.h\"\n\n#include \n#include \n#include \"ll-zeroconf.hh\"\n#include \"mk-zeroconf.hh\"\n#include \"mk-zeroconf-types.h\"\n#include \n\n\n#include \nusing namespace google::protobuf;\n\nstatic pb::Container command, reply;\n\nstatic zctx_t *z_context;\nstatic void *z_command;\nstatic int timeout = 5000;\nstatic std::string errormsg;\n\nint rtapi_rpc(void *socket, pb::Container &tx, pb::Container &rx)\n{\n zframe_t *request = zframe_new (NULL, tx.ByteSize());\n assert(request);\n assert(tx.SerializeWithCachedSizesToArray(zframe_data (request)));\n\n assert (zframe_send (&request, socket, 0) == 0);\n zframe_t *reply = zframe_recv (socket);\n if (reply == NULL) {\n\terrormsg = \"rtapi_rpc(): reply timeout\";\n\treturn -1;\n }\n int retval = rx.ParseFromArray(zframe_data (reply),\n\t\t\t\t zframe_size (reply)) ? 0 : -1;\n \/\/ assert(retval == 0);\n zframe_destroy(&reply);\n\n errormsg = \"\";\n for (int i = 0; i < rx.note_size(); i++)\n\terrormsg += rx.note(i) + \"\\n\";\n return retval;\n}\n\n\nint rtapi_callfunc(int instance,\n\t\t const char *func,\n\t\t const char **args)\n{\n pb::RTAPICommand *cmd;\n command.Clear();\n command.set_type(pb::MT_RTAPI_APP_CALLFUNC);\n cmd = command.mutable_rtapicmd();\n cmd->set_func(func);\n cmd->set_instance(instance);\n\n int argc = 0;\n if (args)\n\twhile(args[argc] && *args[argc]) {\n\t cmd->add_argv(args[argc]);\n\t argc++;\n\t}\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n}\n\nint rtapi_newinst(int instance,\n\t\t const char *comp,\n\t\t const char *instname,\n\t\t const char **args)\n{\n pb::RTAPICommand *cmd;\n command.Clear();\n command.set_type(pb::MT_RTAPI_APP_NEWINST);\n cmd = command.mutable_rtapicmd();\n cmd->set_instance(instance);\n\n cmd->set_comp(comp);\n cmd->set_instname(instname);\n\n int argc = 0;\n if (args)\n\twhile(args[argc] && *args[argc]) {\n\t cmd->add_argv(args[argc]);\n\t argc++;\n\t}\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n}\n\nint rtapi_delinst(int instance,\n\t\t const char *instname)\n{\n pb::RTAPICommand *cmd;\n command.Clear();\n command.set_type(pb::MT_RTAPI_APP_DELINST);\n cmd = command.mutable_rtapicmd();\n cmd->set_instance(instance);\n cmd->set_instname(instname);\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n\n}\n\nstatic int rtapi_loadop(pb::ContainerType type, int instance, const char *modname, const char **args)\n{\n pb::RTAPICommand *cmd;\n command.Clear();\n command.set_type(type);\n cmd = command.mutable_rtapicmd();\n cmd->set_modname(modname);\n cmd->set_instance(instance);\n\n int argc = 0;\n if (args)\n\twhile(args[argc] && *args[argc]) {\n\t cmd->add_argv(args[argc]);\n\t argc++;\n\t}\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n}\n\nint rtapi_loadrt(int instance, const char *modname, const char **args)\n{\n return rtapi_loadop(pb::MT_RTAPI_APP_LOADRT, instance, modname, args);\n}\n\nint rtapi_unloadrt(int instance, const char *modname)\n{\n return rtapi_loadop(pb::MT_RTAPI_APP_UNLOADRT, instance, modname, NULL);\n}\n\nint rtapi_shutdown(int instance)\n{\n pb::RTAPICommand *cmd;\n\n command.Clear();\n command.set_type(pb::MT_RTAPI_APP_EXIT);\n cmd = command.mutable_rtapicmd();\n cmd->set_instance(instance);\n\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n}\n\n\nint rtapi_ping(int instance)\n{\n pb::RTAPICommand *cmd;\n command.Clear();\n command.set_type(pb::MT_RTAPI_APP_PING);\n cmd = command.mutable_rtapicmd();\n cmd->set_instance(instance);\n\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n}\n\nint rtapi_newthread(int instance, const char *name, int period, int cpu, int use_fp)\n{\n pb::RTAPICommand *cmd;\n command.Clear();\n command.set_type(pb::MT_RTAPI_APP_NEWTHREAD);\n cmd = command.mutable_rtapicmd();\n cmd->set_instance(instance);\n cmd->set_threadname(name);\n cmd->set_threadperiod(period);\n cmd->set_cpu(cpu);\n cmd->set_use_fp(use_fp);\n\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n}\n\nint rtapi_delthread(int instance, const char *name)\n{\n pb::RTAPICommand *cmd;\n command.Clear();\n command.set_type(pb::MT_RTAPI_APP_DELTHREAD);\n cmd = command.mutable_rtapicmd();\n cmd->set_instance(instance);\n cmd->set_threadname(name);\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n}\n\nconst char *rtapi_rpcerror(void)\n{\n return errormsg.c_str();\n}\n\nint rtapi_connect(int instance, char *uri, const char *svc_uuid)\n{\n GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n char ipcuri[100];\n\n if (uri == NULL) {\n\tsnprintf(ipcuri, sizeof(ipcuri),ZMQIPC_FORMAT,\n\t\t RUNDIR, instance, \"rtapi\", svc_uuid);\n\turi = ipcuri;\n }\n\n#if 0\n \/\/ we're not doing remote RTAPI just yet\n if (uri == NULL) {\n\tchar uuid[50];\n\tsnprintf(uuid, sizeof(uuid),\"uuid=%s\", svc_uuid);\n\n\tzresolve_t res = {0};\n\tres.proto =\t AVAHI_PROTO_UNSPEC;\n\tres.interface = AVAHI_IF_UNSPEC;\n\tres.type = (char *) RTAPI_DNSSD_SUBTYPE MACHINEKIT_DNSSD_SERVICE_TYPE;\n\tres.match = uuid;\n\tres.domain = NULL;\n\tres.name = (char *)\"\";\n\tres.timeout_ms = 3000;\n\tres.result = SD_UNSET;\n\n\tresolve_context_t *p = ll_zeroconf_resolve(&res);\n\n\tif (res.result == SD_OK) {\n\t \/\/ fish out the dsn= TXT record\n\n\t AvahiStringList *dsn = avahi_string_list_find(res.txt, \"dsn\");\n\t char *key;\n\t size_t vlen;\n\n\t if (avahi_string_list_get_pair(dsn, &key, &uri, &vlen)) {\n\t\tfprintf(stderr,\n\t\t\t\"halcmd: service discovery failed - no dsn= key\\n\");\n\t\treturn -1;\n\t }\n\t} else {\n\t fprintf(stderr,\n\t\t \"halcmd: service discovery failed - cant retrieve rtapi_app command uri: %d\\n\",\n\t\t res.result );\n\t return -1;\n\t}\n\tll_zeroconf_resolve_free(p);\n }\n#endif\n\n z_context = zctx_new ();\n assert(z_context);\n z_command = zsocket_new (z_context, ZMQ_DEALER);\n assert(z_command);\n\n char z_ident[30];\n snprintf(z_ident, sizeof(z_ident), \"halcmd%d\",getpid());\n\n zsocket_set_identity(z_command, z_ident);\n zsocket_set_linger(z_command, 0);\n\n if (zsocket_connect(z_command, uri)) {\n\tperror(\"connect\");\n\treturn -EINVAL;\n }\n zsocket_set_rcvtimeo (z_command, timeout * ZMQ_POLL_MSEC);\n\n return rtapi_ping(instance);\n}\nhalcmd_rtapiapp.cc: concatenate all notes into a multiline error string#include \"config.h\"\n#include \"halcmd_rtapiapp.h\"\n\n#include \n#include \n#include \"ll-zeroconf.hh\"\n#include \"mk-zeroconf.hh\"\n#include \"mk-zeroconf-types.h\"\n#include \"pbutil.hh\"\n#include \n\n\n#include \nusing namespace google::protobuf;\n\nstatic pb::Container command, reply;\n\nstatic zctx_t *z_context;\nstatic void *z_command;\nstatic int timeout = 5000;\nstatic std::string errormsg;\n\nint rtapi_rpc(void *socket, pb::Container &tx, pb::Container &rx)\n{\n zframe_t *request = zframe_new (NULL, tx.ByteSize());\n assert(request);\n assert(tx.SerializeWithCachedSizesToArray(zframe_data (request)));\n\n assert (zframe_send (&request, socket, 0) == 0);\n zframe_t *reply = zframe_recv (socket);\n if (reply == NULL) {\n\terrormsg = \"rtapi_rpc(): reply timeout\";\n\treturn -1;\n }\n int retval = rx.ParseFromArray(zframe_data (reply),\n\t\t\t\t zframe_size (reply)) ? 0 : -1;\n \/\/ assert(retval == 0);\n zframe_destroy(&reply);\n if (rx.note_size())\n\terrormsg = pbconcat(rx.note(), \"\\n\");\n \/\/errormsg = rx.note(0); \/\/ simplify - one line only\n else\n\terrormsg = \"\";\n return retval;\n}\n\n\nint rtapi_callfunc(int instance,\n\t\t const char *func,\n\t\t const char **args)\n{\n pb::RTAPICommand *cmd;\n command.Clear();\n command.set_type(pb::MT_RTAPI_APP_CALLFUNC);\n cmd = command.mutable_rtapicmd();\n cmd->set_func(func);\n cmd->set_instance(instance);\n\n int argc = 0;\n if (args)\n\twhile(args[argc] && *args[argc]) {\n\t cmd->add_argv(args[argc]);\n\t argc++;\n\t}\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n}\n\nint rtapi_newinst(int instance,\n\t\t const char *comp,\n\t\t const char *instname,\n\t\t const char **args)\n{\n pb::RTAPICommand *cmd;\n command.Clear();\n command.set_type(pb::MT_RTAPI_APP_NEWINST);\n cmd = command.mutable_rtapicmd();\n cmd->set_instance(instance);\n\n cmd->set_comp(comp);\n cmd->set_instname(instname);\n\n int argc = 0;\n if (args)\n\twhile(args[argc] && *args[argc]) {\n\t cmd->add_argv(args[argc]);\n\t argc++;\n\t}\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n}\n\nint rtapi_delinst(int instance,\n\t\t const char *instname)\n{\n pb::RTAPICommand *cmd;\n command.Clear();\n command.set_type(pb::MT_RTAPI_APP_DELINST);\n cmd = command.mutable_rtapicmd();\n cmd->set_instance(instance);\n cmd->set_instname(instname);\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n\n}\n\nstatic int rtapi_loadop(pb::ContainerType type, int instance, const char *modname, const char **args)\n{\n pb::RTAPICommand *cmd;\n command.Clear();\n command.set_type(type);\n cmd = command.mutable_rtapicmd();\n cmd->set_modname(modname);\n cmd->set_instance(instance);\n\n int argc = 0;\n if (args)\n\twhile(args[argc] && *args[argc]) {\n\t cmd->add_argv(args[argc]);\n\t argc++;\n\t}\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n}\n\nint rtapi_loadrt(int instance, const char *modname, const char **args)\n{\n return rtapi_loadop(pb::MT_RTAPI_APP_LOADRT, instance, modname, args);\n}\n\nint rtapi_unloadrt(int instance, const char *modname)\n{\n return rtapi_loadop(pb::MT_RTAPI_APP_UNLOADRT, instance, modname, NULL);\n}\n\nint rtapi_shutdown(int instance)\n{\n pb::RTAPICommand *cmd;\n\n command.Clear();\n command.set_type(pb::MT_RTAPI_APP_EXIT);\n cmd = command.mutable_rtapicmd();\n cmd->set_instance(instance);\n\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n}\n\n\nint rtapi_ping(int instance)\n{\n pb::RTAPICommand *cmd;\n command.Clear();\n command.set_type(pb::MT_RTAPI_APP_PING);\n cmd = command.mutable_rtapicmd();\n cmd->set_instance(instance);\n\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n}\n\nint rtapi_newthread(int instance, const char *name, int period, int cpu, int use_fp)\n{\n pb::RTAPICommand *cmd;\n command.Clear();\n command.set_type(pb::MT_RTAPI_APP_NEWTHREAD);\n cmd = command.mutable_rtapicmd();\n cmd->set_instance(instance);\n cmd->set_threadname(name);\n cmd->set_threadperiod(period);\n cmd->set_cpu(cpu);\n cmd->set_use_fp(use_fp);\n\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n}\n\nint rtapi_delthread(int instance, const char *name)\n{\n pb::RTAPICommand *cmd;\n command.Clear();\n command.set_type(pb::MT_RTAPI_APP_DELTHREAD);\n cmd = command.mutable_rtapicmd();\n cmd->set_instance(instance);\n cmd->set_threadname(name);\n int retval = rtapi_rpc(z_command, command, reply);\n if (retval)\n\treturn retval;\n return reply.retcode();\n}\n\nconst char *rtapi_rpcerror(void)\n{\n return errormsg.c_str();\n}\n\nint rtapi_connect(int instance, char *uri, const char *svc_uuid)\n{\n GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n char ipcuri[100];\n\n if (uri == NULL) {\n\tsnprintf(ipcuri, sizeof(ipcuri),ZMQIPC_FORMAT,\n\t\t RUNDIR, instance, \"rtapi\", svc_uuid);\n\turi = ipcuri;\n }\n\n#if 0\n \/\/ we're not doing remote RTAPI just yet\n if (uri == NULL) {\n\tchar uuid[50];\n\tsnprintf(uuid, sizeof(uuid),\"uuid=%s\", svc_uuid);\n\n\tzresolve_t res = {0};\n\tres.proto =\t AVAHI_PROTO_UNSPEC;\n\tres.interface = AVAHI_IF_UNSPEC;\n\tres.type = (char *) RTAPI_DNSSD_SUBTYPE MACHINEKIT_DNSSD_SERVICE_TYPE;\n\tres.match = uuid;\n\tres.domain = NULL;\n\tres.name = (char *)\"\";\n\tres.timeout_ms = 3000;\n\tres.result = SD_UNSET;\n\n\tresolve_context_t *p = ll_zeroconf_resolve(&res);\n\n\tif (res.result == SD_OK) {\n\t \/\/ fish out the dsn= TXT record\n\n\t AvahiStringList *dsn = avahi_string_list_find(res.txt, \"dsn\");\n\t char *key;\n\t size_t vlen;\n\n\t if (avahi_string_list_get_pair(dsn, &key, &uri, &vlen)) {\n\t\tfprintf(stderr,\n\t\t\t\"halcmd: service discovery failed - no dsn= key\\n\");\n\t\treturn -1;\n\t }\n\t} else {\n\t fprintf(stderr,\n\t\t \"halcmd: service discovery failed - cant retrieve rtapi_app command uri: %d\\n\",\n\t\t res.result );\n\t return -1;\n\t}\n\tll_zeroconf_resolve_free(p);\n }\n#endif\n\n z_context = zctx_new ();\n assert(z_context);\n z_command = zsocket_new (z_context, ZMQ_DEALER);\n assert(z_command);\n\n char z_ident[30];\n snprintf(z_ident, sizeof(z_ident), \"halcmd%d\",getpid());\n\n zsocket_set_identity(z_command, z_ident);\n zsocket_set_linger(z_command, 0);\n\n if (zsocket_connect(z_command, uri)) {\n\tperror(\"connect\");\n\treturn -EINVAL;\n }\n zsocket_set_rcvtimeo (z_command, timeout * ZMQ_POLL_MSEC);\n\n return rtapi_ping(instance);\n}\n<|endoftext|>"} {"text":"#include \"library.h\"\n\n#include \n\n#ifdef _WIN32\n#include \n#elif __linux__\n#include \n#else\n#warning file::library is incompatible with target OS!\n#endif\n\nnamespace z\n{\n\tnamespace file\n\t{\n\t\t\/**\n\t\t * \\brief Default empty constructor.\n\t\t *\/\n\t\tlibrary::library()\n\t\t{\n\t\t\tlib_ptr = 0;\n\t\t}\n\n\t\t\/**\n\t\t * \\brief Destructor frees any loaded library.\n\t\t *\/\n\t\tlibrary::~library()\n\t\t{\n#\t\t\tifdef _WIN32\n\t\t\tif (lib_ptr) FreeLibrary((HMODULE)lib_ptr);\n#\t\t\telif __linux__\n\t\t\tif (lib_ptr) dlclose(lib_ptr);\n#\t\t\tendif\n\t\t}\n\n\t\t\/**\n\t\t * \\brief Load a dynamic library with the given file name.\n\t\t *\n\t\t * \\param file_name the path of the library to load.\n\t\t *\n\t\t * \\return \\b True if the library loaded successfully.\n\t\t * \\b False otherwise.\n\t\t *\/\n\t\tbool library::load(const zpath& file_name)\n\t\t{\n#\t\t\tifdef _WIN32\n\t\t\tif (lib_ptr) FreeLibrary((HMODULE)lib_ptr);\n\t\t\tlib_ptr = (void*)LoadLibrary((char*)file_name.cstring());\n\t\t\treturn (bool)lib_ptr;\n#\t\t\telif __linux__\n\t\t\tif (lib_ptr) dlclose(lib_ptr);\n\t\t\tlib_ptr = dlopen((char*)file_name.cstring(), RTLD_NOW);\n\t\t\treturn (bool)lib_ptr;\n#\t\t\telse\n\t\t\treturn false;\n#\t\t\tendif\n\t\t}\n\n\t\t\/**\n\t\t * \\brief Unload the dynamic library.\n\t\t *\n\t\t * \\return \\b False if unable to unload previously\n\t\t * loaded library. \\b True otherwise.\n\t\t *\/\n\t\tbool library::unload()\n\t\t{\n#\t\t\tifdef _WIN32\n\t\t\tif (lib_ptr)\n\t\t\t\treturn (bool)FreeLibrary((HMODULE)lib_ptr);\n\t\t\telse\n\t\t\t\treturn true;\n#\t\t\telif __linux__\n\t\t\tif (lib_ptr)\n\t\t\t\treturn (bool)dlclose(lib_ptr);\n\t\t\telse\n\t\t\t\treturn true;\n#\t\t\telse\n\t\t\treturn true;\n#\t\t\tendif\n\t\t}\n\n\t\t\/**\n\t\t * \\brief Get whether the library has been loaded.\n\t\t *\n\t\t * \\return \\b True if the library has been loaded.\n\t\t * \\b False otherwise.\n\t\t *\n\t\t * \\see bad()\n\t\t *\/\n\t\tbool library::good()\n\t\t{\n\t\t\treturn (bool)lib_ptr;\n\t\t}\n\n\t\t\/**\n\t\t * \\brief Get whether the library has not been loaded.\n\t\t *\n\t\t * \\return \\b False if the library has been loaded.\n\t\t * \\b True otherwise.\n\t\t *\n\t\t * \\see good()\n\t\t *\/\n\t\tbool library::bad()\n\t\t{\n\t\t\treturn !lib_ptr;\n\t\t}\n\n\t\tvoid* library::symbol(const zpath& symbol_name)\n\t\t{\n\t\t\tvoid* symbol_pointer = NULL;\n#\t\t\tifdef _WIN32\n\t\t\tif (lib_ptr)\n\t\t\t\tsymbol_pointer = GetProcAddress((HMODULE)lib_ptr, (char*)symbol_name.cstring());\n#\t\t\telif __linux__\n\t\t\tif(lib_ptr)\n\t\t\t\tsymbol_pointer = dlsym(lib_ptr, (const char*)symbol_name.cstring());\n#\t\t\tendif\n\t\t\treturn symbol_pointer;\n\t\t}\n\n\t\tfunc library::function(const zpath& symbol_name)\n\t\t{\n\t\t\tvoid* symbol_pointer = NULL;\n\t\t\tfunc func_pointer = NULL;\n#\t\t\tifdef _WIN32\n\t\t\tif (lib_ptr)\n\t\t\t\tsymbol_pointer = GetProcAddress((HMODULE)lib_ptr, (const char*)symbol_name.cstring());\n#\t\t\telif __linux__\n\t\t\tif(lib_ptr)\n\t\t\t\tsymbol_pointer = dlsym(lib_ptr, (const char*)symbol_name.cstring());\n#\t\t\tendif\n\t\t\tif (symbol_pointer)\n\t\t\t{\n\t\t\t\tif (sizeof(void*) == 8) \/\/64 bit pointers\n\t\t\t\t\tfunc_pointer = reinterpret_cast(reinterpret_cast(symbol_pointer));\n\t\t\t\telse\n\t\t\t\t\tfunc_pointer = reinterpret_cast(reinterpret_cast(symbol_pointer));\n\t\t\t}\n\t\t\treturn func_pointer;\n\t\t}\n\n\t}\n}\nremoved documentation from library.cpp#include \"library.h\"\n\n#include \n\n#ifdef _WIN32\n#include \n#elif __linux__\n#include \n#else\n#warning file::library is incompatible with target OS!\n#endif\n\nnamespace z\n{\n\tnamespace file\n\t{\n\t\tlibrary::library()\n\t\t{\n\t\t\tlib_ptr = 0;\n\t\t}\n\n\t\tlibrary::~library()\n\t\t{\n#\t\t\tifdef _WIN32\n\t\t\tif (lib_ptr) FreeLibrary((HMODULE)lib_ptr);\n#\t\t\telif __linux__\n\t\t\tif (lib_ptr) dlclose(lib_ptr);\n#\t\t\tendif\n\t\t}\n\n\t\tbool library::load(const zpath& file_name)\n\t\t{\n#\t\t\tifdef _WIN32\n\t\t\tif (lib_ptr) FreeLibrary((HMODULE)lib_ptr);\n\t\t\tlib_ptr = (void*)LoadLibrary((char*)file_name.cstring());\n\t\t\treturn (bool)lib_ptr;\n#\t\t\telif __linux__\n\t\t\tif (lib_ptr) dlclose(lib_ptr);\n\t\t\tlib_ptr = dlopen((char*)file_name.cstring(), RTLD_NOW);\n\t\t\treturn (bool)lib_ptr;\n#\t\t\telse\n\t\t\treturn false;\n#\t\t\tendif\n\t\t}\n\n\t\tbool library::unload()\n\t\t{\n#\t\t\tifdef _WIN32\n\t\t\tif (lib_ptr)\n\t\t\t\treturn (bool)FreeLibrary((HMODULE)lib_ptr);\n\t\t\telse\n\t\t\t\treturn true;\n#\t\t\telif __linux__\n\t\t\tif (lib_ptr)\n\t\t\t\treturn (bool)dlclose(lib_ptr);\n\t\t\telse\n\t\t\t\treturn true;\n#\t\t\telse\n\t\t\treturn true;\n#\t\t\tendif\n\t\t}\n\n\t\tbool library::good()\n\t\t{\n\t\t\treturn (bool)lib_ptr;\n\t\t}\n\n\t\tbool library::bad()\n\t\t{\n\t\t\treturn !lib_ptr;\n\t\t}\n\n\t\tvoid* library::symbol(const zpath& symbol_name)\n\t\t{\n\t\t\tvoid* symbol_pointer = NULL;\n#\t\t\tifdef _WIN32\n\t\t\tif (lib_ptr)\n\t\t\t\tsymbol_pointer = GetProcAddress((HMODULE)lib_ptr, (char*)symbol_name.cstring());\n#\t\t\telif __linux__\n\t\t\tif(lib_ptr)\n\t\t\t\tsymbol_pointer = dlsym(lib_ptr, (const char*)symbol_name.cstring());\n#\t\t\tendif\n\t\t\treturn symbol_pointer;\n\t\t}\n\n\t\tfunc library::function(const zpath& symbol_name)\n\t\t{\n\t\t\tvoid* symbol_pointer = NULL;\n\t\t\tfunc func_pointer = NULL;\n#\t\t\tifdef _WIN32\n\t\t\tif (lib_ptr)\n\t\t\t\tsymbol_pointer = GetProcAddress((HMODULE)lib_ptr, (const char*)symbol_name.cstring());\n#\t\t\telif __linux__\n\t\t\tif(lib_ptr)\n\t\t\t\tsymbol_pointer = dlsym(lib_ptr, (const char*)symbol_name.cstring());\n#\t\t\tendif\n\t\t\tif (symbol_pointer)\n\t\t\t{\n\t\t\t\tif (sizeof(void*) == 8) \/\/64 bit pointers\n\t\t\t\t\tfunc_pointer = reinterpret_cast(reinterpret_cast(symbol_pointer));\n\t\t\t\telse\n\t\t\t\t\tfunc_pointer = reinterpret_cast(reinterpret_cast(symbol_pointer));\n\t\t\t}\n\t\t\treturn func_pointer;\n\t\t}\n\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/*\n * $Log$\n * Revision 1.4 2000\/03\/02 19:54:29 roddey\n * This checkin includes many changes done while waiting for the\n * 1.1.0 code to be finished. I can't list them all here, but a list is\n * available elsewhere.\n *\n * Revision 1.3 2000\/02\/06 07:47:53 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.2 1999\/12\/15 19:49:37 roddey\n * Added second getValue() method which takes a short name for the attribute\n * to get the value for. Just a convenience method.\n *\n * Revision 1.1.1.1 1999\/11\/09 01:08:19 twl\n * Initial checkin\n *\n * Revision 1.2 1999\/11\/08 20:44:44 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include \n#include \n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nVecAttrListImpl::VecAttrListImpl() :\n\n fAdopt(false)\n , fCount(0)\n , fVector(0)\n{\n}\n\nVecAttrListImpl::~VecAttrListImpl()\n{\n \/\/\n \/\/ Note that some compilers can't deal with the fact that the pointer\n \/\/ is to a const object, so we have to cast off the const'ness here!\n \/\/\n if (fAdopt)\n delete (RefVectorOf*)fVector;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Implementation of the attribute list interface\n\/\/ ---------------------------------------------------------------------------\nunsigned int VecAttrListImpl::getLength() const\n{\n return fCount;\n}\n\nconst XMLCh* VecAttrListImpl::getName(const unsigned int index) const\n{\n if (index >= fCount)\n ThrowXML(ArrayIndexOutOfBoundsException, XMLExcepts::AttrList_BadIndex);\n return fVector->elementAt(index)->getName();\n}\n\nconst XMLCh* VecAttrListImpl::getType(const unsigned int index) const\n{\n if (index >= fCount)\n ThrowXML(ArrayIndexOutOfBoundsException, XMLExcepts::AttrList_BadIndex);\n return XMLAttDef::getAttTypeString(fVector->elementAt(index)->getType());\n}\n\nconst XMLCh* VecAttrListImpl::getValue(const unsigned int index) const\n{\n if (index >= fCount)\n ThrowXML(ArrayIndexOutOfBoundsException, XMLExcepts::AttrList_BadIndex);\n return fVector->elementAt(index)->getValue();\n}\n\nconst XMLCh* VecAttrListImpl::getType(const XMLCh* const name) const\n{\n \/\/\n \/\/ Search the vector for the attribute with the given name and return\n \/\/ its type.\n \/\/\n for (unsigned int index = 0; index < fCount; index++)\n {\n const XMLAttr* curElem = fVector->elementAt(index);\n\n if (!XMLString::compareString(curElem->getName(), name))\n return XMLAttDef::getAttTypeString(curElem->getType());\n }\n return 0;\n}\n\nconst XMLCh* VecAttrListImpl::getValue(const XMLCh* const name) const\n{\n \/\/\n \/\/ Search the vector for the attribute with the given name and return\n \/\/ its type.\n \/\/\n for (unsigned int index = 0; index < fCount; index++)\n {\n const XMLAttr* curElem = fVector->elementAt(index);\n\n if (!XMLString::compareString(curElem->getName(), name))\n return curElem->getValue();\n }\n return 0;\n}\n\nconst XMLCh* VecAttrListImpl::getValue(const char* const name) const\n{\n \/\/ Temporarily transcode the name for lookup\n XMLCh* wideName = XMLString::transcode(name);\n ArrayJanitor janName(wideName);\n\n \/\/\n \/\/ Search the vector for the attribute with the given name and return\n \/\/ its type.\n \/\/\n for (unsigned int index = 0; index < fCount; index++)\n {\n const XMLAttr* curElem = fVector->elementAt(index);\n\n if (!XMLString::compareString(curElem->getName(), wideName))\n return curElem->getValue();\n }\n return 0;\n}\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Setter methods\n\/\/ ---------------------------------------------------------------------------\nvoid VecAttrListImpl::setVector(const RefVectorOf* const srcVec\n , const unsigned int count\n , const bool adopt)\n{\n \/\/\n \/\/ Delete the previous vector (if any) if we are adopting. Note that some\n \/\/ compilers can't deal with the fact that the pointer is to a const\n \/\/ object, so we have to cast off the const'ness here!\n \/\/\n if (fAdopt)\n delete (RefVectorOf*)fVector;\n\n fAdopt = fAdopt;\n fCount = count;\n fVector = srcVec;\n}\nFixed #54. Changed self-assignment to now use the parameter value. Reported by Helmut Eiken \/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/*\n * $Log$\n * Revision 1.5 2000\/03\/13 20:19:11 rahulj\n * Fixed #54. Changed self-assignment to now use the parameter value.\n * Reported by Helmut Eiken \n *\n * Revision 1.4 2000\/03\/02 19:54:29 roddey\n * This checkin includes many changes done while waiting for the\n * 1.1.0 code to be finished. I can't list them all here, but a list is\n * available elsewhere.\n *\n * Revision 1.3 2000\/02\/06 07:47:53 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.2 1999\/12\/15 19:49:37 roddey\n * Added second getValue() method which takes a short name for the attribute\n * to get the value for. Just a convenience method.\n *\n * Revision 1.1.1.1 1999\/11\/09 01:08:19 twl\n * Initial checkin\n *\n * Revision 1.2 1999\/11\/08 20:44:44 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include \n#include \n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nVecAttrListImpl::VecAttrListImpl() :\n\n fAdopt(false)\n , fCount(0)\n , fVector(0)\n{\n}\n\nVecAttrListImpl::~VecAttrListImpl()\n{\n \/\/\n \/\/ Note that some compilers can't deal with the fact that the pointer\n \/\/ is to a const object, so we have to cast off the const'ness here!\n \/\/\n if (fAdopt)\n delete (RefVectorOf*)fVector;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Implementation of the attribute list interface\n\/\/ ---------------------------------------------------------------------------\nunsigned int VecAttrListImpl::getLength() const\n{\n return fCount;\n}\n\nconst XMLCh* VecAttrListImpl::getName(const unsigned int index) const\n{\n if (index >= fCount)\n ThrowXML(ArrayIndexOutOfBoundsException, XMLExcepts::AttrList_BadIndex);\n return fVector->elementAt(index)->getName();\n}\n\nconst XMLCh* VecAttrListImpl::getType(const unsigned int index) const\n{\n if (index >= fCount)\n ThrowXML(ArrayIndexOutOfBoundsException, XMLExcepts::AttrList_BadIndex);\n return XMLAttDef::getAttTypeString(fVector->elementAt(index)->getType());\n}\n\nconst XMLCh* VecAttrListImpl::getValue(const unsigned int index) const\n{\n if (index >= fCount)\n ThrowXML(ArrayIndexOutOfBoundsException, XMLExcepts::AttrList_BadIndex);\n return fVector->elementAt(index)->getValue();\n}\n\nconst XMLCh* VecAttrListImpl::getType(const XMLCh* const name) const\n{\n \/\/\n \/\/ Search the vector for the attribute with the given name and return\n \/\/ its type.\n \/\/\n for (unsigned int index = 0; index < fCount; index++)\n {\n const XMLAttr* curElem = fVector->elementAt(index);\n\n if (!XMLString::compareString(curElem->getName(), name))\n return XMLAttDef::getAttTypeString(curElem->getType());\n }\n return 0;\n}\n\nconst XMLCh* VecAttrListImpl::getValue(const XMLCh* const name) const\n{\n \/\/\n \/\/ Search the vector for the attribute with the given name and return\n \/\/ its type.\n \/\/\n for (unsigned int index = 0; index < fCount; index++)\n {\n const XMLAttr* curElem = fVector->elementAt(index);\n\n if (!XMLString::compareString(curElem->getName(), name))\n return curElem->getValue();\n }\n return 0;\n}\n\nconst XMLCh* VecAttrListImpl::getValue(const char* const name) const\n{\n \/\/ Temporarily transcode the name for lookup\n XMLCh* wideName = XMLString::transcode(name);\n ArrayJanitor janName(wideName);\n\n \/\/\n \/\/ Search the vector for the attribute with the given name and return\n \/\/ its type.\n \/\/\n for (unsigned int index = 0; index < fCount; index++)\n {\n const XMLAttr* curElem = fVector->elementAt(index);\n\n if (!XMLString::compareString(curElem->getName(), wideName))\n return curElem->getValue();\n }\n return 0;\n}\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Setter methods\n\/\/ ---------------------------------------------------------------------------\nvoid VecAttrListImpl::setVector(const RefVectorOf* const srcVec\n , const unsigned int count\n , const bool adopt)\n{\n \/\/\n \/\/ Delete the previous vector (if any) if we are adopting. Note that some\n \/\/ compilers can't deal with the fact that the pointer is to a const\n \/\/ object, so we have to cast off the const'ness here!\n \/\/\n if (fAdopt)\n delete (RefVectorOf*)fVector;\n\n fAdopt = adopt;\n fCount = count;\n fVector = srcVec;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2007-2022 CM4all GmbH\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"YamlSubstIstream.hxx\"\n#include \"SubstIstream.hxx\"\n#include \"UnusedPtr.hxx\"\n#include \"pool\/pool.hxx\"\n#include \"util\/IterableSplitString.hxx\"\n#include \"util\/RuntimeError.hxx\"\n#include \"util\/StringView.hxx\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nstatic YAML::Node\nResolveYamlPathSegment(const YAML::Node &parent, StringView segment)\n{\n\tif (parent.IsMap()) {\n\t\tauto result = parent[std::string(segment.data, segment.size).c_str()];\n\t\tif (!result)\n\t\t\tthrow FormatRuntimeError(\"YAML path segment '%.*s' does not exist\",\n\t\t\t\t\t\t int(segment.size), segment.data);\n\n\t\treturn result;\n\t} else\n\t\tthrow FormatRuntimeError(\"Failed to resolve YAML path segment '%.*s'\",\n\t\t\t\t\t int(segment.size), segment.data);\n}\n\nstatic YAML::Node\nResolveYamlPath(YAML::Node node, StringView path)\n{\n\tfor (StringView s : IterableSplitString(path, '.')) {\n\t\tif (s.empty())\n\t\t\tcontinue;\n\n\t\tnode = ResolveYamlPathSegment(node, s);\n\t}\n\n\treturn node;\n}\n\nstatic YAML::Node\nResolveYamlMap(YAML::Node node, StringView path)\n{\n\tnode = ResolveYamlPath(node, path);\n\tif (!node.IsMap())\n\t\tthrow path.empty()\n\t\t\t? std::runtime_error(\"Not a YAML map\")\n\t\t\t: FormatRuntimeError(\"Path '%.*s' is not a YAML map\",\n\t\t\t\t\t int(path.size), path.data);\n\n\treturn node;\n}\n\nstatic auto\nMakePrefix(bool alt_syntax, const char *_prefix)\n{\n\tstd::string prefix = alt_syntax ? \"{[\" : \"{%\";\n\tif (_prefix != nullptr)\n\t\tprefix += _prefix;\n\treturn prefix;\n}\n\nstatic void\nLoadYamlMap(struct pool &pool, SubstTree &tree,\n\t const std::string &prefix,\n\t const std::string &suffix,\n\t const YAML::Node &node) noexcept\n{\n\tassert(node.IsMap());\n\n\tfor (const auto &i : node) {\n\t\tif (!i.first.IsScalar())\n\t\t\tcontinue;\n\n\t\tif (i.second.IsScalar()) {\n\t\t\tconst auto name = prefix + i.first.as() + suffix;\n\t\t\tconst auto value = i.second.as();\n\t\t\ttree.Add(pool, p_strndup(&pool, name.data(), name.length()),\n\t\t\t\t {p_strndup(&pool, value.data(), value.length()), value.length()});\n\t\t} else if (i.second.IsMap()) {\n\t\t\tLoadYamlMap(pool, tree, prefix + i.first.as() + \".\",\n\t\t\t\t suffix,\n\t\t\t\t i.second);\n\t\t}\n\t}\n}\n\nstatic SubstTree\nLoadYamlMap(struct pool &pool, bool alt_syntax, const char *_prefix,\n\t const YAML::Node &node) noexcept\n{\n\tassert(node.IsMap());\n\n\tconst auto prefix = MakePrefix(alt_syntax, _prefix);\n\tconst std::string suffix(alt_syntax ? \"]}\" : \"%}\");\n\n\tSubstTree tree;\n\tLoadYamlMap(pool, tree, prefix, suffix, node);\n\treturn tree;\n}\n\nUnusedIstreamPtr\nNewYamlSubstIstream(struct pool &pool, UnusedIstreamPtr input,\n\t\t bool alt_syntax,\n\t\t const char *prefix,\n\t\t const YAML::Node &yaml_node, const char *yaml_map_path)\n{\n\treturn istream_subst_new(&pool, std::move(input),\n\t\t\t\t LoadYamlMap(pool, alt_syntax, prefix,\n\t\t\t\t\t ResolveYamlMap(yaml_node,\n\t\t\t\t\t\t\t yaml_map_path)));\n}\n\nstatic SubstTree\nLoadYamlFile(struct pool &pool, bool alt_syntax,\n\t const char *prefix,\n\t const char *file_path, const char *map_path)\n\ttry {\n\t\treturn LoadYamlMap(pool, alt_syntax, prefix,\n\t\t\t\t ResolveYamlMap(YAML::LoadFile(file_path), map_path));\n\t} catch (...) {\n\t\tstd::throw_with_nested(FormatRuntimeError(\"Failed to load YAML file '%s'\",\n\t\t\t\t\t\t\t file_path));\n\t}\n\nUnusedIstreamPtr\nNewYamlSubstIstream(struct pool &pool, UnusedIstreamPtr input,\n\t\t bool alt_syntax,\n\t\t const char *prefix,\n\t\t const char *yaml_file, const char *yaml_map_path)\n{\n\treturn istream_subst_new(&pool, std::move(input),\n\t\t\t\t LoadYamlFile(pool, alt_syntax, prefix,\n\t\t\t\t\t yaml_file, yaml_map_path));\n}\nistream\/YamlSubst: use std::string_view\/*\n * Copyright 2007-2022 CM4all GmbH\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"YamlSubstIstream.hxx\"\n#include \"SubstIstream.hxx\"\n#include \"UnusedPtr.hxx\"\n#include \"pool\/pool.hxx\"\n#include \"util\/IterableSplitString.hxx\"\n#include \"util\/RuntimeError.hxx\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nstatic YAML::Node\nResolveYamlPathSegment(const YAML::Node &parent, std::string_view segment)\n{\n\tif (parent.IsMap()) {\n\t\tauto result = parent[std::string{segment}.c_str()];\n\t\tif (!result)\n\t\t\tthrow FormatRuntimeError(\"YAML path segment '%.*s' does not exist\",\n\t\t\t\t\t\t int(segment.size()), segment.data());\n\n\t\treturn result;\n\t} else\n\t\tthrow FormatRuntimeError(\"Failed to resolve YAML path segment '%.*s'\",\n\t\t\t\t\t int(segment.size()), segment.data());\n}\n\nstatic YAML::Node\nResolveYamlPath(YAML::Node node, std::string_view path)\n{\n\tfor (const auto s : IterableSplitString(path, '.')) {\n\t\tif (s.empty())\n\t\t\tcontinue;\n\n\t\tnode = ResolveYamlPathSegment(node, s);\n\t}\n\n\treturn node;\n}\n\nstatic YAML::Node\nResolveYamlMap(YAML::Node node, std::string_view path)\n{\n\tnode = ResolveYamlPath(node, path);\n\tif (!node.IsMap())\n\t\tthrow path.empty()\n\t\t\t? std::runtime_error(\"Not a YAML map\")\n\t\t\t: FormatRuntimeError(\"Path '%.*s' is not a YAML map\",\n\t\t\t\t\t int(path.size()), path.data());\n\n\treturn node;\n}\n\nstatic auto\nMakePrefix(bool alt_syntax, const char *_prefix)\n{\n\tstd::string prefix = alt_syntax ? \"{[\" : \"{%\";\n\tif (_prefix != nullptr)\n\t\tprefix += _prefix;\n\treturn prefix;\n}\n\nstatic void\nLoadYamlMap(struct pool &pool, SubstTree &tree,\n\t const std::string &prefix,\n\t const std::string &suffix,\n\t const YAML::Node &node) noexcept\n{\n\tassert(node.IsMap());\n\n\tfor (const auto &i : node) {\n\t\tif (!i.first.IsScalar())\n\t\t\tcontinue;\n\n\t\tif (i.second.IsScalar()) {\n\t\t\tconst auto name = prefix + i.first.as() + suffix;\n\t\t\tconst auto value = i.second.as();\n\t\t\ttree.Add(pool, p_strndup(&pool, name.data(), name.length()),\n\t\t\t\t {p_strndup(&pool, value.data(), value.length()), value.length()});\n\t\t} else if (i.second.IsMap()) {\n\t\t\tLoadYamlMap(pool, tree, prefix + i.first.as() + \".\",\n\t\t\t\t suffix,\n\t\t\t\t i.second);\n\t\t}\n\t}\n}\n\nstatic SubstTree\nLoadYamlMap(struct pool &pool, bool alt_syntax, const char *_prefix,\n\t const YAML::Node &node) noexcept\n{\n\tassert(node.IsMap());\n\n\tconst auto prefix = MakePrefix(alt_syntax, _prefix);\n\tconst std::string suffix(alt_syntax ? \"]}\" : \"%}\");\n\n\tSubstTree tree;\n\tLoadYamlMap(pool, tree, prefix, suffix, node);\n\treturn tree;\n}\n\nUnusedIstreamPtr\nNewYamlSubstIstream(struct pool &pool, UnusedIstreamPtr input,\n\t\t bool alt_syntax,\n\t\t const char *prefix,\n\t\t const YAML::Node &yaml_node, const char *yaml_map_path)\n{\n\treturn istream_subst_new(&pool, std::move(input),\n\t\t\t\t LoadYamlMap(pool, alt_syntax, prefix,\n\t\t\t\t\t ResolveYamlMap(yaml_node,\n\t\t\t\t\t\t\t yaml_map_path)));\n}\n\nstatic SubstTree\nLoadYamlFile(struct pool &pool, bool alt_syntax,\n\t const char *prefix,\n\t const char *file_path, const char *map_path)\n\ttry {\n\t\treturn LoadYamlMap(pool, alt_syntax, prefix,\n\t\t\t\t ResolveYamlMap(YAML::LoadFile(file_path), map_path));\n\t} catch (...) {\n\t\tstd::throw_with_nested(FormatRuntimeError(\"Failed to load YAML file '%s'\",\n\t\t\t\t\t\t\t file_path));\n\t}\n\nUnusedIstreamPtr\nNewYamlSubstIstream(struct pool &pool, UnusedIstreamPtr input,\n\t\t bool alt_syntax,\n\t\t const char *prefix,\n\t\t const char *yaml_file, const char *yaml_map_path)\n{\n\treturn istream_subst_new(&pool, std::move(input),\n\t\t\t\t LoadYamlFile(pool, alt_syntax, prefix,\n\t\t\t\t\t yaml_file, yaml_map_path));\n}\n<|endoftext|>"} {"text":"fix compilation errors<|endoftext|>"} {"text":"Bump version<|endoftext|>"} {"text":"exception message improved<|endoftext|>"} {"text":"\n\/\/\n\/\/ A WebAssembly shell, loads a .wast file (WebAssembly in S-Expression format) and executes it.\n\/\/\n\n#include \n\n#include \"wasm-s-parser.h\"\n#include \"wasm-interpreter.h\"\n\nusing namespace cashew;\nusing namespace wasm;\n\nIString ASSERT_RETURN(\"assert_return\"),\n ASSERT_TRAP(\"assert_trap\"),\n PRINT(\"print\"),\n INVOKE(\"invoke\");\n\n\/\/\n\/\/ Implementation of the shell interpreter execution environment\n\/\/\n\nstruct ShellExternalInterface : ModuleInstance::ExternalInterface {\n char *memory;\n size_t memorySize;\n\n ShellExternalInterface() : memory(nullptr) {}\n\n void init(Module& wasm) override {\n memory = new char[wasm.memory.initial];\n memorySize = wasm.memory.initial;\n \/\/ apply memory segments\n for (auto segment : wasm.memory.segments) {\n memcpy(memory + segment.offset, segment.data, segment.size);\n }\n }\n\n Literal callImport(Import *import, ModuleInstance::LiteralList& arguments) override {\n if (import->name == PRINT) {\n for (auto argument : arguments) {\n std::cout << argument << ' ';\n }\n std::cout << '\\n';\n return Literal();\n }\n std::cout << \"callImport \" << import->name.str << \"\\n\";\n abort();\n }\n\n Literal load(Load* load, size_t addr) override {\n \/\/ ignore align - assume we are on x86 etc. which does that\n switch (load->type) {\n case i32: {\n switch (load->bytes) {\n case 1: return load->signed_ ? (int32_t)((int8_t*)memory)[addr] : (int32_t)((uint8_t*)memory)[addr];\n case 2: return load->signed_ ? (int32_t)((int16_t*)memory)[addr] : (int32_t)((uint16_t*)memory)[addr];\n case 4: return load->signed_ ? (int32_t)((int32_t*)memory)[addr] : (int32_t)((uint32_t*)memory)[addr];\n default: abort();\n }\n break;\n }\n case i64: {\n switch (load->bytes) {\n case 1: return load->signed_ ? (int64_t)((int8_t*)memory)[addr] : (int64_t)((uint8_t*)memory)[addr];\n case 2: return load->signed_ ? (int64_t)((int16_t*)memory)[addr] : (int64_t)((uint16_t*)memory)[addr];\n case 4: return load->signed_ ? (int64_t)((int32_t*)memory)[addr] : (int64_t)((uint32_t*)memory)[addr];\n case 8: return load->signed_ ? (int64_t)((int64_t*)memory)[addr] : (int64_t)((uint64_t*)memory)[addr];\n default: abort();\n }\n break;\n }\n case f32: return ((float*)memory)[addr];\n case f64: return ((double*)memory)[addr];\n default: abort();\n }\n }\n\n void store(Store* store, size_t addr, Literal value) override {\n \/\/ ignore align - assume we are on x86 etc. which does that\n switch (store->type) {\n case i32: {\n switch (store->bytes) {\n case 1: ((int8_t*)memory)[addr] = value.geti32(); break;\n case 2: ((int16_t*)memory)[addr] = value.geti32(); break;\n case 4: ((int32_t*)memory)[addr] = value.geti32(); break;\n case 8: ((int64_t*)memory)[addr] = value.geti64(); break;\n default: abort();\n }\n break;\n }\n case f32: ((float*)memory)[addr] = value.getf32(); break;\n case f64: ((double*)memory)[addr] = value.getf64(); break;\n default: abort();\n }\n }\n\n jmp_buf trapState;\n\n void trap() override {\n longjmp(trapState, 1);\n }\n};\n\nint main(int argc, char **argv) {\n debug = getenv(\"WASM_SHELL_DEBUG\") ? getenv(\"WASM_SHELL_DEBUG\")[0] - '0' : 0;\n\n char *infile = argv[1];\n bool print_wasm = argc >= 3; \/\/ second arg means print it out\n\n if (debug) std::cerr << \"loading '\" << infile << \"'...\\n\";\n FILE *f = fopen(argv[1], \"r\");\n assert(f);\n fseek(f, 0, SEEK_END);\n int size = ftell(f);\n char *input = new char[size+1];\n rewind(f);\n int num = fread(input, 1, size, f);\n \/\/ On Windows, ftell() gives the byte position (\\r\\n counts as two bytes), but when\n \/\/ reading, fread() returns the number of characters read (\\r\\n is read as one char \\n, and counted as one),\n \/\/ so return value of fread can be less than size reported by ftell, and that is normal.\n assert((num > 0 || size == 0) && num <= size);\n fclose(f);\n input[num] = 0;\n\n if (debug) std::cerr << \"parsing text to s-expressions...\\n\";\n SExpressionParser parser(input);\n Element& root = *parser.root;\n if (debug) std::cout << root << '\\n';\n\n \/\/ A .wast may have multiple modules, with some asserts after them\n size_t i = 0;\n while (i < root.size()) {\n if (debug) std::cerr << \"parsing s-expressions to wasm...\\n\";\n Module wasm;\n SExpressionWasmBuilder builder(wasm, *root[i]);\n i++;\n\n auto interface = new ShellExternalInterface();\n auto instance = new ModuleInstance(wasm, interface);\n\n if (print_wasm) {\n if (debug) std::cerr << \"printing...\\n\";\n std::cout << wasm;\n }\n\n \/\/ run asserts\n while (i < root.size()) {\n Element& curr = *root[i];\n IString id = curr[0]->str();\n if (id == MODULE) break;\n Colors::red(std::cerr);\n std::cerr << i << '\/' << (root.size()-1);\n Colors::green(std::cerr);\n std::cerr << \" CHECKING: \";\n Colors::normal(std::cerr);\n std::cerr << curr << '\\n';\n Element& invoke = *curr[1];\n assert(invoke[0]->str() == INVOKE);\n IString name = invoke[1]->str();\n ModuleInstance::LiteralList arguments;\n for (size_t j = 2; j < invoke.size(); j++) {\n Expression* argument = builder.parseExpression(*invoke[2]);\n arguments.push_back(argument->dyn_cast()->value);\n }\n bool trapped = false;\n Literal result;\n if (setjmp(interface->trapState) == 0) {\n result = instance->callFunction(name, arguments);\n } else {\n trapped = true;\n }\n if (id == ASSERT_RETURN) {\n assert(!trapped);\n Literal expected;\n if (curr.size() >= 3) {\n expected = builder.parseExpression(*curr[2])->dyn_cast()->value;\n }\n std::cerr << \"seen \" << result << \", expected \" << expected << '\\n';\n assert(expected == result);\n }\n if (id == ASSERT_TRAP) assert(trapped);\n i++;\n }\n }\n\n if (debug) std::cerr << \"done.\\n\";\n}\n\ni64 stores in shell\n\/\/\n\/\/ A WebAssembly shell, loads a .wast file (WebAssembly in S-Expression format) and executes it.\n\/\/\n\n#include \n\n#include \"wasm-s-parser.h\"\n#include \"wasm-interpreter.h\"\n\nusing namespace cashew;\nusing namespace wasm;\n\nIString ASSERT_RETURN(\"assert_return\"),\n ASSERT_TRAP(\"assert_trap\"),\n PRINT(\"print\"),\n INVOKE(\"invoke\");\n\n\/\/\n\/\/ Implementation of the shell interpreter execution environment\n\/\/\n\nstruct ShellExternalInterface : ModuleInstance::ExternalInterface {\n char *memory;\n size_t memorySize;\n\n ShellExternalInterface() : memory(nullptr) {}\n\n void init(Module& wasm) override {\n memory = new char[wasm.memory.initial];\n memorySize = wasm.memory.initial;\n \/\/ apply memory segments\n for (auto segment : wasm.memory.segments) {\n memcpy(memory + segment.offset, segment.data, segment.size);\n }\n }\n\n Literal callImport(Import *import, ModuleInstance::LiteralList& arguments) override {\n if (import->name == PRINT) {\n for (auto argument : arguments) {\n std::cout << argument << ' ';\n }\n std::cout << '\\n';\n return Literal();\n }\n std::cout << \"callImport \" << import->name.str << \"\\n\";\n abort();\n }\n\n Literal load(Load* load, size_t addr) override {\n \/\/ ignore align - assume we are on x86 etc. which does that\n switch (load->type) {\n case i32: {\n switch (load->bytes) {\n case 1: return load->signed_ ? (int32_t)((int8_t*)memory)[addr] : (int32_t)((uint8_t*)memory)[addr];\n case 2: return load->signed_ ? (int32_t)((int16_t*)memory)[addr] : (int32_t)((uint16_t*)memory)[addr];\n case 4: return load->signed_ ? (int32_t)((int32_t*)memory)[addr] : (int32_t)((uint32_t*)memory)[addr];\n default: abort();\n }\n break;\n }\n case i64: {\n switch (load->bytes) {\n case 1: return load->signed_ ? (int64_t)((int8_t*)memory)[addr] : (int64_t)((uint8_t*)memory)[addr];\n case 2: return load->signed_ ? (int64_t)((int16_t*)memory)[addr] : (int64_t)((uint16_t*)memory)[addr];\n case 4: return load->signed_ ? (int64_t)((int32_t*)memory)[addr] : (int64_t)((uint32_t*)memory)[addr];\n case 8: return load->signed_ ? (int64_t)((int64_t*)memory)[addr] : (int64_t)((uint64_t*)memory)[addr];\n default: abort();\n }\n break;\n }\n case f32: return ((float*)memory)[addr];\n case f64: return ((double*)memory)[addr];\n default: abort();\n }\n }\n\n void store(Store* store, size_t addr, Literal value) override {\n \/\/ ignore align - assume we are on x86 etc. which does that\n switch (store->type) {\n case i32: {\n switch (store->bytes) {\n case 1: ((int8_t*)memory)[addr] = value.geti32(); break;\n case 2: ((int16_t*)memory)[addr] = value.geti32(); break;\n case 4: ((int32_t*)memory)[addr] = value.geti32(); break;\n default: abort();\n }\n break;\n }\n case i64: {\n switch (store->bytes) {\n case 1: ((int8_t*)memory)[addr] = value.geti64(); break;\n case 2: ((int16_t*)memory)[addr] = value.geti64(); break;\n case 4: ((int32_t*)memory)[addr] = value.geti64(); break;\n case 8: ((int64_t*)memory)[addr] = value.geti64(); break;\n default: abort();\n }\n break;\n }\n case f32: ((float*)memory)[addr] = value.getf32(); break;\n case f64: ((double*)memory)[addr] = value.getf64(); break;\n default: abort();\n }\n }\n\n jmp_buf trapState;\n\n void trap() override {\n longjmp(trapState, 1);\n }\n};\n\nint main(int argc, char **argv) {\n debug = getenv(\"WASM_SHELL_DEBUG\") ? getenv(\"WASM_SHELL_DEBUG\")[0] - '0' : 0;\n\n char *infile = argv[1];\n bool print_wasm = argc >= 3; \/\/ second arg means print it out\n\n if (debug) std::cerr << \"loading '\" << infile << \"'...\\n\";\n FILE *f = fopen(argv[1], \"r\");\n assert(f);\n fseek(f, 0, SEEK_END);\n int size = ftell(f);\n char *input = new char[size+1];\n rewind(f);\n int num = fread(input, 1, size, f);\n \/\/ On Windows, ftell() gives the byte position (\\r\\n counts as two bytes), but when\n \/\/ reading, fread() returns the number of characters read (\\r\\n is read as one char \\n, and counted as one),\n \/\/ so return value of fread can be less than size reported by ftell, and that is normal.\n assert((num > 0 || size == 0) && num <= size);\n fclose(f);\n input[num] = 0;\n\n if (debug) std::cerr << \"parsing text to s-expressions...\\n\";\n SExpressionParser parser(input);\n Element& root = *parser.root;\n if (debug) std::cout << root << '\\n';\n\n \/\/ A .wast may have multiple modules, with some asserts after them\n size_t i = 0;\n while (i < root.size()) {\n if (debug) std::cerr << \"parsing s-expressions to wasm...\\n\";\n Module wasm;\n SExpressionWasmBuilder builder(wasm, *root[i]);\n i++;\n\n auto interface = new ShellExternalInterface();\n auto instance = new ModuleInstance(wasm, interface);\n\n if (print_wasm) {\n if (debug) std::cerr << \"printing...\\n\";\n std::cout << wasm;\n }\n\n \/\/ run asserts\n while (i < root.size()) {\n Element& curr = *root[i];\n IString id = curr[0]->str();\n if (id == MODULE) break;\n Colors::red(std::cerr);\n std::cerr << i << '\/' << (root.size()-1);\n Colors::green(std::cerr);\n std::cerr << \" CHECKING: \";\n Colors::normal(std::cerr);\n std::cerr << curr << '\\n';\n Element& invoke = *curr[1];\n assert(invoke[0]->str() == INVOKE);\n IString name = invoke[1]->str();\n ModuleInstance::LiteralList arguments;\n for (size_t j = 2; j < invoke.size(); j++) {\n Expression* argument = builder.parseExpression(*invoke[2]);\n arguments.push_back(argument->dyn_cast()->value);\n }\n bool trapped = false;\n Literal result;\n if (setjmp(interface->trapState) == 0) {\n result = instance->callFunction(name, arguments);\n } else {\n trapped = true;\n }\n if (id == ASSERT_RETURN) {\n assert(!trapped);\n Literal expected;\n if (curr.size() >= 3) {\n expected = builder.parseExpression(*curr[2])->dyn_cast()->value;\n }\n std::cerr << \"seen \" << result << \", expected \" << expected << '\\n';\n assert(expected == result);\n }\n if (id == ASSERT_TRAP) assert(trapped);\n i++;\n }\n }\n\n if (debug) std::cerr << \"done.\\n\";\n}\n\n<|endoftext|>"} {"text":"* 修复识别不了canvas.fillStyle(\"#ffff0000\"); 这种四个字节的颜色格式的问题<|endoftext|>"} {"text":"\/\/ @(#)root\/base:$Id$\n\/\/ Author: Fons Rademakers 29\/07\/95\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TStorage \/\/\n\/\/ \/\/\n\/\/ Storage manager. The storage manager works best in conjunction with \/\/\n\/\/ the custom ROOT new and delete operators defined in the file \/\/\n\/\/ NewDelete.cxx (libNew.so). Only when using the custom allocation \/\/\n\/\/ operators will memory usage statistics be gathered using the \/\/\n\/\/ TStorage EnterStat(), RemoveStat(), etc. functions. \/\/\n\/\/ Memory checking is by default enabled (when using libNew.so) and \/\/\n\/\/ usage statistics is gathered. Using the resource (in .rootrc): \/\/\n\/\/ Root.MemStat one can toggle statistics gathering on or off. More \/\/\n\/\/ specifically on can trap the allocation of a block of memory of a \/\/\n\/\/ certain size. This can be specified using the resource: \/\/\n\/\/ Root.MemStat.size, using the resource Root.MemStat.cnt one can \/\/\n\/\/ specify after how many allocations of this size the trap should \/\/\n\/\/ occur. \/\/\n\/\/ Set the compile option R__NOSTATS to de-activate all memory checking \/\/\n\/\/ and statistics gathering in the system. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n\n#include \"TROOT.h\"\n#include \"TObjectTable.h\"\n#include \"TError.h\"\n#include \"TString.h\"\n#include \"TVirtualMutex.h\"\n#include \"TInterpreter.h\"\n\n#if !defined(R__NOSTATS)\n# define MEM_DEBUG\n# define MEM_STAT\n# define MEM_CHECKOBJECTPOINTERS\n#endif\n\n#if defined(MEM_STAT) && !defined(MEM_DEBUG)\n# define MEM_DEBUG\n#endif\n\n#ifdef MEM_DEBUG\n# ifdef R__B64\n# define storage_size(p) ((size_t)(((size_t*)p)[-1]))\n# else\n# define storage_size(p) ((size_t)(((int*)p)[-2]))\n# endif\n#else\n# define storage_size(p) ((size_t)0)\n#endif\n\n#define PVOID (-1)\n\nULong_t TStorage::fgHeapBegin = (ULong_t)-1L;\nULong_t TStorage::fgHeapEnd;\nsize_t TStorage::fgMaxBlockSize;\nFreeHookFun_t TStorage::fgFreeHook;\nvoid *TStorage::fgFreeHookData;\nReAllocFun_t TStorage::fgReAllocHook;\nReAllocCFun_t TStorage::fgReAllocCHook;\nBool_t TStorage::fgHasCustomNewDelete;\n\n\nClassImp(TStorage)\n\n\/\/------------------------------------------------------------------------------\n\nstatic const char *gSpaceErr = \"storage exhausted\";\n\nconst size_t kObjMaxSize = 10024;\n\nstatic Bool_t gMemStatistics;\nstatic Int_t gAllocated[kObjMaxSize], gFreed[kObjMaxSize];\nstatic Int_t gAllocatedTotal, gFreedTotal;\nstatic void **gTraceArray = 0;\nstatic Int_t gTraceCapacity = 10, gTraceIndex = 0,\n gMemSize = -1, gMemIndex = -1;\n\n\n\/\/______________________________________________________________________________\nvoid TStorage::EnterStat(size_t size, void *p)\n{\n \/\/ Register a memory allocation operation. If desired one can trap an\n \/\/ allocation of a certain size in case one tries to find a memory\n \/\/ leak of that particular size. This function is only called via\n \/\/ the ROOT custom new operators.\n\n TStorage::SetMaxBlockSize(TMath::Max(TStorage::GetMaxBlockSize(), size));\n\n if (!gMemStatistics) return;\n\n if ((Int_t)size == gMemSize) {\n if (gTraceIndex == gMemIndex)\n Fatal(\"EnterStat\", \"trapped allocation %d\", gMemIndex);\n\n if (!gTraceArray)\n gTraceArray = (void**) malloc(sizeof(void*)*gTraceCapacity);\n\n if (gTraceIndex >= gTraceCapacity) {\n gTraceCapacity = gTraceCapacity*2;\n gTraceArray = (void**) realloc(gTraceArray, sizeof(void*)*gTraceCapacity);\n }\n gTraceArray[gTraceIndex++] = p;\n }\n if (size >= kObjMaxSize)\n gAllocated[kObjMaxSize-1]++;\n else\n gAllocated[size]++;\n gAllocatedTotal += size;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::RemoveStat(void *vp)\n{\n \/\/ Register a memory free operation. This function is only called via\n \/\/ the custom ROOT delete operator.\n\n if (!gMemStatistics) return;\n\n size_t size = storage_size(vp);\n if ((Int_t)size == gMemSize) {\n for (int i = 0; i < gTraceIndex; i++)\n if (gTraceArray[i] == vp) {\n gTraceArray[i] = 0;\n break;\n }\n }\n if (size >= kObjMaxSize)\n gFreed[kObjMaxSize-1]++;\n else\n gFreed[size]++;\n gFreedTotal += size;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::Alloc(size_t size)\n{\n \/\/ Allocate a block of memory, that later can be resized using\n \/\/ TStorage::ReAlloc().\n\n static const char *where = \"TStorage::Alloc\";\n\n#ifndef WIN32\n void *vp = ::operator new[](size);\n#else\n void *vp = ::operator new(size);\n#endif\n if (vp == 0)\n Fatal(where, \"%s\", gSpaceErr);\n\n return vp;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::Dealloc(void *ptr)\n{\n \/\/ De-allocate block of memory, that was allocated via TStorage::Alloc().\n\n#ifndef WIN32\n ::operator delete[](ptr);\n#else\n ::operator delete(ptr);\n#endif\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ReAlloc(void *ovp, size_t size)\n{\n \/\/ Reallocate (i.e. resize) block of memory.\n\n \/\/ Needs to be protected by global mutex\n R__LOCKGUARD(gGlobalMutex);\n\n if (fgReAllocHook && fgHasCustomNewDelete && !TROOT::MemCheck())\n return (*fgReAllocHook)(ovp, size);\n\n static const char *where = \"TStorage::ReAlloc\";\n\n#ifndef WIN32\n void *vp = ::operator new[](size);\n#else\n void *vp = ::operator new(size);\n#endif\n if (vp == 0)\n Fatal(where, \"%s\", gSpaceErr);\n\n if (ovp == 0)\n return vp;\n\n memmove(vp, ovp, size);\n#ifndef WIN32\n ::operator delete[](ovp);\n#else\n ::operator delete(ovp);\n#endif\n return vp;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ReAlloc(void *ovp, size_t size, size_t oldsize)\n{\n \/\/ Reallocate (i.e. resize) block of memory. Checks if current size is\n \/\/ equal to oldsize. If not memory was overwritten.\n\n \/\/ Needs to be protected by global mutex\n R__LOCKGUARD(gGlobalMutex);\n\n if (fgReAllocCHook && fgHasCustomNewDelete && !TROOT::MemCheck())\n return (*fgReAllocCHook)(ovp, size, oldsize);\n\n static const char *where = \"TStorage::ReAlloc\";\n\n if (oldsize == size)\n return ovp;\n\n#ifndef WIN32\n void *vp = ::operator new[](size);\n#else\n void *vp = ::operator new(size);\n#endif\n if (vp == 0)\n Fatal(where, \"%s\", gSpaceErr);\n\n if (ovp == 0)\n return vp;\n\n if (size > oldsize) {\n memcpy(vp, ovp, oldsize);\n memset((char*)vp+oldsize, 0, size-oldsize);\n } else\n memcpy(vp, ovp, size);\n#ifndef WIN32\n ::operator delete[](ovp);\n#else\n ::operator delete(ovp);\n#endif\n return vp;\n}\n\n\/\/______________________________________________________________________________\nchar *TStorage::ReAllocChar(char *ovp, size_t size, size_t oldsize)\n{\n \/\/ Reallocate (i.e. resize) array of chars. Size and oldsize are\n \/\/ in number of chars.\n\n \/\/ Needs to be protected by global mutex\n R__LOCKGUARD(gGlobalMutex);\n\n static const char *where = \"TStorage::ReAllocChar\";\n\n char *vp;\n if (ovp == 0) {\n vp = new char[size];\n if (vp == 0)\n Fatal(where, \"%s\", gSpaceErr);\n return vp;\n }\n if (oldsize == size)\n return ovp;\n\n vp = new char[size];\n if (vp == 0)\n Fatal(where, \"%s\", gSpaceErr);\n if (size > oldsize) {\n memcpy(vp, ovp, oldsize);\n memset((char*)vp+oldsize, 0, size-oldsize);\n } else\n memcpy(vp, ovp, size);\n delete [] ovp;\n return vp;\n}\n\n\/\/______________________________________________________________________________\nInt_t *TStorage::ReAllocInt(Int_t *ovp, size_t size, size_t oldsize)\n{\n \/\/ Reallocate (i.e. resize) array of integers. Size and oldsize are\n \/\/ number of integers (not number of bytes).\n\n \/\/ Needs to be protected by global mutex\n R__LOCKGUARD(gGlobalMutex);\n\n static const char *where = \"TStorage::ReAllocInt\";\n\n Int_t *vp;\n if (ovp == 0) {\n vp = new Int_t[size];\n if (vp == 0)\n Fatal(where, \"%s\", gSpaceErr);\n return vp;\n }\n if (oldsize == size)\n return ovp;\n\n vp = new Int_t[size];\n if (vp == 0)\n Fatal(where, \"%s\", gSpaceErr);\n if (size > oldsize) {\n memcpy(vp, ovp, oldsize*sizeof(Int_t));\n memset((Int_t*)vp+oldsize, 0, (size-oldsize)*sizeof(Int_t));\n } else\n memcpy(vp, ovp, size*sizeof(Int_t));\n delete [] ovp;\n return vp;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ObjectAlloc(size_t sz)\n{\n \/\/ Used to allocate a TObject on the heap (via TObject::operator new()).\n \/\/ Directly after this routine one can call (in the TObject ctor)\n \/\/ TStorage::IsOnHeap() to find out if the just created object is on\n \/\/ the heap.\n\n \/\/ Needs to be protected by global mutex\n R__LOCKGUARD(gGlobalMutex);\n\n ULong_t space = (ULong_t) ::operator new(sz);\n AddToHeap(space, space+sz);\n return (void*) space;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ObjectAlloc(size_t , void *vp)\n{\n \/\/ Used to allocate a TObject on the heap (via TObject::operator new(size_t,void*))\n \/\/ in position vp. vp is already allocated (maybe on heap, maybe on\n \/\/ stack) so just return.\n\n return vp;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::ObjectDealloc(void *vp)\n{\n \/\/ Used to deallocate a TObject on the heap (via TObject::operator delete()).\n\n ::operator delete(vp);\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::ObjectDealloc(void *vp, void *ptr)\n{\n \/\/ Used to deallocate a TObject on the heap (via TObject::operator delete(void*,void*)).\n\n if (vp && ptr) { }\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetFreeHook(FreeHookFun_t fh, void *data)\n{\n \/\/ Set a free handler.\n\n fgFreeHook = fh;\n fgFreeHookData = data;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetReAllocHooks(ReAllocFun_t rh1, ReAllocCFun_t rh2)\n{\n \/\/ Set a custom ReAlloc handlers. This function is typically\n \/\/ called via a static object in the ROOT libNew.so shared library.\n\n fgReAllocHook = rh1;\n fgReAllocCHook = rh2;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::PrintStatistics()\n{\n \/\/ Print memory usage statistics.\n\n \/\/ Needs to be protected by global mutex\n R__LOCKGUARD(gGlobalMutex);\n\n#if defined(MEM_DEBUG) && defined(MEM_STAT)\n\n if (!gMemStatistics || !HasCustomNewDelete())\n return;\n\n \/\/Printf(\"\");\n Printf(\"Heap statistics\");\n Printf(\"%12s%12s%12s%12s\", \"size\", \"alloc\", \"free\", \"diff\");\n Printf(\"================================================\");\n\n int i;\n for (i = 0; i < (int)kObjMaxSize; i++)\n if (gAllocated[i] != gFreed[i])\n \/\/if (gAllocated[i])\n Printf(\"%12d%12d%12d%12d\", i, gAllocated[i], gFreed[i],\n gAllocated[i]-gFreed[i]);\n\n if (gAllocatedTotal != gFreedTotal) {\n Printf(\"------------------------------------------------\");\n Printf(\"Total: %12d%12d%12d\", gAllocatedTotal, gFreedTotal,\n gAllocatedTotal-gFreedTotal);\n }\n\n if (gMemSize != -1) {\n Printf(\"------------------------------------------------\");\n for (i= 0; i < gTraceIndex; i++)\n if (gTraceArray[i])\n Printf(\"block %d of size %d not freed\", i, gMemSize);\n }\n Printf(\"================================================\");\n Printf(\" \");\n#endif\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::EnableStatistics(int size, int ix)\n{\n \/\/ Enable memory usage statistics gathering. Size is the size of the memory\n \/\/ block that should be trapped and ix is after how many such allocations\n \/\/ the trap should happen.\n\n#ifdef MEM_STAT\n gMemSize = size;\n gMemIndex = ix;\n gMemStatistics = kTRUE;\n#else\n int idum = size; int iidum = ix;\n#endif\n}\n\n\/\/______________________________________________________________________________\nULong_t TStorage::GetHeapBegin()\n{\n \/\/return begin of heap\n return fgHeapBegin;\n}\n\n\/\/______________________________________________________________________________\nULong_t TStorage::GetHeapEnd()\n{\n \/\/return end of heap\n return fgHeapEnd;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::GetFreeHookData()\n{\n \/\/return static free hook data\n return fgFreeHookData;\n}\n\n\/\/______________________________________________________________________________\nBool_t TStorage::HasCustomNewDelete()\n{\n \/\/return the has custom delete flag\n return fgHasCustomNewDelete;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetCustomNewDelete()\n{\n \/\/set the has custom delete flag\n fgHasCustomNewDelete = kTRUE;\n}\n\n#ifdef WIN32\n\n\/\/______________________________________________________________________________\nvoid TStorage::AddToHeap(ULong_t begin, ULong_t end)\n{\n \/\/add a range to the heap\n if (begin < fgHeapBegin) fgHeapBegin = begin;\n if (end > fgHeapEnd) fgHeapEnd = end;\n}\n\n\/\/______________________________________________________________________________\nBool_t TStorage::IsOnHeap(void *p)\n{\n \/\/is object at p in the heap?\n return (ULong_t)p >= fgHeapBegin && (ULong_t)p < fgHeapEnd;\n}\n\n\/\/______________________________________________________________________________\nsize_t TStorage::GetMaxBlockSize()\n{\n \/\/return max block size\n return fgMaxBlockSize;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetMaxBlockSize(size_t size)\n{\n \/\/set max block size\n fgMaxBlockSize = size;\n}\n\n\/\/______________________________________________________________________________\nFreeHookFun_t TStorage::GetFreeHook()\n{\n \/\/return free hook\n return fgFreeHook;\n}\n\n#endif\nmark ReAlloc(void*,size_t) as obsolete for v6-02-00 as it is non-safe.\/\/ @(#)root\/base:$Id$\n\/\/ Author: Fons Rademakers 29\/07\/95\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TStorage \/\/\n\/\/ \/\/\n\/\/ Storage manager. The storage manager works best in conjunction with \/\/\n\/\/ the custom ROOT new and delete operators defined in the file \/\/\n\/\/ NewDelete.cxx (libNew.so). Only when using the custom allocation \/\/\n\/\/ operators will memory usage statistics be gathered using the \/\/\n\/\/ TStorage EnterStat(), RemoveStat(), etc. functions. \/\/\n\/\/ Memory checking is by default enabled (when using libNew.so) and \/\/\n\/\/ usage statistics is gathered. Using the resource (in .rootrc): \/\/\n\/\/ Root.MemStat one can toggle statistics gathering on or off. More \/\/\n\/\/ specifically on can trap the allocation of a block of memory of a \/\/\n\/\/ certain size. This can be specified using the resource: \/\/\n\/\/ Root.MemStat.size, using the resource Root.MemStat.cnt one can \/\/\n\/\/ specify after how many allocations of this size the trap should \/\/\n\/\/ occur. \/\/\n\/\/ Set the compile option R__NOSTATS to de-activate all memory checking \/\/\n\/\/ and statistics gathering in the system. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n\n#include \"TROOT.h\"\n#include \"TObjectTable.h\"\n#include \"TError.h\"\n#include \"TString.h\"\n#include \"TVirtualMutex.h\"\n#include \"TInterpreter.h\"\n\n#if !defined(R__NOSTATS)\n# define MEM_DEBUG\n# define MEM_STAT\n# define MEM_CHECKOBJECTPOINTERS\n#endif\n\n#if defined(MEM_STAT) && !defined(MEM_DEBUG)\n# define MEM_DEBUG\n#endif\n\n#ifdef MEM_DEBUG\n# ifdef R__B64\n# define storage_size(p) ((size_t)(((size_t*)p)[-1]))\n# else\n# define storage_size(p) ((size_t)(((int*)p)[-2]))\n# endif\n#else\n# define storage_size(p) ((size_t)0)\n#endif\n\n#define PVOID (-1)\n\nULong_t TStorage::fgHeapBegin = (ULong_t)-1L;\nULong_t TStorage::fgHeapEnd;\nsize_t TStorage::fgMaxBlockSize;\nFreeHookFun_t TStorage::fgFreeHook;\nvoid *TStorage::fgFreeHookData;\nReAllocFun_t TStorage::fgReAllocHook;\nReAllocCFun_t TStorage::fgReAllocCHook;\nBool_t TStorage::fgHasCustomNewDelete;\n\n\nClassImp(TStorage)\n\n\/\/------------------------------------------------------------------------------\n\nstatic const char *gSpaceErr = \"storage exhausted\";\n\nconst size_t kObjMaxSize = 10024;\n\nstatic Bool_t gMemStatistics;\nstatic Int_t gAllocated[kObjMaxSize], gFreed[kObjMaxSize];\nstatic Int_t gAllocatedTotal, gFreedTotal;\nstatic void **gTraceArray = 0;\nstatic Int_t gTraceCapacity = 10, gTraceIndex = 0,\n gMemSize = -1, gMemIndex = -1;\n\n\n\/\/______________________________________________________________________________\nvoid TStorage::EnterStat(size_t size, void *p)\n{\n \/\/ Register a memory allocation operation. If desired one can trap an\n \/\/ allocation of a certain size in case one tries to find a memory\n \/\/ leak of that particular size. This function is only called via\n \/\/ the ROOT custom new operators.\n\n TStorage::SetMaxBlockSize(TMath::Max(TStorage::GetMaxBlockSize(), size));\n\n if (!gMemStatistics) return;\n\n if ((Int_t)size == gMemSize) {\n if (gTraceIndex == gMemIndex)\n Fatal(\"EnterStat\", \"trapped allocation %d\", gMemIndex);\n\n if (!gTraceArray)\n gTraceArray = (void**) malloc(sizeof(void*)*gTraceCapacity);\n\n if (gTraceIndex >= gTraceCapacity) {\n gTraceCapacity = gTraceCapacity*2;\n gTraceArray = (void**) realloc(gTraceArray, sizeof(void*)*gTraceCapacity);\n }\n gTraceArray[gTraceIndex++] = p;\n }\n if (size >= kObjMaxSize)\n gAllocated[kObjMaxSize-1]++;\n else\n gAllocated[size]++;\n gAllocatedTotal += size;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::RemoveStat(void *vp)\n{\n \/\/ Register a memory free operation. This function is only called via\n \/\/ the custom ROOT delete operator.\n\n if (!gMemStatistics) return;\n\n size_t size = storage_size(vp);\n if ((Int_t)size == gMemSize) {\n for (int i = 0; i < gTraceIndex; i++)\n if (gTraceArray[i] == vp) {\n gTraceArray[i] = 0;\n break;\n }\n }\n if (size >= kObjMaxSize)\n gFreed[kObjMaxSize-1]++;\n else\n gFreed[size]++;\n gFreedTotal += size;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::Alloc(size_t size)\n{\n \/\/ Allocate a block of memory, that later can be resized using\n \/\/ TStorage::ReAlloc().\n\n static const char *where = \"TStorage::Alloc\";\n\n#ifndef WIN32\n void *vp = ::operator new[](size);\n#else\n void *vp = ::operator new(size);\n#endif\n if (vp == 0)\n Fatal(where, \"%s\", gSpaceErr);\n\n return vp;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::Dealloc(void *ptr)\n{\n \/\/ De-allocate block of memory, that was allocated via TStorage::Alloc().\n\n#ifndef WIN32\n ::operator delete[](ptr);\n#else\n ::operator delete(ptr);\n#endif\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ReAlloc(void *ovp, size_t size)\n{\n \/\/ Reallocate (i.e. resize) block of memory. Don't use if size is larger\n \/\/ than old size, use ReAlloc(void *, size_t, size_t) instead.\n\n ::Obsolete(\"ReAlloc(void*,size_t)\", \"v5-34-00\", \"v6-02-00\");\n ::Info(\"ReAlloc(void*,size_t)\", \"please use ReAlloc(void*,size_t,size_t)\");\n\n \/\/ Needs to be protected by global mutex\n R__LOCKGUARD(gGlobalMutex);\n\n if (fgReAllocHook && fgHasCustomNewDelete && !TROOT::MemCheck())\n return (*fgReAllocHook)(ovp, size);\n\n static const char *where = \"TStorage::ReAlloc\";\n\n#ifndef WIN32\n void *vp = ::operator new[](size);\n#else\n void *vp = ::operator new(size);\n#endif\n if (vp == 0)\n Fatal(where, \"%s\", gSpaceErr);\n\n if (ovp == 0)\n return vp;\n\n memmove(vp, ovp, size);\n#ifndef WIN32\n ::operator delete[](ovp);\n#else\n ::operator delete(ovp);\n#endif\n return vp;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ReAlloc(void *ovp, size_t size, size_t oldsize)\n{\n \/\/ Reallocate (i.e. resize) block of memory. Checks if current size is\n \/\/ equal to oldsize. If not memory was overwritten.\n\n \/\/ Needs to be protected by global mutex\n R__LOCKGUARD(gGlobalMutex);\n\n if (fgReAllocCHook && fgHasCustomNewDelete && !TROOT::MemCheck())\n return (*fgReAllocCHook)(ovp, size, oldsize);\n\n static const char *where = \"TStorage::ReAlloc\";\n\n if (oldsize == size)\n return ovp;\n\n#ifndef WIN32\n void *vp = ::operator new[](size);\n#else\n void *vp = ::operator new(size);\n#endif\n if (vp == 0)\n Fatal(where, \"%s\", gSpaceErr);\n\n if (ovp == 0)\n return vp;\n\n if (size > oldsize) {\n memcpy(vp, ovp, oldsize);\n memset((char*)vp+oldsize, 0, size-oldsize);\n } else\n memcpy(vp, ovp, size);\n#ifndef WIN32\n ::operator delete[](ovp);\n#else\n ::operator delete(ovp);\n#endif\n return vp;\n}\n\n\/\/______________________________________________________________________________\nchar *TStorage::ReAllocChar(char *ovp, size_t size, size_t oldsize)\n{\n \/\/ Reallocate (i.e. resize) array of chars. Size and oldsize are\n \/\/ in number of chars.\n\n \/\/ Needs to be protected by global mutex\n R__LOCKGUARD(gGlobalMutex);\n\n static const char *where = \"TStorage::ReAllocChar\";\n\n char *vp;\n if (ovp == 0) {\n vp = new char[size];\n if (vp == 0)\n Fatal(where, \"%s\", gSpaceErr);\n return vp;\n }\n if (oldsize == size)\n return ovp;\n\n vp = new char[size];\n if (vp == 0)\n Fatal(where, \"%s\", gSpaceErr);\n if (size > oldsize) {\n memcpy(vp, ovp, oldsize);\n memset((char*)vp+oldsize, 0, size-oldsize);\n } else\n memcpy(vp, ovp, size);\n delete [] ovp;\n return vp;\n}\n\n\/\/______________________________________________________________________________\nInt_t *TStorage::ReAllocInt(Int_t *ovp, size_t size, size_t oldsize)\n{\n \/\/ Reallocate (i.e. resize) array of integers. Size and oldsize are\n \/\/ number of integers (not number of bytes).\n\n \/\/ Needs to be protected by global mutex\n R__LOCKGUARD(gGlobalMutex);\n\n static const char *where = \"TStorage::ReAllocInt\";\n\n Int_t *vp;\n if (ovp == 0) {\n vp = new Int_t[size];\n if (vp == 0)\n Fatal(where, \"%s\", gSpaceErr);\n return vp;\n }\n if (oldsize == size)\n return ovp;\n\n vp = new Int_t[size];\n if (vp == 0)\n Fatal(where, \"%s\", gSpaceErr);\n if (size > oldsize) {\n memcpy(vp, ovp, oldsize*sizeof(Int_t));\n memset((Int_t*)vp+oldsize, 0, (size-oldsize)*sizeof(Int_t));\n } else\n memcpy(vp, ovp, size*sizeof(Int_t));\n delete [] ovp;\n return vp;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ObjectAlloc(size_t sz)\n{\n \/\/ Used to allocate a TObject on the heap (via TObject::operator new()).\n \/\/ Directly after this routine one can call (in the TObject ctor)\n \/\/ TStorage::IsOnHeap() to find out if the just created object is on\n \/\/ the heap.\n\n \/\/ Needs to be protected by global mutex\n R__LOCKGUARD(gGlobalMutex);\n\n ULong_t space = (ULong_t) ::operator new(sz);\n AddToHeap(space, space+sz);\n return (void*) space;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ObjectAlloc(size_t , void *vp)\n{\n \/\/ Used to allocate a TObject on the heap (via TObject::operator new(size_t,void*))\n \/\/ in position vp. vp is already allocated (maybe on heap, maybe on\n \/\/ stack) so just return.\n\n return vp;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::ObjectDealloc(void *vp)\n{\n \/\/ Used to deallocate a TObject on the heap (via TObject::operator delete()).\n\n ::operator delete(vp);\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::ObjectDealloc(void *vp, void *ptr)\n{\n \/\/ Used to deallocate a TObject on the heap (via TObject::operator delete(void*,void*)).\n\n if (vp && ptr) { }\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetFreeHook(FreeHookFun_t fh, void *data)\n{\n \/\/ Set a free handler.\n\n fgFreeHook = fh;\n fgFreeHookData = data;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetReAllocHooks(ReAllocFun_t rh1, ReAllocCFun_t rh2)\n{\n \/\/ Set a custom ReAlloc handlers. This function is typically\n \/\/ called via a static object in the ROOT libNew.so shared library.\n\n fgReAllocHook = rh1;\n fgReAllocCHook = rh2;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::PrintStatistics()\n{\n \/\/ Print memory usage statistics.\n\n \/\/ Needs to be protected by global mutex\n R__LOCKGUARD(gGlobalMutex);\n\n#if defined(MEM_DEBUG) && defined(MEM_STAT)\n\n if (!gMemStatistics || !HasCustomNewDelete())\n return;\n\n \/\/Printf(\"\");\n Printf(\"Heap statistics\");\n Printf(\"%12s%12s%12s%12s\", \"size\", \"alloc\", \"free\", \"diff\");\n Printf(\"================================================\");\n\n int i;\n for (i = 0; i < (int)kObjMaxSize; i++)\n if (gAllocated[i] != gFreed[i])\n \/\/if (gAllocated[i])\n Printf(\"%12d%12d%12d%12d\", i, gAllocated[i], gFreed[i],\n gAllocated[i]-gFreed[i]);\n\n if (gAllocatedTotal != gFreedTotal) {\n Printf(\"------------------------------------------------\");\n Printf(\"Total: %12d%12d%12d\", gAllocatedTotal, gFreedTotal,\n gAllocatedTotal-gFreedTotal);\n }\n\n if (gMemSize != -1) {\n Printf(\"------------------------------------------------\");\n for (i= 0; i < gTraceIndex; i++)\n if (gTraceArray[i])\n Printf(\"block %d of size %d not freed\", i, gMemSize);\n }\n Printf(\"================================================\");\n Printf(\" \");\n#endif\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::EnableStatistics(int size, int ix)\n{\n \/\/ Enable memory usage statistics gathering. Size is the size of the memory\n \/\/ block that should be trapped and ix is after how many such allocations\n \/\/ the trap should happen.\n\n#ifdef MEM_STAT\n gMemSize = size;\n gMemIndex = ix;\n gMemStatistics = kTRUE;\n#else\n int idum = size; int iidum = ix;\n#endif\n}\n\n\/\/______________________________________________________________________________\nULong_t TStorage::GetHeapBegin()\n{\n \/\/return begin of heap\n return fgHeapBegin;\n}\n\n\/\/______________________________________________________________________________\nULong_t TStorage::GetHeapEnd()\n{\n \/\/return end of heap\n return fgHeapEnd;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::GetFreeHookData()\n{\n \/\/return static free hook data\n return fgFreeHookData;\n}\n\n\/\/______________________________________________________________________________\nBool_t TStorage::HasCustomNewDelete()\n{\n \/\/return the has custom delete flag\n return fgHasCustomNewDelete;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetCustomNewDelete()\n{\n \/\/set the has custom delete flag\n fgHasCustomNewDelete = kTRUE;\n}\n\n#ifdef WIN32\n\n\/\/______________________________________________________________________________\nvoid TStorage::AddToHeap(ULong_t begin, ULong_t end)\n{\n \/\/add a range to the heap\n if (begin < fgHeapBegin) fgHeapBegin = begin;\n if (end > fgHeapEnd) fgHeapEnd = end;\n}\n\n\/\/______________________________________________________________________________\nBool_t TStorage::IsOnHeap(void *p)\n{\n \/\/is object at p in the heap?\n return (ULong_t)p >= fgHeapBegin && (ULong_t)p < fgHeapEnd;\n}\n\n\/\/______________________________________________________________________________\nsize_t TStorage::GetMaxBlockSize()\n{\n \/\/return max block size\n return fgMaxBlockSize;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetMaxBlockSize(size_t size)\n{\n \/\/set max block size\n fgMaxBlockSize = size;\n}\n\n\/\/______________________________________________________________________________\nFreeHookFun_t TStorage::GetFreeHook()\n{\n \/\/return free hook\n return fgFreeHook;\n}\n\n#endif\n<|endoftext|>"} {"text":"\n\/\/\n\/\/ A WebAssembly shell, loads a .wast file (WebAssembly in S-Expression format) and executes it.\n\/\/\n\n#include \n\n#include \"wasm-s-parser.h\"\n#include \"wasm-interpreter.h\"\n\nusing namespace cashew;\nusing namespace wasm;\n\nIString ASSERT_RETURN(\"assert_return\"),\n ASSERT_TRAP(\"assert_trap\"),\n PRINT(\"print\"),\n INVOKE(\"invoke\");\n\n\/\/\n\/\/ Implementation of the shell interpreter execution environment\n\/\/\n\nstruct ShellExternalInterface : ModuleInstance::ExternalInterface {\n char *memory;\n size_t memorySize;\n\n ShellExternalInterface() : memory(nullptr) {}\n\n void init(Module& wasm) override {\n memory = new char[wasm.memory.initial];\n memorySize = wasm.memory.initial;\n \/\/ apply memory segments\n for (auto segment : wasm.memory.segments) {\n memcpy(memory + segment.offset, segment.data, segment.size);\n }\n }\n\n jmp_buf trapState;\n\n void trap() {\n longjmp(trapState, 1);\n }\n\n Literal callImport(Import *import, ModuleInstance::LiteralList& arguments) override {\n if (import->name == PRINT) {\n for (auto argument : arguments) {\n std::cout << argument << ' ';\n }\n std::cout << '\\n';\n return Literal();\n }\n std::cout << \"callImport \" << import->name.str << \"\\n\";\n abort();\n }\n\n Literal load(Load* load, Literal ptr) override {\n \/\/ ignore align - assume we are on x86 etc. which does that\n size_t addr = ptr.geti32();\n int64_t full = addr;\n full += load->offset;\n if (full + load->bytes > memorySize) trap();\n addr = full;\n switch (load->type) {\n case i32: {\n switch (load->bytes) {\n case 1: return load->signed_ ? (int32_t)((int8_t*)memory)[addr] : (int32_t)((uint8_t*)memory)[addr];\n case 2: return load->signed_ ? (int32_t)((int16_t*)memory)[addr] : (int32_t)((uint16_t*)memory)[addr];\n case 4: return load->signed_ ? (int32_t)((int32_t*)memory)[addr] : (int32_t)((uint32_t*)memory)[addr];\n default: abort();\n }\n break;\n }\n case f32: return ((float*)memory)[addr];\n case f64: return ((double*)memory)[addr];\n default: abort();\n }\n }\n\n void store(Store* store, Literal ptr, Literal value) override {\n \/\/ ignore align - assume we are on x86 etc. which does that\n size_t addr = ptr.geti32();\n int64_t full = addr;\n full += store->offset;\n if (full + store->bytes > memorySize) trap();\n switch (store->type) {\n case i32: {\n switch (store->bytes) {\n case 1: ((int8_t*)memory)[addr] = value.geti32();\n case 2: ((int16_t*)memory)[addr] = value.geti32();\n case 4: ((int32_t*)memory)[addr] = value.geti32();\n default: abort();\n }\n break;\n }\n case f32: ((float*)memory)[addr] = value.getf32();\n case f64: ((double*)memory)[addr] = value.getf64();\n default: abort();\n }\n }\n};\n\nint main(int argc, char **argv) {\n debug = getenv(\"WASM_SHELL_DEBUG\") ? getenv(\"WASM_SHELL_DEBUG\")[0] - '0' : 0;\n\n char *infile = argv[1];\n bool print_wasm = argc >= 3; \/\/ second arg means print it out\n\n if (debug) std::cerr << \"loading '\" << infile << \"'...\\n\";\n FILE *f = fopen(argv[1], \"r\");\n assert(f);\n fseek(f, 0, SEEK_END);\n int size = ftell(f);\n char *input = new char[size+1];\n rewind(f);\n int num = fread(input, 1, size, f);\n \/\/ On Windows, ftell() gives the byte position (\\r\\n counts as two bytes), but when\n \/\/ reading, fread() returns the number of characters read (\\r\\n is read as one char \\n, and counted as one),\n \/\/ so return value of fread can be less than size reported by ftell, and that is normal.\n assert((num > 0 || size == 0) && num <= size);\n fclose(f);\n input[num] = 0;\n\n if (debug) std::cerr << \"parsing text to s-expressions...\\n\";\n SExpressionParser parser(input);\n Element& root = *parser.root;\n if (debug) std::cout << root << '\\n';\n\n \/\/ A .wast may have multiple modules, with some asserts after them\n size_t i = 0;\n while (i < root.size()) {\n if (debug) std::cerr << \"parsing s-expressions to wasm...\\n\";\n Module wasm;\n SExpressionWasmBuilder builder(wasm, *root[i]);\n i++;\n\n auto interface = new ShellExternalInterface();\n auto instance = new ModuleInstance(wasm, interface);\n\n if (print_wasm) {\n if (debug) std::cerr << \"printing...\\n\";\n std::cout << wasm;\n }\n\n \/\/ run asserts\n while (i < root.size()) {\n Element& curr = *root[i];\n IString id = curr[0]->str();\n if (id == MODULE) break;\n std::cerr << curr << '\\n';\n Element& invoke = *curr[1];\n assert(invoke[0]->str() == INVOKE);\n IString name = invoke[1]->str();\n ModuleInstance::LiteralList arguments;\n for (size_t j = 2; j < invoke.size(); j++) {\n Expression* argument = builder.parseExpression(*invoke[2]);\n arguments.push_back(argument->dyn_cast()->value);\n }\n bool trapped = false;\n if (setjmp(interface->trapState) == 0) {\n instance->callFunction(name, arguments);\n } else {\n trapped = true;\n }\n if (id == ASSERT_RETURN) assert(!trapped);\n if (id == ASSERT_TRAP) assert(trapped);\n i++;\n }\n }\n\n if (debug) std::cerr << \"done.\\n\";\n}\n\nverify return values\n\/\/\n\/\/ A WebAssembly shell, loads a .wast file (WebAssembly in S-Expression format) and executes it.\n\/\/\n\n#include \n\n#include \"wasm-s-parser.h\"\n#include \"wasm-interpreter.h\"\n\nusing namespace cashew;\nusing namespace wasm;\n\nIString ASSERT_RETURN(\"assert_return\"),\n ASSERT_TRAP(\"assert_trap\"),\n PRINT(\"print\"),\n INVOKE(\"invoke\");\n\n\/\/\n\/\/ Implementation of the shell interpreter execution environment\n\/\/\n\nstruct ShellExternalInterface : ModuleInstance::ExternalInterface {\n char *memory;\n size_t memorySize;\n\n ShellExternalInterface() : memory(nullptr) {}\n\n void init(Module& wasm) override {\n memory = new char[wasm.memory.initial];\n memorySize = wasm.memory.initial;\n \/\/ apply memory segments\n for (auto segment : wasm.memory.segments) {\n memcpy(memory + segment.offset, segment.data, segment.size);\n }\n }\n\n jmp_buf trapState;\n\n void trap() {\n longjmp(trapState, 1);\n }\n\n Literal callImport(Import *import, ModuleInstance::LiteralList& arguments) override {\n if (import->name == PRINT) {\n for (auto argument : arguments) {\n std::cout << argument << ' ';\n }\n std::cout << '\\n';\n return Literal();\n }\n std::cout << \"callImport \" << import->name.str << \"\\n\";\n abort();\n }\n\n Literal load(Load* load, Literal ptr) override {\n \/\/ ignore align - assume we are on x86 etc. which does that\n size_t addr = ptr.geti32();\n int64_t full = addr;\n full += load->offset;\n if (full + load->bytes > memorySize) trap();\n addr = full;\n switch (load->type) {\n case i32: {\n switch (load->bytes) {\n case 1: return load->signed_ ? (int32_t)((int8_t*)memory)[addr] : (int32_t)((uint8_t*)memory)[addr];\n case 2: return load->signed_ ? (int32_t)((int16_t*)memory)[addr] : (int32_t)((uint16_t*)memory)[addr];\n case 4: return load->signed_ ? (int32_t)((int32_t*)memory)[addr] : (int32_t)((uint32_t*)memory)[addr];\n default: abort();\n }\n break;\n }\n case f32: return ((float*)memory)[addr];\n case f64: return ((double*)memory)[addr];\n default: abort();\n }\n }\n\n void store(Store* store, Literal ptr, Literal value) override {\n \/\/ ignore align - assume we are on x86 etc. which does that\n size_t addr = ptr.geti32();\n int64_t full = addr;\n full += store->offset;\n if (full + store->bytes > memorySize) trap();\n switch (store->type) {\n case i32: {\n switch (store->bytes) {\n case 1: ((int8_t*)memory)[addr] = value.geti32();\n case 2: ((int16_t*)memory)[addr] = value.geti32();\n case 4: ((int32_t*)memory)[addr] = value.geti32();\n default: abort();\n }\n break;\n }\n case f32: ((float*)memory)[addr] = value.getf32();\n case f64: ((double*)memory)[addr] = value.getf64();\n default: abort();\n }\n }\n};\n\nint main(int argc, char **argv) {\n debug = getenv(\"WASM_SHELL_DEBUG\") ? getenv(\"WASM_SHELL_DEBUG\")[0] - '0' : 0;\n\n char *infile = argv[1];\n bool print_wasm = argc >= 3; \/\/ second arg means print it out\n\n if (debug) std::cerr << \"loading '\" << infile << \"'...\\n\";\n FILE *f = fopen(argv[1], \"r\");\n assert(f);\n fseek(f, 0, SEEK_END);\n int size = ftell(f);\n char *input = new char[size+1];\n rewind(f);\n int num = fread(input, 1, size, f);\n \/\/ On Windows, ftell() gives the byte position (\\r\\n counts as two bytes), but when\n \/\/ reading, fread() returns the number of characters read (\\r\\n is read as one char \\n, and counted as one),\n \/\/ so return value of fread can be less than size reported by ftell, and that is normal.\n assert((num > 0 || size == 0) && num <= size);\n fclose(f);\n input[num] = 0;\n\n if (debug) std::cerr << \"parsing text to s-expressions...\\n\";\n SExpressionParser parser(input);\n Element& root = *parser.root;\n if (debug) std::cout << root << '\\n';\n\n \/\/ A .wast may have multiple modules, with some asserts after them\n size_t i = 0;\n while (i < root.size()) {\n if (debug) std::cerr << \"parsing s-expressions to wasm...\\n\";\n Module wasm;\n SExpressionWasmBuilder builder(wasm, *root[i]);\n i++;\n\n auto interface = new ShellExternalInterface();\n auto instance = new ModuleInstance(wasm, interface);\n\n if (print_wasm) {\n if (debug) std::cerr << \"printing...\\n\";\n std::cout << wasm;\n }\n\n \/\/ run asserts\n while (i < root.size()) {\n Element& curr = *root[i];\n IString id = curr[0]->str();\n if (id == MODULE) break;\n std::cerr << curr << '\\n';\n Element& invoke = *curr[1];\n assert(invoke[0]->str() == INVOKE);\n IString name = invoke[1]->str();\n ModuleInstance::LiteralList arguments;\n for (size_t j = 2; j < invoke.size(); j++) {\n Expression* argument = builder.parseExpression(*invoke[2]);\n arguments.push_back(argument->dyn_cast()->value);\n }\n bool trapped = false;\n Literal result;\n if (setjmp(interface->trapState) == 0) {\n result = instance->callFunction(name, arguments);\n } else {\n trapped = true;\n }\n if (id == ASSERT_RETURN) {\n assert(!trapped);\n Literal expected;\n if (curr.size() >= 3) {\n expected = builder.parseExpression(*curr[2])->dyn_cast()->value;\n }\n std::cerr << \"seen \" << result << \", expected \" << expected << '\\n';\n assert(expected == result);\n }\n if (id == ASSERT_TRAP) assert(trapped);\n i++;\n }\n }\n\n if (debug) std::cerr << \"done.\\n\";\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"Matrix.hpp\"\n\nMatrix::Matrix(const Matrix &matrix) : m_rows(matrix.m_rows), m_columns(matrix.m_columns)\n{\n fill(matrix.m_elements);\n}\n\nMatrix::Matrix(unsigned int rows, unsigned int columns) : m_rows(rows), m_columns(columns)\n{\n fill(nullptr);\n}\n\nMatrix::Matrix(unsigned int rows, unsigned int columns, int **elements) : m_rows(rows), m_columns(columns)\n{\n std::cout << __PRETTY_FUNCTION__ << std::endl;\n fill(elements);\n}\n\nvoid Matrix::fill(int **elements)\n{\n m_elements = new int *[m_columns];\n for (unsigned int i = 0; i < m_columns; ++i) {\n m_elements[i] = new int[m_rows];\n for (unsigned int j = 0; j < m_rows; ++j) {\n m_elements[i][j] = elements ? elements[i][j] : 0;\n }\n }\n}\n\nMatrix & Matrix::operator=(const Matrix &matrix)\n{\n if ( this != &matrix ) {\n Matrix(matrix).swap(*this);\n }\n\n return *this;\n}\n\nvoid Matrix::swap(Matrix &matrix)\n{\n std::swap(m_rows, matrix.m_rows);\n std::swap(m_columns, matrix.m_columns);\n std::swap(m_elements, matrix.m_elements);\n}\n\nMatrix::~Matrix()\n{\n for (unsigned int i = 0; i < m_rows; ++i) {\n delete [] m_elements[i];\n }\n\n delete [] m_elements;\n}\n\nunsigned int Matrix::rows() const\n{\n return m_rows;\n}\n\nunsigned int Matrix::columns() const\n{\n return m_columns;\n}\n\nbool Matrix::fill(const std::string filePath)\n{\n std::ifstream input;\n input.open(filePath);\n\n bool isSucess = true;\n if ( input.is_open() ) {\n for (unsigned int i = 0; i < m_rows; ++i) {\n for (unsigned int j = 0; j < m_columns; ++j) {\n if ( !(input >> m_elements[i][j]) ) {\n throw \"exception in fill matrix\";\n }\n }\n }\n }\n else {\n isSucess = false;\n }\n\n input.close();\n\n return isSucess;\n}\n\nconst int *Matrix::operator[](unsigned int index) const\n{\n if ( index >= m_rows ) {\n throw std::invalid_argument(\"index goes abroad\");\n }\n\n return m_elements[index];\n}\n\nMatrix Matrix::operator *(const Matrix &matrix) const\n{\n std::cout << __PRETTY_FUNCTION__ << std::endl;\n\n if ( m_columns != matrix.m_rows ) {\n throw std::invalid_argument(\"matrix sizes do not match\");\n }\n\n unsigned int n = m_rows;\n unsigned int m = matrix.m_columns;\n unsigned int s = m_columns;\n\n int **elements = new int *[n];\n for (unsigned int i = 0; i < n; ++i) {\n elements[i] = new int[m];\n for (unsigned int j = 0; j < m; ++j) {\n int value = 0;\n for (unsigned int k = 0; k < s; ++k) {\n value += m_elements[i][k] * matrix.m_elements[k][j];\n }\n elements[i][j] = value;\n }\n }\n\n return Matrix(n, m, elements);\n}\n\n\nMatrix Matrix::operator +(const Matrix &matrix) const\n{\n std::cout << __PRETTY_FUNCTION__ << std::endl;\n\n if ( m_rows != matrix.m_rows || m_columns != matrix.m_columns ) {\n throw std::invalid_argument(\"matrix sizes do not match\");\n }\n\n unsigned int n = m_rows;\n unsigned int m = m_columns;\n\n int **data = new int *[n];\n for (unsigned int i = 0; i < n; ++i) {\n data[i] = new int[m];\n for (unsigned int j = 0; j < m; ++j) {\n data[i][j] = m_elements[i][j] + matrix.m_elements[i][j];\n }\n }\n\n return Matrix(n, m, data);\n}\n\nbool Matrix::operator==(const Matrix &matrix) const\n{\n std::cout << __PRETTY_FUNCTION__ << std::endl;\n\n if ( m_rows != matrix.m_rows || m_columns != matrix.m_columns ) {\n return false;\n }\n\n for (unsigned int i = 0; i < m_rows; ++i) {\n for (unsigned int j = 0; j < m_columns; ++j) {\n if ( m_elements[i][j] != matrix.m_elements[i][j] ) {\n return false;\n }\n }\n }\n\n return true;\n}\n\nvoid Matrix::show() const\n{\n std::cout << __PRETTY_FUNCTION__ << std::endl;\n\n std::cout << m_rows << \" * \" << m_columns << std::endl;\n for (unsigned int i = 0; i < m_rows; ++i) {\n for (unsigned int j = 0; j < m_columns; ++j) {\n std::cout << m_elements[i][j] << \"\\t\";\n }\n std::cout << std::endl;\n }\n}\nUpdate Matrix.cpp#include \n#include \n#include \n\n#include \"Matrix.hpp\"\n\nMatrix::Matrix(const Matrix &matrix) : m_rows(matrix.m_rows), m_columns(matrix.m_columns)\n{\n fill(matrix.m_elements);\n}\n\nMatrix::Matrix(unsigned int rows, unsigned int columns) : m_rows(rows), m_columns(columns)\n{\n fill(nullptr);\n}\n\nMatrix::Matrix(unsigned int rows, unsigned int columns, int **elements) : m_rows(rows), m_columns(columns)\n{\n std::cout << __PRETTY_FUNCTION__ << std::endl;\n fill(elements);\n}\n\nvoid Matrix::fill(int **elements)\n{\n m_elements = new int *[m_columns];\n for (unsigned int i = 0; i < m_columns; ++i) {\n m_elements[i] = new int[m_rows];\n for (unsigned int j = 0; j < m_rows; ++j) {\n m_elements[i][j] = elements ? elements[i][j] : 0;\n }\n }\n}\n\nMatrix & Matrix::operator=(const Matrix &matrix)\n{\n if ( this != &matrix ) {\n Matrix(matrix).swap(*this);\n }\n\n return *this;\n}\n\nvoid Matrix::swap(Matrix &matrix)\n{\n std::swap(m_rows, matrix.m_rows);\n std::swap(m_columns, matrix.m_columns);\n std::swap(m_elements, matrix.m_elements);\n}\n\nMatrix::~Matrix()\n{\n for (unsigned int i = 0; i < m_rows; ++i) {\n delete [] m_elements[i];\n }\n\n delete [] m_elements;\n}\n\nunsigned int Matrix::rows() const\n{\n return m_rows;\n}\n\nunsigned int Matrix::columns() const\n{\n return m_columns;\n}\n\nbool Matrix::fill(const std::string filePath)\n{\n std::ifstream input;\n input.open(filePath);\n\n bool isSucess = true;\n if ( input.is_open() ) {\n for (unsigned int i = 0; i < m_rows; ++i) {\n for (unsigned int j = 0; j < m_columns; ++j) {\n if ( !(input >> m_elements[i][j]) ) {\n throw \"exception in fill matrix\";\n }\n }\n }\n }\n else {\n isSucess = false;\n }\n\n input.close();\n\n return isSucess;\n}\n\nconst int *Matrix::operator[](unsigned int index) const\n{\n if ( index >= m_rows ) {\n throw std::invalid_argument(\"index goes abroad\");\n }\n\n return m_elements[index];\n}\n\nMatrix Matrix::operator *(const Matrix &matrix) const\n{\n std::cout << __PRETTY_FUNCTION__ << std::endl;\n\n if ( m_columns != matrix.m_rows ) {\n throw std::invalid_argument(\"matrix sizes do not match\");\n }\n\n unsigned int n = m_rows;\n unsigned int m = matrix.m_columns;\n unsigned int s = m_columns;\n\n int **elements = new int *[n];\n for (unsigned int i = 0; i < n; ++i) {\n elements[i] = new int[m];\n for (unsigned int j = 0; j < m; ++j) {\n int value = 0;\n for (unsigned int k = 0; k < s; ++k) {\n value += m_elements[i][k] * matrix.m_elements[k][j];\n }\n elements[i][j] = value;\n }\n }\n\n return Matrix(n, m, elements);\n}\n\n\nMatrix Matrix::operator +(const Matrix &matrix) const\n{\n std::cout << __PRETTY_FUNCTION__ << std::endl;\n\n if ( m_rows != matrix.m_rows || m_columns != matrix.m_columns ) {\n throw std::invalid_argument(\"matrix sizes do not match\");\n }\n\n unsigned int n = m_rows;\n unsigned int m = m_columns;\n\n int **data = new int *[n];\n for (unsigned int i = 0; i < n; ++i) {\n data[i] = new int[m];\n for (unsigned int j = 0; j < m; ++j) {\n data[i][j] = m_elements[i][j] + m_elements[i][j];\n }\n }\n\n return Matrix(n, m, data);\n}\n\nbool Matrix::operator==(const Matrix &matrix) const\n{\n std::cout << __PRETTY_FUNCTION__ << std::endl;\n\n if ( m_rows != matrix.m_rows || m_columns != matrix.m_columns ) {\n return false;\n }\n\n for (unsigned int i = 0; i < m_rows; ++i) {\n for (unsigned int j = 0; j < m_columns; ++j) {\n if ( m_elements[i][j] != matrix.m_elements[i][j] ) {\n return false;\n }\n }\n }\n\n return true;\n}\n\nvoid Matrix::show() const\n{\n std::cout << __PRETTY_FUNCTION__ << std::endl;\n\n std::cout << m_rows << \" * \" << m_columns << std::endl;\n for (unsigned int i = 0; i < m_rows; ++i) {\n for (unsigned int j = 0; j < m_columns; ++j) {\n std::cout << m_elements[i][j] << \"\\t\";\n }\n std::cout << std::endl;\n }\n}\n<|endoftext|>"} {"text":"Fixed a small bug where if no linear solver packages were defined, there was a compilation error. This was due to auto_ptr.h not being included properly in that case.<|endoftext|>"} {"text":"Fix bug in Windows.<|endoftext|>"} {"text":"\/**\n * This file is part of TelepathyQt4\n *\n * @copyright Copyright (C) 2008 Collabora Ltd. \n * @copyright Copyright (C) 2008 Nokia Corporation\n * @license LGPL 2.1\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \n#include \"TelepathyQt4\/_gen\/pending-contacts.moc.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"TelepathyQt4\/debug-internal.h\"\n\nnamespace Tp\n{\n\nstruct TELEPATHY_QT4_NO_EXPORT PendingContacts::Private\n{\n enum RequestType\n {\n ForHandles,\n ForIdentifiers,\n Upgrade\n };\n\n Private(PendingContacts *parent, const ContactManagerPtr &manager, const UIntList &handles,\n const Features &features, const Features &missingFeatures,\n const QMap &satisfyingContacts)\n : parent(parent),\n manager(manager),\n features(features),\n missingFeatures(missingFeatures),\n satisfyingContacts(satisfyingContacts),\n requestType(ForHandles),\n handles(handles),\n nested(0)\n {\n }\n\n Private(PendingContacts *parent, const ContactManagerPtr &manager, const QStringList &identifiers,\n const Features &features)\n : parent(parent),\n manager(manager),\n features(features),\n requestType(ForIdentifiers),\n identifiers(identifiers),\n nested(0)\n {\n }\n\n Private(PendingContacts *parent,\n const ContactManagerPtr &manager, const QList &contactsToUpgrade,\n const Features &features)\n : parent(parent),\n manager(manager),\n features(features),\n requestType(Upgrade),\n contactsToUpgrade(contactsToUpgrade),\n nested(0)\n {\n }\n\n void setFinished();\n\n \/\/ Public object\n PendingContacts *parent;\n\n \/\/ Generic parameters\n ContactManagerPtr manager;\n Features features;\n Features missingFeatures;\n QMap satisfyingContacts;\n\n \/\/ Request type specific parameters\n RequestType requestType;\n UIntList handles;\n QStringList identifiers;\n QList contactsToUpgrade;\n PendingContacts *nested;\n\n \/\/ Results\n QList contacts;\n UIntList invalidHandles;\n QStringList validIds;\n QHash > invalidIds;\n\n ReferencedHandles handlesToInspect;\n};\n\nvoid PendingContacts::Private::setFinished()\n{\n ConnectionLowlevelPtr connLowlevel = manager->connection()->lowlevel();\n UIntList handles = invalidHandles;\n foreach (uint handle, handles) {\n if (connLowlevel->hasContactId(handle)) {\n satisfyingContacts.insert(handle, manager->ensureContact(handle,\n connLowlevel->contactId(handle), missingFeatures));\n invalidHandles.removeOne(handle);\n }\n }\n\n parent->setFinished();\n}\n\n\/**\n * \\class PendingContacts\n * \\ingroup clientconn\n * \\headerfile TelepathyQt4\/pending-contacts.h \n *\n * \\brief The PendingContacts class is used by ContactManager when\n * creating\/updating Contact objects.\n *\/\n\nPendingContacts::PendingContacts(const ContactManagerPtr &manager,\n const UIntList &handles,\n const Features &features,\n const Features &missingFeatures,\n const QStringList &interfaces,\n const QMap &satisfyingContacts,\n const QSet &otherContacts,\n const QString &errorName,\n const QString &errorMessage)\n : PendingOperation(manager),\n mPriv(new Private(this, manager, handles, features, missingFeatures, satisfyingContacts))\n{\n if (!errorName.isEmpty()) {\n setFinishedWithError(errorName, errorMessage);\n return;\n }\n\n if (!otherContacts.isEmpty()) {\n ConnectionPtr conn = manager->connection();\n if (conn->interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_CONTACTS))) {\n PendingContactAttributes *attributes =\n conn->lowlevel()->contactAttributes(otherContacts.toList(),\n interfaces, true);\n\n connect(attributes,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(onAttributesFinished(Tp::PendingOperation*)));\n } else {\n \/\/ fallback to just create the contacts\n PendingHandles *handles = conn->lowlevel()->referenceHandles(HandleTypeContact,\n otherContacts.toList());\n connect(handles,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(onReferenceHandlesFinished(Tp::PendingOperation*)));\n }\n } else {\n allAttributesFetched();\n }\n}\n\nPendingContacts::PendingContacts(const ContactManagerPtr &manager,\n const QStringList &identifiers, const Features &features,\n const QString &errorName, const QString &errorMessage)\n : PendingOperation(manager),\n mPriv(new Private(this, manager, identifiers, features))\n{\n if (!errorName.isEmpty()) {\n setFinishedWithError(errorName, errorMessage);\n return;\n }\n\n ConnectionPtr conn = manager->connection();\n PendingHandles *handles = conn->lowlevel()->requestHandles(HandleTypeContact, identifiers);\n\n connect(handles,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(onRequestHandlesFinished(Tp::PendingOperation*)));\n}\n\nPendingContacts::PendingContacts(const ContactManagerPtr &manager,\n const QList &contacts, const Features &features,\n const QString &errorName, const QString &errorMessage)\n : PendingOperation(manager),\n mPriv(new Private(this, manager, contacts, features))\n{\n if (!errorName.isEmpty()) {\n setFinishedWithError(errorName, errorMessage);\n return;\n }\n\n UIntList handles;\n foreach (const ContactPtr &contact, contacts) {\n handles.push_back(contact->handle()[0]);\n }\n\n mPriv->nested = manager->contactsForHandles(handles, features);\n connect(mPriv->nested,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(onNestedFinished(Tp::PendingOperation*)));\n}\n\n\/**\n * Class destructor.\n *\/\nPendingContacts::~PendingContacts()\n{\n delete mPriv;\n}\n\nContactManagerPtr PendingContacts::manager() const\n{\n return mPriv->manager;\n}\n\nFeatures PendingContacts::features() const\n{\n return mPriv->features;\n}\n\nbool PendingContacts::isForHandles() const\n{\n return mPriv->requestType == Private::ForHandles;\n}\n\nUIntList PendingContacts::handles() const\n{\n if (!isForHandles()) {\n warning() << \"Tried to get handles from\" << this << \"which is not for handles!\";\n }\n\n return mPriv->handles;\n}\n\nbool PendingContacts::isForIdentifiers() const\n{\n return mPriv->requestType == Private::ForIdentifiers;\n}\n\nQStringList PendingContacts::identifiers() const\n{\n if (!isForIdentifiers()) {\n warning() << \"Tried to get identifiers from\" << this << \"which is not for identifiers!\";\n }\n\n return mPriv->identifiers;\n}\n\nbool PendingContacts::isUpgrade() const\n{\n return mPriv->requestType == Private::Upgrade;\n}\n\nQList PendingContacts::contactsToUpgrade() const\n{\n if (!isUpgrade()) {\n warning() << \"Tried to get contacts to upgrade from\" << this << \"which is not an upgrade!\";\n }\n\n return mPriv->contactsToUpgrade;\n}\n\nQList PendingContacts::contacts() const\n{\n if (!isFinished()) {\n warning() << \"PendingContacts::contacts() called before finished\";\n } else if (isError()) {\n warning() << \"PendingContacts::contacts() called when errored\";\n }\n\n return mPriv->contacts;\n}\n\nUIntList PendingContacts::invalidHandles() const\n{\n if (!isFinished()) {\n warning() << \"PendingContacts::invalidHandles() called before finished\";\n } else if (isError()) {\n warning() << \"PendingContacts::invalidHandles() called when errored\";\n } else if (!isForHandles()) {\n warning() << \"PendingContacts::invalidHandles() called for\" << this << \"which is for IDs!\";\n }\n\n return mPriv->invalidHandles;\n}\n\nQStringList PendingContacts::validIdentifiers() const\n{\n if (!isFinished()) {\n warning() << \"PendingContacts::validIdentifiers called before finished\";\n } else if (!isValid()) {\n warning() << \"PendingContacts::validIdentifiers called when not valid\";\n }\n\n return mPriv->validIds;\n}\n\nQHash > PendingContacts::invalidIdentifiers() const\n{\n if (!isFinished()) {\n warning() << \"PendingContacts::invalidIdentifiers called before finished\";\n }\n\n return mPriv->invalidIds;\n}\n\nvoid PendingContacts::onAttributesFinished(PendingOperation *operation)\n{\n PendingContactAttributes *pendingAttributes =\n qobject_cast(operation);\n\n if (pendingAttributes->isError()) {\n debug() << \"PendingAttrs error\" << pendingAttributes->errorName()\n << \"message\" << pendingAttributes->errorMessage();\n setFinishedWithError(pendingAttributes->errorName(), pendingAttributes->errorMessage());\n return;\n }\n\n ReferencedHandles validHandles = pendingAttributes->validHandles();\n ContactAttributesMap attributes = pendingAttributes->attributes();\n\n foreach (uint handle, mPriv->handles) {\n if (!mPriv->satisfyingContacts.contains(handle)) {\n int indexInValid = validHandles.indexOf(handle);\n if (indexInValid >= 0) {\n ReferencedHandles referencedHandle = validHandles.mid(indexInValid, 1);\n QVariantMap handleAttributes = attributes[handle];\n mPriv->satisfyingContacts.insert(handle, manager()->ensureContact(referencedHandle,\n mPriv->missingFeatures, handleAttributes));\n } else {\n mPriv->invalidHandles.push_back(handle);\n }\n }\n }\n\n allAttributesFetched();\n}\n\nvoid PendingContacts::onRequestHandlesFinished(PendingOperation *operation)\n{\n PendingHandles *pendingHandles = qobject_cast(operation);\n\n mPriv->validIds = pendingHandles->validNames();\n mPriv->invalidIds = pendingHandles->invalidNames();\n\n if (pendingHandles->isError()) {\n debug() << \"RequestHandles error\" << operation->errorName()\n << \"message\" << operation->errorMessage();\n setFinishedWithError(operation->errorName(), operation->errorMessage());\n return;\n }\n\n mPriv->nested = manager()->contactsForHandles(pendingHandles->handles(), features());\n connect(mPriv->nested,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(onNestedFinished(Tp::PendingOperation*)));\n}\n\nvoid PendingContacts::onReferenceHandlesFinished(PendingOperation *operation)\n{\n PendingHandles *pendingHandles = qobject_cast(operation);\n\n if (pendingHandles->isError()) {\n debug() << \"ReferenceHandles error\" << operation->errorName()\n << \"message\" << operation->errorMessage();\n setFinishedWithError(operation->errorName(), operation->errorMessage());\n return;\n }\n\n ReferencedHandles validHandles = pendingHandles->handles();\n UIntList invalidHandles = pendingHandles->invalidHandles();\n ConnectionPtr conn = mPriv->manager->connection();\n mPriv->handlesToInspect = ReferencedHandles(conn, HandleTypeContact, UIntList());\n foreach (uint handle, mPriv->handles) {\n if (!mPriv->satisfyingContacts.contains(handle)) {\n int indexInValid = validHandles.indexOf(handle);\n if (indexInValid >= 0) {\n ReferencedHandles referencedHandle = validHandles.mid(indexInValid, 1);\n mPriv->handlesToInspect.append(referencedHandle);\n } else {\n mPriv->invalidHandles.push_back(handle);\n }\n }\n }\n\n QDBusPendingCallWatcher *watcher =\n new QDBusPendingCallWatcher(\n conn->baseInterface()->InspectHandles(HandleTypeContact,\n mPriv->handlesToInspect.toList()),\n this);\n connect(watcher,\n SIGNAL(finished(QDBusPendingCallWatcher*)),\n SLOT(onInspectHandlesFinished(QDBusPendingCallWatcher*)));\n}\n\nvoid PendingContacts::onNestedFinished(PendingOperation *operation)\n{\n Q_ASSERT(operation == mPriv->nested);\n\n if (operation->isError()) {\n debug() << \" error\" << operation->errorName()\n << \"message\" << operation->errorMessage();\n setFinishedWithError(operation->errorName(), operation->errorMessage());\n return;\n }\n\n mPriv->contacts = mPriv->nested->contacts();\n mPriv->nested = 0;\n mPriv->setFinished();\n}\n\nvoid PendingContacts::onInspectHandlesFinished(QDBusPendingCallWatcher *watcher)\n{\n QDBusPendingReply reply = *watcher;\n\n if (reply.isError()) {\n debug().nospace() << \"InspectHandles: error \" << reply.error().name() << \": \"\n << reply.error().message();\n setFinishedWithError(reply.error());\n return;\n }\n\n QStringList names = reply.value();\n int i = 0;\n ConnectionPtr conn = mPriv->manager->connection();\n foreach (uint handle, mPriv->handlesToInspect) {\n QVariantMap handleAttributes;\n handleAttributes.insert(QLatin1String(TELEPATHY_INTERFACE_CONNECTION \"\/contact-id\"),\n names[i++]);\n ReferencedHandles referencedHandle(conn, HandleTypeContact,\n UIntList() << handle);\n mPriv->satisfyingContacts.insert(handle, manager()->ensureContact(referencedHandle,\n mPriv->missingFeatures, handleAttributes));\n }\n\n allAttributesFetched();\n\n watcher->deleteLater();\n}\n\nvoid PendingContacts::allAttributesFetched()\n{\n foreach (uint handle, mPriv->handles) {\n if (mPriv->satisfyingContacts.contains(handle)) {\n mPriv->contacts.push_back(mPriv->satisfyingContacts[handle]);\n }\n }\n\n mPriv->setFinished();\n}\n\n} \/\/ Tp\nPendingContacts: Update docs.\/**\n * This file is part of TelepathyQt4\n *\n * @copyright Copyright (C) 2008 Collabora Ltd. \n * @copyright Copyright (C) 2008 Nokia Corporation\n * @license LGPL 2.1\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \n#include \"TelepathyQt4\/_gen\/pending-contacts.moc.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"TelepathyQt4\/debug-internal.h\"\n\nnamespace Tp\n{\n\nstruct TELEPATHY_QT4_NO_EXPORT PendingContacts::Private\n{\n enum RequestType\n {\n ForHandles,\n ForIdentifiers,\n Upgrade\n };\n\n Private(PendingContacts *parent, const ContactManagerPtr &manager, const UIntList &handles,\n const Features &features, const Features &missingFeatures,\n const QMap &satisfyingContacts)\n : parent(parent),\n manager(manager),\n features(features),\n missingFeatures(missingFeatures),\n satisfyingContacts(satisfyingContacts),\n requestType(ForHandles),\n handles(handles),\n nested(0)\n {\n }\n\n Private(PendingContacts *parent, const ContactManagerPtr &manager, const QStringList &identifiers,\n const Features &features)\n : parent(parent),\n manager(manager),\n features(features),\n requestType(ForIdentifiers),\n identifiers(identifiers),\n nested(0)\n {\n }\n\n Private(PendingContacts *parent,\n const ContactManagerPtr &manager, const QList &contactsToUpgrade,\n const Features &features)\n : parent(parent),\n manager(manager),\n features(features),\n requestType(Upgrade),\n contactsToUpgrade(contactsToUpgrade),\n nested(0)\n {\n }\n\n void setFinished();\n\n \/\/ Public object\n PendingContacts *parent;\n\n \/\/ Generic parameters\n ContactManagerPtr manager;\n Features features;\n Features missingFeatures;\n QMap satisfyingContacts;\n\n \/\/ Request type specific parameters\n RequestType requestType;\n UIntList handles;\n QStringList identifiers;\n QList contactsToUpgrade;\n PendingContacts *nested;\n\n \/\/ Results\n QList contacts;\n UIntList invalidHandles;\n QStringList validIds;\n QHash > invalidIds;\n\n ReferencedHandles handlesToInspect;\n};\n\nvoid PendingContacts::Private::setFinished()\n{\n ConnectionLowlevelPtr connLowlevel = manager->connection()->lowlevel();\n UIntList handles = invalidHandles;\n foreach (uint handle, handles) {\n if (connLowlevel->hasContactId(handle)) {\n satisfyingContacts.insert(handle, manager->ensureContact(handle,\n connLowlevel->contactId(handle), missingFeatures));\n invalidHandles.removeOne(handle);\n }\n }\n\n parent->setFinished();\n}\n\n\/**\n * \\class PendingContacts\n * \\ingroup clientconn\n * \\headerfile TelepathyQt4\/pending-contacts.h \n *\n * \\brief The PendingContacts class is used by ContactManager when\n * creating\/updating Contact objects.\n *\n * See \\ref async_model\n *\/\n\nPendingContacts::PendingContacts(const ContactManagerPtr &manager,\n const UIntList &handles,\n const Features &features,\n const Features &missingFeatures,\n const QStringList &interfaces,\n const QMap &satisfyingContacts,\n const QSet &otherContacts,\n const QString &errorName,\n const QString &errorMessage)\n : PendingOperation(manager),\n mPriv(new Private(this, manager, handles, features, missingFeatures, satisfyingContacts))\n{\n if (!errorName.isEmpty()) {\n setFinishedWithError(errorName, errorMessage);\n return;\n }\n\n if (!otherContacts.isEmpty()) {\n ConnectionPtr conn = manager->connection();\n if (conn->interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_CONTACTS))) {\n PendingContactAttributes *attributes =\n conn->lowlevel()->contactAttributes(otherContacts.toList(),\n interfaces, true);\n\n connect(attributes,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(onAttributesFinished(Tp::PendingOperation*)));\n } else {\n \/\/ fallback to just create the contacts\n PendingHandles *handles = conn->lowlevel()->referenceHandles(HandleTypeContact,\n otherContacts.toList());\n connect(handles,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(onReferenceHandlesFinished(Tp::PendingOperation*)));\n }\n } else {\n allAttributesFetched();\n }\n}\n\nPendingContacts::PendingContacts(const ContactManagerPtr &manager,\n const QStringList &identifiers, const Features &features,\n const QString &errorName, const QString &errorMessage)\n : PendingOperation(manager),\n mPriv(new Private(this, manager, identifiers, features))\n{\n if (!errorName.isEmpty()) {\n setFinishedWithError(errorName, errorMessage);\n return;\n }\n\n ConnectionPtr conn = manager->connection();\n PendingHandles *handles = conn->lowlevel()->requestHandles(HandleTypeContact, identifiers);\n\n connect(handles,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(onRequestHandlesFinished(Tp::PendingOperation*)));\n}\n\nPendingContacts::PendingContacts(const ContactManagerPtr &manager,\n const QList &contacts, const Features &features,\n const QString &errorName, const QString &errorMessage)\n : PendingOperation(manager),\n mPriv(new Private(this, manager, contacts, features))\n{\n if (!errorName.isEmpty()) {\n setFinishedWithError(errorName, errorMessage);\n return;\n }\n\n UIntList handles;\n foreach (const ContactPtr &contact, contacts) {\n handles.push_back(contact->handle()[0]);\n }\n\n mPriv->nested = manager->contactsForHandles(handles, features);\n connect(mPriv->nested,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(onNestedFinished(Tp::PendingOperation*)));\n}\n\n\/**\n * Class destructor.\n *\/\nPendingContacts::~PendingContacts()\n{\n delete mPriv;\n}\n\nContactManagerPtr PendingContacts::manager() const\n{\n return mPriv->manager;\n}\n\nFeatures PendingContacts::features() const\n{\n return mPriv->features;\n}\n\nbool PendingContacts::isForHandles() const\n{\n return mPriv->requestType == Private::ForHandles;\n}\n\nUIntList PendingContacts::handles() const\n{\n if (!isForHandles()) {\n warning() << \"Tried to get handles from\" << this << \"which is not for handles!\";\n }\n\n return mPriv->handles;\n}\n\nbool PendingContacts::isForIdentifiers() const\n{\n return mPriv->requestType == Private::ForIdentifiers;\n}\n\nQStringList PendingContacts::identifiers() const\n{\n if (!isForIdentifiers()) {\n warning() << \"Tried to get identifiers from\" << this << \"which is not for identifiers!\";\n }\n\n return mPriv->identifiers;\n}\n\nbool PendingContacts::isUpgrade() const\n{\n return mPriv->requestType == Private::Upgrade;\n}\n\nQList PendingContacts::contactsToUpgrade() const\n{\n if (!isUpgrade()) {\n warning() << \"Tried to get contacts to upgrade from\" << this << \"which is not an upgrade!\";\n }\n\n return mPriv->contactsToUpgrade;\n}\n\nQList PendingContacts::contacts() const\n{\n if (!isFinished()) {\n warning() << \"PendingContacts::contacts() called before finished\";\n } else if (isError()) {\n warning() << \"PendingContacts::contacts() called when errored\";\n }\n\n return mPriv->contacts;\n}\n\nUIntList PendingContacts::invalidHandles() const\n{\n if (!isFinished()) {\n warning() << \"PendingContacts::invalidHandles() called before finished\";\n } else if (isError()) {\n warning() << \"PendingContacts::invalidHandles() called when errored\";\n } else if (!isForHandles()) {\n warning() << \"PendingContacts::invalidHandles() called for\" << this << \"which is for IDs!\";\n }\n\n return mPriv->invalidHandles;\n}\n\nQStringList PendingContacts::validIdentifiers() const\n{\n if (!isFinished()) {\n warning() << \"PendingContacts::validIdentifiers called before finished\";\n } else if (!isValid()) {\n warning() << \"PendingContacts::validIdentifiers called when not valid\";\n }\n\n return mPriv->validIds;\n}\n\nQHash > PendingContacts::invalidIdentifiers() const\n{\n if (!isFinished()) {\n warning() << \"PendingContacts::invalidIdentifiers called before finished\";\n }\n\n return mPriv->invalidIds;\n}\n\nvoid PendingContacts::onAttributesFinished(PendingOperation *operation)\n{\n PendingContactAttributes *pendingAttributes =\n qobject_cast(operation);\n\n if (pendingAttributes->isError()) {\n debug() << \"PendingAttrs error\" << pendingAttributes->errorName()\n << \"message\" << pendingAttributes->errorMessage();\n setFinishedWithError(pendingAttributes->errorName(), pendingAttributes->errorMessage());\n return;\n }\n\n ReferencedHandles validHandles = pendingAttributes->validHandles();\n ContactAttributesMap attributes = pendingAttributes->attributes();\n\n foreach (uint handle, mPriv->handles) {\n if (!mPriv->satisfyingContacts.contains(handle)) {\n int indexInValid = validHandles.indexOf(handle);\n if (indexInValid >= 0) {\n ReferencedHandles referencedHandle = validHandles.mid(indexInValid, 1);\n QVariantMap handleAttributes = attributes[handle];\n mPriv->satisfyingContacts.insert(handle, manager()->ensureContact(referencedHandle,\n mPriv->missingFeatures, handleAttributes));\n } else {\n mPriv->invalidHandles.push_back(handle);\n }\n }\n }\n\n allAttributesFetched();\n}\n\nvoid PendingContacts::onRequestHandlesFinished(PendingOperation *operation)\n{\n PendingHandles *pendingHandles = qobject_cast(operation);\n\n mPriv->validIds = pendingHandles->validNames();\n mPriv->invalidIds = pendingHandles->invalidNames();\n\n if (pendingHandles->isError()) {\n debug() << \"RequestHandles error\" << operation->errorName()\n << \"message\" << operation->errorMessage();\n setFinishedWithError(operation->errorName(), operation->errorMessage());\n return;\n }\n\n mPriv->nested = manager()->contactsForHandles(pendingHandles->handles(), features());\n connect(mPriv->nested,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(onNestedFinished(Tp::PendingOperation*)));\n}\n\nvoid PendingContacts::onReferenceHandlesFinished(PendingOperation *operation)\n{\n PendingHandles *pendingHandles = qobject_cast(operation);\n\n if (pendingHandles->isError()) {\n debug() << \"ReferenceHandles error\" << operation->errorName()\n << \"message\" << operation->errorMessage();\n setFinishedWithError(operation->errorName(), operation->errorMessage());\n return;\n }\n\n ReferencedHandles validHandles = pendingHandles->handles();\n UIntList invalidHandles = pendingHandles->invalidHandles();\n ConnectionPtr conn = mPriv->manager->connection();\n mPriv->handlesToInspect = ReferencedHandles(conn, HandleTypeContact, UIntList());\n foreach (uint handle, mPriv->handles) {\n if (!mPriv->satisfyingContacts.contains(handle)) {\n int indexInValid = validHandles.indexOf(handle);\n if (indexInValid >= 0) {\n ReferencedHandles referencedHandle = validHandles.mid(indexInValid, 1);\n mPriv->handlesToInspect.append(referencedHandle);\n } else {\n mPriv->invalidHandles.push_back(handle);\n }\n }\n }\n\n QDBusPendingCallWatcher *watcher =\n new QDBusPendingCallWatcher(\n conn->baseInterface()->InspectHandles(HandleTypeContact,\n mPriv->handlesToInspect.toList()),\n this);\n connect(watcher,\n SIGNAL(finished(QDBusPendingCallWatcher*)),\n SLOT(onInspectHandlesFinished(QDBusPendingCallWatcher*)));\n}\n\nvoid PendingContacts::onNestedFinished(PendingOperation *operation)\n{\n Q_ASSERT(operation == mPriv->nested);\n\n if (operation->isError()) {\n debug() << \" error\" << operation->errorName()\n << \"message\" << operation->errorMessage();\n setFinishedWithError(operation->errorName(), operation->errorMessage());\n return;\n }\n\n mPriv->contacts = mPriv->nested->contacts();\n mPriv->nested = 0;\n mPriv->setFinished();\n}\n\nvoid PendingContacts::onInspectHandlesFinished(QDBusPendingCallWatcher *watcher)\n{\n QDBusPendingReply reply = *watcher;\n\n if (reply.isError()) {\n debug().nospace() << \"InspectHandles: error \" << reply.error().name() << \": \"\n << reply.error().message();\n setFinishedWithError(reply.error());\n return;\n }\n\n QStringList names = reply.value();\n int i = 0;\n ConnectionPtr conn = mPriv->manager->connection();\n foreach (uint handle, mPriv->handlesToInspect) {\n QVariantMap handleAttributes;\n handleAttributes.insert(QLatin1String(TELEPATHY_INTERFACE_CONNECTION \"\/contact-id\"),\n names[i++]);\n ReferencedHandles referencedHandle(conn, HandleTypeContact,\n UIntList() << handle);\n mPriv->satisfyingContacts.insert(handle, manager()->ensureContact(referencedHandle,\n mPriv->missingFeatures, handleAttributes));\n }\n\n allAttributesFetched();\n\n watcher->deleteLater();\n}\n\nvoid PendingContacts::allAttributesFetched()\n{\n foreach (uint handle, mPriv->handles) {\n if (mPriv->satisfyingContacts.contains(handle)) {\n mPriv->contacts.push_back(mPriv->satisfyingContacts[handle]);\n }\n }\n\n mPriv->setFinished();\n}\n\n} \/\/ Tp\n<|endoftext|>"} {"text":"\/*!\n \\file encoding.cpp\n \\brief Encoding utilities implementation\n \\author Ivan Shynkarenka\n \\date 12.08.2016\n \\copyright MIT License\n*\/\n\n#include \"string\/encoding.h\"\n\n#include \n#include \n\nnamespace CppCommon {\n\nstd::string Encoding::ToUTF8(const std::wstring& wstr)\n{\n#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)\n std::wstring_convert> convert;\n return convert.to_bytes(wstr);\n#elif defined(_WIN32) || defined(_WIN64)\n std::wstring_convert> convert;\n return convert.to_bytes(wstr);\n#endif\n}\n\nstd::wstring Encoding::FromUTF8(const std::string& str)\n{\n#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)\n std::wstring_convert> convert;\n return convert.from_bytes(str);\n#elif defined(_WIN32) || defined(_WIN64)\n std::wstring_convert> convert;\n return convert.from_bytes(str);\n#endif\n}\n\nstd::u16string Encoding::UTF8toUTF16(const std::string& str)\n{\n#if defined(_MSC_VER) && (_MSC_VER == 1900)\n std::wstring_convert, uint16_t> convert;\n auto tmp = convert.from_bytes(str);\n return std::u16string(tmp.data(), tmp.data() + tmp.size());\n#else\n std::wstring_convert, char16_t> convert;\n return convert.from_bytes(str);\n#endif\n}\n\nstd::u32string Encoding::UTF8toUTF32(const std::string& str)\n{\n#if defined(_MSC_VER) && (_MSC_VER == 1900)\n std::wstring_convert, uint32_t> convert;\n auto tmp = convert.from_bytes(str);\n return std::u32string(tmp.data(), tmp.data() + tmp.size());\n#else\n std::wstring_convert, char32_t> convert;\n return convert.from_bytes(str);\n#endif\n}\n\nstd::string Encoding::UTF16toUTF8(const std::u16string& str)\n{\n#if defined(_MSC_VER) && (_MSC_VER == 1900)\n std::wstring_convert, uint16_t> convert;\n return convert.to_bytes((uint16_t*)str.data(), (uint16_t*)str.data() + str.size());\n#else\n std::wstring_convert, char16_t> convert;\n return convert.to_bytes(str);\n#endif\n}\n\nstd::u32string Encoding::UTF16toUTF32(const std::u16string& str)\n{\n std::string bytes;\n bytes.reserve(str.size() * 2);\n\n for (const char16_t ch : str)\n {\n bytes.push_back((uint8_t)(ch \/ 256));\n bytes.push_back((uint8_t)(ch % 256));\n }\n\n#if defined(_MSC_VER) && (_MSC_VER == 1900)\n std::wstring_convert, uint32_t> convert;\n auto tmp = convert.from_bytes(bytes);\n return std::u32string(tmp.data(), tmp.data() + tmp.size());\n#else\n std::wstring_convert, char32_t> convert;\n return convert.from_bytes(bytes);\n#endif\n}\n\nstd::string Encoding::UTF32toUTF8(const std::u32string& str)\n{\n#if defined(_MSC_VER) && (_MSC_VER == 1900)\n std::wstring_convert, uint32_t> convert;\n return convert.to_bytes((uint32_t*)str.data(), (uint32_t*)str.data() + str.size());\n#else\n std::wstring_convert, char32_t> convert;\n return convert.to_bytes(str);\n#endif\n}\n\nstd::u16string Encoding::UTF32toUTF16(const std::u32string& str)\n{\n#if defined(_MSC_VER) && (_MSC_VER == 1900)\n std::wstring_convert, uint32_t> convert;\n std::string bytes = convert.to_bytes((uint32_t*)str.data(), (uint32_t*)str.data() + str.size());\n#else\n std::wstring_convert, char32_t> convert;\n std::string bytes = convert.to_bytes(str);\n#endif\n\n std::u16string result;\n result.reserve(bytes.size() \/ 2);\n\n for (size_t i = 0; i < bytes.size(); i += 2)\n result.push_back((char16_t)((uint8_t)(bytes[i]) * 256 + (uint8_t)(bytes[i + 1])));\n\n return result;\n}\n\n} \/\/ namespace CppCommon\nFix Cygwin build\/*!\n \\file encoding.cpp\n \\brief Encoding utilities implementation\n \\author Ivan Shynkarenka\n \\date 12.08.2016\n \\copyright MIT License\n*\/\n\n#include \"string\/encoding.h\"\n\n#include \n#include \n\nnamespace CppCommon {\n\nstd::string Encoding::ToUTF8(const std::wstring& wstr)\n{\n#if defined(__CYGWIN__)\n std::wstring_convert, char16_t> convert;\n return convert.to_bytes((char16_t*)wstr.data(), (char16_t*)wstr.data() + wstr.size());\n#elif defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)\n std::wstring_convert> convert;\n return convert.to_bytes(wstr);\n#elif defined(_WIN32) || defined(_WIN64)\n std::wstring_convert> convert;\n return convert.to_bytes(wstr);\n#endif\n}\n\nstd::wstring Encoding::FromUTF8(const std::string& str)\n{\n#if defined(__CYGWIN__)\n std::wstring_convert, char16_t> convert;\n auto tmp = convert.from_bytes(str);\n return std::wstring(tmp.data(), tmp.data() + tmp.size());\n#elif defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)\n std::wstring_convert> convert;\n return convert.from_bytes(str);\n#elif defined(_WIN32) || defined(_WIN64)\n std::wstring_convert> convert;\n return convert.from_bytes(str);\n#endif\n}\n\nstd::u16string Encoding::UTF8toUTF16(const std::string& str)\n{\n#if defined(_MSC_VER) && (_MSC_VER == 1900)\n std::wstring_convert, uint16_t> convert;\n auto tmp = convert.from_bytes(str);\n return std::u16string(tmp.data(), tmp.data() + tmp.size());\n#else\n std::wstring_convert, char16_t> convert;\n return convert.from_bytes(str);\n#endif\n}\n\nstd::u32string Encoding::UTF8toUTF32(const std::string& str)\n{\n#if defined(_MSC_VER) && (_MSC_VER == 1900)\n std::wstring_convert, uint32_t> convert;\n auto tmp = convert.from_bytes(str);\n return std::u32string(tmp.data(), tmp.data() + tmp.size());\n#else\n std::wstring_convert, char32_t> convert;\n return convert.from_bytes(str);\n#endif\n}\n\nstd::string Encoding::UTF16toUTF8(const std::u16string& str)\n{\n#if defined(_MSC_VER) && (_MSC_VER == 1900)\n std::wstring_convert, uint16_t> convert;\n return convert.to_bytes((uint16_t*)str.data(), (uint16_t*)str.data() + str.size());\n#else\n std::wstring_convert, char16_t> convert;\n return convert.to_bytes(str);\n#endif\n}\n\nstd::u32string Encoding::UTF16toUTF32(const std::u16string& str)\n{\n std::string bytes;\n bytes.reserve(str.size() * 2);\n\n for (const char16_t ch : str)\n {\n bytes.push_back((uint8_t)(ch \/ 256));\n bytes.push_back((uint8_t)(ch % 256));\n }\n\n#if defined(_MSC_VER) && (_MSC_VER == 1900)\n std::wstring_convert, uint32_t> convert;\n auto tmp = convert.from_bytes(bytes);\n return std::u32string(tmp.data(), tmp.data() + tmp.size());\n#else\n std::wstring_convert, char32_t> convert;\n return convert.from_bytes(bytes);\n#endif\n}\n\nstd::string Encoding::UTF32toUTF8(const std::u32string& str)\n{\n#if defined(_MSC_VER) && (_MSC_VER == 1900)\n std::wstring_convert, uint32_t> convert;\n return convert.to_bytes((uint32_t*)str.data(), (uint32_t*)str.data() + str.size());\n#else\n std::wstring_convert, char32_t> convert;\n return convert.to_bytes(str);\n#endif\n}\n\nstd::u16string Encoding::UTF32toUTF16(const std::u32string& str)\n{\n#if defined(_MSC_VER) && (_MSC_VER == 1900)\n std::wstring_convert, uint32_t> convert;\n std::string bytes = convert.to_bytes((uint32_t*)str.data(), (uint32_t*)str.data() + str.size());\n#else\n std::wstring_convert, char32_t> convert;\n std::string bytes = convert.to_bytes(str);\n#endif\n\n std::u16string result;\n result.reserve(bytes.size() \/ 2);\n\n for (size_t i = 0; i < bytes.size(); i += 2)\n result.push_back((char16_t)((uint8_t)(bytes[i]) * 256 + (uint8_t)(bytes[i + 1])));\n\n return result;\n}\n\n} \/\/ namespace CppCommon\n<|endoftext|>"} {"text":"\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"kudu\/util\/debug\/leakcheck_disabler.h\"\n#include \"kudu\/util\/mutex.h\"\n#include \"kudu\/util\/thread.h\"\n#include \"kudu\/util\/net\/ssl_factory.h\"\n#include \"kudu\/util\/net\/ssl_socket.h\"\n\nnamespace kudu {\n\n\/\/ These non-POD elements will be alive for the lifetime of the process, so don't allocate in\n\/\/ static storage.\nstatic std::vector ssl_mutexes;\n\n\/\/ Lock\/Unlock the nth lock. Only to be used by OpenSSL.\nstatic void CryptoLockingCallback(int mode, int n, const char* \/*unused*\/, int \/*unused*\/) {\n if (mode & CRYPTO_LOCK) {\n ssl_mutexes[n]->Acquire();\n } else {\n ssl_mutexes[n]->Release();\n }\n}\n\n\/\/ Return the current pthread's tid. Only to be used by OpenSSL.\nstatic void CryptoThreadIDCallback(CRYPTO_THREADID* id) {\n return CRYPTO_THREADID_set_numeric(id, Thread::UniqueThreadId());\n}\n\nvoid DoSSLInit() {\n SSL_library_init();\n SSL_load_error_strings();\n OpenSSL_add_all_algorithms();\n RAND_poll();\n\n for (int i = 0; i < CRYPTO_num_locks(); ++i) {\n debug::ScopedLeakCheckDisabler d;\n ssl_mutexes.push_back(new Mutex());\n }\n\n \/\/ Callbacks used by OpenSSL required in a multi-threaded setting.\n CRYPTO_set_locking_callback(CryptoLockingCallback);\n CRYPTO_THREADID_set_callback(CryptoThreadIDCallback);\n}\n\nSSLFactory::SSLFactory() : ctx_(nullptr, SSL_CTX_free) {\n static std::once_flag ssl_once;\n std::call_once(ssl_once, DoSSLInit);\n}\n\nSSLFactory::~SSLFactory() {\n}\n\nStatus SSLFactory::Init() {\n CHECK(!ctx_.get());\n \/\/ NOTE: 'SSLv23 method' sounds like it would enable only SSLv2 and SSLv3, but in fact\n \/\/ this is a sort of wildcard which enables all methods (including TLSv1 and later).\n \/\/ We explicitly disable SSLv2 and SSLv3 below so that only TLS methods remain.\n \/\/ See the discussion on https:\/\/trac.torproject.org\/projects\/tor\/ticket\/11598 for more\n \/\/ info.\n ctx_.reset(SSL_CTX_new(SSLv23_method()));\n if (!ctx_) {\n return Status::RuntimeError(\"Could not create SSL context\");\n }\n SSL_CTX_set_mode(ctx_.get(), SSL_MODE_AUTO_RETRY);\n\n \/\/ Disable SSLv2 and SSLv3 which are vulnerable to various issues such as POODLE.\n \/\/ We support versions back to TLSv1.0 since OpenSSL on RHEL 6.4 and earlier does not\n \/\/ not support TLSv1.1 or later.\n SSL_CTX_set_options(ctx_.get(), SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);\n SSL_CTX_set_verify(ctx_.get(),\n SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, nullptr);\n return Status::OK();\n}\n\nstd::string SSLFactory::GetLastError(int errno_copy) {\n int error_code = ERR_get_error();\n if (error_code == 0) return kudu::ErrnoToString(errno_copy);\n const char* error_reason = ERR_reason_error_string(error_code);\n if (error_reason != NULL) return error_reason;\n return strings::Substitute(\"SSL error $0\", error_code);\n}\n\nStatus SSLFactory::LoadCertificate(const std::string& certificate_path) {\n ERR_clear_error();\n errno = 0;\n if (SSL_CTX_use_certificate_file(ctx_.get(), certificate_path.c_str(), SSL_FILETYPE_PEM) != 1) {\n return Status::NotFound(\n \"Failed to load certificate file '\" + certificate_path + \"': \" + GetLastError(errno));\n }\n return Status::OK();\n}\n\nStatus SSLFactory::LoadPrivateKey(const std::string& key_path) {\n ERR_clear_error();\n errno = 0;\n if (SSL_CTX_use_PrivateKey_file(ctx_.get(), key_path.c_str(), SSL_FILETYPE_PEM) != 1) {\n return Status::NotFound(\n \"Failed to load private key file '\" + key_path + \"': \" + GetLastError(errno));\n }\n return Status::OK();\n}\n\nStatus SSLFactory::LoadCertificateAuthority(const std::string& certificate_path) {\n ERR_clear_error();\n errno = 0;\n if (SSL_CTX_load_verify_locations(ctx_.get(), certificate_path.c_str(), nullptr) != 1) {\n return Status::NotFound(\n \"Failed to load certificate authority file '\" + certificate_path + \"': \" +\n GetLastError(errno));\n }\n return Status::OK();\n}\n\nstd::unique_ptr SSLFactory::CreateSocket(int socket_fd, bool is_server) {\n CHECK(ctx_);\n \/\/ Create SSL object and transfer ownership to the SSLSocket object created.\n SSL* ssl = SSL_new(ctx_.get());\n if (ssl == nullptr) {\n return nullptr;\n }\n std::unique_ptr socket(new SSLSocket(socket_fd, ssl, is_server));\n return socket;\n \/\/return new SSLSocket(socket_fd, ssl, is_server);\n}\n\n} \/\/ namespace kudu\n[ssl] disable SSL\/TLS compression\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"kudu\/util\/debug\/leakcheck_disabler.h\"\n#include \"kudu\/util\/mutex.h\"\n#include \"kudu\/util\/thread.h\"\n#include \"kudu\/util\/net\/ssl_factory.h\"\n#include \"kudu\/util\/net\/ssl_socket.h\"\n\nnamespace kudu {\n\n\/\/ These non-POD elements will be alive for the lifetime of the process, so don't allocate in\n\/\/ static storage.\nstatic std::vector ssl_mutexes;\n\n\/\/ Lock\/Unlock the nth lock. Only to be used by OpenSSL.\nstatic void CryptoLockingCallback(int mode, int n, const char* \/*unused*\/, int \/*unused*\/) {\n if (mode & CRYPTO_LOCK) {\n ssl_mutexes[n]->Acquire();\n } else {\n ssl_mutexes[n]->Release();\n }\n}\n\n\/\/ Return the current pthread's tid. Only to be used by OpenSSL.\nstatic void CryptoThreadIDCallback(CRYPTO_THREADID* id) {\n return CRYPTO_THREADID_set_numeric(id, Thread::UniqueThreadId());\n}\n\nvoid DoSSLInit() {\n SSL_library_init();\n SSL_load_error_strings();\n OpenSSL_add_all_algorithms();\n RAND_poll();\n\n for (int i = 0; i < CRYPTO_num_locks(); ++i) {\n debug::ScopedLeakCheckDisabler d;\n ssl_mutexes.push_back(new Mutex());\n }\n\n \/\/ Callbacks used by OpenSSL required in a multi-threaded setting.\n CRYPTO_set_locking_callback(CryptoLockingCallback);\n CRYPTO_THREADID_set_callback(CryptoThreadIDCallback);\n}\n\nSSLFactory::SSLFactory() : ctx_(nullptr, SSL_CTX_free) {\n static std::once_flag ssl_once;\n std::call_once(ssl_once, DoSSLInit);\n}\n\nSSLFactory::~SSLFactory() {\n}\n\nStatus SSLFactory::Init() {\n CHECK(!ctx_.get());\n \/\/ NOTE: 'SSLv23 method' sounds like it would enable only SSLv2 and SSLv3, but in fact\n \/\/ this is a sort of wildcard which enables all methods (including TLSv1 and later).\n \/\/ We explicitly disable SSLv2 and SSLv3 below so that only TLS methods remain.\n \/\/ See the discussion on https:\/\/trac.torproject.org\/projects\/tor\/ticket\/11598 for more\n \/\/ info.\n ctx_.reset(SSL_CTX_new(SSLv23_method()));\n if (!ctx_) {\n return Status::RuntimeError(\"Could not create SSL context\");\n }\n SSL_CTX_set_mode(ctx_.get(), SSL_MODE_AUTO_RETRY);\n\n \/\/ Disable SSLv2 and SSLv3 which are vulnerable to various issues such as POODLE.\n \/\/ We support versions back to TLSv1.0 since OpenSSL on RHEL 6.4 and earlier does not\n \/\/ not support TLSv1.1 or later.\n \/\/\n \/\/ Disable SSL\/TLS compression to free up CPU resources and be less prone\n \/\/ to attacks exploiting the compression feature:\n \/\/ https:\/\/tools.ietf.org\/html\/rfc7525#section-3.3\n SSL_CTX_set_options(ctx_.get(),\n SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |\n SSL_OP_NO_COMPRESSION);\n SSL_CTX_set_verify(ctx_.get(),\n SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, nullptr);\n return Status::OK();\n}\n\nstd::string SSLFactory::GetLastError(int errno_copy) {\n int error_code = ERR_get_error();\n if (error_code == 0) return kudu::ErrnoToString(errno_copy);\n const char* error_reason = ERR_reason_error_string(error_code);\n if (error_reason != NULL) return error_reason;\n return strings::Substitute(\"SSL error $0\", error_code);\n}\n\nStatus SSLFactory::LoadCertificate(const std::string& certificate_path) {\n ERR_clear_error();\n errno = 0;\n if (SSL_CTX_use_certificate_file(ctx_.get(), certificate_path.c_str(), SSL_FILETYPE_PEM) != 1) {\n return Status::NotFound(\n \"Failed to load certificate file '\" + certificate_path + \"': \" + GetLastError(errno));\n }\n return Status::OK();\n}\n\nStatus SSLFactory::LoadPrivateKey(const std::string& key_path) {\n ERR_clear_error();\n errno = 0;\n if (SSL_CTX_use_PrivateKey_file(ctx_.get(), key_path.c_str(), SSL_FILETYPE_PEM) != 1) {\n return Status::NotFound(\n \"Failed to load private key file '\" + key_path + \"': \" + GetLastError(errno));\n }\n return Status::OK();\n}\n\nStatus SSLFactory::LoadCertificateAuthority(const std::string& certificate_path) {\n ERR_clear_error();\n errno = 0;\n if (SSL_CTX_load_verify_locations(ctx_.get(), certificate_path.c_str(), nullptr) != 1) {\n return Status::NotFound(\n \"Failed to load certificate authority file '\" + certificate_path + \"': \" +\n GetLastError(errno));\n }\n return Status::OK();\n}\n\nstd::unique_ptr SSLFactory::CreateSocket(int socket_fd, bool is_server) {\n CHECK(ctx_);\n \/\/ Create SSL object and transfer ownership to the SSLSocket object created.\n SSL* ssl = SSL_new(ctx_.get());\n if (ssl == nullptr) {\n return nullptr;\n }\n std::unique_ptr socket(new SSLSocket(socket_fd, ssl, is_server));\n return socket;\n \/\/return new SSLSocket(socket_fd, ssl, is_server);\n}\n\n} \/\/ namespace kudu\n<|endoftext|>"} {"text":"#include \"matrix.hpp\"\n\nMatrix::Matrix(int length) {\n\trow = length;\n\tcol = length;\n\n\tmas = new int*[row];\n\tfor (int i = 0; i < row; i++) {\n\t\tmas[i] = new int[col];\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tmas[i][j] = 0;\n\t\t}\n\t}\n}\n\nMatrix::Matrix(int r, int c) {\n\trow = r;\n\tcol = c;\n\n\tmas = new int*[row];\n\tfor (int i = 0; i < row; i++) {\n\t\tmas[i] = new int[col];\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tmas[i][j] = 0;\n\t\t}\n\t}\n}\n\nMatrix::~Matrix() {\n\tfor (int i = 0; i < row; i++) {\n\t\tdelete[] mas[i];\n\t}\n\n\tdelete[] mas;\n}\n\nMatrix::Matrix(const Matrix&a) {\n\trow = a.row;\n\tcol = a.col;\n\n\tmas = new int*[row];\n\tfor (int i = 0; i < row; i++) {\n\t\tmas[i] = new int[col];\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tmas[i][j] = a.mas[i][j];\n\t\t}\n\t}\n}\n\nvoid Matrix::fill( const char*file) {\n\tifstream fin1(file);\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tfin1 >> mas[i][j];\n\t\t}\n\t}\n}\n\nvoid Matrix::show() const {\n\t\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tcout << mas[i][j] << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n\tcout << endl;\n}\n\nMatrix Matrix::operator+(const Matrix& a) const {\n\n\tMatrix help(row, col);\n\n\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\thelp.mas[i][j] = mas[i][j] + a.mas[i][j];\n\t\t}\n\t}\n\treturn help;\n}\n\nMatrix Matrix::operator*(const Matrix& a) const {\n\n\tMatrix help(row, col);\n\n\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\thelp.mas[i][j] = 0;\n\t\t\tfor (int k = 0; k < col; k++) {\n\t\t\t\thelp.mas[i][j] += mas[i][k] * a.mas[k][j];\n\t\t\t}\n\t\t}\n\t}\n\treturn help;\n}\n\nint Matrix::rows() {\n\treturn row;\n}\n\nint Matrix::columns() {\n\treturn col;\n}\n\nint Matrix::Element(int i, int j)\n {\n if (i> (std::istream& is, Matrix& a)\n{\n\tfor (int i = 0; i < a.row; i++)\n\t{\n\t\tfor (int j = 0; j < a.col; j++)\n\t\t{\n\t\t\tcout << \"mas[\" << i << \"][\" << j << \"] = \";\n\t\t\tis >> a.mas[i][j];\n\t\t\tcout << endl;\n\t\t}\n\t}\n\treturn is;\n}\nostream& operator << (std::ostream& os, const Matrix& a)\n{\n\tfor (int i = 0; i < a.row; i++)\n\t{\n\t\tfor (int j = 0; j < a.col; j++)\n\t\t{\n\t\t\tos.width(4);\n\t\t\tos << a.mas[i][j] << \" \";\n\t\t}\n\t\tos << '\\n';\n\t}\n\tos << std::endl;\n\treturn os;\n}\n\nUpdate matrix.cpp#include \"matrix.hpp\"\n\nMatrix::Matrix(int length) {\n\trow = length;\n\tcol = length;\n\n\tmas = new int*[row];\n\tfor (int i = 0; i < row; i++) {\n\t\tmas[i] = new int[col];\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tmas[i][j] = 0;\n\t\t}\n\t}\n}\n\nMatrix::Matrix(int r, int c) {\n\trow = r;\n\tcol = c;\n\n\tmas = new int*[row];\n\tfor (int i = 0; i < row; i++) {\n\t\tmas[i] = new int[col];\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tmas[i][j] = 0;\n\t\t}\n\t}\n}\n\nMatrix::~Matrix() {\n\tfor (int i = 0; i < row; i++) {\n\t\tdelete[] mas[i];\n\t}\n\n\tdelete[] mas;\n}\n\nMatrix::Matrix(const Matrix&a) {\n\trow = a.row;\n\tcol = a.col;\n\n\tmas = new int*[row];\n\tfor (int i = 0; i < row; i++) {\n\t\tmas[i] = new int[col];\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tmas[i][j] = a.mas[i][j];\n\t\t}\n\t}\n}\n\nvoid Matrix::fill( const char*file) {\n\tifstream fin1(file);\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tfin1 >> mas[i][j];\n\t\t}\n\t}\n}\n\nvoid Matrix::show() const {\n\t\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tcout << mas[i][j] << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n\tcout << endl;\n}\n\nMatrix Matrix::operator+(const Matrix& a) const {\n\n\tMatrix help(row, a.col);\n\n\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\thelp.mas[i][j] = mas[i][j] + a.mas[i][j];\n\t\t}\n\t}\n\treturn help;\n}\n\nMatrix Matrix::operator*(const Matrix& a) const {\n\n\tMatrix help(row, col);\n\n\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\thelp.mas[i][j] = 0;\n\t\t\tfor (int k = 0; k < col; k++) {\n\t\t\t\thelp.mas[i][j] += mas[i][k] * a.mas[k][j];\n\t\t\t}\n\t\t}\n\t}\n\treturn help;\n}\n\nint Matrix::rows() const {\n\treturn row;\n}\n\nint Matrix::columns() const {\n\treturn col;\n}\n\nint Matrix::Element(int i, int j) const\n {\n if (i> (std::istream& is, Matrix& a)\n{\n\tfor (int i = 0; i < a.row; i++)\n\t{\n\t\tfor (int j = 0; j < a.col; j++)\n\t\t{\n\t\t\tcout << \"mas[\" << i << \"][\" << j << \"] = \";\n\t\t\tis >> a.mas[i][j];\n\t\t\tcout << endl;\n\t\t}\n\t}\n\treturn is;\n}\nostream& operator << (std::ostream& os, const Matrix& a)\n{\n\tfor (int i = 0; i < a.row; i++)\n\t{\n\t\tfor (int j = 0; j < a.col; j++)\n\t\t{\n\t\t\tos.width(4);\n\t\t\tos << a.mas[i][j] << \" \";\n\t\t}\n\t\tos << '\\n';\n\t}\n\tos << std::endl;\n\treturn os;\n}\n\n<|endoftext|>"} {"text":"\/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/aa365968(VS.85).aspx\n\n\/\/ Targets: Windows\n\/\/ return vector of name servers from \/etc\/resolv.conf\n\n\/\/\n\/\/ Link with IPHlpAPI.lib\n\/\/\n#include \n#include \n#include \n#include \n#pragma comment(lib, \"IPHLPAPI.lib\")\n\n#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))\n#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))\n\n\/* Note: could also use malloc() and free() *\/\n\nint __cdecl main()\n{\n\n FIXED_INFO *pFixedInfo;\n ULONG ulOutBufLen;\n DWORD dwRetVal;\n IP_ADDR_STRING *pIPAddr;\n\n pFixedInfo = (FIXED_INFO *) MALLOC(sizeof (FIXED_INFO));\n ulOutBufLen = sizeof (FIXED_INFO);\n\n GetNetworkParams(pFixedInfo, &ulOutBufLen);\n\n printf(\"DNS Servers:\\n\");\n printf(\"\\t%s\\n\", pFixedInfo->DnsServerList.IpAddress.String);\n\n pIPAddr = pFixedInfo->DnsServerList.Next;\n while (pIPAddr) {\n printf(\"\\t%s\\n\", pIPAddr->IpAddress.String);\n pIPAddr = pIPAddr->Next;\n }\n\n FREE(pFixedInfo);\n return 0;\n}renamed to -win<|endoftext|>"} {"text":"#include \n\n#include \"utils\/math.hpp\"\n#include \"x11\/atoms.hpp\"\n#include \"x11\/window.hpp\"\n#include \"x11\/xutils.hpp\"\n\n#include \"components\/types.hpp\"\n\nLEMONBUDDY_NS\n\nwindow window::create_checked(int16_t x, int16_t y, uint16_t w, uint16_t h, uint32_t mask, const xcb_params_cw_t* p) {\n if (*this == XCB_NONE) {\n resource(connection(), connection().generate_id());\n }\n\n auto root{connection().screen()->root};\n auto copy{XCB_COPY_FROM_PARENT};\n uint32_t values[16]{0};\n xutils::pack_values(mask, p, values);\n connection().create_window_checked(copy, *this, root, x, y, w, h, 0, copy, copy, mask, values);\n\n return *this;\n}\n\nwindow window::reconfigure_geom(uint16_t w, uint16_t h, int16_t x, int16_t y) {\n uint32_t mask{0};\n uint32_t values[7]{0};\n\n xcb_params_configure_window_t params;\n XCB_AUX_ADD_PARAM(&mask, ¶ms, width, w);\n XCB_AUX_ADD_PARAM(&mask, ¶ms, height, h);\n XCB_AUX_ADD_PARAM(&mask, ¶ms, x, x);\n XCB_AUX_ADD_PARAM(&mask, ¶ms, y, y);\n\n xutils::pack_values(mask, ¶ms, values);\n connection().configure_window_checked(*this, mask, values);\n\n return *this;\n}\n\nwindow window::reconfigure_pos(int16_t x, int16_t y) {\n uint32_t mask{0};\n uint32_t values[2]{0};\n\n xcb_params_configure_window_t params;\n XCB_AUX_ADD_PARAM(&mask, ¶ms, x, x);\n XCB_AUX_ADD_PARAM(&mask, ¶ms, y, y);\n\n xutils::pack_values(mask, ¶ms, values);\n connection().configure_window_checked(*this, mask, values);\n\n return *this;\n}\n\nwindow window::reconfigure_struts(uint16_t w, uint16_t h, int16_t x, bool bottom) {\n auto& conn = connection();\n\n uint32_t none{0};\n uint32_t values[12]{none};\n\n if (bottom) {\n values[static_cast(strut::BOTTOM)] = h;\n values[static_cast(strut::BOTTOM_START_X)] = x;\n values[static_cast(strut::BOTTOM_END_X)] = x + w;\n } else {\n values[static_cast(strut::TOP)] = h;\n values[static_cast(strut::TOP_START_X)] = x;\n values[static_cast(strut::TOP_END_X)] = x + w;\n }\n\n conn.change_property_checked(XCB_PROP_MODE_REPLACE, *this, _NET_WM_STRUT, XCB_ATOM_CARDINAL, 32, 4, values);\n conn.change_property_checked(XCB_PROP_MODE_REPLACE, *this, _NET_WM_STRUT_PARTIAL, XCB_ATOM_CARDINAL, 32, 12, values);\n\n return *this;\n}\n\nvoid window::redraw() {\n xutils::visibility_notify(connection(), *this, XCB_VISIBILITY_FULLY_OBSCURED);\n xutils::visibility_notify(connection(), *this, XCB_VISIBILITY_UNOBSCURED);\n connection().flush();\n}\n\nLEMONBUDDY_NS_END\nfix: Strut end values should be inclusive#include \n\n#include \"utils\/math.hpp\"\n#include \"x11\/atoms.hpp\"\n#include \"x11\/window.hpp\"\n#include \"x11\/xutils.hpp\"\n\n#include \"components\/types.hpp\"\n\nLEMONBUDDY_NS\n\nwindow window::create_checked(int16_t x, int16_t y, uint16_t w, uint16_t h, uint32_t mask, const xcb_params_cw_t* p) {\n if (*this == XCB_NONE) {\n resource(connection(), connection().generate_id());\n }\n\n auto root{connection().screen()->root};\n auto copy{XCB_COPY_FROM_PARENT};\n uint32_t values[16]{0};\n xutils::pack_values(mask, p, values);\n connection().create_window_checked(copy, *this, root, x, y, w, h, 0, copy, copy, mask, values);\n\n return *this;\n}\n\nwindow window::reconfigure_geom(uint16_t w, uint16_t h, int16_t x, int16_t y) {\n uint32_t mask{0};\n uint32_t values[7]{0};\n\n xcb_params_configure_window_t params;\n XCB_AUX_ADD_PARAM(&mask, ¶ms, width, w);\n XCB_AUX_ADD_PARAM(&mask, ¶ms, height, h);\n XCB_AUX_ADD_PARAM(&mask, ¶ms, x, x);\n XCB_AUX_ADD_PARAM(&mask, ¶ms, y, y);\n\n xutils::pack_values(mask, ¶ms, values);\n connection().configure_window_checked(*this, mask, values);\n\n return *this;\n}\n\nwindow window::reconfigure_pos(int16_t x, int16_t y) {\n uint32_t mask{0};\n uint32_t values[2]{0};\n\n xcb_params_configure_window_t params;\n XCB_AUX_ADD_PARAM(&mask, ¶ms, x, x);\n XCB_AUX_ADD_PARAM(&mask, ¶ms, y, y);\n\n xutils::pack_values(mask, ¶ms, values);\n connection().configure_window_checked(*this, mask, values);\n\n return *this;\n}\n\nwindow window::reconfigure_struts(uint16_t w, uint16_t h, int16_t x, bool bottom) {\n auto& conn = connection();\n\n uint32_t none{0};\n uint32_t values[12]{none};\n\n if (bottom) {\n values[static_cast(strut::BOTTOM)] = h;\n values[static_cast(strut::BOTTOM_START_X)] = x;\n values[static_cast(strut::BOTTOM_END_X)] = x + w - 1;\n } else {\n values[static_cast(strut::TOP)] = h;\n values[static_cast(strut::TOP_START_X)] = x;\n values[static_cast(strut::TOP_END_X)] = x + w - 1;\n }\n\n conn.change_property_checked(XCB_PROP_MODE_REPLACE, *this, _NET_WM_STRUT, XCB_ATOM_CARDINAL, 32, 4, values);\n conn.change_property_checked(XCB_PROP_MODE_REPLACE, *this, _NET_WM_STRUT_PARTIAL, XCB_ATOM_CARDINAL, 32, 12, values);\n\n return *this;\n}\n\nvoid window::redraw() {\n xutils::visibility_notify(connection(), *this, XCB_VISIBILITY_FULLY_OBSCURED);\n xutils::visibility_notify(connection(), *this, XCB_VISIBILITY_UNOBSCURED);\n connection().flush();\n}\n\nLEMONBUDDY_NS_END\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\n\nstatic const char image_path[] = \"\/sparsebundle.dmg\";\n\nstruct sparsebundle_data {\n char *path;\n off_t band_size;\n off_t size;\n off_t times_opened;\n};\n\n#define SB_DATA_CAST(ptr) ((struct sparsebundle_data *) ptr)\n#define SB_DATA (SB_DATA_CAST(fuse_get_context()->private_data))\n\nstatic int sparsebundle_readdir(const char *path, void *buf, fuse_fill_dir_t filler,\n off_t offset, struct fuse_file_info *fi)\n{\n if (strcmp(path, \"\/\") != 0)\n return -ENOENT;\n\n filler(buf, \".\", 0, 0);\n filler(buf, \"..\", 0, 0);\n filler(buf, image_path + 1, 0, 0);\n\n return 0;\n}\n\nstatic int sparsebundle_getattr(const char *path, struct stat *stbuf)\n{\n memset(stbuf, 0, sizeof(struct stat));\n\n if (strcmp(path, \"\/\") == 0) {\n stbuf->st_mode = S_IFDIR | 0755;\n stbuf->st_nlink = 3;\n } else if (strcmp(path, image_path) == 0) {\n stbuf->st_mode = S_IFREG | 0444;\n stbuf->st_nlink = 1;\n stbuf->st_size = SB_DATA->size;\n } else\n return -ENOENT;\n\n return 0;\n}\n\nstatic int sparsebundle_open(const char *path, struct fuse_file_info *fi)\n{\n if (strcmp(path, image_path) != 0)\n return -ENOENT;\n\n if ((fi->flags & O_ACCMODE) != O_RDONLY)\n return -EACCES;\n\n SB_DATA->times_opened++;\n syslog(LOG_DEBUG, \"opened %s, now referenced %llx times\",\n SB_DATA->path, SB_DATA->times_opened);\n\n return 0;\n}\n\nstatic int sparsebundle_read(const char *path, char *buffer, size_t length, off_t offset,\n struct fuse_file_info *fi)\n{\n if (strcmp(path, image_path) != 0)\n return -ENOENT;\n\n if (offset >= SB_DATA->size)\n return 0;\n\n if (offset + length > SB_DATA->size)\n length = SB_DATA->size - offset;\n\n syslog(LOG_DEBUG, \"asked to read %zu bytes at offset %llu\", length, offset);\n\n size_t bytes_read = 0;\n while (bytes_read < length) {\n off_t band_number = (offset + bytes_read) \/ SB_DATA->band_size;\n off_t band_offset = (offset + bytes_read) % SB_DATA->band_size;\n\n ssize_t to_read = min(static_cast(length - bytes_read),\n SB_DATA->band_size - band_offset);\n\n char *band_name;\n if (asprintf(&band_name, \"%s\/bands\/%llx\", SB_DATA->path, band_number) == -1) {\n syslog(LOG_ERR, \"failed to resolve band name\");\n return -1;\n }\n\n syslog(LOG_DEBUG, \"reading %zu bytes from band %llx at offset %llu\",\n to_read, band_number, band_offset);\n\n ssize_t read = 0;\n int band_file = open(band_name, O_RDONLY);\n if (band_file != -1) {\n read = pread(band_file, buffer + bytes_read, to_read, band_offset);\n close(band_file);\n\n if (read == -1) {\n syslog(LOG_ERR, \"failed to read band: %s\", strerror(errno));\n free(band_name);\n return -1;\n }\n } else if (errno != ENOENT) {\n syslog(LOG_ERR, \"failed to open band %s: %s\", band_name, strerror(errno));\n free(band_name);\n return -1;\n }\n\n free(band_name);\n\n if (read < to_read) {\n syslog(LOG_DEBUG, \"missing %zu bytes from band %llx, padding with zeroes\",\n to_read - read, band_number);\n memset(buffer + bytes_read + read, 0, to_read - read);\n }\n\n bytes_read += to_read;\n\n syslog(LOG_DEBUG, \"done reading from band %llx, %zu bytes left to read\",\n band_number, length - bytes_read);\n }\n\n assert(bytes_read == length);\n return bytes_read;\n}\n\nstatic int sparsebundle_release(const char *path, struct fuse_file_info *fi)\n{\n SB_DATA->times_opened--;\n syslog(LOG_DEBUG, \"closed %s, now referenced %llx times\",\n SB_DATA->path, SB_DATA->times_opened);\n\n if (SB_DATA->times_opened == 0) {\n syslog(LOG_DEBUG, \"no more references to sparsebundle, cleaning up\");\n }\n\n return 0;\n}\n\nstatic int sparsebundle_show_usage(char *program_name)\n{\n fprintf(stderr, \"usage: %s [-o options] [-f] [-D] \\n\", program_name);\n return 1;\n}\n\nenum { SPARSEBUNDLE_OPT_DEBUG };\n\nstatic int sparsebundle_opt_proc(void *data, const char *arg, int key, struct fuse_args *outargs)\n{\n switch (key) {\n case SPARSEBUNDLE_OPT_DEBUG:\n setlogmask(LOG_UPTO(LOG_DEBUG));\n return 0;\n case FUSE_OPT_KEY_NONOPT:\n if (SB_DATA_CAST(data)->path)\n return 1;\n\n SB_DATA_CAST(data)->path = strdup(arg);\n return 0;\n }\n\n return 1;\n}\n\nstatic off_t read_size(const string &str)\n{\n uintmax_t value = strtoumax(str.c_str(), 0, 10);\n if (errno == ERANGE || value > static_cast(numeric_limits::max())) {\n fprintf(stderr, \"Disk image too large to be mounted (%s bytes)\\n\", str.c_str());\n exit(-1);\n }\n\n return value;\n}\n\nint main(int argc, char **argv)\n{\n openlog(\"sparsebundlefs\", LOG_CONS | LOG_PERROR, LOG_USER);\n setlogmask(~(LOG_MASK(LOG_DEBUG)));\n\n struct sparsebundle_data data = {};\n\n static struct fuse_opt sparsebundle_options[] = {\n FUSE_OPT_KEY(\"-D\", SPARSEBUNDLE_OPT_DEBUG), FUSE_OPT_END\n };\n\n struct fuse_args args = FUSE_ARGS_INIT(argc, argv);\n fuse_opt_parse(&args, &data, sparsebundle_options, sparsebundle_opt_proc);\n fuse_opt_add_arg(&args, \"-oro\"); \/\/ Force read-only mount\n\n if (!data.path)\n return sparsebundle_show_usage(argv[0]);\n\n char *abs_path = realpath(data.path, 0);\n if (!abs_path) {\n perror(\"Could not resolve absolute path\");\n return -1;\n }\n\n free(data.path);\n data.path = abs_path;\n\n char *plist_path;\n if (asprintf(&plist_path, \"%s\/Info.plist\", data.path) == -1) {\n perror(\"Failed to resolve Info.plist path\");\n return -1;\n }\n\n ifstream plist_file(plist_path);\n stringstream plist_data;\n plist_data << plist_file.rdbuf();\n\n string key, line;\n while (getline(plist_data, line)) {\n static const char whitespace_chars[] = \" \\n\\r\\t\";\n line.erase(0, line.find_first_not_of(whitespace_chars));\n line.erase(line.find_last_not_of(whitespace_chars) + 1);\n\n if (line.compare(0, 5, \"\") == 0) {\n key = line.substr(5, line.length() - 11);\n } else if (!key.empty()) {\n line.erase(0, line.find_first_of('>') + 1);\n line.erase(line.find_first_of('<'));\n\n if (key == \"band-size\")\n data.band_size = read_size(line);\n else if (key == \"size\")\n data.size = read_size(line);\n\n key.clear();\n }\n }\n\n syslog(LOG_DEBUG, \"initialized %s, band size %llu, total size %llu\",\n data.path, data.band_size, data.size);\n\n struct fuse_operations sparsebundle_filesystem_operations = {};\n sparsebundle_filesystem_operations.getattr = sparsebundle_getattr;\n sparsebundle_filesystem_operations.open = sparsebundle_open;\n sparsebundle_filesystem_operations.read = sparsebundle_read;\n sparsebundle_filesystem_operations.readdir = sparsebundle_readdir;\n sparsebundle_filesystem_operations.release = sparsebundle_release;\n\n return fuse_main(args.argc, args.argv, &sparsebundle_filesystem_operations, &data);\n}\nClean up use of error return codes#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\n\nstatic const char image_path[] = \"\/sparsebundle.dmg\";\n\nstruct sparsebundle_data {\n char *path;\n off_t band_size;\n off_t size;\n off_t times_opened;\n};\n\n#define SB_DATA_CAST(ptr) ((struct sparsebundle_data *) ptr)\n#define SB_DATA (SB_DATA_CAST(fuse_get_context()->private_data))\n\nstatic int sparsebundle_readdir(const char *path, void *buf, fuse_fill_dir_t filler,\n off_t offset, struct fuse_file_info *fi)\n{\n if (strcmp(path, \"\/\") != 0)\n return -ENOENT;\n\n filler(buf, \".\", 0, 0);\n filler(buf, \"..\", 0, 0);\n filler(buf, image_path + 1, 0, 0);\n\n return 0;\n}\n\nstatic int sparsebundle_getattr(const char *path, struct stat *stbuf)\n{\n memset(stbuf, 0, sizeof(struct stat));\n\n if (strcmp(path, \"\/\") == 0) {\n stbuf->st_mode = S_IFDIR | 0755;\n stbuf->st_nlink = 3;\n } else if (strcmp(path, image_path) == 0) {\n stbuf->st_mode = S_IFREG | 0444;\n stbuf->st_nlink = 1;\n stbuf->st_size = SB_DATA->size;\n } else\n return -ENOENT;\n\n return 0;\n}\n\nstatic int sparsebundle_open(const char *path, struct fuse_file_info *fi)\n{\n if (strcmp(path, image_path) != 0)\n return -ENOENT;\n\n if ((fi->flags & O_ACCMODE) != O_RDONLY)\n return -EACCES;\n\n SB_DATA->times_opened++;\n syslog(LOG_DEBUG, \"opened %s, now referenced %llx times\",\n SB_DATA->path, SB_DATA->times_opened);\n\n return 0;\n}\n\nstatic int sparsebundle_read(const char *path, char *buffer, size_t length, off_t offset,\n struct fuse_file_info *fi)\n{\n if (strcmp(path, image_path) != 0)\n return -ENOENT;\n\n if (offset >= SB_DATA->size)\n return 0;\n\n if (offset + length > SB_DATA->size)\n length = SB_DATA->size - offset;\n\n syslog(LOG_DEBUG, \"asked to read %zu bytes at offset %llu\", length, offset);\n\n size_t bytes_read = 0;\n while (bytes_read < length) {\n off_t band_number = (offset + bytes_read) \/ SB_DATA->band_size;\n off_t band_offset = (offset + bytes_read) % SB_DATA->band_size;\n\n ssize_t to_read = min(static_cast(length - bytes_read),\n SB_DATA->band_size - band_offset);\n\n char *band_name;\n if (asprintf(&band_name, \"%s\/bands\/%llx\", SB_DATA->path, band_number) == -1) {\n syslog(LOG_ERR, \"failed to resolve band name\");\n return -errno;\n }\n\n syslog(LOG_DEBUG, \"reading %zu bytes from band %llx at offset %llu\",\n to_read, band_number, band_offset);\n\n ssize_t read = 0;\n int band_file = open(band_name, O_RDONLY);\n if (band_file != -1) {\n read = pread(band_file, buffer + bytes_read, to_read, band_offset);\n close(band_file);\n\n if (read == -1) {\n syslog(LOG_ERR, \"failed to read band: %s\", strerror(errno));\n free(band_name);\n return -errno;\n }\n } else if (errno != ENOENT) {\n syslog(LOG_ERR, \"failed to open band %s: %s\", band_name, strerror(errno));\n free(band_name);\n return -errno;\n }\n\n free(band_name);\n\n if (read < to_read) {\n syslog(LOG_DEBUG, \"missing %zu bytes from band %llx, padding with zeroes\",\n to_read - read, band_number);\n memset(buffer + bytes_read + read, 0, to_read - read);\n }\n\n bytes_read += to_read;\n\n syslog(LOG_DEBUG, \"done reading from band %llx, %zu bytes left to read\",\n band_number, length - bytes_read);\n }\n\n assert(bytes_read == length);\n return bytes_read;\n}\n\nstatic int sparsebundle_release(const char *path, struct fuse_file_info *fi)\n{\n SB_DATA->times_opened--;\n syslog(LOG_DEBUG, \"closed %s, now referenced %llx times\",\n SB_DATA->path, SB_DATA->times_opened);\n\n if (SB_DATA->times_opened == 0) {\n syslog(LOG_DEBUG, \"no more references to sparsebundle, cleaning up\");\n }\n\n return 0;\n}\n\nstatic int sparsebundle_show_usage(char *program_name)\n{\n fprintf(stderr, \"usage: %s [-o options] [-f] [-D] \\n\", program_name);\n return 1;\n}\n\nenum { SPARSEBUNDLE_OPT_DEBUG };\n\nstatic int sparsebundle_opt_proc(void *data, const char *arg, int key, struct fuse_args *outargs)\n{\n switch (key) {\n case SPARSEBUNDLE_OPT_DEBUG:\n setlogmask(LOG_UPTO(LOG_DEBUG));\n return 0;\n case FUSE_OPT_KEY_NONOPT:\n if (SB_DATA_CAST(data)->path)\n return 1;\n\n SB_DATA_CAST(data)->path = strdup(arg);\n return 0;\n }\n\n return 1;\n}\n\nstatic off_t read_size(const string &str)\n{\n uintmax_t value = strtoumax(str.c_str(), 0, 10);\n if (errno == ERANGE || value > static_cast(numeric_limits::max())) {\n fprintf(stderr, \"Disk image too large to be mounted (%s bytes)\\n\", str.c_str());\n exit(EXIT_FAILURE);\n }\n\n return value;\n}\n\nint main(int argc, char **argv)\n{\n openlog(\"sparsebundlefs\", LOG_CONS | LOG_PERROR, LOG_USER);\n setlogmask(~(LOG_MASK(LOG_DEBUG)));\n\n struct sparsebundle_data data = {};\n\n static struct fuse_opt sparsebundle_options[] = {\n FUSE_OPT_KEY(\"-D\", SPARSEBUNDLE_OPT_DEBUG), FUSE_OPT_END\n };\n\n struct fuse_args args = FUSE_ARGS_INIT(argc, argv);\n fuse_opt_parse(&args, &data, sparsebundle_options, sparsebundle_opt_proc);\n fuse_opt_add_arg(&args, \"-oro\"); \/\/ Force read-only mount\n\n if (!data.path)\n return sparsebundle_show_usage(argv[0]);\n\n char *abs_path = realpath(data.path, 0);\n if (!abs_path) {\n perror(\"Could not resolve absolute path\");\n return EXIT_FAILURE;\n }\n\n free(data.path);\n data.path = abs_path;\n\n char *plist_path;\n if (asprintf(&plist_path, \"%s\/Info.plist\", data.path) == -1) {\n perror(\"Failed to resolve Info.plist path\");\n return EXIT_FAILURE;\n }\n\n ifstream plist_file(plist_path);\n stringstream plist_data;\n plist_data << plist_file.rdbuf();\n\n string key, line;\n while (getline(plist_data, line)) {\n static const char whitespace_chars[] = \" \\n\\r\\t\";\n line.erase(0, line.find_first_not_of(whitespace_chars));\n line.erase(line.find_last_not_of(whitespace_chars) + 1);\n\n if (line.compare(0, 5, \"\") == 0) {\n key = line.substr(5, line.length() - 11);\n } else if (!key.empty()) {\n line.erase(0, line.find_first_of('>') + 1);\n line.erase(line.find_first_of('<'));\n\n if (key == \"band-size\")\n data.band_size = read_size(line);\n else if (key == \"size\")\n data.size = read_size(line);\n\n key.clear();\n }\n }\n\n syslog(LOG_DEBUG, \"initialized %s, band size %llu, total size %llu\",\n data.path, data.band_size, data.size);\n\n struct fuse_operations sparsebundle_filesystem_operations = {};\n sparsebundle_filesystem_operations.getattr = sparsebundle_getattr;\n sparsebundle_filesystem_operations.open = sparsebundle_open;\n sparsebundle_filesystem_operations.read = sparsebundle_read;\n sparsebundle_filesystem_operations.readdir = sparsebundle_readdir;\n sparsebundle_filesystem_operations.release = sparsebundle_release;\n\n return fuse_main(args.argc, args.argv, &sparsebundle_filesystem_operations, &data);\n}\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \n#include \n\n\/\/ for debug only\n#include \n#include \n\nusing namespace std;\nusing namespace nanosoft;\n\n\/**\n* Конструктор потока\n*\/\nXMPPStream::XMPPStream(XMPPServer *srv, int sock): AsyncXMLStream(sock), server(srv), XMLWriter(1024), state(init)\n{\n\tdepth = 0;\n\tbuilder = new ATTagBuilder();\n}\n\n\/**\n* Деструктор потока\n*\/\nXMPPStream::~XMPPStream()\n{\n\tdelete builder;\n}\n\n\/**\n* Запись XML\n*\/\nvoid XMPPStream::onWriteXML(const char *data, size_t len)\n{\n\tint r = write(data, len);\n\tif ( r != len ) onError(\"write fault\");\n\tcout << \"written: \\033[22;34m\" << string(data, len) << \"\\033[0m\\n\";\n}\n\n\/**\n* Событие готовности к записи\n*\n* Вызывается, когда в поток готов принять\n* данные для записи без блокировки\n*\/\nvoid XMPPStream::onWrite()\n{\n\tcerr << \"not implemented XMPPStream::onWrite()\" << endl;\n}\n\n\/**\n* Событие закрытие соединения\n*\n* Вызывается если peer закрыл соединение\n*\/\nvoid XMPPStream::onShutdown()\n{\n\tserver->onOffline(this);\n\tAsyncXMLStream::onShutdown();\n\tXMLWriter::flush();\n\tcerr << \"[TestStream]: peer shutdown connection\" << endl;\n\tif ( shutdown(fd, SHUT_RDWR) != 0 )\n\t{\n\t\tstderror();\n\t}\n\tserver->daemon->removeObject(this);\n\tdelete this;\n}\n\n\/**\n* Обработчик открытия тега\n*\/\nvoid XMPPStream::onStartElement(const std::string &name, const attributtes_t &attributes)\n{\n\tdepth ++;\n\tswitch ( depth )\n\t{\n\tcase 1:\n\t\tonStartStream(name, attributes);\n\t\tbreak;\n\tcase 2: \/\/ начало станзы\n\t\tbuilder->startElement(name, attributes, depth);\n\tbreak;\n\tdefault: \/\/ добавить тег в станзу\n\t\tbuilder->startElement(name, attributes, depth);\n\t}\n}\n\n\/**\n* Обработчик символьных данных\n*\/\nvoid XMPPStream::onCharacterData(const std::string &cdata)\n{\n\tbuilder->characterData(cdata);\n}\n\n\/**\n* Обработчик закрытия тега\n*\/\nvoid XMPPStream::onEndElement(const std::string &name)\n{\n\tswitch (depth)\n\t{\n\tcase 1:\n\t\tonEndStream();\n\t\tbreak;\n\tcase 2: {\n\t\tbuilder->endElement(name);\n\t\tStanza *s = new Stanza(builder->fetchResult());\n\t\tonStanza(s);\n\t\tdelete s; \/\/ Внимание — станза удаляется здесь\n\t\tbreak;\n\t}\n\tdefault:\n\t\tbuilder->endElement(name);\n\t}\n\tdepth --;\n}\n\n\/**\n* Обработчик станз\n*\/\nvoid XMPPStream::onStanza(Stanza *stanza)\n{\n\tcout << \"stanza: \" << stanza->tag()->name() << endl;\n\tif (stanza->tag()->name() == \"iq\") onIqStanza(stanza);\n\telse if (stanza->tag()->name() == \"auth\") onAuthStanza(stanza);\n\telse if (stanza->tag()->name() == \"response\" ) onResponseStanza(stanza);\n\telse if (stanza->tag()->name() == \"message\") onMessageStanza(stanza);\n\telse if (stanza->tag()->name() == \"presence\") onPresenceStanza(stanza);\n\telse ; \/\/ ...\n}\n\n\/**\n* Обработчик авторизации\n*\/\nvoid XMPPStream::onAuthStanza(Stanza *stanza)\n{\n\tstring mechanism = stanza->tag()->getAttribute(\"mechanism\");\n\t\n\tsasl = server->start(\"xmpp\", client_jid.hostname(), mechanism);\n\tonSASLStep(string());\n}\n\n\/**\n* Обработка этапа авторизации SASL\n*\/\nvoid XMPPStream::onSASLStep(const std::string &input)\n{\n\tstring output;\n\tswitch ( server->step(sasl, input, output) )\n\t{\n\tcase SASLServer::ok:\n\t\tclient_jid.setUsername(server->getUsername(sasl));\n\t\tserver->close(sasl);\n\t\tstartElement(\"success\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-sasl\");\n\t\tendElement(\"success\");\n\t\tflush();\n\t\tresetWriter();\n\t\tstate = authorized;\n\t\tdepth = 1; \/\/ после выхода из onAuthStanza\/onStanza() будет стандартный depth--\n\t\tresetParser();\n\t\tbreak;\n\tcase SASLServer::next:\n\t\tstartElement(\"challenge\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-sasl\");\n\t\t\tcharacterData(base64_encode(output));\n\t\tendElement(\"challenge\");\n\t\tflush();\n\t\tbreak;\n\tcase SASLServer::error:\n\t\tserver->close(sasl);\n\t\tstartElement(\"failure\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-sasl\");\n\t\t\taddElement(\"temporary-auth-failure\", \"\");\n\t\tendElement(\"failure\");\n\t\tflush();\n\t\tbreak;\n\t}\n}\n\n\/**\n* Обработчик авторизации: ответ клиента\n*\/\nvoid XMPPStream::onResponseStanza(Stanza *stanza)\n{\n\tonSASLStep(base64_decode(stanza->tag()->getCharacterData()));\n}\n\n\/**\n* Обработчик iq-станзы\n*\/\nvoid XMPPStream::onIqStanza(Stanza *stanza)\n{\n\tif(stanza->tag()->hasChild(\"bind\") && (stanza->type() == \"set\" || stanza->type() == \"get\")) {\n\t\tclient_jid.setResource(stanza->type() == \"set\" ? stanza->tag()->getChild(\"bind\")->getChild(\"resource\")->getCharacterData() : \"foo\");\n\t\tstartElement(\"iq\");\n\t\t\tsetAttribute(\"type\", \"result\");\n\t\t\tsetAttribute(\"id\", stanza->tag()->getAttribute(\"id\"));\n\t\t\tstartElement(\"bind\");\n\t\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-bind\");\n\t\t\t\tstartElement(\"jid\");\n\t\t\t\t\tcharacterData(jid().full());\n\t\t\t\tendElement(\"jid\");\n\t\t\tendElement(\"bind\");\n\t\tendElement(\"iq\");\n\t\tflush();\n\t}\n\tif(stanza->tag()->hasChild(\"session\") && stanza->type() == \"set\") {\n\t\tstartElement(\"iq\");\n\t\t\tsetAttribute(\"id\", stanza->tag()->getAttribute(\"id\"));\n\t\t\tsetAttribute(\"type\", \"result\");\n\t\t\tstartElement(\"session\");\n\t\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-session\");\n\t\t\tendElement(\"session\");\n\t\tendElement(\"iq\");\n\t\tflush();\n\t\tserver->onOnline(this);\n\t}\n\tif(stanza->tag()->hasChild(\"query\") && stanza->type() == \"get\") {\n\t\t\/\/ Входящие запросы информации\n\t\tstd::string query_xmlns = stanza->tag()->getChild(\"query\")->getAttribute(\"xmlns\");\n\t\tif(query_xmlns == \"jabber:iq:version\") {\n\t\t\t\/\/ Отправить версию сервера\n\t\t\t\/\/ send(Stanza::serverVersion(сервер, stanza->from(), stanza->id()));\n\t\t} else if (query_xmlns == \"jabber:iq:roster\") {\n\t\t\tstartElement(\"iq\");\n\t\t\t\tsetAttribute(\"type\", \"result\");\n\t\t\t\tsetAttribute(\"id\", stanza->tag()->getAttribute(\"id\"));\n\t\t\t\tstartElement(\"query\");\n\t\t\t\t\tsetAttribute(\"xmlns\", \"jabber:iq:roster\");\n\t\t\t\t\tXMPPServer::users_t users = server->getUserList();\n\t\t\t\t\tfor(XMPPServer::users_t::iterator pos = users.begin(); pos != users.end(); ++pos)\n\t\t\t\t\t{\n\t\t\t\t\t\tstartElement(\"item\");\n\t\t\t\t\t\t\tsetAttribute(\"jid\", *pos);\n\t\t\t\t\t\t\tsetAttribute(\"name\", *pos);\n\t\t\t\t\t\t\tsetAttribute(\"subscription\", \"both\");\n\t\t\t\t\t\t\taddElement(\"group\", \"Friends\");\n\t\t\t\t\t\tendElement(\"item\");\n\t\t\t\t\t}\n\t\t\t\tendElement(\"query\");\n\t\t\tendElement(\"iq\");\n\t\t\tflush();\n\t\t} else {\n\t\t \/\/ Неизвестный запрос\n\t\t\t\/\/Stanza s = Stanza::badRequest(JID(\"\"), stanza->from(), stanza->id());\n\t\t \/\/sendStanza(&s);\n\t\t}\n\t}\n}\n\nClientPresence XMPPStream::presence() {\n\treturn client_presence;\n}\n\nvoid XMPPStream::onMessageStanza(Stanza *stanza) {\n\tstanza->tag()->insertAttribute(\"from\", jid().full());\n\t\n\tXMPPServer::sessions_t::iterator it;\n\tXMPPServer::reslist_t reslist;\n\tXMPPServer::reslist_t::iterator jt;\n\t\n\tit = server->onliners.find(stanza->to().bare());\n\tif(it != server->onliners.end()) {\n\t\t\/\/ Проверить, есть ли ресурс, если он указан\n\t\tJID to = stanza->to();\n\t\tif(to.resource() != \"\") {\n\t\t\tjt = it->second.find(to.resource());\n\t\t\tif(jt != it->second.end()) {\n\t\t\t\tjt->second->sendStanza(stanza);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\/\/ Не отправили на выбранный ресурс, смотрим дальше…\n\t\t}\n\t\tstd::list sendto_list;\n\t\tstd::list::iterator kt;\n\t\tint max_priority = 0;\n\t\tfor(jt = it->second.begin(); jt != it->second.end(); jt++) {\n\t\t\tif(jt->second->presence().priority == max_priority) {\n\t\t\t\tsendto_list.push_back(jt->second);\n\t\t\t} else if(jt->second->presence().priority > max_priority) {\n\t\t\t\tsendto_list.clear();\n\t\t\t\tsendto_list.push_back(jt->second);\n\t\t\t}\n\t\t}\n\t\tif(sendto_list.empty()) {\n\t\t\treturn;\n\t\t\tcout << \"Offline message for: \" << stanza->to().bare() << endl;\n\t\t}\n\t\tfor(kt = sendto_list.begin() ; kt != sendto_list.end(); kt++) {\n\t\t\t(*kt)->sendStanza(stanza);\n\t\t}\n\t} else {\n\t\tcout << \"Offline message for: \" << stanza->to().bare() << endl;\n\t}\n}\n\nvoid XMPPStream::onPresenceStanza(Stanza *stanza)\n{\n\tclient_presence.priority = atoi(stanza->tag()->getChildValue(\"priority\", \"0\").c_str()); \/\/ TODO\n\tclient_presence.status_text = stanza->tag()->getChildValue(\"status\", \"\");\n\t\n\tfor(XMPPServer::sessions_t::iterator it = server->onliners.begin(); it != server->onliners.end(); it++) {\n\t\tstanza->tag()->insertAttribute(\"to\", it->first);\n\t\tfor(XMPPServer::reslist_t::iterator jt = it->second.begin(); jt != it->second.end(); jt++) {\n\t\t\tjt->second->sendStanza(stanza);\n\t\t}\n\t}\n}\n\n\n\/**\n* Событие: начало потока\n*\/\nvoid XMPPStream::onStartStream(const std::string &name, const attributes_t &attributes)\n{\n\tcout << \"new stream\" << endl;\n\tinitXML();\n\tstartElement(\"stream:stream\");\n\tsetAttribute(\"xmlns\", \"jabber:client\");\n\tsetAttribute(\"xmlns:stream\", \"http:\/\/etherx.jabber.org\/streams\");\n\tsetAttribute(\"id\", \"123456\"); \/\/ Требования к id — непредсказуемость и уникальность\n\tsetAttribute(\"from\", \"localhost\");\n\tsetAttribute(\"version\", \"1.0\");\n\tsetAttribute(\"xml:lang\", \"en\");\n\t\n\tstartElement(\"stream:features\");\n\tif ( state == init )\n\t{\n\t\tclient_jid.setHostname(attributes.find(\"to\")->second);\n\t\tstartElement(\"mechanisms\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-sasl\");\n\t\t\tSASLServer::mechanisms_t list = server->getMechanisms();\n\t\t\tfor(SASLServer::mechanisms_t::const_iterator pos = list.begin(); pos != list.end(); ++pos)\n\t\t\t{\n\t\t\t\taddElement(\"mechanism\", *pos);\n\t\t\t}\n\t\tendElement(\"mechanisms\");\n\t\tstartElement(\"register\");\n\t\t\tsetAttribute(\"xmlns\", \"http:\/\/jabber.org\/features\/iq-register\");\n\t\tendElement(\"register\");\n\t}\n\telse\n\t{\n\t\tstartElement(\"bind\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-bind\");\n\t\tendElement(\"bind\");\n\t\t\/*\n\t\tstartElement(\"session\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-session\");\n\t\tendElement(\"session\");\n\t\t*\/\n\t}\n\tendElement(\"stream:features\");\n\tflush();\n}\n\n\/**\n* Событие: конец потока\n*\/\nvoid XMPPStream::onEndStream()\n{\n\tcerr << \"session closed\" << endl;\n\tendElement(\"stream:stream\");\n}\n\n\/**\n* JID потока\n*\/\nJID XMPPStream::jid()\n{\n\treturn client_jid;\n}\n\nvoid XMPPStream::sendTag(ATXmlTag * tag) {\n\tstartElement(tag->name());\n\tattributes_t attributes = tag->getAttributes();\n\tfor(attributes_t::iterator it = attributes.begin(); it != attributes.end(); it++) {\n\t\tsetAttribute(it->first, it->second);\n\t}\n\tnodes_list_t nodes = tag->getChildNodes();\n\tfor(nodes_list_t::iterator it = nodes.begin(); it != nodes.end(); it++) {\n\t\tif((*it)->type == TTag) {\n\t\t\tsendTag((*it)->tag);\n\t\t} else {\n\t\t\tcharacterData((*it)->cdata);\n\t\t}\n\t}\n\tendElement(tag->name());\n\t\/\/ send(tag->asString()); — так будет куда проще…\n}\n\nvoid XMPPStream::sendStanza(Stanza * stanza) {\n\tsendTag(stanza->tag());\n\tflush();\n}\nТьфу, return строкой выше нужного написал\n#include \n#include \n#include \n#include \n\n\/\/ for debug only\n#include \n#include \n\nusing namespace std;\nusing namespace nanosoft;\n\n\/**\n* Конструктор потока\n*\/\nXMPPStream::XMPPStream(XMPPServer *srv, int sock): AsyncXMLStream(sock), server(srv), XMLWriter(1024), state(init)\n{\n\tdepth = 0;\n\tbuilder = new ATTagBuilder();\n}\n\n\/**\n* Деструктор потока\n*\/\nXMPPStream::~XMPPStream()\n{\n\tdelete builder;\n}\n\n\/**\n* Запись XML\n*\/\nvoid XMPPStream::onWriteXML(const char *data, size_t len)\n{\n\tint r = write(data, len);\n\tif ( r != len ) onError(\"write fault\");\n\tcout << \"written: \\033[22;34m\" << string(data, len) << \"\\033[0m\\n\";\n}\n\n\/**\n* Событие готовности к записи\n*\n* Вызывается, когда в поток готов принять\n* данные для записи без блокировки\n*\/\nvoid XMPPStream::onWrite()\n{\n\tcerr << \"not implemented XMPPStream::onWrite()\" << endl;\n}\n\n\/**\n* Событие закрытие соединения\n*\n* Вызывается если peer закрыл соединение\n*\/\nvoid XMPPStream::onShutdown()\n{\n\tserver->onOffline(this);\n\tAsyncXMLStream::onShutdown();\n\tXMLWriter::flush();\n\tcerr << \"[TestStream]: peer shutdown connection\" << endl;\n\tif ( shutdown(fd, SHUT_RDWR) != 0 )\n\t{\n\t\tstderror();\n\t}\n\tserver->daemon->removeObject(this);\n\tdelete this;\n}\n\n\/**\n* Обработчик открытия тега\n*\/\nvoid XMPPStream::onStartElement(const std::string &name, const attributtes_t &attributes)\n{\n\tdepth ++;\n\tswitch ( depth )\n\t{\n\tcase 1:\n\t\tonStartStream(name, attributes);\n\t\tbreak;\n\tcase 2: \/\/ начало станзы\n\t\tbuilder->startElement(name, attributes, depth);\n\tbreak;\n\tdefault: \/\/ добавить тег в станзу\n\t\tbuilder->startElement(name, attributes, depth);\n\t}\n}\n\n\/**\n* Обработчик символьных данных\n*\/\nvoid XMPPStream::onCharacterData(const std::string &cdata)\n{\n\tbuilder->characterData(cdata);\n}\n\n\/**\n* Обработчик закрытия тега\n*\/\nvoid XMPPStream::onEndElement(const std::string &name)\n{\n\tswitch (depth)\n\t{\n\tcase 1:\n\t\tonEndStream();\n\t\tbreak;\n\tcase 2: {\n\t\tbuilder->endElement(name);\n\t\tStanza *s = new Stanza(builder->fetchResult());\n\t\tonStanza(s);\n\t\tdelete s; \/\/ Внимание — станза удаляется здесь\n\t\tbreak;\n\t}\n\tdefault:\n\t\tbuilder->endElement(name);\n\t}\n\tdepth --;\n}\n\n\/**\n* Обработчик станз\n*\/\nvoid XMPPStream::onStanza(Stanza *stanza)\n{\n\tcout << \"stanza: \" << stanza->tag()->name() << endl;\n\tif (stanza->tag()->name() == \"iq\") onIqStanza(stanza);\n\telse if (stanza->tag()->name() == \"auth\") onAuthStanza(stanza);\n\telse if (stanza->tag()->name() == \"response\" ) onResponseStanza(stanza);\n\telse if (stanza->tag()->name() == \"message\") onMessageStanza(stanza);\n\telse if (stanza->tag()->name() == \"presence\") onPresenceStanza(stanza);\n\telse ; \/\/ ...\n}\n\n\/**\n* Обработчик авторизации\n*\/\nvoid XMPPStream::onAuthStanza(Stanza *stanza)\n{\n\tstring mechanism = stanza->tag()->getAttribute(\"mechanism\");\n\t\n\tsasl = server->start(\"xmpp\", client_jid.hostname(), mechanism);\n\tonSASLStep(string());\n}\n\n\/**\n* Обработка этапа авторизации SASL\n*\/\nvoid XMPPStream::onSASLStep(const std::string &input)\n{\n\tstring output;\n\tswitch ( server->step(sasl, input, output) )\n\t{\n\tcase SASLServer::ok:\n\t\tclient_jid.setUsername(server->getUsername(sasl));\n\t\tserver->close(sasl);\n\t\tstartElement(\"success\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-sasl\");\n\t\tendElement(\"success\");\n\t\tflush();\n\t\tresetWriter();\n\t\tstate = authorized;\n\t\tdepth = 1; \/\/ после выхода из onAuthStanza\/onStanza() будет стандартный depth--\n\t\tresetParser();\n\t\tbreak;\n\tcase SASLServer::next:\n\t\tstartElement(\"challenge\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-sasl\");\n\t\t\tcharacterData(base64_encode(output));\n\t\tendElement(\"challenge\");\n\t\tflush();\n\t\tbreak;\n\tcase SASLServer::error:\n\t\tserver->close(sasl);\n\t\tstartElement(\"failure\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-sasl\");\n\t\t\taddElement(\"temporary-auth-failure\", \"\");\n\t\tendElement(\"failure\");\n\t\tflush();\n\t\tbreak;\n\t}\n}\n\n\/**\n* Обработчик авторизации: ответ клиента\n*\/\nvoid XMPPStream::onResponseStanza(Stanza *stanza)\n{\n\tonSASLStep(base64_decode(stanza->tag()->getCharacterData()));\n}\n\n\/**\n* Обработчик iq-станзы\n*\/\nvoid XMPPStream::onIqStanza(Stanza *stanza)\n{\n\tif(stanza->tag()->hasChild(\"bind\") && (stanza->type() == \"set\" || stanza->type() == \"get\")) {\n\t\tclient_jid.setResource(stanza->type() == \"set\" ? stanza->tag()->getChild(\"bind\")->getChild(\"resource\")->getCharacterData() : \"foo\");\n\t\tstartElement(\"iq\");\n\t\t\tsetAttribute(\"type\", \"result\");\n\t\t\tsetAttribute(\"id\", stanza->tag()->getAttribute(\"id\"));\n\t\t\tstartElement(\"bind\");\n\t\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-bind\");\n\t\t\t\tstartElement(\"jid\");\n\t\t\t\t\tcharacterData(jid().full());\n\t\t\t\tendElement(\"jid\");\n\t\t\tendElement(\"bind\");\n\t\tendElement(\"iq\");\n\t\tflush();\n\t}\n\tif(stanza->tag()->hasChild(\"session\") && stanza->type() == \"set\") {\n\t\tstartElement(\"iq\");\n\t\t\tsetAttribute(\"id\", stanza->tag()->getAttribute(\"id\"));\n\t\t\tsetAttribute(\"type\", \"result\");\n\t\t\tstartElement(\"session\");\n\t\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-session\");\n\t\t\tendElement(\"session\");\n\t\tendElement(\"iq\");\n\t\tflush();\n\t\tserver->onOnline(this);\n\t}\n\tif(stanza->tag()->hasChild(\"query\") && stanza->type() == \"get\") {\n\t\t\/\/ Входящие запросы информации\n\t\tstd::string query_xmlns = stanza->tag()->getChild(\"query\")->getAttribute(\"xmlns\");\n\t\tif(query_xmlns == \"jabber:iq:version\") {\n\t\t\t\/\/ Отправить версию сервера\n\t\t\t\/\/ send(Stanza::serverVersion(сервер, stanza->from(), stanza->id()));\n\t\t} else if (query_xmlns == \"jabber:iq:roster\") {\n\t\t\tstartElement(\"iq\");\n\t\t\t\tsetAttribute(\"type\", \"result\");\n\t\t\t\tsetAttribute(\"id\", stanza->tag()->getAttribute(\"id\"));\n\t\t\t\tstartElement(\"query\");\n\t\t\t\t\tsetAttribute(\"xmlns\", \"jabber:iq:roster\");\n\t\t\t\t\tXMPPServer::users_t users = server->getUserList();\n\t\t\t\t\tfor(XMPPServer::users_t::iterator pos = users.begin(); pos != users.end(); ++pos)\n\t\t\t\t\t{\n\t\t\t\t\t\tstartElement(\"item\");\n\t\t\t\t\t\t\tsetAttribute(\"jid\", *pos);\n\t\t\t\t\t\t\tsetAttribute(\"name\", *pos);\n\t\t\t\t\t\t\tsetAttribute(\"subscription\", \"both\");\n\t\t\t\t\t\t\taddElement(\"group\", \"Friends\");\n\t\t\t\t\t\tendElement(\"item\");\n\t\t\t\t\t}\n\t\t\t\tendElement(\"query\");\n\t\t\tendElement(\"iq\");\n\t\t\tflush();\n\t\t} else {\n\t\t \/\/ Неизвестный запрос\n\t\t\t\/\/Stanza s = Stanza::badRequest(JID(\"\"), stanza->from(), stanza->id());\n\t\t \/\/sendStanza(&s);\n\t\t}\n\t}\n}\n\nClientPresence XMPPStream::presence() {\n\treturn client_presence;\n}\n\nvoid XMPPStream::onMessageStanza(Stanza *stanza) {\n\tstanza->tag()->insertAttribute(\"from\", jid().full());\n\t\n\tXMPPServer::sessions_t::iterator it;\n\tXMPPServer::reslist_t reslist;\n\tXMPPServer::reslist_t::iterator jt;\n\t\n\tit = server->onliners.find(stanza->to().bare());\n\tif(it != server->onliners.end()) {\n\t\t\/\/ Проверить, есть ли ресурс, если он указан\n\t\tJID to = stanza->to();\n\t\tif(to.resource() != \"\") {\n\t\t\tjt = it->second.find(to.resource());\n\t\t\tif(jt != it->second.end()) {\n\t\t\t\tjt->second->sendStanza(stanza);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\/\/ Не отправили на выбранный ресурс, смотрим дальше…\n\t\t}\n\t\tstd::list sendto_list;\n\t\tstd::list::iterator kt;\n\t\tint max_priority = 0;\n\t\tfor(jt = it->second.begin(); jt != it->second.end(); jt++) {\n\t\t\tif(jt->second->presence().priority == max_priority) {\n\t\t\t\tsendto_list.push_back(jt->second);\n\t\t\t} else if(jt->second->presence().priority > max_priority) {\n\t\t\t\tsendto_list.clear();\n\t\t\t\tsendto_list.push_back(jt->second);\n\t\t\t}\n\t\t}\n\t\tif(sendto_list.empty()) {\n\t\t\tcout << \"Offline message for: \" << stanza->to().bare() << endl;\n\t\t\treturn;\n\t\t}\n\t\tfor(kt = sendto_list.begin() ; kt != sendto_list.end(); kt++) {\n\t\t\t(*kt)->sendStanza(stanza);\n\t\t}\n\t} else {\n\t\tcout << \"Offline message for: \" << stanza->to().bare() << endl;\n\t}\n}\n\nvoid XMPPStream::onPresenceStanza(Stanza *stanza)\n{\n\tclient_presence.priority = atoi(stanza->tag()->getChildValue(\"priority\", \"0\").c_str()); \/\/ TODO\n\tclient_presence.status_text = stanza->tag()->getChildValue(\"status\", \"\");\n\t\n\tfor(XMPPServer::sessions_t::iterator it = server->onliners.begin(); it != server->onliners.end(); it++) {\n\t\tstanza->tag()->insertAttribute(\"to\", it->first);\n\t\tfor(XMPPServer::reslist_t::iterator jt = it->second.begin(); jt != it->second.end(); jt++) {\n\t\t\tjt->second->sendStanza(stanza);\n\t\t}\n\t}\n}\n\n\n\/**\n* Событие: начало потока\n*\/\nvoid XMPPStream::onStartStream(const std::string &name, const attributes_t &attributes)\n{\n\tcout << \"new stream\" << endl;\n\tinitXML();\n\tstartElement(\"stream:stream\");\n\tsetAttribute(\"xmlns\", \"jabber:client\");\n\tsetAttribute(\"xmlns:stream\", \"http:\/\/etherx.jabber.org\/streams\");\n\tsetAttribute(\"id\", \"123456\"); \/\/ Требования к id — непредсказуемость и уникальность\n\tsetAttribute(\"from\", \"localhost\");\n\tsetAttribute(\"version\", \"1.0\");\n\tsetAttribute(\"xml:lang\", \"en\");\n\t\n\tstartElement(\"stream:features\");\n\tif ( state == init )\n\t{\n\t\tclient_jid.setHostname(attributes.find(\"to\")->second);\n\t\tstartElement(\"mechanisms\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-sasl\");\n\t\t\tSASLServer::mechanisms_t list = server->getMechanisms();\n\t\t\tfor(SASLServer::mechanisms_t::const_iterator pos = list.begin(); pos != list.end(); ++pos)\n\t\t\t{\n\t\t\t\taddElement(\"mechanism\", *pos);\n\t\t\t}\n\t\tendElement(\"mechanisms\");\n\t\tstartElement(\"register\");\n\t\t\tsetAttribute(\"xmlns\", \"http:\/\/jabber.org\/features\/iq-register\");\n\t\tendElement(\"register\");\n\t}\n\telse\n\t{\n\t\tstartElement(\"bind\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-bind\");\n\t\tendElement(\"bind\");\n\t\t\/*\n\t\tstartElement(\"session\");\n\t\t\tsetAttribute(\"xmlns\", \"urn:ietf:params:xml:ns:xmpp-session\");\n\t\tendElement(\"session\");\n\t\t*\/\n\t}\n\tendElement(\"stream:features\");\n\tflush();\n}\n\n\/**\n* Событие: конец потока\n*\/\nvoid XMPPStream::onEndStream()\n{\n\tcerr << \"session closed\" << endl;\n\tendElement(\"stream:stream\");\n}\n\n\/**\n* JID потока\n*\/\nJID XMPPStream::jid()\n{\n\treturn client_jid;\n}\n\nvoid XMPPStream::sendTag(ATXmlTag * tag) {\n\tstartElement(tag->name());\n\tattributes_t attributes = tag->getAttributes();\n\tfor(attributes_t::iterator it = attributes.begin(); it != attributes.end(); it++) {\n\t\tsetAttribute(it->first, it->second);\n\t}\n\tnodes_list_t nodes = tag->getChildNodes();\n\tfor(nodes_list_t::iterator it = nodes.begin(); it != nodes.end(); it++) {\n\t\tif((*it)->type == TTag) {\n\t\t\tsendTag((*it)->tag);\n\t\t} else {\n\t\t\tcharacterData((*it)->cdata);\n\t\t}\n\t}\n\tendElement(tag->name());\n\t\/\/ send(tag->asString()); — так будет куда проще…\n}\n\nvoid XMPPStream::sendStanza(Stanza * stanza) {\n\tsendTag(stanza->tag());\n\tflush();\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/\n\/\/ MIT License\n\/\/\n\/\/ Copyright (c) 2017 Stellacore Corporation.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal in the Software without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject\n\/\/ to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n\/\/ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n\/\/ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n\/\/ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN\n\/\/ AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\n\/\/ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\/\/\n\n\/*! \\file\n\\brief This file contains unit test for sys::time\n*\/\n\n\n#include \"libsys\/time.h\"\n\n#include \"libio\/stream.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace\n{\n\n\/\/! Check for basics\nstd::string\nsys_time_test0\n\t()\n{\n\tstd::ostringstream oss;\n\n\tdouble const absT0(sys::time::now());\n\tdouble const relT0(sys::time::relativeNow());\n\n\tlong const microSleep(123456l);\n\tstd::this_thread::sleep_for(std::chrono::microseconds(microSleep));\n\n\tdouble const absT1(sys::time::now());\n\tdouble const relT1(sys::time::relativeNow());\n\n\tdouble const absDelta(absT1 - absT0);\n\tdouble const relDelta(relT1 - relT0);\n\n\t\/\/ check within a few micro seconds\n\tdouble const microDif(std::abs(1.e6*(relDelta - absDelta)));\n\tstatic double const microTol(4.); \/\/ allow for run time of code\n\tif (! (microDif < microTol))\n\t{\n\t\toss << \"Failure of relative time test\" << std::endl;\n\t\toss << \"absT0: \" << absT0 << std::endl;\n\t\toss << \"absT1: \" << absT1 << std::endl;\n\t\toss << \"absDelta: \" << absDelta << std::endl;\n\t\toss << \"relT0: \" << relT0 << std::endl;\n\t\toss << \"relT1: \" << relT1 << std::endl;\n\t\toss << \"relDelta: \" << relDelta << std::endl;\n\t\toss << \"microDif: \" << microDif << std::endl;\n\t\toss << \"microTol: \" << microTol << std::endl;\n\t}\n\n\treturn oss.str();\n}\n\n\n}\n\n\/\/! Unit test for sys::time\nint\nmain\n\t( int const \/*argc*\/\n\t, char const * const * const \/*argv*\/\n\t)\n{\n\tstd::ostringstream oss;\n\n\t\/\/ run tests\n\toss << sys_time_test0();\n\n\t\/\/ check\/report results\n\tstd::string const errMessages(oss.str());\n\tif (! errMessages.empty())\n\t{\n\t\tio::err() << errMessages << std::endl;\n\t\treturn 1;\n\t}\n\treturn 0;\n}\ntestsys\/utime.cpp cleanup test cases a bit - still very heuristic\/\/\n\/\/\n\/\/ MIT License\n\/\/\n\/\/ Copyright (c) 2017 Stellacore Corporation.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal in the Software without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject\n\/\/ to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n\/\/ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n\/\/ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n\/\/ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN\n\/\/ AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\n\/\/ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\/\/\n\n\/*! \\file\n\\brief This file contains unit test for sys::time\n*\/\n\n\n#include \"libsys\/time.h\"\n\n#include \"libio\/stream.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace\n{\n\n\/\/! Check for basics\nstd::string\nsys_time_test0\n\t()\n{\n\tstd::ostringstream oss;\n\n\t\/\/ expect executation of squential statement exectuation to *probably* be\n\t\/\/ simultaneous withint at least this time interval\n\tconstexpr double tolSync{ .001 };\n\n\t\/\/ get two times that should be *approximately* \"simultaneous-ish\n\tdouble const absT0{ sys::time::now() }; \/\/ since 1970.01.01-00:00:00.0\n\tdouble const relT0{ sys::time::relativeNow() }; \/\/ should be ~= 0\n\n\t\/\/ assume chorono::steady_clock should have been running at least this long\n\tconstexpr double sinceStart{ 1. };\n\tif (! (sinceStart < absT0))\n\t{\n\t\toss << \"Failure of absolute time to return value larger than 1 sec\"\n\t\t\t<< std::endl;\n\t\toss << \"absT0: \" << absT0 << std::endl;\n\t}\n\tif (relT0 < 0.)\n\t{\n\t\toss << \"Failure of positive relative time test\" << std::endl;\n\t\toss << \"relT0: \" << relT0 << std::endl;\n\t}\n\tif (! (relT0 < tolSync)) \/\/ relative should initilize near zero\n\t{\n\t\toss << \"Faiure of first relative time test\" << std::endl;\n\t\toss << \"relT0: \" << relT0 << std::endl;\n\t}\n\n\t\/\/ introduce significant delay (relative to tolSync)\n\tconstexpr double delay{ .125 };\n\tconstexpr long microSleep{ static_cast(1.e6 * delay) };\n\tstd::this_thread::sleep_for(std::chrono::microseconds(microSleep));\n\n\t\/\/ get another approximately \"simultaneous\"-ish times\n\tdouble const absT1{ sys::time::now() };\n\tdouble const relT1{ sys::time::relativeNow() }; \/\/~= (absT1-absT0)\n\n\tdouble const absDelta{ absT1 - absT0 };\n\tdouble const & relDelta = relT1; \/\/ since relT0 ~= 0\n\n\tdouble const dif{ std::abs(relDelta - absDelta) };\n\tstatic double const tol(10.*tolSync); \/\/ allow for run time of code\n\tif (! (dif < tol))\n\t{\n\t\toss << \"Failure of relative time test\" << std::endl;\n\t\toss << \" absT0: \" << absT0 << std::endl;\n\t\toss << \" absT1: \" << absT1 << std::endl;\n\t\toss << \"absDelta: \" << absDelta << std::endl;\n\t\toss << \" relT0: \" << relT0 << std::endl;\n\t\toss << \" relT1: \" << relT1 << std::endl;\n\t\toss << \"relDelta: \" << relDelta << std::endl;\n\t\toss << \" dif: \" << dif << std::endl;\n\t\toss << \" tol: \" << tol << std::endl;\n\t}\n\n\treturn oss.str();\n}\n\n\n}\n\n\/\/! Unit test for sys::time\nint\nmain\n\t( int const \/*argc*\/\n\t, char const * const * const \/*argv*\/\n\t)\n{\n\tstd::ostringstream oss;\n\n\t\/\/ run tests\n\toss << sys_time_test0();\n\n\t\/\/ check\/report results\n\tstd::string const errMessages(oss.str());\n\tif (! errMessages.empty())\n\t{\n\t\tio::err() << errMessages << std::endl;\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n<|endoftext|>"} {"text":"#include \"pqVelodyneManager.h\"\n#include \"vvLoadDataReaction.h\"\n#include \"vvCalibrationDialog.h\"\n#include \"vvPythonQtDecorators.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/-----------------------------------------------------------------------------\nclass pqVelodyneManager::pqInternal\n{\npublic:\n\n pqInternal()\n {\n\n }\n\n QAction* OpenFile;\n QAction* Close;\n QAction* OpenSensor;\n QAction* ChooseCalibrationFile;\n QAction* ResetView;\n QAction* Play;\n QAction* SeekForward;\n QAction* SeekBackward;\n QAction* GotoStart;\n QAction* GotoEnd;\n QAction* Record;\n QAction* MeasurementGrid;\n QAction* SaveCSV;\n};\n\n\/\/-----------------------------------------------------------------------------\nQPointer pqVelodyneManagerInstance = NULL;\n\n\/\/-----------------------------------------------------------------------------\npqVelodyneManager *pqVelodyneManager::instance()\n{\n if (!pqVelodyneManagerInstance)\n {\n pqVelodyneManagerInstance = new pqVelodyneManager(pqApplicationCore::instance());\n }\n\n return pqVelodyneManagerInstance;\n}\n\n\/\/-----------------------------------------------------------------------------\npqVelodyneManager::pqVelodyneManager(QObject *p) : QObject(p)\n{\n this->Internal = new pqInternal;\n}\n\n\/\/-----------------------------------------------------------------------------\npqVelodyneManager::~pqVelodyneManager()\n{\n delete this->Internal;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::pythonStartup()\n{\n QStringList pythonDirs;\n pythonDirs << QCoreApplication::applicationDirPath() + \"\/..\/Python\" \/\/ MacOSX application bundle\n << QCoreApplication::applicationDirPath() + \"\/..\/..\/..\/..\/lib\/site-packages\" \/\/ MacOSX application bundle in build directory\n << QCoreApplication::applicationDirPath() + \"\/..\/lib\/site-packages\" \/\/ Windows NMake build directory\n << QCoreApplication::applicationDirPath() + \"\/site-packages\"; \/\/ Windows install tree\n\n foreach (const QString& dirname, pythonDirs)\n {\n if (QDir(dirname).exists())\n {\n vtkPythonInterpreter::PrependPythonPath(dirname.toAscii().data());\n break;\n }\n }\n\n vtkPythonInterpreter::RunSimpleString(\"import PythonQt\");\n PythonQt::self()->addDecorators(new vvPythonQtDecorators());\n vtkPythonInterpreter::RunSimpleString(\"import veloview\");\n\n this->runPython(QString(\n \"import PythonQt\\n\"\n \"QtGui = PythonQt.QtGui\\n\"\n \"QtCore = PythonQt.QtCore\\n\"\n \"import veloview.applogic as vv\\n\"\n \"vv.start()\\n\"));\n\n this->onMeasurementGrid();\n\n bool showDialogAtStartup = false;\n if (showDialogAtStartup)\n {\n pqPythonManager* manager = pqPVApplicationCore::instance()->pythonManager();\n pqPythonDialog* dialog = manager->pythonShellDialog();\n dialog->show();\n dialog->raise();\n dialog->activateWindow();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::runPython(const QString& statements)\n{\n \/\/printf(\"runPython(\\\"%s\\\")\\n\", qPrintable(statements));\n pqPythonManager* manager = pqPVApplicationCore::instance()->pythonManager();\n pqPythonDialog* dialog = manager->pythonShellDialog();\n dialog->runString(statements);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::saveFramesToPCAP(vtkSMSourceProxy* proxy, int startFrame, int endFrame, const QString& filename)\n{\n if (!proxy)\n {\n return;\n }\n\n vtkVelodyneHDLReader* reader = vtkVelodyneHDLReader::SafeDownCast(proxy->GetClientSideObject());\n if (!reader)\n {\n return;\n }\n\n reader->Open();\n reader->DumpFrames(startFrame, endFrame, filename.toAscii().data());\n reader->Close();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::setup(QAction* openFile, QAction* close, QAction* openSensor,\n QAction* chooseCalibrationFile, QAction* resetView, QAction* play, QAction* seekForward, QAction* seekBackward, QAction* gotoStart, QAction* gotoEnd,\n QAction* record, QAction* measurementGrid, QAction* saveScreenshot, QAction* saveCSV)\n{\n this->Internal->OpenFile = openFile;\n this->Internal->Close = close;\n this->Internal->OpenSensor = openSensor;\n this->Internal->ChooseCalibrationFile = chooseCalibrationFile;\n this->Internal->ResetView = resetView;\n this->Internal->Play = play;\n this->Internal->SeekForward = seekForward;\n this->Internal->SeekBackward = seekBackward;\n this->Internal->GotoStart = gotoStart;\n this->Internal->GotoEnd = gotoEnd;\n this->Internal->Record = record;\n this->Internal->MeasurementGrid = measurementGrid;\n this->Internal->SaveCSV = saveCSV;\n\n pqSettings* settings = pqApplicationCore::instance()->settings();\n bool gridVisible = settings->value(\"VelodyneHDLPlugin\/MeasurementGrid\/Visibility\", true).toBool();\n measurementGrid->setChecked(gridVisible);\n\n this->connect(openSensor, SIGNAL(triggered()), SLOT(onOpenSensor()));\n this->connect(chooseCalibrationFile, SIGNAL(triggered()), SLOT(onChooseCalibrationFile()));\n\n this->connect(measurementGrid, SIGNAL(triggered()), SLOT(onMeasurementGrid()));\n\n new vvLoadDataReaction(openFile);\n\n QTimer::singleShot(0, this, SLOT(pythonStartup()));\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::openData(const QString& filename)\n{\n if (QFileInfo(filename).suffix() == \"pcap\")\n {\n vvCalibrationDialog dialog;\n int accepted = dialog.exec();\n\n if (!accepted)\n {\n return;\n }\n\n QString calibrationFile = dialog.selectedCalibrationFile();\n\n this->runPython(QString(\"vv.openPCAP('%1', '%2')\\n\").arg(filename).arg(calibrationFile));\n }\n else\n {\n this->runPython(QString(\"vv.openData('%1')\\n\").arg(filename));\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::onMeasurementGrid()\n{\n bool gridVisible = this->Internal->MeasurementGrid->isChecked();\n pqSettings* settings = pqApplicationCore::instance()->settings();\n settings->setValue(\"VelodyneHDLPlugin\/MeasurementGrid\/Visibility\", gridVisible);\n\n if (gridVisible)\n {\n this->runPython(\"vv.showMeasurementGrid()\\n\");\n }\n else\n {\n this->runPython(\"vv.hideMeasurementGrid()\\n\");\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::onOpenSensor()\n{\n vvCalibrationDialog dialog;\n int accepted = dialog.exec();\n\n if (!accepted)\n {\n return;\n }\n\n QString calibrationFile = dialog.selectedCalibrationFile();\n\n this->runPython(QString(\"vv.openSensor('%1')\\n\").arg(calibrationFile));\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::onChooseCalibrationFile()\n{\n vvCalibrationDialog dialog;\n int accepted = dialog.exec();\n\n if (!accepted)\n {\n return;\n }\n\n QString calibrationFile = dialog.selectedCalibrationFile();\n\n this->runPython(QString(\"vv.setCalibrationFile('%1')\\n\").arg(calibrationFile));\n}\n\n\/\/-----------------------------------------------------------------------------\npqServer *pqVelodyneManager::getActiveServer()\n{\n pqApplicationCore *app = pqApplicationCore::instance();\n pqServerManagerModel *smModel = app->getServerManagerModel();\n pqServer *server = smModel->getItemAtIndex(0);\n return server;\n}\n\n\/\/-----------------------------------------------------------------------------\nQWidget *pqVelodyneManager::getMainWindow()\n{\n foreach(QWidget *topWidget, QApplication::topLevelWidgets())\n {\n if (qobject_cast(topWidget))\n {\n return topWidget;\n }\n }\n return NULL;\n}\n\n\/\/-----------------------------------------------------------------------------\npqView *pqVelodyneManager::findView(pqPipelineSource *source, int port, const QString &viewType)\n{\n \/\/ Step 1, try to find a view in which the source is already shown.\n if (source)\n {\n foreach (pqView *view, source->getViews())\n {\n pqDataRepresentation *repr = source->getRepresentation(port, view);\n if (repr && repr->isVisible()) return view;\n }\n }\n\n \/\/ Step 2, check to see if the active view is the right type.\n pqView *view = pqActiveView::instance().current();\n if (view->getViewType() == viewType) return view;\n\n \/\/ Step 3, check all the views and see if one is the right type and not\n \/\/ showing anything.\n pqApplicationCore *core = pqApplicationCore::instance();\n pqServerManagerModel *smModel = core->getServerManagerModel();\n foreach (view, smModel->findItems())\n {\n if ( view && (view->getViewType() == viewType)\n && (view->getNumberOfVisibleRepresentations() < 1) )\n {\n return view;\n }\n }\n\n \/\/ Give up. A new view needs to be created.\n return NULL;\n}\n\n\/\/-----------------------------------------------------------------------------\npqView* pqVelodyneManager::getRenderView()\n{\n return findView(0, 0, pqRenderView::renderViewType());\n}\nFix python path initialization for ParaView 4.0#include \"pqVelodyneManager.h\"\n#include \"vvLoadDataReaction.h\"\n#include \"vvCalibrationDialog.h\"\n#include \"vvPythonQtDecorators.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/-----------------------------------------------------------------------------\nclass pqVelodyneManager::pqInternal\n{\npublic:\n\n pqInternal()\n {\n\n }\n\n QAction* OpenFile;\n QAction* Close;\n QAction* OpenSensor;\n QAction* ChooseCalibrationFile;\n QAction* ResetView;\n QAction* Play;\n QAction* SeekForward;\n QAction* SeekBackward;\n QAction* GotoStart;\n QAction* GotoEnd;\n QAction* Record;\n QAction* MeasurementGrid;\n QAction* SaveCSV;\n};\n\n\/\/-----------------------------------------------------------------------------\nQPointer pqVelodyneManagerInstance = NULL;\n\n\/\/-----------------------------------------------------------------------------\npqVelodyneManager *pqVelodyneManager::instance()\n{\n if (!pqVelodyneManagerInstance)\n {\n pqVelodyneManagerInstance = new pqVelodyneManager(pqApplicationCore::instance());\n }\n\n return pqVelodyneManagerInstance;\n}\n\n\/\/-----------------------------------------------------------------------------\npqVelodyneManager::pqVelodyneManager(QObject *p) : QObject(p)\n{\n this->Internal = new pqInternal;\n}\n\n\/\/-----------------------------------------------------------------------------\npqVelodyneManager::~pqVelodyneManager()\n{\n delete this->Internal;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::pythonStartup()\n{\n QStringList pythonDirs;\n pythonDirs << QCoreApplication::applicationDirPath() + \"\/..\/Python\" \/\/ MacOSX application bundle\n << QCoreApplication::applicationDirPath() + \"\/..\/..\/..\/..\/lib\/site-packages\" \/\/ MacOSX application bundle in build directory\n << QCoreApplication::applicationDirPath() + \"\/site-packages\" \/\/ Windows NMake build directory and install tree\n << QCoreApplication::applicationDirPath() + \"\/..\/lib\/paraview-4.0\/site-packages\"; \/\/ Windows install tree\n\n foreach (const QString& dirname, pythonDirs)\n {\n if (QDir(dirname).exists())\n {\n vtkPythonInterpreter::PrependPythonPath(dirname.toAscii().data());\n }\n }\n\n vtkPythonInterpreter::RunSimpleString(\"import PythonQt\");\n PythonQt::self()->addDecorators(new vvPythonQtDecorators());\n vtkPythonInterpreter::RunSimpleString(\"import veloview\");\n\n this->runPython(QString(\n \"import PythonQt\\n\"\n \"QtGui = PythonQt.QtGui\\n\"\n \"QtCore = PythonQt.QtCore\\n\"\n \"import veloview.applogic as vv\\n\"\n \"vv.start()\\n\"));\n\n this->onMeasurementGrid();\n\n bool showDialogAtStartup = false;\n if (showDialogAtStartup)\n {\n pqPythonManager* manager = pqPVApplicationCore::instance()->pythonManager();\n pqPythonDialog* dialog = manager->pythonShellDialog();\n dialog->show();\n dialog->raise();\n dialog->activateWindow();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::runPython(const QString& statements)\n{\n \/\/printf(\"runPython(\\\"%s\\\")\\n\", qPrintable(statements));\n pqPythonManager* manager = pqPVApplicationCore::instance()->pythonManager();\n pqPythonDialog* dialog = manager->pythonShellDialog();\n dialog->runString(statements);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::saveFramesToPCAP(vtkSMSourceProxy* proxy, int startFrame, int endFrame, const QString& filename)\n{\n if (!proxy)\n {\n return;\n }\n\n vtkVelodyneHDLReader* reader = vtkVelodyneHDLReader::SafeDownCast(proxy->GetClientSideObject());\n if (!reader)\n {\n return;\n }\n\n reader->Open();\n reader->DumpFrames(startFrame, endFrame, filename.toAscii().data());\n reader->Close();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::setup(QAction* openFile, QAction* close, QAction* openSensor,\n QAction* chooseCalibrationFile, QAction* resetView, QAction* play, QAction* seekForward, QAction* seekBackward, QAction* gotoStart, QAction* gotoEnd,\n QAction* record, QAction* measurementGrid, QAction* saveScreenshot, QAction* saveCSV)\n{\n this->Internal->OpenFile = openFile;\n this->Internal->Close = close;\n this->Internal->OpenSensor = openSensor;\n this->Internal->ChooseCalibrationFile = chooseCalibrationFile;\n this->Internal->ResetView = resetView;\n this->Internal->Play = play;\n this->Internal->SeekForward = seekForward;\n this->Internal->SeekBackward = seekBackward;\n this->Internal->GotoStart = gotoStart;\n this->Internal->GotoEnd = gotoEnd;\n this->Internal->Record = record;\n this->Internal->MeasurementGrid = measurementGrid;\n this->Internal->SaveCSV = saveCSV;\n\n pqSettings* settings = pqApplicationCore::instance()->settings();\n bool gridVisible = settings->value(\"VelodyneHDLPlugin\/MeasurementGrid\/Visibility\", true).toBool();\n measurementGrid->setChecked(gridVisible);\n\n this->connect(openSensor, SIGNAL(triggered()), SLOT(onOpenSensor()));\n this->connect(chooseCalibrationFile, SIGNAL(triggered()), SLOT(onChooseCalibrationFile()));\n\n this->connect(measurementGrid, SIGNAL(triggered()), SLOT(onMeasurementGrid()));\n\n new vvLoadDataReaction(openFile);\n\n QTimer::singleShot(0, this, SLOT(pythonStartup()));\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::openData(const QString& filename)\n{\n if (QFileInfo(filename).suffix() == \"pcap\")\n {\n vvCalibrationDialog dialog;\n int accepted = dialog.exec();\n\n if (!accepted)\n {\n return;\n }\n\n QString calibrationFile = dialog.selectedCalibrationFile();\n\n this->runPython(QString(\"vv.openPCAP('%1', '%2')\\n\").arg(filename).arg(calibrationFile));\n }\n else\n {\n this->runPython(QString(\"vv.openData('%1')\\n\").arg(filename));\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::onMeasurementGrid()\n{\n bool gridVisible = this->Internal->MeasurementGrid->isChecked();\n pqSettings* settings = pqApplicationCore::instance()->settings();\n settings->setValue(\"VelodyneHDLPlugin\/MeasurementGrid\/Visibility\", gridVisible);\n\n if (gridVisible)\n {\n this->runPython(\"vv.showMeasurementGrid()\\n\");\n }\n else\n {\n this->runPython(\"vv.hideMeasurementGrid()\\n\");\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::onOpenSensor()\n{\n vvCalibrationDialog dialog;\n int accepted = dialog.exec();\n\n if (!accepted)\n {\n return;\n }\n\n QString calibrationFile = dialog.selectedCalibrationFile();\n\n this->runPython(QString(\"vv.openSensor('%1')\\n\").arg(calibrationFile));\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid pqVelodyneManager::onChooseCalibrationFile()\n{\n vvCalibrationDialog dialog;\n int accepted = dialog.exec();\n\n if (!accepted)\n {\n return;\n }\n\n QString calibrationFile = dialog.selectedCalibrationFile();\n\n this->runPython(QString(\"vv.setCalibrationFile('%1')\\n\").arg(calibrationFile));\n}\n\n\/\/-----------------------------------------------------------------------------\npqServer *pqVelodyneManager::getActiveServer()\n{\n pqApplicationCore *app = pqApplicationCore::instance();\n pqServerManagerModel *smModel = app->getServerManagerModel();\n pqServer *server = smModel->getItemAtIndex(0);\n return server;\n}\n\n\/\/-----------------------------------------------------------------------------\nQWidget *pqVelodyneManager::getMainWindow()\n{\n foreach(QWidget *topWidget, QApplication::topLevelWidgets())\n {\n if (qobject_cast(topWidget))\n {\n return topWidget;\n }\n }\n return NULL;\n}\n\n\/\/-----------------------------------------------------------------------------\npqView *pqVelodyneManager::findView(pqPipelineSource *source, int port, const QString &viewType)\n{\n \/\/ Step 1, try to find a view in which the source is already shown.\n if (source)\n {\n foreach (pqView *view, source->getViews())\n {\n pqDataRepresentation *repr = source->getRepresentation(port, view);\n if (repr && repr->isVisible()) return view;\n }\n }\n\n \/\/ Step 2, check to see if the active view is the right type.\n pqView *view = pqActiveView::instance().current();\n if (view->getViewType() == viewType) return view;\n\n \/\/ Step 3, check all the views and see if one is the right type and not\n \/\/ showing anything.\n pqApplicationCore *core = pqApplicationCore::instance();\n pqServerManagerModel *smModel = core->getServerManagerModel();\n foreach (view, smModel->findItems())\n {\n if ( view && (view->getViewType() == viewType)\n && (view->getNumberOfVisibleRepresentations() < 1) )\n {\n return view;\n }\n }\n\n \/\/ Give up. A new view needs to be created.\n return NULL;\n}\n\n\/\/-----------------------------------------------------------------------------\npqView* pqVelodyneManager::getRenderView()\n{\n return findView(0, 0, pqRenderView::renderViewType());\n}\n<|endoftext|>"} {"text":"fix hang<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"..\/newbrt\/brttypes.h\"\n#include \n\nDbEnv::DbEnv (u_int32_t flags)\n : do_no_exceptions((flags&DB_CXX_NO_EXCEPTIONS)!=0),\n errcall(NULL)\n{\n int ret = db_env_create(&the_env, flags & ~DB_CXX_NO_EXCEPTIONS);\n assert(ret==0); \/\/ should do an error.\n the_env->api1_internal = this;\n}\n\nDbEnv::DbEnv(DB_ENV *env, u_int32_t flags)\n : do_no_exceptions((flags&DB_CXX_NO_EXCEPTIONS)!=0), _error_stream(0)\n{\n the_env = env;\n if (env == 0) {\n\tDB_ENV *new_env;\n\tint ret = db_env_create(&new_env, flags & ~DB_CXX_NO_EXCEPTIONS);\n\tassert(ret==0); \/\/ should do an error.\n\tthe_env = new_env;\n }\n the_env->api1_internal = this;\n}\n\n\/\/ If still open, close it. In most cases, the caller should call close explicitly so that they can catch the exceptions.\nDbEnv::~DbEnv(void)\n{\n if (the_env!=NULL) {\n\t(void)the_env->close(the_env, 0);\n\tthe_env = 0;\n }\n}\n\nint DbEnv::close(u_int32_t flags) {\n int ret = EINVAL;\n if (the_env)\n ret = the_env->close(the_env, flags);\n the_env = 0; \/* get rid of the env ref, so we don't touch it (even if we failed, or when the destructor is called) *\/\n return maybe_throw_error(ret);\n}\n\nint DbEnv::open(const char *home, u_int32_t flags, int mode) {\n int ret = the_env->open(the_env, home, flags, mode);\n return maybe_throw_error(ret);\n}\n\nint DbEnv::set_cachesize(u_int32_t gbytes, u_int32_t bytes, int ncache) {\n int ret = the_env->set_cachesize(the_env, gbytes, bytes, ncache);\n return maybe_throw_error(ret);\n}\n\nint DbEnv::set_redzone(u_int32_t percent) {\n int ret = the_env->set_redzone(the_env, percent);\n return maybe_throw_error(ret);\n}\n\nint DbEnv::set_flags(u_int32_t flags, int onoff) {\n int ret = the_env->set_flags(the_env, flags, onoff);\n return maybe_throw_error(ret);\n}\n\n#if DB_VERSION_MAJOR<4 || (DB_VERSION_MAJOR==4 && DB_VERSION_MINOR<=4)\nint DbEnv::set_lk_max(u_int32_t flags) {\n int ret = the_env->set_lk_max(the_env, flags);\n return maybe_throw_error(ret);\n}\n#endif\n\nint DbEnv::txn_begin(DbTxn *parenttxn, DbTxn **txnp, u_int32_t flags) {\n DB_TXN *txn;\n int ret = the_env->txn_begin(the_env, parenttxn->get_DB_TXN(), &txn, flags);\n if (ret==0) {\n\t*txnp = new DbTxn(txn);\n }\n return maybe_throw_error(ret);\n}\n\nint DbEnv::set_default_bt_compare(bt_compare_fcn_type bt_compare_fcn) {\n int ret = the_env->set_default_bt_compare(the_env, bt_compare_fcn);\n return maybe_throw_error(ret);\n}\n\nint DbEnv::set_data_dir(const char *dir) {\n int ret = the_env->set_data_dir(the_env, dir);\n return maybe_throw_error(ret);\n}\n\nvoid DbEnv::set_errpfx(const char *errpfx) {\n the_env->set_errpfx(the_env, errpfx);\n}\n\nint DbEnv::maybe_throw_error(int err, DbEnv *env, int no_exceptions) throw (DbException) {\n if (err==0 || err==DB_NOTFOUND || err==DB_KEYEXIST) return err;\n if (no_exceptions) return err;\n if (err==DB_LOCK_DEADLOCK) {\n\tDbDeadlockException e(env);\n\tthrow e;\n } else {\n\tDbException e(err);\n\te.set_env(env);\n\tthrow e;\n }\n}\n\nint DbEnv::maybe_throw_error(int err) throw (DbException) {\n return maybe_throw_error(err, this, do_no_exceptions);\n}\n\nextern \"C\" {\nvoid toku_ydb_error_all_cases(const DB_ENV * env, \n int error, \n BOOL include_stderrstring, \n BOOL use_stderr_if_nothing_else, \n const char *fmt, va_list ap);\n}\n\nvoid DbEnv::err(int error, const char *fmt, ...) {\n va_list ap;\n va_start(ap, fmt);\n toku_ydb_error_all_cases(the_env, error, TRUE, TRUE, fmt, ap);\n va_end(ap);\n}\n\nvoid DbEnv::set_errfile(FILE *errfile) {\n the_env->set_errfile(the_env, errfile);\n}\n\nint DbEnv::get_flags(u_int32_t *flagsp) {\n int ret = the_env->get_flags(the_env, flagsp);\n return maybe_throw_error(ret);\n}\n\nextern \"C\" void toku_db_env_errcall_c(const DB_ENV *dbenv_c, const char *errpfx, const char *msg) {\n DbEnv *dbenv = (DbEnv *) dbenv_c->api1_internal;\n dbenv->errcall(dbenv, errpfx, msg);\n}\n\nvoid DbEnv::set_errcall(void (*db_errcall_fcn)(const DbEnv *, const char *, const char *)) {\n errcall = db_errcall_fcn;\n the_env->set_errcall(the_env, toku_db_env_errcall_c);\n}\n\nextern \"C\" void toku_db_env_error_stream_c(const DB_ENV *dbenv_c, const char *errpfx, const char *msg) {\n DbEnv *dbenv = (DbEnv *) dbenv_c->api1_internal;\n if (dbenv->_error_stream) {\n if (errpfx) *(dbenv->_error_stream) << errpfx;\n if (msg) *(dbenv->_error_stream) << \":\" << msg << \"\\n\";\n }\n}\n\nvoid DbEnv::set_error_stream(std::ostream *new_error_stream) {\n _error_stream = new_error_stream;\n the_env->set_errcall(the_env, toku_db_env_error_stream_c);\n}\n\nint DbEnv::set_lk_max_locks(u_int32_t max_locks) {\n int ret = the_env->set_lk_max_locks(the_env, max_locks);\n return maybe_throw_error(ret);\n}\n\nint DbEnv::get_lk_max_locks(u_int32_t *max_locks) {\n int ret = the_env->get_lk_max_locks(the_env, max_locks);\n return maybe_throw_error(ret);\n}\n\nclose[t:3880] Fix the cxx compile. Refs #3880.#include \n#include \n#include \n#include \"..\/newbrt\/brttypes.h\"\n#include \n\nDbEnv::DbEnv (u_int32_t flags)\n : do_no_exceptions((flags&DB_CXX_NO_EXCEPTIONS)!=0),\n errcall(NULL)\n{\n int ret = db_env_create(&the_env, flags & ~DB_CXX_NO_EXCEPTIONS);\n assert(ret==0); \/\/ should do an error.\n the_env->api1_internal = this;\n}\n\nDbEnv::DbEnv(DB_ENV *env, u_int32_t flags)\n : do_no_exceptions((flags&DB_CXX_NO_EXCEPTIONS)!=0), _error_stream(0)\n{\n the_env = env;\n if (env == 0) {\n\tDB_ENV *new_env;\n\tint ret = db_env_create(&new_env, flags & ~DB_CXX_NO_EXCEPTIONS);\n\tassert(ret==0); \/\/ should do an error.\n\tthe_env = new_env;\n }\n the_env->api1_internal = this;\n}\n\n\/\/ If still open, close it. In most cases, the caller should call close explicitly so that they can catch the exceptions.\nDbEnv::~DbEnv(void)\n{\n if (the_env!=NULL) {\n\t(void)the_env->close(the_env, 0);\n\tthe_env = 0;\n }\n}\n\nint DbEnv::close(u_int32_t flags) {\n int ret = EINVAL;\n if (the_env)\n ret = the_env->close(the_env, flags);\n the_env = 0; \/* get rid of the env ref, so we don't touch it (even if we failed, or when the destructor is called) *\/\n return maybe_throw_error(ret);\n}\n\nint DbEnv::open(const char *home, u_int32_t flags, int mode) {\n int ret = the_env->open(the_env, home, flags, mode);\n return maybe_throw_error(ret);\n}\n\nint DbEnv::set_cachesize(u_int32_t gbytes, u_int32_t bytes, int ncache) {\n int ret = the_env->set_cachesize(the_env, gbytes, bytes, ncache);\n return maybe_throw_error(ret);\n}\n\nint DbEnv::set_redzone(u_int32_t percent) {\n int ret = the_env->set_redzone(the_env, percent);\n return maybe_throw_error(ret);\n}\n\nint DbEnv::set_flags(u_int32_t flags, int onoff) {\n int ret = the_env->set_flags(the_env, flags, onoff);\n return maybe_throw_error(ret);\n}\n\n#if DB_VERSION_MAJOR<4 || (DB_VERSION_MAJOR==4 && DB_VERSION_MINOR<=4)\nint DbEnv::set_lk_max(u_int32_t flags) {\n int ret = the_env->set_lk_max(the_env, flags);\n return maybe_throw_error(ret);\n}\n#endif\n\nint DbEnv::txn_begin(DbTxn *parenttxn, DbTxn **txnp, u_int32_t flags) {\n DB_TXN *txn;\n int ret = the_env->txn_begin(the_env, parenttxn->get_DB_TXN(), &txn, flags);\n if (ret==0) {\n\t*txnp = new DbTxn(txn);\n }\n return maybe_throw_error(ret);\n}\n\nint DbEnv::set_default_bt_compare(bt_compare_fcn_type bt_compare_fcn) {\n int ret = the_env->set_default_bt_compare(the_env, bt_compare_fcn);\n return maybe_throw_error(ret);\n}\n\nint DbEnv::set_data_dir(const char *dir) {\n int ret = the_env->set_data_dir(the_env, dir);\n return maybe_throw_error(ret);\n}\n\nvoid DbEnv::set_errpfx(const char *errpfx) {\n the_env->set_errpfx(the_env, errpfx);\n}\n\nint DbEnv::maybe_throw_error(int err, DbEnv *env, int no_exceptions) throw (DbException) {\n if (err==0 || err==DB_NOTFOUND || err==DB_KEYEXIST) return err;\n if (no_exceptions) return err;\n if (err==DB_LOCK_DEADLOCK) {\n\tDbDeadlockException e(env);\n\tthrow e;\n } else {\n\tDbException e(err);\n\te.set_env(env);\n\tthrow e;\n }\n}\n\nint DbEnv::maybe_throw_error(int err) throw (DbException) {\n return maybe_throw_error(err, this, do_no_exceptions);\n}\n\nextern \"C\" {\nvoid toku_ydb_error_all_cases(const DB_ENV * env, \n int error, \n BOOL include_stderrstring, \n BOOL use_stderr_if_nothing_else, \n const char *fmt, va_list ap);\n}\n\nvoid DbEnv::err(int error, const char *fmt, ...) {\n va_list ap;\n va_start(ap, fmt);\n toku_ydb_error_all_cases(the_env, error, TRUE, TRUE, fmt, ap);\n va_end(ap);\n}\n\nvoid DbEnv::set_errfile(FILE *errfile) {\n the_env->set_errfile(the_env, errfile);\n}\n\nint DbEnv::get_flags(u_int32_t *flagsp) {\n int ret = the_env->get_flags(the_env, flagsp);\n return maybe_throw_error(ret);\n}\n\nextern \"C\" void toku_db_env_errcall_c(const DB_ENV *dbenv_c, const char *errpfx, const char *msg) {\n DbEnv *dbenv = (DbEnv *) dbenv_c->api1_internal;\n dbenv->errcall(dbenv, errpfx, msg);\n}\n\nvoid DbEnv::set_errcall(void (*db_errcall_fcn)(const DbEnv *, const char *, const char *)) {\n errcall = db_errcall_fcn;\n the_env->set_errcall(the_env, toku_db_env_errcall_c);\n}\n\nextern \"C\" void toku_db_env_error_stream_c(const DB_ENV *dbenv_c, const char *errpfx, const char *msg) {\n DbEnv *dbenv = (DbEnv *) dbenv_c->api1_internal;\n if (dbenv->_error_stream) {\n if (errpfx) *(dbenv->_error_stream) << errpfx;\n if (msg) *(dbenv->_error_stream) << \":\" << msg << \"\\n\";\n }\n}\n\nvoid DbEnv::set_error_stream(std::ostream *new_error_stream) {\n _error_stream = new_error_stream;\n the_env->set_errcall(the_env, toku_db_env_error_stream_c);\n}\n\nint DbEnv::set_lk_max_locks(u_int32_t max_locks) {\n int ret = the_env->set_lk_max_locks(the_env, max_locks);\n return maybe_throw_error(ret);\n}\n\nint DbEnv::get_lk_max_locks(u_int32_t *max_locks) {\n int ret = the_env->get_lk_max_locks(the_env, max_locks);\n return maybe_throw_error(ret);\n}\n\n<|endoftext|>"} {"text":"\/*\nCopyright 2013-present Barefoot Networks, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \n\n#include \n#include \"source_file.h\"\n#include \"exceptions.h\"\n\nvoid IHasDbPrint::print() const { dbprint(std::cout); std::cout << std::endl; }\n\nnamespace Util {\nSourcePosition::SourcePosition(unsigned lineNumber, unsigned columnNumber)\n : lineNumber(lineNumber),\n columnNumber(columnNumber) {\n if (lineNumber == 0)\n BUG(\"Line numbering should start at one\");\n}\n\ncstring SourcePosition::toString() const {\n return Util::printf_format(\"%d:%d\", lineNumber, columnNumber);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSourceInfo::SourceInfo(SourcePosition start, SourcePosition end) :\n start(start),\n end(end) {\n if (!start.isValid() || !end.isValid())\n BUG(\"Invalid source position in SourceInfo %1%-%2%\",\n start.toString(), end.toString());\n if (start > end)\n BUG(\"SourceInfo position start %1% after end %2%\",\n start.toString(), end.toString());\n}\n\ncstring SourceInfo::toDebugString() const {\n return Util::printf_format(\"(%s)-(%s)\", start.toString(), end.toString());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nInputSources* InputSources::instance = new InputSources();\n\nInputSources::InputSources() :\n sealed(false) {\n mapLine(nullptr, 1); \/\/ the first line read will be line 1 of stdin\n contents.push_back(\"\");\n}\n\n\/* static *\/ void InputSources::reset() {\n instance = new InputSources;\n}\n\n\/\/\/ prevent further changes\nvoid InputSources::seal() {\n LOG4(toDebugString());\n if (sealed)\n BUG(\"InputSources already sealed\");\n sealed = true;\n}\n\nunsigned InputSources::lineCount() const {\n int size = contents.size();\n if (contents.back().isNullOrEmpty()) {\n \/\/ do not count the last line if it is empty.\n size -= 1;\n if (size < 0)\n BUG(\"Negative line count\");\n }\n return size;\n}\n\n\/\/ Append this text to the last line\nvoid InputSources::appendToLastLine(StringRef text) {\n if (sealed)\n BUG(\"Appending to sealed InputSources\");\n \/\/ Text should not contain any newline characters\n for (size_t i = 0; i < text.len; i++) {\n char c = text[i];\n if (c == '\\n')\n BUG(\"Text contains newlines\");\n }\n contents.back() += text.toString();\n}\n\n\/\/ Append a newline and start a new line\nvoid InputSources::appendNewline(StringRef newline) {\n if (sealed)\n BUG(\"Appending to sealed InputSources\");\n contents.back() += newline.toString();\n contents.push_back(\"\"); \/\/ start a new line\n}\n\nvoid InputSources::appendText(const char* text) {\n if (text == nullptr)\n BUG(\"Null text being appended\");\n StringRef ref = text;\n\n while (ref.len > 0) {\n const char* nl = ref.find(\"\\r\\n\");\n if (nl == nullptr) {\n appendToLastLine(ref);\n break;\n }\n\n size_t toCut = nl - ref.p;\n if (toCut != 0) {\n StringRef nonnl(ref.p, toCut);\n appendToLastLine(nonnl);\n ref += toCut;\n } else {\n if (ref[0] == '\\n') {\n appendNewline(\"\\n\");\n ref += 1;\n } else if (ref.len > 2 && ref[0] == '\\r' && ref[1] == '\\n') {\n appendNewline(\"\\r\\n\");\n ref += 2;\n } else {\n \/\/ Just \\r\n appendToLastLine(ref.substr(0, 1));\n ref += 1;\n }\n }\n }\n}\n\ncstring InputSources::getLine(unsigned lineNumber) const {\n if (lineNumber == 0) {\n return \"\";\n \/\/ BUG(\"Lines are numbered starting at 1\");\n \/\/ don't throw: this code may be called by exceptions\n \/\/ reporting on elements that have no source position\n }\n return contents.at(lineNumber - 1);\n}\n\nvoid InputSources::mapLine(cstring file, unsigned originalSourceLineNo) {\n if (sealed)\n BUG(\"Changing mapping to sealed InputSources\");\n unsigned lineno = getCurrentLineNumber();\n line_file_map.emplace(lineno, SourceFileLine(file, originalSourceLineNo));\n}\n\nSourceFileLine InputSources::getSourceLine(unsigned line) const {\n auto it = line_file_map.upper_bound(line+1);\n if (it == line_file_map.begin())\n \/\/ There must be always something mapped to line 0\n BUG(\"No source information for line %1%\", line);\n LOG3(line << \" mapped to \" << it->first << \",\" << it->second.toString());\n --it;\n LOG3(line << \" corrected to \" << it->first << \",\" << it->second.toString());\n \/\/ For a source file such as\n \/\/ ----------\n \/\/ # 1 \"x.p4\"\n \/\/ parser start { }\n \/\/ ----------\n \/\/ The first line indicates that line 2 is the first line in x.p4\n \/\/ line=2, it->first=1, it->second.sourceLine=1\n \/\/ So we have to subtract one to get the real line number\n BUG_CHECK(line - it->first + it->second.sourceLine > 0, \"invalid source line\");\n return SourceFileLine(it->second.fileName, line - it->first + it->second.sourceLine - 1);\n}\n\nunsigned InputSources::getCurrentLineNumber() const {\n return contents.size();\n}\n\nSourcePosition InputSources::getCurrentPosition() const {\n unsigned line = getCurrentLineNumber();\n unsigned column = contents.back().size();\n return SourcePosition(line, column);\n}\n\ncstring InputSources::getSourceFragment(const SourcePosition &position) const {\n SourceInfo info(position, position);\n return getSourceFragment(info);\n}\n\ncstring carets(cstring source, unsigned start, unsigned end) {\n std::stringstream builder;\n if (start > source.size())\n start = source.size();\n\n unsigned i;\n for (i=0; i < start; i++) {\n char c = source.c_str()[i];\n if (c == ' ' || c == '\\t')\n builder.put(c);\n else\n builder.put(' ');\n }\n\n for (; i < std::max(end, start+1); i++)\n builder.put('^');\n\n return builder.str();\n}\n\ncstring InputSources::getSourceFragment(const SourceInfo &position) const {\n if (!position.isValid())\n return \"\";\n\n \/\/ If the position spans multiple lines, truncate to just the first line\n if (position.getEnd().getLineNumber() > position.getStart().getLineNumber())\n return getSourceFragment(position.getStart());\n\n cstring result = getLine(position.getStart().getLineNumber());\n \/\/ Normally result has a newline, but if not\n \/\/ then we have to add a newline\n cstring toadd = \"\";\n if (result.find('\\n') == nullptr)\n toadd = cstring::newline;\n cstring marker = carets(result, position.getStart().getColumnNumber(),\n position.getEnd().getColumnNumber());\n return result + toadd + marker + cstring::newline;\n}\n\ncstring InputSources::getBriefSourceFragment(const SourceInfo &position) const {\n if (!position.isValid())\n return \"\";\n\n cstring result = getLine(position.getStart().getLineNumber());\n unsigned int start = position.getStart().getColumnNumber();\n unsigned int end;\n cstring toadd = \"\";\n\n \/\/ If the position spans multiple lines, truncate to just the first line\n if (position.getEnd().getLineNumber() > position.getStart().getLineNumber()) {\n \/\/ go to the end of the first line\n end = result.size();\n if (result.find('\\n') != nullptr) {\n --end;\n }\n toadd = \" ...\";\n } else {\n end = position.getEnd().getColumnNumber();\n }\n return result.substr(start, end - start) + toadd;\n}\n\ncstring InputSources::toDebugString() const {\n std::stringstream builder;\n for (auto line : contents)\n builder << line;\n builder << \"---------------\" << std::endl;\n for (auto lf : line_file_map)\n builder << lf.first << \": \" << lf.second.toString() << std::endl;\n return cstring(builder.str());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ncstring SourceInfo::toSourceFragment() const {\n return InputSources::instance->getSourceFragment(*this);\n}\n\ncstring SourceInfo::toBriefSourceFragment() const {\n return InputSources::instance->getBriefSourceFragment(*this);\n}\n\ncstring SourceInfo::toPositionString() const {\n if (!isValid())\n return \"\";\n SourceFileLine position = InputSources::instance->getSourceLine(start.getLineNumber());\n return position.toString();\n}\n\ncstring SourceInfo::toSourcePositionData(unsigned *outLineNumber,\n unsigned *outColumnNumber) const {\n SourceFileLine position = InputSources::instance->getSourceLine(start.getLineNumber());\n if (outLineNumber != nullptr) {\n *outLineNumber = position.sourceLine;\n }\n if (outColumnNumber != nullptr) {\n *outColumnNumber = start.getColumnNumber();\n }\n return position.fileName.c_str();\n}\n\nSourceFileLine SourceInfo::toPosition() const {\n return InputSources::instance->getSourceLine(start.getLineNumber());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ncstring SourceFileLine::toString() const {\n return Util::printf_format(\"%s(%d)\", fileName.c_str(), sourceLine);\n}\n\n} \/\/ namespace Util\nFix for issue #989 (#990)\/*\nCopyright 2013-present Barefoot Networks, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \n\n#include \n#include \"source_file.h\"\n#include \"exceptions.h\"\n#include \"lib\/log.h\"\n\nvoid IHasDbPrint::print() const { dbprint(std::cout); std::cout << std::endl; }\n\nnamespace Util {\nSourcePosition::SourcePosition(unsigned lineNumber, unsigned columnNumber)\n : lineNumber(lineNumber),\n columnNumber(columnNumber) {\n if (lineNumber == 0)\n BUG(\"Line numbering should start at one\");\n}\n\ncstring SourcePosition::toString() const {\n return Util::printf_format(\"%d:%d\", lineNumber, columnNumber);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSourceInfo::SourceInfo(SourcePosition start, SourcePosition end) :\n start(start),\n end(end) {\n if (!start.isValid() || !end.isValid())\n BUG(\"Invalid source position in SourceInfo %1%-%2%\",\n start.toString(), end.toString());\n if (start > end)\n BUG(\"SourceInfo position start %1% after end %2%\",\n start.toString(), end.toString());\n}\n\ncstring SourceInfo::toDebugString() const {\n return Util::printf_format(\"(%s)-(%s)\", start.toString(), end.toString());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nInputSources* InputSources::instance = new InputSources();\n\nInputSources::InputSources() :\n sealed(false) {\n mapLine(nullptr, 1); \/\/ the first line read will be line 1 of stdin\n contents.push_back(\"\");\n}\n\n\/* static *\/ void InputSources::reset() {\n instance = new InputSources;\n}\n\n\/\/\/ prevent further changes\nvoid InputSources::seal() {\n LOG4(toDebugString());\n if (sealed)\n BUG(\"InputSources already sealed\");\n sealed = true;\n}\n\nunsigned InputSources::lineCount() const {\n int size = contents.size();\n if (contents.back().isNullOrEmpty()) {\n \/\/ do not count the last line if it is empty.\n size -= 1;\n if (size < 0)\n BUG(\"Negative line count\");\n }\n return size;\n}\n\n\/\/ Append this text to the last line\nvoid InputSources::appendToLastLine(StringRef text) {\n if (sealed)\n BUG(\"Appending to sealed InputSources\");\n \/\/ Text should not contain any newline characters\n for (size_t i = 0; i < text.len; i++) {\n char c = text[i];\n if (c == '\\n')\n BUG(\"Text contains newlines\");\n }\n contents.back() += text.toString();\n}\n\n\/\/ Append a newline and start a new line\nvoid InputSources::appendNewline(StringRef newline) {\n if (sealed)\n BUG(\"Appending to sealed InputSources\");\n contents.back() += newline.toString();\n contents.push_back(\"\"); \/\/ start a new line\n}\n\nvoid InputSources::appendText(const char* text) {\n if (text == nullptr)\n BUG(\"Null text being appended\");\n StringRef ref = text;\n\n while (ref.len > 0) {\n const char* nl = ref.find(\"\\r\\n\");\n if (nl == nullptr) {\n appendToLastLine(ref);\n break;\n }\n\n size_t toCut = nl - ref.p;\n if (toCut != 0) {\n StringRef nonnl(ref.p, toCut);\n appendToLastLine(nonnl);\n ref += toCut;\n } else {\n if (ref[0] == '\\n') {\n appendNewline(\"\\n\");\n ref += 1;\n } else if (ref.len > 2 && ref[0] == '\\r' && ref[1] == '\\n') {\n appendNewline(\"\\r\\n\");\n ref += 2;\n } else {\n \/\/ Just \\r\n appendToLastLine(ref.substr(0, 1));\n ref += 1;\n }\n }\n }\n}\n\ncstring InputSources::getLine(unsigned lineNumber) const {\n if (lineNumber == 0) {\n return \"\";\n \/\/ BUG(\"Lines are numbered starting at 1\");\n \/\/ don't throw: this code may be called by exceptions\n \/\/ reporting on elements that have no source position\n }\n return contents.at(lineNumber - 1);\n}\n\nvoid InputSources::mapLine(cstring file, unsigned originalSourceLineNo) {\n if (sealed)\n BUG(\"Changing mapping to sealed InputSources\");\n unsigned lineno = getCurrentLineNumber();\n line_file_map.emplace(lineno, SourceFileLine(file, originalSourceLineNo));\n}\n\nSourceFileLine InputSources::getSourceLine(unsigned line) const {\n auto it = line_file_map.upper_bound(line+1);\n if (it == line_file_map.begin())\n \/\/ There must be always something mapped to line 0\n BUG(\"No source information for line %1%\", line);\n LOG3(line << \" mapped to \" << it->first << \",\" << it->second.toString());\n --it;\n LOG3(line << \" corrected to \" << it->first << \",\" << it->second.toString());\n \/\/ For a source file such as\n \/\/ ----------\n \/\/ # 1 \"x.p4\"\n \/\/ parser start { }\n \/\/ ----------\n \/\/ The first line indicates that line 2 is the first line in x.p4\n \/\/ line=2, it->first=1, it->second.sourceLine=1\n \/\/ So we have to subtract one to get the real line number\n BUG_CHECK(line - it->first + it->second.sourceLine > 0, \"invalid source line\");\n return SourceFileLine(it->second.fileName, line - it->first + it->second.sourceLine - 1);\n}\n\nunsigned InputSources::getCurrentLineNumber() const {\n return contents.size();\n}\n\nSourcePosition InputSources::getCurrentPosition() const {\n unsigned line = getCurrentLineNumber();\n unsigned column = contents.back().size();\n return SourcePosition(line, column);\n}\n\ncstring InputSources::getSourceFragment(const SourcePosition &position) const {\n SourceInfo info(position, position);\n return getSourceFragment(info);\n}\n\ncstring carets(cstring source, unsigned start, unsigned end) {\n std::stringstream builder;\n if (start > source.size())\n start = source.size();\n\n unsigned i;\n for (i=0; i < start; i++) {\n char c = source.c_str()[i];\n if (c == ' ' || c == '\\t')\n builder.put(c);\n else\n builder.put(' ');\n }\n\n for (; i < std::max(end, start+1); i++)\n builder.put('^');\n\n return builder.str();\n}\n\ncstring InputSources::getSourceFragment(const SourceInfo &position) const {\n if (!position.isValid())\n return \"\";\n\n \/\/ If the position spans multiple lines, truncate to just the first line\n if (position.getEnd().getLineNumber() > position.getStart().getLineNumber())\n return getSourceFragment(position.getStart());\n\n cstring result = getLine(position.getStart().getLineNumber());\n \/\/ Normally result has a newline, but if not\n \/\/ then we have to add a newline\n cstring toadd = \"\";\n if (result.find('\\n') == nullptr)\n toadd = cstring::newline;\n cstring marker = carets(result, position.getStart().getColumnNumber(),\n position.getEnd().getColumnNumber());\n return result + toadd + marker + cstring::newline;\n}\n\ncstring InputSources::getBriefSourceFragment(const SourceInfo &position) const {\n if (!position.isValid())\n return \"\";\n\n cstring result = getLine(position.getStart().getLineNumber());\n unsigned int start = position.getStart().getColumnNumber();\n unsigned int end;\n cstring toadd = \"\";\n\n \/\/ If the position spans multiple lines, truncate to just the first line\n if (position.getEnd().getLineNumber() > position.getStart().getLineNumber()) {\n \/\/ go to the end of the first line\n end = result.size();\n if (result.find('\\n') != nullptr) {\n --end;\n }\n toadd = \" ...\";\n } else {\n end = position.getEnd().getColumnNumber();\n }\n return result.substr(start, end - start) + toadd;\n}\n\ncstring InputSources::toDebugString() const {\n std::stringstream builder;\n for (auto line : contents)\n builder << line;\n builder << \"---------------\" << std::endl;\n for (auto lf : line_file_map)\n builder << lf.first << \": \" << lf.second.toString() << std::endl;\n return cstring(builder.str());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ncstring SourceInfo::toSourceFragment() const {\n return InputSources::instance->getSourceFragment(*this);\n}\n\ncstring SourceInfo::toBriefSourceFragment() const {\n return InputSources::instance->getBriefSourceFragment(*this);\n}\n\ncstring SourceInfo::toPositionString() const {\n if (!isValid())\n return \"\";\n SourceFileLine position = InputSources::instance->getSourceLine(start.getLineNumber());\n return position.toString();\n}\n\ncstring SourceInfo::toSourcePositionData(unsigned *outLineNumber,\n unsigned *outColumnNumber) const {\n SourceFileLine position = InputSources::instance->getSourceLine(start.getLineNumber());\n if (outLineNumber != nullptr) {\n *outLineNumber = position.sourceLine;\n }\n if (outColumnNumber != nullptr) {\n *outColumnNumber = start.getColumnNumber();\n }\n return position.fileName.c_str();\n}\n\nSourceFileLine SourceInfo::toPosition() const {\n return InputSources::instance->getSourceLine(start.getLineNumber());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ncstring SourceFileLine::toString() const {\n return Util::printf_format(\"%s(%d)\", fileName.c_str(), sourceLine);\n}\n\n} \/\/ namespace Util\n<|endoftext|>"} {"text":"\/**\n * Copyright [2016]\n *\n * \\author [Artur Troian ]\n * \\author [Oleg Kravchenko ]\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace daemonize {\n\nstatic Json::Value *g_config = nullptr;\nstatic int *g_lock_fd = nullptr;\nstatic cleanup_cb cleanup = nullptr;\nstatic void *cleanup_ctx = nullptr;\n\nvoid exit_daemon(int err)\n{\n\tif (cleanup)\n\t\tcleanup(cleanup_ctx);\n\n\tif (g_lock_fd) {\n\t\tif (*g_lock_fd > 0) {\n\t\t\tif (flock(*g_lock_fd, LOCK_UN) != 0) {\n\t\t\t\tstd::cerr << \"Can't unlock the lock file\";\n\t\t\t}\n\t\t\tclose(*g_lock_fd);\n\t\t\t*g_lock_fd = 0;\n\t\t}\n\n\t\tdelete g_lock_fd;\n\t}\n\n\tif (!g_config->operator[](\"pid_file\").empty()) {\n\t\tunlink(g_config->operator[](\"pid_file\").asString().c_str());\n\t}\n\n\tdelete g_config;\n\n\t_exit(err);\n}\n\nstatic void already_running(const std::string &lock_file)\n{\n\t*g_lock_fd = open(lock_file.c_str(), O_RDONLY, S_IRUSR | S_IWUSR);\n\tif (*g_lock_fd <= 0) {\n\t\tfprintf(stderr, \"Can't open executable to lock: \\\"%s\\\": %s\\n\", lock_file.c_str(), strerror(errno));\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n\n\tif (flock(*g_lock_fd, LOCK_EX | LOCK_NB) != 0) {\n\t\tfprintf(stderr, \"Can't lock the lock file \\\"%s\\\". Is another instance running?\\n\", lock_file.c_str());\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n}\n\nstatic void write_pid(const std::string &pid_file)\n{\n\ttry {\n\t\tstd::ofstream file(pid_file, std::ios_base::trunc);\n\t\tfile << std::to_string(getpid());\n\t} catch (const std::exception &e) {\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n}\n\nstatic void verify_config(Json::Value *config)\n{\n\tif (!config->isMember(\"lock_file\")) {\n\t\tstd::cerr << \"Daemon config must provide \\\"lock_file\\\" member\";\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n\n\tif (!config->isMember(\"env_dir\")) {\n\t\tstd::cerr << \"Daemon config must provide \\\"env_dir\\\" member\";\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n\n\tif (!config->isMember(\"as_daemon\")) {\n\t\tstd::cerr << \"Daemon config must provide \\\"as_daemon\\\" member\";\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n}\n\npid_t make_daemon(Json::Value *config, cleanup_cb cb, void *userdata)\n{\n\tg_lock_fd = new int;\n\tg_config = config;\n\tcleanup = cb;\n\tcleanup_ctx = userdata;\n\n\tverify_config(config);\n\n\talready_running(config->operator[](\"lock_file\").asString());\n\n\tif (config->operator[](\"as_daemon\").asBool()) {\n\t\tpid_t p = daemonize::detached::make();\n\t\tif (p > 0 || p < 0)\n\t\t\treturn p;\n\t}\n\n\t\/\/ Setup environment dir\n\tif (chdir(config->operator[](\"env_dir\").asString().c_str()) < 0) {\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n\n\t\/\/ check of log directory exists\n\tstd::string log_path(config->operator[](\"env_dir\").asString());\n\tif (log_path.back() != '\/') {\n\t\tlog_path += \"\/\";\n\t}\n\n\tif (config->operator[](\"log\")[\"dir\"].asString().substr(0, 1) != \"\/\") {\n\t\tlog_path += config->operator[](\"log\")[\"dir\"].asString();\n\t}\n\n\tif (!boost::filesystem::exists(log_path)) {\n\t\tboost::filesystem::create_directory(log_path);\n\t}\n\n\tstd::string std_file;\n\tJson::Value io_config;\n\n\tif (config->operator[](\"io_mode\").asString().compare(\"io_daemon\") == 0) {\n\t\tio_config = config->operator[](\"io_daemon\");\n\t} else {\n\t\tio_config = config->operator[](\"io_debug\");\n\t}\n\n\tif (io_config[\"stdin\"].asString().compare(\"stdin\") != 0) {\n\t\t\/\/ stdin needs redirection\n\t\tif (io_config[\"stdin\"].asString().compare(\"\/dev\/null\") == 0) {\n\t\t\tstd_file = \"\/dev\/null\";\n\t\t} else {\n\t\t\tstd_file = config->operator[](\"log\")[\"dir\"].asString();\n\t\t\tstd_file.append(\"\/\");\n\t\t\tstd_file.append(io_config[\"stdin\"].asString());\n\t\t}\n\n\t\tclose(STDIN_FILENO);\n\n\t\tint stdin_fd = open(std_file.c_str(), O_RDONLY);\n\n\t\tif (stdin_fd != 0) {\n\t\t\tif (stdin_fd > 0)\n\t\t\t\tclose(stdin_fd);\n\t\t\tfprintf(stderr, \"Unable to redirect stdin: Opened to: %d. Error: %s\", stdin_fd, strerror(errno));\n\t\t\texit_daemon(EXIT_FAILURE);\n\t\t}\n\t}\n\n\tif (io_config[\"stdout\"].asString().compare(\"stdout\") != 0) {\n\t\t\/\/ stdout needs redirection\n\t\tif (io_config[\"stdout\"].asString().compare(\"\/dev\/null\") == 0) {\n\t\t\tstd_file = \"\/dev\/null\";\n\t\t} else {\n\t\t\tstd_file = config->operator[](\"log\")[\"dir\"].asString();\n\t\t\tstd_file.append(\"\/\");\n\t\t\tstd_file.append(io_config[\"stdout\"].asString());\n\t\t}\n\n\t\tclose(STDOUT_FILENO);\n\n\t\tint stdout_fd = open(std_file.c_str(), O_CREAT | O_WRONLY | O_TRUNC);\n\t\tif (stdout_fd != 1) {\n\t\t\tif (stdout_fd > 0)\n\t\t\t\tclose(stdout_fd);\n\t\t\tfprintf(stderr, \"Unable to redirect stdout: Opened to: %d. Error: %s\\n\", stdout_fd, strerror(errno));\n\t\t\texit_daemon(EXIT_FAILURE);\n\t\t}\n\n\t\tif (std_file.compare(\"\/dev\/null\") != 0) {\n\t\t\tif (chmod(std_file.c_str(), 0644) < 0) {\n\t\t\t\tfprintf(stderr, \"Unable change file permision: [%s]. Reason: %s\\n\", std_file.c_str(), strerror(errno));\n\t\t\t\texit_daemon(EXIT_FAILURE);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (io_config[\"stderr\"].asString().compare(\"stdout\") != 0) {\n\t\t\/\/ stderr needs redirection\n\t\tif (io_config[\"stderr\"].asString().compare(\"\/dev\/null\") == 0) {\n\t\t\tstd_file = \"\/dev\/null\";\n\t\t} else {\n\t\t\tstd_file = config->operator[](\"log\")[\"dir\"].asString();\n\t\t\tstd_file.append(\"\/\");\n\t\t\tstd_file.append(io_config[\"stderr\"].asString());\n\t\t}\n\n\t\tclose(STDERR_FILENO);\n\n\t\tint stderr_fd = open(std_file.c_str(), O_CREAT | O_WRONLY | O_TRUNC);\n\n\t\tif (stderr_fd != 2) {\n\t\t\tif (stderr_fd > 0)\n\t\t\t\tclose(stderr_fd);\n\t\t\tfprintf(stderr, \"Unable to redirect stderr: Opened to: %d. Error: %s\", stderr_fd, strerror(errno));\n\t\t\texit_daemon(EXIT_FAILURE);\n\t\t}\n\n\t\tif (std_file.compare(\"\/dev\/null\") != 0) {\n\t\t\tif (chmod(std_file.c_str(), 0644) < 0) {\n\t\t\t\tfprintf(stderr, \"Unable change file permision: [%s]. Reason: %s\", std_file.c_str(), strerror(errno));\n\t\t\t\texit_daemon(EXIT_FAILURE);\n\t\t\t}\n\t\t}\n\t}\n\n\trlimit core_limits;\n\tcore_limits.rlim_cur = core_limits.rlim_max = (rlim_t)RLIM_INFINITY;\n\n\tif (setrlimit(RLIMIT_CORE, &core_limits) < 0) {\n\t\tfprintf(stderr, \"Unable to set rlimits. Error: %s\", strerror(errno));\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n\n\tif (!g_config->operator[](\"pid_file\").empty()) {\n\t\twrite_pid(config->operator[](\"pid_file\").asString());\n\t}\n\n\treturn 0;\n}\n\n} \/\/ namespace daemonize\nstyle: typo fix\/**\n * Copyright [2016]\n *\n * \\author [Artur Troian ]\n * \\author [Oleg Kravchenko ]\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace daemonize {\n\nstatic Json::Value *g_config = nullptr;\nstatic int *g_lock_fd = nullptr;\nstatic cleanup_cb cleanup = nullptr;\nstatic void *cleanup_ctx = nullptr;\n\nvoid exit_daemon(int err)\n{\n\tif (cleanup)\n\t\tcleanup(cleanup_ctx);\n\n\tif (g_lock_fd) {\n\t\tif (*g_lock_fd > 0) {\n\t\t\tif (flock(*g_lock_fd, LOCK_UN) != 0) {\n\t\t\t\tstd::cerr << \"Can't unlock the lock file\";\n\t\t\t}\n\t\t\tclose(*g_lock_fd);\n\t\t\t*g_lock_fd = 0;\n\t\t}\n\n\t\tdelete g_lock_fd;\n\t}\n\n\tif (!g_config->operator[](\"pid_file\").empty()) {\n\t\tunlink(g_config->operator[](\"pid_file\").asString().c_str());\n\t}\n\n\tdelete g_config;\n\n\t_exit(err);\n}\n\nstatic void already_running(const std::string &lock_file)\n{\n\t*g_lock_fd = open(lock_file.c_str(), O_RDONLY, S_IRUSR | S_IWUSR);\n\tif (*g_lock_fd <= 0) {\n\t\tfprintf(stderr, \"Can't open executable to lock: \\\"%s\\\": %s\\n\", lock_file.c_str(), strerror(errno));\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n\n\tif (flock(*g_lock_fd, LOCK_EX | LOCK_NB) != 0) {\n\t\tfprintf(stderr, \"Can't lock the lock file \\\"%s\\\". Is another instance running?\\n\", lock_file.c_str());\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n}\n\nstatic void write_pid(const std::string &pid_file)\n{\n\ttry {\n\t\tstd::ofstream file(pid_file, std::ios_base::trunc);\n\t\tfile << std::to_string(getpid());\n\t} catch (const std::exception &e) {\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n}\n\nstatic void verify_config(Json::Value *config)\n{\n\tif (!config->isMember(\"lock_file\")) {\n\t\tstd::cerr << \"Daemon config must provide \\\"lock_file\\\" member\";\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n\n\tif (!config->isMember(\"env_dir\")) {\n\t\tstd::cerr << \"Daemon config must provide \\\"env_dir\\\" member\";\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n\n\tif (!config->isMember(\"as_daemon\")) {\n\t\tstd::cerr << \"Daemon config must provide \\\"as_daemon\\\" member\";\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n}\n\npid_t make_daemon(Json::Value *config, cleanup_cb cb, void *userdata)\n{\n\tg_lock_fd = new int;\n\tg_config = config;\n\tcleanup = cb;\n\tcleanup_ctx = userdata;\n\n\tverify_config(config);\n\n\talready_running(config->operator[](\"lock_file\").asString());\n\n\tif (config->operator[](\"as_daemon\").asBool()) {\n\t\tpid_t p = daemonize::detached::make();\n\t\tif (p > 0 || p < 0)\n\t\t\treturn p;\n\t}\n\n\t\/\/ Setup environment dir\n\tif (chdir(config->operator[](\"env_dir\").asString().c_str()) < 0) {\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n\n\t\/\/ check of log directory exists\n\tstd::string log_path(config->operator[](\"env_dir\").asString());\n\tif (log_path.back() != '\/') {\n\t\tlog_path += \"\/\";\n\t}\n\n\tif (config->operator[](\"log\")[\"dir\"].asString().substr(0, 1) != \"\/\") {\n\t\tlog_path += config->operator[](\"log\")[\"dir\"].asString();\n\t}\n\n\tif (!boost::filesystem::exists(log_path)) {\n\t\tboost::filesystem::create_directory(log_path);\n\t}\n\n\tstd::string std_file;\n\tJson::Value io_config;\n\n\tif (config->operator[](\"io_mode\").asString().compare(\"io_daemon\") == 0) {\n\t\tio_config = config->operator[](\"io_daemon\");\n\t} else {\n\t\tio_config = config->operator[](\"io_debug\");\n\t}\n\n\tif (io_config[\"stdin\"].asString().compare(\"stdin\") != 0) {\n\t\t\/\/ stdin needs redirection\n\t\tif (io_config[\"stdin\"].asString().compare(\"\/dev\/null\") == 0) {\n\t\t\tstd_file = \"\/dev\/null\";\n\t\t} else {\n\t\t\tstd_file = config->operator[](\"log\")[\"dir\"].asString();\n\t\t\tstd_file.append(\"\/\");\n\t\t\tstd_file.append(io_config[\"stdin\"].asString());\n\t\t}\n\n\t\tclose(STDIN_FILENO);\n\n\t\tint stdin_fd = open(std_file.c_str(), O_RDONLY);\n\n\t\tif (stdin_fd != 0) {\n\t\t\tif (stdin_fd > 0)\n\t\t\t\tclose(stdin_fd);\n\t\t\tfprintf(stderr, \"Unable to redirect stdin: Opened to: %d. Error: %s\", stdin_fd, strerror(errno));\n\t\t\texit_daemon(EXIT_FAILURE);\n\t\t}\n\t}\n\n\tif (io_config[\"stdout\"].asString().compare(\"stdout\") != 0) {\n\t\t\/\/ stdout needs redirection\n\t\tif (io_config[\"stdout\"].asString().compare(\"\/dev\/null\") == 0) {\n\t\t\tstd_file = \"\/dev\/null\";\n\t\t} else {\n\t\t\tstd_file = config->operator[](\"log\")[\"dir\"].asString();\n\t\t\tstd_file.append(\"\/\");\n\t\t\tstd_file.append(io_config[\"stdout\"].asString());\n\t\t}\n\n\t\tclose(STDOUT_FILENO);\n\n\t\tint stdout_fd = open(std_file.c_str(), O_CREAT | O_WRONLY | O_TRUNC);\n\t\tif (stdout_fd != 1) {\n\t\t\tif (stdout_fd > 0)\n\t\t\t\tclose(stdout_fd);\n\t\t\tfprintf(stderr, \"Unable to redirect stdout: Opened to: %d. Error: %s\\n\", stdout_fd, strerror(errno));\n\t\t\texit_daemon(EXIT_FAILURE);\n\t\t}\n\n\t\tif (std_file.compare(\"\/dev\/null\") != 0) {\n\t\t\tif (chmod(std_file.c_str(), 0644) < 0) {\n\t\t\t\tfprintf(stderr, \"Unable change file permission: [%s]. Reason: %s\\n\", std_file.c_str(), strerror(errno));\n\t\t\t\texit_daemon(EXIT_FAILURE);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (io_config[\"stderr\"].asString().compare(\"stdout\") != 0) {\n\t\t\/\/ stderr needs redirection\n\t\tif (io_config[\"stderr\"].asString().compare(\"\/dev\/null\") == 0) {\n\t\t\tstd_file = \"\/dev\/null\";\n\t\t} else {\n\t\t\tstd_file = config->operator[](\"log\")[\"dir\"].asString();\n\t\t\tstd_file.append(\"\/\");\n\t\t\tstd_file.append(io_config[\"stderr\"].asString());\n\t\t}\n\n\t\tclose(STDERR_FILENO);\n\n\t\tint stderr_fd = open(std_file.c_str(), O_CREAT | O_WRONLY | O_TRUNC);\n\n\t\tif (stderr_fd != 2) {\n\t\t\tif (stderr_fd > 0)\n\t\t\t\tclose(stderr_fd);\n\t\t\tfprintf(stderr, \"Unable to redirect stderr: Opened to: %d. Error: %s\", stderr_fd, strerror(errno));\n\t\t\texit_daemon(EXIT_FAILURE);\n\t\t}\n\n\t\tif (std_file.compare(\"\/dev\/null\") != 0) {\n\t\t\tif (chmod(std_file.c_str(), 0644) < 0) {\n\t\t\t\tfprintf(stderr, \"Unable change file permision: [%s]. Reason: %s\", std_file.c_str(), strerror(errno));\n\t\t\t\texit_daemon(EXIT_FAILURE);\n\t\t\t}\n\t\t}\n\t}\n\n\trlimit core_limits;\n\tcore_limits.rlim_cur = core_limits.rlim_max = (rlim_t)RLIM_INFINITY;\n\n\tif (setrlimit(RLIMIT_CORE, &core_limits) < 0) {\n\t\tfprintf(stderr, \"Unable to set rlimits. Error: %s\", strerror(errno));\n\t\texit_daemon(EXIT_FAILURE);\n\t}\n\n\tif (!g_config->operator[](\"pid_file\").empty()) {\n\t\twrite_pid(config->operator[](\"pid_file\").asString());\n\t}\n\n\treturn 0;\n}\n\n} \/\/ namespace daemonize\n<|endoftext|>"} {"text":"\/*************************************************************************\/\n\/* resource_saver.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"resource_saver.h\"\n#include \"core\/config\/project_settings.h\"\n#include \"core\/io\/file_access.h\"\n#include \"core\/io\/resource_loader.h\"\n#include \"core\/object\/script_language.h\"\n\nRef ResourceSaver::saver[MAX_SAVERS];\n\nint ResourceSaver::saver_count = 0;\nbool ResourceSaver::timestamp_on_save = false;\nResourceSavedCallback ResourceSaver::save_callback = nullptr;\nResourceSaverGetResourceIDForPath ResourceSaver::save_get_id_for_path = nullptr;\n\nError ResourceFormatSaver::save(const Ref &p_resource, const String &p_path, uint32_t p_flags) {\n\tint64_t res;\n\tif (GDVIRTUAL_CALL(_save, p_resource, p_path, p_flags, res)) {\n\t\treturn (Error)res;\n\t}\n\n\treturn ERR_METHOD_NOT_FOUND;\n}\n\nbool ResourceFormatSaver::recognize(const Ref &p_resource) const {\n\tbool success;\n\tif (GDVIRTUAL_CALL(_recognize, p_resource, success)) {\n\t\treturn success;\n\t}\n\n\treturn false;\n}\n\nvoid ResourceFormatSaver::get_recognized_extensions(const Ref &p_resource, List *p_extensions) const {\n\tPackedStringArray exts;\n\tif (GDVIRTUAL_CALL(_get_recognized_extensions, p_resource, exts)) {\n\t\tconst String *r = exts.ptr();\n\t\tfor (int i = 0; i < exts.size(); ++i) {\n\t\t\tp_extensions->push_back(r[i]);\n\t\t}\n\t}\n}\n\nvoid ResourceFormatSaver::_bind_methods() {\n\tGDVIRTUAL_BIND(_save, \"path\", \"resource\", \"flags\");\n\tGDVIRTUAL_BIND(_recognize, \"resource\");\n\tGDVIRTUAL_BIND(_get_recognized_extensions, \"resource\");\n}\n\nError ResourceSaver::save(const Ref &p_resource, const String &p_path, uint32_t p_flags) {\n\tString path = p_path;\n\tif (path.is_empty()) {\n\t\tpath = p_resource->get_path();\n\t}\n\tERR_FAIL_COND_V_MSG(p_path.is_empty(), ERR_INVALID_PARAMETER, \"Can't save resource to empty path. Provide non-empty path or a Resource with non-empty resource_path.\");\n\n\tString extension = path.get_extension();\n\tError err = ERR_FILE_UNRECOGNIZED;\n\n\tfor (int i = 0; i < saver_count; i++) {\n\t\tif (!saver[i]->recognize(p_resource)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tList extensions;\n\t\tbool recognized = false;\n\t\tsaver[i]->get_recognized_extensions(p_resource, &extensions);\n\n\t\tfor (const String &E : extensions) {\n\t\t\tif (E.nocasecmp_to(extension) == 0) {\n\t\t\t\trecognized = true;\n\t\t\t}\n\t\t}\n\n\t\tif (!recognized) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tString old_path = p_resource->get_path();\n\n\t\tString local_path = ProjectSettings::get_singleton()->localize_path(path);\n\n\t\tRef rwcopy = p_resource;\n\t\tif (p_flags & FLAG_CHANGE_PATH) {\n\t\t\trwcopy->set_path(local_path);\n\t\t}\n\n\t\terr = saver[i]->save(p_resource, path, p_flags);\n\n\t\tif (err == OK) {\n#ifdef TOOLS_ENABLED\n\n\t\t\t((Resource *)p_resource.ptr())->set_edited(false);\n\t\t\tif (timestamp_on_save) {\n\t\t\t\tuint64_t mt = FileAccess::get_modified_time(path);\n\n\t\t\t\t((Resource *)p_resource.ptr())->set_last_modified_time(mt);\n\t\t\t}\n#endif\n\n\t\t\tif (p_flags & FLAG_CHANGE_PATH) {\n\t\t\t\trwcopy->set_path(old_path);\n\t\t\t}\n\n\t\t\tif (save_callback && path.begins_with(\"res:\/\/\")) {\n\t\t\t\tsave_callback(p_resource, path);\n\t\t\t}\n\n\t\t\treturn OK;\n\t\t}\n\t}\n\n\treturn err;\n}\n\nvoid ResourceSaver::set_save_callback(ResourceSavedCallback p_callback) {\n\tsave_callback = p_callback;\n}\n\nvoid ResourceSaver::get_recognized_extensions(const Ref &p_resource, List *p_extensions) {\n\tfor (int i = 0; i < saver_count; i++) {\n\t\tsaver[i]->get_recognized_extensions(p_resource, p_extensions);\n\t}\n}\n\nvoid ResourceSaver::add_resource_format_saver(Ref p_format_saver, bool p_at_front) {\n\tERR_FAIL_COND_MSG(p_format_saver.is_null(), \"It's not a reference to a valid ResourceFormatSaver object.\");\n\tERR_FAIL_COND(saver_count >= MAX_SAVERS);\n\n\tif (p_at_front) {\n\t\tfor (int i = saver_count; i > 0; i--) {\n\t\t\tsaver[i] = saver[i - 1];\n\t\t}\n\t\tsaver[0] = p_format_saver;\n\t\tsaver_count++;\n\t} else {\n\t\tsaver[saver_count++] = p_format_saver;\n\t}\n}\n\nvoid ResourceSaver::remove_resource_format_saver(Ref p_format_saver) {\n\tERR_FAIL_COND_MSG(p_format_saver.is_null(), \"It's not a reference to a valid ResourceFormatSaver object.\");\n\n\t\/\/ Find saver\n\tint i = 0;\n\tfor (; i < saver_count; ++i) {\n\t\tif (saver[i] == p_format_saver) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tERR_FAIL_COND(i >= saver_count); \/\/ Not found\n\n\t\/\/ Shift next savers up\n\tfor (; i < saver_count - 1; ++i) {\n\t\tsaver[i] = saver[i + 1];\n\t}\n\tsaver[saver_count - 1].unref();\n\t--saver_count;\n}\n\nRef ResourceSaver::_find_custom_resource_format_saver(String path) {\n\tfor (int i = 0; i < saver_count; ++i) {\n\t\tif (saver[i]->get_script_instance() && saver[i]->get_script_instance()->get_script()->get_path() == path) {\n\t\t\treturn saver[i];\n\t\t}\n\t}\n\treturn Ref();\n}\n\nbool ResourceSaver::add_custom_resource_format_saver(String script_path) {\n\tif (_find_custom_resource_format_saver(script_path).is_valid()) {\n\t\treturn false;\n\t}\n\n\tRef res = ResourceLoader::load(script_path);\n\tERR_FAIL_COND_V(res.is_null(), false);\n\tERR_FAIL_COND_V(!res->is_class(\"Script\"), false);\n\n\tRef